auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private boolean setLabelWithFeatureValue(final DCell cell, final ColumnMapping columnMapping, final String featureName) { boolean init = false; String label = ""; try { final Object featureObject = accessor.eGet(cell.getTarget(), featureName); if (featureObject != null) { if (featureObject instanceof EList<?>) { List<String> texts = Lists.newArrayList(); for (Object obj : (EList<?>) featureObject) { <START> if (obj instanceof String) { texts.add((String) obj); } else { texts.add(getText(obj)); } <END> } label = texts.toString(); } else if (featureObject instanceof EObject) { label = getText(featureObject); } else { label = featureObject.toString(); } init = true; } else if (cell.getTarget().eClass().getEStructuralFeature(featureName) != null) { init = true; } if (init) { if (isDifferent(cell.getLabel(), label)) { cell.setLabel(label); } } } catch (final FeatureNotFoundException e) { RuntimeLoggerManager.INSTANCE.error(columnMapping, DescriptionPackage.eINSTANCE.getFeatureColumnMapping_FeatureName(), e); } return init; }</code><technical_language>handle String case? be: if (obj instanceof EObject) { texts.add(getText(obj)); } else if (obj != null) { texts.add(String.valueOf(obj)); }</technical_language>

Target:
private boolean setLabelWithFeatureValue(final DCell cell, final ColumnMapping columnMapping, final String featureName) { boolean init = false; String label = ""; try { final Object featureObject = accessor.eGet(cell.getTarget(), featureName); if (featureObject != null) { if (featureObject instanceof EList<?>) { List<String> texts = Lists.newArrayList(); for (Object obj : (EList<?>) featureObject) { texts.add(getText(obj)); } label = texts.toString(); } else if (featureObject instanceof EObject) { label = getText(featureObject); } else { label = featureObject.toString(); } init = true; } else if (cell.getTarget().eClass().getEStructuralFeature(featureName) != null) { init = true; } if (init) { if (isDifferent(cell.getLabel(), label)) { cell.setLabel(label); } } } catch (final FeatureNotFoundException e) { RuntimeLoggerManager.INSTANCE.error(columnMapping, DescriptionPackage.eINSTANCE.getFeatureColumnMapping_FeatureName(), e); } return init; }
Source:
<code>public void InteractiveMaps_030_PalantirSetPlayerCorrectPosition() { InteractiveMapPageObject selectedMap = new InteractiveMapPageObject(driver); <START> selectedMap.openMap(wikiURL, 3); <END> selectedMap.verifyMapOpened(); PalantirComponentObject poi = new PalantirComponentObject(driver); PalantirContent handle = new PalantirContent(); handle = poi.setAndVerifyPlayerPosition(-40, -10, 3, true); poi.verifyCorrectPlayerPos(handle.success, handle.responseCode, handle.message); poi.verifyPoiAppearOnMap(); }</code><technical_language>Suggest move 2nd param a class variable I other tests value</technical_language>

Target:
public void InteractiveMaps_030_PalantirSetPlayerCorrectPosition() { InteractiveMapsPageObject specialMap = new InteractiveMapsPageObject(driver); InteractiveMapPageObject selectedMap = specialMap.openMap(wikiURL, PalantirContent.PALANTIR_MAP); selectedMap.verifyMapOpened(); PalantirComponentObject poi = new PalantirComponentObject(driver); PalantirContent handle = poi.setAndVerifyPlayerPosition(-40, -10, 3, true); poi.verifyCorrectPlayerPos(handle); poi.verifyPoiAppearOnMap(); }
Source:
<code>protected byte[] getSampleBuffer() { final File file = new File(getFilename()); final int bufferSize = getBufferSize(); byte[] bytes = new byte[bufferSize]; FileInputStream fileInputStream = null; try { fileInputStream = new FileInputStream(file); int startPosition = getStartPosition(); fileInputStream.skip(startPosition); int bytesRead = fileInputStream.read(bytes, 0, bufferSize); if (bytesRead != -1 && bytesRead <= bufferSize) { bytes = Arrays.copyOf(bytes, bytesRead); } return bytes; } catch (IOException e) { logger.error("IOException occurred while reading sample buffer", e); return new byte[0]; } finally { <START> FileHelper.safeClose(fileInputStream); <END> } }</code><technical_language>able skip "safeClose" try-with-resources directly. Actually, safe safeClose in mind. swallows exceptions logs debug level</technical_language>

Target:
protected byte[] getSampleBuffer() { final File file = new File(getFilename()); final int bufferSize = getBufferSize(); byte[] bytes = new byte[bufferSize]; try (final FileInputStream fileInputStream = new FileInputStream(file)) { int startPosition = getStartPosition(); fileInputStream.skip(startPosition); int bytesRead = fileInputStream.read(bytes, 0, bufferSize); if (bytesRead != -1 && bytesRead <= bufferSize) { bytes = Arrays.copyOf(bytes, bytesRead); } return bytes; } catch (IOException e) { logger.error("IOException occurred while reading sample buffer", e); return new byte[0]; } }
Source:
<code>private void closeMainWindow(WindowEvent event) { if (applicationContext.getBean(GameService.class).isGameRunning()) { I18n i18n = applicationContext.getBean(I18n.class); NotificationService notificationService = applicationContext.getBean(NotificationService.class); notificationService.addNotification(new ImmediateNotification(i18n.get("exitWarning.title"), i18n.get("exitWarning.message"), Severity.WARN, asList( new Action(i18n.get("yes"), ev -> { <START> Window window = (Window) event.getSource(); window.hide(); <END> }), new Action(i18n.get("no"), ev -> { }) ))); event.consume(); } }</code><technical_language>Platform.exit()</technical_language>

Target:
private void closeMainWindow(WindowEvent event) { if (applicationContext.getBean(GameService.class).isGameRunning()) { I18n i18n = applicationContext.getBean(I18n.class); NotificationService notificationService = applicationContext.getBean(NotificationService.class); notificationService.addNotification(new ImmediateNotification(i18n.get("exitWarning.title"), i18n.get("exitWarning.message"), Severity.WARN, asList( new Action(i18n.get("yes"), ev -> { Platform.exit(); }), new Action(i18n.get("no"), ev -> { }) ))); event.consume(); } }
Source:
<code>public static Object convert(Schema.Type type, Object value) { <START> Objects.requireNonNull(value, "'null' value is not allowed"); <END> switch (type) { case BOOLEAN: if (value instanceof Boolean) { return value; } else if (value instanceof String) { return Boolean.valueOf((String) value); } break; case BYTE: case SHORT: case INTEGER: case LONG: case FLOAT: case DOUBLE: return convertNumber(type, value); case STRING: if (value instanceof String) { return value; } break; case BINARY: if (value instanceof byte[]) { return value; } break; case NESTED: if (value instanceof Map) { return value; } break; case ARRAY: if (value instanceof List) { return value; } break; } throw new IllegalArgumentException("Cannot convert value " + value + " with Java type class " + value.getClass() + " to type " + type); }</code><technical_language>want handle this IllegalArgumentException, change forEach catch IllegalArgumentException wrap SchemaValidationFailedException. Bubbling NullPointerException IllegalArgumentException REST API response bad for end users. If want ensure denying null, OK leave is, I handle it</technical_language>

Target:
public static Object convert(Schema.Type type, Object value) { if (value == null) { return null; } switch (type) { case BOOLEAN: if (value instanceof Boolean) { return value; } else if (value instanceof String) { return Boolean.valueOf((String) value); } break; case BYTE: case SHORT: case INTEGER: case LONG: case FLOAT: case DOUBLE: return convertNumber(type, value); case STRING: if (value instanceof String) { return value; } break; case BINARY: if (value instanceof byte[]) { return value; } break; case NESTED: if (value instanceof Map) { return value; } break; case ARRAY: if (value instanceof List) { return value; } break; } throw new IllegalArgumentException("Cannot convert value " + value + " with Java type class " + value.getClass() + " to type " + type); }
Source:
<code>private Constraint flightConflict(ConstraintFactory constraintFactory) { return constraintFactory.fromUniquePair(FlightAssignment.class) <START> .filter((first, second) -> Objects.equals(first.getEmployee(), second.getEmployee())) <END> .filter((first, second) -> second.getFlight().overlaps(first.getFlight())) .filter((first, second) -> second.getId() > first.getId()) .penalize("Flight conflict", HardSoftLongScore.ofHard(10)); }</code><technical_language>This a joiner, for performance: constraintFactory.fromUniquePair(FlightAssignment.class, equals(FlightAssignment::getEmployee))</technical_language>

Target:
private Constraint flightConflict(ConstraintFactory constraintFactory) { return constraintFactory.fromUniquePair(FlightAssignment.class, Joiners.equal(FlightAssignment::getEmployee)) .filter((first, second) -> second.getFlight().overlaps(first.getFlight())) .penalize("Flight conflict", HardSoftLongScore.ofHard(10)); }
Source:
<code>private void generateGetMethod(Method method) { Parameter mainParameter = jaxrsGeneratorUtils.getMainUpdateParameter(method); if (mainParameter == null) { throw new IllegalStateException("Method \"" + method + "\" doesn't have any struct parameter"); } Service service = method.getDeclaringService(); boolean isRoot = service == service.getModel().getRoot(); javaBuffer.addImport(GET.class); javaBuffer.addLine("@GET"); if (isRoot) { javaBuffer.addImport(Response.class); addResponseReturnMethod("get()"); } else { Type mainType = mainParameter.getType(); JavaTypeReference mainTypeReference = schemaNames.getXjcTypeReference(mainType); javaBuffer.addImports(mainTypeReference.getImports()); generateDoGetMethod(mainParameter, mainTypeReference); generateDoc(method); <START> javaBuffer.addLine(""); <END> addMethod(mainTypeReference.getText(), "get()"); } javaBuffer.addLine(); }</code><technical_language>need for empty string</technical_language>

Target:
private void generateGetMethod(Method method) { Parameter mainParameter = jaxrsGeneratorUtils.getMainUpdateParameter(method); if (mainParameter == null) { throw new IllegalStateException("Method \"" + method + "\" doesn't have any struct parameter"); } Service service = method.getDeclaringService(); boolean isRoot = service == service.getModel().getRoot(); javaBuffer.addImport(GET.class); javaBuffer.addLine("@GET"); if (isRoot) { javaBuffer.addImport(Response.class); addResponseReturnMethod("get()"); } else { Type mainType = mainParameter.getType(); JavaTypeReference mainTypeReference = schemaNames.getXjcTypeReference(mainType); javaBuffer.addImports(mainTypeReference.getImports()); generateDoGetMethod(mainParameter, mainTypeReference); generateDoc(method); javaBuffer.addLine(); addMethod(mainTypeReference.getText(), "get()"); } javaBuffer.addLine(); }
Source:
<code>public static Map<String, List<String>> splitQuery(URI uri) { try { final Map<String, List<String>> query_pairs = new LinkedHashMap<>(); final String[] pairs = uri.getQuery().split("&"); for (String pair : pairs) { final int idx = pair.indexOf("="); final String key = idx > 0 ? URLDecoder.decode(pair.substring(0, idx), "UTF-8") : pair; if (!query_pairs.containsKey(key)) { query_pairs.put(key, new LinkedList<>()); } final String value = idx > 0 && pair.length() > idx + 1 ? URLDecoder.decode(pair.substring(idx + 1), "UTF-8") : null; query_pairs.get(key).add(value); } return query_pairs; } catch (Exception e) { <START> return Collections.emptyMap(); <END> } }</code><technical_language>Wondering if LOG report returning empty map exception e occurred</technical_language>

Target:
public static Map<String, List<String>> splitQuery(URI uri) { try { final Map<String, List<String>> query_pairs = new LinkedHashMap<>(); final String[] pairs = uri.getQuery().split("&"); for (String pair : pairs) { final int idx = pair.indexOf("="); final String key = idx > 0 ? URLDecoder.decode(pair.substring(0, idx), "UTF-8") : pair; if (!query_pairs.containsKey(key)) { query_pairs.put(key, new LinkedList<>()); } final String value = idx > 0 && pair.length() > idx + 1 ? URLDecoder.decode(pair.substring(idx + 1), "UTF-8") : null; query_pairs.get(key).add(value); } return query_pairs; } catch (Exception e) { LOGGER.warning("Unable to split query into key/value pairs for URI " + uri + ". " + e.getMessage()); return Collections.emptyMap(); } }
Source:
<code>public int compareTo(Name o) { <START> return normalizedName.compareTo(o.normalizedName); <END> }</code><technical_language>gestalt is a basic library, I deprecation here..</technical_language>

Target:
public int compareTo(Name o) { return normalisedName.compareTo(o.normalisedName); }
Source:
<code>EntityDescriptor getEntityDescriptor() { if (!isMetadataValid()) { LOGGER.debug("SSO metadata is invalid. Purging metadata cache"); entityData.set(null); } EntityData ed = Optional.ofNullable(entityData.get()) <START> .orElse( <END> Optional.ofNullable(parseMetadata()) .map(this::extractRootEntityFromMap) .map(EntityData::new) .orElse(null)); if (isMetadataExpired()) { LOGGER.debug("SSO metadata cache is expired. Attempted to retrieve new metadata"); entityData.set(null); } boolean updated = entityData.compareAndSet(null, ed); if (!updated) { LOGGER.debug("Safe but concurrent update to serviceProviders map; using processed value"); } return entityData.get().getEntityDescriptor(); }</code><technical_language>This occur reparsing lines 176-182, it? Otherwise, this method AtomicReference set, find is expired, reset right value</technical_language>

Target:
EntityDescriptor getEntityDescriptor() { EntityData previousEntityData = null; if (!isMetadataValid()) { LOGGER.debug("SSO metadata is invalid. Purging metadata cache"); entityData.set(null); } if (isMetadataExpired()) { LOGGER.debug("SSO metadata cache is expired. Attempt to retrieve new metadata"); previousEntityData = entityData.getAndSet(null); } EntityData newEntityData = null; if (entityData.get() == null) { newEntityData = Optional.ofNullable(parseMetadata()) .map(this::extractRootEntityFromMap) .map(EntityData::new) .orElse(previousEntityData); } boolean updated = entityData.compareAndSet(null, newEntityData); if (!updated) { LOGGER.trace("Safe but concurrent update to SAML entity; using processed value"); } final EntityData ed = entityData.get(); return ed == null ? null : ed.getEntityDescriptor(); }
Source:
<code>private String getAbbreviatedName(Abbreviation text) { <START> if (abbrvType == 0) { <END> return text.getIsoAbbreviation(); } else if (abbrvType == 1) { return text.getMedlineAbbreviation(); } else if (abbrvType == 2) { return text.getShortestUnique(); } return null; }</code><technical_language>Do a switch/case here. enum introduce</technical_language>

Target:
private String getAbbreviatedName(Abbreviation text) { switch (abbreviationType) { case DEFAULT: return text.getAbbreviation(); case MEDLINE: return text.getMedlineAbbreviation(); case SHORTEST_UNIQUE: return text.getShortestUniqueAbbreviation(); default: throw new IllegalStateException(String.format("Unexpected value: %s", abbreviationType)); } }
Source:
<code>private static <T> Object getFieldValue(T entity, String fieldPath, RequestScope requestScope) { Object val = entity; for (String field : fieldPath.split("\\.")) { if ("this".equals(field)) { continue; } if (val == null) { <START> continue; <END> } val = PersistentResource.getValue(val, field, requestScope); } return val; }</code><technical_language>return null break</technical_language>

Target:
private static <T> Object getFieldValue(T entity, String fieldPath, RequestScope requestScope) { Object val = entity; for (String field : fieldPath.split("\\.")) { if ("this".equals(field)) { continue; } if (val == null) { break; } val = PersistentResource.getValue(val, field, requestScope); } return val; }
Source:
<code>public static void main(String[] args) { MiniOptions options = new MiniOptions(); try { JCommander jcommand = new JCommander(options, args); if (options.help) { jcommand.usage(); System.exit(-1); } options.validateConfig(); <START> ClusterUtil.verifyConfigFilesExist(options.getConfigDir(), "fluo.properties", "log4j-stdout.xml"); <END> Log4jUtil.init("MiniAdmin", options.getConfigDir(), "STDOUT", false); } catch (Exception e) { System.err.println("Exception running MiniFluo: "+ e.getMessage()); e.printStackTrace(); } try { FluoConfiguration config = new FluoConfiguration(new File(options.getFluoProps())); switch (options.getCommand().toLowerCase()) { case "stop": File dataDir = new File(config.getMiniDataDir()); if (dataDir.exists() && config.getMiniStartAccumulo()) { FileUtils.deleteDirectory(dataDir); } break; default: log.error("Unknown command: " + options.getCommand()); break; } } catch (Exception e) { log.error("Exception running MiniAdmin: ", e); } }</code><technical_language>For log config files, verify existance in Log4jUtil.init() LogbackUtil.ini(). code calling methods assumptions</technical_language>

Target:
public static void main(String[] args) { MiniOptions options = new MiniOptions(); try { JCommander jcommand = new JCommander(options, args); if (options.help) { jcommand.usage(); System.exit(-1); } options.validateConfig(); Log4jUtil.init("MiniAdmin", options.getConfigDir(), "STDOUT", false); } catch (Exception e) { System.err.println("Exception running MiniFluo: "+ e.getMessage()); e.printStackTrace(); } try { ClusterUtil.verifyConfigPathsExist(options.getFluoProps()); FluoConfiguration config = new FluoConfiguration(new File(options.getFluoProps())); switch (options.getCommand().toLowerCase()) { case "stop": File dataDir = new File(config.getMiniDataDir()); if (dataDir.exists() && config.getMiniStartAccumulo()) { FileUtils.deleteDirectory(dataDir); } break; default: log.error("Unknown command: " + options.getCommand()); break; } } catch (Exception e) { log.error("Exception running MiniAdmin: ", e); } }
Source:
<code>public void initializeSchema(Configuration configuration, SessionFactoryImplementor factory) { SessionFactoryImplementor sessionFactoryImplementor = factory; ServiceRegistryImplementor registry = sessionFactoryImplementor.getServiceRegistry(); Neo4jDatastoreProvider provider = (Neo4jDatastoreProvider) registry.getService( DatastoreProvider.class ); createSequences( sessionFactoryImplementor, provider ); createEntityConstraints( provider.getDataBase(), configuration ); <START> initializeQueries( sessionFactoryImplementor, registry ); <END> }</code><technical_language>wondering this is triggered schema initializer. done dialect construction? schema initializer create/update persistent structures in datastore. This avoid need for injectQueries() method</technical_language>

Target:
public void initializeSchema(Configuration configuration, SessionFactoryImplementor factory) { SessionFactoryImplementor sessionFactoryImplementor = factory; ServiceRegistryImplementor registry = sessionFactoryImplementor.getServiceRegistry(); Neo4jDatastoreProvider provider = (Neo4jDatastoreProvider) registry.getService( DatastoreProvider.class ); createSequences( sessionFactoryImplementor, provider ); createEntityConstraints( provider.getDataBase(), configuration ); }
Source:
<code>TimeOfDay currentTimeOfDay() { TimeOfDay[] values = TimeOfDay.values(); flag++; if (flag >= values.length) { flag = 0; <START> } <END> return values[flag]; }</code><technical_language>flag = (flag+1) % values.length;</technical_language>

Target:
TimeOfDay currentTimeOfDay() { Calendar calendar = Calendar.getInstance(); int hourOfDay = calendar.get(Calendar.HOUR_OF_DAY); return TimeOfDay.forHourOfDay(hourOfDay); }
Source:
<code><START> private XmlRpcStruct[] getVmInfo(List<String> vmsToUpdate) { <END> return (XmlRpcStruct[]) (new FullListVdsCommand<VdsIdAndVdsVDSCommandParametersBase>( new FullListVDSCommandParameters(_vds.getId(), vmsToUpdate)).ExecuteWithReturnValue()); }</code><technical_language>wrap this call, a specific failure of refresh fail</technical_language>

Target:
private XmlRpcStruct[] getVmInfo(List<String> vmsToUpdate) { return (XmlRpcStruct[]) (new FullListVdsCommand<FullListVDSCommandParameters>( new FullListVDSCommandParameters(_vds.getId(), vmsToUpdate)).ExecuteWithReturnValue()); }
Source:
<code>public void testImportOpenShift3AppViaServerAdapterSettings() { ServerSettingsWizard serverWizard = new ServerSettingsWizard().openFromOpenshiftView(service); ImportApplicationWizard importWizard = new ServerSettingsWizardPage().importProject(); importWizard.next(); importWizard.finish(); <START> serverWizard.cancel(); <END> assertProjectExistsInProjectView(OpenShiftResources.NODEJS_GIT_NAME); }</code><technical_language>I guess in this phase, freshly created project pre-selected in "Eclipse Project:" textbox. Please add check for this</technical_language>

Target:
public void testImportOpenShift3AppViaServerAdapterSettings() { ServerSettingsWizard serverWizard = new ServerSettingsWizard().openFromOpenshiftView(service); ImportApplicationWizard importWizard = new ServerSettingsWizardPage().importProject(); importWizard.next(); importWizard.finish(); new DefaultShell(serverWizard.getTitle()); assertProjectNameFilled(); serverWizard.cancel(); assertProjectExistsInProjectView(OpenShiftResources.NODEJS_GIT_NAME); }
Source:
<code>public StreamBlockQueue(String path, String nonce, String streamName, int partitionId, long genId) throws java.io.IOException { m_path = path; m_nonce = nonce; m_streamName = streamName; m_partitionId = partitionId; long initialGenId = genId; Table streamTable = VoltDB.instance().getCatalogContext().database.getTables().get(m_streamName); <START> ExportRowSchema schema = ExportRowSchema.create(streamTable, m_partitionId, initialGenId, genId); <END> ExportRowSchemaSerializer serializer = new ExportRowSchemaSerializer(); m_persistentDeque = PersistentBinaryDeque.builder(m_nonce, new VoltFile(m_path), exportLog) .initialExtraHeader(schema, serializer) .compression(!DISABLE_COMPRESSION).build(); m_reader = m_persistentDeque.openForRead(m_nonce); BinaryDequeReader.Entry<ExportRowSchema> entry = m_reader.pollHeader(); if (entry != null) { initialGenId = entry.getExtraHeader().initialGenerationId; schema = ExportRowSchema.create(streamTable, m_partitionId, initialGenId, genId); m_persistentDeque.updateExtraHeader(schema); } m_initialGenerationId = initialGenId; if (exportLog.isDebugEnabled()) { exportLog.debug(m_nonce + " At SBQ creation, PBD size is " + (m_reader.sizeInBytes() - (8 * m_reader.getNumObjects())) + " initial generation ID is " + m_initialGenerationId); } }</code><technical_language>I need 2 generation id fields; concerned reading createdGenerationId field PBD wrong decisions it. IMO authority for 'created' generation id a) current catalog version creating a new EDS b) snapshot (that communicated truncate call)</technical_language>

Target:
public StreamBlockQueue(String path, String nonce, String streamName, int partitionId, long genId) throws java.io.IOException { m_path = path; m_nonce = nonce; m_streamName = streamName; m_partitionId = partitionId; m_initialGenerationId = genId; constructPBD(genId); if (exportLog.isDebugEnabled()) { exportLog.debug(m_nonce + " At SBQ creation, PBD size is " + (m_reader.sizeInBytes() - (8 * m_reader.getNumObjects())) + " initial generation ID is " + m_initialGenerationId); } }
Source:
<code>public void testProjectWithMapType() { String sqlQuery = "SELECT a, d['e']\n" + <START> "FROM MyTable"; <END> util().verifyPlan(sqlQuery); }</code><technical_language>MyTable support nested-projection-supported</technical_language>

Target:
public void testProjectWithMapType() { String sqlQuery = "SELECT id, testMap['e']\n" + "FROM NestedTable"; util().verifyPlan(sqlQuery); }
Source:
<code>public void tearDown() throws Exception { Activator.getDefault().getRepositoryCache().clear(); for (IProject project : createdProjects) { <START> if (project.exists()) { <END> project.delete(true, true, null); } } for (File pathToClean : pathsToClean) { if (pathToClean.exists()) { FileUtils.delete(pathToClean, FileUtils.RECURSIVE | FileUtils.RETRY); } } }</code><technical_language>style nit: braces single line blocks, more occurrences this patch</technical_language>

Target:
public void tearDown() throws Exception { Activator.getDefault().getRepositoryCache().clear(); for (IProject project : createdProjects) if (project.exists()) project.delete(true, true, null); for (File pathToClean : pathsToClean) if (pathToClean.exists()) FileUtils.delete(pathToClean, FileUtils.RECURSIVE | FileUtils.RETRY); }
Source:
<code><START> private Long getHeaderValueLong(String headerName) throws Exception { <END> String headerString = getHeaderValueString(headerName); try { return Long.parseLong(headerString); } catch (Exception e){ throw new SdkException("Error parsing " + headerName + " header"); } }</code><technical_language>methods return a primitive long Object Long</technical_language>

Target:
private long getHeaderValueLong(String headerName) throws Exception { String headerString = getHeaderValueString(headerName); try { return Long.parseLong(headerString); } catch (Exception e){ throw new SdkException("Error parsing " + headerName + " header"); } }
Source:
<code>protected void setUp() throws Exception { super.setUp(); git = new Git(db); <START> writeTrashFile("SomeFile.txt", "Hi there"); <END> git.commit().setMessage("initial commit").call(); File sourceFile = new File(db.getWorkTree(), "Test.txt"); FileOutputStream fos = new FileOutputStream(sourceFile); fos.write("Hello world".getBytes("UTF-8")); fos.close(); git.add().addFilepattern("Test.txt").call(); initialCommit = git.commit().setMessage("Initial commit").call(); fos = new FileOutputStream(sourceFile); fos.write("Some change".getBytes("UTF-8")); fos.close(); git.add().addFilepattern("Test.txt").call(); secondCommit = git.commit().setMessage("Second commit").call(); RefUpdate rup = db.updateRef("refs/heads/master"); rup.setNewObjectId(initialCommit.getId()); rup.setForceUpdate(true); rup.update(); }</code><technical_language>do create this file? added initial commit</technical_language>

Target:
protected void setUp() throws Exception { super.setUp(); git = new Git(db); git.commit().setMessage("initial commit").call(); writeTrashFile("Test.txt", "Hello world"); git.add().addFilepattern("Test.txt").call(); initialCommit = git.commit().setMessage("Initial commit").call(); writeTrashFile("Test.txt", "Some change"); git.add().addFilepattern("Test.txt").call(); secondCommit = git.commit().setMessage("Second commit").call(); RefUpdate rup = db.updateRef("refs/heads/master"); rup.setNewObjectId(initialCommit.getId()); rup.setForceUpdate(true); rup.update(); }
Source:
<code>public void setBoolean(StudyIdentifier studyIdentifier, String healthCode, ParticipantOption option, boolean value) { checkNotNull(studyIdentifier); checkArgument(isNotBlank(healthCode)); <START> checkNotNull(option == ParticipantOption.EMAIL_NOTIFICATIONS); <END> AccountId accountId = AccountId.forHealthCode(studyIdentifier.getIdentifier(), healthCode); Account account = accountDao.getAccount(accountId); if (account != null) { account.setNotifyByEmail(value); accountDao.updateAccount(account, false); } }</code><technical_language>this is check for. option==ParticipantOption.EMAIL_NOTIFICATIONS non-null. (Here a other places in this class.)</technical_language>

Target:
public void setBoolean(StudyIdentifier studyIdentifier, String healthCode, ParticipantOption option, boolean value) { checkNotNull(studyIdentifier); checkArgument(isNotBlank(healthCode)); checkArgument(option == ParticipantOption.EMAIL_NOTIFICATIONS); AccountId accountId = AccountId.forHealthCode(studyIdentifier.getIdentifier(), healthCode); Account account = accountDao.getAccount(accountId); if (account == null) { throw new EntityNotFoundException(Account.class, "Account not found"); } account.setNotifyByEmail(value); accountDao.updateAccount(account, false); }
Source:
<code>public static Configuration getHBaseConfiguration() { <START> Configuration result = new HBaseConfiguration().create(); <END> boolean foundHBaseConfiguration = false; String possibleHBaseConfPath = null; final String hbaseHome = System.getenv("HBASE_HOME"); if (hbaseHome != null) { LOG.debug("Searching HBase configuration files in HBASE_HOME: {}", hbaseHome); possibleHBaseConfPath = hbaseHome + "/conf"; } if (possibleHBaseConfPath != null) { foundHBaseConfiguration = addHBaseConfIfFound(result, possibleHBaseConfPath); } String hbaseConfDir = System.getenv("HBASE_CONF_DIR"); if (hbaseConfDir != null) { LOG.debug("Searching HBase configuration files in HBASE_CONF_DIR: {}", hbaseConfDir); foundHBaseConfiguration = addHBaseConfIfFound(result, hbaseConfDir) || foundHBaseConfiguration; } if (!foundHBaseConfiguration) { LOG.warn("Could not find HBase configuration via any of the supported methods " + "(Flink configuration, environment variables)."); } return result; }</code><technical_language>suggestion Configuration result = HBaseConfiguration.create();</technical_language>

Target:
public static Configuration getHBaseConfiguration() { Configuration result = HBaseConfiguration.create(); boolean foundHBaseConfiguration = false; String possibleHBaseConfPath = null; final String hbaseHome = System.getenv("HBASE_HOME"); if (hbaseHome != null) { LOG.debug("Searching HBase configuration files in HBASE_HOME: {}", hbaseHome); possibleHBaseConfPath = hbaseHome + "/conf"; } if (possibleHBaseConfPath != null) { foundHBaseConfiguration = addHBaseConfIfFound(result, possibleHBaseConfPath); } String hbaseConfDir = System.getenv("HBASE_CONF_DIR"); if (hbaseConfDir != null) { LOG.debug("Searching HBase configuration files in HBASE_CONF_DIR: {}", hbaseConfDir); foundHBaseConfiguration = addHBaseConfIfFound(result, hbaseConfDir) || foundHBaseConfiguration; } if (!foundHBaseConfiguration) { LOG.warn("Could not find HBase configuration via any of the supported methods " + "(Flink configuration, environment variables)."); } return result; }
Source:
<code><START> private void doSuspend(IExecutionDMContext context, final RequestMonitor rm) { <END> final MonitorSuspendJob monitorJob = new MonitorSuspendJob(0, rm); fCommandControl.queueCommand(fCommandFactory.createMIExecInterrupt(context), new ImmediateDataRequestMonitor<MIInfo>() { @Override protected void handleSuccess() { } @Override protected void handleFailure() { monitorJob.cleanAndCancel(); rm.done(getStatus()); } }); }</code><technical_language>If running full console (i.e. async) interrupt this ^C instead</technical_language>

Target:
private void doSuspend(IExecutionDMContext context, final RequestMonitor rm) { if (fGDBBackEnd.isFullGdbConsoleSupported()) { final MonitorSuspendJob monitorJob = new MonitorSuspendJob(0, rm); fCommandControl.queueCommand(fCommandFactory.createMIExecInterrupt(context), new ImmediateDataRequestMonitor<MIInfo>() { @Override protected void handleSuccess() { } @Override protected void handleFailure() { monitorJob.cleanAndCancel(); rm.done(getStatus()); } }); } else { super.suspend(context, rm); } }
Source:
<code>public Collection<CommentedFile> getFileComments(AbstractBuild build) { if (thisOverrides("getFileComments", Run.class)) { return getFileComments((Run)build); } <START> return null; <END> }</code><technical_language>IIRC previous contract return empty list null?, method</technical_language>

Target:
public Collection<CommentedFile> getFileComments(AbstractBuild build) { if (thisOverrides("getFileComments", Run.class)) { return getFileComments((Run)build); } return Collections.emptyList(); }
Source:
<code>public void expressionsAreConcurrentHashMap() { <START> assertTrue("Expressions should be concurrent to allow startup", getField(source, "channels") instanceof ConcurrentHashMap); <END> assertTrue("Expressions should be concurrent to allow startup", getField(source, "payloadExpressions") instanceof ConcurrentHashMap); assertTrue("Expressions should be concurrent to allow startup", getField(source, "headersExpressions") instanceof ConcurrentHashMap); }</code><technical_language>is assertThat() Matchers.instanceOf() for failure report if that</technical_language>

Target:
public void expressionsAreConcurrentHashMap() { assertThat("Expressions should be concurrent to allow startup", ReflectionTestUtils.getField(source, "channels"), instanceOf(ConcurrentHashMap.class)); assertThat("Expressions should be concurrent to allow startup", ReflectionTestUtils.getField(source, "payloadExpressions"), instanceOf(ConcurrentHashMap.class)); assertThat("Expressions should be concurrent to allow startup", ReflectionTestUtils.getField(source, "headersExpressions"), instanceOf(ConcurrentHashMap.class)); }
Source:
<code>public GrillClientResultSet getResults(String sql) { GrillStatement statement = new GrillStatement(conn); LOG.debug("Executing query " + sql); statement.execute(sql, true); if(statement.getStatus().getStatus() <START> != QueryStatus.Status.SUCCESSFUL) { <END> throw new IllegalStateException(statement.getStatus().getErrorMessage()); } return new GrillClientResultSet(statement.getResultSet(), statement.getResultSetMetaData()); }</code><technical_language>do this for FAILED status? For CANCELED queries, error message null</technical_language>

Target:
public GrillClientResultSet getResults(String sql) { GrillStatement statement = new GrillStatement(conn); LOG.debug("Executing query " + sql); statement.execute(sql, true); if(statement.getStatus().getStatus() == QueryStatus.Status.FAILED) { throw new IllegalStateException(statement.getStatus().getErrorMessage()); } return new GrillClientResultSet(statement.getResultSet(), statement.getResultSetMetaData()); }
Source:
<code>private ValidationResult validateStatus(VDSStatus hostStatus) { return ValidationResult.failWith(EngineMessage.ACTION_TYPE_FAILED_VDS_STATUS_ILLEGAL, ReplacementUtils.createSetVariableString("hostStatus", host.getStatus().name())) <START> .unless(hostStatus == host.getStatus()); <END> }</code><technical_language>please when</technical_language>

Target:
private ValidationResult validateStatus(VDSStatus hostStatus) { return ValidationResult.failWith(EngineMessage.ACTION_TYPE_FAILED_VDS_STATUS_ILLEGAL, ReplacementUtils.createSetVariableString("hostStatus", hostStatus.name())) .unless(hostStatus == host.getStatus()); }
Source:
<code>public IllegalIdentifierNameCheck() { <START> super("(?i)^(?!(record|yield|var|_)$).+$"); <END> }</code><technical_language>[JEP 360](<LINK_0> more keywords in Java: permits, sealed, non-sealed. one, non-sealed is a valid identifier anyway, permits, sealed in list</technical_language>

Target:
public IllegalIdentifierNameCheck() { super("(?i)^(?!(record|yield|var|permits|sealed|_)$).+$"); }
Source:
<code>private CompletionStage<RestResponse> runTask(RestRequest request) { String taskName = request.variables().get("taskName"); EmbeddedCacheManager cacheManager = invocationHelper.getRestCacheManager().getInstance(); TaskManager taskManager = SecurityActions.getGlobalComponentRegistry(cacheManager).getComponent(TaskManager.class); TaskContext taskContext = new TaskContext(); request.parameters().forEach((k, v) -> { if (k.startsWith("param.")) { taskContext.addParameter(k.substring(6), v.get(0)); } }); return taskManager.runTask(taskName, taskContext).thenApply(result -> { NettyRestResponse.Builder builder = new NettyRestResponse.Builder(); try { if (result instanceof byte[]) { builder.contentType(TEXT_PLAIN_TYPE).entity(result); } else { byte[] resultBytes = invocationHelper.getMapper().writeValueAsBytes(result); builder.contentType(APPLICATION_JSON_TYPE).entity(resultBytes); } } catch (JsonProcessingException e) { <START> builder.status(HttpResponseStatus.INTERNAL_SERVER_ERROR); <END> } return builder.build(); }); }</code><technical_language>want add exception message response</technical_language>

Target:
private CompletionStage<RestResponse> runTask(RestRequest request) { String taskName = request.variables().get("taskName"); EmbeddedCacheManager cacheManager = invocationHelper.getRestCacheManager().getInstance(); TaskManager taskManager = SecurityActions.getGlobalComponentRegistry(cacheManager).getComponent(TaskManager.class); TaskContext taskContext = new TaskContext(); request.parameters().forEach((k, v) -> { if (k.startsWith("param.")) { taskContext.addParameter(k.substring(6), v.get(0)); } }); return taskManager.runTask(taskName, taskContext).thenApply(result -> { NettyRestResponse.Builder builder = new NettyRestResponse.Builder(); try { if (result instanceof byte[]) { builder.contentType(TEXT_PLAIN_TYPE).entity(result); } else { byte[] resultBytes = invocationHelper.getMapper().writeValueAsBytes(result); builder.contentType(APPLICATION_JSON_TYPE).entity(resultBytes); } } catch (JsonProcessingException e) { builder.status(HttpResponseStatus.INTERNAL_SERVER_ERROR).entity(e.getMessage()); } return builder.build(); }); }
Source:
<code>public void unbind(final String eventName, final SubscriptionEventListener listener) { validateArguments(eventName, listener); <START> final Set<SubscriptionEventListener> listeners = eventNameToListenerMap.get(eventName); <END> synchronized (lock) { if (listeners != null) { listeners.remove(listener); if (listeners.isEmpty()) { eventNameToListenerMap.remove(eventName); } } } }</code><technical_language>above, perform read write in critical section, guarantee of consistency</technical_language>

Target:
public void unbind(final String eventName, final SubscriptionEventListener listener) { validateArguments(eventName, listener); synchronized (lock) { final Set<SubscriptionEventListener> listeners = eventNameToListenerMap.get(eventName); if (listeners != null) { listeners.remove(listener); if (listeners.isEmpty()) { eventNameToListenerMap.remove(eventName); } } } }
Source:
<code>public String downloadIgnite(String ver) throws IOException { assert ver != null; URL url; if (ver.equals(ClusterProperties.DEFAULT_IGNITE_VERSION)) { <START> ver = findLatestVersion(); <END> url = new URL(String.format(findMirror() + IGNITE_PATH, ver, ver)); } else { url = new URL(String.format(DOWNLOAD_URL_PATTERN, ver, ver)); } return downloadIgnite(url); }</code><technical_language>need try this logic, if catch() log error DOWNLOAD_URL_PATTERN</technical_language>

Target:
public String downloadIgnite(String ver) throws IOException { assert ver != null; URL url; if (ver.equals(ClusterProperties.DEFAULT_IGNITE_VERSION)) { try { ver = findLatestVersion(); url = new URL(String.format(findMirror() + IGNITE_PATH, ver, ver)); } catch (Exception e) { url = new URL(String.format(DOWNLOAD_URL_PATTERN, ver, ver)); } } else { url = new URL(String.format(DOWNLOAD_URL_PATTERN, ver, ver)); } return downloadIgnite(url); }
Source:
<code>private static Map<String, TemplateResolverFactory<LogEvent, EventResolverContext, ? extends TemplateResolver<LogEvent>>> createResolverFactoryByName() { <START> final List<EventResolverFactory<? extends EventResolver>> resolverFactories = Arrays.asList( <END> ContextDataResolverFactory.getInstance(), ContextStackResolverFactory.getInstance(), EndOfBatchResolverFactory.getInstance(), ExceptionResolverFactory.getInstance(), ExceptionRootCauseResolverFactory.getInstance(), LevelResolverFactory.getInstance(), LoggerResolverFactory.getInstance(), MainMapResolverFactory.getInstance(), MapResolverFactory.getInstance(), MarkerResolverFactory.getInstance(), MessageResolverFactory.getInstance(), SourceResolverFactory.getInstance(), ThreadResolverFactory.getInstance(), TimestampResolverFactory.getInstance()); final Map<String, TemplateResolverFactory<LogEvent, EventResolverContext, ? extends TemplateResolver<LogEvent>>> resolverFactoryByName = new LinkedHashMap<>(); for (final EventResolverFactory<? extends EventResolver> resolverFactory : resolverFactories) { resolverFactoryByName.put(resolverFactory.getName(), resolverFactory); } return Collections.unmodifiableMap(resolverFactoryByName); }</code><technical_language>This brittle this improved need arises</technical_language>

Target:
private static Map<String, TemplateResolverFactory<LogEvent, EventResolverContext, ? extends TemplateResolver<LogEvent>>> createResolverFactoryByName() { final List<EventResolverFactory<? extends EventResolver>> resolverFactories = Arrays.asList( ContextDataResolverFactory.getInstance(), ContextStackResolverFactory.getInstance(), EndOfBatchResolverFactory.getInstance(), ExceptionResolverFactory.getInstance(), ExceptionRootCauseResolverFactory.getInstance(), LevelResolverFactory.getInstance(), LoggerResolverFactory.getInstance(), MainMapResolverFactory.getInstance(), MapResolverFactory.getInstance(), MarkerResolverFactory.getInstance(), MessageResolverFactory.getInstance(), PatternResolverFactory.getInstance(), SourceResolverFactory.getInstance(), ThreadResolverFactory.getInstance(), TimestampResolverFactory.getInstance()); final Map<String, TemplateResolverFactory<LogEvent, EventResolverContext, ? extends TemplateResolver<LogEvent>>> resolverFactoryByName = new LinkedHashMap<>(); for (final EventResolverFactory<? extends EventResolver> resolverFactory : resolverFactories) { resolverFactoryByName.put(resolverFactory.getName(), resolverFactory); } return Collections.unmodifiableMap(resolverFactoryByName); }
Source:
<code>public void saveApplicationShouldSaveAProperApplicationDTOAndStateDTO() { final StateDTO stateDTO = StateDTO.builder().channel(new ChannelDTO(8L,null)).candidateId(1L).position(new PositionDTO(1L,null)).description("sss").stateType("newstate").stateIndex(0).build(); given(modelMapper.map(applicationDTO, ApplicationEntity.class)).willReturn(applicationEntity); given(candidateRepository.findOne(CANDIDATE_ID)).willReturn(candidateEntity); given(positionRepository.findOne(POSITION_ID)).willReturn(positionEntity); given(channelRepository.findOne(CHANNEL_ID)).willReturn(channelEntity); given(applicationsRepository.save(applicationEntity)).willReturn(this.applicationEntity); Long result = applicationsService.saveApplicaton(applicationDTO,stateDTO); assertNotNull(result); assertEquals(APPLICATION_ID, result); <START> then(statesService).should().saveState(stateDTO,APPLICATION_ID); <END> }</code><technical_language>check invocation of mocks for this test</technical_language>

Target:
public void saveApplicationShouldSaveAProperApplicationDTOAndStateDTO() { final StateDTO stateDTO = StateDTO.builder().channel(new ChannelDTO(8L,null)).candidateId(1L).position(new PositionDTO(1L,null)).description("sss").stateType("newstate").stateIndex(0).build(); given(modelMapper.map(applicationDTO, ApplicationEntity.class)).willReturn(applicationEntity); given(candidateRepository.findOne(CANDIDATE_ID)).willReturn(candidateEntity); given(positionRepository.findOne(POSITION_ID)).willReturn(positionEntity); given(channelRepository.findOne(CHANNEL_ID)).willReturn(channelEntity); given(applicationsRepository.save(applicationEntity)).willReturn(this.applicationEntity); Long result = applicationsService.saveApplicaton(applicationDTO,stateDTO); assertNotNull(result); assertEquals(APPLICATION_ID, result); then(statesService).should().saveState(stateDTO,APPLICATION_ID); then(modelMapper).should().map(applicationDTO, ApplicationEntity.class); then(candidateRepository).should().findOne(CANDIDATE_ID); then(positionRepository).should().findOne(POSITION_ID); then(channelRepository).should().findOne(CHANNEL_ID); then(applicationsRepository).should().save(applicationEntity); }
Source:
<code>private void syncAccounts() { OpacClient app = (OpacClient) getApplication(); AccountDataSource data = new AccountDataSource(this); data.open(); List<Account> accounts = data.getAccountsWithPassword(); for (Account account : accounts) { if (BuildConfig.DEBUG) Log.i(NAME, "Loading data for Account " + account.toString()); try { Library library = app.getLibrary(account.getLibrary()); if (!library.isAccountSupported()) continue; OpacApi api = app.getNewApi(library); AccountData res = api.account(account); if (res == null) continue; data.storeCachedAccountData(account, res); <START> data.close(); <END> new ReminderHelper(app).generateAlarms(); } catch (JSONException | IOException | OpacApi.OpacErrorException e) { data.close(); e.printStackTrace(); } } }</code><technical_language>data.close account data.open once. Do I miss this fail more account? Also, DataSource open network operations prevent concurrency issues. Therefore, close line 76 open line 87</technical_language>

Target:
private void syncAccounts() { OpacClient app = (OpacClient) getApplication(); AccountDataSource data = new AccountDataSource(this); data.open(); List<Account> accounts = data.getAccountsWithPassword(); data.close(); for (Account account : accounts) { if (BuildConfig.DEBUG) Log.i(NAME, "Loading data for Account " + account.toString()); try { Library library = app.getLibrary(account.getLibrary()); if (!library.isAccountSupported()) continue; OpacApi api = app.getNewApi(library); AccountData res = api.account(account); if (res == null) continue; data.open(); data.storeCachedAccountData(account, res); data.close(); new ReminderHelper(app).generateAlarms(); } catch (JSONException | IOException | OpacApi.OpacErrorException e) { data.close(); e.printStackTrace(); failed = true; } } }
Source:
<code>public void filter(final MethodNode methodNode, final IFilterContext context, final IFilterOutput output) { if ((methodNode.access & Opcodes.ACC_SYNTHETIC) == 0) { return; } if (methodNode.name.startsWith("lambda$")) { return; } if (KotlinGeneratedFilter.isKotlinClass(context)) { if (KotlinDefaultArgumentsFilter .isDefaultArgumentsMethodName(methodNode.name)) { return; } <START> final Type methodType = Type.getMethodType(methodNode.desc); <END> final int lastArgument = methodType.getArgumentTypes().length - 1; if (lastArgument >= 0 && "kotlin.coroutines.Continuation" .equals(methodType.getArgumentTypes()[lastArgument] .getClassName())) { return; } } output.ignore(methodNode.instructions.getFirst(), methodNode.instructions.getLast()); }</code><technical_language>@Godin Move this code block a static method in KotlinCoroutinesFilter</technical_language>

Target:
public void filter(final MethodNode methodNode, final IFilterContext context, final IFilterOutput output) { if ((methodNode.access & Opcodes.ACC_SYNTHETIC) == 0) { return; } if (methodNode.name.startsWith("lambda$")) { return; } if (KotlinGeneratedFilter.isKotlinClass(context)) { if (KotlinDefaultArgumentsFilter .isDefaultArgumentsMethodName(methodNode.name)) { return; } if (KotlinCoroutineFilter.isLastArgumentContinuation(methodNode)) { return; } } output.ignore(methodNode.instructions.getFirst(), methodNode.instructions.getLast()); }