auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public static Field saveField(Field oldField) throws DotHibernateException { if (oldField.getFieldType().equals("host or folder") || oldField.getFieldType().equals("line_divider") || oldField.getFieldType().equals("tab_divider") || oldField.getFieldType().equals("categories_tab") || oldField.getFieldType().equals("permissions_tab") || oldField.getFieldType().equals( "relationships_tab") || oldField.getFieldType().equals("category") || oldField.getFieldType().equals("tag") ) { oldField.setFieldContentlet(DataTypes.SYSTEM.toString()); } if(oldField.getFieldType().equals(Field.FieldType.HOST_OR_FOLDER.toString()) || oldField.getFieldType().equals(Field.FieldType.TAG.toString())){ oldField.setIndexed(true); } com.dotcms.contenttype.model.field.Field field = new LegacyFieldTransformer(oldField).from(); try { return new LegacyFieldTransformer( APILocator.getContentTypeFieldAPI().save(field, APILocator.systemUser()) ).asOldField(); } catch (DotDataException | DotSecurityException e) { throw new DotHibernateException(e.getMessage(),e); } }

Target:
public static Field saveField(Field oldField) throws DotHibernateException { if (oldField.getFieldType().equals("host or folder") || oldField.getFieldType().equals("line_divider") || oldField.getFieldType().equals("tab_divider") || oldField.getFieldType().equals("categories_tab") || oldField.getFieldType().equals("permissions_tab") || oldField.getFieldType().equals( "relationships_tab") || oldField.getFieldType().equals("category") || oldField.getFieldType().equals("tag") ) { oldField.setFieldContentlet(DataTypes.SYSTEM.toString()); } if(Field.FieldType.HOST_OR_FOLDER.toString().equals(oldField.getFieldType()) || Field.FieldType.TAG.toString().equals(oldField.getFieldType())){ oldField.setIndexed(true); } com.dotcms.contenttype.model.field.Field field = new LegacyFieldTransformer(oldField).from(); try { return new LegacyFieldTransformer( APILocator.getContentTypeFieldAPI().save(field, APILocator.systemUser()) ).asOldField(); } catch (DotDataException | DotSecurityException e) { throw new DotHibernateException(e.getMessage(),e); } }
Source:
public synchronized boolean append(TxnHeader hdr, Record txn) throws IOException { if (hdr != null) { if (hdr.getZxid() <= lastZxidSeen) { LOG.warn("Current zxid " + hdr.getZxid() + " is <= " + lastZxidSeen + " for " + hdr.getType()); } else { lastZxidSeen = hdr.getZxid(); } if (logStream==null) { if(LOG.isInfoEnabled()){ LOG.info("Creating new log file: log." + Long.toHexString(hdr.getZxid())); } logFileWrite = new File(logDir, ("log." + Long.toHexString(hdr.getZxid()))); fos = new FileOutputStream(logFileWrite); logStream=new BufferedOutputStream(fos); oa = BinaryOutputArchive.getArchive(logStream); FileHeader fhdr = new FileHeader(TXNLOG_MAGIC,VERSION, dbId); fhdr.serialize(oa, "fileheader"); logStream.flush(); currentSize = fos.getChannel().position(); streamsToFlush.add(fos); } padFile(fos); byte[] buf = Util.marshallTxnEntry(hdr, txn); if (buf == null || buf.length == 0) { throw new IOException("Faulty serialization for header " + "and txn"); } Checksum crc = makeChecksumAlgorithm(); crc.update(buf, 0, buf.length); oa.writeLong(crc.getValue(), "txnEntryCRC"); Util.writeTxnBytes(oa, buf); return true; } return false; }

Target:
public synchronized boolean append(TxnHeader hdr, Record txn) throws IOException { if (hdr == null) { return false; } if (hdr.getZxid() <= lastZxidSeen) { LOG.warn("Current zxid " + hdr.getZxid() + " is <= " + lastZxidSeen + " for " + hdr.getType()); } else { lastZxidSeen = hdr.getZxid(); } if (logStream==null) { if(LOG.isInfoEnabled()){ LOG.info("Creating new log file: log." + Long.toHexString(hdr.getZxid())); } logFileWrite = new File(logDir, ("log." + Long.toHexString(hdr.getZxid()))); fos = new FileOutputStream(logFileWrite); logStream=new BufferedOutputStream(fos); oa = BinaryOutputArchive.getArchive(logStream); FileHeader fhdr = new FileHeader(TXNLOG_MAGIC,VERSION, dbId); fhdr.serialize(oa, "fileheader"); logStream.flush(); currentSize = fos.getChannel().position(); streamsToFlush.add(fos); } padFile(fos); byte[] buf = Util.marshallTxnEntry(hdr, txn); if (buf == null || buf.length == 0) { throw new IOException("Faulty serialization for header " + "and txn"); } Checksum crc = makeChecksumAlgorithm(); crc.update(buf, 0, buf.length); oa.writeLong(crc.getValue(), "txnEntryCRC"); Util.writeTxnBytes(oa, buf); return true; }
Source:
public void writeJSON(Patient patient, JSONObject json, Collection<String> selectedFieldNames) { if (selectedFieldNames != null && !selectedFieldNames.contains(UNAFFECTED)) { return; } PatientData<String> data = patient.getData(getName()); if (data == null) { return; } JSONObject container = json.getJSONObject(getName()); if (container == null || container.isNullObject()) { json.put(getName(), new JSONObject()); container = json.getJSONObject(getName()); } container.put(data.getName(), data.getValue()); }

Target:
public void writeJSON(Patient patient, JSONObject json, Collection<String> selectedFieldNames) { if (selectedFieldNames != null && !selectedFieldNames.contains(FIELD_NAME)) { return; } PatientData<String> data = patient.getData(getName()); if (data == null) { return; } JSONObject container = json.getJSONObject(getName()); if (container == null || container.isNullObject()) { json.put(getName(), new JSONObject()); container = json.getJSONObject(getName()); } container.put(data.getName(), data.getValue()); }
Source:
public static String resolvePath(String path, String relativeTo) { if (new File(path).isAbsolute()) { return path; } else if (relativeTo != null) { return new File(new File(relativeTo), path).getAbsolutePath(); } else { return path; } }

Target:
public static String resolvePath(String path, String relativeTo) { if (path == null) { return null; } else if (new File(path).isAbsolute()) { return path; } else if (relativeTo != null) { return new File(new File(relativeTo), path).getAbsolutePath(); } else { return path; } }
Source:
public int delete(Uri uri, String selection, String[] selectionArgs) { return values.remove(uri) != null ? 1 : 0; }

Target:
public int delete(Uri uri, String selection, String[] selectionArgs) { return values.remove(uri) == null ? 0 : 1; }
Source:
protected void retrieve(@CheckForNull SCMSourceCriteria criteria, @NonNull final SCMHeadObserver observer, @CheckForNull SCMHeadEvent<?> event, @NonNull TaskListener listener) throws IOException, InterruptedException { SVNRepositoryView repository = null; try { listener.getLogger().println("Opening conection to " + remoteBase); SVNURL repoURL = SVNURL.parseURIEncoded(remoteBase); repository = openSession(repoURL); String repoPath = SubversionSCM.DescriptorImpl.getRelativePath(repoURL, repository.getRepository()); List<String> prefix = Collections.emptyList(); fetch(listener, repository, -1, repoPath, toPaths(splitCludes(includes)), prefix, prefix, toPaths(splitCludes(excludes)), criteria, observer ); } catch (SVNException e) { e.printStackTrace(listener.error("Could not communicate with Subversion server")); throw new IOException(e); } finally { closeSession(repository); } }

Target:
protected void retrieve(@CheckForNull SCMSourceCriteria criteria, @NonNull final SCMHeadObserver observer, @CheckForNull SCMHeadEvent<?> event, @NonNull TaskListener listener) throws IOException { SVNRepositoryView repository = null; try { listener.getLogger().println("Opening conection to " + remoteBase); SVNURL repoURL = SVNURL.parseURIEncoded(remoteBase); repository = openSession(repoURL); String repoPath = SubversionSCM.DescriptorImpl.getRelativePath(repoURL, repository.getRepository()); List<String> prefix = Collections.emptyList(); fetch(listener, repository, -1, repoPath, toPaths(splitCludes(includes)), prefix, prefix, toPaths(splitCludes(excludes)), criteria, observer ); } catch (SVNException e) { e.printStackTrace(listener.error("Could not communicate with Subversion server")); throw new IOException(e); } finally { closeSession(repository); } }
Source:
protected String getTaskAsString(String file) throws IOException { return IOUtils.toString(ITRealtimeIndexTaskTest.class.getResourceAsStream(file), "UTF-8"); }

Target:
protected String getTaskAsString(String file) throws IOException { final InputStream inputStream = ITRealtimeIndexTaskTest.class.getResourceAsStream(file); try { return IOUtils.toString(inputStream, "UTF-8"); } finally { IOUtils.closeQuietly(inputStream); } }
Source:
public int hashCode() { int result = 17; result = result * 31 + id.hashCode(); return result; }

Target:
public int hashCode() { return Objects.hashCode(id); }
Source:
public List<PluginViewModel> populatePluginViewModels() throws IllegalAccessException, ClassNotFoundException, InstantiationException { return pluginViewModelFactory.getAllPluginViewModels(); }

Target:
public List<PluginViewModel> populatePluginViewModels() throws ReflectiveOperationException { return pluginViewModelFactory.getAllPluginViewModels(); }
Source:
private boolean storeMetadata() { boolean result = true; try { fileService.writeMetadataFile(this.gdzfile, this.process); } catch (Exception e) { Helper.setFehlerMeldung("fehlerNichtSpeicherbar", e); logger.error(e.getMessage(), e); result = false; } return result; }

Target:
private boolean storeMetadata() { boolean result = true; try { fileService.writeMetadataFile(this.gdzfile, this.process); } catch (PreferencesException | WriteException | IOException | RuntimeException e) { Helper.setErrorMessage("fehlerNichtSpeicherbar", logger, e); result = false; } return result; }
Source:
public int getHeight() { return levelOffsets.length; }

Target:
int getHeight() { return levelOffsets.length; }
Source:
private void calcUQ(final File input, final File output, final File reference) throws IOException { final String[] args = new String[] { "INPUT="+input, "OUTPUT="+output, "REFERENCE_SEQUENCE="+reference }; CalculateUqTag calculateUqTag = new CalculateUqTag(); Assert.assertEquals(calculateUqTag.instanceMain(args), 0, "Fix did not succeed"); }

Target:
private void calcUQ(final File input, final File output, final File reference) throws IOException { final String[] args = { "INPUT=" + input, "OUTPUT=" + output, "REFERENCE_SEQUENCE=" + reference }; CalculateUqTag calculateUqTag = new CalculateUqTag(); Assert.assertEquals(calculateUqTag.instanceMain(args), 0, "Uq calc did not succeed"); }
Source:
public VerificationCodeHolder obtainVerificationCodeFromExternalUserInteraction(String title) { receiver = new CancellableServerReceiver(); String redirectUrl; try { redirectUrl = receiver.getRedirectUri(); } catch (IOException e) { logErrorAndDisplayDialog(title == null? "Google Login" : title, e); return null; } AuthorizationCodeRequestUrl authCodeRequestUrl = new AuthorizationCodeRequestUrl(GoogleOAuthConstants.AUTHORIZATION_SERVER_URL, clientInfo.getId()) .setRedirectUri(redirectUrl) .setScopes(OAuthScopeRegistry.getScopes()); BrowserUtil.browse(authCodeRequestUrl.build()); String verificationCode; try { verificationCode = receiver.waitForCode(); } catch (IOException e) { logErrorAndDisplayDialog(title == null? "Google Login" : title, e); return null; } return new VerificationCodeHolder(verificationCode, redirectUrl); }

Target:
public VerificationCodeHolder obtainVerificationCodeFromExternalUserInteraction(String title) { receiver = new CancellableServerReceiver(); String redirectUrl; try { redirectUrl = receiver.getRedirectUri(); } catch (IOException e) { logErrorAndDisplayDialog(title == null? "Google Login" : title, e); return null; } AuthorizationCodeRequestUrl authCodeRequestUrl = new AuthorizationCodeRequestUrl(GoogleOAuthConstants.AUTHORIZATION_SERVER_URL, clientInfo.getId()) .setRedirectUri(redirectUrl) .setScopes(OAuthScopeRegistry.getScopes()); BrowserUtil.browse(authCodeRequestUrl.build()); String verificationCode; try { verificationCode = receiver.waitForCode(); } catch (IOException e) { logErrorAndDisplayDialog(title == null? "Google Login" : title, e); return null; } finally { receiver = null; } return new VerificationCodeHolder(verificationCode, redirectUrl); }
Source:
public void can_fetch_message_count() throws Exception { setupFolderWith23Messages(); assertEquals(23, folder.getMessageCount()); }

Target:
public void can_fetch_message_count() throws Exception { int messageCount = 23; HashMap<String, String> headers = new HashMap<>(); headers.put("Brief", "t"); String messageCountXml = "<xml>MessageCountXml</xml>"; when(mockStore.getMessageCountXml("True")).thenReturn(messageCountXml); when(mockStore.processRequest("https://localhost/webDavStoreUrl/testFolder", "SEARCH", messageCountXml, headers)).thenReturn(mockDataSet); when(mockDataSet.getMessageCount()).thenReturn(messageCount); int result = folder.getMessageCount(); assertEquals(messageCount, result); }
Source:
public void testId() { ProductItemPrice price = ProductItemPrice.builder().id(1234).build(); ProductItem item = ProductItem.builder().id(1234).prices(price).build(); assertEquals("1234",imageId().apply(item)); }

Target:
public void testId() { ProductItemPrice price = ProductItemPrice.builder().id(1234).build(); ProductItem item = ProductItem.builder().id(5678).prices(price).build(); assertEquals(imageId().apply(item), "1234", "Expected the ID of the ProductItemPrice to be returned"); }
Source:
public String ping(@Sender EntityRef sender ) { class InnerClass{ public String runSystemCommand(String command) { String ret = ""; try { Process p = Runtime.getRuntime().exec(command); BufferedReader inputStream = new BufferedReader( new InputStreamReader(p.getInputStream())); String s = ""; while ((s = inputStream.readLine()) != null) { ret += s; } } catch (Exception e) { ret += e.toString(); } return ret; } public String uglyPing(String address){ return runSystemCommand("ping -n 1 " + address); } } Server server = networkSystem.getServer(); if(server == null){ return "You need to be in a server to ping \r\n and no , single player doesn't count"; } else { InnerClass TempObject = new InnerClass(); String temp = server.getRemoteAddress(); String[] arr = temp.split("-"); temp = TempObject.uglyPing(arr[1]); arr = temp.split(" "); String ret = ""; for(String s : arr){ if(s.contains("time=")){ String[] secondArr = s.split("="); if(secondArr.length == 2){ ret = secondArr[1]; } else { return "An error occured"; } } } return ret; } }

Target:
public String ping(@Sender EntityRef sender ) { try{ Server server = networkSystem.getServer(); if(server == null){ return "Please make sure you are connected to an online server (SinglePlayer doesn't count)"; } String temp = server.getRemoteAddress(); String[] arr = temp.split("-"); String address = arr[1]; int port = -1; try{ port = Integer.valueOf(arr[2]); } catch(Exception ex){ return "An error occured" + ex.toString(); } Instant starts = Instant.now(); Socket sock = new Socket(address, port); Instant ends = Instant.now(); sock.close(); String response = String.valueOf(Duration.between(starts, ends)); String millis = ""; char[] AllowedValues = {'0' , '1' ,'2' ,'3' ,'4' ,'5' ,'6' ,'7' ,'8' ,'9' ,'.'}; for (char c : response.toCharArray()){ for(char a : AllowedValues){ if(a == c){ millis += c; } } } float intMillis = Float.valueOf(millis); intMillis = intMillis * 1000; return String.valueOf(intMillis).substring(0 , String.valueOf(intMillis).length() - 2) + "ms"; } catch(Exception e){ return e.toString(); } }
Source:
public BigtableAsyncAdmin(CommonConnection asyncConnection) throws IOException { LOG.debug("Creating BigtableAsyncAdmin"); BigtableOptions options = asyncConnection.getOptions(); this.bigtableTableAdminClient = asyncConnection.getSession().getTableAdminClientWrapper(); this.disabledTables = asyncConnection.getDisabledTables(); this.bigtableInstanceName = options.getInstanceName(); this.tableAdapter2x = new TableAdapter2x(options); this.asyncConnection = asyncConnection; Configuration configuration = asyncConnection.getConfiguration(); String clusterId = configuration.get(BigtableOptionsFactory.BIGTABLE_SNAPSHOT_CLUSTER_ID_KEY, null); if (clusterId != null) { bigtableSnapshotClusterName = bigtableInstanceName.toClusterName(clusterId); } this.ttlSeconds = configuration.getInt(BigtableOptionsFactory.BIGTABLE_SNAPSHOT_DEFAULT_TTL_SECS_KEY, 86400); }

Target:
public BigtableAsyncAdmin(CommonConnection asyncConnection) throws IOException { LOG.debug("Creating BigtableAsyncAdmin"); BigtableOptions options = asyncConnection.getOptions(); this.bigtableTableAdminClient = asyncConnection.getSession().getTableAdminClientWrapper(); this.disabledTables = asyncConnection.getDisabledTables(); this.bigtableInstanceName = options.getInstanceName(); this.tableAdapter2x = new TableAdapter2x(options); this.asyncConnection = asyncConnection; Configuration configuration = asyncConnection.getConfiguration(); String clusterId = configuration.get(BigtableOptionsFactory.BIGTABLE_SNAPSHOT_CLUSTER_ID_KEY, null); if (clusterId != null) { bigtableSnapshotClusterName = bigtableInstanceName.toClusterName(clusterId); } this.ttlSeconds = configuration.getInt( BigtableOptionsFactory.BIGTABLE_SNAPSHOT_DEFAULT_TTL_SECS_KEY, BigtableOptionsFactory.BIGTABLE_SNAPSHOT_DEFAULT_TTL_SECS_VALUE); if (this.ttlSeconds <= 0) { throw new IllegalArgumentException( BigtableOptionsFactory.BIGTABLE_SNAPSHOT_DEFAULT_TTL_SECS_KEY + " must be > 0"); } }
Source:
public AuthProvider.Factory authProviderFactory() { final String authServer = System.getenv("AUTH_CRT_SERVER"); return new AuthProvider.Factory() { @Override public AuthProvider create(AuthProvider.Context context) { return new CrtAuthProvider(context, authServer); } }; }

Target:
public AuthProvider.Factory authProviderFactory() { final String authServer = firstNonNull(System.getenv("AUTH_CRT_SERVER_NAME"), "heliosmaster"); return new AuthProvider.Factory() { @Override public AuthProvider create(final AuthProvider.Context context) { final CrtAuthClient crtClient; try { crtClient = new CrtAuthClient(new AgentSigner(), authServer); } catch (CrtAuthException e) { throw Throwables.propagate(e); } return new CrtAuthProvider(context.dispatcher(), crtClient, context.user()); } }; }
Source:
private Score compareTitles(final String subjectTitle, final String suggestionTitle) { boolean matches; String subjTitle = normalize(normaliseForVs(subjectTitle)); String suggTitle = normalize(normaliseForVs(suggestionTitle)); if (appearsToBeWithApostrophe(subjectTitle)) { String regexp = normalizeRegularExpression(subjectTitle); matches = Pattern.matches(regexp, suggTitle); } else if (appearsToBeWithApostrophe(suggestionTitle)) { String regexp = normalizeRegularExpression(suggestionTitle); matches = Pattern.matches(regexp, subjTitle); } else { matches = matchWithoutDashes(subjTitle, suggTitle) || subjTitle.equals(suggTitle); } if (!matches) { return partialTitleScore(subjectTitle, suggestionTitle); } else { return Score.valueOf(2D); } }

Target:
private Score compareTitles(final String subjectTitle, final String suggestionTitle) { boolean matches; String subjTitle = normalize(subjectTitle); String suggTitle = normalize(suggestionTitle); if (appearsToBeWithApostrophe(subjectTitle)) { String regexp = normalizeRegularExpression(subjectTitle); matches = Pattern.matches(regexp, suggTitle); } else if (appearsToBeWithApostrophe(suggestionTitle)) { String regexp = normalizeRegularExpression(suggestionTitle); matches = Pattern.matches(regexp, subjTitle); } else { matches = matchWithoutDashes(subjTitle, suggTitle) || subjTitle.equals(suggTitle); } if (!matches) { return partialTitleScore(subjectTitle, suggestionTitle); } else { return Score.valueOf(2D); } }
Source:
public static synchronized UserIdent get(EntityPlayerMP player) { if (player == null) throw new IllegalArgumentException(); UserIdent ident = byUuid.get(player.getPersistentID()); if (ident == null) { ident = byUsername.get(player.getCommandSenderName().toLowerCase()); if (ident != null) { ident.uuid = player.getPersistentID(); byUuid.put(ident.uuid, ident); } else ident = new UserIdent(player); } else { String name = player.getCommandSenderName(); String newname = name + "_" + ident.uuid.hashCode(); if (name != null && !name.equals(ident.username) && !newname.equals(ident.username)) { if (byUsername.containsKey(name.toLowerCase())) { try { throw new Throwable(); } catch (Throwable t) { LoggingHandler.felog.fatal("Duplicate Player Error:\nA fake player, '" + name + "' is trying to change its name to one that already exists in the database.\nThis is not a forge essentials error! It is being caused by another mod.\nI have renamed this player to '" + newname + "' to prevent forge essentials from failing to start up, but this is a mod error cause you can only have one player name per uuid.\nI have printed the stack trace to give you some more details on what mod is misbehaving."); t.printStackTrace(); } name = newname; } byUsername.remove(ident.username != null ? ident.username.toLowerCase() : null); ident.username = name; byUsername.put(ident.username.toLowerCase(), ident); } } if (ident.player == null || ident.player.get() != player) ident.player = new WeakReference<EntityPlayer>(player); return ident; }

Target:
public static synchronized UserIdent get(EntityPlayerMP player) { if (player == null) throw new IllegalArgumentException(); UserIdent ident = byUuid.get(player.getPersistentID()); if (ident == null) { ident = byUsername.get(player.getCommandSenderName().toLowerCase()); if (ident != null) { ident.uuid = player.getPersistentID(); byUuid.put(ident.uuid, ident); } else ident = new UserIdent(player); } else { String name = player.getCommandSenderName(); String newname = name + "_" + ident.uuid.hashCode(); if (name != null && !name.equals(ident.username) && !newname.equals(ident.username)) { if (byUsername.containsKey(name.toLowerCase())) { new Exception().printStackTrace(); LoggingHandler.felog.fatal("Duplicate Player Error:\nA fake player, '" + name + "' is trying to change its name to one that already exists in the database.\nThis is not a forge essentials error! It is being caused by another mod.\nI have renamed this player to '" + newname + "' to prevent forge essentials from failing to start up, but this is a mod error cause you can only have one player name per uuid.\nI have printed the stack trace to give you some more details on what mod is misbehaving."); name = newname; } byUsername.remove(ident.username != null ? ident.username.toLowerCase() : null); ident.username = name; byUsername.put(ident.username.toLowerCase(), ident); } } if (ident.player == null || ident.player.get() != player) ident.player = new WeakReference<EntityPlayer>(player); return ident; }
Source:
public Object execute(final ExecutionEvent event) throws ExecutionException { final TaskData data = getTaskData(event); if (data == null) return null; Job job = new Job(MessageFormat.format( Messages.MergePullRequestHandler_MergeJob, data.getTaskId())) { @Override protected IStatus run(IProgressMonitor monitor) { PullRequestComposite prComp = PullRequestConnector .getPullRequest(data); if (prComp == null) return Status.CANCEL_STATUS; PullRequest request = prComp.getRequest(); Repository repo = PullRequestUtils.getRepository(request); if (repo == null) return Status.CANCEL_STATUS; String target = request.getBase().getRef(); String branchName = PullRequestUtils.getBranchName(request); try { Ref sourceRef = repo.findRef(branchName); if (sourceRef != null) { SubMonitor progress = SubMonitor.convert(monitor, 2); if (!PullRequestUtils.isCurrentBranch(target, repo)) { monitor.setTaskName(MessageFormat .format(Messages.MergePullRequestHandler_TaskCheckout, target)); BranchOperationUI.checkout(repo, target).run( progress.split(1)); } monitor.setTaskName(MessageFormat.format( Messages.MergePullRequestHandler_TaskMerge, branchName, target)); new MergeOperation(repo, branchName) .execute(progress.split(1)); executeCallback(event); } } catch (IOException e) { GitHubUi.logError(e); } catch (CoreException e) { GitHubUi.logError(e); } return Status.OK_STATUS; } }; schedule(job, event); return null; }

Target:
public Object execute(final ExecutionEvent event) throws ExecutionException { final TaskData data = getTaskData(event); if (data == null) return null; Job job = new Job(MessageFormat.format( Messages.MergePullRequestHandler_MergeJob, data.getTaskId())) { protected IStatus run(IProgressMonitor monitor) { PullRequestComposite prComp = PullRequestConnector .getPullRequest(data); if (prComp == null) return Status.CANCEL_STATUS; PullRequest request = prComp.getRequest(); Repository repo = PullRequestUtils.getRepository(request); if (repo == null) return Status.CANCEL_STATUS; String target = request.getBase().getRef(); String branchName = PullRequestUtils.getBranchName(request); try { Ref sourceRef = repo.findRef(branchName); if (sourceRef != null) { if (!PullRequestUtils.isCurrentBranch(target, repo)) { monitor.setTaskName(MessageFormat .format(Messages.MergePullRequestHandler_TaskCheckout, target)); BranchOperationUI.checkout(repo, target).run( new SubProgressMonitor(monitor, 1)); } monitor.setTaskName(MessageFormat.format( Messages.MergePullRequestHandler_TaskMerge, branchName, target)); new MergeOperation(repo, branchName) .execute(new SubProgressMonitor(monitor, 1)); executeCallback(event); } } catch (IOException e) { GitHubUi.logError(e); } catch (CoreException e) { GitHubUi.logError(e); } return Status.OK_STATUS; } }; schedule(job, event); return null; }
Source:
protected void configure() { Multibinder<ServicePlugin> plugins = Multibinder.newSetBinder(binder(), ServicePlugin.class); plugins.addBinding().toInstance(Plugins.of(new HttpBackend(port))); install(new ServletModule() { @Override protected void configureServlets() { bind(TestServlet.class).in(Singleton.class); serve("/test").with(TestServlet.class); } }); install(new SitebricksModule() { @Override protected void configureSitebricks() { at("/testservice").serve(ExampleService.class); at("/r/controllers").serve(ApControllerService.class); at("/r/aps").serve(AccessPointService.class); at("/r/operator").serve(OperatorService.class); } }); }

Target:
protected void configure() { Multibinder<ServicePlugin> plugins = Multibinder.newSetBinder(binder(), ServicePlugin.class); plugins.addBinding().toInstance(Plugins.of(new HttpBackend(port))); install(new ServletModule() { @Override protected void configureServlets() { bind(TestServlet.class).in(Singleton.class); serve("/test").with(TestServlet.class); } }); install(new SitebricksModule() { @Override protected void configureSitebricks() { at("/testservice").serve(ExampleService.class); at("/r/controllers").serve(ApControllerService.class); at("/r/aps").serve(AccessPointService.class); at("/r/operators").serve(OperatorService.class); } }); }
Source:
public Mono<DownloadAsyncResponse> download(BlobRange range, BlobAccessConditions accessConditions, boolean rangeGetContentMD5) { range = range == null ? new BlobRange(0) : range; Boolean getMD5 = rangeGetContentMD5 ? rangeGetContentMD5 : null; accessConditions = accessConditions == null ? new BlobAccessConditions() : accessConditions; HTTPGetterInfo info = new HTTPGetterInfo() .offset(range.offset()) .count(range.count()) .eTag(accessConditions.modifiedAccessConditions().ifMatch()); return postProcessResponse(this.azureBlobStorage.blobs().downloadWithRestResponseAsync( null, null, null, null, null, range.toHeaderValue(), getMD5, null, null, null, null, accessConditions.leaseAccessConditions(), accessConditions.modifiedAccessConditions(), Context.NONE)) .map(response -> { info.eTag(response.deserializedHeaders().eTag()); return new DownloadAsyncResponse(response, info, newInfo -> this.download(new BlobRange(newInfo.offset(), newInfo.count()), new BlobAccessConditions().modifiedAccessConditions( new ModifiedAccessConditions().ifMatch(info.eTag())), false)); }); }

Target:
public Mono<DownloadAsyncResponse> download(BlobRange range, BlobAccessConditions accessConditions, boolean rangeGetContentMD5) { range = range == null ? new BlobRange(0) : range; Boolean getMD5 = rangeGetContentMD5 ? rangeGetContentMD5 : null; accessConditions = accessConditions == null ? new BlobAccessConditions() : accessConditions; HTTPGetterInfo info = new HTTPGetterInfo() .offset(range.offset()) .count(range.count()) .eTag(accessConditions.modifiedAccessConditions().ifMatch()); return postProcessResponse(this.azureBlobStorage.blobs().downloadWithRestResponseAsync( null, null, snapshot, null, null, range.toHeaderValue(), getMD5, null, null, null, null, accessConditions.leaseAccessConditions(), accessConditions.modifiedAccessConditions(), Context.NONE)) .map(response -> { info.eTag(response.deserializedHeaders().eTag()); return new DownloadAsyncResponse(response, info, newInfo -> this.download(new BlobRange(newInfo.offset(), newInfo.count()), new BlobAccessConditions().modifiedAccessConditions( new ModifiedAccessConditions().ifMatch(info.eTag())), false)); }); }
Source:
public Entity createEntityNaturally(EntityType type, Vector3d position) throws IllegalArgumentException, IllegalStateException { checkRange(position.getX(), position.getY(), position.getZ()); return this.extent.createEntityNaturally(type, position); }

Target:
public Entity createEntityNaturally(EntityType type, Vector3d position) throws IllegalArgumentException, IllegalStateException { checkNotNull(position, "The position cannot be null!"); return this.extent.createEntityNaturally(type, position); }
Source:
public static byte[] serialize(Object obj) { ObjectOutputStream ous = null; ByteArrayOutputStream baos=null; try { baos = new ByteArrayOutputStream(); if(useJBoss){ ous=new JBossObjectOutputStream(baos); } else { ous=new ObjectOutputStream(baos); } ous.writeObject(obj); return baos.toByteArray(); } catch (Exception e) { throw new RuntimeException("Error during " + obj + " serialization", e); } finally { if (ous!=null){ try { ous.close(); } catch (IOException e) { log.warn("Exception during closing OutputStream: ",e); } } else { if(baos!=null){ try { baos.close(); } catch (IOException e) { log.warn("Exception during closing OutputStream: ",e); } } } } }

Target:
public static byte[] serialize(Object obj) { ObjectOutputStream ous = null; ByteArrayOutputStream baos=null; try { baos = new ByteArrayOutputStream(); if(useJBoss){ ous=new JBossObjectOutputStream(baos); } else { ous=new ObjectOutputStream(baos); } ous.writeObject(obj); return baos.toByteArray(); } catch (Exception e) { throw new RuntimeException("Error during " + obj + " serialization", e); } finally { Closeables.closeQuietly(ous); Closeables.closeQuietly(baos); } }
Source:
protected void doStart() throws Exception { super.doStart(); if (server == null) { LOG.debug("Starting the Thrift server"); initializeServer(); server.serve(); LOG.info("Thrift server started and listening on port: " + serverTransport.getPort()); } }

Target:
protected void doStart() throws Exception { super.doStart(); if (server == null) { LOG.debug("Starting the Thrift server"); initializeServer(); server.serve(); LOG.info("Thrift server started and listening on port: {}", serverTransport.getPort()); } }
Source:
public static void main(String[] args) throws IOException { Options options = new Options(); Option input = new Option("d", "deleteOld", false, "Whether delete old note file"); options.addOption(input); CommandLineParser parser = new DefaultParser(); CommandLine cmd = null; try { cmd = parser.parse(options, args); } catch (ParseException e) { System.out.println(e.getMessage()); System.exit(1); } ZeppelinConfiguration conf = ZeppelinConfiguration.create(); NotebookRepoSync notebookRepoSync = new NotebookRepoSync(conf); notebookRepoSync.convertNoteFiles(conf, cmd.hasOption("d")); }

Target:
public static void main(String[] args) throws IOException { Options options = new Options(); Option input = new Option("d", "deleteOld", false, "Whether delete old note file"); options.addOption(input); CommandLineParser parser = new DefaultParser(); CommandLine cmd = null; try { cmd = parser.parse(options, args); } catch (ParseException e) { System.out.println(e); System.exit(1); } ZeppelinConfiguration conf = ZeppelinConfiguration.create(); NotebookRepoSync notebookRepoSync = new NotebookRepoSync(conf); notebookRepoSync.convertNoteFiles(conf, cmd.hasOption("d")); }
Source:
public Pagination<CustomFieldModelDao> searchCustomFields(final String fieldName, final String fieldValue, final ObjectType objectType, final Long offset, final Long limit, final InternalTenantContext context) { return null; }

Target:
public Pagination<CustomFieldModelDao> searchCustomFields(final String fieldName, final String fieldValue, final ObjectType objectType, final Long offset, final Long limit, final InternalTenantContext context) { throw new UnsupportedOperationException(); }
Source:
public StreamWriter createWriter(String stream) throws NotFoundException, IOException { long ttl = getTTL(stream); LOG.debug("The Stream with id exists. Got the current Stream TTL value successfully.", stream, ttl); PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(); connectionManager.setMaxTotal(writerPoolSize); connectionManager.setDefaultMaxPerRoute(writerPoolSize); RestClient writerRestClient = new RestClient(config, connectionManager); return new RestStreamWriter(writerRestClient, writerPoolSize, stream); }

Target:
public StreamWriter createWriter(String stream) throws IOException { long ttl = getTTL(stream); LOG.debug("The Stream with id exists. Got the current Stream TTL value successfully.", stream, ttl); PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(); connectionManager.setMaxTotal(writerPoolSize); connectionManager.setDefaultMaxPerRoute(writerPoolSize); RestClient writerRestClient = new RestClient(config, connectionManager); return new RestStreamWriter(writerRestClient, writerPoolSize, stream); }
Source:
public synchronized void updateAcquiredBuffer(boolean metadata) { if (serializedCache == null) { return; } acquireBufferInternal(metadata); }

Target:
public synchronized void updateAcquiredBuffer(boolean metadata) { Preconditions.checkState(serializedCache != null, "updateAcquiredBuffer requires serialized form"); acquireBufferInternal(metadata); }
Source:
protected void doInitialize() throws Exception { if (this.taskScheduler == null) { ThreadPoolTaskScheduler threadPoolTaskScheduler = new ThreadPoolTaskScheduler(); threadPoolTaskScheduler.setThreadNamePrefix(getBeanName() + "-consumerMonitor-"); threadPoolTaskScheduler.setDaemon(true); threadPoolTaskScheduler.afterPropertiesSet(); this.taskScheduler = threadPoolTaskScheduler; } }

Target:
protected void doInitialize() throws Exception { if (this.taskScheduler == null) { ThreadPoolTaskScheduler threadPoolTaskScheduler = new ThreadPoolTaskScheduler(); threadPoolTaskScheduler.setThreadNamePrefix(getBeanName() + "-consumerMonitor-"); threadPoolTaskScheduler.afterPropertiesSet(); this.taskScheduler = threadPoolTaskScheduler; } }
Source:
public void populateDAG(DAG dag, Configuration conf) { JdbcPOJOInputOperator jdbcInputOperator = dag.addOperator("JdbcInput", new JdbcPOJOInputOperator()); JdbcStore store = new JdbcStore(); jdbcInputOperator.setStore(store); jdbcInputOperator.setFieldInfos(addFieldInfos()); dag.getMeta(jdbcInputOperator).getMeta(jdbcInputOperator.outputPort).getAttributes() .put(Context.PortContext.TUPLE_CLASS, TestPOJOEvent.class); FileLineOutputOperator fileOutput = dag.addOperator("FileOutputOperator", new FileLineOutputOperator()); dag.addStream("POJO's", jdbcInputOperator.outputPort, fileOutput.input).setLocality(Locality.CONTAINER_LOCAL); }

Target:
public void populateDAG(DAG dag, Configuration conf) { JdbcPOJOInputOperator jdbcInputOperator = dag.addOperator("JdbcInput", new JdbcPOJOInputOperator()); jdbcInputOperator.setFieldInfos(addFieldInfos()); JdbcStore store = new JdbcStore(); jdbcInputOperator.setStore(store); FileLineOutputOperator fileOutput = dag.addOperator("FileOutputOperator", new FileLineOutputOperator()); dag.addStream("POJO's", jdbcInputOperator.outputPort, fileOutput.input).setLocality(Locality.CONTAINER_LOCAL); }
Source:
public GsonBuilder(Gson gson) { this.excluder = gson.excluder; this.fieldNamingPolicy = gson.fieldNamingStrategy; this.instanceCreators.putAll(gson.instanceCreators); this.serializeNulls = gson.serializeNulls; this.complexMapKeySerialization = gson.complexMapKeySerialization; this.generateNonExecutableJson = gson.generateNonExecutableJson; this.escapeHtmlChars = gson.htmlSafe; this.prettyPrinting = gson.prettyPrinting; this.lenient = gson.lenient; this.serializeSpecialFloatingPointValues = gson.serializeSpecialFloatingPointValues; this.longSerializationPolicy = gson.longSerializationPolicy; this.datePattern = gson.datePattern; this.dateStyle = gson.dateStyle; this.timeStyle = gson.timeStyle; this.factories.addAll(gson.builderFactories); this.hierarchyFactories.addAll(gson.builderHierarchyFactories); }

Target:
GsonBuilder(Gson gson) { this.excluder = gson.excluder; this.fieldNamingPolicy = gson.fieldNamingStrategy; this.instanceCreators.putAll(gson.instanceCreators); this.serializeNulls = gson.serializeNulls; this.complexMapKeySerialization = gson.complexMapKeySerialization; this.generateNonExecutableJson = gson.generateNonExecutableJson; this.escapeHtmlChars = gson.htmlSafe; this.prettyPrinting = gson.prettyPrinting; this.lenient = gson.lenient; this.serializeSpecialFloatingPointValues = gson.serializeSpecialFloatingPointValues; this.longSerializationPolicy = gson.longSerializationPolicy; this.datePattern = gson.datePattern; this.dateStyle = gson.dateStyle; this.timeStyle = gson.timeStyle; this.factories.addAll(gson.builderFactories); this.hierarchyFactories.addAll(gson.builderHierarchyFactories); }
Source:
private static void updateChildrenFonts(CTabFolder folder, Font font) { for (CTabItem item : folder.getItems()) { Font itemFont = item.getFont(); if (itemFont == null || itemFont.isDisposed()) { item.setFont(font); } } }

Target:
private static void updateChildrenFonts(CTabFolder folder, Font font) { for (CTabItem item : folder.getItems()) { Font itemFont = item.getFont(); if (itemFont != null && !itemFont.equals(font)) { item.setFont(font); } } }
Source:
public void shouldInsertCreatedAndModifiedFields() { Person p = new Person("John", "Phiri"); p.setId(1); personDAO.insert(p); Person found = personDAO.get(1); assertThat(found.getCreated()).isNotNull(); assertThat(found.getModified()).isNotNull(); h2DatabaseRule.getJdbi().setTimingCollector((l, statementContext) -> { assertThat(statementContext.getBinding().findForName("now")).isPresent(); }); }

Target:
public void shouldInsertCreatedAndModifiedFields() { h2DatabaseRule.getJdbi().setTimingCollector((l, statementContext) -> { assertThat(statementContext.getBinding().findForName("now")).isPresent(); }); Person p = new Person("John", "Phiri"); p.setId(1); personDAO.insert(p); h2DatabaseRule.getJdbi().setTimingCollector(TimingCollector.NOP_TIMING_COLLECTOR); Person found = personDAO.get(1); assertThat(found.getCreated()).isNotNull(); assertThat(found.getModified()).isNotNull(); }
Source:
public UUID forceSnapshotSync(String clusterId) throws LogReplicationDiscoveryServiceException { if (localClusterDescriptor.getRole() == ClusterRole.STANDBY) { String errorStr = "The forceSnapshotSync command is not supported on standby cluster."; log.error(errorStr); throw new LogReplicationDiscoveryServiceException(errorStr); } log.info("Received the forceSnapshotSync command for standby cluster {}", clusterId); UUID forceSyncId = UUID.randomUUID(); ReplicationEventKey key = ReplicationEventKey.newBuilder().setKey(System.currentTimeMillis() + " "+ clusterId).build(); ReplicationEvent event = ReplicationEvent.newBuilder() .setClusterId(clusterId) .setEventId(forceSyncId.toString()) .build(); getLogReplicationMetadataManager().updateLogReplicationEventTable(key, event); return forceSyncId; }

Target:
public UUID forceSnapshotSync(String clusterId) throws LogReplicationDiscoveryServiceException { if (localClusterDescriptor.getRole() == ClusterRole.STANDBY) { String errorStr = "The forceSnapshotSync command is not supported on standby cluster."; log.error(errorStr); throw new LogReplicationDiscoveryServiceException(errorStr); } UUID forceSyncId = UUID.randomUUID(); log.info("Received the forceSnapshotSync command for standby cluster {}, forced sync id {}", clusterId, forceSyncId); ReplicationEventKey key = ReplicationEventKey.newBuilder().setKey(System.currentTimeMillis() + " "+ clusterId).build(); ReplicationEvent event = ReplicationEvent.newBuilder() .setClusterId(clusterId) .setEventId(forceSyncId.toString()) .setType(ReplicationEvent.ReplicationEventType.FORCE_SNAPSHOT_SYNC) .build(); getLogReplicationMetadataManager().updateLogReplicationEventTable(key, event); return forceSyncId; }
Source:
public void process(FContext ctx, FProtocol iprot, FProtocol oprot) throws TException { buyAlbum_args args = new buyAlbum_args(); try { args.read(iprot); } catch (TException e) { iprot.readMessageEnd(); synchronized (WRITE_LOCK) { e = writeApplicationException(ctx, oprot, TApplicationException.PROTOCOL_ERROR, "buyAlbum", e.getMessage()); } throw e; } iprot.readMessageEnd(); buyAlbum_result result = new buyAlbum_result(); try { result.success = handler.buyAlbum(ctx, args.ASIN, args.acct); result.setSuccessIsSet(true); } catch (PurchasingError error) { result.error = error; } catch (TApplicationException e) { oprot.writeResponseHeader(ctx); oprot.writeMessageBegin(new TMessage("buyAlbum", TMessageType.EXCEPTION, 0)); e.write(oprot); return; } catch (TException e) { synchronized (WRITE_LOCK) { e = writeApplicationException(ctx, oprot, TApplicationException.INTERNAL_ERROR, "buyAlbum", "Internal error processing buyAlbum: " + e.getMessage()); } throw e; } synchronized (WRITE_LOCK) { try { oprot.writeResponseHeader(ctx); oprot.writeMessageBegin(new TMessage("buyAlbum", TMessageType.REPLY, 0)); result.write(oprot); oprot.writeMessageEnd(); oprot.getTransport().flush(); } catch (TTransportException e) { if (e.getType() == FTransportExceptionType.RESPONSE_TOO_LARGE) { writeApplicationException(ctx, oprot, FApplicationExceptionType.RESPONSE_TOO_LARGE, "buyAlbum", "response too large: " + e.getMessage()); } else { throw e; } } } }

Target:
public void process(FContext ctx, FProtocol iprot, FProtocol oprot) throws TException { buyAlbum_args args = new buyAlbum_args(); try { args.read(iprot); } catch (TException e) { iprot.readMessageEnd(); synchronized (WRITE_LOCK) { e = writeApplicationException(ctx, oprot, FrugalTApplicationExceptionType.PROTOCOL_ERROR, "buyAlbum", e.getMessage()); } throw e; } iprot.readMessageEnd(); buyAlbum_result result = new buyAlbum_result(); try { result.success = handler.buyAlbum(ctx, args.ASIN, args.acct); result.setSuccessIsSet(true); } catch (PurchasingError error) { result.error = error; } catch (TApplicationException e) { oprot.writeResponseHeader(ctx); oprot.writeMessageBegin(new TMessage("buyAlbum", TMessageType.EXCEPTION, 0)); e.write(oprot); return; } catch (TException e) { synchronized (WRITE_LOCK) { e = writeApplicationException(ctx, oprot, FrugalTApplicationExceptionType.INTERNAL_ERROR, "buyAlbum", "Internal error processing buyAlbum: " + e.getMessage()); } throw e; } synchronized (WRITE_LOCK) { try { oprot.writeResponseHeader(ctx); oprot.writeMessageBegin(new TMessage("buyAlbum", TMessageType.REPLY, 0)); result.write(oprot); oprot.writeMessageEnd(); oprot.getTransport().flush(); } catch (TTransportException e) { if (e.getType() == FrugalTTransportExceptionType.RESPONSE_TOO_LARGE) { writeApplicationException(ctx, oprot, FrugalTApplicationExceptionType.RESPONSE_TOO_LARGE, "buyAlbum", "response too large: " + e.getMessage()); } else { throw e; } } } }
Source:
public List<String> events() { return events; }

Target:
public List<EventType> events() throws InvalidArgumentException { return EventType.fromStringList(events); }
Source:
public void clearAnswer() { clearAnswerWithoutValueChangeListener(); widgetValueChanged(); }

Target:
public void clearAnswer() { resetAnswerFields(); widgetValueChanged(); }
Source:
public Builder to(String name) { Assert.checkNotNullParam("to", name); this.name = name; return this; }

Target:
public Builder to(String name) { Assert.checkNotNullParam("name", name); this.name = name; return this; }
Source:
public void setUp() throws Exception{ classInstance = new urn_perun_user_facility_attribute_def_virt_defaultUnixGID(); session = mock(PerunSessionImpl.class, RETURNS_DEEP_STUBS); attrDef = session.getPerunBl().getAttributesManagerBl().getAttributeDefinition(session, AttributesManager.NS_USER_FACILITY_ATTR_VIRT + "defaultUnixGID"); dDefaultUnixGid = new Attribute(); gidNamespace = "test"; groupNameNamespace = "test"; prefferedUnixGroupName = new Attribute(); allowedResource = new ArrayList<>(); memberByUser = new ArrayList<>(); assignedGroupsToResource = new ArrayList<>(); groupMembers = new ArrayList<>(); basicDefaultGID = new Attribute(); facility = new Facility(1, "testFacility"); user = new User(1, "name", "surname", "middlename", "title", "title"); prefferedUnixGroupNameSelectedValueGID = new Attribute(attrDef); resource = new Resource(1, "testName", "desc", 1); member = new Member(1, 1); group = new Group("name", "desc"); allowedResource.add(resource); memberByUser.add(member); assignedGroupsToResource.add(group); groupMembers.add(member); resourceGroupName = "test1"; groupGroupName = "test2"; resourceUnixGID = 1; groupUnixGID = 2; }

Target:
public void setUp() throws Exception{ classInstance = new urn_perun_user_facility_attribute_def_virt_defaultUnixGID(); session = mock(PerunSessionImpl.class, RETURNS_DEEP_STUBS); attrDef = session.getPerunBl().getAttributesManagerBl().getAttributeDefinition(session, AttributesManager.NS_USER_FACILITY_ATTR_VIRT + "defaultUnixGID"); dDefaultUnixGid = new Attribute(); gidNamespace = "test1"; groupNameNamespace = "test2"; prefferedUnixGroupName = new Attribute(); allowedResource = new ArrayList<>(); memberByUser = new ArrayList<>(); assignedGroupsToResource = new ArrayList<>(); groupMembers = new ArrayList<>(); basicDefaultGID = new Attribute(); facility = new Facility(1, "testFacility"); user = new User(1, "name", "surname", "middlename", "title", "title"); prefferedUnixGroupNameSelectedValueGID = new Attribute(attrDef); resource = new Resource(1, "testName", "desc", 1); member = new Member(1, 1); group = new Group("name", "desc"); allowedResource.add(resource); memberByUser.add(member); assignedGroupsToResource.add(group); groupMembers.add(member); resourceGroupName = "test1"; groupGroupName = "test2"; resourceUnixGID = 1; groupUnixGID = 2; }
Source:
public static Boolean extractHook(IHopper dest) { TileEntity tileEntity = dest.getWorld().getTileEntity(new BlockPos(dest.getXPos(), dest.getYPos() + 1, dest.getZPos())); if (tileEntity == null || !tileEntity.hasCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY, EnumFacing.DOWN)) return null; IItemHandler handler = tileEntity.getCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY, EnumFacing.DOWN); for (int i = 0; i < handler.getSlots(); i++) { ItemStack extractItem = handler.extractItem(i, 1, true); if (extractItem != null) { for (int j = 0; j < dest.getSizeInventory(); j++) { ItemStack destStack = dest.getStackInSlot(j); if (destStack == null || destStack.stackSize < destStack.getMaxStackSize() && destStack.getMaxStackSize() < dest.getInventoryStackLimit() && ItemHandlerHelper.canItemStacksStack(extractItem, destStack)) { extractItem = handler.extractItem(i, 1, false); if (destStack == null) dest.setInventorySlotContents(j, extractItem); else { destStack.stackSize++; dest.setInventorySlotContents(j, destStack); } dest.markDirty(); return true; } } } } return false; }

Target:
public static Boolean extractHook(IHopper dest) { TileEntity tileEntity = dest.getWorld().getTileEntity(new BlockPos(dest.getXPos(), dest.getYPos() + 1, dest.getZPos())); if (tileEntity == null || !tileEntity.hasCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY, EnumFacing.DOWN)) return null; IItemHandler handler = tileEntity.getCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY, EnumFacing.DOWN); for (int i = 0; i < handler.getSlots(); i++) { ItemStack extractItem = handler.extractItem(i, 1, true); if (extractItem != null) { for (int j = 0; j < dest.getSizeInventory(); j++) { ItemStack destStack = dest.getStackInSlot(j); if (destStack == null || destStack.stackSize < destStack.getMaxStackSize() && destStack.stackSize < dest.getInventoryStackLimit() && ItemHandlerHelper.canItemStacksStack(extractItem, destStack)) { extractItem = handler.extractItem(i, 1, false); if (destStack == null) dest.setInventorySlotContents(j, extractItem); else { destStack.stackSize++; dest.setInventorySlotContents(j, destStack); } dest.markDirty(); return true; } } } } return false; }