auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void write(final Kryo kryo, final Output output, final Cipher object) { if (object.getProvider() != null && !"BC".equals(object.getProvider().getName())) { String msg = String.format("Serialization is only " + "supported for ciphers from the BouncyCastle provider. " + "Actual provider: %s", object.getProvider().getName()); throw new UnsupportedOperationException(msg); } final Object cryptoPerm = readField(cryptoPermField, object); kryo.writeObjectOrNull(output, cryptoPerm, cryptoAllPermissionClass); kryo.writeClassAndObject(output, readField(exmechField, object)); kryo.writeClassAndObject(output, readField(firstServiceField, object)); kryo.writeClassAndObject(output, readField(firstSpiField, object)); output.writeBoolean((Boolean)readField(initializedField, object)); kryo.writeClassAndObject(output, readField(lockField, object)); final int opmode = (int)readField(opmodeField, object); output.writeInt(opmode, true); Provider provider = (Provider)readField(providerField, object); output.writeString(provider.getName()); kryo.writeClassAndObject(output, readField(serviceIteratorField, object)); final Object spi = readField(spiField, object); kryo.writeClassAndObject(output, spi); output.writeString((String)readField(transformationField, object)); kryo.writeClassAndObject(output, readField(transformsField, object)); output.flush(); }

Target:
public void write(final Kryo kryo, final Output output, final Cipher object) { if (object.getProvider() != null && !BouncyCastleProvider.PROVIDER_NAME .equals(object.getProvider().getName())) { String msg = String.format("Serialization is only " + "supported for ciphers from the BouncyCastle provider. " + "Actual provider: %s", object.getProvider().getName()); throw new UnsupportedOperationException(msg); } final Object cryptoPerm = readField(cryptoPermField, object); kryo.writeObjectOrNull(output, cryptoPerm, cryptoAllPermissionClass); kryo.writeClassAndObject(output, readField(exmechField, object)); kryo.writeClassAndObject(output, readField(firstServiceField, object)); kryo.writeClassAndObject(output, readField(firstSpiField, object)); output.writeBoolean((Boolean)readField(initializedField, object)); kryo.writeClassAndObject(output, readField(lockField, object)); final int opmode = (int)readField(opmodeField, object); output.writeInt(opmode, true); Provider provider = (Provider)readField(providerField, object); output.writeString(provider.getName()); kryo.writeClassAndObject(output, readField(serviceIteratorField, object)); final Object spi = readField(spiField, object); kryo.writeClassAndObject(output, spi); output.writeString((String)readField(transformationField, object)); kryo.writeClassAndObject(output, readField(transformsField, object)); output.flush(); }
Source:
public void cancel(InterpreterContext context) { SparkInterpreter sparkInterpreter = getSparkInterpreter(); sparkInterpreter.cancel(context); try { interrupt(); } catch (IOException e) { e.printStackTrace(); } }

Target:
public void cancel(InterpreterContext context) { SparkInterpreter sparkInterpreter = getSparkInterpreter(); sparkInterpreter.cancel(context); try { interrupt(); } catch (IOException e) { logger.error("Error", e); } }
Source:
public void setOAuthHeader(MessageContext messageContext) throws OAuthException { String token; try { token = TokenCache.getInstance().getToken(id, new Callable<String>() { @Override public String call() throws OAuthException, IOException { return OAuthClient.generateToken(tokenApiUrl, buildTokenRequestPayload(), getEncodedCredentials()); } }); } catch (ExecutionException e) { throw new OAuthException(e); } setAuthorizationHeader(messageContext, token); }

Target:
public void setOAuthHeader(MessageContext messageContext) throws OAuthException { setAuthorizationHeader(messageContext, getToken()); }
Source:
public boolean getNext(EtlKey key, BytesWritable payload, BytesWritable pKey) throws IOException { if (hasNext()) { MessageAndOffset msgAndOffset = messageIter.next(); Message message = msgAndOffset.message(); ByteBuffer buf = message.payload(); int origSize = buf.remaining(); byte[] bytes = new byte[origSize]; buf.get(bytes, buf.position(), origSize); payload.set(bytes, 0, origSize); buf = message.key(); if (buf != null) { origSize = buf.remaining(); bytes = new byte[origSize]; buf.get(bytes, buf.position(), origSize); pKey.set(bytes, 0, origSize); } else { pKey.setSize(0); } key.clear(); key.set(kafkaRequest.getTopic(), kafkaRequest.getLeaderId(), kafkaRequest.getPartition(), currentOffset, msgAndOffset.offset() + 1, message.checksum()); key.setMessageSize(msgAndOffset.message().size()); currentOffset = msgAndOffset.offset() + 1; currentCount++; return true; } else { return false; } }

Target:
public boolean getNext(EtlKey key, BytesWritable payload, BytesWritable pKey) throws IOException { if (hasNext()) { MessageAndOffset msgAndOffset = messageIter.next(); Message message = msgAndOffset.message(); ByteBuffer buf = message.payload(); int origSize = buf.remaining(); byte[] bytes = new byte[origSize]; buf.get(bytes, buf.position(), origSize); payload.set(bytes, 0, origSize); buf = message.key(); if (buf != null) { origSize = buf.remaining(); bytes = new byte[origSize]; buf.get(bytes, buf.position(), origSize); pKey.set(bytes, 0, origSize); } else { log.warn("Received message with null message.key(): " + msgAndOffset); pKey.setSize(0); } key.clear(); key.set(kafkaRequest.getTopic(), kafkaRequest.getLeaderId(), kafkaRequest.getPartition(), currentOffset, msgAndOffset.offset() + 1, message.checksum()); key.setMessageSize(msgAndOffset.message().size()); currentOffset = msgAndOffset.offset() + 1; currentCount++; return true; } else { return false; } }
Source:
private void setDate(Date newDate) { Calendar calendar = Calendar.getInstance(); calendar.setTime(newDate); this.ms = calendar.get(Calendar.MILLISECOND); this.zone_offset = calendar.get(Calendar.ZONE_OFFSET); this.dst_offset = calendar.get(Calendar.DST_OFFSET); this.date.setDate(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH)); this.date.setTime(calendar.get(Calendar.HOUR_OF_DAY), calendar.get(Calendar.MINUTE), calendar.get(Calendar.SECOND)); }

Target:
private void setDate(Date newDate) { if (newDate != null) { Calendar calendar = Calendar.getInstance(); calendar.setTime(newDate); this.ms = calendar.get(Calendar.MILLISECOND); this.zoneOffset = calendar.get(Calendar.ZONE_OFFSET); this.dstOffset = calendar.get(Calendar.DST_OFFSET); this.date.setDate(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH)); this.date.setTime(calendar.get(Calendar.HOUR_OF_DAY), calendar.get(Calendar.MINUTE), calendar.get(Calendar.SECOND)); } }
Source:
public static Long timeToLong(String value) { Pattern timeValuePattern = Pattern.compile("\\d+"); Pattern durationPattern = Pattern.compile("\\D+"); Matcher timeMatcher = timeValuePattern.matcher(value); Matcher durationMatcher = durationPattern.matcher(value); int timeValue; TimePeriod.Duration duration; if (timeMatcher.find() && durationMatcher.find()) { duration = normalizeDuration(durationMatcher.group(0).trim()); timeValue = Integer.parseInt(timeMatcher.group(0)); try { switch (duration) { case SECONDS: return Expression.Time.sec(timeValue).value(); case MINUTES: return Expression.Time.minute(timeValue).value(); case HOURS: return Expression.Time.hour(timeValue).value(); case DAYS: return Expression.Time.day(timeValue).value(); case YEARS: return Expression.Time.year(timeValue).value(); default: return Expression.Time.month(timeValue).value(); } } catch (NoSuchDurationException e) { throw new NoSuchDurationException("Duration" + timeValue + "does not exists", e); } } else { throw new NoSuchDurationException("Provided retention parameter cannot be identified. retention " + "period: " + value + "."); } }

Target:
public static Long timeToLong(String value) { Pattern timeValuePattern = Pattern.compile("\\d+"); Pattern durationPattern = Pattern.compile("\\D+"); Matcher timeMatcher = timeValuePattern.matcher(value); Matcher durationMatcher = durationPattern.matcher(value); int timeValue; TimePeriod.Duration duration; if (timeMatcher.find() && durationMatcher.find()) { duration = normalizeDuration(durationMatcher.group(0).trim()); timeValue = Integer.parseInt(timeMatcher.group(0)); switch (duration) { case SECONDS: return Expression.Time.sec(timeValue).value(); case MINUTES: return Expression.Time.minute(timeValue).value(); case HOURS: return Expression.Time.hour(timeValue).value(); case DAYS: return Expression.Time.day(timeValue).value(); case YEARS: return Expression.Time.year(timeValue).value(); default: return Expression.Time.month(timeValue).value(); } } else { throw new SiddhiAppValidationException("Provided retention parameter cannot be identified. retention " + "period: " + value + "."); } }
Source:
public Query visit(LikeExpr likeExpr) { PropertyValueExpr propertyValueExpr = (PropertyValueExpr) likeExpr.getChild(); String[] propertyPath = propertyValueExpr.getPropertyPath(); ensureNotAnalyzed(propertyPath); String lucenePattern = likeExpr.getPattern() .replace(LUCENE_MULTIPLE_CHARACTERS_WILDCARD, "\\" + LUCENE_MULTIPLE_CHARACTERS_WILDCARD) .replace(LUCENE_SINGLE_CHARACTER_WILDCARD, "\\" + LUCENE_SINGLE_CHARACTER_WILDCARD) .replace("%", LUCENE_MULTIPLE_CHARACTERS_WILDCARD) .replace("_", LUCENE_SINGLE_CHARACTER_WILDCARD); return applyFieldBridge(propertyPath, queryBuilder.keyword().wildcard().onField(StringHelper.join(propertyPath))) .matching(lucenePattern).createQuery(); }

Target:
public Query visit(LikeExpr likeExpr) { PropertyValueExpr propertyValueExpr = (PropertyValueExpr) likeExpr.getChild(); String[] propertyPath = propertyValueExpr.getPropertyPath(); ensureNotAnalyzed(propertyPath); StringBuilder lucenePattern = new StringBuilder(likeExpr.getPattern()); for (int i = 0; i < lucenePattern.length(); i++) { switch (lucenePattern.charAt(i)) { case LUCENE_MULTIPLE_CHARACTERS_WILDCARD: case LUCENE_SINGLE_CHARACTER_WILDCARD: lucenePattern.insert(i, '\\'); i++; break; case '%': lucenePattern.setCharAt(i, LUCENE_MULTIPLE_CHARACTERS_WILDCARD); break; case '_': lucenePattern.setCharAt(i, LUCENE_SINGLE_CHARACTER_WILDCARD); break; } } return applyFieldBridge(propertyPath, queryBuilder.keyword().wildcard().onField(StringHelper.join(propertyPath))) .matching(lucenePattern.toString()).createQuery(); }
Source:
public Optional<String> getCommitTemplateContent() { if (commitTemplatePath != null) { File commitTemplateFile = new File(commitTemplatePath); try { return Optional.ofNullable( RawParseUtils.decode(IO.readFully(commitTemplateFile))); } catch (IOException e) { LOG.error(e.getMessage(), e); } } return Optional.empty(); }

Target:
public String getCommitTemplateContent() throws FileNotFoundException, IOException { if (commitTemplatePath != null) { File commitTemplateFile = new File( resolveHomePath(commitTemplatePath)); return RawParseUtils.decode(commitMessageEncoding, IO.readFully(commitTemplateFile)); } return null; }
Source:
public void testRegularAndRuntimeParametersAreEqualWithScan() { CloudBigtableScanConfiguration withRegularParameters = config.toBuilder().withConfiguration("somekey", "somevalue").build(); CloudBigtableScanConfiguration withRuntimeParameters = new CloudBigtableScanConfiguration.Builder() .withTableId(StaticValueProvider.of(TABLE)) .withProjectId(StaticValueProvider.of(PROJECT)) .withInstanceId(StaticValueProvider.of(INSTANCE)) .withScan(new Scan(START_ROW, STOP_ROW)) .withConfiguration("somekey", StaticValueProvider.of("somevalue")) .build(); Assert.assertNotSame(withRegularParameters, withRuntimeParameters); Assert.assertEquals(withRegularParameters, withRuntimeParameters); ReadRowsRequest request = withRegularParameters.getRequest(); withRegularParameters = withRegularParameters.toBuilder().withRequest(request).build(); withRuntimeParameters = withRuntimeParameters.toBuilder().withRequest(StaticValueProvider.of(request)).build(); Assert.assertNotSame(withRegularParameters, withRuntimeParameters); Assert.assertEquals(withRegularParameters, withRuntimeParameters); }

Target:
public void testRegularAndRuntimeParametersAreEqualWithScan() { CloudBigtableScanConfiguration withRegularParameters = config.toBuilder().withConfiguration("somekey", "somevalue").build(); CloudBigtableScanConfiguration withRuntimeParameters = new CloudBigtableScanConfiguration.Builder() .withTableId(StaticValueProvider.of(TABLE)) .withProjectId(StaticValueProvider.of(PROJECT)) .withInstanceId(StaticValueProvider.of(INSTANCE)) .withScan(new Scan(START_ROW, STOP_ROW)) .withConfiguration("somekey", StaticValueProvider.of("somevalue")) .build(); Assert.assertEquals(withRegularParameters, withRuntimeParameters); ReadRowsRequest request = withRegularParameters.getRequest(); withRegularParameters = withRegularParameters.toBuilder().withRequest(request).build(); withRuntimeParameters = withRuntimeParameters.toBuilder().withRequest(StaticValueProvider.of(request)).build(); Assert.assertEquals(withRegularParameters, withRuntimeParameters); }
Source:
public void testHeaderWithInvalidRegexp() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(RegexpHeaderCheck.class); checkConfig.addAttribute("headerFile", getPath("regexp.invalid.header")); final String[] expected = CommonUtils.EMPTY_STRING_ARRAY; String message = ""; try { verify(checkConfig, getPath("InputRegexpHeader5.java"), expected); } catch (IllegalArgumentException ex) { message = ex.getMessage(); } assertEquals("line 1 in header specification is not a regular expression", message); }

Target:
public void testHeaderWithInvalidRegexp() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(RegexpHeaderCheck.class); checkConfig.addAttribute("headerFile", getPath("regexp.invalid.header")); final String[] expected = CommonUtils.EMPTY_STRING_ARRAY; try { verify(checkConfig, getPath("InputRegexpHeader5.java"), expected); fail("IllegalArgumentException is expected"); } catch (IllegalArgumentException ex) { assertEquals("line 1 in header specification is not a regular expression", ex.getMessage()); } }
Source:
public static IRegistrationFieldView getInstance(LayoutInflater inflater, RegistrationFormField field) { RegistrationFieldType fieldType = field.getFieldType(); if (fieldType.equals(RegistrationFieldType.EMAIL)) { View view = inflater.inflate(R.layout.view_register_edit_text, null); return new RegistrationEmailView(field, view); } else if (fieldType.equals(RegistrationFieldType.CONFIRM_EMAIL)) { View view = inflater.inflate(R.layout.view_register_edit_text, null); return new RegistrationEmailView(field, view); } else if (fieldType.equals(RegistrationFieldType.PASSWORD)) { View view = inflater.inflate(R.layout.view_register_edit_text, null); return new RegistrationPasswordView(field, view); } else if (fieldType.equals(RegistrationFieldType.TEXT)) { View view = inflater.inflate(R.layout.view_register_edit_text, null); return new RegistrationTextView(field, view); } else if (fieldType.equals(RegistrationFieldType.TEXTAREA)) { View view = inflater.inflate(R.layout.view_register_edit_text, null); return new RegistrationTextAreaView(field, view); } else if (fieldType.equals(RegistrationFieldType.MULTI)) { View view = inflater.inflate(R.layout.view_register_spinner, null); return new RegistrationSelectView(field, view); } else if (fieldType.equals(RegistrationFieldType.PLAINTEXT)) { return null; } else { logger.error(new Exception( String.format("Unknown field type found for field named: %s in RegistrationDescription, skipping it!", field.getName()) )); return null; } }

Target:
public static IRegistrationFieldView getInstance(LayoutInflater inflater, RegistrationFormField field) { RegistrationFieldType fieldType = field.getFieldType(); if (fieldType.equals(RegistrationFieldType.EMAIL)) { View view = inflater.inflate(R.layout.view_register_edit_text, null); return new RegistrationEmailView(field, view); } else if (fieldType.equals(RegistrationFieldType.PASSWORD)) { View view = inflater.inflate(R.layout.view_register_edit_text, null); return new RegistrationPasswordView(field, view); } else if (fieldType.equals(RegistrationFieldType.TEXT)) { View view = inflater.inflate(R.layout.view_register_edit_text, null); return new RegistrationTextView(field, view); } else if (fieldType.equals(RegistrationFieldType.TEXTAREA)) { View view = inflater.inflate(R.layout.view_register_edit_text, null); return new RegistrationTextAreaView(field, view); } else if (fieldType.equals(RegistrationFieldType.MULTI)) { View view = inflater.inflate(R.layout.view_register_spinner, null); return new RegistrationSelectView(field, view); } else if (fieldType.equals(RegistrationFieldType.PLAINTEXT)) { return null; } else { logger.error(new Exception( String.format("Unknown field type found for field named: %s in RegistrationDescription, skipping it!", field.getName()) )); return null; } }
Source:
private static String getSchemaContent( final Util.PropertyList connectInfo, final String catalogUrl) { String dynProcName = connectInfo.get( RolapConnectionProperties.DynamicSchemaProcessor.name() ); String catalogStr = connectInfo.get( RolapConnectionProperties.CatalogContent.name() ); if (Util.isEmpty(catalogStr)) { if (Util.isEmpty(catalogUrl)) { throw MondrianResource.instance().ConnectStringMandatoryProperties.ex( RolapConnectionProperties.Catalog.name(), RolapConnectionProperties.CatalogContent.name()); } if (!Util.isEmpty(dynProcName)) { catalogStr = processDynamicSchema( dynProcName, catalogUrl, null, connectInfo); } if (Util.isEmpty(catalogStr)) { try { catalogStr = Util.readVirtualFileAsString(catalogUrl); } catch (IOException e) { throw Util.newError( e,"loading schema from url " + catalogUrl); } } } else { if (!Util.isEmpty(dynProcName)) { catalogStr = catalogStr = processDynamicSchema( dynProcName, null, catalogStr, connectInfo ); } } return catalogStr; }

Target:
private static String getSchemaContent( final Util.PropertyList connectInfo, final String catalogUrl) { String dynProcName = connectInfo.get( RolapConnectionProperties.DynamicSchemaProcessor.name() ); String catalogStr = connectInfo.get( RolapConnectionProperties.CatalogContent.name() ); if (Util.isEmpty(catalogStr)) { if (Util.isEmpty(catalogUrl)) { throw MondrianResource.instance().ConnectStringMandatoryProperties.ex( RolapConnectionProperties.Catalog.name(), RolapConnectionProperties.CatalogContent.name()); } if (!Util.isEmpty(dynProcName)) { catalogStr = processDynamicSchema( dynProcName, catalogUrl, null, connectInfo); } if (Util.isEmpty(catalogStr)) { try { catalogStr = Util.readVirtualFileAsString(catalogUrl); } catch (IOException e) { throw Util.newError( e,"loading schema from url " + catalogUrl); } } } else { if (!Util.isEmpty(dynProcName)) { catalogStr = processDynamicSchema( dynProcName, null, catalogStr, connectInfo ); } } return catalogStr; }
Source:
public void run(PortBindings portBindings, Configuration configuration, Map<String, String> parameters) throws Exception { Path inputRecordsPath = portBindings.getInput().get(PORT_INPUT); String propertiesPathsCSV = parameters.get(PROPERTIES_CSV); Preconditions.checkArgument(StringUtils.isNotBlank(propertiesPathsCSV), "no '%s' property value provided, field requirements were not specified!", PROPERTIES_CSV); String[] recordsExpectationPropertiesLocations = StringUtils.split(propertiesPathsCSV, ','); FileSystem fs = FileSystem.get(configuration); if (!fs.exists(inputRecordsPath)) { throw new RuntimeException(inputRecordsPath + " hdfs location does not exist!"); } try (CloseableIterator<SpecificRecord> recordsIterator = DataStore.getReader(new FileSystemPath(fs, inputRecordsPath))) { int recordsCount = 0; while (recordsIterator.hasNext()) { SpecificRecord record = recordsIterator.next(); recordsCount++; if (recordsCount > recordsExpectationPropertiesLocations.length) { throw new RuntimeException("got more records than expected: " + "unable to verify record no " + recordsCount + ", no field specification provided! Record contents: " + JsonUtils.toPrettyJSON(record.toString())); } else { validateRecord(record, readProperties(recordsExpectationPropertiesLocations[recordsCount - 1])); } } if (recordsCount < recordsExpectationPropertiesLocations.length) { throw new RuntimeException( "records count mismatch: " + "got: " + recordsCount + " expected: " + recordsExpectationPropertiesLocations.length); } } }

Target:
public void run(PortBindings portBindings, Configuration configuration, Map<String, String> parameters) throws Exception { Path inputRecordsPath = portBindings.getInput().get(PORT_INPUT); String expectationsPathsCSV = parameters.get(EXPECTATIONS_CSV); Preconditions.checkArgument(StringUtils.isNotBlank(expectationsPathsCSV), "no '%s' property value provided, field requirements were not specified!", EXPECTATIONS_CSV); String[] recordExpectationsLocations = StringUtils.split(expectationsPathsCSV, ','); FileSystem fs = FileSystem.get(configuration); if (!fs.exists(inputRecordsPath)) { throw new RuntimeException(inputRecordsPath + " hdfs location does not exist!"); } try (CloseableIterator<SpecificRecord> recordIterator = DataStore.getReader(new FileSystemPath(fs, inputRecordsPath))) { int recordCount = 0; while (recordIterator.hasNext()) { SpecificRecord record = recordIterator.next(); recordCount++; if (recordCount > recordExpectationsLocations.length) { throw new RuntimeException("got more records than expected: " + "unable to verify record no " + recordCount + ", no field specification provided! Record contents: " + JsonUtils.toPrettyJSON(record.toString())); } else { validateRecord(record, readExpectedValues(recordExpectationsLocations[recordCount - 1])); } } if (recordCount < recordExpectationsLocations.length) { throw new RuntimeException( "records count mismatch: " + "got: " + recordCount + " expected: " + recordExpectationsLocations.length); } } }
Source:
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setRetainInstance(true); setStyle(DialogFragment.STYLE_NORMAL, android.R.style.Theme_Material_Light_Dialog); }

Target:
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setStyle(DialogFragment.STYLE_NORMAL, android.R.style.Theme_Material_Light_Dialog); }
Source:
static CodeCoverageMetrics convertCobertura(CoverageResult result) { if (result == null) { return null; } float packagesCoverage = getCoveragePercentage(result, CoverageMetric.PACKAGES); float filesCoverage = getCoveragePercentage(result, CoverageMetric.FILES); float classesCoverage = getCoveragePercentage(result, CoverageMetric.CLASSES); float methodCoverage = getCoveragePercentage(result, CoverageMetric.METHOD); float lineCoverage = getCoveragePercentage(result, CoverageMetric.LINE); float conditionalCoverage = getCoveragePercentage(result, CoverageMetric.CONDITIONAL); float linesCovered = result.getCoverage(CoverageMetric.LINE).numerator; float linesTested = result.getCoverage(CoverageMetric.LINE).denominator; return new CodeCoverageMetrics( packagesCoverage, filesCoverage, classesCoverage, methodCoverage, lineCoverage, conditionalCoverage, linesCovered, linesTested ); }

Target:
static CodeCoverageMetrics convertCobertura(CoverageResult result) { if (result == null) { return null; } float packagesCoverage = getCoveragePercentage(result, CoverageMetric.PACKAGES); float filesCoverage = getCoveragePercentage(result, CoverageMetric.FILES); float classesCoverage = getCoveragePercentage(result, CoverageMetric.CLASSES); float methodCoverage = getCoveragePercentage(result, CoverageMetric.METHOD); float lineCoverage = getCoveragePercentage(result, CoverageMetric.LINE); float conditionalCoverage = getCoveragePercentage(result, CoverageMetric.CONDITIONAL); long linesCovered = (long) result.getCoverage(CoverageMetric.LINE).numerator; long linesTested = (long) result.getCoverage(CoverageMetric.LINE).denominator; return new CodeCoverageMetrics( packagesCoverage, filesCoverage, classesCoverage, methodCoverage, lineCoverage, conditionalCoverage, linesCovered, linesTested ); }
Source:
public Optional<Either<L, R>> subSequence(Either<L, R> seg, int start, int end) { return seg.unify(ll -> seg.unify(l -> lOps.subSequence(l, start, end).map(Either::left), e -> Optional.empty()), rr -> seg.unify(e -> Optional.empty(), r -> rOps.subSequence(r, start, end).map(Either::right))); }

Target:
public Either<L, R> subSequence(Either<L, R> seg, int start, int end) { return seg.map(l -> lOps.subSequence(l, start, end), r -> rOps.subSequence(r, start, end)); }
Source:
public void testFileNullException() throws IOException { String fakeData = "SomeRandomFakeData"; ByteArrayInputStream is = new ByteArrayInputStream(fakeData.getBytes("UTF-8")); boolean success = false; encoder.encode(is, file, new Options()); success = encoder.encode(is, null, new Options()); assertTrue(success); }

Target:
public void testFileNullException() throws IOException { String fakeData = "SomeRandomFakeData"; file.createNewFile(); final ByteArrayInputStream is = new ByteArrayInputStream(fakeData.getBytes("UTF-8")); final boolean[] success = {false}; class EncodeNPETest implements ThrowingRunnable { @Override public void run() throws Throwable { success[0] = encoder.encode(is, null, new Options()); } } assertThrows(NullPointerException.class, new EncodeNPETest()); }
Source:
public Family createFamily(User creator) { return create(creator.getProfileDocument()); }

Target:
public Family createFamily(User creator) { return create(creator != null ? creator.getProfileDocument() : null); }
Source:
private Request prepareMetadataQuery(String query) { HttpUriBuilder uriBuilder = uriBuilderFrom(druidBroker).replacePath(SQL_ENDPOINT); return setContentTypeHeaders(preparePost()) .setUri(uriBuilder.build()) .setBodyGenerator(createStaticBodyGenerator(createRequestBody(query, DruidResultFormat.OBJECT, false))) .build(); }

Target:
private Request prepareMetadataQuery(String query) { HttpUriBuilder uriBuilder = uriBuilderFrom(druidBroker).replacePath(SQL_ENDPOINT); return setContentTypeHeaders(preparePost()) .setUri(uriBuilder.build()) .setBodyGenerator(createStaticBodyGenerator(createRequestBody(query, OBJECT, false))) .build(); }
Source:
public Analyzer open(Assembler a, Resource root, Mode mode) { if (root.hasProperty(TextVocab.pTokenizer)) { Resource tokenizerResource = (Resource) root.getProperty(TextVocab.pTokenizer).getObject(); String tokenizer = tokenizerResource.getLocalName(); List<String> filters; if (root.hasProperty(TextVocab.pFilters)) { Resource filtersResource = (Resource) root.getProperty(TextVocab.pFilters).getObject(); filters = toFilterList(filtersResource); } else { filters = new ArrayList<>(); } return new ConfigurableAnalyzer(TextIndexLucene.VER, tokenizer, filters); } else { throw new TextIndexException("text:tokenizer setting is required by ConfigurableAnalyzer"); } }

Target:
public Analyzer open(Assembler a, Resource root, Mode mode) { if (root.hasProperty(TextVocab.pTokenizer)) { Resource tokenizerResource = root.getPropertyResourceValue(TextVocab.pTokenizer); String tokenizer = tokenizerResource.getLocalName(); List<String> filters; if (root.hasProperty(TextVocab.pFilters)) { Resource filtersResource = root.getPropertyResourceValue(TextVocab.pFilters); filters = toFilterList(filtersResource); } else { filters = new ArrayList<>(); } return new ConfigurableAnalyzer(TextIndexLucene.VER, tokenizer, filters); } else { throw new TextIndexException("text:tokenizer setting is required by ConfigurableAnalyzer"); } }
Source:
void testSerializeAndDeserializeList() { objectMapper.activateDefaultTyping( objectMapper.getPolymorphicTypeValidator(), ObjectMapper.DefaultTyping.OBJECT_AND_NON_CONCRETE ); SimpleSerializableType toSerialize = new SimpleSerializableType("first", time, new SimpleSerializableType("nested")); SerializedObject<String> serialized = testSubject.serialize(singletonList(toSerialize), String.class); List<SimpleSerializableType> actual = testSubject.deserialize(serialized); assertEquals(1, actual.size()); assertEquals(toSerialize.getValue(), actual.get(0).getValue()); assertEquals(toSerialize.getNested().getValue(), actual.get(0).getNested().getValue()); }

Target:
void testSerializeAndDeserializeList() { objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_CONCRETE_AND_ARRAYS); SimpleSerializableType toSerialize = new SimpleSerializableType("first", time, new SimpleSerializableType("nested")); SerializedObject<String> serialized = testSubject.serialize(singletonList(toSerialize), String.class); List<SimpleSerializableType> actual = testSubject.deserialize(serialized); assertEquals(1, actual.size()); assertEquals(toSerialize.getValue(), actual.get(0).getValue()); assertEquals(toSerialize.getNested().getValue(), actual.get(0).getNested().getValue()); }
Source:
public <R> Try<R> of(CheckedFunction1<? super T1, ? extends R> f) { return Try.of(() -> { final R result; try (T1 t1 = t1Supplier.get()) { result = f.apply(t1); } return result; }); }

Target:
public <R> Try<R> of(CheckedFunction1<? super T1, ? extends R> f) { return Try.of(() -> { try (T1 t1 = t1Supplier.get()) { return f.apply(t1); } }); }
Source:
protected void reorderNode( String workspaceName, NodeKey key, Name primaryType, Set<Name> mixinTypes, NodeKey parent, Path newPath, Path oldPath, Path reorderedBeforePath ) { String nodeKey = nodeKey(key); index().remove(nodeKey, valueOf(oldPath)); index().add(nodeKey, valueOf(newPath)); }

Target:
protected void reorderNode( String workspaceName, NodeKey key, Name primaryType, Set<Name> mixinTypes, NodeKey parent, Path newPath, Path oldPath, Path reorderedBeforePath ) { if (newPath.getLastSegment().hasIndex() || oldPath.getLastSegment().hasIndex()) { } }
Source:
public String getLiteral(Geometry geometry) { String str = Wkt.newEncoder(Wkt.Dialect.POSTGIS_EWKT_1).encode(geometry); if (geometry.getSRID() > -1) { return "geometry::STGeomFromText('" + str + "', " + geometry.getSRID() + ")"; } else { return "geometry::STGeomFromText('" + str + "', 4326)"; } }

Target:
public String getLiteral(Geometry geometry) { String str = Wkt.newEncoder(Wkt.Dialect.POSTGIS_EWKT_1).encode(geometry); if (geometry.getSRID() > -1) { return "geometry::STGeomFromText('" + str + "', " + geometry.getSRID() + ")"; } else { return "geometry::STGeomFromText('" + str + "', " + DEFAULT_SRID + ")"; } }
Source:
protected ConfigurationValidation validateConnectorConfiguration() { if (isFieldValueNotSet(testField)) { return ConfigurationValidation.notValid("testField canont be empty"); } return ConfigurationValidation.valid(); }

Target:
protected ConfigurationValidation validateConnectorConfiguration() { if (isFieldValueNotSet(testField)) { return ConfigurationValidation.notValid("testField cannot be empty"); } return ConfigurationValidation.valid(); }
Source:
private Metacard resultsMapper(Map map) { LOGGER.debug("Starting result processing..."); String title = safeGet(map, "title", String.class); String description = safeGet(map, "description", String.class); List<String> descriptors = safeGetList(map, "descriptors", String.class); if (anyNull(title, description, descriptors)) { LOGGER.debug("Invalid entry in results.json"); return null; } ResultTemplateMetacardImpl metacard = new ResultTemplateMetacardImpl(title, description); metacard.setResultDescriptors(new HashSet<>(descriptors)); return metacard; }

Target:
private Metacard resultsMapper(Map map) { String title = safeGet(map, Core.TITLE, String.class); String description = safeGet(map, Core.DESCRIPTION, String.class); List<String> descriptors = safeGetList(map, "descriptors", String.class); if (anyNull(title, description, descriptors)) { return null; } AttributeGroupMetacard metacard = new AttributeGroupMetacard(title, description); metacard.setGroupDescriptors(new HashSet<>(descriptors)); return metacard; }
Source:
public boolean evaluate(int content) { if (content == 1) { return true; } else { return false; } }

Target:
public boolean evaluate(int content) { return content == 1; }
Source:
public BitWorld() { dynamicBodies = new ArrayList<>(); pendingAdds = new ArrayList<>(); pendingRemoves = new ArrayList<>(); occupiedSpaces = new HashMap<>(); pendingResolutions = new HashMap<>(); contacts = new HashMap<>(); }

Target:
public BitWorld() { pendingAdds = new ArrayList<>(); pendingRemoves = new ArrayList<>(); occupiedSpaces = new HashMap<>(); pendingResolutions = new HashMap<>(); contacts = new HashMap<>(); }
Source:
public Response getChildrenByParentId(@PathParam("parentId") String parentId) { if (parentId == null) { String errorMessage = "The parameter of the parent ID is empty."; return Response.status(Response.Status.BAD_REQUEST).entity(errorMessage).build(); } List<DeviceOrganizationMetadataHolder> result; DeviceOrganizationProviderService dops = new DeviceOrganizationProviderServiceImpl(); try { result = dops.getChildrenByParentId(parentId); if (result == null) { String msg = "No children connected to device"; log.error(msg); return Response.status(Response.Status.NOT_FOUND).entity(msg).build(); } return Response.status(Response.Status.OK).entity(result).build(); } catch (DeviceOrganizationException e) { String msg = "Error occurred while retrieving children of device"; log.error(msg, e); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); } catch (InvalidConfigurationException e) { log.error("failed to add operation", e); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); } }

Target:
public Response getChildrenByParentId(@PathParam("parentId") String parentId) { if (parentId == null) { String errorMessage = "The parameter of the parent ID is empty."; return Response.status(Response.Status.BAD_REQUEST).entity(errorMessage).build(); } List<DeviceOrganizationMetadataHolder> result; DeviceOrganizationProviderService dops = new DeviceOrganizationProviderServiceImpl(); try { result = dops.getChildrenByParentId(parentId); if (result == null) { String msg = "No children connected to device"; if (log.isDebugEnabled()) { log.debug(msg); } return Response.status(Response.Status.NOT_FOUND).entity(msg).build(); } return Response.status(Response.Status.OK).entity(result).build(); } catch (DeviceOrganizationException e) { String msg = "Error occurred while retrieving children of device"; log.error(msg, e); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); } catch (InvalidConfigurationException e) { log.error("failed to add operation", e); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); } }
Source:
public void testProcessEvent() throws UnsupportedEncodingException, NoSuchAlgorithmException { final APIEvent event = new APIEvent(EventStrings.API_EVENT); event.setAPIId("123"); event.setAuthority("AAD"); event.setAuthorityType("AAD"); event.setExtendedExpiresOnSetting(true); event.setIdToken(AuthenticationContextTest.TEST_IDTOKEN); event.setLoginHint("pii@pii.com"); final Map<String, String> dispatchMap = new HashMap(); event.processEvent(dispatchMap); assertFalse(dispatchMap.isEmpty()); assertTrue(dispatchMap.containsKey(EventStrings.AUTHORITY_TYPE)); assertTrue(dispatchMap.containsKey(EventStrings.EXTENDED_EXPIRES_ON_SETTING)); assertFalse(dispatchMap.containsKey(EventStrings.API_ERROR_CODE)); assertFalse(dispatchMap.containsKey(EventStrings.API_ERROR_CODE)); final String email = dispatchMap.get(EventStrings.LOGIN_HINT); assertTrue(email.equals(StringExtensions.createHash("pii@pii.com"))); }

Target:
public void testProcessEvent() throws UnsupportedEncodingException, NoSuchAlgorithmException { final APIEvent event = new APIEvent(EventStrings.API_EVENT); event.setAPIId("123"); event.setAuthority("AAD"); event.setAuthorityType("AAD"); event.setExtendedExpiresOnSetting(true); event.setIdToken(AuthenticationContextTest.TEST_IDTOKEN); event.setLoginHint("pii@pii.com"); final Map<String, String> dispatchMap = new HashMap(); event.processEvent(dispatchMap); assertFalse(dispatchMap.isEmpty()); assertTrue(dispatchMap.containsKey(EventStrings.AUTHORITY_TYPE)); assertTrue(dispatchMap.containsKey(EventStrings.EXTENDED_EXPIRES_ON_SETTING)); assertFalse(dispatchMap.containsKey(EventStrings.API_ERROR_CODE)); assertTrue(dispatchMap.containsKey(EventStrings.TENANT_ID)); assertTrue(dispatchMap.containsKey(EventStrings.DEVICE_ID)); assertTrue(dispatchMap.containsKey(EventStrings.CLIENT_ID)); assertTrue(dispatchMap.containsKey(EventStrings.APPLICATION_VERSION)); assertTrue(dispatchMap.containsKey(EventStrings.USER_ID)); final String email = dispatchMap.get(EventStrings.LOGIN_HINT); assertTrue(email.equals(StringExtensions.createHash("pii@pii.com"))); }
Source:
public void shouldFailWhenCreatingExistingChildNameDocument() { try (CloseableCoreSession bobSession = CoreInstance.openCoreSession(coreSession.getRepositoryName(), "bob")) { createDocument(bobSession, folder, DOCUMENT_NAME); } try (CloseableCoreSession jamesSession = CoreInstance.openCoreSession(coreSession.getRepositoryName(), "james")) { createDocument(jamesSession, folder, DOCUMENT_NAME); fail("should throw a ConcurrentUpdateException"); } catch (ConcurrentUpdateException cue) { assertEquals(SC_CONFLICT, cue.getStatusCode()); String mongoDBName = Framework.getProperties().getProperty(MONGODB_DBNAME_PROPERTY); assertTrue( cue.getMessage() .contains(String.format( "E11000 duplicate key error collection: %s.test index: ecm:parentId_1_ecm:name_1 dup key: { : \"%s\", : \"%s\" }", mongoDBName, folder.getId(), DOCUMENT_NAME))); } }

Target:
public void shouldFailWhenCreatingExistingChildNameDocument() { try (CloseableCoreSession bobSession = CoreInstance.openCoreSession(coreSession.getRepositoryName(), "bob")) { createDocument(bobSession, folder, DOCUMENT_NAME); } try (CloseableCoreSession jamesSession = CoreInstance.openCoreSession(coreSession.getRepositoryName(), "james")) { createDocument(jamesSession, folder, DOCUMENT_NAME); fail("should throw a ConcurrentUpdateException"); } catch (ConcurrentUpdateException cue) { assertEquals(SC_CONFLICT, cue.getStatusCode()); String message = cue.getMessage(); assertTrue(message, message.contains("E11000 duplicate key error collection")); assertTrue(message, message.contains(DOCUMENT_NAME)); assertTrue(message, message.contains(folder.getId())); } }
Source:
public void schedulePeriodicBackgroundJob(int delay){ final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context); if(preferences.getBoolean(context.getResources().getString(R.string.preference_real_time_sync), false)) { Runnable runnable = new Runnable() { @Override public void run() { if (!isJobAlreadyScheduled(context)) { handleScheduledPeriodicDataSyncJob(); Log.e(getClass().getSimpleName(), "============Background task is scheduled============="); } else { Log.e(getClass().getSimpleName(), "There is already a background service running."); } } }; Handler handler = new Handler(); handler.postDelayed(runnable, delay); } }

Target:
public void schedulePeriodicBackgroundJob(int delay){ final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context); if(preferences.getBoolean(context.getResources().getString(R.string.preference_real_time_sync), false)) { Runnable runnable = new Runnable() { @Override public void run() { if (!isJobAlreadyScheduled(context)) { handleScheduledPeriodicDataSyncJob(); } } }; Handler handler = new Handler(); handler.postDelayed(runnable, delay); } }
Source:
private static VCFTextTransformer getTextTransformerForVCFVersion(final VCFHeaderVersion targetVersion) { return targetVersion.isAtLeastAsRecentAs(VCFHeaderVersion.VCF4_3) ? new VCFTextTransformer() : new VCFPassThruTextTransformer(); }

Target:
private VCFTextTransformer getTextTransformerForVCFVersion(final VCFHeaderVersion targetVersion) { return targetVersion != null && targetVersion.isAtLeastAsRecentAs(VCFHeaderVersion.VCF4_3) ? percentEncodingTextTransformer : passThruTextTransformer; }
Source:
public void setupContext() { super.setup(); String zone = api.getConfiguredZones().iterator().next(); quotaApi = api.getQuotaApi(zone); }

Target:
public void setupContext() { super.setup(); String zone = Iterables.getFirst(api.getConfiguredZones(), "nova"); quotaApi = api.getQuotaApi(zone); }
Source:
public Chunk getChunk(final long splitStart, final long splitEnd) { if (splitStart >= splitEnd) { throw new IllegalArgumentException(String.format("Split start (%s) must be less than end (%s)", splitStart, splitEnd)); } long lastVirtualOffset = virtualOffsets[virtualOffsets.length - 1]; long maxEnd = BlockCompressedFilePointerUtil.getBlockAddress(lastVirtualOffset); long actualSplitStart = Math.min(splitStart, maxEnd); long actualSplitEnd = Math.min(splitEnd, maxEnd); long virtualSplitStart = BlockCompressedFilePointerUtil.makeFilePointer(actualSplitStart); long virtualSplitEnd = BlockCompressedFilePointerUtil.makeFilePointer(actualSplitEnd); long virtualSplitStartAlignment = ceiling(virtualSplitStart); long virtualSplitEndAlignment = ceiling(virtualSplitEnd); if (virtualSplitStartAlignment == virtualSplitEndAlignment) { return null; } return new Chunk(virtualSplitStartAlignment, virtualSplitEndAlignment); }

Target:
public Chunk getChunk(final long splitStart, final long splitEnd) { if (splitStart >= splitEnd) { throw new IllegalArgumentException(String.format("Split start (%s) must be less than end (%s)", splitStart, splitEnd)); } final long lastVirtualOffset = virtualOffsets[virtualOffsets.length - 1]; final long maxEnd = BlockCompressedFilePointerUtil.getBlockAddress(lastVirtualOffset); final long actualSplitStart = Math.min(splitStart, maxEnd); final long actualSplitEnd = Math.min(splitEnd, maxEnd); final long virtualSplitStart = BlockCompressedFilePointerUtil.makeFilePointer(actualSplitStart); final long virtualSplitEnd = BlockCompressedFilePointerUtil.makeFilePointer(actualSplitEnd); final long virtualSplitStartAlignment = ceiling(virtualSplitStart); final long virtualSplitEndAlignment = ceiling(virtualSplitEnd); if (virtualSplitStartAlignment == virtualSplitEndAlignment) { return null; } return new Chunk(virtualSplitStartAlignment, virtualSplitEndAlignment); }
Source:
public void handleSetAlarmNotificationsResponse(final DeviceMessageMetadata deviceMessageMetadata, final ResponseMessageResultType deviceResult, final OsgpException exception) { LOGGER.info("handleSetAlarmNotificationsResponse for MessageType: {}", deviceMessageMetadata.getMessageType()); ResponseMessageResultType result = deviceResult; if (exception != null) { LOGGER.error("Set Alarm Notifications Response not ok. Unexpected Exception", exception); result = ResponseMessageResultType.NOT_OK; } this.webServiceResponseMessageSender.send(ResponseMessage.newResponseMessageBuilder() .withCorrelationUid(deviceMessageMetadata.getCorrelationUid()) .withOrganisationIdentification(deviceMessageMetadata.getOrganisationIdentification()) .withDeviceIdentification(deviceMessageMetadata.getDeviceIdentification()).withResult(result) .withOsgpException(exception).withMessagePriority(deviceMessageMetadata.getMessagePriority()).build(), deviceMessageMetadata.getMessageType()); }

Target:
public void handleSetAlarmNotificationsResponse(final DeviceMessageMetadata deviceMessageMetadata, final ResponseMessageResultType deviceResult, final OsgpException exception) { LOGGER.info("handleSetAlarmNotificationsResponse for MessageType: {}", deviceMessageMetadata.getMessageType()); ResponseMessageResultType result = deviceResult; if (exception != null) { LOGGER.error("Set Alarm Notifications Response not ok. Unexpected Exception", exception); result = ResponseMessageResultType.NOT_OK; } ResponseMessage responseMessage = ResponseMessage.newResponseMessageBuilder() .withCorrelationUid(deviceMessageMetadata.getCorrelationUid()) .withOrganisationIdentification(deviceMessageMetadata.getOrganisationIdentification()) .withDeviceIdentification(deviceMessageMetadata.getDeviceIdentification()).withResult(result) .withOsgpException(exception).withMessagePriority(deviceMessageMetadata.getMessagePriority()).build(); this.webServiceResponseMessageSender.send(responseMessage, deviceMessageMetadata.getMessageType()); }
Source:
public Response moveFileAnswers(@QueryParam("count") Integer count) { if (count == null || count < 0) { return Response.status(Status.BAD_REQUEST).build(); } EnvironmentUser user = environmentUserController.findEnvironmentUserByUserEntity(sessionController.getLoggedUserEntity()); if (user == null || user.getRole() == null || user.getRole().getArchetype() != EnvironmentRoleArchetype.ADMINISTRATOR) { return Response.status(Status.FORBIDDEN).build(); } int bytes = 0; int totalBytes = 0; int totalFiles = 0; Long currentId = fileAnswerUtils.getLastEntityId(); List<Long> answerIds = workspaceMaterialFileFieldAnswerDAO.listIdsByLargerAndLimit(currentId, count); for (Long answerId : answerIds) { try { WorkspaceMaterialFileFieldAnswer answer = workspaceMaterialFileFieldAnswerDAO.findById(answerId); if (answer != null) { bytes = fileAnswerUtils.relocateToFileSystem(answer); if (bytes > 0) { totalBytes += bytes; totalFiles++; } currentId = answerId; } } catch (IOException e) { logger.log(Level.SEVERE, String.format("Failed to relocate WorkspaceMaterialFileFieldAnswer %d", currentId), e); return Response.status(Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build(); } } fileAnswerUtils.setLastEntityId(currentId); return Response.ok(String.format("Moved %d files (%d bytes) with latest entity at %d", totalFiles, totalBytes, currentId)).build(); }

Target:
public Response moveFileAnswers(@QueryParam("count") Integer count) { if (count == null || count < 0) { return Response.status(Status.BAD_REQUEST).build(); } EnvironmentUser user = environmentUserController.findEnvironmentUserByUserEntity(sessionController.getLoggedUserEntity()); if (user == null || user.getRole() == null || user.getRole().getArchetype() != EnvironmentRoleArchetype.ADMINISTRATOR) { return Response.status(Status.FORBIDDEN).build(); } int bytes = 0; int totalBytes = 0; int totalFiles = 0; Long currentId = fileAnswerUtils.getLastEntityId(); List<Long> answerIds = workspaceMaterialFileFieldAnswerDAO.listIdsByLargerAndLimit(currentId, count); for (Long answerId : answerIds) { try { WorkspaceMaterialFileFieldAnswer answer = workspaceMaterialFileFieldAnswerDAO.findById(answerId); if (answer != null) { bytes = fileAnswerUtils.relocateToFileSystem(answer); if (bytes > 0) { totalBytes += bytes; totalFiles++; } currentId = answerId; } fileAnswerUtils.setLastEntityId(currentId); } catch (IOException e) { logger.log(Level.SEVERE, String.format("Failed to relocate WorkspaceMaterialFileFieldAnswer %d", currentId), e); return Response.status(Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build(); } } return Response.ok(String.format("Moved %d files (%d bytes) with latest entity at %d", totalFiles, totalBytes, currentId)).build(); }