auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { super.channelRead(ctx, msg); }

Target:
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { ReferenceCountUtil.release(msg); }
Source:
public void appendPage(Page page) { Block temporalBlock = temporalColumnIndex.isPresent() ? page.getBlock(temporalColumnIndex.getAsInt()) : null; Page bucketArgs = bucketFunction.isPresent() ? getBucketArgsPage(page) : null; for (int position = 0; position < page.getPositionCount(); position++) { int bucket = bucketFunction.isPresent() ? bucketFunction.get().getBucket(bucketArgs, position) : 0; int day = temporalFunction.isPresent() ? temporalFunction.get().getDay(session, temporalBlock, position) : 0; long partition = (((long) bucket) << 32) | (day & 0xFFFF_FFFFL); PageStore store = pageStores.get(partition); if (store == null) { OptionalInt bucketNumber = bucketFunction.isPresent() ? OptionalInt.of(bucket) : OptionalInt.empty(); PageBuffer buffer = createPageBuffer(bucketNumber); store = new PageStore(buffer, columnTypes); pageStores.put(partition, store); } store.appendPosition(page, position); } flushIfNecessary(); }

Target:
public void appendPage(Page page) { Block temporalBlock = temporalColumnIndex.isPresent() ? page.getBlock(temporalColumnIndex.getAsInt()) : null; Page bucketArgs = bucketFunction.isPresent() ? getBucketArgsPage(page) : null; for (int position = 0; position < page.getPositionCount(); position++) { int bucket = bucketFunction.isPresent() ? bucketFunction.get().getBucket(bucketArgs, position) : 0; int day = temporalColumnType.isPresent() ? temporalFunction.getDay(temporalColumnType.get(), temporalBlock, position) : 0; long partition = (((long) bucket) << 32) | (day & 0xFFFF_FFFFL); PageStore store = pageStores.get(partition); if (store == null) { OptionalInt bucketNumber = bucketFunction.isPresent() ? OptionalInt.of(bucket) : OptionalInt.empty(); PageBuffer buffer = createPageBuffer(bucketNumber); store = new PageStore(buffer, columnTypes); pageStores.put(partition, store); } store.appendPosition(page, position); } flushIfNecessary(); }
Source:
public int daysBetween(LocalDate startInclusive, LocalDate endExclusive) { ArgChecker.inOrderOrEqual(startInclusive, endExclusive, "startInclusive", "endExclusive"); try { int startIndex = (startInclusive.getYear() - startYear) * 12 + startInclusive.getMonthValue() - 1; int endIndex = (endExclusive.getYear() - startYear) * 12 + endExclusive.getMonthValue() - 1; int start = Integer.bitCount(lookup[startIndex] & (BIT_MASK_ALL_ONES << (startInclusive.getDayOfMonth() - 1))); int missingEnd = Integer.bitCount(lookup[endIndex] & (BIT_MASK_ALL_ONES << endExclusive.getDayOfMonth() - 1)); if (startIndex == endIndex) { return start - missingEnd; } int end = Integer.bitCount(lookup[endIndex]) - missingEnd; long count = start + end; for (int i = startIndex + 1; i < endIndex; i++) { count += Integer.bitCount(lookup[i]); } return Math.toIntExact(count); } catch (ArrayIndexOutOfBoundsException ex) { return daysBetweenOutOfRange(startInclusive, endExclusive); } }

Target:
public int daysBetween(LocalDate startInclusive, LocalDate endExclusive) { ArgChecker.inOrderOrEqual(startInclusive, endExclusive, "startInclusive", "endExclusive"); try { int startIndex = (startInclusive.getYear() - startYear) * 12 + startInclusive.getMonthValue() - 1; int endIndex = (endExclusive.getYear() - startYear) * 12 + endExclusive.getMonthValue() - 1; int start = Integer.bitCount(lookup[startIndex] & (BIT_MASK_ALL_ONES << (startInclusive.getDayOfMonth() - 1))); int missingEnd = Integer.bitCount(lookup[endIndex] & (BIT_MASK_ALL_ONES << (endExclusive.getDayOfMonth() - 1))); if (startIndex == endIndex) { return start - missingEnd; } int end = Integer.bitCount(lookup[endIndex]) - missingEnd; int count = start + end; for (int i = startIndex + 1; i < endIndex; i++) { count += Integer.bitCount(lookup[i]); } return count; } catch (ArrayIndexOutOfBoundsException ex) { return daysBetweenOutOfRange(startInclusive, endExclusive); } }
Source:
public void testMoveNodeWithSelfEdge() { diagram.addNode(aClassNode, new Point2D.Double(5, 7)); diagram.addEdge(aggrEdge, new Point2D.Double(8, 10), new Point2D.Double(12, 9)); double old_y = aggrEdge.getBounds().getY(); double old_x = aggrEdge.getBounds().getX(); aList.add(aClassNode); for(GraphElement element: aList) { if(element instanceof Node) { ((Node) element).translate(10, 10); } } assertTrue(15 == aClassNode.getBounds().getX()); assertTrue(17 == aClassNode.getBounds().getY()); assertEquals(aClassNode, aggrEdge.getStart()); assertEquals(aClassNode, aggrEdge.getEnd()); assertTrue((10+old_x) == aggrEdge.getBounds().getX()); assertTrue((10+old_y) == aggrEdge.getBounds().getY()); }

Target:
public void testMoveNodeWithSelfEdge() { aDiagram.addNode(aClassNode, new Point2D.Double(5, 7)); aDiagram.addEdge(aAggregationEdge, new Point2D.Double(8, 10), new Point2D.Double(12, 9)); Rectangle2D oldAggregationEdgeBounds = aAggregationEdge.getBounds(); aList.add(aClassNode); for(GraphElement element: aList) { if(element instanceof Node) { ((Node) element).translate(10, 10); } } assertEquals(new Rectangle2D.Double(15, 17, 100, 60), aClassNode.getBounds()); assertEquals(aClassNode, aAggregationEdge.getStart()); assertEquals(aClassNode, aAggregationEdge.getEnd()); assertFalse(oldAggregationEdgeBounds == aAggregationEdge.getBounds()); }
Source:
public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); searchParams = (SearchView) view.findViewById(R.id.params_filter); searchParams.setOnQueryTextListener(new SearchView.OnQueryTextListener() { @Override public boolean onQueryTextSubmit(String s) { filterInput(s); return false; } @Override public boolean onQueryTextChange(String s) { filterInput(s); return true; } }); searchParams.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { searchParams.findViewById(android.support.v7.appcompat.R.id.search_button).callOnClick(); } }); mLoadingProgress = (ProgressBar) view.findViewById(R.id.reload_progress); mLoadingProgress.setVisibility(View.GONE); }

Target:
public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); searchParams = (SearchView) view.findViewById(R.id.params_filter); searchParams.setOnQueryTextListener(new SearchView.OnQueryTextListener() { @Override public boolean onQueryTextSubmit(String s) { filterInput(s); return false; } @Override public boolean onQueryTextChange(String s) { filterInput(s); return true; } }); searchButton = searchParams.findViewById(android.support.v7.appcompat.R.id.search_button); searchParams.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { searchButton.callOnClick(); } }); mLoadingProgress = (ProgressBar) view.findViewById(R.id.reload_progress); mLoadingProgress.setVisibility(View.GONE); }
Source:
private ListenableFuture<ResultSet> selectPeersFuture(final Connection connection) { if (isPeersV2) { DefaultResultSetFuture peersV2Future = new DefaultResultSetFuture( null, cluster.protocolVersion(), new Requests.Query(SELECT_PEERS_V2)); connection.write(peersV2Future); final SettableFuture<ResultSet> peersFuture = SettableFuture.create(); GuavaCompatibility.INSTANCE.addCallback( peersV2Future, new FutureCallback<ResultSet>() { @Override public void onSuccess(ResultSet result) { peersFuture.set(result); } @Override public void onFailure(Throwable t) { if (t instanceof InvalidQueryException || t instanceof ServerError) { isPeersV2 = false; MoreFutures.propagateFuture(peersFuture, selectPeersFuture(connection)); } else { peersFuture.setException(t); } } }); return peersFuture; } else { DefaultResultSetFuture peersFuture = new DefaultResultSetFuture( null, cluster.protocolVersion(), new Requests.Query(SELECT_PEERS)); connection.write(peersFuture); return peersFuture; } }

Target:
private ListenableFuture<ResultSet> selectPeersFuture(final Connection connection) { if (isPeersV2) { DefaultResultSetFuture peersV2Future = new DefaultResultSetFuture( null, cluster.protocolVersion(), new Requests.Query(SELECT_PEERS_V2)); connection.write(peersV2Future); final SettableFuture<ResultSet> peersFuture = SettableFuture.create(); GuavaCompatibility.INSTANCE.addCallback( peersV2Future, new FutureCallback<ResultSet>() { @Override public void onSuccess(ResultSet result) { peersFuture.set(result); } @Override public void onFailure(Throwable t) { if (t instanceof InvalidQueryException || (t instanceof ServerError && t.getMessage().contains("Unknown keyspace/cf pair (system.peers_v2)"))) { isPeersV2 = false; MoreFutures.propagateFuture(peersFuture, selectPeersFuture(connection)); } else { peersFuture.setException(t); } } }); return peersFuture; } else { DefaultResultSetFuture peersFuture = new DefaultResultSetFuture( null, cluster.protocolVersion(), new Requests.Query(SELECT_PEERS)); connection.write(peersFuture); return peersFuture; } }
Source:
public static Bundle updateBundleConfig(Connection connection, Bundle bundle) throws SQLException { final String sql = "UPDATE portti_view_bundle_seq SET config=? WHERE bundle_id=? AND view_id=?"; try (final PreparedStatement statement = connection.prepareStatement(sql)) { statement.setString(1, bundle.config); statement.setLong(2, bundle.bundle); statement.setLong(3, bundle.view); statement.execute(); } return null; }

Target:
private void updateBundleConfig(Connection connection, Bundle bundle) throws SQLException { final String sql = "UPDATE portti_view_bundle_seq SET config=? WHERE bundle_id=? AND view_id=?"; try (final PreparedStatement statement = connection.prepareStatement(sql)) { statement.setString(1, bundle.config); statement.setLong(2, bundle.bundle); statement.setLong(3, bundle.view); statement.execute(); } }
Source:
Options(ReadableMap options) { if (options.getString("mediaType").equals("video")) { pickVideo = true; } includeBase64 = options.getBoolean("includeBase64"); String videoQualityString = options.getString("videoQuality"); if(!TextUtils.isEmpty(videoQualityString) && videoQualityString.toLowerCase() != "high") { videoQuality = 0; } quality = (int) (options.getDouble("quality") * 100); maxHeight = options.getInt("maxHeight"); maxWidth = options.getInt("maxWidth"); saveToPhotos = options.getBoolean("saveToPhotos"); durationLimit = options.getInt("durationLimit"); }

Target:
Options(ReadableMap options) { if (options.getString("mediaType").equals("video")) { pickVideo = true; } includeBase64 = options.getBoolean("includeBase64"); String videoQualityString = options.getString("videoQuality"); if(!TextUtils.isEmpty(videoQualityString) && !videoQualityString.toLowerCase().equals("high")) { videoQuality = 0; } quality = (int) (options.getDouble("quality") * 100); maxHeight = options.getInt("maxHeight"); maxWidth = options.getInt("maxWidth"); saveToPhotos = options.getBoolean("saveToPhotos"); durationLimit = options.getInt("durationLimit"); }
Source:
public List<String> getIndices(ElasticsearchTableDescription tableDescription) { if (tableDescription.getIndexExactMatch()) { return ImmutableList.of(tableDescription.getIndex()); } TransportClient client = clients.get(tableDescription.getClusterName()); verify(client != null); return Arrays.stream(client.admin().indices().getIndex(new GetIndexRequest()).actionGet(timeout.toMillis()).getIndices()) .filter(index -> index.startsWith(tableDescription.getIndex())) .collect(toImmutableList()); }

Target:
public List<String> getIndices(ElasticsearchTableDescription tableDescription) { if (tableDescription.getIndexExactMatch()) { return ImmutableList.of(tableDescription.getIndex()); } TransportClient client = clients.get(tableDescription.getClusterName()); verify(client != null, "TransportClient should not be null"); String[] indices = client.admin() .indices() .getIndex(new GetIndexRequest()) .actionGet(timeout.toMillis()) .getIndices(); return Arrays.stream(indices) .filter(index -> index.startsWith(tableDescription.getIndex())) .collect(toImmutableList()); }
Source:
public TrackingToken lowerBound(TrackingToken other) { Assert.isTrue(other instanceof MultiSourceTrackingToken, () -> "Incompatible token type provided."); MultiSourceTrackingToken otherMultiToken = (MultiSourceTrackingToken) other; Assert.isTrue(otherMultiToken.trackingTokens.size() == this.trackingTokens.size(), () -> "MultiSourceTrackingTokens contain different number of member tokens"); Map<String, TrackingToken> tokenMap = new HashMap<>(); otherMultiToken.trackingTokens.forEach((key, otherToken) -> tokenMap.put(key, trackingTokens.get(key).lowerBound(otherToken)) ); return new MultiSourceTrackingToken(tokenMap); }

Target:
public TrackingToken lowerBound(TrackingToken other) { Assert.isTrue(other instanceof MultiSourceTrackingToken, () -> "Incompatible token type provided."); MultiSourceTrackingToken otherMultiToken = (MultiSourceTrackingToken) other; Assert.isTrue(otherMultiToken.trackingTokens.keySet().equals(this.trackingTokens.keySet()), () -> "MultiSourceTrackingTokens contain different keys"); Map<String, TrackingToken> tokenMap = new HashMap<>(); otherMultiToken.trackingTokens.forEach((tokenSourceName, otherToken) -> tokenMap.put(tokenSourceName, trackingTokens.get(tokenSourceName).lowerBound(otherToken)) ); return new MultiSourceTrackingToken(tokenMap); }
Source:
public RocksDbStorageConfiguration(VoldemortConfig config) { this.voldemortconfig = config; Props props = config.getAllProps(); this.lockStripes = props.getInt("rocksdb.lock.stripes", 50); compactionStyle = CompactionStyle.valueOf(props.getString("rocksdb.options.compactionStyle", CompactionStyle.UNIVERSAL.toString())); compressionType = CompressionType.valueOf(props.getString("rocksdb.options.compressionType", CompressionType.SNAPPY_COMPRESSION.toString())); maxBackgroundCompactions = props.getInt("rocksdb.options.maxBackgroundCompactions", 10); maxBackgroundFlushes = props.getInt("rocksdb.options.maxBackgroundFlushes", 1); maxBytesForLevelBase = props.getLong("rocksdb.options.maxBytesForLevelBase", (10 * SizeUnit.MB)); maxWriteBufferNumber = props.getInt("rocksdb.options.maxWriteBufferNumber", 3); statsDumpPeriodSec = props.getInt("rocksdb.options.statsDumpPeriodSec", 3600); targetFileSizeBase = props.getLong("rocksdb.options.targetFileSizeBase", (2 * SizeUnit.MB)); targetFileSizeMultiplier = props.getInt("rocksdb.options.targetFileSizeMultiplier", 1); writeBufferSize = props.getLong("rocksdb.options.writeBufferSize", (4 * SizeUnit.MB)); }

Target:
public RocksDbStorageConfiguration(VoldemortConfig config) { this.voldemortconfig = config; this.lockStripes = config.getAllProps().getInt("rocksdb.lock.stripes", 50); }
Source:
DateTimeBuilder assignToSubBuilders( Field field, AnyValue value ) { if ( field == Field.date || field.field != null && field.field.isDateBased() ) { if ( date == null ) { date = new ConstructDate(); } date = date.assign( field, value ); } else if ( field == Field.time || field.field != null && field.field.isTimeBased() ) { if ( time == null ) { time = new ConstructTime(); } time.assign( field, value ); } else { throw new UnsupportedTemporalUnitException( "This method should not be used for any fields the DateBuilder or TimeBuilder can't handle" ); } return this; }

Target:
DateTimeBuilder assignToSubBuilders( Field field, AnyValue value ) { if ( field == Field.date || field.field != null && field.field.isDateBased() ) { if ( date == null ) { date = new ConstructDate(); } date = date.assign( field, value ); } else if ( field == Field.time || field.field != null && field.field.isTimeBased() ) { if ( time == null ) { time = new ConstructTime(); } time.assign( field, value ); } else { throw new IllegalStateException( "This method should not be used for any fields the DateBuilder or TimeBuilder can't handle" ); } return this; }
Source:
public Loader<Cursor> onCreateLoader(int i, Bundle bundle) { Uri uri = Contract.TruckEntry.CONTENT_URI.buildUpon() .appendQueryParameter(Contract.TruckEntry.COLUMN_IS_SERVING, "1").build(); return CursorLoaderFactory.create(getActivity(), uri, ActiveTrucksQuery.PROJECTION); }

Target:
public Loader<Cursor> onCreateLoader(int i, Bundle bundle) { Uri uri = Contract.TruckEntry.buildServingTrucks(); return CursorLoaderFactory.create(getActivity(), uri, ActiveTrucksQuery.PROJECTION); }
Source:
public static String toAnnotationName(String key) { if (!key.startsWith(X_OPT_PREFIX.toString())) { if (key.startsWith(AMQ_PROPERTY_PREFIX.toString())) { return X_OPT_PREFIX.toString().concat(key.substring(AMQ_PROPERTY_PREFIX.toString().length()).replace('_', '-')); } return key; } return key; }

Target:
public static String toAnnotationName(String key) { if (!key.startsWith(X_OPT_PREFIX.toString())) { if (key.startsWith(AMQ_PROPERTY_PREFIX)) { return X_OPT_PREFIX.concat(key.substring(AMQ_PROPERTY_PREFIX.length()).replace('_', '-')); } return key; } return key; }
Source:
public void evaluate_shouldReturnAUniquePatientNumber() throws Exception { Patient patient = Context.getPatientService().getPatient(8); MohUniquePatientNumberRule mohUniquePatientNumberRule = new MohUniquePatientNumberRule(); String result = mohUniquePatientNumberRule.evaluate(null, patient.getId(), null).toString(); String expectedResult = "not found"; Assert.assertEquals("The patient has no CCC Number",expectedResult,result ); Patient patient1 = Context.getPatientService().getPatient(6); AdministrationService ams = Context.getAdministrationService(); GlobalProperty globalProperty = new GlobalProperty(); globalProperty.setProperty("mflgenerator.mfl"); globalProperty.setPropertyValue("CCC Number"); ams.saveGlobalProperty(globalProperty); PatientIdentifierType pit = MohCacheUtils.getPatientIdentifierType(ams.getGlobalProperty("mflgenerator.mfl")); PatientIdentifier pi = new PatientIdentifier("11740-00001", pit, null); pi.setPatient(patient1); PatientIdentifier pidtest=patient1.getPatientIdentifier(pit); String result1 = mohUniquePatientNumberRule.evaluate(null, patient1.getId(), null).toString(); String expectedResult1 = "11740-00001"; Assert.assertEquals("The two identifiers are not equal",expectedResult1,result1); }

Target:
public void evaluate_shouldReturnAUniquePatientNumber() throws Exception { MohUniquePatientNumberRule mohUniquePatientNumberRule = new MohUniquePatientNumberRule(); PatientService patientService = Context.getPatientService(); Patient patient = patientService.getPatient(8); Result result = mohUniquePatientNumberRule.evaluate(null, patient.getId(), null); Result expectedResult = new Result("not found"); Assert.assertEquals("The patient has no CCC Number",expectedResult,result ); }
Source:
public Description matchAnnotation(AnnotationTree tree, VisitorState state) { if (nullableAnnotationMatcher.matches(tree, state)) { if (isPrimitiveType().matches(getAnnotatedNode(state), state)) { return describeMatch(tree, SuggestedFix.delete(tree)); } } return Description.NO_MATCH; }

Target:
public Description matchAnnotation(AnnotationTree tree, VisitorState state) { if (NULLABLE_ANNOTATION_MATCHER.matches(tree, state)) { Tree annotatedNode = getAnnotatedNode(state); if (IS_PRIMITIVE_TYPE_MATCHER.matches(annotatedNode, state)) { return describeMatch(tree, SuggestedFix.delete(tree)); } else if (isMethod(annotatedNode) && !METHOD_RETURNS_NON_PRIMITIVE_TYPE_MATCHER .matches((MethodTree) annotatedNode, state)) { return describeMatch(tree, SuggestedFix.delete(tree)); } } return Description.NO_MATCH; }
Source:
public List<IRepositoryViewObject> getSortVersion(List<IRepositoryViewObject> versions) { List<IRepositoryViewObject> temp = new ArrayList<IRepositoryViewObject>(); temp.addAll(versions); Collections.sort(temp, new Comparator<IRepositoryViewObject>() { @Override public int compare(IRepositoryViewObject o1, IRepositoryViewObject o2) { String version1 = o1.getVersion(); String version2 = o2.getVersion(); if(version1 != null && version2 != null) { try { float v1 = Float.parseFloat(version1); float v2 = Float.parseFloat(version2); if(v1 > v2) { return 1; }else if(v1 < v2) { return -1; } } catch (Exception e) { return 0; } } return 0; } }); return temp; }

Target:
public List<IRepositoryViewObject> getSortVersion(List<IRepositoryViewObject> versions) { List<IRepositoryViewObject> temp = new ArrayList<IRepositoryViewObject>(); temp.addAll(versions); Collections.sort(temp, new Comparator<IRepositoryViewObject>() { @Override public int compare(IRepositoryViewObject o1, IRepositoryViewObject o2) { String version1 = o1.getVersion(); String version2 = o2.getVersion(); if(version1 != null && version2 != null) { return new Version(version1).compareTo(new Version(version2)); } return 0; } }); return temp; }
Source:
public StartContainerCmd createHostConfig(StartContainerCmd hostConfig) { hostConfig.withPortBindings(Iterables.toArray(getPortMappings(), PortBinding.class)); hostConfig.withPublishAllPorts(bindAllPorts); hostConfig.withPrivileged(this.privileged); if( dnsHosts.length > 0 ) hostConfig.withDns(dnsHosts); for( String _volume : volumes){ String __volume[] = _volume.split(":",2); if(__volume.length==2) hostConfig.withBinds(new Bind(__volume[0],new Volume(__volume[1]))); else hostConfig.withBinds(new Bind(_volume,new Volume(_volume))); } List<LxcConf> lxcConfs = getLxcConf(); if (!lxcConfs.isEmpty()) { hostConfig.withLxcConf(Iterables.toArray(lxcConfs, LxcConf.class)); } if(!Strings.isNullOrEmpty(volumesFrom) ) hostConfig.withVolumesFrom(volumesFrom); return hostConfig; }

Target:
public StartContainerCmd createHostConfig(StartContainerCmd hostConfig) { hostConfig.withPortBindings(Iterables.toArray(getPortMappings(), PortBinding.class)); hostConfig.withPublishAllPorts(bindAllPorts); hostConfig.withPrivileged(this.privileged); if( dnsHosts.length > 0 ) hostConfig.withDns(dnsHosts); if(volumesString!=null) { for (String volume : splitAndFilterEmpty(volumesString)) { try { hostConfig.withBinds(Bind.parse(volume)); } catch (IllegalArgumentException e) { LOGGER.log(Level.WARNING,"Cannot create volume "+volume+" when starting host"); } } } List<LxcConf> lxcConfs = getLxcConf(); if (!lxcConfs.isEmpty()) { hostConfig.withLxcConf(Iterables.toArray(lxcConfs, LxcConf.class)); } if(!Strings.isNullOrEmpty(volumesFrom) ) hostConfig.withVolumesFrom(volumesFrom); return hostConfig; }
Source:
private void visitRecordLikeType(ObjectType type) { emit("{"); Iterator<String> it = type.getOwnPropertyNames().iterator(); Boolean isFirst = true; while (it.hasNext()) { String propName = it.next(); if (propName.equals("prototype")) continue; if (isFirst) { isFirst = false; } else { emit(","); } emit(propName); visitTypeDeclaration(type.getPropertyType(propName)); } emit("}"); }

Target:
private void visitRecordLikeType(ObjectType type) { emit("{"); Iterable allProps = type.getOwnPropertyNames(); Iterator<String> it = Iterables.filter(allProps, not(equalTo("prototype"))).iterator(); while (it.hasNext()) { String propName = it.next(); emit(propName); visitTypeDeclaration(type.getPropertyType(propName)); if (it.hasNext()) { emit(","); } } emit("}"); }
Source:
protected MqttAsyncClient createAndConnectClient() throws MqttException, ConfigurationException { StringBuilder serverURI = new StringBuilder(); switch (protocol) { case TCP: serverURI.append((secure ? "ssl://" : "tcp://")); break; case Websockets: serverURI.append((secure ? "wss://" : "ws://")); break; default: throw new ConfigurationException("protocol", "Protocol unknown"); } serverURI.append(host); serverURI.append(":"); serverURI.append(port); Path tmpDir = Paths.get(ConfigConstants.getUserDataFolder()); try { tmpDir = Files.createDirectories(tmpDir.resolve("mqtt").resolve(host)); } catch (IOException e) { throw new MqttException(e); } MqttClientPersistence dataStore = new MqttDefaultFilePersistence(tmpDir.toString()); MqttAsyncClient _client; try { _client = new MqttAsyncClient(serverURI.toString(), clientId, dataStore); } catch (org.eclipse.paho.client.mqttv3.MqttException e) { throw new MqttException(e); } _client.setCallback(clientCallbacks); try { connectionToken = _client.connect(createMqttOptions(), null, connectionCallbacks); logger.info("Starting MQTT broker connection to '{}' with clientid and file store '{}'", host, getClientId(), tmpDir); } catch (org.eclipse.paho.client.mqttv3.MqttException e) { throw new MqttException(e); } return _client; }

Target:
protected MqttAsyncClient createAndConnectClient() throws MqttException, ConfigurationException { StringBuilder serverURI = new StringBuilder(); switch (protocol) { case TCP: serverURI.append(secure ? "ssl://" : "tcp://"); break; case Websockets: serverURI.append(secure ? "wss://" : "ws://"); break; default: throw new ConfigurationException("protocol", "Protocol unknown"); } serverURI.append(host); serverURI.append(":"); serverURI.append(port); Path tmpDir = Paths.get(ConfigConstants.getUserDataFolder()); try { tmpDir = Files.createDirectories(tmpDir.resolve("mqtt").resolve(host)); } catch (IOException e) { throw new MqttException(e); } MqttClientPersistence dataStore = new MqttDefaultFilePersistence(tmpDir.toString()); MqttAsyncClient _client; try { _client = new MqttAsyncClient(serverURI.toString(), clientId, dataStore); } catch (org.eclipse.paho.client.mqttv3.MqttException e) { throw new MqttException(e); } _client.setCallback(clientCallbacks); try { connectionToken = _client.connect(createMqttOptions(), null, connectionCallbacks); logger.info("Starting MQTT broker connection to '{}' with clientid and file store '{}'", host, getClientId(), tmpDir); } catch (org.eclipse.paho.client.mqttv3.MqttException e) { throw new MqttException(e); } return _client; }
Source:
protected CommandResult doExecuteWithResult(IProgressMonitor monitor, IAdaptable info) throws ExecutionException { if (!canExecute()) { throw new ExecutionException("Unexecutable command."); } ConnectorEnd modifiedEnd = getModifiedConnectorEnd(); NestedConnectorEnd nestedConnectorEnd = UMLUtil.getStereotypeApplication(modifiedEnd, NestedConnectorEnd.class); if (nestedPath.isEmpty()) { if (nestedConnectorEnd != null) { EcoreUtil.delete(nestedConnectorEnd, true); } } else { if (nestedConnectorEnd == null) { nestedConnectorEnd = (NestedConnectorEnd) StereotypeApplicationHelper.getInstance(null).applyStereotype(modifiedEnd, BlocksPackage.eINSTANCE.getNestedConnectorEnd()); ConnectorEnd opposite = getNonModifiedConnectorEnd(); ConnectableElement connectableElement = opposite.getRole(); if (((ISpecializationType) ElementTypeRegistry.getInstance().getType(SysMLServiceTypeUtil.ORG_ECLIPSE_PAPYRUS_SYSML14_BOUNDREFERENCE)).getMatcher().matches(connectableElement)) { Stereotype stereotype = connectableElement.getAppliedStereotype("SysML::Blocks::BoundReference"); BoundReference default_boundReference = (BoundReference) connectableElement.getStereotypeApplication(stereotype); default_boundReference.setBoundEnd(modifiedEnd); } if (!nestedConnectorEnd.getPropertyPath().equals(nestedPath)) { nestedConnectorEnd.getPropertyPath().clear(); nestedConnectorEnd.getPropertyPath().addAll(nestedPath); } } } return CommandResult.newOKCommandResult(getConnector()); }

Target:
protected CommandResult doExecuteWithResult(IProgressMonitor monitor, IAdaptable info) throws ExecutionException { if (!canExecute()) { throw new ExecutionException("Unexecutable command."); } ConnectorEnd modifiedEnd = getModifiedConnectorEnd(); NestedConnectorEnd nestedConnectorEnd = UMLUtil.getStereotypeApplication(modifiedEnd, NestedConnectorEnd.class); if (nestedPath.isEmpty()) { if (nestedConnectorEnd != null) { EcoreUtil.delete(nestedConnectorEnd, true); } } else { if (nestedConnectorEnd == null) { nestedConnectorEnd = (NestedConnectorEnd) StereotypeApplicationHelper.getInstance(null).applyStereotype(modifiedEnd, BlocksPackage.eINSTANCE.getNestedConnectorEnd()); ConnectorEnd opposite = getNonModifiedConnectorEnd(); ConnectableElement connectableElement = opposite.getRole(); if (((ISpecializationType) ElementTypeRegistry.getInstance().getType(SysMLServiceTypeUtil.ORG_ECLIPSE_PAPYRUS_SYSML14_BOUNDREFERENCE)).getMatcher().matches(connectableElement)) { BoundReference defaultBoundReference = UMLUtil.getStereotypeApplication(connectableElement, BoundReference.class); defaultBoundReference.setBoundEnd(modifiedEnd); } if (!nestedConnectorEnd.getPropertyPath().equals(nestedPath)) { nestedConnectorEnd.getPropertyPath().clear(); nestedConnectorEnd.getPropertyPath().addAll(nestedPath); } } } return CommandResult.newOKCommandResult(getConnector()); }
Source:
public final boolean send(Message<?> message, long timeout) { Assert.notNull(message, "message must not be null"); Assert.notNull(message.getPayload(), "message payload must not be null"); if (this.shouldTrack) { message = MessageHistory.write(message, this, this.getMessageBuilderFactory()); } AtomicInteger sendInterceptorIndex = new AtomicInteger(-1); boolean sent = false; try { if (this.datatypes.length > 0) { message = this.convertPayloadIfNecessary(message); } message = this.interceptors.preSend(message, this, sendInterceptorIndex); if (message == null) { return false; } sent = this.doSend(message, timeout); this.interceptors.postSend(message, this, sent); this.interceptors.afterSendCompletion(message, this, sent, null, sendInterceptorIndex.get()); return sent; } catch (Exception e) { this.interceptors.afterSendCompletion(message, this, sent, e, sendInterceptorIndex.get()); if (e instanceof MessagingException) { throw (MessagingException) e; } throw new MessageDeliveryException(message, "failed to send Message to channel '" + this.getComponentName() + "'", e); } }

Target:
public final boolean send(Message<?> message, long timeout) { Assert.notNull(message, "message must not be null"); Assert.notNull(message.getPayload(), "message payload must not be null"); if (this.shouldTrack) { message = MessageHistory.write(message, this, this.getMessageBuilderFactory()); } Deque<ChannelInterceptor> interceptorStack = null; boolean sent = false; try { if (this.datatypes.length > 0) { message = this.convertPayloadIfNecessary(message); } if (this.interceptors.getInterceptors().size() > 0) { interceptorStack = new ArrayDeque<ChannelInterceptor>(); message = this.interceptors.preSend(message, this, interceptorStack); if (message == null) { return false; } } sent = this.doSend(message, timeout); this.interceptors.postSend(message, this, sent); if (interceptorStack != null) { this.interceptors.afterSendCompletion(message, this, sent, null, interceptorStack); } return sent; } catch (Exception e) { if (interceptorStack != null) { this.interceptors.afterSendCompletion(message, this, sent, e, interceptorStack); } if (e instanceof MessagingException) { throw (MessagingException) e; } throw new MessageDeliveryException(message, "failed to send Message to channel '" + this.getComponentName() + "'", e); } }
Source:
public static HeliosClient getClient(final Target target, final PrintStream err, final String username) { List<URI> endpoints = Collections.emptyList(); try { endpoints = target.getEndpointSupplier().get(); } catch (Exception ignore) { err.println(ignore.getMessage()); } if (endpoints.size() == 0) { err.println("Failed to resolve helios master in " + target); return null; } return HeliosClient.newBuilder() .setEndpointSupplier(target.getEndpointSupplier()) .setUser(username) .build(); }

Target:
public static HeliosClient getClient(final Target target, final PrintStream err, final String username) { List<URI> endpoints = Collections.emptyList(); try { endpoints = target.getEndpointSupplier().get(); } catch (Exception ignore) { } if (endpoints.size() == 0) { err.println("Failed to resolve helios master in " + target); return null; } return HeliosClient.newBuilder() .setEndpointSupplier(target.getEndpointSupplier()) .setUser(username) .build(); }
Source:
public void testBufferAggregateWithFoldCheck() { final long[] timestamps = {1526724600L, 1526724700L, 1526724800L, 1526725900L, 1526725000L}; final String[] strings = {"AAAA", "BBBB", "CCCC", "DDDD", "EEEE"}; Integer maxStringBytes = 1024; TestLongColumnSelector longColumnSelector = new TestLongColumnSelector(timestamps); TestObjectColumnSelector<String> objectColumnSelector = new TestObjectColumnSelector<>(strings); StringLastAggregatorFactory factory = new StringLastAggregatorFactory( "billy", "billy", maxStringBytes ); StringLastBufferAggregator agg = new StringLastBufferAggregator( longColumnSelector, objectColumnSelector, maxStringBytes, true ); ByteBuffer buf = ByteBuffer.allocate(factory.getMaxIntermediateSize()); int position = 0; agg.init(buf, position); for (int i = 0; i < timestamps.length; i++) { aggregateBuffer(longColumnSelector, objectColumnSelector, agg, buf, position); } SerializablePairLongString sp = ((SerializablePairLongString) agg.get(buf, position)); Assert.assertEquals("expectec last string value", "DDDD", sp.rhs); Assert.assertEquals("last string timestamp is the biggest", new Long(1526725900L), new Long(sp.lhs)); }

Target:
public void testBufferAggregateWithFoldCheck() { final long[] timestamps = {1526724600L, 1526724700L, 1526724800L, 1526725900L, 1526725000L}; final String[] strings = {"AAAA", "BBBB", "CCCC", "DDDD", "EEEE"}; Integer maxStringBytes = 1024; TestLongColumnSelector longColumnSelector = new TestLongColumnSelector(timestamps); TestObjectColumnSelector<String> objectColumnSelector = new TestObjectColumnSelector<>(strings); StringLastAggregatorFactory factory = new StringLastAggregatorFactory( "billy", "billy", maxStringBytes ); StringLastBufferAggregator agg = new StringLastBufferAggregator( longColumnSelector, objectColumnSelector, maxStringBytes, true ); ByteBuffer buf = ByteBuffer.allocate(factory.getMaxIntermediateSize()); int position = 0; agg.init(buf, position); for (int i = 0; i < timestamps.length; i++) { aggregateBuffer(longColumnSelector, objectColumnSelector, agg, buf, position); } SerializablePairLongString sp = ((SerializablePairLongString) agg.get(buf, position)); Assert.assertEquals("expected last string value", "DDDD", sp.rhs); Assert.assertEquals("last string timestamp is the biggest", new Long(1526725900L), new Long(sp.lhs)); }
Source:
private void closeAll() { final Set<FastqWriter> fastqWriters = new HashSet<>(); fastqWriters.add(firstOfPair); fastqWriters.add(unpaired); fastqWriters.addAll(additionalWriters.values().stream().flatMap(Collection::stream).collect(Collectors.toList())); if (secondOfPair.isInitialized()) { fastqWriters.add(secondOfPair.get()); } for (final FastqWriter fastqWriter : fastqWriters) { fastqWriter.close(); } }

Target:
private void closeAll() { final Set<FastqWriter> fastqWriters = new HashSet<>(); fastqWriters.add(firstOfPair); fastqWriters.add(unpaired); if (secondOfPair.isInitialized()) { fastqWriters.add(secondOfPair.get()); } for (final FastqWriter fastqWriter : fastqWriters) { fastqWriter.close(); } }
Source:
public void setAzureCloudIdentityMapping(String stackCrn, Map<String, String> azureUserMapping, Map<String, String> azureGroupMapping) throws ApiException { ApiClient client = clouderaManagerProxiedClientFactory.getProxiedClouderaManagerClient(stackCrn); String clusterName = getClusterName(client); String rangerUserSyncRoleName = getRangerUserSyncRoleName(client, clusterName); RolesResourceApi rolesResourceApi = clouderaManagerApiFactory.getRolesResourceApi(client); if (!isCloudIdMappingSupported(rolesResourceApi, clusterName, rangerUserSyncRoleName)) { LOGGER.info("This version of CM does not support cloud identity mapping. Skipping."); } else { ApiConfigList configList = new ApiConfigList(); configList.addItemsItem(newCloudIdentityConfig(AZURE_USER_MAPPING, azureUserMapping)); configList.addItemsItem(newCloudIdentityConfig(AZURE_GROUP_MAPPING, azureGroupMapping)); rolesResourceApi.updateRoleConfig(clusterName, rangerUserSyncRoleName, RANGER_SERVICE_NAME, "Updating Azure Cloud Identity Mapping through Cloudbreak", configList); if (isRoleRefreshNeeded(rolesResourceApi, clusterName, rangerUserSyncRoleName)) { LOGGER.info("Role refresh required, trigerring role refresh"); triggerRoleRefresh(client, clusterName, RANGER_SERVICE_NAME, rangerUserSyncRoleName); } else { LOGGER.info("No role refresh required"); } } }

Target:
public void setAzureCloudIdentityMapping(String stackCrn, Map<String, String> azureUserMapping, Map<String, String> azureGroupMapping) throws ApiException { ApiClient client = clouderaManagerProxiedClientFactory.getProxiedClouderaManagerClient(stackCrn); String clusterName = getClusterName(client); String rangerUserSyncRoleName = getRangerUserSyncRoleName(client, clusterName); RolesResourceApi rolesResourceApi = clouderaManagerApiFactory.getRolesResourceApi(client); if (!isCloudIdMappingSupported(rolesResourceApi, clusterName, rangerUserSyncRoleName)) { LOGGER.info("This version of CM does not support cloud identity mapping. Skipping."); } else { ApiConfigList configList = new ApiConfigList(); configList.addItemsItem(newCloudIdentityConfig(AZURE_USER_MAPPING, azureUserMapping)); configList.addItemsItem(newCloudIdentityConfig(AZURE_GROUP_MAPPING, azureGroupMapping)); rolesResourceApi.updateRoleConfig(clusterName, rangerUserSyncRoleName, RANGER_SERVICE_NAME, "Updating Azure Cloud Identity Mapping through Cloudbreak", configList); refreshRoleIfStale(client, rolesResourceApi, clusterName, rangerUserSyncRoleName); } }
Source:
public void addInvalidationListener(final Consumer<String> onEventTypeInvalidated) { this.invalidationListeners.add(onEventTypeInvalidated); }

Target:
public void addInvalidationListener(final Consumer<String> onEventTypeInvalidated) { invalidationListeners.add(onEventTypeInvalidated); }
Source:
private boolean shouldReplicateFromDc(String datacenterName) { if (cloudConfig.cloudIsVcr) { return datacenterName.equals(dataNodeId.getDatacenterName()); } else { return cloudConfig.vcrCrossColoReplicationPeerDatacenters.contains(datacenterName); } }

Target:
private boolean shouldReplicateFromDc(String datacenterName) { return cloudConfig.vcrSourceDatacenters.contains(datacenterName); }
Source:
void testAllJdbcComponentsAutoConfigured() { new ApplicationContextRunner() .withUserConfiguration(Context.class) .run(context -> { assertThat(context).hasSingleBean(JdbcEventStorageEngine.class); assertThat(context).getBean(EventStorageEngine.class).isInstanceOf(JdbcEventStorageEngine.class); assertThat(context).getBean(EventStore.class).isInstanceOf(EmbeddedEventStore.class); assertThat(context).getBean(TokenStore.class).isInstanceOf(JdbcTokenStore.class); assertThat(context).getBean(SagaStore.class).isInstanceOf(JdbcSagaStore.class); assertThat(context).getBean(TokenStore.class).isEqualTo(context.getBean(EventProcessingConfiguration.class).tokenStore("test")); }); }

Target:
void testAllJdbcComponentsAutoConfigured() { new ApplicationContextRunner() .withUserConfiguration(Context.class) .run(context -> { assertThat(context).hasSingleBean(JdbcEventStorageEngine.class); assertThat(context).getBean(EventStorageEngine.class).isInstanceOf(JdbcEventStorageEngine.class); assertThat(context).getBean(EventStore.class).isInstanceOf(EmbeddedEventStore.class); assertThat(context).getBean(TokenStore.class).isInstanceOf(JdbcTokenStore.class); assertThat(context).getBean(SagaStore.class).isInstanceOf(JdbcSagaStore.class); assertThat(context).getBean(TokenStore.class).isEqualTo(context.getBean(EventProcessingConfiguration.class).tokenStore("test")); assertThat(context).getBean(PersistenceExceptionResolver.class).isInstanceOf(JdbcSQLErrorCodesResolver.class); assertThat(context).getBean(ConnectionProvider.class).isInstanceOf(UnitOfWorkAwareConnectionProviderWrapper.class); }); }
Source:
public void onIterationCompleted(final int numCompletedIterations) { LOG.log(Level.INFO, "{0}th iteration is completed."); }

Target:
public void onIterationCompleted(final int numCompletedIterations) { LOG.log(Level.INFO, "{0}th iteration is completed.", numCompletedIterations); }
Source:
private void execute(CommandLine command, String stdin) { InputStream inputStream = new ByteArrayInputStream(stdin.getBytes()); CollectingLogOutputStream outputStream = new CollectingLogOutputStream(); try { Executor executor = new DefaultExecutor(); executor.setStreamHandler(new PumpStreamHandler(outputStream, outputStream, inputStream)); executor.execute(command); } catch (IOException ee) { StringBuilder commandLog = new StringBuilder(command.toString()); commandLog.append(outputStream.getLines()); throw new NetCdfProcessingException(commandLog.toString()); } }

Target:
private void execute(CommandLine command, String stdin) { InputStream inputStream = new ByteArrayInputStream(stdin.getBytes()); try ( LogOutputStream outputStream = new LogOutputStream() { @Override protected void processLine(String line, int level) { logger.info(line); } }; LogOutputStream errorStream = new LogOutputStream() { @Override protected void processLine(String line, int level) { logger.error(line); } } ){ Executor executor = new DefaultExecutor(); executor.setStreamHandler(new PumpStreamHandler(outputStream, errorStream, inputStream)); executor.execute(command); } catch (IOException e) { throw new NetCdfProcessingException(String.format("Error running %s", command.toString()), e); } }
Source:
protected void executeQueryCommand() { VDS vds = getVds(); if (FeatureSupported.isLlldpInformationSupported(vds.getClusterCompatibilityVersion())) { VDSReturnValue command = runVdsCommand(VDSCommandType.GetLldp, lldpVDSCommandParameters); getQueryReturnValue().setReturnValue(command.getReturnValue()); } else { getQueryReturnValue().setReturnValue(null); } }

Target:
protected void executeQueryCommand() { if (FeatureSupported.isLlldpInformationSupported(getVds().getClusterCompatibilityVersion())) { VDSReturnValue command = runVdsCommand(VDSCommandType.GetLldp, lldpVDSCommandParameters); getQueryReturnValue().setReturnValue(command.getReturnValue()); } }
Source:
public void executeRulesInCorrectOrder() throws Exception { LOG.clear(); testResult(UseRuleChain.class); List<String> expectedLog = asList("starting outer rule", "starting middle rule", "starting inner rule", "finished inner rule", "finished middle rule", "finished outer rule"); assertEquals(expectedLog, LOG); }

Target:
public void executeRulesInCorrectOrder() throws Exception { testResult(UseRuleChain.class); List<String> expectedLog = asList("starting outer rule", "starting middle rule", "starting inner rule", "finished inner rule", "finished middle rule", "finished outer rule"); assertEquals(expectedLog, LOG); }
Source:
protected void addLinks(CollectionResource halResource, Pageable pageable, LinkedList<Link> list) throws Exception { Context context = ContextUtil.obtainContext(requestService.getCurrentRequest().getHttpServletRequest()); Collection collection = collectionService.find(context, UUID.fromString(halResource.getContent().getId())); Map<String, Role> roles = WorkflowUtils.getCollectionRoles(collection); for (Map.Entry<String, Role> entry : roles.entrySet()) { list.add(buildLink("workflowGroups/" + entry.getKey(), getMethodOn() .getWorkflowGroupForRole(UUID.fromString(halResource.getContent().getUuid()), null, null, entry.getKey()))); } }

Target:
protected void addLinks(CollectionResource halResource, Pageable pageable, LinkedList<Link> list) throws Exception { Context context = ContextUtil.obtainContext(requestService.getCurrentRequest().getHttpServletRequest()); Collection collection = collectionService.find(context, UUID.fromString(halResource.getContent().getId())); Map<String, Role> roles = WorkflowUtils.getCollectionRoles(collection); UUID resourceUuid = UUID.fromString(halResource.getContent().getUuid()); for (Map.Entry<String, Role> entry : roles.entrySet()) { list.add(buildLink("workflowGroups/" + entry.getKey(), getMethodOn() .getWorkflowGroupForRole(resourceUuid, null, null, entry.getKey()))); } }
Source:
private List<ActionEventRequest> buildActionsForConfig(Config config) { List<ActionEventRequest> actions = new ArrayList<>(); for (CommcareApplicationJson application : schemaService.retrieveApplications(config.getName())) { for (CommcareModuleJson module : application.getModules()) { for (FormSchemaJson form : module.getFormSchemas()) { SortedSet<ActionParameterRequest> parameters = buildActionParameters(form); String displayName = DisplayNameHelper.buildDisplayName(DisplayNames.SUBMIT_FORM, form.getFormName(), application.getApplicationName(), config.getName()); String appId = application.getCommcareAppId(); if (appId == null) { appId = ""; } ActionEventRequestBuilder actionBuilder = new ActionEventRequestBuilder() .setDisplayName(displayName) .setSubject(EventSubjects.SUBMIT_FORM + "." + form.getXmlns() + appId + "." + config.getName()) .setActionParameters(parameters); actions.add(actionBuilder.createActionEventRequest()); } } } return actions; }

Target:
private List<ActionEventRequest> buildActionsForConfig(Config config) { List<ActionEventRequest> actions = new ArrayList<>(); for (CommcareApplicationJson application : schemaService.retrieveApplications(config.getName())) { for (CommcareModuleJson module : application.getModules()) { for (FormSchemaJson form : module.getFormSchemas()) { SortedSet<ActionParameterRequest> parameters = buildActionParameters(form); String displayName = DisplayNameHelper.buildDisplayName(DisplayNames.SUBMIT_FORM, form.getFormName(), application.getApplicationName(), config.getName()); String appId = (application.getCommcareAppId() == null) ? "" : application.getCommcareAppId(); ActionEventRequestBuilder actionBuilder = new ActionEventRequestBuilder() .setDisplayName(displayName) .setSubject(EventSubjects.SUBMIT_FORM + "." + form.getXmlns() + appId + "." + config.getName()) .setActionParameters(parameters); actions.add(actionBuilder.createActionEventRequest()); } } } return actions; }
Source:
public void setUp() throws IOException { if (extractor == null) { doorHtmlExport = folder.newFile("sample_DOORS_export.htm"); copyResource("sample_DOORS_export.htm", doorHtmlExport); copyResource(THIS_IS_A_JPEG_IMAGE_JPG, folder.newFile(THIS_IS_A_JPEG_IMAGE_JPG)); copyResource(THIS_IS_A_PNG_IMAGE_PNG, folder.newFile(THIS_IS_A_PNG_IMAGE_PNG)); } extractor = new DoorsArtifactExtractor(); collector = new RoughArtifactCollector(null); }

Target:
public void setUp() { extractor = new DoorsArtifactExtractor(); collector = new RoughArtifactCollector(null); }
Source:
public List<ManufacturerDto> getManufacturers() { return Manufacturer.createDto(manufacturerDao.getAll()); }

Target:
public Response getManufacturers() { List<ManufacturerDto> manufacturerDtos = Manufacturer.createDto(manufacturerDao.getAll()); return Response.ok(manufacturerDtos).build(); }