src_fm_fc_ms_ff stringlengths 43 86.8k | target stringlengths 20 276k |
|---|---|
SignedHeaderAuth implements HttpRequestFilter { @VisibleForTesting String canonicalPath(String path) { path = path.replaceAll("\\/+", "/"); return path.endsWith("/") && path.length() > 1 ? path.substring(0, path.length() - 1) : path; } @Inject SignedHeaderAuth(SignatureWire signatureWire, @org.jclouds.location.Provide... | @Test void canonicalizedPathRemovesMultipleSlashes() { assertEquals(signing_obj.canonicalPath(" }
@Test void canonicalizedPathRemovesTrailingSlash() { assertEquals(signing_obj.canonicalPath("/path/"), "/path"); } |
SignedHeaderAuth implements HttpRequestFilter { public HttpRequest filter(HttpRequest input) throws HttpException { HttpRequest request = input.toBuilder().endpoint(input.getEndpoint().toString().replace("%3F", "?")).build(); String contentHash = hashBody(request.getPayload()); Multimap<String, String> headers = ArrayL... | @Test void shouldGenerateTheCorrectStringToSignAndSignatureWithNoBody() { HttpRequest request = HttpRequest.builder().method(HttpMethod.DELETE).endpoint("http: .build(); request = signing_obj.filter(request); Multimap<String, String> headersWithoutContentLength = LinkedHashMultimap.create(request.getHeaders()); assertE... |
BindGroupToUpdateRequestJsonPayload extends BindToJsonPayload { @Override public <R extends HttpRequest> R bindToRequest(R request, Object payload) { checkArgument(checkNotNull(payload, "payload") instanceof Group, "this binder is only valid for Group objects"); GroupUpdateRequest updateGroup = new GroupUpdateRequest((... | @Test(expectedExceptions = NullPointerException.class) public void testInvalidNullInput() { HttpRequest request = HttpRequest.builder().method("POST").endpoint(URI.create("http: binder.bindToRequest(request, null); }
@Test(expectedExceptions = IllegalArgumentException.class) public void testInvalidTypeInput() { HttpReq... |
BindGroupNameToJsonPayload extends BindToStringPayload { @Override public <R extends HttpRequest> R bindToRequest(R request, Object payload) { super.bindToRequest(request, String.format("{\"groupname\":\"%s\"}", checkNotNull(payload, "payload"))); request.getPayload().getContentMetadata().setContentType(MediaType.APPLI... | @Test(expectedExceptions = NullPointerException.class) public void testInvalidNullInput() { BindGroupNameToJsonPayload binder = new BindGroupNameToJsonPayload(); HttpRequest request = HttpRequest.builder().method("POST").endpoint(URI.create("http: binder.bindToRequest(request, null); } |
GroupName implements Function<Object, String> { @Override public String apply(Object from) { return ((Group) checkNotNull(from, "from")).getGroupname(); } @Override String apply(Object from); } | @Test(expectedExceptions = NullPointerException.class) public void testInvalidNullInput() { new GroupName().apply(null); } |
CreateNodeAndPopulateAutomaticAttributesImpl implements CreateNodeAndPopulateAutomaticAttributes { @Override public Node execute(Node node) { logger.trace("creating node %s", node.getName()); node.getAutomatic().putAll(automaticSupplier.get()); chef.createNode(node); logger.debug("created node %s", node.getName()); ret... | @Test public void testWithNoRunlist() { ChefApi chef = createMock(ChefApi.class); Map<String, JsonBall> automatic = ImmutableMap.<String, JsonBall> of(); Node node = new Node("name", ImmutableSet.<String> of(), "_default"); Supplier<Map<String, JsonBall>> automaticSupplier = Suppliers.<Map<String, JsonBall>> ofInstance... |
UpdateAutomaticAttributesOnNodeImpl implements UpdateAutomaticAttributesOnNode { @Override public void execute(String nodeName) { logger.trace("updating node %s", nodeName); Node node = chef.getNode(nodeName); Node mutable = new Node(node.getName(), node.getNormal(), node.getOverride(), node.getDefault(), automaticSupp... | @Test public void test() { ChefApi chef = createMock(ChefApi.class); Map<String, JsonBall> automatic = ImmutableMap.<String, JsonBall> of(); Node node = new Node("name", ImmutableSet.<String> of(), "_default"); Supplier<Map<String, JsonBall>> automaticSupplier = Suppliers.<Map<String, JsonBall>> ofInstance(automatic); ... |
ChefUtils { public static String findRoleInRunList(List<String> runList) { final Pattern pattern = Pattern.compile("^role\\[(.*)\\]$"); String roleToParse = Iterables.find(runList, new Predicate<String>() { @Override public boolean apply(String input) { return pattern.matcher(input).matches(); } }); Matcher matcher = p... | @Test(expectedExceptions = NoSuchElementException.class) public void testFindRoleInRunListThrowsNoSuchElementOnRecipe() { ChefUtils.findRoleInRunList(ImmutableList.of("recipe[java]")); } |
Extension implements FREExtension { @Override public FREContext createContext(String extId) { Logger.log("Create Context"); return LocalNotificationsContext.getInstance(); } @Override FREContext createContext(String extId); @Override void initialize(); @Override void dispose(); } | @Test public void extension_createContext_returnsContext() { PowerMockito.mockStatic(LocalNotificationsContext.class); when(LocalNotificationsContext.getInstance()).thenReturn(context); assertSame(context, getSubject().createContext("anyId")); } |
SoundSettings { public Uri getSoundUri() { String soundName = getSoundName(); if (soundName == null) return null; return NotificationSoundProvider.getSoundUri(soundName); } SoundSettings(Bundle bundle); Uri getSoundUri(); int getSoundDefault(); } | @Test public void settings_getSoundUri_returnsNullIfBundleDoesNotPlaySoundAndDoesNotHaveSoundName() { assertNull(getSubject().getSoundUri()); }
@Test public void settings_getSoundUri_returnsUriIfBundlePlaysSoundAndHasSoundName() { when(bundle.getString(Constants.SOUND_NAME)).thenReturn("sound.mp3"); when(bundle.getBool... |
SoundSettings { public int getSoundDefault() { return shouldPlayDefaultSound()? Notification.DEFAULT_SOUND : 0; } SoundSettings(Bundle bundle); Uri getSoundUri(); int getSoundDefault(); } | @Test public void settings_getSoundDefault_returnsZeroIfBundlePlaysSoundAndDoesNotHaveSoundName() { when(bundle.getBoolean(Constants.PLAY_SOUND)).thenReturn(true); assertEquals(Notification.DEFAULT_SOUND, getSubject().getSoundDefault()); }
@Test public void settings_getSoundDefault_returnsZeroIfBundlePlaysSoundAndHasSo... |
Application extends android.app.Application { @Override public void onCreate() { super.onCreate(); registerActivityLifecycleCallbacks(new LifecycleCallbacks()); } @Override void onCreate(); } | @Test public void application_addsCallbacks_onCreate() { getSubject().onCreate(); verify(getSubject()).registerActivityLifecycleCallbacks(callbacks); } |
LocalNotificationIntentService extends IntentService { @Override public final void onHandleIntent(Intent intent) { boolean backgroundMode = intent.getBooleanExtra(Constants.BACKGROUND_MODE_KEY, false); sendBroadcast(new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)); tryEventDispatch(intent); handleResponse(intent); logSt... | @Test public void intentService_onHandleIntent_doesNotDispatchNotificationWhenUserResponseNotPresent() { try { PowerMockito.whenNew(LocalNotificationEventDispatcher.class) .withArguments("KeyCode", data, "ActionId", null) .thenReturn(dispatcher); } catch(Exception e) { e.printStackTrace(); } when(intent.getStringExtra(... |
LocalNotification implements ISerializable, IDeserializable { public void deserialize(JSONObject jsonObject) { if (jsonObject != null) { code = jsonObject.optString("code", code); tickerText = jsonObject.optString("tickerText", tickerText); title = jsonObject.optString("title", title); body = jsonObject.optString("body... | @Test public void notification_deserialize_deserializesFromJsonObject() { when(jsonObject.optString("code", "")).thenReturn("MyCode"); when(jsonObject.optString("tickerText", "")).thenReturn("Ticker"); when(jsonObject.optString("title", "")).thenReturn("Title"); when(jsonObject.optString("body", "")).thenReturn("Body")... |
LocalNotification implements ISerializable, IDeserializable { public JSONObject serialize() { JSONObject jsonObject = new JSONObject(); try { jsonObject.putOpt("code", code); jsonObject.putOpt("tickerText", tickerText); jsonObject.putOpt("title", title); jsonObject.putOpt("body", body); jsonObject.putOpt("playSound", p... | @Test public void notification_serialize_serializesNotification() { try { assertSame(jsonObject, getSubject("MyCode").serialize()); verify(jsonObject).putOpt("code", "MyCode"); verify(jsonObject).putOpt("tickerText", "Ticker2"); verify(jsonObject).putOpt("title", "Title2"); verify(jsonObject).putOpt("body", "Body2"); v... |
LocalNotification implements ISerializable, IDeserializable { @SuppressWarnings("WeakerAccess") public long getRepeatIntervalMilliseconds() { return new LocalNotificationTimeInterval(repeatInterval) .toMilliseconds(); } LocalNotification(); LocalNotification(String activityClassName); @SuppressWarnings("WeakerAccess")... | @Test public void notification_getRepeatIntervalMilliseconds_returnsTimeInMilliseconds() { LocalNotificationTimeInterval intervalMock = mock(LocalNotificationTimeInterval.class); try { PowerMockito.whenNew(LocalNotificationTimeInterval.class) .withArguments(10) .thenReturn(intervalMock); } catch (Throwable e) { e.print... |
LocalNotification implements ISerializable, IDeserializable { public boolean repeatsRecurrently() { return (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT || isExact) && repeatInterval != 0; } LocalNotification(); LocalNotification(String activityClassName); @SuppressWarnings("WeakerAccess") long getRepeatInterva... | @Test public void notification_repeatsRecurrently_returnsTrueIfHasRepeatInterval_afterKitKat() { Whitebox.setInternalState(Build.VERSION.class, "SDK_INT", Build.VERSION_CODES.KITKAT); getSubject().repeatInterval = 10; getSubject().isExact = false; assertTrue(getSubject().repeatsRecurrently()); }
@Test public void notif... |
LocalNotificationsContext extends FREContext { void dispatchNotificationSelectedEvent() { LocalNotificationCache.getInstance().reset(); dispatchStatusEventAsync(NOTIFICATION_SELECTED, STATUS); } @Override void dispose(); @Override Map<String, FREFunction> getFunctions(); static final public String NOTIFICATION_SELECTE... | @Test public void context_dispatchNotificationSelectedEvent_dispatchesEvent() { getSubject().dispatchNotificationSelectedEvent(); verify(getSubject()).dispatchStatusEventAsync("notificationSelected", "status"); } |
LocalNotificationsContext extends FREContext { static LocalNotificationsContext getInstance() { if (currentContext == null) { currentContext = new LocalNotificationsContext(); } return currentContext; } @Override void dispose(); @Override Map<String, FREFunction> getFunctions(); static final public String NOTIFICATION... | @Test public void context_functions_getSelectedNotificationData() { byte[] data = {}; PowerMockito.mockStatic(LocalNotificationCache.class); PowerMockito.mockStatic(ExtensionUtils.class); when(LocalNotificationCache.getInstance()).thenReturn(cache); when(cache.getNotificationData()).thenReturn(data); when(ExtensionUtil... |
LocalNotificationsContext extends FREContext { private void cancel(String notificationCode) { getPersistenceManager().removeNotification(notificationCode); getManager().cancel(notificationCode); } @Override void dispose(); @Override Map<String, FREFunction> getFunctions(); static final public String NOTIFICATION_SELEC... | @Test public void context_functions_cancel() { try { when(arg1.getAsString()).thenReturn("MyID"); } catch (Throwable e) { e.printStackTrace(); } callFunction("cancel"); verify(manager).cancel("MyID"); verify(persistenceManager).removeNotification("MyID"); } |
LocalNotificationsContext extends FREContext { private void cancelAll() { getManager().cancelAll(); getPersistenceManager().clearNotifications(); } @Override void dispose(); @Override Map<String, FREFunction> getFunctions(); static final public String NOTIFICATION_SELECTED; static final public String SETTINGS_SUBSCRIB... | @Test public void context_functions_cancelAll() { callFunction("cancelAll"); verify(manager).cancelAll(); verify(persistenceManager).clearNotifications(); } |
LocalNotificationsContext extends FREContext { private void setInForeground(boolean status) { if (isLegacyBehavior()) { ApplicationStatus.setInForeground(status); } } @Override void dispose(); @Override Map<String, FREFunction> getFunctions(); static final public String NOTIFICATION_SELECTED; static final public Strin... | @Test public void context_functions_activate_legacy() { when(activity.getApplication()).thenReturn(legacyApplication); ApplicationStatus.setInForeground(false); callFunction("activate"); assertTrue(ApplicationStatus.getInForeground()); }
@Test public void context_functions_deactivate_legacy() { when(activity.getApplica... |
LocalNotificationEventDispatcher { boolean dispatchWhenInForeground() { return dispatchWhen(ApplicationStatus.getInForeground()); } LocalNotificationEventDispatcher(String code, byte[] data); LocalNotificationEventDispatcher(String code, byte[] data, String actionId, String userResponse); } | @Test public void dispatcher_dispatchInForeground_setsCacheIfAppIsNotActive() { getSubject().dispatchWhenInForeground(); assertCache(); }
@Test public void dispatcher_dispatchInForeground_doesNotDispatchesIfAppIsNotActive() { getSubject().dispatchWhenInForeground(); verify(context, never()).dispatchNotificationSelected... |
LocalNotificationTimeInterval { public long toMilliseconds() { return mapIntervalToMilliseconds(this.intervalId); } LocalNotificationTimeInterval(int intervalId); long toMilliseconds(); long toMilliseconds(int units); final static int YEAR_CALENDAR_UNIT; final static int MONTH_CALENDAR_UNIT; final static int DAY_CALEND... | @Test public void notificationTimeInterval_yearInterval_toMilliseconds() { assertEquals( (long)1000 * 60 * 60 * 24 * 365, getSubject(LocalNotificationTimeInterval.YEAR_CALENDAR_UNIT).toMilliseconds() ); }
@Test public void notificationTimeInterval_monthInterval_toMilliseconds() { assertEquals( (long)1000 * 60 * 60 * 24... |
AlarmRestoreOnBoot extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { if(intent.getAction() == null || !intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)) { return; } PersistenceManager persistenceManager = new PersistenceManager(context); final Set<String> notificationI... | @Test public void provider_onReceive_doesNothing_ifNotRightPermission() { when(intent.getAction()).thenReturn("any.other.permission"); getSubject().onReceive(context, intent); verify(persistenceManager, never()).readNotificationKeys(); }
@Test public void provider_onReceive_notifiesEventsInTheFuture() { initNotificatio... |
TextInputActionIntentService extends BroadcastReceiver { @SuppressWarnings("ConstantConditions") @Override public void onReceive(Context context, Intent intent) { String code = intent.getStringExtra(Constants.NOTIFICATION_CODE_KEY); PersistenceManager persistenceManager = new PersistenceManager(context); LocalNotificat... | @Test public void service_onReceive_startsService() { getSubject().onReceive(context, intent); verify(notificationIntent).setClass(context, LocalNotificationIntentService.class); verify(context).startService(notificationIntent); }
@Test public void service_onReceive_tonesDownNotificationService() { getSubject().onRecei... |
LifecycleCallbacks implements Application.ActivityLifecycleCallbacks { @Override public void onActivityStarted(Activity activity) { ApplicationStatus.setInForeground(true); } @Override void onActivityCreated(Activity activity, Bundle bundle); @Override void onActivityStarted(Activity activity); @Override void onActivi... | @Test public void callbacks_setAppInForeground_whenActivityStarted() { ApplicationStatus.setInForeground(false); getSubject().onActivityStarted(null); assertTrue(ApplicationStatus.getInForeground()); } |
LifecycleCallbacks implements Application.ActivityLifecycleCallbacks { @Override public void onActivityStopped(Activity activity) { ApplicationStatus.setInForeground(false); } @Override void onActivityCreated(Activity activity, Bundle bundle); @Override void onActivityStarted(Activity activity); @Override void onActiv... | @Test public void callbacks_setAppInForeground_whenActivityStopped() { ApplicationStatus.setInForeground(true); getSubject().onActivityStopped(null); assertFalse(ApplicationStatus.getInForeground()); } |
LifecycleCallbacks implements Application.ActivityLifecycleCallbacks { @Override public void onActivityCreated(Activity activity, Bundle bundle) { if (getBackgroundMode(activity)) { activity.moveTaskToBack(true); } } @Override void onActivityCreated(Activity activity, Bundle bundle); @Override void onActivityStarted(A... | @Test public void callbacks_doesNothing_whenNullIntent() { when(activity.getIntent()).thenReturn(null); getSubject().onActivityCreated(activity, null); verify(activity, never()).moveTaskToBack(true); }
@Test public void callbacks_doesNothing_whenNotInBackgroundMode() { when(activity.getIntent()).thenReturn(intent); whe... |
LocalNotificationManager { void notify(LocalNotification notification) { NextNotificationCalculator calculator = new NextNotificationCalculator(notification); long notificationTime = calculator.getTime(new Date()); PendingIntent pendingIntent = PendingIntent.getBroadcast( context, notification.code.hashCode(), intentFa... | @Test public void manager_notify_notifiesOnce_whenIntervalIsZero() { setupIntervalCalculator(); when(PendingIntent.getBroadcast(context, "MyCode".hashCode(), intent, PendingIntent.FLAG_CANCEL_CURRENT)) .thenReturn(pendingIntent); when(calculator.getTime(any(Date.class))).thenReturn(100L); notification.repeatInterval = ... |
LocalNotificationManager { void cancel(String notificationCode) { final Intent intent = new Intent(context, AlarmIntentService.class); intent.setAction(notificationCode); final PendingIntent pi = PendingIntent.getBroadcast(context, notificationCode.hashCode(), intent, PendingIntent.FLAG_CANCEL_CURRENT); final AlarmMana... | @Test public void manager_cancel_cancelsAllStoredAlarms() { when(PendingIntent.getBroadcast(context, "notif1".hashCode(), intent, PendingIntent.FLAG_CANCEL_CURRENT)) .thenReturn(pendingIntent); getSubject().cancel("notif1"); verify(intent).setAction("notif1"); verify(alarmManager).cancel(pendingIntent); } |
NotificationDispatcher { void dispatch() { dispatchNotification(); } NotificationDispatcher(Context context, Bundle bundle); } | @Test public void dispatcher_dispatch_whenAppIsInForeground_andNormalNotification_doesNotDisplayNotification() { getSubject().dispatch(); verify(notificationManager).notify("testCode", Constants.STANDARD_NOTIFICATION_ID, notification); } |
AlarmIntentService extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { Bundle bundle = intent.getExtras(); assert bundle != null; boolean showInForeground = bundle.getBoolean(Constants.SHOW_IN_FOREGROUND); handleRepeatingNotification(context, bundle); NotificationDispatcher dis... | @Test public void intentService_onReceiveWhenAppIsInForeground_andNormalNotification_doesNotDispatchNotification() { when(eventDispatcher.dispatchWhenInForeground()).thenReturn(true); getSubject().onReceive(context, intent); verify(notificationDispatcher, never()).dispatch(); }
@Test public void intentService_onReceive... |
NotificationSoundProvider extends ContentProvider { @Override public void attachInfo(Context context, ProviderInfo info) { super.attachInfo(context, info); AUTHORITY = info.authority; CONTENT_URI = "content: } NotificationSoundProvider(); static Uri getSoundUri(String soundName); @Override int delete(Uri uri, String se... | @Test public void provider_attachInfo_updatesAuthority() { assertEquals("expected.authority", NotificationSoundProvider.AUTHORITY); getSubject().attachInfo(null, info); assertEquals("new.authority", NotificationSoundProvider.AUTHORITY); }
@Test public void provider_attachInfo_updatesUri() { assertEquals("content: getSu... |
NotificationSoundProvider extends ContentProvider { @Override public AssetFileDescriptor openAssetFile(Uri uri, String mode) throws FileNotFoundException { String lastPathSegment = uri.getLastPathSegment(); if (!lastPathSegment.endsWith(".wav") && !lastPathSegment.endsWith(".mp3")) { return null; } return new AssetDeco... | @Test public void provider_openAssetFile_returnsNullIfNotMp3OrWav() { when(uri.getLastPathSegment()).thenReturn("sound.mp3"); try { assertSame(fileDescriptor, getSubject().openAssetFile(uri, "")); } catch (FileNotFoundException e) { e.printStackTrace(); } when(uri.getLastPathSegment()).thenReturn("sound.wav"); try { as... |
WinOrLose { public static int winOrLose(long first, long second) { final long compare = first - second; if (compare > 0) return 1; else if (compare < 0) return 0; return random.nextBoolean() ? 1 : 0; } static void main(String[] args); static int winOrLose(long first, long second); } | @Test public void testWinOrLose() { Map<Integer, Long[]> mapIO = new HashMap<Integer, Long[]>() {{ put(0, new Long[]{new Long("2"), new Long("3")}); put(1, new Long[]{new Long("5"), new Long("3")}); }}; for (Map.Entry<Integer, Long[]> io : mapIO.entrySet()) { Assert.assertEquals( io.getKey().intValue(), WinOrLose.winOr... |
HelloBean { @Deprecated public String sayHello() { return "Hello world!"; } HelloBean(); @Override String toString(); @Deprecated String sayHello(); @SuppressWarnings("all") long getValue(); } | @Test public void testHello() { String ret = helloBean.sayHello(); Assertions.assertNotNull(ret); System.out.println(ret); } |
HelloBean { @Override public String toString() { return "HelloBean says hello world!"; } HelloBean(); @Override String toString(); @Deprecated String sayHello(); @SuppressWarnings("all") long getValue(); } | @Test public void testValue() { String ret = helloBean.osName; Assertions.assertNotNull(ret); System.out.println(String.format("osName:%s, resource: %s", helloBean.osName, helloBean.url.toString() )); } |
HelloController { @ResponseStatus(HttpStatus.ACCEPTED) @AccessLimited(count = 1) @RequestMapping(path="hello/{name}", method = {RequestMethod.GET, RequestMethod.POST}) public Object hello(@RequestAttribute String ip, @PathVariable String name, @RequestParam String gender) { return new HashMap<String, Object>() {{ put("... | @Test public void testHello() { Object ret = helloController.hello("test", null, null); Assertions.assertTrue(ret.toString().contains("test")); System.out.println(ret); } |
ServerConfig { public String getServerUrl() { String strPort = port > 0 && port != 80 ? String.format(":%d", port) : ""; return String.format("http: } void setDomain(String domain); void setPort(long port); String getServerUrl(); boolean isSkipInit(); void setSkipInit(boolean skipInit); boolean isTesting(); void setTe... | @Test public void testServerUrl() { String ret = serverConfig.getServerUrl(); Assertions.assertTrue(ret.contains("http: System.out.println(ret); } |
MqService { public void sendQueue(Object msgObj) { System.out.printf("Send queue msg: %s\n", msgObj); try { jmsMessagingTemplate.convertAndSend(queue, msgObj); } catch (MessagingException e) { System.out.println(e.getMessage()); throw e; } } void sendQueue(Object msgObj); void sendTopic(Object msgObj); } | @Test public void testSendQueue() { for (Object obj : msgArr) { mqService.sendQueue(obj); } } |
MqService { public void sendTopic(Object msgObj) { System.out.printf("Send topic msg: %s\n", msgObj); try { jmsMessagingTemplate.convertAndSend(topic, msgObj); } catch (MessagingException e) { System.out.println(e.getMessage()); throw e; } } void sendQueue(Object msgObj); void sendTopic(Object msgObj); } | @Test public void testSendTopic() { for (Object obj : msgArr) { mqService.sendTopic(obj); } } |
App { public static void main(String[] args) { final JFrame frame = new Frame(); frame.setTitle("Hello App"); frame.setSize(300, 300); frame.setLocationRelativeTo(null); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); frame.setResizable(false); frame.setVisible(true); } static void main(String[] args); ... | @Test public void testApp() { App.main(null); } |
Inst3 { public static Inst3 getInst() { synchronized (Inst3.class) { if (inst == null) { inst = new Inst3(); } } return inst; } private Inst3(); static Inst3 getInst(); } | @Test public void testGetInst() { Inst3 inst = Inst3.getInst(); System.out.printf("%s, %s\n", inst.getClass().getSimpleName(), inst); } |
Inst2 { public static Inst2 getInst() { if (inst == null) { inst = new Inst2(); } return inst; } private Inst2(); static Inst2 getInst(); } | @Test public void testGetInst() { Inst2 inst = Inst2.getInst(); System.out.printf("%s, %s\n", inst.getClass().getSimpleName(), inst); } |
Inst4 { public static Inst4 getInst() { if (inst == null) { synchronized (Inst4.class) { if (inst == null) { inst = new Inst4(); } } } return inst; } private Inst4(); static Inst4 getInst(); } | @Test public void testGetInst() { Inst4 inst = Inst4.getInst(); System.out.printf("%s, %s\n", inst.getClass().getSimpleName(), inst); } |
MinDifference { public static int getMinDifference(int[] arA, int n, int[] arB, int m) { if (n <= 0 || n > m || n != arA.length || m != arB.length) { return 0; } int minDiff = Integer.MAX_VALUE; for (int j = n - 1; j < m; j++) { int diff = 0; for (int i = 0; i < n; i++) { int tmp = arA[i] - arB[j - n + 1 + i]; diff += ... | @Test public void testGetMinDifference() { int n = 2, m = 4; int[] arA = {1, 2}, arB = {3, 1, 2, 4}; Assert.assertEquals(0, MinDifference.getMinDifference(arA, n, arB, m)); }
@Test public void testGetMinDifference2() { int n = 2, m = 4; int[] arA = {1, 2}, arB = {1, 4, 2, 3}; Assert.assertEquals(2, MinDifference.getMin... |
Inst5 { public static Inst5 getInst() { return Holder.inst; } private Inst5(); static Inst5 getInst(); } | @Test public void testGetInst() { Inst5 inst = Inst5.getInst(); System.out.printf("%s, %s\n", inst.getClass().getSimpleName(), inst); } |
Inst1 { public static Inst1 getInst() { return inst; } private Inst1(); static Inst1 getInst(); } | @Test public void testGetInst() { Inst1 inst = Inst1.getInst(); System.out.printf("%s, %s\n", inst.getClass().getSimpleName(), inst); } |
FtpUtil { public static boolean upload(String pathname, String fileName, InputStream inputStream) { System.out.printf("Start upload: %s\n", fileName); FTPClient ftpClient = getInst(); ftpClient.enterLocalPassiveMode(); try { ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE); ftpClient.makeDirectory(pathname); ftpClient... | @Test public void testUpload() throws IOException { String filePath = "readme.md"; InputStream fileStream = new FileInputStream(new File(filePath)); boolean ret = FtpUtil.upload("unit-testing", String.format("%d_%s", new Date().getHours(), filePath), fileStream); fileStream.close(); FtpUtil.close(); Assert.assertTrue(r... |
HttpService { public <T> T sendHttpGet(String url, ResponseHandler<T> handler) { return sendRequest(new HttpGet(url), handler); } T sendRequest(HttpRequestBase httpRequest, ResponseHandler<T> handler); T sendHttpGet(String url, ResponseHandler<T> handler); T sendHttpForm(String httpUrl, Map<String, String> headers, Ma... | @Test public void testSendHttpGet() { String html = httpService.sendHttpGet("https: String ret = html.substring(100, 130); System.out.println(ret); Assertions.assertNotNull(ret); } |
HttpService { public <T> T sendHttpForm(String httpUrl, Map<String, String> headers, Map<String, Object> params, ResponseHandler<T> handler) { HttpPost httpPost = new HttpPost(httpUrl); fillHeaders(httpPost, headers); if (params != null) { List<NameValuePair> pairs = new ArrayList<NameValuePair>(params.size()); for (Ma... | @Test public void testBaiduToken() throws UnsupportedEncodingException { String url = "https: Map<String, String> headers = new HashMap<String, String>() {{ put("Content-Type", "application/x-www-form-urlencoded"); }}; Map<String, Object> params = new HashMap<String, Object>() {{ put("grant_type", "client_credentials")... |
AiController { @ApiOperation("语音合成") @GetMapping("/tts") public Object tts(HttpServletResponse response, @RequestParam("text") String text) { String url = "https: Map<String, String> headers = new HashMap<String, String>() {{ put("Content-Type", "application/x-www-form-urlencoded"); }}; Map<String, Object> params = new... | @Test public void testTts() throws IOException { MockHttpServletResponse response = new MockHttpServletResponse(); Object ret = aiController.tts(response, "测试AiController"); System.out.println(ret); Assertions.assertEquals("ok", ret); } |
FileController { @ApiOperation("上传文件") @PostMapping("/upload") public Object upload(@RequestPart MultipartFile file) { File tmpFile = new File(file.getOriginalFilename()); String fileName = tmpFile.getName(); Path path = Paths.get(fileName); try { Files.write(path, file.getBytes()); } catch (IOException e) { System.out... | @Test public void testUpload() throws IOException { File file = File.createTempFile("tmp", ".txt"); MockMultipartFile multipartFile = new MockMultipartFile( file.getName(), file.getName(), null, new FileInputStream(file) ); Object ret = fileController.upload(multipartFile); System.out.println(ret); String name = (Strin... |
DateUtil { public static String getYYMMDD() { Date d = new Date(); SimpleDateFormat sdf = new SimpleDateFormat("yy-MM-dd"); return sdf.format(d); } static String getYYMMDD(); static String getYYMMDDHHmmSS(); static String getHHmmSS(); static String getStringDate(String rule, Date date); static Date getStartOfToday(); ... | @Test public void testGetYYMMDD() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { Map<String, String> io = new HashMap<String, String>() {{ put("yy-MM-dd", "getYYMMDD"); put("yy-MM-dd:HH:mm:ss", "getYYMMDDHHmmSS"); put("HH:mm:ss", "getHHmmSS"); }}; for (Map.Entry<String, String> entry ... |
DateUtil { public static String getStringDate(String rule, Date date) { SimpleDateFormat sdf = new SimpleDateFormat(rule); return sdf.format(date); } static String getYYMMDD(); static String getYYMMDDHHmmSS(); static String getHHmmSS(); static String getStringDate(String rule, Date date); static Date getStartOfToday()... | @Test public void testGetStringDate() { Date date = mock(Date.class); String[] io = {"yyyy-MM-dd:HH:mm:ss", "yyyy-MM-dd", "HH:mm:ss"}; for (String i : io) { String format = i; SimpleDateFormat sdf = new SimpleDateFormat(format); String expected = sdf.format(date); Assert.assertEquals(expected, DateUtil.getStringDate(fo... |
App { public static void main(String[] args) { Clerk clerk = new Clerk(); executorService.execute(new Producer(clerk)); executorService.execute(new Consumer(clerk)); } static void main(String[] args); } | @Test public void testApp() { new App().main(null); } |
App { public static void main(String[] args) { final JFrame frame = new JFrame("Audio"); frame.setSize(300, 300); frame.setLocationRelativeTo(null); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); frame.setResizable(false); JPanel panel = new JPanel(); Box verticalBox = Box.createVerticalBox(); panel.add... | @Test public void testApp() { App.main(null); } |
Player implements Runnable { public static void asyncPlay(byte[] audioBytes) { if (audioBytes == null || audioBytes.length <= 0) { return; } ByteArrayInputStream audioStream = new ByteArrayInputStream(audioBytes); Player player = new Player(); try { player.audioStream = AudioSystem.getAudioInputStream(audioStream); } c... | @Test public void testPlayUrl() throws Exception { URL fileUrl = new URL("http: Player.asyncPlay(fileUrl); Thread.sleep(3000); } |
RecordHelper { public void record(TimeListener timeListener, Long msDuration) { byteOutputStream = new ByteArrayOutputStream(); Recorder.record(byteOutputStream, timeListener, msDuration); } private RecordHelper(); static RecordHelper getInst(); void record(TimeListener timeListener, Long msDuration); void stop(); voi... | @Test public void testRecord() throws Exception { RecordHelper recordHelper = RecordHelper.getInst(); recordHelper.record(null, null); recordHelper.stop(5000); ByteArrayOutputStream ret = recordHelper.save(new ByteArrayOutputStream()); System.out.printf("data: %d\n", ret == null ? 0 : ret.size()); recordHelper.play(); ... |
SplitNumbers { public static boolean splitStr(String str, int index, List<BigInteger> numbers) { if (index >= str.length()) { return numbers.size() >= 2; } if (index < 0 || str.charAt(index) == '0') { return false; } BigInteger offset = new BigInteger("-1"); for (int i = index; i < str.length(); i++) { if (numbers.size... | @Test public void testSplitNumbers() { Map<String, String> ioMap = new HashMap<String, String>() {{ put("101112", "YES 10"); put("1234", "YES 1"); put("91011", "YES 9"); put("99100", "YES 99"); put("101103", "NO"); put("010203", "NO"); put("13", "NO"); put("1", "NO"); put("11111111111111111111111111111111", "NO"); }}; ... |
DayOfProgrammer { public static String solve(int year) { int month = 0; int day = DAY_OF_PROGRAMMER; for (; month < 12; month++) { int days = DAYS_OF_MONTH[month]; if (day > days) { day -= days; } else { break; } } if (year == 1918) { day += 13; if (day > DAYS_OF_MONTH[month]) { day -= DAYS_OF_MONTH[month]; month++; } ... | @Test public void testResolve() { Map<Integer, String> ioMap = new HashMap<Integer, String>() {{ put(2016, "12.09.2016"); }}; for (Map.Entry<Integer, String> io : ioMap.entrySet()) { String r = DayOfProgrammer.solve(io.getKey()); if (!io.getValue().equals(r)) { System.out.println(r); } Assert.assertEquals(io.getValue()... |
StringDecoder { static int[] frequency(String s) { int[] chars = new int[26]; if (s == null || s.length() <= 0) { return chars; } int i = 0; final int count = s.length(); final char SYMBOL = '#'; while (i < count) { char c = s.charAt(i); if (c >= '3' && c <= '9') { addFrequency(chars, c - '1'); i++; } else if (c >= '1'... | @Test public void testFrequency() { String input = "1226#24#"; int[] output = StringDecoder.frequency(input); Assert.assertEquals(1, output[0]); Assert.assertEquals(1, output[1]); } |
SortHotel { static int[] sort_hotels(String keywords, int[] hotel_ids, String[] reviews) { if (keywords == null || keywords.trim().length() <= 0 || hotel_ids == null || hotel_ids.length <= 0 || reviews == null || reviews.length <= 0 || hotel_ids.length != reviews.length) { return null; } final String[] keywordArr = key... | @Test public void testSortHotels() { int[] ret = SortHotel.sort_hotels( "breakfast beach citycenter location metro view staff price", new int[]{1, 2, 1, 1, 2}, new String[]{ "This hotel has a nice view of the citycenter. The location is perfect.", "The breakfast is ok. Regarding location, it is quite far from citycente... |
Triangle { public static int triangle(int a, int b, int c) { if (a <= 0 || b <= 0 || c <= 0) { return 0; } if (a == b && b == c) { return 1; } else if (a + b > c && b + c > a && a + c > b) { return 2; } return 0; } static int triangle(int a, int b, int c); static String[] triangleOrNot(int[] a, int[] b, int[] c); } | @Test public void testTriangle() { Map<int[], Integer> mapIO = new HashMap<int[], Integer>() {{ put(new int[]{3, 3, 3}, 1); put(new int[]{3, 5, 4}, 2); }}; for (Map.Entry<int[], Integer> io : mapIO.entrySet()) { int[] i = io.getKey(); int ret = Triangle.triangle(i[0], i[1], i[2]); Assert.assertEquals(io.getValue().intV... |
Triangle { public static String[] triangleOrNot(int[] a, int[] b, int[] c) { if (a == null || b == null || c == null || a.length != b.length || a.length != c.length) { return null; } final int count = a.length; String[] results = new String[count]; for (int i = 0; i < count; i++) { if (triangle(a[i], b[i], c[i]) > 0) {... | @Test public void testTriangleOrNot() { int[] a = {7, 10, 7}; int[] b = {2, 3, 4}; int[] c = {2, 7, 4}; String[] results = Triangle.triangleOrNot(a, b, c); System.out.println(Arrays.asList(results)); } |
CustomerServiceCapacity { public static int howManyAgentsToAdd(int noOfCurrentAgents, int[][] callsTimes) { if (callsTimes == null || callsTimes.length <= 0) { return 0; } Call[] calls = new Call[callsTimes.length]; for (int i = 0; i < calls.length; i++) { calls[i] = new Call(callsTimes[i][0], callsTimes[i][1]); } Arra... | @Test public void testHowManyAgentsToAdd() { Map<int[][], int[]> mapIO = new HashMap<int[][], int[]>(){{ put(new int[][] {{1481122000, 1481122020}, {1481122000, 1481122040}, {1481122030, 1481122035}}, new int[]{1, 1}); }}; for (Map.Entry<int[][], int[]> io : mapIO.entrySet()) { int ret = CustomerServiceCapacity.howMany... |
Coupon { public static long findValidLogs(List<String> logs) { if (logs == null || logs.size() <= 0) { return -1; } long index = 0; long freeErrors = 0; HashMap<Long, String> map = new HashMap<Long, String>(); for (String log : logs) { index++; if (log == null || log.length() <= 0) { break; } String[] values = log.spli... | @Test public void testFindValidLogs() { Map<String[], Long> mapIO = new HashMap<String[], Long>() {{ put(new String[]{}, -1L); put(new String[]{"o 1"}, 1L); put(new String[]{"?", "o 1"}, -1L); put(new String[]{"I 1", "?", "O 1"}, -1L); put(new String[]{"i 2", "o 1"}, 2L); put(new String[]{"?", "O 1", "?", "O 2"}, -1L);... |
ElectionWinner { public static String electionWinner(String[] votes) { if (votes == null || votes.length <= 0) { return null; } Map<String, Integer> voteCountMap = new HashMap<String, Integer>(); int maxCount = 0; for (String vote : votes) { String tmp = vote.trim(); int count = 1 + (voteCountMap.containsKey(tmp) ? vot... | @Test public void testElectionWinner() { String ret = ElectionWinner.electionWinner(new String[] {"Alex", "Michael", "harry", "Dave", "Michael", "Victor", "Harry", "Alex", "Mary", "Mary"}); Assert.assertEquals("Michael", ret); } |
DeltaEncode { public static int[] delta_encode(final int[] array) { if (array == null || array.length <= 1) { return array; } List<Integer> encode = new ArrayList<Integer>(){{ add(array[0]); }}; for (int i = 1; i < array.length; i++) { int diff = array[i] - array[i - 1]; if (diff < -127 || diff > 127) { encode.add(-128... | @Test public void testDeltaEncode() { Map<int[], int[]> mapIO = new HashMap<int[], int[]>(){{ put(new int[]{25626, 25757, 24367, 24267, 16, 100, 2, 7277}, new int[]{25626, -128, 131, -128, -1390, -100, -128, -24251, 84, -98, -128, 7275}); }}; for (Map.Entry<int[], int[]> io : mapIO.entrySet()) { int[] ret = DeltaEncode... |
ZombieCluster { static int zombieCluster(String[] zombieArr) { if (zombieArr == null || zombieArr.length <= 0) { return 0; } int len = zombieArr.length; boolean[][] zombieMatric = new boolean[len][len]; for (int i = 0; i < len; i++) { int j = 0; for (char c : zombieArr[i].toCharArray()) { zombieMatric[i][j++] = (c == '... | @Test public void testZombieCluster() { Map<String[], Integer> mapIO = new HashMap<String[], Integer>() {{ put(new String[]{"10000", "01000", "00100", "00010", "00001"}, 5); put(new String[]{"1100", "1110", "0110", "0001"}, 2); }}; for (Map.Entry<String[], Integer> io : mapIO.entrySet()) { int ret = ZombieCluster.zombi... |
GetDay { public static String getDay(String day, String month, String year) { if (day == null || day.length() <= 0 || month == null || month.length() <= 0 || year == null || year.length() <= 0) { return ""; } String dateStr = String.format("%s-%s-%s", year, month, day); DateFormat df = new SimpleDateFormat("yyyy-MM-dd"... | @Test public void testGetDay() { Map<String[], String> mapIO = new HashMap<String[], String>() {{ put(new String[]{"05", "08", "2015"}, "WEDNESDAY"); put(new String[]{"04", "06", "2018"}, "MONDAY"); put(new String[]{"06", "06", "2018"}, "WEDNESDAY"); }}; for (Map.Entry<String[], String> io : mapIO.entrySet()) { String[... |
LeaderBoard { public static int[] getRanks(int[] scores, int[] alice) { Player[] players = new Player[scores.length]; for (int i = 0; i < scores.length; i++) { players[i] = new Player(scores[i], 0); } Arrays.sort(players); for (int i = 0; i < scores.length; i++) { if (i == 0) { players[i].setRank(1); } else if (players... | @Test public void testGetRanks() { Map<List<int[]>, int[]> ioMap = new HashMap<List<int[]>, int[]>() {{ put(new ArrayList() {{ add(new int[] {100, 100, 50, 40, 40, 20, 10}); add(new int[] {5, 25, 50, 120}); }}, new int[] {6, 4, 2, 1}); }}; for (Map.Entry<List<int[]>, int[]> io : ioMap.entrySet()) { int[] ranks = Leader... |
WaitingTime { public static long waitingTime(int[] tickets, int p) { if (tickets == null || tickets.length <= 0 || p < 0 || p >= tickets.length) { return -1; } int count = 0; int ticket = tickets[p]; for (int i = 0; i < tickets.length; i++) { int tmp = tickets[i]; if (tmp < ticket) { count += tmp; } else { count += tic... | @Test public void testWaitingTime() { Map<int[], long[]> mapIO = new HashMap<int[], long[]>(){{ put(new int[]{2, 6, 3, 4, 5}, new long[]{2, 12}); put(new int[]{1, 1, 1, 1}, new long[]{0, 1}); put(new int[]{5, 5, 2, 3}, new long[]{3, 11}); }}; for(Map.Entry<int[], long[]> io : mapIO.entrySet()) { long ret = WaitingTime.... |
Hello { public static void main(String[] args) { Map<String, Integer> map = new HashMap<String, Integer>() {{ put("a", 1); put("b", 2); }}; System.out.println(map.toString()); System.out.println(map.keySet().toString()); } static void main(String[] args); } | @Test public void testMain() { Hello.main(null); } |
IP { public static boolean isValid(String ip) { if (ip == null || ip.length() <= 0) { return false; } return ip.trim().matches(new MyRegex().pattern); } static boolean isValid(String ip); } | @Test public void testIsValid() { Map<String, Boolean> mapIO = new HashMap<String, Boolean>() {{ put("000.12.12.034", true); put("121.234.12.12", true); put("23.45.12.56", true); put("000.12.234.23.23", false); put("666.666.23.23", false); put(".213.123.23.32", false); put("23.45.22.32.", false); put("I.Am.not.an.ip", ... |
PermutationEquation { public static int[] permutationEquation(final int[] p) { if (p == null || p.length <= 0) { return null; } Map<Integer, Integer> equationMap = new HashMap<Integer, Integer>(){{ for (int i = 0; i < p.length; i++) { put(p[i], i + 1); } }}; int[] arr = new int[p.length]; for (int i = 0; i < arr.length... | @Test public void testPermutationEquation() { Map<int[], int[]> mapIO = new HashMap<int[], int[]>(){{ put(new int[]{2, 3, 1}, new int[] {2, 3, 1}); }}; for (Map.Entry<int[], int[]> io : mapIO.entrySet()) { int[] ret = PermutationEquation.permutationEquation(io.getKey()); Assert.assertArrayEquals(io.getValue(), ret); } ... |
MaxMin { public static long[] maxMin(String[] operations, int[] values) { if (operations == null || values == null || operations.length > values.length) { return null; } long[] products = new long[operations.length]; int max = Integer.MIN_VALUE; int min = Integer.MAX_VALUE; int[] arr = new int[operations.length]; int i... | @Test public void testMaxMin() { Map<Object[], long[]> pairIO = new HashMap<Object[], long[]>() {{ put(new Object[] {new String[]{"push", "push", "push", "pop"}, new int[]{1, 2, 3, 1}}, new long[]{1, 2, 3, 6}); put(new Object[] {new String[]{"push", "push"}, new int[] {3, 2}}, new long[]{9, 6}); }}; for (Map.Entry<Obje... |
WinOrLose2 { public static int winOrLose(long first, long second) { if (first > second) return 1; else if (first < second) return 0; return random.nextBoolean() ? 1 : 0; } static void main(String[] args); static int calculateLoop(List<Long> ar); static int winOrLose(long first, long second); } | @Test public void testWinOrLose() { Map<Integer, int[]> mapIO = new HashMap<Integer, int[]>() {{ put(0, new int[] {2, 3}); put(1, new int[] {5, 3}); }}; for (Map.Entry<Integer, int[]> io : mapIO.entrySet()) { Assert.assertEquals( io.getKey().intValue(), WinOrLose2.winOrLose(io.getValue()[0], io.getValue()[1]) ); } } |
CutSticks { public static int[] cutSticks(int[] lengths) { if (lengths == null || lengths.length <= 0) { return null; } Arrays.sort(lengths); int index = 0, count = lengths.length; List<Integer> countList = new ArrayList<Integer>(); while (index < count) { countList.add(count - index); if (index == count - 1) { break; ... | @Test public void testCutSticks() { Map<int[], int[]> mapIO = new HashMap<int[], int[]>() {{ put(new int[]{1, 1, 2, 3}, new int[]{4, 2, 1}); put(new int[]{5, 4, 4, 2, 2, 8}, new int[]{6, 4, 2, 1}); }}; for (Map.Entry<int[], int[]> io : mapIO.entrySet()) { int[] ret = CutSticks.cutSticks(io.getKey()); Assert.assertArray... |
BinarySubString { public static int counting(String s) { if (s == null || s.trim().length() <= 1) { return 0; } char[] arr = s.trim().toCharArray(); int len = arr.length; int count = 0; for (int i = 0; i < len - 1; i++) { if (arr[i] != arr[i + 1]) { count++; int m = i - 1; int n = i + 1 + 1; while (m >= 0 && n < len &&... | @Test public void testCounting() { Map<String, Integer> mapIO = new HashMap<String, Integer>(){{ put("10001", 2); put("10101", 4); put("00110", 3); }}; for (Map.Entry<String, Integer> io : mapIO.entrySet()) { int ret = BinarySubString.counting(io.getKey()); Assert.assertEquals(io.getValue().intValue(), ret); } } |
Portfolio { public static long findMax(int n, String tree) { if (n <= 0 || tree == null || tree.trim().length() <= 0) { return 0; } String[] nodes = tree.trim().split(" "); if (nodes.length < n) { return 0; } List<Long> sumList = new ArrayList<Long>(); int countExpected = 1; int count = 0; int index = 0; long sum = 0; ... | @Test public void testFindMax() { Map<String, int[]> mapIO = new HashMap<String, int[]>() {{ put("3 4 5 1 3 # 1", new int[]{6, 9}); put("3 2 3 # 3 # 1", new int[]{5, 7}); }}; for (Map.Entry<String, int[]> io : mapIO.entrySet()) { long ret = Portfolio.findMax(io.getValue()[0], io.getKey()); Assert.assertEquals((long)(io... |
BestTrio { static int bestTrio(int friends_nodes, int[] friends_from, int[] friends_to) { if (friends_nodes < 0 || friends_from == null || friends_to == null || friends_from.length > friends_to.length) { return -1; } List<HashSet<Integer>> friends = new ArrayList<HashSet<Integer>>(friends_nodes); for (int i = 0; i < fr... | @Test public void testBestTrio() { Map<Object[], Integer> mapIO = new HashMap<Object[], Integer>() {{ put(new Object[]{5, new int[]{1, 1, 2, 2, 3, 4}, new int[]{2, 3, 3, 4, 4, 5}}, 2); put(new Object[]{7, new int[]{2, 3, 5, 1}, new int[]{1, 6, 1, 7}}, -1); }}; for (Map.Entry<Object[], Integer> io : mapIO.entrySet()) { ... |
MovieTitles { public static String[] getMovieTitles(String substr) { if (substr == null || substr.trim().length() <= 0) { return null; } int page = 1; final String url = "https: Gson gson = new Gson(); List<String> movies = new ArrayList<String>(); while (true) { String response = null; try { response = httpGet(String.... | @Test public void testMovieTitles() { final String[] ret = MovieTitles.getMovieTitles("spiderman"); System.out.println(Arrays.asList(ret).toString()); Assert.assertArrayEquals(new String[]{ "Amazing Spiderman Syndrome", "Fighting, Flying and Driving: The Stunts of Spiderman 3", "Hollywood's Master Storytellers: Spiderm... |
ReductionCost { public static int reductionCost(int[] numArr) { if (numArr == null || numArr.length <= 0) { return 0; } int cost = 0; for (int i = 0; i < numArr.length - 1; i++) { Arrays.sort(numArr); int sum = numArr[i] + numArr[i + 1]; numArr[i] = 0; numArr[i + 1] = sum; cost += sum; } return cost; } static int redu... | @Test public void testReductionCost() { Map<int[], Integer> mapIO = new HashMap<int[], Integer>() {{ put(new int[] {1, 2, 3}, 9); put(new int[] {1, 2, 3, 4}, 19); }}; for (Map.Entry<int[], Integer> io : mapIO.entrySet()) { int ret = ReductionCost.reductionCost(io.getKey()); Assert.assertEquals(io.getValue().intValue(),... |
Arbitrage { public static int[] arbitrage(String[] quotes) { if (quotes == null || quotes.length <= 0) { return null; } int[] profits = new int[quotes.length]; for (int i = 0; i < quotes.length; i++) { double[] prices = parseQuote(quotes[i]); int profit = 0; if (prices != null) { double dollar = 100000; for (int j = 0;... | @Test public void testArbitrage() { int[] ret = Arbitrage.arbitrage(new String[]{"1.1837 1.3829 0.6102", "1.1234 1.2134 1.2311"}); Assert.assertArrayEquals(new int[]{114, 0}, ret); } |
SubStr { public static String[] splitTokens(String str) { if (str == null || str.trim().length() <= 0) { return null; } String[] strArr = str.trim().split("[ !,?._'@]+"); return strArr; } static String[] splitTokens(String str); static String getSmallestAndLargest(String str, int k); } | @Test public void testSplitTokens() { Map<String, Integer> mapIO = new HashMap<String, Integer>() {{ put("He is a very very good boy, isn't he?", 10); put(" YES leading spaces are valid, problemsetters are evillllll", 8); put("", 0); put(null, 0); }}; for (Map.Entry<String, Integer> io : mapIO.entrySet()) { String[] re... |
SubStr { public static String getSmallestAndLargest(String str, int k) { if (str == null || str.length() < k || k <= 0) { return "\n"; } String smallest = str.substring(0, k); String largest = smallest; for (int i = 1; i < str.length() - k + 1; i++) { String sub = str.substring(i, i + k); if (smallest.compareTo(sub) > ... | @Test public void testGetSmallestAndLargest() { Map<String, String> mapIO = new HashMap<String, String>() {{ put("welcometojava", "ava\nwel"); }}; for (Map.Entry<String, String> io : mapIO.entrySet()) { String ret = SubStr.getSmallestAndLargest(io.getKey(), 3); Assert.assertEquals(io.getValue(), ret); } } |
NumberOfPairs { static int numberOfPairs(int[] a, long k) { if (a == null || a.length <= 1) { return 0; } Arrays.sort(a); Map<Integer, Integer> pairMap = new HashMap<Integer, Integer>(); for (int i = 0; i < a.length; i++) { int m = a[i]; for (int j = a.length - 1; j > i; j--) { int n = a[j]; if (m + n < k) { break; } e... | @Test public void testBraces() { Map<int[], Integer[]> mapIO = new HashMap<int[], Integer[]>() {{ put(new int[] {6, 6, 3, 9, 3, 5, 1}, new Integer[]{12, 2}); }}; for (Map.Entry<int[], Integer[]> io : mapIO.entrySet()) { Integer ret = NumberOfPairs.numberOfPairs(io.getKey(), io.getValue()[0]); Assert.assertEquals(io.get... |
WinOrLose2 { public static int calculateLoop(List<Long> ar) { int n = ar.size(); if (n <= 1 || (n & (n - 1)) != 0) { return 0; } Iterator<Long> iterator = ar.iterator(); long score = iterator.next(); long index = 0; long mark = 1; int loop = 0; while (iterator.hasNext()) { if (winOrLose(score, iterator.next()) == 1) { ... | @Test public void testCalculateLoop() { Map<long[], Integer> mapIO = new HashMap<long[], Integer>() {{ put(new long[] {7, 1, 2, 3, 1, 3, 1, 2, 5, 6, 1, 6, 2, 5}, 0); put(new long[] {4, 1}, 1); put(new long[] {1000000, 1, 2, -1000000}, 2); put(new long[] {4, 1, 2, 3, 1, 3, 1, 2}, 3); put(new long[] {7, 1, 2, 3, 1, 3, 1,... |
Palindrome { static int getScore(String s) { if (s == null || s.trim().length() <= 1) { return 0; } if (s.length() == 2) { return 1; } int score = 0; for (int i = 1; i < s.length(); i++) { String p1 = getMaxPalindrome(s.substring(0, i)); String p2 = getMaxPalindrome(s.substring(i, s.length())); int tmp = (p1 == null ? ... | @Test public void testGetScore() { Map<String, Integer> mapIO = new HashMap<String, Integer>(){{ put("acdapmpomp", 15); put("axbawbaseksqke", 25); put("aa", 1); put("ab", 1); put("abb", 2); put("aab", 2); }}; for (Map.Entry<String, Integer> io : mapIO.entrySet()) { int ret = Palindrome.getScore(io.getKey()); Assert.ass... |
PickNumbers { public static int pickNumbers(int[] ar) { if (ar == null || ar.length <= 0) { return 0; } Arrays.sort(ar); int n = ar.length; int max = Integer.MIN_VALUE; for (int i = 0; i < n; i++) { int count = 0; int diff = 0; for (int j = i - 1; j >= 0; j--) { int tmp = Math.abs(ar[i] - ar[j]); if (tmp <= 1) { count+... | @Test public void testPickNumbers() { Map<int[], Integer> mapIO = new HashMap<int[], Integer>() {{ put(null, 0); put(new int[]{4, 6, 5, 3, 3, 1}, 3); put(new int[]{1, 2, 2, 3, 1, 2}, 5); put(new int[]{ 4, 2, 3, 4, 4, 9, 98, 98, 3, 3, 3, 4, 2, 98, 1, 98, 98, 1, 1, 4, 98, 2, 98, 3, 9, 9, 3, 1, 4, 1, 98, 9, 9, 2, 9, 4, 2,... |
Braces { static String[] braces(String[] values) { if (values == null || values.length <= 0) { return null; } Map<Integer, Integer> braceMap = new HashMap<Integer, Integer>() {{ put((int)')', (int)'('); put((int)']', (int)'['); put((int)'}', (int)'{'); }}; String[] ret = new String[values.length]; for (int i = 0; i < v... | @Test public void testBraces() { Map<String[], String[]> mapIO = new HashMap<String[], String[]>() {{ put(new String[] {"{}[]()", "{[}]}"}, new String[] {"YES", "NO"}); put(new String[] {"}][}}(}][))]"}, new String[] {"NO"}); }}; for (Map.Entry<String[], String[]> io : mapIO.entrySet()) { String[] ret = Braces.braces(i... |
AopInstrumenter implements MethodInterceptor { public Object getInstrumentedClass(Class clz) { enhancer.setSuperclass(clz); enhancer.setCallback(this); return enhancer.create(); } Object getInstrumentedClass(Class clz); Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy); } | @Test public void testGetInstrumentedObject() { AopInstrumenter instrumenter = new AopInstrumenter(); AopService service = (AopService) instrumenter.getInstrumentedClass(AopServiceImpl.class); service.findInfo("Instrumenter from test"); } |
App { public static void main(String[] args) { AopService service = (AopService) AopFactory.getAopProxyedObject(AopServiceImpl.class.getName()); service.findInfo("Jonn from app.main"); AopInstrumenter instrumenter = new AopInstrumenter(); service = (AopService) instrumenter.getInstrumentedClass(AopServiceImpl.class); s... | @Test public void testApp() { App.main(null); } |
AopFactory { public static Object getAopProxyedObject(String clzName) { Object proxy = null; AopHandler handler = new AopHandler(); Object obj = getClassInst(clzName); if (obj != null) { proxy = handler.bind(obj); } else { System.out.println("Can't get the proxyObj"); } return proxy; } static Object getAopProxyedObjec... | @Test public void testGetAopProxyedObject() { AopService service = (AopService) AopFactory.getAopProxyedObject(AopServiceImpl.class.getName()); service.findInfo("Jonn from test"); } |
RedisService { public long incr(String key) { Long ret = strValOps.increment(key, 1L); return ret == null ? 0 : ret; } long incr(String key); boolean expire(String key, long seconds); } | @Test public void testIncr() { String key = "RedisServiceTest.testStr"; long ret = redisService.incr(key); Assertions.assertTrue(ret > 0); System.out.println(ret); redisService.expire(key, 1); } |
HookMetadataParser { SortedSet<HookMetadata> parse() throws IOException, ClassNotFoundException { return parse(className -> true); } HookMetadataParser(Collection<Path> hookJars); SortedSet<HookMetadata> parse(Predicate<String> classNameFilter); } | @Test void testServletHook() throws ClassNotFoundException, IOException { String expected = ServletTestHook.class.getName() + " instruments [javax.servlet.Filter, javax.servlet.Servlet]:\n" + " * doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse)\n" + " * service(javax.servlet.ServletRequest, javax.s... |
JarFiles { static Path findAgentJarFromCmdline(List<String> cmdlineArgs) { Pattern p = Pattern.compile("^-javaagent:(.*promagent([^/]*).jar)(=.*)?$"); for (String arg : cmdlineArgs) { Matcher m = p.matcher(arg); if (m.matches()) { return Paths.get(m.group(1)); } } throw new RuntimeException("Failed to locate promagent.... | @Test void testCmdlineParserWildfly() { String[] cmdlineArgs = new String[]{ "-D[Standalone]", "-Xbootclasspath/p:/tmp/wildfly-10.1.0.Final/modules/system/layers/base/org/jboss/logmanager/main/jboss-logmanager-2.0.4.Final.jar", "-Djboss.modules.system.pkgs=org.jboss.logmanager,io.promagent.agent", "-Djava.util.logging.... |
SyncMetadataService extends BaseService implements IMetadataService { @Override public SalientAttributes getAttributes() throws RemotePeerException, IOException { SalientAttributes originAttributes = new SalientAttributes(); originAttributes.setApplication(context.getApplication()); originAttributes.setVersion(context.... | @Test public void getAttributes() throws Exception { long peerId = 100500L; String hostAddress = "testAddress.com"; String app = "testApp"; String version = "testVersion"; ExecutionContext ctx = mock(ExecutionContext.class); ExecutionContext.Host host = mock(ExecutionContext.Host.class); fork = mock(IFork.class); when(... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.