text:
import random

import DistributedBossCogAI
import DistributedSuitAI
import SuitDNA
from direct.directnotify import DirectNotifyGlobal
from direct.distributed.ClockDelta import *
from direct.fsm import FSM
from otp.ai.AIBaseGlobal import *
from toontown.battle import BattleExperienceAI
from toontown.toon import NPCToons
from toontown.toonbase import TTLocalizer
from toontown.toonbase import ToontownGlobals
from otp.ai.MagicWordGlobal import *

class DistributedSellbotBossAI(DistributedBossCogAI.DistributedBossCogAI, FSM.FSM):
    notify = DirectNotifyGlobal.directNotify.newCategory('DistributedSellbotBossAI')
    limitHitCount = 6
    hitCountDamage = 35
    numPies = ToontownGlobals.FullPies

    def __init__(self, air):
        DistributedBossCogAI.DistributedBossCogAI.__init__(self, air, 's')
        FSM.FSM.__init__(self, 'DistributedSellbotBossAI')
        self.doobers = []
        self.cagedToonNpcId = random.choice(NPCToons.HQnpcFriends.keys())
        self.bossMaxDamage = ToontownGlobals.SellbotBossMaxDamage
        self.recoverRate = 0
        self.recoverStartTime = 0

    def delete(self):
        return DistributedBossCogAI.DistributedBossCogAI.delete(self)

    def getHoodId(self):
        return ToontownGlobals.SellbotHQ

    def getCagedToonNpcId(self):
        return self.cagedToonNpcId

    def magicWordHit(self, damage, avId):
        if self.attackCode != ToontownGlobals.BossCogDizzyNow:
            self.hitBossInsides()
        self.hitBoss(damage)

    def hitBoss(self, bossDamage):
        avId = self.air.getAvatarIdFromSender()
        if not self.validate(avId, avId in self.involvedToons, 'hitBoss from unknown avatar'):
            return
        self.validate(avId, bossDamage == 1, 'invalid bossDamage %s' % bossDamage)
        if bossDamage < 1:
            return
        currState = self.getCurrentOrNextState()
        if currState != 'BattleThree':
            return
        if self.attackCode != ToontownGlobals.BossCogDizzyNow:
            return
        bossDamage = min(self.getBossDamage() + bossDamage, self.bossMaxDamage)
        self.b_setBossDamage(bossDamage, 0, 0)
        if self.bossDamage >= self.bossMaxDamage:
            self.setState('NearVictory')
        else:
            self.__recordHit()

    def hitBossInsides(self):
        avId = self.air.getAvatarIdFromSender()
        if not self.validate(avId, avId in self.involvedToons, 'hitBossInsides from unknown avatar'):
            return
        currState = self.getCurrentOrNextState()
        if currState != 'BattleThree':
            return
        self.b_setAttackCode(ToontownGlobals.BossCogDizzyNow)
        self.b_setBossDamage(self.getBossDamage(), 0, 0)

    def hitToon(self, toonId):
        avId = self.air.getAvatarIdFromSender()
        if not self.validate(avId, avId != toonId, 'hitToon on self'):
            return
        if avId not in self.involvedToons or toonId not in self.involvedToons:
            return
        toon = self.air.doId2do.get(toonId)
        if toon:
            self.healToon(toon, 1)

    def touchCage(self):
        avId = self.air.getAvatarIdFromSender()
        currState = self.getCurrentOrNextState()
        if currState != 'BattleThree' and currState != 'NearVictory':
            return
        if not self.validate(avId, avId in self.involvedToons, 'touchCage from unknown avatar'):
            return
        toon = simbase.air.doId2do.get(avId)
        if toon:
            toon.b_setNumPies(self.numPies)
            toon.__touchedCage = 1
            self.__goodJump(avId)

    def finalPieSplat(self):
        if self.state != 'NearVictory':
            return
        self.b_setState('Victory')

    def doNextAttack(self, task):
        if self.attackCode == ToontownGlobals.BossCogDizzyNow:
            attackCode = ToontownGlobals.BossCogRecoverDizzyAttack
        else:
            attackCode = random.choice([ToontownGlobals.BossCogAreaAttack,
             ToontownGlobals.BossCogFrontAttack,
             ToontownGlobals.BossCogDirectedAttack,
             ToontownGlobals.BossCogDirectedAttack,
             ToontownGlobals.BossCogDirectedAttack,
             ToontownGlobals.BossCogDirectedAttack])
        if attackCode == ToontownGlobals.BossCogAreaAttack:
            self.__doAreaAttack()
        elif attackCode == ToontownGlobals.BossCogDirectedAttack:
            self.__doDirectedAttack()
        else:
            self.b_setAttackCode(attackCode)

    def __doAreaAttack(self):
        self.b_setAttackCode(ToontownGlobals.BossCogAreaAttack)
        if self.recoverRate:
            newRecoverRate = min(200, self.recoverRate * 1.2)
        else:
            newRecoverRate = 2
        now = globalClock.getFrameTime()
        self.b_setBossDamage(self.getBossDamage(), newRecoverRate, now)

    def __doDirectedAttack(self):
        if self.nearToons:
            toonId = random.choice(self.nearToons)
            self.b_setAttackCode(ToontownGlobals.BossCogDirectedAttack, toonId)
        else:
            self.__doAreaAttack()

    def b_setBossDamage(self, bossDamage, recoverRate, recoverStartTime):
        self.d_setBossDamage(bossDamage, recoverRate, recoverStartTime)
        self.setBossDamage(bossDamage, recoverRate, recoverStartTime)

    def setBossDamage(self, bossDamage, recoverRate, recoverStartTime):
        self.bossDamage = bossDamage
        self.recoverRate = recoverRate
        self.recoverStartTime = recoverStartTime

    def getBossDamage(self):
        now = globalClock.getFrameTime()
        elapsed = now - self.recoverStartTime
        return int(max(self.bossDamage - self.recoverRate * elapsed / 60.0, 0))

    def d_setBossDamage(self, bossDamage, recoverRate, recoverStartTime):
        timestamp = globalClockDelta.localToNetworkTime(recoverStartTime)
        self.sendUpdate('setBossDamage', [bossDamage, recoverRate, timestamp])

    def waitForNextStrafe(self, delayTime):
        currState = self.getCurrentOrNextState()
        if currState == 'BattleThree':
            taskName = self.uniqueName('NextStrafe')
            taskMgr.remove(taskName)
            taskMgr.doMethodLater(delayTime, self.doNextStrafe, taskName)

    def stopStrafes(self):
        taskName = self.uniqueName('NextStrafe')
        taskMgr.remove(taskName)

    def doNextStrafe(self, task):
        if self.attackCode != ToontownGlobals.BossCogDizzyNow:
            side = random.choice([0, 1])
            direction = random.choice([0, 1])
            self.sendUpdate('doStrafe', [side, direction])
        delayTime = 9
        self.waitForNextStrafe(delayTime)

    def __sendDooberIds(self):
        dooberIds = []
        for suit in self.doobers:
            dooberIds.append(suit.doId)

        self.sendUpdate('setDooberIds', [dooberIds])

    def d_cagedToonBattleThree(self, index, avId):
        self.sendUpdate('cagedToonBattleThree', [index, avId])

    def formatReward(self):
        return str(self.cagedToonNpcId)

    def makeBattleOneBattles(self):
        self.postBattleState = 'RollToBattleTwo'
        self.initializeBattles(1, ToontownGlobals.SellbotBossBattleOnePosHpr)

    def generateSuits(self, battleNumber):
        if battleNumber == 1:
            return self.invokeSuitPlanner(9, 0)
        else:
            return self.invokeSuitPlanner(10, 1)

    def removeToon(self, avId):
        toon = simbase.air.doId2do.get(avId)
        if toon:
            toon.b_setNumPies(0)
        DistributedBossCogAI.DistributedBossCogAI.removeToon(self, avId)

    def enterOff(self):
        DistributedBossCogAI.DistributedBossCogAI.enterOff(self)
        self.__resetDoobers()

    def enterElevator(self):
        DistributedBossCogAI.DistributedBossCogAI.enterElevator(self)
        self.b_setBossDamage(0, 0, 0)

    def enterIntroduction(self):
        DistributedBossCogAI.DistributedBossCogAI.enterIntroduction(self)
        self.__makeDoobers()
        self.b_setBossDamage(0, 0, 0)
        self.air.achievementsManager.toonsStartedVP(self.involvedToons)

    def exitIntroduction(self):
        DistributedBossCogAI.DistributedBossCogAI.exitIntroduction(self)
        self.__resetDoobers()

    def enterRollToBattleTwo(self):
        self.divideToons()
        self.barrier = self.beginBarrier('RollToBattleTwo', self.involvedToons, 45, self.__doneRollToBattleTwo)

    def __doneRollToBattleTwo(self, avIds):
        self.b_setState('PrepareBattleTwo')

    def exitRollToBattleTwo(self):
        self.ignoreBarrier(self.barrier)

    def enterPrepareBattleTwo(self):
        self.barrier = self.beginBarrier('PrepareBattleTwo', self.involvedToons, 30, self.__donePrepareBattleTwo)
        self.makeBattleTwoBattles()

    def __donePrepareBattleTwo(self, avIds):
        self.b_setState('BattleTwo')

    def exitPrepareBattleTwo(self):
        self.ignoreBarrier(self.barrier)

    def makeBattleTwoBattles(self):
        self.postBattleState = 'PrepareBattleThree'
        self.initializeBattles(2, ToontownGlobals.SellbotBossBattleTwoPosHpr)

    def enterBattleTwo(self):
        if self.battleA:
            self.battleA.startBattle(self.toonsA, self.suitsA)
        if self.battleB:
            self.battleB.startBattle(self.toonsB, self.suitsB)

    def exitBattleTwo(self):
        self.resetBattles()

    def enterPrepareBattleThree(self):
        self.barrier = self.beginBarrier('PrepareBattleThree', self.involvedToons, 30, self.__donePrepareBattleThree)

    def __donePrepareBattleThree(self, avIds):
        self.b_setState('BattleThree')

    def exitPrepareBattleThree(self):
        self.ignoreBarrier(self.barrier)

    def enterBattleThree(self):
        self.resetBattles()
        self.setPieType()
        self.b_setBossDamage(0, 0, 0)
        self.battleThreeStart = globalClock.getFrameTime()
        for toonId in self.involvedToons:
            toon = simbase.air.doId2do.get(toonId)
            if toon:
                toon.__touchedCage = 0

        self.waitForNextAttack(5)
        self.waitForNextStrafe(9)
        self.cagedToonDialogIndex = 100
        self.__saySomethingLater()

    def __saySomething(self, task = None):
        index = None
        avId = 0
        if len(self.involvedToons) == 0:
            return
        avId = random.choice(self.involvedToons)
        toon = simbase.air.doId2do.get(avId)
        if toon.__touchedCage:
            if self.cagedToonDialogIndex <= TTLocalizer.CagedToonBattleThreeMaxAdvice:
                index = self.cagedToonDialogIndex
                self.cagedToonDialogIndex += 1
            elif random.random() < 0.2:
                index = random.randrange(100, TTLocalizer.CagedToonBattleThreeMaxAdvice + 1)
        else:
            index = random.randrange(20, TTLocalizer.CagedToonBattleThreeMaxTouchCage + 1)
        if index:
            self.d_cagedToonBattleThree(index, avId)
        self.__saySomethingLater()
        return

    def __saySomethingLater(self, delayTime = 15):
        taskName = self.uniqueName('CagedToonSaySomething')
        taskMgr.remove(taskName)
        taskMgr.doMethodLater(delayTime, self.__saySomething, taskName)

    def __goodJump(self, avId):
        currState = self.getCurrentOrNextState()
        if currState != 'BattleThree':
            return
        index = random.randrange(10, TTLocalizer.CagedToonBattleThreeMaxGivePies + 1)
        self.d_cagedToonBattleThree(index, avId)
        self.__saySomethingLater()

    def exitBattleThree(self):
        self.stopAttacks()
        self.stopStrafes()
        taskName = self.uniqueName('CagedToonSaySomething')
        taskMgr.remove(taskName)

    def enterNearVictory(self):
        self.resetBattles()

    def exitNearVictory(self):
        pass

    def enterVictory(self):
        self.resetBattles()
        self.suitsKilled.append({'type': None,
         'level': None,
         'track': self.dna.dept,
         'isSkelecog': 0,
         'isForeman': 0,
         'isVP': 1,
         'isCFO': 0,
         'isSupervisor': 0,
         'isVirtual': 0,
         'activeToons': self.involvedToons[:]})
        self.barrier = self.beginBarrier('Victory', self.involvedToons, 10, self.__doneVictory)
        return

    def __doneVictory(self, avIds):
        self.d_setBattleExperience()
        self.b_setState('Reward')
        BattleExperienceAI.assignRewards(self.involvedToons, self.toonSkillPtsGained, self.suitsKilled, ToontownGlobals.dept2cogHQ(self.dept), self.helpfulToons)
        for toonId in self.involvedToons:
            toon = self.air.doId2do.get(toonId)
            if toon:
                if not toon.attemptAddNPCFriend(self.cagedToonNpcId, numCalls=1):
                    self.notify.info('%s.unable to add NPCFriend %s to %s.' % (self.doId, self.cagedToonNpcId, toonId))
                toon.b_promote(self.deptIndex)

    def exitVictory(self):
        self.takeAwayPies()

    def enterFrolic(self):
        DistributedBossCogAI.DistributedBossCogAI.enterFrolic(self)
        self.b_setBossDamage(0, 0, 0)

    def __resetDoobers(self):
        for suit in self.doobers:
            suit.requestDelete()

        self.doobers = []

    def __makeDoobers(self):
        self.__resetDoobers()
        for i in xrange(8):
            suit = DistributedSuitAI.DistributedSuitAI(self.air, None)
            level = random.randrange(len(SuitDNA.suitsPerLevel))
            suit.dna = SuitDNA.SuitDNA()
            suit.dna.newSuitRandom(level=level, dept=self.dna.dept)
            suit.setLevel(level)
            suit.generateWithRequired(self.zoneId)
            self.doobers.append(suit)

        self.__sendDooberIds()
        return

    def setPieType(self):
        for toonId in self.involvedToons:
            toon = simbase.air.doId2do.get(toonId)
            if toon:
                toon.d_setPieType(4)

    def takeAwayPies(self):
        for toonId in self.involvedToons:
            toon = simbase.air.doId2do.get(toonId)
            if toon:
                toon.b_setNumPies(0)

    def __recordHit(self):
        now = globalClock.getFrameTime()
        self.hitCount += 1
        if self.hitCount < self.limitHitCount or self.bossDamage < self.hitCountDamage:
            return
        self.b_setAttackCode(ToontownGlobals.BossCogRecoverDizzyAttack)

    def enterReward(self):
        self.air.achievementsManager.toonsFinishedVP(self.involvedToons)
        DistributedBossCogAI.DistributedBossCogAI.enterReward(self)

@magicWord(category=CATEGORY_ADMINISTRATOR)
def skipVP():
    """
    Skips to the final round of the VP.
    """
    invoker = spellbook.getInvoker()
    boss = None
    for do in simbase.air.doId2do.values():
        if isinstance(do, DistributedSellbotBossAI):
            if invoker.doId in do.involvedToons:
                boss = do
                break
    if not boss:
        return "You aren't in a VP!"
    if boss.state in ('PrepareBattleThree', 'BattleThree'):
        return "You can't skip this round."
    boss.exitIntroduction()
    boss.b_setState('PrepareBattleThree')
    return 'Skipping the first round...'

@magicWord(category=CATEGORY_ADMINISTRATOR)
def killVP():
    """
    Kills the VP.
    """
    invoker = spellbook.getInvoker()
    boss = None
    for do in simbase.air.doId2do.values():
        if isinstance(do, DistributedSellbotBossAI):
            if invoker.doId in do.involvedToons:
                boss = do
                break
    if not boss:
        return "You aren't in a VP!"
    boss.b_setState('Victory')
    return 'Killed VP.'


text:
var debug    = require('debug')('socializr:provider:instagram')
  , stream   = require('stream')
  , util     = require('util')
  , request  = require('superagent')
  , _        = require('underscore')
  , uuid     = require('node-uuid')
  , oauth1a  = require('../auth/oauth1a')
  , PubSubConnection  = require('../auth/pubsub')
  , Message = require('../message')

  , Transform = stream.Transform

  , IG_API_URL = 'https://api.instagram.com/v1/'

  , IG_OBJECT_USER = 'user'

  , IG_OBJECT_TAG = 'tag'

  , IG_OBJECT_LOCATION = 'location'

  , IG_OBJECT_GEOGRAPHY = 'geography'

  , IG_DEFAULT_SUBSRIPTION_TYPE = IG_OBJECT_USER

;

function Instagram(options){

  options = _.extend({
    filters: []
  },options);

  Transform.call(this, {
    objectMode: true
  });

  this.clientId     = options.appId;
  this.clientSecret = options.appSecret;
  this.subscriptionCallbackURL = options.subscriptionCallbackURL;

  this.pubsub         = options.pubsub || new PubSubConnection( this.clientSecret, this);
  this.uuid           = uuid.v1();

  this._filters = options.filters;
  this._tags = [];
};
util.inherits(Instagram, Transform);

Instagram.prototype.stream = function(request, auth, socializr){
  if( !this._piped){
    this._piped = true;
    this.pubsub
    .pipe( this)
    .pipe( socializr);
    this.on('warning', socializr._onError.bind(socializr));
  }
  var data, i;
  this._tags = this._tags.concat( request.tags);
  for( i in request.tags){
    data = {
      type: IG_OBJECT_TAG,
      tag: request.tags[i].toString().replace('#','')
    };
    debug('Subscribing to %s with %s',data.type,data.tag);
    this.subscribe( data, function(err,res){
      debug('Subscription responded %j',res?res.body:err);
    });
  }
  return this;
};

Instagram.prototype.unstream = function(request, auth, socializr){

  var data, i;
  this._tags = this._tags.concat( request.tags);
  for( i in request.tags){
    debug('Unsubscribing data %j',request.tags[i]);
    this.unsubscribe( request.tags[i].toString().replace('#',''), function(err,res){
      debug('Unsubscribe responded %j',res.body);
    });
  }
  return this;
};

Instagram.prototype.auth = function(auth){
  auth._provider = this;
  return auth;
};

Instagram.prototype.subscribe = function(sub, cb){

  var verify_token = this.pubsub.verifyToken()
    , data = {
        client_id: this.clientId,
        client_secret: this.clientSecret,
        object: sub.type || IG_DEFAULT_SUBSRIPTION_TYPE,
        aspect: 'media',
        verify_token: verify_token,
        callback_url: this.subscriptionCallbackURL
      }
  ;

  switch( sub.type){
    case IG_OBJECT_TAG:
      data = _.extend(data,{
        object_id: sub.tag
      });
      break;

    case IG_OBJECT_LOCATION:
      data = _.extend(data,{
        object_id: sub.location
      });
      break;

    case IG_OBJECT_GEOGRAPHY:
      data = _.extend(data,{
        lat: sub.lat,
        lng: sub.lng,
        radius: sub.radius
      });
      break;
  };

  debug('Creating subscription with data %j', data);
  this._apiRequest( 'subscriptions', 'POST', data, function(err,res){
    cb&&cb(err,res);
  });
};

Instagram.prototype.unsubscribe = function(type){

  switch(type){
    case 'all':
    case 'tag':
    case 'location':
    case 'user':
    case 'geography':
      this._apiRequest( 'subscriptions', 'DELETE', {
        client_id:     this.clientId,
        client_secret: this.clientSecret,
        object: type
      }, function(){
        debug('%s subscription removed %s', type);
      });
    break;
    default:
      if( type&&type.length){

        var self = this;
        this.subscriptions( function(err,res){

          data = res.body.data;
          data = data instanceof Array ? data : [data];
          type = type instanceof Array ? type : [type];

          debug('Unsubscribing data %s',type);

          for(var i in data) {
            d = data[ i];
            if( d && type.indexOf(d.object_id) !== -1 ){
              self._apiRequest( 'subscriptions', 'DELETE', {
                client_id:     self.clientId,
                client_secret: self.clientSecret,
                id: d.id
              }, function(err,res){
                // console.log('unsubscribe instagram', err, d.object_id, res.body);
                debug('Request %s to unsubscribe responded',d.id);
              });
            }
          };
        });
      }

    break;
  }

};

Instagram.prototype.subscriptions = function(cb){
  this._apiRequest( 'subscriptions', 'GET', {
    client_id:     this.clientId,
    client_secret: this.clientSecret
  }, function(err,data){
    cb&&cb(err,data);
  });
};

Instagram.prototype._transform = function(chunk, encoding, done){

  var expected = 0
    , stream = this
    , obj = null
    , complete = _.after(chunk.length, function(){
      done();
    })
  ;
  for( var i in chunk){

    obj = chunk[i];
    switch( obj.object){
      case IG_OBJECT_TAG:
        this.getMediaByTag(chunk[i].object_id, function(err,res){
          var data = res.body.data;
          for( var j in data){
            if( stream.include(data[j])){
              stream.push(
                new Message(stream,data[j])
              );
            }
          }
          complete();
        });

        break;
      default:
        complete();
        break;
    }
  }

};

Instagram.prototype.include = function(data){
  var pass = true;
  this._filters.forEach( function(cb){
    if( !cb(data)){
      pass = false;
      return false;
    }
  });
  return pass;
};

Instagram.prototype.getMediaByTag = function(tag, cb){
  this._apiRequest( 'tags/' + tag + '/media/recent', 'GET', {
    client_id: this.clientId
  }, function(err,res){
    cb&&cb(err, res);
  });
};

Instagram.prototype.getFeed = function(token, cb){
  this._apiRequest( 'users/self/feed', 'GET', {
    access_token: token
  }, function(err,res){
    cb&&cb(err, res);
  });
};

Instagram.prototype.findMediaAtLocation = function(id){
  this._apiRequest( 'locations/' + id + '/media/recent', 'GET', {
  }, function(err,res){
    cb&&cb(err, res);
  });
};

Instagram.prototype.getLocations = function(lat, lng){
  this._apiRequest( 'locations/search', 'GET', {
    lat: '',
    lng: ''
  }, function(err,res){
    cb&&cb(err, res);
  });
};

Instagram.prototype.getMediaByLocation = function(id){
  this._apiRequest( 'locations/' + id + '/media/recent', 'GET', {
  }, function(err,res){
    cb&&cb(err, res);
  });
};

Instagram.prototype.getMediaByGeo = function(id){
  this._apiRequest( 'geographies/' + id + '/media/recent', 'GET', {
    client_id: this.clientId
  }, function(err,res){
    cb&&cb(err, res);
  });
};

Instagram.prototype._apiRequest = function(endpoint, method, data, cb){
  var url = IG_API_URL + endpoint;
  switch( method.toUpperCase()){

    case 'GET':

      request.get(url)
        .query(data)
        .end( function(err,res){
          cb&&cb(err,res);
        });
      break;

    case 'POST':

      request.post(url)
        .type('form')
        .send(data)
        .end( function(err,res){
          cb&&cb(err,res);
        });

      break;

    case 'DELETE':

      request.del(url)
        .query(data)
        .end( function(err,res){
          cb&&cb(err,res);
        });
      break;
  }

};

module.exports = Instagram;

redpajama_set_name: RedPajamaGithub


text:
namespace app {
namespace Fuse {
namespace Entities {
namespace Designer {

// This file was generated based on 'C:\ProgramData\Uno\Packages\Fuse.Entities\0.11.3\Designer\$.uno'.
// WARNING: Changes might be lost if you edit this file directly.

AnimationHelpers__uType* AnimationHelpers__typeof()
{
    static ::uStaticStrong<AnimationHelpers__uType*> type;
    if (type != NULL) return type;

    type = (AnimationHelpers__uType*)::uAllocClassType(sizeof(AnimationHelpers__uType), "Fuse.Entities.Designer.AnimationHelpers");

    type->SetFunctions(1,
        ::uNewFunction("Sample", AnimationHelpers__Sample, 0, true, ::app::Uno::Float__typeof(), ::uGetArrayType(::app::Uno::Double__typeof()), ::uGetArrayType(::app::Uno::Float__typeof()), ::uGetArrayType(::app::Uno::Float__typeof()), ::uGetArrayType(::app::Uno::Int__typeof()), ::uGetArrayType(::app::Uno::Float__typeof()), ::uGetArrayType(::app::Uno::Float__typeof()), ::app::Uno::Double__typeof()));

    ::uRegisterType(type);
    return type;
}

float AnimationHelpers__Sample(::uStatic* __this, ::uArray* times, ::uArray* leftValues, ::uArray* rightValues, ::uArray* easing, ::uArray* leftTangents, ::uArray* rightTangents, double time)
{
    if (::uPtr< ::uArray*>(times)->Length() == 0)
    {
        return 0.0f;
    }

    for (int i = 0; i < ::uPtr< ::uArray*>(times)->Length(); i++)
    {
        double kTime = ::uPtr< ::uArray*>(times)->Item< double>(i);

        if (time >= kTime)
        {
            if (i == (::uPtr< ::uArray*>(times)->Length() - 1))
            {
                return ::uPtr< ::uArray*>(rightValues)->Item< float>(i);
            }

            double k2time = ::uPtr< ::uArray*>(times)->Item< double>(i + 1);

            if (time < k2time)
            {
                float f = (float)((time - kTime) / (k2time - kTime));

                switch (::uPtr< ::uArray*>(easing)->Item< int>(i))
                {
                    case 1:
                    {
                        f = f * f;
                        break;
                    }
                    case 2:
                    {
                        f = 1.0f - ::app::Uno::Math__Pow_1(NULL, 1.0f - f, 2.0f);
                        break;
                    }
                    case 3:
                    {
                        float f2 = f * f;
                        float f3 = f2 * f;
                        float h1 = ((2.0f * f3) - (3.0f * f2)) + 1.0f;
                        float h2 = (-2.0f * f3) + (3.0f * f2);
                        float h3 = (f3 - (2.0f * f2)) + f;
                        float h4 = f3 - f2;
                        return (((::uPtr< ::uArray*>(rightValues)->Item< float>(i) * h1) + (::uPtr< ::uArray*>(leftValues)->Item< float>(i + 1) * h2)) + (::uPtr< ::uArray*>(rightTangents)->Item< float>(i) * h3)) + (::uPtr< ::uArray*>(leftTangents)->Item< float>(i + 1) * h4);
                    }
                }

                return (::uPtr< ::uArray*>(rightValues)->Item< float>(i) * (1.0f - f)) + (::uPtr< ::uArray*>(leftValues)->Item< float>(i + 1) * f);
            }
        }
        else if (i == 0)
        {
            return ::uPtr< ::uArray*>(leftValues)->Item< float>(i);
        }
    }

    return 0.0f;
}

// This file was generated based on 'C:\ProgramData\Uno\Packages\Fuse.Entities\0.11.3\Designer\$.uno'.
// WARNING: Changes might be lost if you edit this file directly.

::uStaticStrong< ::app::Uno::Collections::Dictionary__string__object*> PreloadedResources__resources;

PreloadedResources__uType* PreloadedResources__typeof()
{
    static ::uStaticStrong<PreloadedResources__uType*> type;
    if (type != NULL) return type;

    type = (PreloadedResources__uType*)::uAllocClassType(sizeof(PreloadedResources__uType), "Fuse.Entities.Designer.PreloadedResources");

    type->SetFields(1,
        ::uNewField("resources", &PreloadedResources__resources, 0, ::app::Uno::Collections::Dictionary__string__object__typeof()));

    type->SetFunctions(1,
        ::uNewFunction("Get", PreloadedResources__Get, 0, true, ::uObject__typeof(), ::app::Uno::String__typeof()));

    ::uRegisterType(type);
    return type;
}

void PreloadedResources___TypeInit(::uStatic* __this)
{
    PreloadedResources__resources = ::app::Uno::Collections::Dictionary__string__object__New_1(NULL);
}

::uObject* PreloadedResources__Get(::uStatic* __this, ::uString* descriptor)
{
    ::uObject* resource;

    if (::uPtr< ::app::Uno::Collections::Dictionary__string__object*>(PreloadedResources__resources)->TryGetValue(descriptor, &resource))
    {
        return resource;
    }

    return NULL;
}

}}}}


text:
// Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

package org.chromium.chrome.browser.tasks.tab_management;

import android.content.Context;
import android.graphics.drawable.Drawable;

import androidx.annotation.IntDef;
import androidx.annotation.VisibleForTesting;
import androidx.appcompat.content.res.AppCompatResources;

import org.chromium.base.metrics.RecordUserAction;
import org.chromium.chrome.browser.tab.Tab;
import org.chromium.chrome.tab_ui.R;

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.util.List;

/**
 * Select all and deselect all toggle action for the {@link TabSelectionEditorMenu}.
 */
public class TabSelectionEditorSelectionAction extends TabSelectionEditorAction {
    private Context mContext;
    private @ActionState int mActionState;
    private final Drawable mSelectAllIcon;
    private final Drawable mDeselectAllIcon;

    @IntDef({ActionState.UNKNOWN, ActionState.SELECT_ALL, ActionState.DESELECT_ALL})
    @Retention(RetentionPolicy.SOURCE)
    public @interface ActionState {
        int UNKNOWN = 0;
        int SELECT_ALL = 1;
        int DESELECT_ALL = 2;
    }

    /**
     * Create an action for closing tabs.
     * @param context to load drawable from.
     * @param showMode whether to show an action view.
     * @param buttonType the type of the action view.
     * @param iconPosition the position of the icon in the action view.
     * @param isIncognito whether the current tab model is incognito this will update dynamically.
     */
    public static TabSelectionEditorAction createAction(Context context, @ShowMode int showMode,
            @ButtonType int buttonType, @IconPosition int iconPosition) {
        Drawable selectAllIcon =
                AppCompatResources.getDrawable(context, R.drawable.ic_select_all_24dp);
        Drawable deselectAllIcon =
                AppCompatResources.getDrawable(context, R.drawable.ic_deselect_all_24dp);
        return new TabSelectionEditorSelectionAction(
                context, showMode, buttonType, iconPosition, selectAllIcon, deselectAllIcon);
    }

    @VisibleForTesting
    TabSelectionEditorSelectionAction(Context context, @ShowMode int showMode,
            @ButtonType int buttonType, @IconPosition int iconPosition, Drawable selectAllIcon,
            Drawable deselectAllIcon) {
        super(R.id.tab_selection_editor_selection_menu_item, showMode, buttonType, iconPosition,
                R.string.tab_selection_editor_select_all, null, selectAllIcon);

        mContext = context;
        mActionState = ActionState.UNKNOWN;
        mSelectAllIcon = selectAllIcon;
        mDeselectAllIcon = deselectAllIcon;
        getPropertyModel().set(TabSelectionEditorActionProperties.SHOULD_DISMISS_MENU, false);
        updateState(ActionState.SELECT_ALL);
    }

    @Override
    public boolean shouldNotifyObserversOfAction() {
        return false;
    }

    @Override
    public void onSelectionStateChange(List<Integer> tabIds) {
        setEnabledAndItemCount(true, tabIds.size());
        updateState(getActionDelegate().areAllTabsSelected() ? ActionState.DESELECT_ALL
                                                             : ActionState.SELECT_ALL);
    }

    @Override
    public boolean performAction(List<Tab> tabs) {
        if (mActionState == ActionState.SELECT_ALL) {
            getActionDelegate().selectAll();
            RecordUserAction.record("TabMultiSelectV2.SelectAll");
        } else if (mActionState == ActionState.DESELECT_ALL) {
            getActionDelegate().deselectAll();
            RecordUserAction.record("TabMultiSelectV2.DeselectAll");
        } else {
            assert false : "Invalid selection state";
        }
        return true;
    }

    @Override
    public boolean shouldHideEditorAfterAction() {
        return false;
    }

    private void updateState(@ActionState int selectionState) {
        if (mActionState == selectionState) return;

        mActionState = selectionState;

        if (mActionState == ActionState.SELECT_ALL) {
            getPropertyModel().set(TabSelectionEditorActionProperties.TITLE_RESOURCE_ID,
                    R.string.tab_selection_editor_select_all);
            getPropertyModel().set(TabSelectionEditorActionProperties.ICON, mSelectAllIcon);
        } else if (mActionState == ActionState.DESELECT_ALL) {
            getPropertyModel().set(TabSelectionEditorActionProperties.TITLE_RESOURCE_ID,
                    R.string.tab_selection_editor_deselect_all);
            getPropertyModel().set(TabSelectionEditorActionProperties.ICON, mDeselectAllIcon);
        } else {
            assert false : "Invalid selection state";
        }
    }
}


text:
{% extends "base.html" %}

{% block content %}
	{% for msg in get_flashed_messages() %}

{{ msg }}

	{% endfor %}

    <form action="/signup" method="post">

            Email address
            <input type="email" class="form-control" id="email" name="email" placeholder="Enter email">

            Password
            <input type="password" class="form-control" id="password" name="password" placeholder="Password">

            Confirm Password
            <input type="password" class="form-control" id="confirm_password" name="confirm_password" placeholder="Repeat Password">

            First Name
            <input type="text" class="form-control" id="first_name" name="first_name" placeholder="Enter First Name">

            Last Name
            <input type="text" class="form-control" id="last_name" name="last_name" placeholder="Enter Last Name">

        <button type="submit" class="btn btn-default">Submit</button>
    </form>

{% endblock %}


text:
@interface UIWindow (ECLaunch)

- (UIViewController *)ecl_visibleViewController;

@end


text:
<?php defined('SYSPATH') OR die('No direct script access.');

class Kohana_HTTP_Exception_405 extends HTTP_Exception_Expected {

	/**
	 * @var   integer    HTTP 405 Method Not Allowed
	 */
	protected $_code = 405;

	/**
	 * Specifies the list of allowed HTTP methods
	 *
	 * @param  array $methods List of allowed methods
	 */
	public function allowed($methods)
	{
		if (is_array($methods))
		{
			$methods = implode(',', $methods);
		}

		$this->headers('allow', $methods);

		return $this;
	}

	/**
	 * Validate this exception contains everything needed to continue.
	 *
	 * @throws Kohana_Exception
	 * @return bool
	 */
	public function check()
	{
		if ($location = $this->headers('allow') === NULL)
			throw new Kohana_Exception('A list of allowed methods must be specified');

		return TRUE;
	}

}


text:
using System;
using System.ComponentModel;

namespace Azure.ResourceManager.NetApp.Models
{
    /// <summary> Encryption type of the capacity pool, set encryption type for data at rest for this pool and all volumes in it. This value can only be set when creating new pool. </summary>
    public readonly partial struct CapacityPoolEncryptionType : IEquatable<CapacityPoolEncryptionType>
    {
        private readonly string _value;

        /// <summary> Initializes a new instance of <see cref="CapacityPoolEncryptionType"/>. </summary>
        /// <exception cref="ArgumentNullException"> <paramref name="value"/> is null. </exception>
        public CapacityPoolEncryptionType(string value)
        {
            _value = value ?? throw new ArgumentNullException(nameof(value));
        }

        private const string SingleValue = "Single";
        private const string DoubleValue = "Double";

        /// <summary> EncryptionType Single, volumes will use single encryption at rest. </summary>
        public static CapacityPoolEncryptionType Single { get; } = new CapacityPoolEncryptionType(SingleValue);
        /// <summary> EncryptionType Double, volumes will use double encryption at rest. </summary>
        public static CapacityPoolEncryptionType Double { get; } = new CapacityPoolEncryptionType(DoubleValue);
        /// <summary> Determines if two <see cref="CapacityPoolEncryptionType"/> values are the same. </summary>
        public static bool operator ==(CapacityPoolEncryptionType left, CapacityPoolEncryptionType right) => left.Equals(right);
        /// <summary> Determines if two <see cref="CapacityPoolEncryptionType"/> values are not the same. </summary>
        public static bool operator !=(CapacityPoolEncryptionType left, CapacityPoolEncryptionType right) => !left.Equals(right);
        /// <summary> Converts a string to a <see cref="CapacityPoolEncryptionType"/>. </summary>
        public static implicit operator CapacityPoolEncryptionType(string value) => new CapacityPoolEncryptionType(value);

        /// <inheritdoc />
        [EditorBrowsable(EditorBrowsableState.Never)]
        public override bool Equals(object obj) => obj is CapacityPoolEncryptionType other && Equals(other);
        /// <inheritdoc />
        public bool Equals(CapacityPoolEncryptionType other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase);

        /// <inheritdoc />
        [EditorBrowsable(EditorBrowsableState.Never)]
        public override int GetHashCode() => _value?.GetHashCode() ?? 0;
        /// <inheritdoc />
        public override string ToString() => _value;
    }
}


text:
<?xml version="1.0" ?>
<openerp>
    <data>
        <record model="ir.ui.view" id="res_partner_opt_out_form">
            <field name="name">res.partner.opt_out.form</field>
            <field name="model">res.partner</field>
            <field name="inherit_id" ref="base.view_partner_form"/>
            <field name="arch" type="xml">
                <xpath expr="//field[@name='active']" position="after">
                    <field name="opt_out"/>
                </xpath>
            </field>
        </record>

       <record model="ir.ui.view" id="res_partner_opt_out_search">
            <field name="name">res.partner.opt_out.search</field>
            <field name="model">res.partner</field>
            <field name="inherit_id" ref="base.view_res_partner_filter"/>
            <field name="arch" type="xml">
                    <filter string="Suppliers" position="after">
                        <separator />
                        <filter string="Available for mass mailing"
                                name='not_opt_out' domain="[('opt_out', '=', False)]"
                                help="Partners that did not ask not to be included in mass mailing campaigns" />
                    </filter>
            </field>
        </record>
    </data>
</openerp>


text:
package main.clrs.datastructures.elementarydatastructures;

/**
 * As an exercise of clrs 10.1.6
 * @author larry
 *
 * @param <T>
 */
public class StackOutOfQueues<T> implements Stack<T> {
	private Queue<T> qOne;
	private Queue<T> qTwo;

	public static enum FAVORS{
		FAVOR_PUSH, FAVOR_POP;
	}

	private FAVORS favorPushOrPop;

	public StackOutOfQueues(int capacity) {
		qOne = new PureArrayQueue<>(capacity);
		qTwo = new PureArrayQueue<>(capacity);
		favorPushOrPop = FAVORS.FAVOR_PUSH;
	}

	public StackOutOfQueues(){
		qOne = new PureArrayQueue<>();
		qTwo = new PureArrayQueue<>();
		favorPushOrPop = FAVORS.FAVOR_PUSH;
	}

	@Override
	public int size() {
		return qOne.size() + qTwo.size();
	}

	@Override
	public T pop() {
		if(favorPushOrPop == FAVORS.FAVOR_PUSH){
			return popElement_A();
		}else{
			return popElement_B();
		}
	}

	@Override
	public void push(T t) {
		if(favorPushOrPop == FAVORS.FAVOR_PUSH){
			pushElement_A(t);
		}else{
			pushElement_B(t);
		}

	}

	public StackOutOfQueues<T> setFavorPushOrPop(FAVORS favor){
		this.favorPushOrPop = favor;
		return this;
	}

	private T popElement_B(){
		if(isEmpty()){
			throw new IllegalStateException("No elements contained in the stack!!!");
		}
		if(qOne.isEmpty()){
			return qTwo.dequeue();
		}else{
			return qOne.dequeue();
		}
	}

	private void pushElement_B(T t){
		if(qOne.isEmpty() && qTwo.isEmpty()){
			qOne.enqueue(t);
		}else if(qOne.isEmpty()){
			swapInPlace();
		}

		qTwo.enqueue(t);
		while(!qOne.isEmpty()){
			qTwo.enqueue(qOne.dequeue());
		}
	}

	private void pushElement_A(T t){
		if(qOne.isEmpty()){
			qTwo.enqueue(t);
		}else{
			qOne.enqueue(t);
		}
	}

	private T popElement_A(){
		if(isEmpty()){
			throw new IllegalStateException("Stack empty, can not pop!!!");
		}

		if(qOne.isEmpty()){
			swapInPlace();
		}

		T r = qOne.dequeue();

		while(!qOne.isEmpty()){
			qTwo.enqueue(r);
			r = qOne.dequeue();
		}

		return r;
	}

	@Override
	public boolean isEmpty() {
		return size() == 0 ;
	}

	private void swapInPlace(){
		Queue<T> q;
		q = qOne;
		qOne = qTwo;
		qTwo = q;
	}

	public static void main(String args[]){
		StackOutOfQueues<Integer> s = new StackOutOfQueues<Integer>();
		s.setFavorPushOrPop(StackOutOfQueues.FAVORS.FAVOR_POP);
		for(int i = 0; i < 10; i++){
			s.push(i);
			assert s.size() == i + 1;
		}

		for (int i = 0; i < 10; i++){
			System.out.println(s.pop());
		}
	}

}


text:
**ACCEPTED** (being implemented)

This PEEP describes an addition that would allow configuring Pipenv options via environment variables suitable especially for automated systems or CI/CD systems.

☤

Systems running not only on containerized solutions (like Kubernetes or OpenShift) are often parametrized via environment variables. The aim of this PEEP is to provide an extension to the current Pipenv implementation that would simplify parametrizing options passed via environment variables.

The current implementation requires most of the options to be passed via command line. It is possible to adjust some of the command line options via pre-defined names of environment variables (such as ``PIPENV_PYTHON``) but this approach does not allow to define environment variables for all of the options that can be possibly passed to Pipenv.

The proposed approach is to re-use existing options passing via environment variables avaliable in [click](http://click.pocoo.org/5/options/#values-from-environment-variables>) (bundled with Pipenv). All of the options for available Pipenv's sub-commands can directly pick options passed via environment variables:

```console
$ export PIPENV_INSTALL_DEPLOY=1
$ export PIPENV_INSTALL_VERBOSE=1
$ pipenv install
```

The naming schema for environment variables configuring options is following:

```
PIPENV_<SUBCOMMAND>_<OPTION_NAME>
```

where sub-command is an uppercase name of Pipenv's sub-command (such as `install`, `run` or others) and option name is the name of Pipenv's sub-command option all in uppercase. Any dashes are translated to underscores; flags accept `1` signalizing the flag to be present.

The naming schema guarantees no clashes for the already existing Pipenv configuration using environment variables.

The proposed configuration via environment variables is available for Pipenv sub-commands. Options supplied via command line have higher priority than the ones supplied via environment variables.

Author: Fridolín Pokorný <fridolin.pokorny@gmail.com>


text:
package ru.salauyou.util.concurrent;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.locks.Lock;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import org.junit.Test;

import helpers.Helper;
import helpers.Model.Bank;
import helpers.Model.Payment;
import helpers.Model.Subj;
import helpers.Model.Subject;
import ru.salauyou.util.misc.StatsBuilder;

public class TestLockKeeperV2 {

    static final int PAYERS    = 1000;
    static final int RECEIVERS = 2000;
    static final int BANKS     = 50;
    static final int PAYMENTS  = 500000;
    static final int THREADS   = 10;

    @Test
    public void testLocks() {

        LockKeeperV2 lockKeeper = new LockKeeperV2(8, Bank.class, Subj.class, Payment.class);

        Random rnd = new Random();

        List<Bank> banks = Stream.generate(() -> Helper.generateBank(rnd)).limit(BANKS)
                .collect(Collectors.toList());
        List<Subject> payers = Stream.generate(() -> Helper.generateSubject(rnd, banks)).limit(PAYERS)
                .collect(Collectors.toList());
        List<Subject> receivers = Stream.generate(() -> Helper.generateSubject(rnd, banks)).limit(RECEIVERS)
                .collect(Collectors.toList());
        List<Payment> payments = Stream.generate(() -> Helper.generatePayment(rnd, payers, receivers)).limit(PAYMENTS)
                .collect(Collectors.toList());

        List<Future<Void>> tasks = new ArrayList<>();
        ExecutorService es = Executors.newFixedThreadPool(THREADS);

        for (int i = 0; i < 10; i++) {
            StatsBuilder<Integer> sb = new StatsBuilder<>();
            payments.forEach(p -> {
                tasks.add(es.submit(() -> {
                    long timeStart = System.nanoTime();
                    Lock lock = lockKeeper.lockAndGet(
                            LockKeeperV2.LockType.WRITE,
                            /*rnd.nextDouble() < (ii * 0.2d)
                                    ? LockKeeper.LockType.WRITE
                                    : LockKeeper.LockType.READ,*/
                            p,
                            p.getPayer(),
                            p.getReceiver(),
                            p.getPayer().getBank(),
                            p.getReceiver().getBank()
                            );
                    sb.put((int) ((System.nanoTime() - timeStart) / 1E6));
                    if (rnd.nextDouble() < 0.00001)
                        System.out.println("Locks acquired for: " + p);
//                    Thread.sleep(50);
                    lock.unlock();
                    return null;
                }));
            });

            long timeStart = System.currentTimeMillis();
            for (Future<Void> task : tasks) {
                try {
                    task.get();
                } catch (InterruptedException | ExecutionException e) {
                    e.printStackTrace();
                }
            }
            tasks.clear();

            double time = (System.currentTimeMillis() - timeStart) / 1000d;
            System.out.println(String.format("Executed in %s s.", time));
            System.out.println(sb.percentilesToString(new double[] { 0, 25, 50, 75, 85, 90, 95, 99, 100 }));
        }
        es.shutdownNow();
    }

}


text:
layout: post
title: Effective Modern C++ 小结
date: 2020-10-26 13:54
categories:
  - C++
typora-root-url: ../../layamon.github.io
---
* TOC
{:toc}
Most Vexing Parse

*everything that can be interpreted as a declaration, will be interpreted as a declaration"* rather than *"everything that can be interpreted as a declaration, will be interpreted as a declaration, unless it's a single variable definition, in which case it's a variable definition"*.

Coding style is ultimately subjective, and it is highly unlikely that substantial performance benefits will come from it. But here's what I would say that you gain from liberal use of uniform initialization:

## Minimizes Redundant Typenames

Consider the following:

```cpp
vec3 GetValue()
{
  return vec3(x, y, z);
}
```

Why do I need to type `vec3` twice? Is there a point to that? The compiler knows good and well what the function returns. Why can't I just say, "call the constructor of what I return with these values and return it?" With uniform initialization, I can:

```cpp
vec3 GetValue()
{
  return {x, y, z};
}
```

Everything works.

Even better is for function arguments. Consider this:

```cpp
void DoSomething(const std::string &str);

DoSomething("A string.");
```

That works without having to type a typename, because `std::string` knows how to build itself from a `const char*` implicitly. That's great. But what if that string came from, say RapidXML. Or a Lua string. That is, let's say I actually know the length of the string up front. The `std::string` constructor that takes a `const char*` will have to take the length of the string if I just pass a `const char*`.

There is an overload that takes a length explicitly though. But to use it, I'd have to do this: `DoSomething(std::string(strValue, strLen))`. Why have the extra typename in there? The compiler knows what the type is. Just like with `auto`, we can avoid having extra typenames:

```cpp
DoSomething({strValue, strLen});
```

It just works. No typenames, no fuss, nothing. The compiler does its job, the code is shorter, and everyone's happy.

Granted, there are arguments to be made that the first version (`DoSomething(std::string(strValue, strLen))`) is more legible. That is, it's obvious what's going on and who's doing what. That is true, to an extent; understanding the uniform initialization-based code requires looking at the function prototype. This is the same reason why some say you should never pass parameters by non-const reference: so that you can see at the call site if a value is being modified.

But the same could be said for `auto`; knowing what you get from `auto v = GetSomething();` requires looking at the definition of `GetSomething`. But that hasn't stopped `auto` from being used with near reckless abandon once you have access to it. Personally, I think it'll be fine once you get used to it. Especially with a good IDE.

## Never Get The Most Vexing Parse

Here's some code.

```cpp
class Bar;

void Func()
{
  int foo(Bar());
}
```

Pop quiz: what is `foo`? If you answered "a variable", you're wrong. It's actually the prototype of a function that takes as its parameter a function that returns a `Bar`, and the `foo` function's return value is an int.

This is called C++'s "Most Vexing Parse" because it makes absolutely no sense to a human being. But the rules of C++ sadly require this: if it can possibly be interpreted as a function prototype, then it *will* be. The problem is `Bar()`; that could be one of two things. It could be a type named `Bar`, which means that it is creating a temporary. Or it could be a function that takes no parameters and returns a `Bar`.

Uniform initialization cannot be interpreted as a function prototype:

```cpp
class Bar;

void Func()
{
  int foo{Bar{}};
}
```

`Bar{}` always creates a temporary. `int foo{...}` always creates a variable.

There are many cases where you want to use `Typename()` but simply can't because of C++'s parsing rules. With `Typename{}`, there is no ambiguity.

注意区分 std::vector<int> v{100};

https://softwareengineering.stackexchange.com/questions/133688/is-c11-uniform-initialization-a-replacement-for-the-old-style-syntax


text:
class DropDaysTable < ActiveRecord::Migration
  def up
    drop_table :days
  end

  def down
    create_table "days", force: :cascade do |t|
      t.integer  "work_id",    limit: 4,             null: false
      t.integer  "source_id",  limit: 4,             null: false
      t.integer  "event_id",   limit: 4,             null: false
      t.integer  "year",       limit: 4,             null: false
      t.integer  "month",      limit: 4,             null: false
      t.integer  "day",        limit: 4,             null: false
      t.integer  "total",      limit: 4, default: 0, null: false
      t.integer  "html",       limit: 4, default: 0, null: false
      t.integer  "pdf",        limit: 4, default: 0, null: false
      t.integer  "comments",   limit: 4, default: 0, null: false
      t.integer  "likes",      limit: 4, default: 0, null: false
      t.datetime "created_at",                       null: false
      t.datetime "updated_at",                       null: false
      t.integer  "readers",    limit: 4, default: 0, null: false
    end

    add_index "days", ["event_id", "year", "month", "day"], name: "index_days_on_event_id_and_year_and_month_and_day"
    add_index "days", ["source_id"], name: "days_source_id_fk", using: :btree
    add_index "days", ["work_id", "source_id", "year", "month"], name: "index_days_on_work_id_and_source_id_and_year_and_month"

    add_foreign_key "days", "events", name: "days_event_id_fk", on_delete: :cascade
    add_foreign_key "days", "sources", name: "days_source_id_fk", on_delete: :cascade
    add_foreign_key "days", "works", name: "days_work_id_fk", on_delete: :cascade
  end
end


text:
.class public Lcom/htc/preference/HtcVolumePreference;
.super Lcom/htc/preference/HtcSeekBarDialogPreference;
.source "HtcVolumePreference.java"

# interfaces
.implements Lcom/htc/preference/HtcPreferenceManager$OnActivityStopListener;
.implements Landroid/view/View$OnKeyListener;

# annotations
.annotation system Ldalvik/annotation/MemberClasses;
    value = {
        Lcom/htc/preference/HtcVolumePreference$1;,
        Lcom/htc/preference/HtcVolumePreference$SeekBarVolumizer;,
        Lcom/htc/preference/HtcVolumePreference$SavedState;,
        Lcom/htc/preference/HtcVolumePreference$VolumeStore;
    }
.end annotation

# static fields
.field private static LOGD:Z = false

.field private static final TAG:Ljava/lang/String; = "VolumePreference"

# instance fields
.field private mSeekBarVolumizer:Lcom/htc/preference/HtcVolumePreference$SeekBarVolumizer;

.field private mStreamType:I

.field private mVoiceCapable:Z

# direct methods
.method static constructor <clinit>()V
    .locals 1

    .prologue
    .line 71
    const/4 v0, 0x0

    sput-boolean v0, Lcom/htc/preference/HtcVolumePreference;->LOGD:Z

    return-void
.end method

.method public constructor <init>(Landroid/content/Context;Landroid/util/AttributeSet;)V
    .locals 3
    .parameter "context"
    .parameter "attrs"

    .prologue
    const/4 v2, 0x0

    .line 80
    invoke-direct {p0, p1, p2}, Lcom/htc/preference/HtcSeekBarDialogPreference;-><init>(Landroid/content/Context;Landroid/util/AttributeSet;)V

    .line 82
    sget-object v1, Lcom/android/internal/R$styleable;->VolumePreference:[I

    invoke-virtual {p1, p2, v1, v2, v2}, Landroid/content/Context;->obtainStyledAttributes(Landroid/util/AttributeSet;[III)Landroid/content/res/TypedArray;

    move-result-object v0

    .line 84
    .local v0, a:Landroid/content/res/TypedArray;
    invoke-virtual {v0, v2, v2}, Landroid/content/res/TypedArray;->getInt(II)I

    move-result v1

    iput v1, p0, Lcom/htc/preference/HtcVolumePreference;->mStreamType:I

    .line 85
    invoke-virtual {v0}, Landroid/content/res/TypedArray;->recycle()V

    .line 86
    invoke-virtual {p1}, Landroid/content/Context;->getResources()Landroid/content/res/Resources;

    move-result-object v1

    const v2, 0x1110023

    invoke-virtual {v1, v2}, Landroid/content/res/Resources;->getBoolean(I)Z

    move-result v1

    iput-boolean v1, p0, Lcom/htc/preference/HtcVolumePreference;->mVoiceCapable:Z

    .line 88
    return-void
.end method

.method static synthetic access$1000()Z
    .locals 1

    .prologue
    .line 67
    sget-boolean v0, Lcom/htc/preference/HtcVolumePreference;->LOGD:Z

    return v0
.end method

.method static synthetic access$1300(Lcom/htc/preference/HtcVolumePreference;)Z
    .locals 1
    .parameter "x0"

    .prologue
    .line 67
    iget-boolean v0, p0, Lcom/htc/preference/HtcVolumePreference;->mVoiceCapable:Z

    return v0
.end method

.method private cleanup()V
    .locals 5

    .prologue
    const/4 v4, 0x0

    .line 157
    invoke-virtual {p0}, Lcom/htc/preference/HtcVolumePreference;->getPreferenceManager()Lcom/htc/preference/HtcPreferenceManager;

    move-result-object v2

    invoke-virtual {v2, p0}, Lcom/htc/preference/HtcPreferenceManager;->unregisterOnActivityStopListener(Lcom/htc/preference/HtcPreferenceManager$OnActivityStopListener;)V

    .line 159
    iget-object v2, p0, Lcom/htc/preference/HtcVolumePreference;->mSeekBarVolumizer:Lcom/htc/preference/HtcVolumePreference$SeekBarVolumizer;

    if-eqz v2, :cond_2

    .line 160
    invoke-virtual {p0}, Lcom/htc/preference/HtcVolumePreference;->getDialog()Landroid/app/Dialog;

    move-result-object v0

    .line 161
    .local v0, dialog:Landroid/app/Dialog;
    if-eqz v0, :cond_1

    invoke-virtual {v0}, Landroid/app/Dialog;->isShowing()Z

    move-result v2

    if-eqz v2, :cond_1

    .line 162
    invoke-virtual {v0}, Landroid/app/Dialog;->getWindow()Landroid/view/Window;

    move-result-object v2

    invoke-virtual {v2}, Landroid/view/Window;->getDecorView()Landroid/view/View;

    move-result-object v2

    const v3, 0x10202d9

    invoke-virtual {v2, v3}, Landroid/view/View;->findViewById(I)Landroid/view/View;

    move-result-object v1

    .line 164
    .local v1, view:Landroid/view/View;
    if-eqz v1, :cond_0

    invoke-virtual {v1, v4}, Landroid/view/View;->setOnKeyListener(Landroid/view/View$OnKeyListener;)V

    .line 166
    :cond_0
    iget-object v2, p0, Lcom/htc/preference/HtcVolumePreference;->mSeekBarVolumizer:Lcom/htc/preference/HtcVolumePreference$SeekBarVolumizer;

    invoke-virtual {v2}, Lcom/htc/preference/HtcVolumePreference$SeekBarVolumizer;->revertVolume()V

    .line 168
    .end local v1           #view:Landroid/view/View;
    :cond_1
    iget-object v2, p0, Lcom/htc/preference/HtcVolumePreference;->mSeekBarVolumizer:Lcom/htc/preference/HtcVolumePreference$SeekBarVolumizer;

    invoke-virtual {v2}, Lcom/htc/preference/HtcVolumePreference$SeekBarVolumizer;->stop()V

    .line 169
    iput-object v4, p0, Lcom/htc/preference/HtcVolumePreference;->mSeekBarVolumizer:Lcom/htc/preference/HtcVolumePreference$SeekBarVolumizer;

    .line 172
    .end local v0           #dialog:Landroid/app/Dialog;
    :cond_2
    return-void
.end method

# virtual methods
.method public onActivityStop()V
    .locals 0

    .prologue
    .line 147
    invoke-direct {p0}, Lcom/htc/preference/HtcVolumePreference;->cleanup()V

    .line 149
    return-void
.end method

.method protected onBindDialogView(Landroid/view/View;)V
    .locals 4
    .parameter "view"

    .prologue
    .line 96
    invoke-super {p0, p1}, Lcom/htc/preference/HtcSeekBarDialogPreference;->onBindDialogView(Landroid/view/View;)V

    .line 97
    const v1, 0x10202d9

    invoke-virtual {p1, v1}, Landroid/view/View;->findViewById(I)Landroid/view/View;

    move-result-object v0

    check-cast v0, Landroid/widget/SeekBar;

    .line 98
    .local v0, seekBar:Landroid/widget/SeekBar;
    if-eqz v0, :cond_0

    .line 99
    new-instance v1, Lcom/htc/preference/HtcVolumePreference$SeekBarVolumizer;

    invoke-virtual {p0}, Lcom/htc/preference/HtcVolumePreference;->getContext()Landroid/content/Context;

    move-result-object v2

    iget v3, p0, Lcom/htc/preference/HtcVolumePreference;->mStreamType:I

    invoke-direct {v1, p0, v2, v0, v3}, Lcom/htc/preference/HtcVolumePreference$SeekBarVolumizer;-><init>(Lcom/htc/preference/HtcVolumePreference;Landroid/content/Context;Landroid/widget/SeekBar;I)V

    iput-object v1, p0, Lcom/htc/preference/HtcVolumePreference;->mSeekBarVolumizer:Lcom/htc/preference/HtcVolumePreference$SeekBarVolumizer;

    .line 101
    :cond_0
    invoke-virtual {p0}, Lcom/htc/preference/HtcVolumePreference;->getPreferenceManager()Lcom/htc/preference/HtcPreferenceManager;

    move-result-object v1

    invoke-virtual {v1, p0}, Lcom/htc/preference/HtcPreferenceManager;->registerOnActivityStopListener(Lcom/htc/preference/HtcPreferenceManager$OnActivityStopListener;)V

    .line 105
    invoke-virtual {p1, p0}, Landroid/view/View;->setOnKeyListener(Landroid/view/View$OnKeyListener;)V

    .line 106
    const/4 v1, 0x1

    invoke-virtual {p1, v1}, Landroid/view/View;->setFocusableInTouchMode(Z)V

    .line 108
    if-eqz v0, :cond_1

    invoke-virtual {v0}, Landroid/widget/SeekBar;->requestFocus()Z

    .line 109
    :cond_1
    return-void
.end method

.method protected onDialogClosed(Z)V
    .locals 1
    .parameter "positiveResult"

    .prologue
    .line 138
    invoke-super {p0, p1}, Lcom/htc/preference/HtcSeekBarDialogPreference;->onDialogClosed(Z)V

    .line 139
    if-nez p1, :cond_0

    iget-object v0, p0, Lcom/htc/preference/HtcVolumePreference;->mSeekBarVolumizer:Lcom/htc/preference/HtcVolumePreference$SeekBarVolumizer;

    if-eqz v0, :cond_0

    .line 140
    iget-object v0, p0, Lcom/htc/preference/HtcVolumePreference;->mSeekBarVolumizer:Lcom/htc/preference/HtcVolumePreference$SeekBarVolumizer;

    invoke-virtual {v0}, Lcom/htc/preference/HtcVolumePreference$SeekBarVolumizer;->revertVolume()V

    .line 143
    :cond_0
    invoke-direct {p0}, Lcom/htc/preference/HtcVolumePreference;->cleanup()V

    .line 144
    return-void
.end method

.method public onKey(Landroid/view/View;ILandroid/view/KeyEvent;)Z
    .locals 4
    .parameter "v"
    .parameter "keyCode"
    .parameter "event"

    .prologue
    const/4 v2, 0x0

    const/4 v1, 0x1

    .line 113
    iget-object v3, p0, Lcom/htc/preference/HtcVolumePreference;->mSeekBarVolumizer:Lcom/htc/preference/HtcVolumePreference$SeekBarVolumizer;

    if-nez v3, :cond_1

    .line 132
    :cond_0
    :goto_0
    return v1

    .line 114
    :cond_1
    invoke-virtual {p3}, Landroid/view/KeyEvent;->getAction()I

    move-result v3

    if-nez v3, :cond_2

    move v0, v1

    .line 115
    .local v0, isdown:Z
    :goto_1
    sparse-switch p2, :sswitch_data_0

    move v1, v2

    .line 132
    goto :goto_0

    .end local v0           #isdown:Z
    :cond_2
    move v0, v2

    .line 114
    goto :goto_1

    .line 117
    .restart local v0       #isdown:Z
    :sswitch_0
    if-eqz v0, :cond_0

    .line 118
    iget-object v2, p0, Lcom/htc/preference/HtcVolumePreference;->mSeekBarVolumizer:Lcom/htc/preference/HtcVolumePreference$SeekBarVolumizer;

    const/4 v3, -0x1

    invoke-virtual {v2, v3}, Lcom/htc/preference/HtcVolumePreference$SeekBarVolumizer;->changeVolumeBy(I)V

    goto :goto_0

    .line 122
    :sswitch_1
    if-eqz v0, :cond_0

    .line 123
    iget-object v2, p0, Lcom/htc/preference/HtcVolumePreference;->mSeekBarVolumizer:Lcom/htc/preference/HtcVolumePreference$SeekBarVolumizer;

    invoke-virtual {v2, v1}, Lcom/htc/preference/HtcVolumePreference$SeekBarVolumizer;->changeVolumeBy(I)V

    goto :goto_0

    .line 127
    :sswitch_2
    if-eqz v0, :cond_0

    .line 128
    iget-object v2, p0, Lcom/htc/preference/HtcVolumePreference;->mSeekBarVolumizer:Lcom/htc/preference/HtcVolumePreference$SeekBarVolumizer;

    invoke-virtual {v2}, Lcom/htc/preference/HtcVolumePreference$SeekBarVolumizer;->muteVolume()V

    goto :goto_0

    .line 115
    :sswitch_data_0
    .sparse-switch
        0x18 -> :sswitch_1
        0x19 -> :sswitch_0
        0xa4 -> :sswitch_2
    .end sparse-switch
.end method

.method protected onRestoreInstanceState(Landroid/os/Parcelable;)V
    .locals 3
    .parameter "state"

    .prologue
    .line 202
    sget-boolean v1, Lcom/htc/preference/HtcVolumePreference;->LOGD:Z

    if-eqz v1, :cond_0

    .line 203
    const-string v1, "VolumePreference"

    const-string v2, "onRestoreInstanceState"

    invoke-static {v1, v2}, Landroid/util/Log;->d(Ljava/lang/String;Ljava/lang/String;)I

    .line 205
    :cond_0
    if-eqz p1, :cond_1

    invoke-virtual {p1}, Ljava/lang/Object;->getClass()Ljava/lang/Class;

    move-result-object v1

    const-class v2, Lcom/htc/preference/HtcVolumePreference$SavedState;

    invoke-virtual {v1, v2}, Ljava/lang/Object;->equals(Ljava/lang/Object;)Z

    move-result v1

    if-nez v1, :cond_3

    .line 207
    :cond_1
    invoke-super {p0, p1}, Lcom/htc/preference/HtcSeekBarDialogPreference;->onRestoreInstanceState(Landroid/os/Parcelable;)V

    .line 218
    :cond_2
    :goto_0
    return-void

    :cond_3
    move-object v0, p1

    .line 211
    check-cast v0, Lcom/htc/preference/HtcVolumePreference$SavedState;

    .line 212
    .local v0, myState:Lcom/htc/preference/HtcVolumePreference$SavedState;
    invoke-virtual {v0}, Lcom/htc/preference/HtcVolumePreference$SavedState;->getSuperState()Landroid/os/Parcelable;

    move-result-object v1

    invoke-super {p0, v1}, Lcom/htc/preference/HtcSeekBarDialogPreference;->onRestoreInstanceState(Landroid/os/Parcelable;)V

    .line 214
    iget-object v1, p0, Lcom/htc/preference/HtcVolumePreference;->mSeekBarVolumizer:Lcom/htc/preference/HtcVolumePreference$SeekBarVolumizer;

    if-eqz v1, :cond_2

    .line 215
    iget-object v1, p0, Lcom/htc/preference/HtcVolumePreference;->mSeekBarVolumizer:Lcom/htc/preference/HtcVolumePreference$SeekBarVolumizer;

    invoke-virtual {v0}, Lcom/htc/preference/HtcVolumePreference$SavedState;->getVolumeStore()Lcom/htc/preference/HtcVolumePreference$VolumeStore;

    move-result-object v2

    invoke-virtual {v1, v2}, Lcom/htc/preference/HtcVolumePreference$SeekBarVolumizer;->onRestoreInstanceState(Lcom/htc/preference/HtcVolumePreference$VolumeStore;)V

    goto :goto_0
.end method

.method protected onSampleStarting(Lcom/htc/preference/HtcVolumePreference$SeekBarVolumizer;)V
    .locals 1
    .parameter "volumizer"

    .prologue
    .line 175
    iget-object v0, p0, Lcom/htc/preference/HtcVolumePreference;->mSeekBarVolumizer:Lcom/htc/preference/HtcVolumePreference$SeekBarVolumizer;

    if-eqz v0, :cond_0

    iget-object v0, p0, Lcom/htc/preference/HtcVolumePreference;->mSeekBarVolumizer:Lcom/htc/preference/HtcVolumePreference$SeekBarVolumizer;

    if-eq p1, v0, :cond_0

    .line 176
    iget-object v0, p0, Lcom/htc/preference/HtcVolumePreference;->mSeekBarVolumizer:Lcom/htc/preference/HtcVolumePreference$SeekBarVolumizer;

    invoke-virtual {v0}, Lcom/htc/preference/HtcVolumePreference$SeekBarVolumizer;->stopSample()V

    .line 178
    :cond_0
    return-void
.end method

.method protected onSaveInstanceState()Landroid/os/Parcelable;
    .locals 4

    .prologue
    .line 182
    sget-boolean v2, Lcom/htc/preference/HtcVolumePreference;->LOGD:Z

    if-eqz v2, :cond_0

    .line 183
    const-string v2, "VolumePreference"

    const-string v3, "onSaveInstanceState"

    invoke-static {v2, v3}, Landroid/util/Log;->d(Ljava/lang/String;Ljava/lang/String;)I

    .line 185
    :cond_0
    invoke-super {p0}, Lcom/htc/preference/HtcSeekBarDialogPreference;->onSaveInstanceState()Landroid/os/Parcelable;

    move-result-object v1

    .line 186
    .local v1, superState:Landroid/os/Parcelable;
    invoke-virtual {p0}, Lcom/htc/preference/HtcVolumePreference;->isPersistent()Z

    move-result v2

    if-eqz v2, :cond_1

    .line 197
    .end local v1           #superState:Landroid/os/Parcelable;
    :goto_0
    return-object v1

    .line 191
    .restart local v1       #superState:Landroid/os/Parcelable;
    :cond_1
    new-instance v0, Lcom/htc/preference/HtcVolumePreference$SavedState;

    invoke-direct {v0, v1}, Lcom/htc/preference/HtcVolumePreference$SavedState;-><init>(Landroid/os/Parcelable;)V

    .line 193
    .local v0, myState:Lcom/htc/preference/HtcVolumePreference$SavedState;
    iget-object v2, p0, Lcom/htc/preference/HtcVolumePreference;->mSeekBarVolumizer:Lcom/htc/preference/HtcVolumePreference$SeekBarVolumizer;

    if-eqz v2, :cond_2

    .line 194
    iget-object v2, p0, Lcom/htc/preference/HtcVolumePreference;->mSeekBarVolumizer:Lcom/htc/preference/HtcVolumePreference$SeekBarVolumizer;

    invoke-virtual {v0}, Lcom/htc/preference/HtcVolumePreference$SavedState;->getVolumeStore()Lcom/htc/preference/HtcVolumePreference$VolumeStore;

    move-result-object v3

    invoke-virtual {v2, v3}, Lcom/htc/preference/HtcVolumePreference$SeekBarVolumizer;->onSaveInstanceState(Lcom/htc/preference/HtcVolumePreference$VolumeStore;)V

    :cond_2
    move-object v1, v0

    .line 197
    goto :goto_0
.end method

.method public setStreamType(I)V
    .locals 0
    .parameter "streamType"

    .prologue
    .line 91
    iput p1, p0, Lcom/htc/preference/HtcVolumePreference;->mStreamType:I

    .line 92
    return-void
.end method