id
stringlengths
7
14
source
stringlengths
135
41.2k
target
stringlengths
36
20.4k
19419350_42
class ScriptChunk { public byte[] toByteArray() { ByteArrayOutputStream stream = new ByteArrayOutputStream(); try { write(stream); } catch (IOException e) { // Should not happen as ByteArrayOutputStream does not throw IOException on write throw new Runtim...
byte[] expected = new byte[] { OP_IF }; byte[] actual = new ScriptChunk(OP_IF, null).toByteArray(); assertArrayEquals(expected, actual); } }
19436066_16
class ConfigUtils { public int getIntValue(Properties props, String key, int defaultValue) { return Integer.parseInt(getStringValue(props, key, Integer.toString(defaultValue))); } public List<String> getNormalizedPackages(String packages); String getNormalizedPackagePrefix(String packagePrefix); public...
assertThat(getIntValue(new Properties(), "key", 17), is(17)); } }
19454960_0
class RewindableReader extends Reader { public int read(char[] cbuf, int off, int len) throws IOException { int charactersRead = wrappedReader.read(cbuf, off, len); if (charactersRead > 0) { if (rewindable && pos + charactersRead > buffer.length) { rewindable = false; } if (pos < ...
reader = newReaderInstance(EXAMPLE_INPUT_STRING, DEFAULT_BUFFER_SIZE); char[] buffer = new char[5]; reader.read(buffer); assertThat(SpinIoUtil.getStringFromReader(reader)).isEqualTo(EXAMPLE_INPUT_STRING.substring(5)); } }
19458722_0
class WXBizDataCrypt { public JSONObject decryptData(final String encryptedData, final String iv) { final byte[] aesKey = Base64.decodeBase64(sessionKey); final byte[] aesCipher = Base64.decodeBase64(encryptedData); final byte[] aesIV = Base64.decodeBase64(iv); final byte[] decryptedBytes = AESUtils.decrypt(...
String appId = "wx4f4bc4dec97d474b"; String sessionKey = "tiihtNczf5v6AKRyjwEUhQ=="; WXBizDataCrypt biz = new WXBizDataCrypt(appId, sessionKey); String encryptedData = "CiyLU1Aw2KjvrjMdj8YKliAjtP4gsMZM" + "QmRzooG2xrDcvSnxIMXFufNstNGTyaGS" + "9uT5geRa0W4oTOb1WT7fJlAC+oNPdbB+" + "3hVbJSRgv+4lGOETKU...
19480672_1
class StringTransforms { public static String trim(String input, final String toTrim) { if (input == null) return null; Preconditions.checkNotNull(toTrim); input = input.trim(); while (!input.isEmpty() && input.length() >= toTrim.length() && input.startsWith(toTrim)) input = input.substri...
final String input = " 111hello11 "; final String trimmed = StringTransforms.trim(input, "2"); Assert.assertEquals("111hello11", trimmed); } }
19481229_1
class DirectTupleSchema extends TupleSchema { public long createRecord() { return unsafe.allocateMemory(byteSize); } public DirectTupleSchema(Builder builder); public long getLong(long address, int index); public int getInt(long address, int index); public short getShort(long address...
DirectTupleSchema schema = TupleSchema.builder(). addField("aByte", Byte.TYPE). addField("aChar", Character.TYPE). addField("aInt", Integer.TYPE). addField("aShort", Short.TYPE). addField("aFloat", Float.TYPE). addFi...
19537685_13
class WarpAutenticationManager { public void removeUser(String userName) throws CommunicationException { try { WebResource webResource = createRequestResource( "users/" + userName); webResource.delete(); } catch (UniformInterfaceException t) { ...
context.checking( new Expectations() { { oneOf(client).removeAllFilters(); oneOf(client).addFilter( with(equal(new BasicAuthFilter("admin", "lamepass")))); oneOf(client).re...
19547790_0
class TimberLoggerAdapter extends MarkerIgnoringBase { @Override public void debug(String msg) { log(LogType.DEBUG, msg, null); } TimberLoggerAdapter(String tag); @Override public boolean isTraceEnabled(); @Override public void trace(String msg); @Override public void trace(String format, Object ...
Timber.plant(new Timber.DebugTree()); logger.debug("Hello, world!"); List<LogItem> logs = ShadowLog.getLogs(); assertThat(logs).hasSize(1); LogItem log = logs.get(0); assertThat(log.type).isEqualTo(Log.DEBUG); assertThat(log.tag).isEqualTo("TimberLoggerAdapterTest"); assertThat(log.msg...
19551343_0
class SocketAddressParser { public static InetSocketAddress parse(String str) { String address, port; if (str.startsWith("[")) { int addressEnd = str.indexOf(']'); if (addressEnd == -1) throw new IllegalArgumentException(); if ((addressEnd + 2) > str.length()) throw new IllegalArgumentException...
InetSocketAddress address = SocketAddressParser.parse("198.51.100.1:443"); assertEquals(new InetSocketAddress("198.51.100.1", 443), address); } }
19576190_8
class LQEvent extends LQModel { public static boolean hasValidName(String name, boolean raiseException) { boolean valid = name == null || name.length() == 0 || (name.charAt(0) != '_' && !name.contains("$") && !name.contains(".") && !name.contains("\0")); if(!valid) { LiquidTools.excepti...
assertFalse( "Event name with \0", LQEvent.hasValidName("_custom_\0event", false) ); } }
19603587_1
class CodeCompleter { public List<CodeCompletionHint> complete(String incompletePath) { List<CodeCompletionHint> hints = new ArrayList<CodeCompletionHint>(); String objectPath = null; String prefix = null; String lastDelimiter = null; int lastSplit = splitter.lastSplit(incompletePath); if ...
List<CodeCompletionHint> hints = completer.complete("runtimeService.signalEventR"); Assert.assertEquals(4, hints.size()); } }
19624760_12
class Tracks { public static Track reverse(Track track) { Track view = reverseView(track); return new DefaultTrack(view.getId(), view.getMetadata(), track.getWaypoints(), view.getSegments(), view.getStatistics()); } private Tracks(); public static LinkedTrackPoint getStartPoint(Track track); public sta...
Track track = toDefault(loadTrack()); Track rev1 = Tracks.reverse(track); Track rev2 = Tracks.reverse(rev1); assertEquals(track, rev2); } }
19628709_8
class TaxTransferer { public void transferTaxFor(Person person) { if (person == null) { taxService.sendErrorReport(); return; } taxService.transferTaxFor(person); } public TaxTransferer(TaxService taxService); @Mock TaxService taxService; @InjectMo...
// when systemUnderTest.transferTaxFor(null); // then verify(taxService).sendErrorReport(); verifyNoMoreInteractions(taxService); } }
19634578_0
class SSTableIndexIndexer { public void index(final Path sstablePath) throws IOException { final FileSystem fileSystem = FileSystem.get(URI.create(sstablePath.toString()), configuration); final FileStatus fileStatus = fileSystem.getFileStatus(sstablePath); if (fileStatus.isDir()) { ...
// Create a temp dir... final File tmpDir = Files.createTempDir(); tmpDir.deleteOnExit(); // Copy the .Index.db file to the temp dir... File sampleFile = new File(getClass().getResource(INDEX_FILE).getFile()); File tmpSampleFile = new File(tmpDir, sampleFile.getName());...
19638422_1129
class TelemetryCommonConfigService { @VisibleForTesting void resolveLogPathReferences(Telemetry telemetry, List<VmLog> logs) { Map<String, Object> fluentAttributes = telemetry.getFluentAttributes(); if (CollectionUtils.isNotEmpty(logs)) { Properties props = new Properties(); ...
// GIVEN Telemetry telemetry = new Telemetry(); Map<String, Object> fluentAttributes = new HashMap<>(); fluentAttributes.put(SERVICE_LOG_FOLDER_PREFIX, "/var/log"); fluentAttributes.put(SERVER_LOG_FOLDER_PREFIX, "/custom/log"); fluentAttributes.put(AGENT_LOG_FOLDER_PREFIX...
19668829_0
class ArrayInputStream implements BufferedInputStream { @Override public final int read(ByteBuffer dst) throws IOException { int available = this.buf.remaining(); int size = java.lang.Math.min(dst.remaining(), available); if (size == 0) { // end of stream return ...
ArrayInputStream stream = new ArrayInputStream(ByteBuffer.allocate(0)); ByteBuffer dst = ByteBuffer.allocate(10); // read() should return -1 at the end of the stream // https://docs.oracle.com/javase/7/docs/api/java/nio/channels/ReadableByteChannel.html Assert.assertEquals(stream.read(dst), -1); ...
19685642_1
class ThrowErrorTree extends Timber.Tree { @Override protected boolean isLoggable(int priority) { return priority >= mLogPriority; } public ThrowErrorTree(); public ThrowErrorTree(int logPriority); public ThrowErrorTree(int logPriority, LogExclusionStrategy logExclusionStrategy); ...
ThrowErrorTree tree = new ThrowErrorTree(); assertTrue(tree.isLoggable(Log.ERROR)); assertFalse(tree.isLoggable(Log.WARN)); tree = new ThrowErrorTree(Log.INFO); assertTrue(tree.isLoggable(Log.INFO)); assertFalse(tree.isLoggable(Log.DEBUG)); } }
19688946_30
class MessageBroker extends ManageableComponent { public void addFactory(String id, FlexFactory factory) { if (id == null) { // Cannot add ''{0}'' with null id to the ''{1}'' ConfigurationException ex = new ConfigurationException(); ex.setMessage(Configuratio...
String id = "java"; JavaFactory expected = new JavaFactory(); try { broker.addFactory(id, expected); Assert.fail("ConfigurationException expected"); } catch (ConfigurationException ce) { int error = ConfigurationConstants.DUPLICATE_COMPONENT_ID; ...
19691579_63
class CourseDAO { public void setCourses(List<Course> courses) { this.courses = courses; dataSource.save(courses); } public CourseDAO(DataSource<Course> dataSource); public void loadCourses(); public List<Course> getCourses(); public void updateCourse(Course course); publ...
List<Course> l = new ArrayList<>(); l.add(new Course("aaa")); dao.setCourses(l); assertEquals(1, dao.getCourses().size()); } }
19715233_2
class BulldogUtil { public static String bytesToString(byte[] bytes, String encoding) { if(bytes == null) { throw new IllegalArgumentException("bytes may not be null in string conversion"); } if(bytes.length == 0) { return null; } try { return new String(bytes, encoding); } catch (Exception e) { ...
String string = BulldogUtil.bytesToString("Hello World".getBytes("ASCII")); TestCase.assertEquals("Hello World", string); string = BulldogUtil.bytesToString("Hello World".getBytes()); TestCase.assertEquals("Hello World", string); string = BulldogUtil.bytesToString(new byte[] {}); TestCase.assertNull(s...
19733248_1
class UnpublishDocument { @OperationMethod(collector = DocumentModelCollector.class) public DocumentModel run(DocumentModel input) { DocumentModelList proxies = session.getProxies(input.getRef(), null); for (DocumentModel proxy : proxies) { session.removeDocument(proxy.getRef()); ...
OperationContext ctx = new OperationContext(session); ctx.setInput(fileToPublish); OperationChain chain = new OperationChain("testpublish"); chain.add(FetchContextDocument.ID); chain.add(PublishDocument.ID).set("target",section.getId()); DocumentModel publishedDoc = (Docu...
19739444_17
class HandlebarsTemplateEngine extends TemplateEngine { @Override public String render(ModelAndView modelAndView) { String viewName = modelAndView.getViewName(); try { Template template = handlebars.compile(viewName); return template.apply(modelAndView.getModel()); ...
String templateVariable = "Hello Handlebars!"; Map<String, Object> model = new HashMap<>(); model.put("message", templateVariable); String expected = String.format("<h1>%s</h1>", templateVariable); String actual = new HandlebarsTemplateEngine().render(new ModelAndView(model, "hel...
19746703_106
class LatLong implements Comparable<LatLong>, Serializable { @Override public int compareTo(LatLong latLong) { if (this.longitude > latLong.longitude) { return 1; } else if (this.longitude < latLong.longitude) { return -1; } else if (this.latitude > latLong.latitude) { return 1; } else if (this.lati...
LatLong latLong1 = new LatLong(LATITUDE, LONGITUDE); LatLong latLong2 = new LatLong(LATITUDE, LONGITUDE); LatLong latLong3 = new LatLong(LATITUDE, LATITUDE); LatLong latLong4 = new LatLong(LONGITUDE, LONGITUDE); Assert.assertEquals(0, latLong1.compareTo(latLong2)); TestUtils.notCompareToTest(latLong1, lat...
19748926_0
class SimpleCardStackAdapter extends CardStackAdapter { @Override public View getCardView(int position, CardModel model, View convertView, ViewGroup parent) { if(convertView == null) { LayoutInflater inflater = LayoutInflater.from(getContext()); convertView = inflater.inflate(R.layout.std_card_inner, parent,...
//given CardModel cardModel=initializeCardModel(); SimpleCardStackAdapter simpleCardStackAdapter=initializeSimpleCardStackAdapter(); View view=initializeView(); ViewGroup parent=mock(ViewGroup.class); initializeInflater(parent,view); //when View cardView=s...
19759384_20
class PartialSorter { public static <T> void partialSort(List<T> list, List<Integer> items, Comparator<? super T> c) { List<T> temp = Lists.newLinkedList(); for (int index : items) { temp.add(list.get(index)); } Collections.sort(temp, c); for (int i = 0; i < temp...
List<Integer> a = Lists.newArrayList(); a.add(100); a.add(2); a.add(92); a.add(1); a.add(0); PartialSorter.partialSort(a, Lists.newArrayList(1, 3, 4), new Comparator<Integer>() { @Override public int compare(Integer o1, Integer o2) { ...
19777812_9
class GalleryPageApiParser { public static Result parse(String body) throws ParseException { try { Matcher m; Result result = new Result(); JSONObject jo = new JSONObject(body); if (jo.has("error")) { throw new ParseException(jo.getString("er...
InputStream resource = GalleryPageApiParserTest.class.getResourceAsStream("GalleryPageApiParserTest.json"); BufferedSource source = Okio.buffer(Okio.source(resource)); String body = source.readUtf8(); GalleryPageApiParser.Result result = GalleryPageApiParser.parse(body); assertEquals("http://69.30....
19781635_3
class TypedBaseAdapter extends BaseAdapter { @SuppressWarnings("unchecked") @Override public C getView(int position, View convertView, ViewGroup parent) { C view = null; if (convertView != null) { view = (C) convertView; } else { view = createView(); ...
// given final TestView mockView = Mockito.mock(TestView.class); TypedBaseAdapterExtension adapter = new TypedBaseAdapterExtension(new String[] { "hello" }, mockView); // when adapter.getView(0, null, null); // then assertTrue(adapter.isCreateViewCalled); ...
19786369_9
class DVEConfigCLI extends CLIBuilder { @Override public void close() { if (catHelper != null) { catHelper.close(); catHelper = null; } super.close(); } public DVEConfigCLI(String[] args); protected CatalogHelper getCatalogHelper(); public void cmd_dump(Scanner scanner); public void cmd_locate_ca...
final DVEClientToolTestConsole console = new DVEClientToolTestConsole(new DVEConfigCLI(null)); console.executeInteractiveCommand("delete catalog", "y"); console.executeCommand("setup localhost catalog 5 5"); // Create a CatalogDAO to verify the contents CatalogDAO c = CatalogDAOFactory.newInstance(); // ...
19789077_76
class SdbCassandraInstanceDao implements CassandraInstanceDao { @Override public void save(String ring, CassandraInstance instance) { PutAttributesRequest request = new PutAttributesRequest( domain(ring), String.valueOf(instance.getId()), buildSaveAttributes(instance)); client.putAttributes(request...
CassandraInstance instance = createMock(CassandraInstance.class); Capture<PutAttributesRequest> requestCapture = new Capture<PutAttributesRequest>(); expect(domainFactory.createFromRing(RING_NAME)).andReturn(domain(RING_NAME)); expect(instance.getId()).andReturn(ID).times(2); expect(instance.getData...
19802105_7
class HttpRedirectPolicyUtils { public static boolean shouldFollowRedirect(HttpRedirectPolicy redirectPolicy, URL currentURL, URL redirectURL) { return POLICY_CHECKERS.get(redirectPolicy).compare(currentURL, redirectURL) == 0; } private HttpRedirectPolicyUtils(); } class HttpRedirectPolicyUtils...
URL currentURL = new URL("http://example.com:8080/path"); URL redirectURL = new URL("http://example.com:8081/path"); assertFalse(shouldFollowRedirect(ORIGIN, currentURL, redirectURL)); } }
19821698_135
class SenchaParseRequestStage extends ParseRequestStage { @Override protected <T> void doExecute(SelectContext<T> context) { super.doExecute(context); Map<String, List<String>> protocolParameters = context.getProtocolParameters(); // TODO: make symmetrical with AgRequestBuilder (name...
@SuppressWarnings("unchecked") MultivaluedMap<String, String> params = mock(MultivaluedMap.class); when(params.get("cayenneExp")).thenReturn(Collections.singletonList("{\"exp\" : \"address = '1 Main Street'\"}")); when(params.get(SenchaParseRequestStage.FILTER)).thenReturn(Collections.singletonList("[{\"proper...
19825381_78
class Cli implements Callable<Integer> { @SuppressWarnings("WeakerAccess") // Public API. public int run( String[] args ) { CommandLine cl = new CommandLine(this); cl.setUsageHelpAutoWidth(true); cl.setExecutionStrategy(new CommandLine.RunAll()); cl.setOverwrittenOptionsAllowed(...
Cli c = new Cli(); c.run( new String[] {} ); ManipulationSession session = (ManipulationSession) FieldUtils.readField( c, "session", true ); File defaultTarget = (File) FieldUtils.readField( c, "target", true ); assertEquals( "Session file should match", defaultTarget, session....
19827565_2
class RvfReleaseDbSchemaNameGenerator { public static String generate(String releaseFilename) { if (releaseFilename != null && !releaseFilename.endsWith(".zip")) { return releaseFilename.replaceAll("-", "_"); } releaseFilename = releaseFilename.replace(".zip", ""); String[] splits = releaseFilename.split("...
assertEquals("rvf_intrf2_prod_20180731t120000z", generate("SnomedCT_InternationalRF2_PRODUCTION_20180731T120000Z.zip")); } }
19836152_70
class ExpressionTransform { public List transformList( List source, EvaluationContext evaluationContext, ExpressionEvaluationSummary summary, Map<String, Object> additionalContext) { List<Object> result = new ArrayList<>(); for (Object obj : source) { if (obj instanceof Map) { ...
List<Object> input = Collections.singletonList(Collections.singletonMap("key", "value")); List<?> evaluated = new ExpressionTransform(parserContext, parser, Function.identity()) .transformList( input, new StandardEvaluationContext(), new Expre...
19851429_9
class ControlFieldExpression implements Expression<String, Document> { @Override public String evaluate(final Document target) { final String result = currentState.evaluate(target); return result != null && result.trim().length() > 0 ? result : null; } public ControlFieldExpression(final String specs); @Ov...
final Document document = newRecord(null, null); final ControlFieldExpression expression = new ControlFieldExpression(A_CONTROL_FIELD_NAME + "[00-05]"); expression.xpath = new OXPath(); assertNull(expression.evaluate(document)); } }
19873472_1
class Utility { public static byte[] read(String filename) throws IOException { BufferedInputStream stream = new BufferedInputStream( new FileInputStream(filename)); byte[] content = read(stream); stream.close(); return (content); } ...
byte[] data = "abcdefhijklmnopqrstuvwxyz".getBytes(); InputStream in = new ByteArrayInputStream(data); byte[] result = Utility.read(in); assertArrayEquals(data, result); } }
19961085_109
class ServiceStatus { public static Status getServiceStatus() { return getServiceStatus(serviceStatusCallback); } public static void setServiceStatusCallback(String name, ServiceStatusCallback serviceStatusCallback); public static void removeServiceStatusCallback(String name); public static Status getSe...
TestIdealStateAndExternalViewMatchServiceStatusCallback callback; // No ideal state = GOOD callback = buildTestISEVCallback(); callback.setExternalView(new ExternalView(TABLE_NAME)); assertEquals(callback.getServiceStatus(), ServiceStatus.Status.GOOD); // No external view = STARTING callba...
19975898_1
class VerdictConverter { public static Boolean toBoolean(Verdict verdict) { if(verdict == Verdict.INCONCLUSIVE) return null; if(verdict == Verdict.PASS) return true; return false; } public static Verdict toVerdict(Boolean bool); } class VerdictConverterTest { @Test public void TestVerdictToBoolean...
assertFalse(VerdictConverter.toBoolean(Verdict.FAIL)); assertTrue(VerdictConverter.toBoolean(Verdict.PASS)); assertNull(VerdictConverter.toBoolean(Verdict.INCONCLUSIVE)); } }
19995362_4
class LocaleUtil { public static String getLocaleCode(String localeStr) { Locale locale = FALLBACK; try { locale = (localeStr != null)? LocaleUtils.toLocale(localeStr):FALLBACK; } catch (IllegalArgumentException e) { logger.warn("cannot get locale from {}. Returning ...
assertThat(LocaleUtil.getLocaleCode("en_GB")).isEqualTo("en_GB"); } }
20076963_0
class BasicScript implements PhonScript, Cloneable { public BasicScript(String text) { super(); buffer.append(text); setupImports(); } public BasicScript(String text); public BasicScript(File file); protected StringBuffer getBuffer(); private void setupImports(); @Override public String getScript()...
final String script = "x = 1 + 1\n"; final BasicScript bs = new BasicScript(script); final PhonScriptContext ctx = bs.getContext(); final Scriptable scope = ctx.createImporterScope(); final Object val = ctx.exec(scope); Assert.assertEquals(Integer.class, val.getClass()); Assert.assertEquals(2, (int)...
20127629_1
class Customer extends BaseModel { public void setName(String name) { this.name = name; } public String toString(); public String getName(); public LocalDate getRegistered(); public void setRegistered(LocalDate registered); public String getComments(); public void setComments(String comments); p...
DelegateEbeanServer mock = new DelegateEbeanServer(); mock.withPersisting(true); MockiEbean.runWithMock(mock, () -> { Customer customer = new Customer(); customer.setName("jim"); //customer.setComments("first comment"); customer.save(); //customer.setComments("second comm...
20132937_2
class UploadFile implements Serializable { public String getName() { return name; } public UploadFile(String name, String contentType, long size, byte[] contents); public String getId(); public void setName(String name); public String getContentType(); public void set...
uploadedFile.setName("flag.png"); assertEquals("flag.png", uploadedFile.getName()); } }
20147131_4
class AtmosphereServerWebSocket extends AbstractServerWebSocket { @Override public <T> T unwrap(Class<T> clazz) { return AtmosphereResource.class.isAssignableFrom(clazz) ? clazz.cast(resource) : null; } public AtmosphereServerWebSocket(AtmosphereResource resource); @Override public Strin...
performer.onserver(new Action<ServerWebSocket>() { @Override public void on(ServerWebSocket ws) { assertThat(ws.unwrap(AtmosphereResource.class), instanceOf(AtmosphereResource.class)); performer.start(); } }) .connect(); } ...
20175098_0
class RSGaussianBlurTransformation implements Transformation { @Override public Bitmap transform(Bitmap source) { if (Build.VERSION.SDK_INT < 17) { return source; } RenderScript rs = RenderScript.create(mContext); Allocation input = Allocation.createFromBitm...
Transformation t = getTransformation(); Bitmap copy = getCopyOfBitmap(); Bitmap bm = t.transform(copy); assertThat(bm).isNotNull(); } }
20214352_40
class BuildState { public BuildState setAllEnabled(){ for (BuildStateEnum state : states.keySet()){ switch (state){ case BUILD_BROKEN: disable(state); break; case BUILD_FIXED: disable(state); break; default: enable(state); break; } }...
BuildState state = new BuildState(); assertTrue(state.noneEnabled()); state.setAllEnabled(); assertTrue(state.allEnabled()); } }
20216746_5
class StaxUtils { public static boolean isStaxResult(Result result) { return (result instanceof StaxResult || (jaxp14Available && Jaxp14StaxHandler.isStaxResult(result))); } public static Source createCustomStaxSource(XMLStreamReader streamReader); public static Source createStaxSource(XMLStreamReader streamRea...
XMLOutputFactory outputFactory = XMLOutputFactory.newInstance(); XMLStreamWriter streamWriter = outputFactory.createXMLStreamWriter(new StringWriter()); StAXResult result = new StAXResult(streamWriter); assertTrue("Not a StAX Result", StaxUtils.isStaxResult(result)); } }
20227177_0
class BaseBatchingStrategy implements BatchingStrategy<E, T> { @Override public void onDataPushed(Collection<E> dataCollection) { persistenceStrategy.add(dataCollection); } public BaseBatchingStrategy(PersistenceStrategy<E> persistenceStrategy); @Override public boolean isInitialized(); ...
PersistenceStrategy<Data> persistenceStrategy = mock(PersistenceStrategy.class); BaseBatchingStrategy<Data, Batch<Data>> baseBatchingStrategy = new BaseBatchingStrategy<Data, Batch<Data>>(persistenceStrategy) { @Override public void flush(boolean forced) { } ...
20236504_1
class Numek { public String text2number(String snumber) { // UK "and" hundreds/thousands/tens/units separator "five hundred and six" // UK/US "-" is tens and units separator // UK magnitudes are singular. Plural (milions) is informal/indefinite (e.g., there were millions of people) ...
System.out.println("text2number"); instance = new Numek(new Locale("en","US")); assertEquals("25", instance.text2number("twenty five")); assertEquals("0.01", instance.text2number("00.010")); assertEquals("2000025", instance.text2number("two million twenty five")); assertE...
20249391_68
class Whitebox { public static Method[] getMethods(Class<?> clazz, String... methodNames) { return WhiteboxImpl.getMethods(clazz, methodNames); } public static Field getField(Class<?> type, String fieldName); public static Field[] getFields(Class<?> clazz, String... fieldNames); public static Method getMethod(...
try { Whitebox.getMethods(ClassWithSeveralMethodsWithSameName.class, "notFound1", "notFound2", "notFound3"); } catch (MethodNotFoundException e) { assertEquals( "No methods matching the name(s) notFound1, notFound2 or notFound3 were found in the class hierarch...
20256052_0
class VariableStatementResolver implements StatementResolver { private void injectVariables(Map<String, String> variables, Statement statement) { if (statement instanceof VariablesAware) { ((VariablesAware) statement).setVariables(variables); } } public VariableStatementResolv...
VariableAwareFact factMock = mock(VariableAwareFact.class); variableStatementResolver.addStatement("a ${b} c", factMock, Fact.class); assertEquals(factMock, variableStatementResolver.resolveStatement("a value c", Fact.class)); Map<String, String> expectedVariables = new HashMap<String, S...
20281385_0
class PropertyUtil { public static String getProperty(String str) { String value = ""; String defaultValue = ""; if( !StringUtils.isNullOrEmpty(str) && str.startsWith("${") && str.endsWith("}") ) { String variable = str.trim().substring(2, str.length()-1); if( varia...
Assert.assertEquals("1", PropertyUtil.getProperty("${test:1}")); Assert.assertEquals("", PropertyUtil.getProperty("${test}")); System.setProperty("test", "2"); Assert.assertEquals("2", PropertyUtil.getProperty("${test}")); Assert.assertEquals("2", PropertyUtil.getProperty("${tes...
20303761_199
class RegionMergeTransaction { public boolean prepare(final RegionServerServices services) { if (!region_a.getTableDesc().getTableName() .equals(region_b.getTableDesc().getTableName())) { LOG.info("Can't merge regions " + region_a + "," + region_b + " because they do not belong to the sam...
HStore storeMock = Mockito.mock(HStore.class); when(storeMock.hasReferences()).thenReturn(true); when(storeMock.getFamily()).thenReturn(new HColumnDescriptor("cf")); when(storeMock.close()).thenReturn(ImmutableList.<StoreFile>of()); this.region_a.stores.put(Bytes.toBytes(""), storeMock); RegionM...
20320123_137
class Trace { public static Tracer trace(String desc, Parameter... parameters) { TraceCollector collector = _tracer.get(); if (collector == null) { return DO_NOTHING; } TracerImpl tracer = new TracerImpl(desc, parameters, collector.getNextId(), collector.getScope()); collector.add(tracer); ...
Trace.setStorage(new BaseTraceStorage(new BlurConfiguration()) { @Override public void store(TraceCollector collector) { assertEquals("test", collector.getId().getRootId()); assertEquals(3, collector.getTraces().size()); } @Override public void close() throws IOExcepti...
20321029_18
class CronExpression { public ZonedDateTime nextTimeAfter(ZonedDateTime afterTime) { // will search for the next time within the next 4 years. If there is no // time matching, an InvalidArgumentException will be thrown (it is very // likely that the cron expression is invalid, like the Febr...
CronExpression cronExpr = new CronExpression("0 0 0 9W * *"); // 9 - is weekday in may ZonedDateTime after = ZonedDateTime.of(2012, 5, 2, 0, 0, 0, 0, zoneId); ZonedDateTime expected = ZonedDateTime.of(2012, 5, 9, 0, 0, 0, 0, zoneId); assertEquals(expected, cronExpr.nextTimeAfter...
20332528_2
class Pig { public void execute(String path) { execute(path, (String) null, (Type) null, (Callback) null); } private Pig(Context context); Pig(Context context, WebViewWrapper webViewWrapper); public static Pig get(Context context); public void execute(String path, Callback<R> callb...
Pig pig = PigTestUtils.getMockedPiggie(); PigTestUtils.addMockHandler(pig, new MockWebViewWrapper.Handler(pig) { public void handle(String data) { send("1"); } }); stringReceived = false; stringReceivedError = null; stringReceived...
20336406_9
class Game { public void addListener(AchievementListener listener) { listeners.add(listener); } public abstract void insertAchievement(Object user, Achievement a); public abstract void deleteAchievement(Object user, Achievement a); public abstract void updateAchievement(Object user, Achievement a); public abs...
AchievementListenerMock mock = new AchievementListenerMock(); Achievement a2 = new Point(10,"point"); game.addListener(mock); game.addAchievement("user",a2); mock.verifyReceivedAchievements("user",a2); } }
20337377_1
class MessageService { public String getMessage() { return "Hello World!"; } private MessageService messageService; } class MessageServiceTest { private MessageService messageService; @Test public void getMessage_ShouldReturnMessage() {
assertEquals("Hello World!", messageService.getMessage()); } }
20356428_5
class AbstractTabOverlayHandler implements PacketHandler, TabOverlayHandler { @Override public <R> R enterContentOperationMode(ContentOperationMode<R> operationMode) { AbstractContentOperationModeHandler<?> handler; if (operationMode == ContentOperationMode.PASS_TROUGH) { handler = ...
SimpleTabOverlay tabOverlay = tabOverlayHandler.enterContentOperationMode(ContentOperationMode.SIMPLE); for (int size = 1; size <= 80; size++) { tabOverlay.setSize(size); assertEquals("Size check failed for size " + size, size, clientTabList.getSize()); tabOverlay....
20374886_5
class BCryptPasswordEncoder implements PasswordEncoder { public boolean matches(CharSequence rawPassword, String encodedPassword) { if (encodedPassword == null || encodedPassword.length() == 0) { logger.warning("Empty encoded password"); return false; } if (!BCRYPT_PATTERN.matcher(encodedPassword).matche...
String rawPassword = "test"; boolean matched = this.instance.matches(rawPassword, "notmatched"); assertFalse(matched); } }
20426356_0
class BidRestService { @POST @Consumes("application/json") @Produces("application/json") public Bid addBid(Bid bid) { return bidService.addBid(bid); } @GET @Path("{id}") @Produces("application/json") public Bid getBid(@PathParam("id") Long id); @PUT @Path("{id}") @Consumes("applica...
WebTarget target = ClientBuilder.newClient() .target("http://localhost:8080/actionbazaar-rest-test/rest/bids"); // Save a new bid. Bid bid = new Bid(); bid.setBidder("nrahman"); bid.setItem("Test item"); bid.setAmount(130.75); bid = target.reques...
20432793_28
class AWSRunInstancesOptions extends RunInstancesOptions { @Override public AWSRunInstancesOptions asType(String type) { launchSpecificationBuilder.instanceType(type); return AWSRunInstancesOptions.class.cast(super.asType(type)); } public AWSRunInstancesOptions inPlacementGroup(String placemen...
AWSRunInstancesOptions options = new AWSRunInstancesOptions(); options.asType(InstanceType.C1_XLARGE); assertEquals(options.buildFormParameters().get("InstanceType"), ImmutableList.of("c1.xlarge")); } }
20433857_36
class DIRClient implements TimeServerClient { public AddressMappingSet xtreemfs_address_mappings_get(InetSocketAddress server, final Auth authHeader, final UserCredentials userCreds, final String uuid) throws IOException, InterruptedException { return xtreemfs_address_mappings_get(server, authH...
dir1.donotAnswer = true; dir2.donotAnswer = true; try { DIRClient client = new DIRClient(testEnv.getDirClient(), servers, 5, 2); client.xtreemfs_address_mappings_get(null, RPCAuthentication.authNone, RPCAuthentication.userService, "*"); fail("Expected excepti...
20439978_2
class ActionHandler { public abstract Percept performAction(Action action) throws ActExceptionpublic abstract Percept performAction(Action action) throws ActException; public abstract Percept performAction(Action action) throws ActExceptionpublic abstract boolean isSupportedByEntity(Action action); public abstract Pe...
Percept percept = handler.performAction(new Action("getX")); assertEquals(new Percept("getX", new Numeral(0)), percept); percept = handler.performAction(new Action("setX", new Numeral(1))); assertEquals(null, percept); percept = handler.performAction(new Action("getX")); assertEquals(new Percept("getX", n...
20456181_2
class RandomLoadBalancer implements LoadBalancer { @Override public ServerStats choose(List<ServerStats> availableServerStats) { int index = random.nextInt(availableServerStats.size()); return availableServerStats.get(index); } } class RandomLoadBalancerTest { @Test public void o...
ServerInstance serverInstance = new ServerInstance("dummy","dummy","localhost",false,-1,81); serverInstance.setAvailable(true); ServerStats serverStats = new ServerStats(); serverStats.setServerInstance(serverInstance); RandomLoadBalancer lb = new RandomLoadBalancer(); S...
20473418_5
class SequentialIntegerDataGenerator implements RuleBasedDataGenerator { @Override public DataValue getDataValue() { return new DataValue(columnRule.getType(), String.valueOf((counter.getAndIncrement() % (maxValue - minValue + 1)) + minValue)); } public SequentialIntegerDataGenerator(Column c...
Column columnA = new Column(); columnA.setType(INTEGER); columnA.setDataSequence(DataSequence.SEQUENTIAL); columnA.setMinValue(1); columnA.setMaxValue(3); generator = new SequentialIntegerDataGenerator(columnA); DataValue result1 = generator.getDataValue(); ...
20499820_5
class Api { @NonNull @WorkerThread public CallResult<Depth> depth(@NonNull String pair) { final String serverPair = PairUtils.localToServer(pair); final String url = hostUrl + "/api/3/depth/" + serverPair; JsonObject response = guestApi.call(url); CallResult<Depth> result = ...
when(mockGuestApi.call(anyString())) .thenReturn(JSON_PARSER.parse("{\"success\":0," + " \"error\":\"Invalid pair name: btc_us\"}").getAsJsonObject()); CallResult<Depth> depthCallResult = testable.depth("BTC/US"); assertFalse(depthCallResult.isSuccess());...
20501508_0
class DemoController implements Serializable { public void updateIntModel(AjaxBehaviorEvent event) { intModel.setValue(intModel.getValue() + UPDATE_INT_VALUE); eduContext.update("int-model-changed"); } public DemoModel<String> getStringModel(); public DemoModel<Integer> getIntModel(); ...
final String initialStringValue = controller.getStringModel().getValue(); final int initialIntValue = controller.getIntModel().getValue(); controller.updateIntModel(mock(AjaxBehaviorEvent.class)); assertThat(controller.getStringModel().getValue(), is(initialStringValue)); assert...
20517345_6
class DiagnosticContextFilter implements Filter { @Override public void init(FilterConfig config) throws ServletException { String headerName = config.getInitParameter(CORRELATION_ID_HEADER_NAME_PARAM); if (headerName == null) { LOG.debug("Parameter {} not configured via filter config.", CORRELATION...
// setup DiagnosticContextFilter filter = new DiagnosticContextFilter(); String field = (String) ReflectionTestUtils.getField(DiagnosticContextFilter.class, CORRELATION_ID_HEADER_NAME_PARAM_FIELD_NAME); assertThat(field).isNotNull(); String nonDefaultParameter = "test"; when(this.config...
20522047_10
class KeyStoreOperations implements IKeyStoreOperations { @Override public <T> void updateOrCreateDTOList(List<T> toUpdate, KeySet keySet, JsonWriter<T> jsonWriter, List<Long> oids) { int i = 0; for (T type : toUpdate) { final String key = keySet.createKey(String.valueOf(oids.get(i))); localStorage.setItem...
KeyStoreOperations ops = new KeyStoreOperations(storage, keySetJsonReader, keySetJsonWriter); List<TestDto> list = new ArrayList<TestDto>(); list.add(new TestDto(1, "Test1")); list.add(new TestDto(2, "Test2")); list.add(new TestDto(3, "Test3")); KeySet keySet = new KeySet(TestDto.class, "user", "UC_LIST"); ...
20530482_7
class PatternMatcher { public static boolean match(Writable value, String regex) { if (value == null) { return false; } String valueStr = value.toString(); if (valueStr == null || valueStr.length() == 0) { return false; } // TODO: Remove Pattern.compile Pattern p = Pattern.compile(regex); Matc...
boolean check = PatternMatcher.match(null, UtilitiesConstantsTestInterface.REGEX); assertFalse(check); } }
20530820_70
class CassandraUtils { public static Object parseValue(final DataType type, final String value) { if (value == null) { return null; } switch (type.getName()) { case TEXT: case VARCHAR: case ASCII: return value; case INET: return type.parse("'" + value + "'"); case IN...
assertThat(CassandraUtils.parseValue(DataType.cint(), " 1 2 ")) .isEqualTo(12); } }
20572012_144
class FunctionDefinitionEquality extends FunctionDefinitionHomogeneousSimple<Boolean, I> { @Override public ExpressionResult evaluate(EvaluationContext evaluationContext, List<FunctionArgument> arguments) { List<I> convertedArguments = new ArrayList<I>(); Status status = this.validateArguments(arguments, conv...
XPathYearMonthDuration dur1 = new XPathYearMonthDuration(1, 3, 5); XPathYearMonthDuration dur2 = new XPathYearMonthDuration(1, 3, 5); XPathYearMonthDuration differentDur = new XPathYearMonthDuration(-1, 4, 7); FunctionArgumentAttributeValue attrDur1 = null; FunctionArgumentAttributeValue attrDur2 = null; ...
20576090_0
class MissionLog { static String colorToHTML(int argb) { return String.format("#%06X", argb & 0xffffff); } public MissionLog(CharSequence actionText, CharSequence clockText); public MissionLog(CharSequence actionText); public CharSequence getActionText(); public CharSequence getCloc...
assertEquals("#C7EBFC", MissionLog.colorToHTML(0xffc7ebfc)); assertEquals("#C7EBFC", MissionLog.colorToHTML(0xc7ebfc)); assertEquals("#07EBFC", MissionLog.colorToHTML(0xff07ebfc)); assertEquals("#07EBFC", MissionLog.colorToHTML(0x7ebfc)); assertEquals("#00EBFC", MissionLog.colorT...
20577351_0
class HoltWintersComputer { public double getAlpha() { return alpha; } public HoltWintersComputer(final double alpha); public HoltWintersComputer(final double alpha, final double beta); public HoltWintersComputer(final double alpha, final double beta, final double gamma, final int perio...
// series<-ts(c(315.42, 316.31, 316.50, 317.56, 318.13, 318.00, 316.39, 314.65, 313.68, 313.18, 314.66, 315.43)) final double[] series = {315.42, 316.31, 316.50, 317.56, 318.13, 318.00, 316.39, 314.65, 313.68, 313.18, 314.66, 315.43}; // smooth<-HoltWinters(co2, alpha=0.8, beta=FALSE, gamma=FAL...
20582138_2
class JunitSuiteRunner extends ParentRunner<Runner> { @Override protected List<Runner> getChildren() { return fRunners; } public JunitSuiteRunner(Class<?> testClass); private static List<Runner> createRunners(Class<?> testClass); private static Map<String, List<CompleteBehaviour>> findSuitesInClass( Clas...
JunitSuiteRunner testee = new JunitSuiteRunner(ValidTestWithTwoDescriptions.class); List<Runner> actual = testee.getChildren(); assertEquals(createSuiteDescription("a thing"), actual.get(0).getDescription()); assertEquals(createSuiteDescription("another thing"), actual.get(1).getDescript...
20614852_6
class ColorUtils { public static String getRGB(float n) { return String.format(Locale.ENGLISH, "%.0f", n).replaceAll("\\.0*$", ""); } private ColorUtils(); public static String RGBToHex(int n); public static float[] RGBToHSB(@IntRange(from = 0, to = 255) int r, ...
assertEquals(ColorUtils.getRGB(0), "0"); assertEquals(ColorUtils.getRGB(100), "100"); assertEquals(ColorUtils.getRGB(255), "255"); assertEquals(ColorUtils.getRGB(0.10f), "0"); assertEquals(ColorUtils.getRGB(100.10f), "100"); assertEquals(ColorUtils.getRGB(255.10f), "255")...
20645540_8
class Over extends EvalFunc<DataBag> { @Override public Schema outputSchema(Schema inputSch) { try { if (returnType == DataType.UNKNOWN) { return Schema.generateNestedSchema(DataType.BAG, DataType.NULL); } else { Schema outputTupleSchema = new Sch...
// No type Over func = new Over(); Schema in = Schema.generateNestedSchema(DataType.BAG, DataType.INTEGER); Schema out = func.outputSchema(in); assertEquals("{{NULL}}", out.toString()); // chararray func = new Over("chararray"); in = Schema.generateNested...
20647901_31
class Hibernate4MemcachedRegionFactory implements RegionFactory { @Override public TimestampsRegion buildTimestampsRegion(String regionName, Properties properties) throws CacheException { return new TimestampMemcachedRegion(regionName, new OverridableReadOnlyPropertiesImpl(properties, c...
givenStart(); TimestampsRegion timestampsRegion = regionFactory.buildTimestampsRegion("UpdateTimestamps", properties); assertThat(timestampsRegion.getName()).isEqualTo("UpdateTimestamps"); assertThat(timestampsRegion).isExactlyInstanceOf(TimestampMemcachedRegion.class); } }
20673421_39
class TransactionService { public static Transaction get(final Context context, final String number) throws NetLicensingException { CheckUtils.paramNotEmpty(number, "number"); return NetLicensingService.getInstance().get(context, Constants.Transaction.ENDPOINT_PATH + "/" + number, null, ...
final Transaction transaction = TransactionService.get(context, "TR001TEST"); assertNotNull(transaction); assertEquals("TR001TEST", transaction.getNumber()); assertEquals(true, transaction.getActive()); assertEquals(TransactionStatus.CLOSED, transaction.getStatus()); ass...
20707395_11
class Position { public final double getDistanceToPathKm(List<Position> positions) { if (positions.size() == 0) throw new RuntimeException("positions must not be empty"); else if (positions.size() == 1) return this.getDistanceToKm(positions.get(0)); else { ...
// positions to test Position p = new Position(-10, 150); // segment positions constituting a path Position sp1 = new Position(-30, 100); Position sp2 = new Position(-20, 120); Position sp3 = new Position(-30, 140); // path with two segments List<Positio...
20710724_3
class Configuration { public FeatureMap getFeatureMap() { return featureMap; public FeatureMap getFeatureMap() { return featureMap; } public FeatureMap getFeatureMap() { return featureMap; public Configuration(); public FeatureMap getFeatureMap() { return featureMap; public Configuration(final boolean tracing); pub...
final Configuration config = new Configuration(this.getClass().getResourceAsStream(configResource), false); assertEquals(config.getFeatureMap(), r.featureMap); } }
20717348_1
class ResourceModifier { public static String modifyWorkFlowExtensions(String xmlContent) throws APIMigrationException { Writer stringWriter = new StringWriter(); Document doc = ResourceUtil.buildDocument(xmlContent, APIConstants.WORKFLOW_EXECUTOR_LOCATION); if (doc != null) { ...
String workFlowExtensions19 = IOUtils.toString(workflow19Stream); String modifiedWorkFlowExtensions = ResourceModifier.modifyWorkFlowExtensions(workFlowExtensions19); Document modifiedDoc = ResourceUtil.buildDocument(modifiedWorkFlowExtensions, "modifiedWorkFlowExtensions"); Document ex...
20746753_2
class InstancesQueryHandler extends AbstractWorkerQueryHandler { public void setOutputFolder(String outputFolder) { this.outputFolder = outputFolder; } public InstancesQueryHandler(List<Worker> workers); public InstancesQueryHandler(List<Worker> workers, String lang); @Override protected File[] generateQuer...
//Get queries file Connection con = new Connection(); con.setName("a"); con.setEndpoint("http://test.com"); Worker worker = getWorker(con, 1, "1"); InstancesQueryHandler qh = new InstancesQueryHandler(Lists.newArrayList(worker)); qh.setOutputFolder(this.dir); ...
20811348_6
class SshUriPropertyProcessor { public Map<String, JGitEnvironmentProperties> getSshKeysByHostname() { return extractNestedProperties(this.sshUriProperties); } public SshUriPropertyProcessor(MultipleJGitEnvironmentProperties sshUriProperties); protected static String getHostname(String uri); private Map<Stri...
SshUriPropertyProcessor sshUriPropertyProcessor = new SshUriPropertyProcessor(mainRepoPropertiesFixture()); Map<String, JGitEnvironmentProperties> sshKeysByHostname = sshUriPropertyProcessor.getSshKeysByHostname(); assertThat(sshKeysByHostname.values()).hasSize(1); JGitEnvironmentProperties sshKey = sshKeysBy...
20855247_10
class SphereJsonUtils { public static <T> T readObject(final String jsonAsString, final TypeReference<T> typeReference) { return executing(() -> objectMapper.readValue(jsonAsString, typeReference)); } private SphereJsonUtils(); public static ObjectMapper newObjectMapper(); public static ...
final String jsonString = "\"en\""; final Locale locale = SphereJsonUtils.readObject(jsonString, TypeReferences.localeTypeReference()); assertThat(locale).isEqualTo(Locale.ENGLISH); } }
20874043_4
class Highest extends Activation { @Override public void activate(RuleBlock ruleBlock) { if (FuzzyLite.isDebugging()) { FuzzyLite.logger().log(Level.FINE, "Activation: {0} {1}", new String[]{getClass().getName(), parameters()}); } TNorm conjunction = rule...
Engine engine = Console.mamdani(); InputVariable ambient = engine.getInputVariable(0); ambient.setValue(0.3); RuleBlock ruleBlock = engine.getRuleBlock(0); ruleBlock.setActivation(new Highest(1)); engine.process(); List<Rule> rules = engine.getRuleBlock(0).getRul...
20882897_131
class GeometricMeanCalculator implements Function<double[], Double> { @Override public Double apply(double[] x) { ArgChecker.notEmpty(x, "x"); int n = x.length; double mult = x[0]; for (int i = 1; i < n; i++) { mult *= x[i]; } return Math.pow(mult, 1. / n); } private static final...
assertThatIllegalArgumentException() .isThrownBy(() -> GEOMETRIC.apply(null)); } }
20893538_4
class TrivialTask extends AbstractSimpleTask { @Override public Void call() throws Exception { setState(ExecutionState.RUNNING); try { callable.call(); incrementProgress(); } catch (Exception e) { setState(ExecutionState.FAILED); throw e; ...
public void callableProgressTest() throws Exception { final Callable<?> mock = createMockCallable(); final ProgressListener listener = createMockListener(PENDING_REPORT, RUNNING_REPORT, INCREMENTED_REPORT, COMPLETED_REPORT); final Task t = new TrivialTask("Foo", mock); t.addListener...
20898148_15
class ObjectList { public static boolean equals( Object head1, Object head2){ if (head1 != null){ return head1.equals(head2); } else { return head2 == null; // both null is treated as equal } } private ObjectList(); public static Iterator iterator(Object head); public static ...
assertTrue( ObjectList.equals(a1, a2)); a1 = null; a2 = "one"; assertFalse( ObjectList.equals(a1, a2)); a1 = "one"; a2 = null; assertFalse( ObjectList.equals(a1, a2)); a1 = ObjectList.createList("one", "two"); a2 = null; assertFalse( ObjectList.equals(a1, a2)); a1...
20989862_0
class Futures { public static <T> CompletableFuture<T> afterTimeout(T value, long millis) { CompletableFuture<T> future = new CompletableFuture<>(); timer.newTimeout(t -> future.complete(value), millis, TimeUnit.MILLISECONDS); return future; } } class FuturesTest { @Test publ...
CountDownLatch latch = new CountDownLatch(1); Set<String> resultHolder = Collections.newSetFromMap(new ConcurrentHashMap<>()); CompletableFuture<String> slow = Futures.afterTimeout("slow", 1000); CompletableFuture<String> fast = Futures.afterTimeout("fast", 1); fast.acceptEither(...
20990716_0
class RelEx implements Translator, LabelProvider { public Sentence parse(String originalLiteral) { // StrTokenizer tokenizer = new StrTokenizer(originalLiteral); List<String> tokens = tokenizer.tokenize(originalLiteral); log.debug("Tokens: {}", tokens); Sentence sentence = RelexidFactory.eINSTANCE.create...
final Sentence sentence = relex.parse("Aku cinta kamu."); log.info("Sentence structure: {}", sentence); log.info("Sentence in English: {}", sentence.generate(Locale.ENGLISH, DICT_EN_US, relex)); log.info("Sentence in Indonesian: {}", sentence.generate(RelEx.INDONESIAN, DICT_ID_ID, relex)); assertEquals("(S (P...
20991787_0
class ReactiveAudit { boolean isThreadNameMatch(String name) { if (name == null) return false; if (threadPattern == null) { return false; } if (historyThreadName.add(name)) { int now = ManagementFactory.getThreadMXBean().getThreadCount(); int old; for (; ; ) { old = statMaxThread.get()...
TestTools.strict.commit(); assertTrue(config.isThreadNameMatch(Thread.currentThread().getName())); } }
21003796_53
class ScriptUpdatesAnalyzer { public ScriptUpdates calculateScriptUpdates() { // Iterate over the already executed scripts to find out whether the contents of some scripts has been modified // since the last update. We also map the executed scripts with their script counterparts, to be able to veri...
executedScripts(POSTPROCESSING_2, POSTPROCESSING_3); scripts(POSTPROCESSING_3_RENAMED_WITH_INDEX_1, POSTPROCESSING_2); calculateScriptUpdates(); assertPostProcessingScriptUpdate(POSTPROCESSING_SCRIPT_RENAMED, POSTPROCESSING_3, POSTPROCESSING_3_RENAMED_WITH_INDEX_1); } }
21019546_0
class TorConfig { public File getDataDir() { return dataDir; } public static TorConfig createDefault(File configDir); public static TorConfig createFlatConfig(File configDir); public static TorConfig createConfig(File installDir, File configDir, File dataDir); public File getInstallDir...
TorConfig config = new TorConfig.Builder(sampleFile, sampleFile).build(); assertEquals(new File(sampleFile, "lib/tor").getPath(), config.getDataDir().getPath()); } }
21019797_28
class FrameworkScheduler extends Scheduler { boolean onStartJob(JobParameters params) { SchedulerConstraint constraint; try { constraint = fromBundle(params.getExtras()); } catch (Exception e) { JqLog.e(e, "bad bundle from framework job scheduler start callback."); ...
// see https://github.com/yigit/android-priority-jobqueue/issues/254 JobParameters params = mock(JobParameters.class); PersistableBundle badBundle = mock(PersistableBundle.class); when(badBundle.getString(anyString(), anyString())).thenThrow(new NullPointerException()); when(badB...
21052744_4
class SpringSessionBackedSessionRegistry implements SessionRegistry { @Override public List<SessionInformation> getAllSessions(Object principal, boolean includeExpiredSessions) { Collection<S> sessions = this.sessionRepository.findByPrincipalName(name(principal)).values(); List<SessionInformation> infos = new Ar...
setUpSessions(); List<SessionInformation> allSessionInfos = this.sessionRegistry .getAllSessions((AuthenticatedPrincipal) () -> USER_NAME, true); assertThat(allSessionInfos).extracting("sessionId").containsExactly(SESSION_ID, SESSION_ID2); } }
21089070_4
class ClouderaAPIUtil { public static String extractNavigatorURL(String navigatorUrl) { Pattern compile = Pattern.compile("((?:ht|f)tps?\\:\\/\\/[^:]*:[0-9]*)"); Matcher matcher = compile.matcher(navigatorUrl); if (matcher.find()) { return matcher.group(0); } else { ...
assertEquals("http://domain:3333", ClouderaAPIUtil.extractNavigatorURL("http://domain:3333/api/v1/")); assertEquals("https://domain:3333", ClouderaAPIUtil.extractNavigatorURL("https://domain:3333/api/v1/")); assertEquals("http://sd01.sd02.domain:3333", ClouderaAPIUtil.extractNavigatorURL("http:/...
21099161_9
class LinkNormalizer { public String normalize(String original, String extracted) { Validate.notBlank(original); Validate.notNull(extracted); URI originalUri = null; URI extractedUri = null; try { originalUri = new URI(original); extractedUri = new...
// Arrange String original = "http://www.foo.com/bar/baz"; String extracted = "../quux"; // Act String output = linkNormalizer.normalize(original, extracted); // Assert assertEquals("http://www.foo.com/quux", output); } }
21112886_7
class Lexer { public List<Token> lex(final InputStream stream) { try (final BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(stream))) { List<Token> tokens = tokenize(bufferedReader); tokens.add(Token.END_OF_INPUT); return tokens; } cat...
assertEquals(4, lex("a~i~").size()); assertEquals(4, lex("~i~b").size()); assertEquals(6, lex("~i~~id~").size()); assertEquals(7, lex("~i~ ~id~").size()); assertEquals(7, lex("~i~\n~id~").size()); assertEquals(7, lex("~i~\t~id~").size()); assertEquals(7, lex("~i~\...
21138894_2
class VirtualFileRepoCacheImpl implements VirtualFileRepoCache, Disposable { @Nullable @Override public GitRepository getRepoForRoot(@NotNull VirtualFile root) { Preconditions.checkArgument(root.isDirectory(), "%s is not a dir", root); return rootsVFileCache.get(root); } VirtualFileRepoCacheImpl(@...
setupRepo(); assertThat(cache.getRepoForRoot(repositoryRoot)).isEqualTo(repositoryMock); } }