vom GC behandelte Referenzen wegräumen
12061
private static void purgeQueue() {

        ChronoReference cref;

        while ((cref = (ChronoReference) QUEUE.poll()) != null) {
            for (ChronoReference test : CHRONOS) {
                if (test.name.equals(cref.name)) {
                    CHRONOS.remove(test);
                    break;
                }
            }
        }

    }
691623
public function register_gc_handler($func)
    {
        foreach ($this->gc_handlers as $handler) {
            if ($handler == $func) {
                return;
            }
        }

        $this->gc_handlers[] = $func;
    }
271991
public function gc()
    {
        $hasGC = false;
        $maxActiveTime = $this->config->getMaxActiveTime();
        $maxUsedTime = $this->config->getMaxUsedTime();
        foreach($this->pool as $key => $item)
        {
            if(
                (null !== $maxActiveTime && $item->isFree() && time() - $item->getCreateTime() >= $maxActiveTime) // 最大存活时间
                || (null !== $maxUsedTime && $item->getLastReleaseTime() < $item->getLastUseTime() && time() - $item->getLastUseTime() >= $maxUsedTime) // 每次获取资源最长使用时间
                )
            {
                $item->getResource()->close();
                unset($this->pool[$key]);
                $hasGC = true;
            }
        }
        if($hasGC)
        {
            $this->fillMinResources();
            $this->buildQueue();
        }
    }
819914
@edu.umd.cs.findbugs.annotations.SuppressFBWarnings("DM_GC")
    @RequirePOST
    public void doGc(StaplerResponse rsp) throws IOException {
        checkPermission(Jenkins.ADMINISTER);
        System.gc();
        rsp.setStatus(HttpServletResponse.SC_OK);
        rsp.setContentType("text/plain");
        rsp.getWriter().println("GCed");
    }
583099
public static function gc() {
        global $CFG, $DB;

        // This may take a long time...
        \core_php_time_limit::raise();

        $maxlifetime = $CFG->sessiontimeout;

        try {
            // Kill all sessions of deleted and suspended users without any hesitation.
            $rs = $DB->get_recordset_select('sessions', "userid IN (SELECT id FROM {user} WHERE deleted <> 0 OR suspended <> 0)", array(), 'id DESC', 'id, sid');
            foreach ($rs as $session) {
                self::kill_session($session->sid);
            }
            $rs->close();

            // Kill sessions of users with disabled plugins.
            $auth_sequence = get_enabled_auth_plugins(true);
            $auth_sequence = array_flip($auth_sequence);
            unset($auth_sequence['nologin']); // No login means user cannot login.
            $auth_sequence = array_flip($auth_sequence);

            list($notplugins, $params) = $DB->get_in_or_equal($auth_sequence, SQL_PARAMS_QM, '', false);
            $rs = $DB->get_recordset_select('sessions', "userid IN (SELECT id FROM {user} WHERE auth $notplugins)", $params, 'id DESC', 'id, sid');
            foreach ($rs as $session) {
                self::kill_session($session->sid);
            }
            $rs->close();

            // Now get a list of time-out candidates - real users only.
            $sql = "SELECT u.*, s.sid, s.timecreated AS s_timecreated, s.timemodified AS s_timemodified
                      FROM {user} u
                      JOIN {sessions} s ON s.userid = u.id
                     WHERE s.timemodified < :purgebefore AND u.id <> :guestid";
            $params = array('purgebefore' => (time() - $maxlifetime), 'guestid'=>$CFG->siteguest);

            $authplugins = array();
            foreach ($auth_sequence as $authname) {
                $authplugins[$authname] = get_auth_plugin($authname);
            }
            $rs = $DB->get_recordset_sql($sql, $params);
            foreach ($rs as $user) {
                foreach ($authplugins as $authplugin) {
                    /** @var \auth_plugin_base $authplugin*/
                    if ($authplugin->ignore_timeout_hook($user, $user->sid, $user->s_timecreated, $user->s_timemodified)) {
                        continue 2;
                    }
                }
                self::kill_session($user->sid);
            }
            $rs->close();

            // Delete expired sessions for guest user account, give them larger timeout, there is no security risk here.
            $params = array('purgebefore' => (time() - ($maxlifetime * 5)), 'guestid'=>$CFG->siteguest);
            $rs = $DB->get_recordset_select('sessions', 'userid = :guestid AND timemodified < :purgebefore', $params, 'id DESC', 'id, sid');
            foreach ($rs as $session) {
                self::kill_session($session->sid);
            }
            $rs->close();

            // Delete expired sessions for userid = 0 (not logged in), better kill them asap to release memory.
            $params = array('purgebefore' => (time() - $maxlifetime));
            $rs = $DB->get_recordset_select('sessions', 'userid = 0 AND timemodified < :purgebefore', $params, 'id DESC', 'id, sid');
            foreach ($rs as $session) {
                self::kill_session($session->sid);
            }
            $rs->close();

            // Cleanup letfovers from the first browser access because it may set multiple cookies and then use only one.
            $params = array('purgebefore' => (time() - 60*3));
            $rs = $DB->get_recordset_select('sessions', 'userid = 0 AND timemodified = timecreated AND timemodified < :purgebefore', $params, 'id ASC', 'id, sid');
            foreach ($rs as $session) {
                self::kill_session($session->sid);
            }
            $rs->close();

        } catch (\Exception $ex) {
            debugging('Error gc-ing sessions: '.$ex->getMessage(), DEBUG_NORMAL, $ex->getTrace());
        }
    }
1037212
public function gc_run()
    {
        $probability = (int) ini_get('session.gc_probability');
        $divisor     = (int) ini_get('session.gc_divisor');

        if ($divisor > 0 && $probability > 0) {
            $random = mt_rand(1, $divisor);
            if ($random <= $probability) {
                $this->gc();
            }
        }
    }
114145
private static double gCf(double x, double A) {
       // Good for X>A+1
       double A0=0;
       double B0=1;
       double A1=1;
       double B1=x;
       double AOLD=0;
       double N=0;
       while (Math.abs((A1-AOLD)/A1)>.00001) {
           AOLD=A1;
           N=N+1;
           A0=A1+(N-A)*A0;
           B0=B1+(N-A)*B0;
           A1=x*A0+N*A1;
           B1=x*B0+N*B1;
           A0=A0/B1;
           B0=B0/B1;
           A1=A1/B1;
           B1=1;
       }
       double Prob=Math.exp(A*Math.log(x)-x-logGamma(A))*A1;

       return 1.0-Prob;
    }
558191
public function gc()
	{
		$hash = $this->options['hash'];

		$allinfo = wincache_ucache_info();

		foreach ($allinfo['cache_entries'] as $key)
		{
			if (strpos($key['key_name'], $hash . '-cache-'))
			{
				wincache_ucache_get($key['key_name']);
			}
		}
	}
909109
def SolicitarCTGInicial(self, numero_carta_de_porte, codigo_especie,
        cuit_canjeador, cuit_destino, cuit_destinatario, codigo_localidad_origen,
        codigo_localidad_destino, codigo_cosecha, peso_neto_carga, 
        cant_horas=None, patente_vehiculo=None, cuit_transportista=None, 
        km_a_recorrer=None, remitente_comercial_como_canjeador=None, 
        cuit_corredor=None, remitente_comercial_como_productor=None, 
        turno=None,
        **kwargs):
        ""
        # ajusto parámetros según validaciones de AFIP:
        if not cuit_canjeador or int(cuit_canjeador) == 0:
            cuit_canjeador = None         # nulo
        if not cuit_corredor or int(cuit_corredor) == 0:
            cuit_corredor = None         # nulo
        if not remitente_comercial_como_canjeador:
            remitente_comercial_como_canjeador = None
        if not remitente_comercial_como_productor:
            remitente_comercial_como_productor = None
        if turno == '':
            turno  = None                # nulo

        ret = self.client.solicitarCTGInicial(request=dict(
                        auth={
                            'token': self.Token, 'sign': self.Sign,
                            'cuitRepresentado': self.Cuit, },
                         datosSolicitarCTGInicial=dict(
                            cartaPorte=numero_carta_de_porte, 
                            codigoEspecie=codigo_especie,
                            cuitCanjeador=cuit_canjeador or None, 
                            remitenteComercialComoCanjeador=remitente_comercial_como_canjeador,
                            cuitDestino=cuit_destino, 
                            cuitDestinatario=cuit_destinatario, 
                            codigoLocalidadOrigen=codigo_localidad_origen,
                            codigoLocalidadDestino=codigo_localidad_destino, 
                            codigoCosecha=codigo_cosecha, 
                            pesoNeto=peso_neto_carga, 
                            cuitTransportista=cuit_transportista,
                            cantHoras=cant_horas,
                            patente=patente_vehiculo, 
                            kmARecorrer=km_a_recorrer,
                            cuitCorredor=cuit_corredor,
                            remitenteComercialcomoProductor=remitente_comercial_como_productor,
                            turno=turno,
                            )))['response']
        self.__analizar_errores(ret)
        self.Observaciones = ret['observacion']
        datos = ret.get('datosSolicitarCTGResponse')
        if datos:
            self.CartaPorte = str(datos['cartaPorte'])
            datos_ctg = datos.get('datosSolicitarCTG')
            if datos_ctg:
                self.NumeroCTG = str(datos_ctg['ctg'])
                self.FechaHora = str(datos_ctg['fechaEmision'])
                self.VigenciaDesde = str(datos_ctg['fechaVigenciaDesde'])
                self.VigenciaHasta = str(datos_ctg['fechaVigenciaHasta'])
                self.TarifaReferencia = str(datos_ctg.get('tarifaReferencia'))
            self.__analizar_controles(datos)
        return self.NumeroCTG or 0
837027
def ConsultarCodigoGradoReferencia(self, sep="||"):
        ""
        ret = self.client.codigoGradoReferenciaConsultar(
                        auth={
                            'token': self.Token, 'sign': self.Sign,
                            'cuit': self.Cuit, },
                            )['gradoRefReturn']
        self.__analizar_errores(ret)
        array = ret.get('gradosRef', [])
        if sep is None:
            return dict([(it['codigoDescripcion']['codigo'], 
                          it['codigoDescripcion']['descripcion']) 
                           for it in array])
        else:
            return [("%s %%s %s %%s %s" % (sep, sep, sep)) %
                    (it['codigoDescripcion']['codigo'], 
                     it['codigoDescripcion']['descripcion']) 
               for it in array]
1165056
@Override
    public String incomingClearText(String st, Document document, String msgName) {
        // empfangene Nachricht parsen, dabei die validvalues-Überprüfung weglassen
        String myMsgName = msgName + "Res";
        Message msg = new Message(myMsgName, st, document,
            Message.CHECK_SEQ, Message.DONT_CHECK_VALIDS);

        // in einer Schleife durch alle SuppSecMethods-Datensätze laufen
        for (int i = 0; ; i++) {
            String elemBaseName = HBCIUtils.withCounter(myMsgName + ".BPD.SecMethod.SuppSecMethods", i);
            SyntaxElement elem = msg.getElement(elemBaseName + ".method");

            if (elem == null) {
                break;
            }

            // Methodenbezeichner extrahieren
            String method = elem.toString();
            if (method.equals("TAN")) { // "TAN" ist ungültiger Bezeichner
                log.warn("there is an invalid sec type (TAN) in this BPD - removing it");

                // Elternelement finden (Segment "SecMethods")
                SyntaxElement parent = elem.getParent().getParent().getParent().getParent();
                String parentPath = parent.getPath();
                int number = 0;

                // durch alle Elemente dieses Segmentes laufen, bis die Multiple-DEG
                // mit den unterstützten SecMethods gefunden wurde
                for (Iterator<MultipleSyntaxElements> it = parent.getChildContainers().iterator(); it.hasNext(); ) {
                    MultipleSyntaxElements childContainer = it.next();
                    if (childContainer.getPath().equals(parentPath + ".SuppSecMethods")) {
                        // die Anzahl der eingestellten unterstützten SecMethods herausholen
                        number = childContainer.getElements().size();
                        break;
                    }
                }

                int startpos;
                int endpos;

                /* wenn mehr als eine SecMethod im Segment stand, dann braucht nur
                 * das eine der multiplen DEGs entfernt werden. Wenn aber nur die eine
                 * fehlerhafte Info enthalten war, dann muss das gesamte Segment
                 * entfernt werden, weil ein SecMethods-Segment ohne tatsächliche Daten
                 * über unterstützte SecMethods ungültig ist. */

                if (number > 1) { // nur das eine fehlerhafte TAN:1 löschen
                    startpos = elem.getPosInMsg();
                    endpos = startpos
                        + 1
                        + elem.toString(0).length()
                        + 1
                        + msg.getElement(elemBaseName + ".version").toString(0).length();
                } else { // komplettes segment "SecMethod" löschen
                    startpos = parent.getPosInMsg() + 1;
                    endpos = startpos + parent.toString(0).length();
                    /* der Fehler, der hier gemacht wird (nachfolgende Segment-
                     * Sequenznummern sind falsch), wird durch ein nachgeschaltetes
                     * Olly-Modul korrigiert */
                }

                st = new StringBuffer(st).delete(startpos, endpos).toString();
                log.debug("new message after removing: " + st);
                break;
            }
        }
        return st;
    }
433909
public static void gc() {
    class GCTask extends DTask<GCTask> {
      public GCTask() {super(GUI_PRIORITY);}
      @Override public void compute2() {
        Log.info("Calling System.gc() now...");
        System.gc();
        Log.info("System.gc() finished");
        tryComplete();
      }
    }

    for (H2ONode node : H2O.CLOUD._memary) {
      GCTask t = new GCTask();
      new RPC<>(node, t).call().get();
    }
  }
1338318
public function isUpdateProviderListNecessary()
    {
        $lastWeek = time() - (7 * 24 * 60 * 60);

        if (false === file_exists($this->cachePath .'/referrerblocked.txt') ||
             $lastWeek > filemtime($this->cachePath .'/referrerblocked.txt')
            )
        {
            return true; // update/anlegen notwendig
        }
        foreach($this->referrerProvider as $source => $url)
        {
            if (true === file_exists($this->cachePath .'/'. strtolower($source) . '.txt') &&
                $lastWeek > filemtime($this->cachePath .'/'. strtolower($source) . '.txt')
               )
            {
                return true; // update/anlegen notwendig, da eine Provider Datei neuer ist
            }
        }

        return false;
    }
961198
public function gc()
	{
		$this->engine->setOption('automaticCleaningFactor', 1);
		$this->engine->setOption('hashedDirectoryLevel', 1);

		$success1 = $this->engine->clean($this->directory . DS, false, 'old');

		if (!($dh = opendir($this->directory . DS)))
		{
			return false;
		}

		$result = true;

		while ($file = readdir($dh))
		{
			if ($file != '.' && $file != '..' && $file != '.svn')
			{
				$file2 = $this->directory . DS . $file;

				if (is_dir($file2))
				{
					$result = ($result and $this->engine->clean($file2 . DS, false, 'old'));
				}
			}
		}

		$success = ($success1 && $result);

		return $success;
	}
584953
@Override
    public synchronized T refer() {
        if (proxyIns != null) {
            return proxyIns;
        }

        referenceConfig = new ReferenceConfig<T>();
        covert(consumerConfig, referenceConfig);

        proxyIns = referenceConfig.get();

        return proxyIns;
    }
1344259
protected function getSingleWeighting()
	{
	    $arrPrio = array();
	    $arrPrioW = array();
	    $arrWeights = array_flip($this->arrAllBannersBasic);

	    //welche Wichtungen gibt es?
	    if (array_key_exists(1, $arrWeights)) { $arrPrioW[1] = 1; };
	    if (array_key_exists(2, $arrWeights)) { $arrPrioW[2] = 2; };
	    if (array_key_exists(3, $arrWeights)) { $arrPrioW[3] = 3; };
	    
	    $arrPrio[0] = array('start'=>0,  'stop'=>0);
	    $arrPrio[1] = array('start'=>1,  'stop'=>90);
	    $arrPrio[2] = array('start'=>91, 'stop'=>150);
	    $arrPrio[3] = array('start'=>151,'stop'=>180);
	    if ( !array_key_exists(2, $arrPrioW) )
	    {
	        // no prio 2 banner
	        $arrPrio[2] = array('start'=>0,  'stop'=>0);
	        $arrPrio[3] = array('start'=>91, 'stop'=>120);
	    }
	    $intPrio1 = (count($arrPrioW)) ? min($arrPrioW) : 0 ;
	    $intPrio2 = (count($arrPrioW)) ? max($arrPrioW) : 0 ;
	    
	    //wenn Wichtung vorhanden, dann per Zufall eine auswählen
	    if ($intPrio1>0)
	    {
	        $intWeightingHigh = mt_rand($arrPrio[$intPrio1]['start'],$arrPrio[$intPrio2]['stop']);
	    
	        // 1-180 auf 1-3 umrechnen
	        if ($intWeightingHigh<=$arrPrio[3]['stop'])
	        {
	            $intWeighting=3;
	        }
	        if ($intWeightingHigh<=$arrPrio[2]['stop'])
	        {
	            $intWeighting=2;
	        }
	        if ($intWeightingHigh<=$arrPrio[1]['stop'])
	        {
	            $intWeighting=1;
	        }
	    }
	    else
	    {
	        $intWeighting=0;
	    }
	    return $intWeighting;
	}
174523
static function gc()
    {
        $rcube = rcube::get_instance();
        $db    = $rcube->get_dbh();

        $db->query("DELETE FROM " . $db->table_name('cache', true) . " WHERE `expires` < " . $db->now());
    }