hexsha stringlengths 40 40 | size int64 8 1.04M | content stringlengths 8 1.04M | avg_line_length float64 2.24 100 | max_line_length int64 4 1k | alphanum_fraction float64 0.25 0.97 |
|---|---|---|---|---|---|
b678bb2fddbd5c1ff9f7c43da7c6bda3a577d89e | 6,041 | package org.highmed.dsf.fhir.dao;
import static org.junit.Assert.assertEquals;
import org.highmed.dsf.fhir.dao.jdbc.MeasureReportDaoJdbc;
import org.hl7.fhir.r4.model.MeasureReport;
import org.hl7.fhir.r4.model.MeasureReport.MeasureReportStatus;
import org.junit.Test;
public class MeasureReportDaoTest extends AbstractResourceDaoTest<MeasureReport, MeasureReportDao>
implements ReadAccessDaoTest<MeasureReport>
{
public MeasureReportDaoTest()
{
super(MeasureReport.class, MeasureReportDaoJdbc::new);
}
@Override
public MeasureReport createResource()
{
MeasureReport measureReport = new MeasureReport();
measureReport.setStatus(MeasureReportStatus.PENDING);
return measureReport;
}
@Override
protected void checkCreated(MeasureReport resource)
{
assertEquals(MeasureReportStatus.PENDING, resource.getStatus());
}
@Override
protected MeasureReport updateResource(MeasureReport resource)
{
resource.setStatus(MeasureReportStatus.COMPLETE);
return resource;
}
@Override
protected void checkUpdates(MeasureReport resource)
{
assertEquals(MeasureReportStatus.COMPLETE, resource.getStatus());
}
@Override
@Test
public void testReadAccessTriggerAll() throws Exception
{
ReadAccessDaoTest.super.testReadAccessTriggerAll();
}
@Override
@Test
public void testReadAccessTriggerLocal() throws Exception
{
ReadAccessDaoTest.super.testReadAccessTriggerLocal();
}
@Override
@Test
public void testReadAccessTriggerOrganization() throws Exception
{
ReadAccessDaoTest.super.testReadAccessTriggerOrganization();
}
@Override
@Test
public void testReadAccessTriggerOrganizationResourceFirst() throws Exception
{
ReadAccessDaoTest.super.testReadAccessTriggerOrganizationResourceFirst();
}
@Override
@Test
public void testReadAccessTriggerOrganization2Organizations1Matching() throws Exception
{
ReadAccessDaoTest.super.testReadAccessTriggerOrganization2Organizations1Matching();
}
@Override
@Test
public void testReadAccessTriggerOrganization2Organizations2Matching() throws Exception
{
ReadAccessDaoTest.super.testReadAccessTriggerOrganization2Organizations2Matching();
}
@Override
@Test
public void testReadAccessTriggerRole() throws Exception
{
ReadAccessDaoTest.super.testReadAccessTriggerRole();
}
@Override
@Test
public void testReadAccessTriggerRoleResourceFirst() throws Exception
{
ReadAccessDaoTest.super.testReadAccessTriggerRoleResourceFirst();
}
@Override
@Test
public void testReadAccessTriggerRole2Organizations1Matching() throws Exception
{
ReadAccessDaoTest.super.testReadAccessTriggerRole2Organizations1Matching();
}
@Override
@Test
public void testReadAccessTriggerRole2Organizations2Matching() throws Exception
{
ReadAccessDaoTest.super.testReadAccessTriggerRole2Organizations2Matching();
}
@Override
@Test
public void testReadAccessTriggerAllUpdate() throws Exception
{
ReadAccessDaoTest.super.testReadAccessTriggerAllUpdate();
}
@Override
@Test
public void testReadAccessTriggerLocalUpdate() throws Exception
{
ReadAccessDaoTest.super.testReadAccessTriggerLocalUpdate();
}
@Override
@Test
public void testReadAccessTriggerOrganizationUpdate() throws Exception
{
ReadAccessDaoTest.super.testReadAccessTriggerOrganizationUpdate();
}
@Override
@Test
public void testReadAccessTriggerRoleUpdate() throws Exception
{
ReadAccessDaoTest.super.testReadAccessTriggerRoleUpdate();
}
@Override
@Test
public void testReadAccessTriggerRoleUpdateMemberOrganizationNonActive() throws Exception
{
ReadAccessDaoTest.super.testReadAccessTriggerRoleUpdateMemberOrganizationNonActive();
}
@Override
@Test
public void testReadAccessTriggerRoleUpdateParentOrganizationNonActive() throws Exception
{
ReadAccessDaoTest.super.testReadAccessTriggerRoleUpdateParentOrganizationNonActive();
}
@Override
@Test
public void testReadAccessTriggerRoleUpdateMemberAndParentOrganizationNonActive() throws Exception
{
ReadAccessDaoTest.super.testReadAccessTriggerRoleUpdateMemberAndParentOrganizationNonActive();
}
@Override
@Test
public void testReadAccessTriggerAllDelete() throws Exception
{
ReadAccessDaoTest.super.testReadAccessTriggerAllDelete();
}
@Override
@Test
public void testReadAccessTriggerLocalDelete() throws Exception
{
ReadAccessDaoTest.super.testReadAccessTriggerLocalDelete();
}
@Override
@Test
public void testReadAccessTriggerOrganizationDelete() throws Exception
{
ReadAccessDaoTest.super.testReadAccessTriggerOrganizationDelete();
}
@Override
@Test
public void testReadAccessTriggerRoleDelete() throws Exception
{
ReadAccessDaoTest.super.testReadAccessTriggerRoleDelete();
}
@Override
@Test
public void testReadAccessTriggerRoleDeleteMember() throws Exception
{
ReadAccessDaoTest.super.testReadAccessTriggerRoleDeleteMember();
}
@Override
@Test
public void testReadAccessTriggerRoleDeleteParent() throws Exception
{
ReadAccessDaoTest.super.testReadAccessTriggerRoleDeleteParent();
}
@Override
@Test
public void testReadAccessTriggerRoleDeleteMemberAndParent() throws Exception
{
ReadAccessDaoTest.super.testReadAccessTriggerRoleDeleteMemberAndParent();
}
@Override
@Test
public void testSearchWithUserFilterAfterReadAccessTriggerAllWithLocalUser() throws Exception
{
ReadAccessDaoTest.super.testSearchWithUserFilterAfterReadAccessTriggerAllWithLocalUser();
}
@Override
@Test
public void testSearchWithUserFilterAfterReadAccessTriggerLocalwithLocalUser() throws Exception
{
ReadAccessDaoTest.super.testSearchWithUserFilterAfterReadAccessTriggerLocalwithLocalUser();
}
@Override
@Test
public void testSearchWithUserFilterAfterReadAccessTriggerAllWithRemoteUser() throws Exception
{
ReadAccessDaoTest.super.testSearchWithUserFilterAfterReadAccessTriggerAllWithRemoteUser();
}
@Override
@Test
public void testSearchWithUserFilterAfterReadAccessTriggerLocalWithRemoteUser() throws Exception
{
ReadAccessDaoTest.super.testSearchWithUserFilterAfterReadAccessTriggerLocalWithRemoteUser();
}
}
| 25.06639 | 99 | 0.829664 |
c3d570489503951502f6cefee74abe7170aa40d8 | 210 | @MethodsReturnNonnullByDefault
@ParametersAreNonnullByDefault
package com.ridanisaurus.emendatusenigmatica.jei;
import mcp.MethodsReturnNonnullByDefault;
import javax.annotation.ParametersAreNonnullByDefault; | 30 | 54 | 0.904762 |
cffd7be9fb0f743e96954a58790fbb456c0ddd5b | 4,066 | /***
Copyright (c) 2016 CommonsWare, LLC
Licensed under the Apache License, Version 2.0 (the "License"); you may not
use this file except in compliance with the License. You may obtain a copy
of the License at http://www.apache.org/licenses/LICENSE-2.0. Unless required
by applicable law or agreed to in writing, software distributed under the
License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS
OF ANY KIND, either express or implied. See the License for the specific
language governing permissions and limitations under the License.
Covered in detail in the book _The Busy Coder's Guide to Android Development_
https://commonsware.com/Android
*/
package com.commonsware.android.pdfium;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import com.github.barteksc.pdfviewer.PDFView;
import com.github.barteksc.pdfviewer.scroll.DefaultScrollHandle;
public class MainActivity extends Activity {
private static final int REQUEST_OPEN=1337;
private static final int REQUEST_GET=REQUEST_OPEN+1;
private static final String STATE_ASSET="asset";
private static final String STATE_PICKED="picked";
private PDFView viewer;
private String chosenAsset=null;
private Uri pickedDocument=null;
@SuppressLint("SetJavaScriptEnabled")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewer=(PDFView)findViewById(R.id.viewer);
if (savedInstanceState!=null) {
chosenAsset=savedInstanceState.getString(STATE_ASSET);
if (chosenAsset==null) {
pickedDocument=savedInstanceState.getParcelable(STATE_PICKED);
if (pickedDocument!=null) {
configureViewer(viewer.fromUri(pickedDocument));
}
}
else {
configureViewer(viewer.fromAsset(chosenAsset));
}
}
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putString(STATE_ASSET, chosenAsset);
outState.putParcelable(STATE_PICKED, pickedDocument);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.pdf, menu);
return(super.onCreateOptionsMenu(menu));
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId()==R.id.preso) {
loadPdf("MultiWindowAndYourApp.pdf");
return(true);
}
else if (item.getItemId()==R.id.taxes) {
loadPdf("f1040a.pdf");
return(true);
}
else if (item.getItemId()==R.id.open) {
open();
}
return(super.onOptionsItemSelected(item));
}
@Override
protected void onActivityResult(int requestCode, int resultCode,
Intent data) {
if (resultCode==Activity.RESULT_OK) {
pickedDocument=data.getData();
chosenAsset=null;
configureViewer(viewer.fromUri(pickedDocument));
}
}
private void loadPdf(String name) {
chosenAsset=name;
pickedDocument=null;
configureViewer(viewer.fromAsset(name));
}
private void configureViewer(PDFView.Configurator configurator) {
configurator
.enableSwipe(true)
.swipeHorizontal(true)
.enableDoubletap(true)
.scrollHandle(new DefaultScrollHandle(this))
.load();
}
private void open() {
if (Build.VERSION.SDK_INT<Build.VERSION_CODES.KITKAT) {
Intent i=
new Intent()
.setType("application/pdf")
.setAction(Intent.ACTION_GET_CONTENT)
.addCategory(Intent.CATEGORY_OPENABLE);
startActivityForResult(i, REQUEST_GET);
}
else {
Intent i=
new Intent()
.setType("application/pdf")
.setAction(Intent.ACTION_OPEN_DOCUMENT)
.addCategory(Intent.CATEGORY_OPENABLE);
startActivityForResult(i, REQUEST_OPEN);
}
}
}
| 29.251799 | 78 | 0.709051 |
f670100e1d7c35204e56e836b5cdb4ab3e7f4b50 | 549 | package com.peregud.shoppingcenter.servlet;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.*;
class DeleteDiscountServletTest extends MockInit {
@Test
void doGet() throws IOException {
when(request.getParameter("id")).thenReturn("1");
assertEquals("1", request.getParameter("id"));
new DeleteDiscountServlet().doGet(request, response);
verify(request, atLeast(1)).getParameter("id");
}
}
| 26.142857 | 61 | 0.717668 |
87175a5a2f2a7233d5a458d9121c52377b821fc2 | 1,507 | /**
* Copyright (C) 2004 - 2012 Shopzilla, Inc.
* All rights reserved. Unauthorized disclosure or distribution is prohibited.
*/
package com.shopzilla.api.client.model.response;
import java.util.ArrayList;
import java.util.List;
import com.shopzilla.api.client.model.Suggestion;
/**
*
* @author Tom Suthanurak
* @author Swati Achar
* @since Jan 3, 2012
*/
public class Classification extends BaseResponse {
private String originalKeyword;
private Long originalNumResults;
private Boolean mature;
private Boolean media;
private List<Suggestion> suggestions;
public Classification() {
}
public String getOriginalKeyword() {
return originalKeyword;
}
public void setOriginalKeyword(String originalKeyword) {
this.originalKeyword = originalKeyword;
}
public Long getOriginalNumResults() {
return originalNumResults;
}
public void setOriginalNumResults(Long originalNumResults) {
this.originalNumResults = originalNumResults;
}
public Boolean getMature() {
return mature;
}
public void setMature(Boolean mature) {
this.mature = mature;
}
public Boolean getMedia() {
return media;
}
public void setMedia(Boolean media) {
this.media = media;
}
public List<Suggestion> getSuggestions() {
if (suggestions == null) {
suggestions = new ArrayList<Suggestion>();
}
return suggestions;
}
} | 22.492537 | 78 | 0.66357 |
1dedb2c342dc01563500a1ec27b7fa1f78e7cbfa | 15,668 | package com.webimageloader.test;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLStreamHandler;
import java.util.Random;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import android.annotation.TargetApi;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.test.AndroidTestCase;
import com.webimageloader.ImageLoader;
import com.webimageloader.ImageLoader.Listener;
import com.webimageloader.Request;
import com.webimageloader.transformation.SimpleTransformation;
@TargetApi(16)
public class ImageLoaderTestCase extends AndroidTestCase {
private static final int TIMEOUT = 1;
private static final int TEN_MEGABYTES = 10 * 1024 * 1024;
private static final String MOCK_SCHEME = "mock://";
private static final String CORRECT_FILE_PATH = "test.png";
private static final String CORRECT_MOCK_FILE_PATH = MOCK_SCHEME + CORRECT_FILE_PATH;
private static final String WRONG_FILE_PATH = MOCK_SCHEME + "error.jpeg";
private static final Request CORRECT_REQUEST = new Request(CORRECT_MOCK_FILE_PATH);
private static final Listener<Object> EMPTY_LISTENER = new Listener<Object>() {
@Override
public void onSuccess(Object tag, Bitmap b) {}
@Override
public void onError(Object tag, Throwable t) {}
};
private ImageLoader loader;
private Bitmap correctFile;
private MockURLStreamHandler streamHandler;
@Override
protected void setUp() throws Exception {
int random = Math.abs(new Random().nextInt());
File cacheDir = new File(getContext().getCacheDir(), String.valueOf(random));
streamHandler = new MockURLStreamHandler(getContext().getAssets());
loader = new ImageLoader.Builder(getContext())
.enableDiskCache(cacheDir, TEN_MEGABYTES)
.enableMemoryCache(TEN_MEGABYTES)
.addURLSchemeHandler("mock", streamHandler)
.build();
correctFile = BitmapFactory.decodeStream(getContext().getAssets().open(CORRECT_FILE_PATH));
}
@Override
protected void tearDown() throws Exception {
loader.destroy();
}
public void testSameThread() throws IOException {
Bitmap b = loader.loadBlocking(CORRECT_MOCK_FILE_PATH);
assertTrue(correctFile.sameAs(b));
}
public void testNoDiskCacheFallback() throws IOException {
File invalidCacheDir = new File("../");
ImageLoader loader = new ImageLoader.Builder(getContext())
.enableDiskCache(invalidCacheDir, TEN_MEGABYTES)
.enableMemoryCache(TEN_MEGABYTES)
.addURLSchemeHandler("mock", new MockURLStreamHandler(getContext().getAssets()))
.build();
Bitmap b = loader.loadBlocking(CORRECT_MOCK_FILE_PATH);
assertTrue(correctFile.sameAs(b));
}
public void testTag() throws InterruptedException {
final CountDownLatch latch = new CountDownLatch(1);
final Object t = new Object();
final Holder<Object> h = new Holder<Object>();
loader.load(t, CORRECT_MOCK_FILE_PATH, new Listener<Object>() {
@Override
public void onSuccess(Object tag, Bitmap b) {
h.value = tag;
latch.countDown();
}
@Override
public void onError(Object tag, Throwable t) {
h.value = tag;
latch.countDown();
}
});
assertTrue(latch.await(TIMEOUT, TimeUnit.SECONDS));
assertSame(t, h.value);
}
public void testMissingImageAsync() throws InterruptedException {
final CountDownLatch latch = new CountDownLatch(1);
final Holder<Throwable> h = new Holder<Throwable>();
loader.load(null, WRONG_FILE_PATH, new Listener<Object>() {
@Override
public void onSuccess(Object tag, Bitmap b) {
latch.countDown();
}
@Override
public void onError(Object tag, Throwable t) {
h.value = t;
latch.countDown();
}
});
assertTrue(latch.await(TIMEOUT, TimeUnit.SECONDS));
assertTrue(h.value instanceof FileNotFoundException);
}
public void testMissingImage() throws IOException {
try {
loader.loadBlocking(WRONG_FILE_PATH);
fail("Should have thrown an exception");
} catch (FileNotFoundException e) {
// Expected
}
}
public void testMemory() throws IOException {
loader.loadBlocking(CORRECT_MOCK_FILE_PATH);
Bitmap b = loader.load(null, CORRECT_MOCK_FILE_PATH, EMPTY_LISTENER);
assertNotNull(b);
}
public void testAsyncSuccess() throws InterruptedException {
final CountDownLatch latch = new CountDownLatch(1);
final Holder<Bitmap> h = new Holder<Bitmap>();
loader.load(null, CORRECT_MOCK_FILE_PATH, new Listener<Object>() {
@Override
public void onSuccess(Object tag, Bitmap b) {
h.value = b;
latch.countDown();
}
@Override
public void onError(Object tag, Throwable t) {
latch.countDown();
}
});
assertTrue(latch.await(TIMEOUT, TimeUnit.SECONDS));
assertNotNull(h.value);
assertTrue(h.value.sameAs(correctFile));
}
public void testAsyncError() throws InterruptedException {
final CountDownLatch latch = new CountDownLatch(1);
final Holder<Throwable> h = new Holder<Throwable>();
loader.load(null, WRONG_FILE_PATH, new Listener<Object>() {
@Override
public void onSuccess(Object tag, Bitmap b) {
latch.countDown();
}
@Override
public void onError(Object tag, Throwable t) {
h.value = t;
latch.countDown();
}
});
assertTrue(latch.await(TIMEOUT, TimeUnit.SECONDS));
assertNotNull(h.value);
}
public void testMultipleRequests() throws InterruptedException {
final CountDownLatch latch = new CountDownLatch(5);
for (int i = 0; i < 5; i++) {
loader.load(null, CORRECT_MOCK_FILE_PATH, new Listener<Object>() {
@Override
public void onSuccess(Object tag, Bitmap b) {
latch.countDown();
}
@Override
public void onError(Object tag, Throwable t) {
latch.countDown();
}
});
}
assertTrue(latch.await(TIMEOUT, TimeUnit.SECONDS));
}
public void testRequestReuse() throws InterruptedException {
final CountDownLatch latch = new CountDownLatch(2);
final Holder<Bitmap> h1 = new Holder<Bitmap>();
final Holder<Bitmap> h2 = new Holder<Bitmap>();
loader.load(null, CORRECT_MOCK_FILE_PATH, new Listener<Object>() {
@Override
public void onSuccess(Object tag, Bitmap b) {
h1.value = b;
latch.countDown();
}
@Override
public void onError(Object tag, Throwable t) {
latch.countDown();
}
});
loader.load(null, CORRECT_MOCK_FILE_PATH, new Listener<Object>() {
@Override
public void onSuccess(Object tag, Bitmap b) {
h2.value = b;
latch.countDown();
}
@Override
public void onError(Object tag, Throwable t) {
latch.countDown();
}
});
assertTrue(latch.await(TIMEOUT, TimeUnit.SECONDS));
assertNotNull(h1.value);
assertNotNull(h2.value);
assertSame(h1.value, h2.value);
}
public void testRequestCancellation() throws InterruptedException {
final CountDownLatch latch = new CountDownLatch(1);
Object tag = new Object();
final Holder<Boolean> failed = new Holder<Boolean>();
loader.load(tag, WRONG_FILE_PATH, new Listener<Object>() {
@Override
public void onSuccess(Object tag, Bitmap b) {
failed.value = true;
latch.countDown();
}
@Override
public void onError(Object tag, Throwable t) {
failed.value = true;
latch.countDown();
}
});
loader.load(tag, CORRECT_MOCK_FILE_PATH, new Listener<Object>() {
@Override
public void onSuccess(Object tag, Bitmap b) {
latch.countDown();
}
@Override
public void onError(Object tag, Throwable t) {
latch.countDown();
}
});
assertTrue(latch.await(TIMEOUT, TimeUnit.SECONDS));
if (failed.value == Boolean.TRUE) {
fail("First request should have been cancelled");
}
}
public void testTagCancel() throws InterruptedException {
final CountDownLatch latch = new CountDownLatch(1);
Object tag = new Object();
// Use wrong path so it will fail faster
loader.load(tag, WRONG_FILE_PATH, new Listener<Object>() {
@Override
public void onSuccess(Object tag, Bitmap b) {
latch.countDown();
}
@Override
public void onError(Object tag, Throwable t) {
latch.countDown();
}
});
loader.cancel(tag);
// We should not get any callbacks
assertFalse(latch.await(TIMEOUT, TimeUnit.SECONDS));
}
public void testIgnoreCache() throws InterruptedException {
ignoreCache(new Request(CORRECT_MOCK_FILE_PATH));
}
public void testIgnoreCacheTransformation() throws InterruptedException {
ignoreCache(new Request(CORRECT_MOCK_FILE_PATH, new IdentityTransformation()));
}
public void testNoCache() throws InterruptedException {
noCache(new Request(CORRECT_MOCK_FILE_PATH), new Request(CORRECT_MOCK_FILE_PATH));
}
public void testNoCacheTransformation() throws InterruptedException {
noCache(new Request(CORRECT_MOCK_FILE_PATH), new Request(CORRECT_MOCK_FILE_PATH, new IdentityTransformation()));
}
public void noCache(Request firstRequest, Request secondRequest) throws InterruptedException {
firstRequest.addFlag(Request.Flag.NO_CACHE);
final CountDownLatch latch1 = new CountDownLatch(1);
loader.load(null, firstRequest, new Listener<Object>() {
@Override
public void onSuccess(Object tag, Bitmap b) {
latch1.countDown();
}
@Override
public void onError(Object tag, Throwable t) {
latch1.countDown();
}
});
assertTrue(latch1.await(TIMEOUT, TimeUnit.SECONDS));
// Request the image again and and see if the cache is present
final CountDownLatch latch2 = new CountDownLatch(1);
Bitmap b = loader.load(null, secondRequest, new Listener<Object>() {
@Override
public void onSuccess(Object tag, Bitmap b) {
latch2.countDown();
}
@Override
public void onError(Object tag, Throwable t) {
latch2.countDown();
}
});
assertNull(b);
assertTrue(latch2.await(TIMEOUT, TimeUnit.SECONDS));
assertEquals(2, streamHandler.timesOpened);
}
private void ignoreCache(Request request) throws InterruptedException {
request.addFlag(Request.Flag.IGNORE_CACHE);
final CountDownLatch latch1 = new CountDownLatch(1);
loader.load(null, CORRECT_MOCK_FILE_PATH, new Listener<Object>() {
@Override
public void onSuccess(Object tag, Bitmap b) {
latch1.countDown();
}
@Override
public void onError(Object tag, Throwable t) {
latch1.countDown();
}
});
assertTrue(latch1.await(TIMEOUT, TimeUnit.SECONDS));
// Request the image again and ignore cache
final CountDownLatch latch2 = new CountDownLatch(1);
Bitmap b = loader.load(null, request, new Listener<Object>() {
@Override
public void onSuccess(Object tag, Bitmap b) {
latch2.countDown();
}
@Override
public void onError(Object tag, Throwable t) {
latch2.countDown();
}
});
assertNull(b);
assertTrue(latch2.await(TIMEOUT, TimeUnit.SECONDS));
assertEquals(2, streamHandler.timesOpened);
}
public void testProgress() throws InterruptedException {
final CountDownLatch latch = new CountDownLatch(1);
final Holder<Float> h = new Holder<Float>();
loader.load(null, CORRECT_REQUEST, new Listener<Object>() {
@Override
public void onSuccess(Object tag, Bitmap b) {
latch.countDown();
}
@Override
public void onError(Object tag, Throwable t) {
latch.countDown();
}
}, new ImageLoader.ProgressListener() {
@Override
public void onProgress(float value) {
h.value = value;
}
});
assertTrue(latch.await(TIMEOUT, TimeUnit.SECONDS));
assertEquals(1f, h.value);
}
public void testProgressBlocking() throws IOException {
final Holder<Float> h = new Holder<Float>();
loader.loadBlocking(CORRECT_REQUEST, new ImageLoader.ProgressListener() {
@Override
public void onProgress(float value) {
h.value = value;
}
});
assertEquals(1f, h.value);
}
private static class IdentityTransformation extends SimpleTransformation {
@Override
public String getIdentifier() {
return "identity";
}
@Override
public Bitmap transform(Bitmap b) {
return b;
}
}
private static class MockURLStreamHandler extends URLStreamHandler {
private AssetManager assets;
public int timesOpened = 0;
public MockURLStreamHandler(AssetManager assets) {
this.assets = assets;
}
@Override
protected URLConnection openConnection(URL url) throws IOException {
timesOpened++;
return new MockURLConnection(assets, url);
}
}
private static class MockURLConnection extends URLConnection {
private AssetManager assets;
private String filename;
protected MockURLConnection(AssetManager assets, URL url) {
super(url);
this.assets = assets;
filename = url.getAuthority();
}
@Override
public void connect() throws IOException {}
@Override
public InputStream getInputStream() throws IOException {
return assets.open(filename);
}
@Override
public int getContentLength() {
return (int) new File(filename).length();
}
}
private static class Holder<T> {
public T value;
}
}
| 30.305609 | 120 | 0.597141 |
17643947fe9a41ba30ab8cbbcf2985368fd7c431 | 1,519 |
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
public class KeyManager implements KeyListener {
private boolean[] keys;
public boolean up, left, right, jump, down, start, res;
private int counter = 1;
static boolean check = true;
public KeyManager() {
keys = new boolean[256];
}
public void tick() {
jump = keys[KeyEvent.VK_SPACE];
left = keys[KeyEvent.VK_A];
right = keys[KeyEvent.VK_D];
up = keys[KeyEvent.VK_W];
down = keys[KeyEvent.VK_S];
start = keys[KeyEvent.VK_ENTER];
res = keys[KeyEvent.VK_UP];
}
public boolean isenter() {
return start;
}
@Override
public void keyPressed(KeyEvent e) {
keys[e.getKeyCode()] = true;
int c = e.getKeyCode();
if (c == KeyEvent.VK_SPACE) {
if (check) {
Mario.marioPressed = true;
}
}
}
@Override
public void keyReleased(KeyEvent e) {
keys[e.getKeyCode()] = false;
int c = e.getKeyCode();
if (c == KeyEvent.VK_SPACE) {
Mario.marioPressed = false;
if (check && Mario.marioPressed == false) {
check = false;
}
}
}
@Override
public void keyTyped(KeyEvent e) {
}
public boolean[] getKeys() {
return keys;
}
public void setKeys(boolean[] keys) {
this.keys = keys;
}
public boolean isUp() {
return up;
}
public void setUp(boolean up) {
this.up = up;
}
public int getCounter() {
return counter;
}
public void setCounter(int counter) {
this.counter = counter;
}
}
| 17.662791 | 57 | 0.614878 |
e6b529962239f9fb0097820a3a39b3db3d54025c | 7,279 | package com.atlassian.plugin.connect.plugin.web.panel;
import com.atlassian.plugin.ModuleDescriptor;
import com.atlassian.plugin.connect.api.descriptor.ConnectJsonSchemaValidator;
import com.atlassian.plugin.connect.api.web.WebFragmentLocationBlacklist;
import com.atlassian.plugin.connect.api.web.condition.ConditionLoadingValidator;
import com.atlassian.plugin.connect.api.web.iframe.IFrameRenderStrategy;
import com.atlassian.plugin.connect.api.web.iframe.IFrameRenderStrategyBuilderFactory;
import com.atlassian.plugin.connect.api.web.iframe.IFrameRenderStrategyRegistry;
import com.atlassian.plugin.connect.api.web.redirect.RedirectData;
import com.atlassian.plugin.connect.api.web.redirect.RedirectDataBuilderFactory;
import com.atlassian.plugin.connect.api.web.redirect.RedirectRegistry;
import com.atlassian.plugin.connect.modules.beans.ConnectAddonBean;
import com.atlassian.plugin.connect.modules.beans.ConnectModuleMeta;
import com.atlassian.plugin.connect.modules.beans.ConnectModuleValidationException;
import com.atlassian.plugin.connect.modules.beans.ShallowConnectAddonBean;
import com.atlassian.plugin.connect.modules.beans.WebPanelModuleBean;
import com.atlassian.plugin.connect.modules.beans.WebPanelModuleMeta;
import com.atlassian.plugin.connect.plugin.AbstractConnectCoreModuleProvider;
import com.atlassian.plugin.osgi.bridge.external.PluginRetrievalService;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import static com.atlassian.plugin.connect.api.web.redirect.RedirectData.AccessDeniedTemplateType.IFRAME;
public class WebPanelModuleProvider extends AbstractConnectCoreModuleProvider<WebPanelModuleBean> {
private static final WebPanelModuleMeta META = new WebPanelModuleMeta();
private final WebPanelConnectModuleDescriptorFactory webPanelFactory;
private final IFrameRenderStrategyBuilderFactory iFrameRenderStrategyBuilderFactory;
private final IFrameRenderStrategyRegistry iFrameRenderStrategyRegistry;
private final WebFragmentLocationBlacklist webFragmentLocationBlacklist;
private final ConditionLoadingValidator conditionLoadingValidator;
private final RedirectRegistry redirectRegistry;
private final RedirectDataBuilderFactory redirectDataBuilderFactory;
private final RedirectedWebPanelSectionSearcher redirectedWebPanelSectionSearcher;
public WebPanelModuleProvider(PluginRetrievalService pluginRetrievalService,
ConnectJsonSchemaValidator schemaValidator,
WebPanelConnectModuleDescriptorFactory webPanelFactory,
IFrameRenderStrategyBuilderFactory iFrameRenderStrategyBuilderFactory,
IFrameRenderStrategyRegistry iFrameRenderStrategyRegistry,
WebFragmentLocationBlacklist webFragmentLocationBlacklist,
ConditionLoadingValidator conditionLoadingValidator,
RedirectRegistry redirectRegistry,
RedirectDataBuilderFactory redirectDataBuilderFactory,
RedirectedWebPanelSectionSearcher redirectedWebPanelSectionSearcher) {
super(pluginRetrievalService, schemaValidator);
this.webPanelFactory = webPanelFactory;
this.iFrameRenderStrategyBuilderFactory = iFrameRenderStrategyBuilderFactory;
this.iFrameRenderStrategyRegistry = iFrameRenderStrategyRegistry;
this.webFragmentLocationBlacklist = webFragmentLocationBlacklist;
this.conditionLoadingValidator = conditionLoadingValidator;
this.redirectRegistry = redirectRegistry;
this.redirectDataBuilderFactory = redirectDataBuilderFactory;
this.redirectedWebPanelSectionSearcher = redirectedWebPanelSectionSearcher;
}
@Override
public ConnectModuleMeta<WebPanelModuleBean> getMeta() {
return META;
}
@Override
public List<WebPanelModuleBean> deserializeAddonDescriptorModules(String jsonModuleListEntry, ShallowConnectAddonBean descriptor) throws ConnectModuleValidationException {
List<WebPanelModuleBean> webPanels = super.deserializeAddonDescriptorModules(jsonModuleListEntry, descriptor);
conditionLoadingValidator.validate(pluginRetrievalService.getPlugin(), descriptor, getMeta(), webPanels);
assertLocationNotBlacklisted(descriptor, webPanels);
return webPanels;
}
@Override
public List<ModuleDescriptor<?>> createPluginModuleDescriptors(List<WebPanelModuleBean> modules, ConnectAddonBean addon) {
List<ModuleDescriptor<?>> descriptors = new ArrayList<>();
for (WebPanelModuleBean webPanel : modules) {
registerIframeRenderStrategy(webPanel, addon);
descriptors.add(webPanelFactory.createModuleDescriptor(webPanel, addon, pluginRetrievalService.getPlugin()));
}
return descriptors;
}
private void assertLocationNotBlacklisted(ShallowConnectAddonBean descriptor, List<WebPanelModuleBean> webPanelModuleBeans) throws ConnectModuleValidationException {
List<String> blacklistedLocationsUsed = webPanelModuleBeans.stream()
.filter(webPanel -> webFragmentLocationBlacklist.getBlacklistedWebPanelLocations().contains(webPanel.getLocation()))
.map(WebPanelModuleBean::getLocation)
.collect(Collectors.toList());
if (blacklistedLocationsUsed.size() > 0) {
String exceptionMsg = String.format("Installation failed. The add-on includes a web fragment with an unsupported location (%s).", blacklistedLocationsUsed);
throw new ConnectModuleValidationException(descriptor, getMeta(), exceptionMsg, "connect.install.error.invalid.location", blacklistedLocationsUsed.toArray(new String[blacklistedLocationsUsed.size()]));
}
}
private void registerIframeRenderStrategy(WebPanelModuleBean webPanel, ConnectAddonBean descriptor) {
boolean webPanelNeedsRedirection = redirectedWebPanelSectionSearcher.doesWebPanelNeedsToBeRedirected(webPanel, descriptor);
IFrameRenderStrategy renderStrategy = iFrameRenderStrategyBuilderFactory.builder()
.addon(descriptor.getKey())
.module(webPanel.getKey(descriptor))
.genericBodyTemplate()
.urlTemplate(webPanel.getUrl())
.title(webPanel.getDisplayName())
.redirect(webPanelNeedsRedirection)
.dimensions(webPanel.getLayout().getWidth(), webPanel.getLayout().getHeight())
.build();
iFrameRenderStrategyRegistry.register(descriptor.getKey(), webPanel.getRawKey(), renderStrategy);
if (webPanelNeedsRedirection) {
RedirectData redirectData = redirectDataBuilderFactory.builder()
.addOn(descriptor.getKey())
.urlTemplate(webPanel.getUrl())
.accessDeniedTemplateType(IFRAME)
.title(webPanel.getDisplayName())
.conditions(webPanel.getConditions())
.build();
redirectRegistry.register(descriptor.getKey(), webPanel.getRawKey(), redirectData);
}
}
}
| 59.178862 | 213 | 0.752164 |
8da45c2957798478a7d47ac770f1b89635b0f9bf | 11,835 | /*
* Jitsi, the OpenSource Java VoIP and Instant Messaging client.
*
* Copyright @ 2015 Atlassian Pty Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.java.sip.communicator.impl.protocol.irc;
import java.util.*;
import net.java.sip.communicator.util.*;
import com.ircclouds.irc.api.*;
import com.ircclouds.irc.api.domain.messages.*;
import com.ircclouds.irc.api.state.*;
/**
* MONITOR presence watcher.
*
* @author Danny van Heumen
*/
class MonitorPresenceWatcher
implements PresenceWatcher
{
/**
* Static overhead in message payload required for 'MONITOR +' command.
*/
private static final int MONITOR_ADD_CMD_STATIC_OVERHEAD = 10;
/**
* Logger.
*/
private static final Logger LOGGER = Logger
.getLogger(MonitorPresenceWatcher.class);
/**
* IRCApi instance.
*/
private final IRCApi irc;
/**
* IRC connection state.
*/
private final IIRCState connectionState;
/**
* Complete nick watch list.
*/
private final Set<String> nickWatchList;
/**
* List of monitored nicks.
*
* The instance is stored here only for access in order to remove a nick
* from the list, since 'MONITOR - ' command does not reply so we cannot
* manage list removals from the reply listener.
*/
private final Set<String> monitoredList;
/**
* Constructor.
*
* @param irc the IRCApi instance
* @param connectionState the connection state
* @param nickWatchList SYNCHRONIZED the nick watch list
* @param monitored SYNCHRONIZED The shared collection which contains all
* the nicks that are confirmed to be subscribed to the MONITOR
* command.
* @param operationSet the persistent presence operation set
*/
MonitorPresenceWatcher(final IRCApi irc, final IIRCState connectionState,
final Set<String> nickWatchList, final Set<String> monitored,
final OperationSetPersistentPresenceIrcImpl operationSet,
final int maxListSize)
{
if (irc == null)
{
throw new IllegalArgumentException("irc cannot be null");
}
this.irc = irc;
if (connectionState == null)
{
throw new IllegalArgumentException(
"connectionState cannot be null");
}
this.connectionState = connectionState;
if (nickWatchList == null)
{
throw new IllegalArgumentException("nickWatchList cannot be null");
}
this.nickWatchList = nickWatchList;
if (monitored == null)
{
throw new IllegalArgumentException("monitored cannot be null");
}
this.monitoredList = monitored;
this.irc.addListener(new MonitorReplyListener(this.monitoredList,
operationSet));
setUpMonitor(this.irc, this.nickWatchList, maxListSize);
LOGGER.debug("MONITOR presence watcher initialized.");
}
/**
* Set up monitor based on the nick watch list in its current state.
*
* Created a static method as not to interfere too much with a state that is
* still being initialized.
*/
private static void setUpMonitor(final IRCApi irc,
final Collection<String> nickWatchList, final int maxListSize)
{
List<String> current;
synchronized (nickWatchList)
{
current = new LinkedList<String>(nickWatchList);
}
if (current.size() > maxListSize)
{
// cut off list to maximum number of entries allowed by server
current = current.subList(0, maxListSize);
}
final int maxLength = 510 - MONITOR_ADD_CMD_STATIC_OVERHEAD;
final StringBuilder query = new StringBuilder();
for (String nick : current)
{
if (query.length() + nick.length() + 1 > maxLength)
{
// full payload, send monitor query now
irc.rawMessage("MONITOR + " + query);
query.delete(0, query.length());
}
else if (query.length() > 0)
{
query.append(",");
}
query.append(nick);
}
if (query.length() > 0)
{
// send query for remaining nicks
irc.rawMessage("MONITOR + " + query);
}
}
@Override
public void add(final String nick)
{
LOGGER.trace("Adding nick '" + nick + "' to MONITOR watch list.");
this.nickWatchList.add(nick);
this.irc.rawMessage("MONITOR + " + nick);
}
@Override
public void remove(final String nick)
{
LOGGER.trace("Removing nick '" + nick + "' from MONITOR watch list.");
this.nickWatchList.remove(nick);
this.irc.rawMessage("MONITOR - " + nick);
// 'MONITOR - nick' command does not send confirmation, so immediately
// remove nick from monitored list.
this.monitoredList.remove(nick);
}
/**
* Listener for MONITOR replies.
*
* @author Danny van Heumen
*/
private final class MonitorReplyListener
extends AbstractIrcMessageListener
{
/**
* Numeric message id for ONLINE nick response.
*/
private static final int IRC_RPL_MONONLINE = 730;
/**
* Numeric message id for OFFLINE nick response.
*/
private static final int IRC_RPL_MONOFFLINE = 731;
// /**
// * Numeric message id for MONLIST entry.
// */
// private static final int IRC_RPL_MONLIST = 732;
//
// /**
// * Numeric message id for ENDOFMONLIST.
// */
// private static final int IRC_RPL_ENDOFMONLIST = 733;
/**
* Error message signaling full list. Nick list provided are all nicks
* that failed to be added to the monitor list.
*/
private static final int IRC_ERR_MONLISTFULL = 734;
/**
* Operation set persistent presence instance.
*/
private final OperationSetPersistentPresenceIrcImpl operationSet;
/**
* Set of nicks that are confirmed to be monitored by the server.
*/
private final Set<String> monitoredNickList;
/**
* Constructor.
*
* @param monitored SYNCHRONIZED Collection of monitored nicks. This
* collection will be updated with all nicks that are
* confirmed to be subscribed by the MONITOR command.
* @param operationSet the persistent presence opset used to update nick
* presence statuses.
*/
public MonitorReplyListener(final Set<String> monitored,
final OperationSetPersistentPresenceIrcImpl operationSet)
{
super(MonitorPresenceWatcher.this.irc,
MonitorPresenceWatcher.this.connectionState);
if (operationSet == null)
{
throw new IllegalArgumentException(
"operationSet cannot be null");
}
this.operationSet = operationSet;
if (monitored == null)
{
throw new IllegalArgumentException("monitored cannot be null");
}
this.monitoredNickList = monitored;
}
/**
* Numeric messages received in response to MONITOR commands or presence
* updates.
*/
@Override
public void onServerNumericMessage(final ServerNumericMessage msg)
{
final List<String> acknowledged;
switch (msg.getNumericCode())
{
case IRC_RPL_MONONLINE:
acknowledged = parseMonitorResponse(msg.getText());
for (String nick : acknowledged)
{
update(nick, IrcStatusEnum.ONLINE);
}
monitoredNickList.addAll(acknowledged);
break;
case IRC_RPL_MONOFFLINE:
acknowledged = parseMonitorResponse(msg.getText());
for (String nick : acknowledged)
{
update(nick, IrcStatusEnum.OFFLINE);
}
monitoredNickList.addAll(acknowledged);
break;
case IRC_ERR_MONLISTFULL:
LOGGER.debug("MONITOR list full. Nick was not added. "
+ "Fall back Basic Poller will be used if it is enabled. ("
+ msg.getText() + ")");
break;
}
}
/**
* Update all monitored nicks upon receiving a server-side QUIT message
* for local user.
*/
@Override
public void onUserQuit(QuitMessage msg)
{
super.onUserQuit(msg);
if (localUser(msg.getSource().getNick())) {
updateAll(IrcStatusEnum.OFFLINE);
}
}
/**
* Update all monitored nicks upon receiving a server-side ERROR
* response.
*/
@Override
public void onError(ErrorMessage msg)
{
super.onError(msg);
updateAll(IrcStatusEnum.OFFLINE);
}
/**
* Update all monitored nicks upon receiving a client-side ERROR
* response.
*/
@Override
public void onClientError(ClientErrorMessage msg)
{
super.onClientError(msg);
updateAll(IrcStatusEnum.OFFLINE);
}
/**
* Parse response messages.
*
* @param message the message
* @return Returns the list of targets extracted.
*/
private List<String> parseMonitorResponse(final String message)
{
// Note: this should support both targets consisting of only a nick,
// and targets consisting of nick!ident@host formats. (And probably
// any variation on this that is typically allowed in IRC.)
final LinkedList<String> acknowledged = new LinkedList<String>();
final String[] targets = message.substring(1).split(",");
for (String target : targets)
{
String[] parts = target.trim().split("!");
acknowledged.add(parts[0]);
}
return acknowledged;
}
/**
* Update all monitored nicks to specified status.
*
* @param status the desired status
*/
private void updateAll(final IrcStatusEnum status)
{
final LinkedList<String> nicks;
synchronized (monitoredNickList)
{
nicks = new LinkedList<String>(monitoredNickList);
}
for (String nick : nicks)
{
update(nick, status);
}
}
/**
* Update specified nick to specified presence status.
*
* @param nick the target nick
* @param status the current status
*/
private void update(final String nick, final IrcStatusEnum status)
{
this.operationSet.updateNickContactPresence(nick, status);
}
}
}
| 32.336066 | 80 | 0.575412 |
fbc622493a63b22059b7f8dfb6032e5e86d61ea3 | 2,610 | package org.infinispan.api.client.configuration;
import java.util.List;
import java.util.function.Supplier;
import org.infinispan.api.configuration.ClientConfig;
import org.infinispan.client.hotrod.FailoverRequestBalancingStrategy;
import org.infinispan.client.hotrod.ProtocolVersion;
import org.infinispan.client.hotrod.configuration.ClientIntelligence;
import org.infinispan.client.hotrod.configuration.ClusterConfiguration;
import org.infinispan.client.hotrod.configuration.ConnectionPoolConfiguration;
import org.infinispan.client.hotrod.configuration.ExecutorFactoryConfiguration;
import org.infinispan.client.hotrod.configuration.NearCacheConfiguration;
import org.infinispan.client.hotrod.configuration.SecurityConfiguration;
import org.infinispan.client.hotrod.configuration.ServerConfiguration;
import org.infinispan.client.hotrod.configuration.StatisticsConfiguration;
import org.infinispan.client.hotrod.configuration.TransactionConfiguration;
import org.infinispan.client.hotrod.impl.consistenthash.ConsistentHash;
import org.infinispan.commons.marshall.Marshaller;
import org.infinispan.commons.util.Features;
public class Configuration implements ClientConfig {
private final org.infinispan.client.hotrod.configuration.Configuration configuration;
public Configuration(ExecutorFactoryConfiguration asyncExecutorFactory, Supplier<FailoverRequestBalancingStrategy> balancingStrategyFactory, ClassLoader classLoader, ClientIntelligence clientIntelligence, ConnectionPoolConfiguration connectionPool, int connectionTimeout, Class<? extends ConsistentHash>[] consistentHashImpl, boolean forceReturnValues, int keySizeEstimate, Marshaller marshaller, Class<? extends Marshaller> marshallerClass, ProtocolVersion protocolVersion, List<ServerConfiguration> servers, int socketTimeout, SecurityConfiguration security, boolean tcpNoDelay, boolean tcpKeepAlive, int valueSizeEstimate, int maxRetries, NearCacheConfiguration nearCache, List<ClusterConfiguration> clusters, List<String> serialWhitelist, int batchSize, TransactionConfiguration transaction, StatisticsConfiguration statistics, Features features) {
configuration = new org.infinispan.client.hotrod.configuration.Configuration(asyncExecutorFactory, balancingStrategyFactory, classLoader, clientIntelligence, connectionPool, connectionTimeout, consistentHashImpl, forceReturnValues, keySizeEstimate, marshaller, marshallerClass, protocolVersion, servers, socketTimeout, security, tcpNoDelay, tcpKeepAlive, valueSizeEstimate, maxRetries, nearCache, clusters, serialWhitelist, batchSize, transaction, statistics, features);
}
}
| 87 | 855 | 0.869732 |
a9015b92d18f37180b18d9aa2a6b1c4b8780b0a9 | 9,869 | /*
* Copyright (c) 2017, 2018, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.Collections;
import java.util.List;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.LogManager;
import java.util.logging.Logger;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* @test
* @bug 8191033
* @build custom.DotHandler custom.Handler
* @run main/othervm RootLoggerHandlers
* @run main/othervm/java.security.policy==test.policy RootLoggerHandlers
* @author danielfuchs
*/
public class RootLoggerHandlers {
public static final Path SRC_DIR =
Paths.get(System.getProperty("test.src", "src"));
public static final Path USER_DIR =
Paths.get(System.getProperty("user.dir", "."));
public static final Path CONFIG_FILE = Paths.get("logging.properties");
// Uncomment this to run the test on Java 8. Java 8 does not have
// List.of(...)
// static final class List {
// static <T> java.util.List<T> of(T... items) {
// return Collections.unmodifiableList(Arrays.asList(items));
// }
// }
public static void main(String[] args) throws IOException {
Path initialProps = SRC_DIR.resolve(CONFIG_FILE);
Path loggingProps = USER_DIR.resolve(CONFIG_FILE);
System.setProperty("java.util.logging.config.file", loggingProps.toString());
Files.copy(initialProps, loggingProps, StandardCopyOption.REPLACE_EXISTING);
loggingProps.toFile().setWritable(true);
System.out.println("Root level is: " + Logger.getLogger("").getLevel());
if (Logger.getLogger("").getLevel() != Level.INFO) {
throw new RuntimeException("Expected root level INFO, got: "
+ Logger.getLogger("").getLevel());
}
// Verify that we have two handlers. One was configured with
// handlers=custom.Handler, the other with
// .handlers=custom.DotHandler
// Verify that exactly one of the two handlers is a custom.Handler
// Verify that exactly one of the two handlers is a custom.DotHandler
// Verify that the two handlers has an id of '1'
checkHandlers(Logger.getLogger(""),
Logger.getLogger("").getHandlers(),
1L,
custom.Handler.class,
custom.DotHandler.class);
checkHandlers(Logger.getLogger("global"),
Logger.getGlobal().getHandlers(),
1L,
custom.GlobalHandler.class);
// The log message "hi" should appear twice on the console.
// We don't check that. This is just for log analysis in case
// of test failure.
Logger.getAnonymousLogger().info("hi");
// Change the root logger level to FINE in the properties file
// and reload the configuration.
Files.write(loggingProps,
Files.lines(initialProps)
.map((s) -> s.replace("INFO", "FINE"))
.collect(Collectors.toList()));
LogManager.getLogManager().readConfiguration();
System.out.println("Root level is: " + Logger.getLogger("").getLevel());
if (Logger.getLogger("").getLevel() != Level.FINE) {
throw new RuntimeException("Expected root level FINE, got: "
+ Logger.getLogger("").getLevel());
}
// Verify that we have now only one handler, configured with
// handlers=custom.Handler, and that the other configured with
// .handlers=custom.DotHandler was ignored.
// Verify that the handler is a custom.Handler
// Verify that the handler has an id of '2'
checkHandlers(Logger.getLogger(""),
Logger.getLogger("").getHandlers(),
2L,
custom.Handler.class);
checkHandlers(Logger.getGlobal(),
Logger.getGlobal().getHandlers(),
1L);
// The log message "there" should appear only once on the console.
// We don't check that. This is just for log analysis in case
// of test failure.
Logger.getAnonymousLogger().info("there!");
// Change the root logger level to FINER in the properties file
// and reload the configuration.
Files.write(loggingProps,
Files.lines(initialProps)
.map((s) -> s.replace("INFO", "FINER"))
.collect(Collectors.toList()));
LogManager.getLogManager().readConfiguration();
System.out.println("Root level is: " + Logger.getLogger("").getLevel());
if (Logger.getLogger("").getLevel() != Level.FINER) {
throw new RuntimeException("Expected root level FINER, got: "
+ Logger.getLogger("").getLevel());
}
// Verify that we have only one handler, configured with
// handlers=custom.Handler, and that the other configured with
// .handlers=custom.DotHandler was ignored.
// Verify that the handler is a custom.Handler
// Verify that the handler has an id of '3'
checkHandlers(Logger.getLogger(""),
Logger.getLogger("").getHandlers(),
3L,
custom.Handler.class);
checkHandlers(Logger.getGlobal(),
Logger.getGlobal().getHandlers(),
1L);
LogManager.getLogManager().reset();
LogManager.getLogManager().updateConfiguration((s) -> (o,n) -> n);
// Verify that we have only one handler, configured with
// handlers=custom.Handler, and that the other configured with
// .handlers=custom.DotHandler was ignored.
// Verify that the handler is a custom.Handler
// Verify that the handler has an id of '4'
checkHandlers(Logger.getLogger(""),
Logger.getLogger("").getHandlers(),
4L,
custom.Handler.class);
checkHandlers(Logger.getGlobal(),
Logger.getGlobal().getHandlers(),
2L,
custom.GlobalHandler.class);
LogManager.getLogManager().updateConfiguration((s) -> (o,n) -> n);
// Verify that we have only one handler, configured with
// handlers=custom.Handler, and that the other configured with
// .handlers=custom.DotHandler was ignored.
// Verify that the handler is a custom.Handler
// Verify that the handler has an id of '4'
checkHandlers(Logger.getLogger(""),
Logger.getLogger("").getHandlers(),
4L,
custom.Handler.class);
checkHandlers(Logger.getGlobal(),
Logger.getGlobal().getHandlers(),
2L,
custom.GlobalHandler.class);
// The log message "done" should appear only once on the console.
// We don't check that. This is just for log analysis in case
// of test failure.
Logger.getAnonymousLogger().info("done!");
}
static void checkHandlers(Logger logger, Handler[] handlers, Long expectedID, Class<?>... clz) {
// Verify that we have the expected number of handlers.
if (Stream.of(handlers).count() != clz.length) {
throw new RuntimeException("Expected " + clz.length + " handlers, got: "
+ List.of(logger.getHandlers()));
}
for (Class<?> cl : clz) {
// Verify that the handlers are of the expected class.
// For each class, we should have exactly one handler
// of that class.
if (Stream.of(handlers)
.map(Object::getClass)
.filter(cl::equals)
.count() != 1) {
throw new RuntimeException("Expected one " + cl +", got: "
+ List.of(logger.getHandlers()));
}
}
// Verify that all handlers have the expected ID
if (Stream.of(logger.getHandlers())
.map(RootLoggerHandlers::getId)
.filter(expectedID::equals)
.count() != clz.length) {
throw new RuntimeException("Expected ids to be " + expectedID + ", got: "
+ List.of(logger.getHandlers()));
}
}
static long getId(Handler h) {
if (h instanceof custom.Handler) {
return ((custom.Handler)h).id;
}
if (h instanceof custom.DotHandler) {
return ((custom.DotHandler)h).id;
}
if (h instanceof custom.GlobalHandler) {
return ((custom.GlobalHandler)h).id;
}
return -1;
}
}
| 42.722944 | 100 | 0.603202 |
c35951165a44503b44e348dcbfbccd60216afcd4 | 7,016 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package engines;
import distancemetrics.DistanceMetric;
import utils.InputOutput;
import utils.Mathematics;
import utils.RandomNumberGenerator;
import emo.Individual;
import emo.IndividualsSet;
import emo.OptimizationProblem;
import java.io.*;
import refdirs.ReferenceDirection;
import java.util.ArrayList;
import parsing.IndividualEvaluator;
/**
* This class represents the Unified NSGA-III algorithm. A detailed description
* of the algorithm can be found at: Seada, Haitham, and Kalyanmoy Deb. "A
* unified evolutionary optimization procedure for single, multiple, and many
* objectives." IEEE Transactions on Evolutionary Computation 20.3 (2016):
* 358-369.
*
* @author Haitham Seada
*/
public class UnifiedNSGA3Engine extends NSGA3Engine {
public UnifiedNSGA3Engine(
OptimizationProblem optimizationProblem,
IndividualEvaluator individualEvaluator,
DistanceMetric distanceMetric,
File outputDir) {
super(optimizationProblem, individualEvaluator, distanceMetric, outputDir);
}
public UnifiedNSGA3Engine(
OptimizationProblem optimizationProblem,
IndividualEvaluator individualEvaluator,
DistanceMetric distanceMetric,
File outputDir,
int[] divisions) {
super(optimizationProblem, individualEvaluator, distanceMetric, outputDir, divisions);
}
public UnifiedNSGA3Engine(
OptimizationProblem optimizationProblem,
IndividualEvaluator individualEvaluator,
DistanceMetric distanceMetric,
File outputDir,
File directionsFile)
throws
FileNotFoundException,
IOException {
super(optimizationProblem, individualEvaluator, distanceMetric, outputDir);
// Read Directions from File
BufferedReader reader = null;
try {
referenceDirectionsList = new ArrayList<ReferenceDirection>();
reader = new BufferedReader(new FileReader(directionsFile));
String line;
while ((line = reader.readLine()) != null) {
String[] splits = line.trim().split(" ");
if (!line.isEmpty()) {
double[] dirValues = new double[splits.length];
for (int i = 0; i < splits.length; i++) {
dirValues[i] = Double.parseDouble(splits[i]);
}
referenceDirectionsList.add(
new ReferenceDirection(dirValues));
}
}
} finally {
if (reader != null) {
reader.close();
}
}
InputOutput.displayReferenceDirections(
"Reference Directions",
referenceDirectionsList);
}
public static int totalSelectionsCount = 0;
public static int bothFeasibleCount = 0;
@Override
protected Individual tournamentSelect(IndividualsSet subset) {
totalSelectionsCount++;
Individual individual1 = subset.getIndividual1();
Individual individual2 = subset.getIndividual2();
// If only one of the solutions is infeasible, return the feasible
// solution
if (optimizationProblem.constraints != null
&& optimizationProblem.constraints.length != 0
&& (individual1.isFeasible() ^ individual2.isFeasible())) {
// If the problem is constrained and one of the individuals
// under investigation is feasible while the other is infeasible,
// return the feasible one (which is normally the dominating
// individual).
if (individual1.isFeasible()) {
return individual1;
} else {
return individual2;
}
} else if (!individual1.isFeasible() && !individual2.isFeasible()) {
// If both the two solutions are infeasible, return the less
// violating.
if (Mathematics.compare(
individual1.getTotalConstraintViolation(),
individual2.getTotalConstraintViolation()) == 1) {
// individual1 is less violating (remember: the more negative
// the value, the more the violation)
return individual1;
} else {
// individual2 is less violating
return individual2;
}
} //else if (optimizationProblem.objectives.length == 1) {
// If we have only one objective and both solutions are feasible,
// return the better in terms of objective value (i.e. the
// dominating solution). If the two ranks are equal this means that
// the two individuals are identical so return any of them.
// (Remember: in the case of single objective, one idividual must
// dominate the other unless both are identical to each other. This
// is the only case where they will have the same rank)
//if (individual1.dominates(individual2)) {
//return individual1;
//} else {
//return individual2;
//}
//}
else if (currentGenerationIndex != 0
&& individual1.getReferenceDirection().equals(
individual2.getReferenceDirection())) {
bothFeasibleCount++;
// If both the two solutions are feasible. You have the
// following two options:
// If the two individuals belong to the same reference direction,
// return the one with lower rank.
if (individual1.getRank() < individual2.getRank()) {
return individual1;
} else if (individual2.getRank() < individual1.getRank()) {
return individual2;
} else {
// If they both belong to the same rank return the one
// closest to the reference direction.
if (Mathematics.compare(
individual1.getPerpendicularDistance(),
individual2.getPerpendicularDistance()) == -1) {
return individual1;
} else {
return individual2;
}
}
} else {
// If the two individuals are associated with two different
// reference directions, then return one of them randomly
if (RandomNumberGenerator.next() <= 0.5) {
return individual1;
} else {
return individual2;
}
}
}
@Override
public String getAlgorithmName() {
return "unified_nsga3";
}
}
| 40.091429 | 95 | 0.579532 |
136ee120405343cf698911d3b24426451cb5db35 | 66 | package com.augustine.jpa.domain;
public class StdVoca {
}
| 11 | 34 | 0.69697 |
c07becb2ed0b8af6c5c675936228837cbfd25bdb | 272 | package com.mizuledevelopment.node.threads;
import com.mizuledevelopment.node.jedis.JedisPublisher;
public class PingRunnable implements Runnable {
@Override
public void run() {
new JedisPublisher().publishData("PING///" + System.getenv("ID"));
}
}
| 22.666667 | 74 | 0.716912 |
b7e1dd42a6ad77770b6f831eab5a5ad0f06f8220 | 5,336 | package com.trycatch.wasuradananjith.smartkubura2;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.method.LinkMovementMethod;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.trycatch.wasuradananjith.smartkubura2.Model.User;
public class LoginActivity extends AppCompatActivity {
TextView proceedToSignUp;
EditText etPhone, etPassword;
DatabaseReference mDatabase;
Button btnLogin;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
etPassword = (EditText)findViewById(R.id.edtPassword);
etPhone = (EditText)findViewById(R.id.edtTelephone);
btnLogin = (Button)findViewById(R.id.btn_sign_in);
proceedToSignUp = (TextView)findViewById(R.id.link_sign_up);
TextView privacy_policy_link = (TextView)findViewById(R.id.privacyPolicy);
privacy_policy_link.setMovementMethod(LinkMovementMethod.getInstance());
// get the database reference "users" in firebase realtime database
mDatabase = FirebaseDatabase.getInstance().getReference("users");
// when the login button is clicked
btnLogin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
signIn(etPhone.getText().toString(),etPassword.getText().toString());
}
});
// when the register new user button is clicked
proceedToSignUp.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), RegisterActivity.class);
startActivity(intent);
finish();
overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
}
});
}
// when the log in button is clicked, this method will be called
private void signIn(final String phone, final String pwd) {
mDatabase.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.child(phone).exists()){
if (!phone.isEmpty()){
final User login = dataSnapshot.child(phone).getValue(User.class);
if (login.getPassword().equals(pwd)){
final ProgressDialog progressDialog = new ProgressDialog(LoginActivity.this,
R.style.AppTheme_Dark_Dialog);
progressDialog.setIndeterminate(true);
progressDialog.setMessage("මදක් රැඳෙන්න ...");
progressDialog.show();
// set current user
SharedPreferences pref = getSharedPreferences("loginData", MODE_PRIVATE);
final SharedPreferences.Editor editor = pref.edit();
editor.putString("phone", phone);
editor.putString("email", login.getEmail());
editor.putString("user", login.getName());
editor.commit();
new android.os.Handler().postDelayed(
new Runnable() {
public void run() {
Toast.makeText(LoginActivity.this,"පිළිගන්නවා "+login.getName()+"!",Toast.LENGTH_SHORT).show();
progressDialog.dismiss();
Intent intent = new Intent(getApplicationContext(), HomeActivity.class);
startActivity(intent);
finish();
overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
}
}, 3000);
}
else{
Toast.makeText(LoginActivity.this,"මුරපදය වැරදිය !",Toast.LENGTH_SHORT).show();
}
}
else{
Toast.makeText(LoginActivity.this,"ජංගම දුරකථන අංකය සටහන් කරන්න !",Toast.LENGTH_SHORT).show();
}
}
else{
Toast.makeText(LoginActivity.this,"ඔබ ලියාපදිංචි වී නැත !",Toast.LENGTH_SHORT).show();
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
| 43.737705 | 139 | 0.566529 |
759003c832f9f3041e82794d887b2cf8eec2c3aa | 2,174 | package com.neusoft.labour.controller;
import javax.jws.WebService;
import javax.xml.ws.Holder;
import org.apache.log4j.Logger;
import com.neusoft.labour.service.InsurancePortService;
import com.neusoft.labour.util.CommonConstantUtil;
import cn.gov.ynhrss.psp.YnhrssPSPPortType;
import cn.gov.ynhrss.psp.Pspenv;
/**
*
* <p>Title: 云南省云南人社公共服务平台劳动合同备案接口</p>
* <p>Description: 接入平台和劳动备案网厅交互的webservice实现类</p>
* <p>Copyright: Copyright (c) 2016</p>
* <p>Company: 东软集团股份有限公司</p>
* <p>Department: 西南大区(昆明)-云南研发与交付中心二</p>
* @author chen-tao
* @version 1.0
*/
@WebService(name= "YnhrssPSPPortType",serviceName="YnhrssPSPService",endpointInterface = "cn.gov.ynhrss.psp.YnhrssPSPPortType", targetNamespace = "http://www.ynhrss.gov.cn/psp", portName = "YnhrssPSPPortType")
public class LdwtController implements YnhrssPSPPortType {
private static Logger logger = Logger.getLogger(LdwtController.class);
InsurancePortService insurancePortService =new InsurancePortService();
/**
* 业务核心逻辑处理类 service
*/
public void ynhrssPSPOP(Holder<Pspenv> parameters) {
// TODO Auto-generated method stub
String strServiceID = parameters.value.getPsppilot().getServiceid();
if (true) {
// APP已接入到云南人社公共服务平劳动合同备案接口
logger.info("LdwtController------Loadin...OK");
try {
// 查询二代金融社保卡制卡进度
if ("8030999999".equals(strServiceID)) {
insurancePortService.transfrompspenv(parameters);
}
// 劳动合同备案
else if ("8030010001".equals(strServiceID)) {
insurancePortService.ldhtba(parameters);
}
// 劳动合同备案结果查询
else if ("8030010002".equals(strServiceID)) {
insurancePortService.querylthtba(parameters);
}
else {
logger.info("云南人社公共服务平劳动合同备案接口---业务代码不存在!");
parameters.value.getPsppilot().setStatuscode(CommonConstantUtil.STATUSFAIL);
parameters.value.getPsppilot().setStatusmessage(CommonConstantUtil.NOBUSINESS);
}
} catch (Exception e) {
e.printStackTrace();
logger.info("云南人社公共服务平劳动合同备案接口---系统异常1!");
parameters.value.getPsppilot().setStatuscode(CommonConstantUtil.STATUSFAIL);
parameters.value.getPsppilot().setStatusmessage(CommonConstantUtil.SYSEXCEPTION);
}
}
}
} | 31.057143 | 210 | 0.734591 |
3f3373b5cc262bb90bb21aeedbd655b35d26ade9 | 1,630 | /*
* User Stories - Frontend
* Copyright (c) 2021 Falko Schumann <falko.schumann@muspellheim.de>
*/
package de.muspellheim.userstories.frontend;
import de.muspellheim.userstories.contract.messages.commands.CreateUserCommand;
import de.muspellheim.userstories.contract.messages.queries.UserQuery;
import de.muspellheim.userstories.contract.messages.queries.UserQueryResult;
import java.util.function.Consumer;
import javafx.fxml.FXML;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;
import lombok.Getter;
import lombok.Setter;
public class MainViewController {
@Getter @Setter private Runnable onOpenInfo;
@Getter @Setter private Consumer<CreateUserCommand> onCreateUserCommand;
@Getter @Setter private Consumer<UserQuery> onUserQuery;
@FXML private HBox commandBar;
@FXML private Label greeting;
public static MainViewController create(Stage stage) {
var factory = new ViewControllerFactory(MainViewController.class);
var scene = new Scene(factory.getView());
stage.setScene(scene);
stage.setTitle("User Stories");
stage.setMinWidth(320);
stage.setMinHeight(569);
return factory.getController();
}
private Stage getWindow() {
return (Stage) commandBar.getScene().getWindow();
}
public void run() {
getWindow().show();
onUserQuery.accept(new UserQuery());
}
public void display(UserQueryResult result) {
greeting.setText("Hello " + result.getUser().getName());
}
@FXML
private void initialize() {}
@FXML
private void handleOpenInfo() {
onOpenInfo.run();
}
}
| 26.721311 | 79 | 0.749693 |
9faa8853b4036a22baf0719d686df69a6712b8b9 | 3,039 | /*
* Copyright (c) 2002, 2018, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
// THIS TEST IS LINE NUMBER SENSITIVE
package nsk.jdb.locals.locals002;
import nsk.share.*;
import nsk.share.jpda.*;
import nsk.share.jdb.*;
import java.io.*;
/* This is debuggee aplication */
public class locals002a {
static locals002a _locals002a = new locals002a();
public static void main(String args[]) {
System.exit(locals002.JCK_STATUS_BASE + _locals002a.runIt(args, System.out));
}
static void lastBreak () {}
public int runIt(String args[], PrintStream out) {
JdbArgumentHandler argumentHandler = new JdbArgumentHandler(args);
Log log = new Log(out, argumentHandler);
int arr[] = new int[3];
for (int i = 0 ; i < 3 ; i++) arr[i] = i*i;
allKindsOfVars (
false,
(byte)12,
'A',
(short)327,
3647,
(long)65789,
(float)4.852,
(double)3.8976,
"objArgString",
arr
);
allKindsOfLocals();
log.display("Debuggee PASSED");
return locals002.PASSED;
}
public void allKindsOfVars (
boolean boolVar,
byte byteVar,
char charVar,
short shortVar,
int intVar,
long longVar,
float floatVar,
double doubleVar,
Object objVar,
int[] arrVar
)
{
int x = 3; // locals002.BREAKPOINT_LINE1
}
static void allKindsOfLocals() {
boolean boolVar = true;
byte byteVar = 27;
char charVar = 'V';
short shortVar = (short)767;
int intVar = 1474;
long longVar = (long)21345;
float floatVar = (float)3.141;
double doubleVar = (double)2.578;
Object objVar = "objVarString";
int[] arrVar = new int[5];
for (int j = 0; j < 5 ; j++) arrVar[j] = j;
int x = 4; // locals002.BREAKPOINT_LINE2
}
}
| 29.504854 | 84 | 0.604146 |
5ced27b2b288f09a9692747cf586f5d4ed58c1d8 | 1,337 | package ru.otus.quiz;
import lombok.RequiredArgsConstructor;
import org.springframework.context.MessageSource;
import org.springframework.stereotype.Component;
import ru.otus.infrastructure.IOService;
import ru.otus.quiz.config.QuizProps;
import ru.otus.quiz.domain.User;
import ru.otus.quiz.service.LoginService;
import ru.otus.quiz.service.QuizRunner;
@Component
@RequiredArgsConstructor
public class QuizApplication {
private static final String SUCCESS_RESULT = "quiz.result.success";
private static final String FAILURE_RESULT = "quiz.result.fail";
private final LoginService loginService;
private final QuizRunner quizRunner;
private final IOService ioService;
private final QuizProps quizProps;
private final MessageSource quizLocalization;
public void takeQuiz() {
final User user = loginService.login();
final long numberOfRightAnswers = quizRunner.runQuiz();
String result = numberOfRightAnswers > quizProps.getPassPoints()
? SUCCESS_RESULT
: FAILURE_RESULT;
final String resultMessage = quizLocalization.getMessage(
result,
new String[]{user.getName(), String.valueOf(numberOfRightAnswers)},
quizProps.getLocale()
);
ioService.printLine(resultMessage);
}
}
| 34.282051 | 83 | 0.723261 |
4a204cdf6d7a36464c87e09c57cc574ce12efb08 | 1,026 | package binarySearch;
public class BinarySearch {
/**
* Function to search value using binary search algorithm.
* @param sortedArray array to be searched
* @param target search key value
* @return index if value found
* -1 if value not in the array
*/
public static int BinarySearch(int[] sortedArray, int target){
//Check if the array is not null
if(sortedArray == null){
throw new IllegalArgumentException("Parameters cannot be null");
}
// Set left and right index
int left = 0;
int right = sortedArray.length - 1;
//Iterate through the loop
while(left <= right){
int mid = left + right / 2;
if(sortedArray[mid] < target){
left = mid + 1;
} else if(sortedArray[mid] > target){
right = mid - 1;
} else {
return mid;
}
}
// Return -1 if not found
return -1;
}
} | 27 | 76 | 0.52924 |
8584358687205cd6790305883c25fdfaafb5eab6 | 472 | package com.alexvasilkov.foldablelayout.sample.data;
import com.google.gson.Gson;
import java.util.ArrayList;
public class order {
public String id;
public String user;
public ArrayList<orderItem> itemList;
public order(){}
public order(String user, ArrayList<orderItem> item_list){
this.user = user;
this.itemList = item_list;
}
@Override
public String toString(){
return new Gson().toJson(this);
}
}
| 16.857143 | 62 | 0.663136 |
31b93dbd34cc12ae735113b3b262c5501252698c | 7,004 | package org.webcurator.core.coordinator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.webcurator.core.exceptions.WCTRuntimeException;
import org.webcurator.core.scheduler.TargetInstanceManager;
import org.webcurator.core.util.PatchUtil;
import org.webcurator.core.visualization.VisualizationProgressView;
import org.webcurator.core.visualization.networkmap.metadata.NetworkMapResult;
import org.webcurator.core.visualization.networkmap.service.NetworkMapClient;
import org.webcurator.domain.model.core.HarvestResult;
import org.webcurator.domain.model.core.HarvestResultDTO;
import org.webcurator.domain.model.core.TargetInstance;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class HarvestResultManagerImpl implements HarvestResultManager {
private static final Logger log = LoggerFactory.getLogger(HarvestResultManagerImpl.class);
private final Map<String, HarvestResultDTO> harvestResults = Collections.synchronizedMap(new HashMap<>());
private TargetInstanceManager targetInstanceManager;
private NetworkMapClient networkMapClient;
@Override
public void removeHarvestResult(HarvestResultDTO hrDTO) {
harvestResults.remove(hrDTO.getKey());
}
@Override
public void removeHarvestResult(long targetInstanceId, int harvestResultNumber) {
String key = PatchUtil.getPatchJobName(targetInstanceId, harvestResultNumber);
harvestResults.remove(key);
}
@Override
public HarvestResultDTO getHarvestResultDTO(long targetInstanceId, int harvestResultNumber) throws WCTRuntimeException {
String key = PatchUtil.getPatchJobName(targetInstanceId, harvestResultNumber);
HarvestResultDTO hrDTO = harvestResults.containsKey(key) ? harvestResults.get(key) : initHarvestResultDTO(targetInstanceId, harvestResultNumber);
if (hrDTO == null) {
return null;
}
//Refresh state, status and progress
if (hrDTO.getState() == HarvestResult.STATE_MODIFYING || hrDTO.getState() == HarvestResult.STATE_INDEXING) {
NetworkMapResult progressBar = networkMapClient.getProgress(targetInstanceId, harvestResultNumber);
if (progressBar.getRspCode() == NetworkMapResult.RSP_CODE_SUCCESS) {
VisualizationProgressView progressView = VisualizationProgressView.getInstance(progressBar.getPayload());
hrDTO.setProgressView(progressView);
hrDTO.setState(progressView.getState());
hrDTO.setStatus(progressView.getStatus());
} else {
hrDTO.setStatus(HarvestResult.STATUS_SCHEDULED);
}
}
return hrDTO;
}
@Override
public void updateHarvestResultStatus(long targetInstanceId, int harvestResultNumber, int state, int status) {
log.debug("updateHarvestResultStatus: targetInstanceId={}, harvestResultNumber={}, state={}, status={}", targetInstanceId, harvestResultNumber, state, status);
HarvestResultDTO hrDTO = getHarvestResultDTO(targetInstanceId, harvestResultNumber);
if (hrDTO != null) {
//Update the state in DB
HarvestResult hr = targetInstanceManager.getHarvestResult(targetInstanceId, harvestResultNumber);
if (hr != null && hrDTO.getState() != state) {
hr.setState(state);
targetInstanceManager.save(hr);
}
hrDTO.setState(state);
hrDTO.setStatus(status);
String key = PatchUtil.getPatchJobName(targetInstanceId, harvestResultNumber);
harvestResults.put(key, hrDTO);
}
}
@Override
public void updateHarvestResultStatus(HarvestResultDTO hrDTO) {
updateHarvestResultStatus(hrDTO.getTargetInstanceOid(), hrDTO.getHarvestNumber(), hrDTO.getState(), hrDTO.getStatus());
}
@Override
public void updateHarvestResultsStatus(List<HarvestResultDTO> harvestResultDTOList) {
harvestResults.clear();
for (HarvestResultDTO hrDTO : harvestResultDTOList) {
updateHarvestResultStatus(hrDTO);
}
}
private HarvestResultDTO initHarvestResultDTO(long targetInstanceId, int harvestResultNumber) {
HarvestResultDTO hrDTO = null;
TargetInstance ti = targetInstanceManager.getTargetInstance(targetInstanceId);
if (ti == null || ti.getHarvestResult(harvestResultNumber) == null) {
log.info("Harvest Result does not exist, targetInstanceId={}, harvestResultNumber={}", targetInstanceId, harvestResultNumber);
return null;
}
if (!ti.getState().equalsIgnoreCase(TargetInstance.STATE_PATCHING) || harvestResultNumber == 1) {
hrDTO = new HarvestResultDTO();
hrDTO.setTargetInstanceOid(targetInstanceId);
hrDTO.setHarvestNumber(harvestResultNumber);
hrDTO.setState(HarvestResult.STATE_UNASSESSED);
hrDTO.setStatus(HarvestResult.STATUS_UNASSESSED);
return hrDTO;
}
NetworkMapResult remoteResult = networkMapClient.getProcessingHarvestResultDTO(targetInstanceId, harvestResultNumber);
if (remoteResult.getRspCode() == NetworkMapResult.RSP_CODE_SUCCESS) {
hrDTO = HarvestResultDTO.getInstance(remoteResult.getPayload());
} else {
hrDTO = new HarvestResultDTO();
}
HarvestResult hr = targetInstanceManager.getHarvestResult(targetInstanceId, harvestResultNumber);
if (hr == null) {
log.info("Harvest Result does not exist, targetInstanceId={}, harvestResultNumber={}", targetInstanceId, harvestResultNumber);
return null;
}
hrDTO.setTargetInstanceOid(targetInstanceId);
hrDTO.setHarvestNumber(harvestResultNumber);
hrDTO.setOid(hr.getOid());
if (hr.getCreatedBy() != null) {
hrDTO.setCreatedByFullName(hr.getCreatedBy().getFullName());
} else {
hrDTO.setCreatedByFullName("Unknown");
}
hrDTO.setDerivedFrom(hr.getDerivedFrom());
hrDTO.setProvenanceNote(hr.getProvenanceNote());
hrDTO.setCreationDate(hr.getCreationDate());
hrDTO.setState(hr.getState());
//Normalize state
if (hrDTO.getState() == HarvestResult.STATE_CRAWLING
|| hrDTO.getState() == HarvestResult.STATE_MODIFYING
|| hrDTO.getState() == HarvestResult.STATE_INDEXING) {
hrDTO.setStatus(HarvestResult.STATUS_SCHEDULED);
} else {
hrDTO.setStatus(HarvestResult.STATUS_UNASSESSED);
}
harvestResults.put(hrDTO.getKey(), hrDTO);
return hrDTO;
}
public void setTargetInstanceManager(TargetInstanceManager targetInstanceManager) {
this.targetInstanceManager = targetInstanceManager;
}
public void setNetworkMapClient(NetworkMapClient networkMapClient) {
this.networkMapClient = networkMapClient;
}
}
| 43.775 | 167 | 0.703027 |
7e16ca03f7e77cb7cfe4a10a98089655accce680 | 2,877 | package robosky.uplands.world.biome;
import robosky.uplands.block.BlockRegistry;
import robosky.uplands.block.UplandsOreBlock;
import robosky.uplands.world.feature.FeatureRegistry;
import robosky.uplands.world.feature.UplandsOreFeatureConfig;
import net.minecraft.block.Blocks;
import net.minecraft.entity.EntityCategory;
import net.minecraft.entity.EntityType;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.biome.Biome;
import net.minecraft.world.gen.GenerationStep;
import net.minecraft.world.gen.decorator.ChanceDecoratorConfig;
import net.minecraft.world.gen.decorator.Decorator;
import net.minecraft.world.gen.decorator.RangeDecoratorConfig;
import net.minecraft.world.gen.feature.FeatureConfig;
import net.minecraft.world.gen.feature.SingleStateFeatureConfig;
public class UplandsVoidBiome extends Biome {
protected UplandsVoidBiome() {
super(new Settings().configureSurfaceBuilder(BiomeRegistry.UPLANDS_AUTUMN_SURFACE_BUILDER,
BiomeRegistry.UPLANDS_GRASS_DIRT_STONE_SURFACE).precipitation(Precipitation.NONE).category(Category.FOREST)
.depth(0).scale(0.2F).temperature(0.5F).downfall(0.0F)
.waterColor(0x9898BC).waterFogColor(0x9898BC).category(Category.FOREST));
addFeature(GenerationStep.Feature.UNDERGROUND_ORES, FeatureRegistry.ORE_FEATURE.configure(
new UplandsOreFeatureConfig(9, 1, 128, BlockRegistry.UPLANDS_ORES.get(UplandsOreBlock.oreTypeAegisalt).getDefaultState()))
.createDecoratedFeature(Decorator.COUNT_RANGE.configure(new RangeDecoratorConfig(1, 0, 0, 256))));
addFeature(GenerationStep.Feature.UNDERGROUND_ORES, FeatureRegistry.ORE_FEATURE.configure(
new UplandsOreFeatureConfig(20, 1, 64, BlockRegistry.LODESTONE.getDefaultState()))
.createDecoratedFeature(Decorator.COUNT_RANGE.configure(new RangeDecoratorConfig(4, 0, 0, 256))));
addFeature(GenerationStep.Feature.LOCAL_MODIFICATIONS, FeatureRegistry.SKY_LAKE.configure(
new SingleStateFeatureConfig(Blocks.WATER.getDefaultState()))
.createDecoratedFeature(Decorator.WATER_LAKE.configure(new ChanceDecoratorConfig(8))));
addFeature(GenerationStep.Feature.SURFACE_STRUCTURES, FeatureRegistry.TREEHOUSE.configure(FeatureConfig.DEFAULT)
.createDecoratedFeature(Decorator.CHANCE_PASSTHROUGH.configure(new ChanceDecoratorConfig(100))));
addSpawn(EntityCategory.MONSTER, new Biome.SpawnEntry(EntityType.ENDERMAN, 10, 1, 4));
}
@Override
public int getSkyColor() {
return 12632319;
}
@Override
protected float computeTemperature(BlockPos blockPos) {
return getTemperature();
}
@Override
public int getGrassColorAt(double d, double e) {
return 15382866;
}
@Override
public int getFoliageColor() {
return 15382866;
}
}
| 44.261538 | 134 | 0.766771 |
3b41ebb80c2dfeb8c4282776eec892fd3401da67 | 1,452 | package de.hgu.gsehen.model;
import java.util.Date;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
@Entity
public class ManualWaterSupply {
@Id
@GeneratedValue
private long id;
private Date date;
private Double irrigation;
private Double precipitation;
private String unit;
public ManualWaterSupply() {
}
/**
* Constructor for ManualWaterSupply.
*
* @param date
* Date of Manual action
* @param irrigation
* applied amount of water in mm/Liter
* @param precipitation
* amount of rainfall in mm/Liter
* @param unit
* mm/Liter
*/
public ManualWaterSupply(Date date, Double irrigation, Double precipitation, String unit) {
super();
this.date = date;
this.irrigation = irrigation;
this.precipitation = precipitation;
this.unit = unit;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public Double getIrrigation() {
return irrigation;
}
public void setIrrigation(Double irrigation) {
this.irrigation = irrigation;
}
public Double getPrecipitation() {
return precipitation;
}
public void setPrecipitation(Double precipitation) {
this.precipitation = precipitation;
}
public String getUnit() {
return unit;
}
public void setUnit(String unit) {
this.unit = unit;
}
}
| 19.621622 | 93 | 0.670799 |
f79651fa6d3cb0f3d1094a2c6d8354663e23c697 | 767 | package L12InterfacesExercise.Ex04Telephony;
import java.util.List;
public class SmartPhoneImpl implements SmartPhone {
@Override
public void call(List<String> numbers) {
for (String number : numbers) {
if (number.matches("[0-9]*")) {
System.out.println(String.format("Calling... %s", number));
} else {
System.out.println("Invalid number!");
}
}
}
@Override
public void browse(List<String> sites) {
for (String site : sites) {
if (site.matches("[^0-9]*")) {
System.out.println(String.format("Browsing: %s!", site));
} else {
System.out.println("Invalid URL!");
}
}
}
}
| 25.566667 | 75 | 0.521512 |
4c3d27a81088103eacfe8b36092cd8c84729510a | 173 | package org.cloud.ssm.service;
import org.cloud.ssm.entity.Person;
import org.cloud.ssm.utils.BaseService;
public interface PersonService extends BaseService<Person> {
}
| 19.222222 | 60 | 0.803468 |
159b9da5bf19a6cafdca72cc3da965bf1b04bd7d | 1,336 | package org.dfm.piggyurl.domain.port;
import org.dfm.piggyurl.domain.common.UserGroupType;
import org.dfm.piggyurl.domain.model.Group;
import org.dfm.piggyurl.domain.model.User;
import java.util.Optional;
public interface ObtainUser {
default Optional<User> getUserLoginDetail(final String userName, final String password) {
return Optional.empty();
}
default Optional<Group> createGroup(final String groupName, final UserGroupType groupType) {
return Optional.empty();
}
default Optional<Group> getGroupByNameAndType(final String groupName, final UserGroupType groupType) {
return Optional.empty();
}
default Optional<Group> getGroupByIdAndType(final Long groupId, final UserGroupType groupType) {
return Optional.empty();
}
default Optional<Group> getGroupById(final Long groupId) {
return Optional.empty();
}
default Optional<User> createUser(final User userToBeCreated) {
return Optional.empty();
}
default Optional<User> getUserByUserName(final String userName) {
return Optional.empty();
}
default Optional<User> getUserByTribeId(final Long tribeId) {
return Optional.empty();
}
default Optional<User> getUserByFeatureTeamId(final Long tribeId) {
return Optional.empty();
}
}
| 29.688889 | 106 | 0.712575 |
73282e9b643b3a102d4591b2c4a210c141156ab8 | 769 | package io.openlineage.spark3.agent.lifecycle.plan.columnLineage.customVisitors;
import io.openlineage.spark3.agent.lifecycle.plan.columnLineage.ColumnLevelLineageBuilder;
import org.apache.spark.sql.catalyst.plans.logical.LogicalPlan;
/**
* Interface to visit custom {@link LogicalPlan} nodes to collect expression dependencies within the
* plan.
*/
public interface ExpressionDependencyVisitor {
/**
* Verifies if the visitor should be applied on the plan
*
* @param plan
* @return
*/
boolean isDefinedAt(LogicalPlan plan);
/**
* Applies the visitor and adds extracted dependencies to {@link ColumnLevelLineageBuilder}
*
* @param plan
* @param builder
*/
void apply(LogicalPlan plan, ColumnLevelLineageBuilder builder);
}
| 27.464286 | 100 | 0.752926 |
4b35a7148a183e7cb0b2a1c2132d3040385761f1 | 1,936 | package io.agent.agent;
import org.junit.jupiter.api.Test;
import static io.agent.agent.JarFiles.findAgentJarFromCmdline;
import static java.util.Arrays.asList;
import static org.junit.jupiter.api.Assertions.*;
class JarFilesTest {
@Test
void testCmdlineParserWildfly() {
// The command line arguments are taken from the Wildfly application server example.
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.agent.agent",
"-Djava.util.logging.manager=org.jboss.logmanager.LogManager",
"-javaagent:../agent/agent-dist/target/agent.jar=port=9300",
"-Dorg.jboss.boot.log.file=/tmp/wildfly-10.1.0.Final/standalone/log/server.log",
"-Dlogging.configuration=file:/tmp/wildfly-10.1.0.Final/standalone/configuration/logging.properties"
};
assertEquals("../agent/agent-dist/target/agent.jar", findAgentJarFromCmdline(asList(cmdlineArgs)).toString());
}
@Test
void testCmdlineParserVersioned() {
String[] cmdlineArgs = new String[] {
"-javaagent:agent-1.0-SNAPSHOT.jar"
};
assertEquals("agent-1.0-SNAPSHOT.jar", findAgentJarFromCmdline(asList(cmdlineArgs)).toString());
}
@Test()
void testCmdlineParserFailed() {
String[] cmdlineArgs = new String[] {
"-javaagent:/some/other/agent.jar",
"-jar",
"agent.jar"
};
Exception e = assertThrows(Exception.class, () -> findAgentJarFromCmdline(asList(cmdlineArgs)));
// The exception should contain some message indicating agent.jar was not found.
assertTrue(e.getMessage().contains("agent.jar"));
}
}
| 42.086957 | 148 | 0.647211 |
d03470a2d0f55b6a9b34c38fa671fed62bdcb029 | 405 | package csust.imageSearch.orm.dao.impl;
import csust.imageSearch.orm.Picture;
import csust.imageSearch.orm.dao.PictureDao;
public class PictureDaoImpl extends Base implements PictureDao{
@Override
public Picture getPictueByName(String name) {
String hql = "from Picture picture where picture.name = ?";
return (Picture) this.getSession().createQuery(hql).setString(0, name).uniqueResult();
}
}
| 27 | 88 | 0.777778 |
494fbdcfe7b78f84affacf34dd47873c649da504 | 3,224 | /**
* Copyright 2015-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0/
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazon.android.contentbrowser.database;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import android.content.Context;
import android.support.test.InstrumentationRegistry;
import android.support.test.runner.AndroidJUnit4;
import java.io.File;
import java.lang.reflect.Field;
@SuppressWarnings("unchecked")
@RunWith(AndroidJUnit4.class)
/**
* Test class for {@link ContentDatabase}.
*/
public class ContentDatabaseTest {
/**
* Clear out the singleton instance of the database helper so each test has a clean slate.
*/
@Before
public void resetDatabase() throws NoSuchFieldException, IllegalAccessException {
Field instance = ContentDatabase.class.getDeclaredField("sInstance");
instance.setAccessible(true);
instance.set(null, null);
}
/**
* Test getting the content database instance.
*/
@Test
public void testGetInstance() throws Exception {
ContentDatabase contentDatabase = ContentDatabase.getInstance(InstrumentationRegistry
.getContext());
assertNotNull("ContentDatabase should not be null", contentDatabase);
}
/**
* Test getting the SQLite Database instance.
*/
@Test
public void testGetDatabaseInstance() throws Exception {
ContentDatabase contentDatabase = ContentDatabase.getInstance(InstrumentationRegistry
.getContext());
assertNotNull("ContentDatabase should not be null", contentDatabase);
assertNotNull("Database instance should not be null.", contentDatabase
.getDatabaseInstance());
}
/**
* Test deleting the database.
*/
@Test
public void testDeleteDatabase() throws Exception {
Context context = InstrumentationRegistry.getContext();
ContentDatabase contentDatabase = ContentDatabase.getInstance(context);
assertNotNull(contentDatabase);
String databaseFilePath = contentDatabase.getDatabasePath(context);
assertTrue(contentDatabase.deleteDatabase(context));
File databaseFile = new File(databaseFilePath);
assertFalse(databaseFilePath + " should not exist.", databaseFile.exists());
contentDatabase.close();
}
}
| 32.897959 | 94 | 0.664702 |
72ac06468b5d67a1f094afbdbb27963f104196ca | 814 | package cn.router7.mediator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Abstract base class for party members.
*/
public abstract class PartyMemberBase implements PartyMember {
private static final Logger log = LoggerFactory.getLogger(PartyMemberBase.class);
protected Party party;
@Override
public void joinedParty(Party party) {
log.info("{} joins the party", this);
this.party = party;
}
@Override
public void partyAction(Action action) {
log.info("{} {}", this, action.getDescription());
}
@Override
public void act(Action action) {
if (party != null) {
log.info("{} {}", this, action);
party.act(this, action);
}
}
@Override
public abstract String toString();
}
| 21.421053 | 85 | 0.626536 |
e39e6588f9818b1ee6dd67c61a2aa7abcc67ac4e | 1,647 | package com.henry.android.popularmovies;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import com.henry.android.popularmovies.data.MovieContract;
/**
* Created by Henry on 2017/9/14.
*/
public class MovieDbHelper extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "favorite.db";
public MovieDbHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
String SQL_CREATE_FAVORITE_MOVIES_TABLE = "CREATE TABLE " + MovieContract.MovieEntry.TABLE_NAME + " ("
+ MovieContract.MovieEntry._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ MovieContract.MovieEntry.COLUMN_MOVIE_ID + " INTEGER NOT NULL UNIQUE, "
+ MovieContract.MovieEntry.COLUMN_MOVIE_TITLE + " TEXT NOT NULL, "
+ MovieContract.MovieEntry.COLUMN_MOVIE_VOTE + " REAL, "
+ MovieContract.MovieEntry.COLUMN_MOVIE_POSTER + " TEXT, "
+ MovieContract.MovieEntry.COLUMN_MOVIE_TIME + " INTEGER, "
+ MovieContract.MovieEntry.COLUMN_MOVIE_OVERVIEW + " TEXT, "
+ MovieContract.MovieEntry.COLUMN_MOVIE_RELEASE_DATE + " TEXT);";
sqLiteDatabase.execSQL(SQL_CREATE_FAVORITE_MOVIES_TABLE);
}
@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
}
public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
| 34.3125 | 110 | 0.697632 |
3646a44f882763abdfe0ab3277f1a085e2132b38 | 3,684 | /*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gbif.common.parsers.core;
import java.util.Date;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
public class ParseResultTest {
@Test
public void testSuccess() {
// check with basic string payload
assertNotNull(ParseResult.success(ParseResult.CONFIDENCE.DEFINITE, new String("Bingo")));
assertNotNull(ParseResult.success(ParseResult.CONFIDENCE.DEFINITE, new String("Bingo")).getPayload());
assertEquals(String.class,
ParseResult.success(ParseResult.CONFIDENCE.DEFINITE, new String("Bingo")).getPayload().getClass());
assertEquals(ParseResult.CONFIDENCE.DEFINITE,
ParseResult.success(ParseResult.CONFIDENCE.DEFINITE, new String("Bingo")).getConfidence());
assertEquals(ParseResult.STATUS.SUCCESS,
ParseResult.success(ParseResult.CONFIDENCE.DEFINITE, new String("Bingo")).getStatus());
assertNull(ParseResult.success(ParseResult.CONFIDENCE.DEFINITE, new String("Bingo")).getError());
// check generics with Date payload
assertNotNull(ParseResult.success(ParseResult.CONFIDENCE.DEFINITE, new Date()));
assertNotNull(ParseResult.success(ParseResult.CONFIDENCE.DEFINITE, new Date()).getPayload());
assertEquals(Date.class, ParseResult.success(ParseResult.CONFIDENCE.DEFINITE, new Date()).getPayload().getClass());
assertEquals(ParseResult.CONFIDENCE.DEFINITE,
ParseResult.success(ParseResult.CONFIDENCE.DEFINITE, new Date()).getConfidence());
assertEquals(ParseResult.STATUS.SUCCESS,
ParseResult.success(ParseResult.CONFIDENCE.DEFINITE, new Date()).getStatus());
assertNull(ParseResult.success(ParseResult.CONFIDENCE.DEFINITE, new Date()).getError());
}
@Test
public void testFail() {
assertNotNull(ParseResult.fail());
assertEquals(ParseResult.STATUS.FAIL, ParseResult.fail().getStatus());
assertNull(ParseResult.fail().getConfidence());
assertNull(ParseResult.fail().getError());
assertNull(ParseResult.fail().getPayload());
}
@Test
public void testUnknownError() {
assertNotNull(ParseResult.error());
assertEquals(ParseResult.STATUS.ERROR, ParseResult.error().getStatus());
assertNull(ParseResult.error().getConfidence());
assertNull(ParseResult.error().getError());
assertNull(ParseResult.error().getPayload());
}
@Test
public void testError() {
assertNotNull(ParseResult.error(new RuntimeException("Bingo")));
assertEquals(ParseResult.STATUS.ERROR, ParseResult.error(new RuntimeException("Bingo")).getStatus());
assertNull(ParseResult.error(new RuntimeException("Bingo")).getConfidence());
assertNotNull(ParseResult.error(new RuntimeException("Bingo")).getError());
assertEquals(RuntimeException.class, ParseResult.error(new RuntimeException("Bingo")).getError().getClass());
assertEquals("Bingo", ParseResult.error(new RuntimeException("Bingo")).getError().getMessage());
assertNull(ParseResult.error(new RuntimeException("Bingo")).getPayload());
}
}
| 45.481481 | 119 | 0.7538 |
8154decb367e46f50dd7cfddfb3f73028c5c25e1 | 5,632 | package com.radish.master.system;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import com.cnpc.framework.utils.CodeException;
public class GUID {
// 共62个字符 0-9, A-Z, a-z, 支持 0-61的转换
private static final char[] CHARACTER_TABLE = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K',
'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' };
public static final int LEN_16 = 16;
public static final int LEN_20 = 20;
public static final int LEN_25 = 25;
/**
* 生成指定长度流水号, 流水号只包含数字
*
* @param length
* 流水号长度, 支持16,20,25
* @return 指定长度的流水号
* @throws Exception
*/
public static String genTxNo(int length) throws CodeException {
String txNo = null;
switch (length) {
case LEN_16:
txNo = genTxNo(LEN_16, false);
break;
case LEN_20:
txNo = genTxNo(LEN_20, false);
break;
case LEN_25:
txNo = genTxNo(LEN_25, false);
break;
default:
throw new CodeException("", "don't support length[" + length + "]");
}
return txNo;
}
/**
* 生成指定长度流水号, 流水号可包含字母
* <p>
* 当流水号包含字母时, 字母不区分大小写
*
* @param length
* 流水号长度, 支持16,20,25
* @param characterContained
* 流水号是否包含字母: true包含, false不包含
* @return 指定长度的流水号
* @throws Exception
*/
public static String genTxNo(int length, boolean characterContained) throws CodeException {
String txNo = null;
switch (length) {
case LEN_16:
if (characterContained) {
txNo = getTxNo16V2();
} else {
txNo = getTxNo16();
}
break;
case LEN_20:
if (characterContained) {
txNo = getTxNoV2();
} else {
txNo = getTxNo();
}
break;
case LEN_25:
if (characterContained) {
throw new CodeException("", "length [" + length + "] don't support generate txNo with charactes");
} else {
txNo = getTxNo25();
}
break;
default:
throw new CodeException("", "don't support length[" + length + "]");
}
return txNo;
}
/**
* 20位流水号
* <p>
* yyMMddHHmm+Random(10)
*/
public static String getTxNo() {
String timeString = new SimpleDateFormat("yyMMddHHmm").format(Calendar.getInstance().getTime());
return timeString + RandomNumberGenerator.getRandomNumber(10);
}
/**
* 16位流水号
* <p>
* yyMMdd+Random(10)
*/
public static String getTxNo16() {
String timeString = new SimpleDateFormat("yyMMdd").format(Calendar.getInstance().getTime());
return timeString + RandomNumberGenerator.getRandomNumber(10);
}
/**
* 20位流水号
* <p>
* yyyyMMddHHmmss(compressed with 9 digits) + 11 digits or characters(case
* sensitive)
*
* @throws Exception
*/
private static String getTxNoV2() throws CodeException {
String time = new SimpleDateFormat("yyyyMMddHHmmss").format(Calendar.getInstance().getTime());
StringBuilder timeCoverted = new StringBuilder();
// 转换
timeCoverted.append(time.substring(0, 4))
.append(convert(time.substring(4)))
.append(RandomNumberGenerator.getRandomCharAndNumber(11, true));
return timeCoverted.toString();
}
/**
* 25位流水号
* <p>
* yyMMddHHmmssSSS+Random(10)
*/
private static String getTxNo25() {
String timeString = new SimpleDateFormat("yyMMddHHmmssSSS").format(Calendar.getInstance().getTime());
return timeString + RandomNumberGenerator.getRandomNumber(10);
}
/**
* 获取16位的流水号 版本2
* <p>
* yyMMddHHmmss(compressed with 7 digits) + 9 digits or characters(case
* sensitive)
*/
private static String getTxNo16V2() throws CodeException {
String time = new SimpleDateFormat("yyMMddHHmmss").format(Calendar.getInstance().getTime());
StringBuilder timeCoverted = new StringBuilder();
// 转换
timeCoverted.append(time.substring(0, 2))
.append(convert(time.substring(2)))
.append(RandomNumberGenerator.getRandomCharAndNumber(9, true));
return timeCoverted.toString();
}
public static String convert(String time) throws CodeException {
StringBuilder timeConverted = new StringBuilder();
for (int index = 0; index < time.length(); index += 2) {
int num = Integer.parseInt(time.substring(index, index + 2));
timeConverted.append(convertNumber2Character(num));
}
return timeConverted.toString();
}
private static char convertNumber2Character(int num) throws CodeException {
if (num > 61) {
throw new CodeException("", "don't supprot digit larger than 61");
}
return CHARACTER_TABLE[num];
}
}
| 32.554913 | 157 | 0.520064 |
fdf6fc6b8ff90d0ee1a9111d2ca8f5c0ba35c4b4 | 1,750 | package com.github.kjarosh.jfm.impl.mounter.rproxy.generator;
import com.github.kjarosh.jfm.api.FilesystemMapperException;
import com.github.kjarosh.jfm.api.annotations.Content;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.lang.reflect.Type;
/**
* @author Kamil Jarosz
*/
public class ResourceMethodInvoker {
private final Method method;
private Object resource;
private Type contentType;
private int contentPosition;
private Object content;
ResourceMethodInvoker(Method method, Object resource) {
this.method = method;
this.resource = resource;
int position = 0;
for (Parameter parameter : method.getParameters()) {
if (parameter.isAnnotationPresent(Content.class)) {
contentType = parameter.getParameterizedType();
contentPosition = position;
}
++position;
}
}
public Type getContentType() {
return contentType;
}
public Type getReturnType() {
return method.getGenericReturnType();
}
public void setContent(Object content) {
this.content = content;
}
public Object invoke() {
Object[] args = new Object[method.getParameterCount()];
if (content != null) {
args[contentPosition] = content;
}
try {
return method.invoke(resource, args);
} catch (IllegalAccessException e) {
throw new FilesystemMapperException("Cannot access method", e);
} catch (InvocationTargetException e) {
throw new FilesystemMapperException("Method threw an exception", e);
}
}
}
| 27.34375 | 80 | 0.648 |
bf7ea8dadcc09b846ce3e64d06e172de17d377cd | 1,064 | package com.a6raywa1cher.muchelpspring.model;
import com.a6raywa1cher.muchelpspring.utils.Views;
import com.fasterxml.jackson.annotation.JsonIdentityInfo;
import com.fasterxml.jackson.annotation.JsonView;
import com.fasterxml.jackson.annotation.ObjectIdGenerators;
import lombok.Data;
import javax.persistence.*;
import java.util.List;
import java.util.Map;
@Entity
@Data
@JsonIdentityInfo(
generator = ObjectIdGenerators.PropertyGenerator.class,
property = "id")
public class Ticket {
@Id
@GeneratedValue
@JsonView(Views.Public.class)
private Long id;
@OneToOne(mappedBy = "lastTicket")
@JsonView(Views.Public.class)
private User ticketIssuer;
@ElementCollection
@MapKeyClass(User.class)
@Enumerated(value = EnumType.STRING)
@JsonView(Views.Public.class)
private Map<User, TicketStatus> statusMap;
@Column(length = 1024)
@JsonView(Views.Public.class)
private String message;
@ElementCollection
@JsonView(Views.Public.class)
private List<String> attachmentPaths;
@ManyToOne
@JsonView(Views.Public.class)
private Subject subject;
}
| 23.130435 | 59 | 0.793233 |
7fda11b34c46b16f96eacada6a2724dd830fd365 | 1,503 | package com.avaje.ebeaninternal.api;
import java.sql.SQLException;
import com.avaje.ebean.annotation.ConcurrencyMode;
import com.avaje.ebean.bean.EntityBean;
import com.avaje.ebeaninternal.server.persist.dml.DmlHandler;
import com.avaje.ebeaninternal.server.persist.dmlbind.Bindable;
/**
* A plan for executing bean updates for a given set of changed properties.
* <p>
* This is a cachable plan with the purpose of being being able to skip some
* phases of the update bean processing.
* </p>
* <p>
* The plans are cached by the BeanDescriptors.
* </>
*/
public interface SpiUpdatePlan {
/**
* Return true if the set clause has no columns.
* <p>
* Can occur when the only columns updated have a updatable=false in their
* deployment.
* </p>
*/
boolean isEmptySetClause();
/**
* Bind given the request and bean. The bean could be the oldValues bean
* when binding a update or delete where clause with ALL concurrency mode.
*/
void bindSet(DmlHandler bind, EntityBean bean) throws SQLException;
/**
* Return the time this plan was created.
*/
long getTimeCreated();
/**
* Return the time this plan was last used.
*/
Long getTimeLastUsed();
/**
* Return the hash key for this plan.
*/
Integer getKey();
/**
* Return the concurrency mode for this plan.
*/
ConcurrencyMode getMode();
/**
* Return the update SQL statement.
*/
String getSql();
/**
* Return the set of bindable update properties.
*/
Bindable getSet();
} | 22.432836 | 76 | 0.697272 |
d976b1e92be4d716107b3d4757e60b963f158c4e | 11,308 | package uk.ac.ebi.fgpt.urigen;
import junit.framework.TestCase;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.SingleConnectionDataSource;
import uk.ac.ebi.fgpt.urigen.dao.*;
import uk.ac.ebi.fgpt.urigen.exception.PreferenceCreationException;
import uk.ac.ebi.fgpt.urigen.exception.UrigenException;
import uk.ac.ebi.fgpt.urigen.exception.UserCreateException;
import uk.ac.ebi.fgpt.urigen.impl.*;
import uk.ac.ebi.fgpt.urigen.model.UrigenManager;
import uk.ac.ebi.fgpt.urigen.model.UrigenPreference;
import uk.ac.ebi.fgpt.urigen.model.UrigenRequest;
import uk.ac.ebi.fgpt.urigen.model.UrigenUser;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
/**
* @author Simon Jupp
* @date 02/03/2012
* Functional Genomics Group EMBL-EBI
*/
public class UrigenManagerJDBCTest extends TestCase {
private final JDBCUserDAO uDao = new JDBCUserDAO();
private final JDBCPreferencesDAO pDao = new JDBCPreferencesDAO();
private final JDBCUrigenEntityDAO eDao = new JDBCUrigenEntityDAO();
private UrigenManager uriGenManager;
private Connection connection;
private final Logger log = LoggerFactory.getLogger(getClass());
@Override
protected void setUp() throws Exception {
try {
// load driver
Class.forName("org.hsqldb.jdbc.JDBCDriver");
// get connection and create table
connection = DriverManager.getConnection("jdbc:hsqldb:file:target/hsql/urigen_test;hsqldb.write_delay=false");
rebuildDatabases();
for (String id : GeneratorTypes.ALL_TYPES_ID) {
log.debug("populating generator types table with id : " +id);
PreparedStatement p = connection.prepareStatement("insert into ID_GENERATOR_TYPE (class_name) values(?)");
p.setString(1, id);
p.execute();
}
SingleConnectionDataSource ds = new SingleConnectionDataSource(connection, true);
uDao.setJdbcTemplate(new JdbcTemplate(ds));
pDao.setJdbcTemplate(new JdbcTemplate(ds));
eDao.setJdbcTemplate(new JdbcTemplate(ds));
uriGenManager = new UrigenManagerImpl(pDao, eDao, uDao, new OWLAPIOntologyDAO());
}
catch (Exception e) {
e.printStackTrace();
tearDown();
fail();
}
}
public void testLoadUser() {
UrigenUser adminUser =new SimpleUrigenUserImpl("admin", "admin@test", "12345", true);
UrigenUser regularUser =new SimpleUrigenUserImpl("test", "test@test", "54321", false);
assertEquals(uriGenManager.getUsers().size(), 0);
try {
assertEquals(uriGenManager.saveUser(adminUser).getId(), 0);
} catch (UserCreateException e) {
rebuildDatabases();
fail();
}
try {
assertEquals(uriGenManager.saveUser(regularUser).getId(), 1);
} catch (UserCreateException e) {
rebuildDatabases();
fail();
}
assertEquals(uriGenManager.getUsers().size(), 2);
}
public void testLoadPrefs() {
UrigenUser adminUser =new SimpleUrigenUserImpl("admin", "admin@test", "12345", true);
UrigenUser regularUser =new SimpleUrigenUserImpl("test", "test@test", "54321", false);
assertEquals(uriGenManager.getUsers().size(), 0);
try {
assertEquals(uriGenManager.saveUser(adminUser).getId(), 0);
} catch (UserCreateException e) {
rebuildDatabases();
fail();
}
try {
assertEquals(uriGenManager.saveUser(regularUser).getId(), 1);
} catch (UserCreateException e) {
rebuildDatabases();
fail();
}
assertEquals(uriGenManager.getUsers().size(), 2);
UrigenPreference pref1 = new SimpleUrigenPreferencesImpl(
"test-onto-1",
"http://www.uri-manager/test-1.owl",
"http://www.uri-manager/test-1.owl",
"../rescources/test-1.owl",
"/",
GeneratorTypes.ITERATIVE.getClassId(),
"TEST1_",
"",
6,
0,
-1,
true
);
try {
log.debug("saving pref 1");
pref1 = uriGenManager.savePreference(pref1);
assertEquals((pref1.getPreferenceId()), 0);
} catch (PreferenceCreationException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
UrigenPreference pref2 = new SimpleUrigenPreferencesImpl(
"test-onto-2",
"http://www.uri-manager/test-2.owl",
"http://www.uri-manager/test-2.owl",
"../rescources/test-2.owl",
"#",
GeneratorTypes.ITERATIVE.getClassId(),
"TEST2_",
"",
6,
0,
-1,
true
);
try {
log.debug("saving pref 2");
pref2 = uriGenManager.savePreference(pref2);
assertEquals((pref2.getPreferenceId()), 1);
} catch (PreferenceCreationException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
UrigenPreference pref3 = new SimpleUrigenPreferencesImpl(
"test-onto-3",
"http://www.uri-manager/test-3.owl",
"http://www.uri-manager/test-3.owl",
"../rescources/test-3.owl",
":",
GeneratorTypes.ITERATIVE.getClassId(),
"TEST3_",
"",
6,
0,
-1,
true
);
try {
log.debug("saving pref 3");
pref3 = uriGenManager.savePreference(pref3);
assertEquals((pref3.getPreferenceId()), 2);
} catch (PreferenceCreationException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
UrigenPreference pref4 = new SimpleUrigenPreferencesImpl(
"test-onto-4",
"http://www.uri-manager/test-4.owl",
"http://www.uri-manager/test-4.owl",
"../rescources/test-4.owl",
":",
GeneratorTypes.PSEUDO_RANDOM.getClassId(),
"TEST4_",
"_PSEUDO_RANDOM",
6,
-1,
-1,
true);
try {
log.debug("saving pref 4");
pref4 = uriGenManager.savePreference(pref4);
assertEquals((pref4.getPreferenceId()), 3);
} catch (PreferenceCreationException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
UrigenPreference pref5 = new SimpleUrigenPreferencesImpl(
"test-onto-5",
"http://www.uri-manager/test-5.owl",
"http://www.uri-manager/test-5.owl",
"../rescources/test-5.owl",
":",
GeneratorTypes.RANDOM.getClassId(),
"TEST5_",
"_RANDOM",
10,
-1,
-1,
true
);
try {
log.debug("saving pref 5");
pref5 = uriGenManager.savePreference(pref5);
assertEquals((pref5.getPreferenceId()), 4);
} catch (PreferenceCreationException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
UrigenPreference pref6 = new SimpleUrigenPreferencesImpl(
"test-onto-6",
"http://www.uri-manager/test-6.owl",
"http://www.uri-manager/test-6.owl",
"../rescources/test-6.owl",
":",
GeneratorTypes.ITERATIVE_RANGE.getClassId(),
"TEST_6_",
"_RANGE",
8,
-1,
-1,
true
);
try {
log.debug("saving pref 6");
pref6 = uriGenManager.savePreference(pref6);
assertEquals((pref6.getPreferenceId()), 5);
} catch (PreferenceCreationException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
pref6.getAllUserRange().add(new UrigenUserRangeImpl(uriGenManager.getUserByUserName("admin").getId(),pref6.getPreferenceId(), 400, 700));
log.debug("added new user range to pref 6: " + pref6.getPreferenceId());
try {
uriGenManager.updatePreference(pref6);
} catch (PreferenceCreationException e) {
rebuildDatabases();
fail();
}
assertEquals(uriGenManager.getUsers().size(), 2);
assertEquals(uriGenManager.getPreferences().size(), 6);
log.info("generating URIS...");
for (UrigenUser u : uriGenManager.getUsers()) {
for (UrigenPreference p : uriGenManager.getPreferences()) {
UrigenRequest request1 = new SimpleUrigenRequestImpl(u.getId(), "", p.getPreferenceId(), "", "");
try {
System.out.println(p.toString());
for (int x = 0; x <100; x++) {
uriGenManager.getNewEntity(request1);
}
} catch (UrigenException e) {
if (!e.getLocalizedMessage().equals("No user range associated with this preference")) {
fail(e.getMessage());
}
}
}
}
}
public void testGenerateUris() {
}
public void rebuildDatabases () {
try {
connection.prepareStatement("drop table if exists URI;").execute();
connection.prepareStatement("drop table if exists USER_RANGE;").execute();
connection.prepareStatement("drop table if exists PREFERENCE;").execute();
connection.prepareStatement("drop table if exists ID_GENERATOR_TYPE;").execute();
connection.prepareStatement("drop table if exists USER;").execute();
connection.prepareStatement(HSQLDBInitializer.USER).execute();
connection.prepareStatement(HSQLDBInitializer.ID_GENERATOR_TYPE).execute();
connection.prepareStatement(HSQLDBInitializer.ONTOLOGY_PREFS).execute();
connection.prepareStatement(HSQLDBInitializer.ONTOLOGY_RANGES).execute();
connection.prepareStatement(HSQLDBInitializer.GENERATED_URI).execute();
} catch (SQLException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
}
@Override
protected void tearDown() throws Exception {
rebuildDatabases();
}
}
| 33.064327 | 145 | 0.562434 |
990224b38456993b04f75237577dbc9a47c268d3 | 1,451 | package com.yasinbee.libman.hex.domain.email.infrastructure;
import com.sendgrid.Method;
import com.sendgrid.Request;
import com.sendgrid.SendGrid;
import com.sendgrid.helpers.mail.Mail;
import com.sendgrid.helpers.mail.objects.Content;
import com.sendgrid.helpers.mail.objects.Email;
import com.yasinbee.libman.hex.domain.email.core.model.ReservationConfirmEmail;
import com.yasinbee.libman.hex.domain.email.core.ports.outgoing.EmailSender;
import java.io.IOException;
public class SendGridEmailSender implements EmailSender {
@Override
public void sendReservationConfirmationEmail(ReservationConfirmEmail reservationConfirmEmail) {
Email from = new Email(reservationConfirmEmail.getFromEmailAddressAsString());
Email to = new Email(reservationConfirmEmail.getToEmailAddressAsString());
Content content = new Content("text/plain", reservationConfirmEmail.getContentAsString());
Mail mail = new Mail(
from,
reservationConfirmEmail.getSubjectAsString(),
to,
content);
SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY"));
Request request = new Request();
try {
request.setMethod(Method.POST);
request.setEndpoint("mail/send");
request.setBody(mail.build());
sg.api(request);
} catch (IOException ex) {
System.out.print(ex);
}
}
}
| 37.205128 | 99 | 0.69745 |
b6e3e44a63698e1e59c7e9f1fd6b675ed50e09b3 | 6,817 | package com.dev.bins.hexagonlayoutmanager;
import android.graphics.Rect;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import java.util.ArrayList;
import java.util.List;
/**
* Created by bin on 24/11/2016.
*/
public class HexagonLayoutManager extends RecyclerView.LayoutManager {
private List<List<Rect>> rects = new ArrayList<>();
private List<Rect> rectList = new ArrayList<>();
private int length = 0;
@Override
public RecyclerView.LayoutParams generateDefaultLayoutParams() {
return new RecyclerView.LayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
}
@Override
public void onLayoutChildren(RecyclerView.Recycler recycler, RecyclerView.State state) {
// rects.clear();
// rectList.clear();
int itemCount = state.getItemCount();
if (itemCount == 0) return;
detachAndScrapAttachedViews(recycler);//解绑所有view
// initCenter(recycler);
// generateRects(itemCount);
// for (int i = 0; i < itemCount; i++) {
// View view = recycler.getViewForPosition(i);
// measureChildWithMargins(view, 0, 0);
// addView(view);
// Rect rect = rectList.get(i);
// layoutDecoratedWithMargins(view, rect.left, rect.top, rect.right, rect.bottom);
// }
for (int i = 0; i < itemCount; i++) {
if (i >= rectList.size()) {//判断对应索引的位置有没有确定,没有确定则进行计算
generateRectsOfFloor(getFloorByPosition(i), recycler);
}
// 布局
View view = recycler.getViewForPosition(i);
measureChildWithMargins(view, 0, 0);
addView(view);
Rect rect = rectList.get(i);
layoutDecoratedWithMargins(view, rect.left, rect.top, rect.right, rect.bottom);
}
}
/**
* 产生对应层的位置
* @param floor
* @param recycler
*/
private void generateRectsOfFloor(int floor, RecyclerView.Recycler recycler) {
if (floor == 0) {
initCenter(recycler);
return;
}
// 第一层特殊处理
if (floor == 1) {
Rect zeroRect = rectList.get(0);
for (int j = 0; j < 6; j++) {
int x = (int) (length * Math.cos(j * Math.PI / 3));
int y = (int) (length * Math.sin(j * Math.PI / 3));
Rect rect = new Rect(zeroRect);
rect.offset(x, y);
rectList.add(rect);
}
return;
}
int startPosition = getFloorStartPosition(floor - 1);
int count = getFloorCount(floor - 1);
for (int i = 0; i < count; i++) {
Rect rect = rectList.get(startPosition + i);
if ((i % (floor - 1)) == 0) {
getListRect(i, floor - 1, rect);
} else {
int x = (int) (length * Math.cos((((i / (floor - 1) + 1) % 6) * Math.PI / 3)));
int y = (int) (length * Math.sin((((i / (floor - 1) + 1) % 6) * Math.PI / 3)));
rect.offset(x, y);
rectList.add(rect);
}
}
}
private void generateRects(int itemCount) {
int floor = getFloorByPosition(itemCount - 1);
for (int i = 1; i <= floor; i++) {
getFloorRectList(i - 1);
}
}
private void getFloorRectList(int floor) {
List<Rect> floorList = new ArrayList<>();
if (floor == 0) {
Rect zeroRect = rects.get(0).get(0);
for (int j = 0; j < 6; j++) {
// int height = zeroRect.height();
// int len = height / 2;
int x = (int) (length * Math.cos(j * Math.PI / 3));
int y = (int) (length * Math.sin(j * Math.PI / 3));
Rect rect = new Rect(zeroRect);
rect.offset(x, y);
floorList.add(rect);
rectList.add(rect);
}
} else {
List<Rect> lastRect = this.rects.get(floor);
int size = lastRect.size();
for (int j = 0; j < size; j++) {
if (j % floor == 0) {
floorList.addAll(getListRect(j, floor, lastRect.get(j)));
} else {
Rect rect = new Rect(lastRect.get(j));
int x = (int) (length * Math.cos((((j / floor + 1) % 6) * Math.PI / 3)));
int y = (int) (length * Math.sin((((j / floor + 1) % 6) * Math.PI / 3)));
rect.offset(x, y);
floorList.add(rect);
rectList.add(rect);
}
}
}
rects.add(floorList);
}
private List<Rect> getListRect(int index, int floor, Rect lastRect) {
List<Rect> list = new ArrayList<>();
for (int i = 0; i < 2; i++) {
Rect rect = new Rect(lastRect);
int x = (int) (length * Math.cos((((index / floor + i) % 6) * Math.PI / 3)));
int y = (int) (length * Math.sin((((index / floor + i) % 6) * Math.PI / 3)));
rect.offset(x, y);
list.add(rect);
rectList.add(rect);
}
return list;
}
/**
* 获得对应层的第一个索引
* @param floor
* @return
*/
public int getFloorStartPosition(int floor) {
int pos = 0;
for (int i = 0; i < floor; i++) {
pos += i * 6;
}
return pos + 1;
}
/**
* 根据索引得到处于第几层
* @param index 索引
* @return
*/
public int getFloorByPosition(int index) {
if (index == 0) return 0;
int floor = 0;
index -= 1;
do {
floor++;
index -= getFloorCount(floor);
} while (index >= 0);
return floor;
}
/**
* 对应层六边形的个数
* @param floor
* @return
*/
public int getFloorCount(int floor) {
if (floor == 0) return 1;
return floor * 6;
}
/**
* 最中间的,索引为0
* @param recycler
*/
private void initCenter(RecyclerView.Recycler recycler) {
View view = recycler.getViewForPosition(0);
//addView(view);
measureChildWithMargins(view, 0, 0);
int w = view.getMeasuredWidth();
int h = view.getMeasuredHeight();
int width = getWidth();
int height = getHeight();
length = (int) (Math.sqrt(3) * w / 2);
Rect rect = new Rect(width / 2 - w / 2, height / 2 - h / 2, width / 2 + h / 2, height / 2 + h / 2);
layoutDecoratedWithMargins(view, rect.left, rect.top, rect.right, rect.bottom);
List<Rect> first = new ArrayList<>();
first.add(rect);
rects.add(first);
rectList.add(rect);
}
}
| 30.986364 | 147 | 0.50242 |
92a99a1203a9fe64a0603a77542f3489b1231704 | 4,478 | /*
* Licensed to the Hipparchus project under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The Hipparchus project licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.hipparchus.linear;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import java.text.DecimalFormat;
import org.junit.Test;
public class OrderedEigenDecompositionTest {
static private final RealMatrixFormat f =
new RealMatrixFormat("", "", "\n", "", "", "\t\t",
new DecimalFormat(" ##############0.0000;-##############0.0000"));
/**
*
*/
@Test
public void testOrdEigenDecomposition_Real() {
// AA = [1 2;1 -3];
RealMatrix A = MatrixUtils.createRealMatrix(new double[][] {
{ 1, 2 }, { 1, -3 }
});
OrderedEigenDecomposition ordEig = new OrderedEigenDecomposition(A);
assertNotNull(ordEig.getD());
assertNotNull(ordEig.getV());
RealMatrix D_expected = MatrixUtils.createRealMatrix(new double[][] {
{ -3.4495, 0 }, { 0, 1.4495 }
});
RealMatrix V_expected = MatrixUtils.createRealMatrix(new double[][] {
{ -0.4184, 0.9757 }, { 0.9309, 0.2193 }
});
assertEquals(f.format(D_expected), f.format(ordEig.getD()));
assertEquals(f.format(V_expected), f.format(ordEig.getV()));
// checking definition of the decomposition A = V*D*inv(V)
assertEquals(f.format(A),
f.format(ordEig.getV().multiply(ordEig.getD()).multiply(MatrixUtils.inverse(ordEig.getV())).scalarAdd(0)));
}
/**
*
*/
@Test
public void testOrdEigenDecomposition_Imaginary() {
// AA = [3 -2;4 -1];
RealMatrix A = MatrixUtils.createRealMatrix(new double[][] {
{ 3, -2 }, { 4, -1 }
});
OrderedEigenDecomposition ordEig = new OrderedEigenDecomposition(A);
assertNotNull(ordEig.getD());
assertNotNull(ordEig.getV());
RealMatrix D_expected = MatrixUtils.createRealMatrix(new double[][] {
{ 1, 2 }, { -2, 1 }
});
RealMatrix V_expected = MatrixUtils.createRealMatrix(new double[][] {
{ -0.5, 0.5 }, { 0, 1 }
});
assertEquals(f.format(D_expected), f.format(ordEig.getD()));
assertEquals(f.format(V_expected), f.format(ordEig.getV()));
// checking definition of the decomposition A = V*D*inv(V)
assertEquals(f.format(A),
f.format(ordEig.getV().multiply(ordEig.getD()).multiply(MatrixUtils.inverse(ordEig.getV())).scalarAdd(0)));
}
/**
*
*/
@Test
public void testOrdEigenDecomposition_Imaginary_33() {
// AA = [3 -2 0;4 -1 0;1 1 1];
RealMatrix A = MatrixUtils.createRealMatrix(new double[][] {
{ 3, -2, 0 }, { 4, -1, 0 }, { 3, -2, 0 }
});
OrderedEigenDecomposition ordEig = new OrderedEigenDecomposition(A);
assertNotNull(ordEig.getD());
assertNotNull(ordEig.getV());
RealMatrix D_expected = MatrixUtils.createRealMatrix(new double[][] {
{ 0, 0, 0 }, { 0, 1, 2 }, { 0, -2, 1 }
});
RealMatrix V_expected = MatrixUtils.createRealMatrix(new double[][] {
{ -0.00001, -0.4690, -0.9381 }, { -0.0, -1.4071, -0.4690 },
{ 1.4142, -0.4690, -0.9381 }
});
assertEquals(f.format(D_expected), f.format(ordEig.getD()));
assertEquals(f.format(V_expected), f.format(ordEig.getV()));
// checking definition of the decomposition A = V*D*inv(V)
assertEquals(A.subtract(ordEig.getV().multiply(ordEig.getD()).multiply(MatrixUtils.inverse(ordEig.getV()))).getFrobeniusNorm(),
0,
1E-10);
}
}
| 34.183206 | 135 | 0.596025 |
e8ff15b897fc771fe977a366a8bd133f0aa53f95 | 946 | package kr.co.gardener.admin.model.user.list;
import kr.co.gardener.admin.model.user.User;
import kr.co.gardener.util.CommonList;
public class UserList extends CommonList<User> {
public UserList() {
super("유저 관리");
this.addTh("UserID","userId","none");
this.addTh("닉네임","userNick","text");
this.addTh("비밀번호","userPass","pass");
this.addTh("생년월일","userBirth","date");
this.addTh("성별","userGender","combo",0);
this.addTh("상태ID","stateId","combo",1);
this.addTh("숲ID","forestId","combo",2);
this.addTh("식물ID","plantId","combo",3);
this.addInsert("UserID","userId","text");
this.addInsert("닉네임","userNick","text");
this.addInsert("비밀번호","userPass","pass");
this.addInsert("생년월일","userBirth","date");
this.addInsert("성별","userGender","combo",0);
this.addInsert("상태ID","stateId","combo",1);
this.addInsert("숲ID","forestId","combo",2);
this.addInsert("식물ID","plantId","combo",3);
setView(true);
}
}
| 27.028571 | 48 | 0.656448 |
1b50f7d8b6878218c1ef37c4d1b2d7f4d48ab215 | 634 | package com.imooc.mall.dao;
import com.imooc.mall.pojo.OrderItem;
import org.springframework.data.repository.query.Param;
import java.util.List;
import java.util.Set;
public interface OrderItemMapper {
int deleteByPrimaryKey(Integer id);
int insert(OrderItem record);
int insertSelective(OrderItem record);
OrderItem selectByPrimaryKey(Integer id);
int updateByPrimaryKeySelective(OrderItem record);
int updateByPrimaryKey(OrderItem record);
int batchInsert(@Param("orderItemList") List<OrderItem> orderItemList);
List<OrderItem> selectByOrderNo (@Param("orderNoSet") Set<Long> orderNoSet);
} | 25.36 | 80 | 0.769716 |
c71c95f4822beee1ca6249277d21a400e86033da | 598 | package com.pega.gsea.util;
public class Counter {
String id;
double cnt;
public Counter(String id, double cnt) {
super();
this.id = id;
this.cnt = cnt;
}
public Counter(String id) {
super();
this.id = id;
this.cnt = 0;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public double getCnt() {
return cnt;
}
public void setCnt(double cnt) {
this.cnt = cnt;
}
public void incCnt() {
this.cnt++;
}
}
| 14.238095 | 43 | 0.489967 |
4ed134dab40c54d1b78783b1caae6b209c2ee321 | 7,753 | package us.ihmc.robotics.geometry;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.plot.XYPlot;
import org.jfree.chart.renderer.xy.XYItemRenderer;
import org.jfree.data.xy.XYDataset;
import org.jfree.data.xy.XYSeries;
import org.jfree.data.xy.XYSeriesCollection;
import org.jfree.util.ShapeUtilities;
import org.junit.Test;
import us.ihmc.tools.continuousIntegration.ContinuousIntegrationAnnotations.ContinuousIntegrationTest;
import javax.swing.*;
import javax.vecmath.Point2d;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import static org.junit.Assert.assertTrue;
public class InPlaceConvexHullCalculator2dTest
{
private static final boolean DEBUG = true;
Random rand = new Random(100l);
@ContinuousIntegrationTest(estimatedDuration = 2.6)
@Test(timeout = 30000)
public void testRandomV1()
{
int iterations = 5000;
ArrayList<Point2d> points = new ArrayList<Point2d>();
ArrayList<Point2d> inPlaceHull = new ArrayList<Point2d>();
long optClock = 0;
long inPlaceClock = 0;
for (; iterations > 0; iterations--)
{
points.clear();
inPlaceHull.clear();
for (int i = 0; i < 150; i++)
{
double x = rand.nextDouble();
double y = rand.nextDouble();
points.add(new Point2d(x, y));
inPlaceHull.add(new Point2d(x, y));
}
optClock -= System.nanoTime();
List<Point2d> hull = ConvexHullCalculator2d.getConvexHullCopy(points);
optClock += System.nanoTime();
inPlaceClock -= System.nanoTime();
InPlaceConvexHullCalculator2d.inPlaceGiftWrapConvexHull2d(inPlaceHull);
inPlaceClock += System.nanoTime();
boolean sizesMatch = hull.size() == inPlaceHull.size();
boolean convexAndClockwise1 = ConvexHullCalculator2d.isConvexAndClockwise(inPlaceHull);
boolean convexAndClockwise2 = InPlaceConvexHullCalculator2d.isConvexAndClockwise(inPlaceHull);
if (!sizesMatch || !convexAndClockwise1 || !convexAndClockwise2)
printForDebug(points, inPlaceHull.size(), hull, iterations);
assertTrue(sizesMatch);
assertTrue(convexAndClockwise1);
assertTrue(convexAndClockwise2);
//assertTrue(hull.size() == inPlaceHull.size());
}
System.out.println(optClock / 1000000 + " " + inPlaceClock / 1000000);
}
@ContinuousIntegrationTest(estimatedDuration = 2.1)
@Test(timeout = 30000)
public void testRandomV2()
{
int iterations = 5000;
ArrayList<Point2d> points = new ArrayList<Point2d>();
ArrayList<Point2d> inPlaceHull = new ArrayList<Point2d>();
long optClock = 0;
long inPlaceClock = 0;
for (; iterations > 0; iterations--)
{
points.clear();
inPlaceHull.clear();
for (int i = 0; i < 150; i++)
{
double x = rand.nextDouble();
double y = rand.nextDouble();
points.add(new Point2d(x, y));
inPlaceHull.add(new Point2d(x, y));
}
optClock -= System.nanoTime();
List<Point2d> hull = ConvexHullCalculator2d.getConvexHullCopy(points);
optClock += System.nanoTime();
inPlaceClock -= System.nanoTime();
int originalSize = inPlaceHull.size();
int inPlaceHullNewSize = InPlaceConvexHullCalculator2d.inPlaceGiftWrapConvexHull2d(inPlaceHull, originalSize);
inPlaceClock += System.nanoTime();
boolean sizesMatch = hull.size() == inPlaceHullNewSize;
boolean convexAndClockwise1 = ConvexHullCalculator2d.isConvexAndClockwise(inPlaceHull, inPlaceHullNewSize);
boolean convexAndClockwise2 = InPlaceConvexHullCalculator2d.isConvexAndClockwise(inPlaceHull, inPlaceHullNewSize);
if (!sizesMatch || !convexAndClockwise1 || !convexAndClockwise2)
printForDebug(inPlaceHull, inPlaceHullNewSize, hull, iterations);
assertTrue(sizesMatch);
assertTrue(convexAndClockwise1);
assertTrue(convexAndClockwise2);
//assertTrue(hull.size() == inPlaceHull.size());
}
System.out.println(optClock / 1000000 + " " + inPlaceClock / 1000000);
}
private void printForDebug(ArrayList<Point2d> points, int newSize, List<Point2d> hull, int iterations)
{
if (DEBUG)
{
System.out.println("Iteration: " + iterations);
int maxSize = Math.max(hull.size(), newSize);
for (int i = 0; i < maxSize; i++)
{
String hullPoint = i >= hull.size() ? "null" : hull.get(i).toString();
String pointsString = i >= newSize ? "null" : points.get(i).toString();
System.out.println("NewStuff: " + pointsString + ", Hull: " + hullPoint);
}
System.out.println();
plot(points);
plot(hull);
}
}
public static void plot(List<Point2d> points)
{
double[][] data = new double[2][points.size()];
for (int i = 0; i < points.size(); i++)
{
data[0][i] = points.get(i).getX();
data[1][i] = points.get(i).getY();
}
JFreeChart jfreechart = ChartFactory
.createScatterPlot("Scatter Plot Demo", "X", "Y", sampleFromData(data), PlotOrientation.VERTICAL, true, true, false);
XYPlot xyPlot = (XYPlot) jfreechart.getPlot();
xyPlot.setDomainCrosshairVisible(true);
xyPlot.setRangeCrosshairVisible(true);
XYItemRenderer renderer = xyPlot.getRenderer();
renderer.setSeriesShape(0, ShapeUtilities.createDiagonalCross(3, 1));
JFrame jf = new JFrame();
jf.setContentPane(new ChartPanel(jfreechart));
jf.setVisible(true);
}
private static XYDataset sampleFromData(double[][] data)
{
XYSeriesCollection xySeriesCollection = new XYSeriesCollection();
XYSeries series = new XYSeries("Random");
for (int i = 0; i < data[0].length; i++)
{
series.add(data[0][i], data[1][i]);
}
xySeriesCollection.addSeries(series);
return xySeriesCollection;
}
@ContinuousIntegrationTest(estimatedDuration = 0.0)
@Test(timeout = 30000)
public void testConvexCounterclockwise()
{
ArrayList<Point2d> points = new ArrayList<Point2d>();
points.add(new Point2d(-1, -1));
points.add(new Point2d(1, -1));
points.add(new Point2d(1, 1));
points.add(new Point2d(-1, 1));
List<Point2d> hull = ConvexHullCalculator2d.getConvexHullCopy(points);
int originalSize = points.size();
int newSize = InPlaceConvexHullCalculator2d.inPlaceGiftWrapConvexHull2d(points, originalSize);
assertTrue(hull.size() == newSize);
assertTrue(ConvexHullCalculator2d.isConvexAndClockwise(points, newSize));
}
@ContinuousIntegrationTest(estimatedDuration = 0.0)
@Test(timeout = 30000)
public void testFirstPointSelection()
{
ArrayList<Point2d> points = new ArrayList<Point2d>();
points.add(new Point2d(1, -1));
points.add(new Point2d(-1, -1));
points.add(new Point2d(1, 1));
points.add(new Point2d(-1, 1));
List<Point2d> hull = ConvexHullCalculator2d.getConvexHullCopy(points);
int originalSize = points.size();
int newSize = InPlaceConvexHullCalculator2d.inPlaceGiftWrapConvexHull2d(points, originalSize);
assertTrue(hull.size() == originalSize);
assertTrue(ConvexHullCalculator2d.isConvexAndClockwise(points, newSize));
}
public static void main(String[] args)
{
InPlaceConvexHullCalculator2dTest test = new InPlaceConvexHullCalculator2dTest();
test.testRandomV1();
}
}
| 35.56422 | 129 | 0.659487 |
1b9f3ad13fef9a34a3c2419312afceecfa875559 | 13,144 | package com.example.saurab.abc.util;
import android.os.Environment;
import com.example.saurab.abc.vo.HttpResponseVO;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.net.HttpURLConnection;
/**
* Created by saurab on 2/6/2016.
*/
public final class HttpUtil {
public static void get(String url, Map<String, String> headers,
HttpResponseVO responseVo) throws IOException {
try {
DefaultHttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet(url);
Set<String> keySet = headers.keySet();
for (String key : keySet) {
get.addHeader(key, headers.get(key));
}
HttpResponse response = client.execute(get);
HttpEntity entity = response.getEntity();
responseVo
.setResponseCode(response.getStatusLine().getStatusCode());
InputStream inputStream = entity.getContent();
ByteArrayOutputStream content = new ByteArrayOutputStream();
// Read response into a buffered stream
int readBytes = 0;
byte[] sBuffer = new byte[512];
while ((readBytes = inputStream.read(sBuffer)) != -1) {
content.write(sBuffer, 0, readBytes);
}
responseVo.setResponse(new String(content.toByteArray()));
} catch (IOException e) {
responseVo.setError(e.getMessage());
}
}
public static void post(String url, final byte[] data,
Map<String, String> headers, HttpResponseVO responseVo)
throws IOException {
HttpPost post = new HttpPost(url);
Set<String> keySet = headers.keySet();
for (String key : keySet) {
post.addHeader(key, headers.get(key));
}
post.setEntity(new HttpEntity() {
@Override
public void writeTo(OutputStream outstream) throws IOException {
outstream.write(data);
}
@Override
public boolean isStreaming() {
return false;
}
@Override
public boolean isRepeatable() {
return false;
}
@Override
public boolean isChunked() {
return false;
}
@Override
public Header getContentType() {
return new BasicHeader(Constants.HTTP_HEADER_CONTENT_TYPE,
"application/x-www-form-urlencoded");
}
@Override
public long getContentLength() {
return data.length;
}
@Override
public Header getContentEncoding() {
return null;
}
@Override
public InputStream getContent() throws IOException,
IllegalStateException {
InputStream is = new ByteArrayInputStream(data, 0, data.length);
return is;
}
@Override
public void consumeContent() throws IOException {
}
});
DefaultHttpClient client = new DefaultHttpClient();
HttpResponse response = client.execute(post);
HttpEntity entity = response.getEntity();
InputStream inputStream = entity.getContent();
ByteArrayOutputStream content = new ByteArrayOutputStream();
responseVo.setResponseCode(response.getStatusLine().getStatusCode());
// Read response into a buffered stream
int readBytes = 0;
byte[] sBuffer = new byte[512];
while ((readBytes = inputStream.read(sBuffer)) != -1) {
content.write(sBuffer, 0, readBytes);
}
responseVo.setResponse(new String(content.toByteArray()));
}
public static void delete(String url, Map<String, String> headers,
HttpResponseVO responseVo) throws IOException {
DefaultHttpClient client = new DefaultHttpClient();
HttpDelete delete = new HttpDelete(url);
Set<String> keySet = headers.keySet();
for (String key : keySet) {
delete.addHeader(key, headers.get(key));
}
HttpResponse response = client.execute(delete);
responseVo.setResponseCode(response.getStatusLine().getStatusCode());
}
public static void put(String url, final byte[] data,
Map<String, String> headers, HttpResponseVO responseVo)
throws IOException {
HttpPut post = new HttpPut(url);
Set<String> keySet = headers.keySet();
for (String key : keySet) {
post.addHeader(key, headers.get(key));
}
post.setEntity(new HttpEntity() {
@Override
public void writeTo(OutputStream outstream) throws IOException {
outstream.write(data);
}
@Override
public boolean isStreaming() {
return false;
}
@Override
public boolean isRepeatable() {
return false;
}
@Override
public boolean isChunked() {
return false;
}
@Override
public Header getContentType() {
return new BasicHeader(Constants.HTTP_HEADER_CONTENT_TYPE,
Constants.HTTP_HEADER_ACCEPT_VAUE_JSON);
}
@Override
public long getContentLength() {
return data.length;
}
@Override
public Header getContentEncoding() {
return null;
}
@Override
public InputStream getContent() throws IOException,
IllegalStateException {
InputStream is = new ByteArrayInputStream(data, 0, data.length);
return is;
}
@Override
public void consumeContent() throws IOException {
}
});
DefaultHttpClient client = new DefaultHttpClient();
HttpResponse response = client.execute(post);
HttpEntity entity = response.getEntity();
InputStream inputStream = entity.getContent();
ByteArrayOutputStream content = new ByteArrayOutputStream();
responseVo.setResponseCode(response.getStatusLine().getStatusCode());
// Read response into a buffered stream
int readBytes = 0;
byte[] sBuffer = new byte[512];
while ((readBytes = inputStream.read(sBuffer)) != -1) {
content.write(sBuffer, 0, readBytes);
}
responseVo.setResponse(new String(content.toByteArray()));
}
public static HttpResponseVO getPostResponse(String url,
final String data) throws IOException {
HttpResponseVO responseVo = new HttpResponseVO();
HttpPost post = new HttpPost(url);
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("data", data));
post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
DefaultHttpClient client = new DefaultHttpClient();
HttpResponse response = client.execute(post);
HttpEntity entity = response.getEntity();
InputStream inputStream = entity.getContent();
ByteArrayOutputStream content = new ByteArrayOutputStream();
responseVo.setResponseCode(response.getStatusLine().getStatusCode());
// Read response into a buffered stream
int readBytes = 0;
byte[] sBuffer = new byte[512];
while ((readBytes = inputStream.read(sBuffer)) != -1) {
content.write(sBuffer, 0, readBytes);
}
responseVo.setResponse(new String(content.toByteArray()));
return responseVo;
}
public static boolean isExternalStorageAvailable() {
boolean mExternalStorageAvailable = false;
boolean mExternalStorageWriteable = false;
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
mExternalStorageAvailable = mExternalStorageWriteable = true;
} else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
mExternalStorageAvailable = true;
mExternalStorageWriteable = false;
} else {
mExternalStorageAvailable = mExternalStorageWriteable = false;
}
return (mExternalStorageAvailable && mExternalStorageWriteable);
}
public static void uploadFile(String endPoint, String path,
HttpResponseVO vo) {
HttpURLConnection connection = null;
DataOutputStream outputStream = null;
String pathToOurFile = path;
String urlServer = endPoint;
String filename = pathToOurFile.substring(pathToOurFile
.lastIndexOf(File.separator) + 1);
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
try {
FileInputStream fileInputStream = new FileInputStream(new File(
pathToOurFile));
URL url = new URL(urlServer);
connection = (HttpURLConnection) url.openConnection();
// Allow Inputs & Outputs.
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
// Set HTTP method to POST.
connection.setRequestMethod("POST");
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("Content-Type",
"multipart/form-data;boundary=" + boundary);
outputStream = new DataOutputStream(connection.getOutputStream());
outputStream.writeBytes(twoHyphens + boundary + lineEnd);
outputStream
.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\""
+ filename + "\"" + lineEnd);
outputStream.writeBytes(lineEnd);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
// Read file
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0) {
outputStream.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
outputStream.writeBytes(lineEnd);
outputStream.writeBytes(twoHyphens + boundary + twoHyphens
+ lineEnd);
// Responses from the server (code and message)
vo.setResponseCode(connection.getResponseCode());
if (vo.getResponseCode() == Constants.HTTP_OK_200) {
StringBuilder sb = new StringBuilder();
byte[] tempBuf = new byte[1024];
InputStream is = connection.getInputStream();
while (is.read(tempBuf) != -1) {
sb.append(new String(tempBuf));
}
String s = sb.toString();
s = s.replace("�", "");
vo.setResponse(s);
} else {
StringBuilder sb = new StringBuilder();
byte[] tempBuf = new byte[1024];
InputStream is = connection.getErrorStream();
while (is.read(tempBuf) != -1) {
sb.append(new String(tempBuf));
}
vo.setResponse(sb.toString());
}
fileInputStream.close();
outputStream.flush();
outputStream.close();
} catch (Exception ex) {
vo.setError(ex.getMessage());
}
}
}
| 35.333333 | 99 | 0.587492 |
2fc269f5df0ec1ee815759d12af000af8030d856 | 2,935 | package com.example.binxie.helloworld.recyclerview;
import android.content.Context;
import android.media.Image;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.example.binxie.helloworld.R;
public class LinearAdapter extends RecyclerView.Adapter {
private Context mContext;
private OnItemClickListener mListener;
public LinearAdapter(Context context, OnItemClickListener listener) {
this.mContext = context;
mListener = listener;
}
@NonNull
@Override
public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
if (viewType == 0) {
return new LinearViewHolder(LayoutInflater.from(mContext).inflate(R.layout.layout_linear_item, parent, false));
} else {
return new LinearViewHolder2(LayoutInflater.from(mContext).inflate(R.layout.layout_linear_item_2, parent, false));
}
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
if (getItemViewType(position) == 0) {
((LinearViewHolder)holder).textView.setText("小朋友真可爱");
holder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mListener.onClick(position);
}
});
}else {
((LinearViewHolder2)holder).textView.setText("小朋友真的6");
holder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mListener.onClick(position);
}
});
}
}
@Override
public int getItemViewType(int position) {
if (position%2 == 0) {
return 0;
}else {
return 1;
}
}
@Override
public int getItemCount() {
return 30;
}
class LinearViewHolder extends RecyclerView.ViewHolder {
private TextView textView;
public LinearViewHolder(View itemView) {
super(itemView);
textView = itemView.findViewById(R.id.tv_title);
}
}
class LinearViewHolder2 extends RecyclerView.ViewHolder {
private TextView textView;
private ImageView imageView;
public LinearViewHolder2(View itemView) {
super(itemView);
textView = itemView.findViewById(R.id.tv_title);
imageView = itemView.findViewById(R.id.iv_iamge);
}
}
public interface OnItemClickListener {
void onClick(int pos);
}
}
| 27.429907 | 126 | 0.641567 |
5ea6057218db44550e79e4d42d944cfbdf73cef8 | 5,220 | /*
* Copyright 2015 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.samples.apps.topeka.adapter;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.support.annotation.ColorRes;
import android.support.annotation.DrawableRes;
import android.support.v4.content.ContextCompat;
import android.support.v4.graphics.drawable.DrawableCompat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.google.samples.apps.topeka.R;
import com.google.samples.apps.topeka.model.Category;
import com.google.samples.apps.topeka.model.quiz.Quiz;
import java.util.List;
/**
* Adapter for displaying score cards.
*/
public class ScoreAdapter extends BaseAdapter {
private final Category mCategory;
private final int count;
private final List<Quiz> mQuizList;
private Drawable mSuccessIcon;
private Drawable mFailedIcon;
public ScoreAdapter(Category category) {
mCategory = category;
mQuizList = mCategory.getQuizzes();
count = mQuizList.size();
}
@Override
public int getCount() {
return count;
}
@Override
public Quiz getItem(int position) {
return mQuizList.get(position);
}
@Override
public long getItemId(int position) {
if (position > count || position < 0) {
return AbsListView.INVALID_POSITION;
}
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (null == convertView) {
convertView = createView(parent);
}
final Quiz quiz = getItem(position);
ViewHolder viewHolder = (ViewHolder) convertView.getTag();
viewHolder.mQuizView.setText(quiz.getQuestion());
viewHolder.mAnswerView.setText(quiz.getStringAnswer());
setSolvedStateForQuiz(viewHolder.mSolvedState, position);
return convertView;
}
private void setSolvedStateForQuiz(ImageView solvedState, int position) {
final Context context = solvedState.getContext();
final Drawable tintedImage;
if (mCategory.isSolvedCorrectly(getItem(position))) {
tintedImage = getSuccessIcon(context);
} else {
tintedImage = getFailedIcon(context);
}
solvedState.setImageDrawable(tintedImage);
}
private Drawable getSuccessIcon(Context context) {
if (null == mSuccessIcon) {
mSuccessIcon = loadAndTint(context, R.drawable.ic_tick, R.color.theme_green_primary);
}
return mSuccessIcon;
}
private Drawable getFailedIcon(Context context) {
if (null == mFailedIcon) {
mFailedIcon = loadAndTint(context, R.drawable.ic_cross, R.color.theme_red_primary);
}
return mFailedIcon;
}
/**
* Convenience method to aid tintint of vector drawables at runtime.
*
* @param context The {@link Context} for this app.
* @param drawableId The id of the drawable to load.
* @param tintColor The tint to apply.
* @return The tinted drawable.
*/
private Drawable loadAndTint(Context context, @DrawableRes int drawableId,
@ColorRes int tintColor) {
Drawable imageDrawable = ContextCompat.getDrawable(context, drawableId);
if (imageDrawable == null) {
throw new IllegalArgumentException("The drawable with id " + drawableId
+ " does not exist");
}
DrawableCompat.setTint(DrawableCompat.wrap(imageDrawable), tintColor);
return imageDrawable;
}
private View createView(ViewGroup parent) {
View convertView;
final LayoutInflater inflater = LayoutInflater.from(parent.getContext());
ViewGroup scorecardItem = (ViewGroup) inflater.inflate(
R.layout.item_scorecard, parent, false);
convertView = scorecardItem;
ViewHolder holder = new ViewHolder(scorecardItem);
convertView.setTag(holder);
return convertView;
}
private class ViewHolder {
final TextView mAnswerView;
final TextView mQuizView;
final ImageView mSolvedState;
public ViewHolder(ViewGroup scorecardItem) {
mQuizView = (TextView) scorecardItem.findViewById(R.id.quiz);
mAnswerView = (TextView) scorecardItem.findViewById(R.id.answer);
mSolvedState = (ImageView) scorecardItem.findViewById(R.id.solved_state);
}
}
}
| 33.037975 | 97 | 0.680843 |
0707284be95e3cca8d7cce3638c9845f88a90612 | 2,828 | /**
* Copyright (C) 2016-2019 Expedia, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hotels.bdp.circustrain.core.replica;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hive.conf.HiveConf;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Component;
import com.google.common.base.Function;
import com.hotels.bdp.circustrain.api.Modules;
import com.hotels.bdp.circustrain.api.conf.TableReplication;
import com.hotels.bdp.circustrain.api.metadata.ColumnStatisticsTransformation;
import com.hotels.bdp.circustrain.api.metadata.PartitionTransformation;
import com.hotels.bdp.circustrain.api.metadata.TableTransformation;
@Profile({ Modules.REPLICATION })
@Component
public class ReplicaTableFactoryProvider {
private final HiveConf sourceHiveConf;
private final Function<Path, String> checksumFunction;
private final TableTransformation tableTransformation;
private final PartitionTransformation partitionTransformation;
private final ColumnStatisticsTransformation columnStatisticsTransformation;
@Autowired
public ReplicaTableFactoryProvider(
@Value("#{sourceHiveConf}") HiveConf sourceHiveConf,
@Value("#{checksumFunction}") Function<Path, String> checksumFunction,
TableTransformation tableTransformation,
PartitionTransformation partitionTransformation,
ColumnStatisticsTransformation columnStatisticsTransformation) {
this.sourceHiveConf = sourceHiveConf;
this.checksumFunction = checksumFunction;
this.tableTransformation = tableTransformation;
this.partitionTransformation = partitionTransformation;
this.columnStatisticsTransformation = columnStatisticsTransformation;
}
public ReplicaTableFactory newInstance(TableReplication tableReplication) {
if (tableReplication.getSourceTable().isGeneratePartitionFilter()) {
return new AddCheckSumReplicaTableFactory(sourceHiveConf, checksumFunction, tableTransformation,
partitionTransformation, columnStatisticsTransformation);
}
return new ReplicaTableFactory(sourceHiveConf, tableTransformation, partitionTransformation,
columnStatisticsTransformation);
}
}
| 42.848485 | 102 | 0.806223 |
10bdaefa59c9a2df138a4763eed9478ec481f600 | 530 | package homework1;
import java.util.HashMap;
import java.util.Map;
public class MapTest2 {
public static void main(String[] args) {
Map<Integer,String> map = new HashMap<Integer, String>();
map.put(1, "张三丰");
map.put(2, "周芷若");
map.put(3, "汪峰");
map.put(4, "灭绝师太");
for(Integer i : map.keySet()){
System.out.println(map.get(i));
}
map.putIfAbsent(5, "李晓红");
map.remove(1);
map.put(2, "周林");
System.out.println(map);
}
}
| 24.090909 | 65 | 0.535849 |
51b7c6d2ad90b9471aae9eec108e71121fd2a7d9 | 3,254 | package org.datadog.jenkins.plugins.datadog.steps;
import hudson.ExtensionList;
import hudson.model.labels.LabelAtom;
import net.sf.json.JSONObject;
import org.apache.commons.io.IOUtils;
import org.datadog.jenkins.plugins.datadog.DatadogGlobalConfiguration;
import org.datadog.jenkins.plugins.datadog.DatadogUtilities;
import org.datadog.jenkins.plugins.datadog.clients.ClientFactory;
import org.datadog.jenkins.plugins.datadog.clients.DatadogClientStub;
import org.jenkinsci.plugins.workflow.cps.CpsFlowDefinition;
import org.jenkinsci.plugins.workflow.job.WorkflowJob;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.ClassRule;
import org.junit.Test;
import org.jvnet.hudson.test.JenkinsRule;
import java.util.List;
public class DatadogOptionsTest {
@ClassRule
public static JenkinsRule j = new JenkinsRule();
private static DatadogClientStub stubClient = new DatadogClientStub();
@BeforeClass
public static void setup() throws Exception {
ClientFactory.setTestClient(stubClient);
DatadogGlobalConfiguration cfg = DatadogUtilities.getDatadogGlobalDescriptor();
ExtensionList.clearLegacyInstances();
cfg.setCollectBuildLogs(false);
j.createOnlineSlave(new LabelAtom("test"));
}
@Test
public void testLogCollection() throws Exception {
WorkflowJob p = j.jenkins.createProject(WorkflowJob.class, "testLogCollection");
String definition = IOUtils.toString(
this.getClass().getResourceAsStream("logCollectedInOptions.txt"),
"UTF-8"
);
p.setDefinition(new CpsFlowDefinition(definition, true));
p.scheduleBuild2(0).get();
assertLogs("foo", false);
}
@Test
public void testMetricTags() throws Exception {
WorkflowJob p = j.jenkins.createProject(WorkflowJob.class, "testMetricTags");
String definition = IOUtils.toString(
this.getClass().getResourceAsStream("pipelineMetricTags.txt"),
"UTF-8"
);
p.setDefinition(new CpsFlowDefinition(definition, true));
p.scheduleBuild2(0).get();
String hostname = DatadogUtilities.getHostname(null);
String[] expectedTags = new String[]{
"jenkins_url:" + DatadogUtilities.getJenkinsUrl(),
"user_id:anonymous",
"job:testMetricTags",
"result:SUCCESS",
"foo:bar",
"bar:foo"
};
stubClient.assertMetric("jenkins.job.duration", hostname, expectedTags);
}
private void assertLogs(final String expectedMessage, final boolean checkTraces) {
boolean hasExpectedMessage = false;
List<JSONObject> logLines = stubClient.logLines;
for(final JSONObject logLine : logLines) {
if(checkTraces) {
Assert.assertNotNull(logLine.get("dd.trace_id"));
Assert.assertNotNull(logLine.get("dd.span_id"));
}
if(!hasExpectedMessage) {
hasExpectedMessage = expectedMessage.equals(logLine.get("message"));
}
}
Assert.assertTrue("loglines does not contain '"+expectedMessage+"' message.", hasExpectedMessage);
}
}
| 38.282353 | 106 | 0.678242 |
8d69ecfa9e1caa874cb05e8dea49e22dc841303a | 2,790 | /**
* Die Klasse heißt: ReportCommand.java
* Die Klasse wurde am: 12.05.2017 | 22:07:37 erstellt.
* Der Author der Klasse ist: bySwordGames
*/
package de.bySwordGames.Bungee.Commands;
import java.util.concurrent.TimeUnit;
import de.bySwordGames.Bungee.Bungee;
import de.bySwordGames.Bungee.APIs.Report;
import net.md_5.bungee.BungeeCord;
import net.md_5.bungee.api.CommandSender;
import net.md_5.bungee.api.connection.ProxiedPlayer;
import net.md_5.bungee.api.plugin.Command;
public class ReportCommand extends Command {
public ReportCommand(String name) {
super(name);
}
@SuppressWarnings("deprecation")
@Override
public void execute(CommandSender sender, String[] args) {
if(!(sender instanceof ProxiedPlayer)) {
sender.sendMessage(Bungee.prefix + "§cDu musst ein Spieler sein, um diesen Befehl nutzen zu können.");
return;
}
ProxiedPlayer player = (ProxiedPlayer) sender;
if(args.length == 0) {
player.sendMessage(Bungee.prefix + "§cDu musst einen Spielernamen angeben, um ihn zu melden.");
return;
}
if(args.length == 1) {
player.sendMessage(Bungee.prefix + "§cDu musst einen Grund angeben, um diesen Spieler zu melden.");
return;
}
ProxiedPlayer target = BungeeCord.getInstance().getPlayer(args[0]);
if(target == null) {
player.sendMessage(Bungee.prefix + "§cDer Spieler §e" + args[0] + "§c ist nicht online.");
return;
}
if(target == player) {
player.sendMessage(Bungee.prefix + "§cDu darfst dich nicht selbst melden.");
return;
}
if(Bungee.getInstance().onlineStaff.contains(target)) {
player.sendMessage(Bungee.prefix + "§cDu darfst keine §eTeammitglieder §cmelden.");
return;
}
if(Bungee.getInstance().reports.containsKey(target)) {
player.sendMessage(Bungee.prefix + "§cDer Spieler §e" + args[0] + "§c wurde bereits reportet.");
return;
}
if(Bungee.getInstance().reportCooldown.contains(player)) {
player.sendMessage(Bungee.prefix + "§cDu darfst nur alle §e5 Sekunden §ceinen Spieler melden.");
return;
}
String grund = "";
for(int i = 1; i < args.length; i++) {
grund = grund + args[i] + " ";
}
Report report = new Report(target, grund, player);
report.announce();
player.sendMessage(Bungee.prefix + "§7Dein Report über " + target.getDisplayName() + "§7 wurde erstellt!");
player.sendMessage(Bungee.prefix + "§cMissbrauch wird mit einem Mute bestraft.");
Bungee.getInstance().reportCooldown.add(player);
BungeeCord.getInstance().getScheduler().schedule(Bungee.getInstance(), new Runnable() {
@Override
public void run() {
Bungee.getInstance().reportCooldown.remove(player);
}
}, 5, TimeUnit.SECONDS);
}
}
| 30 | 110 | 0.673835 |
52ced27106cf4823552c89c461fc2688c1948151 | 8,614 | /*
* Copyright 1999-2019 Seata.io Group.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.seata.rm.datasource;
import io.seata.rm.datasource.sql.struct.Field;
import io.seata.rm.datasource.sql.struct.Row;
import io.seata.rm.datasource.sql.struct.TableMeta;
import io.seata.rm.datasource.sql.struct.TableRecords;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import java.sql.JDBCType;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
/**
* @author Geng Zhang
*/
public class DataCompareUtilsTest {
@Test
public void isFieldEquals() {
Field field0 = new Field("name", 0, "111");
Field field1 = new Field("name", 1, "111");
Field field2 = new Field("name", 0, "222");
Field field3 = new Field("age", 0, "222");
Field field4 = new Field("name", 0, null);
Assertions.assertFalse(DataCompareUtils.isFieldEquals(field0, null).getResult());
Assertions.assertFalse(DataCompareUtils.isFieldEquals(null, field0).getResult());
Assertions.assertFalse(DataCompareUtils.isFieldEquals(field0, field1).getResult());
Assertions.assertFalse(DataCompareUtils.isFieldEquals(field0, field2).getResult());
Assertions.assertFalse(DataCompareUtils.isFieldEquals(field0, field3).getResult());
Assertions.assertFalse(DataCompareUtils.isFieldEquals(field0, field4).getResult());
Field field10 = new Field("Name", 0, "111");
Field field11 = new Field("Name", 0, null);
Assertions.assertTrue(DataCompareUtils.isFieldEquals(field0, field10).getResult());
Assertions.assertTrue(DataCompareUtils.isFieldEquals(field4, field11).getResult());
Field field12 = new Field("information", JDBCType.BLOB.getVendorTypeNumber(), "hello world".getBytes());
Field field13 = new Field("information", JDBCType.BLOB.getVendorTypeNumber(), "hello world".getBytes());
Assertions.assertTrue(DataCompareUtils.isFieldEquals(field12, field13).getResult());
}
@Test
public void isRecordsEquals() {
TableMeta tableMeta = Mockito.mock(TableMeta.class);
Mockito.when(tableMeta.getPrimaryKeyOnlyName()).thenReturn(Arrays.asList(new String[]{"pk"}));
Mockito.when(tableMeta.getTableName()).thenReturn("table_name");
TableRecords beforeImage = new TableRecords();
beforeImage.setTableName("table_name");
beforeImage.setTableMeta(tableMeta);
List<Row> rows = new ArrayList<>();
Row row = new Row();
Field field01 = addField(row,"pk", 1, "12345");
Field field02 = addField(row,"age", 1, "18");
rows.add(row);
beforeImage.setRows(rows);
Assertions.assertFalse(DataCompareUtils.isRecordsEquals(beforeImage, null).getResult());
Assertions.assertFalse(DataCompareUtils.isRecordsEquals(null, beforeImage).getResult());
TableRecords afterImage = new TableRecords();
afterImage.setTableName("table_name1"); // wrong table name
afterImage.setTableMeta(tableMeta);
Assertions.assertFalse(DataCompareUtils.isRecordsEquals(beforeImage, afterImage).getResult());
afterImage.setTableName("table_name");
Assertions.assertFalse(DataCompareUtils.isRecordsEquals(beforeImage, afterImage).getResult());
List<Row> rows2 = new ArrayList<>();
Row row2 = new Row();
Field field11 = addField(row2,"pk", 1, "12345");
Field field12 = addField(row2,"age", 1, "18");
rows2.add(row2);
afterImage.setRows(rows2);
Assertions.assertTrue(DataCompareUtils.isRecordsEquals(beforeImage, afterImage).getResult());
field11.setValue("23456");
Assertions.assertFalse(DataCompareUtils.isRecordsEquals(beforeImage, afterImage).getResult());
field11.setValue("12345");
field12.setName("sex");
Assertions.assertFalse(DataCompareUtils.isRecordsEquals(beforeImage, afterImage).getResult());
field12.setName("age");
field12.setValue("19");
Assertions.assertFalse(DataCompareUtils.isRecordsEquals(beforeImage, afterImage).getResult());
field12.setName("18");
Field field3 = new Field("pk", 1, "12346");
Row row3 = new Row();
row3.add(field3);
rows2.add(row3);
Assertions.assertFalse(DataCompareUtils.isRecordsEquals(beforeImage, afterImage).getResult());
beforeImage.setRows(new ArrayList<>());
afterImage.setRows(new ArrayList<>());
Assertions.assertTrue(DataCompareUtils.isRecordsEquals(beforeImage, afterImage).getResult());
}
private Field addField(Row row, String name, int type, Object value){
Field field = new Field(name, type, value);
row.add(field);
return field;
}
@Test
public void isRowsEquals() {
TableMeta tableMeta = Mockito.mock(TableMeta.class);
Mockito.when(tableMeta.getPrimaryKeyOnlyName()).thenReturn(Arrays.asList(new String[]{"pk"}));
Mockito.when(tableMeta.getTableName()).thenReturn("table_name");
List<Row> rows = new ArrayList<>();
Field field = new Field("pk", 1, "12345");
Row row = new Row();
row.add(field);
rows.add(row);
Assertions.assertFalse(DataCompareUtils.isRowsEquals(tableMeta, rows, null).getResult());
Assertions.assertFalse(DataCompareUtils.isRowsEquals(tableMeta, null, rows).getResult());
List<Row> rows2 = new ArrayList<>();
Field field2 = new Field("pk", 1, "12345");
Row row2 = new Row();
row2.add(field2);
rows2.add(row2);
Assertions.assertTrue(DataCompareUtils.isRowsEquals(tableMeta, rows, rows2).getResult());
field.setValue("23456");
Assertions.assertFalse(DataCompareUtils.isRowsEquals(tableMeta, rows, rows2).getResult());
field.setValue("12345");
Field field3 = new Field("pk", 1, "12346");
Row row3 = new Row();
row3.add(field3);
rows2.add(row3);
Assertions.assertFalse(DataCompareUtils.isRowsEquals(tableMeta, rows, rows2).getResult());
}
@Test
public void testRowListToMapWithSinglePk(){
List<String> primaryKeyList = new ArrayList<>();
primaryKeyList.add("id");
List<Row> rows = new ArrayList<>();
Field field = new Field("id", 1, "1");
Row row = new Row();
row.add(field);
rows.add(row);
Field field2 = new Field("id", 1, "2");
Row row2 = new Row();
row2.add(field2);
rows.add(row2);
Field field3 = new Field("id", 1, "3");
Row row3 = new Row();
row3.add(field3);
rows.add(row3);
Map<String, Map<String, Field>> result =DataCompareUtils.rowListToMap(rows,primaryKeyList);
Assertions.assertTrue(result.size()==3);
Assertions.assertEquals(result.keySet().iterator().next(),"1");
}
@Test
public void testRowListToMapWithMultipPk(){
List<String> primaryKeyList = new ArrayList<>();
primaryKeyList.add("id1");
primaryKeyList.add("id2");
List<Row> rows = new ArrayList<>();
Field field1 = new Field("id1", 1, "1");
Field field11 = new Field("id2", 1, "2");
Row row = new Row();
row.add(field1);
row.add(field11);
rows.add(row);
Field field2 = new Field("id1", 1, "3");
Field field22 = new Field("id2", 1, "4");
Row row2 = new Row();
row2.add(field2);
row2.add(field22);
rows.add(row2);
Field field3 = new Field("id1", 1, "5");
Field field33 = new Field("id2", 1, "6");
Row row3 = new Row();
row3.add(field3);
row3.add(field33);
rows.add(row3);
Map<String, Map<String, Field>> result =DataCompareUtils.rowListToMap(rows,primaryKeyList);
Assertions.assertTrue(result.size()==3);
Assertions.assertEquals(result.keySet().iterator().next(),"1_2");
}
} | 38.627803 | 112 | 0.652078 |
b59b0addfea0269d21156e343408d653139cf2d0 | 1,432 | package org.jetbrains.plugins.github;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
/**
* Information about Github repository.
*
* @author oleg
* @author Kirill Likhodedov
*/
public class RepositoryInfo {
@NotNull private final String myName;
@NotNull private final String myCloneUrl;
@NotNull private final String myOwnerName;
@Nullable private final String myParentName;
private final boolean myFork;
public RepositoryInfo(@NotNull String name, @NotNull String cloneUrl, @NotNull String ownerName, @Nullable String parentName,
boolean fork) {
myName = name;
myParentName = parentName;
myCloneUrl = cloneUrl;
myOwnerName = ownerName;
myFork = fork;
}
@NotNull
public String getName() {
return myName;
}
@NotNull
public String getOwnerName() {
return myOwnerName;
}
public boolean isFork() {
return myFork;
}
/**
* @return The name of the parent of this repository, or null.
* Null is returned if this repository doesn't have a parent, i. e. is not a fork,
* or if the parent information was not retrieved by the time of constructing of this RepositoryInfo object.
* To be sure use {@link #isFork()}.
*/
@Nullable
public String getParentName() {
return myParentName;
}
@NotNull
public String getCloneUrl() {
return myCloneUrl;
}
}
| 23.866667 | 127 | 0.685754 |
4cccd23c39fb8524735dc3e270a6724d17241ccb | 5,287 | /*
* Copyright 2017-present Open Networking Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.onosproject.drivers.arista;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.onosproject.net.DeviceId;
import org.onosproject.net.behaviour.ControllerConfig;
import org.onosproject.net.behaviour.ControllerInfo;
import org.onosproject.net.driver.AbstractHandlerBehaviour;
import org.onosproject.net.driver.DriverHandler;
import org.onosproject.protocol.rest.RestSBController;
import org.slf4j.Logger;
import javax.ws.rs.core.MediaType;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import static com.google.common.base.Preconditions.checkNotNull;
import static org.slf4j.LoggerFactory.getLogger;
/**
* Sets, gets and removes the openflow controller configuration from a Arista Rest device.
*/
public class ControllerConfigAristaImpl extends AbstractHandlerBehaviour implements ControllerConfig {
private static final String CONFIGURE_TERMINAL = "configure";
private static final String OPENFLOW_CMD = "openflow";
private static final String REMOVE_CONTROLLER_CMD = "no controller tcp:%s:%d";
private static final String API_ENDPOINT = "/command-api/";
private static final String JSON = "json";
private static final String JSONRPC = "jsonrpc";
private static final String METHOD = "method";
private static final String RUN_CMDS = "runCmds";
private static final String VERSION = "version";
private static final String ID = "id";
private static final String PARAMS = "params";
private static final String FORMAT = "format";
private static final String TIMESTAMPS = "timestamps";
private static final String CMDS = "cmds";
private static final String TWO_POINT_ZERO = "2.0";
private static final String REMOVE_CONTROLLERS = "removeControllers";
private static final String ENABLE = "enable";
private static final int MAX_CONTROLLERS = 8;
private static final Boolean FALSE = false;
private static final int VERSION_1 = 1;
private final Logger log = getLogger(getClass());
@Override
public List<ControllerInfo> getControllers() {
throw new UnsupportedOperationException("get controllers configuration is not supported");
}
@Override
public void setControllers(List<ControllerInfo> controllers) {
throw new UnsupportedOperationException("set controllers configuration is not supported");
}
@Override
public void removeControllers(List<ControllerInfo> controllers) {
DriverHandler handler = handler();
RestSBController controller = checkNotNull(handler.get(RestSBController.class));
DeviceId deviceId = handler.data().deviceId();
List<String> cmds = new ArrayList<>();
cmds.add(CONFIGURE_TERMINAL);
cmds.add(OPENFLOW_CMD);
controllers.stream().limit(MAX_CONTROLLERS).forEach(c -> cmds
.add(String.format(REMOVE_CONTROLLER_CMD, c.ip().toString(), c.port())));
String request = generate(cmds);
log.info("request :{}", request);
InputStream stream = new ByteArrayInputStream(request.getBytes(StandardCharsets.UTF_8));
String response = controller.post(deviceId, API_ENDPOINT, stream,
MediaType.APPLICATION_JSON_TYPE, String.class);
log.info("response :{}", response);
try {
JsonNode json = new ObjectMapper().readTree(response);
} catch (IOException e) {
log.error("Cannot communicate with device {} , exception {}", deviceId, e);
}
}
/**
* Generates a ObjectNode from a list of commands in String format.
*
* @param commands a list of commands
* @return an ObjectNode generated from a list of commands in String format
*/
private static String generate(List<String> commands) {
ObjectMapper om = new ObjectMapper();
ArrayNode cmds = om.createArrayNode();
cmds.add(ENABLE);
commands.stream().forEach(cmds::add); //commands here
ObjectNode parm = om.createObjectNode();
parm.put(FORMAT, JSON);
parm.put(TIMESTAMPS, FALSE);
parm.put(CMDS, cmds);
parm.put(VERSION, VERSION_1);
ObjectNode node = om.createObjectNode();
node.put(JSONRPC, TWO_POINT_ZERO);
node.put(METHOD, RUN_CMDS);
node.put(PARAMS, parm);
node.put(ID, REMOVE_CONTROLLERS);
return node.toString();
}
}
| 38.875 | 102 | 0.71534 |
9fa58267628eabfd5ee19c4d30ebdae7eed45bcc | 383 | //Given a Binary Tree, convert it into its mirror.
class D33_MirrorTree
{
void mirror(TNode node)
{
// Your code here
if(node==null || (node.left==null&&node.right==null)){
return;
}
TNode temp = node.right;
node.right = node.left;
node.left = temp;
mirror(node.left);
mirror(node.right);
}
} | 20.157895 | 62 | 0.535248 |
adffa5916305694a41141d7764e66cbc19b933a5 | 1,201 | package no.nav.registre.medl.provider.rs;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
import no.nav.registre.medl.database.model.TMedlemPeriode;
import no.nav.registre.medl.database.multitenancy.TenantContext;
import no.nav.registre.medl.provider.rs.requests.SyntetiserMedlRequest;
import no.nav.registre.medl.service.SyntetiseringService;
@RestController
@RequestMapping("api/v1/syntetisering")
@RequiredArgsConstructor
public class SyntetiseringController {
private final SyntetiseringService syntetiseringService;
@PostMapping(value = "/generer")
public ResponseEntity<List<TMedlemPeriode>> genererMedlemskapsmeldinger(
@RequestBody SyntetiserMedlRequest syntetiserMedlRequest
) {
TenantContext.setTenant(syntetiserMedlRequest.getMiljoe());
return ResponseEntity.ok(syntetiseringService.opprettMeldinger(syntetiserMedlRequest));
}
} | 38.741935 | 95 | 0.822648 |
386e3f14fb9d51c1cccb3076292411bf36589dc7 | 893 | package com.app.service.util;
import java.io.UnsupportedEncodingException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Created by Victor on 17-6-28.
*/
public class CharHandle {
private static Pattern unicodeOutliers = Pattern.compile("[\ud83c\udc00-\ud83c\udfff]|[\ud83d\udc00-\ud83d\udfff]|[\u2600-\u27ff]", Pattern.UNICODE_CASE | Pattern.CANON_EQ | Pattern.CASE_INSENSITIVE);
public static String filterSpecChar(String content) {
String utf8tweet = "";
try {
byte[] utf8Bytes = content.getBytes("UTF-8");
utf8tweet = new String(utf8Bytes, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
Matcher unicodeOutlierMatcher = unicodeOutliers.matcher(utf8tweet);
utf8tweet = unicodeOutlierMatcher.replaceAll(" ");
return utf8tweet;
}
}
| 35.72 | 204 | 0.677492 |
f73f6f8b3ef95faca38e3e2b226887d4fe4de379 | 8,754 | package org.nzbhydra.config;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonFormat.Shape;
import com.google.common.base.Strings;
import lombok.Data;
import org.javers.core.metamodel.annotation.DiffIgnore;
import org.nzbhydra.NzbHydra;
import org.nzbhydra.config.downloading.ProxyType;
import org.nzbhydra.config.sensitive.SensitiveData;
import org.nzbhydra.debuginfos.DebugInfosProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.context.properties.ConfigurationProperties;
import java.io.File;
import java.io.IOException;
import java.math.BigInteger;
import java.net.InetAddress;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.Random;
@ConfigurationProperties("main")
@Data
public class MainConfig extends ValidatingConfig<MainConfig> {
private static final Logger logger = LoggerFactory.getLogger(MainConfig.class);
private Integer configVersion = 18;
//Hosting settings
@RestartRequired
private String host = "0.0.0.0";
@RestartRequired
private int port = 5076;
@RestartRequired
protected String urlBase = null;
//Proxy settings
@RestartRequired
@JsonFormat(shape = Shape.STRING)
private ProxyType proxyType = ProxyType.NONE;
@SensitiveData
private String proxyHost = null;
private int proxyPort;
private boolean proxyIgnoreLocal = true;
private List<String> proxyIgnoreDomains = new ArrayList<>();
@SensitiveData
private String proxyUsername;
@SensitiveData
private String proxyPassword;
//Database settings
private String backupFolder;
private Integer backupEveryXDays = 7;
private boolean backupBeforeUpdate = true;
private Integer deleteBackupsAfterWeeks = 4;
//History settings
private boolean keepHistory = true;
private Integer keepStatsForWeeks = null;
private Integer keepHistoryForWeeks = null;
//SSL settings
@RestartRequired
private boolean ssl = false;
@RestartRequired
private String sslKeyStore = null;
@SensitiveData
@RestartRequired
private String sslKeyStorePassword = null;
//Security settings
@RestartRequired
private boolean verifySsl = true;
private boolean disableSslLocally = false;
private List<String> sniDisabledFor = new ArrayList<>();
private List<String> verifySslDisabledFor = new ArrayList<>();
//Update settings
private boolean updateAutomatically = false;
private boolean updateToPrereleases = false;
private boolean updateCheckEnabled = true;
private boolean showUpdateBannerOnDocker = true;
private boolean showWhatsNewBanner = true;
//Startup / GUI settings
private boolean showNews = true;
private boolean startupBrowser = true;
private boolean welcomeShown = false;
protected String theme;
//Database settings
@RestartRequired
private int databaseCompactTime = 15_000;
@RestartRequired
private int databaseRetentionTime = 1000;
@RestartRequired
private int databaseWriteDelay = 5000;
//Other settings
@SensitiveData
@DiffIgnore
private String apiKey = null;
private String dereferer = null;
private boolean instanceCounterDownloaded = false;
private String repositoryBase;
private boolean shutdownForRestart = false;
@RestartRequired
private boolean useCsrf = true;
@RestartRequired
private int xmx;
private LoggingConfig logging = new LoggingConfig();
public Optional<String> getUrlBase() {
return Optional.ofNullable(Strings.emptyToNull(urlBase));
}
public Optional<Integer> getDeleteBackupsAfterWeeks() {
return Optional.ofNullable(deleteBackupsAfterWeeks);
}
public Optional<String> getDereferer() {
return Optional.ofNullable(dereferer); //This must be returned as empty string so that the config can overwrite it
}
public Optional<Integer> getBackupEveryXDays() {
return Optional.ofNullable(backupEveryXDays);
}
@Override
public ConfigValidationResult validateConfig(BaseConfig oldConfig, MainConfig newMainConfig, BaseConfig newBaseConfig) {
ConfigValidationResult result = new ConfigValidationResult();
MainConfig oldMain = oldConfig.getMain();
boolean portChanged = oldMain.getPort() != port;
boolean urlBaseChanged = oldMain.getUrlBase().isPresent() && !oldMain.getUrlBase().get().equals(urlBase);
if (urlBase == null && oldMain.getUrlBase().isPresent() && oldMain.getUrlBase().get().equals("/")) {
urlBaseChanged = false;
}
boolean sslChanged = oldMain.isSsl() != isSsl();
if (portChanged || urlBaseChanged || sslChanged && !startupBrowser) {
result.getWarningMessages().add("You've made changes that affect Hydra's URL and require a restart. Hydra will try and reload using the new URL when it's back.");
}
if (DebugInfosProvider.isRunInDocker() && !"0.0.0.0".equals(host)) {
result.getWarningMessages().add("You've changed the host but NZBHydra seems to be run in docker. It's recommended to use the host '0.0.0.0'.");
}
if (!"0.0.0.0".equals(host)) {
try {
boolean reachable = InetAddress.getByName(host).isReachable(1);
if (!reachable) {
result.getWarningMessages().add("The configured host address cannot be reached. Are you sure it is correct?");
}
} catch (IOException e) {
//Ignore, user will have to know what he does
}
}
if (oldConfig.getMain().getXmx() < 128) {
result.getErrorMessages().add("The JVM memory must be set to at least 128");
}
MainConfig newMain = newBaseConfig.getMain();
if (newMain.getKeepHistoryForWeeks() != null && newMain.getKeepHistoryForWeeks() <= 0) {
result.getErrorMessages().add("Please either delete the value for \"Keep history for\" or set it to a positive value.");
}
if (newMain.getKeepStatsForWeeks() != null && newMain.getKeepStatsForWeeks() <= 0) {
result.getErrorMessages().add("Please either delete the value for \"Keep stats for\" or set it to a positive value.");
}
if (newMain.getKeepStatsForWeeks() != null && newMain.getKeepHistoryForWeeks() != null && newMain.getKeepStatsForWeeks() > newMain.getKeepHistoryForWeeks()) {
result.getErrorMessages().add("Please set the time to keep stats to a value not higher than the time to keep history.");
}
if (newMain.getBackupFolder() != null) {
final File backupFolderFile;
if (backupFolder.contains(File.separator)) {
backupFolderFile = new File(backupFolder);
} else {
backupFolderFile = new File(NzbHydra.getDataFolder(), backupFolder);
}
if (!backupFolderFile.exists()) {
final boolean created = backupFolderFile.mkdirs();
if (!created) {
result.getErrorMessages().add("Backup folder " + backupFolder + " does not exist and could not be created");
}
}
}
ConfigValidationResult validationResult = getLogging().validateConfig(oldConfig, getLogging(), newBaseConfig);
result.getWarningMessages().addAll(validationResult.getWarningMessages());
result.getErrorMessages().addAll(validationResult.getErrorMessages());
oldMain = oldMain.prepareForSaving(oldConfig);
result.setRestartNeeded(validationResult.isRestartNeeded() || isRestartNeeded(oldMain));
result.setOk(validationResult.isOk() && result.isOk());
return result;
}
@Override
public MainConfig prepareForSaving(BaseConfig oldBaseConfig) {
if (!Strings.isNullOrEmpty(urlBase) && (!urlBase.startsWith("/") || urlBase.endsWith("/") || "/".equals(urlBase))) {
if (!urlBase.startsWith("/")) {
urlBase = "/" + urlBase;
}
if (urlBase.endsWith("/")) {
urlBase = urlBase.substring(0, urlBase.length() - 1);
}
if ("/".equals(urlBase) || "".equals(urlBase)) {
urlBase = "/";
}
setUrlBase(urlBase);
}
return this;
}
@Override
public MainConfig updateAfterLoading() {
return this;
}
@Override
public MainConfig initializeNewConfig() {
Random random = new Random();
setApiKey(new BigInteger(130, random).toString(32).toUpperCase());
return this;
}
}
| 36.173554 | 174 | 0.670436 |
31bb7f72b29b4093bd392d8d4b48f0351ff2bc9b | 4,655 | package razerdp.demo.fragment.basedemo;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.AppCompatCheckBox;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import razerdp.basepopup.BasePopupWindow;
import razerdp.basepopup.R;
import razerdp.demo.fragment.other.SimpleBaseFrag;
import razerdp.demo.popup.GravityPopup;
import razerdp.demo.utils.MultiSpanUtil;
/**
* Created by 大灯泡 on 2018/11/28.
*/
public class GravityPopupFrag extends SimpleBaseFrag implements View.OnClickListener {
private GravityPopup mPopupWindow;
private AppCompatCheckBox checkGravityLeft;
private AppCompatCheckBox checkGravityTop;
private AppCompatCheckBox checkGravityRight;
private AppCompatCheckBox checkGravityBottom;
private AppCompatCheckBox checkGravityCenterVertical;
private AppCompatCheckBox checkGravityCenterHorizontal;
private AppCompatCheckBox checkGravityCenter;
private Button popupShow;
private AppCompatCheckBox checkCombineAnchor;
private static final String DESC = " · 不跟anchorView关联的情况下,gravity意味着在整个decorView中的方位,默认Gravity为NO_GRAVITY,即屏幕左上角\n\n" +
" · 如果跟anchorView关联,gravity意味着以anchorView为中心的方位,默认处于anchorView正下方,并且尽可能左对齐。";
@Nullable
@Override
public View onCreateView(LayoutInflater inflater,
@Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
return super.onCreateView(inflater, container, savedInstanceState);
}
@Override
public void onInitView(View rootView) {
initView();
mPopupWindow = new GravityPopup(mContext);
popupShow.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int gravity = Gravity.NO_GRAVITY;
if (checkGravityLeft.isChecked()) {
gravity |= Gravity.LEFT;
}
if (checkGravityTop.isChecked()) {
gravity |= Gravity.TOP;
}
if (checkGravityRight.isChecked()) {
gravity |= Gravity.RIGHT;
}
if (checkGravityBottom.isChecked()) {
gravity |= Gravity.BOTTOM;
}
if (checkGravityCenterVertical.isChecked()) {
gravity |= Gravity.CENTER_VERTICAL;
}
if (checkGravityCenterHorizontal.isChecked()) {
gravity |= Gravity.CENTER_HORIZONTAL;
}
if (checkGravityCenter.isChecked()) {
gravity |= Gravity.CENTER;
}
mPopupWindow.setPopupGravity(gravity);
if (checkCombineAnchor.isChecked()) {
mPopupWindow.showPopupWindow(v);
} else {
mPopupWindow.showPopupWindow();
}
}
});
}
private void initView() {
this.checkGravityLeft = (AppCompatCheckBox) findViewById(R.id.check_gravity_left);
this.checkGravityTop = (AppCompatCheckBox) findViewById(R.id.check_gravity_top);
this.checkGravityRight = (AppCompatCheckBox) findViewById(R.id.check_gravity_right);
this.checkGravityBottom = (AppCompatCheckBox) findViewById(R.id.check_gravity_bottom);
this.checkGravityCenterVertical = (AppCompatCheckBox) findViewById(R.id.check_gravity_center_vertical);
this.checkGravityCenterHorizontal = (AppCompatCheckBox) findViewById(R.id.check_gravity_center_horizontal);
this.checkGravityCenter = (AppCompatCheckBox) findViewById(R.id.check_gravity_center);
this.checkCombineAnchor = (AppCompatCheckBox) findViewById(R.id.check_combine_anchor);
this.popupShow = (Button) findViewById(R.id.popup_show);
initDesc();
}
private void initDesc() {
TextView desc = (TextView) findViewById(R.id.tv_desc);
MultiSpanUtil.create(DESC)
.append("默认Gravity为NO_GRAVITY,即屏幕左上角").setTextColor(Color.RED)
.append("默认处于anchorView正下方,并且尽可能左对齐。").setTextColor(Color.RED)
.into(desc);
}
@Override
public BasePopupWindow getPopup() {
return null;
}
@Override
public Button getButton() {
return null;
}
@Override
public View getFragment() {
return mInflater.inflate(R.layout.frag_demo_gravity, container, false);
}
}
| 36.944444 | 123 | 0.66015 |
d2c10a09d6e6bc482ab27435e0e301a312bfcb9e | 268 | package com.cheng.common.utils.retrofit;
import com.alibaba.fastjson.JSONObject;
import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.Path;
public interface IpApiService {
@GET("{ip}")
Call<JSONObject> getIpInfo(@Path("ip") String ip);
}
| 20.615385 | 54 | 0.75 |
9c44d83fe713c3857008c7eacda07cc839293bde | 10,080 | package de.clashofdynasties.game;
import com.fasterxml.jackson.databind.node.JsonNodeFactory;
import com.fasterxml.jackson.databind.node.ObjectNode;
import de.clashofdynasties.models.*;
import de.clashofdynasties.repository.*;
import de.clashofdynasties.service.RoutingService;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.annotation.Secured;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import java.security.Principal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Controller
@RequestMapping("/game/caravans")
@Secured("ROLE_USER")
public class CaravanController {
@Autowired
private PlayerRepository playerRepository;
@Autowired
private CaravanRepository caravanRepository;
@Autowired
private ItemRepository itemRepository;
@Autowired
private CityRepository cityRepository;
@Autowired
private RoadRepository roadRepository;
@Autowired
private RelationRepository relationRepository;
@Autowired
private EventRepository eventRepository;
@RequestMapping(value = "/route", method = RequestMethod.GET)
public
@ResponseBody
ObjectNode calculateRoute(Principal principal, @RequestParam ObjectId point1, @RequestParam ObjectId point2) {
Player player = playerRepository.findByName(principal.getName());
City city1 = cityRepository.findById(point1);
City city2 = cityRepository.findById(point2);
if (city1 != null && city2 != null) {
if(city1.getBuildings().stream().filter(b -> b.getBlueprint().getId() == 12).count() > 0 && city2.getBuildings().stream().filter(b -> b.getBlueprint().getId() == 12).count() > 0) {
RoutingService routing = new RoutingService(roadRepository, relationRepository);
if (routing.calculateRoute(city1, city2, player)) {
return routing.getRoute().toJSON();
}
}
}
return JsonNodeFactory.instance.objectNode();
}
@RequestMapping(value = "/{caravan}", method = RequestMethod.DELETE)
@ResponseStatus(HttpStatus.OK)
public void remove(Principal principal, @PathVariable("caravan") ObjectId caravanId) {
Player player = playerRepository.findByName(principal.getName());
Caravan caravan = caravanRepository.findById(caravanId);
if(caravan.isPaused()) {
Relation relation = relationRepository.findByPlayers(caravan.getPoint1().getPlayer(), caravan.getPoint2().getPlayer());
if(relation != null) {
relation.removePendingCaravan(caravan);
}
eventRepository.add(new Event("Trade", "Handelsvorschlag wurde abgelehnt", caravan.getPoint2().getPlayer().getName() + " hat euer Handelsvorschlag abgelehnt.Die Karawane " + caravan.getName() + " wird nicht entsandt.", "diplomacy?pid=" + player.getId(), caravan.getPoint1().getPlayer()));
caravanRepository.remove(caravan);
} else if (caravan.getPoint1().getPlayer().equals(caravan.getPoint2().getPlayer()) && caravan.getPlayer().equals(player)) {
caravan.setTerminate(!caravan.isTerminate());
} else if(caravan.getPoint1().getPlayer().equals(player) || caravan.getPoint2().getPlayer().equals(player)) {
caravan.setTerminate(true);
Player otherPlayer = caravan.getPoint1().getPlayer();
if(otherPlayer.equals(player))
otherPlayer = caravan.getPoint2().getPlayer();
eventRepository.add(new Event("Trade", "Handelsweg wurde von " + player.getName() + " aufgelöst", "Der Handelsweg zwischen " + caravan.getPoint1().getName() + " und " + caravan.getPoint2().getName() + " wurde von " + player.getName() + " aufgelöst. Die Karawane " + caravan.getName() + " wird bei Ankunft in " + caravan.getPoint1().getName() + " aufgelöst.", "diplomacy?pid=" + player.getId(), otherPlayer));
}
}
@RequestMapping(value = "/{caravan}/accept", method = RequestMethod.PUT)
@ResponseStatus(HttpStatus.OK)
public void accept(Principal principal, @PathVariable("caravan") ObjectId caravanId) {
Player player = playerRepository.findByName(principal.getName());
Caravan caravan = caravanRepository.findById(caravanId);
if(caravan.getPoint2().getPlayer().equals(player)) {
Relation relation = relationRepository.findByPlayers(caravan.getPoint1().getPlayer(), caravan.getPoint2().getPlayer());
if(relation != null) {
relation.removePendingCaravan(caravan);
relation.addCaravan(caravan);
caravan.setPaused(false);
loadPoint1In(caravan);
caravan.updateTimestamp();
eventRepository.add(new Event("Trade", "Handelsweg wurde etabliert", "Der Handelsweg zwischen " + caravan.getPoint1().getName() + " und " + caravan.getPoint2().getName() + " wurde etabliert. Die Karawane " + caravan.getName() + " wurde entsandt.", caravan.getPoint1(), caravan.getPoint1().getPlayer()));
} else {
remove(principal, caravanId);
}
}
}
@RequestMapping(method = RequestMethod.POST)
@ResponseStatus(HttpStatus.OK)
public void create(Principal principal, @RequestParam String name, @RequestParam ObjectId point1, @RequestParam Integer point1Item, @RequestParam Integer point1Load, @RequestParam ObjectId point2, @RequestParam Integer point2Item, @RequestParam Integer point2Load) {
Player player = playerRepository.findByName(principal.getName());
City city1 = cityRepository.findById(point1);
City city2 = cityRepository.findById(point2);
if (city1 != null && city2 != null) {
RoutingService routing = new RoutingService(roadRepository, relationRepository);
if (routing.calculateRoute(city1, city2, player) && city1.getPlayer().equals(player) && city2.getPlayer().equals(player)) {
createCaravan(player, name, city1, itemRepository.findById(point1Item), point1Load, city2, itemRepository.findById(point2Item), point2Load, routing.getRoute(), false);
} else if(routing.calculateRoute(city1, city2, player) && city1.getPlayer().equals(player) || !city2.getPlayer().equals(player)) {
Relation relation = relationRepository.findByPlayers(city1.getPlayer(), city2.getPlayer());
if(relation != null && relation.getRelation() >= 2) {
Caravan caravan = createCaravan(player, name, city1, itemRepository.findById(point1Item), point1Load, city2, itemRepository.findById(point2Item), point2Load, routing.getRoute(), true);
relation.addPendingCaravan(caravan);
eventRepository.add(new Event("Trade", "Handelsvorschlag von " + player.getName(), "Der Spieler " + player.getName() + " unterbreitet euch einen Handelsvorschlag zwischen eurer Stadt " + city2.getName() + " und " + city1.getName() + ".", "diplomacy?pid=" + player.getId(), city2.getPlayer()));
}
}
}
}
private Caravan createCaravan(Player player, String name, City point1, Item point1Item, Integer point1Load, City point2, Item point2Item, Integer point2Load, Route route, boolean paused) {
Caravan caravan = new Caravan();
caravan.setPoint1(point1);
caravan.setPoint2(point2);
caravan.setRoute(route);
caravan.setX(point1.getX());
caravan.setY(point1.getY());
caravanRepository.add(caravan);
caravan.getRoute().setCurrentRoad(roadRepository.findByCities(point1, caravan.getRoute().getNext()));
caravan.setPoint1Item(point1Item);
caravan.setPoint1Load(point1Load);
caravan.setPoint2Item(point2Item);
caravan.setPoint2Load(point2Load);
caravan.setName(name);
caravan.setPlayer(player);
caravan.setPaused(paused);
if(!paused)
loadPoint1In(caravan);
caravan.move(70);
caravan.updateTimestamp();
caravan.setDirection(2);
return caravan;
}
private void loadPoint1In(Caravan caravan) {
double amount = (caravan.getPoint1().getStoredItem(caravan.getPoint1Item().getId()) - caravan.getPoint1Load() > 0) ? caravan.getPoint1Load() : Math.floor(caravan.getPoint1().getStoredItem(caravan.getPoint1Item().getId()));
if (caravan.getPoint1().getItems() == null)
caravan.getPoint1().setItems(new HashMap<>());
caravan.getPoint1().getItems().put(caravan.getPoint1Item().getId(), caravan.getPoint1().getStoredItem(caravan.getPoint1Item().getId()) - amount);
caravan.setPoint1Store(new Double(amount).intValue());
caravan.setPoint1StoreItem(caravan.getPoint1Item());
}
@RequestMapping(value = "/{caravan}", method = RequestMethod.PUT)
@ResponseStatus(HttpStatus.OK)
public void save(Principal principal, @PathVariable("caravan") ObjectId id, @RequestParam(required = false) String name, @RequestParam(required = false) Integer point1Item, @RequestParam(required = false) Integer point1Load, @RequestParam(required = false) Integer point2Item, @RequestParam(required = false) Integer point2Load) {
Player player = playerRepository.findByName(principal.getName());
Caravan caravan = caravanRepository.findById(id);
if (caravan.getPlayer().equals(player)) {
if (name != null)
caravan.setName(name);
if (point1Item != null)
caravan.setPoint1Item(itemRepository.findById(point1Item));
if (point1Load != null)
caravan.setPoint1Load(point1Load);
if (point2Item != null)
caravan.setPoint2Item(itemRepository.findById(point2Item));
if (point2Load != null)
caravan.setPoint2Load(point2Load);
}
}
}
| 46.451613 | 420 | 0.675198 |
619b23c87ac930989293b27cec68e999193ebf75 | 16,181 | /**
* Licensed to The Apereo Foundation under one or more contributor license
* agreements. See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
*
*
* The Apereo Foundation licenses this file to you under the Educational
* Community License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of the License
* at:
*
* http://opensource.org/licenses/ecl2.txt
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*
*/
package org.opencastproject.workflow.handler.videoeditor;
import org.opencastproject.job.api.Job;
import org.opencastproject.mediapackage.Catalog;
import org.opencastproject.mediapackage.MediaPackage;
import org.opencastproject.mediapackage.MediaPackageBuilder;
import org.opencastproject.mediapackage.MediaPackageBuilderFactory;
import org.opencastproject.mediapackage.MediaPackageElement;
import org.opencastproject.mediapackage.MediaPackageElementFlavor;
import org.opencastproject.mediapackage.MediaPackageElementParser;
import org.opencastproject.mediapackage.MediaPackageException;
import org.opencastproject.mediapackage.Track;
import org.opencastproject.mediapackage.selector.TrackSelector;
import org.opencastproject.serviceregistry.api.ServiceRegistry;
import org.opencastproject.serviceregistry.api.ServiceRegistryException;
import org.opencastproject.smil.api.SmilException;
import org.opencastproject.smil.api.SmilService;
import org.opencastproject.smil.entity.api.Smil;
import org.opencastproject.util.NotFoundException;
import org.opencastproject.videoeditor.api.ProcessFailedException;
import org.opencastproject.videoeditor.api.VideoEditorService;
import org.opencastproject.workflow.api.WorkflowInstance;
import org.opencastproject.workflow.api.WorkflowOperationException;
import org.opencastproject.workflow.api.WorkflowOperationInstance;
import org.opencastproject.workflow.api.WorkflowOperationResult;
import org.opencastproject.workspace.api.Workspace;
import org.easymock.EasyMock;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.xml.sax.SAXException;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.xml.bind.JAXBException;
/**
* Test class for {@link VideoEditorWorkflowOperationHandler}
*/
public class VideoEditorWorkflowOperationHandlerTest {
private VideoEditorWorkflowOperationHandler videoEditorWorkflowOperationHandler = null;
private SmilService smilService = null;
private VideoEditorService videoEditorServiceMock = null;
private Workspace workspaceMock = null;
private URI mpURI = null;
private MediaPackage mp = null;
private URI mpSmilURI = null;
private MediaPackage mpSmil = null;
@Before
public void setUp() throws MediaPackageException, IOException, NotFoundException, URISyntaxException, SmilException,
JAXBException, SAXException {
MediaPackageBuilder mpBuilder = MediaPackageBuilderFactory.newInstance().newMediaPackageBuilder();
mpURI = VideoEditorWorkflowOperationHandlerTest.class.getResource("/editor_mediapackage.xml").toURI();
mp = mpBuilder.loadFromXml(mpURI.toURL().openStream());
mpSmilURI = VideoEditorWorkflowOperationHandlerTest.class.getResource("/editor_smil_mediapackage.xml").toURI();
mpSmil = mpBuilder.loadFromXml(mpSmilURI.toURL().openStream());
videoEditorServiceMock = EasyMock.createNiceMock(VideoEditorService.class);
workspaceMock = EasyMock.createNiceMock(Workspace.class);
smilService = SmilServiceMock.createSmilServiceMock(mpSmilURI);
videoEditorWorkflowOperationHandler = new VideoEditorWorkflowOperationHandler();
videoEditorWorkflowOperationHandler.setJobBarrierPollingInterval(0);
videoEditorWorkflowOperationHandler.setSmilService(smilService);
videoEditorWorkflowOperationHandler.setVideoEditorService(videoEditorServiceMock);
videoEditorWorkflowOperationHandler.setWorkspace(workspaceMock);
}
private static Map<String, String> getDefaultConfiguration(boolean interactive) {
Map<String, String> configuration = new HashMap<String, String>();
configuration.put("source-flavors", "*/work");
configuration.put("preview-flavors", "*/preview");
configuration.put("skipped-flavors", "*/work");
configuration.put("smil-flavors", "*/smil");
configuration.put("target-smil-flavor", "episode/smil");
configuration.put("target-flavor-subtype", "trimmed");
configuration.put("interactive", Boolean.toString(interactive));
return configuration;
}
private WorkflowInstance getWorkflowInstance(MediaPackage mp, Map<String, String> configurations) {
WorkflowInstance workflowInstance = new WorkflowInstance();
workflowInstance.setId(1);
workflowInstance.setState(WorkflowInstance.WorkflowState.RUNNING);
workflowInstance.setMediaPackage(mp);
WorkflowOperationInstance operation = new WorkflowOperationInstance("op",
WorkflowOperationInstance.OperationState.RUNNING);
operation.setTemplate("editor");
operation.setState(WorkflowOperationInstance.OperationState.RUNNING);
for (String key : configurations.keySet()) {
operation.setConfiguration(key, configurations.get(key));
}
List<WorkflowOperationInstance> operations = new ArrayList<WorkflowOperationInstance>(1);
operations.add(operation);
workflowInstance.setOperations(operations);
return workflowInstance;
}
@Test
public void testEditorOperationStart() throws WorkflowOperationException, IOException {
// uri for new preview track smil file
EasyMock.expect(
workspaceMock.put((String) EasyMock.anyObject(), (String) EasyMock.anyObject(),
(String) EasyMock.anyObject(), (InputStream) EasyMock.anyObject())).andReturn(
URI.create("http://localhost:8080/foo/presenter.smil"));
// uri for new episode smil file
String episodeSmilUri = "http://localhost:8080/foo/episode.smil";
EasyMock.expect(
workspaceMock.put((String) EasyMock.anyObject(), (String) EasyMock.anyObject(),
(String) EasyMock.anyObject(), (InputStream) EasyMock.anyObject())).andReturn(
URI.create(episodeSmilUri));
EasyMock.replay(workspaceMock);
WorkflowInstance workflowInstance = getWorkflowInstance(mp, getDefaultConfiguration(true));
WorkflowOperationResult result = videoEditorWorkflowOperationHandler.start(workflowInstance, null);
Assert.assertNotNull(
"VideoEditor workflow operation returns null but should be an instantiated WorkflowOperationResult", result);
EasyMock.verify(workspaceMock);
WorkflowOperationInstance worflowOperationInstance = workflowInstance.getCurrentOperation();
String smillFlavorsProperty = worflowOperationInstance.getConfiguration("smil-flavors");
String previewFlavorsProperty = worflowOperationInstance.getConfiguration("preview-flavors");
MediaPackageElementFlavor smilFlavor = MediaPackageElementFlavor.parseFlavor(smillFlavorsProperty);
MediaPackageElementFlavor previewFlavor = MediaPackageElementFlavor.parseFlavor(previewFlavorsProperty);
// each preview track (e.g. presenter/preview) should have an own smil catalog in media package
Catalog[] previewSmilCatalogs = result.getMediaPackage().getCatalogs(
new MediaPackageElementFlavor("presenter", "smil"));
Assert.assertTrue(previewSmilCatalogs != null && previewSmilCatalogs.length > 0);
for (Track track : result.getMediaPackage().getTracks()) {
if (track.getFlavor().matches(previewFlavor)) {
boolean smilCatalogFound = false;
MediaPackageElementFlavor trackSmilFlavor = new MediaPackageElementFlavor(track.getFlavor().getType(),
smilFlavor.getSubtype());
for (Catalog previewSmilCatalog : previewSmilCatalogs) {
if (previewSmilCatalog.getFlavor().matches(trackSmilFlavor)) {
smilCatalogFound = true;
break;
}
}
Assert.assertTrue("Mediapackage doesn't contain a smil catalog with flavor " + trackSmilFlavor.toString(),
smilCatalogFound);
}
}
// an "target-smil-flavor catalog" schould be in media package
String targetSmilFlavorProperty = worflowOperationInstance.getConfiguration("target-smil-flavor");
Catalog[] episodeSmilCatalogs = result.getMediaPackage().getCatalogs(
MediaPackageElementFlavor.parseFlavor(targetSmilFlavorProperty));
Assert.assertTrue("Mediapackage should contain catalog with flavor " + targetSmilFlavorProperty,
episodeSmilCatalogs != null && episodeSmilCatalogs.length > 0);
Assert.assertTrue("Target smil catalog URI does not match",
episodeSmilCatalogs[0].getURI().compareTo(URI.create(episodeSmilUri)) == 0);
}
@Test
public void testEditorOperationSkip() throws WorkflowOperationException {
WorkflowInstance workflowInstance = getWorkflowInstance(mp, getDefaultConfiguration(true));
WorkflowOperationResult result = videoEditorWorkflowOperationHandler.skip(workflowInstance, null);
Assert.assertNotNull(
"VideoEditor workflow operation returns null but should be an instantiated WorkflowOperationResult", result);
// mediapackage should contain new derived track with flavor given by "target-flavor-subtype" configuration
WorkflowOperationInstance worflowOperationInstance = workflowInstance.getCurrentOperation();
String targetFlavorSubtypeProperty = worflowOperationInstance.getConfiguration("target-flavor-subtype");
String skippedFlavorsProperty = worflowOperationInstance.getConfiguration("skipped-flavors");
TrackSelector trackSelector = new TrackSelector();
trackSelector.addFlavor(skippedFlavorsProperty);
Collection<Track> skippedTracks = trackSelector.select(result.getMediaPackage(), false);
Assert.assertTrue("Mediapackage does not contain any tracks matching flavor " + skippedFlavorsProperty,
skippedTracks != null && !skippedTracks.isEmpty());
for (Track skippedTrack : skippedTracks) {
MediaPackageElementFlavor derivedTrackFlavor = MediaPackageElementFlavor.flavor(skippedTrack.getFlavor()
.getType(), targetFlavorSubtypeProperty);
MediaPackageElement[] derivedElements = result.getMediaPackage().getDerived(skippedTrack, derivedTrackFlavor);
Assert.assertTrue("Media package should contain track with flavor " + derivedTrackFlavor.toString(),
derivedElements != null && derivedElements.length > 0);
}
}
@Test
public void testEditorOperationInteractiveSkip() throws WorkflowOperationException {
WorkflowInstance workflowInstance = getWorkflowInstance(mp, getDefaultConfiguration(false));
WorkflowOperationResult result = videoEditorWorkflowOperationHandler.start(workflowInstance, null);
Assert.assertNotNull(
"VideoEditor workflow operation returns null but should be an instantiated WorkflowOperationResult", result);
// mediapackage should contain new derived track with flavor given by "target-flavor-subtype" configuration
WorkflowOperationInstance worflowOperationInstance = workflowInstance.getCurrentOperation();
String targetFlavorSubtypeProperty = worflowOperationInstance.getConfiguration("target-flavor-subtype");
String skippedFlavorsProperty = worflowOperationInstance.getConfiguration("skipped-flavors");
TrackSelector trackSelector = new TrackSelector();
trackSelector.addFlavor(skippedFlavorsProperty);
Collection<Track> skippedTracks = trackSelector.select(result.getMediaPackage(), false);
Assert.assertTrue("Mediapackage does not contain any tracks matching flavor " + skippedFlavorsProperty,
skippedTracks != null && !skippedTracks.isEmpty());
for (Track skippedTrack : skippedTracks) {
MediaPackageElementFlavor derivedTrackFlavor = MediaPackageElementFlavor.flavor(skippedTrack.getFlavor()
.getType(), targetFlavorSubtypeProperty);
MediaPackageElement[] derivedElements = result.getMediaPackage().getDerived(skippedTrack, derivedTrackFlavor);
Assert.assertTrue("Media package should contain track with flavor " + derivedTrackFlavor.toString(),
derivedElements != null && derivedElements.length > 0);
}
}
@Test
public void testEditorResume() throws WorkflowOperationException, URISyntaxException, NotFoundException, IOException,
ProcessFailedException, ServiceRegistryException, MediaPackageException {
// filled smil file
URI episodeSmilURI = VideoEditorWorkflowOperationHandlerTest.class.getResource("/editor_smil_filled.smil").toURI();
File episodeSmilFile = new File(episodeSmilURI);
// setup mock services
EasyMock.expect(workspaceMock.get((URI) EasyMock.anyObject())).andReturn(episodeSmilFile);
EasyMock.expect(
workspaceMock.put((String) EasyMock.anyObject(), (String) EasyMock.anyObject(),
(String) EasyMock.anyObject(), (InputStream) EasyMock.anyObject())).andReturn(episodeSmilURI);
EasyMock.expect(
workspaceMock.moveTo((URI) EasyMock.anyObject(), (String) EasyMock.anyObject(),
(String) EasyMock.anyObject(), (String) EasyMock.anyObject())).andReturn(
URI.create("http://localhost:8080/foo/trimmed.mp4"));
Job job = EasyMock.createNiceMock(Job.class);
EasyMock.expect(job.getPayload()).andReturn(MediaPackageElementParser.getAsXml(mpSmil.getTracks()[0])).anyTimes();
EasyMock.expect(job.getStatus()).andReturn(Job.Status.FINISHED);
ServiceRegistry serviceRegistry = EasyMock.createNiceMock(ServiceRegistry.class);
videoEditorWorkflowOperationHandler.setServiceRegistry(serviceRegistry);
EasyMock.expect(serviceRegistry.getJob(EasyMock.anyLong())).andReturn(job);
EasyMock.expect(videoEditorServiceMock.processSmil((Smil) EasyMock.anyObject())).andReturn(Arrays.asList(job));
EasyMock.replay(workspaceMock, job, serviceRegistry, videoEditorServiceMock);
WorkflowInstance workflowInstance = getWorkflowInstance(mpSmil, getDefaultConfiguration(true));
// run test
WorkflowOperationResult result = videoEditorWorkflowOperationHandler.resume(workflowInstance, null, null);
Assert.assertNotNull(
"VideoEditor workflow operation returns null but should be an instantiated WorkflowOperationResult", result);
EasyMock.verify(workspaceMock, job, serviceRegistry, videoEditorServiceMock);
// verify trimmed track derived from source track
WorkflowOperationInstance worflowOperationInstance = workflowInstance.getCurrentOperation();
String targetFlavorSubtypeProperty = worflowOperationInstance.getConfiguration("target-flavor-subtype");
String sourceFlavorsProperty = worflowOperationInstance.getConfiguration("source-flavors");
TrackSelector trackSelector = new TrackSelector();
trackSelector.addFlavor(sourceFlavorsProperty);
Collection<Track> sourceTracks = trackSelector.select(result.getMediaPackage(), false);
Assert.assertTrue("Mediapackage does not contain any tracks matching flavor " + sourceFlavorsProperty,
sourceTracks != null && !sourceTracks.isEmpty());
for (Track sourceTrack : sourceTracks) {
MediaPackageElementFlavor targetFlavor = MediaPackageElementFlavor.flavor(sourceTrack.getFlavor().getType(),
targetFlavorSubtypeProperty);
Track[] targetTracks = result.getMediaPackage().getTracks(targetFlavor);
Assert.assertTrue("Media package doesn't contain track with flavor " + targetFlavor.toString(),
targetTracks != null && targetTracks.length > 0);
}
}
}
| 53.052459 | 119 | 0.774427 |
1457b878a4a178d4bf9ed8fd838761201a1493c0 | 83 | package qub;
public enum VerticalAlignment
{
Top,
Center,
Bottom,
}
| 7.545455 | 29 | 0.626506 |
61b3953c87d5a1625e933c5bbfac4d2e0e5b3539 | 2,389 | /*
*
* Copyright 2012-2014 Eurocommercial Properties NV
*
*
* Licensed under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.estatio.fixture.lease.refdata;
import javax.inject.Inject;
import org.isisaddons.module.security.dom.tenancy.ApplicationTenancyRepository;
import org.estatio.dom.lease.LeaseType;
import org.estatio.dom.lease.LeaseTypes;
import org.estatio.fixture.EstatioFixtureScript;
public class LeaseTypeForItalyRefData extends EstatioFixtureScript {
private enum LeaseTypeData {
AA("Apparecchiature Automatic"),
AD("Affitto d'Azienda"),
CG("Comodato Gratuito"),
CO("Comodato"),
DH("Dehors"),
LO("Locazione"),
OA("Occup. Abusiva Affito"),
OL("Occup. Abusiva Locazione"),
PA("Progroga Affitto"),
PL("Progroga Locazione"),
PP("Pannelli Pubblicitari"),
PR("Precaria"),
SA("Scritt. Privata Affitto"),
SL("Scritt. Privata Locazione");
private final String title;
private LeaseTypeData(final String title) {
this.title = title;
}
public String title() {
return title;
}
}
@Override
protected void execute(ExecutionContext fixtureResults) {
for (LeaseTypeData ltd : LeaseTypeData.values()) {
createLeaseType(fixtureResults, ltd);
}
}
private void createLeaseType(ExecutionContext fixtureResults, LeaseTypeData ltd) {
final LeaseType leaseType = leaseTypes.findOrCreate(ltd.name(), ltd.title(), applicationTenancyRepository.findByPath("/ITA"));
fixtureResults.addResult(this, leaseType.getReference(), leaseType);
}
// //////////////////////////////////////
@Inject
private LeaseTypes leaseTypes;
@Inject
private ApplicationTenancyRepository applicationTenancyRepository;
}
| 29.8625 | 134 | 0.666806 |
5d01d7a0858edae55e7274293e4836ee794d086f | 1,406 | package com.rideaustin.service;
import java.util.Collections;
import javax.inject.Inject;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import com.rideaustin.model.Document;
import com.rideaustin.model.enums.DocumentType;
import com.rideaustin.model.ride.DriverType;
import com.rideaustin.model.user.Driver;
import com.rideaustin.repo.dsl.DocumentDslRepository;
import com.rideaustin.service.user.DriverTypeUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
@Slf4j
@Component
@RequiredArgsConstructor(onConstructor = @__(@Inject))
public class ChauffeurLicenseExpirationHandler implements DocumentExpirationHandler {
private final DocumentDslRepository documentDslRepository;
@Override
@Transactional
public void handle(Document document) {
Driver driver = documentDslRepository.findDriver(document);
if (driver == null) {
log.error(String.format("Exception: no driver found for document %d", document.getId()));
} else {
driver.setGrantedDriverTypesBitmask(driver.getGrantedDriverTypesBitmask() ^ DriverTypeUtils.toBitMask(Collections.singleton(DriverType.DIRECT_CONNECT)));
documentDslRepository.saveAny(driver);
}
}
@Override
public boolean supports(DocumentType documentType) {
return DocumentType.CHAUFFEUR_LICENSE.equals(documentType);
}
}
| 31.954545 | 159 | 0.803698 |
95e1cecbfbf0c94af1b35d40e479a4dd7d370045 | 154 | package pl.edu.agh.mobilecodereviewer.model;
/**
* Created by lee on 2014-09-13.
*/
public enum DiffLineType {
UNCHANGED,REMOVED, SKIPPED, ADDED
}
| 17.111111 | 44 | 0.714286 |
5236b251493657d139d8ce0600e1860c819983ab | 369 | package com.g2forge.reassert.core.model.contract.usage;
import lombok.Builder;
import lombok.Data;
import lombok.RequiredArgsConstructor;
/**
* Represent a usage we do not yet recognize, but have some kind of text for.
*/
@Data
@Builder(toBuilder = true)
@RequiredArgsConstructor
public class UnknownUsage implements IUsageApplied {
protected final String text;
}
| 23.0625 | 77 | 0.791328 |
fcfd26250ddb1a8a0433a4e9f0c38f5f090efe48 | 1,682 | // Copyright 2021 The Terasology Foundation
// SPDX-License-Identifier: Apache-2.0
package org.terasology.engine.module;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import org.terasology.module.ModuleLoader;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assumptions.assumeTrue;
import static org.terasology.engine.TerasologyConstants.MODULE_INFO_FILENAME;
public class ModuleManagerTest {
@ParameterizedTest
@ValueSource(strings = {
"testdummy-1.0.0-SNAPSHOT.jar",
"messy-name-directory & $t#f/testmessy-1.0.0-SNAPSHOT.jar"
})
void testLoadModuleFromURL(String jarLocation) throws IOException, URISyntaxException {
ModuleManagerImpl mm = new ThisModuleManager("");
ModuleLoader loader = new ModuleLoader();
loader.setModuleInfoPath(MODULE_INFO_FILENAME);
URL url = getClass().getResource("/org/terasology/engine/module/" + jarLocation);
assumeTrue(url != null, "test resource not found:" + jarLocation);
URL jarUrl = new URL("jar", null, url.toString() + "!/" + MODULE_INFO_FILENAME);
assertNotNull(mm.load(loader, jarUrl));
}
private static class ThisModuleManager extends ModuleManagerImpl {
ThisModuleManager(String masterServerAddress) {
super(masterServerAddress);
}
@Override
void loadModulesFromClassPath() {
// empty implementation so it doesn't fire everything off during the constructor
}
}
}
| 35.787234 | 92 | 0.718787 |
5a2813211b9049cf079869495083e349fee934ed | 3,967 | package com.google.android.gms.internal.ads;
import android.os.IInterface;
import android.os.Parcel;
import android.os.RemoteException;
import com.google.android.gms.dynamic.IObjectWrapper.Stub;
public abstract class zzzw extends zzfn implements zzzv {
public zzzw() {
super("com.google.android.gms.ads.internal.client.IClientApi");
}
/* access modifiers changed from: protected */
/* renamed from: a */
public final boolean mo29357a(int i, Parcel parcel, Parcel parcel2, int i2) throws RemoteException {
switch (i) {
case 1:
zzzk zza = zza(Stub.m22186a(parcel.readStrongBinder()), (zzyd) zzfo.m30220a(parcel, zzyd.CREATOR), parcel.readString(), zzamq.m25249a(parcel.readStrongBinder()), parcel.readInt());
parcel2.writeNoException();
zzfo.m30221a(parcel2, (IInterface) zza);
break;
case 2:
zzzk zzb = zzb(Stub.m22186a(parcel.readStrongBinder()), (zzyd) zzfo.m30220a(parcel, zzyd.CREATOR), parcel.readString(), zzamq.m25249a(parcel.readStrongBinder()), parcel.readInt());
parcel2.writeNoException();
zzfo.m30221a(parcel2, (IInterface) zzb);
break;
case 3:
zzzf zza2 = zza(Stub.m22186a(parcel.readStrongBinder()), parcel.readString(), zzamq.m25249a(parcel.readStrongBinder()), parcel.readInt());
parcel2.writeNoException();
zzfo.m30221a(parcel2, (IInterface) zza2);
break;
case 4:
zzaab zzg = zzg(Stub.m22186a(parcel.readStrongBinder()));
parcel2.writeNoException();
zzfo.m30221a(parcel2, (IInterface) zzg);
break;
case 5:
zzaem zzc = zzc(Stub.m22186a(parcel.readStrongBinder()), Stub.m22186a(parcel.readStrongBinder()));
parcel2.writeNoException();
zzfo.m30221a(parcel2, (IInterface) zzc);
break;
case 6:
zzasw zza3 = zza(Stub.m22186a(parcel.readStrongBinder()), zzamq.m25249a(parcel.readStrongBinder()), parcel.readInt());
parcel2.writeNoException();
zzfo.m30221a(parcel2, (IInterface) zza3);
break;
case 7:
zzaqq zzh = zzh(Stub.m22186a(parcel.readStrongBinder()));
parcel2.writeNoException();
zzfo.m30221a(parcel2, (IInterface) zzh);
break;
case 8:
zzaqg zzf = zzf(Stub.m22186a(parcel.readStrongBinder()));
parcel2.writeNoException();
zzfo.m30221a(parcel2, (IInterface) zzf);
break;
case 9:
zzaab zza4 = zza(Stub.m22186a(parcel.readStrongBinder()), parcel.readInt());
parcel2.writeNoException();
zzfo.m30221a(parcel2, (IInterface) zza4);
break;
case 10:
zzzk zza5 = zza(Stub.m22186a(parcel.readStrongBinder()), (zzyd) zzfo.m30220a(parcel, zzyd.CREATOR), parcel.readString(), parcel.readInt());
parcel2.writeNoException();
zzfo.m30221a(parcel2, (IInterface) zza5);
break;
case 11:
zzaer zza6 = zza(Stub.m22186a(parcel.readStrongBinder()), Stub.m22186a(parcel.readStrongBinder()), Stub.m22186a(parcel.readStrongBinder()));
parcel2.writeNoException();
zzfo.m30221a(parcel2, (IInterface) zza6);
break;
case 12:
zzatt zzb2 = zzb(Stub.m22186a(parcel.readStrongBinder()), parcel.readString(), zzamq.m25249a(parcel.readStrongBinder()), parcel.readInt());
parcel2.writeNoException();
zzfo.m30221a(parcel2, (IInterface) zzb2);
break;
default:
return false;
}
return true;
}
}
| 47.795181 | 196 | 0.574237 |
9db3c143d1e8d865e8cf3233b9c6f5e5e0ed980c | 871 | package com.danielme.jakartaee.jpa.dao;
import jakarta.persistence.EntityManager;
import java.util.Optional;
public class GenericDAOImpl<T, K> implements GenericDAO<T, K> {
private final EntityManager em;
private final Class<T> entityClass;
public GenericDAOImpl(EntityManager em, Class<T> entityClass) {
this.em = em;
this.entityClass = entityClass;
}
@Override
public Optional<T> findById(K id) {
return Optional.ofNullable(em.find(entityClass, id));
}
@Override
public void create(T entity) {
em.persist(entity);
}
@Override
public T save(T entity) {
return em.merge(entity);
}
@Override
public void deleteById(Long id) {
em.remove(em.find(entityClass, id));
}
@Override
public void delete(T entity) {
em.remove(entity);
}
}
| 20.255814 | 67 | 0.639495 |
5a964b950bd0499133c14286cc971306f94593cb | 1,585 | package com.lzf.flyingsocks.client.proxy.socks;
import com.lzf.flyingsocks.client.proxy.ProxyRequest;
import io.netty.buffer.ByteBuf;
import io.netty.channel.socket.DatagramChannel;
import java.net.InetSocketAddress;
import java.util.Objects;
/**
* UDP代理请求
*/
public final class DatagramProxyRequest extends ProxyRequest {
/**
* 来自客户端,去除包头的UDP消息
*/
private ByteBuf content;
/**
* UDP包的发送方
*/
private final InetSocketAddress sender;
DatagramProxyRequest(String ipAddr, int port, DatagramChannel channel, InetSocketAddress sender) {
super(Objects.requireNonNull(ipAddr), port, Objects.requireNonNull(channel), Protocol.UDP);
this.sender = Objects.requireNonNull(sender);
}
void setContent(ByteBuf content) {
this.content = content;
}
public InetSocketAddress senderAddress() {
return sender;
}
@Override
public DatagramChannel clientChannel() {
return (DatagramChannel)super.clientChannel();
}
@Override
public ByteBuf takeClientMessage() {
if(content != null) {
ByteBuf buf = content;
content = null;
return buf;
}
return null;
}
@Override
public boolean ensureMessageOnlyOne() {
return true;
}
@Override
public String toString() {
return "DatagramProxyRequest{" +
"sender=" + sender +
", host='" + host + '\'' +
", port=" + port +
", protocol=" + protocol +
'}';
}
}
| 23.308824 | 102 | 0.607571 |
8266ba41c36ed9178602d573fa7138d262670c2c | 3,053 | package tsuteto.tofu.eventhandler;
import cpw.mods.fml.common.eventhandler.Event;
import cpw.mods.fml.common.eventhandler.SubscribeEvent;
import net.minecraft.block.Block;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.world.World;
import net.minecraftforge.event.entity.player.BonemealEvent;
import tsuteto.tofu.achievement.TcAchievementMgr;
import tsuteto.tofu.achievement.TcAchievementMgr.Key;
import tsuteto.tofu.block.BlockLeek;
import tsuteto.tofu.block.BlockTcSapling;
import tsuteto.tofu.block.BlockTofuBase;
import tsuteto.tofu.init.TcBlocks;
import java.util.Random;
public class EventBonemeal
{
@SubscribeEvent
public void onBonemeal(BonemealEvent event)
{
EntityPlayer player = event.entityPlayer;
World world = event.world;
Random rand = world.rand;
Block block = event.block;
int posX = event.x;
int posY = event.y;
int posZ = event.z;
int var11;
int var12;
int var13;
// Saplings
if (block == TcBlocks.tcSapling)
{
if (!world.isRemote)
{
((BlockTcSapling) TcBlocks.tcSapling).growTree(world, posX, posY, posZ, world.rand);
}
event.setResult(Event.Result.ALLOW);
}
// Leek
if (block instanceof BlockTofuBase)
{
if (!world.isRemote)
{
label133:
for (var12 = 0; var12 < 32; ++var12)
{
var13 = posX;
int var14 = posY + 1;
int var15 = posZ;
for (int var16 = 0; var16 < var12 / 16; ++var16)
{
var13 += rand.nextInt(3) - 1;
var14 += (rand.nextInt(3) - 1) * rand.nextInt(3) / 2;
var15 += rand.nextInt(3) - 1;
if (!(world.getBlock(var13, var14 - 1, var15) instanceof BlockTofuBase) || world.getBlock(var13, var14, var15).isNormalCube())
{
continue label133;
}
}
if (world.isAirBlock(var13, var14, var15))
{
if (rand.nextInt(10) < 5)
{
if (TcBlocks.leek.canBlockStay(world, var13, var14, var15))
{
world.setBlock(var13, var14, var15, TcBlocks.leek, BlockLeek.META_NATURAL, 3);
TcAchievementMgr.achieve(player, Key.leek);
}
}
else
{
world.getBiomeGenForCoords(var13, var15).plantFlower(world, rand, var13, var14, var15);
}
}
}
}
event.setResult(Event.Result.ALLOW);
}
//event.setCanceled(false);
}
}
| 33.184783 | 150 | 0.497871 |
4aa691ef40ff64748cbb04d35231d0f2872f18ea | 1,812 | /*
* Copyright (c) 2020, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*
*/
package org.wso2.ei.dashboard.core.db.manager;
import org.wso2.ei.dashboard.core.commons.Constants;
import org.wso2.ei.dashboard.core.exception.DashboardServerException;
/**
* Manage databases.
*/
public class DatabaseManagerFactory {
private DatabaseManagerFactory() {
}
private static DatabaseManager databaseManager;
public static DatabaseManager getDbManager() {
if (databaseManager == null) {
String connectionUrl = Constants.DATABASE_URL;
String dbType = getDbType(connectionUrl);
databaseManager = getDatabaseManager(dbType);
}
return databaseManager;
}
public static DatabaseManager getDatabaseManager(String dbType) {
if ("jdbc".equals(dbType)) {
return new JDBCDatabaseManager();
}
throw new DashboardServerException("The database type " + dbType + " is not supported.");
}
private static String getDbType(String connectionUrl) {
String dbType = "";
if (connectionUrl.startsWith("jdbc")) {
dbType = "jdbc";
}
return dbType;
}
}
| 29.704918 | 97 | 0.676049 |
e11f7f23955df3152a24e9db7e9713c064f2abb2 | 1,445 | package life.genny.qwanda.payments.assembly;
import java.io.Serializable;
import com.google.gson.annotations.Expose;
public class QPaymentsAssemblyKYC implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
public enum UserKYCState {
//Waiting for information of the user to fulfil our KYC data requirements
pending,
//Information received, waiting for Assembly to Approve the KYC
pending_check,
//Stage 1 of the KYC is approved
approved_kyc_check,
//Stage 1 and underwriting of the user has been approved.
approved
}
@Expose
private UserKYCState verificationStatus;
@Expose
private Boolean heldState;
/**
* @return the verificationStatus
*/
public UserKYCState getVerificationStatus() {
return verificationStatus;
}
/**
* @param verificationStatus the verificationStatus to set
*/
public void setVerificationStatus(UserKYCState verificationStatus) {
this.verificationStatus = verificationStatus;
}
/**
* @return the heldState
*/
public Boolean getHeldState() {
return heldState;
}
/**
* @param heldState the heldState to set
*/
public void setHeldState(Boolean heldState) {
this.heldState = heldState;
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "QPaymentsAssemblyKYC [verificationStatus=" + verificationStatus + ", heldState=" + heldState + "]";
}
}
| 19.794521 | 109 | 0.722491 |
694c9350b228d24c481270a4e42ea63808ea3903 | 4,116 | /*
* Copyright (C) 2015 HaiYang Li
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.landawn.abacus.type;
import java.io.IOException;
import java.io.Writer;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import com.landawn.abacus.parser.SerializationConfig;
import com.landawn.abacus.util.CharacterWriter;
import com.landawn.abacus.util.IOUtil;
import com.landawn.abacus.util.N;
/**
*
* @author Haiyang Li
* @since 0.8
*/
public abstract class AbstractFloatType extends NumberType<Number> {
protected AbstractFloatType(String typeName) {
super(typeName);
}
/**
*
* @param x
* @return
*/
@Override
public String stringOf(Number x) {
if (x == null) {
return null;
}
return N.stringOf(x.floatValue());
}
/**
*
* @param st
* @return
*/
@Override
public Float valueOf(String st) {
try {
return N.isNullOrEmpty(st) ? ((Float) defaultValue()) : Float.valueOf(st);
} catch (NumberFormatException e) {
if (st.length() > 1) {
char ch = st.charAt(st.length() - 1);
if ((ch == 'l') || (ch == 'L') || (ch == 'f') || (ch == 'F') || (ch == 'd') || (ch == 'D')) {
return Float.valueOf(st.substring(0, st.length() - 1));
}
}
throw e;
}
}
/**
*
* @param rs
* @param columnIndex
* @return
* @throws SQLException the SQL exception
*/
@Override
public Float get(ResultSet rs, int columnIndex) throws SQLException {
return rs.getFloat(columnIndex);
}
/**
*
* @param rs
* @param columnLabel
* @return
* @throws SQLException the SQL exception
*/
@Override
public Float get(ResultSet rs, String columnLabel) throws SQLException {
return rs.getFloat(columnLabel);
}
/**
*
* @param stmt
* @param columnIndex
* @param x
* @throws SQLException the SQL exception
*/
@Override
public void set(PreparedStatement stmt, int columnIndex, Number x) throws SQLException {
stmt.setFloat(columnIndex, (x == null) ? 0 : x.floatValue());
}
/**
*
* @param stmt
* @param parameterName
* @param x
* @throws SQLException the SQL exception
*/
@Override
public void set(CallableStatement stmt, String parameterName, Number x) throws SQLException {
stmt.setFloat(parameterName, (x == null) ? 0 : x.floatValue());
}
/**
*
* @param writer
* @param x
* @throws IOException Signals that an I/O exception has occurred.
*/
@Override
public void write(Writer writer, Number x) throws IOException {
if (x == null) {
writer.write(NULL_CHAR_ARRAY);
} else {
IOUtil.write(writer, x.floatValue());
}
}
/**
*
* @param writer
* @param x
* @param config
* @throws IOException Signals that an I/O exception has occurred.
*/
@Override
public void writeCharacter(CharacterWriter writer, Number x, SerializationConfig<?> config) throws IOException {
if (x == null) {
writer.write(NULL_CHAR_ARRAY);
} else {
IOUtil.write(writer, x.floatValue());
}
}
}
| 26.554839 | 117 | 0.569485 |
c8a70283cfd59bb73d09072df4b937827f3eccce | 1,804 | package de.rieckpil.blog;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.oauth2.client.AuthorizationCodeOAuth2AuthorizedClientProvider;
import org.springframework.security.oauth2.client.OAuth2AuthorizedClientManager;
import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository;
import org.springframework.security.oauth2.client.web.DefaultOAuth2AuthorizedClientManager;
import org.springframework.security.oauth2.client.web.OAuth2AuthorizedClientRepository;
import org.springframework.security.oauth2.client.web.reactive.function.client.ServletOAuth2AuthorizedClientExchangeFilterFunction;
import org.springframework.web.reactive.function.client.WebClient;
@Configuration
public class WebClientConfig {
@Bean
public WebClient webClient(OAuth2AuthorizedClientManager authorizedClientManager) {
ServletOAuth2AuthorizedClientExchangeFilterFunction oauth =
new ServletOAuth2AuthorizedClientExchangeFilterFunction(authorizedClientManager);
return WebClient.builder()
.filter(oauth)
.build();
}
@Bean
public OAuth2AuthorizedClientManager authorizedClientManager(
ClientRegistrationRepository clientRegistrationRepository,
OAuth2AuthorizedClientRepository authorizedClientRepository) {
DefaultOAuth2AuthorizedClientManager authorizedClientManager =
new DefaultOAuth2AuthorizedClientManager(
clientRegistrationRepository, authorizedClientRepository);
authorizedClientManager.setAuthorizedClientProvider(new AuthorizationCodeOAuth2AuthorizedClientProvider());
return authorizedClientManager;
}
}
| 46.25641 | 131 | 0.806541 |
89f8e91b515c3064320d874971555f0ab88f2178 | 365 | package com.srch2;
/* User defined RefiningFloat that has a backing of Float class, rather
than the java float primitive. */
public class MyRefiningFloat implements RefiningFloatInterface {
Float value;
MyRefiningFloat(Float value) { this.value = value; }
public float getFloat() { return this.value; }
public Float getValue() { return this.value; }
}
| 30.416667 | 71 | 0.745205 |
0c37efaedb039a3f1ccc54032105385be605f2a0 | 4,188 | /*******************************************************************************
* Copyright 2011 Danny Kunz
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package org.omnaest.utils.streams;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import org.apache.commons.lang3.StringUtils;
import org.junit.Test;
import org.omnaest.utils.streams.StreamConnector.TransferResult;
import org.omnaest.utils.structure.container.ByteArrayContainer;
public class StreamConnectorTest
{
@Test
public void testConnectInputStreamStringBufferString()
{
//
String testString = "testßßßßßßüäöäöäöä##+#+~~~";
for ( int ii = 1; ii <= 10; ii++ )
{
testString += testString;
}
//
StringBuffer sb = new StringBuffer();
ByteArrayContainer firstBac = new ByteArrayContainer();
ByteArrayContainer secondBac = new ByteArrayContainer();
final String encoding = "utf-8";
try
{
StreamConnector.connect( new StringBuffer( testString ), firstBac.getOutputStream(), encoding );
StreamConnector.connect( firstBac.getInputStream(), secondBac.getOutputStream() );
StreamConnector.connect( secondBac.getInputStream(), sb, encoding );
}
catch ( IOException e )
{
fail();
}
//
assertEquals( testString, sb.toString() );
assertEquals( testString, secondBac.toString( encoding ) );
//
ByteArrayContainer directBac = new ByteArrayContainer();
directBac.copyFrom( testString );
assertEquals( testString, directBac.toString( encoding ) );
directBac.copyFrom( secondBac );
assertEquals( testString, directBac.toString( encoding ) );
File file = new File( "ByteArrayContainerTest.bin" );
directBac.writeTo( file );
directBac.clear();
assertNull( directBac.getContent() );
directBac.copyFrom( file );
file.delete();
assertEquals( testString, directBac.toString( encoding ) );
}
@Test
public void testZippedBac()
{
String test = "asdfsfjlkjflksjspoo9384584385094385943543=)?=)(=)098ß}]}]}[]}[{]{6[";
ByteArrayContainer testBac = new ByteArrayContainer();
testBac.copyFrom( test );
assertNotNull( testBac );
assertEquals( test, testBac.toString() );
testBac.zip();
assertTrue( !StringUtils.equals( test, testBac.toString() ) );
testBac.unzip();
assertEquals( test, testBac.toString() );
}
@Test
public void testTransfer()
{
//
String sourceContent = "asdfsfjlßßß+ö#äö#äöäö#äö@@@@µµµµµ";
//
InputStream inputStream = new ByteArrayInputStream( sourceContent.getBytes() );
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
//
TransferResult transferResult = StreamConnector.transfer( inputStream, outputStream );
//
assertTrue( transferResult.isSuccessful() );
assertEquals( null, transferResult.getException() );
assertEquals( sourceContent.getBytes().length, transferResult.getTransferSizeInBytes() );
//
String destinationContent = outputStream.toString();
assertEquals( sourceContent, destinationContent );
}
}
| 32.465116 | 103 | 0.651385 |
05be8f2fcd39b4b5f07ab53d27abea912f9208dd | 1,105 | package com.nishitp;
import java.util.List;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.nishitp.optiondata.dao.DBDao;
import com.nishitp.optiondata.dao.MySqlDao;
import com.nishitp.optiondata.scraper.OptionDataRetriever;
import com.nishitp.otpiondata.beans.Pair;
public class App {
public static void main(String[] args) throws Exception {
long start = System.currentTimeMillis();
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
"applicationContext.xml");
OptionDataRetriever retriever = (OptionDataRetriever) context.getBean(OptionDataRetriever.class);
DBDao dbInserter = (MySqlDao) context.getBean(MySqlDao.class);
List<Pair<String, String>> urls = retriever.fetchDom();
for (Pair<String, String> urlSymbolPair : urls) {
System.out.println("URL IS : " + urlSymbolPair.getUrl());
dbInserter.insertData(retriever.fetchData(urlSymbolPair.getUrl(), urlSymbolPair.getSymbol()));
}
long end = System.currentTimeMillis();
System.out.println("Total Time is : " + (end - start));
context.close();
}
}
| 33.484848 | 99 | 0.770136 |
e4fb08f7be409fb074aab6c0016b95b9f4ef8fd1 | 18,591 | package ca.uhn.fhir.jpa.patch;
/*-
* #%L
* HAPI FHIR JPA Server
* %%
* Copyright (C) 2014 - 2022 Smile CDR, Inc.
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
import ca.uhn.fhir.i18n.Msg;
import ca.uhn.fhir.context.BaseRuntimeChildDefinition;
import ca.uhn.fhir.context.BaseRuntimeElementCompositeDefinition;
import ca.uhn.fhir.context.BaseRuntimeElementDefinition;
import ca.uhn.fhir.context.FhirContext;
import ca.uhn.fhir.parser.path.EncodeContextPath;
import ca.uhn.fhir.rest.server.exceptions.InvalidRequestException;
import ca.uhn.fhir.util.IModelVisitor2;
import ca.uhn.fhir.util.ParametersUtil;
import org.apache.commons.lang3.Validate;
import org.hl7.fhir.instance.model.api.IBase;
import org.hl7.fhir.instance.model.api.IBaseEnumeration;
import org.hl7.fhir.instance.model.api.IBaseExtension;
import org.hl7.fhir.instance.model.api.IBaseParameters;
import org.hl7.fhir.instance.model.api.IBaseResource;
import org.hl7.fhir.instance.model.api.IIdType;
import org.hl7.fhir.instance.model.api.IPrimitiveType;
import org.hl7.fhir.utilities.xhtml.XhtmlNode;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import static org.apache.commons.lang3.StringUtils.defaultString;
import static org.apache.commons.lang3.StringUtils.isNotBlank;
public class FhirPatch {
private final FhirContext myContext;
private boolean myIncludePreviousValueInDiff;
private Set<EncodeContextPath> myIgnorePaths = Collections.emptySet();
public FhirPatch(FhirContext theContext) {
myContext = theContext;
}
/**
* Adds a path element that will not be included in generated diffs. Values can take the form
* <code>ResourceName.fieldName.fieldName</code> and wildcards are supported, such
* as <code>*.meta</code>.
*/
public void addIgnorePath(String theIgnorePath) {
Validate.notBlank(theIgnorePath, "theIgnorePath must not be null or empty");
if (myIgnorePaths.isEmpty()) {
myIgnorePaths = new HashSet<>();
}
myIgnorePaths.add(new EncodeContextPath(theIgnorePath));
}
public void setIncludePreviousValueInDiff(boolean theIncludePreviousValueInDiff) {
myIncludePreviousValueInDiff = theIncludePreviousValueInDiff;
}
public void apply(IBaseResource theResource, IBaseResource thePatch) {
List<IBase> opParameters = ParametersUtil.getNamedParameters(myContext, thePatch, "operation");
for (IBase nextOp : opParameters) {
String type = ParametersUtil.getParameterPartValueAsString(myContext, nextOp, "type");
String path = ParametersUtil.getParameterPartValueAsString(myContext, nextOp, "path");
Optional<IBase> valuePart = ParametersUtil.getParameterPart(myContext, nextOp, "value");
Optional<IBase> valuePartValue = ParametersUtil.getParameterPartValue(myContext, nextOp, "value");
type = defaultString(type);
path = defaultString(path);
String containingPath;
String elementName;
Integer removeIndex = null;
Integer insertIndex = null;
if ("delete".equals(type)) {
doDelete(theResource, path);
return;
} else if ("add".equals(type)) {
containingPath = path;
elementName = ParametersUtil.getParameterPartValueAsString(myContext, nextOp, "name");
} else if ("replace".equals(type)) {
int lastDot = path.lastIndexOf(".");
containingPath = path.substring(0, lastDot);
elementName = path.substring(lastDot + 1);
} else if ("insert".equals(type)) {
int lastDot = path.lastIndexOf(".");
containingPath = path.substring(0, lastDot);
elementName = path.substring(lastDot + 1);
insertIndex = ParametersUtil
.getParameterPartValue(myContext, nextOp, "index")
.map(t -> (IPrimitiveType<Integer>) t)
.map(t -> t.getValue())
.orElseThrow(() -> new InvalidRequestException("No index supplied for insert operation"));
} else if ("move".equals(type)) {
int lastDot = path.lastIndexOf(".");
containingPath = path.substring(0, lastDot);
elementName = path.substring(lastDot + 1);
insertIndex = ParametersUtil
.getParameterPartValue(myContext, nextOp, "destination")
.map(t -> (IPrimitiveType<Integer>) t)
.map(t -> t.getValue())
.orElseThrow(() -> new InvalidRequestException("No index supplied for insert operation"));
removeIndex = ParametersUtil
.getParameterPartValue(myContext, nextOp, "source")
.map(t -> (IPrimitiveType<Integer>) t)
.map(t -> t.getValue())
.orElseThrow(() -> new InvalidRequestException("No index supplied for insert operation"));
} else {
throw new InvalidRequestException(Msg.code(1267) + "Unknown patch operation type: " + type);
}
List<IBase> paths = myContext.newFhirPath().evaluate(theResource, containingPath, IBase.class);
for (IBase next : paths) {
BaseRuntimeElementDefinition<?> elementDef = myContext.getElementDefinition(next.getClass());
String childName = elementName;
BaseRuntimeChildDefinition childDef = elementDef.getChildByName(childName);
BaseRuntimeElementDefinition<?> childElement;
if (childDef == null) {
childName = elementName + "[x]";
childDef = elementDef.getChildByName(childName);
childElement = childDef.getChildByName(childDef.getValidChildNames().iterator().next());
} else {
childElement = childDef.getChildByName(childName);
}
if ("move".equals(type)) {
List<IBase> existingValues = new ArrayList<>(childDef.getAccessor().getValues(next));
if (removeIndex == null || removeIndex >= existingValues.size()) {
String msg = myContext.getLocalizer().getMessage(FhirPatch.class, "invalidMoveSourceIndex", removeIndex, path, existingValues.size());
throw new InvalidRequestException(Msg.code(1268) + msg);
}
IBase newValue = existingValues.remove(removeIndex.intValue());
if (insertIndex == null || insertIndex > existingValues.size()) {
String msg = myContext.getLocalizer().getMessage(FhirPatch.class, "invalidMoveDestinationIndex", insertIndex, path, existingValues.size());
throw new InvalidRequestException(Msg.code(1269) + msg);
}
existingValues.add(insertIndex, newValue);
childDef.getMutator().setValue(next, null);
for (IBase nextNewValue : existingValues) {
childDef.getMutator().addValue(next, nextNewValue);
}
continue;
}
IBase newValue;
if (valuePartValue.isPresent()) {
newValue = valuePartValue.get();
} else {
newValue = childElement.newInstance();
if (valuePart.isPresent()) {
List<IBase> valuePartParts = myContext.newTerser().getValues(valuePart.get(), "part");
for (IBase nextValuePartPart : valuePartParts) {
String name = myContext.newTerser().getSingleValue(nextValuePartPart, "name", IPrimitiveType.class).map(t -> t.getValueAsString()).orElse(null);
if (isNotBlank(name)) {
Optional<IBase> value = myContext.newTerser().getSingleValue(nextValuePartPart, "value[x]", IBase.class);
if (value.isPresent()) {
BaseRuntimeChildDefinition partChildDef = childElement.getChildByName(name);
partChildDef.getMutator().addValue(newValue, value.get());
}
}
}
}
}
if (IBaseEnumeration.class.isAssignableFrom(childElement.getImplementingClass()) || XhtmlNode.class.isAssignableFrom(childElement.getImplementingClass())) {
// If the compositeElementDef is an IBaseEnumeration, we will use the actual compositeElementDef definition to build one, since
// it needs the right factory object passed to its constructor
IPrimitiveType<?> newValueInstance = (IPrimitiveType<?>) childElement.newInstance();
newValueInstance.setValueAsString(((IPrimitiveType<?>) newValue).getValueAsString());
childDef.getMutator().setValue(next, newValueInstance);
newValue = newValueInstance;
}
if ("insert".equals(type)) {
List<IBase> existingValues = new ArrayList<>(childDef.getAccessor().getValues(next));
if (insertIndex == null || insertIndex > existingValues.size()) {
String msg = myContext.getLocalizer().getMessage(FhirPatch.class, "invalidInsertIndex", insertIndex, path, existingValues.size());
throw new InvalidRequestException(Msg.code(1270) + msg);
}
existingValues.add(insertIndex, newValue);
childDef.getMutator().setValue(next, null);
for (IBase nextNewValue : existingValues) {
childDef.getMutator().addValue(next, nextNewValue);
}
} else {
childDef.getMutator().setValue(next, newValue);
}
}
}
}
private void doDelete(IBaseResource theResource, String thePath) {
List<IBase> paths = myContext.newFhirPath().evaluate(theResource, thePath, IBase.class);
for (IBase next : paths) {
myContext.newTerser().visit(next, new IModelVisitor2() {
@Override
public boolean acceptElement(IBase theElement, List<IBase> theContainingElementPath, List<BaseRuntimeChildDefinition> theChildDefinitionPath, List<BaseRuntimeElementDefinition<?>> theElementDefinitionPath) {
if (theElement instanceof IPrimitiveType) {
((IPrimitiveType<?>) theElement).setValueAsString(null);
}
return true;
}
@Override
public boolean acceptUndeclaredExtension(IBaseExtension<?, ?> theNextExt, List<IBase> theContainingElementPath, List<BaseRuntimeChildDefinition> theChildDefinitionPath, List<BaseRuntimeElementDefinition<?>> theElementDefinitionPath) {
theNextExt.setUrl(null);
theNextExt.setValue(null);
return true;
}
});
}
}
public IBaseParameters diff(@Nullable IBaseResource theOldValue, @Nonnull IBaseResource theNewValue) {
IBaseParameters retVal = ParametersUtil.newInstance(myContext);
String newValueTypeName = myContext.getResourceDefinition(theNewValue).getName();
if (theOldValue == null) {
IBase operation = ParametersUtil.addParameterToParameters(myContext, retVal, "operation");
ParametersUtil.addPartCode(myContext, operation, "type", "insert");
ParametersUtil.addPartString(myContext, operation, "path", newValueTypeName);
ParametersUtil.addPart(myContext, operation, "value", theNewValue);
} else {
String oldValueTypeName = myContext.getResourceDefinition(theOldValue).getName();
Validate.isTrue(oldValueTypeName.equalsIgnoreCase(newValueTypeName), "Resources must be of same type");
BaseRuntimeElementCompositeDefinition<?> def = myContext.getResourceDefinition(theOldValue).getBaseDefinition();
String path = def.getName();
EncodeContextPath contextPath = new EncodeContextPath();
contextPath.pushPath(path, true);
compare(retVal, contextPath, def, path, path, theOldValue, theNewValue);
contextPath.popPath();
assert contextPath.getPath().isEmpty();
}
return retVal;
}
private void compare(IBaseParameters theDiff, EncodeContextPath theSourceEncodeContext, BaseRuntimeElementDefinition<?> theDef, String theSourcePath, String theTargetPath, IBase theOldField, IBase theNewField) {
boolean pathIsIgnored = pathIsIgnored(theSourceEncodeContext);
if (pathIsIgnored) {
return;
}
BaseRuntimeElementDefinition<?> sourceDef = myContext.getElementDefinition(theOldField.getClass());
BaseRuntimeElementDefinition<?> targetDef = myContext.getElementDefinition(theNewField.getClass());
if (!sourceDef.getName().equals(targetDef.getName())) {
IBase operation = ParametersUtil.addParameterToParameters(myContext, theDiff, "operation");
ParametersUtil.addPartCode(myContext, operation, "type", "replace");
ParametersUtil.addPartString(myContext, operation, "path", theTargetPath);
addValueToDiff(operation, theOldField, theNewField);
} else {
if (theOldField instanceof IPrimitiveType) {
IPrimitiveType<?> oldPrimitive = (IPrimitiveType<?>) theOldField;
IPrimitiveType<?> newPrimitive = (IPrimitiveType<?>) theNewField;
String oldValueAsString = toValue(oldPrimitive);
String newValueAsString = toValue(newPrimitive);
if (!Objects.equals(oldValueAsString, newValueAsString)) {
IBase operation = ParametersUtil.addParameterToParameters(myContext, theDiff, "operation");
ParametersUtil.addPartCode(myContext, operation, "type", "replace");
ParametersUtil.addPartString(myContext, operation, "path", theTargetPath);
addValueToDiff(operation, oldPrimitive, newPrimitive);
}
}
List<BaseRuntimeChildDefinition> children = theDef.getChildren();
for (BaseRuntimeChildDefinition nextChild : children) {
compareField(theDiff, theSourceEncodeContext, theSourcePath, theTargetPath, theOldField, theNewField, nextChild);
}
}
}
private void compareField(IBaseParameters theDiff, EncodeContextPath theSourceEncodePath, String theSourcePath, String theTargetPath, IBase theOldField, IBase theNewField, BaseRuntimeChildDefinition theChildDef) {
String elementName = theChildDef.getElementName();
boolean repeatable = theChildDef.getMax() != 1;
theSourceEncodePath.pushPath(elementName, false);
if (pathIsIgnored(theSourceEncodePath)) {
theSourceEncodePath.popPath();
return;
}
List<? extends IBase> sourceValues = theChildDef.getAccessor().getValues(theOldField);
List<? extends IBase> targetValues = theChildDef.getAccessor().getValues(theNewField);
int sourceIndex = 0;
int targetIndex = 0;
while (sourceIndex < sourceValues.size() && targetIndex < targetValues.size()) {
IBase sourceChildField = sourceValues.get(sourceIndex);
Validate.notNull(sourceChildField); // not expected to happen, but just in case
BaseRuntimeElementDefinition<?> def = myContext.getElementDefinition(sourceChildField.getClass());
IBase targetChildField = targetValues.get(targetIndex);
Validate.notNull(targetChildField); // not expected to happen, but just in case
String sourcePath = theSourcePath + "." + elementName + (repeatable ? "[" + sourceIndex + "]" : "");
String targetPath = theSourcePath + "." + elementName + (repeatable ? "[" + targetIndex + "]" : "");
compare(theDiff, theSourceEncodePath, def, sourcePath, targetPath, sourceChildField, targetChildField);
sourceIndex++;
targetIndex++;
}
// Find newly inserted items
while (targetIndex < targetValues.size()) {
String path = theTargetPath + "." + elementName;
addInsertItems(theDiff, targetValues, targetIndex, path, theChildDef);
targetIndex++;
}
// Find deleted items
while (sourceIndex < sourceValues.size()) {
IBase operation = ParametersUtil.addParameterToParameters(myContext, theDiff, "operation");
ParametersUtil.addPartCode(myContext, operation, "type", "delete");
ParametersUtil.addPartString(myContext, operation, "path", theTargetPath + "." + elementName + (repeatable ? "[" + targetIndex + "]" : ""));
sourceIndex++;
targetIndex++;
}
theSourceEncodePath.popPath();
}
private void addInsertItems(IBaseParameters theDiff, List<? extends IBase> theTargetValues, int theTargetIndex, String thePath, BaseRuntimeChildDefinition theChildDefinition) {
IBase operation = ParametersUtil.addParameterToParameters(myContext, theDiff, "operation");
ParametersUtil.addPartCode(myContext, operation, "type", "insert");
ParametersUtil.addPartString(myContext, operation, "path", thePath);
ParametersUtil.addPartInteger(myContext, operation, "index", theTargetIndex);
IBase value = theTargetValues.get(theTargetIndex);
BaseRuntimeElementDefinition<?> valueDef = myContext.getElementDefinition(value.getClass());
/*
* If the value is a Resource or a datatype, we can put it into the part.value and that will cover
* all of its children. If it's an infrastructure element though, such as Patient.contact we can't
* just put it into part.value because it isn't an actual type. So we have to put all of its
* childen in instead.
*/
if (valueDef.isStandardType()) {
ParametersUtil.addPart(myContext, operation, "value", value);
} else {
for (BaseRuntimeChildDefinition nextChild : valueDef.getChildren()) {
List<IBase> childValues = nextChild.getAccessor().getValues(value);
for (int index = 0; index < childValues.size(); index++) {
boolean childRepeatable = theChildDefinition.getMax() != 1;
String elementName = nextChild.getChildNameByDatatype(childValues.get(index).getClass());
String targetPath = thePath + (childRepeatable ? "[" + index + "]" : "") + "." + elementName;
addInsertItems(theDiff, childValues, index, targetPath, nextChild);
}
}
}
}
private void addValueToDiff(IBase theOperationPart, IBase theOldValue, IBase theNewValue) {
if (myIncludePreviousValueInDiff) {
IBase oldValue = massageValueForDiff(theOldValue);
ParametersUtil.addPart(myContext, theOperationPart, "previousValue", oldValue);
}
IBase newValue = massageValueForDiff(theNewValue);
ParametersUtil.addPart(myContext, theOperationPart, "value", newValue);
}
private boolean pathIsIgnored(EncodeContextPath theSourceEncodeContext) {
boolean pathIsIgnored = false;
for (EncodeContextPath next : myIgnorePaths) {
if (theSourceEncodeContext.startsWith(next, false)) {
pathIsIgnored = true;
break;
}
}
return pathIsIgnored;
}
private IBase massageValueForDiff(IBase theNewValue) {
// XHTML content is dealt with by putting it in a string
if (theNewValue instanceof XhtmlNode) {
String xhtmlString = ((XhtmlNode) theNewValue).getValueAsString();
theNewValue = myContext.getElementDefinition("string").newInstance(xhtmlString);
}
// IIdType can hold a fully qualified ID, but we just want the ID part to show up in diffs
if (theNewValue instanceof IIdType) {
String idPart = ((IIdType) theNewValue).getIdPart();
theNewValue = myContext.getElementDefinition("id").newInstance(idPart);
}
return theNewValue;
}
private String toValue(IPrimitiveType<?> theOldPrimitive) {
if (theOldPrimitive instanceof IIdType) {
return ((IIdType) theOldPrimitive).getIdPart();
}
return theOldPrimitive.getValueAsString();
}
}
| 39.980645 | 238 | 0.739336 |
c162af1273df39bf7edfcc22e6946d7b0dbc213f | 2,758 | package com.github.chenxdGit.common.util;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.lang3.StringUtils;
/**
* 字符串工具类
* @author 陈晓东
*
*/
public class StringUtil extends StringUtils {
public static String getMD5String(String str) {
try {
// 生成一个MD5加密计算摘要
MessageDigest md = MessageDigest.getInstance("MD5");
// 计算md5函数
md.update(str.getBytes());
return new BigInteger(1, md.digest()).toString(16);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* 驼峰 转下划线
* @param camelCase
* @return
*/
public static String toLine(String camelCase){
Pattern humpPattern = Pattern.compile("[A-Z]");
Matcher matcher = humpPattern.matcher(camelCase);
StringBuffer sb = new StringBuffer();
while(matcher.find()){
matcher.appendReplacement(sb, "_"+matcher.group(0).toLowerCase());
}
matcher.appendTail(sb);
return sb.toString();
}
public static String filter(String str){
if(str == null || str.length() == 0){
return "";
}
StringBuffer sb = new StringBuffer();
for(int i=0;i<str.length();i++){
int ch = str.charAt(i);
int min = Integer.parseInt("E001", 16);
int max = Integer.parseInt("E537", 16);
if(ch >= min && ch <= max){
sb.append("");
}else{
sb.append((char)ch);
}
}
return sb.toString();
}
/**
* 过滤昵称特殊表情
*/
public static String filterName(String name) {
if(isNoneEmpty(name)){
return name;
}
Pattern patter = Pattern.compile("[a-zA-Z0-9\u4e00-\u9fa5]");
Matcher match = patter.matcher(name);
StringBuffer buffer = new StringBuffer();
while (match.find()) {
buffer.append(match.group());
}
String str=buffer.toString();
String newName=filter(str);
return newName;
}
/**
* 判断为空
* @param object
* @return
*/
public static boolean isNull(Object object){
String b=String.valueOf(object);
if(b!=null) {
b = b.trim();
}
String a = new String();
if(b==null|| b.equals("") || b.equals(a) || b.equals("null")){
return true;
}
return false;
}
/**
* 判断为非空
* @param object
* @return
*/
public static boolean isNotNull(Object object){
return !isNull(object);
}
public static void main(String[]args){
Object b=" ";
System.out.println(isNull(b));
}
} | 23.982609 | 77 | 0.549311 |
f9b956c961662e28a91adece2ada4b6241d41cdc | 6,809 | /* Copyright 2018-2019 Wehe Web Technologies
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.wwt.tools.mathtools.function;
import java.util.Arrays;
/**
* Immutable implementation of Polynomial as double array of coefficients
* @author benw@wwt
*/
public class ArrayPolynomial implements Polynomial {
private final double [] coefficients;
private int hashCode;
/**
* protected constructor for subclassing, so that the implementation can be extended with new operations
* For creation use the static factory method.
* @param coefficients
*/
@SuppressWarnings("WeakerAccess")
protected ArrayPolynomial(double [] coefficients) {
this.coefficients = coefficients;
}
/**
* Implementation with Horner Schema
* @param x
* @return
*/
@Override
public double f(double x) {
double value=coefficients[coefficients.length-1];
for(int i=coefficients.length-2;i>=0;i--) {
value = value * x + coefficients[i] ;
}
return value;
}
@Override
public int getDegree() {
for(int i = coefficients.length-1;i>= 0; i--) {
if(coefficients[i] != 0) {
return i;
}
}
return 0;
}
@Override
public double getCoefficient(int degree){
if(degree > coefficients.length-1 || degree < 0) {
return 0;
}
return coefficients[degree];
}
@Override
public Polynomial normalize() {
ArrayPolynomial returnValue = this.constructReturnValue();
double tmp = returnValue.coefficients[returnValue.coefficients.length-1];
for(int i=0;i<returnValue.coefficients.length-1;i++) {
if(returnValue.coefficients[i] != 0) {
returnValue.coefficients[i] /= tmp;
}
}
returnValue.coefficients[returnValue.coefficients.length-1]=1;
return returnValue;
}
@Override
public Polynomial multiplyScalar(double scalar) {
ArrayPolynomial returnValue = this.constructReturnValue();
for(int i=0;i<returnValue.coefficients.length;i++) {
returnValue.coefficients[i] *= scalar;
}
return returnValue;
}
@Override
public Polynomial differentiate() {
double [] derivative =new double[coefficients.length-1];
for(int i=0;i<derivative.length;i++){
derivative[i] = coefficients[i+1]*(double)(i+1);
}
return ArrayPolynomial.from(derivative);
}
@Override
public Polynomial add(Polynomial p2) {
double [] addedCoefficients = new double[Math.max(this.getDegree(),p2.getDegree())+1];
for(int i = 0;i<addedCoefficients.length;i++) {
addedCoefficients[i] = this.getCoefficient(i) + p2.getCoefficient(i);
}
return ArrayPolynomial.from(addedCoefficients);
}
@Override
public Polynomial subtract(Polynomial p2) {
double [] addedCoefficients = new double[Math.max(this.getDegree(),p2.getDegree())+1];
for(int i = 0;i<addedCoefficients.length;i++) {
addedCoefficients[i] = this.getCoefficient(i) - p2.getCoefficient(i);
}
return ArrayPolynomial.from(addedCoefficients);
}
@Override
public Polynomial multiply(Polynomial p2) {
double [] multipliedCoefficients=new double[this.getDegree()+p2.getDegree()+1];
for(int i=0;i<=this.getDegree();i++) {
for(int j=0;j<=p2.getDegree();j++) {
multipliedCoefficients[i+j] += this.getCoefficient(i)*p2.getCoefficient(j);
}
}
return ArrayPolynomial.from(multipliedCoefficients);
}
@Override
public String toString() {
StringBuilder s = new StringBuilder("[");
for(int i = coefficients.length-1;i>= 2; i--) {
if(coefficients[i] != 0) {
if(s.length()>1) s.append("+");
s.append(coefficients[i]).append("*x^").append(i);
}
}
if(coefficients.length> 1 && coefficients[1] != 0 ) {
s.append("+").append(coefficients[1]).append("*x");
}
if(coefficients[0] != 0 ) s.append("+").append(coefficients[0]);
s.append("]");
return s.toString();
}
@Override
public boolean equals(Object other){
if (other == null) return false;
if (other == this) return true;
if (!(other instanceof Polynomial))return false;
Polynomial v = (Polynomial) other;
if (v.getDegree() != this.getDegree()) return false;
for (int i = 0; i <= this.getDegree(); i++) {
if(this.getCoefficient(i) != v.getCoefficient(i)) return false;
}
return(true);
}
@Override
public int hashCode() {
int result = hashCode;
if(hashCode == 0) {
for (int i = 0; i <= this.getDegree(); i++) {
result = result * 31 + Double.hashCode(this.getCoefficient(i));
}
hashCode = result;
}
return result;
}
/**
* Exposed public for storage optimization
*
* @return
*/
public final ArrayPolynomial shrinkArray() {
if(coefficients[coefficients.length-1] != 0) {
return this;
}
else return (ArrayPolynomial) ArrayPolynomial.from(coefficients);
}
private ArrayPolynomial constructReturnValue() {
if (coefficients[coefficients.length-1] == 0) {
return this.shrinkArray();
}
else {
double [] coefficientsCopy = Arrays.copyOf(coefficients,coefficients.length);
return new ArrayPolynomial(coefficientsCopy);
}
}
/**
* Please note that a copy of the input array is created to guarantee immutability
*
* @param coefficients
* @return
*/
public static Polynomial from(double [] coefficients) {
int newSize = 1;
for(int i = coefficients.length-1;i>= 0; i--) {
if(coefficients[i] != 0) {
newSize = i+1;
break;
}
}
double [] coefficientsCopy = Arrays.copyOf(coefficients,newSize);
return new ArrayPolynomial(coefficientsCopy);
}
}
| 30.95 | 108 | 0.595682 |
2f29f81b235a1e04f8f31adf1039d5b137279aa2 | 198 | for(int i = 0; i < a.length; i++) {
for(int j = 0; j < a.length; j++) {
for(int k = 0; k < a.length; k++) {
a[j][k] = a[j][k] || (a[j][i] && a[i][k]);
}
}
} | 28.285714 | 55 | 0.318182 |
49f4585a7e49744b7f66f0334f3d36278e2cf10b | 14,232 | begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1
begin_comment
comment|/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */
end_comment
begin_package
package|package
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|hive
operator|.
name|serde2
operator|.
name|columnar
package|;
end_package
begin_import
import|import
name|java
operator|.
name|io
operator|.
name|IOException
import|;
end_import
begin_import
import|import
name|java
operator|.
name|util
operator|.
name|ArrayList
import|;
end_import
begin_import
import|import
name|java
operator|.
name|util
operator|.
name|List
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|hive
operator|.
name|serde2
operator|.
name|SerDeStatsStruct
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|hive
operator|.
name|serde2
operator|.
name|StructObject
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|hive
operator|.
name|serde2
operator|.
name|lazy
operator|.
name|ByteArrayRef
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|hive
operator|.
name|serde2
operator|.
name|lazy
operator|.
name|LazyObjectBase
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|hive
operator|.
name|serde2
operator|.
name|objectinspector
operator|.
name|ObjectInspector
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|hive
operator|.
name|serde2
operator|.
name|objectinspector
operator|.
name|StructField
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|hive
operator|.
name|serde2
operator|.
name|objectinspector
operator|.
name|StructObjectInspector
import|;
end_import
begin_class
specifier|public
specifier|abstract
class|class
name|ColumnarStructBase
implements|implements
name|StructObject
implements|,
name|SerDeStatsStruct
block|{
class|class
name|FieldInfo
block|{
name|LazyObjectBase
name|field
decl_stmt|;
comment|/* * use an array instead of only one object in case in future hive does not do * the byte copy. */
name|ByteArrayRef
name|cachedByteArrayRef
decl_stmt|;
name|BytesRefWritable
name|rawBytesField
decl_stmt|;
name|boolean
name|inited
decl_stmt|;
name|boolean
name|fieldSkipped
decl_stmt|;
name|ObjectInspector
name|objectInspector
decl_stmt|;
specifier|public
name|FieldInfo
parameter_list|(
name|LazyObjectBase
name|lazyObject
parameter_list|,
name|boolean
name|fieldSkipped
parameter_list|,
name|ObjectInspector
name|oi
parameter_list|)
block|{
name|field
operator|=
name|lazyObject
expr_stmt|;
name|cachedByteArrayRef
operator|=
operator|new
name|ByteArrayRef
argument_list|()
expr_stmt|;
name|objectInspector
operator|=
name|oi
expr_stmt|;
if|if
condition|(
name|fieldSkipped
condition|)
block|{
name|this
operator|.
name|fieldSkipped
operator|=
literal|true
expr_stmt|;
name|inited
operator|=
literal|true
expr_stmt|;
block|}
else|else
block|{
name|inited
operator|=
literal|false
expr_stmt|;
block|}
block|}
comment|/* * ============================ [PERF] =================================== * This function is called for every row. Setting up the selected/projected * columns at the first call, and don't do that for the following calls. * Ideally this should be done in the constructor where we don't need to * branch in the function for each row. * ========================================================================= */
specifier|public
name|void
name|init
parameter_list|(
name|BytesRefWritable
name|col
parameter_list|)
block|{
if|if
condition|(
name|col
operator|!=
literal|null
condition|)
block|{
name|rawBytesField
operator|=
name|col
expr_stmt|;
name|inited
operator|=
literal|false
expr_stmt|;
name|fieldSkipped
operator|=
literal|false
expr_stmt|;
block|}
else|else
block|{
comment|// select columns that actually do not exist in the file.
name|fieldSkipped
operator|=
literal|true
expr_stmt|;
block|}
block|}
comment|/** * Return the uncompressed size of this field */
specifier|public
name|long
name|getSerializedSize
parameter_list|()
block|{
if|if
condition|(
name|rawBytesField
operator|==
literal|null
condition|)
block|{
return|return
literal|0
return|;
block|}
return|return
name|rawBytesField
operator|.
name|getLength
argument_list|()
return|;
block|}
comment|/** * Get the field out of the row without checking parsed. This is called by * both getField and getFieldsAsList. * * @return The value of the field */
specifier|protected
name|Object
name|uncheckedGetField
parameter_list|()
block|{
if|if
condition|(
name|fieldSkipped
condition|)
block|{
return|return
literal|null
return|;
block|}
if|if
condition|(
operator|!
name|inited
condition|)
block|{
try|try
block|{
name|cachedByteArrayRef
operator|.
name|setData
argument_list|(
name|rawBytesField
operator|.
name|getData
argument_list|()
argument_list|)
expr_stmt|;
block|}
catch|catch
parameter_list|(
name|IOException
name|e
parameter_list|)
block|{
throw|throw
operator|new
name|RuntimeException
argument_list|(
name|e
argument_list|)
throw|;
block|}
name|inited
operator|=
literal|true
expr_stmt|;
name|int
name|byteLength
init|=
name|getLength
argument_list|(
name|objectInspector
argument_list|,
name|cachedByteArrayRef
argument_list|,
name|rawBytesField
operator|.
name|getStart
argument_list|()
argument_list|,
name|rawBytesField
operator|.
name|getLength
argument_list|()
argument_list|)
decl_stmt|;
if|if
condition|(
name|byteLength
operator|==
operator|-
literal|1
condition|)
block|{
return|return
literal|null
return|;
block|}
name|field
operator|.
name|init
argument_list|(
name|cachedByteArrayRef
argument_list|,
name|rawBytesField
operator|.
name|getStart
argument_list|()
argument_list|,
name|byteLength
argument_list|)
expr_stmt|;
return|return
name|field
operator|.
name|getObject
argument_list|()
return|;
block|}
else|else
block|{
if|if
condition|(
name|getLength
argument_list|(
name|objectInspector
argument_list|,
name|cachedByteArrayRef
argument_list|,
name|rawBytesField
operator|.
name|getStart
argument_list|()
argument_list|,
name|rawBytesField
operator|.
name|getLength
argument_list|()
argument_list|)
operator|==
operator|-
literal|1
condition|)
block|{
return|return
literal|null
return|;
block|}
return|return
name|field
operator|.
name|getObject
argument_list|()
return|;
block|}
block|}
block|}
specifier|protected
name|int
index|[]
name|prjColIDs
init|=
literal|null
decl_stmt|;
specifier|private
name|FieldInfo
index|[]
name|fieldInfoList
init|=
literal|null
decl_stmt|;
specifier|private
name|ArrayList
argument_list|<
name|Object
argument_list|>
name|cachedList
decl_stmt|;
specifier|public
name|ColumnarStructBase
parameter_list|(
name|ObjectInspector
name|oi
parameter_list|,
name|List
argument_list|<
name|Integer
argument_list|>
name|notSkippedColumnIDs
parameter_list|)
block|{
name|List
argument_list|<
name|?
extends|extends
name|StructField
argument_list|>
name|fieldRefs
init|=
operator|(
operator|(
name|StructObjectInspector
operator|)
name|oi
operator|)
operator|.
name|getAllStructFieldRefs
argument_list|()
decl_stmt|;
name|int
name|num
init|=
name|fieldRefs
operator|.
name|size
argument_list|()
decl_stmt|;
name|fieldInfoList
operator|=
operator|new
name|FieldInfo
index|[
name|num
index|]
expr_stmt|;
for|for
control|(
name|int
name|i
init|=
literal|0
init|;
name|i
operator|<
name|num
condition|;
name|i
operator|++
control|)
block|{
name|ObjectInspector
name|foi
init|=
name|fieldRefs
operator|.
name|get
argument_list|(
name|i
argument_list|)
operator|.
name|getFieldObjectInspector
argument_list|()
decl_stmt|;
name|fieldInfoList
index|[
name|i
index|]
operator|=
operator|new
name|FieldInfo
argument_list|(
name|createLazyObjectBase
argument_list|(
name|foi
argument_list|)
argument_list|,
operator|!
name|notSkippedColumnIDs
operator|.
name|contains
argument_list|(
name|i
argument_list|)
argument_list|,
name|foi
argument_list|)
expr_stmt|;
block|}
comment|// maintain a list of non-NULL column IDs
name|int
name|min
init|=
name|notSkippedColumnIDs
operator|.
name|size
argument_list|()
operator|>
name|num
condition|?
name|num
else|:
name|notSkippedColumnIDs
operator|.
name|size
argument_list|()
decl_stmt|;
name|prjColIDs
operator|=
operator|new
name|int
index|[
name|min
index|]
expr_stmt|;
for|for
control|(
name|int
name|i
init|=
literal|0
init|,
name|index
init|=
literal|0
init|;
name|i
operator|<
name|notSkippedColumnIDs
operator|.
name|size
argument_list|()
condition|;
operator|++
name|i
control|)
block|{
name|int
name|readCol
init|=
name|notSkippedColumnIDs
operator|.
name|get
argument_list|(
name|i
argument_list|)
operator|.
name|intValue
argument_list|()
decl_stmt|;
if|if
condition|(
name|readCol
operator|<
name|num
condition|)
block|{
name|prjColIDs
index|[
name|index
index|]
operator|=
name|readCol
expr_stmt|;
name|index
operator|++
expr_stmt|;
block|}
block|}
block|}
comment|/** * Get one field out of the struct. * * If the field is a primitive field, return the actual object. Otherwise * return the LazyObject. This is because PrimitiveObjectInspector does not * have control over the object used by the user - the user simply directly * use the Object instead of going through Object * PrimitiveObjectInspector.get(Object). * * NOTE: separator and nullSequence has to be the same each time this method * is called. These two parameters are used only once to parse each record. * * @param fieldID * The field ID * @return The field as a LazyObject */
specifier|public
name|Object
name|getField
parameter_list|(
name|int
name|fieldID
parameter_list|)
block|{
return|return
name|fieldInfoList
index|[
name|fieldID
index|]
operator|.
name|uncheckedGetField
argument_list|()
return|;
block|}
comment|/** * Check if the object is null and return the length of the stream * * @param objectInspector * @param cachedByteArrayRef * the bytes of the object * @param start * the start offset * @param length * the length * * @return -1 for null,>=0 for length */
specifier|protected
specifier|abstract
name|int
name|getLength
parameter_list|(
name|ObjectInspector
name|objectInspector
parameter_list|,
name|ByteArrayRef
name|cachedByteArrayRef
parameter_list|,
name|int
name|start
parameter_list|,
name|int
name|length
parameter_list|)
function_decl|;
comment|/** * create the lazy object for this field * * @param objectInspector * the object inspector for the field * @return the lazy object for the field */
specifier|protected
specifier|abstract
name|LazyObjectBase
name|createLazyObjectBase
parameter_list|(
name|ObjectInspector
name|objectInspector
parameter_list|)
function_decl|;
specifier|public
name|void
name|init
parameter_list|(
name|BytesRefArrayWritable
name|cols
parameter_list|)
block|{
for|for
control|(
name|int
name|i
init|=
literal|0
init|;
name|i
operator|<
name|prjColIDs
operator|.
name|length
condition|;
operator|++
name|i
control|)
block|{
name|int
name|fieldIndex
init|=
name|prjColIDs
index|[
name|i
index|]
decl_stmt|;
if|if
condition|(
name|fieldIndex
operator|<
name|cols
operator|.
name|size
argument_list|()
condition|)
block|{
name|fieldInfoList
index|[
name|fieldIndex
index|]
operator|.
name|init
argument_list|(
name|cols
operator|.
name|unCheckedGet
argument_list|(
name|fieldIndex
argument_list|)
argument_list|)
expr_stmt|;
block|}
else|else
block|{
comment|// select columns that actually do not exist in the file.
name|fieldInfoList
index|[
name|fieldIndex
index|]
operator|.
name|init
argument_list|(
literal|null
argument_list|)
expr_stmt|;
block|}
block|}
block|}
comment|/** * Get the values of the fields as an ArrayList. * * @return The values of the fields as an ArrayList. */
specifier|public
name|ArrayList
argument_list|<
name|Object
argument_list|>
name|getFieldsAsList
parameter_list|()
block|{
if|if
condition|(
name|cachedList
operator|==
literal|null
condition|)
block|{
name|cachedList
operator|=
operator|new
name|ArrayList
argument_list|<
name|Object
argument_list|>
argument_list|()
expr_stmt|;
block|}
else|else
block|{
name|cachedList
operator|.
name|clear
argument_list|()
expr_stmt|;
block|}
for|for
control|(
name|int
name|i
init|=
literal|0
init|;
name|i
operator|<
name|fieldInfoList
operator|.
name|length
condition|;
name|i
operator|++
control|)
block|{
name|cachedList
operator|.
name|add
argument_list|(
name|fieldInfoList
index|[
name|i
index|]
operator|.
name|uncheckedGetField
argument_list|()
argument_list|)
expr_stmt|;
block|}
return|return
name|cachedList
return|;
block|}
specifier|public
name|long
name|getRawDataSerializedSize
parameter_list|()
block|{
name|long
name|serializedSize
init|=
literal|0
decl_stmt|;
for|for
control|(
name|int
name|i
init|=
literal|0
init|;
name|i
operator|<
name|fieldInfoList
operator|.
name|length
condition|;
operator|++
name|i
control|)
block|{
name|serializedSize
operator|+=
name|fieldInfoList
index|[
name|i
index|]
operator|.
name|getSerializedSize
argument_list|()
expr_stmt|;
block|}
return|return
name|serializedSize
return|;
block|}
block|}
end_class
end_unit
| 15.760797 | 813 | 0.767566 |
80d30f61409133249a636bb039c8c562542d6dd3 | 2,184 | /*
* Copyright 2015-2021 OpenEstate.org.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.openestate.io.openimmo;
import org.openestate.io.core.XmlConvertableDocument;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
/**
* A general OpenImmo-XML document.
*
* @param <JavaType> the class of a (via JAXB generated) Java object, that the contained
* {@link Document} is mapped to
* @author Andreas Rudolph
* @since 1.0
*/
public abstract class OpenImmoDocument<JavaType> extends XmlConvertableDocument<JavaType, OpenImmoVersion> {
@SuppressWarnings("unused")
private final static Logger LOGGER = LoggerFactory.getLogger(OpenImmoDocument.class);
/**
* Create from a {@link Document}.
*
* @param document the document to create from
*/
protected OpenImmoDocument(Document document) {
super(document);
}
@Override
public abstract OpenImmoVersion getDocumentVersion();
@Override
public OpenImmoVersion getLatestVersion() {
return OpenImmoUtils.VERSION;
}
/**
* Checks, if the current document is a {@link OpenImmoFeedbackDocument}.
*
* @return true, if the current document is a {@link OpenImmoFeedbackDocument}
*/
public boolean isFeedback() {
return this instanceof OpenImmoFeedbackDocument;
}
/**
* Checks, if the current document is a {@link OpenImmoTransferDocument}.
*
* @return true, if the current document is a {@link OpenImmoTransferDocument}
*/
public boolean isTransfer() {
return this instanceof OpenImmoTransferDocument;
}
} | 31.652174 | 108 | 0.702381 |
46259b30c0b3a7c94377bdc7ad078f92f1e335a8 | 348 | package com.example.oauth.domain;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import java.util.List;
import java.util.UUID;
@Repository
public interface UserRoleRepository extends JpaRepository<UserRoleEntity, Integer> {
List<UserRoleEntity> findRoleByUserId(UUID userId);
} | 24.857143 | 84 | 0.833333 |
845f2962dd85189100f824c6cd051b3ec83741e7 | 791 | // Template Source: Enum.java.tt
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
package com.microsoft.graph.models;
/**
* The Enum Vpn Service Exception Action.
*/
public enum VpnServiceExceptionAction
{
/**
* force Traffic Via VPN
*/
FORCE_TRAFFIC_VIA_VPN,
/**
* allow Traffic Outside
*/
ALLOW_TRAFFIC_OUTSIDE,
/**
* drop Traffic
*/
DROP_TRAFFIC,
/**
* For VpnServiceExceptionAction values that were not expected from the service
*/
UNEXPECTED_VALUE
}
| 25.516129 | 152 | 0.538559 |
ad58ab1760145ad7fcc92244635df135df16b1c7 | 3,465 | package cn.share.jack.cyghttp;
import com.jakewharton.retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import java.util.concurrent.TimeUnit;
import cn.share.jack.cyghttp.app.HttpServletAddress;
import cn.share.jack.cyghttp.convert.CustomGsonConverterFactory;
import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
/**
* BaseRetrofit
*/
public abstract class BaseRetrofit {
protected Retrofit mRetrofit;
private static final int DEFAULT_TIME = 20; //默认超时时间
private final long RETRY_TIMES = 0; //重订阅次数
public BaseRetrofit() {
//创建okHttpClient
if (null == mRetrofit) {
OkHttpClient.Builder builder = new OkHttpClient().newBuilder();
builder.readTimeout(DEFAULT_TIME, TimeUnit.SECONDS);
builder.connectTimeout(DEFAULT_TIME, TimeUnit.SECONDS);
//设置拦截器 添加header
// builder.addInterceptor(new BasicParamsInterceptor.Builder().addHeaderParamsMap(getCommonMap()).build());
builder.addInterceptor(getApiheader());
//如果不是在正式包,添加拦截 打印响应json
if (isDebug()) {
builder.addInterceptor(getlogging());
}
// builder.addInterceptor(new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY));
OkHttpClient okHttpClient = builder.build();
mRetrofit = new Retrofit.Builder()
.baseUrl(HttpServletAddress.getInstance().getServletAddress())
.client(okHttpClient)
.addConverterFactory(CustomGsonConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.build();
}
}
//公共参数
// protected abstract Map<String, String> getCommonMap();
protected abstract Interceptor getApiheader();
protected abstract HttpLoggingInterceptor getlogging();
protected abstract Boolean isDebug();
protected <T> void toSubscribe(Observable<T> observable, Observer<T> observer) {
observable.subscribeOn(Schedulers.io()) // 指定subscribe()发生在IO线程
.observeOn(AndroidSchedulers.mainThread()) // 指定Subscriber的回调发生在io线程
.timeout(DEFAULT_TIME, TimeUnit.SECONDS) //重连间隔时间
.retry(RETRY_TIMES)
// .repeatWhen(new Function<Observable<Object>, ObservableSource<?>>() {
// @Override
// public ObservableSource<?> apply(@NonNull Observable<Object> objectObservable) throws Exception {
// return null;
// }
// })
.subscribe(observer); //订阅
}
protected static <T> T getPresent(Class<T> cls) {
T instance = null;
try {
instance = cls.newInstance();
if (instance == null) {
return null;
}
return instance;
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
return null;
}
} | 37.258065 | 135 | 0.609812 |
c9a9671fe4405cadaaec66725b98d9f5b776a44b | 1,583 | package jr.dungeon.entities.monsters.canines;
import jr.dungeon.Dungeon;
import jr.dungeon.Level;
import jr.dungeon.entities.EntityAppearance;
import jr.dungeon.entities.EntityLiving;
import jr.dungeon.entities.effects.StatusEffect;
import jr.dungeon.entities.interfaces.LightEmitter;
import jr.dungeon.serialisation.Registered;
import jr.dungeon.tiles.TileType;
import jr.dungeon.wishes.Wishable;
import jr.language.Lexicon;
import jr.language.Noun;
import jr.utils.Colour;
import jr.utils.Point;
import java.util.List;
@Wishable(name="hellhound")
@Registered(id="monsterHellhound")
public class MonsterHellhound extends MonsterHound implements LightEmitter {
private static final Colour LIGHT_COLOUR = new Colour(0xFF9B26FF);
public MonsterHellhound(Dungeon dungeon, Level level, Point position) {
super(dungeon, level, position);
getAI().addAvoidTile(TileType.TILE_GROUND_WATER);
getAI().addAvoidTile(TileType.TILE_ROOM_PUDDLE);
}
protected MonsterHellhound() { super(); }
@Override
public Noun getName(EntityLiving observer) {
return Lexicon.hellhound.clone();
}
@Override
public EntityAppearance getAppearance() {
return EntityAppearance.APPEARANCE_HELLHOUND;
}
@Override
public List<StatusEffect> getCorpseEffects(EntityLiving victim) {
return null; // TODO: Fire
}
@Override
public Colour getLightColour() {
return LIGHT_COLOUR;
}
@Override
public int getLightIntensity() {
return 60;
}
}
| 27.293103 | 76 | 0.718256 |
4005e41277fa8cd5da9dc2508bc100e452ef728f | 2,783 | /**
* Copyright (C) 2013 Motown.IO (info@motown.io)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.motown.ocpp.websocketjson.response.handler;
import com.google.gson.Gson;
import io.motown.domain.api.chargingstation.ChargingStationId;
import io.motown.domain.api.chargingstation.CorrelationToken;
import io.motown.domain.api.security.AddOnIdentity;
import io.motown.ocpp.viewmodel.domain.DomainService;
import io.motown.ocpp.websocketjson.schema.generated.v15.DatatransferResponse;
import io.motown.ocpp.websocketjson.wamp.WampMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class DataTransferResponseHandler extends ResponseHandler {
private static final Logger LOG = LoggerFactory.getLogger(DataTransferResponseHandler.class);
public DataTransferResponseHandler(CorrelationToken correlationToken) {
this.setCorrelationToken(correlationToken);
}
@Override
public void handle(ChargingStationId chargingStationId, WampMessage wampMessage, Gson gson, DomainService domainService, AddOnIdentity addOnIdentity) {
DatatransferResponse response = gson.fromJson(wampMessage.getPayloadAsString(), DatatransferResponse.class);
switch (response.getStatus()) {
case UNKNOWN_VENDOR_ID:
LOG.info(String.format("Unknown vendor id for datatransfer request with correlation token %s", getCorrelationToken().getToken()));
break;
case UNKNOWN_MESSAGE_ID:
LOG.info(String.format("Unknown message id for datatransfer request with correlation token %s", getCorrelationToken().getToken()));
break;
case REJECTED:
LOG.info(String.format("Datatransfer request with correlation token %s has been rejected", getCorrelationToken().getToken()));
break;
case ACCEPTED:
if (response.getData() != null) {
domainService.informDataTransferResponse(chargingStationId, response.getData(), getCorrelationToken(), addOnIdentity);
}
break;
default:
throw new AssertionError(String.format("Unknown data transfer response status: %s", response.getStatus()));
}
}
}
| 46.383333 | 155 | 0.717212 |
04ca3330619892e233da13950c40ac760dfcdaa6 | 1,180 | /**
* Created by kerr.
*
* 代码清单 11-1 添加 SSL/TLS 支持 {@link nia.chapter11.SslChannelInitializer}
*
* 代码清单 11-2 添加 HTTP 支持 {@link nia.chapter11.HttpPipelineInitializer}
*
* 代码清单 11-3 自动聚合 HTTP 的消息片段 {@link nia.chapter11.HttpAggregatorInitializer}
*
* 代码清单 11-4 自动压缩 HTTP 消息 {@link nia.chapter11.HttpCompressionInitializer}
*
* 代码清单 11-5 使用 HTTPS {@link nia.chapter11.HttpsCodecInitializer}
*
* 代码清单 11-6 在服务器端支持 WebSocket {@link nia.chapter11.WebSocketServerInitializer}
*
* 代码清单 11-7 发送心跳 {@link nia.chapter11.IdleStateHandlerInitializer}
*
* 代码清单 11-8 处理由行尾符分隔的帧 {@link nia.chapter11.LineBasedHandlerInitializer}
*
* 代码清单 11-9 使用 ChannelInitializer 安装解码器 {@link nia.chapter11.CmdHandlerInitializer}
*
* 代码清单 11-10 使用 LengthFieldBasedFrameDecoder 解码器基于长度的协议 {@link nia.chapter11.LengthBasedInitializer}
*
* 代码清单 11-11 使用 FileRegion 传输文件的内容 {@link nia.chapter11.FileRegionWriteHandler}
*
* 代码清单 11-12 使用 ChunkedStream 传输文件内容 {@link nia.chapter11.ChunkedWriteHandlerInitializer}
*
* 代码清单 11-13 使用 JBoss Marshalling {@link nia.chapter11.MarshallingInitializer}
*
* 代码清单 11-14 使用 protobuf {@link nia.chapter11.ProtoBufInitializer}
*/
package nia.chapter11; | 36.875 | 101 | 0.764407 |
d65536d1171da7ea9b73118d71eed8d1fc4b58f0 | 1,682 | /*
* Copyright (c) 2020, 2021 Oracle and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.helidon.build.devloop;
import java.nio.file.attribute.FileTime;
import java.util.List;
import java.util.Optional;
import static io.helidon.build.devloop.FileChangeAware.changedTimeOf;
import static java.util.Collections.unmodifiableList;
import static java.util.Objects.requireNonNull;
/**
* A collection of {@link BuildFile}s that can be polled for changes.
*/
public class BuildFiles implements FileChangeAware {
private final List<BuildFile> buildFiles;
/**
* Constructor.
*
* @param buildFiles The build files.
*/
public BuildFiles(List<BuildFile> buildFiles) {
if (requireNonNull(buildFiles).isEmpty()) {
throw new IllegalArgumentException("empty");
}
this.buildFiles = unmodifiableList(buildFiles);
}
@Override
public Optional<FileTime> changedTime() {
return changedTimeOf(buildFiles);
}
/**
* Returns the build files.
*
* @return The files.
*/
public List<BuildFile> list() {
return buildFiles;
}
}
| 28.508475 | 75 | 0.697384 |
967ef702a241c33a8351cf5e7587c45f8a21c19f | 1,551 | package com.youlai.mall.pms.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.youlai.mall.pms.pojo.domain.PmsSku;
import com.youlai.mall.pms.pojo.dto.SkuDTO;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import java.util.List;
@Mapper
public interface PmsSkuMapper extends BaseMapper<PmsSku> {
@Select("<script>" +
" select * from pms_sku where spu_id=#{spuId}" +
"</script>")
List<PmsSku> listBySpuId(Long spuId);
@Select({
"<script>",
" SELECT",
" t1.id,",
" t1.CODE,",
" t1.NAME,",
" t1.pic,",
" t1.origin_price,",
" t1.price price,",
" t1.inventory inventory,",
" t2.id spu_id,",
" t2.NAME product_name,",
" t2.pic product_pic,",
" t3.id category_id,",
" t3.NAME category_name,",
" t4.id brand_id,",
" t4.NAME brand_name",
" FROM",
" pms_sku t1",
" LEFT JOIN pms_spu t2 ON t1.spu_id = t2.id",
" LEFT JOIN pms_category t3 ON t2.category_id = t3.id",
" LEFT JOIN pms_brand t4 ON t2.brand_id = t4.id",
" WHERE t1.id in ",
" <foreach collection='skuIds' item='skuId' open='(' separator=',' close=')'>",
" #{skuId}",
" </foreach>",
"</script>"
})
List<SkuDTO> listBySkuIds(List<Long> skuIds);
}
| 31.02 | 92 | 0.520309 |
332b3d16f765463a809fcf363c18cbbdc0a2b220 | 1,709 | package tech.peller.mrblackandroidwatch.utils;
import android.app.Activity;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import tech.peller.mrblackandroidwatch.R;
/**
* Created by r2d2 on 20.01.2017.
*/
public class ToastMrBlack {
public static void showToast(Context context, @Nullable CharSequence text, int duration) {
if (context == null || text == null)
return;
Activity activity = ((Activity) context);
View toast_layout = activity.getLayoutInflater().inflate(R.layout.custom_toast,
(ViewGroup) activity.findViewById(R.id.custom_toast_container));
TextView textView = (TextView) toast_layout.findViewById(R.id.text);
textView.setText(customErrorMessageFixing(text.toString()));
Toast toast = new Toast(context);
toast.setGravity(Gravity.TOP | Gravity.FILL_HORIZONTAL, 0, 0);
toast.setDuration(duration);
toast.setView(toast_layout);
toast.show();
}
@NonNull
private static CharSequence customErrorMessageFixing(String errorMessage) {
if (errorMessage.contains("Failed to connect")) {
errorMessage = "The Internet connection appears to be offline.";
}
return errorMessage;
}
/**
* Default toast with LENGTH_LONG
*
* @param context
* @param text
*/
public static void showToast(Context context, CharSequence text) {
showToast(context, text, Toast.LENGTH_LONG);
}
}
| 31.072727 | 94 | 0.690462 |
4b061386788af3e5f3e52a4e90b015246cd4e5b0 | 117 | package com.hea3ven.tools.mappings;
public abstract class TypeDesc {
public abstract String get(ObfLevel level);
}
| 19.5 | 44 | 0.794872 |
aea78daa3fd3a78970953ac9b5dcc578734e8fb0 | 703 | package dhbwka.wwi.vertsys.javee.filmsortierung.filme.jpa;
public enum FilmStatus {
OPEN, IN_PROGRESS, FINISHED, CANCELED, POSTPONED;
/**
* Bezeichnung ermitteln
*
* @return Bezeichnung
*/
public String getLabel() {
switch (this) {
case OPEN:
return "Noch nicht gesehen";
case IN_PROGRESS:
return "Am schauen";
case FINISHED:
return "Gesehen";
case CANCELED:
return "Interessiert mich nicht";
case POSTPONED:
return "Möchte ich noch sehen";
default:
return this.toString();
}
}
}
| 24.241379 | 58 | 0.516358 |
9b19c187083de1eebdbcc2ddd80c9cd43c003ffc | 937 | package com.nekretnine.dto;
import com.nekretnine.models.Comment;
public class CommentDTO {
private Long id;
private String data;
private AdvertisementDTO advertisementDTO;
private long time;
public CommentDTO() {}
public CommentDTO(Comment comment) {
this.id = comment.getId();
this.data = comment.getData();
this.advertisementDTO = new AdvertisementDTO(comment.getAdvertisement());
this.time = comment.getTime();
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getData() {
return data;
}
public void setData(String data) {
this.data = data;
}
public AdvertisementDTO getAdvertisementDTO() {
return advertisementDTO;
}
public void setAdvertisementDTO(AdvertisementDTO advertisementDTO) {
this.advertisementDTO = advertisementDTO;
}
public long getTime() {
return time;
}
public void setTime(long time) {
this.time = time;
}
}
| 19.93617 | 76 | 0.719317 |
1ae8a729dd2ccae0449a229fc0a3835149954f88 | 11,440 | package org.vaadin.mvp.eventbus;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyZeroInteractions;
import static org.mockito.Mockito.when;
import java.util.Arrays;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InOrder;
import org.vaadin.mvp.test.Util.ChildEventBus;
import org.vaadin.mvp.test.Util.FilterEventBus;
import org.vaadin.mvp.test.Util.OtherEventBus;
import org.vaadin.mvp.test.Util.ParentEventBus;
import org.vaadin.mvp.test.Util.SimpleEventBus;
import org.vaadin.mvp.test.Util.ChildEventBus.ChildPresenter;
import org.vaadin.mvp.test.Util.FilterEventBus.EventFiringFilter;
import org.vaadin.mvp.test.Util.FilterEventBus.EventNameBasedFilter;
import org.vaadin.mvp.test.Util.FilterEventBus.FilterPresenter;
import org.vaadin.mvp.test.Util.OtherEventBus.OtherPresenter;
import org.vaadin.mvp.test.Util.ParentEventBus.ParentPresenter;
import org.vaadin.mvp.test.Util.SimpleEventBus.SimplePresenter;
import com.vaadin.ui.Button;
import de.bechte.junit.runners.context.HierarchicalContextRunner;
@RunWith(HierarchicalContextRunner.class)
public class EventBusInvocationHandlerTest {
private EventHandlerRegistry eventHandlerRegistry;
private EventBusManager eventBusManager;
@Before
public void setUp() {
eventHandlerRegistry = mock(EventHandlerRegistry.class);
eventBusManager = spy(EventBusManager.class);
}
public class EventHandling {
SimpleEventBus eventBus;
SimplePresenter presenter;
EventBusInvocationHandler invocationHandler;
@Before
public void setUp() {
presenter = mock(SimplePresenter.class);
when(eventHandlerRegistry.lookup(SimplePresenter.class)).thenReturn(presenter);
invocationHandler = spy(EventBusInvocationHandler.class);
invocationHandler.setEventHandlerRegistry(eventHandlerRegistry);
eventBus = eventBusManager.createEventBus(SimpleEventBus.class, invocationHandler);
}
@Test
public void isToStringMethod_printsEventBusName() throws Throwable {
String result = eventBus.toString();
verify(invocationHandler).invokeObjectMethod(any(), any(), any());
assertTrue(result.contains("SimpleEventBus"));
}
@Test(expected = IllegalArgumentException.class)
public void missingEventAnnotationOnMethod_throwsRuntimeException() {
eventBus.eventMissingEventAnnotation();
}
@Test
public void eventWithoutHandlers_doesNothing() throws Throwable {
eventBus.eventWithoutHandlers();
verifyZeroInteractions(presenter);
}
@Test
public void eventWithSingleHandler_routedCorrectly() throws Throwable {
eventBus.eventWithSingleHandler();
verify(presenter).onEventWithSingleHandler();
}
@Test
public void eventWithHandler_handlerMethodNotDefined_continuesAndDoesNothing() throws Throwable {
eventBus.eventNotDefinedOnHandler();
verifyZeroInteractions(presenter);
}
@Test
public void eventWithHandler_handlerMethodDefinedWithMismatchingArguments_continuesAndDoesNothing() {
eventBus.eventDefinedWithMismatchingArguments("", new Button.ClickEvent(new Button()));
verifyZeroInteractions(presenter);
}
@Test
public void eventWithHandler_handlerMethodReturningValue_returnsValue() {
when(presenter.onEventWithReturningValue()).thenReturn("test");
String returningValue = eventBus.eventWithReturningValue();
verify(presenter).onEventWithReturningValue();
assertNotNull(returningValue);
assertTrue("test".equals(returningValue));
}
public class Multiple {
OtherEventBus otherEventBus;
OtherPresenter otherPresenter;
EventBusInvocationHandler otherEventBusInvocationHandler;
@Before
public void setUp() {
otherPresenter = mock(OtherPresenter.class);
when(eventHandlerRegistry.lookup(OtherPresenter.class)).thenReturn(otherPresenter);
otherEventBusInvocationHandler = spy(EventBusInvocationHandler.class);
otherEventBusInvocationHandler.setEventHandlerRegistry(eventHandlerRegistry);
otherEventBus = eventBusManager.createEventBus(OtherEventBus.class, otherEventBusInvocationHandler);
}
@Test
public void eventWithHandlers_routedCorrectly() {
eventBus.eventWithHandlers();
verify(presenter).onEventWithHandlers();
verify(otherPresenter).onEventWithHandlers();
}
@Test
public void eventWithHandlers_callOrderIsRespected() {
eventBus.eventWithHandlers();
InOrder inOrder = inOrder(presenter, otherPresenter);
inOrder.verify(presenter).onEventWithHandlers();
inOrder.verify(otherPresenter).onEventWithHandlers();
}
@Test
public void eventWithHandlers_someNotRegistered_continuesAndDoesNothing() {
when(eventHandlerRegistry.lookup(OtherPresenter.class)).thenReturn(null);
eventBus.eventWithHandlers();
verify(presenter).onEventWithHandlers();
verify(otherPresenter, never()).onEventWithHandlers();
}
}
}
public class Parent {
ParentEventBus parentEventBus;
ParentPresenter parentPresenter;
EventBusInvocationHandler parentEventBusInvocationHandler;
@Before
public void setUp() {
parentPresenter = mock(ParentPresenter.class);
when(eventHandlerRegistry.lookup(ParentPresenter.class)).thenReturn(parentPresenter);
parentEventBusInvocationHandler = spy(EventBusInvocationHandler.class);
parentEventBusInvocationHandler.setEventHandlerRegistry(eventHandlerRegistry);
parentEventBus = eventBusManager.createEventBus(ParentEventBus.class, parentEventBusInvocationHandler);
}
public class Child {
ChildEventBus childEventBus;
ChildPresenter childPresenter;
EventBusInvocationHandler childEventBusInvocationHandler;
@Before
public void setUp() {
childPresenter = mock(ChildPresenter.class);
when(eventHandlerRegistry.lookup(ChildPresenter.class)).thenReturn(childPresenter);
childEventBusInvocationHandler = spy(EventBusInvocationHandler.class);
childEventBusInvocationHandler.setEventHandlerRegistry(eventHandlerRegistry);
childEventBusInvocationHandler.setParent(ParentEventBus.class);
childEventBus = eventBusManager.createEventBus(ChildEventBus.class, childEventBusInvocationHandler);
}
@Test
public void eventWithHandler_forwardingToParent_successfullyForwarded() throws Throwable {
when(eventHandlerRegistry.findEventBusByType(ParentEventBus.class)).thenReturn(parentEventBus);
childEventBus.eventWithHandlerAndForwardingToParent();
InOrder inOrder = inOrder(childPresenter, parentPresenter);
inOrder.verify(childPresenter).onEventWithHandlerAndForwardingToParent();
inOrder.verify(parentPresenter).onEventWithHandlerAndForwardingToParent();
}
// TODO invoke_eventForwardingToParent_withoutParentEventBus_
@Test
public void eventWithHandler_notForwardingToParentButHasParentEventBus_eventNotForwardedToParent() throws Throwable {
childEventBus.eventWithHandlerNotForwardingToParent();
verify(childPresenter).onEventWithHandlerNotForwardingToParent();
verifyZeroInteractions(parentPresenter);
}
// TODO invoke_eventNotForwardingToParent_withoutParentEventBus_
@Test
public void eventWithHandler_methodReturningValueAndForwardingToParent_returnsParentValue() {
when(eventHandlerRegistry.findEventBusByType(ParentEventBus.class)).thenReturn(parentEventBus);
when(childPresenter.onEventWithHandlerMethodReturningValueAndForwardingToParent()).thenReturn("child");
when(parentPresenter.onEventWithHandlerMethodReturningValueAndForwardingToParent()).thenReturn("parent");
String returningValue = childEventBus.eventWithHandlerMethodReturningValueAndForwardingToParent();
InOrder inOrder = inOrder(childPresenter, parentPresenter);
inOrder.verify(childPresenter).onEventWithHandlerMethodReturningValueAndForwardingToParent();
inOrder.verify(parentPresenter).onEventWithHandlerMethodReturningValueAndForwardingToParent();
assertNotNull(returningValue);
assertTrue("parent".equals(returningValue));
}
}
}
public class Filter {
FilterEventBus filterEventBus;
FilterPresenter filterPresenter;
EventBusInvocationHandler filterEventBusInvocationHandler;
@Before
public void setUp() {
filterPresenter = mock(FilterPresenter.class);
when(eventHandlerRegistry.lookup(FilterPresenter.class)).thenReturn(filterPresenter);
filterEventBusInvocationHandler = spy(EventBusInvocationHandler.class);
filterEventBusInvocationHandler.setEventHandlerRegistry(eventHandlerRegistry);
filterEventBusInvocationHandler.setFilters(Arrays.asList(new EventNameBasedFilter(), new EventFiringFilter()));
filterEventBus = eventBusManager.createEventBus(FilterEventBus.class, filterEventBusInvocationHandler);
}
@Test
public void eventWithoutFilters_eventPropagateSuccessfully() {
filterEventBus.eventWithoutFilters();
verify(filterPresenter).onEventWithoutFilters();
}
@Test
public void eventWithFilters_eventNameBaseFilter_eventFilteredSuccessfully() {
filterEventBus.eventWithEventNameBasedFilter();
verify(filterPresenter, never()).onEventWithEventNameBasedFilter();
}
@Test
public void eventWithFilters_filterFiringEventFromEventBus_otherEventSuccessfullyFired() {
filterEventBus.eventWithEventBusFiringFilter();
verify(filterPresenter, never()).onEventWithEventBusFiringFilter();
verify(filterPresenter).onEventFiredFromFilter();
}
}
}
| 37.385621 | 130 | 0.684091 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.