function run_opp_compute_delta_atti($task, $args, $options)
{
    static $loaded;
    // load application context
    if (!$loaded) {
        task_loader();
        $loaded = true;
    }
    $data = '';
    $dry_run = false;
    if (array_key_exists('data', $options)) {
        $data = $options['data'];
    }
    if (array_key_exists('dry-run', $options)) {
        $dry_run = true;
    }
    // definisce la data fino alla quale vanno fatti i calcoli
    // data_lookup serve per controllare se i record già esistono
    if ($data != '') {
        $data_lookup = $data;
    } else {
        $data_lookup = OppActHistoryCachePeer::fetchLastData();
    }
    $msg = sprintf("start time: %s\n", date('H:i:s'));
    echo $msg;
    // calcolo date fine mese scorso e precedente
    list($last_month_start, $last_month_end) = Util::getLastMonthDates($data_lookup);
    // calcolo delta per dati di presenza, indice e ribellioni
    $rs = OppActHistoryCachePeer::getRSByData($data_lookup);
    $cnt = 0;
    while ($rs->next()) {
        $cnt++;
        $r = $rs->getRow();
        printf("%6d) %1s %7d ... ", $cnt, $r['chi_tipo'], $r['chi_id']);
        // estrazione record storico del mese scorso
        $r_1 = OppActHistoryCachePeer::retrieveByDataChiTipoChiId($last_month_end, $r['chi_tipo'], $r['chi_id']);
        // salta record per cui non c'è abbastanza storia
        if (!$r_1 instanceof OppActHistoryCache) {
            printf(" NA \n");
            continue;
        }
        $rilevanza_delta = indiceDelta($data_lookup, $r, $r_1);
        printf("d_rilevanza: %7.2f,  ", $rilevanza_delta);
        if (!$dry_run) {
            $r = OppActHistoryCachePeer::retrieveByDataChiTipoChiId($data_lookup, $r['chi_tipo'], $r['chi_id']);
            $r->setIndiceDelta($rilevanza_delta);
            $r->save();
            printf(" OK!\n");
        } else {
            printf("\n");
        }
    }
    echo "data: {$data_lookup}\n";
    $msg = sprintf("end time: %s\n", date('H:i:s'));
    echo $msg;
}
 protected function impactFactorCSV($ramo)
 {
     sfLoader::loadHelpers(array('Number'));
     $this->opp_user = OppUserPeer::retrieveByPK($this->getUser()->getId());
     $this->forward404Unless($this->getUser()->hasCredential('adhoc'));
     // get user's monitored tags
     $this->tags_ids = $this->opp_user->getMonitoredPks('Tag');
     $limit = sfConfig::get('app_limit_classifica_parlamentari_sioccupanodi', 15);
     $data_inizio = OppLegislaturaPeer::$legislature[OppLegislaturaPeer::getCurrent()]['data_inizio'];
     $data_fine = OppActHistoryCachePeer::fetchLastData();
     $date = array_reverse(Util::buildCacheDatesArray($data_inizio, $data_fine));
     $politici_csv = array();
     if (count($this->tags_ids)) {
         $this->group_filter = $this->getRequestParameter('group_filter');
         if (is_array($this->group_filter)) {
             $c = new Criteria();
             $c->add(OppGruppoPeer::ID, $this->group_filter, Criteria::IN);
         } else {
             $this->group_filter = array();
         }
         // estrazione classifica dei politici che più si interessano degli argomenti monitorati
         $politici = OppCaricaPeer::getClassificaPoliticiSiOccupanoDiArgomenti($this->tags_ids, $ramo, $data_fine, $limit, $this->group_filter);
         // costruzione delle serie storiche per ogni politico (da inizio legislatura)
         foreach ($politici as $carica_id => $politico) {
             // genero il label
             $label = sprintf("%s %s (%s)", $politico['nome'], $politico['cognome'], $politico['acronimo']);
             // arrotonda l'array dei valori storici a due cifre decimali (max)
             $storico = OppCaricaPeer::getStoricoInteressePoliticoArgomenti($carica_id, $this->tags_ids);
             // calcola la posizione del politico
             $posizione = OppCaricaPeer::getPosizionePoliticoOggettiVotatiPerArgomenti($carica_id, $this->tags_ids, $this->getUser()->getId());
             $posizione = format_number(round($posizione, 2), 'it_IT');
             // primi campi (dati fissi)
             $csv_row = "{$carica_id},\"{$label}\",\"{$posizione}\",";
             foreach ($date as $cnt => $data) {
                 if (array_key_exists($data, $storico)) {
                     $storico[$data] = format_number(round($storico[$data], 2), 'it_IT');
                 } else {
                     $storico[$data] = 0;
                 }
                 $csv_row .= '"' . $storico[$data] . '"';
                 if ($cnt < count($date) - 1) {
                     $csv_row .= ",";
                 }
             }
             $politici_csv[] = $csv_row;
         }
     }
     $this->date_csv = "carica_id,politico,posizione," . implode(",", $date);
     $this->politici_csv = $politici_csv;
     $this->setLayout(false);
     $this->setTemplate('impactFactorCSV');
     $this->response->setContentType('text/csv');
 }
 protected function addListSortCriteriaAtti($c)
 {
     if ($sort_column = $this->session->getAttribute('sort', 'indice', 'sf_admin/opp_storici/sort')) {
         if (!in_array($sort_column, array('presenze', 'assenze', 'missioni'))) {
             $sort_column = OppActHistoryCachePeer::translateFieldName($sort_column, BasePeer::TYPE_FIELDNAME, BasePeer::TYPE_COLNAME);
             if ($this->session->getAttribute('type', null, 'sf_admin/opp_storici/sort') == 'asc') {
                 $c->addAscendingOrderByColumn($sort_column);
             } else {
                 $c->addDescendingOrderByColumn($sort_column);
             }
         }
     }
 }
 /**
  * calcola l'indice di rilevanza accumulato fino a una certa data, per un tag
  * come somma degli indici di rilevanza di tutti gli atti taggati con quel tag 
  *
  * @param integer $tag_id
  * @param date $data 
  * @param SimpleXMLElement    $xml_node   
  * @param boolean   $verbose
  * @return float
  * @author Guglielmo Celata
  */
 public static function calcolaRilevanzaTag($tag_id, $data, $xml_node, $verbose = false)
 {
     $tag_node = $xml_node->addChild('tag', null, self::$opp_ns);
     // estrazione array atti taggati con un tag
     $atti_ids = TaggingPeer::getTaggableIds($tag_id, 'OppAtto');
     if ($verbose) {
         printf("tag: %10s\n", $tag_id);
     }
     $tag_node->addAttribute('id', $tag_id);
     $tag_node->addAttribute('n_atti', count($atti_ids));
     $punteggio = 0.0;
     // --- estrazione rilevanza singoli atti ---
     foreach ($atti_ids as $cnt => $atto_id) {
         $punteggio += $d_punteggio = OppActHistoryCachePeer::getIndiceForAttoData($atto_id, $data);
         $atto_node = $tag_node->addChild('atto', null, self::$opp_ns);
         $atto_node->addAttribute('totale', $d_punteggio);
         $atto_node->addAttribute('atto_id', $atto_id);
         if ($verbose) {
             printf("atto: %10s totale: %7.2f\n", $atto_id, $d_punteggio);
         }
     }
     $tag_node->addAttribute('totale', $punteggio);
     return $punteggio;
 }
 public function executeListClassificaActionAid()
 {
     $this->ramo = $this->getRequestParameter('ramo');
     $this->argomentis = array('aiuti umanitari' => 6729, 'cooperazione allo sviluppo' => 4653);
     $this->forward404Unless(in_array($this->ramo, array('C', 'S')));
     if ($this->ramo == 'C') {
         $this->tipo_politici = 'dep';
     } else {
         $this->tipo_politici = 'sen';
     }
     if ($this->hasRequestParameter('limit')) {
         $limit = $this->getRequestParameter('limit');
     }
     // la data è passata come parametro o viene estratta l'ultima nella cache (per dati di tipo 'A', singoli atti)
     if ($this->hasRequestParameter('data')) {
         $data = $this->getRequestParameter('data');
     } else {
         $data = OppActHistoryCachePeer::fetchLastData();
     }
     $this->politici = OppCaricaPeer::getClassificaPoliticiSiOccupanoDiArgomenti(array_values($this->argomentis), $this->ramo, $data);
 }
/**
 * Calcola o ri-calcola la rilevanza degli atti
 * Si può specificare il una data fino alla quale calcolare la rilevanza
 * Se sono passati degli ID (argomenti), sono interpretati come ID di atti e il calcolo è fatto solo per loro
 */
function run_opp_calcola_rilevanza_atti($task, $args, $options)
{
    static $loaded;
    // load application context
    if (!$loaded) {
        define('SF_ROOT_DIR', sfConfig::get('sf_root_dir'));
        define('SF_APP', 'fe');
        define('SF_ENVIRONMENT', 'task');
        define('SF_DEBUG', false);
        require_once SF_ROOT_DIR . DIRECTORY_SEPARATOR . 'apps' . DIRECTORY_SEPARATOR . SF_APP . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'config.php';
        sfContext::getInstance();
        sfConfig::set('pake', true);
        error_reporting(E_ALL);
        $loaded = true;
    }
    echo "memory usage: " . memory_get_usage() . "\n";
    $data = '';
    $verbose = false;
    $offset = null;
    $limit = null;
    if (array_key_exists('data', $options)) {
        $data = $options['data'];
    }
    if (array_key_exists('verbose', $options)) {
        $verbose = true;
    }
    if (array_key_exists('offset', $options)) {
        $offset = $options['offset'];
    }
    if (array_key_exists('limit', $options)) {
        $limit = $options['limit'];
    }
    if ($data != '') {
        $legislatura_corrente = OppLegislaturaPeer::getCurrent($data);
        $data_lookup = $data;
    } else {
        $legislatura_corrente = OppLegislaturaPeer::getCurrent();
        $data = date('Y-m-d');
        $data_lookup = OppActHistoryCachePeer::fetchLastData();
    }
    $msg = sprintf("calcolo rilevanza - fino a: %10s\n", $data);
    echo pakeColor::colorize($msg, array('fg' => 'cyan', 'bold' => true));
    $start_time = time();
    if (count($args) > 0) {
        try {
            $atti_rs = OppAttoPeer::getRSFromIDArray($args);
        } catch (Exception $e) {
            throw new Exception("Specificare degli ID validi. \n" . $e);
        }
    } else {
        $atti_rs = OppAttoPeer::getAttiDataRS($data, $offset, $limit);
    }
    $n_atti = $atti_rs->getRecordCount();
    echo "memory usage: " . memory_get_usage() . "\n";
    $cnt = 0;
    while ($atti_rs->next()) {
        $a = $atti_rs->getRow();
        $atto_id = $a['id'];
        $tipo_atto_id = $a['tipo_atto_id'];
        $atto = OppAttoPeer::retrieveByPK($atto_id);
        $priorita = is_null($atto->getPriorityValue()) ? 1 : $atto->getPriorityValue();
        $cnt++;
        if (!array_key_exists($tipo_atto_id, OppTipoAttoPeer::$tipi_per_indice)) {
            continue;
        }
        printf("%5d/%6d) %40s %d ... ", $cnt, $n_atti, OppTipoAttoPeer::$tipi_per_indice[$tipo_atto_id], $atto_id);
        $indice = OppIndiceRilevanzaPeer::calcola_rilevanza_atto($atto, $tipo_atto_id, $data, $verbose);
        // inserimento o aggiornamento del valore in opp_politician_history_cache
        $cache_record = OppActHistoryCachePeer::retrieveByDataChiTipoChiId($data_lookup, 'A', $atto_id);
        if (!$cache_record) {
            $cache_record = new OppActHistoryCache();
        }
        $cache_record->setLegislatura($legislatura_corrente);
        $cache_record->setChiTipo('A');
        $cache_record->setChiId($atto_id);
        $cache_record->setTipoAttoId($tipo_atto_id);
        $cache_record->setIndice($indice);
        $cache_record->setPriorita($priorita);
        $cache_record->setData($data);
        $cache_record->setUpdatedAt(date('Y-m-d H:i'));
        // forza riscrittura updated_at, per tenere traccia esecuzioni
        $cache_record->save();
        unset($cache_record);
        $msg = sprintf("%7.2f", $indice);
        echo pakeColor::colorize($msg, array('fg' => 'cyan', 'bold' => true));
        $msg = sprintf(" [%4d sec] [%10d bytes]\n", time() - $start_time, memory_get_usage());
        echo pakeColor::colorize($msg, array('fg' => 'red', 'bold' => false));
    }
    $msg = sprintf("%d atti elaborati\n", $cnt);
    echo pakeColor::colorize($msg, array('fg' => 'cyan', 'bold' => true));
}