text:
"""
MoinMoin - MoinMoin.backends.wiki_group tests

@copyright: 2003-2004 by Juergen Hermann <jh@web.de>,
            2007 by MoinMoin:ThomasWaldmann
            2008 by MoinMoin:MelitaMihaljevic
            2009 by MoinMoin:DmitrijsMilajevs
@license: GNU GPL, see COPYING for details.
"""

from py.test import raises
import re, shutil

from MoinMoin.datastruct.backends._tests import GroupsBackendTest
from MoinMoin.datastruct import WikiGroups
from MoinMoin import Page, security
from MoinMoin.PageEditor import PageEditor
from MoinMoin.user import User
from MoinMoin._tests import append_page, become_trusted, create_page, create_random_string_list, nuke_page, nuke_user, wikiconfig

class TestWikiGroupBackend(GroupsBackendTest):

    # Suppose that default configuration for the groups is used which
    # is WikiGroups backend.

    def setup_class(self):
        become_trusted(self.request)

        for group, members in self.test_groups.iteritems():
            page_text = ' * %s' % '\n * '.join(members)
            create_page(self.request, group, page_text)

    def teardown_class(self):
        become_trusted(self.request)

        for group in self.test_groups:
            nuke_page(self.request, group)

    def test_rename_group_page(self):
        """
        Tests if the groups cache is refreshed after renaming a Group page.
        """
        request = self.request
        become_trusted(request)

        page = create_page(request, u'SomeGroup', u" * ExampleUser")
        page.renamePage('AnotherGroup')

        result = u'ExampleUser' in request.groups[u'AnotherGroup']
        nuke_page(request, u'AnotherGroup')

        assert result is True

    def test_copy_group_page(self):
        """
        Tests if the groups cache is refreshed after copying a Group page.
        """
        request = self.request
        become_trusted(request)

        page = create_page(request, u'SomeGroup', u" * ExampleUser")
        page.copyPage(u'SomeOtherGroup')

        result = u'ExampleUser' in request.groups[u'SomeOtherGroup']

        nuke_page(request, u'OtherGroup')
        nuke_page(request, u'SomeGroup')

        assert result is True

    def test_appending_group_page(self):
        """
        Test scalability by appending a name to a large list of group members.
        """
        request = self.request
        become_trusted(request)

        # long list of users
        page_content = [u" * %s" % member for member in create_random_string_list(length=15, count=1234)]
        test_user = create_random_string_list(length=15, count=1)[0]
        create_page(request, u'UserGroup', "\n".join(page_content))
        append_page(request, u'UserGroup', u' * %s' % test_user)
        result = test_user in request.groups['UserGroup']
        nuke_page(request, u'UserGroup')

        assert result

    def test_user_addition_to_group_page(self):
        """
        Test addition of a username to a large list of group members.
        """
        request = self.request
        become_trusted(request)

        # long list of users
        page_content = [u" * %s" % member for member in create_random_string_list()]
        create_page(request, u'UserGroup', "\n".join(page_content))

        new_user = create_random_string_list(length=15, count=1)[0]
        append_page(request, u'UserGroup', u' * %s' % new_user)
        user = User(request, name=new_user)
        if not user.exists():
            User(request, name=new_user, password=new_user).save()

        result = new_user in request.groups[u'UserGroup']
        nuke_page(request, u'UserGroup')
        nuke_user(request, new_user)

        assert result

    def test_member_removed_from_group_page(self):
        """
        Tests appending a member to a large list of group members and
        recreating the page without the member.
        """
        request = self.request
        become_trusted(request)

        # long list of users
        page_content = [u" * %s" % member for member in create_random_string_list()]
        page_content = "\n".join(page_content)
        create_page(request, u'UserGroup', page_content)

        test_user = create_random_string_list(length=15, count=1)[0]
        page = append_page(request, u'UserGroup', u' * %s' % test_user)

        # saves the text without test_user
        page.saveText(page_content, 0)
        result = test_user in request.groups[u'UserGroup']
        nuke_page(request, u'UserGroup')

        assert not result

    def test_group_page_user_addition_trivial_change(self):
        """
        Test addition of a user to a group page by trivial change.
        """
        request = self.request
        become_trusted(request)

        test_user = create_random_string_list(length=15, count=1)[0]
        member = u" * %s\n" % test_user
        page = create_page(request, u'UserGroup', member)

        # next member saved  as trivial change
        test_user = create_random_string_list(length=15, count=1)[0]
        member = u" * %s\n" % test_user
        page.saveText(member, 0, trivial=1)

        result = test_user in request.groups[u'UserGroup']

        nuke_page(request, u'UserGroup')

        assert result

    def test_wiki_backend_page_acl_append_page(self):
        """
        Test if the wiki group backend works with acl code.
        First check acl rights of a user that is not a member of group
        then add user member to a page group and check acl rights
        """
        request = self.request
        become_trusted(request)

        create_page(request, u'NewGroup', u" * ExampleUser")

        acl_rights = ["NewGroup:read,write"]
        acl = security.AccessControlList(request.cfg, acl_rights)

        has_rights_before = acl.may(request, u"AnotherUser", "read")

        # update page - add AnotherUser to a page group NewGroup
        append_page(request, u'NewGroup', u" * AnotherUser")

        has_rights_after = acl.may(request, u"AnotherUser", "read")

        nuke_page(request, u'NewGroup')

        assert not has_rights_before, 'AnotherUser has no read rights because in the beginning he is not a member of a group page NewGroup'
        assert has_rights_after, 'AnotherUser must have read rights because after appendage he is member of NewGroup'

    def test_simple_group_page(self):
        """
        Tests if a simple group page is evaluated correctly.
        """
        request = self.request
        become_trusted(request)
        group_name = u'SimpleGroup'
        page_text = u"""\
 * FirstUser
 * SecondUser
 * LastUser"""
        page = create_page(request, group_name, page_text)
        group_members = set(request.groups[group_name])
        assert group_members == set([u'FirstUser', u'SecondUser', u'LastUser'])
        nuke_page(request, group_name)

    def test_complex_group_page(self):
        """
        Tests if a complex group page is evaluated correctly.
        """
        request = self.request
        become_trusted(request)
        group_name = u'ComplexGroup'
        page_text = u"""\
 * FirstUser
  * any text
 * SecondUser
 * LastUser
  * any text"""
        page = create_page(request, group_name, page_text)
        group_members = set(request.groups[group_name])
        assert group_members == set([u'FirstUser', u'SecondUser', u'LastUser'])
        nuke_page(request, group_name)

coverage_modules = ['MoinMoin.datastruct.backends.wiki_groups']


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

<title>Jayesh Kawli's High School</title>

<meta name="keywords" content="Jayesh Kawli Official website homepage web developer Objective-C" />
<meta name="description" content="This is Jayesh Kawli's Personal Website" />

<link href="templatemo_style.css" rel="stylesheet" type="text/css" />
<link rel="stylesheet" type="text/css" href="css/ddsmoothmenu.css" />

Jayesh Kawli's Home Page

Home

Education

High School

Undergraduate

Graduate

Work

TCS

Mainframe

DB2

COBOL

Skills

Languages

Tools

Platforms

Databases

Projects

Miscellaneous

About Me

Contact

Resume

Gallery

My Highschool

I completed my Higher Secondary College from Thomas Baptista Junior College at Vasai.
				I was in science stream and took following courses like Physics, Mathematics and Chemistry.

 However my most favorite course was Compuer Programming which I took it as a
				vocational and I really enjoyed it. My real love
				for computer programming begun from that point. And those two years are the
				main motivational force behind me being at
				Indiana University, Bloomington

Mailing Address

 Thomas Baptista Junior College

                Papdy,Vasai ,Dist - Thane,

                Pincode - 401207

                Tel No : 0250-2322159

                contact@tbjc.org

Our Location

        Copyright ©  2014 Jayesh Kawli |
        Acknowledgements |
        Copyrights

Design Downloaded from free Joomla templates | free website templates | Free PSD Files.

redpajama_set_name: RedPajamaGithub


text:
import sys
import requests

from flask import Flask, Blueprint, request, jsonify
from flask_cors import CORS
from flask_security import auth_token_required
from core import db, security, user_datastore
from users import Users
app = Flask(__name__)
bp = Blueprint('auth', __name__, url_prefix='/auth')

users = Users()

@bp.route("/validate", methods=["GET"])
@auth_token_required
def validate():
    return 'ok'

if __name__ == "__main__":
    port = 7000

    # Read port from commandline
    if len(sys.argv) >= 2:
        port = sys.argv[1]

    # Setup app
    app.register_blueprint(bp)
    app.config.from_object('settings')

    db.init_app(app)
    db.create_all(app=app)

    security.init_app(app, user_datastore)

    if app.debug:
        CORS(app, resources=r'/*',
                 allow_headers=['Content-Type', 'Authentication'],
                 supports_credentials=True)

    # Register to discovery service
    discoveryServiceRequest = 'http://' + app.config['DISCOVERY_SERVICE_URL'] + '/' + bp.name
    discoveryServiceData = {
        'service_id': bp.name,
        'host': 'localhost',
        'port': port
    }
    response = requests.put(discoveryServiceRequest, json = discoveryServiceData)

    # Start app
    app.run(port=port)


text:
#ifndef __HACKING_NETWORK_H__
#define __HACKING_NETWORK_H__ 1

/* This function accepts a socket FD and a ptr to the null terminated
 * string to send. The function will make sure all the bytes of the
 * string are sent. Returns 1 on success and 0 a failure.
 */
#include <string.h>
#include <sys/socket.h>
int send_string(int sockfd, char* buffer)
{
	int sent_bytes, bytes_to_send;
	bytes_to_send = strlen(buffer);

	while(bytes_to_send > 0)
	{
		sent_bytes = send(sockfd, buffer, bytes_to_send, 0);
		if(sent_bytes == -1)
			return 0;
		bytes_to_send -= sent_bytes;
		buffer += sent_bytes;
	}
	return 1;
}

/* This function accepts a socket FD and a ptr to a destination
 * buffer. It will receive from the socket until the EOL byte
 * sequence is seen. The EOL bytes are read from the socket, but
 * the destination buffer is terminated before these bytes.
 * Returns the size of the read line(without EOL bytes).
 */
int recv_line(int sockfd, char* dest_buffer)
{
#define EOL "\r\n"
#define EOL_SIZE 2
	char *ptr;
	int eol_matched = 0;

	ptr = dest_buffer;
	while(recv(sockfd, ptr, 1, 0) == 1)
	{
		if(*ptr == EOL[eol_matched])
		{
			eol_matched++;
			if(eol_matched == EOL_SIZE)
			{
				*(ptr + 1 - EOL_SIZE) = '\0';
				return strlen(dest_buffer);
			}
		}
		else
			eol_matched = 0;
		ptr++;
	}
	return 0;
}

#define ETHER_ADDR_LEN 6
#define ETHER_HDR_LEN 14

struct ether_hdr
{
	unsigned char ether_dest_addr[ETHER_ADDR_LEN]; // Destination MAC Address
	unsigned char ether_src_addr[ETHER_ADDR_LEN];  // Source MAC Address
	unsigned short ether_type; // Type of Ethernet packet
};

struct ip_hdr
{
	unsigned char ip_version_and_header_length; // Version and header length
	unsigned char ip_tos;			// Type of Service
	unsigned short ip_len;		// Total Length
	unsigned short ip_id;			// Identification number
	unsigned short ip_frag_offset; // Fragment offset and flags
	unsigned char ip_ttl;			// Time to live
	unsigned char ip_type;		// Protocol type
	unsigned short ip_checksum;	// Checksum
	unsigned int ip_src_addr;	// Source IP Address
	unsigned int ip_dest_addr;	// Destination IP Address
};

struct tcp_hdr
{
	unsigned short tcp_src_port;	// Source TCP Port
	unsigned short tcp_dst_port;	// Destination TCP Port
	unsigned int tcp_seq;					// TCP sequence number
	unsigned int tcp_ack;					// TCP acknowledgment number
	unsigned char reserved:4;			// 4 bits from the 6 bits of reserved space
	unsigned char tcp_offset:4;		// TCP data offset for little-endian host
	unsigned char tcp_flags;			// TCP flags(and 2 bits from reserted space)
#define TCP_FIN 0x01
#define TCP_SYN 0x02
#define TCP_RST 0x04
#define TCP_PUSH 0x08
#define TCP_ACK 0x10
#define TCP_URG 0x20
	unsigned short tcp_window;		// TCP window size
	unsigned short tcp_checksum;	// TCP checksum
	unsigned short tcp_urgent;		// TCP urgent pointer
};

#endif


text:
package DDG::Spice::SalesTax;
#ABSTRACT: Returns the sales tax for any state (not including territories) in the United States.

use strict;
use DDG::Spice;
use Locale::SubCountry;

triggers any => 'sales tax for', 'sales tax in', 'sales tax';
spice to => 'http://dev.snapcx.io:9100/taxv1/getStateTaxRate?request_id=DDG_Requestor&state=$1';
spice wrap_jsonp_callback => 1;
spice is_cached => 1;

#Create US SubCountry object
my $US = new Locale::SubCountry("US");

# Handle statement
handle remainder_lc => sub {

# No need to check US country, as this IA will run for all international users. I am still keeping commented out code as FYI.
#    return unless $loc && $loc->{country_code} eq 'US';

    my ($state, $stateCode); #Define vars
    s/^what is (the)?//g; # strip common words
    return unless $_; # Guard against "no answer"

   # Guard against, to sending zipcodes as parameters. We have different IA.
   if ($_ =~ /^[0-9]{5}$/){
      return;
    }
    # Guard against, sales tax holiday. We have different IA.
    if ($_ =~ /((?i)holiday)/){
      return;
    }

    # Washington D.C is a district and is not supported by the SubCountry package.
    if(m/\b(washington\s(dc|d\.c))\b/i) {
        $state = "Washington D.C";
        $stateCode = "DC";
    } else {
        # $US->full_name returns the full state name based on the ISO3166 code
        $stateCode = $_;
        $state = $US->full_name($_); # Check for state using ISO code (PA)
        if($state eq "unknown") {
            $state = $US->full_name($US->code($_)); # If state is "unknown" search for code using full state name (Pennsylvania)
            $stateCode = $US->code($_);
        }
    }

    # error checking
    return if $state eq "unknown";
    return unless (defined $state and $stateCode);
    return $stateCode; # return result
};
1;


text:
package org.elasticsearch.test.transport;

import org.elasticsearch.Version;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.cluster.node.DiscoveryNode;
import org.elasticsearch.common.component.Lifecycle;
import org.elasticsearch.common.component.LifecycleListener;
import org.elasticsearch.common.lease.Releasable;
import org.elasticsearch.common.transport.BoundTransportAddress;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.transport.ConnectionProfile;
import org.elasticsearch.transport.RequestHandlerRegistry;
import org.elasticsearch.transport.Transport;
import org.elasticsearch.transport.TransportException;
import org.elasticsearch.transport.TransportMessageListener;
import org.elasticsearch.transport.TransportRequest;
import org.elasticsearch.transport.TransportRequestOptions;
import org.elasticsearch.transport.TransportStats;

import java.io.IOException;
import java.net.UnknownHostException;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public final class StubbableTransport implements Transport {

    private final ConcurrentHashMap<TransportAddress, SendRequestBehavior> sendBehaviors = new ConcurrentHashMap<>();
    private final ConcurrentHashMap<TransportAddress, OpenConnectionBehavior> connectBehaviors = new ConcurrentHashMap<>();
    private volatile SendRequestBehavior defaultSendRequest = null;
    private volatile OpenConnectionBehavior defaultConnectBehavior = null;
    private final Transport delegate;

    public StubbableTransport(Transport transport) {
        this.delegate = transport;
    }

    boolean setDefaultSendBehavior(SendRequestBehavior sendBehavior) {
        SendRequestBehavior prior = defaultSendRequest;
        defaultSendRequest = sendBehavior;
        return prior == null;
    }

    public boolean setDefaultConnectBehavior(OpenConnectionBehavior openConnectionBehavior) {
        OpenConnectionBehavior prior = this.defaultConnectBehavior;
        this.defaultConnectBehavior = openConnectionBehavior;
        return prior == null;
    }

    boolean addSendBehavior(TransportAddress transportAddress, SendRequestBehavior sendBehavior) {
        return sendBehaviors.put(transportAddress, sendBehavior) == null;
    }

    boolean addConnectBehavior(TransportAddress transportAddress, OpenConnectionBehavior connectBehavior) {
        return connectBehaviors.put(transportAddress, connectBehavior) == null;
    }

    void clearBehaviors() {
        this.defaultSendRequest = null;
        sendBehaviors.clear();
        this.defaultConnectBehavior = null;
        connectBehaviors.clear();
    }

    void clearBehavior(TransportAddress transportAddress) {
        SendRequestBehavior behavior = sendBehaviors.remove(transportAddress);
        if (behavior != null) {
            behavior.clearCallback();
        }
        connectBehaviors.remove(transportAddress);
    }

    Transport getDelegate() {
        return delegate;
    }

    @Override
    public void addMessageListener(TransportMessageListener listener) {
        delegate.addMessageListener(listener);
    }

    @Override
    public boolean removeMessageListener(TransportMessageListener listener) {
        return delegate.removeMessageListener(listener);
    }

    @Override
    public <Request extends TransportRequest> void registerRequestHandler(RequestHandlerRegistry<Request> reg) {
        delegate.registerRequestHandler(reg);
    }

    @Override
    public RequestHandlerRegistry getRequestHandler(String action) {
        return delegate.getRequestHandler(action);
    }

    @Override
    public BoundTransportAddress boundAddress() {
        return delegate.boundAddress();
    }

    @Override
    public TransportAddress[] addressesFromString(String address, int perAddressLimit) throws UnknownHostException {
        return delegate.addressesFromString(address, perAddressLimit);
    }

    @Override
    public List<String> getLocalAddresses() {
        return delegate.getLocalAddresses();
    }

    @Override
    public Releasable openConnection(DiscoveryNode node, ConnectionProfile profile, ActionListener<Connection> listener) {
        TransportAddress address = node.getAddress();
        OpenConnectionBehavior behavior = connectBehaviors.getOrDefault(address, defaultConnectBehavior);

        ActionListener<Connection> wrappedListener = new ActionListener<Connection>() {

            @Override
            public void onResponse(Connection connection) {
                listener.onResponse(new WrappedConnection(connection));
            }

            @Override
            public void onFailure(Exception e) {
                listener.onFailure(e);
            }
        };

        if (behavior == null) {
            return delegate.openConnection(node, profile, wrappedListener);
        } else {
            return behavior.openConnection(delegate, node, profile, wrappedListener);
        }
    }

    @Override
    public TransportStats getStats() {
        return delegate.getStats();
    }

    @Override
    public Transport.ResponseHandlers getResponseHandlers() {
        return delegate.getResponseHandlers();
    }

    @Override
    public Lifecycle.State lifecycleState() {
        return delegate.lifecycleState();
    }

    @Override
    public void addLifecycleListener(LifecycleListener listener) {
        delegate.addLifecycleListener(listener);
    }

    @Override
    public void removeLifecycleListener(LifecycleListener listener) {
        delegate.removeLifecycleListener(listener);
    }

    @Override
    public void start() {
        delegate.start();
    }

    @Override
    public void stop() {
        delegate.stop();
    }

    @Override
    public void close() {
        delegate.close();
    }

    @Override
    public Map<String, BoundTransportAddress> profileBoundAddresses() {
        return delegate.profileBoundAddresses();
    }

    public class WrappedConnection implements Transport.Connection {

        private final Transport.Connection connection;

        private WrappedConnection(Transport.Connection connection) {
            this.connection = connection;
        }

        @Override
        public DiscoveryNode getNode() {
            return connection.getNode();
        }

        @Override
        public void sendRequest(long requestId, String action, TransportRequest request, TransportRequestOptions options)
            throws IOException, TransportException {
            TransportAddress address = connection.getNode().getAddress();
            SendRequestBehavior behavior = sendBehaviors.getOrDefault(address, defaultSendRequest);
            if (behavior == null) {
                connection.sendRequest(requestId, action, request, options);
            } else {
                behavior.sendRequest(connection, requestId, action, request, options);
            }
        }

        @Override
        public void addCloseListener(ActionListener<Void> listener) {
            connection.addCloseListener(listener);
        }

        @Override
        public boolean isClosed() {
            return connection.isClosed();
        }

        @Override
        public Version getVersion() {
            return connection.getVersion();
        }

        @Override
        public Object getCacheKey() {
            return connection.getCacheKey();
        }

        @Override
        public void close() {
            connection.close();
        }

        public Transport.Connection getConnection() {
            return connection;
        }
    }

    @FunctionalInterface
    public interface OpenConnectionBehavior {

        Releasable openConnection(Transport transport, DiscoveryNode discoveryNode, ConnectionProfile profile,
                                  ActionListener<Connection> listener);
    }

    @FunctionalInterface
    public interface SendRequestBehavior {
        void sendRequest(Connection connection, long requestId, String action, TransportRequest request,
                         TransportRequestOptions options) throws IOException;

        default void clearCallback() {
        }
    }
}


text:
/** api: example[popup]
 *  Feature Popup
 *  -------------
 *  Display a popup with feature information, which is positioned automatically.
 */

var mapPanel, popup;

Ext.onReady(function() {

    // create a vector layer, add features into it
    var vectorLayer = new OpenLayers.Layer.Vector("vector");
    vectorLayer.addFeatures([
        new OpenLayers.Feature.Vector(
            new OpenLayers.Geometry.Point(-75, 45)
        ), new OpenLayers.Feature.Vector(
            new OpenLayers.Geometry.Point(+75, -45)
        ), new OpenLayers.Feature.Vector(
            new OpenLayers.Geometry.Point(+75, +45)
        ), new OpenLayers.Feature.Vector(
            new OpenLayers.Geometry.Point(-75, -45)
        )]

    );

    // create select feature control
    var selectCtrl = new OpenLayers.Control.SelectFeature(vectorLayer);

    // define "createPopup" function
    var bogusMarkup = "Lorem ipsum dolor sit amet, consectetuer adipiscing elit.";
    function createPopup(feature) {
        popup = new GeoExt.Popup({
            title: 'My Popup',
            location: feature,
            width:200,
            html: bogusMarkup,
            maximizable: true,
            collapsible: true,
            anchorPosition: "auto"
        });
        // unselect feature when the popup
        // is closed
        popup.on({
            close: function() {
                if(OpenLayers.Util.indexOf(vectorLayer.selectedFeatures,
                                           this.feature) > -1) {
                    selectCtrl.unselect(this.feature);
                }
            }
        });
        popup.show();
    }

    // create popup on "featureselected"
    vectorLayer.events.on({
        featureselected: function(e) {
            createPopup(e.feature);
        }
    });

    // create Ext window including a map panel
    var mapwin = new Ext.Window({
        layout: "fit",
        title: "Map",
        closeAction: "hide",
        width: 650,
        height: 356,
        x: 50,
        y: 100,
        items: {
            xtype: "gx_mappanel",
            region: "center",
            layers: [
                new OpenLayers.Layer.WMS(
                    "OpenLayers WMS",
                    "http://vmap0.tiles.osgeo.org/wms/vmap0",
                    {layers: 'basic'} ),
                vectorLayer
            ]
        }
    });
    mapwin.show();

    mapPanel = mapwin.items.get(0);
    mapPanel.map.addControl(selectCtrl);
    selectCtrl.activate();
});


text:
package gwt.material.design.addins.client.carousel.events;

import com.google.gwt.event.shared.EventHandler;
import com.google.gwt.event.shared.GwtEvent;
import com.google.gwt.event.shared.HasHandlers;

/**
 * When Slick initializes for the first time callback. Note that this event should be defined before initializing the slider.
 *
 * @author kevzlou7979
 */
public class InitEvent extends GwtEvent<InitEvent.InitHandler> {

    public interface InitHandler extends EventHandler {
        void onInit(InitEvent event);
    }

    public static final Type<InitHandler> TYPE = new Type<>();

    public static Type<InitHandler> getType() {
        return TYPE;
    }

    public InitEvent() {
    }

    public static void fire(HasHandlers source) {
        source.fireEvent(new InitEvent());
    }

    @Override
    public Type<InitHandler> getAssociatedType() {
        return TYPE;
    }

    @Override
    protected void dispatch(InitEvent.InitHandler handler) {
        handler.onInit(this);
    }
}


text:
package org.primaresearch.dla.page.layout.physical.impl;

import org.primaresearch.dla.page.layout.PageLayout;
import org.primaresearch.dla.page.layout.logical.Layer;
import org.primaresearch.dla.page.layout.physical.ContentIterator;
import org.primaresearch.dla.page.layout.physical.ContentObject;
import org.primaresearch.dla.page.layout.physical.Region;
import org.primaresearch.dla.page.layout.physical.RegionContainer;
import org.primaresearch.dla.page.layout.physical.shared.ContentType;
import org.primaresearch.dla.page.layout.physical.shared.RegionType;

/**
 * Page content object iterator implementation for regions (zones/blocks).
 *
 * @author Christian Clausner
 *
 */
public class RegionIterator implements ContentIterator {

	protected RegionType contentType;
	protected PageLayout pageLayout;
	protected Layer layer;
	protected int index = 0;
	protected NestedRegionIterator currentNestedRegionIterator = null;

	/**
	 * Constructor
	 * @param contentType Specific region type (e.g. table) or null to include all regions
	 * @param layer Restrict the iterator to this layer (use null for no restriction)
	 */
	public RegionIterator(PageLayout pageLayout, RegionType contentType, Layer layer) {
		this.contentType = contentType;
		this.pageLayout = pageLayout;
		this.layer = layer;
	}

	@Override
	public boolean hasNext() {
		if (contentType == null && layer == null) { //No specific region type or layer
			if (currentNestedRegionIterator == null)
				return index < pageLayout.getRegionCount();
			else
				return currentNestedRegionIterator.hasNext() || index < pageLayout.getRegionCount()-1;
		}
		//Filter by region type and/or layer
		else {
			boolean ok;
			int startIndex = index;

			//Check current nested iterator first
			if (currentNestedRegionIterator != null) {
				if (currentNestedRegionIterator.hasNext())
					return true;
				else
					startIndex++;
			}

			//Go through all remaining regions
			for (int i=startIndex; i<pageLayout.getRegionCount(); i++) {
				//Check region
				Region reg = pageLayout.getRegion(i);
				ok = true;
				if (contentType != null)
					ok = reg.getType().equals(contentType);
				if (ok && layer != null)
					ok = layer.containsRegionRef(reg.getId());
				if (ok)
					return ok;

				//Check nested regions
				NestedRegionIterator it = new NestedRegionIterator((RegionContainer)reg, pageLayout, contentType, layer);
				if (it.hasNext())
					return true;
			}
		}
		return false;
	}

	@Override
	public ContentObject next() {
		if (!hasNext())
			return null;

		//Check current nested region iterator
		if (currentNestedRegionIterator != null) {
			//Is there a next nested region?
			if (currentNestedRegionIterator.hasNext())
				return currentNestedRegionIterator.next();
			else { //No next nested region
				//Proceed to next parent
				index++;
				currentNestedRegionIterator = null;
			}
		}

		Region ret = null;
		if (contentType == null && layer == null) { //No specific region type or layer
			ret = pageLayout.getRegion(index);
			currentNestedRegionIterator = new NestedRegionIterator((RegionContainer)ret, pageLayout, contentType, layer);
		}
		//Filter by region type and/or layer
		else {
			boolean ok;

			//Go through all remaining regions
			for (int i=index; i<pageLayout.getRegionCount(); i++) {
				//Current nested iterator cannot have a result here (otherwise it would have been found at the start of this method).

				//Check region (not nested)
				Region reg = pageLayout.getRegion(i);
				ok = true;
				if (contentType != null)
					ok = reg.getType().equals(contentType);
				if (ok && layer != null)
					ok = layer.containsRegionRef(reg.getId());
				if (ok) {
					ret = reg;
					if (((RegionContainer)reg).getRegionCount() == 0) //No child regions
						index = i+1;
					else {
						index = i;
						currentNestedRegionIterator = new NestedRegionIterator((RegionContainer)reg, pageLayout, contentType, layer);
					}
					break;
				}

				//Check nested regions
				NestedRegionIterator it = new NestedRegionIterator((RegionContainer)reg, pageLayout, contentType, layer);
				if (it.hasNext()) {
					ret = (Region)it.next();
					currentNestedRegionIterator = it;
					index = i;
					break;
				}
			}

		}
		return ret;
	}

	@Override
	public ContentType getContentType() {
		return contentType;
	}

	@Override
	public Layer getLayer() {
		return layer;
	}

	/**
	 * Iterates over all nested regions of a parent region
	 *
	 * @author Christian Clausner
	 *
	 */
	private static class NestedRegionIterator extends RegionIterator {

		private RegionContainer parent;

		public NestedRegionIterator(RegionContainer parent, PageLayout pageLayout,
				RegionType contentType, Layer layer) {
			super(pageLayout, contentType, layer);
			this.parent = parent;
		}

		@Override
		public boolean hasNext() {
			if (contentType == null && layer == null) { //No specific region type or layer
				if (currentNestedRegionIterator == null)
					return index < parent.getRegionCount();
				else
					return currentNestedRegionIterator.hasNext() || index < parent.getRegionCount()-1;
			}
			//Filter by region type and/or layer
			else {
				boolean ok;
				int startIndex = index;

				//Check current nested iterator first
				if (currentNestedRegionIterator != null) {
					if (currentNestedRegionIterator.hasNext())
						return true;
					else
						startIndex++;
				}

				//Go through all remaining regions
				for (int i=startIndex; i<parent.getRegionCount(); i++) {
					//Check region
					Region reg = parent.getRegion(i);
					ok = true;
					if (contentType != null)
						ok = reg.getType().equals(contentType);
					if (ok && layer != null)
						ok = layer.containsRegionRef(reg.getId());
					if (ok)
						return ok;

					//Check nested regions
					NestedRegionIterator it = new NestedRegionIterator((RegionContainer)reg, pageLayout, contentType, layer);
					if (it.hasNext())
						return true;
				}
			}
			return false;
		}

		@Override
		public ContentObject next() {
			if (!hasNext())
				return null;

			//Check current nested region iterator
			if (currentNestedRegionIterator != null) {
				//Is there a next nested region?
				if (currentNestedRegionIterator.hasNext())
					return currentNestedRegionIterator.next();
				else { //No next nested region
					//Proceed to next parent
					index++;
					currentNestedRegionIterator = null;
				}
			}

			Region ret = null;
			if (contentType == null && layer == null) { //No specific region type or layer
				ret = parent.getRegion(index);
				currentNestedRegionIterator = new NestedRegionIterator((RegionContainer)ret, pageLayout, contentType, layer);
			}
			//Filter by region type and/or layer
			else {
				boolean ok;

				//Go through all remaining regions
				for (int i=index; i<parent.getRegionCount(); i++) {
					//Current nested iterator cannot have a result here (otherwise it would have been found at the start of this method).

					//Check region (not nested)
					Region reg = parent.getRegion(i);
					ok = true;
					if (contentType != null)
						ok = reg.getType().equals(contentType);
					if (ok && layer != null)
						ok = layer.containsRegionRef(reg.getId());
					if (ok) {
						ret = reg;
						if (((RegionContainer)reg).getRegionCount() == 0) //No child regions
							index = i+1;
						else {
							index = i;
							currentNestedRegionIterator = new NestedRegionIterator((RegionContainer)reg, pageLayout, contentType, layer);
						}
						break;
					}

					//Check nested regions
					NestedRegionIterator it = new NestedRegionIterator((RegionContainer)reg, pageLayout, contentType, layer);
					if (it.hasNext()) {
						ret = (Region)it.next();
						currentNestedRegionIterator = it;
						index = i;
						break;
					}
				}

			}
			return ret;
		}
	}

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
    Ordering three line items for delivery on the same day (a few days
    after the order date).
-->
<!--- <!DOCTYPE cXML SYSTEM "cXML.dtd"> -->
<cXML payloadID="680319@ariba.flextronics.com"
      timestamp="2000-10-12T18:39:09-08:00" xml:lang="en-US">
    <Header>
        <From>
            <!-- The buying marketplace and member organization. -->
            <Credential domain="AribaNetworkUserId" type="marketplace">
                <Identity>bigadmin@marketplace.org</Identity>
            </Credential>
            <Credential domain="AribaNetworkUserId">
                <Identity>admin@acme.com</Identity>
            </Credential>
        </From>
        <To>
            <Credential domain="DUNS">
                <Identity>942888711</Identity>
            </Credential>
        </To>
        <Sender>
            <!-- This document has passed through Ariba CSN to the
                 supplier. -->
            <Credential domain="AribaNetworkUserId">
                <Identity>sysadmin@ariba.com</Identity>
                <SharedSecret>abracadabra</SharedSecret>
            </Credential>
            <UserAgent>Ariba CSN 33</UserAgent>
        </Sender>
    </Header>
    <Request deploymentMode="test">
        <OrderRequest>
             <OrderRequestHeader orderID="DO7865" orderDate="2000-12-10"
                                 type="new">
                 <Total>
                     <Money currency="USD">187.60</Money>
                 </Total>
                 <ShipTo>
                     <Address>
                         <Name xml:lang="en">Acme</Name>
                         <PostalAddress name="default">
                             <DeliverTo>Joe Smith</DeliverTo>
                             <DeliverTo>Mailstop M-543</DeliverTo>
                             <Street>123 Anystreet</Street>
                             <City>Sunnyvale</City>
                             <State>CA</State>
                             <PostalCode>90489</PostalCode>
                             <Country isoCountryCode="US">United States
                             </Country>
                         </PostalAddress>
                     </Address>
                 </ShipTo>
                 <BillTo>
                     <Address>
                         <Name xml:lang="en">Acme</Name>
                         <PostalAddress name="default">
                             <Street>123 Anystreet</Street>
                             <City>Sunnyvale</City>
                             <State>CA</State>
                             <PostalCode>90489</PostalCode>
                             <Country isoCountryCode="US">United States
                             </Country>
                         </PostalAddress>
                     </Address>
                 </BillTo>
                 <Payment>
                     <PCard number="1234567890123456"
                            expiration="2001-03-12"/>
                 </Payment>
                 <Comments xml:lang="en-US">Anything well formed in XML.
                 </Comments>
             </OrderRequestHeader>
             <ItemOut quantity="3" requestedDeliveryDate="2000-10-18"
                      lineNumber="5">
                 <ItemID>
                     <SupplierPartID>1233246</SupplierPartID>
                 </ItemID>
                 <ItemDetail>
                    <UnitPrice>
                        <Money currency="USD">4.02</Money>
                    </UnitPrice>
                    <Description xml:lang="en">Steel Rebar
                    </Description>
                    <UnitOfMeasure>EA</UnitOfMeasure>
                    <Classification domain="SPSC">12347</Classification>
                    <ManufacturerPartID>236</ManufacturerPartID>
                    <ManufacturerName>foobar</ManufacturerName>
                    <URL>www.foo.com</URL>
                 </ItemDetail>
             </ItemOut>
             <ItemOut quantity="10" requestedDeliveryDate="2000-10-18"
                      lineNumber="1">
                 <ItemID>
                     <SupplierPartID>1233244</SupplierPartID>
                 </ItemID>
                 <ItemDetail>
                    <UnitPrice>
                        <Money currency="USD">1.34</Money>
                    </UnitPrice>
                    <Description xml:lang="en">Titanium screws
                    </Description>
                    <UnitOfMeasure>EA</UnitOfMeasure>
                    <Classification domain="SPSC">12345</Classification>
                    <ManufacturerPartID>234</ManufacturerPartID>
                    <ManufacturerName>foobar</ManufacturerName>
                    <URL>www.foo.com</URL>
                 </ItemDetail>
             </ItemOut>
             <ItemOut quantity="20" requestedDeliveryDate="2000-10-18"
                      lineNumber="4">
                 <ItemID>
                     <SupplierPartID>1233245</SupplierPartID>
                 </ItemID>
                 <ItemDetail>
                    <UnitPrice>
                        <Money currency="USD">2.68</Money>
                    </UnitPrice>
                    <Description xml:lang="en">hello from item 4
                    </Description>
                    <UnitOfMeasure>EA</UnitOfMeasure>
                    <Classification domain="SPSC">12346</Classification>
                    <ManufacturerPartID>235</ManufacturerPartID>
                    <ManufacturerName>foobar</ManufacturerName>
                    <URL>www.foo.com</URL>
                 </ItemDetail>
             </ItemOut>
             <ItemOut quantity="30" requestedDeliveryDate="2000-10-18"
                      lineNumber="5">
                 <ItemID>
                     <SupplierPartID>1233246</SupplierPartID>
                 </ItemID>
                 <ItemDetail>
                    <UnitPrice>
                        <Money currency="USD">4.02</Money>
                    </UnitPrice>
                    <Description xml:lang="en">hello from item 5
                    </Description>
                    <UnitOfMeasure>EA</UnitOfMeasure>
                    <Classification domain="SPSC">12347</Classification>
                    <ManufacturerPartID>236</ManufacturerPartID>
                    <ManufacturerName>foobar</ManufacturerName>
                    <URL>www.foo.com</URL>
                 </ItemDetail>
             </ItemOut>
         </OrderRequest>
    </Request>
</cXML>


text:
(function() {
  var CONFIG, Deploy, HashReplace, Mustache, colors, deploy_map, exec, frag_name, fs, hash_map, path, project_dir, rel_path;

  require("js-yaml");

  fs = require("fs");

  path = require("path");

  colors = require("colors");

  Mustache = require("mustache");

  exec = require('child_process').exec;

  console.log("\n\n Zonda Tool".bold + ":  Deploy...");

  project_dir = path.resolve('./', '../');

  CONFIG = require("" + project_dir + "/etc/zonda.yml");

  deploy_map = CONFIG.deploy_map;

  if (CONFIG.version === "md5") {
    hash_map = fs.readFileSync("" + project_dir + "/dist/.cache_hash_map.json", {
      encoding: "utf8"
    });
    hash_map = JSON.parse(hash_map);
  }

  HashReplace = function(text) {
    var file, hash, target_file;
    if (CONFIG.version !== "md5") {
      return text;
    }
    for (file in hash_map) {
      hash = hash_map[file];
      target_file = file.replace(CONFIG.version, hash);
      text = text.replace(file, target_file);
    }
    return text;
  };

  Deploy = function(rel_path, frag_name) {
    var deploy_dir, err, res_content, tpl;
    deploy_dir = path.resolve(project_dir, rel_path);
    console.log("\n   Deploying: ".bold + ("" + deploy_dir + "/") + (" " + frag_name).bold.yellow + "...");
    try {
      tpl = fs.readFileSync("" + project_dir + "/tool/deploy_fragment/" + frag_name, {
        encoding: "utf8"
      });
      res_content = Mustache.render(tpl, {
        CONFIG: CONFIG
      });
      res_content = HashReplace(res_content);
      fs.writeFileSync("" + deploy_dir + "/" + frag_name, res_content);
      return console.log("   >>".bold + " Success!".green);
    } catch (_error) {
      err = _error;
      console.log("   >>".bold + " Error!".red.inverse);
      return console.log("   >>".bold + (" " + err).red.inverse.bold);
    }
  };

  for (frag_name in deploy_map) {
    rel_path = deploy_map[frag_name];
    Deploy(rel_path, frag_name);
  }

}).call(this);


text:
using System;
using Neutronium.Core.JavascriptFramework;
using Neutronium.Core.WebBrowserEngine.JavascriptObject;
using Tests.Infra.WebBrowserEngineTesterHelper.HtmlContext;

namespace Tests.Infra.JavascriptFrameworkTesterHelper
{
    public class FrameworkTestContext
    {
        public IJavascriptFrameworkManager FrameworkManager { get; set; }

        public Func<IWebView, IJavascriptFrameworkExtractor> JavascriptFrameworkExtractorBuilder { get; set; }

        public ITestHtmlProvider HtmlProvider { get; set; }
    }
}


text:
from django.db import models
from django.core.urlresolvers import reverse
from django.utils.translation import ugettext_lazy as _
from localflavor.us.us_states import US_STATES

import re

class District(models.Model):
    name = models.CharField(_("name"), max_length=250)
    slug = models.SlugField(_("slug"), unique=True)
    fips = models.PositiveIntegerField(_("FIPS"), max_length=5, blank=True, help_text=_("See FIPS County Code."))
    county_seat = models.CharField(_("county seat"), max_length=250, blank=True)
    created = models.PositiveIntegerField(_("year created"), max_length=4, blank=True)
    population = models.PositiveIntegerField(_("population"), max_length=10, blank=True)
    area = models.PositiveIntegerField(_("area"), max_length=6, blank=True, help_text=_("In square miles"))
    google_map = models.CharField(_("google maps ID"), blank=True, max_length=43, help_text=_("Example: 100086641935463435263.00043d849437ec4ec3308"))

    class Meta:
        ordering = ["name"]
        verbose_name = _("district")
        verbose_name_plural = _("districts")

    def __unicode__(self):
        return u"%s" % (self.name)

class Place(models.Model):
    name = models.CharField(_("name"), max_length=250)
    slug = models.SlugField(_("slug"), unique=True)
    address = models.CharField(_("address"), max_length=250, blank=True, help_text=_("Optional, but add them when possible."))
    city = models.CharField(_("city"), max_length=250, blank=True)
    district = models.ForeignKey(District, blank=True, null=True)
    state = models.CharField(_("state"), choices=US_STATES, max_length=255, blank=True)
    zipcode = models.CharField(_("ZIP code"), max_length=11, blank=True)
    country = models.CharField(_("country"), max_length=250, default="USA", blank=True)
    description = models.TextField(_("description"), blank=True, help_text=_("Please use Markdown styling."))
    photo = models.ImageField(_("photo"), upload_to="places/", blank=True)
    photo_url = models.URLField(_("photo's origin URL"), blank=True, help_text=_("Probably the original Flickr photo page"))
    photographer = models.CharField(_("photographer's name"), max_length=250, blank=True)
    photographer_url = models.URLField(_("photographer's URL"), blank=True, help_text=_("Could be a Flickr profile page, Facebook profile page, etc."))
    latitude = models.DecimalField(_("latitude"), max_digits=9, decimal_places=6, help_text=_("Use GetLatLon.com to find the latitude. Only six places after the decimal are allowed."))
    longitude = models.DecimalField(_("longitude"), max_digits=9, decimal_places=6, help_text=_("Use GetLatLon.com to find the longitude. Only six places after the decimal are allowed."))
    street = models.CharField(_("street view"), blank=True, max_length=250, help_text=_("1. Find location on Google Maps
2. Click on “Street View” and adjust camera.
3. Click “Link to this Page” > “Customize and preview embedded map”
4. Scroll to number three and extract quoted URL in src=\"\" from <iframe> HTML tag."))
    url = models.URLField(_("URL"), blank=True)

    class Meta:
        ordering = ["name"]
        verbose_name = _("place")
        verbose_name_plural = _("places")

    def __unicode__(self):
        return u"%s" % (self.name)

    def get_absolute_url(self):
        return reverse("places_place_detail", args=[str(self.slug)])

    def website(self):
        domain = re.sub(r"(http|https)://(?:www\.)", "", self.url)
        pretty = re.sub(r"\/$", "", domain)
        return u"%s" % (pretty)


text:
package ca.uhn.fhir.jpa.model.util;

import ca.uhn.fhir.util.UrlUtil;
import com.google.common.base.Charsets;
import com.google.common.hash.HashCode;
import com.google.common.hash.HashFunction;
import com.google.common.hash.Hasher;
import com.google.common.hash.Hashing;

public class CodeSystemHash {
    private static final HashFunction HASH_FUNCTION = Hashing.murmur3_128(0);
    private static final byte[] DELIMITER_BYTES = "|".getBytes(Charsets.UTF_8);

    static public long hashCodeSystem( String system, String code ) {
        Hasher hasher = HASH_FUNCTION.newHasher();
        addStringToHasher(hasher, system);
        addStringToHasher(hasher, code);

        HashCode hashCode = hasher.hash();
        return hashCode.asLong();
    }

    static private void addStringToHasher(Hasher hasher, String next) {
        if (next == null) {
            hasher.putByte((byte) 0);
        } else {
            next = UrlUtil.escapeUrlParam(next);
            byte[] bytes = next.getBytes(Charsets.UTF_8);
            hasher.putBytes(bytes);
        }
        hasher.putBytes(DELIMITER_BYTES);
    }
}


text:
<?php

namespace OTPAuthenticate;

use PHPUnit\Framework\TestCase;

require_once(dirname(__FILE__) . '/../lib/OTPAuthenticate.php');
require_once(dirname(__FILE__) . '/../vendor/christian-riesen/base32/src/Base32.php');

class weakCrypto extends TestCase
{
	protected $secret = "MRTGW2TEONWDQMR7";

	static public $weak_crypto = false;

	/** @var \OTPAuthenticate\OTPAuthenticate */
	protected $otp_auth;

	public function setUp(): void
	{
		parent::setUp();

		$this->otp_auth = new \OTPAuthenticate\OTPAuthenticate();
	}

	public function testWeakCrypto()
	{
		$this->assertNotSame('', $this->otp_auth->generateSecret());
		self::$weak_crypto = true;
		$this->assertSame('', $this->otp_auth->generateSecret());
		self::$weak_crypto = false;
		$this->assertNotSame('', $this->otp_auth->generateSecret());
	}
}

function openssl_random_pseudo_bytes($length, &$strong_secret)
{
	$random_string = \openssl_random_pseudo_bytes($length, $strong_secret);
	if (\OTPAuthenticate\weakCrypto::$weak_crypto === true)
	{
		$strong_secret = false;
	}

	return $random_string;
}


text:
/* ========================================================================== */
/* === KLU/Include/klu_internal.h =========================================== */
/* ========================================================================== */

/* For internal use in KLU routines only, not for user programs */

#ifndef _KLU_INTERNAL_H
#define _KLU_INTERNAL_H

#include "klu.h"
#include "btf.h"
#include "klu_version.h"

/* ========================================================================== */
/* make sure debugging and printing is turned off */

#ifndef NDEBUG
#define NDEBUG
#endif
#ifndef NPRINT
#define NPRINT
#endif

/* To enable debugging and assertions, uncomment this line:
 #undef NDEBUG
 */

/* To enable diagnostic printing, uncomment this line:
 #undef NPRINT
 */

/* ========================================================================== */

#include <stdio.h>
#include <assert.h>
#include <limits.h>
#include <stdlib.h>
#include <math.h>

#undef ASSERT
#ifndef NDEBUG
#define ASSERT(a) assert(a)
#else
#define ASSERT(a)
#endif

#define SCALAR_IS_NAN(x) ((x) != (x))

/* true if an integer (stored in double x) would overflow (or if x is NaN) */
#define INT_OVERFLOW(x) ((!((x) * (1.0+1e-8) <= (double) INT_MAX)) \
                        || SCALAR_IS_NAN (x))

#undef TRUE
#undef FALSE
#undef MAX
#undef MIN
#undef PRINTF
#undef FLIP

#ifndef NPRINT
#define PRINTF(s) { printf s ; } ;
#else
#define PRINTF(s)
#endif

#define TRUE 1
#define FALSE 0
#define MAX(a,b) (((a) > (b)) ?  (a) : (b))
#define MIN(a,b) (((a) < (b)) ?  (a) : (b))

/* FLIP is a "negation about -1", and is used to mark an integer i that is
 * normally non-negative.  FLIP (EMPTY) is EMPTY.  FLIP of a number > EMPTY
 * is negative, and FLIP of a number < EMTPY is positive.  FLIP (FLIP (i)) = i
 * for all integers i.  UNFLIP (i) is >= EMPTY. */
#define EMPTY (-1)
#define FLIP(i) (-(i)-2)
#define UNFLIP(i) (((i) < EMPTY) ? FLIP (i) : (i))

size_t KLU_kernel   /* final size of LU on output */
(
    /* input, not modified */
    Int n,              /* A is n-by-n */
    Int Ap [ ],         /* size n+1, column pointers for A */
    Int Ai [ ],         /* size nz = Ap [n], row indices for A */
    Entry Ax [ ],       /* size nz, values of A */
    Int Q [ ],          /* size n, optional input permutation */
    size_t lusize,      /* initial size of LU */

    /* output, not defined on input */
    Int Pinv [ ],       /* size n */
    Int P [ ],          /* size n */
    Unit **p_LU,        /* size lusize on input, size Uxp[n] on output*/
    Entry Udiag [ ],    /* size n, diagonal of U */
    Int Llen [ ],       /* size n, column length of L */
    Int Ulen [ ],       /* size n, column length of U */
    Int Lip [ ],        /* size n+1 */
    Int Uip [ ],        /* size n+1 */
    Int *lnz,           /* size of L */
    Int *unz,           /* size of U */

    /* workspace, not defined on input */
    Entry X [ ],   /* size n, zero on output */

    /* workspace, not defined on input or output */
    Int Stack [ ],  /* size n */
    Int Flag [ ],   /* size n */
    Int adj_pos [ ],    /* size n */

    /* workspace for pruning only */
    Int Lpend [ ],      /* size n workspace */

    /* inputs, not modified on output */
    Int k1,             /* the block of A is from k1 to k2-1 */
    Int PSinv [ ],      /* inverse of P from symbolic factorization */
    double Rs [ ],      /* scale factors for A */

    /* inputs, modified on output */
    Int Offp [ ],   /* off-diagonal matrix (modified by this routine) */
    Int Offi [ ],
    Entry Offx [ ],
    KLU_common *Common  /* the control input/output structure */
) ;

size_t KLU_kernel_factor            /* 0 if failure, size of LU if OK */
(
    /* inputs, not modified */
    Int n,          /* A is n-by-n. n must be > 0. */
    Int Ap [ ],     /* size n+1, column pointers for A */
    Int Ai [ ],     /* size nz = Ap [n], row indices for A */
    Entry Ax [ ],   /* size nz, values of A */
    Int Q [ ],      /* size n, optional column permutation */
    double Lsize,   /* initial size of L and U */

    /* outputs, not defined on input */
    Unit **p_LU,        /* row indices and values of L and U */
    Entry Udiag [ ],    /* size n, diagonal of U */
    Int Llen [ ],       /* size n, column length of L */
    Int Ulen [ ],       /* size n, column length of U */
    Int Lip [ ],        /* size n+1, column pointers of L */
    Int Uip [ ],        /* size n+1, column pointers of U */
    Int P [ ],          /* row permutation, size n */
    Int *lnz,           /* size of L */
    Int *unz,           /* size of U */

    /* workspace, undefined on input */
    Entry *X,       /* size n entries.  Zero on output */
    Int *Work,      /* size 5n Int's */

    /* inputs, not modified on output */
    Int k1,             /* the block of A is from k1 to k2-1 */
    Int PSinv [ ],      /* inverse of P from symbolic factorization */
    double Rs [ ],      /* scale factors for A */

    /* inputs, modified on output */
    Int Offp [ ],   /* off-diagonal matrix (modified by this routine) */
    Int Offi [ ],
    Entry Offx [ ],
    KLU_common *Common  /* the control input/output structure */
) ;

void KLU_lsolve
(
    /* inputs, not modified: */
    Int n,
    Int Lp [ ],
    Int Li [ ],
    Unit LU [ ],
    Int nrhs,
    /* right-hand-side on input, solution to Lx=b on output */
    Entry X [ ]
) ;

void KLU_ltsolve
(
    /* inputs, not modified: */
    Int n,
    Int Lp [ ],
    Int Li [ ],
    Unit LU [ ],
    Int nrhs,
#ifdef COMPLEX
    Int conj_solve,
#endif
    /* right-hand-side on input, solution to L'x=b on output */
    Entry X [ ]
) ;

void KLU_usolve
(
    /* inputs, not modified: */
    Int n,
    Int Up [ ],
    Int Ui [ ],
    Unit LU [ ],
    Entry Udiag [ ],
    Int nrhs,
    /* right-hand-side on input, solution to Ux=b on output */
    Entry X [ ]
) ;

void KLU_utsolve
(
    /* inputs, not modified: */
    Int n,
    Int Up [ ],
    Int Ui [ ],
    Unit LU [ ],
    Entry Udiag [ ],
    Int nrhs,
#ifdef COMPLEX
    Int conj_solve,
#endif
    /* right-hand-side on input, solution to U'x=b on output */
    Entry X [ ]
) ;

Int KLU_valid
(
    Int n,
    Int Ap [ ],
    Int Ai [ ],
    Entry Ax [ ]
) ;

Int KLU_valid_LU
(
    Int n,
    Int flag_test_start_ptr,
    Int Xip [ ],
    Int Xlen [ ],
    Unit LU [ ]
);

size_t KLU_add_size_t (size_t a, size_t b, Int *ok) ;

size_t KLU_mult_size_t (size_t a, size_t k, Int *ok) ;

KLU_symbolic *KLU_alloc_symbolic (Int n, Int *Ap, Int *Ai, KLU_common *Common) ;

#endif


text:
This is a simple Golang based demo which demonstrates how software can be intelligent enough to do its own load balancing, easing the work load on system administrations and engineers.

In an ideal world, developers would have the time to ensure their systems are robust enough to deal with remote endpoints being unavailable, either failing gracefully or re-trying at appropriate intervals.

## Architecture

You have a remote API which serves up nothing but its instance name - it's clearly the greatest API to hit the Internet. You want to be able to launch multiple instances of this API and have the incoming requests load balanced for speed and reliability. Here are the common ways to do this.

### Load Balancer

```
HAProxy -> [API, API, ...]
```

The problem with this approach is HAProxy is a single point of failure - if it goes down, nothing is available.

### Two Load Balancers

```
[HAProxy | HAProxy] -> [API, API, API, ...]
```

(I'm making up syntax/symbols as I go along here; "," means each item is independant; "|" means the items on each side are dependent on each other, like in a cluster)

Much better, but this means you need to cluster the HAProxy instances and have a floating IP. There are situation were the latter isn't possible, stability of the cluster isn't performant, or you simply don't want the complexity of managing a cluster (I know I don't.)

### Two Load Balancers, No Cluster

```
[HAProxy, HAProxy] -> [API, API, API, ...]
```

Now we have two HAProxy instances which can LB requests between our pool of API servers. The problem here, however, is you now have two public IPs (and thus two public DNS records) for each HAProxy instance, but the clients talking to the API are probably only configured to talk to one... well that's the problem.

## A Solution

Have your client's be aware of both endpoints and programmatically switch between them as their availability comes and goes (which hopefully won't happen):

```python
endpoints = ["api01", "api02"]
use_endpoint = None

for endpoint in endpoints:
  if check_endpoint_health(endpoint):
    use_endpoint = endpoint
    break

if not use_endpoint:
  headless_chicken_mode()

# ...
```

This is very basic code, of course, but the idea is simple:

1. Configure you client with multiple endpoints;
1. Have the client iterate over the endpoints either on start up or per-request, or some other algorithm;
1. If an endpoint isn't available, move on to the next one;
1. If none are available, wait a bit, don't just die like a drama queen;

Such a simple solution resulting in a very stable experience for the end user, not to mention an even simpler infrastructure for the engineering team to design and the administration team to maintain.

## This Repository

This repository contains Go code which can be used to launch a few local APIs and run a multi-endpoint aware client to talk to them. Try running multiple API instances (which just need a configuration file) and then launching a correctly configured client. What happens if you kill an API and use the client again? it should skip the "broken" API endpoint. #win

### Example Session

Let's start the API servers:

```
$ api configs/api_01.json
Starting API with the following configuration...
	BindPort: 0.0.0.0
	BindIP: 8081
	APIName: API01
2015/08/04 15:12:42.878093 Starting Goji on [::]:8081
```

```
$ api configs/api_02.json
Starting API with the following configuration...
	BindPort: 0.0.0.0
	BindIP: 8082
	APIName: API02
2015/08/04 15:16:43.398193 Starting Goji on [::]:8082
```

Let's flip their health statuses to ensure they're showing as "OK":

```
$ curl localhost:8081/health/flip
{"Result":true,"Message":"OK"}

$ curl localhost:8082/health/flip
{"Result":true,"Message":"OK"}
```

And are they OK?

```
$ curl localhost:8082/health
{"Result":true,"Message":"OK"}

$ curl localhost:8081/health
{"Result":true,"Message":"OK"}
```

But what does the client think:

```
$ client configs/client.json
Configuration loaded.
Configured Endpoint: 127.0.0.1, Port: 8081, Name: Remote API 01
Configured Endpoint: 127.0.0.1, Port: 8082, Name: Remote API 02
Using endpoint: Remote API 01
Response Message (Result): This is API: API01 (true)
```

And if we turn "off" `API01`?

```
$ curl localhost:8081/health/flip
{"Result":false,"Message":"OK"}

$ client configs/client.json
Configuration loaded.
Configured Endpoint: 127.0.0.1, Port: 8081, Name: Remote API 01
Configured Endpoint: 127.0.0.1, Port: 8082, Name: Remote API 02
Using endpoint: Remote API 02
Response Message (Result): This is API: API02 (true)
```

The client automatically detected that the first endpoint in its configuration is dead, so it used the second one. What if both go down?

```
$ curl localhost:8082/health/flip
{"Result":false,"Message":"OK"}

$ client configs/client.json
Configuration loaded.
Configured Endpoint: 127.0.0.1, Port: 8081, Name: Remote API 01
Configured Endpoint: 127.0.0.1, Port: 8082, Name: Remote API 02
No endpoints to work with. Exiting.
```

It correctly detects that no endpoints are available and exits gracefully. We can exit gracefully here because this is a demo, but in the real world, you would want your application to hang around and periodically check if the endpoints have come back again - that's the sensible thing to do.

## Author

Michael Crilly


text:
well this is my first repository...
I am an undergraduate from BUCT majoring in ploymer material. Now I am at grade Two.
I have to say I love coding. and I'd like to change my major to something about computer science in graduate level.
Here, the journey begin.

I can code in Python and C and I love them. So if anyone have the same sense with me, let's chat and communicating.
February. 6th. 2017


text:
import { useEffect, useState } from 'react';

import {
    LoaderPage,
    StandardLoadErrorPage,
    useApi,
    useCache,
    useEventManager,
    useGetAddressKeys,
    useGetAddresses,
} from '@proton/components';
import setupCalendarHelper from '@proton/shared/lib/calendar/keys/setupCalendarHelper';
import { setupCalendarKeys } from '@proton/shared/lib/calendar/keys/setupCalendarKeys';
import { traceError } from '@proton/shared/lib/helpers/sentry';
import { VisualCalendar } from '@proton/shared/lib/interfaces/calendar';
import { CalendarUserSettingsModel, CalendarsModel } from '@proton/shared/lib/models';
import { loadModels } from '@proton/shared/lib/models/helper';

interface Props {
    onDone: () => void;
    calendars?: VisualCalendar[];
}
const CalendarSetupContainer = ({ onDone, calendars }: Props) => {
    const { call } = useEventManager();
    const cache = useCache();
    const getAddresses = useGetAddresses();
    const getAddressKeys = useGetAddressKeys();

    const normalApi = useApi();
    const silentApi = <T,>(config: any) => normalApi<T>({ ...config, silence: true });

    const [error, setError] = useState();

    useEffect(() => {
        const run = async () => {
            const addresses = await getAddresses();

            if (calendars) {
                await setupCalendarKeys({
                    api: silentApi,
                    calendars,
                    getAddressKeys,
                });
            } else {
                await setupCalendarHelper({
                    api: silentApi,
                    addresses,
                    getAddressKeys,
                });
            }

            await call();
            await loadModels([CalendarsModel, CalendarUserSettingsModel], { api: silentApi, cache, useCache: false });
        };
        run()
            .then(() => {
                onDone();
            })
            .catch((e) => {
                setError(e);
                traceError(e);
            });
    }, []);

    if (error) {
        return <StandardLoadErrorPage />;
    }

    return <LoaderPage />;
};

export default CalendarSetupContainer;


text:
var keyMirror = require('react/lib/keyMirror');

// Define action constants
module.exports = keyMirror({
	TOGGLE_ACTIVE: null,
	DELETE_PATIENTS: null,
	ADD_PATIENT: null,
	LOAD_PATIENTS: null
});


text:
using FlatRedBall.Glue.GuiDisplay;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FlatRedBall.AnimationEditorForms.PropertyGrids
{
    internal class CircleDisplayer : PropertyGridDisplayer
    {
        public override System.Windows.Forms.PropertyGrid PropertyGrid
        {
            get => base.PropertyGrid;
            set
            {
                if (value != null)
                {
                    value.PropertySort = System.Windows.Forms.PropertySort.Categorized;
                }
                base.PropertyGrid = value;
            }
        }

        public override object Instance
        {
            get => base.Instance;
            set
            {
                base.Instance = value;
                UpdateShownProperties();
            }
        }

        private void UpdateShownProperties() {/*eventually include/exclude?*/}
    }
}


text:
package org.wso2.carbon.security.sts.service.util;

import java.io.Serializable;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;

/**
 * Trusted service information
 */
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class TrustedServiceData implements Serializable {

    private static final long serialVersionUID = 8180341106812151691L;

    private String serviceAddress;
    private String certAlias;

    /**
     * Create a new data instance with the service address and cert alias
     *
     * @param serviceAddress Address of the trusted service
     * @param certAlias      Alias of the cert of the service
     */
    public TrustedServiceData(String serviceAddress, String certAlias) {

        this.serviceAddress = serviceAddress;
        this.certAlias = certAlias;
    }

    public TrustedServiceData() {

    }

    public String getServiceAddress() {

        return serviceAddress;
    }

    public String getCertAlias() {

        return certAlias;
    }

}


text:
Guard plugin for Processing.
Automatically run sketch when files are modified.

## Installation

Add this line to your application's Gemfile:

    gem 'guard-processing'

And then execute:

    $ bundle

Or install it yourself as:

    $ gem install guard-processing

## Usage

    $ guard init processing
    $ guard

## Contributing

1. Fork it
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create new Pull Request


text:
/** @module emberfire-utils */
import Service from 'ember-service';
import inject from 'ember-service/inject';

import FirebaseUi from 'firebaseui';
import firebase from 'firebase';

/**
 * This is a service for FirebaseUI
 *
 * @class FirebaseUi
 * @namespace Service
 * @extends Ember.Service
 */
export default Service.extend({
  /**
   * @type Ember.Service
   * @readonly
   */
  firebaseApp: inject(),

  /**
   * @type {FirebaseUi}
   * @readonly
   */
  ui: null,

  /**
   * Service hook
   *
   * - Sets the global firebase variable
   */
  init() {
    this._super(...arguments);

    // Workaround for when the firebase asset is an AMD module
    window.firebase = firebase;
  },

  /**
   * Starts the FirebaseUI Auth
   *
   * @param {Object} uiConfig
   */
  startAuthUi(uiConfig) {
    let auth = this.get('firebaseApp').auth();
    let ui = this.get('ui');

    if (!ui) {
      ui = new FirebaseUi.auth.AuthUI(auth);
      this.set('ui', ui);
    }

    ui.start('#firebaseui-auth-container', uiConfig);
  },

  /**
   * Resets the FirebaseUI Auth
   */
  resetAuthUi() {
    this.get('ui').reset();
  },
});


text:
![](design/math.jpg)

## DeckRocket turns your iPhone into a remote for [Deckset](http://decksetapp.com) presentations

![](demo.gif)

## Requirements

DeckRocket is built in Swift and relies on Multipeer Connectivity on both OS X
and iOS. Xcode 8, OS X 10.10 (and up) and iOS 8 (and up) are all required to
build, install and use DeckRocket.

## Usage

1. Make sure you meet the requirements listed above.
2. Run `git submodule update --init`
2. Build and run both the "Mac" and "iOS" schemes in the `DeckRocket.xcodeproj`
   Xcode project. You should see a :rocket: icon in your menu bar.
3. Open a presentation in Deckset on your Mac.
4. Click the DeckRocket menu bar icon and select "Send Slides".

From there, swipe on your phone to control your Deckset slides, tap the screen
to toggle between current slide and notes view, and finally: keep an eye on the
color of the border!

Red means the connection was lost. Green means everything should work!

A connection should be established between the Mac and iOS apps within a few
seconds. You'll then be able to swipe through your slides and see Deckset
navigate to them fairly instantly.

The magic of Multipeer Connectivity should allow this to work even if devices
have no Internet connectivity and aren't even on the same WiFi network. But they
must both have either Bluetooth or WiFi turned on.

## License

This project is MIT licensed and was developed independently from Deckset and
Unsigned Integer (but those guys are great!).


text:
package org.apache.felix.dm.test.bundle.annotation.extraproperties;

import java.util.HashMap;
import java.util.Map;

import org.apache.felix.dm.annotation.api.Component;
import org.apache.felix.dm.annotation.api.Property;
import org.apache.felix.dm.annotation.api.ServiceDependency;
import org.apache.felix.dm.annotation.api.Start;
import org.apache.felix.dm.test.bundle.annotation.sequencer.Sequencer;

/**
 * This test validates that a basic Service may specify some extra service properties
 * from it's start callback
 */
public class ExtraServiceProperties
{
    public interface Provider
    {
    }

    @Component(properties={@Property(name="foo", value="bar")})
    public static class ProviderImpl implements Provider
    {
        @Start
        Map<String, String> start()
        {
            return new HashMap<String, String>() {{ put("foo2", "bar2"); }};
        }
    }

    @Component
    public static class Consumer
    {
        @ServiceDependency(filter="(test=ExtraServiceProperties)")
        Sequencer m_sequencer;

        private Map m_properties;

        @ServiceDependency
        void bindProvider(Map properties, Provider m_provider)
        {
            m_properties = properties;
        }

        @Start
        void start()
        {
            System.out.println("provider service properties: " + m_properties);
            if ("bar".equals(m_properties.get("foo")))
            {
                m_sequencer.step(1);
            }

            if ("bar2".equals(m_properties.get("foo2")))
            {
                m_sequencer.step(2);
            }
        }
    }
}


text:
#pragma warning (disable: 4786)

#include <stdio.h>
#include "Token.h"

#include <map>
#include <sstream>

#include <iostream>

using std::ostringstream;
using std::ostream;
using std::endl;

/* This function is more of a convenience than
   anything; for debugging purposes and intelligent
   error messages we'd like to be returning something
   other than "token #2843" for human-readable output;
   this lookup table solves that.

   If you add tokens, simply add them to this table
   with
     tokenNames[ MY_TOKEN_NAME ] = "string representation";
*/
string getNameForToken( const SYMBOL kind )
{
  static std::map<int, string> tokenNames;

  if( tokenNames.empty() )
  {
    tokenNames[ EOFSYM ]            = "EOF";
    tokenNames[ SBT_RAYTRACER ]     = "SBT-raytracer";
    tokenNames[ IDENT ]             = "Identifier";
    tokenNames[ SCALAR ]            = "Scalar";
    tokenNames[ SYMTRUE ]              = "true";
    tokenNames[ SYMFALSE ]             = "false";
    tokenNames[ LPAREN ]            = "Left paren";
    tokenNames[ RPAREN ]            = "Right paren";
    tokenNames[ LBRACE ]            = "Left brace";
    tokenNames[ RBRACE ]            = "Right brace";
    tokenNames[ COMMA ]             = "Comma";
    tokenNames[ EQUALS ]            = "Equals";
    tokenNames[ SEMICOLON ]         = "Semicolon";
    tokenNames[ CAMERA ]            = "camera";
	tokenNames[ AMBIENT_LIGHT ]     = "ambient_light";
    tokenNames[ POINT_LIGHT ]       = "point_light";
    tokenNames[ DIRECTIONAL_LIGHT ] = "directional_light";
    tokenNames[ CONSTANT_ATTENUATION_COEFF ] = "constant_attenuation_coeff";
    tokenNames[ LINEAR_ATTENUATION_COEFF ] = "linear_attenuation_coeff";
    tokenNames[ QUADRATIC_ATTENUATION_COEFF ] = "quadratic_attenuation_coeff";
    tokenNames[ SPHERE ]            = "sphere";
    tokenNames[ BOX ]               = "box";
    tokenNames[ SQUARE ]            = "square";
    tokenNames[ CYLINDER ]          = "cylinder";
    tokenNames[ CONE ]              = "cone";
    tokenNames[ TRIMESH ]           = "trimesh";
    tokenNames[ POSITION ]          = "position";
    tokenNames[ VIEWDIR ]           = "viewdir";
    tokenNames[ UPDIR ]             = "updir";
    tokenNames[ ASPECTRATIO ]       = "aspectratio";
    tokenNames[ COLOR ]             = "color";
    tokenNames[ DIRECTION ]         = "direction";
    tokenNames[ CAPPED ]            = "capped";
    tokenNames[ HEIGHT ]            = "height";
    tokenNames[ BOTTOM_RADIUS ]     = "bottom_radius";
    tokenNames[ TOP_RADIUS ]        = "top_radius";
    tokenNames[ QUATERNIAN ]        = "quaternian";
    tokenNames[ POLYPOINTS ]            = "points";
    tokenNames[ HEIGHT ]            = "height";
    tokenNames[ NORMALS ]           = "normals";
    tokenNames[ MATERIALS ]         = "materials";
    tokenNames[ FACES ]             = "faces";
    tokenNames[ TRANSLATE ]         = "translate";
    tokenNames[ SCALE ]             = "scale";
    tokenNames[ ROTATE ]            = "rotate";
    tokenNames[ TRANSFORM ]         = "transform";
    tokenNames[ MATERIAL ]          = "material";
    tokenNames[ EMISSIVE ]          = "emissive";
    tokenNames[ AMBIENT ]           = "ambient";
    tokenNames[ SPECULAR ]          = "specular";
    tokenNames[ REFLECTIVE ]        = "reflective";
    tokenNames[ DIFFUSE ]           = "diffuse";
    tokenNames[ TRANSMISSIVE ]      = "transmissive";
    tokenNames[ SHININESS ]         = "shininess";
    tokenNames[ INDEX ]             = "index";
    tokenNames[ NAME ]              = "name";
    tokenNames[ MAP ]               = "map";
    tokenNames[ OBJFILE ]           = "objfile";
    tokenNames[ OBJGROUP ]          = "objgroup";
  }
  // search tokenNames table
  std::map<int, string>::const_iterator itr =
    tokenNames.find( kind );
  if( itr == tokenNames.end() )
    return string("Unknown token type");
  else
    return (*itr).second;

}

/* This function is used by the parser to lookup
   "reserved" words (i.e., things like "sphere", "cone",
   etc.).  What you will be concerned with is adding
   entries to the reservedWords map as appropriate;
   if you add a new reserved word to the parser,
   simply add it to the list below.  I.e., if you had
   the reserved word "regular17gon" as your new primitive,
   for example, and the SYMBOL representing it was
   "SEVENTEENGON", you'd add the line
      reservedWords["regular17gon"] = SEVENTEENGON;
   to the list below.
*/
SYMBOL lookupReservedWord(const string& ident) {
  static std::map<string, SYMBOL> reservedWords;

  if( reservedWords.empty() )
  {
    reservedWords["ambient_light"] = AMBIENT_LIGHT;
    reservedWords["ambient"] = AMBIENT;
    reservedWords["aspectratio"] = ASPECTRATIO;
    reservedWords["bottom_radius"] = BOTTOM_RADIUS;
    reservedWords["box"] = BOX;
    reservedWords["camera"] = CAMERA;
    reservedWords["capped"] = CAPPED;
    reservedWords["color"] = COLOR;
    reservedWords["colour"] = COLOR;
    reservedWords["cone"] = CONE;
    reservedWords["constant_attenuation_coeff"] = CONSTANT_ATTENUATION_COEFF;
    reservedWords["cylinder"] = CYLINDER;
    reservedWords["diffuse"] = DIFFUSE;
    reservedWords["direction"] = DIRECTION;
    reservedWords["directional_light"] = DIRECTIONAL_LIGHT;
    reservedWords["emissive"] = EMISSIVE;
    reservedWords["faces"] = FACES;
    reservedWords["false"] = SYMFALSE;
    reservedWords["fov"] = FOV;
    reservedWords["gennormals"] = GENNORMALS;
    reservedWords["height"] = HEIGHT;
    reservedWords["index"] = INDEX;
    reservedWords["linear_attenuation_coeff"] = LINEAR_ATTENUATION_COEFF;
    reservedWords["material"] = MATERIAL;
    reservedWords["materials"] = MATERIALS;
    reservedWords["map"] = MAP;
    reservedWords["name"] = NAME;
    reservedWords["normals"] = NORMALS;
    reservedWords["point_light"] = POINT_LIGHT;
    reservedWords["points"] = POLYPOINTS;
    reservedWords["polymesh"] = TRIMESH;
    reservedWords["position"] = POSITION;
    reservedWords["quadratic_attenuation_coeff"] = QUADRATIC_ATTENUATION_COEFF;
    reservedWords["quaternian"] = QUATERNIAN;
    reservedWords["reflective"] = REFLECTIVE;
    reservedWords["rotate"] = ROTATE;
    reservedWords["SBT-raytracer"] = SBT_RAYTRACER;
    reservedWords["scale"] = SCALE;
    reservedWords["shininess"] = SHININESS;
    reservedWords["specular"] = SPECULAR;
    reservedWords["sphere"] = SPHERE;
    reservedWords["square"] = SQUARE;
    reservedWords["top_radius"] = TOP_RADIUS;
    reservedWords["transform"] = TRANSFORM;
    reservedWords["translate"] = TRANSLATE;
    reservedWords["transmissive"] = TRANSMISSIVE;
    reservedWords["trimesh"] = TRIMESH;
    reservedWords["true"] = SYMTRUE;
    reservedWords["updir"] = UPDIR;
    reservedWords["viewdir"] = VIEWDIR;
    reservedWords[ "objfile" ]           = OBJFILE ;
    reservedWords[ "objgroup" ]          = OBJGROUP ;

  }

  // search ReservedWords table
  std::map<string, SYMBOL>::const_iterator itr =
    reservedWords.find( ident );
  if( itr == reservedWords.end() )
    return UNKNOWN;
  else
    return (*itr).second;
}

string Token::toString() const
{
  return getNameForToken( kind() );
}

void Token::Print( ostream& out ) const {
  out << toString();
}

void Token::Print( ) const {
  Print( std::cout );
}

string IdentToken::toString( ) const {
  ostringstream oss( Token::toString() );
  oss << ": \"" << _ident << "\"";
  return oss.str();
}

string ScalarToken::toString( ) const {
  ostringstream oss( Token::toString() );
  oss << ": " << _value;
  return oss.str();
}


text:
layout: page
permalink: /motion-invariant/
mathjax: true
---
## Motion-invariant photography

**Motivation**
Scenes with moving objects are difficult to image especially with high
exposure due to motion blur. One option is to segment the image into
different regions based on moving objects and deblur each of them
individually. But this method may lead to artifacts in the edges
between objects (if at all, segmentation is perfect). How to do away
with the segmentation and space-variant deblurring?

**Track objects**
If the blur is space-invariant, then the deblurring will output better
images that that of space-variant. If we keep the camera static in a
dynamic scene, the blur will always be space-variant (assuming
different objects move with different velocities). The important
observation to make here is that the background will appear clean in
this case, since its velocity is zero. In other words, the camera is
tracking the background (since both their velocities are equal, yes,
zero). If we move the camera with a velocity \\(v\\) in a dynamic
scene, then objects moving with velocity \\(v\\) will appear
clean. Thus, if we could track all objects within a single exposure
time, it would be imaged clean at some point in the exposure. But,
what is its use?

**Make it space-invariant**
Consider you are looking at a road with many vehicles. The road will
look clean to your eyes, and the fast moving cars will look
blurred. Now, shake your head fast, left and right continuously. Now,
the road also will look blurred in addition to cars. But, the blur is
same for all objects and the road. That is, if you want to deblur
easily, blur more. Counter-intuitive?!

**Sweeping the camera**
If we know the range of possible velocities of objects in the scene,
say \\([-v_max,v_max\\]), then we can sweep the camera through all
these velocities during a single exposure time. This would create a
space-invarnt blurred image

//explain more//


text:
set -eu
export LC_ALL='C'

main() {
	source="${1:?}"
	target="${2:?}"
	hblock="${3:-hblock}"

	export HBLOCK_HEADER=''
	export HBLOCK_FOOTER=''
	export HBLOCK_SOURCES="file://${source:?}"
	export HBLOCK_ALLOWLIST=''
	export HBLOCK_DENYLIST='hblock-check.molinero.dev'

	export HBLOCK_REDIRECTION=''
	export HBLOCK_WRAP='1'
	export HBLOCK_TEMPLATE='local-zone: "%D" always_nxdomain'
	export HBLOCK_COMMENT='#'

	export HBLOCK_LENIENT='false'
	export HBLOCK_REGEX='false'
	export HBLOCK_FILTER_SUBDOMAINS='true'
	export HBLOCK_CONTINUE='false'

	"${hblock:?}" -qO "${target:?}"
}

main "${@-}"


text:
jQuery.fn.highlight = function(start,end) {
 function innerHighlight(node, start, end) {
  var skip = 0;

  if (node.nodeType == 3) {
   if (start >= 0 && start < node.data.length && end >= 0 && end <= node.data.length) {
    var spannode = document.createElement('span');

	spannode.className = 'highlight';
    var middlebit = node.splitText(start);
    var endbit = middlebit.splitText(end-start)
    var middleclone = middlebit.cloneNode(true);
    spannode.appendChild(middleclone);
    middlebit.parentNode.replaceChild(spannode, middlebit);
    skip = 1;
   }
  }
  else if (node.nodeType == 1 && node.childNodes && !/(script|style)/i.test(node.tagName)) {
    innerHighlight(node.childNodes[0], start, end);
  }
  return skip;
 }
 return this.each(function() {
  innerHighlight(this, start, end);
 });
};

jQuery.fn.removeHighlight = function() {
	console.log('remove')
 return this.find("span.highlight").each(function() {
  this.parentNode.firstChild.nodeName;
  with (this.parentNode) {
   replaceChild(this.firstChild, this);
   normalize();
  }
 }).end();
};

Highlight = {}
Highlight.highlight = function(node, start, end, options){

	if (node.nodeType == 3) {

	   if (start >= 0 && start < node.data.length && end >= 0 && end <= node.data.length) {
	    var spannode = document.createElement('span');
	    spannode.className = options.highlightClass + ' highlight';
	    var middlebit = node.splitText(start);

		var endbit = middlebit.splitText(end-start)

		var middleclone = middlebit.cloneNode(true);

			spannode.appendChild(middleclone);

	    middlebit.parentNode.replaceChild(spannode, middlebit);
	   }
	 }

}

Highlight.removeHighlight = function(node) {

 jQuery(node).find("span.highlight").each(function() {

  this.parentNode.firstChild.nodeName;
  with (this.parentNode) {
   replaceChild(this.firstChild, this);
   normalize();
  }
 });
};


text:
    <title>Hello World Guestbook</title>
    <link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css"/>
    <meta charset="utf-8"></meta>
    <meta name="viewport" content="width=device-width, initial-scale=1"></meta>

            <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
                Toggle navigation

            </button>
            Guestbook

Home

        <form action="/greet" method="post">
            Your name:<input type="text" name="name" th:value="${name}"/>
            Message:<input type="text" name="message"/>
            <input type="submit" value="Greet!"/>
        </form>

        Greeting

            Username
            Message


text:
package gnu.kawa.reflect;
import gnu.bytecode.*;
import gnu.mapping.*;
import gnu.mapping.Location;  // As opposed to gnu.bytecode.Location.
import gnu.expr.*;

public class FieldLocation extends ClassMemberLocation
{
  Declaration decl;
  /** The cached location of the field, if final.
   * This is the value of this Location.  Howeve, if INDIRECT_LOCATION is
   * set and CONSTANT is cleared, then we need to do an extra indirection. */
  Object value;
  static final int SETUP_DONE = 1; // FIXME - do we still need this?

  /** Flag that indicates that field value has type Location.
   * Hence get of this Location requires an extra indirection. */
  static final int INDIRECT_LOCATION = 2;
  /** The actual value (following any indirection) is constant.
   * I.e. if INDIRECT_LOCATION is set, then that Location has isConstant set,
   * Otherwise the actual value is a final field. */
  static final int CONSTANT = 4;
  /** Flag that indicates that the value field has been set.
   * If INDIRECT_LOCATION has been set, but not CONSTANT, then
   * the value is a Location we need to indirect.
   * If CONSTANT is set, then this is the actual (final) value.
   * Not set unless at least one of INDIRECT_LOCATION or CONSTANT are set. */
  static final int VALUE_SET = 8;
  // The PROCEDURE and SYNTAX flags aren't current used by getDeclaration,
  // but probably should be, assuming we can count on them.
  public static final int PROCEDURE = 16;
  public static final int SYNTAX = 32;
  /** True if the flags PROCEDURE|SYNTAX|INDIRECT_LOCATION|CONSTANT
   * are valid. */
  public static final int KIND_FLAGS_SET = 64;
  private int flags;

  public boolean isIndirectLocation ()
  { return (flags & INDIRECT_LOCATION) != 0; }

  public void setProcedure ()
  {
    flags |= PROCEDURE|CONSTANT|KIND_FLAGS_SET;
  }

  public void setSyntax ()
  {
    flags |= SYNTAX|CONSTANT|KIND_FLAGS_SET;
  }

  void setKindFlags ()
  {
    String fname = getMemberName();
    gnu.bytecode.Field fld = getDeclaringClass().getDeclaredField(fname);
    int fflags = fld.getModifiers();
    Type ftype = fld.getType();
    if (ftype.isSubtype(Compilation.typeLocation))
      flags |= INDIRECT_LOCATION;
    if ((fflags & Access.FINAL) != 0)
      {
        if ((flags & INDIRECT_LOCATION) == 0)
          {
            flags |= CONSTANT;
            if (ftype.isSubtype(Compilation.typeProcedure))
              flags |= PROCEDURE;
            if (ftype instanceof ClassType
                && ((ClassType) ftype).isSubclass("kawa.lang.Syntax"))
              flags |= SYNTAX;
          }
        else
          {
            Location loc = (Location) getFieldValue();
            if (loc instanceof FieldLocation)
              {
                FieldLocation floc = (FieldLocation) loc;
                if ((floc.flags & KIND_FLAGS_SET) == 0)
                  floc.setKindFlags();
                flags |= (floc.flags & (SYNTAX|PROCEDURE|CONSTANT));
                if ((floc.flags & CONSTANT) != 0)
                  {
                    if ((floc.flags & VALUE_SET) != 0)
                      {
                        value = floc.value;
                        flags |= VALUE_SET;
                      }
                  }
                else
                  {
                    value = floc;
                    flags |= VALUE_SET;
                  }
              }
            else if (loc.isConstant())
              {
                Object val = loc.get(null);
                // if (val == null) ????;
                if (val instanceof Procedure)
                  flags |= PROCEDURE;
                if (val instanceof kawa.lang.Syntax) // FIXME
                  flags |= SYNTAX;
                flags |= CONSTANT|VALUE_SET;
                value = val;
              }
          }
      }
    flags |= KIND_FLAGS_SET;
  }

  public boolean isProcedureOrSyntax ()
  {
    if ((flags & KIND_FLAGS_SET) == 0)
      setKindFlags();
    return (flags & (PROCEDURE+SYNTAX)) != 0;
  }

  public FieldLocation(Object instance, String cname, String fname)
  {
    super(instance, ClassType.make(cname), fname);
  }

  public FieldLocation(Object instance, ClassType type, String mname)
  {
    super(instance, type, mname);
  }

  public FieldLocation (Object instance, java.lang.reflect.Field field)
  {
    super(instance, field);
    type = (ClassType) Type.make(field.getDeclaringClass());
  }

  public void setDeclaration (Declaration decl)
  {
    this.decl = decl;
  }

  public Field getField ()
  {
    return type.getDeclaredField(mname);
  }

  /** Get the type of the field. */
  public Type getFType ()
  {
    return type.getDeclaredField(mname).getType();
  }

  public synchronized Declaration getDeclaration ()
  {
    if ((flags & KIND_FLAGS_SET) == 0)
      setKindFlags();
    Declaration d = decl;
    if (d == null)
      {
	String fname = getMemberName();
	ClassType t = getDeclaringClass();
	gnu.bytecode.Field procField = t.getDeclaredField(fname);
	if (procField == null)
	  return null;
        ModuleInfo info = ModuleInfo.find(t);
        ModuleExp mexp = info.getModuleExp();
        for (d = mexp.firstDecl();  d != null; d = d.nextDecl())
          {
            if (d.field != null && d.field.getName().equals(fname))
              break;
          }
        if (d == null)
          throw new RuntimeException("no field found for "+this);
        decl = d;
      }
    return d;
  }

  void setup ()
  {
    synchronized (this)
      {
	if ((flags & SETUP_DONE) != 0)
	  return;
	super.setup();
        if ((flags & KIND_FLAGS_SET) == 0)
          setKindFlags();
        flags |= SETUP_DONE;
      }
  }

  public Object get (Object defaultValue)
  {
    try
      {
        setup();
      }
    catch (Throwable ex)
      {
        return defaultValue;
      }
    Object v;
    if ((flags & VALUE_SET) != 0)
      {
        v = value;
        if ((flags & CONSTANT) != 0)
          return v;
      }
    else
      {
	v = getFieldValue();
	if ((type.getDeclaredField(mname).getModifiers() & Access.FINAL) != 0)
	  {
	    flags |= VALUE_SET;
	    if ((flags & INDIRECT_LOCATION) == 0)
              flags |= CONSTANT;
	    value = v;
	  }
      }
    if ((flags & INDIRECT_LOCATION) != 0)
      {
	Object unb = Location.UNBOUND;
	Location loc = (Location) v;
	v = loc.get(unb);
	if (v == unb)
	  return defaultValue;
	if (loc.isConstant())
	  {
	    flags |= CONSTANT;
	    value = v;
	  }
      }
    return v;
  }

  private Object getFieldValue ()
  {
    super.setup(); // Set rfield, if needed.
    try
      {
	return rfield.get(instance);
      }
    catch (Throwable ex)
      {
	throw WrappedException.wrapIfNeeded(ex);
      }
  }

  public void set (Object newValue)
  {
    setup();
    if ((flags & INDIRECT_LOCATION) == 0)
      {
	try
	  {
	    rfield.set(instance, newValue);
	  }
	catch (Throwable ex)
	  {
	    throw WrappedException.wrapIfNeeded(ex);
	  }
      }
    else
      {
	Object v;
	if ((flags & VALUE_SET) != 0)
	  v = value;
	else
	  {
	    flags |= VALUE_SET;
	    v = getFieldValue();
	    value = v;
	  }
	((Location) v).set(newValue);
      }
  }

  public Object setWithSave (Object newValue)
  {
    if ((flags & KIND_FLAGS_SET) == 0)
      setKindFlags();
    if ((flags & INDIRECT_LOCATION) == 0)
      return super.setWithSave(newValue);
    else
      {
	Object v;
	if ((flags & VALUE_SET) != 0)
	  v = value;
	else
	  {
	    flags |= VALUE_SET;
	    v = getFieldValue();
	    value = v;
	  }
	return ((Location) v).setWithSave(newValue);
      }
  }

  public void setRestore (Object oldValue)
  {
    if ((flags & INDIRECT_LOCATION) == 0)
      super.setRestore(oldValue);
    else
      ((Location) value).setRestore(oldValue);
  }

  public boolean isConstant ()
  {
    if ((flags & KIND_FLAGS_SET) == 0)
      setKindFlags();
    if ((flags & CONSTANT) != 0)
      return true;
    if (isIndirectLocation())
      {
	Object v;
	if ((flags & VALUE_SET) != 0)
	  v = value;
	else
	  {
            try
              {
                setup();
              }
            catch (Throwable ex)
              {
                return false;
              }
	    v = getFieldValue();
	    flags |= VALUE_SET;
	    value = v;
	  }
	return ((Location) v).isConstant();
      }
    return false;
  }

  public boolean isBound ()
  {
    if ((flags & KIND_FLAGS_SET) == 0)
      setKindFlags();
    if ((flags & CONSTANT) != 0 || (flags & INDIRECT_LOCATION) == 0)
      return true;
    Object v;
    if ((flags & VALUE_SET) != 0)
      v = value;
    else
      {
        try
          {
            setup();
          }
        catch (Throwable ex)
          {
            return false;
          }
	v = getFieldValue();
	flags |= VALUE_SET;
	value = v;
      }
    return ((Location) v).isBound();
  }

  public static FieldLocation make (Object instance, Declaration decl)
  {
    gnu.bytecode.Field fld = decl.field;
    ClassType ctype = fld.getDeclaringClass();
    FieldLocation loc = new FieldLocation(instance, ctype, fld.getName());
    loc.setDeclaration(decl);
    //maybe setKindFlags();
    return loc;
  }

  public static FieldLocation make (/*Object name,*/ Object instance, String cname, String fldName)
  {
    return new FieldLocation(/*name,*/ instance, ClassType.make(cname), fldName);
  }

  public String toString()
  {
    StringBuffer sbuf = new StringBuffer();
    sbuf.append("FieldLocation[");
    if (instance != null)
      {
	sbuf.append(instance);
	sbuf.append(' ');
      }
    sbuf.append(type == null ? "(null)" : type.getName());
    sbuf.append('.');
    sbuf.append(mname);
    /* DEBUGGING:
    sbuf.append(" #:");
    sbuf.append(id);
    */
    sbuf.append(']');
    return sbuf.toString();
  }
}


text:
import {BotListener} from "timbot2/lib/BotListener";

export class Pizza extends BotListener {
  name = "Pizza";
  desc = "Mmmm, pizza"
  hidden = true;
  active = true;

  channels = ['direct_message','direct_mention','mention','ambient'];

  start() {
    this.controller.hears('pizza', this.channels, function(bot,message) {
      // use from BotListener
      this.reply(bot, message, "pizza? I want pizza");

    // to use reply
    }.bind(this));
  }
}


text:
module ValidationScenarios
  module ActiveRecordExtensions
    def self.included(base)
      base.class_eval <<-IN_THE_EVAL
        include ValidationScenarios::With
        include InstanceMethods
      IN_THE_EVAL
    end

    module InstanceMethods
      def save_in_scenario(*args)
        # don't want to mess around with ar#save signature
        scenario = args.pop
        with_scenario(scenario) do
          save(args)
        end
      end

      def save_in_scenario!(scenario)
        with_scenario(scenario) do
          save!
        end
      end
    end
  end
end


text:
@interface PodsDummy_Pods_IJMRandomName : NSObject
@end
@implementation PodsDummy_Pods_IJMRandomName
@end


text:
using System;
using System.Reflection;
using System.Threading.Tasks;
using System.Runtime.InteropServices;

namespace RemoteExecutorConsoleApp
{
    /// <summary>
    /// Provides an entry point in a new process that will load a specified method and invoke it.
    /// </summary>
    internal static class Program
    {
        private static int Main(string[] args)
        {
            // The program expects to be passed the target assembly name to load, the type
            // from that assembly to find, and the method from that assembly to invoke.
            // Any additional arguments are passed as strings to the method.
            if (args.Length < 3)
            {
                Console.Error.WriteLine("Usage: {0} assemblyName typeName methodName", typeof(Program).GetTypeInfo().Assembly.GetName().Name);
                Environment.Exit(-1);
                return -1;
            }

            string assemblyName = args[0];
            string typeName = args[1];
            string methodName = args[2];
            string[] additionalArgs = args.Length > 3 ?
                args.Subarray(3, args.Length - 3) :
                Array.Empty<string>();

            // Load the specified assembly, type, and method, then invoke the method.
            // The program's exit code is the return value of the invoked method.
            Assembly a = null;
            Type t = null;
            MethodInfo mi = null;
            object instance = null;
            int exitCode;
            try
            {
                // Create the test class if necessary
                a = Assembly.Load(new AssemblyName(assemblyName));
                t = a.GetType(typeName);
                mi = t.GetTypeInfo().GetDeclaredMethod(methodName);
                if (!mi.IsStatic)
                {
                    instance = Activator.CreateInstance(t);
                }

                // Invoke the test
                object result = mi.Invoke(instance, additionalArgs);
                exitCode = result is Task<int> task ?
                    task.GetAwaiter().GetResult() :
                    (int)result;
            }
            catch (Exception exc)
            {
                Console.Error.WriteLine("Exception from RemoteExecutorConsoleApp({0}):", string.Join(", ", args));
                Console.Error.WriteLine("Assembly: {0}", a);
                Console.Error.WriteLine("Type: {0}", t);
                Console.Error.WriteLine("Method: {0}", mi);
                Console.Error.WriteLine("Exception: {0}", exc);
                throw exc;
            }
            finally
            {
                (instance as IDisposable)?.Dispose();
            }

            // Environment.Exit not supported on .Net Native - don't even call it to avoid the nuisance exception.
            if (!RuntimeInformation.FrameworkDescription.StartsWith(".NET Native", StringComparison.OrdinalIgnoreCase))
            {
                // Use Exit rather than simply returning the exit code so that we forcibly shut down
                // the process even if there are foreground threads created by the operation that would
                // end up keeping the process alive potentially indefinitely.
                try
                {
                    Environment.Exit(exitCode);
                }
                catch (PlatformNotSupportedException)
                {
                }
            }
            return exitCode;
        }

        private static MethodInfo GetMethod(this Type type, string methodName)
        {
            Type t = type;
            while (t != null)
            {
                TypeInfo ti = t.GetTypeInfo();
                MethodInfo mi = ti.GetDeclaredMethod(methodName);
                if (mi != null)
                {
                    return mi;
                }
                t = ti.BaseType;
            }
            return null;
        }

        private static T[] Subarray<T>(this T[] arr, int offset, int count)
        {
            var newArr = new T[count];
            Array.Copy(arr, offset, newArr, 0, count);
            return newArr;
        }
    }
}