auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public UICommandEntry() { subscribe(new CursorUpdateEventListener() { @Override public void onCursorUpdated(int oldPosition, int newPosition) { START if(tabCompletionEngine == null) END return; tabCompletionEngine.reset(); } }); } Need some braces here. :)

Target:
public UICommandEntry() { subscribe(new CursorUpdateEventListener() { @Override public void onCursorUpdated(int oldPosition, int newPosition) { if (tabCompletionEngine == null) { return; } tabCompletionEngine.reset(); } }); }
Source:
public UIScreenLayer pushScreen(UIElement element) { if (element != null && element.getRootWidget() instanceof CoreScreenLayer) { CoreScreenLayer result = (CoreScreenLayer) element.getRootWidget(); START if (!result.equals(screens.peek())) { END result.setId(element.getURI().toNormalisedSimpleString()); pushScreen(result, element.getURI()); } return result; } return null; } Possibly should check the entire screen stack.

Target:
public UIScreenLayer pushScreen(UIElement element) { if (element != null && element.getRootWidget() instanceof CoreScreenLayer) { CoreScreenLayer result = (CoreScreenLayer) element.getRootWidget(); if (!screens.contains(result)) { result.setId(element.getURI().toNormalisedSimpleString()); pushScreen(result, element.getURI()); } return result; } return null; }
Source:
public void onChangeVelocity(ChangeVelocityEvent event, EntityRef entity) { START if (event.getAngularVelocity().length() > 0) { END physics.getRigidBody(entity).setAngularVelocity(event.getAngularVelocity()); } if (event.getLinearVelocity().length() > 0) { physics.getRigidBody(entity).setLinearVelocity(event.getLinearVelocity()); } } What If I want to set velocity to zero?

Target:
public void onChangeVelocity(ChangeVelocityEvent event, EntityRef entity) { if (event.getAngularVelocity() != null) { physics.getRigidBody(entity).setAngularVelocity(event.getAngularVelocity()); } if (event.getLinearVelocity() != null) { physics.getRigidBody(entity).setLinearVelocity(event.getLinearVelocity()); } }
Source:
public static int ceilPowerOfTwo(int val) { START if(val == Integer.MIN_VALUE) END return 0; int result = val - 1; result = (result >> 1) | result; result = (result >> 2) | result; result = (result >> 4) | result; result = (result >> 8) | result; result = (result >> 16) | result; result++; return result; } I have to admit that I never considered negative numbers at all. Both min and max integer will suffer from overflow though, so I'm not sure it matters.

Target:
public static int ceilPowerOfTwo(int val) { int result = val - 1; result = (result >> 1) | result; result = (result >> 2) | result; result = (result >> 4) | result; result = (result >> 8) | result; result = (result >> 16) | result; result++; return (result & ~(Integer.MIN_VALUE)); }
Source:
public void cancelDelayedAction(CancelDelayedActionEvent event, EntityRef entity) { DelayedActionComponent delayedComponent = entity.getComponent(DelayedActionComponent.class); START delayedOperationsSortedByTime.remove(delayedComponent.getWorldTime(), new DelayedOperation(entity, delayedComponent.getActionId())); END entity.removeComponent(DelayedActionComponent.class); } I recommend moving this line to a BeforeDeactivatedComponent event handler (or if you already have one, it is unnecessary).

Target:
public void cancelDelayedAction(CancelDelayedActionEvent event, EntityRef entity) { entity.removeComponent(DelayedActionComponent.class); }
Source:
public void update(float delta) { if (speed > 0) { speed -= delta; return; } speed = 0.1f; START for (EntityRef minion : entityManager.getEntitiesWith(BehaviorComponent.class)) { END addEntity(minion, minion.getComponent(BehaviorComponent.class)); } for (Map.Entry<BehaviorTree, List<Interpreter>> entry : interpreters.entrySet()) { for (Interpreter interpreter : entry.getValue()) { interpreter.tick(0.1f); } } } I suspect you should use the lifecycle events here (OnAddedComponent), rather than scanning all entities with BehaviourComponents each frame?

Target:
public void update(float delta) { if (speed > 0) { speed -= delta; return; } speed = 0.1f; for (Map.Entry<BehaviorTree, List<Interpreter>> entry : interpreters.entrySet()) { for (Interpreter interpreter : entry.getValue()) { interpreter.tick(0.1f); } } }
Source:
START public void getPosition(Vector3f output) { END LocationComponent location = entity.getComponent(LocationComponent.class); if (location == null) { output.x = 0; output.y = 0; output.z = 0; } else { location.getWorldPosition(output); } } Would recommend having this method return the output Vector3f, makes it easier to use.

Target:
public Vector3f getPosition(Vector3f output) { LocationComponent location = entity.getComponent(LocationComponent.class); if (location == null) { output.x = 0; output.y = 0; output.z = 0; } else { location.getWorldPosition(output); } return output; }
Source:
public void onError(Throwable th) { LOGGER.info("---- onError\n" + th.toString()); lastPong = null; warnDisconnect(); START executorService.shutdownNow(); END } 起動時にエラーが発生して onOpen が実行される前に onError が呼び出されたりしないか(しても大丈夫かどうか)気になりました。

Target:
public void onError(Throwable th) { LOGGER.info("---- onError\n" + th.toString()); lastPong = null; warnDisconnect(); if (executorService != null) { executorService.shutdownNow(); executorService = null; } }
Source:
public Map<String, Map<String, Integer>> dumpHashTableStats() { START Map<String, Map<String, Integer>> ret = new HashMap<String, Map<String, Integer>>(); END if (leftHashTable != null) { ret.put(leftHashTable.name, leftHashTable.dumpStats()); } if (rightHashTable != null) { ret.put(rightHashTable.name, rightHashTable.dumpStats()); } return ret; } Can you just use the diamond operator here? ``` Map<String, Map<String, Integer>> ret = new HashMap<>(); ```

Target:
public Map<String, Map<String, Integer>> dumpHashTableStats() { Map<String, Map<String, Integer>> ret = new HashMap<>(); if (leftHashTable != null) { ret.put(leftHashTable.name, leftHashTable.dumpStats()); } if (rightHashTable != null) { ret.put(rightHashTable.name, rightHashTable.dumpStats()); } return ret; }
Source:
public Map<String, Map<String, Integer>> dumpHashTableStats() { START Map<String, Map<String, Integer>> ret = new HashMap<String, Map<String, Integer>>(); END if (groupStates != null) { ret.put(groupStates.name, groupStates.dumpStats()); } return ret; } again I think you can use the diamond operator

Target:
public Map<String, Map<String, Integer>> dumpHashTableStats() { Map<String, Map<String, Integer>> ret = new HashMap<>(); if (groupStates != null) { ret.put(groupStates.name, groupStates.dumpStats()); } return ret; }
Source:
public Map<String, Map<String, Integer>> dumpHashTableStats(final Operator op) { START Map<String, Map<String, Integer>> ret = new HashMap<String, Map<String, Integer>>(); END for (Operator o : op.getChildren()) { ret.putAll(dumpHashTableStats(o)); } ret.putAll(op.dumpHashTableStats()); return ret; } again I think you can use the diamond operator

Target:
public Map<String, Map<String, Integer>> dumpHashTableStats(final Operator op) { Map<String, Map<String, Integer>> ret = new HashMap<>(); for (Operator o : op.getChildren()) { ret.putAll(dumpHashTableStats(o)); } ret.putAll(op.dumpHashTableStats()); return ret; }
Source:
public Map<String, Map<String, Integer>> dumpHashTableStats() { START Map<String, Map<String, Integer>> ret = new HashMap<String, Map<String, Integer>>(); END for (LocalFragment t : fragments) { ret.putAll(t.dumpHashTableStats(t.getRootOp())); } return ret; } again I think you can use the diamond operator

Target:
public Map<String, Map<String, Integer>> dumpHashTableStats() { Map<String, Map<String, Integer>> ret = new HashMap<>(); for (LocalFragment t : fragments) { ret.putAll(t.dumpHashTableStats(t.getRootOp())); } return ret; }
Source:
public boolean isValid() { START try { END return accessMethod.getConnection().isValid(1); } catch (SQLException e) { LOGGER.warn("Error checking connection validity", e); return false; } } Can you check if this is called anywhere?

Target:
public boolean isValid() { try { return accessMethod.getConnection().isValid(1); } catch (SQLException e) { LOGGER.debug("Error checking connection validity", e); return false; } }
Source:
public PythonFunctionRegistrar getPythonFunctionRegistrar() throws DbException { PythonFunctionRegistrar pyFuncRegistrar = null; try { if (execEnvVars.get(MyriaConstants.EXEC_ENV_VAR_TEST_MODE) == null) { if (getLocalSubQuery() instanceof WorkerSubQuery) { pyFuncRegistrar = ((WorkerSubQuery) getLocalSubQuery()).getWorker().getPythonFunctionRegistrar(); } } } catch (Exception e) { LOGGER.debug("exception getting pyFuncRegistrar"); START pyFuncRegistrar = null; END } return pyFuncRegistrar; } Here, `pyFuncRegistrar` will already be null anyway. Also, wouldn't you want to throw an exception at this point? I noticed that at several points in your code, you call this function to get the registrar, but you wouldn't ever want to return a null value right?

Target:
public PythonFunctionRegistrar getPythonFunctionRegistrar() throws DbException { PythonFunctionRegistrar pyFuncRegistrar = null; if (!execEnvVars.containsKey(MyriaConstants.EXEC_ENV_VAR_TEST_MODE)) { if (getLocalSubQuery() instanceof WorkerSubQuery) { pyFuncRegistrar = ((WorkerSubQuery) getLocalSubQuery()).getWorker().getPythonFunctionRegistrar(); } } return pyFuncRegistrar; }
Source:
START public static int getBatchSize(Type type) { END int batchSize = 1000 * 10; if (type == Type.BLOB_TYPE) { batchSize = 1; } return batchSize; } Similar to above

Target:
public static int getBatchSize(Type type) { int batchSize = 1000 * 10; if (type == Type.BLOB_TYPE) batchSize = 1; return batchSize; }
Source:
public BooleanColumnBuilder() { data = new BitSet(); numBits = 0; Schema schema = new Schema(Arrays.asList(Type.BOOLEAN_TYPE)); START int batchSize = TupleUtils.getBatchSize(schema); END capacity = batchSize; } Call the function with a single `Type` as input instead.

Target:
public BooleanColumnBuilder() { data = new BitSet(); numBits = 0; int batchSize = TupleUtils.getBatchSize(Type.BOOLEAN_TYPE); capacity = batchSize; }
Source:
public static void main(final String[] args) throws Exception { START LauncherStatus run = run(args); END LOGGER.info("Exit with status " + run); } `run` -> `status`

Target:
public static void main(final String[] args) throws Exception { LauncherStatus status = run(args); LOGGER.info("Exit with status " + status); }
Source:
public IdentityHashPartitionFunction( @JsonProperty(value = "index", required = true) final Integer index) { super(null); START this.index = java.util.Objects.requireNonNull(index, "missing property index"); END Preconditions.checkArgument(this.index >= 0, "IdentityHash field index cannot take negative value %s", this.index); } Why not import `Objects`?

Target:
public IdentityHashPartitionFunction( @JsonProperty(value = "index", required = true) final Integer index) { super(null); this.index = Objects.requireNonNull(index, "missing property index"); Preconditions.checkArgument(this.index >= 0, "IdentityHash field index cannot take negative value %s", this.index); }
Source:
public InputStream getInputStream() throws IOException { URI parsedUri = URI.create(uri); START return parsedUri.getScheme().equals("http") || parsedUri.getScheme().equals("https") END ? parsedUri.toURL().openConnection().getInputStream() : getHadoopFileSystemInputStream(parsedUri); } I tend to avoid trigraphs unless they're absolutely necessary, but that's up to you. However, please `()` around the condition of `||` here... the code is correct but you have to know non-obvious parts of [the precedence chart (13 vs 14)](http://introcs.cs.princeton.edu/java/11precedence/). LGTM!

Target:
public InputStream getInputStream() throws IOException { URI parsedUri = URI.create(uri); return (parsedUri.getScheme().equals("http") || parsedUri.getScheme().equals("https")) ? parsedUri.toURL().openConnection().getInputStream() : getHadoopFileSystemInputStream(parsedUri); }
Source:
public ConstantExpression(final int value) { START valueType = Type.INT_TYPE; END this.value = String.valueOf(value); } use the constructor-delegate form instead. More concise and if we ever need to put in checks we only need to put them one place. e.g., `this(Type.INT_TYPE, String.valueOf(value))`

Target:
public ConstantExpression(final int value) { this(Type.INT_TYPE, String.valueOf(value)); }
Source:
public static synchronized ProfilingLogger getLogger(final ImmutableMap<String, Object> execEnvVars) { if (instance == null) { try { instance = new ProfilingLogger(execEnvVars); } catch (DbException e) { START if (LOGGER.isErrorEnabled()) { END LOGGER.error("Failed to initialize profiling logger:", e); } } } Preconditions.checkArgument(instance.connectionInfo == (ConnectionInfo) execEnvVars .get(MyriaConstants.EXEC_ENV_VAR_DATABASE_CONN_INFO), "Connection info should not change."); return instance; } I am trying to get rid of these checks where they don't save a large amount of work. No need to check whether logging is enabled here, there's no work inside the function.

Target:
public static synchronized ProfilingLogger getLogger(final ImmutableMap<String, Object> execEnvVars) { if (instance == null) { try { instance = new ProfilingLogger(execEnvVars); } catch (DbException e) { LOGGER.error("Failed to initialize profiling logger:", e); } } Preconditions.checkArgument(instance.connectionInfo == (ConnectionInfo) execEnvVars .get(MyriaConstants.EXEC_ENV_VAR_DATABASE_CONN_INFO), "Connection info should not change."); return instance; }
Source:
START public void testNonStaticInnerClasses() { END boolean successful = false; try { ReflectData.get().getSchema(Definition.class); } catch (AvroTypeException ex) { if (ex.getMessage().contains("must be a static inner class")) { successful = true; } } assertTrue(successful); } I'd prefer to use the annotation: `@Test(expected = AvroTypeException.class)` What do you think?

Target:
public void testNonStaticInnerClasses() { ReflectData.get().getSchema(Definition.class); }
Source:
START public void testStaticInnerClasses() { END try { ReflectData.get().getSchema(Meta.class); } catch (AvroTypeException ex) { fail("Should have no exception"); } } Same here, I'd love to use the annotation, and remove the fail("") part. If it throws an exception, it will fail anyway

Target:
public void testStaticInnerClasses() { ReflectData.get().getSchema(Meta.class); }
Source:
public FastReaderBuilder getFastReaderBuilder() { if (fastReaderBuilder == null) { START FastReaderBuilder localFastReader = new FastReaderBuilder(this); END this.fastReaderBuilder = localFastReader; return localFastReader; } else { return this.fastReaderBuilder; } } Definitely a nit, but why introduce the local variable here?

Target:
public FastReaderBuilder getFastReaderBuilder() { if (fastReaderBuilder == null) { fastReaderBuilder = new FastReaderBuilder(this); } return this.fastReaderBuilder; }
Source:
protected boolean isArray(Object datum) { if (datum == null) return false; Class c = datum.getClass(); return (datum instanceof Collection) START || (c.isArray() && !(c.getComponentType() == Byte.TYPE)) END || isNonStringMap(datum); } I would suggest `c.getComponentType() != Byte.TYPE` instead of `!(c.getComponentType() == Byte.TYPE)`

Target:
protected boolean isArray(Object datum) { if (datum == null) return false; Class c = datum.getClass(); return (datum instanceof Collection) || (c.isArray() && c.getComponentType() != Byte.TYPE) || isNonStringMap(datum); }
Source:
public SchemaCompatibilityResult mergedWith(SchemaCompatibilityResult toMerge) { List<Incompatibility> mergedIncompatibilities = new ArrayList<Incompatibility>(mIncompatibilities); mergedIncompatibilities.addAll(toMerge.getIncompatibilities()); START SchemaCompatibilityType compatibilityType = mCompatibilityType == SchemaCompatibilityType.COMPATIBLE END && toMerge.mCompatibilityType == SchemaCompatibilityType.COMPATIBLE ? SchemaCompatibilityType.COMPATIBLE : SchemaCompatibilityType.INCOMPATIBLE; return new SchemaCompatibilityResult(compatibilityType, mergedIncompatibilities); } What happens in case of `RECURSION_IN_PROGRESS`? I'm not sure we need `&& toMerge.mCompatibilityType == SchemaCompatibilityType.COMPATIBLE`, isn't this simpler a bit: `SchemaCompatibilityType compatibilityType = mCompatibilityType == SchemaCompatibilityType.COMPATIBLE ? toMerge.getCompatibility() : SchemaCompatibilityType.INCOMPATIBLE; `

Target:
public SchemaCompatibilityResult mergedWith(SchemaCompatibilityResult toMerge) { List<Incompatibility> mergedIncompatibilities = new ArrayList<Incompatibility>(mIncompatibilities); mergedIncompatibilities.addAll(toMerge.getIncompatibilities()); SchemaCompatibilityType compatibilityType = mCompatibilityType == SchemaCompatibilityType.COMPATIBLE ? toMerge.mCompatibilityType : SchemaCompatibilityType.INCOMPATIBLE; return new SchemaCompatibilityResult(compatibilityType, mergedIncompatibilities); }
Source:
private static void printStream(InputStream in) throws Exception { byte[] buffer = new byte[1024]; try { for (int i = in.read(buffer); i != -1; i = in.read(buffer)) System.err.write(buffer, 0, i); } finally { START in.close(); END } } Why are we closing in within this method instead of having the caller do it?

Target:
private static void printStream(InputStream in) throws Exception { byte[] buffer = new byte[1024]; for (int i = in.read(buffer); i != -1; i = in.read(buffer)) System.err.write(buffer, 0, i); }
Source:
public DataFileWriter<D> appendTo(File file) throws IOException { SeekableInput input = new SeekableFileInput(file); START OutputStream output = new SyncableFileOutputStream(file, true); END try { return appendTo(input, output); } finally { input.close(); } } I think this line should be inside the try block as well to guarantee that input is always closed. Or, alternatively, it may be before the first line if order does not matter.

Target:
public DataFileWriter<D> appendTo(File file) throws IOException { SeekableInput input = null; try { input = new SeekableFileInput(file); OutputStream output = new SyncableFileOutputStream(file, true); return appendTo(input, output); } finally { if (input != null) input.close(); // output does not need to be closed here. It will be closed by invoking close() of this writer. } }
Source:
private void consumeFieldAlias(Field field, Schema.Field recordField) { START if (field.isAnnotationPresent(AvroAlias.class)) { END AvroAlias alias = field.getAnnotation(AvroAlias.class); if (!alias.space().equals(AvroAlias.NULL)) { throw new AvroRuntimeException( "Namespaces are not allowed on field aliases. " + "Offending field: " + recordField.name()); } recordField.addAlias(alias.alias()); } } Field.isAnnotationPresent(Class) checks whether Field.getAnnotation(Class) returns null. I would suggest checking for alias != null to avoid the double invocation.

Target:
private void consumeFieldAlias(Field field, Schema.Field recordField) { AvroAlias alias = field.getAnnotation(AvroAlias.class); if (alias != null) { if (!alias.space().equals(AvroAlias.NULL)) { throw new AvroRuntimeException( "Namespaces are not allowed on field aliases. " + "Offending field: " + recordField.name()); } recordField.addAlias(alias.alias()); } }
Source:
START public Object getRecordState(Object record, Schema schema) { return null; } END With the recent writer change, I don't think this needs to be exposed any longer.

Target:
protected Object getRecordState(Object record, Schema schema) { return null; }
Source:
public void put(String orcid, OrcidProfile orcidProfile) { try { START profileCache.acquireWriteLockOnKey(orcid); END profileCache.put(new Element(new OrcidCacheKey(orcid, releaseName), orcidProfile)); } finally { profileCache.releaseWriteLockOnKey(orcid); } } Hey @rcpeters, i think here you should create the key _new OrcidCacheKey(orcid, releaseName)_ and acquire the lock on that key, not in the orcid id right?

Target:
public void put(String orcid, OrcidProfile orcidProfile) { Object key = new OrcidCacheKey(orcid, releaseName); try { profileCache.acquireWriteLockOnKey(key); profileCache.put(new Element(key, orcidProfile)); } finally { profileCache.releaseWriteLockOnKey(key); } }
Source:
public PentahoOrcInputFormat( NamedCluster namedCluster ) { if ( namedCluster == null ) { conf = new Configuration(); } else { conf = inClassloader( () -> { Configuration confProxy = new ConfigurationProxy(); confProxy.addResource( "hive-site.xml" ); BiConsumer<InputStream, String> consumer = ( is, filename ) -> START { END confProxy.addResource( is, filename ); }; ShimConfigsLoader.addConfigsAsResources( namedCluster, consumer ); return confProxy; } ); } } Can we roll this functionality directly into the NamedCluster object and start to eliminate ShimConfigsLoader?

Target:
public PentahoOrcInputFormat( NamedCluster namedCluster ) { if ( namedCluster == null ) { conf = new Configuration(); } else { conf = inClassloader( () -> { Configuration confProxy = new ConfigurationProxy(); confProxy.addResource( "hive-site.xml" ); BiConsumer<InputStream, String> consumer = ( is, filename ) -> confProxy.addResource( is, filename ); ShimConfigsLoader.addConfigsAsResources( namedCluster, consumer ); return confProxy; } ); } }
Source:
public ExtensionBean getDetail(String extensionName) { EntityManager entityManager = getEntityManager(); beginTransaction(entityManager); Query q = entityManager.createNamedQuery(PersistenceConstants.GET_EXTENSION); q.setParameter(EXTENSION_NAME, extensionName); try { List resultList = q.getResultList(); START if (resultList.size()>0) { END return (ExtensionBean)resultList.get(0); } else { return null; } } finally { commitAndCloseTransaction(entityManager); } } Nit : use isEmpty instead.

Target:
public ExtensionBean getDetail(String extensionName) { EntityManager entityManager = getEntityManager(); beginTransaction(entityManager); Query q = entityManager.createNamedQuery(PersistenceConstants.GET_EXTENSION); q.setParameter(EXTENSION_NAME, extensionName); try { List resultList = q.getResultList(); if (!resultList.isEmpty()) { return (ExtensionBean)resultList.get(0); } else { return null; } } finally { commitAndCloseTransaction(entityManager); } }
Source:
public Response getDetail(@PathParam("extension-name") String extensionName){ checkIfExtensionServiceIsEnabled(); validateExtensionName(extensionName); JSONObject result = new JSONObject(); try { START result.put(EXTENSION_DETAIL,buildDetailResult(extensionName)); END return Response.ok(result).build(); } catch (Throwable e) { throw FalconWebException.newAPIException(e, Response.Status.INTERNAL_SERVER_ERROR); } } why JSON inside a JSON? Can you send the json object from buildDetailResult directly?

Target:
public Response getDetail(@PathParam("extension-name") String extensionName){ checkIfExtensionServiceIsEnabled(); validateExtensionName(extensionName); try { return Response.ok(buildDetailResult(extensionName)).build(); } catch (Throwable e) { throw FalconWebException.newAPIException(e, Response.Status.INTERNAL_SERVER_ERROR); } }
Source:
public void onRemove(Entity entity) throws FalconException{ if (entity.getEntityType() != EntityType.PROCESS){ return; } START synchronized (this){ END backlogMetricStore.deleteEntityInstance(entity.getName()); entityBacklogs.remove(entity); } } Should be sufficient to synchronize on entityBacklogs, right? Same applies for onChange method.

Target:
public void onRemove(Entity entity) throws FalconException{ if (entity.getEntityType() != EntityType.PROCESS){ return; } synchronized (entityBacklogs){ backlogMetricStore.deleteEntityInstance(entity.getName()); entityBacklogs.remove(entity); } }
Source:
public void putMonitoredEntity(String entityName, String entityType) throws FalconException{ MonitoredEntityBean monitoredEntityBean = new MonitoredEntityBean(); monitoredEntityBean.setEntityName(entityName); START monitoredEntityBean.setEntityType(entityType.toLowerCase()); END EntityManager entityManager = getEntityManager(); try { beginTransaction(entityManager); entityManager.persist(monitoredEntityBean); } finally { commitAndCloseTransaction(entityManager); } } Why this change?

Target:
public void putMonitoredEntity(String entityName, String entityType) throws FalconException{ MonitoredEntityBean monitoredEntityBean = new MonitoredEntityBean(); monitoredEntityBean.setEntityName(entityName); monitoredEntityBean.setEntityType(entityType); EntityManager entityManager = getEntityManager(); try { beginTransaction(entityManager); entityManager.persist(monitoredEntityBean); } finally { commitAndCloseTransaction(entityManager); } }
Source:
public EntityList getDependency(String entityType, String entityName, String doAsUser) { ClientResponse clientResponse = new ResourceBuilder().path(Entities.DEPENDENCY.path, entityType, entityName) .addQueryParam(DO_AS_OPT, doAsUser).call(Entities.DEPENDENCY); printClientResponse(clientResponse); checkIfSuccessful(clientResponse); EntityList result = clientResponse.getEntity(EntityList.class); START if (result == null || result.getElements() == null) { END return new EntityList(); } return result; } You dont need the " result.getElements() == null " condition

Target:
public EntityList getDependency(String entityType, String entityName, String doAsUser) { ClientResponse clientResponse = new ResourceBuilder().path(Entities.DEPENDENCY.path, entityType, entityName) .addQueryParam(DO_AS_OPT, doAsUser).call(Entities.DEPENDENCY); printClientResponse(clientResponse); checkIfSuccessful(clientResponse); EntityList result = clientResponse.getEntity(EntityList.class); if (result == null) { return new EntityList(); } return result; }
Source:
public static Sla getSLA(Cluster cluster, Process process) { final Sla clusterSla = cluster.getSla(); if (clusterSla != null) { return clusterSla; } final Sla processSla = process.getSla(); START return processSla == null ? null : processSla; END } The additional null check seems unnecessary. You could just return process.getSla().

Target:
public static Sla getSLA(Cluster cluster, Process process) { final Sla clusterSla = cluster.getSla(); if (clusterSla != null) { return clusterSla; } return process.getSla(); }
Source:
public void tearDown() throws Exception { // delete temporary jks files START File credDir = new File("."); END File file = new File(credDir, JKS_FILE_NAME); file.delete(); file = new File(credDir, "." + JKS_FILE_NAME + ".crc"); file.delete(); } Can we define credDir as public static final String CRED_DIR so that it can be reused in tearDown and testResolveAlias? Thanks!

Target:
public void tearDown() throws Exception { // delete temporary jks files File file = new File(credDir, JKS_FILE_NAME); file.delete(); file = new File(credDir, "." + JKS_FILE_NAME + ".crc"); file.delete(); }
Source:
public static String getActionStatus(OozieClient oozieClient, String workflowId, String actionName) throws OozieClientException { List<WorkflowAction> wfAction = oozieClient.getJobInfo(workflowId).getActions(); for (WorkflowAction wf : wfAction) { if (wf.getName().contains(actionName)) { START if (wf.getExternalStatus() != null) { END return wf.getExternalStatus(); } } } return ""; } please use 'and' operator in if condition and combine both the if statements for better readability.

Target:
public static String getActionStatus(OozieClient oozieClient, String workflowId, String actionName) throws OozieClientException { List<WorkflowAction> wfAction = oozieClient.getJobInfo(workflowId).getActions(); for (WorkflowAction wf : wfAction) { if ((wf.getName().contains(actionName)) && (wf.getExternalStatus() != null)) { return wf.getExternalStatus(); } } return ""; }
Source:
public CatalogStorage(Cluster cluster, CatalogTable table) throws URISyntaxException { this(ClusterHelper.getInterface(cluster, Interfacetype.REGISTRY).getEndpoint(), table); START verifyAndUpdateConfiguration(getConf()); END } You don't need it here. verifyAndUpdateConfiguration is already called in CatalogStorage(String catalogUrl, CatalogTable table).

Target:
public CatalogStorage(Cluster cluster, CatalogTable table) throws URISyntaxException { this(ClusterHelper.getInterface(cluster, Interfacetype.REGISTRY).getEndpoint(), table); }
Source:
public void putMonitoredFeed(String feedName){ MonitoredFeedsBean monitoredFeedsBean = new MonitoredFeedsBean(); monitoredFeedsBean.setFeedName(feedName); EntityManager entityManager = getEntityManager(); beginTransaction(entityManager); entityManager.persist(monitoredFeedsBean); START commitAndCloseTransaction(entityManager); END } Should commitAndCloseTransaction be part of a finally statement?

Target:
public void putMonitoredFeed(String feedName){ MonitoredFeedsBean monitoredFeedsBean = new MonitoredFeedsBean(); monitoredFeedsBean.setFeedName(feedName); EntityManager entityManager = getEntityManager(); try { beginTransaction(entityManager); entityManager.persist(monitoredFeedsBean); } finally { commitAndCloseTransaction(entityManager); } }
Source:
public List<PendingInstanceBean> getAllInstances(){ EntityManager entityManager = getEntityManager(); Query q = entityManager.createNamedQuery(PersistenceConstants.GET_ALL_PENDING_INSTANCES); List result = q.getResultList(); if (CollectionUtils.isEmpty(result)) { return null; } entityManager.close(); START return result; END } result seems to be implicitly type casted.

Target:
public List<PendingInstanceBean> getAllInstances(){ EntityManager entityManager = getEntityManager(); Query q = entityManager.createNamedQuery(PersistenceConstants.GET_ALL_PENDING_INSTANCES); List result = q.getResultList(); try { if (CollectionUtils.isEmpty(result)) { return null; } } finally{ entityManager.close(); } return result; }
Source:
protected void initializeService() { START lastCheckedAt = new Date(); END lastSerializedAt = new Date(); } Other two can be removed as well.

Target:
protected void initializeService() { lastCheckedAt = new Date(); }
Source:
public void setup() throws Exception { START System.out.println("Executing setup"); END StateStoreProperties.get().setProperty(FalconJPAService.URL, url); Configuration localConf = new Configuration(); fs.initialize(LocalFileSystem.getDefaultUri(localConf), localConf); fs.mkdirs(new Path(DB_BASE_DIR)); createDB(DB_SQL_FILE); falconJPAService.init(); this.dfsCluster = EmbeddedCluster.newCluster("testCluster"); this.conf = dfsCluster.getConf(); // registerServices(); } required?

Target:
public void setup() throws Exception{ StateStoreProperties.get().setProperty(FalconJPAService.URL, url); Configuration localConf = new Configuration(); fs.initialize(LocalFileSystem.getDefaultUri(localConf), localConf); fs.mkdirs(new Path(DB_BASE_DIR)); createDB(DB_SQL_FILE); falconJPAService.init(); this.dfsCluster = EmbeddedCluster.newCluster("testCluster"); this.conf = dfsCluster.getConf(); }
Source:
private void kill(String cluster, String jobId, String rangeType, String scope) throws FalconException { try { START OozieClientFactory.get(cluster).kill(jobId, rangeType, scope); END assertStatus(cluster, jobId, Status.KILLED, Status.SUCCEEDED, Status.FAILED); LOG.info("Killed job for instances on cluster {}", jobId, scope, cluster); } catch (OozieClientException e) { throw new FalconException(e); } } Did you miss to attach LocalOozieCoordClientProxy class ?

Target:
private void kill(String cluster, String jobId, String rangeType, String scope) throws FalconException { try { OozieClientFactory.get(cluster).kill(jobId, rangeType, scope); LOG.info("Killed job for instances on cluster {}", jobId, scope, cluster); } catch (OozieClientException e) { throw new FalconException(e); } }
Source:
public void add(Edge<I, E> edge) { ExtendedDataOutput extendedDataOutput = getConf().createExtendedDataOutput( serializedEdges, serializedEdgesBytesUsed); try { WritableUtils.writeEdge(extendedDataOutput, edge); } catch (IOException e) { throw new IllegalStateException("add: Failed to write to the new " + "byte array"); } catch (NegativeArraySizeException negativeArraySizeException) { throw new IllegalStateException("add: Too many edges for a vertex, " + START edge.getTargetVertexId() + "hence failed to write to byte array"); END } serializedEdges = extendedDataOutput.getByteArray(); serializedEdgesBytesUsed = extendedDataOutput.getPos(); ++edgeCount; } ```suggestion edge.getTargetVertexId() + " hence failed to write to byte array"); ```

Target:
public void add(Edge<I, E> edge) { ExtendedDataOutput extendedDataOutput = getConf().createExtendedDataOutput( serializedEdges, serializedEdgesBytesUsed); try { WritableUtils.writeEdge(extendedDataOutput, edge); } catch (IOException e) { throw new IllegalStateException("add: Failed to write to the new " + "byte array"); } catch (NegativeArraySizeException negativeArraySizeException) { throw new IllegalStateException("add: Too many edges for a vertex, " + "hence failed to write to byte array"); } serializedEdges = extendedDataOutput.getByteArray(); serializedEdgesBytesUsed = extendedDataOutput.getPos(); ++edgeCount; }
Source:
public PieceCount getPieceCount() { START PieceCount ret = new PieceCount(0); END for (AbstractPiece<I, V, E, M, WV, WM, S> innerPiece : innerPieces) { ret.add(innerPiece.getPieceCount()); } return ret; } this should be 1, this executes all pieces simultaneously.

Target:
public PieceCount getPieceCount() { return new PieceCount(1); }
Source:
protected boolean addToBuffer(T persistenceItem) { try { return buffer.offer(persistenceItem, BUFFER_OFFER_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS); } catch (InterruptedException e) { START logger.error("Interrupted when trying to buffer data! Dropping data"); END return false; } } This should be a WARN instead of an ERROR.

Target:
protected boolean addToBuffer(T persistenceItem) { try { return buffer.offer(persistenceItem, BUFFER_OFFER_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS); } catch (InterruptedException e) { logger.warn("Interrupted when trying to buffer data! Dropping data"); return false; } }
Source:
private boolean sleep() { try { long sleepTime; if (retry == 1 && lastException != null && lastException instanceof ResourceNotFoundException) { sleepTime = WAIT_ON_FIRST_RESOURCE_NOT_FOUND_MILLIS; } else { sleepTime = WAIT_MILLIS_IN_RETRIES[retry]; } Thread.sleep(sleepTime); return true; } catch (InterruptedException e) { START logger.error("Interrupted while writing data!"); END return false; } } I'd argue this should be DEBUG instead of ERROR.

Target:
private boolean sleep() { try { long sleepTime; if (retry == 1 && lastException != null && lastException instanceof ResourceNotFoundException) { sleepTime = WAIT_ON_FIRST_RESOURCE_NOT_FOUND_MILLIS; } else { sleepTime = WAIT_MILLIS_IN_RETRIES[retry]; } Thread.sleep(sleepTime); return true; } catch (InterruptedException e) { logger.debug("Interrupted while writing data!"); return false; } }
Source:
private void parseFrame(IByteProvider byteProvider) { try { byte currentByte = byteProvider.getByte(); if (currentByte == Frame.START_BYTE) { int length = byteProvider.getByte(); if (length > 0) { byte[] data = byteProvider.getBytes(length + 1); ReceiveFrame frame = new ReceiveFrame(); frame.parse(data); receiveFrames.add(frame); } } } catch (Exception e) { START logger.error("Error while parsing ReceiveFrame", e); END } } Please also change this to WARN instead of ERROR.

Target:
private void parseFrame(IByteProvider byteProvider) { try { byte currentByte = byteProvider.getByte(); if (currentByte == Frame.START_BYTE) { int length = byteProvider.getByte(); if (length > 0) { byte[] data = byteProvider.getBytes(length + 1); ReceiveFrame frame = new ReceiveFrame(); frame.parse(data); receiveFrames.add(frame); } } } catch (Exception e) { logger.warn("Error while parsing ReceiveFrame", e); } }
Source:
public synchronized boolean bridgeLogin() { logger.trace("bridgeLogin() called."); START Login bcp = this.bridgeAPI().login(); END bcp.setPassword(this.bridgeInstance.veluxBridgeConfiguration().bridgePassword); if (bridgeCommunicate(bcp, false)) { logger.trace("bridgeLogin(): communication succeeded."); if (bcp.isCommunicationSuccessful()) { logger.trace("bridgeLogin(): storing authentication token for further access."); authenticationToken = bcp.getAuthToken(); return true; } } return false; } Drop all the unnecessary use of `this.` throughout.

Target:
public synchronized boolean bridgeLogin() { logger.trace("bridgeLogin() called."); Login bcp = bridgeAPI().login(); bcp.setPassword(bridgeInstance.veluxBridgeConfiguration().bridgePassword); if (bridgeCommunicate(bcp, false)) { logger.trace("bridgeLogin(): communication succeeded."); if (bcp.isCommunicationSuccessful()) { logger.trace("bridgeLogin(): storing authentication token for further access."); authenticationToken = bcp.getAuthToken(); return true; } } return false; }
Source:
public boolean modifyHSM(VeluxBridge bridge, boolean enableService) { logger.trace("modifyHSM({}) called.", enableService); ModifyHouseStatusMonitor bcp = bridge.bridgeAPI().modifyHouseStatusMonitor(); bcp.serviceActivation(enableService); START if ((bridge.bridgeCommunicate(bcp)) && (bcp.isCommunicationSuccessful())) { END logger.debug("modifyHSM() finished successfully."); return true; } else { logger.trace("modifyHSM() finished with failure."); return false; } } redundant parentheses

Target:
public boolean modifyHSM(VeluxBridge bridge, boolean enableService) { logger.trace("modifyHSM({}) called.", enableService); ModifyHouseStatusMonitor bcp = bridge.bridgeAPI().modifyHouseStatusMonitor(); bcp.serviceActivation(enableService); if (bridge.bridgeCommunicate(bcp) && bcp.isCommunicationSuccessful()) { logger.debug("modifyHSM() finished successfully."); return true; } else { logger.trace("modifyHSM() finished with failure."); return false; } }
Source:
public boolean execute(VeluxBridge bridge, int sceneNo) { logger.trace("execute({}) called.", sceneNo); RunScene bcp = bridge.bridgeAPI().runScene(); bcp.setSceneId(sceneNo); START if ((bridge.bridgeCommunicate(bcp)) && (bcp.isCommunicationSuccessful())) { END logger.debug("execute() finished successfully."); return true; } else { logger.trace("execute() finished with failure."); return false; } } redundant parentheses

Target:
public boolean execute(VeluxBridge bridge, int sceneNo) { logger.trace("execute({}) called.", sceneNo); RunScene bcp = bridge.bridgeAPI().runScene(); bcp.setSceneId(sceneNo); if (bridge.bridgeCommunicate(bcp) && bcp.isCommunicationSuccessful()) { logger.debug("execute() finished successfully."); return true; } else { logger.trace("execute() finished with failure."); return false; } }
Source:
public boolean setSilentMode(VeluxBridge bridge, int sceneNo, boolean silentMode) { logger.trace("setSilentMode({},{}) called.", sceneNo, silentMode); SetSilentMode bcp = bridge.bridgeAPI().setSilentMode(); bcp.setMode(sceneNo, silentMode); START if ((bridge.bridgeCommunicate(bcp)) && (bcp.isCommunicationSuccessful())) { END logger.info("setSilentMode() finished successfully."); return true; } logger.trace("setSilentMode() finished with failure."); return false; } redundant parentheses

Target:
public boolean setSilentMode(VeluxBridge bridge, int sceneNo, boolean silentMode) { logger.trace("setSilentMode({},{}) called.", sceneNo, silentMode); SetSilentMode bcp = bridge.bridgeAPI().setSilentMode(); bcp.setMode(sceneNo, silentMode); if (bridge.bridgeCommunicate(bcp) && bcp.isCommunicationSuccessful()) { logger.info("setSilentMode() finished successfully."); return true; } logger.trace("setSilentMode() finished with failure."); return false; }
Source:
public void setPassword(String thisPassword) { logger.trace("setPassword({}) called.",thisPassword); request.params.password = thisPassword; START return; END } Remove this line.

Target:
public void setPassword(String thisPassword) { logger.trace("setPassword({}) called.", thisPassword); request.params.password = thisPassword; }
Source:
private static boolean check4matchingAnyID(Logger logger, String idName, int requestID, int responseID) { logger.trace("check4matchingAnyID() called for request{} and response{} {}.", idName, requestID, idName, responseID); if (requestID != responseID) { logger.warn("Gateway response with unexpected as query asked for {}.", idName, requestID, idName, responseID); return false; START } else { END logger.trace("check4matchingAnyID() returns {}.", true); return true; } } `else` is redundant here

Target:
private static boolean check4matchingAnyID(Logger logger, String idName, int requestID, int responseID) { logger.trace("check4matchingAnyID() called for request{} and response{} {}.", idName, requestID, idName, responseID); if (requestID != responseID) { logger.warn("Gateway response with unexpected as query asked for {}.", idName, requestID, idName, responseID); return false; } logger.trace("check4matchingAnyID() returns {}.", true); return true; }
Source:
public BridgeAPI bridgeAPI() { START logger.error( END "bridgeAPI({}) called. Should NEVER occur as it seems to be a lack of protocol-specific implementation of this bridge API."); return null; } This should be a DEBUG.

Target:
public BridgeAPI bridgeAPI() { logger.debug( "bridgeAPI({}) called. Should NEVER occur as it seems to be a lack of protocol-specific implementation of this bridge API."); return null; }
Source:
public void receiveCommand(String itemName, Command command) { logger.trace("receiveCommand({},{}) called.", itemName, command.toString()); if (this.eventPublisher == null) { START logger.error("receiveCommand(): eventPublisher is NULL. Should NEVER occur."); END return; } super.receiveCommand(itemName, command); } Revert to WARN.

Target:
public void receiveCommand(String itemName, Command command) { logger.trace("receiveCommand({},{}) called.", itemName, command.toString()); if (this.eventPublisher == null) { logger.warn("receiveCommand(): eventPublisher is NULL. Should NEVER occur."); return; } super.receiveCommand(itemName, command); }
Source:
public void onCommand(ProtocolRead c) throws IOException, Exception { try { myPlant.sendCommandAsync(OWNUtilities.createFrame(c), 1); } catch (MalformedCommandOPEN ex) { START logger.error("onCommand error : {}", ex.getMessage()); END } } This should be a WARN instead of an ERROR.

Target:
public void onCommand(ProtocolRead c) throws IOException, Exception { try { myPlant.sendCommandAsync(OWNUtilities.createFrame(c), 1); } catch (MalformedCommandOPEN ex) { logger.warn("onCommand error : {}", ex.getMessage()); } }
Source:
public void run() { try { while (!Thread.interrupted()) { // synchronizes the software with the system status // Every x seconds do a full bus scan checkForBusScan(); Thread.sleep(1000); } } catch (InterruptedException p_i_ex) { logger.error("Openwebnet.run, InterruptedException : " + p_i_ex.getMessage()); } catch (Exception p_i_ex) { START logger.error("Openwebnet.run, Exception : {}", p_i_ex.getMessage()); END } finally { // interrupt handler on monitor thread will stop thread monitorSessionThread.interrupt(); logger.info("Stopped monitorSessionThread thread"); } logger.info("Stopped OpenWebNet thread"); } This should be a WARN instead of an ERROR.

Target:
public void run() { try { while (!Thread.interrupted()) { // synchronizes the software with the system status // Every x seconds do a full bus scan checkForBusScan(); Thread.sleep(1000); } } catch (InterruptedException p_i_ex) { logger.error("Openwebnet.run, InterruptedException : " + p_i_ex.getMessage()); } catch (Exception p_i_ex) { logger.warn("Openwebnet.run, Exception : {}", p_i_ex.getMessage()); } finally { // interrupt handler on monitor thread will stop thread monitorSessionThread.interrupt(); logger.info("Stopped monitorSessionThread thread"); } logger.info("Stopped OpenWebNet thread"); }
Source:
public void notifyEvent(ProtocolRead p_i_event) { for (IBticinoEventListener l_event_listener : m_event_listener_list) { try { l_event_listener.handleEvent(p_i_event); } catch (Exception p_ex) { START logger.error("notifyEvent, Exception : {}", p_ex.getMessage()); END } } } This should be a WARN instead of an ERROR.

Target:
public void notifyEvent(ProtocolRead p_i_event) { for (IBticinoEventListener l_event_listener : m_event_listener_list) { try { l_event_listener.handleEvent(p_i_event); } catch (Exception p_ex) { logger.warn("notifyEvent, Exception : {}", p_ex.getMessage()); } } }
Source:
public void start(BundleContext bc) throws Exception { context = bc; START logger.info("Slack action has been started."); END } Could this and the next logger statement be reduced to debug?

Target:
public void start(BundleContext bc) throws Exception { context = bc; logger.debug("Slack action has been started."); }
Source:
public void stateUpdated(Item item, State state) { if (exposedItems != null && exposedItems.contains(item.getName())) { START logger.debug("Sending item update to openhab Cloud: - {}", item.getName(), state.toString()); END cloudClient.sendItemUpdate(item.getName(), state.toString()); } } The `.toString()` can be left to the logger for performance.

Target:
public void stateUpdated(Item item, State state) { if (exposedItems != null && exposedItems.contains(item.getName())) { logger.debug("Sending item update to openhab Cloud: - {}", item.getName(), state); cloudClient.sendItemUpdate(item.getName(), state.toString()); } }
Source:
public Object getValueParameter() { START if (valueParameter == null) { END return null; } else { return valueParameter; } } This should be simplified to just: >return valueParameter;

Target:
public Object getValueParameter() { return valueParameter; }
Source:
public void start() throws Exception { logger.trace("Starting Dmx transmitter ..."); transmitter = new DmxTransmitter(this); START transmitter.setTransmitRefresh(transmitRefreshMs); END transmitterTimer = new Timer(true); transmitterTimer.schedule(transmitter, 0, TRANSMIT_FREQUENCY_MS); logger.trace("Dmx transmitter started."); } Could the variables/members/methods all use the phrase `refreshInterval` so the changed code is easier to follow?

Target:
public void start() throws Exception { logger.trace("Starting Dmx transmitter ..."); transmitter = new DmxTransmitter(this); transmitterTimer = new Timer(true); transmitterTimer.schedule(transmitter, 0, TRANSMIT_FREQUENCY_MS); logger.trace("Dmx transmitter started."); }
Source:
public DmxTransmitter(DmxService service) { this.service = service; START lastTransmit = 0; END } Could `lastTransmit` be initialized to 0 above, instead of one private member being initialized that way, and the other initialized in the constructor?

Target:
public DmxTransmitter(DmxService service) { this.service = service; }
Source:
public static String updateStatusVar(LcnDefs.Var var, int value) throws IllegalArgumentException { int id = LcnDefs.Var.toVarId(var); if (id != -1) { // define variable to set, offset 0x01000000 START int x2cmd = id |= 0x40; END int b1 = (value >> 8) & 0xff; int b2 = value & 0xff; return String.format("X2%03d%03d%03d", x2cmd, b1, b2); } // Setting variables and thresholds absolute not implemented in LCN firmware yet throw new IllegalArgumentException(); } It doesn't affect the result, but it would be clearer to use the simple bitwise OR operator (`|`) instead of the bitwise inclusive OR and assignment operator (`|=`).

Target:
public static String updateStatusVar(LcnDefs.Var var, int value) throws IllegalArgumentException { int id = LcnDefs.Var.toVarId(var); if (id != -1) { // define variable to set, offset 0x01000000 int x2cmd = id | 0x40; int b1 = (value >> 8) & 0xff; int b2 = value & 0xff; return String.format("X2%03d%03d%03d", x2cmd, b1, b2); } // Setting variables and thresholds absolute not implemented in LCN firmware yet throw new IllegalArgumentException(); }
Source:
public void updated(Dictionary<String, ?> config) throws ConfigurationException { if (config == null) { return; } validateKeyPatternsInConfig(config); stick = setupStick(config); if (stick != null) { setupNonStickDevices(config); setProperlyConfigured(true); } else { START logger.error("Plugwise needs at least one Stick in order to operate"); END } } This would be better as a `logger.warn`, since `logger.error` is reserved for messages that affect system stability.

Target:
public void updated(Dictionary<String, ?> config) throws ConfigurationException { if (config == null) { return; } validateKeyPatternsInConfig(config); stick = setupStick(config); if (stick != null) { setupNonStickDevices(config); setProperlyConfigured(true); } else { logger.warn("Plugwise needs at least one Stick in order to operate"); } }