text:
  Louvigné est
       un village
       géographiquement positionné dans le département de Mayenne en Pays de la Loire. On dénombrait 799 habitants en 2008.

La commune compte quelques  équipements, elle dispose, entre autres, de un terrain de tennis, un terrain de sport et une boucle de randonnée.

À coté de Louvigné sont positionnées géographiquement les communes de
Bazougers localisée à 5 km, 976 habitants,
Bonchamp-lès-Laval localisée à 5 km, 5 381 habitants,
Argentré située à 3 km, 2 480 habitants,
Parné-sur-Roc située à 6 km, 1 174 habitants,
La Chapelle-Anthenaise localisée à 8 km, 859 habitants,
Saint-Céneré à 7 km, 441 habitants,
 entre autres. De plus, Louvigné est située à seulement dix km de Laval.

Si vous pensez emmenager à Louvigné, vous pourrez facilement trouver une maison à vendre.

À Louvigné, la valorisation moyenne à la vente d'un appartement s'évalue à 1 584 € du m² en vente. Le prix moyen d'une maison à l'achat se situe à 1 447 € du m². À la location la valorisation moyenne se situe à 6,91 € du m² mensuel.

Le parc d'habitations, à Louvigné, était réparti en 2011 en un appartements et 405 maisons soit
 un marché relativement équilibré.

redpajama_set_name: RedPajamaGithub


text:
typedef struct Nest_CompilerModule Nest_CompilerModule;

/// Getter for the LLVMBackend module
Nest_CompilerModule* getLLVMBackendModule();


text:
package commands

type CmdSwitchMultilevel struct {
	node  byte
	level byte
}

func NewSwitchMultilevel() *CmdSwitchMultilevel {

	return &CmdSwitchMultilevel{}
}

func (c *CmdSwitchMultilevel) SetValue(v float64) *CmdSwitchMultilevel {
	if v < 1 {
		v = 0
	}
	if v > 99 {
		v = 99
	}
	// TODO: Round to integer first to fix precision error
	c.level = byte(v)
	return c
}
func (c *CmdSwitchMultilevel) SetNode(n int) *CmdSwitchMultilevel {
	c.node = byte(n)
	return c
}

func (c *CmdSwitchMultilevel) Encode() []byte {
	return []byte{
		0x13,             // SEND ZW
		c.node,           // NOD ID
		0x03,             // length
		SwitchMultilevel, // command class id
		0x01,             // set
		c.level,          // value
		0x25,             // transmit options
	}
}


text:
import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;
import javax.servlet.ServletRequestAttributeEvent;
import javax.servlet.ServletRequestAttributeListener;
import javax.servlet.annotation.WebServlet;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebListener
@WebServlet(urlPatterns = "/")
public class app extends HttpServlet implements
    ServletRequestListener,
    ServletRequestAttributeListener
{
    private static String request_initialized = "";
    private static String request_destroyed = "";
    private static String attribute_added = "";
    private static String attribute_removed = "";
    private static String attribute_replaced = "";

    @Override
    public void requestInitialized(ServletRequestEvent sre)
    {
        HttpServletRequest r = (HttpServletRequest) sre.getServletRequest();

        request_initialized = r.getRequestURI();
    }

    @Override
    public void requestDestroyed(ServletRequestEvent sre)
    {
        HttpServletRequest r = (HttpServletRequest) sre.getServletRequest();

        request_destroyed = r.getRequestURI();

        attribute_added = "";
        attribute_removed = "";
        attribute_replaced = "";
    }

    @Override
    public void attributeAdded(ServletRequestAttributeEvent event)
    {
        attribute_added += event.getName() + "=" + event.getValue() + ";";
    }

    @Override
    public void attributeRemoved(ServletRequestAttributeEvent event)
    {
        attribute_removed += event.getName() + "=" + event.getValue() + ";";
    }

    @Override
    public void attributeReplaced(ServletRequestAttributeEvent event)
    {
        attribute_replaced += event.getName() + "=" + event.getValue() + ";";
    }

    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException
    {
        request.setAttribute("var", request.getParameter("var1"));
        request.setAttribute("var", request.getParameter("var2"));
        request.setAttribute("var", request.getParameter("var3"));

        response.addHeader("X-Request-Initialized", request_initialized);
        response.addHeader("X-Request-Destroyed", request_destroyed);
        response.addHeader("X-Attr-Added", attribute_added);
        response.addHeader("X-Attr-Removed", attribute_removed);
        response.addHeader("X-Attr-Replaced", attribute_replaced);
    }
}


text:
using namespace std;

namespace lomse
{

//=======================================================================================
// GmoObj implementation
//=======================================================================================

//association object-type <-> object-name
static std::map<int, std::string> m_typeToName;
static bool m_fNamesLoaded = false;
static string m_unknown = "unknown";

//---------------------------------------------------------------------------------------
GmoObj::GmoObj(int objtype, ImoObj* pCreatorImo)
    : m_objtype(objtype)
    , m_origin(0.0f, 0.0f)
    , m_size(0.0f, 0.0f)
    , m_flags(k_dirty | k_add_to_vprofile)
    , m_pCreatorImo(pCreatorImo)
    , m_pParentBox(nullptr)
{
}

//---------------------------------------------------------------------------------------
GmoObj::~GmoObj()
{
}

//---------------------------------------------------------------------------------------
void GmoObj::set_origin(UPoint& pos)
{
    set_origin(pos.x, pos.y);
}

//---------------------------------------------------------------------------------------
void GmoObj::set_origin(const UPoint& pos)
{
    set_origin(pos.x, pos.y);
}

//---------------------------------------------------------------------------------------
void GmoObj::set_origin(LUnits xLeft, LUnits yTop)
{
    m_origin.x = xLeft;
    m_origin.y = yTop;
}

//---------------------------------------------------------------------------------------
void GmoObj::set_left(LUnits xLeft)
{
    set_origin(xLeft, m_origin.y);
}

//---------------------------------------------------------------------------------------
void GmoObj::set_top(LUnits yTop)
{
    set_origin(m_origin.x, yTop);
}

//---------------------------------------------------------------------------------------
URect GmoObj::get_bounds()
{
    return URect(m_origin.x, m_origin.y, m_size.width, m_size.height);
}

//---------------------------------------------------------------------------------------
bool GmoObj::bounds_contains_point(UPoint& p)
{
    return get_bounds().contains(p);
}

//---------------------------------------------------------------------------------------
void GmoObj::shift_origin(const USize& shift)
{
    m_origin.x += shift.width;
    m_origin.y += shift.height;
}

//---------------------------------------------------------------------------------------
void GmoObj::dump(ostream& outStream, int level)
{
    std::ios_base::fmtflags f( outStream.flags() );  //save formating options

    outStream << setw(level*3) << level << " [" << setw(3) << m_objtype << "] "
              << setw(15) << setfill(' ') << get_name(m_objtype)
              << fixed << setprecision(2)
              << setw(10) << round_half_up(m_origin.x) << ", "
              << setw(10) << round_half_up(m_origin.y) << ", "
              << setw(10) << round_half_up(m_size.width) << ", "
              << setw(10) << round_half_up(m_size.height) << endl;

    outStream.flags( f );  //restore formating options
}

//---------------------------------------------------------------------------------------
const string& GmoObj::get_name(int objtype)
{
    if (!m_fNamesLoaded)
    {
        m_typeToName[k_box]                     = "box (A)";
        m_typeToName[k_box_control]             = "box-control";
        m_typeToName[k_box_document]            = "box-document";
        m_typeToName[k_box_doc_page]            = "box-doc-page";
        m_typeToName[k_box_doc_page_content]    = "box-docpg-cont.";
        m_typeToName[k_box_inline]              = "box-inline";
        m_typeToName[k_box_link]                = "box-link";
        m_typeToName[k_box_paragraph]           = "box-paragraph";
        m_typeToName[k_box_score_page]          = "box-score-page";
        m_typeToName[k_box_slice]               = "box-slice";
        m_typeToName[k_box_slice_instr]         = "box-slice-intr";
        m_typeToName[k_box_slice_staff]         = "box-slice-staff";
        m_typeToName[k_box_system]              = "box-system";
        m_typeToName[k_box_table]               = "box-table";
        m_typeToName[k_box_table_rows]          = "box-table-rows";

        // shapes
        m_typeToName[k_shape]                   = "shape (A)";
        m_typeToName[k_shape_accidentals]       = "accidentals";
        m_typeToName[k_shape_accidental_sign]   = "accidental-sign";
        m_typeToName[k_shape_arpeggio]          = "arpeggio";
        m_typeToName[k_shape_articulation]      = "articulation";
        m_typeToName[k_shape_barline]           = "barline";
        m_typeToName[k_shape_beam]              = "beam";
        m_typeToName[k_shape_brace]             = "brace";
        m_typeToName[k_shape_bracket]           = "bracket";
        m_typeToName[k_shape_clef]              = "clef";
        m_typeToName[k_shape_coda_segno]        = "coda-segno";
        m_typeToName[k_shape_debug]             = "shape-debug";
        m_typeToName[k_shape_dot]               = "dot";
        m_typeToName[k_shape_dynamics_mark]     = "dynamics-mark";
        m_typeToName[k_shape_fermata]           = "fermata";
        m_typeToName[k_shape_fingering_box]     = "fingering-box";
        m_typeToName[k_shape_fingering]         = "fingering";
        m_typeToName[k_shape_flag]              = "flag";
        m_typeToName[k_shape_grace_stroke]      = "grace-stroke";
        m_typeToName[k_shape_image]             = "image";
        m_typeToName[k_shape_invisible]         = "invisible";
        m_typeToName[k_shape_key_signature]     = "key";
        m_typeToName[k_shape_line]              = "line";
        m_typeToName[k_shape_lyrics]            = "lyrics";
        m_typeToName[k_shape_metronome_glyph]   = "metronome-glyph";
        m_typeToName[k_shape_metronome_mark]    = "metronome-mark";
        m_typeToName[k_shape_note]              = "note";
        m_typeToName[k_shape_chord_base_note]   = "chord-base-note";
        m_typeToName[k_shape_notehead]          = "notehead";
        m_typeToName[k_shape_octave_shift]      = "octave-shift";
        m_typeToName[k_shape_octave_glyph]      = "octave-glyph";
        m_typeToName[k_shape_ornament]          = "ornament";
        m_typeToName[k_shape_pedal_glyph]       = "pedal-glyph";
        m_typeToName[k_shape_pedal_line]        = "pedal-line";
        m_typeToName[k_shape_rectangle]         = "rectangle";
        m_typeToName[k_shape_rest]              = "rest";
        m_typeToName[k_shape_rest_glyph]        = "rest-glyph";
        m_typeToName[k_shape_slur]              = "slur";
        m_typeToName[k_shape_stem]              = "stem";
        m_typeToName[k_shape_squared_bracket]   = "squared-bracket";
        m_typeToName[k_shape_staff]             = "staff";
        m_typeToName[k_shape_technical]         = "technical";
        m_typeToName[k_shape_text]              = "text";
        m_typeToName[k_shape_text_box]          = "text-box";
        m_typeToName[k_shape_time_signature]    = "time";
        m_typeToName[k_shape_tie]               = "tie";
        m_typeToName[k_shape_time_signature_glyph]
                                                = "time-glyph";
        m_typeToName[k_shape_tuplet]            = "tuplet";
        m_typeToName[k_shape_volta_bracket]     = "volta-bracket";
        m_typeToName[k_shape_word]              = "word";
        m_typeToName[k_shape_wedge]             = "wedge";

        m_fNamesLoaded = true;
    }

	map<int, std::string>::const_iterator it = m_typeToName.find( objtype );
	if (it != m_typeToName.end())
		return it->second;
    else
        return m_unknown;
}

//---------------------------------------------------------------------------------------
void GmoObj::set_dirty(bool dirty)
{
    if (dirty)
    {
        m_flags |= k_dirty;
        propagate_dirty();
    }
    else
        m_flags &= ~k_dirty;
}

//---------------------------------------------------------------------------------------
void GmoObj::set_children_dirty(bool value)
{
    value ? m_flags |= k_children_dirty : m_flags &= ~k_children_dirty;
}

//---------------------------------------------------------------------------------------
void GmoObj::propagate_dirty()
{
    if (m_pParentBox)
    {
        m_pParentBox->set_children_dirty(true);
        m_pParentBox->propagate_dirty();
    }

    if (this->is_box_document())
    {
        GmoBoxDocument* pBox = static_cast<GmoBoxDocument*>(this);
        pBox->get_graphic_model()->set_modified(true);
    }
}

//---------------------------------------------------------------------------------------
GmoRef GmoObj::get_ref()
{
    if (this->is_box())
    {
        ImoObj* pImo = get_creator_imo();
        if (pImo)
        {
            if (this->is_box_control() || pImo->is_mouse_over_generator())
            {
                ImoId id = pImo->get_id();
                ImoId idg = 0;
                if (is_box_control())
                {
                    Control* pControl =
                        static_cast<GmoBoxControl*>(this)->get_creator_control();
                    idg = pControl->get_control_id();
                }

                return make_pair(id, idg);
            }
        }
    }
    return k_no_gmo_ref;
}

//---------------------------------------------------------------------------------------
GmoBoxDocPage* GmoObj::get_page_box()
{
    if (is_box_doc_page())
        return static_cast<GmoBoxDocPage*>(this);
    else
    {
        GmoBox* pParent = get_owner_box();
        return pParent->get_page_box();
    }
}

//---------------------------------------------------------------------------------------
const string GmoObj::get_notation_id(const string& prefix)
{
    ImoObj* pImo = get_creator_imo();
    if (pImo)
    {
        stringstream ss;
        ss << "m" << pImo->get_id();
        if (!prefix.empty())
            ss << "-" << prefix;
        if (is_shape() && static_cast<GmoShape*>(this)->get_shape_id() != 0)
            ss << "-" << static_cast<GmoShape*>(this)->get_shape_id();
        return ss.str();
    }
    return string();
}

//---------------------------------------------------------------------------------------
const string GmoObj::get_notation_class()
{
    ImoObj* pImo = get_creator_imo();
    if (pImo)
        return pImo->get_name();

    return string();
}

//=======================================================================================
// GmoBox
//=======================================================================================
GmoBox::GmoBox(int objtype, ImoObj* pCreatorImo)
    : GmoObj(objtype, pCreatorImo)
    , m_uTopMargin(0.0f)
    , m_uBottomMargin(0.0f)
    , m_uLeftMargin(0.0f)
    , m_uRightMargin(0.0f)
{
}

//---------------------------------------------------------------------------------------
GmoBox::~GmoBox()
{
    delete_boxes();
    delete_shapes();
}

//---------------------------------------------------------------------------------------
void GmoBox::delete_boxes()
{
    std::vector<GmoBox*>::iterator it;
    for (it=m_childBoxes.begin(); it != m_childBoxes.end(); ++it)
        delete *it;
    m_childBoxes.clear();
}

//---------------------------------------------------------------------------------------
void GmoBox::delete_shapes()
{
    std::list<GmoShape*>::iterator it;
    for (it=m_shapes.begin(); it != m_shapes.end(); ++it)
        delete *it;
    m_shapes.clear();
}

//---------------------------------------------------------------------------------------
void GmoBox::add_child_box(GmoBox* child)
{
    m_childBoxes.push_back(child);
    child->set_owner_box(this);
}

//---------------------------------------------------------------------------------------
GmoBox* GmoBox::get_child_box(int i)  //i = 0..n-1
{
    if (i < get_num_boxes())
        return m_childBoxes[i];
    else
        return nullptr;
}

//---------------------------------------------------------------------------------------
void GmoBox::add_shape(GmoShape* shape, int layer)
{
    shape->set_layer(layer);
    shape->set_owner_box(this);
    m_shapes.push_back(shape);
}

//---------------------------------------------------------------------------------------
void GmoBox::add_shapes_to_tables_in(GmoBoxDocPage* pPage)
{
    std::list<GmoShape*>::iterator itS;
    for (itS=m_shapes.begin(); itS != m_shapes.end(); ++itS)
        pPage->add_to_tables(*itS);

    std::vector<GmoBox*>::iterator itB;
    for (itB=m_childBoxes.begin(); itB != m_childBoxes.end(); ++itB)
        (*itB)->add_shapes_to_tables_in(pPage);
}

//---------------------------------------------------------------------------------------
void GmoBox::add_shapes_to_tables()
{
    GmoBoxDocPage* pPage = get_parent_doc_page();
    GmoBox* pBox = this;        //gcc complains if next method is invoked directly
    pBox->add_shapes_to_tables_in(pPage);
}

//---------------------------------------------------------------------------------------
GmoBoxDocPage* GmoBox::get_parent_doc_page()
{
    if (this->is_box_doc_page())
        return dynamic_cast<GmoBoxDocPage*>(this);
    else
        return get_parent_box()->get_parent_doc_page();
}

//---------------------------------------------------------------------------------------
GraphicModel* GmoBox::get_graphic_model()
{
    GmoBox* pParent = get_parent_box();
    return (pParent == nullptr ? nullptr : pParent->get_graphic_model());
}

//---------------------------------------------------------------------------------------
GmoShape* GmoBox::get_shape(int i)  //i = 0..n-1
{
    std::list<GmoShape*>::iterator it = m_shapes.begin();
    for (; it != m_shapes.end() && i > 0; ++it, --i);
    if (it != m_shapes.end())
        return *it;
    else
        return nullptr;
}

//---------------------------------------------------------------------------------------
void GmoBox::set_flag_value(bool value, unsigned int flag)
{
    //set flag
    if (value)
        m_flags |= flag;
    else
        m_flags &= ~flag;

    //propagate to contained shapes
    std::list<GmoShape*>::iterator itS;
    for (itS=m_shapes.begin(); itS != m_shapes.end(); ++itS)
        (*itS)->set_flag_value(value, flag);

    //propagate to contained boxes
    std::vector<GmoBox*>::iterator itB;
    for (itB=m_childBoxes.begin(); itB != m_childBoxes.end(); ++itB)
        (*itB)->set_flag_value(value, flag);
}

//---------------------------------------------------------------------------------------
void GmoBox::on_draw(Drawer* pDrawer, RenderOptions& opt)
{
    draw_border(pDrawer, opt);
    draw_shapes(pDrawer, opt);

    //draw contained boxes
    std::vector<GmoBox*>::iterator it;
    for (it=m_childBoxes.begin(); it != m_childBoxes.end(); ++it)
        (*it)->on_draw(pDrawer, opt);
}

//---------------------------------------------------------------------------------------
void GmoBox::draw_shapes(Drawer* pDrawer, RenderOptions& opt)
{
    std::list<GmoShape*>::iterator itS;
    for (itS=m_shapes.begin(); itS != m_shapes.end(); ++itS)
        (*itS)->on_draw(pDrawer, opt);
}

//---------------------------------------------------------------------------------------
void GmoBox::draw_border(Drawer* pDrawer, RenderOptions& opt)
{
    ImoStyle* pStyle = get_style();
    if (pStyle && (pStyle->border_width_top() > 0.0f
                    || pStyle->border_width_bottom() > 0.0f
                    || pStyle->border_width_left() > 0.0f
                    || pStyle->border_width_right() > 0.0f) )
    {
        double xLeft = double(m_origin.x
                        + pStyle->margin_left());
        double yTop = double(m_origin.y
                        + pStyle->margin_top());
        double xRight = double(get_right()
                        - pStyle->margin_right());
        double yBottom = double(get_bottom()
                            - pStyle->margin_bottom());

        pDrawer->begin_path();
        pDrawer->fill( pStyle->background_color() );
        pDrawer->stroke( Color(0,0,0) );            //TODO: border color
        pDrawer->move_to(xLeft, yTop);

        //top border
        if (pStyle->border_width_top() > 0.0f)
        {
            pDrawer->stroke_width( pStyle->border_width_top() );
            pDrawer->hline_to(xRight);
        }
        else
            pDrawer->move_to(xRight, yTop);

        //right border
        if (pStyle->border_width_right() > 0.0f)
        {
            pDrawer->stroke_width( pStyle->border_width_right() );
            pDrawer->vline_to(yBottom);
        }
        else
            pDrawer->move_to(xRight, yBottom);

        //bottom border
        if (pStyle->border_width_bottom() > 0.0f)
        {
            pDrawer->stroke_width( pStyle->border_width_bottom() );
            pDrawer->hline_to(xLeft);
        }
        else
            pDrawer->move_to(xLeft, yBottom);

        //left border
        if (pStyle->border_width_left() > 0.0f)
        {
            pDrawer->stroke_width( pStyle->border_width_left() );
            pDrawer->vline_to(yTop);
        }

        pDrawer->end_path();
    }

    if (this->is_item_main_box() && opt.draw_focus_lines_on_boxes_flag == true)
    {
        double xorg = m_origin.x;
        double yorg = m_origin.y;
        Color color = opt.unfocussed_box_color;
        draw_box_bounds(pDrawer, xorg, yorg, color);
    }

    else if (must_draw_bounds(opt))
    {
        double xorg = m_origin.x;
        double yorg = m_origin.y;
        Color color = get_box_color();
        draw_box_bounds(pDrawer, xorg, yorg, color);
    }
}

//---------------------------------------------------------------------------------------
bool GmoBox::must_draw_bounds(RenderOptions& opt)
{
    return opt.must_draw_box_for( get_gmobj_type() );
}

//---------------------------------------------------------------------------------------
Color GmoBox::get_box_color()
{
    if (this->is_box_doc_page_content())
        return Color(255,255,0);    //yellow
    if (this->is_item_main_box())
        return Color(255,128,0);    //orange
    if (this->is_box_system())
        return Color(255,0,0);      //red
    if (this->is_box_slice())
        return Color(255,0,255);    //magenta
    if (this->is_box_slice_instr())
        return Color(0,0,255);      //blue
    return Color(0,255,0);          //green
}

//---------------------------------------------------------------------------------------
void GmoBox::draw_box_bounds(Drawer* pDrawer, double xorg, double yorg, Color& color)
{
    pDrawer->begin_path();
    pDrawer->fill( Color(255, 255, 255, 0) );     //background white transparent
    pDrawer->stroke( color );
    pDrawer->stroke_width(50.0);    //0.5 mm
    pDrawer->move_to(xorg, yorg);
    pDrawer->hline_to(xorg + get_width());
    pDrawer->vline_to(yorg + get_height());
    pDrawer->hline_to(xorg);
    pDrawer->vline_to(yorg);
    pDrawer->end_path();
}

//---------------------------------------------------------------------------------------
GmoBox* GmoBox::find_inner_box_at(LUnits x, LUnits y)
{
    URect bbox = get_bounds();
    if (bbox.contains(x, y))
    {
        std::vector<GmoBox*>::iterator it;
        for (it=m_childBoxes.begin(); it != m_childBoxes.end(); ++it)
        {
            GmoBox* pBox = (*it)->find_inner_box_at(x, y);
            if (pBox)
			    return pBox;
        }
        return this;
    }
    return nullptr;
}

//---------------------------------------------------------------------------------------
void GmoBox::shift_origin_and_content(const USize& shift)
{
    if (shift.width == 0.0f && shift.height == 0.0f) return;

    m_origin.x += shift.width;
    m_origin.y += shift.height;

    //shift contained boxes
    std::vector<GmoBox*>::iterator itB;
    for (itB=m_childBoxes.begin(); itB != m_childBoxes.end(); ++itB)
        (*itB)->shift_origin_and_content(shift);

    //shift contained shapes
    std::list<GmoShape*>::iterator itS;
    for (itS=m_shapes.begin(); itS != m_shapes.end(); ++itS)
        (*itS)->shift_origin(shift);
}

//---------------------------------------------------------------------------------------
void GmoBox::dump_boxes_shapes(ostream& outStream, int level)
{
    dump(outStream, level);

    dump_shapes(outStream, ++level);

    //dump contained boxes
    std::vector<GmoBox*>::iterator it;
    for (it=m_childBoxes.begin(); it != m_childBoxes.end(); ++it)
        (*it)->dump_boxes_shapes(outStream, level);
}

//---------------------------------------------------------------------------------------
void GmoBox::dump_shapes(ostream& outStream, int level)
{
    std::list<GmoShape*>::iterator itS;
    for (itS=m_shapes.begin(); itS != m_shapes.end(); ++itS)
        (*itS)->dump(outStream, level);
}

//---------------------------------------------------------------------------------------
LUnits GmoBox::get_content_top()
{
    ImoStyle* pStyle = get_style();
    if (pStyle)
        return get_top() + pStyle->margin_top()
                + pStyle->border_width_top()
                + pStyle->padding_top();
    else
        return get_top();
}

//---------------------------------------------------------------------------------------
LUnits GmoBox::get_content_left()
{
    ImoStyle* pStyle = get_style();
    if (pStyle)
        return get_left() + pStyle->margin_left()
                + pStyle->border_width_left()
                + pStyle->padding_left();
    else
        return get_left();
}

//---------------------------------------------------------------------------------------
LUnits GmoBox::get_content_width()
{
    ImoStyle* pStyle = get_style();
    if (pStyle)
        return get_width() - pStyle->margin_left()
                - pStyle->border_width_left()
                - pStyle->padding_left()
                - pStyle->margin_right()
                - pStyle->border_width_right()
                - pStyle->padding_right();
    else
        return get_width();
}

//---------------------------------------------------------------------------------------
LUnits GmoBox::get_content_height()
{
    ImoStyle* pStyle = get_style();
    if (pStyle)
        return get_height() - pStyle->margin_top()
                - pStyle->border_width_top()
                - pStyle->padding_top()
                - pStyle->margin_bottom()
                - pStyle->border_width_bottom()
                - pStyle->padding_bottom();
    else
        return get_height();
}

//---------------------------------------------------------------------------------------
ImoStyle* GmoBox::get_style()
{
    if (m_pCreatorImo && m_pCreatorImo->is_contentobj())
    {
        ImoContentObj* pImo = dynamic_cast<ImoContentObj*>(m_pCreatorImo);
        if (pImo)
            return pImo->get_style();
    }
    return nullptr;
}

//---------------------------------------------------------------------------------------
void GmoBox::add_boxes_to_controls_map(GraphicModel* pGM)
{
    pGM->add_to_map_ref_to_box(this);

    vector<GmoBox*>::iterator it;
    for (it = m_childBoxes.begin(); it != m_childBoxes.end(); ++it)
    {
        (*it)->add_boxes_to_controls_map(pGM);
    }
}

//---------------------------------------------------------------------------------------
void GmoBox::add_boxes_to_map_imo_to_box(GraphicModel* pGM)
{
    //filter out boxes for non-terminal elements
    if (this->is_box_control()
        || this->is_box_document()
        || this->is_box_doc_page()
        || this->is_box_doc_page_content()
        || this->is_box_paragraph()
        || this->is_box_score_page()
        || this->is_box_table()
       )
    {
        pGM->add_to_map_imo_to_box(this);

        vector<GmoBox*>::iterator it;
        for (it = m_childBoxes.begin(); it != m_childBoxes.end(); ++it)
        {
            (*it)->add_boxes_to_map_imo_to_box(pGM);
        }
    }
}

//=======================================================================================
// StaffObjShapeCursor
//=======================================================================================
StaffObjShapeCursor::StaffObjShapeCursor(GmoBox* pBox)
    : m_pCurrentBox(pBox), m_it(pBox->m_shapes.begin())
{
}

//---------------------------------------------------------------------------------------
StaffObjShapeCursor::StaffObjShapeCursor(GmoShape* pShape)
    : m_pCurrentBox(pShape->get_owner_box())
{
    std::list<GmoShape*>& shapes = m_pCurrentBox->m_shapes;
    m_it = std::find(shapes.begin(), shapes.end(), pShape);
}

//---------------------------------------------------------------------------------------
TimeUnits StaffObjShapeCursor::get_time() const
{
    return static_cast<ImoStaffObj*>(get_shape()->get_creator_imo())->get_time();
}

//---------------------------------------------------------------------------------------
bool StaffObjShapeCursor::next()
{
    ++m_it;
    return m_it != m_pCurrentBox->m_shapes.end() && (*m_it)->get_creator_imo()->is_staffobj();
}

//---------------------------------------------------------------------------------------
bool StaffObjShapeCursor::next(TimeUnits maxTime)
{
    if (!next())
        return false;

    //next() ensures that we have a staffobj shape
    ImoStaffObj* pSO = static_cast<ImoStaffObj*>(get_shape()->get_creator_imo());
    return pSO->get_time() <= maxTime;
}

//---------------------------------------------------------------------------------------
bool StaffObjShapeCursor::nextAfter(TimeUnits time)
{
    while (next())
    {
        //next() ensures that we have a staffobj shape
        ImoStaffObj* pSO = static_cast<ImoStaffObj*>(get_shape()->get_creator_imo());
        if (pSO->get_time() > time)
            return true;
    }

    return false;
}

//---------------------------------------------------------------------------------------
bool StaffObjShapeCursor::prev()
{
    if (m_it == m_pCurrentBox->m_shapes.begin())
        return false;

    --m_it;
    return (*m_it)->get_creator_imo()->is_staffobj();
}

//---------------------------------------------------------------------------------------
bool StaffObjShapeCursor::prev(TimeUnits minTime)
{
    if (!prev())
        return false;

    //prev() ensures that we have a staffobj shape
    ImoStaffObj* pSO = static_cast<ImoStaffObj*>(get_shape()->get_creator_imo());
    return pSO->get_time() >= minTime;
}

//---------------------------------------------------------------------------------------
bool StaffObjShapeCursor::prevBefore(TimeUnits time)
{
    while (prev())
    {
        //prev() ensures that we have a staffobj shape
        ImoStaffObj* pSO = static_cast<ImoStaffObj*>(get_shape()->get_creator_imo());
        if (pSO->get_time() < time)
            return true;
    }

    return false;
}

//=======================================================================================
// GmoLayer: helper class. A collection of GmoShape objects
//=======================================================================================

////to assign ID to user layers
//static long m_nLayerCounter = GmoShape::k_layer_user;

class GmoLayer
{
public:
    GmoLayer(int layer) : m_nLayerID(layer) {}
    ~GmoLayer() {}

    //void InsertShapeInLayer(GmoShape* pShape);
    //void RenderLayer(lmPaper* pPaper);
    //GmoObj* FindShapeAtPos(lmUPoint& uPoint, bool fSelectable);

    long m_nLayerID;
    std::list<GmoShape*> m_shapes;		//contained shapes, ordered by creation order
};

////---------------------------------------------------------------------------------------
//void GmoLayer::InsertShapeInLayer(GmoShape* pShape)
//{
//    //Algorithm: the sorted list is traversed in order to find the element which is
//    //greater than or equal to the object to be inserted.
//    //In the worst case, when the object to be inserted is larger than all of the
//    //objects already present in the list, the entire list needs to be traversed
//    //before doing the insertion. Therefore, the total running time for the insert
//    //operation is O(n).
//
//    if (m_shapes.empty())
//    {
//        //this is going to be the first element.
//        m_shapes.push_back(pShape);
//        return;
//    }
//
//    //there are elements. Find where to insert new item
//    std::list<GmoShape*>::iterator itCur;
//    for (itCur = m_shapes.begin(); itCur != m_shapes.end(); ++itCur)
//    {
//        if ((*itCur)->GetOrder() < pShape->GetOrder())
//            break;      //insertion point found
//    }
//
//    //position found: insert before itCur
//    if (itCur != m_shapes.end())
//        m_shapes.insert(itCur, pShape);
//    else
//        m_shapes.push_back(pShape);
//
//    return;
//
//    //std::list<GmoShape*>::iterator it = m_shapes.begin();
//    //for (; it != m_shapes.end() && (*it)->get_layer() <= layer; ++it);
//
//    //if (it == m_shapes.end())
//    //    m_shapes.push_back(shape);
//    //else
//    //    m_shapes.insert(it, shape);
//}
//
////---------------------------------------------------------------------------------------
//void GmoLayer::RenderLayer(lmPaper* pPaper)
//{
//    std::list<GmoShape*>::iterator it;
//    for (it = m_shapes.begin(); it != m_shapes.end(); ++it)
//    {
//        (*it)->Render(pPaper);
//    }
//}
//
////---------------------------------------------------------------------------------------
//GmoObj* GmoLayer::FindShapeAtPos(lmUPoint& uPoint, bool fSelectable)
//{
//    std::list<GmoShape*>::reverse_iterator it;
//    for (it = m_shapes.rbegin(); it != m_shapes.rend(); ++it)
//    {
//        bool fFound = (*it)->HitTest(uPoint);
//        if ( (fSelectable && (*it)->IsSelectable() && fFound) ||
//            (!fSelectable && fFound) )
//            return *it;
//    }
//    return nullptr;
//}

//=======================================================================================
// GmoBoxDocPage
//=======================================================================================
GmoBoxDocPage::GmoBoxDocPage(ImoObj* pCreatorImo)
    : GmoBox(GmoObj::k_box_doc_page, pCreatorImo)
    , m_numPage(1)
{
}

//---------------------------------------------------------------------------------------
void GmoBoxDocPage::on_draw(Drawer* pDrawer, RenderOptions& opt)
{
    if (pDrawer->accepts_id_class())
    {
        stringstream ss;
        ss << "page-" << m_numPage;
        pDrawer->start_simple_notation(get_notation_id(ss.str()), "background");
    }

    draw_page_background(pDrawer, opt);
    GmoBox::on_draw(pDrawer, opt);
}

//---------------------------------------------------------------------------------------
void GmoBoxDocPage::draw_page_background(Drawer* pDrawer, RenderOptions& UNUSED(opt))
{
    pDrawer->begin_path();
    pDrawer->fill( Color(255, 255, 255) );     //background white
    pDrawer->stroke( Color(255, 255, 255) );
    pDrawer->move_to(0.0, 0.0);
    pDrawer->hline_to(get_width());
    pDrawer->vline_to(get_height());
    pDrawer->hline_to(0.0);
    pDrawer->vline_to(0.0);
    pDrawer->end_path();
}

//---------------------------------------------------------------------------------------
void GmoBoxDocPage::add_to_tables(GmoShape* pShape)
{
    int layer = pShape->get_layer();
    std::list<GmoShape*>::iterator it;
    for (it = m_allShapes.begin(); it != m_allShapes.end(); ++it)
    {
        if ((*it)->get_layer() > layer)
            break;
    }

    if (it == m_allShapes.end())
        m_allShapes.push_back(pShape);
    else
        m_allShapes.insert(it, pShape);

    store_in_map_imo_shape(pShape);
}

//---------------------------------------------------------------------------------------
void GmoBoxDocPage::store_in_map_imo_shape(GmoShape* pShape)
{
    ImoObj* pImo = pShape->get_creator_imo();
    if (pImo)
    {
        GraphicModel* pModel = get_graphic_model();
        if (pModel)
            pModel->store_in_map_imo_shape(pImo, pShape);
    }
}

//---------------------------------------------------------------------------------------
GmoShape* GmoBoxDocPage::get_first_shape_for_layer(int layer)
{
    std::list<GmoShape*>::reverse_iterator it;
    for (it = m_allShapes.rbegin(); it != m_allShapes.rend(); ++it)
    {
        if ((*it)->get_layer() == layer)
            return *it;
    }
    return nullptr;
}

//---------------------------------------------------------------------------------------
GmoShape* GmoBoxDocPage::find_shape_at(LUnits x, LUnits y)
{
    std::list<GmoShape*>::reverse_iterator it;
    for (it = m_allShapes.rbegin(); it != m_allShapes.rend(); ++it)
    {
        if ((*it)->hit_test(x, y))
            return *it;
    }
    return nullptr;
}

//---------------------------------------------------------------------------------------
GmoShape* GmoBoxDocPage::find_shape_for_object(ImoStaffObj* pSO)
{
    std::list<GmoShape*>::iterator it;
    for (it = m_allShapes.begin(); it != m_allShapes.end(); ++it)
    {
        if ((*it)->was_created_by(pSO))
            return *it;
    }
    return nullptr;
}

//---------------------------------------------------------------------------------------
GmoObj* GmoBoxDocPage::hit_test(LUnits x, LUnits y)
{
    GmoObj* pShape = find_shape_at(x, y);
    if (pShape)
        return pShape;

    GmoBox* pBox = find_inner_box_at(x, y);
    if (pBox)
	    return pBox;

    return nullptr;
}

//---------------------------------------------------------------------------------------
void GmoBoxDocPage::select_objects_in_rectangle(SelectionSet* selection,
                                                const URect& selRect,
                                                unsigned UNUSED(flags))
{
    bool fSomethingSelected = false;
    std::list<GmoShape*>::reverse_iterator it;
    for (it = m_allShapes.rbegin(); it != m_allShapes.rend(); ++it)
    {
        URect bbox = (*it)->get_bounds();
        if (selRect.contains(bbox))
        {
            selection->add(*it);
            fSomethingSelected = true;
        }
    }

    //if no objects in rectangle try to select clicked object
    if (!fSomethingSelected)
    {
        GmoShape* pShape = find_shape_at(selRect.get_x(), selRect.get_y());
        if (pShape)
            selection->add(pShape);
    }

}

//=======================================================================================
// GmoBoxDocument
//=======================================================================================
GmoBoxDocument::GmoBoxDocument(GraphicModel* pGModel, ImoObj* pCreatorImo)
    : GmoBox(GmoObj::k_box_document, pCreatorImo)
    , m_pLastPage(nullptr)
    , m_pGModel(pGModel)
{
}

//---------------------------------------------------------------------------------------
GmoBoxDocPage* GmoBoxDocument::add_new_page()
{
    m_pLastPage = LOMSE_NEW GmoBoxDocPage(m_pCreatorImo);
    add_child_box(m_pLastPage);
    m_pLastPage->set_number(get_num_pages());
    return m_pLastPage;
}

//---------------------------------------------------------------------------------------
GmoBoxDocPage* GmoBoxDocument::get_page(int i)
{
    return dynamic_cast<GmoBoxDocPage*>(get_child_box(i));
}

//---------------------------------------------------------------------------------------
int GmoBoxDocument::get_page_number(GmoBoxDocPage* pBoxPage)
{
    vector<GmoBox*>& pages = get_child_boxes();
    int iMax = int(pages.size());
    for (int i=0; i < iMax; ++i)
    {
        if (pages[i] == pBoxPage)
            return i;
    }
    return -1;
}

//=======================================================================================
// GmoBoxDocPageContent
//=======================================================================================
GmoBoxDocPageContent::GmoBoxDocPageContent(ImoObj* pCreatorImo)
    : GmoBox(GmoObj::k_box_doc_page_content, pCreatorImo)
{
}

//=======================================================================================
// GmoBoxControl
//=======================================================================================
GmoBoxControl::GmoBoxControl(Control* ctrl, const UPoint& origin,
                             LUnits width, LUnits height, ImoStyle* style)
    : GmoBox(GmoObj::k_box_control, ctrl->get_owner_imo() )
    , m_pStyle(style)
    , m_pControl(ctrl)
{
    set_origin(origin);
    set_width(width);
    set_height(height);
}

//---------------------------------------------------------------------------------------
void GmoBoxControl::on_draw(Drawer* pDrawer, RenderOptions& opt)
{
    GmoBox::on_draw(pDrawer, opt);

    if (m_pControl)
        m_pControl->on_draw(pDrawer, opt);
}

//---------------------------------------------------------------------------------------
void GmoBoxControl::notify_event(SpEventInfo pEvent)
{
    if (m_pControl)
        m_pControl->handle_event(pEvent);
}

//=======================================================================================
// GmoBoxLink
//=======================================================================================
void GmoBoxLink::notify_event(SpEventInfo pEvent)
{
    if (pEvent->is_mouse_in_event())
    {
        LOMSE_LOG_DEBUG(Logger::k_events, "set hover true");
        set_hover(true);
        set_dirty(true);
    }
    else if (pEvent->is_mouse_out_event())
    {
        LOMSE_LOG_DEBUG(Logger::k_events, "set hover false");
        set_hover(false);
        set_dirty(true);
    }
    else if (pEvent->is_on_click_event())
    {
        LOMSE_LOG_ERROR("is_on_click_event: TODO");
        //AWARE: should not reach this point as click events on links
        //will be dispatched to the global handler.
        //TODO: GmoBoxLink::notify_event, on_click_event
//        m_visited = true;
//        m_prevColor = m_visitedColor;
    }
    else
    {
        LOMSE_LOG_DEBUG(Logger::k_events, "event ignored");
    }
}

//=======================================================================================
// ScoreStub implementation
//=======================================================================================
ScoreStub::ScoreStub(ImoScore* pScore)
    : m_scoreId(pScore->get_id())
{
    m_measures = LOMSE_NEW GmMeasuresTable(pScore);
}

//---------------------------------------------------------------------------------------
ScoreStub::~ScoreStub()
{
    delete m_measures;
}

//---------------------------------------------------------------------------------------
GmoBoxScorePage* ScoreStub::get_page_for(TimeUnits timepos)
{
    //find page with end time greater or equal than requested time

    int maxPage = int(m_pages.size());
    int i=0;
    for (; i < maxPage; ++i)
    {
//        LOMSE_LOG_DEBUG(Logger::k_events, "page %d. End time = %f",
//                        i, m_pages[i]->end_time());

        //BUG-BYPASS: first page could be empty when the score is embedded in a text and
        // space in current page is small. In these cases, an score page is allocated
        // at the end of current document page, but as there is not enough space for
        // the score, a new document page is created and a new score page is allocated.
        // This causes the previously allocated score page to remain without content.
        // This is a bug bypass. The real solution would be not to allocate the unused
        // page or to remove it from ScoreStub.
        if (m_pages[i]->get_num_systems() == 0)
            continue;

        if (is_lower_time(timepos, m_pages[i]->end_time()))
            break;
        else if(is_equal_time(timepos, m_pages[i]->end_time()))
        {
            //look in next page
            int iNext = i + 1;
            if (iNext < maxPage)
            {
                if (is_equal_time(timepos, m_pages[iNext]->start_time()))
                    ++i;
            }
            break;
        }
    }
    if (i == maxPage)
        return nullptr;
    else
        return m_pages[i];
}

}  //namespace lomse


text:
$ReceiveLocationName = "rlo_PickUpFiles_FILE"
Try
{
    #
    # Get the Recieve Location of the specified name and Disable
    #
    Write-Host "Retrieving the Receive Location " $ReceiveLocationName
    $nameFilter = "name='" + $ReceiveLocationName.ToString() + "'"
    $location = get-wmiobject msbts_receivelocation -Namespace 'root\MicrosoftBizTalkServer' -Filter $nameFilter

    #
    # Disable the Recieve Location
    #
    Write-Host "Disabling the Receive Location " $ReceiveLocationName
    $location.Disable()

    # OR

    #
    # Enable the Recieve Location
    #
    Write-Host "Enabling the Receive Location " $ReceiveLocationName
    $location.Enable()

    Write-Host "Finished"
}Catch
{
    Write-Host "An error occurred while attempting to disable/enable the receive location " $ReceiveLocationName
    Write-Host "ErrorMessage: " $_.Exception.Message
}


text:
import logging.handlers
import re
import sys
import types

from django.utils import six

from django_compat_patcher.deprecation import *

warnings.warn("django.utils.dictconfig will be removed in Django 1.9.",
              RemovedInDjango19Warning, stacklevel=2)

# This is a copy of the Python logging.config.dictconfig module,
# reproduced with permission. It is provided here for backwards
# compatibility for Python versions prior to 2.7.
#
# Copyright 2009-2010 by Vinay Sajip. All Rights Reserved.
#
# Permission to use, copy, modify, and distribute this software and its
# documentation for any purpose and without fee is hereby granted,
# provided that the above copyright notice appear in all copies and that
# both that copyright notice and this permission notice appear in
# supporting documentation, and that the name of Vinay Sajip
# not be used in advertising or publicity pertaining to distribution
# of the software without specific, written prior permission.
# VINAY SAJIP DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING
# ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL
# VINAY SAJIP BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR
# ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER
# IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

IDENTIFIER = re.compile('^[a-z_][a-z0-9_]*$', re.I)

def valid_ident(s):
    m = IDENTIFIER.match(s)
    if not m:
        raise ValueError('Not a valid Python identifier: %r' % s)
    return True

#
# This function is defined in logging only in recent versions of Python
#
try:
    from logging import _checkLevel
except ImportError:
    def _checkLevel(level):
        if isinstance(level, int):
            rv = level
        elif str(level) == level:
            if level not in logging._levelNames:
                raise ValueError('Unknown level: %r' % level)
            rv = logging._levelNames[level]
        else:
            raise TypeError('Level not an integer or a '
                            'valid string: %r' % level)
        return rv

# The ConvertingXXX classes are wrappers around standard Python containers,
# and they serve to convert any suitable values in the container. The
# conversion converts base dicts, lists and tuples to their wrapped
# equivalents, whereas strings which match a conversion format are converted
# appropriately.
#
# Each wrapper should have a configurator attribute holding the actual
# configurator to use for conversion.

class ConvertingDict(dict):
    """A converting dictionary wrapper."""

    def __getitem__(self, key):
        value = dict.__getitem__(self, key)
        result = self.configurator.convert(value)
        # If the converted value is different, save for next time
        if value is not result:
            self[key] = result
            if type(result) in (ConvertingDict, ConvertingList,
                                ConvertingTuple):
                result.parent = self
                result.key = key
        return result

    def get(self, key, default=None):
        value = dict.get(self, key, default)
        result = self.configurator.convert(value)
        # If the converted value is different, save for next time
        if value is not result:
            self[key] = result
            if type(result) in (ConvertingDict, ConvertingList,
                                ConvertingTuple):
                result.parent = self
                result.key = key
        return result

    def pop(self, key, default=None):
        value = dict.pop(self, key, default)
        result = self.configurator.convert(value)
        if value is not result:
            if type(result) in (ConvertingDict, ConvertingList,
                                ConvertingTuple):
                result.parent = self
                result.key = key
        return result

class ConvertingList(list):
    """A converting list wrapper."""

    def __getitem__(self, key):
        value = list.__getitem__(self, key)
        result = self.configurator.convert(value)
        # If the converted value is different, save for next time
        if value is not result:
            self[key] = result
            if type(result) in (ConvertingDict, ConvertingList,
                                ConvertingTuple):
                result.parent = self
                result.key = key
        return result

    def pop(self, idx=-1):
        value = list.pop(self, idx)
        result = self.configurator.convert(value)
        if value is not result:
            if type(result) in (ConvertingDict, ConvertingList,
                                ConvertingTuple):
                result.parent = self
        return result

class ConvertingTuple(tuple):
    """A converting tuple wrapper."""

    def __getitem__(self, key):
        value = tuple.__getitem__(self, key)
        result = self.configurator.convert(value)
        if value is not result:
            if type(result) in (ConvertingDict, ConvertingList,
                                ConvertingTuple):
                result.parent = self
                result.key = key
        return result

class BaseConfigurator(object):
    """
    The configurator base class which defines some useful defaults.
    """

    CONVERT_PATTERN = re.compile(r'^(?P<prefix>[a-z]+)://(?P<suffix>.*)$')

    WORD_PATTERN = re.compile(r'^\s*(\w+)\s*')
    DOT_PATTERN = re.compile(r'^\.\s*(\w+)\s*')
    INDEX_PATTERN = re.compile(r'^\[\s*(\w+)\s*\]\s*')
    DIGIT_PATTERN = re.compile(r'^\d+$')

    value_converters = {
        'ext': 'ext_convert',
        'cfg': 'cfg_convert',
    }

    # We might want to use a different one, e.g. importlib
    importer = __import__

    def __init__(self, config):
        self.config = ConvertingDict(config)
        self.config.configurator = self

    def resolve(self, s):
        """
        Resolve strings to objects using standard import and attribute
        syntax.
        """
        name = s.split('.')
        used = name.pop(0)
        try:
            found = self.importer(used)
            for frag in name:
                used += '.' + frag
                try:
                    found = getattr(found, frag)
                except AttributeError:
                    self.importer(used)
                    found = getattr(found, frag)
            return found
        except ImportError:
            e, tb = sys.exc_info()[1:]
            v = ValueError('Cannot resolve %r: %s' % (s, e))
            v.__cause__, v.__traceback__ = e, tb
            raise v

    def ext_convert(self, value):
        """Default converter for the ext:// protocol."""
        return self.resolve(value)

    def cfg_convert(self, value):
        """Default converter for the cfg:// protocol."""
        rest = value
        m = self.WORD_PATTERN.match(rest)
        if m is None:
            raise ValueError("Unable to convert %r" % value)
        else:
            rest = rest[m.end():]
            d = self.config[m.groups()[0]]
            # print d, rest
            while rest:
                m = self.DOT_PATTERN.match(rest)
                if m:
                    d = d[m.groups()[0]]
                else:
                    m = self.INDEX_PATTERN.match(rest)
                    if m:
                        idx = m.groups()[0]
                        if not self.DIGIT_PATTERN.match(idx):
                            d = d[idx]
                        else:
                            try:
                                n = int(idx)  # try as number first (most likely)
                                d = d[n]
                            except TypeError:
                                d = d[idx]
                if m:
                    rest = rest[m.end():]
                else:
                    raise ValueError('Unable to convert '
                                     '%r at %r' % (value, rest))
        # rest should be empty
        return d

    def convert(self, value):
        """
        Convert values to an appropriate type. dicts, lists and tuples are
        replaced by their converting alternatives. Strings are checked to
        see if they have a conversion format and are converted if they do.
        """
        if not isinstance(value, ConvertingDict) and isinstance(value, dict):
            value = ConvertingDict(value)
            value.configurator = self
        elif not isinstance(value, ConvertingList) and isinstance(value, list):
            value = ConvertingList(value)
            value.configurator = self
        elif not isinstance(value, ConvertingTuple) and \
                isinstance(value, tuple):
            value = ConvertingTuple(value)
            value.configurator = self
        elif isinstance(value, six.string_types):  # str for py3k
            m = self.CONVERT_PATTERN.match(value)
            if m:
                d = m.groupdict()
                prefix = d['prefix']
                converter = self.value_converters.get(prefix, None)
                if converter:
                    suffix = d['suffix']
                    converter = getattr(self, converter)
                    value = converter(suffix)
        return value

    def configure_custom(self, config):
        """Configure an object with a user-supplied factory."""
        c = config.pop('()')
        if not hasattr(c, '__call__') and hasattr(types, 'ClassType') and type(c) != types.ClassType:
            c = self.resolve(c)
        props = config.pop('.', None)
        # Check for valid identifiers
        kwargs = {k: config[k] for k in config if valid_ident(k)}
        result = c(**kwargs)
        if props:
            for name, value in props.items():
                setattr(result, name, value)
        return result

    def as_tuple(self, value):
        """Utility function which converts lists to tuples."""
        if isinstance(value, list):
            value = tuple(value)
        return value

class DictConfigurator(BaseConfigurator):
    """
    Configure logging using a dictionary-like object to describe the
    configuration.
    """

    def configure(self):
        """Do the configuration."""

        config = self.config
        if 'version' not in config:
            raise ValueError("dictionary doesn't specify a version")
        if config['version'] != 1:
            raise ValueError("Unsupported version: %s" % config['version'])
        incremental = config.pop('incremental', False)
        EMPTY_DICT = {}
        logging._acquireLock()
        try:
            if incremental:
                handlers = config.get('handlers', EMPTY_DICT)
                # incremental handler config only if handler name
                # ties in to logging._handlers (Python 2.7)
                if sys.version_info[:2] == (2, 7):
                    for name in handlers:
                        if name not in logging._handlers:
                            raise ValueError('No handler found with '
                                             'name %r' % name)
                        else:
                            try:
                                handler = logging._handlers[name]
                                handler_config = handlers[name]
                                level = handler_config.get('level', None)
                                if level:
                                    handler.setLevel(_checkLevel(level))
                            except StandardError as e:
                                raise ValueError('Unable to configure handler '
                                                 '%r: %s' % (name, e))
                loggers = config.get('loggers', EMPTY_DICT)
                for name in loggers:
                    try:
                        self.configure_logger(name, loggers[name], True)
                    except StandardError as e:
                        raise ValueError('Unable to configure logger '
                                         '%r: %s' % (name, e))
                root = config.get('root', None)
                if root:
                    try:
                        self.configure_root(root, True)
                    except StandardError as e:
                        raise ValueError('Unable to configure root '
                                         'logger: %s' % e)
            else:
                disable_existing = config.pop('disable_existing_loggers', True)

                logging._handlers.clear()
                del logging._handlerList[:]

                # Do formatters first - they don't refer to anything else
                formatters = config.get('formatters', EMPTY_DICT)
                for name in formatters:
                    try:
                        formatters[name] = self.configure_formatter(
                            formatters[name])
                    except StandardError as e:
                        raise ValueError('Unable to configure '
                                         'formatter %r: %s' % (name, e))
                # Next, do filters - they don't refer to anything else, either
                filters = config.get('filters', EMPTY_DICT)
                for name in filters:
                    try:
                        filters[name] = self.configure_filter(filters[name])
                    except StandardError as e:
                        raise ValueError('Unable to configure '
                                         'filter %r: %s' % (name, e))

                # Next, do handlers - they refer to formatters and filters
                # As handlers can refer to other handlers, sort the keys
                # to allow a deterministic order of configuration
                handlers = config.get('handlers', EMPTY_DICT)
                for name in sorted(handlers):
                    try:
                        handler = self.configure_handler(handlers[name])
                        handler.name = name
                        handlers[name] = handler
                    except StandardError as e:
                        raise ValueError('Unable to configure handler '
                                         '%r: %s' % (name, e))
                # Next, do loggers - they refer to handlers and filters

                # we don't want to lose the existing loggers,
                # since other threads may have pointers to them.
                # existing is set to contain all existing loggers,
                # and as we go through the new configuration we
                # remove any which are configured. At the end,
                # what's left in existing is the set of loggers
                # which were in the previous configuration but
                # which are not in the new configuration.
                root = logging.root
                existing = list(root.manager.loggerDict)
                # The list needs to be sorted so that we can
                # avoid disabling child loggers of explicitly
                # named loggers. With a sorted list it is easier
                # to find the child loggers.
                existing.sort()
                # We'll keep the list of existing loggers
                # which are children of named loggers here...
                child_loggers = []
                # now set up the new ones...
                loggers = config.get('loggers', EMPTY_DICT)
                for name in loggers:
                    if name in existing:
                        i = existing.index(name)
                        prefixed = name + "."
                        pflen = len(prefixed)
                        num_existing = len(existing)
                        i = i + 1  # look at the entry after name
                        while (i < num_existing) and \
                                (existing[i][:pflen] == prefixed):
                            child_loggers.append(existing[i])
                            i = i + 1
                        existing.remove(name)
                    try:
                        self.configure_logger(name, loggers[name])
                    except StandardError as e:
                        raise ValueError('Unable to configure logger '
                                         '%r: %s' % (name, e))

                # Disable any old loggers. There's no point deleting
                # them as other threads may continue to hold references
                # and by disabling them, you stop them doing any logging.
                # However, don't disable children of named loggers, as that's
                # probably not what was intended by the user.
                for log in existing:
                    logger = root.manager.loggerDict[log]
                    if log in child_loggers:
                        logger.level = logging.NOTSET
                        logger.handlers = []
                        logger.propagate = True
                    elif disable_existing:
                        logger.disabled = True

                # And finally, do the root logger
                root = config.get('root', None)
                if root:
                    try:
                        self.configure_root(root)
                    except StandardError as e:
                        raise ValueError('Unable to configure root '
                                         'logger: %s' % e)
        finally:
            logging._releaseLock()

    def configure_formatter(self, config):
        """Configure a formatter from a dictionary."""
        if '()' in config:
            factory = config['()']  # for use in exception handler
            try:
                result = self.configure_custom(config)
            except TypeError as te:
                if "'format'" not in str(te):
                    raise
                # Name of parameter changed from fmt to format.
                # Retry with old name.
                # This is so that code can be used with older Python versions
                # (e.g. by Django)
                config['fmt'] = config.pop('format')
                config['()'] = factory
                result = self.configure_custom(config)
        else:
            fmt = config.get('format', None)
            dfmt = config.get('datefmt', None)
            result = logging.Formatter(fmt, dfmt)
        return result

    def configure_filter(self, config):
        """Configure a filter from a dictionary."""
        if '()' in config:
            result = self.configure_custom(config)
        else:
            name = config.get('name', '')
            result = logging.Filter(name)
        return result

    def add_filters(self, filterer, filters):
        """Add filters to a filterer from a list of names."""
        for f in filters:
            try:
                filterer.addFilter(self.config['filters'][f])
            except StandardError as e:
                raise ValueError('Unable to add filter %r: %s' % (f, e))

    def configure_handler(self, config):
        """Configure a handler from a dictionary."""
        formatter = config.pop('formatter', None)
        if formatter:
            try:
                formatter = self.config['formatters'][formatter]
            except StandardError as e:
                raise ValueError('Unable to set formatter '
                                 '%r: %s' % (formatter, e))
        level = config.pop('level', None)
        filters = config.pop('filters', None)
        if '()' in config:
            c = config.pop('()')
            if not hasattr(c, '__call__') and hasattr(types, 'ClassType') and type(c) != types.ClassType:
                c = self.resolve(c)
            factory = c
        else:
            klass = self.resolve(config.pop('class'))
            # Special case for handler which refers to another handler
            if issubclass(klass, logging.handlers.MemoryHandler) and \
                            'target' in config:
                try:
                    config['target'] = self.config['handlers'][config['target']]
                except StandardError as e:
                    raise ValueError('Unable to set target handler '
                                     '%r: %s' % (config['target'], e))
            elif issubclass(klass, logging.handlers.SMTPHandler) and \
                            'mailhost' in config:
                config['mailhost'] = self.as_tuple(config['mailhost'])
            elif issubclass(klass, logging.handlers.SysLogHandler) and \
                            'address' in config:
                config['address'] = self.as_tuple(config['address'])
            factory = klass
        kwargs = {k: config[k] for k in config if valid_ident(k)}
        try:
            result = factory(**kwargs)
        except TypeError as te:
            if "'stream'" not in str(te):
                raise
            # The argument name changed from strm to stream
            # Retry with old name.
            # This is so that code can be used with older Python versions
            # (e.g. by Django)
            kwargs['strm'] = kwargs.pop('stream')
            result = factory(**kwargs)
        if formatter:
            result.setFormatter(formatter)
        if level is not None:
            result.setLevel(_checkLevel(level))
        if filters:
            self.add_filters(result, filters)
        return result

    def add_handlers(self, logger, handlers):
        """Add handlers to a logger from a list of names."""
        for h in handlers:
            try:
                logger.addHandler(self.config['handlers'][h])
            except StandardError as e:
                raise ValueError('Unable to add handler %r: %s' % (h, e))

    def common_logger_config(self, logger, config, incremental=False):
        """
        Perform configuration which is common to root and non-root loggers.
        """
        level = config.get('level', None)
        if level is not None:
            logger.setLevel(_checkLevel(level))
        if not incremental:
            # Remove any existing handlers
            for h in logger.handlers[:]:
                logger.removeHandler(h)
            handlers = config.get('handlers', None)
            if handlers:
                self.add_handlers(logger, handlers)
            filters = config.get('filters', None)
            if filters:
                self.add_filters(logger, filters)

    def configure_logger(self, name, config, incremental=False):
        """Configure a non-root logger from a dictionary."""
        logger = logging.getLogger(name)
        self.common_logger_config(logger, config, incremental)
        propagate = config.get('propagate', None)
        if propagate is not None:
            logger.propagate = propagate

    def configure_root(self, config, incremental=False):
        """Configure a root logger from a dictionary."""
        root = logging.getLogger()
        self.common_logger_config(root, config, incremental)

dictConfigClass = DictConfigurator

def dictConfig(config):
    """Configure logging using a dictionary."""
    dictConfigClass(config).configure()


text:
/**
 * SMS Composer plugin for Cordova
 * window.plugins.SMSComposer
 *
 * @constructor
 */
function SMSComposer()
{
	this.resultCallback = null;
}

SMSComposer.ComposeResultType =
{
Cancelled:0,
Sent:1,
Failed:2,
NotSent:3
}

SMSComposer.prototype.showSMSComposer = function(toRecipients, body)
{

	var args = {};

	if(toRecipients)
		args.toRecipients = toRecipients;

	if(body)
		args.body = body;

	//cordova.exec("SMSComposer.showSMSComposer",args);
	cordova.exec(null, null, "SMSComposer", "showSMSComposer", args);
}

SMSComposer.prototype.showSMSComposerWithCB = function(cbFunction,toRecipients,body)
{
	this.resultCallback = cbFunction;
	this.showSMSComposer.apply(this,[toRecipients,body]);
}

SMSComposer.prototype._didFinishWithResult = function(res)
{
	this.resultCallback(res);
}

cordova.addConstructor(function() {

					   if(!window.plugins)	{
					   window.plugins = {};
					   }
					   window.plugins.smsComposer = new SMSComposer();
					   });


text:
var _ = require('lodash');

function Map() {
	this._contents = {};
};

Map.prototype.__defineGetter__('length', function () {
	return _.size(this._contents);
});

Map.prototype.contains = function (k) {
	return _.has(this._contents, k);
};

Map.prototype.put = function (k, v) {
	this._contents[k] = v;
};

Map.prototype.get = function (k) {
	if (this.contains(k))
		return this._contents[k];
};

Map.prototype.remove = function (k) {
	delete this._contents[k];
};

Map.prototype.keys = function () {
	return _.keys(this._contents);
};

Map.prototype.values = function () {
	return _.values(this._contents);
};

Map.prototype.toArray = function () {
	return _.pairs(this._contents);
};

function StringSet() {
	this._contents = new Map();

	_.each(arguments, function (arg, i) {
		if (_.isArray(arg))
			this.addAll(arg);
		else
			this.add(arg);
	}, this);

};

StringSet.prototype.add = function (str) {
	this._contents.put(str, true);
};

StringSet.prototype.addAll = function (arr) {
	_.each(arr, function (str) {
		this.add(str);
	}, this);
};

StringSet.prototype.has = function (str) {
	return this._contents.contains(str);
};

StringSet.prototype.remove = function (str) {
	this._contents.remove(str);
};

StringSet.prototype.count = function () {
	return this._contents.length;
};

StringSet.prototype.intersect = function (b) {
	return StringSet.intersect(this, b);
};

StringSet.prototype.intersectCount = function (b) {
	return StringSet.intersectCount(this, b);
};

StringSet.prototype.union = function (b) {
	return StringSet.union(this, b);
};

StringSet.prototype.unionCount = function (b) {
	return StringSet.unionCount(this, b);
};

StringSet.prototype.diff = function (b) {
	return StringSet.diff(this, b);
};

StringSet.prototype.diffCount = function (b) {
	return StringSet.diffCount(this, b);
};

StringSet.prototype.elements = function () {
	return this._contents.keys();
};

StringSet.intersect = function (a, b) {
	var p = (a.count() < b.count() ? a : b);
	var s = (a.count() < b.count() ? b : a);

	return p.elements().reduce(function (S, el) {
		if (s.has(el)) S.add(el);
		return S;
	}, new StringSet());
};

StringSet.intersectCount = function (a, b) {
	var p = (a.count() < b.count() ? a : b);
	var s = (a.count() < b.count() ? b : a);

	return p.elements().reduce(function (n, el) {
		return s.has(el) ? ++n : n;
	}, 0);
};

StringSet.union = function (a, b) {
	return new StringSet(a.elements(), b.elements());
};

StringSet.unionCount = function (a, b) {
	var p = (a.count() < b.count() ? a : b);
	var s = (a.count() < b.count() ? b : a);

	return s.count() + s.diffCount(p);
};

StringSet.diff = function (a, b) {
	return b.elements().reduce(function (S, el) {
		if (! a.has(el))
			S.add(el);
		return S;
	}, new StringSet());
};

StringSet.diffCount = function (a, b) {
	return b.elements().reduce(function (n, el) {
		return a.has(el) ? n : ++n;
	}, 0);
};

module.exports = {
	Map: Map,
	StringSet: StringSet
};


text:
package services.neo4j

import javax.inject.{Inject, Named}

import akka.actor.ActorSystem
import akka.stream.ActorMaterializer
import akka.stream.scaladsl.{Sink, Source}
import akka.{Done, NotUsed}
import com.google.inject.assistedinject.Assisted
import play.api.libs.json.Reads.of
import play.api.libs.json.{Json, _}
import play.api.libs.ws.{StreamedResponse, WSAuthScheme, WSClient, WSResponse}
import services.TwitterService
import streams.Identifier

import scala.concurrent.{ExecutionContext, Future}
import scala.language.postfixOps

class FollowerSink @Inject()(@Assisted() labelOpt: Option[String],
                             neo4jUserSinkFactory: UserSink.Factory,
                             twitterService: TwitterService,
                             wsClient: WSClient,
                             @Named("Neo4jURI") neo4jURI: String,
                             @Named("Neo4jUserName") neo4jUserName: String,
                             @Named("Neo4jPassword") neo4jPassword: String)
                            (implicit context: ExecutionContext,
                             system: ActorSystem) {

  private implicit val materializer = ActorMaterializer()
  private type UserId = Identifier
  private type UserScreenName = Identifier

  //------------------------------------------------------------------------------------------//
  //
  //------------------------------------------------------------------------------------------//
  def insertBreadthFirstByUserId(root: UserId, depth: Int): Future[Done] = {
    val breadthFirstMerger = new BreadthFirstMerger(
      labelOpt,
      neo4jUserSinkFactory,
      twitterService,
      twitterService.getFollowerIdsByUserId,
      twitterService.getFollowerIdsByUserId,
      getNotYetVisitedNeighbors,
      followerSink(_, "id"),
      followerSink(_, "id"))
    breadthFirstMerger.addBreadthFirstById(root.id, depth)
  }

  def insertBreadthFirstByScreenName(root: UserScreenName, depth: Int): Future[Done] = {
    val breadthFirstMerger = new BreadthFirstMerger(
      labelOpt,
      neo4jUserSinkFactory,
      twitterService,
      twitterService.getFollowerIdsByScreenName,
      twitterService.getFollowerIdsByUserId,
      getNotYetVisitedNeighbors,
      followerSink(_, "id"),
      followerSink(_, "screenName"))
    breadthFirstMerger.addBreadthFirstByScreenName(root.id, depth)
  }

  private def mergeFollowerRelationships(users: JsArray, rootIdentifier: String): Future[WSResponse] = {
    val query = Json.obj(
      "statement" ->
        s"""UNWIND $$json AS user
           |MERGE (root:${Schema.NodeLabels.User} {$rootIdentifier: user.user.previousUserId})
           |MERGE (follower:${Schema.NodeLabels.User} {id: user.user.id_str})
           |CREATE UNIQUE (root)<-[:${Schema.RelationshipTypes.Follows}]-(follower)""".stripMargin,
      "parameters" ->
        Json.obj(
          "json" -> Json.toJson(users)
        )
    )

    wsClient.url(neo4jURI + "/db/data/transaction/commit")
      .withAuth(neo4jUserName, neo4jPassword, WSAuthScheme.BASIC)
      .withHeaders(
        "Accept" -> "application/json; charset=UTF-8",
        "Content-Type" -> "application/json"
      )
      .post {
        Json.obj(
          "statements" -> Json.toJson(Vector(query))
        )
      }
  }

  private def followerSink(source: Source[(Identifier, JsValue), NotUsed], rootIdentifier: String):
  Future[Done] = {
    source.map {
      case (id, json) =>
        val prev = if (id.previous.isEmpty) id.id else id.previous.last
        json.transform(
          (__ \ "user").json.update(
            of[JsObject].map(_ ++ Json.obj("previousUserId" -> prev))
          )
        ).get
    }
      .grouped(5000)
      .map(JsArray)
      .mapAsyncUnordered(Runtime.getRuntime.availableProcessors())(mergeFollowerRelationships(_, rootIdentifier))
      .runWith(Sink.ignore)
  }

  private def getNotYetVisitedNeighbors(root: String,
                                        identifierName: String,
                                        minDepth: Int,
                                        maxDepth: Int): Future[StreamedResponse] = {
    require(minDepth > -1)
    require(maxDepth > -1)

    val query = Json.obj(
      "statement" ->
        s"""MATCH (root:${Schema.NodeLabels.User} {$identifierName: $$rootUser})
           |WITH root
           |MATCH r=(root)<-[:${Schema.RelationshipTypes.Follows}*$minDepth..$maxDepth]-(follower)
           |WHERE NOT exists(follower.followerBreadthFirstSearchVisited)
           |SET follower.followerBreadthFirstSearchVisited = TRUE
           |RETURN follower""".stripMargin,
      "parameters" ->
        Json.obj(
          "rootUser" -> root
        )
    )

    wsClient.url(neo4jURI + "/db/data/transaction/commit")
      .withMethod("POST")
      .withAuth(neo4jUserName, neo4jPassword, WSAuthScheme.BASIC)
      .withHeaders(
        "Accept" -> "application/json; charset=UTF-8",
        "Content-Type" -> "application/json",
        "X-Stream" -> "true"
      )
      .withBody(Json.obj(
        "statements" -> Json.toJson(Vector(query))
      ))
      .stream()
  }
}

object FollowerSink {

  trait Factory {
    def create(labelOpt: Option[String]): FollowerSink
  }

}