method2testcases
stringlengths
118
6.63k
### 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: ArtemisBrokerManager { public void createAddress(String name, ArtemisCommonProperties properties) { logger.debug("Creating address '{}'", name); SimpleString nameString = SimpleString.toSimpleString(name); try (ClientSessionFactory sessionFactory = serverLocator.createSessionFactory(); ClientSession sessi...
### Question: ArtemisBrokerManager { public void createQueue(String address, String name) { try (ClientSessionFactory sessionFactory = serverLocator.createSessionFactory(); ClientSession session = getClientSession(sessionFactory)) { createQueueInternal(session, address, name); } catch (ProvisioningException e) { throw ...
### 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: 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: Scorer { public static Map<String, Integer> readLabelsFromFile(File file) throws IOException { FileInputStream inputStream = new FileInputStream(file); List<String> lines = IOUtils.readLines(inputStream, UTF8); IOUtils.closeQuietly(inputStream); Map<String, Integer> result = new TreeMap<>(); for (int i = ...
### Question: Scorer { public static double computeAccuracy(Map<String, Integer> gold, Map<String, Integer> predictions) throws IllegalArgumentException { if (gold == null) { throw new IllegalArgumentException("Parameter 'gold' is null"); } if (predictions == null) { throw new IllegalArgumentException("Parameter 'predi...
### 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 IstexData fromJson(String inputLine) { try { ObjectMapper mapper = new ObjectMapper(); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, true); mapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true); return mapper.readValue(inputLine, IstexData.class); } c...
### 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: Items { public static <T> T chooseWeighted( Collection<Weighted<T>> items, SourceOfRandomness random) { if (items.size() == 1) return items.iterator().next().item; int range = items.stream().mapToInt(i -> i.weight).sum(); int sample = random.nextInt(range); int threshold = 0; for (Weighted<T> each : items...
### Question: Lists { public static <T> List<List<T>> removeFrom(List<T> target, int howMany) { if (howMany < 0) throw new IllegalArgumentException("Can't remove " + howMany + " elements from a list"); if (howMany == 0) return singletonList(target); if (howMany > target.size()) return emptyList(); List<T> left = target...
### 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: Reflection { public static <T> Constructor<T> findConstructor( Class<T> type, Class<?>... parameterTypes) { try { return type.getConstructor(parameterTypes); } catch (Exception ex) { throw reflectionException(ex); } } private Reflection(); static Class<?> maybeWrap(Class<?> clazz); static Constructor<T> ...
### Question: Reflection { public static <T> Constructor<T> findDeclaredConstructor( Class<T> type, Class<?>... parameterTypes) { try { Constructor<T> ctor = type.getDeclaredConstructor(parameterTypes); ctor.setAccessible(true); return ctor; } catch (Exception ex) { throw reflectionException(ex); } } private Reflectio...
### 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 { @SuppressWarnings("unchecked") public static <T> Constructor<T> singleAccessibleConstructor( Class<T> type) { Constructor<?>[] constructors = type.getConstructors(); if (constructors.length != 1) { throw new ReflectionException( type + " needs a single accessible constructor"); } return (Cons...
### Question: Reflection { public static <T> T instantiate(Class<T> clazz) { try { return clazz.newInstance(); } catch (Exception ex) { throw reflectionException(ex); } } private Reflection(); static Class<?> maybeWrap(Class<?> clazz); static Constructor<T> findConstructor( Class<T> type, Class<?>... p...
### 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: Reflection { public static Method singleAbstractMethodOf(Class<?> rawClass) { if (!rawClass.isInterface()) return null; int abstractCount = 0; Method singleAbstractMethod = null; for (Method each : rawClass.getMethods()) { if (isAbstract(each.getModifiers()) && !overridesJavaLangObjectMethod(each)) { sing...
### Question: Reflection { public static boolean isMarkerInterface(Class<?> clazz) { if (!clazz.isInterface()) return false; return Arrays.stream(clazz.getMethods()) .filter(m -> !m.isDefault()) .noneMatch(m -> !overridesJavaLangObjectMethod(m)); } private Reflection(); static Class<?> maybeWrap(Class<?> clazz); stati...
### 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: Reflection { public static void setField( Field field, Object target, Object value, boolean suppressProtection) { doPrivileged((PrivilegedAction<Void>) () -> { field.setAccessible(suppressProtection); return null; }); try { field.set(target, value); } catch (Exception ex) { throw reflectionException(ex); ...
### Question: Reflection { public static List<Field> allDeclaredFieldsOf(Class<?> type) { List<Field> allFields = new ArrayList<>(); for (Class<?> c = type; c != null; c = c.getSuperclass()) Collections.addAll(allFields, c.getDeclaredFields()); List<Field> results = allFields.stream() .filter(f -> !f.isSynthetic()) .co...
### 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: MappingsResolver { public static List<String> getRequestMappings(Method method, Class<?> controller) { return getJoinedMappings(method, controller, PathExtractor.of(RequestMapping.class, RequestMapping::path)); } static List<String> getRequestMappings(Method method, Class<?> controller); static List<Stri...
### 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: JavadocTypeDocReader implements TypeDocReader { @NotNull @Override public Optional<PropertyDoc> buildPropertyDoc(Property property, TypeDoc parentDoc, TypeReferenceProvider typeReferenceProvider) { PropertyDoc doc = new PropertyDoc(); doc.setName(property.getName()); doc.setDescription(getPropertyDescript...
### 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: AddSpannerController { @RequestMapping(value = CONTROLLER_URL, method = RequestMethod.POST) public ModelAndView addSpanner(@Valid @ModelAttribute(MODEL_SPANNER) SpannerForm formData, BindingResult validationResult, Principal principal) { if (validationResult.hasErrors()) { return new ModelAndView(VIEW_VAL...
### 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: SignupController { @RequestMapping(value = CONTROLLER_URL, method = RequestMethod.POST) public String signup(@Valid @ModelAttribute SignupForm signupForm, Errors errors) { if (errors.hasErrors()) { log.warn("Oh no! Signup failed as there are validation errors."); return null; } String hashedPassword = pas...
### 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 = CONTROLLER_URL, method = RequestMethod.GET) public String displaySpanners(ModelMap model) { Collection<Spanner> spanners = spannersService.findAll(); String greeting = timeOfDayGreeting(); model.addAttribute(MODEL_ATTRIBUTE_SPANNERS, spanners); model.add...
### 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: OptimizedBubbleSort { public <T> int sort(T[] array, Comparator<T> comparator, boolean optimized) { if (array == null) { return 0; } int counter = 0; boolean swapped = true; int lastSwap = array.length-1; while (swapped) { swapped = false; int limit = array.length - 1; if(optimized){ limit = lastSwap; } f...
### 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> findPathBFS(V start, V end) { if(! graph.containsKey(start) || ! graph.containsKey(end)){ return null; } if(start.equals(end)){ throw new IllegalArgumentException(); } Queue<V> queue = new ArrayDeque<>(); Map<V,V> bestParent = new HashMap<>()...
### 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 ...