text
stringlengths 10
2.72M
|
|---|
package com.tencent.mm.boot.svg.a.a;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Paint.Cap;
import android.graphics.Paint.Join;
import android.graphics.Paint.Style;
import android.graphics.Path;
import android.os.Looper;
import com.tencent.mm.svg.WeChatSVGRenderC2Java;
import com.tencent.mm.svg.c;
public final class aam extends c {
private final int height = 96;
private final int width = 96;
protected final int b(int i, Object... objArr) {
switch (i) {
case 0:
return 96;
case 1:
return 96;
case 2:
Canvas canvas = (Canvas) objArr[0];
Looper looper = (Looper) objArr[1];
Matrix f = c.f(looper);
float[] e = c.e(looper);
Paint i2 = c.i(looper);
i2.setFlags(385);
i2.setStyle(Style.FILL);
Paint i3 = c.i(looper);
i3.setFlags(385);
i3.setStyle(Style.STROKE);
i2.setColor(-16777216);
i3.setStrokeWidth(1.0f);
i3.setStrokeCap(Cap.BUTT);
i3.setStrokeJoin(Join.MITER);
i3.setStrokeMiter(4.0f);
i3.setPathEffect(null);
c.a(i3, looper).setStrokeWidth(1.0f);
i3 = c.a(i2, looper);
i3.setColor(-14046139);
Path j = c.j(looper);
j.moveTo(0.0f, 0.0f);
j.lineTo(96.0f, 0.0f);
j.lineTo(96.0f, 96.0f);
j.lineTo(0.0f, 96.0f);
j.lineTo(0.0f, 0.0f);
j.close();
canvas.saveLayerAlpha(null, 0, 4);
canvas.drawPath(j, c.a(i3, looper));
canvas.restore();
canvas.save();
Paint a = c.a(i2, looper);
a.setColor(-16777216);
e = c.a(e, 1.0f, 0.0f, 12.0f, 0.0f, 1.0f, 12.0f);
f.reset();
f.setValues(e);
canvas.concat(f);
canvas.saveLayerAlpha(null, 51, 4);
canvas.save();
e = c.a(e, 1.0f, 0.0f, 6.0f, 0.0f, 1.0f, 13.5f);
f.reset();
f.setValues(e);
canvas.concat(f);
canvas.save();
Paint a2 = c.a(a, looper);
Path j2 = c.j(looper);
j2.moveTo(3.6f, 5.1f);
j2.lineTo(3.6f, 39.9f);
j2.lineTo(56.4f, 39.9f);
j2.lineTo(56.4f, 5.1f);
j2.lineTo(3.6f, 5.1f);
j2.close();
j2.moveTo(0.0f, 4.5f);
j2.cubicTo(-2.0290612E-16f, 2.8431458f, 1.3431457f, 1.5f, 3.0f, 1.5f);
j2.lineTo(57.0f, 1.5f);
j2.cubicTo(58.656853f, 1.5f, 60.0f, 2.8431458f, 60.0f, 4.5f);
j2.lineTo(60.0f, 40.5f);
j2.cubicTo(60.0f, 42.156853f, 58.656853f, 43.5f, 57.0f, 43.5f);
j2.lineTo(3.0f, 43.5f);
j2.cubicTo(1.3431457f, 43.5f, -2.7402583E-15f, 42.156853f, 0.0f, 40.5f);
j2.lineTo(0.0f, 4.5f);
j2.close();
WeChatSVGRenderC2Java.setFillType(j2, 1);
canvas.drawPath(j2, a2);
canvas.restore();
canvas.save();
a2 = c.a(a, looper);
j2 = c.j(looper);
j2.moveTo(2.5124738f, 6.5230727f);
j2.lineTo(25.253035f, 23.99735f);
j2.cubicTo(28.055511f, 26.150826f, 31.955736f, 26.150826f, 34.758213f, 23.99735f);
j2.lineTo(57.498775f, 6.5230727f);
j2.lineTo(55.30527f, 3.6685066f);
j2.lineTo(32.56471f, 21.142784f);
j2.cubicTo(31.055685f, 22.30235f, 28.955564f, 22.30235f, 27.446539f, 21.142784f);
j2.lineTo(4.7059765f, 3.6685066f);
j2.lineTo(2.5124738f, 6.5230727f);
j2.close();
WeChatSVGRenderC2Java.setFillType(j2, 1);
canvas.drawPath(j2, a2);
canvas.restore();
canvas.restore();
canvas.restore();
canvas.restore();
c.h(looper);
break;
}
return 0;
}
}
|
package com.example.hp.above;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
public class SudokuActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sudoku);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
public boolean onCreateOptionsMenu(Menu menu) {
return true;
}
public void sudoku_code(View view) {
TextView tv = (TextView) findViewById(R.id.sudoku_code);
tv.setText("// A Backtracking program in C++ to solve Sudoku problem\n" +
"#include <stdio.h>\n" +
" \n" +
"// UNASSIGNED is used for empty cells in sudoku grid\n" +
"#define UNASSIGNED 0\n" +
" \n" +
"// N is used for size of Sudoku grid. Size will be NxN\n" +
"#define N 9\n" +
" \n" +
"// This function finds an entry in grid that is still unassigned\n" +
"bool FindUnassignedLocation(int grid[N][N], int &row, int &col);\n" +
" \n" +
"// Checks whether it will be legal to assign num to the given row,col\n" +
"bool isSafe(int grid[N][N], int row, int col, int num);\n" +
" \n" +
"/* Takes a partially filled-in grid and attempts to assign values to\n" +
" all unassigned locations in such a way to meet the requirements\n" +
" for Sudoku solution (non-duplication across rows, columns, and boxes) */\n" +
"bool SolveSudoku(int grid[N][N])\n" +
"{\n" +
" int row, col;\n" +
" \n" +
" // If there is no unassigned location, we are done\n" +
" if (!FindUnassignedLocation(grid, row, col))\n" +
" return true; // success!\n" +
" \n" +
" // consider digits 1 to 9\n" +
" for (int num = 1; num <= 9; num++)\n" +
" {\n" +
" // if looks promising\n" +
" if (isSafe(grid, row, col, num))\n" +
" {\n" +
" // make tentative assignment\n" +
" grid[row][col] = num;\n" +
" \n" +
" // return, if success, yay!\n" +
" if (SolveSudoku(grid))\n" +
" return true;\n" +
" \n" +
" // failure, unmake & try again\n" +
" grid[row][col] = UNASSIGNED;\n" +
" }\n" +
" }\n" +
" return false; // this triggers backtracking\n" +
"}\n" +
" \n" +
"/* Searches the grid to find an entry that is still unassigned. If\n" +
" found, the reference parameters row, col will be set the location\n" +
" that is unassigned, and true is returned. If no unassigned entries\n" +
" remain, false is returned. */\n" +
"bool FindUnassignedLocation(int grid[N][N], int &row, int &col)\n" +
"{\n" +
" for (row = 0; row < N; row++)\n" +
" for (col = 0; col < N; col++)\n" +
" if (grid[row][col] == UNASSIGNED)\n" +
" return true;\n" +
" return false;\n" +
"}\n" +
" \n" +
"/* Returns a boolean which indicates whether any assigned entry\n" +
" in the specified row matches the given number. */\n" +
"bool UsedInRow(int grid[N][N], int row, int num)\n" +
"{\n" +
" for (int col = 0; col < N; col++)\n" +
" if (grid[row][col] == num)\n" +
" return true;\n" +
" return false;\n" +
"}\n" +
" \n" +
"/* Returns a boolean which indicates whether any assigned entry\n" +
" in the specified column matches the given number. */\n" +
"bool UsedInCol(int grid[N][N], int col, int num)\n" +
"{\n" +
" for (int row = 0; row < N; row++)\n" +
" if (grid[row][col] == num)\n" +
" return true;\n" +
" return false;\n" +
"}\n" +
" \n" +
"/* Returns a boolean which indicates whether any assigned entry\n" +
" within the specified 3x3 box matches the given number. */\n" +
"bool UsedInBox(int grid[N][N], int boxStartRow, int boxStartCol, int num)\n" +
"{\n" +
" for (int row = 0; row < 3; row++)\n" +
" for (int col = 0; col < 3; col++)\n" +
" if (grid[row+boxStartRow][col+boxStartCol] == num)\n" +
" return true;\n" +
" return false;\n" +
"}\n" +
" \n" +
"/* Returns a boolean which indicates whether it will be legal to assign\n" +
" num to the given row,col location. */\n" +
"bool isSafe(int grid[N][N], int row, int col, int num)\n" +
"{\n" +
" /* Check if 'num' is not already placed in current row,\n" +
" current column and current 3x3 box */\n" +
" return !UsedInRow(grid, row, num) &&\n" +
" !UsedInCol(grid, col, num) &&\n" +
" !UsedInBox(grid, row - row%3 , col - col%3, num);\n" +
"}\n" +
" \n" +
"/* A utility function to print grid */\n" +
"void printGrid(int grid[N][N])\n" +
"{\n" +
" for (int row = 0; row < N; row++)\n" +
" {\n" +
" for (int col = 0; col < N; col++)\n" +
" printf(\"%2d\", grid[row][col]);\n" +
" printf(\"\\n\");\n" +
" }\n" +
"}\n" +
" \n" +
"/* Driver Program to test above functions */\n" +
"int main()\n" +
"{\n" +
" // 0 means unassigned cells\n" +
" int grid[N][N] = {{3, 0, 6, 5, 0, 8, 4, 0, 0},\n" +
" {5, 2, 0, 0, 0, 0, 0, 0, 0},\n" +
" {0, 8, 7, 0, 0, 0, 0, 3, 1},\n" +
" {0, 0, 3, 0, 1, 0, 0, 8, 0},\n" +
" {9, 0, 0, 8, 6, 3, 0, 0, 5},\n" +
" {0, 5, 0, 0, 9, 0, 6, 0, 0},\n" +
" {1, 3, 0, 0, 0, 0, 2, 5, 0},\n" +
" {0, 0, 0, 0, 0, 0, 0, 7, 4},\n" +
" {0, 0, 5, 2, 0, 6, 3, 0, 0}};\n" +
" if (SolveSudoku(grid) == true)\n" +
" printGrid(grid);\n" +
" else\n" +
" printf(\"No solution exists\");\n" +
" \n" +
" return 0;\n" +
"}" +
"\n\nOutput:\n" +
"\n" +
" 3 1 6 5 7 8 4 9 2\n" +
" 5 2 9 1 3 4 7 6 8\n" +
" 4 8 7 6 2 9 5 3 1\n" +
" 2 6 3 4 1 5 9 8 7\n" +
" 9 7 4 8 6 3 1 2 5\n" +
" 8 5 1 7 9 2 6 4 3\n" +
" 1 3 8 9 4 7 2 5 6\n" +
" 6 9 2 3 5 1 8 7 4\n" +
" 7 4 5 2 8 6 3 1 9");
}
}
|
package com.tencent.mm.plugin.profile.ui;
import com.tencent.mm.plugin.profile.ui.NormalUserFooterPreference.e;
import com.tencent.mm.pluginsdk.ui.preference.NormalUserHeaderPreference;
class k$10 implements e {
final /* synthetic */ NormalUserHeaderPreference lWF;
final /* synthetic */ k lWx;
k$10(k kVar, NormalUserHeaderPreference normalUserHeaderPreference) {
this.lWx = kVar;
this.lWF = normalUserHeaderPreference;
}
public final void aJ(String str, boolean z) {
this.lWF.bo(str, z);
this.lWF.jX(this.lWx.guS.field_username);
}
}
|
package preExamen;
public class primerProblema {
private String frase;
private int distancia;
public String Salida1 = "";
public String Salida2 = "";
public primerProblema(String nFrase, int nDistancia) {
// TODO Auto-generated constructor stub
frase= nFrase;
distancia=nDistancia;
}
public String cifrarCesar(String frase, int distancia)
{
StringBuilder codigoCesar = new StringBuilder();
distancia = distancia % 26;
for (int i = 0; i < frase.length(); i++) {
if (frase.charAt(i) >= 'a' && frase.charAt(i) <= 'z') {
if ((frase.charAt(i) + distancia) > 'z') {
codigoCesar.append((char) (frase.charAt(i) + distancia - 26));
} else {
codigoCesar.append((char) (frase.charAt(i) + distancia));
}
} else if (frase.charAt(i) >= 'A' && frase.charAt(i) <= 'Z') {
if ((frase.charAt(i) + distancia) > 'Z') {
codigoCesar.append((char) (frase.charAt(i) + distancia - 26));
} else {
codigoCesar.append((char) (frase.charAt(i) + distancia));
}
}
}
return Salida1;
}
public String cifrarCesar(String frase, String alfabeto, int distancia)
{
return Salida2;
}
}
|
package de.johni0702.minecraft.gui.versions.callbacks;
import de.johni0702.minecraft.gui.utils.Event;
import net.minecraft.client.gui.screen.Screen;
public interface OpenGuiScreenCallback {
Event<OpenGuiScreenCallback> EVENT = Event.create((listeners) ->
(screen) -> {
for (OpenGuiScreenCallback listener : listeners) {
listener.openGuiScreen(screen);
}
}
);
void openGuiScreen(Screen screen);
}
|
package com.tt.miniapphost;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.PersistableBundle;
import android.support.v4.app.FragmentActivity;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import com.storage.async.Action;
import com.tt.frontendapiinterface.c;
import com.tt.miniapp.AppbrandApplicationImpl;
import com.tt.miniapp.TTAppbrandTabUI;
import com.tt.miniapp.adsite.AdSiteBrowser;
import com.tt.miniapp.adsite.AdSiteManager;
import com.tt.miniapp.dialog.LoadHelper;
import com.tt.miniapp.errorcode.ErrorCode;
import com.tt.miniapp.manager.AppInfoManager;
import com.tt.miniapp.manager.ForeBackgroundManager;
import com.tt.miniapp.manager.HostSnapShotManager;
import com.tt.miniapp.manager.SchemeEntityHelper;
import com.tt.miniapp.manager.SnapshotManager;
import com.tt.miniapp.process.bridge.InnerHostProcessBridge;
import com.tt.miniapp.shortcut.ShortcutService;
import com.tt.miniapp.thread.ThreadUtil;
import com.tt.miniapp.util.ChannelUtil;
import com.tt.miniapp.util.TimeLogger;
import com.tt.miniapp.util.timeline.MpTimeLineReporter;
import com.tt.miniapphost.entity.AppInfoEntity;
import com.tt.miniapphost.game.GameModuleController;
import com.tt.miniapphost.game.GameNotReadyActivityProxy;
import com.tt.miniapphost.host.HostDependManager;
import com.tt.miniapphost.process.HostProcessBridge;
import com.tt.miniapphost.util.ProcessUtil;
import com.tt.miniapphost.view.BaseActivity;
public class MiniappHostBase extends BaseActivity {
private boolean isFilledUpContainer;
protected IActivityProxy mActivityProxy;
private int mDefaultFragmentBackground;
private boolean mIsOnActivityStackTop;
private static void startCacheSpecialCrossProcessData() {
ThreadUtil.runOnWorkThread(new Action() {
public final void act() {
HostProcessBridge.getLoginCookie();
HostProcessBridge.getNetCommonParams();
HostProcessBridge.getUserInfo();
InnerHostProcessBridge.getPlatformSession((AppbrandApplicationImpl.getInst().getAppInfo()).appId);
}
}, LaunchThreadPool.getInst());
}
public void attachBaseContext(Context paramContext) {
super.attachBaseContext(paramContext);
AppbrandContext.tryKillIfNotInit(paramContext);
}
protected IActivityProxy createRealActivity(int paramInt) {
GameNotReadyActivityProxy gameNotReadyActivityProxy;
if (paramInt != 2) {
if (AdSiteManager.getInstance().isAdSiteBrowserInited()) {
if (AdSiteManager.getInstance().isAdSiteBrowser())
return (IActivityProxy)new AdSiteBrowser((FragmentActivity)this);
} else {
AppInfoEntity appInfoEntity2 = AppbrandApplicationImpl.getInst().getAppInfo();
AppInfoEntity appInfoEntity1 = appInfoEntity2;
if (appInfoEntity2 == null) {
Intent intent = getIntent();
appInfoEntity1 = appInfoEntity2;
if (intent != null) {
appInfoEntity2 = (AppInfoEntity)intent.getParcelableExtra("microapp_appinfo");
appInfoEntity1 = appInfoEntity2;
if (appInfoEntity2 == null) {
String str = intent.getStringExtra("microapp_url");
appInfoEntity1 = appInfoEntity2;
if (!TextUtils.isEmpty(str))
appInfoEntity1 = AppInfoManager.generateInitAppInfo(str);
}
}
}
if (AdSiteManager.getInstance().initIsAdSiteBrowser(getApplicationContext(), appInfoEntity1))
return (IActivityProxy)new AdSiteBrowser((FragmentActivity)this);
}
return (IActivityProxy)new TTAppbrandTabUI((FragmentActivity)this);
}
IActivityProxy iActivityProxy2 = GameModuleController.inst().getGameActivity((FragmentActivity)this);
IActivityProxy iActivityProxy1 = iActivityProxy2;
if (iActivityProxy2 == null) {
gameNotReadyActivityProxy = new GameNotReadyActivityProxy((FragmentActivity)this);
LoadHelper.handleMiniProcessFail(ErrorCode.MAIN.GAME_MODULE_NOT_READY.getCode());
}
return (IActivityProxy)gameNotReadyActivityProxy;
}
public View findViewById(int paramInt) {
IActivityProxy iActivityProxy = this.mActivityProxy;
if (iActivityProxy != null) {
View view = iActivityProxy.findViewById(paramInt);
if (view != null)
return view;
}
return super.findViewById(paramInt);
}
public IActivityProxy getActivityProxy() {
return this.mActivityProxy;
}
public int getDefaultFragmentBackground() {
return this.mDefaultFragmentBackground;
}
public boolean isFilledUpContainer() {
return this.isFilledUpContainer;
}
public boolean isInHostStack() {
return false;
}
public boolean isOnActivityStackTop() {
return this.mIsOnActivityStackTop;
}
public boolean isTriggeredHomeOrRecentApp() {
return ((HostSnapShotManager)AppbrandApplicationImpl.getInst().getService(HostSnapShotManager.class)).isTriggeredHomeOrRecentApp();
}
protected boolean needGetSnapShot() {
return true;
}
public void notifyUpdateSnapShot() {
((HostSnapShotManager)AppbrandApplicationImpl.getInst().getService(HostSnapShotManager.class)).notifyUpdateSnapShot();
}
public void onActivityResult(int paramInt1, int paramInt2, Intent paramIntent) {
IActivityProxy iActivityProxy = this.mActivityProxy;
if (iActivityProxy != null && iActivityProxy.onActivityResult(paramInt1, paramInt2, paramIntent)) {
c.a().b();
return;
}
c.a().b();
super.onActivityResult(paramInt1, paramInt2, paramIntent);
}
public void onBackPressed() {
AppBrandLogger.d("MiniappHostBase", new Object[] { "onBackPressed" });
IActivityProxy iActivityProxy = this.mActivityProxy;
if (iActivityProxy != null)
iActivityProxy.onBackPressed();
}
public void onCreate(Bundle paramBundle) {
super.onCreate(null);
TimeLogger timeLogger = TimeLogger.getInstance();
int i = 1;
timeLogger.logTimeDuration(new String[] { "MiniappHostBase_onCreate" });
AppbrandContext appbrandContext = AppbrandContext.getInst();
if (appbrandContext != null)
appbrandContext.setCurrentActivity(this);
Intent intent = getIntent();
if (intent != null) {
int j = intent.getIntExtra("app_type", 1);
i = j;
if (ChannelUtil.isLocalTest()) {
SchemeEntityHelper.remoteValidate((Activity)this, j, intent.getStringExtra("microapp_url"));
i = j;
}
}
this.mActivityProxy = createRealActivity(i);
if (this.mActivityProxy.beforeOnCreate(paramBundle)) {
this.mActivityProxy.onCreate(paramBundle);
this.mActivityProxy.afterOnCreate(paramBundle);
AppbrandApplicationImpl.getInst().getForeBackgroundManager().registerCloseSystemDialogReceiver();
final HostSnapShotManager hostSnapShotManager = (HostSnapShotManager)AppbrandApplicationImpl.getInst().getService(HostSnapShotManager.class);
if (needGetSnapShot())
hostSnapShotManager.updateSnapShotView();
if (!isInHostStack())
AppbrandApplicationImpl.getInst().getForeBackgroundManager().registerForeBackgroundListener((ForeBackgroundManager.ForeBackgroundListener)new ForeBackgroundManager.DefaultForeBackgroundListener() {
public void onTriggerHomeOrRecentApp() {
AppbrandApplicationImpl.getInst().setJumpToApp(false);
if (MiniappHostBase.this.needGetSnapShot()) {
hostSnapShotManager.setTriggeredHomeOrRecentApp(true);
hostSnapShotManager.clearSwipeBackground();
}
}
});
startCacheSpecialCrossProcessData();
return;
}
this.mActivityProxy = null;
LoadHelper.handleMiniProcessFail(ErrorCode.MAIN.BEFORE_ON_CREATE_CHECK_FAIL.getCode());
}
public void onDestroy() {
super.onDestroy();
AppBrandLogger.d("MiniappHostBase", new Object[] { "onDestroy" });
IActivityProxy iActivityProxy = this.mActivityProxy;
if (iActivityProxy != null)
iActivityProxy.onDestroy();
AppbrandApplicationImpl.getInst().finish();
ProcessUtil.killCurrentMiniAppProcess((Context)this);
}
public boolean onKeyDown(int paramInt, KeyEvent paramKeyEvent) {
IActivityProxy iActivityProxy = this.mActivityProxy;
return (iActivityProxy != null && iActivityProxy.onKeyDown(paramInt, paramKeyEvent)) ? true : super.onKeyDown(paramInt, paramKeyEvent);
}
public void onNewIntent(Intent paramIntent) {
super.onNewIntent(paramIntent);
AppBrandLogger.d("MiniappHostBase", new Object[] { "onNewIntent" });
((MpTimeLineReporter)AppbrandApplicationImpl.getInst().getService(MpTimeLineReporter.class)).addPoint("activity_on_create_begin", (new MpTimeLineReporter.ExtraBuilder()).kv("start_type", Integer.valueOf(2)).build());
IActivityProxy iActivityProxy = this.mActivityProxy;
if (iActivityProxy != null)
iActivityProxy.onNewIntent(paramIntent);
if (needGetSnapShot()) {
HostSnapShotManager hostSnapShotManager = (HostSnapShotManager)AppbrandApplicationImpl.getInst().getService(HostSnapShotManager.class);
hostSnapShotManager.setTriggeredHomeOrRecentApp(false);
hostSnapShotManager.setNeedUpdateSnapshotWhenOnStart(true);
}
}
public void onPause() {
super.onPause();
AppBrandLogger.d("MiniappHostBase", new Object[] { "onPause" });
IActivityProxy iActivityProxy = this.mActivityProxy;
if (iActivityProxy != null)
iActivityProxy.onPause();
this.mIsOnActivityStackTop = false;
((ShortcutService)AppbrandApplicationImpl.getInst().getService(ShortcutService.class)).onActivityPause();
}
public void onPostCreate(Bundle paramBundle) {
super.onPostCreate(paramBundle);
IActivityProxy iActivityProxy = this.mActivityProxy;
if (iActivityProxy != null)
iActivityProxy.onPostCreate(paramBundle);
}
public void onRequestPermissionsResult(int paramInt, String[] paramArrayOfString, int[] paramArrayOfint) {
super.onRequestPermissionsResult(paramInt, paramArrayOfString, paramArrayOfint);
IActivityProxy iActivityProxy = this.mActivityProxy;
if (iActivityProxy != null)
iActivityProxy.onRequestPermissionsResult(paramInt, paramArrayOfString, paramArrayOfint);
}
protected void onRestart() {
super.onRestart();
AppBrandLogger.d("MiniappHostBase", new Object[] { "onRestart" });
}
public void onResume() {
super.onResume();
AppBrandLogger.d("MiniappHostBase", new Object[] { "onResume" });
if (AppbrandApplicationImpl.getInst().getJumToApp())
(AppbrandApplicationImpl.getInst().getAppInfo()).scene = HostDependManager.getInst().getScene("back_mp");
AppbrandApplicationImpl.getInst().setJumpToApp(false);
IActivityProxy iActivityProxy = this.mActivityProxy;
if (iActivityProxy != null)
iActivityProxy.onResume();
this.mIsOnActivityStackTop = true;
((ShortcutService)AppbrandApplicationImpl.getInst().getService(ShortcutService.class)).onActivityResume();
}
public void onSaveInstanceState(Bundle paramBundle, PersistableBundle paramPersistableBundle) {
TimeLogger.getInstance().logTimeDuration(new String[] { "MiniappHostBase_onSaveInstanceState" });
}
public void onStart() {
super.onStart();
AppBrandLogger.d("MiniappHostBase", new Object[] { "onStart" });
if (needGetSnapShot()) {
HostSnapShotManager hostSnapShotManager = (HostSnapShotManager)AppbrandApplicationImpl.getInst().getService(HostSnapShotManager.class);
if (this.mActivityProxy instanceof TTAppbrandTabUI)
if (hostSnapShotManager.isTriggeredHomeOrRecentApp()) {
hostSnapShotManager.updateSnapShotView((Context)this, true);
} else if (hostSnapShotManager.isNeedUpdateSnapshotWhenOnStart()) {
hostSnapShotManager.updateSnapShotView();
}
getWindow().clearFlags(8192);
hostSnapShotManager.setNeedUpdateSnapshotWhenOnStart(false);
}
SnapshotManager.clearCacheSnapshot();
}
public void onStop() {
super.onStop();
AppBrandLogger.d("MiniappHostBase", new Object[] { "onStop" });
IActivityProxy iActivityProxy = this.mActivityProxy;
if (iActivityProxy != null)
iActivityProxy.onStop();
}
public void onTrimMemory(int paramInt) {
if (paramInt != 5 && paramInt != 10 && paramInt != 15)
return;
IActivityProxy iActivityProxy = this.mActivityProxy;
if (iActivityProxy != null)
iActivityProxy.onMemoryWarning(paramInt);
}
public void onUserInteraction() {
IActivityProxy iActivityProxy = this.mActivityProxy;
if (iActivityProxy != null)
iActivityProxy.onUserInteraction();
super.onUserInteraction();
}
public void onWindowFocusChanged(boolean paramBoolean) {
IActivityProxy iActivityProxy = this.mActivityProxy;
if (iActivityProxy != null)
iActivityProxy.onWindowFocusChanged(paramBoolean);
super.onWindowFocusChanged(paramBoolean);
}
public void setDefaultFragmentBackground(int paramInt) {
this.mDefaultFragmentBackground = paramInt;
}
public void setFilledUpContainer(boolean paramBoolean) {
this.isFilledUpContainer = paramBoolean;
}
public void startActivityForResult(Intent paramIntent, int paramInt) {
super.startActivityForResult(paramIntent, paramInt);
IActivityProxy iActivityProxy = this.mActivityProxy;
if (iActivityProxy != null)
iActivityProxy.onStartActivityForResult(paramIntent, paramInt);
}
}
/* Location: C:\Users\august\Desktop\tik\df_miniapp\classes.jar!\com\tt\miniapphost\MiniappHostBase.class
* Java compiler version: 6 (50.0)
* JD-Core Version: 1.1.3
*/
|
package pe.gob.trabajo.repository;
import pe.gob.trabajo.domain.Calbensoc;
import org.springframework.stereotype.Repository;
import org.springframework.data.jpa.repository.*;
import java.util.List;
/**
* Spring Data JPA repository for the Calbensoc entity.
*/
@SuppressWarnings("unused")
@Repository
public interface CalbensocRepository extends JpaRepository<Calbensoc, Long> {
@Query("select calbensoc from Calbensoc calbensoc where calbensoc.nFlgactivo = true")
List<Calbensoc> findAll_Activos();
@Query("select calbensoc " +
" from Calbensoc calbensoc inner join Atencion atencion on atencion.liquidacion.id=calbensoc.liquidacion.id " +
" where atencion.id=?1 and calbensoc.bensocial.id=?2 and calbensoc.bensocial.nFlgactivo = true and atencion.nFlgactivo = true and calbensoc.nFlgactivo = true")
List<Calbensoc> findCalbensoc_ByIdAtencionIdBensocial(Long id_aten, Long id_bsoc);
@Query("select calbensoc " +
" from Calbensoc calbensoc inner join Atencion atencion on atencion.liquidacion.id=calbensoc.liquidacion.id " +
" where atencion.id=?1 and atencion.nFlgactivo = true and calbensoc.nFlgactivo = true ")
List<Calbensoc> findAllCalbensoc_ByIdAtencion(Long id_aten);
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package hadoop;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.LineNumberReader;
import java.io.Reader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author Kimo
*/
public class Hadoop {
public class MapCountry implements Mapper, Callable<Object> {
HashMap<Object, Object> file = new HashMap<Object, Object>();
@Override
public HashMap<Object, Object> mapper(HashMap<Object, Object> file) {
BufferedReader br = new BufferedReader((Reader) file.entrySet().iterator().next().getValue());
String line = "";
String cvsSplitBy = ",";
HashMap<Object, Object> result = new HashMap<Object, Object>();
try {
while ((line = br.readLine()) != null) {
// use comma as separator
String[] country = line.split(cvsSplitBy);
if (result.containsKey(country[0].toString())) {
result.put(country[0].toString(), Long.valueOf((Long) result.get(country[0]) + Long.valueOf(Long.parseLong((country[1])))));
} else {
result.put(country[0], Long.valueOf(Long.parseLong(country[1])));
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return result;
// throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public Object call() throws Exception {
return this.mapper(this.file);
// throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
}
public class ReduceCountry implements Reducer {
List<Future<Object>> file;
@Override
public HashMap<Object, Object> reducer(List<Future<Object>> file) {
HashMap<Object, Object> result = new HashMap<Object, Object>();
HashMap<String, Long> temp = new HashMap<String, Long>();
for (Future<Object> fut : file) {
try {
temp = (HashMap<String, Long>) fut.get();
for (Map.Entry<String, Long> entrySet : temp.entrySet()) {
String key = entrySet.getKey();
Long value = entrySet.getValue();
if (result.containsKey(key)) {
result.put(key, Long.valueOf((Long) result.get(key) + value));
} else {
result.put(key, Long.valueOf(value));
}
}
// if(result.containsKey();
// result.put(HashMap<Object, Object>fut.get(), Long.valueOf((long) result.get(fut.get()) + 1);
} catch (InterruptedException ex) {
Logger.getLogger(Hadoop.class.getName()).log(Level.SEVERE, null, ex);
} catch (ExecutionException ex) {
Logger.getLogger(Hadoop.class.getName()).log(Level.SEVERE, null, ex);
}
}
return result;
// throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) throws FileNotFoundException, IOException, Exception {
// TODO code application logic here
FileReader big_data_file = new FileReader(new File("data1.txt"));
LineNumberReader lnr = new LineNumberReader(big_data_file);
lnr.skip(Long.MAX_VALUE);
Long file_size = new Long(0);
file_size += lnr.getLineNumber() + 1; //Add 1 because line index starts at 0
// Finally, the LineNumberReader object should be closed to prevent resource leak
lnr.close();
int processors = Runtime.getRuntime().availableProcessors();
double line_iteration = (double) file_size / processors;
// line_iteration = line_iteration.doubleVal;
line_iteration = Math.ceil(line_iteration);
System.out.println(line_iteration);
List<Future<Object>> map_result = new ArrayList<Future<Object>>();
Hadoop hadoop = new Hadoop();
ExecutorService executor = null;
for (int i = 0; i < processors; i++) {
MapCountry map_country = hadoop.new MapCountry();
// map_country.
// map_country.file = new HashMap<Double, FileReader>();
// HashMap<Long,FileReader>file = new HashMap<Long,FileReader>();
// file.put();
map_country.file.put(Long.valueOf((long) line_iteration), new FileReader(new File("data"+(i+1)+".txt")));
// map_country.call();
//Get ExecutorService from Executors utility class, thread pool size is 10
executor = Executors.newCachedThreadPool();
Future<Object> future = executor.submit(map_country);
map_result.add(future);
}
ReduceCountry reduce_country = hadoop.new ReduceCountry();
reduce_country.file = map_result;
HashMap<Object, Object> reduce_result = reduce_country.reducer(reduce_country.file);
for (Map.Entry<Object, Object> entrySet : reduce_result.entrySet()) {
Object key = entrySet.getKey();
Object value = entrySet.getValue();
System.out.println("Country " + String.valueOf(key) + " Count " + Long.valueOf((Long) value));
}
executor.shutdown();
return;
}
}
|
package com.example.demo.service;
import com.example.demo.entity.Author;
import com.example.demo.model.dto.AuthorDto;
import com.example.demo.model.request.CreateAuthorReq;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public interface AuthorService {
public List<AuthorDto> getAuthors();
public CreateAuthorReq createAuthor(CreateAuthorReq req);
}
|
package com.sixmac.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
/**
* Created by Administrator on 2016/6/12 0012.
*/
@Entity
@Table(name = "t_system_vip_experience")
public class SysExperience extends BaseEntity {
@Column(name = "experience")
private Integer experience;
@Column(name = "action")
private Integer action;
public Integer getExperience() {
return experience;
}
public void setExperience(Integer experience) {
this.experience = experience;
}
public Integer getAction() {
return action;
}
public void setAction(Integer action) {
this.action = action;
}
}
|
package com.yin.trip.util;
import java.io.Serializable;
/**
* Created by yinfeng on 2017/3/14 0014.
* 发送至服务端的位置信息
*/
public class LocationSendData implements Serializable{
private double longtitude; //经度
private double latitude; //纬度
private String addr; //位置信息
public LocationSendData(double longtitude, double latitude){
this.setLatitude(latitude);
this.setLongtitude(longtitude);
}
public double getLongtitude() {
return longtitude;
}
public void setLongtitude(double longtitude) {
this.longtitude = longtitude;
}
public double getLatitude() {
return latitude;
}
public void setLatitude(double latitude) {
this.latitude = latitude;
}
public String getAddr() {
return addr;
}
public void setAddr(String addr) {
this.addr = addr;
}
}
|
package net.jgp.labs.io.dir;
import static org.junit.Assert.*;
import java.io.File;
import java.util.List;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
public class FileListerTest {
@BeforeClass
public static void setUpBeforeClass() throws Exception {
}
@AfterClass
public static void tearDownAfterClass() throws Exception {
}
@Before
public void setUp() throws Exception {
}
@After
public void tearDown() throws Exception {
}
@Test
public void test() {
FileLister fl = new FileLister();
fl.setPath("/Users/jgp/Pictures/All Photos/2010-2019/");
fl.addExtensionFilter("jpg");
fl.addExtensionFilter("jpeg");
fl.setRecursive();
List<File> list = fl.list();
System.out.println(list.size());
for (File f: list) {
System.out.println(f);
}
}
}
|
package tes;
import java.util.Scanner;
public class No10 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("Input uang : ");
Integer uang = Integer.parseInt(scan.nextLine());
int bil = 0;
int a = 100000;
int b = 50000;
int c = 20000;
int d = 10000;
int e = 5000;
int j = 2000;
int f = 1000;
int g = 500;
int h = 200;
int i = 100;
int m = uang.toString().length();
for(int x = 0; x < m; x++) {
if(uang >= a)
{
bil = uang / 100000;
System.out.println("100000 sebananyak "+bil);
}
uang = uang % 100000;
if ((uang >= b) && (uang <a))
{
bil = uang / 50000;
System.out.println("50000 sebanyak "+bil);
}
uang = uang % 50000;
if ((uang >= c) && (uang <b))
{
bil = uang / 20000;
System.out.println("20000 sebanyak "+bil);
}
uang = uang % 20000;
if ((uang >= d) && (uang <c))
{
bil = uang / 10000;
System.out.println("10000 sebanyak "+bil);
}
uang = uang % 10000;
if ((uang >= e) && (uang <d))
{
bil = uang / 5000;
System.out.println("5000 sebanyak "+bil);
}
uang = uang % 5000;
if ((uang >= j) && (uang <e))
{
bil = uang / 2000;
System.out.println("2000 sebanyak "+bil);
}
uang = uang % 2000;
if ((uang >= f) && (uang <j))
{
bil = uang / 1000;
System.out.println("1000 sebanyak "+bil);
}
uang = uang % 1000;
if ((uang >= g) && (uang <f))
{
bil = uang / 500;
System.out.println("500 sebanyak "+bil);
}
uang = uang % 500;
if ((uang >= h) && (uang <g))
{
bil = uang / 200;
System.out.println ("200 sebanyak "+bil);
}
uang = uang % 200;
if ((uang >= i) && (uang <h))
{
bil = uang / 100;
System.out.println ("100 sebanyak "+bil);
}
}
}
}
|
package com.mrice.txl.appthree.bean;
import com.mrice.txl.appthree.http.ParamNames;
import java.io.Serializable;
import java.util.List;
/**
* Created by cai on 2017/8/7.
*/
public class LotteryDetailBean implements Serializable {
@ParamNames("code")
private String code;
@ParamNames("pageInfo")
private PageInfo pageInfo;
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public PageInfo getPageInfo() {
return pageInfo;
}
public void setPageInfo(PageInfo pageInfo) {
this.pageInfo = pageInfo;
}
public static class PageInfo implements Serializable {
@ParamNames("pageNum")
private int pageNum;
@ParamNames("pageSize")
private int pageSize;
@ParamNames("size")
private int size;
@ParamNames("startRow")
private int startRow;
@ParamNames("endRow")
private int endRow;
@ParamNames("total")
private int total;
@ParamNames("pages")
private int pages;
@ParamNames("firstPage")
private int firstPage;
@ParamNames("prePage")
private int prePage;
@ParamNames("nextPage")
private int nextPage;
@ParamNames("lastPage")
private int lastPage;
@ParamNames("isFirstPage")
private boolean isFirstPage;
@ParamNames("isLastPage")
private boolean isLastPage;
@ParamNames("hasPreviousPage")
private boolean hasPreviousPage;
@ParamNames("hasNextPage")
private boolean hasNextPage;
@ParamNames("navigatePages")
private int navigatePages;
@ParamNames("list")
private List<LotteryDetailBeanIn> list;
@ParamNames("navigatepageNums")
private List<Integer> navigatepageNums;
public int getPageNum() {
return pageNum;
}
public void setPageNum(int pageNum) {
this.pageNum = pageNum;
}
public int getPageSize() {
return pageSize;
}
public void setPageSize(int pageSize) {
this.pageSize = pageSize;
}
public int getSize() {
return size;
}
public void setSize(int size) {
this.size = size;
}
public int getStartRow() {
return startRow;
}
public void setStartRow(int startRow) {
this.startRow = startRow;
}
public int getEndRow() {
return endRow;
}
public void setEndRow(int endRow) {
this.endRow = endRow;
}
public int getTotal() {
return total;
}
public void setTotal(int total) {
this.total = total;
}
public int getPages() {
return pages;
}
public void setPages(int pages) {
this.pages = pages;
}
public int getFirstPage() {
return firstPage;
}
public void setFirstPage(int firstPage) {
this.firstPage = firstPage;
}
public int getPrePage() {
return prePage;
}
public void setPrePage(int prePage) {
this.prePage = prePage;
}
public int getNextPage() {
return nextPage;
}
public void setNextPage(int nextPage) {
this.nextPage = nextPage;
}
public int getLastPage() {
return lastPage;
}
public void setLastPage(int lastPage) {
this.lastPage = lastPage;
}
public boolean isFirstPage() {
return isFirstPage;
}
public void setFirstPage(boolean firstPage) {
isFirstPage = firstPage;
}
public boolean isLastPage() {
return isLastPage;
}
public void setLastPage(boolean lastPage) {
isLastPage = lastPage;
}
public boolean isHasPreviousPage() {
return hasPreviousPage;
}
public void setHasPreviousPage(boolean hasPreviousPage) {
this.hasPreviousPage = hasPreviousPage;
}
public boolean isHasNextPage() {
return hasNextPage;
}
public void setHasNextPage(boolean hasNextPage) {
this.hasNextPage = hasNextPage;
}
public int getNavigatePages() {
return navigatePages;
}
public void setNavigatePages(int navigatePages) {
this.navigatePages = navigatePages;
}
public List<LotteryDetailBeanIn> getList() {
return list;
}
public void setList(List<LotteryDetailBeanIn> list) {
this.list = list;
}
public List<Integer> getNavigatepageNums() {
return navigatepageNums;
}
public void setNavigatepageNums(List<Integer> navigatepageNums) {
this.navigatepageNums = navigatepageNums;
}
public class LotteryDetailBeanIn implements Serializable {
@ParamNames("id")
private Integer id;
@ParamNames("no")
private String no;
@ParamNames("noDate")
private Long noDate;
@ParamNames("q1")
private String q1;
@ParamNames("q2")
private String q2;
@ParamNames("q3")
private String q3;
@ParamNames("q4")
private String q4;
@ParamNames("q5")
private String q5;
@ParamNames("q6")
private String q6;
@ParamNames("q7")
private String q7;
@ParamNames("type")
private String type;
public LotteryDetailBeanIn(Integer id, String no, Long noDate, String q1, String q2, String q3, String q4, String q5, String q6,
String q7, String type) {
super();
this.id = id;
this.no = no;
this.noDate = noDate;
this.q1 = q1;
this.q2 = q2;
this.q3 = q3;
this.q4 = q4;
this.q5 = q5;
this.q6 = q6;
this.q7 = q7;
this.type = type;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getNo() {
return no;
}
public void setNo(String no) {
this.no = no;
}
public Long getNoDate() {
return noDate;
}
public void setNoDate(Long noDate) {
this.noDate = noDate;
}
public String getQ1() {
return q1 + getOneChar();
}
public void setQ1(String q1) {
this.q1 = q1;
}
public String getQ2() {
return q2 + getOneChar();
}
public String getOneChar() {
return " ";
}
public void setQ2(String q2) {
this.q2 = q2;
}
public String getQ3() {
return q3 + getOneChar();
}
public void setQ3(String q3) {
this.q3 = q3;
}
public String getQ4() {
return q4 + getOneChar();
}
public void setQ4(String q4) {
this.q4 = q4;
}
public String getQ5() {
return q5 + getOneChar();
}
public void setQ5(String q5) {
this.q5 = q5;
}
public String getQ6() {
return q6 + getOneChar();
}
public void setQ6(String q6) {
this.q6 = q6;
}
public String getQ7() {
return q7 + getOneChar();
}
public void setQ7(String q7) {
this.q7 = q7;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
@Override
public String toString() {
return "LotteryDetailBeanIn{" +
"id=" + id +
", no='" + no + '\'' +
", noDate=" + noDate +
", q1='" + q1 + '\'' +
", q2='" + q2 + '\'' +
", q3='" + q3 + '\'' +
", q4='" + q4 + '\'' +
", q5='" + q5 + '\'' +
", q6='" + q6 + '\'' +
", q7='" + q7 + '\'' +
", type='" + type + '\'' +
'}';
}
}
@Override
public String toString() {
return "PageInfo{" +
"pageNum=" + pageNum +
", pageSize=" + pageSize +
", size=" + size +
", startRow=" + startRow +
", endRow=" + endRow +
", total=" + total +
", pages=" + pages +
", firstPage=" + firstPage +
", prePage=" + prePage +
", nextPage=" + nextPage +
", lastPage=" + lastPage +
", isFirstPage=" + isFirstPage +
", isLastPage=" + isLastPage +
", hasPreviousPage=" + hasPreviousPage +
", hasNextPage=" + hasNextPage +
", navigatePages=" + navigatePages +
", list=" + list +
", navigatepageNums=" + navigatepageNums +
'}';
}
}
@Override
public String toString() {
return "NiceBean{" +
"code='" + code + '\'' +
", pageInfo=" + pageInfo +
'}';
}
}
|
package day4_04;
import java.util.HashMap;
import java.util.Map;
import java.util.Iterator;
import java.util.Map.Entry;
import java.util.Scanner;
public class SoGhiNho
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
HashMap<String, Integer> map = new HashMap<>();
map.put("Joy", 34543);
map.put("Jack", 56765);
map.put("Tina", 34567);
System.out.println("Name\tNumber");
for (Entry<String, Integer> entry : map.entrySet())
{
System.out.println(entry.getKey()+"\t"+ entry.getValue());
}
//Tim xem so 3443 co trong so cua ban hay khong
if(map.containsValue("3443")){
System.out.println("Da ton tai so 3443");
}else{
System.out.println("Khong ton tai so 3443");
}
//Tim xem tin cua Jack con ton tai hay khong
if(map.containsKey("Jack"))
{
System.out.println("Con ton tin nhan cua Jack");
}else{
System.out.println("Khong con ton tai tin nhan cua Jack");
}
//Tim so cua tina
for (Entry<String, Integer> entry : map.entrySet())
{
if( entry.getKey().equalsIgnoreCase("tina"))
{
System.out.println("Tina's number is: "+ entry.getValue());
}
}
//Xoa Joy
map.remove("Joy");
//in ra so ghi nho khi xoa joy
System.out.println("Name\tNumber");
for (Entry<String, Integer> entry : map.entrySet())
{
System.out.println(entry.getKey()+"\t"+ entry.getValue());
}
}
}
|
package jp.mironal.java.aws.app.glacier;
import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.util.List;
import org.codehaus.jackson.JsonParseException;
import com.amazonaws.services.glacier.model.DescribeJobResult;
import com.amazonaws.services.glacier.model.GlacierJobDescription;
/**
* @author mironal
*/
public class RestoreJobOperator extends StateLessJobOperator {
public static final String ACTION_ARCHIVE_RETRIEVAL = "ArchiveRetrieval";
public static final String ACTION_INVENTORY_RETRIEVAL = "InventoryRetrieval";
public static RestoreJobOperator restoreJob(JobRestoreParam param, File awsProperties)
throws IOException {
RestoreJobOperator operator = new RestoreJobOperator(param, awsProperties);
return operator;
}
private final JobOperator operator;
private final JobRestoreParam jobRestoreParam;
private String action = null;
private RestoreJobOperator(JobRestoreParam param, File awsProperties) throws IOException {
super(param.getRegion(), awsProperties);
operator = JobOperator.restore(param, awsProperties);
jobRestoreParam = param;
}
public DescribeJobResult describeJob() {
return operator.describeJob(jobRestoreParam.getVaultName(), jobRestoreParam.getJobId());
}
public List<GlacierJobDescription> listJobs() {
return operator.listJobs(jobRestoreParam.getVaultName());
}
/**
* Jobが完了して成功しているか?
*
* @return true:Jobが完了して成功している.false:それ以外.
*/
public boolean checkJobSucceeded() {
DescribeJobResult result = describeJob();
return result.getStatusCode().equals(JobOperator.STATUS_SUCCEEDED);
}
public String getStatusCode() {
return describeJob().getStatusCode();
}
public String updateJobKind() {
DescribeJobResult result = describeJob();
this.action = result.getAction();
return this.action;
}
public String getAction() {
if (action == null) {
updateJobKind();
}
return action;
}
public boolean waitForJobComplete() throws InterruptedException {
return operator.waitForJobToComplete();
}
public void downloadArchiveJobOutput(File saveFile) {
if (!getAction().equals(ACTION_ARCHIVE_RETRIEVAL)) {
throw new IllegalStateException("This job is " + getAction());
}
operator.downloadArchiveJobOutput(saveFile);
}
public InventoryRetrievalResult downloadInventoryJobOutput() throws JsonParseException,
IOException, ParseException {
if (!getAction().equals(ACTION_INVENTORY_RETRIEVAL)) {
throw new IllegalStateException("This job is " + getAction());
}
return operator.downloadInventoryJobOutput();
}
}
|
package com.commercetools.util;
import io.sphere.sdk.http.HttpHeaders;
import org.slf4j.MDC;
import spark.Request;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.UUID;
import static net.logstash.logback.encoder.org.apache.commons.lang3.StringUtils.isBlank;
public final class CorrelationIdUtil {
public static final String CORRELATION_ID_LOG_VAR_NAME = "correlationId";
public static void attachFromRequestOrGenerateNew(@Nonnull final Request request) {
MDC.put(CORRELATION_ID_LOG_VAR_NAME, getOrGenerate(request.headers(HttpHeaders.X_CORRELATION_ID)));
}
public static String getFromMDCOrGenerateNew() {
final String correlationId = getOrGenerate(MDC.get(CORRELATION_ID_LOG_VAR_NAME));
MDC.put(CORRELATION_ID_LOG_VAR_NAME, correlationId);
return correlationId;
}
private static String getOrGenerate(@Nullable final String correlationId) {
return isBlank(correlationId)? UUID.randomUUID().toString() : correlationId;
}
private CorrelationIdUtil() {
}
}
|
package com.zetwerk.app.zetwerk.data.firebase;
import com.zetwerk.app.zetwerk.data.model.Employee;
/**
* Created by varun.am on 19/01/19
*/
public interface EmployeeCardInteractionCallbacks {
public void onEmployeeCardLongClicked(Employee employee);
}
|
package com.ds.algo.matters.array;
import java.util.Arrays;
public class RearrangePosNeg {
public static void main(String[] args){
int[] input = {4, -3, -7, -1, 5, 6, 2, 8, 9};
rearrangeArrayOfPosNeg(input);
System.out.println(Arrays.toString(input));
}
private static void rearrangeArrayOfPosNeg(int[] A){
int i = -1, temp = 0, N = A.length;
for (int j = 0; j < N; j++){
if (A[j] < 0){
i++;
temp = A[j];
A[j] = A[i];
A[i] = temp;
}
}
int pos = i + 1, neg = 0;
while (pos < N && neg < pos && A[neg] < 0){
temp = A[neg];
A[neg] = A[pos];
A[pos] = temp;
pos++;
neg += 2;
}
}
}
|
import java.util.*;
//In a Binary Tree, Create Linked Lists of all the nodes at each depth.
class Tree_node{
int data;
Tree_node left,right;
public Tree_node(int item){
data=item;
left=null;
right=null;
// next=null;
}
}
/*class Linkedlist{
int data;
Node next;
public Linkedlist(int item){
data=item;
next=null;
}
}*/
public class creteLinkedlist {
static void Print_linkedlists_at_each_level_in_binary_tree(Tree_node root) {
if (root == null) {
return;
}
Queue<Tree_node> q = new LinkedList<Tree_node>();
q.add(root);
System.out.println("q.peek() " + ((Tree_node) q.peek()));
while (!q.isEmpty()) {//2
HashMap<Tree_node,Tree_node> hm=new HashMap<Tree_node,Tree_node>;
int m = q.size();//1
System.out.println("size of array before entering into while loop " + m);
Tree_node head = null;
Tree_node temp = null;
while (m > 0) {
if (q.size() > 0) {
Tree_node B = q.remove();//2
System.out.println("queue size is " + q.size());
if (B.left != null) {//3
q.add(B.left);
}
if (B.right != null) {//3 4
q.add(B.right);
}
if (head == null) {
head = B;//2
temp = B;//2
}
else {
/* temp.next = B;
temp = temp.next;*/
hm.put(temp,B);//2 3, 3 4
temp=B;//4
}
}
display(head,hm);
m--;
System.out.println("end of first method");
}
}
}
//}
void display(Tree_node A,HashMap hm) {
System.out.ptintln(head->data);
Tree_node temp1=head;//2
while(hm.get(temp1)!=null){
System.out.println("-->");
System.out.println(hm.get(temp1).data);
temp1=temp1.get(temp1);
}
}
}
public static void main(String[] args){
Tree_node k=new Tree_node(3);
root.left=new Tree_node(7);
root.right=new Tree_node(5);
root.left.left=new Tree_node(8);
root.left.right=new Tree_node(0);
root.right.left=new Tree_node(9);
root.right.right=new Tree_node(1);
k.Print_linkedlists_at_each_level_in_binary_tree(root);
}
}
|
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author Naren Thanikesh
*/
public class view_class extends javax.swing.JFrame {
public static Connection con;
public static PreparedStatement pstmt;
public static Statement stmt;
public static Statement stmt1;
public static ResultSet rs;
public static ResultSet rs1;
public static String admin_id;
/**
* Creates new form view_class
*/
public view_class() {
try {
// DriverManager.registerDriver(new oracle.jdbc.OracleDriver());
Class.forName("oracle.jdbc.driver.OracleDriver");
}catch (ClassNotFoundException e) {
System.out.println("MySQL JDBC Driver missing!!!");
e.printStackTrace();
return;
}
try
{
con=DriverManager.getConnection("jdbc:oracle:thin:@//orca.csc.ncsu.edu:1521/orcl.csc.ncsu.edu","nthanik","200152371");
}
catch(SQLException ex)
{
System.out.println("ASD");
JOptionPane.showMessageDialog(this,ex.getMessage());
}
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jScrollPane1 = new javax.swing.JScrollPane();
t1 = new javax.swing.JTable();
jLabel1 = new javax.swing.JLabel();
jButton1 = new javax.swing.JButton();
class_id = new javax.swing.JTextField();
jLabel2 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
t1.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
},
new String [] {
"semester", "days", "start time", "end time", "class size", "waitlist size"
}
));
jScrollPane1.setViewportView(t1);
jLabel1.setText("Enter Class id:");
jButton1.setText("Display");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
class_id.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
class_idActionPerformed(evt);
}
});
jLabel2.setText("Menu");
jLabel2.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jLabel2MouseClicked(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(26, 26, 26)
.addComponent(jLabel1)
.addGap(33, 33, 33)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jButton1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(class_id))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 508, Short.MAX_VALUE)
.addComponent(jLabel2)
.addGap(28, 28, 28))
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 758, Short.MAX_VALUE)
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(24, 24, 24)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(class_id, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel2)))
.addGap(24, 24, 24)
.addComponent(jButton1)
.addGap(18, 18, 18)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 206, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(28, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void class_idActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_class_idActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_class_idActionPerformed
private void jLabel2MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabel2MouseClicked
// TODO add your handling code here:
admin_page pg= new admin_page();
pg.setVisible(true);
this.setVisible(false);
}//GEN-LAST:event_jLabel2MouseClicked
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
// TODO add your handling code here:
try{
DefaultTableModel tm=(DefaultTableModel)t1.getModel();
tm.setRowCount(0);
stmt=con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_READ_ONLY);
rs=stmt.executeQuery ("select * from classes where class_id='" + class_id.getText() + "'");
System.out.println(class_id.getText());
stmt1=con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_READ_ONLY);
rs1=stmt1.executeQuery ("select * from schedule where class_id='" + class_id.getText() + "'");
rs.first();
rs1.first();
String sem,faculty="",days="";
int waitlist_no,class_count;
String stime,etime;
System.out.println(rs.getString(2));
sem=(rs.getString(4));
waitlist_no=Integer.parseInt(rs.getString(2));
class_count=Integer.parseInt(rs.getString(6));
stime = rs1.getString(3).split(" ")[1].substring(0,5);
etime = rs1.getString(4).split(" ")[1].substring(0,5);
days=rs1.getString(2);
rs1.next();
do
{
days+=",";
days+=rs1.getString(2);
}while(rs1.next());
/* stmt1=con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_READ_ONLY);
rs1=stmt1.executeQuery ("select * from class_faculty where class_id='" + class_id.getText() + "'");
rs1.first();
faculty=rs1.getString(2);
rs1.next();
do
{
faculty+=",";
faculty+=rs1.getString(2);
}while(rs1.next());
*/
Object row[]={sem,days,stime,etime,class_count,waitlist_no};
tm.addRow(row);
}
catch(SQLException ex){
JOptionPane.showMessageDialog(this,ex.getMessage());
}
}//GEN-LAST:event_jButton1ActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(view_class.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(view_class.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(view_class.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(view_class.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new view_class().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JTextField class_id;
private javax.swing.JButton jButton1;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTable t1;
// End of variables declaration//GEN-END:variables
}
|
package com.design.pattern.abstractFactory.btn;
/**
* @author zhangbingquan
* @desc 抽象的按钮工具接口
* @time 2019/7/28 18:32
*/
public interface Button {
public void click();
}
|
//package HT8;
/*
* William Orozco, 13386
* Dulce Chacon, 13463
* Luis Gomez, 13135
* Programa para contar diferentes tipos de palabras en un archivo de texto.
* HOJA DE TRABAJO 8
*
* Se uso codigo de referencia adjuntado con la hoja de trabajo
*
* Descripci�n: Word. Clase para almacenar las palabras junto con su tipo.
*/
class Word implements Comparable<Word> {
private String word;
private String type;
// Constructor, inicializa la palabra con su tipo
public Word(String word, String type)
{
this.word=word;
this.type=type;
}
public Word()
{
this.word= "";
this.type="";
}
// Comparadores, solo importa comparar la palabra, no el tipo.
public int compareTo(Word o)
{
return this.word.compareTo(o.getWord());
}
public boolean equals(Object obj)
{
return (obj instanceof Word && getWord().equals(((Word)obj).getWord()));
}
// M�todos de acceso..
public void setWord(String word)
{
this.word=word;
}
public void setType(String type)
{
this.type=type;
}
public String getWord()
{
return word;
}
public String getType()
{
return type;
}
}
|
package com.woniu.buke;
public class Count {
static Lock lock=new Lock();
public static void main(String [] args) throws InterruptedException {
lock.lock();
doAll();
lock.unlock();
}
public static void doAll() throws InterruptedException {
lock.lock();
lock.unlock();
}
}
|
package com.tencent.mm.plugin.aa.a.c;
import com.tencent.mm.protocal.c.v;
import com.tencent.mm.sdk.platformtools.x;
import com.tencent.mm.vending.g.g;
import com.tencent.mm.vending.h.e;
public class g$d implements e<v, Void> {
final /* synthetic */ g eBH;
public g$d(g gVar) {
this.eBH = gVar;
}
public final /* synthetic */ Object call(Object obj) {
f fVar = this.eBH.eBA;
String stringExtra = fVar.uPN.getStringExtra("bill_no");
int intExtra = fVar.uPN.getIntExtra("enter_scene", 0);
String stringExtra2 = fVar.uPN.getStringExtra("chatroom");
String stringExtra3 = fVar.uPN.getStringExtra("key_sign");
int intExtra2 = fVar.uPN.getIntExtra("key_ver", 0);
x.i("MicroMsg.PaylistAAInteractor", "getPayListDetail, billNo: %s, scene: %s, chatRoom: %s", new Object[]{stringExtra, Integer.valueOf(intExtra), stringExtra2});
g.a(g.a(stringExtra, Integer.valueOf(intExtra), stringExtra2, stringExtra3, Integer.valueOf(intExtra2)).c(fVar.eBw.eAe));
return null;
}
public final String xr() {
return "Vending.LOGIC";
}
}
|
package br.usp.memoriavirtual.controle;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.ResourceBundle;
import javax.ejb.EJB;
import javax.el.ELResolver;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.component.UIData;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletResponse;
import br.usp.memoriavirtual.modelo.entidades.Multimidia;
import br.usp.memoriavirtual.modelo.entidades.Usuario;
import br.usp.memoriavirtual.modelo.entidades.bempatrimonial.Assunto;
import br.usp.memoriavirtual.modelo.entidades.bempatrimonial.BemPatrimonial;
import br.usp.memoriavirtual.modelo.entidades.bempatrimonial.Descritor;
import br.usp.memoriavirtual.modelo.fachadas.ModeloException;
import br.usp.memoriavirtual.modelo.fachadas.remoto.CadastrarBemPatrimonialRemote;
import br.usp.memoriavirtual.modelo.fachadas.remoto.RealizarBuscaSimplesRemote;
import br.usp.memoriavirtual.modelo.fachadas.remoto.UtilMultimidiaRemote;
import br.usp.memoriavirtual.utils.MVControleMemoriaVirtual;
import br.usp.memoriavirtual.utils.MVModeloCamposMultimidia;
import br.usp.memoriavirtual.utils.MensagensDeErro;
import br.usp.memoriavirtual.utils.StringContainer;
@ManagedBean(name = "realizarBuscaSimplesMB")
@SessionScoped
public class RealizarBuscaSimplesMB implements BeanMemoriaVirtual, Serializable {
private static final long serialVersionUID = 4130356176853401265L;
@EJB
private CadastrarBemPatrimonialRemote cadastrarBemPatrimonialEJB;
@EJB
private RealizarBuscaSimplesRemote realizarBuscaEJB;
@EJB
private UtilMultimidiaRemote utilMultimidiaEJB;
private List<MVModeloCamposMultimidia> campos = new ArrayList<MVModeloCamposMultimidia>();
private String busca;
private List<BemPatrimonial> bens = new ArrayList<BemPatrimonial>();
private BemPatrimonial bemPatrimonial;
private String assuntos = "";
private String descritores = "";
private List<StringContainer> fontesInformacao = new ArrayList<StringContainer>();
private boolean proximaPaginaDisponivel;
private Integer pagina = 1;
private ArrayList<String> paginas;
private UIData controlePagina;
private MensagensMB mensagens;
public RealizarBuscaSimplesMB() {
FacesContext facesContext = FacesContext.getCurrentInstance();
ELResolver resolver = facesContext.getApplication().getELResolver();
this.mensagens = (MensagensMB) resolver.getValue(
facesContext.getELContext(), null, "mensagensMB");
}
private void buscarNovaPagina(Integer pagina) {
try {
this.bens = realizarBuscaEJB.buscarExterno(this.busca, pagina);
if (pagina.intValue() == realizarBuscaEJB.getNumeroDePaginasBusca()
.intValue())
proximaPaginaDisponivel = false;
else
proximaPaginaDisponivel = true;
this.pagina = pagina;
} catch (Exception e) {
e.printStackTrace();
MensagensDeErro.getErrorMessage("realizarBuscaSimplesErro",
"resultado");
}
}
public String buscar() {
try {
this.bens = realizarBuscaEJB.buscarExterno(this.busca, pagina);
if (pagina == realizarBuscaEJB.getNumeroDePaginasBusca())
proximaPaginaDisponivel = false;
else
proximaPaginaDisponivel = true;
paginas = new ArrayList<String>();
for (int i = 0; i < realizarBuscaEJB.getNumeroDePaginasBusca(); i++) {
paginas.add(new Integer(i + 1).toString());
}
} catch (Exception e) {
e.printStackTrace();
MensagensDeErro.getErrorMessage("realizarBuscaSimplesErro",
"resultado");
return null;
}
return "resultadosbusca";
}
public String excluir() {
FacesContext facesContext = FacesContext.getCurrentInstance();
ELResolver resolver = facesContext.getApplication().getELResolver();
ExcluirBemPatrimonialMB managedBean = (ExcluirBemPatrimonialMB) resolver
.getValue(facesContext.getELContext(), null,
"excluirBemPatrimonialMB");
managedBean.setId(new Long(this.bemPatrimonial.getId()).toString());
managedBean.selecionar();
return "/restrito/selecionarbemexclusao.jsf";
}
public String editar() {
FacesContext facesContext = FacesContext.getCurrentInstance();
ELResolver resolver = facesContext.getApplication().getELResolver();
EditarBemPatrimonialMB managedBean = (EditarBemPatrimonialMB) resolver
.getValue(facesContext.getELContext(), null,
"editarBemPatrimonialMB");
managedBean.setId(new Long(this.bemPatrimonial.getId()).toString());
managedBean.selecionar();
return "/restrito/editarbempatrimonial.jsf?faces-redirect=true";
}
public boolean permissao() {
Usuario usuario = (Usuario) FacesContext.getCurrentInstance()
.getExternalContext().getSessionMap().get("usuario");
if (usuario == null)
return false;
try {
if (usuario.isAdministrador())
return true;
else if (this.realizarBuscaEJB.possuiAcesso(usuario,
this.bemPatrimonial.getInstituicao()))
return true;
else
return false;
} catch (ModeloException m) {
m.printStackTrace();
}
return false;
}
public String resultado(BemPatrimonial b) {
try {
this.bemPatrimonial = b;
this.campos = this.utilMultimidiaEJB
.listarCampos(this.bemPatrimonial.getContainerMultimidia());
for (Descritor d : this.bemPatrimonial.getDescritores()) {
this.descritores += d.getDescritor() + " ";
}
for (Assunto a : this.bemPatrimonial.getAssuntos()) {
this.assuntos += a.getAssunto() + " ";
}
for (String s : this.bemPatrimonial.getFontesInformacao()) {
this.fontesInformacao.add(new StringContainer(s));
}
return this.redirecionar("/bempatrimonial.jsf", true);
} catch (Exception e) {
e.printStackTrace();
this.getMensagens().mensagemErro(this.traduzir("erroInterno"));
return null;
}
}
public String selecionaPagina(Integer numeroPagina) {
buscarNovaPagina(numeroPagina);
return "resultadosbusca";
}
public String proximaPagina() {
pagina++;
buscarNovaPagina(pagina);
return "resultadosbusca";
}
public String paginaAnterior() {
pagina--;
buscarNovaPagina(pagina);
return "resultadosbusca";
}
public String voltar() {
return this.buscar();
}
public void download(Integer index) {
FacesContext facesContext = FacesContext.getCurrentInstance();
ExternalContext externalContext = facesContext.getExternalContext();
HttpServletResponse response = (HttpServletResponse) externalContext
.getResponse();
Multimidia midia = this.bemPatrimonial.getContainerMultimidia()
.getMultimidia().get(index);
response.reset();
response.setContentType(midia.getContentType());
response.setHeader("Content-disposition", "attachment; filename="
+ midia.getNome());
BufferedInputStream input = null;
BufferedOutputStream output = null;
try {
input = new BufferedInputStream(new ByteArrayInputStream(
midia.getContent()));
output = new BufferedOutputStream(response.getOutputStream());
for (int length; (length = input.read(midia.getContent())) > 0;)
output.write(midia.getContent(), 0, length);
input.close();
output.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public String getBusca() {
return busca;
}
public void setBusca(String busca) {
this.busca = busca;
}
public List<BemPatrimonial> getBens() {
return bens;
}
public void setBens(List<BemPatrimonial> bens) {
this.bens = bens;
}
public boolean isRendSair() {
FacesContext context = FacesContext.getCurrentInstance();
Usuario usuario = (Usuario) context.getExternalContext()
.getSessionMap().get("usuario");
if (usuario != null) {
return true;
} else {
return false;
}
}
public boolean isRendLogin() {
FacesContext context = FacesContext.getCurrentInstance();
Usuario usuario = (Usuario) context.getExternalContext()
.getSessionMap().get("usuario");
if (usuario != null) {
return false;
} else {
return true;
}
}
public BemPatrimonial getBemPatrimonial() {
return bemPatrimonial;
}
public void setBemPatrimonial(BemPatrimonial bem) {
this.bemPatrimonial = bem;
}
public Integer getPagina() {
return pagina;
}
public void setPagina(Integer pagina) {
this.pagina = pagina;
}
public ArrayList<String> getPaginas() {
return paginas;
}
public void setPaginas(ArrayList<String> paginas) {
this.paginas = paginas;
}
public String url(Integer index) {
return "/multimidia?bean=realizarBuscaSimplesMB&indice="
+ index.toString() + "&thumb=true&type=false";
}
public boolean isProximaPaginaDisponivel() {
return proximaPaginaDisponivel;
}
public void setProximaPaginaDisponivel(boolean proximaPaginaDisponivel) {
this.proximaPaginaDisponivel = proximaPaginaDisponivel;
}
public UIData getControlePagina() {
return controlePagina;
}
public void setControlePagina(UIData controlePagina) {
this.controlePagina = controlePagina;
}
public RealizarBuscaSimplesRemote getRealizarBuscaEJB() {
return realizarBuscaEJB;
}
public void setRealizarBuscaEJB(RealizarBuscaSimplesRemote realizarBuscaEJB) {
this.realizarBuscaEJB = realizarBuscaEJB;
}
@Override
public String traduzir(String chave) {
FacesContext context = FacesContext.getCurrentInstance();
ResourceBundle bundle = context.getApplication().getResourceBundle(
context, MVControleMemoriaVirtual.bundleName);
return bundle.getString(chave);
}
@Override
public String redirecionar(String pagina, boolean redirect) {
return redirect ? pagina + "?faces-redirect=true" : pagina;
}
@Override
public String cancelar() {
// TODO Auto-generated method stub
return null;
}
@Override
public boolean validar() {
return false;
}
public String getContentType(Long id) {
try {
return this.utilMultimidiaEJB.getContentType(id.longValue());
} catch (ModeloException m) {
this.getMensagens().mensagemErro(this.traduzir("erroInterno"));
m.printStackTrace();
return null;
}
}
public String imagemDisplay(Long id) {
try {
if (id.equals(null) || id == null) {
throw new ModeloException(
"Campo ID para multimidia não pode ser null");
}
String tipo = this.utilMultimidiaEJB.getContentType(id.longValue());
return tipo.contains("image") ? "" : "none";
} catch (ModeloException m) {
this.getMensagens().mensagemErro(this.traduzir("erroInterno"));
m.printStackTrace();
return null;
}
}
public String videoDisplay(Long id) {
try {
if (id.equals(null) || id == null) {
throw new ModeloException(
"Campo ID para multimidia não pode ser null");
}
String tipo = this.utilMultimidiaEJB.getContentType(id.longValue());
return tipo.contains("video") ? "" : "none";
} catch (ModeloException m) {
this.getMensagens().mensagemErro(this.traduzir("erroInterno"));
m.printStackTrace();
return null;
}
}
public String midiaDisplay(Long id) {
try {
if (id.equals(null) || id == null) {
throw new ModeloException(
"Campo ID para multimidia não pode ser null");
}
String tipo = this.utilMultimidiaEJB.getContentType(id.longValue());
return !tipo.contains("image") && !tipo.contains("video") ? ""
: "none";
} catch (ModeloException m) {
this.getMensagens().mensagemErro(this.traduzir("erroInterno"));
m.printStackTrace();
return null;
}
}
public MensagensMB getMensagens() {
return mensagens;
}
public void setMensagens(MensagensMB mensagens) {
this.mensagens = mensagens;
}
public String getAssuntos() {
return assuntos;
}
public void setAssuntos(String assuntos) {
this.assuntos = assuntos;
}
public String getDescritores() {
return descritores;
}
public void setDescritores(String descritores) {
this.descritores = descritores;
}
public List<StringContainer> getFontesInformacao() {
return fontesInformacao;
}
public void setFontesInformacao(List<StringContainer> fontesInformacao) {
this.fontesInformacao = fontesInformacao;
}
public List<MVModeloCamposMultimidia> getCampos() {
return campos;
}
public void setCampos(List<MVModeloCamposMultimidia> campos) {
this.campos = campos;
}
}
|
package com.dev.lungyu.homecontroller;
import android.content.Context;
import android.net.wifi.WifiManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Spinner;
import android.widget.ToggleButton;
import com.dev.lungyu.homecontroller.fragment.situation.SituationPanel;
import com.dev.lungyu.homecontroller.fragment.situation.items.GridAdapter;
import com.dev.lungyu.homecontroller.fragment.situation.items.GridItem;
import com.dev.lungyu.homecontroller.fragment.situation.items.ItemConditionRule;
import com.dev.lungyu.homecontroller.tools.interpreter.DeviceInterpreter;
import com.dev.lungyu.homecontroller.webapi.DelAlertCondition;
import com.dev.lungyu.homecontroller.webapi.LoadAlertCondition;
import com.dev.lungyu.homecontroller.webapi.LoadDeviceControlGroup;
import com.dev.lungyu.homecontroller.webapi.LoadDeviceGroup;
import com.dev.lungyu.homecontroller.webapi.LoadDevices;
import com.dev.lungyu.homecontroller.webapi.SendAlertCondition;
import com.dev.lungyu.homecontroller.webapi.base.WebApiCallBack;
import com.dev.lungyu.homecontroller.webapi.datamodel.ConditionModel;
import com.dev.lungyu.homecontroller.webapi.datamodel.DeviceGroupInfo;
import com.dev.lungyu.homecontroller.webapi.datamodel.DeviceItemInfo;
import java.util.ArrayList;
import java.util.List;
public class SetupActivity extends Navigation_BaseActivity {
private static final String TAG = "SetupActivity";
private Context context = this;
private Spinner spinnerDevice;
private Spinner spinnerOption;
private Spinner spinnerCtrlDevice;
private Spinner spinnerArduino1;
private Spinner spinnerArduino2;
private EditText editConditionName;
private EditText editConditionValue;
private ToggleButton toggleButton;
private ListView listView;
private GridAdapter adapter;
private ArrayAdapter adapterArduino;
private List<String> arduinoString = new ArrayList<>();
private List<String> option = new ArrayList<>();
private List<String> devices = new ArrayList<>();
private List<String> ctrlDevices = new ArrayList<>();
private List<GridItem> rules = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_setup);
page_init(R.string.navigation_setup, PagePosition.SETUP);
spinnerDevice = (Spinner) findViewById(R.id.spinner1);
spinnerOption = (Spinner) findViewById(R.id.spinner2);
spinnerCtrlDevice = (Spinner) findViewById(R.id.spinner3);
spinnerArduino1 = (Spinner) findViewById(R.id.spinner);
spinnerArduino2 = (Spinner) findViewById(R.id.spinner4);
listView = (ListView) findViewById(R.id.listview);
editConditionName = (EditText) findViewById(R.id.edittext1);
editConditionValue = (EditText) findViewById(R.id.edittext2);
toggleButton = (ToggleButton) findViewById(R.id.toggleButton1);
initData();
ArrayAdapter adapterOption = new ArrayAdapter(this, android.R.layout.simple_spinner_item, option);
spinnerOption.setAdapter(adapterOption);
final ArrayAdapter adapterdevice = new ArrayAdapter(this, android.R.layout.simple_spinner_item, devices);
spinnerDevice.setAdapter(adapterdevice);
spinnerDevice.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
final ArrayAdapter adapterCtrldevice = new ArrayAdapter(this, android.R.layout.simple_spinner_item, ctrlDevices);
spinnerCtrlDevice.setAdapter(adapterCtrldevice);
spinnerCtrlDevice.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
adapterArduino = new ArrayAdapter(this, android.R.layout.simple_spinner_item, arduinoString);
spinnerArduino1.setAdapter(adapterArduino);
spinnerArduino2.setAdapter(adapterArduino);
spinnerArduino1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String mac = infos.get(position).getMac();
loadNotControlDevice(devices,adapterdevice);
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
spinnerArduino2.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String mac = infos.get(position).getMac();
loadControlDevice(ctrlDevices,adapterCtrldevice);
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
adapter = new GridAdapter(this, rules);
listView.setAdapter(adapter);
LoadAlertCondition();
loadArduinoInfo();
}
private List<DeviceItemInfo> infos;
private void loadArduinoInfo(){
final LoadDevices service = new LoadDevices(this);
service.setCallBackFunc(new WebApiCallBack() {
@Override
public void onProcessCallBack() {
infos = service.getDatas();
for(int i=0;i<infos.size();i++){
arduinoString.add(infos.get(i).getName());
}
adapterArduino.notifyDataSetChanged();
}
});
service.execute();
}
private void LoadAlertCondition(){
rule_init();
final LoadAlertCondition service = new LoadAlertCondition(this);
service.setCallBackFunc(new WebApiCallBack() {
@Override
public void onProcessCallBack() {
for(ConditionModel model : service.getDatas())
convert2UI(model);
adapter.notifyDataSetChanged();
}
});
service.execute();
}
private void rule_init(){
if(rules!= null)
rules.clear();
else
rules = new ArrayList<>();
}
private void loadControlDevice(final List<String> target_list,final BaseAdapter target_adapter){
final LoadDeviceControlGroup service = new LoadDeviceControlGroup(this);
service.setControl(true);
service.setCallBackFunc(new WebApiCallBack() {
@Override
public void onProcessCallBack() {
DeviceInterpreter interpreter = new DeviceInterpreter();
List<DeviceGroupInfo> infos = service.getDatas();
for(int i=0;i<infos.size();i++){
interpreter.setDeviceId(Integer.parseInt(infos.get(i).getType()));
target_list.add(interpreter.getDeviceName());
}
target_adapter.notifyDataSetChanged();
}
});
service.execute();
}
private void loadNotControlDevice(final List<String> target_list,final BaseAdapter target_adapter){
final LoadDeviceControlGroup service = new LoadDeviceControlGroup(this);
service.setControl(false);
service.setCallBackFunc(new WebApiCallBack() {
@Override
public void onProcessCallBack() {
DeviceInterpreter interpreter = new DeviceInterpreter();
List<DeviceGroupInfo> infos = service.getDatas();
for(int i=0;i<infos.size();i++){
interpreter.setDeviceId(Integer.parseInt(infos.get(i).getType()));
target_list.add(interpreter.getDeviceName());
}
target_adapter.notifyDataSetChanged();
}
});
service.execute();
}
private void loadDeviceGroup(String mac,final List<String> target_list,final BaseAdapter target_adapter){
Log.d(TAG,"load device group.");
Log.d(TAG,mac);
Log.d(TAG,target_list.toString());
target_list.clear();
final LoadDeviceGroup service = new LoadDeviceGroup(this);
service.setMacAddress(mac);
service.setCallBackFunc(new WebApiCallBack() {
@Override
public void onProcessCallBack() {
DeviceInterpreter interpreter = new DeviceInterpreter();
List<DeviceGroupInfo> infos = service.getDatas();
for(int i=0;i<infos.size();i++){
interpreter.setDeviceId(Integer.parseInt(infos.get(i).getType()));
target_list.add(interpreter.getDeviceName());
}
target_adapter.notifyDataSetChanged();
}
});
service.execute();
}
public void onAdd(View v) {
String condition_name = editConditionName.getText().toString();
String condition_value = editConditionValue.getText().toString();
String device = spinnerDevice.getSelectedItem().toString();
String option = spinnerOption.getSelectedItem().toString();
String triggerDevice = spinnerCtrlDevice.getSelectedItem().toString();
if(!inputValid())
return;
ConditionModel model = new ConditionModel();
model.setConditionName(condition_name);
model.setConditionValue(condition_value);
model.setDevice(device);
model.setOption(option);
model.setActionId(toggleButton.isChecked() ? 1 : 0);
model.setActionDevice(triggerDevice);
model.setInputArduinoMac(infos.get((int)spinnerArduino1.getSelectedItemId()).getMac());
model.setOutputArduinoMac(infos.get((int)spinnerArduino2.getSelectedItemId()).getMac());
model.setId(String.valueOf(rules.size()));
addAlert2Server(model);
Log.d(TAG, model.getUIMessage());
convert2UI(model);
inputClear();
}
private void convert2UI(ConditionModel model){
rules.add(new ItemConditionRule(model,onItemDeleteListener));
adapter.notifyDataSetChanged();
}
private void addAlert2Server(ConditionModel model){
final SendAlertCondition service = new SendAlertCondition(this,model);
service.execute();
}
private ItemConditionRule.OnItemDeleteListener onItemDeleteListener = new ItemConditionRule.OnItemDeleteListener() {
@Override
public void delete(ConditionModel model) {
final DelAlertCondition service = new DelAlertCondition(context);
service.setAlert_id(String.valueOf(model.getActionId()));
service.setCallBackFunc(new WebApiCallBack() {
@Override
public void onProcessCallBack() {
//reload alert list
LoadAlertCondition();
}
});
service.execute();
}
};
private void inputClear(){
editConditionName.setText("");
editConditionValue.setText("");
}
private boolean inputValid() {
boolean isValid = true;
if (editConditionName.getText().toString().isEmpty()) {
editConditionName.setError("空白");
isValid = false;
}
if (editConditionValue.getText().toString().isEmpty()) {
editConditionValue.setError("空白");
isValid = false;
}
return isValid;
}
private void initData() {
option.add(">");
option.add("<");
option.add("=");
option.add(">=");
option.add("<=");
}
}
|
package com.thoughtworks.rslist.api;
import com.thoughtworks.rslist.domain.RsEvent;
import com.thoughtworks.rslist.dto.RsEventDto;
import com.thoughtworks.rslist.exception.InvalidIndexException;
import com.thoughtworks.rslist.service.RsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import java.util.List;
@RestController
public class RsController {
@Autowired
private RsService rsService;
@GetMapping("/rs/events")
@ResponseBody
public ResponseEntity rsList() {
List<RsEventDto> rsList = rsService.rsList();
return ResponseEntity.ok(rsList);
}
@GetMapping("/rs/event/{index}")
@ResponseBody
public ResponseEntity rsListIndex(@PathVariable int index) throws InvalidIndexException {
return ResponseEntity.ok(rsService.rsListIndex(index));
}
@GetMapping("/rs/eventBetween")
@ResponseBody
public ResponseEntity rsListBetween(@RequestParam int start, @RequestParam int end) throws InvalidIndexException {
return ResponseEntity.ok(rsService.rsListBetween(start, end));
}
@PostMapping("/rs/event")
public ResponseEntity rsEvent(@RequestBody @Valid RsEvent rsEvent) throws InvalidIndexException {
return ResponseEntity.created(null).body(rsService.rsEvent(rsEvent));
}
@PatchMapping(value = "/rs/{rsEventId}")
public ResponseEntity update(@PathVariable int rsEventId, @RequestParam(required = false) String eventName, @RequestParam(required = false) String keyWords, @RequestParam int userId) throws Exception {
RsEvent rsEvent = new RsEvent(eventName, keyWords, userId);
RsEventDto rsEventDto = rsService.update(rsEventId, rsEvent);
return ResponseEntity.ok(rsEventDto);
}
@DeleteMapping("/rs/delete/{index}")
public ResponseEntity delete(@PathVariable int index) throws InvalidIndexException {
rsService.delete(index);
return ResponseEntity.ok().build();
}
}
|
package com.optimus;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class QbaycreditApplication {
public static void main(String[] args) {
//上传到github
SpringApplication.run(QbaycreditApplication.class, args);
}
}
|
package com.yuecheng.yue.ui.presenter;
import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import com.flyco.animation.BounceEnter.BounceRightEnter;
import com.flyco.animation.SlideExit.SlideLeftExit;
import com.flyco.dialog.entity.DialogMenuItem;
import com.flyco.dialog.listener.OnOperItemClickL;
import com.flyco.dialog.widget.ActionSheetDialog;
import com.flyco.dialog.widget.NormalListDialog;
import com.flyco.dialog.widget.popup.BubblePopup;
import com.lljjcoder.Interface.OnCityItemClickListener;
import com.lljjcoder.bean.CityBean;
import com.lljjcoder.bean.DistrictBean;
import com.lljjcoder.bean.ProvinceBean;
import com.lljjcoder.citywheel.CityConfig;
import com.lljjcoder.citywheel.CityPickerView;
import com.yuecheng.yue.R;
import com.yuecheng.yue.http.ICommonInteractorCallback;
import com.yuecheng.yue.ui.activity.YUE_ISetUserInfoView;
import com.yuecheng.yue.ui.bean.YUE_SPsave;
import com.yuecheng.yue.ui.interactor.YUE_ISetUserInfoInteractor;
import com.yuecheng.yue.ui.interactor.impl.YUE_SetUserInfoInteractorImpl;
import com.yuecheng.yue.util.ColorUtil;
import com.yuecheng.yue.util.CommonUtils;
import com.yuecheng.yue.util.PhotoUtils;
import com.yuecheng.yue.util.YUE_LogUtils;
import com.yuecheng.yue.util.YUE_SharedPreferencesUtils;
import com.yuecheng.yue.widget.LoadDialog;
import com.yuecheng.yue.widget.datetimepicker.DatePickerPopWin;
import java.util.ArrayList;
import io.reactivex.disposables.Disposable;
import static android.support.v4.app.ActivityCompat.requestPermissions;
import static io.rong.imkit.plugin.image.PictureSelectorActivity.REQUEST_CODE_ASK_PERMISSIONS;
/**
* Created by administraot on 2017/11/22.
*/
public class YUE_SetUserInfoViewPresenter {
private String TAG = getClass().getSimpleName();
private YUE_ISetUserInfoView mView;
private Context mContext;
private PhotoUtils mPhotoUtils;
private Uri mSelectUri;
private CityConfig mCityConfig;
private CityPickerView mCityPicker;
private String mColor;
private YUE_ISetUserInfoInteractor mInteractor;
private String mSign;//签名
private String mNickName;//昵称
private String mSex;//性别
private String mBirthday;//生日
private String mJob;//职业
private String mCompany;//公司
private String mEmail;//邮箱
private String mNowAddress;//现居地
private String mDetailAddress;//详细地址
private String mHomeTownAddress;//家乡
public YUE_SetUserInfoViewPresenter(Context context, YUE_ISetUserInfoView a) {
super();
this.mView = a;
this.mContext = context;
mColor = ColorUtil.int2Hex(CommonUtils.getColorByAttrId(mContext, R.attr
.colorPrimary));
mInteractor = new YUE_SetUserInfoInteractorImpl();
}
// 设置头像
public void setUserIcon() {
// 弹出弹出框。选择图片
actionSheetDialog();
}
private void actionSheetDialog() {
final String[] stringItems = {"从相册选择", "拍照"};
final ActionSheetDialog dialog = new ActionSheetDialog(mContext, stringItems, null);
dialog.isTitleShow(false)
.cancelText(CommonUtils.getColorByAttrId(mContext, R.attr.colorPrimary))
.itemTextColor(CommonUtils.getColorByAttrId(mContext, R.attr.colorPrimary))
.show();
dialog.setOnOperItemClickL(new OnOperItemClickL() {
@Override
public void onOperItemClick(AdapterView<?> parent, View view, int position, long id) {
// mHomeView.showMessage(stringItems[position]);
//todo 选择照片
switch (position) {
case 0://相册
mPhotoUtils.selectPicture((Activity) mView);
break;
case 1://相机
checkCameraPermission();
mPhotoUtils.takePicture((Activity) mView);
break;
}
dialog.dismiss();
}
});
}
private void checkCameraPermission() {
if (Build.VERSION.SDK_INT >= 23) {
int checkCallPhonePermission = ContextCompat.checkSelfPermission(mContext, Manifest
.permission.CAMERA);
if (checkCallPhonePermission != PackageManager.PERMISSION_GRANTED) {
requestPermissions((Activity) mContext, new String[]{Manifest.permission.CAMERA},
REQUEST_CODE_ASK_PERMISSIONS);
return;
} else {
new AlertDialog.Builder(mContext)
.setMessage("您需要在设置里打开相机权限。")
.setPositiveButton("确认", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
requestPermissions((Activity) mContext,new String[]{Manifest.permission
.CAMERA},
REQUEST_CODE_ASK_PERMISSIONS);
}
})
.setNegativeButton("取消", null)
.create().show();
}
return;
}
}
public void dealResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case PhotoUtils.INTENT_CROP:
case PhotoUtils.INTENT_TAKE:
case PhotoUtils.INTENT_SELECT:
mPhotoUtils.onActivityResult((Activity) mView, requestCode, resultCode, data);
break;
}
}
//选择照片后回调监听
public void pickIconListener() {
mPhotoUtils = new PhotoUtils(new PhotoUtils.OnPhotoResultListener() {
@Override
public void onPhotoResult(Uri uri) {
if (uri != null && !TextUtils.isEmpty(uri.getPath())) {
mSelectUri = uri;
mView.setIcon(mSelectUri);
uploadHeaderIcon(mSelectUri.getPath());
// YUE_LogUtils.i(TAG,uri.getEncodedPath());// ------>
// /storage/emulated/0/crop_file.jpg
// LoadDialog.show(mContext);
// request(GET_QI_NIU_TOKEN);
}
}
@Override
public void onPhotoCancel() {
}
});
}
private void uploadHeaderIcon(String path) {
LoadDialog.show(mContext);
mInteractor.uploadHeaderIcon(YUE_SharedPreferencesUtils.getParam(mContext, YUE_SPsave
.YUE_LOGING_PHONE,"")+
"_imageHeaderIcon",
path,new
ICommonInteractorCallback(){
@Override
public void loadSuccess(Object object) {
LoadDialog.dismiss(mContext);
YUE_LogUtils.d(TAG,object.toString());
}
@Override
public void loadFailed() {
}
@Override
public void loadCompleted() {
}
@Override
public void addDisaposed(Disposable disposable) {
}
});
}
//设置性别
public void setUserSex() {
userSexNormalListDialogNoTitle();
}
private void userSexNormalListDialogNoTitle() {
final ArrayList<DialogMenuItem> mMenuItems = new ArrayList<DialogMenuItem>() {
{
add(new DialogMenuItem("男", R.drawable.img_boy));
add(new DialogMenuItem("女", R.drawable.img_girl));
}
};
final NormalListDialog dialog = new NormalListDialog(mContext, mMenuItems);
dialog.title("请选择,性别按生理区分")//
.isTitleShow(true)//
.titleTextSize_SP(18)//
.titleBgColor(CommonUtils.getColorByAttrId(mContext, R.attr.colorPrimary))//
.itemPressColor(Color.parseColor("#85D3EF"))//
.itemTextColor(Color.parseColor("#303030"))//
.itemTextSize(15)//
.cornerRadius(10)//
.widthScale(0.75f)//
.showAnim(new BounceRightEnter())
.dismissAnim(new SlideLeftExit())
.show();
dialog.setOnOperItemClickL(new OnOperItemClickL() {
@Override
public void onOperItemClick(AdapterView<?> parent, View view, int position, long id) {
// T.showShort(mContext, mMenuItems.get(position).mOperName);
YUE_LogUtils.i(this.getClass().getSimpleName(), mMenuItems.get(position).mOperName);
mView.setSex(mMenuItems.get(position).mOperName);
dialog.dismiss();
}
});
}
//设置签名
public void setUserDisplay() {
View view = View.inflate(mContext, R.layout.setuserdisplay_pop_layout, null);
final EditText mUserDesc = (EditText) view.findViewById(R.id.et_setdesc);
//设置框内字显示旧签名
mUserDesc.setText(mView.getUserSign());
//设置光标到末尾
mUserDesc.setSelection(mView.getUserSign().length());
BubblePopup bubblePopup = new BubblePopup(mContext, view);
bubblePopup.anchorView(mView.getWrappedView())//控件
.gravity(Gravity.BOTTOM)
.widthScale(1)
.triangleHeight(10)
.triangleWidth(20)
.bubbleColor(CommonUtils.getColorByAttrId(mContext, R.attr.colorPrimary))
.dimEnabled(true)
.showAnim(new BounceRightEnter())
.dismissAnim(new SlideLeftExit())
.show();
bubblePopup.setOnDismissListener(new DialogInterface.OnDismissListener() {
@Override
public void onDismiss(DialogInterface dialogInterface) {
//消失则把已经输入的赋值
mView.setUserSign(mUserDesc.getText().toString());
}
});
}
//设置生日
public void setUserBirtyday() {
DatePickerPopWin pickerPopWin = new DatePickerPopWin.Builder(mContext, new
DatePickerPopWin.OnDatePickedListener() {
@Override
public void onDatePickCompleted(int year, int month, int day, String dateDesc) {
mView.setBirthday(dateDesc);
}
}).textConfirm("确定") //text of confirm button
.textCancel("取消") //text of cancel button
.btnTextSize(16) // button text size
.viewTextSize(25) // pick view text size
.colorCancel(CommonUtils.getColorByAttrId(mContext, R.attr.colorPrimary)) //color
// of cancel button
.colorConfirm(CommonUtils.getColorByAttrId(mContext, R.attr.colorPrimary))//color
// of confirm button
.minYear(1960) //min year in loop
.maxYear(2017) // max year in loop
.dateChose("2006-08-01") // date chose when init popwindow
.build();
pickerPopWin.showPopWin((Activity) mView);
}
//设置地址
public void setUserAddress() {
mCityConfig = new CityConfig.Builder(mContext).title("选择地区")
.titleBackgroundColor(mColor)
.textSize(14)
.titleTextColor("#ffffff")
.textColor(mColor)
.confirTextColor("#ffffff")
.cancelTextColor("#ffffff")
.setCityWheelType(CityConfig.WheelType.PRO_CITY_DIS)//三级联动
.showBackground(true)//显示半透明背景
.visibleItemsCount(5)
.province("湖北")
.city("十堰")
.district("竹溪县")//这三个配合定位使用
.provinceCyclic(false)
.cityCyclic(true)
.districtCyclic(true)
.itemPadding(16)
.setCityInfoType(CityConfig.CityInfoType.DETAIL)
.build();
mCityPicker = new CityPickerView(mCityConfig);
mCityPicker.show();
mCityPicker.setOnCityItemClickListener(new OnCityItemClickListener() {
@Override
public void onSelected(ProvinceBean province, CityBean city, DistrictBean district) {
if (district != null)
//返回结果
YUE_LogUtils.i(mContext.getClass().getSimpleName(),(province.toString() + "-" + city.toString()));
mView.setNowAddress(province.toString() + "-" + city.toString() + "-" +
district
.toString());
}
@Override
public void onCancel() {
}
});
}
public void setUserHomeAddress() {
mCityConfig = new CityConfig.Builder(mContext).title("选择地区")
.titleBackgroundColor(mColor)
.textSize(14)
.titleTextColor("#ffffff")
.textColor(mColor)
.confirTextColor("#ffffff")
.cancelTextColor("#ffffff")
.setCityWheelType(CityConfig.WheelType.PRO_CITY_DIS)//省市三级联动
.showBackground(true)//显示半透明背景
.visibleItemsCount(5)
.province("湖北")
.city("十堰")
// .district("竹溪县")//这三个配合定位使用
.provinceCyclic(false)
.cityCyclic(true)
// .districtCyclic(true)
.itemPadding(16)
.setCityInfoType(CityConfig.CityInfoType.DETAIL)
.build();
mCityPicker = new CityPickerView(mCityConfig);
mCityPicker.show();
mCityPicker.setOnCityItemClickListener(new OnCityItemClickListener() {
@Override
public void onSelected(ProvinceBean province, CityBean city, DistrictBean district) {
if (district != null)
//返回结果
YUE_LogUtils.i(mContext.getClass().getSimpleName(),(province.toString() + "-" + city.toString()));
mView.setHomeTownAddress(province.toString() + "-" + city.toString());
}
@Override
public void onCancel() {
}
});
}
public void submitUpdateInfo() {
}
}
|
package com.koreait.guestbook.model;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.koreait.dao.GuestbookDao;
import com.koreait.dto.GuestbookDto;
import com.oreilly.servlet.MultipartRequest;
import com.oreilly.servlet.multipart.DefaultFileRenamePolicy;
public class InsertAction implements Action {
@Override
public String command(HttpServletRequest request, HttpServletResponse response) {
// 업로드 될 파일의 실제 경로는 request 로도 구할 수 있다.
String realPath = request.getServletContext().getRealPath("/upload");
MultipartRequest mr = null;
try {
mr = new MultipartRequest(
request,
realPath,
1024 * 1024 * 10, // 10MB
"utf-8",
new DefaultFileRenamePolicy());
} catch (IOException e) {
e.printStackTrace();
}
// dto를 만들어서 dao의 getInsert() 에 전달하기 위함
GuestbookDto dto = new GuestbookDto();
dto.setWriter( mr.getParameter("writer") );
dto.setTitle( mr.getParameter("title") );
dto.setEmail( mr.getParameter("email") );
dto.setPw( mr.getParameter("pw") );
dto.setContent( mr.getParameter("content") );
// 첨부파일 유무에 따라서 filename 값을 결정
if ( mr.getFile("filename") != null ) {
dto.setFilename( mr.getFilesystemName("filename") );
} else {
dto.setFilename("");
}
// dto를 getInsert()에 전달하면,
// getInsert()는 받은 dto를 guestbook.xml에게 전달함
GuestbookDao dao = GuestbookDao.getInstance();
int result = dao.getInsert(dto);
// 성공, 실패에 따라 다른 path 사용
String path = null;
if (result > 0) {
path = "/list.do"; // 삽입 성공 -> 전체 보기
} else {
path = "/pageForInsert.do"; // 삽입 실패 -> 다시 삽입 페이지로
}
return path;
}
}
|
package br.com.desafio.models;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
/**
* Utilizado as anotações do Lombok para reduzir boilerplate na aplicação.
* @author Windows
*
*/
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Entity (name="Pessoa")
public class PessoasEntity {
@Id
@Column
private Integer id;
@Column
private String nome;
@Column
private String sobrenome;
}
|
package exer;
import java.util.Arrays;
public class Day05 {
public static void main(String[] args) {
int[] arr = { 1, 2, 3, 4, 3, 2,1};
int[] arr1 = { 1, 2, 3, 4, 3, 2, 1 };
Test3(50);
}
public static void Test1() {
int[] arr = { 10, 20, 30, 40, 50, 60, 66, 70, 80, 99 };
System.out.println("您的大乐透号码为:");
System.out.println(Arrays.toString(arr));
}
public static void Test2() {
String[] str1 = { "A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K" };
String[] str2 = { "黑桃", "红桃", "梅花", "方片" };
for (int i = 0; i < str2.length; i++) {
for (int j = 0; j < str1.length; j++) {
System.out.print(str2[i] + str1[j] + " ");
}
System.out.println();
}
}
public static void Test3(int num) {
String[] str1 = { "A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K" };
String[] str2 = { "黑桃", "红桃", "梅花", "方片" };
String[][] str = new String[4][13];
for (int i = 0; i < str.length; i++) {
for (int j = 0; j < str[i].length; j++) {
str[i][j] = str2[i] + str1[j];
}
}
/*
for (int i = 0; i < str.length; i++) {
for (int j = 0; j < str[i].length; j++) {
System.out.print(str[i][j] + " ");
}
System.out.println();
}
*/
int i = num / 14;
int j = (num - i * 13 - 1) % 13;
System.out.println(str[i][j]);
}
public static void Test4() {
char[] c = { 'a', 'l', 'f', 'm', 'f', 'o', 'b', 'b', 's', 'n' };
char[] c1 = new char[26];
int[] i1 = new int[26];
for (int i = 0; i < c1.length; i++) {
c1[i] = (char) (97 + i);
}
for (int i = 0; i < c1.length; i++) {
for (int j = 0; j < c.length; j++) {
if(c1[i] == c[j]){
i1[i] += 1;
}
}
}
for (int i = 0; i < c1.length; i++) {
if(i1[i] == 0)continue;
System.out.println(c1[i] + "--" + i1[i]);
}
}
public static void Test5() {
int[] arr = { 95, 92, 75, 56, 98, 71, 80, 58, 91, 91 };
int count = 0;
int sum = 0;
for (int i = 0; i < arr.length; i++) {
sum += arr[i];
}
double avg = sum * 1.0 / arr.length;
for (int i = 0; i < arr.length; i++) {
count += avg > arr[i] ? 1 : 0;
}
System.out.println("高于平均分:" + avg + "的个数有" + count + "个");
}
public static void Test6(int[] arr) {
int count = 0;
for (int i = 0; i < arr.length / 2; i++) {
if (arr[i] == arr[arr.length - 1 - i]) {
count++;
}
}
System.out.print(Arrays.toString(arr));
if (count == arr.length / 2) {
System.out.println("是否对称:true");
} else {
System.out.println("是否对称:false");
}
}
public static void Test7(int[] arr, int[] arr1) {
int len1 = arr.length;
int len2 = arr1.length;
int len = len1 < len2 ? len1 : len2;
int count = 0;
System.out.println(Arrays.toString(arr));
System.out.println(Arrays.toString(arr1));
System.out.print("是否一致:");
if (len1 == len2) {//先确认数组长度是否一致
for (int i = 0; i < len; i++) {//如果数组长度一致,则比较数组每个元素内容是否一致
if (arr[i] == arr1[i])
count++;//元素内容相同则计数器+1
}
if (count == len1) {//如果计数器累加后的数字与数组长度一样,则为相同的数组
System.out.println(true);
} else {
System.out.println(false);
}
} else {
System.out.println(false);
}
}
public static void Test8() {
int[] arr = {26,67,49,38,52,66,7,71,56,87};
System.out.println("原数组:" + "\n" + Arrays.toString(arr));
for (int i = 0; i < arr.length / 2; i++) {
if(arr[i] % 2 == 0){
for(int j = arr.length - 1;j > arr.length / 2;j--){
if(arr[j] % 2 == 1){
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
break;
}
}
}
}
System.out.println("排序后:" + "\n" + Arrays.toString(arr));
}
public static void Test8_1() {
int[] arr = {26,67,49,38,52,66,7,71,56,87};
System.out.println("原数组:" + "\n" + Arrays.toString(arr));
int start = 0,end = arr.length - 1;
while(start < end){//指针相交后停止
while(arr[start] % 2 == 1){//从头开始找偶数,找到后停止
start++;
}
while(arr[end] % 2 == 0){//从尾找奇数,找到后停止
end--;
}
int temp = arr[start];//交换
arr[start] = arr[end];
arr[end] = temp;
start++;//指针自增、自减
end--;
}
System.out.println("排序后:" + "\n" + Arrays.toString(arr));
}
public static void Test9() {
int count = 0;
int[] arr = {9,10,6,6,1,9,3,5,6,4};
System.out.println("原数组:" + "\n" + Arrays.toString(arr));
for (int i = 0; i < arr.length; i++) {
for (int j = i + 1; j < arr.length; j++) {
if(arr[j] != 0 && arr[i] == arr[j]){
arr[j] = 0;//将重复的元素置为0
count++;//每置一次0便累加1
}
}
}
int[] arr1 = new int[arr.length - count];
for (int i = 0,j = 0; i < arr1.length; i++) {
if(arr[j] == 0)j++;//将旧数组元素赋值给新数组,遇到0就跳过
arr1[i] = arr[j];
j++;
}
System.out.println("排序后:" + "\n" + Arrays.toString(arr1));
}
}
|
package hibernate.jpa.daoClass;
import hibernate.jpa.tableClass.Microphones;
import javax.persistence.EntityManager;
public class MicrophonesDao extends AbstractDao<Microphones> {
public MicrophonesDao(EntityManager entityManager) {
super(entityManager);
}
}
|
package com.androidavenger.gyminventory.view;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.androidavenger.gyminventory.R;
import com.androidavenger.gyminventory.model.db.data.Equipement;
import com.androidavenger.gyminventory.model.db.data.EquipementDatabaseHelper;
import static com.androidavenger.gyminventory.utils.constants.GYM_EQUIPMENT;
public class DetailsActivity extends AppCompatActivity {
EquipementDatabaseHelper databaseHelper;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_details);
databaseHelper= new EquipementDatabaseHelper(this);
Intent intent = getIntent();
Equipement myOrder = intent.getParcelableExtra(GYM_EQUIPMENT);
if(myOrder != null) {
displayDetails(myOrder);
}
Button purchase = findViewById(R.id.purchase_button);
purchase.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
EditText purchaseNumber = findViewById(R.id.num_items);
String purchaseString = purchaseNumber.getText().toString();
if("".equals(purchaseString)) {
Toast.makeText(DetailsActivity.this, "Enter a valid number", Toast.LENGTH_LONG).show();
} else {
int numPurchase = Integer.parseInt(purchaseNumber.getText().toString());
databaseHelper.purchaseEquipment(myOrder, numPurchase);
finish();
}
}
});
}
private void displayDetails(Equipement myOrder) {
TextView nameEquip = findViewById(R.id.name_equip_textview);
String itemName = "Name: " + myOrder.getEquipName();
nameEquip.setText(itemName);
TextView descriptionItem = findViewById(R.id.item_descrp);
String itemDes = myOrder.getEquipDescr();
descriptionItem.setText(itemDes);
TextView priceItem = findViewById(R.id.price_textview);
String price = String.valueOf(myOrder.getEquipPrice());
priceItem.setText(price);
TextView numOwned = findViewById(R.id.owned_view);
String owned = String.valueOf(myOrder.getOwned());
numOwned.setText(owned);
}
}
|
package presentacion.controlador.command.CommandLibro;
import java.util.Collection;
import negocio.factorias.FactorySA;
import negocio.libro.SALibro;
import negocio.libro.TFLibro;
import presentacion.contexto.Contexto;
import presentacion.controlador.command.Command;
import presentacion.eventos.EventosLibro;
/**
* The Class ListarLibro.
*/
public class ListarLibro implements Command {
/*
* (non-Javadoc)
*
* @see presentacion.controlador.command.Command#execute(java.lang.Object)
*/
@Override
public Contexto execute(final Object objeto) {
final SALibro libroSA = FactorySA.getInstance().createLibro();
String mensaje;
Contexto contexto;
try {
final Collection<TFLibro> listaLibros = libroSA.listarLibros();
contexto = new Contexto(EventosLibro.LISTAR_LIBROS_OK, listaLibros);
} catch (final Exception e) {
mensaje = e.getMessage();
contexto = new Contexto(EventosLibro.LISTAR_LIBROS_KO, mensaje);
}
return contexto;
}
}
|
package com.iontrading.buildbot2;
import java.util.Collection;
import org.junit.Before;
import org.junit.Test;
import static org.mockito.Matchers.*;
import static org.mockito.Mockito.*;
import org.pircbotx.Colors;
import org.pircbotx.PircBotX;
import org.pircbotx.User;
import org.pircbotx.hooks.events.PrivateMessageEvent;
import org.pircbotx.hooks.managers.ListenerManager;
import com.google.common.collect.Lists;
import com.iontrading.model.Build;
public class BuildBotTest {
private PircBotX buildBot;
private BuildBot bb;
private IQuery query;
@Before
public void beforeMethod() throws Exception {
buildBot = mock(PircBotX.class);
query = mock(IQuery.class);
ListenerManager listenerManager = mock(ListenerManager.class);
bb = new BuildBot(buildBot, query);
when(buildBot.getListenerManager()).thenReturn(listenerManager);
doNothing().when(buildBot).connect(anyString());
doNothing().when(buildBot).sendAction(isA(User.class), anyString());
}
@Test
public void testNameIsSetOnStart() throws Exception {
bb.start();
verify(buildBot).setName("buildbot");
}
@Test
public void testBotConnectsOnStart() throws Exception {
bb.start();
verify(buildBot).connect(anyString(), anyInt());
}
@Test
public void testBotJoinsOurChannelOnStart() throws Exception {
doNothing().when(buildBot).joinChannel(anyString());
bb.start();
verify(buildBot).joinChannel("#xtp-tests");
}
@Test
public void testBotSendsMessageOnChannelOnStart() throws Exception {
doNothing().when(buildBot).sendMessage(anyString(), anyString());
String message = Colors.UNDERLINE + "Up & running, will report build status";
bb.start();
verify(buildBot).sendMessage("#xtp-tests", message);
}
@Test
public void testBotReportsFailingTestsOnPrivateMessage() throws Exception {
User user = mock(User.class);
Build build = mock(Build.class);
String statusTxt = "Status text for test build";
Collection<Build> builds = Lists.newArrayList(build);
when(query.queryFails()).thenReturn(builds);
when(build.getStatusText()).thenReturn(statusTxt);
PrivateMessageEvent<PircBotX> event = new PrivateMessageEvent<PircBotX>(buildBot, user, "!fails");
bb.onPrivateMessage(event);
verify(query).queryFails();
verify(buildBot, times(1)).sendAction(user, statusTxt);
}
@Test
public void testBotReportsAllTestsOnPrivateMessage() throws Exception {
User user = mock(User.class);
Build build = mock(Build.class);
Build build2 = mock(Build.class);
Collection<Build> builds = Lists.newArrayList(build, build2);
when(query.queryAll()).thenReturn(builds);
PrivateMessageEvent<PircBotX> event = new PrivateMessageEvent<PircBotX>(buildBot, user, "!list");
bb.onPrivateMessage(event);
verify(query).queryAll();
verify(buildBot, times(2)).sendAction(isA(User.class), anyString());
}
}
|
package com.qq.controllor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetails;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.qq.connect.QQConnectException;
import com.qq.connect.api.OpenID;
import com.qq.connect.javabeans.AccessToken;
import com.qq.connect.oauth.Oauth;
import com.qq.domain.QQuser;
import com.qq.service.QQuserService;
import com.ybg.base.util.DesUtils;
import com.ybg.base.util.ServletUtil;
import com.ybg.rbac.user.UserStateConstant;
import com.ybg.rbac.user.domain.User;
import com.ybg.rbac.user.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
@Api("QQ登陆接口")
@Controller
@RequestMapping(value = { "/common/qq/login_do/" })
public class QQloginControllor {
@Autowired
QQuserService qQuserService;
@Autowired
UserService userService;
@Autowired
AuthenticationManager authenticationManager;
@ApiOperation(value = "QQ登陆", notes = "", produces = MediaType.TEXT_HTML_VALUE)
@RequestMapping(value = { "login.do" }, method = { RequestMethod.GET, RequestMethod.POST })
public String login(HttpServletRequest request, HttpServletResponse response, ModelMap map) throws Exception {
AccessToken accessTokenObj = new Oauth().getAccessTokenByRequest(request);
String accessToken = null, openID = null;
long tokenExpireIn = 0L;
if (accessTokenObj.getAccessToken().equals("")) {
// 我们的网站被CSRF攻击了或者用户取消了授权
// 做一些数据统计工作
System.out.print("没有获取到响应参数");
}
else {
accessToken = accessTokenObj.getAccessToken();
tokenExpireIn = accessTokenObj.getExpireIn();
request.getSession().setAttribute("demo_access_token", accessToken);
request.getSession().setAttribute("demo_token_expirein", String.valueOf(tokenExpireIn));
// 利用获取到的accessToken 去获取当前用的openid -------- start
OpenID openIDObj = new OpenID(accessToken);
openID = openIDObj.getUserOpenID();
QQuser qquser = qQuserService.getByopenId(openID);
if (qquser == null) {
map.put("openid", openID);
return "/qq/qqbund";
}
User user = userService.get(qquser.getUserid());
if (user.getState().equals(UserStateConstant.LOCK)) {
return "/lock";
}
if (user.getState().equals(UserStateConstant.DIE)) {
return "/die";
}
if (!user.getState().equals(UserStateConstant.OK)) {
return "";// XXX 返回错误的请求 比如账号封锁、未激活等状态;
}
/***/
UsernamePasswordAuthenticationToken token2 = new UsernamePasswordAuthenticationToken(user.getUsername(), new DesUtils().decrypt(user.getCredentialssalt()));
token2.setDetails(new WebAuthenticationDetails(request));
Authentication authenticatedUser = authenticationManager.authenticate(token2);
SecurityContextHolder.getContext().setAuthentication(authenticatedUser);/****/
return "redirect:/common/login_do/index.do";
}
return null;
}
@ApiOperation(value = "绑定QQ账号页面", notes = "", produces = MediaType.TEXT_HTML_VALUE)
@RequestMapping(value = "bund.do", method = { RequestMethod.GET, RequestMethod.POST })
public String weibobund(HttpServletRequest request, HttpServletResponse response) throws Exception {
String username = ServletUtil.getStringParamDefaultBlank(request, "username");
String password = ServletUtil.getStringParamDefaultBlank(request, "password");
String openid = ServletUtil.getStringParamDefaultBlank(request, "openid");
if (openid.equals("")) {
return null;
}
QQuser weibouser = qQuserService.getByopenId(openid);
if (weibouser != null) {
return null;
}
request.removeAttribute("error");
User user = userService.login(username);
if (!(user.isAccountNonLocked())) {
request.setAttribute("error", "用户已经被锁定不能绑定,请与管理员联系!");
}
if (user.isAccountNonExpired()) {
request.setAttribute("error", "账号未激活!");
}
if (new DesUtils().encrypt(password).equals(user.getPassword())) {
UsernamePasswordAuthenticationToken token2 = new UsernamePasswordAuthenticationToken(user.getUsername(), new DesUtils().decrypt(user.getCredentialssalt()));
token2.setDetails(new WebAuthenticationDetails(request));
Authentication authenticatedUser = authenticationManager.authenticate(token2);
SecurityContextHolder.getContext().setAuthentication(authenticatedUser);
QQuser bean = new QQuser();
bean.setOpenid(openid);
bean.setUserid(user.getId());
qQuserService.create(bean);
return "redirect:/common/login_do/index.do";
}
else {
request.setAttribute("error", "用户或密码不正确!");
return "/login";
}
}
@ApiOperation(value = "QQ登陆页面", notes = "", produces = MediaType.TEXT_HTML_VALUE)
@RequestMapping(value = { "index.do" }, method = { RequestMethod.GET, RequestMethod.POST })
public String index(HttpServletRequest request, HttpServletResponse response, ModelMap map) throws QQConnectException {
return "redirect:" + new Oauth().getAuthorizeURL(request);
}
}
|
package main.java;
import jodd.util.collection.ArrayEnumeration;
import java.util.Iterator;
import java.util.Vector;
public class FF_p_norm {
public static Vector normalize(Vector in_vector, int norm){
if(in_vector.isEmpty()){
System.out.println("Error: Empty vector!");
return null;
}
if(in_vector.firstElement() instanceof String||in_vector.firstElement() instanceof Character){
System.out.println("Error: Non-numeric element contained!");
return null;
}
Vector<Double> ret_vector = new Vector<>(in_vector.size());
double sum = 0;
Iterator iterator1 = in_vector.iterator();
Iterator iterator2 = in_vector.iterator();
switch (norm){
case 1:
while(iterator1.hasNext()){
sum = sum + Math.abs(Double.parseDouble(iterator1.next().toString()));
}
while(iterator2.hasNext()){
ret_vector.add((Double.parseDouble(iterator2.next().toString())/sum));
}
return ret_vector;
case 2:
while(iterator1.hasNext()){
sum = sum + Math.pow(Double.parseDouble(iterator1.next().toString()),2);
}
while(iterator2.hasNext()){
ret_vector.add(Double.parseDouble(iterator2.next().toString())/sum);
}
return ret_vector;
default:
System.out.println("Error:norm error");
break;
}
return null;
}
public static void vector_print(Vector v){
if(v==null){
System.out.println("NULL");
return;
}
Iterator iter = v.iterator();
while(iter.hasNext()){
System.out.print(iter.next()+" ");
}
System.out.println();
}
/* public static void main(String[] args){
Vector<Integer> v_test_1 = new Vector(10);
Vector<Double> v_test_2 = new Vector(10);
Vector<String> v_test_3 = new Vector(10);
Vector<Character> v_test_4 = new Vector(10);
int i=0;
while(i<10){
v_test_1.add(2);
v_test_2.add(2.0);
v_test_3.add("2.0");
v_test_4.add('C');
i++;
}
Vector v1_1 = normalize(v_test_1,1);
Vector v1_2 = normalize(v_test_1,2);
Vector v2_1 = normalize(v_test_2,1);
Vector v2_2 = normalize(v_test_2,2);
Vector v2_3 = normalize(v_test_2,3);
Vector v3_1 = normalize(v_test_3,1);
Vector v4_1 = normalize(v_test_4,1);
vector_print(v_test_1);
vector_print(v1_1);
vector_print(v1_2);
vector_print(v_test_2);
vector_print(v2_1);
vector_print(v2_2);
vector_print(v3_1);
vector_print(v4_1);
}
*/
}
|
package com.sample.observer.view.observer;
import java.util.Observable;
import java.util.Observer;
import com.sample.observer.model.WeatherData;
public class CurrentConditionsPanel implements Observer {
@Override
public void update(Observable obs, Object arg) {
WeatherData weatherData = (WeatherData)arg;
System.out.println("CurrentConditionsPanel temperature:" + weatherData.temperature);
System.out.println("CurrentConditionsPanel humidity :" + weatherData.humidity);
System.out.println("CurrentConditionsPanel pressure :" + weatherData.pressure);
}
}
|
public static void main1(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JFrame form3 = new JFrame("form2");
form3.setTitle("Изменение налоговой ставки");
form3.setSize(475, 290);
form3.setLocationRelativeTo(null);
form3.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
form3.setLayout (new BorderLayout());
form3.setVisible(true);
JButton calc3,calc4;
JPanel panel2,panel3;
JLabel label_1,label_n1,label_n2,label_n3,label_n4,
label_n5,label_n6,label_n7,label_n8,label_n9,label_n10,
|
package com.mysql.cj.jdbc.exceptions;
import com.mysql.cj.Messages;
import java.sql.SQLNonTransientException;
public class MySQLStatementCancelledException extends SQLNonTransientException {
static final long serialVersionUID = -8762717748377197378L;
public MySQLStatementCancelledException(String reason, String SQLState, int vendorCode) {
super(reason, SQLState, vendorCode);
}
public MySQLStatementCancelledException(String reason, String SQLState) {
super(reason, SQLState);
}
public MySQLStatementCancelledException(String reason) {
super(reason);
}
public MySQLStatementCancelledException() {
super(Messages.getString("MySQLStatementCancelledException.0"));
}
}
/* Location: C:\Users\BSV\AppData\Local\Temp\Rar$DRa6216.20396\Preview\Preview.jar!\com\mysql\cj\jdbc\exceptions\MySQLStatementCancelledException.class
* Java compiler version: 8 (52.0)
* JD-Core Version: 1.1.3
*/
|
package Chapter4.TreesAndGraphs;
public class BinarySearchTree {
BinaryTreeNode<Integer> root;
BinarySearchTree() {
this.root = null;
}
BinaryTreeNode<Integer> insert(BinaryTreeNode<Integer> root, int key) {
if (root == null) {
root = new BinaryTreeNode<>(key);
return root;
}
if (key < root.data) {
root.left = insert(root.left, key);
} else if (key > root.data) {
root.right = insert(root.right, key);
}
return root;
}
BinaryTreeNode<Integer> search(BinaryTreeNode<Integer> root, int key) {
if (root == null || root.data == key) {
return root;
}
if (root.data < key)
return search(root.right, key);
return search(root.left, key);
}
}
|
package javaPrepTwo;
import java.util.Arrays;
public class Question {
public static int[] ascending(int[] intArry){
Arrays.sort(intArry);
return intArry;
}
public static int countWords(String str){
return str.split(" ").length;
}
public static int calculator(String op, int num1, int num2){
switch (op){
case "+":
return num1 + num2;
case "-":
return num1 - num2;
case "*":
return num1 * num2;
case "/":
return num1 / num2;
default:
return 0;
}
}
public static void cardHidden(){
// String input = "123456789";
// String lastFourDigits = "";
//
// if (input.length() > 4) {
//
// lastFourDigits = input.substring(input.length() - 4);
// } else {
// lastFourDigits = input;
// }
// System.out.println(lastFourDigits);
}
}
|
package com.example.demo.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RequestMapping("/api/v1/redis")
@RestController
public class RedisController {
@Autowired
private StringRedisTemplate redisTemplate;
@GetMapping(value="add")
public Object add() {
redisTemplate.opsForValue().set("fazhicao", "chenwen");
return "redis add";
}
@GetMapping(value="get")
public Object get() {
String val = redisTemplate.opsForValue().get("fazhicao");
return val;
}
}
|
package com.qgbase.biz.info.controller;
import com.qgbase.biz.info.domain.TDic;
import com.qgbase.biz.info.service.TDicService;
import com.qgbase.biz.info.TinfoQuery;
import com.qgbase.biz.storage.domain.TAttachment;
import com.qgbase.biz.storage.service.StorageService;
import com.qgbase.common.domain.OperInfo;
import com.qgbase.common.enumeration.EnumResultType;
import com.qgbase.config.annotation.Permission;
import com.qgbase.config.exception.SysRunException;
import com.qgbase.excel.ExcelUtil;
import com.qgbase.util.StringUtil;
import com.qgbase.util.TToolRequest;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* Created by Mark on 2019-08-16
* * 主要用于:数据字典 接口层,此代码为自动生成
*/
@Controller
@RequestMapping(value = "/api/TDic")
public class TDicController {
@Autowired
TDicService TDicService;
@Autowired
TinfoQuery infoQuery;
@Autowired
StorageService storageService;
@ApiOperation(value="添加对象")
@PostMapping(value = "/addobj")
@ResponseBody
@Permission(moduleCode = "TDic",operationCode = "NEW")
public String addobj(@ModelAttribute TDic TDic, OperInfo opUser) throws Exception {
TDic obj = TDicService.addobj(TDic,opUser);
return TToolRequest.Result(EnumResultType.SAVE_SUCCESS.getCode(), EnumResultType.SAVE_SUCCESS.getMsg(), obj);
}
@ApiOperation(value="查询对象")
@PostMapping(value = "/getobj")
@ResponseBody
@Permission(moduleCode = "TDic",operationCode = "QUERY")
public String getobj(@RequestParam("id") String id,OperInfo opUser) throws Exception{
TDic obj = TDicService.getobj(id,opUser);
return TToolRequest.Result(EnumResultType.SUCCESS.getCode(), EnumResultType.SUCCESS.getMsg(), obj);
}
@ApiOperation(value="修改对象")
@PostMapping(value = "/updateobj")
@ResponseBody
@Permission(moduleCode = "TDic",operationCode = "UPDATE")
public String updateobj(@ModelAttribute TDic TDic, OperInfo opUser) throws Exception{
TDic obj = TDicService.updateobj(TDic,opUser);
return TToolRequest.Result(EnumResultType.UPDATE_SUCCESS.getCode(), EnumResultType.UPDATE_SUCCESS.getMsg(), obj);
}
@ApiOperation(value="删除对象")
@PostMapping(value = "/deleteobj")
@ResponseBody
@Permission(moduleCode = "TDic",operationCode = "DELETE")
public String deleteobj(@RequestParam("id") String id,OperInfo opUser) throws Exception {
TDicService.deleteobj(id,opUser);
return TToolRequest.Result(EnumResultType.DEL_SUCCESS.getCode(), EnumResultType.DEL_SUCCESS.getMsg(),null);
}
@ApiOperation(value="添加初始化对象")
@PostMapping(value = "/newObj")
@ResponseBody
@Permission(moduleCode = "TDic",operationCode = "NEW")
public String newObj(OperInfo opUser) throws Exception {
TDic obj = TDicService.newObj(opUser);
return TToolRequest.Result(EnumResultType.SUCCESS.getCode(), EnumResultType.SUCCESS.getMsg(), obj);
}
@ApiOperation(value="查询")
@PostMapping(value = "/queryTDicList")
@ResponseBody
@Permission(moduleCode = "TDic",operationCode = "QUERY")
public String queryTDicList(@RequestBody Map queryMap, OperInfo operInfo) throws Exception {
return TToolRequest.Result(EnumResultType.SUCCESS.getCode(), EnumResultType.SUCCESS.getMsg(),infoQuery.queryTDicList(queryMap, operInfo));
}
@ApiOperation(value="导出")
@PostMapping(value = "/exportExcel")
@Permission(moduleCode = "TDic",operationCode = "QUERY")
public void exportExcel(@RequestBody Map queryMap, HttpServletResponse response, OperInfo operInfo) throws Exception {
List list = infoQuery.queryTDicList(queryMap,operInfo).getList();
response.reset();
response.setContentType("application/octet-stream;charset=UTF-8");
response.setHeader("Pragma", "No-cache");
OutputStream os = response.getOutputStream();
ExcelUtil.writeWithMap(list,os,TDic.class);
os.close();
}
@ApiOperation(value="添加初始化对象")
@PostMapping(value = "/importExcel/{uid}")
@ResponseBody
public String importExcel(@PathVariable("uid")String uid,OperInfo opr) throws Exception {
TAttachment attachment = storageService.getobj(uid,opr);
List<TDic> objs = null;
if(attachment != null)
{
String filePath = attachment.getStorePath() + "/" + attachment.getNewName() + "."+ attachment.getFileExtension();
List objList = new ArrayList();
objs = ExcelUtil.readFrom(filePath,TDic.class,TDicService,opr);
if(objs != null && objs.size() > 0)
{
for(TDic obj : objs)
{
try {
String msg = TDicService.checkAddorUpdate(obj, opr,true);
if(StringUtil.isNotBlankIfStr(msg))
{
obj.setImportMsg(msg);
objList.add(obj);
}
}
catch (SysRunException sre)
{
sre.printStackTrace();
obj.setImportMsg(sre.getMessage());
}
catch (Exception e)
{
e.printStackTrace();
obj.setImportMsg("系统繁忙");
}
}
if(objList.size() == 0) {
for (TDic obj : objs) {
TDicService.addobj(obj, opr);
}
}
else
{
return TToolRequest.ResultSuccess(objList);
}
}
}
return TToolRequest.ResultSuccess(null);
}
@ApiOperation(value="查询所有")
@PostMapping(value = "/getAllList")
@ResponseBody
@Permission(moduleCode = "TDic",operationCode = "QUERY")
public String getAllList(OperInfo operInfo){
return TToolRequest.ResultSuccess( TDicService.getAllList(operInfo));
}
@ApiOperation(value="按字典类型查询")
@PostMapping(value = "/getByDicType")
@ResponseBody
@Permission(moduleCode = "TDic",operationCode = "QUERY")
public String getByDicType(@RequestParam("dicType") String dicType, OperInfo operInfo){
return TToolRequest.ResultSuccess( TDicService.getByDicType(dicType,operInfo));
}
}
|
package com.tencent.weui.base.preference;
import android.content.Context;
import android.util.AttributeSet;
import com.tencent.mm.bw.a.g;
public class PreferenceSmallCategory extends PreferenceCategory {
public PreferenceSmallCategory(Context context) {
this(context, null);
}
public PreferenceSmallCategory(Context context, AttributeSet attributeSet) {
this(context, attributeSet, 0);
}
public PreferenceSmallCategory(Context context, AttributeSet attributeSet, int i) {
super(context, attributeSet, i);
setLayoutResource(g.mm_preference_header_catalog);
}
}
|
package com.tencent.mm.protocal.c;
import com.tencent.mm.bk.a;
import java.util.LinkedList;
public final class bob extends a {
public int rdq;
public bhz slT;
public bhz slV;
public int slW;
protected final int a(int i, Object... objArr) {
int fS;
if (i == 0) {
f.a.a.c.a aVar = (f.a.a.c.a) objArr[0];
if (this.slT != null) {
aVar.fV(1, this.slT.boi());
this.slT.a(aVar);
}
aVar.fT(2, this.rdq);
if (this.slV != null) {
aVar.fV(3, this.slV.boi());
this.slV.a(aVar);
}
aVar.fT(4, this.slW);
return 0;
} else if (i == 1) {
if (this.slT != null) {
fS = f.a.a.a.fS(1, this.slT.boi()) + 0;
} else {
fS = 0;
}
fS += f.a.a.a.fQ(2, this.rdq);
if (this.slV != null) {
fS += f.a.a.a.fS(3, this.slV.boi());
}
return fS + f.a.a.a.fQ(4, this.slW);
} else if (i == 2) {
f.a.a.a.a aVar2 = new f.a.a.a.a((byte[]) objArr[0], unknownTagHandler);
for (fS = a.a(aVar2); fS > 0; fS = a.a(aVar2)) {
if (!super.a(aVar2, this, fS)) {
aVar2.cJS();
}
}
return 0;
} else if (i != 3) {
return -1;
} else {
f.a.a.a.a aVar3 = (f.a.a.a.a) objArr[0];
bob bob = (bob) objArr[1];
int intValue = ((Integer) objArr[2]).intValue();
LinkedList IC;
int size;
byte[] bArr;
bhz bhz;
f.a.a.a.a aVar4;
boolean z;
switch (intValue) {
case 1:
IC = aVar3.IC(intValue);
size = IC.size();
for (intValue = 0; intValue < size; intValue++) {
bArr = (byte[]) IC.get(intValue);
bhz = new bhz();
aVar4 = new f.a.a.a.a(bArr, unknownTagHandler);
for (z = true; z; z = bhz.a(aVar4, bhz, a.a(aVar4))) {
}
bob.slT = bhz;
}
return 0;
case 2:
bob.rdq = aVar3.vHC.rY();
return 0;
case 3:
IC = aVar3.IC(intValue);
size = IC.size();
for (intValue = 0; intValue < size; intValue++) {
bArr = (byte[]) IC.get(intValue);
bhz = new bhz();
aVar4 = new f.a.a.a.a(bArr, unknownTagHandler);
for (z = true; z; z = bhz.a(aVar4, bhz, a.a(aVar4))) {
}
bob.slV = bhz;
}
return 0;
case 4:
bob.slW = aVar3.vHC.rY();
return 0;
default:
return -1;
}
}
}
}
|
package khmil.java8.Lambda;
public class LambdaApp {
public static void main(String[] args) {
Operationable op = (x, y) -> {
if (x > 50) {
x = x + 10;
return x + y;
} else {
return x - y;
}
};
Operationable op2 = (x, y) -> x / y;
Operationable op3 = (x, y) -> x * y;
Operationable op4 = (x, y) -> x % y;
int result = op.calculate(40, 40);
System.out.println(result);
}
}
interface Operationable {
int calculate(int x, int y);
}
|
package com.guli.ucenter.entity.vo;
import lombok.Data;
@Data
public class RegisterVo {
private String nickname;
private String mobile;
private String password;
private String code;
}
|
package com.noteshare.solr.services.impl;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.impl.HttpSolrClient;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;
import org.springframework.stereotype.Service;
import com.noteshare.common.model.Page;
import com.noteshare.common.utils.page.PageConstants;
import com.noteshare.common.utils.page.PageUtil;
import com.noteshare.note.note.dao.NoteMapper;
import com.noteshare.note.note.model.Note;
import com.noteshare.solr.model.Entity;
import com.noteshare.solr.services.SolrService;
import com.noteshare.solr.utils.SolrUtil;
@Service
public class SolrServiceImpl implements SolrService{
@Resource
private NoteMapper noteMapper;
@Override
public Page<Entity> search(String queryField,String condition, int currentPage, int startPageNumber, int endPageNumber,
int size) throws SolrServerException, IOException {
//对查询条件进行处理
if(null != condition){
condition = SolrUtil.escapeQueryChars(condition);
}else{
condition = "";
}
//页数处理
if(currentPage < 1){
currentPage = 1;
}
int start = (currentPage - 1) * size;
SolrQuery params = new SolrQuery();
params.setQuery(queryField + ":" + condition);
//设置分页
params.setStart(new Integer(start));
params.setRows(new Integer(size));
//设置高亮
params.setHighlight(true); // set other params
params.addHighlightField("title");// 高亮字段
params.addHighlightField("summary");// 高亮字段
//设置高亮前缀和后缀
params.setHighlightSimplePre("<span class='highligter'>").setHighlightSimplePost("</span>");
//结果分片数,默认为1
params.setHighlightSnippets(2);
//每个分片的最大长度,默认为100
params.setHighlightFragsize(200);
//分片信息--段--分片字段
params.setFacet(true).setFacetMinCount(1).setFacetLimit(5).addFacetField("summary");
//查询
QueryResponse query = SolrUtil.getSolrClient(null).query(params);
//查询结果
SolrDocumentList results = query.getResults();
List<Entity> list = new ArrayList<Entity>();
//获取高亮部分和分页集合
Map<String,Map<String,List<String>>> highlightMap=query.getHighlighting();
Entity entity = null;
for(SolrDocument doc : results){
entity = new Entity();
String id = doc.getFieldValue("id").toString() ;
String type = (null == doc.getFieldValue("type")) ? "" : doc.getFieldValue("type").toString();
String labelnames = (null == doc.getFieldValue("labelnames")) ? "" : doc.getFieldValue("labelnames").toString() ;
entity.setId(id);
entity.setType(type);
entity.setCreatetime((Date)doc.getFieldValue("createtime"));
entity.setLabelnames(labelnames);
entity.setNickname((null == doc.getFieldValue("nickname")) ? "" : doc.getFieldValue("nickname").toString());
if(highlightMap.get(id)!=null) {
List<String> titleList = highlightMap.get(id).get("title");
if(titleList!=null && titleList.size()>0){
entity.setTitle(titleList.get(0));
}else{
entity.setTitle(doc.getFieldValue("title").toString());
}
List<String> summaryList = highlightMap.get(id).get("summary");
if(summaryList!=null && summaryList.size()>0){
entity.setSummary(summaryList.get(0));
}else{
if(null != doc.getFieldValue("summary") && ((String)doc.getFieldValue("summary")).length()>160)
entity.setSummary((doc.getFieldValue("summary")+"").substring(0, 160)+"...");
else
entity.setSummary(doc.getFieldValue("summary")+"");
}
}
list.add(entity);
}
//--------分页相关内容
int total = (int) results.getNumFound();
Page<Entity> page = new Page<Entity>();
//设置page基础参数
PageUtil.getBaseParamMap(page,total,currentPage,size);
page.setList(list);
PageUtil.setPage(page,currentPage, startPageNumber, endPageNumber,PageConstants.PAGEFLAGNUMBER,PageConstants.MAXPAGENUMBER);
return page;
}
@Override
public void addIndex(Entity entity) throws IOException, SolrServerException {
HttpSolrClient solrClient = SolrUtil.getSolrClient(null);
solrClient.addBean(entity);
solrClient.commit();
}
@Override
public void addIndexByList(List<Entity> list) throws SolrServerException, IOException {
HttpSolrClient solrClient = SolrUtil.getSolrClient(null);
solrClient.addBeans(list);
solrClient.commit();
}
@Override
public void deleteIndexALl() throws SolrServerException, IOException {
// TODO Auto-generated method stub
}
@Override
public void deleteNoteIndex() throws SolrServerException, IOException {
HttpSolrClient solrClient = SolrUtil.getSolrClient(null);
solrClient.deleteByQuery("type:note");
solrClient.commit();
}
@Override
public void deleteById(String id) throws SolrServerException, IOException {
HttpSolrClient solrClient = SolrUtil.getSolrClient(null);
solrClient.deleteById(id);
solrClient.commit();
}
@Override
public void updateIndex(Entity entity) throws IOException, SolrServerException {
deleteById(entity.getId());
addIndex(entity);
}
@Override
public void reBuildIndexAll() throws SolrServerException, IOException {
//重建笔记索引---------start
reBuildNoteIndex();
//重建笔记索引---------end
}
@Override
public void reBuildNoteIndex() throws SolrServerException, IOException {
deleteNoteIndex();
//重建笔记索引---------start
List<Note> notes = noteMapper.selectNoteAll();
List<Entity> entitys = new ArrayList<Entity>();
HttpSolrClient solrClient = SolrUtil.getSolrClient(null);
for (Note note : notes) {
Entity entity = new Entity(note);
entitys.add(entity);
if(entitys.size() % 500 == 0){
solrClient.addBeans(entitys);
solrClient.commit();
entitys = new ArrayList<Entity>();
}
}
if(entitys.size() > 0){
solrClient.addBeans(entitys);
solrClient.commit();
}
//重建笔记索引---------end
}
}
|
package com.example.a86182.icamera;
import android.Manifest;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import java.io.File;
import java.util.List;
import pub.devrel.easypermissions.EasyPermissions;
/**
*
* main page
* @author LB WZW CXW
*
*/
public class MainActivity extends AppCompatActivity implements View.OnClickListener,
EasyPermissions.PermissionCallbacks {
// private ImageView ivTest;
/** 拍照照片路径*/
private File cameraSavePath;
/** 照片路径*/
public static Uri uri;
/** 获取权限 */
private String[] permissions =
{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE};
public static String testString = "";
/**
*
* @param uri
*/
public MainActivity(final Uri uri)
{
super();
this.uri = uri;
}
/**
*
*/
public MainActivity()
{
super();
}
/**
* Instantiate some objects
* @param bundle
*/
@Override
protected void onCreate(final Bundle bundle) {
super.onCreate(bundle);
setContentView(R.layout.activity_main);
getSupportActionBar().hide();
final ImageButton camera = findViewById(R.id.camera);
final Button album = findViewById(R.id.album);
// ivTest = findViewById(R.id.iv_test);
gainPermission();
camera.setOnClickListener(this);
album.setOnClickListener(this);
cameraSavePath = new File(Environment.getExternalStorageDirectory().getPath() + "/"
+ System.currentTimeMillis() + ".jpg");
}
/**
* Judge click the button to perform different actions
* @param view Current click object
*/
@Override
public void onClick(final View view) {
final int viewId = view.getId();
switch (viewId) {
case R.id.camera:
goCamera();
break;
case R.id.album:
goPhotoAlbum();
break;
default:
break;
}
}
//获取权限
/**
* Apply camera permissions to the user
*/
private void gainPermission() {
if (EasyPermissions.hasPermissions(this, permissions)) {
//已经打开权限
Toast.makeText(this, "已经申请相关权限", Toast.LENGTH_SHORT).show();
} else {
//没有打开相关权限、申请权限
EasyPermissions.requestPermissions(this, "需要获取您的相册、照相使用权限", 1, permissions);
}
}
//激活相册操作
/**
*Activate the album operation
*/
private void goPhotoAlbum() {
final Intent intent = new Intent();
intent.setAction(Intent.ACTION_PICK);
intent.setType("image/*");
startActivityForResult(intent, 2);
Toast.makeText(this, "album starts", Toast.LENGTH_SHORT).show();
}
//激活相机操作
/**
*Activate camera operation
*/
private void goCamera() {
final Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
uri = FileProvider.getUriForFile(this,
"com.example.a86182.icamera.fileprovider", cameraSavePath);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
} else {
uri = Uri.fromFile(cameraSavePath);
}
intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
this.startActivityForResult(intent, 1);
Toast.makeText(this, "camera starts", Toast.LENGTH_SHORT).show();
}
/**
* Same as the parent method
* @param requestCode
* @param permissions
* @param grantResults
*/
@Override
public void onRequestPermissionsResult(final int requestCode,
final @NonNull String[] permissions,
final @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
//框架要求必须这么写
EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
}
//成功打开权限
/**
* Same as the parent method
* @param requestCode
* @param perms
*/
@Override
public void onPermissionsGranted(final int requestCode, final @NonNull List<String> perms) {
Toast.makeText(this, "相关权限获取成功", Toast.LENGTH_SHORT).show();
}
//用户未同意权限
/**
* Same as the parent method
* @param requestCode
* @param perms
*/
@Override
public void onPermissionsDenied(final int requestCode, final @NonNull List<String> perms) {
Toast.makeText(this, "请同意相关权限,否则功能无法使用", Toast.LENGTH_SHORT).show();
}
/**
* Same as the parent method
* @param requestCode
* @param resultCode
* @param data
*/
@Override
protected void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
String photoPath;
if (requestCode == 1 && resultCode == RESULT_OK) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
photoPath = String.valueOf(cameraSavePath);
} else {
photoPath = uri.getEncodedPath();
}
Log.d("拍照返回图片路径:", photoPath);
Intent in=new Intent(MainActivity.this,Phote_View_Activity.class);
in.putExtra("Uri",uri.toString());
in.putExtra("photopath",photoPath);
startActivity(in);
// Glide.with(MainActivity.this).load(photoPath).into(ivTest);
} else if (requestCode == 2 && resultCode == RESULT_OK) {
// photoPath = getPhotoFromPhotoAlbum.getRealPathFromUri(this, data.getData());
// Glide.with(MainActivity.this).load(photoPath).into(ivTest);
}
super.onActivityResult(requestCode, resultCode, data);
}
}
|
package verify.exam00;
public class MusicRunnable implements Runnable{
public void run() {
for(int i=0;i<3;i++) {
System. out .println("음악을 재생합니다.");
try { Thread. sleep (1000);
} catch (InterruptedException e) {
}
}
}
}
|
package com.hly.o2o.interceptor.shopadmin;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import com.hly.o2o.entity.Shop;
/**
* 对店家管理系统操作的拦截器
* @author hp
*
*/
public class ShopPermissionInterceptor extends HandlerInterceptorAdapter {
/**
* 主要做事前拦截,即用户操作发生前,改写preHandle的逻辑,进行拦截
*/
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
//从session中获取当前选择的店铺
Shop shop=(Shop) request.getSession().getAttribute("currentShop");
@SuppressWarnings("unchecked")
//从session中获取当前用户可操作的 店铺列表
List<Shop> shopList=(List<Shop>) request.getSession().getAttribute("shopList");
//非空判断
if(shop!=null && shopList!=null){
//遍历可操作的店铺
for(Shop s:shopList){
//如果当前店铺在可操作的店铺列表里,则返回true
if(s.getShopId()==shop.getShopId()){
return true;
}
}
}
//若不满足拦截器的条件则直接返回fasle
return false;
}
}
|
/*
* Copyright © 2018 tesshu.com (webmaster@tesshu.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.tesshu.sonic.player.plugin.command.testimpl;
import com.tesshu.sonic.player.action.IParameter;
import com.tesshu.sonic.player.command.impl.MessageParam;
import com.tesshu.sonic.player.plugin.command.CommandLogicSupplier;
import java.util.List;
import java.util.Optional;
import java.util.function.Consumer;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
public class TestSupplier2 implements CommandLogicSupplier {
@Override
public String getName() {
return "TestSupplier2";
}
@Nullable
public <P extends IParameter> Optional<Consumer<P>> createCommandLogic(String logicId) {
Consumer<P> consumer = null;
switch (logicId) {
case "doHello":
consumer = (p) -> System.out
.println(String.format("%s -> Hello Brother!", ((MessageParam) p).getMessage()));
break;
default:
break;
}
return Optional.ofNullable(consumer);
};
@NonNull
public List<String> getProvidableLogic() {
return List.of("doHello");
};
}
|
package LC1600_1800.LC1750_1800;
public class LC1786_Number_Of_Restricted_Path_From_First_To_Last_Node {
public int countRestrictedPaths(int n, int[][] edges) {
return 1;
}
}
|
package com.yinghai.a24divine_user.module.login.wechat;
import com.example.fansonlib.base.BaseView;
import com.yinghai.a24divine_user.bean.PersonInfoBean;
import com.yinghai.a24divine_user.callback.IHandleCodeCallback;
import io.rong.imlib.RongIMClient;
/**
* @author Created by:fanson
* Created Time: 2017/11/27 17:02
* Describe:第三方登录契约类
*/
public interface ContractThird {
interface IView extends BaseView{
/**
* 第三方登陸失敗
*/
void showThirdLoginFailure(String msg);
/**
* 第三方登录成功
*/
void showThirdSuccess();
/**
* 尚未绑定第三方账号
* @param thirdPartyId 绑定新用户时,后台需要的数据
*/
void showIsNewUser(int thirdPartyId);
}
interface IPresenter{
/**
* 第三方登录
* @param type 登录方式: 0 微信;3 baceBook
* @param code 第三方同意登录标识: facebook第三方登录的 code 为access token;
*/
void thirdLogin(int type,String code);
}
interface IModel{
/**
* 第三方登录接口(微信或 Facebook)
* @param type 登录方式: 0 微信;3 baceBook
* @param code 第三方同意登录标识: facebook第三方登录的 code 为access token;
* @param callback
*/
void onThirdLogin(int type, String code, ILoginCallback callback);
interface ILoginCallback extends IHandleCodeCallback{
/**
* 登陸失敗
*/
void onThirdLoginFailure(String msg);
/**
* 第三方登录成功
*/
void onThirdSuccess(PersonInfoBean bean);
/**
* 尚未绑定第三方账号
* @param thirdPartyId 绑定新用户时,后台需要的数据
*/
void onIsNewUser(int thirdPartyId);
}
/**
* 登录融云的服务器
* @param token
* @param mConnectCallback
*/
void rongIMLogin(String token, RongIMClient.ConnectCallback mConnectCallback);
}
}
|
package model.dao;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import model.vo.reservation.PaymentMethodInfoVO;
import model.vo.reservation.ReservationVO;
import model.vo.reservation.TimeTableVO;
import model.vo.theater.LocalInfoVO;
import com.ibatis.sqlmap.client.SqlMapClient;
public class ReserVationDao {
private SqlMapClient sqlMapClient;
public void setSqlMapClient(SqlMapClient sqlMapClient) {
this.sqlMapClient = sqlMapClient;
}
public ArrayList<HashMap> getScreeningMovieList() throws SQLException {
// 현재 상영중인 영화 목록 리스트
return (ArrayList<HashMap>) this.sqlMapClient.queryForList("reservation.screeningmovieList");
}
public ArrayList<LocalInfoVO> getLocalList() throws SQLException {
return (ArrayList<LocalInfoVO>)sqlMapClient.queryForList("reservation.localList");
}
public ArrayList<LocalInfoVO> getLocalListByMovieNo(int movie_no) throws SQLException {
return (ArrayList<LocalInfoVO>) this.sqlMapClient.queryForList("reservation.localListByMovieNo",movie_no);
}
public ArrayList<HashMap> getTheaterListByLocalAndMovie(HashMap map)
throws SQLException {
// 지역정보, 영화 정보에 따른 영화관 리스트
System.out.println("여기뽑는중" + map);
ArrayList<HashMap> list = (ArrayList<HashMap>) this.sqlMapClient
.queryForList("reservation.theaterListByLocalAndMovie", map);
System.out.println("여기뽑는중" + list);
return list;
}
public ArrayList<HashMap> getTheaterListByLocal(int local_no)
throws SQLException {
// 지역정보에 따른 영화관 리스트
return (ArrayList<HashMap>) this.sqlMapClient.queryForList(
"reservation.theaterListByLocal", local_no);
}
public ArrayList<HashMap> getTimeTableList(TimeTableVO ttVO)
throws SQLException {
return (ArrayList<HashMap>) this.sqlMapClient.queryForList(
"reservation.timeTableList", ttVO);
}
public ArrayList<PaymentMethodInfoVO> getPaymentMethodInfo()
throws SQLException {
// TODO Auto-generated method stub
return (ArrayList<PaymentMethodInfoVO>) this.sqlMapClient
.queryForList("reservation.paymentMethodInfo");
}
public void setReservationInfo(ReservationVO rVO) throws SQLException {
this.sqlMapClient.insert("reservation.reservationInfo", rVO);
}
public void setReservationMyMovieInfo(ReservationVO rVO) throws SQLException {
this.sqlMapClient.insert("reservation.reservationMyMovieInfo", rVO);
}
public int getMovieGradeByMovieNo(int movie_no) throws SQLException {
return (int) this.sqlMapClient.queryForObject("reservation.movieGradeByMovieNo", movie_no);
}
public ArrayList<HashMap> getReservationInfo(ReservationVO rVO) throws SQLException {
return (ArrayList<HashMap>)this.sqlMapClient.queryForList("reservation.getReservationInfo",rVO);
}
/**
* 결제창에서 예매정보 보여주는 메서드
*/
public ArrayList<HashMap> getReservationConfirm(int timetable_no) throws SQLException {
return (ArrayList<HashMap>) sqlMapClient.queryForList("reservation.getReservationConfirm",timetable_no);
}
public String getMovieTitle(int movie_no) throws SQLException {
return (String) sqlMapClient.queryForObject("reservation.getMovieTitle",movie_no);
}
public ArrayList<String> getConfirmedSeat(int timetable_no) throws SQLException {
return (ArrayList<String>) sqlMapClient.queryForList("reservation.getConfirmedSeat",timetable_no);
}
public ArrayList<Map> getReservationList(int member_no) throws SQLException {
return (ArrayList<Map>) sqlMapClient.queryForList("reservation.getReservationList",member_no);
}
public ReservationVO getReservationInfo(String res_no) throws SQLException {
return (ReservationVO) sqlMapClient.queryForObject("reservation.getReservationInfo2",res_no);
}
public void insertMyMovieInfo(ReservationVO rvo) throws SQLException {
sqlMapClient.insert("reservation.insertMyMovieInfo",rvo);
}
public void deleteReservation(String res_no) throws SQLException {
sqlMapClient.delete("reservation.deleteReservation",res_no);
}
}
|
import java.util.ArrayList;
import java.util.List;
/**
* Este arquivo ficará responsável por chamar os serviços e delegar qual método realiza qual função sem
* se importar com as regras de negócio.
*/
public class OfficeRepository {
List<Office> offices = new ArrayList<Office>();
public void Create(Office new_office){
this.offices.add(new_office);
}
public List<Office> getAll(){
return this.offices;
}
public void Delete(int position_office){
this.offices.remove(position_office);
}
}
|
package com.mes.cep.meta.operationsCapabilityModel;
/**
* @author Stephen·Wen
* @email 872003894@qq.com
* @date 2017年4月19日
* @Chinesename 设备能力
*/
public class EquipmentCapability {
}
|
package networking.udp.examples;
import java.net.*;
import java.io.*;
public class UDPWordCountServer {
private static int WordCount(String str) {
int wordChar = 0;
boolean prevCharWasSpace=true;
for (int i = 0; i < str.length(); i++)
{
if (str.charAt(i) == ' ') {
prevCharWasSpace=true;
}
else{
if(prevCharWasSpace) wordChar++;
prevCharWasSpace = false;
}
}
return wordChar;
}
public static void main(String args[]){
DatagramSocket aSocket = null;
try {
int socket_no = 1090;
aSocket = new DatagramSocket(socket_no);
byte[] buffer = new byte[1000];
while(true) {
DatagramPacket request = new DatagramPacket(buffer,
buffer.length);
aSocket.receive(request);
byte[] received_data = request.getData();
// Convert byte[] to String
String str = new String(received_data, "UTF-8");
Integer NumWord = WordCount(str);
String NumWordStr = NumWord.toString();
System.out.println(received_data);
System.out.println(NumWordStr);
// Convert String to byte[]
byte [] m = NumWordStr.getBytes();
// DatagramPacket only accept byte array as its argument
DatagramPacket reply = new DatagramPacket(m,
NumWordStr.length(),request.getAddress(),
request.getPort());
// Use send method to send datagram
aSocket.send(reply);
}
}
catch (SocketException e) {
System.out.println("Socket: " + e.getMessage());
}
catch (IOException e) {
System.out.println("IO: " + e.getMessage());
}
finally {
if (aSocket != null)
aSocket.close();
}
}
}
|
package com.bingo.code.example.design.chainofresponsibility.allprocess;
/**
* �����������۵�ҵ���ܵ�ְ�����
*/
public class SaleMgr extends SaleHandler{
public boolean sale(String user, String customer, SaleModel saleModel) {
//����������ҵ��������
System.out.println(user+"������"+customer+"���� "+saleModel+" ����������");
return true;
}
}
|
package com.cnk.travelogix.supplier.inventory.dao.impl;
import java.util.List;
import javax.annotation.Resource;
import org.apache.log4j.Logger;
import com.cnk.travelogix.acco.inventory.core.model.AccoInventoryGridModel;
import com.cnk.travelogix.accoinventory.core.model.AccoInventoryDefinitionModel;
import com.cnk.travelogix.accoinventory.core.model.AccoInventoryDetailModel;
import com.cnk.travelogix.accoinventory.core.model.AccoPenaltyChargesReleaseModel;
import com.cnk.travelogix.accoinventory.core.model.InventoryRoomInfoModel;
import com.cnk.travelogix.accoinventory.core.model.RoomingListCutOffsModel;
import com.cnk.travelogix.common.inventory.core.enums.InventoryType;
import com.cnk.travelogix.common.inventory.model.OverBookingLimitModel;
import com.cnk.travelogix.masterdata.core.c2l.model.CityModel;
import com.cnk.travelogix.masterdata.core.enums.RoomCategory;
import com.cnk.travelogix.masterdata.core.enums.RoomType;
import com.cnk.travelogix.supplier.commercials.core.advancedefinition.model.accommodation.AccoSupplierAdvanceDefinitionModel;
import com.cnk.travelogix.supplier.inventory.dao.InventoryDao;
import de.hybris.platform.core.model.product.ProductModel;
import de.hybris.platform.search.restriction.SearchRestrictionService;
import de.hybris.platform.servicelayer.search.FlexibleSearchQuery;
import de.hybris.platform.servicelayer.search.FlexibleSearchService;
import de.hybris.platform.servicelayer.search.SearchResult;
public class InventoryDaoImpl implements InventoryDao{
private static final Logger LOG = Logger.getLogger(InventoryDaoImpl.class);
@Resource(name = "flexibleSearchService")
private FlexibleSearchService flexibleSearchService;
@Resource(name = "searchRestrictionService")
private SearchRestrictionService searchRestrictionService;
private final String INVENTORY_GRID = "Select {"+AccoInventoryGridModel.PK +"} from { "+AccoInventoryGridModel._TYPECODE
+"as aig }" ;
private final String ACCO_INVENTORY_DEFINATION = " SELECT {aid.pk} from {AccoInventoryGrid as aig JOIN AccoInventoryDefinition as aid ON {aid.pk} = {aig.accoInventoryDefinition}JOIN Supplier as sup ON {sup.pk} = {aid.supplier} }WHERE {sup.code} =?supplier and {aid.code} =?code ";
private final String INVENTORY_DETAIL = "SELECT {AID.PK} FROM {AccoInventoryGrid AS AIG JOIN AccoInventoryDetail AS AID ON {AID.accoInventoryGrid} = {AIG.PK} JOIN Product as PRO ON {PRO.pk} = {AID.product} JOIN City as CIT ON {CIT.PK} = {AID.city} } WHERE {PRO.code} =?productCode and {CIT.isoCode} =?cityIso and {AID.inventoryType} =?inventorytype" ;
private final String INVENTORY_ROOM_INFO = "SELECT {IRI.PK} FROM { AccoInventoryGrid AS AIG JOIN AccoInventoryDetail AS AID ON {AIG.PK} = {AID.accoInventoryGrid} JOIN Product as PRO ON {PRO.pk} = {AID.product} JOIN City as CIT ON {CIT.PK} = {AID.city} JOIN InventoryRoomInfo as IRI ON {IRI.accoInventoryDetail} = {AID.pk} } WHERE {PRO.code} =?productCode and {CIT.isoCode} =?cityIso and {IRI.roomCategory} =?roomCategory and {IRI.roomType} =?roomType ";
private final String SUPPLIER_ADVANCE_DEFINATION = " SELECT {ASAD.pk} FROM { AccoInventoryGrid as AIG JOIN AccoInventoryDefinition as AID ON {AID.pk} = {AIG.accoInventoryDefinition} JOIN AccoSupplierAdvanceDefinition as ASAD ON {ASAD.pk} = {AID.supplierAdvanceDefinition} JOIN Supplier as SUP ON {SUP.pk} = {AID.supplier} JOIN RoomCategoryConfig as RCC ON {RCC.pk} = {ASAD.roomCategories} JOIN RoomTypeConfig as RTC ON {RTC.pk} = {ASAD.roomTypes} } WHERE {RCC.roomCategory} =?roomCategory AND {RTC.roomType} =?roomType AND {SUP.code} =?supplier ";
private final String PENALTY_CHARGES_RELEASE = " SELECT {apcr.pk} from { AccoInventoryGrid as aig JOIN AccoInventoryDefinition as aid ON {aid.pk} = {aig.accoInventoryDefinition} JOIN OverBookingLimit as obl ON {obl.accoSupplierAdvanceDefinition} = {aid.supplierAdvanceDefinition} JOIN AccoPenaltyChargesRelease as apcr ON {apcr.accoSupplierAdvanceDefinition} ={aid.supplierAdvanceDefinition} JOIN RoomingListCutOffs as rlco ON {rlco.accoSupplierAdvanceDefinition} = {aid.supplierAdvanceDefinition} } WHERE {apcr.roomCategory} =?roomCategory and {apcr.roomType} =?roomtype";
@Override
public AccoInventoryDefinitionModel findInventoryDefination(String supplier , String code){
List<AccoInventoryDefinitionModel> inventoryDefination = null;
AccoInventoryDefinitionModel accoInventoryDefinitionModel = null;
final FlexibleSearchQuery flexibleSearchQuery = new FlexibleSearchQuery(ACCO_INVENTORY_DEFINATION);
flexibleSearchQuery.addQueryParameter("supplier",supplier);
flexibleSearchQuery.addQueryParameter("code",code);
LOG.info("Query :" + flexibleSearchQuery.getQuery());
try{
searchRestrictionService.disableSearchRestrictions();
final SearchResult<AccoInventoryDefinitionModel> searchResult = flexibleSearchService.search(flexibleSearchQuery);
inventoryDefination =searchResult.getResult();
if(!inventoryDefination.isEmpty())
{
accoInventoryDefinitionModel = inventoryDefination.get(0);
}
}catch(Exception e){
LOG.info("Error occured while fetching Inventory Defination Information" + e.getMessage(),e);
}finally{
searchRestrictionService.enableSearchRestrictions();
}
return accoInventoryDefinitionModel ;
}
@Override
public AccoInventoryGridModel findInventoryGrid(){
List<AccoInventoryGridModel> inventoryGrids = null;
AccoInventoryGridModel accoInventoryGridModel = null;
final FlexibleSearchQuery flexibleSearchQuery = new FlexibleSearchQuery(INVENTORY_GRID);
LOG.info("Query :" + flexibleSearchQuery.getQuery());
try{
searchRestrictionService.disableSearchRestrictions();
final SearchResult<AccoInventoryGridModel> searchResult = flexibleSearchService.search(flexibleSearchQuery);
inventoryGrids =searchResult.getResult();
if(!inventoryGrids.isEmpty())
{
accoInventoryGridModel = inventoryGrids.get(0);
}
}catch(Exception e){
LOG.info("Error occured while fetching Inventory Grid Information" + e.getMessage(),e);
}
finally
{
searchRestrictionService.enableSearchRestrictions();
}
return accoInventoryGridModel ;
}
@Override
public AccoInventoryDetailModel findInventroyDetail(String productCode, String cityIso,
InventoryType inventoryType) {
List<AccoInventoryDetailModel> inventoryDetails = null;
AccoInventoryDetailModel accoInventoryDetailModel = null;
final FlexibleSearchQuery flexibleSearchQuery = new FlexibleSearchQuery(INVENTORY_DETAIL);
flexibleSearchQuery.addQueryParameter("productCode",productCode);
flexibleSearchQuery.addQueryParameter("cityIso",cityIso);
flexibleSearchQuery.addQueryParameter("inventoryType",inventoryType);
LOG.info("Query :" + flexibleSearchQuery.getQuery());
try{
searchRestrictionService.disableSearchRestrictions();
final SearchResult<AccoInventoryDetailModel> searchResult = flexibleSearchService.search(flexibleSearchQuery);
inventoryDetails =searchResult.getResult();
if(!inventoryDetails.isEmpty())
{
accoInventoryDetailModel = inventoryDetails.get(0);
}
}catch(Exception e){
LOG.info("Error occured while fetching Inventory Detail Information" + e.getMessage(),e);
}finally{
searchRestrictionService.enableSearchRestrictions();
}
return accoInventoryDetailModel ;
}
@Override
public InventoryRoomInfoModel findInventryRoomInfo(String productCode, String cityIso, RoomCategory roomCategory , RoomType roomType){
List<InventoryRoomInfoModel> inventoryRoomInfo = null;
InventoryRoomInfoModel inventoryRoomInfoModel = null;
final FlexibleSearchQuery flexibleSearchQuery = new FlexibleSearchQuery(INVENTORY_ROOM_INFO);
flexibleSearchQuery.addQueryParameter("productCode",productCode);
flexibleSearchQuery.addQueryParameter("cityIso",cityIso);
flexibleSearchQuery.addQueryParameter("roomCategory",roomCategory);
flexibleSearchQuery.addQueryParameter("roomType",roomType);
LOG.info("Query :" + flexibleSearchQuery.getQuery());
try{
searchRestrictionService.disableSearchRestrictions();
final SearchResult<InventoryRoomInfoModel> searchResult = flexibleSearchService.search(flexibleSearchQuery);
inventoryRoomInfo =searchResult.getResult();
if(!inventoryRoomInfo.isEmpty())
{
inventoryRoomInfoModel = inventoryRoomInfo.get(0);
}
}catch(Exception e){
LOG.info("Error occured while fetching Inventory Room Information" + e.getMessage(),e);
}finally{
searchRestrictionService.enableSearchRestrictions();
}
return inventoryRoomInfoModel;
}
@Override
public AccoSupplierAdvanceDefinitionModel findSupplierAdvanceDefination(String supplier , RoomCategory roomCategory , RoomType roomType){
List<AccoSupplierAdvanceDefinitionModel> supplierAdvanceDefination = null;
AccoSupplierAdvanceDefinitionModel accoSupplierAdvanceDefinitionModel= null;
final FlexibleSearchQuery flexibleSearchQuery = new FlexibleSearchQuery(SUPPLIER_ADVANCE_DEFINATION);
flexibleSearchQuery.addQueryParameter("supplier",supplier);
flexibleSearchQuery.addQueryParameter("roomCategory",roomCategory);
flexibleSearchQuery.addQueryParameter("roomType",roomType);
LOG.info("Query :" + flexibleSearchQuery.getQuery());
try{
searchRestrictionService.disableSearchRestrictions();
final SearchResult<AccoSupplierAdvanceDefinitionModel> searchResult = flexibleSearchService.search(flexibleSearchQuery);
supplierAdvanceDefination =searchResult.getResult();
if(!supplierAdvanceDefination.isEmpty())
{
accoSupplierAdvanceDefinitionModel = supplierAdvanceDefination.get(0);
}
}catch(Exception e){
LOG.info("Error occured while fetching Supplier Advance Defination Information" + e.getMessage(),e);
}finally{
searchRestrictionService.enableSearchRestrictions();
}
return accoSupplierAdvanceDefinitionModel ;
}
@Override
public AccoPenaltyChargesReleaseModel findPenaltychargesRelease(String supplier, RoomCategory roomCategory,
RoomType roomType) {
List<AccoPenaltyChargesReleaseModel> penaltychargesRelease = null;
AccoPenaltyChargesReleaseModel accoPenaltyChargesReleaseModel = null;
final FlexibleSearchQuery flexibleSearchQuery = new FlexibleSearchQuery(PENALTY_CHARGES_RELEASE);
flexibleSearchQuery.addQueryParameter("supplier",supplier);
flexibleSearchQuery.addQueryParameter("roomCategory",roomCategory);
flexibleSearchQuery.addQueryParameter("roomType",roomType);
LOG.info("Query :" + flexibleSearchQuery.getQuery());
try{
searchRestrictionService.disableSearchRestrictions();
final SearchResult<AccoPenaltyChargesReleaseModel> searchResult = flexibleSearchService.search(flexibleSearchQuery);
penaltychargesRelease =searchResult.getResult();
if(!penaltychargesRelease.isEmpty())
{
accoPenaltyChargesReleaseModel = penaltychargesRelease.get(0);
}
}catch(Exception e){
LOG.info("Error occured while fetching Penalty charges Release Information" + e.getMessage(),e);
}finally{
searchRestrictionService.enableSearchRestrictions();
}
return accoPenaltyChargesReleaseModel ;
}
}
|
package com.johacks;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.PublicKey;
import java.security.SignatureException;
import java.security.spec.InvalidKeySpecException;
import java.util.ArrayList;
import java.util.Date;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
public class Miner {
private static final Logger logger = LogManager.getLogger("MinerLogger");
private final GsonBuilder builder = new GsonBuilder();
private final Gson gson = builder.create();
private final BlockChain blockChain;
private final KeyPair minerKey;
private ArrayList<Transaction> wipTransactions;
private final static String REQUIRED_HASH_PREFIX = "000";
/** Can create a miner either from an existing BlockChain or from new
* Either way, needs the keypair for miner fees
* @param blockChain
* @param minerKey
*/
public Miner(BlockChain blockChain,KeyPair minerKey) {
this.blockChain=blockChain;
this.minerKey=minerKey;
wipTransactions=new ArrayList<Transaction>();
}
/** Can create a miner either from an existing BlockChain or from new
* Either way, needs the keypair for miner fees
* @param genesysTransaction
* @param minerKey
*/
public Miner(Transaction genesysTransaction, KeyPair minerKey) {
this.blockChain=new BlockChain();
this.minerKey=minerKey;
wipTransactions=new ArrayList<Transaction>();
// bypasses validation for genesys
wipTransactions.add(genesysTransaction);
// get block 0 onto the chain
confirmWipTransactions();
}
public void addTransaction (Transaction txn) throws InvalidKeyException, UnsupportedEncodingException, NoSuchAlgorithmException, InvalidKeySpecException, SignatureException {
validateTransaction(txn);
wipTransactions.add(txn);
}
public void validateTransaction(Transaction txn) throws InvalidKeyException, UnsupportedEncodingException, NoSuchAlgorithmException, InvalidKeySpecException, SignatureException {
// TODO check it has an input
// TODO check it has an output
// TODO check the input signature
// TODO check the input is exactly spent
// TODO confirmation fees for this transaction
validateInputs(txn);
validateOutputs(txn);
}
private void validateInputs(Transaction txn) throws InvalidKeyException, UnsupportedEncodingException, NoSuchAlgorithmException, InvalidKeySpecException, SignatureException {
for (TransactionInput input : txn.retreiveInputs()) {
//FIXME check the signature on this input points as the pub key on this output
validateInputSignture(input);
}
}
private void validateOutputs(Transaction txn) {
for (TransactionOutput output : txn.retreiveOutputs()) {
//FIXME check there is a signature on this output that points at something
validateOutputSignture(output);
}
}
private void validateInputSignture(TransactionInput input) throws UnsupportedEncodingException, NoSuchAlgorithmException, InvalidKeySpecException, InvalidKeyException, SignatureException {
logger.info("validating an input");
final TransactionOutput srcOutput=input.getOutput();
final String srcTxnProof = srcOutput.getProof();
final String srcOutputKeyString=srcOutput.getPublicKey();
final PublicKey srcOutputKey=CryptoUtils.generatePubKey(srcOutputKeyString);
//FIXME this has hardcoded outputs 0,0,1 needs to use the real values from the mined block
final Proof outputProof=new Proof(0,0,1,srcOutputKeyString,srcOutput.getValue());
final String jsonProof = gson.toJson(outputProof);
final boolean valid = CryptoUtils.verifySignature(jsonProof, srcTxnProof, srcOutputKey);
logger.info("======srcTxnProof="+srcTxnProof);
}
private void validateOutputSignture(TransactionOutput output) {
logger.info("validating an output");
/*
* private String getProofString(int blockId, int txnId, int outputId, String destPublic, Wallet wallet, String keyname, double value) throws InvalidKeyException, NoSuchAlgorithmException, SignatureException, UnsupportedEncodingException, InvalidKeySpecException {
final Proof outputProof=new Proof(blockId,txnId,outputId,destPublic,value);
final String destPrivate = wallet.getKeyPair(keyname).getPrivateKey();
final String jsonProof = gson.toJson(outputProof);
final String outputProofString = CryptoUtils.signMessage(jsonProof,destPrivate);
// FIXME - validate signature - needs porting to the miner next
final String pubKeyAsString=wallet.getKeyPair(keyname).getPublicKey();
final PublicKey pubKey=CryptoUtils.generatePubKey(pubKeyAsString);
final boolean validSignature = CryptoUtils.verifySignature(jsonProof, outputProofString, pubKey);
logger.info("Signature Validation:"+validSignature);
logger.info("Proof: JSON=" + jsonProof + " signature="+ outputProofString);
return outputProofString;
}
*/
}
public void confirmWipTransactions() {
final Block newBlock = new Block();
for (Transaction txn: wipTransactions) {
newBlock.addTransaction(txn);
final String txnAsJSON = gson.toJson(txn);
logger.info("WIP txn Confirmed: "+txnAsJSON);
}
// TODO fees for creating a block
// TODO abort mining if receive a new block from different miner (threads!)
boolean mined=false;
int nonce=-1;
String hash="";
newBlock.setMinedBy(minerKey.getPublicKey());
String blockAsJSON;;
while (! mined) {
nonce++;
newBlock.setNonce(nonce);
newBlock.setConfirmationTime(new Date());
blockAsJSON = gson.toJson(newBlock);
hash = CryptoUtils.calcHash(blockAsJSON);
mined= hash.startsWith(REQUIRED_HASH_PREFIX);
}
newBlock.setHash(hash);
final String minedBlockAsJSON = gson.toJson(newBlock);
logger.info("Confirmed new block:"+minedBlockAsJSON);
blockChain.addBlock(newBlock);
// clear out WIP
wipTransactions=new ArrayList<Transaction>();
}
}
|
package pages;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
public class LoginPage extends Base{
private By loginEmail = By.id("email");
private By loginPassword = By.id("pass");
private By loginClick = By.id("u_0_2");
public LoginPage(WebDriver driver) {
super(driver);
// TODO Auto-generated constructor stub
}
public DashBoard populate(String username,String password) {
driver.findElement (loginEmail).sendKeys(username);
driver.findElement(loginPassword).sendKeys(password);
driver.findElement(loginClick).click();
return new DashBoard(driver);
}
}
|
package com.lupan.ehcache;
/**
* TODO 缓存操作类型
*
* @author lupan
* @version 2016/4/7 0007
*/
public enum CacheOperation {
READ,UPDATE
}
|
/*
* This software is licensed under the MIT License
* https://github.com/GStefanowich/MC-Server-Protection
*
* Copyright (c) 2019 Gregory Stefanowich
*
* 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 net.theelm.sewingmachine.protection.mixins.Blocks;
import net.theelm.sewingmachine.protection.enums.ClaimPermissions;
import net.theelm.sewingmachine.protection.utilities.ClaimChunkUtils;
import net.theelm.sewingmachine.utilities.BlockUtils;
import net.minecraft.block.BlockState;
import net.minecraft.block.PistonBlock;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.Direction;
import net.minecraft.world.World;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
@Mixin(value = PistonBlock.class, priority = 1)
public abstract class PistonBlockMixin {
@Inject(at = @At("RETURN"), method = "isMovable", cancellable = true)
private static void isMovable(BlockState blockState, World world, BlockPos blockPos, Direction moveDir, boolean bl, Direction pistonDir, CallbackInfoReturnable<Boolean> callback) {
BlockPos pistonPos, movePos;
// If block is immovable
if (!callback.getReturnValue())
return;
boolean pushing = pistonDir == moveDir;
// If pushing
if (pushing) {
pistonPos = blockPos.offset(pistonDir.getOpposite());
movePos = blockState.isAir() ? blockPos // If AIR, don't offset
: blockPos.offset(moveDir); // Move block position to where it is GOING to be
}
// If pulling
else {
pistonPos = blockPos.offset(moveDir, 2);
movePos = blockPos;
}
// Check that first chunk owner can modify the next chunk
if (!ClaimChunkUtils.canBlockModifyBlock(world, movePos, pistonPos, ClaimPermissions.BLOCKS)) {
// Send the ghost block update
if (!pushing)
BlockUtils.markDirty(world, movePos);
// Cancel the block movement
callback.setReturnValue(false);
}
}
}
|
package final_project;
import java.io.*;
import java.sql.*;
import java.util.*;
public class ExecuteFile {
static String usr ="postgres";
static String pwd ="123";
static String url ="jdbc:postgresql://localhost:5432/postgres";
Connection con;
ArrayList<ArrayList<String>> finalResult;
HashMap<Integer, groupvaInfo> groupVari;
String[] groupAttri;
HashMap<String, Integer> tableTitle;
HashMap<String, Integer> originalTitle;
int scanTime = 0;
ArrayList<ArrayList<Integer>> optimizedResult;
private File fout;
private BufferedWriter bw;
String[] Output;
public ExecuteFile(){
finalResult = new ArrayList<>();
groupVari = new HashMap<>();
tableTitle = new HashMap<>();
originalTitle = new HashMap<>();
optimizedResult = new ArrayList<>();
this.fout = new File("out.txt");
try {
this.bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fout)));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public class groupvaInfo{
conditionInfo Condit;
functionInfo funct;
public groupvaInfo(){;
Condit = new conditionInfo();
funct = new functionInfo();
}
}
public class conditionInfo{
HashMap<Integer, conditionkeyRelevantinfo> condition;
String[] sequentialconditionKey;
String[] operatorAnd;
String[] operatorOr;
public conditionInfo(){
condition = new HashMap<>();
}
}
public class conditionkeyRelevantinfo{
int index;
String operator;
String conditionValue;
pairvalue pairs = new pairvalue();
public class pairvalue{
char operatorPre = ' ';
double coefpre = 1;
double coefpost = 1;
char operatorPost = ' ';
};
};
public class functionInfo{
ArrayList<String> function;
HashMap<Byte, Integer> funcPosition;
HashMap<Byte, Integer> funcMaxMinPosit;
byte flag;
byte flagMaxMin;
public functionInfo(){
function = new ArrayList<>();
funcPosition = new HashMap<>();
funcMaxMinPosit = new HashMap<>();
flag = 0;
flagMaxMin = 0;
}
}
public void assign() {
for(int i = 0; i < 11; i++)
finalResult.add(new ArrayList<String>());
groupAttri = new String[2];
scanTime = 3;
groupAttri[0]= "cust";
groupAttri[1]= "prod";
Output = new String[6];
Output[0]= "cust";
Output[1]= "prod";
Output[2]= "1_sum_quant / 1_count_quant";
Output[3]= "1_avg_quant";
Output[4]= "2_avg_quant";
Output[5]= "3_avg_quant";
originalTitle.put("cust", 1);
originalTitle.put("prod", 2);
originalTitle.put("day", 3);
originalTitle.put("month", 4);
originalTitle.put("year", 5);
originalTitle.put("state", 6);
originalTitle.put("quant", 7);
tableTitle.put("1_sum_quant",7);
tableTitle.put("3_count_quant",11);
tableTitle.put("prod",2);
tableTitle.put("2_count_quant",5);
tableTitle.put("1_avg_quant",6);
tableTitle.put("1_count_quant",8);
tableTitle.put("2_sum_quant",4);
tableTitle.put("2_avg_quant",3);
tableTitle.put("3_sum_quant",10);
tableTitle.put("3_avg_quant",9);
tableTitle.put("cust",1);
optimizedResult.add(new ArrayList<Integer>());
optimizedResult.get(0).add(1);
optimizedResult.get(0).add(2);
optimizedResult.get(0).add(3);
groupVari.put(1 , new groupvaInfo());
groupVari.get(1).Condit.condition.put(0 , new conditionkeyRelevantinfo());
groupVari.get(1).Condit.condition.get(0).index = 1;
groupVari.get(1).Condit.condition.get(0).operator = "=";
groupVari.get(1).Condit.condition.get(0).conditionValue = "cust";
groupVari.get(1).Condit.condition.get(0).pairs.coefpost = 1.0;
groupVari.get(1).Condit.condition.get(0).pairs.coefpre = 1.0;
groupVari.get(1).Condit.condition.get(0).pairs.operatorPost = " ".charAt(0);
groupVari.get(1).Condit.condition.get(0).pairs.operatorPre = " ".charAt(0);
groupVari.get(1).Condit.condition.put(1 , new conditionkeyRelevantinfo());
groupVari.get(1).Condit.condition.get(1).index = 2;
groupVari.get(1).Condit.condition.get(1).operator = "=";
groupVari.get(1).Condit.condition.get(1).conditionValue = "prod";
groupVari.get(1).Condit.condition.get(1).pairs.coefpost = 1.0;
groupVari.get(1).Condit.condition.get(1).pairs.coefpre = 1.0;
groupVari.get(1).Condit.condition.get(1).pairs.operatorPost = " ".charAt(0);
groupVari.get(1).Condit.condition.get(1).pairs.operatorPre = " ".charAt(0);
groupVari.get(1).Condit.condition.put(2 , new conditionkeyRelevantinfo());
groupVari.get(1).Condit.condition.get(2).index = 6;
groupVari.get(1).Condit.condition.get(2).operator = "=";
groupVari.get(1).Condit.condition.get(2).conditionValue = "NY";
groupVari.get(1).Condit.condition.get(2).pairs.coefpost = 1.0;
groupVari.get(1).Condit.condition.get(2).pairs.coefpre = 1.0;
groupVari.get(1).Condit.condition.get(2).pairs.operatorPost = " ".charAt(0);
groupVari.get(1).Condit.condition.get(2).pairs.operatorPre = " ".charAt(0);
groupVari.get(1).Condit.sequentialconditionKey = new String[3];
groupVari.get(1).Condit.sequentialconditionKey[0] = "cust";
groupVari.get(1).Condit.sequentialconditionKey[1] = "prod";
groupVari.get(1).Condit.sequentialconditionKey[2] = "state";
groupVari.get(1).Condit.operatorAnd = new String[2];
groupVari.get(1).Condit.operatorAnd[0] = "0_1";
groupVari.get(1).Condit.operatorAnd[1] = "1_2";
groupVari.get(1).Condit.operatorOr = new String[0];
groupVari.get(1).funct.function.add("1_avg_quant");
groupVari.get(1).funct.function.add("1_sum_quant");
groupVari.get(1).funct.function.add("1_count_quant");
groupVari.get(1).funct.flag = 100;
groupVari.get(1).funct.flagMaxMin = 0;
groupVari.get(1).funct.funcPosition.put((byte)100,6);
groupVari.put(2 , new groupvaInfo());
groupVari.get(2).Condit.condition.put(0 , new conditionkeyRelevantinfo());
groupVari.get(2).Condit.condition.get(0).index = 1;
groupVari.get(2).Condit.condition.get(0).operator = "=";
groupVari.get(2).Condit.condition.get(0).conditionValue = "cust";
groupVari.get(2).Condit.condition.get(0).pairs.coefpost = 1.0;
groupVari.get(2).Condit.condition.get(0).pairs.coefpre = 1.0;
groupVari.get(2).Condit.condition.get(0).pairs.operatorPost = " ".charAt(0);
groupVari.get(2).Condit.condition.get(0).pairs.operatorPre = " ".charAt(0);
groupVari.get(2).Condit.condition.put(1 , new conditionkeyRelevantinfo());
groupVari.get(2).Condit.condition.get(1).index = 2;
groupVari.get(2).Condit.condition.get(1).operator = "=";
groupVari.get(2).Condit.condition.get(1).conditionValue = "prod";
groupVari.get(2).Condit.condition.get(1).pairs.coefpost = 1.0;
groupVari.get(2).Condit.condition.get(1).pairs.coefpre = 1.0;
groupVari.get(2).Condit.condition.get(1).pairs.operatorPost = " ".charAt(0);
groupVari.get(2).Condit.condition.get(1).pairs.operatorPre = " ".charAt(0);
groupVari.get(2).Condit.condition.put(2 , new conditionkeyRelevantinfo());
groupVari.get(2).Condit.condition.get(2).index = 6;
groupVari.get(2).Condit.condition.get(2).operator = "=";
groupVari.get(2).Condit.condition.get(2).conditionValue = "NJ";
groupVari.get(2).Condit.condition.get(2).pairs.coefpost = 1.0;
groupVari.get(2).Condit.condition.get(2).pairs.coefpre = 1.0;
groupVari.get(2).Condit.condition.get(2).pairs.operatorPost = " ".charAt(0);
groupVari.get(2).Condit.condition.get(2).pairs.operatorPre = " ".charAt(0);
groupVari.get(2).Condit.sequentialconditionKey = new String[3];
groupVari.get(2).Condit.sequentialconditionKey[0] = "cust";
groupVari.get(2).Condit.sequentialconditionKey[1] = "prod";
groupVari.get(2).Condit.sequentialconditionKey[2] = "state";
groupVari.get(2).Condit.operatorAnd = new String[2];
groupVari.get(2).Condit.operatorAnd[0] = "0_1";
groupVari.get(2).Condit.operatorAnd[1] = "1_2";
groupVari.get(2).Condit.operatorOr = new String[0];
groupVari.get(2).funct.function.add("2_avg_quant");
groupVari.get(2).funct.function.add("2_sum_quant");
groupVari.get(2).funct.function.add("2_count_quant");
groupVari.get(2).funct.flag = 100;
groupVari.get(2).funct.flagMaxMin = 0;
groupVari.get(2).funct.funcPosition.put((byte)100,3);
groupVari.put(3 , new groupvaInfo());
groupVari.get(3).Condit.condition.put(0 , new conditionkeyRelevantinfo());
groupVari.get(3).Condit.condition.get(0).index = 2;
groupVari.get(3).Condit.condition.get(0).operator = "=";
groupVari.get(3).Condit.condition.get(0).conditionValue = "prod";
groupVari.get(3).Condit.condition.get(0).pairs.coefpost = 1.0;
groupVari.get(3).Condit.condition.get(0).pairs.coefpre = 1.0;
groupVari.get(3).Condit.condition.get(0).pairs.operatorPost = " ".charAt(0);
groupVari.get(3).Condit.condition.get(0).pairs.operatorPre = " ".charAt(0);
groupVari.get(3).Condit.condition.put(1 , new conditionkeyRelevantinfo());
groupVari.get(3).Condit.condition.get(1).index = 1;
groupVari.get(3).Condit.condition.get(1).operator = "=";
groupVari.get(3).Condit.condition.get(1).conditionValue = "cust";
groupVari.get(3).Condit.condition.get(1).pairs.coefpost = 1.0;
groupVari.get(3).Condit.condition.get(1).pairs.coefpre = 1.0;
groupVari.get(3).Condit.condition.get(1).pairs.operatorPost = " ".charAt(0);
groupVari.get(3).Condit.condition.get(1).pairs.operatorPre = " ".charAt(0);
groupVari.get(3).Condit.condition.put(2 , new conditionkeyRelevantinfo());
groupVari.get(3).Condit.condition.get(2).index = 6;
groupVari.get(3).Condit.condition.get(2).operator = "=";
groupVari.get(3).Condit.condition.get(2).conditionValue = "CT";
groupVari.get(3).Condit.condition.get(2).pairs.coefpost = 1.0;
groupVari.get(3).Condit.condition.get(2).pairs.coefpre = 1.0;
groupVari.get(3).Condit.condition.get(2).pairs.operatorPost = " ".charAt(0);
groupVari.get(3).Condit.condition.get(2).pairs.operatorPre = " ".charAt(0);
groupVari.get(3).Condit.sequentialconditionKey = new String[3];
groupVari.get(3).Condit.sequentialconditionKey[0] = "prod";
groupVari.get(3).Condit.sequentialconditionKey[1] = "cust";
groupVari.get(3).Condit.sequentialconditionKey[2] = "state";
groupVari.get(3).Condit.operatorAnd = new String[2];
groupVari.get(3).Condit.operatorAnd[0] = "0_1";
groupVari.get(3).Condit.operatorAnd[1] = "1_2";
groupVari.get(3).Condit.operatorOr = new String[0];
groupVari.get(3).funct.function.add("3_avg_quant");
groupVari.get(3).funct.function.add("3_sum_quant");
groupVari.get(3).funct.function.add("3_count_quant");
groupVari.get(3).funct.flag = 100;
groupVari.get(3).funct.flagMaxMin = 0;
groupVari.get(3).funct.funcPosition.put((byte)100,9);
}
public static void main(String[] args) {
connect();
ExecuteFile dbmsass1 = new ExecuteFile();
try {
dbmsass1.con = DriverManager.getConnection(url, usr, pwd);
} catch (SQLException e1) {
e1.printStackTrace();
}
System.out.println("Success connecting server!");
dbmsass1.assign();
ResultSet rs;
Statement st;
try {
boolean targetOutput = true;
st = dbmsass1.con.createStatement();
String ret = "select * from sales";
rs = st.executeQuery(ret);
if(dbmsass1.groupVari.containsKey(-1))
dbmsass1.retreive0(rs,dbmsass1.groupAttri, dbmsass1.groupVari.get(-1), targetOutput);
else dbmsass1.retreive0(rs,dbmsass1.groupAttri, null, targetOutput);
for(int i = 0; i < dbmsass1.optimizedResult.size(); i++){
rs = st.executeQuery(ret);
dbmsass1.retreive(rs, dbmsass1.optimizedResult.get(i), dbmsass1, targetOutput);
}
targetOutput = false;
dbmsass1.output(rs, dbmsass1.groupVari.get(dbmsass1.scanTime + 1), targetOutput);
dbmsass1.closeFile();
} catch (SQLException e) {
e.printStackTrace();
}
}
public static void connect(){
try {
Class.forName("org.postgresql.Driver");
System.out.println("Success loading Driver!");
} catch(Exception exception) {
System.out.println("Fail loading Driver!");
exception.printStackTrace();
}
}
public String tableTitleNotContain(String unmatched, int checkrow){
String turnback ="";
int left = 0, right = left;
while(unmatched.charAt(right) != ' ') ++right;
String leftPart = unmatched.substring(left, right++);
char operator = unmatched.charAt(right++);
left = ++right;
String rightPart = unmatched.substring(left);
if(operator == '/'){
if(finalResult.get( tableTitle.get(rightPart) - 1).get(checkrow).equals("0") ) turnback = "0.0";
else turnback = (int)(1000 * Double.parseDouble(finalResult.get( tableTitle.get(leftPart) - 1).get(checkrow)) / Double.parseDouble(finalResult.get( tableTitle.get(rightPart) - 1).get(checkrow))) / 1000.0 +"";
}
else if(operator == '*')
turnback = Double.parseDouble(finalResult.get( tableTitle.get(leftPart) - 1).get(checkrow)) * Double.parseDouble(finalResult.get( tableTitle.get(rightPart) - 1).get(checkrow)) +"";
else if(operator == '+')
turnback = Double.parseDouble(finalResult.get( tableTitle.get(leftPart) - 1).get(checkrow)) + Double.parseDouble(finalResult.get( tableTitle.get(rightPart) - 1).get(checkrow)) +"";
else
turnback = Double.parseDouble(finalResult.get( tableTitle.get(leftPart) - 1).get(checkrow)) - Double.parseDouble(finalResult.get( tableTitle.get(rightPart) - 1).get(checkrow)) +"";
return turnback;
}
public void closeFile(){
try {
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public void outputfinal(int checkrow){
String result = "";
try {
for(int i = 0; i < Output.length; i++){
if(!tableTitle.containsKey(Output[i])) result = tableTitleNotContain(Output[i], checkrow);
else result = finalResult.get( tableTitle.get(Output[i]) - 1).get(checkrow);
System.out.printf("%-11s", result);
bw.write(result + " ");
}
System.out.println();
bw.write('\n');
} catch (IOException e) {
e.printStackTrace();
}
}
public void output(ResultSet rs, groupvaInfo outputInfo, boolean targetOutput){
int len = finalResult.get(0).size();
for(int checkrow = 0; checkrow < len; checkrow++){
if(outputInfo == null)
outputfinal(checkrow);
else if(outputInfo.Condit != null && ifclauseDeter(rs, outputInfo.Condit, checkrow, targetOutput))
outputfinal(checkrow);
}
}
public void processRetreive0(ResultSet rs , String[] groupAttri, HashSet<String> avoidDup){
StringBuilder conn = new StringBuilder(20);
for(int i = 0 ; i < groupAttri.length; i++){
try {
conn.append( rs.getString( originalTitle.get(groupAttri[i]) )).append("_");
} catch (SQLException e) {
e.printStackTrace();
}
}
if(!avoidDup.contains(conn.toString())){
avoidDup.add(conn.toString());
String[] a = conn.toString().split("_");
for(int i = 0; i < a.length; i++){
finalResult.get(tableTitle.get(groupAttri[i]) - 1).add(a[i]);
if(i == a.length - 1) while(++i < finalResult.size()) finalResult.get(i).add("0");
}
}
}
void retreive0(ResultSet rs , String[] groupAttri, groupvaInfo gvInfo, boolean targetOutput){
try {
HashSet<String> avoidDup = new HashSet<>();
boolean more;
more=rs.next();
while(more){
if( gvInfo != null && ifclauseDeter(rs, gvInfo.Condit, 0, targetOutput)) processRetreive0(rs , groupAttri, avoidDup);
else if(gvInfo == null) processRetreive0(rs , groupAttri, avoidDup);
more=rs.next();
}
} catch(SQLException e) {
System.out.println("Connection URL or username or password errors!");
e.printStackTrace();
}
}
void retreive(ResultSet rs, ArrayList<Integer> gvInfoBatch, ExecuteFile dbmsass1, boolean targetOutput){
try {
boolean more;
more=rs.next();
int len = finalResult.get(0).size();
byte flag;
byte flagMaxMin;
int inputFunctionValue;
int inputMaxMinFunctValue = 0;
while(more){
for(int checkrow = 0; checkrow < len; checkrow++){
for(Integer e : gvInfoBatch){
groupvaInfo gvInfo = dbmsass1.groupVari.get(e);
flagMaxMin = gvInfo.funct.flagMaxMin;
if(flagMaxMin != 0) inputMaxMinFunctValue = gvInfo.funct.funcMaxMinPosit.get(flagMaxMin) - 1;
flag = gvInfo.funct.flag;
inputFunctionValue = gvInfo.funct.funcPosition.get(flag) - 1;
if( ifclauseDeter(rs, gvInfo.Condit, checkrow, targetOutput)){
if(flagMaxMin == 11){
String max = finalResult.get(inputMaxMinFunctValue - 1).get(checkrow);
max = Integer.parseInt(max) >= rs.getInt(7)? max : rs.getInt(7) + "";
finalResult.get(inputMaxMinFunctValue - 1).set(checkrow,max);
String min = finalResult.get(inputMaxMinFunctValue).get(checkrow);
if(min.equals("0")) min = rs.getInt(7) + "";
else min = Integer.parseInt(min) <= rs.getInt(7)? min : rs.getInt(7) + "";
finalResult.get(inputMaxMinFunctValue).set(checkrow,min);
}
else if(flagMaxMin == 10){
String min = finalResult.get(inputMaxMinFunctValue).get(checkrow);
if(min.equals("0")) min = rs.getInt(7) + "";
else min = Integer.parseInt(min) <= rs.getInt(7)? min : rs.getInt(7) + "";
finalResult.get(inputMaxMinFunctValue).set(checkrow,min);
}
else if(flagMaxMin == 1){
String max = finalResult.get(inputMaxMinFunctValue).get(checkrow);
max = Integer.parseInt(max) >= rs.getInt(7)? max : rs.getInt(7) + "";
finalResult.get(inputMaxMinFunctValue).set(checkrow,max);
}
if(flag == 100){
String sum = finalResult.get(inputFunctionValue + 1).get(checkrow);
sum = Integer.parseInt(sum) + rs.getInt(7) +"";
String count = finalResult.get(inputFunctionValue + 2).get(checkrow);
count = Integer.parseInt(count) + 1 + "";
finalResult.get(inputFunctionValue + 1).set(checkrow,sum);
finalResult.get(inputFunctionValue + 2).set(checkrow,count);
}
else if(flag == 11){
String sum = finalResult.get(inputFunctionValue - 1).get(checkrow);
sum = Integer.parseInt(sum) + rs.getInt(7) +"";
String count = finalResult.get(inputFunctionValue).get(checkrow);
count = Integer.parseInt(count) + 1 + "";
finalResult.get(inputFunctionValue - 1).set(checkrow,sum);
finalResult.get(inputFunctionValue).set(checkrow,count);
}
else if(flag == 10){
String count = finalResult.get(inputFunctionValue).get(checkrow) ;
count = Integer.parseInt(count) + 1 + "";
finalResult.get(inputFunctionValue).set(checkrow,count);
}
else if(flag == 1){
String sum = finalResult.get(inputFunctionValue).get(checkrow);
sum = Integer.parseInt(sum) + rs.getInt(7) +"";
finalResult.get(inputFunctionValue).set(checkrow,sum);
}
if( gvInfo.Condit.sequentialconditionKey.length - 1 == groupAttri.length) break;
}
}
}
more = rs.next();
}
for(int checkrow = 0; checkrow < len; checkrow++){
for(Integer e : gvInfoBatch){
groupvaInfo gvInfo = dbmsass1.groupVari.get(e);
flag = gvInfo.funct.flag;
inputFunctionValue = gvInfo.funct.funcPosition.get(flag) - 1;
if(flag == 100){
String sum = finalResult.get(inputFunctionValue + 1).get(checkrow);
String count = finalResult.get(inputFunctionValue + 2).get(checkrow);
double b = Double.parseDouble(sum) / Integer.parseInt(count);
b = (int)(b*100) / 100.0;
finalResult.get(inputFunctionValue).set(checkrow,b +"");
}
}
}
} catch(SQLException e) {
System.out.println("Connection URL or username or password errors!");
e.printStackTrace();
}
}
public boolean extractConditionAndValue(int generalCondition, ResultSet rs, conditionInfo Condit, int checkrow, boolean targetOutput){
conditionkeyRelevantinfo indicate = Condit.condition.get(generalCondition);
int Conditionkey = indicate.index;
String detailedCondtion = null;
if(targetOutput){
try {
detailedCondtion = rs.getString(Conditionkey);
} catch (SQLException e) {
e.printStackTrace();
}
}
else detailedCondtion = finalResult.get(Conditionkey - 1).get(checkrow);
String conditionValue = indicate.conditionValue;
if(tableTitle.containsKey(conditionValue)) conditionValue = finalResult.get(tableTitle.get(conditionValue) - 1).get(checkrow);
String operator = indicate.operator;
if(indicate.pairs.operatorPre == '*') detailedCondtion = Double.parseDouble(detailedCondtion) * indicate.pairs.coefpre + "";
else if(indicate.pairs.operatorPre == '/') detailedCondtion = Double.parseDouble(detailedCondtion) / indicate.pairs.coefpre + "";
else if(indicate.pairs.operatorPre == '+') detailedCondtion = Double.parseDouble(detailedCondtion) + indicate.pairs.coefpre + "";
else if(indicate.pairs.operatorPre == '-') detailedCondtion = Double.parseDouble(detailedCondtion) - indicate.pairs.coefpre + "";
if(indicate.pairs.operatorPost == '*') conditionValue = Double.parseDouble(conditionValue) * indicate.pairs.coefpost + "";
else if(indicate.pairs.operatorPost == '/') conditionValue = Double.parseDouble(conditionValue) / indicate.pairs.coefpost + "";
else if(indicate.pairs.operatorPost == '+') conditionValue = Double.parseDouble(conditionValue) + indicate.pairs.coefpost + "";
else if(indicate.pairs.operatorPost == '-') conditionValue = Double.parseDouble(conditionValue) - indicate.pairs.coefpost + "";
if(operator.equals("=")){
if(conditionValue.charAt(0) >= '0' && conditionValue.charAt(0) <= '9')
return Math.abs(Double.parseDouble(conditionValue) - Double.parseDouble(detailedCondtion)) < 0.0000000001? true : false;
else return (detailedCondtion.equals(conditionValue) ? true : false);
}
else{
if(operator.equals(">=")) return Double.parseDouble(detailedCondtion) >= Double.parseDouble(conditionValue) ? true : false;
else if(operator.equals(">")) return Double.parseDouble(detailedCondtion) > Double.parseDouble(conditionValue) ? true : false;
else if(operator.equals("<=")) return Double.parseDouble(detailedCondtion) <= Double.parseDouble(conditionValue) ? true : false;
else if(operator.equals("!=")){
if(conditionValue.charAt(0) >= '0' && conditionValue.charAt(0) <= '9')
return Math.abs(Double.parseDouble(conditionValue) - Double.parseDouble(detailedCondtion)) >= 0.0000000001? true : false;
else return (detailedCondtion.equals(conditionValue) ? false : true);
}
return Double.parseDouble(detailedCondtion) < Double.parseDouble(conditionValue) ? true : false;
}
}
public void getTwopart(boolean[] twoPart,ResultSet rs, conditionInfo Condit, int checkrow, int index, int flag, boolean targetOutput){
if(flag == 0){
twoPart[0] = extractConditionAndValue(Condit.operatorAnd[index].charAt(0) - '0', rs, Condit, checkrow, targetOutput);
twoPart[1] = extractConditionAndValue(Condit.operatorAnd[index].charAt(2) - '0', rs, Condit, checkrow, targetOutput);
}
else {
twoPart[0] = extractConditionAndValue(Condit.operatorOr[index].charAt(0) - '0', rs, Condit, checkrow, targetOutput);
twoPart[1] = extractConditionAndValue(Condit.operatorOr[index].charAt(2) - '0', rs, Condit, checkrow, targetOutput);
}
}
public boolean ifclauseDeter(ResultSet rs, conditionInfo Condit, int checkrow, boolean targetOutput){
boolean connect = true;
boolean[] twoPart = new boolean[2];
ArrayList<Boolean> processOr = new ArrayList<>();
for(int i = 0 ; i < Condit.operatorAnd.length; i++){
getTwopart(twoPart, rs, Condit, checkrow, i , 0, targetOutput);
connect = connect && twoPart[0] && twoPart[1];
if(i + 1 >= Condit.operatorAnd.length) break;
if(Condit.operatorAnd[i].charAt(2) - '0' != Condit.operatorAnd[i + 1].charAt(0) - '0'){
processOr.add(connect);
connect = true;
}
}
for(int i = 0 ; i < processOr.size(); i++)
connect = connect || processOr.get(i);
if(Condit.operatorOr.length != 0 && Condit.operatorAnd.length != 0){
int indexCheckPre = 0, indexCheckPost = Condit.operatorOr.length - 1;
while(Condit.operatorOr[indexCheckPre].charAt(2) - '0' < Condit.operatorAnd[0].charAt(0) - '0') ++indexCheckPre;
if(Condit.operatorOr[indexCheckPre].charAt(2) - '0' == Condit.operatorAnd[0].charAt(0) - '0')
connect = connect || extractConditionAndValue(Condit.operatorOr[indexCheckPre].charAt(0) - '0', rs, Condit, checkrow, targetOutput);
for(int i = 0 ; i < indexCheckPre; i++){
getTwopart(twoPart, rs, Condit, checkrow, i , 1, targetOutput);
connect = connect || twoPart[0] || twoPart[1];
}
while(Condit.operatorOr[indexCheckPost].charAt(0) - '0' > Condit.operatorAnd[Condit.operatorAnd.length - 1].charAt(2) - '0') --indexCheckPost;
if(Condit.operatorOr[indexCheckPost].charAt(0) - '0' == Condit.operatorAnd[Condit.operatorAnd.length - 1].charAt(2) - '0')
connect = connect || extractConditionAndValue(Condit.operatorOr[indexCheckPost].charAt(2) - '0', rs, Condit, checkrow, targetOutput);
for(int i = indexCheckPost + 1 ; i < Condit.operatorOr.length; i++){
getTwopart(twoPart, rs, Condit, checkrow, i , 1, targetOutput);
connect = connect || twoPart[0] || twoPart[1];
}
}
else if(Condit.operatorOr.length == 0 && Condit.operatorAnd.length == 0){
connect = extractConditionAndValue(0, rs, Condit, checkrow, targetOutput);
}
else{
for(int i = 0 ; i < Condit.operatorOr.length; i++){
getTwopart(twoPart, rs, Condit, checkrow, i , 1, targetOutput);
connect = connect || twoPart[0] || twoPart[1];
}
}
return connect;
}
}
|
package com.tt.miniapp.component.nativeview.video.controller;
import com.ss.ttvideoengine.TTVideoEngine;
import com.ss.ttvideoengine.utils.Error;
import com.tt.frontendapiinterface.j;
import com.tt.miniapp.AppbrandApplicationImpl;
import com.tt.miniapp.WebViewManager;
import com.tt.miniapp.component.nativeview.video.VideoView;
import com.tt.miniapp.event.Event;
import com.tt.miniapp.video.patchad.PatchAdVideoCallback;
import com.tt.miniapp.video.patchad.PatchAdVideoController;
import com.tt.miniapp.view.webcore.AbsoluteLayout;
import com.tt.miniapphost.AppBrandLogger;
import com.tt.miniapphost.AppbrandApplication;
import com.tt.miniapphost.util.JsonBuilder;
import com.tt.option.ad.c;
import org.json.JSONObject;
public class BaseVideoViewController extends PatchAdVideoController {
VideoLayoutEntity mBeforeFullScreenLayoutInfo;
WebViewManager.IRender mRender;
VideoView.VideoModel mVideoModel;
VideoView mVideoView;
int mZIndex;
BaseVideoViewController(VideoView paramVideoView, WebViewManager.IRender paramIRender) {
super((PatchAdVideoCallback)paramVideoView, (paramVideoView.getVideoModel()).videoPlayerId);
this.mVideoView = paramVideoView;
this.mVideoModel = paramVideoView.getVideoModel();
this.mRender = paramIRender;
}
private void callbackVideoAdEvent(String paramString, boolean paramBoolean) {
String str;
if (paramBoolean) {
str = c.APP_VIDEO_PATCH_AD_PRE.getStrType();
} else {
str = c.APP_VIDEO_PATCH_AD_POST.getStrType();
}
AppBrandLogger.i("BaseVideoViewController", new Object[] { "send patchAd Event", paramString, Boolean.valueOf(paramBoolean) });
callbackVideoEvent(paramString, (new JsonBuilder()).put("adType", str).build());
}
private void callbackVideoEvent(String paramString) {
callbackVideoEvent(paramString, (JSONObject)null);
}
private void callbackVideoEvent(String paramString, JSONObject paramJSONObject) {
j j = AppbrandApplication.getInst().getJsBridge();
if (j == null)
return;
j.sendMsgToJsCore(paramString, (new JsonBuilder(paramJSONObject)).put("videoPlayerId", Integer.valueOf(this.mVideoModel.videoPlayerId)).put("data", this.mVideoModel.data.toString()).build().toString(), this.mRender.getWebViewId());
}
public static BaseVideoViewController getImpl(VideoView paramVideoView, WebViewManager.IRender paramIRender) {
return (BaseVideoViewController)(paramVideoView.getViewParent().isRenderInBrowserEnabled() ? new RenderInBrowserController(paramVideoView, paramIRender) : new NormalController(paramVideoView, paramIRender, null));
}
private void publishVideoEvent(String paramString, JsonBuilder paramJsonBuilder) {
String str = paramJsonBuilder.put("videoPlayerId", Integer.valueOf(this.mVideoModel.videoPlayerId)).put("data", this.mVideoModel.data.toString()).build().toString();
AppBrandLogger.i("BaseVideoViewController", new Object[] { "publish patchAd Event", paramString, str });
AppbrandApplicationImpl.getInst().getWebViewManager().publish(this.mRender.getWebViewId(), paramString, str);
}
public void destroyPatchAd() {
super.destroyPatchAd();
if (this.calledVideoAdStarted != null)
onVideoAdClose(Boolean.TRUE.equals(this.calledVideoAdStarted));
}
public void onBufferStart() {
super.onBufferStart();
AppBrandLogger.d("BaseVideoViewController", new Object[] { "onBufferStart" });
callbackVideoEvent("onVideoWaiting");
}
public void onCompletion(TTVideoEngine paramTTVideoEngine) {
super.onCompletion(paramTTVideoEngine);
StringBuilder stringBuilder = new StringBuilder("ended:给js发消息--onVideoEnded--: videoPlayerId = ");
stringBuilder.append(this.mVideoModel.videoPlayerId);
AppBrandLogger.d("BaseVideoViewController", new Object[] { stringBuilder.toString() });
callbackVideoEvent("onVideoEnded");
}
public void onError(Error paramError) {
String str;
super.onError(paramError);
try {
str = (new JSONObject(paramError.toMap())).toString();
} catch (Exception exception) {
AppBrandLogger.eWithThrowable("BaseVideoViewController", "video error 2 json failed", exception);
str = "";
}
Event.builder("mp_video_error").kv("error_msg", str).flush();
AppBrandLogger.e("BaseVideoViewController", new Object[] { "ended:给js发消息--onVideoError--: videoPlayerId =", Integer.valueOf(this.mVideoModel.videoPlayerId), "errMsg =", str });
callbackVideoEvent("onVideoError", (new JsonBuilder()).put("errMsg", str).build());
}
public void onFullScreen(boolean paramBoolean, int paramInt) {
String str;
super.onFullScreen(paramBoolean, paramInt);
JsonBuilder jsonBuilder = (new JsonBuilder()).put("fullScreen", Boolean.valueOf(paramBoolean));
if (paramInt == 0 || paramInt == 8) {
str = "horizontal";
} else {
str = "vertical";
}
callbackVideoEvent("onVideoFullScreenChange", jsonBuilder.put("direction", str).build());
}
public void onPlaybackStateChanged(TTVideoEngine paramTTVideoEngine, int paramInt) {
super.onPlaybackStateChanged(paramTTVideoEngine, paramInt);
if (paramInt != 1) {
if (paramInt != 2)
return;
StringBuilder stringBuilder1 = new StringBuilder("pause:给js发消息--onVideoPause--: videoPlayerId = ");
stringBuilder1.append(this.mVideoModel.videoPlayerId);
AppBrandLogger.d("BaseVideoViewController", new Object[] { stringBuilder1.toString() });
callbackVideoEvent("onVideoPause");
return;
}
StringBuilder stringBuilder = new StringBuilder("play:给js发消息--onVideoPlay--: videoPlayerId = ");
stringBuilder.append(this.mVideoModel.videoPlayerId);
AppBrandLogger.d("BaseVideoViewController", new Object[] { stringBuilder.toString() });
callbackVideoEvent("onVideoPlay");
}
public void onPrepare(TTVideoEngine paramTTVideoEngine) {
super.onPrepare(paramTTVideoEngine);
}
public void onProgressAndTimeUpdate(int paramInt1, int paramInt2) {
super.onProgressAndTimeUpdate(paramInt1, paramInt2);
callbackVideoEvent("onVideoTimeUpdate", (new JsonBuilder()).put("currentTime", Integer.valueOf(paramInt1)).put("duration", Integer.valueOf(paramInt2)).build());
}
public void onStuffOverVideoVisibilityChange(boolean paramBoolean1, boolean paramBoolean2) {
super.onStuffOverVideoVisibilityChange(paramBoolean1, paramBoolean2);
if (!paramBoolean2 || this.called2Hidden) {
String str;
this.called2Hidden = paramBoolean2 ^ true;
if (paramBoolean1) {
str = c.APP_VIDEO_PATCH_AD_PRE.getStrType();
} else {
str = c.APP_VIDEO_PATCH_AD_POST.getStrType();
}
publishVideoEvent("onStuffOverVideoVisibilityShouldChange", (new JsonBuilder()).put("adType", str).put("hidden", Boolean.valueOf(this.called2Hidden)));
}
}
public void onVideoAdClose(boolean paramBoolean) {
super.onVideoAdClose(paramBoolean);
callbackVideoAdEvent("onVideoAdClose", paramBoolean);
this.calledVideoAdStarted = null;
}
public void onVideoAdEnded(boolean paramBoolean) {
super.onVideoAdEnded(paramBoolean);
callbackVideoAdEvent("onVideoAdEnded", paramBoolean);
this.calledVideoAdStarted = null;
}
public void onVideoAdError(boolean paramBoolean, int paramInt, String paramString) {
String str;
super.onVideoAdError(paramBoolean, paramInt, paramString);
JsonBuilder jsonBuilder = new JsonBuilder();
if (paramBoolean) {
str = c.APP_VIDEO_PATCH_AD_PRE.getStrType();
} else {
str = c.APP_VIDEO_PATCH_AD_POST.getStrType();
}
callbackVideoEvent("onVideoAdError", jsonBuilder.put("adType", str).put("errCode", Integer.valueOf(paramInt)).put("errMsg", paramString).build());
}
public void onVideoAdFullscreenChange(boolean paramBoolean1, boolean paramBoolean2) {
String str1;
String str2;
super.onVideoAdFullscreenChange(paramBoolean1, paramBoolean2);
if (paramBoolean2) {
str1 = "onVideoRequestFullScreen";
} else {
str1 = "onVideoExitFullScreen";
}
if (paramBoolean1) {
str2 = c.APP_VIDEO_PATCH_AD_PRE.getStrType();
} else {
str2 = c.APP_VIDEO_PATCH_AD_POST.getStrType();
}
publishVideoEvent(str1, (new JsonBuilder()).put("adType", str2).put("fullscreen", Boolean.valueOf(paramBoolean2)));
}
public void onVideoAdLoaded(boolean paramBoolean) {
super.onVideoAdLoaded(paramBoolean);
callbackVideoAdEvent("onVideoAdLoad", paramBoolean);
}
public void onVideoAdStart(boolean paramBoolean) {
super.onVideoAdStart(paramBoolean);
if (this.calledVideoAdStarted != null)
return;
this.calledVideoAdStarted = Boolean.valueOf(paramBoolean);
callbackVideoAdEvent("onVideoAdStart", paramBoolean);
}
public void setZIndex(int paramInt) {
this.mZIndex = paramInt;
}
static class VideoLayoutEntity {
AbsoluteLayout.LayoutParams mBeforeFullScreenLayoutParams;
AbsoluteLayout.ViewOffset mBeforeFullScreenOffset;
int mBeforeFullScreenScrollX;
int mBeforeFullScreenScrollY;
public VideoLayoutEntity(VideoView param1VideoView) {
if (param1VideoView != null)
this.mBeforeFullScreenLayoutParams = (AbsoluteLayout.LayoutParams)param1VideoView.getLayoutParams();
}
public static VideoLayoutEntity saveBeforeFullScreenInfo(VideoView param1VideoView) {
if (param1VideoView == null)
return null;
VideoLayoutEntity videoLayoutEntity = new VideoLayoutEntity(param1VideoView);
if (param1VideoView.getViewParent() != null) {
AbsoluteLayout absoluteLayout = param1VideoView.getViewParent();
videoLayoutEntity.mBeforeFullScreenOffset = absoluteLayout.getViewOffset(param1VideoView.getId());
videoLayoutEntity.mBeforeFullScreenScrollX = absoluteLayout.getCurScrollX();
videoLayoutEntity.mBeforeFullScreenScrollY = absoluteLayout.getCurScrollY();
}
return videoLayoutEntity;
}
public static void updateVideoLayoutInfo(VideoLayoutEntity param1VideoLayoutEntity, VideoView param1VideoView) {
if (param1VideoLayoutEntity != null) {
if (param1VideoView == null)
return;
if (param1VideoView.getViewParent() != null) {
if (param1VideoView.getViewParent().isRenderInBrowserEnabled())
return;
int i = param1VideoView.getViewParent().getCurScrollX();
int j = param1VideoLayoutEntity.mBeforeFullScreenScrollX;
int k = param1VideoView.getViewParent().getCurScrollY();
int m = param1VideoLayoutEntity.mBeforeFullScreenScrollY;
AbsoluteLayout.LayoutParams layoutParams2 = param1VideoLayoutEntity.mBeforeFullScreenLayoutParams;
layoutParams2.x -= i - j;
AbsoluteLayout.LayoutParams layoutParams1 = param1VideoLayoutEntity.mBeforeFullScreenLayoutParams;
layoutParams1.y -= k - m;
}
}
}
}
}
/* Location: C:\Users\august\Desktop\tik\df_miniapp\classes.jar!\com\tt\miniapp\component\nativeview\video\controller\BaseVideoViewController.class
* Java compiler version: 6 (50.0)
* JD-Core Version: 1.1.3
*/
|
package com.tfjybj.integral.provider.service;
import com.alibaba.fastjson.JSONObject;
import com.tfjybj.integral.model.NoUserOrgModel;
import com.tfjybj.integral.provider.dao.GetNewDingPersonDao;
import com.tfjybj.integral.utils.http.HttpUtils;
import com.tfjybj.integral.utils.http.ResponseWrap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.client.RestTemplate;
import javax.annotation.Resource;
import java.util.*;
@Service("getNewDingPersonService")
public class GetNewDingPersonService {
@Resource
private GetNewDingPersonDao getNewDingPersonDao;
@Autowired
private NoUserOrgModel noUserOrgModel;
private String token;
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
{
//获取token
HttpUtils http =
HttpUtils.get("https://oapi.dingtalk.com/gettoken?appkey=dingt452prfmxlwv9dsx&appsecret=HojvOyIB0eVdmLurfK4d8RNkxO_2JviKyT4MsKkpWVt81NkKRiP0Q0X_gXQlCKR-");
http.addHeader("Content-Type", "application/json;charset=utf-8");
ResponseWrap execute = http.execute();
String resultStr = execute.getString();
Object parse = JSONObject.parse(resultStr);
JSONObject jsonObject = (JSONObject) parse;
this.setToken(jsonObject.getString("access_token"));
}
/**
* 通过子部门id更新isgiveself字段
* @author 梁佳宝
*/
public void allUserDingId(){
//获取到所有子部门id
List<Integer> dingDept = getDingDept();
RestTemplate restTemplate = new RestTemplate();
HashSet<String> allUserDingId = new HashSet<>();
//遍历子部门id,获取dingid
dingDept.stream().forEach(child->{
String getDingIdUrl = "https://oapi.dingtalk.com/user/getDeptMember?access_token="+ token+"&deptId="+ child;
JSONObject resultJson = restTemplate.getForEntity(getDingIdUrl, JSONObject.class).getBody();
List<String> userIds = (List<String>) resultJson.get("userIds");
//如果dingid不为空,则添加到集合中
if(!CollectionUtils.isEmpty(userIds)){
allUserDingId.addAll(userIds);
}
});
Integer intresult = getNewDingPersonDao.updateIsGivingSelfZero();
List<String> ids = getNewDingPersonDao.selectIdByDingId(allUserDingId);
Integer integer = getNewDingPersonDao.updateIsGivingSelfById(ids);
}
/**
* 获取所有子部门id
* @return
* @author 梁佳宝
*/
public List<Integer> getDingDept() {
//获取所有部门id进行筛选
RestTemplate restTemplate = new RestTemplate();
String url = "https://oapi.dingtalk.com/department/list_ids?access_token=" + token + "&id=1";
JSONObject resultJson = restTemplate.getForEntity(url, JSONObject.class).getBody();
List<Integer> subDeptIdListist = (List<Integer>) resultJson.get("sub_dept_id_list");
//获取没用的部门id并移除
List<Integer> deptlist = noUserOrgModel.getDept();
subDeptIdListist.removeAll(deptlist);
List<Integer> allSonDept = new ArrayList<>();
//将根目录部门id添加进去
allSonDept.add(1);
//遍历根目录下的几个部门
subDeptIdListist.stream().forEach(item ->{
String allSonDeptUrl = "https://oapi.dingtalk.com/department/list?access_token="+ token +"&id="+item;
JSONObject sonDeptJson = restTemplate.getForEntity(allSonDeptUrl,JSONObject.class).getBody();
List<Object> department = (List<Object>) sonDeptJson.get("department");
//如果部门下有子部门,获取子部门id添加到子部门集合中
if (!CollectionUtils.isEmpty(department)){
for (Object object:department){
JSONObject jsObject = JSONObject.parseObject(JSONObject.toJSONString(object));
Integer id = jsObject.getInteger("id");
allSonDept.add(id);
}
}else{
//如果部门下没有子部门,直接将该部门id添加到子部门集合中
allSonDept.add(item);
}
});
return allSonDept;
}
}
|
package com.tencent.mm.plugin.ext.provider;
import com.tencent.mm.ab.e;
import com.tencent.mm.plugin.ext.provider.ExtControlProviderMsg.2;
class ExtControlProviderMsg$2$1 implements e {
final /* synthetic */ String iKh;
final /* synthetic */ 2 iKi;
ExtControlProviderMsg$2$1(2 2, String str) {
this.iKi = 2;
this.iKh = str;
}
/* JADX WARNING: inconsistent code. */
/* Code decompiled incorrectly, please refer to instructions dump. */
public final void a(int r10, int r11, java.lang.String r12, com.tencent.mm.ab.l r13) {
/*
r9 = this;
r8 = 522; // 0x20a float:7.31E-43 double:2.58E-321;
r7 = 4;
r6 = 2;
r5 = 1;
r4 = 0;
r0 = "MicroMsg.ExtControlProviderMsg";
r1 = "onSceneEnd errType=%s, errCode=%s";
r2 = new java.lang.Object[r6];
r3 = java.lang.Integer.valueOf(r10);
r2[r4] = r3;
r3 = java.lang.Integer.valueOf(r11);
r2[r5] = r3;
com.tencent.mm.sdk.platformtools.x.d(r0, r1, r2);
if (r13 != 0) goto L_0x003e;
L_0x001f:
r0 = "MicroMsg.ExtControlProviderMsg";
r1 = "scene == null";
com.tencent.mm.sdk.platformtools.x.e(r0, r1);
r0 = com.tencent.mm.model.au.DF();
r0.b(r8, r9);
r0 = r9.iKi;
r0 = r0.iKf;
r0.pr(r7);
r0 = r9.iKi;
r0 = r0.heb;
r0.countDown();
L_0x003d:
return;
L_0x003e:
r0 = r13.getType();
switch(r0) {
case 522: goto L_0x005b;
default: goto L_0x0045;
};
L_0x0045:
r0 = r9.iKi;
r0 = r0.iKf;
r0.pr(r4);
L_0x004c:
r0 = r9.iKi;
r0 = r0.heb;
r0.countDown();
r0 = com.tencent.mm.model.au.DF();
r0.b(r8, r9);
goto L_0x003d;
L_0x005b:
if (r10 != 0) goto L_0x0080;
L_0x005d:
if (r11 != 0) goto L_0x0080;
L_0x005f:
r0 = "MicroMsg.ExtControlProviderMsg";
r1 = "rtSENDMSG onSceneEnd ok, ";
com.tencent.mm.sdk.platformtools.x.d(r0, r1);
r0 = r9.iKi;
r0 = r0.iKf;
r0 = com.tencent.mm.plugin.ext.provider.ExtControlProviderMsg.a(r0);
r1 = new java.lang.Object[r6];
r2 = r9.iKh;
r1[r4] = r2;
r2 = java.lang.Integer.valueOf(r5);
r1[r5] = r2;
r0.addRow(r1);
goto L_0x0045;
L_0x0080:
r0 = "MicroMsg.ExtControlProviderMsg";
r1 = new java.lang.StringBuilder;
r2 = "rtSENDMSG onSceneEnd err, errType = ";
r1.<init>(r2);
r1 = r1.append(r10);
r2 = ", errCode = ";
r1 = r1.append(r2);
r1 = r1.append(r11);
r1 = r1.toString();
com.tencent.mm.sdk.platformtools.x.e(r0, r1);
r0 = r9.iKi;
r0 = r0.iKf;
r0 = com.tencent.mm.plugin.ext.provider.ExtControlProviderMsg.a(r0);
r1 = new java.lang.Object[r6];
r2 = r9.iKh;
r1[r4] = r2;
r2 = java.lang.Integer.valueOf(r6);
r1[r5] = r2;
r0.addRow(r1);
r0 = r9.iKi;
r0 = r0.iKf;
r0.pr(r7);
goto L_0x004c;
*/
throw new UnsupportedOperationException("Method not decompiled: com.tencent.mm.plugin.ext.provider.ExtControlProviderMsg$2$1.a(int, int, java.lang.String, com.tencent.mm.ab.l):void");
}
}
|
package leetcode_easy;
import java.util.Arrays;
public class Question_908 {
public int smallestRangeI(int[] A, int K) {
Arrays.sort(A);
int min = A[0];
int min_max = min + K;
int max = A[A.length - 1];
int max_min = max - K;
int range = 0;
if (min_max >= max_min) {
range = 0;
} else {
range = max_min - min_max;
}
return range;
}
public void solve() {
int[] A = new int[] {0,10};
int K = 2;
System.out.println(smallestRangeI(A,K));
}
}
|
package com.onlylemi.mapview.library.layer;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.view.MotionEvent;
import com.onlylemi.mapview.library.MapView;
public class AnchorLayer extends MapBaseLayer {
public AnchorLayer(MapView mapView) {
super(mapView);
}
@Override
public void onTouch(MotionEvent event) {
}
@Override
public void draw(Canvas canvas, Matrix currentMatrix, float currentZoom, float currentRotateDegrees) {
}
}
|
package com.kingbbode.bot.common.annotations;
import com.kingbbode.bot.common.enums.BrainRequestType;
import org.springframework.stereotype.Component;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Component
public @interface Brain {
BrainRequestType request() default BrainRequestType.COMMON;
}
|
package paper;
import java.io.*;
public class txtSplit{
/**
*根據需求,直接調用靜態方法start來執行操作
*參數:
* rows為多少行一個文件int類型
* sourceFilePath為源文件路徑String類型
* targetDirectoryPath為文件分割後存放的目標目錄String類型
* ---分割後的文件名 為索引號(從0開始)加'_'加源文件名,例如源文件名 為test.txt,則分割後文件名 為0_test .txt,以此類推
*/
public static void start(int rows,String sourceFilePath,String targetDirectoryPath){
File sourceFile = new File(sourceFilePath);
File targetFile = new File(targetDirectoryPath);
if(!sourceFile.exists()||rows<=0||sourceFile.isDirectory()){
System.out.println("源文件不存在或者輸入了錯誤的行數");
return;
}
if(targetFile.exists()){
if(!targetFile.isDirectory()){
System.out.println("目標文件夾錯誤,不是一個文件夾");
return;
}
}else{
targetFile.mkdirs();
}
try{
long strLength = sourceFile.length();
long size = 500 * 1024;
//System.out.println(strLength/size);
int dataNum = (int)strLength/(int)size;
if(strLength/size != 0 ){
dataNum = ((int)strLength/(int)size + 1);
}
rows = rows/dataNum ;
BufferedReader br = new BufferedReader(new FileReader(sourceFile));
BufferedWriter bw = null;
String str = "";
String tempData = br.readLine();
int i=1,s=0;
while(tempData!=null){
str += tempData+"\r\n";
if(i%rows==0){
bw = new BufferedWriter(new FileWriter(new File(targetFile.getAbsolutePath()+"/"+s+"_"+sourceFile.getName())));
bw.write(str);
bw.close();
str = "";
s += 1;
}
i++;
tempData = br.readLine();
}
if((i-1)%rows!=0){
bw = new BufferedWriter(new FileWriter(new File(targetFile.getAbsolutePath()+"/"+s+"_"+sourceFile.getName())));
bw.write(str);
bw.close();
br.close();
s += 1;
}
System.out.println("文件分割結束,共分割成了"+s+"個文件");
}catch(Exception e){}
}
//Test
public static void main(String args[]){
txtSplit.start(97236,"D:/test/PreProcess/ppOutPut_1123.txt","D:/test/PreProcess/ppOutPut_out2/");
}
}
|
package com.jst.model;
import java.util.Date;
/**
* 这是一个权限表
* @author Administrator
*
*/
public class Sys_function {
private int function_id;//权限id
private int parent_id;//权限父id
private String function_name;//权限名
private String function_url;//权限url
private int function_type;//权限类型 1,菜单 2,功能
private Date create_time;//创建时间
private int sort;//排序
public int getFunction_id() {
return function_id;
}
public void setFunction_id(int function_id) {
this.function_id = function_id;
}
public int getParent_id() {
return parent_id;
}
public void setParent_id(int parent_id) {
this.parent_id = parent_id;
}
public String getFunction_name() {
return function_name;
}
public void setFunction_name(String function_name) {
this.function_name = function_name;
}
public String getFunction_url() {
return function_url;
}
public void setFunction_url(String function_url) {
this.function_url = function_url;
}
public int getFunction_type() {
return function_type;
}
public void setFunction_type(int function_type) {
this.function_type = function_type;
}
public Date getCreate_time() {
return create_time;
}
public void setCreate_time(Date create_time) {
this.create_time = create_time;
}
public int getSort() {
return sort;
}
public void setSort(int sort) {
this.sort = sort;
}
@Override
public String toString() {
return "Sys_function [function_id=" + function_id + ", parent_id=" + parent_id + ", function_name="
+ function_name + ", function_url=" + function_url + ", function_type=" + function_type
+ ", create_time=" + create_time + ", sort=" + sort + "]";
}
}
|
/*
* 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.beam.sdk.io.gcp.bigtable.changestreams.dao;
import static com.google.cloud.bigtable.data.v2.models.Filters.FILTERS;
import static org.apache.beam.sdk.io.gcp.bigtable.changestreams.dao.MetadataTableAdminDao.DETECT_NEW_PARTITION_SUFFIX;
import static org.apache.beam.sdk.io.gcp.bigtable.changestreams.dao.MetadataTableAdminDao.NEW_PARTITION_PREFIX;
import static org.apache.beam.sdk.io.gcp.bigtable.changestreams.dao.MetadataTableAdminDao.STREAM_PARTITION_PREFIX;
import com.google.api.gax.rpc.ServerStream;
import com.google.cloud.bigtable.data.v2.BigtableDataClient;
import com.google.cloud.bigtable.data.v2.models.ChangeStreamContinuationToken;
import com.google.cloud.bigtable.data.v2.models.ConditionalRowMutation;
import com.google.cloud.bigtable.data.v2.models.Filters.Filter;
import com.google.cloud.bigtable.data.v2.models.Mutation;
import com.google.cloud.bigtable.data.v2.models.Query;
import com.google.cloud.bigtable.data.v2.models.Range.ByteStringRange;
import com.google.cloud.bigtable.data.v2.models.Row;
import com.google.cloud.bigtable.data.v2.models.RowMutation;
import com.google.protobuf.ByteString;
import com.google.protobuf.InvalidProtocolBufferException;
import java.util.HashMap;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import org.apache.beam.repackaged.core.org.apache.commons.lang3.SerializationException;
import org.apache.beam.repackaged.core.org.apache.commons.lang3.SerializationUtils;
import org.apache.beam.sdk.annotations.Internal;
import org.joda.time.Instant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Data access object for managing the state of the metadata Bigtable table.
*
* <p>Metadata table is shared across many beam jobs. Each beam job uses a specific prefix to
* identify itself which is used as the row prefix.
*/
@Internal
public class MetadataTableDao {
private static final Logger LOG = LoggerFactory.getLogger(MetadataTableDao.class);
private final BigtableDataClient dataClient;
private final String tableId;
private final ByteString changeStreamNamePrefix;
public MetadataTableDao(
BigtableDataClient dataClient, String tableId, ByteString changeStreamNamePrefix) {
this.dataClient = dataClient;
this.tableId = tableId;
this.changeStreamNamePrefix = changeStreamNamePrefix;
}
/** @return the prefix that is prepended to every row belonging to this beam job. */
public ByteString getChangeStreamNamePrefix() {
return changeStreamNamePrefix;
}
/**
* Return new partition row key prefix concatenated with change stream name.
*
* @return new partition row key prefix concatenated with change stream name.
*/
private ByteString getFullNewPartitionPrefix() {
return changeStreamNamePrefix.concat(NEW_PARTITION_PREFIX);
}
/**
* Return stream partition row key prefix concatenated with change stream name.
*
* @return stream partition row key prefix concatenated with change stream name.
*/
private ByteString getFullStreamPartitionPrefix() {
return changeStreamNamePrefix.concat(STREAM_PARTITION_PREFIX);
}
/**
* Return detect new partition row key concatenated with change stream name.
*
* @return detect new partition row key concatenated with change stream name.
*/
private ByteString getFullDetectNewPartition() {
return changeStreamNamePrefix.concat(DETECT_NEW_PARTITION_SUFFIX);
}
/**
* Convert stream partition row key to partition to process metadata read from Bigtable.
*
* <p>RowKey should be directly from Cloud Bigtable and not altered in any way.
*
* @param rowKey row key from Cloud Bigtable
* @return partition extracted from rowKey
* @throws InvalidProtocolBufferException if conversion from rowKey to partition fails
*/
public ByteStringRange convertStreamPartitionRowKeyToPartition(ByteString rowKey)
throws InvalidProtocolBufferException {
int prefixLength = changeStreamNamePrefix.size() + STREAM_PARTITION_PREFIX.size();
return ByteStringRange.toByteStringRange(rowKey.substring(prefixLength));
}
/**
* Convert partition to a Stream Partition row key to query for metadata of partitions that are
* currently being streamed.
*
* @param partition convert to row key
* @return row key to insert to Cloud Bigtable.
*/
public ByteString convertPartitionToStreamPartitionRowKey(ByteStringRange partition) {
return getFullStreamPartitionPrefix().concat(ByteStringRange.serializeToByteString(partition));
}
/**
* Convert new partition row key to partition to process metadata read from Bigtable.
*
* <p>RowKey should be directly from Cloud Bigtable and not altered in any way.
*
* @param rowKey row key from Cloud Bigtable
* @return partition extracted from rowKey
* @throws InvalidProtocolBufferException if conversion from rowKey to partition fails
*/
public ByteStringRange convertNewPartitionRowKeyToPartition(ByteString rowKey)
throws InvalidProtocolBufferException {
int prefixLength = changeStreamNamePrefix.size() + NEW_PARTITION_PREFIX.size();
return ByteStringRange.toByteStringRange(rowKey.substring(prefixLength));
}
/**
* Convert partition to a New Partition row key to query for partitions ready to be streamed as
* the result of splits and merges.
*
* @param partition convert to row key
* @return row key to insert to Cloud Bigtable.
*/
public ByteString convertPartitionToNewPartitionRowKey(ByteStringRange partition) {
return getFullNewPartitionPrefix().concat(ByteStringRange.serializeToByteString(partition));
}
/**
* @return stream of all the new partitions resulting from splits and merges waiting to be
* streamed.
*/
public ServerStream<Row> readNewPartitions() {
// It's important that we limit to the latest value per column because it's possible to write to
// the same column multiple times. We don't want to read and send duplicate tokens to the
// server.
Query query =
Query.create(tableId)
.prefix(getFullNewPartitionPrefix())
.filter(FILTERS.limit().cellsPerColumn(1));
return dataClient.readRows(query);
}
/**
* After a split or merge from a close stream, write the new partition's information to the
* metadata table.
*
* @param newPartition the new partition
* @param changeStreamContinuationToken the token that can be used to pick up from where the
* parent left off
* @param parentPartition the parent that stopped and split or merged
* @param lowWatermark the low watermark of the parent stream
*/
public void writeNewPartition(
ByteStringRange newPartition,
ChangeStreamContinuationToken changeStreamContinuationToken,
ByteStringRange parentPartition,
Instant lowWatermark) {
writeNewPartition(
newPartition,
changeStreamContinuationToken.toByteString(),
ByteStringRange.serializeToByteString(parentPartition),
lowWatermark);
}
/**
* After a split or merge from a close stream, write the new partition's information to the
* metadata table.
*
* @param newPartition the new partition
* @param newPartitionContinuationToken continuation token for the new partition
* @param parentPartition the parent that stopped
* @param lowWatermark low watermark of the parent
*/
private void writeNewPartition(
ByteStringRange newPartition,
ByteString newPartitionContinuationToken,
ByteString parentPartition,
Instant lowWatermark) {
LOG.debug("Insert new partition");
ByteString rowKey = convertPartitionToNewPartitionRowKey(newPartition);
RowMutation rowMutation =
RowMutation.create(tableId, rowKey)
.setCell(MetadataTableAdminDao.CF_INITIAL_TOKEN, newPartitionContinuationToken, 1)
.setCell(MetadataTableAdminDao.CF_PARENT_PARTITIONS, parentPartition, 1)
.setCell(
MetadataTableAdminDao.CF_PARENT_LOW_WATERMARKS,
parentPartition,
lowWatermark.getMillis());
dataClient.mutateRow(rowMutation);
}
/**
* @return stream of partitions currently being streamed by the beam job that have set a
* watermark.
*/
public ServerStream<Row> readFromMdTableStreamPartitionsWithWatermark() {
// We limit to the latest value per column.
Query query =
Query.create(tableId)
.prefix(getFullStreamPartitionPrefix())
.filter(
FILTERS
.chain()
.filter(FILTERS.limit().cellsPerColumn(1))
.filter(FILTERS.family().exactMatch(MetadataTableAdminDao.CF_WATERMARK))
.filter(
FILTERS.qualifier().exactMatch(MetadataTableAdminDao.QUALIFIER_DEFAULT)));
return dataClient.readRows(query);
}
/**
* Update the metadata for the rowKey. This helper adds necessary prefixes to the row key.
*
* @param rowKey row key of the row to update
* @param watermark watermark value to set for the cell
* @param currentToken continuation token to set for the cell
*/
private void writeToMdTableWatermarkHelper(
ByteString rowKey, Instant watermark, @Nullable ChangeStreamContinuationToken currentToken) {
RowMutation rowMutation =
RowMutation.create(tableId, rowKey)
.setCell(
MetadataTableAdminDao.CF_WATERMARK,
MetadataTableAdminDao.QUALIFIER_DEFAULT,
watermark.getMillis());
if (currentToken != null) {
rowMutation.setCell(
MetadataTableAdminDao.CF_CONTINUATION_TOKEN,
MetadataTableAdminDao.QUALIFIER_DEFAULT,
currentToken.getToken());
}
dataClient.mutateRow(rowMutation);
}
/**
* Update the metadata for the row key represented by the partition.
*
* @param partition forms the row key of the row to update
* @param watermark watermark value to set for the cell
* @param currentToken continuation token to set for the cell
*/
public void updateWatermark(
ByteStringRange partition,
Instant watermark,
@Nullable ChangeStreamContinuationToken currentToken) {
writeToMdTableWatermarkHelper(
convertPartitionToStreamPartitionRowKey(partition), watermark, currentToken);
}
/**
* Delete the row key represented by the partition. This represents that the partition will no
* longer be streamed.
*
* @param partition forms the row key of the row to delete
*/
public void deleteStreamPartitionRow(ByteStringRange partition) {
ByteString rowKey = convertPartitionToStreamPartitionRowKey(partition);
RowMutation rowMutation = RowMutation.create(tableId, rowKey).deleteRow();
dataClient.mutateRow(rowMutation);
}
/**
* Delete the row.
*
* @param rowKey row key of the row to delete
*/
public void deleteRowKey(ByteString rowKey) {
RowMutation rowMutation = RowMutation.create(tableId, rowKey).deleteRow();
dataClient.mutateRow(rowMutation);
}
/**
* Lock the partition in the metadata table for the DoFn streaming it. Only one DoFn is allowed to
* stream a specific partition at any time. Each DoFn has an uuid and will try to lock the
* partition at the very start of the stream. If another DoFn has already locked the partition
* (i.e. the uuid in the cell for the partition belongs to the DoFn), any future DoFn trying to
* lock the same partition will and terminate.
*
* @param partition form the row key in the metadata table to lock
* @param uuid id of the DoFn
* @return true if uuid holds the lock, otherwise false.
*/
public boolean lockPartition(ByteStringRange partition, String uuid) {
LOG.debug("Locking partition before processing stream");
ByteString rowKey = convertPartitionToStreamPartitionRowKey(partition);
Filter lockCellFilter =
FILTERS
.chain()
.filter(FILTERS.family().exactMatch(MetadataTableAdminDao.CF_LOCK))
.filter(FILTERS.qualifier().exactMatch(MetadataTableAdminDao.QUALIFIER_DEFAULT))
.filter(FILTERS.limit().cellsPerRow(1));
Row row = dataClient.readRow(tableId, rowKey, lockCellFilter);
// If the query returns non-null row, that means the lock is being held. Check if the owner is
// same as uuid.
if (row != null) {
return row.getCells().get(0).getValue().toStringUtf8().equals(uuid);
}
// We cannot check whether a cell is empty, We can check if the cell matches any value. If it
// does not, we perform the mutation to set the cell.
Mutation mutation =
Mutation.create()
.setCell(MetadataTableAdminDao.CF_LOCK, MetadataTableAdminDao.QUALIFIER_DEFAULT, uuid);
Filter matchAnyString =
FILTERS
.chain()
.filter(FILTERS.family().exactMatch(MetadataTableAdminDao.CF_LOCK))
.filter(FILTERS.qualifier().exactMatch(MetadataTableAdminDao.QUALIFIER_DEFAULT))
.filter(FILTERS.value().regex("\\C*"));
ConditionalRowMutation rowMutation =
ConditionalRowMutation.create(tableId, rowKey)
.condition(matchAnyString)
.otherwise(mutation);
return !dataClient.checkAndMutateRow(rowMutation);
}
/**
* Set the version number for DetectNewPartition. This value can be checked later to verify that
* the existing metadata table is compatible with current beam connector code.
*/
public void writeDetectNewPartitionVersion() {
RowMutation rowMutation =
RowMutation.create(tableId, getFullDetectNewPartition())
.setCell(
MetadataTableAdminDao.CF_VERSION,
MetadataTableAdminDao.QUALIFIER_DEFAULT,
MetadataTableAdminDao.CURRENT_METADATA_TABLE_VERSION);
dataClient.mutateRow(rowMutation);
}
/**
* Read and deserialize missing partition and how long they have been missing from the metadata
* table.
*
* @return deserialized missing partitions and duration.
*/
public HashMap<ByteStringRange, Long> readDetectNewPartitionMissingPartitions() {
@Nonnull HashMap<ByteStringRange, Long> missingPartitions = new HashMap<>();
Filter missingPartitionsFilter =
FILTERS
.chain()
.filter(FILTERS.family().exactMatch(MetadataTableAdminDao.CF_MISSING_PARTITIONS))
.filter(FILTERS.qualifier().exactMatch(MetadataTableAdminDao.QUALIFIER_DEFAULT))
.filter(FILTERS.limit().cellsPerColumn(1));
Row row = dataClient.readRow(tableId, getFullDetectNewPartition(), missingPartitionsFilter);
if (row == null
|| row.getCells(
MetadataTableAdminDao.CF_MISSING_PARTITIONS,
MetadataTableAdminDao.QUALIFIER_DEFAULT)
.isEmpty()) {
return missingPartitions;
}
ByteString serializedMissingPartition =
row.getCells(
MetadataTableAdminDao.CF_MISSING_PARTITIONS,
MetadataTableAdminDao.QUALIFIER_DEFAULT)
.get(0)
.getValue();
try {
missingPartitions = SerializationUtils.deserialize(serializedMissingPartition.toByteArray());
} catch (SerializationException | NullPointerException exception) {
LOG.warn("Failed to deserialize missingPartitions: {}", exception.toString());
}
return missingPartitions;
}
/**
* Write to metadata table serialized missing partitions and how long they have been missing.
*
* @param missingPartitionDurations missing partitions and duration.
*/
public void writeDetectNewPartitionMissingPartitions(
HashMap<ByteStringRange, Long> missingPartitionDurations) {
byte[] serializedMissingPartition = SerializationUtils.serialize(missingPartitionDurations);
RowMutation rowMutation =
RowMutation.create(tableId, getFullDetectNewPartition())
.setCell(
MetadataTableAdminDao.CF_MISSING_PARTITIONS,
ByteString.copyFromUtf8(MetadataTableAdminDao.QUALIFIER_DEFAULT),
ByteString.copyFrom(serializedMissingPartition));
dataClient.mutateRow(rowMutation);
}
}
|
package ru.iidf.jira.reports.resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ru.iidf.jira.reports.common.UTF8Control;
import java.util.Locale;
import java.util.ResourceBundle;
public final class Info {
private static final Logger LOG = LoggerFactory.getLogger(Info.class);
private static final ResourceBundle VALUES = ResourceBundle.getBundle(Info.class.getName(), new UTF8Control());
public static final String ESTIMATED = "estimated";
public static final String FACT = "fact";
public static final String TOTAL = "total";
public static final String COST = "cost";
public static final String TASKS = "tasks";
public static final String ERROR = "error";
public static String getValueByCode(String code) {
return getValue(code, code);
}
protected static String getValue(String string, String defaultValue) {
try {
return Info.VALUES.getString(string);
} catch (Exception e) {
LOG.error("Could not find resource with name {}", string);
return defaultValue;
}
}
}
|
package fr.mb.volontario.business.impl;
import fr.mb.volontario.business.contract.AssociationManager;
import fr.mb.volontario.dao.contract.AssociationDAO;
import fr.mb.volontario.model.bean.Association;
import fr.mb.volontario.model.exception.FunctionalException;
import fr.mb.volontario.model.exception.NotFoundException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
@Service
public class AssociationManagerImpl implements AssociationManager {
@Autowired
AssociationDAO associationDAO;
@Override
public Association getAssociation(Integer idAssociation) throws FunctionalException, NotFoundException {
Assert.notNull(idAssociation, "l'id est obligatoire");
Association association = associationDAO.findById(idAssociation).orElse(null);
if (association==null) throw new NotFoundException("l'association n'existe pas");
else return association;
}
@Override
public Association saveAssociation(Association association) {
Assert.notNull(association, "L'association est obligaroire");
return associationDAO.save(association);
}
}
|
package foodchain.strategies;
import foodchain.products.Product;
import static foodchain.parties.Data.*;
/**
* Strategy to initialize characteristics of Apple.
*/
public class AppleStrategy extends Strategy {
/**
* Constructs strategy.
* @param product the product for strategy.
*/
public AppleStrategy(Product product) {
super(product);
}
/**
* Init strategy for storage parametres.
*/
@Override
public void initStorageParametres() {
System.out.println("Store apple...");
product.setStorageParameters(APPLE_STORAGE_TIME, APPLE_STORAGE_TEMPERATURE,
APPLE_STORAGE_HUMIDITY);
}
/**
* Init strategy for seller parametres.
*/
@Override
public void initSellerParametres() {
System.out.println("Sell apple...");
product.setSellerParameters(APPLE_PACKAGING, APPLE_SELLING_PLACE);
}
/**
* Init strategy for processor parametres.
*/
@Override
public void initProcessorParametres() {
System.out.println("Process apple...");
product.setProcessorParameters(APPLE_PROCESSING_TEMPERATURE, APPLE_CHEMICAL_PROCESSING_DEGREE);
}
}
|
/**
*
* this package has the panels / button that can interact with user. So we have :
* <ol>
* <li>{@link nl.rug.oop.flaps.aircraft_editor.view.panels.aircraft_info.interaction_panels.InteractionPanel}</li>
* <li>{@link nl.rug.oop.flaps.aircraft_editor.view.panels.aircraft_info.interaction_panels.FuelConfigPanel}</li>
* <li>{@link nl.rug.oop.flaps.aircraft_editor.view.panels.aircraft_info.interaction_panels.CargoConfigPanel}</li>
* <li>{@link nl.rug.oop.flaps.aircraft_editor.view.panels.aircraft_info.interaction_panels.PassengersConfigPanel}</li>
* <li>{@link nl.rug.oop.flaps.aircraft_editor.view.panels.aircraft_info.interaction_panels.DepartButton}</li>
* </ol>
*
* */
package nl.rug.oop.flaps.aircraft_editor.view.panels.aircraft_info.interaction_panels;
|
package com.wt.jiaduo.controller.pojovalid;
// Generated 2018-3-31 10:29:38 by Hibernate Tools 5.2.8.Final
import java.util.Date;
import javax.validation.constraints.NotNull;
import org.springframework.format.annotation.DateTimeFormat;
/**
* XiaomaiCongaibingTianjianzishengmaimiao generated by hbm2java
*/
public class XiaomaiCongaibingTianjianzishengmaimiaoUpdateValid implements java.io.Serializable {
@NotNull(message="id不能为空")
private Integer id;
@DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss")
private Date dateTime;
private String person;
private String place;
private String pinzhong;
private String diaochazhushu;
private String fabingzhushu;
private String bingzhulv;
private String remark;
private Integer userId;
private String userName;
private String longitude;
private String latitude;
public XiaomaiCongaibingTianjianzishengmaimiaoUpdateValid() {
}
public XiaomaiCongaibingTianjianzishengmaimiaoUpdateValid(Date dateTime, String person, String place, String pinzhong,
String diaochazhushu, String fabingzhushu, String bingzhulv, String remark, Integer userId, String userName,
String longitude, String latitude) {
this.dateTime = dateTime;
this.person = person;
this.place = place;
this.pinzhong = pinzhong;
this.diaochazhushu = diaochazhushu;
this.fabingzhushu = fabingzhushu;
this.bingzhulv = bingzhulv;
this.remark = remark;
this.userId = userId;
this.userName = userName;
this.longitude = longitude;
this.latitude = latitude;
}
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
public Date getDateTime() {
return this.dateTime;
}
public void setDateTime(Date dateTime) {
this.dateTime = dateTime;
}
public String getPerson() {
return this.person;
}
public void setPerson(String person) {
this.person = person;
}
public String getPlace() {
return this.place;
}
public void setPlace(String place) {
this.place = place;
}
public String getPinzhong() {
return this.pinzhong;
}
public void setPinzhong(String pinzhong) {
this.pinzhong = pinzhong;
}
public String getDiaochazhushu() {
return this.diaochazhushu;
}
public void setDiaochazhushu(String diaochazhushu) {
this.diaochazhushu = diaochazhushu;
}
public String getFabingzhushu() {
return this.fabingzhushu;
}
public void setFabingzhushu(String fabingzhushu) {
this.fabingzhushu = fabingzhushu;
}
public String getBingzhulv() {
return this.bingzhulv;
}
public void setBingzhulv(String bingzhulv) {
this.bingzhulv = bingzhulv;
}
public String getRemark() {
return this.remark;
}
public void setRemark(String remark) {
this.remark = remark;
}
public Integer getUserId() {
return this.userId;
}
public void setUserId(Integer userId) {
this.userId = userId;
}
public String getUserName() {
return this.userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getLongitude() {
return this.longitude;
}
public void setLongitude(String longitude) {
this.longitude = longitude;
}
public String getLatitude() {
return this.latitude;
}
public void setLatitude(String latitude) {
this.latitude = latitude;
}
}
|
package br.com.jdrmservices.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;
import br.com.jdrmservices.model.ItemContrato;
import br.com.jdrmservices.session.TabelaItensContrato;
import static br.com.jdrmservices.util.Constants.VIEW_ITEM_CONTRATO;
@RestController
@RequestMapping("/itenscontrato")
public class ItensContratoController {
@Autowired
private TabelaItensContrato tabelaItensContrato;
@PostMapping
public ModelAndView adicionarItem(ItemContrato itemContrato) {
ModelAndView mv = new ModelAndView(VIEW_ITEM_CONTRATO);
tabelaItensContrato.adicionarItem(itemContrato);
mv.addObject("itens", tabelaItensContrato.getItens());
return mv;
}
@DeleteMapping("/{index}")
public ModelAndView removerItem(@PathVariable int index) {
ModelAndView mv = new ModelAndView(VIEW_ITEM_CONTRATO);
tabelaItensContrato.removerItem(index);
mv.addObject("itens", tabelaItensContrato.getItens());
return mv;
}
}
|
package com.lec.ex4_threadN_objectN;
public class ThreadEx2TestMain { //thread로부터 상속받음
public static void main(String[] args) {
//t1.run() 수행하는 thread A 생성 / t1.num
Thread t1 = new ThreadEx2("A"); // 내가 매개변수 있는 생성자 안만들어놨다 . 쓰고 싶으면 그전에 매개변수 있는 생정자 만들어놔야
//t1.setName("A");
//t2.run() 수행하는 thread B 생성 / t2.num
Thread t2 = new ThreadEx2("B");
t1.start();
t2.start(); //************왜super를 해도 껴들 수 있는지?********88
}
}
|
package com.bjstudio.blog.login.RepositoryTest;
import java.util.Optional;
import com.bjstudio.blog.login.model.Member;
import com.bjstudio.blog.login.repository.MemberRepository;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.transaction.annotation.Transactional;
import lombok.extern.java.Log;
@SpringBootTest
@RunWith(SpringRunner.class)
@Log
@Transactional
public class MemberRepositoryTest {
@Autowired
private MemberRepository memberRepository;
private final String email = "test@email.com";
private final String firstName = "firstName";
private final String lastName = "lastName";
@Test
public void findByEmailTest() {
log.info("Test findByEmail");
Optional<Member> members = this.memberRepository.findByEmail(email);
members.ifPresent(user -> log.info("user: " + user));
}
@Test
public void findByFirstNameContainingOrderByIdDescTest() {
log.info("Test findByFirstNameContainingOrderByIdDesc");
Optional<Member> members = this.memberRepository.findByFirstNameContainingOrderByIdDesc(firstName);
members.ifPresent(user -> log.info("user: " + user));
}
@Test
public void findByLastNameContainingOrderByIdDescTest() {
log.info("Test findByLastNameContainingOrderByIdDesc");
Optional<Member> members = this.memberRepository.findByLastNameContainingOrderByIdDesc(lastName);
members.ifPresent(user -> log.info("user: " + user));
}
}
|
package de.nschilling.awssslchecker;
import java.util.ArrayList;
import java.util.List;
import com.amazonaws.services.sns.AmazonSNS;
import com.amazonaws.services.sns.AmazonSNSClient;
import com.amazonaws.services.sns.model.PublishRequest;
import com.amazonaws.services.sns.model.PublishResult;
public class SnsServices {
HelpServices helpServices = new HelpServices();
@SuppressWarnings("unused")
protected void publishToSNS(String message) {
List<String> envVariablesToCheck = new ArrayList<>();
envVariablesToCheck.add("sns_topic_arn");
if (helpServices.areEnvVariablesMissing(envVariablesToCheck)) {
System.out.println("publishToSNS: The environmental variable (" + envVariablesToCheck.toString()
+ ") is missing. Not able to publish to SNS.");
throw new RuntimeException("publishToSNS: The environmental variable (" + envVariablesToCheck.toString()
+ ") is missing. Not able to publish to SNS.");
}
String sns_topic_arn = System.getenv("sns_topic_arn");
AmazonSNS snsClient = AmazonSNSClient.builder().build();
PublishRequest publishRequest = new PublishRequest();
publishRequest.setSubject("AWS SSL Check - certificate expired");
publishRequest.setMessage(message);
publishRequest.setTopicArn(sns_topic_arn);
PublishResult publishResult = snsClient.publish(publishRequest);
}
}
|
package Test;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
/**
* Created by skyll on 07.02.2017.
*/
public class Request {
public static void main(String[] args) throws IOException {
String request = "http://vk.com";
}
}
|
package sample;
public class Yobidasi {
private static int TEST = 26;
//private static int TEST2 = 5;
public static void main(String[] args) {
Modoriti modoriti = new Modoriti();
String str ;
// int str2 ;
str = modoriti.keisan(TEST);
System.out.println("入力した数は" + str );
// int k ;
// str2 = modoriti.calculate(TEST2);
}
}
|
package com.spbsu.flamestream.example.benchmark;
/**
* User: Artem
* Date: 28.12.2017
*/
public interface GraphDeployer extends AutoCloseable {
void deploy();
@Override
void close();
}
|
package com.tencent.mm.plugin.account.friend.ui;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import com.tencent.mm.ab.e;
import com.tencent.mm.ab.l;
import com.tencent.mm.plugin.account.a.j;
import com.tencent.mm.plugin.account.friend.a.ah;
import com.tencent.mm.sdk.platformtools.x;
import com.tencent.mm.ui.base.h;
public final class g implements e {
private Context context;
private ProgressDialog dId;
a eNf;
private boolean eNg = true;
String eNh = "";
public g(Context context, a aVar) {
this.context = context;
this.eNf = aVar;
this.eNg = true;
}
public g(Context context, a aVar, byte b) {
this.context = context;
this.eNf = aVar;
this.eNg = false;
}
public final void g(int[] iArr) {
com.tencent.mm.kernel.g.DF().a(116, this);
final ah ahVar = new ah(iArr);
com.tencent.mm.kernel.g.DF().a(ahVar, 0);
if (this.eNg) {
Context context = this.context;
this.context.getString(j.inviteqqfriends_title);
this.dId = h.a(context, this.context.getString(j.inviteqqfriends_inviting), true, new OnCancelListener() {
public final void onCancel(DialogInterface dialogInterface) {
com.tencent.mm.kernel.g.DF().c(ahVar);
g.this.eNf.c(false, g.this.eNh);
}
});
}
}
public final void a(int i, int i2, String str, l lVar) {
if (lVar.getType() == 116) {
if (this.dId != null) {
this.dId.dismiss();
this.dId = null;
}
com.tencent.mm.kernel.g.DF().b(116, this);
if (i == 0 && i2 == 0) {
x.i("MicroMsg.SendInviteEmail", "dealSendInviteEmailSuccess");
if (this.eNg) {
h.a(this.context, j.inviteqqfriends_invite_success, j.app_tip, new 2(this));
return;
} else {
this.eNf.c(true, this.eNh);
return;
}
}
x.i("MicroMsg.SendInviteEmail", "dealSendInviteEmailFail");
this.eNf.c(false, this.eNh);
}
}
}
|
package Manager;
import File.File;
import Id.Id;
public interface FileManager {
File getFile(Id<File> fileId);
File newFile(Id<File> fileId);
File registerFile(File file);
int getSize();
Id<FileManager> getId();
}
|
package com.systex.sysgateii.ratesvr.dao;
import java.io.File;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.apache.commons.configuration2.ConfigurationMap;
import org.apache.commons.configuration2.XMLConfiguration;
import org.apache.commons.configuration2.builder.ReloadingFileBasedConfigurationBuilder;
import org.apache.commons.configuration2.builder.fluent.Parameters;
import org.apache.commons.configuration2.ex.ConfigurationException;
import org.apache.commons.configuration2.tree.DefaultExpressionEngine;
import org.apache.commons.configuration2.tree.DefaultExpressionEngineSymbols;
import org.apache.commons.lang3.StringUtils;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import com.systex.sysgateii.util.LogUtil;
/*
* GwCfgDao
* Configuration object process (file)
*
* MatsudairaSyuMe
* Ver 1.0
* 20190730
*/
public class GwCfgDao {
private static Logger log = LoggerFactory.getLogger(GwCfgDao.class);
public static final String ENCODING = "UTF-8";
public static final String XMLPATH = "rateservice.xml";
private String selurl;
private String seluser;
private String selpass;
private String auid;
private ResultSet selectresult = null;
private Connection selconn = null;
public GwCfgDao() throws Throwable {
log.info(" new GwCfgDao={}", XMLPATH);
readXml();
getDB2Connection();
}
public void readXml() {
log.info("xmlpath={}", XMLPATH);
File xmlfile = new File(XMLPATH);
SAXReader reader = new SAXReader();
Document doc;
try {
doc = reader.read(xmlfile);
Element root = doc.getRootElement();
Element foo;
for (java.util.Iterator<Element> i = root.elementIterator("Resource"); i.hasNext();) {
foo = i.next();
// log.info("Resource ==>{}", foo);
setSelurl(foo.attribute("url").getStringValue());
setSelpass(foo.attribute("using").getStringValue()); //20230110 change from password to using
setSeluser(foo.attribute("username").getStringValue());
}
Parameters params = new Parameters();
ReloadingFileBasedConfigurationBuilder<XMLConfiguration> builder = new ReloadingFileBasedConfigurationBuilder<XMLConfiguration>(XMLConfiguration.class)
.configure(params.fileBased().setFile(new File(XMLPATH)));
DefaultExpressionEngine engine = new DefaultExpressionEngine(DefaultExpressionEngineSymbols.DEFAULT_SYMBOLS);
builder.getConfiguration().setExpressionEngine(engine);
Map<Object, Object> cfg = new ConfigurationMap(builder.getConfiguration());
cfg.entrySet();
for (@SuppressWarnings("rawtypes")
Map.Entry entry : cfg.entrySet()) {
if(entry.getKey().equals("system.auid")) {
setAuid(entry.getValue().toString());
}
}
if(StringUtils.isBlank(getAuid())) {
setAuid("2");
}
} catch (DocumentException e) {
log.info(e.getMessage());
} catch (ConfigurationException e) {
log.info(e.getMessage());
}
}
public List<Map<String, Object>> findAllMemberNodes(int sysFlag, int isEnable) {
List<Map<String, Object>> list = null;
log.info("read AllMemberNodes sysFlag={} isEnable={}", sysFlag, isEnable);
return list;
}
public void getDB2Connection() throws Exception {
Class.forName("com.ibm.db2.jcc.DB2Driver");
log.info("Driver Loaded.");
setSelconn(DriverManager.getConnection(getSelurl(), getSeluser(), getSelpass()));
}
public void CloseConnect() throws Exception {
try {
if (selconn != null)
selconn.close();
} catch (SQLException se) {
log.error("CloseConnect():{}", se.getMessage());
} // end finally try
}
public List<String> SELECTTB_AUDEVPRM(String DEVTPE, String BRWS) throws Exception {
List<String> rtnVal = new ArrayList<String>();
try {
java.sql.Statement stmt = selconn.createStatement();
selectresult = ((java.sql.Statement) stmt).executeQuery(
"SELECT IP FROM TB_AUDEVPRM where DEVTPE = " + DEVTPE + " and BRWS like '" + BRWS + "%'");
if (selectresult != null) {
while (selectresult.next()) {
rtnVal.add(selectresult.getString("IP"));
}
}
} catch (Exception e) {
log.info("error : {}", e.toString());
} finally {
CloseConnect();
}
log.info("return TBSDY=[{}]", LogUtil.vaildLog(rtnVal.toString()));
return rtnVal;
}
// 10/14 SUN uodate
public List<Map<String, String>> SELECTALLTB_AUDEVPRM() throws Exception {
String selectsql = "SELECT IP,BRWS FROM TB_AUDEVPRM WHERE DEVTPE IN (0,1)";
List<Map<String, String>> rtnVal = new ArrayList<Map<String, String>>();
try {
PreparedStatement selSQL = selconn.prepareStatement(selectsql);
selectresult = selSQL.executeQuery();
if (selectresult != null) {
while (selectresult.next()) {
Map<String, String> setrtn = new HashMap<String, String>();
setrtn.put("boards.board.ip", selectresult.getString("IP"));
setrtn.put("boards.board.brno", selectresult.getString("BRWS"));
rtnVal.add(setrtn);
}
}
} catch (Exception e) {
log.info("error : {}", e.toString());
} finally {
CloseConnect();
}
log.info("return TBSDY=[{}]", LogUtil.vaildLog(rtnVal.toString()));
return rtnVal;
}
// 10/14 SUN uodate
public void UPDATETB_AUDEVSTS(String IP, String CURSTUS) throws Exception {
String selectsql = "SELECT * FROM TB_AUDEVSTS WHERE IP = ?";
String updatesql = "update TB_AUDEVSTS set CURSTUS = ?" + ",VERSION = ?" + ",LASTUPDATE = ?" + ",MODIFIER = ?" + " where ip = ?"; //20220713 add MODIFIER = SYSTEM
Timestamp ts = new Timestamp(System.currentTimeMillis());
String timestamp = "";
DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
timestamp = sdf.format(ts);
try {
PreparedStatement selSQL = selconn.prepareStatement(selectsql);
selSQL.setString(1, IP);
selectresult = selSQL.executeQuery();
if (selectresult.next()) {
String verStr = "";
verStr = String.valueOf((Integer.parseInt(selectresult.getString("VERSION")) + 1) % 10000); //20220718 MatsudairaSyuMe max 0~9999
selSQL = selconn.prepareStatement(updatesql);
selSQL.setString(1, CURSTUS);
selSQL.setString(2, verStr);
selSQL.setString(3, timestamp);
selSQL.setString(4, "SYSTEM"); //20220713 add MODIFIER = SYSTEM
selSQL.setString(5, IP); //20220713 change to 5 for MODIFIER = SYSTEM
selSQL.executeUpdate();
} else {
INSERTTB_AUDEVSTS(IP, CURSTUS);
}
selconn.commit(); //20220706 MatsudairaSyume
} catch (Exception e) {
log.info("error : {}", e.toString());
} finally {
CloseConnect();
}
}
public void INSERTTB_AUDEVSTS(String IP, String CURSTUS) throws Exception {
String selectsql = "SELECT * FROM TB_AUDEVPRM where IP = ?";
String insertsql = "insert into TB_AUDEVSTS (BRWS,IP,PORT,SVRID,SYSIP,SYSPORT,ACTPAS,DEVTPE,CURSTUS,VERSION,CREATOR,CREATETIME,LASTUPDATE,MODIFIER) VALUES "
+ "(?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
Timestamp ts = new Timestamp(System.currentTimeMillis());
String timestamp = "";
DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
timestamp = sdf.format(ts);
try {
PreparedStatement selSQL = selconn.prepareStatement(selectsql);
log.info(" IP={}", LogUtil.vaildLog(IP));
selSQL.setString(1, IP);
selectresult = selSQL.executeQuery();
log.info(" selectresult={}", LogUtil.vaildLog(selectresult.toString()));
if (selectresult.next()) {
selSQL = selconn.prepareStatement(insertsql);
log.info(" BRWS={}", LogUtil.vaildLog(selectresult.getString("BRWS")));
selSQL.setString(1, selectresult.getString("BRWS"));
selSQL.setString(2, IP);
log.info(" PORT={}", LogUtil.vaildLog(selectresult.getString("PORT")));
selSQL.setString(3, selectresult.getString("PORT"));
log.info(" SVRID={}", LogUtil.vaildLog(selectresult.getString("SVRID")));
selSQL.setString(4, selectresult.getString("SVRID"));
selSQL.setString(5, IP);
selSQL.setString(6, selectresult.getString("PORT"));
log.info(" ACTPAS={}", LogUtil.vaildLog(selectresult.getString("ACTPAS")));
selSQL.setString(7, selectresult.getString("ACTPAS"));
log.info(" DEVTPE={}", LogUtil.vaildLog(selectresult.getString("DEVTPE")));
selSQL.setString(8, selectresult.getString("DEVTPE"));
log.info(" CURSTUS={}", LogUtil.vaildLog(CURSTUS));
selSQL.setString(9, CURSTUS);
selSQL.setString(10, "1");
selSQL.setString(11, "SYSTEM"); //20220713 change to SYSTEM
log.info(" DEVTPE={}", LogUtil.vaildLog(timestamp));
selSQL.setString(12, timestamp);
selSQL.setString(13, timestamp);
selSQL.setString(14, "SYSTEM"); //20220713 change to SYSTEM
selSQL.executeUpdate();
}
} catch (SQLException e) {
log.info("error : {}", e.toString());
} finally {
CloseConnect();
}
}
public String SelectTB_AUFASPRM() throws Exception {
String rtnVal ="";
try {
java.sql.Statement stmt = selconn.createStatement();
selectresult = ((java.sql.Statement) stmt).executeQuery("SELECT CONNPRM FROM TB_AUFASPRM where AUID = "+getAuid());
if (selectresult != null) {
while (selectresult.next()) {
rtnVal = selectresult.getString("CONNPRM");
}
}
} catch (Exception e) {
log.info("error : {}", e.toString());
} finally {
CloseConnect();
}
log.info("return TBSDY=[{}]", LogUtil.vaildLog(rtnVal));
return rtnVal;
}
public String getSelurl() {
return selurl;
}
public void setSelurl(String selurl) {
this.selurl = selurl;
}
public String getSeluser() {
return seluser;
}
public void setSeluser(String seluser) {
this.seluser = seluser;
}
public String getSelpass() {
return selpass;
}
public void setSelpass(String selpass) {
this.selpass = selpass;
}
public Connection getSelconn() {
return selconn;
}
public void setSelconn(Connection selconn) {
this.selconn = selconn;
}
public String getAuid() {
return auid;
}
public void setAuid(String auid) {
this.auid = auid;
}
}
|
package com.programmers.level3;
/** [시저 암호]
* 어떤 문장의 각 알파벳을 일정한 거리만큼 밀어서 다른 알파벳으로 바꾸는 암호화 방식을 시저 암호라고 합니다.
* A를 3만큼 밀면 D가 되고 z를 1만큼 밀면 a가 됩니다. 공백은 수정하지 않습니다.
* 보낼 문자열 s와 얼마나 밀지 알려주는 n을 입력받아 암호문을 만드는 caesar 함수를 완성해 보세요.
* “a B z”,4를 입력받았다면 “e F d”를 리턴합니다.
*/
public class Caesar {
String caesar(String s, int n) {
/*
String result = "";
// 함수를 완성하세요.
return result;
*/
n = n % 26;
String result = "";
char[] temp = s.toCharArray();
for (int i = 0; i < temp.length; i++) {
if ('a' <= temp[i] && temp[i] <= 'z') {
temp[i] = (char) ((temp[i] + n) > 'z' ? (temp[i] + n - 1) % 'z' + 'a' : temp[i] + n);
}
else if('A' <= temp[i] && temp[i] <= 'Z') {
temp[i] = (char) ((temp[i] + n) > 'Z' ? (temp[i] + n - 1) % 'Z' + 'A' : temp[i] + n);
}
result += temp[i];
}
return result;
}
public static void main(String[] args) {
Caesar c = new Caesar();
System.out.println("s는 'a B z', n은 4인 경우: " + c.caesar("a B z", 4));
}
}
|
package com.jim.multipos.ui.settings.accounts;
import com.jim.multipos.core.Presenter;
import com.jim.multipos.data.db.model.Account;
import com.jim.multipos.ui.settings.accounts.model.AccountItem;
public interface AccountSettingsPresenter extends Presenter {
void initAccounts();
void saveChanges(AccountItem account, int position);
void addAccount(String name, boolean checked);
}
|
package sec.project.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import sec.project.domain.Siteuser;
import sec.project.repository.SiteuserRepository;
/**
*
* @author iisti
*/
@Controller
public class SiteuserController {
@Autowired
private SiteuserRepository siteuserRepository;
@Autowired
private PasswordEncoder passwordEncoder;
@RequestMapping(value = "/users", method = RequestMethod.GET)
public String getUsers(Model model) {
model.addAttribute("users", siteuserRepository.findAll());
return "users";
}
@RequestMapping(value = "/locked", method = RequestMethod.GET)
public String locked() {
return "locked";
}
@RequestMapping(value = "/create-user", method = RequestMethod.GET)
public String loadForm() {
return "create-user";
}
@RequestMapping(value = "/create-user", method = RequestMethod.POST)
public String submitForm(@RequestParam String username, @RequestParam String psw, @RequestParam(value="admin", required = false )boolean admin) {
siteuserRepository.save(new Siteuser(username, passwordEncoder.encode(psw), admin));
return "created";
}
@RequestMapping(value = "/created", method = RequestMethod.GET)
public String createdUser() {
return "created";
}
}
|
package com.cyberway.spring_boot_starter_cqrs.anotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import com.cyberway.spring_boot_starter_cqrs.config.CQRStarterAutoConfiguration;
/**
* Indicates that an annotated class is a "Domain event handler". Such classes
* are considered as listener handler for auto-detection
*
*
*
* @author xnq
* @see CQRStarterAutoConfiguration
*/
@Target({ ElementType.METHOD, ElementType.TYPE })
@Documented
@Retention(RetentionPolicy.RUNTIME)
public @interface EventHandle {
String[] value() default {};
}
|
package net.packet.client;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import java.nio.ByteOrder;
import net.ClientOpCode;
import net.packet.MaplePacket;
public class MapleDropMesoPacket extends MaplePacket {
public static int unk = 57140058;
public MapleDropMesoPacket(int amount) {
super(ClientOpCode.MESO_DROP.getCode());
ByteBuf buf = Unpooled.buffer().order(ByteOrder.LITTLE_ENDIAN);
buf.writeInt(unk += 5000);
buf.writeInt(amount);
buf = buf.capacity(buf.writerIndex());
setPayload(buf);
}
}
|
package com.darkania.darkers.comandos;
import java.util.ArrayList;
import java.util.List;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import com.darkania.darkers.extras.Permisos;
public class Renombrar implements CommandExecutor{
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args){
if (cmd.getName().equalsIgnoreCase("renombrar") && sender instanceof Player){
Player p = (Player) sender;
if (Permisos.tiene(p, "Darkers.staff")){
if (args.length == 0){
p.sendMessage(ChatColor.RED+"Uso: /renombrar [Nombre]");
return true;
}
@SuppressWarnings("deprecation")
ItemStack item = p.getItemInHand();
if ((item.getType() == Material.AIR) || (item == null)){
p.sendMessage(ChatColor.RED+"Necesitas tener seleccionado un item");
return true;
}
ItemMeta Item = item.getItemMeta();
String Nombre = "";
for (int i = 0; i <= args.length - 1; i++)
{
Nombre = Nombre + args[i] + "";
}
Nombre = ChatColor.translateAlternateColorCodes('&', Nombre);
Item.setDisplayName(Nombre);
item.setItemMeta(Item);
List<String> lore = new ArrayList<String>();
lore.add(ChatColor.GREEN+"Propiedad de "+p.getName());
Item.setLore(lore);
item.setItemMeta(Item);
sender.sendMessage(ChatColor.GOLD+"¡Item renombrado con exito!");
}
if (!Permisos.tiene(p, "Darkers.staff")){
p.sendMessage(ChatColor.translateAlternateColorCodes('&', Bukkit.getPluginManager().getPlugin("Darkers").getConfig().getString("General.SinPermisos")));
return true;
}
}
if (!(sender instanceof Player)){
sender.sendMessage(ChatColor.GREEN+"[Darkers] "+ChatColor.RED+"No utilizable desde la consola");
return true;
}
return false;
}
}
|
/* *****************************************************************************
* Name: Alan Turing
* Coursera User ID: 123456
* Last modified: 1/1/2019
**************************************************************************** */
public class ColorHSB {
private final int hue;
private final int sat;
private final int bright;
public ColorHSB(int h, int s, int b) {
if (h >= 0 && h <= 359) {
hue = h;
}
else {
throw new IllegalArgumentException("Value not in big range");
}
if (s >= 0 && s <= 100) {
sat = s;
}
else {
throw new IllegalArgumentException("Value not in big range");
}
if (b >= 0 && b <= 100) {
bright = b;
}
else {
throw new IllegalArgumentException("Value not in big range");
}
}
public String toString() {
return "(" + hue + ", " + sat + ", " + bright + ")";
}
public boolean isGrayscale() {
if (bright == 0 || sat == 0) {
return true;
}
return false;
}
public int distanceSquaredTo(ColorHSB that) {
if (that == null) {
throw new IllegalArgumentException("argument is null");
}
else {
int num =
(int) (Math.min(Math.pow((hue - that.hue), 2),
Math.pow((360 - Math.abs(hue - that.hue)), 2)))
+ ((sat - that.sat) * (sat - that.sat)) + ((bright - that.bright) * (
bright - that.bright));
return num;
}
}
public static void main(String[] args) {
int h = Integer.parseInt(args[0]);
int s = Integer.parseInt(args[1]);
int b = Integer.parseInt(args[2]);
ColorHSB a = new ColorHSB(h, s, b);
int min = (int) Double.POSITIVE_INFINITY;
String name = "";
String o = "";
while (!StdIn.isEmpty()) {
String S = StdIn.readString();
int hu = StdIn.readInt();
int sa = StdIn.readInt();
int br = StdIn.readInt();
ColorHSB that = new ColorHSB(hu, sa, br);
if (that.distanceSquaredTo(a) < min) {
min = that.distanceSquaredTo(a);
name = S;
o = that.toString();
}
}
System.out.println(name + " " + o);
}
}
|
package com.smxknfie.springcloud.netflix.eureka.move.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
/**
* @author smxknife
* 2018/9/5
*/
@RestController
@RequestMapping("/move")
public class IndexController {
@Autowired
RestTemplate restTemplate;
@GetMapping("/user")
public Object getUser() {
return restTemplate.getForObject("http://user-service/user", String.class);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.