code
stringlengths
73
34.1k
label
stringclasses
1 value
public static LocalDocument findLocalDocumentByParentAndUrlName(Folder parentFolder, String urlName) { ResourceDAO resourceDAO = new ResourceDAO(); Resource resource = resourceDAO.findByUrlNameAndParentFolder(urlName, parentFolder); if (resource instanceof LocalDocument) { return (LocalDocument) ...
java
protected OffsetDateTime translateDate(Date date) { if (date == null) { return null; } return OffsetDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault()); }
java
protected UUID translateUserId(User user) { if (user == null) { return null; } return userController.getUserKeycloakId(user); }
java
public String getCommentLabel(Long id) { Map<String, String> valueMap = answers.get(id); if (valueMap != null && !valueMap.isEmpty()) { Set<Entry<String,String>> entrySet = valueMap.entrySet(); List<String> labels = entrySet.stream() .map(entry -> String.format("%s / %s", entry.getKey(), ent...
java
protected void setCommentLabel(Long id, String caption, String value) { Map<String, String> valueMap = answers.get(id); if (valueMap == null) { valueMap = new LinkedHashMap<>(); } valueMap.put(caption, value); answers.put(id, valueMap); }
java
private List<QueryQuestionComment> listRootComments() { QueryQuestionCommentDAO queryQuestionCommentDAO = new QueryQuestionCommentDAO(); return queryQuestionCommentDAO.listRootCommentsByQueryPageAndStampOrderByCreated(queryPage, panelStamp); }
java
private boolean isPanelUser(JdbcConnection connection, Long panelId, String email) throws CustomChangeException { try (PreparedStatement statement = connection.prepareStatement("SELECT id FROM PANELUSER WHERE panel_id = ? AND user_id = (SELECT id FROM USEREMAIL WHERE address = ?)")) { statement.setLong(1, pan...
java
private void deleteInvitation(JdbcConnection connection, Long id) throws CustomChangeException { try (PreparedStatement statement = connection.prepareStatement("DELETE FROM PANELINVITATION WHERE id = ?")) { statement.setLong(1, id); statement.execute(); } catch (Exception e) { throw new Custom...
java
public Double getQuantile(int quantile, int base) { if (getCount() == 0) return null; if ((quantile > base) || (quantile <= 0) || (base <= 0)) throw new IllegalArgumentException("Incorrect quantile/base specified."); double quantileFraq = (double) quantile / base; int index = ...
java
private QueryFieldDataStatistics createStatistics(List<Double> data, double min, double max, double step) { Map<Double, String> dataNames = new HashMap<>(); for (double d = min; d <= max; d += step) { String caption = step % 1 == 0 ? Long.toString(Math.round(d)) : Double.toString(d); dataNames....
java
@Deprecated public List<List<String>> getParsedArgs(String[] args) throws InvalidFormatException { for (int i = 0; i < args.length; i++) { if (!args[i].startsWith("-")) { if (this.params.size() > 0) { List<String> option = new ArrayList<String>(); option.add(this.params.get(0).longOption); t...
java
@Deprecated public void addArguments(String[] argList) throws DuplicateOptionException, InvalidFormatException { for (String arg : argList) { Argument f = new Argument(); String[] breakdown = arg.split(","); for (String s : breakdown) { s = s.trim(); if (s.startsWith("--")) { f.longOption = ...
java
@Deprecated public void addArgument(char shortForm, String longForm, String helpText, boolean isParameter, boolean takesValue, boolean valueRequired) throws DuplicateOptionException { Argument f = new Argument(); f.option = "" + shortForm; f.longOption = longForm; f.takesValue = takesValue; f.valueRequ...
java
public void add(JDesktopPaneLayout child, Object constraints, int index) { if (child.parent != this) { throw new IllegalArgumentException( "Layout is not a child of this layout"); } container.add(child.container, constraints, index); }
java
public void remove(JDesktopPaneLayout child) { if (child.parent != this) { throw new IllegalArgumentException( "Layout is not a child of this layout"); } container.remove(child.container); }
java
public void validate() { Dimension size = desktopPane.getSize(); size.height -= computeDesktopIconsSpace(); layoutInternalFrames(size); }
java
private int computeDesktopIconsSpace() { for (JInternalFrame f : frameToComponent.keySet()) { if (f.isIcon()) { JDesktopIcon desktopIcon = f.getDesktopIcon(); return desktopIcon.getPreferredSize().height; } } ...
java
private void callDoLayout(Container container) { container.doLayout(); int n = container.getComponentCount(); for (int i=0; i<n; i++) { Component component = container.getComponent(i); if (component instanceof Container) { ...
java
private void applyLayout() { int n = container.getComponentCount(); for (int i=0; i<n; i++) { Component component = container.getComponent(i); if (component instanceof FrameComponent) { FrameComponent frameComponent = (FrameComponen...
java
public void addData(final BenchmarkMethod meth, final AbstractMeter meter, final double data) { final Class<?> clazz = meth.getMethodToBench().getDeclaringClass(); if (!elements.containsKey(clazz)) { elements.put(clazz, new ClassResult(clazz)); } final ClassResult clazzResu...
java
public void addException(final AbstractPerfidixMethodException exec) { this.getExceptions().add(exec); for (final AbstractOutput output : outputs) { output.listenToException(exec); } }
java
static Action create(Runnable command) { Objects.requireNonNull(command, "The command may not be null"); return new AbstractAction() { /** * Serial UID */ private static final long serialVersionUID = 8693271079128413874L; ...
java
public void doAESEncryption() throws Exception{ if(!initAESDone) initAES(); cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); //System.out.println(secretKey.getEncoded()); cipher.init(Cipher.ENCRYPT_MODE, secretKey); AlgorithmParameters params = cipher.getParameters(); iv = params.getParameterSpec(IvP...
java
public static JPanel wrapTitled(String title, JComponent component) { JPanel p = new JPanel(new GridLayout(1,1)); p.setBorder(BorderFactory.createTitledBorder(title)); p.add(component); return p; }
java
public static JPanel wrapFlow(JComponent component) { JPanel p = new JPanel(new FlowLayout(FlowLayout.CENTER, 0, 0)); p.add(component); return p; }
java
public static void setDeepEnabled(Component component, boolean enabled) { component.setEnabled(enabled); if (component instanceof Container) { Container container = (Container)component; for (Component c : container.getComponents()) { ...
java
static int indexOf(String source, String target, int startIndex, boolean ignoreCase) { if (ignoreCase) { return indexOf(source, target, startIndex, IGNORING_CASE); } return indexOf(source, target, startIndex, (c0, c1) -> Integer.compare(c0, c...
java
private static int indexOf(String source, String target, int startIndex, IntBinaryOperator comparator) { return indexOf( source, 0, source.length(), target, 0, target.length(), startIndex, comparator); }
java
private static int indexOf( String source, int sourceOffset, int sourceCount, String target, int targetOffset, int targetCount, int startIndex, IntBinaryOperator comparator) { int fromIndex = startIndex; // Adapted from String#indexOf if (fromIndex >...
java
private static int lastIndexOf(String source, String target, int startIndex, IntBinaryOperator comparator) { return lastIndexOf( source, 0, source.length(), target, 0, target.length(), startIndex, comparator); }
java
static int lastIndexOf( String source, int sourceOffset, int sourceCount, String target, int targetOffset, int targetCount, int startIndex, IntBinaryOperator comparator) { int fromIndex = startIndex; // Adapted from String#lastIndexOf int rightIndex ...
java
Observable<ComapiResult<MessagesQueryResponse>> doQueryMessages(@NonNull final String token, @NonNull final String conversationId, final Long from, @NonNull final Integer limit) { return wrapObservable(service.queryMessages(AuthManager.addAuthPrefix(token), apiSpaceId, conversationId, from, limit).map(mapToComa...
java
Observable<ComapiResult<Void>> doIsTyping(@NonNull final String token, @NonNull final String conversationId, final boolean isTyping) { if (isTyping) { return wrapObservable(service.isTyping(AuthManager.addAuthPrefix(token), apiSpaceId, conversationId).map(mapToComapiResult()), log, "Sending is typin...
java
@Override public void init(Key key, IvParameterSpec iv) throws InvalidKeyException { if(!(key instanceof SecretKey)) throw new InvalidKeyException(); int ivLength = iv.getIV().length; if(key.getEncoded().length < MIN_KEY_SIZE || key.getEncoded().length < ivLength) throw new InvalidKeyException("Key must be...
java
private void onParticipantIsTyping(ParticipantTypingEvent event) { handler.post(() -> listener.onParticipantIsTyping(event)); log("Event published " + event.toString()); }
java
private void onParticipantTypingOff(ParticipantTypingOffEvent event) { handler.post(() -> listener.onParticipantTypingOff(event)); log("Event published " + event.toString()); }
java
private void onProfileUpdate(ProfileUpdateEvent event) { handler.post(() -> listener.onProfileUpdate(event)); log("Event published " + event.toString()); }
java
private void onMessageSent(MessageSentEvent event) { handler.post(() -> listener.onMessageSent(event)); log("Event published " + event.toString()); }
java
private void onSocketStarted(SocketStartEvent event) { handler.post(() -> listener.onSocketStarted(event)); log("Event published " + event.toString()); }
java
private void onParticipantAdded(ParticipantAddedEvent event) { handler.post(() -> listener.onParticipantAdded(event)); log("Event published " + event.toString()); }
java
private void onParticipantUpdated(ParticipantUpdatedEvent event) { handler.post(() -> listener.onParticipantUpdated(event)); log("Event published " + event.toString()); }
java
private void onParticipantRemoved(ParticipantRemovedEvent event) { handler.post(() -> listener.onParticipantRemoved(event)); log("Event published " + event.toString()); }
java
private void onConversationUpdated(ConversationUpdateEvent event) { handler.post(() -> listener.onConversationUpdated(event)); log("Event published " + event.toString()); }
java
private void onConversationDeleted(ConversationDeleteEvent event) { handler.post(() -> listener.onConversationDeleted(event)); log("Event published " + event.toString()); }
java
private void onConversationUndeleted(ConversationUndeleteEvent event) { handler.post(() -> listener.onConversationUndeleted(event)); log("Event published " + event.toString()); }
java
protected String getToken() { return dataMgr.getSessionDAO().session() != null ? dataMgr.getSessionDAO().session().getAccessToken() : null; }
java
public void init(@NonNull final Context context, @Nullable final String suffix, @NonNull final Logger log) { deviceDAO = new DeviceDAO(context, suffix); onetimeDeviceSetup(context); logInfo(log); sessionDAO = new SessionDAO(context, suffix); }
java
private void logInfo(@NonNull final Logger log) { log.i("App ver. = " + deviceDAO.device().getAppVer()); log.i("Comapi device ID = " + deviceDAO.device().getDeviceId()); log.d("Firebase ID = " + deviceDAO.device().getInstanceId()); }
java
private static <T> Stream<T> enumerationAsStream(Enumeration<? extends T> e) { Iterator<T> iterator = new Iterator<T>() { @Override public T next() { return e.nextElement(); } @Override public boolean...
java
public int getRowWidth() { int overallWidth = 0; for (int i = 0; i < data.length; i++) { overallWidth += getTable().getColumnWidth(i); } return overallWidth; }
java
public static byte[] shuffle(byte[] input){ for(int i=0; i<input.length; i++){ int i2 = input[i]; if(i2 < 0) i2 = 127 + Math.abs(i2); input[i] = shuffle[i2]; //result of more shuffles could just be mapped to the first // i2 = input[i]; // if(i2 < 0) // i2 = 127 + Math.abs(i2); // input[i] = (...
java
public static byte[] getSHA256(byte[] input, boolean asSingleton){ if(SHA256_INSTANCE == null){ if(asSingleton){ try { SHA256_INSTANCE = MessageDigest.getInstance("SHA-256"); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } }else{ return getHash("SHA-256", input); } ...
java
SocketInterface createSocket(@NonNull final String token, @NonNull final WeakReference<SocketStateListener> stateListenerWeakReference) { WebSocket socket = null; WebSocketFactory factory = new WebSocketFactory(); // Configure proxy if provided if (proxyAddress != null) { ...
java
protected WebSocketAdapter createWebSocketAdapter(@NonNull final WeakReference<SocketStateListener> stateListenerWeakReference) { return new WebSocketAdapter() { @Override public void onConnected(WebSocket websocket, Map<String, List<String>> headers) throws Exception { ...
java
public static int getNumberOfAnnotatedRuns(final Method meth) { if (!isBenchmarkable(meth)) { throw new IllegalArgumentException("Method " + meth + " must be a benchmarkable method."); } final Bench benchAnno = meth.getAnnotation(Bench.class); final BenchClass benchClassAnno = meth.getDeclaringClass() ...
java
public static Method findAndCheckAnyMethodByAnnotation( final Class<?> clazz, final Class<? extends Annotation> anno) throws PerfidixMethodCheckException { // needed variables, one for check for duplicates Method anyMethod = null; // Scanning all methods final Method[] possAnnoMethods = clazz.getDeclared...
java
public static boolean isBenchmarkable(final Method meth) { boolean returnVal = true; // Check if bench-anno is given. For testing purposes against // before/after annos final Bench benchAnno = meth.getAnnotation(Bench.class); // if method is annotated with SkipBench, the method is never // benchmarkable. ...
java
public static boolean isReflectedExecutable(final Method meth, final Class<? extends Annotation> anno) { boolean returnVal = true; // Check if DataProvider is valid if set. if (anno.equals(DataProvider.class) && !meth.getReturnType().isAssignableFrom(Object[][].class)) { returnVal = false; } // for ...
java
private Method findDataProvider() throws PerfidixMethodCheckException { final Bench benchAnno = getMethodToBench().getAnnotation(Bench.class); Method dataProvider = null; if (benchAnno != null && !benchAnno.dataProvider().equals("")) { try { // Getting the String name for the dataProvider final String...
java
public static void setDividerLocation( final JSplitPane splitPane, final double location) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { splitPane.setDividerLocation(location); splitPane...
java
private SessionData loadSession() { synchronized (sharedLock) { SharedPreferences sharedPreferences = getSharedPreferences(); String id = sharedPreferences.getString(KEY_PROFILE_ID, null); if (!TextUtils.isEmpty(id)) { sharedLock.notifyAll(); ...
java
public String clearSession() { synchronized (sharedLock) { SessionData session = loadSession(); String id = session != null ? session.getSessionId() : null; clearAll(); sharedLock.notifyAll(); return id; } }
java
public boolean startSession() { synchronized (sharedLock) { SessionData session = loadSession(); if (isSessionActive(session)) { sharedLock.notifyAll(); return false; } else { clearAll(); } sharedLock.no...
java
public boolean updateSessionDetails(final SessionData session) { synchronized (sharedLock) { if (session != null) { SharedPreferences.Editor editor = getSharedPreferences().edit(); editor.putString(KEY_PROFILE_ID, session.getProfileId()); editor.putSt...
java
public static Object fromJSON(String jsonString){ List<Token> tokens = Derulo.toTokens(jsonString); return fromJSON(tokens); }
java
final void add(final int e) { if (size == list.length) list = Arrays.copyOf(list, newSize()); list[size++] = e; }
java
public final boolean contains(final int e) { for (int i = 0; i < size; ++i) if (list[i] == e) return true; return false; }
java
public final void insert(final int i, final int[] e) { final int l = e.length; if (l == 0) return; if (size + l > list.length) list = Arrays.copyOf(list, newSize(size + l)); Array.move(list, i, l, size - i); System.arraycopy(e, 0, list, i, l); size += l; }
java
public static void expandAllFixedHeight(JTree tree) { // Determine a suitable row height for the tree, based on the // size of the component that is used for rendering the root TreeCellRenderer cellRenderer = tree.getCellRenderer(); Component treeCellRendererComponent = ...
java
private static void expandAllRecursively(JTree tree, TreePath treePath) { TreeModel model = tree.getModel(); Object lastPathComponent = treePath.getLastPathComponent(); int childCount = model.getChildCount(lastPathComponent); if (childCount == 0) { return; ...
java
public static void collapseAll(JTree tree, boolean omitRoot) { int rows = tree.getRowCount(); int limit = (omitRoot ? 1 : 0); for (int i = rows - 1; i >= limit; i--) { tree.collapseRow(i); } }
java
private static int countNodes(TreeModel treeModel, Object node) { int sum = 1; int n = treeModel.getChildCount(node); for (int i=0; i<n; i++) { sum += countNodes(treeModel, treeModel.getChild(node, i)); } return sum; }
java
public static List<Object> getChildren(TreeModel treeModel, Object node) { List<Object> children = new ArrayList<Object>(); int n = treeModel.getChildCount(node); for (int i=0; i<n; i++) { Object child = treeModel.getChild(node, i); children.add(child);...
java
public static List<Object> getAllNodes(TreeModel treeModel) { List<Object> result = new ArrayList<Object>(); getAllDescendants(treeModel, treeModel.getRoot(), result); result.add(0, treeModel.getRoot()); return result; }
java
private static void getAllDescendants( TreeModel treeModel, Object node, List<Object> result) { if (node == null) { return; } result.add(node); List<Object> children = getChildren(treeModel, node); for (Object child : children) { ...
java
public static List<Object> getLeafNodes(TreeModel treeModel, Object node) { List<Object> leafNodes = new ArrayList<Object>(); getLeafNodes(treeModel, node, leafNodes); return leafNodes; }
java
private static void getLeafNodes( TreeModel treeModel, Object node, Collection<Object> leafNodes) { if (node == null) { return; } int childCount = treeModel.getChildCount(node); if (childCount == 0) { leafNodes.add(node); ...
java
public static TreePath createTreePathToRoot( TreeModel treeModel, Object node) { List<Object> nodes = new ArrayList<Object>(); nodes.add(node); Object current = node; while (true) { Object parent = getParent(treeModel, current); if (pa...
java
public static List<TreePath> computeExpandedPaths(JTree tree) { List<TreePath> treePaths = new ArrayList<TreePath>(); int rows = tree.getRowCount(); for (int i = 0; i < rows; i++) { TreePath treePath = tree.getPathForRow(i); treePaths.add(treePath); ...
java
public static TreePath translatePath( TreeModel newTreeModel, TreePath oldPath) { return translatePath(newTreeModel, oldPath, Objects::equals); }
java
public static TreePath translatePath( TreeModel newTreeModel, TreePath oldPath, BiPredicate<Object, Object> equality) { Object newRoot = newTreeModel.getRoot(); List<Object> newPath = new ArrayList<Object>(); newPath.add(newRoot); Object newPreviousElement = n...
java
private static Object getChildWith(Object node, Object userObject, BiPredicate<Object, Object> equality) { DefaultMutableTreeNode treeNode = (DefaultMutableTreeNode)node; for (int j=0; j<treeNode.getChildCount(); j++) { TreeNode child = treeNode.getChildAt(j); ...
java
public static int computeIndexInParent(Object nodeObject) { if (nodeObject instanceof DefaultMutableTreeNode) { DefaultMutableTreeNode node = (DefaultMutableTreeNode)nodeObject; TreeNode parent = node.getParent(); if (parent == null) ...
java
private void layoutChild( Component component, int cellX, int cellY, int cellSizeX, int cellSizeY) { int maxAspectW = (int)(cellSizeY * aspect); int maxAspectH = (int)(cellSizeX / aspect); if (maxAspectW > cellSizeX) { int w = cellSizeX; ...
java
private static double computeWastedSpace( double maxSizeX, double maxSizeY, double aspect) { int maxAspectX = (int) (maxSizeY * aspect); int maxAspectY = (int) (maxSizeX / aspect); if (maxAspectX > maxSizeX) { double sizeX = maxSizeX; double si...
java
String formatMessage(int msgLogLevel, String tag, String msg, Throwable exception) { if (exception != null) { return DateHelper.getUTC(System.currentTimeMillis()) + "/" + getLevelTag(msgLogLevel) + tag + ": " + msg + "\n" + getStackTrace(exception) + "\n"; } else { return DateHel...
java
private String getStackTrace(final Throwable exception) { if (exception != null) { StringBuilder sb = new StringBuilder(); StackTraceElement[] stackTrace = exception.getStackTrace(); for (StackTraceElement element : stackTrace) { sb.append(element.toString(...
java
private void doSearch() { setSearchPanelVisible(true); String selectedText = textComponent.getSelectedText(); if (selectedText != null) { searchPanel.setQuery(selectedText); } searchPanel.requestFocusForTextField(); }
java
void setSearchPanelVisible(boolean b) { if (!searchPanelVisible && b) { add(searchPanel, BorderLayout.NORTH); revalidate(); } else if (searchPanelVisible && !b) { remove(searchPanel); revalidate(); } ...
java
void doFindNext() { String query = searchPanel.getQuery(); if (query.isEmpty()) { return; } String text = getDocumentText(); boolean ignoreCase = !searchPanel.isCaseSensitive(); int caretPosition = textComponent.getCaretPositio...
java
private String getDocumentText() { try { Document document = textComponent.getDocument(); String text = document.getText(0, document.getLength()); return text; } catch (BadLocationException e) { logger.warning(e.toStri...
java
private void addHighlights(Collection<? extends Point> points, Color color) { removeHighlights(points); Map<Point, Object> newHighlights = JTextComponents.addHighlights(textComponent, points, color); highlights.putAll(newHighlights); }
java
private void removeHighlights(Collection<? extends Point> points) { Set<Object> highlightsToRemove = new LinkedHashSet<Object>(); for (Point point : points) { Object oldHighlight = highlights.remove(point); if (oldHighlight != null) { ...
java
public final Collection<Double> getResultSet(final AbstractMeter meter) { checkIfMeterExists(meter); return this.meterResults.get(meter); }
java
public final double squareSum(final AbstractMeter meter) { checkIfMeterExists(meter); final AbstractUnivariateStatistic sqrSum = new SumOfSquares(); final CollectionDoubleCollection doubleColl = new CollectionDoubleCollection(this.meterResults.get(meter)); return sqrSum.evaluate(doubleCo...
java
public final double getStandardDeviation(final AbstractMeter meter) { checkIfMeterExists(meter); final AbstractUnivariateStatistic stdDev = new StandardDeviation(); final CollectionDoubleCollection doubleColl = new CollectionDoubleCollection(this.meterResults.get(meter)); return stdDev.e...
java
public final double sum(final AbstractMeter meter) { checkIfMeterExists(meter); final AbstractUnivariateStatistic sum = new Sum(); final CollectionDoubleCollection doubleColl = new CollectionDoubleCollection(this.meterResults.get(meter)); return sum.evaluate(doubleColl.toArray(), 0, doub...
java
public final double min(final AbstractMeter meter) { checkIfMeterExists(meter); final AbstractUnivariateStatistic min = new Min(); final CollectionDoubleCollection doubleColl = new CollectionDoubleCollection(this.meterResults.get(meter)); return min.evaluate(doubleColl.toArray(), 0, doub...
java
public final double getConf05(final AbstractMeter meter) { checkIfMeterExists(meter); final AbstractUnivariateStatistic conf05 = new Percentile(5.0); final CollectionDoubleCollection doubleColl = new CollectionDoubleCollection(this.meterResults.get(meter)); return conf05.evaluate(doubleC...
java
public final double getConf95(final AbstractMeter meter) { checkIfMeterExists(meter); final AbstractUnivariateStatistic conf95 = new Percentile(95.0); final CollectionDoubleCollection doubleColl = new CollectionDoubleCollection(this.meterResults.get(meter)); return conf95.evaluate(double...
java