auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public boolean acquire(String lock) { <START> if (this.template.update(this.updateQuery, new Date(), this.region, lock, this.id, <END> new Date(System.currentTimeMillis() - this.ttl)) > 0) { return true; } try { return this.template.update(this.insertQuery, this.region, lock, this.id, new Date()) > 0; } catch (DuplicateKeyException e) { return false; } }</code><technical_language>Wll, I deleteExpired() missing fact another node in cluster able acquire lock removed. able reacquire current node is expired, lock is for another clients insert row for is there. ideas deal that, please, new approach</technical_language>

Target:
public boolean acquire(String lock) { if (this.template.update(this.updateQuery, this.id, new Date(), this.region, lock, this.id, new Date(System.currentTimeMillis() - this.ttl)) > 0) { return true; } try { return this.template.update(this.insertQuery, this.region, lock, this.id, new Date()) > 0; } catch (DuplicateKeyException e) { return false; } }
Source:
<code>public void testAddPrefixToDs3ObjectsList() throws IOException, SignatureException { final List<Ds3Object> ds3ObjectList = Lists.newArrayList(new Ds3Object("foo"), new Ds3Object("bar")); final Ds3ClientHelpers helper = Ds3ClientHelpers.wrap(buildDs3ClientForBulk()); final Iterable<Ds3Object> modifiedDs3ObjectList = helper.addPrefixToDs3ObjectsList(ds3ObjectList, "baz/"); boolean foundBazFoo = false; boolean foundBazBar = false; <START> for (Ds3Object obj : modifiedDs3ObjectList) { <END> if (obj.getName().equals("baz/foo")) { foundBazFoo = true; } else if (obj.getName().equals("baz/bar")) { foundBazBar = true; } } assertTrue(foundBazFoo); assertTrue(foundBazBar); }</code><technical_language>Missing final</technical_language>

Target:
public void testAddPrefixToDs3ObjectsList() throws IOException, SignatureException { final List<Ds3Object> ds3ObjectList = Lists.newArrayList(new Ds3Object("foo"), new Ds3Object("bar")); final Ds3ClientHelpers helper = Ds3ClientHelpers.wrap(buildDs3ClientForBulk()); final Iterable<Ds3Object> modifiedDs3ObjectList = helper.addPrefixToDs3ObjectsList(ds3ObjectList, "baz/"); boolean foundBazFoo = false; boolean foundBazBar = false; for (final Ds3Object obj : modifiedDs3ObjectList) { if (obj.getName().equals("baz/foo")) { foundBazFoo = true; } else if (obj.getName().equals("baz/bar")) { foundBazBar = true; } } assertTrue(foundBazFoo); assertTrue(foundBazBar); }
Source:
<code>public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_health_thermometer, container, false); mEditTextTemperatureMeasurement = (EditText) view .findViewById(R.id.editText_temperatureMeasurementValue); mEditTextTemperatureMeasurement .setOnEditorActionListener(mOnEditorActionListenerTemperatureMeasurement); mEditTextMeasurementInterval = (EditText) view .findViewById(R.id.editText_measurementIntervalValue); mEditTextMeasurementInterval .setOnEditorActionListener(mOnEditorActionListenerMeasurementInterval); <START> setDefaultMeasurementValues(INITIAL_TEMPERATURE_MEASUREMENT_VALUE, <END> INITIAL_MEASUREMENT_INTERVAL); setTimer(INITIAL_MEASUREMENT_INTERVAL); return view; }</code><technical_language>this is inline contents of function</technical_language>

Target:
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_health_thermometer, container, false); mEditTextTemperatureMeasurement = (EditText) view .findViewById(R.id.editText_temperatureMeasurementValue); mEditTextTemperatureMeasurement .setOnEditorActionListener(mOnEditorActionListenerTemperatureMeasurement); mEditTextMeasurementInterval = (EditText) view .findViewById(R.id.editText_measurementIntervalValue); mEditTextMeasurementInterval .setOnEditorActionListener(mOnEditorActionListenerMeasurementInterval); mEditTextTemperatureMeasurement.setText(Float.toString(INITIAL_TEMPERATURE_MEASUREMENT_VALUE)); setTemperatureMeasurementValue(INITIAL_TEMPERATURE_MEASUREMENT_VALUE); mMeasurementIntervalCharacteristic.setValue(INITIAL_MEASUREMENT_INTERVAL, MEASUREMENT_INTERVAL_FORMAT, 0); mEditTextMeasurementInterval.setText(Integer.toString(INITIAL_MEASUREMENT_INTERVAL)); mTextViewNotifications = (TextView) view.findViewById(R.id.textView_notifications); mTextViewNotifications.setText(R.string.notificationsNotEnabled); return view; }
Source:
<code>protected boolean isReasoningAvailable(){ try { TBoxReasonerStatus status = ApplicationUtils.instance().getTBoxReasonerModule().getStatus(); return status.isConsistent() && !status.isInErrorState(); <START> } catch (IllegalStateException e) { <END> log.debug("Status of reasoner could not be determined.", e); return false; } }</code><technical_language>Minor: Formatting is a bit off. } catch (... ..should lined try</technical_language>

Target:
protected boolean isReasoningAvailable(){ try { TBoxReasonerStatus status = ApplicationUtils.instance().getTBoxReasonerModule().getStatus(); return status.isConsistent() && !status.isInErrorState(); } catch (IllegalStateException e) { log.debug("Status of reasoner could not be determined. It is likely disabled.", e); return false; } }
Source:
<code>public Response execute(ElasticsearchRequest request) throws IOException { Gson gson = gsonProvider.getGson(); HttpEntity entity = ElasticsearchClientUtils.toEntity( gson, request ); long start = System.currentTimeMillis(); try { return restClient.performRequest( request.getMethod(), request.getPath(), request.getParameters(), entity ); } catch (ResponseException e) { return e.getResponse(); } finally { <START> long executionTime = System.currentTimeMillis() - start; <END> requestLog.executedRequest( request.getPath(), request.getParameters(), executionTime ); } }</code><technical_language>measure durations System.currentTimeMillis(), System.nanoTime()</technical_language>

Target:
public Response execute(ElasticsearchRequest request) throws IOException { Gson gson = gsonProvider.getGson(); HttpEntity entity = ElasticsearchClientUtils.toEntity( gson, request ); long start = System.nanoTime(); try { return restClient.performRequest( request.getMethod(), request.getPath(), request.getParameters(), entity ); } catch (ResponseException e) { return e.getResponse(); } finally { long executionTime = System.nanoTime() - start; requestLog.executedRequest( request.getPath(), request.getParameters(), TimeUnit.NANOSECONDS.toMillis( executionTime ) ); } }
Source:
<code>public boolean hasEntity(StudentProfileAttributes attributes) { if (getEntityQueryKeys(attributes).first().now() != null) { return true; } <START> return getEntityQueryKeysForLegacyData(attributes).first().now() != null; <END> }</code><technical_language>flip guard clause</technical_language>

Target:
public boolean hasEntity(StudentProfileAttributes attributes) { if (getEntityQueryKeys(attributes).first().now() == null) { return getEntityQueryKeysForLegacyData(attributes).first().now() != null; } return true; }
Source:
<code>public static <T> T instanceFromClass(Class<T> targetSuperType, Class<?> classToLoad, String componentDescription) { checkClassType( classToLoad, componentDescription ); <START> final Constructor<?> constructor = getNoArgConstructor( classToLoad, componentDescription ); <END> final Object instance = untypedInstanceFromClass( classToLoad, componentDescription ); return verifySuperTypeCompatibility( targetSuperType, instance, classToLoad, componentDescription ); }</code><technical_language>This variable is used. this line removed</technical_language>

Target:
public static <T> T instanceFromClass(Class<T> targetSuperType, Class<?> classToLoad, String componentDescription) { checkClassType( classToLoad, componentDescription ); final Object instance = untypedInstanceFromClass( classToLoad, componentDescription ); return verifySuperTypeCompatibility( targetSuperType, instance, classToLoad, componentDescription ); }
Source:
<code>TapTargetBase(LinearLayout tapTargetView, View fadeView, WelcomeActivity activity, int bottomBarResourceId) { this.targetView = tapTargetView; this.fadeView = fadeView; this.activity = activity; this.context = activity.getBaseContext(); final DisplayMetrics metrics = context.getResources().getDisplayMetrics(); this.radius = calculateTapTargetRadius(targetView.getHeight(), metrics, RADIUS_OFFSET); bottomBarView = activity.findViewById(bottomBarResourceId); <START> bottomScrollBar = bottomBarView.findViewById(R.id.pocketpaint_intro_bottom_bar_scroll_view); <END> }</code><technical_language>Please revert changes this file</technical_language>

Target:
TapTargetBase(LinearLayout tapTargetView, View fadeView, WelcomeActivity activity, int bottomBarResourceId) { this.targetView = tapTargetView; this.fadeView = fadeView; this.activity = activity; this.context = activity.getBaseContext(); final DisplayMetrics metrics = context.getResources().getDisplayMetrics(); this.radius = calculateTapTargetRadius(targetView.getHeight(), metrics, RADIUS_OFFSET); bottomBarView = activity.findViewById(bottomBarResourceId); bottomScrollBar = (BottomBarHorizontalScrollView) bottomBarView.findViewById(R.id.pocketpaint_intro_bottom_bar_scroll_view); }
Source:
<code>public Map<String, Collection<String>> toMap() { Map<String, Collection<String>> params = new HashMap<String, Collection<String>>(); if (null != name) { ArrayList<String> valueList = new ArrayList<String>(); valueList.add(name); params.put("name", valueList); } <START> if (null != resolution) { <END> ArrayList<String> valueList = new ArrayList<String>(); valueList.add(resolution); params.put("resolution", valueList); } ArrayList<String> valueList = new ArrayList<String>(); valueList.add(Boolean.toString(hasAudio)); params.put("hasAudio", valueList); valueList = new ArrayList<String>(); valueList.add(Boolean.toString(hasVideo)); params.put("hasVideo", valueList); valueList = new ArrayList<String>(); valueList.add(outputMode.toString()); params.put("outputMode", valueList); valueList = new ArrayList<String>(); valueList.add(layout.toString()); params.put("layout", valueList); return params; }</code><technical_language>picky here, I format resolution != null consistent. do think</technical_language>

Target:
public Map<String, Collection<String>> toMap() { Map<String, Collection<String>> params = new HashMap<String, Collection<String>>(); if (name != null) { ArrayList<String> valueList = new ArrayList<String>(); valueList.add(name); params.put("name", valueList); } if (resolution != null) { ArrayList<String> valueList = new ArrayList<String>(); valueList.add(resolution); params.put("resolution", valueList); } ArrayList<String> valueList = new ArrayList<String>(); valueList.add(Boolean.toString(hasAudio)); params.put("hasAudio", valueList); valueList = new ArrayList<String>(); valueList.add(Boolean.toString(hasVideo)); params.put("hasVideo", valueList); valueList = new ArrayList<String>(); valueList.add(outputMode.toString()); params.put("outputMode", valueList); valueList = new ArrayList<String>(); valueList.add(layout.toString()); params.put("layout", valueList); return params; }
Source:
<code>public PlanNodeCostEstimate visitSpatialJoin(SpatialJoinNode node, Void context) { return calculateJoinCost( node, node.getLeft(), node.getRight(), <START> Objects.equals(node.getDistributionType(), SpatialJoinNode.DistributionType.REPLICATED)); <END> }</code><technical_language>node.getDistributionType() == SpatialJoinNode.DistributionType.REPLICATED</technical_language>

Target:
public PlanNodeCostEstimate visitSpatialJoin(SpatialJoinNode node, Void context) { return calculateJoinCost( node, node.getLeft(), node.getRight(), node.getDistributionType() == SpatialJoinNode.DistributionType.REPLICATED); }
Source:
<code>private void validateName(Task task) { Long taskId = task.getId(); <START> int tasksWithName = tasksDataService.findTasksByName(task.getName()).size(); <END> if(taskId == null && tasksWithName > 0) { LOGGER.warn("Task with name: already exists", task.getName()); throw new TaskNameAlreadyExistsException(task.getName()); } else if (taskId != null && tasksWithName > 0) { if(!(tasksDataService.findTasksByName(task.getName()).get(0).getId().equals(taskId))) { LOGGER.warn("Task with name: already exists", task.getName()); throw new TaskNameAlreadyExistsException(task.getName()); } } }</code><technical_language>store returned objects here, repeat database call in line 593</technical_language>

Target:
private void validateName(Task task) { Long taskId = task.getId(); List<Task> tasksWithName = tasksDataService.findTasksByName(task.getName()); if(taskId == null && tasksWithName.size() > 0) { throw new TaskNameAlreadyExistsException(task.getName()); } else if (taskId != null && tasksWithName.size() > 0 && !tasksWithName.get(0).getId().equals(taskId)) { throw new TaskNameAlreadyExistsException(task.getName()); } }
Source:
<code>protected byte[] idSubmodule(File directory, Entry e) { final String gitDirPath = e.getName() + "/" + Constants.DOT_GIT; final File submoduleGitDir = new File(directory, gitDirPath); if (!submoduleGitDir.isDirectory()) return zeroid; final Repository submoduleRepo; try { FS fs = repository != null ? repository.getFS() : FS.DETECTED; submoduleRepo = new RepositoryBuilder().setGitDir(submoduleGitDir) <START> .setMustExist(true).setFS(fs).setMustExist(true).build(); <END> } catch (IOException exception) { return zeroid; } final ObjectId head; try { head = submoduleRepo.resolve(Constants.HEAD); } catch (IOException exception) { return zeroid; } finally { submoduleRepo.close(); } if (head == null) return zeroid; final byte[] id = new byte[Constants.OBJECT_ID_LENGTH]; head.copyRawTo(id, 0); return id; }</code><technical_language>called setMustExist(true) here. of is unnecessary</technical_language>

Target:
protected byte[] idSubmodule(File directory, Entry e) { final String gitDirPath = e.getName() + "/" + Constants.DOT_GIT; final File submoduleGitDir = new File(directory, gitDirPath); if (!submoduleGitDir.isDirectory()) return zeroid; final Repository submoduleRepo; try { FS fs = repository != null ? repository.getFS() : FS.DETECTED; submoduleRepo = new RepositoryBuilder().setGitDir(submoduleGitDir) .setMustExist(true).setFS(fs).build(); } catch (IOException exception) { return zeroid; } final ObjectId head; try { head = submoduleRepo.resolve(Constants.HEAD); } catch (IOException exception) { return zeroid; } finally { submoduleRepo.close(); } if (head == null) return zeroid; final byte[] id = new byte[Constants.OBJECT_ID_LENGTH]; head.copyRawTo(id, 0); return id; }
Source:
<code><START> private CompletableCallOnSubscribe(Call originalCall) { <END> this.originalCall = originalCall; }</code><technical_language>nit: remove private avoid need for a synthetic accessor method generated</technical_language>

Target:
CompletableCallOnSubscribe(Call originalCall) { this.originalCall = originalCall; }
Source:
<code>private Optional<TestDescriptor> discoverEngineRoot(TestEngine testEngine, LauncherDiscoveryRequest discoveryRequest) { UniqueId uniqueEngineId = UniqueId.forEngine(testEngine.getId()); try { TestDescriptor engineRoot = testEngine.discover(discoveryRequest, uniqueEngineId); Preconditions.notNull(engineRoot, () -> String.format( "The discover() method for TestEngine with ID '%s' must return a non-null root TestDescriptor.", testEngine.getId())); Preconditions.condition(isAcyclic(engineRoot), () -> String.format("The discover() method for TestEngine with ID '%s' returned a cyclic graph.", <START> testEngine.getId())); <END> return Optional.of(engineRoot); } catch (Throwable throwable) { handleThrowable(testEngine, "discover", throwable); return Optional.empty(); } }</code><technical_language>I extract checks a separate EngineDiscoveryResultValidator class sth. similar</technical_language>

Target:
private Optional<TestDescriptor> discoverEngineRoot(TestEngine testEngine, LauncherDiscoveryRequest discoveryRequest) { UniqueId uniqueEngineId = UniqueId.forEngine(testEngine.getId()); try { TestDescriptor engineRoot = testEngine.discover(discoveryRequest, uniqueEngineId); discoveryResultValidator.validate(testEngine, engineRoot); return Optional.of(engineRoot); } catch (Throwable throwable) { handleThrowable(testEngine, "discover", throwable); return Optional.empty(); } }
Source:
<code><START> List<String> getMgrsCoordinateStrings(String query) { <END> return coordinateStringsFromQuery(query); }</code><technical_language>Consolidate this method coordinateStringsFromQuery implementation method</technical_language>

Target:
List<String> getMgrsCoordinateStrings(String query) { final String terminatedQuery = query.concat(WHITESPACE); final Matcher matcher = PATTERN_MGRS_ANYPART.matcher(terminatedQuery); final List<String> mgrsStrings = new ArrayList<>(); final StringBuilder mgrsBuilder = new StringBuilder(); MgrsPartType previousType = MgrsPartType.NONE; while (matcher.find()) { final String mgrsPart = matcher.group().toUpperCase(); final MgrsPartType type = getPartType(mgrsPart); switch (type) { case ZONE: handleZoneWithPreviousType(mgrsPart, previousType, mgrsBuilder, mgrsStrings); break; case HUNDRED_KM: handleHundredKmWithPreviousType(mgrsPart, previousType, mgrsBuilder); break; case NUMERIC: handleNumericWithPreviousType(mgrsPart, previousType, mgrsBuilder, mgrsStrings); break; case NONE: throw new IllegalStateException( format("The provided mgrs part [ %s ] must map to a valid type", mgrsPart)); } LOGGER.debug( "MGRS strings [{}], builder state [{}], and types [{}|{}]", mgrsStrings, mgrsBuilder, previousType, type); previousType = type; } LOGGER.trace("Builder's final state [{}]", mgrsBuilder); if (previousType != MgrsPartType.NUMERIC && mgrsBuilder.length() > 0) { mgrsStrings.add(mgrsBuilder.toString()); } return mgrsStrings.stream().distinct().collect(Collectors.toList()); }
Source:
<code>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> }</code><technical_language>result implicitly type casted</technical_language>

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:
<code>public void jumpToFrame(GraphName frame) { synchronized (mutex) { this.frame = frame; <START> double scale = cameraToRosTransform.getScale(); <END> resetTransform(); cameraToRosTransform = cameraToRosTransform.scale(scale / cameraToRosTransform.getScale()); } }</code><technical_language>final</technical_language>

Target:
public void jumpToFrame(GraphName frame) { synchronized (mutex) { this.frame = frame; final double scale = cameraToRosTransform.getScale(); resetTransform(); cameraToRosTransform = cameraToRosTransform.scale(scale / cameraToRosTransform.getScale()); } }
Source:
<code>public Response endPointsGet(String apiName, String label, String apiId, MessageContext messageContext) { InMemoryAPIDeployer inMemoryApiDeployer = new InMemoryAPIDeployer(); GatewayAPIDTO gatewayAPIDTO = inMemoryApiDeployer.getAPIArtifact(apiId, label); JSONObject responseObj = new JSONObject(); JSONArray endPointArray = new JSONArray(); if (gatewayAPIDTO != null) { if (gatewayAPIDTO.getEndpointEntriesToBeAdd() != null ) { EndpointAdminServiceProxy endpointAdminServiceProxy = new EndpointAdminServiceProxy (gatewayAPIDTO.getTenantDomain()); for (GatewayContentDTO gatewayEndpoint : gatewayAPIDTO.getEndpointEntriesToBeAdd()) { try { if (endpointAdminServiceProxy.isEndpointExist(gatewayEndpoint.getName())) { endPointArray.put(endpointAdminServiceProxy.getEndpoints(gatewayEndpoint.getName())); } else { <START> log.error(gatewayEndpoint.getName() + " was not deployed in the gateway"); <END> } } catch (EndpointAdminException e) { log.error("Error in fetching deployed Endpoints from Synapse Configuration." , e); } } } responseObj.put("Endpoints", endPointArray); String responseStringObj = String.valueOf(responseObj); return Response.ok().entity(responseStringObj).build(); } else { responseObj.put("Message", "Error"); String responseStringObj = String.valueOf(responseObj); return Response.serverError().entity(responseStringObj).build(); } }</code><technical_language>this in response</technical_language>

Target:
public Response endPointsGet(String apiName, String label, String apiId, MessageContext messageContext) { InMemoryAPIDeployer inMemoryApiDeployer = new InMemoryAPIDeployer(); GatewayAPIDTO gatewayAPIDTO = inMemoryApiDeployer.getAPIArtifact(apiId, label); JSONObject responseObj = new JSONObject(); if (gatewayAPIDTO != null) { try { JSONArray endPointArray = new JSONArray(); JSONArray unDeployedEndPointArray = new JSONArray(); if (gatewayAPIDTO.getEndpointEntriesToBeAdd() != null) { EndpointAdminServiceProxy endpointAdminServiceProxy = new EndpointAdminServiceProxy (gatewayAPIDTO.getTenantDomain()); for (GatewayContentDTO gatewayEndpoint : gatewayAPIDTO.getEndpointEntriesToBeAdd()) { if (endpointAdminServiceProxy.isEndpointExist(gatewayEndpoint.getName())) { endPointArray.put(endpointAdminServiceProxy.getEndpoints(gatewayEndpoint.getName())); } else { log.error(gatewayEndpoint.getName() + " was not deployed in the gateway"); unDeployedEndPointArray.put(gatewayEndpoint.getContent()); } } } responseObj.put("Deployed Endpoints", endPointArray); responseObj.put("UnDeployed Endpoints", unDeployedEndPointArray); } catch (EndpointAdminException e) { String errorMessage = "Error in fetching deployed Endpoints from Synapse Configuration"; log.error(errorMessage, e); RestApiUtil.handleInternalServerError(errorMessage, e, log); } String responseStringObj = String.valueOf(responseObj); return Response.ok().entity(responseStringObj).build(); } else { responseObj.put("Message", "Error"); String responseStringObj = String.valueOf(responseObj); return Response.serverError().entity(responseStringObj).build(); } }
Source:
<code>protected void onTimerDurationChange() { String oldValue = value; <START> value = copy(oldValue); <END> value = view.getTimeDuration(); notifyChange(oldValue, value); }</code><technical_language>Calling copy() method effect</technical_language>

Target:
protected void onTimerDurationChange() { String oldValue = value; value = view.getTimeDuration(); if (view.isValid()) { notifyChange(oldValue, value); } }
Source:
<code>private boolean holderListContains(V object) { <START> return resourceHolderList.stream().filter(a -> a.getResource().equals(object)).findAny().isPresent(); <END> }</code><technical_language>stream().anyMatch(a -> a.getResource().equals(object))</technical_language>

Target:
private boolean holderListContains(V object) { return resourceHolderList.stream().anyMatch(a -> a.getResource().equals(object)); }
Source:
<code>public Vector3d toVector3(double z) { <START> return null; <END> }</code><technical_language>This return new SpongeVector3d(x, y, z);</technical_language>

Target:
public Vector3d toVector3(double z) { return new SpongeVector3d(x, y, z); }
Source:
<code>public Traversal.Admin<S, S> getRepeatTraversal() { if(null == this.repeatTraversal) <START> throw new IllegalStateException("The repeat()-traversal was not defined: " + this); <END> return this.repeatTraversal; }</code><technical_language>I throw exception in a Getter</technical_language>

Target:
public Traversal.Admin<S, S> getRepeatTraversal() { return this.repeatTraversal; }
Source:
<code>public GitProjectType(GitValueProviderFactory gitRepositoryValueProviderFactory) { super("git", "git"); addVariableDefinition(VCS_PROVIDER_NAME, "Is this git repo or not?", false, gitRepositoryValueProviderFactory); <START> addVariableDefinition(CURRENT_BRANCH_NAME, "Name of current brunch", false, <END> gitRepositoryValueProviderFactory); addVariableDefinition(REPOSITORY_REMOTES, "List of repository remote addresses", false, gitRepositoryValueProviderFactory); }</code><technical_language>Fix "brunch"</technical_language>

Target:
public GitProjectType(GitValueProviderFactory gitRepositoryValueProviderFactory) { super("git", "git"); addVariableDefinition(VCS_PROVIDER_NAME, "Is this git repo or not?", false, gitRepositoryValueProviderFactory); addVariableDefinition(GIT_CURRENT_BRANCH_NAME, "Name of current git branch", false, gitRepositoryValueProviderFactory); addVariableDefinition(GIT_REPOSITORY_REMOTES, "List of git repository remote addresses", false, gitRepositoryValueProviderFactory); }
Source:
<code>private DataSegment createDescriptorFile(DataSegment segment, Path outDir, final FileSystem fs) throws IOException { final Path descriptorFile = new Path(outDir, "descriptor.json"); log.info("Creating descriptor file at[%s]", descriptorFile); <START> final ByteSource byteSource = ByteSource.wrap(jsonMapper.writeValueAsBytes(segment)); <END> byteSource.copyTo(new HdfsOutputStreamSupplier(fs, descriptorFile)); return segment; }</code><technical_language>This is a requirement, simply chain methods more readable java ByteSource .wrap(jsonMapper.writeValueAsBytes(segment)) .copyTo(new HdfsOutputStreamSupplier(fs, descriptorFile));</technical_language>

Target:
private DataSegment createDescriptorFile(DataSegment segment, Path outDir, final FileSystem fs) throws IOException { final Path descriptorFile = new Path(outDir, "descriptor.json"); log.info("Creating descriptor file at[%s]", descriptorFile); ByteSource .wrap(jsonMapper.writeValueAsBytes(segment)) .copyTo(new HdfsOutputStreamSupplier(fs, descriptorFile)); return segment; }
Source:
<code>protected void prepareTestData() { testData = loadDataBundle("/StudentHomePageUiTest.json"); String student1GoogleId = TestProperties.TEST_STUDENT1_ACCOUNT; String student1Email = student1GoogleId + "@gmail.com"; testData.accounts.get("alice.tmms").googleId = student1GoogleId; testData.accounts.get("alice.tmms").email = student1Email; <START> testData.students.get("alice.tmms@SHomeUiT.CS2104").googleId = student1GoogleId; <END> testData.students.get("alice.tmms@SHomeUiT.CS2104").email = student1Email; testData.students.get("alice.tmms@SHomeUiT.CS1101").googleId = student1GoogleId; testData.students.get("alice.tmms@SHomeUiT.CS1101").email = student1Email; testData.students.get("alice.tmms@SHomeUiT.CS4215").googleId = student1GoogleId; testData.students.get("alice.tmms@SHomeUiT.CS4215").email = student1Email; testData.students.get("alice.tmms@SHomeUiT.CS4221").googleId = student1GoogleId; testData.students.get("alice.tmms@SHomeUiT.CS4221").email = student1Email; removeAndRestoreDataBundle(testData); FeedbackSessionAttributes gracedFeedbackSession = BackDoor.getFeedbackSession("SHomeUiT.CS2104", "Graced Feedback Session"); gracedFeedbackSession.setEndTime(Instant.now()); BackDoor.editFeedbackSession(gracedFeedbackSession); }</code><technical_language>Actually, this need changed Alice joined joined other. more "real". I problem is top of JSON error-prone completely new test data test sharing test data guaranteed correct other tests :( another perspective data loaded JSON checks data loaded is valid</technical_language>

Target:
protected void prepareTestData() { testData = loadDataBundle("/StudentHomePageUiTest.json"); String student1GoogleId = TestProperties.TEST_STUDENT1_ACCOUNT; String student1Email = student1GoogleId + "@gmail.com"; testData.accounts.get("alice.tmms").googleId = student1GoogleId; testData.accounts.get("alice.tmms").email = student1Email; testData.students.get("alice.tmms@SHomeUiT.CS2104").email = student1Email; testData.students.get("alice.tmms@SHomeUiT.CS1101").googleId = student1GoogleId; testData.students.get("alice.tmms@SHomeUiT.CS1101").email = student1Email; testData.students.get("alice.tmms@SHomeUiT.CS4215").googleId = student1GoogleId; testData.students.get("alice.tmms@SHomeUiT.CS4215").email = student1Email; testData.students.get("alice.tmms@SHomeUiT.CS4221").googleId = student1GoogleId; testData.students.get("alice.tmms@SHomeUiT.CS4221").email = student1Email; removeAndRestoreDataBundle(testData); FeedbackSessionAttributes gracedFeedbackSession = BackDoor.getFeedbackSession("SHomeUiT.CS2104", "Graced Feedback Session"); gracedFeedbackSession.setEndTime(Instant.now()); BackDoor.editFeedbackSession(gracedFeedbackSession); }
Source:
<code>public void testInitializeWithNoChroot() throws AlreadyInitializedException { config.setAllowReinitialize(true); <START> config.setZookeepers("localhost"); <END> FluoAdmin fluoAdmin = new FluoAdminImpl(config); try { fluoAdmin.initialize(); fail("This should have failed"); } catch (IllegalArgumentException e) { } }</code><technical_language>nice try a configs here... localhost, localhost/, localhost:9999/, localhost:9999, localhost/ .... test do foreach(String zk : new String[]{"localhost", "localhost/", etc}</technical_language>

Target:
public void testInitializeWithNoChroot() throws AlreadyInitializedException { config.setAllowReinitialize(true); for (String host : new String[]{"localhost", "localhost/", "localhost:9999", "localhost:9999/"}) { config.setZookeepers(host); FluoAdmin fluoAdmin = new FluoAdminImpl(config); try { fluoAdmin.initialize(); fail("This should have failed"); } catch (IllegalArgumentException e) { } } }
Source:
<code>public void start() { final SocketConnector connector = new SocketConnector(); connector.setPort(port); if (null != host && !host.equals("")) { connector.setHost(host); } server.setConnectors(new Connector[] { connector }); final ServletContextHandler idHandler = configureRestHandler(); final RequestLogHandler requestLogHandler = configureRequestLoggerIfDesired(); final HandlerCollection handlers = new HandlerCollection(); if (null == requestLogHandler) { handlers.setHandlers(new Handler[] { idHandler }); } else { handlers.setHandlers(new Handler[] { idHandler, requestLogHandler }); } server.setHandler(handlers); try { <START> log.log(Level.INFO, <END> "Starting " + serviceName + " server on port " + port + " ( <LINK_0>" + port + " )", new Object[] { serviceName, port, port }); server.start(); } catch (Exception e) { throw new RuntimeException(e); } }</code><technical_language>this log line work? Object[] is inserted string, is java variables comlete String argument</technical_language>

Target:
public void start() { final SocketConnector connector = new SocketConnector(); connector.setPort(port); if (null != host && !host.equals("")) { connector.setHost(host); } server.setConnectors(new Connector[] { connector }); final ServletContextHandler idHandler = configureRestHandler(); final RequestLogHandler requestLogHandler = configureRequestLoggerIfDesired(); final HandlerCollection handlers = new HandlerCollection(); if (null == requestLogHandler) { handlers.setHandlers(new Handler[] { idHandler }); } else { handlers.setHandlers(new Handler[] { idHandler, requestLogHandler }); } server.setHandler(handlers); try { log.log(Level.INFO, "Starting " + serviceName + " server on port " + port + " ( <LINK_0>" + port + " )"); server.start(); } catch (Exception e) { throw new RuntimeException(e); } }
Source:
<code>public void updateIfNeeded(VdsDynamic vdsDynamic) { VdsDynamic dbData = get(vdsDynamic.getId()); if (!dbData.equals(vdsDynamic)) { dbData.setcpu_over_commit_time_stamp(vdsDynamic.getcpu_over_commit_time_stamp()); if (dbData.equals(vdsDynamic)) { <START> updateCpuOverCommit(vdsDynamic.getId(), vdsDynamic.getcpu_over_commit_time_stamp()); <END> } else { update(vdsDynamic); } } else { log.debug("Ignored an unneeded update of VdsDynamic"); } }</code><technical_language>move statistics</technical_language>

Target:
public void updateIfNeeded(VdsDynamic vdsDynamic) { VdsDynamic dbData = get(vdsDynamic.getId()); if (!dbData.equals(vdsDynamic)) { update(vdsDynamic); } else { log.debug("Ignored an unneeded update of VdsDynamic"); } }
Source:
<code>protected String getRequestToken(final Request request) throws AuthException { final Configuration c = getConfiguration(); final Promise<Response> r = WS.url( c.getString(SettingKeys.REQUEST_TOKEN_URL)) .setHeader("Content-Type", "application/x-www-form-urlencoded") .post(getRequestTokenParams(request, c)); final Response response = r.get(); if (response.getStatus() > 400) { throw new AuthException(response.asJson() .get("meta") .get("errorDetail") .asText()); } else { <START> String body = response.getBody(); <END> if(body != null && !body.equals("") && body.indexOf("=") != -1) { return body.substring(body.indexOf("=") + 1); } else { throw new AuthException("No token could be found in body response"); } } }</code><technical_language>This fragile - querystring parser JSON API is advised I think..</technical_language>

Target:
protected String getRequestToken(final Request request) throws AuthException { final Configuration c = getConfiguration(); final List<NameValuePair> params = getRequestTokenParams(request, c); final Response r = WS.url(c.getString(SettingKeys.REQUEST_TOKEN_URL)) .setHeader("Content-Type", "application/json") .setHeader("X-Accept", "application/json") .post(encodeParamsAsJson(params)) .get(PlayAuthenticate.TIMEOUT); if (r.getStatus() >= 400) { throw new AuthException(r.asJson().asText()); } else { return r.asJson().get("code").asText(); } }
Source:
<code>public boolean containsKey(final K key) throws StoreAccessException { <START> if(getInternal(key) == null) { <END> return false; } else { return true; } }</code><technical_language>simplify return getInternal(key) != null</technical_language>

Target:
public boolean containsKey(final K key) throws StoreAccessException { return getInternal(key) != null; }
Source:
<code>public boolean configDnsSupportForSubnet(Network network, NicProfile nic, VirtualMachineProfile vm, DeployDestination dest, ReservationContext context) throws ConcurrentOperationException, InsufficientCapacityException, ResourceUnavailableException { if (_networkModel.isProviderSupportServiceInNetwork(network.getId(), Service.Dhcp, getProvider())) { return true; <START> } else { <END> return configureDhcpSupport(network, nic, vm, dest, Service.Dns); } }</code><technical_language>This else block is unnecessary if block returns. Please remove it</technical_language>

Target:
public boolean configDnsSupportForSubnet(Network network, NicProfile nic, VirtualMachineProfile vm, DeployDestination dest, ReservationContext context) throws ConcurrentOperationException, InsufficientCapacityException, ResourceUnavailableException { if (_networkModel.isProviderSupportServiceInNetwork(network.getId(), Service.Dhcp, getProvider())) { return true; } return configureDhcpSupport(network, nic, vm, dest, Service.Dns); }
Source:
<code>protected List<URL> getDriversFromMirror(URL driverUrl) throws IOException { if (mirrorLog) { log.info("Crawling driver list from mirror {}", driverUrl); mirrorLog = true; } else { log.trace("[Recursive call] Crawling driver list from mirror {}", driverUrl); } String driverStr = driverUrl.toString(); HttpResponse response = httpClient .execute(httpClient.createHttpGet(driverUrl)); try (InputStream in = response.getEntity().getContent()) { org.jsoup.nodes.Document doc = Jsoup.parse(in, null, driverStr); Iterator<org.jsoup.nodes.Element> iterator = doc.select("a") .iterator(); List<URL> urlList = new ArrayList<>(); while (iterator.hasNext()) { String link = iterator.next().attr("abs:href"); if (link.startsWith(driverStr) && link.endsWith(SLASH)) { urlList.addAll(getDriversFromMirror(new URL(link))); <START> } else if (link.startsWith(driverStr) && !link.contains("icons") && (link.toLowerCase().endsWith(".bz2") <END> || link.toLowerCase().endsWith(".zip") || link.toLowerCase().endsWith(".gz"))) { urlList.add(new URL(link)); } } return urlList; } }</code><technical_language>Is this condition needed? I check bz2, zip, etc. If so, extension added: msi (it is for compatibility versions of edgedriver)</technical_language>

Target:
protected List<URL> getDriversFromMirror(URL driverUrl) throws IOException { if (mirrorLog) { log.info("Crawling driver list from mirror {}", driverUrl); mirrorLog = true; } else { log.trace("[Recursive call] Crawling driver list from mirror {}", driverUrl); } String driverStr = driverUrl.toString(); HttpResponse response = httpClient .execute(httpClient.createHttpGet(driverUrl)); try (InputStream in = response.getEntity().getContent()) { org.jsoup.nodes.Document doc = Jsoup.parse(in, null, driverStr); Iterator<org.jsoup.nodes.Element> iterator = doc.select("a") .iterator(); List<URL> urlList = new ArrayList<>(); while (iterator.hasNext()) { String link = iterator.next().attr("abs:href"); if (link.startsWith(driverStr) && link.endsWith(SLASH)) { urlList.addAll(getDriversFromMirror(new URL(link))); } else if (link.startsWith(driverStr) && !link.contains("icons") && (link.toLowerCase().endsWith(".bz2") || link.toLowerCase().endsWith(".zip") || link.toLowerCase().endsWith(".msi") || link.toLowerCase().endsWith(".gz"))) { urlList.add(new URL(link)); } } return urlList; } }
Source:
<code>public BuildStatusNotifierPlugin() { try { Properties properties = new Properties(); properties.load(getClass().getResourceAsStream("/defaults.properties")); Class<?> providerClass = Class.forName(properties.getProperty("provider")); Constructor<?> constructor = providerClass.getConstructor(); provider = (Provider) constructor.newInstance(); <START> templateName = properties.getProperty("settings.template"); <END> } catch (Exception e) { throw new RuntimeException("could not create provider", e); } }</code><technical_language>This IMO provider, of configuration files a minimum</technical_language>

Target:
public BuildStatusNotifierPlugin() { try { Properties properties = new Properties(); properties.load(getClass().getResourceAsStream("/defaults.properties")); Class<?> providerClass = Class.forName(properties.getProperty("provider")); Constructor<?> constructor = providerClass.getConstructor(); provider = (Provider) constructor.newInstance(); } catch (Exception e) { throw new RuntimeException("could not create provider", e); } }
Source:
<code>public long lastModified() throws IOException { if (IoUtils.isFileUrl(url)) { return super.lastModified(); } else { URLConnection conn = null; try { conn = url.openConnection(); configureUrlConnection(conn); if (conn instanceof HttpURLConnection) { HttpURLConnection httpConn = (HttpURLConnection) conn; int responseCode = httpConn.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { return httpConn.getLastModified(); } else if (responseCode == HttpURLConnection.HTTP_NOT_FOUND) { throw new FileNotFoundException(getDescription() + " not found: " + "responseCode=" + responseCode + ", usingProxy=" + httpConn.usingProxy()); } else if (responseCode / 100 == 4) { throw new IOException(getDescription() + " is not accessible: " + "responseCode=" + responseCode + ", usingProxy=" + httpConn.usingProxy()); } else if (responseCode / 100 == 5) { throw new IOException(getDescription() + " is not available: " + "responseCode=" + responseCode + ", usingProxy=" + httpConn.usingProxy()); } else { <START> return 0; END> } } else { return super.lastModified(); } } finally { IoUtils.closeQuietly(conn); } } }</code><technical_language>I fail caller decide proceed</technical_language>

Target:
public long lastModified() { if (IoUtils.isFileUrl(url)) { return super.lastModified(); } else { URLConnection conn = null; try { conn = url.openConnection(); configureUrlConnection(conn); if (conn instanceof HttpURLConnection) { HttpURLConnection httpConn = (HttpURLConnection) conn; int responseCode = httpConn.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { return httpConn.getLastModified(); } else if (responseCode == HttpURLConnection.HTTP_NOT_FOUND) { throw new FileNotFoundRuntimeException(getDescription() + " not found: " + "responseCode=" + responseCode + ", usingProxy=" + httpConn.usingProxy()); } else if ((responseCode / 100 == 2) || (responseCode / 100 == 3)) { long lastModified = httpConn.getLastModified(); if (logger.isLoggable(Level.FINER)) { logger.finer(getDescription() + " returned an unexpected '" + responseCode + " " + httpConn.getResponseMessage() + "'. lastModified=" + lastModified); } return lastModified; } else if (responseCode / 100 == 4) { throw new IoRuntimeException(getDescription() + " is not accessible: " + "responseCode=" + responseCode + ", usingProxy=" + httpConn.usingProxy()); } else if (responseCode / 100 == 5) { throw new IoRuntimeException(getDescription() + " is not available: " + "responseCode=" + responseCode + ", usingProxy=" + httpConn.usingProxy()); } else { throw new IoRuntimeException(getDescription() + "returned an unexpected " + responseCode + " " + httpConn.getResponseMessage()); } } else { return super.lastModified(); } } catch (IOException e) { throw IoRuntimeException.propagate(e); } finally { IoUtils.closeQuietly(conn); } } }
Source:
<code>protected RowMapper<AffinityGroup> createEntityRowMapper() { <START> return new RowMapper<AffinityGroup>() { <END> @Override public AffinityGroup mapRow(ResultSet rs, int arg1) throws SQLException { AffinityGroup affinityGroup = new AffinityGroup(); affinityGroup.setId(getGuid(rs, "id")); affinityGroup.setName(rs.getString("name")); affinityGroup.setDescription(rs.getString("description")); affinityGroup.setClusterId(getGuid(rs, "cluster_id")); affinityGroup.setPolarity(AffinityPolarity.forValue(rs.getInt("polarity"))); affinityGroup.setEnforcementType(AffinityEnforcementType.forValue(rs.getInt("enforcement_type"))); affinityGroup.setVmIds(GuidUtils.getGuidListFromString(rs.getString("vm_ids"))); affinityGroup.setVmNames(split(rs.getString("vm_names"))); return affinityGroup; } }; }</code><technical_language>I recommend returning a static instance. Row mappers stateless nature</technical_language>

Target:
protected RowMapper<AffinityGroup> createEntityRowMapper() { return AffinityGropupRowMapper.instance; }
Source:
<code>public final void returnsVerboseIterator() throws Exception { <START> final Iterator<Object> iterator = this.list.iterator(); <END> MatcherAssert.assertThat( iterator, Matchers.instanceOf(VerboseIterator.class) ); }</code><technical_language>@Happy-Neko avoid inline this variable argument in assertThat instead of declaring a variable once</technical_language>

Target:
public final void returnsVerboseIterator() throws Exception { MatcherAssert.assertThat( this.list.iterator(), Matchers.instanceOf(VerboseIterator.class) ); }
Source:
<code>public Collection<DocumentFieldMetadata> getAllDocumentFieldMetadata() { if ( embeddedTypeMetadata.isEmpty() ) { return documentFieldMetadata; } else { Collection<DocumentFieldMetadata> allMetadata = new ArrayList<DocumentFieldMetadata>( documentFieldMetadata.size() ); for ( EmbeddedTypeMetadata element : embeddedTypeMetadata ) { allMetadata.addAll( element.getAllDocumentFieldMetadata() ); } allMetadata.addAll( documentFieldMetadata ); <START> return allMetadata; <END> } }</code><technical_language>I expected a Collections.unmodifiableCollection here</technical_language>

Target:
public Collection<DocumentFieldMetadata> getAllDocumentFieldMetadata() { if ( embeddedTypeMetadata.isEmpty() ) { return documentFieldMetadata; } else { Collection<DocumentFieldMetadata> allMetadata = new ArrayList<DocumentFieldMetadata>( documentFieldMetadata.size() ); for ( EmbeddedTypeMetadata element : embeddedTypeMetadata ) { allMetadata.addAll( element.getAllDocumentFieldMetadata() ); } allMetadata.addAll( documentFieldMetadata ); return Collections.unmodifiableCollection( allMetadata ); } }
Source:
<code>private static void runTest(CtfTmfTestTrace testTrace, String testName, Map<String, Long> testCases) { assumeTrue(testTrace.exists()); Performance perf = Performance.getDefault(); PerformanceMeter pm = perf.createPerformanceMeter(TEST_ID + '#' + testName); perf.tagAsSummary(pm, "Statistics Analysis: " + testName, Dimension.CPU_TIME); if (testTrace == <START> CtfTmfTestTrace.DJANGO_CLIENT || <END> testTrace == CtfTmfTestTrace.DJANGO_HTTPD) { perf.tagAsGlobalSummary(pm, "Statistics Analysis: " + testName, Dimension.CPU_TIME); } for (int i = 0; i < LOOP_COUNT; i++) { TmfStatisticsModule module = null; try (LttngKernelTrace trace = new LttngKernelTrace()) { module = new TmfStatisticsModule(); module.setId("test"); trace.initTrace(null, testTrace.getPath(), CtfTmfEvent.class); module.setTrace(trace); pm.start(); TmfTestHelper.executeAnalysis(module); pm.stop(); ITmfStatistics stats = module.getStatistics(); if (stats == null) { throw new IllegalStateException(); } Map<String, Long> map = stats.getEventTypesTotal(); try { for (Entry<String, Long> entry : testCases.entrySet()) { Assert.assertTrue(map.get(entry.getKey()).equals(entry.getValue())); } } catch (NullPointerException e) { fail(e.getMessage()); } File suppDir = new File(TmfTraceManager.getSupplementaryFileDir(trace)); for (File file : suppDir.listFiles()) { file.delete(); } } catch (TmfAnalysisException | TmfTraceException e) { fail(e.getMessage()); } finally { if (module != null) { module.dispose(); } } } pm.commit(); testTrace.dispose(); }</code><technical_language>I in global summary, give a good idea if analysis regressed. do think? global shown <LINK_0></technical_language>

Target:
private static void runTest(CtfTmfTestTrace testTrace, String testName, Map<String, Long> testCases) { assumeTrue(testTrace.exists()); Performance perf = Performance.getDefault(); PerformanceMeter pm = perf.createPerformanceMeter(TEST_ID + '#' + testName); perf.tagAsSummary(pm, "Statistics Analysis: " + testName, Dimension.CPU_TIME); if (testTrace == CtfTmfTestTrace.DJANGO_CLIENT) { perf.tagAsGlobalSummary(pm, "Statistics Analysis: " + testName, Dimension.CPU_TIME); } for (int i = 0; i < LOOP_COUNT; i++) { TmfStatisticsModule module = null; try (LttngKernelTrace trace = new LttngKernelTrace()) { module = new TmfStatisticsModule(); module.setId("test"); trace.initTrace(null, testTrace.getPath(), CtfTmfEvent.class); module.setTrace(trace); pm.start(); TmfTestHelper.executeAnalysis(module); pm.stop(); ITmfStatistics stats = module.getStatistics(); if (stats == null) { throw new IllegalStateException(); } Map<String, Long> map = stats.getEventTypesTotal(); try { for (Entry<String, Long> entry : testCases.entrySet()) { Assert.assertTrue(map.get(entry.getKey()).equals(entry.getValue())); } } catch (NullPointerException e) { fail(e.getMessage()); } File suppDir = new File(TmfTraceManager.getSupplementaryFileDir(trace)); for (File file : suppDir.listFiles()) { file.delete(); } } catch (TmfAnalysisException | TmfTraceException e) { fail(e.getMessage()); } finally { if (module != null) { module.dispose(); } } } pm.commit(); testTrace.dispose(); }
Source:
<code>private Callable<Throwable> callable(final ProceedingJoinPoint point, final CountDownLatch start) { return new Callable<Throwable>() { @Override public Throwable call() { try { start.await(); point.proceed(); } catch (Throwable ex) { <START> return ex; <END> } return null; } }; }</code><technical_language>I this multiple returning in method. declare Throwable result assign twice, return once</technical_language>

Target:
private Callable<Throwable> callable(final ProceedingJoinPoint point, final CountDownLatch start) { return new Callable<Throwable>() { @Override public Throwable call() { Throwable result = null; try { start.await(); point.proceed(); } catch (Throwable ex) { result = ex; } return result; } }; }