auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public static void main(String[] args) throws IOException, NoSuchAlgorithmException, InvalidKeyException, XmlPullParserException { try { MinioClient minioClient = new MinioClient("<LINK_1>", "Q3AM3UQ867SPQQA43P2F", "zuf+tfteSlswRu7BJ86wekitnifILbZam1KYY3TG"); NotificationConfiguration notificationConfiguration = minioClient.getBucketNotification("my-bucketname"); List<TopicConfiguration> topicConfigurationList = notificationConfiguration.topicConfigurationList(); TopicConfiguration topicConfiguration = new TopicConfiguration(); topicConfiguration.setTopic("arn:aws:sns:us-west-2:444455556666:sns-topic-xyz"); List<String> eventList = new LinkedList<>(); eventList.add("s3:ObjectCreated:Put"); eventList.add("s3:ObjectCreated:Copy"); topicConfiguration.setEvents(eventList); notificationConfiguration.setTopicConfigurationList(topicConfigurationList); minioClient.setBucketNotification("my-bucketname", notificationConfiguration); System.out.println("Bucket notification is set successfully"); } catch (MinioException e) { System.out.println("Error occurred: " + e); } }

Target:
public static void main(String[] args) throws IOException, NoSuchAlgorithmException, InvalidKeyException, XmlPullParserException { try { MinioClient minioClient = new MinioClient("<LINK_1>", "Q3AM3UQ867SPQQA43P2F", "zuf+tfteSlswRu7BJ86wekitnifILbZam1KYY3TG"); NotificationConfiguration notificationConfiguration = minioClient.getBucketNotification("my-bucketname"); List<TopicConfiguration> topicConfigurationList = notificationConfiguration.topicConfigurationList(); TopicConfiguration topicConfiguration = new TopicConfiguration(); topicConfiguration.setTopic("arn:aws:sns:us-west-2:444455556666:sns-topic-xyz"); List<EventType> eventList = new LinkedList<>(); eventList.add(EventType.OBJECT_CREATED_PUT); eventList.add(EventType.OBJECT_CREATED_COPY); topicConfiguration.setEvents(eventList); Filter filter = new Filter(); filter.setPrefixRule("images"); filter.setSuffixRule("pg"); topicConfiguration.setFilter(filter); topicConfigurationList.add(topicConfiguration); notificationConfiguration.setTopicConfigurationList(topicConfigurationList); minioClient.setBucketNotification("my-bucketname", notificationConfiguration); System.out.println("Bucket notification is set successfully"); } catch (MinioException e) { System.out.println("Error occurred: " + e); } }
Source:
public void testValidation() { try { new JsonItemReaderBuilder<String>() .build(); fail("A json object reader is required."); } catch (IllegalArgumentException iae) { assertEquals("A json object reader is required.", iae.getMessage()); } try { new JsonItemReaderBuilder<String>() .jsonObjectReader(this.jsonObjectReader) .build(); fail("A resource is required."); } catch (IllegalArgumentException iae) { assertEquals("A resource is required.", iae.getMessage()); } try { new JsonItemReaderBuilder<String>() .jsonObjectReader(this.jsonObjectReader) .resource(this.resource) .saveState(true) .build(); fail("A name is required when saveState is set to true."); } catch (IllegalStateException iae) { assertEquals("A name is required when saveState is set to true.", iae.getMessage()); } }

Target:
public void testValidation() { try { new JsonItemReaderBuilder<String>() .build(); fail("A json object reader is required."); } catch (IllegalArgumentException iae) { assertEquals("A json object reader is required.", iae.getMessage()); } try { new JsonItemReaderBuilder<String>() .jsonObjectReader(this.jsonObjectReader) .build(); fail("A resource is required."); } catch (IllegalArgumentException iae) { assertEquals("A resource is required.", iae.getMessage()); } try { new JsonItemReaderBuilder<String>() .jsonObjectReader(this.jsonObjectReader) .resource(this.resource) .build(); fail("A name is required when saveState is set to true."); } catch (IllegalStateException iae) { assertEquals("A name is required when saveState is set to true.", iae.getMessage()); } }
Source:
public ParamertizedString(final String pattern) { final StringBuilder raw = new StringBuilder(); final List<Parameter> prs = new ArrayList<Parameter>(4); final List<Format> ops = new ArrayList<Format>(4); final List<Function> functions = new ArrayList<Function>(); int i = 0; while (i < pattern.length()) { final int b = pattern.indexOf("${", i); if (b < 0) { break; } final int e = pattern.indexOf("}", b + 2); if (e < 0) { break; } raw.append(pattern.substring(i, b)); ops.add(new Constant(pattern.substring(i, b))); String expr = pattern.substring(b + 2, e); String parameterName = ""; if (!expr.contains(".")) { parameterName = expr; } else { int firstDot = expr.indexOf('.'); parameterName = expr.substring(0, firstDot); String actionsStr = expr.substring(firstDot + 1); String[] actions = actionsStr.split("\\."); for (String action : actions) { Function function = FUNCTIONS.get(action); if (function == null) { function = NOOP; } functions.add(function); } } functions.add(NOOP); final Parameter p = new Parameter(parameterName, Collections.unmodifiableList(functions)); raw.append("{" + prs.size() + "}"); prs.add(p); ops.add(p); i = e + 1; } if (i < pattern.length()) { raw.append(pattern.substring(i)); ops.add(new Constant(pattern.substring(i))); } this.pattern = pattern; this.rawPattern = raw.toString(); this.patternOps = Collections.unmodifiableList(ops); this.parameters = Collections.unmodifiableList(prs); }

Target:
public ParamertizedString(final String pattern) { final StringBuilder raw = new StringBuilder(); final List<Parameter> prs = new ArrayList<Parameter>(4); final List<Format> ops = new ArrayList<Format>(4); final List<Function> functions = new ArrayList<Function>(); int i = 0; while (i < pattern.length()) { final int b = pattern.indexOf("${", i); if (b < 0) { break; } final int e = pattern.indexOf("}", b + 2); if (e < 0) { break; } raw.append(pattern.substring(i, b)); ops.add(new Constant(pattern.substring(i, b))); String expr = pattern.substring(b + 2, e); String parameterName = ""; if (!expr.contains(".")) { parameterName = expr; } else { int firstDot = expr.indexOf('.'); parameterName = expr.substring(0, firstDot); String actionsStr = expr.substring(firstDot + 1); String[] actions = actionsStr.split("\\."); for (String action : actions) { Function function = FUNCTIONS.get(action); if (function == null) { function = NOOP; } functions.add(function); } } final Parameter p = new Parameter(parameterName, Collections.unmodifiableList(functions)); raw.append("{" + prs.size() + "}"); prs.add(p); ops.add(p); i = e + 1; } if (i < pattern.length()) { raw.append(pattern.substring(i)); ops.add(new Constant(pattern.substring(i))); } this.pattern = pattern; this.rawPattern = raw.toString(); this.patternOps = Collections.unmodifiableList(ops); this.parameters = Collections.unmodifiableList(prs); }
Source:
public void execute() throws Exception { if (!ElasticsearchProcessMonitor.getWasElasticsearchStarted()) { String exceptionMsg = "Elasticsearch is not yet started, check back again later"; logger.info(exceptionMsg); return; } HealthBean healthBean = new HealthBean(); try { healthBean.esprocessdown = 0; if (!ElasticsearchProcessMonitor.isElasticsearchRunning()) { healthBean.esprocessdown = 1; } } catch (Exception e) { resetHealthStats(healthBean); logger.warn("failed to check if Elasticsearch process is running", e); } healthReporter.healthBean.set(healthBean); }

Target:
public void execute() throws Exception { if (!ElasticsearchProcessMonitor.getWasElasticsearchStarted()) { String exceptionMsg = "Elasticsearch is not yet started, check back again later"; logger.info(exceptionMsg); return; } HealthBean healthBean = new HealthBean(); try { healthBean.esprocessrunning = 0; if (!ElasticsearchProcessMonitor.isElasticsearchRunning()) { logger.info("Elasticsearch process is up & running"); healthBean.esprocessrunning = 1; } } catch (Exception e) { resetHealthStats(healthBean); logger.warn("failed to check if Elasticsearch process is running", e); } healthReporter.healthBean.set(healthBean); }
Source:
public void equalsAndHashCodeEqualTest() throws Exception { MatcherAssert.assertThat( psbyflag.equals( new PsByFlag( new PsByFlag.Pair( KEY, new PsFake(true) ) ) ), Matchers.is(true) ); }

Target:
public void equalsAndHashCodeEqualTest() throws Exception { EqualsVerifier.forClass(PsByFlag.class) .suppress(Warning.TRANSIENT_FIELDS) .verify(); }
Source:
public void testSingleLaunchStartupFullyDrawnMetric() throws Exception { String settingsLaunchCommand = String.format(LUANCH_APP_CMD_TEMPLATE, SETTINGS_PKG_NAME); HelperTestUtility.executeShellCommand(String.format(KEYEVENT_CMD_TEMPLATE, KEYCODE_WAKEUP)); SystemClock.sleep(HelperTestUtility.ACTION_DELAY); HelperTestUtility.executeShellCommand(String.format(KEYEVENT_CMD_TEMPLATE, KEYCODE_UNLOCK)); SystemClock.sleep(HelperTestUtility.ACTION_DELAY); assertTrue(mAppStartupHelper.startCollecting()); HelperTestUtility.executeShellCommand(settingsLaunchCommand); SystemClock.sleep(HelperTestUtility.ACTION_DELAY); boolean hasFullyDrawnKey = false; Map<String, StringBuilder> appLaunchMetrics = mAppStartupHelper.getMetrics(); for (String key : appLaunchMetrics.keySet()) { if (key.contains(FULLY_DRAWN_KEY_KEYWORD) && key.contains(SETTINGS_PKG_NAME)) { hasFullyDrawnKey = true; } } assertTrue(hasFullyDrawnKey); assertTrue(mAppStartupHelper.stopCollecting()); HelperTestUtility.executeShellCommand(String.format(KEYEVENT_CMD_TEMPLATE, KEYCODE_HOME)); SystemClock.sleep(HelperTestUtility.ACTION_DELAY); HelperTestUtility.clearApp(String.format(KILL_TEST_APP_CMD_TEMPLATE, SETTINGS_PKG_NAME)); SystemClock.sleep(HelperTestUtility.ACTION_DELAY); }

Target:
public void testSingleLaunchStartupFullyDrawnMetric() throws Exception { assertTrue(mAppStartupHelper.startCollecting()); HelperTestUtility.launchPackageViaAdb(SETTINGS_PKG_NAME); SystemClock.sleep(HelperTestUtility.ACTION_DELAY); boolean hasFullyDrawnKey = false; Map<String, StringBuilder> appLaunchMetrics = mAppStartupHelper.getMetrics(); for (String key : appLaunchMetrics.keySet()) { if (key.contains(FULLY_DRAWN_KEY_KEYWORD) && key.contains(SETTINGS_PKG_NAME)) { hasFullyDrawnKey = true; } } assertTrue(hasFullyDrawnKey); assertTrue(mAppStartupHelper.stopCollecting()); HelperTestUtility.sendKeyCode(KEYCODE_HOME); SystemClock.sleep(HelperTestUtility.ACTION_DELAY); HelperTestUtility.clearApp(String.format(KILL_TEST_APP_CMD_TEMPLATE, SETTINGS_PKG_NAME)); SystemClock.sleep(HelperTestUtility.ACTION_DELAY); }
Source:
private void newAppBar() { DWORD dwABM = new DWORD(); APPBARDATA ABData = new APPBARDATA.ByReference(); ABData.uCallbackMessage.setValue( WM_USER + 1); ABData.cbSize.setValue( ABData.size() ); dwABM.setValue(ShellAPI.ABM_NEW); UINT_PTR result = Shell32.INSTANCE.SHAppBarMessage( dwABM, ABData); assertNotNull(result ); }

Target:
private void newAppBar() { APPBARDATA data = new APPBARDATA.ByReference(); data.cbSize.setValue(data.size()); data.uCallbackMessage.setValue(WM_USER + 1); UINT_PTR result = Shell32.INSTANCE.SHAppBarMessage(new DWORD(ShellAPI.ABM_NEW), data); assertNotNull(result); }
Source:
public void resourceChanged(final IResourceChangeEvent event) { final Set<IMarker> added = new HashSet<>(); final Set<IMarker> removed = new HashSet<>(); boolean changed = false; for (final IMarkerDelta delta : event.findMarkerDeltas(IMarker.BOOKMARK, false)) { if (delta.getResource().equals(fFile)) { if (delta.getKind() == IResourceDelta.REMOVED) { removed.add(delta.getMarker()); } else if (delta.getKind() == IResourceDelta.ADDED) { added.add(delta.getMarker()); } changed = true; } } if (!changed) { return; } Display.getDefault().asyncExec(new Runnable() { @Override public void run() { if (!removed.isEmpty()) { fEventsTable.removeBookmark(Iterables.toArray(removed, IMarker.class)); } if (!added.isEmpty()) { fEventsTable.addBookmark(Iterables.toArray(added, IMarker.class)); } if (removed.isEmpty() && added.isEmpty()) { fEventsTable.getTable().refresh(); } } }); }

Target:
public void resourceChanged(final IResourceChangeEvent event) { final Set<IMarker> added = new HashSet<>(); final Set<IMarker> removed = new HashSet<>(); boolean deltaFound = false; for (final IMarkerDelta delta : event.findMarkerDeltas(IMarker.BOOKMARK, false)) { if (delta.getResource().equals(fFile)) { if (delta.getKind() == IResourceDelta.REMOVED) { removed.add(delta.getMarker()); } else if (delta.getKind() == IResourceDelta.ADDED) { added.add(delta.getMarker()); } deltaFound = true; } } if (!deltaFound) { return; } Display.getDefault().asyncExec(new Runnable() { @Override public void run() { if (removed.isEmpty() && added.isEmpty()) { fEventsTable.getTable().refresh(); } else { if (!removed.isEmpty()) { fEventsTable.removeBookmark(Iterables.toArray(removed, IMarker.class)); } if (!added.isEmpty()) { fEventsTable.addBookmark(Iterables.toArray(added, IMarker.class)); } } } }); }
Source:
public void searchForProcesses() throws Exception { desktopPage.searchInSearchField("process"); int numberOfResults = searchResultPage.getNumberOfResults(); assertEquals("There should be two processes found",2,numberOfResults); searchResultPage.searchInSearchField("Second"); Thread.sleep(2000); assertEquals("There should be two processes found",2,searchResultPage.getNumberOfResults()); searchResultPage.searchInSearchField("möhö"); Thread.sleep(2000); assertEquals("There should be no processes found",0,searchResultPage.getNumberOfResults()); }

Target:
public void searchForProcesses() throws Exception { desktopPage.searchInSearchField("process"); int numberOfResults = searchResultPage.getNumberOfResults(); assertEquals("There should be two processes found", 2, numberOfResults); searchResultPage.searchInSearchField("Second"); await("Wait for visible search results").atMost(20, TimeUnit.SECONDS).ignoreExceptions().untilAsserted( () -> assertEquals("There should be two processes found", 2, searchResultPage.getNumberOfResults())); searchResultPage.searchInSearchField("möhö"); await("Wait for visible search results").atMost(20, TimeUnit.SECONDS).ignoreExceptions().untilAsserted( () -> assertEquals("There should be no processes found", 0, searchResultPage.getNumberOfResults())); }
Source:
private void checkSubmodules() throws IOException { ObjectDatabase odb = db.getObjectDatabase(); if (objectChecker == null) { return; } for (GitmoduleEntry entry : objectChecker.getGitsubmodules()) { AnyObjectId blobId = entry.getBlobId(); ObjectLoader blob = odb.open(blobId, Constants.OBJ_BLOB); try { SubmoduleValidator.assertValidGitModulesFile( new String(blob.getBytes(), UTF_8)); } catch (LargeObjectException | SubmoduleValidationException e) { throw new IOException(e.getMessage(), e); } } }

Target:
private void checkSubmodules() throws IOException { ObjectDatabase odb = db.getObjectDatabase(); if (objectChecker == null) { return; } for (GitmoduleEntry entry : objectChecker.getGitsubmodules()) { AnyObjectId blobId = entry.getBlobId(); ObjectLoader blob = odb.open(blobId, Constants.OBJ_BLOB); try { SubmoduleValidator.assertValidGitModulesFile( new String(blob.getBytes(), UTF_8)); } catch (LargeObjectException | SubmoduleValidationException e) { throw new IOException(e); } } }
Source:
public Object invoke(MethodInvocation methodInvocation) throws Throwable { Object result; try { result = methodInvocation.proceed(); } catch (ValidationException e) { List<ErrorMessage> messages = Lists.newArrayList(); for (Error error : e.errors) { messages.add(new ErrorMessage(error.message)); } return Reply.with(new Errors(messages)).status(SC_BAD_REQUEST).as(Json.class); } catch (ClassCastException e) { return Reply.with(new Errors(Lists.newArrayList(new ErrorMessage(defaultInternalServerError)))).status(SC_BAD_REQUEST).as(Json.class); } catch (NotFoundException e) { return Reply.with(new Errors(Lists.newArrayList(new ErrorMessage(e.getMessage())))).status(SC_NOT_FOUND).as(Json.class); } catch (EmergencyNumberException e) { return Reply.with(new Errors(Lists.newArrayList(new ErrorMessage(e.getMessage())))).status(SC_BAD_REQUEST).as(Json.class); } catch (RuntimeException e) { logger.error("Exception stack trace", e); if(isNullOrEmpty(e.getMessage())) { return Reply.with(new Errors(Lists.newArrayList(new ErrorMessage(defaultInternalServerError)))).error().as(Json.class); } return Reply.with(new Errors(Lists.newArrayList(new ErrorMessage(e.getMessage())))).error().as(Json.class); } if (!(result instanceof Reply)) { throw new ProgrammerMistake("Wrong interceptor binding was performed. It seems that methods that are not returning" + " Reply objects are matched."); } return result; }

Target:
public Object invoke(MethodInvocation methodInvocation) throws Throwable { Object result; try { result = methodInvocation.proceed(); } catch (ValidationException e) { List<ErrorMessage> messages = Lists.newArrayList(); for (Error error : e.errors) { messages.add(new ErrorMessage(error.message)); } return Reply.with(new Errors(messages)).status(SC_BAD_REQUEST).as(Json.class); } catch (ClassCastException e) { return Reply.with(new Errors(Lists.newArrayList(new ErrorMessage(defaultInternalServerError)))).status(SC_BAD_REQUEST).as(Json.class); } catch (NotFoundException e) { return Reply.with(new Errors(Lists.newArrayList(new ErrorMessage(e.getMessage())))).status(SC_NOT_FOUND).as(Json.class); } catch (RuntimeException e) { logger.error("Exception stack trace", e); if(isNullOrEmpty(e.getMessage())) { return Reply.with(new Errors(Lists.newArrayList(new ErrorMessage(defaultInternalServerError)))).error().as(Json.class); } return Reply.with(new Errors(Lists.newArrayList(new ErrorMessage(e.getMessage())))).error().as(Json.class); } if (!(result instanceof Reply)) { throw new ProgrammerMistake("Wrong interceptor binding was performed. It seems that methods that are not returning" + " Reply objects are matched."); } return result; }
Source:
private ArrayList<NewConnectionSnippetParts> parseSnippet(String input) { ArrayList<NewConnectionSnippetParts> parts = new ArrayList<NewConnectionSnippetParts>(); String pattern = "\\$\\{([0-9]+):([^:=}]+)(=([^:}]+))?(:([^}]+))?\\}"; RegExp regExp = RegExp.compile(pattern, "g"); for (MatchResult matcher = regExp.exec(input); matcher != null; matcher = regExp.exec(input)) { if (matcher.getGroupCount() >= 2) { int order = 0; try { order = Integer.parseInt(matcher.getGroup(1)); } catch (NumberFormatException e) { } String key = matcher.getGroup(2); String value = matcher.getGroupCount() >= 4 ? matcher.getGroup(4) : null; String connStringField = matcher.getGroupCount() >= 6 ? matcher.getGroup(6) : null; if (value != null) { value = value.replaceAll("\\$colon\\$", ":"); value = value.replaceAll("\\$equal\\$", "="); } parts.add(new NewConnectionSnippetParts(order, key, value, connStringField)); } } Collections.sort(parts, new Comparator<NewConnectionSnippetParts>() { @Override public int compare(NewConnectionSnippetParts p1, NewConnectionSnippetParts p2) { return p1.getOrder() == p2.getOrder() ? 0 : p1.getOrder() < p2.getOrder() ? -1 : 1; } }); return parts; }

Target:
private ArrayList<NewConnectionSnippetParts> parseSnippet(String input) { ArrayList<NewConnectionSnippetParts> parts = new ArrayList<NewConnectionSnippetParts>(); RegExp regExp = RegExp.compile(pattern_, "g"); for (MatchResult matcher = regExp.exec(input); matcher != null; matcher = regExp.exec(input)) { if (matcher.getGroupCount() >= 2) { int order = 0; try { order = Integer.parseInt(matcher.getGroup(1)); } catch (NumberFormatException e) { } String key = matcher.getGroup(2); String value = matcher.getGroupCount() >= 4 ? matcher.getGroup(4) : null; String connStringField = matcher.getGroupCount() >= 6 ? matcher.getGroup(6) : null; if (value != null) { value = value.replaceAll("\\$colon\\$", ":"); value = value.replaceAll("\\$equal\\$", "="); } parts.add(new NewConnectionSnippetParts(order, key, value, connStringField)); } } Collections.sort(parts, new Comparator<NewConnectionSnippetParts>() { @Override public int compare(NewConnectionSnippetParts p1, NewConnectionSnippetParts p2) { return p1.getOrder() - p2.getOrder(); } }); return parts; }
Source:
public boolean checkTypesAndScope(Model model, Map scope) { boolean correct = true; for (int i = 0; i < terms.size(); ++i) { Object element = terms.get(i); if (element instanceof Term) { Term term = (Term) element; Term termInScope = term.getTermInScope(model, scope); if (termInScope == null) { correct = false; } else { terms.set(i, termInScope); } } else if (element instanceof ListSpec) { ListSpec listSpec = (ListSpec) element; if (listSpec.checkTypesAndScope(model, scope)) { terms.set(i, listSpec); } else { correct = false; } } else { throw new IllegalArgumentException( "don't know how to process set element of type " + terms.get(i).getClass().getName()); } } return correct; }

Target:
public boolean checkTypesAndScope(Model model, Map scope) { boolean correct = true; for (int i = 0; i < terms.size(); ++i) { Object element = terms.get(i); if (element instanceof Term) { Term term = (Term) element; if (term.getTermInScope(model, scope) == null) { correct = false; } } else if (element instanceof ListSpec) { ListSpec listSpec = (ListSpec) element; if (!listSpec.checkTypesAndScope(model, scope)) { correct = false; } } else { throw new IllegalArgumentException( "don't know how to process set element of type " + terms.get(i).getClass().getName()); } } return correct; }
Source:
public SquareContainer(Map<Direction, SquareContainer> neighbours, AbstractSquare square) { this.square = square; this.decorators = new HashMap<Property, AbstractSquareDecorator>(); if (!canHaveAsNeighbours(neighbours)) throw new IllegalArgumentException( "the specified neighbours could not be set as the neighbours for this square!"); this.neighbours = new HashMap<Direction, SquareContainer>(neighbours); for (Direction direction : neighbours.keySet()) neighbours.get(direction).neighbours.put(direction.getOppositeDirection(), this); }

Target:
public SquareContainer(Map<Direction, SquareContainer> neighbours, AbstractSquare square) { if (square == null) throw new IllegalArgumentException("the given square cannot be null"); if (!canHaveAsNeighbours(neighbours)) throw new IllegalArgumentException( "the specified neighbours could not be set as the neighbours for this square!"); this.square = square; this.decorators = new HashMap<Property, AbstractSquareDecorator>(); this.neighbours = new HashMap<Direction, SquareContainer>(neighbours); for (Direction direction : neighbours.keySet()) neighbours.get(direction).setNeighbourInDirection(direction.getOppositeDirection(), this); }
Source:
public void onApplicationEvent(RefreshRemoteApplicationEvent event) { log.info("Received remote refresh request."); if (serviceMatcher == null) { log.warn( "RefreshListener does not have a ServiceMatcher, refresh will not be performed. Consider" + "passing a ServiceMatcher in the constructor"); return; } if (serviceMatcher.isForSelf(event)) { Set<String> keys = this.contextRefresher.refresh(); log.info("Keys refreshed " + keys); } else { log.info("Refresh not performed, the event was targetting " + event.getDestinationService()); } }

Target:
public void onApplicationEvent(RefreshRemoteApplicationEvent event) { log.info("Received remote refresh request."); if (serviceMatcher == null) { log.warn( "RefreshListener does not have a ServiceMatcher, refresh may be performed even if " + "the event does not target this app. Consider passing a ServiceMatcher in " + "the constructor"); refresh(); } else if (serviceMatcher.isForSelf(event)) { refresh(); } else { log.info("Refresh not performed, the event was targetting " + event.getDestinationService()); } }
Source:
public String getObservedScript() { if (observeredScript == null) { if (failureInfos.size() == 0) { observeredScript = expectedScript; } else { StringBuilder builder = new StringBuilder(); processRegion(builder, scriptInfo, failureInfos); if (!failureInfos.isEmpty()) { throw new RuntimeException("Script failure detected but not located"); } observeredScript = builder.toString(); } } return observeredScript; }

Target:
public String getObservedScript() { if (observeredScript == null) { int numberOfFailures = failureInfos.size(); if (numberOfFailures == 0) { observeredScript = expectedScript; } else { StringBuilder builder = new StringBuilder(); processRegion(builder, scriptInfo, failureInfos); if (numberOfFailures <= failureInfos.size()) { throw new RuntimeException("Script failure detected but not located"); } observeredScript = builder.toString(); } } return observeredScript; }
Source:
public static CompositeActionTypeDTO map(final CompositeActionType actionType) { final CompositeActionTypeDTO actionTypeDto = new CompositeActionTypeDTO(); fillProperties(actionType, actionTypeDto); actionTypeDto.inputs = actionType.getInputs(); actionTypeDto.outputs = actionType.getOutputs(); actionTypeDto.children = ActionDTOMapper.map(actionType.getChildren()); return actionTypeDto; }

Target:
public static CompositeActionTypeDTO map(final CompositeActionType actionType) { final CompositeActionTypeDTO actionTypeDto = map(actionType, new CompositeActionTypeDTO()); actionTypeDto.children = ActionDTOMapper.map(actionType.getChildren()); return actionTypeDto; }
Source:
public void setTitle(@NonNull final String title) { mToolbarTitle = title.isEmpty() ? getString(R.string.wordpress_as_site_title_when_no_title) : title; if (mToolbar != null) { mToolbar.setTitle(mToolbarTitle); } }

Target:
public void setTitle(@NonNull final String title) { if (isAdded()) { mToolbarTitle = (title == null || title.isEmpty()) ? getString(R.string.wordpress) : title; if (mToolbar != null) { mToolbar.setTitle(mToolbarTitle); } } }
Source:
public final void setData(String sessionId, String key, Object value) { SessionInfo sessionInfo = getSessionInfo(sessionId); if (sessionInfo == null) { sessionInfo = new SessionInfo(); sessionInfo.contentOfSession.put(ENGINE_SESSION_ID, sessionId); sessionInfo.contentOfSession.put(SOFT_LIMIT_INTERVAL_PARAMETER_NAME, Config.<Integer> getValue(ConfigValues.UserSessionTimeOutInterval)); SessionInfo oldSessionInfo = sessionInfoMap.putIfAbsent(sessionId, sessionInfo); if (oldSessionInfo != null) { sessionInfo = oldSessionInfo; } } sessionInfo.contentOfSession.put(key, value); }

Target:
protected final void setData(String sessionId, String key, Object value) { SessionInfo sessionInfo = getSessionInfo(sessionId); if (sessionInfo == null) { sessionInfo = new SessionInfo(); sessionInfo.contentOfSession.put(ENGINE_SESSION_ID, sessionId); sessionInfo.contentOfSession.put(SOFT_LIMIT_INTERVAL_PARAMETER_NAME, Config.<Integer> getValue(ConfigValues.UserSessionTimeOutInterval)); SessionInfo oldSessionInfo = sessionInfoMap.putIfAbsent(sessionId, sessionInfo); if (oldSessionInfo != null) { sessionInfo = oldSessionInfo; } } sessionInfo.contentOfSession.put(key, value); }
Source:
private boolean pendingPullRequestExists(final PullRequest pullRequest, final int requestId) { if (pullRequest == null) { LOG.log(Level.FINE, "Pending pull was not found"); return false; } else if (requestId != pullRequest.getRequestId()) { LOG.log(Level.FINE, "Pull request id not matched, received: {0}, actual: {1}", new Object[]{requestId, pullRequest.getRequestId()}); return false; } return true; }

Target:
private boolean pendingPullRequestExists(final PullRequest pullRequest, final int requestId) { if (pullRequest == null) { LOG.log(Level.FINE, "Pending pull was not found"); return false; } else if (requestId != pullRequest.getRequestId()) { LOG.log(Level.FINE, "Pull request id not matched, received: {0}, actual: {1}", new Object[]{requestId, pullRequest.getRequestId()}); return false; } else { return true; } }
Source:
public Optional<StructureData> fill(DataContainer container, StructureData data) { return Optional.empty(); }

Target:
public Optional<StructureData> fill(DataContainer container, StructureData data) { checkNotNull(data, "data"); Optional<String> author = container.getString(Keys.STRUCTURE_AUTHOR.getQuery()); if (author.isPresent()) { data = data.set(Keys.STRUCTURE_AUTHOR, author.get()); } Optional<Boolean> ignoreEntities = container.getBoolean(Keys.STRUCTURE_IGNORE_ENTITIES.getQuery()); if (ignoreEntities.isPresent()) { data = data.set(Keys.STRUCTURE_IGNORE_ENTITIES, ignoreEntities.get()); } Optional<Float> integrity = container.getFloat(Keys.STRUCTURE_INTEGRITY.getQuery()); if (integrity.isPresent()) { data = data.set(Keys.STRUCTURE_INTEGRITY, integrity.get()); } Optional<StructureMode> mode = container.getObject(Keys.STRUCTURE_MODE.getQuery(), StructureMode.class); if (mode.isPresent()) { data = data.set(Keys.STRUCTURE_MODE, mode.get()); } Optional<Vector3i> position = container.getObject(Keys.STRUCTURE_POSITION.getQuery(), Vector3i.class); if (position.isPresent()) { data = data.set(Keys.STRUCTURE_POSITION, position.get()); } Optional<Boolean> powered = container.getBoolean(Keys.STRUCTURE_POWERED.getQuery()); if (powered.isPresent()) { data = data.set(Keys.STRUCTURE_POWERED, powered.get()); } Optional<Boolean> showAir = container.getBoolean(Keys.STRUCTURE_SHOW_AIR.getQuery()); if (showAir.isPresent()) { data = data.set(Keys.STRUCTURE_SHOW_AIR, showAir.get()); } Optional<Boolean> showBoundingBox = container.getBoolean(Keys.STRUCTURE_SHOW_BOUNDING_BOX.getQuery()); if (showBoundingBox.isPresent()) { data = data.set(Keys.STRUCTURE_SHOW_BOUNDING_BOX, showBoundingBox.get()); } Optional<Vector3i> size = container.getObject(Keys.STRUCTURE_SIZE.getQuery(), Vector3i.class); if (size.isPresent()) { data = data.set(Keys.STRUCTURE_SIZE, size.get()); } return Optional.of(data); }
Source:
public Environment(@JsonProperty("name") String name, @JsonProperty("profiles") String[] profiles, @JsonProperty("label") String label, @JsonProperty("version") String version, @JsonProperty("state") String state) { super(); this.name = name; this.profiles = profiles; this.label = label; this.version = version; this.state = state; this.cached = false; }

Target:
public Environment(@JsonProperty("name") String name, @JsonProperty("profiles") String[] profiles, @JsonProperty("label") String label, @JsonProperty("version") String version, @JsonProperty("state") String state) { super(); this.name = name; this.profiles = profiles; this.label = label; this.version = version; this.state = state; }
Source:
private SortingCollection<String> makeSortingCollection() { final String parent = System.getProperty("java.io.tmpdir") + "/" + System.getProperty("user.name"); final String child = getClass().getSimpleName(); final File tmpDir = new File(parent, child); IOUtil.deleteDirectoryTree(tmpDir); if (!tmpDir.mkdirs()) { throw new IllegalStateException("Could not create tmpdir: " + tmpDir.getAbsolutePath()); } tmpDir.deleteOnExit(); long maxNamesInRam = Runtime.getRuntime().maxMemory() / 256 / 10; return SortingCollection.newInstance( String.class, new StringCodec(), String::compareTo, maxNamesInRam > Integer.MAX_VALUE ? Integer.MAX_VALUE : (int) maxNamesInRam, tmpDir ); }

Target:
private SortingCollection<String> makeSortingCollection() { final String name = getClass().getSimpleName(); final File tmpDir = IOUtil.createTempDir(name, null); tmpDir.deleteOnExit(); long maxNamesInRam = Runtime.getRuntime().maxMemory() / 256 / 10; return SortingCollection.newInstance( String.class, new StringCodec(), String::compareTo, (int) Math.min(maxNamesInRam, Integer.MAX_VALUE), tmpDir ); }
Source:
public static Properties defaultProperties() { Properties properties = BaseHttpApiMetadata.defaultProperties(); properties.put(TEMPLATE, "osFamily=UBUNTU,os64Bit=true,osVersionMatches=14.*"); properties.put(TIMEOUT_NODE_RUNNING, 300000); return properties; }

Target:
public static Properties defaultProperties() { Properties properties = BaseHttpApiMetadata.defaultProperties(); properties.put(TEMPLATE, "osFamily=UBUNTU,os64Bit=true,osVersionMatches=16.*"); properties.put(TIMEOUT_NODE_RUNNING, 300000); return properties; }
Source:
public void testVCard() { VCardBean vcard = BEANS.get(VCardBuilder.class) .withDisplayName("displayname") .withName("Samuel", "middlename", "Keusch", "Dr.") .withEmail(VCardBean.PARAM_HOME, "samuel.keusch@bsi-software.com") .withJobTitle("Software Engineer") .withOrganizations("BSI Business Systems Integration AG", "FHNW.ch") .withProductIdentifier("productidentifiert") .withTel(VCardBean.PARAM_WORK, VCardBean.PARAM_CELL, "0772424244") .withAddress(VCardBean.PARAM_HOME, "Bahnhofstrasse", "5612", "Villmergen", "Schweiz") .build(); assertEquals("BEGIN:VCARD\r\n" + "VERSION:4.0\r\n" + "FN:displayname\r\n" + "N:Keusch;Samuel;middlename;Dr.;\r\n" + "EMAIL;TYPE=HOME:samuel.keusch@bsi-software.com\r\n" + "TITLE:Software Engineer\r\n" + "ORG:BSI Business Systems Integration AG;FHNW.ch\r\n" + "PRODID:productidentifiert\r\n" + "TEL;TYPE=WORK,CELL:0772424244\r\n" + "ADR;TYPE=HOME:;;Bahnhofstrasse;Villmergen;;5612;Schweiz\r\n" + "END:VCARD\r\n", new String(vcard.toBytes("utf-8"))); }

Target:
public void testVCard() { VCardBean vcard = BEANS.get(VCardBuilder.class) .withDisplayName("displayname") .withName("Tommy", "middlename", "Mustermann", "Dr.") .withEmail(VCardProperties.PARAM_NAME_HOME, "tommy@mustermann.de") .withJobTitle("Software Engineer") .withOrganizations("Mustermann GmbH", "mustermann.de") .withProductIdentifier("productidentifiert") .withTel(VCardProperties.PARAM_NAME_WORK, VCardProperties.PARAM_NAME_CELL, "0776665544") .withAddress(VCardProperties.PARAM_NAME_HOME, "Bahnhofstrasse", "1234", "Entenhausen", "Schweiz") .build(); assertEquals("BEGIN:VCARD\r\n" + "VERSION:4.0\r\n" + "FN:displayname\r\n" + "N:Mustermann;Tommy;middlename;Dr.;\r\n" + "EMAIL;TYPE=HOME:tommy@mustermann.de\r\n" + "TITLE:Software Engineer\r\n" + "ORG:Mustermann GmbH;mustermann.de\r\n" + "PRODID:productidentifiert\r\n" + "TEL;TYPE=WORK,CELL:0776665544\r\n" + "ADR;TYPE=HOME:;;Bahnhofstrasse;Entenhausen;;1234;Schweiz\r\n" + "END:VCARD\r\n", new String(vcard.toBytes("utf-8"))); }
Source:
public ICommandLineInterface getCli() { return new ICommandLineInterface() { @Override public String getName() { return "smoketest"; } @Override public int call(String[] args) { String testFile = System.getProperty("IRIS_DIR")+"/examples/3c273.xml"; if(args.length>0) { try{ Integer timeout = Integer.parseInt(args[0]); test = new SherpaSmokeTest(testFile, timeout); } catch (NumberFormatException ex) { System.out.println(args[0]+" is not a number."); return 1; } } else test = new SherpaSmokeTest(testFile); try { test.runTest(); } catch (Exception ex) { Logger.getLogger(SmokeTest.class.getName()).log(Level.SEVERE, null, ex); } finally { return test.exit(); } } }; }

Target:
public ICommandLineInterface getCli() { return new ICommandLineInterface() { @Override public String getName() { return "smoketest"; } @Override public int call(String[] args) { String testFile = System.getProperty("IRIS_DIR")+"/examples/3c273.xml"; if(args.length>0) { try{ Integer timeout = Integer.parseInt(args[0]); test = new SherpaSmokeTest(testFile, timeout); } catch (NumberFormatException ex) { System.out.println(args[0]+" is not a number."); return 1; } } else test = new SherpaSmokeTest(testFile); try { test.runTest(); } catch (Throwable ex) { ex.printStackTrace(System.err); } finally { return test.exit(); } } }; }
Source:
public void visitFile(Tree scriptTree) { List<String> lines; try { lines = Files.readLines(getContext().getFile(), charset); for (int i = 0; i < lines.size(); i++) { String line = lines.get(i); if (line.length() > 0 && Pattern.matches("[" + EcmaScriptLexer.WHITESPACE + "]", line.subSequence(line.length() - 1, line.length()))) { getContext().addIssue(this, i + 1, "Remove the useless trailing whitespaces at the end of this line."); } } } catch (IOException e) { LOG.error("Unable to execute rule \"TrailingWhitespace\" for file because of error: {}", getContext().getFile().getName(), e); } }

Target:
public void visitFile(Tree scriptTree) { List<String> lines = Collections.emptyList(); try { lines = Files.readLines(getContext().getFile(), charset); } catch (IOException e) { LOG.error("Unable to execute rule \"TrailingWhitespace\" for file because of error: {}", getContext().getFile().getName(), e); } for (int i = 0; i < lines.size(); i++) { String line = lines.get(i); if (line.length() > 0 && Pattern.matches("[" + EcmaScriptLexer.WHITESPACE + "]", line.subSequence(line.length() - 1, line.length()))) { getContext().addIssue(this, i + 1, "Remove the useless trailing whitespaces at the end of this line."); } } }
Source:
public void setBlockSelectionMode(boolean enable) { if (!isBlockSelectionModeSupported()) return; ISourceViewer viewer= getSourceViewer(); if (viewer != null) { StyledText styledText= viewer.getTextWidget(); if (styledText != null) { if (enable) { Font blockFont= JFaceResources.getFont(BLOCK_SELECTION_MODE_FONT); Font normalFont= styledText.getFont(); if (!blockFont.equals(normalFont) && !normalFont.getFontData()[0].equals(blockFont.getFontData()[0])) { setFont(viewer, blockFont); disposeFont(); updateCaret(); } styledText.setWordWrap(false); if (fVerticalRuler != null) { fVerticalRuler.update(); } } styledText.setBlockSelection(enable); if (!enable) { initializeViewerFont(viewer); updateCaret(); if (fWordWrapHint) { styledText.setWordWrap(true); if (fVerticalRuler != null) { fVerticalRuler.update(); } } } } } }

Target:
public void setBlockSelectionMode(boolean enable) { if (!isBlockSelectionModeSupported()) return; ISourceViewer viewer= getSourceViewer(); if (viewer != null) { StyledText styledText= viewer.getTextWidget(); if (styledText != null) { if (enable) { Font blockFont= JFaceResources.getFont(BLOCK_SELECTION_MODE_FONT); Font normalFont= styledText.getFont(); if (!blockFont.equals(normalFont) && !normalFont.getFontData()[0].equals(blockFont.getFontData()[0])) { setFont(viewer, blockFont); disposeFont(); updateCaret(); } if (styledText.getWordWrap()) { styledText.setWordWrap(false); if (fVerticalRuler != null) { fVerticalRuler.update(); } } } styledText.setBlockSelection(enable); if (!enable) { initializeViewerFont(viewer); updateCaret(); if (!styledText.getWordWrap() && fIsWordWrapActivated) { styledText.setWordWrap(true); if (fVerticalRuler != null) { fVerticalRuler.update(); } } } } } }
Source:
public void releaseStore(final Store<?, ?> resource) { if (createdStores.remove(resource) == null) { throw new IllegalArgumentException("Given cluster tier is not managed by this provider : " + resource); } ClusteredStore clusteredStore = (ClusteredStore)resource; this.clusteringService.releaseServerStoreProxy(clusteredStore.storeProxy); StatisticsManager.nodeFor(clusteredStore).clean(); tierOperationStatistics.remove(clusteredStore); }

Target:
public void releaseStore(final Store<?, ?> resource) { if (createdStores.remove(resource) == null) { throw new IllegalArgumentException("Given clustered tier is not managed by this provider : " + resource); } ClusteredStore clusteredStore = (ClusteredStore)resource; this.clusteringService.releaseServerStoreProxy(clusteredStore.storeProxy); StatisticsManager.nodeFor(clusteredStore).clean(); tierOperationStatistics.remove(clusteredStore); }
Source:
KeenClient(Builder builder, Environment env) { this.httpHandler = builder.httpHandler; this.jsonHandler = builder.jsonHandler; this.eventStore = builder.eventStore; this.publishExecutor = builder.publishExecutor; if (httpHandler == null || jsonHandler == null || eventStore == null || publishExecutor == null) { setActive(false); } this.baseUrl = KeenConstants.SERVER_ADDRESS; this.globalPropertiesEvaluator = null; this.globalProperties = null; this.builder = builder; if (env.getKeenProjectId() != null) { defaultProject = new KeenProject(env); } }

Target:
KeenClient(Builder builder, Environment env) { this.httpHandler = builder.httpHandler; this.jsonHandler = builder.jsonHandler; this.eventStore = builder.eventStore; this.publishExecutor = builder.publishExecutor; this.networkStatusHandler = builder.networkStatusHandler; if (httpHandler == null || jsonHandler == null || eventStore == null || publishExecutor == null) { setActive(false); } this.baseUrl = KeenConstants.SERVER_ADDRESS; this.globalPropertiesEvaluator = null; this.globalProperties = null; if (env.getKeenProjectId() != null) { defaultProject = new KeenProject(env); } }
Source:
public void visitFunctionCall(FunctionCallTree tree) { super.visitFunctionCall(tree); String callee = tree.callee().toString(); if (!this.isExcludedFile() && WRONG_FUNCTIONS.contains(callee.toLowerCase(Locale.ENGLISH))) { String message = String.format(MESSAGE, callee); context().newIssue(this, tree.callee(), message); } }

Target:
public void visitFunctionCall(FunctionCallTree tree) { super.visitFunctionCall(tree); String callee = tree.callee().toString(); if (WRONG_FUNCTIONS.contains(callee.toLowerCase(Locale.ENGLISH))) { String message = String.format(MESSAGE, callee); context().newIssue(this, tree.callee(), message); } }
Source:
private void readBytesFromFile(String fileName, byte[] bytes) { try (FileInputStream fos = getApplicationContext().openFileInput(fileName)) { fos.read(bytes); } catch (IOException e) { throw new RuntimeException("Couldn't write to " + fileName, e); } }

Target:
private void readBytesFromFile(String fileName, byte[] bytes) { try (FileInputStream fis = openFileInput(fileName)) { int n = 0; while (n < bytes.length) { n += fis.read(bytes, n, bytes.length - n); } } catch (IOException e) { throw new RuntimeException("Couldn't read from " + fileName, e); } }
Source:
private static TableDefinition partitionedTableDefinition() { String createTableDdl = "CREATE TABLE %NAME%(" + "id int," + "name string" + ")" + "PARTITIONED BY (dt string)" + "ROW FORMAT SERDE 'org.apache.hadoop.hive.serde2.lazy.LazySimpleSerDe'" + "WITH SERDEPROPERTIES (" + "'field.delim'='\\t'," + "'line.delim'='\\n'," + "'serialization.format'='\\t'" + ")"; return HiveTableDefinition.builder(PARTITIONED_TABLE).setCreateTableDDLTemplate(createTableDdl).setNoData().build(); }

Target:
private static TableDefinition partitionedTableDefinition() { String createTableDdl = "CREATE TABLE %NAME%( " + "id int, " + "name string " + ") " + "PARTITIONED BY (dt string) " + "ROW FORMAT SERDE 'org.apache.hadoop.hive.serde2.lazy.LazySimpleSerDe' " + "WITH SERDEPROPERTIES ( " + "'field.delim'='\\t', " + "'line.delim'='\\n', " + "'serialization.format'='\\t' " + ")"; return HiveTableDefinition.builder(PARTITIONED_TABLE_WITH_SERDE) .setCreateTableDDLTemplate(createTableDdl) .setNoData() .build(); }
Source:
public void testSalesforceConnectionPropertiesMigration() throws IOException { Deserialized<SalesforceConnectionProperties> deser = Properties.Helper.fromSerializedPersistent( TestUtils.getResourceAsString(getClass(), "tSalesforceConnectionProperties_621.json"), SalesforceConnectionProperties.class); assertTrue("should be true, but not", deser.migrated); SalesforceConnectionProperties properties = deser.object; String apiVersion = properties.apiVersion.getValue(); assertEquals("\"34.0\"", apiVersion); }

Target:
public void testSalesforceConnectionPropertiesMigration() throws IOException { Deserialized<SalesforceConnectionProperties> deser = Properties.Helper.fromSerializedPersistent( TestUtils.getResourceAsString(getClass(), "tSalesforceConnectionProperties_621.json"), SalesforceConnectionProperties.class); assertTrue("the property should be migrated, the migration returned false instead of true", deser.migrated); SalesforceConnectionProperties properties = deser.object; String apiVersion = properties.apiVersion.getValue(); assertEquals("\"34.0\"", apiVersion); }
Source:
public static void showPushNotification(Context context, Intent messageIntent, MixpanelPushNotification mixpanelPushNotification) { Notification notification = mixpanelPushNotification.createNotification(messageIntent); MixpanelNotificationData data = mixpanelPushNotification.getData(); String message = data == null ? "null" : data.getMessage(); MPLog.d(LOGTAG, "MP FCM notification received: " + message); if (notification != null && !mixpanelPushNotification.hasOnTapError) { final NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); if (null != data.getTag()) { notificationManager.notify(data.getTag(), NOTIFICATION_ID, notification); } else { notificationManager.notify(mixpanelPushNotification.notificationId, notification); } } }

Target:
public static void showPushNotification(Context context, Intent messageIntent, MixpanelPushNotification mixpanelPushNotification) { Notification notification = mixpanelPushNotification.createNotification(messageIntent); MixpanelNotificationData data = mixpanelPushNotification.getData(); String message = data == null ? "null" : data.getMessage(); MPLog.d(LOGTAG, "MP FCM notification received: " + message); if (notification != null) { if (!mixpanelPushNotification.isValid()) { MPLog.e(LOGTAG, "MP FCM notification has error"); } final NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); if (null != data.getTag()) { notificationManager.notify(data.getTag(), NOTIFICATION_ID, notification); } else { notificationManager.notify(mixpanelPushNotification.getNotificationId(), notification); } } }
Source:
public void write(Object datum) throws IOException { if (!opened) { throw new IOException("Writer is not opened"); } result.totalCount++; if (datum == null) { return; } IndexedRecord record = (IndexedRecord) datum; Schema schema = record.getSchema(); Schema.Field idField = schema.getField(idFieldName); if (idField == null) { throw new IOException("Schema does not contain ID field: " + idFieldName); } int idPos = idField.pos(); String id = record.get(idPos).toString(); connection.upsert(id, datum.toString()); }

Target:
public void write(Object datum) throws IOException { if (!opened) { throw new IOException("Writer is not opened"); } result.totalCount++; if (datum == null) { return; } IndexedRecord record = (IndexedRecord) datum; Schema schema = record.getSchema(); Schema.Field idField = schema.getField(idFieldName); if (idField == null) { throw new IOException("Schema does not contain ID field: " + idFieldName); } int idPos = idField.pos(); Object id = record.get(idPos); if (id == null) { throw new IOException("ID field is null: " + idField.name()); } try { connection.upsert(id.toString(), datum.toString()); result.successCount++; } catch (Exception e) { result.rejectCount++; throw new IOException("Failed to upsert value - " + datum.toString(), e); } }