auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public Boolean hasModifierProperty(@NotNull PsiModifierList modifierList, @NotNull String name) { final PsiElement parent = modifierList.getParent(); //Only apply final modifier to val local variables if (parent instanceof PsiLocalVariable && isVal((PsiLocalVariable) parent)) { return PsiModifier.FINAL.equals(name) ? Boolean.TRUE : null; } return null; }

Target:
public Boolean hasModifierProperty(@NotNull PsiModifierList modifierList, @NotNull String name) { final PsiElement parent = modifierList.getParent(); //Only apply final modifier to val local variables if (PsiModifier.FINAL.equals(name) && parent instanceof PsiLocalVariable && isVal((PsiLocalVariable) parent)) { return Boolean.TRUE; } return null; }
Source:
public void onEntityCollidedWithBlock(IAlchemyArray array, World world, BlockPos pos, IBlockState state, Entity entity) { double motionY = 1; double motionYGlowstoneMod = 0.1; double motionYFeatherMod = 0.05; entity.fallDistance = 0; TileAlchemyArray tileArray = (TileAlchemyArray) array; entity.motionY = motionY + motionYGlowstoneMod * (tileArray.getStackInSlot(0).getCount() - 1) + motionYFeatherMod * (tileArray.getStackInSlot(1).getCount() - 1); }

Target:
public void onEntityCollidedWithBlock(IAlchemyArray array, World world, BlockPos pos, IBlockState state, Entity entity) { double motionY = 1; double motionYGlowstoneMod = 0.1; double motionYFeatherMod = 0.05; entity.fallDistance = 0; TileAlchemyArray tileArray = (TileAlchemyArray) array; motionY += motionYGlowstoneMod * (tileArray.getStackInSlot(0).getCount() - 1); // Glowstone Dust motionY += motionYFeatherMod * (tileArray.getStackInSlot(1).getCount() - 1); // Feathers entity.motionY = motionY; }
Source:
public static ItemStack compressInventory(ItemStack[] inv, World world) { for (CompressionHandler handler : compressionRegistry) { ItemStack stack = handler.compressInventory(inv, world); if (stack != null && stack != ItemStack.EMPTY) { return stack; } } return null; }

Target:
public static ItemStack compressInventory(ItemStack[] inv, World world) { for (CompressionHandler handler : compressionRegistry) { ItemStack stack = handler.compressInventory(inv, world); if (!stack.isEmpty()) { return stack; } } return null; }
Source:
public ItemStackWrapper(Item item, int stackSize) { this(item, stackSize, 0, null); }

Target:
public ItemStackWrapper(Item item, int stackSize) { this(item, stackSize, 0); }
Source:
private boolean canDeclare(AbstractProject owner) { // In Hudson 1.341+ builds will be triggered via DependencyGraph // Inner class added in Hudson 1.341 String ownerClassName = owner.getClass().getName(); return DependencyGraph.class.getClasses().length > 0 // See HUDSON-5679 -- dependency graph is also not used when triggered from a promotion && !ownerClassName.equals("hudson.plugins.promoted_builds.PromotionProcess"); }

Target:
private boolean canDeclare(AbstractProject owner) { // See HUDSON-5679 -- dependency graph is also not used when triggered from a promotion return !owner.getClass().getName().equals("hudson.plugins.promoted_builds.PromotionProcess"); }
Source:
public void buildDependencyGraph(AbstractProject owner, DependencyGraph graph) { // Can only add dependencies in Hudson 1.341 or higher if (!canDeclare(owner)) return; for (BuildTriggerConfig config : configs) { List<AbstractProject> projectList = config.getProjectList(owner.getParent(), null); for (AbstractProject project : projectList) ParameterizedDependency.add(owner, project, config, graph); } }

Target:
public void buildDependencyGraph(AbstractProject owner, DependencyGraph graph) { // Can only add dependencies in Hudson 1.341 or higher if (!canDeclare(owner)) return; for (BuildTriggerConfig config : configs) { List<AbstractProject> projectList = config.getProjectList(owner.getParent(), null); for (AbstractProject project : projectList) { ParameterizedDependency.add(owner, project, config, graph); } } }
Source:
public static void smite(final Player player) { smite(player, reason); }

Target:
public static void smite(final Player player) { String reason = null; smite(player, reason); }
Source:
public void whenSealed() { assertLine("whenSealed.when", ICounter.FULLY_COVERED, 0, 0); assertLine("whenSealed.case1", ICounter.FULLY_COVERED, 0, 2); // without filter next line covered partly and has one uncovered branch: assertLine("whenSealed.case2", ICounter.FULLY_COVERED, 0, 0); assertLine("whenSealed.return", ICounter.FULLY_COVERED, 0, 0); }

Target:
public void whenSealed() { assertLine("whenSealed.when", ICounter.FULLY_COVERED); assertLine("whenSealed.case1", ICounter.FULLY_COVERED, 0, 2); // without filter next line covered partly and has one uncovered branch: assertLine("whenSealed.case2", ICounter.FULLY_COVERED); assertLine("whenSealed.return", ICounter.FULLY_COVERED); }
Source:
public void testSetPredecessor() { final Instruction predecessor = new Instruction( new InsnNode(Opcodes.NOP), 122); instruction.setPredecessor(predecessor, 0); assertEquals(1, predecessor.getBranches()); try { instruction.setPredecessor(predecessor, 0); fail("exception expected"); } catch (IllegalStateException e) { // expected } }

Target:
public void testSetPredecessor() { final Instruction predecessor = new Instruction( new InsnNode(Opcodes.NOP), 122); instruction.setPredecessor(predecessor, 0); assertEquals(1, predecessor.getBranches()); }
Source:
void restOfInit(IClientConfig clientConfig) { refeshIntervalMills = Integer.parseInt(clientConfig.getProperty( CommonClientConfigKey.ServerListRefreshInterval, LISTOFSERVERS_CACHE_REPEAT_INTERVAL).toString()); boolean primeConnection = this.isEnablePrimingConnections(); // turn this off to avoid duplicated asynchronous priming done in BaseLoadBalancer.setServerList() this.setEnablePrimingConnections(false); enableAndInitLearnNewServersFeature(); updateListOfServers(); if (primeConnection && this.getPrimeConnections() != null) { this.getPrimeConnections() .primeConnections(getServerList(true)); } this.setEnablePrimingConnections(primeConnection); }

Target:
void restOfInit(IClientConfig clientConfig) { refeshIntervalMills =clientConfig.get(CommonClientConfigKey.ServerListRefreshInterval, LISTOFSERVERS_CACHE_REPEAT_INTERVAL); boolean primeConnection = this.isEnablePrimingConnections(); // turn this off to avoid duplicated asynchronous priming done in BaseLoadBalancer.setServerList() this.setEnablePrimingConnections(false); enableAndInitLearnNewServersFeature(); updateListOfServers(); if (primeConnection && this.getPrimeConnections() != null) { this.getPrimeConnections() .primeConnections(getServerList(true)); } this.setEnablePrimingConnections(primeConnection); }
Source:
public void setCredentialsRefreshInterval( Integer credentialsRefreshInterval) { // Convert seconds to milliseconds this.credentialsRefreshInterval = credentialsRefreshInterval * 1000; }

Target:
public void setCredentialsRefreshInterval( Integer credentialsRefreshInterval) { this.credentialsRefreshInterval = credentialsRefreshInterval; }
Source:
public static JsonParser enterPath(JsonParser parser, String path) throws IOException { if (!parser.isExpectedStartObjectToken()) return null; JsonToken value; while ((value = parser.nextValue()) != JsonToken.END_OBJECT) { if (value == null) { // End of input. throw new IOException("End of input while parsing object."); } if (parser.getCurrentName().equals(path) && value != JsonToken.VALUE_NULL) { return parser; } else { parser.skipChildren(); } } return null; }

Target:
public static JsonParser enterPath(JsonParser parser, String path) throws IOException { if (!parser.isExpectedStartObjectToken()) return null; JsonToken value; while ((value = parser.nextValue()) != JsonToken.END_OBJECT) { if (value == null) { // End of input so ignore. return null; } if (parser.getCurrentName().equals(path) && value != JsonToken.VALUE_NULL) { return parser; } else { parser.skipChildren(); } } return null; }
Source:
public void close() { ExecutorService maybeNull = maybeNull(); if (maybeNull != null) { maybeNull.shutdownNow(); try { maybeNull.awaitTermination(5, TimeUnit.SECONDS); } catch (InterruptedException e) { // at least we tried } } }

Target:
public void close() { ExecutorService maybeNull = maybeNull(); if (maybeNull != null) { maybeNull.shutdownNow(); try { maybeNull.awaitTermination(1, TimeUnit.SECONDS); } catch (InterruptedException e) { // at least we tried } } }
Source:
protected int compare(Number number) { // At this point number can be a floating point number and it should be treated differently in such case: if ( number instanceof Double ) { return NumberComparatorHelper.compare( (Double) number, maxValue, InfinityNumberComparatorHelper.GREATER_THAN ); } if ( number instanceof Float ) { return NumberComparatorHelper.compare( (Float) number, maxValue, InfinityNumberComparatorHelper.GREATER_THAN ); } return NumberComparatorHelper.compare( number, maxValue ); }

Target:
protected int compare(Number number) { return NumberComparatorHelper.compare( number, maxValue, InfinityNumberComparatorHelper.GREATER_THAN ); }
Source:
@Override public Class<?> getDeclaringClass() { return declaringClass; }

Target:
public Class<?> getDeclaringClass() { return declaringClass; }
Source:
private boolean isAnnotationAllowed(Annotation annotationToCheck, Set<Annotation> processedAnnotations) { // need to have this to prevent infinite loops for example on annotations like @Target if ( !processedAnnotations.add( annotationToCheck ) ) { return false; } Class<? extends Annotation> annotationType = annotationToCheck.annotationType(); return ALLOWED_ANNOTATIONS.contains( annotationType ) || Arrays.stream( annotationType.getDeclaredAnnotations() ) .anyMatch( annotation -> isAnnotationAllowed( annotation, processedAnnotations ) ); }

Target:
private boolean isAnnotationAllowed(Annotation annotationToCheck, Set<Annotation> processedAnnotations) { // Need to have this to prevent infinite loops, for example on annotations like @Target if ( !processedAnnotations.add( annotationToCheck ) ) { return false; } Class<? extends Annotation> annotationType = annotationToCheck.annotationType(); if ( ALLOWED_ANNOTATIONS.contains( annotationType ) ) { return true; } for ( Annotation annotation : annotationType.getDeclaredAnnotations() ) { if ( isAnnotationAllowed( annotation, processedAnnotations ) ) { return true; } } return false; }
Source:
public boolean equals(Object o) { if ( this == o ) { return true; } if ( o == null || o.getClass() != BeanGroupProcessedUnit.class ) { return false; } BeanGroupProcessedUnit that = (BeanGroupProcessedUnit) o; if ( bean != that.bean ) { // instance equality return false; } if ( !group.equals( that.group ) ) { return false; } return true; }

Target:
public boolean equals(Object o) { if ( this == o ) { return true; } // No need to check if the class matches because of how this class is used in the set. BeanGroupProcessedUnit that = (BeanGroupProcessedUnit) o; if ( bean != that.bean ) { // instance equality return false; } if ( !group.equals( that.group ) ) { return false; } return true; }
Source:
public boolean equals(Object o) { // no need to check for instance equality or if the calss match because of // how this class is used in the set. BeanPathMetaConstraintProcessedUnit that = (BeanPathMetaConstraintProcessedUnit) o; if ( bean != that.bean ) { // instance equality return false; } if ( metaConstraint != that.metaConstraint ) { return false; } if ( !path.equals( that.path ) ) { return false; } return true; }

Target:
public boolean equals(Object o) { if ( this == o ) { return true; } // No need to check if the class matches because of how this class is used in the set. BeanPathMetaConstraintProcessedUnit that = (BeanPathMetaConstraintProcessedUnit) o; if ( bean != that.bean ) { // instance equality return false; } if ( metaConstraint != that.metaConstraint ) { return false; } if ( !path.equals( that.path ) ) { return false; } return true; }
Source:
protected GroupConversionDescriptorSetAssert(Set<GroupConversionDescriptor> actual) { super( new ArrayList( actual ) ); this.actual = actual; }

Target:
protected GroupConversionDescriptorSetAssert(Set<GroupConversionDescriptor> actual) { super( actual ); this.actual = actual; }
Source:
public Object invoke(ELContext context, Object base, Object method, Class<?>[] paramTypes, Object[] params) { if ( resolve( context, base, method ) ) { throw new ValidationException( "Invalid property" ); } Object returnValue = null; // due to bugs in most EL implementations when it comes to evaluating varargs we take care of the formatter call // ourselves. if ( base instanceof FormatterWrapper ) { returnValue = evaluateFormatExpression( context, base, method, paramTypes, params ); } return returnValue; }

Target:
public Object invoke(ELContext context, Object base, Object method, Class<?>[] paramTypes, Object[] params) { if ( resolve( context, base, method ) ) { throw new ValidationException( "Invalid property" ); } Object returnValue = null; // due to bugs in most EL implementations when it comes to evaluating varargs we take care of the formatter call // ourselves. if ( base instanceof FormatterWrapper ) { returnValue = evaluateFormatExpression( context, method, params ); } return returnValue; }
Source:
public void EdgeReached(Direction edge) { postEvent(this, "EdgeReached", edge); }

Target:
public void EdgeReached(Direction edge) { // We will have to use getValue() to send an int for backwards-compat. But I decided to use this // function as the base because I think converting the enum is a better check than the one from // before. // But if you think using the old func as the base is less confusing, we can do that. postEvent(this, "EdgeReached", edge.getValue()); }
Source:
public void updateMenuState(int numSelectedProjects, int numProjects) { boolean allowDelete = !isReadOnly && numSelectedProjects > 0; boolean allowExport = numSelectedProjects > 0; boolean allowExportAll = numProjects > 0; String exportProjectLabel = numSelectedProjects > 1 ? MESSAGES.exportSelectedProjectsMenuItem() : MESSAGES.exportProjectMenuItem(); fileDropDown.setItemHtmlById(WIDGET_NAME_EXPORTPROJECT, exportProjectLabel); fileDropDown.setItemEnabled(MESSAGES.deleteProjectMenuItem(), allowDelete); fileDropDown.setItemEnabledById(WIDGET_NAME_EXPORTPROJECT, allowExport); fileDropDown.setItemEnabled(MESSAGES.exportAllProjectsMenuItem(), allowExportAll); }

Target:
public void updateMenuState(int numSelectedProjects, int numProjects) { boolean allowDelete = !isReadOnly && numSelectedProjects > 0; boolean allowExport = numSelectedProjects > 0; boolean allowExportAll = numProjects > 0; String exportProjectLabel = numSelectedProjects > 1 ? MESSAGES.exportSelectedProjectsMenuItem(numSelectedProjects) : MESSAGES.exportProjectMenuItem(); fileDropDown.setItemHtmlById(WIDGET_NAME_EXPORTPROJECT, exportProjectLabel); fileDropDown.setItemEnabled(MESSAGES.deleteProjectMenuItem(), allowDelete); fileDropDown.setItemEnabledById(WIDGET_NAME_EXPORTPROJECT, allowExport); fileDropDown.setItemEnabled(MESSAGES.exportAllProjectsMenuItem(), allowExportAll); }
Source:
public int getLeftX() { try { return (int) Math.round(Double.parseDouble(getPropertyValue(PROPERTY_NAME_X))); } catch (NumberFormatException e) { // Ignore this. If we throw an exception here, the project is unrecoverable. return 0; } }

Target:
public int getLeftX() { return x; }
Source:
public int getTopY() { try { return (int) Math.round(Double.parseDouble(getPropertyValue(PROPERTY_NAME_Y))); } catch (NumberFormatException e) { // Ignore this. If we throw an exception here, the project is unrecoverable. return 0; } }

Target:
public int getTopY() { return y; }
Source:
public MockBarChartDataModel(MockBarChartView view) { super(view.getChartWidget().getData()); // Set local view variable (needed to invoke the updateLabels method) this.view = view; // Create the Data Series object dataSeries = new BarDataset(); // Set the default style properties for the Data Series setDefaultStylingProperties(); // Adds the Data Series to the Chart. addDataSeriesToChart(); }

Target:
public MockBarChartDataModel(MockBarChartView view) { super(view); // Create the Data Series object dataSeries = new BarDataset(); // Set the default style properties for the Data Series setDefaultStylingProperties(); // Adds the Data Series to the Chart. addDataSeriesToChart(); }
Source:
public void addDataFile(MockDataFile dataFileSource) { List<String> columnNames = dataFileSource.getColumnNames(); for (String column : columnNames) { // Create a new MockChartData2D component and attach it to the Chart // TODO: More data component support MockChartData2D data = new MockChartData2D(editor); addComponent(data); data.addToChart(MockChart.this); // Change the properties of the instantiated data component data.changeProperty("DataFileYColumn", column); data.changeProperty("Label", column); data.changeProperty("Source", dataFileSource.getName()); } }

Target:
public void addDataFile(MockDataFile dataFileSource) { List<String> columnNames = dataFileSource.getColumnNames(); for (String column : columnNames) { // Create a new MockChartData2D component and attach it to the Chart // TODO: More data component support MockChartData2D data = new MockChartData2D(editor); addComponent(data); data.addToChart(this); // Change the properties of the instantiated data component data.changeProperty("DataFileYColumn", column); data.changeProperty("Label", column); data.changeProperty("Source", dataFileSource.getName()); } }
Source:
public List<List<String>> getColumns(List<String> columns) { ArrayList<List<String>> dataColumns = new ArrayList<List<String>>(); for (String column : columns) { // Get the index of the column and get the column itself int index = columnNames.indexOf(column); List<String> dataColumn = getColumn(index); // Add the column to the result dataColumns.add(dataColumn); } return dataColumns; }

Target:
public List<List<String>> getColumns(List<String> columns) { List<List<String>> dataColumns = new ArrayList<List<String>>(); for (String column : columns) { // Get the index of the column and get the column itself int index = columnNames.indexOf(column); List<String> dataColumn = getColumn(index); // Add the column to the result dataColumns.add(dataColumn); } return dataColumns; }
Source:
public void onColumnsChange(MockDataFile dataFile) { // Edge case: Event originates from the wrong MockDataFile source if (!this.dataFile.equals(dataFile)) { return; } // Update the column entries updateColumns(); }

Target:
public void onColumnsChange(MockDataFile dataFile) { // Edge case: Event originates from the wrong MockDataFile source if (this.dataFile != dataFile) { return; } // Update the column entries updateColumns(); }
Source:
public void removeDataObserver(ChartDataBase dataComponent) { dataSourceObservers.remove(dataComponent); // No more Data Source observers exist; // Shut down polling service and null it // (the reason for nulling is so that a new // service could be created upon adding a new // observer) if (dataSourceObservers.isEmpty()) { dataPollService.shutdown(); dataPollService = null; } }

Target:
public synchronized void removeDataObserver(ChartDataBase dataComponent) { dataSourceObservers.remove(dataComponent); // No more Data Source observers exist; // Shut down polling service and null it // (the reason for nulling is so that a new // service could be created upon adding a new // observer) if (dataSourceObservers.isEmpty()) { dataPollService.shutdown(); dataPollService = null; } }
Source:
public void Namespace(String namespace) { this.namespace = namespace; sharedPreferences = context.getSharedPreferences(namespace, Context.MODE_PRIVATE); // SharedPreferences listener currently exists; Unregister it if (sharedPreferenceChangeListener != null) { sharedPreferences.unregisterOnSharedPreferenceChangeListener(sharedPreferenceChangeListener); } // Create a new SharedPreferences change listener sharedPreferenceChangeListener = new SharedPreferences.OnSharedPreferenceChangeListener() { @Override public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { // Upon value change, notify the observers with the key and the value notifyDataObservers(key, GetValue(key, null)); } }; // Register the SharedPreferences change listener sharedPreferences.registerOnSharedPreferenceChangeListener(sharedPreferenceChangeListener); }

Target:
public void Namespace(String namespace) { this.namespace = namespace; // SharedPreferences previously defined; Unregister the change listener. if (sharedPreferences != null) { sharedPreferences.unregisterOnSharedPreferenceChangeListener(sharedPreferenceChangeListener); } sharedPreferences = context.getSharedPreferences(namespace, Context.MODE_PRIVATE); // Register the SharedPreferences change listener sharedPreferences.registerOnSharedPreferenceChangeListener(sharedPreferenceChangeListener); }
Source:
public List getDataValue(String key) { // Get the value from the TinyDB data with the specified key Object value = GetValue(key, new ArrayList()); // Check if value is of type List, and return it if that is the case. if (value instanceof List) { return (List)value; } // Default option (could not parse data): return empty ArrayList return new ArrayList(); }

Target:
public List<Object> getDataValue(String key) { // Get the value from the TinyDB data with the specified key Object value = GetValue(key, new ArrayList()); // Check if value is of type List, and return it if that is the case. if (value instanceof List) { return (List<Object>) value; } // Default option (could not parse data): return empty ArrayList return new ArrayList<Object>(); }
Source:
private YailList getYailListPropertyHelper(Callable<YailList> propertyCallable) { // Since reading might be in progress, the task of // getting a DataFile property should be queued so that the // thread is blocked until the reading is finished. try { return threadRunner .submit(propertyCallable) // Run the callable async (and queued) .get(); // Get the property (blocks thread until previous threads finish) } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } return new YailList(); // Return empty list (default option) }

Target:
private YailList getYailListPropertyHelper(Callable<YailList> propertyCallable) { // Since reading might be in progress, the task of // getting a DataFile property should be queued so that the // thread is blocked until the reading is finished. try { return threadRunner .submit(propertyCallable) // Run the callable async (and queued) .get(); // Get the property (blocks thread until previous threads finish) } catch (InterruptedException e) { Log.e(this.getClass().getName(), e.getMessage()); } catch (ExecutionException e) { Log.e(this.getClass().getName(), e.getMessage()); } return new YailList(); // Return empty list (default option) }
Source:
public void changePreviewSize(int width, int height, int idx) { // It will definitely be modified in the future to add more options. PORTRAIT_WIDTH = width; PORTRAIT_HEIGHT = height; LANDSCAPE_WIDTH = height; LANDSCAPE_HEIGHT = width; idxPhoneSize = idx; setPhoneStyle(); if (landscape) resizePanel(LANDSCAPE_WIDTH, LANDSCAPE_HEIGHT); else resizePanel(width, height); }

Target:
public void changePreviewSize(int width, int height, int idx) { // It will definitely be modified in the future to add more options. PORTRAIT_WIDTH = width; PORTRAIT_HEIGHT = height; LANDSCAPE_WIDTH = height; LANDSCAPE_HEIGHT = width; idxPhoneSize = idx; setPhoneStyle(); if (landscape) { resizePanel(LANDSCAPE_WIDTH, LANDSCAPE_HEIGHT); } else { resizePanel(width, height); } }
Source:
public void unregisterPercentLength(AndroidViewComponent component, PercentStorageRecord.Dim dim) { // iterate map, remove all entry match this for (Integer key : dimChanges.keySet()) { dimChanges.remove(generateHashCode(component, dim)); } }

Target:
public void unregisterPercentLength(AndroidViewComponent component, PercentStorageRecord.Dim dim) { // iterate map, remove all entry match this dimChanges.remove(generateHashCode(component, dim)); }
Source:
public TooltipImpl(Element element, TooltipOptions options) { this.$element = $(element); this.options = getOptions(options); //Is GWT optimization works here ? if (options.getResources() != null){ this.style = options.getResources().css(); } else{ this.style = getDefaultResources().css(); } init(); }

Target:
public TooltipImpl(Element element, TooltipOptions options) { this(element, options, getDefaultResources()); }
Source:
public List getExtensions() { return ImmutableList.of( PropertyDefinition.builder(XmlPlugin.FILE_SUFFIXES_KEY) .name("File suffixes") .description("Comma-separated list of suffixes for files to analyze.") .defaultValue(".xml") .category("XML") .onQualifiers(Qualifiers.PROJECT) .build(), Xml.class, XmlRulesDefinition.class, XmlSonarWayProfile.class, // Sensors XmlSensor.class, LineCounter.class, XmlCodeColorizerFormat.class); }

Target:
public List getExtensions() { return ImmutableList.of( PropertyDefinition.builder(XmlPlugin.FILE_SUFFIXES_KEY) .name("File suffixes") .description("Comma-separated list of suffixes for files to analyze.") .defaultValue(".xml") .category("XML") .onQualifiers(Qualifiers.PROJECT) .build(), Xml.class, XmlRulesDefinition.class, XmlSonarWayProfile.class, // Sensors XmlSensor.class); }
Source:
protected String generateApiKey() { return new UUIDGenerator().generate(); }

Target:
private String generateApiKey() { return new UUIDGenerator().generate(); }
Source:
public boolean skipValue() throws IOException { // NOTE: This implementation must be as efficient as possible int remainingValues = 1; while(remainingValues > 0) { MessageFormat f = getNextFormat(); if(f == MessageFormat.EOF) return false; remainingValues += f.skip(this); remainingValues--; } return true; }

Target:
public boolean skipValue() throws IOException { // NOTE: This implementation must be as efficient as possible int remainingValues = 1; while(remainingValues > 0) { MessageFormat f = getNextFormat(); remainingValues += f.skip(this); remainingValues--; } return true; }
Source:
public static final void addSearchPathSuffix(String libraryName, String pathSuffix) { File ps = new File(pathSuffix); // only accept the suffix if it is not an absolute path if (!ps.isAbsolute()) { synchronized (pathSuffixes) { List customPaths = (List) pathSuffixes.get(libraryName); if (customPaths == null) { customPaths = Collections.synchronizedList(new LinkedList()); pathSuffixes.put(libraryName, customPaths); } customPaths.add(pathSuffix); } } }

Target:
public static final void addSearchPathSuffix(String libraryName, String pathSuffix) { File ps = new File(pathSuffix); // only accept the suffix if it is not an absolute path if (!ps.isAbsolute()) { synchronized (pathSuffixes) { List<String> customPaths = pathSuffixes.get(libraryName); if (customPaths == null) { customPaths = Collections.synchronizedList(new LinkedList<String>()); pathSuffixes.put(libraryName, customPaths); } customPaths.add(pathSuffix); } } }
Source:
public COMLateBindingBaseObject(IDispatch dispatch) { // enable JNA protected mode Native.setProtected(true); // transfer the value this.iDispatch = dispatch; }

Target:
public COMLateBindingBaseObject(IDispatch dispatch) { // transfer the value this.iDispatch = dispatch; }
Source:
public void emit(ErrorType etype, ANTLRMessage msg) { switch ( etype.severity ) { case WARNING_ONE_OFF: case ERROR_ONE_OFF: if ( errorTypes.contains(etype) ) break; // fall thru case WARNING: warnings++; tool.warning(msg); break; case ERROR: errors++; tool.error(msg); break; } errorTypes.add(etype); }

Target:
public void emit(ErrorType etype, ANTLRMessage msg) { switch ( etype.severity ) { case WARNING_ONE_OFF: if ( errorTypes.contains(etype) ) break; // fall thru case WARNING: warnings++; tool.warning(msg); break; case ERROR_ONE_OFF: if ( errorTypes.contains(etype) ) break; // fall thru case ERROR: errors++; tool.error(msg); break; } errorTypes.add(etype); }
Source:
public Token match(int ttype) throws RecognitionException { Token t = getCurrentToken(); if ( t.getType()==ttype ) { if ( t.getType()==Token.EOF ) { matchedEOF = true; } _errHandler.reportMatch(this); consume(); } else { t = _errHandler.recoverInline(this); if ( _buildParseTrees && t.getTokenIndex()==-1 ) { // we must have conjured up a new token during single token insertion // if it's not the current symbol _ctx.addErrorNode(t); } } return t; }

Target:
public Token match(int ttype) throws RecognitionException { Token t = getCurrentToken(); if ( t.getType()==ttype ) { if ( ttype==Token.EOF ) { matchedEOF = true; } _errHandler.reportMatch(this); consume(); } else { t = _errHandler.recoverInline(this); if ( _buildParseTrees && t.getTokenIndex()==-1 ) { // we must have conjured up a new token during single token insertion // if it's not the current symbol _ctx.addErrorNode(t); } } return t; }
Source:
public boolean shouldCaptureBuildInfo(@NotNull TaskContext taskContext) { boolean shouldCaptureBuildInfo = false; if (isCaptureBuildInfo()) { shouldCaptureBuildInfo = true; } else { if (isPublishBuildInfo()) { // First check if there is a publish build info task. if there is then use aggregation List<? extends TaskDefinition> taskDefinitions = taskContext.getBuildContext().getRuntimeTaskDefinitions(); if (TaskDefinitionHelper.isBuildPublishTaskExists(taskDefinitions)) { shouldCaptureBuildInfo = true; resetPublishBuildInfo(); } } } return shouldCaptureBuildInfo; }

Target:
public boolean shouldCaptureBuildInfo(@NotNull TaskContext taskContext) { if (isCaptureBuildInfo()) { return true; } if (isPublishBuildInfo()) { // First check if there is a publish build info task. if there is then use aggregation List<? extends TaskDefinition> taskDefinitions = taskContext.getBuildContext().getRuntimeTaskDefinitions(); if (TaskDefinitionHelper.isBuildPublishTaskExists(taskDefinitions)) { resetPublishBuildInfo(); return true; } } return false; }
Source:
public static TaskDefinition findReleaseTaskDefinition(List<? extends TaskDefinition> taskDefinitions) { if (taskDefinitions != null) { for (TaskDefinition taskDefinition : taskDefinitions) { if (taskDefinition.isEnabled()) { AbstractBuildContext config = AbstractBuildContext.createContextFromMap(taskDefinition.getConfiguration()); // Check the release management is enabled if ((config != null) && config.releaseManagementContext.isReleaseMgmtEnabled()) { return taskDefinition; } } } } return null; }

Target:
public static TaskDefinition findReleaseTaskDefinition(List<? extends TaskDefinition> taskDefinitions) { if (taskDefinitions != null) { for (TaskDefinition taskDefinition : taskDefinitions) { if (taskDefinition.isEnabled() && isReleaseMgmtEnabled(taskDefinition)) { return taskDefinition; } } } return null; }
Source:
private void handleEditorImage(Intent data) { String newFilePath = data.getStringExtra(EditImageActivity.EXTRA_OUTPUT); boolean isImageEdit = data.getBooleanExtra(EditImageActivity.IMAGE_IS_EDIT, false); if (isImageEdit) { } else {//Or use the original unedited pictures newFilePath = data.getStringExtra(EditImageActivity.FILE_PATH); ; } //System.out.println("newFilePath---->" + newFilePath); //File file = new File(newFilePath); //System.out.println("newFilePath size ---->" + (file.length() / 1024)+"KB"); Log.d("image is edit", isImageEdit + ""); LoadImageTask loadTask = new LoadImageTask(); loadTask.execute(newFilePath); }

Target:
private void handleEditorImage(Intent data) { String newFilePath = data.getStringExtra(EditImageActivity.EXTRA_OUTPUT); boolean isImageEdit = data.getBooleanExtra(EditImageActivity.IMAGE_IS_EDIT, false); if (isImageEdit) { } else {//Or use the original unedited pictures newFilePath = data.getStringExtra(EditImageActivity.FILE_PATH); } //System.out.println("newFilePath---->" + newFilePath); //File file = new File(newFilePath); //System.out.println("newFilePath size ---->" + (file.length() / 1024)+"KB"); Log.d("image is edit", isImageEdit + ""); LoadImageTask loadTask = new LoadImageTask(); loadTask.execute(newFilePath); }
Source:
private void handleZoom(MotionEvent event, Camera.Parameters params) { int maxZoom = params.getMaxZoom(); int zoom = params.getZoom(); float newDist = getFingerSpacing(event); if (newDist > mDist) { //zoom in if (zoom < maxZoom) zoom+=6; } else if (newDist < mDist) { //zoom out if (zoom > 0) zoom-=6; } mDist = newDist; params.setZoom(zoom); mCamera.setParameters(params); }

Target:
private void handleZoom(MotionEvent event, Camera.Parameters params) { int maxZoom = params.getMaxZoom(); int zoom = params.getZoom(); float newDist = getFingerSpacing(event); if (newDist > mDist && zoom < maxZoom) { //zoom in zoom+=6; } else if (newDist < mDist && zoom > 0) { //zoom out zoom-=6; } mDist = newDist; params.setZoom(zoom); mCamera.setParameters(params); }
Source:
private boolean entitySupportRetry(HttpRequest request) { boolean entitySupportRetry = true; if (request.getEntity() != null) { if (request.getEntity() instanceof InputStreamHttpEntity) { // If input stream is not 'mark supported' can not be consumed again so retry is not supported entitySupportRetry = ((InputStreamHttpEntity) request.getEntity()).getInputStream().markSupported(); } } return entitySupportRetry; }

Target:
private boolean entitySupportRetry(HttpRequest request) { boolean entitySupportRetry = true; if (request.getEntity() != null && request.getEntity() instanceof InputStreamHttpEntity) { // If input stream is not 'mark supported' can not be consumed again so retry is not supported entitySupportRetry = ((InputStreamHttpEntity) request.getEntity()).getInputStream().markSupported(); } return entitySupportRetry; }
Source:
private Throwable getExceptionCause(Throwable throwable) { // For subclasses of ModuleException, we use it as it already contains additional information if (throwable.getClass().equals(ModuleException.class)) { return throwable.getCause() != null ? suppressIfPresent(throwable.getCause(), MessagingException.class) : new MuleRuntimeException(createStaticMessage(throwable.getMessage())); } else { return throwable; } }

Target:
private Throwable getExceptionCause(Throwable throwable) { // For subclasses of ModuleException, we use it as it already contains additional information if (throwable.getClass().equals(ModuleException.class)) { return throwable.getCause() != null ? suppressIfPresent(throwable.getCause(), MessagingException.class) : new MuleRuntimeException(createStaticMessage(throwable.getMessage())); } else { return suppressIfPresent(throwable, MessagingException.class); } }
Source:
public ClassLoaderModel build() { Optional<Plugin> pluginOptional = empty(); if (processSharedLibraries || processAdditionalPluginLibraries) { pluginOptional = findMuleMavenPluginDeclaration(); } if (processSharedLibraries) { pluginOptional.ifPresent(this::exportSharedLibrariesResourcesAndPackages); } if (processAdditionalPluginLibraries) { pluginOptional.ifPresent(this::processAdditionalPluginLibraries); } // do the filtering of local packages and resources after exported and processed sharedRuntimeLibraries and additionalPluginDependencies localPackages.removeAll(packages); localResources.removeAll(resources); return super.build(); }

Target:
public ClassLoaderModel build() { Optional<Plugin> pluginOptional = empty(); if (processSharedLibraries || processAdditionalPluginLibraries) { pluginOptional = findMuleMavenPluginDeclaration(); } if (processSharedLibraries) { pluginOptional.ifPresent(this::exportSharedLibrariesResourcesAndPackages); } if (processAdditionalPluginLibraries) { pluginOptional.ifPresent(this::processAdditionalPluginLibraries); } return super.build(); }
Source:
public void sendResponseToClient(CoreEvent response, Map<String, Object> parameters, CompletableCallback<Void> callback) { ((BaseEventContext) response.getContext()).success(); }

Target:
public void sendResponseToClient(CoreEvent response, Map<String, Object> parameters, CompletableCallback<Void> callback) { // Do nothing. }
Source:
private void doPoll() { try { InternalEvent internalEvent = InternalEvent.builder(EventContextFactory.create(flowConstruct, getLocation())).message(Message.of(null)).build(); setCurrentEvent(internalEvent); messageProcessingManager .processMessage(flowProcessingTemplate, flowProcessContext); } catch (Exception e) { muleContext.getExceptionListener().handleException(e); } }

Target:
private void doPoll() { try { setCurrentEvent(InternalEvent.builder(EventContextFactory.create(flowConstruct, getLocation())).message(Message.of(null)) .build()); messageProcessingManager.processMessage(flowProcessingTemplate, flowProcessContext); } catch (Exception e) { muleContext.getExceptionListener().handleException(e); } }
Source:
public void doNotExpireDynamicConfigWithCustomExpirationUsedBySource() throws Exception { HeisenbergExtension config = invokeDynamicConfig("dynamicWithCustomExpirationForSource", "heisenbergWithCustomExpirationForSource", "Walter Blanco"); try { assertExpired(config, 10000, 1000); fail("Config should not have been expired"); } catch (AssertionError e) { assertThat(e.getMessage(), is(not("Config should not have been expired"))); } assertInitialised(config); sourceWithDynamicConfig.stop(); assertExpired(config, 6000, 100); }

Target:
public void doNotExpireDynamicConfigWithCustomExpirationUsedBySource() throws Exception { HeisenbergExtension config = invokeDynamicConfig("dynamicWithCustomExpirationForSource", "heisenbergWithCustomExpirationForSource", "Walter Blanco"); try { assertExpired(config, 10000, 1000); throw new IllegalStateException("Config should not have been expired"); } catch (AssertionError e) { //all good } assertInitialised(config); sourceWithDynamicConfig.stop(); assertExpired(config, 6000, 100); }
Source:
private CoreEvent addContextToEvent(CoreEvent event, Context ctx) { final CoreEvent eventWithContext; if (ctx.hasKey(POLICY_NEXT_OPERATION)) { return quickCopy(event, singletonMap(INNER_CHAIN_CTX_MAPPING, (Function<Context, Context>) (innerChainCtx -> innerChainCtx .put(POLICY_NEXT_OPERATION, ctx.get(POLICY_NEXT_OPERATION))))); } else { return event; } }

Target:
private CoreEvent addContextToEvent(CoreEvent event, Context ctx) { if (ctx.hasKey(POLICY_NEXT_OPERATION)) { return quickCopy(event, singletonMap(INNER_CHAIN_CTX_MAPPING, (Function<Context, Context>) (innerChainCtx -> innerChainCtx .put(POLICY_NEXT_OPERATION, ctx.get(POLICY_NEXT_OPERATION))))); } else { return event; } }
Source:
void test() { Function<String, String> trimmer = s -> s.trim(); // warn }

Target:
void test() { Function<String, String> trimmer = (s) -> s.trim(); // warn }
Source:
public int compareOrder(NodeInfo other) { int result = 0; if (other instanceof ElementNode) { result = getDepth() - ((AbstractNode) other).getDepth(); if (result == 0) { final ElementNode[] children = getCommonAncestorChildren(other); result = children[0].indexAmongSiblings - children[1].indexAmongSiblings; } } return result; }

Target:
public int compareOrder(NodeInfo other) { int result = 0; if (other instanceof AbstractNode) { result = getDepth() - ((AbstractNode) other).getDepth(); if (result == 0) { final ElementNode[] children = getCommonAncestorChildren(other); result = children[0].indexAmongSiblings - children[1].indexAmongSiblings; } } return result; }
Source:
public void visitToken(final DetailAST ast) { if (!allowClassImports && ast.getType() == TokenTypes.IMPORT) { final DetailAST startingDot = ast.getFirstChild(); logsStarredImportViolation(startingDot); } else if (!allowStaticMemberImports) { // must navigate past the static keyword final DetailAST startingDot = ast.getFirstChild().getNextSibling(); logsStarredImportViolation(startingDot); } }

Target:
public void visitToken(final DetailAST ast) { if (ast.getType() == TokenTypes.IMPORT) { if (!allowClassImports) { final DetailAST startingDot = ast.getFirstChild(); logsStarredImportViolation(startingDot); } } else if (!allowStaticMemberImports) { // must navigate past the static keyword final DetailAST startingDot = ast.getFirstChild().getNextSibling(); logsStarredImportViolation(startingDot); } }
Source:
public boolean isMatch(TreeWalkerAuditEvent event) { boolean match = false; if (isInScopeOfSuppression(event)) { if (isCheckMatch(event)) { match = isMessageMatch(event); } else if (isIdMatch(event)) { match = isMessageMatch(event); } } return match; }

Target:
public boolean isMatch(TreeWalkerAuditEvent event) { return isInScopeOfSuppression(event) && (isCheckMatch(event) || isIdMatch(event)) && isMessageMatch(event); }
Source:
public ParseErrorMessage(int lineNumber, String messageKey, Object... messageArguments) { this.lineNumber = lineNumber; this.messageKey = messageKey; this.messageArguments = messageArguments.clone(); }

Target:
/* default */ ParseErrorMessage(int lineNumber, String messageKey, Object... messageArguments) { this.lineNumber = lineNumber; this.messageKey = messageKey; this.messageArguments = messageArguments.clone(); }
Source:
public void onCreate(Bundle savedInstanceState) { if (DEVELOPER_MODE) { StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().detectDiskReads() .detectDiskWrites().detectNetwork().penaltyLog().build()); StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder().detectLeakedSqlLiteObjects() .detectAll().penaltyLog().penaltyDeath().build()); } super.onCreate(savedInstanceState); // Initial all the data needed initData(); // Initial the UI manually. initUi(); }

Target:
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Initial all the data needed initData(); // Initial the UI manually. initUi(); }
Source:
protected IOReport execute(ProgressIndicator progress, IOReporter reporter) throws IOProviderConfigurationException, IOException { // now that the service should be available, build the required source HaleConnectService hcs = getServiceProvider().getService(HaleConnectService.class); // TODO login if applicable? (based on reader parameters) // XXX for now only support public projects LocatableInputSupplier<? extends InputStream> hcSource; try { hcSource = hcs.loadProject(owner, projectId); } catch (HaleConnectException e) { throw new IllegalStateException(); } super.setSource(hcSource); return super.execute(progress, reporter); }

Target:
protected IOReport execute(ProgressIndicator progress, IOReporter reporter) throws IOProviderConfigurationException, IOException { // now that the service should be available, build the required source HaleConnectService hcs = getServiceProvider().getService(HaleConnectService.class); // TODO login if applicable? (based on reader parameters) // XXX for now only support public projects LocatableInputSupplier<? extends InputStream> hcSource; try { hcSource = hcs.loadProject(owner, projectId); } catch (HaleConnectException e) { throw new IllegalStateException(e.getMessage(), e); } super.setSource(hcSource); return super.execute(progress, reporter); }
Source:
public static boolean isCounterClockwise(Geometry geometry) { if (geometry == null) return false; // Get coordinates of geometry Coordinate[] coordinates = geometry.getCoordinates(); // Using algorithm get order of geometry boolean orientation = false; try { orientation = CGAlgorithms.isCCW(coordinates); } catch (IllegalArgumentException ex) { System.err.println("Illegal Argument"); // TODO:: or Throw ? } return orientation; }

Target:
public static boolean isCounterClockwise(Geometry geometry) { if (geometry == null) return false; // Get coordinates of geometry Coordinate[] coordinates = geometry.getCoordinates(); // Get order of geometry using algorithm boolean orientation = false; orientation = CGAlgorithms.isCCW(coordinates); return orientation; }
Source:
protected char getSeparatorCharacter(IServer server) { // Discover the proper separator character for the paths being used char sep = File.separatorChar; IControllableServerBehavior beh = JBossServerBehaviorUtils.getControllableBehavior(server); if( beh != null ) { try { IDeploymentOptionsController cont = (IDeploymentOptionsController)beh.getController(IDeploymentOptionsController.SYSTEM_ID); if( cont != null ) { sep = cont.getPathSeparatorCharacter(); } } catch(CoreException ce) { // Ignore } } return sep; }

Target:
protected char getSeparatorCharacter(IServer server) { // Discover the proper separator character for the paths being used try { IDeploymentOptionsController cont = (IDeploymentOptionsController)JBossServerBehaviorUtils.getController(server, IDeploymentOptionsController.SYSTEM_ID, IDeploymentOptionsController.class); return cont == null ? File.separatorChar : cont.getPathSeparatorCharacter(); } catch(CoreException ce) { // Ignore } return File.separatorChar; }
Source:
private IModuleResource[] getCleanedChildren(IModuleResource[] children) { // Depth-first cleaning ArrayList<IModuleResource> cleaned = new ArrayList<IModuleResource>(); IModuleResource tmp = null; for( int i = 0; i < children.length; i++ ) { tmp = getCleanedResource(children[i]); if( tmp != null ) cleaned.add(tmp); } return cleaned.toArray(new IModuleResource[cleaned.size()]); }

Target:
private IModuleResource[] getCleanedChildren(IModuleResource[] children) { // Depth-first cleaning ArrayList<IModuleResource> cleaned = new ArrayList<IModuleResource>(children.length); IModuleResource tmp = null; for( int i = 0; i < children.length; i++ ) { tmp = getCleanedResource(children[i]); if( tmp != null ) cleaned.add(tmp); } return cleaned.toArray(new IModuleResource[cleaned.size()]); }
Source:
protected IModule promptForModule(ArrayList<IModule> modules) { if(modules.size() == 1 ) return modules.get(0); // TODO prompt return modules.get(0); }

Target:
protected IModule promptForModule(ArrayList<IModule> modules) { if( modules.size() > 0 ) { if(modules.size() == 1 ) return modules.get(0); // TODO prompt. Unfortunately there's no easy way to do this in UI // Since there's no prompt-for-module dialogs in wtp, // and it is unclear what type of ui should be designed return modules.get(0); } return null; }
Source:
protected synchronized void forceStop() { System.out.println("Stopping in forcestop"); //$NON-NLS-1$ // just terminate the process. if( isProcessRunning()) { try { process.terminate(); addForceStopEvent(); } catch( DebugException e ) { addForceStopFailedEvent(e); } } process = null; getActualBehavior().setServerStopped(); nextStopRequiresForce = false; }

Target:
protected synchronized void forceStop() { // just terminate the process. if( isProcessRunning()) { try { process.terminate(); addForceStopEvent(); } catch( DebugException e ) { addForceStopFailedEvent(e); } } process = null; getActualBehavior().setServerStopped(); nextStopRequiresForce = false; }
Source:
private synchronized void handleProcessTerminatedEvent(ProcessTerminatedDebugListener listener) { // If there's a new process that's not equal to myProcess, // then the server is already starting again if( listener.myProcess != null && !listener.myProcess.equals(getProcess())) return; System.out.println(getProcess()); if( getServer().getServerState() != IServer.STATE_STOPPED) { stopPolling(); addProcessTerminatedEvent(); getActualBehavior().setServerStopped(); } DebugPlugin.getDefault().removeDebugEventListener(listener); processListener = null; process = null; nextStopRequiresForce = false; }

Target:
private synchronized void handleProcessTerminatedEvent(ProcessTerminatedDebugListener listener) { // If there's a new process that's not equal to myProcess, // then the server is already starting again if( listener.myProcess != null && !listener.myProcess.equals(getProcess())) return; if( getServer().getServerState() != IServer.STATE_STOPPED) { stopPolling(); addProcessTerminatedEvent(); getActualBehavior().setServerStopped(); } DebugPlugin.getDefault().removeDebugEventListener(listener); processListener = null; process = null; nextStopRequiresForce = false; }
Source:
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); app = (MapzenApplication) getApplication(); app.inject(this); BugSenseHandler.initAndStartSession(this, "ebfa8fd7"); BugSenseHandler.addCrashExtraData("OEM", Build.MANUFACTURER); app = (MapzenApplication) getApplication(); setContentView(R.layout.base); initMapFragment(); gpsPromptDialogFragment = new MapzenGPSPromptDialogFragment(); initMapController(); initLocationClient(); initAlarm(); initSavedSearches(); }

Target:
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); app = (MapzenApplication) getApplication(); app.inject(this); BugSenseHandler.initAndStartSession(this, "ebfa8fd7"); BugSenseHandler.addCrashExtraData("OEM", Build.MANUFACTURER); setContentView(R.layout.base); initMapFragment(); gpsPromptDialogFragment = new MapzenGPSPromptDialogFragment(); initMapController(); initLocationClient(); initAlarm(); initSavedSearches(); }