auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void init() { broker = LdapFactory.getInstance(getProfileName()); context.put(ExtensionProperties.AUTHOR, "oVirt"); <START> context.put(ExtensionProperties.EXTENSION_NAME, "Provisional Authentication (LbapBroker code based)"); <END> context.put(ExtensionProperties.LICENSE, "ASL 2.0"); context.put(ExtensionProperties.HOME, "<LINK_0>"); context.put(ExtensionProperties.VERSION, "1.0"); }</code><technical_language>Internal Kerberos/LDAP Authentication</technical_language>

Target:
public void init() { broker = LdapFactory.getInstance(getProfileName()); context.put(ExtensionProperties.AUTHOR, "The oVirt Project"); context.put(ExtensionProperties.EXTENSION_NAME, "Internal Kerberos/LDAP authentication (Built-in)"); context.put(ExtensionProperties.LICENSE, "ASL 2.0"); context.put(ExtensionProperties.HOME, "<LINK_0>"); context.put(ExtensionProperties.VERSION, "N/A"); }
Source:
<code>public void endWindow() { super.endWindow(); <START> updatedKeyStorage.endWindow(); <END> }</code><technical_language>Instead of calling endWindow explicitly, part of components member variable</technical_language>

Target:
public void endWindow() { super.endWindow(); if (useUpdatedKeyStorage()) { updatedKeyStorage.endWindow(); } }
Source:
<code>protected boolean canCreateOrUpdateUser(DocumentModel userDoc) { NuxeoPrincipal principal = new NuxeoPrincipalImpl((String) userDoc.getProperty(SCHEMA_NAME, USERNAME_COLUMN)); principal.setModel(userDoc); List<String> adminGroups = userManager.getAdministratorsGroups(); <START> for (String adminGroup : adminGroups) { <END> if (principal.getAllGroups().contains(adminGroup)) { return false; } } return true; }</code><technical_language>if replace by: NuxeoPrincipal principal = new NuxeoPrincipalImpl((String) userDoc.getProperty(SCHEMA_NAME, USERNAME_COLUMN)); principal.setModel(userDoc); return userManager.getAdministratorsGroups().stream().noneMatch(principal.getAllGroups()::contains);</technical_language>

Target:
protected boolean canCreateOrUpdateUser(DocumentModel userDoc) { NuxeoPrincipal principal = new NuxeoPrincipalImpl((String) userDoc.getProperty(SCHEMA_NAME, USERNAME_COLUMN)); principal.setModel(userDoc); return userManager.getAdministratorsGroups().stream().noneMatch(principal.getAllGroups()::contains); }
Source:
<code>public void testInvalidIV() throws Exception { Assume.assumeTrue(Openssl.getLoadingFailureReason() == null); Openssl cipher = Openssl.getInstance("AES/CTR/NoPadding"); <START> Assert.assertTrue(cipher != null); <END> final byte[] invalidIV = {0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x11}; try { cipher.init(Openssl.ENCRYPT_MODE, key, invalidIV); Assert.fail("java.security.InvalidAlgorithmParameterException should be thrown."); } catch (Exception e) { Assert.assertTrue(e.getMessage().contains("Wrong IV length.")); throw e; } }</code><technical_language>hint: Assert.assertNull</technical_language>

Target:
public void testInvalidIV() throws Exception { Assume.assumeTrue(Openssl.getLoadingFailureReason() == null); Openssl cipher = Openssl.getInstance(CipherTransformation.AES_CTR_NOPADDING.getName()); Assert.assertNotNull(cipher); final byte[] invalidIV = {0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x11}; try { cipher.init(Openssl.ENCRYPT_MODE, key, invalidIV); Assert.fail("java.security.InvalidAlgorithmParameterException should be thrown."); } catch (Exception e) { Assert.assertTrue(e.getMessage().contains("Wrong IV length.")); throw e; } }
Source:
<code>public void setAssignmentsInfo(AssignmentsInfo info) { ParsedAssignmentsInfo assignmentsInfo = ParsedAssignmentsInfo.of(info); <START> List<InitializedOutputVariable> outputs = <END> assignmentsInfo.createInitializedOutputVariables( getId(), variableScope); if (outputs.isEmpty()) { return; } if (outputs.size() > 1) { throw new IllegalArgumentException("Output Associations should be at most 1 in Catch Events"); } InitializedOutputVariable output = outputs.get(0); DataOutput dataOutput = output.getDataOutput(); event.getDataOutputs().add(dataOutput); event.getOutputSet().getDataOutputRefs().add(dataOutput); this.addItemDefinition(dataOutput.getItemSubjectRef()); DataOutputAssociation dataOutputAssociation = output.getDataOutputAssociation(); if (dataOutputAssociation != null) { event.getDataOutputAssociation().add(dataOutputAssociation); } }</code><technical_language>@evacchi suggest creating output set here, finally put</technical_language>

Target:
public void setAssignmentsInfo(AssignmentsInfo info) { ParsedAssignmentsInfo assignmentsInfo = ParsedAssignmentsInfo.of(info); List<InitializedOutputVariable> outputs = assignmentsInfo.createInitializedOutputVariables( getId(), variableScope); if (outputs.isEmpty()) { return; } if (outputs.size() > 1) { throw new IllegalArgumentException("Output Associations should be at most 1 in Catch Events"); } InitializedOutputVariable output = outputs.get(0); DataOutput dataOutput = output.getDataOutput(); event.getDataOutputs().add(dataOutput); getOutputSet().getDataOutputRefs().add(dataOutput); this.addItemDefinition(dataOutput.getItemSubjectRef()); DataOutputAssociation dataOutputAssociation = output.getDataOutputAssociation(); if (dataOutputAssociation != null) { event.getDataOutputAssociation().add(dataOutputAssociation); } }
Source:
<code>public File downloadTargetEntry(String toolpath, ToolDescriptor.TypeEnum type, boolean unzip, File directory) throws IOException { String[] parts = toolpath.split(":"); String path = parts[0]; <START> String tag = (parts.length > 1) ? parts[1] : "master"; <END> Workflow workflow = getDockstoreWorkflowByPath(path); Optional<WorkflowVersion> first = workflow.getWorkflowVersions().stream().filter(foo -> foo.getName().equalsIgnoreCase(tag)) .findFirst(); if (first.isPresent()) { Long versionId = first.get().getId(); byte[] arbitraryURL = SwaggerUtility .getArbitraryURL("/workflows/" + workflow.getId() + "/zip/" + versionId, new GenericType<byte[]>() { }, workflowsApi.getApiClient()); File zipFile = new File(zipFilename(workflow)); FileUtils.writeByteArrayToFile(zipFile, arbitraryURL, false); if (unzip) { SwaggerUtility.unzipFile(zipFile, directory); } return new File(directory, first.get().getWorkflowPath()); } else { throw new RuntimeException("version not found"); } }</code><technical_language>realized this work for hosted entries. entry sense</technical_language>

Target:
public File downloadTargetEntry(String toolpath, ToolDescriptor.TypeEnum type, boolean unzip, File directory) throws IOException { String[] parts = toolpath.split(":"); String path = parts[0]; String tag = (parts.length > 1) ? parts[1] : "master"; Workflow workflow = getDockstoreWorkflowByPath(path); Optional<WorkflowVersion> first = workflow.getWorkflowVersions().stream().filter(foo -> foo.getName().equalsIgnoreCase(tag)) .findFirst(); if (!first.isPresent()) { first = workflow.getWorkflowVersions().stream().max(Comparator.comparing(WorkflowVersion::getLastModified)); } if (first.isPresent()) { Long versionId = first.get().getId(); byte[] arbitraryURL = SwaggerUtility .getArbitraryURL("/workflows/" + workflow.getId() + "/zip/" + versionId, new GenericType<byte[]>() { }, workflowsApi.getApiClient()); File zipFile = new File(zipFilename(workflow)); FileUtils.writeByteArrayToFile(zipFile, arbitraryURL, false); if (unzip) { SwaggerUtility.unzipFile(zipFile, directory); } return new File(directory, first.get().getWorkflowPath()); } else { throw new RuntimeException("version not found"); } }
Source:
<code>public void fillInRepo() throws Exception { final File sourceSnapshotsRoot = new File( getBasedir(), "src/test/resources/reposes/snapshots" ).getAbsoluteFile(); final URL snapshotsRootUrl = new URL( snapshots.getLocalUrl() ); final File snapshotsRoot = new File( snapshotsRootUrl.toURI() ).getAbsoluteFile(); copyDirectory( sourceSnapshotsRoot, snapshotsRoot ); final File sourceReleasesRoot = new File( getBasedir(), "src/test/resources/reposes/releases" ); final URL releaseRootUrl = new URL( releases.getLocalUrl() ); final File releasesRoot = new File( releaseRootUrl.toURI() ); copyDirectory( sourceReleasesRoot, releasesRoot ); final File sourceApacheSnapshotsRoot = new File( getBasedir(), "src/test/resources/reposes/apache-snapshots" ); final URL apacheSnapshotsRootUrl = new URL( apacheSnapshots.getLocalUrl() ); final File apacheSnapshotsRoot = new File( apacheSnapshotsRootUrl.toURI() ); copyDirectory( sourceApacheSnapshotsRoot, apacheSnapshotsRoot ); ResourceStoreRequest root = new ResourceStoreRequest( RepositoryItemUid.PATH_ROOT ); snapshots.expireCaches( root ); releases.expireCaches( root ); apacheSnapshots.expireCaches( root ); ( (MavenProxyRepository) apacheSnapshots ).setRemoteUrl( "http://localhost:" + super.getContainer().getContext().get( PROXY_SERVER_PORT )+"/apache-snapshots/" ); ( (MavenProxyRepository) apacheSnapshots ).setDownloadRemoteIndexes( false ); nexusConfiguration.saveConfiguration(); <START> waitForTasksToStop(); <END> }</code><technical_language>checking, events.waitForQuietPeriod() well</technical_language>

Target:
public void fillInRepo() throws Exception { final File sourceSnapshotsRoot = new File( getBasedir(), "src/test/resources/reposes/snapshots" ).getAbsoluteFile(); final URL snapshotsRootUrl = new URL( snapshots.getLocalUrl() ); final File snapshotsRoot = new File( snapshotsRootUrl.toURI() ).getAbsoluteFile(); copyDirectory( sourceSnapshotsRoot, snapshotsRoot ); final File sourceReleasesRoot = new File( getBasedir(), "src/test/resources/reposes/releases" ); final URL releaseRootUrl = new URL( releases.getLocalUrl() ); final File releasesRoot = new File( releaseRootUrl.toURI() ); copyDirectory( sourceReleasesRoot, releasesRoot ); final File sourceApacheSnapshotsRoot = new File( getBasedir(), "src/test/resources/reposes/apache-snapshots" ); final URL apacheSnapshotsRootUrl = new URL( apacheSnapshots.getLocalUrl() ); final File apacheSnapshotsRoot = new File( apacheSnapshotsRootUrl.toURI() ); copyDirectory( sourceApacheSnapshotsRoot, apacheSnapshotsRoot ); ResourceStoreRequest root = new ResourceStoreRequest( RepositoryItemUid.PATH_ROOT ); snapshots.expireCaches( root ); releases.expireCaches( root ); apacheSnapshots.expireCaches( root ); ( (MavenProxyRepository) apacheSnapshots ).setRemoteUrl( "http://localhost:" + super.getContainer().getContext().get( PROXY_SERVER_PORT )+"/apache-snapshots/" ); ( (MavenProxyRepository) apacheSnapshots ).setDownloadRemoteIndexes( false ); nexusConfiguration.saveConfiguration(); wairForAsyncEventsToCalmDown(); waitForTasksToStop(); }
Source:
<code>Location location() default BOTH; enum Location { ACTIVE, PASSIVE, NONE, <START> BOTH <END> }</code><technical_language>Why</technical_language>

Target:
Location location() default BOTH; enum Location { ACTIVE, PASSIVE, BOTH, NONE }
Source:
<code>public Transcriber(String roomName, TranscriptionService service) { if (!service.supportsStreamRecognition()) { throw new IllegalArgumentException("Currently only services which" + <START> " support streaming recognition are supported"); <END> } this.transcriptionService = service; addTranscriptionListener(this.transcript); this.roomName = roomName; }</code><technical_language>exceed 80 chars limit here</technical_language>

Target:
public Transcriber(String roomName, TranscriptionService service) { if (!service.supportsStreamRecognition()) { throw new IllegalArgumentException( "Currently only services which support streaming " + "recognition are supported"); } this.transcriptionService = service; addTranscriptionListener(this.transcript); this.roomName = roomName; }
Source:
<code>public CabSearchView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); <START> SearchView.SearchAutoComplete mSearchSrcTextView = (SearchAutoComplete) findViewById(R.id.search_src_text); <END> if (ApiUtil.hasHoneyComb()) { mSearchSrcTextView.setCustomSelectionActionModeCallback(new CallbackWrapper()); } initLayoutAttributes(attrs, defStyleAttr); }</code><technical_language>I tend exception for Views fields accustomed Butter Knife View injection annotations. Additionally, this class exists of a deficiency in support libraries field intentionally added match name of identical private field in super, offering a more context. said, objections other please rename variable searchSrcTextView a local now</technical_language>

Target:
public CabSearchView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); SearchView.SearchAutoComplete searchSrcTextView = (SearchAutoComplete) findViewById(R.id.search_src_text); if (ApiUtil.hasHoneyComb()) { searchSrcTextView.setCustomSelectionActionModeCallback(new CallbackWrapper()); } initLayoutAttributes(attrs, defStyleAttr); }
Source:
<code>public void setFilters(String filterSequence) { char[][] filters= filterSequence != null && filterSequence.length() > 0 ? splitAndTrimOn(',', filterSequence.toCharArray()) : null; if (filters == null) { fExtraResourceFileFilters= null; fExtraResourceFolderFilters= null; } else { int fileCount= 0, folderCount= 0; for (char[] <START> f : <END> filters) { if (f.length == 0) continue; if (f[f.length - 1] == '/') folderCount++; else fileCount++; } fExtraResourceFileFilters= new char[fileCount][]; fExtraResourceFolderFilters= new String[folderCount]; for (char[] f : filters) { if (f.length == 0) continue; if (f[f.length - 1] == '/') fExtraResourceFolderFilters[--folderCount]= new String(subarray(f, 0, f.length - 1)); else fExtraResourceFileFilters[--fileCount]= f; } } }</code><technical_language>rename filter (to consistent above)</technical_language>

Target:
public void setFilters(String filterSequence) { char[][] filters= filterSequence != null && filterSequence.length() > 0 ? splitAndTrimOn(',', filterSequence.toCharArray()) : null; if (filters == null) { fExtraResourceFileFilters= null; fExtraResourceFolderFilters= null; } else { int fileCount= 0, folderCount= 0; for (char[] filter : filters) { if (filter.length == 0) continue; if (filter[filter.length - 1] == '/') folderCount++; else fileCount++; } fExtraResourceFileFilters= new char[fileCount][]; fExtraResourceFolderFilters= new String[folderCount]; for (char[] filter : filters) { if (filter.length == 0) continue; if (filter[filter.length - 1] == '/') fExtraResourceFolderFilters[--folderCount]= new String(subarray(filter, 0, filter.length - 1)); else fExtraResourceFileFilters[--fileCount]= filter; } } }
Source:
<code>NewUserTagNameDialog() { super(new JFrame(NbBundle.getMessage(NewUserTagNameDialog.class, "NewUserTagNameDialog.title.text")), NbBundle.getMessage(NewUserTagNameDialog.class, "NewUserTagNameDialog.title.text"), true); initComponents(); <START> String test = ""; <END> this.display(); }</code><technical_language>Line 48 a left test code</technical_language>

Target:
NewUserTagNameDialog() { super(new JFrame(NbBundle.getMessage(NewUserTagNameDialog.class, "NewUserTagNameDialog.title.text")), NbBundle.getMessage(NewUserTagNameDialog.class, "NewUserTagNameDialog.title.text"), true); initComponents(); this.display(); }
Source:
<code>@Override public String toString() { StringBuilder builder = new StringBuilder(); if (value instanceof String) { <START> builder.append(name).append(" = \"").append(value).append('"'); <END> } else if (value instanceof Option) { Option optionValue = (Option) value; builder.append('(').append(name).append(").").append(optionValue.toString()); } else if (value instanceof List) { builder.append(name).append(" = [\n"); List<Option> optionList = (List<Option>) value; for (int i = 0, count = optionList.size(); i < count; i++) { String endl = (i < count - 1) ? "," : ""; appendIndented(builder, optionList.get(i).toString() + endl); } builder.append(']'); } else { throw new IllegalStateException("Unknown value type " + value.getClass().getCanonicalName()); } return builder.toString(); }</code><technical_language>I assume this escaping work for other " chars</technical_language>

Target:
@Override public String toString() { StringBuilder builder = new StringBuilder(); if (value instanceof String) { String stringValue = (String) value; builder.append(name).append(" = \"").append(escape(stringValue)).append('"'); } else if (value instanceof Option) { Option optionValue = (Option) value; builder.append('(').append(name).append(").").append(optionValue.toString()); } else if (value instanceof List) { builder.append(name).append(" = [\n"); List<Option> optionList = (List<Option>) value; for (int i = 0, count = optionList.size(); i < count; i++) { String endl = (i < count - 1) ? "," : ""; appendIndented(builder, optionList.get(i).toString() + endl); } builder.append(']'); } else { throw new IllegalStateException("Unknown value type " + value.getClass().getCanonicalName()); } return builder.toString(); }
Source:
<code>public Map<FactoryContainer, Attributes> getEnabledContainers() { Map<FactoryContainer, Attributes> map = new LinkedHashMap<>(); synchronized(_path) { for <START> (Entry<FactoryContainer, <END> Attributes> entry : getReversed(_path.entrySet())) { Attributes attr = entry.getValue(); if (attr.isEnabled()) { Attributes attrClone = new Attributes(attr); map.put(entry.getKey(), attrClone); } } } return map; }</code><technical_language>For clarity preferable: Map.Entry</technical_language>

Target:
public Map<FactoryContainer, Attributes> getEnabledContainers() { Map<FactoryContainer, Attributes> map = new LinkedHashMap<>(); synchronized(_path) { for (Map.Entry<FactoryContainer, Attributes> entry : getReversed(_path.entrySet())) { Attributes attr = entry.getValue(); if (attr.isEnabled()) { Attributes attrClone = new Attributes(attr); map.put(entry.getKey(), attrClone); } } } return map; }
Source:
<code>public boolean canUseLocalCache() { boolean brokerSwitch; try { brokerSwitch = canSwitchToBroker(); } <START> catch (DeveloperAuthenticationException e){ <END> Logger.w( TAG, e.getMessage(), "", ADALError.DEVELOPER_BROKER_PERMISSIONS_MISSING); brokerSwitch = false; } if (!brokerSwitch) { Logger.v(TAG, "It does not use broker"); return true; } String packageName = mContext.getPackageName(); if (verifySignature(packageName)) { Logger.v(TAG, "Broker installer can use local cache"); return true; } return false; }</code><technical_language>picky here. do need change thrown exception? final</technical_language>

Target:
public boolean canUseLocalCache() { boolean brokerSwitch; try { brokerSwitch = canSwitchToBroker(); } catch (final UsageAuthenticationException e) { Logger.w( TAG, e.getMessage(), "", ADALError.DEVELOPER_BROKER_PERMISSIONS_MISSING); brokerSwitch = false; } if (!brokerSwitch) { Logger.v(TAG, "It does not use broker"); return true; } String packageName = mContext.getPackageName(); if (verifySignature(packageName)) { Logger.v(TAG, "Broker installer can use local cache"); return true; } return false; }
Source:
<code>private void connectReceiver(ActiveMQProtonRemotingConnection protonRemotingConnection, Session session, AMQPSessionContext sessionContext, Queue queue, Symbol... capabilities) { if (logger.isDebugEnabled()) { logger.debug("Connecting inbound for " + queue); } { Receiver checkRec = receivers.get(queue); if (checkRec != null) { logger.debug("Receiver for queue " + queue + " already exists, just giving up"); return; } } if (session == null) { logger.debug("session is null"); return; } Receiver receiver = session.receiver(queue.getName().toString() + UUIDGenerator.getInstance().generateStringUUID()); Target target = new Target(); target.setAddress(queue.getAddress().toString()); receiver.setTarget(target); <START> Source source = new Source(); source.setAddress(queue.getName().toString()); <END> receiver.setSource(source); if (capabilities != null) { source.setCapabilities(capabilities); } receivers.put(queue, receiver); protonRemotingConnection.getAmqpConnection().runLater(() -> { receiver.open(); protonRemotingConnection.getAmqpConnection().flush(); try { sessionContext.addReceiver(receiver); } catch (Exception e) { error(e); } }); }</code><technical_language>outomes, default outcome, terminus expiry set too</technical_language>

Target:
private void connectReceiver(ActiveMQProtonRemotingConnection protonRemotingConnection, Session session, AMQPSessionContext sessionContext, Queue queue, Symbol... capabilities) { if (logger.isDebugEnabled()) { logger.debug("Connecting inbound for " + queue); } if (session == null) { logger.debug("session is null"); return; } protonRemotingConnection.getAmqpConnection().runLater(() -> { if (receivers.contains(queue)) { logger.debug("Receiver for queue " + queue + " already exists, just giving up"); return; } receivers.add(queue); Receiver receiver = session.receiver(queue.getName().toString() + UUIDGenerator.getInstance().generateStringUUID()); receiver.setSenderSettleMode(SenderSettleMode.UNSETTLED); receiver.setReceiverSettleMode(ReceiverSettleMode.FIRST); Target target = new Target(); target.setAddress(queue.getAddress().toString()); receiver.setTarget(target); Source source = new Source(); source.setAddress(queue.getAddress().toString()); receiver.setSource(source); if (capabilities != null) { source.setCapabilities(capabilities); } receiver.open(); protonRemotingConnection.getAmqpConnection().flush(); try { sessionContext.addReceiver(receiver); } catch (Exception e) { error(e); } }); }
Source:
<code>public ManagedTimestampService createManagedTimestampService( KeyValueService rawKvs, Optional<TableReference> tableReferenceOverride, boolean initializeAsync) { <START> if (initializeAsync) { <END> log.warn("Asynchronous initialization not implemented, will initialize synchronousy."); } Preconditions.checkArgument( rawKvs instanceof ConnectionManagerAwareDbKvs, "DbAtlasDbFactory expects a raw kvs of type ConnectionManagerAwareDbKvs, found %s", rawKvs.getClass()); ConnectionManagerAwareDbKvs dbkvs = (ConnectionManagerAwareDbKvs) rawKvs; return PersistentTimestampServiceImpl.create(createTimestampBoundStore(tableReferenceOverride, dbkvs)); }</code><technical_language>useful validation checks i.e. tableReferenceOverride is DB_TIMELOCK_TIMESTAMP_TABLE</technical_language>

Target:
public ManagedTimestampService createManagedTimestampService( KeyValueService rawKvs, Optional<TableReference> tableReferenceOverride, boolean initializeAsync) { if (initializeAsync) { log.warn("Asynchronous initialization not implemented, will initialize synchronously."); } Preconditions.checkArgument( !tableReferenceOverride .map(AtlasDbConstants.DB_TIMELOCK_TIMESTAMP_TABLE::equals) .orElse(false), "Cannot specify the DB TimeLock timestamp table as a timestamp table override!"); Preconditions.checkArgument( rawKvs instanceof ConnectionManagerAwareDbKvs, "DbAtlasDbFactory expects a raw kvs of type ConnectionManagerAwareDbKvs, found %s", rawKvs.getClass()); ConnectionManagerAwareDbKvs dbkvs = (ConnectionManagerAwareDbKvs) rawKvs; return PersistentTimestampServiceImpl.create(createTimestampBoundStore(tableReferenceOverride, dbkvs)); }
Source:
<code>private boolean hasEnoughLag(Interval target, Interval maxInterval) { <START> if ((target.getStartMillis() + minDataLagMs) > maxInterval.getStartMillis()) { <END> return false; } else { return true; } }</code><technical_language>return boolean expression</technical_language>

Target:
private boolean hasEnoughLag(Interval target, Interval maxInterval) { return minDataLagMs <= (maxInterval.getStartMillis() - target.getStartMillis()); }
Source:
<code>public Mono<AccessToken> authenticateToManagedIdentityEnpoint(String msiEndpoint, String msiSecret, String clientId, String[] scopes) { String resource = ScopeUtil.scopesToResource(scopes); HttpURLConnection connection = null; try { StringBuilder urlStringBuilder = new StringBuilder(String.format("%s?resource=%s&api-version=2017-09-01", msiEndpoint, resource)); if (clientId != null) { urlStringBuilder.append("&"); urlStringBuilder.append("client_id"); <START> urlStringBuilder.append("="); <END> urlStringBuilder.append(clientId); } URL url = new URL(urlStringBuilder.toString()); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Secret", msiSecret); connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()).useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; return adapter.deserialize(result, MSIToken.class, SerializerEncoding.JSON); } catch (IOException e) { return Mono.error(e); } finally { if (connection != null) { connection.disconnect(); } } }</code><technical_language>lines line - concatenating string constants</technical_language>

Target:
public Mono<AccessToken> authenticateToManagedIdentityEnpoint(String msiEndpoint, String msiSecret, String clientId, String[] scopes) { String resource = ScopeUtil.scopesToResource(scopes); HttpURLConnection connection = null; StringBuilder payload = new StringBuilder(); try { payload.append("resource="); payload.append(URLEncoder.encode(resource, "UTF-8")); payload.append("&api-version="); payload.append(URLEncoder.encode("2017-09-01", "UTF-8")); if (clientId != null) { payload.append("&client_id="); payload.append(URLEncoder.encode(clientId, "UTF-8")); } } catch (IOException exception) { return Mono.error(exception); } try { URL url = new URL(String.format("%s?%s", msiEndpoint, payload)); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Secret", msiSecret); connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()).useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; return adapter.deserialize(result, MSIToken.class, SerializerEncoding.JSON); } catch (IOException e) { return Mono.error(e); } finally { if (connection != null) { connection.disconnect(); } } }
Source:
<code><START> protected Map<String, Pair<String, String>> getSharedLocks() { <END> List<Disk> disksToLock = getVmPluggedDisks(); if (!disksToLock.isEmpty()) { Map<String, Pair<String, String>> sharedLockMap = new HashMap<String, Pair<String, String>>(disksToLock.size()); for (Disk disk : disksToLock) { sharedLockMap.put(disk.getId().toString(), LockMessagesMatchUtil.DISK); } } return null; }</code><technical_language>exclusive locks, prevent locks in case of live storage migration, taken? LiveMigrateDiskCommand MoveOrCopyDiskCommand annotated @LockIdNameAttribute</technical_language>

Target:
protected Map<String, Pair<String, String>> getSharedLocks() { List<Disk> disksToLock = getVmPluggedDisks(); if (!disksToLock.isEmpty()) { Map<String, Pair<String, String>> sharedLockMap = new HashMap<String, Pair<String, String>>(disksToLock.size()); for (Disk disk : disksToLock) { sharedLockMap.put(disk.getId().toString(), LockMessagesMatchUtil.makeLockingPair(LockingGroup.DISK, getDiskSharedLockMessage())); } } return null; }
Source:
<code>public static void main(String[] args) { try { boolean isHeadless = false; Path homePath = null; for (String arg : args) { if (arg.startsWith(HOME_ARG)) { homePath = Paths.get(arg.substring(HOME_ARG.length())); } else if (arg.equals(LOCAL_ARG)) { homePath = Paths.get(""); } else if (arg.equals(HEADLESS_ARG)) { isHeadless = true; } } if (homePath != null) { PathManager.getInstance().useOverrideHomePath(homePath); } else { PathManager.getInstance().useDefaultHomePath(); } Collection<EngineSubsystem> subsystemList; if (isHeadless) { subsystemList = Lists.newArrayList(new HeadlessGraphics(), new HeadlessTimer(), new HeadlessAudio(), new HeadlessInput()); } else { subsystemList = Lists.<EngineSubsystem>newArrayList(new LwjglGraphics(), new LwjglTimer(), new LwjglAudio(), new LwjglInput()); } TerasologyEngine engine = new TerasologyEngine(subsystemList); try { engine.init(); if (isHeadless) { engine.run(new StateHeadlessSetup()); } else { engine.run(new StateMainMenu()); } } finally { try { engine.dispose(); } catch (Exception e) { e.printStackTrace(); } } } catch (Throwable t) { if (!GraphicsEnvironment.isHeadless()) { Path logDirectory = Paths.get("."); try { <START> logDirectory = PathManager.getInstance().getLogPath(); <END> } catch (Exception e) { } Path logPath = logDirectory.resolve("Terasology.log"); CrashReporter.report(t, logPath); } } System.exit(0); }</code><technical_language>need deal PathManager returning null if initialised</technical_language>

Target:
public static void main(String[] args) { try { boolean isHeadless = false; Path homePath = null; for (String arg : args) { if (arg.startsWith(HOME_ARG)) { homePath = Paths.get(arg.substring(HOME_ARG.length())); } else if (arg.equals(LOCAL_ARG)) { homePath = Paths.get(""); } else if (arg.equals(HEADLESS_ARG)) { isHeadless = true; } } if (homePath != null) { PathManager.getInstance().useOverrideHomePath(homePath); } else { PathManager.getInstance().useDefaultHomePath(); } Collection<EngineSubsystem> subsystemList; if (isHeadless) { subsystemList = Lists.newArrayList(new HeadlessGraphics(), new HeadlessTimer(), new HeadlessAudio(), new HeadlessInput()); } else { subsystemList = Lists.<EngineSubsystem>newArrayList(new LwjglGraphics(), new LwjglTimer(), new LwjglAudio(), new LwjglInput()); } TerasologyEngine engine = new TerasologyEngine(subsystemList); try { engine.init(); if (isHeadless) { engine.run(new StateHeadlessSetup()); } else { engine.run(new StateMainMenu()); } } finally { try { engine.dispose(); } catch (Exception e) { e.printStackTrace(); } } } catch (RuntimeException | IOException e) { if (!GraphicsEnvironment.isHeadless()) { Path logPath = Paths.get("."); try { Path gameLogPath = PathManager.getInstance().getLogPath(); if (gameLogPath != null) { logPath = gameLogPath; } } catch (Exception eat) { } Path logFile = logPath.resolve("Terasology.log"); CrashReporter.report(e, logFile); } } System.exit(0); }
Source:
<code>public void serialize(final TraversalExplanation traversalExplanation, final JsonGenerator jsonGenerator, final SerializerProvider serializerProvider) throws IOException { final Map<String, Object> m = new HashMap<>(); m.put(GraphSONTokens.ORIGINAL, getStepsAsList(traversalExplanation.getOriginalTraversal())); final List<Pair<TraversalStrategy, Traversal.Admin<?, ?>>> strategyTraversals = traversalExplanation.getStrategyTraversals(); final List<Map<String, Object>> intermediates = new ArrayList<>(); for (final Pair<TraversalStrategy, Traversal.Admin<?, ?>> pair : strategyTraversals) { final Map<String, Object> intermediate = new HashMap<>(); intermediate.put(GraphSONTokens.STRATEGY, pair.getValue0().toString()); intermediate.put(GraphSONTokens.CATEGORY, pair.getValue0().getTraversalCategory().getSimpleName()); intermediate.put(GraphSONTokens.TRAVERSAL, getStepsAsList(pair.getValue1())); <START> intermediate.put(GraphSONTokens.TRAVERSAL, getStepsAsList(pair.getValue1())); <END> intermediates.add(intermediate); } m.put(GraphSONTokens.INTERMEDIATE, intermediates); if (strategyTraversals.isEmpty()) m.put(GraphSONTokens.FINAL, getStepsAsList(traversalExplanation.getOriginalTraversal())); else m.put(GraphSONTokens.FINAL, getStepsAsList(strategyTraversals.get(strategyTraversals.size() - 1).getValue1())); jsonGenerator.writeObject(m); }</code><technical_language>Is this line supposed duplicated</technical_language>

Target:
public void serialize(final TraversalExplanation traversalExplanation, final JsonGenerator jsonGenerator, final SerializerProvider serializerProvider) throws IOException { final Map<String, Object> m = new HashMap<>(); m.put(GraphSONTokens.ORIGINAL, getStepsAsList(traversalExplanation.getOriginalTraversal())); final List<Pair<TraversalStrategy, Traversal.Admin<?, ?>>> strategyTraversals = traversalExplanation.getStrategyTraversals(); final List<Map<String, Object>> intermediates = new ArrayList<>(); for (final Pair<TraversalStrategy, Traversal.Admin<?, ?>> pair : strategyTraversals) { final Map<String, Object> intermediate = new HashMap<>(); intermediate.put(GraphSONTokens.STRATEGY, pair.getValue0().toString()); intermediate.put(GraphSONTokens.CATEGORY, pair.getValue0().getTraversalCategory().getSimpleName()); intermediate.put(GraphSONTokens.TRAVERSAL, getStepsAsList(pair.getValue1())); intermediates.add(intermediate); } m.put(GraphSONTokens.INTERMEDIATE, intermediates); if (strategyTraversals.isEmpty()) m.put(GraphSONTokens.FINAL, getStepsAsList(traversalExplanation.getOriginalTraversal())); else m.put(GraphSONTokens.FINAL, getStepsAsList(strategyTraversals.get(strategyTraversals.size() - 1).getValue1())); jsonGenerator.writeObject(m); }
Source:
<code>private void addMetricsCacheClientTasksOnWakeUp() { Runnable task = new Runnable() { @Override public void run() { TopologyMaster.PublishMetrics publishMetrics; <START> synchronized (publishMetricsCommunicator) { <END> publishMetrics = publishMetricsCommunicator.poll(); } while (publishMetrics != null) { LOG.info(String.format("%d Metrics, %d Exceptions to send to MetricsCache", publishMetrics.getMetricsCount(), publishMetrics.getExceptionsCount())); LOG.fine("Publish Metrics sending to MetricsCache: " + publishMetrics.toString()); sendMessage(publishMetrics); synchronized (publishMetricsCommunicator) { publishMetrics = publishMetricsCommunicator.poll(); } } } }; getNIOLooper().addTasksOnWakeup(task); }</code><technical_language>I previously synchronized operations publishMetricsCommunicator. changed? Do work publishMetricsCommunicator in threads</technical_language>

Target:
private void addMetricsCacheClientTasksOnWakeUp() { Runnable task = new Runnable() { @Override public void run() { TopologyMaster.PublishMetrics publishMetrics; while (true) { synchronized (publishMetricsCommunicator) { publishMetrics = publishMetricsCommunicator.poll(); } if (publishMetrics == null) { break; } LOG.info(String.format("%d Metrics, %d Exceptions to send to MetricsCache", publishMetrics.getMetricsCount(), publishMetrics.getExceptionsCount())); LOG.fine("Publish Metrics sending to MetricsCache: " + publishMetrics.toString()); sendMessage(publishMetrics); } } }; getNIOLooper().addTasksOnWakeup(task); }
Source:
<code>public void fillZeroRecords(final ContextAccumulator fullContextAccumulator, final int contextSize) { final String padding = StringUtil.repeatCharNTimes('N', contextSize); for (Map.Entry<String,AlignmentAccumulator[]> fullContext : fullContextAccumulator.artifactMap.entrySet()) { final String context = fullContext.getKey(); final char centralBase = context.charAt(contextSize); <START> final String key = padding + centralBase + padding; <END> final AlignmentAccumulator[] zeroAlignmentAccumulators = this.artifactMap.get(key); final AlignmentAccumulator[] fullAlignmentAccumulators = fullContext.getValue(); for (int i=0; i < fullAlignmentAccumulators.length; i++) { zeroAlignmentAccumulators[i].mergeCounts(fullContext.getValue()[i]); } } }</code><technical_language>rename key->zeroContextKey similar</technical_language>

Target:
public void fillZeroRecords(final ContextAccumulator fullContextAccumulator, final int contextSize) { final String padding = StringUtil.repeatCharNTimes('N', contextSize); for (Map.Entry<String,AlignmentAccumulator[]> fullContext : fullContextAccumulator.artifactMap.entrySet()) { final String fullContextKey = fullContext.getKey(); final char centralBase = fullContextKey.charAt(contextSize); final String zeroContextKey = padding + centralBase + padding; final AlignmentAccumulator[] zeroAlignmentAccumulators = this.artifactMap.get(zeroContextKey); final AlignmentAccumulator[] fullAlignmentAccumulators = fullContext.getValue(); for (int i=0; i < fullAlignmentAccumulators.length; i++) { zeroAlignmentAccumulators[i].merge(fullAlignmentAccumulators[i]); } } }
Source:
<code>public void beforeTest() { reset(tx); elide = mock(Elide.class); user = mock(User.class); asyncQuery = mock(AsyncQuery.class); graphQLParser = mock(GraphQLParser.class); <START> TransactionRegistry transactionRegistry = mock(TransactionRegistry.class); <END> DataStore dataStore = mock(DataStore.class); AuditLogger auditLogger = mock(AuditLogger.class); ElideSettings settings = mock(ElideSettings.class); EntityDictionary dictionary = mock(EntityDictionary.class); EntityProjection projection = EntityProjection.builder().type(AsyncQuery.class).build(); when(asyncQuery.getRequestId()).thenReturn(UUID.randomUUID().toString()); when(asyncQuery.getQueryType()).thenReturn(QueryType.GRAPHQL_V1_0); when(elide.getTransactionRegistry()).thenReturn(transactionRegistry); when(elide.getAuditLogger()).thenReturn(auditLogger); when(elide.getDataStore()).thenReturn(dataStore); when(elide.getElideSettings()).thenReturn(settings); when(settings.getDictionary()).thenReturn(dictionary); when(dataStore.beginTransaction()).thenReturn(tx); when(graphQLParser.parse(any())).thenReturn(projection); }</code><technical_language>I feel mocking of objects tests brittle. Also, mocks global created test. I focus mocking challenging objects (like data store something). else real objects</technical_language>

Target:
public void beforeTest() { dataStore = new HashMapDataStore(AsyncQuery.class.getPackage()); Map<String, Class<? extends Check>> map = new HashMap<>(); map.put(AsyncQueryInlineChecks.AsyncQueryOwner.PRINCIPAL_IS_OWNER, AsyncQueryInlineChecks.AsyncQueryOwner.class); map.put(AsyncQueryInlineChecks.AsyncQueryAdmin.PRINCIPAL_IS_ADMIN, AsyncQueryInlineChecks.AsyncQueryAdmin.class); map.put(AsyncQueryInlineChecks.AsyncQueryStatusValue.VALUE_IS_CANCELLED, AsyncQueryInlineChecks.AsyncQueryStatusValue.class); map.put(AsyncQueryInlineChecks.AsyncQueryStatusQueuedValue.VALUE_IS_QUEUED, AsyncQueryInlineChecks.AsyncQueryStatusQueuedValue.class); elide = new Elide( new ElideSettingsBuilder(dataStore) .withEntityDictionary(new EntityDictionary(map)) .withAuditLogger(new Slf4jLogger()) .build()); user = mock(User.class); }
Source:
<code>public void importProject(final CompleteCallback callback, MutableProjectConfig projectConfig) { final Path path = !isNullOrEmpty(projectConfig.getPath()) ? Path.valueOf(projectConfig.getPath()) : !isNullOrEmpty(projectConfig.getName()) ? Path.valueOf(projectConfig.getName()).makeAbsolute() : null; checkState(path != null, "Import path is undefined"); startImport(path, projectConfig.getSource()) .then( arg -> { if (callback != null) { callback.onCompleted(); } }) .catchError( <START> arg -> { <END> if (callback != null) { callback.onFailure(arg.getCause()); } }); }</code><technical_language>rename this variable error</technical_language>

Target:
public void importProject(final CompleteCallback callback, MutableProjectConfig projectConfig) { final Path path = !isNullOrEmpty(projectConfig.getPath()) ? Path.valueOf(projectConfig.getPath()) : !isNullOrEmpty(projectConfig.getName()) ? Path.valueOf(projectConfig.getName()).makeAbsolute() : null; checkState(path != null, "Import path is undefined"); startImport(path, projectConfig.getSource()) .then( project -> { if (callback != null) { callback.onCompleted(); } }) .catchError( error -> { if (callback != null) { callback.onFailure(error.getCause()); } }); }
Source:
<code>public static String createWebsequenceUrl(String style, String content) { style = StringUtils.defaultString(style, "default"); OutputStreamWriter writer = null; BufferedReader reader = null; try { String query = new StringBuilder() .append("style=") .append(style) .append("&message=") .append(URLEncoder.encode(content, "UTF-8")) .append("&apiVersion=1") .toString(); URL url = new URL("<LINK_1>"); URLConnection conn = url.openConnection(); conn.setDoOutput(true); writer = new OutputStreamWriter(conn.getOutputStream(), StandardCharsets.UTF_8); writer.write(query); writer.flush(); StringBuilder response = new StringBuilder(); reader = new BufferedReader( new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8)); String line; while ((line = reader.readLine()) != null) { response.append(line); } writer.close(); reader.close(); String json = response.toString(); int start = json.indexOf("?png="); int end = json.indexOf("\"", start); if (start != -1 && end != -1) { return "<LINK_0>" + json.substring(start, end); } } catch (IOException e) { <START> throw new RuntimeException("Failed to get proper response from websequencediagrams.com"); <END> } finally { IOUtils.closeQuietly(writer); IOUtils.closeQuietly(reader); } return ""; }</code><technical_language>good idea propagate e Constructor aid debugging</technical_language>

Target:
public static String createWebsequenceUrl(String style, String content) { style = StringUtils.defaultString(style, "default"); OutputStreamWriter writer = null; BufferedReader reader = null; String webSeqUrl = ""; try { String query = new StringBuilder() .append("style=") .append(style) .append("&message=") .append(URLEncoder.encode(content, "UTF-8")) .append("&apiVersion=1") .toString(); URL url = new URL(WEBSEQ_URL); URLConnection conn = url.openConnection(); conn.setDoOutput(true); writer = new OutputStreamWriter(conn.getOutputStream(), StandardCharsets.UTF_8); writer.write(query); writer.flush(); StringBuilder response = new StringBuilder(); reader = new BufferedReader( new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8)); String line; while ((line = reader.readLine()) != null) { response.append(line); } writer.close(); reader.close(); String json = response.toString(); int start = json.indexOf("?png="); int end = json.indexOf("\"", start); if (start != -1 && end != -1) { webSeqUrl = WEBSEQ_URL + "/" + json.substring(start, end); } } catch (IOException e) { throw new RuntimeException("Failed to get proper response from websequencediagrams.com", e); } finally { IOUtils.closeQuietly(writer); IOUtils.closeQuietly(reader); } return webSeqUrl; }
Source:
<code>public FormValidation updateNow() throws IOException { List<JSONObject> jsonList = new ArrayList<>(); boolean toolInstallerMetadataExists = false; for (UpdateSite updatesite : Jenkins.getActiveInstance().getUpdateCenter().getSiteList()) { <START> String site = getUrl(updatesite); <END> String jsonString; try { jsonString = loadJSONHTML(new URL(site + ".html?id=" + URLEncoder.encode(getId(), "UTF-8") + "&version=" + URLEncoder.encode(Jenkins.VERSION, "UTF-8"))); toolInstallerMetadataExists = true; } catch (Exception e) { LOGGER.log(Level.FINE, "Could not load json from " + site, e ); continue; } JSONObject o = JSONObject.fromObject(jsonString); if (signatureCheck) { FormValidation e = updatesite.getJsonSignatureValidator("downloadable '"+id+"'").verifySignature(o); if (e.kind!= Kind.OK) { LOGGER.log(Level.WARNING, "signature check failed for " + site, e ); continue; } } jsonList.add(o); } if (jsonList.size() == 0 && toolInstallerMetadataExists) { return FormValidation.warning("None of the tool installer metadata passed the signature check"); } else if (!toolInstallerMetadataExists) { LOGGER.log(Level.WARNING, "No tool installer metadata found for " + id); return FormValidation.ok(); } JSONObject reducedJson = reduce(jsonList); return load(reducedJson.toString(), System.currentTimeMillis()); }</code><technical_language>Unchecked null. fatal, error propagation is bad</technical_language>

Target:
public FormValidation updateNow() throws IOException { List<JSONObject> jsonList = new ArrayList<>(); boolean toolInstallerMetadataExists = false; for (UpdateSite updatesite : Jenkins.getActiveInstance().getUpdateCenter().getSiteList()) { String site = updatesite.getMetadataUrlForDownloadable(url); if (site == null) { return FormValidation.warning("The update site " + site + " does not look like an update center"); } String jsonString; try { jsonString = loadJSONHTML(new URL(site + ".html?id=" + URLEncoder.encode(getId(), "UTF-8") + "&version=" + URLEncoder.encode(Jenkins.VERSION, "UTF-8"))); toolInstallerMetadataExists = true; } catch (Exception e) { LOGGER.log(Level.FINE, "Could not load json from " + site, e ); continue; } JSONObject o = JSONObject.fromObject(jsonString); if (signatureCheck) { FormValidation e = updatesite.getJsonSignatureValidator(signatureValidatorPrefix +" '"+id+"'").verifySignature(o); if (e.kind!= Kind.OK) { LOGGER.log(Level.WARNING, "signature check failed for " + site, e ); continue; } } jsonList.add(o); } if (jsonList.size() == 0 && toolInstallerMetadataExists) { return FormValidation.warning("None of the tool installer metadata passed the signature check"); } else if (!toolInstallerMetadataExists) { LOGGER.log(Level.WARNING, "No tool installer metadata found for " + id); return FormValidation.ok(); } JSONObject reducedJson = reduce(jsonList); return load(reducedJson.toString(), System.currentTimeMillis()); }
Source:
<code>protected void destroyCreatedChannel(Binding binding) { MessageChannel channel = binding.getChannel(); <START> if ("producer".equals(binding.getType()) && this.createdChannels.contains(channel)) { <END> this.createdChannels.remove(channel); BeanFactory beanFactory = this.applicationContext.getBeanFactory(); if (beanFactory instanceof DefaultListableBeanFactory) { String name = ((NamedComponent) channel).getComponentName(); ((DefaultListableBeanFactory) beanFactory).destroySingleton(name); if (logger.isDebugEnabled()) { logger.debug("Removed channel:" + name); } } } }</code><technical_language>Binding.PRODUCER const instead of leteral</technical_language>

Target:
protected void destroyCreatedChannel(Binding binding) { MessageChannel channel = binding.getChannel(); if (Binding.PRODUCER.equals(binding.getType()) && this.createdChannels.contains(channel)) { this.createdChannels.remove(channel); BeanFactory beanFactory = this.applicationContext.getBeanFactory(); if (beanFactory instanceof DefaultListableBeanFactory) { String name = ((NamedComponent) channel).getComponentName(); ((DefaultListableBeanFactory) beanFactory).destroySingleton(name); if (logger.isDebugEnabled()) { logger.debug("Removed channel:" + name); } } } }
Source:
<code><START> long getTokenCount() { <END> return tokens.get(); }</code><technical_language>nit: I generally prefer explicitly state access modifiers</technical_language>

Target:
protected long getTokenCount() { return tokens.get(); }
Source:
<code>public void populateDAG(DAG dag, Configuration conf) { RandomNumberGenerator rand = dag.addOperator("rand", RandomNumberGenerator.class); StdoutOperator stdout = dag.addOperator("stdout", new StdoutOperator()); <START> dag.addModule("testModule", com.example.mydtapp.TestModule.class); <END> dag.addStream("data", rand.out, stdout.in).setLocality(Locality.CONTAINER_LOCAL); }</code><technical_language>this change is required? Tests run this change well</technical_language>

Target:
public void populateDAG(DAG dag, Configuration conf) { RandomNumberGenerator rand = dag.addOperator("rand", RandomNumberGenerator.class); StdoutOperator stdout = dag.addOperator("stdout", new StdoutOperator()); Module testModule = dag.addModule("testModule", com.example.mydtapp.TestModule.class); dag.addStream("data", rand.out, stdout.in).setLocality(Locality.CONTAINER_LOCAL); }