code
stringlengths
23
201k
docstring
stringlengths
17
96.2k
func_name
stringlengths
0
235
language
stringclasses
1 value
repo
stringlengths
8
72
path
stringlengths
11
317
url
stringlengths
57
377
license
stringclasses
7 values
public static String toSizeUnit(Long size) { if (size == null) { return "n/a"; } if (size < 1024) { return String.format("%4d", size); } if (size / 1024 < 1024) { return String.format("%4dk", size / 1024); } if (size / (1024 * 1024) < 1024) { return String.format("%4dm", size / (1024 * 1024)); } if (size / (1024 * 1024 * 1024) < 1024) { return String.format("%4dg", size / (1024 * 1024 * 1024)); } return String.format("%4dt", size / (1024 * 1024 * 1024 * 1024)); }
Formats a long value containing "number of bytes" to its megabyte representation. If the value is negative, "n/a" will be returned.
toSizeUnit
java
DarLiner/vjtools
vjtop/src/main/java/com/vip/vjtools/vjtop/Utils.java
https://github.com/DarLiner/vjtools/blob/master/vjtop/src/main/java/com/vip/vjtools/vjtop/Utils.java
Apache-2.0
public static String toTimeUnit(long millis) { long seconds = millis / 1000; if (seconds < 60) { return String.format("%02ds", seconds); } if (seconds < 3600) { return String.format("%02dm%02ds", seconds / 60, seconds % 60); } if (seconds < (24 * 3600)) { return String.format("%02dh%02dm", seconds / 3600, (seconds / 60) % 60); } return String.format("%dd%02dh", seconds / (3600 * 24), (seconds / 3600) % 24); }
Formats a long value containing "number of bytes" to its megabyte representation. If the value is negative, "n/a" will be returned.
toTimeUnit
java
DarLiner/vjtools
vjtop/src/main/java/com/vip/vjtools/vjtop/Utils.java
https://github.com/DarLiner/vjtools/blob/master/vjtop/src/main/java/com/vip/vjtools/vjtop/Utils.java
Apache-2.0
public static String rightStr(String str, int length) { return str.substring(Math.max(0, str.length() - length)); }
Returns a substring of the given string, representing the 'length' most-right characters
rightStr
java
DarLiner/vjtools
vjtop/src/main/java/com/vip/vjtools/vjtop/Utils.java
https://github.com/DarLiner/vjtools/blob/master/vjtop/src/main/java/com/vip/vjtools/vjtop/Utils.java
Apache-2.0
public static String leftStr(String str, int length) { return str.substring(0, Math.min(str.length(), length)); }
Returns a substring of the given string, representing the 'length' most-left characters
leftStr
java
DarLiner/vjtools
vjtop/src/main/java/com/vip/vjtools/vjtop/Utils.java
https://github.com/DarLiner/vjtools/blob/master/vjtop/src/main/java/com/vip/vjtools/vjtop/Utils.java
Apache-2.0
public static double calcLoad(double deltaUptime, double deltaTime, int factor) { if (deltaTime <= 0 || deltaUptime == 0) { return 0.0; } return Math.min(99.99, deltaTime / (deltaUptime * factor)); }
calculates a "load", given on two deltas
calcLoad
java
DarLiner/vjtools
vjtop/src/main/java/com/vip/vjtools/vjtop/Utils.java
https://github.com/DarLiner/vjtools/blob/master/vjtop/src/main/java/com/vip/vjtools/vjtop/Utils.java
Apache-2.0
public static long[] sortAndFilterThreadIdsByValue(Map map, int threadLimit) { int max = Math.min(threadLimit, map.size()); List<Map.Entry> list = new LinkedList(map.entrySet()); Collections.sort(list, new Comparator() { @Override public int compare(Object o1, Object o2) { return ((Comparable) ((Map.Entry) (o2)).getValue()).compareTo(((Map.Entry) (o1)).getValue()); } }); long[] topTidArray = new long[max]; int i = 0; for (Map.Entry entry : list) { topTidArray[i] = (Long) entry.getKey(); if (++i >= max) { break; } } return topTidArray; }
Sorts a Map by its values, using natural ordering.
sortAndFilterThreadIdsByValue
java
DarLiner/vjtools
vjtop/src/main/java/com/vip/vjtools/vjtop/Utils.java
https://github.com/DarLiner/vjtools/blob/master/vjtop/src/main/java/com/vip/vjtools/vjtop/Utils.java
Apache-2.0
@Override public int compare(Object o1, Object o2) { return ((Comparable) ((Map.Entry) (o2)).getValue()).compareTo(((Map.Entry) (o1)).getValue()); }
Sorts a Map by its values, using natural ordering.
compare
java
DarLiner/vjtools
vjtop/src/main/java/com/vip/vjtools/vjtop/Utils.java
https://github.com/DarLiner/vjtools/blob/master/vjtop/src/main/java/com/vip/vjtools/vjtop/Utils.java
Apache-2.0
public static long parseFromSize(String str) { if (str == null || str.isEmpty()) { return -1; } str = str.toLowerCase(); int fromScale = BYTE_SIZE; try { if (str.endsWith("kb")) { str = str.substring(0, str.length() - 2).trim(); fromScale = KB_SIZE; } if (str.endsWith("k")) { str = str.substring(0, str.length() - 1).trim(); fromScale = KB_SIZE; } else if (str.endsWith("mb")) { str = str.substring(0, str.length() - 2).trim(); fromScale = MB_SIZE; } else if (str.endsWith("m")) { str = str.substring(0, str.length() - 1).trim(); fromScale = MB_SIZE; } else if (str.endsWith("gb")) { str = str.substring(0, str.length() - 2).trim(); fromScale = GB_SIZE; } else if (str.endsWith("g")) { str = str.substring(0, str.length() - 1).trim(); fromScale = GB_SIZE; } else if (str.endsWith("bytes")) { str = str.substring(0, str.length() - "bytes".length()).trim(); fromScale = BYTE_SIZE; } str = str.replace(",", ""); long value = (long) Double.parseDouble(str); return value * fromScale; } catch (Throwable ex) { return -1; } }
Sorts a Map by its values, using natural ordering.
parseFromSize
java
DarLiner/vjtools
vjtop/src/main/java/com/vip/vjtools/vjtop/Utils.java
https://github.com/DarLiner/vjtools/blob/master/vjtop/src/main/java/com/vip/vjtools/vjtop/Utils.java
Apache-2.0
public static void sleep(long mills) { try { Thread.sleep(mills); } catch (InterruptedException e) { } }
Sorts a Map by its values, using natural ordering.
sleep
java
DarLiner/vjtools
vjtop/src/main/java/com/vip/vjtools/vjtop/Utils.java
https://github.com/DarLiner/vjtools/blob/master/vjtop/src/main/java/com/vip/vjtools/vjtop/Utils.java
Apache-2.0
private static OptionParser createOptionParser() { OptionParser parser = new OptionParser(); // commmon parser.acceptsAll(Arrays.asList(new String[]{"help", "?", "h"}), "shows this help").forHelp(); parser.acceptsAll(Arrays.asList(new String[]{"n", "iteration"}), "vjtop will exit after n output iterations (defaults to unlimit)").withRequiredArg() .ofType(Integer.class); parser.acceptsAll(Arrays.asList(new String[]{"d", "interval"}), "interval between each output iteration (defaults to 10s)").withRequiredArg().ofType(Integer.class); parser.acceptsAll(Arrays.asList(new String[]{"w", "width"}), "Number of columns for the console display (defaults to 100)").withRequiredArg().ofType(Integer.class); parser.acceptsAll(Arrays.asList(new String[]{"l", "limit"}), "Number of threads to display ( default to 10 threads)").withRequiredArg().ofType(Integer.class); // detail mode parser.accepts("cpu", "default mode in detail view, display thread cpu usage and sort by thread delta cpu time "); parser.accepts("totalcpu", "display thread cpu usage and sort by total cpu time"); parser.accepts("syscpu", "display thread cpu usage and sort by delta syscpu time"); parser.accepts("totalsyscpu", "display thread cpu usage and sort by total syscpu time"); parser.accepts("memory", "display thread memory allocated and sort by delta"); parser.accepts("totalmemory", "display thread memory allocated and sort by total"); return parser; }
VJTop entry point class. - parses program arguments - selects console view - prints header - main "iteration loop" @author paru
createOptionParser
java
DarLiner/vjtools
vjtop/src/main/java/com/vip/vjtools/vjtop/VJTop.java
https://github.com/DarLiner/vjtools/blob/master/vjtop/src/main/java/com/vip/vjtools/vjtop/VJTop.java
Apache-2.0
public static void main(String[] args) { try { // 1. create option parser OptionParser parser = createOptionParser(); OptionSet optionSet = parser.parse(args); if (optionSet.has("help")) { printHelper(parser); System.exit(0); } // 2. create view String pid = parsePid(parser, optionSet); VMDetailView.DetailMode displayMode = parseDisplayMode(optionSet); Integer width = null; if (optionSet.hasArgument("width")) { width = (Integer) optionSet.valueOf("width"); } VMDetailView view = new VMDetailView(pid, displayMode, width); if (optionSet.hasArgument("limit")) { Integer limit = (Integer) optionSet.valueOf("limit"); view.threadLimit = limit; } // 3. create main application VJTop app = new VJTop(); app.mainThread = Thread.currentThread(); app.view = view; Integer interval = DEFAULT_INTERVAL; if (optionSet.hasArgument("interval")) { interval = (Integer) (optionSet.valueOf("interval")); if (interval < 1) { throw new IllegalArgumentException("Interval cannot be set below 1.0"); } } app.interval = interval; if (optionSet.hasArgument("n")) { Integer iterations = (Integer) optionSet.valueOf("n"); app.maxIterations = iterations; } // 4. start thread to get user input Thread interactiveThread = new Thread(new InteractiveTask(app)); interactiveThread.setDaemon(true); interactiveThread.start(); // 5. run views app.run(view); } catch (Exception e) { e.printStackTrace(System.err); } }
VJTop entry point class. - parses program arguments - selects console view - prints header - main "iteration loop" @author paru
main
java
DarLiner/vjtools
vjtop/src/main/java/com/vip/vjtools/vjtop/VJTop.java
https://github.com/DarLiner/vjtools/blob/master/vjtop/src/main/java/com/vip/vjtools/vjtop/VJTop.java
Apache-2.0
private static VMDetailView.DetailMode parseDisplayMode(OptionSet optionSet) { VMDetailView.DetailMode displayMode = VMDetailView.DetailMode.cpu; if (optionSet.has("memory")) { displayMode = VMDetailView.DetailMode.memory; } else if (optionSet.has("totalmemory")) { displayMode = VMDetailView.DetailMode.totalmemory; } else if (optionSet.has("totalcpu")) { displayMode = VMDetailView.DetailMode.totalcpu; } else if (optionSet.has("syscpu")) { displayMode = VMDetailView.DetailMode.syscpu; } else if (optionSet.has("totalsyscpu")) { displayMode = VMDetailView.DetailMode.totalsyscpu; } return displayMode; }
VJTop entry point class. - parses program arguments - selects console view - prints header - main "iteration loop" @author paru
parseDisplayMode
java
DarLiner/vjtools
vjtop/src/main/java/com/vip/vjtools/vjtop/VJTop.java
https://github.com/DarLiner/vjtools/blob/master/vjtop/src/main/java/com/vip/vjtools/vjtop/VJTop.java
Apache-2.0
private static String parsePid(OptionParser parser, OptionSet optionSet) { Integer pid = null; // to support PID as non option argument if (optionSet.nonOptionArguments().size() > 0) { pid = Integer.valueOf((String) optionSet.nonOptionArguments().get(0)); } if (pid == null) { System.out.println("PID can't be empty !!!"); printHelper(parser); System.exit(0); } return String.valueOf(pid); }
VJTop entry point class. - parses program arguments - selects console view - prints header - main "iteration loop" @author paru
parsePid
java
DarLiner/vjtools
vjtop/src/main/java/com/vip/vjtools/vjtop/VJTop.java
https://github.com/DarLiner/vjtools/blob/master/vjtop/src/main/java/com/vip/vjtools/vjtop/VJTop.java
Apache-2.0
private static void printHelper(OptionParser parser) { try { System.out.println("vjtop - java monitoring for the command-line"); System.out.println("Usage: vjtop.sh [options...] <PID>"); System.out.println(""); parser.printHelpOn(System.out); } catch (IOException ignored) { } }
VJTop entry point class. - parses program arguments - selects console view - prints header - main "iteration loop" @author paru
printHelper
java
DarLiner/vjtools
vjtop/src/main/java/com/vip/vjtools/vjtop/VJTop.java
https://github.com/DarLiner/vjtools/blob/master/vjtop/src/main/java/com/vip/vjtools/vjtop/VJTop.java
Apache-2.0
private static void clearTerminal() { if (System.getProperty("os.name").contains("Windows")) { // hack System.out.printf("%n%n%n%n%n%n%n%n%n%n%n%n%n%n%n%n%n%n%n%n%n%n%n%n%n%n%n%n%n%n%n"); } else if (System.getProperty("vjtop.altClear") != null) { System.out.print('\f'); } else { System.out.print(CLEAR_TERMINAL_ANSI_CMD); } }
VJTop entry point class. - parses program arguments - selects console view - prints header - main "iteration loop" @author paru
clearTerminal
java
DarLiner/vjtools
vjtop/src/main/java/com/vip/vjtools/vjtop/VJTop.java
https://github.com/DarLiner/vjtools/blob/master/vjtop/src/main/java/com/vip/vjtools/vjtop/VJTop.java
Apache-2.0
public void exit() { view.exit(); mainThread.interrupt(); System.err.println(" Quit."); }
VJTop entry point class. - parses program arguments - selects console view - prints header - main "iteration loop" @author paru
exit
java
DarLiner/vjtools
vjtop/src/main/java/com/vip/vjtools/vjtop/VJTop.java
https://github.com/DarLiner/vjtools/blob/master/vjtop/src/main/java/com/vip/vjtools/vjtop/VJTop.java
Apache-2.0
public void preventFlush() { needMoreInput = true; }
VJTop entry point class. - parses program arguments - selects console view - prints header - main "iteration loop" @author paru
preventFlush
java
DarLiner/vjtools
vjtop/src/main/java/com/vip/vjtools/vjtop/VJTop.java
https://github.com/DarLiner/vjtools/blob/master/vjtop/src/main/java/com/vip/vjtools/vjtop/VJTop.java
Apache-2.0
public void continueFlush() { needMoreInput = false; }
VJTop entry point class. - parses program arguments - selects console view - prints header - main "iteration loop" @author paru
continueFlush
java
DarLiner/vjtools
vjtop/src/main/java/com/vip/vjtools/vjtop/VJTop.java
https://github.com/DarLiner/vjtools/blob/master/vjtop/src/main/java/com/vip/vjtools/vjtop/VJTop.java
Apache-2.0
private void waitForInput() { while (needMoreInput) { Utils.sleep(1000); } }
VJTop entry point class. - parses program arguments - selects console view - prints header - main "iteration loop" @author paru
waitForInput
java
DarLiner/vjtools
vjtop/src/main/java/com/vip/vjtools/vjtop/VJTop.java
https://github.com/DarLiner/vjtools/blob/master/vjtop/src/main/java/com/vip/vjtools/vjtop/VJTop.java
Apache-2.0
public void printView() throws Exception { long iterationStartTime = System.currentTimeMillis(); long preCpuTime = operatingSystemMXBean.getProcessCpuTime(); vmInfo.update(); if (!checkState()) { return; } printJvmInfo(); if (mode == DetailMode.memory || mode == DetailMode.totalmemory) { printTopMemoryThreads(mode); } else { printTopCpuThreads(mode); } long deltaTime = System.currentTimeMillis() - iterationStartTime; long deltaCpuTime = (operatingSystemMXBean.getProcessCpuTime() - preCpuTime) / (Utils.NANOS_TO_MILLS); System.out.printf(" Cost time: %3dms, CPU time: %3dms%n", deltaTime, deltaCpuTime); System.out.print(" Input command (h for help):"); }
"detail" view, printing detail metrics of a specific jvm. Also printing the top threads (based on the current CPU usage) @author paru
printView
java
DarLiner/vjtools
vjtop/src/main/java/com/vip/vjtools/vjtop/VMDetailView.java
https://github.com/DarLiner/vjtools/blob/master/vjtop/src/main/java/com/vip/vjtools/vjtop/VMDetailView.java
Apache-2.0
public boolean shouldExit() { return shouldExit; }
Requests the disposal of this view - it should be called again.
shouldExit
java
DarLiner/vjtools
vjtop/src/main/java/com/vip/vjtools/vjtop/VMDetailView.java
https://github.com/DarLiner/vjtools/blob/master/vjtop/src/main/java/com/vip/vjtools/vjtop/VMDetailView.java
Apache-2.0
public void exit() { shouldExit = true; }
Requests the disposal of this view - it should be called again.
exit
java
DarLiner/vjtools
vjtop/src/main/java/com/vip/vjtools/vjtop/VMDetailView.java
https://github.com/DarLiner/vjtools/blob/master/vjtop/src/main/java/com/vip/vjtools/vjtop/VMDetailView.java
Apache-2.0
private void setWidth(Integer width) { if (width == null) { this.width = DEFAULT_WIDTH; } else if (width < MIN_WIDTH) { this.width = MIN_WIDTH; } else { this.width = width; } }
Requests the disposal of this view - it should be called again.
setWidth
java
DarLiner/vjtools
vjtop/src/main/java/com/vip/vjtools/vjtop/VMDetailView.java
https://github.com/DarLiner/vjtools/blob/master/vjtop/src/main/java/com/vip/vjtools/vjtop/VMDetailView.java
Apache-2.0
private int getThreadNameWidth() { return this.width - 48; }
Requests the disposal of this view - it should be called again.
getThreadNameWidth
java
DarLiner/vjtools
vjtop/src/main/java/com/vip/vjtools/vjtop/VMDetailView.java
https://github.com/DarLiner/vjtools/blob/master/vjtop/src/main/java/com/vip/vjtools/vjtop/VMDetailView.java
Apache-2.0
public static DetailMode parse(String mode){ switch (mode) { case "1": return cpu; case "2": return syscpu; case "3": return totalcpu; case "4": return totalsyscpu; case "5": return memory; case "6": return totalmemory; default: System.err.println(" Wrong option for display mode(1-6)"); return null; } }
Requests the disposal of this view - it should be called again.
parse
java
DarLiner/vjtools
vjtop/src/main/java/com/vip/vjtools/vjtop/VMDetailView.java
https://github.com/DarLiner/vjtools/blob/master/vjtop/src/main/java/com/vip/vjtools/vjtop/VMDetailView.java
Apache-2.0
@Override public void run() { jmxClient.disconnect(); }
VMInfo retrieves or updates the metrics for a specific remote jvm, using JmxClient. @author paru
run
java
DarLiner/vjtools
vjtop/src/main/java/com/vip/vjtools/vjtop/VMInfo.java
https://github.com/DarLiner/vjtools/blob/master/vjtop/src/main/java/com/vip/vjtools/vjtop/VMInfo.java
Apache-2.0
public static VMInfo createDeadVM(String pid, VMInfoState state) { VMInfo vmInfo = new VMInfo(); vmInfo.state = state; vmInfo.pid = pid; return vmInfo; }
Creates a dead VMInfo, representing a jvm in a given state which cannot be attached or other monitoring issues occurred.
createDeadVM
java
DarLiner/vjtools
vjtop/src/main/java/com/vip/vjtools/vjtop/VMInfo.java
https://github.com/DarLiner/vjtools/blob/master/vjtop/src/main/java/com/vip/vjtools/vjtop/VMInfo.java
Apache-2.0
public void update() throws Exception { if (state == VMInfoState.ERROR_DURING_ATTACH || state == VMInfoState.DETACHED || state == VMInfoState.CONNECTION_REFUSED) { return; } if (perfDataSupport) { perfCounters = perfData.getAllCounters(); } try { jmxClient.flush(); updateIO(); updateCpu(); updateThreads(); updateClassLoad(); updateMemoryPool(); updateGC(); updateSafepoint(); } catch (Throwable e) { Logger.getLogger("vjtop").log(Level.INFO, "error during update", e); updateErrorCount++; if (updateErrorCount > 10) { state = VMInfoState.DETACHED; } else { state = VMInfoState.ATTACHED_UPDATE_ERROR; } } }
Updates all jvm metrics to the most recent remote values
update
java
DarLiner/vjtools
vjtop/src/main/java/com/vip/vjtools/vjtop/VMInfo.java
https://github.com/DarLiner/vjtools/blob/master/vjtop/src/main/java/com/vip/vjtools/vjtop/VMInfo.java
Apache-2.0
private void updateIO() { Map<String, String> procIo = ProcFileData.getProcIO(pid); long rchar = Utils.parseFromSize(procIo.get("rchar")); long wchar = Utils.parseFromSize(procIo.get("wchar")); long readBytes = Utils.parseFromSize(procIo.get("read_bytes")); long writeBytes = Utils.parseFromSize(procIo.get("write_bytes")); if (lastRchar > 0 || lastWchar > 0 || lastReadBytes > 0 || lastWriteBytes > 0) { deltaRchar = rchar - lastRchar; deltaWchar = wchar - lastWchar; deltaReadBytes = readBytes - lastReadBytes; deltaWriteBytes = writeBytes - lastWriteBytes; } lastRchar = rchar; lastWchar = wchar; lastReadBytes = readBytes; lastWriteBytes = writeBytes; }
Updates all jvm metrics to the most recent remote values
updateIO
java
DarLiner/vjtools
vjtop/src/main/java/com/vip/vjtools/vjtop/VMInfo.java
https://github.com/DarLiner/vjtools/blob/master/vjtop/src/main/java/com/vip/vjtools/vjtop/VMInfo.java
Apache-2.0
private void updateCpu() throws Exception { long uptimeMills = jmxClient.getRuntimeMXBean().getUptime(); long cpuTimeNanos = jmxClient.getOperatingSystemMXBean().getProcessCpuTime(); if (lastUpTimeMills > 0 && lastCPUTimeNanos > 0) { deltaUptimeMills = uptimeMills - lastUpTimeMills; deltaCpuTimeNanos = (cpuTimeNanos - lastCPUTimeNanos); cpuLoad = Utils.calcLoad(deltaUptimeMills, deltaCpuTimeNanos / (Utils.NANOS_TO_MILLS * 1D), processors); singleCoreCpuLoad = Utils.calcLoad(deltaUptimeMills, deltaCpuTimeNanos / (Utils.NANOS_TO_MILLS * 1D), 1); } lastUpTimeMills = uptimeMills; lastCPUTimeNanos = cpuTimeNanos; Map<String, String> procStatus = ProcFileData.getProcStatus(pid); rss = Utils.parseFromSize(procStatus.get("VmRSS")); swap = Utils.parseFromSize(procStatus.get("VmSwap")); }
Updates all jvm metrics to the most recent remote values
updateCpu
java
DarLiner/vjtools
vjtop/src/main/java/com/vip/vjtools/vjtop/VMInfo.java
https://github.com/DarLiner/vjtools/blob/master/vjtop/src/main/java/com/vip/vjtools/vjtop/VMInfo.java
Apache-2.0
private void updateThreads() throws IOException { if (perfDataSupport) { threadActive = ((LongCounter) perfCounters.get("java.threads.live")).getLong(); threadDaemon = ((LongCounter) perfCounters.get("java.threads.daemon")).getLong(); threadPeak = ((LongCounter) perfCounters.get("java.threads.livePeak")).getLong(); threadStarted = ((LongCounter) perfCounters.get("java.threads.started")).getLong(); } else { threadActive = jmxClient.getThreadMXBean().getThreadCount(); threadDaemon = jmxClient.getThreadMXBean().getDaemonThreadCount(); threadPeak = jmxClient.getThreadMXBean().getPeakThreadCount(); threadStarted = jmxClient.getThreadMXBean().getTotalStartedThreadCount(); } }
Updates all jvm metrics to the most recent remote values
updateThreads
java
DarLiner/vjtools
vjtop/src/main/java/com/vip/vjtools/vjtop/VMInfo.java
https://github.com/DarLiner/vjtools/blob/master/vjtop/src/main/java/com/vip/vjtools/vjtop/VMInfo.java
Apache-2.0
private void updateClassLoad() throws IOException { classLoaded = jmxClient.getClassLoadingMXBean().getLoadedClassCount(); classUnLoaded = jmxClient.getClassLoadingMXBean().getUnloadedClassCount(); }
Updates all jvm metrics to the most recent remote values
updateClassLoad
java
DarLiner/vjtools
vjtop/src/main/java/com/vip/vjtools/vjtop/VMInfo.java
https://github.com/DarLiner/vjtools/blob/master/vjtop/src/main/java/com/vip/vjtools/vjtop/VMInfo.java
Apache-2.0
private void updateMemoryPool() throws IOException { MemoryPoolMXBean survivorMemoryPool = jmxClient.getMemoryPoolManager().getSurvivorMemoryPool(); if (survivorMemoryPool != null) { surUsedBytes = survivorMemoryPool.getUsage().getUsed(); surMaxBytes = getMemoryPoolMaxOrCommited(survivorMemoryPool); } edenUsedBytes = jmxClient.getMemoryPoolManager().getEdenMemoryPool().getUsage().getUsed(); edenMaxBytes = getMemoryPoolMaxOrCommited(jmxClient.getMemoryPoolManager().getEdenMemoryPool()); oldUsedBytes = jmxClient.getMemoryPoolManager().getOldMemoryPool().getUsage().getUsed(); oldMaxBytes = getMemoryPoolMaxOrCommited(jmxClient.getMemoryPoolManager().getOldMemoryPool()); permUsedBytes = jmxClient.getMemoryPoolManager().getPermMemoryPool().getUsage().getUsed(); permMaxBytes = getMemoryPoolMaxOrCommited(jmxClient.getMemoryPoolManager().getPermMemoryPool()); if (jvmMajorVersion >= 8) { ccsUsedBytes = jmxClient.getMemoryPoolManager().getCompressedClassSpaceMemoryPool().getUsage().getUsed(); ccsMaxBytes = getMemoryPoolMaxOrCommited(jmxClient.getMemoryPoolManager() .getCompressedClassSpaceMemoryPool()); } codeCacheUsedBytes = jmxClient.getMemoryPoolManager().getCodeCacheMemoryPool().getUsage().getUsed(); codeCacheMaxBytes = getMemoryPoolMaxOrCommited(jmxClient.getMemoryPoolManager().getCodeCacheMemoryPool()); directUsedBytes = jmxClient.getBufferPoolManager().getDirectBufferPool().getMemoryUsed(); directMaxBytes = jmxClient.getBufferPoolManager().getDirectBufferPool().getTotalCapacity(); mapUsedBytes = jmxClient.getBufferPoolManager().getMappedBufferPool().getMemoryUsed(); mapMaxBytes = jmxClient.getBufferPoolManager().getMappedBufferPool().getTotalCapacity(); }
Updates all jvm metrics to the most recent remote values
updateMemoryPool
java
DarLiner/vjtools
vjtop/src/main/java/com/vip/vjtools/vjtop/VMInfo.java
https://github.com/DarLiner/vjtools/blob/master/vjtop/src/main/java/com/vip/vjtools/vjtop/VMInfo.java
Apache-2.0
private void updateGC() throws IOException { long youngGcCount = 0; long youngGcTimeMills = 0; long fullGcCount = 0; long fullGcTimeMills = 0; if (perfDataSupport) { youngGcCount = ((LongCounter) perfCounters.get("sun.gc.collector.0.invocations")).getLong(); youngGcTimeMills = ((TickCounter) perfCounters.get("sun.gc.collector.0.time")).getMills(); fullGcCount = ((LongCounter) perfCounters.get("sun.gc.collector.1.invocations")).getLong(); fullGcTimeMills = ((TickCounter) perfCounters.get("sun.gc.collector.1.time")).getMills(); } else { youngGcCount = jmxClient.getYoungCollector().getCollectionCount(); youngGcTimeMills = jmxClient.getYoungCollector().getCollectionTime(); fullGcCount = jmxClient.getFullCollector().getCollectionCount(); fullGcTimeMills = jmxClient.getFullCollector().getCollectionTime(); } if (lastYgcCount > 0) { deltaYgcTimeMills = youngGcTimeMills - lastYgcTimeMills; deltaYgcCount = youngGcCount - lastYgcCount; } if (lastFullgcCount > 0) { deltaFullgcTimeMills = fullGcTimeMills - lastFullgcTimeMills; deltaFullgcCount = fullGcCount - lastFullgcCount; } lastYgcTimeMills = youngGcTimeMills; lastYgcCount = youngGcCount; lastFullgcTimeMills = fullGcTimeMills; lastFullgcCount = fullGcCount; }
Updates all jvm metrics to the most recent remote values
updateGC
java
DarLiner/vjtools
vjtop/src/main/java/com/vip/vjtools/vjtop/VMInfo.java
https://github.com/DarLiner/vjtools/blob/master/vjtop/src/main/java/com/vip/vjtools/vjtop/VMInfo.java
Apache-2.0
private void updateSafepoint() { if (!perfDataSupport) { return; } long safepointCount = ((LongCounter) perfCounters.get("sun.rt.safepoints")).getLong(); long safepointTimeMills = ((TickCounter) perfCounters.get("sun.rt.safepointTime")).getMills(); long safepointSyncTimeMills = ((TickCounter) perfCounters.get("sun.rt.safepointTime")).getMills(); if (lastSafepointCount > 0) { deltaSafepointCount = safepointCount - lastSafepointCount; deltaSafepointTimeMills = safepointTimeMills - lastSafepointTimeMills; deltaSafepointSyncTimeMills = safepointSyncTimeMills - lastSafepointSyncTimeMills; } lastSafepointCount = safepointCount; lastSafepointTimeMills = safepointTimeMills; lastSafepointSyncTimeMills = safepointSyncTimeMills; }
Updates all jvm metrics to the most recent remote values
updateSafepoint
java
DarLiner/vjtools
vjtop/src/main/java/com/vip/vjtools/vjtop/VMInfo.java
https://github.com/DarLiner/vjtools/blob/master/vjtop/src/main/java/com/vip/vjtools/vjtop/VMInfo.java
Apache-2.0
public ThreadMXBean getThreadMXBean() throws IOException { return jmxClient.getThreadMXBean(); }
Updates all jvm metrics to the most recent remote values
getThreadMXBean
java
DarLiner/vjtools
vjtop/src/main/java/com/vip/vjtools/vjtop/VMInfo.java
https://github.com/DarLiner/vjtools/blob/master/vjtop/src/main/java/com/vip/vjtools/vjtop/VMInfo.java
Apache-2.0
private long getMemoryPoolMaxOrCommited(MemoryPoolMXBean memoryPool) { MemoryUsage usage = memoryPool.getUsage(); long max = usage.getMax(); max = max < 0 ? usage.getCommitted() : max; return max; }
Updates all jvm metrics to the most recent remote values
getMemoryPoolMaxOrCommited
java
DarLiner/vjtools
vjtop/src/main/java/com/vip/vjtools/vjtop/VMInfo.java
https://github.com/DarLiner/vjtools/blob/master/vjtop/src/main/java/com/vip/vjtools/vjtop/VMInfo.java
Apache-2.0
private int getJavaMajorVersion() { if (jvmVersion.startsWith("1.8")) { return 8; } else if (jvmVersion.startsWith("1.7")) { return 7; } else if (jvmVersion.startsWith("1.6")) { return 6; } else { return 0; } }
Updates all jvm metrics to the most recent remote values
getJavaMajorVersion
java
DarLiner/vjtools
vjtop/src/main/java/com/vip/vjtools/vjtop/VMInfo.java
https://github.com/DarLiner/vjtools/blob/master/vjtop/src/main/java/com/vip/vjtools/vjtop/VMInfo.java
Apache-2.0
public static PerfData connect(long pid) { try { return new PerfIntr((int) pid); } catch (ThreadDeath e) { throw e; } catch (OutOfMemoryError e) { throw e; } catch (Error e) { throw new RuntimeException("Cannot perf data for process " + pid + " - " + e.toString()); } catch (Exception e) { throw new RuntimeException("Cannot perf data for process " + pid + " - " + e.toString()); } }
Wraps {@link PerfInstrumentation} class. Its purpose is to shield warnings and {@link NoClassDefFoundError}s. @author Alexey Ragozin (alexey.ragozin@gmail.com)
connect
java
DarLiner/vjtools
vjtop/src/main/java/com/vip/vjtools/vjtop/data/PerfData.java
https://github.com/DarLiner/vjtools/blob/master/vjtop/src/main/java/com/vip/vjtools/vjtop/data/PerfData.java
Apache-2.0
@Override public int getMajorVersion() { return instr.getMajorVersion(); }
Wraps {@link PerfInstrumentation} class. Its purpose is to shield warnings and {@link NoClassDefFoundError}s. @author Alexey Ragozin (alexey.ragozin@gmail.com)
getMajorVersion
java
DarLiner/vjtools
vjtop/src/main/java/com/vip/vjtools/vjtop/data/PerfData.java
https://github.com/DarLiner/vjtools/blob/master/vjtop/src/main/java/com/vip/vjtools/vjtop/data/PerfData.java
Apache-2.0
@Override public int getMinorVersion() { return instr.getMinorVersion(); }
Wraps {@link PerfInstrumentation} class. Its purpose is to shield warnings and {@link NoClassDefFoundError}s. @author Alexey Ragozin (alexey.ragozin@gmail.com)
getMinorVersion
java
DarLiner/vjtools
vjtop/src/main/java/com/vip/vjtools/vjtop/data/PerfData.java
https://github.com/DarLiner/vjtools/blob/master/vjtop/src/main/java/com/vip/vjtools/vjtop/data/PerfData.java
Apache-2.0
@Override public long getModificationTimeStamp() { return instr.getModificationTimeStamp(); }
Wraps {@link PerfInstrumentation} class. Its purpose is to shield warnings and {@link NoClassDefFoundError}s. @author Alexey Ragozin (alexey.ragozin@gmail.com)
getModificationTimeStamp
java
DarLiner/vjtools
vjtop/src/main/java/com/vip/vjtools/vjtop/data/PerfData.java
https://github.com/DarLiner/vjtools/blob/master/vjtop/src/main/java/com/vip/vjtools/vjtop/data/PerfData.java
Apache-2.0
@Override public Map<String, Counter<?>> getAllCounters() { Map<String, Counter<?>> result = new LinkedHashMap<String, PerfData.Counter<?>>(); for (Object c : instr.getAllCounters()) { Counter<?> cc = convert(c); result.put(cc.getName(), cc); } return result; }
Wraps {@link PerfInstrumentation} class. Its purpose is to shield warnings and {@link NoClassDefFoundError}s. @author Alexey Ragozin (alexey.ragozin@gmail.com)
getAllCounters
java
DarLiner/vjtools
vjtop/src/main/java/com/vip/vjtools/vjtop/data/PerfData.java
https://github.com/DarLiner/vjtools/blob/master/vjtop/src/main/java/com/vip/vjtools/vjtop/data/PerfData.java
Apache-2.0
@Override public List<Counter<?>> findByPattern(String pattern) { return convert(instr.findByPattern(pattern)); }
Wraps {@link PerfInstrumentation} class. Its purpose is to shield warnings and {@link NoClassDefFoundError}s. @author Alexey Ragozin (alexey.ragozin@gmail.com)
findByPattern
java
DarLiner/vjtools
vjtop/src/main/java/com/vip/vjtools/vjtop/data/PerfData.java
https://github.com/DarLiner/vjtools/blob/master/vjtop/src/main/java/com/vip/vjtools/vjtop/data/PerfData.java
Apache-2.0
@SuppressWarnings("rawtypes") private List<Counter<?>> convert(List list) { List<Counter<?>> cl = new ArrayList<Counter<?>>(list.size()); for (Object c : list) { cl.add(convert(c)); } return cl; }
Wraps {@link PerfInstrumentation} class. Its purpose is to shield warnings and {@link NoClassDefFoundError}s. @author Alexey Ragozin (alexey.ragozin@gmail.com)
convert
java
DarLiner/vjtools
vjtop/src/main/java/com/vip/vjtools/vjtop/data/PerfData.java
https://github.com/DarLiner/vjtools/blob/master/vjtop/src/main/java/com/vip/vjtools/vjtop/data/PerfData.java
Apache-2.0
@SuppressWarnings("rawtypes") private Counter<?> convert(Object c) { if (c instanceof sun.management.counter.LongCounter) { sun.management.counter.LongCounter lc = (sun.management.counter.LongCounter) c; if (U_TICKS.equals(lc.getUnits())) { return new TickWrapper(tick, lc); } else { return new LongWrapper(lc); } } else if (c instanceof sun.management.counter.StringCounter) { sun.management.counter.StringCounter lc = (sun.management.counter.StringCounter) c; return new StringWrapper(lc); } else if (c instanceof sun.management.counter.LongArrayCounter) { sun.management.counter.LongArrayCounter lc = (sun.management.counter.LongArrayCounter) c; return new CounterWrapper(lc); } else if (c instanceof sun.management.counter.ByteArrayCounter) { sun.management.counter.ByteArrayCounter lc = (sun.management.counter.ByteArrayCounter) c; return new ByteArrayWrapper(lc); } else { return new CounterWrapper((sun.management.counter.Counter) c); } }
Wraps {@link PerfInstrumentation} class. Its purpose is to shield warnings and {@link NoClassDefFoundError}s. @author Alexey Ragozin (alexey.ragozin@gmail.com)
convert
java
DarLiner/vjtools
vjtop/src/main/java/com/vip/vjtools/vjtop/data/PerfData.java
https://github.com/DarLiner/vjtools/blob/master/vjtop/src/main/java/com/vip/vjtools/vjtop/data/PerfData.java
Apache-2.0
@Override public String getName() { return counter.getName(); }
Wraps {@link PerfInstrumentation} class. Its purpose is to shield warnings and {@link NoClassDefFoundError}s. @author Alexey Ragozin (alexey.ragozin@gmail.com)
getName
java
DarLiner/vjtools
vjtop/src/main/java/com/vip/vjtools/vjtop/data/PerfData.java
https://github.com/DarLiner/vjtools/blob/master/vjtop/src/main/java/com/vip/vjtools/vjtop/data/PerfData.java
Apache-2.0
@Override public Units getUnits() { Units u = UNIT_MAP.get(counter.getUnits()); return u == null ? Units.INVALID : u; }
Wraps {@link PerfInstrumentation} class. Its purpose is to shield warnings and {@link NoClassDefFoundError}s. @author Alexey Ragozin (alexey.ragozin@gmail.com)
getUnits
java
DarLiner/vjtools
vjtop/src/main/java/com/vip/vjtools/vjtop/data/PerfData.java
https://github.com/DarLiner/vjtools/blob/master/vjtop/src/main/java/com/vip/vjtools/vjtop/data/PerfData.java
Apache-2.0
@Override public Variability getVariability() { Variability v = VARIABILITY_MAP.get(counter.getVariability()); return v == null ? Variability.INVALID : v; }
Wraps {@link PerfInstrumentation} class. Its purpose is to shield warnings and {@link NoClassDefFoundError}s. @author Alexey Ragozin (alexey.ragozin@gmail.com)
getVariability
java
DarLiner/vjtools
vjtop/src/main/java/com/vip/vjtools/vjtop/data/PerfData.java
https://github.com/DarLiner/vjtools/blob/master/vjtop/src/main/java/com/vip/vjtools/vjtop/data/PerfData.java
Apache-2.0
@Override @SuppressWarnings("unchecked") public T getValue() { return (T) counter.getValue(); }
Wraps {@link PerfInstrumentation} class. Its purpose is to shield warnings and {@link NoClassDefFoundError}s. @author Alexey Ragozin (alexey.ragozin@gmail.com)
getValue
java
DarLiner/vjtools
vjtop/src/main/java/com/vip/vjtools/vjtop/data/PerfData.java
https://github.com/DarLiner/vjtools/blob/master/vjtop/src/main/java/com/vip/vjtools/vjtop/data/PerfData.java
Apache-2.0
@Override public String toString() { return counter.toString().replace((char) 0, ' '); }
Wraps {@link PerfInstrumentation} class. Its purpose is to shield warnings and {@link NoClassDefFoundError}s. @author Alexey Ragozin (alexey.ragozin@gmail.com)
toString
java
DarLiner/vjtools
vjtop/src/main/java/com/vip/vjtools/vjtop/data/PerfData.java
https://github.com/DarLiner/vjtools/blob/master/vjtop/src/main/java/com/vip/vjtools/vjtop/data/PerfData.java
Apache-2.0
@Override public String getString() { return trim(((sun.management.counter.StringCounter) counter) .stringValue()); }
Wraps {@link PerfInstrumentation} class. Its purpose is to shield warnings and {@link NoClassDefFoundError}s. @author Alexey Ragozin (alexey.ragozin@gmail.com)
getString
java
DarLiner/vjtools
vjtop/src/main/java/com/vip/vjtools/vjtop/data/PerfData.java
https://github.com/DarLiner/vjtools/blob/master/vjtop/src/main/java/com/vip/vjtools/vjtop/data/PerfData.java
Apache-2.0
private String trim(String value) { int n = value.indexOf(0); if (n >= 0) { return value.substring(0, n); } else { return value; } }
Wraps {@link PerfInstrumentation} class. Its purpose is to shield warnings and {@link NoClassDefFoundError}s. @author Alexey Ragozin (alexey.ragozin@gmail.com)
trim
java
DarLiner/vjtools
vjtop/src/main/java/com/vip/vjtools/vjtop/data/PerfData.java
https://github.com/DarLiner/vjtools/blob/master/vjtop/src/main/java/com/vip/vjtools/vjtop/data/PerfData.java
Apache-2.0
@Override public long getLong() { return ((sun.management.counter.LongCounter) counter) .longValue(); }
Wraps {@link PerfInstrumentation} class. Its purpose is to shield warnings and {@link NoClassDefFoundError}s. @author Alexey Ragozin (alexey.ragozin@gmail.com)
getLong
java
DarLiner/vjtools
vjtop/src/main/java/com/vip/vjtools/vjtop/data/PerfData.java
https://github.com/DarLiner/vjtools/blob/master/vjtop/src/main/java/com/vip/vjtools/vjtop/data/PerfData.java
Apache-2.0
@Override public double getTick() { return tick; }
Wraps {@link PerfInstrumentation} class. Its purpose is to shield warnings and {@link NoClassDefFoundError}s. @author Alexey Ragozin (alexey.ragozin@gmail.com)
getTick
java
DarLiner/vjtools
vjtop/src/main/java/com/vip/vjtools/vjtop/data/PerfData.java
https://github.com/DarLiner/vjtools/blob/master/vjtop/src/main/java/com/vip/vjtools/vjtop/data/PerfData.java
Apache-2.0
@Override public long getTicks() { return getLong(); }
Wraps {@link PerfInstrumentation} class. Its purpose is to shield warnings and {@link NoClassDefFoundError}s. @author Alexey Ragozin (alexey.ragozin@gmail.com)
getTicks
java
DarLiner/vjtools
vjtop/src/main/java/com/vip/vjtools/vjtop/data/PerfData.java
https://github.com/DarLiner/vjtools/blob/master/vjtop/src/main/java/com/vip/vjtools/vjtop/data/PerfData.java
Apache-2.0
@Override public long getMills() { return (long) ((tick * getLong())/Utils.NANOS_TO_MILLS); }
Wraps {@link PerfInstrumentation} class. Its purpose is to shield warnings and {@link NoClassDefFoundError}s. @author Alexey Ragozin (alexey.ragozin@gmail.com)
getMills
java
DarLiner/vjtools
vjtop/src/main/java/com/vip/vjtools/vjtop/data/PerfData.java
https://github.com/DarLiner/vjtools/blob/master/vjtop/src/main/java/com/vip/vjtools/vjtop/data/PerfData.java
Apache-2.0
public static SnapshotMBeanServerConnection newSnapshot(MBeanServerConnection mbsc) { final InvocationHandler ih = new SnapshotInvocationHandler(mbsc); return (SnapshotMBeanServerConnection) Proxy.newProxyInstance(Snapshot.class.getClassLoader(), new Class[] { SnapshotMBeanServerConnection.class }, ih); }
Flush all cached values of attributes.
newSnapshot
java
DarLiner/vjtools
vjtop/src/main/java/com/vip/vjtools/vjtop/data/jmx/JmxClient.java
https://github.com/DarLiner/vjtools/blob/master/vjtop/src/main/java/com/vip/vjtools/vjtop/data/jmx/JmxClient.java
Apache-2.0
synchronized void flush() { cachedValues = newMap(); }
Flush all cached values of attributes.
flush
java
DarLiner/vjtools
vjtop/src/main/java/com/vip/vjtools/vjtop/data/jmx/JmxClient.java
https://github.com/DarLiner/vjtools/blob/master/vjtop/src/main/java/com/vip/vjtools/vjtop/data/jmx/JmxClient.java
Apache-2.0
@Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { final String methodName = method.getName(); if (methodName.equals("getAttribute")) { return getAttribute((ObjectName) args[0], (String) args[1]); } else if (methodName.equals("getAttributes")) { return getAttributes((ObjectName) args[0], (String[]) args[1]); } else if (methodName.equals("flush")) { flush(); return null; } else { try { return method.invoke(conn, args); } catch (InvocationTargetException e) { throw e.getCause(); } } }
Flush all cached values of attributes.
invoke
java
DarLiner/vjtools
vjtop/src/main/java/com/vip/vjtools/vjtop/data/jmx/JmxClient.java
https://github.com/DarLiner/vjtools/blob/master/vjtop/src/main/java/com/vip/vjtools/vjtop/data/jmx/JmxClient.java
Apache-2.0
private Object getAttribute(ObjectName objName, String attrName) throws MBeanException, InstanceNotFoundException, AttributeNotFoundException, ReflectionException, IOException { final NameValueMap values = getCachedAttributes(objName, Collections.singleton(attrName)); Object value = values.get(attrName); if (value != null || values.containsKey(attrName)) { return value; } // Not in cache, presumably because it was omitted from the // getAttributes result because of an exception. Following // call will probably provoke the same exception. return conn.getAttribute(objName, attrName); }
Flush all cached values of attributes.
getAttribute
java
DarLiner/vjtools
vjtop/src/main/java/com/vip/vjtools/vjtop/data/jmx/JmxClient.java
https://github.com/DarLiner/vjtools/blob/master/vjtop/src/main/java/com/vip/vjtools/vjtop/data/jmx/JmxClient.java
Apache-2.0
private AttributeList getAttributes(ObjectName objName, String[] attrNames) throws InstanceNotFoundException, ReflectionException, IOException { final NameValueMap values = getCachedAttributes(objName, new TreeSet<String>(Arrays.asList(attrNames))); final AttributeList list = new AttributeList(); for (String attrName : attrNames) { final Object value = values.get(attrName); if (value != null || values.containsKey(attrName)) { list.add(new Attribute(attrName, value)); } } return list; }
Flush all cached values of attributes.
getAttributes
java
DarLiner/vjtools
vjtop/src/main/java/com/vip/vjtools/vjtop/data/jmx/JmxClient.java
https://github.com/DarLiner/vjtools/blob/master/vjtop/src/main/java/com/vip/vjtools/vjtop/data/jmx/JmxClient.java
Apache-2.0
private synchronized NameValueMap getCachedAttributes(ObjectName objName, Set<String> attrNames) throws InstanceNotFoundException, ReflectionException, IOException { NameValueMap values = cachedValues.get(objName); if (values != null && values.keySet().containsAll(attrNames)) { return values; } attrNames = new TreeSet<String>(attrNames); Set<String> oldNames = cachedNames.get(objName); if (oldNames != null) { attrNames.addAll(oldNames); } values = new NameValueMap(); final AttributeList attrs = conn.getAttributes(objName, attrNames.toArray(new String[attrNames.size()])); for (Attribute attr : attrs.asList()) { values.put(attr.getName(), attr.getValue()); } cachedValues.put(objName, values); cachedNames.put(objName, attrNames); return values; }
Flush all cached values of attributes.
getCachedAttributes
java
DarLiner/vjtools
vjtop/src/main/java/com/vip/vjtools/vjtop/data/jmx/JmxClient.java
https://github.com/DarLiner/vjtools/blob/master/vjtop/src/main/java/com/vip/vjtools/vjtop/data/jmx/JmxClient.java
Apache-2.0
private static <K, V> Map<K, V> newMap() { return new HashMap<K, V>(); }
Flush all cached values of attributes.
newMap
java
DarLiner/vjtools
vjtop/src/main/java/com/vip/vjtools/vjtop/data/jmx/JmxClient.java
https://github.com/DarLiner/vjtools/blob/master/vjtop/src/main/java/com/vip/vjtools/vjtop/data/jmx/JmxClient.java
Apache-2.0
public ListNode addTwoNumbers(ListNode l1, ListNode l2) { ListNode current1 = l1; ListNode current2 = l2; ListNode head = new ListNode(0); ListNode currentHead = head; int sum = 0; while(current1 != null || current2 != null) { sum /= 10; if(current1 != null) { sum += current1.val; current1 = current1.next; } if(current2 != null) { sum += current2.val; current2 = current2.next; } currentHead.next = new ListNode(sum % 10); currentHead = currentHead.next; } if(sum / 10 == 1) { currentHead.next = new ListNode(1); } return head.next; }
Definition for singly-linked list. public class ListNode { int val; ListNode next; ListNode(int x) { val = x; } }
addTwoNumbers
java
kdn251/interviews
company/airbnb/AddTwoNumbers.java
https://github.com/kdn251/interviews/blob/master/company/airbnb/AddTwoNumbers.java
MIT
public TreeNode sortedArrayToBST(int[] nums) { if(nums.length == 0) { return null; } TreeNode root = helper(nums, 0, nums.length - 1); return root; }
Definition for a binary tree node. public class TreeNode { int val; TreeNode left; TreeNode right; TreeNode(int x) { val = x; } }
sortedArrayToBST
java
kdn251/interviews
company/airbnb/ConvertSortedArrayToBinarySearchTree.java
https://github.com/kdn251/interviews/blob/master/company/airbnb/ConvertSortedArrayToBinarySearchTree.java
MIT
private TreeNode helper(int[] nums, int start, int end) { if(start <= end) { int mid = (start + end) / 2; TreeNode current = new TreeNode(nums[mid]); current.left = helper(nums, start, mid - 1); current.right = helper(nums, mid + 1, end); return current; } return null; }
Definition for a binary tree node. public class TreeNode { int val; TreeNode left; TreeNode right; TreeNode(int x) { val = x; } }
helper
java
kdn251/interviews
company/airbnb/ConvertSortedArrayToBinarySearchTree.java
https://github.com/kdn251/interviews/blob/master/company/airbnb/ConvertSortedArrayToBinarySearchTree.java
MIT
public ListNode mergeKLists(ListNode[] lists) { if (lists==null||lists.length==0) { return null; } PriorityQueue<ListNode> queue= new PriorityQueue<ListNode>(lists.length,new Comparator<ListNode>(){ @Override public int compare(ListNode o1,ListNode o2){ if (o1.val<o2.val) { return -1; } else if (o1.val==o2.val) { return 0; } else { return 1; } } }); ListNode dummy = new ListNode(0); ListNode tail=dummy; for (ListNode node:lists) { if (node!=null) { queue.add(node); } } while (!queue.isEmpty()) { tail.next=queue.poll(); tail=tail.next; if (tail.next!=null) { queue.add(tail.next); } } return dummy.next; }
Definition for singly-linked list. public class ListNode { int val; ListNode next; ListNode(int x) { val = x; } }
mergeKLists
java
kdn251/interviews
company/airbnb/MergeKSortedLists.java
https://github.com/kdn251/interviews/blob/master/company/airbnb/MergeKSortedLists.java
MIT
@Override public int compare(ListNode o1,ListNode o2){ if (o1.val<o2.val) { return -1; } else if (o1.val==o2.val) { return 0; } else { return 1; } }
Definition for singly-linked list. public class ListNode { int val; ListNode next; ListNode(int x) { val = x; } }
compare
java
kdn251/interviews
company/airbnb/MergeKSortedLists.java
https://github.com/kdn251/interviews/blob/master/company/airbnb/MergeKSortedLists.java
MIT
public ListNode addTwoNumbers(ListNode l1, ListNode l2) { ListNode current1 = l1; ListNode current2 = l2; ListNode head = new ListNode(0); ListNode currentHead = head; int sum = 0; while(current1 != null || current2 != null) { sum /= 10; if(current1 != null) { sum += current1.val; current1 = current1.next; } if(current2 != null) { sum += current2.val; current2 = current2.next; } currentHead.next = new ListNode(sum % 10); currentHead = currentHead.next; } if(sum / 10 == 1) { currentHead.next = new ListNode(1); } return head.next; }
Definition for singly-linked list. public class ListNode { int val; ListNode next; ListNode(int x) { val = x; } }
addTwoNumbers
java
kdn251/interviews
company/amazon/AddTwoNumbers.java
https://github.com/kdn251/interviews/blob/master/company/amazon/AddTwoNumbers.java
MIT
public List<List<Integer>> levelOrder(TreeNode root) { List<List<Integer>> result = new ArrayList<List<Integer>>(); if(root == null) { return result; } Queue<TreeNode> queue = new LinkedList<TreeNode>(); queue.add(root); List<Integer> tempList = new ArrayList<Integer>(); tempList.add(root.val); result.add(tempList); while(!queue.isEmpty()) { Queue<TreeNode> currentLevel = new LinkedList<TreeNode>(); List<Integer> list = new ArrayList<Integer>(); while(!queue.isEmpty()) { TreeNode current = queue.remove(); if(current.left != null) { currentLevel.add(current.left); list.add(current.left.val); } if(current.right != null) { currentLevel.add(current.right); list.add(current.right.val); } } if(list.size() > 0) { result.add(list); } queue = currentLevel; } return result; }
Definition for a binary tree node. public class TreeNode { int val; TreeNode left; TreeNode right; TreeNode(int x) { val = x; } }
levelOrder
java
kdn251/interviews
company/amazon/BinaryTreeLevelOrderTraversal.java
https://github.com/kdn251/interviews/blob/master/company/amazon/BinaryTreeLevelOrderTraversal.java
MIT
public boolean insert(int val) { if(!map.containsKey(val)) { map.put(val, val); values.add(val); return true; } else { return false; } }
Inserts a value to the set. Returns true if the set did not already contain the specified element.
insert
java
kdn251/interviews
company/amazon/InsertDeleteGetRandomO1.java
https://github.com/kdn251/interviews/blob/master/company/amazon/InsertDeleteGetRandomO1.java
MIT
public boolean remove(int val) { if(map.containsKey(val)) { map.remove(val); values.remove(values.indexOf(val)); return true; } return false; }
Removes a value from the set. Returns true if the set contained the specified element.
remove
java
kdn251/interviews
company/amazon/InsertDeleteGetRandomO1.java
https://github.com/kdn251/interviews/blob/master/company/amazon/InsertDeleteGetRandomO1.java
MIT
public int getRandom() { int random = (int)(Math.random() * values.size()); int valueToReturn = values.get(random); return map.get(valueToReturn); }
Get a random element from the set.
getRandom
java
kdn251/interviews
company/amazon/InsertDeleteGetRandomO1.java
https://github.com/kdn251/interviews/blob/master/company/amazon/InsertDeleteGetRandomO1.java
MIT
public boolean hasCycle(ListNode head) { if(head == null || head.next == null) { return false; } ListNode slow = head; ListNode fast = head.next; while(fast != null && fast.next != null && fast != slow) { slow = slow.next; fast = fast.next.next; } return fast == slow; }
Definition for singly-linked list. class ListNode { int val; ListNode next; ListNode(int x) { val = x; next = null; } }
hasCycle
java
kdn251/interviews
company/amazon/LinkedListCycle.java
https://github.com/kdn251/interviews/blob/master/company/amazon/LinkedListCycle.java
MIT
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { if(root == null || root == p || root == q) { return root; } TreeNode left = lowestCommonAncestor(root.left, p, q); TreeNode right = lowestCommonAncestor(root.right, p, q); if(left != null && right != null) { return root; } return left == null ? right : left; }
Definition for a binary tree node. public class TreeNode { int val; TreeNode left; TreeNode right; TreeNode(int x) { val = x; } }
lowestCommonAncestor
java
kdn251/interviews
company/amazon/LowestCommonAncestorOfABinaryTree.java
https://github.com/kdn251/interviews/blob/master/company/amazon/LowestCommonAncestorOfABinaryTree.java
MIT
public ListNode mergeKLists(ListNode[] lists) { if (lists==null||lists.length==0) { return null; } PriorityQueue<ListNode> queue= new PriorityQueue<ListNode>(lists.length,new Comparator<ListNode>(){ @Override public int compare(ListNode o1,ListNode o2){ if (o1.val<o2.val) { return -1; } else if (o1.val==o2.val) { return 0; } else { return 1; } } }); ListNode dummy = new ListNode(0); ListNode tail=dummy; for (ListNode node:lists) { if (node!=null) { queue.add(node); } } while (!queue.isEmpty()){ tail.next=queue.poll(); tail=tail.next; if (tail.next!=null) { queue.add(tail.next); } } return dummy.next; }
Definition for singly-linked list. public class ListNode { int val; ListNode next; ListNode(int x) { val = x; } }
mergeKLists
java
kdn251/interviews
company/amazon/MergeKSortedLists.java
https://github.com/kdn251/interviews/blob/master/company/amazon/MergeKSortedLists.java
MIT
@Override public int compare(ListNode o1,ListNode o2){ if (o1.val<o2.val) { return -1; } else if (o1.val==o2.val) { return 0; } else { return 1; } }
Definition for singly-linked list. public class ListNode { int val; ListNode next; ListNode(int x) { val = x; } }
compare
java
kdn251/interviews
company/amazon/MergeKSortedLists.java
https://github.com/kdn251/interviews/blob/master/company/amazon/MergeKSortedLists.java
MIT
public boolean isPalindrome(ListNode head) { if(head == null || head.next == null) { return true; } Stack<Integer> stack = new Stack<Integer>(); ListNode fast = head; ListNode slow = head; while(fast != null && fast.next != null) { stack.push(slow.val); fast = fast.next.next; slow = slow.next; } if(fast != null) { slow = slow.next; } while(slow != null) { if(stack.pop() != slow.val) { return false; } slow = slow.next; } return true; }
Definition for singly-linked list. public class ListNode { int val; ListNode next; ListNode(int x) { val = x; } }
isPalindrome
java
kdn251/interviews
company/amazon/PalindromeLinkedList.java
https://github.com/kdn251/interviews/blob/master/company/amazon/PalindromeLinkedList.java
MIT
public ListNode reverseList(ListNode head) { if(head == null) { return head; } ListNode newHead = null; while(head != null) { ListNode next = head.next; head.next = newHead; newHead = head; head = next; } return newHead; }
Definition for singly-linked list. public class ListNode { int val; ListNode next; ListNode(int x) { val = x; } }
reverseList
java
kdn251/interviews
company/amazon/ReverseLinkedList.java
https://github.com/kdn251/interviews/blob/master/company/amazon/ReverseLinkedList.java
MIT
public boolean isValidBST(TreeNode root) { if(root == null) { return true; } return validBSTRecursive(root, Long.MIN_VALUE, Long.MAX_VALUE); }
Definition for a binary tree node. public class TreeNode { int val; TreeNode left; TreeNode right; TreeNode(int x) { val = x; } }
isValidBST
java
kdn251/interviews
company/amazon/ValidateBinarySearchTree.java
https://github.com/kdn251/interviews/blob/master/company/amazon/ValidateBinarySearchTree.java
MIT
public boolean validBSTRecursive(TreeNode root, long minValue, long maxValue) { if(root == null) { return true; } else if(root.val >= maxValue || root.val <= minValue) { return false; } else { return validBSTRecursive(root.left, minValue, root.val) && validBSTRecursive(root.right, root.val, maxValue); } }
Definition for a binary tree node. public class TreeNode { int val; TreeNode left; TreeNode right; TreeNode(int x) { val = x; } }
validBSTRecursive
java
kdn251/interviews
company/amazon/ValidateBinarySearchTree.java
https://github.com/kdn251/interviews/blob/master/company/amazon/ValidateBinarySearchTree.java
MIT
public boolean hasCycle(ListNode head) { if(head == null || head.next == null) { return false; } ListNode slow = head; ListNode fast = head.next; while(fast != null && fast.next != null && fast != slow) { slow = slow.next; fast = fast.next.next; } return fast == slow; }
Definition for singly-linked list. class ListNode { int val; ListNode next; ListNode(int x) { val = x; next = null; } }
hasCycle
java
kdn251/interviews
company/bloomberg/LinkedListCycle.java
https://github.com/kdn251/interviews/blob/master/company/bloomberg/LinkedListCycle.java
MIT
public boolean hasNext() { return stack.isEmpty() ? false : true; }
@return whether we have a next smallest number
hasNext
java
kdn251/interviews
company/facebook/BinarySearchTreeIterator.java
https://github.com/kdn251/interviews/blob/master/company/facebook/BinarySearchTreeIterator.java
MIT
public List<List<Integer>> levelOrder(TreeNode root) { List<List<Integer>> result = new ArrayList<List<Integer>>(); if(root == null) { return result; } Queue<TreeNode> queue = new LinkedList<TreeNode>(); queue.add(root); List<Integer> tempList = new ArrayList<Integer>(); tempList.add(root.val); result.add(tempList); while(!queue.isEmpty()) { Queue<TreeNode> currentLevel = new LinkedList<TreeNode>(); List<Integer> list = new ArrayList<Integer>(); while(!queue.isEmpty()) { TreeNode current = queue.remove(); if(current.left != null) { currentLevel.add(current.left); list.add(current.left.val); } if(current.right != null) { currentLevel.add(current.right); list.add(current.right.val); } } if(list.size() > 0) { result.add(list); } queue = currentLevel; } return result; }
Definition for a binary tree node. public class TreeNode { int val; TreeNode left; TreeNode right; TreeNode(int x) { val = x; } }
levelOrder
java
kdn251/interviews
company/facebook/BinaryTreeLevelOrderTraversal.java
https://github.com/kdn251/interviews/blob/master/company/facebook/BinaryTreeLevelOrderTraversal.java
MIT
public List<String> binaryTreePaths(TreeNode root) { List<String> result = new ArrayList<String>(); if(root == null) { return result; } helper(new String(), root, result); return result; }
Definition for a binary tree node. public class TreeNode { int val; TreeNode left; TreeNode right; TreeNode(int x) { val = x; } }
binaryTreePaths
java
kdn251/interviews
company/facebook/BinaryTreePaths.java
https://github.com/kdn251/interviews/blob/master/company/facebook/BinaryTreePaths.java
MIT
public void helper(String current, TreeNode root, List<String> result) { if(root.left == null && root.right == null) { result.add(current + root.val); } if(root.left != null) { helper(current + root.val + "->", root.left, result); } if(root.right != null) { helper(current + root.val + "->", root.right, result); } }
Definition for a binary tree node. public class TreeNode { int val; TreeNode left; TreeNode right; TreeNode(int x) { val = x; } }
helper
java
kdn251/interviews
company/facebook/BinaryTreePaths.java
https://github.com/kdn251/interviews/blob/master/company/facebook/BinaryTreePaths.java
MIT
public List<List<Integer>> verticalOrder(TreeNode root) { List<List<Integer>> result = new ArrayList<>(); if(root == null) { return result; } Map<Integer, ArrayList<Integer>> map = new HashMap<>(); Queue<TreeNode> q = new LinkedList<>(); Queue<Integer> cols = new LinkedList<>(); q.add(root); cols.add(0); int min = 0; int max = 0; while(!q.isEmpty()) { TreeNode node = q.poll(); int col = cols.poll(); if(!map.containsKey(col)) { map.put(col, new ArrayList<Integer>()); } map.get(col).add(node.val); if(node.left != null) { q.add(node.left); cols.add(col - 1); min = Math.min(min, col - 1); } if(node.right != null) { q.add(node.right); cols.add(col + 1); max = Math.max(max, col + 1); } } for(int i = min; i <= max; i++) { result.add(map.get(i)); } return result; }
Definition for a binary tree node. public class TreeNode { int val; TreeNode left; TreeNode right; TreeNode(int x) { val = x; } }
verticalOrder
java
kdn251/interviews
company/facebook/BinaryTreeVerticalOrderTraversal.java
https://github.com/kdn251/interviews/blob/master/company/facebook/BinaryTreeVerticalOrderTraversal.java
MIT
public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) { if(node == null) { return null; } if(map.containsKey(node.label)) { return map.get(node.label); } UndirectedGraphNode newNode = new UndirectedGraphNode(node.label); map.put(newNode.label, newNode); for(UndirectedGraphNode neighbor : node.neighbors) { newNode.neighbors.add(cloneGraph(neighbor)); } return newNode; }
Definition for undirected graph. class UndirectedGraphNode { int label; List<UndirectedGraphNode> neighbors; UndirectedGraphNode(int x) { label = x; neighbors = new ArrayList<UndirectedGraphNode>(); } };
cloneGraph
java
kdn251/interviews
company/facebook/CloneGraph.java
https://github.com/kdn251/interviews/blob/master/company/facebook/CloneGraph.java
MIT
@Override public Integer next() { return stack.pop().getInteger(); }
// This is the interface that allows for creating nested lists. // You should not implement it, or speculate about its implementation public interface NestedInteger { // @return true if this NestedInteger holds a single integer, rather than a nested list. public boolean isInteger(); // @return the single integer that this NestedInteger holds, if it holds a single integer // Return null if this NestedInteger holds a nested list public Integer getInteger(); // @return the nested list that this NestedInteger holds, if it holds a nested list // Return null if this NestedInteger holds a single integer public List<NestedInteger> getList(); }
next
java
kdn251/interviews
company/facebook/FlattenNestedListIterator.java
https://github.com/kdn251/interviews/blob/master/company/facebook/FlattenNestedListIterator.java
MIT
@Override public boolean hasNext() { while(!stack.isEmpty()) { NestedInteger current = stack.peek(); if(current.isInteger()) { return true; } stack.pop(); for(int i = current.getList().size() - 1; i >= 0; i--) { stack.push(current.getList().get(i)); } } return false; }
// This is the interface that allows for creating nested lists. // You should not implement it, or speculate about its implementation public interface NestedInteger { // @return true if this NestedInteger holds a single integer, rather than a nested list. public boolean isInteger(); // @return the single integer that this NestedInteger holds, if it holds a single integer // Return null if this NestedInteger holds a nested list public Integer getInteger(); // @return the nested list that this NestedInteger holds, if it holds a nested list // Return null if this NestedInteger holds a single integer public List<NestedInteger> getList(); }
hasNext
java
kdn251/interviews
company/facebook/FlattenNestedListIterator.java
https://github.com/kdn251/interviews/blob/master/company/facebook/FlattenNestedListIterator.java
MIT
public TreeNode inorderSuccessor(TreeNode root, TreeNode p) { TreeNode successor = null; while(root != null) { if(p.val < root.val) { successor = root; root = root.left; } else { root = root.right; } } return successor; }
Definition for a binary tree node. public class TreeNode { int val; TreeNode left; TreeNode right; TreeNode(int x) { val = x; } }
inorderSuccessor
java
kdn251/interviews
company/facebook/InorderSuccessorInBST.java
https://github.com/kdn251/interviews/blob/master/company/facebook/InorderSuccessorInBST.java
MIT
public boolean insert(int val) { if(!map.containsKey(val)) { map.put(val, val); values.add(val); return true; } else { return false; } }
Inserts a value to the set. Returns true if the set did not already contain the specified element.
insert
java
kdn251/interviews
company/facebook/InsertDeleteGetRandomO1.java
https://github.com/kdn251/interviews/blob/master/company/facebook/InsertDeleteGetRandomO1.java
MIT
public boolean remove(int val) { if(map.containsKey(val)) { map.remove(val); values.remove(values.indexOf(val)); return true; } return false; }
Removes a value from the set. Returns true if the set contained the specified element.
remove
java
kdn251/interviews
company/facebook/InsertDeleteGetRandomO1.java
https://github.com/kdn251/interviews/blob/master/company/facebook/InsertDeleteGetRandomO1.java
MIT
public int getRandom() { int random = (int)(Math.random() * values.size()); int valueToReturn = values.get(random); return map.get(valueToReturn); }
Get a random element from the set.
getRandom
java
kdn251/interviews
company/facebook/InsertDeleteGetRandomO1.java
https://github.com/kdn251/interviews/blob/master/company/facebook/InsertDeleteGetRandomO1.java
MIT
public List<Interval> insert(List<Interval> intervals, Interval newInterval) { int i = 0; while(i < intervals.size() && intervals.get(i).end < newInterval.start) { i++; } while(i < intervals.size() && intervals.get(i).start <= newInterval.end) { newInterval = new Interval(Math.min(intervals.get(i).start, newInterval.start), Math.max(intervals.get(i).end, newInterval.end)); intervals.remove(i); } intervals.add(i, newInterval); return intervals; }
Definition for an interval. public class Interval { int start; int end; Interval() { start = 0; end = 0; } Interval(int s, int e) { start = s; end = e; } }
insert
java
kdn251/interviews
company/facebook/InsertInterval.java
https://github.com/kdn251/interviews/blob/master/company/facebook/InsertInterval.java
MIT
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { if(root == null || root == p || root == q) { return root; } TreeNode left = lowestCommonAncestor(root.left, p, q); TreeNode right = lowestCommonAncestor(root.right, p, q); if(left != null && right != null) { return root; } return left == null ? right : left; }
Definition for a binary tree node. public class TreeNode { int val; TreeNode left; TreeNode right; TreeNode(int x) { val = x; } }
lowestCommonAncestor
java
kdn251/interviews
company/facebook/LowestCommonAncestorOfABinaryTree.java
https://github.com/kdn251/interviews/blob/master/company/facebook/LowestCommonAncestorOfABinaryTree.java
MIT
public boolean canAttendMeetings(Interval[] intervals) { if(intervals == null) { return false; } // Sort the intervals by start time Arrays.sort(intervals, new Comparator<Interval>() { public int compare(Interval a, Interval b) { return a.start - b.start; } }); for(int i = 1; i < intervals.length; i++) { if(intervals[i].start < intervals[i - 1].end) { return false; } } return true; }
Definition for an interval. public class Interval { int start; int end; Interval() { start = 0; end = 0; } Interval(int s, int e) { start = s; end = e; } }
canAttendMeetings
java
kdn251/interviews
company/facebook/MeetingRooms.java
https://github.com/kdn251/interviews/blob/master/company/facebook/MeetingRooms.java
MIT
public List<Interval> merge(List<Interval> intervals) { List<Interval> result = new ArrayList<Interval>(); if(intervals == null || intervals.size() == 0) { return result; } Interval[] allIntervals = intervals.toArray(new Interval[intervals.size()]); Arrays.sort(allIntervals, new Comparator<Interval>() { public int compare(Interval a, Interval b) { if(a.start == b.start) { return a.end - b.end; } return a.start - b.start; } }); for(Interval i: allIntervals) { if (result.size() == 0 || result.get(result.size() - 1).end < i.start) { result.add(i); } else { result.get(result.size() - 1).end = Math.max(result.get(result.size() - 1).end, i.end); } } return result; }
Definition for an interval. public class Interval { int start; int end; Interval() { start = 0; end = 0; } Interval(int s, int e) { start = s; end = e; } }
merge
java
kdn251/interviews
company/facebook/MergeIntervals.java
https://github.com/kdn251/interviews/blob/master/company/facebook/MergeIntervals.java
MIT
public int compare(Interval a, Interval b) { if(a.start == b.start) { return a.end - b.end; } return a.start - b.start; }
Definition for an interval. public class Interval { int start; int end; Interval() { start = 0; end = 0; } Interval(int s, int e) { start = s; end = e; } }
compare
java
kdn251/interviews
company/facebook/MergeIntervals.java
https://github.com/kdn251/interviews/blob/master/company/facebook/MergeIntervals.java
MIT