auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void getSearchHandler_shouldReturnSearchHandlerProvidingAllRequestParametersAndParametersSatisfyingItsRequiredParameters() throws Exception { SearchHandler searchHandler1 = mock(SearchHandler.class); SearchConfig searchConfig1 = new SearchConfig("default", "v1/concept", "1.8.*", new SearchQuery.Builder( "description").withRequiredParameters(new SearchParameter("source", "some source")) .withOptionalParameters(new SearchParameter("code", "some code")).build()); when(searchHandler1.getSearchConfig()).thenReturn(searchConfig1); SearchHandler searchHandler2 = mock(SearchHandler.class); SearchConfig searchConfig2 = new SearchConfig("conceptByMapping", "v1/concept", "1.8.*", new SearchQuery.Builder( "description").withRequiredParameters(new SearchParameter("source", "some source")).build()); when(searchHandler2.getSearchConfig()).thenReturn(searchConfig2); setCurrentOpenmrsVersion("1.8.10"); when(restHelperService.getRegisteredSearchHandlers()).thenReturn(asList(searchHandler1, searchHandler2)); RestUtil.disableContext(); Map<String, String[]> parameters = new HashMap<String, String[]>(); parameters.put("source", new String[] { "some source" }); parameters.put("code", new String[] { "some code" }); assertThat(restService.getSearchHandler("v1/concept", parameters), is(searchHandler1)); }

Target:
public void getSearchHandler_shouldReturnSearchHandlerProvidingAllRequestParametersAndParametersSatisfyingItsRequiredParameters() throws Exception { SearchHandler searchHandler1 = mock(SearchHandler.class); SearchConfig searchConfig1 = new SearchConfig("default", "v1/concept", "1.8.*", new SearchQuery.Builder( "description").withRequiredParameters("source").withOptionalParameters("code").build()); when(searchHandler1.getSearchConfig()).thenReturn(searchConfig1); SearchHandler searchHandler2 = mock(SearchHandler.class); SearchConfig searchConfig2 = new SearchConfig("conceptByMapping", "v1/concept", "1.8.*", new SearchQuery.Builder( "description").withRequiredParameters("source").build()); when(searchHandler2.getSearchConfig()).thenReturn(searchConfig2); setCurrentOpenmrsVersion("1.8.10"); when(restHelperService.getRegisteredSearchHandlers()).thenReturn(asList(searchHandler1, searchHandler2)); RestUtil.disableContext(); Map<String, String[]> parameters = new HashMap<String, String[]>(); parameters.put("source", new String[] { "some source" }); parameters.put("code", new String[] { "some code" }); assertThat(restService.getSearchHandler("v1/concept", parameters), is(searchHandler1)); }
Source:
public void setProtocol(ProtocolConfig protocol) { setProtocols(new ArrayList<ProtocolConfig>(Arrays.asList(protocol))); }

Target:
public void setProtocol(ProtocolConfig protocol) { setProtocols(new ArrayList<>(Arrays.asList(protocol))); }
Source:
public void testGetGeoJsonResponseWfs20() throws Exception { JSON response = getAsJSON( "wfs?request=GetFeature&version=2.0" + "&typenames=st_gml32:Station_gml32&outputFormat=application/json"); print(response); checkStation1Exists(response); JSONObject station = getFeaturePropertiesById(response, "st.2"); assertThat(station, notNullValue()); JSONObject contact = station.getJSONObject("contact"); assertThat(contact.size(), is(3)); assertThat(contact.get("@mail"), is("st2@stations.org")); JSONObject phone = contact.getJSONObject("phone"); assertThat(phone.size(), is(1)); assertFalse(phone.has("value")); assertThat(phone.get("@timeZone"), is("")); JSONObject featureLinkA = station.getJSONArray("featureLinkA").getJSONObject(0); assertEquals("<LINK_2>", featureLinkA.getString("@href")); JSONObject featureLinkB = station.getJSONArray("featureLinkB").getJSONObject(0); assertEquals("<LINK_0>", featureLinkB.getString("@href")); JSONObject featureLinkC = station.getJSONObject("featureLinkC"); assertEquals("<LINK_1>", featureLinkC.getString("@href")); }

Target:
public void testGetGeoJsonResponseWfs20() throws Exception { JSON response = getAsJSON( "wfs?request=GetFeature&version=2.0" + "&typenames=st_gml32:Station_gml32&outputFormat=application/json"); checkStation1Exists(response); JSONObject station = getFeaturePropertiesById(response, "st.2"); assertThat(station, notNullValue()); JSONObject contact = station.getJSONObject("contact"); assertThat(contact.size(), is(3)); assertThat(contact.get("@mail"), is("st2@stations.org")); JSONObject phone = contact.getJSONObject("phone"); assertThat(phone.size(), is(1)); assertFalse(phone.has("value")); assertThat(phone.get("@timeZone"), is("")); JSONObject featureLinkA = station.getJSONArray("featureLinkA").getJSONObject(0); assertEquals("<LINK_2>", featureLinkA.getString("@href")); JSONObject featureLinkB = station.getJSONArray("featureLinkB").getJSONObject(0); assertEquals("<LINK_0>", featureLinkB.getString("@href")); JSONObject featureLinkC = station.getJSONObject("featureLinkC"); assertEquals("<LINK_1>", featureLinkC.getString("@href")); }
Source:
public void tickGO() { if(running) { if(playersDead()) { levelLost(); } } }

Target:
public void tickGO() { if(running && playersDead()) { levelLost(); } }
Source:
public long getTableWriteId(String dbName, String tableName) throws LockException { String fullTableName = AcidUtils.getFullTableName(dbName, tableName); if (tableWriteIds.containsKey(fullTableName)) { return tableWriteIds.get(fullTableName); } try { long writeId = 0; if (isTxnOpen()) { writeId = getMS().allocateTableWriteId(txnId, dbName, tableName); tableWriteIds.put(fullTableName, writeId); } return writeId; } catch (TException e) { throw new LockException(ErrorMsg.METASTORE_COMMUNICATION_FAILED.getMsg(), e); } }

Target:
public long getTableWriteId(String dbName, String tableName) throws LockException { assert isTxnOpen(); String fullTableName = AcidUtils.getFullTableName(dbName, tableName); if (tableWriteIds.containsKey(fullTableName)) { return tableWriteIds.get(fullTableName); } try { long writeId = getMS().allocateTableWriteId(txnId, dbName, tableName); tableWriteIds.put(fullTableName, writeId); return writeId; } catch (TException e) { throw new LockException(ErrorMsg.METASTORE_COMMUNICATION_FAILED.getMsg(), e); } }
Source:
protected void persistExpansion() { if(fLaunchConfigurationView != null) { IDialogSettings settings = getDialogSettings(); TreeItem[] items = fLaunchConfigurationView.getTreeViewer().getTree().getItems(); String value = settings.get(DIALOG_EXPANDED_NODES); if(value == null) { value = IInternalDebugCoreConstants.EMPTY_STRING; } ArrayList<String> list = new ArrayList<>(); String[] persisted = value.split(DELIMITER); Collections.addAll(list, persisted); String type = IInternalDebugCoreConstants.EMPTY_STRING; for (TreeItem item : items) { type = ((ILaunchConfigurationType) item.getData()).getIdentifier(); if (!list.contains(type) & item.getExpanded()) { list.add(type); } else if (!item.getExpanded()) { list.remove(type); } } value = IInternalDebugCoreConstants.EMPTY_STRING; for (String string : list) { value += string + DELIMITER; } settings.put(DIALOG_EXPANDED_NODES, value); } }

Target:
protected void persistExpansion() { if(fLaunchConfigurationView != null) { IDialogSettings settings = getDialogSettings(); TreeItem[] items = fLaunchConfigurationView.getTreeViewer().getTree().getItems(); String value = settings.get(DIALOG_EXPANDED_NODES); if(value == null) { value = IInternalDebugCoreConstants.EMPTY_STRING; } ArrayList<String> list = new ArrayList<>(); String[] persisted = value.split(DELIMITER); Collections.addAll(list, persisted); String type = IInternalDebugCoreConstants.EMPTY_STRING; for (TreeItem item : items) { type = ((ILaunchConfigurationType) item.getData()).getIdentifier(); if (!list.contains(type) & item.getExpanded()) { list.add(type); } else if (!item.getExpanded()) { list.remove(type); } } value = IInternalDebugCoreConstants.EMPTY_STRING; for (String segment : list) { value += segment + DELIMITER; } settings.put(DIALOG_EXPANDED_NODES, value); } }
Source:
public static void main(String...args) { @SuppressWarnings({ "unchecked" }) CliBuilder<Callable> builder = Cli.buildCli("brooklyn", Callable.class) .withDescription("Brooklyn Management Service") .withDefaultCommand(Help.class) .withCommands( Help.class, Launch.class ); Cli<Callable> brooklynParser = builder.build(); Help.help(brooklynParser.getMetadata(), Arrays.asList("launch"), launchHelp); try { Callable<?> command = brooklynParser.parse(args); command.call(); } catch (ParseException pe) { System.err.println("Parse error: " + pe.getMessage()); System.err.println(launchHelp.toString()); System.exit(1); } catch (Exception e) { System.err.println("Execution error: " + e.getMessage()); e.printStackTrace(); } }

Target:
public static void main(String...args) { Cli<BrooklynCommand> parser = buildCli(); try { log.debug("Parsing command line arguments"); BrooklynCommand command = parser.parse(args); log.debug("Executing command: "+command); command.call(); } catch (ParseException pe) { System.err.println("Parse error: " + pe.getMessage()); StringBuilder help = new StringBuilder(); Help.help(parser.getMetadata(), ImmutableList.of("brooklyn"), help); System.err.println(help); System.exit(1); } catch (Exception e) { System.err.println("Execution error: " + e.getMessage()); e.printStackTrace(); } }
Source:
public ActualProperties visitSpatialJoin(SpatialJoinNode node, List<ActualProperties> inputProperties) { ActualProperties probeProperties = inputProperties.get(0); ActualProperties buildProperties = inputProperties.get(1); switch (node.getType()) { case INNER: probeProperties = probeProperties.translate(column -> filterIfMissing(node.getOutputSymbols(), column)); buildProperties = buildProperties.translate(column -> filterIfMissing(node.getOutputSymbols(), column)); Map<Symbol, NullableValue> constants = new HashMap<>(); constants.putAll(probeProperties.getConstants()); constants.putAll(buildProperties.getConstants()); return ActualProperties.builderFrom(probeProperties) .constants(constants) .build(); case LEFT: return ActualProperties.builderFrom(probeProperties.translate(column -> filterIfMissing(node.getOutputSymbols(), column))) .build(); default: throw new UnsupportedOperationException("Unsupported spatial join type: " + node.getType()); } }

Target:
public ActualProperties visitSpatialJoin(SpatialJoinNode node, List<ActualProperties> inputProperties) { ActualProperties probeProperties = inputProperties.get(0); ActualProperties buildProperties = inputProperties.get(1); switch (node.getType()) { case INNER: probeProperties = probeProperties.translate(column -> filterIfMissing(node.getOutputSymbols(), column)); buildProperties = buildProperties.translate(column -> filterIfMissing(node.getOutputSymbols(), column)); Map<Symbol, NullableValue> constants = new HashMap<>(); constants.putAll(probeProperties.getConstants()); constants.putAll(buildProperties.getConstants()); return ActualProperties.builderFrom(probeProperties) .constants(constants) .build(); case LEFT: return ActualProperties.builderFrom(probeProperties.translate(column -> filterIfMissing(node.getOutputSymbols(), column))) .build(); default: throw new IllegalArgumentException("Unsupported spatial join type: " + node.getType()); } }
Source:
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { binding = DataBindingUtil.inflate(inflater, R.layout.fragment_albums, container, false); binding.albumRecycler.setHasFixedSize(true); binding.albumRecycler.setLayoutManager(new GridLayoutManager(getContext(), calculateColumnCount())); binding.photoRecycler.setHasFixedSize(true); binding.photoRecycler.setLayoutManager(new GridLayoutManager(getContext(), calculateColumnCount() * Integer.parseInt(SettingsPreferences.getSettingPreference(SettingsPreferences.KEY_NUMBER_ROW, "3")))); return binding.getRoot(); }

Target:
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { binding = DataBindingUtil.inflate(inflater, R.layout.fragment_albums, container, false); binding.albumRecycler.setHasFixedSize(true); binding.albumRecycler.setLayoutManager(new GridLayoutManager(getContext(), calculateColumnCount())); binding.photoRecycler.setHasFixedSize(true); binding.photoRecycler.setLayoutManager(new GridLayoutManager(getContext(), calculateColumnCount() * preferences.getInt(PreferencesRepository.KEY_PREF_PHOTOS_PER_ROW))); return binding.getRoot(); }
Source:
public void testAddPointsTwoSprites() { final int expectedInvocations = 1; testSprite1.getActionFactory().createStitchAction(testSprite1).act(1f); testSprite2.getActionFactory().createStitchAction(testSprite2).act(1f); Mockito.verify(StageActivity.stageListener.embroideryList, Mockito.times(expectedInvocations)).add(new StitchPoint(spriteCoords1, StitchPoint.NORMALSTITCH, testSprite1)); Mockito.verify(StageActivity.stageListener.embroideryList, Mockito.times(expectedInvocations)).add(new StitchPoint(spriteCoords2, StitchPoint.NORMALSTITCH, testSprite2)); }

Target:
public void testAddPointsTwoSprites() { ActionFactory.createStitchAction(testSprite1).act(1f); ActionFactory.createStitchAction(testSprite2).act(1f); Mockito.verify(StageActivity.stageListener.embroideryPatternManager, Mockito.times(1)).addStitchCommand(new DSTStitchCommand(spriteCoords1.x, spriteCoords1.y, testSprite1.look.getZIndex(), testSprite1)); Mockito.verify(StageActivity.stageListener.embroideryPatternManager, Mockito.times(1)).addStitchCommand(new DSTStitchCommand(spriteCoords2.x, spriteCoords2.y, testSprite2.look.getZIndex(), testSprite2)); }
Source:
public Scope newScope(TraceContext currentSpan) { final String previousTraceId = (String) MDC.get("traceId"); final String previousSpanId = (String) MDC.get("spanId"); MDC.put("traceId", currentSpan.traceIdString()); MDC.put("spanId", HexCodec.toLowerHex(currentSpan.spanId())); Scope scope = delegate.newScope(currentSpan); return () -> { scope.close(); if (previousTraceId != null) { MDC.put("traceId", previousTraceId); } else { MDC.remove("traceId"); } if (previousSpanId != null) { MDC.put("spanId", previousSpanId); } else { MDC.remove("spanId"); } }; }

Target:
public Scope newScope(TraceContext currentSpan) { final Object previousTraceId = MDC.get("traceId"); final Object previousSpanId = MDC.get("spanId"); if (currentSpan != null) { MDC.put("traceId", currentSpan.traceIdString()); MDC.put("spanId", HexCodec.toLowerHex(currentSpan.spanId())); } else { MDC.remove("traceId"); MDC.remove("spanId"); } Scope scope = delegate.newScope(currentSpan); return () -> { scope.close(); if (previousTraceId != null) { MDC.put("traceId", previousTraceId); } else { MDC.remove("traceId"); } if (previousSpanId != null) { MDC.put("spanId", previousSpanId); } else { MDC.remove("spanId"); } }; }
Source:
public void copyFrom(ColumnIndices other, RealmProxyMediator mediator) { for (Map.Entry<Class<? extends RealmModel>, ColumnInfo> entry : classes.entrySet()) { final ColumnInfo otherColumnInfo = other.getColumnInfo(entry.getKey()); if (otherColumnInfo == null) { throw new IllegalStateException("failed to copy ColumnIndices cache: " + Table.tableNameToClassName(mediator.getTableName(entry.getKey()))); } entry.getValue().copyColumnInfoFrom(otherColumnInfo); } this.schemaVersion = other.schemaVersion; }

Target:
public void copyFrom(ColumnIndices other, RealmProxyMediator mediator) { for (Map.Entry<Class<? extends RealmModel>, ColumnInfo> entry : classes.entrySet()) { final ColumnInfo otherColumnInfo = other.getColumnInfo(entry.getKey()); if (otherColumnInfo == null) { throw new IllegalStateException("Failed to copy ColumnIndices cache: " + Table.tableNameToClassName(mediator.getTableName(entry.getKey()))); } entry.getValue().copyColumnInfoFrom(otherColumnInfo); } this.schemaVersion = other.schemaVersion; }
Source:
protected void prepareTestData() { dataBundle = getTypicalDataBundle(); typicalBundle = getTypicalDataBundle(); removeAndRestoreDataBundle(typicalBundle); removeAndRestoreTypicalDataBundle(); }

Target:
protected void prepareTestData() { removeAndRestoreTypicalDataBundle(); }
Source:
public boolean checkTrigger(GameEvent event, Game game) { Spell spell = game.getStack().getSpell(event.getTargetId()); if (spell != null) { for (Ability ability : spell.getAbilities()) { if (ability instanceof KickerAbility && ((KickerAbility) ability).getKickedCounter(game, spell.getSpellAbility()) > 0) { return true; } } } return false; }

Target:
public boolean checkTrigger(GameEvent event, Game game) { return true; }
Source:
public Point find(Square square){ for (int i = 0; i < squares.length; i++){ for (int j = 0; j < squares[i].length; j++){ if (square == squares[i][j]) return new Point(i, j); } } return null; }

Target:
public Point find(Square square){ for (int j = 0; j < size.height; j++){ for (int i = 0; i < size.width; i++){ if (square == squares[j][i]){ return new Point(i, j); } } } throw new IllegalArgumentException("Square not found in grid"); }
Source:
public PatchLink createLink(int index, PatchScreen.Type patchType, SafeHtml before, SafeHtml after) { Patch patch = patchList.get(index); Key thisKey = patch.getKey(); PatchLink link; if (patchType == PatchScreen.Type.SIDE_BY_SIDE && patch.getPatchType() == Patch.PatchType.UNIFIED) { link = new PatchLink.SideBySide("", base, thisKey, index, detail, this); } else { link = new PatchLink.Unified("", base, thisKey, index, detail, this); } SafeHtmlBuilder text = new SafeHtmlBuilder(); text.append(before); text.append(getFileNameOnly(patch)); text.append(after); SafeHtml.set(link, text); return link; }

Target:
private PatchLink createLink(int index, PatchScreen.Type patchType, SafeHtml before, SafeHtml after) { Patch patch = patchList.get(index); Key thisKey = patch.getKey(); PatchLink link; if (patchType == PatchScreen.Type.SIDE_BY_SIDE && patch.getPatchType() == Patch.PatchType.UNIFIED) { link = new PatchLink.SideBySide("", base, thisKey, index, detail, this); } else { link = new PatchLink.Unified("", base, thisKey, index, detail, this); } SafeHtmlBuilder text = new SafeHtmlBuilder(); text.append(before); text.append(getFileNameOnly(patch)); text.append(after); SafeHtml.set(link, text); return link; }
Source:
public Collection<Measurement> executeSensors() { for (TopologyAPI.Config.KeyValue kv : physicalPlanProvider.get().getTopology().getTopologyConfig().getKvsList()) { LOG.info("kv " + kv.getKey() + " => " + kv.getValue()); if (kv.getKey().equals(TOGGLE_RUNTIME_CONFIG_KEY)) { String val = kv.getValue(); if ("False".equals(val) || "false".equals(val)) { if (running) { running = false; LOG.info("policy running status changed to False"); } } else if ("True".equals(val) || "true".equals(val)) { if (!running) { running = true; LOG.info("policy running status changed to True"); } } else { LOG.warning("unknown runtime config for `policy running status`: " + val); } } } if (running) { return super.executeSensors(); } else { return new ArrayList<Measurement>(); } }

Target:
public Collection<Measurement> executeSensors() { for (TopologyAPI.Config.KeyValue kv : physicalPlanProvider.get().getTopology().getTopologyConfig().getKvsList()) { LOG.fine("kv " + kv.getKey() + ":" + kv.getValue()); if (kv.getKey().equals(policyIdRuntime)) { try { PolicyMode val = PolicyMode.valueOf(kv.getValue()); if (!policyMode.equals(val)) { policyMode = val; LOG.info("policy " + policyId + " status changed to " + policyMode); } else { LOG.fine("policy " + policyId + " status remains same " + policyMode); } break; } catch (IllegalArgumentException e) { LOG.warning("policy " + policyId + " status does not change " + policyMode + "; unknown input " + kv.getValue()); } } } if (policyMode.equals(PolicyMode.activated)) { return super.executeSensors(); } else { return new ArrayList<Measurement>(); } }
Source:
public void shouldReturnNone() { Option<String> none = HashMap.<Integer, String>empty().lift().apply(1); assertThat(none instanceof Option.None); }

Target:
public void shouldReturnNone() { Option<String> oneToOne = HashMap.<Integer, String>empty().lift().apply(1); assertThat(oneToOne).isEqualTo(Option.none()); }
Source:
private boolean save(Path targetPath, SaveDatabaseMode mode) { var f = throttler.scheduleTask(() -> executeSave(targetPath, mode)); try { var ok = f.get(); LOGGER.debug("Saved {}", ok); return (boolean) f.get(); } catch (InterruptedException | ExecutionException e) { LOGGER.error("Exectutor Exception", e); } return false; }

Target:
private boolean save(Path targetPath, SaveDatabaseMode mode) { if (mode == SaveDatabaseMode.NORMAL) { dialogService.notify(String.format("%s...", Localization.lang("Saving library"))); } libraryTab.setSaving(true); try { Charset encoding = libraryTab.getBibDatabaseContext() .getMetaData() .getEncoding() .orElse(preferences.getDefaultEncoding()); libraryTab.getBibDatabaseContext().getMetaData().setEncoding(encoding, ChangePropagation.DO_NOT_POST_EVENT); boolean success = saveDatabase(targetPath, false, encoding, SavePreferences.DatabaseSaveType.ALL); if (success) { libraryTab.getUndoManager().markUnchanged(); libraryTab.resetChangedProperties(); } return success; } catch (SaveException ex) { LOGGER.error(String.format("A problem occurred when trying to save the file %s", targetPath), ex); dialogService.showErrorDialogAndWait(Localization.lang("Save library"), Localization.lang("Could not save file."), ex); return false; } finally { libraryTab.setSaving(false); } }
Source:
public TDImportResult importBytes(String databaseName, String tableName, byte[] content) { return doPut(buildUrl(String.format("/v3/table/import/%s/%s/%s", databaseName, tableName, "msgpack.gz")), ImmutableMap.of(), content, TDImportResult.class); }

Target:
public TDImportResult importBytes(String databaseName, String tableName, byte[] content) { return doPut(buildUrl(String.format("/v3/table/import/%s/%s/%s", databaseName, tableName, "msgpack.gz")), ImmutableMap.of(), content, 0, content.length, TDImportResult.class); }
Source:
public boolean isFinal() { boolean parkAndRide = stateData.opt.parkAndRide; boolean bikeParkAndRide = stateData.opt.bikeParkAndRide; boolean bikeRentingOk; boolean bikeParkAndRideOk; boolean carParkAndRideOk; boolean taxiOk; if (stateData.opt.arriveBy) { bikeRentingOk = !isBikeRenting() && (!stateData.opt.bikeRental || hasUsedRentedBike()); bikeParkAndRideOk = !bikeParkAndRide || !isBikeParked(); carParkAndRideOk = !parkAndRide || !isCarParked(); taxiOk = getTaxiState() != CarPickupState.WALK_FROM_DROP_OFF; } else { bikeRentingOk = !isBikeRenting() && (!stateData.opt.bikeRental || hasUsedRentedBike()); bikeParkAndRideOk = !bikeParkAndRide || isBikeParked(); carParkAndRideOk = !parkAndRide || isCarParked(); taxiOk = getTaxiState() != CarPickupState.WALK_TO_PICKUP; } return bikeRentingOk && bikeParkAndRideOk && carParkAndRideOk && taxiOk; }

Target:
public boolean isFinal() { boolean parkAndRide = stateData.opt.parkAndRide; boolean bikeParkAndRide = stateData.opt.bikeParkAndRide; boolean bikeRentingOk; boolean bikeParkAndRideOk; boolean carParkAndRideOk; boolean pickedUpByCar; if (stateData.opt.arriveBy) { bikeRentingOk = !isBikeRenting() && (!stateData.opt.bikeRental || hasUsedRentedBike()); bikeParkAndRideOk = !bikeParkAndRide || !isBikeParked(); carParkAndRideOk = !parkAndRide || !isCarParked(); pickedUpByCar = getCarPickupState() != CarPickupState.WALK_FROM_DROP_OFF; } else { bikeRentingOk = !isBikeRenting() && (!stateData.opt.bikeRental || hasUsedRentedBike()); bikeParkAndRideOk = !bikeParkAndRide || isBikeParked(); carParkAndRideOk = !parkAndRide || isCarParked(); pickedUpByCar = getCarPickupState() != CarPickupState.WALK_TO_PICKUP; } return bikeRentingOk && bikeParkAndRideOk && carParkAndRideOk && pickedUpByCar; }
Source:
SharedTokenCacheCredential(String username, String clientID, IdentityClientOptions identityClientOptions) { this.configuration = Configuration.getGlobalConfiguration().clone(); if (username == null) { if (configuration.contains(Configuration.PROPERTY_AZURE_USERNAME)) { this.username = configuration.get(Configuration.PROPERTY_AZURE_USERNAME); } else { this.username = null; } } else { this.username = username; } this.clientID = clientID; }

Target:
SharedTokenCacheCredential(String username, String clientID, IdentityClientOptions identityClientOptions) { this.configuration = Configuration.getGlobalConfiguration().clone(); if (username == null) { this.username = configuration.get(Configuration.PROPERTY_AZURE_USERNAME); } else { this.username = username; } this.clientID = clientID; }
Source:
public Response updateFirmware( @HeaderParam(HttpHeaders.ACCEPT_LANGUAGE) @ApiParam(value = "language") String language, @PathParam("thingUID") @ApiParam(value = "thing") String thingUID, @PathParam("firmwareVersion") @ApiParam(value = "version") String firmwareVersion) throws IOException { Thing thing = thingRegistry.get(new ThingUID(thingUID)); if (thing == null) { return JSONResponse.createResponse(Status.BAD_REQUEST, null, "Unknown thingUID"); } FirmwareUID firmwareUID = new FirmwareUID(thing.getThingTypeUID(), firmwareVersion); try { firmwareUpdateService.updateFirmware(thing.getUID(), firmwareUID, LocaleUtil.getLocale(language)); } catch (IllegalArgumentException | NullPointerException ex) { return JSONResponse.createResponse(Status.BAD_REQUEST, null, "Unknown thing/firmware id"); } return Response.status(Status.OK).build(); }

Target:
public Response updateFirmware( @HeaderParam(HttpHeaders.ACCEPT_LANGUAGE) @ApiParam(value = "language") String language, @PathParam("thingUID") @ApiParam(value = "thing") String thingUID, @PathParam("firmwareVersion") @ApiParam(value = "version") String firmwareVersion) throws IOException { Thing thing = thingRegistry.get(new ThingUID(thingUID)); if (thing == null) { return getThingNotFoundResponse(thingUID); } FirmwareUID firmwareUID = new FirmwareUID(thing.getThingTypeUID(), firmwareVersion); try { firmwareUpdateService.updateFirmware(thing.getUID(), firmwareUID, LocaleUtil.getLocale(language)); } catch (IllegalArgumentException | NullPointerException | IllegalStateException ex) { return JSONResponse.createResponse(Status.BAD_REQUEST, null, "Firmware update preconditions not satisfied."); } return Response.status(Status.OK).build(); }
Source:
public void init(FilterConfig filterConfig) throws ServletException { List<String> filterParams = Collections.list(filterConfig .getInitParameterNames()); if (null == cachePattern) { for (String paramName : filterParams) { if (CACHE.equals(paramName)) { cachePattern = Pattern.compile(filterConfig .getInitParameter(paramName)); break; } } } if (null == noCachePattern) { for (String paramName : filterParams) { if (NO_CACHE.equals(paramName)) { noCachePattern = Pattern.compile(filterConfig .getInitParameter(paramName)); break; } } } }

Target:
public void init(FilterConfig filterConfig) throws ServletException { if (cachePattern == null) { String cachePatternString = filterConfig.getInitParameter(CACHE); if(cachePatternString != null) { cachePattern = Pattern.compile(filterConfig .getInitParameter(cachePatternString)); } } if (noCachePattern == null) { String noCachePatternString = filterConfig.getInitParameter(NO_CACHE); if(noCachePatternString != null) { noCachePattern = Pattern.compile(filterConfig .getInitParameter(noCachePatternString)); } } }
Source:
public Object[] factory() { List<Object> tests = new ArrayList<>(3 * 2); for (org.infinispan.configuration.cache.TransactionMode txMode : org.infinispan.configuration.cache.TransactionMode.values()) { if (txMode == org.infinispan.configuration.cache.TransactionMode.NONE) { continue; } for (LockingMode lockingMode : LockingMode.values()) { tests.add(new TxFunctionalTest().transactionMode(txMode).lockingMode(lockingMode)); } } return tests.toArray(); }

Target:
public Object[] factory() { return Arrays.stream(org.infinispan.configuration.cache.TransactionMode.values()) .filter(tMode -> tMode != org.infinispan.configuration.cache.TransactionMode.NONE) .flatMap(txMode -> Arrays.stream(LockingMode.values()) .map(lockingMode -> new TxFunctionalTest() .transactionMode(txMode) .lockingMode(lockingMode))) .toArray(); }
Source:
private static List<StartIdentifiedAtlasDbTransactionResponse> getStartTransactionResponses( LockLeaseService lockLeaseService, LockWatchEventCache lockWatchEventCache, int numberOfTransactions) { List<StartIdentifiedAtlasDbTransactionResponse> result = new ArrayList<>(); while (result.size() < numberOfTransactions) { try { Optional<IdentifiedVersion> requestedVersion = lockWatchEventCache.lastKnownVersion(); ConjureStartTransactionsResponse response = lockLeaseService.startTransactionsWithWatches( requestedVersion, numberOfTransactions - result.size()); lockWatchEventCache.processStartTransactionsUpdate( response.getTimestamps().stream().boxed().collect(Collectors.toSet()), response.getLockWatchUpdate()); result.addAll(split(response)); if (log.isDebugEnabled()) { Optional<LockWatchStateUpdate.Success> successfulUpdate = response.getLockWatchUpdate() .accept(new LockWatchStateUpdate.Visitor<Optional<LockWatchStateUpdate.Success>>() { @Override public Optional<LockWatchStateUpdate.Success> visit( LockWatchStateUpdate.Success success) { return Optional.of(success); } @Override public Optional<LockWatchStateUpdate.Success> visit( LockWatchStateUpdate.Snapshot snapshot) { return Optional.empty(); } }); successfulUpdate.ifPresent(success -> log.debug("Start transaction batch request and response", SafeArg.of("requestedVersion", requestedVersion), SafeArg.of("responseFirstVersion", Iterables.getFirst(success.events(), null)), SafeArg.of("responseLatestVersion", success.lastKnownVersion()))); } } catch (Throwable t) { unlock(result.stream() .map(response -> response.immutableTimestamp().getLock()) .collect(Collectors.toSet()), lockLeaseService); throw Throwables.throwUncheckedException(t); } } return result; }

Target:
private static List<StartIdentifiedAtlasDbTransactionResponse> getStartTransactionResponses( LockLeaseService lockLeaseService, LockWatchEventCache lockWatchEventCache, int numberOfTransactions) { List<StartIdentifiedAtlasDbTransactionResponse> result = new ArrayList<>(); while (result.size() < numberOfTransactions) { try { Optional<IdentifiedVersion> requestedVersion = lockWatchEventCache.lastKnownVersion(); ConjureStartTransactionsResponse response = lockLeaseService.startTransactionsWithWatches( requestedVersion, numberOfTransactions - result.size()); lockWatchEventCache.processStartTransactionsUpdate( response.getTimestamps().stream().boxed().collect(Collectors.toSet()), response.getLockWatchUpdate()); result.addAll(split(response)); LockWatchLogUtility.logTransactionEvents(requestedVersion, response.getLockWatchUpdate()); } catch (Throwable t) { unlock(result.stream() .map(response -> response.immutableTimestamp().getLock()) .collect(Collectors.toSet()), lockLeaseService); throw Throwables.throwUncheckedException(t); } } return result; }
Source:
public void testChangeUserPasswordH2DB() throws Exception { int httpsPort = Integer.parseInt(FrameworkConstants.SERVER_DEFAULT_HTTPS_PORT) + portOffset; String url = context.getContextUrls().getBackEndUrl(); String backendURL = url.replaceAll("(:\\d+)", ":" + httpsPort); String loginStatusString = loginLogoutUtil.login("admin", "admin123".toCharArray(), backendURL); assertTrue(loginStatusString.contains("JSESSIONID"), "Unsuccessful login"); }

Target:
public void testChangeUserPasswordH2DB() throws Exception { int httpsPort = Integer.parseInt(FrameworkConstants.SERVER_DEFAULT_HTTPS_PORT) + portOffset; String url = context.getContextUrls().getBackEndUrl(); String backendURL = url.replaceAll("(:\\d+)", ":" + httpsPort); String loginStatusString = loginLogoutUtil.login("admin", String.valueOf(userNewPassword).toCharArray(), backendURL); assertTrue(loginStatusString.contains("JSESSIONID"), "Unsuccessful login"); }
Source:
private void updateTaskStatuses( Map<Guid, Map<Guid, AsyncTaskStatus>> poolsAllTasksMap) { for (SPMTask task : _tasks.values()) { if (task.getShouldPoll()) { Map<Guid, AsyncTaskStatus> asyncTasksForPoolMap = poolsAllTasksMap .get(task.getStoragePoolID()); if (asyncTasksForPoolMap != null) { AsyncTaskStatus cachedAsyncTaskStatus = asyncTasksForPoolMap .get(task.getVdsmTaskId()); log.debug("Updating task of command: with id: to status: {}.", task.getParameters().getDbAsyncTask().getActionType(), task.getCommandId(), cachedAsyncTaskStatus); task.updateTask(cachedAsyncTaskStatus); } } else { log.debug("Not updating task of command: with id: and status: {}.", task.getParameters().getDbAsyncTask().getActionType(), task.getCommandId(), task.getLastTaskStatus()); } } }

Target:
private void updateTaskStatuses( Map<Guid, Map<Guid, AsyncTaskStatus>> poolsAllTasksMap) { for (SPMTask task : _tasks.values()) { if (task.getShouldPoll()) { Map<Guid, AsyncTaskStatus> asyncTasksForPoolMap = poolsAllTasksMap .get(task.getStoragePoolID()); if (asyncTasksForPoolMap != null) { AsyncTaskStatus cachedAsyncTaskStatus = asyncTasksForPoolMap .get(task.getVdsmTaskId()); log.debug("Updating task of command with id '{}' to status '{}'.", task.getParameters().getDbAsyncTask().getActionType(), task.getCommandId(), cachedAsyncTaskStatus); task.updateTask(cachedAsyncTaskStatus); } } else { log.debug("Not updating task of command with id '{}' and status '{}'.", task.getParameters().getDbAsyncTask().getActionType(), task.getCommandId(), task.getLastTaskStatus()); } } }
Source:
private String getDisplayValue(String value, String name, Map<String, ListItem> map, String def, XWikiContext context) { ListItem item = map.get(value); String displayValue; if (item == null) { displayValue = def; } else { displayValue = item.getValue(); } if ((context == null) || (context.getWiki() == null)) { return displayValue; } String msgname = getFieldFullName() + "_" + value; String newresult = localizePlain(msgname); String syntax = context.getDoc().getSyntax().toIdString(); if (newresult == null) { msgname = "option_" + name + "_" + value; newresult = localizePlain(msgname); if (newresult == null) { msgname = "option_" + value; newresult = localizePlain(msgname); if (newresult == null) { newresult = context.getDoc().getRenderedInlineContent(displayValue, syntax); } } } else { newresult = context.getDoc().getRenderedInlineContent(newresult, syntax); } return newresult; }

Target:
private String getDisplayValue(String value, String name, Map<String, ListItem> map, String def, XWikiContext context) { ListItem item = map.get(value); String displayValue; if (item == null) { displayValue = def; } else { displayValue = item.getValue(); } if ((context == null) || (context.getWiki() == null)) { return displayValue; } String msgname = getFieldFullName() + "_" + value; String newresult = localizePlain(msgname); if (newresult == null) { msgname = "option_" + name + "_" + value; newresult = localizePlain(msgname); if (newresult == null) { msgname = "option_" + value; newresult = localizePlain(msgname); if (newresult == null) { newresult = displayValue; } } } return newresult; }
Source:
private EObject getInput(boolean restore) { EObject input = inputRef != null ? inputRef.get() : null; if (input == null) { if (getSession(restore) != null && getSession(restore).isOpen() && getURI().hasFragment()) { input = getSession(restore).getTransactionalEditingDomain().getResourceSet().getEObject(getURI(), false); if (input != null) { inputRef = new WeakReference<EObject>(input); } } } return input; }

Target:
private EObject getInput(boolean restore) { EObject input = inputRef != null ? inputRef.get() : null; if (input == null) { Session session = getSession(restore); if (session != null && session.isOpen() && getURI().hasFragment()) { input = session.getTransactionalEditingDomain().getResourceSet().getEObject(getURI(), false); if (input != null) { inputRef = new WeakReference<EObject>(input); } } } return input; }
Source:
public String getQuestionAdditionalInfoHtml(int questionNumber, String additionalInfoId) { StringBuilder optionListHtml = new StringBuilder(); String optionFragmentTemplate = FeedbackQuestionFormTemplates.MSQ_ADDITIONAL_INFO_FRAGMENT; StringBuilder additionalInfo = new StringBuilder(); if (this.isDistributeToRecipients()) { additionalInfo.append(this.getQuestionTypeDisplayName()).append("<br>"); } else if (getNumOfConstSumOptions() > 0) { optionListHtml.append("<ul style=\"list-style-type: disc;margin-left: 20px;\" >"); for (int i = 0; i < getNumOfConstSumOptions(); i++) { String optionFragment = FeedbackQuestionFormTemplates.populateTemplate(optionFragmentTemplate, "${msqChoiceValue}", getConstSumOptions().get(i)); optionListHtml.append(optionFragment); } optionListHtml.append("</ul>"); additionalInfo.append(FeedbackQuestionFormTemplates.populateTemplate( FeedbackQuestionFormTemplates.MSQ_ADDITIONAL_INFO, "${questionTypeName}", this.getQuestionTypeDisplayName(), "${msqAdditionalInfoFragments}", optionListHtml.toString())); } additionalInfo.append(isPointsPerOption() ? "Points per " + (isDistributeToRecipients() ? "recipient" : "option") + ": " + getPoints() : "Total points: " + getPoints()); return FeedbackQuestionFormTemplates.populateTemplate( FeedbackQuestionFormTemplates.FEEDBACK_QUESTION_ADDITIONAL_INFO, "${more}", "[more]", "${less}", "[less]", "${questionNumber}", Integer.toString(questionNumber), "${additionalInfoId}", additionalInfoId, "${questionAdditionalInfo}", additionalInfo.toString()); }

Target:
public String getQuestionAdditionalInfoHtml(int questionNumber, String additionalInfoId) { StringBuilder optionListHtml = new StringBuilder(); String optionFragmentTemplate = FeedbackQuestionFormTemplates.MSQ_ADDITIONAL_INFO_FRAGMENT; StringBuilder additionalInfo = new StringBuilder(); if (distributeToRecipients) { additionalInfo.append(getQuestionTypeDisplayName()).append("<br>"); } else if (numOfConstSumOptions > 0) { optionListHtml.append("<ul style=\"list-style-type: disc;margin-left: 20px;\" >"); for (int i = 0; i < numOfConstSumOptions; i++) { String optionFragment = Templates.populateTemplate(optionFragmentTemplate, "${msqChoiceValue}", constSumOptions.get(i)); optionListHtml.append(optionFragment); } optionListHtml.append("</ul>"); additionalInfo.append(Templates.populateTemplate( FeedbackQuestionFormTemplates.MSQ_ADDITIONAL_INFO, "${questionTypeName}", getQuestionTypeDisplayName(), "${msqAdditionalInfoFragments}", optionListHtml.toString())); } additionalInfo.append(pointsPerOption ? "Points per " + (distributeToRecipients ? "recipient" : "option") + ": " + points : "Total points: " + points); return Templates.populateTemplate( FeedbackQuestionFormTemplates.FEEDBACK_QUESTION_ADDITIONAL_INFO, "${more}", "[more]", "${less}", "[less]", "${questionNumber}", Integer.toString(questionNumber), "${additionalInfoId}", additionalInfoId, "${questionAdditionalInfo}", additionalInfo.toString()); }
Source:
public Optional<ResourceID> failAllocation(final AllocationID allocationID, final Exception cause) { componentMainThreadExecutor.assertRunningInMainThread(); final PendingRequest pendingRequest = pendingRequests.getKeyB(allocationID); if (pendingRequest != null) { if (isBatchRequestAndFailureCanBeIgnored(pendingRequest, cause)) { log.debug("Ignoring allocation failure for batch slot request {}.", pendingRequest.getSlotRequestId()); } else { pendingRequests.removeKeyB(allocationID); failPendingRequest(pendingRequest, cause); } return Optional.empty(); } else { return tryFailingAllocatedSlot(allocationID, cause); } }

Target:
public Optional<ResourceID> failAllocation(final AllocationID allocationID, final Exception cause) { componentMainThreadExecutor.assertRunningInMainThread(); final PendingRequest pendingRequest = pendingRequests.getValueByKeyB(allocationID); if (pendingRequest != null) { if (isBatchRequestAndFailureCanBeIgnored(pendingRequest, cause)) { log.debug("Ignoring allocation failure for batch slot request {}.", pendingRequest.getSlotRequestId()); } else { removePendingRequest(pendingRequest.getSlotRequestId()); failPendingRequest(pendingRequest, cause); } return Optional.empty(); } else { return tryFailingAllocatedSlot(allocationID, cause); } }
Source:
public boolean addAccountUpdateConsumer(Consumer<Collection<Account>> accountUpdateConsumer) { checkOpen(); Objects.requireNonNull(accountUpdateConsumer, "accountUpdateConsumer to subscribe cannot be null"); return accountUpdateConsumers.add(accountUpdateConsumer); }

Target:
public boolean addAccountUpdateConsumer(Consumer<Collection<Account>> accountUpdateConsumer) { checkOpen(); Objects.requireNonNull(accountUpdateConsumer, "accountUpdateConsumer to subscribe cannot be null"); return true; }
Source:
private void addBuyOrder(Order order) { if (this.buyOrders.containsKey(order.getStockSymbol())){ ArrayList<Order> list =buyOrders.get(order.getStockSymbol()); list.add(order); } else{ ArrayList<Order> list = new ArrayList<Order>(); list.add(order); this.buyOrders.put(order.getStockSymbol(), list); } }

Target:
private void addBuyOrder(Order order) { if (this.buyOrders.containsKey(order.getStockSymbol())){ ArrayList<Order> buyOrderList =buyOrders.get(order.getStockSymbol()); buyOrderList.add(order); } else{ ArrayList<Order> buyOrderList = new ArrayList<Order>(); buyOrderList.add(order); this.buyOrders.put(order.getStockSymbol(), buyOrderList); } }
Source:
@Override public void setAlpha(int alpha) { image.setAlpha(alpha); }

Target:
@Override public void setAlpha(int alpha) { if (placeholder != null) { placeholder.setAlpha(alpha); } image.setAlpha(alpha); }
Source:
public ColumnStatistics build() { return new ColumnStatistics(nullsFraction, distinctValuesCount, dataSize, lowValue, highValue); }

Target:
public ColumnStatistics build() { return new ColumnStatistics(nullsFraction, distinctValuesCount, dataSize, range); }
Source:
private void setupServer() throws Exception { LOG.info("foobar"); _embeddedZookeeper = new EmbeddedZookeeper(); _embeddedZookeeper.startup(); setupDatastreamServer(); }

Target:
private void setupServer() throws Exception { _embeddedZookeeper = new EmbeddedZookeeper(); _embeddedZookeeper.startup(); setupDatastreamServer(); }
Source:
public int getUnsortedEncodedKeyComponentHashCode(@Nullable Float key) { return Objects.hashCode(DimensionHandlerUtils.nullToZero(key)); }

Target:
public int getUnsortedEncodedKeyComponentHashCode(@Nullable Float key) { return DimensionHandlerUtils.nullToZero(key).hashCode(); }
Source:
public void addMeter( @Identification final String organisationIdentification, @Identification final String deviceIdentification, final String correlationUid, final com.alliander.osgp.domain.core.valueobjects.smartmetering.SmartMeteringDevice smartMeteringDeviceValueObject, final String messageType) throws FunctionalException { LOGGER.info("addMeter for organisationIdentification: for deviceIdentification: {}", organisationIdentification, deviceIdentification); SmartMeteringDevice device = this.smartMeteringDeviceRepository .findByDeviceIdentification(deviceIdentification); if (device == null) { device = this.installationMapper.map(smartMeteringDeviceValueObject, SmartMeteringDevice.class); final ProtocolInfo protocolInfo = this.protocolInfoRepository.findByProtocolAndProtocolVersion("DSMR", smartMeteringDeviceValueObject.getDSMRVersion()); device.updateProtocol(protocolInfo); this.smartMeteringDeviceRepository.save(device); } else { throw new FunctionalException(FunctionalExceptionType.EXISTING_DEVICE, ComponentType.DOMAIN_SMART_METERING); } final com.alliander.osgp.domain.core.valueobjects.smartmetering.SmartMeteringDevice smartMeteringDevicDto = this.installationMapper .map(smartMeteringDeviceValueObject, com.alliander.osgp.domain.core.valueobjects.smartmetering.SmartMeteringDevice.class); this.osgpCoreRequestMessageSender.send(new RequestMessage(correlationUid, organisationIdentification, deviceIdentification, smartMeteringDevicDto), messageType); }

Target:
public void addMeter( @Identification final String organisationIdentification, @Identification final String deviceIdentification, final String correlationUid, final com.alliander.osgp.domain.core.valueobjects.smartmetering.SmartMeteringDevice smartMeteringDeviceValueObject, final String messageType) throws FunctionalException { LOGGER.info("addMeter for organisationIdentification: for deviceIdentification: {}", organisationIdentification, deviceIdentification); SmartMeteringDevice device = this.smartMeteringDeviceRepository .findByDeviceIdentification(deviceIdentification); if (device == null) { device = this.installationMapper.map(smartMeteringDeviceValueObject, SmartMeteringDevice.class); final ProtocolInfo protocolInfo = this.protocolInfoRepository.findByProtocolAndProtocolVersion("DSMR", smartMeteringDeviceValueObject.getDSMRVersion()); if (protocolInfo == null) { throw new FunctionalException(FunctionalExceptionType.UNKNOWN_PROTOCOL_NAME_OR_VERSION, ComponentType.DOMAIN_SMART_METERING); } device.updateProtocol(protocolInfo); this.smartMeteringDeviceRepository.save(device); } else { throw new FunctionalException(FunctionalExceptionType.EXISTING_DEVICE, ComponentType.DOMAIN_SMART_METERING); } final com.alliander.osgp.dto.valueobjects.smartmetering.SmartMeteringDevice smartMeteringDevicDto = this.installationMapper .map(smartMeteringDeviceValueObject, com.alliander.osgp.dto.valueobjects.smartmetering.SmartMeteringDevice.class); this.osgpCoreRequestMessageSender.send(new RequestMessage(correlationUid, organisationIdentification, deviceIdentification, smartMeteringDevicDto), messageType); }
Source:
public void setup(OperatorContext context) { ((ExpirableHdfsBucketStore<Object>)bucketManager.getBucketStore()).setConfiguration(context.getId(), context.getValue(DAG.APPLICATION_PATH), partitionKeys, partitionMask); super.setup(context); }

Target:
public void setup(OperatorContext context) { Preconditions.checkArgument(bucketManager.getBucketStore() instanceof ExpirableHdfsBucketStore); ExpirableHdfsBucketStore<Object> store = (ExpirableHdfsBucketStore<Object>)bucketManager.getBucketStore(); store.setConfiguration(context.getId(), context.getValue(DAG.APPLICATION_PATH), partitionKeys, partitionMask); super.setup(context); }
Source:
public int partition(String topic, Object key, byte[] keyBytes, Object value, byte[] valueBytes, Cluster cluster) { return partition(topic, key, keyBytes, value, valueBytes, cluster, 0); }

Target:
public int partition(String topic, Object key, byte[] keyBytes, Object value, byte[] valueBytes, Cluster cluster) { return partition(topic, key, keyBytes, value, valueBytes, cluster, cluster.partitionsForTopic(topic).size()); }
Source:
public void mp4SampleWithProfile5DolbyVision() throws Exception { ExtractorAsserts.assertBehavior(Mp4Extractor::new, "mp4/dvhe_05_09.mp4", simulationConfig); }

Target:
public void mp4SampleWithProfile5DolbyVision() throws Exception { ExtractorAsserts.assertBehavior(Mp4Extractor::new, "mp4/dvhe_05_05.mp4", simulationConfig); }