method2testcases stringlengths 118 3.08k |
|---|
### Question:
NamingUtils { public static String getPartitionAddress(String address, int partition) { Objects.requireNonNull(address); return String.format("%s-%d", address, partition); } static String getPartitionAddress(String address, int partition); static String getQueueName(String address, String group); static ... |
### Question:
ArtemisProducerDestination implements ProducerDestination { @Override public String getNameForPartition(int i) { return getPartitionAddress(name, i); } ArtemisProducerDestination(String name); @Override String getName(); @Override String getNameForPartition(int i); @Override String toString(); }### Answe... |
### Question:
ArtemisConsumerDestination implements ConsumerDestination { @Override public String getName() { return name; } ArtemisConsumerDestination(String name); @Override String getName(); @Override String toString(); }### Answer:
@Test public void shouldGetName() { String name = "test-name"; ArtemisConsumerDesti... |
### Question:
ArtemisProvisioningProvider implements ProvisioningProvider<
ExtendedConsumerProperties<ArtemisConsumerProperties>, ExtendedProducerProperties<ArtemisProducerProperties>> { @Override public ConsumerDestination provisionConsumerDestination(String address, String group, ExtendedConsumerProperties<Ar... |
### Question:
ListenerContainerFactory { public AbstractMessageListenerContainer getListenerContainer(String topic, String subscriptionName) { DefaultMessageListenerContainer listenerContainer = new DefaultMessageListenerContainer(); listenerContainer.setConnectionFactory(connectionFactory); listenerContainer.setPubSub... |
### Question:
NamingUtils { public static String getQueueName(String address, String group) { Objects.requireNonNull(address); Objects.requireNonNull(group); return String.format("%s-%s", address, group); } static String getPartitionAddress(String address, int partition); static String getQueueName(String address, Str... |
### Question:
NamingUtils { public static String getAnonymousGroupName() { UUID uuid = UUID.randomUUID(); ByteBuffer buffer = ByteBuffer.wrap(new byte[16]); buffer.putLong(uuid.getMostSignificantBits()) .putLong(uuid.getLeastSignificantBits()); return "anonymous-" + Base64Utils.encodeToUrlSafeString(buffer.array()) .re... |
### Question:
ArtemisMessageChannelBinder extends
AbstractMessageChannelBinder<ExtendedConsumerProperties<ArtemisConsumerProperties>,
ExtendedProducerProperties<ArtemisProducerProperties>, ArtemisProvisioningProvider> implements ExtendedPropertiesBinder<MessageChannel, ArtemisConsumerProperties,... |
### Question:
ArtemisProducerDestination implements ProducerDestination { @Override public String getName() { return name; } ArtemisProducerDestination(String name); @Override String getName(); @Override String getNameForPartition(int i); @Override String toString(); }### Answer:
@Test public void shouldGetName() { St... |
### Question:
GrobidResponseStaxHandler implements StaxParserContentHandler { public GrobidResponse getResponse() { return response; } @Override void onStartDocument(XMLStreamReader2 reader); @Override void onEndDocument(XMLStreamReader2 reader); @Override void onStartElement(XMLStreamReader2 reader); @Override void o... |
### Question:
IstexIdsReader { public void load(String input, Consumer<IstexData> closure) { try (Stream<String> stream = Files.lines(Paths.get(input))) { stream.forEach(line -> closure.accept(fromJson(line))); } catch (IOException e) { LOGGER.error("Some serious error when processing the input Istex ID file.", e); } }... |
### Question:
PmidReader { public PmidData fromCSV(String inputLine) { final String[] split = StringUtils.splitPreserveAllTokens(inputLine, ","); if (split.length > 0 && split.length <= 3) { return new PmidData(split[0], split[1], replaceAll(split[2], "\"", "")); } return null; } void load(String input, Consumer<PmidD... |
### Question:
SupplyLocationBulkUploadController { public List<SupplyLocation> uploadFitleredLocations(List<SupplyLocation> locations) { return this.service.saveSupplyLocationsZipContains504(locations); } @Autowired SupplyLocationBulkUploadController(SupplyLocationRepository repository); @Autowired SupplyLocationBulk... |
### Question:
HashtableGenerator extends MapGenerator<Hashtable> { @Override protected boolean okToAdd(Object key, Object value) { return key != null && value != null; } HashtableGenerator(); @Override void addComponentGenerators(List<Generator<?>> newComponents); }### Answer:
@Test public void disallowsNullKeyAndNull... |
### Question:
Items { @SuppressWarnings("unchecked") public static <T> T choose(Collection<T> items, SourceOfRandomness random) { int size = items.size(); if (size == 0) { throw new IllegalArgumentException( "Collection is empty, can't pick an element from it"); } if (items instanceof RandomAccess && items instanceof L... |
### Question:
Lists { public static <T> List<List<T>> shrinksOfOneItem( SourceOfRandomness random, List<T> target, Shrink<T> shrink) { if (target.isEmpty()) return new ArrayList<>(); T head = target.get(0); List<T> tail = target.subList(1, target.size()); List<List<T>> shrinks = new ArrayList<>(); shrinks.addAll( shrin... |
### Question:
Lambdas { public static <T, U> T makeLambda( Class<T> lambdaType, Generator<U> returnValueGenerator, GenerationStatus status) { if (singleAbstractMethodOf(lambdaType) == null) { throw new IllegalArgumentException( lambdaType + " is not a functional interface type"); } return lambdaType.cast( newProxyInsta... |
### Question:
Pair { @Override public String toString() { return String.format("[%s = %s]", first, second); } Pair(F first, S second); @Override int hashCode(); @Override boolean equals(Object o); @Override String toString(); final F first; final S second; }### Answer:
@Test public void stringifying() { assertEquals("[... |
### Question:
Sequences { public static Iterable<BigInteger> halvingIntegral( BigInteger max, BigInteger start) { return () -> new BigIntegerHalvingIterator(start, max); } private Sequences(); static Iterable<BigInteger> halvingIntegral(
BigInteger max,
BigInteger start); static Iterable<BigDecimal> ha... |
### Question:
Sequences { public static Iterable<BigDecimal> halvingDecimal( BigDecimal max, BigDecimal start) { return () -> new BigDecimalHalvingIterator(start, max); } private Sequences(); static Iterable<BigInteger> halvingIntegral(
BigInteger max,
BigInteger start); static Iterable<BigDecimal> hal... |
### Question:
Sequences { public static Iterable<Integer> halving(int start) { return () -> new IntegerHalvingIterator(start); } private Sequences(); static Iterable<BigInteger> halvingIntegral(
BigInteger max,
BigInteger start); static Iterable<BigDecimal> halvingDecimal(
BigDecimal max,
... |
### Question:
EnumGenerator extends Generator<Enum> { @Override public boolean canShrink(Object larger) { return enumType.isInstance(larger); } EnumGenerator(Class<?> enumType); @Override Enum<?> generate(
SourceOfRandomness random,
GenerationStatus status); @Override boolean canShrink(Object larger); ... |
### Question:
CompositeGenerator extends Generator<Object> { @Override public boolean canShrink(Object larger) { return composed.stream() .map(w -> w.item) .anyMatch(g -> g.canShrink(larger)); } CompositeGenerator(List<Weighted<Generator<?>>> composed); @Override Object generate(SourceOfRandomness random, GenerationSta... |
### Question:
ArrayGenerator extends Generator<Object> { @Override public boolean canShrink(Object larger) { return larger.getClass().getComponentType() == componentType; } ArrayGenerator(Class<?> componentType, Generator<?> component); void configure(Size size); void configure(Distinct distinct); @Override Object gene... |
### Question:
Comparables { public static <T extends Comparable<? super T>> T leastMagnitude( T min, T max, T zero) { if (min == null && max == null) return zero; if (min == null) return max.compareTo(zero) <= 0 ? max : zero; if (max == null) return min.compareTo(zero) >= 0 ? min : zero; if (min.compareTo(zero) > 0) re... |
### Question:
GeometricDistribution { int sample(double p, SourceOfRandomness random) { ensureProbability(p); if (p == 1) return 0; double uniform = random.nextDouble(); return (int) ceil(log(1 - uniform) / log(1 - p)); } int sampleWithMean(double mean, SourceOfRandomness random); }### Answer:
@Test public void negat... |
### Question:
GeometricDistribution { double probabilityOfMean(double mean) { if (mean <= 0) throw new IllegalArgumentException("Need a positive mean, got " + mean); return 1 / mean; } int sampleWithMean(double mean, SourceOfRandomness random); }### Answer:
@Test public void negativeMeanProbability() { thrown.expect(... |
### Question:
GeometricDistribution { public int sampleWithMean(double mean, SourceOfRandomness random) { return sample(probabilityOfMean(mean), random); } int sampleWithMean(double mean, SourceOfRandomness random); }### Answer:
@Test public void sampleWithMean() { when(random.nextDouble()).thenReturn(0.76); assertEq... |
### Question:
CodePoints { public static CodePoints forCharset(Charset c) { if (ENCODABLES.containsKey(c)) return ENCODABLES.get(c); CodePoints points = load(c); ENCODABLES.put(c, points); return points; } CodePoints(); int at(int index); int size(); boolean contains(int codePoint); static CodePoints forCharset(Charset... |
### Question:
Reflection { public static Method findMethod( Class<?> target, String methodName, Class<?>... argTypes) { try { return target.getMethod(methodName, argTypes); } catch (Exception ex) { throw reflectionException(ex); } } private Reflection(); static Class<?> maybeWrap(Class<?> clazz); static Constructor<T>... |
### Question:
CodePoints { public int at(int index) { if (index < 0) throw new IndexOutOfBoundsException("illegal negative index: " + index); int min = 0; int max = ranges.size() - 1; while (min <= max) { int midpoint = min + ((max - min) / 2); CodePointRange current = ranges.get(midpoint); if (index >= current.previou... |
### Question:
Reflection { public static Object invoke(Method method, Object target, Object... args) { try { return method.invoke(target, args); } catch (Exception ex) { throw reflectionException(ex); } } private Reflection(); static Class<?> maybeWrap(Class<?> clazz); static Constructor<T> findConstructor(
Cl... |
### Question:
Reflection { public static Object defaultValueOf( Class<? extends Annotation> annotationType, String attribute) { try { return annotationType.getMethod(attribute).getDefaultValue(); } catch (Exception ex) { throw reflectionException(ex); } } private Reflection(); static Class<?> maybeWrap(Class<?> clazz)... |
### Question:
CodePoints { public int size() { if (ranges.isEmpty()) return 0; CodePointRange last = ranges.get(ranges.size() - 1); return last.previousCount + last.size(); } CodePoints(); int at(int index); int size(); boolean contains(int codePoint); static CodePoints forCharset(Charset c); }### Answer:
@Test public... |
### Question:
VoidGenerator extends Generator<Void> { @Override public Void generate(SourceOfRandomness random, GenerationStatus status) { return null; } @SuppressWarnings("unchecked") VoidGenerator(); @Override Void generate(SourceOfRandomness random, GenerationStatus status); @Override boolean canRegisterAsType(Clas... |
### Question:
Reflection { public static Field findField(Class<?> type, String fieldName) { try { return type.getDeclaredField(fieldName); } catch (NoSuchFieldException ex) { throw reflectionException(ex); } } private Reflection(); static Class<?> maybeWrap(Class<?> clazz); static Constructor<T> findConstructor(
... |
### Question:
Ranges { static long findNextPowerOfTwoLong(long positiveLong) { return isPowerOfTwoLong(positiveLong) ? positiveLong : ((long) 1) << (64 - Long.numberOfLeadingZeros(positiveLong)); } private Ranges(); static int checkRange(
Type type,
T min,
T max); static BigInteger choose(
... |
### Question:
Ranges { public static BigInteger choose( SourceOfRandomness random, BigInteger min, BigInteger max) { BigInteger range = max.subtract(min).add(BigInteger.ONE); BigInteger generated; do { generated = random.nextBigInteger(range.bitLength()); } while (generated.compareTo(range) >= 0); return generated.add(... |
### Question:
FieldPropertyScanner implements PropertyScanner { @Override public List<Property> getProperties(Type type) { Class<?> clazz = extractClass(type); return getAllFields(clazz).stream() .filter(FieldPropertyScanner::isRelevantWhenSerialized) .map(FieldPropertyScanner::toProperty) .collect(toList()); } @Overr... |
### Question:
RecursivePropertyTypeScanner implements TypeScanner { @Override public Set<Class<?>> findTypesToDocument(Collection<? extends Type> rootTypes) { Set<Class<?>> allTypes = new HashSet<>(); rootTypes.forEach(type -> exploreType(type, allTypes)); return allTypes; } RecursivePropertyTypeScanner(PropertyScanner... |
### Question:
ConcreteSubtypesMapper implements Function<Class<?>, Set<Class<?>>> { @Override public Set<Class<?>> apply(Class<?> type) { if (isAbstract(type)) { return getImplementationsOf(type); } return Collections.singleton(type); } ConcreteSubtypesMapper(Reflections reflections); @Override Set<Class<?>> apply(Clas... |
### Question:
Defaults { public static Object defaultValueFor(@Nullable Class<?> type) { if (type == null) { return null; } return primitiveDefaults.get(type); } static Object defaultValueFor(@Nullable Class<?> type); }### Answer:
@Test public void defaultValueFor_primitives() { assertEquals(0, Defaults.defaultValueF... |
### Question:
JavadocTypeDocReader implements TypeDocReader { @NotNull @Override public Optional<TypeDoc> buildTypeDocBase(@NotNull Class<?> clazz, @NotNull TypeReferenceProvider typeReferenceProvider, @NotNull TemplateProvider templateProvider) { TypeDoc doc = new TypeDoc(clazz); doc.setName(clazz.getSimpleName()); do... |
### Question:
JacksonPropertyScanner implements PropertyScanner { @Override public List<Property> getProperties(Type type) { return getJacksonProperties(type).stream() .filter(JacksonPropertyScanner::isReadable) .map(this::convertProp) .collect(toList()); } JacksonPropertyScanner(ObjectMapper mapper); @Override List<Pr... |
### Question:
RestUserDetailsService implements UserDetailsManager { @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { return restTemplate.getForObject("/{0}", User.class, username); } RestUserDetailsService(RestTemplateBuilder builder,
... |
### Question:
SpannersService { public void create(Spanner spanner) { restTemplate.postForObject("/", spanner, Spanner.class); } SpannersService(RestTemplateBuilder builder,
@Value("${app.service.url.spanners}") String rootUri); Collection<Spanner> findAll(); Spanner findOne(Long id); @PreAut... |
### Question:
SpannersService { @PreAuthorize("hasPermission(#spanner, 'owner')") public void update(Spanner spanner) { restTemplate.put("/{0}", spanner, spanner.getId()); } SpannersService(RestTemplateBuilder builder,
@Value("${app.service.url.spanners}") String rootUri); Collection<Spanner>... |
### Question:
AddSpannerController { @RequestMapping(value = CONTROLLER_URL, method = RequestMethod.GET) public ModelAndView displayPage() { SpannerForm newSpanner = new SpannerForm(); return new ModelAndView(VIEW_ADD_SPANNER, MODEL_SPANNER, newSpanner); } @RequestMapping(value = CONTROLLER_URL, method = RequestMethod... |
### Question:
DetailSpannerController { @RequestMapping(value = "/detailSpanner", method = RequestMethod.GET) public ModelAndView displayDetail(@RequestParam Long id) throws SpannerNotFoundException { Spanner spanner = spannersService.findOne(id); if (spanner == null) { throw new SpannerNotFoundException(id); } return ... |
### Question:
HomeController { @RequestMapping(value = CONTROLLER_URL, method = RequestMethod.GET) public String index() { return VIEW_NOT_SIGNED_IN; } @RequestMapping(value = CONTROLLER_URL, method = RequestMethod.GET) String index(); static final String CONTROLLER_URL; static final String VIEW_NOT_SIGNED_IN; }### An... |
### Question:
RestUserDetailsService implements UserDetailsManager { @Override public void createUser(UserDetails userDetails) { restTemplate.postForLocation("/", userDetails); } RestUserDetailsService(RestTemplateBuilder builder,
@Value("${app.service.url.users}") String rootUri); @Ov... |
### Question:
DisplaySpannersController { @RequestMapping(value = "/deleteSpanner", method = RequestMethod.GET) public String deleteSpanner(@RequestParam Long id, ModelMap model) throws SpannerNotFoundException { Spanner spanner = spannersService.findOne(id); if (spanner == null) { throw new SpannerNotFoundException(id... |
### Question:
EditSpannerController implements ApplicationEventPublisherAware { @RequestMapping(value = CONTROLLER_URL, method = RequestMethod.GET) public ModelAndView displayPage(@RequestParam Long id) throws SpannerNotFoundException { Spanner spanner = spannersService.findOne(id); if (spanner == null) { throw new Spa... |
### Question:
RestUserDetailsService implements UserDetailsManager { @Override public void updateUser(UserDetails userDetails) { restTemplate.put("/{0}", userDetails, userDetails.getUsername()); } RestUserDetailsService(RestTemplateBuilder builder,
@Value("${app.service.url.users}") St... |
### Question:
RestUserDetailsService implements UserDetailsManager { @Override public void deleteUser(String username) { restTemplate.delete("/{0}", username); } RestUserDetailsService(RestTemplateBuilder builder,
@Value("${app.service.url.users}") String rootUri); @Override UserDetail... |
### Question:
RestUserDetailsService implements UserDetailsManager { @Override public boolean userExists(String username) { try { ResponseEntity<User> responseEntity = restTemplate.getForEntity("/{0}", User.class, username); return HttpStatus.OK.equals(responseEntity.getStatusCode()); } catch (HttpClientErrorException ... |
### Question:
RestUserDetailsService implements UserDetailsManager { @Override public void changePassword(String username, String password) { User user = new User(); user.setUsername(username); user.setPassword(password); HttpEntity<User> requestEntity = new HttpEntity<>(user); restTemplate.exchange("/{0}", HttpMethod.... |
### Question:
SpannersService { public Collection<Spanner> findAll() { ResponseEntity<PagedResources<Spanner>> response = restTemplate.exchange("/", HttpMethod.GET, null, new ParameterizedTypeReference<PagedResources<Spanner>>(){}); PagedResources<Spanner> pages = response.getBody(); return pages.getContent(); } Spanne... |
### Question:
SpannersService { public Spanner findOne(Long id) { return restTemplate.getForObject("/{0}", Spanner.class, id); } SpannersService(RestTemplateBuilder builder,
@Value("${app.service.url.spanners}") String rootUri); Collection<Spanner> findAll(); Spanner findOne(Long id); @PreAut... |
### Question:
SpannersService { @PreAuthorize("hasPermission(#spanner, 'owner')") public void delete(Spanner spanner) { restTemplate.delete("/{0}", spanner.getId()); } SpannersService(RestTemplateBuilder builder,
@Value("${app.service.url.spanners}") String rootUri); Collection<Spanner> findA... |
### Question:
MongoDbController { @GetMapping("/mongo/findAll") public List<Book> findAll() { return mongoDbService.findAll(); } @PostMapping("/mongo/save") String saveObj(@RequestBody Book book); @GetMapping("/mongo/findAll") List<Book> findAll(); @GetMapping("/mongo/findOne") Book findOne(@RequestParam String id); @... |
### Question:
MongoDbController { @PostMapping("/mongo/update") public String update(@RequestBody Book book) { return mongoDbService.updateBook(book); } @PostMapping("/mongo/save") String saveObj(@RequestBody Book book); @GetMapping("/mongo/findAll") List<Book> findAll(); @GetMapping("/mongo/findOne") Book findOne(@Re... |
### Question:
MongoDbController { @GetMapping("/mongo/findLikes") public List<Book> findByLikes(@RequestParam String search) { return mongoDbService.findByLikes(search); } @PostMapping("/mongo/save") String saveObj(@RequestBody Book book); @GetMapping("/mongo/findAll") List<Book> findAll(); @GetMapping("/mongo/findOne... |
### Question:
MyRingArrayQueue implements MyQueue<T> { @Override public T peek() { if(isEmpty()){ throw new RuntimeException(); } return (T) data[head]; } MyRingArrayQueue(); MyRingArrayQueue(int capacity); @Override void enqueue(T value); @Override T dequeue(); @Override T peek(); @Override int size(); }### Answer:
... |
### Question:
CopyExample { public static String[] copyWrong(String[] input){ if(input == null){ return null; } String[] output = input; return output; } static String[] copyWrong(String[] input); static String[] copy(String[] input); static String[][] copyWrong(String[][] input); static String[][] copy(String[][] inp... |
### Question:
CopyExample { public static String[] copy(String[] input){ if(input == null){ return null; } String[] output = new String[input.length]; for(int i=0; i<output.length; i++){ output[i] = input[i]; } return output; } static String[] copyWrong(String[] input); static String[] copy(String[] input); static Str... |
### Question:
User { public void setName(String name) { this.name = name; } User(String name, String surname, int id); @Override boolean equals(Object o); @Override int hashCode(); String getName(); void setName(String name); String getSurname(); void setSurname(String surname); int getId(); void setId(int id); }### A... |
### Question:
MySetHashMap implements MySet<E> { @Override public int size() { return map.size(); } @Override void add(E element); @Override void remove(E element); @Override boolean isPresent(E element); @Override int size(); }### Answer:
@Test public void testEmpty() { assertEquals(0, set.size()); assertTrue(set.is... |
### Question:
MySetHashMap implements MySet<E> { @Override public void remove(E element) { map.delete(element); } @Override void add(E element); @Override void remove(E element); @Override boolean isPresent(E element); @Override int size(); }### Answer:
@Test public void testRemove() { int n = set.size(); String elem... |
### Question:
HashFunctions { public static int hashLongToInt(long x) { return (int) x; } static int nonUniformHash(int x); static int identityHash(int x); static int shiftedHash(int x); static int hashLongToInt(long x); static int hashLongToIntRevised(long x); static int hashStringSum(String x); static int hashString... |
### Question:
HashFunctions { public static int hashLongToIntRevised(long x) { return (int) (x ^ (x >>> 32)); } static int nonUniformHash(int x); static int identityHash(int x); static int shiftedHash(int x); static int hashLongToInt(long x); static int hashLongToIntRevised(long x); static int hashStringSum(String x);... |
### Question:
UndirectedGraph implements Graph<V> { @Override public List<V> findPathDFS(V start, V end) { if(! graph.containsKey(start) || ! graph.containsKey(end)){ return null; } if(start.equals(end)){ throw new IllegalArgumentException(); } Set<V> alreadyVisited = new HashSet<>(); Deque<V> stack = new ArrayDeque<>... |
### Question:
UndirectedGraph implements Graph<V> { @Override public Set<V> findConnected(V vertex) { if(! graph.containsKey(vertex)){ return null; } Set<V> connected = new HashSet<>(); findConnected(connected, vertex); return connected; } @Override void addVertex(V vertex); @Override void addEdge(V from, V to); @Ove... |
### Question:
GenericExample { public <Z> MyPair<T,Z> createPair(T t, Z z){ MyPair<T, Z> pair = new MyPair<>(t, z); return pair; } Object identityObject(Object x); T identityGeneric(T x); Z identityGenericOnMethod(T t, Z z); MyPair<T,Z> createPair(T t, Z z); Comparable max(Comparable x, Comparable y); Z maxWithGeneric... |
### Question:
ArrayExample { public static int sum(int[] array){ if(array == null){ return 0; } int sum = 0; for(int i=0; i< array.length; i++){ sum += array[i]; } return sum; } static int sum(int[] array); }### Answer:
@Test public void testBase(){ int[] array = {1, 2, 3}; int res = ArrayExample.sum(array); assertEq... |
### Question:
GreedyForKnapsack { public static boolean[] solveByHeavierFirst(KnapsackProblem problem){ List<KnapsackProblem.Item> items = problem.getCopyOfItems(); items.sort((a,b) -> { double diff = a.getWeight() - b.getWeight(); if(diff < 0){ return 1; } else if(diff > 0){ return -1; } else { return 0; } }); return ... |
### Question:
GreedyForKnapsack { public static boolean[] solveByLighterFirst(KnapsackProblem problem){ List<KnapsackProblem.Item> items = problem.getCopyOfItems(); items.sort((a,b) -> { double diff = a.getWeight() - b.getWeight(); if(diff > 0){ return 1; } else if(diff < 0){ return -1; } else { return 0; } }); return ... |
### Question:
GreedyForKnapsack { public static boolean[] solveByBestRatioFirst(KnapsackProblem problem){ List<KnapsackProblem.Item> items = problem.getCopyOfItems(); items.sort((a,b) -> { if(a.getWeight() == 0){ return -1; } if(b.getWeight() == 0){ return 1; } double ra = a.getValue() / a.getWeight(); double rb = b.ge... |
### Question:
DnaCompressor { public static byte[] compress(String dna){ BitWriter writer = new BitWriter(); writer.write(dna.length()); for(int i=0; i<dna.length(); i++){ char c = dna.charAt(i); if(c== 'A'){ writer.write(true); writer.write(true); } else if(c== 'C'){ writer.write(true); writer.write(false); }else if(c... |
### Question:
BitReader { public byte readByte(){ if(bits % 8 == 0){ int i = bits / 8; bits += 8; return data[i]; } byte tmp = 0; for(int j=0; j<8; j++){ tmp = (byte) (tmp << 1); boolean k = readBoolean(); if(k){ tmp |= 1; } } return tmp; } BitReader(byte[] data); byte readByte(); boolean readBoolean(); int readInt(); ... |
### Question:
BitReader { public boolean readBoolean(){ int i = bits / 8; if(i >= data.length){ throw new IllegalStateException("No more data to read"); } byte b = data[i]; int k = bits % 8; bits++; return ((b >>> (8 - k - 1)) & 1) == 1; } BitReader(byte[] data); byte readByte(); boolean readBoolean(); int readInt(); i... |
### Question:
BitReader { public int readInt(){ int x; byte a = readByte(); x = a & 0xFF; byte b = readByte(); x = x << 8; x |= (b & 0xFF); byte c = readByte(); x = x << 8; x |= (c & 0xFF); byte d = readByte(); x = x << 8; x |= (d & 0xFF); return x; } BitReader(byte[] data); byte readByte(); boolean readBoolean(); int ... |
### Question:
BitReader { public char readChar(){ int x; byte a = readByte(); x = a & 0xFF; byte b = readByte(); x = x << 8; x |= (b & 0xFF); return (char) x; } BitReader(byte[] data); byte readByte(); boolean readBoolean(); int readInt(); int readInt(int nbits); char readChar(); }### Answer:
@Test public void testStr... |
### Question:
MyMapBinarySearchTree implements MyMapTreeBased<K, V> { @Override public int getMaxTreeDepth() { if (root == null) { return 0; } return depth(root); } @Override void put(K key, V value); @Override void delete(K key); @Override V get(K key); @Override int size(); @Override int getMaxTreeDepth(); }### Ans... |
### Question:
LambdaExamples { public static void useRunnable(Runnable runnable){ System.out.println("Before runnable"); runnable.run(); System.out.println("After runnable"); } static void useRunnable(Runnable runnable); static void useConsumer(Consumer<String> consumer); static String usePredicate(Predicate<String> p... |
### Question:
LambdaExamples { public static void useConsumer(Consumer<String> consumer){ String foo = "foo"; System.out.println("Before consumer"); consumer.accept(foo); System.out.println("After consumer"); } static void useRunnable(Runnable runnable); static void useConsumer(Consumer<String> consumer); static Strin... |
### Question:
LambdaExamples { public static String usePredicate(Predicate<String> predicate){ String foo = "foo"; if(predicate.test(foo)){ return foo; } else { return null; } } static void useRunnable(Runnable runnable); static void useConsumer(Consumer<String> consumer); static String usePredicate(Predicate<String> ... |
### Question:
LambdaExamples { public static int useFunction(Function<String, Integer> function){ String input = "foo"; return function.apply(input); } static void useRunnable(Runnable runnable); static void useConsumer(Consumer<String> consumer); static String usePredicate(Predicate<String> predicate); static int use... |
### Question:
MyIterableLinkedList implements Iterable<T> { public void add(T value) { ListNode node = new ListNode(); node.value = value; size++; modificationCounter++; if (head == null) { head = node; tail = node; return; } tail.next = node; tail = node; } @Override Iterator<T> iterator(); void delete(int index); T ... |
### Question:
MyIterableLinkedList implements Iterable<T> { public int size() { return size; } @Override Iterator<T> iterator(); void delete(int index); T get(int index); void add(T value); int size(); boolean isEmpty(); boolean contains(T value); }### Answer:
@Test public void testEmpty(){ MyIterableLinkedList<Integ... |
### Question:
AllPathsGraph extends UndirectedGraph<V> { public List<List<V>> findAllPaths(V start, V end) { if (!graph.containsKey(start) && !graph.containsKey(end)) { return Collections.emptyList(); } if (start.equals(end)) { throw new IllegalArgumentException(); } Deque<V> stack = new ArrayDeque<>(); List<List<V>> p... |
### Question:
MyIterableLinkedList implements Iterable<T> { public T get(int index) { if (index < 0 || index >= size()) { throw new IndexOutOfBoundsException(); } ListNode current = head; int counter = 0; while (current != null) { if (counter == index) { return current.value; } current = current.next; counter++; } asse... |
### Question:
MyIterableHashMap implements MyHashMap<K,V>, Iterable<V> { @Override public void put(K key, V value) { modificationCounter++; int i = index(key); if(data[i] == null){ data[i] = new ArrayList<>(); } List<Entry> list = data[i]; for(int j=0; j<list.size(); j++){ Entry entry = list.get(j); if(key.equals(entry... |
### Question:
MyIterableHashMap implements MyHashMap<K,V>, Iterable<V> { @Override public int size() { int size = 0; for(int i=0; i<data.length; i++){ if(data[i] != null){ size += data[i].size(); } } return size; } MyIterableHashMap(); MyIterableHashMap(int capacity); @Override Iterator<V> iterator(); @Override void p... |
### Question:
MyIterableHashMap implements MyHashMap<K,V>, Iterable<V> { @Override public void delete(K key) { int i = index(key); if(data[i] == null){ return; } List<Entry> list = data[i]; for(int j=0; j<list.size(); j++){ Entry entry = list.get(j); if(key.equals(entry.key)){ list.remove(j); modificationCounter++; ret... |
### Question:
TernaryTreeMap implements MyMapTreeBased<K, V> { @Override public int getMaxTreeDepth() { if (root == null) { return 0; } return depth(root); } @Override void put(K key, V value); @Override void delete(K key); @Override V get(K key); @Override int size(); @Override int getMaxTreeDepth(); }### Answer:
@T... |
### Question:
MyArrayListInteger { public int size() { return size; } MyArrayListInteger(); MyArrayListInteger(int maxSize); Integer get(int index); void add(Integer value); int size(); }### Answer:
@Test public void testEmpty(){ assertEquals(0, data.size()); } |
### Question:
MyArrayListInteger { public Integer get(int index) { if(index < 0 || index >= size){ return null; } return data[index]; } MyArrayListInteger(); MyArrayListInteger(int maxSize); Integer get(int index); void add(Integer value); int size(); }### Answer:
@Test public void testOutOfIndex(){ assertNull(data.g... |
### Question:
AxonDBEventStore extends AbstractEventStore { @Override public TrackingEventStream openStream(TrackingToken trackingToken) { return storageEngine().openStream(trackingToken); } AxonDBEventStore(AxonDBConfiguration configuration, Serializer serializer); AxonDBEventStore(AxonDBConfiguration configuration, ... |
### Question:
IdGenerator { public static long newRandomId(@Nullable Set<Long> existingIds) { while (true) { long candidateId = ThreadLocalRandom.current().nextLong(); if (MIN <= candidateId && candidateId <= MAX) { if (existingIds == null) { return candidateId; } if (!existingIds.contains(candidateId)) { return candid... |
End of preview. Expand in Data Studio
README.md exists but content is empty.
- Downloads last month
- 4