auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void testServiceDiscovery() throws Exception { final TemporaryJob nginx = jobs.job() .image(NGINX) .port("http", 80, ports.localPort("http")) .registration("nginx", "http", "http") .deploy(); final TemporaryJob alpine = jobs.job() .image(ALPINE) .port("nc", 4711, ports.localPort("nc")) .command("sh", "-c", "apk add --update bind-tools " + "&& export SRV=$(dig -t SRV +short _nginx._http.test.$SPOTIFY_DOMAIN) " + "&& export HOST=$(echo $SRV | cut -d' ' -f4) " + "&& export PORT=$(echo $SRV | cut -d' ' -f3) " + "&& nc -lk -p 4711 -e curl http://$HOST:$PORT" ) .deploy(); final HostAndPort alpineAddress = alpine.address("nc"); <START> final Callable<String> curlResponse = () -> { <END> try (final Socket s = new Socket(alpineAddress.getHostText(), alpineAddress.getPort())) { return IOUtils.toString(s.getInputStream()).trim(); } }; Awaitility.await("alpine container returns nginx welcome") .atMost(10, TimeUnit.SECONDS) .until(curlResponse, containsString("Welcome to nginx!")); assertThat(new String(logStreamProvider.getStderr(nginx.job().getId())), containsString("nginx")); }</code><technical_language>call this var response curl</technical_language>

Target:
public void testServiceDiscovery() throws Exception { final TemporaryJob nginx = jobs.job() .image(NGINX) .port("http", 80, ports.localPort("http")) .registration("nginx", "http", "http") .deploy(); final TemporaryJob alpine = jobs.job() .image(ALPINE) .port("nc", 4711, ports.localPort("nc")) .command("sh", "-c", "apk add --update bind-tools " + "&& export SRV=$(dig -t SRV +short _nginx._http.test.$SPOTIFY_DOMAIN) " + "&& export HOST=$(echo $SRV | cut -d' ' -f4) " + "&& export PORT=$(echo $SRV | cut -d' ' -f3) " + "&& nc -lk -p 4711 -e curl http://$HOST:$PORT" ) .deploy(); final HostAndPort alpineAddress = alpine.address("nc"); final Callable<String> socketResponse = () -> { try (final Socket s = new Socket(alpineAddress.getHostText(), alpineAddress.getPort())) { return IOUtils.toString(s.getInputStream()).trim(); } }; Awaitility.await("alpine container returns nginx welcome") .atMost(10, TimeUnit.SECONDS) .until(socketResponse, containsString("Welcome to nginx!")); assertThat(new String(logStreamProvider.getStderr(nginx.job().getId())), containsString("nginx")); }
Source:
<code>private static String zoneFromUri(String defaultZoneUri) { String hostname = null; try { <START> hostname = new URI(defaultZoneUri).getHost(); <END> } catch (URISyntaxException e) { LOGGER.warning(String.format(INDETERMINATE_EUREKA_ZONE_MESSAGE + " %s", DEFAULT_ZONE_PROPERTY, defaultZoneUri, UNKNOWN_ZONE, e)); return UNKNOWN_ZONE; } if (hostname == null || !hostname.contains(".")) { LOGGER.warning(String.format(INDETERMINATE_EUREKA_ZONE_MESSAGE, DEFAULT_ZONE_PROPERTY, defaultZoneUri, UNKNOWN_ZONE)); return UNKNOWN_ZONE; } return hostname.substring(hostname.indexOf(".") + 1); }</code><technical_language>URI throw a NullPullException if defaultZoneUri is null. case happen</technical_language>

Target:
private static String zoneFromUri(String defaultZoneUri) { String hostname = null; try { hostname = new URI(defaultZoneUri).getHost(); } catch (Exception e) { LOGGER.warning(String.format(INDETERMINATE_EUREKA_ZONE_MESSAGE + " %s", DEFAULT_ZONE_PROPERTY, defaultZoneUri, UNKNOWN_ZONE, e)); return UNKNOWN_ZONE; } if (hostname == null || !hostname.contains(".")) { LOGGER.warning(String.format(INDETERMINATE_EUREKA_ZONE_MESSAGE, DEFAULT_ZONE_PROPERTY, defaultZoneUri, UNKNOWN_ZONE)); return UNKNOWN_ZONE; } return hostname.substring(hostname.indexOf(".") + 1); }
Source:
<code>protected void setup(Context context) throws IOException, InterruptedException { this.connectionTimeout = context.getConfiguration().getInt( IMPORT_CONTENT_CONNECTION_TIMEOUT, 60000); this.readTimeout = context.getConfiguration().getInt( IMPORT_CONTENT_READ_TIMEOUT, 60000); String maxFileSizeMBStr = WorkflowRuntimeParameters.getParamValue( ImportWorkflowRuntimeParameters.IMPORT_CONTENT_MAX_FILE_SIZE_MB, context.getConfiguration()); if (maxFileSizeMBStr != null) { this.contentApprover = new ComplexContentApprover( new PDFHeaderBasedContentApprover(), <START> new SizeLimitContentApprover(Integer.valueOf(maxFileSizeMBStr))); <END> } else { this.contentApprover = new PDFHeaderBasedContentApprover(); } }</code><technical_language>Integer.parseInt</technical_language>

Target:
protected void setup(Context context) throws IOException, InterruptedException { this.connectionTimeout = context.getConfiguration().getInt(IMPORT_CONTENT_CONNECTION_TIMEOUT, 60000); this.readTimeout = context.getConfiguration().getInt(IMPORT_CONTENT_READ_TIMEOUT, 60000); Integer maxFileSizeMB = WorkflowRuntimeParameters.getIntegerParamValue( ImportWorkflowRuntimeParameters.IMPORT_CONTENT_MAX_FILE_SIZE_MB, context.getConfiguration()); if (maxFileSizeMB != null) { this.contentApprover = new ComplexContentApprover(new PDFHeaderBasedContentApprover(), new SizeLimitContentApprover(maxFileSizeMB)); } else { this.contentApprover = new PDFHeaderBasedContentApprover(); } }
Source:
<code>public Response getTopology(@PathParam("id") String id, @DefaultValue(":all-time") @QueryParam("window") String window, @QueryParam("sys") boolean sys, @QueryParam(callbackParameterName) String callback) throws TException { topologyPageRequestMeter.mark(); try (NimbusClient nimbusClient = NimbusClient.getConfiguredClient(config)) { return UIHelpers.makeStandardResponse( UIHelpers.getTopologySummary( nimbusClient.getClient().getTopologyPageInfo(id, window, sys), window, config, servletRequest.getRemoteUser() ), callback ); <START> } catch (RuntimeException e) { <END> LOG.error("Failure getting topology visualization", e); throw e; } }</code><technical_language>do need this</technical_language>

Target:
public Response getTopology(@PathParam("id") String id, @DefaultValue(":all-time") @QueryParam("window") String window, @QueryParam("sys") boolean sys, @QueryParam(callbackParameterName) String callback) throws TException { topologyPageRequestMeter.mark(); try (NimbusClient nimbusClient = NimbusClient.getConfiguredClient(config)) { return UIHelpers.makeStandardResponse( UIHelpers.getTopologySummary( nimbusClient.getClient().getTopologyPageInfo(id, window, sys), window, config, servletRequest.getRemoteUser() ), callback ); } }
Source:
<code>public HttpRequest setUrl(String url) { try { this.url = new URL(url); } catch (MalformedURLException e) { <START> throw logger.logExceptionAsWarning(new IllegalArgumentException("'url' must be a valid URL.")); <END> } return this; }</code><technical_language>here. Add e argument IllegalArgumentException constructor</technical_language>

Target:
public HttpRequest setUrl(String url) { try { this.url = new URL(url); } catch (MalformedURLException ex) { throw logger.logExceptionAsWarning(new IllegalArgumentException("'url' must be a valid URL.", ex)); } return this; }
Source:
<code>public void prepareListeners(){ <START> this.dummyListener = ExtensionList.lookup(SecurityListener.class).get(DummySecurityListener.class); <END> dummyListener.clearPreviousCalls(); }</code><technical_language>@daniel-beck a PR simplify this call: <LINK_0></technical_language>

Target:
public void prepareListeners(){ this.spySecurityListener = ExtensionList.lookup(SecurityListener.class).get(SpySecurityListenerImpl.class); }
Source:
<code><START> public boolean evaluate(Tuple tuple, ImmutableBytesWritable ptr) { <END> Expression expression = children.get(0); if (!expression.evaluate(tuple, ptr)) { return false; } else if (ptr.getLength() == 0) { return true; } byte[] bs = ptr.get(); if (this.dataType == null) { this.dataType = getDataType(); } Object object = this.dataType.toObject(bs, ptr.getOffset(), ptr.getLength(), this.dataType, this.index); byte[] bytes = this.dataType.toBytes(object); ptr.set(bytes); return true; }</code><technical_language>Sound doable</technical_language>

Target:
public boolean evaluate(Tuple tuple, ImmutableBytesWritable ptr) { Expression indexExpr = children.get(1); if (!indexExpr.evaluate(tuple, ptr)) { return false; } else if (ptr.getLength() == 0) { return true; } int index = PDataType.INTEGER.getCodec().decodeInt(ptr, indexExpr.getColumnModifier()); if(index < 0) { throw new ParseException("Index cannot be negative :" + index); } Expression arrayExpr = children.get(0); if (!arrayExpr.evaluate(tuple, ptr)) { return false; } else if (ptr.getLength() == 0) { return true; } PArrayDataType.positionAtArrayElement(ptr, index, getDataType()); return true; }
Source:
<code>public String getGridNodeContainerId() throws IOException { if (!gridMode) { throw new UnsupportedOperationException("We can't get grid node container id in local mode."); } if (gridNodeContainerId == null) { String getGridNodeInfoUrl = format("http://localhost:4444/grid/api/testsession?session=%s", getSessionId()); <START> <END> Map<String, String> gridNodeInfo; try { gridNodeInfo = httpJsonRequestFactory.fromUrl(getGridNodeInfoUrl).request().asProperties(); } catch (ServerException | UnauthorizedException | ForbiddenException | NotFoundException | ConflictException | BadRequestException e) { throw new IOException(e); } if (!gridNodeInfo.containsKey("proxyId")) { throw new IOException("Proxy ID of grid node wasn't found."); } URL proxyId = new URL(gridNodeInfo.get("proxyId")); gridNodeContainerId = dockerUtil.findGridNodeContainerByIp(proxyId.getHost()); } return gridNodeContainerId; }</code><technical_language>id grid other configuration in some specific cases? localhost:4444</technical_language>

Target:
public String getGridNodeContainerId() throws IOException { if (!gridMode) { throw new UnsupportedOperationException("We can't get grid node container id in local mode."); } if (gridNodeContainerId == null) { String getGridNodeInfoUrl = format( "http://localhost:%s/grid/api/testsession?session=%s", webDriverPort, driver.getSessionId()); Map<String, String> gridNodeInfo; try { gridNodeInfo = httpJsonRequestFactory.fromUrl(getGridNodeInfoUrl).request().asProperties(); } catch (ServerException | UnauthorizedException | ForbiddenException | NotFoundException | ConflictException | BadRequestException e) { throw new IOException(e); } if (!gridNodeInfo.containsKey("proxyId")) { throw new IOException("Proxy ID of grid node wasn't found."); } URL proxyId = new URL(gridNodeInfo.get("proxyId")); gridNodeContainerId = dockerUtil.findGridNodeContainerByIp(proxyId.getHost()); } return gridNodeContainerId; }
Source:
<code>public List<String> getSuggestions(String input) { <START> return WorldEdit.getInstance().getPlatformManager() <END> .queryCapability(Capability.GAME_HOOKS).getWorlds().stream() .map(World::getId) .filter(world -> world.startsWith(input)) .collect(Collectors.toList()); }</code><technical_language>extract world-stream extraction method</technical_language>

Target:
public List<String> getSuggestions(String input) { return getWorlds() .map(World::getId) .filter(world -> world.startsWith(input)) .collect(Collectors.toList()); }
Source:
<code>private Criteria buildCoreCriteria(final Map<StudyFilters, String> parameters, final Order orderBy) { final Criteria criteria = this.getSession().createCriteria(this.getPersistentClass()); criteria.createAlias("properties", "pr"); criteria.add(Restrictions.eq("pr.typeId", TermId.STUDY_TYPE.getId())); final DetachedCriteria inactive = DetachedCriteria.forClass(ProjectProperty.class); inactive.add(Restrictions.eq(DmsProjectDao.TYPE_ID, Integer.valueOf(DmsProjectDao.STUDY_STATUS))); inactive.add(Restrictions.eq(DmsProjectDao.VALUE, String.valueOf(DmsProjectDao.DELETED_STUDY))); inactive.setProjection(Projections.property("project.projectId")); criteria.add(Property.forName(DmsProjectDao.PROJECT_ID).notIn(inactive)); if (parameters.containsKey(StudyFilters.PROGRAM_ID)) { criteria.add(Restrictions.eq(StudyFilters.PROGRAM_ID.getParameter(), parameters.get(StudyFilters.PROGRAM_ID))); <START> }else{ <END> criteria.add(Restrictions.isNotNull(StudyFilters.PROGRAM_ID.getParameter())); } if (parameters.containsKey(StudyFilters.LOCATION_ID)) { final DetachedCriteria ppLocation = DetachedCriteria.forClass(ProjectProperty.class); ppLocation.add(Restrictions.eq(DmsProjectDao.TYPE_ID, DmsProjectDao.LOCATION_ABBR)); ppLocation.add(Restrictions.ilike(DmsProjectDao.VALUE, '%' + parameters.get(StudyFilters.LOCATION_ID).toLowerCase() + '%')); ppLocation.setProjection(Projections.property("project.projectId")); criteria.add(Property.forName(DmsProjectDao.PROJECT_ID).in(ppLocation)); } criteria.addOrder(orderBy); return criteria; }</code><technical_language>format</technical_language>

Target:
private Criteria buildCoreCriteria(final Map<StudyFilters, String> parameters, final Order orderBy) { final Criteria criteria = this.getSession().createCriteria(this.getPersistentClass()); criteria.createAlias("properties", "pr"); criteria.add(Restrictions.eq("pr.typeId", TermId.STUDY_TYPE.getId())); final DetachedCriteria inactive = DetachedCriteria.forClass(ProjectProperty.class); inactive.add(Restrictions.eq(DmsProjectDao.TYPE_ID, Integer.valueOf(DmsProjectDao.STUDY_STATUS))); inactive.add(Restrictions.eq(DmsProjectDao.VALUE, String.valueOf(DmsProjectDao.DELETED_STUDY))); inactive.setProjection(Projections.property("project.projectId")); criteria.add(Property.forName(DmsProjectDao.PROJECT_ID).notIn(inactive)); if (parameters.containsKey(StudyFilters.PROGRAM_ID)) { criteria.add(Restrictions.eq(StudyFilters.PROGRAM_ID.getParameter(), parameters.get(StudyFilters.PROGRAM_ID))); } else { criteria.add(Restrictions.isNotNull(StudyFilters.PROGRAM_ID.getParameter())); } if (parameters.containsKey(StudyFilters.LOCATION_ID)) { final DetachedCriteria ppLocation = DetachedCriteria.forClass(ProjectProperty.class); ppLocation.add(Restrictions.eq(DmsProjectDao.TYPE_ID, DmsProjectDao.LOCATION_ID)); ppLocation.add(Restrictions.eq(DmsProjectDao.VALUE, parameters.get(StudyFilters.LOCATION_ID))); ppLocation.setProjection(Projections.property("project.projectId")); criteria.add(Property.forName(DmsProjectDao.PROJECT_ID).in(ppLocation)); } criteria.addOrder(orderBy); return criteria; }
Source:
<code>public void run() { while (true) { try { Thread.sleep(watchInterval); } catch (InterruptedException ie) { Thread.currentThread().interrupt(); } if (!isBookieRunning()) { shutdown(); if (null != uncaughtExceptionHandler) { uncaughtExceptionHandler.uncaughtException( this, new BookieDeadException("Bookie is not running any more") <START> .fillInStackTrace()); <END> } break; } } LOG.info("BookieDeathWatcher exited loop!"); }</code><technical_language>do need fillInStackTrace() here? Stack trace filled in Throwable's constructor already, assuming BookieException called super's constructor. this BookieException. "public BookieException(int code)" sets private field code call super(). other constructors call super(..) variants set code rely getCode(). Luckily, getCode() is do bother passing code field</technical_language>

Target:
public void run() { while (true) { try { Thread.sleep(watchInterval); } catch (InterruptedException ie) { Thread.currentThread().interrupt(); } if (!isBookieRunning()) { LOG.info("BookieDeathWatcher noticed the bookie is not running any more, exiting the watch loop!"); throw new RuntimeException("Bookie is not running any more"); } } }
Source:
<code>public void onMapReady(@NonNull final MapboxMap mapboxMap) { this.mapboxMap = mapboxMap; mapboxMap.setStyle(Style.SATELLITE, new Style.OnStyleLoaded() { @Override public void onStyleLoaded(@NonNull Style style) { mapboxMap.animateCamera( CameraUpdateFactory.newCameraPosition(new CameraPosition.Builder() .zoom(16) .build()), 4000); fillLayerPointList = new ArrayList<>(); circleLayerFeatureList = new ArrayList<>(); <START> lineLayerPointList = new ArrayList<>(); <END> initCircleSource(); initLineSource(); initFillSource(); circleSource = mapboxMap.getStyle().getSourceAs(CIRCLE_SOURCE_ID); fillSource = mapboxMap.getStyle().getSourceAs(FILL_SOURCE_ID); lineSource = mapboxMap.getStyle().getSourceAs(LINE_SOURCE_ID); initCircleLayer(); initLineLayer(); initFillLayer(); initFloatingActionButtonClickListeners(); Toast.makeText(SatelliteLandSelectActivity.this, R.string.trace_instruction, Toast.LENGTH_LONG).show(); } }); }</code><technical_language>initialized field creation final</technical_language>

Target:
public void onMapReady(@NonNull final MapboxMap mapboxMap) { this.mapboxMap = mapboxMap; mapboxMap.setStyle(Style.SATELLITE, new Style.OnStyleLoaded() { @Override public void onStyleLoaded(@NonNull Style style) { mapboxMap.animateCamera( CameraUpdateFactory.newCameraPosition(new CameraPosition.Builder() .zoom(16) .build()), 4000); circleSource = initCircleSource(style); fillSource = initFillSource(style); lineSource = initLineSource(style); initCircleLayer(style); initLineLayer(style); initFillLayer(style); initFloatingActionButtonClickListeners(); Toast.makeText(SatelliteLandSelectActivity.this, R.string.trace_instruction, Toast.LENGTH_LONG).show(); } }); }
Source:
<code>public static void sendEmail(String content) { if (!shouldSendEmail) { LOGGER.warn("EmailLogger is disabled (email.send must be set to true) or has not been setup. " + "Will not send email. Message: " + content); return; } try { Properties props = System.getProperties(); props.setProperty("mail.transport.protocol", "smtp"); props.put("mail.smtp.host", mailHost); props.put("mail.smtp.port", mailPort); Session session = Session.getInstance(props, null); MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress(senderEmail)); for (String to : emailList) <START> message.addRecipient(Message.RecipientType.TO, new InternetAddress(to, false)); <END> message.setSubject(subjectLine); message.setContent(content, "text/html"); Transport.send(message); } catch(Exception exception) { LOGGER.warn("Could not send requested email. Message: " + content, exception); } }</code><technical_language>add braces</technical_language>

Target:
public static void sendEmail(String content) { if (!shouldSendEmail) { LOGGER.warn("EmailLogger is disabled (email.send must be set to true) or has not been setup. " + "Will not send email. Message: " + content); return; } try { Properties props = System.getProperties(); props.setProperty("mail.transport.protocol", "smtp"); props.put("mail.smtp.host", mailHost); props.put("mail.smtp.port", mailPort); Session session = Session.getInstance(props, null); MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress(senderEmail)); for (String to : emailList) { message.addRecipient(Message.RecipientType.TO, new InternetAddress(to, false)); } message.setSubject(subjectLine); message.setContent(content, "text/html"); Transport.send(message); } catch(Exception exception) { LOGGER.warn("Could not send requested email. Message: " + content, exception); } }
Source:
<code>public void shouldCreateIndexesInCollection() throws Exception { List<PopulationStatistics> populationStatisticsList = buildPopulationStatsList(); String databaseName = mongoRule.getRandomTemporaryDatabaseName(); StatisticsMongoWriter statisticsMongoWriter = getStatisticsMongoWriter(databaseName); statisticsMongoWriter.write(populationStatisticsList); DBCollection statsCollection = mongoRule.getCollection(databaseName, jobOptions.getDbCollectionsStatsName()); assertEquals("[{ \"v\" : 1 , \"key\" : { \"_id\" : 1} , \"name\" : \"_id_\" , \"ns\" : \"" + databaseName + ".populationStatistics\"}, { \"v\" : 1 , \"unique\" : true , \"key\" : " + "{ \"chr\" : 1 , \"start\" : 1 , \"ref\" : 1 , \"alt\" : 1 , \"sid\" : 1 , \"cid\" : 1} , " + "\"name\" : \"vscid\" , \"ns\" : \"" + databaseName + ".populationStatistics\"}]", <START> statsCollection.getIndexInfo().toString()); <END> }</code><technical_language>This test compare DBObjects extracted getIndexInfo() equals() method</technical_language>

Target:
public void shouldCreateIndexesInCollection() throws Exception { List<PopulationStatistics> populationStatisticsList = buildPopulationStatsList(); String databaseName = mongoRule.getRandomTemporaryDatabaseName(); StatisticsMongoWriter statisticsMongoWriter = getStatisticsMongoWriter(databaseName); statisticsMongoWriter.write(populationStatisticsList); DBCollection statsCollection = mongoRule.getCollection(databaseName, jobOptions.getDbCollectionsStatsName()); List<DBObject> indexes = new ArrayList<>(); indexes.add(new BasicDBObject("v", 1) .append("key", new BasicDBObject("_id", 1)) .append("name", "_id_") .append("ns", databaseName + ".populationStatistics") ); indexes.add(new BasicDBObject("v", 1) .append("unique", true) .append("key", new BasicDBObject("chr", 1) .append("start", 1) .append("ref", 1) .append("alt", 1) .append("sid", 1) .append("cid", 1)) .append("name", "vscid") .append("ns", databaseName + ".populationStatistics") ); assertEquals(statsCollection.getIndexInfo(), indexes); }
Source:
<code>public CompletableFuture<Void> send(Address address, Message message) { transport.send(address, message, COMPLETED_PROMISE); <START> return COMPLETED_PROMISE; <END> }</code><technical_language>I return if is completed promise. In case is send return value, returns void. transport send method do accept parameter practically this</technical_language>

Target:
public void send(Address address, Message message) { transport.send(address, message); }
Source:
<code>void onQuickAddNext() { <START> if (!(docDisplay_ instanceof AceEditor)) <END> return; AceEditor editor = (AceEditor) docDisplay_; if (editor.getNativeSelection().isEmpty()) { editor.getNativeSelection().selectWord(); return; } String needle = editor.getSelectionValue(); Search search = Search.create( needle, false, true, true, true, editor.getCursorPosition(), null, false); Range range = search.find(editor.getSession()); if (range == null) return; editor.getNativeSelection().addRange(range, false); editor.centerSelection(); }</code><technical_language>this case</technical_language>

Target:
void onQuickAddNext() { docDisplay_.quickAddNext(); }
Source:
<code>public Secret createSecret(String projectId, String secretId) throws IOException { try (SecretManagerServiceClient client = SecretManagerServiceClient.create()) { ProjectName parent = ProjectName.of(projectId); CreateSecretRequest request = CreateSecretRequest.newBuilder() .setParent(parent.toString()) .setSecretId(secretId) .setSecret( <START> Secret.newBuilder() <END> .setReplication( Replication.newBuilder() .setAutomatic(Replication.Automatic.newBuilder().build()) .build()) .build()) .build(); Secret secret = client.createSecret(request); System.out.printf("Created secret %s\n", secret.getName()); return secret; } }</code><technical_language>nit: Nesting builders this hamper readability. I generally prefer build a single line (or two) prior building request</technical_language>

Target:
public void createSecret(String projectId, String secretId) throws IOException { try (SecretManagerServiceClient client = SecretManagerServiceClient.create()) { ProjectName parent = ProjectName.of(projectId); Secret secret = Secret.newBuilder() .setReplication( Replication.newBuilder() .setAutomatic(Replication.Automatic.newBuilder().build()) .build()) .build(); CreateSecretRequest request = CreateSecretRequest.newBuilder() .setParent(parent.toString()) .setSecretId(secretId) .setSecret(secret) .build(); Secret createdSecret = client.createSecret(request); System.out.printf("Created secret %s\n", createdSecret.getName()); } }
Source:
<code>public void handleResponse(Object response) { <START> if (response.getBucket().isEmpty()) { <END> throw new RuntimeException( "Got response from service with empty/missing bucketName: " + response.toString()); } Map<String, byte[]> metadata = Maps.transformValues( response.getMetadataMap(), value -> { try { return BaseEncoding.base64().decode(value); } catch (IllegalArgumentException iae) { logger.atSevere().withCause(iae).log( "In: " + this + "Failed to parse base64 encoded attribute value %s - %s", value, iae); return null; } }); byte[] md5Hash = response.getMd5Hash().length() > 0 ? BaseEncoding.base64().decode(response.getMd5Hash()) : null; byte[] crc32c = response.hasCrc32C() ? ByteBuffer.allocate(4).putInt(response.getCrc32C().getValue()).array() : null; completedItemInfo = new GoogleCloudStorageItemInfo( new StorageResourceId(response.getBucket(), response.getName()), Timestamps.toMillis(response.getUpdated()), Timestamps.toMillis(response.getUpdated()), response.getSize(), null, null, response.getContentType(), response.getContentEncoding(), metadata, response.getGeneration(), response.getMetageneration(), new VerificationAttributes(md5Hash, crc32c)); }</code><technical_language>checkArgument instead: java checkArgument( !response.getBucket().isEmpty(), "Got response service empty/missing bucketName: %s" response);</technical_language>

Target:
public void handleResponse(Object response) { checkArgument( !response.getBucket().isEmpty(), "Got response from service with empty/missing bucketName: %s", response); Map<String, byte[]> metadata = response.getMetadataMap().entrySet().stream() .collect( toMap(Map.Entry::getKey, entry -> BaseEncoding.base64().decode(entry.getValue()))); byte[] md5Hash = response.getMd5Hash().length() > 0 ? BaseEncoding.base64().decode(response.getMd5Hash()) : null; byte[] crc32c = response.hasCrc32C() ? ByteBuffer.allocate(4).putInt(response.getCrc32C().getValue()).array() : null; completedItemInfo = new GoogleCloudStorageItemInfo( new StorageResourceId(response.getBucket(), response.getName()), Timestamps.toMillis(response.getTimeCreated()), Timestamps.toMillis(response.getUpdated()), response.getSize(), null, null, response.getContentType(), response.getContentEncoding(), metadata, response.getGeneration(), response.getMetageneration(), new VerificationAttributes(md5Hash, crc32c)); }
Source:
<code>public void should_report_secondary_issue_locations_from_eslint_based_rules() throws Exception { when(eslintBridgeServerMock.call(any())).thenReturn( "[{\"line\":1,\"column\":3,\"endLine\":3,\"endColumn\":5,\"ruleId\":\"no-all-duplicated-branches\",\"message\":\"Issue message\", " + "\"cost\": 14," + <START> "\"secondaryLocations\": [{ message: \"Secondary\", \"line\":1,\"column\":3,\"endLine\":3,\"endColumn\":5}]}]"); <END> EslintBasedRulesSensor sensor = createSensor(); DefaultInputFile inputFile = createInputFile(context); sensor.execute(context); assertThat(context.allIssues()).hasSize(1); Iterator<Issue> issues = context.allIssues().iterator(); Issue issue = issues.next(); IssueLocation location = issue.primaryLocation(); assertThat(location.inputComponent()).isEqualTo(inputFile); assertThat(location.message()).isEqualTo("Issue message"); assertThat(location.textRange()).isEqualTo(new DefaultTextRange(new DefaultTextPointer(1, 2), new DefaultTextPointer(3, 4))); assertThat(issue.gap()).isEqualTo(14); List<IssueLocation> secondaryLocations = issue.flows().get(0).locations(); assertThat(secondaryLocations).hasSize(1); IssueLocation secondary = secondaryLocations.get(0); assertThat(secondary.inputComponent()).isEqualTo(inputFile); assertThat(secondary.message()).isEqualTo("Secondary"); assertThat(secondary.textRange()).isEqualTo(new DefaultTextRange(new DefaultTextPointer(1, 2), new DefaultTextPointer(3, 4))); }</code><technical_language>2 secondaries location primary nice test issue cost secondaries</technical_language>

Target:
public void should_report_secondary_issue_locations_from_eslint_based_rules() throws Exception { when(eslintBridgeServerMock.call(any())).thenReturn( "[{\"line\":1,\"column\":3,\"endLine\":3,\"endColumn\":5,\"ruleId\":\"no-all-duplicated-branches\",\"message\":\"Issue message\", " + "\"cost\": 14," + "\"secondaryLocations\": [" + "{ message: \"Secondary\", \"line\":2,\"column\":1,\"endLine\":2,\"endColumn\":4}," + "{ message: \"Secondary\", \"line\":3,\"column\":2,\"endLine\":3,\"endColumn\":5}" + "]}]"); EslintBasedRulesSensor sensor = createSensor(); DefaultInputFile inputFile = createInputFile(context); sensor.execute(context); assertThat(context.allIssues()).hasSize(1); Iterator<Issue> issues = context.allIssues().iterator(); Issue issue = issues.next(); assertThat(issue.gap()).isEqualTo(14); assertThat(issue.flows()).hasSize(2); IssueLocation secondary1 = issue.flows().get(0).locations().get(0); assertThat(secondary1.inputComponent()).isEqualTo(inputFile); assertThat(secondary1.message()).isEqualTo("Secondary"); assertThat(secondary1.textRange()).isEqualTo(new DefaultTextRange(new DefaultTextPointer(2, 0), new DefaultTextPointer(2, 3))); IssueLocation secondary2 = issue.flows().get(1).locations().get(0); assertThat(secondary2.inputComponent()).isEqualTo(inputFile); assertThat(secondary2.message()).isEqualTo("Secondary"); assertThat(secondary2.textRange()).isEqualTo(new DefaultTextRange(new DefaultTextPointer(3, 1), new DefaultTextPointer(3, 4))); }
Source:
<code>public Schema(List<Column> columns) { if (columns instanceof ImmutableList) { @SuppressWarnings("unchecked") ImmutableList<Column> columnsCasted = (ImmutableList)columns; this.columns = columnsCasted; } else { <START> this.columns = ImmutableList.copyOf(columns); <END> } }</code><technical_language>This line is good. Other lines necessary ImmutableList.copyOf logic internally. fix it</technical_language>

Target:
public Schema(List<Column> columns) { this.columns = ImmutableList.copyOf(columns); }
Source:
<code>private void fetch() { <START> if ((current == null || current.length <= pos) && base.hasNext()) { <END> T[] result = Objects.requireNonNull(base.next()); wrapUp(result); current = result; pos = 0; } }</code><technical_language>specific this PR, but, I a quick overview of relationships current, pos, base. I thought I figured out for a minute I guess I don't</technical_language>

Target:
private void fetch() { if ((currentPage == null || currentPage.length <= nextItemIndex) && base.hasNext()) { T[] result = Objects.requireNonNull(base.next()); wrapUp(result); currentPage = result; nextItemIndex = 0; } }
Source:
<code><START> public String redact(String redactableString) { for (String stopWord : STOP_WORDS) { if (redactableString.contains(stopWord)) { switch (stopWord) { case USER_DELEGATION_KEY: redactableString = redactUserDelegationKey(redactableString); break; case ACCESS_TOKEN: redactableString = redactAccessToken(redactableString); break; default: break; } } } return redactableString; } <END></code><technical_language>simplify this this: java private static final List<Function<String, String>> RECORDING_REDACTORS = loadRedactors(); private static List<Function<String, String>> loadRedactors() { List<Function<String, String>> redactors = new ArrayList<>(); redactors.add(Redactor::redactAccessToken); redactors.add(Redactor::redactDelegationKey); return redactors; } private static String redactDelegationKey(String content) { // redact content } private static String redactAccessToken(String content) { // redact content } public String redact(String redactableString) { String redactedString = redactableString; for (Function<String, String> redactor : RECORDING_REDACTORS) { redactedString = redactor.apply(redactedString); } return redactedString; }</technical_language>

Target:
public String redact(String redactableString) { String redactedString = redactableString; for (Function<String, String> redactor : RECORDING_REDACTORS) { redactedString = redactor.apply(redactedString); } return redactedString; }
Source:
<code>public boolean isPackageExportedTo(PackageBinding pkg, ModuleBinding client) { <START> PackageBinding resolved = getDeclaredPackage(pkg.compoundName); <END> if (resolved != null) { if (this.isAuto || this == client) { return true; } Predicate<IPackageExport> isExportedTo = e -> Stream.of(e.targets()).map(ref -> this.environment.getModule(ref)).filter(m -> m != null).anyMatch(client::equals); return Stream.of(this.exports).filter(e -> CharOperation.equals(pkg.readableName(), e.name())) .anyMatch(e -> { if (!e.isQualified()) return true; return client != this.environment.UnNamedModule && isExportedTo.test(e); }); } return false; }</code><technical_language>This indirection binding->name->binding bogus me. explain achieves? In particular: if "resolved != pkg" unrelated packages (regardless of name) resolved instead of pkg give wrong results, no</technical_language>

Target:
public boolean isPackageExportedTo(PackageBinding pkg, ModuleBinding client) { PackageBinding resolved = getDeclaredPackage(pkg.compoundName); if (resolved == pkg) { if (this.isAuto) { return true; } Predicate<IPackageExport> isExportedTo = e -> Stream.of(e.targets()).map(ref -> this.environment.getModule(ref)).filter(m -> m != null).anyMatch(client::equals); return Stream.of(this.exports).filter(e -> CharOperation.equals(pkg.readableName(), e.name())) .anyMatch(e -> { if (!e.isQualified()) return true; return client != this.environment.UnNamedModule && isExportedTo.test(e); }); } return false; }
Source:
<code>public void initialize(BatchRuntimeContext context) throws Exception { <START> batchConfig.verifySolrConfiguration(); <END> }</code><technical_language>this check done in configurePipeline stage. fail early deploy time runtime. If macros, sense do this check prepareRun, currently macros either</technical_language>

Target:
public void initialize(BatchRuntimeContext context) throws Exception { metrics = context.getMetrics(); batchConfig.testSolrConnection(); }
Source:
<code>public static boolean singleNewlineTerminated(File inputFile) throws IOException { RandomAccessFile randomAccessFile = new RandomAccessFile(inputFile, READ_ONLY_MODE); if (inputFile.length() < 1) { return true; } long indexOfLastByte = inputFile.length() - 1; long numTerminatingNewlines = 0; randomAccessFile.seek(indexOfLastByte); while (Byte.compare(randomAccessFile.readByte(), NEWLINE_DELIMITER) == 0) { <START> numTerminatingNewlines++; <END> indexOfLastByte--; if (indexOfLastByte < 0) { return false; } randomAccessFile.seek(indexOfLastByte); } return (numTerminatingNewlines == 1L); }</code><technical_language>short circuit this loop numTerminationNewline 1</technical_language>

Target:
public static boolean singleNewlineTerminated(File inputFile) throws IOException { RandomAccessFile randomAccessFile = new RandomAccessFile(inputFile, READ_ONLY_MODE); if (inputFile.length() < 1) { return true; } randomAccessFile.seek(inputFile.length() - 1); if (Byte.compare(randomAccessFile.readByte(), NEWLINE_DELIMITER) != 0) { return false; } if (inputFile.length() < 2) { return true; } randomAccessFile.seek(inputFile.length() - 2); return (Byte.compare(randomAccessFile.readByte(), NEWLINE_DELIMITER) != 0); }
Source:
<code>public boolean isInDiskCacheSync(final Uri uri) { <START> return isInDiskCacheSync(uri, ImageRequest.CacheChoice.DEFAULT); <END> }</code><technical_language>check caches here? isInDiskCacheSync(uri, CacheChoice.SMALL) || isInDiskCacheSync(uri, CacheChoice.DEFAULT) in-memory index for disk cache now, this faster</technical_language>

Target:
public boolean isInDiskCacheSync(final Uri uri) { return isInDiskCacheSync(uri, ImageRequest.CacheChoice.SMALL) || isInDiskCacheSync(uri, ImageRequest.CacheChoice.DEFAULT); }
Source:
<code>public boolean initialize() { if (events == null) { try { events = CacheBuilder.newBuilder() <START> .expireAfterWrite(unit.toMillis(expiration), TimeUnit.MILLISECONDS) <END> .build(); logger.info("initialized replication cache with expiration in {}: {}", unit, expiration); } catch (Exception ex) { logger.warn("initialize failure in {}: {}", unit, expiration); return false; } } return true; }</code><technical_language>unit parameter</technical_language>

Target:
public boolean initialize() { if (events == null) { try { events = CacheBuilder.newBuilder() .expireAfterWrite(expiration, unit) .build(); logger.info("initialized replication cache with expiration in {}: {}", unit, expiration); } catch (Exception ex) { logger.warn("initialize failure in {}: {}", unit, expiration); return false; } } return true; }
Source:
<code>private ArrayList<String> loadWMSServers() { <START> CoreWorkspace ws = (CoreWorkspace) Services.getService(CoreWorkspace.class); <END> File file = new File(ws.getWorkspaceFolder() + File.separator + WMSServerFile); try { if (file.exists()) { return readWMSServerFile(new FileInputStream(file)); } else { return readWMSServerFile(WMSConnectionPanel.class.getResourceAsStream(WMSServerFile)); } } catch (IOException e) { } return null; }</code><technical_language>useless cast</technical_language>

Target:
private ArrayList<String> loadWMSServers() { CoreWorkspace ws = Services.getService(CoreWorkspace.class); File file = new File(ws.getWorkspaceFolder() + File.separator + WMSServerFile); try { if (file.exists()) { return readWMSServerFile(new FileInputStream(file)); } else { return readWMSServerFile(WMSConnectionPanel.class.getResourceAsStream(WMSServerFile)); } } catch (IOException e) { LOGGER.error(I18N.tr("Cannot load the list of WMS url"), e); } return null; }
Source:
<code>public List<CloudResource> handleTransientDeployment(AzureClient client, String resourceGroupName, String deploymentName) { List<CloudResource> deployedResources = new ArrayList<>(); ResourceStatus deploymentStatus = client.getTemplateDeploymentStatus(resourceGroupName, deploymentName); if (deploymentStatus.isTransient()) { LOGGER.info("Template deployment has transient status , cancelling it now.", deploymentName, deploymentStatus); Deployment deployment = client.getTemplateDeployment(resourceGroupName, deploymentName); deployment.cancel(); deployedResources = azureCloudResourceService.getDeploymentCloudResources(deployment); LOGGER.info("Found resources to be removed: {}", deployedResources); <START> List<CloudResource> transientVms = deployedResources.stream() .filter(cloudResource -> ResourceType.AZURE_INSTANCE == cloudResource.getType()) .collect(Collectors.toList()); List<CloudResource> osDiskResources = azureCloudResourceService.getAttachedOsDiskResources(transientVms, resourceGroupName, client); <END> deployedResources.addAll(osDiskResources); } return deployedResources; }</code><technical_language>please extract lines a separate method</technical_language>

Target:
public List<CloudResource> handleTransientDeployment(AzureClient client, String resourceGroupName, String deploymentName) { List<CloudResource> deployedResources = azureTransientDeploymentService.handleTransientDeployment(client, resourceGroupName, deploymentName); if (CollectionUtils.isNotEmpty(deployedResources)) { List<CloudResource> osDiskResources = getOsDiskResources(client, resourceGroupName, deployedResources); deployedResources.addAll(osDiskResources); } return deployedResources; }
Source:
<code>public Void visit(Definition def, Void _) { super.visit(def, _); if (def.getMainSyntaxModule().equals(def.getMainModule())) { <START> def.getModulesMap().get(def.getMainModule()).getModuleContext().addImportedModule(this.getCurrentDefinition().getModulesMap().get(Constants.AUTO_INCLUDED_MODULE)); <END> moduleInclusion.addRelation(def.getModulesMap().get(def.getMainModule()).getName(), Constants.AUTO_INCLUDED_MODULE); } List<String> circuit = moduleInclusion.checkForCycles(); if (circuit != null) { String msg = "Found circularity in module imports: "; for (String moduleName : circuit) msg += moduleName + " < "; msg += circuit.get(0); throw KExceptionManager.compilerError(msg, this, def); } Set<Module> visited = new HashSet<>(); DFS(def.getModulesMap().get(def.getMainModule()), visited); return null; }</code><technical_language>this wrong me. visitors check correct information autoincludes add "imports" statement</technical_language>

Target:
public Void visit(Definition def, Void _) { super.visit(def, _); Set<Module> visited = new HashSet<>(); DFS(def.getDefinitionContext().getModuleByName(def.getMainModule()), visited); return null; }
Source:
<code>public Map<String, String> getAliasMap() { <START> return aliases; <END> }</code><technical_language>interface docs this a read-only reference; this transformed ImmutableMap copied returned</technical_language>

Target:
public ImmutableMap<String, String> getAliasMap() { return aliases; }
Source:
<code><START> public LoggingInterceptor(@NonNull Logger logger) { <END> this.logger = logger; }</code><technical_language>I suppose private create static method. easer support compatibility in future)</technical_language>

Target:
private LoggingInterceptor(@NonNull Logger logger) { this.logger = logger; }
Source:
<code>public void run() throws OperationException { try { Class clazz = Class.forName(auditStorageClass); if (!AuditStorage.class.isAssignableFrom(clazz)) { throw new OperationException( "The class " + auditStorageClass + " does not implement the AuditStorage interface"); } AuditStorage auditStorage = (AuditStorage) clazz.getDeclaredConstructor().newInstance(); <START> Logs auditBackend = (Logs) Framework.getService(AuditLogger.class); <END> auditBackend.restore(auditStorage, batchSize, keepAlive); } catch (ReflectiveOperationException e) { throw new OperationException("Cannot create audit storage of type " + auditStorageClass, e); } }</code><technical_language>do Framework.getService(Logs.class)</technical_language>

Target:
public void run() { NXAuditEventsService audit = (NXAuditEventsService) Framework.getRuntime() .getComponent(NXAuditEventsService.NAME); auditBackend.restore(audit.getAuditStorage(auditStorageId), batchSize, keepAlive); }
Source:
<code>public final void testSuccessfulConsumerStateTransition() throws Exception { ExecutorService directExecutorService = spy(executorService); doAnswer(invocation -> directlyExecuteRunnable(invocation)) .when(directExecutorService).execute(any()); ShardConsumer consumer = new ShardConsumer(recordsPublisher, directExecutorService, shardInfo, logWarningForTaskAfterMillis, shardConsumerArgument, blockedOnParentsState, t -> t, 1, taskExecutionListener, 0); mockSuccessfulUnblockOnParents(); mockSuccessfulInitializeWithFailureTransition(); mockSuccessfulProcessing(null); int arbitraryExecutionCount = 3; <START> do { <END> try { consumer.executeLifecycle(); } catch (Exception e) { } } while (--arbitraryExecutionCount > 0); assertEquals(ShardConsumerState.PROCESSING.consumerState().state(), consumer.currentState().state()); verify(directExecutorService, times(2)).execute(any()); }</code><technical_language>Consider writing regular while loop for readability</technical_language>

Target:
public final void testSuccessfulConsumerStateTransition() throws Exception { ExecutorService directExecutorService = spy(executorService); doAnswer(invocation -> directlyExecuteRunnable(invocation)) .when(directExecutorService).execute(any()); ShardConsumer consumer = new ShardConsumer(recordsPublisher, directExecutorService, shardInfo, logWarningForTaskAfterMillis, shardConsumerArgument, blockedOnParentsState, t -> t, 1, taskExecutionListener, 0); mockSuccessfulUnblockOnParents(); mockSuccessfulInitializeWithFailureTransition(); mockSuccessfulProcessing(null); int arbitraryExecutionCount = 3; do { try { consumer.executeLifecycle(); } catch (Exception e) { fail("Unexpected exception while executing consumer lifecycle"); } } while (--arbitraryExecutionCount > 0); assertEquals(ShardConsumerState.PROCESSING.consumerState().state(), consumer.currentState().state()); verify(directExecutorService, times(2)).execute(any()); }
Source:
<code>public void testRemoveObserver() throws CacheException { InfinispanPropertyCache cache = createCache(); CountingObserver observer = new CountingObserver(); Property<Integer> property = new Property<>("id1", 2); cache.store(null, property); cache.addObserver(null, "id1", observer); cache.store(null, new Property<>("id1", 34)); Assert.assertEquals(1, observer.updatedCounter.intValue()); cache.removeObserver(null, "id1", observer); <START> cache.store(null, new Property<>("id1", 34)); <END> Assert.assertEquals(1, observer.updatedCounter.intValue()); }</code><technical_language>This update update counter anyway, value. sure, change 34 else - test is fine</technical_language>

Target:
public void testRemoveObserver() throws CacheException { CountingObserver observer = new CountingObserver(); propertyCache.store(null, new Property<>("id1", 2)); propertyCache.addObserver(null, "id1", observer); propertyCache.store(null, new Property<>("id1", 34)); Assert.assertEquals(1, observer.updatedCounter.intValue()); propertyCache.removeObserver(null, "id1", observer); propertyCache.store(null, new Property<>("id1", 32)); Assert.assertEquals(1, observer.updatedCounter.intValue()); }
Source:
<code>public void testUnsupportedKeyValueCollectionOperations() { final String key1 = "1", value1 = "one", key2 = "2", value2 = "two", key3 = "3", value3 = "three"; Map<String, String> m = new HashMap<>(); m.put(key1, value1); m.put(key2, value2); m.put(key3, value3); cache(0, "replSync").putAll(m); Set<Object> keys = cache(0, "replSync").keySet(); Collection<Object> values = cache(0, "replSync").values(); Collection[] collections = new Collection[]{keys, values}; Object newObj = new Object(); List newObjCol = new ArrayList(); newObjCol.add(newObj); for (Collection col : collections) { try { col.add(newObj); <START> assert false : "Should have thrown a UnsupportedOperationException"; <END> } catch (UnsupportedOperationException uoe) { } catch (ClassCastException e) { } try { col.addAll(newObjCol); assert false : "Should have thrown a UnsupportedOperationException"; } catch (UnsupportedOperationException uoe) { } } }</code><technical_language>JDK assertions fail()</technical_language>

Target:
public void testUnsupportedKeyValueCollectionOperations() { final String key1 = "1", value1 = "one", key2 = "2", value2 = "two", key3 = "3", value3 = "three"; Map<String, String> m = new HashMap<>(); m.put(key1, value1); m.put(key2, value2); m.put(key3, value3); cache(0, "replSync").putAll(m); Set<Object> keys = cache(0, "replSync").keySet(); Collection<Object> values = cache(0, "replSync").values(); Collection[] collections = new Collection[]{keys, values}; Object newObj = new Object(); List newObjCol = new ArrayList(); newObjCol.add(newObj); for (Collection col : collections) { try { col.add(newObj); fail("Should have thrown a UnsupportedOperationException"); } catch (UnsupportedOperationException uoe) { } catch (ClassCastException e) { } try { col.addAll(newObjCol); fail("Should have thrown a UnsupportedOperationException"); } catch (UnsupportedOperationException uoe) { } } }
Source:
<code>protected IRefreshMonitor createPollingMonitor(IResource resource) { PollingMonitor monitor = <START> ((Workspace)resource.getWorkspace()).getRefreshManager().monitors.pollMonitor; <END> monitor.monitor(resource); return monitor; }</code><technical_language>Long call chains this investigating NPEs harder necessary. A space is missing cast</technical_language>

Target:
protected IRefreshMonitor createPollingMonitor(IResource resource) { Workspace workspace = (Workspace) resource.getWorkspace(); RefreshManager refreshManager = workspace.getRefreshManager(); MonitorManager monitors = refreshManager.monitors; PollingMonitor pollingMonitor = monitors.pollMonitor; pollingMonitor.monitor(resource); return pollingMonitor; }
Source:
<code>public PipelineStatus getPipelineStatus() { <START> return new PipelineStatus(ImmutableList.copyOf(this.drivers)); <END> }</code><technical_language>PipelineStatus constructor dumb possible. Put logic instead</technical_language>

Target:
public PipelineStatus getPipelineStatus() { return getPipelineStatus(ImmutableList.copyOf(drivers)); }
Source:
<code><START> public String toString() { return "" + key; } <END></code><technical_language>Integer.toString</technical_language>

Target:
public String toString() { return Integer.toString(key); }