auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private void validateSetOptimizeQueriesOption(boolean optimizeQueries) { if (!setCacheDeserializedValuesExplicitlyInvoked) { return; } if ((cacheDeserializedValues == CacheDeserializedValues.INDEX_ONLY || cacheDeserializedValues == CacheDeserializedValues.NEVER) && optimizeQueries) { throw new ConfigurationException("Deprecated option 'optimize-queries' is being set to true, " + "but 'cacheDeserializedValues' was set to NEVER or INDEX_ONLY. " + "These are conflicting options. Please remove the `optimize-queries'"); } else if (cacheDeserializedValues == CacheDeserializedValues.ALWAYS && !optimizeQueries) { throw new ConfigurationException("Deprecated option 'optimize-queries' is being set to false, " + "but 'cacheDeserializedValues' was set to ALWAYS. " + "These are conflicting options. Please remove the `optimize-queries'"); } }

Target:
private void validateSetOptimizeQueriesOption(boolean optimizeQueries) { if (!setCacheDeserializedValuesExplicitlyInvoked) { return; } if (cacheDeserializedValues != CacheDeserializedValues.ALWAYS && optimizeQueries) { throw new ConfigurationException("Deprecated option 'optimize-queries' is being set to true, " + "but 'cacheDeserializedValues' was set to NEVER or INDEX_ONLY. " + "These are conflicting options. Please remove the `optimize-queries'"); } else if (cacheDeserializedValues == CacheDeserializedValues.ALWAYS && !optimizeQueries) { throw new ConfigurationException("Deprecated option 'optimize-queries' is being set to false, " + "but 'cacheDeserializedValues' was set to ALWAYS. " + "These are conflicting options. Please remove the `optimize-queries'"); } }
Source:
protected void afterRunInternal() { // Publish listener events // This should happen in after-run to avoid surfacing exceptions during predicate attribute conversion. // Single Map.put() behaves the same. see. https://github.com/hazelcast/hazelcast/issues/15415 for (EventDescriptor descriptor : unpublishedEvents) { mapEventPublisher.publishEvent(descriptor.caller, descriptor.mapName, descriptor.eventType, descriptor.dataKey, descriptor.oldValue, descriptor.dataValue); } invalidateNearCache(invalidationKeys); disposeDeferredBlocks = true; super.afterRunInternal(); }

Target:
protected void afterRunInternal() { invalidateNearCache(invalidationKeys); super.afterRunInternal(); }
Source:
public Record putReplicatedRecord(Record replicatedRecord, long nowInMillis, boolean populateIndexes) { Record newRecord = createRecord(replicatedRecord, nowInMillis); markRecordStoreExpirable(replicatedRecord.getTtl(), replicatedRecord.getMaxIdle()); // Note that newRecord may not know its key yet, key assignment // is done after storage put in some cases so better to // use key of replicatedRecord when doing storage.put storage.put(replicatedRecord.getKey(), newRecord); mutationObserver.onReplicationPutRecord(newRecord.getKey(), newRecord, !populateIndexes); updateStatsOnPut(replicatedRecord.getHits(), nowInMillis); return newRecord; }

Target:
public Record putReplicatedRecord(Record replicatedRecord, long nowInMillis, boolean populateIndexes) { Record newRecord = createRecord(replicatedRecord, nowInMillis); markRecordStoreExpirable(replicatedRecord.getTtl(), replicatedRecord.getMaxIdle()); // Note that newRecord may not know its key yet, key assignment // is done after storage put in some cases so better to // use key of replicatedRecord when doing storage.put storage.put(replicatedRecord.getKey(), newRecord); mutationObserver.onReplicationPutRecord(newRecord.getKey(), newRecord, populateIndexes); updateStatsOnPut(replicatedRecord.getHits(), nowInMillis); return newRecord; }
Source:
protected void runInternal() { if (dataRecords == null) { // If dataRecords is null and we are in // `runInternal` method, means this operation // has not been serialized/deserialized // and is running directly on caller node for (int i = 0; i < recordAndDataValuePairs.size(); i += 2) { Object obj = recordAndDataValuePairs.get(i); if (obj != null) { putBackup((Record) obj); } } } else { for (Record<Data> record : dataRecords) { putBackup(record); } } }

Target:
protected void runInternal() { if (dataRecords != null) { for (Record<Data> record : dataRecords) { putBackup(record); } } else { // If dataRecords is null and we are in // `runInternal` method, means this operation // has not been serialized/deserialized // and is running directly on caller node. for (int i = 0; i < recordAndDataValuePairs.size(); i += 2) { putBackup((Record) recordAndDataValuePairs.get(i)); } } }
Source:
public JavaKeyStoreSecureStoreConfig setPassword(String password) { checkNotNull(password, "Java Key Store password cannot be null!"); this.password = password; return this; }

Target:
public JavaKeyStoreSecureStoreConfig setPassword(String password) { // null password allowed this.password = password; return this; }
Source:
public boolean equals(Object o) { if (o == null || getClass() != o.getClass()) { return false; } CompositeValue that = (CompositeValue) o; assert components.length == that.components.length; for (int i = 0; i < components.length; ++i) { if (!Comparables.equal(components[i], that.components[i])) { return false; } } return true; }

Target:
public boolean equals(Object o) { if (o == null || getClass() != o.getClass()) { return false; } CompositeValue that = (CompositeValue) o; // We are not using Comparables.equal here since an externally // canonicalized composite value is expected here, otherwise we can't // guarantee hashCode is working properly. return Arrays.equals(components, that.components); }
Source:
public void addAllInternal(CanonicalizingHashSet<E> set) { // elements are already canonicalized map.putAll(set.map); }

Target:
void addAllInternal(CanonicalizingHashSet<E> set) { // elements are already canonicalized map.putAll(set.map); }
Source:
public int getActivePartitionCount() { // todo allocating a new Address each time ?? InetSocketAddress thisAddress = hazelcastInstance.getCluster().getLocalMember().getSocketAddress(MEMBER); return managedObject.getMemberPartitionsIfAssigned(new Address(thisAddress)).size(); }

Target:
public int getActivePartitionCount() { // todo allocating a new Address each time ?? InetSocketAddress thisAddress = hazelcastInstance.getCluster().getLocalMember().getSocketAddress(); return managedObject.getMemberPartitionsIfAssigned(new Address(thisAddress)).size(); }
Source:
public MapEvictionPolicy getMapEvictionPolicy() { if (mapEvictionPolicy != null) { return mapEvictionPolicy; } if (evictionPolicy == null) { return null; } return findMatchingMapEvictionPolicy(evictionPolicy); }

Target:
public MapEvictionPolicy getMapEvictionPolicy() { return mapEvictionPolicy; }
Source:
public ClientReliableTopicConfig setName(String name) { this.name = name; return this; }

Target:
public void setName(String name) { this.name = name; }
Source:
public String getDownloadId() { String downloadId = "source"; InputStream is = null; try { is = getClass().getClassLoader().getResourceAsStream("hazelcast-download.properties"); if (is != null) { final Properties properties = new Properties(); properties.load(is); downloadId = properties.getProperty("hazelcastDownloadId"); } } catch (IOException ignored) { ignore(ignored); } finally { closeResource(is); } return downloadId; }

Target:
private String getDownloadId() { String downloadId = "source"; InputStream is = null; try { is = getClass().getClassLoader().getResourceAsStream("hazelcast-download.properties"); if (is != null) { final Properties properties = new Properties(); properties.load(is); downloadId = properties.getProperty("hazelcastDownloadId"); } } catch (IOException ignored) { ignore(ignored); } finally { closeResource(is); } return downloadId; }
Source:
public void observerMethodNotOverridingNotifyMethodTreatedAsDefinitionError() { deployer.deploy(CONFIGURATOR); }

Target:
public void observerMethodNotOverridingNotifyMethodTreatedAsDefinitionError() { }
Source:
private void createServer(Module module, boolean queryParamsAsFormParams) throws Exception { Injector injector = bootstrapTest() .withModules( new ApplicationNameModule("test-application"), new TestingNodeModule(), explicitJaxrsModule(), new JsonModule(), new ReportingModule(), new TestingHttpServerModule(), module) .setRequiredConfigurationProperty("jaxrs.query-params-as-form-params", String.valueOf(queryParamsAsFormParams)) .initialize(); lifeCycleManager = injector.getInstance(LifeCycleManager.class); server = injector.getInstance(TestingHttpServer.class); }

Target:
private void createServer(Module module, boolean queryParamsAsFormParams) throws Exception { Injector injector = bootstrapTest() .withModules( new TestingNodeModule(), explicitJaxrsModule(), new JsonModule(), new ReportingModule(), new TestingHttpServerModule(), module) .setRequiredConfigurationProperty("jaxrs.query-params-as-form-params", String.valueOf(queryParamsAsFormParams)) .initialize(); lifeCycleManager = injector.getInstance(LifeCycleManager.class); server = injector.getInstance(TestingHttpServer.class); }
Source:
public XmlUserList() { binder = new XmlBinder<User>(User.class); try { serializer = XmlBinder.class.getDeclaredMethod("serializeObjectToWriter", Object.class, XMLStreamWriter.class); deserializer = XmlBinder.class.getDeclaredMethod("deserializeToValue", Element.class, Class.class); } catch (NoSuchMethodException e) { throw new RuntimeException("Cannot create object.", e); } serializer.setAccessible(true); deserializer.setAccessible(true); }

Target:
public XmlUserList() { binder = new XmlBinder<User>(User.class); }
Source:
protected BigIntegerExtension() { super(BigInteger.class); }

Target:
public BigIntegerExtension() { super(BigInteger.class); }
Source:
public void run() { if (comparator == null) { Arrays.sort(array); } else { Arrays.sort(array, comparator); } }

Target:
public void run() { Arrays.sort(array, comparator); }
Source:
public void format(StringBuilder buffer, String format, Object... args) throws FormatterException { position = 0; nextFormat(buffer, format, args); }

Target:
public void format(StringBuilder buffer, String format, Object... args) throws FormatterException { nextFormat(buffer, 0, format, args); }
Source:
public void close() { try { bufferedReader.close(); } catch (Exception e) { } out.flush(); out.close(); }

Target:
public void close() { // bufferedReader // if fileInput then is already closed // else no need to close cin out.flush(); out.close(); }
Source:
public synchronized String format(String format, Object... args) throws FormatterException { StringBuilder buffer = new StringBuilder(); format(buffer, format, args); return buffer.toString(); }

Target:
public String format(String format, Object... args) throws FormatterException { StringBuilder buffer = new StringBuilder(); format(buffer, format, args); return buffer.toString(); }
Source:
public void format(StringBuilder buffer, Object o, String pattern) { Formatter formatter = new Formatter(); buffer.append(formatter.format("%" + pattern + "d", o)); }

Target:
public void format(StringBuilder buffer, Object o, String pattern) { Formatter formatter = new Formatter(); buffer.append(formatter.format("%" + pattern, o)); }
Source:
private void close() { try { reader.close(); } catch (Exception e) { // corrupted input stream. So bad. } }

Target:
public void close() { try { reader.close(); } catch (Exception e) { // corrupted input stream. So bad. } }
Source:
public void add(String string) { if (persnicketiness == Persnicketiness.ALL) { count++; return; } if (persnicketiness == Persnicketiness.UNIQUE_ANYCASE) { string = string.toLowerCase(); } Integer res = map.get(string); if (res == null) { map.put(string, 1); } else { map.put(string, res + 1); } }

Target:
public void add(String string) { if (persnicketiness == Persnicketiness.ALL) { count++; return; } Integer res = map.get(string); if (res == null) { map.put(string, 1); } else { map.put(string, res + 1); } }
Source:
public static boolean isNumber(String s) { if (s.length() != 0) { if (Character.isDigit(s.charAt(0))) { return true; } } return false; }

Target:
public static boolean isNumber(String s) { return ((s.length() > 0) && (Character.isDigit(s.charAt(0)))); }
Source:
public static Boolean getMessage(SocketChannel sc, ByteBuffer message, Map<String, SocketChannel> clients) { try { int count = sc.read(message); if (count == -1) { // проверка на случай экстренного выхода клиента closeClient(clients, sc); return true; } } catch (Exception e) { printErrorAndExit("Bad geting message!" + e.getMessage()); } return false; }

Target:
public static boolean getMessage(SocketChannel sc, ByteBuffer message, Map<String, SocketChannel> clients) { try { int count = sc.read(message); if (count == -1) { // проверка на случай экстренного выхода клиента closeClient(clients, sc); return true; } } catch (Exception e) { printErrorAndExit("Bad geting message!" + e.getMessage()); } return false; }
Source:
private static boolean checkRpn(String[] parsedInput) { int countOfDigits = 0; int countOfOperands = 0; for (String s : parsedInput) { if (s.equals("+") || s.equals("-") || s.equals("/") || s.equals("*")) { ++countOfOperands; } else { ++countOfDigits; } } if ((countOfDigits - countOfOperands) == 1) { return true; } else { return false; } }

Target:
private static boolean checkRpn(String[] parsedInput) { int countOfDigits = 0; int countOfOperands = 0; for (String s : parsedInput) { if (s.equals("+") || s.equals("-") || s.equals("/") || s.equals("*")) { ++countOfOperands; } else { ++countOfDigits; } } return ((countOfDigits - countOfOperands) == 1); }
Source:
static void interactiveRegime() throws Exception{ while(true) { System.out.print("$ "); BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); String command = reader.readLine(); try { recognizeCommand(command); } catch (Exception e) { System.err.print(e.getMessage()); System.exit(1); } } }

Target:
static void interactiveRegime() throws Exception{ while(true) { System.out.print("$ "); BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); String command = reader.readLine(); try { recognizeCommand(command); } catch (Exception e) { System.err.println(e.getMessage()); } } }
Source:
private boolean allowedToEvict() { boolean allowed = evictionStrategy.allowedToEvict(expectedRegistrySize, eurekaRegistry.size()) >= 0; moveHealthTo(allowed ? Status.UP : Status.DOWN); return allowed; }

Target:
private boolean allowedToEvict() { boolean allowed = evictionStrategy.allowedToEvict(expectedRegistrySize, eurekaRegistry.size()) >= 0; // TODO We decided that self preservation should not trigger component DOWN transition. Health check from PreservableEurekaRegistry might be not needed // moveHealthTo(allowed ? Status.UP : Status.DOWN); return allowed; }
Source:
public void shutdown() { cancelScheduledTasks(); // If APPINFO was registered if (instanceInfo != null && shouldRegister(instanceInfo)) { instanceInfo.setStatus(InstanceStatus.DOWN); unregister(); } DiscoveryManager.getInstance().setDiscoveryClient(null); DiscoveryManager.getInstance().setEurekaClientConfig(null); }

Target:
public void shutdown() { cancelScheduledTasks(); // If APPINFO was registered if (instanceInfo != null && shouldRegister(instanceInfo)) { instanceInfo.setStatus(InstanceStatus.DOWN); unregister(); } }
Source:
protected Object doExecute() throws Exception { checkNotNull(template, "You must choose a template for the image you are trying to create."); Provisionr service = getService(); final Pool pool = createPoolOfOne(service); final String processInstanceId = service.startPoolManagementProcess("j-" + UUID.randomUUID().toString(), pool); return String.format("Pool management process started (id: %s)", processInstanceId); }

Target:
protected Object doExecute() throws Exception { Provisionr service = getService(); final Pool pool = createPoolOfOne(service); // TODO: create service.startCachingProcess(uuid, pool) in the Provisionr class return null; }
Source:
protected List<Instance> collectInstancesFromReservations(List<Reservation> reservation) { /* Make a copy as an ArrayList to force lazy collection evaluation */ List<List<Instance>> allInstances = Lists.newArrayList(Lists.transform(reservation, new Function<Reservation, List<Instance>>() { @Override public List<Instance> apply(Reservation reservation) { return reservation.getInstances(); } })); return Lists.newArrayList(Iterables.concat(allInstances)); }

Target:
protected List<Instance> collectInstancesFromReservations(List<Reservation> reservation) { /* Make a copy as an ArrayList to force lazy collection evaluation */ List<List<Instance>> allInstances = Lists.transform(reservation, new Function<Reservation, List<Instance>>() { @Override public List<Instance> apply(Reservation reservation) { return reservation.getInstances(); } }); return Lists.newArrayList(Iterables.concat(allInstances)); }
Source:
static void deleteByName(CloudStackClient cloudStackClient, String securityGroupName) { try { SecurityGroup securityGroup = getByName(cloudStackClient, securityGroupName); LOG.info("Deleting SecurityGroup {}", securityGroup.getName()); cloudStackClient.getSecurityGroupClient().deleteSecurityGroup(securityGroup.getId()); } catch (NoSuchElementException e) { LOG.debug("Exception retrieving SecurityGroup (most likely it does not yet exist){}: {}", securityGroupName, e); } }

Target:
static void deleteByName(CloudStackClient cloudStackClient, String securityGroupName) { try { SecurityGroup securityGroup = getByName(cloudStackClient, securityGroupName); LOG.info("Deleting SecurityGroup {}", securityGroup.getName()); cloudStackClient.getSecurityGroupClient().deleteSecurityGroup(securityGroup.getId()); } catch (NoSuchElementException e) { LOG.warn("Exception retrieving SecurityGroup (most likely it does not yet exist){}: {}", securityGroupName, e); } }
Source:
public static WebArchive createDeployment() { return Deployments.getBasicWebArchive() .addClass(HttpServletRequestHolderServlet.class) .addClass(TogglzFilterServlet.class) // we don't need to bootstrap Togglz here as we only test the request holder .setWebXML(Packaging.webAppDescriptor() .contextParam("org.togglz.FEATURE_MANAGER_PROVIDED", "true") .filter(TogglzFilter.class, "/*") .filter(TogglzFilter.class, "/*") .exportAsAsset()); }

Target:
public static WebArchive createDeployment() { return Deployments.getBasicWebArchive() .addClass(HttpServletRequestHolderServlet.class) // we don't need to bootstrap Togglz here as we only test the request holder .setWebXML(Packaging.webAppDescriptor() .contextParam("org.togglz.FEATURE_MANAGER_PROVIDED", "true") // the Togglz filter is added twice to test if it fails when called multiple times for the same request .filter(TogglzFilter.class, "/*") .filter(TogglzFilter.class, "/*") .exportAsAsset()); }
Source:
public void resetState(boolean postOptimization) { super.resetState(postOptimization); // clear closure variables set on inline function calls.forEach(call -> { if (!postOptimization) { call.getFunction().setClosureVariables(null); } }); calls.clear(); function.resetState(postOptimization); }

Target:
public void resetState(boolean postOptimization) { super.resetState(postOptimization); // clear closure variables set on inline function if (!postOptimization) { calls.forEach(call -> call.getFunction().setClosureVariables(null)); } calls.clear(); function.resetState(postOptimization); }
Source:
public int compareTo(Duration other) { if (count == 0 && other.count == 0) { return 0; } // this is negative, other is non-negative if (count < 0 && other.count >= 0) { return -1; } // this is non-negative, other is negative if (count >= 0 && other.count < 0) { return 1; } if (unit == other.unit) { return Long.compare(count, other.count); } return Long.compare(toNanoseconds(), other.toNanoseconds()); }

Target:
public int compareTo(Duration other) { if (unit == other.unit) { return Long.compare(count, other.count); } return Long.compare(toNanoseconds(), other.toNanoseconds()); }
Source:
private int atEnd(int res) { // Only run the post LRA actions if both the LRA and participant are in an end state // check the participant first since it will have been removed from one of the lists if (!isFinished() || !lra.isFinished()) { if (afterURI != null) { return TwoPhaseOutcome.HEURISTIC_HAZARD; } return res; } // run post LRA actions if (afterURI == null || afterLRARequest(afterURI, lra, lra.getLRAStatus().name())) { afterURI = null; // the post LRA actions succeeded so remove the participant from the intentions list otherwise retry return TwoPhaseOutcome.FINISH_OK; } return TwoPhaseOutcome.HEURISTIC_HAZARD; }

Target:
private int atEnd(int res) { // Only run the post LRA actions if both the LRA and participant are in an end state // check the participant first since it will have been removed from one of the lists if (!isFinished() || !lra.isFinished()) { if (afterURI != null) { return TwoPhaseOutcome.HEURISTIC_HAZARD; } return res; } // run post LRA actions if (afterURI == null || afterLRARequest(afterURI, lra.getLRAStatus().name())) { afterURI = null; // the post LRA actions succeeded so remove the participant from the intentions list otherwise retry return TwoPhaseOutcome.FINISH_OK; } return TwoPhaseOutcome.HEURISTIC_HAZARD; }
Source:
public int cancel () { if (parent() != null) parent().removeChildAction(this); // beforeCompletion(); int outcome; synchronized (_cancelLock) { // https://issues.jboss.org/browse/JBTM-2643 if (TxStats.enabled() && running()) TxStats.getInstance().incrementApplicationRollbacks(); outcome = super.Abort(); } if (outcome == ActionStatus.ABORTED) { afterCompletion(outcome); } return outcome; }

Target:
public int cancel () { if (parent() != null) parent().removeChildAction(this); // beforeCompletion(); int outcome = super.Abort(true); if (outcome == ActionStatus.ABORTED) { afterCompletion(outcome); } return outcome; }
Source:
public static String format(final String format, final String... args) { String[] split = format.split("%s"); final StringBuilder msg = new StringBuilder(); for (int pos = 0; pos < split.length - 1; pos += 1) { msg.append(split[pos]); msg.append(args[pos]); } msg.append(split[split.length - 1]); return msg.toString(); }

Target:
private static String format(final String format, final String... args) { String[] split = format.split("%s"); final StringBuilder msg = new StringBuilder(); for (int pos = 0; pos < split.length - 1; pos += 1) { msg.append(split[pos]); msg.append(args[pos]); } msg.append(split[split.length - 1]); return msg.toString(); }
Source:
protected void populateEntities(List<GuestId> entities, List<String> guestIds) { if (entities == null) { throw new IllegalArgumentException("the guestId model entity is null"); } if (guestIds == null) { throw new IllegalArgumentException("the list of guestId is null"); } for (String guestId : guestIds) { if (guestId == null) { continue; } GuestId guestIdEntity = new GuestId(); populateEntity(guestIdEntity, new GuestIdDTO().guestId(guestId)); entities.add(guestIdEntity); } }

Target:
protected void populateEntities(List<GuestId> entities, List<String> guestIds) { if (entities == null) { throw new IllegalArgumentException("the guestId model entity is null"); } if (guestIds == null) { throw new IllegalArgumentException("the list of guestId is null"); } for (String guestId : guestIds) { if (guestId == null) { continue; } entities.add(new GuestId(guestId)); } }
Source:
private CPMProducer getProducer() throws CPMException { if (this.cpmProducer == null || this.cpmProducer.isClosed()) { log.debug("Creating new CPM producer for job message dispatch..."); CPMSession session = this.getSession(); CPMProducerConfig config = session.createProducerConfig(); // TODO: Add any other job-system-specific producer configuration here this.cpmProducer = session.createProducer(config); log.debug("Created new CPM producer: {}", this.cpmProducer); } return this.cpmProducer; }

Target:
private synchronized CPMProducer getProducer() throws CPMException { if (this.cpmProducer == null || this.cpmProducer.isClosed()) { log.debug("Creating new CPM producer for job message dispatch..."); CPMSession session = this.getSession(); CPMProducerConfig config = session.createProducerConfig(); // TODO: Add any other job-system-specific producer configuration here this.cpmProducer = session.createProducer(config); log.debug("Created new CPM producer: {}", this.cpmProducer); } return this.cpmProducer; }
Source:
public InputStream getInputStream(boolean buffered) { if (this.inputStream != null) { return this.inputStream; } InputStream inputStream = requestContext.getInputStream(); return inputStream; }

Target:
public InputStream getInputStream(boolean buffered) { return requestContext.getInputStream(); }
Source:
public Collection<Consumer> findByUuids(Collection<String> uuids) { Set<Consumer> consumers = new HashSet<>(); for (List<String> block : this.partition(uuids)) { // Unfortunately, this needs to be a secure criteria due to the contexts in which this // is called. Criteria criteria = this.createSecureCriteria() .add(Restrictions.in("uuid", uuids)); consumers.addAll(criteria.list()); } return consumers; }

Target:
public Collection<Consumer> findByUuids(Collection<String> uuids) { Set<Consumer> consumers = new HashSet<>(); for (List<String> block : this.partition(uuids)) { // Unfortunately, this needs to be a secure criteria due to the contexts in which this // is called. Criteria criteria = this.createSecureCriteria() .add(Restrictions.in("uuid", block)); consumers.addAll(criteria.list()); } return consumers; }
Source:
public void sendEvents() { log.debug("Committing ActiveMQ transaction"); try { ClientSession session = this.getClientSession(); session.commit(); session.close(); } catch (Exception e) { // This would be pretty bad, but we always try not to let event errors // interfere with the operation of the overall application. log.error("Error committing ActiveMQ transaction", e); } }

Target:
public void sendEvents() { log.debug("Committing ActiveMQ transaction"); try (ClientSession session = this.getClientSession()) { session.commit(); } catch (Exception e) { // This would be pretty bad, but we always try not to let event errors // interfere with the operation of the overall application. log.error("Error committing ActiveMQ transaction", e); } }
Source:
protected Object getOutputValueForAccessor(String field, Object input) { // Since we're returning primitives for two methods, we need to convert them as necessary if (field != null && (field.equals("Result") || field.equals("Standalone")) && input == null) { return false; } return input; }

Target:
protected Object getOutputValueForAccessor(String field, Object input) { return input; }
Source:
public String getHref() { return this.id != null ? String.format("/pools/%s", this.id) : null; }

Target:
public String getHref() { return this.getId() != null ? String.format("/pools/%s", this.getId()) : null; }
Source:
public void deleteSubscription(@PathParam("subscription_id") String subscriptionId) { // Look up master pool by subscription Id Pool master = this.poolManager.getMasterPoolBySubscriptionId(subscriptionId); if (master == null) { throw new NotFoundException( i18n.tr("A subscription with the ID \"{0}\" could not be found.", subscriptionId)); } this.poolManager.deletePools(Collections.singletonList(master), null); }

Target:
public void deleteSubscription(@PathParam("subscription_id") String subscriptionId) { // Look up master pool by subscription Id Pool master = this.poolManager.getMasterPoolBySubscriptionId(subscriptionId); if (master == null) { throw new NotFoundException( i18n.tr("A subscription with the ID \"{0}\" could not be found.", subscriptionId)); } this.poolManager.deletePools(Collections.singletonList(master)); }
Source:
public boolean preProcess(BindContext context) { for (BindOperation operation : operations) { log.debug("Starting preprocess of {}", operation.getClass().getSimpleName()); if (operation.preProcess(context)) { log.debug("Finished preprocess of {}", operation.getClass().getSimpleName()); } else { log.error("Skipped chain in preprocess of operation {}", operation.getClass().getSimpleName()); return false; } } return true; }

Target:
private boolean preProcess(BindContext context) { for (BindOperation operation : operations) { log.debug("Starting preprocess of {}", operation.getClass().getSimpleName()); if (operation.preProcess(context)) { log.debug("Finished preprocess of {}", operation.getClass().getSimpleName()); } else { log.error("Skipped chain in preprocess of operation {}", operation.getClass().getSimpleName()); return false; } } return true; }
Source:
public void remove(@PathParam("owner_key") String ownerKey, @PathParam("content_id") String contentId) { Owner owner = this.getOwnerByKey(ownerKey); Content content = this.getContent(ownerKey, contentId); if (content.isLocked()) { throw new ForbiddenException(i18n.tr("content \"{1}\" is locked", content.getId())); } List<Product> affectedProducts = this.contentManager.removeContent(content, owner, true); }

Target:
public void remove(@PathParam("owner_key") String ownerKey, @PathParam("content_id") String contentId) { Owner owner = this.getOwnerByKey(ownerKey); Content content = this.getContent(ownerKey, contentId); if (content.isLocked()) { throw new ForbiddenException(i18n.tr("content \"{1}\" is locked", content.getId())); } this.contentManager.removeContent(content, owner, true); }
Source:
public void tearDown(Run<?, ?> build, FilePath workspace, Launcher launcher, TaskListener listener) throws IOException, InterruptedException { // null result means success so far. If no logs are found, it's probably because it was simply skipped if (build.getResult() == null) { SonarUtils.addBuildInfoTo(build, installation.getName(), true); } else { SonarUtils.addBuildInfoTo(build, installation.getName(), false); } }

Target:
public void tearDown(Run<?, ?> build, FilePath workspace, Launcher launcher, TaskListener listener) throws IOException, InterruptedException { // null result means success so far. If no logs are found, it's probably because it was simply skipped SonarUtils.addBuildInfoTo(build, installation.getName(), build.getResult() == null); }
Source:
public void writeToFile(final File destination) { InputStream input = null; final OutputStream output; try { input = getDataSource().getInputStream(); output = new FileOutputStream(destination); StreamUtil.copy(input, output); } catch (final IOException ioex) { throw new MailException(ioex); } finally { StreamUtil.close(input); StreamUtil.close(output); } }

Target:
public void writeToFile(final File destination) { InputStream input = null; OutputStream output = null; try { input = getDataSource().getInputStream(); output = new FileOutputStream(destination); StreamUtil.copy(input, output); } catch (final IOException ioex) { throw new MailException(ioex); } finally { StreamUtil.close(input); StreamUtil.close(output); } }
Source:
private static int zzUnpackAction() { int result = new int[184]; int offset = 0; zzUnpackAction(ZZ_ACTION_PACKED_0, offset, result); return result; }

Target:
private static int zzUnpackAction() { int result = new int[184]; int offset = 0; offset = zzUnpackAction(ZZ_ACTION_PACKED_0, offset, result); return result; }
Source:
private Boolean addTermAndAncestors(Term t, Observations o) { try { int id = this.boqa.getTermIndex(t); o.observations[id] = true; this.boqa.activateAncestors(id, o.observations); } catch (Exception e) { this.logger.warn("Unable to find the boqa index of [{}].", t); return false; } return true; }

Target:
private boolean addTermAndAncestors(Term t, Observations o) { try { int id = this.boqa.getTermIndex(t); o.observations[id] = true; this.boqa.activateAncestors(id, o.observations); } catch (Exception e) { this.logger.warn("Unable to find the boqa index of [{}].", t); return false; } return true; }
Source:
public SpiTransaction createQueryTransaction(Object tenantId) { SpiTransaction t = transactionManager.createQueryTransaction(tenantId); try { transactionScopeManager.set(t); } catch (PersistenceException existingTransactionError) { t.end(); throw existingTransactionError; } return t; }

Target:
public SpiTransaction createQueryTransaction(Object tenantId) { SpiTransaction t = transactionManager.createQueryTransaction(tenantId); // try { // transactionScopeManager.set(t); // } catch (PersistenceException existingTransactionError) { // t.end(); // throw existingTransactionError; // } return t; }
Source:
Class<?> forName(String name) throws ClassNotFoundException { if (preferredLoader != null) { // only use the explicitly set classLoader return classForName(name, preferredLoader); } try { // try the context loader first return classForName(name, contextLoader); } catch (ClassNotFoundException e) { if (JHelper.objectSameReference(callerLoader, contextLoader)) { throw e; } else { // fallback to the caller classLoader return classForName(name, callerLoader); } } }

Target:
Class<?> forName(String name) throws ClassNotFoundException { if (preferredLoader != null) { // only use the explicitly set classLoader return classForName(name, preferredLoader); } try { // try the context loader first return classForName(name, contextLoader); } catch (ClassNotFoundException e) { if (callerLoader == contextLoader) { throw e; } else { // fallback to the caller classLoader return classForName(name, callerLoader); } } }
Source:
private DbPlatformType getJsonType(DbType type, boolean withScale) { DbPlatformType dbType = get(type); if (JHelper.objectSameReference(dbType, JSON_CLOB_PLACEHOLDER)) { // if we have scale that implies this maps to varchar return withScale ? get(DbType.VARCHAR) : get(DbType.CLOB); } if (JHelper.objectSameReference(dbType, JSON_BLOB_PLACEHOLDER)) { return get(DbType.BLOB); } if (JHelper.objectSameReference(dbType, JSON_VARCHAR_PLACEHOLDER)) { return get(DbType.VARCHAR); } // Postgres has specific type return get(type); }

Target:
private DbPlatformType getJsonType(DbType type, boolean withScale) { DbPlatformType dbType = get(type); if (dbType == JSON_CLOB_PLACEHOLDER) { // if we have scale that implies this maps to varchar return withScale ? get(DbType.VARCHAR) : get(DbType.CLOB); } if (dbType == JSON_BLOB_PLACEHOLDER) { return get(DbType.BLOB); } if (dbType == JSON_VARCHAR_PLACEHOLDER) { return get(DbType.VARCHAR); } // Postgres has specific type return get(type); }
Source:
private AuthService authService() { if (null == authService) { throw new IllegalStateException("The auth-server endpoint is not configured."); } return authService; }

Target:
private AuthService authService() { if (authService == null) { throw new IllegalStateException("The auth-server endpoint is not configured."); } return authService; }
Source:
public StringAttribute(String value){ this.value = value; }

Target:
StringAttribute(String value){ this.value = value; }
Source:
protected Object doGetValue() { //System.out.println("NumberCellEditor doGetValue -->" + (data != null ? data : "null")); //BigDecimal value = NumberUtils.createBigDecimal(StringUtils.isNotEmpty(text.getText()) ? text.getText() : null ); //data = value; try { return convertToNumber(); } catch (NumberFormatException e) { e.printStackTrace(); } return null; }

Target:
protected Object doGetValue() { return convertToNumber(); }
Source:
public static boolean waitForCopy(CloudBlob blob) throws StorageException, InterruptedException { boolean continueLoop = true; CopyStatus status = CopyStatus.PENDING; while (continueLoop) { blob.downloadAttributes(); status = blob.getCopyState().getStatus(); continueLoop = status == CopyStatus.PENDING; // Sleep if retry is needed if (continueLoop) { Thread.sleep(500); } } return status == CopyStatus.SUCCESS; }

Target:
private static boolean waitForCopy(CloudBlob blob) throws StorageException, InterruptedException { boolean continueLoop = true; CopyStatus status = CopyStatus.PENDING; while (continueLoop) { blob.downloadAttributes(); status = blob.getCopyState().getStatus(); continueLoop = status == CopyStatus.PENDING; // Sleep if retry is needed if (continueLoop) { Thread.sleep(500); } } return status == CopyStatus.SUCCESS; }
Source:
protected String tryResourceLookup(Resource resource) { try { // added in Java EE 6 / Java SE 7 Method lookup = Resource.class.getDeclaredMethod("lookup"); return (String) lookup.invoke(resource); } catch (NoSuchMethodException e) { return ""; } catch (IllegalAccessException e) { return ""; } catch (InvocationTargetException e) { return ""; } }

Target:
protected String tryResourceLookup(Resource resource) { try { // added in Java EE 6 / Java SE 7 Method lookup = Resource.class.getDeclaredMethod("lookup"); return (String) lookup.invoke(resource); } catch (Exception e) { return ""; } }
Source:
public void should_replace_classpath_in_arquillian_xml() throws Exception { final String xml = desc.get().exportAsString(); System.out.println(xml); AssertXPath.assertXPath(xml, "/arquillian/container/@qualifier", VALUE_EL_OVERRIDE); final URL resource = Thread.currentThread().getContextClassLoader().getResource("arquillian_sysprop.xml"); assertXPath(xml, "/arquillian/container/configuration/property", String.format("-Djavax.net.ssl.trustStore=%s", resource.toString())); }

Target:
public void should_replace_classpath_in_arquillian_xml() throws Exception { // when final String xml = desc.get().exportAsString(); // then AssertXPath.assertXPath(xml, "/arquillian/container/@qualifier", VALUE_EL_OVERRIDE); final URL resource = Thread.currentThread().getContextClassLoader().getResource("arquillian_sysprop.xml"); assertXPath(xml, "/arquillian/container/configuration/property", String.format("-Djavax.net.ssl.trustStore=%s", resource.toString())); }
Source:
protected void shutdown(TestRunnerAdaptor adaptor) { State.runnerFinished(); try { if (State.isLastRunner()) { try { if (adaptor != null) { adaptor.afterSuite(); adaptor.shutdown(); } } finally { State.clean(); } } setAdaptor(null); } catch (Exception e) { throw new RuntimeException("Could not run @AfterSuite", e); } }

Target:
void shutdown(TestRunnerAdaptor adaptor) { State.runnerFinished(); try { if (State.isLastRunner()) { try { if (adaptor != null) { adaptor.afterSuite(); adaptor.shutdown(); } } finally { State.clean(); } } setAdaptor(null); } catch (Exception e) { throw new RuntimeException("Could not run @AfterSuite", e); } }
Source:
public String getX() { return x; }

Target:
String getX() { return x; }
Source:
public String getCurve() { return curve; }

Target:
String getCurve() { return curve; }
Source:
public void reassignColors(){ userColors.clear(); for(User u: connectedUsers){ u.setColor(userColors.getNextAvailableColor()); } }

Target:
private void reassignColors(){ userColors.clear(); for(User u: connectedUsers){ u.setColor(userColors.getNextAvailableColor()); } }
Source:
public List<SongMetadata> getLibrary() { synchronized(metadataMutex) { //sorts the list before returning it - for now, //order is simply alphabetical by artist, album, then song. ArrayList<SongMetadata> music = new ArrayList<SongMetadata>(metadataList); Collections.sort(music); //unmodifiable copy, for safety return Collections.unmodifiableList(music); } }

Target:
public List<SongMetadata> getLibrary() { synchronized(metadataMutex) { //unmodifiable copy, for safety return Collections.unmodifiableList(new ArrayList<SongMetadata>(metadataList)); } }
Source:
public IBinder onBind(Intent intent) { this.audioPlayer = new SingleFileAudioPlayer( new OnCompletionListener(){ @Override public void onCompletion(MediaPlayer mp) { new BroadcastIntent(SingleFileAudioPlayer.ACTION_SONG_FINISHED).send(PlaylistService.this); } }); this.mPlaylist = new Playlist(); // TODO: kick off a thread to feed the monster that is the audio service registerReceivers(); return new PlaylistServiceBinder(); }

Target:
public IBinder onBind(Intent intent) { this.audioPlayer = new SingleFileAudioPlayer(this); this.mPlaylist = new Playlist(); // TODO: kick off a thread to feed the monster that is the audio service registerReceivers(); return new PlaylistServiceBinder(); }
Source:
protected void onDestroy() { super.onDestroy(); //Make sure to destroy services when the application closes Toaster.iToast(this, "Destroying MusicLibrary Service"); Intent intent = new Intent(this, MusicLibraryService.class); stopService(intent); }

Target:
protected void onDestroy() { super.onDestroy(); //Make sure to destroy services when the application closes Intent intent = new Intent(this, MusicLibraryService.class); stopService(intent); }
Source:
public void testBasicRoundTrip() { byte[] serialized = serialize(kryo, UnicodeBlock.UNIFIED_CANADIAN_ABORIGINAL_SYLLABICS); try { assertSame(deserialize(kryo, serialized, UnicodeBlock.class), UnicodeBlock.UNIFIED_CANADIAN_ABORIGINAL_SYLLABICS); } catch (NullPointerException e) { // Temporary debugging code e.printStackTrace(); throw e; } }

Target:
public void testBasicRoundTrip() { byte[] serialized = serialize(kryo, UnicodeBlock.UNIFIED_CANADIAN_ABORIGINAL_SYLLABICS); assertSame(deserialize(kryo, serialized, UnicodeBlock.class), UnicodeBlock.UNIFIED_CANADIAN_ABORIGINAL_SYLLABICS); }
Source:
public static Set<ArtifactVersion> ensureDefaultAndPreviousVersionAvailable(final Set<ArtifactVersion> versions) { // add default version final ArtifactVersion defaultVersion = parseVersion(NewSwitchYardProjectWizard.DEFAULT_RUNTIME_VERSION); if (!versions.contains(defaultVersion)) { versions.add(defaultVersion); } // add previous version as well final ArtifactVersion previousVersion = parseVersion(NewSwitchYardProjectWizard.PREVIOUS_RUNTIME_VERSION); if (!versions.contains(previousVersion)) { versions.add(previousVersion); } return versions; }

Target:
public static Set<ArtifactVersion> ensureDefaultAndPreviousVersionAvailable(final Set<ArtifactVersion> versions) { // add default version final ArtifactVersion defaultVersion = parseVersion(NewSwitchYardProjectWizard.DEFAULT_RUNTIME_VERSION); versions.add(defaultVersion); // add previous version as well final ArtifactVersion previousVersion = parseVersion(NewSwitchYardProjectWizard.PREVIOUS_RUNTIME_VERSION); versions.add(previousVersion); return versions; }
Source:
private void refreshProject(IProgressMonitor monitor) throws CoreException { // update the project so we ensure a Project->Clean is done so the // MANIFEST.MF is built and we don't run into trouble deploying the // project on a Fuse server. if (_projectMetatData.getNewProjectHandle() != null) { _projectMetatData.getNewProjectHandle().refreshLocal(IProject.DEPTH_INFINITE, monitor); // also, update the maven project so we start in a deployable state // with a valid MANIFEST.MF built as part of the build process. Job updateJob = new UpdateMavenProjectJob(new IProject[] {_projectMetatData.getNewProjectHandle() }); updateJob.schedule(); } }

Target:
private void refreshProject(IProgressMonitor monitor) throws CoreException { // update the project so we ensure a Project->Clean is done so the // MANIFEST.MF is built and we don't run into trouble deploying the // project on a Fuse server. IProject project = _projectMetatData.getNewProjectHandle(); if (project != null) { // update the maven project so we start in a deployable state // with a valid MANIFEST.MF built as part of the build process. Job updateJob = new UpdateMavenProjectJob(new IProject[] {project}); updateJob.schedule(); } }
Source:
public void setUpdatableParameters(String cardId, String cardHash, String planId){ this.planId = planId; if(!Strings.isNullOrEmpty(cardId)){ this.cardHash = cardId; }else if(!Strings.isNullOrEmpty(cardHash)){ this.cardHash = cardHash; } }

Target:
public void setUpdatableParameters(String cardId, String cardHash, String planId){ this.planId = planId; this.cardId = cardId; this.cardHash = cardHash; }
Source:
public void deleteAnticipation(BulkAnticipation anticipation) throws PagarMeException{ validateId(); String path = String.format("/%s/%s/%s/%s", getClassName(), getId(), anticipation.getClassName(), anticipation.getId()); final PagarMeRequest request = new PagarMeRequest(HttpMethod.DELETE, path); request.execute(); }

Target:
public void deleteAnticipation(BulkAnticipation anticipation) throws PagarMeException{ String path = String.format("/%s/%s/%s/%s", getClassName(), getId(), anticipation.getClassName(), anticipation.getId()); final PagarMeRequest request = new PagarMeRequest(HttpMethod.DELETE, path); request.execute(); }
Source:
public String getTransactionId() { return transactionId; }

Target:
public Integer getTransactionId() { return transactionId; }
Source:
public Collection<Payable> findCollection(final Integer totalPerPage, Integer page, final Map<String, Object> filters) throws PagarMeException { String path = String.format("/%s", getClassName()); return _findCollection(path, totalPerPage, page, filters); }

Target:
public Collection<Payable> findCollection(final Integer totalPerPage, Integer page, final Map<String, Object> filters) throws PagarMeException { String path = String.format("/%s", getClassName()); return findCollection(path, totalPerPage, page, filters); }
Source:
private ItemGroup getItemGroup(Run<?, ?> build) { if (build instanceof AbstractBuild) { return ((AbstractBuild) build).getProject().getRootProject().getParent(); } else { // TODO: hmmm ??? return build.getParent().getParent(); } }

Target:
private ItemGroup getItemGroup(Run<?, ?> build) { return getRootProject(build.getParent()).getParent(); }
Source:
private Parser(Module module) throws IOException { // TODO: remove hack once the frontend is cleaner; also remove the IOException once the hack is cleared if (module.name().endsWith(RuleGrammarGenerator.RULE_CELLS)) { org.kframework.definition.Definition definitionWithBuiltins = Definition.from("require \"domians.k\"", "K"); this.parseInModule = new RuleGrammarGenerator(definitionWithBuiltins, true).getCombinedGrammar(module); } else { this.parseInModule = new ParseInModule(module); } }

Target:
private Parser(Module module) { // TODO: remove hack once the frontend is cleaner; also remove the IOException once the hack is cleared if (module.name().endsWith(RuleGrammarGenerator.RULE_CELLS)) { org.kframework.definition.Definition definitionWithBuiltins = Definition.from("require \"domians.k\"", "K"); this.parseInModule = new RuleGrammarGenerator(definitionWithBuiltins, true).getCombinedGrammar(module); } else { this.parseInModule = new ParseInModule(module); } }
Source:
public Sort sort() { // TODO(AndreiS): track the original sort from the grammar return KSorts.MAP; }

Target:
public Sort sort() { // TODO(AndreiS): track the original sort from the grammar return Sort.MAP; }
Source:
public JavaSymbolicKRun(Context context) throws KRunExecutionException { /* context is unused for directory paths; the actual context is de-serialized */ /* load the definition from a binary file */ definition = (Definition) BinaryLoader.load( new File(context.kompiled, JavaSymbolicBackend.DEFINITION_FILENAME).toString()); if (definition == null) { throw new KRunExecutionException("cannot load definition"); } /* initialize the builtin function table */ builtins = new BuiltinFunction(definition); this.context = definition.context(); this.context.kompiled = context.kompiled; this.context.globalOptions = context.globalOptions; transformer = new KILtoBackendJavaKILTransformer(this.context); }

Target:
public JavaSymbolicKRun(Context context) throws KRunExecutionException { /* context is unused for directory paths; the actual context is de-serialized */ /* load the definition from a binary file */ definition = (Definition) BinaryLoader.load( new File(context.kompiled, JavaSymbolicBackend.DEFINITION_FILENAME).toString()); if (definition == null) { throw new KRunExecutionException("cannot load definition"); } this.context = definition.context(); this.context.kompiled = context.kompiled; this.context.globalOptions = context.globalOptions; transformer = new KILtoBackendJavaKILTransformer(this.context); }
Source:
public int hashCode() { if (upToDateHash) { cachedHashCode = cons != null ? cons.hashCode() : 0; cachedHashCode = 31 * cachedHashCode + production.hashCode(); for (Term t : contents) cachedHashCode = 31 * cachedHashCode + t.hashCode(); upToDateHash = true; } return cachedHashCode; }

Target:
public int hashCode() { if (!upToDateHash) { cachedHashCode = cons != null ? cons.hashCode() : 0; cachedHashCode = 31 * cachedHashCode + production.hashCode(); for (Term t : contents) cachedHashCode = 31 * cachedHashCode + t.hashCode(); upToDateHash = true; } return cachedHashCode; }