http://wiki.apache.org/spamassassin/TopSharedMemoryBug
338861
def val_accuracy(show_swap):
    """"""
    kv = kernel_ver()
    pid = os.getpid()
    swap_accuracy = -1
    if kv[:2] == (2,4):
        if proc.open('meminfo').read().find("Inact_") == -1:
            return 1, swap_accuracy
        return 0, swap_accuracy
    elif kv[:2] == (2,6):
        if os.path.exists(proc.path(pid, 'smaps')):
            swap_accuracy = 1
            if proc.open(pid, 'smaps').read().find("Pss:")!=-1:
                return 2, swap_accuracy
            else:
                return 1, swap_accuracy
        if (2,6,1) <= kv <= (2,6,9):
            return -1, swap_accuracy
        return 0, swap_accuracy
    elif kv[0] > 2 and os.path.exists(proc.path(pid, 'smaps')):
        swap_accuracy = 1
        if show_swap and proc.open(pid, 'smaps').read().find("SwapPss:")!=-1:
            swap_accuracy = 2
        return 2, swap_accuracy
    else:
        return 1, swap_accuracy
523015
static long getTotalUsage(Map<String, MemoryUsage> usages) {
    long sum = 0L;
    for (Map.Entry<String, MemoryUsage> e : usages.entrySet()) {
      sum += e.getValue().getUsed();
    }
    return sum;
  }
675855
protected function memory()
    {
        $s = $this->grabkey('hw.memsize');
        if (CommonFunctions::executeProgram('vm_stat', '', $pstat, PSI_DEBUG)) {
            // calculate free memory from page sizes (each page = 4096)
            if (preg_match('/^Pages free:\s+(\S+)/m', $pstat, $free_buf)) {
                if (preg_match('/^Anonymous pages:\s+(\S+)/m', $pstat, $anon_buf)
                   && preg_match('/^Pages wired down:\s+(\S+)/m', $pstat, $wire_buf)
                   && preg_match('/^File-backed pages:\s+(\S+)/m', $pstat, $fileb_buf)) {
                        // OS X 10.9 or never
                        $this->sys->setMemFree($free_buf[1] * 4 * 1024);
                        $this->sys->setMemApplication(($anon_buf[1]+$wire_buf[1]) * 4 * 1024);
                        $this->sys->setMemCache($fileb_buf[1] * 4 * 1024);
                        if (preg_match('/^Pages occupied by compressor:\s+(\S+)/m', $pstat, $compr_buf)) {
                            $this->sys->setMemBuffer($compr_buf[1] * 4 * 1024);
                        }
                } else {
                    if (preg_match('/^Pages speculative:\s+(\S+)/m', $pstat, $spec_buf)) {
                        $this->sys->setMemFree(($free_buf[1]+$spec_buf[1]) * 4 * 1024);
                    } else {
                        $this->sys->setMemFree($free_buf[1] * 4 * 1024);
                    }
                    $appMemory = 0;
                    if (preg_match('/^Pages wired down:\s+(\S+)/m', $pstat, $wire_buf)) {
                        $appMemory += $wire_buf[1] * 4 * 1024;
                    }
                    if (preg_match('/^Pages active:\s+(\S+)/m', $pstat, $active_buf)) {
                        $appMemory += $active_buf[1] * 4 * 1024;
                    }
                    $this->sys->setMemApplication($appMemory);

                    if (preg_match('/^Pages inactive:\s+(\S+)/m', $pstat, $inactive_buf)) {
                        $this->sys->setMemCache($inactive_buf[1] * 4 * 1024);
                    }
                }
            } else {
                $lines = preg_split("/\n/", $pstat, -1, PREG_SPLIT_NO_EMPTY);
                $ar_buf = preg_split("/\s+/", $lines[1], 19);
                $this->sys->setMemFree($ar_buf[2] * 4 * 1024);
            }

            $this->sys->setMemTotal($s);
            $this->sys->setMemUsed($this->sys->getMemTotal() - $this->sys->getMemFree());

            if (CommonFunctions::executeProgram('sysctl', 'vm.swapusage | colrm 1 22', $swapBuff, PSI_DEBUG)) {
                $swap1 = preg_split('/M/', $swapBuff);
                $swap2 = preg_split('/=/', $swap1[1]);
                $swap3 = preg_split('/=/', $swap1[2]);
                $dev = new DiskDevice();
                $dev->setName('SWAP');
                $dev->setMountPoint('SWAP');
                $dev->setFsType('swap');
                $dev->setTotal($swap1[0] * 1024 * 1024);
                $dev->setUsed($swap2[1] * 1024 * 1024);
                $dev->setFree($swap3[1] * 1024 * 1024);
                $this->sys->setSwapDevices($dev);
            }
        }
    }
482147
def MemoryExceeded(self):
    """"""
    rss_size = self.proc.memory_info().rss
    return rss_size // 1024 // 1024 > config.CONFIG["Client.rss_max"]
387312
@Override
    public int getInMemoryDataSize()
    {
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            SibTr.entry(this, tc, "getInMemoryDataSize");

        JsMessage localMsg = getJSMessage(true);
        int msgSize = localMsg.getInMemorySize();

        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            SibTr.exit(this, tc, "getInMemoryDataSize", Integer.valueOf(msgSize));

        return msgSize;
    }
984961
def GetMemSharedMB(self):
        ''''''
        counter = c_uint()
        ret = vmGuestLib.VMGuestLib_GetMemSharedMB(self.handle.value, byref(counter))
        if ret != VMGUESTLIB_ERROR_SUCCESS: raise VMGuestLibException(ret)
        return counter.value
213017
def getTotalCpuTimeAndMemoryUsage():
    
    me = resource.getrusage(resource.RUSAGE_SELF)
    childs = resource.getrusage(resource.RUSAGE_CHILDREN)
    totalCpuTime = me.ru_utime+me.ru_stime+childs.ru_utime+childs.ru_stime
    totalMemoryUsage = me.ru_maxrss+ me.ru_maxrss
    return totalCpuTime, totalMemoryUsage
1030968
protected function getMemoryUsageString()
    {
        switch (strtoupper(trim(ShopgateLogger::getInstance()->getMemoryAnalyserLoggingSizeUnit()))) {
            case 'GB':
                return (memory_get_usage() / (1024 * 1024 * 1024)) . " GB (real usage " . (memory_get_usage(
                            true
                        ) / (1024 * 1024 * 1024)) . " GB)";
            case 'MB':
                return (memory_get_usage() / (1024 * 1024)) . " MB (real usage " . (memory_get_usage(
                            true
                        ) / (1024 * 1024)) . " MB)";
            case 'KB':
                return (memory_get_usage() / 1024) . " KB (real usage " . (memory_get_usage(true) / 1024) . " KB)";
            default:
                return memory_get_usage() . " Bytes (real usage " . memory_get_usage(true) . " Bytes)";
        }
    }
1145590
public function memory_stats()
    {
        if ($this->host_os === 'WINDOWS') {
            $wmi = new \COM("winmgmts:\\\\.\\root\\cimv2");
            $os =  $wmi->ExecQuery("SELECT * FROM Win32_OperatingSystem");

            foreach ($os as $m) {
                $mem_total = $m->TotalVisibleMemorySize;
                $mem_free = $m->FreePhysicalMemory;
            }

            $prefMemory = $wmi->ExecQuery("SELECT * FROM Win32_PerfFormattedData_PerfOS_Memory");

            foreach ($prefMemory as $pm) {
                $mem_cache = $pm->CacheBytes/1024;
            }
            $mem_buff = 0;
        } else {
            $fh = fopen('/proc/meminfo', 'r');

            $mem_free = $mem_buff = $mem_cache = $mem_total = 0;

            while ($line = fgets($fh)) {
                $pieces = array();
                if (preg_match('/^MemTotal:\s+(\d+)\skB$/', $line, $pieces)) {
                    $mem_total = $pieces[1];
                }
                if (preg_match('/^MemFree:\s+(\d+)\skB$/', $line, $pieces)) {
                    $mem_free = $pieces[1];
                }
                if (preg_match('/^Buffers:\s+(\d+)\skB$/', $line, $pieces)) {
                    $mem_buff = $pieces[1];
                }
                if (preg_match('/^Cached:\s+(\d+)\skB$/', $line, $pieces)) {
                    $mem_cache = $pieces[1];
                    break;
                }
            }
            fclose($fh);
        }

        $result['used']  = round(($mem_total - ($mem_buff + $mem_cache + $mem_free)) * 100 / $mem_total);
        $result['cache'] = round(($mem_cache + $mem_buff) * 100 / $mem_total);
        $result['free']  = round($mem_free * 100 / $mem_total);
        return $result;
    }
7844
def GetUsedMemory(self):
    
    try:
      memory_info = self._process.memory_info()
    except psutil.NoSuchProcess:
      return None

    # Psutil will return different memory information depending on what is
    # available in that platform.
    memory_data = getattr(memory_info, 'data', 0)
    memory_shared = getattr(memory_info, 'shared', 0)

    return memory_data + memory_shared
606567
def _log_diff_memory_data(self, prefix, new_memory_data, old_memory_data):
        
        def _vmem_used(memory_data):
            return memory_data['machine_data'].used

        def _process_mem_percent(memory_data):
            return memory_data['process_data']['memory_percent']

        def _process_rss(memory_data):
            return memory_data['process_data']['memory_info'].rss

        def _process_vms(memory_data):
            return memory_data['process_data']['memory_info'].vms

        if new_memory_data and old_memory_data:
            log.info(
                u"%s Diff Vmem used: %s, Diff percent memory: %s, Diff rss: %s, Diff vms: %s",
                prefix,
                _vmem_used(new_memory_data) - _vmem_used(old_memory_data),
                _process_mem_percent(new_memory_data) - _process_mem_percent(old_memory_data),
                _process_rss(new_memory_data) - _process_rss(old_memory_data),
                _process_vms(new_memory_data) - _process_vms(old_memory_data),
            )
604138
public static String getMemoryUsageStatsAsString(MemoryMXBean memoryMXBean) {
		MemoryUsage heap = memoryMXBean.getHeapMemoryUsage();
		MemoryUsage nonHeap = memoryMXBean.getNonHeapMemoryUsage();

		long heapUsed = heap.getUsed() >> 20;
		long heapCommitted = heap.getCommitted() >> 20;
		long heapMax = heap.getMax() >> 20;

		long nonHeapUsed = nonHeap.getUsed() >> 20;
		long nonHeapCommitted = nonHeap.getCommitted() >> 20;
		long nonHeapMax = nonHeap.getMax() >> 20;

		return String.format("Memory usage stats: [HEAP: %d/%d/%d MB, " +
				"NON HEAP: %d/%d/%d MB (used/committed/max)]",
				heapUsed, heapCommitted, heapMax, nonHeapUsed, nonHeapCommitted, nonHeapMax);
	}
93063
private void printJVMStats(final TSDB tsdb, final HttpQuery query) {
    final Map<String, Map<String, Object>> map = 
        new HashMap<String, Map<String, Object>>();
    
    final RuntimeMXBean runtime_bean = ManagementFactory.getRuntimeMXBean();
    final Map<String, Object> runtime = new HashMap<String, Object>();
    map.put("runtime", runtime);
    
    runtime.put("startTime", runtime_bean.getStartTime());
    runtime.put("uptime", runtime_bean.getUptime());
    runtime.put("vmName", runtime_bean.getVmName());
    runtime.put("vmVendor", runtime_bean.getVmVendor());
    runtime.put("vmVersion", runtime_bean.getVmVersion());
    
    final MemoryMXBean mem_bean = ManagementFactory.getMemoryMXBean();
    final Map<String, Object> memory = new HashMap<String, Object>();
    map.put("memory", memory);
    
    memory.put("heapMemoryUsage", mem_bean.getHeapMemoryUsage());
    memory.put("nonHeapMemoryUsage", mem_bean.getNonHeapMemoryUsage());
    memory.put("objectsPendingFinalization",
        mem_bean.getObjectPendingFinalizationCount());
    
    final List<GarbageCollectorMXBean> gc_beans = 
        ManagementFactory.getGarbageCollectorMXBeans();
    final Map<String, Object> gc = new HashMap<String, Object>();
    map.put("gc", gc);
    
    for (final GarbageCollectorMXBean gc_bean : gc_beans) {
      final Map<String, Object> stats = new HashMap<String, Object>();
      final String name = formatStatName(gc_bean.getName());
      if (name == null) {
        LOG.warn("Null name for bean: " + gc_bean);
        continue;
      }
      
      gc.put(name, stats);
      stats.put("collectionCount", gc_bean.getCollectionCount());
      stats.put("collectionTime", gc_bean.getCollectionTime());
    }    
    
    final List<MemoryPoolMXBean> pool_beans = 
        ManagementFactory.getMemoryPoolMXBeans();
    final Map<String, Object> pools = new HashMap<String, Object>();
    map.put("pools", pools);
    
    for (final MemoryPoolMXBean pool_bean : pool_beans) {
      final Map<String, Object> stats = new HashMap<String, Object>();
      final String name = formatStatName(pool_bean.getName());
      if (name == null) {
        LOG.warn("Null name for bean: " + pool_bean);
        continue;
      }
      pools.put(name, stats);
      
      stats.put("collectionUsage", pool_bean.getCollectionUsage());
      stats.put("usage", pool_bean.getUsage());
      stats.put("peakUsage", pool_bean.getPeakUsage());
      stats.put("type", pool_bean.getType());
    }
    
    final OperatingSystemMXBean os_bean = 
        ManagementFactory.getOperatingSystemMXBean();
    final Map<String, Object> os = new HashMap<String, Object>();
    map.put("os", os);
    
    os.put("systemLoadAverage", os_bean.getSystemLoadAverage());
    
    query.sendReply(query.serializer().formatJVMStatsV1(map));
  }
979273
static ImmutableList<ListFindingsResult> listFindingsAtTime(SourceName sourceName) {
    try (SecurityCenterClient client = SecurityCenterClient.create()) {
      // SourceName sourceName = SourceName.of(/*organizationId=*/"123234324",
      // /*sourceId=*/"423432321");

      // 5 days ago
      Instant fiveDaysAgo = Instant.now().minus(Duration.ofDays(5));

      ListFindingsRequest.Builder request =
          ListFindingsRequest.newBuilder()
              .setParent(sourceName.toString())
              .setReadTime(
                  Timestamp.newBuilder()
                      .setSeconds(fiveDaysAgo.getEpochSecond())
                      .setNanos(fiveDaysAgo.getNano()));

      // Call the API.
      ListFindingsPagedResponse response = client.listFindings(request.build());

      // This creates one list for all findings.  If your organization has a large number of
      // findings this can cause out of memory issues.  You can process them in incrementally
      // by returning the Iterable returned response.iterateAll() directly.
      ImmutableList<ListFindingsResult> results = ImmutableList.copyOf(response.iterateAll());
      System.out.println("Findings:");
      System.out.println(results);
      return results;
    } catch (IOException e) {
      throw new RuntimeException("Couldn't create client.", e);
    }
  }
1270371
public String getHealthMemory() {
        StringBuilder sb = new StringBuilder();
        sb.append("Logging JVM Stats\n");
        MonitorProvider mp = MonitorProvider.getInstance();
        PerformUsage perf = mp.getJVMMemoryUsage();
        sb.append(perf.toString());

        if (perf.memoryUsagePercent >= THRESHOLD_PERCENT) {
            sb.append("========= WARNING: MEM USAGE > " + THRESHOLD_PERCENT
                    + "!!");
            sb.append(" !! Live Threads List=============\n");
            sb.append(mp.getThreadUsage().toString());
            sb.append("========================================\n");
            sb.append("========================JVM Thread Dump====================\n");
            ThreadInfo[] threadDump = mp.getThreadDump();
            for (ThreadInfo threadInfo : threadDump) {
                sb.append(threadInfo.toString() + "\n");
            }
            sb.append("===========================================================\n");
        }
        sb.append("Logged JVM Stats\n");

        return sb.toString();
    }
284622
private void dumpThreads() {

        if (LOG.isDebugEnabled()) {
            StringBuffer b = new StringBuffer(512);
            Iterator<CmsUUID> i = m_threads.keySet().iterator();
            while (i.hasNext()) {
                CmsUUID key = i.next();
                A_CmsReportThread thread = m_threads.get(key);
                b.append(thread.getName());
                b.append(" - ");
                b.append(thread.getUUID());
                b.append('\n');
            }
            LOG.debug(
                Messages.get().getBundle().key(
                    Messages.LOG_THREADSTORE_POOL_CONTENT_2,
                    new Integer(m_threads.size()),
                    b.toString()));
        }
    }
998308
def memory
      @pagesize ||= Vmstat.pagesize
      has_available = false

      total = free = active = inactive = pageins = pageouts = available = 0
      procfs_file("meminfo") do |file|
        content = file.read(2048) # the requested information is in the first bytes

        content.scan(/(\w+):\s+(\d+) kB/) do |name, kbytes|
          pages = (kbytes.to_i * 1024) / @pagesize

          case name
            when "MemTotal" then total = pages
            when "MemFree" then free = pages
            when "MemAvailable"
                available = pages
                has_available = true
            when "Active" then active = pages
            when "Inactive" then inactive = pages
          end
        end
      end

      procfs_file("vmstat") do |file|
        content = file.read

        if content =~ /pgpgin\s+(\d+)/
          pageins = $1.to_i
        end

        if content =~ /pgpgout\s+(\d+)/
          pageouts = $1.to_i
        end
      end

      mem_klass = has_available ? LinuxMemory : Memory
      mem_klass.new(@pagesize, total-free-active-inactive, active,
                    inactive, free, pageins, pageouts).tap do |mem|
        mem.available = available if has_available
      end
    end