method2testcases
stringlengths 118
3.08k
|
---|
### Question:
IntOrString { public boolean isInteger() { return isInt; } IntOrString(final String value); IntOrString(final int value); boolean isInteger(); String getStrValue(); Integer getIntValue(); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); }### Answer:
@Test public void whenCreatedWithInt_isInteger() { IntOrString intOrString = new IntOrString(17); assertThat(intOrString.isInteger(), is(true)); }
@Test public void whenCreatedWithString_isNotInteger() { IntOrString intOrString = new IntOrString("17"); assertThat(intOrString.isInteger(), is(false)); } |
### Question:
IntOrString { public Integer getIntValue() { if (!isInt) { throw new IllegalStateException("Not an integer"); } return intValue; } IntOrString(final String value); IntOrString(final int value); boolean isInteger(); String getStrValue(); Integer getIntValue(); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); }### Answer:
@Test public void whenCreatedWithInt_canRetrieveIntValue() { IntOrString intOrString = new IntOrString(17); assertThat(intOrString.getIntValue(), equalTo(17)); }
@Test(expected = IllegalStateException.class) public void whenCreatedWithInt_cannotRetrieveIntValue() { IntOrString intOrString = new IntOrString("17"); intOrString.getIntValue(); } |
### Question:
IntOrString { public String getStrValue() { if (isInt) { throw new IllegalStateException("Not a string"); } return strValue; } IntOrString(final String value); IntOrString(final int value); boolean isInteger(); String getStrValue(); Integer getIntValue(); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); }### Answer:
@Test(expected = IllegalStateException.class) public void whenCreatedWithInt_cannotRetrieveStringValue() { IntOrString intOrString = new IntOrString(17); intOrString.getStrValue(); }
@Test public void whenCreatedWithString_canRetrieveStringValue() { IntOrString intOrString = new IntOrString("17"); assertThat(intOrString.getStrValue(), equalTo("17")); } |
### Question:
ModelMapper { public static Class<?> getApiTypeClass(String apiGroupVersion, String kind) { String[] parts = apiGroupVersion.split("/"); String apiGroup; String apiVersion; if (parts.length == 1) { apiGroup = ""; apiVersion = apiGroupVersion; } else { apiGroup = parts[0]; apiVersion = parts[1]; } return getApiTypeClass(apiGroup, apiVersion, kind); } @Deprecated static void addModelMap(String apiGroupVersion, String kind, Class<?> clazz); @Deprecated static void addModelMap(String group, String version, String kind, Class<?> clazz); static void addModelMap(
String group, String version, String kind, String resourceNamePlural, Class<?> clazz); static void addModelMap(
String group,
String version,
String kind,
String resourceNamePlural,
Boolean isNamespacedResource,
Class<?> clazz); static Class<?> getApiTypeClass(String apiGroupVersion, String kind); static Class<?> getApiTypeClass(String group, String version, String kind); static GroupVersionKind getGroupVersionKindByClass(Class<?> clazz); static GroupVersionResource getGroupVersionResourceByClass(Class<?> clazz); static Set<Discovery.APIResource> refresh(Discovery discovery); static Set<Discovery.APIResource> refresh(Discovery discovery, Duration refreshInterval); static boolean isApiDiscoveryRefreshed(); static Class<?> preBuiltGetApiTypeClass(String group, String version, String kind); static GroupVersionKind preBuiltGetGroupVersionKindByClass(Class<?> clazz); static Boolean isNamespaced(Class<?> clazz); static final Duration DEFAULT_DISCOVERY_REFRESH_INTERVAL; }### Answer:
@Test public void testPrebuiltModelMapping() { assertEquals(V1Pod.class, ModelMapper.getApiTypeClass("", "v1", "Pod")); assertEquals(V1Deployment.class, ModelMapper.getApiTypeClass("", "v1", "Deployment")); assertEquals( V1beta1CustomResourceDefinition.class, ModelMapper.getApiTypeClass("", "v1beta1", "CustomResourceDefinition")); } |
### Question:
ClassFileNameHandler { @Nonnull static String shortenPathComponent(@Nonnull String pathComponent, int maxLength) { int toRemove = pathComponent.length() - maxLength + 1; int firstIndex = (pathComponent.length()/2) - (toRemove/2); return pathComponent.substring(0, firstIndex) + "#" + pathComponent.substring(firstIndex+toRemove); } ClassFileNameHandler(File path, String fileExtension); File getUniqueFilenameForClass(String className); }### Answer:
@Test public void testShortedPathComponent() { StringBuilder sb = new StringBuilder(); for (int i=0; i<300; i++) { sb.append((char)i); } String result = ClassFileNameHandler.shortenPathComponent(sb.toString(), 255); Assert.assertEquals(255, result.length()); } |
### Question:
BaseDexBuffer { public int readUshort(int offset) { byte[] buf = this.buf; return (buf[offset] & 0xff) | ((buf[offset+1] & 0xff) << 8); } BaseDexBuffer(@Nonnull byte[] buf); int readSmallUint(int offset); int readOptionalUint(int offset); int readUshort(int offset); int readUbyte(int offset); long readLong(int offset); int readInt(int offset); int readShort(int offset); int readByte(int offset); @Nonnull BaseDexReader readerAt(int offset); }### Answer:
@Test public void testReadUshort() { BaseDexBuffer dexBuf = new BaseDexBuffer(new byte[] {0x11, 0x22}); Assert.assertEquals(dexBuf.readUshort(0), 0x2211); dexBuf = new BaseDexBuffer(new byte[] {0x00, 0x00}); Assert.assertEquals(dexBuf.readUshort(0), 0); dexBuf = new BaseDexBuffer(new byte[] {(byte)0xff, (byte)0xff}); Assert.assertEquals(dexBuf.readUshort(0), 0xffff); dexBuf = new BaseDexBuffer(new byte[] {(byte)0x00, (byte)0x80}); Assert.assertEquals(dexBuf.readUshort(0), 0x8000); dexBuf = new BaseDexBuffer(new byte[] {(byte)0xff, (byte)0x7f}); Assert.assertEquals(dexBuf.readUshort(0), 0x7fff); } |
### Question:
BaseDexBuffer { public int readUbyte(int offset) { return buf[offset] & 0xff; } BaseDexBuffer(@Nonnull byte[] buf); int readSmallUint(int offset); int readOptionalUint(int offset); int readUshort(int offset); int readUbyte(int offset); long readLong(int offset); int readInt(int offset); int readShort(int offset); int readByte(int offset); @Nonnull BaseDexReader readerAt(int offset); }### Answer:
@Test public void testReadUbyte() { byte[] buf = new byte[1]; BaseDexBuffer dexBuf = new BaseDexBuffer(buf); for (int i=0; i<=0xff; i++) { buf[0] = (byte)i; Assert.assertEquals(i, dexBuf.readUbyte(0)); } } |
### Question:
BaseDexBuffer { public int readShort(int offset) { byte[] buf = this.buf; return (buf[offset] & 0xff) | (buf[offset+1] << 8); } BaseDexBuffer(@Nonnull byte[] buf); int readSmallUint(int offset); int readOptionalUint(int offset); int readUshort(int offset); int readUbyte(int offset); long readLong(int offset); int readInt(int offset); int readShort(int offset); int readByte(int offset); @Nonnull BaseDexReader readerAt(int offset); }### Answer:
@Test public void testReadShort() { BaseDexBuffer dexBuf = new BaseDexBuffer(new byte[] {0x11, 0x22}); Assert.assertEquals(dexBuf.readShort(0), 0x2211); dexBuf = new BaseDexBuffer(new byte[] {0x00, 0x00}); Assert.assertEquals(dexBuf.readShort(0), 0); dexBuf = new BaseDexBuffer(new byte[] {(byte)0xff, (byte)0xff}); Assert.assertEquals(dexBuf.readShort(0), -1); dexBuf = new BaseDexBuffer(new byte[] {(byte)0x00, (byte)0x80}); Assert.assertEquals(dexBuf.readShort(0), Short.MIN_VALUE); dexBuf = new BaseDexBuffer(new byte[] {(byte)0xff, (byte)0x7f}); Assert.assertEquals(dexBuf.readShort(0), 0x7fff); dexBuf = new BaseDexBuffer(new byte[] {(byte)0xff, (byte)0x80}); Assert.assertEquals(dexBuf.readShort(0), 0xffff80ff); } |
### Question:
BaseDexBuffer { public int readByte(int offset) { return buf[offset]; } BaseDexBuffer(@Nonnull byte[] buf); int readSmallUint(int offset); int readOptionalUint(int offset); int readUshort(int offset); int readUbyte(int offset); long readLong(int offset); int readInt(int offset); int readShort(int offset); int readByte(int offset); @Nonnull BaseDexReader readerAt(int offset); }### Answer:
@Test public void testReadByte() { byte[] buf = new byte[1]; BaseDexBuffer dexBuf = new BaseDexBuffer(buf); for (int i=0; i<=0xff; i++) { buf[0] = (byte)i; Assert.assertEquals((byte)i, dexBuf.readByte(0)); } } |
### Question:
GenerateConfigMojo extends AbstractMojo { public String getSettingsForArtifact( String fullSettings, String groupId, String artifactId ) { if( fullSettings != null ) { for( String token : fullSettings.split( "," ) ) { int end = ( token.indexOf( "@" ) >= 0 ) ? token.indexOf( "@" ) : token.length(); String ga_part[] = token.substring( 0, end ).split( ":" ); if( ga_part[ 0 ].equals( groupId ) && ga_part[ 1 ].equals( artifactId ) ) { return token.substring( end ); } } } return ""; } void execute(); String getSettingsForArtifact( String fullSettings, String groupId, String artifactId ); }### Answer:
@Test public void testSettingsMatching() { assertEquals( "@42@bee", new GenerateConfigMojo().getSettingsForArtifact( "cheese:ham@1@nope,foo:bar@42@bee,fuel:oil@1@xx", "foo", "bar" ) ); assertEquals( "", new GenerateConfigMojo().getSettingsForArtifact( "cheese:ham@1@nope,foo:bar@42@bee,fuel:oil@1@xx", "xx", "bb" ) ); assertEquals( "", new GenerateConfigMojo().getSettingsForArtifact( "cheese:ham@1@nope,foo:bar@42@bee,fuel:oil@1@xx", "cheese", "bb" ) ); assertEquals( "@42@bee", new GenerateConfigMojo().getSettingsForArtifact( "cheese:ham@1@nope,foo:bar@42@bee,fuel:oil@1@xx", "foo", "bar" ) ); assertEquals( "", new GenerateConfigMojo().getSettingsForArtifact( "cheese:ham@1@nope,foo:bar@42@bee,fuel:oil@1@xx,ping:back", "ping", "back" ) ); } |
### Question:
FileScannerProvisionOption extends AbstractUrlProvisionOption<FileScannerProvisionOption> implements Scanner { public String getURL() { return new StringBuilder() .append( SCHEMA ) .append( SEPARATOR_SCHEME ) .append( super.getURL() ) .append( getOptions( this ) ) .toString(); } FileScannerProvisionOption( final String url ); FileScannerProvisionOption( final UrlReference url ); String getURL(); }### Answer:
@Test public void urlAsString() { assertThat( "Scan file url", new FileScannerProvisionOption( "file:foo.bundles" ).getURL(), is( equalTo( "scan-file:file:foo.bundles" ) ) ); }
@Test public void urlAsStringViaFactoryMethod() { assertThat( "Scan file url", scanFile( "file:foo.bundles" ).getURL(), is( equalTo( "scan-file:file:foo.bundles" ) ) ); }
@Test public void urlAsReference() { assertThat( "Scan file url", new FileScannerProvisionOption( url( "file:foo.bundles" ) ).getURL(), is( equalTo( "scan-file:file:foo.bundles" ) ) ); }
@Test public void urlAsReferenceViaFactoryMethod() { assertThat( "Scan file url", scanFile( url( "file:foo.bundles" ) ).getURL(), is( equalTo( "scan-file:file:foo.bundles" ) ) ); }
@Test public void urlAsMavenUrl() { assertThat( "Scan file url", new FileScannerProvisionOption( maven().groupId( "bar" ).artifactId( "foo" ).type( "bundles" ) ).getURL(), is( equalTo( "scan-file:mvn:bar/foo ); }
@Test public void urlAsMavenUrlViaFactoryMethod() { assertThat( "Scan file url", scanFile( maven().groupId( "bar" ).artifactId( "foo" ).type( "bundles" ) ).getURL(), is( equalTo( "scan-file:mvn:bar/foo ); } |
### Question:
ConfigurationManager { static void setEnableDefaultload(boolean enabled){ enableDefaultload =enabled; } static Map<String,Map<String,String>> getAllProperties(); static Map<String,String> getPropertiesByConfigName(String configName); static Set<String> getConfigKeys(String configName); static synchronized boolean isConfigurationInstalled(); static Configuration getConfigInstance(); static Configuration getConfigFromPropertiesFile(URL startingUrl); static Properties getPropertiesFromFile(URL startingUrl); static void installReadonlyProperties(Properties pros); }### Answer:
@Test public void testGetDefaultAppPro(){ ConfigurationManager.setEnableDefaultload(true); System.out.println(ConfigurationManager.class.getProtectionDomain().getCodeSource().getLocation().toString()); URL url = getClass().getProtectionDomain().getCodeSource().getLocation(); try { InputStream in = ConfigurationManager.class.getClassLoader().getResourceAsStream("jar:"+url.toURI().toString()+"!/META-INF/MANIFEST.MF"); System.out.println(url.toURI().toString()); System.out.println(in); ZipInputStream zip = new ZipInputStream(url.openStream()); ZipEntry ze; while ((ze = zip.getNextEntry())!=null){ if(ze.getName().equals("META-INF/MANIFEST.MF")){ System.out.println(ze.getName()); break; } } System.out.println(IOUtils.readAll(zip)); } catch (URISyntaxException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } ConfigurationManager.setEnableDefaultload(false); } |
### Question:
ConfigurationManager { static void loadProperties(Properties properties) throws InitConfigurationException { if (instance == null) { instance = getConfigInstance(); } ConfigurationUtils.loadProperties(properties, instance); } static Map<String,Map<String,String>> getAllProperties(); static Map<String,String> getPropertiesByConfigName(String configName); static Set<String> getConfigKeys(String configName); static synchronized boolean isConfigurationInstalled(); static Configuration getConfigInstance(); static Configuration getConfigFromPropertiesFile(URL startingUrl); static Properties getPropertiesFromFile(URL startingUrl); static void installReadonlyProperties(Properties pros); }### Answer:
@Test public void testLoadProperties() throws Exception { ConfigurationManager.loadPropertiesFromResources("test.properties"); assertEquals("9", ConfigurationManager.getConfigInstance().getProperty("com.ctrip.config.samples.needCount")); assertEquals("9", ConfigurationManager.getConfigInstance().getString("com.ctrip.config.samples.needCount")); assertEquals("100", ConfigurationManager.getConfigInstance().getString("no.exist","100")); } |
### Question:
ConfigurationManager { public static Configuration getConfigInstance() throws InitConfigurationException { if (instance == null) { synchronized (ConfigurationManager.class) { if (instance == null) { instance = createDefaultConfigInstance(); try { customProperties = Tools.loadPropertiesFromFile(TEMPFILENAME); } catch (Throwable e) { logger.error("load temp custom properties failed!", e); } if(customProperties!=null) { Iterator<String> keys = customProperties.getKeys(); while (keys.hasNext()) { String key = keys.next(); if (instance.containsKey(key)) { instance.setProperty(key, customProperties.getString(key)); } } } } } } return instance; } static Map<String,Map<String,String>> getAllProperties(); static Map<String,String> getPropertiesByConfigName(String configName); static Set<String> getConfigKeys(String configName); static synchronized boolean isConfigurationInstalled(); static Configuration getConfigInstance(); static Configuration getConfigFromPropertiesFile(URL startingUrl); static Properties getPropertiesFromFile(URL startingUrl); static void installReadonlyProperties(Properties pros); }### Answer:
@Test public void testNumberProperties() throws Exception { Configuration config = ConfigurationManager.getConfigInstance(); double val = 12.3; config.setProperty("test-double",val); assertTrue(val == config.getDouble("test-double")); config.setProperty("test-int",10); assertTrue(10 == config.getDouble("test-int")); assertTrue(0 == config.getDouble("test-int-emp")); assertTrue(20 == config.getInt("test-int-emp",20)); assertTrue(new Integer(23) == config.getInt("test-int-emp",new Integer(23))); assertEquals(false,config.getBoolean("test-boolean")); } |
### Question:
ConfigurationManager { private static Properties loadCascadedProperties(String configName) throws IOException { String defaultConfigFileName = configName + ".properties"; ClassLoader loader = Thread.currentThread().getContextClassLoader(); URL url = loader.getResource(defaultConfigFileName); if (url == null) { throw new IOException("Cannot locate " + defaultConfigFileName + " as a classpath resource."); } Properties props = getPropertiesFromFile(url); String environment = EnFactory.getEnBase().getEnvType(); if(environment!=null) { environment = environment.toLowerCase(); } if (environment != null && environment.length() > 0) { String envConfigFileName = configName + "-" + environment + ".properties"; url = loader.getResource(envConfigFileName); if(url==null){ url = loader.getResource(configName.replace("config/",environment+"-config/") +".properties"); } if (url != null) { Properties envProps = getPropertiesFromFile(url); if (envProps != null) { props.putAll(envProps); } } } return props; } static Map<String,Map<String,String>> getAllProperties(); static Map<String,String> getPropertiesByConfigName(String configName); static Set<String> getConfigKeys(String configName); static synchronized boolean isConfigurationInstalled(); static Configuration getConfigInstance(); static Configuration getConfigFromPropertiesFile(URL startingUrl); static Properties getPropertiesFromFile(URL startingUrl); static void installReadonlyProperties(Properties pros); }### Answer:
@Test public void testLoadCascadedProperties() throws Exception { ConfigurationManager.loadCascadedPropertiesFromResources("config/test"); assertEquals("7", ConfigurationManager.getConfigInstance().getProperty("com.ctrip.config.samples.needCount")); assertEquals("1", ConfigurationManager.getConfigInstance().getProperty("cascaded.property")); } |
### Question:
VIServer { public VIServer(int listenPort,boolean useVIAuthentication) throws Exception { server = new Server(listenPort); handler = bind(server, String.valueOf(listenPort),useVIAuthentication); } VIServer(int listenPort,boolean useVIAuthentication); VIServer(int listenPort); static ServletHandler bind(Server server,String id); static ServletHandler bind(Server server,String id,boolean useVIAuthentication); Server getInnerServer(); ServletHandler getHandler(); synchronized void start(); synchronized void stop(); }### Answer:
@Test public void testVIServer() throws Exception { int port = 1998; VIServer server = new VIServer(port); server.start(); URL url = new URL("http: Gson gson = new Gson(); List<CInfo> infos= new ArrayList<>(); String content = IOUtils.readAll((InputStream)url.getContent()); System.out.println(IgniteManager.getStatus().getMessages()); infos =gson.fromJson(content, infos.getClass()); Assert.assertTrue(infos.size()>=3); server.stop(); try{ infos =gson.fromJson(IOUtils.readAll((InputStream)url.getContent()), infos.getClass()); Assert.fail("can't reach there"); }catch (Exception e){ Assert.assertTrue(e instanceof ConnectException); } } |
### Question:
EventBusDispatcher implements IEventDispatcher { @Override public void dispatch(String name, Object event) { logger.debug("DispatchEvent: {} ({})", name, event); final Object[] args = event!=null?new Object[]{event}:new Object[]{}; dispatch(name, args); } EventBusDispatcher(EventBusManager ebManager, EventBus eb); @Override void dispatch(String name, Object event); @Override void dispatch(String name, Object... args); }### Answer:
@Test public void testDispatch_withArgumentAndExistingMethod_willSuccess() { testEventBus.testEventWithArgument(THE_ARG); replay(testEventBus); eventBusDispatcher.dispatch("testEventWithArgument", THE_ARG); verify(testEventBus); }
@Test public void testDispatch_withoutArgumentAndExistingMethod_willSuccess() { testEventBus.testEventWithoutArgument(); replay(testEventBus); eventBusDispatcher.dispatch("testEventWithoutArgument"); verify(testEventBus); }
@Test(expected = Exception.class) public void testDispatch_withoutArgument_exceptionOccurred_willBeRaised() { testEventBus.testEventWithoutArgument(); expectLastCall().andThrow(new RuntimeException("Faking an exception")); replay(testEventBus); eventBusDispatcher.dispatch("testEventWithoutArgument"); verify(testEventBus); }
@Test(expected = Exception.class) public void testDispatch_witArgument_exceptionOccurred_willBeRaised() { testEventBus.testEventWithArgument(THE_ARG); expectLastCall().andThrow(new RuntimeException("Faking an exception")); replay(testEventBus); eventBusDispatcher.dispatch("testEventWithArgument",THE_ARG); verify(testEventBus); }
@Test public void testDispatch_notExistingMethod() { replay(testEventBus); eventBusDispatcher.dispatch("notExistingMethod",THE_ARG); verify(testEventBus); } |
### Question:
ResourceBundleUiMessageSource implements IUiMessageSource { @Override public String getMessage(String key, Locale locale) { ResourceBundle bundle = getBundle(locale); if (bundle.containsKey(key)) { return bundle.getString(key); } return "{{ message missing: " + key + "}}"; } ResourceBundleUiMessageSource(String baseName); @Override String getMessage(String key, Locale locale); @Override String getMessage(String key, Object[] args, Locale locale); }### Answer:
@Test public void testGetMessageStringLocale() { String message = instance.getMessage("message.key", new Locale("de")); assertNotNull(message); assertEquals("Hier ein kleiner Text um die Sache zu erläutern.", message); }
@Test public void testGetMessageStringLocaleDefault() { String message = instance.getMessage("message.default", new Locale("en")); assertNotNull(message); assertEquals("Dieser Text steht nur in deutsch", message); }
@Test public void testGetMessageStringObjectArrayLocale() { String message = instance.getMessage("message.args", new Object[] {"PARAM"}, new Locale("de")); assertNotNull(message); assertEquals("Hier eine Nachricht mit Parametern... PARAM wurde eingegeben.", message); } |
### Question:
MethodHandler implements TargetHandler { @Override public String getTargetNamespace() { return "urn:org.vaadin.mvp.uibinder.method"; } MethodHandler(ComponentHandler ch); @Override String getTargetNamespace(); @Override void handleElementOpen(String uri, String name); @Override void handleElementClose(); @Override void handleAttribute(String name, Object value); }### Answer:
@Test public void getTargetNamespace() { assertEquals("urn:org.vaadin.mvp.uibinder.method", instance.getTargetNamespace()); } |
### Question:
MethodHandler implements TargetHandler { @Override public void handleElementOpen(String uri, String name) { method = findMethod(ch.getCurrent().getClass(), name); if (method == null) { throw new IllegalArgumentException("The method " + name + " is missing in " + ch.getCurrent().getClass()); } ch.setCurrentMethod(method); } MethodHandler(ComponentHandler ch); @Override String getTargetNamespace(); @Override void handleElementOpen(String uri, String name); @Override void handleElementClose(); @Override void handleAttribute(String name, Object value); }### Answer:
@Test public void handleElementOpen() { instance.handleElementOpen("", "addComponent"); Method m = ch.getCurrentMethod(); assertNotNull(m); assertEquals("addComponent", m.getName()); assertEquals(1, m.getParameterTypes().length); }
@Test (expected = IllegalArgumentException.class) public void handleElementOpenFail() { instance.handleElementOpen("", "nirvanaMethod"); } |
### Question:
MethodHandler implements TargetHandler { protected Method findMethod(Class<?> clazz, String name) { Class<?> searchType = clazz; while (searchType != null) { Method[] methods = (searchType.isInterface() ? searchType.getMethods() : searchType.getDeclaredMethods()); for (Method method : methods) { if (name.equals(method.getName()) && method.getParameterTypes().length == 1 && Component.class.isAssignableFrom(method.getParameterTypes()[0])) { return method; } } searchType = searchType.getSuperclass(); } return null; } MethodHandler(ComponentHandler ch); @Override String getTargetNamespace(); @Override void handleElementOpen(String uri, String name); @Override void handleElementClose(); @Override void handleAttribute(String name, Object value); }### Answer:
@Test public void findMethod() throws SecurityException, NoSuchMethodException { Method m = instance.findMethod(VerticalLayout.class, "addComponent"); assertNotNull(m); assertEquals("addComponent", m.getName()); assertEquals(1, m.getParameterTypes().length); }
@Test public void findMethodNotFound() throws SecurityException, NoSuchMethodException { Method m = instance.findMethod(VerticalLayout.class, "nirvanaMethod"); assertNull(m); } |
### Question:
EventBusManager { public <T extends EventBus> T getEventBus(Class<T> busType) { if (isPrivateEventBus(busType)) { throw new IllegalArgumentException("The bus " + busType + " is marked as private and it can be retrieved only from his presenter"); } assertEventBus(busType); EventBus eventBus = eventBusses.get(busType); return busType.cast(eventBus); } EventBusManager(); T register(Class<T> busType, Object subscriber); T register(Class<T> busType, Object subscriber,EventBus parentEventBus); void addSubscriber(Object subscriber); T getEventBus(Class<T> busType); }### Answer:
@Test(expected = IllegalArgumentException.class) public void testGetEventBus_privateEventBus_NotSupported() { eventBusManager.getEventBus(StubPrivateEventBus.class); }
@Test public void testGetEventBus_NonPrivateEventBus_Supported() { eventBusManager.getEventBus(StubEventBus.class); } |
### Question:
EventBusManager { public <T extends EventBus> T register(Class<T> busType, Object subscriber) { return this.register(busType,subscriber,null); } EventBusManager(); T register(Class<T> busType, Object subscriber); T register(Class<T> busType, Object subscriber,EventBus parentEventBus); void addSubscriber(Object subscriber); T getEventBus(Class<T> busType); }### Answer:
@Test public void testRegister_NonPrivateEventBus_mustReturnSameBus() { EventBus eventBus = eventBusManager.register(StubEventBus.class,new Object()); EventBus eventBus2 = eventBusManager.register(StubEventBus.class,new Object()); Assert.assertSame("Different event bus instances",eventBus,eventBus2); }
@Test public void testRegister_NonPrivateEventBus_mustReturnDifferentBus() { EventBus eventBus = eventBusManager.register(StubPrivateEventBus.class,new Object()); EventBus eventBus2 = eventBusManager.register(StubPrivateEventBus.class,new Object()); Assert.assertNotSame("Same event bus instances",eventBus,eventBus2); } |
### Question:
SpringPresenterFactory extends AbstractPresenterFactory implements ApplicationContextAware { @SuppressWarnings("unchecked") public IPresenter<?, ? extends EventBus> create(Object name,EventBus parentEventBus) { if (!(name instanceof String)) { throw new IllegalArgumentException("Argument is expected to be a bean name (string)"); } String beanName = (String) name; if (applicationContext.containsBean(beanName)) { IPresenter p = applicationContext.getBean(beanName, IPresenter.class); p.setApplication(application); p.setMessageSource(messageSource); Presenter def = p.getClass().getAnnotation(Presenter.class); if (def == null) { throw new IllegalArgumentException("Missing @Presenter annotation on bean '" + beanName + "'"); } EventBus eventBus = createEventBus((Class<IPresenter>) p.getClass(), p,parentEventBus); p.setEventBus(eventBus); try { Object view = viewFactory.createView(eventBusManager, p, def.view(), locale); p.setView(view); } catch (ViewFactoryException e) { logger.error("Failed to create view for presenter", e); } p.bind(); return p; } throw new IllegalArgumentException("No presenter is defined for name: " + name); } @Override void setApplicationContext(ApplicationContext applicationContext); @SuppressWarnings("unchecked") IPresenter<?, ? extends EventBus> create(Object name,EventBus parentEventBus); @Override IViewFactory getViewFactory(); }### Answer:
@Test public void testCreate() { IPresenter<?, ? extends EventBus> presenter = instance.createPresenter("spring"); assertNotNull("created presenter is null", presenter); assertNotNull("presenters view is null", presenter.getView()); assertTrue("presenters bind() method has not been called", ((SpringPresenter)presenter).bound); assertNotNull("presenter eventbus is null", presenter.getEventBus()); } |
### Question:
EventDeserializer extends AbstractAttributeStoreDeserializer<BaseEvent, EventBuilder> { @Override public BaseEvent build(EventBuilder entityBuilder) { return (BaseEvent) entityBuilder.build(); } @Override EventBuilder deserialize(JsonNode root); @Override BaseEvent build(EventBuilder entityBuilder); }### Answer:
@Test public void testBasicDeserialization() throws Exception { Event event = create("type", "id", 0) .attr("key", "value") .attr("key1", "valu1") .build(); String json = objectMapper.writeValueAsString(event); Event actualEntity = objectMapper.readValue(json, Event.class); assertEquals(actualEntity.getId(), event.getId()); assertEquals(actualEntity.getTimestamp(), event.getTimestamp()); assertEquals(new HashSet<>(actualEntity.getAttributes()), new HashSet<>(event.getAttributes())); }
@Test public void testBasicDeserialization2() throws Exception { Event event = create("type", "id", currentTimeMillis()) .attr("key", "value") .attr("key1", "valu1") .build(); String json = objectMapper.writeValueAsString(event); Event actualEntity = objectMapper.readValue(json, Event.class); assertEquals(actualEntity.getId(), event.getId()); assertEquals(actualEntity.getTimestamp(), event.getTimestamp()); assertEquals(new HashSet<>(actualEntity.getAttributes()), new HashSet<>(event.getAttributes())); } |
### Question:
Iterators2 { public static <T> Iterator<T> distinct(final Iterator<T> iterator) { requireNonNull(iterator); return new AbstractIterator<T>() { private final PeekingIterator<T> peekingIterator = peekingIterator(iterator); private T curr = null; @Override protected T computeNext() { while (peekingIterator.hasNext() && Objects.equals(curr, peekingIterator.peek())) { peekingIterator.next(); } if (!peekingIterator.hasNext()) return endOfData(); curr = peekingIterator.next(); return curr; } }; } private Iterators2(); static Iterator<T> distinct(final Iterator<T> iterator); static Iterator<List<T>> groupBy(final Iterator<? extends T> iterator, final Function<? super T, ?> groupingFunction); }### Answer:
@Test public void distinctTest() throws Exception { Iterator<Integer> distinct = distinct(asList(1, 1, 2, 2, 3, 3, 3, 4, 5, 6, 7, 7, 7).iterator()); assertTrue(elementsEqual(asList(1, 2, 3, 4, 5, 6, 7).iterator(), distinct)); assertFalse(distinct.hasNext()); }
@Test(expected = NullPointerException.class) public void distinctNullIteratorTest() { distinct(null); } |
### Question:
MoreInetAddresses { public static InetAddress forString(String ipString) { requireNonNull(ipString); InetAddress address = InetAddresses.forString(ipString); if (address instanceof Inet4Address && ipString.contains(":")) return getIPv4MappedIPv6Address((Inet4Address) address); return address; } private MoreInetAddresses(); static InetAddress forString(String ipString); static Inet4Address forIPv4String(String ipString); static Inet6Address forIPv6String(String ipString); static boolean isMappedIPv4Address(Inet6Address ip); static Inet4Address getMappedIPv4Address(Inet6Address ip); static boolean hasEmbeddedIPv4ClientAddress(Inet6Address ip); static Inet4Address getEmbeddedIPv4ClientAddress(Inet6Address ip); static Inet6Address getIPv4MappedIPv6Address(Inet4Address ip); static Inet6Address getIPV4CompatIPv6Address(Inet4Address ip); static Inet4Address increment(Inet4Address ip); static Inet6Address increment(Inet6Address ip); static Inet4Address decrement(Inet4Address ip); static Inet6Address decrement(Inet6Address ip); static CidrInfo parseCIDR(String cidr); }### Answer:
@Test public void forStringTest() { InetAddress address; address = MoreInetAddresses.forString("1.2.3.4"); assertTrue(address instanceof Inet4Address); assertEquals("1.2.3.4", toAddrString(address)); address = MoreInetAddresses.forString("::1.2.3.4"); assertTrue(address instanceof Inet6Address); assertEquals("::102:304", toAddrString(address)); address = MoreInetAddresses.forString("::ffff:1.2.3.4"); assertTrue(address instanceof Inet6Address); assertEquals("::ffff:102:304", toAddrString(address)); }
@Test(expected = NullPointerException.class) public void forStringNullTest() { MoreInetAddresses.forString(null); } |
### Question:
EntityDeserializer extends AbstractAttributeStoreDeserializer<BaseEntity, EntityBuilder> { @Override public BaseEntity build(EntityBuilder entityBuilder) { return (BaseEntity)entityBuilder.build(); } @Override EntityBuilder deserialize(JsonNode root); @Override BaseEntity build(EntityBuilder entityBuilder); }### Answer:
@Test public void testBasicDeserialization() throws Exception { Entity entity = create("type", "id") .attr("key", "value") .build(); String json = objectMapper.writeValueAsString(entity); Entity actualEntity = objectMapper.readValue(json, Entity.class); assertEquals(actualEntity.getType(), entity.getType()); assertEquals(actualEntity.getId(), entity.getId()); assertEquals(new HashSet<>(actualEntity.getAttributes()), new HashSet<>(entity.getAttributes())); } |
### Question:
MoreInetAddresses { public static Inet4Address forIPv4String(String ipString) { requireNonNull(ipString); try{ InetAddress parsed = forString(ipString); if (parsed instanceof Inet4Address) return (Inet4Address) parsed; } catch(Exception ignored){} throw new IllegalArgumentException(format("Invalid IPv4 representation: %s", ipString)); } private MoreInetAddresses(); static InetAddress forString(String ipString); static Inet4Address forIPv4String(String ipString); static Inet6Address forIPv6String(String ipString); static boolean isMappedIPv4Address(Inet6Address ip); static Inet4Address getMappedIPv4Address(Inet6Address ip); static boolean hasEmbeddedIPv4ClientAddress(Inet6Address ip); static Inet4Address getEmbeddedIPv4ClientAddress(Inet6Address ip); static Inet6Address getIPv4MappedIPv6Address(Inet4Address ip); static Inet6Address getIPV4CompatIPv6Address(Inet4Address ip); static Inet4Address increment(Inet4Address ip); static Inet6Address increment(Inet6Address ip); static Inet4Address decrement(Inet4Address ip); static Inet6Address decrement(Inet6Address ip); static CidrInfo parseCIDR(String cidr); }### Answer:
@Test public void forIpv4StringTest() { Inet4Address address; address = forIPv4String("1.2.3.4"); assertEquals("1.2.3.4", toAddrString(address)); }
@Test(expected = NullPointerException.class) public void forIpv4StringNullTest() { forIPv4String(null); }
@Test(expected = IllegalArgumentException.class) public void forIpv4StringWithIpv6Test() { forIPv4String("::1.2.3.4"); }
@Test(expected = IllegalArgumentException.class) public void forIpv4StringWithMappedIpv4Test() { forIPv4String("::ffff:1.2.3.4"); } |
### Question:
MoreInetAddresses { public static Inet6Address forIPv6String(String ipString) { requireNonNull(ipString); try{ InetAddress parsed = forString(ipString); if (parsed instanceof Inet6Address) return (Inet6Address) parsed; } catch(Exception ignored){} throw new IllegalArgumentException(format("Invalid IPv6 representation: %s", ipString)); } private MoreInetAddresses(); static InetAddress forString(String ipString); static Inet4Address forIPv4String(String ipString); static Inet6Address forIPv6String(String ipString); static boolean isMappedIPv4Address(Inet6Address ip); static Inet4Address getMappedIPv4Address(Inet6Address ip); static boolean hasEmbeddedIPv4ClientAddress(Inet6Address ip); static Inet4Address getEmbeddedIPv4ClientAddress(Inet6Address ip); static Inet6Address getIPv4MappedIPv6Address(Inet4Address ip); static Inet6Address getIPV4CompatIPv6Address(Inet4Address ip); static Inet4Address increment(Inet4Address ip); static Inet6Address increment(Inet6Address ip); static Inet4Address decrement(Inet4Address ip); static Inet6Address decrement(Inet6Address ip); static CidrInfo parseCIDR(String cidr); }### Answer:
@Test public void forIpv6StringTest() { Inet6Address address; address = forIPv6String("::1.2.3.4"); assertEquals("::102:304", toAddrString(address)); address = forIPv6String("::ffff:1.2.3.4"); assertEquals("::ffff:102:304", toAddrString(address)); }
@Test(expected = NullPointerException.class) public void forIpv6StringNullTest() { forIPv6String(null); }
@Test(expected = IllegalArgumentException.class) public void forIpv6StringWithIpv4Test() { forIPv6String("1.2.3.4"); } |
### Question:
Iterables2 { public static <T> Iterable<T> distinct(final Iterable<T> iterable) { requireNonNull(iterable); return () -> Iterators2.distinct(iterable.iterator()); } private Iterables2(); static Iterable<T> simpleIterable(final Iterable<T> iterable); static Iterable<T> distinct(final Iterable<T> iterable); static Iterable<List<T>> groupBy(final Iterable<? extends T> iterable, final Function<? super T, ?> groupingFunction); }### Answer:
@Test public void distinctTest() throws Exception { Iterable<Integer> distinct = distinct(asList(1, 1, 2, 2, 3, 3, 3, 4, 5, 6, 7, 7, 7)); assertEquals(asList(1, 2, 3, 4, 5, 6, 7), newArrayList(distinct)); }
@Test(expected = NullPointerException.class) public void distinctNullIteratorTest() { distinct(null); } |
### Question:
MoreInetAddresses { public static boolean hasEmbeddedIPv4ClientAddress(Inet6Address ip) { return isMappedIPv4Address(ip) || InetAddresses.hasEmbeddedIPv4ClientAddress(ip); } private MoreInetAddresses(); static InetAddress forString(String ipString); static Inet4Address forIPv4String(String ipString); static Inet6Address forIPv6String(String ipString); static boolean isMappedIPv4Address(Inet6Address ip); static Inet4Address getMappedIPv4Address(Inet6Address ip); static boolean hasEmbeddedIPv4ClientAddress(Inet6Address ip); static Inet4Address getEmbeddedIPv4ClientAddress(Inet6Address ip); static Inet6Address getIPv4MappedIPv6Address(Inet4Address ip); static Inet6Address getIPV4CompatIPv6Address(Inet4Address ip); static Inet4Address increment(Inet4Address ip); static Inet6Address increment(Inet6Address ip); static Inet4Address decrement(Inet4Address ip); static Inet6Address decrement(Inet6Address ip); static CidrInfo parseCIDR(String cidr); }### Answer:
@Test public void hasEmbeddedIPv4ClientAddressTest() { assertTrue(MoreInetAddresses.hasEmbeddedIPv4ClientAddress(forIPv6String("::ffff:1.2.3.4"))); assertTrue(MoreInetAddresses.hasEmbeddedIPv4ClientAddress(forIPv6String("::1.2.3.4"))); assertTrue(MoreInetAddresses.hasEmbeddedIPv4ClientAddress(forIPv6String("2002:102:304::"))); assertFalse(MoreInetAddresses.hasEmbeddedIPv4ClientAddress(forIPv6String("1::1.2.3.4"))); }
@Test(expected = NullPointerException.class) public void hasEmbeddedIPv4ClientAddressNullTest() { MoreInetAddresses.hasEmbeddedIPv4ClientAddress(null); } |
### Question:
MoreInetAddresses { public static Inet6Address getIPv4MappedIPv6Address(Inet4Address ip) { byte[] from = ip.getAddress(); byte[] bytes = new byte[] { 0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0, 0x0,0x0,(byte)0xff,(byte)0xff, from[0],from[1],from[2],from[3] }; return getInet6Address(bytes); } private MoreInetAddresses(); static InetAddress forString(String ipString); static Inet4Address forIPv4String(String ipString); static Inet6Address forIPv6String(String ipString); static boolean isMappedIPv4Address(Inet6Address ip); static Inet4Address getMappedIPv4Address(Inet6Address ip); static boolean hasEmbeddedIPv4ClientAddress(Inet6Address ip); static Inet4Address getEmbeddedIPv4ClientAddress(Inet6Address ip); static Inet6Address getIPv4MappedIPv6Address(Inet4Address ip); static Inet6Address getIPV4CompatIPv6Address(Inet4Address ip); static Inet4Address increment(Inet4Address ip); static Inet6Address increment(Inet6Address ip); static Inet4Address decrement(Inet4Address ip); static Inet6Address decrement(Inet6Address ip); static CidrInfo parseCIDR(String cidr); }### Answer:
@Test public void getIPv4MappedIPv6AddressTest() { assertEquals("::ffff:102:304", toAddrString(MoreInetAddresses.getIPv4MappedIPv6Address(forIPv4String("1.2.3.4")))); }
@Test(expected = NullPointerException.class) public void getIPv4MappedIPv6AddressNullTest() { MoreInetAddresses.getIPv4MappedIPv6Address(null); } |
### Question:
MoreInetAddresses { public static Inet6Address getIPV4CompatIPv6Address(Inet4Address ip) { byte[] from = ip.getAddress(); byte[] bytes = new byte[] { 0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0, from[0],from[1],from[2],from[3] }; return getInet6Address(bytes); } private MoreInetAddresses(); static InetAddress forString(String ipString); static Inet4Address forIPv4String(String ipString); static Inet6Address forIPv6String(String ipString); static boolean isMappedIPv4Address(Inet6Address ip); static Inet4Address getMappedIPv4Address(Inet6Address ip); static boolean hasEmbeddedIPv4ClientAddress(Inet6Address ip); static Inet4Address getEmbeddedIPv4ClientAddress(Inet6Address ip); static Inet6Address getIPv4MappedIPv6Address(Inet4Address ip); static Inet6Address getIPV4CompatIPv6Address(Inet4Address ip); static Inet4Address increment(Inet4Address ip); static Inet6Address increment(Inet6Address ip); static Inet4Address decrement(Inet4Address ip); static Inet6Address decrement(Inet6Address ip); static CidrInfo parseCIDR(String cidr); }### Answer:
@Test public void getIPv4CompatIPv6AddressTest() { assertEquals("::102:304", toAddrString(MoreInetAddresses.getIPV4CompatIPv6Address(forIPv4String("1.2.3.4")))); }
@Test(expected = NullPointerException.class) public void getIPv4CompatIPv6AddressNullTest() { MoreInetAddresses.getIPV4CompatIPv6Address(null); } |
### Question:
IP implements Serializable { @Override public String toString() { return toAddrString(address); } protected IP(T address); @SuppressWarnings("unchecked") T getAddress(); byte[] toByteArray(); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); }### Answer:
@Test public void ipv4ToStringTest() { IPv4 ip = new IPv4(forIPv4String("1.2.3.4")); assertEquals("1.2.3.4", ip.toString()); }
@Test public void ipv6ToStringTest() { IPv6 ip = new IPv6(forIPv6String("::1.2.3.4")); assertEquals("::102:304", ip.toString()); ip = new IPv6(forIPv6String("ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff")); assertEquals("ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff", ip.toString()); ip = new IPv6(forIPv6String("1234:0000:0000:0000:0000:0000:0000:1234")); assertEquals("1234::1234", ip.toString()); } |
### Question:
QueryBuilder { public QueryBuilder eq(String type, Object value) { checkFinished(); if (this.current == null) { this.current = new AndNode(); finished = true; } EqualsLeaf equalsLeaf = new EqualsLeaf<>(type, value, current); this.current.addChild(equalsLeaf); return this; } protected QueryBuilder(); protected QueryBuilder(ParentNode current, QueryBuilder parentBuilder); static QueryBuilder create(); QueryBuilder and(); QueryBuilder or(); Node build(); QueryBuilder eq(String type, Object value); QueryBuilder has(String key); QueryBuilder hasNot(String key); QueryBuilder in(String key, Collection<Object> values); QueryBuilder in(String key, Object... values); QueryBuilder notIn(String key, Collection<Object> values); QueryBuilder notIn(String key, Object... values); QueryBuilder notEq(String type, Object value); QueryBuilder lessThan(String type, Object value); QueryBuilder lessThanEq(String type, Object value); QueryBuilder greaterThan(String type, Object value); QueryBuilder greaterThanEq(String type, Object value); QueryBuilder range(String type, Object start, Object end); QueryBuilder end(); }### Answer:
@Test public void testEq() throws Exception { Node build = QueryBuilder.create().eq("feedName", "netflowv9").build(); StringWriter writer = new StringWriter(); build.accept(new PrintNodeVisitor(writer)); assertEquals("AndNode(Equals[feedName,netflowv9],),", writer.toString()); } |
### Question:
CollapseParentClauseVisitor implements NodeVisitor { @Override public void end(ParentNode node) { } @Override void begin(ParentNode node); @Override void end(ParentNode node); @Override void visit(Leaf node); }### Answer:
@Test public void testCollapseAndAndChildren() throws Exception { StringWriter writer = new StringWriter(); Node node = QueryBuilder.create().and().and().eq("k1", "v1").eq("k2", "v2").end().end().build(); node.accept(new PrintNodeVisitor(writer)); writer.append('\n'); node.accept(new CollapseParentClauseVisitor()); node.accept(new PrintNodeVisitor(writer)); writer.append('\n'); }
@Test public void testCollapseAndAndOrChildren() throws Exception { StringWriter writer = new StringWriter(); Node node = QueryBuilder.create().and().and().eq("k1", "v1").eq("k2", "v2").end().or().eq("k3", "v3").eq("k4", "v4").end().end().build(); node.accept(new PrintNodeVisitor(writer)); writer.append('\n'); node.accept(new CollapseParentClauseVisitor()); node.accept(new PrintNodeVisitor(writer)); writer.append('\n'); } |
### Question:
LessThanEqualsCriteria extends ComparableTermValueCriteria<T> { @Override public boolean test(AttributeStore obj) { for (Attribute attribute : obj.getAttributes(getTerm())) { if (getComparator().compare((T)(attribute.getValue()), getValue()) <= 0) return true; } return false; } LessThanEqualsCriteria(String term, T value, Comparator<T> comparator, ParentCriteria parentCriteria); @Override boolean test(AttributeStore obj); @Override Criteria clone(ParentCriteria parentCriteria); @Override String toString(); }### Answer:
@Test public void test() { LessThanEqualsCriteria criteria = new LessThanEqualsCriteria<>("key1", 5, naturalOrder(), null); EntityBuilder entity = EntityBuilder.create("type", "id"); assertFalse(criteria.test(entity.build())); entity = entity.attr("key1", 10); assertFalse(criteria.test(entity.build())); entity = entity.attr("key1", 5); assertTrue(criteria.test(entity.build())); entity = entity.attr("key1", 4); assertTrue(criteria.test(entity.build())); } |
### Question:
EqualsCriteria extends ComparableTermValueCriteria<T> { @Override public boolean test(AttributeStore obj) { for (Attribute attribute : obj.getAttributes(getTerm())) { if (getComparator().compare((T)(attribute.getValue()), getValue()) == 0) return true; } return false; } EqualsCriteria(String term, T value, Comparator<T> comparator, ParentCriteria parentCriteria); @Override boolean test(AttributeStore obj); @Override Criteria clone(ParentCriteria parentCriteria); @Override String toString(); }### Answer:
@Test public void testEquals() { Criteria eq = new EqualsCriteria<>("key1", "val1", naturalOrder(), null); EntityBuilder entity = EntityBuilder.create("type", "id") .attr("key1", "val1"); assertTrue(eq.test(entity.build())); }
@Test public void testNotEquals() { Criteria eq = new EqualsCriteria<>("key1", "val1", naturalOrder(), null); EntityBuilder entity = EntityBuilder.create("type", "id") .attr("key1", "val2"); assertFalse(eq.test(entity.build())); } |
### Question:
NotEqualsCriteria extends ComparableTermValueCriteria<T> { @Override public boolean test(AttributeStore obj) { for (Attribute attribute : obj.getAttributes(getTerm())) { if (getComparator().compare((T)(attribute.getValue()), getValue()) != 0) return true; } return false; } NotEqualsCriteria(String term, T value, Comparator<T> comparator, ParentCriteria parentCriteria); @Override boolean test(AttributeStore obj); @Override Criteria clone(ParentCriteria parentCriteria); @Override String toString(); }### Answer:
@Test public void testNotEquals() { Criteria eq = new NotEqualsCriteria<>("key1", "val1", naturalOrder(), null); EntityBuilder entity = EntityBuilder.create("type", "id") .attr("key1", "val2"); assertTrue(eq.test(entity.build())); }
@Test public void testEquals() { Criteria eq = new NotEqualsCriteria<>("key1", "val1", naturalOrder(), null); EntityBuilder entity = EntityBuilder.create("type", "id") .attr("key1", "val1"); assertFalse(eq.test(entity.build())); } |
### Question:
Iterables2 { public static <T> Iterable<List<T>> groupBy(final Iterable<? extends T> iterable, final Function<? super T, ?> groupingFunction) { requireNonNull(iterable); requireNonNull(groupingFunction); return () -> Iterators2.groupBy(iterable.iterator(), groupingFunction); } private Iterables2(); static Iterable<T> simpleIterable(final Iterable<T> iterable); static Iterable<T> distinct(final Iterable<T> iterable); static Iterable<List<T>> groupBy(final Iterable<? extends T> iterable, final Function<? super T, ?> groupingFunction); }### Answer:
@Test public void groupByTest() { List<Integer> testdata = asList(0, 1, 2, 3, 4, 5, 6, 7, 8, 9); Iterable<List<Integer>> grouped = groupBy(testdata, input -> input / 5); assertEquals(2, size(grouped)); assertEquals(asList(0, 1, 2, 3, 4), get(grouped, 0)); assertEquals(asList(5, 6, 7, 8, 9), get(grouped, 1)); grouped = groupBy(testdata, input -> null); assertEquals(1, size(grouped)); assertEquals(testdata, get(grouped, 0)); grouped = groupBy(testdata, input -> input); assertEquals(10, size(grouped)); for (int i = 0; i< testdata.size(); i++) { List<Integer> group = get(grouped, i); assertEquals(1, group.size()); assertEquals(new Integer(i), group.get(0)); } }
@Test(expected = NullPointerException.class) public void groupByNullIteratorTest() { groupBy(null, input -> null); }
@Test(expected = NullPointerException.class) public void groupByNullEquivTest() { groupBy(emptyList(), null); } |
### Question:
LessThanCriteria extends ComparableTermValueCriteria<T> { @Override public boolean test(AttributeStore obj) { for (Attribute attribute : obj.getAttributes(getTerm())) { if (getComparator().compare((T)(attribute.getValue()), getValue()) < 0) return true; } return false; } LessThanCriteria(String term, T value, Comparator<T> comparator, ParentCriteria parentCriteria); @Override boolean test(AttributeStore obj); @Override Criteria clone(ParentCriteria parentCriteria); @Override String toString(); }### Answer:
@Test public void test() { LessThanCriteria criteria = new LessThanCriteria<>("key1", 5, naturalOrder(), null); EntityBuilder entity = EntityBuilder.create("type", "id"); assertFalse(criteria.test(entity.build())); entity = entity.attr("key1", 10); assertFalse(criteria.test(entity.build())); entity = entity.attr("key1", 4); assertTrue(criteria.test(entity.build())); } |
### Question:
HasNotCriteria extends TermCriteria { @Override public boolean test(AttributeStore obj) { if(obj.get(getTerm()) == null) return true; Collection<Attribute> attributes = obj.getAttributes(getTerm()); if(attributes.size() > 0 && clazz == null) return false; for(Attribute attribute : attributes) { if(attribute.getValue().getClass().equals(clazz)) return false; } return true; } HasNotCriteria(String term, Class<T> clazz, ParentCriteria parentCriteria); HasNotCriteria(String term, ParentCriteria parentCriteria); @Override boolean test(AttributeStore obj); @Override Criteria clone(ParentCriteria parentCriteria); @Override String toString(); }### Answer:
@Test public void test() { HasNotCriteria criteria = new HasNotCriteria("key1", null); EntityBuilder entity = EntityBuilder.create("type", "id") .attr("key2", "val2"); assertTrue(criteria.test(entity.build())); entity = entity.attr("key1", "val1"); assertFalse(criteria.test(entity.build())); } |
### Question:
RangeCriteria extends TermCriteria { @Override public boolean test(AttributeStore obj) { for (Attribute attribute : obj.getAttributes(getTerm())) { if (comparator.compare((T)(attribute.getValue()), start) >= 0 && comparator.compare((T)(attribute.getValue()), end) <= 0) { return true; } } return false; } RangeCriteria(String term, T start, T end, Comparator<T> comparator, ParentCriteria parentCriteria); @Override boolean test(AttributeStore obj); @Override Criteria clone(ParentCriteria parentCriteria); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }### Answer:
@Test public void test() { RangeCriteria criteria = new RangeCriteria<>("key1", 5, 10, naturalOrder(), null); EntityBuilder entity = EntityBuilder.create("type", "id"); assertFalse(criteria.test(entity.build())); entity = entity.attr("key1", 11); assertFalse(criteria.test(entity.build())); entity = entity.attr("key1", 4); assertFalse(criteria.test(entity.build())); entity = entity.attr("key1", 5); assertTrue(criteria.test(entity.build())); entity = entity.attr("key1", 6); assertTrue(criteria.test(entity.build())); }
@Test public void acceptAnyTupleWithinRange() { RangeCriteria criteria = new RangeCriteria<>("key1", 5, 10, naturalOrder(), null); EntityBuilder entity = EntityBuilder.create("type", "id") .attr("key1", 4) .attr("key1", 6); assertTrue(criteria.test(entity.build())); } |
### Question:
NodeUtils { public static Criteria criteriaFromNode(Node node) { return criteriaFromNode(node, naturalOrder(), null); } NodeUtils(); static boolean isLeaf(Node node); static boolean isEmpty(Node node); static boolean parentContainsOnlyLeaves(ParentNode parentNode); static boolean isRangeLeaf(Leaf leaf); static Criteria criteriaFromNode(Node node); static Criteria criteriaFromNode(Node node, Comparator rangeComparator); }### Answer:
@Test public void testCriteriaFromNode_fullTree() { Node node = QueryBuilder.create().or().and().eq("key1", "val1").eq("key2", "val2").end().eq("key3", "val3").end().build(); Criteria criteria = NodeUtils.criteriaFromNode(node); assertTrue(criteria instanceof OrCriteria); assertTrue(criteria.children().get(0) instanceof AndCriteria); assertTrue(criteria.children().get(0).children().get(0) instanceof EqualsCriteria); assertTrue(criteria.children().get(0).children().get(1) instanceof EqualsCriteria); assertTrue(criteria.children().get(1).children().get(0) instanceof EqualsCriteria); } |
### Question:
AbstractCloseableIterable implements CloseableIterable<T> { @Override public void close() { if (!closed) { doClose(); closed = true; } } @Override void close(); @Override Iterator<T> iterator(); }### Answer:
@SuppressWarnings({"rawtypes", "unchecked"}) @Test public void closeTest() throws Exception { MockIterable iterable = new MockIterable(emptyList()); iterable.close(); assertTrue(iterable.isClosed()); } |
### Question:
GlobalIndexExpirationFilter extends Filter { @Override public boolean accept(Key k, Value v) { long expiration = new GlobalIndexValue(v).getExpiration(); return !MetadataExpirationFilter.shouldExpire(expiration, k.getTimestamp()); } @Override boolean accept(Key k, Value v); }### Answer:
@Test public void testExpiration() { GlobalIndexExpirationFilter expirationFilter = new GlobalIndexExpirationFilter(); Key key = new Key(); key.setTimestamp(System.currentTimeMillis() - 1000); assertTrue(expirationFilter.accept(key, new GlobalIndexValue(1, 100000).toValue())); assertFalse(expirationFilter.accept(key, new GlobalIndexValue(1, 1).toValue())); assertTrue(expirationFilter.accept(key, new GlobalIndexValue(1, -1).toValue())); assertTrue(expirationFilter.accept(key, new Value("1".getBytes()))); } |
### Question:
EventWritable implements Writable, Settable<Event>, Gettable<Event> { public Event get() { return entry; } EventWritable(); EventWritable(Event entry); void setAttributeWritable(AttributeWritable sharedAttributeWritable); @Override void write(DataOutput dataOutput); @Override void readFields(DataInput dataInput); void set(Event entry); Event get(); }### Answer:
@Test public void testSerializesAndDeserializes() throws IOException { Event event = EventBuilder.create("", "id", System.currentTimeMillis()) .attr(new Attribute("key", "val", ImmutableMap.of("metaKey", "metaVal"))).build(); byte[] serialized = serialize(new EventWritable(event)); Event actual = asWritable(serialized, EventWritable.class).get(); assertEquals(event, actual); } |
### Question:
AttributeWritable implements Writable, Gettable<Attribute>, Settable<Attribute> { @Override public Attribute get() { return attribute; } AttributeWritable(); AttributeWritable(Attribute attribute); void setTypeRegistry(TypeRegistry<String> registry); @Override void write(DataOutput dataOutput); @Override void readFields(DataInput dataInput); @Override Attribute get(); @Override void set(Attribute item); }### Answer:
@Test public void testSerializesAndDeserializes() throws IOException { Attribute attribute = new Attribute("key", "val", ImmutableMap.of("metaKey", "metaVal")); byte[] serialized = serialize(new AttributeWritable(attribute)); Attribute actual = asWritable(serialized, AttributeWritable.class).get(); assertEquals(attribute, actual); } |
### Question:
RangeSplitterVisitor implements NodeVisitor { @Override public void end(ParentNode parentNode) { } @Override void begin(ParentNode parentNode); @Override void end(ParentNode parentNode); @Override void visit(Leaf leaf); }### Answer:
@Test public void test() { Node query = QueryBuilder.create().and().eq("key1", "val1").range("key2", 0, 5).end().build(); query.accept(new RangeSplitterVisitor()); assertTrue(query instanceof AndNode); assertEquals(3, query.children().size()); assertTrue(query.children().get(0) instanceof EqualsLeaf); assertTrue(query.children().get(1) instanceof GreaterThanEqualsLeaf); assertTrue(query.children().get(2) instanceof LessThanEqualsLeaf); query = QueryBuilder.create().or().eq("key1", "val1").range("key2", 0, 5).end().build(); query.accept(new RangeSplitterVisitor()); assertTrue(query instanceof OrNode); assertEquals(2, query.children().size()); assertTrue(query.children().get(0) instanceof EqualsLeaf); assertTrue(query.children().get(1) instanceof AndNode); assertTrue(query.children().get(1).children().get(0) instanceof GreaterThanEqualsLeaf); assertTrue(query.children().get(1).children().get(1) instanceof LessThanEqualsLeaf); } |
### Question:
ExtractInNotInVisitor implements NodeVisitor { @Override public void end(ParentNode parentNode) { } @Override void begin(ParentNode parentNode); @Override void end(ParentNode parentNode); @Override void visit(Leaf leaf); }### Answer:
@Test public void testIn() { Node query = QueryBuilder.create().in("key", "hello", "goodbye").build(); Node expected = QueryBuilder.create().and().or().eq("key", "hello").eq("key", "goodbye").end().end().build(); query.accept(new ExtractInNotInVisitor()); assertEquals(expected, query); } |
### Question:
EntityWritable implements WritableComparable, Settable<Entity>, Gettable<Entity> { public Entity get() { return entity; } EntityWritable(); EntityWritable(Entity entity); void setAttributeWritable(AttributeWritable sharedAttributeWritable); @Override void write(DataOutput dataOutput); @Override void readFields(DataInput dataInput); void set(Entity entity); Entity get(); @Override int compareTo(Object o); }### Answer:
@Test public void testSerializesAndDeserializes() throws IOException { Entity entity = EntityBuilder.create("type", "id") .attr(new Attribute("key", "val", ImmutableMap.of("metaKey", "metaVal"))) .build(); byte[] serialized = serialize(new EntityWritable(entity)); Entity actual = asWritable(serialized, EntityWritable.class).get(); assertEquals(entity, actual); } |
### Question:
Metric implements Writable { public double getVariance() { BigDecimal sumSquare = new BigDecimal(this.sumSquare); if(count < 2) return 0; BigDecimal sumSquareDivideByCount = sumSquare.divide(valueOf(count), 15, FLOOR); return (sumSquareDivideByCount.subtract(new BigDecimal(getMean() * getMean()))).doubleValue(); } Metric(); Metric(long value); Metric(long min, long max, long sum, long count, BigInteger sumSquare); long getMin(); long getMax(); long getSum(); long getCount(); BigInteger getSumSquare(); double getMean(); double getVariance(); double getStdDev(); @Override void write(DataOutput dataOutput); @Override void readFields(DataInput dataInput); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }### Answer:
@Test public void testVariance() { Metric metric = new Metric(1); assertEquals(0.0, metric.getVariance()); metric = new Metric(1, 1, 1, 5, BigInteger.valueOf(1)); assertEquals(0.16, metric.getVariance()); metric = new Metric(1, 1, 5, 5, BigInteger.valueOf(5)); assertEquals(0.0, metric.getVariance()); } |
### Question:
FeatureRegistry { public AccumuloFeatureConfig transformForClass(Class<? extends Feature> clazz) { AccumuloFeatureConfig featureConfig = classToTransform.get(clazz); if(featureConfig == null) { for(Map.Entry<Class, AccumuloFeatureConfig> clazzes : classToTransform.entrySet()) { if(clazzes.getKey().isAssignableFrom(clazz)) { featureConfig = clazzes.getValue(); classToTransform.put(clazz, featureConfig); } } } return featureConfig; } FeatureRegistry(AccumuloFeatureConfig... transforms); AccumuloFeatureConfig transformForClass(Class<? extends Feature> clazz); Iterable<AccumuloFeatureConfig> getConfigs(); static final FeatureRegistry BASE_FEATURES; }### Answer:
@Test public void testMyTestFeatureReturns() { FeatureRegistry registry = new FeatureRegistry(new MetricFeatureConfig()); assertNotNull(registry.transformForClass(MyTestFeature.class)); } |
### Question:
MetricFeatureConfig implements AccumuloFeatureConfig<MetricFeature> { @Override public MetricFeature buildFeatureFromValue(long timestamp, String group, String type, String name, String visibility, Value value) { Metric metricFeatureVector = valueToVector.apply(value); return new MetricFeature(timestamp, group, type, name, visibility, metricFeatureVector); } @Override Class<MetricFeature> transforms(); @Override Value buildValue(MetricFeature feature); @Override MetricFeature buildFeatureFromValue(long timestamp, String group, String type, String name, String visibility, Value value); @Override String featureName(); @Override List<IteratorSetting> buildIterators(int priority); static final Function<Value, Metric> valueToVector; static final Function<Metric, Value> vectorToValue; }### Answer:
@Test public void testBuildFeatureFromValue() { Value value = new Value("1,2,3,4,5".getBytes()); long timestamp = currentTimeMillis(); String group = "group"; String type = "type"; String name = "name"; String vis = "vis"; MetricFeature feature = new MetricFeatureConfig().buildFeatureFromValue( timestamp, group, type, name, vis, value ); assertEquals(group, feature.getGroup()); assertEquals(timestamp, feature.getTimestamp()); assertEquals(type, feature.getType()); assertEquals(name, feature.getName()); assertEquals(vis, feature.getVisibility()); assertEquals(1, feature.getVector().getMin()); assertEquals(2, feature.getVector().getMax()); assertEquals(3, feature.getVector().getSum()); assertEquals(4, feature.getVector().getCount()); assertEquals(BigInteger.valueOf(5), feature.getVector().getSumSquare()); } |
### Question:
MetricFeatureConfig implements AccumuloFeatureConfig<MetricFeature> { @Override public Value buildValue(MetricFeature feature) { return vectorToValue.apply(feature.getVector()); } @Override Class<MetricFeature> transforms(); @Override Value buildValue(MetricFeature feature); @Override MetricFeature buildFeatureFromValue(long timestamp, String group, String type, String name, String visibility, Value value); @Override String featureName(); @Override List<IteratorSetting> buildIterators(int priority); static final Function<Value, Metric> valueToVector; static final Function<Metric, Value> vectorToValue; }### Answer:
@Test public void testBuildValueFromFeature() { long currentTime = currentTimeMillis(); MetricFeature feature = new MetricFeature(currentTimeMillis(), "group", "type", "name", "vis", new Metric(1)); Value value = new MetricFeatureConfig().buildValue(feature); assertEquals("1,1,1,1,1", new String(value.get())); } |
### Question:
MerkleTree implements Serializable { public Node getTopHash() { return topHash; } MerkleTree(List<T> leaves); MerkleTree(List<T> leaves, int dimensions); Node getTopHash(); Integer getDimensions(); Integer getNumLeaves(); @SuppressWarnings("rawtypes") List<T> diff(MerkleTree other); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }### Answer:
@Test public void testTreeBuilds() throws NoSuchAlgorithmException, IOException, ClassNotFoundException { List<MockLeaf> leaves = asList(leaf1, leaf2, leaf8, leaf7, leaf4); MerkleTree<MockLeaf> tree = new MerkleTree<>(leaves, 2); assertEquals("17a19db32d969668fb08f9a5491eb4fe", tree.getTopHash().getHash()); assertEquals(2, tree.getTopHash().getChildren().size()); } |
### Question:
MerkleTree implements Serializable { @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; MerkleTree<?> that = (MerkleTree<?>) o; return dimensions == that.dimensions && numLeaves == that.numLeaves && Objects.equals(topHash, that.topHash); } MerkleTree(List<T> leaves); MerkleTree(List<T> leaves, int dimensions); Node getTopHash(); Integer getDimensions(); Integer getNumLeaves(); @SuppressWarnings("rawtypes") List<T> diff(MerkleTree other); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }### Answer:
@Test public void testEquals_false() { List<MockLeaf> leaves = asList(leaf1, leaf2); List<MockLeaf> leaves2 = asList(leaf1, leaf3); MerkleTree<MockLeaf> tree = new MerkleTree<>(leaves, 2); MerkleTree<MockLeaf> tree2 = new MerkleTree<>(leaves2, 2); assertFalse(tree.equals(tree2)); assertFalse(tree2.equals(tree)); }
@Test public void testEquals_true() { List<MockLeaf> leaves = asList(leaf1, leaf2); List<MockLeaf> leaves2 = asList(leaf1, leaf2); MerkleTree<MockLeaf> tree = new MerkleTree<>(leaves, 2); MerkleTree<MockLeaf> tree2 = new MerkleTree<>(leaves2, 2); assertTrue(tree.equals(tree2)); assertTrue(tree2.equals(tree)); } |
### Question:
CollectionSizeAdjuster { public void adjustSizeIfNeed(int requiredNumber) { if (requiredNumber < 0) { throw new ArrayIndexOutOfBoundsException("index out of bounds"); } if (requiredNumber > collection.size() - 1) { addUnits(requiredNumber); } } CollectionSizeAdjuster(Collection<T> collection, UnitFactory<T> unitFactory); void adjustSizeIfNeed(int requiredNumber); }### Answer:
@Test public void adjustSizeIfNeed() throws Exception { for (int i = 0; i < 100; i++) { useAdjuster(i); } } |
### Question:
OffsetAnimator { protected float computeValueByOffset(float positionOffset) { positionOffset = computeByTimeShift(positionOffset); positionOffset = computeByInterpolator(positionOffset); return computeExactPosition(x1, x2, positionOffset); } protected OffsetAnimator(float x1, float x2); void animate(float positionOffset); void setParams(AnimatorParams params); OffsetAnimator setStartThreshold(float startThreshold); OffsetAnimator setDuration(float duration); OffsetAnimator setInterpolator(Interpolator interpolator); OffsetAnimator setListener(ValueListener valueListener); }### Answer:
@Test public void getCurrentValue() throws Exception { OffsetAnimator offsetAnimator = new OffsetAnimator(0, 100); float[] positionOffsets = PositionGenerator.generatePositionOffsets(); final float[] expectedValues = new float[100]; for (int i = 1; i < 100; i++) { expectedValues[i] = i; } final float[] actualValues = new float[100]; for (int i = 0; i < positionOffsets.length; i++) { actualValues[i] = offsetAnimator.computeValueByOffset(positionOffsets[i]); } assertArrayEquals(expectedValues, actualValues, 0.00001f); } |
### Question:
ImagesPresenter implements ImagesContract.Presenter { @Override public void openImage(String path) { mView.showImage(path); } ImagesPresenter(ImagesRepository imagesRepository, ImagesContract.View imagesView); @Override void start(); @Override void openTakePhoto(); @Override void openImportPhoto(); @Override void openImage(String path); @Override void onImportImage(Bitmap image); @Override void onPhotoTaken(Bitmap image); @Override void setPictureTaker(PictureTaker pictureTaker); @Override void clearPictureTaker(); @Override void setImageImporter(ImageImporter imageImporter); @Override void clearImageImporter(); @Override void onPermissionRequestResult(boolean isGranted); }### Answer:
@Test public void openImage() throws Exception { final String image = "1.png"; mPresenter.openImage(image); verify(mView).showImage(image); } |
### Question:
ImageViewerPresenter implements ImageViewerContract.Presenter { @Override public void showImage() { Bitmap bitmap = mImagesRepository.getImage(mImage); mView.displayImage(bitmap); } ImageViewerPresenter(@NonNull ImageViewerContract.View view, @NonNull ImagesRepository repository, @NonNull ImageSharer imageSharer, @NonNull String image); @Override void start(); @Override void showImage(); @Override void deleteImage(); @Override void shareImage(); }### Answer:
@Test public void openImage() throws Exception { final String image = "1.png"; mPresenter.showImage(); verify(mView).displayImage(any(Bitmap.class)); } |
### Question:
ImageViewerPresenter implements ImageViewerContract.Presenter { @Override public void deleteImage() { mImagesRepository.deleteImage(mImage); mView.displayImageDeleted(); } ImageViewerPresenter(@NonNull ImageViewerContract.View view, @NonNull ImagesRepository repository, @NonNull ImageSharer imageSharer, @NonNull String image); @Override void start(); @Override void showImage(); @Override void deleteImage(); @Override void shareImage(); }### Answer:
@Test public void deleteImage() throws Exception { mPresenter.deleteImage(); verify(mRepository).deleteImage(anyString()); } |
### Question:
ImageViewerPresenter implements ImageViewerContract.Presenter { @Override public void shareImage() { mImageSharer.shareImage(mImage); } ImageViewerPresenter(@NonNull ImageViewerContract.View view, @NonNull ImagesRepository repository, @NonNull ImageSharer imageSharer, @NonNull String image); @Override void start(); @Override void showImage(); @Override void deleteImage(); @Override void shareImage(); }### Answer:
@Test public void shareImage() throws Exception { mPresenter.shareImage(); verify(mSharer).shareImage(anyString()); } |
### Question:
CardTemplate { private String updateImagesPath(String template) { return template.replaceAll(IMAGE_PATH_REGEX, IMAGE_PATH_REPLACEMENT); } CardTemplate(String frontTemplate, String rearTemplate, int ord); String getFrontTemplate(); String getRearTemplate(); int getOrd(); }### Answer:
@Test public void updateImagesPathTest() throws Exception { String sampleText = "Che cos'è un latch SR?\n<hr id=answer>\n<div>Un circuito elettronico capace di memorizzare informazioni</div><img src=\"paste-9921374453761.jpg\" /> oppure <img src=\"paste-9921374453761.jpg\" />"; String expectedText = "Che cos'è un latch SR?\n<hr id=answer>\n<div>Un circuito elettronico capace di memorizzare informazioni</div><img src=\"anki-images/paste-9921374453761.jpg\" /> oppure <img src=\"anki-images/paste-9921374453761.jpg\" />"; String result = sampleText.replaceAll("(<img.+?src=\")([^\"]+)\"", "$1anki-images/$2\""); Assert.assertEquals(null, expectedText, result); String sample2 = "<img class=\"latex\" src=\"latex-6a3ac365210c170e4573d6f669410f5812e87aff.png\">"; String expected2 = "<img class=\"latex\" src=\"anki-images/latex-6a3ac365210c170e4573d6f669410f5812e87aff.png\">"; String result2 = sample2.replaceAll("(<img.+?src=\")([^\"]+)\"", "$1anki-images/$2\""); Assert.assertEquals(null, expected2, result2); } |
### Question:
NodeBasedRewriteRule implements DialogRewriteRule { @Override public String toString() { String path = null; try { path = ruleNode.getPath(); } catch (RepositoryException e) { } return "NodeBasedRewriteRule[" + (path == null ? "" : "path=" +path + ",") + "ranking=" + getRanking() + "]"; } NodeBasedRewriteRule(Node ruleNode); boolean matches(Node root); Node applyTo(Node root, Set<Node> finalNodes); @Override String toString(); int getRanking(); }### Answer:
@Test public void testToString() throws Exception { Node ruleNode = context.resourceResolver().getResource(RULES_PATH + "/simple").adaptTo(Node.class); Node rootNode = context.resourceResolver().getResource(ROOTS_PATH + "/simple").adaptTo(Node.class); NodeBasedRewriteRule rule = new NodeBasedRewriteRule(ruleNode); String expected = "NodeBasedRewriteRule[path=" + RULES_PATH + "/simple,ranking=" + Integer.MAX_VALUE + "]"; assertEquals(expected, rule.toString()); } |
### Question:
NodeBasedRewriteRule implements DialogRewriteRule { public int getRanking() { if (ranking == null) { try { if (ruleNode.hasProperty(PROPERTY_RANKING)) { long ranking = ruleNode.getProperty(PROPERTY_RANKING).getLong(); this.ranking = new Long(ranking).intValue(); } else { this.ranking = Integer.MAX_VALUE; } } catch (RepositoryException e) { logger.warn("Caught exception while reading the " + PROPERTY_RANKING + " property"); } } return this.ranking; } NodeBasedRewriteRule(Node ruleNode); boolean matches(Node root); Node applyTo(Node root, Set<Node> finalNodes); @Override String toString(); int getRanking(); }### Answer:
@Test public void testGetRanking() throws Exception { Node ruleNode = context.resourceResolver().getResource(RULES_PATH + "/simple").adaptTo(Node.class); Node rootNode = context.resourceResolver().getResource(ROOTS_PATH + "/simple").adaptTo(Node.class); NodeBasedRewriteRule rule = new NodeBasedRewriteRule(ruleNode); assertEquals(Integer.MAX_VALUE, rule.getRanking()); } |
### Question:
DialogRewriteUtils { public static boolean isDesignDialog(Node node) throws RepositoryException { if (node == null) { return false; } String name = node.getName(); return name.equals(NameConstants.NN_DESIGN_DIALOG) || name.equals(NN_CQ_DESIGN_DIALOG) || name.equals(NN_CQ_DESIGN_DIALOG + CORAL_2_BACKUP_SUFFIX); } static boolean hasXtype(Node node, String xtype); static boolean hasType(Node node, String type); static boolean hasPrimaryType(Node node, String typeName); static void rename(Node node); static Property copyProperty(Node source, String relPropertyPath, Node destination, String name); static DialogType getDialogType(Node node); static boolean isDesignDialog(Node node); static final String CORAL_2_BACKUP_SUFFIX; static final String NT_DIALOG; static final String NN_CQ_DIALOG; static final String NN_CQ_DESIGN_DIALOG; static final String DIALOG_CONTENT_RESOURCETYPE_PREFIX_CORAL3; }### Answer:
@Test public void testIsDesignDialog() throws Exception { boolean allDesignDialogs = false; String[] designDialogPaths = { DIALOGS_ROOT + "/classic/design_dialog", DIALOGS_ROOT + "/coral2/cq:design_dialog", DIALOGS_ROOT + "/backupsnoreplacementdiscarded/cq:design_dialog.coral2", DIALOGS_ROOT + "/level1/classicandcoral2/design_dialog", DIALOGS_ROOT + "/level1/classicandcoral2/cq:design_dialog" }; for (String path: designDialogPaths) { Resource resource = context.resourceResolver().getResource(path); Node node = resource.adaptTo(Node.class); allDesignDialogs = DialogRewriteUtils.isDesignDialog(node); if (!allDesignDialogs) { break; } } assertTrue(allDesignDialogs); } |
### Question:
NodeBasedRewriteRule implements DialogRewriteRule { public boolean matches(Node root) throws RepositoryException { if (!ruleNode.hasNode("patterns")) { return false; } Node patterns = ruleNode.getNode("patterns"); if (!patterns.hasNodes()) { return false; } NodeIterator iterator = patterns.getNodes(); while (iterator.hasNext()) { Node pattern = iterator.nextNode(); if (matches(root, pattern)) { return true; } } return false; } NodeBasedRewriteRule(Node ruleNode); boolean matches(Node root); Node applyTo(Node root, Set<Node> finalNodes); @Override String toString(); int getRanking(); }### Answer:
@Test public void testRewriteOptional() throws Exception { Node ruleNode = context.resourceResolver().getResource(RULES_PATH + "/rewriteOptional").adaptTo(Node.class); Node rootNode = context.resourceResolver().getResource(ROOTS_PATH + "/simple").adaptTo(Node.class); NodeBasedRewriteRule rule = new NodeBasedRewriteRule(ruleNode); assertTrue(rule.matches(rootNode)); Node itemsNode = ruleNode.getNode("patterns/pattern/items"); itemsNode.getProperty("cq:rewriteOptional").remove(); rule = new NodeBasedRewriteRule(ruleNode); assertFalse(rule.matches(rootNode)); } |
### Question:
StringUtils { public static int tokenOverlap(String[] tokens1, String[] tokens2) { Set<String> tokenSet2 = new HashSet<String>(Arrays.asList(tokens2)); int score = 0; for (String word : tokens1) if (tokenSet2.contains(word)) score++; return score; } static int tokenOverlap(String[] tokens1, String[] tokens2); static int tokenOverlapExp(String[] tokens1, String[] tokens2); static int findOverlap(String[] tokens1, int i,
String[] tokens2, int j); }### Answer:
@Test public void testTokenOverlapDouble() { String[] tokens1 = {"the", "cat", "has", "a", "brown", "bag"}; String[] tokens2 = {"bag", "dog", "was", "the", "blah", "bag"}; assertEquals(2, StringUtils.tokenOverlap(tokens1, tokens2)); }
@Test public void testTokenOverlapSingle() { String[] tokens1 = {"the", "cat", "has", "a", "brown", "bag"}; String[] tokens2 = {"chicken", "dog", "was", "the", "blah", "bag"}; assertEquals(2, StringUtils.tokenOverlap(tokens1, tokens2)); }
@Test public void testTokenOverlapMixed() { String[] tokens1 = {"the", "cat", "has", "a", "brown", "bag"}; String[] tokens2 = {"bag", "dog", "was", "cat", "blah", "bag"}; assertEquals(2, StringUtils.tokenOverlap(tokens1, tokens2)); } |
### Question:
StringPair implements Comparable, WritableComparable { public int compareTo(Object o) { return compareTo((StringPair) o); } StringPair(); StringPair(String x, String y); int compareTo(Object o); void write(DataOutput out); void readFields(DataInput in); int compareTo(StringPair w); boolean equals(Object o); int hashCode(); static StringPair fromString(String text); String toString(); public String x; public String y; }### Answer:
@Test public void testCompareToFirstEqual() { StringPair pair1 = new StringPair("cat", "alpha"); StringPair pair2 = new StringPair("cat", "dog"); assertTrue(pair1.compareTo(pair2) < 0); }
@Test public void testCompareToBothEqual() { StringPair pair1 = new StringPair("cat", "dog"); StringPair pair2 = new StringPair("cat", "dog"); assertTrue(pair1.compareTo(pair2) == 0); }
@Test public void testCompareToFirstDiffer() { StringPair pair1 = new StringPair("cat", "alpha"); StringPair pair2 = new StringPair("cats", "dog"); assertTrue(pair1.compareTo(pair2) < 0); } |
### Question:
StringPair implements Comparable, WritableComparable { public String toString() { return "{" + x.replaceAll(",", ",") + ", " + y.replaceAll(",", ",") + "}"; } StringPair(); StringPair(String x, String y); int compareTo(Object o); void write(DataOutput out); void readFields(DataInput in); int compareTo(StringPair w); boolean equals(Object o); int hashCode(); static StringPair fromString(String text); String toString(); public String x; public String y; }### Answer:
@Test public void testToString() { StringPair pair = new StringPair("c,at", "dog,"); assertEquals("{c,at, dog,}", pair.toString()); } |
### Question:
StringPair implements Comparable, WritableComparable { public static StringPair fromString(String text) { text = text.trim(); text = text.substring(1, text.length() - 1); String[] parts = text.split(", ", 2); return new StringPair(parts[0].replaceAll(",", ","), parts[1].replaceAll(",", ",")); } StringPair(); StringPair(String x, String y); int compareTo(Object o); void write(DataOutput out); void readFields(DataInput in); int compareTo(StringPair w); boolean equals(Object o); int hashCode(); static StringPair fromString(String text); String toString(); public String x; public String y; }### Answer:
@Test public void testFromString() { StringPair pair = StringPair.fromString( "{c,at, dog,}"); assertEquals("c,at", pair.x); assertEquals("dog,", pair.y); } |
### Question:
ExtendedList extends AbstractList<T> { public boolean add(T e) { return extendedItems.add(e); } ExtendedList(List<T> baseItems); boolean add(T e); T get(int index); int size(); }### Answer:
@Test public void testAdd() { List<String> extendedList = new ExtendedList<String>(array1); for (String s : array2) assertTrue(extendedList.add(s)); assertEquals(3, array1.size()); }
@Test public void testIterator() { List<String> extendedList = new ExtendedList<String>(array1); for (String s : array2) extendedList.add(s); Iterator<String> comboIter = extendedList.iterator(); Iterator<String> iter1 = array1.iterator(); Iterator<String> iter2 = array2.iterator(); while (iter1.hasNext()) { assertTrue(comboIter.hasNext()); assertEquals(iter1.next(), comboIter.next()); } while (iter2.hasNext()) { assertTrue(comboIter.hasNext()); assertEquals(iter2.next(), comboIter.next()); } } |
### Question:
ExtendedList extends AbstractList<T> { public int size() { return baseItems.size() + extendedItems.size(); } ExtendedList(List<T> baseItems); boolean add(T e); T get(int index); int size(); }### Answer:
@Test public void testSize() { List<String> extendedList = new ExtendedList<String>(array1); assertEquals(array1.size(), extendedList.size()); int size = array1.size(); for (String s : array2) { extendedList.add(s); assertEquals(++size, extendedList.size()); } } |
### Question:
ExtendedList extends AbstractList<T> { public T get(int index) { return (index < baseItems.size()) ? baseItems.get(index) : extendedItems.get(index - baseItems.size()); } ExtendedList(List<T> baseItems); boolean add(T e); T get(int index); int size(); }### Answer:
@Test public void testGet() { List<String> extendedList = new ExtendedList<String>(array1); for (int i = 0; i < array1.size(); ++i) assertEquals(array1.get(i), extendedList.get(i)); for (String s : array2) extendedList.add(s); for (int i = 0; i < array1.size(); ++i) assertEquals(array1.get(i), extendedList.get(i)); for (int i = 0; i < array2.size(); ++i) assertEquals(array2.get(i), extendedList.get(i + array1.size())); } |
### Question:
SenseEval2007DocumentReader implements DocumentReader { public Document readDocument(String doc) { return readDocument(doc, corpusName()); } String corpusName(); Document readDocument(String doc); Document readDocument(String doc, String corpusName); static final String CORPUS_NAME; }### Answer:
@Test public void testReadDocument() { DocumentReader reader = new SenseEval2007DocumentReader(); Document doc = reader.readDocument(TEST_SENT); assertEquals("explain.v.4", doc.key()); assertEquals("explain", doc.title()); assertEquals(3, doc.id()); assertEquals(TEST_SENT, doc.originalText()); assertEquals("senseEval2007", doc.sourceCorpus()); assertTrue(doc.rawText().contains("explain ")); assertFalse(doc.rawText().contains("head")); } |
### Question:
SemEval2010TrainDocumentReader implements DocumentReader { public Document readDocument(String doc) { return readDocument(doc, corpusName()); } SemEval2010TrainDocumentReader(); String corpusName(); Document readDocument(String doc); Document readDocument(String doc, String corpusName); static final String CORPUS_NAME; }### Answer:
@Test public void testRead() { DocumentReader reader = new SemEval2010TrainDocumentReader(); Document doc = reader.readDocument(TEST_SENT); assertEquals("class.n.4", doc.key()); assertFalse(doc.rawText().contains("class.n.4")); assertTrue(doc.rawText().contains("Ltd.")); assertEquals("semeval2010_train", doc.sourceCorpus()); } |
### Question:
UkWacDocumentReader implements DocumentReader { public gov.llnl.ontology.text.Document readDocument(String doc) { return readDocument(doc, corpusName()); } String corpusName(); gov.llnl.ontology.text.Document readDocument(String doc); gov.llnl.ontology.text.Document readDocument(String doc,
String corpusName); static final String CORPUS_NAME; }### Answer:
@Test public void testReader() { DocumentReader reader = new UkWacDocumentReader(); Document doc = reader.readDocument(INPUT); assertEquals("ukwac:http: assertEquals("ukwac:http: assertEquals(22, doc.rawText().split("\\s+").length); assertEquals(INPUT, doc.originalText()); assertEquals(UkWacDocumentReader.CORPUS_NAME, doc.sourceCorpus()); } |
### Question:
PubMedDocumentReader extends DefaultHandler implements DocumentReader { public Document readDocument(String originalText, String corpusName) { inAbstract = false; inTitle = false; inPMID = false; inTitle = false; labels.clear(); b.setLength(0); try { saxParser.parse(new InputSource(new StringReader(originalText)), this); } catch (SAXException se) { throw new RuntimeException(se); } catch (IOException ioe) { throw new IOError(ioe); } return new SimpleDocument(corpusName, docText, originalText, key, id, title, labels); } PubMedDocumentReader(); Document readDocument(String originalText, String corpusName); Document readDocument(String originalText); @Override void startElement(String uri, String localName, String name, Attributes atts); @Override void characters(char[] ch, int start, int length); @Override void endElement(String uri, String localName, String name); }### Answer:
@Test public void readDocument() { DocumentReader reader = new PubMedDocumentReader(); Document doc = reader.readDocument(DOCUMENT_ONE); assertEquals("pubmed", doc.sourceCorpus()); assertEquals(12345, doc.id()); assertEquals("12345", doc.key()); assertEquals("CHICKEN", doc.title()); assertEquals("And once there was a chicken.", doc.rawText()); assertEquals(DOCUMENT_ONE, doc.originalText()); assertEquals(2, doc.categories().size()); assertTrue(doc.categories().contains("Anit-Chicken Agents")); assertTrue(doc.categories().contains("Non-geese")); doc = reader.readDocument(DOCUMENT_TWO); assertEquals("pubmed", doc.sourceCorpus()); assertEquals(62345, doc.id()); assertEquals("62345", doc.key()); assertEquals("CHICKENS ATTACK", doc.title()); assertEquals("A flock of chickens have attacked new york.", doc.rawText()); assertEquals(DOCUMENT_TWO, doc.originalText()); assertEquals(2, doc.categories().size()); assertTrue(doc.categories().contains("Human-Chicken Resistance")); assertTrue(doc.categories().contains("Pro-Fowl")); } |
### Question:
TextUtil { public static String cleanTerm(String term) { term = term.toLowerCase().trim(); if (term.matches("[0-9\\-\\.:]+")) return "<NUM>"; if (term.startsWith("http:") || term.startsWith("ftp:")) return "<URL>"; while (term.length() > 0 && term.startsWith("-")) term = term.substring(1, term.length()); while (term.length() > 0 && term.endsWith("-")) term = term.substring(0, term.length()-1); term = term.replaceAll("\"", ""); term = term.replaceAll("\'", ""); term = term.replaceAll("\\[", ""); term = term.replaceAll("\\]", ""); term = term.replaceAll("\\?", ""); term = term.replaceAll("\\*", ""); term = term.replaceAll("\\(", ""); term = term.replaceAll("\\)", ""); term = term.replaceAll("\\^", ""); term = term.replaceAll("\\+", ""); term = term.replaceAll(" term = term.replaceAll(";", ""); term = term.replaceAll("%", ""); term = term.replaceAll(",", ""); term = term.replaceAll("!", ""); return term.trim(); } static String cleanTerm(String term); }### Answer:
@Test public void testNumClean() { String[] numbers = { "1900", ":123", "1-2", "1.2", "10000:", "125121", ".123", "123.", }; for (String number : numbers) assertEquals("<NUM>", TextUtil.cleanTerm(number)); } |
### Question:
Sentence implements Serializable, Iterable<Annotation> { public String sentenceText() { return (text == null) ? null : text.substring(start, end); } private Sentence(); Sentence(int start, int end, int numTokens); void setText(String text); String sentenceText(); void addAnnotation(int index, Annotation annotation); Annotation getAnnotation(int index); DependencyTreeNode[] dependencyParseTree(); StringPair[] taggedTokens(); Iterator<Annotation> iterator(); int start(); int end(); int numTokens(); static List<Sentence> readSentences(String sentenceText,
String tokenText); static StringPair writeSentences(List<Sentence> sentences); }### Answer:
@Test public void testSentenceText() { Sentence sent = new Sentence(2, 10, 8); String text = "abcdefghijlkmop"; sent.setText(text); assertEquals(text.substring(2, 10), sent.sentenceText()); } |
### Question:
Sentence implements Serializable, Iterable<Annotation> { public Annotation getAnnotation(int index) { return tokenAnnotations[index]; } private Sentence(); Sentence(int start, int end, int numTokens); void setText(String text); String sentenceText(); void addAnnotation(int index, Annotation annotation); Annotation getAnnotation(int index); DependencyTreeNode[] dependencyParseTree(); StringPair[] taggedTokens(); Iterator<Annotation> iterator(); int start(); int end(); int numTokens(); static List<Sentence> readSentences(String sentenceText,
String tokenText); static StringPair writeSentences(List<Sentence> sentences); }### Answer:
@Test public void testEmptyGet() { Sentence sent = new Sentence(0, 100, 1); assertEquals(null, sent.getAnnotation(0)); }
@Test (expected=IndexOutOfBoundsException.class) public void testNegativeGet() { Sentence sent = new Sentence(0, 100, 1); sent.getAnnotation(-1); }
@Test (expected=IndexOutOfBoundsException.class) public void testTooLargeGet() { Sentence sent = new Sentence(0, 100, 1); sent.getAnnotation(1); } |
### Question:
Sentence implements Serializable, Iterable<Annotation> { public void addAnnotation(int index, Annotation annotation) { tokenAnnotations[index] = annotation; } private Sentence(); Sentence(int start, int end, int numTokens); void setText(String text); String sentenceText(); void addAnnotation(int index, Annotation annotation); Annotation getAnnotation(int index); DependencyTreeNode[] dependencyParseTree(); StringPair[] taggedTokens(); Iterator<Annotation> iterator(); int start(); int end(); int numTokens(); static List<Sentence> readSentences(String sentenceText,
String tokenText); static StringPair writeSentences(List<Sentence> sentences); }### Answer:
@Test (expected=IndexOutOfBoundsException.class) public void testNegativeSet() { Sentence sent = new Sentence(0, 100, 1); Annotation annot = new SimpleAnnotation("blah"); sent.addAnnotation(-1, annot); }
@Test (expected=IndexOutOfBoundsException.class) public void testTooLargeSet() { Sentence sent = new Sentence(0, 100, 1); Annotation annot = new SimpleAnnotation("blah"); sent.addAnnotation(1, annot); } |
### Question:
Sentence implements Serializable, Iterable<Annotation> { public StringPair[] taggedTokens() { StringPair[] taggedTokens = new StringPair[tokenAnnotations.length]; for (int i = 0; i < taggedTokens.length; ++i) taggedTokens[i] = new StringPair( tokenAnnotations[i].word(), tokenAnnotations[i].pos()); return taggedTokens; } private Sentence(); Sentence(int start, int end, int numTokens); void setText(String text); String sentenceText(); void addAnnotation(int index, Annotation annotation); Annotation getAnnotation(int index); DependencyTreeNode[] dependencyParseTree(); StringPair[] taggedTokens(); Iterator<Annotation> iterator(); int start(); int end(); int numTokens(); static List<Sentence> readSentences(String sentenceText,
String tokenText); static StringPair writeSentences(List<Sentence> sentences); }### Answer:
@Test public void testTaggedTokens() { Sentence sentence = makeSentence(0, 4, TOKEN_INFO, RANGES); StringPair[] taggedPairs = sentence.taggedTokens(); assertEquals(TOKEN_INFO.length, taggedPairs.length); for (int i = 0; i < TOKEN_INFO.length; ++i) { assertEquals(TOKEN_INFO[i][0], taggedPairs[i].x); assertEquals(TOKEN_INFO[i][1], taggedPairs[i].y); } } |
### Question:
StringUtils { public static int tokenOverlapExp(String[] tokens1, String[] tokens2) { int index1 = 0; int index2 = 0; int score = 0; for (int i = 0; i < tokens1.length; ++i) for (int j = 0; j < tokens2.length; ++j) if (tokens1[i].equals(tokens2[j])) score += Math.pow(findOverlap(tokens1, i, tokens2, j), 2); return score; } static int tokenOverlap(String[] tokens1, String[] tokens2); static int tokenOverlapExp(String[] tokens1, String[] tokens2); static int findOverlap(String[] tokens1, int i,
String[] tokens2, int j); }### Answer:
@Test public void testTokenOverlapExpNoSequence() { String[] tokens1 = {"the", "cat", "has", "a", "brown", "bag"}; String[] tokens2 = {"bag", "dog", "was", "cat", "blah", "bag"}; assertEquals(3, StringUtils.tokenOverlapExp(tokens1, tokens2)); }
@Test public void testTokenOverlapExpBoundedSequence() { String[] tokens1 = {"the", "cat", "has", "chicken", "bag", "the"}; String[] tokens2 = {"the", "dog", "was", "blarg", "chicken", "bag"}; assertEquals(7, StringUtils.tokenOverlapExp(tokens1, tokens2)); } |
### Question:
LeskSimilarity implements SynsetSimilarity { public double similarity(Synset synset1, Synset synset2) { String[] gloss1 = synset1.getGloss().split("\\s+"); String[] gloss2 = synset2.getGloss().split("\\s+"); return StringUtils.tokenOverlap(gloss1, gloss2); } double similarity(Synset synset1, Synset synset2); }### Answer:
@Test public void testLeskSimilarity() { Synset s1 = new BaseSynset(PartsOfSpeech.NOUN); Synset s2 = new BaseSynset(PartsOfSpeech.NOUN); s1.setDefinition("how now brown cow"); s2.setDefinition("how now sad meow"); SynsetSimilarity sim = new LeskSimilarity(); assertEquals(2, sim.similarity(s1, s2), .00001); } |
### Question:
ExtendedLeskSimilarity implements SynsetSimilarity { public double similarity(Synset synset1, Synset synset2) { Set<Synset> synsets1 = Sets.newHashSet(synset1.allRelations()); synsets1.add(synset1); Set<Synset> synsets2 = Sets.newHashSet(synset2.allRelations()); synsets2.add(synset2); double score = 0; for (Synset s1 : synsets1) for (Synset s2 : synsets2) score += score(s1.getGloss(), s2.getGloss()); return score; } double similarity(Synset synset1, Synset synset2); }### Answer:
@Test public void testLeskSimilarity() { Synset s1 = new BaseSynset(PartsOfSpeech.NOUN); Synset s2 = new BaseSynset(PartsOfSpeech.NOUN); Synset p2 = new BaseSynset(PartsOfSpeech.NOUN); s1.setDefinition("how now brown cow"); s2.setDefinition("how now sad meow"); p2.setDefinition("cow sad sad"); s2.addRelation(Relation.HYPERNYM, p2); SynsetSimilarity sim = new ExtendedLeskSimilarity(); assertEquals(6, sim.similarity(s1, s2), .00001); } |
### Question:
ExtendedLeskWordSenseDisambiguation extends LeskWordSenseDisambiguation { public void setup(OntologyReader reader) { this.reader = reader; this.sim = new ExtendedLeskSimilarity(); } void setup(OntologyReader reader); String toString(); }### Answer:
@Test public void testDisambiguation() { WordSenseDisambiguation wsdAlg = new ExtendedLeskWordSenseDisambiguation(); Sentence sentences = getSentences(TEST_SENTENCE, TEST_POS); wsdAlg.setup(new GenericMockReader(SYNSET_DATA)); Sentence sent = wsdAlg.disambiguate(sentences); Sentence expected = sentences; assertEquals(expected.numTokens(), sent.numTokens()); assertEquals(expected.start(), sent.start()); assertEquals(expected.end(), sent.end()); Annotation word = sent.getAnnotation(1); assertNotNull(word); assertEquals(SYNSET_DATA[2][0], word.sense()); } |
### Question:
LeskWordSenseDisambiguation extends SlidingWindowDisambiguation { public void setup(OntologyReader reader) { this.reader = reader; this.sim = new LeskSimilarity(); } void setup(OntologyReader reader); String toString(); }### Answer:
@Test public void testDisambiguation() { WordSenseDisambiguation wsdAlg = new LeskWordSenseDisambiguation(); Sentence sentences = getSentences(TEST_SENTENCE, TEST_POS); wsdAlg.setup(new GenericMockReader(SYNSET_DATA)); Sentence sent = wsdAlg.disambiguate(sentences); Sentence expected = sentences; assertEquals(expected.numTokens(), sent.numTokens()); assertEquals(expected.start(), sent.start()); assertEquals(expected.end(), sent.end()); Annotation word = sent.getAnnotation(1); assertNotNull(word); assertEquals(SYNSET_DATA[0][0], word.sense()); } |
### Question:
CombinedSet extends AbstractSet<T> { public int size() { int size = 0; for (Set<T> set : sets) size += set.size(); return size; } CombinedSet(Set<T>...sets); CombinedSet(Collection<Set<T>> setCollection); Iterator<T> iterator(); int size(); }### Answer:
@Test public void testCombinedSize() { Set<String> set1 = new HashSet<String>(); for (String s : array1) set1.add(s); Set<String> set2 = new HashSet<String>(); for (String s : array2) set2.add(s); Set<String> combined = new CombinedSet<String>(set1, set2); assertEquals(6, combined.size()); } |
### Question:
PersonalizedPageRankWSD extends SlidingWindowDisambiguation { public void setup(OntologyReader wordnet) { this.wordnet = wordnet; synsetMap = Maps.newHashMap(); synsetList = Lists.newArrayList(); for (String lemma : wordnet.wordnetTerms()) { for (Synset synset : wordnet.getSynsets(lemma)) if (!synsetMap.containsKey(synset)) { synsetMap.put(synset, synsetMap.size()); synsetList.add(synset); } } SynsetPagerank.setupTransitionAttributes(synsetList, synsetMap); } void setup(OntologyReader wordnet); String toString(); static final String LINK; }### Answer:
@Test public void testDisambiguation() { WordSenseDisambiguation wsdAlg = new PersonalizedPageRankWSD(); Sentence sentences = getSentences(TEST_SENTENCE, TEST_POS); LinkedMockReader reader = new LinkedMockReader(SYNSET_DATA); for (String[] synsetLink : SYNSET_LINKS) reader.connectSynsets(synsetLink[0], synsetLink[1], "r"); wsdAlg.setup(reader); Sentence sent = wsdAlg.disambiguate(sentences); Sentence expected = sentences; assertEquals(expected.numTokens(), sent.numTokens()); assertEquals(expected.start(), sent.start()); assertEquals(expected.end(), sent.end()); Annotation word = sent.getAnnotation(1); assertNotNull(word); assertEquals(SYNSET_DATA[2][0], word.sense()); } |
### Question:
CombinedSet extends AbstractSet<T> { public Iterator<T> iterator() { List<Iterator<T>> iters = new ArrayList<Iterator<T>>(); for (Set<T> set : sets) iters.add(set.iterator()); return new CombinedIterator<T>(iters); } CombinedSet(Set<T>...sets); CombinedSet(Collection<Set<T>> setCollection); Iterator<T> iterator(); int size(); }### Answer:
@Test public void testIterator() { Set<String> set1 = new HashSet<String>(); for (String s : array1) set1.add(s); Set<String> set2 = new HashSet<String>(); for (String s : array2) set2.add(s); Set<String> combined = new CombinedSet<String>(set1, set2); Iterator<String> comboIter = combined.iterator(); Iterator<String> iter1 = set1.iterator(); Iterator<String> iter2 = set2.iterator(); while (iter1.hasNext()) { assertTrue(comboIter.hasNext()); assertEquals(iter1.next(), comboIter.next()); } while (iter2.hasNext()) { assertTrue(comboIter.hasNext()); assertEquals(iter2.next(), comboIter.next()); } } |
### Question:
ExtendedMap extends AbstractMap<K, V> { public V put(K key, V value) { if (baseMap.containsKey(key)) throw new IllegalArgumentException("Should not reinsert keys"); return extendedMap.put(key, value); } ExtendedMap(Map<K, V> baseMap); Set<Map.Entry<K, V>> entrySet(); V get(Object key); V put(K key, V value); }### Answer:
@Test public void testPut() { Map<String,String> extendedMap = new ExtendedMap<String, String>(map1); for (Map.Entry<String, String> s : map2.entrySet()) assertNull(extendedMap.put(s.getKey(), s.getValue())); assertEquals(3, map1.size()); } |
### Question:
ExtendedMap extends AbstractMap<K, V> { public V get(Object key) { V value = baseMap.get(key); return (value != null) ? value : extendedMap.get(key); } ExtendedMap(Map<K, V> baseMap); Set<Map.Entry<K, V>> entrySet(); V get(Object key); V put(K key, V value); }### Answer:
@Test public void testGet() { Map<String,String> extendedMap = new ExtendedMap<String, String>(map1); for (String key : map1.keySet()) assertEquals(map1.get(key), extendedMap.get(key)); for (Map.Entry<String, String> s : map2.entrySet()) extendedMap.put(s.getKey(), s.getValue()); for (String key : map1.keySet()) assertEquals(map1.get(key), extendedMap.get(key)); for (String key : map2.keySet()) if (!map1.containsKey(key)) assertEquals(map2.get(key), extendedMap.get(key)); } |
### Question:
Pager implements Runnable { public Pager(BiFunction<Long, Long, T> fetchFn, Long limit, Long pageSize) { Function<RequestPager.Page, T> fn = (page) -> { try { return fetchFn.apply(page.getLimit(), page.getOffset()); } catch (Exception e) { Long start = page.getOffset(); Long end = start + page.getLimit(); throw new RuntimeException("Page request from " + start + " + to " + end + " failed"); } }; RequestPager<T> pager = new RequestPager<>(fn, 2, 2); runner = pager.build(limit.intValue(), pageSize.intValue()); } Pager(BiFunction<Long, Long, T> fetchFn, Long limit, Long pageSize); void run(); Observable<T> getObservable(); }### Answer:
@Test public void testPager() { var data = new ArrayList<Integer>(); for (var i = 0; i < 1000; i++) { data.add(i); } var pager = new Pager<>((limit, offset) -> { var start = offset; Long end = limit + offset; if (start > data.size()) { start = (long) data.size() - 1; } if (end >= data.size()) { end = (long) data.size(); } return data.subList(start.intValue(), end.intValue()); }, (long) data.size(), 10L); var n = new AtomicInteger(0); pager.getObservable() .subscribe(xs -> n.addAndGet(xs.size()), ex -> Assert.fail(), () -> Assert.assertEquals(data.size(), n.get())); pager.run(); } |
### Question:
AVFImageCaptureService implements SelectableImageCaptureService { @Override public Framegrab capture(File file) { Framegrab framegrab = new Framegrab(); start(); Optional<Image> imageOpt = imageCapture.capture(file, Duration.ofSeconds(10)); if (imageOpt.isPresent()) { framegrab.setImage(imageOpt.get()); MediaPlayer<? extends VideoState, ? extends VideoError> mediaPlayer = Initializer.getToolBox().getMediaPlayer(); if (mediaPlayer != null) { try { mediaPlayer.requestVideoIndex() .thenAccept(framegrab::setVideoIndex) .get(3000, TimeUnit.MILLISECONDS); } catch (Exception e) { log.warn("Problem with requesting videoIndex while capturing a framegrab", e); framegrab.setVideoIndex(new VideoIndex(Instant.now())); } } if (!framegrab.getVideoIndex().isPresent()) { log.warn("Failed to get video index. Using current timestamp for video index"); framegrab.setVideoIndex(new VideoIndex(Instant.now())); } } else { log.warn("Failed to capture image from device named '" + currentDevice + "'"); } return framegrab; } protected AVFImageCaptureService(); Collection<String> listDevices(); void setDevice(String device); @Override Framegrab capture(File file); @Override void dispose(); static synchronized AVFImageCaptureService getInstance(); AVFImageCapture getImageCapture(); static AVFImageCaptureService imageCaptureService; }### Answer:
@Ignore @Test public void testImageCapture() throws Exception { AVFImageCapture ic = new AVFImageCapture(); String[] devices = ic.videoDevicesAsStrings(); if (devices.length > 0) { ic.startSessionWithNamedDevice(devices[0]); Path path = Paths.get("target", getClass().getSimpleName() + "-0-" + Instant.now() + ".png"); Optional<Image> png = ic.capture(path.toFile()); Assert.assertTrue(png.isPresent()); ic.stopSession(); } else { System.err.println("No frame capture devices were found"); } } |
### Question:
Initializer { public static Path getSettingsDirectory() { if (settingsDirectory == null) { String home = System.getProperty("user.home"); Path path = Paths.get(home, ".vars"); settingsDirectory = createDirectory(path); if (settingsDirectory == null) { log.warn("Failed to create settings directory at " + path); } } return settingsDirectory; } static Config getConfig(); static UIToolBox getToolBox(); static Path getSettingsDirectory(); static Path getImageDirectory(); static Path createDirectory(Path path); }### Answer:
@Test public void getSettingsDirectoryTest() { Path path = Initializer.getSettingsDirectory(); assertNotNull("The Settings directory was null", path); assertTrue("The settings directory does not exist", Files.exists(path)); } |
### Question:
Initializer { public static UIToolBox getToolBox() { if (toolBox == null) { Services services = ServicesBuilder.build(Initializer.getConfig()); ResourceBundle bundle = ResourceBundle.getBundle("i18n", Locale.getDefault()); LessCSSLoader lessLoader = new LessCSSLoader(); String stylesheet = lessLoader.loadLess(Initializer.class.getResource("/less/annotation.less")) .toExternalForm(); Data data = new Data(); Integer timeJump = SharktopodaSettingsPaneController.getTimeJump(); log.info("Setting Time Jump to {} millis", timeJump); data.setTimeJump(timeJump); toolBox = new UIToolBox(data, services, new EventBus(), bundle, getConfig(), Collections.singletonList(stylesheet), new ForkJoinPool()); } return toolBox; } static Config getConfig(); static UIToolBox getToolBox(); static Path getSettingsDirectory(); static Path getImageDirectory(); static Path createDirectory(Path path); }### Answer:
@Ignore @Test public void getToolBoxTest() throws Exception { UIToolBox toolBox = Initializer.getToolBox(); assertNotNull("UIToolBox was null", toolBox); Data data = toolBox.getData(); assertNotNull("Data in toolbox was null", data); Services services = toolBox.getServices(); assertNotNull("Services in toolbox was null", data); } |
### Question:
GraywaterAdapter extends RecyclerView.Adapter<VH> { public void add(@NonNull final T item) { add(mItems.size(), item, true); } @Override int getItemViewType(final int position); @Override VH onCreateViewHolder(final ViewGroup parent, final int viewType); @Override @SuppressLint("RecyclerView") void onBindViewHolder(final VH holder, final int viewHolderPosition); @VisibleForTesting int getViewHolderCount(final int itemPosition); @Override int getItemCount(); void add(@NonNull final T item); void add(@NonNull final T item, final boolean notify); int getItemPosition(final int viewHolderPosition); int getBinderPosition(final int itemIndex, final int viewHolderPosition); void add(final int position, @NonNull final T item, final boolean notify); @Nullable T remove(final int itemPosition); @Nullable T remove(final int itemPosition, final boolean notify); int getFirstViewHolderPosition(final int itemPosition, @NonNull final Class<? extends VH> viewHolderClass); void clear(); static View inflate(final ViewGroup parent, @LayoutRes final int layoutRes); @Override void onViewRecycled(final VH holder); @NonNull List<T> getItems(); @Nullable List<Provider<Binder<? super T, VH, ? extends VH>>> getBindersForPosition(final int itemPosition); @Nullable Pair<Integer, Integer> getViewHolderRange(final int itemPosition); }### Answer:
@Test public void testAdd() throws Exception { final TestAdapter adapter = new TestAdapter(); adapter.add("one"); assertEquals(2, adapter.getItemCount()); adapter.add("two"); assertEquals(4, adapter.getItemCount()); adapter.add("three"); assertEquals(6, adapter.getItemCount()); } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.