_id
stringlengths
2
7
title
stringlengths
3
140
partition
stringclasses
3 values
text
stringlengths
73
34.1k
language
stringclasses
1 value
meta_information
dict
q14300
ImageDownloader.downloadAsync
train
public static void downloadAsync(ImageRequest request) { if (request == null) { return; } // NOTE: This is the ONLY place where the original request's Url is read. From here on, // we will keep track of the Url separately. This is because we might be dealing with a // redirect response and the Url might change. We can't create our own new ImageRequests // for these changed Urls since the caller might be doing some book-keeping with the request's // object reference. So we keep the old references and just map them to new urls in the downloader RequestKey key = new RequestKey(request.getImageUri(), request.getCallerTag()); synchronized (pendingRequests) { DownloaderContext downloaderContext = pendingRequests.get(key); if (downloaderContext != null) { downloaderContext.request = request; downloaderContext.isCancelled = false; downloaderContext.workItem.moveToFront(); } else { enqueueCacheRead(request, key, request.isCachedRedirectAllowed()); } } }
java
{ "resource": "" }
q14301
AppEventsLogger.newLogger
train
public static AppEventsLogger newLogger(Context context, String applicationId) { return new AppEventsLogger(context, applicationId, null); }
java
{ "resource": "" }
q14302
AppEventsLogger.logEvent
train
public void logEvent(String eventName, Bundle parameters) { logEvent(eventName, null, parameters, false); }
java
{ "resource": "" }
q14303
AppEventsLogger.logEvent
train
public void logEvent(String eventName, double valueToSum, Bundle parameters) { logEvent(eventName, valueToSum, parameters, false); }
java
{ "resource": "" }
q14304
AppEventsLogger.logPurchase
train
public void logPurchase(BigDecimal purchaseAmount, Currency currency, Bundle parameters) { if (purchaseAmount == null) { notifyDeveloperError("purchaseAmount cannot be null"); return; } else if (currency == null) { notifyDeveloperError("currency cannot be null"); return; } if (parameters == null) { parameters = new Bundle(); } parameters.putString(AppEventsConstants.EVENT_PARAM_CURRENCY, currency.getCurrencyCode()); logEvent(AppEventsConstants.EVENT_NAME_PURCHASED, purchaseAmount.doubleValue(), parameters); eagerFlush(); }
java
{ "resource": "" }
q14305
AppEventsLogger.logSdkEvent
train
public void logSdkEvent(String eventName, Double valueToSum, Bundle parameters) { logEvent(eventName, valueToSum, parameters, true); }
java
{ "resource": "" }
q14306
AppEventsLogger.getSessionEventsState
train
private static SessionEventsState getSessionEventsState(Context context, AccessTokenAppIdPair accessTokenAppId) { // Do this work outside of the lock to prevent deadlocks in implementation of // AdvertisingIdClient.getAdvertisingIdInfo, because that implementation blocks waiting on the main thread, // which may also grab this staticLock. SessionEventsState state = stateMap.get(accessTokenAppId); AttributionIdentifiers attributionIdentifiers = null; if (state == null) { // Retrieve attributionId, but we will only send it if attribution is supported for the app. attributionIdentifiers = AttributionIdentifiers.getAttributionIdentifiers(context); } synchronized (staticLock) { // Check state again while we're locked. state = stateMap.get(accessTokenAppId); if (state == null) { state = new SessionEventsState(attributionIdentifiers, context.getPackageName(), hashedDeviceAndAppId); stateMap.put(accessTokenAppId, state); } return state; } }
java
{ "resource": "" }
q14307
AppEventsLogger.setSourceApplication
train
private static void setSourceApplication(Activity activity) { ComponentName callingApplication = activity.getCallingActivity(); if (callingApplication != null) { String callingApplicationPackage = callingApplication.getPackageName(); if (callingApplicationPackage.equals(activity.getPackageName())) { // open by own app. resetSourceApplication(); return; } sourceApplication = callingApplicationPackage; } // Tap icon to open an app will still get the old intent if the activity was opened by an intent before. // Introduce an extra field in the intent to force clear the sourceApplication. Intent openIntent = activity.getIntent(); if (openIntent == null || openIntent.getBooleanExtra(SOURCE_APPLICATION_HAS_BEEN_SET_BY_THIS_INTENT, false)) { resetSourceApplication(); return; } Bundle applinkData = AppLinks.getAppLinkData(openIntent); if (applinkData == null) { resetSourceApplication(); return; } isOpenedByApplink = true; Bundle applinkReferrerData = applinkData.getBundle("referer_app_link"); if (applinkReferrerData == null) { sourceApplication = null; return; } String applinkReferrerPackage = applinkReferrerData.getString("package"); sourceApplication = applinkReferrerPackage; // Mark this intent has been used to avoid use this intent again and again. openIntent.putExtra(SOURCE_APPLICATION_HAS_BEEN_SET_BY_THIS_INTENT, true); return; }
java
{ "resource": "" }
q14308
QueryPlannerImpl.extractWhereConditions
train
private Pair<List<BooleanExpression>, Optional<BooleanExpression>> extractWhereConditions(SelectQueryAware selectQueryAware) { List<BooleanExpression> whereConditions = new ArrayList<>(); Optional<BooleanExpression> whereExpressionCandidate = selectQueryAware.getWhereExpression(); if (whereExpressionCandidate.isPresent()) { whereConditions.add(whereExpressionCandidate.get()); } boolean noGroupByTaskExists = selectQueryAware.getGroupByExpressions().isEmpty(); Optional<BooleanExpression> havingExpressionCandidate = selectQueryAware.getHavingExpression(); if (havingExpressionCandidate.isPresent() && noGroupByTaskExists) { whereConditions.add(havingExpressionCandidate.get()); return new Pair<>(whereConditions, Optional.empty()); } else { return new Pair<>(whereConditions, havingExpressionCandidate); } }
java
{ "resource": "" }
q14309
QueryPlannerImpl.optimizeDataSource
train
private Pair<DataSource, Optional<BooleanExpression>> optimizeDataSource( DataSource originalDataSource, List<BooleanExpression> originalWhereConditions, Map<String, Object> selectionMap, Map<String, String> tableAliases ) { OptimizationContext optimizationContext = analyzeOriginalData(originalDataSource, originalWhereConditions, tableAliases); DataSource optimizedDataSource = createOptimizedDataSource(originalDataSource, optimizationContext, selectionMap, tableAliases); Optional<BooleanExpression> optimizedWhereCondition = createOptimizedWhereCondition(optimizationContext); return new Pair<>(optimizedDataSource, optimizedWhereCondition); }
java
{ "resource": "" }
q14310
ReplyObject.success
train
public static ReplyObject success(final String name, final Object result) { final ReplyObject ret = new ReplyObject(name, result); ret.success = true; return ret; }
java
{ "resource": "" }
q14311
Session.close
train
public final void close() { synchronized (this.lock) { final SessionState oldState = this.state; switch (this.state) { case CREATED: case OPENING: this.state = SessionState.CLOSED_LOGIN_FAILED; postStateChange(oldState, this.state, new FacebookException( "Log in attempt aborted.")); break; case CREATED_TOKEN_LOADED: case OPENED: case OPENED_TOKEN_UPDATED: this.state = SessionState.CLOSED; postStateChange(oldState, this.state, null); break; case CLOSED: case CLOSED_LOGIN_FAILED: break; } } }
java
{ "resource": "" }
q14312
Session.closeAndClearTokenInformation
train
public final void closeAndClearTokenInformation() { if (this.tokenCachingStrategy != null) { this.tokenCachingStrategy.clear(); } Utility.clearFacebookCookies(staticContext); Utility.clearCaches(staticContext); close(); }
java
{ "resource": "" }
q14313
Session.addCallback
train
public final void addCallback(StatusCallback callback) { synchronized (callbacks) { if (callback != null && !callbacks.contains(callback)) { callbacks.add(callback); } } }
java
{ "resource": "" }
q14314
Session.saveSession
train
public static final void saveSession(Session session, Bundle bundle) { if (bundle != null && session != null && !bundle.containsKey(SESSION_BUNDLE_SAVE_KEY)) { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); try { new ObjectOutputStream(outputStream).writeObject(session); } catch (IOException e) { throw new FacebookException("Unable to save session.", e); } bundle.putByteArray(SESSION_BUNDLE_SAVE_KEY, outputStream.toByteArray()); bundle.putBundle(AUTH_BUNDLE_SAVE_KEY, session.authorizationBundle); } }
java
{ "resource": "" }
q14315
Session.restoreSession
train
public static final Session restoreSession( Context context, TokenCachingStrategy cachingStrategy, StatusCallback callback, Bundle bundle) { if (bundle == null) { return null; } byte[] data = bundle.getByteArray(SESSION_BUNDLE_SAVE_KEY); if (data != null) { ByteArrayInputStream is = new ByteArrayInputStream(data); try { Session session = (Session) (new ObjectInputStream(is)).readObject(); initializeStaticContext(context); if (cachingStrategy != null) { session.tokenCachingStrategy = cachingStrategy; } else { session.tokenCachingStrategy = new SharedPreferencesTokenCachingStrategy(context); } if (callback != null) { session.addCallback(callback); } session.authorizationBundle = bundle.getBundle(AUTH_BUNDLE_SAVE_KEY); return session; } catch (ClassNotFoundException e) { Log.w(TAG, "Unable to restore session", e); } catch (IOException e) { Log.w(TAG, "Unable to restore session.", e); } } return null; }
java
{ "resource": "" }
q14316
LoggerWrapperConfigurator.getConfigurationOption
train
public Node getConfigurationOption (String optionName) { NodeList children = configuration.getChildNodes (); Node configurationOption = null; for (int childIndex = 0; childIndex < children.getLength (); childIndex++) { if (children.item (childIndex).getNodeName ().equals (optionName)) { configurationOption = children.item (childIndex); break; } } return configurationOption; }
java
{ "resource": "" }
q14317
LoggerWrapperConfigurator.getConfigurationOptionValue
train
public String getConfigurationOptionValue (String optionName, String defaultValue) { String optionValue; Node configurationOption = this.getConfigurationOption (optionName); if (configurationOption != null) { optionValue = configurationOption.getTextContent (); } else { optionValue = defaultValue; } return optionValue; }
java
{ "resource": "" }
q14318
FileLruCache.interceptAndPut
train
public InputStream interceptAndPut(String key, InputStream input) throws IOException { OutputStream output = openPutStream(key); return new CopyingInputStream(input, output); }
java
{ "resource": "" }
q14319
DefaultTemplateEngineProvider.configure
train
public void configure() { ServletContext servletContext = ServletActionContext.getServletContext(); ServletContextTemplateResolver templateResolver = new ServletContextTemplateResolver(servletContext); templateResolver.setTemplateMode(templateMode); templateResolver.setCharacterEncoding(characterEncoding); templateResolver.setPrefix(prefix); templateResolver.setSuffix(suffix); templateResolver.setCacheable(cacheable); templateResolver.setCacheTTLMs(cacheTtlMillis); templateEngine.setTemplateResolver(templateResolver); StrutsMessageResolver messageResolver = new StrutsMessageResolver(); templateEngine.setMessageResolver(new StrutsMessageResolver()); if (templateEngine instanceof SpringTemplateEngine) { ((SpringTemplateEngine) templateEngine).setMessageSource(messageResolver.getMessageSource()); } // extension diarects. FieldDialect fieldDialect = new FieldDialect(TemplateMode.HTML ,"sth"); templateEngine.addDialect(fieldDialect); }
java
{ "resource": "" }
q14320
DefaultTemplateEngineProvider.setContainer
train
public void setContainer(Container container) { this.container = container; Map<String, TemplateEngine> map = new HashMap<String, TemplateEngine>(); // loading TemplateEngine class from DI Container. Set<String> prefixes = container.getInstanceNames(TemplateEngine.class); for (String prefix : prefixes) { TemplateEngine engine = (TemplateEngine) container.getInstance(TemplateEngine.class, prefix); map.put(prefix, engine); } this.templateEngines = Collections.unmodifiableMap(map); }
java
{ "resource": "" }
q14321
TokenCachingStrategy.hasTokenInformation
train
public static boolean hasTokenInformation(Bundle bundle) { if (bundle == null) { return false; } String token = bundle.getString(TOKEN_KEY); if ((token == null) || (token.length() == 0)) { return false; } long expiresMilliseconds = bundle.getLong(EXPIRATION_DATE_KEY, 0L); if (expiresMilliseconds == 0L) { return false; } return true; }
java
{ "resource": "" }
q14322
TokenCachingStrategy.getToken
train
public static String getToken(Bundle bundle) { Validate.notNull(bundle, "bundle"); return bundle.getString(TOKEN_KEY); }
java
{ "resource": "" }
q14323
TokenCachingStrategy.putToken
train
public static void putToken(Bundle bundle, String value) { Validate.notNull(bundle, "bundle"); Validate.notNull(value, "value"); bundle.putString(TOKEN_KEY, value); }
java
{ "resource": "" }
q14324
TokenCachingStrategy.getExpirationDate
train
public static Date getExpirationDate(Bundle bundle) { Validate.notNull(bundle, "bundle"); return getDate(bundle, EXPIRATION_DATE_KEY); }
java
{ "resource": "" }
q14325
TokenCachingStrategy.getPermissions
train
public static List<String> getPermissions(Bundle bundle) { Validate.notNull(bundle, "bundle"); return bundle.getStringArrayList(PERMISSIONS_KEY); }
java
{ "resource": "" }
q14326
TokenCachingStrategy.putPermissions
train
public static void putPermissions(Bundle bundle, List<String> value) { Validate.notNull(bundle, "bundle"); Validate.notNull(value, "value"); ArrayList<String> arrayList; if (value instanceof ArrayList<?>) { arrayList = (ArrayList<String>) value; } else { arrayList = new ArrayList<String>(value); } bundle.putStringArrayList(PERMISSIONS_KEY, arrayList); }
java
{ "resource": "" }
q14327
TokenCachingStrategy.putDeclinedPermissions
train
public static void putDeclinedPermissions(Bundle bundle, List<String> value) { Validate.notNull(bundle, "bundle"); Validate.notNull(value, "value"); ArrayList<String> arrayList; if (value instanceof ArrayList<?>) { arrayList = (ArrayList<String>) value; } else { arrayList = new ArrayList<String>(value); } bundle.putStringArrayList(DECLINED_PERMISSIONS_KEY, arrayList); }
java
{ "resource": "" }
q14328
TokenCachingStrategy.getSource
train
public static AccessTokenSource getSource(Bundle bundle) { Validate.notNull(bundle, "bundle"); if (bundle.containsKey(TokenCachingStrategy.TOKEN_SOURCE_KEY)) { return (AccessTokenSource) bundle.getSerializable(TokenCachingStrategy.TOKEN_SOURCE_KEY); } else { boolean isSSO = bundle.getBoolean(TokenCachingStrategy.IS_SSO_KEY); return isSSO ? AccessTokenSource.FACEBOOK_APPLICATION_WEB : AccessTokenSource.WEB_VIEW; } }
java
{ "resource": "" }
q14329
TokenCachingStrategy.putSource
train
public static void putSource(Bundle bundle, AccessTokenSource value) { Validate.notNull(bundle, "bundle"); bundle.putSerializable(TOKEN_SOURCE_KEY, value); }
java
{ "resource": "" }
q14330
TokenCachingStrategy.getLastRefreshDate
train
public static Date getLastRefreshDate(Bundle bundle) { Validate.notNull(bundle, "bundle"); return getDate(bundle, LAST_REFRESH_DATE_KEY); }
java
{ "resource": "" }
q14331
TaskGroupInformation.newCopyBuilder
train
public Builder newCopyBuilder() { return new Builder(getInputFormat(), getOutputFormat(), getActivity()).locale(getLocale()).setRequiredOptions(keys); }
java
{ "resource": "" }
q14332
TaskGroupInformation.newConvertBuilder
train
public static Builder newConvertBuilder(String input, String output) { return new Builder(input, output, TaskGroupActivity.CONVERT); }
java
{ "resource": "" }
q14333
ErrorPrinter.printError
train
@SuppressWarnings({ "PMD.DataflowAnomalyAnalysis", "PMD.AvoidCatchingGenericException", "PMD.UseStringBufferForStringAppends", "PMD.SystemPrintln" }) public void printError(Error event) { String msg = "Unhandled " + event; System.err.println(msg); if (event.throwable() == null) { System.err.println("No stack trace available."); } else { event.throwable().printStackTrace(); } }
java
{ "resource": "" }
q14334
Recipe.segment
train
protected List<Segment> segment() { List<Segment> segments = new ArrayList<>(); List<Recipe> recipeStack = new ArrayList<>(); recipeStack.add(this); _segment(new Recipe(), recipeStack, null, segments); return segments; }
java
{ "resource": "" }
q14335
WsEchoServer.onGet
train
@RequestHandler(patterns = "/ws/echo", priority = 100) public void onGet(Request.In.Get event, IOSubchannel channel) throws InterruptedException { final HttpRequest request = event.httpRequest(); if (!request.findField( HttpField.UPGRADE, Converters.STRING_LIST) .map(f -> f.value().containsIgnoreCase("websocket")) .orElse(false)) { return; } openChannels.add(channel); channel.respond(new ProtocolSwitchAccepted(event, "websocket")); event.stop(); }
java
{ "resource": "" }
q14336
WsEchoServer.onUpgraded
train
@Handler public void onUpgraded(Upgraded event, IOSubchannel channel) { if (!openChannels.contains(channel)) { return; } channel.respond(Output.from("/Greetings!", true)); }
java
{ "resource": "" }
q14337
SslCodec.onOutput
train
@Handler public void onOutput(Output<ByteBuffer> event, PlainChannel plainChannel) throws InterruptedException, SSLException, ExecutionException { if (plainChannel.hub() != this) { return; } plainChannel.sendUpstream(event); }
java
{ "resource": "" }
q14338
SslCodec.onClose
train
@Handler public void onClose(Close event, PlainChannel plainChannel) throws InterruptedException, SSLException { if (plainChannel.hub() != this) { return; } plainChannel.close(event); }
java
{ "resource": "" }
q14339
FileStorage.onInput
train
@Handler public void onInput(Input<ByteBuffer> event, Channel channel) { Writer writer = inputWriters.get(channel); if (writer != null) { writer.write(event.buffer()); } }
java
{ "resource": "" }
q14340
FileStorage.onClose
train
@Handler public void onClose(Close event, Channel channel) throws InterruptedException { Writer writer = inputWriters.get(channel); if (writer != null) { writer.close(event); } writer = outputWriters.get(channel); if (writer != null) { writer.close(event); } }
java
{ "resource": "" }
q14341
FileStorage.onStop
train
@Handler(priority = -1000) public void onStop(Stop event) throws InterruptedException { while (!inputWriters.isEmpty()) { Writer handler = inputWriters.entrySet().iterator().next() .getValue(); handler.close(event); } while (!outputWriters.isEmpty()) { Writer handler = outputWriters.entrySet().iterator().next() .getValue(); handler.close(event); } }
java
{ "resource": "" }
q14342
BoxPlot.data
train
private String data() { if (datasets.isEmpty()) { return ""; } else { final StringBuilder ret = new StringBuilder(); int biggestSize = 0; for (final Dataset dataset : datasets) { biggestSize = Math.max(biggestSize, dataset.numPoints()); } for (int row = 0; row < biggestSize; ++row) { ret.append(valueOrBlank(datasets.get(0), row)); // all dataset vlaues but first are prefixed with tab for (final Dataset dataset : Iterables.skip(datasets, 1)) { ret.append("\t"); ret.append(valueOrBlank(dataset, row)); } ret.append("\n"); } return ret.toString(); } }
java
{ "resource": "" }
q14343
BoxPlot.valueOrBlank
train
private String valueOrBlank(Dataset dataset, int idx) { if (idx < dataset.numPoints()) { return Double.toString(dataset.get(idx)); } else { return ""; } }
java
{ "resource": "" }
q14344
BoxPlot.main
train
public static void main(String[] argv) throws IOException { final File outputDir = new File(argv[0]); final Random rand = new Random(); final double mean1 = 5.0; final double mean2 = 7.0; final double dev1 = 2.0; final double dev2 = 4.0; final double[] data1 = new double[100]; final double[] data2 = new double[100]; for (int i = 0; i < 100; ++i) { data1[i] = rand.nextGaussian() * dev1 + mean1; data2[i] = rand.nextGaussian() * dev2 + mean2; } BoxPlot.builder() .addDataset(Dataset.createAdoptingData("A", data1)) .addDataset(Dataset.createAdoptingData("B", data2)) .setTitle("A vs B") .setXAxis(Axis.xAxis().setLabel("FooCategory").build()) .setYAxis(Axis.yAxis().setLabel("FooValue").setRange(Range.closed(0.0, 15.0)).build()) .hideKey() .build().renderToEmptyDirectory(outputDir); }
java
{ "resource": "" }
q14345
OrientedBox3f.setFirstAxis
train
@Override public void setFirstAxis(double x, double y, double z, double extent, CoordinateSystem3D system) { this.axis1.set(x, y, z); assert(this.axis1.isUnitVector()); if (system.isLeftHanded()) { this.axis3.set(this.axis1.crossLeftHand(this.axis2)); } else { this.axis3.set(this.axis3.crossRightHand(this.axis2)); } this.extent1 = extent; }
java
{ "resource": "" }
q14346
Path2dfx.windingRuleProperty
train
public ObjectProperty<PathWindingRule> windingRuleProperty() { if (this.windingRule == null) { this.windingRule = new SimpleObjectProperty<>(this, MathFXAttributeNames.WINDING_RULE, DEFAULT_WINDING_RULE); } return this.windingRule; }
java
{ "resource": "" }
q14347
Path2dfx.isPolylineProperty
train
public BooleanProperty isPolylineProperty() { if (this.isPolyline == null) { this.isPolyline = new ReadOnlyBooleanWrapper(this, MathFXAttributeNames.IS_POLYLINE, false); this.isPolyline.bind(Bindings.createBooleanBinding(() -> { boolean first = true; boolean hasOneLine = false; for (final PathElementType type : innerTypesProperty()) { if (first) { if (type != PathElementType.MOVE_TO) { return false; } first = false; } else if (type != PathElementType.LINE_TO) { return false; } else { hasOneLine = true; } } return hasOneLine; }, innerTypesProperty())); } return this.isPolyline; }
java
{ "resource": "" }
q14348
Path2dfx.isCurvedProperty
train
public BooleanProperty isCurvedProperty() { if (this.isCurved == null) { this.isCurved = new ReadOnlyBooleanWrapper(this, MathFXAttributeNames.IS_CURVED, false); this.isCurved.bind(Bindings.createBooleanBinding(() -> { for (final PathElementType type : innerTypesProperty()) { if (type == PathElementType.CURVE_TO || type == PathElementType.QUAD_TO) { return true; } } return false; }, innerTypesProperty())); } return this.isCurved; }
java
{ "resource": "" }
q14349
Path2dfx.isPolygonProperty
train
public BooleanProperty isPolygonProperty() { if (this.isPolygon == null) { this.isPolygon = new ReadOnlyBooleanWrapper(this, MathFXAttributeNames.IS_POLYGON, false); this.isPolygon.bind(Bindings.createBooleanBinding(() -> { boolean first = true; boolean lastIsClose = false; for (final PathElementType type : innerTypesProperty()) { lastIsClose = false; if (first) { if (type != PathElementType.MOVE_TO) { return false; } first = false; } else if (type == PathElementType.MOVE_TO) { return false; } else if (type == PathElementType.CLOSE) { lastIsClose = true; } } return lastIsClose; }, innerTypesProperty())); } return this.isPolygon; }
java
{ "resource": "" }
q14350
Path2dfx.innerTypesProperty
train
protected ReadOnlyListWrapper<PathElementType> innerTypesProperty() { if (this.types == null) { this.types = new ReadOnlyListWrapper<>(this, MathFXAttributeNames.TYPES, FXCollections.observableList(new ArrayList<>())); } return this.types; }
java
{ "resource": "" }
q14351
MultiMapLayer.setMapLayerAt
train
protected void setMapLayerAt(int index, L layer) { this.subLayers.set(index, layer); layer.setContainer(this); resetBoundingBox(); }
java
{ "resource": "" }
q14352
MultiMapLayer.fireLayerAddedEvent
train
protected void fireLayerAddedEvent(MapLayer layer, int index) { fireLayerHierarchyChangedEvent(new MapLayerHierarchyEvent(this, layer, Type.ADD_CHILD, index, layer.isTemporaryLayer())); }
java
{ "resource": "" }
q14353
MultiMapLayer.fireLayerRemovedEvent
train
protected void fireLayerRemovedEvent(MapLayer layer, int oldChildIndex) { fireLayerHierarchyChangedEvent(new MapLayerHierarchyEvent( this, layer, Type.REMOVE_CHILD, oldChildIndex, layer.isTemporaryLayer())); }
java
{ "resource": "" }
q14354
MultiMapLayer.fireLayerMovedUpEvent
train
protected void fireLayerMovedUpEvent(MapLayer layer, int newIndex) { fireLayerHierarchyChangedEvent(new MapLayerHierarchyEvent(this, layer, Type.MOVE_CHILD_UP, newIndex, layer.isTemporaryLayer())); }
java
{ "resource": "" }
q14355
MultiMapLayer.fireLayerMovedDownEvent
train
protected void fireLayerMovedDownEvent(MapLayer layer, int newIndex) { fireLayerHierarchyChangedEvent(new MapLayerHierarchyEvent(this, layer, Type.MOVE_CHILD_DOWN, newIndex, layer.isTemporaryLayer())); }
java
{ "resource": "" }
q14356
MultiMapLayer.fireLayerRemoveAllEvent
train
protected void fireLayerRemoveAllEvent(List<? extends L> removedObjects) { fireLayerHierarchyChangedEvent( new MapLayerHierarchyEvent( this, removedObjects, Type.REMOVE_ALL_CHILDREN, -1, isTemporaryLayer())); }
java
{ "resource": "" }
q14357
Vector2dfx.convert
train
public static Vector2dfx convert(Tuple2D<?> tuple) { if (tuple instanceof Vector2dfx) { return (Vector2dfx) tuple; } return new Vector2dfx(tuple.getX(), tuple.getY()); }
java
{ "resource": "" }
q14358
Point2d.convert
train
public static Point2d convert(Tuple2D<?> tuple) { if (tuple instanceof Point2d) { return (Point2d) tuple; } return new Point2d(tuple.getX(), tuple.getY()); }
java
{ "resource": "" }
q14359
TableUtils.columnTransformerByCell
train
public static <R, C, V, C2> ImmutableTable<R, C2, V> columnTransformerByCell( final Table<R, C, V> table, final Function<Table.Cell<R, C, V>, C2> columnTransformer) { final ImmutableTable.Builder<R, C2, V> newTable = ImmutableTable.builder(); for(Table.Cell<R, C, V> cell : table.cellSet()) { C2 col = columnTransformer.apply(cell); newTable.put(cell.getRowKey(), col, cell.getValue()); } return newTable.build(); }
java
{ "resource": "" }
q14360
GeoLocationUtil.setDistanceEpsilon
train
public static double setDistanceEpsilon(double newPrecisionValue) { if ((newPrecisionValue >= 1) || (newPrecisionValue <= 0)) { throw new IllegalArgumentException(); } final double old = distancePrecision; distancePrecision = newPrecisionValue; return old; }
java
{ "resource": "" }
q14361
GeoLocationUtil.epsilonEqualsDistance
train
@Pure public static boolean epsilonEqualsDistance(double value1, double value2) { return value1 >= (value2 - distancePrecision) && value1 <= (value2 + distancePrecision); }
java
{ "resource": "" }
q14362
GeoLocationUtil.epsilonCompareToDistance
train
@Pure public static int epsilonCompareToDistance(double distance1, double distance2) { final double min = distance2 - distancePrecision; final double max = distance2 + distancePrecision; if (distance1 >= min && distance1 <= max) { return 0; } if (distance1 < min) { return -1; } return 1; }
java
{ "resource": "" }
q14363
GeoLocationUtil.makeInternalId
train
@Pure public static String makeInternalId(float x, float y) { final StringBuilder buf = new StringBuilder("point"); //$NON-NLS-1$ buf.append(x); buf.append(';'); buf.append(y); return Encryption.md5(buf.toString()); }
java
{ "resource": "" }
q14364
GeoLocationUtil.makeInternalId
train
@Pure public static String makeInternalId(UUID uid) { final StringBuilder buf = new StringBuilder("nowhere(?"); //$NON-NLS-1$ buf.append(uid.toString()); buf.append("?)"); //$NON-NLS-1$ return Encryption.md5(buf.toString()); }
java
{ "resource": "" }
q14365
GeoLocationUtil.makeInternalId
train
@Pure public static String makeInternalId(float minx, float miny, float maxx, float maxy) { final StringBuilder buf = new StringBuilder("rectangle"); //$NON-NLS-1$ buf.append('('); buf.append(minx); buf.append(';'); buf.append(miny); buf.append(")-("); //$NON-NLS-1$ buf.append(maxx); buf.append(';'); buf.append(maxy); buf.append(')'); return Encryption.md5(buf.toString()); }
java
{ "resource": "" }
q14366
DssatCRIDHelper.get2BitCrid
train
public static String get2BitCrid(String str) { if (str != null) { String crid = LookupCodes.lookupCode("CRID", str, "DSSAT"); if (crid.equals(str) && crid.length() > 2) { crid = def2BitVal; } return crid.toUpperCase(); } else { return def2BitVal; } // if (str == null) { // return def2BitVal; // } else if (str.length() == 2) { // return str; // } // String ret = crids.get(str); // if (ret == null || ret.equals("")) { // return str; // } else { // return ret; // } }
java
{ "resource": "" }
q14367
DssatCRIDHelper.get3BitCrid
train
public static String get3BitCrid(String str) { if (str != null) { // return LookupCodes.modelLookupCode("DSSAT", "CRID", str).toUpperCase(); return LookupCodes.lookupCode("CRID", str, "code", "DSSAT").toUpperCase(); } else { return def3BitVal; } // if (str == null || !crids.containsValue(str)) { // return def3BitVal; // } else if (str.length() == 3) { // return str; // } // for (String key : crids.keySet()) { // if (str.equals(crids.get(key))) { // return key; // } // } // return str; }
java
{ "resource": "" }
q14368
Locale.decodeString
train
private static CharBuffer decodeString(byte[] bytes, Charset charset, int referenceLength) { try { final Charset autodetectedCharset; final CharsetDecoder decoder = charset.newDecoder(); final CharBuffer buffer = decoder.decode(ByteBuffer.wrap(bytes)); if ((decoder.isAutoDetecting()) && (decoder.isCharsetDetected())) { autodetectedCharset = decoder.detectedCharset(); if (charset.contains(autodetectedCharset)) { buffer.position(0); if ((referenceLength >= 0) && (buffer.remaining() == referenceLength)) { return buffer; } return null; } } // Apply a proprietary detection buffer.position(0); char c; int type; while (buffer.hasRemaining()) { c = buffer.get(); type = Character.getType(c); switch (type) { case Character.UNASSIGNED: case Character.CONTROL: case Character.FORMAT: case Character.PRIVATE_USE: case Character.SURROGATE: // Character not supported? return null; default: } } buffer.position(0); if ((referenceLength >= 0) && (buffer.remaining() == referenceLength)) { return buffer; } } catch (CharacterCodingException e) { // } return null; }
java
{ "resource": "" }
q14369
ArrayMapElementLayer.iterator
train
@Override @Pure public Iterator<E> iterator(Rectangle2afp<?, ?, ?, ?, ?, ?> bounds) { return new BoundedElementIterator<>(bounds, iterator()); }
java
{ "resource": "" }
q14370
DssatTFileInput.readFile
train
@Override protected HashMap readFile(HashMap brMap) throws IOException { HashMap ret = new HashMap(); ArrayList<HashMap> expArr = new ArrayList<HashMap>(); HashMap<String, HashMap> files = readObvData(brMap); // compressData(file); ArrayList<HashMap> obvData; HashMap obv; HashMap expData; for (String exname : files.keySet()) { obvData = (ArrayList) files.get(exname).get(obvDataKey); for (HashMap obvSub : obvData) { expData = new HashMap(); obv = new HashMap(); copyItem(expData, files.get(exname), "exname"); copyItem(expData, files.get(exname), "crid"); copyItem(expData, files.get(exname), "local_name"); expData.put(jsonKey, obv); obv.put(obvFileKey, obvSub.get(obvDataKey)); expArr.add(expData); } } // remove index variables ArrayList idNames = new ArrayList(); idNames.add("trno_t"); removeIndex(expArr, idNames); ret.put("experiments", expArr); return ret; }
java
{ "resource": "" }
q14371
FileResourceProcessor.normalizeOutputPath
train
public Path normalizeOutputPath(FileResource resource) { Path resourcePath = resource.getPath(); Path rel = Optional.ofNullable((contentDir.relativize(resourcePath)).getParent())// .orElseGet(() -> resourcePath.getFileSystem().getPath("")); String finalOutput = rel.resolve(finalOutputName(resource)).toString(); // outputDir and contentDir can have different underlying FileSystems return outputDir.resolve(finalOutput); }
java
{ "resource": "" }
q14372
ProgressionConsoleMonitor.setModel
train
public void setModel(Progression model) { this.model.removeProgressionListener(new WeakListener(this, this.model)); if (model == null) { this.model = new DefaultProgression(); } else { this.model = model; } this.previousValue = this.model.getValue(); this.model.addProgressionListener(new WeakListener(this, this.model)); }
java
{ "resource": "" }
q14373
ProgressionConsoleMonitor.buildMessage
train
@SuppressWarnings("static-method") protected String buildMessage(double progress, String comment, boolean isRoot, boolean isFinished, NumberFormat numberFormat) { final StringBuilder txt = new StringBuilder(); txt.append('['); txt.append(numberFormat.format(progress)); txt.append("] "); //$NON-NLS-1$ if (comment != null) { txt.append(comment); } return txt.toString(); }
java
{ "resource": "" }
q14374
TernaryTreeNode.setLeftChild
train
public boolean setLeftChild(N newChild) { final N oldChild = this.left; if (oldChild == newChild) { return false; } if (oldChild != null) { oldChild.setParentNodeReference(null, true); --this.notNullChildCount; firePropertyChildRemoved(0, oldChild); } if (newChild != null) { final N oldParent = newChild.getParentNode(); if (oldParent != this) { newChild.removeFromParent(); } } this.left = newChild; if (newChild != null) { newChild.setParentNodeReference(toN(), true); ++this.notNullChildCount; firePropertyChildAdded(0, newChild); } return true; }
java
{ "resource": "" }
q14375
TernaryTreeNode.setMiddleChild
train
public boolean setMiddleChild(N newChild) { final N oldChild = this.middle; if (oldChild == newChild) { return false; } if (oldChild != null) { oldChild.setParentNodeReference(null, true); --this.notNullChildCount; firePropertyChildRemoved(1, oldChild); } if (newChild != null) { final N oldParent = newChild.getParentNode(); if (oldParent != this) { newChild.removeFromParent(); } } this.middle = newChild; if (newChild != null) { newChild.setParentNodeReference(toN(), true); ++this.notNullChildCount; firePropertyChildAdded(1, newChild); } return true; }
java
{ "resource": "" }
q14376
TernaryTreeNode.hasChild
train
@Pure public boolean hasChild(N potentialChild) { if ((this.left == potentialChild) || (this.middle == potentialChild) || (this.right == potentialChild)) { return true; } return false; }
java
{ "resource": "" }
q14377
TernaryTreeNode.getHeights
train
@Override protected void getHeights(int currentHeight, List<Integer> heights) { if (isLeaf()) { heights.add(new Integer(currentHeight)); } else { if (this.left != null) { this.left.getHeights(currentHeight + 1, heights); } if (this.middle != null) { this.middle.getHeights(currentHeight + 1, heights); } if (this.right != null) { this.right.getHeights(currentHeight + 1, heights); } } }
java
{ "resource": "" }
q14378
SplitCorpus.splitToNChunks
train
private static Iterable<List<Map.Entry<Symbol, File>>> splitToNChunks( final ImmutableMap<Symbol, File> inputMap, int numChunks) { checkArgument(numChunks > 0); final List<Map.Entry<Symbol, File>> emptyChunk = ImmutableList.of(); if (inputMap.isEmpty()) { return Collections.nCopies(numChunks, emptyChunk); } final int chunkSize = IntMath.divide(inputMap.size(), numChunks, RoundingMode.UP); final ImmutableList<List<Map.Entry<Symbol, File>>> chunks = ImmutableList.copyOf(splitToChunksOfFixedSize(inputMap, chunkSize)); if (chunks.size() == numChunks) { return chunks; } else { // there weren't enough elements to make the desired number of chunks, so we need to // pad with empty chunks final int shortage = numChunks - chunks.size(); final List<List<Map.Entry<Symbol, File>>> padding = Collections.nCopies(shortage, emptyChunk); return Iterables.concat(chunks, padding); } }
java
{ "resource": "" }
q14379
SplitCorpus.loadDocIdToFileMap
train
private static ImmutableMap<Symbol, File> loadDocIdToFileMap( final Optional<File> inputFileListFile, final Optional<File> inputFileMapFile) throws IOException { checkArgument(inputFileListFile.isPresent() || inputFileMapFile.isPresent()); final Optional<ImmutableList<File>> fileList; if (inputFileListFile.isPresent()) { fileList = Optional.of(FileUtils.loadFileList(inputFileListFile.get())); } else { fileList = Optional.absent(); } final Optional<ImmutableMap<Symbol, File>> fileMap; if (inputFileMapFile.isPresent()) { fileMap = Optional.of(FileUtils.loadSymbolToFileMap(inputFileMapFile.get())); } else { fileMap = Optional.absent(); } // sanity checks if (fileList.isPresent()) { // file list may not contain duplicates final boolean containsDuplicates = ImmutableSet.copyOf(fileList.get()).size() != fileList.get().size(); if (containsDuplicates) { throw new RuntimeException("Input file list contains duplicates"); } } // if both a file map and a file list are given, they must be compatible. if (fileList.isPresent() && fileMap.isPresent()) { if (fileList.get().size() != fileMap.get().size()) { throw new RuntimeException("Input file list and file map do not match in size (" + fileList.get().size() + " vs " + fileMap.get().size()); } final boolean haveExactlyTheSameFiles = ImmutableSet.copyOf(fileList.get()).equals(ImmutableSet.copyOf(fileMap.get().values())); if (!haveExactlyTheSameFiles) { throw new RuntimeException( "Input file list and file map do not containe exactly the same files"); } } // output if (fileMap.isPresent()) { return fileMap.get(); } else { // if we only had a file list as input, we make a fake doc-id-to-file-map using // the absolute path as the document ID. This won't get output, so it doesn't matter // that this is a little hacky final Function<File, Symbol> fileNameAsSymbolFunction = compose(SymbolUtils.symbolizeFunction(), FileUtils.toAbsolutePathFunction()); return Maps.uniqueIndex(fileList.get(), fileNameAsSymbolFunction); } }
java
{ "resource": "" }
q14380
DssatCulFileOutput.writeFile
train
@Override public void writeFile(String arg0, Map result) { // Initial variables HashMap culData; // Data holder for one site of cultivar data ArrayList<HashMap> culArr; // Data holder for one site of cultivar data BufferedWriter bwC; // output object StringBuilder sbData = new StringBuilder(); // construct the data info in the output try { // Set default value for missing data setDefVal(); culData = getObjectOr(result, "dssat_cultivar_info", new HashMap()); culArr = getObjectOr(culData, "data", new ArrayList()); if (culArr.isEmpty()) { return; } // decompressData(culArr); // Initial BufferedWriter // Get File name String fileName = getFileName(result, "X"); if (fileName.matches("TEMP\\d{4}\\.\\w{2}X")) { fileName = "Cultivar.CUL"; } else { try { fileName = fileName.replaceAll("\\.", "_") + ".CUL"; } catch (Exception e) { fileName = "Cultivar.CUL"; } } arg0 = revisePath(arg0); outputFile = new File(arg0 + fileName); bwC = new BufferedWriter(new FileWriter(outputFile, outputFile.exists())); // Output Cultivar File String lastHeaderInfo = ""; String lastTitles = ""; for (HashMap culSubData : culArr) { // If come to new header, add header line and title line if (!getObjectOr(culSubData, "header_info", "").equals(lastHeaderInfo)) { lastHeaderInfo = getObjectOr(culSubData, "header_info", ""); sbData.append(lastHeaderInfo).append("\r\n"); lastTitles = getObjectOr(culSubData, "cul_titles", ""); sbData.append(lastTitles).append("\r\n"); } // If come to new title line, add title line if (!getObjectOr(culSubData, "cul_titles", "").equals(lastTitles)) { lastTitles = getObjectOr(culSubData, "cul_titles", ""); sbData.append(lastTitles).append("\r\n"); } // Write data line sbData.append(getObjectOr(culSubData, "cul_info", "")).append("\r\n"); } // Output finish bwC.write(sbError.toString()); bwC.write(sbData.toString()); bwC.close(); } catch (IOException e) { LOG.error(DssatCommonOutput.getStackTrace(e)); } }
java
{ "resource": "" }
q14381
CodepointMatcher.anyOf
train
public static CodepointMatcher anyOf(final String sequence) { switch (sequence.length()) { case 0: return none(); case 1: return is(sequence); default: return new AnyOf(sequence); } }
java
{ "resource": "" }
q14382
CodepointMatcher.removeFrom
train
public final String removeFrom(String s) { final StringBuilder sb = new StringBuilder(); for (int offset = 0; offset < s.length(); ) { final int codePoint = s.codePointAt(offset); if (!matches(codePoint)) { sb.appendCodePoint(codePoint); } offset += Character.charCount(codePoint); } return sb.toString(); }
java
{ "resource": "" }
q14383
CodepointMatcher.trimFrom
train
public final String trimFrom(String s) { int first; int last; // removes leading matches for (first = 0; first < s.length(); ) { final int codePoint = s.codePointAt(first); if (!matches(codePoint)) { break; } first += Character.charCount(codePoint); } //remove trailing matches for (last = s.length() - 1; last >= first; --last) { if (Character.isLowSurrogate(s.charAt(last))) { --last; } if (!matches(s.codePointAt(last))) { break; } } return s.substring(first, last + 1); }
java
{ "resource": "" }
q14384
StringWithNonBmp.codeUnitOffsetFor
train
private UTF16Offset codeUnitOffsetFor(final CharOffset codePointOffset) { int charOffset = 0; int codePointsConsumed = 0; for (; charOffset < utf16CodeUnits().length() && codePointsConsumed < codePointOffset.asInt(); ++codePointsConsumed) { final int codePoint = utf16CodeUnits().codePointAt(charOffset); charOffset += Character.charCount(codePoint); } if (codePointsConsumed == codePointOffset.asInt()) { return UTF16Offset.of(charOffset); } else { // this will happen if codePointOffset is negative or equal to or greater than the // total number of codepoints in the string throw new IndexOutOfBoundsException(); } }
java
{ "resource": "" }
q14385
JTreeExtensions.expandAll
train
public static void expandAll(JTree tree, TreePath path, boolean expand) { TreeNode node = (TreeNode)path.getLastPathComponent(); if (node.getChildCount() >= 0) { Enumeration<?> enumeration = node.children(); while (enumeration.hasMoreElements()) { TreeNode n = (TreeNode)enumeration.nextElement(); TreePath p = path.pathByAddingChild(n); expandAll(tree, p, expand); } } if (expand) { tree.expandPath(path); } else { tree.collapsePath(path); } }
java
{ "resource": "" }
q14386
AbstractBusPrimitive.fireValidityChangedFor
train
protected void fireValidityChangedFor(Object changedObject, int index, BusPrimitiveInvalidity oldReason, BusPrimitiveInvalidity newReason) { resetBoundingBox(); final BusChangeEvent event = new BusChangeEvent( // source of the event this, // type of the event BusChangeEventType.VALIDITY, changedObject, index, "validity", //$NON-NLS-1$ oldReason, newReason); firePrimitiveChanged(event); }
java
{ "resource": "" }
q14387
AbstractBusPrimitive.getColor
train
@Pure public int getColor(int defaultColor) { final Integer c = getRawColor(); if (c != null) { return c; } final BusContainer<?> container = getContainer(); if (container != null) { return container.getColor(); } return defaultColor; }
java
{ "resource": "" }
q14388
AbstractBusPrimitive.setPrimitiveValidity
train
@SuppressWarnings("unlikely-arg-type") protected final void setPrimitiveValidity(BusPrimitiveInvalidity invalidityReason) { if ((invalidityReason == null && this.invalidityReason != null) || (invalidityReason != null && !invalidityReason.equals(BusPrimitiveInvalidityType.VALIDITY_NOT_CHECKED) && !invalidityReason.equals(this.invalidityReason))) { final BusPrimitiveInvalidity old = this.invalidityReason; this.invalidityReason = invalidityReason; fireValidityChanged(old, this.invalidityReason); } }
java
{ "resource": "" }
q14389
Parallelogram2dfx.secondAxisProperty
train
public UnitVectorProperty secondAxisProperty() { if (this.saxis == null) { this.saxis = new UnitVectorProperty(this, MathFXAttributeNames.SECOND_AXIS, getGeomFactory()); } return this.saxis; }
java
{ "resource": "" }
q14390
Parallelogram2dfx.firstAxisExtentProperty
train
@Pure public DoubleProperty firstAxisExtentProperty() { if (this.extentR == null) { this.extentR = new SimpleDoubleProperty(this, MathFXAttributeNames.FIRST_AXIS_EXTENT) { @Override protected void invalidated() { if (get() < 0.) { set(0.); } } }; } return this.extentR; }
java
{ "resource": "" }
q14391
Parallelogram2dfx.secondAxisExtentProperty
train
@Pure public DoubleProperty secondAxisExtentProperty() { if (this.extentS == null) { this.extentS = new SimpleDoubleProperty(this, MathFXAttributeNames.SECOND_AXIS_EXTENT) { @Override protected void invalidated() { if (get() < 0.) { set(0.); } } }; } return this.extentS; }
java
{ "resource": "" }
q14392
AbstractGenericView.getRootParentView
train
public View<?, ?> getRootParentView() { View<?, ?> currentView = this; while (currentView.hasParent()) { currentView = currentView.getParent(); } return currentView; }
java
{ "resource": "" }
q14393
CoreNLPParseNode.terminalHead
train
public Optional<CoreNLPParseNode> terminalHead() { if (terminal()) { return Optional.of(this); } if (immediateHead().isPresent()) { return immediateHead().get().terminalHead(); } return Optional.absent(); }
java
{ "resource": "" }
q14394
AbstractPathElement3D.newInstance
train
@Pure public static AbstractPathElement3D newInstance(PathElementType type, Point3d last, Point3d[] coords) { switch(type) { case MOVE_TO: return new MovePathElement3d(coords[0]); case LINE_TO: return new LinePathElement3d(last, coords[0]); case QUAD_TO: return new QuadPathElement3d(last, coords[0], coords[1]); case CURVE_TO: return new CurvePathElement3d(last, coords[0], coords[1], coords[2]); case CLOSE: return new ClosePathElement3d(last, coords[0]); default: } throw new IllegalArgumentException(); }
java
{ "resource": "" }
q14395
PrintConfigCommand.extractConfigValues
train
protected void extractConfigValues(Map<String, Object> yaml, List<ConfigMetadataNode> configs) { for (final ConfigMetadataNode config : configs) { Configs.defineConfig(yaml, config, this.injector); } }
java
{ "resource": "" }
q14396
PrintConfigCommand.generateYaml
train
@SuppressWarnings("static-method") protected String generateYaml(Map<String, Object> map) throws JsonProcessingException { final YAMLFactory yamlFactory = new YAMLFactory(); yamlFactory.configure(Feature.WRITE_DOC_START_MARKER, false); final ObjectMapper mapper = new ObjectMapper(yamlFactory); return mapper.writerWithDefaultPrettyPrinter().writeValueAsString(map); }
java
{ "resource": "" }
q14397
PrintConfigCommand.generateJson
train
@SuppressWarnings("static-method") protected String generateJson(Map<String, Object> map) throws JsonProcessingException { final ObjectMapper mapper = new ObjectMapper(); return mapper.writerWithDefaultPrettyPrinter().writeValueAsString(map); }
java
{ "resource": "" }
q14398
PrintConfigCommand.generateXml
train
@SuppressWarnings({"static-method"}) protected String generateXml(Map<String, Object> map) throws JsonProcessingException { final XmlMapper mapper = new XmlMapper(); return mapper.writerWithDefaultPrettyPrinter().withRootName(XML_ROOT_NAME).writeValueAsString(map); }
java
{ "resource": "" }
q14399
AbstractCLI.parseOptionsFromFile
train
@SuppressWarnings("unchecked") private void parseOptionsFromFile(String optionFileName) throws ParseException { List<String> options = OptionsFileLoader.loadOptions(optionFileName); options.addAll(commandLine.getArgList()); commandLine = cliParser.parse(cliOptions, options.toArray(new String[0])); }
java
{ "resource": "" }