text:
#include <OgreOctreeZoneOctree.h>
#include <OgrePCZSceneNode.h>
#include "OgreOctreeZone.h"

namespace Ogre
{

    /* INTERSECTION UTILITY FUNCTIONS ***/

    enum Intersection
    {
        OUTSIDE=0,
        INSIDE=1,
        INTERSECT=2
    };

    Intersection intersect( const Ray &one, const AxisAlignedBox &two )
    {
        // Null box?
        if (two.isNull()) return OUTSIDE;
	    // Infinite box?
	    if (two.isInfinite()) return INTERSECT;

        bool inside = true;
        const Vector3& twoMin = two.getMinimum();
        const Vector3& twoMax = two.getMaximum();
        Vector3 origin = one.getOrigin();
        Vector3 dir = one.getDirection();

        Vector3 maxT(-1, -1, -1);

        int i = 0;
        for(i=0; i<3; i++ )
        {
            if( origin[i] < twoMin[i] )
            {
                inside = false;
                if( dir[i] > 0 )
                {
                    maxT[i] = (twoMin[i] - origin[i])/ dir[i];
                }
            }
            else if( origin[i] > twoMax[i] )
            {
                inside = false;
                if( dir[i] < 0 )
                {
                    maxT[i] = (twoMax[i] - origin[i]) / dir[i];
                }
            }
        }

        if( inside )
        {
            return INTERSECT;
        }
        int whichPlane = 0;
        if( maxT[1] > maxT[whichPlane])
            whichPlane = 1;
        if( maxT[2] > maxT[whichPlane])
            whichPlane = 2;

        if( ((int)maxT[whichPlane]) & 0x80000000 )
        {
            return OUTSIDE;
        }
        for(i=0; i<3; i++ )
        {
            if( i!= whichPlane )
            {
                float f = origin[i] + maxT[whichPlane] * dir[i];
                if ( f < (twoMin[i] - 0.00001f) ||
                        f > (twoMax[i] +0.00001f ) )
                {
                    return OUTSIDE;
                }
            }
        }

        return INTERSECT;

    }

    /** Checks how the axis aligned box intersects with the plane bounded volume
    */
    Intersection intersect( const PlaneBoundedVolume &one, const AxisAlignedBox &two )
    {
        // Null box?
        if (two.isNull()) return OUTSIDE;
	    // Infinite box?
	    if (two.isInfinite()) return INTERSECT;

        // Get centre of the box
        Vector3 centre = two.getCenter();
        // Get the half-size of the box
        Vector3 halfSize = two.getHalfSize();

        // For each plane, see if all points are on the negative side
        // If so, object is not visible.
        // If one or more are, it's partial.
        // If all aren't, full
        bool all_inside = true;
        PlaneList::const_iterator i, iend;
        iend = one.planes.end();
        for (i = one.planes.begin(); i != iend; ++i)
        {
            const Plane& plane = *i;

            Plane::Side side = plane.getSide(centre, halfSize);
            if(side == one.outside)
                    return OUTSIDE;
            if(side == Plane::BOTH_SIDE)
                    all_inside = false;
        }

        if ( all_inside )
            return INSIDE;
        else
            return INTERSECT;

    }

    /** Checks how the second box intersects with the first.
    */
    Intersection intersect( const AxisAlignedBox &one, const AxisAlignedBox &two )
    {
        // Null box?
        if (one.isNull() || two.isNull()) return OUTSIDE;
	    if (one.isInfinite()) return INSIDE;
	    if (two.isInfinite()) return INTERSECT;

        const Vector3& insideMin = two.getMinimum();
        const Vector3& insideMax = two.getMaximum();

        const Vector3& outsideMin = one.getMinimum();
        const Vector3& outsideMax = one.getMaximum();

        if (    insideMax.x < outsideMin.x ||
                insideMax.y < outsideMin.y ||
                insideMax.z < outsideMin.z ||
                insideMin.x > outsideMax.x ||
                insideMin.y > outsideMax.y ||
                insideMin.z > outsideMax.z )
        {
            return OUTSIDE;
        }

        bool full = ( insideMin.x > outsideMin.x &&
                    insideMin.y > outsideMin.y &&
                    insideMin.z > outsideMin.z &&
                    insideMax.x < outsideMax.x &&
                    insideMax.y < outsideMax.y &&
                    insideMax.z < outsideMax.z );

        if ( full )
            return INSIDE;
        else
            return INTERSECT;

    }

    /** Checks how the box intersects with the sphere.
    */
    Intersection intersect( const Sphere &one, const AxisAlignedBox &two )
    {
        // Null box?
        if (two.isNull()) return OUTSIDE;
	    if (two.isInfinite()) return INTERSECT;

        float sradius = one.getRadius();

        sradius *= sradius;

        Vector3 scenter = one.getCenter();

        const Vector3& twoMin = two.getMinimum();
        const Vector3& twoMax = two.getMaximum();

        float s, d = 0;

        Vector3 mndistance = ( twoMin - scenter );
        Vector3 mxdistance = ( twoMax - scenter );

        if ( mndistance.squaredLength() < sradius &&
                mxdistance.squaredLength() < sradius )
        {
            return INSIDE;
        }

        //find the square of the distance
        //from the sphere to the box
        for ( int i = 0 ; i < 3 ; i++ )
        {
            if ( scenter[ i ] < twoMin[ i ] )
            {
                s = scenter[ i ] - twoMin[ i ];
                d += s * s;
            }

            else if ( scenter[ i ] > twoMax[ i ] )
            {
                s = scenter[ i ] - twoMax[ i ];
                d += s * s;
            }

        }

        bool partial = ( d <= sradius );

        if ( !partial )
        {
            return OUTSIDE;
        }

        else
        {
            return INTERSECT;
        }

    }
    /***************************************************/

    /** Returns true is the box will fit in a child.
    */
    bool Octree::_isTwiceSize( const AxisAlignedBox &box ) const
    {
	    // infinite boxes never fit in a child - always root node
	    if (box.isInfinite())
		    return false;

        Vector3 halfMBoxSize = mBox.getHalfSize();
        Vector3 boxSize = box.getSize();
        return ((boxSize.x <= halfMBoxSize.x) && (boxSize.y <= halfMBoxSize.y) && (boxSize.z <= halfMBoxSize.z));

    }

    /** It's assumed the the given box has already been proven to fit into
    * a child.  Since it's a loose octree, only the centers need to be
    * compared to find the appropriate node.
    */
    void Octree::_getChildIndexes( const AxisAlignedBox &box, int *x, int *y, int *z ) const
    {
        Vector3 center = mBox.getMaximum().midPoint( mBox.getMinimum() );

        Vector3 ncenter = box.getMaximum().midPoint( box.getMinimum() );

        if ( ncenter.x > center.x )
            * x = 1;
        else
            *x = 0;

        if ( ncenter.y > center.y )
            * y = 1;
        else
            *y = 0;

        if ( ncenter.z > center.z )
            * z = 1;
        else
            *z = 0;

    }

    Octree::Octree(PCZone * oz, Octree * parent )
        : mWireBoundingBox(0),
        mHalfSize( 0, 0, 0 )
    {
        //initialize all children to null.
        for ( int i = 0; i < 2; i++ )
        {
            for ( int j = 0; j < 2; j++ )
            {
                for ( int k = 0; k < 2; k++ )
                {
                    mChildren[ i ][ j ][ k ] = 0;
                }
            }
        }
	    mZone = oz;
        mParent = parent;
        mNumNodes = 0;
    }

    Octree::~Octree()
    {
        //initialize all children to null.
        for ( int i = 0; i < 2; i++ )
        {
            for ( int j = 0; j < 2; j++ )
            {
                for ( int k = 0; k < 2; k++ )
                {
                    if ( mChildren[ i ][ j ][ k ] != 0 )
                        OGRE_DELETE mChildren[ i ][ j ][ k ];
                }
            }
        }

        if(mWireBoundingBox)
            OGRE_DELETE mWireBoundingBox;

        mParent = 0;
    }

    void Octree::_addNode( PCZSceneNode * n )
    {
        mNodes.insert(n);
        ((OctreeZoneData*)n ->getZoneData(mZone))->setOctant( this );

        //update total counts.
        _ref();

    }

    void Octree::_removeNode( PCZSceneNode * n )
    {
        mNodes.erase(n);
		((OctreeZoneData*)n ->getZoneData(mZone))->setOctant( 0 );

        //update total counts.
        _unref();
    }

    void Octree::_getCullBounds( AxisAlignedBox *b ) const
    {
        b -> setExtents( mBox.getMinimum() - mHalfSize, mBox.getMaximum() + mHalfSize );
    }

    WireBoundingBox* Octree::getWireBoundingBox()
    {
        // Create a WireBoundingBox if needed
        if(mWireBoundingBox == 0)
            mWireBoundingBox = OGRE_NEW WireBoundingBox();

        mWireBoundingBox->setupBoundingBox(mBox);
        return mWireBoundingBox;
    }

    void Octree::_findNodes(const AxisAlignedBox &t,
                            PCZSceneNodeList &list,
                            PCZSceneNode *exclude,
							bool includeVisitors,
                            bool full )
    {
	    if ( !full )
	    {
		    AxisAlignedBox obox;
		    _getCullBounds( &obox );

		    Intersection isect = intersect( t, obox );

		    if ( isect == OUTSIDE )
			    return ;

		    full = ( isect == INSIDE );
	    }

	    PCZSceneNodeList::iterator it = mNodes.begin();

	    while ( it != mNodes.end() )
	    {
		    PCZSceneNode * on = ( *it );

		    if ( on != exclude && (on->getHomeZone() == mZone || includeVisitors ))
		    {
			    if ( full )
			    {
					// make sure the node isn't already on the list
					list.insert( on );
			    }

			    else
			    {
				    Intersection nsect = intersect( t, on -> _getWorldAABB() );

				    if ( nsect != OUTSIDE )
				    {
						// make sure the node isn't already on the list
						list.insert( on );
				    }
			    }

		    }
		    ++it;
	    }

	    Octree* child;

	    if ( (child=mChildren[ 0 ][ 0 ][ 0 ]) != 0 )
		    child->_findNodes( t, list, exclude, includeVisitors, full );

	    if ( (child=mChildren[ 1 ][ 0 ][ 0 ]) != 0 )
		    child->_findNodes( t, list, exclude, includeVisitors, full );

	    if ( (child=mChildren[ 0 ][ 1 ][ 0 ]) != 0 )
		    child->_findNodes( t, list, exclude, includeVisitors, full );

	    if ( (child=mChildren[ 1 ][ 1 ][ 0 ]) != 0 )
		    child->_findNodes( t, list, exclude, includeVisitors, full );

	    if ( (child=mChildren[ 0 ][ 0 ][ 1 ]) != 0 )
		    child->_findNodes( t, list, exclude, includeVisitors, full );

	    if ( (child=mChildren[ 1 ][ 0 ][ 1 ]) != 0 )
		    child->_findNodes( t, list, exclude, includeVisitors, full );

	    if ( (child=mChildren[ 0 ][ 1 ][ 1 ]) != 0 )
		    child->_findNodes( t, list, exclude, includeVisitors, full );

	    if ( (child=mChildren[ 1 ][ 1 ][ 1 ]) != 0 )
		    child->_findNodes( t, list, exclude, includeVisitors, full );

    }

    void Octree::_findNodes(const Ray &t,
                            PCZSceneNodeList &list,
                            PCZSceneNode *exclude,
							bool includeVisitors,
                            bool full )
    {
	    if ( !full )
	    {
		    AxisAlignedBox obox;
		    _getCullBounds( &obox );

		    Intersection isect = intersect( t, obox );

		    if ( isect == OUTSIDE )
			    return ;

		    full = ( isect == INSIDE );
	    }

	    PCZSceneNodeList::iterator it = mNodes.begin();

	    while ( it != mNodes.end() )
	    {
		    PCZSceneNode * on = ( *it );

		    if ( on != exclude && (on->getHomeZone() == mZone || includeVisitors ))
		    {
			    if ( full )
			    {
					// make sure the node isn't already on the list
					list.insert( on );
			    }

			    else
			    {
				    Intersection nsect = intersect( t, on -> _getWorldAABB() );

				    if ( nsect != OUTSIDE )
				    {
						// make sure the node isn't already on the list
						list.insert( on );
				    }
			    }

		    }
		    ++it;
	    }

	    Octree* child;

	    if ( (child=mChildren[ 0 ][ 0 ][ 0 ]) != 0 )
		    child->_findNodes( t, list, exclude, includeVisitors, full );

	    if ( (child=mChildren[ 1 ][ 0 ][ 0 ]) != 0 )
		    child->_findNodes( t, list, exclude, includeVisitors, full );

	    if ( (child=mChildren[ 0 ][ 1 ][ 0 ]) != 0 )
		    child->_findNodes( t, list, exclude, includeVisitors, full );

	    if ( (child=mChildren[ 1 ][ 1 ][ 0 ]) != 0 )
		    child->_findNodes( t, list, exclude, includeVisitors, full );

	    if ( (child=mChildren[ 0 ][ 0 ][ 1 ]) != 0 )
		    child->_findNodes( t, list, exclude, includeVisitors, full );

	    if ( (child=mChildren[ 1 ][ 0 ][ 1 ]) != 0 )
		    child->_findNodes( t, list, exclude, includeVisitors, full );

	    if ( (child=mChildren[ 0 ][ 1 ][ 1 ]) != 0 )
		    child->_findNodes( t, list, exclude, includeVisitors, full );

	    if ( (child=mChildren[ 1 ][ 1 ][ 1 ]) != 0 )
		    child->_findNodes( t, list, exclude, includeVisitors, full );

    }

    void Octree::_findNodes(const Sphere &t,
                            PCZSceneNodeList &list,
                            PCZSceneNode *exclude,
							bool includeVisitors,
                            bool full )
    {
	    if ( !full )
	    {
		    AxisAlignedBox obox;
		    _getCullBounds( &obox );

		    Intersection isect = intersect( t, obox );

		    if ( isect == OUTSIDE )
			    return ;

		    full = ( isect == INSIDE );
	    }

	    PCZSceneNodeList::iterator it = mNodes.begin();

	    while ( it != mNodes.end() )
	    {
		    PCZSceneNode * on = ( *it );

		    if ( on != exclude && (on->getHomeZone() == mZone || includeVisitors ))
		    {
			    if ( full )
			    {
					// make sure the node isn't already on the list
					list.insert( on );
			    }

			    else
			    {
				    Intersection nsect = intersect( t, on -> _getWorldAABB() );

				    if ( nsect != OUTSIDE )
				    {
						// make sure the node isn't already on the list
						list.insert( on );
				    }
			    }

		    }
		    ++it;
	    }

	    Octree* child;

	    if ( (child=mChildren[ 0 ][ 0 ][ 0 ]) != 0 )
		    child->_findNodes( t, list, exclude, includeVisitors, full );

	    if ( (child=mChildren[ 1 ][ 0 ][ 0 ]) != 0 )
		    child->_findNodes( t, list, exclude, includeVisitors, full );

	    if ( (child=mChildren[ 0 ][ 1 ][ 0 ]) != 0 )
		    child->_findNodes( t, list, exclude, includeVisitors, full );

	    if ( (child=mChildren[ 1 ][ 1 ][ 0 ]) != 0 )
		    child->_findNodes( t, list, exclude, includeVisitors, full );

	    if ( (child=mChildren[ 0 ][ 0 ][ 1 ]) != 0 )
		    child->_findNodes( t, list, exclude, includeVisitors, full );

	    if ( (child=mChildren[ 1 ][ 0 ][ 1 ]) != 0 )
		    child->_findNodes( t, list, exclude, includeVisitors, full );

	    if ( (child=mChildren[ 0 ][ 1 ][ 1 ]) != 0 )
		    child->_findNodes( t, list, exclude, includeVisitors, full );

	    if ( (child=mChildren[ 1 ][ 1 ][ 1 ]) != 0 )
		    child->_findNodes( t, list, exclude, includeVisitors, full );

    }

    void Octree::_findNodes(const PlaneBoundedVolume &t,
                            PCZSceneNodeList &list,
                            PCZSceneNode *exclude,
							bool includeVisitors,
                            bool full )
    {
	    if ( !full )
	    {
		    AxisAlignedBox obox;
		    _getCullBounds( &obox );

		    Intersection isect = intersect( t, obox );

		    if ( isect == OUTSIDE )
			    return ;

		    full = ( isect == INSIDE );
	    }

	    PCZSceneNodeList::iterator it = mNodes.begin();

	    while ( it != mNodes.end() )
	    {
		    PCZSceneNode * on = ( *it );

		    if ( on != exclude && (on->getHomeZone() == mZone || includeVisitors ))
		    {
			    if ( full )
			    {
					// make sure the node isn't already on the list
					list.insert( on );
			    }

			    else
			    {
				    Intersection nsect = intersect( t, on -> _getWorldAABB() );

				    if ( nsect != OUTSIDE )
				    {
						// make sure the node isn't already on the list
						list.insert( on );
				    }
			    }

		    }
		    ++it;
	    }

	    Octree* child;

	    if ( (child=mChildren[ 0 ][ 0 ][ 0 ]) != 0 )
		    child->_findNodes( t, list, exclude, includeVisitors, full );

	    if ( (child=mChildren[ 1 ][ 0 ][ 0 ]) != 0 )
		    child->_findNodes( t, list, exclude, includeVisitors, full );

	    if ( (child=mChildren[ 0 ][ 1 ][ 0 ]) != 0 )
		    child->_findNodes( t, list, exclude, includeVisitors, full );

	    if ( (child=mChildren[ 1 ][ 1 ][ 0 ]) != 0 )
		    child->_findNodes( t, list, exclude, includeVisitors, full );

	    if ( (child=mChildren[ 0 ][ 0 ][ 1 ]) != 0 )
		    child->_findNodes( t, list, exclude, includeVisitors, full );

	    if ( (child=mChildren[ 1 ][ 0 ][ 1 ]) != 0 )
		    child->_findNodes( t, list, exclude, includeVisitors, full );

	    if ( (child=mChildren[ 0 ][ 1 ][ 1 ]) != 0 )
		    child->_findNodes( t, list, exclude, includeVisitors, full );

	    if ( (child=mChildren[ 1 ][ 1 ][ 1 ]) != 0 )
		    child->_findNodes( t, list, exclude, includeVisitors, full );

    }

}


text:
from __future__ import absolute_import

from django.utils.translation import ugettext_lazy as _
from rest_framework import status
from rest_framework.response import Response

from sentry import features
from sentry.api.bases.organization import OrganizationEndpoint, OrganizationAuthProviderPermission
from sentry.api.serializers import serialize
from sentry.models import AuthProvider

ERR_NO_SSO = _('The SSO feature is not enabled for this organization.')

class OrganizationAuthProviderDetailsEndpoint(OrganizationEndpoint):
    permission_classes = (OrganizationAuthProviderPermission, )

    def get(self, request, organization):
        """
        Retrieve details about Organization's SSO settings and
        currently installed auth_provider
        ``````````````````````````````````````````````````````

        :pparam string organization_slug: the organization short name
        :auth: required
        """
        if not features.has('organizations:sso', organization, actor=request.user):
            return Response(ERR_NO_SSO, status=status.HTTP_403_FORBIDDEN)

        try:
            auth_provider = AuthProvider.objects.get(
                organization=organization,
            )
        except AuthProvider.DoesNotExist:
            # This is a valid state where org does not have an auth provider
            # configured, make sure we respond with a 20x
            return Response(status=status.HTTP_204_NO_CONTENT)

        # cache organization so that we don't need to query for org when serializing
        auth_provider._organization_cache = organization

        return Response(serialize(auth_provider, request.user))

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html>

	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<title>Assignment Solution for Module 2</title>
	<link rel="stylesheet" type="text/css" href="css/custom.css">

Our Menu

Chicken

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
			tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
			quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
			consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
			cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
			proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

Beef

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
			tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
			quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
			consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
			cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
			proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

Sushi

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
			tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
			quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
			consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
			cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
			proident, sunt in culpa qui officia deserunt mollit anim id est laborum.


text:
import sys
import MySQLdb
import MySQLdb.cursors
import nflgame
import nflgame.update_players
import nflgame.update_sched
import argparse
import collections
import stat_functions as f
import math
import time
import datetime
import urllib2
import xml.dom.minidom as xml
import subprocess
import pytz
from tzlocal import get_localzone
import urllib2
import urllib
import os
import json
import hashlib
import pprint

try:
	import player_photo
	custom_player_photo = True
except:
	custom_player_photo = False

import config as c

db = MySQLdb.connect(host=c.DBHOST, user=c.DBUSER, passwd=c.DBPASS, db=c.DBNAME, cursorclass=MySQLdb.cursors.DictCursor)
cur = db.cursor()
cur.execute("SET sql_mode=(SELECT REPLACE(@@sql_mode, 'ONLY_FULL_GROUP_BY', ''));")

query = 'select current_timestamp'
cur.execute(query)
sql_now = cur.fetchone()['current_timestamp']

def main():

  cur_year, cur_week = nflgame.live.current_year_and_week()
  cur_weektype = nflgame.live._cur_season_phase

  now = datetime.datetime.now()

  if args.year == "0": year = str(cur_year)
  else: year = args.year
  if args.week == "0": week = str(cur_week)
  else: week = args.week
  if args.weektype == "none": weektype = str(cur_weektype)
  else: weektype = args.weektype.upper()

  if weektype not in ("REG","PRE","POST"):
    print
    sys.exit("Invalid weektype: "+weektype)

  if args.hello:
    print
    print "Year: "+str(year)+", Week: "+str(week)+", Weektype: "+str(weektype)
    print
    sys.exit()

  if(args.schedule): # Update schedule
    update_schedule(year, week, weektype)

  #if(args.g): # Update games
#    update_games(year, week, weektype, args.all)

  if(args.players): # Update players
    update_players(year, week, weektype)

  if(args.stats_summary): # calculate statistic_week
    update_statistic_summaries(year, week, weektype)

  if(args.standings):
    update_standings(year, week, weektype)

  if(args.team_photos):
    update_team_photos()

  if(args.player_news):
    update_player_news(year, week, weektype)

  if(args.player_draft_ranks):
    update_player_draft_ranks()

  if(args.player_injuries):
    update_player_injuries()

  if(args.backfill_esbids):
    backfill_esbids(year)

  if(args.clear_player_generic_photo is not None):
      clear_player_photos(args.clear_player_generic_photo)

def update_standings(year, week ,weektype):

    if week == 'all':
        weeks = ['1','2','3','4','5','6','7','8','9','10','11','12','13','14','15','16','17']
        weeks = range(1,18)
    else:
        weeks = [week]

    if args.week == "0":
        weeks = range(1,int(week)+1)

    # Get all leagues of current weektype
    query = ('select league.id from league join league_settings on league.id = league_settings.league_id where nfl_season = "%s"' % weektype)
    cur.execute(query)
    leagues = cur.fetchall()

    for l in leagues:
        leagueid = l['id']

        for week in weeks:

            # Check if this weeks NFL games are all marked complete?
            # Either by the nfl_schedule quarter having F in it, or by 3 hours past the start times of all games

            # Get score totals for this week
            query = (('SELECT sum(fs.points) as points, team_id FROM fantasy_statistic as fs join starter as s on '+
                    's.player_id = fs.player_id and s.year = fs.year and s.week = fs.week where fs.league_id = %s and '+
                    'fs.nfl_week_type_id = (select id from nfl_week_type where text_id = "%s") and fs.year = %s and fs.week = %s '+
                    'and s.league_id = %s group by team_id, fs.year, fs.week') % (str(leagueid), weektype, str(year), str(week), str(leagueid)))

            scores = dict()
            cur.execute(query)
            rows = cur.fetchall()

            # If there are no stats for this week, skip it, it's probably not happend yet.
            if len(rows) == 0:
                continue

            print "Updating week "+str(week)+" for leagueid "+str(leagueid)

            for row in rows:
                scores[row['team_id']] = row['points']

            # Get all match ups for this week
            query = (('select id, home_team_id, away_team_id from schedule where league_id = %s and '+
                    'week = %s and year = %s and nfl_week_type_id = (select id from nfl_week_type where text_id = "%s")') %
                    (str(leagueid),str(week),str(year),weektype))
            cur.execute(query)

            schedule = cur.fetchall()
            for one in schedule:

                sched_id = one['id']
                #find winner team_id and loser team_id
                winid = 0
                lossid = 0
                tie = 0
                homewin = 0
                homeloss = 0
                awaywin = 0
                awayloss = 0
                homeid = one['home_team_id']
                awayid = one['away_team_id']
                if scores.get(homeid) is None: homescore = 0
                else: homescore = int(scores[homeid])
                if scores.get(awayid) is None: awayscore = 0
                else: awayscore = int(scores[awayid])

                if homescore > awayscore:
                    winid = homeid
                    lossid = awayid
                    homewin = 1
                    awayloss = 1
                if awayscore > homescore:
                    winid = awayid
                    lossid = homeid
                    awaywin = 1
                    homeloss = 1
                if awayscore == homescore:
                    tie = 1

                # There was no opponent, don't award win/loss/tie
                if homeid == 0 or awayid == 0:
                    winid = 0
                    lossid = 0
                    homewin = 0
                    awaywin = 0
                    homeloss = 0
                    awayloss = 0
                    tie = 0

                query = 'select id from schedule_result where schedule_id = %s and team_id = %s' % (str(sched_id),str(homeid))

                cur.execute(query)
                if cur.rowcount == 1:
                    sched_result_id = cur.fetchone()['id']
                    query = (('update schedule_result set team_id=%s,opp_id=%s,team_score=%s,opp_score=%s,win=%s,loss=%s,tie=%s,year=%s,week=%s '+
                        'where id=%s') %(str(homeid),str(awayid),str(homescore),str(awayscore),str(homewin),str(homeloss),str(tie),str(year),str(week),str(sched_result_id)))
                else:
                    query = ('insert into schedule_result (schedule_id,team_id,opp_id,team_score,opp_score,win,loss,tie,year,week) values (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)' %
                        (str(sched_id),str(homeid),str(awayid),str(homescore),str(awayscore),str(homewin),str(homeloss),str(tie),str(year),str(week)))
                cur.execute(query)

                query = 'select id from schedule_result where schedule_id = %s and team_id = %s' % (str(one['id']),str(awayid))
                cur.execute(query)

                if cur.rowcount == 1:
                    sched_result_id = cur.fetchone()['id']
                    query = (('update schedule_result set team_id=%s,opp_id=%s,team_score=%s,opp_score=%s,win=%s,loss=%s,tie=%s,year=%s,week=%s '+
                        'where id=%s') %(str(awayid),str(homeid),str(awayscore),str(homescore),str(awaywin),str(awayloss),str(tie),str(year),str(week),str(sched_result_id)))
                else:
                    query = ('insert into schedule_result (schedule_id,team_id,opp_id,team_score,opp_score,win,loss,tie,year,week) values (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)' %
                        (str(sched_id),str(awayid),str(homeid),str(awayscore),str(homescore),str(awaywin),str(awayloss),str(tie),str(year),str(week)))
                cur.execute(query)

            db.commit()

            query = ('delete from schedule_result where schedule_id not in (select schedule.id from schedule)')
            cur.execute(query)
            db.commit()

def update_team_photos():
    print "(Save team photos should be saved as T_<club_id>.ext)"
    path = raw_input("Enter the path where they are located.    ./images/")
    ext = raw_input("Enter the extension of the files (.gif, .jpg, etc): ")

    query = ('SELECT player.id AS player_id, club_id, player.player_id as nflgame_id FROM nfl_position JOIN player ON nfl_position.id = player.nfl_position_id '+
             'JOIN nfl_team ON nfl_team.id = player.nfl_team_id WHERE nfl_position.type = 3 OR nfl_position.type = 4')

    cur.execute(query)
    rows = cur.fetchall()
    for row in rows:
        photo = os.path.join(path,"T_"+row['club_id']+ext)
        query = 'update player set photo = "'+photo+'" where player.id = '+str(row['player_id'])
        cur.execute(query)
        db.commit()
        print "Updated "+row['nflgame_id']+" with "+photo

def clear_player_photos(photo_filename):
    photo_path =  os.path.join(c.BASEDIR,"images/players/"+photo_filename)
    try:
        md5_to_match = hashlib.md5(open(photo_path,'rb').read()).hexdigest()
    except IOError:
        sys.exit('File not found: '+photo_path)

    count = 0
    print "Scanning photos...\n"
    for p_filename in os.listdir(os.path.join(c.BASEDIR,"images/players/")):
        p_path = os.path.join(c.BASEDIR,"images/players/"+p_filename)
        p_md5 = hashlib.md5(open(p_path,'rb').read()).hexdigest()
        if p_md5 == md5_to_match:

            query = 'update player set photo = "" where photo = "players/'+p_filename+'"'
            cur.execute(query)

            if cur.rowcount > 0:
                count += cur.rowcount
            db.commit()
            os.remove(p_path)

            print p_filename+" matched file hash and was cleared."
    print
    if count > 0:
        print "Player photos cleared: "+str(count)
        print "\nRun 'update.py -players -photos' to re-scan for new player photos"
    else:
        print "No player photos matched "
    print

def update_players(year, week, weektype):
    # Helper functions for update_players
    def get_pos_dict():
        cur.execute('select id, text_id from nfl_position')
        pos_dict = collections.defaultdict(lambda: 0, {})
        for row in cur.fetchall():
            pos_dict[row['text_id']] = row['id']

        return pos_dict

    def get_photo(player):
	photo = ""
	if custom_player_photo:
        	photo = player_photo.get(player)
        if photo == "":
            if (player.team != ""):
                photo = 'nfl/'+player.team.upper()+".png"
            else:
                photo = "nfl/NOTEAM.png"
        else:
            photo = 'players/'+photo
        return photo

    # First, update nflgame
    if not args.photos:
        if args.year == "0" and args.week == "0" and args.weektype == "none":
            subprocess.call(c.PLAYER_UPDATE_CMD.split(' '))
        else:
            subprocess.call((c.PLAYER_UPDATE_CMD+' --year '+str(year)+' --week '+str(week)+' --phase '+weektype.upper()).split(' '))

    photodir = "./"

    print "Updating local FF database...."
    players = nflgame.players
    count = 0

    pos_dict = get_pos_dict()
    team_dict = get_team_dict()

    positions = {}

    add_count = 0
    update_count = 0
    checked_count = 0
    for p in players:

        # print ".",
        count = count + 1
        try:
            birthdate = str(datetime.datetime.strptime(players[p].birthdate, '%m/%d/%Y'))
        except:
            birthdate = "0000-00-00"
        college = players[p].college
        full = players[p].full_name
        gsis_id = players[p].gsis_id
        gsis_name = players[p].gsis_name
        height = str(players[p].height)
        weight = str(players[p].weight)
        years_pro = str(players[p].years_pro)
        name = players[p].name
        number = str(players[p].number)
        player_id = players[p].player_id
        playerid = players[p].playerid
        profile_id = str(players[p].profile_id)
        profile_url = players[p].profile_url
        status = players[p].status
        uniform_number = players[p].uniform_number
        first = players[p].first_name
        last = players[p].last_name
        pos = str(pos_dict[players[p].position])
        team = str(team_dict[players[p].team])
        status = players[p].status
        active = (1 if status != "" else 0)

        cur.execute("select id, short_name, photo from player where player_id = '"+str(player_id)+"'")
        if cur.rowcount < 1: # Not found, must be a new player
            print "New player: "+p+" "+first+" "+last+" ("+pos+" - "+team+")"
            photo = get_photo(players[p])

            add_count = add_count + 1
            query = ("insert into player (player_id,nfl_position_id,nfl_team_id,first_name,last_name,birthdate,college,"+
            "short_name,height,weight,years_pro,number,profile_id,profile_url,status, active,photo, last_seen) "+
            "values('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s',now())" %
            			(player_id,
            			pos,
            			team,
            			MySQLdb.escape_string(first),
            			MySQLdb.escape_string(last),
            			MySQLdb.escape_string(birthdate),
            			MySQLdb.escape_string(college),
            			MySQLdb.escape_string(gsis_name),
            			height,
            			weight,
            			years_pro,
            			number,
            			profile_id,
            			MySQLdb.escape_string(profile_url),
            			status,
                        active,
                        photo))

        else: # Already have this player, update some stuff.

            row = cur.fetchone()
            short_name = MySQLdb.escape_string(gsis_name)
            if (short_name == ""):
                short_name = MySQLdb.escape_string(first)[0]+'.'+MySQLdb.escape_string(last)
            if row['photo'] == "":
                if (players[p].team != ""):
                    photo = 'nfl/'+players[p].team.upper()+".png"
                else:
                    photo = "nfl/NOTEAM.png"
            else:
                photo = row['photo']

            # Recheck for photo from get_photo function if this player has the default team photo.
            # and photos arg was specified
            if args.photos and ('nfl/' in photo or photo == "") and active:
                print "Checking photo for "+player_info(players[p])
                photo = get_photo(players[p])

            checked_count += 1
            query = ("update player set "+
            "nfl_team_id = " + team +
            ", years_pro = " + years_pro +
            ", number = " + number +
            ", active = "+str(active)+
            ", short_name = '"+short_name+"'"+
            ", status = '"+status+"'"+
            ", photo = '"+photo+"'"+
            " where player_id = '" + str(gsis_id)+"'")
        cur.execute(query)
        if cur.rowcount > 0:
            update_count += 1

        query = 'update player set last_seen = now() where player_id ="%s"' % (str(gsis_id))
        cur.execute(query)

	db.commit()
    print "\n================================"
    print "Added: " + str(add_count) + " new players."
    print "Checked: "+str(checked_count)+ " players for changes."
    print "Updated: " + str(update_count) + " players."
    print "================================\n"

    update_esbids(year,week)

    # Adding this temporarily to correct team positions that got marked inactive
    query = ('UPDATE player JOIN nfl_position ON nfl_position.id = player.nfl_position_id SET player.active = 1 '
            +'WHERE nfl_position.type = 3 or nfl_position.type = 4')

    cur.execute(query)

    # This one stays, sets all non-team players inactive if they have last_seen older than 30 days ago
    query = ('UPDATE player JOIN nfl_position ON nfl_position.id = player.nfl_position_id SET player.active = 0 '
            +'WHERE last_seen < DATE_SUB( NOW( ) , INTERVAL 30 DAY ) AND nfl_position.type !=3 AND nfl_position.type !=4')
    cur.execute(query)

    num_inactive = cur.rowcount
    print "Players marked inactive: "+str(num_inactive)
    db.commit()

def update_esbids(year, week):
    print 'Updating esbids from api.fantasy.nfl.com using year '+year+', week '+week

    stats_url = 'http://api.fantasy.nfl.com/v1/players/stats?statType=seasonStats&season=%s&week=%s&format=json' % (year, week)
    players = list()

    response = urllib.urlopen(stats_url)
    data = json.loads(response.read())
    esbid_count = 0
    for one in data['players']:
        gsis_id = one['gsisPlayerId']
        query = 'select id from player where player_id = "%s" and (esbid is null or esbid="" or esbid="None")' %(gsis_id)
        cur.execute(query)
        player_row = cur.fetchone()

        if player_row:
            query = 'update player set esbid = "%s" where id = %s' % (one['esbid'],str(player_row['id']))
            cur.execute(query)
            db.commit()
            esbid_count+=1
    if esbid_count > 0:
        print "Added "+str(esbid_count)+" esbids"

def backfill_esbids(year):
    for year in range(int(year)-4,int(year)+1):
        update_esbids(str(year),"1")

def update_statistic_summaries(year, week, weektype):

    if week == 'all' and weektype == "REG":
        weeks = ['1','2','3','4','5','6','7','8','9','10','11','12','13','14','15','16','17']
    elif weektype == "REG" or weektype == "PRE":
        weeks = [week]
    else:
        sys.exit('quitting')

    query = 'select id from nfl_week_type where text_id = "%s"' % (weektype)
    cur.execute(query)
    nfl_week_type_id = cur.fetchone()['id']
    query = ('select league.id from league join league_settings on league_settings.league_id = league.id where league_settings.nfl_season = "%s"' %(weektype))
    cur.execute(query)
    leaguerows = cur.fetchall()

    for league in leaguerows:
        leagueid = league['id']
        for w in weeks:
            query = ('select fs.player_id, sum(fs.points) as points, fs.week, fs.nfl_week_type_id, fs.year, fs.league_id, '+
                    'IFNULL(s.team_id,0) as team_id from fantasy_statistic as fs left join starter as s on s.league_id = fs.league_id and '+
                    's.week = fs.week and s.year = fs.year and s.nfl_week_type_id = fs.nfl_week_type_id and s.player_id = fs.player_id '+
                    'where fs.league_id = %s and fs.year = %s and fs.week=%s and fs.nfl_week_type_id = %s group by fs.player_id' %
                    (str(leagueid),str(year),str(w),str(nfl_week_type_id)))

            cur.execute(query)
            results = cur.fetchall();
            for row in results:
                query = ('select id from fantasy_statistic_week where player_id = %s and week=%s and year=%s and nfl_week_type_id=%s and league_id=%s'
                  % (row['player_id'], str(w), str(year), row['nfl_week_type_id'], row['league_id']))
                cur.execute(query)
                #print row
                if cur.rowcount == 0:
                    query = ('insert into fantasy_statistic_week (player_id,points,week,year,nfl_week_type_id,league_id,team_id)'+
                        ' VALUES(%s,%s,%s,%s,%s,%s,%s)' % (str(row['player_id']),str(row['points']),str(w),str(year),str(nfl_week_type_id),
                            str(row['league_id']),str(row['team_id'])))
                    cur.execute(query)
                else:
                    query = ('update fantasy_statistic_week set points = %s, team_id = %s where id = %s' %
                            (str(row['points']),str(row['team_id']),str(cur.fetchone()['id'])))
                    #print query
                    cur.execute(query)
            db.commit()

def update_schedule(season_year, week, weektype="REG"):

  team_dict = get_team_dict()

  if week == 'all' and weektype == "REG":
    weeks = ['1','2','3','4','5','6','7','8','9','10','11','12','13','14','15','16','17']
  elif weektype == "POST" and week == "all":
    weeks = ['1','2','3','4']
  elif weektype == "PRE" and week == "all":
    weeks = ['1','2','3','4']
  else:
	weeks = [week]

  for week in weeks:

    if (args.schedule_clear):
        query = ('delete from nfl_schedule where week = %s and year = %s and gt = "%s"' %
            (str(week),str(season_year), weektype))
        cur.execute(query)
        db.commit()

    # Should probably change this to use nflgame somehow, otherwise the timezone stuff without am/pm is tricky.
    updated = 0
    added = 0
    sched_url = 'http://www.nfl.com/ajax/scorestrip?season=%s&seasonType=%s&week=%s' % (season_year, weektype, str(int(week)))

    try:
      dom = xml.parse(urllib2.urlopen(sched_url))
    except urllib2.HTTPError:
      print >> sys.stderr, 'Could not load %s' % sched_url

    for g in dom.getElementsByTagName("g"):
      #year type week
      eid = g.getAttribute('eid')
      gsis = g.getAttribute('gsis')
      day = g.getAttribute('d')
      month = int(eid[4:6])
      day = int(eid[6:8])
      year = int(eid[0:4])
      time = g.getAttribute('t')
      quarter = g.getAttribute('q')
      k = g.getAttribute('k')
      home = g.getAttribute('h')
      home_long = g.getAttribute('hnn')
      home_score = g.getAttribute('hs')
      away = g.getAttribute('v')
      away_long = g.getAttribute('vnn')
      away_score = g.getAttribute('vs')
      p = g.getAttribute('p')
      rz = g.getAttribute('rz')
      ga = g.getAttribute('ga')
      h_id = team_dict[home]
      v_id = team_dict[away]
      (hour, minute) = time.split(":")

      # Ugh, this timezone stuff is ugly since it's in 12-hour with no AM/PM and there are games
      # in London before noon.  Just sort of guessing for now.
      hour = int(hour)
      if hour != 12 and hour != 9:
          hour = hour+12
      minute = int(minute)

      utc = pytz.timezone("UTC")
      est = pytz.timezone("US/Eastern")
      local = pytz.timezone(str(get_localzone()))

      start_time = est.localize(datetime.datetime(int(year),month,day,hour,minute,0,0))
      start_time = start_time.astimezone(local)

      #print start_time

      if home_score == '':
          home_score = -1
      if away_score == '':
          away_score = -1

      cur.execute("Select id from nfl_schedule where gsis = "+gsis)
      if cur.rowcount > 0:
        query = (('update nfl_schedule set eid=%s,d=%s,t="%s",q="%s",k="%s",h="%s",hnn="%s",v="%s",vnn="%s",hs="%s",vs="%s"'
                +',p="%s",rz="%s",ga="%s",start_time="%s",year="%s",h_id=%s,v_id=%s where id = %s') %
            (eid,day,time,quarter,k,home,home_long,away,away_long,home_score,away_score,p,rz,ga,
                str(start_time)[:-6],str(season_year),str(h_id),str(v_id),cur.fetchone()['id']))
        updated += 1
      else:
        query = ("Insert into nfl_schedule (eid, gsis, d, t, q, k, h, hnn, hs, v, vnn, vs, p, rz, ga, gt, week, year, start_time,h_id,v_id) "+
			   "Values(%s,%s,'%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s',%s,%s)" %
	       (eid, gsis, day, time, quarter, k, home, home_long, home_score, away, away_long, away_score, p, rz, ga,
                weektype, week, season_year, str(start_time)[:-6],str(h_id),str(v_id)))
        added += 1
      cur.execute(query)

    db.commit()

    print "(%s Week %s): %s updated, %s added." % (str(season_year),str(week),str(updated),str(added))
  #http://www.nfl.com/ajax/scorestrip?season=2013&seasonType=REG&week=1
  #sched_url = 'http://www.nfl.com/ajax/scorestrip?season=%d&seasonType=%s&week=%d'

  #game_url = http://www.nfl.com/liveupdate/game-center/%s/%s_gtd.json
  #game_url = 'http://www.nfl.com/liveupdate/game-center/%s/%s_gtd.json'

def player_info(player):
    name = player.player_id+": "
    name += player.first_name+" "+player.last_name
    name += " ("+player.team+" - "+player.position+")"
    return name

def update_player_news(year,week,weektype):
    news_url = 'http://api.fantasy.nfl.com/v1/players/news?format=json'
    editor_rank_url = 'http://api.fantasy.nfl.com/v1/players/editorweekranks?format=json&season=%s&week=%s&count=75' % (str(year),str(week))
    researchinfo_url = 'http://api.fantasy.nfl.com/v1/players/researchinfo?format=json&season=%s&week=%s&count=200' % (str(year),str(week))

    # Update player researchinfo

    response = urllib.urlopen(researchinfo_url)
    data = json.loads(response.read())
    research_last_updated = data['lastUpdated']

    added = 0
    updated = 0

    for row in data['players']:
        # Get the gsisPlayerId from this rank, either a player or defense
        if row['gsisPlayerId'] == False and row['position'] == 'DEF':
            gsisPlayerId = row['teamAbbr']+'_D'
        elif row['gsisPlayerId'] != '':
            gsisPlayerId = row['gsisPlayerId']
        else:
            continue
        if row['depthChartOrder'] is None: row['depthChartOrder'] = 0

        query = 'select id, lastUpdated from player_researchinfo where gsisPlayerId="%s"' % (gsisPlayerId)
        cur.execute(query)
        if cur.rowcount > 0:
            research_row = cur.fetchone()
            if str(research_row['lastUpdated']) == str(research_last_updated): continue
            query = (('update player_researchinfo set percentOwned=%s,percentOwnedChange=%s,depthChartOrder=%s,percentStartedChange=%s,'
                     +'numAdds=%s,percentStarted=%s,numDrops=%s,lastUpdated="%s",player_id=(select id from player where player_id="%s") where id=%s')
                %(row['percentOwned'],row['percentOwnedChange'],row['depthChartOrder'],row['percentStartedChange'],
                  row['numAdds'],row['percentStarted'],row['numDrops'],str(research_last_updated),gsisPlayerId,str(research_row['id'])))
            cur.execute(query)
            updated+=1
        else:
            query = (('insert into player_researchinfo (gsisPlayerId,percentOwned,percentOwnedChange,depthChartOrder,percentStartedChange,'
                     +'numAdds,percentStarted,numDrops,lastUpdated,player_id) VALUES("%s",%s,%s,%s,%s,%s,%s,%s,"%s",(select id from player where player_id="%s"))')
                %(gsisPlayerId,row['percentOwned'],row['percentOwnedChange'],row['depthChartOrder'],row['percentStartedChange'],
                  row['numAdds'],row['percentStarted'],row['numDrops'],str(research_last_updated),gsisPlayerId))

            cur.execute(query)
            added+=1
    db.commit()
    query = ('delete from player_researchinfo where lastUpdated < "%s"' %(research_last_updated))
    cur.execute(query)
    deleted = cur.rowcount
    db.commit()

    if added > 0:
        print "Researchinfo players added: " + str(added)
    elif updated >0:
        print "Researchinfo players updated: " + str(updated)
    else:
        print "No new researchinfo players"

    if deleted > 0:
        print "Deleted "+str(deleted)+" researchinfo players."
    else:
        print "No researchinfo players to delete"

    # Update editor player ranks
    editor_rank_positions = ['QB','RB','WR','TE','K','DEF']
    added = 0
    updated = 0
    for pos in editor_rank_positions:
        temp_url = editor_rank_url+'&position='+pos

        response = urllib.urlopen(temp_url)
        data = json.loads(response.read())
        rank_last_updated = data['lastUpdated']
        for row in data['players']:
            # Get the gsisPlayerId from this rank, either a player or defense
            if row['gsisPlayerId'] == False and row['position'] == 'DEF':
                gsisPlayerId = row['teamAbbr']+'_D'
            elif row['gsisPlayerId'] != '':
                gsisPlayerId = row['gsisPlayerId']
            else:
                continue
            query = 'select id, lastUpdated from player_rank where gsisPlayerId="%s"' % (gsisPlayerId)
            cur.execute(query)
            if cur.rowcount > 0:
                rank_row = cur.fetchone()
                if str(rank_row['lastUpdated']) == str(rank_last_updated): continue

                rank_id = rank_row['id']
                query = (('update player_rank set rank=%s,rank_pos="%s",player_id=(select id from player where player_id="%s"),lastUpdated="%s" where id=%s')
                    %(row['rank'],row['position'],str(gsisPlayerId),str(rank_last_updated),str(rank_id)))
                cur.execute(query)
                updated+=1
            else:
                query = (('insert into player_rank (gsisPlayerId,rank,rank_pos,lastUpdated,player_id) VALUES ("%s",%s,"%s","%s",(select id from player where player_id="%s"))')
                    %(gsisPlayerId,row['rank'],row['position'],str(rank_last_updated),gsisPlayerId))
                cur.execute(query)
                added+=1
    db.commit()
    query = ('delete from player_rank where lastUpdated < "%s"' %(rank_last_updated))
    cur.execute(query)
    deleted = cur.rowcount
    db.commit()

    if added > 0:
        print "Ranked players added: " + str(added)
    elif updated >0:
        print "Ranked players updated: " + str(updated)
    else:
        print "No new ranked players"

    if deleted > 0:
        print "Deleted "+str(deleted)+" ranked players."
    else:
        print "No ranked players to delete"

    response = urllib.urlopen(news_url)
    data = json.loads(response.read())

    added = 0

    for row in data['news']:

        # Check if news ID already exists in player_news table
        query = 'select id from player_news where news_id = %s' % (str(row['id']))
        cur.execute(query)
        if cur.rowcount > 0: continue

        # Check if the player's gsisPlayerId is in the player table
        query = 'select id from player where player_id = "%s"' % (row['gsisPlayerId'])
        cur.execute(query)
        if cur.rowcount == 0: continue

        player_id = cur.fetchone()['id']

        query = (('insert into player_news (news_id,gsisPlayerId,news_date,source,headline,body,analysis,player_id) values (%s,"%s","%s","%s","%s","%s","%s",%s)')
                % (row['id'],row['gsisPlayerId'],str(row['timestamp']),MySQLdb.escape_string(row['source']),MySQLdb.escape_string(row['headline']),
                   MySQLdb.escape_string(row['body']),MySQLdb.escape_string(row['analysis']),str(player_id)))

        cur.execute(query)
        db.commit()

        added += 1

    query = ('delete from player_news where news_date < NOW() - INTERVAL 90 DAY')
    cur.execute(query)
    deleted = cur.rowcount
    db.commit()

    if added > 0:
        print "New news items added: " + str(added)
    else:
        print "No new news items to add."

    if deleted > 0:
        print "Deleted "+str(deleted)+" news items older than 90 days."
    else:
        print "No news items older than 90 days to delete."

def update_player_draft_ranks():
    ranks_url = 'http://api.fantasy.nfl.com/v1/players/userdraftranks?format=json&count=100'
    players = list()

    for i in range(0,5):
        response = urllib.urlopen(ranks_url+'&offset='+str(i*100))
        data = json.loads(response.read())
        players += data['players']

    for p in players:

        # Get the gsisPlayerId from this rank, either a player or defense
        if p['gsisPlayerId'] == False and p['position'] == 'DEF':
            gsisPlayerId = p['teamAbbr']+'_D'
        elif p['gsisPlayerId'] != '':
            gsisPlayerId = p['gsisPlayerId']
        else:
            continue

        # Look up an id in the player table for this gsisPlayerId
        query = 'select id from player where player_id = "%s"' % (gsisPlayerId)
        cur.execute(query)

        if cur.rowcount < 1: continue
        player_id = cur.fetchone()['id']

        # Sometimes aav is None, but we're expecting a float
        if p['aav'] == None:
            p['aav'] = 0.0

        # Check to see if that player_id is already in the rank table
        query = 'select * from draft_player_rank where player_id = %s' % (str(player_id))
        cur.execute(query)

        # Player is already ranked, update the record with new data
        if cur.rowcount == 1:
            rank_id = cur.fetchone()['id']
            query = (('update draft_player_rank set rank=%s, aav=%s, last_updated="%s" where id = %s')
                    % (str(p['rank']),str(p['aav']),sql_now,str(rank_id)))
            cur.execute(query)
        # Else, player is not yet ranked, add the new record
        else:
            query = (('insert into draft_player_rank (player_id, rank, aav, gsisPlayerId, last_updated) VALUES (%s,%s,%s,"%s","%s")')
                    % (str(player_id),str(p['rank']),str(p['aav']),gsisPlayerId,sql_now))
            cur.execute(query)
        db.commit()

    # Delete any records for players who haven't been updated, they are not ranked any longer.
    query = 'delete from draft_player_rank where last_updated != "%s"' % (sql_now)
    cur.execute(query)
    db.commit()

    # Lastly, set the rank_order so players can be ordered by integers 1 to n, best to worst
    query = 'select id from draft_player_rank order by rank asc'
    cur.execute(query)
    results = cur.fetchall()
    cur_rank = 1
    for row in results:
        query = 'update draft_player_rank set rank_order = %s where id = %s' % (str(cur_rank), str(row['id']))
        cur.execute(query)
        cur_rank += 1
    db.commit()

def update_player_injuries():
    # Get the injury types
    query = 'select text_id, short_text from player_injury_type'
    cur.execute(query)
    injury_type_results = cur.fetchall()
    injury_types = list()
    for i in injury_type_results:
        injury_types.append(i['short_text'])

    injury_url = 'http://www.nfl.com/injuries'

    response = urllib.urlopen(injury_url)
    data = response.read()

    # Figure out what week this injury data is from
    injury_week = data.split('<h3>NFL Injuries Week ')[1].split('</h3>')[0]

    prefix='{player: '
    suffix='}'
    player_start = data.split(prefix)
    updated_count = 0
    added_count = 0
    for p in player_start[1:]:
        player_json_like = prefix+p.split(suffix)[0].strip()+suffix
        player_parts_list = player_json_like.replace('{','').replace('}','').split(',')
        player_dict = dict()
        for p in player_parts_list:
            (key, val) = p.split(':')
            player_dict[key.strip()] = val.replace('"',"").strip()
        if player_dict['gameStatus'] not in injury_types: continue
        query = 'select id from player where esbid = "%s"' % (player_dict['esbId'])
        cur.execute(query)
        if cur.rowcount > 0:
            player_db_id = cur.fetchone()['id']
        else:
            continue
        query = 'select id from player_injury where player_id = %s' % (player_db_id)
        cur.execute(query)
        if cur.rowcount > 0:
            row_id = cur.fetchone()['id']
            query = (('update player_injury set injury="%s", practiceStatus="%s", last_updated="%s", player_injury_type_id='
                     +'(select id from player_injury_type where short_text="%s"), week=%s where id=%s')
                     %(player_dict['injury'],player_dict['practiceStatus'],sql_now,player_dict['gameStatus'],str(injury_week),str(row_id)))
            cur.execute(query)
            updated_count+=1
        else:
            query = (('insert into player_injury (player_id,injury,practiceStatus,last_updated,player_injury_type_id,description,week)'+
                    'values(%s,"%s","%s","%s",(select id from player_injury_type where short_text="%s"),"",%s)')
                    %(str(player_db_id),player_dict['injury'],player_dict['practiceStatus'],sql_now,player_dict['gameStatus'],str(injury_week)))
            cur.execute(query)
            added_count+=1
        db.commit()

    query = ('delete from player_injury where last_updated < "%s"' %(sql_now))
    cur.execute(query)
    deleted = cur.rowcount
    db.commit()

    print "Injury report for week "+str(injury_week)

    if added_count > 0:
        print "Injured players added: " + str(added_count)
    elif updated_count >0:
        print "Injured players updated: " + str(updated_count)
    else:
        print "No new injured players"

    if deleted > 0:
        print "Deleted "+str(deleted)+" injured players."
    else:
        print "No injured players to delete"

# Used to look up database IDs for NFL teams
def get_team_dict():
    cur.execute('select id, club_id, alt_club_ids from nfl_team')
    team_dict = collections.defaultdict(lambda: 0, {})
    for row in cur.fetchall():
        team_dict[row['club_id']] = row['id']
        if row['alt_club_ids']:
            for alt in row['alt_club_ids'].split(','):
                alt = alt.strip()
                if alt != "":
                    team_dict[alt] = row['id']

    return team_dict

parser = argparse.ArgumentParser(description='FFLProject: Update various parts of the database')

parser.add_argument('-schedule', action="store_true", default=False, help="Update NFL schedule")
parser.add_argument('-schedule_clear', action="store_true", default=False, help="Add this to delete existing schedule records for the week and re-add them.")
#parser.add_argument('-g', action="store_true", default=False, help="Update NFL game stats and recalculate fantasy stats")
parser.add_argument('-players', action="store_true", default=False, help="Update NFL players")
parser.add_argument('-photos', action="store_true", default=False, help="Check for photos for players that don't have one.")
parser.add_argument('-clear_player_generic_photo', action="store", default=None, required=False, help="Specify filename of player photo. Photos matching this file's hash will be cleared so they can be re-scanned.")
parser.add_argument('-stats_summary', action="store_true", default=False, help="Calculate and store player fantasy stats summaries")
parser.add_argument('-standings', action="store_true", default=False, help="Calculate standings results and add to schedule table.")
parser.add_argument('-year', action="store", default="0", required=False, help="Year")
parser.add_argument('-week', action="store", default="0", required=False, help="Week, use 'all' for all weeks.")
parser.add_argument('-weektype', action="store", default="none", required=False, help="Type: REG, POST, PRE")
parser.add_argument('-hello', action="store_true", default=False, help="Just tell me what the current Year, Week, and WeekType is!")
parser.add_argument('-team_photos', action="store_true", default=False, help="Update generic team photos for defenses, offensive lines, and other non-players.")
parser.add_argument('-player_news', action="store_true", default=False, help="Update player news from NFL Fantasy api.")
parser.add_argument('-player_draft_ranks', action="store_true", default=False, help="Update player draft rankings from NFL Fantasy api.")
parser.add_argument('-player_injuries', action="store_true", default=False, help="Update player injury data from nfl.com/injuries.")
parser.add_argument('-backfill_esbids', action="store_true", default=False, help="Some NFL.com feeds use esbid's, attempt to go back 5 years and find them.")

start_time = time.time()
args = parser.parse_args()
main()

#update_players_from_game_data(2015, 1, "PRE")

print "Completed "+str(datetime.datetime.now())


text:
"""
ec2
===

A light-weight wrapper around boto to query for AWS EC2 instances,
security groups, and VPCs in a sane way.
"""

from setuptools import setup, find_packages
from setuptools.command.test import test as TestCommand

install_requires = [
    'boto',
]

tests_require = [
    'mock',
    'pytest',
    'pytest-cov',
]

class PyTest(TestCommand):
    def finalize_options(self):
        TestCommand.finalize_options(self)
        self.test_suite = True

    def run_tests(self):
        import pytest
        import sys
        sys.exit(pytest.main(self.test_args))

setup(
    name='ec2',
    version='0.4.0',
    author='Matt Robenolt',
    author_email='matt@ydekproductions.com',
    url='https://github.com/mattrobenolt/ec2',
    description='Query for AWS EC2 instances, security groups, and VPCs simply',
    long_description=__doc__,
    packages=find_packages(exclude=('tests',)),
    install_requires=install_requires,
    tests_require=tests_require,
    license='BSD',
    cmdclass={'test': PyTest},
    test_suite='tests',
    zip_safe=False,
    classifiers=[
        'Development Status :: 4 - Beta',
        'Intended Audience :: Developers',
        'Operating System :: OS Independent',
        'Topic :: Software Development',
    ],
)


text:
FROM omab/pyenv-tox
MAINTAINER Matías Aguirre <matiasaguirre@gmail.com>
RUN apt-get update
RUN apt-get install -y make libxml2-dev libxmlsec1-dev pkg-config


text:
from watson.validators import abc

class SuppliedValues(abc.Validator):

    """Validate that a value exists in the list of supplied values.

    Example:

    .. code-block:: python

        validator = Length(1, 10)
        validator('Test')  # True
        validator('Testing maximum')  # raises ValueError
    """

    message = None

    def __init__(self, message='"{value}" is not a valid option.'):
        self.message = message

    def __call__(self, value, **kwargs):
        iterable = (tuple, list)
        if not isinstance(value, iterable):
            value = [value]
        if not set(value).issubset(set(kwargs['field'].actual_values)):
            value = ', '.join(str(v) for v in value) if isinstance(value, iterable) else value
            raise ValueError(self.message.format(value=value))
        return True


text:
describe("JAIL plugin", function(){

	afterEach(function(){
		$('#container').empty();
	});

	it("should load the images when visible", function(){
		loadFixtures('myfixture.html');
		runs(function(){
			$('#container img').jail();
		});

		waitsFor(function(){
			return (!!$('img#img1').attr("src").match("sample1.jpg"));
		}, 1000);

		// img1 visible, img2 not visible
		runs(function(){
			expect($('img#img1').attr("data-src")).toBeFalsy();
			expect($('img#img2').attr("data-src")).toBeTruthy();
		});
	});

	it("should load an image after scrolling down and the image becomes visible", function(){
		loadFixtures('myfixture2.html');
		// Not loaded immediately
		expect($('img#img2').attr("data-src")).toBeTruthy();
		expect($('img#img3').attr("data-src")).toBeTruthy();

		runs(function(){
			$('#container img').jail();
			$('html, body').animate({
		        scrollTop: $("#img2").offset().top
		    }, 100);
		});

		waitsFor(function(){
			return (!!$('img#img2').attr("src").match("sample2.jpg"));
		}, 1000);

		// img1 visible, img2  visible, im3 not visible
		runs(function(){
			expect($('img#img1').attr("data-src")).toBeFalsy();
			expect($('img#img2').attr("data-src")).toBeFalsy();
			expect($('img#img3').attr("data-src")).toBeTruthy();
		});
	});

	it("should load the images when visible after 1000ms with parameter 'timeout:1000'", function(){
		loadFixtures('myfixture.html');
		runs(function(){
			$('#container img').jail({timeout: 1000});
		});

		waitsFor(function(){
			return (!!$('img#img1').attr("src").match("sample1.jpg"));
		}, 2000);

		// Not loaded immediately
		expect($('img#img1').attr("data-src")).toBeTruthy();

		// img1 visible, img2 not visible
		runs(function(){
			expect($('img#img1').attr("data-src")).toBeFalsy();
			expect($('img#img2').attr("data-src")).toBeTruthy();
		});
	});

	it("should load the images when visible or, not visible but within a certain 'offset'", function(){
		loadFixtures('myfixture.html');
		runs(function(){
			$('#container img').jail({offset: 1200});
		});

		waitsFor(function(){
			return (!!$('img#img2').attr("src").match("sample2.jpg"));
		}, 1000);

		// Not loaded immediately
		expect($('img#img2').attr("data-src")).toBeTruthy();

		// img1 visible, img2 visible
		runs(function(){
			expect($('img#img1').attr("data-src")).toBeFalsy();
			expect($('img#img2').attr("data-src")).toBeFalsy();
		});
	});

	it("should load an image after clicking on a link", function(){
		loadFixtures('myfixture2.html');

		// Not loaded immediately
		expect($('img#img1').attr("data-src")).toBeTruthy();
		expect($('img#img2').attr("data-src")).toBeTruthy();
		expect($('img#img3').attr("data-src")).toBeTruthy();

		runs(function(){
			$('#container img').jail({
				event: 'click',
				triggerElement: 'a.link'
			});
			$('a.link').click();
		});

		waitsFor(function(){
			return (!!$('img#img1').attr("src").match("sample1.jpg"));
		}, 2000);

		// img1 loaded, img2 not visible, im3 visible
		runs(function(){
			expect($('img#img1').attr("data-src")).toBeFalsy();
			expect($('img#img2').attr("data-src")).toBeTruthy();
			expect($('img#img3').attr("data-src")).toBeTruthy();
		});

		runs(function(){
			$('html, body').animate({
		        scrollTop: $("#img2").offset().top
		    }, 10);
		});

		waitsFor(function(){
			return (!!$('img#img2').attr("src").match("sample2.jpg"));
		}, 3000);

		// img1 loaded, img2 not visible, im3 visible
		runs(function(){
			expect($('img#img2').attr("data-src")).toBeFalsy();
			expect($('img#img3').attr("data-src")).toBeTruthy();
		});
	});

	it("should load the image after mouseovering on it", function(){
		loadFixtures('myfixture2.html');

		// Not loaded immediately
		expect($('img#img1').attr("data-src")).toBeTruthy();
		expect($('img#img2').attr("data-src")).toBeTruthy();
		expect($('img#img3').attr("data-src")).toBeTruthy();

		runs(function(){
			$('html, body').animate({
		        scrollTop: $("#img2").offset().top
		    }, 100);
		    $('#container img').jail({
				event: 'mouseover'
			});
			$('#img2').mouseover();
		});

		waitsFor(function(){
			return (!!$('img#img2').attr("src").match("sample2.jpg"));
		}, 1000);

		// img1 visible, img2 visible, img3 not loaded
		runs(function(){
			expect($('img#img2').attr("data-src")).toBeFalsy();
			expect($('img#img3').attr("data-src")).toBeTruthy();
		});
	});

	it("should call callbacks after the images are loaded", function(){
		loadFixtures('myfixture2.html');

		// Not loaded immediately
		expect($('img#img1').attr("data-src")).toBeTruthy();
		expect($('img#img2').attr("data-src")).toBeTruthy();
		expect($('img#img3').attr("data-src")).toBeTruthy();

		runs(function(){
			$('html, body').animate({
		        scrollTop: $("#img2").offset().top
		    }, 100);
		    $('#container img').jail({
				callback: function () { $('img').attr("alt", "Alternative"); },
				callbackAfterEachImage: function () { $('img').attr("alt", "New alt"); }
			});
		});

		waitsFor(function(){
			return (!!$('img#img2').attr("src").match("sample2.jpg"));
		}, 1000);

		// img1 visible, img2 visible, img3 not loaded
		runs(function(){
			expect($('img#img1').attr("data-src")).toBeFalsy();
			expect($('img#img2').attr("data-src")).toBeFalsy();
			expect($('img#img3').attr("data-src")).toBeTruthy();

			expect($('img').attr("alt")).toBe("New alt");
		});

		runs(function(){
			$('html, body').animate({
		        scrollTop: $("#img3").offset().top
		    }, 10);
		});

		waitsFor(function(){
			return (!!$('img#img3').attr("src").match("sample3.jpg"));
		}, 3000);

		runs(function(){
			expect($('img#img3').attr("data-src")).toBeFalsy();
			expect($('img').attr("alt")).toBe("Alternative");
		});

	});

	it("should load all images even the hidden ones", function(){
		loadFixtures('myfixture2.html');

		// Not loaded immediately
		expect($('img#img1').attr("data-src")).toBeTruthy();
		expect($('img#img2').attr("data-src")).toBeTruthy();
		expect($('img#img3').attr("data-src")).toBeTruthy();

		$('#container').css('visibility', 'hidden');

		runs(function(){
			$('#container img').jail({
				loadHiddenImages: true
			});
			$('html, body').animate({
		        scrollTop: $("#img2").offset().top
		    }, 10);
		});

		waitsFor(function(){
			return (!!$('img#img2').attr("src").match("sample2.jpg"));
		}, 3000);

		// img1 visible, img2 visible, img3 not loaded
		runs(function(){
			expect($('img#img2').attr("data-src")).toBeFalsy();
		});
	});
});


text:
Avatao C WebIDE challenge template
==================================

This project is prepared to provide an environment for challenges where the user has to write or complete C code, which is then checked by the CMocka framework. The provided code is also checked for memory leaks and other programming errors with _valgrind_, and for dangerous functions such as `system()` or `fork()` with _objdump_.

## Usage

You have to prepare a skeleton for the user to work on, and the unit tests which will test the submitted solution, and place them in `solvable/src` and `solvable/test`, respectively. You probably also want to place a copy of a complete solution in `controller/usr/share` for testing. Update the filenames in `controller/opt/server.py`, `solvable/server.py` and `solvable/CMakeLists.txt` according to your changes. You can also update any of the `CMakeLists.txt`s and the `Dockerfile`s to satisfy challenge-specific needs, should they arise. Fire up the containers and debug away!

## Tips and tricks

If you want to access the socket of the solvable container directly on the host, you can simply telnet to it:
```bash
telnet <container-ip> 7777
```
The IP of the container can be learned with the following command:
```bash
docker inspect $(docker ps | grep solvable | cut -c1-12) -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}'
```


text:
'use strict';

var _ = require('lodash');
var validator = require('validator');
var Reflux = require('reflux');

var Server = require('../../api/Server.js');
var Repository = require('../../api/Repository.js');
var Common = require('../../api/Common.js');
var DeskPageFrameActions = require('../../action/desk/DeskPageFrameActions.js');
var WizardGenerateComponentActions = require('../../action/wizard/WizardGenerateComponentActions.js');
var ModalComponentGeneratorActions = require('../../action/modal/ModalComponentGeneratorActions.js');

var defaultModel = {
    step: 0,
    errors: []
};

var WizardGenerateComponentStore = Reflux.createStore({
    listenables: WizardGenerateComponentActions,

    getInitialModel: function(){
        this.model = _.clone(defaultModel);
        return this.model;
    },

    onSetInitialOptions: function(options){
        this.model.selectedUmyId = options.selectedUmyId;
    },

    onStartStep0: function(){
        this.model.step = 0;
        this.trigger(this.model);
    },

    onSubmitStep0: function(options){
        this.model.errors = [];
        var componentGroup = options.componentGroup;
        if(!componentGroup || componentGroup.length <= 0 || !validator.isAlphanumeric(componentGroup)){
            this.model.errors.push('Please enter alphanumeric value for group name');
        }
        var componentName = options.componentName;
        if(!componentName || componentName.length <= 0 || !validator.isAlphanumeric(componentName)){
            this.model.errors.push('Please enter alphanumeric value for component name');
        }

        if(componentGroup === componentName){
            this.model.errors.push('Component name is equal to group name.');
        }

        var testComponent = Repository.getComponentFromTree(componentName);
        if(testComponent.value){
            this.model.errors.push(
                'There is already a component with name: ' + componentName + '.'
            );
        }

        var pageNames = Repository.getCurrentProjectPageNames();
        if(_.includes(pageNames, componentName)){
            this.model.errors.push('Entered component name is equal to the name of the existing page.');
        }

        if(this.model.errors.length === 0){
            var _componentName = options.componentName;
            if (_componentName && _componentName.length > 0) {
                var firstChar = _componentName.charAt(0).toUpperCase();
                _componentName = firstChar + _componentName.substr(1);
            }
            this.model.componentGroup = componentGroup;
            this.model.componentName = _componentName;

            this.onStartStep1();
        } else {
            this.trigger(this.model);
        }
    },

    onStartStep1: function(){

        Server.invoke('getGeneratorList', {},

            function(errors){
                this.model.errors = errors;
                this.trigger(this.model);
            }.bind(this),

            function(data){

                this.model.generatorList = data;

                this.model.step = 1;
                this.trigger(this.model);
            }.bind(this)

        );

    },

    onSubmitStep1: function(options) {

        var searchResult = Repository.findInCurrentPageModelByUmyId(this.model.selectedUmyId);
        var copy = searchResult.found;
        Common.cleanPropsUmyId(copy);
        copy.props = copy.props || {};

        Server.invoke('generateComponentCode',
            {
                componentGroup: this.model.componentGroup,
                componentName: this.model.componentName,
                componentModel: copy,
                generatorName: options.generatorName
            },

            function (errors) {
                this.model.errors = errors;
                this.trigger(this.model);
            }.bind(this),

            function (data) {

                this.model.componentSourceDataObject = data;
                this.model.componentModel = copy;
                this.onStartStep2();

            }.bind(this)
        );
    },

    onStartStep2: function(){
        this.model.step = 2;
        this.trigger(this.model);
    },

    onSubmitStep2: function(options){
        //if(options.sourceCode){
        //    this.model.componentSourceDataObject.component.sourceCode = options.sourceCode;
        //}

        Server.invoke('commitComponentCode', this.model.componentSourceDataObject,
            function(errors){
                this.model.errors = errors;
                this.trigger(this.model);
            }.bind(this),
            function(response){

                var isChildrenAcceptable = options.sourceCode.indexOf('this.props.children') >= 0;

                var projectModel = Repository.getCurrentProjectModel();
                var searchResult = null;
                for(var i = 0; i < projectModel.pages.length; i++){
                    if(!searchResult){
                        searchResult = Common.findByUmyId(projectModel.pages[i], this.model.selectedUmyId);
                    }
                }
                if(searchResult){
                    searchResult.found.type = this.model.componentName;
                    if(!isChildrenAcceptable){
                        searchResult.found.children = [];
                    }
                    searchResult.found.text = null;
                    Repository.renewCurrentProjectModel(projectModel);
                    DeskPageFrameActions.renderPageFrame();
                }

                ModalComponentGeneratorActions.hideModal();
            }.bind(this)
        );
    }
});

module.exports = WizardGenerateComponentStore;


text:
import path from 'path';
import {wrap} from 'jest-snapshot-serializer-raw';
import runJest from '../runJest';
import {extractSummary} from '../Utils';
const dir = path.resolve(__dirname, '../expect-async-matcher');

test('works with passing tests', () => {
  const result = runJest(dir, ['success.test.js']);
  expect(result.status).toBe(0);
});

test('shows the correct errors in stderr when failing tests', () => {
  const result = runJest(dir, ['failure.test.js']);

  expect(result.status).toBe(1);

  const rest = extractSummary(result.stderr)
    .rest.split('\n')
    .filter(line => line.indexOf('packages/expect/build/index.js') === -1)
    .join('\n');

  expect(wrap(rest)).toMatchSnapshot();
});


text:
package ru.r2cloud.jradio.meteor;

import ru.r2cloud.jradio.ByteInput;
import ru.r2cloud.jradio.lrpt.LRPT;

public class MeteorMN2 extends MeteorM {

	public MeteorMN2(ByteInput qpsk) {
		super(new LRPT(qpsk, false, false));
	}

}


text:
(function (window) {
  function Monkberry() {
    this.pool = new Pool();
    this.templates = {};
    this.filters = {};
    this.wrappers = {};
  }

  Monkberry.prototype.foreach = function (parent, node, children, template, data) {
    var i, j, len, childrenSize = size(children);

    len = childrenSize - data.length;
    for (i in children) if (children.hasOwnProperty(i)) {
      if (len-- > 0) {
        children[i].remove();
      } else {
        break;
      }
    }

    j = 0;
    for (i in children) if (children.hasOwnProperty(i)) {
      children[i].update(data[j++]);
    }

    for (j = childrenSize, len = data.length; j < len; j++) {
      var view = this.render(template, data[j]);
      view.parent = parent;
      view.appendTo(node);
      i = push(children, view);

      var viewRemove = view.remove;
      view.remove = (function (i, viewRemove) {
        return function () {
          viewRemove();
          remove(children, i);
        };
      })(i, viewRemove);
    }
  };

  Monkberry.prototype.iftest = function (parent, node, child/*.ref*/, template, data, test) {
    if (child.ref) {
      if (test) {
        child.ref.update(data);
      }
      else {
        child.ref.remove();
      }
    } else if (test) {
      var view = this.render(template, data);
      view.parent = parent;
      view.appendTo(node);

      var viewRemove = view.remove;
      view.remove = function () {
        viewRemove();
        child.ref = null;
      };

      child.ref = view;
    }
  };

  Monkberry.prototype.render = function (name, values, no_cache) {
    no_cache = no_cache || false;

    if (this.templates[name]) {
      var view, self = this;

      if (no_cache) {
        view = this.templates[name]();
      } else {
        view = this.pool.pull(name);
        if (!view) {
          view = this.templates[name]();
        }
      }

      view.appendTo = function (toNode) {
        for (var i = 0, len = view.nodes.length; i < len; i++) {
          if (toNode.nodeType == 8) {
            if (toNode.parentNode) {
              toNode.parentNode.insertBefore(view.nodes[i], toNode);
            } else {
              throw new Error("Can not insert child view into parent view.");
            }
          } else {
            toNode.appendChild(view.nodes[i]);
          }
        }
      };

      view.root = function (toNode) {
        if (view.nodes.length == 1) {
          return view.nodes[0];
        } else {
          var fragment = document.createDocumentFragment();
          for (var i = 0, len = view.nodes.length; i < len; i++) {
            fragment.appendChild(view.nodes[i]);
          }
          return fragment;
        }
      };

      view.remove = function () {
        var i = view.nodes.length;
        while (i--) {
          console.log('Remove', view.nodes[i]);
          view.nodes[i].parentNode.removeChild(view.nodes[i]);
        }
        self.pool.push(name, view);
      };

      if (values !== undefined) {
        view.update(values);
      }

      view.wrapped = view.wrapped || {};
      if (this.wrappers[name] && !view.wrapped[name]) {
        view = this.wrappers[name](view);
        view.wrapped[name] = true;
      }

      return view;
    } else {
      throw new Error('Template with name "' + name + '" does not found.');
    }
  };

  Monkberry.prototype.prerender = function (name, times) {
    while (times--) {
      this.pool.push(name, this.render(name, undefined, true));
    }
  };

  Monkberry.prototype.mount = function (templates) {
    var _this = this;
    Object.keys(templates).forEach(function (name) {
      _this.templates[name] = templates[name];
    });
  };

  function Pool() {
    this.store = {};
  }

  Pool.prototype.push = function (name, view) {
    if (!this.store[name]) {
      this.store[name] = [];
    }
    this.store[name].push(view);
  };

  Pool.prototype.pull = function (name) {
    if (this.store[name]) {
      return this.store[name].pop();
    } else {
      return void 0;
    }
  };

  // Helper functions

  function max(map) {
    var maximum = 0;
    for (var i in map) if (map.hasOwnProperty(i)) {
      if (i > maximum) {
        maximum = i;
      }
    }
    return parseInt(maximum);
  }

  function push(map, element) {
    var maximum = max(map) + 1;
    map[maximum] = element;
    return maximum;
  }

  function remove(map, i) {
    delete map[i];
  }

  function size(map) {
    var size = 0;
    for (var i in map) if (map.hasOwnProperty(i)) {
      size++;
    }
    return size;
  }

  window.monkberry = new Monkberry();
})(window);


text:
package helpdesk.controllers;

import java.util.List;
import helpdesk.beans.Usuario;

public interface IUsuarioController {

    Usuario efetuarLogin(String usuario,String senha);
}


text:
from django.test import TestCase, Client
from django.test.client import RequestFactory
from django.core.urlresolvers import reverse
from django.contrib import admin
from django.contrib.flatpages.models import FlatPage

from admin_extras.admin import ReadOnlyMixin

from .utils import (
    create_staff_user,
    create_superuser_user,
    create_flatpage,
    add_change_permission,
)

from nose import tools

class TestReadOnlyAdmin(TestCase):

    def setUp(self):
        super(TestReadOnlyAdmin, self).setUp()
        self.model_for_read_only = FlatPage
        self.rf = RequestFactory()
        self.staff_user = create_staff_user(
            self,
            username='john',
            email='john@john.com',
            password='top_secret',
        )
        self.superuser = create_superuser_user(
            self,
            username='joe',
            email='joe@joe.com',
            password='top_secret',
        )
        self.flatpage = create_flatpage(
            self,
            content='page'
        )

    def test_readonly_staff_user_has_excluded_spec_actions(self):
        add_change_permission(self.staff_user, self.model_for_read_only, readonly=True)
        admin_class = admin.site._registry[self.model_for_read_only].__class__
        admin_instance = admin_class(self.model_for_read_only, admin.site)
        url = reverse('admin:flatpages_flatpage_changelist')
        request = self.rf.get(url)
        request.user = self.staff_user
        for action in ReadOnlyMixin.drop_actions:
            tools.assert_not_in(action, admin_instance.get_actions(request))

    def test_readonly_staff_user_get_change_flatpage(self):
        add_change_permission(self.staff_user, self.model_for_read_only, readonly=True)
        url = reverse('admin:flatpages_flatpage_change', args=(self.flatpage.id,))
        c = Client()
        tools.assert_true(c.login(username=self.staff_user.username, password='top_secret'))
        response = c.get(url)
        tools.assert_true(self.staff_user.is_staff)
        tools.assert_true(self.staff_user.is_active)
        tools.assert_true(self.staff_user.is_authenticated())
        tools.assert_equals(200, response.status_code)

    def test_readonly_staff_user_cannot_change_flatpage(self):
        new_content = '%s 2' % self.flatpage.content
        add_change_permission(self.staff_user, self.model_for_read_only, readonly=True)
        url = reverse('admin:flatpages_flatpage_change', args=(self.flatpage.id,))
        c = Client()
        tools.assert_true(c.login(username=self.staff_user.username, password='top_secret'))
        post_data = dict(
            _save='save',
            url=self.flatpage.url,
            title=self.flatpage.title,
            template_name=self.flatpage.template_name or '',
            sites=self.flatpage.sites.all()[0].pk,
            content=new_content,
        )
        response = c.post(url, data=post_data)
        tools.assert_true(self.staff_user.is_staff)
        tools.assert_true(self.staff_user.is_active)
        tools.assert_true(self.staff_user.is_authenticated())
        tools.assert_equals(self.flatpage.content, FlatPage.objects.get(pk=self.flatpage.pk).content)
        self.assertRedirects(response, url)

    def test_superuser_has_all_actions(self):
        admin_class = admin.site._registry[self.model_for_read_only].__class__
        admin_instance = admin_class(self.model_for_read_only, admin.site)
        url = reverse('admin:flatpages_flatpage_changelist')
        request = self.rf.get(url)
        request.user = self.superuser
        for action in ReadOnlyMixin.drop_actions:
            tools.assert_in(action, admin_instance.get_actions(request))

    def test_superuser_get_change_flatpage(self):
        url = reverse('admin:flatpages_flatpage_change', args=(self.flatpage.id,))
        c = Client()
        tools.assert_true(c.login(username=self.superuser.username, password='top_secret'))
        response = c.get(url)
        tools.assert_true(self.superuser.is_staff)
        tools.assert_true(self.superuser.is_active)
        tools.assert_true(self.superuser.is_superuser)
        tools.assert_true(self.superuser.is_authenticated())
        tools.assert_equals(200, response.status_code)

    def test_superuser_user_can_change_flatpage(self):
        new_content = '%s 2' % self.flatpage.content
        url = reverse('admin:flatpages_flatpage_change', args=(self.flatpage.id,))
        redir_url = reverse('admin:flatpages_flatpage_changelist')
        c = Client()
        tools.assert_true(c.login(username=self.superuser.username, password='top_secret'))
        post_data = dict(
            _save='save',
            url=self.flatpage.url,
            title=self.flatpage.title,
            template_name=self.flatpage.template_name or '',
            sites=self.flatpage.sites.all()[0].pk,
            content=new_content,
        )
        response = c.post(url, data=post_data)
        tools.assert_true(self.superuser.is_staff)
        tools.assert_true(self.superuser.is_active)
        tools.assert_true(self.superuser.is_authenticated())
        tools.assert_equals(new_content, FlatPage.objects.get(pk=self.flatpage.pk).content)
        self.assertRedirects(response, redir_url)

    def test_staff_user_with_perm_has_all_actions(self):
        add_change_permission(self.staff_user, self.model_for_read_only)
        admin_class = admin.site._registry[self.model_for_read_only].__class__
        admin_instance = admin_class(self.model_for_read_only, admin.site)
        url = reverse('admin:flatpages_flatpage_changelist')
        request = self.rf.get(url)
        request.user = self.staff_user
        for action in ReadOnlyMixin.drop_actions:
            tools.assert_in(action, admin_instance.get_actions(request))

    def test_staff_user_with_perm_get_change_flatpage(self):
        add_change_permission(self.staff_user, self.model_for_read_only)
        url = reverse('admin:flatpages_flatpage_change', args=(self.flatpage.id,))
        c = Client()
        tools.assert_true(c.login(username=self.staff_user.username, password='top_secret'))
        response = c.get(url)
        tools.assert_true(self.staff_user.is_staff)
        tools.assert_true(self.staff_user.is_active)
        tools.assert_true(self.staff_user.is_authenticated())
        tools.assert_equals(200, response.status_code)

    def test_staff_user_with_perm_can_change_flatpage(self):
        new_content = '%s 2' % self.flatpage.content
        add_change_permission(self.staff_user, self.model_for_read_only)
        url = reverse('admin:flatpages_flatpage_change', args=(self.flatpage.id,))
        redir_url = reverse('admin:flatpages_flatpage_changelist')
        c = Client()
        tools.assert_true(c.login(username=self.staff_user.username, password='top_secret'))
        post_data = dict(
            _save='save',
            url=self.flatpage.url,
            title=self.flatpage.title,
            template_name=self.flatpage.template_name or '',
            sites=self.flatpage.sites.all()[0].pk,
            content=new_content,
        )
        response = c.post(url, data=post_data)
        tools.assert_true(self.staff_user.is_staff)
        tools.assert_true(self.staff_user.is_active)
        tools.assert_true(self.staff_user.is_authenticated())
        tools.assert_equals(new_content, FlatPage.objects.get(pk=self.flatpage.pk).content)
        self.assertRedirects(response, redir_url)

    def test_staff_user_without_perms_cannot_view_change_flatpage(self):
        url = reverse('admin:flatpages_flatpage_change', args=(self.flatpage.id,))
        c = Client()
        tools.assert_true(c.login(username=self.staff_user.username, password='top_secret'))
        response = c.get(url)
        tools.assert_true(self.staff_user.is_staff)
        tools.assert_true(self.staff_user.is_active)
        tools.assert_true(self.staff_user.is_authenticated())
        tools.assert_equals(403, response.status_code)

    def test_staff_user_without_perms_cannot_change_flatpage(self):
        new_content = '%s 2' % self.flatpage.content
        url = reverse('admin:flatpages_flatpage_change', args=(self.flatpage.id,))
        c = Client()
        tools.assert_true(c.login(username=self.staff_user.username, password='top_secret'))
        post_data = dict(
            _save='save',
            url=self.flatpage.url,
            title=self.flatpage.title,
            template_name=self.flatpage.template_name or '',
            sites=self.flatpage.sites.all()[0].pk,
            content=new_content,
        )
        response = c.post(url, data=post_data)
        tools.assert_true(self.staff_user.is_staff)
        tools.assert_true(self.staff_user.is_active)
        tools.assert_true(self.staff_user.is_authenticated())
        tools.assert_equals(self.flatpage.content, FlatPage.objects.get(pk=self.flatpage.pk).content)
        tools.assert_equals(403, response.status_code)


text:
<?php
/**
 * @package WPSEO\Admin
 */

/**
 * Class to change or add WordPress dashboard widgets
 */
class Yoast_Dashboard_Widget {

	const CACHE_TRANSIENT_KEY = 'wpseo-dashboard-totals';

	/**
	 * @var WPSEO_Statistics
	 */
	protected $statistics;

	/**
	 * @param WPSEO_Statistics $statistics The statistics class to retrieve statistics from.
	 */
	public function __construct( WPSEO_Statistics $statistics = null ) {
		if ( null === $statistics ) {
			$statistics = new WPSEO_Statistics();
		}

		$this->statistics = $statistics;

		add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_dashboard_stylesheet' ) );
		add_action( 'wp_insert_post', array( $this, 'clear_cache' ) );
		add_action( 'delete_post', array( $this, 'clear_cache' ) );

		if ( $this->show_widget() ) {
			add_action( 'wp_dashboard_setup', array( $this, 'add_dashboard_widget' ) );
		}
	}

	/**
	 * Adds dashboard widget to WordPress
	 */
	public function add_dashboard_widget() {
		wp_add_dashboard_widget(
			'wpseo-dashboard-overview',
			/* translators: %s is the plugin name */
			sprintf( __( '%s Posts Overview', 'wordpress-seo' ), 'Yoast SEO' ),
			array( $this, 'display_dashboard_widget' )
		);
	}

	/**
	 * Display the dashboard widget
	 */
	public function display_dashboard_widget() {
		$statistics = $this->statistic_items();

		$onpage_option = new WPSEO_OnPage_Option();
		$onpage        = false;
		if ( $onpage_option->is_enabled() ) {
			$onpage = array(
					'indexable' => $onpage_option->get_status(),
					'can_fetch' => $onpage_option->should_be_fetched(),
			);
		}

		include WPSEO_PATH . '/admin/views/dashboard-widget.php';
	}

	/**
	 * Enqueue's stylesheet for the dashboard if the current page is the dashboard
	 */
	public function enqueue_dashboard_stylesheet() {
		$current_screen = get_current_screen();

		if ( $current_screen instanceof WP_Screen && 'dashboard' === $current_screen->id ) {
			$asset_manager = new WPSEO_Admin_Asset_Manager();
			$asset_manager->enqueue_style( 'wp-dashboard' );
		}
	}

	/**
	 * Clears the dashboard widget items cache
	 */
	public function clear_cache() {
		delete_transient( self::CACHE_TRANSIENT_KEY );
	}

	/**
	 * An array representing items to be added to the At a Glance dashboard widget
	 *
	 * @return array
	 */
	private function statistic_items() {
		$transient = get_transient( self::CACHE_TRANSIENT_KEY );
		$user_id   = get_current_user_id();

		if ( isset( $transient[ $user_id ] ) ) {
			return $transient[ $user_id ];
		}

		return $this->set_statistic_items_for_this_user( $transient );
	}

	/**
	 * Set the cache for a specific user
	 *
	 * @param array|boolean $transient The current stored transient with the cached data.
	 *
	 * @return mixed
	 */
	private function set_statistic_items_for_this_user( $transient ) {
		if ( $transient === false ) {
			$transient = array();
		}

		$user_id               = get_current_user_id();
		$transient[ $user_id ] = array_filter( $this->get_seo_scores_with_post_count(), array( $this, 'filter_items' ) );

		set_transient( self::CACHE_TRANSIENT_KEY, $transient, DAY_IN_SECONDS );

		return $transient[ $user_id ];
	}

	/**
	 * Set the SEO scores belonging to their SEO score result
	 *
	 * @return array
	 */
	private function get_seo_scores_with_post_count() {
		$ranks = WPSEO_Rank::get_all_ranks();

		return array_map( array( $this, 'map_rank_to_widget' ), $ranks );
	}

	/**
	 * Converts a rank to data usable in the dashboard widget
	 *
	 * @param WPSEO_Rank $rank The rank to map.
	 *
	 * @return array
	 */
	private function map_rank_to_widget( WPSEO_Rank $rank ) {
		return array(
			'seo_rank'   => $rank->get_rank(),
			'title'      => $this->get_title_for_rank( $rank ),
			'class'      => 'wpseo-glance-' . $rank->get_css_class(),
			'icon_class' => $rank->get_css_class(),
			'count'      => $this->statistics->get_post_count( $rank ),
		);
	}

	/**
	 * Returns a dashboard widget label to use for a certain rank
	 *
	 * @param WPSEO_Rank $rank The rank to return a label for.
	 *
	 * @return string
	 */
	private function get_title_for_rank( WPSEO_Rank $rank ) {
		$labels = array(
			WPSEO_Rank::NO_FOCUS => __( 'Posts without focus keyword', 'wordpress-seo' ),
			WPSEO_Rank::BAD      => __( 'Posts with bad SEO score', 'wordpress-seo' ),
			WPSEO_Rank::OK       => __( 'Posts with OK SEO score', 'wordpress-seo' ),
			WPSEO_Rank::GOOD     => __( 'Posts with good SEO score', 'wordpress-seo' ),
			/* translators: %s expands to noindex */
			WPSEO_Rank::NO_INDEX => sprintf( __( 'Posts that are set to “%s”', 'wordpress-seo' ), 'noindex' ),
		);

		return $labels[ $rank->get_rank() ];
	}

	/**
	 * Filter items if they have a count of zero
	 *
	 * @param array $item Data array.
	 *
	 * @return bool
	 */
	private function filter_items( $item ) {
		return 0 !== $item['count'];
	}

	/**
	 * Returns true when the dashboard widget should be shown.
	 *
	 * @return bool
	 */
	private function show_widget() {
		$analysis_seo = new WPSEO_Metabox_Analysis_SEO();

		return $analysis_seo->is_enabled() && current_user_can( 'edit_posts' );
	}
}


text:
#include "qwindowsdirect2dintegration.h"

#include <QtGui/qpa/qplatformintegrationplugin.h>
#include <QtCore/QStringList>

QT_BEGIN_NAMESPACE

class QWindowsDirect2DIntegrationPlugin : public QPlatformIntegrationPlugin
{
    Q_OBJECT
    Q_PLUGIN_METADATA(IID "org.qt-project.Qt.QPA.QPlatformIntegrationFactoryInterface.5.2" FILE "direct2d.json")
public:
    QPlatformIntegration *create(const QString&, const QStringList&);
};

QPlatformIntegration *QWindowsDirect2DIntegrationPlugin::create(const QString& system, const QStringList& paramList)
{
    if (system.compare(system, QLatin1String("direct2d"), Qt::CaseInsensitive) == 0)
        return QWindowsDirect2DIntegration::create(paramList);
    return 0;
}

QT_END_NAMESPACE

#include "qwindowsdirect2dplatformplugin.moc"


text:
<!DOCTYPE html>

	<meta charset="utf-8">

	<title>CBBluetoothState Constants Reference</title>

	<link rel="stylesheet" href="../css/style.css">
	<meta name="viewport" content="initial-scale=1, maximum-scale=1.4">
	<meta name="generator" content="appledoc 2.2.1 (build 1333)">

				Cubeacon

				Eyro Labs

Index

Hierarchy

							On This Page

							<select id="jump-to">
	<option value="top">Jump To…</option>

</select>

CBBluetoothState Constants Reference

	Declared in
	CBConstant.h

	References
	CBBluetoothManager

CBBluetoothState

CBBluetoothState enum represents the current state of a CBBluetoothManager.

Definition

                        typedef NS_ENUM(uint8_t, CBBluetoothState ) {

                               CBBluetoothStateUnknown = 0,

                               CBBluetoothStateResetting,

                               CBBluetoothStateUnsupported,

                               CBBluetoothStateUnauthorized,

                               CBBluetoothStatePoweredOff,

                               CBBluetoothStatePoweredOn,

                            };

Constants

CBBluetoothStateUnknown

 State unknown, update imminent.

		Declared In CBConstant.h.

CBBluetoothStateResetting

 The connection with the system service was momentarily lost, update imminent.

		Declared In CBConstant.h.

CBBluetoothStateUnsupported

 The platform doesn't support the Bluetooth Low Energy Central/Client role.

		Declared In CBConstant.h.

CBBluetoothStateUnauthorized

 The application is not authorized to use the Bluetooth Low Energy role.

		Declared In CBConstant.h.

CBBluetoothStatePoweredOff

 Bluetooth is currently powered off.

		Declared In CBConstant.h.

CBBluetoothStatePoweredOn

 Bluetooth is currently powered on and available to use.

		Declared In CBConstant.h.

See Also

CBBluetoothManager

Declared In

CBConstant.h

Copyright © 2016 Eyro Labs. All rights reserved. Updated: 2016-12-06

Generated by appledoc 2.2.1 (build 1333).


text:
<?php

/**
 * Attribute form apply element
 *
 * @author      Magento Core Team <core@magentocommerce.com>
 */
namespace Magento\Catalog\Block\Adminhtml\Product\Helper\Form;

class Apply extends \Magento\Framework\Data\Form\Element\Multiselect
{
    /**
     * @return string
     */
    public function getElementHtml()
    {
        $elementAttributeHtml = '';

        if ($this->getReadonly()) {
            $elementAttributeHtml = $elementAttributeHtml . ' readonly="readonly"';
        }

        if ($this->getDisabled()) {
            $elementAttributeHtml = $elementAttributeHtml . ' disabled="disabled"';
        }

        $html = '<select onchange="toggleApplyVisibility(this)"' . $elementAttributeHtml . '>'
            . '<option value="0">' . $this->getModeLabels('all') . '</option>'
            . '<option value="1" ' . ($this->getValue() == null ? '' : 'selected') . '>'
            . $this->getModeLabels('custom') . '</option>' . '</select>

';

        $html .= parent::getElementHtml();
        return $html;
    }

    /**
     * Dublicate interface of \Magento\Framework\Data\Form\Element\AbstractElement::setReadonly
     *
     * @param bool $readonly
     * @param bool $useDisabled
     * @return $this
     */
    public function setReadonly($readonly, $useDisabled = false)
    {
        $this->setData('readonly', $readonly);
        $this->setData('disabled', $useDisabled);
        return $this;
    }
}