id
stringlengths
7
14
source
stringlengths
135
41.2k
target
stringlengths
36
20.4k
251068401_3
class DateTimeUtils { public static DateTime withStartOfQuarter(DateTime dateTime) { int monthOfYear = dateTime.getMonthOfYear(); DateTime firstMonthOfQuarter; if (monthOfYear >= DateTimeConstants.OCTOBER) { firstMonthOfQuarter = dateTime.withMonthOfYear(DateTimeConstants.OCTOBE...
DateTime dateTime = DateTime.now(); DateTime startOfQuarter = DateTimeUtils.withStartOfQuarter(dateTime.withMonthOfYear(2)); Assert.assertEquals(1, startOfQuarter.monthOfYear().get()); startOfQuarter = DateTimeUtils.withStartOfQuarter(dateTime.withMonthOfYear(5)); Assert.assertE...
252293371_1
class TCNProtoUtil { public static void generateAllTCNsFromReport(byte[] report, INextTCNCallback callback) { int from = readUShort(report, 64); byte[] bstartTCK = Arrays.copyOfRange(report, 32, 64); TCNProtoGen ratchet = new TCNProtoGen(report[68], getRvkfromReport(report), bstartTCK, from...
byte[] report = hex2Byte(TCNProtoGenTest.VALIDREPORT); List<String> tcns = new LinkedList<>(); TCNProtoUtil.generateAllTCNsFromReport(report, x -> tcns.add(byte2Hex(x)) ); assertArrayEquals(REPORTTCNS, tcns.toArray()); } }
252902347_4
class WebServerPortFileWriter implements ApplicationListener<WebServerInitializedEvent> { @Override public void onApplicationEvent(WebServerInitializedEvent event) { File portFile = getPortFile(event.getApplicationContext()); try { String port = String.valueOf(event.getWebServer().getPort()); createParentF...
File file = this.temporaryFolder.newFile(); file = new File(file.getParentFile(), file.getName().toUpperCase(Locale.ENGLISH)); WebServerPortFileWriter listener = new WebServerPortFileWriter(file); listener.onApplicationEvent(mockEvent("management", 9090)); String managementFile = file.getName(); managementF...
253269900_126
class Fragment implements Iterable<Atom> { List<Atom> getAtomList() { return new ArrayList<Atom>(atomCollection); } Fragment(Element tokenEl); Fragment(String type); void addAtom(Atom atom); int getAtomCount(); void addBond(Bond bond); boolean removeBond(Bond bond); Set<Bond> getBondSet(); int ...
Fragment dhp = fm.buildSMILES("c1cCccC1"); FragmentTools.convertSpareValenciesToDoubleBonds(dhp); for(Atom a : dhp.getAtomList()) { assertEquals("All atoms have no sv", false, a.hasSpareValency()); } Fragment funnydiene = fm.buildSMILES("C(=C)C=C"); FragmentTools.convertSpareValenciesToDoubleBonds(funnyd...
253595061_79
class ReclaimerConfig { public String validate() { List<String> validationIssues = new LinkedList<>(); if(maximumExecutionSeconds < 0) validationIssues.add("maximumExecutionSeconds must be non-negative"); return validationIssues.size() == 0 ? null ...
String validationResult = config.validate(); Assert.assertTrue(StringUtils.containsIgnoreCase(validationResult, EXPECTED_FRAGMENT)); } }
254264048_0
class ParseEngine { public static ASTNode parse(final String sql) { ParseTree parseTree = createParseTree(sql); return new SQLVisitor().visit(parseTree.getChild(0)); } private static ParseTree createParseTree(final String sql); } class ParseEngineTest { @Test public void testPar...
String sql = "use sharding_db"; UseStatement useStatement = (UseStatement) ParseEngine.parse(sql); assertThat(useStatement.getSchemeName().getIdentifier().getValue(), is("sharding_db")); } }
255469961_50
class ExceptionHandlingControllerAdvice extends ResponseEntityExceptionHandler { @ExceptionHandler(RuntimeException.class) public ResponseEntity<Object> handleRuntimeException(RuntimeException exception) { return new ResponseEntity<>(createResponseBody(exception.getMessage(), BAD_REQUEST), new HttpHead...
var exception = new RuntimeException("kaboom"); var expectedResponse = ApiErrorResponse.builder() .status(BAD_REQUEST) .message("kaboom") .timeStamp(Instant.now(clock)) .build(); assertEquals(new ResponseEntity<>(expectedResponse, ...
255633533_25
class ExecutionNodeCompiler { static List<ExecutionNode> sort(List<ExecutionNode> nodes) { // priority is initial order in the list, node earlier in the list // would be always executed earlier if possible Map<String, Integer> priorityMap = new HashMap<>(); Map<String, Integer> degreeMap = new HashMa...
ExecutionNode node1 = createExecutionNode("node-1", ImmutableList.of("node-2")); VerifyException e = assertThrows( VerifyException.class, () -> ExecutionNodeCompiler.sort(ImmutableList.of(node1))); Assert.assertEquals("workflow graph isn't connected or has a cycle", e.getMessage()); ...
256285632_3
class SystemBleDevice implements IBleDevice { @Override public void stopScans(@NonNull ScanCallback scanCallback) { try { if (!bluetoothAdapter.isEnabled()) { BeaconLogger.e( "Can't stop the BLE scans since BluetoothAdapter is not enabled, most likely " ...
// given when(adapter.getBluetoothLeScanner()).thenReturn(null); when(adapter.isEnabled()).thenReturn(true); // when device.stopScans(scanCallback); // then verify(adapter).isEnabled(); verify(adapter).getBluetoothLeScanner(); verifyNoMoreInterac...
257682134_30
class PBKDF2 { public static String createHash(String password, String salt, int iterations, int dkLen) throws NoSuchAlgorithmException, InvalidKeySpecException { byte[] saltBytes = salt.getBytes(StandardCharsets.UTF_8); byte[] hash = pbkdf2(password.toCharArray(), saltBytes, iterations, dkLen); return toHex...
try { assertEquals( "5a27c13513ac42482cce07a543293c56dbfe06deb56634c1f2c6bd1cdeaab1bd373e22861d1f6c6785a406f0d75a7f247f87666b02d08f142c9097e8d40e6f17", PBKDF2.createHash("test input", "testsalt", 2, 512)); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (InvalidKeySpecException...
259639325_11
class Tensor { public void setOnCoord(Object value, int... coords) { checkCoordsLength(coords); if (value != null) { if (this.isScalar()) { this.data = value; } else if (value.getClass().isArray()) { this.setArrayOnCoord(value, coords); ...
Tensor tensor = new Tensor(DataType.INTEGER, new int[] {3, 2, 4}); EvaluationException exception = assertThrows( EvaluationException.class, () -> tensor.setOnCoord(4, 0, 0, -1) ); assertEquals("Coordinates contained at least an undefined value : [0, 0, -1]", excep...
259929534_5
class BookController { @DeleteMapping() public ResponseEntity<Book> deleteAll() { LOGGER.info("Delete all books"); books.clear(); return ResponseEntity.noContent().build(); } @PostMapping public ResponseEntity<Book> create(@Valid @RequestBody BookRequest request); @GetMappi...
MockHttpServletResponse response = deleteAll(); assertThat(response.getStatus(), is(HttpStatus.NO_CONTENT.value())); } }
260172508_9
class MmapChunkAllocator implements ChunkAllocator { @Override public void close() { if (!isClosed.compareAndSet(false, true)) { return; } // unmap and close file for (Tuple2<RandomAccessFile, MappedByteBuffer> tuple : memoryMappedFiles) { PlatformDependent.freeDirectBuffer(tuple.f1); IOUtils.close...
File[] dirs = new File[3]; for (int i = 0; i < dirs.length; i++) { dirs[i] = tempFolder.newFolder(); } MmapChunkAllocator allocator = new MmapChunkAllocator(10240, dirs, new Configuration()); for (File dir : dirs) { Assert.assertTrue(new File(dir, MmapChunkAllocator.MMAP_DIR).exists()); } alloc...
261970003_3
class DatabaseOperator { public <T> T query(final String baseQuery, final ResultSetHandler<T> resultHandler, final Object... params) throws SQLException { try { return this.queryRunner.query(baseQuery, resultHandler, params); } catch (final SQLException ex) { // todo kunkun-tang: Retr...
final int res = this.dbOperator.query("select * from blah where ? = ?", this.handler, "id", 3); Assert.assertEquals(0, res); } }
263047969_22
class ReduxViewModel extends AndroidViewModel implements Store<S, A> { @MainThread public void restoreState(@NonNull S state) { store.restoreState(state); } public ReduxViewModel(@NonNull Application applicationContext); @NonNull protected abstract ReduxStore<S, A> initializeStore(); ...
State state = currentState -> { }; reduxViewModel.restoreState(state); Mockito.verify(store, Mockito.times(1)).restoreState(state); } }
263923665_38
class SourceCodeAnalyzer { public int calculateNOC(String filepath, String analyzerType) throws IOException { if(analyzerType.equals("regex")) { String sourceCode = fileReader.readFileIntoString(filepath); Pattern pattern = Pattern.compile(".*\\s*class\\s+.*"); Matcher classSignatures = pattern.matc...
assertEquals(3, sca.calculateNOC(TEST_CLASS, TYPE_STRCOMP)); } }
264141019_7
class ColumnarDataSet extends AbstractDataSet { @Override protected Stream<DataPoint> streamDataPoints() { return Utils.getStream(nRows) .mapToObj(this::mapIndexToDataPoint); } public ColumnarDataSet(Map<? extends DataStructureComponent<?, ?, ?>, ScalarValue<?, ?, ?>[]> columns); private DataPoint mapIn...
boolean found[] = new boolean[5]; Iterator<DataPoint> it = INSTANCE.stream().iterator(); while (it.hasNext()) { DataPoint dp = it.next(); for (int i = 0; i < 5; i++) if (new StringValue(STR_ID_VAL[i]).equals(dp.get(STR_ID)) && new IntegerValue(INT_ID_VAL[i]).equals(dp.get(INT_ID))) { ScalarVa...
264503046_2
class ConfigurationLoader { @Nullable protected T initClass() { T instance = null; try { final Constructor<T> constructor = getClazz().getDeclaredConstructor(); constructor.setAccessible(true); instance = constructor.newInstance(); } catch (NoSuchMet...
TestConfig config = configurationLoader.initClass(); assertNotNull(config); assertNull(config.name); } }
265243047_3
class StringUtil { public static String convertRegularExpr (String str) { if(str == null){ return ""; } String pattern = "\\\\(\\d{3})"; Pattern r = Pattern.compile(pattern); while(true) { Matcher m = r.matcher(str); if(!m.find()) { ...
String result = StringUtil.convertRegularExpr("\\t\\r\\n"); Assert.assertEquals(result, "\t\r\n"); result = StringUtil.convertRegularExpr(null); Assert.assertEquals(result, ""); } }
265564812_1
class HttpService extends SingletonSerializeAsToken { @SneakyThrows public void destroy() { server.stop(); server.destroy(); } @SneakyThrows public HttpService(AppServiceHub appServiceHub); private boolean existsClass(String name); } class HttpServiceTest { @Test public void verifyHttpServerAvailable...
AppServiceHub serviceHub = Mockito.mock(AppServiceHub.class); HttpService service = new HttpService(serviceHub); try { String url = "http://127.0.0.1:" + service.getPort() + "/hello"; HttpClient client = HttpClientBuilder.create().build(); HttpResponse response = client.execute(new HttpGet(url)); asse...
267999301_0
class XMLUtils { public Document getXmlDocument() { return xmlDocument; } public XMLUtils(String xmlString); public List<Double> getDoubleValues(String tagName); public List<Long> getLongValues(String tagName); public List<Integer> getIntValues(String tagName); public List<Boolea...
Document xmlDocument = XMLUtils.getXmlDocument(xmlString); /*w3c document is created with xml string to access the different nodes of xml*/ Check.assertEquals(3, xmlDocument.getElementsByTagName("book").getLength(), "Book count in xml mismatched"); } }
269759605_7
class BattlePositionHoldingArea { public void setColumns(int columns) { this.columns = columns; } public BattlePositionHoldingArea(int rows, int columns); public int getRows(); public void setRows(int rows); public int getColumns(); } class BattlePositionHoldingAreaTest { @Tes...
BattlePositionHoldingArea bpha = new BattlePositionHoldingArea(2, 4); bpha.setColumns(2); Assert.assertEquals("getColumns == 2", bpha.getColumns(), 2); } }
271229375_1
class TypeConverter { public static Time toTime(String s) { try { return new Time(StdDateFormat.getTimeInstance().parse(s).getTime()); } catch (ParseException e) { throw new IllegalArgumentException(s); } } public static int toInt(String s); public stati...
assertThat(TypeConverter.toTime("10:11:12")) .hasHourOfDay(10) .hasMinute(11) .hasSecond(12); } }
276117258_29
class Parser { public static List<NativeQuery> parseJdbcSql(String query, boolean standardConformingStrings, boolean withParameters, boolean splitStatements, boolean isBatchedReWriteConfigured, String... returningColumnNames) throws SQLException { int numOfOverSymble = 0; boolean havePr...
String query = "insert test(id, name) select 1, 'value' from test2 RETURNING id"; List<NativeQuery> qry = Parser.parseJdbcSql( query, true, true, true, true); boolean returningKeywordPresent = qry.get(0).command.isReturningKeywordPresent(); Assert.assertTrue("Query has a retu...