code
stringlengths
73
34.1k
label
stringclasses
1 value
private void validateTimes(int idx, SubPicture subPic, SubPicture subPicNext, SubPicture subPicPrev) { long startTime = subPic.getStartTime(); long endTime = subPic.getEndTime(); final long delay = 5000 * 90; // default delay for missing end time (5 // seconds) idx += 1; // only used for di...
java
private List<Integer> getSubPicturesToBeExported() { List<Integer> subPicturesToBeExported = new ArrayList<Integer>(); for (int i = 0; i < subPictures.length; i++) { SubPicture subPicture = subPictures[i]; if (!subPicture.isExcluded() && (!configuration.isExportForced() || subPicture .isForc...
java
private void determineFramePal(int index) { if ((inMode != InputMode.VOBSUB && inMode != InputMode.SUPIFO) || configuration.getPaletteMode() != PaletteMode.KEEP_EXISTING) { // get the primary color from the source palette int rgbSrc[] = subtitleStream.getPalette().getRGB( subtitleStream.getPrimary...
java
@SuppressWarnings("unchecked") public <TO> ChainedTransformer<I, TO> chain(Transformer<O, TO> transformer) { if (transformer != null) { transformers.add(transformer); } return (ChainedTransformer<I, TO>) this; }
java
protected void processResult(RHI aggregatedResult) { // Process the result with all result handlers for (ResultHandler<RHI> resultHandler : resultHandlers) { resultHandler.handleResult(aggregatedResult); } }
java
@CheckForNull public static String getFirstIdent(@Nonnull final DetailAST pAst) { String result = null; DetailAST ast = pAst.findFirstToken(TokenTypes.IDENT); if (ast != null) { result = ast.getText(); } return result; }
java
@CheckForNull public static String getFullIdent(@Nonnull final DetailAST pAst) { String result = null; DetailAST ast = checkTokens(pAst.getFirstChild(), TokenTypes.DOT, TokenTypes.IDENT); if (ast != null) { StringBuilder sb = new StringBuilder(); if (getFullIdentI...
java
public static boolean containsString(@Nullable final Iterable<String> pIterable, @Nullable final String pSearched, final boolean pCaseSensitive) { boolean result = false; if (pSearched != null && pIterable != null) { for (String s : pIterable) { if (stringEquals(p...
java
public static boolean stringEquals(@Nullable final String pStr1, @Nullable final String pStr2, final boolean pCaseSensitive) { boolean result = false; if (pStr1 == null && pStr2 == null) { result = true; } else if (pStr1 != null) { if (pCaseSensitive) ...
java
@Nonnull public static DetailAST findLeftMostTokenInLine(@Nonnull final DetailAST pAst) { return findLeftMostTokenInLineInternal(pAst, pAst.getLineNo(), pAst.getColumnNo()); }
java
public void setToolTipText(String text) { this.toolTipText = text; if (toolTipDialog != null) { toolTipDialog.setText(text); } }
java
private void updateToolTipDialogVisibility() { // Determine whether tooltip should be/remain visible boolean shouldBeVisible = isOverDecorationPainter() || isOverToolTipDialog(); // Create tooltip dialog if needed if (shouldBeVisible) { createToolTipDialogIfNeeded(); ...
java
public void send(Event event) throws MetricsException { HttpPost request = new HttpPost(MetricsUtils.GA_ENDPOINT_URL); request.setEntity(MetricsUtils.buildPostBody(event, analyticsId, random)); try { client.execute(request, RESPONSE_HANDLER); } catch (IOException e) { // All errors in the re...
java
public synchronized boolean isRunning() { if (null == process) return false; try { process.exitValue(); return false; } catch(IllegalThreadStateException itse) { return true; } }
java
private static String convertToRomaji(String katakana) throws EasyJaSubException { try { return Kurikosu.convertKatakanaToRomaji(katakana); } catch (EasyJaSubException ex) { try { return LuceneUtil.katakanaToRomaji(katakana); } catch (Throwable luceneEx) { throw ex; } } }
java
public DataProviderContext on(final Trigger... triggers) { if (triggers != null) { Collections.addAll(registeredTriggers, triggers); } return this; }
java
public <D> RuleContext<D> read(final DataProvider<D>... dataProviders) { final List<DataProvider<D>> registeredDataProviders = new ArrayList<DataProvider<D>>(); if (dataProviders != null) { Collections.addAll(registeredDataProviders, dataProviders); } return new RuleContext<D...
java
public FileCollection buildClassPath(@Nonnull final DependencyConfig pDepConfig, @Nullable final String pCsVersionOverride, final boolean pIsTestRun, @Nonnull final SourceSet pSourceSet1, @Nullable final SourceSet... pOtherSourceSets) { FileCollection cp = getClassesDirs(pSourceSet1, pDepCon...
java
public static TriggerContext on(Trigger trigger) { List<Trigger> addedTriggers = new ArrayList<Trigger>(); if (trigger != null) { addedTriggers.add(trigger); } return new TriggerContext(addedTriggers); }
java
public static String getFileName(final ConfigurationSourceKey source){ //ensure an exception is thrown if we are not file. if (source.getType()!=ConfigurationSourceKey.Type.FILE) throw new AssertionError("Can only load configuration sources with type "+ConfigurationSourceKey.Type.FILE); return source.getName()...
java
public void setExtraFields(Collection<String> fields) { extraFields = new HashSet<String>(); if (fields != null) { extraFields.addAll(fields); } }
java
public Map<String,String> data() { try { return event().get(); } catch (InterruptedException e) { // Can only happen if invoked before completion throw new IllegalStateException(e); } }
java
@Handler public void onRead(Input<ByteBuffer> event) throws InterruptedException { for (IOSubchannel channel : event.channels(IOSubchannel.class)) { ManagedBuffer<ByteBuffer> out = channel.byteBufferPool().acquire(); out.backingBuffer().put(event.buffer().backingBuffer())...
java
@Handler public void onOutput(Output<ByteBuffer> event, TcpChannelImpl channel) throws InterruptedException { if (channels.contains(channel)) { channel.write(event); } }
java
public String replace(CharSequence text) { TextBuffer tb = wrap(new StringBuilder(text.length())); replace(pattern.matcher(text), substitution, tb); return tb.toString(); }
java
public int replace(CharSequence text, StringBuilder sb) { return replace(pattern.matcher(text), substitution, wrap(sb)); }
java
@Handler(priority = 1000) public void onProtocolSwitchAccepted( ProtocolSwitchAccepted event, IOSubchannel channel) { event.requestEvent().associated(Selection.class) .ifPresent( selection -> channel.setAssociated(Selection.class, selection)); }
java
public static Locale associatedLocale(Associator assoc) { return assoc.associated(Selection.class) .map(sel -> sel.get()[0]).orElse(Locale.getDefault()); }
java
private DataContainer fetch(String tableAlias, IndexBooleanExpression condition, Map<String, String> tableAliases) { String tableName = tableAliases.get(tableAlias); Set<String> ids = getIdsFromIndex(tableName, tableAlias, condition); return fetchContainer(tableName, tableAlias, ids); }
java
private static Set<Key> conditionToKeys(int keyLength, Map<String, Set<Object>> condition) { return crossProduct(new ArrayList<>(condition.values())).stream() .map(v -> Keys.key(keyLength, v.toArray())) .collect(Collectors.toSet()); }
java
public Value getValue(final Environment in){ log.debug("looking up value for "+name+" in "+in); return attributeValue.get(in); }
java
public KeyValueStoreUpdate update(String key, String value) { actions.add(new Update(key, value)); return this; }
java
public KeyValueStoreUpdate storeAs(String value, String... segments) { actions.add(new Update("/" + String.join("/", segments), value)); return this; }
java
public KeyValueStoreUpdate clearAll(String... segments) { actions.add(new Deletion("/" + String.join("/", segments))); return this; }
java
public void set(Value value, Environment in){ values.put(in.expandedStringForm(), value); }
java
@SuppressWarnings({ "PMD.DataflowAnomalyAnalysis" }) /* default */ static ComponentVertex getComponentProxy( ComponentType component, Channel componentChannel) { ComponentProxy componentProxy = null; try { Field field = getManagerField(component.getClass()); synch...
java
public final <T extends GraphObject> T getGraphObjectAs(Class<T> graphObjectClass) { if (graphObject == null) { return null; } if (graphObjectClass == null) { throw new NullPointerException("Must pass in a valid interface that extends GraphObject"); } retu...
java
public final <T extends GraphObject> GraphObjectList<T> getGraphObjectListAs(Class<T> graphObjectClass) { if (graphObjectList == null) { return null; } return graphObjectList.castToListOf(graphObjectClass); }
java
public Request getRequestForPagedResults(PagingDirection direction) { String link = null; if (graphObject != null) { PagedResults pagedResults = graphObject.cast(PagedResults.class); PagingInfo pagingInfo = pagedResults.getPaging(); if (pagingInfo != null) { ...
java
protected Configuration freemarkerConfig() { if (fmConfig == null) { fmConfig = new Configuration(Configuration.VERSION_2_3_26); fmConfig.setClassLoaderForTemplateLoading( contentLoader, contentPath); fmConfig.setDefaultEncoding("utf-8"); fmConfig....
java
protected Map<String, Object> fmSessionModel(Optional<Session> session) { @SuppressWarnings("PMD.UseConcurrentHashMap") final Map<String, Object> model = new HashMap<>(); Locale locale = session.map( sess -> sess.locale()).orElse(Locale.getDefault()); model.put("locale", loca...
java
protected ResourceBundle resourceBundle(Locale locale) { return ResourceBundle.getBundle( contentPath.replace('/', '.') + ".l10n", locale, contentLoader, ResourceBundle.Control.getNoFallbackControl( ResourceBundle.Control.FORMAT_DEFAULT)); }
java
private void removeBuffer(W buffer) { createdBufs.decrementAndGet(); if (bufferMonitor.remove(buffer) == null) { if (logger.isLoggable(Level.FINE)) { logger.log(Level.WARNING, "Attempt to remove unknown buffer from pool.", new Throwable...
java
@SuppressWarnings("PMD.GuardLogStatement") public W acquire() throws InterruptedException { // Stop draining, because we obviously need this kind of buffers Optional.ofNullable(idleTimer.getAndSet(null)).ifPresent( timer -> timer.cancel()); if (createdBufs.get() < maximumBufs) { ...
java
@Override public void recollect(W buffer) { if (queue.size() < preservedBufs) { long effectiveDrainDelay = drainDelay > 0 ? drainDelay : defaultDrainDelay; if (effectiveDrainDelay > 0) { // Enqueue buffer.clear(); queue....
java
public Value getIncludedValue(Environment in){ return ConfigurationManager.INSTANCE.getConfiguration(configurationName, in).getAttribute(attributeName); }
java
public ConfigurationSourceKey getConfigName() { return new ConfigurationSourceKey(ConfigurationSourceKey.Type.FILE, ConfigurationSourceKey.Format.JSON, configurationName); }
java
Configuration copyWithIdentifier(String identifier) { return new Configuration(details.builder().identifier(identifier).build(), new HashMap<>(config)); }
java
void write(File f) throws FileNotFoundException, IOException { try (ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream(f))) { os.writeObject(this); } }
java
public void fireUpdateEvent(final long timestamp){ synchronized(listeners){ for (final ConfigurationSourceListener listener : listeners){ try{ log.debug("Calling configurationSourceUpdated on "+listener); listener.configurationSourceUpdated(this); }catch(final Exception e){ log.error("Error ...
java
InventoryEntry remove(String key) { InventoryEntry ret = configs.remove(key); if (ret!=null) { ret.getPath().delete(); } return ret; }
java
List<Configuration> removeMismatching() { // List mismatching List<InventoryEntry> mismatching = configs.values().stream() .filter(v-> (v.getConfiguration().isPresent() && !v.getIdentifier().equals(v.getConfiguration().get().getDetails().getKey())) ).collect(Collectors.toList()); // Remove from inve...
java
List<File> removeUnreadable() { // List unreadable List<InventoryEntry> unreadable = configs.values() .stream() .filter(v->!v.getConfiguration().isPresent()) .collect(Collectors.toList()); // Remove from inventory unreadable.forEach(v->configs.remove(v.getIdentifier())); // Return the list of remo...
java
@RequestHandler(patterns = "/form,/form/**") public void onGet(Request.In.Get event, IOSubchannel channel) throws ParseException { ResponseCreationSupport.sendStaticContent(event, channel, path -> FormProcessor.class.getResource( ResourcePattern.removeSegments(path, 1...
java
@RequestHandler(patterns = "/form,/form/**") public void onPost(Request.In.Post event, IOSubchannel channel) { FormContext ctx = channel .associated(this, FormContext::new); ctx.request = event.httpRequest(); ctx.session = event.associated(Session.class).get(); event.setR...
java
@Handler public void onInput(Input<ByteBuffer> event, IOSubchannel channel) throws InterruptedException, UnsupportedEncodingException { Optional<FormContext> ctx = channel.associated(this, FormContext.class); if (!ctx.isPresent()) { return; } ctx.get().fieldDe...
java
@Handler(channels = NetworkChannel.class) @SuppressWarnings("PMD.DataflowAnomalyAnalysis") public void onConnected(Connected event, TcpChannel netConnChannel) throws InterruptedException, IOException { // Check if an app channel has been waiting for such a connection WebAppMsgChannel...
java
@Handler(channels = NetworkChannel.class) public void onInput(Input<ByteBuffer> event, TcpChannel netConnChannel) throws InterruptedException, ProtocolException { Optional<WebAppMsgChannel> appChannel = netConnChannel.associated(WebAppMsgChannel.class); if (appChannel.isPrese...
java
@Handler(channels = NetworkChannel.class) public void onClosed(Closed event, TcpChannel netConnChannel) { netConnChannel.associated(WebAppMsgChannel.class).ifPresent( appChannel -> appChannel.handleClosed(event)); pooled.remove(netConnChannel.remoteAddress(), netConnChannel); }
java
Map<String, Object> bindStrutsContext(Object action) { Map<String, Object> variables = new HashMap<String, Object>(); variables.put(ACTION_VARIABLE_NAME, action); if ( action instanceof ActionSupport) { ActionSupport actSupport = (ActionSupport)action; // Struts2 field errors.( Map<fieldname , fiel...
java
public static synchronized void sdkInitialize(Context context) { if (sdkInitialized == true) { return; } BoltsMeasurementEventListener.getInstance(context.getApplicationContext()); sdkInitialized = true; }
java
public static Executor getExecutor() { synchronized (LOCK) { if (Settings.executor == null) { Executor executor = getAsyncTaskExecutor(); if (executor == null) { executor = new ThreadPoolExecutor(DEFAULT_CORE_POOL_SIZE, DEFAULT_MAXIMUM_POOL_SIZE, ...
java
public static void setExecutor(Executor executor) { Validate.notNull(executor, "executor"); synchronized (LOCK) { Settings.executor = executor; } }
java
public static String getAttributionId(ContentResolver contentResolver) { try { String [] projection = {ATTRIBUTION_ID_COLUMN_NAME}; Cursor c = contentResolver.query(ATTRIBUTION_ID_CONTENT_URI, projection, null, null, null); if (c == null || !c.moveToFirst()) { ...
java
public static boolean getLimitEventAndDataUsage(Context context) { SharedPreferences preferences = context.getSharedPreferences(APP_EVENT_PREFERENCES, Context.MODE_PRIVATE); return preferences.getBoolean("limitEventUsage", false); }
java
public static void setLimitEventAndDataUsage(Context context, boolean limitEventUsage) { SharedPreferences preferences = context.getSharedPreferences(APP_EVENT_PREFERENCES, Context.MODE_PRIVATE); SharedPreferences.Editor editor = preferences.edit(); editor.putBoolean("limitEventUsage", limitEven...
java
public void show() { if (mAnchorViewRef.get() != null) { mPopupContent = new PopupContentView(mContext); TextView body = (TextView) mPopupContent.findViewById( R.id.com_facebook_tooltip_bubble_view_text_body); body.setText(mText); if (mStyle ==...
java
public void onCreate(Bundle savedInstanceState) { Session session = Session.getActiveSession(); if (session == null) { if (savedInstanceState != null) { session = Session.restoreSession(activity, null, callback, savedInstanceState); } if (session == nu...
java
public void onResume() { Session session = Session.getActiveSession(); if (session != null) { if (callback != null) { session.addCallback(callback); } if (SessionState.CREATED_TOKEN_LOADED.equals(session.getState())) { session.openForRe...
java
public void onActivityResult(int requestCode, int resultCode, Intent data) { onActivityResult(requestCode, resultCode, data, null); }
java
public void onActivityResult(int requestCode, int resultCode, Intent data, FacebookDialog.Callback facebookDialogCallback) { Session session = Session.getActiveSession(); if (session != null) { session.onActivityResult(activity, requestCode, resultCode, data); } ...
java
public void onSaveInstanceState(Bundle outState) { Session.saveSession(Session.getActiveSession(), outState); outState.putParcelable(DIALOG_CALL_BUNDLE_SAVE_KEY, pendingFacebookDialogCall); }
java
public void onPause() { // remove the broadcast receiver broadcastManager.unregisterReceiver(receiver); if (callback != null) { Session session = Session.getActiveSession(); if (session != null) { session.removeCallback(callback); } } ...
java
public static Evaluator definitionEvaluator( HandlerDefinition hda) { return definitionEvaluators.computeIfAbsent(hda.evaluator(), key -> { try { return hda.evaluator().getConstructor().newInstance(); } catch (InstantiationException | IllegalAccessException ...
java
public boolean matches(TaskGroupInformation info) { return getActivity().equals(info.getActivity()) && getInputType().equals(info.getInputType()) && getOutputType().equals(info.getOutputType()) && info.matchesLocale(getLocale()); }
java
public void logDomNodeList (String msg, NodeList nodeList) { StackTraceElement caller = StackTraceUtils.getCallerStackTraceElement (); String toLog = (msg != null ? msg + "\n" : "DOM nodelist:\n"); for (int i = 0; i < nodeList.getLength (); i++) { toLog += domNodeDescription (nodeList.item (i), 0) + "\n"; }...
java
public void logDomNode (String msg, Node node) { StackTraceElement caller = StackTraceUtils.getCallerStackTraceElement (); logDomNode (msg, node, Level.FINER, caller); }
java
public void logDomNode (String msg, Node node, Level level, StackTraceElement caller) { String toLog = (msg != null ? msg + "\n" : "DOM node:\n") + domNodeDescription (node, 0); if (caller != null) { logger.logp (level, caller.getClassName (), caller.getMethodName () + "():" + caller.getLineNumber (), toLog); ...
java
private String domNodeDescription (Node node, int tablevel) { String domNodeDescription = null; String nodeName = node.getNodeName (); String nodeValue = node.getNodeValue (); if (!(nodeName.equals ("#text") && nodeValue.replaceAll ("\n", "").trim ().equals (""))) { domNodeDescription = tabs (tablevel) + no...
java
public void setLevel (Level level) { this.defaultLevel = level; logger.setLevel (level); for (Handler handler : logger.getHandlers ()) { handler.setLevel (level); } }
java
@Handler(channels = Self.class) public void onRegistered(NioRegistration.Completed event) throws InterruptedException, IOException { NioHandler handler = event.event().handler(); if (handler == this) { if (event.event().get() == null) { fire(new Error(event, ...
java
@Handler @SuppressWarnings("PMD.DataflowAnomalyAnalysis") public void onClose(Close event) throws IOException, InterruptedException { boolean subOnly = true; for (Channel channel : event.channels()) { if (channel instanceof TcpChannelImpl) { if (channels.contains(chan...
java
public static Vector<String> tokenize2vector(final String source, final char delimiter) { final Vector<String> v = new Vector<>(); StringBuilder currentS = new StringBuilder(); char c; for (int i = 0; i < source.length(); i++) { c = source.charAt(i); if (c == delimiter) { v.addElement(currentS.length(...
java
public static String removeCComments(final String src) { final StringBuilder ret = new StringBuilder(); boolean inComments = false; for (int i = 0; i < src.length(); i++) { char c = src.charAt(i); if (inComments) { if (c == '*' && src.charAt(i + 1) == '/') { inComments = false; i++; } }...
java
public void cleanupAttachmentsForCall(Context context, UUID callId) { File dir = getAttachmentsDirectoryForCall(callId, false); Utility.deleteDirectory(dir); }
java
@SuppressWarnings("unchecked") public final T duplicate() { if (backing instanceof ByteBuffer) { return (T) ((ByteBuffer) backing).duplicate(); } if (backing instanceof CharBuffer) { return (T) ((CharBuffer) backing).duplicate(); } throw new IllegalArg...
java
public void process(EventPipeline eventPipeline, EventBase<?> event) { try { for (HandlerReference hdlr : this) { try { hdlr.invoke(event); if (event.isStopped()) { break; } } catch (A...
java
public Session getOpenSession() { Session openSession = getSession(); if (openSession != null && openSession.isOpened()) { return openSession; } return null; }
java
public void setSession(Session newSession) { if (newSession == null) { if (session != null) { // We're current tracking a Session. Remove the callback // and start tracking the active Session. session.removeCallback(callback); session =...
java
public void stopTracking() { if (!isTracking) { return; } Session session = getSession(); if (session != null) { session.removeCallback(callback); } broadcastManager.unregisterReceiver(receiver); isTracking = false; }
java
@Override @SuppressWarnings("PMD.ShortVariable") public <V> Optional<V> associated(Object by, Class<V> type) { Optional<V> result = super.associated(by, type); if (!result.isPresent()) { IOSubchannel upstream = upstreamChannel(); if (upstream != null) { re...
java
public Task<AppLink> getAppLinkFromUrlInBackground(final Uri uri) { ArrayList<Uri> uris = new ArrayList<Uri>(); uris.add(uri); Task<Map<Uri, AppLink>> resolveTask = getAppLinkFromUrlsInBackground(uris); return resolveTask.onSuccess(new Continuation<Map<Uri, AppLink>, AppLink>() { ...
java
public void flush() { if (eventLoop.inEventLoop()) { pending++; if (pending >= maxPending) { pending = 0; channel.flush(); } } if (woken == 0 && WOKEN.compareAndSet(this, 0, 1)) { woken = 1; eventLoop.execute(wakeup); } }
java
@Handler public void onStart(Start event) { synchronized (this) { if (runner != null) { return; } buffers = new ManagedBufferPool<>(ManagedBuffer::new, () -> { return ByteBuffer.allocateDirect(bufferSize); ...
java
@Handler(priority = -10000) public void onStop(Stop event) throws InterruptedException { synchronized (this) { if (runner == null) { return; } runner.interrupt(); synchronized (this) { if (registered) { unreg...
java
public static ComponentVertex componentVertex( ComponentType component, Channel componentChannel) { if (component instanceof ComponentVertex) { return (ComponentVertex) component; } return ComponentProxy.getComponentProxy(component, componentChannel); }
java
private void setTree(ComponentTree tree) { synchronized (this) { this.tree = tree; for (ComponentVertex child : children) { child.setTree(tree); } } }
java
@SuppressWarnings("PMD.UseVarargs") /* default */ void collectHandlers(Collection<HandlerReference> hdlrs, EventBase<?> event, Channel[] channels) { for (HandlerReference hdlr : handlers) { if (hdlr.handles(event, channels)) { hdlrs.add(hdlr); } } ...
java
public GraphPlace getSelection() { Collection<GraphPlace> selection = getSelectedGraphObjects(); return (selection != null && !selection.isEmpty()) ? selection.iterator().next() : null; }
java
protected boolean hasFieldError(String fieldname) { if ( StringUtils.isEmpty(fieldname)) { return false; } Object action = ActionContext.getContext().getActionInvocation().getAction(); // check action instance 'ActionSupport'. if (!(action instanceof ActionSupport)) { return false; } Ac...
java