auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public static void main(String[] args) { LoadBalancerExtension extension = null; try { File configFile = new File(getFilePathOfConfigFile(Constants.CONFIG_FILE_NAME)); OMElement documentElement = AxiomXpathParserUtil.parse(configFile); GCEConfigParser.parse(documentElement); <START> PropertyConfigurator.configure(getFilePathOfConfigFile(GCEContext.getInstance().getLog4jPropertiesFileName())); <END> if (log.isInfoEnabled()) { log.info("GCE extension started"); } final Thread mainThread = Thread.currentThread(); final LoadBalancerExtension finalExtension = extension; Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { try { if (finalExtension != null) { log.info("GCE instance is stopping..."); finalExtension.stop(); } mainThread.join(); } catch (Exception e) { log.error(e); } } }); executorService = StratosThreadPool.getExecutorService("gce.extension.thread.pool", 10); TopologyProvider topologyProvider = new TopologyProvider(); GCEStatisticsReader statisticsReader = GCEContext.getInstance().isCEPStatsPublisherEnabled() ? new GCEStatisticsReader(topologyProvider) : null; extension = new LoadBalancerExtension(new GCELoadBalancer(), statisticsReader, topologyProvider); extension.setExecutorService(executorService); extension.execute(); } catch (Exception e) { if (log.isErrorEnabled()) { log.error(e); } if (extension != null) { log.info("Shutting GCE instance..."); extension.stop(); } } }</code><technical_language>Log4j configured a system property. need programatically configure</technical_language>

Target:
public static void main(String[] args) { LoadBalancerExtension extension = null; try { File configFile = new File(getFilePathOfConfigFile(Constants.CONFIG_FILE_NAME)); OMElement documentElement = AxiomXpathParserUtil.parse(configFile); GCEConfigParser.parse(documentElement); PropertyConfigurator.configure(System.getProperty("log4j.properties.file.path")); if (log.isInfoEnabled()) { log.info("GCE extension started"); } final Thread mainThread = Thread.currentThread(); final LoadBalancerExtension finalExtension = extension; Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { try { if (finalExtension != null) { log.info("GCE instance is stopping..."); finalExtension.stop(); } mainThread.join(); } catch (Exception e) { log.error(e); } } }); executorService = StratosThreadPool.getExecutorService("gce.extension.thread.pool", 10); TopologyProvider topologyProvider = new TopologyProvider(); GCEStatisticsReader statisticsReader = GCEContext.getInstance().isCEPStatsPublisherEnabled() ? new GCEStatisticsReader(topologyProvider) : null; extension = new LoadBalancerExtension(new GCELoadBalancer(), statisticsReader, topologyProvider); extension.setExecutorService(executorService); extension.execute(); } catch (Exception e) { if (log.isErrorEnabled()) { log.error(e); } if (extension != null) { log.info("Shutting GCE instance..."); extension.stop(); } } }
Source:
<code>private static ConcurrentMap<String, String> asMap( final Iterable<String> args) throws IllegalStateException { <START> final ConcurrentMap<String, String> map = <END> new ConcurrentHashMap<String, String>(0); final Pattern ptn = Pattern.compile("--([a-z\\-]+)(=.+)?"); for (final String arg : args) { final Matcher matcher = ptn.matcher(arg); if (!matcher.matches()) { throw new IllegalStateException( String.format("can't parse this argument: '%s'", arg) ); } final String value = matcher.group(2); if (value == null) { map.put(matcher.group(1), ""); } else { map.put(matcher.group(1), value.substring(1)); } } return map; }</code><technical_language>@essobedo field type relaxed simple Map ConcurrentMap specific operations</technical_language>

Target:
private static Map<String, String> asMap(final Iterable<String> args) { final Map<String, String> map = new HashMap<String, String>(0); final Pattern ptn = Pattern.compile("--([a-z\\-]+)(=.+)?"); for (final String arg : args) { final Matcher matcher = ptn.matcher(arg); if (!matcher.matches()) { throw new IllegalStateException( String.format("can't parse this argument: '%s'", arg) ); } final String value = matcher.group(2); if (value == null) { map.put(matcher.group(1), ""); } else { map.put(matcher.group(1), value.substring(1)); } } return map; }
Source:
<code>public void setMessage(String message) { <START> messageLabel.getElement().setInnerHTML(message != null ? message.replace("\n", "<br/>") : ""); END> }</code><technical_language>I suspect this bring in XSS vulnerability. If for example VM name delete contains some HTML (or JS), try e.g. delete it, this dialog interpret this HTML (JS). Please SafeHtmlUtils.fromString(message).asString().replace("\n", "<br/>") this</technical_language>

Target:
public void setMessage(String message) { messageHTML.setHTML(SafeHtmlUtils.fromString(message != null ? message : "").asString().replace("\n", "<br>")); }
Source:
<code>protected SimpleDictionaryDialog(@Nullable SimpleDictionary dictionary, MutableReferenceDataCatalog catalog, WindowContext windowContext) { super(windowContext, ImageManager.get().getImage(IconUtils.DICTIONARY_SIMPLE_IMAGEPATH)); _originalDictionary = dictionary; _catalog = catalog; _nameTextField = WidgetFactory.createTextField("Dictionary name"); _valuesTextArea = WidgetFactory.createTextArea("Values"); _valuesTextArea.setRows(14); _caseSensitiveCheckBox = new DCCheckBox<>("Case-sensitive?", false); _caseSensitiveCheckBox.setForeground(WidgetUtils.BG_COLOR_BRIGHTEST); _caseSensitiveCheckBox.setOpaque(false); _caseSensitiveCheckBox.setToolTipText("Only match on dictionary terms when text-case is the same."); if (dictionary != null) { _nameTextField.setText(dictionary.getName()); <START> Collection<String> values = dictionary.getValueSet(); <END> StringBuilder sb = new StringBuilder(); boolean first = true; for (String value : values) { if (first) { first = false; } else { sb.append('\n'); } sb.append(value); } _valuesTextArea.setText(sb.toString()); _caseSensitiveCheckBox.setSelected(dictionary.isCaseSensitive()); } }</code><technical_language>final</technical_language>

Target:
protected SimpleDictionaryDialog(@Nullable SimpleDictionary dictionary, MutableReferenceDataCatalog catalog, WindowContext windowContext) { super(windowContext, ImageManager.get().getImage(IconUtils.DICTIONARY_SIMPLE_IMAGEPATH)); _originalDictionary = dictionary; _catalog = catalog; _nameTextField = WidgetFactory.createTextField("Dictionary name"); _valuesTextArea = WidgetFactory.createTextArea("Values"); _valuesTextArea.setRows(14); _caseSensitiveCheckBox = new DCCheckBox<>("Case-sensitive?", false); _caseSensitiveCheckBox.setForeground(WidgetUtils.BG_COLOR_BRIGHTEST); _caseSensitiveCheckBox.setOpaque(false); _caseSensitiveCheckBox.setToolTipText("Only match on dictionary terms when text-case is the same."); if (dictionary != null) { _nameTextField.setText(dictionary.getName()); final Collection<String> values = dictionary.getValueSet(); final StringBuilder sb = new StringBuilder(); boolean first = true; for (String value : values) { if (first) { first = false; } else { sb.append('\n'); } sb.append(value); } _valuesTextArea.setText(sb.toString()); _caseSensitiveCheckBox.setSelected(dictionary.isCaseSensitive()); } }
Source:
<code>protected Pool initSourceObject() { Pool source = new Pool(); source.setId("pool-id"); source.setQuantity(1L); source.setStartDate(new Date()); source.setEndDate(new Date()); Map<String, String> attributes = new HashMap<>(); attributes.put(Pool.Attributes.SOURCE_POOL_ID, "true"); source.setAttributes(attributes); source.setRestrictedToUsername("restricted-to-username-value"); source.setConsumed(6L); source.setAttribute(Pool.Attributes.DEVELOPMENT_POOL, "true"); Product product = new Product(); product.setId("product-id-2"); product.setName("product-name-2"); source.setProduct(product); Product derivedProduct = new Product(); derivedProduct.setId("derived-product-id-2"); derivedProduct.setName("derived-product-name-2"); derivedProduct.setAttributes(new HashMap<>()); derivedProduct.setAttribute(Product.Attributes.ARCHITECTURE, "POWER"); derivedProduct.setAttribute(Product.Attributes.STACKING_ID, "2221"); source.setDerivedProduct(derivedProduct); Product providedProd = new Product(); providedProd.setId("provided-product-id-1"); providedProd.setName("provided-product-name-1"); <START> source.getProduct().addProvidedProduct(providedProd); <END> Product derivedProvidedProd = new Product(); derivedProvidedProd.setId("derived-provided-product-id-1"); derivedProvidedProd.setName("derived-provided-product-name-1"); source.getDerivedProduct().addProvidedProduct(derivedProvidedProd); return source; }</code><technical_language>Move this block add product instead of indirectly pool</technical_language>

Target:
protected Pool initSourceObject() { Pool source = new Pool(); source.setId("pool-id"); source.setQuantity(1L); source.setStartDate(new Date()); source.setEndDate(new Date()); Map<String, String> attributes = new HashMap<>(); attributes.put(Pool.Attributes.SOURCE_POOL_ID, "true"); source.setAttributes(attributes); source.setRestrictedToUsername("restricted-to-username-value"); source.setConsumed(6L); source.setAttribute(Pool.Attributes.DEVELOPMENT_POOL, "true"); Product providedProd = new Product(); providedProd.setId("provided-product-id-1"); providedProd.setName("provided-product-name-1"); Product product = new Product(); product.setId("product-id-2"); product.setName("product-name-2"); product.addProvidedProduct(providedProd); source.setProduct(product); Product derivedProvidedProd = new Product(); derivedProvidedProd.setId("derived-provided-product-id-1"); derivedProvidedProd.setName("derived-provided-product-name-1"); Product derivedProduct = new Product(); derivedProduct.setId("derived-product-id-2"); derivedProduct.setName("derived-product-name-2"); derivedProduct.setAttributes(new HashMap<>()); derivedProduct.setAttribute(Product.Attributes.ARCHITECTURE, "POWER"); derivedProduct.setAttribute(Product.Attributes.STACKING_ID, "2221"); derivedProduct.addProvidedProduct(derivedProvidedProd); source.setDerivedProduct(derivedProduct); return source; }
Source:
<code>public Future<Void> login(final String user, final String password) { return (Future<Void>) executor.submit(new Runnable() { <START> @Override <END> public void run() { try { receiveTokenFromKeycloak("client_id=" + appName + "&username=" + user + "&password=" + password + "&grant_type=password"); } catch (IOException e) { throw new DolphinRuntimeException("Error in security", e); } } }); }</code><technical_language>lamda here</technical_language>

Target:
public Future<Void> login(final String user, final String password) { return (Future<Void>) executor.submit(() -> { try { receiveTokenFromKeycloak("client_id=" + appName + "&username=" + user + "&password=" + password + "&grant_type=password"); } catch (IOException e) { throw new DolphinRuntimeException("Error in security", e); } }); }
Source:
<code>public List<Encounter> getTransferHistory(Patient patient) { EncounterService encounterService = Context.getEncounterService(); Collection<EncounterType> encounterTypes = new ArrayList<>(); List<Encounter> encounters = new ArrayList<>(); encounterTypes.add(encounterService.getEncounterTypeByUuid(TRANSFER_IN.uuid())); encounterTypes.add(encounterService.getEncounterTypeByUuid(TRANSFER_OUT.uuid())); EncounterSearchCriteria encounterSearchCriteria = new EncounterSearchCriteriaBuilder().setPatient(patient).setIncludeVoided(false).setEncounterTypes(encounterTypes).createEncounterSearchCriteria(); <START> if (!encounterTypes.isEmpty()) { <END> encounters = encounterService.getEncounters(encounterSearchCriteria); } return encounters; }</code><technical_language>@slubwama This check is needed initialize encounterTypes</technical_language>

Target:
public List<Encounter> getTransferHistory(Patient patient) { EncounterService encounterService = Context.getEncounterService(); Collection<EncounterType> encounterTypes = new ArrayList<>(); encounterTypes.add(encounterService.getEncounterTypeByUuid(TRANSFER_IN.uuid())); encounterTypes.add(encounterService.getEncounterTypeByUuid(TRANSFER_OUT.uuid())); EncounterSearchCriteria encounterSearchCriteria = new EncounterSearchCriteriaBuilder().setPatient(patient).setIncludeVoided(false).setEncounterTypes(encounterTypes).createEncounterSearchCriteria(); List<Encounter> encounters = encounterService.getEncounters(encounterSearchCriteria); return encounters; }
Source:
<code>public Object parseDefaultString(FieldType fieldType, String defaultStr) throws SQLException { try { <START> return Timestamp.valueOf(LocalDateTime.parse(defaultStr, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss[.SSS]"))); <END> } catch (NumberFormatException e) { throw SqlExceptionUtil.create("Problems with field " + fieldType + " parsing default LocalDateTime value: " + defaultStr, e); } }</code><technical_language>This caused problems in tests for me. A approach (and ultimately more user friendly) variable length fractions. example of this is here: <LINK_0>, adjustments tests consistently truncated (H2 supports milliseconds tests comparing microseconds machine)</technical_language>

Target:
public Object parseDefaultString(FieldType fieldType, String defaultStr) throws SQLException { return Timestamp.valueOf((LocalDateTime) super.parseDefaultString(fieldType, defaultStr)); }
Source:
<code>public boolean[] encode(String contents) { int length = contents.length(); if (length > 80) { throw new IllegalArgumentException( "Requested contents should be less than 80 digits long, but got " + length); } for (int i = 0; i < length; i++) { int indexInString = Code39Reader.ALPHABET_STRING.indexOf(contents.charAt(i)); if (indexInString < 0) { contents = tryToConvertToExtendedMode(contents); length = contents.length(); if (length > 80) { throw new IllegalArgumentException( <START> "Requested contents should be less than 80 digits long, but got " + length + " (extended full ascii mode)"); <END> } break; } } int[] widths = new int[9]; int codeWidth = 24 + 1 + length; for (int i = 0; i < length; i++) { int indexInString = Code39Reader.ALPHABET_STRING.indexOf(contents.charAt(i)); toIntArray(Code39Reader.CHARACTER_ENCODINGS[indexInString], widths); for (int width : widths) { codeWidth += width; } } boolean[] result = new boolean[codeWidth]; toIntArray(Code39Reader.ASTERISK_ENCODING, widths); int pos = appendPattern(result, 0, widths, true); int[] narrowWhite = {1}; pos += appendPattern(result, pos, narrowWhite, false); for (int i = 0; i < length; i++) { int indexInString = Code39Reader.ALPHABET_STRING.indexOf(contents.charAt(i)); toIntArray(Code39Reader.CHARACTER_ENCODINGS[indexInString], widths); pos += appendPattern(result, pos, widths, true); pos += appendPattern(result, pos, narrowWhite, false); } toIntArray(Code39Reader.ASTERISK_ENCODING, widths); appendPattern(result, pos, widths, true); return result; }</code><technical_language>some nits here. ascii -> ASCII</technical_language>

Target:
public boolean[] encode(String contents) { int length = contents.length(); if (length > 80) { throw new IllegalArgumentException( "Requested contents should be less than 80 digits long, but got " + length); } for (int i = 0; i < length; i++) { int indexInString = Code39Reader.ALPHABET_STRING.indexOf(contents.charAt(i)); if (indexInString < 0) { contents = tryToConvertToExtendedMode(contents); length = contents.length(); if (length > 80) { throw new IllegalArgumentException( "Requested contents should be less than 80 digits long, but got " + length + " (extended full ASCII mode)"); } break; } } int[] widths = new int[9]; int codeWidth = 24 + 1 + length; for (int i = 0; i < length; i++) { int indexInString = Code39Reader.ALPHABET_STRING.indexOf(contents.charAt(i)); toIntArray(Code39Reader.CHARACTER_ENCODINGS[indexInString], widths); for (int width : widths) { codeWidth += width; } } boolean[] result = new boolean[codeWidth]; toIntArray(Code39Reader.ASTERISK_ENCODING, widths); int pos = appendPattern(result, 0, widths, true); int[] narrowWhite = {1}; pos += appendPattern(result, pos, narrowWhite, false); for (int i = 0; i < length; i++) { int indexInString = Code39Reader.ALPHABET_STRING.indexOf(contents.charAt(i)); toIntArray(Code39Reader.CHARACTER_ENCODINGS[indexInString], widths); pos += appendPattern(result, pos, widths, true); pos += appendPattern(result, pos, narrowWhite, false); } toIntArray(Code39Reader.ASTERISK_ENCODING, widths); appendPattern(result, pos, widths, true); return result; }
Source:
<code>private boolean executeSshReboot(String version) { try ( final EngineSSHClient sshClient = new EngineSSHClient(); final ByteArrayOutputStream cmdOut = new ByteArrayOutputStream(); final ByteArrayOutputStream cmdErr = new ByteArrayOutputStream() ) { try { log.info("Opening SSH reboot session on host {}", getVds().getHostName()); sshClient.setVds(getVds()); sshClient.useDefaultKeyPair(); sshClient.connect(); sshClient.authenticate(); log.info("Executing SSH reboot command on host {}", getVds().getHostName()); sshClient.executeCommand( Config.<String> getValue(ConfigValues.SshHostRebootCommand, version), null, cmdOut, cmdErr ); return true; } catch (Exception ex) { log.error("SSH reboot command failed on host '{}': {}\nStdout: {}\nStderr: {}", getVds().getHostName(), ex.getMessage(), cmdOut, cmdErr); log.debug("Exception", ex); } } catch(IOException e) { <START> log.error("IOException"); <END> log.debug("Exception", e); } return false; }</code><technical_language>Please change to: log.error("Error opening SSH connection '{}': {}", getVds().getHostName(), e.getMessage()); log.debug("Exception", ex);</technical_language>

Target:
private boolean executeSshReboot(String version) { try ( final EngineSSHClient sshClient = new EngineSSHClient(); final ByteArrayOutputStream cmdOut = new ByteArrayOutputStream(); final ByteArrayOutputStream cmdErr = new ByteArrayOutputStream() ) { try { log.info("Opening SSH reboot session on host {}", getVds().getHostName()); sshClient.setVds(getVds()); sshClient.useDefaultKeyPair(); sshClient.connect(); sshClient.authenticate(); log.info("Executing SSH reboot command on host {}", getVds().getHostName()); sshClient.executeCommand( Config.<String> getValue(ConfigValues.SshHostRebootCommand, version), null, cmdOut, cmdErr ); return true; } catch (Exception ex) { log.error("SSH reboot command failed on host '{}': {}\nStdout: {}\nStderr: {}", getVds().getHostName(), ex.getMessage(), cmdOut, cmdErr); log.debug("Exception", ex); } } catch (IOException e) { log.error("Error opening SSH connection to '{}': {}", getVds().getHostName(), e.getMessage()); log.debug("Exception", e); } return false; }
Source:
<code>public void runScript(String scriptContent, Consumer<Exception> errorCallback) { <START> final String scriptContenti18n = "var tr = Packages.org.phoenicis.configuration.localisation.Localisation.tr;" <END> + scriptContent; nashornEngineFactory.createEngine().eval(scriptContenti18n, errorCallback); }</code><technical_language>I java NashornEngine engine = nashornEngineFactory.createEngine(); engine.eval("var tr = Packages.org.phoenicis.configuration.localisation.Localisation.tr;", errorCallback); engine.eval(scriptContent, errorCallback); a more clear implementation</technical_language>

Target:
public void runScript(String scriptContent, Consumer<Exception> errorCallback) { nashornEngineFactory.createEngine().eval(scriptContent, errorCallback); }
Source:
<code>public Set<Integer> getLinesWithNoSonar() { <START> return noSonar; <END> }</code><technical_language>@pynicolas other getters, this getter return a copy (ImmutableSet.copyOf)</technical_language>

Target:
public Set<Integer> getLinesWithNoSonar() { return ImmutableSet.copyOf(noSonar); }
Source:
<code>public RankingWidget(Context context, QuestionDetails prompt) { super(context, prompt); <START> getOrderedItems(); <END> setUpLayout(); }</code><technical_language>This is a new change a getter mutates is dangerous, I think. A rename buildOrderedItems help</technical_language>

Target:
public RankingWidget(Context context, QuestionDetails prompt) { super(context, prompt); setUpLayout(getOrderedItems()); }
Source:
<code>protected Sequence getServicesSequence(DsfSession session, ILaunch launch, IProgressMonitor rm) { if (launch instanceof GdbLaunch) { return new ServicesLaunchSequence(session, (GdbLaunch)launch, rm); } return null; <START> } <END></code><technical_language>is expected launch instance of GdbLaunch, I check is required</technical_language>

Target:
protected Sequence getServicesSequence(DsfSession session, ILaunch launch, IProgressMonitor rm) { return new ServicesLaunchSequence(session, (GdbLaunch)launch, rm); }
Source:
<code>protected void doInit() { oldNumaNodeIds = <START> LinqUtils.transformToList(getVmNumaNodesForValidation(), <END> new Function<VmNumaNode, Guid>() { @Override public Guid eval(VmNumaNode vmNumaNode) { return vmNumaNode.getId(); } }); setVmNumaNodesForValidation(getParameters().getVmNumaNodeList()); }</code><technical_language>checkout Entities.getIds(list).for alternative if like. I stay loyal jdk7 for ease of backporting (perfect for now)</technical_language>

Target:
protected void doInit() { oldNumaNodeIds = Entities.getIds(getVmNumaNodesForValidation()); setVmNumaNodesForValidation(getParameters().getVmNumaNodeList()); }
Source:
<code>public String getProductName(String languageCode) { <START> if (!languageCode.equals("en") && additionalProperties.get("product_name_" + languageCode) != null <END> && isNotBlank(additionalProperties.get("product_name_" + languageCode).toString())) { return additionalProperties.get("product_name_" + languageCode) .toString() .replace("\\'", "'") .replace("&quot", "'"); } else if (additionalProperties.get("product_name_en") != null && isNotBlank(additionalProperties.get("product_name_en").toString())) { return additionalProperties.get("product_name_en") .toString() .replace("\\'", "'") .replace("&quot", "'"); } else { return getProductName(); } }</code><technical_language>Lot's of duplicated code in if else if conditions, pull a helper method</technical_language>

Target:
public String getProductName(String languageCode) { String result = getFieldHelper("product_name", languageCode); if (result != null) { return result; } else { return getProductName(); } }
Source:
<code>public static JSONObject read(final String url) throws IOException, JSONException { final InputStream is = new URL(url).openStream(); try { final BufferedReader rd = new BufferedReader( <START> new InputStreamReader(is, Charset.forName("UTF-8"))); <END> final String jsonText = readAll(rd); final JSONObject json = new JSONObject(jsonText); return json; } finally { is.close(); } }</code><technical_language>try-with-resources</technical_language>

Target:
public static JSONObject read(final String url) throws IOException, JSONException { final InputStream is = new URL(url).openStream(); try { final BufferedReader rd = new BufferedReader( new InputStreamReader(is, Charset.forName("UTF-8"))); final String jsonText = readAll(rd); final JSONObject json = new JSONObject(jsonText); return json; } finally { try { is.close(); } catch (Throwable ex) { } } }
Source:
<code>public static Partition fromProto(alluxio.grpc.table.layout.hive.PartitionInfo info) { Partition.Builder builder = Partition.builder() .setColumns(info.getDataColsList().stream().map(AlluxioProtoUtils::fromProto).collect(Collectors.toList())) .setDatabaseName(info.getDbName()) .setParameters(info.getParametersMap()) .setValues(Lists.newArrayList(info.getValuesList())) .setTableName(info.getTableName()); builder.getStorageBuilder() .setSkewed(info.getStorage().getSkewed()) .setStorageFormat(fromProto(info.getStorage().getStorageFormat())) .setLocation(info.getStorage().getLocation()) <START> .setBucketProperty(info.getStorage().hasBucketProperty() ? fromProto(info.getStorage().getBucketProperty()) : Optional.empty()) <END> .setSerdeParameters(info.getStorage().getStorageFormat().getSerdelibParametersMap()); return builder.build(); }</code><technical_language>merge oneline</technical_language>

Target:
public static Partition fromProto(alluxio.grpc.table.layout.hive.PartitionInfo info) { Partition.Builder builder = Partition.builder() .setColumns(info.getDataColsList().stream().map(AlluxioProtoUtils::fromProto).collect(toImmutableList())) .setDatabaseName(info.getDbName()) .setParameters(info.getParametersMap()) .setValues(Lists.newArrayList(info.getValuesList())) .setTableName(info.getTableName()); builder.getStorageBuilder() .setSkewed(info.getStorage().getSkewed()) .setStorageFormat(fromProto(info.getStorage().getStorageFormat())) .setLocation(info.getStorage().getLocation()) .setBucketProperty(info.getStorage().hasBucketProperty() ? fromProto(info.getStorage().getBucketProperty()) : Optional.empty()) .setSerdeParameters(info.getStorage().getStorageFormat().getSerdelibParametersMap()); return builder.build(); }
Source:
<code>public Map<String, String> parseArguments(String[] args) throws Exception { Map<String, String> argMap = new HashMap<>(); if ((args.length < 2 && getName().equals(args[0])) || ACTION_HELP.equals(args[1])) { action = ACTION_HELP; return argMap; } action = args[1]; argMap.put(action, args[2]); ExtendedCliParser parser = initParser(action); argMap = parser.parse(args, 2, args.length); if(argMap.containsKey(ACTION_HELP)) { action = ACTION_HELP; } <START> return argMap; <END> }</code><technical_language>store this member, reason return</technical_language>

Target:
public void parseArguments(String[] args) throws Exception { if (args.length < 2 || ACTION_HELP.equals(args[1])) { action = ACTION_HELP; return; } action = args[1]; argMap.put(action, args[1]); ExtendedCliParser parser = initParser(action); argMap = parser.parse(args, 2, args.length); if(argMap.containsKey(ACTION_HELP)) { action = ACTION_HELP; } }
Source:
<code><START> default DataType[] getFormatFieldNames() { <END> return Arrays.stream(getSchema().getFieldNames()) .filter(name -> !getPartitionKeys().contains(name)) .map(name -> getSchema().getFieldDataType(name).get()) .toArray(DataType[]::new); }</code><technical_language>getFormatFieldTypes</technical_language>

Target:
default String[] getFormatFieldNames() { return Arrays.stream(getSchema().getFieldNames()) .filter(name -> !getPartitionKeys().contains(name)) .toArray(String[]::new); }
Source:
<code>private static void compose(StringBuilder builder, String key, String value) { final char DELIMITER = ','; <START> builder.append(key).append('=').append(value).append(DELIMITER); <END> }</code><technical_language>Imho , some style inconsistency. hand a final char for delimeter, other hand append hte literal '=' (no final char for it) why</technical_language>

Target:
private static void compose(StringBuilder builder, String key, String value) { final char PROPERTY_DELIMITER = ','; final char NAME_VALUE_SEPARATOR = '='; builder.append(key).append(NAME_VALUE_SEPARATOR).append(value).append(PROPERTY_DELIMITER); }
Source:
<code><START> public void populateAndApplyDefaults(ParallelTransferOptions other) { <END> if (other == null) { other = new ParallelTransferOptions(); } this.setBlockSize(other.getBlockSize() == null ? BLOB_DEFAULT_UPLOAD_BLOCK_SIZE : other.getBlockSize()); this.setNumBuffers(other.getNumBuffers() == null ? BLOB_DEFAULT_NUMBER_OF_BUFFERS : other.getNumBuffers()); this.setProgressReceiver(other.getProgressReceiver()); }</code><technical_language>This is a public API change. need public? reviewed other language folks</technical_language>

Target:
public void populateAndApplyDefaults(ParallelTransferOptions other) { if (other == null) { other = new ParallelTransferOptions(); } this.setBlockSize(other.getBlockSize() == null ? Integer.valueOf(BLOB_DEFAULT_UPLOAD_BLOCK_SIZE) : other.getBlockSize()); this.setNumBuffers(other.getNumBuffers() == null ? Integer.valueOf(BLOB_DEFAULT_NUMBER_OF_BUFFERS) : other.getNumBuffers()); this.setProgressReceiver(other.getProgressReceiver()); }
Source:
<code>private CommitHistory pathCommitHistory(final RevWalk rw) throws MissingObjectException, IncorrectObjectTypeException, IOException { final Map<AnyObjectId, String> pathByCommit = new HashMap<>(); final List<RevCommit> commits = new ArrayList<>(); final RenameCaptor renameCaptor = new RenameCaptor(); final TreeRevFilter revFilter = createTreeRevFilter(rw, path, renameCaptor); String curPath = path; <START> for (RevCommit commit : rw) { <END> if (revFilter.include(rw, commit)) { @SuppressWarnings("resource") final TreeWalk tw = new TreeWalk(rw.getObjectReader()); tw.setRecursive(true); tw.setFilter(PathFilter.create(curPath)); tw.addTree(commit.getTree()); if (tw.next()) { commits.add(commit); pathByCommit.put(commit.getId(), curPath); if (renameCaptor.hasCaptured()) { curPath = renameCaptor.getAndReset().getOldPath(); } } } } return new CommitHistory(commits, pathByCommit, path); }</code><technical_language>Minor thing, for consistency I use: java for (final RevCommit commit : rw) { ..</technical_language>

Target:
private CommitHistory pathCommitHistory(final RevWalk rw) throws MissingObjectException, IncorrectObjectTypeException, IOException { final Map<AnyObjectId, String> pathByCommit = new HashMap<>(); final List<RevCommit> commits = new ArrayList<>(); final RenameCaptor renameCaptor = new RenameCaptor(); final TreeRevFilter revFilter = createTreeRevFilter(rw, path, renameCaptor); String curPath = path; for (final RevCommit commit : rw) { if (revFilter.include(rw, commit)) { @SuppressWarnings("resource") final TreeWalk tw = new TreeWalk(rw.getObjectReader()); tw.setRecursive(true); tw.setFilter(PathFilter.create(curPath)); tw.addTree(commit.getTree()); if (tw.next()) { commits.add(commit); pathByCommit.put(commit.getId(), curPath); if (renameCaptor.hasCaptured()) { curPath = renameCaptor.getAndReset().getOldPath(); } } } } return new CommitHistory(commits, pathByCommit, path); }
Source:
<code><START> protected void performDefaults() { CDTPrefUtil.cleanPreferredTCs(); h_selected.handleSelection(); } <END></code><technical_language>perform defaults restore MinGW default too</technical_language>

Target:
protected void performDefaults() { CDTPrefUtil.cleanPreferredTCs(); h_selected.handleSelection(); MinGW.changeMinGWDefaultLocation(MinGW.getAllMinGWHome().get(0)); comboMinGWChains.select(0); }
Source:
<code>public String getLink(HttpServletRequest req, String requestedUrl) { if (urlComputerClass != null && urlComputer == null) { try { <START> urlComputer = urlComputerClass.newInstance(); <END> } catch (ReflectiveOperationException e) { log.error("Unable to instantiate LoginProviderLinkComputer", e); } } if (urlComputer != null) { return urlComputer.computeUrl(req, requestedUrl); } else { return link; } }</code><technical_language>newInstance class is deprecated in java 9, add a getDeclaredConstructor ? suggestion urlComputer = urlComputerClass.getDeclaredConstructor().newInstance();</technical_language>

Target:
public String getLink(HttpServletRequest req, String requestedUrl) { if (urlComputerClass != null && urlComputer == null) { try { urlComputer = urlComputerClass.getDeclaredConstructor().newInstance(); } catch (ReflectiveOperationException e) { log.error("Unable to instantiate LoginProviderLinkComputer", e); } } if (urlComputer != null) { return urlComputer.computeUrl(req, requestedUrl); } else { return link; } }
Source:
<code>private void getDefaultConfigurationVersion(final LoginModel loginModel) { AsyncQuery callback = new AsyncQuery<>(new AsyncCallback<VdcQueryReturnValue>() { @Override public void onSuccess(VdcQueryReturnValue returnValue) { if (returnValue != null) { _defaultConfigurationVersion = <START> returnValue.getReturnValue(); <END> } else { _defaultConfigurationVersion = GENERAL; } loginModel.getLoggedInEvent().raise(loginModel, EventArgs.EMPTY); } }); callback.setHandleFailure(true); Frontend.getInstance().runQuery(VdcQueryType.GetDefaultConfigurationVersion, new VdcQueryParametersBase(), callback); }</code><technical_language>Is this change related patch? if not, u please separate a patch</technical_language>

Target:
private void getDefaultConfigurationVersion(final LoginModel loginModel) { AsyncQuery callback = new AsyncQuery<>(new AsyncCallback<VdcQueryReturnValue>() { @Override public void onSuccess(VdcQueryReturnValue returnValue) { if (returnValue != null) { _defaultConfigurationVersion = ((VdcQueryReturnValue) returnValue).getReturnValue(); } else { _defaultConfigurationVersion = GENERAL; } loginModel.getLoggedInEvent().raise(loginModel, EventArgs.EMPTY); } }); callback.setHandleFailure(true); Frontend.getInstance().runQuery(VdcQueryType.GetDefaultConfigurationVersion, new VdcQueryParametersBase(), callback); }
Source:
<code>public static String stripFullLineComments(String statement) { StringBuilder newStatement = new StringBuilder(statement.length()); for (String line : statement.split("\n")) { if (!line.trim().startsWith("--")) { newStatement.append(line); newStatement.append('\n'); } } <START> return newStatement.toString().trim(); <END> }</code><technical_language>I assume trim() side effects affect else? MutantSwarm matching character positions anything? Is a reason for trims</technical_language>

Target:
public static String stripFullLineComments(String statement) { StringBuilder newStatement = new StringBuilder(statement.length()); String[] lines = statement.split("\n"); for (int i = 0; i < lines.length; i++) { String line = lines[i]; if (!line.trim().startsWith("--")) { newStatement.append(line); if (i < lines.length - 1) { newStatement.append('\n'); } } } return newStatement.toString(); }
Source:
<code><START> public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException { <END> baseRequest.setHandled(true); ServletContext sc = baseRequest.getContext(); ServiceLocator sl = ((ServletContainer) environment.getJerseyServletContainer()).getApplicationHandler().getServiceLocator(); RegistersConfiguration rc = sl.getService(RegistersConfiguration.class); String registerId = RegisterNameExtractor.extractRegisterName(request.getHeader("Host")); RegisterData rd = rc.getRegisterData(registerId); String registerName = registerId.replace('-',' '); WebContext wc = new WebContext(request, response, sc, request.getLocale()); wc.setVariable("register", rd.getRegister()); wc.setVariable("friendlyRegisterName", StringUtils.capitalize(registerName) + " register"); engine.process("404.html", wc, response.getWriter()); }</code><technical_language>errors this handle? is 404s 4xxs 4xxs + 5xxs</technical_language>

Target:
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException { if (response.getStatus() != HttpServletResponse.SC_NOT_FOUND) { return; } baseRequest.setHandled(true); ServletContext sc = baseRequest.getContext(); ServiceLocator sl = ((ServletContainer) environment.getJerseyServletContainer()).getApplicationHandler().getServiceLocator(); RegistersConfiguration rc = sl.getService(RegistersConfiguration.class); String registerId = RegisterNameExtractor.extractRegisterName(request.getHeader("Host")); RegisterData rd = rc.getRegisterData(registerId); String registerName = registerId.replace('-', ' '); WebContext wc = new WebContext(request, response, sc, request.getLocale()); wc.setVariable("register", rd.getRegister()); wc.setVariable("friendlyRegisterName", StringUtils.capitalize(registerName) + " register"); response.setHeader("Content-Type", "text/html; charset=UTF-8"); engine.process("404.html", wc, response.getWriter()); }
Source:
<code>protected <E extends MongoEntity> void extendBatchQuery(MongoQuery<E> query) { if (!Traced.class.isAssignableFrom(query.getDescriptor().getType())) { <START> throw new IllegalArgumentException("Entitis for which 'ChangeChecks' are created must implement 'Traced'."); <END> } query.where(QueryBuilder.FILTERS.gt(Traced.TRACE.inner(TraceData.CHANGED_AT), LocalDateTime.now().minusDays(1))); }</code><technical_language>suggestion throw new IllegalArgumentException("Entities for 'ChangeChecks' created implement 'Traced'.");</technical_language>

Target:
protected <E extends MongoEntity> void extendBatchQuery(MongoQuery<E> query) { if (!Traced.class.isAssignableFrom(query.getDescriptor().getType())) { throw new IllegalArgumentException("Entities for which 'ChangeChecks' are created must implement 'Traced'."); } query.where(QueryBuilder.FILTERS.gt(Traced.TRACE.inner(TraceData.CHANGED_AT), LocalDateTime.now().minusDays(1))); }
Source:
<code>private void handleContent(HttpContent httpContent) throws RestServiceException { if (request != null && !requestContentFullyReceived) { long processingStartTime = System.currentTimeMillis(); nettyMetrics.bytesReadRate.mark(httpContent.content().readableBytes()); requestContentFullyReceived = httpContent instanceof LastHttpContent; logger.trace("Received content for request - {}", request.getUri()); try { request.addContent(httpContent); } catch (IllegalStateException e) { nettyMetrics.contentAdditionError.inc(); <START> throw new RestServiceException(e, RestServiceErrorCode.InvalidRequestState); <END> } finally { long chunkProcessingTime = System.currentTimeMillis() - processingStartTime; nettyMetrics.requestChunkProcessingTimeInMs.update(chunkProcessingTime); request.getMetricsTracker().nioMetricsTracker.addToRequestProcessingTime(chunkProcessingTime); } if (!request.getRestMethod().equals(RestMethod.POST) || (request.isMultipart() && requestContentFullyReceived)) { requestHandler.handleRequest(request, responseChannel); } } else { resetState(); logger.warn("Received content when it was not expected on channel {}", ctx.channel()); nettyMetrics.noRequestError.inc(); responseChannel.onResponseComplete( new RestServiceException("Received content without a request", RestServiceErrorCode.InvalidRequestState)); } }</code><technical_language>responseChannel notified this exception well</technical_language>

Target:
private boolean handleContent(HttpContent httpContent) throws RestServiceException { boolean success = true; if (request != null && !requestContentFullyReceived) { long processingStartTime = System.currentTimeMillis(); nettyMetrics.bytesReadRate.mark(httpContent.content().readableBytes()); requestContentFullyReceived = httpContent instanceof LastHttpContent; logger.trace("Received content for request - {}", request.getUri()); try { request.addContent(httpContent); } catch (IllegalStateException e) { success = false; nettyMetrics.contentAdditionError.inc(); responseChannel.onResponseComplete(new RestServiceException(e, RestServiceErrorCode.InvalidRequestState)); } finally { long chunkProcessingTime = System.currentTimeMillis() - processingStartTime; nettyMetrics.requestChunkProcessingTimeInMs.update(chunkProcessingTime); request.getMetricsTracker().nioMetricsTracker.addToRequestProcessingTime(chunkProcessingTime); } if (success && (!request.getRestMethod().equals(RestMethod.POST) || (request.isMultipart() && requestContentFullyReceived))) { requestHandler.handleRequest(request, responseChannel); } } else { success = false; resetState(); logger.warn("Received content when it was not expected on channel {}", ctx.channel()); nettyMetrics.noRequestError.inc(); responseChannel.onResponseComplete( new RestServiceException("Received content without a request", RestServiceErrorCode.InvalidRequestState)); } return success; }
Source:
<code>public void visit(final MethodCallExpr n, final Void arg) { printComment(n.getComment(), arg); n.getScope().ifPresent(scope -> { scope.accept(this, arg); boolean mayAlignColumns = n.findParent(Statement.class) <START> .map(p -> p.isReturnStmt() || p.isExpressionStmt()) <END> .orElse(false); if (mayAlignColumns && configuration.isColumnAlignFirstMethodChain()) { if (!(scope instanceof MethodCallExpr) || !((MethodCallExpr) scope).getScope().isPresent()) { printer.reindentWithAlignToCursor(); } else { printer.println(); } } printer.print("."); }); printTypeArgs(n, arg); n.getName().accept(this, arg); printer.duplicateIndent(); printArguments(n.getArguments(), arg); printer.unindent(); }</code><technical_language>ThrowStmt AssertStmt? apply? This calculation is costly, is it? if is, done if (configuration.isColumnAlignFirstMethodChain()) block instead of in front of it</technical_language>

Target:
public void visit(final MethodCallExpr n, final Void arg) { printComment(n.getComment(), arg); n.getScope().ifPresent(scope -> { scope.accept(this, arg); if (configuration.isColumnAlignFirstMethodChain()) { if (n.findParent(Statement.class).map(p -> p.isReturnStmt() || p.isThrowStmt() || p.isAssertStmt() || p.isExpressionStmt()).orElse(false)) { if (scope instanceof MethodCallExpr && ((MethodCallExpr) scope).getScope().isPresent()) { printer.println(); } else { printer.reindentWithAlignToCursor(); } } } printer.print("."); }); printTypeArgs(n, arg); n.getName().accept(this, arg); printer.duplicateIndent(); printArguments(n.getArguments(), arg); printer.unindent(); }
Source:
<code>public void testTimestamp() { final Intent intent = new Intent(); intent.putExtra("mp_message", "MESSAGE"); intent.putExtra("mp_time", "2014-10-02T15:01:23.045123456Z"); Notification notification = mpPushSpy.createNotification(intent); <START> Instant instant = Instant.parse( "2014-10-02T15:01:23.045123456Z" ); <END> verify(builderSpy).setShowWhen(true); verify(builderSpy).setWhen(instant.toEpochMilli()); }</code><technical_language>nit: space quotes</technical_language>

Target:
public void testTimestamp() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { final Intent intent = new Intent(); intent.putExtra("mp_message", "MESSAGE"); intent.putExtra("mp_time", "2014-10-02T15:01:23.045123456Z"); Notification notification = mpPushSpy.createNotification(intent); Instant instant = Instant.parse("2014-10-02T15:01:23.045123456Z"); verify(builderSpy).setShowWhen(true); verify(builderSpy).setWhen(instant.toEpochMilli()); } }
Source:
<code>public static final void commonDownloadFile(ServerConnectionInfo serverInfo, File f, String downloadUrl) throws URISyntaxException, IOException, TransmissionException { log.info("Downloading URL into {}", downloadUrl, f); URI u = null; try { log.info("Parsing URL {}", downloadUrl); URL uurl = new URL(downloadUrl); u = uurl.toURI(); } catch (MalformedURLException | URISyntaxException e) { <START> log.error("bad download url", e); <END> throw e; } HttpClient httpclient = WebUtils.createHttpClient(); HttpClientContext localContext = WebUtils.getHttpContext(); HttpGet req = WebUtils.createOpenRosaHttpGet(u); WebUtils.setCredentials(localContext, serverInfo, u); HttpResponse response = null; { response = httpclient.execute(req, localContext); int statusCode = response.getStatusLine().getStatusCode(); if (statusCode == 401) { WebUtils.resetHttpContext(); throw new TransmissionException("Authentication failure"); } else if (statusCode != 200) { String errMsg = "Fetch failed. Detailed reason: " + response.getStatusLine().getReasonPhrase() + " (" + statusCode + ")"; log.error(errMsg); flushEntityBytes(response.getEntity()); throw new TransmissionException(errMsg); } try (InputStream is = response.getEntity().getContent(); OutputStream os = new FileOutputStream(f)) { byte buf[] = new byte[1024]; int len; while ((len = is.read(buf)) > 0) { os.write(buf, 0, len); } os.flush(); } } }</code><technical_language>Wondering if this a level error for now. I stacktrace include URL do it</technical_language>

Target:
public static final void commonDownloadFile(ServerConnectionInfo serverInfo, File f, String downloadUrl) throws URISyntaxException, IOException, TransmissionException { log.info("Downloading URL into {}", downloadUrl, f); URI u = null; try { log.info("Parsing URL {}", downloadUrl); URL uurl = new URL(downloadUrl); u = uurl.toURI(); } catch (MalformedURLException | URISyntaxException e) { log.warn("bad download url", e); throw e; } HttpClient httpclient = WebUtils.createHttpClient(); HttpClientContext localContext = WebUtils.getHttpContext(); HttpGet req = WebUtils.createOpenRosaHttpGet(u); WebUtils.setCredentials(localContext, serverInfo, u); HttpResponse response = null; { response = httpclient.execute(req, localContext); int statusCode = response.getStatusLine().getStatusCode(); if (statusCode == 401) { WebUtils.resetHttpContext(); throw new TransmissionException("Authentication failure"); } else if (statusCode != 200) { String errMsg = "Fetch failed. Detailed reason: " + response.getStatusLine().getReasonPhrase() + " (" + statusCode + ")"; log.error(errMsg); flushEntityBytes(response.getEntity()); throw new TransmissionException(errMsg); } try (InputStream is = response.getEntity().getContent(); OutputStream os = new FileOutputStream(f)) { byte buf[] = new byte[1024]; int len; while ((len = is.read(buf)) > 0) { os.write(buf, 0, len); } os.flush(); } } }
Source:
<code>private Object remoteGetBeforeWrite(InvocationContext ctx, Object key, FlagAffectedCommand command) throws Throwable { if (isStateTransferInProgressForKey(key)) { if (trace) log.tracef("Doing a remote get for key %s", key); InternalCacheEntry ice = dm.retrieveFromRemoteSource(key, ctx, false, command); if (ice != null) { CacheEntry ce = ctx.lookupEntry(key); if (ce == null || ce.isNull() || ce.isLockPlaceholder() || ce.getValue() == null) { if (ce != null && ce.isChanged()) { ce.setValue(ice.getValue()); } else { lockAndWrap(ctx, key, ice, command); } } return ice.getValue(); } } else { <START> if (trace) log.tracef("Not doing a remote get for key %s since entry is mapped to current node (%s), or is in L1. Owners are %s", key, rpcManager.getAddress(), dm.locate(key)); <END> } return null; }</code><technical_language>do remote get is state transfer in progress.</technical_language>

Target:
private Object remoteGetBeforeWrite(InvocationContext ctx, Object key, FlagAffectedCommand command) throws Throwable { if (dm.isAffectedByRehash(key) && !dataContainer.containsKey(key)) { if (trace) log.tracef("Doing a remote get for key %s", key); InternalCacheEntry ice = dm.retrieveFromRemoteSource(key, ctx, false, command); if (ice != null) { if (!ctx.replaceValue(key, ice.getValue())) { entryFactory.wrapEntryForPut(ctx, key, ice, false, command); } return ice.getValue(); } } else { if (trace) log.tracef("Not doing a remote get for key %s since entry is not affected by rehash or is already in data container. We are %s, owners are %s", key, rpcManager.getAddress(), dm.locate(key)); } return null; }
Source:
<code>protected void setUp() throws Exception { String[] commands = {"cmd", "/c", "start", "iexplore.exe","-nohome", "\"<LINK_0>\""}; Runtime.getRuntime().exec(commands); <START> Thread.sleep(30000); <END> }</code><technical_language>do a smarter a 30 wait a browse a specific website? launch Win32 API ShellExecute</technical_language>

Target:
public void setUp() throws Exception { Runtime.getRuntime().exec("cmd /c start iexplore.exe -nohome \"about:blank\""); Thread.sleep(3000); }
Source:
<code>public static MigrationOptions map(HasMigrationOptions entity, MigrationOptions template) { if (template == null) { template = new MigrationOptions(); } template.setAutoConverge(mapToInheritableBoolean(entity.getAutoConverge())); template.setCompressed(mapToInheritableBoolean(entity.getMigrateCompressed())); if (entity.getMigrationPolicyId() != null) { <START> MigrationPolicy policy = new MigrationPolicy(); <END> policy.setId(entity.getMigrationPolicyId().toString()); template.setPolicy(policy); } return template; }</code><technical_language>"template" object passed this method some data (not today, in future) this code is completely overriding it. In general is check create new object needed: MigrationPolicy policy = template.getPolicy(); if (policy == null) { policy = new MigrationPolicy(); template.setPolicy(policy); } ..</technical_language>

Target:
public static MigrationOptions map(HasMigrationOptions entity, MigrationOptions template) { if (template == null) { template = new MigrationOptions(); } template.setAutoConverge(mapToInheritableBoolean(entity.getAutoConverge())); template.setCompressed(mapToInheritableBoolean(entity.getMigrateCompressed())); if (entity.getMigrationPolicyId() != null) { MigrationPolicy policy = template.getPolicy(); if (policy == null) { policy = new MigrationPolicy(); template.setPolicy(policy); } policy.setId(entity.getMigrationPolicyId().toString()); template.setPolicy(policy); } return template; }