text:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <title>Secondary Database Example</title>
    <link rel="stylesheet" href="gettingStarted.css" type="text/css" />
    <meta name="generator" content="DocBook XSL Stylesheets V1.73.2" />
    <link rel="start" href="index.html" title="Getting Started with Berkeley DB" />
    <link rel="up" href="indexes.html" title="Chapter 5. Secondary Databases" />
    <link rel="prev" href="joins.html" title="Database Joins" />
    <link rel="next" href="dbconfig.html" title="Chapter 6. Database Configuration" />

Library Version 11.2.5.3

          Secondary Database Example

          Prev
          Chapter 5. Secondary Databases
           Next

Secondary Database Example

              Secondary Databases with example_database_load

              Secondary Databases with example_database_read

        In previous chapters in this book, we built applications that load
        and display several DB databases. In this example, we will extend those
        examples to use secondary databases. Specifically:

            In

                Database Usage Example
            we built an application that can open and load data into several databases.
            In Secondary Databases with example_database_load we will extend
            that application to also open a secondary database for the purpose
            of indexing inventory item names.

            In Cursor Example we
            built an application to display our inventory database (and related
            vendor information). In
            Secondary Databases with example_database_read
            we will extend that application to
            show inventory records based on the index we cause to be loaded using
            example_database_load.

Secondary Databases with example_database_load

            In order to update example_database_load
            to maintain an index of inventory item names, all we really need
            to do is:

                    Create a new database to be used as a secondary database.

                    Associate our new database to the inventory primary
                    database.

            We also need a function that can create our secondary keys for us.

            Because DB maintains secondary databases for us; once this work
            is done we need not make any other changes to example_database_load.

            Remember that you can find the complete implementation of these functions
            in:

DB_INSTALL/examples_cxx/getting_started

            where DB_INSTALL is the location where you
            placed your DB distribution.

            To begin, we go to gettingStartedCommon.hpp and
            we write our secondary key extractor function. This is a fairly
            trivial function to write because we have already done most of the
            work when we wrote the InventoryData class.
            Recall that when we wrote that class, we provided a constructor that
            accepts a pointer to a buffer and unpacks the contents of the buffer
            for us (see InventoryData Class
            for the implementation). We now make use of that constructor.

// File: gettingStartedCommon.hpp
// Forward declarations
class Db;
class Dbt;

// Used to extract an inventory item's name from an
// inventory database record. This function is used to create
// keys for secondary database records.
int
get_item_name(Db *dbp, const Dbt *pkey, const Dbt *pdata, Dbt *skey)
{
    // Obtain the buffer location where the we placed the item's name. In
    // this example, the item's name is located in the primary data. It is
    // the first string in the buffer after the price (a double) and
    // the quantity (a long).
    size_t offset = sizeof(double) + sizeof(long);
    char * itemname = (char *)pdata->get_data() + offset;

    // unused
    (void)pkey;

    // If the offset is beyond the end of the data, then there is a
    // problem with the buffer contained in pdata, or there's a
    // programming error in how the buffer is marshalled/unmarshalled.
    // This should never happen!
    if (offset > pdata->get_size()) {
        dbp->errx("get_item_name: buffer sizes do not match!");
        // When we return non-zero, the index record is not
        // added/updated.
        return (-1);
    }
    // Now set the secondary key's data to be the item name

    skey->set_data(itemname);
    skey->set_size(strlen(itemname) + 1);

    return (0);
};

        Having written our key extractor callback, we now need to make
        a trivial update to our MyDb implementation.
        Because an item name is used by multiple inventory records, we need our
        secondary database to support sorted duplicates. We therefore must
        update MyDb to handle this detail.

        The MyDb class definition changes to add a
        boolean to the constructor (remember that new code is in
        bold):

// File: MyDb.hpp
#include <db_cxx.h>

class MyDb
{
public:
    // Constructor requires a path to the database,
    // and a database name.
    MyDb(std::string &path, std::string &dbName,
         bool isSecondary = false);

    // Our destructor just calls our private close method.
    ~MyDb() { close(); }

    inline Db &getDb() {return db_;}

private:
    Db db_;
    std::string dbFileName_;
    u_int32_t cFlags_;

    // Make sure the default constructor is private
    // We don't want it used.
    MyDb() : db_(0, 0) {}

    // We put our database close activity here.
    // This is called from our destructor. In
    // a more complicated example, we might want
    // to make this method public, but a private
    // method is more appropriate for this example.
    void close();
};

        And the implementation changes slightly to take advantage of the new
        boolean. Note that to save space, we just show the constructor where the
        code actually changes:

// File: MyDb.cpp
#include "MyDb.hpp"

// Class constructor. Requires a path to the location
// where the database is located, and a database name
MyDb::MyDb(std::string &path, std::string &dbName,
           bool isSecondary)
    : db_(NULL, 0),               // Instantiate Db object
      dbFileName_(path + dbName), // Database file name
      cFlags_(DB_CREATE)          // If the database doesn't yet exist,
                                  // allow it to be created.
{
    try
    {
        // Redirect debugging information to std::cerr
        db_.set_error_stream(&std::cerr);

        // If this is a secondary database, support
        // sorted duplicates
        if (isSecondary)
            db_.set_flags(DB_DUPSORT);

        // Open the database
        db_.open(NULL, dbFileName_.c_str(), NULL, DB_BTREE, cFlags_, 0);
    }
    // DbException is not a subclass of std::exception, so we
    // need to catch them both.
    catch(DbException &e)
    {
        std::cerr << "Error opening database: " << dbFileName_ << "\n";
        std::cerr << e.what() << std::endl;
    }
    catch(std::exception &e)
    {
        std::cerr << "Error opening database: " << dbFileName_ << "\n";
        std::cerr << e.what() << std::endl;
    }
}

        That done, we can now update
        example_database_load to open our new secondary
        database and associate it to the inventory database.

        To save space, we do not show the entire implementation for this program
        here. Instead, we show just the main() function,
        which is where all our modifications occur. To
        see the rest of the implementation for this command, see
          example_database_load.

// Loads the contents of vendors.txt and inventory.txt into
// Berkeley DB databases.
int
main(int argc, char *argv[])
{
    // Initialize the path to the database files
    std::string basename("./");
    std::string databaseHome("./");

    // Database names
    std::string vDbName("vendordb.db");
    std::string iDbName("inventorydb.db");
    std::string itemSDbName("itemname.sdb");

    // Parse the command line arguments here and determine
    // the location of the flat text files containing the
    // inventory data here. This step is omitted for clarity.

    //  Identify the full name for our input files, which should
    //  also include some path information.
    std::string inventoryFile = basename + "inventory.txt";
    std::string vendorFile = basename + "vendors.txt";

    try
    {
        // Open all databases.
        MyDb inventoryDB(databaseHome, iDbName);
        MyDb vendorDB(databaseHome, vDbName);
        MyDb itemnameSDB(databaseHome, itemSDbName, true);

        // Associate the primary and the secondary
        inventoryDB.getDb().associate(NULL,
                                      &(itemnameSDB.getDb()),
                                      get_item_name,
                                      0);

        // Load the vendor database
        loadVendorDB(vendorDB, vendorFile);

        // Load the inventory database
        loadInventoryDB(inventoryDB, inventoryFile);
    } catch(DbException &e) {
        std::cerr << "Error loading databases. " << std::endl;
        std::cerr << e.what() << std::endl;
        return(e.get_errno());
    } catch(std::exception &e) {
        std::cerr << "Error loading databases. " << std::endl;
        std::cerr << e.what() << std::endl;
        return(-1);
    }

    return(0);
} // End main

        Note that the order in which we instantiate our
        MyDb class instances is important. In general you
        want to close a secondary database before closing the primary with which
        it is associated. This is particularly true for multi-threaded or
        multi-processed applications where the database closes are not single
        threaded. Even so, it is a good habit to adopt, even for simple
        applications such as this one. Here, we ensure that the databases are
        closed in the desired order by opening the secondary database last.
        This works because our MyDb objects are on
        the stack, and therefore the last one opened is the first one closed.

        That completes our update to example_database_load.
        Now when this program is called, it will automatically index inventory
        items based on their names. We can then query for those items using the
        new index. We show how to do that in the next section.

Secondary Databases with example_database_read

            In Cursor Example we
            wrote an application that displays every inventory item in the
            Inventory database. In this section, we will update that example to
            allow us to search for and display an inventory item given a
            specific name. To do this, we will make use of the secondary
            database that example_database_load now
            creates.

            The update to example_database_read is
            relatively modest. We need to open the new secondary database
            in exactly the same way was we do for
            example_database_load.
            We also need to add a command line parameter on
            which we can specify the item name, and we will need a new function
            in which we will perform the query and display the results.

            To begin, we add a single forward declaration to the application,
            and update our usage function slightly:

// File: example_database_read.cpp
#include <iostream>
#include <fstream>
#include <cstdlib>

#include "MyDb.hpp"
#include "gettingStartedCommon.hpp"

// Forward declarations
int show_all_records(MyDb &inventoryDB, MyDb &vendorDB);
int show_item(MyDb &itemnameSDB, MyDb &vendorDB, std::string &itemName);
int show_vendor(MyDb &vendorDB, const char *vendor);

        Next, we update main() to
        open the new secondary database and
        accept the new command line switch.
        We also need a new variable to contain the item's name.

        The final update to the main() entails a little bit
        of logic to determine whether we want to display all available inventory
        items, or just the ones that match a name provided on the
        -i command line parameter.

// Displays all inventory items and the associated vendor record.
int
main (int argc, char *argv[])
{
    // Initialize the path to the database files
    std::string databaseHome("./");
    std::string itemName;

    // Database names
    std::string vDbName("vendordb.db");
    std::string iDbName("inventorydb.db");
    std::string itemSDbName("itemname.sdb");

    // Parse the command line arguments
    // Omitted for brevity

    try
    {
        // Open all databases.
        MyDb inventoryDB(databaseHome, iDbName);
        MyDb vendorDB(databaseHome, vDbName);
        MyDb itemnameSDB(databaseHome, itemSDbName, true);

        // Associate the secondary to the primary
        inventoryDB.getDb().associate(NULL,
                                      &(itemnameSDB.getDb()),
                                      get_item_name,
                                      0);

        if (itemName.empty())
        {
            show_all_records(inventoryDB, vendorDB);
        } else {
            show_item(itemnameSDB, vendorDB, itemName);
        }
    } catch(DbException &e) {
        std::cerr << "Error reading databases. " << std::endl;
        std::cerr << e.what() << std::endl;
        return(e.get_errno());
    } catch(std::exception &e) {
        std::cerr << "Error reading databases. " << std::endl;
        std::cerr << e.what() << std::endl;
        return(-1);
    }

    return(0);
} // End main

        The only other thing that we need to add to the application is the
        implementation of the

            show_item()
        function.

Note

            In the interest of space, we refrain from showing the other
            functions used by this application. For their implementation, please
            see Cursor Example.
            Alternatively, you can see the entire implementation of this
            application
            in:

DB_INSTALL/examples_cxx/getting_started

            where DB_INSTALL is the location where you
            placed your DB distribution.

// Shows the records in the inventory database that
// have a specific item name. For each inventory record
// shown, the appropriate vendor record is also displayed.
int
show_item(MyDb &itemnameSDB, MyDb &vendorDB, std::string &itemName)
{
    // Get a cursor to the itemname secondary db
    Dbc *cursorp;

    try {
        itemnameSDB.getDb().cursor(NULL, &cursorp, 0);

        // Get the search key. This is the name on the inventory
        // record that we want to examine.
        std::cout << "Looking for " << itemName << std::endl;
        Dbt key((void *)itemName.c_str(), itemName.length() + 1);
        Dbt data;

        // Position the cursor to the first record in the secondary
        // database that has the appropriate key.
        int ret = cursorp->get(&key, &data, DB_SET);
        if (!ret) {
            do {
                InventoryData inventoryItem(data.get_data());
                inventoryItem.show();

                show_vendor(vendorDB, inventoryItem.getVendor().c_str());

            } while(cursorp->get(&key, &data, DB_NEXT_DUP) == 0);
        } else {
            std::cerr << "No records found for '" << itemName
                      << "'" << std::endl;
        }
    } catch(DbException &e) {
        itemnameSDB.getDb().err(e.get_errno(), "Error in show_item");
        cursorp->close();
        throw e;
    } catch(std::exception &e) {
        itemnameSDB.getDb().errx("Error in show_item: %s", e.what());
        cursorp->close();
        throw e;
    }

    cursorp->close();
    return (0);
}

        This completes our update to
        example_inventory_read. Using this update, you
        can now search for and show all inventory items that match a particular
        name. For example:

    example_inventory_read -i "Zulu Nut"

          Prev

            Up

           Next

          Database Joins

            Home

           Chapter 6. Database Configuration


text:
"""
Base class for implementing digital modulation; contains `Modulation` class.

Revision Info
=============
* $LastChangedBy: mandke $
* $LastChangedDate: 2010-10-19 16:34:02 -0500 (Tue, 19 Oct 2010) $
* $LastChangedRevision: 4811 $

:author: Ketan Mandke <kmandke@mail.utexas.edu>

:copyright:
    Copyright 2009 The University of Texas at Austin

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

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

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.
"""
__docformat__ = "restructuredtext en"

from wins.trace import Traceable
from scapy.all import Packet

class Modulation(Traceable):
    """Abstract base class for implementing digital modulation.

    Concrete subclasses must implement the `ber()` method.
    """
    name = "modulation"
    tracename = "MOD"
    def __init__(self, **kwargs):
        """Constructor."""
        Traceable.__init__(self, **kwargs)

    def ber(self):
        """Abstract method to determine bit-error rate; **must be implemented to
        create concrete subclass**."""
        raise RuntimeError, "[MODULATION]: Abstract method ber not defined!"

    def per(self, p, *args, **kwargs):
        """Calculate packet-error rate (PER); **overload as needed**.

        :param p: Packet (packet length in bytes) to compute PER for.
        :param args: Arguments passed to `ber()`.
        :param kwargs: Additional keywords also passed to `ber()`.
        :return: Packet-error rate (PER) in [0,1].

        By default this method uses the following relationship to determine the
        packet-error rate:

            PER = 1 - (1 - BER)^Nbits

        where BER is the bit-error rate (as determined by calling `ber()` with
        args and kwargs) and Nbits is the number of bits in packet `p`.

        **Overload this method to change how packet-error rate is computed.**
        """
        plen = p
        ber = self.ber(*args, **kwargs)
        if isinstance(p, Packet): plen = len(p)
        nbits = 8*plen
        per = 1 - (1-ber)**nbits
        return per

redpajama_set_name: RedPajamaGithub


text:
package gcpbuildpack

import (
	"os"

	"github.com/GoogleCloudPlatform/buildpacks/pkg/env"
	"github.com/buildpacks/libcnb"
)

// SetFunctionsEnvVars sets launch-time functions environment variables.
func (ctx *Context) SetFunctionsEnvVars(l *libcnb.Layer) error {
	target, ok := os.LookupEnv(env.FunctionTarget)
	if !ok {
		return UserErrorf("required env var %s not found", env.FunctionTarget)
	}
	if target == "" {
		return UserErrorf("required env var %s has an empty value", env.FunctionTarget)
	}
	l.LaunchEnvironment.Default(env.FunctionTargetLaunch, target)
	if signature, ok := os.LookupEnv(env.FunctionSignatureType); ok {
		l.LaunchEnvironment.Default(env.FunctionSignatureTypeLaunch, signature)
	}
	if source, ok := os.LookupEnv(env.FunctionSource); ok {
		l.LaunchEnvironment.Default(env.FunctionSourceLaunch, source)
	}
	return nil
}


text:
package net.sansa_stack.query.spark.graph.jena.serialization

import com.esotericsoftware.kryo.Kryo
import net.sansa_stack.query.spark.graph.jena._
import net.sansa_stack.query.spark.graph.jena.expression.Expression
import net.sansa_stack.query.spark.graph.jena.util._
import org.apache.jena.graph.Node
import org.apache.spark.serializer.KryoRegistrator

/**
  * Register objects that serialized by the Kryo serializer.
  */
class Registrator extends KryoRegistrator {

  override def registerClasses(kryo: Kryo): Unit = {

    // Triple pattern
    kryo.register(classOf[TriplePattern])
    kryo.register(classOf[BasicGraphPattern])
    kryo.register(classOf[MatchCandidate])

    // Parser
    kryo.register(classOf[SparqlParser])
    kryo.register(classOf[ExprParser])

    // Query processing
    kryo.register(classOf[Ops])
    kryo.register(classOf[Expression])

    // Result
    kryo.register(classOf[Result[Node]])
  }
}


text:
require 'spec_helper'

describe "The and statement" do
  it "should always return s(:and)" do
    opal_parse("1 and 2").should == [:and, [:lit, 1], [:lit, 2]]
  end
end

describe "The && expression" do
  it "should always return s(:and)" do
    opal_parse("1 && 2").should == [:and, [:lit, 1], [:lit, 2]]
  end
end


text:
typedef struct readseg_st
{
    struct readseg_st* next;
    char* sequence;
    uint32_t oplen:28, op:4;
    int32_t start; // 0-based leftmost coordinate for this segment
    int32_t end;   // 0-based halfopen right most coordinate for this segment
}readseg;
// for a deleted segment the [start,end) and for inserted segment the inserted
// sequence is after the position denoted by start.

typedef struct readaln_st
{
    char* qname;
    int32_t tid;   // ID of the chromosome this read aligns to
    char strand;   // did I have to reverse complement the read?
    char index;    // index 1/2 for the read
    uint8_t qual;  // mapping quality of the read
    readseg* segments;
}readaln;

// convert 4-bit integer representing the base to nucleotide
char bit2char(const int encodedbase);

// create a new read segment from this information
readseg* new_readseg(const char* const sequence,
                     const uint32_t cigar,
                     int* const prefindx,
                     int* const preadindx);

// glean the information from this BAM alignment
readaln* new_readaln(const bam1_t* const alignment);

// create a read from this BAM alignment
readaln* new_unaligned_readaln(const bam1_t* const alignment,
                               const uint8_t mmq);

// for debugging only: print the read structure
void print_readaln(const readaln* const rln);

// free the resources used by this
void free_readaln(readaln** prln);

// free the resources held by these readsegs
void free_readsegs(readseg** prs);

// modify the segments for this readaln, as per the given cigarstring
void update_readsegs(readaln* const rln,
                     const int r1,
                     const uint32_t* cigarstring1,
                     const int numcigarops1,
                     const int index,
                     const int q2,
                     const int r2,
                     const uint32_t* cigarstring2,
                     const int numcigarops2);

// duplicate this read segment. Duplicate all members except the next pointer.
readseg* duplicate_readseg(const readseg* const rs);

// combine all these readseg to one [begin, end)
readseg* combine_readsegs(const readseg* const begin, const readseg* const end);
#endif


text:
import time
import json
import csv
import sys

from datetime import datetime
from .world import world, res_filename, logged_wait
from nose.tools import eq_, assert_less

from bigml.api import HTTP_CREATED, HTTP_ACCEPTED
from bigml.api import FINISHED
from bigml.api import FAULTY
from bigml.api import UPLOADING
from bigml.api import get_status

from . import read_source_steps as read

#@step(r'I create a data source uploading a "(.*)" file$')
def i_upload_a_file(step, file):
    resource = world.api.create_source(res_filename(file), \
        {'project': world.project_id})
    # update status
    world.status = resource['code']
    world.location = resource['location']
    world.source = resource['object']
    # save reference
    world.sources.append(resource['resource'])

#@step(r'I create a data source uploading a "(.*)" file using a project$')
def i_upload_a_file_with_project_conn(step, file):
    resource = world.api.create_source(res_filename(file))
    # update status
    world.status = resource['code']
    world.location = resource['location']
    world.source = resource['object']
    # save reference
    world.sources.append(resource['resource'])

#@step(r'I create a data source from stdin uploading a "(.*)" file$')
def i_upload_a_file_from_stdin(step, file):
    file_name = res_filename(file)
    with open(file_name, 'rb') as file_handler:
        resource = world.api.create_source(file_handler, \
            {'project': world.project_id})
        # update status
        world.status = resource['code']
        world.location = resource['location']
        world.source = resource['object']
        # save reference
        world.sources.append(resource['resource'])

#@step(r'I create a data source uploading a "(.*)" file with args "(.*)"$')
def i_upload_a_file_with_args(step, file, args):
    args = json.loads(args)
    args.update({'project': world.project_id})
    resource = world.api.create_source(res_filename(file), args)
    # update status
    world.status = resource['code']
    world.location = resource['location']
    world.source = resource['object']
    # save reference
    world.sources.append(resource['resource'])

#@step(r'I create a data source using the url "(.*)"')
def i_create_using_url(step, url):
    resource = world.api.create_source(url, {'project': world.project_id})
    # update status
    world.status = resource['code']
    world.location = resource['location']
    world.source = resource['object']
    # save reference
    world.sources.append(resource['resource'])

#@step(r'I create a data source using the connection ".*"')
def i_create_using_connector(step, connector):
    resource = world.api.create_source(connector, {'project': world.project_id})
    # update status
    world.status = resource['code']
    world.location = resource['location']
    world.source = resource['object']
    # save reference
    world.sources.append(resource['resource'])

#@step(r'I create a data source from inline data slurped from "(.*)"')
def i_create_using_dict_data(step, data):
    # slurp CSV file to local variable
    mode = 'rb'
    if sys.version > '3':
        mode = 'rt'
    with open(res_filename(data), mode) as fid:
        reader = csv.DictReader(fid)
        dict_data = [row for row in reader]
    # create source
    resource = world.api.create_source(dict_data,
                                       {'project': world.project_id})
    # update status
    world.status = resource['code']
    world.location = resource['location']
    world.source = resource['object']
    # save reference
    world.sources.append(resource['resource'])

#@step(r'I create a data source uploading a "(.*)" file in asynchronous mode$')
def i_upload_a_file_async(step, file):
    resource = world.api.create_source(res_filename(file),
                                       {'project': world.project_id},
                                       async_load=True)
    world.resource = resource

#@step(r'I wait until the source has been created less than (\d+) secs')
def the_source_has_been_created_async(step, secs):
    start = datetime.utcnow()
    read.i_get_the_source(step, world.source['resource'])
    status = get_status(world.resource)
    count = 0
    delta = int(secs) * world.delta
    while status['code'] == UPLOADING:
        count += 1
        logged_wait(start, delta, count, "source")
        read.i_get_the_source(step, world.source['resource'])
        status = get_status(world.source)
    eq_(world.resource['code'], HTTP_CREATED)
    # update status
    world.status = world.resource['code']
    world.location = world.resource['location']
    world.source = world.resource['object']
    # save reference
    world.sources.append(world.resource['resource'])

#@step(r'I wait until the source status code is either (\d) or (\d) less than (\d+)')
def wait_until_source_status_code_is(step, code1, code2, secs):
    start = datetime.utcnow()
    delta = int(secs) * world.delta
    read.i_get_the_source(step, world.source['resource'])
    status = get_status(world.source)
    count = 0
    while (status['code'] != int(code1) and
           status['code'] != int(code2)):
        count += 1
        logged_wait(start, delta, count, "source")
        read.i_get_the_source(step, world.source['resource'])
        status = get_status(world.source)
    eq_(status['code'], int(code1))

#@step(r'I wait until the source is ready less than (\d+)')
def the_source_is_finished(step, secs):
    wait_until_source_status_code_is(step, FINISHED, FAULTY, secs)

#@step(r'I update the source with params "(.*)"')
def i_update_source_with(step, data="{}"):
    resource = world.api.update_source(world.source.get('resource'), json.loads(data))
    world.status = resource['code']
    eq_(world.status, HTTP_ACCEPTED)

#@step(r'the source exists and has args "(.*)"')
def source_has_args(step, args="{}"):
    args = json.loads(args)
    for key, value in list(args.items()):
        if key in world.source:
            eq_(world.source[key], value,
                "Expected key %s: %s. Found %s" % (key, value, world.source[key]))
        else:
            assert False, "No key %s in source." % key


text:
    {{mapToggleText}}

        <map center="0, 0" zoom="2"
            ng-class="{'no-pointer-events': !pointerEvents}"
            street-view-control="false"
            disable-default-u-i="true"
            map-type-control-options="{
              mapTypeIds: ['ROADMAP'],
              style: 'DROPDOWN_MENU'
            }"></map>

    <form ng-submit="updateQuery()">

                minimum latitude:
                <input type="text" ng-model="data.value['geobound-minlat']" ng-change="updateQuery()">

                maximum latitude:
                <input type="text" ng-model="data.value['geobound-maxlat']" ng-change="updateQuery()">

                minimum longitude:
                <input type="text" ng-model="data.value['geobound-minlong']" ng-change="updateQuery()">

                maximum longitude:
                <input type="text" ng-model="data.value['geobound-maxlong']" ng-change="updateQuery()">

            <input type="checkbox" ng-model="usingFilter" ng-change="toggle()">
            Use GeoSearch?

    </form>


text:
package org.uberfire.ext.metadata.io;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import org.uberfire.commons.validation.PortablePreconditions;
import org.uberfire.ext.metadata.engine.Indexer;

/**
 * Container for Indexers setup by CDI after IOServiceIndexedImpl has been created
 */
public class IndexersFactory {

    private static final List<Indexer> indexers = new ArrayList<Indexer>();

    public static void addIndexer(final Indexer indexer) {
        indexers.add(PortablePreconditions.checkNotNull("indexer",
                                                        indexer));
    }

    public static List<Indexer> getIndexers() {
        return Collections.unmodifiableList(indexers);
    }

    public static void clear() {
        indexers.clear();
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<Tokens version="1.0">
	<File path="Classes/AutoScalingDescribeAutoScalingGroupsRequest.html">

		<Token>
			<TokenIdentifier>//apple_ref/occ/cl/AutoScalingDescribeAutoScalingGroupsRequest</TokenIdentifier>
			<Abstract type="html">Describe Auto Scaling Groups Request</Abstract>
			<DeclaredIn>AutoScalingDescribeAutoScalingGroupsRequest.h</DeclaredIn>

			<NodeRef refid="69"/>
		</Token>

		<Token>
			<TokenIdentifier>//apple_ref/occ/instm/AutoScalingDescribeAutoScalingGroupsRequest/init</TokenIdentifier>
			<Abstract type="html">Default constructor for a new  object.  Callers should use the
property methods to initialize this object after creating it.</Abstract>
			<DeclaredIn>AutoScalingDescribeAutoScalingGroupsRequest.h</DeclaredIn>

			<Declaration>- (id)init</Declaration>

			<Anchor>//api/name/init</Anchor>
		</Token>

		<Token>
			<TokenIdentifier>//apple_ref/occ/instm/AutoScalingDescribeAutoScalingGroupsRequest/setAutoScalingGroupNames:</TokenIdentifier>
			<Abstract type="html">A list of Auto Scaling group names.</Abstract>
			<DeclaredIn>AutoScalingDescribeAutoScalingGroupsRequest.h</DeclaredIn>

			<Declaration>@property (nonatomic, retain) NSMutableArray *autoScalingGroupNames</Declaration>

			<Anchor>//api/name/autoScalingGroupNames</Anchor>
		</Token>

		<Token>
			<TokenIdentifier>//apple_ref/occ/instp/AutoScalingDescribeAutoScalingGroupsRequest/autoScalingGroupNames</TokenIdentifier>
			<Abstract type="html">A list of Auto Scaling group names.</Abstract>
			<DeclaredIn>AutoScalingDescribeAutoScalingGroupsRequest.h</DeclaredIn>

			<Declaration>@property (nonatomic, retain) NSMutableArray *autoScalingGroupNames</Declaration>

			<Anchor>//api/name/autoScalingGroupNames</Anchor>
		</Token>

		<Token>
			<TokenIdentifier>//apple_ref/occ/instm/AutoScalingDescribeAutoScalingGroupsRequest/setNextToken:</TokenIdentifier>
			<Abstract type="html">A string that marks the start of the next batch of returned results.

Constraints:

Pattern: [\u0020-\uD7FF\uE000-\uFFFD\uD800\uDC00-\uDBFF\uDFFF\r\n\t]*
</Abstract>
			<DeclaredIn>AutoScalingDescribeAutoScalingGroupsRequest.h</DeclaredIn>

			<Declaration>@property (nonatomic, retain) NSString *nextToken</Declaration>

			<Anchor>//api/name/nextToken</Anchor>
		</Token>

		<Token>
			<TokenIdentifier>//apple_ref/occ/instp/AutoScalingDescribeAutoScalingGroupsRequest/nextToken</TokenIdentifier>
			<Abstract type="html">A string that marks the start of the next batch of returned results.

Constraints:

Pattern: [\u0020-\uD7FF\uE000-\uFFFD\uD800\uDC00-\uDBFF\uDFFF\r\n\t]*
</Abstract>
			<DeclaredIn>AutoScalingDescribeAutoScalingGroupsRequest.h</DeclaredIn>

			<Declaration>@property (nonatomic, retain) NSString *nextToken</Declaration>

			<Anchor>//api/name/nextToken</Anchor>
		</Token>

		<Token>
			<TokenIdentifier>//apple_ref/occ/instm/AutoScalingDescribeAutoScalingGroupsRequest/setMaxRecords:</TokenIdentifier>
			<Abstract type="html">The maximum number of records to return.

Constraints:

Range: 1 - 50
</Abstract>
			<DeclaredIn>AutoScalingDescribeAutoScalingGroupsRequest.h</DeclaredIn>

			<Declaration>@property (nonatomic, retain) NSNumber *maxRecords</Declaration>

			<Anchor>//api/name/maxRecords</Anchor>
		</Token>

		<Token>
			<TokenIdentifier>//apple_ref/occ/instp/AutoScalingDescribeAutoScalingGroupsRequest/maxRecords</TokenIdentifier>
			<Abstract type="html">The maximum number of records to return.

Constraints:

Range: 1 - 50
</Abstract>
			<DeclaredIn>AutoScalingDescribeAutoScalingGroupsRequest.h</DeclaredIn>

			<Declaration>@property (nonatomic, retain) NSNumber *maxRecords</Declaration>

			<Anchor>//api/name/maxRecords</Anchor>
		</Token>

		<Token>
			<TokenIdentifier>//apple_ref/occ/instm/AutoScalingDescribeAutoScalingGroupsRequest/addAutoScalingGroupName:</TokenIdentifier>
			<Abstract type="html">Adds a single object to autoScalingGroupNames.
This function will alloc and init autoScalingGroupNames if not already done.</Abstract>
			<DeclaredIn>AutoScalingDescribeAutoScalingGroupsRequest.h</DeclaredIn>

			<Declaration>- (void)addAutoScalingGroupName:(NSString *)autoScalingGroupNameObject</Declaration>

			<Anchor>//api/name/addAutoScalingGroupName:</Anchor>
		</Token>

		<Token>
			<TokenIdentifier>//apple_ref/occ/instm/AutoScalingDescribeAutoScalingGroupsRequest/description</TokenIdentifier>
			<Abstract type="html">Returns a string representation of this object; useful for testing and
debugging.</Abstract>
			<DeclaredIn>AutoScalingDescribeAutoScalingGroupsRequest.h</DeclaredIn>

			<Declaration>- (NSString *)description</Declaration>

			<ReturnValue><Abstract type="html">A string representation of this object.</Abstract></ReturnValue>
			<Anchor>//api/name/description</Anchor>
		</Token>

	</File>
</Tokens>


text:
from matplotlib import pyplot as plt, cm
import photutils
import numpy as np
from astropy import wcs
from astropy.io import fits
from astropy.table import Table
from os import path
from photutils.psf import DAOGroup
from photutils.psf import BasicPSFPhotometry
from photutils.background import MMMBackground
from photutils.aperture import (CircularAperture, CircularAnnulus,
                                aperture_photometry)
from astropy.modeling.fitting import LevMarLSQFitter
from astropy.table import Column

from . import hstzpt_apcorr
from .util import getheaderanddata, getcamera, getfilter, radec2xy

_HST_WFC3_PSF_FWHM_ARCSEC = 0.14  # FWHM of the HST WFC3IR PSF in arcsec

def centroid(imdat, x0, y0, boxsize=11):
    """ Locate a source in the image near position (x0,y0) using a 2-D gaussian
    centroid algorithm.
    :param imdat: image data (2-D array)
    :param x0: initial guess of x pixel location of the source
    :param y0: initial guess of y pixel location of the source
    :param boxsize: size of the box to search in (pixels)
    :return:
    """
    # create a mask that masks out all the pixels more than boxsize/2
    # pixels from the first-guess SN position (the center of the image,
    # or the target location specified by the user)
    halfbox = boxsize / 2.
    mask = np.ones(imdat.shape, dtype=bool)

    mask[int(y0 - halfbox):int(y0 + halfbox),
         int(x0 - halfbox):int(x0 + halfbox)] = False
    xnew, ynew = photutils.centroid_2dg(imdat, mask=mask)

    return xnew, ynew

class MeasuredPhotometry(object):
    """Holds the output of a photutils photometry run. Attributes store
    the name of this object, the type of photutils function used,
    the photutils.Photometry object, and the photometry results Table that
    contains the flux and flux uncertainty, as measured through apertures or
    via psf fitting.
    Methods allow conversion to magnitudes and application of aperture
    corrections.
    """
    def __init__(self, name, phot_type):
        assert phot_type in ['aperture', 'psf']
        self.name = name
        self.phot_type = phot_type
        self.photobject = None
        self.photresultstable = None
        self.psfmodel = None
        self.mag = None
        self.magerr = None
        self.flux = None
        self.flux_raw = None
        self.fluxerr = None
        self.fluxerr_raw = None
        self.aperture_corrections = None

    @property
    def nmeasurements(self):
        """Number of apertures measured"""
        if self.phot_type == 'psf':
            return 1
        if self.photresultstable is None:
            return None
        apertures = np.array([int(k.split('_')[-1])
                             for k in self.photresultstable.colnames
                             if k.startswith('aperture_sum')])
        return len(apertures)

    @property
    def aperture_radii(self):
        """Aperture radii in arcsec"""
        if self.phot_type=='psf':
            return None
        if self.photresultstable is None:
            return None
        apradii = np.array([self.photresultstable[
                                'radius_arcsec_{:d}'.format(i)].data[0]
                            for i in range(self.nmeasurements)])
        return apradii

    def get_flux_and_mag(self, zpt, camera, filtername):
        """Apply aperture corrections to correct the measured (raw) flux to
        the infinite-aperture-equivalent; apply zero points toconvert the
        corrected fluxes into magnitudes.
        :param zpt: zero point magnitude
        :param camera: HST camera name (e.g. 'WFC3-IR')
        :param filtername: HST filter name (e.g. 'F125W')

        Resulting fluxes and mags are stored as attributes.
        """
        if self.photresultstable is None:
            print("No photometry results.  Run doapphot or dopsfphot first.")
            return None

        if self.phot_type == 'aperture':
            # This is a table of aperture photometry.
            self.flux_raw = np.array(
                [self.photresultstable['aperture_sum_{:d}'.format(iap)].data[0]
                 for iap in range(self.nmeasurements)])

            # TODO: get flux uncertainties too!!
            self.fluxerr_raw = np.zeros(len(self.flux_raw))

            # get the aperture corrections and apply to the measured fluxes
            if camera == 'WFC3-IR':
                apcor, aperr = hstzpt_apcorr.apcorrWFC3IR(
                    filtername, self.aperture_radii)
            elif camera == 'WFC3-UVIS':
                apcor, aperr = hstzpt_apcorr.apcorrWFC3UVIS(
                    filtername, self.aperture_radii)
            elif camera == 'ACS-WFC':
                apcor, aperr = hstzpt_apcorr.apcorrACSWFC(
                    filtername, self.aperture_radii)
            else:
                raise RuntimeWarning(
                    "No aperture correction defined for "
                    " camera {}".format(camera))
            self.aperture_corrections = apcor

            # Aperture-corrected flux measurements
            fluxcor = 10**(0.4*apcor)
            self.flux = self.flux_raw * fluxcor

            #  Systematic err from aperture correction :
            ferrap = 0.4 * np.log(10) * self.flux * aperr
            self.fluxerr = np.sqrt(self.fluxerr_raw ** 2 + ferrap ** 2)
            nmeasurements = self.nmeasurements

        else:
            # This is a table of PSF-fitting photometry measurements
            self.flux_raw = self.photresultstable['flux_fit'].data[0]
            self.fluxerr_raw = self.photresultstable['flux_unc'].data[0]

            # TODO: apply a correction factor for PSF scaling?
            self.flux = self.flux_raw
            self.fluxerr = self.fluxerr_raw
            nmeasurements = 1

        # Convert the (corrected) flux to magnitudes and store
        maglist, magerrlist = [], []
        if nmeasurements == 1:
            flux = [self.flux]
            fluxerr = [self.fluxerr]
        else:
            flux = self.flux
            fluxerr = self.fluxerr
        for i in range(nmeasurements):
            if flux[i] <= 0:
                m = -2.5 * np.log10(3 * abs(fluxerr[i])) + zpt
                merr = -9.0
            else:
                m = -2.5 * np.log10(flux[i]) + zpt
                merr = 1.0857 * fluxerr[i] / flux[i]
            maglist.append(m)
            magerrlist.append(merr)
        if nmeasurements>1:
            self.mag = np.array(maglist)
            self.magerr = np.array(magerrlist)
        else:
            self.mag = maglist[0]
            self.magerr = magerrlist[0]

class TargetImage(object):
    """An image containing an isolated point source to be photometered."""

    def __init__(self, imfilename, ext=None, photsys='AB', zpt=None):
        """
        :param imfilename: full path for a .fits image file
        :param ext:  Fits image extension containing the image data.
        :param photsys: Photometric system 'AB' or 'Vega'
        """

        # read in the target image and determine the pixel scale (arcsec/pix)
        imhdr, imdat = getheaderanddata(imfilename, ext=ext)
        self.filename = path.basename(imfilename)
        self.imdat = imdat
        self.imhdr = imhdr
        self.wcs = wcs.WCS(self.imhdr)
        pixscale = wcs.utils.proj_plane_pixel_scales(self.wcs.celestial) * 3600
        if np.iterable(pixscale):
            self.pixscale = np.mean(pixscale)
        else:
            self.pixscale = pixscale

        # From the header, get Instrument, Camera, filter, Zero point, MJD
        self.photsys = photsys
        self.camera = getcamera([imhdr, imdat])
        self.filter = getfilter([imhdr, imdat])
        if zpt is None:
            self.zpt = hstzpt_apcorr.getzpt([imhdr, imdat], system=self.photsys)
        else:
            self.zpt = zpt
        if 'EXPSTART' in imhdr and 'EXPEND' in imhdr:
            self.mjd = (imhdr['EXPEND'] + imhdr['EXPSTART']) / 2.
        else:
            self.mjd = 0.0

        # initial guesses of position and flux of the target source
        self.x_0 = None
        self.y_0 = None
        self.flux_0 = None
        self.targetname = None

        # Sky annulus
        self.skyxy = None
        self.skyannpix = None
        self.skyvalperpix = None

        # Dictionary of Photometry objects. Each entry will hold a PSF model,
        # photometry object, and phot results table. Keyed with
        # user-specified names for the psf models.
        self._photutils_output_dict = {}

    @property
    def target_table(self):
        """ Returns a Table object with the centroid coordinates and the required
        column names x_0 and y_0. We include a flux_0 column to
        give an initial guess for the flux of the star."""
        if self.flux_0 is None:
            target_table = Table(
                data=[[self.x_0], [self.y_0]], names=['x_0', 'y_0'])
        else:
            target_table = Table(
                data=[[self.x_0], [self.y_0], [self.flux_0]],
                names=['x_0','y_0','flux_0'])
        return target_table

    def xy2radec(self, x, y):
        """ Convert the given x,y pixel position into
        ra,dec sky coordinates (in decimal degrees) for the given image.

        NOTE : this program assumes the input position follows the fits convention,
        with the center of the lower left pixel at (1,1).  The numpy/scipy
        convention sets the center of the lower left pixel at (0,0).

        :param x, y: pixel location
        """
        ra, dec = self.wcs.wcs_pix2world(x, y, 1)
        return ra, dec

    def radec2xy(self, ra, dec):
        """ Convert the given ra,dec position (in decimal degrees) into
        x,y pixel coordinates on the given image.
        NOTE : the pixel values returned are in the fits style, with the center
          of the lower left pixel at (1,1).  The numpy/scipy convention sets
          the center of the lower left pixel at (0,0).
        """
        x, y = self.wcs.wcs_world2pix(ra, dec, 1)
        return x, y

    def set_target(self, x_0=None, y_0=None, flux_0=None,
                   ra_0=None, dec_0=None, targetname=None,
                   recenter=False):
        """set the initial guesses for pixel location and optionally
        the flux of the target"""
        # TODO: allow user to specify multiple targets on a single image
        if ra_0 is not None:
            assert dec_0 is not None, "Must provide either x,y or RA,Dec"
            assert x_0 is None, "Must provide either x,y or RA,Dec, not both"
            self.ra_0 = ra_0
            self.dec_0 = dec_0
            self.x_0, self.y_0 = self.radec2xy(ra_0, dec_0)
        else:
            if x_0 is not None:
                assert y_0 is not None, "Must provide either x,y or RA,Dec"
                self.x_0 = x_0
                self.y_0 = y_0
                self.ra_0, self.dec_0 = self.xy2radec(x_0, y_0)
            else:
                self.x_0 = self.imdat.shape[0] / 2.
                self.y_0 = self.imdat.shape[1] / 2.
        if targetname is None:
            self.targetname = 'target'
        else:
            self.targetname = targetname
        if recenter:
            # Apply a centroiding algorithm to locate the source in the image
            self.x_0, self.y_0 = centroid(self.imdat, self.x_0, self.y_0)
            self.ra_0, self.dec_0 = self.xy2radec(self.x_0, self.y_0)
        # If the user leaves flux0 as None then aperture photometry will
        # be used for the first guess at the flux of the target
        self.flux_0 = flux_0

    def load_psfmodel(self, psfimfilename, modelname=None, **kwargs):
        """Initialize an HSTPSFModel object to use for measuring photometry

        :param psfimfilename: full path to the psf image fits file
        :param modelname: name of the model to store in the modeldict. If left
         as None, the basename of the psf image file is used.
        Additional keyword args get passed to the HSTPSFModel initializer.
        :return:
        """
        if modelname is None:
            modelname = path.basename(psfimfilename)
        # TODO: special case for a Gaussian PRF

        # Load a psf model from a "psf star image"
        self._photutils_output_dict[modelname] = \
            MeasuredPhotometry(modelname, 'psf')
        self._photutils_output_dict[modelname].psfmodel = HSTPSFModel(
            psfimfilename, self.pixscale, **kwargs)

    def dopsfphot(self, modelname, fitpix=11, apradpix=3):
        """Do photometry of the target:
        set up a photometry object, do the photometry and store the results.
        fitpix : int or length-2 array-like
          Rectangular shape around the center of a star which will be used
          to collect the data to do the fitting. Can be an integer to be
          the same along both axes. E.g., 5 is the same as (5, 5), which
          means to fit only at the following relative pixel positions:
          [-2, -1, 0, 1, 2].  Each element of ``fitshape`` must be an odd
          number.
        apradpix : float or None
          The radius (in units of pixels) used to compute initial
          estimates for the fluxes of sources. If ``None``, one FWHM will
          be used if it can be determined from the ```psf_model``.

        """
        if modelname not in self._photutils_output_dict:
            print("Model {} not loaded. Use load_psfmodel()".format(modelname))
            return
        if self.skyvalperpix is None:
            self.get_sky_from_annulus()
        hstpsfmodel = self._photutils_output_dict[modelname].psfmodel

        # Make the photometry object
        hstphotobject = BasicPSFPhotometry(
            psf_model=hstpsfmodel.psfmodel, group_maker=hstpsfmodel.grouper,
            bkg_estimator=hstpsfmodel.bkg_estimator,
            fitter=hstpsfmodel.fitter, fitshape=fitpix,
            aperture_radius=apradpix)
        self._photutils_output_dict[modelname].photobject = hstphotobject

        phot_results_table = hstphotobject.do_photometry(
            image=self.imdat, init_guesses=self.target_table)
        self._photutils_output_dict[modelname].photresultstable = phot_results_table

        self._photutils_output_dict[modelname].get_flux_and_mag(
            self.zpt, self.camera, self.filter)

    def get_sky_from_annulus(self, r_in=3, r_out=5, units='arcsec'):
        """ Measure the sky flux with aperture photometry in an annulus.
        :param r_in, r_out: float
            inner, outer radius of the sky annulus
        :param units: 'arcsec' or 'pixels'
           units for the radii.
        :return: skyval : the measured average sky brightness per pixel.
        """
        self.skyxy = [self.x_0, self.y_0]
        if units.lower()=='arcsec':
            r_in = r_in / self.pixscale
            r_out = r_out / self.pixscale
        elif not units.lower().startswith('pix'):
            raise RuntimeError('Unknown unit %s'%units)

        skyannulus = CircularAnnulus(self.skyxy, r_in=r_in, r_out=r_out)
        phot_table = aperture_photometry(
            self.imdat, skyannulus, error=None, mask=None,
            method=u'exact', subpixels=5, unit=None, wcs=None)
        skyvaltot = phot_table['aperture_sum']

        self.skyannpix = [r_in, r_out]
        self.skyvalperpix = skyvaltot / skyannulus.area()

        # TODO: compute the error properly
        self.skyerr = 0.0
        return

    def doapphot(self, apradlist, units='arcsec'):
        """ Measure the flux in one or more apertures.
        :param apradlist: float or array-like
           aperture radius or list of radii.
        :param units: 'arcsec' or 'pixels';
           the units for the aperture radii in apradlist.
        """
        if not np.iterable(apradlist):
            apradlist = [apradlist]
        if units == 'arcsec':
            apradlist = [ap / self.pixscale for ap in apradlist]
        if self.skyvalperpix is None:
            self.get_sky_from_annulus()

        xy = [self.x_0, self.y_0]
        apertures = [CircularAperture(xy, r) for r in apradlist]
        phot_table = aperture_photometry(
            self.imdat, apertures, error=None, mask=None,
            method=u'exact', subpixels=5, unit=None, wcs=None)

        # Modify the output photometry table
        if 'aperture_sum' in phot_table.colnames:
            # if we had only a single aperture, then the aperture sum column
            # has no index number at the end. So we add it.
            phot_table.rename_column('aperture_sum', 'aperture_sum_0')
        for i in range(len(apertures)):
            # add a column for each aperture specifying the radius in arcsec
            colname = 'radius_arcsec_{:d}'.format(i)
            apradarcsec = apradlist[i] * self.pixscale
            apcol = Column(name=colname, data=[apradarcsec,])
            phot_table.add_column(apcol)

        self._photutils_output_dict['aperturephot'] = \
            MeasuredPhotometry('aperturephot', 'aperture')
        self._photutils_output_dict['aperturephot'].photresultstable = \
            phot_table
        self._photutils_output_dict['aperturephot'].get_flux_and_mag(
            self.zpt, self.camera, self.filter)

    @property
    def phot_summary_table(self, verbose=False):
        """Creates a Table object summarizing the photometry results.
        """
        assert len(self._photutils_output_dict),\
            "No photometry recorded. Run a photometry function first."

        if 'aperturephot' in self._photutils_output_dict:
            apphot = self._photutils_output_dict['aperturephot']

        nmeasurements = sum([phot.nmeasurements for phot in
                             self._photutils_output_dict.values()])
        mjdcol = Column(name='MJD', data=np.ones(nmeasurements) * self.mjd)
        imagecol = Column(
            name='IMAGE', data=[self.filename for i in range(nmeasurements)])
        magsyscol = Column(
            name='MAGSYS', data=[self.photsys for i in range(nmeasurements)])
        zpcol = Column(
            name='ZP', data=[self.zpt for i in range(nmeasurements)])
        skycol = Column(
            name='SKY', data=[self.skyvalperpix for i in range(nmeasurements)])
        skyerrcol = Column(
            name='SKYERR', data=[self.skyerr for i in range(nmeasurements)])

        aperlist = np.array([])
        fluxlist = np.array([])
        fluxerrlist = np.array([])
        maglist = np.array([])
        magerrlist = np.array([])

        for phot in self._photutils_output_dict.values():
            if phot.phot_type == 'aperture':
                aperlist = np.append(aperlist, phot.aperture_radii)
            else:
                aperlist = np.append(aperlist, 0)
            fluxlist = np.append(fluxlist, phot.flux)
            fluxerrlist = np.append(fluxerrlist, phot.fluxerr)
            maglist = np.append(maglist, phot.mag)
            magerrlist = np.append(magerrlist, phot.magerr)
        apercol = Column(name='APER', data=aperlist)
        fluxcol = Column(name='FLUX', data=fluxlist)
        fluxerrcol = Column(name='FLUXERR', data=fluxerrlist)
        magcol = Column(name='MAG', data=maglist)
        magerrcol = Column(name='MAGERR', data=magerrlist)

        phot_table = Table([mjdcol, apercol, fluxcol, fluxerrcol,
                            magcol, magerrcol, magsyscol, zpcol,
                            skycol, skyerrcol, imagecol])
        return phot_table

    def plot_resid_image(self, modelname, Npix=15):
        """Make a figure showing the target, the psf model, and the residual
        image after subtracting the PSF model.
        Note: assumes that the photobject has already been used to collect
        photometry on a target image, so that the get_residual_image() method
        will return a valid resid image.
        TODO: make this more generalized!"""

        if modelname not in self._photutils_output_dict:
            print("Model {} not loaded. Use load_psfmodel()"
                  " and then dophot() to run photometry.".format(modelname))
            return
        photinstance = self._photutils_output_dict[modelname]
        if photinstance.photresults is None:
            print("No phot results for model {}. "
                  " Use dophot()".format(modelname))
            return

        psfmodel = self._photutils_output_dict[modelname].psfmodel
        results_table = self._photutils_output_dict[modelname].photresults
        targetimdat = self.imdat

        # TODO : read these from the results table?
        xtarget = self.x_0
        ytarget = self.y_0

        fig = plt.gcf()
        ax1 = fig.add_subplot(1, 3, 1)
        im1 = ax1.imshow(
            targetimdat[int(ytarget) - Npix / 2:int(ytarget) + Npix / 2,
            int(xtarget) - Npix / 2:int(xtarget) + Npix / 2],
            interpolation='nearest', cmap='viridis', origin='left')
        plt.colorbar(im1, orientation='horizontal', fraction=0.046, pad=0.1,
                     ticks=plt.MaxNLocator(5))

        # use np.meshgrid to define a coordinate grid over which the PSF model
        # can be evaluated.
        gridindices = np.meshgrid(np.arange(len(targetimdat)),
                                  np.arange(len(targetimdat)))
        parameters_to_set = {'x_fit': 'x_0', 'y_fit': 'y_0', 'flux_fit': 'flux'}

        photobject = self._photutils_output_dict[modelname].photobject
        groupmodel = photutils.psf.models.get_grouped_psf_model(
            photobject.psf_model, results_table, parameters_to_set)
        psf_image = groupmodel(gridindices[0], gridindices[1])

        ax2 = fig.add_subplot(1, 3, 2)
        im2 = ax2.imshow(psf_image[int(ytarget) - Npix / 2:int(ytarget) + Npix / 2,
                         int(xtarget) - Npix / 2:int(xtarget) + Npix / 2],
                         interpolation='nearest', cmap='viridis', origin='left')
        plt.colorbar(im2, orientation='horizontal', fraction=0.05, pad=0.1,
                     ticks=plt.MaxNLocator(5))

        residual_image = photobject.get_residual_image()
        ax3 = fig.add_subplot(1, 3, 3)
        im3 = ax3.imshow(
            residual_image[int(ytarget) - Npix / 2:int(ytarget) + Npix / 2,
                           int(xtarget) - Npix / 2:int(xtarget) + Npix / 2],
            interpolation='nearest', cmap='viridis', origin='left')
        plt.colorbar(im3, orientation='horizontal', fraction=0.05, pad=0.1,
                     ticks=plt.MaxNLocator(5))
        return groupmodel

class HSTPSFModel(object):
    """A psf model based on an HST image of a standard star or a
    stack of stars."""

    def __init__(self, psfimfilename, targetpixscale, psfpixscale=0.03,
                 x_0=None, y_0=None, psf_recenter=False, fix_target_pos=True,
                 fwhm_arcsec=_HST_WFC3_PSF_FWHM_ARCSEC):
        """
        :param psfimfilename: full path for a .fits image file
        :param targetpixscale: arcseconds per pixel of the target image
        :param psfpixscale: arcseconds per pixel of the psf image (if not
        provided in the image header). Defaults to 0.03" per pixel
        :param xycenter: tuple, giving pixel coordinates of  the star. If not
        provided, we assume it is at the center of the image.
        :param psf_recenter: execute a centroiding algorithm to locate the
        center of the psf
        :param fix_target_pos: execute "forced photometry" with the center of
        the target fixed, and only the psf flux scaling as a free parameter.
        """
        psfimage = fits.open(psfimfilename)
        self.header = psfimage[0].header
        self.psfimdat = psfimage[0].data

        # TODO : check the header for pixel scale info

        if x_0 is None:
            self.xpsf = self.psfimdat.shape[0] / 2.,
            self.ypsf = self.psfimdat.shape[1] / 2.
        else:
            self.xpsf, self.ypsf = x_0, y_0

        if psf_recenter:
            self.xpsf, self.ypsf = centroid(self.psfimdat, x_0, y_0)

        self.psfmodel = photutils.psf.models.FittableImageModel(
            self.psfimdat, x_0=self.xpsf, y_0=self.ypsf,
            oversampling=targetpixscale / psfpixscale)

        # Fix the center of the psf for "forced photometry" -- no recentering
        if fix_target_pos:
            self.psfmodel.x_0.fixed = True
            self.psfmodel.y_0.fixed = True
        else:
            self.psfmodel.x_0.fixed = False
            self.psfmodel.y_0.fixed = False

        # Set up the grouper, background estimator, and fitter objects:
        self.grouper = DAOGroup(2.0 * fwhm_arcsec * psfpixscale)
        self.bkg_estimator = MMMBackground()
        self.fitter = LevMarLSQFitter()

        # Disabled b/c its unnecessary:
        # Measure the background noise level of the target image:
        # bkgrms = MADStdBackgroundRMS()
        # std = bkgrms(targetimdat)
        #
        # If we didn't know where the target was located, we could use the IRAF star
        # finder algorithm to locate sources.  In this case we won't actually
        # use a finder object, because we will feed in the known target location
        #  in the next step.
        #iraffind = IRAFStarFinder(threshold=15*std,
        #                        fwhm=sigma_psf_pixels*gaussian_sigma_to_fwhm,
        #                        minsep_fwhm=0.01, roundhi=5.0, roundlo=-5.0,
        #                        sharplo=0.0, sharphi=2.0)


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

class Article < Content
  include TypoGuid
  include ConfigManager

  serialize :settings, Hash

  content_fields :body, :extended

  validates_uniqueness_of :guid
  validates_presence_of :title

  belongs_to :user

  has_many :pings, :dependent => :destroy, :order => "created_at ASC"
  has_many :trackbacks, :dependent => :destroy, :order => "created_at ASC"
  has_many :feedback, :order => "created_at DESC"
  has_many :resources, :order => "created_at DESC", :dependent => :nullify
  has_many :categorizations
  has_many :categories, :through => :categorizations
  has_many :triggers, :as => :pending_item

  has_many :comments,   :dependent => :destroy, :order => "created_at ASC" do

    # Get only ham or presumed_ham comments
    def ham
      where(:state => ["presumed_ham", "ham"])
    end

    # Get only spam or presumed_spam comments
    def spam
      where(:state => ["presumed_spam", "spam"])
    end

  end

  with_options(:conditions => { :published => true }, :order => 'created_at DESC') do |this|
    this.has_many :published_comments,   :class_name => "Comment", :order => "created_at ASC"
    this.has_many :published_trackbacks, :class_name => "Trackback", :order => "created_at ASC"
    this.has_many :published_feedback,   :class_name => "Feedback", :order => "created_at ASC"
  end

  has_and_belongs_to_many :tags

  before_create :create_guid
  before_save :set_published_at, :ensure_settings_type, :set_permalink
  after_save :post_trigger, :keywords_to_tags, :shorten_url

  scope :category, lambda { |category_id| where('categorizations.category_id = ?', category_id).includes('categorizations') }
  scope :drafts, lambda { where(:state => 'draft').order('created_at DESC') }
  scope :child_of, lambda { |article_id| where(:parent_id => article_id) }
  scope :published, lambda { where(:published => true, :published_at => Time.at(0)..Time.now).order('published_at DESC') }
  scope :published_at, lambda { |time_params| where(:published => true, :published_at => Article.time_delta(*time_params)).order('published_at DESC') }
  scope :withdrawn, lambda { where(:state => 'withdrawn').order('published_at DESC') }
  scope :pending, lambda { where('state = ? and published_at > ?', 'publication_pending', Time.now).order('published_at DESC') }

  setting :password, :string, ''

  attr_accessor :draft, :keywords

  include Article::States

  has_state(:state, :valid_states  => [:new, :draft,
                                       :publication_pending, :just_published, :published,
                                       :just_withdrawn, :withdrawn],
                                       :initial_state =>  :new,
                                       :handles       => [:withdraw,
                                                          :post_trigger,
                                                          :send_pings, :send_notifications,
                                                          :published_at=, :just_published?])

  def initialize(*args)
    super
    # Yes, this is weird - PDC
    begin
      self.settings ||= {}
    rescue Exception => e
      self.settings = {}
    end
  end

  def set_permalink
    return if self.state == 'draft' || self.permalink.present?
    self.permalink = self.title.to_permalink
  end

  def set_author(user)
    self.author = user.login
    self.user = user
  end

  def has_child?
    Article.exists?(parent_id: self.id)
  end

  def self.last_draft(article_id)
    article = Article.find(article_id)
    while article.has_child?
      article = Article.child_of(article.id).first
    end
    article
  end

  def self.search_with_pagination(search_hash, paginate_hash)
    state = (search_hash[:state] and ["no_draft", "drafts", "published", "withdrawn", "pending"].include? search_hash[:state]) ? search_hash[:state] : nil

    if state.nil?
      list_function  = function_search_all_posts(search_hash)
    elsif
      list_function  = ["Article.#{state}"] + function_search_all_posts(search_hash)
    end

    if search_hash[:category] && search_hash[:category].to_i > 0
      list_function << 'category(search_hash[:category])'
    end

    list_function << "page(paginate_hash[:page])"
    list_function << "per(paginate_hash[:per_page])"
    list_function << "order('published_at desc, created_at desc')"
    eval(list_function.join('.'))
  end

  def permalink_url(anchor=nil, only_path=false)
    @cached_permalink_url ||= {}
    @cached_permalink_url["#{anchor}#{only_path}"] ||= blog.url_for(permalink_url_options, anchor: anchor, only_path: only_path)
  end

  def save_attachments!(files)
    files ||= {}
    files.values.each { |f| self.save_attachment!(f) }
  end

  def save_attachment!(file)
    self.resources << Resource.create_and_upload(file)
  rescue => e
    logger.info(e.message)
  end

  def trackback_url
    blog.url_for("trackbacks?article_id=#{self.id}", :only_path => false)
  end

  def comment_url
    blog.url_for("comments?article_id=#{self.id}", :only_path => false)
  end

  def preview_comment_url
    blog.url_for("comments/preview?article_id=#{self.id}", :only_path => false)
  end

  def feed_url(format)
    "#{permalink_url}.#{format.gsub(/\d/,'')}"
  end

  def really_send_pings
    return unless blog.send_outbound_pings

    blog.urls_to_ping_for(self).each do |url_to_ping|
      begin
        url_to_ping.send_weblogupdatesping(blog.base_url, permalink_url)
      rescue Exception => e
        logger.error(e)
        # in case the remote server doesn't respond or gives an error,
        # we should throw an xmlrpc error here.
      end
    end

    html_urls_to_ping.each do |url_to_ping|
      begin
        url_to_ping.send_pingback_or_trackback(permalink_url)
      rescue Exception => exception
        logger.error(exception)
        # in case the remote server doesn't respond or gives an error,
        # we should throw an xmlrpc error here.
      end
    end
  end

  def next
    Article.where('published_at > ?', published_at).order('published_at asc').limit(1).first
  end

  def previous
    Article.where('published_at < ?', published_at).order('published_at desc').limit(1).first
  end

  def self.find_by_published_at
    result = select('published_at').where('published_at is not NULL').where(type: 'Article')
    result.map{ |d| [d.published_at.strftime('%Y-%m')]}.uniq
  end

  def self.get_or_build_article(id)
    return Article.find(id) if id.present?
    article = Article.new.tap do |art|
      art.allow_comments = art.blog.default_allow_comments
      art.allow_pings = art.blog.default_allow_pings
      art.old_permalink = art.permalink_url unless art.permalink.nil? or art.permalink.empty?
      art.published = true
    end
  end

  # Finds one article which was posted on a certain date and matches the supplied dashed-title
  # params is a Hash
  def self.find_by_permalink(params)
    date_range = self.time_delta(params[:year], params[:month], params[:day])

    req_params = {}
    req_params[:permalink] = params[:title] if params[:title]
    req_params[:published_at] = date_range if date_range

    return nil if req_params.empty? # no search if no params send

    article = find_published(:first, :conditions => req_params)
    return article if article

    if params[:title]
      req_params[:permalink] = CGI.escape(params[:title])
      article = find_published(:first, :conditions => req_params)
      return article if article
    end

    raise ActiveRecord::RecordNotFound
  end

  def self.find_by_params_hash(params = {})
    params[:title] ||= params[:article_id]
    find_by_permalink(params)
  end

  # Fulltext searches the body of published articles
  def self.search(query, args={})
    query_s = query.to_s.strip
    if !query_s.empty? && args.empty?
      Article.searchstring(query)
    elsif !query_s.empty? && !args.empty?
      Article.searchstring(query).page(args[:page]).per(args[:per])
    else
      []
    end
  end

  def keywords_to_tags
    Article.transaction do
      tags.clear
      tags <<
      keywords.to_s.scan(/((['"]).*?\2|[\.[[:alnum:]]]+)/).collect do |x|
        x.first.tr("\"'", '')
      end.uniq.map do |tagword|
        Tag.get(tagword)
      end
    end
  end

  def interested_users
    User.find_all_by_notify_on_new_articles(true)
  end

  def notify_user_via_email(user)
    if user.notify_via_email?
      EmailNotify.send_article(self, user)
    end
  end

  def comments_closed?
    !(allow_comments? && in_feedback_window?)
  end

  def html_urls
    urls = Array.new
    html.gsub(/<a\s+[^>]*>/) do |tag|
      if(tag =~ /\bhref=(["']?)([^ >"]+)\1/)
        urls.push($2.strip)
      end
    end
    urls.uniq
  end

  def pings_closed?
    !(allow_pings? && in_feedback_window?)
  end

  # check if time to comment is open or not
  def in_feedback_window?
    self.blog.sp_article_auto_close.zero? ||
      self.published_at.to_i > self.blog.sp_article_auto_close.days.ago.to_i
  end

  def cast_to_boolean(value)
    ActiveRecord::ConnectionAdapters::Column.value_to_boolean(value)
  end
  # Cast the input value for published= before passing it to the state.
  def published=(newval)
    state.published = cast_to_boolean(newval)
  end

  def content_fields
    [:body, :extended]
  end

  # The web interface no longer distinguishes between separate "body" and
  # "extended" fields, and instead edits everything in a single edit field,
  # separating the extended content using "\<!--more-->".
  def body_and_extended
    if extended.nil? || extended.empty?
      body
    else
      body + "\n<!--more-->\n" + extended
    end
  end

  # Split apart value around a "\<!--more-->" comment and assign it to our
  # #body and #extended fields.
  def body_and_extended= value
    parts = value.split(/\n?<!--more-->\n?/, 2)
    self.body = parts[0]
    self.extended = parts[1] || ''
  end

  def link_to_author?
    !user.email.blank? && blog.link_to_author
  end

  def password_protected?
    not password.blank?
  end

  def add_comment(params)
    comments.build(params)
  end

  def add_category(category, is_primary = false)
    self.categorizations.build(:category => category, :is_primary => is_primary)
  end

  def access_by?(user)
    user.admin? || user_id == user.id
  end

  def already_ping?(url)
    self.pings.map(&:url).include?(url)
  end

  def allow_comments?
    return self.allow_comments unless self.allow_comments.nil?
    blog.default_allow_comments
  end

  def allow_pings?
    return self.allow_pings unless self.allow_pings.nil?
    blog.default_allow_pings
  end

  protected

  def set_published_at
    if self.published and self[:published_at].nil?
      self[:published_at] = self.created_at || Time.now
    end
  end

  def ensure_settings_type
    if settings.is_a?(String)
      # Any dump access forcing de-serialization
      password.blank?
    end
  end

  def self.time_delta(year = nil, month = nil, day = nil)
    return nil if year.nil? && month.nil? && day.nil?
    from = Time.utc(year, month || 1, day || 1)

    to = from.next_year
    to = from.next_month unless month.blank?
    to = from + 1.day unless day.blank?
    to = to - 1 # pull off 1 second so we don't overlap onto the next day
    from..to
  end

  private

  def permalink_url_options
    format_url = blog.permalink_format.dup
    format_url.gsub!('%year%', published_at.year.to_s)
    format_url.gsub!('%month%', sprintf("%.2d", published_at.month))
    format_url.gsub!('%day%', sprintf("%.2d", published_at.day))
    format_url.gsub!('%title%', URI.encode(permalink.to_s))
    if format_url[0,1] == '/'
      format_url[1..-1]
    else
      format_url
    end
  end

  def html_urls_to_ping
    urls_to_ping = []
    html_urls.delete_if{|url| already_ping?(url)}.uniq.each do |url_to_ping|
      urls_to_ping << self.pings.build("url" => url_to_ping)
    end
    urls_to_ping
  end
end


text:
Render React components only when they are in viewport.

## Install:

```bash
npm install react-lazyrender
```

## Usage:

### As Mixin

```js
var lazyRenderMixin = require('react-lazyrender/mixin');
var Item = React.createClass({
  mixins: [
    lazyRenderMixin(
      function(nextProps, nextState) {}, // The actual shouldComponentUpdate function
      1000 // The buffer distance. Components within this distance away from viewport will also be rendered.
    ),
  ],
  render: function() {
    return <li></li>;
  }
});
```

### As Higher-Order Component

Removed temporarily


text:
import base64
import collections
import inspect

# Some arguments to __init__ is mungled in order to avoid name conflicts
# with builtin names.
# The standard mangling is to append '_' in order to avoid name clashes
# with reserved keywords.
#
# PEP8:
# Function and method arguments
#   If a function argument's name clashes with a reserved keyword,
#   it is generally better to append a single trailing underscore
#   rather than use an abbreviation or spelling corruption. Thus
#   class_ is better than clss. (Perhaps better is to avoid such
#   clashes by using a synonym.)
#
# grep __init__ *.py | grep '[^_]_\>' showed that
# 'len', 'property', 'set', 'type'
# A bit more generic way is adopted
import __builtin__
_RESERVED_KEYWORD = dir(__builtin__)

_mapdict = lambda f, d: dict([(k, f(v)) for k, v in d.items()])
_mapdict_key = lambda f, d: dict([(f(k), v) for k, v in d.items()])
_mapdict_kv = lambda f, d: dict([(k, f(k, v)) for k, v in d.items()])

class TypeDescr(object):
    pass

class AsciiStringType(TypeDescr):
    @staticmethod
    def encode(v):
        return unicode(v, 'ascii')

    @staticmethod
    def decode(v):
        return v.encode('ascii')

class Utf8StringType(TypeDescr):
    @staticmethod
    def encode(v):
        return unicode(v, 'utf-8')

    @staticmethod
    def decode(v):
        return v.encode('utf-8')

_types = {
    'ascii': AsciiStringType,
    'utf-8': Utf8StringType,
}

class StringifyMixin(object):

    _TYPE = {}
    """_TYPE class attribute is used to annotate types of attributes.

    This type information is used to find an appropriate conversion for
    a JSON style dictionary.

    Currently the following types are implemented.

    ===== ==========
    Type  Descrption
    ===== ==========
    ascii US-ASCII
    utf-8 UTF-8
    ===== ==========

    Example::
        _TYPE = {
            'ascii': [
                'hw_addr',
            ],
            'utf-8': [
                'name',
            ]
        }
    """

    _class_prefixes = []

    def stringify_attrs(self):
        """an override point for sub classes"""
        return obj_python_attrs(self)

    def __str__(self):
        # repr() to escape binaries
        return self.__class__.__name__ + '(' + \
            ','.join("%s=%s" % (k, repr(v)) for k, v in
                     self.stringify_attrs()) + ')'
    __repr__ = __str__  # note: str(list) uses __repr__ for elements

    @classmethod
    def _is_class(cls, dict_):
        # we distinguish a dict like OFPSwitchFeatures.ports
        # from OFPxxx classes using heuristics.
        # exmples of OFP classes:
        #   {"OFPMatch": { ... }}
        #   {"MTIPv6SRC": { ... }}
        assert isinstance(dict_, dict)
        if len(dict_) != 1:
            return False
        k = dict_.keys()[0]
        if not isinstance(k, (bytes, unicode)):
            return False
        for p in cls._class_prefixes:
            if k.startswith(p):
                return True
        return False

    @classmethod
    def _get_type(cls, k):
        if hasattr(cls, '_TYPE'):
            for t, attrs in cls._TYPE.iteritems():
                if k in attrs:
                    return _types[t]
        return None

    @classmethod
    def _get_encoder(cls, k, encode_string):
        t = cls._get_type(k)
        if t:
            return t.encode
        return cls._get_default_encoder(encode_string)

    @classmethod
    def _encode_value(cls, k, v, encode_string=base64.b64encode):
        return cls._get_encoder(k, encode_string)(v)

    @classmethod
    def _get_default_encoder(cls, encode_string):
        def _encode(v):
            if isinstance(v, (bytes, unicode)):
                json_value = encode_string(v)
            elif isinstance(v, list):
                json_value = map(_encode, v)
            elif isinstance(v, dict):
                json_value = _mapdict(_encode, v)
                # while a python dict key can be any hashable object,
                # a JSON object key should be a string.
                json_value = _mapdict_key(str, json_value)
                assert not cls._is_class(json_value)
            else:
                try:
                    json_value = v.to_jsondict()
                except:
                    json_value = v
            return json_value
        return _encode

    def to_jsondict(self, encode_string=base64.b64encode):
        """
        This method returns a JSON style dict to describe this object.

        The returned dict is compatible with json.dumps() and json.loads().

        Suppose ClassName object inherits StringifyMixin.
        For an object like the following::

            ClassName(Param1=100, Param2=200)

        this method would produce::

            { "ClassName": {"Param1": 100, "Param2": 200} }

        This method takes the following arguments.

        =============  =====================================================
        Argument       Description
        =============  =====================================================
        encode_string  (Optional) specify how to encode attributes which has
                       python 'str' type.
                       The default is base64.
                       This argument is used only for attributes which don't
                       have explicit type annotations in _TYPE class attribute.
        =============  =====================================================
        """
        dict_ = {}
        encode = lambda k, x: self._encode_value(k, x, encode_string)
        for k, v in obj_attrs(self):
            dict_[k] = encode(k, v)
        return {self.__class__.__name__: dict_}

    @classmethod
    def cls_from_jsondict_key(cls, k):
        # find a class with the given name from our class' module.
        import sys
        mod = sys.modules[cls.__module__]
        return getattr(mod, k)

    @classmethod
    def obj_from_jsondict(cls, jsondict):
        assert len(jsondict) == 1
        for k, v in jsondict.iteritems():
            obj_cls = cls.cls_from_jsondict_key(k)
            return obj_cls.from_jsondict(v)

    @classmethod
    def _get_decoder(cls, k, decode_string):
        t = cls._get_type(k)
        if t:
            return t.decode
        return cls._get_default_decoder(decode_string)

    @classmethod
    def _decode_value(cls, k, json_value, decode_string=base64.b64decode):
        return cls._get_decoder(k, decode_string)(json_value)

    @classmethod
    def _get_default_decoder(cls, decode_string):
        def _decode(json_value):
            if isinstance(json_value, (bytes, unicode)):
                v = decode_string(json_value)
            elif isinstance(json_value, list):
                v = map(_decode, json_value)
            elif isinstance(json_value, dict):
                if cls._is_class(json_value):
                    v = cls.obj_from_jsondict(json_value)
                else:
                    v = _mapdict(_decode, json_value)
                    # XXXhack
                    # try to restore integer keys used by
                    # OFPSwitchFeatures.ports.
                    try:
                        v = _mapdict_key(int, v)
                    except ValueError:
                        pass
            else:
                v = json_value
            return v
        return _decode

    @staticmethod
    def _restore_args(dict_):
        def restore(k):
            if k in _RESERVED_KEYWORD:
                return k + '_'
            return k
        return _mapdict_key(restore, dict_)

    @classmethod
    def from_jsondict(cls, dict_, decode_string=base64.b64decode,
                      **additional_args):
        """Create an instance from a JSON style dict.

        Instantiate this class with parameters specified by the dict.

        This method takes the following arguments.

        =============== =====================================================
        Argument        Descrpition
        =============== =====================================================
        dict\_          A dictionary which describes the parameters.
                        For example, {"Param1": 100, "Param2": 200}
        decode_string   (Optional) specify how to decode strings.
                        The default is base64.
                        This argument is used only for attributes which don't
                        have explicit type annotations in _TYPE class
                        attribute.
        additional_args (Optional) Additional kwargs for constructor.
        =============== =====================================================
        """
        decode = lambda k, x: cls._decode_value(k, x, decode_string)
        kwargs = cls._restore_args(_mapdict_kv(decode, dict_))
        try:
            return cls(**dict(kwargs, **additional_args))
        except TypeError:
            #debug
            print "CLS", cls
            print "ARG", dict_
            print "KWARG", kwargs
            raise

    @classmethod
    def set_classes(cls, registered_dict):
        cls._class_prefixes.extend([v.__name__ for v in
                                    registered_dict.values()])

def obj_python_attrs(msg_):
    """iterate object attributes for stringify purposes
    """

    # a special case for namedtuple which seems widely used in
    # ofp parser implementations.
    if hasattr(msg_, '_fields'):
        for k in msg_._fields:
            yield(k, getattr(msg_, k))
        return
    base = getattr(msg_, '_base_attributes', [])
    for k, v in inspect.getmembers(msg_):
        if k.startswith('_'):
            continue
        if callable(v):
            continue
        if k in base:
            continue
        if hasattr(msg_.__class__, k):
            continue
        yield (k, v)

def obj_attrs(msg_):
    """similar to obj_python_attrs() but deals with python reserved keywords
    """

    if isinstance(msg_, StringifyMixin):
        iter = msg_.stringify_attrs()
    else:
        # probably called by msg_str_attr
        iter = obj_python_attrs(msg_)
    for k, v in iter:
        if k.endswith('_') and k[:-1] in _RESERVED_KEYWORD:
            # XXX currently only StringifyMixin has restoring logic
            assert isinstance(msg_, StringifyMixin)
            k = k[:-1]
        yield (k, v)


text:
use strict;
use warnings;
use AI::MXNet::Function::Parameters;
package AI::MXNet::Gluon::ModelZoo::Vision::VGG;
use AI::MXNet::Gluon::Mouse;
extends 'AI::MXNet::Gluon::HybridBlock';
use AI::MXNet::Base;

=head1 NAME

    AI::MXNet::Gluon::ModelZoo::Vision::VGG - VGG model from the "Very Deep Convolutional Networks for Large-Scale Image Recognition"
=cut

=head1 DESCRIPTION

    VGG model from the "Very Deep Convolutional Networks for Large-Scale Image Recognition"
    <https://arxiv.org/abs/1409.1556> paper.

    Parameters
    ----------
    layers : array ref of Int
        Numbers of layers in each feature block.
    filters : array ref of Int
        Numbers of filters in each feature block. List length should match the layers.
    classes : Int, default 1000
        Number of classification classes.
    batch_norm : Bool, default 0
        Use batch normalization.
=cut
method python_constructor_arguments() { [qw/layers filters classes batch_norm/] }
has ['layers',
     'filters']   => (is => 'ro', isa => 'ArrayRef[Int]', required => 1);
has  'classes'    => (is => 'ro', isa => 'Int', default => 1000);
has  'batch_norm' => (is => 'ro', isa => 'Bool', default => 0);

sub BUILD
{
    my $self = shift;
    assert(@{ $self->layers } == @{ $self->filters });
    $self->name_scope(sub {
        $self->features($self->_make_features());
        $self->features->add(nn->Dense(4096, activation=>'relu',
                                       weight_initializer=>'normal',
                                       bias_initializer=>'zeros'));
        $self->features->add(nn->Dropout(rate=>0.5));
        $self->features->add(nn->Dense(4096, activation=>'relu',
                                       weight_initializer=>'normal',
                                       bias_initializer=>'zeros'));
        $self->features->add(nn->Dropout(rate=>0.5));
        $self->output(nn->Dense($self->classes,
                                   weight_initializer=>'normal',
                                   bias_initializer=>'zeros'));
    });
}

method _make_features()
{
    my $featurizer = nn->HybridSequential(prefix=>'');
    for(enumerate($self->layers))
    {
        my ($i, $num) = @$_;
        for(0..$num-1)
        {
            $featurizer->add(
                nn->Conv2D(
                    $self->filters->[$i], kernel_size => 3, padding => 1,
                    weight_initializer => mx->init->Xavier(
                        rnd_type    => 'gaussian',
                        factor_type => 'out',
                        magnitude   => 2
                    ),
                    bias_initializer=>'zeros'
                )
            );
            if($self->batch_norm)
            {
                $featurizer->add(nn->BatchNorm());
            }
            $featurizer->add(nn->Activation('relu'));
        }
        $featurizer->add(nn->MaxPool2D(strides=>2));
    }
    return $featurizer;
}

method hybrid_forward(GluonClass $F, GluonInput $x)
{
    $x = $self->features->($x);
    $x = $self->output->($x);
    return $x;
}

package AI::MXNet::Gluon::ModelZoo::Vision;

# Specification
my %vgg_spec = (
    11 => [[1, 1, 2, 2, 2], [64, 128, 256, 512, 512]],
    13 => [[2, 2, 2, 2, 2], [64, 128, 256, 512, 512]],
    16 => [[2, 2, 3, 3, 3], [64, 128, 256, 512, 512]],
    19 => [[2, 2, 4, 4, 4], [64, 128, 256, 512, 512]]
);

=head2 get_vgg

    VGG model from the "Very Deep Convolutional Networks for Large-Scale Image Recognition"
    <https://arxiv.org/abs/1409.1556> paper.

    Parameters
    ----------
    $num_layers : Int
        Number of layers for the variant of densenet. Options are 11, 13, 16, 19.
    :$pretrained : Bool, default 0
        Whether to load the pretrained weights for model.
    :$ctx : AI::MXNet::Context, default AI::MXNet::Context->cpu
        The context in which to load the pretrained weights.
    :$root : Str, default '~/.mxnet/models'
        Location for keeping the model parameters.
=cut

method get_vgg(
    Int $num_layers, Bool :$pretrained=0, AI::MXNet::Context :$ctx=AI::MXNet::Context->cpu(),
    Str :$root='~/.mxnet/models', Int :$classes=1000, Bool :$batch_norm=0
)
{
    my ($layers, $filters) = @{ $vgg_spec{$num_layers} };
    my $net = AI::MXNet::Gluon::ModelZoo::Vision::VGG->new($layers, $filters, $classes, $batch_norm);
    if($pretrained)
    {
        $net->load_parameters(
            AI::MXNet::Gluon::ModelZoo::ModelStore->get_model_file(
                "vgg$num_layers".($batch_norm ? '_bn' : ''),
                root=>$root
            ),
            ctx=>$ctx
        );
    }
    return $net;
}

=head2 vgg11

    VGG-11 model from the "Very Deep Convolutional Networks for Large-Scale Image Recognition"
    <https://arxiv.org/abs/1409.1556> paper.

    Parameters
    ----------
    :$pretrained : Bool, default 0
        Whether to load the pretrained weights for model.
    :$ctx : AI::MXNet::Context, default AI::MXNet::Context->cpu
        The context in which to load the pretrained weights.
    :$root : Str, default '~/.mxnet/models'
        Location for keeping the model parameters.
=cut

method vgg11(%kwargs)
{
    return __PACKAGE__->get_vgg(11, %kwargs);
}

=head2 vgg13

    VGG-13 model from the "Very Deep Convolutional Networks for Large-Scale Image Recognition"
    <https://arxiv.org/abs/1409.1556> paper.

    Parameters
    ----------
    :$pretrained : Bool, default 0
        Whether to load the pretrained weights for model.
    :$ctx : AI::MXNet::Context, default AI::MXNet::Context->cpu
        The context in which to load the pretrained weights.
    :$root : Str, default '~/.mxnet/models'
        Location for keeping the model parameters.
=cut

method vgg13(%kwargs)
{
    return __PACKAGE__->get_vgg(13, %kwargs);
}

=head2 vgg16

    VGG-16 model from the "Very Deep Convolutional Networks for Large-Scale Image Recognition"
    <https://arxiv.org/abs/1409.1556> paper.

    Parameters
    ----------
    :$pretrained : Bool, default 0
        Whether to load the pretrained weights for model.
    :$ctx : AI::MXNet::Context, default AI::MXNet::Context->cpu
        The context in which to load the pretrained weights.
    :$root : Str, default '~/.mxnet/models'
        Location for keeping the model parameters.
=cut

method vgg16(%kwargs)
{
    return __PACKAGE__->get_vgg(16, %kwargs);
}

=head2 vgg19

    VGG-19 model from the "Very Deep Convolutional Networks for Large-Scale Image Recognition"
    <https://arxiv.org/abs/1409.1556> paper.

    Parameters
    ----------
    :$pretrained : Bool, default 0
        Whether to load the pretrained weights for model.
    :$ctx : AI::MXNet::Context, default AI::MXNet::Context->cpu
        The context in which to load the pretrained weights.
    :$root : Str, default '~/.mxnet/models'
        Location for keeping the model parameters.
=cut

method vgg19(%kwargs)
{
    return __PACKAGE__->get_vgg(19, %kwargs);
}

=head2 vgg11_bn

    VGG-11 model with batch normalization from the "Very Deep Convolutional Networks for Large-Scale Image Recognition"
    <https://arxiv.org/abs/1409.1556> paper.

    Parameters
    ----------
    :$pretrained : Bool, default 0
        Whether to load the pretrained weights for model.
    :$ctx : AI::MXNet::Context, default AI::MXNet::Context->cpu
        The context in which to load the pretrained weights.
    :$root : Str, default '~/.mxnet/models'
        Location for keeping the model parameters.
=cut

method vgg11_bn(%kwargs)
{
    $kwargs{batch_norm} = 1;
    return __PACKAGE__->get_vgg(11, %kwargs);
}

=head2 vgg13_bn

    VGG-13 model with batch normalization from the "Very Deep Convolutional Networks for Large-Scale Image Recognition"
    <https://arxiv.org/abs/1409.1556> paper.

    Parameters
    ----------
    :$pretrained : Bool, default 0
        Whether to load the pretrained weights for model.
    :$ctx : AI::MXNet::Context, default AI::MXNet::Context->cpu
        The context in which to load the pretrained weights.
    :$root : Str, default '~/.mxnet/models'
        Location for keeping the model parameters.
=cut

method vgg13_bn(%kwargs)
{
    $kwargs{batch_norm} = 1;
    return __PACKAGE__->get_vgg(13, %kwargs);
}

=head2 vgg16_bn

    VGG-16 model with batch normalization from the "Very Deep Convolutional Networks for Large-Scale Image Recognition"
    <https://arxiv.org/abs/1409.1556> paper.

    Parameters
    ----------
    :$pretrained : Bool, default 0
        Whether to load the pretrained weights for model.
    :$ctx : AI::MXNet::Context, default AI::MXNet::Context->cpu
        The context in which to load the pretrained weights.
    :$root : Str, default '~/.mxnet/models'
        Location for keeping the model parameters.
=cut

method vgg16_bn(%kwargs)
{
    $kwargs{batch_norm} = 1;
    return __PACKAGE__->get_vgg(16, %kwargs);
}

=head2 vgg19_bn

    VGG-19 model with batch normalization from the "Very Deep Convolutional Networks for Large-Scale Image Recognition"
    <https://arxiv.org/abs/1409.1556> paper.

    Parameters
    ----------
    :$pretrained : Bool, default 0
        Whether to load the pretrained weights for model.
    :$ctx : AI::MXNet::Context, default AI::MXNet::Context->cpu
        The context in which to load the pretrained weights.
    :$root : Str, default '~/.mxnet/models'
        Location for keeping the model parameters.
=cut

method vgg19_bn(%kwargs)
{
    $kwargs{batch_norm} = 1;
    return __PACKAGE__->get_vgg(19, %kwargs);
}

1;


text:
module Terraforming
  module Resource
    class RouteTable
      include Terraforming::Util

      def self.tf(client: Aws::EC2::Client.new)
        self.new(client).tf
      end

      def self.tfstate(client: Aws::EC2::Client.new)
        self.new(client).tfstate
      end

      def initialize(client)
        @client = client
      end

      def tf
        apply_template(@client, "tf/route_table")
      end

      def tfstate
        route_tables.inject({}) do |resources, route_table|
          attributes = {
            "id" => route_table.route_table_id,
            "vpc_id" => route_table.vpc_id,
          }

          attributes.merge!(tags_attributes_of(route_table))
          attributes.merge!(routes_attributes_of(route_table))
          attributes.merge!(propagating_vgws_attributes_of(route_table))

          resources["aws_route_table.#{module_name_of(route_table)}"] = {
            "type" => "aws_route_table",
            "primary" => {
              "id" => route_table.route_table_id,
              "attributes" => attributes
            }
          }

          resources
        end
      end

      private

      def routes_of(route_table)
        route_table.routes.reject do |route|
          route.gateway_id.to_s == 'local' ||
            route.origin.to_s == 'EnableVgwRoutePropagation' ||
            route.destination_prefix_list_id
        end
      end

      def module_name_of(route_table)
        normalize_module_name(name_from_tag(route_table, route_table.route_table_id))
      end

      def route_tables
        @client.describe_route_tables.map(&:route_tables).flatten
      end

      def routes_attributes_of(route_table)
        routes = routes_of(route_table)
        attributes = { "route.#" => routes.length.to_s }

        routes.each do |route|
          attributes.merge!(route_attributes_of(route))
        end

        attributes
      end

      def route_attributes_of(route)
        hashcode = route_hashcode_of(route)
        attributes = {
          "route.#{hashcode}.cidr_block" => route.destination_cidr_block.to_s,
          "route.#{hashcode}.gateway_id" => route.gateway_id.to_s,
          "route.#{hashcode}.instance_id" => route.instance_id.to_s,
          "route.#{hashcode}.network_interface_id" => route.network_interface_id.to_s,
          "route.#{hashcode}.vpc_peering_connection_id" => route.vpc_peering_connection_id.to_s
        }

        attributes
      end

      def route_hashcode_of(route)
        string = "#{route.destination_cidr_block}-#{route.gateway_id}-"
        instance_set = !route.instance_id.nil? && route.instance_id != ''

        string << route.instance_id.to_s if instance_set
        string << route.vpc_peering_connection_id.to_s
        string << route.network_interface_id.to_s unless instance_set

        Zlib.crc32(string)
      end

      def propagaving_vgws_of(route_table)
        route_table.propagating_vgws.map(&:gateway_id).map(&:to_s)
      end

      def propagating_vgws_attributes_of(route_table)
        vgws = propagaving_vgws_of(route_table)
        attributes = { "propagating_vgws.#" => vgws.length.to_s }

        vgws.each do |gateway_id|
          hashcode = Zlib.crc32(gateway_id)
          attributes["propagating_vgws.#{hashcode}"] = gateway_id
        end

        attributes
      end

      def tags_attributes_of(route_table)
        tags = route_table.tags
        attributes = { "tags.#" => tags.length.to_s }
        tags.each { |tag| attributes["tags.#{tag.key}"] = tag.value }
        attributes
      end
    end
  end
end


text:
<?php

use yii\db\Schema;
use yii\db\Expression;
use yii\db\Migration;
use common\modules\user\models\Role;

class m141105_184851_user_roles extends Migration
{
    public function safeUp()
    {
        $this->update(Role::tableName(), ['name'=>'Customer'], 'name = :name', [':name'=>'User']);
        //$this->insert(Role::tableName(), ['name'=>'Performer', 'create_time'=>date('Y-m-d H:i:s')]);
        $this->insert(Role::tableName(), ['name'=>'Performer', 'create_time'=>new Expression('NOW()')]);
    }

    public function down()
    {
        $this->update(Role::tableName(), ['name'=>'User'], 'name = :name', [':name'=>'Customer']);
        $this->delete(Role::tableName(), 'name = :name', [':name'=>'Performer']);
    }
}


text:
package org.softeg.slartus.forpdacommon;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

/**
 * Created by slinkin on 26.08.13.
 */
public class Functions {
    public static SimpleDateFormat dateFormat = new SimpleDateFormat("dd.MM.yyyy");
    public static SimpleDateFormat parseDateTimeFormat = new SimpleDateFormat("dd.MM.yyyy, HH:mm");

    public static String getToday() {
        GregorianCalendar nowCalendar = new GregorianCalendar();
        return dateFormat.format(nowCalendar.getTime());
    }

    public static String getYesterToday() {
        GregorianCalendar nowCalendar = new GregorianCalendar();
        nowCalendar.add(Calendar.DAY_OF_MONTH, -1);
        return dateFormat.format(nowCalendar.getTime());
    }

    public static String getForumDateTime(Date date) {

        if (date == null) return "";
        return parseDateTimeFormat.format(date);
    }

    public static String getNewsDateTime(Date date) {

        if (date == null) return "";
        return dateFormat.format(date);
    }

    public static Date parseForumDateTime(String dateTime, String today, String yesterday) {
        try {
            Date res = parseDateTimeFormat.parse(dateTime.replace("Сегодня", today).replace("Вчера", yesterday));

            Calendar calendar = new GregorianCalendar();
            calendar.setTime(res);
            int year = calendar.get(Calendar.YEAR);
            if (year < 100)
                calendar.set(Calendar.YEAR, 2000 + year);
            return calendar.getTime();
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }
}