id
stringlengths
7
14
source
stringlengths
135
41.2k
target
stringlengths
36
20.4k
136173345_53
class SnapshotProcessor extends AbstractProcessor { @Override public void process() { if (snapshotMode == CassandraConnectorConfig.SnapshotMode.ALWAYS) { snapshot(); } else if (snapshotMode == CassandraConnectorConfig.SnapshotMode.INITIAL && initial) { snapshot()...
CassandraConnectorContext context = generateTaskContext(); AtomicBoolean globalTaskState = new AtomicBoolean(true); SnapshotProcessor snapshotProcessor = Mockito.spy(new SnapshotProcessor(context)); when(snapshotProcessor.isRunning()).thenReturn(true); context.getCassandraClient...
136324618_13
class SoliumKeyUtils { public static boolean keyExists(String key) { return rulesKeyset.contains(key); } private SoliumKeyUtils(); } class SoliumKeyUtilsTest { @Test public void test() {
assertThat(SoliumKeyUtils.keyExists(("imports-on-top"))).isTrue(); assertThat(SoliumKeyUtils.keyExists("security/no-unreachable-code")).isTrue(); assertThat(SoliumKeyUtils.keyExists("no_rule")).isFalse(); } }
136395597_4
class JdbcDao implements DonkeyDao { @Override public void updateMessageAttachment(String channelId, long messageId, Attachment attachment) { logger.debug(channelId + "/" + messageId + ": updating message attachment"); PreparedStatement segmentCountStatement = null; ResultSet segmentCo...
String channelId = "testchannel"; long messageId = 1; Attachment attachment = new Attachment("testattachment", StringUtils.repeat("testtest", "", 10 * 1024 * 1024 / 8).getBytes(), "text/plain"); ResultSet segmentCountResult = mock(ResultSet.class); PreparedStatement segmentCount...
136437189_3
class SecureNetworkBeacon extends MeshBeacon { protected boolean canOverwrite(final IvIndex ivIndex, final Calendar updatedAt, final boolean ivRecoveryActive, final boolean isTestMode, final boolean ivRecoveryO...
final byte[] data = MeshParserUtils.toByteArray("0102EE6C0EFF5298ECFF000000025E5AA7B268B5E044"); final SecureNetworkBeacon snb = new SecureNetworkBeacon(data); final IvIndex ivIndex = new IvIndex(0, false, Calendar.getInstance()); final Calendar currentTime = Calendar.getInstance(); ...
136439284_6
class Zmq { public static Sink<ZMsg, NotUsed> publishServerSink(String addresses) { return Flow.fromGraph(new ZmqPublishStage(true, addresses)).to(Sink.ignore()); } public static Source<ZMsg, NotUsed> subscribeClientSource(String addresses); public static Source<ZMsg, NotUsed> subscribeClientSource(String...
//Given final int port = findFreePort(); final String addr = "tcp://localhost:" + port; //When Source<ZMsg, TestPublisher.Probe<ZMsg>> testSource = TestSource.probe(system); TestPublisher.Probe<ZMsg> probe = Zmq.publishServerSink(addr).runWith(testSource, materializer); probe.ensureSubscrip...
136447306_0
class CustomTeaser implements Teaser { public String getImgAlign() { return imgAlign; } @Override public boolean isActionsEnabled(); @Override public List<ListItem> getActions(); @Override public String getLinkURL(); @Override public Resource getImageResource(); @Override public bo...
context.currentResource(TEASER1); CustomTeaser customTeaser1 = context.request().adaptTo(CustomTeaser.class); assertNotNull(customTeaser1); assertNotNull(customTeaser1.getImgAlign()); } }
136463642_29
class ValidationUtils { public static List<ParamValidationError> checkNoFieldsOfType(final DatasetSchema schema, final Class<? extends AbstractValueSchema> fieldClass) { final ImmutableList.Builder<ParamValidationError> errors = ImmutableList...
final DatasetSchema schemaWithoutCat = TestDatasetSchemaBuilder.builder() .withCategoricalFields(3) .withNumericalFields(3) .withStringFields(3) .build(); assertThat(ValidationUtils.checkNoFieldsOfType(schemaWithoutCat, CategoricalValueSc...
136544584_3
class MaxTemperatureDriver extends Configured implements Tool { @Override public int run(String[] args) throws Exception { if (args.length != 2) { System.err.printf("Usage: %s [generic options] <input> <output>\n", getClass().getSimpleName()); ToolRunner.printGenericCommandUsage(System.er...
Configuration conf = new Configuration(); conf.set("fs.defaultFS", "file:///"); conf.set("mapreduce.framework.name", "local"); conf.setInt("mapreduce.task.io.sort.mb", 1); Path input = new Path("input/ncdc/micro"); Path output = new Path("output"); FileSystem fs = FileSystem.getLoc...
136567454_1
class HoldingsController { @PostMapping public Holding[] saveHoldings(@RequestBody Holding[] holdings, Principal principal) { User user = getUser(principal); try { String json = mapper.writeValueAsString(holdings); user.getProfile().put(HOLDINGS_ATTRIBUTE_NAME, json); ...
// define mocks Client client = mock(Client.class); User user = mock(User.class); UserProfile userProfile = mock(UserProfile.class); Principal principal = mock(Principal.class); // define behaviour String username = "joe.coder@example.com"; when(principa...
136645456_2
class RequestRetryAuthenticator implements Authenticator { @Nullable @Override public Request authenticate(@NonNull Route route, @NonNull Response response) throws IOException { if (response.priorResponse() != null) { return null; // Give up, we've already attempted to refre...
when(accountAuthenticator.getAccessToken()).thenAnswer(invocation -> validAccessToken); Response unauthenticatedResponse = response.newBuilder() .request( response.request() .newBuilder() ...
136895157_2
class HazelcastQuorumListener extends MembershipAdapter implements HZQuorumListener { @Override public boolean isQuorum() { return isQuorum.get(); } HazelcastQuorumListener(final int quorum); @Override public void memberAdded(final MembershipEvent e); @Override public void memberRemoved(final Membe...
listener = new HazelcastQuorumListener(2); assertFalse(listener.isQuorum()); } }
136936588_1
class BaseUtils { public static String dateToString(Date d) { return dateToString("dd/MM/yyyy", d); } public static Integer getApiVersion(); public static String getPlatformVersion(); public static String checkClientVersion(String serverPlatformVersion, Integer serverApiVersion, String cli...
assertEquals("01/01/1901", BaseUtils.dateToString(new Date(1, 0, 1))); assertEquals("03/12/2001", BaseUtils.dateToString(new Date(101, 11, 3))); assertEquals("14/10/2012", BaseUtils.dateToString(new Date(112, 9, 14))); assertEquals("01.01.1901", BaseUtils.dateToString("dd.MM.yyyy", new ...
136938960_0
class Generator { private static List<Domain> parseProtocol(String protocolFileName) { InputStream resourceStream = Generator.class.getResourceAsStream(protocolFileName); return parseProtocol(resourceStream); } private static ObjectMapper newObjectMapper(); public static void main(String[] args); st...
InputStream resourceStream = getClass().getResourceAsStream("/sample.json"); Generator generator = new Generator(); Domain domain = Domain.builder() .setName("MyDomain") .setDescription("A description.") .setExperimental(true) .setDeprecated(false) .setDependencies(...
136978154_0
class UserNotifier { public void notifyUser(String text, int duration, String id){ if(duration == Snackbar.LENGTH_SHORT) duration = 2000; else if (duration == Snackbar.LENGTH_LONG) duration = 3500; displayMessage(text, duration, id); } protected abstract vo...
TestUserNotifier notifier = new TestUserNotifier(); final String []messageText = {"test", "test2", "testtest\ntest"}; final int[] duration = {1000, Snackbar.LENGTH_SHORT, Snackbar.LENGTH_LONG}; final String []id = {"A", "B", "C"}; for (int i=0; i<3; i++){ notifier.n...
137041394_4
class ClassificationPythonModel implements ClassificationMLModel { @Override public int classify(final Instance instance) { // The Python API supports an array of instances and returns an array of results, we need to adapt to a // single result. final String classValue = invokeFunction(...
final Path modelPath = Paths.get(getClass().getResource("/dummy_model").toURI()); final String id = "classificationModel"; final List<FieldSchema> fields = ImmutableList.of(FIELD_SCHEMA, CATEGORICAL_FIELD_SCHEMA); final String illegalTargetValue = "those"; final DatasetSchema sch...
137178358_1
class DataService implements Serializable { public abstract Collection<Category> getAllCategories()public abstract Collection<Category> getAllCategories(); public abstract Collection<Category> getAllCategories()public abstract Collection<Product> getAllProducts(); public abstract Collection<Category> getAllCategories...
assertFalse(service.getAllCategories().isEmpty()); } }
137437971_1
class StandardVelocityToolsScanner extends AbstractVelocityToolsScanner implements ServletContextAware { @Override protected void scan(String[] sources, Map<String, VelocityTool> velocityToolsMap) { viewToolManager = ViewToolManagerInitializer.getViewToolManager(servletContext); ToolboxFactor...
Map<String, VelocityTool> velocityToolsMap = scanner.scan(); Assert.assertFalse(velocityToolsMap.isEmpty()); } }
137445556_1
class AccountDetailsService implements UserDetailsService { @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { Optional<Account> accountOptional = accountRepository.findByEmail(username); Account account = accountOptional.orElseThrow(() -> new Us...
AccountDetails accountDetails = (AccountDetails) accountDetailsService.loadUserByUsername("user@example.com"); Account account = accountDetails.getAccount(); assertNotNull(account); List<String> authorities = account.getAuthorities(); assertEquals(1, authorities.size()); ...
137451403_39
class Service extends com.alibaba.nacos.api.naming.pojo.Service implements Record, RecordListener<Instances> { public String toJson() { return JacksonUtils.toJson(this); } public Service(); public Service(String name); @JsonIgnore public PushService getPushService(); public long get...
String actual = new Service("test-service").toJson(); System.out.println(actual); assertTrue(actual.contains("\"checksum\":\"394c845e1160bb880e7f26fb2149ed6d\"")); assertTrue(actual.contains("\"clusterMap\":{}")); assertTrue(actual.contains("\"empty\":true")); assertTrue(...
137528592_190
class BytesSSZReader implements SSZReader { @Override public int readInt(int bitLength) { checkArgument(bitLength % 8 == 0, "bitLength must be a multiple of 8"); int byteLength = bitLength / 8; ensureBytes(byteLength, () -> "SSZ encoded data has insufficient length to read a " + bitLength + "-bit integ...
InvalidSSZTypeException ex = assertThrows(InvalidSSZTypeException.class, () -> { SSZ.decode(fromHexString("1122334455667788"), r -> r.readInt(64)); }); assertEquals("decoded integer is too large for an int", ex.getMessage()); } }
137565180_2
class HitbtcRestService implements ManageOrders, Withdraw, Account { @Override public Optional<OrderDto> get(String id) { try { return getOpenOrderById(id); } catch (HttpClientErrorException ex) { if (ex.getStatusCode() != HttpStatus.BAD_REQUEST) { throw ...
OrderDto expectedOrder = mock(OrderDto.class); when(getOrderDto.mapTo()).thenReturn(expectedOrder); when(restTemplate.exchange( requestCaptor.capture(), eq(HttpMethod.GET), entity.capture(), eq(HitbtcOrderGetDto.class) )).t...
137570946_52
class NewNodeCatchUpTaskGroup { public boolean onReceiveAppendEntriesResult(AppendEntriesResultMessage resultMessage, int nextLogIndex) { NewNodeCatchUpTask task = taskMap.get(resultMessage.getSourceNodeId()); if (task == null) { return false; } task.onReceiveAppendEntri...
NewNodeCatchUpTaskGroup group = new NewNodeCatchUpTaskGroup(); Assert.assertFalse(group.onReceiveAppendEntriesResult( new AppendEntriesResultMessage( new AppendEntriesResult("", 1, true), NodeId.of("A"), new AppendEn...
137728198_47
class LogicalPlan extends TreeNode implements QueryItemInterface { public Query getQuery() { return query; } public LogicalPlan(String description); public TreeNode getCurrentNode(); public void setCurrentNode(TreeNode currentNode); public void setQuery(Query query); public Creat...
String sql = "select a, b from TRANSACTION t where a = 'hello world' group by c having b > 100"; LogicalPlan plan = getLogicalPlan(sql); LogicalPlan logicalPlan = buildHaving(); assertTrue(logicalPlan.getQuery().equals(plan.getQuery())); } }
137746205_1
class AddEditTaskLogic { @Nonnull public static Next<AddEditTaskModel, AddEditTaskEffect> update( AddEditTaskModel model, AddEditTaskEvent event) { return event.map( taskDefinitionCompleted -> onTaskDefinitionCompleted(model, taskDefinitionCompleted), taskCreatedSuccessfully -> exitWithSu...
TaskDetails details = TaskDetails.create("T1", "This is a task"); AddEditTaskModel updatingATask = AddEditTaskModel.builder().mode(AddEditTaskMode.update("123")).details(details).build(); TaskDetails updatedDetails = details.toBuilder().title("").description("Hello World").build(); updateSpec ...
137762067_28
class JiraTransitionIssueActionHandler implements BentenActionHandler { public BentenHandlerResponse handle(BentenMessage bentenMessage) { String issueKey = BentenMessageHelper.getParameterAsString(bentenMessage,JiraActionParameters.PARAMETER_ISSUE_KEY); String status = BentenMessageHelper.getParam...
String issueKey = TestHelper.createStory(bentenJiraClient); TestHelper.updateAssigneeAndReporter(bentenJiraClient,issueKey); JsonElement status = new JsonPrimitive("Closed"); JsonElement currentuser = new JsonPrimitive(TestHelper.assigneeName); Thread.sleep(500); Bente...
137771260_2
class XMLHashtable extends XMLValue { @Override public String toXml() { final StringBuilder ret = new StringBuilder( "<" + getXMLTag() + " " + getColumnLabel(SIZEIDX) + "=\"" + size + "\" >"); for (int i = 0; i < size; i++) { ret.append(tuples[i].toXml()); } ret.append("</" + getXMLTag() + ">"); ...
try { final Collection v = new Vector(); v.add(new String("a string in vector")); v.add(new Integer(100)); v.add(new Boolean("true")); final Hashtable h = new Hashtable(); final Hashtable subHash = new Hashtable(); h.put(new Integer(1), new String("un")); h.put(new String("deux"), new Integer(...
137793178_1
class RunMapImpl implements RunMap { public void reinitialize() { runMapLock.writeLock().lock(); try { for (TestEntry testEntry : runMap.values()) { testEntry.init(); testEntry.reinitTime(); } clearCurrentTestResults(); } f...
AbstractTest test = new MockTest(); runMap.addTest(test); for (int i = 0; i < 100; i++) { runMap.record(createTestResult(test, TestResult.Status.PASSED)); } Assert.assertEquals(100, runMap.getCurrentTestResults().size()); Assert.assertEquals(100, runMap.getRe...
137794579_2
class Mapper { public String convertDateTime(Date date) { return iso8601DateFormat.format(date); } public Mapper(); public Date convertDateTime(String isodate); TimeZone convertTimeZone(String timeZone); static final String[] ISO_DATETIME_EXAMPLES; } class MapperTest { static final String[] I...
Mapper mapper = new Mapper(); TimeZone timeZone = new SimpleTimeZone(0, "GMT"); GregorianCalendar calendar = new GregorianCalendar(timeZone); calendar.set(Calendar.YEAR, 2015); calendar.set(Calendar.MONTH, 03); calendar.set(Calendar.DATE, 26); calendar.set(Calendar.HOUR_OF_DAY, 1); calen...
137988099_78
class WXImage extends WXComponent<ImageView> { @Override protected ImageView initComponentHostView(@NonNull Context context) { WXImageView view = new WXImageView(context); view.setScaleType(ScaleType.FIT_XY); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { view.setCropToPadding(tru...
ImageView imageView = mWXImage.initComponentHostView(Robolectric.setupActivity(TestActivity.class)); mWXImage.mHost = imageView; mWXImage.setBackgroundColor("#FFFFFF"); Drawable drawable = mWXImage.getHostView().getBackground(); assertEquals(drawable instanceof BorderDrawable, true); } }
138077755_37
class Range { @Override public Range clone() { return new Range(start.clone(), end.clone()); } public Range(); public void add(LineColumn position); public void add(Range... ranges); public void add(Range range); public boolean contains(LineColumn position); Range range...
assertEquals(range.clone(), range); } }
138123418_32
class Parser { public List<Derivation> parseSyntactic(String input){ List<String> tokens = tokenizer.tokenize(input); List<String> tokensLower = new ArrayList<>(tokens.size()); for(String token: tokens) tokensLower.add(token.toLowerCase()); int N = tokens.size(); ...
Rule r1 = new Rule("$A", "a"); Rule r2 = new Rule("$B", "b"); Rule r3 = new Rule("$C", "$A $B"); Grammar grammar = new Grammar(Arrays.asList(r1, r2, r3), "$C"); Parser p = new Parser(grammar, s -> Arrays.asList(s.split(" ")), Collections.emptyList()); Derivation dc1 = n...
138216750_32
class ConnectionParams { public String getTelemetryTopic() { return mTelemetryTopic; } private ConnectionParams( @NonNull String projectId, @NonNull String registryId, @NonNull String deviceId, @NonNull String cloudRegion, @NonNull Strin...
ConnectionParams connectionParams = buildAllParameters(); String expectedTelemetrytopic = "/devices/" + DEVICE_ID + "/events"; assertThat(connectionParams.getTelemetryTopic()).isEqualTo(expectedTelemetrytopic); } }
138269161_17
class AsyncLoadBalancingTcpClient extends AbstractLoadBalancerAwareClient<TcpRequest, AsyncTcpResponse> { @Override public RequestSpecificRetryHandler getRequestSpecificRetryHandler(TcpRequest request, IClientConfig requestConfig) { if (!request.isRetriable()) { return new RequestSpecificR...
TcpRequest request = new TcpRequest.Builder(new URI("http://127.0.0.1"), null, true).build(); AsyncLoadBalancingTcpClient client = new AsyncLoadBalancingTcpClient(); RequestSpecificRetryHandler handler = client.getRequestSpecificRetryHandler(request, null); assertTrue(handler.isRetriabl...
138315669_64
class XMLScanner implements Scanner { public static Scanner createScanner(String input) { return createScanner(input, false); } public XMLScanner(String input, int initialOffset, ScannerState initialState, boolean isDTDFile); boolean hasNextElementName(); boolean hasNextAttributeName(); boolean hasNextAt...
scanner = XMLScanner.createScanner("<a</a>"); assertOffsetAndToken(0, TokenType.StartTagOpen); assertOffsetAndToken(1, TokenType.StartTag); assertOffsetAndToken(2, TokenType.EndTagOpen); assertOffsetAndToken(4, TokenType.EndTag); assertOffsetAndToken(5, TokenType.EndTagClose); } }
138608373_5
class IAMReader extends IAMStream { public JSONObject read(IAMIndex index) { return readFromSelection(index, null); } public IAMReader(String id); public JSONObject readFromSelection(IAMIndex index, List<Transaction> selection); public String getID(); private JSONObject findConsensus...
JSONObject message1 = new JSONObject().put("planet", "mars"); JSONObject message2 = new JSONObject().put("planet", "venus"); iamWriter.write(new IAMIndex(100), message1); assertNotNull(iamReader.read(new IAMIndex(100))); iamWriter.write(new IAMIndex(100), message1); ass...
138623536_35
class CreateGroupOperation implements PostOperation { @Override public void run(SlingHttpServletRequest request, PostResponse response, SlingPostProcessor[] processors) { final List<Modification> changes = new ArrayList<>(); try { String name = request.getParameter(SlingPostConstan...
CreateGroupOperation createGroupOperation = new CreateGroupOperation(); PostResponse response = new JSONResponse(); context.currentResource("/home/users"); context.request().setParameterMap( ImmutableMap.<String, Object>builder().put(SlingPostConstants.RP_NODE_NAME, "tes...
138890589_49
class RowSpecGrouper { public static Set<FieldSpecGroup> createGroups(RowSpec rowSpec) { List<FieldPair> pairs = rowSpec.getRelations().stream() .map(relation -> new FieldPair(relation.main(), relation.other())) .collect(Collectors.toList()); return findGroups(rowSpec.getFi...
Field first = createField("first"); Field second = createField("second"); Fields fields = new ProfileFields(Arrays.asList(first, second)); Map<Field, FieldSpec> fieldSpecMap = fieldSpecMapOf(first, second); FieldSpecRelation relation = link(first, second); List<FieldSpe...
138907954_6
class ParamUtils { public static <T> T nonNull(final T object, final Supplier<String> message) { if (object != null) { return object; } throw new IllegalArgumentException(message.get()); } private ParamUtils(); public static void validate(final boolean condition, ...
final String myString = "hello world"; final String returned = ParamUtils.nonNull(myString, () -> "Should not throw"); Assert.assertSame(returned, myString); } }
138952078_0
class Dot { public static <ID> Dot<ID> dot(Graph<ID> graph) { return new Dot<>(graph); } private Dot(Graph<ID> graph); public String getType(); public void setType(String type); public Dot type(String type); public void write(Writer writer); private void writeGraphAttributes(...
NullPointerException thrown = assertThrows(NullPointerException.class, () -> dot(null)); assertThat(thrown).hasMessageThat().isEqualTo("graph must not be null."); } }
138967647_1
class UserEventHandler { @QueryHandler public UserView find(UserByIdQuery query) { String userId = query.getUserId().getIdentifier(); return Optional.ofNullable(userRepository.findByIdentifier(userId)) .orElseGet(() -> { logger.warn("Tried to re...
UserView testView = buildTestView(); when(userViewRepository.findByIdentifier(testUserId.getIdentifier())).thenReturn(testView); UserView result = testSubject.find(new UserByIdQuery(testUserId)); assertEquals(testView, result); } }
139051087_2
class MySQLIntervalLock extends JdbcIntervalLock { @Override protected String buildTryLockSql(TableConfig tableConfig) { return new StringBuilder() .append("INSERT INTO ") .append(getSafeName(tableConfig.getSchema())) .append(".") .append(getSafeName(tableConfig.getTable())) ...
MySQLIntervalLock mySQLIntervalLock = new MySQLIntervalLock(dataSource); String tryLockSQL = mySQLIntervalLock.buildTryLockSql(new TableConfig()); assertEquals( "INSERT INTO `public`.`lock` (`name`, `owner`, `locked_at`, `locked_till`)\n" + "SELECT :name, :owner, CURRENT_TIMESTAMP(), CUR...
139242712_9
class Locale { public String message(String s, Object... objects) { return messageSource.getMessage(s, objects, nativeLocale); } @Autowired public Locale(@Value("#{localeCodeSource.code}") String code, MessageSource messageSource); public String message(String s); } class LocaleTest { ...
String testedString = "Some string {change}"; MessageSource mock = mock(MessageSource.class); Locale locale = new Locale("ru", mock); locale.message(testedString); verify(mock, times(1)).getMessage(eq(testedString), eq(new Object[0]), any()); } }
139299365_25
class TermFrequencySearcher { private long getFrequency(NGramField field) throws IOException { return getFrequency(field, null); } public TermFrequencySearcher(SolrQueryRequest request); public FrequencyMap getFrequencyHashMap(TokenizedString tokens, FrequencyMap map); public Freq...
setUpRequestMock(); setUpFrequencyMocks(NGramField.bigrams, "underwater basketweaver", 1L); TermFrequencySearcher target = new TermFrequencySearcher(mockedRequest); Long actual = Deencapsulation.invoke(target,"getFrequency", NGramField.bigrams, "underwater basketweaver"); Long ex...
139344139_1
class NumarComplex { public NumarComplex add(NumarComplex z) { this.setReal(this.real + z.getReal()); this.setImg(this.img + z.getImg()); return this; } public NumarComplex(); public NumarComplex(String nr); public double getImg(); public void setImg(double img);...
NumarComplex nr=new NumarComplex("3+i"); nr.add(new NumarComplex("i")); assertEquals(new NumarComplex("3.0+2.0i"), nr); } }
139520942_65
class TypeDecoder { static Utf8String decodeUtf8String(String input, int offset) { DynamicBytes dynamicBytesResult = decodeDynamicBytes(input, offset); byte[] bytes = dynamicBytesResult.getValue(); return new Utf8String(new String(bytes, StandardCharsets.UTF_8)); } static int getS...
assertThat(TypeDecoder.decodeUtf8String( "000000000000000000000000000000000000000000000000000000000000000d" // length + "48656c6c6f2c20776f726c642100000000000000000000000000000000000000", 0), CoreMatchers.is(new Utf8String("Hello, world!"))); } }
139621153_94
class Vector2 extends AVector2 { public static Vector2 fromXY(final double x, final double y) { return new Vector2(x, y); } protected Vector2(); protected Vector2(final double x, final double y); protected Vector2(final IVector original); public static Vector2 zero(); public static Vector2 fromX(final d...
Vector2 vec1 = Vector2.fromXY(1, 3); Vector2 vec2 = Vector2.fromXY(-4, 2); double result = vec1.scalarProduct(vec2); assertEquals(2f, result, ACCURACY); vec1 = Vector2.fromXY(1, 3); vec2 = Vector2.fromXY(0, 0); result = vec1.scalarProduct(vec2); assertEquals(0f, result, ACCURACY); vec1 = Vector2...
139879729_5
class DistanceCalculator { public double getDistance( double latitude1, double longitude1, double latitude2, double longitude2) { double latitudeDifference = Math.toRadians(latitude2 - latitude1); double longitudeDifference = Math.toRadians(longitude2 - longitude1); latitude1 = Math.toRadians(latitude1); ...
Assert.assertEquals( 69.382, _distanceCalculator.getDistance( _LATITUDE, _LONGITUDE, 34.045886, -118.564861), _DELTA); Assert.assertEquals( 9070.629, _distanceCalculator.getDistance( _LATITUDE, _LONGITUDE, 48.856614, 2.352222), _DELTA); } }
139898859_32
class CLIParser { public static Arg parse(String[] inputArgs) { Options options = setupOptions(); CommandLineParser parser = new DefaultParser(); Arg argument = new Arg(); try { CommandLine commandLine = parser.parse(options, inputArgs); if (commandLine.has...
Arg parsedArg = CLIParser.parse(asArgArray("'" + defaultPw + "' -" + CLIParser.ARG_HASH + " 6")); Arg expectedArg = new Arg(defaultPw.toCharArray(), null, 6); assertEquals(expectedArg, parsedArg); } }
139914932_102
class KafkaStreamsTopicsHealthCheck implements HealthCheck { @Override public HealthCheckResponse call() { HealthCheckResponseBuilder builder = HealthCheckResponse.named("Kafka Streams topics health check").up(); try { Set<String> missingTopics = manager.getMissingTopics(trimmedTop...
Mockito.when(manager.getMissingTopics(anyList())).thenReturn(Collections.emptySet()); HealthCheckResponse response = healthCheck.call(); assertThat(response.getState()).isEqualTo(HealthCheckResponse.State.UP); } }
139927346_48
class MapUtil { public static <K, V> HashMap<K, V> newHashMap() { return new HashMap<K, V>(); } public static boolean isEmpty(final Map<?, ?> map); public static boolean isNotEmpty(final Map<?, ?> map); public static V putIfAbsentReturnLast(@NotNull final ConcurrentMap<K, V> map, final K key, final V value); ...
try { HashMap<String, Integer> map4 = MapUtil.newHashMap(new String[] { "1", "2" }, new Integer[] { 1 }); fail("should fail here"); } catch (Exception e) { assertThat(e).isInstanceOf(IllegalArgumentException.class); assertThat(e).hasMessage("keys.length is 2 but values.length is 1"); } } }
139940514_67
class WxPayOrderNotifyResult extends BaseWxPayResult { public static WxPayOrderNotifyResult fromXML(String xmlString) { XStream xstream = XStreamInitializer.getInstance(); xstream.processAnnotations(WxPayOrderNotifyResult.class); xstream.registerConverter(new WxPayOrderNotifyResultConverter(xstream.getMa...
String xmlString = "<xml>\n" + " <appid><![CDATA[wx2421b1c4370ec43b]]></appid>\n" + " <attach><![CDATA[支付测试]]></attach>\n" + " <bank_type><![CDATA[CFT]]></bank_type>\n" + " <fee_type><![CDATA[CNY]]></fee_type>\n" + " <is_subscribe><![CDATA[Y]]></is_subscribe>\n" + " <mch_id...
140008964_0
class TimeWarpedClock implements Clock { @Override public void sleep(long dt, TimeUnit timeUnit) throws InterruptedException { Thread.sleep((long) (timeUnit.toMillis(dt) / speedMultiplier)); } public TimeWarpedClock(double speedMultiplier, long startTime); public TimeWarpedClock(double s...
TimeWarpedClock clock = new TimeWarpedClock(10); Stopwatch stopwatch = new Stopwatch(clock); stopwatch.resetIfNotInit(); try { Thread.sleep(5); } catch (InterruptedException e) { e.printStackTrace(); } assertEquals(50, stopwatch.pop(), ...
140073232_0
class UsersRepositoryConnectionImpl implements UsersRepository { @Override public Optional<User> findOne(Long id) { try { PreparedStatement statement = connection.prepareStatement(SQL_FIND_BY_ID); statement.setLong(1, id); ResultSet resultSet = statement.executeQuery...
Optional<User> actualOptional = userRepository.findOne(1L); if (!actualOptional.isPresent()) { fail("Return object is null"); } else { User actual = actualOptional.get(); assertEquals(EXPECTED_USER, actual); } } }
140255413_6
class MarqetaClient { public CreateUserResponse createUser(CreateUserRequest request) { try { final String url = baseUrl + "/users"; return restTemplate.postForObject(url, request, CreateUserResponse.class); } catch (HttpStatusCodeException cause) { throw errorFactory.fromResponseBody(cause...
final CreateUserResponse response = new CreateUserResponse(); when(restTemplate.postForObject(any(), any(), any(), any(Object[].class))).thenReturn(response); final CreateUserRequest request = new CreateUserRequest(); assertThat(target.createUser(request), is(sameInstance(response))); verify(rest...
140269650_6
class ChordHelper { public int getWithFirstString(Chord chord) { int string = 1; int[] frets = chord.getFrets(); int[] fingers = chord.getFingers(); while (frets[frets.length - 1] == frets[frets.length - 1 - string]) { if(fingers!=null){ if(fingers[finger...
assertThat(mChordHelper.getWithFirstString(mChords.get(0)), is(1)); assertThat(mChordHelper.getWithFirstString(mChords.get(1)), is(1)); assertThat(mChordHelper.getWithFirstString(mChords.get(2)), is(1)); assertThat(mChordHelper.getWithFirstString(mChords.get(3)), is(2)); } }
140540897_44
class CreditCardAuthorizationParesPaymentProcessor implements PaymentProcessor { @Override public void processPayment(Payment payment, PaymentOperationData data) throws WirecardPaymenException { String pares = data.getPares(); ThreeD threeD = objectFactory.createThreeD(); threeD.getCont...
this.payment = new Payment(); creditCardAuthorizationParesPaymentProcessor.processPayment(this.payment, data); Assert.assertEquals("response is not equals",this.threeD, payment.getThreeD()); } }
140874933_5
class FileGenerator { void generateServiceDispatcher(Writer output) throws IOException, TemplateException { configuration.getTemplate("ServiceDispatcherTemplate.ftl").process(dispatcherContext, output); } public FileGenerator(List<AnalysisResult> results, String outputPath); public void gene...
AnalysisResult result = buildResult(); List<AnalysisResult> results = new LinkedList<>(); results.add(result); FileGenerator fileGenerator = new FileGenerator(results, "."); StringWriter writer = new StringWriter(); fileGenerator.generateServiceDispatcher(writer); ...
141102600_0
class Decision { public String toJsonString() throws JsonProcessingException { return ObjectMapperProvider.get().writeValueAsString(this); } public static Decision fromJsonString(String json); } class DecisionTest { @Test public void shouldSerializeToJson() throws JsonProcessingExceptio...
LocalDateTime now = LocalDateTime.now().plusNanos(1); Request request = new Request( "user1", "manager1", now, "Proszę o urlop"); Decision d = new Decision( "manager1", request, now, ...
141169138_0
class UserMessage { public String getMessage() { return message; } private UserMessage(Builder builder); public int getBackgroundColor(); public void setBackgroundColor(int backgroundColor); public int getTextColor(); public void setTextColor(int textColor); public void setMe...
UserMessage userMessage = new UserMessage.Builder().with(mContext).build(); assertNotNull(userMessage.getMessage()); } }
141267788_13
class SamlSettings { String getApplicationId() { return configuration.get(APPLICATION_ID).orElseThrow(() -> new IllegalArgumentException("Application ID is missing")); } public SamlSettings(Configuration configuration); String getProviderId(); String getProviderName(); String getLoginUrl(); St...
assertThat(underTest.getApplicationId()).isEqualTo("sonarqube"); } }
141270248_1
class FileManager { public static boolean createUserFolder(final String folder) throws IOException { final String tempPath = FileManager.libDir + OsUtils.getSeparator() + LibPaths.USER.getDirName() + OsUtils.getSeparator() + folder.replaceAll("\\s+", "_"); return FileManager.createD...
Assertions.assertDoesNotThrow(() -> FileManager.createUserFolder(FileManagerTest.USER_FOLDER)); } }
141304234_0
class OpenKoreanTextNormalizer extends BaseCharFilter { @Override public int read(char[] cbuf, int off, int len) throws IOException { if (off < 0) throw new IllegalArgumentException("off < 0"); if (off >= cbuf.length) throw new IllegalArgumentException("off >= cbuf.length"); if (len <= ...
String query = "한국어를 처리하는 예시입니닼ㅋ. 오픈코리안텍스틓ㅎㅎㅎㅎㅎㅎㅎ"; String expected = "한국어를 처리하는 예시입니다ㅋ. 오픈코리안텍스트ㅎㅎㅎ"; CharFilter inputReader = new OpenKoreanTextNormalizer(new StringReader(query)); char[] tempBuff = new char[10]; StringBuilder actual = new StringBuilder(); while (tru...
141402922_2
class Absence extends SequentialGetStepSupplier.GetObjectChainedStepSupplier<T, Boolean, Object, Absence<T>> { private Absence(Function<T, ?> toBeAbsent) { super("Absence of " + (isLoggable(toBeAbsent) ? toBeAbsent.toString() : "<not described value>"), o -> ofNullable(o) ...
var start = currentTimeMillis(); assertThat(testContext.absence(new TestGetSupplier<>(new FunctionThatReturnsObject(ofSeconds(5)).run()), ofSeconds(10)), is(true)); var end = currentTimeMillis(); assertThat(new BigDecimal(end - start), closeTo(new BigDecim...
141550213_24
class DosSantosPairwiseRankingLoss implements ILossFunction { public INDArray scoreArray(INDArray labels, INDArray preOutput, IActivation activationFn, INDArray mask) { INDArray scoreArr; INDArray output = activationFn.getActivation(preOutput.dup(), true); INDArray mPluss = Nd4j.zeros(output.shape()).ad...
INDArray label = Nd4j.create(1, 2); label.put(0, 0, 1); label.put(0, 1, 0); INDArray preOutput = Nd4j.create(label.shape()); preOutput.put(0, 0, 4); preOutput.put(0, 1, 0); INDArray mask = Nd4j.ones(1,1); IActivation tanH = new ActivationTanH(); DosSantosPairwiseRankingLos...
141591175_0
class MyJavaRulesDefinition implements RulesDefinition { @Override public void define(Context context) { NewRepository repository = context .createRepository(REPOSITORY_KEY, Java.KEY) .setName("Sonar Secrets Java"); List<Class> checks = RulesList.getChecks(); new RulesDefinitionAnnotationL...
MyJavaRulesDefinition rulesDefinition = new MyJavaRulesDefinition(); RulesDefinition.Context context = new RulesDefinition.Context(); rulesDefinition.define(context); RulesDefinition.Repository repository = context.repository(MyJavaRulesDefinition.REPOSITORY_KEY); assertThat(repository.name()).isEq...
141626961_1
class ItemsBuilder extends ItemsBuilderAbstraction { @Override public DateTime getNextAlarmDate(DateTime executionDate) { return getBuildingStrategy().getNextAlarmDate(executionDate); } @Override public List<Item> getItems(DateTime currentDate, DateTime executionDate); @Override public boo...
itemsBuilder.setBuildingStrategy(new SleepNowBuildingStrategy()); assertEquals(getDateTime("05/02/2011 02:30"), itemsBuilder.getNextAlarmDate(getDateTime("05/02/2011 01:00"))); assertEquals(getDateTime("06/02/2011 01:25"), itemsBuilder.getNextAlarmDate(getDateTime("05/02/2011 23:55"))); ...
141633330_19
class WebSocket extends Transport { @Override public boolean isWritable() { return true; } public WebSocket(EngineIoWebSocket webSocket); @Override public void onRequest(HttpServletRequest request, HttpServletResponse response); @Override public void send(List<Packet<?>> packets); ...
final WebSocket webSocket = new WebSocket(Mockito.mock(EngineIoWebSocket.class)); assertTrue(webSocket.isWritable()); } }
141671109_207
class Request { public T send() throws IOException { return web3jService.send(this, responseType); } public Request(); public Request(String method, List<S> params, Web3jService web3jService, Class<T> type); public String getJsonrpc(); public void setJsonrpc(Strin...
web3j.ethGetUncleByBlockNumberAndIndex( DefaultBlockParameter.valueOf(Numeric.toBigInt("0x29c")), BigInteger.ZERO).send(); verifyResult("{\"jsonrpc\":\"2.0\",\"method\":\"eth_getUncleByBlockNumberAndIndex\"," + "\"params\":[\"0x29c\",\"0x0\"],\"id\":1}"); } }
141752763_0
class CorsHandler implements HttpHandler { @Override public void handleRequest(HttpServerExchange exchange) throws Exception { HeaderMap responseHeaders = exchange.getResponseHeaders(); responseHeaders.add(HttpString.tryFromString("Access-Control-Allow-Origin"), "*"); handler.handleRequ...
corsHandler.handleRequest(dummyExchange); assertTrue(testHandler.hasCalled()); } }
142015901_2
class RouterFunctions { public static Builder route() { return new RouterFunctionBuilder(); } public static RouterFunction<T> route( RequestPredicate predicate, HandlerFunction<T> handlerFunction); public static RouterFunction<T> nest( RequestPredicate predicate, RouterFunction<T> routerFunction); public...
RouterFunction<ServerResponse> routerFunction1 = request -> Mono.empty(); RequestPredicate requestPredicate = request -> true; RouterFunction<ServerResponse> result = routerFunction1.andRoute(requestPredicate, this::handlerMethod); assertNotNull(result); MockServerRequest request = MockServerRequest.builder...
142037766_2
class PartitionUtil { public static void greedyPartition(Collection<TestTime> testTimes, Set<TestContainer> testContainers) { if(testContainers.isEmpty()) { throw new IllegalArgumentException("Queue must be populated with a partition for each host"); } List<TestTime> sortedList...
Timestamp now = Timestamp.from(Clock.systemUTC().instant()); TestTime test1 = new TestTime("test1", 10, false, "host1", now); TestTime test2 = new TestTime("test2", 5, false, "host1", now); TestTime test3 = new TestTime("test3", 1, false, "host1", now); TestTime test4 = new TestT...
142085119_2
class HandshakeSessionHandler implements MinecraftSessionHandler { @VisibleForTesting static String cleanVhost(String hostname) { // Clean out any anything after any zero bytes (this includes BungeeCord forwarding and the // legacy Forge handshake indicator). String cleaned = hostname; int zeroIdx ...
assertEquals("localhost", cleanVhost("localhost" + HANDSHAKE_HOSTNAME_TOKEN)); assertEquals("mc.example.com", cleanVhost("mc.example.com" + HANDSHAKE_HOSTNAME_TOKEN)); } }
142101199_0
class Function { @FunctionName("HttpTrigger-Java") public HttpResponseMessage run( @HttpTrigger(name = "req", methods = {HttpMethod.GET, HttpMethod.POST}, authLevel = AuthorizationLevel.FUNCTION) HttpRequestMessage<Optional<String>> request, final ExecutionContext context) { con...
// Setup @SuppressWarnings("unchecked") final HttpRequestMessage<Optional<String>> req = mock(HttpRequestMessage.class); final Map<String, String> queryParams = new HashMap<>(); queryParams.put("name", "Azure"); doReturn(queryParams).when(req).getQueryParameters(); ...
142141420_42
class AssetManagerImpl implements IAssetManager { @Override public Response urlValidate(Map<String, Object> asset, String field) { IURLManager urlManager = getURLManager(getProvider(asset)); Map<String, Object> fieldMap = urlManager.validateURL(getUrl(asset), field); Response response = new Respons...
Map<String, Object> asset = new HashMap<>(); asset.put(AssetParams.provider.name(), ""); asset.put(AssetParams.url.name(), "https://www.youtube.com/watch?v=nA1Aqp0sPQo"); try { assetManager.urlValidate(asset, "license"); } catch (ClientException e) { asser...
142195981_33
class Pattern3 implements PartialFunction3<A, B, C, R> { private Pattern3() { this(Pattern1.build()); } private Pattern3(); private Pattern3(Pattern1<Tuple3<A, B, C>, R> pattern); @Override public boolean isDefinedAt(A a, B b, C c); @Override public R apply(A a, B b, C c); public static Pattern3<...
Pattern3<Object, Object, Object, Object> pattern3 = Pattern3.build() .when((a, b, c) -> a.equals(b) && b.equals(c) && a.equals(c)).returns("a equals b equals c") .otherwise().returns("not equals"); assertAll(() -> assertEquals("a equals b equals c", pattern3.apply("a", "a", "a")), () ...
142735552_0
class SelectionManager { public SelectionManager(LauncherConfiguration conf, StatusManager statusManager, RequestManager requestManager) { this.conf = conf; this.statusManager = statusManager; this.requestManager = requestManager; } public SelectionManager(LauncherConfiguration conf, StatusManager ...
Node node1 = new Node("node1", null, ResourceDescriptor.newInstance(200, 200, 2, 3L), ResourceDescriptor.newInstance(0, 0, 0, 0L)); Node node2 = new Node("node2", null, ResourceDescriptor.newInstance(200, 200, 4, 0xFL), ResourceDescriptor.newInstance(0, 0, 0, 0L)); Node node3 = new Node("node3", null, Resou...
142747385_9
class OSHDBBoundingBox implements Serializable { public long[] getLon() { return new long[]{minLon, maxLon}; } public OSHDBBoundingBox(long minLon, long minLat, long maxLon, long maxLat); public OSHDBBoundingBox(double minLon, double minLat, double maxLon, double maxLat); public OSHDBBoundingBox(int ...
OSHDBBoundingBox instance = new OSHDBBoundingBox(0.0, 89.0, 1.0, 90.0); long[] expResult = new long[]{0L, 10000000L}; long[] result = instance.getLon(); assertArrayEquals(expResult, result); } }
142758232_6
class OrderRepository implements OrderDataSource { public OrderList getAllCachedOrderHistory() { return cachedOrderList; } private OrderRepository(@NonNull final BlockchainSource blockchainSource, @NonNull final EventLogger eventLogger, @NonNull final OrderDataSource.Remote remoteData, @NonNull final Orde...
assertNull(orderRepository.getAllCachedOrderHistory()); } }
142763963_24
class RiceCompression { public List<Integer> decompress(int riceParameter, byte[] data) { BitSet bits = new BitSet(data.length * 8); for (int i = 0; i < data.length; i++) { BitSet bitsOfByte = BitSet.valueOf(makeArrayOfByte(data[i])); for (int j = 0; j < bitsOfByte.size(); ...
byte[] bytes = Base64.getDecoder().decode(data1); List<Integer> ls = riceCompression.decompress(parameter, bytes); Assert.assertEquals(336, ls.size()); } }
143078890_1
class TableReporter { static void processRowResult(Result result, Sketches sketches) { // System.out.println(result.toString()); long rowSize = 0; int columnCount = 0; for (Cell cell : result.rawCells()) { rowSize += estimatedSizeOfCell(cell); columnCount += 1; } sketches.rowSizeS...
TableReporter.Sketches sketches = new TableReporter.Sketches(); final int rows = 10; final int columns = 3; final int versions = 2; for (int i = 0; i < rows; i++) { TableReporter.processRowResult(Result.create(makeCells(Bytes.toBytes(i), columns, versions)), sketches); } sketches.print...
143127772_1
class JdbcBatchLoader extends BaseJdbcLoader { @Override public void sort(ETLBucket bucket) { bucket.getParallelRows().addAll(batchGroup(bucket.getRows())); } @Override protected String getPluginName(); @Override public Pair<Boolean, List<DSubmitStatObject>> doLoad(ETLBucket bucket); } c...
List<ETLRow> rows = new ArrayList<>(); rows.add(new ETLRow(0, 0, "s", "t", MessageAction.DELETE, null, null, null)); rows.add(new ETLRow(0, 0, "s", "t", MessageAction.DELETE, null, null, null)); rows.add(new ETLRow(0, 0, "s", "t", MessageAction.INSERT, null, null, null)); rows.ad...
143152220_23
class ControllerModel { public boolean match(String route) { for (String originalRoute : this.originalRoute) { if (this.matchShell(originalRoute, route)) { String routeWithoutShell = this.getRouteWithoutShell(originalRoute); String startRouteWithoutShell = thi...
ControllerModel cm = this.getControllerModelForMatchingTest("/*/route01/:parameter", "route01"); Assertions.assertFalse(cm.match("shell01/route02")); } }
143201223_37
class Time { public static org.joda.time.Duration parseDuration(String value) { return parseJodaDuration(value); } public static ValueProvider<org.joda.time.Duration> parseDuration(ValueProvider<String> value); public static long parseSeconds(String value); public static ValueProvider<Long> parseSeconds...
assertEquals(Time.parseDuration("5.5 seconds").getMillis(), 5500L); assertEquals(Time.parseDuration("5.5 SECONDS").getMillis(), 5500L); assertEquals(Time.parseDuration("1 hour").getMillis(), HOURS.toMillis(1)); assertEquals(Time.parseDuration("2 days").getMillis(), DAYS.toMillis(2)); assertEquals(Ti...
143267111_2
class PolicyQueryResultAssembler { static FindPolicyQueryResult constructResult(List<PolicyView> policies) { return new FindPolicyQueryResult( policies.stream() .map(PolicyListItemDtoAssembler::map) .sorted(Comparator.comparing(PolicyListItemD...
PolicyQueryResultAssembler assembler = new PolicyQueryResultAssembler(); List<PolicyView> policies = new ArrayList<>(Arrays.asList( new PolicyView("1", LocalDate.of(2015,11,1), LocalDate.of(2016,10,30), "Tom Hanks"), new PolicyView("2", null, null, "Alanis Morissette"), ...
143269609_0
class GetReposUseCase extends BaseUseCase { public Flowable<List<Repos>> get(ReposParam param) { return reposRepository .all(param) .subscribeOn(executionThread) .observeOn(postExecutionThread); } @Inject public GetReposUseCase(ReposRepository userR...
ReposParam param = new ReposParam("testName"); List<Repos> listData = new ArrayList<>(); listData.add(new Repos("1", "repos test name", "repos test full name")); listData.add(new Repos("2", "repos test name 2", "repos test full name 2")); when(reposRepository.all(param)).thenR...
143681096_3
class CEKRequestSignatureVerifier implements CEKRequestVerifier { @Override public void verify(HttpServletRequest request, CEKRequestMessage requestMessage, String requestJson, SystemContext system) { String baseEncoded64Signature = request.getHeader(CLOVA_SIGNATURE_REQUEST_HEADE...
doCallRealMethod().when(advice).handle(captor.capture()); String body = CEKRequestGenerator.requestBodyBuilder("data/signature_test_request.json", objectMapper) .customize(bindIntentRequest()) ...
143691055_0
class MaxTemperatureDriver extends Configured implements Tool { public int run(String[] args) throws Exception { if (args.length != 2) { System.err.printf("Usage: %s [generic options] <input> <output>\n", getClass().getSimpleName()); ToolRunner.printGenericCommandUsage(System.err); ...
Configuration conf = new Configuration(); //根据编辑好的xml配置文件创建Configuration实例 conf.set("fs.defaultFS", "file:///"); //设置文件系统为本地文件系统 conf.set("mapreduce.framework.name", "local"); //设置为使用本地作业运行器 conf.setInt("mapreduce.task.io.sort.mb", 1); //设置mapreduce中间输出使用环形缓冲区缓存在本地内存的大小,默认为100M ...
143692325_7
class CustomerService { public void savePreferredNotificationChannels(Customer customer, List<NotificationType> notificationChannels) { customer.setPreferredNotificationChannels(notificationChannels); customerRepository.save(customer); } public CustomerService(CustomerRepository customerR...
NotificationType channelOne = NotificationType.EMAIL; NotificationType channelTwo = NotificationType.FAX; CustomerRepository customerRepository = Mockito.mock(CustomerRepository.class); CustomerService customerService = new CustomerService(customerRepository); List<NotificationTy...
143705035_67
class ServerFactory { public static Server create(String serverType) throws EtiqetException { Server instance; try { instance = (Server) Class.forName(serverType).newInstance(); } catch (Exception e) { LOG.error(ERROR_CREATING_SERVER + serverType, e); thr...
String serverClassName = "com.neueda.etiqet.core.testing.FakeTestServer"; String configFile = "etiqet-core/src/test/resources/properties/testDefaultServer.properties"; String extraConfig = "src/test/resources/properties/test.properties"; try { Server server = ServerFactory.cr...
143836525_16
class AuthenticationService implements IAuthenticationService { public ConfigAttribute findConfigAttributesByUrl(HttpServletRequest authRequest) { return this.resourceConfigAttributes.keySet().stream() .filter(requestMatcher -> requestMatcher.matches(authRequest)) .map(reque...
AuthenticationService authenticationService = new AuthenticationService(this.resourceConfigAttributes); ConfigAttribute attributesByUrl = authenticationService .findConfigAttributesByUrl(new HttpServletRequestAuthWrapper(new MockHttpServletRequest(), "/users/1/order", "POST")); A...
143847547_7
class UiInstanceService { public UiResponse findByInstanceId(HttpServletRequest request, String instanceId) { Map<String, AppEntity> appMap=appService.getCacheData(); UiResponse uiResponse = new UiResponse(); Long count; List<CombinedInstanceDto> instanceList; count = uiInst...
RegisterInstanceRequest registerInstanceRequest = RegisterInstanceUtil.setRegisterInstanceRequest(); RegisterInstanceResponse response = instanceService.registerInstance(registerInstanceRequest); Thread.sleep(2 * 1000); InstanceEntity testInstanceEntity = RegisterInstanceUtil.createTestI...
143854187_2
class RpcValue implements RpcItem { @Override public BigInteger asInteger() { if (!(value.startsWith(HEX_PREFIX) || value.startsWith('-' + HEX_PREFIX))) { throw new RpcValueException("The value is not hex string."); } try { String sign = ""; if (valu...
assertThrows(RpcValueException.class, plainStringValue::asInteger); assertEquals(new BigInteger("0102030405", 16), bytesValue.asInteger()); assertEquals(new BigInteger("1234"), oddIntegerValue.asInteger()); assertEquals(new BigInteger("61731"), evenIntegerValue.asInteger()); asse...
143965831_7
class VoiceCallEngine { public void useSpeaker() { mRtcEngine.setEnableSpeakerphone(true); } private VoiceCallEngine(); public static VoiceCallEngine getInstance(); public RtcEngine getmRtcEngine(); public void joinChannel(String channelID, EventHandler handler); public void leav...
VoiceCallEngine.getInstance().useSpeaker(); verify(VoiceCallEngine.getInstance().getmRtcEngine(), times(1)).setEnableSpeakerphone(true); } }
144020195_62
class StreamingIngestClient implements IngestClient { @Override public IngestionResult ingestFromStream(StreamSourceInfo streamSourceInfo, IngestionProperties ingestionProperties) throws IngestionClientException, IngestionServiceException { Ensure.argIsNotNull(streamSourceInfo, "streamSourceInfo"); ...
InputStream inputStream = new ByteArrayInputStream(new byte[10]); StreamSourceInfo streamSourceInfo = new StreamSourceInfo(inputStream); ingestionProperties.setDataFormat(IngestionProperties.DATA_FORMAT.avro); ingestionProperties.setIngestionMapping("CsvMapping", IngestionMapping.Ingesti...
144143524_29
class MutableKeySet extends AbstractKeySet<K> { @Override public Iterator<K> iterator() { return new Iterator<>() { private final AbstractIterator<K, ?> itr = map().iterator(); @Override public boolean hasNext() { return itr.hasNext(); } ...
final Iterator<String> it = set.iterator(); assertTrue(it.hasNext()); assertEquals(KEY, it.next()); assertFalse(it.hasNext()); } }
144361208_1
class BeanNameAspect { public int getCalled() { return called; } @Around("mypointcuts.MyPointcuts.beanNamePointcut()") public void trace(ProceedingJoinPoint proceedingJP); public void resetCalled(); @Autowired BeanNameAspect beanNameAspect; @Autowired SimpleService simpleService; @Autowired SimpleRepository...
assertThat(beanNameAspect.getCalled(), is(0)); simpleRepository.doSomething(); assertThat(beanNameAspect.getCalled(), is(0)); } }
144435698_5
class OrganizationEntity extends EventSourced implements Organization { @Override public Completes<OrganizationState> renameTo(final String name) { return apply(new OrganizationRenamed(state.organizationId, name), () -> state); } public OrganizationEntity(final Id organizationId); public OrganizationE...
final OrganizationState state = Organization.sourcedWith(grid, DefaultName, DefaultDescription) .andThenTo(s -> grid.actorOf(Organization.class, address(s.id()))) .andThenTo(organization -> organization.renameTo(DefaultName + 1)) .await(); Assert.assertEqua...
144561165_1
class UserController { @RequestMapping("/save") public boolean save() { boolean result = false; User user = new User(); user.setName("Adam"); user.setAge(19); user.setCtime(new Date().getTime()); user.setPwd("123456"); userRepository.save(user); r...
User user = new User(); user.setName("Adam"); user.setAge(19); user.setPwd("123456"); userRepository.save(user); System.out.println("userId:" + user.getId()); Assert.assertTrue(user.getId()>0); } }
144737388_0
class Main extends AllDirectives { public Flow<String, String, NotUsed> addIndexFlow() { final Pair<Integer, String> seed = Pair.create(0, "start"); return Flow.of(String.class) .scan(seed, (acc, message) -> { Integer index = acc.first(); ...
final Main example = new Main(new Helper()); List<String> messages = Arrays.asList( "I say high, you say low", "You say why and I say I don't know", "Oh, no", "You say goodbye and I say hello" ); final Flow<String, String,...
144749542_0
class SNMUtils { static String getMacAddr(String mac) { log.warn("searching mac in string '{}'", mac); if (mac == null) { return ""; } Pattern p = Pattern.compile("(?:[0-9a-fA-F]:?){12}"); Matcher m = p.matcher(mac); if (m.find()) { return m...
assertEquals("11:22:33:aa:bb:cc", SNMUtils.getMacAddr("xxx (192.168.178.1) at 11:22:33:aa:bb:cc [ether] on eth0")); assertEquals("11:22:33:aa:bb:cc", SNMUtils.getMacAddr("xxx (192.168.178.1) at 11:22:33:aa:bb:cc [ether] on eth0 aa:bb:cc:11:22:33")); assertEquals("", SNMUtils.getMacAddr("xxx (192...