auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void remove(String path) throws IOException { final File fileToDelete = new File(path); if (!fileToDelete.exists()) { LOGGER.debug(String.format("Cannot remove file or directory: path \"%s\" does not exist", path)); return; } <START> assertInDirectory(fileToDelete); <END> if (fileToDelete.isDirectory()) { FileUtils.deleteDirectory(fileToDelete); } else { Files.deleteIfExists(fileToDelete.toPath()); } }</code><technical_language>I assertion moved if (!fileToDelete.exists()) { .. }</technical_language>

Target:
public void remove(String path) throws IOException { final File fileToDelete = new File(path); assertInDirectory(fileToDelete); if (!fileToDelete.exists()) { LOGGER.debug(String.format("Cannot remove file or directory: path \"%s\" does not exist", path)); return; } if (fileToDelete.isDirectory()) { FileUtils.deleteDirectory(fileToDelete); } else { Files.deleteIfExists(fileToDelete.toPath()); } }
Source:
<code>public void getMemberships_shouldGetMembershipsAsOfADate() throws Exception { executeDataSet(COHORT_XML); Cohort cohort = Context.getCohortService().getCohort(1); CohortMembership newMember = new CohortMembership((new Patient(4))); SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date dateToTest = dateFormat.parse("2016-11-01 00:00:00"); newMember.setStartDate(dateToTest); service.addMembershipToCohort(cohort, newMember); List<CohortMembership> membersAsOfDate = cohort.getMemberships(dateToTest); <START> assertFalse(membersAsOfDate.isEmpty()); <END> }</code><technical_language>add another call asOfDate returns some matches</technical_language>

Target:
public void getMemberships_shouldGetMembershipsAsOfADate() throws Exception { executeDataSet(COHORT_XML); Cohort cohort = Context.getCohortService().getCohort(1); CohortMembership newMember = new CohortMembership((new Patient(4))); SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date dateToTest = dateFormat.parse("2016-11-01 00:00:00"); newMember.setStartDate(dateToTest); service.addMembershipToCohort(cohort, newMember); List<CohortMembership> membersAsOfDate = cohort.getMemberships(dateToTest); assertFalse(membersAsOfDate.isEmpty()); assertTrue(membersAsOfDate.stream().anyMatch(m -> m.getStartDate().equals(dateToTest))); }
Source:
<code>private void deployJob(final Job job) throws Exception { if (job != null) { <START> ModuleDescriptor descriptor = createJobModuleDescriptor(job.getName(), <END> job.getJobModuleDescriptor().getModuleName()); ModuleDeploymentWriter.ModuleDeploymentPropertiesProvider provider = new ModuleDeploymentWriter.ModuleDeploymentPropertiesProvider() { @Override public ModuleDeploymentProperties propertiesForDescriptor(ModuleDescriptor descriptor) { return DeploymentUtility.createModuleDeploymentProperties(job.getDeploymentProperties(), descriptor); } }; List<ModuleDescriptor> descriptors = new ArrayList<ModuleDescriptor>(); descriptors.add(descriptor); Collection<ModuleDeploymentWriter.Result> results = moduleDeploymentWriter.writeDeployment(descriptors.iterator(), provider); moduleDeploymentWriter.validateResults(results); } }</code><technical_language>get a ModuleDescriptor job.getJobModuleDescriptor(), creating a new instance</technical_language>

Target:
private void deployJob(final Job job) throws Exception { if (job != null) { ModuleDeploymentWriter.ModuleDeploymentPropertiesProvider provider = new ModuleDeploymentWriter.ModuleDeploymentPropertiesProvider() { @Override public ModuleDeploymentProperties propertiesForDescriptor(ModuleDescriptor descriptor) { return DeploymentPropertiesUtility.createModuleDeploymentProperties( job.getDeploymentProperties(), descriptor); } }; List<ModuleDescriptor> descriptors = new ArrayList<ModuleDescriptor>(); descriptors.add(job.getJobModuleDescriptor()); Collection<ModuleDeploymentWriter.Result> results = moduleDeploymentWriter.writeDeployment(descriptors.iterator(), provider); moduleDeploymentWriter.validateResults(results); } }
Source:
<code>public void createSubnet() throws InterruptedException { server.enqueue(jsonResponse("/createsubnetresponse.json").setResponseCode(200)); final SubnetApi subnetApi = api.getSubnetApi(resourcegroup, virtualNetwork); Subnet.SubnetProperties properties = Subnet.SubnetProperties.create(null, "10.2.0.0/24", null); Subnet subnet = subnetApi.createOrUpdateSubnet(subnetName, properties); String path = String.format("/subscriptions/%s/resourcegroups/%s/providers/Microsoft.Network/virtualNetworks/%s/subnets/%s?%s", subscriptionid, resourcegroup, virtualNetwork, subnetName, apiVersion); <START> String json = String.format("{ \"properties\":{\"addressPrefix\":\"%s\"}}", "10.2.0.0/24"); <END> assertSent(server, "PUT", path, json); assertEquals(subnet.name(), subnetName); assertEquals(subnet.properties().addressPrefix(), "10.2.0.0/24"); }</code><technical_language>[minor] is need Stirng.format build this String, a hardcoded value</technical_language>

Target:
public void createSubnet() throws InterruptedException { server.enqueue(jsonResponse("/createsubnetresponse.json").setResponseCode(200)); final SubnetApi subnetApi = api.getSubnetApi(resourcegroup, virtualNetwork); Subnet.SubnetProperties properties = Subnet.SubnetProperties.builder().addressPrefix("10.2.0.0/24").build(); Subnet subnet = subnetApi.createOrUpdate(subnetName, properties); String path = String.format("/subscriptions/%s/resourcegroups/%s/providers/Microsoft.Network/virtualNetworks/%s/subnets/%s?%s", subscriptionid, resourcegroup, virtualNetwork, subnetName, apiVersion); String json = "{ \"properties\":{\"addressPrefix\":\"10.2.0.0/24\"}}"; assertSent(server, "PUT", path, json); assertEquals(subnet.name(), subnetName); assertEquals(subnet.properties().addressPrefix(), "10.2.0.0/24"); }
Source:
<code>private String buildCounterName(String prefix, String name, Map<String, String> tags) { <START> return prefix + "." + name + "." + tags.values().stream().collect(Collectors.joining(".")); <END> }</code><technical_language>String.join(".", tags.values()) instead of tags.values().stream().collect(Collectors.joining(".")</technical_language>

Target:
private String buildCounterName(String prefix, String name, Map<String, String> tags) { return prefix + "." + name + "." + String.join(".", tags.values()); }
Source:
<code>private void executeAddSecurityConstraintCommand(List<InputPair> inputs) throws Exception { try (CommandController commandController = testHarness .createCommandController(AddSecurityConstraintCommand.class, project.getRoot())) { commandController.initialize(); for (InputPair input : inputs) { commandController.setValueFor(input.inputName, input.inputValue); } <START> commandController.execute(); <END> } }</code><technical_language>nice add assertion result</technical_language>

Target:
private void executeAddSecurityConstraintCommand(List<InputPair> inputs) throws Exception { try (CommandController commandController = testHarness .createCommandController(AddSecurityConstraintCommand.class, project.getRoot())) { commandController.initialize(); for (InputPair input : inputs) { commandController.setValueFor(input.inputName, input.inputValue); } Result result = commandController.execute(); assertFalse(result instanceof Failed); } }
Source:
<code>private void addLastUpdateTime(BusinessDetail businessDetail) { try { if(PropertyAccessor.getInstance().getPropertyBoolean(GATEWAY_PROPERTY_FILE, UDDI_UPDATE_TIME)) { businessDetail.setUddiUpdatetime(getTimestamp()); } } catch (PropertyAccessException ex) { <START> LOG.error("Unable to access property: " + UDDI_UPDATE_TIME, ex); <END> } catch (DatatypeConfigurationException ex) { LOG.error("Unable to create timestamp for: " + UDDI_UPDATE_TIME, ex); } }</code><technical_language>Optional: Recommend parameterized logging LOG.error("Unable access property: {}, {}"",UDDI_UPDATE_TIME, ex);</technical_language>

Target:
private void addLastUpdateTime(BusinessDetail businessDetail) { try { if(PropertyAccessor.getInstance().getPropertyBoolean(GATEWAY_PROPERTY_FILE, UDDI_UPDATE_TIME)) { businessDetail.setUddiUpdatetime(getTimestamp()); } } catch (PropertyAccessException ex) { LOG.error("Unable to access property: {}", UDDI_UPDATE_TIME, ex); } catch (DatatypeConfigurationException ex) { LOG.error("Unable to create timestamp for: {}", UDDI_UPDATE_TIME, ex); } }
Source:
<code><START> public List<AudioData> speakBlocking(String toSpeak) { <END> if (mouth != null && !mute) { try { return mouth.speakBlocking(toSpeak); } catch (Exception e) { Logging.logError(e); } } return null; }</code><technical_language>here. This method is speech synthesis service. removed here</technical_language>

Target:
public List<AudioData> speakBlocking(String toSpeak) { if (mouth == null) { log.error("speakBlocking is called, but my mouth is NULL..."); return null; } if (!mute) { try { return mouth.speakBlocking(toSpeak); } catch (Exception e) { Logging.logError(e); } } return null; }
Source:
<code>public void testCreateEmailMessage(){ List<String> senderList = new ArrayList<String>(); senderList.add("sender@xxx.com"); EmailMessage emailMessage = null; Props props = new Props(); props.put("mail.port",445); props.put("mail.user","somebody"); props.put("mail.password","pwd"); props.put("mail.sender","somebody@xxx.com"); props.put("server.port","114"); props.put("server.useSSL","false"); AbstractMailer mailer = new AbstractMailer(props); emailMessage = mailer.createEmailMessage("subject","text/html",senderList); assert emailMessage.getMailPort()==445; <START> Props defaultProps = new Props(); <END> defaultProps.put("mail.user","somebody"); defaultProps.put("mail.password","pwd"); defaultProps.put("mail.sender","somebody@xxx.com"); defaultProps.put("server.port","114"); defaultProps.put("server.useSSL","false"); mailer = new AbstractMailer(defaultProps); emailMessage = mailer.createEmailMessage("subject","text/html",senderList); assert emailMessage.getMailPort()==25; }</code><technical_language>Consider making a separate test? reduce duplicate code</technical_language>

Target:
public void testCreateEmailMessage(){ Props props = createMailProperties(); props.put("mail.port","445"); AbstractMailer mailer = new AbstractMailer(props); EmailMessage emailMessage = mailer.createEmailMessage("subject","text/html",senderList); assert emailMessage.getMailPort()==445; }
Source:
<code>public static void main(String[] args) { CommandLineParameters params = new CommandLineParameters(); try { JCommander jc = new JCommander(params, args); if (params.help) { jc.setProgramName("java -Xmx[several]G -jar otp.jar"); jc.usage(); System.exit(0); } if (params.version) { <START> ch.qos.logback.classic.Logger mavenVersionLogger = <END> (ch.qos.logback.classic.Logger)LoggerFactory.getLogger(MavenVersion.class); mavenVersionLogger.setLevel(Level.OFF); MavenVersion version = MavenVersion.VERSION; System.out.println(version.getVersion(params.versionFragment)); System.exit(0); } params.infer(); } catch (ParameterException pex) { LOG.error("Parameter error: {}", pex.getMessage()); System.exit(1); } if (params.build == null && !params.visualize && !params.server && params.scriptFile == null) { LOG.info("Nothing to do. Use --help to see available tasks."); System.exit(-1); } OTPMain main = new OTPMain(params); main.run(); }</code><technical_language>Programmatically shutting logging (which is kind of ugly) necessary more, I silenced logging happening time MavenVersion parsed properties</technical_language>

Target:
public static void main(String[] args) { CommandLineParameters params = new CommandLineParameters(); try { JCommander jc = new JCommander(params, args); if (params.help) { jc.setProgramName("java -Xmx[several]G -jar otp.jar"); jc.usage(); System.exit(0); } if (params.version) { MavenVersion version = MavenVersion.VERSION; System.out.println(version.getVersion()); System.exit(0); } params.infer(); } catch (ParameterException pex) { LOG.error("Parameter error: {}", pex.getMessage()); System.exit(1); } if (params.build == null && !params.visualize && !params.server && params.scriptFile == null) { LOG.info("Nothing to do. Use --help to see available tasks."); System.exit(-1); } OTPMain main = new OTPMain(params); main.run(); }
Source:
<code>public HttpResponse addApplicationWithCustomAttributes (String application, String tier, String callbackUrl, String description, String applicationAttributes) throws APIManagerIntegrationTestException { try { checkAuthentication(); String urlAppAttributes = URLEncoder.encode(applicationAttributes, "UTF-8"); return HTTPSClientUtils.doPost( new URL(backendURL + "store/site/blocks/application/application-add" + "/ajax/application-add.jag?action=addApplication&tier=" + tier + "&callbackUrl=" + callbackUrl + "&description=" + description + "&application=" + application + "&applicationAttributes=" + urlAppAttributes), "", requestHeaders); <START> } catch (Exception e) { <END> throw new APIManagerIntegrationTestException("Unable to add application - " + application + " with custom attributes. Error: " + e.getMessage(), e); } }</code><technical_language>Instead of generic exception, catch relevant exception(s) here. is practice :)</technical_language>

Target:
public HttpResponse addApplicationWithCustomAttributes (String application, String tier, String callbackUrl, String description, String applicationAttributes) throws APIManagerIntegrationTestException { try { checkAuthentication(); String urlAppAttributes = URLEncoder.encode(applicationAttributes, "UTF-8"); return HTTPSClientUtils.doPost( new URL(backendURL + "store/site/blocks/application/application-add" + "/ajax/application-add.jag?action=addApplication&tier=" + tier + "&callbackUrl=" + callbackUrl + "&description=" + description + "&application=" + application + "&applicationAttributes=" + urlAppAttributes), "", requestHeaders); } catch (IOException e) { String message = "Unable to add application - " + application + " with custom attributes. Error: " + e.getMessage(); log.error(message); throw new APIManagerIntegrationTestException(message, e); } }
Source:
<code>private static String getLinkedResourceExpectedUri( final String entityApi, final String entityId, final Set<String> optionalHalParams, final String linkedEntityType) throws URISyntaxException { final String uriPath = new StringBuilder() .append(entityApi) .append("/") .append(entityId) .append("/") .append(linkedEntityType) .toString(); final String uriString = new URI(URI_SCHEME, URI_HOST, uriPath, null).toString(); <START> String halParams = ""; <END> if (optionalHalParams != null && !optionalHalParams.isEmpty()) { halParams = new StringBuilder() .append("{?") .append(StringUtils.join(optionalHalParams, ",")) .append("}") .toString(); } return uriString + halParams; }</code><technical_language>halParams a new StringBuilder do toString effect. Saves allocating effectively strings</technical_language>

Target:
private static String getLinkedResourceExpectedUri( final String entityApi, final String entityId, final Set<String> optionalHalParams, final String linkedEntityType) throws URISyntaxException { final String uriPath = new StringBuilder() .append(entityApi) .append("/") .append(entityId) .append("/") .append(linkedEntityType) .toString(); final String uriString = new URI(URI_SCHEME, URI_HOST, uriPath, null).toString(); final StringBuilder halParamsStringBuilder = new StringBuilder(); if (optionalHalParams != null && !optionalHalParams.isEmpty()) { halParamsStringBuilder .append("{?") .append(StringUtils.join(optionalHalParams, ",")) .append("}") .toString(); } return uriString + halParamsStringBuilder.toString(); }
Source:
<code>public CborObject toCbor() { Map<String, CborObject> result = new TreeMap<>(); <START> result.put("b", dummySource.toCbor()); <END> result.put("k", cipher.toCbor()); return CborObject.CborMap.build(result); }</code><technical_language>strings b,k is a bit unclear</technical_language>

Target:
public CborObject toCbor() { Map<String, CborObject> result = new TreeMap<>(); result.put("k", dummySource.toCbor()); result.put("f", followRequest.toCbor()); return CborObject.CborMap.build(result); }
Source:
<code>public List<Capability> findByIds(List<Integer> ids) { <START> ids = ImmutableList.copyOf(new TreeSet<>(ids)); <END> List<Capability> capabilities = Lists.newArrayList(); for (Integer id : ids) { if (this.capabilities.containsKey(id)) { Capability capability = this.capabilities.get(id); capabilities.add(capability); } } return capabilities; }</code><technical_language>Lists</technical_language>

Target:
public CapabilityList findByIds(List<Integer> ids) { ids = Lists.newArrayList(new TreeSet<>(ids)); List<Capability> capabilities = Lists.newArrayList(); for (Integer id : ids) { if (this.capabilities.containsKey(id)) { Capability capability = this.capabilities.get(id); capabilities.add(capability); } } return new CapabilityList(capabilities); }
Source:
<code>public void writeExecuteBatch(NetPreparedStatement materialPreparedStatement, Section section, ColumnMetaData parameterMetaData, Object[] inputs, int numInputColumns, boolean outputExpected, boolean chained) throws SqlException { buildEXCSQLSTT(section, true, outputExpected, false, null, false, false, 0, false, 0, false, 0, false, 0, true, <START> inputs.length); END> if (numInputColumns > 0) { if ((extdtaPositions_ != null) && (!extdtaPositions_.isEmpty())) { extdtaPositions_.clear(); } boolean overrideExists = buildSQLDTAcommandDataBatch(numInputColumns, parameterMetaData, inputs); buildEXTDTA(parameterMetaData, inputs, chained); } }</code><technical_language>"qryrowset" tag moved lines</technical_language>

Target:
public void writeExecuteBatch(NetPreparedStatement materialPreparedStatement, Section section, ColumnMetaData parameterMetaData, Object[] inputs, int numInputColumns, boolean outputExpected, boolean chained) throws SqlException { buildEXCSQLSTT(section, true, outputExpected, false, null, false, false, 0, false, 0, false, 0, false, 0, true, inputs.length); if (numInputColumns > 0) { if ((extdtaPositions_ != null) && (!extdtaPositions_.isEmpty())) { extdtaPositions_.clear(); } boolean overrideExists = buildSQLDTAcommandData(numInputColumns, parameterMetaData, inputs); buildEXTDTA(parameterMetaData, inputs, chained); } }
Source:
<code>public void execute(SensorContext context) { PythonConfiguration conf = new PythonConfiguration(context.fileSystem().encoding()); MetricVisitor metricVisitor = new MetricVisitor(fileLinesContextFactory, context.fileSystem(), conf.getIgnoreHeaderComments()); FilePredicates p = context.fileSystem().predicates(); List<InputFile> inputFiles = ImmutableList.copyOf( context.fileSystem().inputFiles(p.and(p.hasType(InputFile.Type.MAIN), p.hasLanguage(Python.KEY)))); <START> new PythonScanner(context, checks, metricVisitor, noSonarFilter, inputFiles).scanFiles(); <END> if (!isSonarLint(context)) { (new PythonCoverageSensor()).execute(context, metricVisitor.fileLinesVisitor().linesOfCodeByFile()); } }</code><technical_language>@pynicolas This design is consistent enough. sensor delegates operations scanner - OK. scanner everything, exception - coverage. This is optimal. existence of extra field linesOfCodeByFile in scanner class is suspicious. delegating lines 77-79 scanner? This imply renaming PythonCoverageSensor else (for best), for instance PythonCoverageMeasurer</technical_language>

Target:
public void execute(SensorContext context) { FilePredicates p = context.fileSystem().predicates(); List<InputFile> inputFiles = ImmutableList.copyOf( context.fileSystem().inputFiles(p.and(p.hasType(InputFile.Type.MAIN), p.hasLanguage(Python.KEY)))); PythonScanner scanner = new PythonScanner(context, checks, fileLinesContextFactory, noSonarFilter, inputFiles); scanner.scanFiles(); }
Source:
<code>public void spellCheckAllText() throws BadLocationException { Document doc = rSyntaxTextArea.getDocument(); if (doc != null) { String editorText = rSyntaxTextArea.getText(0, doc.getLength()); if (editorText != null) { Highlighter highlighter = rSyntaxTextArea.getHighlighter(); Highlighter.HighlightPainter painter = new DefaultHighlighter.DefaultHighlightPainter(Color.PINK); JLanguageTool langTool = new JLanguageTool(new AmericanEnglish()); for (Rule rule : langTool.getAllActiveRules()) { if (rule instanceof SpellingCheckRule) { ((SpellingCheckRule)rule).acceptPhrases(Arrays.asList("tex", "Tex", "TEX", "documentclass", "maketitle")); } <START> } <END> boolean highlighted = getEditorState().isHighlighted(); if(!highlighted) { List<RuleMatch> matches = null; try { matches = langTool.check(editorText); } catch (IOException ex) { Exceptions.printStackTrace(ex); } for (RuleMatch match : matches) { highlighter.addHighlight(match.getFromPos(), match.getToPos(), painter); } } else { Highlighter.Highlight[] highlighters = highlighter.getHighlights(); for (int i = 0; i < highlighters.length; i++) { if (highlighters[i].getPainter() instanceof DefaultHighlighter.DefaultHighlightPainter) { highlighter.removeHighlight(highlighters[i]); } } } getEditorState().setHighlighted(!highlighted); } } }</code><technical_language>LanguageTool object rules created/configured time I click "check" button. Ideally this live in a separate class initiated application startup. runtime, call "check" tool. I this is main reason app hangs for some time clicking "check"</technical_language>

Target:
public void spellCheckAllText() throws BadLocationException { Document doc = rSyntaxTextArea.getDocument(); if (doc != null) { String editorText = rSyntaxTextArea.getText(0, doc.getLength()); if (editorText != null) { Highlighter highlighter = rSyntaxTextArea.getHighlighter(); boolean highlighted = getEditorState().isHighlighted(); if(!highlighted) { List<RuleMatch> matches = null; try { matches = langTool.check(editorText); } catch (IOException ex) { Exceptions.printStackTrace(ex); } for (RuleMatch match : matches) { highlighter.addHighlight(match.getFromPos(), match.getToPos(), painter); } } else { highlighter.removeAllHighlights(); } getEditorState().setHighlighted(!highlighted); } } }
Source:
<code>public static MongoClient getMongoClient(Properties properties) throws UnknownHostException { String[] hosts = properties.getProperty("eva.mongo.host").split(","); List<ServerAddress> servers = new ArrayList<>(); for (String host : hosts) { String[] params = host.split(":"); if (params.length > 1) { servers.add(new ServerAddress(params[0], Integer.parseInt(params[1]))); } else { servers.add(new ServerAddress(params[0], 27017)); } } List<MongoCredential> mongoCredentialList = null; String authenticationDb = properties.getProperty("eva.mongo.auth.db", null); if (authenticationDb != null && !authenticationDb.isEmpty()) { mongoCredentialList = Collections.singletonList(MongoCredential.createCredential( properties.getProperty("eva.mongo.user"), authenticationDb, properties.getProperty("eva.mongo.passwd").toCharArray())); } MongoClientOptions options = MongoClientOptions.builder() <START> .readPreference(ReadPreference.valueOf(properties.getProperty("eva.mongo.read-preference"))) <END> .build(); return new MongoClient(servers, mongoCredentialList, options); }</code><technical_language>A reasonable default for this getProperty "secondaryPreferred". systems' recommendation, if secondaries automatically sends requests primary</technical_language>

Target:
public static MongoClient getMongoClient(Properties properties) throws UnknownHostException { String[] hosts = properties.getProperty("eva.mongo.host").split(","); List<ServerAddress> servers = new ArrayList<>(); for (String host : hosts) { String[] params = host.split(":"); if (params.length > 1) { servers.add(new ServerAddress(params[0], Integer.parseInt(params[1]))); } else { servers.add(new ServerAddress(params[0], 27017)); } } List<MongoCredential> mongoCredentialList = null; String authenticationDb = properties.getProperty("eva.mongo.auth.db", null); if (authenticationDb != null && !authenticationDb.isEmpty()) { mongoCredentialList = Collections.singletonList(MongoCredential.createCredential( properties.getProperty("eva.mongo.user"), authenticationDb, properties.getProperty("eva.mongo.passwd").toCharArray())); } String readPreference = properties.getProperty("eva.mongo.read-preference"); readPreference = readPreference == null || readPreference.isEmpty()? "secondaryPreferred" : readPreference; MongoClientOptions options = MongoClientOptions.builder() .readPreference(ReadPreference.valueOf(readPreference)) .build(); return new MongoClient(servers, mongoCredentialList, options); }
Source:
<code>public void mapAndSend(Event[] events, OptionHolder optionHolder, TemplateBuilder payloadTemplateBuilder, SinkListener sinkListener, DynamicOptions dynamicOptions) throws ConnectionUnavailableException { StringBuilder sb = null; if (payloadTemplateBuilder == null) { <START> String jsonString = constructJsonForDefaultMapping(events); <END> if (jsonString != null) { sb = new StringBuilder(); sb.append(jsonString); } } else { sb = new StringBuilder(); sb.append(constructJsonForCustomMapping(events, payloadTemplateBuilder)); } if (sb != null) { if (!isJsonValidationEnabled) { sinkListener.publish(sb.toString(), dynamicOptions); } else if (isValidJson(sb.toString())) { sinkListener.publish(sb.toString(), dynamicOptions); } else { log.error("Invalid json string : " + sb.toString() + ". Hence dropping the message."); } } }</code><technical_language>this null. else simplify this code</technical_language>

Target:
public void mapAndSend(Event[] events, OptionHolder optionHolder, TemplateBuilder payloadTemplateBuilder, SinkListener sinkListener, DynamicOptions dynamicOptions) throws ConnectionUnavailableException { StringBuilder sb = new StringBuilder(); if (payloadTemplateBuilder == null) { String jsonString = constructJsonForDefaultMapping(events); sb.append(jsonString); } else { sb.append(constructJsonForCustomMapping(events, payloadTemplateBuilder)); } if (!isJsonValidationEnabled) { sinkListener.publish(sb.toString(), dynamicOptions); } else if (isValidJson(sb.toString())) { sinkListener.publish(sb.toString(), dynamicOptions); } else { log.error("Invalid json string : " + sb.toString() + ". Hence dropping the message."); } }
Source:
<code>static Response readBodyToBytesIfNecessary(Response response) throws IOException { final ResponseBody body = response.body(); if (body == null) { return response; } BufferedSource source = body.source(); final Buffer buffer = new Buffer(); buffer.writeAll(source); source.close(); return response.newBuilder() .body(new ResponseBody() { @Override public MediaType contentType() { return body.contentType(); } @Override public long contentLength() { return buffer.size(); } @Override public BufferedSource source() { <START> return buffer; <END> } }) .build(); }</code><technical_language>Do need clone here</technical_language>

Target:
static Response readBodyToBytesIfNecessary(Response response) throws IOException { final ResponseBody body = response.body(); if (body == null) { return response; } BufferedSource source = body.source(); final Buffer buffer = new Buffer(); buffer.writeAll(source); source.close(); return response.newBuilder() .body(new ResponseBody() { @Override public MediaType contentType() { return body.contentType(); } @Override public long contentLength() { return buffer.size(); } @Override public BufferedSource source() { return buffer.clone(); } }) .build(); }
Source:
<code><START> static void validateValueUniquenessInScope(String type, List<Type> nestedTypes) { <END> BitSet tags = new BitSet(); for (Type nestedType : nestedTypes) { if (nestedType instanceof EnumType) { EnumType enumType = (EnumType) nestedType; for (Value value : enumType.getValues()) { int tag = value.getTag(); if (tags.get(tag)) { throw new IllegalStateException("Duplicate enum tag " + tag + " in scope " + type); } tags.set(tag); } } } }</code><technical_language>weird. I this a rule</technical_language>

Target:
static void validateValueUniquenessInScope(String type, List<Type> nestedTypes) { Set<Integer> tags = new LinkedHashSet<Integer>(); for (Type nestedType : nestedTypes) { if (nestedType instanceof EnumType) { EnumType enumType = (EnumType) nestedType; for (Value value : enumType.getValues()) { int tag = value.getTag(); if (!tags.add(tag)) { throw new IllegalStateException("Duplicate enum tag " + tag + " in scope " + type); } } } } }
Source:
<code>public CSVMetaDataBuilder addField(String fieldName, DataType type, List<MetaDataFieldProperty> fieldProperties) { <START> fields.add(new DefaultMetaDataField(fieldName, new DefaultSimpleMetaDataModel(type), MetaDataField.FieldAccessType.READ, fieldProperties)); <END> return this; }</code><technical_language>validating in place list is null? this a NullPointerException in MetaDataPropertyManager line 112</technical_language>

Target:
public CSVMetaDataBuilder addField(String fieldName, DataType type, List<MetaDataFieldProperty> fieldProperties) { Objects.requireNonNull(fieldProperties, "fieldProperties must not be null"); fields.add(new DefaultMetaDataField(fieldName, new DefaultSimpleMetaDataModel(type), MetaDataField.FieldAccessType.READ, fieldProperties)); return this; }
Source:
<code>public ListenableFuture<?> removeRemoteSource(TaskId remoteSourceTaskId) { URI remoteSourceUri = uriBuilderFrom(taskLocation) .appendPath("remote-source") .appendPath(remoteSourceTaskId.toString()) .build(); Request request = prepareDelete() .setUri(remoteSourceUri) .build(); <START> RequestErrorTracker errorTracker = new RequestErrorTracker( <END> taskId, remoteSourceUri, maxErrorDuration, errorScheduledExecutor, "Remove exchange remote source"); SettableFuture<?> future = SettableFuture.create(); removeRemoteSourceHelper(errorTracker, request, future); return future; }</code><technical_language>Do need create tracker create this tracker in removeRemoteSourceHelper usage is pass this variable inside</technical_language>

Target:
public ListenableFuture<?> removeRemoteSource(TaskId remoteSourceTaskId) { URI remoteSourceUri = uriBuilderFrom(taskLocation) .appendPath("remote-source") .appendPath(remoteSourceTaskId.toString()) .build(); Request request = prepareDelete() .setUri(remoteSourceUri) .build(); RequestErrorTracker errorTracker = new RequestErrorTracker( taskId, remoteSourceUri, maxErrorDuration, errorScheduledExecutor, "Remove exchange remote source"); SettableFuture<?> future = SettableFuture.create(); doRemoveRemoteSource(errorTracker, request, future); return future; }
Source:
<code>private static boolean isThriftSupported(VersionNumber cassandraVersion) { <START> return cassandraVersion.compareTo(VersionNumber.parse("4.0-a")) < 0; <END> }</code><technical_language>nextStable() for that: return cassandraVersion.nextStable().compareTo(VersionNumber.parse("4.0")) < 0;</technical_language>

Target:
private static boolean isThriftSupported(VersionNumber cassandraVersion) { return cassandraVersion.nextStable().compareTo(VersionNumber.parse("4.0")) < 0; }
Source:
<code>private void createStudentProfile(String email, String pictureKey) { String shortName = "John"; String institute = "InstituteForJohnDoe"; String nationality = "Singaporean"; String gender = Const.GenderTypes.MALE; String moreInfo = "Information for John Doe."; if (pictureKey == null || pictureKey.isEmpty()) { this.pictureUrl = Const.SystemParams.DEFAULT_PROFILE_PICTURE_PATH; } else { this.pictureUrl = Const.ActionURIs.STUDENT_PROFILE_PICTURE + "?" + Const.ParamsNames.BLOB_KEY + "=" + pictureKey + "&" <START> + Const.ParamsNames.USER_ID + "=" + GOOGLE_ID; <END> } inputStudentProfile = StudentProfileAttributes.builder(GOOGLE_ID) .withShortName(shortName) .withEmail(email) .withInstitute(institute) .withNationality(nationality) .withGender(gender) .withMoreInfo(moreInfo) .withPictureKey(pictureKey) .build(); }</code><technical_language>I misunderstand meaning of USER_ID parameter added GOOGLE_ID wrongly in this file. is Google ID of person requesting page (instructor in this case). interpret Google ID of student</technical_language>

Target:
private void createStudentProfile(String email, String pictureKey) { String googleId = "valid.googleId"; String shortName = "John"; String institute = "InstituteForJohnDoe"; String nationality = "Singaporean"; String gender = Const.GenderTypes.MALE; String moreInfo = "Information for John Doe."; if (pictureKey == null || pictureKey.isEmpty()) { this.pictureUrl = Const.SystemParams.DEFAULT_PROFILE_PICTURE_PATH; } else { this.pictureUrl = Const.ActionURIs.STUDENT_PROFILE_PICTURE + "?" + Const.ParamsNames.BLOB_KEY + "=" + pictureKey + "&" + Const.ParamsNames.USER_ID + "=null"; } inputStudentProfile = StudentProfileAttributes.builder(googleId) .withShortName(shortName) .withEmail(email) .withInstitute(institute) .withNationality(nationality) .withGender(gender) .withMoreInfo(moreInfo) .withPictureKey(pictureKey) .build(); }
Source:
<code>EsSettings(Props props) { this.props = props; String configuredClusterName = props.nonNullValue(ProcessProperties.CLUSTER_NAME); <START> if (isBlank(configuredClusterName)) { <END> this.clusterName = STANDALONE_CLUSTER_NAME; } else { this.clusterName = configuredClusterName; } this.clusterEnabled = props.valueAsBoolean(ProcessProperties.CLUSTER_ENABLED); if (this.clusterEnabled) { this.nodeName = props.value(CLUSTER_SEARCH_NODE_NAME, "sonarqube-" + UUID.randomUUID().toString()); } else { this.nodeName = STANDALONE_NODE_NAME; } }</code><technical_language>condition dropped</technical_language>

Target:
EsSettings(Props props) { this.props = props; this.clusterName = props.nonNullValue(ProcessProperties.CLUSTER_NAME); this.clusterEnabled = props.valueAsBoolean(ProcessProperties.CLUSTER_ENABLED); if (this.clusterEnabled) { this.nodeName = props.value(CLUSTER_SEARCH_NODE_NAME, "sonarqube-" + UUID.randomUUID().toString()); } else { this.nodeName = STANDALONE_NODE_NAME; } }
Source:
<code>public void addConnectionEventListener(ConnectionEventListener listener) { <START> log.debug("addConnectionEventListener()"); <END> if (listener == null) { throw new IllegalArgumentException("Listener is null"); } listeners.add(listener); }</code><technical_language>remove useless debugging messsages</technical_language>

Target:
public void addConnectionEventListener(ConnectionEventListener listener) { if (listener == null) { throw new IllegalArgumentException("Listener is null"); } listeners.add(listener); }
Source:
<code>protected void createCopyFromExeGroup(Composite parent, int colSpan) { Composite mainComp = new Composite(parent, SWT.NONE); GridLayout mainLayout = new GridLayout(); mainLayout.numColumns = 1; mainLayout.marginHeight = 0; mainLayout.marginWidth = 0; mainComp.setLayout(mainLayout); GridData gd = new GridData(GridData.FILL_HORIZONTAL); gd.horizontalSpan = colSpan; mainComp.setLayoutData(gd); <START> enableCopyFromExeButton = createCheckButton(mainComp, "Copy C/C++ executable from:"); END> copyFromExeSelector = new ResourceSelectorWidget(mainComp, ResourceSelectorWidget.ResourceType.FILE, 2, "C/C++ executable origin", null); toLabel = new Label(mainComp, SWT.NONE); toLabel.setText("To:"); copyFromExeSelector.setEnabled(false); enableCopyFromExeButton.setSelection(false); toLabel.setEnabled(false); enableCopyFromExeButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { boolean copyEnabled = enableCopyFromExeButton.getSelection(); setEnableCopyFromSection(copyEnabled); updateLaunchConfigurationDialog(); } }); copyFromExeText = copyFromExeSelector.getURIText(); copyFromExeText.addModifyListener(new ModifyListener() { @Override public void modifyText(ModifyEvent evt) { updateLaunchConfigurationDialog(); } }); }</code><technical_language>This externalized marked translatable</technical_language>

Target:
protected void createCopyFromExeGroup(Composite parent, int colSpan) { Composite mainComp = new Composite(parent, SWT.NONE); GridLayout mainLayout = new GridLayout(); mainLayout.numColumns = 1; mainLayout.marginHeight = 0; mainLayout.marginWidth = 0; mainComp.setLayout(mainLayout); GridData gd = new GridData(GridData.FILL_HORIZONTAL); gd.horizontalSpan = colSpan; mainComp.setLayoutData(gd); enableCopyFromExeButton = createCheckButton(mainComp, ProxyLaunchMessages.copy_cpp_executable); copyFromExeSelector = new ResourceSelectorWidget(mainComp, ResourceSelectorWidget.ResourceType.FILE, 2, ProxyLaunchMessages.executable_origin, null); toLabel = new Label(mainComp, SWT.NONE); toLabel.setText(ProxyLaunchMessages.to); copyFromExeSelector.setEnabled(false); enableCopyFromExeButton.setSelection(false); toLabel.setEnabled(false); enableCopyFromExeButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { boolean copyEnabled = enableCopyFromExeButton.getSelection(); setEnableCopyFromSection(copyEnabled); updateLaunchConfigurationDialog(); } }); copyFromExeText = copyFromExeSelector.getURIText(); copyFromExeText.addModifyListener(new ModifyListener() { @Override public void modifyText(ModifyEvent evt) { updateLaunchConfigurationDialog(); } }); }
Source:
<code>public static Double stSphericalArea(@SqlType(SPHERICAL_GEOGRAPHY_TYPE_NAME) Slice input) { OGCGeometry geometry = deserialize(input); if (geometry.isEmpty()) { return null; } <START> validateSphericalType("ST_Area", geometry, EnumSet.of(POLYGON)); <END> Polygon polygon = (Polygon) geometry.getEsriGeometry(); return sphericalPolygonArea(polygon); }</code><technical_language>add support for multi-polygons well</technical_language>

Target:
public static Double stSphericalArea(@SqlType(SPHERICAL_GEOGRAPHY_TYPE_NAME) Slice input) { OGCGeometry geometry = deserialize(input); if (geometry.isEmpty()) { return null; } validateSphericalType("ST_Area", geometry, EnumSet.of(POLYGON, MULTI_POLYGON)); Polygon polygon = (Polygon) geometry.getEsriGeometry(); double sphericalExcess = 0.0; int numPaths = polygon.getPathCount(); for (int i = 0; i < numPaths; i++) { double sign = polygon.isExteriorRing(i) ? 1.0 : -1.0; sphericalExcess += sign * Math.abs(computeSphericalExcess(polygon, polygon.getPathStart(i), polygon.getPathEnd(i))); } return Math.abs(sphericalExcess * EARTH_RADIUS_M * EARTH_RADIUS_M); }
Source:
<code>public void should_return_translation_for_the_given_local() throws Exception { Map<String, String> parameters = new HashMap<>(); parameters.put("key1", "<strong>message 1</strong>"); parameters.put("key2", "autre méssage"); parameters.put("key3", "~%^*µ"); when(i18n.getLocale(AbstractI18n.LOCALE.fr)).thenReturn(parameters); Response response = request("/system/i18ntranslationv2?f=locale%3Dfr").get(); assertThat(response).hasStatus(Status.SUCCESS_OK); assertJsonEquals("[" + "{\"key\": \"key1\", \"value\": \"<strong>message 1</strong>\"}," + "{\"key\": \"key2\", \"value\": \"autre méssage\"}," + "{\"key\": \"key3\", \"value\": \"~%^*µ\"}" + "]", response.getEntityAsText(), <START> JsonAssert.when(Option.IGNORING_ARRAY_ORDER)); <END> }</code><technical_language>+1: Nice</technical_language>

Target:
public void should_return_translation_for_the_given_local() throws Exception { Map<String, String> parameters = new HashMap<>(); parameters.put("key1", "<strong>message 1</strong>"); parameters.put("key2", "autre méssage"); parameters.put("key3", "~%^*µ"); when(i18n.getLocale(AbstractI18n.LOCALE.fr)).thenReturn(parameters); Response response = request("/system/i18ntranslation?f=locale%3Dfr").get(); assertThat(response).hasStatus(Status.SUCCESS_OK); assertJsonEquals("[" + "{\"key\": \"key1\", \"value\": \"<strong>message 1</strong>\"}," + "{\"key\": \"key2\", \"value\": \"autre méssage\"}," + "{\"key\": \"key3\", \"value\": \"~%^*µ\"}" + "]", response.getEntityAsText(), JsonAssert.when(Option.IGNORING_ARRAY_ORDER)); }
Source:
<code><START> protected void processConfigurationReport(SerialMessage serialMessage, int offset) { <END> int parameter = serialMessage.getMessagePayloadByte(offset + 1); int size = serialMessage.getMessagePayloadByte(offset + 2); int value = 0; for (int i = 0; i < size; ++i) { value <<= 8; value |= serialMessage.getMessagePayloadByte(offset + 3 + i); } logger.debug(String.format("Node configuration report from nodeId = %d, parammeter = %d, value = 0x%02X", this .getNode().getNodeId(), parameter, value)); ZWaveConfigurationParameterEvent zEvent = new ZWaveConfigurationParameterEvent(this.getNode().getNodeId(), parameter, value, size); this.getController().notifyEventListeners(zEvent); }</code><technical_language>pretty complements negative values give incorrect results here. a extractvalue in CommandClass handle negative values</technical_language>

Target:
protected void processConfigurationReport(SerialMessage serialMessage, int offset) { int parameter = serialMessage.getMessagePayloadByte(offset + 1); int size = serialMessage.getMessagePayloadByte(offset + 2); int value = extractValue(serialMessage.getMessagePayload(), offset + 3, size); logger.debug(String.format("Node configuration report from nodeId = %d, parameter = %d, value = 0x%02X", this .getNode().getNodeId(), parameter, value)); ConfigurationParameter configurationParameter = new ConfigurationParameter(parameter, value, size); this.configParameters.put(parameter, configurationParameter); ZWaveConfigurationParameterEvent zEvent = new ZWaveConfigurationParameterEvent(this.getNode().getNodeId(), configurationParameter); this.getController().notifyEventListeners(zEvent); }
Source:
<code>public void testLocaleConsistency() { for (String culture: RoviCulture.cultures()) { Locale locale = RoviCulture.localeFromCulture(culture); assertEquals(culture, RoviCulture.cultureFromLocale(locale)); <START> } <END> }</code><technical_language>need assertion something's tested, assertion is in a for loop right</technical_language>

Target:
public void testLocaleConsistency() { assertFalse(RoviCulture.cultures().isEmpty()); for (String culture: RoviCulture.cultures()) { Locale locale = RoviCulture.localeFromCulture(culture); assertEquals(culture, RoviCulture.cultureFromLocale(locale)); } }
Source:
<code>protected final <T> ConstraintValidator<A, ?> getInitializedConstraintValidator(ValidationContext<T> validationContext, ValueContext<?, ?> valueContext) { ConstraintValidator<A, ?> validator; if ( validationContext.getConstraintValidatorFactory() == validationContext.getConstraintValidatorManager().getDefaultConstraintValidatorFactory() ) { validator = constraintValidatorForDefaultConstraintValidatorFactory; if ( validator == null ) { synchronized ( this ) { validator = constraintValidatorForDefaultConstraintValidatorFactory; if ( validator == null ) { validator = getInitializedConstraintValidator( validationContext ); if ( !( validator instanceof HibernateConstraintValidator ) ) { constraintValidatorForDefaultConstraintValidatorFactory = validator; <START> } <END> } } } } else { validator = getInitializedConstraintValidator( validationContext ); } if ( validator == DUMMY_CONSTRAINT_VALIDATOR ) { throw getExceptionForNullValidator( validatedValueType, valueContext.getPropertyPath().asString() ); } return validator; }</code><technical_language>This I like. fact is in end I HibernateConstraintValidator initialize() contract moved ConstraintValidator defeat purpose of this optimization. I include initialization context right in caching mechanisms. give a try</technical_language>

Target:
protected final <T> ConstraintValidator<A, ?> getInitializedConstraintValidator(ValidationContext<T> validationContext, ValueContext<?, ?> valueContext) { ConstraintValidator<A, ?> validator; if ( validationContext.getConstraintValidatorFactory() == validationContext.getConstraintValidatorManager().getDefaultConstraintValidatorFactory() && validationContext.getConstraintValidatorInitializationContext() == validationContext.getConstraintValidatorManager() .getDefaultConstraintValidatorInitializationContext() ) { validator = constraintValidatorForDefaultConstraintValidatorFactoryAndInitializationContext; if ( validator == null ) { synchronized ( this ) { validator = constraintValidatorForDefaultConstraintValidatorFactoryAndInitializationContext; if ( validator == null ) { validator = getInitializedConstraintValidator( validationContext ); constraintValidatorForDefaultConstraintValidatorFactoryAndInitializationContext = validator; } } } } else { validator = getInitializedConstraintValidator( validationContext ); } if ( validator == DUMMY_CONSTRAINT_VALIDATOR ) { throw getExceptionForNullValidator( validatedValueType, valueContext.getPropertyPath().asString() ); } return validator; }
Source:
<code>public void stop(BundleContext context) throws Exception { ArchiveCommand.unregisterFormat("zip"); <START> ArchiveCommand.unregisterFormat("txz"); <END> ArchiveCommand.unregisterFormat("tgz"); ArchiveCommand.unregisterFormat("tar"); }</code><technical_language>a small helper method setup registrations: private static final List<String> myFormats = Collections.synchronizedList(new ArrayList<String>()); private static final void register(String name, Format<?> fmt) { myFormats.add(name); ArchiveCommand.registerFormat(name, fmt); } public void stop(BundleContext context) throws Exception { for (String name : myFormats) { ArchiveCommand.unregisterFormat(name); } myFormats.clear(); }</technical_language>

Target:
public void stop(BundleContext context) throws Exception { stop(); }
Source:
<code>public void onUpdated(Iterable<CacheEntryEvent<? extends K, ? extends V>> events) throws CacheEntryListenerException { <START> for (Object event1 : events) { <END> CacheEntryEvent event = (CacheEntryEvent) event1; Assert.assertEquals(EventType.UPDATED, event.getEventType()); this.updated.incrementAndGet(); event.getKey(); if (event.isOldValueAvailable()) { event.getOldValue(); } } }</code><technical_language>cast</technical_language>

Target:
public void onUpdated(Iterable<CacheEntryEvent<? extends K, ? extends V>> events) throws CacheEntryListenerException { for (CacheEntryEvent<? extends K, ? extends V> event : events) { Assert.assertEquals(EventType.UPDATED, event.getEventType()); this.updated.incrementAndGet(); if (event.isOldValueAvailable()) { event.getOldValue(); } } }
Source:
<code>@Override public T convert(ResponseBody value) throws IOException { BufferedSource source = value.source(); try { if (source.rangeEquals(0, UTF8_BOM)) { source.skip(UTF8_BOM.size()); } JsonReader reader = JsonReader.of(source); T result = adapter.fromJson(reader); if (requireFullConsumption && reader.peek() == JsonReader.Token.END_DOCUMENT) { <START> throw new RuntimeException("JSON document was not fully consumed."); <END> } return result; } finally { value.close(); } }</code><technical_language>Hmm this a JsonDataException</technical_language>

Target:
@Override public T convert(ResponseBody value) throws IOException { BufferedSource source = value.source(); try { if (source.rangeEquals(0, UTF8_BOM)) { source.skip(UTF8_BOM.size()); } JsonReader reader = JsonReader.of(source); T result = adapter.fromJson(reader); if (reader.peek() != JsonReader.Token.END_DOCUMENT) { throw new JsonDataException("JSON document was not fully consumed."); } return result; } finally { value.close(); } }