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
3515a9c8562ab6f41f7536ac7d5531ab86a04486
10,216
package com.hxjg.vpn.base; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.graphics.Color; import android.os.Bundle; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.widget.ImageButton; import android.widget.LinearLayout; import android.widget.TextView; import com.afollestad.materialdialogs.GravityEnum; import com.afollestad.materialdialogs.MaterialDialog; import com.hxjg.vpn.R; import com.hxjg.vpn.api.exception.ServerError; import com.hxjg.vpn.eventbus.IEvent; import com.hxjg.vpn.statusView.MyStatusView; import com.hxjg.vpn.statusView.StatusLayout; import com.hxjg.vpn.ui.login.LoginActivity; import com.hxjg.vpn.ui.tabbar.TabBarActivity; import com.hxjg.vpn.utils.Logger; import com.hxjg.vpn.utils.ScreenUtils; import com.gyf.immersionbar.ImmersionBar; import org.greenrobot.eventbus.EventBus; import org.greenrobot.eventbus.Subscribe; import org.greenrobot.eventbus.ThreadMode; import java.lang.reflect.Method; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.List; import androidx.annotation.ColorRes; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatActivity; import androidx.core.app.ActivityCompat; import androidx.core.content.ContextCompat; import androidx.viewbinding.ViewBinding; import rx.Subscription; public class BaseActivity<T extends ViewBinding> extends AppCompatActivity { protected T viewBinding; private ImmersionBar mImmersionBar; private MaterialDialog progressDialog; private ArrayList<Subscription> subscriptions = new ArrayList<>(); private OnRequestPermissionResultListener onRequestPermissionResultListener; public static final int REQUEST_CODE_FOR_DIR = 300; protected StatusLayout statusLayout; protected MyStatusView statusView; public interface OnRequestPermissionResultListener { void onRequestPermissionResultListener(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults); } public static void startMe(Context context, Class activityClass) { Intent intent = new Intent(context, activityClass); context.startActivity(intent); ((Activity) context).startActivity(intent); } public static void startMe(Context context, Class activityClass, Bundle bundle) { Intent intent = new Intent(context, activityClass); intent.putExtras(bundle); ((Activity) context).startActivity(intent); } @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); // setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); Type genericSuperclass = getClass().getGenericSuperclass(); if (genericSuperclass instanceof ParameterizedType) { ParameterizedType type = (ParameterizedType) genericSuperclass; Class cls = (Class) type.getActualTypeArguments()[0]; try { Method inflate = cls.getDeclaredMethod("inflate", LayoutInflater.class); viewBinding = (T) inflate.invoke(null, getLayoutInflater()); setContentView(viewBinding.getRoot()); } catch (Exception e) { e.printStackTrace(); } } EventBus.getDefault().register(this); } protected void transparentStatusBar() { //在BaseActivity里初始化 transparentStatusBar(false); } protected void transparentStatusBar(boolean trans) { //在BaseActivity里初始化 mImmersionBar = ImmersionBar.with(this); mImmersionBar.statusBarAlpha(trans ? 0f : 1.0f).init(); } protected void setStatusBarWhite() { mImmersionBar = ImmersionBar.with(this); mImmersionBar.fitsSystemWindows(true) //使用该属性,必须指定状态栏颜色 .statusBarColor(R.color.colorWhite) .init(); } protected void setStatusBarColor(@ColorRes int color) { mImmersionBar = ImmersionBar.with(this); mImmersionBar.fitsSystemWindows(true) //使用该属性,必须指定状态栏颜色 .statusBarColor(color) .init(); } protected void setStatusBarDarkFont(boolean dark) { if (mImmersionBar != null) { mImmersionBar.statusBarDarkFont(dark).init(); } } protected View createFooterView(int height) { LinearLayout view = new LinearLayout(this); LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ScreenUtils.dpToPxInt(this, height)); view.setLayoutParams(params); view.setBackgroundColor(Color.WHITE); return view; } public void showProgressDialog() { if (progressDialog == null) { progressDialog = new MaterialDialog.Builder(this) .backgroundColor(R.color.backgroundColor) .contentGravity(GravityEnum.CENTER) .progress(true, 0) .cancelable(false) .build(); } progressDialog.show(); } public void dismissDialog() { try { if (progressDialog != null && progressDialog.isShowing()) { progressDialog.cancel(); } } catch (Exception e) { Logger.printException(e); } } public void initStatusView(View contentView, MyStatusView.onRetryClickLister onRetryClickLister){ statusView = MyStatusView.getInstance(this, onRetryClickLister); statusLayout = new StatusLayout.Builder().setContentView(contentView).setStatusView(statusView).build(); statusLayout.showLoading(); statusView.startLoading(); } public void showLoading(){ statusLayout.showLoading(); } public void showRetry(){ statusLayout.showRetry(); statusView.setErrorText("网络数据出错,请检查您的网络"); } public void showRetry(ServerError error){ statusLayout.showRetry(); statusView.setErrorText("网络请求出错,错误码:"+error.getErrorCode()+",错误信息:"+error.getMsg()); } public void showNeedVip(){ statusLayout.showNeedVip(); } public void showNeedSVip(){ statusLayout.showNeedSVip(); } public void showContent(){ statusLayout.showContent(); } protected int getViewIdByString(String idStr, Context context) { int id = context.getResources().getIdentifier(idStr, "id", context.getPackageName()); return id; } protected void addSubscription(Subscription subscription) { subscriptions.add(subscription); } @Override protected void onResume() { super.onResume(); } @Override protected void onPause() { super.onPause(); } @Override public boolean dispatchTouchEvent(MotionEvent ev) { return super.dispatchTouchEvent(ev); } @Override protected void onDestroy() { try { for (Subscription subscription : subscriptions) { if (!subscription.isUnsubscribed()) { subscription.unsubscribe(); } } subscriptions.clear(); } catch (Exception e) { Logger.printException(e); } dismissDialog(); EventBus.getDefault().unregister(this); super.onDestroy(); } protected void setTitle(String title) { TextView tvTitle = findViewById(R.id.tv_toolbar_title); if (null != tvTitle) { tvTitle.setText(title); } } protected void initBackBtn() { ImageButton backBtn = findViewById(R.id.ib_toolbar_back); if (null == backBtn) { Logger.w("back btn is null"); return; } backBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { onBackBtnClick(); } }); } protected void onBackBtnClick() { finish(); } @Subscribe(threadMode = ThreadMode.MAIN) public void onMessageEvent(IEvent.Logout event) { Logger.d("this class type:" + this.toString()); if (event.reLogin) { Intent intent = new Intent(this, LoginActivity.class); startActivity(intent); } this.finish(); } @Subscribe(threadMode = ThreadMode.MAIN) public void onMessageEvent(IEvent.LoginSuccess event) { Logger.i("LoginSuccess Event"); TabBarActivity.startMe(this, 0); finish(); } /** * 请求权限 * * @param permissions 权限列表 * @param resultCode * @return 是否已经具备相应权限 */ public boolean checkReadPermission(String[] permissions, int resultCode) { List<String> mPermissionList = new ArrayList<>(); for (int i = 0; i < permissions.length; i++) { if (ContextCompat.checkSelfPermission(this, permissions[i]) != PackageManager.PERMISSION_GRANTED) { mPermissionList.add(permissions[i]); } } if (mPermissionList.size() == 0) { return true; } String[] needPermissions = mPermissionList.toArray(new String[mPermissionList.size()]);//将List转为数组 ActivityCompat.requestPermissions(this, needPermissions, resultCode); return false; } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); if (onRequestPermissionResultListener != null) { this.onRequestPermissionResultListener.onRequestPermissionResultListener(requestCode, permissions, grantResults); } } public void setOnRequestPermissionResultListener(OnRequestPermissionResultListener onRequestPermissionResultListener) { this.onRequestPermissionResultListener = onRequestPermissionResultListener; } }
31.825545
147
0.665623
7e5a7f8d05ad04e655c918accc8d1d61394b7652
6,208
import java.awt.*; import java.awt.image.*; import javax.imageio.*; import java.io.*; import java.util.zip.*; public final class Cactus { final int width; final int height; final int supersample; final int iterations; final BufferedImage image; final int[] brown = new int[]{0x1f, 0x14, 0x01}; final int[] green = new int[]{0x7c, 0xaf, 0x2d}; public static final void main(String[] args) throws Exception { int argumentIndex = 0; final int width = Integer.parseInt(args[argumentIndex++]); final int height = Integer.parseInt(args[argumentIndex++]); final int supersample = Integer.parseInt(args[argumentIndex++]); final int iterations = Integer.parseInt(args[argumentIndex++]); ZipOutputStream zos = new ZipOutputStream(new BufferedOutputStream(System.out)); zos.putNextEntry(new ZipEntry("cactus.bmp")); new Cactus(width, height, supersample, iterations).go(zos); zos.closeEntry(); zos.close(); } private Cactus(final int width, final int height, final int supersample, final int iterations) { this.width = width; this.height = height; this.supersample = supersample; this.iterations = iterations; this.image = new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR); } private static final class Imag { public final double real; public final double imag; public static final Imag ONE = new Imag(1.0); public Imag(final double r) { this(r, 0); } public Imag(final double r, final double i) { this.real = r; this.imag = i; } public Imag power(final int p) { Imag result = new Imag(1.0); for (int i = 1; i <= p; ++i) { result = multiply(result, this); } return result; } public Imag negate() { return new Imag(-real, -imag); } public Imag reciprocal() { final double mag2 = magnitude2(); return new Imag(real / mag2, -imag / mag2); } public double magnitude2() { return real * real + imag * imag; } public double magnitude() { return Math.sqrt(magnitude2()); } public static Imag multiply(final Imag lhs, final Imag rhs) { return new Imag( lhs.real * rhs.real - lhs.imag * rhs.imag, lhs.real * rhs.imag + lhs.imag * rhs.real); } public static Imag divide(final Imag lhs, final Imag rhs) { return multiply(lhs, rhs.reciprocal()); } public static Imag add(final Imag lhs, final Imag rhs) { return new Imag( lhs.real + rhs.real, lhs.imag + rhs.imag); } public static Imag subtract(final Imag lhs, final Imag rhs) { return add(lhs, rhs.negate()); } } private static final double f(final double r) { return (r * (1 + 2*r + r*r) * (r*r - 1)) / ((1 + r*r*r) * (1 + r*r*r)); } private static final double g(final double r) { return (r * (1 - 2*r + r*r) * (r*r - 1)) / ((1 + r*r*r) * (1 + r*r*r)); } private void go(OutputStream out) throws IOException { System.err.println("Width: " + width); System.err.println("Height: " + height); System.err.println("Supersample: " + supersample); System.err.println("Iterations: " + iterations); final double xmin = -2; final double xmax = 2; final double ymin = -2; final double ymax = 2; final int m = 4; for (int x = 0; x < width; ++x) { for (int y = 0; y < height; ++y) { int memberCount = 0; for (int xs = 0; xs < supersample; ++xs) { for (int ys = 0; ys < supersample; ++ys) { final Imag z0 = new Imag( (x * supersample + xs) * (xmax - xmin) / (width * supersample) + xmin, (y * supersample + ys) * (ymax - ymin) / (height * supersample) + ymin).reciprocal(); int count = 0; Imag z = z0; while (count < iterations && z.magnitude2() < 100) { //z = Imag.subtract(Imag.add(z.power(3), Imag.multiply(Imag.subtract(z0, Imag.ONE), z)), z0); //z = Imag.divide(Imag.add(z.power(2), z), Imag.add(Imag.multiply(new Imag(2), z.power(m)), z0)); //z = Imag.add(z.power(2), z0); /* z = Imag.divide( Imag.add(Imag.add(z.power(m), z.power(2)), Imag.ONE), Imag.add(Imag.add(Imag.multiply(new Imag(2), z.power(m-1)), z0.negate()), Imag.ONE) ); */ z = Imag.add( z.power(2), new Imag( f(z.magnitude()), g(z.magnitude()) ) ); count++; } if (count == iterations || (count % 2) == 0) { memberCount++; } } } final double v = 1.0 - (memberCount * 1.0 / (supersample * supersample)); final int r = (int)(brown[0] + (green[0] - brown[0]) * v); final int g = (int)(brown[1] + (green[1] - brown[1]) * v); final int b = (int)(brown[2] + (green[2] - brown[2]) * v); image.setRGB(x, y, (r << 16) | (g << 8) | b); } System.err.print("\r" + x); } System.err.println(); ImageIO.write(image, "bmp", out); } }
33.376344
125
0.464723
8dbde022be70a715f3ab908ca5d06ea80edd02db
681
package cn.navclub.fishpond.app.socket; import cn.navclub.fishpond.protocol.api.APIECode; import cn.navclub.fishpond.protocol.enums.ServiceCode; import cn.navclub.fishpond.protocol.model.TProMessage; import io.vertx.core.json.JsonObject; public interface SocketHook { /** * 消息到达时候回调该函数 */ default void onMessage(TProMessage message) { } /** * 当操作反馈消息到达时出发该函数 */ default void feedback(ServiceCode serviceCode, APIECode code, JsonObject content, TProMessage message) { } /** * TCP connection status change callback that function */ default void onTCNStatusChange(TCNStatus oldValue, TCNStatus newValue) { } }
21.967742
108
0.71072
22a5348a5bc5407bb5d7f7d3e032369ca81bf512
6,916
/* * Hotspot compile command annotations - http://compile-command-annotations.nicoulaj.net * Copyright © 2014-2019 Hotspot compile command annotations contributors * * 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.nicoulaj.compilecommand; import org.apache.commons.io.FileUtils; import java.io.File; import java.nio.charset.Charset; import java.util.Map; /** * Utility for integration test asserts.. * <p>See {@code src/main/it/projects/.../postbuild.groovy} scripts.</p> * * @author <a href="http://github.com/nicoulaj">Julien Nicoulaud</a> * @see <a href="http://maven.apache.org/plugins/maven-invoker-plugin/examples/post-build-script.html"> * maven-invoker-plugin post-build script invocation</a> */ public final class ITAssert { /** The name of the build log file. */ public static final String BUILD_LOG_FILE = "build.log"; /** The absolute path to the base directory of the test project. */ protected File baseDirectory; /** The absolute path to the local repository used for the Maven invocation on the test project. */ protected File localRepositoryPath; /** The storage of key-value pairs used to pass data from the pre-build hook script to the post-build hook script. */ protected Map context; /** * Build a new {@link ITAssert} instance. * * @param baseDirectory the absolute path to the base directory of the test project.. * @param localRepositoryPath the absolute path to the local repository used for the Maven invocation on the test * project.. * @param context the storage of key-value pairs used to pass data from the pre-build hook script to the * post-build hook script.. * @see <a href="http://maven.apache.org/plugins/maven-invoker-plugin/examples/post-build-script.html"> * maven-invoker-plugin post-build script invocation</a> */ public ITAssert(File baseDirectory, File localRepositoryPath, Map context) { this.baseDirectory = baseDirectory; this.localRepositoryPath = localRepositoryPath; this.context = context; } /** * Get the contents of the file. * * @param path the path to the file relative to {@link #baseDirectory}. * @return the file content. * @throws Exception if the build log could not be open. */ public String getFileContent(String path) throws Exception { return FileUtils.readFileToString(new File(baseDirectory, path)); } /** * Get the project build log content. * * @return the project build log content. * @throws Exception if the build log could not be open. */ public String getBuildLog() throws Exception { return getFileContent(BUILD_LOG_FILE); } /** * Assert the given file exists and is a file. * * @param path the path to the file relative to {@link #baseDirectory}. * @throws Exception if conditions are not fulfilled. */ public void assertFileExists(String path) throws Exception { if (!new File(baseDirectory, path).isFile()) throw new Exception("The file " + path + " is missing."); } /** * Assert the given file does not exist. * * @param path the path to the file relative to {@link #baseDirectory}. * @throws Exception if conditions are not fulfilled. */ public void assertFileDoesNotExist(String path) throws Exception { if (new File(baseDirectory, path).isFile()) throw new Exception("The file " + path + " exists, but it should not."); } /** * Assert the given file exists and is a non-empty file. * * @param path the path to the file relative to {@link #baseDirectory}. * @throws Exception if conditions are not fulfilled. */ public void assertFileIsNotEmpty(String path) throws Exception { final File file = new File(baseDirectory, path); if (!file.isFile()) throw new Exception("The file " + path + " is missing or not a file."); else if (FileUtils.readFileToString(file).length() == 0) throw new Exception("The file " + path + " is empty."); } /** * Assert the file contains the given search. * * @param path the path to the file relative to {@link #baseDirectory}. * @param search the expression to search in the build log. * @throws Exception if conditions are not fulfilled. */ public void assertFileContains(String path, String search) throws Exception { if (!FileUtils.readFileToString(new File(baseDirectory, path), Charset.defaultCharset()).contains(search)) throw new Exception(path + " does not contain '" + search + "'."); } /** * Assert the project build log contains the given search. * * @param search the expression to search in the build log. * @throws Exception if conditions are not fulfilled. */ public void assertBuildLogContains(String search) throws Exception { assertFileContains(BUILD_LOG_FILE, search); } /** * Assert the file does not contain the given search. * * @param path the path to the file relative to {@link #baseDirectory}. * @param search the expression to search in the build log. * @throws Exception if conditions are not fulfilled. */ public void assertFileDoesNotContain(String path, String search) throws Exception { if (FileUtils.readFileToString(new File(baseDirectory, path), Charset.defaultCharset()).contains(search)) throw new Exception(path + " contains '" + search + "'."); } /** * Assert the project build log does not contain the given search. * * @param search the expression to search in the build log. * @throws Exception if conditions are not fulfilled. */ public void assertBuildLogDoesNotContain(String search) throws Exception { assertFileDoesNotContain(BUILD_LOG_FILE, search); } /** * Delete the given file if it exists. * * @param file path to the file relative to basedir * @throws Exception if conditions are not fulfilled. */ public void deleteIfExists(String file) throws Exception { final File f = new File(baseDirectory, file); if (f.exists() && f.isFile()) f.delete(); } }
39.295455
121
0.66498
cc80dd31c827ce002f98e9c7da828a16973e5fb7
7,832
package com.tvd12.ezydata.database.bean; import java.lang.reflect.Method; import java.util.Collection; import java.util.concurrent.atomic.AtomicInteger; import com.tvd12.ezydata.database.EzyDatabaseContext; import com.tvd12.ezydata.database.EzyDatabaseContextAware; import com.tvd12.ezydata.database.EzyDatabaseRepository; import com.tvd12.ezydata.database.EzyDatabaseRepositoryWrapper; import com.tvd12.ezydata.database.query.EzyQueryEntity; import com.tvd12.ezydata.database.query.EzyQueryMethod; import com.tvd12.ezydata.database.query.EzyQueryMethodConverter; import com.tvd12.ezydata.database.query.EzyQueryRegister; import com.tvd12.ezydata.database.query.EzyQueryString; import com.tvd12.ezyfox.asm.EzyFunction; import com.tvd12.ezyfox.asm.EzyFunction.EzyBody; import com.tvd12.ezyfox.database.annotation.EzyQuery; import com.tvd12.ezyfox.asm.EzyInstruction; import com.tvd12.ezyfox.io.EzyStrings; import com.tvd12.ezyfox.reflect.EzyClass; import com.tvd12.ezyfox.reflect.EzyGenerics; import com.tvd12.ezyfox.reflect.EzyMethod; import com.tvd12.ezyfox.reflect.EzyMethods; import com.tvd12.ezyfox.util.EzyLoggable; import javassist.ClassPool; import javassist.CtClass; import javassist.CtNewMethod; import lombok.Setter; @SuppressWarnings("rawtypes") public abstract class EzyAbstractRepositoryImplementer extends EzyLoggable { protected final EzyClass clazz; protected Class<?> idType; protected Class<?> entityType; @Setter protected EzyQueryRegister queryManager; @Setter protected EzyQueryMethodConverter queryMethodConverter; @Setter protected EzyDatabaseRepositoryWrapper repositoryWrapper; @Setter protected static boolean debug; protected static final AtomicInteger COUNT = new AtomicInteger(0); public EzyAbstractRepositoryImplementer(Class<?> clazz) { this(new EzyClass(clazz)); } public EzyAbstractRepositoryImplementer(EzyClass clazz) { this.clazz = clazz; } public Object implement(Object template) { try { this.preimplement(template); return doimplement(template); } catch(Exception e) { throw new IllegalStateException("error on repo interface: " + clazz.getName(), e); } } protected void preimplement(Object template) {} protected Object doimplement(Object template) throws Exception { Class[] idAndEntityTypes = getIdAndEntityTypes(); idType = idAndEntityTypes[0]; entityType = idAndEntityTypes[1]; ClassPool pool = ClassPool.getDefault(); String implClassName = getImplClassName(); CtClass implClass = pool.makeClass(implClassName); EzyClass superClass = new EzyClass(getSuperClass()); implClass.setSuperclass(pool.get(superClass.getName())); for(EzyMethod method : getAbstractMethods()) { registerQuery(method); String methodContent = makeAbstractMethodContent(method); printMethodContent(methodContent); implClass.addMethod(CtNewMethod.make(methodContent, implClass)); } String getEntityTypeMethodContent = makeGetEntityTypeMethodContent(entityType); printMethodContent(getEntityTypeMethodContent); implClass.addMethod(CtNewMethod.make(getEntityTypeMethodContent, implClass)); implClass.setInterfaces(new CtClass[] { pool.get(clazz.getName()) }); Class answerClass = implClass.toClass(); implClass.detach(); Object repo = answerClass.newInstance(); if(template instanceof EzyDatabaseContext && repo instanceof EzyDatabaseContextAware) { ((EzyDatabaseContextAware)repo).setDatabaseContext((EzyDatabaseContext) template); } setRepoComponent(repo, template); return repositoryWrapper.wrap(repo); } protected void setRepoComponent(Object repo, Object template) {} protected Collection<EzyMethod> getAbstractMethods() { return clazz.getMethods(m -> isAbstractMethod(m)); } protected boolean isAbstractMethod(EzyMethod method) { if(method.isAnnotated(EzyQuery.class)) return true; if(isAutoImplementMethod(method)) return true; return false; } protected boolean isAutoImplementMethod(EzyMethod method) { for(EzyMethod defMethod : EzyDatabaseRepository.CLASS.getMethods()) { if(method.equals(defMethod)) return false; if(EzyMethods.isOverriddenMethod(method, defMethod)) return false; } return true; } protected void registerQuery(EzyMethod method) { if(queryManager == null) return; EzyQuery queryAnno = method.getAnnotation(EzyQuery.class); if(queryAnno == null) return; String queryValue = queryAnno.value(); if(EzyStrings.isNoContent(queryValue)) return; String queryName = queryAnno.name(); if(EzyStrings.isNoContent(queryName)) queryName = method.toString(); EzyQueryEntity queryEntity = EzyQueryEntity.builder() .name(queryName) .type(queryAnno.type()) .value(queryValue) .nativeQuery(queryAnno.nativeQuery()) .resultType(queryAnno.resultType()) .build(); queryManager.addQuery(queryEntity); } protected String makeAbstractMethodContent(EzyMethod method) { EzyBody body = new EzyFunction(method).body(); return body.function().toString(); } protected EzyQueryString getQueryString(EzyMethod method) { EzyQuery anno = method.getAnnotation(EzyQuery.class); if(anno != null) return getQueryString(method, anno); return convertQueryMethodToQueryString(method); } protected EzyQueryString getQueryString(EzyMethod method, EzyQuery queryAnnotation) { String queryString = queryAnnotation.value(); boolean nativeQuery = queryAnnotation.nativeQuery(); if(EzyStrings.isNoContent(queryString)) { String queryName = queryAnnotation.name(); if(EzyStrings.isNoContent(queryName)) throw new IllegalArgumentException("query name can not be null on method: " + method.getName()); EzyQueryEntity query = queryManager.getQuery(queryName); if(query == null) throw new IllegalArgumentException("not found query with name: " + queryName + " on method: " + method.getName()); queryString = query.getValue(); nativeQuery = query.isNativeQuery(); } return new EzyQueryString(queryString, nativeQuery); } protected EzyQueryString convertQueryMethodToQueryString(EzyMethod method) { EzyQueryMethod queryMethod = new EzyQueryMethod(method); return new EzyQueryString(queryMethodConverter.toQueryString(entityType, queryMethod)); } protected boolean isPaginationMethod(EzyMethod method) { return EzyQueryMethod.isPaginationMethod(method); } protected Class<?> getResultType(EzyMethod method) { Class<?> resultType = Object.class; EzyQuery anno = method.getAnnotation(EzyQuery.class); if(anno != null) resultType = anno.resultType(); if(resultType == Object.class) { resultType = method.getReturnType(); if(Iterable.class.isAssignableFrom(resultType)) { try { resultType = EzyGenerics.getOneGenericClassArgument( method.getGenericReturnType() ); } catch (Exception e) {} } } return resultType; } protected String makeGetEntityTypeMethodContent(Class entityType) { return new EzyFunction(getEntityTypeMethod()) .body() .append(new EzyInstruction("\t", "\n") .answer() .clazz(entityType, true)) .function() .toString(); } protected EzyMethod getEntityTypeMethod() { Method method = EzyMethods.getMethod(getSuperClass(), "getEntityType"); return new EzyMethod(method); } protected abstract Class<?> getSuperClass(); protected String getImplClassName() { return clazz.getName() + "$EzyDatabaseRepository$EzyAutoImpl$" + COUNT.incrementAndGet(); } protected Class[] getIdAndEntityTypes() { return EzyGenerics.getGenericInterfacesArguments(clazz.getClazz(), getBaseRepositoryInterface(), 2); } protected Class<?> getBaseRepositoryInterface() { return EzyDatabaseRepository.class; } protected void printMethodContent(String methodContent) { if(debug) logger.info("method content \n{}", methodContent); } }
33.32766
118
0.767748
352535e38a77079eb27e0a1faff10bf3f4c8043c
885
package JavaOOP.Inheritance_7.Exercise.BookShop_2; import java.security.InvalidParameterException; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String author = sc.nextLine(); String title = sc.nextLine(); double price = Double.parseDouble(sc.nextLine()); try { Book book = new Book(author, title, price); GoldenEditionBook goldenEditionBook = new GoldenEditionBook(author, title, price); System.out.println(book); System.out.println(goldenEditionBook); } catch (InvalidParameterException ex) { System.out.println(ex.getMessage()); return; } } }
25.285714
57
0.548023
81cf16e600f12fdd82285d450caf130cc5f8cdc4
8,894
package com.quantum.steps.api; import static com.qmetry.qaf.automation.core.ConfigurationManager.getBundle; import static com.qmetry.qaf.automation.util.Validator.assertThat; import static org.testng.Assert.assertEquals; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.HashMap; import java.util.Properties; import org.hamcrest.Matchers; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.testng.Assert; import org.testng.SkipException; import com.custom.ap.GenLib; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.gson.Gson; import com.google.gson.JsonObject; import com.google.gson.JsonParseException; import com.jayway.jsonpath.JsonPath; import com.qmetry.qaf.automation.core.ConfigurationManager; import com.qmetry.qaf.automation.rest.RestRequestBean; import com.qmetry.qaf.automation.step.QAFTestStep; import com.qmetry.qaf.automation.step.WsStep; import com.qmetry.qaf.automation.ws.rest.RestTestBase; import com.sun.jersey.api.client.ClientResponse; public class WebServicesStepDef { GenLib genLib; public static Properties prop = new Properties(); public String systemDir = System.getProperty("user.dir"); private Properties temp_properties; public WebServicesStepDef() { genLib = new GenLib(); } @QAFTestStep(description="user requests with json data from path {0}") public static ClientResponse userResuestsWithJsonDataFromPath(String path) throws IOException, ParseException{ /* * This method will trigger a request based from the json request template * Parameter: * - JSON Request filepath */ Logger logger = LoggerFactory.getLogger(WebServicesStepDef.class); JSONParser jsonParser = new JSONParser(); File file = new File(path); Object data = jsonParser.parse(new FileReader(file)); JsonObject jsonObject = new Gson().toJsonTree(data).getAsJsonObject(); HashMap<String, Object> result; try { result = new ObjectMapper().readValue(jsonObject.toString(), HashMap.class); RestRequestBean bean = new RestRequestBean(); bean.fillData(jsonObject.toString()); bean.resolveParameters(result); return WsStep.request(bean); } catch (JsonParseException e) { logger.info("JsonParseException: ", e); } catch (JsonMappingException e) { logger.info("JsonParseException: ", e); } catch (IOException e) { logger.info("JsonParseException: ", e); } return null; } @SuppressWarnings("unchecked") @QAFTestStep(description = "user requests with json data {0}") public static ClientResponse userRequestsWithJsonData(Object data) { /* * This method will trigger a request based from the json request variable key (old implementation) * Parameter: * - JSON Request Variable Key */ Logger logger = LoggerFactory.getLogger(WebServicesStepDef.class); System.out.println(data.getClass()); JsonObject jsonObject = new Gson().toJsonTree(data).getAsJsonObject(); HashMap<String, Object> result; try { result = new ObjectMapper().readValue(jsonObject.toString(), HashMap.class); System.out.println(jsonObject.toString()); RestRequestBean bean = new RestRequestBean(); bean.fillData(jsonObject.toString()); bean.resolveParameters(result); return WsStep.request(bean); }catch (JsonParseException e) { logger.info("JsonParseException: ", e); }catch (JsonMappingException f) { logger.info("JsonMappingException: ", f); }catch (IOException g) { logger.info("IOException: ", g); } return null; } @QAFTestStep(description = "store expected value {0} into key {1}") public static void storeResponseBodytoNew(Object value, String variable) { /* * This method will store the expected value {0} into a variable {1}. * You may use the datafile in the examples or you can delegate hard coded expected value * Parameters: * - Expected Value * - Variable Name */ String convertedValue = String.valueOf(value); getBundle().setProperty(variable, convertedValue); } // @QAFTestStep(description = "store expected int value {0} into key {1}") // public static void storeResponseBodyIntValue(int value, String variable) { // /* // * This method will store the expected value {0} into a variable {1}. // * You may use the datafile in the examples or you can delegate hard coded expected value // * Parameters: // * - Expected Value // * - Variable Name // */ // String convertedValueToInt = Integer.toString(value); // getBundle().setProperty(variable, convertedValueToInt); // } // // @QAFTestStep(description = "store expected long value {0} into key {1}") // public static void storeResponseBodyLongValue(long value, String variable) { // /* // * This method will store the expected value {0} into a variable {1}. // * You may use the datafile in the examples or you can delegate hard coded expected value // * Parameters: // * - Expected Value // * - Variable Name // */ // String convertedValueToLong = Long.toString(value); // getBundle().setProperty(variable, convertedValueToLong); // } @QAFTestStep(description="I wait for {0} seconds") public void iWaitForSeconds(int seconds) throws InterruptedException{ /* * This method will do hard wait for 'x' number of seconds * Parameters: * - Wait time (seconds) */ int secondsToSleep = seconds * 1000; Thread.sleep(secondsToSleep); } @QAFTestStep(description = "user run sessions endpoint {jsonRequestTemplate}") public static ClientResponse callSessionAPIEndpoint(String path) throws IOException, ParseException { /* * This method will store the expected value {0} into a variable {1}. * You may use the datafile in the examples or you can delegate hard coded expected value * Parameters: * - Expected Value * - Variable Name */ Logger logger = LoggerFactory.getLogger(WebServicesStepDef.class); if(ConfigurationManager.getBundle().getProperty("environment").equals("dev")) { logger.info("Session Environment is set to false"); }else if (ConfigurationManager.getBundle().getProperty("environment").equals("sit")) { userResuestsWithJsonDataFromPath(path); } return null; } @QAFTestStep(description="read Json from String {0} and store the response body {1} into variable {2}") public void readJsonFromStringAndStoreTheResponseBodyIntoVariable(String key,String path, String variable) { String jsonString = getBundle().getString(key); if (!path.startsWith("$")) path = "$." + path; String Jsonpathvalue = JsonPath.read(jsonString, path).toString().replace("\"", "").replace("[", "").replace("]", ""); //String Jsonpathvalue = JsonPath.read(jsonString, path).toString(); getBundle().setProperty(variable, Jsonpathvalue); } @QAFTestStep(description="show response value {0} in Console") public void showToken(String key) { System.out.println("value is = "+getBundle().getString(key)); } @QAFTestStep(description="store value from properties file {0} into variable {1} for parameter {2}") public void storeValueIntoBundleFromProperties(String property_filename, String key, String value) { try { temp_properties = genLib.getPropertyFile(property_filename); } catch (IOException e) { e.printStackTrace(); } getBundle().setProperty(key, temp_properties.getProperty(value)); } @QAFTestStep(description ="tests are run with test data flagged as {0} only") public void testCaseApiRun(String TCRun) throws Throwable { if(TCRun.equalsIgnoreCase("N")) { throw new SkipException("Skipping the testcase as the runmode for data set is N"); } } @QAFTestStep(description = "I verify the result between {0} and {1}") public void verifyString(String actual, String expected) { assertThat(getBundle().getString(actual), Matchers.equalToIgnoringCase(getBundle().getString(expected))); } @QAFTestStep(description = "response should have expected value contains {expectedvalue} at {jsonpath}") public static void responseShouldHaveExpectedKeyAndValueContains(Object value, String path) { if (!path.startsWith("$")) path = "$." + path; Object actual = JsonPath.read(new RestTestBase().getResponse().getMessageBody(), path); if(value==null|| value.toString().equals("")) { System.out.println("expected value null!"); System.out.println("actual = "+actual); System.out.println("Expected = "+value); Assert.assertEquals(actual, value); } else { System.out.println("expected value exist!"); String convertedValue = String.valueOf(value); System.out.println("actual = "+String.valueOf(actual)); System.out.println("Expected = "+convertedValue); assertThat(String.valueOf(actual), Matchers.containsString(convertedValue)); } } }
37.058333
120
0.731954
7ef8f1118483dda6a4b8db1524f596948d0857a1
1,956
package uk.gov.companieshouse.confirmationstatementapi.service; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import uk.gov.companieshouse.api.model.common.Address; import uk.gov.companieshouse.confirmationstatementapi.client.OracleQueryClient; import uk.gov.companieshouse.confirmationstatementapi.exception.ServiceException; import uk.gov.companieshouse.confirmationstatementapi.model.json.registerlocation.RegisterLocationJson; import java.util.Arrays; import java.util.List; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.mockito.Mockito.when; @ExtendWith(MockitoExtension.class) class RegisterLocationServiceTest { private static final String COMPANY_NUMBER = "12345678"; @Mock private OracleQueryClient oracleQueryClient; @InjectMocks private RegisterLocationService regLocService; @Test void getRegisterLocationsData() throws ServiceException { var regLoc1 = new RegisterLocationJson(); regLoc1.setRegisterTypeDesc("desc1"); regLoc1.setSailAddress(new Address()); var regLoc2 = new RegisterLocationJson(); regLoc2.setRegisterTypeDesc("desc2"); regLoc2.setSailAddress(new Address()); List<RegisterLocationJson> registerLocations = Arrays.asList(regLoc1, regLoc2); when(oracleQueryClient.getRegisterLocations(COMPANY_NUMBER)).thenReturn(registerLocations); var regLocData = regLocService.getRegisterLocations(COMPANY_NUMBER); assertNotNull(regLocService.getRegisterLocations(COMPANY_NUMBER)); assertEquals("desc1", regLocData.get(0).getRegisterTypeDesc()); assertEquals("desc2", regLocData.get(1).getRegisterTypeDesc()); assertEquals(2, regLocData.size()); } }
37.615385
103
0.781697
36dc264644ea50bd5e89a5c75731d620b1dd35e9
329
// "Replace method call on lambda with lambda body" "true" import java.util.function.Predicate; public class Test { public static void main(String[] args) { while(true) { System.out.println("hello"); if (!Collections.singleton("abc").contains("ab")) break; System.out.println("hello"); } } }
25.307692
64
0.638298
3e96d089cd4e5d2fcb43611226697f6c25ea4ce7
1,802
/* * 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. */ package org.apache.taverna.reference.impl.external.object; import java.io.IOException; import java.io.InputStream; import java.io.ObjectInputStream; import org.apache.taverna.reference.ReferencedDataNature; import org.apache.taverna.reference.StreamToValueConverterSPI; /** * Builds a VMObjectReference from an InputStream. * * @author Alex Nenadic */ public class StreamToVMObjectReferenceConverter implements StreamToValueConverterSPI<VMObjectReference> { @Override public Class<VMObjectReference> getPojoClass() { return VMObjectReference.class; } @Override public VMObjectReference renderFrom(InputStream stream, ReferencedDataNature dataNature, String charset) { VMObjectReference vmRef = new VMObjectReference(); try { ObjectInputStream in = new ObjectInputStream(stream); vmRef = (VMObjectReference) in.readObject(); return vmRef; } catch (IOException e) { throw new RuntimeException(e); } catch (ClassNotFoundException e) { throw new RuntimeException(e); } } }
32.178571
62
0.777469
c1280f3bb189e310e15c75d433b60aa2cd61cb3f
234
package com.ht.dev; public class BackEndDTO { String reponse; public String getReponse() { return reponse; } public void setReponse(String reponse) { this.reponse = reponse; } }
15.6
45
0.576923
dc4ef9ccce3f7249d7583a7600023cd37a7a662e
1,022
package info.itsthesky.disky3.core.skript.properties.message; import ch.njol.skript.doc.Description; import ch.njol.skript.doc.Examples; import ch.njol.skript.doc.Name; import ch.njol.skript.doc.Since; import info.itsthesky.disky3.api.messages.UpdatingMessage; import info.itsthesky.disky3.api.skript.properties.MultipleMessageProperty; import net.dv8tion.jda.api.entities.User; @Name("Message Mentioned Users") @Description("Get every mentioned users in a message.") @Since("3.0") @Examples("mentioned users of event-message") public class MessageMentionedUsers extends MultipleMessageProperty<User> { static { register( MessageMentionedUsers.class, User.class, "[discord] [message] mentioned users" ); } @Override public User[] converting(UpdatingMessage original) { if (original.getMessage().isFromGuild()) return original.getMessage().getMentionedUsers().toArray(new User[0]); return new User[0]; } }
30.969697
82
0.707436
decd9c6bc8ff46bf1436f7a7ebb2ce5136f4de3b
4,076
package io.github.junxworks.ep.sys.entity; import io.github.junxworks.ep.core.orm.annotations.Table; import io.github.junxworks.ep.core.orm.annotations.PrimaryKey; import io.github.junxworks.ep.core.orm.annotations.Column; import java.util.Date; /** * <p>Entity Class</p> * <p>Table: ep_s_org</p> * * @since 2021-2-19 15:18:04 Generated by JunxPlugin */ @Table(tableName="ep_s_org",tableComment="") public class EpSOrg { @PrimaryKey @Column(name="id", type="BIGINT", length="19", nullable="false", comment="编号") private Long id; @Column(name="create_user", type="BIGINT", length="19", nullable="true", comment="创建人编号") private Long createUser; @Column(name="create_time", type="TIMESTAMP", length="19", nullable="true", comment="创建日期") private Date createTime; @Column(name="update_user", type="BIGINT", length="19", nullable="true", comment="修改人编号") private Long updateUser; @Column(name="update_time", type="TIMESTAMP", length="19", nullable="true", comment="修改日期") private Date updateTime; @Column(name="status", type="TINYINT", length="3", nullable="true", comment="状态 -1已删除 0正常") private Byte status; @Column(name="org_no", type="VARCHAR", length="50", nullable="true", comment="组织编码") private String orgNo; @Column(name="org_name", type="VARCHAR", length="100", nullable="true", comment="组织名称") private String orgName; @Column(name="org_type", type="VARCHAR", length="20", nullable="true", comment="机构类型 参考码表机构类型 orgType") private String orgType; @Column(name="parent_no", type="VARCHAR", length="50", nullable="true", comment="直接上级机构编码") private String parentNo; @Column(name="top_level_no", type="VARCHAR", length="50", nullable="true", comment="顶级机构编码") private String topLevelNo; @Column(name="org_path", type="VARCHAR", length="200", nullable="true", comment="组织路径") private String orgPath; @Column(name="remark", type="VARCHAR", length="200", nullable="true", comment="备注") private String remark; public Long getId(){ return this.id; } public void setId(Long id){ this.id = id; } public Long getCreateUser(){ return this.createUser; } public void setCreateUser(Long createUser){ this.createUser = createUser; } public Date getCreateTime(){ return this.createTime; } public void setCreateTime(Date createTime){ this.createTime = createTime; } public Long getUpdateUser(){ return this.updateUser; } public void setUpdateUser(Long updateUser){ this.updateUser = updateUser; } public Date getUpdateTime(){ return this.updateTime; } public void setUpdateTime(Date updateTime){ this.updateTime = updateTime; } public Byte getStatus(){ return this.status; } public void setStatus(Byte status){ this.status = status; } public String getOrgNo(){ return this.orgNo; } public void setOrgNo(String orgNo){ this.orgNo = orgNo; } public String getOrgName(){ return this.orgName; } public void setOrgName(String orgName){ this.orgName = orgName; } public String getOrgType(){ return this.orgType; } public void setOrgType(String orgType){ this.orgType = orgType; } public String getParentNo(){ return this.parentNo; } public void setParentNo(String parentNo){ this.parentNo = parentNo; } public String getTopLevelNo(){ return this.topLevelNo; } public void setTopLevelNo(String topLevelNo){ this.topLevelNo = topLevelNo; } public String getOrgPath(){ return this.orgPath; } public void setOrgPath(String orgPath){ this.orgPath = orgPath; } public String getRemark(){ return this.remark; } public void setRemark(String remark){ this.remark = remark; } }
26.993377
107
0.634691
b2702712870d28158317134b8ed883d463bb714b
4,252
package nyc.c4q.artsy4android.models; public class Artist { /**SLUG OR ID VALUE CAN BE USED AS RETROFIT @PARAM TO DIRECT TO INDIVIDUAL ENDPOINT */ String id; String slug; String created_at; String updated_at; String name; String sortable_name; String gender; String biography; String birthday; String deathday; String hometown; String nationality; String location; String[] image_versions = new String[4]; Links _links; public String getId() { return id; } public String getSlug() { return slug; } public String getCreated_at() { return created_at; } public String getUpdated_at() { return updated_at; } public String getName() { return name; } public String getSortable_name() { return sortable_name; } public String getGender() { return gender; } public String getBiography() { return biography; } public String getBirthday() { return birthday; } public String getDeathday() { return deathday; } public String getHometown() { return hometown; } public String getLocation() { return location; } public String getNationality() { return nationality; } public String[] getImage_versions() { return image_versions; } public Links get_links() { return _links; } /** * Inner Class objects for JSON */ public class Links { Thumbnail thumbnail; Img image; Self self; PermaLink permaLink; ArtworksList artworksList; PublishedArtworks published_artworks; SimilarArtists similar_artists; SimilarContemporaryArtists similar_contemporary_artists; Genes genes; /** * * getters for outerclass */ public Genes getGenes() { return genes; } public SimilarContemporaryArtists getSimilar_contemporary_artists() { return similar_contemporary_artists; } public SimilarArtists getSimilar_artists() { return similar_artists; } public PublishedArtworks getPublished_artworks() { return published_artworks; } public ArtworksList getArtworksList() { return artworksList; } public PermaLink getPermaLink() { return permaLink; } public Self getSelf() { return self; } public Img getImage() { return image; } public Thumbnail getThumbnail() { return thumbnail; } /** * end of outer class getters */ /** * inner class, including getters and inner inner classes */ public class Thumbnail { String href; public String getHref() { return href; } } public class Img { String href; boolean templated; public String getHref() { return href; } public boolean isTemplated() { return templated; } } public class Self { String href; public String getHref() { return href; } } public class PermaLink { String href; public String getHref() { return href; } } public class PublishedArtworks { String href; public String getHref() { return href; } } public class SimilarArtists { String href; public String getHref() { return href; } } public class SimilarContemporaryArtists { String href; public String getHref() { return href; } } public class Genes { String href; public String getHref() { return href; } } } }
20.843137
87
0.519285
b9adedb4e033bed38ca72e1014d850c2f742a1b6
1,254
package net.xdevelop.snowflake.utils; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; public class DateUtils { /** * Patterns */ public static final String DAY_PATTERN = "yyyy-MM-dd"; public static final String DATETIME_PATTERN = "yyyy-MM-dd HH:mm:ss"; /** * Parse date by 'yyyy-MM-dd' pattern * * @param str * @return */ public static Date parseByDayPattern(String str) { try { SimpleDateFormat sdf = new SimpleDateFormat(DAY_PATTERN); return sdf.parse(str); } catch (ParseException e) { throw new RuntimeException(e); } } /** * Format date by 'yyyy-MM-dd HH:mm:ss' pattern * * @param date * @return */ public static String formatByDateTimePattern(Date date) { SimpleDateFormat sdf = new SimpleDateFormat(DATETIME_PATTERN); return sdf.format(date); } /** * Format date by 'yyyy-MM-dd' pattern * * @param date * @return */ public static String formatByDatePattern(Date date) { SimpleDateFormat sdf = new SimpleDateFormat(DAY_PATTERN); return sdf.format(date); } }
25.08
73
0.599681
689a9a7b9f794dfae91071b7519064fe3c1042ba
7,655
/** * Copyright 2013 Benjamin Lerer * * 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.horizondb.db.series; import io.horizondb.db.Configuration; import io.horizondb.db.HorizonDBException; import io.horizondb.io.files.FileUtils; import io.horizondb.model.ErrorCodes; import io.horizondb.model.schema.DatabaseDefinition; import io.horizondb.model.schema.RecordTypeDefinition; import io.horizondb.model.schema.TimeSeriesDefinition; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.concurrent.TimeUnit; import org.easymock.EasyMock; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; /** * */ public class OnDiskTimeSeriesManagerTest { private Path testDirectory; private Configuration configuration; private TimeSeriesPartitionManager partitionManager; @Before public void setUp() throws IOException { this.testDirectory = Files.createTempDirectory("test"); this.configuration = Configuration.newBuilder().dataDirectory(this.testDirectory.resolve("data")).build(); this.partitionManager = EasyMock.createNiceMock(TimeSeriesPartitionManager.class); } @After public void tearDown() throws IOException { FileUtils.forceDelete(this.testDirectory); this.testDirectory = null; this.configuration = null; this.partitionManager = null; } @Test public void testCreateTimeSeries() throws IOException, InterruptedException, HorizonDBException { TimeSeriesManager manager = new OnDiskTimeSeriesManager(this.partitionManager, this.configuration); RecordTypeDefinition quote = RecordTypeDefinition.newBuilder("Quote") .addDecimalField("bestBid") .addDecimalField("bestAsk") .addIntegerField("bidVolume") .addIntegerField("askVolume") .build(); DatabaseDefinition databaseDefinition = new DatabaseDefinition("test"); TimeSeriesDefinition definition = databaseDefinition.newTimeSeriesDefinitionBuilder("DAX") .timeUnit(TimeUnit.NANOSECONDS) .addRecordType(quote) .build(); manager.start(); manager.createTimeSeries(databaseDefinition, definition, true); manager.getTimeSeries(databaseDefinition, "DAX"); manager.shutdown(); } @Test public void testGetTimeSeriesWithUnknownTimeSeries() throws IOException, InterruptedException { TimeSeriesManager manager = new OnDiskTimeSeriesManager(this.partitionManager, this.configuration); manager.start(); try { manager.getTimeSeries(new DatabaseDefinition("test"), "DAX"); Assert.fail(); } catch (HorizonDBException e) { Assert.assertEquals(ErrorCodes.UNKNOWN_TIMESERIES, e.getCode()); } manager.shutdown(); } @Test public void testCreateTimeSeriesWithExistingTimeSeries() throws IOException, InterruptedException { TimeSeriesManager manager = new OnDiskTimeSeriesManager(this.partitionManager, this.configuration); manager.start(); try { RecordTypeDefinition quote = RecordTypeDefinition.newBuilder("Quote") .addDecimalField("bestBid") .addDecimalField("bestAsk") .addIntegerField("bidVolume") .addIntegerField("askVolume") .build(); DatabaseDefinition databaseDefinition = new DatabaseDefinition("test"); TimeSeriesDefinition definition = databaseDefinition.newTimeSeriesDefinitionBuilder("DAX") .timeUnit(TimeUnit.NANOSECONDS) .addRecordType(quote) .build(); manager.createTimeSeries(databaseDefinition, definition, true); TimeSeriesDefinition definition2 = databaseDefinition.newTimeSeriesDefinitionBuilder("dax") .timeUnit(TimeUnit.NANOSECONDS) .addRecordType(quote) .build(); manager.createTimeSeries(databaseDefinition, definition2, true); Assert.fail(); } catch (HorizonDBException e) { Assert.assertEquals(ErrorCodes.DUPLICATE_TIMESERIES, e.getCode()); } manager.shutdown(); } @Test public void testCreateTimeSeriesWithExistingTimeSeriesAndThrowExceptionFalse() throws IOException, InterruptedException, HorizonDBException { TimeSeriesManager manager = new OnDiskTimeSeriesManager(this.partitionManager, this.configuration); manager.start(); RecordTypeDefinition quote = RecordTypeDefinition.newBuilder("Quote") .addDecimalField("bestBid") .addDecimalField("bestAsk") .addIntegerField("bidVolume") .addIntegerField("askVolume") .build(); DatabaseDefinition databaseDefinition = new DatabaseDefinition("test"); TimeSeriesDefinition definition = databaseDefinition.newTimeSeriesDefinitionBuilder("DAX") .timeUnit(TimeUnit.NANOSECONDS) .addRecordType(quote) .build(); manager.createTimeSeries(databaseDefinition, definition, true); TimeSeriesDefinition definition2 = databaseDefinition.newTimeSeriesDefinitionBuilder("dax") .timeUnit(TimeUnit.NANOSECONDS) .addRecordType(quote) .build(); manager.createTimeSeries(databaseDefinition, definition2, false); manager.shutdown(); } }
40.289474
114
0.548008
51ad5d9c2e03d526897671c6d8c7ac95d7e10708
718
package org.minimalj.example.openapiclient.page; import org.minimalj.frontend.action.ActionGroup; import org.minimalj.frontend.action.Separator; import org.minimalj.metamodel.model.MjEntity; import org.minimalj.metamodel.model.MjEntity.MjEntityType; import org.minimalj.metamodel.model.MjModel; public class EntityTableActions extends ActionGroup { public EntityTableActions(MjModel model) { super("Browser"); for (MjEntity entity : model.entities) { if (entity.type == MjEntityType.ENTITY) { add(new EntityTablePage<>(entity)); } } add(new Separator()); for (MjEntity entity : model.entities) { if (entity.type == MjEntityType.CODE) { add(new EntityTablePage<>(entity)); } } } }
26.592593
58
0.743733
725bf4eb00da6418da6c8c5063a662b7cac268f2
53
package com.ssdi; public interface Create { }
8.833333
26
0.660377
67de4a2794fd1452b536d1bb67b53e3b1be10ca6
66,413
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package math.matrix.expressParser; import java.util.HashMap; import java.util.InputMismatchException; import java.util.List; import java.util.Random; import parser.CustomScanner; import parser.Operator; /** * * @author GBEMIRO */ public class Matrix { public static final String lambda = "n"; /** * The simple name used to label this Matrix object. * */ private String name; /** * the data array used to create this Matrix object */ private double array[][]; /** * attribute used to cofactorDet the detMultiplier of the Matrix object. */ private static double det = 0; /** * * @param rows The number of row in the Matrix. * @param cols The number of columns in the Matrix. */ public Matrix(int rows, int cols) { this("NEW"); array = new double[rows][cols]; }//end constructor /** * @param name the simple name used to identify used by the user to label * this Matrix object. * * Assigns name unknown to the Matrix object and a 2D array that has just a * row and a column * */ public Matrix(String name) { this.name = name; this.array = new double[][]{{0}}; } /** * * @param array the data array used to create this Matrix object */ public Matrix(double[][] array) { this("NEW"); setArray(array); }//end constructor /** * * @param matrix constructs a new Matrix object having similar properties to * the one passed as argument, but holding no reference to its data. */ public Matrix(Matrix matrix) { this("NEW"); double arr[][] = new double[matrix.getRows()][matrix.getCols()]; /* Copy the array of the Matrix object parameter into * a separate array object and use for the * Matrix object about to be created. * This ensures that the new Matrix object * has no connection to the one from which it is created * so that it is a true twin or duplicate of the other one. * The user is free to perform operations on this one without fear * that it will cause changes in the other one. * * */ for (int row = 0; row < matrix.getRows(); row++) { for (int col = 0; col < matrix.getCols(); col++) { double val = matrix.array[row][col]; arr[row][col] = val; }//end inner loop }//end outer loop this.array = arr; }//end constructor /** * * @return the number of row in this matrix object */ public int getRows() { return array.length; } /** * * @return the number of columns in this matrix object */ public int getCols() { return array[0].length; } /** * * @param array sets the data of this matrix */ public void setArray(double[][] array) { if (array.length > 0) { this.array = new double[array.length][array[0].length]; for (int row = 0; row < array.length; row++) { for (int col = 0; col < array[0].length; col++) { this.array[row][col] = array[row][col]; }//end inner loop }//end outer loop } else { this.array = new double[][]{{0}, {0}}; } }//end method /** * * @return the data of this matrix */ public double[][] getArray() { return this.array; } public double getElem(int row, int col) { return array[row][col]; } /** * * @param det the detMultiplier attribute of objects of this class */ private static void setDet(double det) { Matrix.det = det; } /** * * @return the detMultiplier */ private static double getDet() { return det; } /** * * @param name set's the simple name used to identify used by the user to * label this Matrix object. */ public void setName(String name) { this.name = name; } /** * * @return the simple name used to identify used by the user to label this * Matrix object. */ public String getName() { return name; } /** * * @param row The row whose contents we desire. * @return the contents of the row. */ private double[] getRow(int row) { if (row < getRows()) { return array[row]; } throw new IndexOutOfBoundsException("Bad Index, " + row); }//end method. /** * * @param row1 The first row. * @param row2 The second row. * * <b color='red'> BE CAREFUL!!!!<br> * THIS METHOD ACTS ON THE MATRIX OBJECT ON WHICH IT IS CALLED AND MODIFIES * IT! * </b> * */ public void swapRow(int row1, int row2) { for (int column = 0; column < getCols(); column++) { double v1 = array[row1][column]; double v2 = array[row2][column]; double v3 = v1; array[row1][column] = v2; array[row2][column] = v3; }//end for }//end method. /** * * @param col1 The first row. * @param col2 The second row. * * <b color='red'> BE CAREFUL!!!!<br> * THIS METHOD ACTS ON THE MATRIX OBJECT ON WHICH IT IS CALLED AND MODIFIES * IT! * </b> * */ public void swapColumn(int col1, int col2) { for (int row = 0; row < getRows(); row++) { double v1 = array[row][col1]; double v2 = array[row][col2]; double v3 = v1; array[row][col1] = v2; array[row][col2] = v3; }//end for }//end method. /** * Fills this matrix object with values */ public void fill() { java.util.Scanner scanner = new java.util.Scanner(System.in); for (int row = 0; row < getRows(); row++) { for (int column = 0; column < getCols(); column++) { array[row][column] = scanner.nextDouble(); } } }//end method fill. /** * * @param matrice the matrix to be added to this one. The operation is ( * this + matrice ) * @return a Matrix containing the product matrix. */ public Matrix add(Matrix matrice) { double array1[][] = matrice.array; double matrix[][] = new double[getRows()][getCols()]; if (getRows() == matrice.getCols() && getCols() == matrice.getRows()) { for (int row = 0; row < getRows(); row++) { for (int column = 0; column < getCols(); column++) { matrix[row][column] = (array[row][column]) + (array1[row][column]); }//end inner for }//end outer for }//end if else { System.out.println("ERROR IN MATRIX INPUT!!"); } return new Matrix(matrix); }//end method add /** * * @param matrice the matrix to be subtracted from this one. The operation * is ( this - matrice ) * @return a Matrix containing the product matrix. */ public Matrix subtract(Matrix matrice) { double array1[][] = matrice.array; double matrix[][] = new double[getRows()][getCols()]; if (getRows() == matrice.getCols() && getCols() == matrice.getRows()) { for (int row = 0; row < getRows(); row++) { for (int column = 0; column < getCols(); column++) { matrix[row][column] = (array[row][column]) - (array1[row][column]); }//end inner for }//end outer for }//end ifghjjk else { System.out.println("ERROR IN MATRIX INPUT!!"); } return new Matrix(matrix); }//end method subtract /** * * @param scalar the constant to be multiplied with this matrix The * operation is ( scalar X matrice ) * @return an array containing the product matrix. */ public Matrix scalarMultiply(double scalar) { double matrix[][] = new double[getRows()][getCols()]; for (int row = 0; row < getRows(); row++) { for (int column = 0; column < getCols(); column++) { matrix[row][column] = scalar * (array[row][column]); }//end inner for }//end outer for return new Matrix(matrix); }//end method scalarMultiply /** * * @param scalar the constant to be multiplied with this matrix The * operation is ( matrice/scalar ) * @return an array containing the scaled matrix. */ public Matrix scalarDivide(double scalar) { double matrix[][] = new double[getRows()][getCols()]; for (int row = 0; row < getRows(); row++) { for (int column = 0; column < getCols(); column++) { matrix[row][column] = (array[row][column]) / scalar; }//end inner for }//end outer for return new Matrix(matrix); }//end method scalarDivide /** * * The operation of matrix multiplication. For this method to run, The * pre-multiplying matrix must have its number of columns equal to the * number of row in the pre-multiplying one. * * The product matrix is one that has its number of columns equal to the * number of columns in the pre-multiplying matrix, and its row equal to * that in the post-multiplying matrix. * * * So if the operation is A X B = C, and A is an m X n matrix while B is an * r X p matrix, then r = n is a necessary condition for the operation to * occur. Also, C is an m X p matrix. * * @param matrice1 the matrix to be pre-multiplying the other one. The * operation is ( matrice1 X matrice2 ) * @param matrice2 the post-multiplying matrix * @return a new Matrix object containing the product matrix of the * operation matrice1 X matrice2 */ public static Matrix multiply(Matrix matrice1, Matrix matrice2) { Matrix m = new Matrix(matrice1.getRows(), matrice2.getCols()); if (matrice1.getCols() == matrice2.getRows()) { for (int i = 0; i < matrice1.getRows(); i++) { for (int row = 0; row < matrice2.getCols(); row++) { double sum = 0; for (int column = 0; column < matrice1.getCols(); column++) { sum += matrice1.array[i][column] * matrice2.array[column][row]; }//end inner for m.array[i][row] = sum; }//end outer for }//end outermost for }//end if else { System.out.println("ERROR IN MATRIX INPUT!!"); } return m; } /** * * @param matrice the matrix to be multiplied by this one. This operation * modifies this matrix and changes its data array into that of the product * matrix The operation is ( this X matrice ) */ public void multiply(Matrix matrice) { setArray(Matrix.multiply(this, matrice).array); } /** * * @param mat the matrix to raise to a given power * @param pow the power to raise this matrix to * @return the */ public static Matrix pow(Matrix mat, int pow) { Matrix m = new Matrix(mat.array); for (int i = 0; i < pow - 1; i++) { m = Matrix.multiply(m, mat); } return m; } public static Matrix power(Matrix mat, int pow) { assert (pow >= 0); switch (pow) { case 0: return unitMatrix(mat.getRows(), mat.getCols()); case 1: return mat; default: /** * n=3: * mul(power(mat,2),mat)---mul(mul(power(mat,1),mat),mat)--mul( * mul(mat,mat),mat )---mul(mat2,mat)-->mat3 */ return multiply(power(mat, pow - 1), mat); } } /** * * @return a unit matrix of the same dimension as this matrix object */ public Matrix unitMatrix() { double matrix[][] = new double[getRows()][getCols()]; for (int row = 0; row < getRows(); row++) { for (int column = 0; column < getCols(); column++) { if (column == row) { matrix[row][column] = 1; } else { matrix[row][column] = 0; } }//end inner for loop }//end outer for loop return new Matrix(matrix); }//end method unitMatrix /** * * @param rowSize the number of row that the unit matrix will have * @param colSize the number of columns that the unit matrix will have * @return a unit matrix having number of row = rowSize and number of * columns=colSize. */ public static Matrix unitMatrix(int rowSize, int colSize) { double matrix[][] = new double[rowSize][colSize]; for (int row = 0; row < rowSize; row++) { for (int column = 0; column < colSize; column++) { if (column == row) { matrix[row][column] = 1; } else { matrix[row][column] = 0; } }//end inner for loop }//end outer for loop return new Matrix(matrix); }//end method unitMatrix /** * * @param mat the Matrix object that we wish to construct a unit matrix of * similar dimensions for. * @return a unit matrix of equal dimensions as this unit matrix. */ public static Matrix unitMatrix(Matrix mat) { int rowSize = mat.getRows(); int colSize = mat.getCols(); double matrix[][] = new double[rowSize][colSize]; for (int row = 0; row < rowSize; row++) { for (int column = 0; column < colSize; column++) { if (column == row) { matrix[row][column] = 1; } else { matrix[row][column] = 0; } }//end inner for loop }//end outer for loop return new Matrix(matrix); }//end method unitMatrix /** * Place the first Matrix object side by side with the second one passed as * argument to this method. The result is a new matrix where: * * if 3 4 5 7 5 9 mat1 = 2 3 1 and mat2 = 4 2 6 1 6 7 5 7 3 in a new matrix * object (mat). * * * e.g 3 4 5 7 5 9 2 3 1 4 2 6 1 6 7 5 7 3 A necessary condition for this * method to run is that the 2 objects must have an equal number of row. IF * THIS CONDITION IS NOT MET, THE METHOD RETURNS A ZERO MATRIX. * * * @param mat1 the first Matrix object * @param mat2 the second Matrix object that we column join with this one * @return a new Matrix object that contains this Matrix object placed side * by side with the Matrix object passed as argument. */ public static Matrix columnJoin(Matrix mat1, Matrix mat2) { Matrix join = new Matrix(mat1.getRows(), mat1.getCols() + mat2.getCols()); if (mat1.getRows() == mat2.getRows()) { int columnextender = 0; for (int row = 0; row < mat1.getRows(); row++) { for (int col = 0; col < join.getCols(); col++) { if (col < mat1.getCols()) { columnextender = 0;//reset to zero join.array[row][col] = mat1.array[row][col]; } else if (col >= mat1.getCols()) { join.array[row][col] = mat2.array[row][columnextender]; columnextender++; } }//end inner for }//end outer for }//end if return join; } /** * * @param value The value to insert * @param row The row where the value is to be inserted. * @param column The column where the value is to be inserted. */ public boolean update(double value, int row, int column) { if (row < getRows() && column < getCols()) { array[row][column] = value; return true; } return false; } /** * Place the first Matrix object side by side with the second one passed as * argument to this method. The result is a new matrix where: * * if 3 4 5 7 5 9 mat1 = 2 3 1 and mat2 = 4 2 6 1 6 7 5 7 3 in a new matrix * object (mat). * * * e.g 3 4 5 2 3 1 1 6 7 7 5 9 4 2 6 5 7 3 * * A necessary condition for this method to run is that the 2 objects must * have an equal number of columns. IF THIS CONDITION IS NOT MET, THE METHOD * RETURNS A ZERO MATRIX. * * @param mat1 the first Matrix object * @param mat2 the second Matrix object that we row join with this one * @return a new Matrix object that contains the first Matrix object * argument placed top to bottom with the second Matrix object argument. */ public static Matrix rowJoin(Matrix mat1, Matrix mat2) { Matrix join = new Matrix(mat1.getRows() + mat2.getRows(), mat1.getCols()); if (mat1.getCols() == mat2.getCols()) { int rowextender = 0; for (int row = 0; row < join.getRows(); row++) { for (int col = 0; col < join.getCols(); col++) { if (row < mat1.getRows()) { join.array[row][col] = mat1.array[row][col]; } else if (row >= mat1.getRows()) { join.array[row][col] = mat2.array[rowextender][col]; } }//end inner for if (row >= mat1.getRows()) { rowextender++; } }//end outer for }//end if return join; }//end method rowJoin /** * Deletes all the specified number of columns from the Matrix object * starting from the end of the Matrix object * * @param column the number of columns to remove from the Matrix object. * This method will take the object that calls it and perform this operation * on it. So it modifies the Matrix object that calls it. Be careful, as * data will be lost. * * e.g if 3 4 5 6 7 8 9 2 1 8 1 4 7 0 A = 3 3 2 1 5 7 1 * * then the call: * * A.columnDeleteFromEnd(3) * * will delete the last three columns in this object leaving: * * 3 4 5 6 * A = 2 1 8 1 * 3 3 2 1 * * */ public void columnDeleteFromEnd(int column) { if (column >= 0 && column <= getCols()) { Matrix matrix = new Matrix(this.getRows(), this.getCols() - column); for (int row = 0; row < getRows(); row++) { for (int col = 0; col < matrix.getCols(); col++) { matrix.array[row][col] = this.array[row][col]; }//end inner for }//end outer for this.setArray(matrix.array); } else { System.out.println("COLUMN VALUE SHOULD " + "RANGE FROM ZERO TO THE NUMBER OF COLUMNS IN THIS MATRIX."); } }//end method columnDeleteFromEnd /** * Deletes all the specified number of columns from the Matrix object from * the beginning of the Matrix object * * @param column the number of columns to remove from the Matrix object's * beginning. This method will take the object that calls it and perform * this operation on it. So it modifies the Matrix object that calls it. Be * careful, as data will be lost. * * e.g if 3 4 5 6 7 8 9 2 1 8 1 4 7 0 A = 3 3 2 1 5 7 1 * * then the call: * * A.columnDeleteFromStart(3) * * will delete the last three columns in this object leaving: * * 6 7 8 9 * A= 1 4 7 0 1 5 7 1 * * */ public void columnDeleteFromStart(int column) { if (column >= 0 && column <= getCols()) { Matrix matrix = new Matrix(this.getRows(), this.getCols() - column); for (int row = 0; row < getRows(); row++) { int counter = 0; for (int col = column; col < getCols(); col++, counter++) { matrix.array[row][counter] = this.array[row][col]; }//end inner for }//end outer for this.setArray(matrix.array); } else { System.out.println("COLUMN VALUE SHOULD " + "RANGE FROM ZERO TO THE NUMBER OF COLUMNS IN THIS MATRIX."); } }//end method columnDeleteFromStart /** * Deletes the specified number of row from the end of the Matrix object * * @param numOfRows the number of row to remove from the Matrix object's * beginning. This method will take the object that calls it and perform * this operation on it. So it modifies the Matrix object that calls it. Be * careful, as data will be lost. * * e.g if 3 4 5 6 2 1 8 1 A = 3 3 2 1 7 8 9 2 4 7 0 5 5 7 1 8 then the call: * * A.rowDeleteFromEnd(3) * * will delete the last three row in this object leaving: * * * 3 4 5 6 * 2 1 8 1 * A = 3 3 2 1 * * */ public void rowDeleteFromEnd(int numOfRows) { if (numOfRows >= 0 && numOfRows <= getRows()) { Matrix matrix = new Matrix(this.getRows() - numOfRows, this.getCols()); for (int row = 0; row < matrix.getRows(); row++) { for (int col = 0; col < getCols(); col++) { matrix.array[row][col] = this.array[row][col]; }//end inner for }//end outer for this.setArray(matrix.array); } else { System.out.println("NUMBER OF ROWS TO BE DELETED SHOULD " + "RANGE FROM ZERO TO (AND INCLUDING) THE NUMBER OF ROWS IN THIS MATRIX."); } }//end method rowDeleteFromEnd /** * Deletes the specified number of row from the beginning of the Matrix * object * * @param numOfRows the number of row to remove from the Matrix object's * beginning. This method will take the object that calls it and perform * this operation on it. So it modifies the Matrix object that calls it. Be * careful, as data will be lost. * * e.g if 3 4 5 6 2 1 8 1 A = 3 3 2 1 7 8 9 2 4 7 0 5 5 7 1 8 then the call: * * A.rowDeleteFromStart(3) * * will delete the last three row in this object leaving: * * * A = 7 8 9 2 * 4 7 0 5 * 5 7 1 8 * * */ public void rowDeleteFromStart(int numOfRows) { if (numOfRows >= 0 && numOfRows <= getRows()) { Matrix matrix = new Matrix(this.getRows() - numOfRows, this.getCols()); int counter = 0; for (int row = numOfRows; row < getRows(); row++, counter++) { for (int col = 0; col < getCols(); col++) { matrix.array[counter][col] = this.array[row][col]; }//end inner for }//end outer for this.setArray(matrix.array); } else { System.out.println("NUMBER OF ROWS TO BE DELETED SHOULD " + "RANGE FROM ZERO TO (AND INCLUDING) THE NUMBER OF ROWS IN THIS MATRIX."); } }//end method rowDeleteFromStart /** * * @return an upper triangular matrix obtained by row reduction. */ public Matrix reduceToTriangularMatrix() { Matrix mat = new Matrix(this); //Now we row-reduce. for (int row = 0; row < mat.getRows(); row++) { if (row >= this.getCols()) { break; } double val = mat.array[row][row]; /** * The division coefficient must not be zero. If zero, search for a * lower row, and swap. */ if (val == 0.0) { for (int rw = row; rw < mat.getRows(); rw++) { val = mat.array[rw][row]; if (val != 0.0) { mat.swapRow(row, rw); break; }//end if }//end for loop if (val == 0.0) { throw new InputMismatchException("EQUATION CANNOT BE SOLVED"); } }//end if for (int col = row; col < mat.getCols(); col++) { mat.array[row][col] /= val; }//end inner for loop for (int rowed = row + 1; rowed < mat.getRows(); rowed++) { double mul = mat.array[rowed][row]; for (int coled = row; coled < mat.getCols(); coled++) { mat.array[rowed][coled] = mat.array[rowed][coled] - mul * mat.array[row][coled]; }//end for }//end for }//end outer for loop return mat; }//end method /** * * @return an upper triangular matrix obtained by row reduction. */ public Matrix reduceToRowEchelonMatrix() { Matrix mat = new Matrix(this); //Now we row-reduce. for (int row = 0; row < mat.getRows(); row++) { if (row >= this.getCols()) { break; } double val = mat.array[row][row]; /** * The division coefficient must not be zero. If zero, search for a * lower row, and swap. */ if (val == 0.0) { for (int rw = row; rw < mat.getRows(); rw++) { val = mat.array[rw][row]; if (val != 0.0) { mat.swapRow(row, rw); break; }//end if }//end for loop if (val == 0.0) { throw new InputMismatchException("EQUATION CANNOT BE SOLVED"); } }//end if for (int rowed = row + 1; rowed < mat.getRows(); rowed++) { double mul = mat.array[rowed][row]; for (int coled = row; coled < mat.getCols(); coled++) { mat.array[rowed][coled] = val * mat.array[rowed][coled] - mul * mat.array[row][coled]; }//end for }//end for }//end outer for loop return mat; }//end method /** * Used to solve a system of simultaneous equations placed in this Matrix * object. * * @return a Matrix object containing the solution matrix. */ public Matrix solveEquation() { return Matrix.solveEquation(this); }//end method solnMatrix /** * Used to solve a system of simultaneous equations placed in the Matrix * object. * * @param matrix The row X row+1 matrix, containing the system of linear * equations * @return a Matrix object containing the solution matrix. */ public static Matrix solveEquation(Matrix matrix) { Matrix solnMatrix = new Matrix(matrix.getRows(), 1); Matrix matrixLoader = matrix.reduceToTriangularMatrix(); // System.out.println( matrixLoader ); if (matrix.getRows() == matrix.getCols() - 1) { //Back-Substitution Algorithm. double sum = 0;//summation variable int counter = 1; for (int row = matrixLoader.getRows() - 1; row >= 0; row--) { for (int col = row + 1; col < matrixLoader.getCols(); col++) { if (col < matrixLoader.getCols() - 1) { sum += (matrixLoader.array[row][col] * solnMatrix.array[col][0]);//sum the product of each coefficient and its unknown's value in the solution matrix } else if (col == matrixLoader.getCols() - 1) { sum = matrixLoader.array[row][col] - sum;//end of summing.Now subtract the sum from the last entry on the row } }//end inner loop solnMatrix.array[matrixLoader.getRows() - counter][0] = sum / matrixLoader.array[row][row]; counter++;// increment counter sum = 0;//reset sum }//end outer loop }//end if else { throw new IndexOutOfBoundsException("Invalid System Of Linear Equations"); }//end else return solnMatrix; }//end method solnMatrix /** * * @return the transpose of this Matrix object. Does not modify this matrix * object but generates the transpose of this Matrix object as another * Matrix object. */ public Matrix transpose() { double matrix[][] = new double[getCols()][getRows()]; for (int row = 0; row < getRows(); row++) { for (int col = 0; col < getCols(); col++) { matrix[col][row] = array[row][col]; }//end inner for }//end outer for return new Matrix(matrix); }//end method transpose public Matrix adjoint() { if (isSquareMatrix()) { int rows = getRows(); int cols = getCols(); double matrix[][] = new double[rows][cols]; for (int row = 0; row < rows; row++) { for (int col = 0; col < cols; col++) { matrix[row][col] = getCofactor(row, col).determ(); }//end inner for }//end outer for return new Matrix(matrix).transpose(); } return null; } /** * * @return a matrix that contains the cofactors of the elements of this Matrix. */ public Matrix getCofactorMatrix() { if (isSquareMatrix()) { int rows = getRows(); int cols = getCols(); double matrix[][] = new double[rows][cols]; int count = 0; for (int row = 0; row < rows; row++) { for (int col = 0; col < cols; col++, count++) { matrix[row][col] = (count%2==0 ? 1 : -1)*getCofactor(row, col).determ(); }//end inner for }//end outer for return new Matrix(matrix); } return null; } /** * * @param i the row on which the element whose minor is needed lies. * @param j the column on which the element whose minor is needed lies. * @return the minor of this matrix relative to this element. */ public Matrix minor(int i, int j) { double matrix[][] = new double[getRows() - 1][getCols() - 1]; for (int row = 0; row < getRows(); row++) { for (int column = 0; column < getCols(); column++) { if (row < i && column < j) { matrix[row][column] = array[row][column]; } else if (row < i && column > j) { matrix[row][column - 1] = array[row][column]; } else if (row > i && column < j) { matrix[row - 1][column] = array[row][column]; } else if (row > i && column > j) { matrix[row - 1][column - 1] = array[row][column]; } }//end inner for }//end outer for return new Matrix(matrix); }//end method minor /** * * @return true if this Matrix object is a square matrix. */ public boolean isSquareMatrix() { return getRows() == getCols(); } /** * * @return true if this Matrix object can represent a system of equations * solvable by reduction to triangular form and subsequent evaluation. */ public boolean isSystemOfEquations() { return getRows() == getCols() - 1; } /** * * @param m a 2 X 2 matrix * @return the detMultiplier of this matrix */ private static double $2X2determinant(Matrix m) { return m.array[0][0] * m.array[1][1] - m.array[1][0] * m.array[0][1]; } /** * * @param m a 2 X 2 matrix * @return the detMultiplier of this matrix */ private static String $2X2determinantForEigen(String[][] m) { /* { {2-n , 4} {3 , 5-n} } m[0][0].m[1][1]-m[1][0].m[0][1] */ //looks like (2-n)(3-n)-(4)(2) String v1 = "", v2 = ""; if (parser.Number.validNumber(m[1][0]) && parser.Number.validNumber(m[0][1])) { double val = Double.parseDouble(m[1][0]) * Double.parseDouble(m[0][1]); v1 = String.valueOf(val); } if (parser.Number.validNumber(m[0][0]) && parser.Number.validNumber(m[1][1])) { double val = Double.parseDouble(m[0][0]) * Double.parseDouble(m[1][1]); v2 = String.valueOf(val); } if (!v1.isEmpty() && !v2.isEmpty()) { return String.valueOf(Double.parseDouble(v2) - Double.parseDouble(v1)); } String expr1 = v1.isEmpty() ? uniVariableExpressionExpander(lambda, m[1][0], m[0][1]) : v1; String expr2 = v2.isEmpty() ? uniVariableExpressionExpander(lambda, m[0][0], m[1][1]) : v2; String negExpr1 = uniVariableExpressionExpander(lambda, "-1", expr1); String expanded = uniVariableExpressionExpander(lambda, "1", expr2 + "+" + negExpr1); return expanded; } /** * @param m the matrix whose top row is to be multiplied by a scalar * Multiplies the top row of a matrix by a scalar. This is an important * operation during the evaluation of a detMultiplier. */ private static Matrix topRowScalarMultiply(Matrix m, double scalar) { for (int col = 0; col < m.getCols(); col++) { m.array[0][col] *= scalar; } return new Matrix(m.array); } /** * Sarus' rule for computing determinants. This technique is too slow and * memory intensive for large matrices..n>=10. Please use the determ() * instance method. It uses a O(cube_n) algorithm as against this method's * O(n!) * * @param m the Matrix object whose detMultiplier is desired. * @return the detMultiplier of the matrix */ private static double det(Matrix m) { //must be square matrix if (m.getRows() == m.getCols()) { if (m.getRows() == 2) { return $2X2determinant(m); }//end else else { for (int col = 0; col < m.getCols(); col++) { double topRow = m.array[0][col] * Math.pow(-1, col); Matrix mat = topRowScalarMultiply(m.minor(0, col), topRow); if (mat.getRows() > 2) { det(mat); } else { det += $2X2determinant(mat); } }//end for return det; }//end else }//end if else { return Double.POSITIVE_INFINITY; }//end else }//end method detMultiplier /** * * @return the determinant of this matrix using a row reduction technique. */ public double determinant() { return this.determ(); } /** * Fills the matrix with randomly generated values between 1 and 101. */ public void randomFill() { Random ran = new Random(); for (int row = 0; row < getRows(); row++) { for (int col = 0; col < getCols(); col++) { array[row][col] = 1 + (double) ran.nextInt(101); }//end inner for }//end outer for }//end method randomFill /** * Fills the matrix with randomly generated values between 1 and n * * @param n the maximum possible size of the integer numbers generated. */ public void randomFill(int n) { Random ran = new Random(); for (int row = 0; row < getRows(); row++) { for (int col = 0; col < getCols(); col++) { array[row][col] = 1 + ran.nextInt(n); }//end inner for }//end outer for }//end method randomFill /** * * @param matrixValue A string that is to be checked if it conforms to valid * syntax for representing a matrix in this software. * @return true if the command string is a valid matrix.e.g * [2,1,4:5,3,-2:4,4,5] value. */ public static boolean isMatrixValue(String matrixValue) { MatrixValueParser matrixValueParser = new MatrixValueParser(matrixValue); boolean isValid = matrixValueParser.isValid(); return isValid; } /** * * @return a string representation of the matrix in row and columns. */ @Override public String toString() { String output = "\n"; String appender = ""; for (int row = 0; row < getRows(); row++) { for (int column = 0; column < getCols(); column++) { if (column < getCols()) { appender += String.format("%7s%3s", array[row][column], ","); } if (column == getCols() - 1) { appender = appender.substring(0, appender.length() - 1); appender += " \n"; } output += appender; appender = ""; } } return output; }//end method toString /** * @param mat The string matrix */ public static void printTextMatrix(String[][] mat) { String output = "\n"; String appender = ""; int rows = mat.length; if (mat.length == 0) { System.out.println("EMPTY"); } int cols = mat[0].length; for (int row = 0; row < rows; row++) { for (int column = 0; column < cols; column++) { if (column < cols) { appender += String.format("%7s%3s", mat[row][column], ","); } if (column == cols - 1) { appender = appender.substring(0, appender.length() - 1); appender += " \n"; } output += appender; appender = ""; } } System.out.println("MATRIX:\n" + output); }//end method toString /** * * @param row The row in this Matrix object to be converted into a new * Matrix object. This operation generates a new Matrix object which is a * row matrix. */ public Matrix getRowMatrix(int row) { double[][] arr = new double[1][getCols()]; for (int col = 0; col < getCols(); col++) { arr[0][col] = array[row][col]; }//end for return new Matrix(arr); } /** * * @param column The column to be converted into a new Matrix object. This * operation generates a new Matrix object which is a column matrix. */ public Matrix getColumnMatrix(int column) { double[][] arr = new double[getRows()][1]; for (int row = 0; row < getRows(); row++) { arr[row][0] = array[row][column]; }//end for return new Matrix(arr); } /** * Computes the inverse of this Matrix object. This technique should never * be used in practise as it is a mere proof of concept. It computes the * inverse by computing the roots of the equations and then reverse * engineering the form A.x = B to get the inverse matrix. * * @return the inverse of the Matrix as another Matrix object. */ public Matrix oldInverse() { Matrix m = new Matrix(this); Matrix unit = m.unitMatrix(); Matrix inverse = new Matrix(new double[m.getRows()][m.getCols()]); if (m.isSquareMatrix()) { for (int rows = 0; rows < m.getCols(); rows++) { Matrix c = Matrix.columnJoin(m, unit.getColumnMatrix(rows)); inverse = Matrix.columnJoin(inverse, c.solveEquation()); }//end for }//end if inverse.columnDeleteFromStart(m.getRows()); return inverse; } /** * Row reduction technique used to compute the inverse of the matrix. Always * use this technique. * * @return the inverse of the Matrix as another Matrix object. */ public Matrix inverse() { Matrix m = new Matrix(this); if (m.isSquareMatrix()) { Matrix unit = m.unitMatrix(); Matrix inverse = Matrix.columnJoin(this, unit); int rows = inverse.getRows(); int cols = inverse.getCols(); for (int row = 0; row < rows; row++) { double pivot = inverse.array[row][row]; /** * The division coefficient must not be zero. If zero, search * for a lower row, and swap. */ if (pivot == 0.0) { for (int rw = row; rw < rows; rw++) { pivot = inverse.array[rw][row]; if (pivot != 0.0) { inverse.swapRow(row, rw); break; }//end if }//end for loop if (pivot == 0.0) { throw new InputMismatchException("INVERSE DOES NOT EXISTS!"); } }//end if for (int col = row; col < cols; col++) { inverse.array[row][col] /= pivot; }//end inner for loop for (int rw = row + 1; rw < rows; rw++) { double newRowMultiplier = -1 * inverse.array[rw][row]; for (int col = row; col < cols; col++) { inverse.array[rw][col] = newRowMultiplier * inverse.array[row][col] + inverse.array[rw][col]; } }//end inner for loop }//end for //////////////Now reduce upwards from the right border of the main matrix...on the partition between the 2 matrices. for (int row = rows - 1; row >= 0; row--) { for (int rw = row - 1; rw >= 0; rw--) { double newRowMultiplier = -1 * inverse.array[rw][row]; /** * The division coefficient must not be zero. If zero, * search for a lower row, and swap. */ if (newRowMultiplier == 0.0) { continue; }//end if for (int col = row; col < cols; col++) { inverse.array[rw][col] = newRowMultiplier * inverse.array[row][col] + inverse.array[rw][col]; } } }//end for inverse.columnDeleteFromStart(m.getRows()); return inverse; }//end if return null; } /** * Row reduction technique used to compute the determinant of this matrix. * The other method using recursion is not worth it above n = 10; The memory * consumed by the process and the time used to compute it is incomparable * to this method's performance. * * @return the inverse of the Matrix as another Matrix object. */ public double determ() { double detMultiplier = 1; Matrix mat = new Matrix(this); //Now we row-reduce. int rows = mat.getRows(); int cols = mat.getCols(); if (rows == cols) { for (int row = 0; row < rows; row++) { double pivot = mat.array[row][row]; /** * The division coefficient must not be zero. If zero, search * for a lower row, and swap. */ if (pivot == 0.0) { for (int rw = row; rw < rows; rw++) { pivot = mat.array[rw][row]; if (pivot != 0.0) { mat.swapRow(row, rw); detMultiplier *= -1; break; }//end if }//end for loop if (pivot == 0.0) { throw new InputMismatchException("INVERSE DOES NOT EXISTS!"); } }//end if for (int col = row; col < cols; col++) { mat.array[row][col] /= pivot; }//end inner for loop detMultiplier *= pivot; for (int rw = row + 1; rw < rows; rw++) { double newRowMultiplier = -1 * mat.array[rw][row]; for (int col = row; col < cols; col++) { mat.array[rw][col] = newRowMultiplier * mat.array[row][col] + mat.array[rw][col]; } }//end inner for loop }//end for for (int row = 0; row < rows; row++) { detMultiplier *= mat.array[row][row]; }//end for return detMultiplier; } throw new InputMismatchException("The input to the determinant function be a square matrix!"); } /** * * @param cofactors The matrix of cofactors. * @return the algebraic expression for the determinant of the matrix of * cofactors. */ private static String findDetEigen(String[][] cofactors) { if (cofactors.length == 2 && cofactors[0].length == 2) { return $2X2determinantForEigen(cofactors); } else { StringBuilder eqnBuilder = new StringBuilder(); int row = 0; for (int col = 0; col < cofactors[0].length; col++) { String[][] cfs = getCofactorTextArray(cofactors, row, col); String cofactorDet = findDetEigen(cfs); if (col == 0) { String expr = uniVariableExpressionExpander(lambda, cofactors[row][col], cofactorDet); if (!expr.isEmpty()) { eqnBuilder.append("+").append(expr); } } else { if (col % 2 == 0) { String expr = uniVariableExpressionExpander(lambda, cofactors[row][col], cofactorDet); if (!expr.isEmpty()) { eqnBuilder.append("+").append(expr); } } else { String negExpr = uniVariableExpressionExpander(lambda, "-1", cofactors[row][col]); if (!negExpr.isEmpty()) { String expr = uniVariableExpressionExpander(lambda, negExpr, cofactorDet); if (!expr.isEmpty()) { eqnBuilder.append("+").append(expr); } } } } } return eqnBuilder.toString(); } } public final String getCharacteristicPolynomialForEigenVector(){ return findCharacteristicPolynomialForEigenValues(this); } /** * * @param m The Matrix object * @return the characteristic polynomial */ public static final String findCharacteristicPolynomialForEigenValues(Matrix m) { if (m.isSquareMatrix()) { int rows = m.getRows(); int cols = m.getCols(); String[][] mat = new String[rows][cols]; //Create matrix array in string format for (int row = 0; row < rows; row++) { for (int col = 0; col < cols; col++) { mat[row][col] = String.valueOf(m.array[row][col]); } } //Create A-λ array in string format for (int row = 0, col = 0; row < rows; row++, col++) { String c = mat[row][col]; mat[row][col] = c + "-" + lambda; } // printTextMatrix(mat); StringBuilder eqnBuilder = new StringBuilder(); int row = 0; for (int col = 0; col < cols; col++) { String entry = mat[row][col]; String cofactorDet; if (mat.length == 2) { return findDetEigen(mat); } String[][] cofactors = getCofactorTextArray(mat, row, col); cofactorDet = findDetEigen(cofactors); if (col == 0) { eqnBuilder.append(uniVariableExpressionExpander(lambda, entry, cofactorDet)); } else { if (col % 2 == 0) { String expr = uniVariableExpressionExpander(lambda, entry, cofactorDet); if (!expr.isEmpty()) { eqnBuilder.append("+").append(expr); } } else { String negExpr = uniVariableExpressionExpander(lambda, "-1", entry); if (!negExpr.isEmpty()) { String expr = uniVariableExpressionExpander(lambda, negExpr, cofactorDet); if (!expr.isEmpty()) { eqnBuilder.append("+").append(expr); } } } } } String expr = uniVariableExpressionExpander(lambda, "1", eqnBuilder.toString()); return expr; } return null; } /** * * @param rw The row of a given element * @param cl The position of that element * @return the cofactor sub-matrix used to calculate the cofactor element of the specified position */ private Matrix getCofactor(int rw, int cl) { if (rw >= 0 && cl >= 0) { int rows = getRows(); int cols = getCols(); Matrix mat = new Matrix(rows - 1, cols - 1); int subRow = 0, subCol = 0; for (int row = 0; row < rows; row++) { if (row != rw) { for (int col = 0; col < cols; col++) { if (col != cl) {// , mat.array[subRow][subCol] = array[row][col]; subCol++; } } subCol = 0; subRow++; } } return mat; } return null; } /** * * @param matrix A 2d matrix array * @param rw The row of a given element * @param cl The position of that element * @return the cofactor sub-matrix used to calculate the cofactor element of the specified position */ private static String[][] getCofactorTextArray(String[][] matrix, int rw, int cl) { if (rw >= 0 && cl >= 0) { int rows = matrix.length; int cols = matrix[0].length; String[][] mat = new String[rows - 1][cols - 1]; int subRow = 0, subCol = 0; for (int row = 0; row < rows; row++) { if (row != rw) { for (int col = 0; col < cols; col++) { if (col != cl) {// , mat[subRow][subCol] = matrix[row][col]; subCol++; } } subCol = 0; subRow++; } } return mat; } return null; } /** * Generates the expression map of the expression... a map whose keys are * the powers of the variable of the expression and whose values are the * coefficients of the variables. e.g. 3x^2-2x+1 would produce: * [{2,3},{1,-2},{0,1}] * * @param variableName The name of the variable * @param scan The list to smoothen * @return the expression map */ private static HashMap<Double, Double> generateExpressionMap(String variableName, List<String> scan) { if (scan.isEmpty()) { return new HashMap<>(); } if (scan.get(0).equals(Operator.PLUS)) { scan.remove(0); } if (scan.isEmpty()) { return new HashMap<>(); } if (scan.get(0).equals(Operator.MINUS)) { if (parser.Number.isNumber(scan.get(1))) { scan.set(1, (-1 * Double.parseDouble(scan.get(1))) + ""); scan.remove(0); } } /** * change kx^n to k*x^n */ for (int i = 0; i < scan.size(); i++) { if (i > 0 && scan.get(i).equals(variableName)) { if (parser.Number.isNumber(scan.get(i - 1))) { scan.add(i, "*"); i += 1; } } } // apply coeffs to variables missing their coefficients for (int i = 0; i < scan.size(); i++) { if (scan.get(i).equals(variableName)) { if (i == 0) { scan.add(0, "*"); scan.add(0, "1"); i += 2; } else { if (Operator.isPlusOrMinus(scan.get(i - 1))) { scan.add(i, "*"); scan.add(i, "1"); if (i == scan.size() - 1) { break; } i += 2; } } } }//end for loop //smoothing change constants; Change terms in x to: x^1 and constant terms to x^0 for (int i = 0; i < scan.size(); i++) { if (i + 1 < scan.size()) { if (scan.get(i).equals(Operator.PLUS) && scan.get(i + 1).equals(Operator.PLUS)) { scan.set(i, Operator.PLUS); scan.remove(i + 1); } if (scan.get(i).equals(Operator.PLUS) && scan.get(i + 1).equals(Operator.MINUS)) { scan.set(i, Operator.MINUS); scan.remove(i + 1); } if (scan.get(i).equals(Operator.MINUS) && scan.get(i + 1).equals(Operator.PLUS)) { scan.set(i, Operator.MINUS); scan.remove(i + 1); } if (scan.get(i).equals(Operator.MINUS) && scan.get(i + 1).equals(Operator.MINUS)) { scan.set(i, Operator.PLUS); scan.remove(i + 1); } } //locate a variable if (scan.get(i).equals(variableName)) { //A free variable can never be at the beginning due to the previous for loop //if at the end if (i == scan.size() - 1) {//make its exponent 1 scan.add(Operator.POWER); scan.add("1"); break; } else {//else if it is just before a ± operator (e.g. x + or x -), then make its exponent 1 if (Operator.isPlusOrMinus(scan.get(i + 1))) { scan.add(i + 1, "1"); scan.add(i + 1, Operator.POWER); i += 2; } } } /*locate a number*/ else if (parser.Number.isNumber(scan.get(i))) { if (i == 0) { //if at start: make its x coefficient 0 if (i + 1 < scan.size()) { if (Operator.isPlusOrMinus(scan.get(i + 1))) { scan.add(1, "0"); scan.add(1, Operator.POWER); scan.add(1, variableName); scan.add(1, Operator.MULTIPLY); i += 4; } } else { scan.add(Operator.MULTIPLY); scan.add(variableName); scan.add(Operator.POWER); scan.add("0"); break; } } else if (i == scan.size() - 1) {//if at end, make its x coefficient 0 if (Operator.isPlusOrMinus(scan.get(i - 1))) { scan.add(Operator.MULTIPLY); scan.add(variableName); scan.add(Operator.POWER); scan.add("0"); } break; } else {//if somewhere within the production, make its x coefficient 0 if (Operator.isPlusOrMinus(scan.get(i - 1)) && Operator.isPlusOrMinus(scan.get(i + 1))) { scan.add(i + 1, Operator.MULTIPLY); scan.add(i + 1, variableName); scan.add(i + 1, Operator.POWER); scan.add(i + 1, "0"); i += 4; } } } }//end for loop HashMap<Double, Double> map = new HashMap<>();//key is the exponent(power of the variable), value is the coefficient //a.x^n for (int i = 0; i < scan.size(); i++) { if (scan.get(i).equals(Operator.POWER)) { double exp = Double.valueOf(scan.get(i + 1)); double coeff = Double.valueOf(scan.get(i - 3));//3*x^2 if (i - 4 >= 0 && scan.get(i - 4).equals(Operator.MINUS)) { coeff *= -1; } double coef = map.getOrDefault(exp, 0.0); map.put(exp, coeff + coef); } } return map; } /** * * @param variableName The variable * @param exprs The different expressions of the variable to be multiplied * @return the expanded product of the expressions. */ private static final String uniVariableExpressionExpander(String variableName, String... exprs) { String eqn = exprs[0]; for (int i = 1; i < exprs.length; i++) { eqn = uniVariableExpressionExpander(variableName, eqn, exprs[i]); } return eqn; } /** * * @param expression Must be a math expression of the * form:(polynomial_1)(polynomial_2) e.g: (1*x^1-2)(3*x^2+5*x^1+8) * @return */ private static final String uniVariableExpressionExpander(String variableName, String expr1, String expr2) { List<String> tokens1 = new CustomScanner(expr1, true, Operator.PLUS, Operator.MINUS, Operator.MULTIPLY, Operator.DIVIDE, Operator.POWER, variableName).scan(); List<String> tokens2 = new CustomScanner(expr2, true, Operator.PLUS, Operator.MINUS, Operator.MULTIPLY, Operator.DIVIDE, Operator.POWER, variableName).scan(); HashMap<Double, Double> map1 = generateExpressionMap(variableName, tokens1); HashMap<Double, Double> map2 = generateExpressionMap(variableName, tokens2); HashMap<Double, Double> product = new HashMap(); for (HashMap.Entry<Double, Double> e : map1.entrySet()) { double exp = e.getKey(); double coeff = e.getValue(); for (HashMap.Entry<Double, Double> f : map2.entrySet()) { double ex = f.getKey(); double coef = f.getValue(); double coeffProd = coef * coeff; double expProd = ex + exp;//3x^2*5x^3 double oldCoef = product.getOrDefault(expProd, 0.0); product.put(expProd, coeffProd + oldCoef); } } int i = 0; StringBuilder result = new StringBuilder(); for (HashMap.Entry<Double, Double> e : product.entrySet()) { double exp = e.getKey(); double coeff = e.getValue(); if (coeff == 0) { continue; } if (i == 0) { result.append(coeff).append("*").append(variableName).append(Operator.POWER).append(exp); //result.append(appendLogic(coeff, variableName, exp)); } else { if (coeff >= 0) { result.append("+").append(coeff).append("*").append(variableName).append(Operator.POWER).append(exp); //result.append("+").append(appendLogic(coeff, variableName, exp)); } else { result.append(coeff).append("*").append(variableName).append(Operator.POWER).append(exp); //result.append("+").append(appendLogic(coeff, variableName, exp)); } } i++; } String res = result.toString(); /* res = res.replace("+-", "-"); res = res.replace("-+", "-"); res = res.replace("--", "+"); res = res.replace("++", "+"); */ return res; } private static String appendLogic(double coeff ,String variableName , double exp){ if(exp == 0.0){ return coeff+""; }else if(exp == 1){ return coeff+"*"+variableName; }else{ return coeff+"*"+variableName+Operator.POWER+exp; } } public void print(){ System.out.println(toString()); } /** * (2-x)(3-x)(1-x)=(6-5x+x^2)(1-x)=6-11x+6x^2-x^3 {1, 2, 3, 4, 5} {6, 7, 8, * 9, 0} {1, 2, 3, 4, 5} {6, 7, 8, 9, 0} {1, 2, 3, 4, 5} * * @param args The command line args */ public static void main(String... args) { String expanded = uniVariableExpressionExpander("x", "2-x", "-8-7*x+x^2"); System.out.println("expanded: " + expanded); double array1[][] = { {1, 2, 3}, {0, 4, 5}, {1, 0, 6} }; Matrix ma = new Matrix(array1); System.out.println("Matrix..."); ma.print(); Matrix cof = ma.getCofactorMatrix(); System.out.println("Cofactor Matrix..."); cof.print(); String eqn = Matrix.findCharacteristicPolynomialForEigenValues(ma); System.out.println("eigen-value-rnd: " + eqn); double arr[][] = { {1, 2, 3, 4, 5}, {6, 7, 8, 9, 0}, {12, -2, 8, 2, 7}, {2, 9, -3, 5, 10}, {21, 4, 13, 0, 15} }; Matrix a = new Matrix(arr); System.out.println("eigen-eqn-a: " + findCharacteristicPolynomialForEigenValues(a)); double ar[][] = { {2, 0, 0, 0}, {1, 2, 0, 0}, {0, 1, 3, 0}, {0, 0, 1, 3} }; a = new Matrix(ar); System.out.println("eigen-eqn-a: " + findCharacteristicPolynomialForEigenValues(a)); double arr1[][] = { {2, 0, 0}, {0, 4, 5}, {0, 4, 3} }; Matrix b = new Matrix(arr1); System.out.println("eigen-eqn-b: " + findCharacteristicPolynomialForEigenValues(b)); double arr2[][] = { {2, 1}, {1, 2} }; Matrix c = new Matrix(arr2); System.out.println("eigen-eqn-c: " + findCharacteristicPolynomialForEigenValues(c)); Matrix m1 = new Matrix(4, 4); double array[][] = {{1, -8, 2, 5}, {4, 8, 2, 4}, {6, 5, 2, 1}, {2, 1, 6, 8}}; m1.array = array; System.out.printf("Matrix: %s\nDeterminant:\n %f\n", m1.toString(), det(m1)); Matrix triMatrix = m1.reduceToRowEchelonMatrix(); System.out.printf("Echelon-matrix of above: %s\n", triMatrix.toString()); int rows = 11; int cols = 11; Matrix m = new Matrix(rows, cols); m.randomFill(20); //System.out.println("Matrix: \n" + m); System.out.println("Processing begins."); double t0 = System.nanoTime(); double det = det(m);// double t1 = System.nanoTime() - t0; System.out.printf("Old method for determinant gives %4f in %4f %2s \n", det, (t1 * 1.0E-6), "ms"); double t2 = System.nanoTime(); double det_1 = m.determ(); double t3 = System.nanoTime() - t2; System.out.printf("New method for determinant gives %4f in %4f %2s \n", det_1, (t3 * 1.0E-6), "ms"); /* Matrix m1 = new Matrix( new double[][]{{5, -6, 8, 9}, {3,1,0,6}, {2,10,4,5}, {16,12,2,4}}); System.out.println("--------------------------Matrix:\n" + m1); System.out.println("Inverse: " + m1.inverse()); Matrix m2 = new Matrix(2, 2); m2.randomFill(20); Matrix m3 = new Matrix(m2); System.out.println("OLD INVERSE METHOD "); System.out.println("NEW MATRIX: " + m2); Matrix m4 = m2.oldInverse(); System.out.println("INVERSE: " + m4); System.out.println("Product using old method: M X 1/M: " + Matrix.multiply(m2, m4)); System.out.println("NEW INVERSE METHOD "); System.out.println("NEW MATRIX: " + m3); Matrix m5 = m3.inverse(); System.out.println("INVERSE: " + m5); System.out.println("Product using new method: M X 1/M: " + Matrix.multiply(m3, m5));*/ /** * double t0 = System.nanoTime(); Matrix m = new Matrix(3024,3025); * double t1 = System.nanoTime() - t0; System.out.println( "Creating the * matrix in "+ (t1 * 1.0E-6)+" ms" ); t0 = System.nanoTime(); * m.randomFill(22000); t1 = System.nanoTime() - t0; * * System.out.println( "Filling the matrix in "+ (t1 * 1.0E-6)+" ms" ); * //System.out.print( m ); * * t0 = System.nanoTime(); Matrix soln = m.solveEquation(); t1 = * System.nanoTime() - t0; System.out.print( "Solved the matrix in "+ * (t1 * 1.0E-6)+" ms" ); //System.out.print( soln ); * * //Matrix a = new * MatrixValueParser("[2,4,5:3,9.939,45.2:1,4,2:]").getMatrix(); * //Matrix b = new * MatrixValueParser("[-2,-4,-5:-3,-9.939,-45.2:-1,-4,-2:]").getMatrix(); * * //System.out.print( Matrix.pow(a, 5) ); */ } }//end class Matrix
32.926624
173
0.497342
f8bdf34ddf5d66d7571db00b117d81f283adaa63
1,032
package com.polybean.biosphere; import java.util.Collection; import com.fasterxml.jackson.databind.ObjectMapper; import com.polybean.biosphere.modal.ParsedSourceCodeDAO; import com.polybean.biosphere.service.SourceCodeMapperService; import com.polybean.biosphere.zip.Zip; import org.apache.commons.io.IOUtils; import lombok.SneakyThrows; import lombok.experimental.UtilityClass; @UtilityClass public class TestUtil { public static final String BIOMSPHERE_JAVA_SAMPLE = "biomsphere-java-data.zip"; @SneakyThrows public static Collection<ParsedSourceCodeDAO> getParsedSourceCodeJavaSample() { var sourceMapperService = new SourceCodeMapperService(new ObjectMapper()); var zipData = IOUtils.toByteArray( TestUtil.class .getClassLoader() .getResourceAsStream(BIOMSPHERE_JAVA_SAMPLE)); var sourceZipData = Zip.unzip(zipData); return sourceMapperService.from("sample", sourceZipData); } }
33.290323
84
0.718992
b172c7a499b25a080bce935543a93d017cb20b11
708
package com.ruoyi.task.domain; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import java.io.Serializable; import java.math.BigDecimal; import java.util.Date; /** * @Description: * @author: liurunkai * @Date: 2020/8/10 9:56 */ @Data @NoArgsConstructor @AllArgsConstructor public class JxphCallRecord implements Serializable { private String caseId; private String name; private String mobile; private String relType; private String teletphoneCode; private String remark; private Long userId; private String customerConnectTime; private String tsrConnectTime; private BigDecimal duration; private String recordUrl; }
21.454545
53
0.757062
4409751c47c28be1ef359f9dd8a21fa38cf89716
632
package top.one.jiemo.service.impl; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import top.one.jiemo.mapper.UserMapper; import top.one.jiemo.model.userEntity; import top.one.jiemo.service.UpdatePhoneService; @Service public class UpdatePhoneServiceImpl implements UpdatePhoneService { @Autowired private UserMapper userMapper; @Override public int updatePhone(userEntity user) { return userMapper.updatePhone(user); } @Override public String findPhone(String userName) { return userMapper.findPhone(userName); } }
26.333333
67
0.767405
791e8317389138848a601de439b5343e2ce02304
674
package com.apexmob.skink; /** * The Text class represents a node containing text within a document tree. * * <p>The Text class implements the flyweight pattern where a single instance can be reused by calling * the clear method and re-populating the content StringBuilder.</p> */ public class Text extends Node { /** * Construct a new Text containing the content provided within a StringBuilder instance. * @param buffer A buffer to contain the content represented by the node. * @throws IllegalArgumentException if the type or content provided is null. */ public Text(StringBuilder buffer) { super(NodeType.TEXT, buffer); } }
32.095238
103
0.722552
a4aa07ace1c21d4d82093bf2ac37fb90534aea03
2,136
/*-------------------------------------------------------------------------- * Copyright 2007 Taro L. Saito * * 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. *--------------------------------------------------------------------------*/ //-------------------------------------- // XerialJ // // Person.java // Since: Jun 27, 2008 11:36:56 AM // // $URL$ // $Author$ //-------------------------------------- package org.xerial.db.sql; public class Person implements Comparable<Person> { int id = -1; String name; String address; public Person() {} public Person(int id) { this.id = id; } /** * @param id * @param name */ public Person(int id, String name) { this.id = id; this.name = name; } public Person(String name) { this.name = name; } public Person(String name, String address) { super(); this.name = name; this.address = address; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } @Override public String toString() { return String.format("id=%s, name=%s, address=%s", id, name, address); } public int compareTo(Person o) { return this.id - o.id; } }
20.342857
78
0.516386
f5788406561661474b01f2f6fab76d3bffcc2b2c
14,458
package com.jiuye.mcp.server.controller.meta; import com.jiuye.mcp.exception.BizException; import com.jiuye.mcp.exception.InvalidRequestException; import com.jiuye.mcp.param.constants.SystemConstant; import com.jiuye.mcp.param.enums.ApplicationErrorCode; import com.jiuye.mcp.response.Response; import com.jiuye.mcp.server.controller.BaseController; import com.jiuye.mcp.server.model.job.JobSchemaEntity; import com.jiuye.mcp.server.model.meta.*; import com.jiuye.mcp.server.service.meta.IDdlService; import com.jiuye.mcp.server.service.meta.IMetaDatarouteService; import com.jiuye.mcp.server.service.meta.IMetaTargetSchemaService; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiParam; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.dao.DuplicateKeyException; import org.springframework.web.bind.annotation.*; import javax.servlet.http.HttpServletRequest; import java.util.ArrayList; import java.util.List; /** * @author zhaopeng * @date 2018-11-14 */ @RestController @RequestMapping(value = "/route", produces = {"application/json;charset=UTF-8"}) public class RouteController extends BaseController { private static final Logger logger = LoggerFactory.getLogger(RouteController.class.getName()); @Autowired private IMetaDatarouteService routeService; @Autowired private IDdlService ddlService; @Autowired private IMetaTargetSchemaService metaTargetSchemaService; /** * 查询路由列表 */ @ApiOperation(value = "查询路由列表") @RequestMapping(value = "/query", method = RequestMethod.GET) public Response<List<MetaDatarouteEntity>> queryRoutes(@ApiParam(value = "路由ID") @RequestParam(value = "routeID", required = false) Long routeId, @ApiParam(value = "路由名称") @RequestParam(value = "routeName", required = false) String routeName, @ApiParam(value = "源端名称") @RequestParam(value = "sourceName", required = false) String sourceName, @ApiParam(value = "终端名称") @RequestParam(value = "targetName", required = false) String targetName, @ApiParam(value = "路由状态") @RequestParam(value = "routeStatus", required = false) String routeStatus) { MetaDatarouteEntity searchEntity = new MetaDatarouteEntity(); if (null != routeId){ searchEntity.setRouteId(routeId); } searchEntity.setRouteName(routeName); searchEntity.setSourceName(sourceName); searchEntity.setTargetName(targetName); searchEntity.setRouteStatus(routeStatus); List<MetaDatarouteEntity> list = routeService.queryDBRoutePage(searchEntity); Response<List<MetaDatarouteEntity>> response =Response.createResponse(list); response.setCode(SystemConstant.RESPONSE_CODE_SUCCESS); return response; } /** * 查询路由 * @return */ @ApiOperation(value = "查询路由", notes = "查询路由", httpMethod = "GET") @RequestMapping(value = "/job_routes", method = RequestMethod.GET) public Response<List<JobSchemaEntity>> queryJobRoutes() { List<JobSchemaEntity> list = new ArrayList<>(); Response<List<JobSchemaEntity>> response = new Response<>(); try { list = routeService.queryJobRoutes(); response.setCode(SystemConstant.RESPONSE_CODE_SUCCESS); response.setItems(list); } catch (Exception e) { logger.error("Query route is exception!", e); if (e instanceof BizException) { throw new InvalidRequestException(((BizException) e).getCode(), e.getMessage()); } throw new InvalidRequestException(ApplicationErrorCode.QUERY_ERROR.getCode(), ApplicationErrorCode.QUERY_ERROR.getMessage()); } return response; } /** * 新增路由信息 */ @ApiOperation(value = "新增路由列表") @RequestMapping(value = "/save", method = RequestMethod.POST) public Response<MetaDatarouteEntity> saveRoute(HttpServletRequest request, @ApiParam(value = "路由信息",required = true) @RequestBody() MetaDatarouteEntity routeInfo) { if (null == routeInfo) { throw new InvalidRequestException(ApplicationErrorCode.INVALID_ARGUMENTS.getCode(), ApplicationErrorCode.INVALID_ARGUMENTS.getMessage()); } Response<MetaDatarouteEntity> response = new Response<>(); try { int cnt = routeService.checkRoute(routeInfo); if (cnt == 0) { routeInfo.setCreateUser(getUser(request)); routeService.addRoute(routeInfo); response.setItems(routeInfo); response.setCode(SystemConstant.RESPONSE_CODE_SUCCESS); } else { throw new InvalidRequestException(ApplicationErrorCode.SAME_DATA_ERROR.getCode(), ApplicationErrorCode.SAME_DATA_ERROR.getMessage()); } } catch (DuplicateKeyException ex) { logger.error("Add Route has an error!", ex); throw new InvalidRequestException(ApplicationErrorCode.SAME_DATA_ERROR.getCode(), ApplicationErrorCode.SAME_DATA_ERROR.getMessage()); } catch (Exception e) { logger.error("Add Route has an error!", e); if (e instanceof BizException) { throw new InvalidRequestException(((BizException) e).getCode(), e.getMessage()); } throw new InvalidRequestException(ApplicationErrorCode.CREATE_ERROR.getCode(), ApplicationErrorCode.CREATE_ERROR.getMessage()); } return response; } /** * 修改路由状态 * @param entity * @return */ @ApiOperation(value = "修改路由状态") @RequestMapping(value = "/update_status", method = RequestMethod.POST) public Response<MetaDatarouteEntity> updateRouteStatus(HttpServletRequest request, @ApiParam(value = "路由信息", required = true) @RequestBody() MetaDatarouteEntity entity) { if (null == entity) { throw new InvalidRequestException(ApplicationErrorCode.INVALID_ARGUMENTS.getCode(), ApplicationErrorCode.INVALID_ARGUMENTS.getMessage()); } Response<MetaDatarouteEntity> response = new Response<>(); try { if (entity.getRouteStatus().equals("1")) { int cnt = routeService.checkRoute(entity); if (cnt == 0) { routeService.updateRouteStatus(entity, getUser(request)); response.setCode(SystemConstant.RESPONSE_CODE_SUCCESS); } else { throw new InvalidRequestException(ApplicationErrorCode.SAME_ROUTE_STATUS_ERROR.getCode(), ApplicationErrorCode.SAME_ROUTE_STATUS_ERROR.getMessage()); } } else { routeService.updateRouteStatus(entity, getUser(request)); response.setCode(SystemConstant.RESPONSE_CODE_SUCCESS); } } catch (Exception e) { logger.error("Update Route Status has an error!", e); if (e instanceof BizException) { throw new InvalidRequestException(((BizException) e).getCode(), e.getMessage()); } throw new InvalidRequestException(ApplicationErrorCode.UPDATE_ERROR.getCode(), ApplicationErrorCode.UPDATE_ERROR.getMessage()); } return response; } /** * 修改路由名称 */ @ApiOperation(value = "修改路由名称") @RequestMapping(value = "/update_name", method = RequestMethod.POST) public Response<MetaDatarouteEntity> updateRouteName(HttpServletRequest request, @ApiParam(value = "路由名称", required = true) @RequestBody(required = true) MetaDatarouteEntity entity) { if (null == entity) { throw new InvalidRequestException(ApplicationErrorCode.INVALID_ARGUMENTS.getCode(), ApplicationErrorCode.INVALID_ARGUMENTS.getMessage()); } Response<MetaDatarouteEntity> response = new Response<>(); try { if (!entity.getRouteName().equals("")) { int cnt = routeService.checkRoute(entity); if (cnt == 0) { routeService.updateRouteName(entity, getUser(request)); response.setCode(SystemConstant.RESPONSE_CODE_SUCCESS); } else { throw new InvalidRequestException(ApplicationErrorCode.SAME_ROUTE_STATUS_ERROR.getCode(), ApplicationErrorCode.SAME_ROUTE_STATUS_ERROR.getMessage()); } } else { throw new InvalidRequestException(ApplicationErrorCode.UPDATE_ERROR.getCode(),ApplicationErrorCode.UPDATE_ERROR.getMessage()); } } catch (Exception e) { logger.error("Update Route Status has an error!", e); if (e instanceof BizException) { throw new InvalidRequestException(((BizException) e).getCode(), e.getMessage()); } throw new InvalidRequestException(ApplicationErrorCode.UPDATE_ERROR.getCode(), ApplicationErrorCode.UPDATE_ERROR.getMessage()); } return response; } /** * 加载Target Schema信息 */ @ApiOperation(value = "加载Target Schema信息") @RequestMapping(value = "/query_schema", method = RequestMethod.POST) public Response<List<MetaTargetSchemaEntity>> querySchemaLists(@ApiParam(value = "MetaTargetSchemaEntity") @RequestBody(required = false) MetaTargetSchemaEntity entity) { List<MetaTargetSchemaEntity> list = metaTargetSchemaService.queryList(entity); Response<List<MetaTargetSchemaEntity>> response = Response.createResponse(list); response.setCode(SystemConstant.RESPONSE_CODE_SUCCESS); return response; } /** * 新增Schema信息 * 修改Schema信息和状态 */ @ApiOperation(value = "新增 flag='1'、修改Schema信息 flag='2'及状态 falg='3'") @RequestMapping(value = "/save_schema", method = RequestMethod.POST) public Response<MetaTargetSchemaEntity> saveSchemaInfo(HttpServletRequest request, @ApiParam(value = "Target Schema实体类schama信息", required = true) @RequestBody() List<MetaTargetSchemaEntity> schemaList){ if (null == schemaList) { throw new InvalidRequestException(ApplicationErrorCode.INVALID_ARGUMENTS.getCode(), ApplicationErrorCode.INVALID_ARGUMENTS.getMessage()); } Response<MetaTargetSchemaEntity> response = new Response<>(); try { metaTargetSchemaService.saveSchemaInfo(schemaList, getUser(request)); response.setCode(SystemConstant.RESPONSE_CODE_SUCCESS); } catch (DuplicateKeyException ex) { logger.error("Add Schema has an error!", ex); throw new InvalidRequestException(ApplicationErrorCode.SAME_DATA_ERROR.getCode(), ApplicationErrorCode.SAME_DATA_ERROR.getMessage()); } catch (Exception e) { logger.error("Add Schema has an error!", e); if (e instanceof BizException) { throw new InvalidRequestException(((BizException) e).getCode(), e.getMessage()); } throw new InvalidRequestException(ApplicationErrorCode.CREATE_ERROR.getCode(), ApplicationErrorCode.CREATE_ERROR.getMessage()); } return response; } /** * 在终端生成Schema信息 */ @ApiOperation(value = "在终端生成Schema信息,schemaId是必须参数") @RequestMapping(value = "/create_schema", method = RequestMethod.POST) public Response<MetaTargetSchemaEntity> createSchemaInfo(HttpServletRequest request, @ApiParam(value = "Schema信息") @RequestBody() List<MetaTargetSchemaEntity> param) { if (null == param) { throw new InvalidRequestException(ApplicationErrorCode.INVALID_ARGUMENTS.getCode(), ApplicationErrorCode.INVALID_ARGUMENTS.getMessage()); } Response<MetaTargetSchemaEntity> response = new Response<>(); try { metaTargetSchemaService.createSchema(param, getUser(request)); response.setCode(SystemConstant.RESPONSE_CODE_SUCCESS); } catch (DuplicateKeyException ex) { logger.error("Create Schema has an error!", ex); throw new InvalidRequestException(ApplicationErrorCode.SAME_DATA_ERROR.getCode(), ApplicationErrorCode.SAME_DATA_ERROR.getMessage()); } catch (Exception e) { logger.error("Create Schema has an error!", e); if (e instanceof BizException) { throw new InvalidRequestException(((BizException) e).getCode(), e.getMessage()); } throw new InvalidRequestException(ApplicationErrorCode.CREATE_SCHEMA_ERROR.getCode(), ApplicationErrorCode.CREATE_SCHEMA_ERROR.getMessage()); } return response; } /** * 判断mcp是否存在表 * @param param * @return */ @ApiOperation(value = "判断源端是否存在表") @RequestMapping(value = "/exist_table", method = RequestMethod.GET) public Response<Boolean> existTables(@ApiParam(value = "srcId集合", required = true) @RequestParam(value = "param") List<Long> param) { if (null == param) { throw new InvalidRequestException(ApplicationErrorCode.INVALID_ARGUMENTS.getCode(), ApplicationErrorCode.INVALID_ARGUMENTS.getMessage()); } Response<Boolean> response = new Response<>(); try { boolean flag = ddlService.existTables(param); if(!flag){ response.setCode(SystemConstant.RESPONSE_CODE_SUCCESS); response.setItems(false); }else { response.setCode(SystemConstant.RESPONSE_CODE_SUCCESS); response.setItems(true); } } catch (DuplicateKeyException ex) { logger.error("Query Tables has an error!", ex); throw new InvalidRequestException(ApplicationErrorCode.SAME_DATA_ERROR.getCode(), ApplicationErrorCode.SAME_DATA_ERROR.getMessage()); } catch (Exception e) { logger.error("Query Tables has an error!", e); if (e instanceof BizException) { throw new InvalidRequestException(((BizException) e).getCode(), e.getMessage()); } throw new InvalidRequestException(ApplicationErrorCode.CREATE_ERROR.getCode(), ApplicationErrorCode.CREATE_ERROR.getMessage()); } return response; } }
45.322884
206
0.661641
fb4e8f2294023c57c63aee55f4e94ec5f2999aef
2,836
package org.apache.sis.desktop.about; import java.awt.Desktop; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.util.ResourceBundle; import java.util.function.Predicate; import java.util.logging.Level; import java.util.logging.Logger; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.control.Hyperlink; import javafx.scene.control.Label; import javafx.scene.layout.Priority; import javafx.scene.layout.VBox; import org.apache.sis.desktop.MetadataView; import org.apache.sis.desktop.metadata.NodeTreeTable; import org.apache.sis.setup.About; import org.apache.sis.util.collection.TableColumn; import org.apache.sis.util.collection.TreeTable; /** * About Window Controller class * * @author Siddhesh Rane */ public class AboutController implements Initializable { @FXML private VBox vBox; @FXML private Label title; @FXML private Hyperlink website; /** * Initializes the controller class. */ @Override public void initialize(URL url, ResourceBundle rb) { website.setOnAction(ae -> { if (Desktop.isDesktopSupported()) { Desktop desktop = Desktop.getDesktop(); Thread thread = new Thread(() -> { try { desktop.browse(new URI("http://sis.apache.org")); } catch (IOException ex) { Logger.getLogger(AboutController.class.getName()).log(Level.SEVERE, null, ex); } catch (URISyntaxException ex) { Logger.getLogger(AboutController.class.getName()).log(Level.SEVERE, null, ex); } }); thread.setDaemon(true); thread.start(); } }); loadAbout(); } private void loadAbout() { final TreeTable configuration = About.configuration(); NodeTreeTable sisabout = new NodeTreeTable(configuration); sisabout.setExpandNode(new Predicate<TreeTable.Node>() { @Override public boolean test(TreeTable.Node node) { if (node.getParent() == null) { return true; } CharSequence name = node.getValue(TableColumn.NAME); if (name == null) { return false; } switch (name.toString()) { case "Versions": case "Localization": case "Locale": case "Timezone": return true; } return false; } }); vBox.getChildren().add(sisabout); VBox.setVgrow(sisabout, Priority.ALWAYS); } }
31.511111
102
0.578279
da18b168d0467e284f5e03796cfd2aa72cac48d6
1,436
/* * Copyright 2014 the original author or authors. * * 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.openhubframework.openhub.spi.throttling; import java.util.Map; import javax.annotation.Nullable; /** * Throttling configuration contract. * * @author Petr Juza */ public interface ThrottlingConfiguration { /** * Gets throttle properties for most equal scope. * * @param inScope the scope of the incoming request * @return properties or {@code null} if there is no properties for specified scope */ @Nullable ThrottleProps getThrottleProps(ThrottleScope inScope); /** * Gets all throttling properties. * * @return throttling properties */ Map<ThrottleScope, ThrottleProps> getProperties(); /** * Is throttling disabled at all? * * @return {@code true} for disabling */ boolean isThrottlingDisabled(); }
26.109091
87
0.698468
1af0ac6f4ad9788843e477f8251911c9226f5a5c
1,516
package com.sforce.soap.partner; /** * Generated by ComplexTypeCodeGenerator.java. Please do not edit. */ public interface IExecuteListViewRequest { /** * element : developerNameOrId of type {http://www.w3.org/2001/XMLSchema}string * java type: java.lang.String */ public java.lang.String getDeveloperNameOrId(); public void setDeveloperNameOrId(java.lang.String developerNameOrId); /** * element : limit of type {http://www.w3.org/2001/XMLSchema}int * java type: java.lang.Integer */ public java.lang.Integer getLimit(); public void setLimit(java.lang.Integer limit); /** * element : offset of type {http://www.w3.org/2001/XMLSchema}int * java type: java.lang.Integer */ public java.lang.Integer getOffset(); public void setOffset(java.lang.Integer offset); /** * element : orderBy of type {urn:partner.soap.sforce.com}ListViewOrderBy * java type: com.sforce.soap.partner.ListViewOrderBy[] */ public com.sforce.soap.partner.IListViewOrderBy[] getOrderBy(); public void setOrderBy(com.sforce.soap.partner.IListViewOrderBy[] orderBy); /** * element : sobjectType of type {http://www.w3.org/2001/XMLSchema}string * java type: java.lang.String */ public java.lang.String getSobjectType(); public void setSobjectType(java.lang.String sobjectType); }
27.563636
86
0.629947
d5ded3e731e3aa338779d9acccb4e630fbcf0aaf
3,467
/** * Copyright 2012 A24Group * * 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.ssgwt.client.ui.tree; import java.util.List; /** * The node object. * * @author Johannes Gryffenberg <johannes.gryffenberg@gmail.com> * @since 31 Jan 2013 */ public abstract class NodeObject { /** * Getter for the list of children nodes for this node * * @author Ruan Naude<ruan.naude@a24Group.com> * @since 18 Feb 2013 * * @return The list of children nodes for this node */ public abstract List<NodeObject> getChildren(); /** * Function used to check if all the items is selected * * @author Johannes Gryffenberg <johannes.gryffenberg@gmail.com> * @since 31 Jan 2013 * * @return true in no children is selected */ public boolean isNoChildrenSelected() { for (NodeObject child : getChildren()) { if (child.isSelected() || !child.isNoChildrenSelected()) { return false; } } return true; } /** * Retrieves the object's selected state * * @author Johannes Gryffenberg <johannes.gryffenberg@gmail.com> * @since 01 Feb 2013 * * @return The object's selected state */ public abstract boolean isSelected(); /** * Set the object's selected state * * @param selected The new selected state * * @author Johannes Gryffenberg <johannes.gryffenberg@gmail.com> * @since 01 Feb 2013 */ public abstract void setSelected(boolean selected); /** * Determine whether the object is read only * * @author Ruan Naude<ruan.naude@a24group.com> * @since 05 Feb 2013 * * @return Whether the object is read only */ public abstract boolean isReadOnly(); /** * Sets whether the object is read only * * @param readOnly The read only state * * @author Ruan Naude<ruan.naude@a24group.com> * @since 05 Feb 2013 */ public abstract void setReadOnly(boolean readOnly); /** * Updates the selected state of all the sub nodes * * @param selected The new selected state * * @author Johannes Gryffenberg <johannes.gryffenberg@gmail.com> * @since 01 Feb 2013 */ public void setAllChildrenSelectedState(boolean selected) { if (getChildren() != null) { for (NodeObject child : getChildren()) { child.setSelected(selected); child.setAllChildrenSelectedState(selected); } } } /** * Retrieves the text that should be displayed on the tree for the item * * @author Johannes Gryffenberg <johannes.gryffenberg@gmail.com> * @since 01 Feb 2013 * * @return The text that should be displayed on the tree for the item */ public abstract String getNodeDisplayText(); }
28.891667
75
0.623305
5e557386a4cc36db028fc93eacd325ba41747e7e
457
package com.ykuee.datamaintenance.model.system.role.converter; import org.mapstruct.Mapper; import com.ykuee.datamaintenance.common.base.beancopy.DtoEntityConverter; import com.ykuee.datamaintenance.model.system.role.dto.SysUserRoleDTO; import com.ykuee.datamaintenance.model.system.role.entity.SysUserRoleEntity; @Mapper(componentModel = "spring") public interface SysUserRoleConverter extends DtoEntityConverter<SysUserRoleDTO, SysUserRoleEntity>{ }
35.153846
101
0.849015
a5a18728c3dafce839c6c2d57e114fe7607d841c
595
package com.nishant.adapter; import android.content.Context; import android.view.ViewGroup; import com.nishant.feedslibrary.adapter.FeedsAdapter; public class CustomAdapter extends FeedsAdapter { public CustomAdapter(Context context) { super(context); } @Override public FeedsAdapter.CustomViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { return super.onCreateViewHolder(parent, viewType); } @Override public void onBindViewHolder(CustomViewHolder holder, int position) { super.onBindViewHolder(holder, position); } }
24.791667
93
0.744538
1a4b385ba66d1826446e5406e8f8234d2da920c5
488
package de.ust.skill.common.java.api; import java.util.Collection; /** * Provides access to Strings in the pool. * * @note As it is the case with Strings in Java, Strings in SKilL are special * objects that behave slightly different, because they are something in * between numbers and objects. * @author Timm Felden */ public interface StringAccess extends Collection<String> { /** * get String by its Skill ID */ public String get(int index); }
24.4
78
0.690574
0f295b79f070465f60cd8f3b45a2c889e70d9ffb
6,815
package edu.stanford.nlp.process; import edu.stanford.nlp.util.Function; import edu.stanford.nlp.ling.BasicDocument; import edu.stanford.nlp.ling.Document; import edu.stanford.nlp.ling.HasWord; import edu.stanford.nlp.ling.Word; import java.io.File; import java.net.URL; import java.util.*; /** * Produces a new Document of Words in which special characters of the PTB * have been properly escaped. * * @author Teg Grenager (grenager@stanford.edu) * @author Sarah Spikes (sdspikes@cs.stanford.edu) (Templatization) * * @param <L> The type of the labels * @param <F> The type of the features */ public class PTBEscapingProcessor<IN extends HasWord, L, F> extends AbstractListProcessor<IN, HasWord, L, F> implements Function<List<IN>, List<HasWord>> { private static final char[] SUBST_CHARS = {'(', ')', '[', ']', '{', '}'}; private static final String[] REPLACE_SUBSTS = {"-LRB-", "-RRB-", "-LSB-", "-RSB-", "-LCB-", "-RCB-"}; protected char[] substChars = SUBST_CHARS; protected String[] replaceSubsts = REPLACE_SUBSTS; protected char[] escapeChars = {'/', '*'}; protected String[] replaceEscapes = {"\\/", "\\*"}; protected boolean fixQuotes = true; public PTBEscapingProcessor() { } public PTBEscapingProcessor(char[] escapeChars, String[] replaceEscapes, char[] substChars, String[] replaceSubsts, boolean fixQuotes) { this.escapeChars = escapeChars; this.replaceEscapes = replaceEscapes; this.substChars = substChars; this.replaceSubsts = replaceSubsts; this.fixQuotes = fixQuotes; } /* public Document processDocument(Document input) { Document result = input.blankDocument(); result.addAll(process((List)input)); return result; } */ /** Unescape a List of HasWords. Implements the * Function&lt;List&lt;HasWord&gt;, List&lt;HasWord&gt;&gt; interface. */ public List<HasWord> apply(List<IN> hasWordsList) { return process(hasWordsList); } public static String unprocess(String s) { for (int i = 0; i < REPLACE_SUBSTS.length; i++) { s = s.replaceAll(REPLACE_SUBSTS[i], String.valueOf(SUBST_CHARS[i])); } // at present doesn't deal with * / stuff ... never did return s; } /** * @param input must be a List of objects of type HasWord */ public List<HasWord> process(List<? extends IN> input) { List<HasWord> output = new ArrayList<HasWord>(); for (IN h : input) { String s = h.word(); h.setWord(escapeString(s)); output.add(h); } if (fixQuotes) { return fixQuotes(output); } return output; } private static List<HasWord> fixQuotes(List<HasWord> input) { int inputSize = input.size(); LinkedList<HasWord> result = new LinkedList<HasWord>(); if (inputSize == 0) { return result; } boolean begin; // see if there is a quote at the end if (input.get(inputSize - 1).word().equals("\"")) { // alternate from the end begin = false; for (int i = inputSize - 1; i >= 0; i--) { HasWord hw = input.get(i); String tok = hw.word(); if (tok.equals("\"")) { if (begin) { hw.setWord("``"); begin = false; } else { hw.setWord("\'\'"); begin = true; } } // otherwise leave it alone result.addFirst(hw); } // end loop } else { // alternate from the beginning begin = true; for (int i = 0; i < inputSize; i++) { HasWord hw = input.get(i); String tok = hw.word(); if (tok.equals("\"")) { if (begin) { hw.setWord("``"); begin = false; } else { hw.setWord("\'\'"); begin = true; } } // otherwise leave it alone result.addLast(hw); } // end loop } return result; } private String escapeString(String s) { StringBuilder buff = new StringBuilder(); for (int i = 0; i < s.length(); i++) { char curChar = s.charAt(i); // run through all the chars we need to replace boolean found = false; for (int k = 0; k < substChars.length; k++) { if (curChar == substChars[k]) { buff.append(replaceSubsts[k]); found = true; break; } } if (found) { continue; } // don't do it if escape is already there usually if (curChar == '\\') { // add this and the next one unless bracket buff.append(curChar); if (maybeAppendOneMore(i + 1, s, buff)) { i++; } found = true; } if (found) { continue; } // run through all the chars we need to escape for (int k = 0; k < escapeChars.length; k++) { if (curChar == escapeChars[k]) { buff.append(replaceEscapes[k]); found = true; break; } } if (found) { continue; } // append the old char no matter what buff.append(curChar); } return buff.toString(); } private boolean maybeAppendOneMore(int pos, String s, StringBuilder buff) { if (pos >= s.length()) { return false; } char candidate = s.charAt(pos); boolean found = false; for (char ch : substChars) { if (candidate == ch) { found = true; break; } } if (found) { return false; } buff.append(candidate); return true; } /** * This will do the escaping on an input file. Input file must already be tokenized, * with tokens separated by whitespace. <br> * Usage: java edu.stanford.nlp.process.PTBEscapingProcessor fileOrUrl * * @param args Command line argument: a file or URL */ public static void main(String[] args) { if (args.length != 1) { System.out.println("usage: java edu.stanford.nlp.process.PTBEscapingProcessor fileOrUrl"); System.exit(0); } String filename = args[0]; try { Document<String, Word, Word> d; // initialized below if (filename.startsWith("http://")) { Document<String, Word, Word> dpre = new BasicDocument<String>(WhitespaceTokenizer.factory()).init(new URL(filename)); DocumentProcessor<Word, Word, String, Word> notags = new StripTagsProcessor<String, Word>(); d = notags.processDocument(dpre); } else { d = new BasicDocument<String>(WhitespaceTokenizer.factory()).init(new File(filename)); } DocumentProcessor<Word, HasWord, String, Word> proc = new PTBEscapingProcessor<Word, String, Word>(); Document<String, Word, HasWord> newD = proc.processDocument(d); for (HasWord word : newD) { System.out.println(word); } } catch (Exception e) { e.printStackTrace(); } } }
28.514644
138
0.589729
d84483d94edcfd7bab34a18fab364e4abfd5d7cc
1,257
package examples; import pinnacle.api.Parameter; import pinnacle.api.PinnacleAPI; import pinnacle.api.PinnacleException; import pinnacle.api.dataobjects.PlacedSpecialBet; import pinnacle.api.enums.ODDS_FORMAT; import pinnacle.api.enums.WIN_RISK_TYPE; public class PlaceSpecialBet { public static void main(String[] args) throws PinnacleException { // settings String username = "yourUserName"; String password = "yourPassword"; PinnacleAPI api = PinnacleAPI.open(username, password); // parameter Parameter bet = Parameter.newInstance(); bet.uniqueRequestId(); bet.acceptBetterLine(true); bet.oddsFormat(ODDS_FORMAT.AMERICAN); bet.stake("200.00"); bet.winRiskStake(WIN_RISK_TYPE.WIN); bet.lineId(33997608); bet.specialId(480692762); bet.contestantId(480692764); Parameter parameter = Parameter.newInstance(); parameter.bets(bet); // response as plain json text String jsonText = api.placeSpecialBetAsJson(parameter); // !! you will bet real money by this operation !! System.out.println(jsonText); // response as data object PlacedSpecialBet placedSpecialBet = api.placeSpecialBetAsObject(parameter); // !! you will bet real money by this operation !! System.out.println(placedSpecialBet); } }
30.658537
128
0.75895
37fedc477e5c71c831543e228c2bf18be331a56d
1,977
package net.benmann.orm8.db; /** * TODO * Executes an SQL BEGIN TRANSACTION; enclosing ORM8 commands then run in this context; executes an END TRANSACTION * at the end of the block. * * Likely we will move on to a different pattern eventually though, such as: * * <pre> * db.withTransaction(() -> { * try { * db.doSomething(); * db.doSomethingElse(); * } catch (SillinessError e) { * return Transaction.ROLLBACK; * } * return Transaction.COMMIT; * }); * </pre> * * which may be a better compile-time story than the following * * <pre> * try (Transaction t = db.createTransaction()) { * db.doSomething(); * db.doSomethingElse(); * t.commit(); * } catch (SillinessError e) { * t.rollback(); * } * </pre> * * which cannot ensure you actually called commit or rollback until runtime. * * TODO transactions started within this one should become part of the enclosing transaction (and manage state accordingly) */ public class Transaction implements AutoCloseable { public enum Result { COMMIT, ROLLBACK, UNKNOWN } protected Result result = Result.UNKNOWN; public Transaction(DbConnection<?> connection) { } public void setResult(Result r) { if (result != Result.UNKNOWN) throw new IllegalStateException("Attempt to change transaction state from " + result + " to " + r); result = r; } public void commit() { setResult(Result.COMMIT); } public void rollback() { setResult(Result.ROLLBACK); } //If we close this object and you haven't called commit or rollback, it's considered a programming error. @Override public void close() { if (result == Result.UNKNOWN) throw new IllegalStateException("The transaction was not closed."); } //If the transaction is garbage collected, run close. @Override public void finalize() { close(); } }
27.458333
123
0.635306
48771d03cfb900eaca61b6d6dda2035f9766905f
2,272
package jp.sf.amateras.jseditor.editors.additional; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import jp.sf.amateras.htmleditor.HTMLPlugin; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IConfigurationElement; import org.eclipse.core.runtime.IExtension; import org.eclipse.core.runtime.IExtensionPoint; import org.eclipse.core.runtime.IExtensionRegistry; import org.eclipse.core.runtime.Platform; /** * * @author Naoki Takezoe */ public class AdditionalJavaScriptCompleterManager { private static Map<String, IAdditionalJavaScriptCompleter> completers = null; private static void init(){ completers = new LinkedHashMap<String, IAdditionalJavaScriptCompleter>(); IExtensionRegistry registry = Platform.getExtensionRegistry(); IExtensionPoint point = registry.getExtensionPoint( HTMLPlugin.getDefault().getPluginId() + ".javaScriptCompleter"); IExtension[] extensions = point.getExtensions(); for(int i=0;i<extensions.length;i++){ IConfigurationElement[] elements = extensions[i].getConfigurationElements(); for (int j = 0; j < elements.length; j++) { if ("completer".equals(elements[j].getName())) { try { String name = elements[j].getAttribute("name"); IAdditionalJavaScriptCompleter completer = (IAdditionalJavaScriptCompleter) elements[j].createExecutableExtension("class"); completers.put(name, completer); } catch(CoreException ex){ HTMLPlugin.logException(ex); } } } } // completers.put("prototype.js", new PrototypeCompleter()); // completers.put("script.aculo.us", new ScriptaculousCompleter()); } public static String[] getAdditionalJavaScriptCompleterNames(){ if(completers == null){ init(); } return completers.keySet().toArray(new String[0]); } public static List<IAdditionalJavaScriptCompleter> getAdditionalJavaScriptCompleters(){ if(completers == null){ init(); } return new ArrayList<IAdditionalJavaScriptCompleter>(completers.values()); } public static IAdditionalJavaScriptCompleter getAdditionalJavaSCriptCompleter(String name){ if(completers == null){ init(); } return completers.get(name); } }
29.128205
88
0.738556
df9b8cf9b9c18fcbd05526a7a8e1153068fb6ea5
1,887
package uk.nhs.digital.nhsconnect.nhais.outbound.mapper; import org.hl7.fhir.r4.model.Enumerations; import org.hl7.fhir.r4.model.Parameters; import org.hl7.fhir.r4.model.Patient; import org.junit.jupiter.api.Test; import uk.nhs.digital.nhsconnect.nhais.outbound.FhirValidationException; import uk.nhs.digital.nhsconnect.nhais.model.edifact.PersonSex; import uk.nhs.digital.nhsconnect.nhais.inbound.fhir.PatientParameter; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; class PersonSexMapperTest { @Test void When_MappingGender_Then_ExpectCorrectResult() { Patient patient = new Patient(); patient.setGender(Enumerations.AdministrativeGender.FEMALE); Parameters parameters = new Parameters() .addParameter(new PatientParameter(patient)); PersonSex personSex = new PersonSexMapper().map(parameters); var expectedPersonSex = PersonSex .builder() .gender(PersonSex.Gender.FEMALE) .build(); assertEquals(expectedPersonSex, personSex); } @Test public void When_MappingGenderWrongType_Then_FhirValidationExceptionIsThrown() { Patient patient = new Patient(); patient.setGender(Enumerations.AdministrativeGender.NULL); Parameters parameters = new Parameters() .addParameter(new PatientParameter(patient)); assertThrows(FhirValidationException.class, () -> new PersonSexMapper().map(parameters)); } @Test public void When_MappingWithoutGender_Then_FhirValidationExceptionIsThrown() { Parameters parameters = new Parameters() .addParameter(new PatientParameter()); var personSexMapper = new PersonSexMapper(); assertThrows(FhirValidationException.class, () -> personSexMapper.map(parameters)); } }
34.944444
97
0.72867
391d069385a58d95575e96cecaa81db045319e9e
555
public class Launcher { public static void main(String[] args) { PseudoRandomGenerator prng = new PseudoRandomGenerator(); double value = 0.0; for (int i = 0; i < 10; i++) { value = prng.random(); System.out.println(value); } long myTime = System.nanoTime(); for (int i = 0; i < 10000000; i++) { value = prng.random(); } myTime = System.nanoTime() - myTime; System.out.println("execution time = " + Long.toString(myTime) + " nsec "); } }
30.833333
83
0.527928
b030baa867959dba4e1747a5610bd72381760be5
2,675
package rahnema.tumaj.bid.backend.services.user; import org.springframework.stereotype.Service; import rahnema.tumaj.bid.backend.controllers.SecurityController; import rahnema.tumaj.bid.backend.domains.user.UserInputDTO; import rahnema.tumaj.bid.backend.domains.user.UserOutputDTO; import rahnema.tumaj.bid.backend.models.User; import rahnema.tumaj.bid.backend.repositories.UserRepository; import rahnema.tumaj.bid.backend.utils.athentication.TokenUtil; import rahnema.tumaj.bid.backend.utils.exceptions.AlreadyExistExceptions.EmailAlreadyExistsException; import rahnema.tumaj.bid.backend.utils.exceptions.NotFoundExceptions.TokenNotFoundException; import rahnema.tumaj.bid.backend.utils.exceptions.NotFoundExceptions.UserNotFoundException; import java.util.ArrayList; import java.util.List; import java.util.Optional; @Service public class UserServiceImpl implements UserService { private final UserRepository userRepository; private final SecurityController securityController; private final TokenUtil tokenUtil; public UserServiceImpl(UserRepository userRepository, SecurityController securityController, TokenUtil tokenUtil) { this.userRepository = userRepository; this.securityController = securityController; this.tokenUtil = tokenUtil; } @Override public Optional<User> getOne(Long id) { return this.userRepository.findById(id); } @Override public List<User> getAll() { Iterable<User> userIterable = this.userRepository.findAll(); List<User> userList = new ArrayList<>(); userIterable.forEach(userList::add); return userList; } @Override public User addOne(UserInputDTO user) { if (this.userRepository.existsByEmail(user.getEmail())) throw new EmailAlreadyExistsException(user.getEmail()); User userModel = UserInputDTO.toModel(user); userModel.setPassword( this.securityController.bCryptPasswordEncoder .encode(userModel.getPassword()) ); return userRepository.save(userModel); } @Override public Optional<User> findByEmail(String email) { return userRepository.findByEmail(email); } @Override public User saveUser(User user) { return userRepository.save(user); } @Override public User getUserWithToken(String token) { System.out.println(token); String email = tokenUtil .getUsernameFromToken(token.split(" ")[1]) .orElseThrow(TokenNotFoundException::new); return this.findByEmail(email).orElseThrow(() -> new UserNotFoundException(email)); } }
36.148649
119
0.730467
e712b24bd81307313480a05bc7e99b320a725702
450
package library.domain.model.item.bibliography; /** * 本の点数 * (本の種類の数) */ public class NumberOfBook { int value; public NumberOfBook(int value) { this.value = value; } public static int MAX_TO_SHOW = 20; public String show() { String over = value > MAX_TO_SHOW ? "以上" : ""; return value + "件" + over; } @Override public String toString() { return Integer.toString(value); } }
18
54
0.586667
a7ec69c1aa132e1f05ba9d7dac934311a1fe5c38
428
package com.milulost.telegram_display.service; import com.milulost.telegram_display.bean.Message; import com.milulost.telegram_display.bean.User; import java.util.List; public interface MessageService { List<Message> findAll(Integer userId, Integer chatUserId); List<Integer> findChatByUserId(Integer userId); List<Message> findMessageByPage(Integer start, Integer limit, Integer userId, Integer chatUserId); }
28.533333
102
0.801402
322bb68f6a12219cd6fdcf9cd8ffd6452581c4e1
3,349
/** * apache2 */ package com.metlingpot.model.transform; import java.util.Map; import java.util.List; import com.amazonaws.SdkClientException; import com.metlingpot.model.*; import com.amazonaws.transform.Marshaller; import com.amazonaws.util.BinaryUtils; import com.amazonaws.util.StringUtils; import com.amazonaws.util.IdempotentUtils; import com.amazonaws.util.StringInputStream; import com.amazonaws.protocol.json.*; /** * GetDBResponseMarshaller */ public class GetDBResponseJsonMarshaller { /** * Marshall the given parameter object, and output to a SdkJsonGenerator */ public void marshall(GetDBResponse getDBResponse, StructuredJsonGenerator jsonGenerator) { if (getDBResponse == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { jsonGenerator.writeStartObject(); if (getDBResponse.getActionname() != null) { jsonGenerator.writeFieldName("actionname").writeValue(getDBResponse.getActionname()); } if (getDBResponse.getActiontype() != null) { jsonGenerator.writeFieldName("actiontype").writeValue(getDBResponse.getActiontype()); } if (getDBResponse.getActorname() != null) { jsonGenerator.writeFieldName("actorname").writeValue(getDBResponse.getActorname()); } if (getDBResponse.getActortype() != null) { jsonGenerator.writeFieldName("actortype").writeValue(getDBResponse.getActortype()); } if (getDBResponse.getContextname() != null) { jsonGenerator.writeFieldName("contextname").writeValue(getDBResponse.getContextname()); } if (getDBResponse.getContexttype() != null) { jsonGenerator.writeFieldName("contexttype").writeValue(getDBResponse.getContexttype()); } if (getDBResponse.getId() != null) { jsonGenerator.writeFieldName("id").writeValue(getDBResponse.getId()); } if (getDBResponse.getSource() != null) { jsonGenerator.writeFieldName("source").writeValue(getDBResponse.getSource()); } if (getDBResponse.getTargetname() != null) { jsonGenerator.writeFieldName("targetname").writeValue(getDBResponse.getTargetname()); } if (getDBResponse.getTargettype() != null) { jsonGenerator.writeFieldName("targettype").writeValue(getDBResponse.getTargettype()); } if (getDBResponse.getTimestamp() != null) { jsonGenerator.writeFieldName("timestamp").writeValue(getDBResponse.getTimestamp()); } if (getDBResponse.getValue() != null) { jsonGenerator.writeFieldName("value").writeValue(getDBResponse.getValue()); } jsonGenerator.writeEndObject(); } catch (Throwable t) { throw new SdkClientException("Unable to marshall request to JSON: " + t.getMessage(), t); } } private static GetDBResponseJsonMarshaller instance; public static GetDBResponseJsonMarshaller getInstance() { if (instance == null) instance = new GetDBResponseJsonMarshaller(); return instance; } }
38.494253
103
0.636608
6e0b00537a1ff213aeaf65c5dfa93f784ac3cdd1
1,003
package com.entfrm.biz.activiti.service; import com.baomidou.mybatisplus.core.metadata.IPage; import com.entfrm.biz.activiti.dto.ProcessDto; import java.io.InputStream; import java.util.Map; /** * @author entfrm * @date 2020/3/23 */ public interface ProcessService { /** * 分页流程列表 * * @param params * @return */ IPage<ProcessDto> list(Map<String, Object> params); /** * 读取xml/image资源 * * @param procInsId * @param procDefId * @param resType * @return */ InputStream readResource(String procInsId, String procDefId, String resType); /** * 更新状态 * * @param status * @param procDefId * @return */ Boolean changeStatus(String procDefId, String status); /** * 删除流程实例 * * @param deployId * @return */ Boolean removeProcIns(String deployId); /** * 启动流程 * * @param id * @return */ Boolean startLeaveProcess(Integer id); }
17.293103
81
0.585244
8d08edc1937f8d65fa21434a187b88b96120fb68
1,943
package com.epicodus.littlemonsters.models; import com.epicodus.littlemonsters.R; import java.util.ArrayList; /** * Created by Guest on 10/21/15. */ public class AlbumLib { public ArrayList<Album> getAlbums() { return mAlbums; } private ArrayList<Album> mAlbums; public AlbumLib() { setAlbums(); } private void setAlbums() { mAlbums = new ArrayList<>(); mAlbums.add(new Album( "Artpop", "2013", "Aura \nVenus \nG.U.Y. \nSexxx Dreams \nJewels N Drugs \nMANiCURE \nDo What U Want \nArtpop \nSwine \nDonatella \nFashion! \nMary Jane Holland \nDope \nGypsy \nApplause", R.drawable.artpop )); mAlbums.add(new Album( "Born This Way", "2011", "Marry The Night \nBorn This Way \nGovernment Hooker \nJudas \nAmericano \nHair \nScheiße \nBloody Mary \nBad Kids \nHighway Unicorn \nElectric Chapel \nYou and I \nEdge of Glory", R.drawable.born_this_way )); mAlbums.add(new Album ( "Fame Monster", "2009", "Bad Romance \nAlejandro \nMonster \nSpeechless \nDance in the Dark \nTelephone \nSo Happy I Could Die \nTeeth", R.drawable.fame_monster )); mAlbums.add(new Album( "The Fame", "2008", "Just Dance \nLove Game \nPaparazzi \nPoker Face \nEh,Eh \nBeautiful, Dirty, Rich \nThe Fame \nMoney Honey \nStarstruck \nBoys Boys Boys \nProper Gangsta \nBrown Eyes \nI like It Rough \nSummerboy", R.drawable.the_fame )); } public Album nextAlbum(Album currentAlbum) { int index = mAlbums.indexOf(currentAlbum); if(index == mAlbums.size() - 1){ return mAlbums.get(0); } else { return mAlbums.get(index + 1); } } }
30.84127
214
0.567679
a09cee0cbf674203046683bf086ddb5fdf9edbb0
7,804
package com.xia.imagewatch; import android.app.Activity; import android.content.Intent; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.view.WindowManager; import android.widget.ImageView; import android.widget.RelativeLayout; import com.bumptech.glide.Glide; import com.facebook.rebound.Spring; import com.facebook.rebound.SpringConfig; import com.facebook.rebound.SpringListener; import com.facebook.rebound.SpringSystem; import com.facebook.rebound.SpringUtil; import com.nineoldandroids.animation.Animator; import com.nineoldandroids.animation.AnimatorSet; import com.nineoldandroids.animation.ObjectAnimator; /** * 站在牛人的肩膀上 * 引用的包: * compile 'com.android.support:appcompat-v7:25.1.1' //可以换成v4或降低版本 * compile 'com.github.chrisbanes.photoview:library:1.2.3' 图片放大缩小 * compile 'com.facebook.rebound:rebound:0.3.8' //facebook的弹性动画 * compile 'com.github.bumptech.glide:glide:3.7.0' //图片加载工具 * compile 'com.nineoldandroids:library:2.4.0' //大神JakeWharton的动画库 */ public class RolloutBaseActivity extends Activity { // 屏幕宽度 public float Width; // 屏幕高度 public float Height; //整个动画过程显示的图片 protected ImageView showimg; //弹性库:拉力,摩擦力 private final Spring mSpring = SpringSystem .create() .createSpring() .addListener(new ExampleSpringListener()); private RelativeLayout MainView; protected RolloutBDInfo bdInfo; protected RolloutInfo imageInfo; //用于动画的数值 private float size, size_h; //关于imageView想要有多宽 private float img_w; private float img_h; //原图高 private float y_img_h; //退出时候图片飞向的坐标xy protected float to_x = 0; protected float to_y = 0; //打开时图片的坐标 private float tx; private float ty; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); Width = RCommonUtil.getScreenWidth(this); Height = RCommonUtil.getScreenHeight(this); } /** * 获取资源 */ protected void findID() { MainView = (RelativeLayout) findViewById(R.id.main_show_view); } /** * 监听 */ protected void Listener() { } /** * 初始 */ public void InData() { } protected void EndSoring() { } protected void EndMove() { } /** * 获取相应的数据 */ protected void getValue() { showimg = new ImageView(this); showimg.setScaleType(ImageView.ScaleType.CENTER_CROP); Glide.with(this).load(imageInfo.url).centerCrop().into(showimg); //关于imageView想要有多宽 img_w = bdInfo.width; img_h = bdInfo.height; //动画变化值 size = Width / img_w; y_img_h = imageInfo.height * Width / imageInfo.width; size_h = y_img_h / img_h; RelativeLayout.LayoutParams p = new RelativeLayout.LayoutParams((int) bdInfo.width, (int) bdInfo.height); showimg.setLayoutParams(p); p.setMargins((int) bdInfo.x, (int) bdInfo.y, (int) (Width - (bdInfo.x + bdInfo.width)), (int) (Height - (bdInfo.y + bdInfo.height))); MainView.addView(showimg); showimg.setVisibility(View.VISIBLE); new Handler().postDelayed(new Runnable() { public void run() { setShowimage(); } }, 300); } /** * 根据数据设置展示图 */ protected void setShowimage() { if (mSpring.getEndValue() == 0) { mSpring.setSpringConfig(SpringConfig.fromOrigamiTensionAndFriction(170, 5)); tx = Width / 2 - (bdInfo.x + img_w / 2); ty = Height / 2 - (bdInfo.y + img_h / 2); MoveView(); return; } mSpring.setSpringConfig(SpringConfig.fromOrigamiTensionAndFriction(1, 5)); mSpring.setEndValue(0); new Handler().postDelayed(new Runnable() { public void run() { //execute the task MoveBackView(); } }, 300); } private class ExampleSpringListener implements SpringListener { @Override public void onSpringUpdate(Spring spring) { double CurrentValue = spring.getCurrentValue(); float mappedValue = (float) SpringUtil.mapValueFromRangeToRange(CurrentValue, 0, 1, 1, size); float mapy = (float) SpringUtil.mapValueFromRangeToRange(CurrentValue, 0, 1, 1, size_h); showimg.setScaleX(mappedValue); showimg.setScaleY(mapy); if (CurrentValue == 1) { EndSoring(); } } @Override public void onSpringAtRest(Spring spring) { } @Override public void onSpringActivate(Spring spring) { } @Override public void onSpringEndStateChange(Spring spring) { } } /** * 图片展示前动画 */ private void MoveView() { //属性动画 ObjectAnimator.ofFloat(MainView, "alpha", 0.8f).setDuration(0).start(); MainView.setVisibility(View.VISIBLE); //属性动画集合 AnimatorSet set = new AnimatorSet(); set.playTogether( ObjectAnimator.ofFloat(showimg, "translationX", tx).setDuration(200), ObjectAnimator.ofFloat(showimg, "translationY", ty).setDuration(200), ObjectAnimator.ofFloat(MainView, "alpha", 1).setDuration(200) ); set.addListener(new Animator.AnimatorListener() { @Override public void onAnimationStart(Animator animator) { } @Override public void onAnimationEnd(Animator animator) { showimg.setScaleType(ImageView.ScaleType.FIT_XY); mSpring.setEndValue(1); MainView.setBackgroundResource(R.color.rollout_preview_bg); } @Override public void onAnimationCancel(Animator animator) { } @Override public void onAnimationRepeat(Animator animator) { } }); set.start(); } /** * 图片退出动画 */ private void MoveBackView() { AnimatorSet set = new AnimatorSet(); set.playTogether( ObjectAnimator.ofFloat(showimg, "translationX", to_x).setDuration(200), ObjectAnimator.ofFloat(showimg, "translationY", to_y).setDuration(200) ); set.addListener(new Animator.AnimatorListener() { @Override public void onAnimationStart(Animator animator) { showimg.setScaleType(ImageView.ScaleType.CENTER_CROP); } @Override public void onAnimationEnd(Animator animator) { EndMove(); } @Override public void onAnimationCancel(Animator animator) { } @Override public void onAnimationRepeat(Animator animator) { } }); set.start(); } /** * 对跳转的动画可以重新自己定义 * * @param intent */ @Override public void startActivity(Intent intent) { super.startActivity(intent); overridePendingTransition(R.anim.activity_in, 0); } @Override public void onBackPressed() { super.onBackPressed(); overridePendingTransition(0, R.anim.activity_out); } @Override public void finish() { super.finish(); overridePendingTransition(0, R.anim.activity_out); } @Override protected void onDestroy() { super.onDestroy(); Glide.get(this).clearMemory(); } }
27.00346
141
0.608534
0b1c6e572ceb36057bf58ca77013f68fddda43b8
5,942
/* * Copyright (c) 2006, Pierre Carion. * * 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.carion.s3.util; import java.io.IOException; import java.io.InputStream; public class ContentLengthInputStream extends InputStream { private static int BUFFER_SIZE = 2048; /** * The maximum number of bytes that can be read from the stream. Subsequent * read operations will return -1. */ private final long _contentLength; /** The current position */ private long _pos = 0; /** True if the stream is closed. */ private boolean _closed = false; private final boolean _keepAlive; /** * Wrapped input stream that all calls are delegated to. */ private final InputStream _in; private final InputStreamObserver _observer; /** * Creates a new length limited stream * * @param in The stream to wrap * @param contentLength The maximum number of bytes that can be read from * the stream. Subsequent read operations will return -1. * * @since 3.0 */ ContentLengthInputStream(InputStream in, long contentLength, boolean keepAlive, InputStreamObserver observer) { if (in == null) { throw new IllegalArgumentException("Input stream may not be null"); } if (contentLength < 0) { throw new IllegalArgumentException( "Content length may not be negative"); } _keepAlive = keepAlive; _observer = observer; _in = in; _contentLength = contentLength; } /** * <p>Reads until the end of the known length of content.</p> * * <p>Does not close the underlying socket input, but instead leaves it * primed to parse the next response.</p> * @throws IOException If an IO problem occurs. */ public void close() throws IOException { if (!_closed) { try { byte buffer[] = new byte[BUFFER_SIZE]; while (read(buffer) >= 0) { } } finally { // close after above so that we don't throw an exception trying // to read after closed! _closed = true; if (!_keepAlive) { _in.close(); } if (_observer != null) { _observer.closeConnection(); } } } } /** * Read the next byte from the stream * @return The next byte or -1 if the end of stream has been reached. * @throws IOException If an IO problem occurs * @see java.io.InputStream#read() */ public int read() throws IOException { if (_closed) { throw new IOException("Attempted read from closed stream."); } if (_pos >= _contentLength) { return -1; } _pos++; return _in.read(); } /** * Does standard {@link InputStream#read(byte[], int, int)} behavior, but * also notifies the watcher when the contents have been consumed. * * @param b The byte array to fill. * @param off Start filling at this position. * @param len The number of bytes to attempt to read. * @return The number of bytes read, or -1 if the end of content has been * reached. * * @throws java.io.IOException Should an error occur on the wrapped stream. */ public int read(byte[] b, int off, int len) throws java.io.IOException { if (_closed) { throw new IOException("Attempted read from closed stream."); } if (_pos >= _contentLength) { return -1; } if (_pos + len > _contentLength) { len = (int) (_contentLength - _pos); } int count = _in.read(b, off, len); _pos += count; return count; } /** * Read more bytes from the stream. * @param b The byte array to put the new data in. * @return The number of bytes read into the buffer. * @throws IOException If an IO problem occurs * @see java.io.InputStream#read(byte[]) */ public int read(byte[] b) throws IOException { return read(b, 0, b.length); } /** * Skips and discards a number of bytes from the input stream. * @param n The number of bytes to skip. * @return The actual number of bytes skipped. <= 0 if no bytes * are skipped. * @throws IOException If an error occurs while skipping bytes. * @see InputStream#skip(long) */ public long skip(long n) throws IOException { if (n <= 0) { return 0; } byte[] buffer = new byte[BUFFER_SIZE]; // make sure we don't skip more bytes than are // still available long remaining = Math.min(n, _contentLength - _pos); // skip and keep track of the bytes actually skipped long count = 0; while (remaining > 0) { int l = read(buffer, 0, (int) Math.min(BUFFER_SIZE, remaining)); if (l == -1) { break; } count += l; remaining -= l; } _pos += count; return count; } }
32.293478
80
0.562942
e6d0c2d6ed8142fa3d1932577fee45b2259e3bae
185
package kodlamaio.hrms.core.utilities.adapters; public interface ValidationService { boolean validateByMernis(long nationalId, String firstName, String lastName, int yearOfBirth); }
26.428571
95
0.827027
85367743e479e6223b335752573dd5e4796dd0ee
1,025
package io.github.benas.randombeans.randomizers; import io.github.benas.randombeans.api.Randomizer; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import static java.lang.String.valueOf; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.when; @RunWith(MockitoJUnitRunner.class) public class StringDelegatingRandomizerTest { @Mock private Randomizer delegate; @Mock private Object object; private StringDelegatingRandomizer stringDelegatingRandomizer; @Before public void setUp() throws Exception { stringDelegatingRandomizer = new StringDelegatingRandomizer(delegate); when(delegate.getRandomValue()).thenReturn(object); } @Test public void testGetRandomValue() throws Exception { String actual = stringDelegatingRandomizer.getRandomValue(); assertThat(actual).isEqualTo(valueOf(object)); } }
27.702703
78
0.766829
2b7dceb2ba74d5ca3300e85801441854419a8714
27,588
package org.openplacereviews.opendb.service; import static org.openplacereviews.opendb.ops.OpBlockChain.OP_CHANGE_DELETE; import static org.openplacereviews.opendb.ops.de.ColumnDef.IndexType.INDEXED; import static org.openplacereviews.opendb.ops.de.ColumnDef.IndexType.NOT_INDEXED; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.TreeMap; import java.util.TreeSet; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.openplacereviews.opendb.OpenDBServer.MetadataDb; import org.openplacereviews.opendb.SecUtils; import org.openplacereviews.opendb.ops.OpBlock; import org.openplacereviews.opendb.ops.OpBlockchainRules; import org.openplacereviews.opendb.ops.OpIndexColumn; import org.openplacereviews.opendb.ops.OpObject; import org.openplacereviews.opendb.ops.OpOperation; import org.openplacereviews.opendb.ops.de.ColumnDef; import org.openplacereviews.opendb.ops.de.ColumnDef.IndexType; import org.openplacereviews.opendb.service.SettingsManager.CommonPreference; import org.openplacereviews.opendb.service.SettingsManager.MapStringObjectPreference; import org.openplacereviews.opendb.util.JsonFormatter; import org.openplacereviews.opendb.util.OUtils; import org.postgresql.util.PGobject; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.dao.DataAccessException; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.ResultSetExtractor; import org.springframework.jdbc.core.RowCallbackHandler; import org.springframework.stereotype.Service; @Service public class DBSchemaManager { protected static final Log LOGGER = LogFactory.getLog(DBSchemaManager.class); private static final int OPENDB_SCHEMA_VERSION = 6; // //////////SYSTEM TABLES DDL //////////// protected static final String SETTINGS_TABLE = "opendb_settings"; protected static final String BLOCKS_TABLE = "blocks"; protected static final String OPERATIONS_TABLE = "operations"; protected static final String OBJS_TABLE = "objs"; protected static final String OPERATIONS_TRASH_TABLE = "operations_trash"; protected static final String BLOCKS_TRASH_TABLE = "blocks_trash"; protected static final String EXT_RESOURCE_TABLE = "resources"; protected static final String OP_OBJ_HISTORY_TABLE = "op_obj_history"; private static DBSchemaHelper dbschema = new DBSchemaHelper(SETTINGS_TABLE); protected static final int MAX_KEY_SIZE = 5; public static final String[] INDEX_P = new String[MAX_KEY_SIZE]; { for(int i = 0; i < MAX_KEY_SIZE; i++) { INDEX_P[i] = "p" + (i + 1); } } protected static final int HISTORY_USERS_SIZE = 2; private static final int BATCH_SIZE = 1000; // loaded from config private Map<String, Map<String, Object>> objtables; private TreeMap<String, ObjectTypeTable> objTableDefs = new TreeMap<String, ObjectTypeTable>(); private TreeMap<String, String> typeToTables = new TreeMap<String, String>(); private TreeMap<String, Map<String, OpIndexColumn>> indexes = new TreeMap<>(); @Autowired private IPFSFileManager externalResourceService; @Autowired private JsonFormatter formatter; @Autowired private SettingsManager settingsManager; static class ObjectTypeTable { public ObjectTypeTable(String tableName, int keySize) { this.tableName = tableName; this.keySize = keySize; } String tableName; int keySize; Set<String> types = new TreeSet<>(); } public Map<String, Map<String, Object>> getIndexState(boolean actualState) { LinkedHashMap<String, Map<String, Object>> state = new LinkedHashMap<String, Map<String,Object>>(); List<CommonPreference<Map<String, Object>>> userIndexes = settingsManager.getPreferencesByPrefix( actualState? SettingsManager.DB_SCHEMA_INTERNAL_INDEXES : SettingsManager.DB_SCHEMA_INDEXES); for(CommonPreference<Map<String, Object>> p : userIndexes) { state.put(p.getId(), p.get()); } return state; } public Map<String, Map<String, OpIndexColumn>> getIndexes() { return indexes; } static { dbschema.registerColumn(BLOCKS_TABLE, "hash", "bytea PRIMARY KEY", INDEXED); dbschema.registerColumn(BLOCKS_TABLE, "phash", "bytea", NOT_INDEXED); dbschema.registerColumn(BLOCKS_TABLE, "blockid", "int", INDEXED); dbschema.registerColumn(BLOCKS_TABLE, "superblock", "bytea", INDEXED); dbschema.registerColumn(BLOCKS_TABLE, "opcount", "int", NOT_INDEXED); dbschema.registerColumn(BLOCKS_TABLE, "objdeleted", "int", NOT_INDEXED); dbschema.registerColumn(BLOCKS_TABLE, "objedited", "int", NOT_INDEXED); dbschema.registerColumn(BLOCKS_TABLE, "objadded", "int", NOT_INDEXED); dbschema.registerColumn(BLOCKS_TABLE, "blocksize", "int", NOT_INDEXED); dbschema.registerColumn(BLOCKS_TABLE, "header", "jsonb", NOT_INDEXED); dbschema.registerColumn(BLOCKS_TABLE, "content", "jsonb", NOT_INDEXED); dbschema.registerColumn(BLOCKS_TRASH_TABLE, "hash", "bytea PRIMARY KEY", INDEXED); dbschema.registerColumn(BLOCKS_TRASH_TABLE, "phash", "bytea", NOT_INDEXED); dbschema.registerColumn(BLOCKS_TRASH_TABLE, "blockid", "int", INDEXED); dbschema.registerColumn(BLOCKS_TRASH_TABLE, "time", "timestamp", NOT_INDEXED); dbschema.registerColumn(BLOCKS_TRASH_TABLE, "content", "jsonb", NOT_INDEXED); dbschema.registerColumn(OPERATIONS_TABLE, "dbid", "serial not null", NOT_INDEXED); dbschema.registerColumn(OPERATIONS_TABLE, "hash", "bytea PRIMARY KEY", INDEXED); dbschema.registerColumn(OPERATIONS_TABLE, "type", "text", INDEXED); dbschema.registerColumn(OPERATIONS_TABLE, "superblock", "bytea", INDEXED); dbschema.registerColumn(OPERATIONS_TABLE, "sblockid", "int", INDEXED); dbschema.registerColumn(OPERATIONS_TABLE, "sorder", "int", INDEXED); dbschema.registerColumn(OPERATIONS_TABLE, "blocks", "bytea[]", NOT_INDEXED); dbschema.registerColumn(OPERATIONS_TABLE, "content", "jsonb", NOT_INDEXED); dbschema.registerColumn(OP_OBJ_HISTORY_TABLE, "sorder", "serial not null", NOT_INDEXED); dbschema.registerColumn(OP_OBJ_HISTORY_TABLE, "blockhash", "bytea", INDEXED); dbschema.registerColumn(OP_OBJ_HISTORY_TABLE, "ophash", "bytea", INDEXED); dbschema.registerColumn(OP_OBJ_HISTORY_TABLE, "type", "text", INDEXED); for (int i = 1; i <= HISTORY_USERS_SIZE; i++) { dbschema.registerColumn(OP_OBJ_HISTORY_TABLE, "usr_" + i, "text", INDEXED); dbschema.registerColumn(OP_OBJ_HISTORY_TABLE, "login_" + i, "text", INDEXED); } for (int i = 1; i <= MAX_KEY_SIZE; i++) { dbschema.registerColumn(OP_OBJ_HISTORY_TABLE, "p" + i, "text", INDEXED); } dbschema.registerColumn(OP_OBJ_HISTORY_TABLE, "time", "timestamp", NOT_INDEXED); dbschema.registerColumn(OP_OBJ_HISTORY_TABLE, "obj", "jsonb", NOT_INDEXED); dbschema.registerColumn(OP_OBJ_HISTORY_TABLE, "status", "int", NOT_INDEXED); dbschema.registerColumn(OPERATIONS_TRASH_TABLE, "id", "int", INDEXED); dbschema.registerColumn(OPERATIONS_TRASH_TABLE, "hash", "bytea", INDEXED); dbschema.registerColumn(OPERATIONS_TRASH_TABLE, "type", "text", INDEXED); dbschema.registerColumn(OPERATIONS_TRASH_TABLE, "time", "timestamp", NOT_INDEXED); dbschema.registerColumn(OPERATIONS_TRASH_TABLE, "content", "jsonb", NOT_INDEXED); dbschema.registerColumn(EXT_RESOURCE_TABLE, "hash", "bytea PRIMARY KEY", INDEXED); dbschema.registerColumn(EXT_RESOURCE_TABLE, "extension", "text", NOT_INDEXED); dbschema.registerColumn(EXT_RESOURCE_TABLE, "cid", "text", NOT_INDEXED); dbschema.registerColumn(EXT_RESOURCE_TABLE, "added", "timestamp", NOT_INDEXED); dbschema.registerColumn(EXT_RESOURCE_TABLE, "blocks", "bytea[]", NOT_INDEXED); registerObjTable(OBJS_TABLE, MAX_KEY_SIZE); } private static void registerObjTable(String tbName, int maxKeySize) { dbschema.registerColumn(tbName, "type", "text", INDEXED); for (int i = 1; i <= maxKeySize; i++) { dbschema.registerColumn(tbName, "p" + i, "text", INDEXED); } dbschema.registerColumn(tbName, "ophash", "bytea", INDEXED); dbschema.registerColumn(tbName, "superblock", "bytea", INDEXED); dbschema.registerColumn(tbName, "sblockid", "int", INDEXED); dbschema.registerColumn(tbName, "sorder", "int", INDEXED); dbschema.registerColumn(tbName, "content", "jsonb", NOT_INDEXED); } public Map<String, Map<String, Object>> getObjtables() { if (objtables != null) { return objtables; } else { Map<String, Map<String, Object>> objtable = new TreeMap<>(); List<CommonPreference<Map<String, Object>>> preferences = settingsManager.getPreferencesByPrefix(SettingsManager.DB_SCHEMA_OBJTABLES); for (CommonPreference<Map<String, Object>> opendbPreference : preferences) { MapStringObjectPreference mp = (MapStringObjectPreference) opendbPreference; String tableName = mp.getStringValue(SettingsManager.OBJTABLE_TABLENAME, ""); objtable.put(tableName, mp.get()); } objtables = objtable; return objtable; } } public Collection<String> getObjectTables() { return objTableDefs.keySet(); } public String getTableByType(String type) { String tableName = typeToTables.get(type); if(tableName != null) { return tableName; } return OBJS_TABLE; } public List<String> getTypesByTable(String table) { List<String> types = new ArrayList<String>(); for (Map.Entry<String, String> entry : typeToTables.entrySet()) { if (table.equals(entry.getValue())) { types.add(entry.getKey()); } } return types; } // this is confusing method and it is incorrect cause we don't know precise key length for type // public int getKeySizeByType(String type) { // return getKeySizeByTable(getTableByType(type)); // } public int getKeySizeByTable(String table) { return objTableDefs.get(table).keySize; } public String generatePKString(String objTable, String mainString, String sep) { return repeatString(mainString, sep, getKeySizeByTable(objTable)); } public String generatePKString(String objTable, String mainString, String sep, int ks) { return repeatString(mainString, sep, ks); } public String repeatString(String mainString, String sep, int ks) { String s = ""; for(int k = 1; k <= ks; k++) { if(k > 1) { s += sep; } s += String.format(mainString, k); } return s; } private void migrateDBSchema(JdbcTemplate jdbcTemplate) { int dbVersion = dbschema.getIntSetting(jdbcTemplate, "opendb.version"); if (dbVersion < OPENDB_SCHEMA_VERSION) { if (dbVersion <= 1) { setOperationsType(jdbcTemplate, OPERATIONS_TABLE); setOperationsType(jdbcTemplate, OPERATIONS_TRASH_TABLE); } if (dbVersion <= 3) { addBlockAdditionalInfo(jdbcTemplate); } if (dbVersion <= 4) { List<CommonPreference<Map<String, Object>>> prefs = settingsManager.getPreferencesByPrefix(SettingsManager.DB_SCHEMA_INDEXES); for(CommonPreference<Map<String, Object>> p : prefs) { CommonPreference<Map<String, Object>> ps = settingsManager.registerMapPreferenceForFamily(SettingsManager.DB_SCHEMA_INTERNAL_INDEXES, p.get()); ps.set(p.get()); } } if (dbVersion < 6) { updateExternalResources(jdbcTemplate); } // if (dbVersion <= 6) { // fixMultipleDeletions(jdbcTemplate); // } setSetting(jdbcTemplate, "opendb.version", OPENDB_SCHEMA_VERSION + ""); } else if (dbVersion > OPENDB_SCHEMA_VERSION) { throw new UnsupportedOperationException(); } } private void handleBatch(JdbcTemplate jdbcTemplate, List<Object[]> batchArgs, String batchQuery, boolean force) { if(batchArgs.size() >= BATCH_SIZE || (force && batchArgs.size() > 0)) { jdbcTemplate.batchUpdate(batchQuery, batchArgs); batchArgs.clear(); } } private void setOperationsType(JdbcTemplate jdbcTemplate, String table) { LOGGER.info("Indexing operation types required for db version 2: " + table); List<Object[]> batchArgs = new ArrayList<Object[]>(); String batchQuery = "update " + table + " set type = ? where hash = ?"; jdbcTemplate.query("select hash, content from " + table, new RowCallbackHandler() { @Override public void processRow(ResultSet rs) throws SQLException { OpOperation op = formatter.parseOperation(rs.getString(2)); Object[] args = new Object[2]; args[0] = op.getType(); args[1] = rs.getObject(1); batchArgs.add(args); handleBatch(jdbcTemplate, batchArgs, batchQuery, false); } }); handleBatch(jdbcTemplate, batchArgs, batchQuery, true); } public void initializeDatabaseSchema(MetadataDb metadataDB, JdbcTemplate jdbcTemplate) { dbschema.initSettingsTable(metadataDB, jdbcTemplate); prepareObjTableMapping(); prepareCustomIndices(jdbcTemplate); dbschema.createTablesIfNeeded(metadataDB, jdbcTemplate); migrateDBSchema(jdbcTemplate); migrateObjMappingIfNeeded(jdbcTemplate); } @SuppressWarnings("unchecked") private void migrateObjMappingIfNeeded(JdbcTemplate jdbcTemplate) { String objMapping = getSetting(jdbcTemplate, "opendb.mapping"); String newMapping = formatter.toJsonElement(getObjtables()).toString(); if (!OUtils.equals(newMapping, objMapping)) { LOGGER.info(String.format("Start object mapping migration from '%s' to '%s'", objMapping, newMapping)); TreeMap<String, String> previousTypeToTable = new TreeMap<>(); if (objMapping != null && objMapping.length() > 0) { TreeMap<String, Object> previousMapping = formatter.fromJsonToTreeMap(objMapping); for(String tableName : previousMapping.keySet()) { Object types = ((Map<String, Object>) previousMapping.get(tableName)).get("types"); Collection<String> otypes = null; if(types instanceof Collection) { otypes = (Collection<String>) types; } else if(types instanceof Map) { otypes = ((Map<Object, String>) types).values(); } if(otypes != null) { for(String type : otypes) { previousTypeToTable.put(type, tableName); } } } } for (String tableName : objTableDefs.keySet()) { ObjectTypeTable ott = objTableDefs.get(tableName); for (String type : ott.types) { String prevTable = previousTypeToTable.remove(type); if (prevTable == null) { prevTable = OBJS_TABLE; } migrateObjDataBetweenTables(type, tableName, prevTable, ott.keySize, jdbcTemplate); } } for (String type : previousTypeToTable.keySet()) { String prevTable = previousTypeToTable.get(type); int keySize = objTableDefs.get(prevTable).keySize; migrateObjDataBetweenTables(type, OBJS_TABLE, prevTable, keySize, jdbcTemplate); } setSetting(jdbcTemplate, "opendb.mapping", newMapping); } } private void migrateObjDataBetweenTables(String type, String tableName, String prevTable, int keySize, JdbcTemplate jdbcTemplate) { if(!OUtils.equals(tableName, prevTable)) { LOGGER.info(String.format("Migrate objects of type '%s' from '%s' to '%s'...", type, prevTable, tableName)); // compare existing table String pks = ""; for(int i = 1; i <= keySize; i++) { pks += ", p" +i; } int update = jdbcTemplate.update( "WITH moved_rows AS ( DELETE FROM " + prevTable + " a WHERE type = ? RETURNING a.*) " + "INSERT INTO " + tableName + "(type, ophash, superblock, sblockid, sorder, content " + pks + ") " + "SELECT type, ophash, superblock, sblockid, sorder, content" + pks + " FROM moved_rows", type); LOGGER.info(String.format("Migrate %d objects of type '%s'.", update, type)); } } private void prepareCustomIndices(JdbcTemplate jdbcTemplate) { List<CommonPreference<Map<String, Object>>> indexes = settingsManager.getPreferencesByPrefix(SettingsManager.DB_SCHEMA_INDEXES); for(CommonPreference<Map<String, Object>> pind : indexes) { Map<String, Object> indexDef = pind.get(); generateIndexColumn(indexDef); } } private IndexType getIndexType(String index) { if (index != null) { if (index.equalsIgnoreCase("true")) { return INDEXED; } else { return ColumnDef.IndexType.valueOf(index); } } return null; } public ColumnDef generateIndexColumn(Map<String, Object> entry) { String name = (String) entry.get(SettingsManager.INDEX_NAME); String tableName = (String) entry.get(SettingsManager.INDEX_TABLENAME); String colType = (String) entry.get(SettingsManager.INDEX_SQL_TYPE); String index = (String) entry.get(SettingsManager.INDEX_INDEX_TYPE); Integer cacheRuntime = entry.get(SettingsManager.INDEX_CACHE_RUNTIME_MAX) == null ? null : ((Number) entry.get(SettingsManager.INDEX_CACHE_RUNTIME_MAX)).intValue(); Integer cacheDB = entry.get(SettingsManager.INDEX_CACHE_DB_MAX) == null ? null : ((Number) entry.get(SettingsManager.INDEX_CACHE_DB_MAX)).intValue(); @SuppressWarnings("unchecked") List<String> fld = (List<String>) entry.get(SettingsManager.INDEX_FIELD); IndexType di = getIndexType(index); ColumnDef cd = new ColumnDef(tableName, name, colType, di); // to be used array // String sqlmapping = (String) entry.get("sqlmapping"); if (fld != null) { ObjectTypeTable objectTypeTable = objTableDefs.get(tableName); for (String type : objectTypeTable.types) { OpIndexColumn indexColumn = new OpIndexColumn(type, name, -1, cd); if (cacheRuntime != null) { indexColumn.setCacheRuntimeBlocks(cacheRuntime); } if (cacheDB != null) { indexColumn.setCacheDBBlocks(cacheDB); } indexColumn.setFieldsExpression(fld); addIndexCol(indexColumn); } } return dbschema.registerColumn(tableName, cd); } @SuppressWarnings("unchecked") private void prepareObjTableMapping() { for(String tableName : getObjtables().keySet()) { Number i = ((Number) getObjtables().get(tableName).get("keysize")); if (i == null) { i = MAX_KEY_SIZE; } registerObjTable(tableName, i.intValue()); ObjectTypeTable ott = new ObjectTypeTable(tableName, i.intValue()); objTableDefs.put(tableName, ott); List<String> tps = (List<String>) getObjtables().get(tableName).get("types"); if(tps != null) { for(String type : tps) { typeToTables.put(type, tableName); ott.types.add(type); for(ColumnDef c : dbschema.schema.get(tableName)) { for(int indId = 0 ; indId < MAX_KEY_SIZE; indId++) { if(c.getColName().equals(INDEX_P[indId])) { addIndexCol(new OpIndexColumn(type, INDEX_P[indId], indId, c)); } } } } } } objTableDefs.put(OBJS_TABLE, new ObjectTypeTable(OBJS_TABLE, MAX_KEY_SIZE)); } public void removeIndex(JdbcTemplate jdbcTemplate, Map<String, Object> entry) { String colName = (String) entry.get(SettingsManager.INDEX_NAME); String tableName = (String) entry.get(SettingsManager.INDEX_TABLENAME); String index = (String) entry.get(SettingsManager.INDEX_INDEX_TYPE); IndexType it = getIndexType(index); ObjectTypeTable objectTypeTable = objTableDefs.get(tableName); for (String type : objectTypeTable.types) { Map<String, OpIndexColumn> indexesByType = indexes.get(type); // potentially concurrent modification exception indexesByType.remove(index); } jdbcTemplate.execute("DROP INDEX " + dbschema.generateIndexName(it, tableName, colName)); CommonPreference<Object> pref = settingsManager.getPreferenceByKey(SettingsManager.DB_SCHEMA_INTERNAL_INDEXES.getId(tableName + "." + colName)); if(pref != null) { settingsManager.removePreferenceInternal(pref); } } private void addIndexCol(OpIndexColumn indexColumn) { if (!indexes.containsKey(indexColumn.getOpType())) { indexes.put(indexColumn.getOpType(), new TreeMap<String, OpIndexColumn>()); } indexes.get(indexColumn.getOpType()).put(indexColumn.getIndexId(), indexColumn); } public boolean setSetting(JdbcTemplate jdbcTemplate, String key, String v) { return dbschema.setSetting(jdbcTemplate, key, v); } public int removeSetting(JdbcTemplate jdbcTemplate, String key) { return dbschema.removeSetting(jdbcTemplate, key); } public String getSetting(JdbcTemplate jdbcTemplate, String key) { return dbschema.getSetting(jdbcTemplate, key); } public void alterTableNewColumn(JdbcTemplate jdbcTemplate, ColumnDef col) { dbschema.alterTableNewColumn(jdbcTemplate, col); } public Map<String, String> getSettings(JdbcTemplate jdbcTemplate) { Map<String, String> r = new TreeMap<>(); try { jdbcTemplate.query("select key, value from " + SETTINGS_TABLE, new ResultSetExtractor<Void>() { @Override public Void extractData(ResultSet rs) throws SQLException, DataAccessException { while(rs.next()) { r.put(rs.getString(1), rs.getString(2)); } return null; } }); } catch (DataAccessException e) { } return r; } public OpIndexColumn getIndex(String type, String columnId) { Map<String, OpIndexColumn> tind = indexes.get(type); if(tind != null) { return tind.get(columnId); } return null; } public Collection<OpIndexColumn> getIndicesForType(String type) { if(type == null) { List<OpIndexColumn> ind = new ArrayList<>(); Iterator<Map<String, OpIndexColumn>> it = indexes.values().iterator(); while(it.hasNext()) { ind.addAll(it.next().values()); } return ind; } Map<String, OpIndexColumn> tind = indexes.get(type); if(tind != null) { return tind.values(); } return Collections.emptyList(); } public void insertObjIntoTableBatch(List<Object[]> args, String table, JdbcTemplate jdbcTemplate, Collection<OpIndexColumn> indexes) { StringBuilder extraColumnNames = new StringBuilder(); for(OpIndexColumn index : indexes) { extraColumnNames.append(index.getColumnDef().getColName()).append(","); } jdbcTemplate.batchUpdate("INSERT INTO " + table + "(type,ophash,superblock,sblockid,sorder,content," + extraColumnNames.toString() + generatePKString(table, "p%1$d", ",") + ") " + " values(?,?,?,?,?,?," + repeatString("?,", "", indexes.size()) + generatePKString(table, "?", ",") + ")", args); } public void insertObjIntoHistoryTableBatch(List<Object[]> args, String table, JdbcTemplate jdbcTemplate) { jdbcTemplate.batchUpdate("INSERT INTO " + table + "(blockhash, ophash, type, time, obj, status," + generatePKString(table, "usr_%1$d, login_%1$d", ",", HISTORY_USERS_SIZE) + "," + generatePKString(table, "p%1$d", ",", MAX_KEY_SIZE) + ") VALUES ("+ generatePKString(table, "?", ",", HISTORY_USERS_SIZE * 2 + MAX_KEY_SIZE + 6 ) + ")", args); } /// MIGRATION functions private void addBlockAdditionalInfo(JdbcTemplate jdbcTemplate) { LOGGER.info("Adding new columns: 'opcount, objdeleted, objedited, objadded' for table: " + BLOCKS_TABLE); final OpBlockchainRules rules = new OpBlockchainRules(formatter, null); jdbcTemplate.query("SELECT content FROM " + BLOCKS_TABLE, new ResultSetExtractor<Integer>() { @Override public Integer extractData(ResultSet rs) throws SQLException, DataAccessException { int i = 0; while (rs.next()) { OpBlock opBlock = formatter.parseBlock(rs.getString(1)); OpBlock blockheader = OpBlock.createHeader(opBlock, rules); PGobject blockHeaderObj = new PGobject(); blockHeaderObj.setType("jsonb"); try { blockHeaderObj.setValue(formatter.fullObjectToJson(blockheader)); } catch (SQLException e) { throw new IllegalArgumentException(e); } jdbcTemplate.update("UPDATE " + BLOCKS_TABLE + " set opcount = ?, objdeleted = ?, objedited = ?, objadded = ?, blocksize = ?, header = ? " + " WHERE hash = ?", blockheader.getIntValue(OpBlock.F_OPERATIONS_SIZE, 0), blockheader.getIntValue(OpBlock.F_OBJ_DELETED, 0), blockheader.getIntValue(OpBlock.F_OBJ_EDITED, 0), blockheader.getIntValue(OpBlock.F_OBJ_ADDED, 0), blockheader.getIntValue(OpBlock.F_BLOCK_SIZE, 0), blockHeaderObj, SecUtils.getHashBytes(opBlock.getRawHash())); i++; } LOGGER.info("Updated " + i + " blocks"); return i; } }); } private void updateExternalResources(JdbcTemplate jdbcTemplate) { LOGGER.info("Adding new columns: 'blocks' for table: " + EXT_RESOURCE_TABLE); final OpBlockchainRules rules = new OpBlockchainRules(formatter, null); jdbcTemplate.query("SELECT content FROM " + BLOCKS_TABLE, new ResultSetExtractor<Integer>() { @Override public Integer extractData(ResultSet rs) throws SQLException, DataAccessException { int i = 0; while (rs.next()) { OpBlock opBlock = formatter.parseBlock(rs.getString(1)); externalResourceService.processOperations(opBlock); i++; } LOGGER.info("Updated " + i + " blocks"); return i; } }); } protected void fixMultipleDeletions(JdbcTemplate jdbcTemplate) { // THIS method was never used cause the errors occurred in blockchain were irreversible, so it was needed to keep both versions of the code (buggy & fixed) LOGGER.info("Fix operations with errorneous multiple deletions"); Map<List<String>, String> objsToFix = new HashMap<>(); jdbcTemplate.query("select content, type, superblock, hash from " + OPERATIONS_TABLE + " where content @@ '$.edit.change.keyvalue().key like_regex \".*\\[^[0]\\].*\"'", new RowCallbackHandler() { @Override public void processRow(ResultSet rs) throws SQLException { OpOperation op = formatter.parseOperation(rs.getString(1)); for (OpObject editObject : op.getEdited()) { Map<String, Object> changedMap = editObject.getChangedEditFields(); int deleteCounter = 0; objFields: for (Map.Entry<String, Object> e : changedMap.entrySet()) { Object opValue = e.getValue(); if (opValue instanceof Map) { continue; } String opValueStr = opValue.toString(); if (OP_CHANGE_DELETE.equals(opValueStr)) { deleteCounter++; } if (deleteCounter > 1) { List<String> combinedId = new ArrayList<>(); combinedId.add(op.getType()); combinedId.addAll(editObject.getId()); LOGGER.info(String.format("Suspicious operation probably to fix: %s, %s - %s", op.getType(), op.getHash(), editObject.getId())); objsToFix.put(combinedId, op.getType()); break objFields; } } } } }); LOGGER.info("To scan & fix objects: " + objsToFix); Iterator<Entry<List<String>, String>> itObj = objsToFix.entrySet().iterator(); while (itObj.hasNext()) { List<String> objectId = itObj.next().getKey(); String objType = objectId.remove(0); List<OpOperation> opsList = new ArrayList<OpOperation>(); StringBuilder idQ = new StringBuilder(); for (String idP : objectId) { if (idQ.length() > 0) { idQ.append(", "); } idQ.append("\"").append(idP).append("\""); } String sqlQuery = "select content, type, superblock, hash from " + OPERATIONS_TABLE + " where type = '" + objType + "' and (content->'edit' @> '[{\"id\":[" + idQ.toString() + "]}]'::jsonb or " + " content->'create' @> '[{\"id\":[" + idQ.toString() + "]}]'::jsonb or " + " content->'create' @> '[{\"id\":[" + idQ.toString() + "]}]'::jsonb)" + " order by sblockid asc, sorder asc"; LOGGER.info(sqlQuery); LOGGER.info("Proceed with " + objectId); jdbcTemplate.query(sqlQuery, new RowCallbackHandler() { @Override public void processRow(ResultSet rs) throws SQLException { OpOperation op = formatter.parseOperation(rs.getString(1)); LOGGER.info(objType + " " + op.getHash()); opsList.add(op); } }); } } }
39.924747
170
0.716036
8c55dc69f83612b6b6ce0137c23d5c4e37c63dfe
6,504
/* * Copyright (c) 2012, The President and Fellows of Harvard College. * All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE UNIVERSITY AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE UNIVERSITY OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ package harvard.robobees.simbeeotic.example; import com.bulletphysics.collision.shapes.CollisionShape; import com.bulletphysics.collision.shapes.SphereShape; import com.bulletphysics.dynamics.DiscreteDynamicsWorld; import com.bulletphysics.dynamics.RigidBody; import com.bulletphysics.dynamics.RigidBodyConstructionInfo; import com.bulletphysics.linearmath.MotionState; import com.bulletphysics.linearmath.Transform; import com.google.inject.Inject; import com.google.inject.name.Named; import harvard.robobees.simbeeotic.SimTime; import harvard.robobees.simbeeotic.environment.PhysicalConstants; import harvard.robobees.simbeeotic.model.EntityInfo; import harvard.robobees.simbeeotic.model.RecordedMotionState; import harvard.robobees.simbeeotic.model.SimpleBee; import harvard.robobees.simbeeotic.model.TimerCallback; import harvard.robobees.simbeeotic.model.comms.Radio; import harvard.robobees.simbeeotic.model.sensor.Accelerometer; import harvard.robobees.simbeeotic.model.sensor.Compass; import harvard.robobees.simbeeotic.model.sensor.ContactSensor; import harvard.robobees.simbeeotic.model.sensor.Gyroscope; import harvard.robobees.simbeeotic.model.sensor.RangeSensor; import org.apache.log4j.Logger; import javax.vecmath.Vector3f; import java.awt.Color; import java.util.concurrent.TimeUnit; /** * A bee that makes random adjustments to its movement at every time step * and takes a sensor reading periodically. It is used to define a typical * workload in instrumentation runs. * * @author bkate */ public class InstrumentBee extends SimpleBee { private Compass compass; private Radio radio; private float maxVelocity = 2.0f; // m/s private float velocitySigma = 0.2f; // m/s private float headingSigma = (float)Math.PI / 16; // rad private long sensorTimeout = 1000; // ms private long radioTimeout = 1000; // ms private boolean useRadio = false; private static Logger logger = Logger.getLogger(InstrumentBee.class); @Override public void initialize() { super.initialize(); setHovering(true); compass = getSensor("compass", Compass.class); createTimer(new TimerCallback() { @Override public void fire(SimTime time) { compass.getHeading(); } }, 0, TimeUnit.SECONDS, sensorTimeout, TimeUnit.MILLISECONDS); radio = getRadio(); if (useRadio) { final byte[] packet = new byte[] {1, 2, 3, 4}; createTimer(new TimerCallback() { @Override public void fire(SimTime time) { radio.transmit(packet); } }, 0, TimeUnit.SECONDS, radioTimeout, TimeUnit.MILLISECONDS); } } @Override protected void updateKinematics(SimTime time) { // randomly vary the heading (rotation about the Z axis) turn((float)getRandom().nextGaussian() * headingSigma); // randomly vary the velocity in the X and Z directions Vector3f newVel = getDesiredLinearVelocity(); newVel.add(new Vector3f((float)getRandom().nextGaussian() * velocitySigma, 0, (float)getRandom().nextGaussian() * velocitySigma)); // cap the velocity if (newVel.length() > maxVelocity) { newVel.normalize(); newVel.scale(maxVelocity); } setDesiredLinearVelocity(newVel); // Vector3f pos = getTruthPosition(); // Vector3f vel = getTruthLinearVelocity(); // // logger.info("ID: " + getModelId() + " " + // "time: " + time.getImpreciseTime() + " " + // "pos: " + pos + " " + // "vel: " + vel + " "); } @Override public void finish() { } @Inject(optional = true) public final void setMaxVelocity(@Named(value = "max-vel") final float vel) { this.maxVelocity = vel; } @Inject(optional = true) public final void setVelocitySigma(@Named(value = "vel-sigma") final float sigma) { this.velocitySigma = sigma; } @Inject(optional = true) public final void setHeadingSigma(@Named(value = "heading-sigma") final float sigma) { this.headingSigma = sigma; } @Inject(optional = true) public final void setSensorTimeout(@Named(value = "sensor-timeout") final long timeout) { this.sensorTimeout = timeout; } @Inject(optional = true) public final void setUserRadio(@Named(value = "use-radio") final boolean use) { this.useRadio = use; } @Inject(optional = true) public final void setRadioTimeout(@Named(value = "radio-timeout") final long timeout) { this.radioTimeout = timeout; } }
33.875
93
0.676507
dc399a93a4f1d01f2c24f147738310e2801c0d44
4,723
/******************************************************************************* * Copyright 2019 Fabrizio Pastore, Leonardo Mariani * * 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 gui.sim; import gui.viewer.StateDrawer; import java.awt.Component; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Point; import javax.swing.Icon; import automata.Automaton; import automata.Configuration; /** * The <CODE>ConfigurationIcon</CODE> is a general sort of icon that * can be used to draw transitions. The <CODE>Icon</CODE> can then be * added as the part of any sort of object. * * @author Thomas Finley */ public abstract class ConfigurationIcon implements Icon { /** * Instantiates a new <CODE>ConfigurationIcon</CODE>. * @param configuration the configuration that is represented * @param automaton the automaton that this configuration "arose" * from */ public ConfigurationIcon(Configuration configuration) { this.configuration = configuration; this.automaton = configuration.getCurrentState().getAutomaton(); } /** * Returns the preferred width of the icon. Subclasses should * attempt to draw within these bounds, and can override if they'd * like a bit more space to play with. * @return the default preferred width is 150 pixels */ public int getIconWidth() { return 150; } /** * Returns the preferred height of the icon, which is just enought * to draw the state. */ public int getIconHeight() { return STATE_RADIUS * 2; } /** * Returns the <CODE>Configuration</CODE> drawn by this icon. * @return the <CODE>Configuration</CODE> drawn by this icon */ public Configuration getConfiguration() { return configuration; } /** * Paints the graphical representation of a configuration on this * icon * @param c the component this icon is drawn on * @param g the graphics object to draw to * @param x the start <CODE>x</CODE> coordinate to draw at * @param y the start <CODE>y</CODE> coordinate to draw at */ public void paintIcon(Component c, Graphics g, int x, int y) { Graphics2D g2 = (Graphics2D) g.create(); g2.translate(x,y); // Draws the state. paintConfiguration(c, g2, getIconWidth(), getIconHeight()); g2.translate(-x,-y); } /** * The general method for painting the rest of the configuration. * The subclasses should override to do whatever it is they do. * At this point the state has already been drawn. The areas * where the state has NOT already been drawn is defined by the * static variables <CODE>RIGHT_STATE</CODE> and * <CODE>BELOW_STATE</CODE>. By default this method paints the * state. * @param c the component this icon is drawn on * @param g the <CODE>Graphics2D</CODE> object to draw on * @param width the width to paint the configuration in * @param height the height to paint the configuration in */ public void paintConfiguration(Component c, Graphics2D g, int width, int height) { STATE_DRAWER.drawState(g, automaton, configuration.getCurrentState(), STATE_POINT); } /** The configuration that is being drawn. */ private Configuration configuration; /** The automaton that this configuration belongs to. */ private Automaton automaton; /** The radius of states drawn here. */ protected static final int STATE_RADIUS = 13; /** The state drawer. */ private static final StateDrawer STATE_DRAWER = new StateDrawer(STATE_RADIUS); /** The point where states are drawn. */ private static final Point STATE_POINT = new Point(STATE_RADIUS*2, STATE_RADIUS); /** For the reference of subclasses, the point on the upper left * of the region to the right of the state. */ protected static final Point RIGHT_STATE = new Point(STATE_RADIUS*3, 0); /** The point on the upper left of the region below the state. */ protected static final Point BELOW_STATE = new Point(0, STATE_RADIUS*2); }
35.246269
81
0.666102
d7c957f0521d63bf7e4ccce401b6f05066cafaac
5,028
/* * E: Ken@kenreid.co.uk * Written by Ken Reid */ package uk.co.kenreid.dataobjects; import java.util.HashMap; import java.util.Map; import uk.co.kenreid.evolutionaryruinandstochasticrecreate.Phase2EvolutionaryRuin.Operator; /** * The Class Context. */ public class Context { /** The cooling rate. */ private double coolingRate; /** The original temperature. */ private int originalTemperature; /** The problem. */ private final String problem = "1-7-3-4-6-7-3-2-1-4-7-6-Charlie-3-2-7-8-9-7-7-7-6-4-3-Tango-7-3-2-Victor-7-3-1-1-7-8-8-8-7-3-2-4-7-6-7-8-9-7-6-4-3-7-6"; /** The ruinp 1 rate. */ private double ruinp1Rate; /** The ruinp 2 rate. */ private double ruinp2Rate; /** The selection operator. */ private Operator selectionOperator; /** The selection rate. */ private double selectionRate; /** The stage one operator. */ private Operator stageOneOperator; /** The stage two operator. */ private Operator stageTwoOperator; /** The temperature. */ private double temperature; /** The weightings per constraint. */ private Map<String, Double> weightingsPerConstraint = new HashMap<>(); /** * Gets the cooling rate. * * @return the cooling rate */ public double getCoolingRate() { // TODO Auto-generated method stub return this.coolingRate; } /** * Gets the original temperature. * * @return the original temperature */ public int getOriginalTemperature() { return this.originalTemperature; } /** * Gets the problem. * * @return the problem */ public String getProblem() { return this.problem; } /** * Gets the ruinp 1 rate. * * @return the ruinp 1 rate */ public double getRuinp1Rate() { return this.ruinp1Rate; } /** * Gets the ruinp 2 rate. * * @return the ruinp 2 rate */ public double getRuinp2Rate() { return this.ruinp2Rate; } /** * Gets the selection operator. * * @return the selection operator */ public Operator getSelectionOperator() { return this.selectionOperator; } /** * Gets the selection rate. * * @return the selection rate */ public double getSelectionRate() { return this.selectionRate; } /** * Gets the stage one operator. * * @return the stage one operator */ public Operator getStageOneOperator() { return this.stageOneOperator; } /** * Gets the stage two operator. * * @return the stage two operator */ public Operator getStageTwoOperator() { return this.stageTwoOperator; } /** * Gets the temperature. * * @return the temperature */ public double getTemperature() { // TODO Auto-generated method stub return this.temperature; } /** * Gets the weightings per constraint. * * @return the weightings per constraint */ public Map<String, Double> getWeightingsPerConstraint() { return this.weightingsPerConstraint; } /** * Sets the cooling rate. * * @param coolingRate * the new cooling rate */ public void setCoolingRate(final double coolingRate) { this.coolingRate = coolingRate; } /** * Sets the original temperature. * * @param i * the new original temperature */ public void setOriginalTemperature(final int i) { this.setTemperature(i); this.originalTemperature = i; } /** * Sets the ruinp 1 rate. * * @param ruinp1Rate * the new ruinp 1 rate */ public void setRuinp1Rate(final double ruinp1Rate) { this.ruinp1Rate = ruinp1Rate; } /** * Sets the ruinp 2 rate. * * @param ruinp2Rate * the new ruinp 2 rate */ public void setRuinp2Rate(final double ruinp2Rate) { this.ruinp2Rate = ruinp2Rate; } /** * Sets the selection operator. * * @param selectionOperator * the new selection operator */ public void setSelectionOperator(final Operator selectionOperator) { this.selectionOperator = selectionOperator; } /** * Sets the selection rate. * * @param selectionRate * the new selection rate */ public void setSelectionRate(final double selectionRate) { this.selectionRate = selectionRate; } /** * Sets the stage one operator. * * @param stageOneOperator * the new stage one operator */ public void setStageOneOperator(final Operator stageOneOperator) { this.stageOneOperator = stageOneOperator; } /** * Sets the stage two operator. * * @param stageTwoOperator * the new stage two operator */ public void setStageTwoOperator(final Operator stageTwoOperator) { this.stageTwoOperator = stageTwoOperator; } /** * Sets the temperature. * * @param temperature * the new temperature */ public void setTemperature(final double temperature) { this.temperature = temperature; } /** * Sets the weightings per constraint. * * @param weightingsPerConstraint * the weightings per constraint */ public void setWeightingsPerConstraint(final Map<String, Double> weightingsPerConstraint) { this.weightingsPerConstraint = weightingsPerConstraint; } }
19.795276
153
0.67144
2268af00c8f607695c134903cbca4e2f1b6e61e7
431
package net.waterfallflower.cursedinterpolatorplugin.api.ui; import javax.swing.*; import java.awt.*; public class SmallButton extends JButton { public SmallButton() { super(); setPreferredSize(new Dimension(16, 16)); setBorderPainted(false); } @Override protected void paintComponent(Graphics g) { if(getIcon() != null) getIcon().paintIcon(this, g, 0, 0); } }
19.590909
60
0.635731
add7da794483807f2adcf264c026ee49f3e3881c
1,982
package com.fastdev.common.http; import android.content.Context; import com.bean.DataObject; import com.bean.LoginReq; import com.bean.LoginRes; import com.blankj.utilcode.util.LogUtils; import com.google.gson.Gson; import com.lzy.okgo.OkGo; import com.lzy.okgo.model.Response; import com.lzy.okrx2.adapter.ObservableResponse; import java.lang.reflect.Type; import io.reactivex.Observable; import io.reactivex.annotations.NonNull; import io.reactivex.functions.Function; /** * Created by lipy on 2017/9/26. */ public class Action<T extends DataObject> extends ActionService { /** * 登录 * * @param loginName * @param password * @param rememberMe * @return */ public Observable<LoginRes> login(String loginName, String password, boolean rememberMe, Type type, Context context) { return postRequest(context, Urls.LOGIN, type) .upJson(encrypt(new LoginReq(loginName, password, rememberMe))) .adapt(new ObservableResponse<ServerModel>()) .map(new Function<Response<ServerModel>, LoginRes>() { @Override public LoginRes apply(@NonNull Response<ServerModel> serverModelResponse) throws Exception { ServerModel body = serverModelResponse.body(); return (LoginRes) body.getData(); } }); } private static <REQ> String encrypt(REQ req) { String str = ""; try { Gson gson = new Gson(); str = gson.toJson(req); LogUtils.d("Param = " + str); // str = URLEncoder.encode(str.substring(0, str.length()), "UTF-8"); } catch (Exception e) { e.printStackTrace(); } return str; } public static void cancle() { OkGo.getInstance().cancelAll(); } public static void cancle(Object tag) { OkGo.getInstance().cancelTag(tag); } }
28.314286
122
0.612008
5a350ad769a34de0be1b652b825bb36056f82c18
4,834
/*- * #%L * OfficeFrame * %% * Copyright (C) 2005 - 2020 Daniel Sagenschneider * %% * 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% */ package net.officefloor.frame.api.managedobject.source; import java.util.concurrent.ThreadFactory; import java.util.logging.Logger; import net.officefloor.frame.api.executive.ExecutionStrategy; import net.officefloor.frame.api.function.FlowCallback; import net.officefloor.frame.api.function.ManagedFunction; import net.officefloor.frame.api.managedobject.AsynchronousContext; import net.officefloor.frame.api.managedobject.ManagedObject; import net.officefloor.frame.internal.structure.Flow; import net.officefloor.frame.internal.structure.ManagedObjectContainer; import net.officefloor.frame.internal.structure.ProcessState; /** * <p> * Context that the {@link ManagedObject} is to execute within. * <p> * In invoking processes the following should be taken into account: * <ol> * <li>The {@link Flow} (process) will be instigated in a new * {@link ProcessState} which for example will cause new {@link ManagedObject} * dependencies to be instantiated.</li> * <li>The {@link ManagedObject} passed to the invocation will go through a full * life-cycle so be careful passing in an existing initialised * {@link ManagedObject}. For example the {@link AsynchronousContext} instance * will be overwritten which will likely cause live-lock as the * {@link AsynchronousContext#complete(net.officefloor.frame.api.managedobject.AsynchronousOperation)} * will notify on the wrong {@link ManagedObjectContainer}.</li> * </ol> * * @author Daniel Sagenschneider */ public interface ManagedObjectExecuteContext<F extends Enum<F>> { /** * Obtains the {@link Logger}. * * @return {@link Logger}. */ Logger getLogger(); /** * Obtains an {@link ExecutionStrategy}. * * @param executionStrategyIndex Index of the {@link ExecutionStrategy}. * @return {@link ThreadFactory} instances for the {@link ExecutionStrategy}. */ ThreadFactory[] getExecutionStrategy(int executionStrategyIndex); /** * Invokes a start up {@link Flow}. * * @param key Key identifying the {@link Flow} to instigate. * @param parameter Parameter to first {@link ManagedFunction} of the * {@link Flow}. * @param managedObject {@link ManagedObject} for the {@link ProcessState} of * the {@link Flow}. * @param callback {@link FlowCallback} on completion of the {@link Flow}. * @return {@link ManagedObjectStartupProcess}. * @throws IllegalArgumentException If * <ul> * <li>unknown {@link Flow} key</li> * <li>parameter is incorrect type</li> * <li>no {@link ManagedObject} is * supplied</li> * </ul> */ ManagedObjectStartupProcess invokeStartupProcess(F key, Object parameter, ManagedObject managedObject, FlowCallback callback) throws IllegalArgumentException; /** * Invokes a start up {@link Flow}. * * @param flowIndex Index identifying the {@link Flow} to instigate. * @param parameter Parameter to first {@link ManagedFunction} of the * {@link Flow}. * @param managedObject {@link ManagedObject} for the {@link ProcessState} of * the {@link Flow}. * @param callback {@link FlowCallback} on completion of the {@link Flow}. * @return {@link ManagedObjectStartupProcess}. * @throws IllegalArgumentException If * <ul> * <li>unknown {@link Flow} key</li> * <li>parameter is incorrect type</li> * <li>no {@link ManagedObject} is * supplied</li> * </ul> */ ManagedObjectStartupProcess invokeStartupProcess(int flowIndex, Object parameter, ManagedObject managedObject, FlowCallback callback) throws IllegalArgumentException; /** * Adds a {@link ManagedObjectService}. * * @param service {@link ManagedObjectService}. */ void addService(ManagedObjectService<F> service); }
39.950413
111
0.655772
864b4426ccb0ffbfb3ff60a4281dbb1433bdad37
1,903
/* * Copyright 2017 Axway Software * * 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.axway.ats.agent.core.model; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import com.axway.ats.core.validation.ValidationType; /** * * This annotation is used for getting the name of * the annotated parameter for the action. * Parameter name information is not available at * run time, that's why we need this annotation for * every parameter of the action method. Thus the client * can query the server and get the parameter types and * names for a specific action */ @Retention( RetentionPolicy.RUNTIME) @Target( ElementType.PARAMETER) public @interface Parameter { /** * The name of the parameter - should be the same * as the actual parameter name */ public String name(); /** The {@link ValidationType} of the parameter, by * default no validation will be performed */ public ValidationType validation() default ValidationType.NONE; /** The array of {@link String} arguments to be used while validating * This is used by only a few of the validation types, see javadoc * of the validation package */ public String[] args() default {}; }
33.982143
76
0.707304
1a61b75e0751197ae4abac3e61760099e525dd41
5,725
/* * 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. * */ package org.selenium.runner.services; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.util.HashMap; import java.util.Map; import net.sf.cglib.reflect.FastClass; import net.sf.cglib.reflect.FastMethod; import org.apache.commons.lang3.text.StrBuilder; import org.selenium.runner.exceptions.SeleniumRunnerException; import org.selenium.runner.model.Instruction; import org.selenium.runner.model.SeleniumActionType; import org.selenium.runner.model.SeleniumParameters; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.thoughtworks.selenium.Selenium; import com.thoughtworks.selenium.webdriven.WebDriverBackedSelenium; /** * SeleniumRunner * * @author pguillerm * @since 16 févr. 2015 */ @SuppressWarnings("deprecation") public class SeleniumRunner { // ========================================================================= // ATTRIBUTES // ========================================================================= private static final Logger LOGGER = LoggerFactory.getLogger(SeleniumRunner.class); private final SeleniumParameters parameters; private final Map<String, String> storedValues = new HashMap<String, String>(); private SeleniumWrapper seleniumWrapper; private FastClass seleniumFastClass = null; private Map<SeleniumActionType, FastMethod> CACH_FAST_METHOD = new HashMap<SeleniumActionType, FastMethod>(); // ========================================================================= // CONSTRUCTORS // ========================================================================= public SeleniumRunner(final WebDriverBackedSelenium selenium, final SeleniumParameters parameters) { super(); this.parameters = parameters; seleniumFastClass = FastClass.create(WebDriverBackedSelenium.class); initilizeFastMethod(); seleniumWrapper = new SeleniumWrapper(selenium, parameters); } private void initilizeFastMethod() { final Method[] methods = WebDriverBackedSelenium.class.getMethods(); for (SeleniumActionType actionType : SeleniumActionType.values()) { FastMethod fast = seleniumFastClass.getMethod(findMethod(methods, actionType.name())); } } private Method findMethod(final Method[] methods, final String name) { Method result = null; for (Method method : methods) { if (method.getName().equals(name)) { result = method; break; } } return result; } // ========================================================================= // METHODS // ========================================================================= public void run(final Instruction instruction) throws SeleniumRunnerException { if (instruction == null) { throw new SeleniumRunnerException("instruction is null"); } if (seleniumWrapper == null) { throw new SeleniumRunnerException("selenium must be initialized!"); } LOGGER.info(instruction.toString()); if (instruction.getValue() == null) { instruction.setValue(""); } else if (instruction.getValue().indexOf('$') != -1) { instruction.setValue(injectValue(instruction.getValue())); } if (instruction.getTarget().indexOf('$') != -1) { instruction.setTarget(injectValue(instruction.getTarget())); } runMethod(instruction); } // ========================================================================= // PROTECTED // ========================================================================= protected String injectValue(final String instruction) throws SeleniumRunnerException { if (instruction == null) { throw new SeleniumRunnerException("can't inject value in null instruction !"); } StrBuilder result = new StrBuilder(instruction); String keyPattern = null; for (String key : storedValues.keySet()) { keyPattern = "${" + key + "}"; if (result.contains(keyPattern)) { result.replaceAll(keyPattern, storedValues.get(key)); } } return result.toString(); } /** * Run method. * * @param instruction the instruction * @param selenium the selenium * @param parameters the parameters * @param seleniumWrapper the selenium wrapper * @throws ClientException the client exception */ protected void runMethod(final Instruction instruction) throws SeleniumRunnerException { if (instruction != null) { FastMethod method = CACH_FAST_METHOD.get(instruction.getType()); } } }
35.339506
114
0.590568
c955d571146a47549278d5aa23d338ba58ff53b5
13,393
package com.mashibing.activiti.l_case; import com.mashibing.activiti.ApplicationTests; import lombok.extern.slf4j.Slf4j; import org.activiti.bpmn.model.*; import org.activiti.engine.*; import org.activiti.engine.history.HistoricActivityInstance; import org.activiti.engine.history.HistoricProcessInstance; import org.activiti.engine.history.HistoricTaskInstance; import org.activiti.engine.impl.identity.Authentication; import org.activiti.engine.impl.persistence.entity.ProcessDefinitionEntity; import org.activiti.engine.repository.Deployment; import org.activiti.engine.runtime.Execution; import org.activiti.engine.runtime.ProcessInstance; import org.activiti.engine.task.Attachment; import org.activiti.engine.task.Comment; import org.activiti.engine.task.Task; import org.activiti.image.ProcessDiagramGenerator; import org.activiti.image.impl.DefaultProcessDiagramGenerator; import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; import org.junit.jupiter.api.Test; import org.springframework.util.CollectionUtils; import org.springframework.util.FileCopyUtils; import javax.annotation.Resource; import java.io.*; import java.util.*; /** * <p></p> * * @author 孙志强 * @date 2020-07-27 22:33 */ @Slf4j public class LeaveTest extends ApplicationTests { @Resource private RepositoryService repositoryService; @Resource private RuntimeService runtimeService; @Resource private TaskService taskService; @Resource private HistoryService historyService; @Resource private ProcessEngineConfiguration processEngineConfiguration; private final String bpmnNameAndKey = "leave"; /* 第一步:需求下来的时候,跟产品,跟业务,跟客户,一起确定的,研发绘制流程图?找客户,产品确认(需求确认) */ @Test public void deployment() { Deployment deployment = repositoryService.createDeployment().name("请假流程") .addClasspathResource("processes/" + bpmnNameAndKey + ".bpmn") .addClasspathResource("processes/" + bpmnNameAndKey + ".png") .category("HR") .deploy(); System.out.println("部署ID\t" + deployment.getId()); System.out.println("部署分类\t" + deployment.getCategory()); System.out.println("部署名称\t" + deployment.getName()); } /* 第二步:启动流程:谁启动,发起人发起, 公司任何一个员工都可以*/ @Test public void start() { Map<String, Object> variables = new HashMap<>(); /* 发起人,来源于账号系统 */ variables.put("inputUser", "张三"); String bussnessKey = "leave-1"; ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(bpmnNameAndKey, bussnessKey, variables); System.out.println("流程实例ID\t" + processInstance.getId()); System.out.println("流程定义ID\t" + processInstance.getProcessDefinitionId()); System.out.println("流程定义KEY\t" + processInstance.getProcessDefinitionKey()); } /* 第三步 :代办列表中有自己的待办任务。消息通知(短信,邮件,企业erp系统)*/ @Test public void findMyTask() { String assignee = "李四"; List<Task> taskList = taskService.createTaskQuery() .taskAssignee(assignee) .list(); for (Task task : taskList) { System.out.println("任务ID\t" + task.getId()); System.out.println("任务名称\t" + task.getName()); System.out.println("流程定义ID\t" + task.getProcessDefinitionId()); System.out.println("流程实例ID\t" + task.getProcessInstanceId()); System.out.println("执行对象ID\t" + task.getExecutionId()); System.out.println("任务创办时间\t" + task.getCreateTime()); String businessKey = runtimeService.createProcessInstanceQuery() .processInstanceId(task.getProcessInstanceId()) .singleResult() .getBusinessKey(); /* 跟据businessKey查询自己业务系统表,查询出来请假单 */ /* 返回来的是根据列表但详情 */ // leave = leaveService.queryLeave(businessKey) System.out.println("======="); } } /* 第五步: 获取流程连线上面的变量-为了页面显示,为了页面传值,为了后台完成任务的时候,动态指定下一个任务节点 */ @Test public void findOutLine() { String taskId = "7507"; Task task = taskService.createTaskQuery().taskId(taskId).singleResult(); String processDefinitionId = task.getProcessDefinitionId(); //获取bpmnModel对象 BpmnModel bpmnModel = repositoryService.getBpmnModel(processDefinitionId); FlowElement flowElement = bpmnModel.getFlowElement(task.getTaskDefinitionKey()); if (flowElement instanceof UserTask) { UserTask userTask = (UserTask) flowElement; System.out.println(userTask.getId()); //获取连线信息 List<SequenceFlow> incomingFlows = userTask.getOutgoingFlows(); for (SequenceFlow sequenceFlow : incomingFlows) { if (sequenceFlow.getConditionExpression() != null) { System.out.println("连线名称\t" + sequenceFlow.getName()); System.out.println("连线表达式\t" + sequenceFlow.getConditionExpression()); System.out.println("连线下一任务节点\t" + sequenceFlow.getTargetRef()); } } } /**/ GraphicInfo graphicInfo = bpmnModel.getGraphicInfo(flowElement.getId()); System.out.println("graphicInfo.getX() = " + graphicInfo.getX()); System.out.println("graphicInfo.getY() = " + graphicInfo.getY()); System.out.println("graphicInfo.getHeight() = " + graphicInfo.getHeight()); System.out.println("graphicInfo.getWidth() = " + graphicInfo.getWidth()); } /* 第四步:完成任务-指定下一个任务的办理人,添加评审意见--添加附件 */ @Test public void compleTask() { String taskId = "2506"; Map<String, Object> variables = new HashMap<>(); /* 批准是页面用户操作按钮动态传递过来的,用来动态完成任务。 */ variables.put("outcome", "批准"); /* 指定下一个节点的办理人--办理人,通常都是自己的直属领导--此处,就要查询ERP系统,根据当前办理人查询 */ variables.put("inputUser", "王五"); Task task = taskService.createTaskQuery().taskId(taskId).singleResult(); taskService.addComment(taskId, task.getProcessInstanceId(), "部门经理同意"); taskService.createAttachment("test", taskId, task.getProcessInstanceId(), "attachment name", "description", new ByteArrayInputStream("附件".getBytes())); taskService.complete(taskId,variables); } /* 获取评论意见 */ @Test public void getComment() { String taskId = "5002"; List<Comment> taskComments = taskService.getTaskComments(taskId); taskComments.forEach((taskComment)->{ System.out.println(taskComment.getFullMessage()); }); System.out.println("*****************"); String processInstanceId = "2501"; List<Comment> processInstanceComments = taskService.getProcessInstanceComments(processInstanceId); processInstanceComments.forEach(item->{ HistoricTaskInstance historicTaskInstance = historyService.createHistoricTaskInstanceQuery() .taskId(item.getTaskId()) .singleResult(); System.out.println(historicTaskInstance.getAssignee() + "\t" + historicTaskInstance.getName() + "\t" + item.getFullMessage()); }); } /* 获取附件信息 */ @Test public void getAttchment(){ String taskId = "5002"; List<Attachment> taskAttachments = taskService.getTaskAttachments(taskId); taskAttachments.forEach((attachment)->{ System.out.println(attachment.getName()); InputStream inputStream = taskService.getAttachmentContent(attachment.getId()); StringWriter writer = new StringWriter(); try { IOUtils.copy(inputStream, writer); System.out.println(writer.toString()); } catch (IOException e) { e.printStackTrace(); } }); System.out.println("*****************"); String processInstanceId = "2501"; List<Attachment> processInstanceAttachments = taskService.getProcessInstanceAttachments(processInstanceId); taskAttachments.forEach((attachment)->{ System.out.println(attachment.getName()); InputStream inputStream = taskService.getAttachmentContent(attachment.getId()); StringWriter writer = new StringWriter(); try { IOUtils.copy(inputStream, writer); System.out.println(writer.toString()); } catch (IOException e) { e.printStackTrace(); } }); } /* 获取当前执行节点的流程图 */ @Test public void getDiagram() throws Exception { String processInstanceId = "2501"; //获得流程实例 ProcessInstance processInstance = runtimeService.createProcessInstanceQuery() .processInstanceId(processInstanceId).singleResult(); String processDefinitionId = StringUtils.EMPTY; if (processInstance == null) { //查询已经结束的流程实例 HistoricProcessInstance processInstanceHistory = historyService.createHistoricProcessInstanceQuery() .processInstanceId(processInstanceId).singleResult(); if (processInstanceHistory != null){ processDefinitionId = processInstanceHistory.getProcessDefinitionId(); } } else { processDefinitionId = processInstance.getProcessDefinitionId(); } //获取BPMN模型对象 BpmnModel model = repositoryService.getBpmnModel(processDefinitionId); //获取流程实例当前的节点,需要高亮显示 List<String> currentActs = Collections.EMPTY_LIST; if (processInstance != null) currentActs = runtimeService.getActiveActivityIds(processInstance.getId()); InputStream inputStream = processEngineConfiguration .getProcessDiagramGenerator() .generateDiagram(model, "png", currentActs, new ArrayList<String>(), "宋体", "微软雅黑", "黑体", null, 2.0); FileUtils.copyInputStreamToFile(inputStream, new File("D://bbb.png")); } /* 撤回到第一个流程节点 ? 能不能动态跳转到任意节点?能-----*/ @Test public void revoke() { String bussnessKey = "leave-1"; Task task = taskService.createTaskQuery().processInstanceBusinessKey(bussnessKey).singleResult(); if(task==null) { System.out.println("流程未启动或已执行完成,无法撤回"); } String userName = "张三"; List<HistoricTaskInstance> htiList = historyService.createHistoricTaskInstanceQuery() .processInstanceBusinessKey(bussnessKey) .orderByTaskCreateTime() .asc() .list(); String myTaskId = null; HistoricTaskInstance myTask = null; /* 循环历史流程节点,找到第一个流程 */ for(HistoricTaskInstance hti : htiList) { /* 能扩展吧 */ if(userName.equals(hti.getAssignee())) { myTaskId = hti.getId(); myTask = hti; break; } } if(null==myTaskId) { System.out.println("该任务非当前用户提交,无法撤回"); } String processDefinitionId = myTask.getProcessDefinitionId(); BpmnModel bpmnModel = repositoryService.getBpmnModel(processDefinitionId); String myActivityId = null; List<HistoricActivityInstance> haiList = historyService.createHistoricActivityInstanceQuery() .executionId(myTask.getExecutionId()).finished().list(); for(HistoricActivityInstance hai : haiList) { if(myTaskId.equals(hai.getTaskId())) { myActivityId = hai.getActivityId(); break; } } FlowNode myFlowNode = (FlowNode) bpmnModel.getMainProcess().getFlowElement(myActivityId); Execution execution = runtimeService.createExecutionQuery().executionId(task.getExecutionId()).singleResult(); String activityId = execution.getActivityId(); System.out.println("------->> activityId:" + activityId); FlowNode flowNode = (FlowNode) bpmnModel.getMainProcess().getFlowElement(activityId); //记录原活动方向 List<SequenceFlow> oriSequenceFlows = new ArrayList<>(); oriSequenceFlows.addAll(flowNode.getOutgoingFlows()); //清理活动方向 flowNode.getOutgoingFlows().clear(); //建立新方向 List<SequenceFlow> newSequenceFlowList = new ArrayList<>(); SequenceFlow newSequenceFlow = new SequenceFlow(); newSequenceFlow.setId("newSequenceFlowId"); newSequenceFlow.setSourceFlowElement(flowNode); newSequenceFlow.setTargetFlowElement(myFlowNode); newSequenceFlowList.add(newSequenceFlow); flowNode.setOutgoingFlows(newSequenceFlowList); taskService.addComment(task.getId(), task.getProcessInstanceId(), "撤回"); Map<String,Object> currentVariables = new HashMap<>(); currentVariables.put("inputUser", userName); //完成任务 taskService.complete(task.getId(),currentVariables); task = taskService.createTaskQuery().processInstanceBusinessKey(bussnessKey).singleResult(); taskService.setAssignee(task.getId(), userName); //恢复原方向 flowNode.setOutgoingFlows(oriSequenceFlows); } @Test public void delete(){ String processInstanceId = "2501"; runtimeService.deleteProcessInstance(processInstanceId, "测试删除"); } }
41.722741
159
0.643545
e1cae44a432f393366cec620f05c6d249f23ea63
403
package com.sap.mlt.xliff12.impl.attribute; import com.sap.mlt.xliff12.api.attribute.MaxBytes; import com.sap.mlt.xliff12.impl.base.XliffAttributeImpl; import com.sap.mlt.xliff12.impl.util.Assert; public class MaxBytesImpl extends XliffAttributeImpl implements MaxBytes { public MaxBytesImpl(String maxBytes) { super(NAME, maxBytes); Assert.isNmtoken(maxBytes, "maxBytes"); } }
26.866667
75
0.764268
b8ec28473a5ef5f4ee17a0ff90d796b2a1741d0c
2,528
package com.java110.dto.activitiesRule; import com.java110.dto.PageDto; import java.io.Serializable; import java.util.Date; /** * @ClassName FloorDto * @Description 活动规则数据层封装 * @Author wuxw * @Date 2019/4/24 8:52 * @Version 1.0 * add by wuxw 2019/4/24 **/ public class ActivitiesRuleDto extends PageDto implements Serializable { private String ruleType; private String objId; private String[] objIds; private String ruleName; private String activitiesObj; private String startTime; private String remark; private String endTime; private String ruleId; private String objType; private Date createTime; private String statusCd = "0"; public String getRuleType() { return ruleType; } public void setRuleType(String ruleType) { this.ruleType = ruleType; } public String getObjId() { return objId; } public void setObjId(String objId) { this.objId = objId; } public String getRuleName() { return ruleName; } public void setRuleName(String ruleName) { this.ruleName = ruleName; } public String getActivitiesObj() { return activitiesObj; } public void setActivitiesObj(String activitiesObj) { this.activitiesObj = activitiesObj; } public String getStartTime() { return startTime; } public void setStartTime(String startTime) { this.startTime = startTime; } public String getRemark() { return remark; } public void setRemark(String remark) { this.remark = remark; } public String getEndTime() { return endTime; } public void setEndTime(String endTime) { this.endTime = endTime; } public String getRuleId() { return ruleId; } public void setRuleId(String ruleId) { this.ruleId = ruleId; } public String getObjType() { return objType; } public void setObjType(String objType) { this.objType = objType; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public String getStatusCd() { return statusCd; } public void setStatusCd(String statusCd) { this.statusCd = statusCd; } public String[] getObjIds() { return objIds; } public void setObjIds(String[] objIds) { this.objIds = objIds; } }
19.151515
72
0.625791
2f1a2b86f6cfc3b7ed7099cbf110ab7074a1261e
2,280
import java.util.TimeZone; import net.runelite.mapping.Export; import net.runelite.mapping.Implements; import net.runelite.mapping.ObfuscatedGetter; import net.runelite.mapping.ObfuscatedName; import net.runelite.mapping.ObfuscatedSignature; @ObfuscatedName("jf") @Implements("Calendar") public class Calendar { @ObfuscatedName("c") @Export("MONTH_NAMES_ENGLISH_GERMAN") static final String[][] MONTH_NAMES_ENGLISH_GERMAN; @ObfuscatedName("b") @Export("DAYS_OF_THE_WEEK") static final String[] DAYS_OF_THE_WEEK; @ObfuscatedName("p") @Export("Calendar_calendar") static java.util.Calendar Calendar_calendar; @ObfuscatedName("ne") @ObfuscatedGetter( intValue = -1622402519 ) @Export("selectedItemSlot") static int selectedItemSlot; static { MONTH_NAMES_ENGLISH_GERMAN = new String[][]{{"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"}, {"Jan", "Feb", "Mär", "Apr", "Mai", "Jun", "Jul", "Aug", "Sep", "Okt", "Nov", "Dez"}, {"jan", "fév", "mars", "avr", "mai", "juin", "juil", "août", "sept", "oct", "nov", "déc"}, {"jan", "fev", "mar", "abr", "mai", "jun", "jul", "ago", "set", "out", "nov", "dez"}, {"jan", "feb", "mrt", "apr", "mei", "jun", "jul", "aug", "sep", "okt", "nov", "dec"}, {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"}, {"ene", "feb", "mar", "abr", "may", "jun", "jul", "ago", "sep", "oct", "nov", "dic"}}; DAYS_OF_THE_WEEK = new String[]{"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"}; java.util.Calendar.getInstance(); Calendar_calendar = java.util.Calendar.getInstance(TimeZone.getTimeZone("GMT")); } @ObfuscatedName("c") @ObfuscatedSignature( descriptor = "(IIIIIII)I", garbageValue = "880813540" ) public static int method5320(int var0, int var1, int var2, int var3, int var4, int var5) { if ((var5 & 1) == 1) { int var6 = var3; var3 = var4; var4 = var6; } var2 &= 3; if (var2 == 0) { return var1; } else if (var2 == 1) { return 7 - var0 - (var3 - 1); } else { return var2 == 2 ? 7 - var1 - (var4 - 1) : var0; } } @ObfuscatedName("aj") @ObfuscatedSignature( descriptor = "(IB)I", garbageValue = "1" ) static int method5323(int var0) { return (int)Math.pow(2.0D, (double)(7.0F + (float)var0 / 256.0F)); } }
35.076923
653
0.619737
357ef02b2fc64b6e7648fbdba8040c1bef6ca7a1
3,680
package com.rmkrings.loader; import android.annotation.SuppressLint; import com.rmkrings.data.staff.StaffDictionary; import com.rmkrings.helper.AppDefaults; import com.rmkrings.helper.Cache; import com.rmkrings.helper.Config; import com.rmkrings.http.HttpResponseData; import com.rmkrings.interfaces.HttpResponseCallback; import org.json.JSONException; import org.json.JSONObject; import java.net.MalformedURLException; import java.net.URL; import java.util.logging.Logger; /** * Load staff data from backend and store in cache. No further processing * is initiated as cache is intended to be updated on app start only. * Whenever staff dictionary is needed loadFromCache() method must be * called. */ public class StaffLoader extends HttpGet implements HttpResponseCallback { private final String cacheFileName = Config.cacheFilename("staff"); private final String digestFileName = Config.digestFilename(("staff")); private final Cache cache = new Cache(); private final static Logger logger = Logger.getLogger(CalendarLoader.class.getName()); @Override protected URL getURL(String digest) throws MalformedURLException { String urlString = String.format("%s/v2/staff", AppDefaults.getBaseUrl()); if (digest != null) { urlString += String.format("?digest=%s", digest); } return new URL(urlString); } public void load() { String digest = null; if (cache.fileExists(digestFileName)) { digest = cache.read(digestFileName); } super.load(this, digest); } /** * Process backend response for staff load request. On success if staff dictionary has changed * this method simply updated local staff cache. No parsing or any other king of processing * is made. This method implements HttpResponseCallback interface. * @param responseData Backend response data with HTTP status code information and data. */ @SuppressLint("DefaultLocale") @Override public void execute(HttpResponseData responseData) { String data; String digest; JSONObject jsonData; if (responseData.getHttpStatusCode() != null && responseData.getHttpStatusCode() != 200 && responseData.getHttpStatusCode() != 304) { logger.severe(String.format("Failed to load data for Staff dictionary. HTTP Status code %d.", responseData.getHttpStatusCode())); return; } data = responseData.getData(); if (data != null) { // When data has changed we need the new digest as it must be updated. try { jsonData = new JSONObject(data); digest = jsonData.getString("_digest"); cache.store(cacheFileName, data); cache.store(digestFileName, digest); } catch(JSONException e) { // Basically there is not much we can do here. Showing an error is not of much // help for the user. e.printStackTrace(); } } } /** * Load staff dictionary from cache. * @return Returns current staff dictionary. This dictionary might be empty. */ public StaffDictionary loadFromCache() { if (!cache.fileExists(cacheFileName)) { return new StaffDictionary(); } String data = cache.read(cacheFileName); if (data == null) { return new StaffDictionary(); } try { return new StaffDictionary(data); } catch (JSONException e) { e.printStackTrace(); return new StaffDictionary(); } } }
34.074074
141
0.650543
8df2c00538a566d8b5efede6ed049778d71dc07f
2,085
package com.cip.crane.restlet.resource.impl; import java.util.ArrayList; import java.util.List; import com.cip.crane.generated.module.PoolExample; import com.cip.crane.restlet.resource.IPoolsResource; import com.cip.crane.restlet.shared.PoolDTO; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.restlet.data.Status; import org.restlet.resource.ServerResource; import org.springframework.beans.factory.annotation.Autowired; import com.cip.crane.generated.mapper.PoolMapper; import com.cip.crane.generated.module.Pool; import com.mysql.jdbc.StringUtils; /** * Resource url : http://xxx.xxx/api/pool * * @author damon.zhu */ public class PoolsResource extends ServerResource implements IPoolsResource { private static final Log LOG = LogFactory.getLog(PoolsResource.class); @Autowired private PoolMapper poolMapper; @Override public ArrayList<PoolDTO> retrieve() { ArrayList<PoolDTO> pools = new ArrayList<PoolDTO>(); PoolExample example = new PoolExample(); example.or(); List<Pool> bPools = poolMapper.selectByExample(example); for (Pool p : bPools) { PoolDTO dto = new PoolDTO(p.getId(),p.getName(),p.getCreator()); pools.add(dto); } return pools; } @Override public void create(PoolDTO t) { if (t != null && !StringUtils.isNullOrEmpty(t.getName())) { try { Pool pool = new Pool(); pool.setName(t.getName()); if(StringUtils.isNullOrEmpty(t.getCreator())){ pool.setCreator("unknown"); }else{ pool.setCreator(t.getCreator()); } poolMapper.insertSelective(pool); setStatus(Status.SUCCESS_CREATED); } catch (Exception e) { setStatus(Status.CLIENT_ERROR_BAD_REQUEST); LOG.info(e.getMessage(), e); } } else { setStatus(Status.CLIENT_ERROR_BAD_REQUEST); } } }
31.590909
77
0.634053
541aa42f9ef153cb48a5b803cef588dca2e248a8
3,071
/* * Copyright (c) 2012-2014 Arne Schwabe * Distributed under the GNU GPL v2. For full terms see the file doc/LICENSE.txt */ package de.blinkt.openvpn.fragments; import android.app.Fragment; import android.os.Build; import android.os.Bundle; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.StaggeredGridLayoutManager; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import de.blinkt.openvpn.R; public class FaqFragment extends Fragment { private static int[] faqitems[] = { {R.string.faq_howto_title, R.string.faq_howto}, {R.string.faq_vpndialog43_title, R.string.faq_vpndialog43}, {R.string.faq_system_dialogs_title, R.string.faq_system_dialogs}, {R.string.faq_duplicate_notification_title, R.string.faq_duplicate_notification}, {R.string.battery_consumption_title, R.string.baterry_consumption}, {R.string.tap_mode, R.string.faq_tap_mode}, {R.string.vpn_tethering_title, R.string.faq_tethering}, {R.string.faq_security_title, R.string.faq_security}, {R.string.broken_images, R.string.broken_images_faq}, {R.string.faq_shortcut, R.string.faq_howto_shortcut}, {R.string.tap_mode, R.string.tap_faq2}, {R.string.copying_log_entries, R.string.faq_copying}, {R.string.tap_mode, R.string.tap_faq3}, {R.string.faq_routing_title, R.string.faq_routing} }; private RecyclerView mRecyclerView; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v= inflater.inflate(R.layout.faq, container, false); int dpwidth = (int) (container.getWidth()/getResources().getDisplayMetrics().density); int columns = dpwidth/400; columns = Math.max(1, columns); mRecyclerView = (RecyclerView) v.findViewById(R.id.faq_recycler_view); // use this setting to improve performance if you know that changes // in content do not change the layout size of the RecyclerView mRecyclerView.setHasFixedSize(true); mRecyclerView.setLayoutManager(new StaggeredGridLayoutManager(columns, StaggeredGridLayoutManager.VERTICAL)); mRecyclerView.setAdapter(new FaqViewAdapter(getActivity(), getFAQEntries())); return v; } /* I think the problem mentioned in there should not affect, 4.3+ */ private int[][] getFAQEntries() { if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) { int[][] newFaqItems = new int[faqitems.length - 1][2]; int j=0; for (int i = 0;i < faqitems.length;i++) { if (faqitems[i][0] != R.string.broken_images) { newFaqItems[j] = faqitems[i]; j++; } } return newFaqItems; } else { return faqitems; } } }
37
117
0.649626
d4f9cebe10b84b16bea995dee9932ff32df28b64
1,157
package cn.net.health.user.jvm; /** * @author xiyou * @version 1.2 * @date 2020/1/13 10:19 */ import org.openjdk.jmh.annotations.Benchmark; /** * @author buhao * @version StringConnectBenchmark.java, v 0.1 2018-12-25 09:29 buhao */ public class StringConnectBenchmark2 { /** * 字符串拼接之 StringBuilder 基准测试 */ @Benchmark public void testStringBuilder() { print(new StringBuilder().append(1).append(2).append(3).toString()); } /** * 字符串拼接之直接相加基准测试 */ @Benchmark public void testStringAdd() { print(new String() + 1 + 2 + 3); } /** * 字符串拼接之String Concat基准测试 */ @Benchmark public void testStringConcat() { print(new String().concat("1").concat("2").concat("3")); } /** * 字符串拼接之 StringBuffer 基准测试 */ @Benchmark public void testStringBuffer() { print(new StringBuffer().append(1).append(2).append(3).toString()); } /** * 字符串拼接之 StringFormat 基准测试 */ @Benchmark public void testStringFormat() { print(String.format("%s%s%s", 1, 2, 3)); } public void print(String str) { } }
19.283333
76
0.579948
dc99b7008c0f4625f3cd36ed76dc21b8fd21917c
83
/** * */ /** * @author smilesnake * */ package github.com.smilesnake.builder;
10.375
38
0.590361
1df9933d4d38aec11f4bb82659c4e3c55531a022
218
package cn.bugstack.design; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; public class Singleton_00 { public static Map<String, String> cache = new ConcurrentHashMap<String, String>(); }
19.818182
86
0.770642
b0e0948493654cd6faf5f308a056853883c73055
2,218
package ua.com.fielden.platform.expression.lexer; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import org.junit.Test; import ua.com.fielden.platform.expression.automata.NoTransitionAvailable; import ua.com.fielden.platform.expression.automata.SequenceRecognitionFailed; import ua.com.fielden.platform.expression.lexer.integer.IntegerTokenAutomata; public class IntegerTokenAutomataTest { private IntegerTokenAutomata automata = new IntegerTokenAutomata(); @Test public void test_full_recognition_of_correct_sequences() throws NoTransitionAvailable, SequenceRecognitionFailed { assertEquals("Incorrect recognition result", "023689", automata.recognisePartiallyFromStart("023689", 0)); assertEquals("Incorrect recognition result", "896", automata.recognisePartiallyFromStart(" 896 ", 0)); assertEquals("Incorrect recognition result", "96003", automata.recognisePartiallyFromStart("\t\n96003\t", 0)); } @Test public void test_recognition_of_partially_correct_sequences() throws NoTransitionAvailable, SequenceRecognitionFailed { assertEquals("Incorrect recognition result", "123", automata.recognisePartiallyFromStart("123 property1.subProperty1+", 0)); assertEquals("Incorrect recognition result", "456", automata.recognisePartiallyFromStart(" 456 + property", 0)); assertEquals("Incorrect recognition result", "456", automata.recognisePartiallyFromStart(" 456 98", 0)); assertEquals("Incorrect recognition result", "456", automata.recognisePartiallyFromStart(" 456.", 0)); } @Test public void test_recognition_of_incorrect_sequences() { try { automata.recognisePartiallyFromStart("", 0); fail("Should have failed"); } catch (final SequenceRecognitionFailed e) { } try { automata.recognisePartiallyFromStart("+12346", 0); fail("Should have failed"); } catch (final SequenceRecognitionFailed e) { } try { automata.recognisePartiallyFromStart("bn12", 0); fail("Should have failed"); } catch (final SequenceRecognitionFailed e) { } } }
44.36
132
0.719116
61345b1d457d98504bb60aba730ae0d2cde72d82
8,776
/** * Copyright (C) 2013-2020 Vasilis Vryniotis <bbriniotis@datumbox.com> * * 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.datumbox.framework.core.machinelearning.featureselection; import com.datumbox.framework.common.Configuration; import com.datumbox.framework.common.concurrency.StreamMethods; import com.datumbox.framework.core.common.dataobjects.Dataframe; import com.datumbox.framework.core.common.dataobjects.Record; import com.datumbox.framework.common.dataobjects.TypeInference; import com.datumbox.framework.common.storage.interfaces.StorageEngine; import com.datumbox.framework.common.storage.interfaces.StorageEngine.MapType; import com.datumbox.framework.common.storage.interfaces.StorageEngine.StorageHint; import com.datumbox.framework.core.machinelearning.common.abstracts.AbstractTrainer; import com.datumbox.framework.core.machinelearning.common.abstracts.featureselectors.AbstractScoreBasedFeatureSelector; import java.util.*; import java.util.function.BiFunction; /** * Implementation of the TF-IDF Feature Selection algorithm. * * * References: * http://en.wikipedia.org/wiki/Tf%E2%80%93idf * https://gist.github.com/AloneRoad/1605037 * http://www.tfidf.com/ * * @author Vasilis Vryniotis <bbriniotis@datumbox.com> */ public class TFIDF extends AbstractScoreBasedFeatureSelector<TFIDF.ModelParameters, TFIDF.TrainingParameters> { /** {@inheritDoc} */ public static class ModelParameters extends AbstractScoreBasedFeatureSelector.AbstractModelParameters { private static final long serialVersionUID = 2L; /** * @param storageEngine * @see AbstractTrainer.AbstractModelParameters#AbstractModelParameters(StorageEngine) */ protected ModelParameters(StorageEngine storageEngine) { super(storageEngine); } } /** {@inheritDoc} */ public static class TrainingParameters extends AbstractScoreBasedFeatureSelector.AbstractTrainingParameters { private static final long serialVersionUID = 1L; private boolean binarized = false; /** * Getter for the binarized flag; when it is set on the frequencies of the * activated keywords are clipped to 1. * * @return */ public boolean isBinarized() { return binarized; } /** * Setter for the binarized flag; when it is set on the frequencies of the * activated keywords are clipped to 1. * * @param binarized */ public void setBinarized(boolean binarized) { this.binarized = binarized; } } /** * @param trainingParameters * @param configuration * @see AbstractTrainer#AbstractTrainer(AbstractTrainer.AbstractTrainingParameters, Configuration) */ protected TFIDF(TrainingParameters trainingParameters, Configuration configuration) { super(trainingParameters, configuration); } /** * @param storageName * @param configuration * @see AbstractTrainer#AbstractTrainer(String, Configuration) */ protected TFIDF(String storageName, Configuration configuration) { super(storageName, configuration); } /** {@inheritDoc} */ @Override public void fit(Dataframe trainingData) { Set<TypeInference.DataType> supportedXDataTypes = getSupportedXDataTypes(); for(TypeInference.DataType d : trainingData.getXDataTypes().values()) { if(!supportedXDataTypes.contains(d)) { throw new IllegalArgumentException("A DataType that is not supported by this method was detected in the Dataframe."); } } super.fit(trainingData); } /** {@inheritDoc} */ @Override protected void _fit(Dataframe trainingData) { ModelParameters modelParameters = knowledgeBase.getModelParameters(); TrainingParameters trainingParameters = knowledgeBase.getTrainingParameters(); boolean binarized = trainingParameters.isBinarized(); int n = trainingData.size(); StorageEngine storageEngine = knowledgeBase.getStorageEngine(); Map<Object, Double> tmp_idfMap = storageEngine.getBigMap("tmp_idf", Object.class, Double.class, MapType.HASHMAP, StorageHint.IN_MEMORY, true, true); //initially estimate the counts of the terms in the dataset and store this temporarily //in idf map. this help us avoid using twice much memory comparing to using two different maps for(Record r : trainingData) { for(Map.Entry<Object, Object> entry : r.getX().entrySet()) { Object keyword = entry.getKey(); Double counts = TypeInference.toDouble(entry.getValue()); if(counts > 0.0) { tmp_idfMap.put(keyword, tmp_idfMap.getOrDefault(keyword, 0.0)+1.0); } } } //remove rare features Integer rareFeatureThreshold = trainingParameters.getRareFeatureThreshold(); if(rareFeatureThreshold != null && rareFeatureThreshold>0) { removeRareFeatures(tmp_idfMap, rareFeatureThreshold); } //convert counts to idf scores streamExecutor.forEach(StreamMethods.stream(tmp_idfMap.entrySet().stream(), isParallelized()), entry -> { Object keyword = entry.getKey(); Double countsInDocument = entry.getValue(); tmp_idfMap.put(keyword, Math.log10(n/countsInDocument)); }); final Map<Object, Double> featureScores = modelParameters.getFeatureScores(); //this lambda checks if the new score is larger than the current max score of the feature BiFunction<Object, Double, Boolean> isGreaterThanMax = (feature, newScore) -> { Double maxScore = featureScores.get(feature); return maxScore==null || maxScore<newScore; }; //calculate the maximum tfidf scores streamExecutor.forEach(StreamMethods.stream(trainingData.stream(), isParallelized()), r -> { //calculate the tfidf scores for(Map.Entry<Object, Object> entry : r.getX().entrySet()) { Double counts = TypeInference.toDouble(entry.getValue()); if(counts > 0.0) { Object keyword = entry.getKey(); double tf = binarized?1.0:counts; double idf = tmp_idfMap.getOrDefault(keyword, 0.0); double tfidf = tf*idf; if(tfidf > 0.0) { //ignore 0 scored features //Threads will help here under the assumption that only //a small number of records will have features that exceed //the maximum score. Thus they will stop in this if statement //and they will not go into the synced block. if(isGreaterThanMax.apply(keyword, tfidf)) { synchronized(featureScores) { if(isGreaterThanMax.apply(keyword, tfidf)) { featureScores.put(keyword, tfidf); } } } } } } }); //Drop the temporary Collection storageEngine.dropBigMap("tmp_idf", tmp_idfMap); //keep only the top features Integer maxFeatures = trainingParameters.getMaxFeatures(); if(maxFeatures!=null && maxFeatures<featureScores.size()) { keepTopFeatures(featureScores, maxFeatures); } } /** {@inheritDoc} */ @Override protected Set<TypeInference.DataType> getSupportedXDataTypes() { return new HashSet<>(Arrays.asList(TypeInference.DataType.BOOLEAN, TypeInference.DataType.NUMERICAL)); } /** {@inheritDoc} */ @Override protected Set<TypeInference.DataType> getSupportedYDataTypes() { return null; } }
39.178571
156
0.634913
edabd126974c87f1269ba4dcd488236b2257df0f
41,007
package org.nypl.simplified.viewer.epub.readium1; import android.annotation.SuppressLint; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.pm.ApplicationInfo; import android.content.res.Configuration; import android.content.res.Resources; import android.graphics.ColorMatrixColorFilter; import android.os.Build; import android.os.Bundle; import android.view.View; import android.view.ViewGroup; import android.view.WindowManager; import android.webkit.ConsoleMessage; import android.webkit.WebChromeClient; import android.webkit.WebSettings; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.ImageView; import android.widget.ProgressBar; import android.widget.TextView; import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatActivity; import androidx.fragment.app.FragmentManager; import com.io7m.jfunctional.Option; import com.io7m.jfunctional.OptionType; import com.io7m.jfunctional.Some; import com.io7m.junreachable.UnreachableCodeException; import org.jetbrains.annotations.NotNull; import org.joda.time.LocalDateTime; import org.librarysimplified.services.api.Services; import org.nypl.drm.core.AdobeAdeptLoan; import org.nypl.simplified.accounts.api.AccountAuthenticationAdobePostActivationCredentials; import org.nypl.simplified.accounts.api.AccountAuthenticationAdobePreActivationCredentials; import org.nypl.simplified.accounts.api.AccountAuthenticationCredentials; import org.nypl.simplified.accounts.api.AccountLoginState; import org.nypl.simplified.accounts.database.api.AccountType; import org.nypl.simplified.accounts.database.api.AccountsDatabaseNonexistentException; import org.nypl.simplified.analytics.api.AnalyticsEvent; import org.nypl.simplified.analytics.api.AnalyticsType; import org.nypl.simplified.app.reader.ReaderColorSchemes; import org.nypl.simplified.books.api.BookDRMInformation; import org.nypl.simplified.profiles.api.ProfilePreferences; import org.nypl.simplified.ui.screen.ScreenSizeInformationType; import org.nypl.simplified.ui.thread.api.UIThreadServiceType; import org.nypl.simplified.viewer.epub.readium1.toc.ReaderTOC; import org.nypl.simplified.viewer.epub.readium1.toc.ReaderTOCActivity; import org.nypl.simplified.viewer.epub.readium1.toc.ReaderTOCElement; import org.nypl.simplified.viewer.epub.readium1.toc.ReaderTOCParameters; import org.nypl.simplified.viewer.epub.readium1.toc.ReaderTOCSelection; import org.nypl.simplified.viewer.epub.readium1.toc.ReaderTOCSelectionListenerType; import org.nypl.simplified.books.api.BookFormat; import org.nypl.simplified.books.api.BookID; import org.nypl.simplified.books.api.BookLocation; import org.nypl.simplified.books.api.Bookmark; import org.nypl.simplified.books.api.BookmarkKind; import org.nypl.simplified.books.book_database.api.BookDatabaseException; import org.nypl.simplified.feeds.api.FeedEntry; import org.nypl.simplified.feeds.api.FeedEntry.FeedEntryOPDS; import org.nypl.simplified.opds.core.OPDSAcquisitionFeedEntry; import org.nypl.simplified.profiles.api.ProfileEvent; import org.nypl.simplified.profiles.api.ProfileNoneCurrentException; import org.nypl.simplified.profiles.api.ProfileUpdated; import org.nypl.simplified.profiles.controller.api.ProfilesControllerType; import org.nypl.simplified.reader.api.ReaderColorScheme; import org.nypl.simplified.reader.api.ReaderPreferences; import org.nypl.simplified.reader.bookmarks.api.ReaderBookmarkServiceType; import org.nypl.simplified.reader.bookmarks.api.ReaderBookmarks; import org.nypl.simplified.ui.theme.ThemeControl; import org.nypl.simplified.ui.theme.ThemeServiceType; import org.readium.sdk.android.Container; import org.readium.sdk.android.Package; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.net.URI; import java.util.Collections; import java.util.List; import java.util.Locale; import java.util.Objects; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import io.reactivex.disposables.Disposable; import kotlin.Pair; import static org.nypl.simplified.books.book_database.api.BookDatabaseEntryFormatHandle.BookDatabaseEntryFormatHandleEPUB; import static org.nypl.simplified.viewer.epub.readium1.ReaderReadiumViewerSettings.ScrollMode.AUTO; import static org.nypl.simplified.viewer.epub.readium1.ReaderReadiumViewerSettings.SyntheticSpreadMode.SINGLE; /** * The main reader activity for reading an EPUB. */ public final class ReaderActivity extends AppCompatActivity implements ReaderSettingsListenerType, ReaderHTTPServerStartListenerType, ReaderSimplifiedFeedbackListenerType, ReaderReadiumFeedbackListenerType, ReaderReadiumEPUBLoadListenerType, ReaderCurrentPageListenerType, ReaderTOCSelectionListenerType, ReaderMediaOverlayAvailabilityListenerType { private static final String BOOK_ID = "org.nypl.simplified.app.ReaderActivity.book"; private static final String FILE_ID = "org.nypl.simplified.app.ReaderActivity.file"; private static final String ENTRY = "org.nypl.simplified.app.ReaderActivity.entry"; private static final Logger LOG = LoggerFactory.getLogger(ReaderActivity.class); private BookID book_id; private OPDSAcquisitionFeedEntry feed_entry; private Container epub_container; private ReaderReadiumJavaScriptAPIType readium_js_api; private ReaderSimplifiedJavaScriptAPIType simplified_js_api; private ImageView view_bookmark; private ViewGroup view_hud; private ProgressBar view_loading; private ViewGroup view_media; private ImageView view_media_next; private ImageView view_media_play; private ImageView view_media_prev; private ProgressBar view_progress_bar; private TextView view_progress_text; private View view_root; private ImageView view_settings; private TextView view_title_text; private ImageView view_toc; private WebView view_web_view; private ReaderReadiumViewerSettings viewer_settings; private boolean web_view_resized; private Bookmark current_location; private AccountType current_account; private int current_page_index = 0; private int current_page_count = 1; private String current_chapter_title = "Unknown"; private Disposable profile_subscription; private BookDatabaseEntryFormatHandleEPUB formatHandle; private UIThreadServiceType uiThread; /** * Construct an activity. */ public ReaderActivity() { } /** * Start a new reader for the given book. * * @param from The parent activity * @param book_id The unique ID of the book * @param file The actual EPUB file * @param entry The OPD feed entry */ public static void startActivity( final Activity from, final BookID book_id, final File file, final FeedEntry.FeedEntryOPDS entry) { Objects.requireNonNull(file); final Bundle b = new Bundle(); b.putSerializable(ReaderActivity.BOOK_ID, book_id); b.putSerializable(ReaderActivity.FILE_ID, file); b.putSerializable(ReaderActivity.ENTRY, entry); final Intent i = new Intent(from, ReaderActivity.class); i.putExtras(b); from.startActivity(i); } private void applyViewerColorFilters() { LOG.debug("applying color filters"); final TextView in_progress_text = Objects.requireNonNull(this.view_progress_text); final TextView in_title_text = Objects.requireNonNull(this.view_title_text); final ImageView in_toc = Objects.requireNonNull(this.view_toc); final ImageView in_bookmark = Objects.requireNonNull(this.view_bookmark); final ImageView in_settings = Objects.requireNonNull(this.view_settings); final ImageView in_media_play = Objects.requireNonNull(this.view_media_play); final ImageView in_media_next = Objects.requireNonNull(this.view_media_next); final ImageView in_media_prev = Objects.requireNonNull(this.view_media_prev); final int mainColor = ThemeControl.resolveColorAttribute(this.getTheme(), R.attr.colorPrimary); final ColorMatrixColorFilter filter = ReaderColorMatrix.getImageFilterMatrix(mainColor); uiThread.runOnUIThread(() -> { in_progress_text.setTextColor(mainColor); in_title_text.setTextColor(mainColor); in_toc.setColorFilter(filter); in_bookmark.setColorFilter(filter); in_settings.setColorFilter(filter); in_media_play.setColorFilter(filter); in_media_next.setColorFilter(filter); in_media_prev.setColorFilter(filter); }); } /** * Apply the given color scheme to all views. Unfortunately, there does not * seem to be a more pleasant way, in the Android API, than manually applying * values to all of the views in the hierarchy. */ private void applyViewerColorScheme(final ReaderColorScheme cs) { LOG.debug("applyViewerColorScheme: {}", cs); final View in_root = Objects.requireNonNull(this.view_root); uiThread.runOnUIThread(() -> { in_root.setBackgroundColor(ReaderColorSchemes.backgroundAsAndroidColor(cs)); this.applyViewerColorFilters(); }); } private void makeInitialReadiumRequest(final ReaderHTTPServerType hs) { final URI reader_uri = URI.create(hs.getURIBase() + "reader.html"); uiThread.runOnUIThreadDelayed(() -> { LOG.debug("makeInitialReadiumRequest: {}", reader_uri); this.view_web_view.loadUrl(reader_uri.toString()); }, 300L); } @Override protected void onActivityResult( final int request_code, final int result_code, final @Nullable Intent data) { super.onActivityResult(request_code, result_code, data); LOG.debug("onActivityResult: {} {} {}", request_code, result_code, data); if (request_code == ReaderTOCActivity.TOC_SELECTION_REQUEST_CODE) { if (result_code == Activity.RESULT_OK) { final Intent nnd = Objects.requireNonNull(data); final Bundle b = Objects.requireNonNull(nnd.getExtras()); final ReaderTOCSelection selection = (ReaderTOCSelection) b.getSerializable(ReaderTOCActivity.TOC_SELECTED_ID); this.onTOCItemSelected(selection); } else { LOG.error("Error from TOC Activity Result"); } } } @Override public void onConfigurationChanged(final @Nullable Configuration c) { super.onConfigurationChanged(c); LOG.debug("configuration changed"); final WebView in_web_view = Objects.requireNonNull(this.view_web_view); final TextView in_progress_text = Objects.requireNonNull(this.view_progress_text); final ProgressBar in_progress_bar = Objects.requireNonNull(this.view_progress_bar); in_web_view.setVisibility(View.INVISIBLE); in_progress_text.setVisibility(View.INVISIBLE); in_progress_bar.setVisibility(View.INVISIBLE); this.web_view_resized = true; uiThread.runOnUIThreadDelayed(() -> { this.readium_js_api.getCurrentPage(this); this.readium_js_api.mediaOverlayIsAvailable(this); }, 300L); } @SuppressLint("SetJavaScriptEnabled") @Override protected void onCreate(final @Nullable Bundle state) { this.setTheme(Services.INSTANCE.serviceDirectory() .requireService(ThemeServiceType.class) .findCurrentTheme() .getThemeWithNoActionBar()); super.onCreate(state); this.setContentView(R.layout.reader); this.uiThread = Services.INSTANCE.serviceDirectory().requireService(UIThreadServiceType.class); LOG.debug("onCreate: starting"); final Intent i = Objects.requireNonNull(this.getIntent()); final Bundle a = Objects.requireNonNull(i.getExtras()); final File in_epub_file = Objects.requireNonNull((File) a.getSerializable(ReaderActivity.FILE_ID)); this.book_id = Objects.requireNonNull((BookID) a.getSerializable(ReaderActivity.BOOK_ID)); final FeedEntryOPDS entry = Objects.requireNonNull((FeedEntryOPDS) a.getSerializable(ReaderActivity.ENTRY)); this.feed_entry = entry.getFeedEntry(); LOG.debug("onCreate: epub file: {}", in_epub_file); LOG.debug("onCreate: book id: {}", this.book_id); LOG.debug("onCreate: entry id: {}", entry.getFeedEntry().getID()); try { this.current_account = Services.INSTANCE.serviceDirectory() .requireService(ProfilesControllerType.class) .profileAccountForBook(this.book_id); } catch (ProfileNoneCurrentException | AccountsDatabaseNonexistentException e) { this.onEPUBLoadFailed(e); this.finish(); return; } this.profile_subscription = Services.INSTANCE.serviceDirectory() .requireService(ProfilesControllerType.class) .profileEvents() .subscribe(this::onProfileEvent); final ReaderPreferences readerPreferences; try { readerPreferences = Services.INSTANCE.serviceDirectory() .requireService(ProfilesControllerType.class) .profileCurrent() .preferences() .getReaderPreferences(); } catch (final ProfileNoneCurrentException e) { this.onEPUBLoadFailed(e); this.finish(); return; } this.viewer_settings = new ReaderReadiumViewerSettings( SINGLE, AUTO, (int) readerPreferences.fontScale(), 20); final ReaderReadiumFeedbackDispatcherType rd = ReaderReadiumFeedbackDispatcher.newDispatcher(); final ReaderSimplifiedFeedbackDispatcherType sd = ReaderSimplifiedFeedbackDispatcher.newDispatcher(); final ViewGroup in_hud = Objects.requireNonNull(this.findViewById(R.id.reader_hud_container)); final ImageView in_toc = Objects.requireNonNull(in_hud.findViewById(R.id.reader_toc)); final ImageView in_bookmark = Objects.requireNonNull(in_hud.findViewById(R.id.reader_bookmark)); final ImageView in_settings = Objects.requireNonNull(in_hud.findViewById(R.id.reader_settings)); final TextView in_title_text = Objects.requireNonNull(in_hud.findViewById(R.id.reader_title_text)); final TextView in_progress_text = Objects.requireNonNull(in_hud.findViewById(R.id.reader_position_text)); final ProgressBar in_progress_bar = Objects.requireNonNull(in_hud.findViewById(R.id.reader_position_progress)); final ViewGroup in_media_overlay = Objects.requireNonNull(this.findViewById(R.id.reader_hud_media)); final ImageView in_media_previous = Objects.requireNonNull(this.findViewById(R.id.reader_hud_media_previous)); final ImageView in_media_next = Objects.requireNonNull(this.findViewById(R.id.reader_hud_media_next)); final ImageView in_media_play = Objects.requireNonNull(this.findViewById(R.id.reader_hud_media_play)); final ProgressBar in_loading = Objects.requireNonNull(this.findViewById(R.id.reader_loading)); final WebView in_webview = Objects.requireNonNull(this.findViewById(R.id.reader_webview)); this.view_root = Objects.requireNonNull(in_hud.getRootView()); in_loading.setVisibility(View.VISIBLE); in_progress_bar.setVisibility(View.INVISIBLE); in_progress_text.setVisibility(View.INVISIBLE); in_webview.setVisibility(View.INVISIBLE); in_hud.setVisibility(View.VISIBLE); in_media_overlay.setVisibility(View.INVISIBLE); in_settings.setOnClickListener(view -> { final FragmentManager fm = this.getSupportFragmentManager(); final ReaderSettingsDialog d = ReaderSettingsDialog.Companion.create(); d.show(fm, "settings-dialog"); }); // set reader brightness. final int brightness = getPreferences(Context.MODE_PRIVATE).getInt("reader_brightness", 50); final float back_light_value = (float) brightness / 100; final WindowManager.LayoutParams layout_params = getWindow().getAttributes(); layout_params.screenBrightness = back_light_value; getWindow().setAttributes(layout_params); this.view_loading = in_loading; this.view_progress_text = in_progress_text; this.view_progress_bar = in_progress_bar; this.view_title_text = in_title_text; this.view_web_view = in_webview; this.view_hud = in_hud; this.view_toc = in_toc; this.view_bookmark = in_bookmark; this.view_settings = in_settings; this.web_view_resized = true; this.view_media = in_media_overlay; this.view_media_next = in_media_next; this.view_media_prev = in_media_previous; this.view_media_play = in_media_play; final WebChromeClient wc_client = new WebChromeClient() { @Override public void onShowCustomView( final @Nullable View view, final @Nullable CustomViewCallback callback) { super.onShowCustomView(view, callback); LOG.debug("web-chrome: {}", view); } @Override public boolean onConsoleMessage(final ConsoleMessage consoleMessage) { LOG.debug("web-chrome: console: {}:{}: {}: {}", consoleMessage.sourceId(), consoleMessage.lineNumber(), consoleMessage.messageLevel(), consoleMessage.message()); return true; } }; final WebViewClient wv_client = new ReaderWebViewClient(this, sd, this, rd, this); in_webview.setWebChromeClient(wc_client); in_webview.setWebViewClient(wv_client); in_webview.setOnLongClickListener(view -> { LOG.debug("ignoring long click on web view"); return true; }); // Allow the webview to be debuggable only if this is a dev build if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { if ((getApplicationInfo().flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0) { WebView.setWebContentsDebuggingEnabled(true); } } final WebSettings s = Objects.requireNonNull(in_webview.getSettings()); s.setAppCacheEnabled(false); s.setAllowFileAccess(false); s.setAllowFileAccessFromFileURLs(false); s.setAllowContentAccess(false); s.setAllowUniversalAccessFromFileURLs(false); s.setSupportMultipleWindows(false); s.setCacheMode(WebSettings.LOAD_NO_CACHE); s.setGeolocationEnabled(false); s.setJavaScriptEnabled(true); this.readium_js_api = ReaderReadiumJavaScriptAPI.newAPI(this.uiThread, in_webview); this.simplified_js_api = ReaderSimplifiedJavaScriptAPI.newAPI(this.uiThread, in_webview); in_title_text.setText(""); try { this.formatHandle = this.current_account.getBookDatabase() .entry(this.book_id) .findFormatHandle(BookDatabaseEntryFormatHandleEPUB.class); } catch (BookDatabaseException e) { this.onEPUBLoadFailed(e); this.finish(); return; } Objects.requireNonNull(this.formatHandle, "formatHandle"); final BookFormat.BookFormatEPUB format = this.formatHandle.getFormat(); final ReaderReadiumEPUBLoaderType loader = Services.INSTANCE.serviceDirectory().requireService(ReaderReadiumEPUBLoaderType.class); final ReaderReadiumEPUBLoadRequest request = ReaderReadiumEPUBLoadRequest.builder(in_epub_file) .setAdobeRightsFile(getAdobeRightsFrom(format)) .build(); LOG.debug("onCreate: loading EPUB"); loader.loadEPUB(request, this); LOG.debug("onCreate: applying viewer color filters"); this.applyViewerColorFilters(); } private OptionType<File> getAdobeRightsFrom(final BookFormat.BookFormatEPUB format) { final BookDRMInformation info = format.getDrmInformation(); if (info instanceof BookDRMInformation.ACS) { final Pair<File, AdobeAdeptLoan> rights = ((BookDRMInformation.ACS) info).getRights(); if (rights != null) { return Option.of(rights.component1()); } } return Option.none(); } private void onProfileEvent(final ProfileEvent event) { if (event instanceof ProfileUpdated.Succeeded) { onProfileEventPreferencesChanged((ProfileUpdated.Succeeded) event); } } private void onProfileEventPreferencesChanged( final ProfileUpdated.Succeeded event) { final ProfilePreferences oldPreferences = event.getOldDescription().getPreferences(); final ProfilePreferences newPreferences = event.getNewDescription().getPreferences(); if (!oldPreferences.equals(newPreferences)) { LOG.debug("onProfileEventPreferencesChanged: reader settings changed"); applyReaderPreferences(newPreferences.getReaderPreferences()); } } private void applyReaderPreferences(final ReaderPreferences preferences) { uiThread.runOnUIThread(() -> { LOG.debug("applyReaderPreferences: executing now"); // Get the CFI from the ReadiumSDK before applying the new // page style settings. this.simplified_js_api.getReadiumCFI(); this.readium_js_api.setPageStyleSettings(preferences); // Once they are applied, go to the CFI that is stored in the // JS ReadiumSDK instance. this.simplified_js_api.setReadiumCFI(); this.applyViewerColorScheme(preferences.colorScheme()); this.readium_js_api.getCurrentPage(this); this.readium_js_api.mediaOverlayIsAvailable(this); }); } @Override public void onCurrentPageError(final Throwable x) { LOG.error("onCurrentPageError: {}", x.getMessage(), x); } @Override public void onCurrentPageReceived(final BookLocation location) { Objects.requireNonNull(location); LOG.debug("onCurrentPageReceived: {}", location); final Bookmark bookmark = new Bookmark( this.feed_entry.getID(), location, BookmarkKind.ReaderBookmarkLastReadLocation.INSTANCE, LocalDateTime.now(), this.current_chapter_title, currentBookProgress(), getDeviceIDString(), null); this.current_location = bookmark; uiThread.runOnUIThread(this::configureBookmarkButtonUI); Services.INSTANCE.serviceDirectory() .requireService(ReaderBookmarkServiceType.class) .bookmarkCreate(this.current_account.getId(), bookmark); } /** * Show the bookmark icon as selected if the current location is an explicit bookmark. Otherwise, * show it as deselected. */ private void configureBookmarkButtonUI() { uiThread.checkIsUIThread(); final Bookmark location = this.current_location; if (location != null) { if (location.getKind().getClass() == BookmarkKind.ReaderBookmarkExplicit.class) { this.view_bookmark.setImageResource(R.drawable.bookmark_on); return; } } this.view_bookmark.setImageResource(R.drawable.bookmark_off); } @Override protected void onPause() { super.onPause(); final Bookmark location = this.current_location; if (location != null) { Services.INSTANCE.serviceDirectory() .requireService(ReaderBookmarkServiceType.class) .bookmarkCreate(this.current_account.getId(), location); } } @Override protected void onDestroy() { super.onDestroy(); this.readium_js_api.getCurrentPage(this); this.readium_js_api.mediaOverlayIsAvailable(this); /* * Publish an analytics event. */ try { Services.INSTANCE.serviceDirectory() .requireService(AnalyticsType.class) .publishEvent(new AnalyticsEvent.BookClosed( LocalDateTime.now(), this.current_account.getLoginState().getCredentials(), Services.INSTANCE.serviceDirectory() .requireService(ProfilesControllerType.class) .profileCurrent() .getId() .getUuid(), this.current_account.getProvider().getId(), this.current_account.getId().getUuid(), this.feed_entry)); } catch (ProfileNoneCurrentException ex) { LOG.error("profile is not current: ", ex); } final Disposable sub = this.profile_subscription; if (sub != null) { sub.dispose(); } this.profile_subscription = null; } @Override public void onEPUBLoadFailed(final Throwable x) { ErrorDialogUtilities.showErrorWithRunnable( this, this.uiThread, LOG, "Could not load EPUB file", x, this::finish); } @Override public void onEPUBLoadSucceeded(final Container c) { LOG.debug("onEPUBLoadSucceeded: {}", c.getName()); this.epub_container = c; final Package p = Objects.requireNonNull(c.getDefaultPackage()); final TextView in_title_text = Objects.requireNonNull(this.view_title_text); uiThread.runOnUIThread(() -> in_title_text.setText(Objects.requireNonNull(p.getTitle()))); /* * Configure the TOC and Bookmark buttons. */ uiThread.runOnUIThread(() -> { this.view_toc.setOnClickListener(v -> { final ReaderBookmarks bookmarks = loadBookmarks(); final ReaderTOC toc = ReaderTOC.Companion.fromPackage(p); final ReaderTOCParameters parameters = new ReaderTOCParameters(bookmarks, toc.getElements()); ReaderTOCActivity.Companion.startActivityForResult(ReaderActivity.this, parameters); this.overridePendingTransition(0, 0); }); this.view_bookmark.setOnClickListener(v -> { this.current_location = this.current_location.toExplicit(); Services.INSTANCE.serviceDirectory() .requireService(ReaderBookmarkServiceType.class) .bookmarkCreate(this.current_account.getId(), this.current_location); this.configureBookmarkButtonUI(); }); }); /* * Get a reference to the web server. Start it if necessary (the callbacks * will still be executed if the server is already running). */ final ReaderHTTPServerType server = Services.INSTANCE.serviceDirectory().requireService(ReaderHTTPServerType.class); server.startIfNecessaryForPackage(p, this); } private ReaderBookmarks loadBookmarks() { try { return Services.INSTANCE.serviceDirectory() .requireService(ReaderBookmarkServiceType.class) .bookmarkLoad(this.current_account.getId(), this.book_id) .get(10L, TimeUnit.SECONDS); } catch (InterruptedException e) { LOG.error("could not load bookmarks: ", e); return new ReaderBookmarks(null, Collections.emptyList()); } catch (ExecutionException e) { LOG.error("could not load bookmarks: ", e); return new ReaderBookmarks(null, Collections.emptyList()); } catch (TimeoutException e) { LOG.error("could not load bookmarks: ", e); return new ReaderBookmarks(null, Collections.emptyList()); } } private double currentBookProgress() { return (double) this.view_progress_bar.getProgress() / (double) this.view_progress_bar.getMax(); } private double currentChapterProgress() { if (this.current_page_count > 0) { return (float) current_page_index / current_page_count; } else { return 0.0; } } private String getDeviceIDString() { final AccountLoginState state = this.current_account.getLoginState(); final AccountAuthenticationCredentials credentials = state.getCredentials(); if (credentials != null) { final AccountAuthenticationAdobePreActivationCredentials preActivation = credentials.getAdobeCredentials(); if (preActivation != null) { final AccountAuthenticationAdobePostActivationCredentials postActivation = preActivation.getPostActivationCredentials(); if (postActivation != null) { return postActivation.getDeviceID().getValue(); } } } return "null"; } @Override public void onMediaOverlayIsAvailable(final boolean available) { LOG.debug("onMediaOverlayIsAvailable: available: {}", available); final ViewGroup in_media_hud = Objects.requireNonNull(this.view_media); final TextView in_title = Objects.requireNonNull(this.view_title_text); uiThread.runOnUIThread(() -> { in_media_hud.setVisibility(available ? View.VISIBLE : View.GONE); in_title.setVisibility(available ? View.GONE : View.VISIBLE); }); } @Override public void onMediaOverlayIsAvailableError(final Throwable x) { LOG.error("{}", x.getMessage(), x); } @Override public void onReadiumFunctionDispatchError(final Throwable x) { LOG.error("{}", x.getMessage(), x); } @Override public void onReadiumFunctionInitialize() { LOG.debug("onReadiumFunctionInitialize: readium initialize requested"); final ReaderHTTPServerType hs = Services.INSTANCE.serviceDirectory().requireService(ReaderHTTPServerType.class); final Container c = Objects.requireNonNull(this.epub_container); final Package p = Objects.requireNonNull(c.getDefaultPackage()); p.setRootUrls(hs.getURIBase().toString(), null); /* * If there's a bookmark for the current book, send a request to open the * book to that specific page. Otherwise, start at the beginning. */ navigateTo(Option.of(this.formatHandle.getFormat().getLastReadLocation())); /* * Configure the visibility of UI elements. */ final WebView in_web_view = Objects.requireNonNull(this.view_web_view); final ProgressBar in_loading = Objects.requireNonNull(this.view_loading); final ProgressBar in_progress_bar = Objects.requireNonNull(this.view_progress_bar); final TextView in_progress_text = Objects.requireNonNull(this.view_progress_text); final ImageView in_media_play = Objects.requireNonNull(this.view_media_play); final ImageView in_media_next = Objects.requireNonNull(this.view_media_next); final ImageView in_media_prev = Objects.requireNonNull(this.view_media_prev); in_loading.setVisibility(View.GONE); in_web_view.setVisibility(View.VISIBLE); in_progress_bar.setVisibility(View.VISIBLE); in_progress_text.setVisibility(View.INVISIBLE); uiThread.runOnUIThread(() -> { in_media_play.setOnClickListener(view -> { LOG.debug("toggling media overlay"); this.readium_js_api.mediaOverlayToggle(); }); in_media_next.setOnClickListener( view -> { LOG.debug("next media overlay"); this.readium_js_api.mediaOverlayNext(); }); in_media_prev.setOnClickListener( view -> { LOG.debug("previous media overlay"); this.readium_js_api.mediaOverlayPrevious(); }); }); } @Override public void onReadiumFunctionInitializeError(final Throwable e) { ErrorDialogUtilities.showErrorWithRunnable( this, this.uiThread, LOG, "Unable to initialize Readium", e, this::finish); } @Override public void onReadiumContentDocumentLoaded() { LOG.debug("onReadiumContentDocumentLoaded"); try { this.applyReaderPreferences( Services.INSTANCE.serviceDirectory() .requireService(ProfilesControllerType.class) .profileCurrent() .preferences() .getReaderPreferences()); } catch (final ProfileNoneCurrentException e) { throw new IllegalStateException(e); } } @Override public void onReadiumContentDocumentLoadedError(final Throwable e) { LOG.error("onReadiumContentDocumentLoadedError: {}", e.getMessage(), e); } /** * {@inheritDoc} * <p> * When the device orientation changes, the configuration change handler * {@link #onConfigurationChanged(Configuration)} makes the web view invisible * so that the user does not see the now incorrectly-paginated content. When * Readium tells the app that the content pagination has changed, it makes the * web view visible again. */ @Override public void onReadiumFunctionPaginationChanged(final ReaderPaginationChangedEvent e) { LOG.debug("onReadiumFunctionPaginationChanged: {}", e); final WebView in_web_view = Objects.requireNonNull(this.view_web_view); /* * Configure the progress bar and text. */ final TextView in_progress_text = Objects.requireNonNull(this.view_progress_text); final ProgressBar in_progress_bar = Objects.requireNonNull(this.view_progress_bar); final Container container = Objects.requireNonNull(this.epub_container); final Package default_package = Objects.requireNonNull(container.getDefaultPackage()); uiThread.runOnUIThread(() -> { final double p = e.getProgressFractional(); in_progress_bar.setMax(100); in_progress_bar.setProgress((int) (100.0 * p)); final List<ReaderPaginationChangedEvent.OpenPage> pages = e.getOpenPages(); if (pages.isEmpty()) { in_progress_text.setText(""); } else { final ReaderPaginationChangedEvent.OpenPage page = Objects.requireNonNull(pages.get(0)); this.current_page_index = page.getSpineItemPageIndex(); this.current_page_count = page.getSpineItemPageCount(); this.current_chapter_title = default_package.getSpineItem(page.getIDRef()).getTitle(); in_progress_text.setText( Objects.requireNonNull( String.format( Locale.ENGLISH, "Page %d of %d (%s)", page.getSpineItemPageIndex() + 1, page.getSpineItemPageCount(), default_package.getSpineItem(page.getIDRef()).getTitle()))); /* * Publish an analytics event. */ try { Services.INSTANCE.serviceDirectory() .requireService(AnalyticsType.class) .publishEvent(new AnalyticsEvent.BookPageTurned( LocalDateTime.now(), this.current_account.getLoginState().getCredentials(), Services.INSTANCE.serviceDirectory() .requireService(ProfilesControllerType.class) .profileCurrent() .getId() .getUuid(), this.current_account.getProvider().getId(), this.current_account.getId().getUuid(), this.feed_entry, this.current_page_index, this.current_page_count, this.current_chapter_title)); } catch (ProfileNoneCurrentException ex) { LOG.error("profile is not current: ", ex); } } /* * Ask for Readium to deliver the unique identifier of the current page, * and tell Simplified that the page has changed and so any Javascript * state should be reconfigured. */ uiThread.runOnUIThreadDelayed(() -> { this.readium_js_api.getCurrentPage(this); this.readium_js_api.mediaOverlayIsAvailable(this); }, 300L); }); /* * Make the web view visible with a slight delay (as sometimes a * pagination-change event will be sent even though the content has not * yet been laid out in the web view). Only do this if the screen * orientation has just changed. */ if (this.web_view_resized) { this.web_view_resized = false; uiThread.runOnUIThreadDelayed(() -> { in_web_view.setVisibility(View.VISIBLE); in_progress_bar.setVisibility(View.VISIBLE); in_progress_text.setVisibility(View.VISIBLE); this.simplified_js_api.pageHasChanged(); }, 300L); } else { uiThread.runOnUIThread(this.simplified_js_api::pageHasChanged); } } @Override public void onReadiumFunctionPaginationChangedError(final Throwable x) { LOG.error("onReadiumFunctionPaginationChangedError: {}", x.getMessage(), x); } @Override public void onReadiumFunctionSettingsApplied() { LOG.debug("onReadiumFunctionSettingsApplied"); } @Override public void onReadiumFunctionSettingsAppliedError(final Throwable e) { LOG.error("onReadiumFunctionSettingsAppliedError: {}", e.getMessage(), e); } @Override public void onReadiumFunctionUnknown(final String text) { LOG.error("onReadiumFunctionUnknown: unknown readium function: {}", text); } @Override public void onReadiumMediaOverlayStatusChangedIsPlaying(final boolean playing) { LOG.debug("onReadiumMediaOverlayStatusChangedIsPlaying: playing: {}", playing); final Resources rr = Objects.requireNonNull(this.getResources()); final ImageView play = Objects.requireNonNull(this.view_media_play); uiThread.runOnUIThread(() -> { if (playing) { play.setImageDrawable(rr.getDrawable(R.drawable.circle_pause_8x)); } else { play.setImageDrawable(rr.getDrawable(R.drawable.circle_play_8x)); } }); } @Override public void onReadiumMediaOverlayStatusError(final Throwable e) { LOG.error("onReadiumMediaOverlayStatusError: {}", e.getMessage(), e); } @Override public void onServerStartFailed( final ReaderHTTPServerType hs, final Throwable x) { ErrorDialogUtilities.showErrorWithRunnable( this, this.uiThread, LOG, "Could not start http server.", x, this::finish); } @Override public void onServerStartSucceeded( final ReaderHTTPServerType hs, final boolean first) { if (first) { LOG.debug("onServerStartSucceeded: http server started"); } else { LOG.debug("onServerStartSucceeded: http server already running"); } this.makeInitialReadiumRequest(hs); } @Override public void onSimplifiedFunctionDispatchError(final Throwable x) { LOG.error("onSimplifiedFunctionDispatchError: {}", x.getMessage(), x); } @Override public void onSimplifiedFunctionUnknown(final String text) { LOG.error("onSimplifiedFunctionUnknown: unknown function: {}", text); } @Override public void onSimplifiedGestureCenter() { final ViewGroup in_hud = Objects.requireNonNull(this.view_hud); uiThread.runOnUIThread(() -> { switch (in_hud.getVisibility()) { case View.VISIBLE: { FadeUtilities.fadeOut(in_hud, FadeUtilities.DEFAULT_FADE_DURATION); break; } case View.INVISIBLE: case View.GONE: { FadeUtilities.fadeIn(in_hud, FadeUtilities.DEFAULT_FADE_DURATION); break; } } }); } @Override public void onSimplifiedGestureCenterError(final Throwable x) { LOG.error("onSimplifiedGestureCenterError: {}", x.getMessage(), x); } @Override public void onSimplifiedGestureLeft() { this.readium_js_api.pagePrevious(); } @Override public void onSimplifiedGestureLeftError(final Throwable x) { LOG.error("onSimplifiedGestureLeftError: {}", x.getMessage(), x); } @Override public void onSimplifiedGestureRight() { this.readium_js_api.pageNext(); } @Override public void onSimplifiedGestureRightError(final Throwable x) { LOG.error("onSimplifiedGestureRightError: {}", x.getMessage(), x); } private void onTOCSelectionReceived(final ReaderTOCElement e) { LOG.debug("onTOCSelectionReceived: received TOC selection: {}", e); this.readium_js_api.openContentURL(e.getContentRef(), e.getSourceHref()); } private void onBookmarkSelectionReceived(final Bookmark bookmark) { LOG.debug("onTOCBookmarkSelectionReceived: received bookmark selection: {}", bookmark); this.navigateTo(Option.some(bookmark)); } private void navigateTo(final OptionType<Bookmark> location) { LOG.debug("navigateTo: {}", location); OptionType<ReaderOpenPageRequestType> page_request; if (location.isSome()) { final Bookmark locReal = ((Some<Bookmark>) location).get(); try { LOG.debug("navigateTo: Creating Page Req for: {}", locReal); final ReaderOpenPageRequestType request = ReaderOpenPageRequest.fromBookLocation(locReal.getLocation()); this.current_location = locReal; page_request = Option.of(request); } catch (Exception e) { LOG.error("navigateTo: failed to create page request: ", e); page_request = Option.none(); } } else { page_request = Option.none(); } this.readium_js_api.openBook( this.epub_container.getDefaultPackage(), this.viewer_settings, page_request ); } @Override public void onTOCItemSelected(final @NotNull ReaderTOCSelection selection) { if (selection instanceof ReaderTOCSelection.ReaderSelectedBookmark) { final ReaderTOCSelection.ReaderSelectedBookmark bookmark = (ReaderTOCSelection.ReaderSelectedBookmark) selection; this.onBookmarkSelectionReceived(bookmark.getReaderBookmark()); } else if (selection instanceof ReaderTOCSelection.ReaderSelectedTOCElement) { final ReaderTOCSelection.ReaderSelectedTOCElement element = (ReaderTOCSelection.ReaderSelectedTOCElement) selection; this.onTOCSelectionReceived(element.component1()); } else { throw new UnreachableCodeException(); } } @Override public ProfilesControllerType onReaderSettingsDialogWantsProfilesController() { return Services.INSTANCE.serviceDirectory().requireService(ProfilesControllerType.class); } @Override public ScreenSizeInformationType onReaderSettingsDialogWantsScreenSize() { return Services.INSTANCE.serviceDirectory().requireService(ScreenSizeInformationType.class); } }
35.229381
122
0.725071
455e0c0cd1e6844592bd6d484815ebe9f6f070f3
3,462
package com.muhimbi.ws; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for ConverterSpecificSettings_PDF complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="ConverterSpecificSettings_PDF"> * &lt;complexContent> * &lt;extension base="{http://types.muhimbi.com/2010/11/22}ConverterSpecificSettings"> * &lt;sequence> * &lt;element name="ConvertAttachments" type="{http://www.w3.org/2001/XMLSchema}boolean" minOccurs="0"/> * &lt;element name="ConvertAttachmentMode" type="{http://schemas.datacontract.org/2004/07/Muhimbi.DocumentConverter.WebService.Data}PDFConvertAttachmentMode" minOccurs="0"/> * &lt;element name="IgnorePortfolioCoverSheet" type="{http://www.w3.org/2001/XMLSchema}boolean" minOccurs="0"/> * &lt;/sequence> * &lt;/extension> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "ConverterSpecificSettings_PDF", namespace = "http://types.muhimbi.com/2014/04/16", propOrder = { "convertAttachments", "convertAttachmentMode", "ignorePortfolioCoverSheet" }) public class ConverterSpecificSettingsPDF extends ConverterSpecificSettings { @XmlElement(name = "ConvertAttachments") protected Boolean convertAttachments; @XmlElement(name = "ConvertAttachmentMode") protected PDFConvertAttachmentMode convertAttachmentMode; @XmlElement(name = "IgnorePortfolioCoverSheet") protected Boolean ignorePortfolioCoverSheet; /** * Gets the value of the convertAttachments property. * * @return * possible object is * {@link Boolean } * */ public Boolean isConvertAttachments() { return convertAttachments; } /** * Sets the value of the convertAttachments property. * * @param value * allowed object is * {@link Boolean } * */ public void setConvertAttachments(Boolean value) { this.convertAttachments = value; } /** * Gets the value of the convertAttachmentMode property. * * @return * possible object is * {@link PDFConvertAttachmentMode } * */ public PDFConvertAttachmentMode getConvertAttachmentMode() { return convertAttachmentMode; } /** * Sets the value of the convertAttachmentMode property. * * @param value * allowed object is * {@link PDFConvertAttachmentMode } * */ public void setConvertAttachmentMode(PDFConvertAttachmentMode value) { this.convertAttachmentMode = value; } /** * Gets the value of the ignorePortfolioCoverSheet property. * * @return * possible object is * {@link Boolean } * */ public Boolean isIgnorePortfolioCoverSheet() { return ignorePortfolioCoverSheet; } /** * Sets the value of the ignorePortfolioCoverSheet property. * * @param value * allowed object is * {@link Boolean } * */ public void setIgnorePortfolioCoverSheet(Boolean value) { this.ignorePortfolioCoverSheet = value; } }
28.61157
182
0.655113
794d6d486476cef960b7a05d516433acd5ce0493
986
/* * Copyright MapStruct Authors. * * Licensed under the Apache License version 2.0, available at http://www.apache.org/licenses/LICENSE-2.0 */ package org.mapstruct.ap.test.bugs._2213; import java.util.Arrays; import javax.annotation.Generated; @Generated( value = "org.mapstruct.ap.MappingProcessor", date = "2020-10-03T10:12:15+0200", comments = "version: , compiler: javac, environment: Java 11.0.4 (AdoptOpenJDK)" ) public class CarMapperImpl implements CarMapper { @Override public Car toCar(Car2 car2) { if ( car2 == null ) { return null; } Car car = new Car(); int[] intData = car2.getIntData(); if ( intData != null ) { car.setIntData( Arrays.copyOf( intData, intData.length ) ); } Long[] longData = car2.getLongData(); if ( longData != null ) { car.setLongData( Arrays.copyOf( longData, longData.length ) ); } return car; } }
25.947368
105
0.610548
7ecc6eb671bc94a8a177d1fc1dc95185c1b84020
514
package datastructures; import org.junit.Test; import java.util.EmptyStackException; import static org.junit.Assert.assertEquals; // The writer never had a test class for Stack.java public class StackTest { Stack stack = new Stack(); @Test public void shouldPopData(){ stack.push(1); int result = stack.pop(); assertEquals(result, 1); } @Test(expected = EmptyStackException.class) public void shouldThrowEmptyStackException(){ stack.pop(); } }
17.724138
51
0.669261
8097c9c24ab7b0e7449c30a8bca38b8a58c80f98
1,022
package com.github.sardine.ant.command; import com.github.sardine.ant.Command; /** * A nice ant wrapper around sardine.exists(). Sets the property value to "true" if the resource at URL * exists. * * @author Jon Stevens */ public class Exists extends Command { /** URL to check. */ private String url; /** Property to set if URL exists. */ private String property; /** * {@inheritDoc} */ @Override protected void execute() throws Exception { if (getSardine().exists(url)) getProject().setProperty(property, "true"); } /** * {@inheritDoc} */ @Override protected void validateAttributes() throws Exception { if (url == null) throw new IllegalArgumentException("url must not be null"); if (property == null) throw new IllegalArgumentException("property must not be null"); } /** Set URL to check. */ public void setUrl(String url) { this.url = url; } /** Set property to set if URL exists. */ public void setProperty(String property) { this.property = property; } }
20.039216
103
0.677104
3ebef142c92d7b318e1800ad88de3d6f74d14568
601
package com.codenotfound; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.dataflow.server.EnableDataFlowServer; import org.springframework.cloud.deployer.spi.cloudfoundry.CloudFoundryDeployerAutoConfiguration; @EnableDataFlowServer @SpringBootApplication( exclude = {CloudFoundryDeployerAutoConfiguration.class}) public class SpringDataFlowServerApplication { public static void main(String[] args) { SpringApplication.run(SpringDataFlowServerApplication.class, args); } }
33.388889
97
0.836938
a0760938c14f6bd3e429a231b2c737362ca87a6c
1,695
/******************************************************************************* * Copyright (c) 2006, 2013 Wind River Systems, Inc. and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Markus Schorn - initial API and implementation *******************************************************************************/ package org.eclipse.cdt.core.index; import org.eclipse.cdt.core.dom.ast.IBinding; import org.eclipse.core.runtime.CoreException; /** * Represents the semantics of a name in the index. * @since 4.0 * * @noextend This interface is not intended to be extended by clients. * @noimplement This interface is not intended to be implemented by clients. */ public interface IIndexBinding extends IBinding { IIndexBinding[] EMPTY_INDEX_BINDING_ARRAY = {}; /** * Returns the qualified name of this binding as array of strings. */ String[] getQualifiedName(); /** * Returns whether the scope of the binding is file-local. A file local * binding is private to an index and should not be adapted to a binding * in another index. */ boolean isFileLocal() throws CoreException; /** * Returns the file this binding is local to, or <code>null</code> for global * bindings. * A binding is local if a file has a separate instances of the binding. This * is used to model static files, static variables. */ IIndexFile getLocalToFile() throws CoreException; /** * @since 5.1 */ @Override IIndexBinding getOwner(); }
32.596154
82
0.658407
a3ee54c99697cbefe2a88283c5e7b717c0ee8317
360
// // InvalidArgumentException.java // BWAVParser // // Created by Robert La Ferla on 1/24/06. // Copyright 2006 Harvard University. All rights reserved. // package edu.harvard.hcl.hclaps.util; /** * @author Robert La Ferla */ public class InvalidArgumentException extends Exception { public InvalidArgumentException(String str) { super(str); } }
18
59
0.725
55ef2902930f55cebe6084241bc49d82cd8fe0d6
1,968
package com.fichajespi.specifications; import java.time.LocalDate; import java.time.LocalTime; import org.springframework.data.jpa.domain.Specification; import org.springframework.stereotype.Component; import com.fichajespi.entity.Permiso; import com.fichajespi.specifications.common.CommonSpecificationImpl; import com.fichajespi.specifications.common.SpecificationHelper; @Component public final class PermisoSpecifications extends CommonSpecificationImpl<Permiso> { public Specification<Permiso> diaDesde(LocalDate dia) { return (root, query, builder) -> builder .greaterThanOrEqualTo(root.get("dia"), dia); } public Specification<Permiso> diaHasta(LocalDate dia) { return (root, query, builder) -> builder .lessThanOrEqualTo(root.get("dia"), dia); } public Specification<Permiso> horaInicioDesde(LocalTime time) { return (root, query, builder) -> builder .greaterThanOrEqualTo(root.get("horaInicio"), time); } public Specification<Permiso> horaInicioHasta(LocalTime time) { return (root, query, builder) -> builder .lessThanOrEqualTo(root.get("horaInicio"), time); } public Specification<Permiso> horaFinDesde(LocalTime time) { return (root, query, builder) -> builder .greaterThanOrEqualTo(root.get("horaFin"), time); } public Specification<Permiso> horaFinHasta(LocalTime time) { return (root, query, builder) -> builder .lessThanOrEqualTo(root.get("horaFin"), time); } public Specification<Permiso> descripcionContains(String expression) { return (root, query, builder) -> builder .like(root.get("descripcion"), SpecificationHelper.contains(expression)); } public Specification<Permiso> estadoContains(String expression) { return (root, query, builder) -> builder .like(root.get("estado"), SpecificationHelper.contains(expression)); } // public Specification<Permiso> isAprobada(Boolean b) { // return (root, query, builder) -> builder // .equal(root.get("aprobado"), b); // } }
31.741935
83
0.752541
0e3a35095b307d55639e8d6dd6ef8df48ddb3fd7
573
package co.paystack.android; import co.paystack.android.api.model.TransactionApiResponse; public class Transaction { private String id; private String reference; void loadFromResponse(TransactionApiResponse t) { if (t.hasValidReferenceAndTrans()) { this.reference = t.reference; this.id = t.trans; } } String getId() { return id; } public String getReference() { return reference; } boolean hasStartedOnServer() { return (reference != null) && (id != null); } }
19.758621
60
0.61082
a395cd0f889aeb4065e77795400098d2d50375bc
2,478
/* * Copyright 2014 Realm 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 io.realm.entities; import java.util.Date; import io.realm.RealmObject; import io.realm.annotations.Index; public class Dog extends RealmObject { public static final String CLASS_NAME = "Dog"; public static final String FIELD_NAME = "name"; public static final String FIELD_AGE = "age"; public static final String FIELD_HEIGHT = "height"; public static final String FIELD_WEIGHT = "weight"; public static final String FIELD_BIRTHDAY = "birthday"; public static final String FIELD_HAS_TAIL = "hasTail"; @Index private String name; private long age; private float height; private double weight; private boolean hasTail; private Date birthday; private Owner owner; public Dog() { } public Dog(String name) { this.name = name; } public Dog(String name, long age) { this.name = name; this.age = age; } public Owner getOwner() { return owner; } public void setOwner(Owner owner) { this.owner = owner; } public Date getBirthday() { return birthday; } public void setBirthday(Date birthday) { this.birthday = birthday; } public boolean isHasTail() { return hasTail; } public void setHasTail(boolean hasTail) { this.hasTail = hasTail; } public double getWeight() { return weight; } public void setWeight(double weight) { this.weight = weight; } public float getHeight() { return height; } public void setHeight(float height) { this.height = height; } public long getAge() { return age; } public void setAge(long age) { this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
22.324324
75
0.641646
1d94b1a90f75a11370e1f4424848b98fbe1dcfeb
545
package com.company; import java.util.Scanner; public class Question_22 { public static void main(String[] args) { System.out.print("Enter a value : "); Scanner in = new Scanner(System.in); int a = in.nextInt(); System.out.print("Enter b value : "); int b = in.nextInt(); int gcd = 1; for (int i = 1 ; i <= a && i <= b ; i++){ if (a % i == 0 && b % i == 0){ gcd = i; } } System.out.println("The hcf value is : " + gcd); } }
27.25
56
0.47156
8130310a98f3e4f6430e234fdb6e382df2d15b8f
1,200
/* * $Id: TreePanelListener.java,v 1.1 2004/03/25 18:39:54 edankert Exp $ * * Copyright (C) 2002, Cladonia Ltd. All rights reserved. * * This software is the proprietary information of Cladonia Ltd. * Use is subject to license terms. */ package com.cladonia.schema.viewer; import java.awt.event.MouseEvent; import java.util.EventListener; /** * Allows for listening to Tree Panel mouse and selection events. * * @version $Revision: 1.1 $, $Date: 2004/03/25 18:39:54 $ * @author Dogsbay */ public interface TreePanelListener extends EventListener { /** * Called when a node has been right clicked. * * @param event the mouse event for the right clicked node. * @param node the selected node. */ public void popupTriggered( MouseEvent event, SchemaNode node); /** * Called when a node has been double clicked. * * @param event the mouse event for the right clicked node. * @param node the selected node. */ public void doubleClicked( MouseEvent event, SchemaNode node); /** * Called when a node has been selected. * * @param node the selected node. */ public void selectionChanged( SchemaNode node); }
27.272727
72
0.678333
a3df630e7be1981da3ef30160a78a5816818b477
2,253
package de.presti.ree6.commands.impl.community; import club.minnced.discord.webhook.send.WebhookEmbed; import club.minnced.discord.webhook.send.WebhookEmbedBuilder; import club.minnced.discord.webhook.send.WebhookMessageBuilder; import de.presti.ree6.bot.BotInfo; import de.presti.ree6.bot.Webhook; import de.presti.ree6.commands.Category; import de.presti.ree6.commands.Command; import de.presti.ree6.main.Main; import net.dv8tion.jda.api.entities.Guild; import net.dv8tion.jda.api.entities.Member; import net.dv8tion.jda.api.entities.Message; import net.dv8tion.jda.api.entities.TextChannel; import net.dv8tion.jda.api.interactions.InteractionHook; import java.awt.*; public class Rainbow extends Command { public Rainbow() { super("rainbow", "Search for Rainbow Mates across Server!", Category.COMMUNITY, new String[] { "r6" , "rainbowsixsiege"}); } @Override public void onPerform(Member sender, Message messageSelf, String[] args, TextChannel m, InteractionHook hook) { deleteMessage(messageSelf); if(!Main.sqlWorker.hasRainbowSetuped(m.getGuild().getId())) { sendMessage("Rainbow Mate searcher isn't setuped!\nAsk a Admin to set it up with "+ Main.sqlWorker.getSetting(sender.getGuild().getId(), "chatprefix").getStringValue() + "setup r6", 5, m, hook); return; } WebhookMessageBuilder wm = new WebhookMessageBuilder(); wm.setAvatarUrl(BotInfo.botInstance.getSelfUser().getAvatarUrl()); wm.setUsername("Ree6 R6 Mate searcher!"); WebhookEmbedBuilder em = new WebhookEmbedBuilder(); em.setColor(Color.GREEN.getRGB()); em.setThumbnailUrl(sender.getUser().getAvatarUrl()); em.setDescription(sender.getUser().getName() + " is searching for Rainbow Mates!"); em.addField(new WebhookEmbed.EmbedField(true, "**Discord Tag**", sender.getUser().getAsTag())); wm.addEmbeds(em.build()); for(Guild g : BotInfo.botInstance.getGuilds()) { if(Main.sqlWorker.hasRainbowSetuped(g.getId())) { String[] info = Main.sqlWorker.getRainbowHooks(g.getId()); Webhook.sendWebhook(null, wm.build(), Long.parseLong(info[0]), info[1]); } } } }
39.526316
206
0.697292
6123459bc0958d3f96911f661b17a2c0eccc2d08
8,817
package de.triology.cas.services; import de.triology.cas.oidc.services.CesOAuthServiceFactory; import de.triology.cas.oidc.services.CesOIDCServiceFactory; import de.triology.cas.services.dogu.CesDoguServiceFactory; import de.triology.cas.services.dogu.CesServiceCreationException; import org.apereo.cas.services.RegexRegisteredService; import org.apereo.cas.services.RegisteredService; import java.net.URI; import java.util.ArrayList; import java.util.List; import java.util.Set; import java.util.stream.Collectors; /** * The stage in which a {@link CesServicesManager} operates in production. * Services accesible via CAS ({@link RegisteredService}s) are queried from a {@link Registry}. * For each Dogu that is accessible via CAS, one {@link RegisteredService} is returned. An additional service allows * CAS to access itself. * For each OAuth client that is accessuble via CAS, one {@link RegisteredService} is returned. An additional service * for the OAuth callback is also created. */ class CesServicesManagerStageProductive extends CesServicesManagerStage { private String fqdn; private Registry registry; private List<CesServiceData> persistentServices; public final CesOAuthServiceFactory oAuthServiceFactory; public final CesOIDCServiceFactory oidcServiceFactory; public final CesDoguServiceFactory doguServiceFactory; private boolean initialized = false; CesServicesManagerStageProductive(CesServiceManagerConfiguration managerConfig, Registry registry) { super(managerConfig); this.registry = registry; this.persistentServices = new ArrayList<>(); this.doguServiceFactory = new CesDoguServiceFactory(); this.oAuthServiceFactory = new CesOAuthServiceFactory(); this.oidcServiceFactory = new CesOIDCServiceFactory(); } /** * Initialize the registered services found in registry. * This is synchronized because otherwise two parallel calls could lead * to multiple initializations and an inconsistent state (e.g. cas-service multiple times). * Parallel calls can happen since we call {@code initRegisteredServices()} in {@link #getRegisteredServices()}. * This will not be an performance issue because this method is only called once, after startup. */ @Override protected synchronized void initRegisteredServices() { if (isInitialized()) { log.info("Already initialized CesServicesManager. Doing nothing."); return; } log.debug("Cas started in production stage. Only installed dogus can get an ST."); fqdn = registry.getFqdn(); addPersistentServices(); synchronizeServicesWithRegistry(); registerChangeListener(); initialized = true; log.debug("Finished initialization of registered services"); } private boolean isInitialized() { return initialized; } @Override protected void updateRegisteredServices() { if (isInitialized()) { synchronizeServicesWithRegistry(); } else { initRegisteredServices(); } } /** * Synchronize services from {@link #registry} to <code>registeredServices</code>. * That is, remove the ones that are not present in{@link #registry} and add the ones that are only present * in {@link #registry} to <code>registeredServices</code>. */ private void synchronizeServicesWithRegistry() { log.debug("Synchronize services with registry"); List<CesServiceData> newServices = new ArrayList<>(persistentServices); newServices.addAll(registry.getInstalledCasServiceAccountsOfType(RegistryEtcd.SERVICE_ACCOUNT_TYPE_OAUTH, oAuthServiceFactory)); newServices.addAll(registry.getInstalledCasServiceAccountsOfType(RegistryEtcd.SERVICE_ACCOUNT_TYPE_OIDC, oidcServiceFactory)); List<String> serviceAccountServices = newServices.stream().map(CesServiceData::getName).collect(Collectors.toList()); List<CesServiceData> doguServices = registry.getInstalledDogusWhichAreUsingCAS(doguServiceFactory); newServices.addAll(doguServices.stream().filter(service -> !serviceAccountServices.contains(service.getName())).collect(Collectors.toList())); synchronizeServices(newServices); log.info("Loaded {} services:", registeredServices.size()); registeredServices.values().forEach(e -> log.debug("[{}]", e)); } /** * Detects when a new dogu is installed or an existing one is removed */ private void registerChangeListener() { log.debug("Entered registerChangeListener"); registry.addDoguChangeListener(() -> { log.debug("Registered change in /dogu"); synchronizeServicesWithRegistry(); }); } /** * Creates and registers a new service for an given name */ void addNewService(CesServiceData serviceData) { String serviceName = serviceData.getName(); log.debug("Add new service: {}", serviceName); try { addNewService(serviceName, serviceData); } catch (CesServiceCreationException e) { log.error("Failed to create service [{}]. Skip service creation - {}", serviceName, e.toString()); } } /** * Creates and registers a new service for an given name */ void addNewService(String serviceName, CesServiceData serviceData) throws CesServiceCreationException { try { URI logoutUri = registry.getCasLogoutUri(serviceName); RegexRegisteredService service = serviceData.getFactory().createNewService(createId(), fqdn, logoutUri, serviceData); addNewService(service); } catch (GetCasLogoutUriException e) { log.debug("GetCasLogoutUriException: CAS logout URI of service {} could not be retrieved: {}", serviceName, e.toString()); log.info("Adding service without CAS logout URI"); RegexRegisteredService service = serviceData.getFactory().createNewService(createId(), fqdn, null, serviceData); addNewService(service); } } /** * Synchronize services from <code>newServices</code> to <code>registeredServices</code>. * That is, remove the ones that are not present in <code>newServices</code> and add the ones that are only present * in <code>newServices</code> to <code>registeredServices</code>. */ private void synchronizeServices(List<CesServiceData> newServiceNames) { removeServicesThatNoLongerExist(newServiceNames); addServicesThatDoNotExistYet(newServiceNames); } /** * First operation of {@link #synchronizeServices(List)}: Remove Services that are not present in * <code>newServices</code> from <code>registeredServices</code>. */ private void removeServicesThatNoLongerExist(List<CesServiceData> newServiceNames) { List<String> newServicesIdentifiers = newServiceNames.stream() .map(CesServiceData::getIdentifier) .collect(Collectors.toList()); List<String> toBeRemovedServices = registeredServices.values() .stream().map(RegisteredService::getName) .filter(serviceName -> !newServicesIdentifiers.contains(serviceName)) .collect(Collectors.toList()); registeredServices.values().stream() .filter(service -> toBeRemovedServices.contains(service.getName())) .forEach(service -> registeredServices.remove(service.getId())); } /** * Second operation of {@link #synchronizeServices(List)}: Add services that are only present in * <code>newServices</code> to <code>registeredServices</code>. */ private void addServicesThatDoNotExistYet(List<CesServiceData> newServiceNames) { Set<String> existingServiceNames = registeredServices.values().stream().map(RegisteredService::getName).collect(Collectors.toSet()); Set<String> newServices = newServiceNames.stream() .map(CesServiceData::getIdentifier) .filter(serviceName -> !existingServiceNames.contains(serviceName)) .collect(Collectors.toSet()); newServiceNames.stream().filter(service -> newServices.contains(service.getIdentifier())) .forEach(this::addNewService); } /** * persistent services will not be removed */ public void addPersistentServices() { //This is necessary for the oauth workflow log.info("Creating cas service for oauth/oidc workflow"); addNewService(doguServiceFactory.createCASService(createId(), fqdn)); persistentServices.add(new CesServiceData(CesDoguServiceFactory.SERVICE_CAS_IDENTIFIER, doguServiceFactory)); } }
44.756345
150
0.699104
aba4d8b8d2cc9ca499e89cb91dc39b2a030e8641
2,874
package cz.xtf.radanalytics.db.postgresdb; import java.util.HashMap; import java.util.Map; import cz.xtf.openshift.OpenShiftUtil; import cz.xtf.openshift.OpenShiftUtils; import cz.xtf.radanalytics.configuration.RadanalyticsConfiguration; import cz.xtf.radanalytics.db.BaseDBDeployment; import cz.xtf.radanalytics.db.entity.OpenshiftDB; import cz.xtf.radanalytics.util.TestHelper; import lombok.extern.slf4j.Slf4j; @Slf4j public class PostgresDB extends BaseDBDeployment { private static final OpenShiftUtil openshift = OpenShiftUtils.master(); private static final String DEFAULT_POSTGRE_SERVICE_NAME = "postgresql"; private static final String POSTGRESQL_PERSISTENT_TEMPLATE_JSON = "postgresql-ephemeral-template.json"; private static final String RESOURCES_WORKDIR = "db"; private static String POSTGRES_PERSISTENT_TEMPLATE = null; public static OpenshiftDB deployEphemeral(String postgresqlUser, String postgresqlPassword, String postgresqlDatabase) { if (POSTGRES_PERSISTENT_TEMPLATE == null) { POSTGRES_PERSISTENT_TEMPLATE = TestHelper.downloadAndGetResources( RESOURCES_WORKDIR, POSTGRESQL_PERSISTENT_TEMPLATE_JSON, RadanalyticsConfiguration.templatePostgresEphemeralUrl()); } return deployPostgresDB(POSTGRES_PERSISTENT_TEMPLATE, postgresqlUser, postgresqlPassword, postgresqlDatabase, DEFAULT_POSTGRE_SERVICE_NAME, null, null, null, null); } private static OpenshiftDB deployPostgresDB(String templatePath, String postgresqlUser, String postgresqlPassword, String postgresqlDatabase, String postgresServiceName, String namespace, String voluemCapacity, String memoryLimit, String postgresqlVersion) { Map<String, String> params = new HashMap(); params.put("POSTGRESQL_USER", postgresqlUser); params.put("POSTGRESQL_PASSWORD", postgresqlPassword); params.put("POSTGRESQL_DATABASE", postgresqlDatabase); params.put("DATABASE_SERVICE_NAME", postgresServiceName); params.put("NAMESPACE", namespace); params.put("VOLUME_CAPACITY", voluemCapacity); params.put("MEMORY_LIMIT", memoryLimit); params.put("POSTGRESQL_VERSION", postgresqlVersion); if (postgresServiceName == null) { postgresServiceName = DEFAULT_POSTGRE_SERVICE_NAME; } deploy(DEFAULT_POSTGRE_SERVICE_NAME, templatePath, params); OpenshiftDB db = new OpenshiftDB(); db.setUsername(postgresqlUser); db.setPassword(postgresqlPassword); db.setAdminUsername(postgresqlUser); db.setAdminPassword(postgresqlPassword); db.setDbName(postgresqlDatabase); db.setDeploymentConfigName(postgresServiceName); db.setConnectionUrl("postgresql://" + DEFAULT_POSTGRE_SERVICE_NAME + ":5432/"); return db; } public static void restartPostgres(String name) { if (name == null || name.isEmpty()) { restartPod(DEFAULT_POSTGRE_SERVICE_NAME); } else { restartPod(name); } } }
33.418605
121
0.789144
6909cdff60cf0051f09847de0f9f9298e1927c58
284
package example.repo; import example.model.Customer1116; import java.util.List; import org.springframework.data.repository.CrudRepository; public interface Customer1116Repository extends CrudRepository<Customer1116, Long> { List<Customer1116> findByLastName(String lastName); }
21.846154
84
0.830986
40504a8fbbfa584fdbe9ac6aa91ca4cbe7faf6cd
1,520
package cn.edu.zucc.pb.servletbasic; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.PrintWriter; /** * @author pengbin * @version 1.0 * @date 2020-03-03 16:05 */ @WebServlet(name = "EchoServlet", urlPatterns = {"/echo"}, loadOnStartup = 1) public class EchoServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setStatus(HttpServletResponse.SC_OK); response.setContentType("text/plain"); PrintWriter out = response.getWriter(); out.println("I got your post"); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String isError = request.getParameter("error"); if("true".equals(isError)){ throw new RuntimeException("I'am an exception"); } String browser = request.getHeader("User-Agent"); response.setStatus(HttpServletResponse.SC_OK); response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<HTML><HEAD><TITLE>Simple servlet"); out.println("</TITLE></HEAD><BODY>"); out.println ("Browser details: " + browser); out.println("</BODY></HTML>"); } }
38
122
0.702632
44fc1724b8e2bdd8274f8de4342d724b423e6500
695
package com.xlaser4j.opening.modules.sys.service.impl; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.xlaser4j.opening.modules.sys.entity.SysRoleMenuDO; import com.xlaser4j.opening.modules.sys.mapper.SysRoleMenuMapper; import com.xlaser4j.opening.modules.sys.service.ISysRoleMenuService; import org.springframework.stereotype.Service; /** * <p> * 角色与菜单对应关系 服务实现类 * </p> * * @package: com.xlaser4j.opening.modules.sys.service.impl * @author: Elijah.D * @time: 2018/10/11 19:43 * @description: * @modified: Elijah.D */ @Service public class SysRoleMenuServiceImpl extends ServiceImpl<SysRoleMenuMapper, SysRoleMenuDO> implements ISysRoleMenuService { }
30.217391
122
0.791367
de2a635c70008509afd61b0cd9e5c3235948122b
1,336
/* CS-211-001 * ------------------------------------------------------------------------------- * Name: Michael Surbey / G#: G00495157 / Assignment: project #2 / Date: 12/5 * ------------------------------------------------------------------------------- * Honor Code Statement: I recieved no assistance on this assignment that * violates the ethical guidelines set forth by the professor and class syllabus. * ------------------------------------------------------------------------------- * References: * * ------------------------------------------------------------------------------- * Comments: * Overrides compareTo to take in a string option (user selected) * ------------------------------------------------------------------------------- * Psedocode: * * ------------------------------------------------------------------------------- * NOTE: width of source code is < 80 characters to facilitate printing * ------------------------------------------------------------------------------- */ /** * @author mikesurbey * interface */ public interface ComparableForm extends Comparable<Object> { /** * override compare to, to accept a string option * @param option - user selected option * @param form - FormEntry object * @return int */ public int compareTo(String option, FormEntry form); }
39.294118
82
0.402695
e9bb105dfd394332fdb8631bd950991359d20572
3,208
/* * Copyright 2012 JBoss 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 org.uberfire.client.workbench.widgets.dnd; import com.google.gwt.user.client.ui.IsWidget; import org.uberfire.client.workbench.model.PanelDefinition; import org.uberfire.client.workbench.model.PartDefinition; import org.uberfire.shared.mvp.PlaceRequest; /** * The context of a drag and drop operation within the Workbench. */ public class WorkbenchDragContext { private final PlaceRequest place; private final PartDefinition sourcePart; private final PanelDefinition sourcePanel; private final String title; private final IsWidget titleDecoration; private final IsWidget widget; private Integer height; private Integer width; private Integer minHeight; private Integer minWidth; public WorkbenchDragContext( final PlaceRequest place, final PartDefinition sourcePart, final PanelDefinition sourcePanel, final String title, final IsWidget titleDecoration, final IsWidget widget, final Integer height, final Integer width, final Integer minHeight, final Integer minWidth ) { this.place = place; this.sourcePart = sourcePart; this.sourcePanel = sourcePanel; this.title = title; this.titleDecoration = titleDecoration; this.widget = widget; this.height = height; this.width = width; this.minHeight = minHeight; this.minWidth = minWidth; } /** * @return the place */ public PlaceRequest getPlace() { return this.place; } /** * @return the sourcePart */ public PartDefinition getSourcePart() { return sourcePart; } /** * @return the sourcePanel */ public PanelDefinition getSourcePanel() { return sourcePanel; } /** * @return the title decoration widget */ public IsWidget getTitleDecoration() { return titleDecoration; } public String getTitle() { return title; } public IsWidget getWidget() { return widget; } public final Integer getHeight() { return height; } public final Integer getWidth() { return width; } public final Integer getMinHeight() { return minHeight; } public final Integer getMinWidth() { return minWidth; } }
28.140351
80
0.613155
2df802f3b52ee3c005a5003fc1711025bbff068d
256
package com.bosssoft.hr.train.j2se.basic.example.socket; /** * @description: 负责 Socket 的初始化 * @author: lwh * @create: 2020/11/5 14:46 * @version: v1.0 **/ public interface Starter { /** * socket 初始化工作 ip指定 端口分配 等 */ void start(); }
17.066667
56
0.613281
12fd65b7481ef1f137536ec562948367852cd017
662
package com.springbootlog; import org.apache.logging.log4j.Level; import org.apache.logging.log4j.core.Logger; import org.apache.logging.log4j.core.LoggerContext; import org.apache.logging.log4j.message.MessageFactory; /** * 自定义日志级别 * @author wxy */ public class CustomizeLogger extends Logger{ private static final Level TRADE = Level.getLevel("Customize"); protected CustomizeLogger(LoggerContext context, String name, MessageFactory messageFactory) { super(context, name, messageFactory); } /** * 输出自定义日志 * @param message */ public void customize(String message) { super.log(TRADE, message); } }
23.642857
98
0.712991
2e45993a5836e20e4d9a05bae90c9a1c75f46120
6,410
/* * MIT License * * Copyright (c) 2020 Igram, d.o.o. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package rs.igram.kiribi.net.natt; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.Inet6Address; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.NetworkInterface; import java.net.SocketAddress; import java.net.SocketException; import java.net.UnknownHostException; import java.util.concurrent.Future; import java.util.logging.Logger; import rs.igram.kiribi.net.Address; import rs.igram.kiribi.net.NetworkExecutor; import static rs.igram.kiribi.io.ByteUtils.*; import static java.util.logging.Level.*; /** * Support class providing methods for a NATT server. * * @author Michael Sargent */ abstract class NATT { private static final Logger LOGGER = Logger.getLogger(NATT.class.getName()); static final byte NATT_PROTOCOL = 1; // natt protocol static final byte KAP_PROTOCOL = 2; // keep alive protocol static final byte RMP_PROTOCOL = 3; // rmp protocol static final byte[] KA_DATA = {KAP_PROTOCOL, 0}; static final byte REG = 1; // register - kiribi address static final byte CON = 2; // connection request - kiribi address static final byte TUN = 3; // tunnel request - remote socket address static final byte ADR = 4; // register response - remote socket address static final byte ADC = 5; // connection response - remote socket address static final byte ERR = 7; static final byte SYN = 1; static final byte ACK = 2; static final byte FIN = 3; // offsets static int OFF_ID = 1; static int OFF_CMD = 9; static int OFF_DATA = 10; // server ports /** Default server port. */ public static final int SERVER_PORT = 6732; static final int KA_PORT = 6733; static final long KA_INTERVAL = 24*1000; //static final DatagramPacket KA_PACKET = new DatagramPacket(KA_DATA, 2, SERVER_ADDRESS); static final int PACKET_SIZE = 1472; // linux - has the smallest default max buffer size // to change on linux: sysctl -w net.core.rmem_max=26214400 static final int MAX_UDP_BUF_SIZE = 131071; DatagramSocket socket; Future<?> reader; /** * Instantiates a new <code>NATT</code> instance. */ protected NATT() {} /** * Starts this <code>NATT</code> instance. * * @param addr The inet socket address to listen on. * @throws SocketException if there was a preblem starting this NAT server. */ public void start(InetSocketAddress addr) throws SocketException { var executor = new NetworkExecutor(); executor.onShutdown(6, this::shutdown); socket = new DatagramSocket(addr); socket.setReceiveBufferSize(MAX_UDP_BUF_SIZE); socket.setSendBufferSize(MAX_UDP_BUF_SIZE); reader = executor.submit(this::read); } abstract void process(DatagramPacket p); void read() { while(!Thread.currentThread().isInterrupted()){ var buf = new byte[PACKET_SIZE]; var p = new DatagramPacket(buf, PACKET_SIZE); try{ socket.receive(p); process(p); }catch(SocketException e){ LOGGER.log(FINER, "Socket closed"); break; }catch(IOException e){ LOGGER.log(SEVERE, e.toString(), e); } } } void write(DatagramPacket p) { try{ socket.send(p); }catch(IOException e){ LOGGER.log(SEVERE, e.toString(), e); } } void write(byte[] buf, SocketAddress address) { try{ socket.send(new DatagramPacket(buf, buf.length, address)); }catch(IOException e){ LOGGER.log(SEVERE, e.toString(), e); } } static void id(byte[] b, long id) { put(b, OFF_ID, id); } static void cmd(byte[] b, byte cmd) { b[OFF_CMD] = cmd; } static void protocol(byte[] b, byte protocol) { b[0] = protocol; } static void address(byte[] b, Address address) { System.arraycopy(address.encodeUnchecked(), 0, b, OFF_DATA, 20); } static void inet(byte[] b, SocketAddress address) { var inet = ((InetSocketAddress)address); if(inet.getAddress() instanceof Inet6Address){ System.arraycopy(inet.getAddress().getAddress(), 0, b, OFF_DATA, 16); }else{ b[OFF_DATA] = (byte)0xff; b[OFF_DATA + 1] = (byte)0xff; System.arraycopy(inet.getAddress().getAddress(), 0, b, OFF_DATA + 2, 4); for(int i = OFF_DATA + 6; i < OFF_DATA + 16; i++) b[i] = 0; } put(b, OFF_DATA + 16, inet.getPort()); } static long id(byte[] b) { return getLong(b, OFF_ID); } static byte cmd(byte[] b) { return b[OFF_CMD]; } static byte protocol(byte[] b) { return b[0]; } static Address address(byte[] b) { return new Address(extract(b, OFF_DATA, 20)); } static SocketAddress inet(byte[] src) throws Exception { byte[] inet = null; if(src[OFF_DATA] == (byte)0xff && src[OFF_DATA + 1] == (byte)0xff){ inet = extract(src, OFF_DATA + 2, 4); }else{ inet = extract(src, OFF_DATA, 16); } var add = InetAddress.getByAddress(inet); var port = getInt(src, OFF_DATA + 16); return new InetSocketAddress(add, port); } /** * Shuts down this <code>NATT</code> instance. */ public void shutdown() { try{ if(reader != null) reader.cancel(true); if(socket != null) socket.close(); }catch(Throwable e) { // ignore } } }
29.539171
91
0.676287
e73ea6abb42f541075095546d30db7580f66fb79
2,918
package com.pulsar.func.client; import com.pulsar.func.constant.CommonConstant; import org.apache.pulsar.client.api.*; import org.apache.pulsar.client.impl.PulsarClientImpl; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.concurrent.TimeUnit; /** * pulsar client builder * * @author pidan * @date 2022/6/5 16:31 */ public class PulsarClientBuilder { private static final Logger logger = LoggerFactory.getLogger(PulsarClientBuilder.class); private static PulsarClient client; private static final String PULSAR_SERVER_URL = "pulsar://localhost:6650"; private static PulsarClientBuilder instance = new PulsarClientBuilder(); public static PulsarClientBuilder getInstance() { if (client == null) { try { client = PulsarClient.builder().serviceUrl(PULSAR_SERVER_URL).build(); } catch (PulsarClientException e) { e.printStackTrace(); } } return instance; } /** * build a producer which schema is String * * @param topic * @return */ public Producer<String> buildProducer(String topic) { try { return client.newProducer(Schema.STRING) .topic(topic) .batchingMaxPublishDelay(CommonConstant.BATCHING_MAX_PUBLISH_DELAY, TimeUnit.MILLISECONDS) .sendTimeout(CommonConstant.SEND_TIMEOUT, TimeUnit.SECONDS) .blockIfQueueFull(true).create(); } catch (PulsarClientException e) { logger.error("buildProducer failed, topic={}, ex={}", topic, e); } return null; } /** * build a consumer which schema is String * * @param topic * @param subscription * @return */ public Consumer<String> buildConsumer(String topic, String subscription, MessageListener<String> listener) { try { return client.newConsumer(Schema.STRING) .topic(topic) .subscriptionName(subscription) .messageListener(listener) .subscribe(); } catch (PulsarClientException e) { logger.error("build consumer failed, topic={},subscription={} ex={}", topic, subscription, e); } return null; } public enum Topic { /** * 测试 */ DEMO("demo-topic"), ; private String name; Topic(String name) { this.name = name; } public String getName() { return name; } } public enum Subscription { /** * 测试 */ DEMO("demo-subscription"), ; private String name; Subscription(String name) { this.name = name; } public String getName() { return name; } } }
26.288288
112
0.574023
14f25fdb5ae0d3b01661a9051e7f0547e0be3a8d
131
package org.spacehq.mc.protocol.data.game.values.window; public enum CreativeGrabParam implements WindowActionParam { GRAB; }
14.555556
60
0.801527
d8f2748a35a29bf5a8c3a415689fed002f66f4cb
1,628
package org.leetcode.linklist.practice; import org.leetcode.linklist.ListNode; import org.leetcode.utils.Utils; import org.leetcode.utils.NodeUtils; import java.util.Arrays; import java.util.List; /** * 快慢指针实现:https://blog.csdn.net/LiuBo_01/article/details/80341377 */ public class RemoveLastKthNode { public static void main(String[] args) { int[] array = Utils.getArray(10); System.out.println(Arrays.toString(array)); ListNode listNode = NodeUtils.generateNodeList(array); ListNode listNode1 = new RemoveLastKthNode().removeLastKthNodeWithSlowFast(listNode, 3); List<Integer> integers = NodeUtils.returnWithList(listNode1); System.out.println(Arrays.toString(integers.toArray())); } public ListNode removeLastKthNode(ListNode head, int k) { ListNode cur = head; while (cur != null) { k--; cur = cur.next; } if (k == 0) { head = head.next; } if (k < 0) { cur = head; while (++k != 0) { cur = cur.next; } cur.next = cur.next.next; } return head; } /** * TODO 待修改为正确版本 * * @param head * @param k * @return */ public ListNode removeLastKthNodeWithSlowFast(ListNode head, int k) { ListNode slow = head; ListNode fast = head; while (k > 0) { k--; fast = fast.next; } while (fast.next != null) { slow = slow.next; fast = fast.next; } return slow; } }
25.84127
96
0.552826
af5ecb6ec9e5826cd91c4cd06001d06f7ced01ce
1,034
package com.octoperf.kraken.git.storage.events.listener; import com.octoperf.kraken.git.event.GitStatusUpdateEvent; import com.octoperf.kraken.storage.entity.StorageWatcherEvent; import com.octoperf.kraken.tools.event.bus.EventBus; import com.octoperf.kraken.tools.event.bus.EventBusListener; import lombok.AccessLevel; import lombok.experimental.FieldDefaults; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Slf4j @Component @FieldDefaults(level = AccessLevel.PRIVATE, makeFinal = true) final class FireGitStatusUpdateOnStorageEvent extends EventBusListener<StorageWatcherEvent> { EventBus eventBus; @Autowired FireGitStatusUpdateOnStorageEvent(final EventBus eventBus) { super(eventBus, StorageWatcherEvent.class); this.eventBus = eventBus; } @Override protected void handleEvent(final StorageWatcherEvent event) { eventBus.publish(GitStatusUpdateEvent.builder().owner(event.getOwner()).build()); } }
33.354839
93
0.818182
ff79b7c06303c90d66a3d95b8f457ac034576045
21,309
/* // Licensed to DynamoBI Corporation (DynamoBI) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. DynamoBI 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 net.sf.farrago.plannerviz; import java.awt.*; import java.awt.event.*; import java.awt.geom.*; import javax.swing.*; import org.jgrapht.*; import org.jgrapht.ext.*; import org.jgrapht.graph.*; import org.jgrapht.graph.DefaultEdge; import org.jgraph.*; import org.jgraph.graph.*; import org.jgraph.layout.*; import org.jgraph.algebra.*; import org.eigenbase.relopt.*; import org.eigenbase.rel.*; import org.eigenbase.rel.convert.*; import java.util.*; import java.util.logging.*; // TODO jvs 18-Feb-2005: avoid these two dependencies import org.eigenbase.relopt.volcano.*; import org.eigenbase.relopt.hep.*; import net.sf.farrago.trace.*; import java.util.List; /** * FarragoPlanVizualizer uses JGraph to visualize the machinations * of the planner. * * @author John V. Sichi * @version $Id$ */ public class FarragoPlanVisualizer extends JApplet implements RelOptListener, WindowListener { private static final Logger tracer = FarragoTrace.getPlannerVizTracer(); private static final int STATE_CRAWLING = 0; private static final int STATE_STEPPING = 1; private static final int STATE_WALKING = 2; private static final int STATE_RUNNING = 3; private static final int STATE_FLYING = 4; private static final int STATE_CLOSED = 5; private static final int DETAIL_LOGICAL = 1; private static final int DETAIL_PHYSICAL = 2; private static final int DETAIL_PHYSIOLOGICAL = 3; private int state; private int detail; private int currentGenerationNumber; private Object stepVar; private JFrame frame; private JScrollPane scrollPane; private JGraph graph; private GraphLayoutCache graphView; private JGraphModelAdapter graphAdapter; private ListenableDirectedGraph<VisualVertex, VisualEdge> graphModel; private JMenuItem status; private UnionFind physicalEquivMap; private UnionFind logicalEquivMap; private double scale; private Set<RelNode> rels; private Map<Object, VisualVertex> objToVertexMap; private AttributeMap normalVertexAttributes; private AttributeMap newVertexAttributes; private AttributeMap oldVertexAttributes; private AttributeMap finalVertexAttributes; private List<VisualVertex> highlightList; private String ruleName; public FarragoPlanVisualizer() { status = new JMenuItem("Building abstract plan"); JMenuBar menuBar = new JMenuBar(); addStateButton(menuBar, "CRAWL", STATE_CRAWLING); addStateButton(menuBar, "STEP", STATE_STEPPING); addStateButton(menuBar, "WALK", STATE_WALKING); addStateButton(menuBar, "RUN", STATE_RUNNING); addStateButton(menuBar, "FLY", STATE_FLYING); addZoomButton(menuBar, "ZOOMIN", 1.5); addZoomButton(menuBar, "ZOOMOUT", 1.0 / 1.5); frame = new JFrame(); frame.setJMenuBar(menuBar); frame.addWindowListener(this); frame.getContentPane().add(this); frame.setTitle("Plannerviz"); frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); init(); frame.setVisible(true); stepVar = new Object(); state = STATE_CRAWLING; scale = 1; rels = new HashSet<RelNode>(); objToVertexMap = new HashMap<Object, VisualVertex>(); physicalEquivMap = new UnionFind(); logicalEquivMap = new UnionFind(); highlightList = new ArrayList<VisualVertex>(); if (tracer.getLevel() == Level.FINEST) { detail = DETAIL_PHYSIOLOGICAL; } else if (tracer.getLevel() == Level.FINER) { detail = DETAIL_PHYSICAL; } else { detail = DETAIL_LOGICAL; } } private void addStateButton( JMenuBar menuBar, String name, final int newState) { JMenuItem button = new JMenuItem(name); button.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { changeState(newState); } }); menuBar.add(button); } private void addZoomButton( JMenuBar menuBar, String name, final double factor) { JMenuItem button = new JMenuItem(name); button.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { scale *= factor; graph.setScale(scale); } }); menuBar.add(button); } private void changeState(int newState) { synchronized (stepVar) { state = newState; stepVar.notifyAll(); } } // implement WindowListener public void windowClosing(WindowEvent e) { } // implement WindowListener public void windowClosed(WindowEvent e) { changeState(STATE_CLOSED); } // implement WindowListener public void windowOpened(WindowEvent e) { } // implement WindowListener public void windowIconified(WindowEvent e) { } // implement WindowListener public void windowDeiconified(WindowEvent e) { } // implement WindowListener public void windowActivated(WindowEvent e) { } // implement WindowListener public void windowDeactivated(WindowEvent e) { } // implement RelOptListener public void relChosen(RelChosenEvent event) { if (state > STATE_RUNNING) { return; } if (event.getRel() == null) { setStatus("Final plan complete"); return; } if (!includeRel(event.getRel())) { return; } setStatus("Adding node to final plan"); VisualVertex vertex = makeVertex(event.getRel()); paintVertex(vertex, finalVertexAttributes); waitForInput(); } // implement RelOptListener public void relDiscarded(RelDiscardedEvent event) { if (state == STATE_CRAWLING) { setStatus("Discarding " + event.getRel()); updateGraph(); highlightVertex(makeVertex(event.getRel()), oldVertexAttributes); waitForInput(); } rels.remove(event.getRel()); } // implement RelOptListener public void relEquivalenceFound(RelEquivalenceEvent event) { if (state > STATE_RUNNING) { return; } if (detail == DETAIL_LOGICAL) { if (event.isPhysical()) { return; } } else if (detail == DETAIL_PHYSICAL) { if (!event.isPhysical()) { return; } } if (!includeRel(event.getRel())) { return; } UnionFind equivMap; String type; if (event.isPhysical()) { type = "Physical"; equivMap = physicalEquivMap; } else { type = "Logical"; equivMap = logicalEquivMap; } // REVIEW jvs 19-Feb-2005: we intentionally create the UnionFind sets // in this order for Volcano to make sure that the representation // chosen is the equivalence class, not the original rel. Object equivSet = equivMap.find(event.getEquivalenceClass()); Object relSet = equivMap.find(event.getRel()); equivMap.union(equivSet, relSet); if (detail == DETAIL_LOGICAL) { // In this case, we don't visualize subsets, but we do // record their equivalence so that inputs get connected // correctly. if (event.getRel() instanceof RelSubset) { return; } } boolean newRel = rels.add(event.getRel()); if (event.getEquivalenceClass() instanceof HepRelVertex) { // For Hep, we don't care about equivalences much. newRel = true; } if ((state == STATE_CRAWLING) || (!newRel && (state == STATE_STEPPING))) { String newStatus; if (newRel) { newStatus = "New expression added to " + type.toLowerCase() + " equivalence class"; } else { newStatus = type + " equivalence found for " + event.getEquivalenceClass(); } if (ruleName != null) { newStatus += " by rule " + ruleName; } setStatus(newStatus); updateGraph(); highlightVertex(makeVertex(event.getRel()), newVertexAttributes); waitForInput(); } } // implement RelOptListener public void ruleAttempted(RuleAttemptedEvent event) { if (event.isBefore()) { ruleName = event.getRuleCall().getRule().toString(); } else { ruleName = null; } } // implement RelOptListener public void ruleProductionSucceeded(RuleProductionEvent event) { if (state > STATE_RUNNING) { return; } if (state == STATE_CRAWLING) { if (!event.isBefore()) { // already previewed; skip post-display return; } } if (!includeRel(event.getRel())) { return; } String verb; if (!event.isBefore()) { if (!rels.contains(event.getRel())) { // The rel didn't get registered, so it must have // matched an existing one; don't bother showing the // rule production. return; } verb = "produced"; } else { verb = "producing"; } if (state > STATE_WALKING) { updateGraph(); return; } setStatus( "Rule " + event.getRuleCall().getRule() + " " + verb + " new expression " + event.getRel()); updateGraph(); highlightRuleVertices(event); waitForInput(); } private void setStatus(String text) { status.setText(text); for (VisualVertex vertex : highlightList) { paintVertex(vertex, normalVertexAttributes); } highlightList.clear(); } private void highlightRuleVertices(RuleProductionEvent event) { if (!event.isBefore()) { highlightVertex(makeVertex(event.getRel()), newVertexAttributes); if (event.getRuleCall() instanceof HepRuleCall) { return; } } RelNode [] rels = event.getRuleCall().rels; for (RelNode rel : rels) { if (includeRel(rel)) { highlightVertex(makeVertex(rel), oldVertexAttributes); } } } private boolean includeRel(RelNode rel) { if (rel == null) { return false; } if (detail == DETAIL_LOGICAL) { if (isConverterRel(rel)) { return false; } } if (rel instanceof AbstractConverter) { return false; } return true; } private boolean isConverterRel(RelNode rel) { boolean volcano = false; if (volcano) { return (rel instanceof ConverterRel); } else { return false; } } private void highlightVertex(VisualVertex vertex, AttributeMap attributes) { paintVertex(vertex, attributes); highlightList.add(vertex); } private void paintVertex(VisualVertex vertex, AttributeMap map) { DefaultGraphCell cell = graphAdapter.getVertexCell(vertex); if (cell == null) { return; } CellView cellView = graphView.getMapping(cell, true); cellView.changeAttributes(map); graphView.cellViewsChanged(new CellView[]{cellView}); if (!graphView.isVisible(cell)) { graph.scrollCellToVisible(cell); } } private void updateGraph() { if (state != STATE_RUNNING) { graph.setVisible(false); } // update the graph model to reflect current state ++currentGenerationNumber; for (RelNode rel : rels) { VisualVertex v1 = makeVertex(rel); if (rel instanceof RelSubset) { Object set = logicalEquivMap.find(rel); if (set != rel) { VisualVertex v2 = makeVertex(set); makeEdge(v2, v1, ""); } continue; } UnionFind equivMap; if (detail == DETAIL_LOGICAL) { equivMap = logicalEquivMap; } else { equivMap = physicalEquivMap; } Object set = equivMap.find(rel); if ((set != rel) && !(set instanceof HepRelVertex)) { VisualVertex v2 = makeVertex(set); makeEdge(v2, v1, ""); } // converters can lead to cycles around subsets, so // omit the edges for their inputs if (!isConverterRel(rel)) { RelNode[] inputs = rel.getInputs(); for (int i = 0; i < inputs.length; ++i) { Object inputSet = equivMap.find(inputs[i]); if (inputSet instanceof HepRelVertex) { inputSet = ((HepRelVertex) inputSet).getCurrentRel(); } VisualVertex v2 = makeVertex(inputSet); if (inputSet != set) { String label; if (inputs.length > 1) { label = Integer.toString(i); } else { label = ""; } makeEdge(v1, v2, label); } } } } List<Object> recyclingList = new ArrayList<Object>(); // collect obsolete edges for (VisualEdge edge : graphModel.edgeSet()) { if (edge.generationNumber != currentGenerationNumber) { recyclingList.add(edge); } } // dispose of obsolete edges for (Object obj : recyclingList) { graphModel.removeEdge((VisualEdge) obj); } recyclingList.clear(); // collect roots and obsolete vertices List<DefaultGraphCell> roots = new ArrayList<DefaultGraphCell>(); for (VisualVertex vertex : graphModel.vertexSet()) { if (vertex.generationNumber != currentGenerationNumber) { recyclingList.add(vertex); continue; } if (graphModel.inDegreeOf(vertex) == 0) { roots.add(graphAdapter.getVertexCell(vertex)); } } // dispose of obsolete vertices for (Object obj : recyclingList) { VisualVertex visualVertex = (VisualVertex) obj; graphModel.removeVertex(visualVertex); objToVertexMap.remove(visualVertex.obj); } // compute graph layout assert (!roots.isEmpty()); JGraphLayoutAlgorithm layout = new SugiyamaLayoutAlgorithm(); JGraphLayoutAlgorithm.applyLayout(graph, layout, roots.toArray(), null); // SugiyamaLayoutAlgorithm doesn't normalize its output, leading to a // cumulative bias for each round. We compensate for this by computing // the bounding rectangle and applying a corresponding negative // translation. Rectangle2D bounds = graph.getCellBounds(graph.getRoots()); GraphLayoutCache.translateViews( graphView.getCellViews(), -bounds.getX(), -bounds.getY()); graphView.update(graphView.getCellViews()); graph.clearSelection(); if (state != STATE_RUNNING) { graph.setVisible(true); } } private void waitForInput() { synchronized (stepVar) { try { switch (state) { case STATE_CRAWLING: case STATE_STEPPING: stepVar.wait(); break; case STATE_WALKING: stepVar.wait(1000); break; default: break; } } catch (InterruptedException ex) { } } } private VisualVertex makeVertex(Object obj) { VisualVertex vertex = objToVertexMap.get(obj); if (vertex == null) { vertex = new VisualVertex(obj); objToVertexMap.put(obj, vertex); graphModel.addVertex(vertex); } vertex.generationNumber = currentGenerationNumber; return vertex; } private VisualEdge makeEdge(VisualVertex v1, VisualVertex v2, String label) { VisualEdge edge = graphModel.getEdge(v1, v2); if (edge == null) { edge = new VisualEdge(label); graphModel.addEdge(v1, v2, edge); } else { // e.g. self-join if (!edge.toString().contains(label)) { edge.setLabel(edge.toString() + ", " + label); } } edge.generationNumber = currentGenerationNumber; return edge; } public void init() { graphModel = new ListenableDirectedGraph<VisualVertex, VisualEdge>( new DefaultDirectedGraph<VisualVertex, VisualEdge>( new VisualEdgeFactory())); AttributeMap defaultVertexAttributes = JGraphModelAdapter.createDefaultVertexAttributes(); GraphConstants.setBounds( defaultVertexAttributes, new Rectangle2D.Double(50, 50, 200, 30)); normalVertexAttributes = new AttributeMap(); GraphConstants.setBackground( defaultVertexAttributes, Color.GRAY); GraphConstants.setBackground( normalVertexAttributes, Color.GRAY); oldVertexAttributes = new AttributeMap(); GraphConstants.setBackground( oldVertexAttributes, Color.GREEN); finalVertexAttributes = new AttributeMap(); GraphConstants.setBackground( finalVertexAttributes, Color.BLUE); newVertexAttributes = new AttributeMap(); GraphConstants.setBackground( newVertexAttributes, Color.RED); graphAdapter = new JGraphModelAdapter<VisualVertex, VisualEdge>( graphModel, defaultVertexAttributes, JGraphModelAdapter.createDefaultEdgeAttributes(graphModel)); graph = new JGraph(graphAdapter); scrollPane = new JScrollPane(graph); scrollPane.setPreferredSize(new Dimension(500, 500)); scrollPane.setColumnHeaderView(status); graph.setAutoscrolls(true); graphView = graph.getGraphLayoutCache(); getContentPane().add(scrollPane); frame.pack(); } private static class VisualVertex { int generationNumber; final RelNode rel; final String name; final Object obj; VisualVertex(Object obj) { this.obj = obj; if (obj instanceof RelNode) { rel = (RelNode) obj; name = rel.getId() + ":" + rel; } else { rel = null; name = obj.toString(); } } public String toString() { return name; } } private static class VisualEdge extends DefaultEdge { private String label; int generationNumber; VisualEdge( String label) { this.label = label; } public void setLabel(String label) { this.label = label; } public String toString() { return label; } } private static class VisualEdgeFactory implements EdgeFactory<VisualVertex, VisualEdge> { public VisualEdge createEdge( VisualVertex sourceVertex, VisualVertex targetVertex) { return new VisualEdge(""); } } } // End FarragoPlanVisualizer.java
28.795946
80
0.565676
5647414b7d2280910ca2951f4a68a08bb3a61ae4
7,124
package de.fraunhofer.sit.codescan.sootbridge; import java.io.PrintStream; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.eclipse.core.runtime.IConfigurationElement; import org.eclipse.core.runtime.IExtensionRegistry; import org.eclipse.core.runtime.Platform; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import soot.Body; import soot.G; import soot.Local; import soot.PackManager; import soot.Scene; import soot.SceneTransformer; import soot.SootMethod; import soot.Transform; import soot.Unit; import soot.Value; import soot.jimple.Stmt; import soot.jimple.toolkits.ide.icfg.BackwardsInterproceduralCFG; import soot.jimple.toolkits.ide.icfg.BiDiInterproceduralCFG; import soot.jimple.toolkits.ide.icfg.JimpleBasedInterproceduralCFG; import soot.toolkits.graph.BriefUnitGraph; import soot.toolkits.graph.DirectedGraph; import com.google.common.base.Joiner; import de.fraunhofer.sit.codescan.sootbridge.internal.LoggingOutputStream; public class SootRunner { private static final class Transformer<C extends IAnalysisConfiguration> extends SceneTransformer { private final Map<C, Set<ErrorMarker>> analysisConfigToResultingErrorMarkers; private final Map<C, Set<String>> analysisToEntryMethodSignatures; private JimpleBasedInterproceduralCFG icfg; private BackwardsInterproceduralCFG bicfg; private AliasAnalysisManager aliasAnalysisManager; private Transformer( Map<C, Set<ErrorMarker>> analysisConfigToResultingErrorMarkers, Map<C, Set<String>> analysisToEntryMethodSignatures) { this.analysisConfigToResultingErrorMarkers = analysisConfigToResultingErrorMarkers; this.analysisToEntryMethodSignatures = analysisToEntryMethodSignatures; } @Override protected void internalTransform(String phaseName, Map<String, String> options) { for(Map.Entry<C, Set<String>> analysisAndMethodSignatures: analysisToEntryMethodSignatures.entrySet()) { for(final String methodSignature: analysisAndMethodSignatures.getValue()) { final SootMethod m; try { m = Scene.v().getMethod(methodSignature); } catch(RuntimeException e) { LOGGER.debug("Failed to find SootMethod:"+methodSignature); continue; } if(!m.hasActiveBody()) continue; final C analysisConfig = analysisAndMethodSignatures.getKey(); analysisConfig.runAnalysis(new IIFDSAnalysisContext() { public SootMethod getSootMethod() { return m; } public BiDiInterproceduralCFG<Unit,SootMethod> getICFG() { return getOrCreateICFG(); } public IAnalysisConfiguration getAnalysisConfiguration() { return analysisConfig; } @Override public void reportError(ErrorMarker... result) { Set<ErrorMarker> set = analysisConfigToResultingErrorMarkers.get(analysisConfig); if(set==null) { set = new HashSet<ErrorMarker>(); analysisConfigToResultingErrorMarkers.put(analysisConfig, set); } set.addAll(Arrays.asList(result)); } @Override public boolean mustAlias(Stmt stmt, Local l1, Stmt stmt2, Local l2) { return getOrCreateAnalysisManager().mustAlias(stmt, l1, stmt2, l2); } @Override public BiDiInterproceduralCFG<Unit,SootMethod> getBackwardICFG() { return getOrCreateBackwardsICFG(); } @Override public Set<Value> mayAliasesAtExit(Value v, SootMethod owner) { return getOrCreateAnalysisManager().mayAliasesAtExit(v, owner); } private BiDiInterproceduralCFG<Unit, SootMethod> getOrCreateBackwardsICFG() { if(bicfg==null) bicfg = new BackwardsInterproceduralCFG(getOrCreateICFG()); return bicfg; } private AliasAnalysisManager getOrCreateAnalysisManager() { if(aliasAnalysisManager==null) { aliasAnalysisManager = new AliasAnalysisManager(getOrCreateICFG()); } return aliasAnalysisManager; } private JimpleBasedInterproceduralCFG getOrCreateICFG() { if(icfg ==null) { icfg = new JimpleBasedInterproceduralCFG() { @Override protected synchronized DirectedGraph<Unit> makeGraph(Body body) { //we use brief unit graphs such that we warn in situations where //the code only might be safe due to some exceptional flows return new BriefUnitGraph(body); } }; } return icfg; } }); } } } } private final static Logger LOGGER = LoggerFactory.getLogger(SootRunner.class); private static String TRANSFORMER_EXTENSION_POINT_ID ="de.fraunhofer.sit.codescan.sootrunnertransformer"; public static <C extends IAnalysisConfiguration> Map<C, Set<ErrorMarker>> runSoot(final Map<C, Set<String>> analysisToEntryMethodSignatures, String staticSootArgs, String sootClassPath) { final Map<C,Set<ErrorMarker>> analysisConfigToResultingErrorMarkers = new HashMap<C, Set<ErrorMarker>>(); IExtensionRegistry reg = Platform.getExtensionRegistry(); IConfigurationElement[] elements = reg.getConfigurationElementsFor(TRANSFORMER_EXTENSION_POINT_ID); List<PluggableTransformer> transformersBefore = new ArrayList<PluggableTransformer>(); List<PluggableTransformer> transformersAfter = new ArrayList<PluggableTransformer>(); for(IConfigurationElement element : elements){ PluggableTransformer transformer = new PluggableTransformer(element); if(transformer.executeBeforeAnalysis()){ transformersBefore.add(transformer); } else{ transformersAfter.add(transformer); } } for(PluggableTransformer transformer : transformersBefore){ PackManager.v().getPack(transformer.getPack()).add(new Transform(transformer.getPackageName(), transformer.getInstance())); } PackManager.v().getPack("wjtp").add(new Transform("wjtp.vulnanalysis", new Transformer<C>(analysisConfigToResultingErrorMarkers, analysisToEntryMethodSignatures))); for(PluggableTransformer transformer : transformersAfter){ PackManager.v().getPack(transformer.getPack()).add(new Transform(transformer.getPackageName(), transformer.getInstance())); } Set<String> classNames = extractClassNames(analysisToEntryMethodSignatures.values()); String[] args = (staticSootArgs+" -cp "+sootClassPath+" "+Joiner.on(" ").join(classNames)).split(" "); G.v().out = new PrintStream(new LoggingOutputStream(LOGGER, false), true); try { LOGGER.trace("SOOT ARGS:"+Joiner.on(" ").join(args)); soot.Main.main(args); } catch(Throwable t) { LOGGER.error("Error executing Soot",t); G.reset(); } return analysisConfigToResultingErrorMarkers; } private static Set<String> extractClassNames(Collection<Set<String>> values) { Set<String> res = new HashSet<String>(); for(Set<String> methodSignatures: values) { for(String methodSig: methodSignatures) { res.add(methodSig.substring(1,methodSig.indexOf(":"))); } } return res; } }
36.346939
188
0.73498
69dd1586b7ec5f606d2980971bce155d9a80a5ea
2,164
package com.ruoyi.novel.domain; import com.baomidou.mybatisplus.annotation.IdType; import com.baomidou.mybatisplus.annotation.TableField; import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableName; import java.io.Serializable; import java.util.Date; import com.fasterxml.jackson.annotation.JsonFormat; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import com.fasterxml.jackson.databind.ser.std.ToStringSerializer; import lombok.Data; import javax.validation.constraints.NotBlank; /** * * @TableName book */ @TableName(value ="book") @Data public class Book implements Serializable { /** * 小说主键 */ @TableId @JsonSerialize(using= ToStringSerializer.class) private Long id; /** * 作者id */ @JsonSerialize(using= ToStringSerializer.class) private Long authorId; /** * 作者姓名 */ private String authorName; /** * 小说名称 */ @NotBlank(message = "小说名称不能为空!") private String bookName; /** * 小说分类名称 */ private String bookCategory; /** * 小说封面 */ private String picUrl; /** * 作品简介 */ @NotBlank(message = "作品简介不能为空!") private String bookIntro; /** * 作者有话说 */ private String authorSpeak; /** * 作品字数 */ private Integer bookWord; /** * 订阅数 */ private Integer subsNum; /** * 点击量 */ private Long visitCount; /** * 创建时间 */ @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8") private Date createTime; /** * 最新章节id */ @JsonSerialize(using= ToStringSerializer.class) private Long lastChapterId; /** * 最新章节标题 */ private String lastChapterTitle; /** * 更新时间 */ @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8") private Date updateTime; /** * 审核状态, 0:审核中 1:审核通过 2:审核不通过 */ private Integer checkStatus; /** * 完结状态, 0:连载中 1:已完结 */ private Integer bookStatus; @TableField(exist = false) private static final long serialVersionUID = 1L; }
18.184874
68
0.614603