text:
// queryutil.cpp

#include "pch.h"

#include "btree.h"
#include "matcher.h"
#include "pdfile.h"
#include "queryoptimizer.h"
#include "../util/unittest.h"
#include "dbmessage.h"
#include "indexkey.h"

namespace mongo {
    extern BSONObj staticNull;

    /** returns a string that when used as a matcher, would match a super set of regex()
        returns "" for complex regular expressions
        used to optimize queries in some simple regex cases that start with '^'

        if purePrefix != NULL, sets it to whether the regex can be converted to a range query
    */
    string simpleRegex(const char* regex, const char* flags, bool* purePrefix) {
        string r = "";

        if (purePrefix) *purePrefix = false;

        bool multilineOK;
        if ( regex[0] == '\\' && regex[1] == 'A') {
            multilineOK = true;
            regex += 2;
        }
        else if (regex[0] == '^') {
            multilineOK = false;
            regex += 1;
        }
        else {
            return r;
        }

        bool extended = false;
        while (*flags) {
            switch (*(flags++)) {
            case 'm': // multiline
                if (multilineOK)
                    continue;
                else
                    return r;
            case 'x': // extended
                extended = true;
                break;
            default:
                return r; // cant use index
            }
        }

        stringstream ss;

        while(*regex) {
            char c = *(regex++);
            if ( c == '*' || c == '?' ) {
                // These are the only two symbols that make the last char optional
                r = ss.str();
                r = r.substr( 0 , r.size() - 1 );
                return r; //breaking here fails with /^a?/
            }
            else if (c == '\\') {
                // slash followed by non-alphanumeric represents the following char
                c = *(regex++);
                if ((c >= 'A' && c <= 'Z') ||
                        (c >= 'a' && c <= 'z') ||
                        (c >= '0' && c <= '0') ||
                        (c == '\0')) {
                    r = ss.str();
                    break;
                }
                else {
                    ss << c;
                }
            }
            else if (strchr("^$.[|()+{", c)) {
                // list of "metacharacters" from man pcrepattern
                r = ss.str();
                break;
            }
            else if (extended && c == '#') {
                // comment
                r = ss.str();
                break;
            }
            else if (extended && isspace(c)) {
                continue;
            }
            else {
                // self-matching char
                ss << c;
            }
        }

        if ( r.empty() && *regex == 0 ) {
            r = ss.str();
            if (purePrefix) *purePrefix = !r.empty();
        }

        return r;
    }
    inline string simpleRegex(const BSONElement& e) {
        switch(e.type()) {
        case RegEx:
            return simpleRegex(e.regex(), e.regexFlags());
        case Object: {
            BSONObj o = e.embeddedObject();
            return simpleRegex(o["$regex"].valuestrsafe(), o["$options"].valuestrsafe());
        }
        default: assert(false); return ""; //return squashes compiler warning
        }
    }

    string simpleRegexEnd( string regex ) {
        ++regex[ regex.length() - 1 ];
        return regex;
    }

    FieldRange::FieldRange( const BSONElement &e, bool isNot, bool optimize ) {
        // NOTE with $not, we could potentially form a complementary set of intervals.
        if ( !isNot && !e.eoo() && e.type() != RegEx && e.getGtLtOp() == BSONObj::opIN ) {
            set< BSONElement, element_lt > vals;
            vector< FieldRange > regexes;
            uassert( 12580 , "invalid query" , e.isABSONObj() );
            BSONObjIterator i( e.embeddedObject() );
            while( i.more() ) {
                BSONElement ie = i.next();
                if ( ie.type() == RegEx ) {
                    regexes.push_back( FieldRange( ie, false, optimize ) );
                }
                else {
                    vals.insert( ie );
                }
            }

            for( set< BSONElement, element_lt >::const_iterator i = vals.begin(); i != vals.end(); ++i )
                _intervals.push_back( FieldInterval(*i) );

            for( vector< FieldRange >::const_iterator i = regexes.begin(); i != regexes.end(); ++i )
                *this |= *i;

            return;
        }

        if ( e.type() == Array && e.getGtLtOp() == BSONObj::Equality ) {

            _intervals.push_back( FieldInterval(e) );

            const BSONElement& temp = e.embeddedObject().firstElement();
            if ( ! temp.eoo() ) {
                if ( temp < e )
                    _intervals.insert( _intervals.begin() , temp );
                else
                    _intervals.push_back( FieldInterval(temp) );
            }

            return;
        }

        _intervals.push_back( FieldInterval() );
        FieldInterval &initial = _intervals[ 0 ];
        BSONElement &lower = initial._lower._bound;
        bool &lowerInclusive = initial._lower._inclusive;
        BSONElement &upper = initial._upper._bound;
        bool &upperInclusive = initial._upper._inclusive;
        lower = minKey.firstElement();
        lowerInclusive = true;
        upper = maxKey.firstElement();
        upperInclusive = true;

        if ( e.eoo() )
            return;
        int op = e.getGtLtOp();
        if ( e.type() == RegEx
                || (e.type() == Object && !e.embeddedObject()["$regex"].eoo())
           ) {
            uassert( 13454, "invalid regular expression operator", op == BSONObj::Equality || op == BSONObj::opREGEX );
            if ( !isNot ) { // no optimization for negated regex - we could consider creating 2 intervals comprising all nonmatching prefixes
                const string r = simpleRegex(e);
                if ( r.size() ) {
                    lower = addObj( BSON( "" << r ) ).firstElement();
                    upper = addObj( BSON( "" << simpleRegexEnd( r ) ) ).firstElement();
                    upperInclusive = false;
                }
                else {
                    BSONObjBuilder b1(32), b2(32);
                    b1.appendMinForType( "" , String );
                    lower = addObj( b1.obj() ).firstElement();

                    b2.appendMaxForType( "" , String );
                    upper = addObj( b2.obj() ).firstElement();
                    upperInclusive = false; //MaxForType String is an empty Object
                }

                // regex matches self - regex type > string type
                if (e.type() == RegEx) {
                    BSONElement re = addObj( BSON( "" << e ) ).firstElement();
                    _intervals.push_back( FieldInterval(re) );
                }
                else {
                    BSONObj orig = e.embeddedObject();
                    BSONObjBuilder b;
                    b.appendRegex("", orig["$regex"].valuestrsafe(), orig["$options"].valuestrsafe());
                    BSONElement re = addObj( b.obj() ).firstElement();
                    _intervals.push_back( FieldInterval(re) );
                }

            }
            return;
        }
        if ( isNot ) {
            switch( op ) {
            case BSONObj::Equality:
                return;
//                    op = BSONObj::NE;
//                    break;
            case BSONObj::opALL:
            case BSONObj::opMOD: // NOTE for mod and type, we could consider having 1-2 intervals comprising the complementary types (multiple intervals already possible with $in)
            case BSONObj::opTYPE:
                // no bound calculation
                return;
            case BSONObj::NE:
                op = BSONObj::Equality;
                break;
            case BSONObj::LT:
                op = BSONObj::GTE;
                break;
            case BSONObj::LTE:
                op = BSONObj::GT;
                break;
            case BSONObj::GT:
                op = BSONObj::LTE;
                break;
            case BSONObj::GTE:
                op = BSONObj::LT;
                break;
            default: // otherwise doesn't matter
                break;
            }
        }
        switch( op ) {
        case BSONObj::Equality:
            lower = upper = e;
            break;
        case BSONObj::NE: {
            // this will invalidate the upper/lower references above
            _intervals.push_back( FieldInterval() );
            // optimize doesn't make sense for negative ranges
            _intervals[ 0 ]._upper._bound = e;
            _intervals[ 0 ]._upper._inclusive = false;
            _intervals[ 1 ]._lower._bound = e;
            _intervals[ 1 ]._lower._inclusive = false;
            _intervals[ 1 ]._upper._bound = maxKey.firstElement();
            _intervals[ 1 ]._upper._inclusive = true;
            optimize = false; // don't run optimize code below
            break;
        }
        case BSONObj::LT:
            upperInclusive = false;
        case BSONObj::LTE:
            upper = e;
            break;
        case BSONObj::GT:
            lowerInclusive = false;
        case BSONObj::GTE:
            lower = e;
            break;
        case BSONObj::opALL: {
            massert( 10370 ,  "$all requires array", e.type() == Array );
            BSONObjIterator i( e.embeddedObject() );
            bool bound = false;
            while ( i.more() ) {
                BSONElement x = i.next();
                if ( x.type() == Object && x.embeddedObject().firstElement().getGtLtOp() == BSONObj::opELEM_MATCH ) {
                    // taken care of elsewhere
                }
                else if ( x.type() != RegEx ) {
                    lower = upper = x;
                    bound = true;
                    break;
                }
            }
            if ( !bound ) { // if no good non regex bound found, try regex bounds
                BSONObjIterator i( e.embeddedObject() );
                while( i.more() ) {
                    BSONElement x = i.next();
                    if ( x.type() != RegEx )
                        continue;
                    string simple = simpleRegex( x.regex(), x.regexFlags() );
                    if ( !simple.empty() ) {
                        lower = addObj( BSON( "" << simple ) ).firstElement();
                        upper = addObj( BSON( "" << simpleRegexEnd( simple ) ) ).firstElement();
                        break;
                    }
                }
            }
            break;
        }
        case BSONObj::opMOD: {
            {
                BSONObjBuilder b;
                b.appendMinForType( "" , NumberDouble );
                lower = addObj( b.obj() ).firstElement();
            }
            {
                BSONObjBuilder b;
                b.appendMaxForType( "" , NumberDouble );
                upper = addObj( b.obj() ).firstElement();
            }
            break;
        }
        case BSONObj::opTYPE: {
            BSONType t = (BSONType)e.numberInt();
            {
                BSONObjBuilder b;
                b.appendMinForType( "" , t );
                lower = addObj( b.obj() ).firstElement();
            }
            {
                BSONObjBuilder b;
                b.appendMaxForType( "" , t );
                upper = addObj( b.obj() ).firstElement();
            }

            break;
        }
        case BSONObj::opREGEX:
        case BSONObj::opOPTIONS:
            // do nothing
            break;
        case BSONObj::opELEM_MATCH: {
            log() << "warning: shouldn't get here?" << endl;
            break;
        }
        case BSONObj::opNEAR:
        case BSONObj::opWITHIN:
            _special = "2d";
            break;
        default:
            break;
        }

        if ( optimize ) {
            if ( lower.type() != MinKey && upper.type() == MaxKey && lower.isSimpleType() ) { // TODO: get rid of isSimpleType
                BSONObjBuilder b;
                b.appendMaxForType( lower.fieldName() , lower.type() );
                upper = addObj( b.obj() ).firstElement();
            }
            else if ( lower.type() == MinKey && upper.type() != MaxKey && upper.isSimpleType() ) { // TODO: get rid of isSimpleType
                BSONObjBuilder b;
                b.appendMinForType( upper.fieldName() , upper.type() );
                lower = addObj( b.obj() ).firstElement();
            }
        }

    }

    void FieldRange::finishOperation( const vector< FieldInterval > &newIntervals, const FieldRange &other ) {
        _intervals = newIntervals;
        for( vector< BSONObj >::const_iterator i = other._objData.begin(); i != other._objData.end(); ++i )
            _objData.push_back( *i );
        if ( _special.size() == 0 && other._special.size() )
            _special = other._special;
    }

    // as called, these functions find the max/min of a bound in the
    // opposite direction, so inclusive bounds are considered less
    // superlative
    FieldBound maxFieldBound( const FieldBound &a, const FieldBound &b ) {
        int cmp = a._bound.woCompare( b._bound, false );
        if ( ( cmp == 0 && !b._inclusive ) || cmp < 0 )
            return b;
        return a;
    }

    FieldBound minFieldBound( const FieldBound &a, const FieldBound &b ) {
        int cmp = a._bound.woCompare( b._bound, false );
        if ( ( cmp == 0 && !b._inclusive ) || cmp > 0 )
            return b;
        return a;
    }

    bool fieldIntervalOverlap( const FieldInterval &one, const FieldInterval &two, FieldInterval &result ) {
        result._lower = maxFieldBound( one._lower, two._lower );
        result._upper = minFieldBound( one._upper, two._upper );
        return result.strictValid();
    }

    const FieldRange &FieldRange::operator&=( const FieldRange &other ) {
        vector< FieldInterval > newIntervals;
        vector< FieldInterval >::const_iterator i = _intervals.begin();
        vector< FieldInterval >::const_iterator j = other._intervals.begin();
        while( i != _intervals.end() && j != other._intervals.end() ) {
            FieldInterval overlap;
            if ( fieldIntervalOverlap( *i, *j, overlap ) ) {
                newIntervals.push_back( overlap );
            }
            if ( i->_upper == minFieldBound( i->_upper, j->_upper ) ) {
                ++i;
            }
            else {
                ++j;
            }
        }
        finishOperation( newIntervals, other );
        return *this;
    }

    void handleInterval( const FieldInterval &lower, FieldBound &low, FieldBound &high, vector< FieldInterval > &newIntervals ) {
        if ( low._bound.eoo() ) {
            low = lower._lower; high = lower._upper;
        }
        else {
            int cmp = high._bound.woCompare( lower._lower._bound, false );
            if ( ( cmp < 0 ) || ( cmp == 0 && !high._inclusive && !lower._lower._inclusive ) ) {
                FieldInterval tmp;
                tmp._lower = low;
                tmp._upper = high;
                newIntervals.push_back( tmp );
                low = lower._lower; high = lower._upper;
            }
            else {
                high = lower._upper;
            }
        }
    }

    const FieldRange &FieldRange::operator|=( const FieldRange &other ) {
        vector< FieldInterval > newIntervals;
        FieldBound low;
        FieldBound high;
        vector< FieldInterval >::const_iterator i = _intervals.begin();
        vector< FieldInterval >::const_iterator j = other._intervals.begin();
        while( i != _intervals.end() && j != other._intervals.end() ) {
            int cmp = i->_lower._bound.woCompare( j->_lower._bound, false );
            if ( ( cmp == 0 && i->_lower._inclusive ) || cmp < 0 ) {
                handleInterval( *i, low, high, newIntervals );
                ++i;
            }
            else {
                handleInterval( *j, low, high, newIntervals );
                ++j;
            }
        }
        while( i != _intervals.end() ) {
            handleInterval( *i, low, high, newIntervals );
            ++i;
        }
        while( j != other._intervals.end() ) {
            handleInterval( *j, low, high, newIntervals );
            ++j;
        }
        FieldInterval tmp;
        tmp._lower = low;
        tmp._upper = high;
        newIntervals.push_back( tmp );
        finishOperation( newIntervals, other );
        return *this;
    }

    const FieldRange &FieldRange::operator-=( const FieldRange &other ) {
        vector< FieldInterval > newIntervals;
        vector< FieldInterval >::iterator i = _intervals.begin();
        vector< FieldInterval >::const_iterator j = other._intervals.begin();
        while( i != _intervals.end() && j != other._intervals.end() ) {
            int cmp = i->_lower._bound.woCompare( j->_lower._bound, false );
            if ( cmp < 0 ||
                    ( cmp == 0 && i->_lower._inclusive && !j->_lower._inclusive ) ) {
                int cmp2 = i->_upper._bound.woCompare( j->_lower._bound, false );
                if ( cmp2 < 0 ) {
                    newIntervals.push_back( *i );
                    ++i;
                }
                else if ( cmp2 == 0 ) {
                    newIntervals.push_back( *i );
                    if ( newIntervals.back()._upper._inclusive && j->_lower._inclusive ) {
                        newIntervals.back()._upper._inclusive = false;
                    }
                    ++i;
                }
                else {
                    newIntervals.push_back( *i );
                    newIntervals.back()._upper = j->_lower;
                    newIntervals.back()._upper.flipInclusive();
                    int cmp3 = i->_upper._bound.woCompare( j->_upper._bound, false );
                    if ( cmp3 < 0 ||
                            ( cmp3 == 0 && ( !i->_upper._inclusive || j->_upper._inclusive ) ) ) {
                        ++i;
                    }
                    else {
                        i->_lower = j->_upper;
                        i->_lower.flipInclusive();
                        ++j;
                    }
                }
            }
            else {
                int cmp2 = i->_lower._bound.woCompare( j->_upper._bound, false );
                if ( cmp2 > 0 ||
                        ( cmp2 == 0 && ( !i->_lower._inclusive || !j->_upper._inclusive ) ) ) {
                    ++j;
                }
                else {
                    int cmp3 = i->_upper._bound.woCompare( j->_upper._bound, false );
                    if ( cmp3 < 0 ||
                            ( cmp3 == 0 && ( !i->_upper._inclusive || j->_upper._inclusive ) ) ) {
                        ++i;
                    }
                    else {
                        i->_lower = j->_upper;
                        i->_lower.flipInclusive();
                        ++j;
                    }
                }
            }
        }
        while( i != _intervals.end() ) {
            newIntervals.push_back( *i );
            ++i;
        }
        finishOperation( newIntervals, other );
        return *this;
    }

    // TODO write a proper implementation that doesn't do a full copy
    bool FieldRange::operator<=( const FieldRange &other ) {
        FieldRange temp = *this;
        temp -= other;
        return temp.empty();
    }

    BSONObj FieldRange::addObj( const BSONObj &o ) {
        _objData.push_back( o );
        return o;
    }

    string FieldRangeSet::getSpecial() const {
        string s = "";
        for ( map<string,FieldRange>::iterator i=_ranges.begin(); i!=_ranges.end(); i++ ) {
            if ( i->second.getSpecial().size() == 0 )
                continue;
            uassert( 13033 , "can't have 2 special fields" , s.size() == 0 );
            s = i->second.getSpecial();
        }
        return s;
    }

    void FieldRangeSet::processOpElement( const char *fieldName, const BSONElement &f, bool isNot, bool optimize ) {
        BSONElement g = f;
        int op2 = g.getGtLtOp();
        if ( op2 == BSONObj::opALL ) {
            BSONElement h = g;
            massert( 13050 ,  "$all requires array", h.type() == Array );
            BSONObjIterator i( h.embeddedObject() );
            if( i.more() ) {
                BSONElement x = i.next();
                if ( x.type() == Object && x.embeddedObject().firstElement().getGtLtOp() == BSONObj::opELEM_MATCH ) {
                    g = x.embeddedObject().firstElement();
                    op2 = g.getGtLtOp();
                }
            }
        }
        if ( op2 == BSONObj::opELEM_MATCH ) {
            BSONObjIterator k( g.embeddedObjectUserCheck() );
            while ( k.more() ) {
                BSONElement h = k.next();
                StringBuilder buf(32);
                buf << fieldName << "." << h.fieldName();
                string fullname = buf.str();

                int op3 = getGtLtOp( h );
                if ( op3 == BSONObj::Equality ) {
                    _ranges[ fullname ] &= FieldRange( h , isNot , optimize );
                }
                else {
                    BSONObjIterator l( h.embeddedObject() );
                    while ( l.more() ) {
                        _ranges[ fullname ] &= FieldRange( l.next() , isNot , optimize );
                    }
                }
            }
        }
        else {
            _ranges[ fieldName ] &= FieldRange( f , isNot , optimize );
        }
    }

    void FieldRangeSet::processQueryField( const BSONElement &e, bool optimize ) {
        bool equality = ( getGtLtOp( e ) == BSONObj::Equality );
        if ( equality && e.type() == Object ) {
            equality = ( strcmp( e.embeddedObject().firstElement().fieldName(), "$not" ) != 0 );
        }

        if ( equality || ( e.type() == Object && !e.embeddedObject()[ "$regex" ].eoo() ) ) {
            _ranges[ e.fieldName() ] &= FieldRange( e , false , optimize );
        }
        if ( !equality ) {
            BSONObjIterator j( e.embeddedObject() );
            while( j.more() ) {
                BSONElement f = j.next();
                if ( strcmp( f.fieldName(), "$not" ) == 0 ) {
                    switch( f.type() ) {
                    case Object: {
                        BSONObjIterator k( f.embeddedObject() );
                        while( k.more() ) {
                            BSONElement g = k.next();
                            uassert( 13034, "invalid use of $not", g.getGtLtOp() != BSONObj::Equality );
                            processOpElement( e.fieldName(), g, true, optimize );
                        }
                        break;
                    }
                    case RegEx:
                        processOpElement( e.fieldName(), f, true, optimize );
                        break;
                    default:
                        uassert( 13041, "invalid use of $not", false );
                    }
                }
                else {
                    processOpElement( e.fieldName(), f, false, optimize );
                }
            }
        }
    }

    FieldRangeSet::FieldRangeSet( const char *ns, const BSONObj &query , bool optimize )
        : _ns( ns ), _queries( 1, query.getOwned() ) {
        BSONObjIterator i( _queries[ 0 ] );

        while( i.more() ) {
            BSONElement e = i.next();
            // e could be x:1 or x:{$gt:1}

            if ( strcmp( e.fieldName(), "$where" ) == 0 ) {
                continue;
            }

            if ( strcmp( e.fieldName(), "$or" ) == 0 ) {
                continue;
            }

            if ( strcmp( e.fieldName(), "$nor" ) == 0 ) {
                continue;
            }

            processQueryField( e, optimize );
        }
    }

    FieldRangeOrSet::FieldRangeOrSet( const char *ns, const BSONObj &query , bool optimize )
        : _baseSet( ns, query, optimize ), _orFound() {

        BSONObjIterator i( _baseSet._queries[ 0 ] );

        while( i.more() ) {
            BSONElement e = i.next();
            if ( strcmp( e.fieldName(), "$or" ) == 0 ) {
                massert( 13262, "$or requires nonempty array", e.type() == Array && e.embeddedObject().nFields() > 0 );
                BSONObjIterator j( e.embeddedObject() );
                while( j.more() ) {
                    BSONElement f = j.next();
                    massert( 13263, "$or array must contain objects", f.type() == Object );
                    _orSets.push_back( FieldRangeSet( ns, f.embeddedObject(), optimize ) );
                    massert( 13291, "$or may not contain 'special' query", _orSets.back().getSpecial().empty() );
                    _originalOrSets.push_back( _orSets.back() );
                }
                _orFound = true;
                continue;
            }
        }
    }

    void FieldRangeOrSet::popOrClause( const BSONObj &indexSpec ) {
        massert( 13274, "no or clause to pop", !orFinished() );
        auto_ptr< FieldRangeSet > holder;
        FieldRangeSet *toDiff = &_originalOrSets.front();
        if ( toDiff->matchPossible() && !indexSpec.isEmpty() ) {
            holder.reset( toDiff->subset( indexSpec ) );
            toDiff = holder.get();
        }
        list< FieldRangeSet >::iterator i = _orSets.begin();
        list< FieldRangeSet >::iterator j = _originalOrSets.begin();
        ++i;
        ++j;
        while( i != _orSets.end() ) {
            *i -= *toDiff;
            if( !i->matchPossible() ) {
                i = _orSets.erase( i );
                j = _originalOrSets.erase( j );
            }
            else {
                ++i;
                ++j;
            }
        }
        _oldOrSets.push_front( _orSets.front() );
        _orSets.pop_front();
        _originalOrSets.pop_front();
    }

    FieldRange *FieldRangeSet::trivialRange_ = 0;
    FieldRange &FieldRangeSet::trivialRange() {
        if ( trivialRange_ == 0 )
            trivialRange_ = new FieldRange();
        return *trivialRange_;
    }

    BSONObj FieldRangeSet::simplifiedQuery( const BSONObj &_fields ) const {
        BSONObj fields = _fields;
        if ( fields.isEmpty() ) {
            BSONObjBuilder b;
            for( map< string, FieldRange >::const_iterator i = _ranges.begin(); i != _ranges.end(); ++i ) {
                b.append( i->first, 1 );
            }
            fields = b.obj();
        }
        BSONObjBuilder b;
        BSONObjIterator i( fields );
        while( i.more() ) {
            BSONElement e = i.next();
            const char *name = e.fieldName();
            const FieldRange &range = _ranges[ name ];
            assert( !range.empty() );
            if ( range.equality() )
                b.appendAs( range.min(), name );
            else if ( range.nontrivial() ) {
                BSONObj o;
                BSONObjBuilder c;
                if ( range.min().type() != MinKey )
                    c.appendAs( range.min(), range.minInclusive() ? "$gte" : "$gt" );
                if ( range.max().type() != MaxKey )
                    c.appendAs( range.max(), range.maxInclusive() ? "$lte" : "$lt" );
                o = c.obj();
                b.append( name, o );
            }
        }
        return b.obj();
    }

    QueryPattern FieldRangeSet::pattern( const BSONObj &sort ) const {
        QueryPattern qp;
        for( map< string, FieldRange >::const_iterator i = _ranges.begin(); i != _ranges.end(); ++i ) {
            assert( !i->second.empty() );
            if ( i->second.equality() ) {
                qp._fieldTypes[ i->first ] = QueryPattern::Equality;
            }
            else if ( i->second.nontrivial() ) {
                bool upper = i->second.max().type() != MaxKey;
                bool lower = i->second.min().type() != MinKey;
                if ( upper && lower )
                    qp._fieldTypes[ i->first ] = QueryPattern::UpperAndLowerBound;
                else if ( upper )
                    qp._fieldTypes[ i->first ] = QueryPattern::UpperBound;
                else if ( lower )
                    qp._fieldTypes[ i->first ] = QueryPattern::LowerBound;
            }
        }
        qp.setSort( sort );
        return qp;
    }

    // TODO get rid of this
    BoundList FieldRangeSet::indexBounds( const BSONObj &keyPattern, int direction ) const {
        typedef vector< pair< shared_ptr< BSONObjBuilder >, shared_ptr< BSONObjBuilder > > > BoundBuilders;
        BoundBuilders builders;
        builders.push_back( make_pair( shared_ptr< BSONObjBuilder >( new BSONObjBuilder() ), shared_ptr< BSONObjBuilder >( new BSONObjBuilder() ) ) );
        BSONObjIterator i( keyPattern );
        bool ineq = false; // until ineq is true, we are just dealing with equality and $in bounds
        while( i.more() ) {
            BSONElement e = i.next();
            const FieldRange &fr = range( e.fieldName() );
            int number = (int) e.number(); // returns 0.0 if not numeric
            bool forward = ( ( number >= 0 ? 1 : -1 ) * ( direction >= 0 ? 1 : -1 ) > 0 );
            if ( !ineq ) {
                if ( fr.equality() ) {
                    for( BoundBuilders::const_iterator j = builders.begin(); j != builders.end(); ++j ) {
                        j->first->appendAs( fr.min(), "" );
                        j->second->appendAs( fr.min(), "" );
                    }
                }
                else {
                    if ( !fr.inQuery() ) {
                        ineq = true;
                    }
                    BoundBuilders newBuilders;
                    const vector< FieldInterval > &intervals = fr.intervals();
                    for( BoundBuilders::const_iterator i = builders.begin(); i != builders.end(); ++i ) {
                        BSONObj first = i->first->obj();
                        BSONObj second = i->second->obj();

                        const unsigned maxCombinations = 4000000;
                        if ( forward ) {
                            for( vector< FieldInterval >::const_iterator j = intervals.begin(); j != intervals.end(); ++j ) {
                                uassert( 13303, "combinatorial limit of $in partitioning of result set exceeded", newBuilders.size() < maxCombinations );
                                newBuilders.push_back( make_pair( shared_ptr< BSONObjBuilder >( new BSONObjBuilder() ), shared_ptr< BSONObjBuilder >( new BSONObjBuilder() ) ) );
                                newBuilders.back().first->appendElements( first );
                                newBuilders.back().second->appendElements( second );
                                newBuilders.back().first->appendAs( j->_lower._bound, "" );
                                newBuilders.back().second->appendAs( j->_upper._bound, "" );
                            }
                        }
                        else {
                            for( vector< FieldInterval >::const_reverse_iterator j = intervals.rbegin(); j != intervals.rend(); ++j ) {
                                uassert( 13304, "combinatorial limit of $in partitioning of result set exceeded", newBuilders.size() < maxCombinations );
                                newBuilders.push_back( make_pair( shared_ptr< BSONObjBuilder >( new BSONObjBuilder() ), shared_ptr< BSONObjBuilder >( new BSONObjBuilder() ) ) );
                                newBuilders.back().first->appendElements( first );
                                newBuilders.back().second->appendElements( second );
                                newBuilders.back().first->appendAs( j->_upper._bound, "" );
                                newBuilders.back().second->appendAs( j->_lower._bound, "" );
                            }
                        }
                    }
                    builders = newBuilders;
                }
            }
            else {
                for( BoundBuilders::const_iterator j = builders.begin(); j != builders.end(); ++j ) {
                    j->first->appendAs( forward ? fr.min() : fr.max(), "" );
                    j->second->appendAs( forward ? fr.max() : fr.min(), "" );
                }
            }
        }
        BoundList ret;
        for( BoundBuilders::const_iterator i = builders.begin(); i != builders.end(); ++i )
            ret.push_back( make_pair( i->first->obj(), i->second->obj() ) );
        return ret;
    }

    FieldRangeSet *FieldRangeSet::subset( const BSONObj &fields ) const {
        FieldRangeSet *ret = new FieldRangeSet( _ns, BSONObj() );
        BSONObjIterator i( fields );
        while( i.more() ) {
            BSONElement e = i.next();
            if ( _ranges[ e.fieldName() ].nontrivial() ) {
                ret->_ranges[ e.fieldName() ] = _ranges[ e.fieldName() ];
            }
        }
        ret->_queries = _queries;
        return ret;
    }

    bool FieldRangeVector::matchesElement( const BSONElement &e, int i, bool forward ) const {
        bool eq;
        int l = matchingLowElement( e, i, forward, eq );
        return ( l % 2 == 0 ); // if we're inside an interval
    }

    // binary search for interval containing the specified element
    // an even return value indicates that the element is contained within a valid interval
    int FieldRangeVector::matchingLowElement( const BSONElement &e, int i, bool forward, bool &lowEquality ) const {
        lowEquality = false;
        int l = -1;
        int h = _ranges[ i ].intervals().size() * 2;
        while( l + 1 < h ) {
            int m = ( l + h ) / 2;
            BSONElement toCmp;
            bool toCmpInclusive;
            const FieldInterval &interval = _ranges[ i ].intervals()[ m / 2 ];
            if ( m % 2 == 0 ) {
                toCmp = interval._lower._bound;
                toCmpInclusive = interval._lower._inclusive;
            }
            else {
                toCmp = interval._upper._bound;
                toCmpInclusive = interval._upper._inclusive;
            }
            int cmp = toCmp.woCompare( e, false );
            if ( !forward ) {
                cmp = -cmp;
            }
            if ( cmp < 0 ) {
                l = m;
            }
            else if ( cmp > 0 ) {
                h = m;
            }
            else {
                if ( m % 2 == 0 ) {
                    lowEquality = true;
                }
                int ret = m;
                // if left match and inclusive, all good
                // if left match and not inclusive, return right before left bound
                // if right match and inclusive, return left bound
                // if right match and not inclusive, return right bound
                if ( ( m % 2 == 0 && !toCmpInclusive ) || ( m % 2 == 1 && toCmpInclusive ) ) {
                    --ret;
                }
                return ret;
            }
        }
        assert( l + 1 == h );
        return l;
    }

    bool FieldRangeVector::matches( const BSONObj &obj ) const {
        if ( !_indexSpec.get() ) {
            _indexSpec.reset( new IndexSpec( _keyPattern ) );
        }
        // TODO The representation of matching keys could potentially be optimized
        // more for the case at hand.  (For example, we can potentially consider
        // fields individually instead of constructing several bson objects using
        // multikey arrays.)  But getKeys() canonically defines the key set for a
        // given object and for now we are using it as is.
        BSONObjSetDefaultOrder keys;
        _indexSpec->getKeys( obj, keys );
        for( BSONObjSetDefaultOrder::const_iterator i = keys.begin(); i != keys.end(); ++i ) {
            BSONObjIterator j( *i );
            BSONObjIterator k( _keyPattern );
            bool match = true;
            for( int l = 0; l < (int)_ranges.size(); ++l ) {
                int number = (int) k.next().number();
                bool forward = ( number >= 0 ? 1 : -1 ) * ( _direction >= 0 ? 1 : -1 ) > 0;
                if ( !matchesElement( j.next(), l, forward ) ) {
                    match = false;
                    break;
                }
            }
            if ( match ) {
                // The *i key matched a valid range for every element.
                return true;
            }
        }
        return false;
    }

    // TODO optimize more
    int FieldRangeVector::Iterator::advance( const BSONObj &curr ) {
        BSONObjIterator j( curr );
        BSONObjIterator o( _v._keyPattern );
        // track first field for which we are not at the end of the valid values,
        // since we may need to advance from the key prefix ending with this field
        int latestNonEndpoint = -1;
        // iterate over fields to determine appropriate advance method
        for( int i = 0; i < (int)_i.size(); ++i ) {
            if ( i > 0 && !_v._ranges[ i - 1 ].intervals()[ _i[ i - 1 ] ].equality() ) {
                // if last bound was inequality, we don't know anything about where we are for this field
                // TODO if possible avoid this certain cases when value in previous field of the previous
                // key is the same as value of previous field in current key
                setMinus( i );
            }
            bool eq = false;
            BSONElement oo = o.next();
            bool reverse = ( ( oo.number() < 0 ) ^ ( _v._direction < 0 ) );
            BSONElement jj = j.next();
            if ( _i[ i ] == -1 ) { // unknown position for this field, do binary search
                bool lowEquality;
                int l = _v.matchingLowElement( jj, i, !reverse, lowEquality );
                if ( l % 2 == 0 ) { // we are in a valid range for this field
                    _i[ i ] = l / 2;
                    int diff = (int)_v._ranges[ i ].intervals().size() - _i[ i ];
                    if ( diff > 1 ) {
                        latestNonEndpoint = i;
                    }
                    else if ( diff == 1 ) {
                        int x = _v._ranges[ i ].intervals()[ _i[ i ] ]._upper._bound.woCompare( jj, false );
                        if ( x != 0 ) {
                            latestNonEndpoint = i;
                        }
                    }
                    continue;
                }
                else {   // not in a valid range for this field - determine if and how to advance
                    // check if we're after the last interval for this field
                    if ( l == (int)_v._ranges[ i ].intervals().size() * 2 - 1 ) {
                        if ( latestNonEndpoint == -1 ) {
                            return -2;
                        }
                        setZero( latestNonEndpoint + 1 );
                        // skip to curr / latestNonEndpoint + 1 / superlative
                        _after = true;
                        return latestNonEndpoint + 1;
                    }
                    _i[ i ] = ( l + 1 ) / 2;
                    if ( lowEquality ) {
                        // skip to curr / i + 1 / superlative
                        _after = true;
                        return i + 1;
                    }
                    // skip to curr / i / nextbounds
                    _cmp[ i ] = &_v._ranges[ i ].intervals()[ _i[ i ] ]._lower._bound;
                    _inc[ i ] = _v._ranges[ i ].intervals()[ _i[ i ] ]._lower._inclusive;
                    for( int j = i + 1; j < (int)_i.size(); ++j ) {
                        _cmp[ j ] = &_v._ranges[ j ].intervals().front()._lower._bound;
                        _inc[ j ] = _v._ranges[ j ].intervals().front()._lower._inclusive;
                    }
                    _after = false;
                    return i;
                }
            }
            bool first = true;
            // _i[ i ] != -1, so we have a starting interval for this field
            // which serves as a lower/equal bound on the first iteration -
            // we advance from this interval to find a matching interval
            while( _i[ i ] < (int)_v._ranges[ i ].intervals().size() ) {
                // compare to current interval's upper bound
                int x = _v._ranges[ i ].intervals()[ _i[ i ] ]._upper._bound.woCompare( jj, false );
                if ( reverse ) {
                    x = -x;
                }
                if ( x == 0 && _v._ranges[ i ].intervals()[ _i[ i ] ]._upper._inclusive ) {
                    eq = true;
                    break;
                }
                // see if we're less than the upper bound
                if ( x > 0 ) {
                    if ( i == 0 && first ) {
                        // the value of 1st field won't go backward, so don't check lower bound
                        // TODO maybe we can check first only?
                        break;
                    }
                    // if it's an equality interval, don't need to compare separately to lower bound
                    if ( !_v._ranges[ i ].intervals()[ _i[ i ] ].equality() ) {
                        // compare to current interval's lower bound
                        x = _v._ranges[ i ].intervals()[ _i[ i ] ]._lower._bound.woCompare( jj, false );
                        if ( reverse ) {
                            x = -x;
                        }
                    }
                    // if we're equal to and not inclusive the lower bound, advance
                    if ( ( x == 0 && !_v._ranges[ i ].intervals()[ _i[ i ] ]._lower._inclusive ) ) {
                        setZero( i + 1 );
                        // skip to curr / i + 1 / superlative
                        _after = true;
                        return i + 1;
                    }
                    // if we're less than the lower bound, advance
                    if ( x > 0 ) {
                        setZero( i + 1 );
                        // skip to curr / i / nextbounds
                        _cmp[ i ] = &_v._ranges[ i ].intervals()[ _i[ i ] ]._lower._bound;
                        _inc[ i ] = _v._ranges[ i ].intervals()[ _i[ i ] ]._lower._inclusive;
                        for( int j = i + 1; j < (int)_i.size(); ++j ) {
                            _cmp[ j ] = &_v._ranges[ j ].intervals().front()._lower._bound;
                            _inc[ j ] = _v._ranges[ j ].intervals().front()._lower._inclusive;
                        }
                        _after = false;
                        return i;
                    }
                    else {
                        break;
                    }
                }
                // we're above the upper bound, so try next interval and reset remaining fields
                ++_i[ i ];
                setZero( i + 1 );
                first = false;
            }
            int diff = (int)_v._ranges[ i ].intervals().size() - _i[ i ];
            if ( diff > 1 || ( !eq && diff == 1 ) ) {
                // check if we're not at the end of valid values for this field
                latestNonEndpoint = i;
            }
            else if ( diff == 0 ) {   // check if we're past the last interval for this field
                if ( latestNonEndpoint == -1 ) {
                    return -2;
                }
                // more values possible, skip...
                setZero( latestNonEndpoint + 1 );
                // skip to curr / latestNonEndpoint + 1 / superlative
                _after = true;
                return latestNonEndpoint + 1;
            }
        }
        return -1;
    }

    void FieldRangeVector::Iterator::prepDive() {
        for( int j = 0; j < (int)_i.size(); ++j ) {
            _cmp[ j ] = &_v._ranges[ j ].intervals().front()._lower._bound;
            _inc[ j ] = _v._ranges[ j ].intervals().front()._lower._inclusive;
        }
    }

    struct SimpleRegexUnitTest : UnitTest {
        void run() {
            {
                BSONObjBuilder b;
                b.appendRegex("r", "^foo");
                BSONObj o = b.done();
                assert( simpleRegex(o.firstElement()) == "foo" );
            }
            {
                BSONObjBuilder b;
                b.appendRegex("r", "^f?oo");
                BSONObj o = b.done();
                assert( simpleRegex(o.firstElement()) == "" );
            }
            {
                BSONObjBuilder b;
                b.appendRegex("r", "^fz?oo");
                BSONObj o = b.done();
                assert( simpleRegex(o.firstElement()) == "f" );
            }
            {
                BSONObjBuilder b;
                b.appendRegex("r", "^f", "");
                BSONObj o = b.done();
                assert( simpleRegex(o.firstElement()) == "f" );
            }
            {
                BSONObjBuilder b;
                b.appendRegex("r", "\\Af", "");
                BSONObj o = b.done();
                assert( simpleRegex(o.firstElement()) == "f" );
            }
            {
                BSONObjBuilder b;
                b.appendRegex("r", "^f", "m");
                BSONObj o = b.done();
                assert( simpleRegex(o.firstElement()) == "" );
            }
            {
                BSONObjBuilder b;
                b.appendRegex("r", "\\Af", "m");
                BSONObj o = b.done();
                assert( simpleRegex(o.firstElement()) == "f" );
            }
            {
                BSONObjBuilder b;
                b.appendRegex("r", "\\Af", "mi");
                BSONObj o = b.done();
                assert( simpleRegex(o.firstElement()) == "" );
            }
            {
                BSONObjBuilder b;
                b.appendRegex("r", "\\Af \t\vo\n\ro  \\ \\# #comment", "mx");
                BSONObj o = b.done();
                assert( simpleRegex(o.firstElement()) == "foo #" );
            }
        }
    } simple_regex_unittest;

    long long applySkipLimit( long long num , const BSONObj& cmd ) {
        BSONElement s = cmd["skip"];
        BSONElement l = cmd["limit"];

        if ( s.isNumber() ) {
            num = num - s.numberLong();
            if ( num < 0 ) {
                num = 0;
            }
        }

        if ( l.isNumber() ) {
            long long limit = l.numberLong();
            if ( limit < num ) {
                num = limit;
            }
        }

        return num;
    }

    string debugString( Message& m ) {
        stringstream ss;
        ss << "op: " << opToString( m.operation() ) << " len: " << m.size();
        if ( m.operation() >= 2000 && m.operation() < 2100 ) {
            DbMessage d(m);
            ss << " ns: " << d.getns();
            switch ( m.operation() ) {
            case dbUpdate: {
                int flags = d.pullInt();
                BSONObj q = d.nextJsObj();
                BSONObj o = d.nextJsObj();
                ss << " flags: " << flags << " query: " << q << " update: " << o;
                break;
            }
            case dbInsert:
                ss << d.nextJsObj();
                break;
            case dbDelete: {
                int flags = d.pullInt();
                BSONObj q = d.nextJsObj();
                ss << " flags: " << flags << " query: " << q;
                break;
            }
            default:
                ss << " CANNOT HANDLE YET";
            }

        }
        return ss.str();
    }

} // namespace mongo


text:
All Sections | News Reportage Articles Special Coverage
Safi Kaskas and Abdalrahman Aboelmajd discuss The Qur'an, A ...
Abdur-Rahman Abul-Majd
Samira Amarir and Abdalrahman Abulmajd about Jenna the ...
Marek Dziekan and Abdalrahman Abulmajd about Qur'anic ...
Lisa Suhay and Abdalrahman Abou Almajd around Mrs. Lisa's ...
Peter Bussey and AbdurRahman Abou Almajd Modern Physics ...
Rebecca Ruth Gould and Abdalrahman Abou Almajd about ...
Sheeza Ali and Abdalrahman Abulmajd discuss God is not a ...
This is what it's like to do Ramadan fasting in the ...
Ramadan also about Quran's True Message
Muslims free to observe Fasting in China
Gambia bans music, dance during Ramadan
punchng
Jerry Bergman and Abdalrahman Abulmajd discuss Darwinism as ...
Home / Muslims Around the World / Reportage
Peter Bussey and AbdurRahman Abou Almajd Modern Physics Point the Way to Belief
Published On: 19/7/2017 A.D. - 24/10/1438 H. Visited: 9559 times
Peter Bussey and AbdurRahman Abou Almajd Modern Physics Point the Way to Belief.
Signposts to God: How Modern Physics and Astronomy Point the Way to Belief.
(We will show them Our signs in the horizons and within themselves until it becomes clear to them that it is the truth.41:53) Sahih International:
We have a fresh opportunity to reflect on Modern Physics Point the Way to Belief!
At this point Peter Bussey, who a particle physicist, isn't going to speak about his views on How Modern Physics and Astronomy Point the Way to Belief only, but he also speaks about challenges face physicalism.
Peter Bussey
Dr Peter Bussey is a particle physicist and a research fellow in the School of Physics and Astronomy at Glasgow University. He is a fellow of the Institute of Physics and previously served at Cambridge University, CERN, and Sheffield University.
Bussey is involved in research with several international particle physics collaborations, including the ZEUS Experiment at DESY in Hamburg, Germany, the CDF Experiment at Fermilab in Chicago, and the ATLAS Experiment at CERN, Geneva, Switzerland. He is widely published in journals such as Science and Christian Belief.
Dr. Bussey is a contributor to 'God and the Big Bang' series of videos.
Q: First of all what made you take up Modern Physics and Astronomy?
PB: I have been active in experimental elementary particle physics for many years. I chose this career because I was interested in understanding basic things.
Q: I want to know what Modern Physics and Physics are.
PB: There are many areas of physics and astronomy where research is active and exciting. In elementary particle physics, the search is for new particles and a more general theory of particles and the structure of matter. The most important recent discovery has been that of the so-called Higgs particle, which is necessary to complete a pattern of particles and to provide a theoretical mechanism by which they can be massive, and not massless like the photon which is the "particle of light". The search is now for "supersymmetric" particles which some theorists predict. In astronomy, the most important recent discovery has been of gravitational waves, which are emitted when really heavy star-like object collide. These even may be "black holes", as predicted by Einstein's theory. In general there is a desire to understand the Big Bang that is believed to have occurred at the beginning of the universe. There are many other important areas of physics – these are just a few.
Q: Could you elaborate on Modern Physics Point the Way to Belief?
PB: I think the most important factor is that the universe is structured in an intelligent way, with mathematical patterns that are apparently essential in order to make the universe work at all. That the universe apparently needs to have a First Cause is also significant. Also, that the physical parameters that are part of the universe appear to be selected within narrow ranges that are appropriate in order for advanced intelligent life to emerge within the universe. That this life is conscious is also very significant, something that one would never be able to predict from first physical principles. All this makes sense if there is a Designer and Creator behind the scenes. Without this, everything is irrational, but we do not seem to live in an irrational universe.
Q: As you said: I think the most important factor is that the universe is structured in an intelligent way it's agreed perfectly to the Qur'an, (the artistry of Allah, who disposes of all things in perfect order. 27:88),Yusuf Ali, You criticize physicalism as Physicalism appears to be similar to materialism, a view that excludes the spiritual by saying that matter is all that there is.
PB: Indeed. "Physicalism" is the preferred term now because of our uncertainty about the material interpretation of quantum physics. But the idea is the same – nothing but physical things. However physics can say nothing about our conscious existence because physics is not set up to talk about this kind of thing. So to insist that physics is all that there is is arbitrary and goes against our most basic experience. Physicalism is simply a way of trying to avoid the really important questions.
Q: I don't know how quantum physics may pose a challenge to physicalism.
PB: Quantum physics is a branch of physics, and you could say that this is now the physics that defines physicalism. But our interpretation of quantum physics is very unclear – there is no universally accepted philosophy here. So any reliance on "physicalism" now rests on very uncertain foundations and amounts to a statement of faith without any well-defined basis.
Q: What about Modern Astronomy and the vastness of the universe?
PB: The universe is vast. It has to be, in order for the processes to occur that will generate stars and planets, and for everything to last long enough for life to evolve. No problem should be seen here, but from the believer's point of view you do have to believe that God is big enough to be interested in everything, even human beings on a small planet.
Q: Great, you reminding me "And the heaven we constructed with strength and indeed we are its expanders the Qur'an " [51:47] Sahih International. and Psalm 19:2 ·
The heavens declare the glory of God; the skies proclaim the work of his hands.
How do Modern Physics point to a designer, could you elaborate on some modern proves?
PB: I have already answered this above. The one thing to add is that if the universe is structured so as to generate life that ends up as conscious, namely ourselves, then it looks as if the Designer is interested in conscious beings, and must in some sense possess consciousness Himself.
This is very important for traditional religious belief.
Abdalrahman: Thank you very much, Dr. Peter Bussey.
Peter Adamson and AbdurRahman Abou Almajd in Islamic philosophy(Article - Muslims Around the World)
Peter Wright and Abdur-RahmanAbouAlmajd in dialog about Modern Qur'anic Hermeneutics(Article - Muslims Around the World)
Duston Barto and AbdurRahman Abou Almajd in some issues facing the Muslim American ummah(Article - Muslims Around the World)
Leonard Swidler and AbdurRahman Abou Almajd on a Bridge to Islamic-Christian Dialogue(Article - Muslims Around the World)
When A Muslim Is At The Point Of Death(Article - Counsels)
The Lowest Point of Earth(Article - Thoughts and Knowledge)
Is life in Paradise like our modern life?(Counsel - Counsels)
Amazing Muslim Inventions Shaped the Modern World(Article - Muslims Around the World)
Modern communication technology (concept and term)(Article - Thoughts and Knowledge)
Kaaba Kiswa Manufacturer Seeks Modern Technology(Article - Muslims Around the World)

redpajama_set_name: RedPajamaCommonCrawl


Google has finally released Google Chrome 4 stable version, which brings in support for Extensions, Bookmark Sync and other 1500+ features to the masses. A great news for both the extension developers and users. Also, according to Chrome blog, chrome 4.0 is 42% faster compared to Chrome 3.0 and 400% since the first stable release last year.
Now chrome is really much faster.
I still prefer mozilla firefox. It has a lot of plugins that can help enhance the usability and performance.


text:
Q: Only some Layout Params work I am trying to align a custom View object above and aligned_left of a RelativeLayout. My (snipped) code looks something like this:
int bored = board.getId(); //board is the RelativeLayout
Border border = new Border();
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.ALIGN_LEFT, bored);
params.addRule(RelativeLayout.ABOVE, bored);
this.addView(border,params);

This gives me a Border object aligned_left with my RelativeLayout but NOT "ABOVE" (technically, it is above it, but it's at the top of the screen not aligned the way it's supposed to be). And, even stranger, when I do this:
int bored = board.getId();
Border border = new Border();
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.ALIGN_LEFT, bored);
params.addRule(RelativeLayout.BELOW, bored); //<---The only difference
this.addView(border,params);

...it works perfectly. it is aligned left and below in the ways that are expected. Why is the ABOVE attribute giving me such a hard time?
Edit:
ABOVE is supposed to align the bottom edge of one view with the top edge of the target. Here is a screen shot of how my project is not working as intended.

The green bar at the top of the screen is the Border object I am trying to align. As you can see, its left edge is aligned with "board" however it is in the wrong place at the top of the screen.

A: Can you check if board and Border are not using more space? for example, by setting the background to a color to see their dimensions in the screen?
Maybe board, which you mention is a RelativeLayout is bigger of what you think.
I hope this helps

A: I fixed my problem by using an ImageView instead of my custom Border class (which was basically just a bitmap drawn to a canvas from a resource). My code now looks like this:
int bored = board.getId(); //board is the RelativeLayout
ImageView border = new ImageView(this);
border.setImageResource(R.drawable.border_tiki1);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.ALIGN_LEFT, bored);
params.addRule(RelativeLayout.ABOVE, bored);
this.addView(border,params);

My best guess is that it was having trouble defining the ABOVE constant for my custom object. Thanks to everyone who took the time to look over this. Here's what my view looks like now:

From this anchor, I'll build the rest of the border out of other small pieces. Thanks again!

A: Without seeing the rest of the code, this is just a guess, but the order in which the objects are created makes a difference in how the objects are layed out. Especially where Relative Layouts are concerned.

redpajama_set_name: RedPajamaStackExchange


One of the steepest hurdles for any entrepreneur to overcome is finding adequate capital for the growth of a new business. While acquiring such financing can be difficult even in the best of times, it is particularly problematic in today's credit-impaired economy. Business Financing and Factoring is designed to provide entrepreneurs with the necessary knowledge to overcome such financing limitations, arming them with powerful options when their banks either "don't know" or simply say, "No!"
Business Financing and Factoring will introduce you to the world of alternative commercial finance (ACF). It is a cutting-edge course packed with the specialized financial knowledge required by each and every entrepreneur seeking to launch a business and become his or her own boss.
Finally, Business Finance and Factoring introduces students to the prestigious world of the ACF broker and the opportunities present as an industry commercial finance consultant (CFC). Such industry consultants can earn exceptionally attractive fees and residual commissions while assisting other entrepreneurs in locating working capital and trade financing.


text:
layout: post
title:  "#EnglishGrammar, Lesson Twenty-eight - Past Perfect Tense"
date:   2017-05-13 17:40:00
categories: English grammar lesson
---

O **Past Perfect Tense** é formado pelo auxiliar **to have** no passado e o verbo principal no **Past Participle**.

Exemplos: verbo to read

I had read |  eu tinha lido | I'd read
you had read | tu tinhas linhas lido | you'd read
he had read | ele tinha lido | he'd read
she had read | ela tinha lido | she'd read
it had read | ele/ela tinha lido | it'd read
we had read | nós tínhamos lido | we'd read
you had read | vós tínheis lido | you'd read
they had read | eles tinham lido | they'd read

Usamos o **Past Perfect** para indicar uma ação passada anterior a uma outra (que vem indicada pelo **Simple Past**). É, normalmente, usado com as preposilçies **before** (antes) e **after** (depois), bem como **already** e **yet**.

 - The plane **had taken** off when Paul **arrived** at the airport. O avião já havia decolado quando Paul chegou.
 - My brother **came** in after his girlfriend **had gone** away. Meu irmão entrou depois que sua namorada tinha ido embora.
 - The film **had started** before he **arrived**. O filme tinha começado antes dele dele chegar.
 - My wife **had** already **had** dinner when I **arrived**. Minha esposa já tinha jantado quando eu cheguei.
 - She **had played** chess before. Ela tinha jogado xadrez antes.

**Forma negativa**

Fazemos uma negação acrecentando-se a partícula **not** ao auxiliar **to have**.

 - He **had not arrived** yet. Ele ainda não tinha chegado.
 - We **hadn't eaten** when our friends **arrived**. Nós não tínhamos comido quando nossos amigos chegaram.

**Forma interrogativa**

Fazemos a interrogação invertendo as posições de sujeito e do verbo auxiliar.

 - **Had** you already **gone** to Mexico? Você já tinha ido para o México?
 - **Had** he recognized** her? Ele a tinha reconhecido

redpajama_set_name: RedPajamaGithub


Chelsea midfielder set for LA Galaxy? | The Transfer Tavern | Where football transfer rumours fly or die!
Chelsea midfielder set for LA Galaxy?
Frank Lampard has had an illustrious career in the Premier League but according to rumours emerging in the Football Transfer Tavern he set to end his time in England by becoming David Beckham's replacement at LA Galaxy, according to Mirror Football.
The England international will make his 500th Premier League appearance in the Blues game against Aston Villas on Sunday but he appears to have accepted that his days at Stamford Bridge are set to end this summer after a 12 years association with the West London outfit.
The 34-year-old had been linked with a move to QPR to help out Uncle Harry Redknapp but now Lampard is set to make the move to America when his contract expires at the end of the season.
Beckham has now left the MLS side leaving a gap in the 'designated player' rule meaning he is not subject to the usual salary cap and rumours that LA will offer Lampard more than £130,000-per-week are rife.
Interim Chelsea manager Rafael Benitez yesterday gave the dreaded vote of confidence surrounding Lampard's commitment to the cause. The manager said: "Frank is an important player for us. His quality and experience are something we can use to help the team and we know he will score goals as well.
Is Lampard's English experience coming to an end? Vote in our polls below.


The ideal material for projects ranging from standard industrial applications to special construction.
JACKODUR® is a high-quality thermal insulation material in extruded polystyrene foam (XPS) and is particularly pressure resistant, dimensionally stable, and moisture and rot resistant. When extruded polystyrene is used in industrial applications, there are high technical specifications for the XPS material, such as high compressive strength with low bulk densities, together with exact thicknesses and precise tolerances. JACKODUR close-tolerance boards satisfy these requirements and can be used in a variety of applications, such as: Sandwich elements, Door panels, XPS cut to size, Motorhomes, Refrigerated vehicles, Special-purpose vehicles.
Special-purpose vehicles Individual solutions with JACKODUR® XPS for even the smallest production runs.
Motorhomes In the construction of recreational vehicles and camping cars, tolerances, stability and weight are crucial factors.


The skyline of pre-war Intramuros was dominated by the domes and towers of different churches. Here you can see the dome of the Manila Cathedral on the left and the Neo-Gothic Santo Domingo Church on the right. You can also see the dome and the tower of the nearby Binondo Church as seen at a distance.
Pre-war Intramuros boasted some of the best and most magnificent churches that exhibited three centuries worth of history and religious heritage in the Philippines. Treasures that remain a mere memory of the past, ravaged by the inexcusable destruction of the city in 1945. Out of all the eight churches, only one survived the destruction of the city. One was rebuilt. One was left in ruins. And all the rest were replaced by modern, soulless, box buildings or mediocre, cheap-looking, feeling old ones that are so out of place. Even though most of these churches are gone now, their legacy will always and forever be a part of our identity as Filipinos.
Intramuros panorama, c1916. The towers of San Agustin, San Ignacio and Santo Domingo. Manila Cathedral's dome can also be partially seen.
Accomplishing this feature has surely taught me a lot of things. I felt a rush of pride and amazement as I was rummaging for photographs and information about these churches. I was always in awe and slightly heartbroken every time I looked at the data that I had collected. I was always so excited to publish it for the whole world to see.
The map I made below shows the proximity of the churches to one another. Oh, Visita Iglesia must have been so fun and convenient back then!
1934 map showing all the 8 churches that once stood proudly in the walls of Intramuros. Only the Manila Cathedral and the San Agustin Church exist today.
In case you missed it, just click on the links below and... READ AWAY!


Georgia Institute of Technology's Lauren Wilcox, an assistant professor in the School of Interactive Computing, recently received a National Science Foundation CAREER award for her research investigating how computational tools can be designed and developed to support collaborative generation and management of everyday, health-related data.
The award, which provides $553,000 for her research, will help Wilcox build on previous studies that investigated how adolescents with chronic illnesses use personal data management tools. Wilcox said the overall goal for the upcoming research is to advance the current state of the art in mobile health sensing.
This will mean, in part, allowing for the reconciliation of system-generated observations, contributed through physiological sensing, and human-contributed observations, like self-reported pain levels.
A challenge is that both adolescents and parents have observations on the adolescent's health, and they don't always agree.
"Who is an expert on what's really happening?" she asked. "They kind of both are. Teens tend to under-report symptoms, which is a problem because if we don't know what they're dealing with, we can't tailor treatment plans. At the same time, parents can over-report. This creates a problem for physicians, but it can also create tensions in the home.
First, she plans to do some formative studies, examining different automated strategies for eliciting symptom data.
"What kinds of data are teens comfortable contributing and comfortable with their parents contributing, and in what ways" she said.
Next, she will prototype and pilot test different strategies for eliciting the data. From there, she plans to develop new collaborative data interaction techniques that leverage the mobile sensing technologies and contribute some user interface software for tracking and managing adolescents' personal health data. And in a longer-term study, she wants to examine the effectiveness of the tools.
"We want to validate that it's usable and examine whether they accept the technology, looking at things like user burden, confidence in carrying out self-management tasks, and impact on communication with clinical caregivers," she said.
Wilcox's integrated education plan will have significant impacts on graduate and undergraduate students. It will encourage young women and minorities to engage in careers in computing and engineering through two outreach programs, and foster mentoring skills at the undergraduate and graduate levels through outreach activities with high school students.
From a personal standpoint, Wilcox said she was thrilled to receive the award and funding from the NSF.
"It contributes to my long-term goals to design, develop, and evaluate automated tools for personalizing interventions that help teenage adolescents better understand their personal health data and engage in self-care tasks," she said.


Whitehead Commercial Interiors will only collect Personal Information where the information is necessary for Whitehead Commercial Interiors to perform one or more of its functions or activities. In this context, "collect" means gather, acquire or obtain by any means, information in circumstances where the individual is identifiable or identified.
c. to provide you with information about promotions, as well as the products and services of Whitehead Commercial Interiors and other organisations.
• and the address of the pages you accessed.
With your permission, we may send you occasional emails about our promotions, new products and other updates.
You can use the online forms for a number of purposes such as to request further information about other Whitehead Commercial Interiors products and services. In order to process your request, we will require you to provide us with certain personal information. This includes such details as your name and contact details.
If after you opt-in, you change your mind, you may withdraw your consent for us to contact you, for the continued collection, use or disclosure of your information, at anytime, by emailing sales@www.ianwhitehead.co.uk or calling us on +44 114 249 0050.
Whitehead Commercial Interiors will take reasonable steps to ensure that its contracts with third parties include requirements for third parties to comply with the Use and Disclosure requirements of the Privacy Act.
Information collected at this site may be disclosed to third parties where functions are being outsourced. Whitehead Commercial Interiors may also disclose personal information to law enforcement agencies, government agencies, courts or external advisors where permitted or required by law.
To protect your personal information, we take reasonable precautions and follow industry best practices to make sure it is not inappropriately lost, misused, accessed, disclosed, altered or destroyed. Whitehead Commercial Interiors requires employees and contractors to perform their duties in a manner that is consistent with Whitehead Commercial Interiors' legal responsibilities in relation to privacy. Whitehead Commercial Interiors will take all reasonable steps to ensure that paper and electronic records containing Personal Information are stored in facilities that are only accessible by people within Whitehead Commercial Interiors who have a genuine "need to know" as well as "right to know".
Whitehead Commercial Interiors strives to protect your personal information during its transmission. Whitehead Commercial Interiors' secure server software (SSL) is the industry standard and among the best software available today for secure commerce transactions. It encrypts all of your personal information, including your name and address, so that it cannot be read as the information travels over the Internet. However, while Whitehead Commercial Interiors maintains high standards in protecting your security, no transmission over the Internet or storage of information on servers connected to the Internet can be guaranteed to be absolutely secure.
Whitehead Commercial Interiors takes reasonable steps to ensure the security of personal information held by it from such risks as loss or unauthorised access, destruction, use, modification or disclosure of data. Whitehead Commercial Interiors only permits your details to be accessed by authorised personnel.


text:
"Because woman gives care and life to the world: she is the way to peace"
"Invite everyone to walk together on the path of peace and salvation that God"
"I am with you in defending the rights of the faithful of every religious community"
Australian Cardinal George Pell has died
Pope Emeritus Benedict XVI Has Died
The Pope's hearing with the President of the Republic of Niger
Church and World
Apostolic Journey to the Democratic Republic of Congo and South Sudan
"For a synodal Church: communion, participation and mission"
Cuba celebrates anniversary of John Paul II visit amid social and economic crisis
"The faith is the most precious treasure"
Fr. Guerrero on Holy See Financial Statement: New steps forward in transparency, sustainability
Interview: Fr Antonio Vatseba, Ukrainian Greek Catholic Priest
Seattle public schools have sued several social networks
Gänswein's blow to Francis, Benedict and his own mission
Benedict XVI, a wise and humble pope
France refuses to include abortion as a right in the Constitution
What is happening with Father Kentenich 54 years after his departure
The dilemma of when human life begins
Florence Charter: Here Is the Text of the Document
Liturgical Rite to Institute the Ministry of the Catechist
Vatican Guidelines on Use of Distance Learning
Nigerian priest: "I shielded them as a hen shields her chicks"
Exaudi Staff·
· 17 Jun ·4 min read
Attack turns Pentecost Mass into bloodbath:
Bishop Jude Arogundade of Ondo, Nigeria (without a mask) visiting the survivor of terrorist attack © ACN
Father Andrew Adeniyi Abayomi is the associate pastor at St Francis Xavier church in Owo, Ondo state, Nigeria, which was hit by a terror attack during Mass on Pentecost Sunday, June 5. The massacre left at least 41 worshipers dead and dozens seriously wounded. Father Abayomi spoke with Aid to the Church in Need about his experience that day, and about the aftermath of the massacre that saw the local Church jump into action to care for the wounded and those mourning the loss of loved ones.
How many attackers were there?
Father Andrew Adeniyi Abayomi, the assistant parish priest conducting the Mass before the attack © ACN
I did not see them, but some eyewitnesses say there were four, while others said that in addition to the four there were some among us in church. Some say six, in total, but the actual number is unknown.
Where were you when the attack happened?
I was still on the sanctuary. I had finished the Mass and was putting incense in the thurible, to prepare for the procession outside the church. That was when I heard a noise. I thought it was a door slamming, or that someone had fallen, or seen a snake, because that has happened before.
But then I heard a second loud noise, and I saw parishioners running in different directions in the church. I stood there in shock, wondering what was going on, when someone ran to me, yelling: "Father, unknown gunmen!"
Did you fear for your life?
At that point I did not fear for my life, rather, I was thinking how to save my parishioners. Some of them summoned the courage to lock the entrance door. I urged people to move through the sanctuary into the sacristy. Some of the parishioners escaped through there. I remained in the inner part of the sacristy. I could not run as I was surrounded by children, while some adults clung to me, some even inside my chasuble. I shielded them just as a hen shields her chicks.
I heard the voices of my parishioners: "Father, please save us; Father, pray!" I encouraged them and calmed them, and said they should not worry, that I was praying, and that God would do something. I heard three or four explosions, one after the other. The whole attack was well planned and lasted about 20-25 minutes.
Finally, we got a message that the attackers had gone. We left the sacristy and I saw that some of the parishioners were dead, while many were injured. I was troubled in my spirit. I pleaded with people to drive our injured brothers and sisters to the hospital. I began moving some of the injured to St. Louis hospital and the Federal Medical Center, with the help of parishioners who were able to drive. We left the dead bodies in church, while trying to save the wounded.
Ondo state has been peaceful, especially compared to northern Nigeria and the Middle Belt, though there have been some tensions between Fulani herdsmen and Christian farmers. How do you explain this sudden outburst of violence?
We have been hearing that militant groups are mobilizing people in the southwest and other parts of the country. We cannot ascertain the tribe, the race, or the group the attackers belong to. Even when the attack was going on, some saw them, but they could not identify them as they didn't speak. Some of the attackers disguised themselves as regular parishioners during Mass. They worshiped with us during Mass until the attack started.
The church after a terrorist attack in Nigeria © ACN
How will you go about caring for the wounded and grieving parishioners?
We have started doing that already, giving them pastoral care, visiting them, praying with them, administering the Sacrament of the Sick and encouraging them to keep hope alive. We went further to care for their families and the bereaved. The diocese called on other parishes for support. Government as well as non-governmental organizations, like the Red Cross, and other groups, even Muslim groups and imams, are coming to our aid practically and financially. The Red Cross has been the most active, pleading for blood donors and material support.
What are the biggest needs right now?
We need material and financial support to care for the victims and the survivors. We also need our own security strategy. Nearby security personnel and police failed to come to our rescue, even though the attack lasted 20 minutes and four artefacts exploded. We need our own security apparatus.
After an experience like this, will people feel safe returning to church?
Blessing a survivor of the terrorist attack © ACN
Fear has set in the minds of some of the parishioners. Bearing this in mind, we are determined to get them on their feet, to keep them strong in faith, and to comfort them by getting close to each one, not only those who were directly affected. The goal is to establish personal contact with them, strengthening them and reminding them that when we profess our faith in God, it means that we have given up our whole life. This life is just a passage to eternity — and eternity should be our focal point.
Has the attack strengthened or weakened their faith?
From my encounter with parishioners, I have not seen a loss of faith, but a strengthening. They are ready and willing to remain steadfast. I keep praying for them, every day, and Mass is being offered for the intentions of those still in the hospital, to aid their quick recovery. Mass is also being said for the souls of those who died, may they rest in peace. Finally, Masses are being offered for the intentions of all members of the parish, so that they may remain steadfast in faith and alive in hope.
nigeriaTrending
Exaudi Staff
Pentescost tragedy in Nigeria: The stories behind the numbers
Ukraine: With Kyiv still restless, priests thank ACN for support
Nicaragua bishop on hunger strike to protest police harassment
Sister Maria Rosa Leggol's Living Legacy
Pope Francis Activities
To Participants in the International Conference "Women Building a Culture of Encounter Interreligiously" (26 January 2023) 26 Jan
Solemnity of the Conversion of Saint Paul - Celebration of Second Vespers (25 January 2023) 25 Jan
General Audience of 25 January 2023 - Catechesis. The passion for evangelization: the apostolic zeal of the believer. 3. Jesus teacher of proclamation 25 Jan
Tweets of Pope
Tweets by Pontifex
pope francis Featured Trending ukraine vatican


Here's a small script that automatically creates network teams with Broadcom nics. Once Windows 8 Server rolls around this won't be needed since the teaming functionality (probably) moves into OS level. But for now… The script requires you to install the Broadcom utilities (or let the script do that for you) and supports three different types of teams. It's meant to be used for example when deploying Windows Server with SCCM or MDT (or Altiris for that matter).
Heavily commented for your change-of-code-pleasures.
Previous PostLots of stuff happening!Next PostTechDays 2012 – The preparation!


The basics of lead tracking, web search, reviews, website optimization, and more with EnergyCircle's Chris Williams.
From prototype to distribution with Sustainable Technologies' second generation flexible roof-mount system.
r.e.thinking Energy with BayWa r.e.
Advance your strategic projects by setting priorities correctly across your organization.
BayWa r.e. sales rep Gilbert Quintana reviews the UNIRAC Sunframe Microrail (SFM).
BayWa r.e. partners with software company PVComplete and chats about '5 Free Projects a Month' and 'Click to Quote' features.
Boaz discusses the risks of having too much (and too little) inventory, cash flow considerations, the effects of labor, availability, technology, and more.
Three ways to think about the solar industry's increasing complexity.
Storage is hot. David Dunlap gives an overview on the current state of storage and shares tips on how to talk to your customers about their storage options.
And learn from the best minds in solar.


text:
Batalion Silnikowy – oddział saperów Wojska Polskiego w II Rzeczypospolitej.

Formowanie i zmiany organizacyjne
Batalion został sformowany w styczniu 1930, w Nowym Dworze Mazowieckim. Podlegał Dowództwu (Szefostwu) Saperów Ministerstwa Spraw Wojskowych.

Podstawą utworzenia w Wojsku Polskim oddziałów silnikowych, zwanych wtedy motorowymi, był sprzęt pochodzący z byłej armii austro-węgierskiej. Na początku 1919, w Krakowie, została sformowana kompania motorowa wojsk kolejowych nr 1 pod dowództwem porucznika inżynier Stanisława Langnera. Zadaniem tej kompanii była budowa i eksploatacja kolejek polowych. W marcu 1919 pododdział został przydzielony do I Batalionu Wojsk Kolejowych. W sierpniu 1919 ukończono tworzenie kompanii motorowej nr 2 pod dowództwem kapitana Władysława Łuczyńskiego, która została wcielona do II Batalionu Wojsk Kolejowych. Podczas walk o Niepodległość obie kompanie motorowe nie odegrały istotnej roli. Wiadomo, że działały one przede wszystkim na Podolu i Wołyniu.

Od 1928 był on rozbudowywany i ostatecznie 10 stycznia 1930 utworzono batalion silnikowy z miejscem postoju w Modlinie. Baon wchodził w skład 1 Brygady Saperów. W marcu 1934 baon został podporządkowany dowódcy 3 Brygady Saperów.

7 grudnia 1931 Minister Spraw Wojskowych ustalił datę święta baonu na dzień 10 lutego.

Mobilizacja i rozformowanie baonu w 1939

Mobilizacja
We wrześniu 1939, w mobilizacji powszechnej, Batalion Silnikowy dowodzony przez ppłk. Stanisława Olczaka wystawił:
 osiem plutonów eksploatacyjnych silnikowych 60 cm o numerach: 11-18 dla Odwodu NW,
 cztery pociągi elektrogeneratorowe normalnotorowe o numerach: 12, 19, 23, 24, w tym dwa dla Armii "Pomorze" (nr 12 i 19)
Ponadto, w składzie załogi Wojskowej Składnicy Tranzytowej na Westerplatte pozostawał pociąg elektrogeneratorowy normalnotorowy nr 27.

Mobilizacja plutonów eksploatacyjnych silnikowych 60 cm (wąskotorowych) odbywała się w ramach I rzutu mobilizacji powszechnej w terminach od 3 do 6 dnia mobilizacji. Natomiast mobilizacja pociągów elektrogeneratorowych normalnotorowych odbywała się w II rzucie mobilizacji powszechnej w terminach od X+3 do X+9.

Mobilizowane plutony eksploatacyjne silnikowe wąskotorowe etatowo obsługiwały odcinek 15-20 km i 4 stacjach. Na stanie miał 3 pociągi składające się każdy z elektrowagonu i 5 wózków silnikowych, był w stanie na odcinku 20 km przewieźć 90-130 t zaopatrzenia z prędkością 7-9 km/h. Pluton taki składał się z:

 dowódcy, ordynansa i kreślarza
 oddziału trakcji i ruchu
 drużyna trakcji przy obsłudze na dwie zmiany liczyła 40 kierowców wózków silnikowych + 8 zapasowych,
 drużyna ruchu i telefoniczna składała się z 2 zawiadowców, 8 dyżurnych ruchu, 12 zwrotniczych i 4 osobowy patrol telefoniczny, łącznie 26 żołnierzy,
 drużyna drogowa liczyła 1 dozorcę drogowego i 12 torowych,
 warsztat z 4 monterami,
 drużyna gospodarcza z 11 żołnierzami.

Pluton liczył 2 oficerów, 113 szeregowych, wyposażony był w 20 wózków silnikowych, 16 kbk, 73 pistolety, 24 sztylety (bagnety), 4 skrzynie do gotowania.

Pociągi elektrogeneratorowe normalnotorowe, służyły do transportu i ewakuacji i przewozu zaopatrzenia. Pracować miał na odciętych przez przeszkody odcinkach kolejowych, jednorazowo przewoził 70 t zaopatrzenia z prędkością 25 km/h. Składał się z elektrowagonu, 4 wagonów silnikowych dodatkowo można było uzupełnić skład 2 wagonami 15 t. Pociąg składał się z oficera-dowódcy, ordynansa, podoficerów; broni, technicznego i gospodarczego, 2 kierowników, 2 pomocników, 2 elektromonterów, 2 kierowców i 2 hamulcowych. Łącznie 15 żołnierzy na dwie zmiany.

Działania bojowe pododdziałów zmobilizowanych przez batalion silnikowy
Po zarządzeniu mobilizacji alarmowej siłami stanu pokojowego batalionu wykonano szereg zadań transportowych na rzecz innych jednostek saperskich garnizonu Modlin. Na przykład w dniu 28 sierpnia przewożono drewno do budowy umocnień twierdzy z lasów nadleśnictwa Pomiechówek.

11 i 12 plutony eksploatacyjne silnikowe wąskotorowe

Z chwilą ogłoszenia mobilizacji powszechnej od 31 sierpnia 1939 roku w ramach jej I rzutu jako pierwsze sformowano 11 i 12 plutony eksploatacyjne silnikowe wąskotorowe. 11 pluton posiadał 20 sztuk wozów silnikowych trzytonowych, a 12 pluton 12 wozów pięciotonowych silnikami Polski Fiat 122B. Oficerowie i podoficerowie otrzymali pistolety w ilości ok. 60 sztuk, a szeregowi 27-29 kbk, reszta bagnety i sztylety. Sprzęt silnikowy, pomiarowy i budowlany został pobrany zgodnie z wykazami należności. 1 września oba plutony osiągnęły gotowość do działań. Dowódcą 11 plutonu został por. Marian Wenge, a 12 plutonu por. Henryk Sosnowski. W godzinach południowych plutony udały się do Szczypiorna koło Modlina. W nocy z 1/2 września dowództwo 11 plutonu objął kpt. Edward Rudomin-Dusiatski. 2 września plutony karczowały la w rejonie Szczypiorna, a pozyskane drewno przetransportowano do północnej części twierdzy. 3 września 11 i 12 plutony pod dowództwem kpt. Rudomira-Dusiatskiego przydzielono do Kwatery Głównej Naczelnego Wodza i rozkazem ze stanowiska NW miały odjechać do rejonu Lublina. Z uwagi na brak transportu kolejowego w Modlinie, plutony przegrupowano celem zawagonowania do Palmir. Nocą 3/4 września i 4 września do południa 11, 12, oraz sukcesywnie formowane plutony 13, 14,15 i 16 pracowały przy budowie kolejki wąskotorowej z twierdzy modlińskiej do Kazunia. Po wybudowaniu torów połączono się z siecią międzyfortową linii wąskotorowej, którą można było dojechać do składnicy w Palmirach. 11 pluton po południu 4 września wybudował odcinek wąskotorowy do linii normalnotorowej prowadzący do składów i magazynów w Palmirach. 5 września 11 i 12 plutony wybudowały prowizoryczne rampy i załadowały swój sprzęt na transport normalnotorowy. Rano 6 września po perturbacjach z lokomotywą transport z 11 i 12 plutonami wyruszył w kierunku Warszawy. W pobliżu Bielan żołnierze plutonów musieli naprawić nasyp i tor kolejowy wysadzony przez polskich saperów przez dezinformację dywersantów. 6 września wieczorem eszelon z saperami silnikowymi dotarł do dworca Warszawa-Gdańska. 7 września rano stację Warszawa-Targówek, a następnie na wysokości stacji Warszawa-Wschodnia Rozrządowa transport z plutonami 11 i 12 został silnie zaatakowany przez lotnictwo niemieckie, w wyniku czego bomby trafiły i zniszczyły trzy wagony z żołnierzami, zginęło co najmniej 39 żołnierzy, 20 zaginęło i do 60 zostało rannych. Wieczorem zakończono porządkować transport, dokonano reorganizacji z powodu strat, utworzono jeden pluton pod dowództwem kpt. E. Rudomina-Dusiatskiego. Transport skierowano w kierunku Brześcia nad Bugiem, 8 września w momencie dojazdu do stacji Dębe Wielkie transport ponownie zaatakowało niemieckie lotnictwo zginęło 2 saperów, a kilku zostało rannych, uszkodzono jedną z lokomotyw. Nocą 8/9 września osiągnięto Mińsk Mazowiecki. 9 i 10 września jazdę kontynuowano tylko nocą, w dzień chroniąc się pobliskich lasach, naprawiano linię kolejową wspierając jadącą z przodu 25 kompanię mostów kolejowych. Nocą 11/12 września z uwagi na zatłoczenie torów pluton zbiorczy w transporcie utknął w rejonie miejscowości Broszków, następnie pomaszerował marszem pieszym w kierunku Siedlec, po drodze pluton podzielił się na grupy pod dowództwem oficerów i podoficerów. Część plutonu zbiorczego (11 i 12 pluton) zdezerterowała lub dostała się do niewoli niemieckiej. Część pomaszerowała w kierunku wschodnim i dostała się do niewoli sowieckiej. 13 września transport kolejowy ze sprzętem i niewielką grupą saperów został opanowany przez wojska niemieckie.

Pozostałe zmobilizowane plutony i pociągi elektrogeneratorowe

Mobilizowane od 31 sierpnia 1939 roku plutony eksploatacyjne silnikowe wąskotorowe nr 13, 14, 15, 16, 17 i 18 oraz co najmniej dwa pociągi elektrowagonowe normalnotorowe zostały zmobilizowane w ramach I i II rzutu mobilizacji powszechnej. Po zmobilizowaniu zostały sukcesywnie kierowane do rejonu Szczypiorna koło Modlina. Od 3 września zmobilizowane już plutony na rozkaz kwatermistrza DOK nr I rozbudowały i uruchomiły linię kolejki wąskotorowej ze składnicy amunicji w Palmirach do Modlina, celem dowozu amunicji. Do 5 września pododdziały silnikowe saperów dotarły do Palmir, tam prawdopodobnie rozkazem dowódcy batalionu pozostawiły sprzęt silnikowy, gdyż do transportu pododdziałów silnikowych do dyspozycji Szefa Komunikacji Wojskowej NW zabrakło taboru kolejowego. Z uwagi na nikłą ilość materiału dokumentacyjnego należy domniemać, że ze sprzętem pozostały w Palmirach plutony eksploatacyjne silnikowe wąskotorowe nr 13-18. Przed połową września plutony z Palmir przybyły do Warszawy. Rozkazem dowódcy saperów obrony Warszawy płk. Langnera włączone zostały do Zgrupowania Saperów Armii "Warszawa". Plutony nr 13 i 14 weszły w skład odtwarzanej 111 rezerwowej kompanii saperów, plutony 15 i 16 uzupełniły 113 rezerwową kompanię saperów, a plutony 17 i 18 weszły w skład 138 rezerwowej kompanii saperów. W składzie w/w kompanii plutony uczestniczyły w pracach i działaniach bojowych aż do kapitulacji stolicy. Dwa pociągi elektrowagonowe normalnotorowe nr 12 i 19 wykonywały zadania na rzecz Armii "Modlin", a następnie dla załogi twierdzy w Modlinie.

Pozostałe pododdziały batalionu silnikowego i OZN

Pozostałe pododdziały batalionu silnikowego: tj. zapasowy pluton silnikowy, załogi 2 pociągów elektrogeneratorowych normalnotorowych oraz Oddział Zbierania Nadwyżek weszły w skład Ośrodka Zapasowego Saperów typ specjalnych nr 1. 5 września 1939 roku między innymi z saperów silnikowych został sformowany batalion saperów w sile 700 żołnierzy, słabo uzbrojonych w pistolety i niewielką liczbę kbk oraz bagnety i sztylety. Ppłk Olczak objął stanowisko zastępcy dowódcy OZSMK nr 2 i wraz z jego dowództwem ewakuował się na wschód, 24 września w rejonie Bełżca ppłk Olczak dostał się do niewoli sowieckiej. Sformowany batalion saperów pomaszerował w kierunku wschodnim poprzez Legionowo, Jabłonnę, Strugę, Rembertów, Sulejówek, Mińsk Maz. Kałuszyn, Siedlce, Międzyrzec Podlaski do Brześcia n/Bugiem. W trakcie marszu pieszego batalion był kilkakrotnie atakowany przez lotnictwo niemieckie ponosząc straty osobowe. Następnie batalion saperski pomaszerował przez Kowel do Sarn. W rejonie miejscowości Antonówka koło Sarn batalion stacjonował w dniu 17 września 1939 roku. Na wieść o agresji sowieckiej dowództwo batalionu dało wolną rękę szeregowym co do dalszego działania, a kadra oficerska udała się na południe zarekwirowanymi samochodami. Dalsze losy żołnierzy batalionu nie są znane. Część na pewno trafiła w ręce Armii Czerwonej i oficerowie zostali zamordowani w zbrodni katyńskiej. Grupa saperów silnikowych licząca ok. 100 żołnierzy pod dowództwem ppor. rez. inż. Tadeusza Zdziarskiego z niewielką ilością amunicji i kilkunastoma kbk i pistoletami szybkim marszem pomaszerował w kierunku Bugu na zachód. Toczyła potyczki z dywersantami ukraińskimi. We wsi Mokrzec po 20 września grupa stoczyła walkę z dużą grupą dywersyjną, poległ ppor. rez. Zdziarski, a żołnierze po wyczerpaniu amunicji dostali się do niewoli, większość została przekazana nadchodzącym wojskom sowieckim, nieliczni zbiegli za Bug.

Od 24 lutego 2004 tradycje batalion silnikowego kontynuuje 5 Ośrodek Przechowywania Sprzętu im. ppłk. Adama Szugajewa w Nowym Dworze Mazowieckim.

Żołnierze batalionu silnikowego
Dowódcy batalionu:
 płk Mikołaj Jasiński (od 10 II 1930)
 ppłk Stanisław Olczak (10 IX 1938 - IX 1939, † 1940 Katyń)
Oficerowie:
 kpt. Aleksander Gawina († 1940 Charków)
 kpt. Stanisław Śliwowski († 1940 Charków)
 por. rez. Zbigniew Wasiutyński
 ppor. Ludwik Kapuściński († 1940 Charków)
 ppor. rez. Flawiusz Jan Stempliński († 1940 Charków)
 ppor. Marian Adolf Wenge († 1940 Katyń)

Organizacja i obsada personalna w 1939
Ostatnia organizacja pokojowa i obsada personalna batalionu:

Dowództwo batalionu

 dowódca batalionu – ppłk. Olczak Stanisław
 I zastępca dowódcy batalionu – mjr. inż. Kapitaniak Bolesław
 adiutant – por. Tąkiel Tadeusz
 oficer sztabowy ds. wyszkolenia – vacat
 oficer poligonowy – por. rez. pdsc. Grabowski Zygmunt
 lekarz medycyny – por. lek. Bujalski Edward
 II zastępca dowódcy (kwatermistrz) – kpt. Urbańczy August Bronisław
 oficer mobilizacyjny – por. Jasiński Seweryn Roman
 z-ca oficera mobilizacyjnego – por. Witak Czesław
 oficer administracyjno-materiałowy – por. Kosieradzki Marian Bolesław Józafat
 oficer gospodarczy – por. int. Kotulski Marian Mikołaj
 dowódca kompanii gospodarczej – por. Sosnowski Henryk Alojzy
 oficer żywnościowy – chor. Panek Stanisław
 komendant parku – kpt. Gołaj Franciszek
 zastępca komendanta – vacat

kompania szkolna
 dowódca kompanii szkolnej – kpt. Wahren Edmund
 instruktor – ppor. Jurewicz Eugeniusz
 instruktor – ppor. Kantor Jerzy

1 kompania silnikowa
 dowódca 1 kompanii silnikowej – por. Komorowski Wacław
 instruktor – ppor. Wenge Marian
 instruktor – ppor. rez. pdsc. Maskiewicz Stefan

2 kompania silnikowa
 dowódca 2 kompanii silnikowej – por. Rudomin Edward

Oddelegowani na kurs
 por. Szymański Henryk Zygmunt
 kpt. Śliwowski Stanislaw
 por. Osmański Stanisław
 por. Walenta Stanislaw Alojzy

Odznaka pamiątkowa

7 grudnia 1931 Minister Spraw Wojskowych zatwierdził wzór i regulamin odznaki pamiątkowej Batalionu Silnikowego. Odznaka o wymiarach 35 x 45 mm ma kształt srebrnego wieńca, na którym umieszczono: u dołu - skrzydełko kolejowe, u góry - trzy cylindry silnika, które razem podtrzymują centralnie osadzony medalion w kolorach saperów, tj. czarno-czerwonych. Na czerwonym tle widnieje orzeł rządowy, na czarnej obwódce widnieje napis "BATALION SILNIKOWY". Po raz pierwszy odznaki wręczono z okazji święta batalionu 9 lutego 1932.

Uwagi

Przypisy

Bibliografia

 Spis byłych oddziałów wojskowych WP, Przegląd Historyczno-Wojskowy, Warszawa 2000, Nr 2 (183), s. 105-108.
 Janusz Turlejski, Wojciech Markert "Odznaki wojsk technicznych"

Bataliony saperów II Rzeczypospolitej
Wojsko Polskie w Nowym Dworze Mazowieckim

redpajama_set_name: RedPajamaWikipedia


my mother used to make pancakes on Sundays.
I liked the pancake days.
I liked to see the pancake flipping in the frying pan.
A gentle Sunday morning .
So much time has gone by.
My today's brunch was pancakes. Made it myself longing for those days.


text:
<?php

namespace Shrikeh\PagerDuty\Entity\ContactMethod\Resource;

use Shrikeh\PagerDuty\Entity\ContactMethod\Resource;
use Shrikeh\PagerDuty\Entity\ContactMethod\Resource\Blacklisted;
use Shrikeh\PagerDuty\Entity\ContactMethod\Resource\Blacklistable;
use Shrikeh\PagerDuty\Entity\ContactMethod\Resource\Type;

final class Sms implements Resource, Blacklistable
{
    use Type;
    use Blacklisted;

    private $countryCode;

    private $number;

    public function __construct(
        $number,
        $countryCode,
        $enabled,
        $blacklisted = false
    ) {
        $this->number = $number;
        $this->countryCode = $countryCode;
        $this->enabled = $enabled;
        $this->blacklisted = $blacklisted;
    }

    public function __toString()
    {
        return $this->render();
    }

    public function countryCode()
    {
        return $this->countryCode;
    }

    public function number()
    {
        return $this->number;
    }

    public function enabled()
    {
        return $this->enabled;
    }

    public function render($prependCountryCode = true)
    {
        if ($prependCountryCode) {
            return sprintf('+%d%d', $this->countryCode, $this->number);
        }
        return $this->number;
    }
}


Like a meadow, you can mix and layer greens together.
Especially the pale sage greens – they can go with everything. Nature's neutral, the greens in Vicente Wolf's Color Diaries relax and calm even when full of color.
When you travel through Africa, there are so many different cultures that have really developed their own individuality.
Agriculture, along with gold and livestock, accounts for 80% of exports from Mali. The bright, chartreuse greens unique to this region can suit modern and traditional settings. Too bright? It says happiness all over it!
Bring nature and softness into a room with blue green shades.
Warm up a space in a modern way with beige grays.
The hardest color to get right since it can change with light.
Relaxing as a pastel, blues get warmer as they get deeper.


In the last couple of days we have encountered two species of salamander, a group of amphibians that we do not have in Australia.
These remarkable animals have soft permeable skin like that of frogs, but at a glance can seem lizard-like. We found a Bark-coloured Salamander (Bolitoglossa lignicolor) on a broad green leaf during one of our evening bug expeditions. It is bizarre to watch; the feet are broad and almost lack distinguishable toes, and it walks in slow motion in a very precise manner. These unusual feet securely anchor it to the moist surfaces on which it travels, and it uses its muscular body and tail to assist it lean out slowly and grasp nearby leaves. Once in the leaf litter, this species all but disappears. Just 30 seconds after I released it I thought it had gone, but in fact it had moved only several centimetres and still right in front of me.
The bumps below the nostrils are nasolabial tubes. These are grooves which connect the nostrils to the upper lip and play an important role in the reception of chemical traces.
The Worm Salamander (Oedipina uniformis) is a small slender species, which has incredibly small limbs. It still seems to utilise these, but also moves in a worm-like manner quite well too. When I first found this one under a rock, it was thrashing and wriggling very fast, and I had to grab it to be sure of its identity. I could have easily dismissed it as a worm.
Costa Rica Day 7 – 8 Eyelash Vipers!
Costa Rica - Day 4-5 Terciopelo!


Sounds European!: Spain | María Parrado feat. Cepeda - "No creo en nada"
Spain | María Parrado feat. Cepeda - "No creo en nada"
Spanish singers María Parrado and Luis Cepeda have joined together in a beautiful single. "No creo en nada" is a very interesting pop ballad in which her sweet and his raspy voices combine perfectly. We're feeling the love, y'all!