text
stringlengths
10
2.72M
package org.libreoffice; import android.graphics.Bitmap; import android.graphics.PointF; import android.os.Environment; import android.util.Log; import android.view.KeyEvent; import org.libreoffice.kit.DirectBufferAllocator; import org.libreoffice.kit.Document; import org.libreoffice.kit.LibreOfficeKit; import org.libreoffice.kit.Office; import org.mozilla.gecko.gfx.BufferedCairoImage; import org.mozilla.gecko.gfx.CairoImage; import org.mozilla.gecko.gfx.GeckoLayerClient; import org.mozilla.gecko.gfx.IntSize; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.nio.ByteBuffer; import java.util.ArrayList; /** * Created by 辉 on 2017/1/10. */ public class MainLOKitTileProvider implements TileProvider { private static final String LOGTAG = MainLOKitTileProvider.class.getSimpleName(); private static int TILE_SIZE = 256; private final GeckoLayerClient mLayerClient; private final float mTileWidth; private final float mTileHeight; private final String mInputFile; private Office mOffice; private Document mDocument; private boolean mIsReady = false; private float mDPI; private float mWidthTwip; private float mHeightTwip; private int mRenderWidth; private int mRenderHeight; private Document.MessageCallback mMessageCallback; private long objectCreationTime = System.currentTimeMillis(); /** * Initialize LOKit and load the document. * @param layerClient - layerclient implementation * @param messageCallback - callback for messages retrieved from LOKit * @param input - input path of the document */ public MainLOKitTileProvider(GeckoLayerClient layerClient, Document.MessageCallback messageCallback, String input) { mLayerClient = layerClient; mMessageCallback = messageCallback; mDPI = MainLOKitShell.getDpi(); mTileWidth = pixelToTwip(TILE_SIZE, mDPI); mTileHeight = pixelToTwip(TILE_SIZE, mDPI); LibreOfficeKit.putenv("SAL_LOG=+WARN+INFO"); MainLibreOfficeKit.init(MainOffice.mContext); mOffice = new Office(LibreOfficeKit.getLibreOfficeKitHandle()); mInputFile = input; Log.i(LOGTAG, "====> Loading file '" + input + "'"); mDocument = mOffice.documentLoad(input); if (mDocument == null) { Log.i(LOGTAG, "====> mOffice.documentLoad() returned null, trying to restart 'Office' and loading again"); mOffice.destroy(); Log.i(LOGTAG, "====> mOffice.destroy() done"); ByteBuffer handle = LibreOfficeKit.getLibreOfficeKitHandle(); Log.i(LOGTAG, "====> getLibreOfficeKitHandle() = " + handle); mOffice = new Office(handle); Log.i(LOGTAG, "====> new Office created"); mDocument = mOffice.documentLoad(input); } Log.i(LOGTAG, "====> mDocument = " + mDocument); if (mDocument != null) mDocument.initializeForRendering(); if (checkDocument()) { postLoad(); mIsReady = true; } else { mIsReady = false; } } public MainLOKitTileProvider(GeckoLayerClient layerClient, Document.MessageCallback messageCallback, String input, int renderWidth, int renderHeight) { mLayerClient = layerClient; mMessageCallback = messageCallback; mDPI = MainLOKitShell.getDpi(); mTileWidth = pixelToTwip(TILE_SIZE, mDPI); mTileHeight = pixelToTwip(TILE_SIZE, mDPI); mRenderHeight = renderHeight; mRenderWidth = renderWidth; LibreOfficeKit.putenv("SAL_LOG=+WARN+INFO"); MainLibreOfficeKit.init(MainOffice.mContext); mOffice = new Office(LibreOfficeKit.getLibreOfficeKitHandle()); mInputFile = input; Log.i(LOGTAG, "====> Loading file '" + input + "'"); mDocument = mOffice.documentLoad(input); if (mDocument == null) { Log.i(LOGTAG, "====> mOffice.documentLoad() returned null, trying to restart 'Office' and loading again"); mOffice.destroy(); Log.i(LOGTAG, "====> mOffice.destroy() done"); ByteBuffer handle = LibreOfficeKit.getLibreOfficeKitHandle(); Log.i(LOGTAG, "====> getLibreOfficeKitHandle() = " + handle); mOffice = new Office(handle); Log.i(LOGTAG, "====> new Office created"); mDocument = mOffice.documentLoad(input); } Log.i(LOGTAG, "====> mDocument = " + mDocument); if (mDocument != null) mDocument.initializeForRendering(); if (checkDocument()) { postLoad(); mIsReady = true; } else { mIsReady = false; } } /** * Triggered after the document is loaded. */ private void postLoad() { mDocument.setMessageCallback(mMessageCallback); int parts = mDocument.getParts(); Log.i(LOGTAG, "Document parts: " + parts); // LibreOfficeMainActivity.mAppContext.getDocumentPartView().clear(); // Writer documents always have one part, so hide the navigation drawer. if (mDocument.getDocumentType() != Document.DOCTYPE_TEXT) { for (int i = 0; i < parts; i++) { String partName = mDocument.getPartName(i); if (partName.isEmpty()) { partName = getGenericPartName(i); } Log.i(LOGTAG, "Document part " + i + " name:'" + partName + "'"); mDocument.setPart(i); resetDocumentSize(); final DocumentPartView partView = new DocumentPartView(i, partName); // LibreOfficeMainActivity.mAppContext.getDocumentPartView().add(partView); } } else { // LibreOfficeMainActivity.mAppContext.disableNavigationDrawer(); } mDocument.setPart(0); setupDocumentFonts(); // LOKitShell.getMainHandler().post(new Runnable() { // @Override // public void run() { // LibreOfficeMainActivity.mAppContext.getDocumentPartViewListAdapter().notifyDataSetChanged(); // } // }); } private void setupDocumentFonts() { String values = mDocument.getCommandValues(".uno:CharFontName"); if (values == null || values.isEmpty()) return; // LOKitShell.getFontController().parseJson(values); // LOKitShell.getFontController().setupFontViews(); } private String getGenericPartName(int i) { if (mDocument == null) { return ""; } switch (mDocument.getDocumentType()) { case Document.DOCTYPE_DRAWING: case Document.DOCTYPE_TEXT: return "Page " + (i + 1); case Document.DOCTYPE_SPREADSHEET: return "Sheet " + (i + 1); case Document.DOCTYPE_PRESENTATION: return "Slide " + (i + 1); case Document.DOCTYPE_OTHER: default: return "Part " + (i + 1); } } public static float twipToPixel(float input, float dpi) { return input / 1440.0f * dpi; } public static float pixelToTwip(float input, float dpi) { return (input / dpi) * 1440.0f; } /** * @see TileProvider#getPartsCount() */ @Override public int getPartsCount() { return mDocument.getParts(); } /** * @see TileProvider#onSwipeLeft() */ @Override public void onSwipeLeft() { if (mDocument.getDocumentType() == Document.DOCTYPE_PRESENTATION && getCurrentPartNumber() < getPartsCount()-1) { LOKitShell.sendChangePartEvent(getCurrentPartNumber()+1); } } /** * @see TileProvider#onSwipeRight() */ @Override public void onSwipeRight() { if (mDocument.getDocumentType() == Document.DOCTYPE_PRESENTATION && getCurrentPartNumber() > 0) { LOKitShell.sendChangePartEvent(getCurrentPartNumber()-1); } } private boolean checkDocument() { String error = null; boolean ret; if (mDocument == null || !mOffice.getError().isEmpty()) { error = "Cannot open " + mInputFile + ": " + mOffice.getError(); ret = false; } else { ret = resetDocumentSize(); if (!ret) { error = "Document returned an invalid size or the document is empty."; } } if (!ret) { final String message = error; LOKitShell.getMainHandler().post(new Runnable() { @Override public void run() { LibreOfficeMainActivity.mAppContext.showAlertDialog(message); } }); } return ret; } private boolean resetDocumentSize() { mWidthTwip = mDocument.getDocumentWidth(); mHeightTwip = mDocument.getDocumentHeight(); if (mWidthTwip == 0 || mHeightTwip == 0) { Log.e(LOGTAG, "Document size zero - last error: " + mOffice.getError()); return false; } else { Log.i(LOGTAG, "Reset document size: " + mDocument.getDocumentWidth() + " x " + mDocument.getDocumentHeight()); } return true; } /** * @see TileProvider#getPageWidth() */ @Override public int getPageWidth() { return (int) twipToPixel(mWidthTwip, mDPI); } /** * @see TileProvider#getPageHeight() */ @Override public int getPageHeight() { return (int) twipToPixel(mHeightTwip, mDPI); } /** * @see TileProvider#isReady() */ @Override public boolean isReady() { return mIsReady; } /** * @see TileProvider#createTile(float, float, IntSize, float) */ @Override public CairoImage createTile(float x, float y, IntSize tileSize, float zoom) { ByteBuffer buffer = DirectBufferAllocator.guardedAllocate(tileSize.width * tileSize.height * 4); if (buffer == null) return null; CairoImage image = new BufferedCairoImage(buffer, tileSize.width, tileSize.height, CairoImage.FORMAT_ARGB32); rerenderTile(image, x, y, tileSize, zoom); return image; } public Bitmap createBlankBitmap(int width, int height){ Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); int[] pix = new int[(width * height)]; /** 创建一个白色背景 */ for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { int index = y * width + x; int r = ((pix[index] >> 16) & 0xff) | 0xff; int g = ((pix[index] >> 8) & 0xff) | 0xff; int b = (pix[index] & 0xff) | 0xff; pix[index] = 0xff000000 | (r << 16) | (g << 8) | b; } } bitmap.setPixels(pix, 0, width, 0, 0, width, height); return bitmap; } public long renderTileHeight(){ long freeMemSize = (long)((Runtime.getRuntime().maxMemory() - Runtime.getRuntime().totalMemory() + Runtime.getRuntime().freeMemory()) * 0.3); long bytePerLine = this.getPageWidth() * 4; long singlePageHeight = freeMemSize / bytePerLine; if (singlePageHeight == 0){ return 0; } return singlePageHeight > this.getPageHeight() ? this.getPageHeight() : singlePageHeight; } public int renderTileHeight(int renderWidth){ long pageWidth = this.getPageWidth(); long pageHeight = this.getPageHeight(); float pageRatio = (float)pageWidth / (float)pageHeight; float renderRatio = (float)mRenderWidth / (float)mRenderHeight; // float dValue = pageRatio - renderRatio; if ((pageRatio - renderRatio) < -0.1){ return mRenderHeight; } else{ return (int)(renderWidth / pageRatio); } } public File createRenderTile(int index) throws IOException { File tempDirs = new File(Environment.getExternalStoragePublicDirectory("StartIPrint").getAbsolutePath() + "/RenderTemp"); if (!tempDirs.exists()){ tempDirs.mkdirs(); } File tempFile = new File(tempDirs.getAbsolutePath() + "/renderfile_" + mDocument.getPart() + "_" + index + ".jpg"); if (tempFile.exists()){ tempFile.delete(); } tempFile.createNewFile(); return tempFile; } // static int i = 0; public void renderTileWidth(float zoom){ Log.d(LOGTAG, "MainLOKitTileProvider renderTileWidth"); ArrayList<String> parseFileList = new ArrayList<>(); try { // if (i == 0) { int documentType = mDocument.getDocumentType();//word = 0, excel = 1, pptx = 2 for (int iPart = 0; iPart < mDocument.getParts(); ++iPart) { long pageWidth = this.getPageWidth(); long pageHeight = this.getPageHeight(); float pageRatio = (float) pageWidth / (float) pageHeight; float renderRatio = (float) mRenderWidth / (float) mRenderHeight; int renderPageHeight = mRenderHeight; if (documentType == 1) { int renderPageWidth = mRenderWidth; if ((pageRatio < 1 && renderRatio > 1) || (pageRatio > 1 && renderRatio < 1)){ renderPageHeight = this.mRenderWidth; renderPageWidth = this.mRenderHeight; } // 竖直方向 // if ((pageRatio < 1 && renderRatio < 1) || (pageRatio > 1 && renderRatio > 1)){ float widthRatio = (float)pageWidth / (float)renderPageWidth; int scaleRenderHeight = (int)(renderPageHeight * widthRatio); if (scaleRenderHeight > pageHeight){ // renderPageHeight = mRenderHeight; renderPageWidth = (int)(renderPageHeight * pageRatio); } else{ // renderPageHeight = mRenderHeight; // renderPageWidth = mRenderWidth; renderPageHeight = (int)(renderPageWidth / pageRatio); } ByteBuffer buffer = DirectBufferAllocator.guardedAllocate(renderPageWidth * renderPageHeight * 4); CairoImage testImage = new BufferedCairoImage(buffer, renderPageWidth, renderPageHeight, CairoImage.FORMAT_ARGB32); mDocument.paintTile(testImage.getBuffer(), renderPageWidth, renderPageHeight, 0, 0, (int) (mWidthTwip), (int) (mHeightTwip)); File file = createRenderTile(0); Bitmap bitmap = createBlankBitmap(renderPageWidth, renderPageHeight); bitmap.copyPixelsFromBuffer(testImage.getBuffer()); OutputStream outputStream = new FileOutputStream(file); bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream); outputStream.flush(); outputStream.close(); bitmap.recycle(); parseFileList.add(file.getAbsolutePath()); // } // // 横向 // else{ // // } } else { if ((pageRatio - renderRatio) > -0.1) { renderPageHeight = (int) (mRenderWidth / pageRatio); if (renderPageHeight == 0) { return; } // for (long totleHeight = 0, i = 0; totleHeight < pageHeight; totleHeight += renderPageHeight, ++i) { // Log.d("reanderfile", "i" + i); long curHeight = renderPageHeight; // if (((i + 1) * renderPageHeight) > pageHeight) { // curHeight = pageHeight - renderPageHeight * i; // } ByteBuffer buffer = DirectBufferAllocator.guardedAllocate(this.mRenderWidth * (int) curHeight * 4); CairoImage testImage = new BufferedCairoImage(buffer, this.mRenderWidth, (int) curHeight, CairoImage.FORMAT_ARGB32); // float twipY = pixelToTwip((renderPageHeight * i), mDPI) / zoom; float twipY = 0; // float twipHeight = pixelToTwip(curHeight, mDPI) / zoom; mDocument.paintTile(testImage.getBuffer(), this.mRenderWidth, (int) curHeight, 0, (int) twipY, (int) (mWidthTwip), (int) (mHeightTwip)); File file = createRenderTile(0); int width = this.mRenderWidth; Bitmap bitmap = createBlankBitmap(width, (int) curHeight); bitmap.copyPixelsFromBuffer(testImage.getBuffer()); OutputStream outputStream = new FileOutputStream(file); bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream); outputStream.flush(); outputStream.close(); bitmap.recycle(); parseFileList.add(file.getAbsolutePath()); // } // } } else { if (renderPageHeight == 0) { return; } // renderPageHeight:绘制的图片高度 // curHeight = renderPageHeight // curWidth:绘制图片的宽度,等于this.mRenderWidth // scaleRenderHeight:根据比率,换算到实际pageWidth的绘制高度 float widthRatio = (float) pageWidth / (float) mRenderWidth; int scaleRenderHeight = (int) (mRenderHeight * widthRatio); int printPart = (int) (pageHeight / scaleRenderHeight); printPart += ((pageHeight % scaleRenderHeight) == 0 ? 0 : 1); int saclePageHeight = (int) (pageHeight / widthRatio); // for (long totleHeight = 0, i = 0; totleHeight < pageHeight; totleHeight += renderPageHeight, ++i) { for (long iPPart = 0, i = 0; iPPart < printPart; ++iPPart, ++i) { Log.d("reanderfile", "i" + i); long curHeight = renderPageHeight; int curWidth = this.mRenderWidth; float twipY = pixelToTwip((scaleRenderHeight * i), mDPI) / zoom; float twipHeight = pixelToTwip(scaleRenderHeight, mDPI) / zoom; if (((i + 1) * renderPageHeight) > saclePageHeight) { curHeight = saclePageHeight - renderPageHeight * i; twipHeight = pixelToTwip(pageHeight - scaleRenderHeight * i, mDPI) / zoom; } ByteBuffer buffer = DirectBufferAllocator.guardedAllocate(curWidth * (int) curHeight * 4); CairoImage testImage = new BufferedCairoImage(buffer, curWidth, (int) curHeight, CairoImage.FORMAT_ARGB32); mDocument.paintTile(testImage.getBuffer(), curWidth, (int) curHeight, 0, (int) twipY, (int) (mWidthTwip), (int) (twipHeight)); File file = createRenderTile((int) i); Bitmap bitmap = createBlankBitmap(curWidth, (int) curHeight); bitmap.copyPixelsFromBuffer(testImage.getBuffer()); OutputStream outputStream = new FileOutputStream(file); bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream); outputStream.flush(); outputStream.close(); bitmap.recycle(); parseFileList.add(file.getAbsolutePath()); // } } } if (documentType == 0) { break; } changePart(iPart); } } changePart(0); MainOffice.sendBroadCast(MainOffice.PARSE_END, parseFileList); } catch (IOException ioe){ ioe.printStackTrace(); MainOffice.sendBroadCast(MainOffice.PARSE_ERROR); } } public void reanderTile(float zoom) { Log.d(LOGTAG, "MainLOKitTileProvider reanderTile"); try { // if (i == 0) { for (int iPart = 0; iPart < mDocument.getParts(); ++iPart) { long renderPageHeight = this.renderTileHeight(); long pageHeight = this.getPageHeight(); if (renderPageHeight == 0) { return; } for (long totleHeight = 0, i = 0; totleHeight < pageHeight; totleHeight += renderPageHeight, ++i) { Log.d("reanderfile", "i" + i); long curHeight = renderPageHeight; if (((i + 1) * renderPageHeight) > pageHeight) { curHeight = pageHeight - renderPageHeight * i; } ByteBuffer buffer = DirectBufferAllocator.guardedAllocate(this.getPageWidth() * (int) curHeight * 4); CairoImage testImage = new BufferedCairoImage(buffer, this.getPageWidth(), (int) curHeight, CairoImage.FORMAT_ARGB32); float twipY = pixelToTwip((renderPageHeight * i), mDPI) / zoom; float twipHeight = pixelToTwip(curHeight, mDPI) / zoom; mDocument.paintTile(testImage.getBuffer(), this.getPageWidth(), (int) curHeight, 0, (int) twipY, (int) (mWidthTwip), (int) (twipHeight)); // // File file = new File("/sdcard/renderTile.png"); //// i++; // if (file.exists()) { // file.delete(); // } // file.createNewFile(); File file = createRenderTile((int) i); int width = this.getPageWidth(); // int height = this.getPageHeight(); Bitmap bitmap = createBlankBitmap(width, (int) curHeight); bitmap.copyPixelsFromBuffer(testImage.getBuffer()); OutputStream outputStream = new FileOutputStream(file); bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream); outputStream.flush(); outputStream.close(); bitmap.recycle(); // } } changePart(iPart); } changePart(0); } catch (IOException ioe){ ioe.printStackTrace(); } } /** * @see TileProvider#rerenderTile(CairoImage, float, float, IntSize, float) */ @Override public void rerenderTile(CairoImage image, float x, float y, IntSize tileSize, float zoom) { if (mDocument != null && image.getBuffer() != null) { float twipX = pixelToTwip(x, mDPI) / zoom; float twipY = pixelToTwip(y, mDPI) / zoom; float twipWidth = mTileWidth / zoom; float twipHeight = mTileHeight / zoom; long start = System.currentTimeMillis() - objectCreationTime; // try { // if (i == 0) { // ByteBuffer buffer = DirectBufferAllocator.guardedAllocate(this.getPageWidth() * this.getPageHeight() * 4); // CairoImage testImage = new BufferedCairoImage(buffer, this.getPageWidth(), this.getPageHeight(), CairoImage.FORMAT_ARGB32); // mDocument.paintTile(testImage.getBuffer(), this.getPageWidth(), this.getPageHeight(), 0, 0, (int)(this.getPageWidth() / 0.225), (int)(this.getPageHeight() / 0.225)); // // File file = new File("/sdcard/test" + i + ".png"); // i++; // if (file.exists()) { // file.delete(); // } // file.createNewFile(); // // int width = this.getPageWidth(); // int height = this.getPageHeight(); // Bitmap bitmap = createBlankBitmap(width, height); // bitmap.copyPixelsFromBuffer(testImage.getBuffer()); // OutputStream outputStream = new FileOutputStream(file); // bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream); // } // } // catch (Exception e){ // e.printStackTrace(); // } //Log.i(LOGTAG, "paintTile >> @" + start + " (" + tileSize.width + " " + tileSize.height + " " + (int) twipX + " " + (int) twipY + " " + (int) twipWidth + " " + (int) twipHeight + ")"); mDocument.paintTile(image.getBuffer(), tileSize.width, tileSize.height, (int) twipX, (int) twipY, (int) twipWidth, (int) twipHeight); // try { // // File file = new File("/sdcard/test" + i + ".png"); // i++; // if (file.exists()){ // file.delete(); // } // file.createNewFile(); // // Bitmap bitmap = createBlankBitmap(tileSize.width, tileSize.height); // bitmap.copyPixelsFromBuffer(image.getBuffer()); // OutputStream outputStream = new FileOutputStream(file); // bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream); // } // catch (Exception e){ // e.printStackTrace(); // } long stop = System.currentTimeMillis() - objectCreationTime; //Log.i(LOGTAG, "paintTile << @" + stop + " elapsed: " + (stop - start)); } else { if (mDocument == null) { Log.e(LOGTAG, "Document is null!!"); } } } /** * @see TileProvider#thumbnail(int) */ @Override public Bitmap thumbnail(int size) { int widthPixel = getPageWidth(); int heightPixel = getPageHeight(); if (widthPixel > heightPixel) { double ratio = heightPixel / (double) widthPixel; widthPixel = size; heightPixel = (int) (widthPixel * ratio); } else { double ratio = widthPixel / (double) heightPixel; heightPixel = size; widthPixel = (int) (heightPixel * ratio); } Log.w(LOGTAG, "Thumbnail size: " + getPageWidth() + " " + getPageHeight() + " " + widthPixel + " " + heightPixel); ByteBuffer buffer = ByteBuffer.allocateDirect(widthPixel * heightPixel * 4); if (mDocument != null) mDocument.paintTile(buffer, widthPixel, heightPixel, 0, 0, (int) mWidthTwip, (int) mHeightTwip); Bitmap bitmap = Bitmap.createBitmap(widthPixel, heightPixel, Bitmap.Config.ARGB_8888); bitmap.copyPixelsFromBuffer(buffer); if (bitmap == null) { Log.w(LOGTAG, "Thumbnail not created!"); } return bitmap; } /** * @see TileProvider#close() */ @Override public void close() { Log.i(LOGTAG, "Document destroyed: " + mInputFile); if (mDocument != null) { mDocument.destroy(); mDocument = null; } } /** * @see TileProvider#isTextDocument() */ @Override public boolean isTextDocument() { return mDocument != null && mDocument.getDocumentType() == Document.DOCTYPE_TEXT; } /** * @see TileProvider#isSpreadsheet() */ @Override public boolean isSpreadsheet() { return mDocument != null && mDocument.getDocumentType() == Document.DOCTYPE_SPREADSHEET; } /** * Returns the Unicode character generated by this event or 0. */ private int getCharCode(KeyEvent keyEvent) { switch (keyEvent.getKeyCode()) { case KeyEvent.KEYCODE_DEL: case KeyEvent.KEYCODE_ENTER: return 0; } return keyEvent.getUnicodeChar(); } /** * Returns the integer code representing the key of the event (non-zero for * control keys). */ private int getKeyCode(KeyEvent keyEvent) { switch (keyEvent.getKeyCode()) { case KeyEvent.KEYCODE_DEL: return com.sun.star.awt.Key.BACKSPACE; case KeyEvent.KEYCODE_ENTER: return com.sun.star.awt.Key.RETURN; } return 0; } /** * @see TileProvider#sendKeyEvent(KeyEvent) */ @Override public void sendKeyEvent(KeyEvent keyEvent) { if (keyEvent.getAction() == KeyEvent.ACTION_MULTIPLE) { String keyString = keyEvent.getCharacters(); for (int i = 0; i < keyString.length(); i++) { int codePoint = keyString.codePointAt(i); mDocument.postKeyEvent(Document.KEY_EVENT_PRESS, codePoint, getKeyCode(keyEvent)); } } else if (keyEvent.getAction() == KeyEvent.ACTION_DOWN) { mDocument.postKeyEvent(Document.KEY_EVENT_PRESS, getCharCode(keyEvent), getKeyCode(keyEvent)); } else if (keyEvent.getAction() == KeyEvent.ACTION_UP) { mDocument.postKeyEvent(Document.KEY_EVENT_RELEASE, getCharCode(keyEvent), getKeyCode(keyEvent)); } } private void mouseButton(int type, PointF inDocument, int numberOfClicks, float zoomFactor) { int x = (int) pixelToTwip(inDocument.x, mDPI); int y = (int) pixelToTwip(inDocument.y, mDPI); mDocument.setClientZoom(TILE_SIZE, TILE_SIZE, (int) (mTileWidth / zoomFactor), (int) (mTileHeight / zoomFactor)); mDocument.postMouseEvent(type, x, y, numberOfClicks, Document.MOUSE_BUTTON_LEFT, Document.KEYBOARD_MODIFIER_NONE); } /** * @see TileProvider#mouseButtonDown(PointF, int) */ @Override public void mouseButtonDown(PointF documentCoordinate, int numberOfClicks, float zoomFactor) { mouseButton(Document.MOUSE_EVENT_BUTTON_DOWN, documentCoordinate, numberOfClicks, zoomFactor); } /** * @see TileProvider#mouseButtonUp(PointF, int) */ @Override public void mouseButtonUp(PointF documentCoordinate, int numberOfClicks, float zoomFactor) { mouseButton(Document.MOUSE_EVENT_BUTTON_UP, documentCoordinate, numberOfClicks, zoomFactor); } /** * @param command UNO command string * @param arguments Arguments to UNO command */ @Override public void postUnoCommand(String command, String arguments) { mDocument.postUnoCommand(command, arguments); } private void setTextSelection(int type, PointF documentCoordinate) { int x = (int) pixelToTwip(documentCoordinate.x, mDPI); int y = (int) pixelToTwip(documentCoordinate.y, mDPI); mDocument.setTextSelection(type, x, y); } /** * @see TileProvider#setTextSelectionStart(PointF) */ @Override public void setTextSelectionStart(PointF documentCoordinate) { setTextSelection(Document.SET_TEXT_SELECTION_START, documentCoordinate); } /** * @see TileProvider#setTextSelectionEnd(PointF) */ @Override public void setTextSelectionEnd(PointF documentCoordinate) { setTextSelection(Document.SET_TEXT_SELECTION_END, documentCoordinate); } /** * @see TileProvider#setTextSelectionReset(PointF) */ @Override public void setTextSelectionReset(PointF documentCoordinate) { setTextSelection(Document.SET_TEXT_SELECTION_RESET, documentCoordinate); } /** * @see TileProvider#setGraphicSelectionStart(PointF) */ @Override public void setGraphicSelectionStart(PointF documentCoordinate) { setGraphicSelection(Document.SET_GRAPHIC_SELECTION_START, documentCoordinate); } /** * @see TileProvider#setGraphicSelectionEnd(PointF) */ @Override public void setGraphicSelectionEnd(PointF documentCoordinate) { setGraphicSelection(Document.SET_GRAPHIC_SELECTION_END, documentCoordinate); } private void setGraphicSelection(int type, PointF documentCoordinate) { int x = (int) pixelToTwip(documentCoordinate.x, mDPI); int y = (int) pixelToTwip(documentCoordinate.y, mDPI); mDocument.setGraphicSelection(type, x, y); } @Override protected void finalize() throws Throwable { close(); super.finalize(); } /** * @see TileProvider#changePart(int) */ @Override public void changePart(int partIndex) { if (mDocument == null) return; mDocument.setPart(partIndex); resetDocumentSize(); } /** * @see TileProvider#getCurrentPartNumber() */ @Override public int getCurrentPartNumber() { if (mDocument == null) return 0; return mDocument.getPart(); } }
package com.gtfs.dao.interfaces; import java.util.List; import com.gtfs.bean.UserRoleRlns; public interface UserRoleRlnsDao { List<UserRoleRlns> findActiveUserRoleByUserId(Long userId); Long insertIntoUserRoleRlns(UserRoleRlns userRoleRlns); Integer deleteFromUserRoleRlnsByRoleIdAndUserId(Long roleId, Long userid, Long loginUserId); }
/* * 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 za.co.terratech.minerstats.statsproviderworkers; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; import java.util.ArrayList; import java.util.List; /** * * @author riazs */ public class AllResults { @SerializedName("results") @Expose private List<Worker> results; public List<Worker> getResults() { if (results == null){ results = new ArrayList(); } return results; } public void setResults(List<Worker> results) { this.results = results; } }
package com.rsm.yuri.projecttaxilivredriver.home.di; import android.util.Log; import com.rsm.yuri.projecttaxilivredriver.domain.FirebaseAPI; import com.rsm.yuri.projecttaxilivredriver.home.HomeInteractor; import com.rsm.yuri.projecttaxilivredriver.home.HomeInteractorImpl; import com.rsm.yuri.projecttaxilivredriver.home.HomePresenter; import com.rsm.yuri.projecttaxilivredriver.home.HomePresenterImpl; import com.rsm.yuri.projecttaxilivredriver.home.HomeRepository; import com.rsm.yuri.projecttaxilivredriver.home.HomeRepositoryImpl; import com.rsm.yuri.projecttaxilivredriver.home.models.AreasFortalezaHelper; import com.rsm.yuri.projecttaxilivredriver.home.models.AreasHelper; import com.rsm.yuri.projecttaxilivredriver.home.models.AreasTeresinaHelper; import com.rsm.yuri.projecttaxilivredriver.home.ui.HomeView; import com.rsm.yuri.projecttaxilivredriver.lib.base.EventBus; import javax.inject.Singleton; import dagger.Module; import dagger.Provides; /** * Created by yuri_ on 09/03/2018. */ @Module public class HomeModule { private HomeView view; private AreasHelper areasHelper = null; private String cidade; public HomeModule(HomeView view, String cidade) { this.view = view; this.cidade = cidade; } /*public void setAreasHelper(AreasHelper areasHelper){ this.areasHelper = areasHelper; }*/ @Provides @Singleton HomeView providesHomeView(){ return view; } @Provides @Singleton HomePresenter providesHomePresenter(EventBus eventBus, HomeView homeView, HomeInteractor homeInteractor){ return new HomePresenterImpl(homeView, homeInteractor, eventBus); } @Provides @Singleton HomeInteractor providesHomeInteractor(HomeRepository homeRepository){ return new HomeInteractorImpl(homeRepository); } @Provides @Singleton HomeRepository providesHomeRepository(FirebaseAPI helper, EventBus eventBus, AreasHelper areasHelper){ return new HomeRepositoryImpl(helper, eventBus, areasHelper, cidade); } @Provides @Singleton AreasHelper providesAreasHelper(){ String nomeDaClasse = "com.rsm.yuri.projecttaxilivredriver.home.models.Areas" + cidade +"Helper"; // String nomeDaClasse = "com.rsm.yuri.projecttaxilivredriver.home.models.AreasTeresinaHelper"; // String nomeDaClasse = "com.rsm.yuri.projecttaxilivredriver.home.models.AreasFortalezaHelper"; // Log.d("d", "HomeModule - providesAreasHelper() - nome da classe: " + nomeDaClasse); Class classe = null;//carregar a classe com o nome da String passada try { classe = Class.forName(nomeDaClasse); areasHelper = (AreasHelper) classe.newInstance(); }catch (ClassNotFoundException e){ e.printStackTrace(); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } return areasHelper; } }
package com.example.barea.notelist.Utils; import android.content.Context; import android.content.SharedPreferences; public class PrefUtils { private static SharedPreferences getSharedPrefernce(Context context){ return context.getSharedPreferences("APP_PREF", Context.MODE_PRIVATE); } public static void storeApiKey(Context context, String apiKey){ SharedPreferences.Editor editor = getSharedPrefernce(context).edit(); editor.putString("API_KEY", apiKey ); editor.commit(); } public static String getApiKey(Context context){ return getSharedPrefernce(context).getString("API_KEY", null); } }
/* * [y] hybris Platform * * Copyright (c) 2018 SAP SE or an SAP affiliate company. All rights reserved. * * This software is the confidential and proprietary information of SAP * ("Confidential Information"). You shall not disclose such Confidential * Information and shall use it only in accordance with the terms of the * license agreement you entered into with SAP. */ package de.hybris.platform.cmsfacades.util.models; import de.hybris.platform.cms2.model.CMSPageTypeModel; import de.hybris.platform.cms2.model.contents.CMSItemModel; import de.hybris.platform.cmsfacades.util.dao.CMSPageTypeDao; import org.springframework.beans.factory.annotation.Required; public class CMSPageTypeModelMother extends AbstractModelMother<CMSPageTypeModel> { protected static final Class<?> SUPER_TYPE = CMSItemModel.class; public static final String CODE_CONTENT_PAGE = "ContentPage"; protected static final String CODE_CATALOG_PAGE = "CatalogPage"; private CMSPageTypeDao cmsPageTypeDao; public CMSPageTypeModel ContentPage() { return cmsPageTypeDao.getCMSPageTypeByCode(CODE_CONTENT_PAGE); } public CMSPageTypeModel CatalogPage() { return cmsPageTypeDao.getCMSPageTypeByCode(CODE_CATALOG_PAGE); } protected CMSPageTypeDao getCmsPageTypeDao() { return cmsPageTypeDao; } @Required public void setCmsPageTypeDao(final CMSPageTypeDao cmsPageTypeDao) { this.cmsPageTypeDao = cmsPageTypeDao; } }
/** * Provides abstract classes that represents CSAR related deployment * information.<br /> * <br /> * Copyright 2012 IAAS University of Stuttgart <br /> * <br /> * * @author Rene Trefft - trefftre@studi.informatik.uni-stuttgart.de */ package org.opentosca.core.model.deployment;
package annotation_test; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Description: * * @author Baltan * @date 2019-05-10 09:10 */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface MyAfter { }
package com.beiyelin.commonwx.miniapp.message; import com.beiyelin.commonwx.miniapp.api.WxMaService; import com.beiyelin.commonwx.miniapp.bean.WxMaMessage; import com.beiyelin.commonwx.common.exception.WxErrorException; import com.beiyelin.commonwx.common.session.WxSessionManager; import java.util.Map; /** * 处理小程序推送消息的处理器接口 * * @author <a href="https://github.com/binarywang">Binary Wang</a> */ public interface WxMaMessageHandler { void handle(WxMaMessage message, Map<String, Object> context, WxMaService service, WxSessionManager sessionManager) throws WxErrorException; }
package moderate; /* Sample code to read in test cases:*/ import java.util.*; import java.lang.*; import java.io.*; public class SumOfIntegers { public static void main (String[] args) throws IOException { File file = new File(args[0]); BufferedReader buffer = new BufferedReader(new FileReader(file)); String line; while ((line = buffer.readLine()) != null) { line = line.trim(); String[] str = line.split(","); int[] n = new int[str.length]; if(line.length()==0){ continue; } for(int i=0; i<str.length;i++){ n[i] = Integer.parseInt(str[i]); } int maxEnding = n[0]; int tempEnding = 0; for(int i=0;i<n.length;i++){ for(int j=i;j<n.length;j++){ tempEnding = 0; for(int k=i;k<=j;k++){ tempEnding+=n[k]; } if(maxEnding < tempEnding){ maxEnding = tempEnding; } if(tempEnding < 0){ tempEnding=0; } } } System.out.println(maxEnding); } } }
package com.framework.controller; import java.util.List; import java.util.Map; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import com.framework.bean.common.Page; import com.framework.bean.common.ResultMessage; import com.framework.controller.BaseController; import com.framework.model.ActReProcdef; import com.framework.service.CommonService; import com.framework.service.ActReProcdefService; import com.google.gson.reflect.TypeToken; @Controller @RequestMapping("actReProcdef") public class ActReProcdefController extends BaseController { private final Logger logger = Logger.getLogger(getClass()); @Autowired private ActReProcdefService actReProcdefService; @RequestMapping("toActReProcdefManage") public String toActReProcdefManage(){ return "framework/actReProcdef/actReProcdefManage"; } @RequestMapping("queryActReProcdefList") @ResponseBody public Page<ActReProcdef> queryActReProcdefList(Page<ActReProcdef> page){ try { Map<String,Object> params = super.getMapParams(); actReProcdefService.queryActReProcdefList(page,params); } catch (Exception e) { logger.error(e.getMessage(),e); } return page; } @RequestMapping("addActReProcdef") @ResponseBody public ResultMessage<ActReProcdef> addActReProcdef(ActReProcdef actReProcdef){ ResultMessage<ActReProcdef> rm = new ResultMessage<>(); try { rm = actReProcdefService.addActReProcdef(actReProcdef); } catch (Exception e) { logger.error(e.getMessage(),e); rm.setMessage(e.getMessage()); } return rm; } @RequestMapping("updateActReProcdef") @ResponseBody public ResultMessage<?> updateActReProcdef(ActReProcdef actReProcdef){ ResultMessage<?> rm = new ResultMessage<>(); try { rm = actReProcdefService.updateActReProcdef(actReProcdef); } catch (Exception e) { logger.error(e.getMessage(),e); rm.setMessage(e.getMessage()); } return rm; } @RequestMapping("deleteActReProcdefs") @ResponseBody public ResultMessage<?> deleteActReProcdefs(String actReProcdefsJson){ ResultMessage<?> rm = null; try { List<ActReProcdef> actReProcdefs = gson.fromJson(actReProcdefsJson, new TypeToken<List<ActReProcdef>>(){}.getType()); rm = actReProcdefService.deleteActReProcdefs(actReProcdefs); } catch (Exception e) { logger.error(e.getMessage(),e); rm.setMessage(e.getMessage()); } return rm; } @RequestMapping("getActReProcdef") @ResponseBody public ResultMessage<ActReProcdef> getActReProcdef(ActReProcdef actReProcdef){ ResultMessage<ActReProcdef> resultMessage = new ResultMessage<>(); try { ActReProcdef actReProcdef1 = actReProcdefService.getActReProcdef(actReProcdef); resultMessage.setModel(actReProcdef1); resultMessage.setSuccess(true); } catch (Exception e) { resultMessage.setMessage(e.getMessage()); } return resultMessage; } }
package com.example.musicthread; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.os.Environment; import android.view.View; import android.widget.Button; import java.io.IOException; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button button1 = findViewById(R.id.button1); Button button2 = findViewById(R.id.button2); Button button3 = findViewById(R.id.button3); View.OnClickListener click = new View.OnClickListener() { @Override public void onClick(View v) { String sdState = android.os.Environment.getExternalStorageState(); //Получаем состояние SD карты (подключена она или нет) - возвращается true и false соответственно if (sdState.equals(android.os.Environment.MEDIA_MOUNTED)) { try { MusicThread thread = new MusicThread(Environment. getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString() + "/test.mp3"); } catch (IOException e) { e.printStackTrace(); } } } }; button1.setOnClickListener(click); button2.setOnClickListener(click); button3.setOnClickListener(click); } }
package br.com.pcmaker.entity; import javax.persistence.MappedSuperclass; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; @NamedQueries({ @NamedQuery( name = "queryFaturamentoMesAno", query = "select new br.com.pcmaker.entity.RelatorioGrafico(date_format(etapaOrdemServico.dataInclusao, '%m/%Y'), sum(ordemServico.valorOrcamento))" + " from OrdemServico as ordemServico" + " join ordemServico.etapaOrdemServico as etapaOrdemServico" + " where etapaOrdemServico.etapa.id = ?" + " and ordemServico.aprovado = ?" + " and etapaOrdemServico.dataInclusao = (" + " select max(dataInclusao) from EtapaOrdemServico as maxEtapaOrdemServico" + " where maxEtapaOrdemServico.ordemServico.id = ordemServico.id" + " ) " + " and date_format(etapaOrdemServico.dataInclusao, '%Y') = ?" + " group by date_format(etapaOrdemServico.dataInclusao, '%m/%Y')" + " order by date_format(etapaOrdemServico.dataInclusao, '%m')" ), @NamedQuery( name = "queryServicosPorEquipamento", query = "select new br.com.pcmaker.entity.RelatorioGrafico(ordemServico.equipamento.nome, count(1))" + " from OrdemServico as ordemServico" + " join ordemServico.etapaOrdemServico as etapaOrdemServico" + " where etapaOrdemServico.etapa.id <> ?" + " and ordemServico.aprovado = ?" + " and etapaOrdemServico.dataInclusao = (" + " select max(dataInclusao) from EtapaOrdemServico as maxEtapaOrdemServico" + " where maxEtapaOrdemServico.ordemServico.id = ordemServico.id" + " ) " + " group by ordemServico.equipamento.nome" + " order by ordemServico.equipamento.nome" ), @NamedQuery( name = "queryOrdensServicoMesAno", query = "select new br.com.pcmaker.entity.RelatorioGrafico(date_format(etapaOrdemServico.dataInclusao, '%m/%Y'), count(1))" + " from OrdemServico as ordemServico" + " join ordemServico.etapaOrdemServico as etapaOrdemServico" + " where etapaOrdemServico.id = (" + " select innerEtapaOrdemServico.id from EtapaOrdemServico as innerEtapaOrdemServico" + " where innerEtapaOrdemServico.ordemServico.id = ordemServico.id" + " and innerEtapaOrdemServico.etapa.id = ?" + " ) " + " and date_format(etapaOrdemServico.dataInclusao, '%Y') = ?" + " group by date_format(etapaOrdemServico.dataInclusao, '%m/%Y')" + " order by date_format(etapaOrdemServico.dataInclusao, '%m')" ) }) @MappedSuperclass public class RelatorioGrafico extends BaseEntity { /** * */ private static final long serialVersionUID = 1L; private String label; private double value; public RelatorioGrafico() { } public RelatorioGrafico(String label, double value) { this.label = label; this.value = value; } public RelatorioGrafico(String label, long value) { this.label = label; this.value = value; } public String getLabel() { return label; } public void setLabel(String label) { this.label = label; } public double getValue() { return value; } public void setValue(double value) { this.value = value; } }
package tests.day14; import org.openqa.selenium.By; import org.openqa.selenium.WebElement; import org.testng.*; import org.testng.annotations.Test; import utilities.TestBase; public class C4_FileUpload extends TestBase { /* 1.Tests packagenin altina bir class oluşturun : D14_UploadFile 2.https://the-internet.herokuapp.com/upload adresine gidelim 3.chooseFile butonuna basalim 4.Yuklemek istediginiz dosyayi secelim. 5.Upload butonuna basalim. 6.“File Uploaded!” textinin goruntulendigini test edelim. */ @Test public void upload (){ driver.get("https://the-internet.herokuapp.com/upload"); // 1- Dosya sec butonu locate edelim WebElement chooseFile = driver.findElement(By.id("file-upload")); // 2- Yuklemek istedigimiz dosyanin dosya yolunu kaydedin String filePath = System.getProperty("user.home")+"/Desktop/FLOWER.jpg"; // 3- SendKeys ile dosyayi secelim chooseFile.sendKeys(filePath); WebElement uploadButton = driver.findElement(By.id("file-submit")); uploadButton.click(); WebElement uploadedText = driver.findElement(By.tagName("h3")); Assert.assertTrue(uploadedText.isDisplayed()); /* - Eger bir sayfada birden fazla Assert.assertTrue yapilacaksa , bastaki ASSERT. yazisini sileriz assertTrue(uploadedText.isDisplayed()); == gibi - ardindan CTE veren kismin ustune gidip ALT+ENTER yapip import edersek eger bir sonraki assert islemleriin basina surekli Assert. yazmak zorunda kalmayiz. - Eger ayni sayfada assertTrue,assertFalse,assertEquals yapilacak ise , import kismina gidilir import org.testng.Assert; yazan kismi import org.testng.*; == ile update edilir *** Ayni islem SoftAssert icin yapilmaz cunku onun icin obje olusturulmasi gerekir. */ } }
package com.gmail.volodymyrdotsenko.cms.be.domain.media; import java.io.Serializable; import javax.persistence.*; //@Entity //@Table(name = "") @Embeddable public class TextItem implements Serializable { private static final long serialVersionUID = 1L; public TextItem() { } public TextItem(String text) { this.text = text; } @Lob @Column(name = "text") private String text; public String getText() { return text; } public void setText(String text) { this.text = text; } }
package ejercicios.clases.wrappers; public class Main { public static void main(String[] args) { // TODO Auto-generated method stub // byte, tipo primitivo System.out.println("1. byte"); byte datoByte = 2; // primitivo Byte datoByteWrapper = 3; // byte, Wrapper System.out.println("primitivo: " + datoByte); System.out.println("Wrapper: " + datoByteWrapper); // conversiones byte datoByte1 = 6; Byte datoConvertido = datoByte1; System.out.println("Byte convertido: " + datoConvertido); // Conversion 2 Byte datoConvertido2 = 5; byte datoByte2 = datoConvertido2.byteValue(); System.out.println("byte convertido: " + datoByte2); // short System.out.println("2. short"); short datoShort = 1; // primitivo Short datoShortWrapper = 1; // Wrapper System.out.println("primitivo: " + datoShort); System.out.println("Wrapper: " + datoShortWrapper); // conversiones short datoShort1 = 4; Short shortConvertido = datoShort1; System.out.println("Short convertido: " + shortConvertido); // Conversion 2 Short datoShortCovertido = 12; short datoShort2 = datoShortCovertido.shortValue(); System.out.println("short convertido: " + datoShort2); // int System.out.println("3. int"); int edad = 45; // primitivo Integer edadWrapper = 48; // Wrapper System.out.println("primitivo: " + edad); System.out.println("Wrapper: " + edadWrapper); // Conversiones int edad1 = 45; Integer integerConvertido = edad1; System.out.println("Integer convertido: " + integerConvertido); // Conversion 2 Integer integerConvertido2 = 6; int edad2 = integerConvertido2.intValue(); System.out.println("int convertido: " + edad2); // long System.out.println("4. long"); long valorGrande = 12312L;// primitivo long valorGrandeWrapper = 123312L;// Wrapper System.out.println("primitivo: " + valorGrande); System.out.println("Wrapper: " + valorGrandeWrapper); // Conversiones long valorLong = 451234L; Long longConvertido = valorLong; System.out.println("Long convertido: " + longConvertido); // Conversion 2 Long longConvertido2 = 6123123L; long datoLong1 = longConvertido2.longValue(); System.out.println("long convertido: " + datoLong1); // boolean System.out.println("5. boolean"); boolean boolean1 = true; // primitivo Boolean boolean1Wrapper = true; // Wrapper System.out.println("primitivo: " + boolean1); System.out.println("Wrapper: " + boolean1Wrapper); // Conversiones boolean valorBoolean = true; Boolean booleanConvertido = valorBoolean; System.out.println("Boolean convertido: " + booleanConvertido); // Conversion 2 Boolean booleanConvertido2 = false; boolean datoBoolean2 = booleanConvertido2.booleanValue(); System.out.println("boolean convertido: " + datoBoolean2); // float System.out.println("6. float"); float numeroDecimal = 12.12F; // primitivo Float numeroDecimalWrapper = 12.12F; // Wrapper System.out.println("primitivo: " + numeroDecimal); System.out.println("Wrapper: " + numeroDecimalWrapper); // Conversiones float valorFloat = 45.12F; Float floatConvertido = valorFloat; System.out.println("Float convertido: " + floatConvertido); // Conversion 2 Float floatConvertido2 = 123.23F; float datoFloat2 = floatConvertido2.floatValue(); System.out.println("float convertido: " + datoFloat2); // double System.out.println("7. double"); double numeroGrandeDecimal = 122321.23;// primitivo double numeroGrandeDecimalWrapper = 122321.23;// Wrapper System.out.println("primitivo: " + numeroGrandeDecimal); System.out.println("Wrapper: " + numeroGrandeDecimalWrapper); // Conversiones double valorDouble = 45234.12345; Double doubleConvertido = valorDouble; System.out.println("Double convertido: " + doubleConvertido); // Conversion 2 Double doubleConvertido2 = 12345.1234; double datoDouble2 = doubleConvertido2.doubleValue(); System.out.println("double convertido: " + datoDouble2); // char System.out.println("8. char"); char caracter = 'a'; // primitivo Character caracterWrapper = 'a';// Wrapper System.out.println("primitivo: " + caracter); System.out.println("Wrapper: " + caracterWrapper); // Conversiones char valorChar = 'y'; Character characterConvertido = valorChar; System.out.println("Character convertido: " + characterConvertido); // Conversion 2 Character characterConvertido2 = 'z'; char datoChar2 = characterConvertido2.charValue(); System.out.println("char convertido: " + datoChar2); } }
import java.util.ArrayList; import java.util.Scanner; /** * Created by Mighty on 29.3.2016 г.. */ public interface CombineListsOfLetters { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String[] firstIn = sc.nextLine().split(" "); String[] secondIn = sc.nextLine().split(" "); ArrayList<Character> firstList = new ArrayList<>(); for (int i = 0; i <firstIn.length ; i++) { firstList.add(firstIn[i].charAt(0)); } ArrayList<Character> secondList = new ArrayList<>(); for (int i = 0; i <secondIn.length ; i++) { if (!firstList.contains(secondIn[i].charAt(0))){ secondList.add(secondIn[i].charAt(0)); } } for (int i = 0; i <secondList.size() ; i++) { firstList.add(secondList.get(i)); } for (int i = 0; i <firstList.size() ; i++) { System.out.print(firstList.get(i)+" "); } System.out.println(); } }
package comparisons; import java.util.Comparator; import fish.Fish; public class CompareFishPreyBySize implements Comparator<Fish>{ public CompareFishPreyBySize(){ } @Override public int compare(Fish fishOne, Fish fishTwo) { // TODO Auto-generated method stub return -(fishOne.getSize() - fishTwo.getSize()); } }
package com.yygame.common.utils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.math.NumberUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.Map; /** * 中国居民身份证工具类 * * @author dw_xiajiqiu1 */ public class IDCardUtil { private static Logger logger = LoggerFactory.getLogger(IDCardUtil.class); /** * 旧版身份证号码长度 **/ private static int OLD_IDCARD_LENGTH = 15; /** * 新版身份证号码长度 **/ private static int NEW_IDCARD_LENGTH = 18; /** * 身份证区域代码Map */ private static final Map<Integer, String> AREA_MAP; private static int[] WI = new int[]{7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2}; /** * 最后一位字符 */ private static String[] LAST_STR = new String[]{"1", "0", "X", "9", "8", "7", "6", "5", "4", "3", "2"}; private static String IDCARD_REGEX = "^\\d+[\\dX]$"; static { Map<Integer, String> areaMap = new HashMap<Integer, String>(); areaMap.put(11, "北京"); areaMap.put(12, "天津"); areaMap.put(13, "河北"); areaMap.put(14, "山西"); areaMap.put(15, "内蒙古"); areaMap.put(21, "辽宁"); areaMap.put(22, "吉林"); areaMap.put(23, "黑龙江"); areaMap.put(31, "上海"); areaMap.put(32, "江苏"); areaMap.put(33, "浙江"); areaMap.put(34, "安徽"); areaMap.put(35, "福建"); areaMap.put(36, "江西"); areaMap.put(37, "山东"); areaMap.put(41, "河南"); areaMap.put(42, "湖北"); areaMap.put(43, "湖南"); areaMap.put(44, "广东"); areaMap.put(45, "广西"); areaMap.put(46, "海南"); areaMap.put(50, "重庆"); areaMap.put(51, "四川"); areaMap.put(52, "贵州"); areaMap.put(53, "云南"); areaMap.put(54, "西藏"); areaMap.put(61, "陕西"); areaMap.put(62, "甘肃"); areaMap.put(63, "青海"); areaMap.put(64, "宁夏"); areaMap.put(65, "新疆"); areaMap.put(71, "台湾"); areaMap.put(81, "香港"); areaMap.put(82, "澳门"); areaMap.put(91, "国外"); AREA_MAP = areaMap; } /** * 是否超过指定的年龄 * * @param idCard 身份证 * @param minAge 最小年龄,包含 * @return 返回是否超过或等于指定年龄 */ public static boolean isOverOrEqualAge(String idCard, int minAge) { int age = getAge(idCard); return age >= minAge; } /** * 提取身份证号码中的年龄 * * @param idCard 身份证号码 * @return 返回身份证号码年龄 * @throws RuntimeException 如果不是合法的身份证将会抛出异常 */ public static int getAge(String idCard) throws RuntimeException { AssertUtil.assertTrue(isValidBirthday(idCard), "身份证格式不合法"); idCard = convertToNewFormatIdCard(idCard); Date birthday = getNewIdCardBirthday(idCard); AssertUtil.assertNotNull(birthday, "身份证格式不合法"); Calendar calendar1 = Calendar.getInstance(); try { calendar1.setTime(birthday); Calendar calendar2 = Calendar.getInstance(); calendar2.setTime(new Date()); int age = calendar2.get(Calendar.YEAR) - calendar1.get(Calendar.YEAR); // 还没过生日,周岁减一 if (calendar2.get(Calendar.MONTH) <= calendar1.get(Calendar.MONTH)) { // 还没过生日,周岁减一 if (calendar2.get(Calendar.DAY_OF_MONTH) < calendar1.get(Calendar.DAY_OF_MONTH)) { age -= 1; } } return age < 1 ? 0 : age; } catch (Exception e) { logger.warn("解析身份证年龄出错, idCard=" + idCard, e); return 0; } } /** * 判断是否是合法的身份证 * * @param idCard - 身份证 * @return - 合法返回true */ public static boolean isValidIdcard(String idCard) { if (StringUtils.isBlank(idCard)) { return false; } idCard = idCard.trim(); int len = idCard.length(); if (len != OLD_IDCARD_LENGTH && len != NEW_IDCARD_LENGTH) { return false; } // 判断身份证区域代码 int areaCode = NumberUtils.toInt(idCard.substring(0, 2)); if (!AREA_MAP.containsKey(areaCode)) { return false; } // 把15位身份证转为18位 idCard = len == OLD_IDCARD_LENGTH ? idCard.substring(0, 6) + "19" + idCard.substring(6, 15) : idCard; // 判断身份证除最后一位,是否全是数字 if (!idCard.matches(IDCARD_REGEX)) { return false; } if (!isValidBirthday(idCard)) { return false; } // 验证身份证最后一位校验码 int ret = 0; for (int i = 0; i < len - 1; i++) { ret += NumberUtils.toInt(idCard.charAt(i) + "") * WI[i]; } return idCard.equals(idCard.substring(0, len - 1) + LAST_STR[ret % 11]); } /** * 验证新身份证号码的年龄是否正确 * * @param idCard 身份证号码 * @return 返回是否合法的出身分日期 */ private static boolean isValidBirthday(String idCard) { Date birthday = getNewIdCardBirthday(idCard); if (null == birthday) { return false; } if (birthday.after(new Date())) { return false; } return true; } private static Date getNewIdCardBirthday(String idCard) { String birthdayString = idCard.substring(6, 14); DateFormat format = new SimpleDateFormat("yyyyMMdd"); try { return format.parse(birthdayString); } catch (ParseException e) { return null; } } private static String convertToNewFormatIdCard(String idCard) { if (idCard.length() == OLD_IDCARD_LENGTH) { // 把15位身份证转为18位 return idCard.substring(0, 6) + "19" + idCard.substring(6, 15); } return idCard; } }
package com.bucares.barcode.controller; import java.util.HashMap; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.servlet.ModelAndView; import com.bucares.barcode.service.AvanceService; import com.bucares.barcode.service.MateriaService; import static com.bucares.barcode.URLConstants.APP_VERSION_URL; import static com.bucares.barcode.URLConstants.HEALTH_ENDPOINT_URL; @RestController public class AppController { private static final Logger logger = LoggerFactory.getLogger(AppController.class); // @Autowired // private AvanceService avanceService; @Autowired private MateriaService materiaService; @Value("${build.version}") private String buildVersion; /* @GetMapping("/") public ModelAndView indexAvance() { ModelAndView model = new ModelAndView(); model.addObject("avance", avanceService.getAllAvance()); model.setViewName("indexAvance"); return model; }*/ @GetMapping("/") public ModelAndView indexMateria() { ModelAndView model = new ModelAndView(); model.addObject("materia", materiaService.getAllMateria()); model.setViewName("indexMateria"); return model; } @GetMapping(HEALTH_ENDPOINT_URL) public String health() { return "redirect:/"; } @GetMapping(APP_VERSION_URL) @ResponseBody public ResponseEntity<Map<String, String>> getVersion() { logger.info("Called resource: getVersion"); logger.info("Project version {}", buildVersion); Map<String, String> response = new HashMap<>(); response.put("version", buildVersion); return new ResponseEntity<>(response, HttpStatus.OK); } }
package com.appdear.client; import com.appdear.client.commctrls.BaseActivity; import com.appdear.client.commctrls.SharedPreferencesControl; import com.appdear.client.download.FileDownloaderService; import com.appdear.client.download.SiteInfoBean; import com.appdear.client.exception.ApiException; import com.appdear.client.model.PackageinstalledInfo; import com.appdear.client.service.AppContext; import com.appdear.client.service.AppdearService; import com.appdear.client.service.MyApplication; import com.appdear.client.service.UpdateService; import com.appdear.client.service.Constants; import com.appdear.client.service.api.ApiManager; import com.appdear.client.service.api.ApiUrl; import com.appdear.client.utility.AsyLoadImageService; import com.appdear.client.utility.ChineseConvert; import com.appdear.client.utility.ServiceUtils; import android.app.NotificationManager; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.pm.PackageManager.NameNotFoundException; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.util.Log; /** * 监听程序的卸载和安装 * @author zqm * */ public class NetworkStateReceiver extends BroadcastReceiver { public static boolean netStateDialog = true; @Override public void onReceive(final Context context, final Intent intent) { // 获得网络连接服务 boolean checkState = ServiceUtils.checkNetState(context); if (AppContext.getInstance().isNetState != checkState) netStateDialog = true; AppContext.getInstance().isNetState = checkState; if (AppContext.getInstance().isNetState) { }else{ ((NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE)).cancel(AppdearService.UPDATE_INFO_ID); } // 暂停当前所有正在下载的线程 /*if (!AppContext.getInstance().isNetState) AppContext.getInstance().downloader.downDb.updatePause();*/ this.clearAbortBroadcast(); } }
package fr.formation.spring.museum.controllers.jsp; import java.sql.Date; import java.time.Instant; import java.util.List; import java.util.Optional; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.validation.FieldError; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; import fr.formation.spring.museum.models.Account; import fr.formation.spring.museum.models.RegistrationDTO; import fr.formation.spring.museum.repositories.AccountRepository; import fr.formation.spring.museum.repositories.LocaleRepository; import fr.formation.spring.museum.repositories.RankRepository; @Controller public class SecurityController { private @Autowired AccountRepository accountRepository; private @Autowired RankRepository rankRepository; private @Autowired LocaleRepository localeRepository; @Autowired @Qualifier("passwordEncoder") private PasswordEncoder passwordEncoder; @RequestMapping(value="/logout", method = RequestMethod.GET) public String logoutPage(HttpServletRequest request, HttpServletResponse response) { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); if (auth != null) new SecurityContextLogoutHandler().logout(request, response, auth); return "redirect:/login?logout"; } /*** * Both of these can be handled by adding similar code * to this to WebMvcConfigurerAdapter suclasses: * * @Override * public void addViewControllers(ViewControllerRegistry registry) { * registry.addViewController("/403").setViewName("jsp/403"); * } * */ @GetMapping(value = "/login") public String loginPage(Model model) { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); if (auth != null) model.addAttribute("message", "label.form.login.error.already_logged_in"); return "jsp/login"; } @GetMapping(value = "/register") public String registerPage(Model model) { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); if (auth != null) model.addAttribute("message", "label.form.login.error.already_logged_in"); model.addAttribute("registrationModel", new RegistrationDTO()); model.addAttribute("locales", localeRepository.findAll()); return "jsp/register"; } @PostMapping(value = "/register") public String registerPagePOST(Model model, @ModelAttribute @Validated RegistrationDTO dto, BindingResult result) { model.addAttribute("registrationModel", dto); model.addAttribute("locales", localeRepository.findAll()); if (accountRepository.existsByUsername(dto.getUsername())) { model.addAttribute("error_username", "error.form.register.username_in_use"); return "jsp/register"; } if (accountRepository.existsByEmail(dto.getEmail())) { model.addAttribute("error_mail", "error.form.register.email_in_use"); return "jsp/register"; } if (!result.hasErrors()) { String encryptedPassword = passwordEncoder.encode(dto.getPassword()); Account newAccount = new Account(); newAccount.setPassword(encryptedPassword); newAccount.setUsername(dto.getUsername()); newAccount.setName(dto.getName()); newAccount.setSurname(dto.getSurname()); newAccount.setRegistrationDate(Date.from(Instant.now())); newAccount.setEnabled(true); // TODO: Send confirmation emails that *then* set this to true newAccount.setRank(rankRepository.findByName("USER")); newAccount.setEmail(dto.getEmail()); accountRepository.save(newAccount); return "redirect:/login"; } else { List<FieldError> fieldErrors = result.getFieldErrors(); for (int i = 0; i < fieldErrors.size(); ++i) { System.out.println("error_" + fieldErrors.get(i).getField() + " = " + fieldErrors.get(i).getDefaultMessage()); model.addAttribute("error_" + fieldErrors.get(i).getField(), fieldErrors.get(i).getDefaultMessage()); } } return "jsp/register"; } @GetMapping(value = "/403") public ModelAndView accessDeniedPage(HttpServletRequest request) { ModelAndView mv = new ModelAndView("jsp/403"); mv.addObject("previousPage", getPreviousPageByRequest(request).orElse("/")); return mv; } protected Optional<String> getPreviousPageByRequest(HttpServletRequest request) { return Optional.ofNullable(request.getHeader("Referer")).map(requestUrl -> "redirect:" + requestUrl); } @ExceptionHandler({ UsernameNotFoundException.class }) public ModelAndView usernameNotFound(Exception ex) { ModelAndView mv = new ModelAndView("/login?error"); mv.addObject("error", "error_username_not_found"); return mv; } }
package tech.adrianohrl.stile.control.bean.reports; /** * * @author Adriano Henrique Rossette Leite (contact@adrianohrl.tech) */ public enum AttendanceChartTypes implements ChartType<AttendanceChartTypes> { ATTENDANCE("Horas de trabalho diárias de ", "Horas de Trabalho", "[h]"); private final String title; private final String label; private final String unit; private AttendanceChartTypes(String title, String label, String unit) { this.title = title; this.label = label; this.unit = unit; } @Override public String getTitle() { return title; } @Override public String getLabel() { return label; } @Override public String getUnit() { return unit; } @Override public boolean equals(String unit) { return this.unit.equalsIgnoreCase(unit); } }
package com.gikk.chat.auto; import com.gikk.ChatSingleton; import com.gikk.SystemConfig; import com.gikk.chat.AbstractChatCommand; import com.gikk.chat.conditions.CooldownPerUser; import com.gikk.twirk.types.emote.Emote; import com.gikk.twirk.types.users.TwitchUser; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.stream.Collectors; /** * * @author Gikkman */ public class QuoteCommand extends AbstractChatCommand { private final static String COMMAND_GET = "!quote"; private final static String COMMAND_ADD = "!addquote"; private final Map<Integer, String> quoteMap = new ConcurrentHashMap<>(); private final Set<String> commandWords = new HashSet<>(); private final String currency; public QuoteCommand() { commandWords.add(COMMAND_GET); commandWords.add(COMMAND_ADD); currency = SystemConfig.CURRENCY; addCondition(new CooldownPerUser(60 * 1000)); } @Override public Set<String> getCommandWords() { return commandWords; } @Override public boolean performCommand(String command, TwitchUser sender, String content, List<Emote> emotes) { switch (command) { case COMMAND_GET: return commandGet(content); case COMMAND_ADD: return commandAdd(sender, content, emotes); default: return false; } } private boolean commandGet(String content) { try { Integer index = Integer.parseInt(content); if (quoteMap.containsKey(index)) { ChatSingleton.GET().broadcast(quoteMap.get(index)); return true; } else { return false; } } catch (Exception e) { return false; } } private boolean commandAdd(TwitchUser sender, String content, List<Emote> emotes) { List<String> parts = Arrays.stream(content.split("\\s", 2)) .collect(Collectors.toList()); if (parts.size() < 2) { showAddUsage(); return false; } /** * A correct quote is formated: !quote <USER> "<QUOTE>" * * This block checks that we have a user, and that the quote is * surrounded by "-signs */ String saidByString = parts.get(0).trim(); String quote = parts.get(1).trim(); if (saidByString.isEmpty() || quote.isEmpty()) { showAddUsage(); return false; } //If the quote starts or ends with an emote, we gotta add an extra space, //so that the emote is displayed despite the "s for (Emote e : emotes) { if (quote.startsWith(e.getPattern())) { quote = " " + quote; } if (quote.endsWith(e.getPattern())) { quote = quote + " "; } } if (!quote.startsWith("\"")) { quote = "\"" + quote; } if (!quote.endsWith("\"")) { quote += "\""; } int idx = quoteMap.size() + 1; quoteMap.put(idx, quote + " by " + saidByString); ChatSingleton.GET().broadcast(sender, "Quote added as #" + idx); return true; } private void showAddUsage() { ChatSingleton.GET().broadcast("Usage: " + COMMAND_ADD + "<USER> <QUOTE>"); } }
package jp.co.disney.spplogin.web; import java.text.MessageFormat; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.servlet.ModelAndView; import jp.co.disney.spplogin.exception.ApplicationErrors; import jp.co.disney.spplogin.exception.ApplicationException; import lombok.extern.slf4j.Slf4j; /** * 共通例外ハンドラー * */ @Slf4j @ControllerAdvice public class ExceptionControllerAdvice { @ExceptionHandler(ApplicationException.class) @ResponseStatus(HttpStatus.BAD_REQUEST) public ModelAndView handleApplicationException(ApplicationException ex) { return handleError(ex.getError(), ex, ex.getArgs()); } @ExceptionHandler(RuntimeException.class) @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) public ModelAndView handleRuntimeException(RuntimeException ex) { return handleError(ApplicationErrors.UNEXPECTED, ex, ex.toString()); } private ModelAndView handleError(ApplicationErrors error, Exception ex, Object... args) { String message; if(args != null) { message = MessageFormat.format(error.getMessage(), args); } else { message = error.getMessage(); } log.error(message, ex); return new ModelAndView("common/error") .addObject("errorCode", error.getCode()) .addObject("errorMessage", message); } }
/* * 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 ventanas; import java.awt.event.*; import javax.swing.*; import SecuGen.FDxSDKPro.jni.*; import clases.Conexion; import com.panamahitek.ArduinoException; import com.panamahitek.PanamaHitek_Arduino; import java.awt.Color; import java.awt.Image; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.awt.image.BufferedImage; import java.net.URL; import java.sql.*; import java.text.SimpleDateFormat; import javax.swing.Icon; import javax.swing.ImageIcon; import javax.swing.JOptionPane; import javax.swing.JTable; import javax.swing.WindowConstants; import javax.swing.JFrame; import javax.swing.SwingUtilities; import static jssc.SerialPort.*; import java.util.logging.Level; import java.util.logging.Logger; import java.util.Date; import jssc.SerialPort; import jssc.SerialPortException; /** * * @author alex_ */ public class Ingreso extends javax.swing.JFrame { private long deviceName; private long devicePort; private JSGFPLib fplib = null; private long ret; private boolean bLEDOn; private byte[] regMin1 = new byte[400]; private byte[] regMin2 = new byte[400]; private byte[] vrfMin = new byte[400]; private byte[] m = new byte[400]; private SGDeviceInfoParam deviceInfo = new SGDeviceInfoParam(); private BufferedImage imgRegistration1; private BufferedImage imgRegistration2; private BufferedImage imgVerification; private boolean r1Captured = false; private boolean r2Captured = false; private boolean v1Captured = false; private static int MINIMUM_QUALITY = 60; //User defined private static int MINIMUM_NUM_MINUTIAE = 20; //User defined private static int MAXIMUM_NFIQ = 2; //User defined private boolean aux = true; private boolean cliente_reconocido = false; private boolean servicio_activo = false; private boolean reingreso = false; PanamaHitek_Arduino ino; Timer timer; int short_delay = 3000; /** * Creates new form Ingreso */ public Ingreso() { setIconImage(getIconImage()); initComponents(); ino = new PanamaHitek_Arduino(); try { ino.arduinoTX("COM4", 9600); } catch (Exception e) { System.out.println("error arduino"); } setTitle("Xtreme Gym: Sistema de Ingreso"); setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); setSize(1500, 800); setResizable(false); setLocationRelativeTo(null); URL url = Ingreso.class.getResource("/wallpaperPrincipal.jpg"); ImageIcon wallpaper = new ImageIcon(url); Icon icono = new ImageIcon(wallpaper.getImage().getScaledInstance(jLabel_Wallpaper.getWidth(), jLabel_Wallpaper.getHeight(), Image.SCALE_DEFAULT)); jLabel_Wallpaper.setIcon(icono); this.repaint(); fplib = new JSGFPLib(); ret = fplib.Init(SGFDxDeviceName.SG_DEV_AUTO); if ((fplib != null) && (ret == SGFDxErrorCode.SGFDX_ERROR_NONE)) { this.jLabelStatus.setText("JSGFPLib Initialization Success"); ret = fplib.OpenDevice(SGPPPortAddr.AUTO_DETECT); if (ret != SGFDxErrorCode.SGFDX_ERROR_NONE) { this.jLabelStatus.setText("OpenDevice() Success [" + ret + "]"); ret = fplib.GetDeviceInfo(deviceInfo); if (ret == SGFDxErrorCode.SGFDX_ERROR_NONE) { imgRegistration1 = new BufferedImage(deviceInfo.imageWidth, deviceInfo.imageHeight, BufferedImage.TYPE_BYTE_GRAY); imgRegistration2 = new BufferedImage(deviceInfo.imageWidth, deviceInfo.imageHeight, BufferedImage.TYPE_BYTE_GRAY); imgVerification = new BufferedImage(deviceInfo.imageWidth, deviceInfo.imageHeight, BufferedImage.TYPE_BYTE_GRAY); } else this.jLabelStatus.setText("GetDeviceInfo() Error [" + ret + "]"); } else this.jLabelStatus.setText("OpenDevice() Error [" + ret + "]"); } else{ this.jLabelStatus.setText("JSGFPLib Initialization Failed"); } } @Override public Image getIconImage() { URL url = Ingreso.class.getResource("/icon.png"); Image retValue = Toolkit.getDefaultToolkit().getImage(url); return retValue; } /** * 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() { jLabel_NombreUsuario = new javax.swing.JLabel(); d = new javax.swing.JLabel(); mensaje = new javax.swing.JLabel(); date = new javax.swing.JLabel(); jLabelStatus = new javax.swing.JLabel(); jLabelVerifyImage = new javax.swing.JLabel(); jProgressBarV1 = new javax.swing.JProgressBar(); jLabel_footer = new javax.swing.JLabel(); name = new javax.swing.JLabel(); n = new javax.swing.JLabel(); obs = new javax.swing.JLabel(); dias = new javax.swing.JLabel(); jLabel_Wallpaper = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setMaximizedBounds(new java.awt.Rectangle(2147483647, 2147483647, 2147483647, 2147483647)); setSize(new java.awt.Dimension(2147483647, 2147483647)); addWindowListener(new java.awt.event.WindowAdapter() { public void windowClosed(java.awt.event.WindowEvent evt) { formWindowClosed(evt); } public void windowOpened(java.awt.event.WindowEvent evt) { formWindowOpened(evt); } }); getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); jLabel_NombreUsuario.setFont(new java.awt.Font("Arial", 1, 60)); // NOI18N jLabel_NombreUsuario.setForeground(new java.awt.Color(255, 255, 255)); jLabel_NombreUsuario.setText("Sistema de ingreso"); jLabel_NombreUsuario.addComponentListener(new java.awt.event.ComponentAdapter() { public void componentShown(java.awt.event.ComponentEvent evt) { jLabel_NombreUsuarioComponentShown(evt); } }); getContentPane().add(jLabel_NombreUsuario, new org.netbeans.lib.awtextra.AbsoluteConstraints(470, 10, -1, -1)); d.setFont(new java.awt.Font("Arial", 0, 48)); // NOI18N d.setForeground(new java.awt.Color(204, 204, 204)); d.setText("jLabel1"); getContentPane().add(d, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 230, -1, -1)); mensaje.setFont(new java.awt.Font("Arial", 0, 80)); // NOI18N mensaje.setForeground(new java.awt.Color(255, 255, 255)); mensaje.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); mensaje.setText("jLabel1"); getContentPane().add(mensaje, new org.netbeans.lib.awtextra.AbsoluteConstraints(430, 410, -1, -1)); date.setFont(new java.awt.Font("Arial", 0, 60)); // NOI18N date.setForeground(new java.awt.Color(255, 255, 255)); date.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); date.setText("jLabel1"); getContentPane().add(date, new org.netbeans.lib.awtextra.AbsoluteConstraints(470, 210, -1, -1)); jLabelStatus.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N jLabelStatus.setText("Click Initialize Button ..."); jLabelStatus.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.LOWERED)); getContentPane().add(jLabelStatus, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 600, 1420, 30)); jLabelVerifyImage.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.LOWERED)); jLabelVerifyImage.setMinimumSize(new java.awt.Dimension(130, 150)); jLabelVerifyImage.setPreferredSize(new java.awt.Dimension(130, 150)); getContentPane().add(jLabelVerifyImage, new org.netbeans.lib.awtextra.AbsoluteConstraints(1220, 100, -1, -1)); jProgressBarV1.setForeground(new java.awt.Color(0, 51, 153)); getContentPane().add(jProgressBarV1, new org.netbeans.lib.awtextra.AbsoluteConstraints(1220, 250, 130, -1)); jLabel_footer.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N jLabel_footer.setText(" Xtreme Gym ®"); getContentPane().add(jLabel_footer, new org.netbeans.lib.awtextra.AbsoluteConstraints(510, 650, -1, -1)); name.setFont(new java.awt.Font("Arial", 0, 60)); // NOI18N name.setForeground(new java.awt.Color(255, 255, 255)); name.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); name.setText("jLabel1"); getContentPane().add(name, new org.netbeans.lib.awtextra.AbsoluteConstraints(470, 120, -1, -1)); n.setFont(new java.awt.Font("Arial", 0, 48)); // NOI18N n.setForeground(new java.awt.Color(204, 204, 204)); n.setText("jLabel1"); getContentPane().add(n, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 130, -1, -1)); obs.setFont(new java.awt.Font("Dialog", 0, 48)); // NOI18N obs.setForeground(new java.awt.Color(255, 255, 255)); obs.setText("jLabel1"); getContentPane().add(obs, new org.netbeans.lib.awtextra.AbsoluteConstraints(490, 510, -1, -1)); dias.setFont(new java.awt.Font("Dialog", 0, 60)); // NOI18N dias.setForeground(new java.awt.Color(255, 255, 255)); dias.setText("jLabel1"); getContentPane().add(dias, new org.netbeans.lib.awtextra.AbsoluteConstraints(470, 310, -1, -1)); getContentPane().add(jLabel_Wallpaper, new org.netbeans.lib.awtextra.AbsoluteConstraints(-70, 0, 1540, 730)); pack(); }// </editor-fold>//GEN-END:initComponents private void jLabel_NombreUsuarioComponentShown(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_jLabel_NombreUsuarioComponentShown }//GEN-LAST:event_jLabel_NombreUsuarioComponentShown private void formWindowOpened(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowOpened ActionListener taskPerformer = new ActionListener() { public void actionPerformed(ActionEvent evt) { huella(); if (cliente_reconocido && servicio_activo && !reingreso){ try { ino.sendData("1"); } catch (ArduinoException | SerialPortException ex) { Logger.getLogger(Ingreso.class.getName()).log(Level.SEVERE, null, ex); } } cliente_reconocido = false; servicio_activo = false; reingreso = false; } }; timer = new Timer(short_delay ,taskPerformer); timer.start(); }//GEN-LAST:event_formWindowOpened private void formWindowClosed(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosed try { ino.killArduinoConnection(); } catch (Exception e) { } }//GEN-LAST:event_formWindowClosed /** * @param args the command line arguments */ public void dormir () { long delay = 5000; try { timer.setDelay(short_delay); }catch(Exception e){ System.out.println("Error dormir"); }; } public void huella(){ int[] quality = new int[1]; int[] numOfMinutiae = new int[1]; byte[] imageBuffer1 = ((java.awt.image.DataBufferByte) imgVerification.getRaster().getDataBuffer()).getData(); long iError = SGFDxErrorCode.SGFDX_ERROR_NONE; iError = fplib.GetImageEx(imageBuffer1,short_delay, 0, 50); fplib.GetImageQuality(deviceInfo.imageWidth, deviceInfo.imageHeight, imageBuffer1, quality); this.jProgressBarV1.setValue(quality[0]); SGFingerInfo fingerInfo = new SGFingerInfo(); fingerInfo.FingerNumber = SGFingerPosition.SG_FINGPOS_LI; fingerInfo.ImageQuality = quality[0]; fingerInfo.ImpressionType = SGImpressionType.SG_IMPTYPE_LP; fingerInfo.ViewNumber = 1; if (iError == SGFDxErrorCode.SGFDX_ERROR_NONE) { this.jLabelVerifyImage.setIcon(new ImageIcon(imgVerification.getScaledInstance(130,150,Image.SCALE_DEFAULT))); if (quality[0] < MINIMUM_QUALITY) this.jLabelStatus.setText("GetImageEx() Realizado [" + ret + "] pero la calidad es: [" + quality[0] + "]. Por favor, intente nuevamente"); else { this.jLabelStatus.setText("GetImageEx() Realizado [" + ret + "]"); iError = fplib.CreateTemplate(fingerInfo, imageBuffer1, vrfMin); if (iError == SGFDxErrorCode.SGFDX_ERROR_NONE) { long nfiqvalue; long ret2 = fplib.GetImageQuality(deviceInfo.imageWidth, deviceInfo.imageHeight, imageBuffer1, quality); nfiqvalue = fplib.ComputeNFIQ(imageBuffer1, deviceInfo.imageWidth, deviceInfo.imageHeight); ret2 = fplib.GetNumOfMinutiae(SGFDxTemplateFormat.TEMPLATE_FORMAT_SG400, vrfMin, numOfMinutiae); if ((quality[0] >= MINIMUM_QUALITY) && (nfiqvalue <= MAXIMUM_NFIQ) && (numOfMinutiae[0] >= MINIMUM_NUM_MINUTIAE)) { this.jLabelStatus.setText("Captura cerificada PASS QC. Quality[" + quality[0] + "] NFIQ[" + nfiqvalue + "] Minutiae[" + numOfMinutiae[0] + "]"); v1Captured = true; long secuLevel = 5; boolean[] matched = new boolean[1]; int id = 0; String nombre, observaciones; matched[0] = false; try { Connection cn = Conexion.conectar(); PreparedStatement pst = cn.prepareStatement("select nombre_cliente, id_cliente, huella_id from clientes "); ResultSet rs = pst.executeQuery(); while (rs.next()) { m = rs.getBytes("huella_id"); iError = fplib.MatchTemplate(m, vrfMin, secuLevel, matched); if (iError == SGFDxErrorCode.SGFDX_ERROR_NONE){ if (matched[0]){ cliente_reconocido = true; this.jLabelStatus.setText( "Cliente reconocido (1er intento)"); id = rs.getInt("id_cliente"); nombre = rs.getString("nombre_cliente"); pst = cn.prepareStatement("select *, datediff(fecha_fin, CURRENT_DATE) as dias FROM equipos WHERE id_cliente=? and fecha_fin>=CURRENT_DATE"); pst.setInt(1, id); rs = pst.executeQuery(); if (rs.next()){ servicio_activo=true; //Verificación de reingreso PreparedStatement pst1 = cn.prepareStatement("SELECT COUNT(id_cliente ) AS cuenta FROM registro WHERE id_cliente=? and fecha_registro=(CURRENT_DATE)"); pst1.setInt(1, id); ResultSet rs1 = pst1.executeQuery(); if (rs1.next() && rs1.getInt("cuenta")==0) { System.out.println("cliente reconocido: " + nombre); pst1 = cn.prepareStatement("INSERT INTO registro values (?,?,CURRENT_DATE)"); pst1.setInt(1, 0); pst1.setInt(2, id); pst1.executeUpdate(); matched[0] = false; reingreso = false; SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd"); String fecha = f.format(rs.getDate("fecha_fin")); Integer dias = rs.getInt("dias"); observaciones = rs.getString("observaciones"); imprimir_cliente(nombre, fecha, dias.toString() , observaciones); } else { limpiar(nombre, "Ingreso Restringido"); reingreso = true; } cn.close(); Timer t2 = new javax.swing.Timer(5000, new ActionListener(){ public void actionPerformed(ActionEvent e){ limpiar("", "Identifíquese"); } }); t2.start(); t2.setRepeats(false); } else { this.jLabelStatus.setText( "Mensualidad vencida! :c "); limpiar(nombre, "Mensualidad vencida"); } break; } else { this.jLabelStatus.setText( "Cliente no registrado. Por favor, solicite ayuda."); limpiar("","No Registrado"); } } else { System.out.println("Error en la lectura de la huella dactilar. Por favor, intente nuevamente."); limpiar("", "Intente nuevamente"); } } } catch (SQLException e) { System.err.println("Error en el llenado de la tabla."); } } else { this.jLabelStatus.setText("Error en la lectura QC. Quality[" + quality[0] + "] NFIQ[" + nfiqvalue + "] Minutiae[" + numOfMinutiae[0] + "]"); limpiar("", "Intente nuevamente"); } } else this.jLabelStatus.setText("CreateTemplate() Error : " + iError); } } else{ this.jLabelStatus.setText("Bien venido. Coloque su dedo en el sensor antes de ingresar"); limpiar("","Identifíquese"); } } public void imprimir_cliente (String nombre, String fecha, String dia, String observaciones){ n.setText("Cliente: "); d.setText("Vigencia: "); name.setText(nombre); date.setText(fecha); mensaje.setText("Bienvenido!!"); obs.setText("Observaciones: " + observaciones); dias.setText("Días restantes: " + dia); } public void limpiar (String nombre, String msg){ n.setText(""); d.setText(""); name.setText(nombre); date.setText(""); mensaje.setText(msg); obs.setText(""); dias.setText(""); } 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(Ingreso.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(Ingreso.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(Ingreso.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(Ingreso.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> SwingUtilities.invokeLater(() -> new Ingreso().setVisible(true)); /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new Ingreso().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JLabel d; private javax.swing.JLabel date; private javax.swing.JLabel dias; private javax.swing.JLabel jLabelStatus; private javax.swing.JLabel jLabelVerifyImage; private javax.swing.JLabel jLabel_NombreUsuario; private javax.swing.JLabel jLabel_Wallpaper; private javax.swing.JLabel jLabel_footer; private javax.swing.JProgressBar jProgressBarV1; private javax.swing.JLabel mensaje; private javax.swing.JLabel n; private javax.swing.JLabel name; private javax.swing.JLabel obs; // End of variables declaration//GEN-END:variables }
package hashimotonet; import java.util.List; import twitter4j.Status; import twitter4j.Twitter; import twitter4j.TwitterException; import twitter4j.TwitterFactory; public class MyFirstTweet { private void output() throws TwitterException { // このファクトリインスタンスは再利用可能でスレッドセーフです Twitter twitter = TwitterFactory.getSingleton(); Status status = twitter.updateStatus("laststatus"); System.out.println("Successfully updated the status to [" + status.getText() + "]."); } private void getTimeline() throws Exception { // このファクトリインスタンスは再利用可能でスレッドセーフです Twitter twitter = TwitterFactory.getSingleton(); List<Status> statuses = twitter.getHomeTimeline(); System.out.println("Showing home timeline."); for (Status status : statuses) { System.out.println(status.getUser().getName() + ":" + status.getText()); } } public static void main(String args[]) { MyFirstTweet tweet = new MyFirstTweet(); try { tweet.getTimeline(); tweet.output(); } catch(Exception e) { e.printStackTrace(); } } }
package Praktikum; /** * * @author Master */ public class DaftarGaji { public Pegawai[] listPegawai; private int jumlahPegawai = 0; public DaftarGaji(int n) { listPegawai = new Pegawai[n]; } public void addPegawai(Pegawai pegawai){ listPegawai[jumlahPegawai] = pegawai; jumlahPegawai++; } public void printSemuaGaji(){ for (int i = 0; i < jumlahPegawai; i++) { String nama = listPegawai[i].getNama(); int gaji = listPegawai[i].getGaji(); System.out.println(nama + " mendapatkan gaji : " + gaji); } } }
import java.util.Scanner; /** * Этот анализатор считывает пользовательский ввод и преобразует его в * Команды для приключенческой игры. При каждом звонке * он читает строку с консоли и пытается это сделать * интерпретировать команду из двух слов. * он возвращает команду как объект команды класса. * * Парсер имеет набор известных команд. он * сравнивает вход с этими командами. Когда вход * не содержит известной команды, тогда парсер возвращается * как неизвестная команда отмеченный объект назад * * @author (Kydyrbek uulu Bakai,Nurmanbetov Bekbolot) * @version (04.05.2018) */ class Parser { private Befehlswoerter befehle; // содержит действительные командные слова private Scanner leser; // Поставщик для введенных команд /** * Создает парсер, который читает команды с консоли. */ public Parser() { befehle = new Befehlswoerter(); leser = new Scanner(System.in); } /** * @return Следующая команда пользователя. */ public Befehl liefereBefehl() { String eingabezeile; // для всей строки ввода String wort1 = null; String wort2 = null; System.out.print("> "); // подсказка eingabezeile = leser.nextLine(); // Найдите до двух слов в строке Scanner zerleger = new Scanner(eingabezeile); if(zerleger.hasNext()) { wort1 = zerleger.next(); // читаем первое слово if (zerleger.hasNext()) { wort2 = zerleger.next();// читаем второе слово // Примечание. Мы игнорируем остальную часть строки ввода. } } // Теперь проверьте, известна ли команда. Если да, сгенерируйте // мы генерируем соответствующий объект команды. Если нет, мы генерируем // неизвестную команду с 'null'. if(befehle.istBefehl(wort1)) { return new Befehl(wort1, wort2); } else { return new Befehl(null, wort2); } } }
package com.groovybot.engine; public interface GroovyShellEngine extends GroovyEngine { }
package conversores; import controle.TipoControle; import javax.faces.component.UIComponent; import javax.faces.context.FacesContext; import javax.faces.convert.Converter; import javax.faces.convert.FacesConverter; import modelo.Tipo; /** * * @author mathe */ @FacesConverter(forClass = Tipo.class) public class TipoConverter implements Converter { @Override public Object getAsObject(FacesContext context, UIComponent component, String value) { if (value == null || value.length() == 0) { return null; } Long id = new Long(value); TipoControle controle = (TipoControle) context.getApplication(). getELResolver().getValue(context.getELContext(), null, "tipoControle"); return controle.buscarTipoPorId(id); } @Override public String getAsString(FacesContext arg0, UIComponent arg1, Object object) { if (object == null) { return null; } if (object instanceof Tipo) { Tipo tipo = (Tipo) object; return tipo.getID() == null ? "" : tipo.getID().toString(); } else { throw new IllegalArgumentException("Objeto é do tipo "+ object.getClass().getName()); } } }
package com.company; import javax.swing.*; import javax.swing.border.BevelBorder; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class FirstForm extends Form{ private JFrame frame; private JTextArea area; //ссылка на текстовое полк private JTextField nameTextField; private JTextField famyliTextField; private JLabel resultTextField; private JPanel statusPanel; private JLabel statusLabel; public JButton button; public FirstForm(Logic logic){ super(logic); createFrame(); initElements(); } public void addToTextArea(String text){ area.append(text); } public void setStatusLabel(String text) { this.statusLabel.setText(text); } public String getNameTextField() { return nameTextField.getText(); } public String getFamyliTextField() { return famyliTextField.getText(); } public void setResultTextField(String resultTextField) { this.resultTextField.setText(resultTextField); } private void createFrame(){ //создает окно графического интерфейса frame = new JFrame("Лабораторная 1"); frame.setSize(900, 600); // выход из приложения по закрытию //frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); } public void show(){ //делает окно видимым frame.setVisible(true); } private void initElements() { //создает необходимые элементы внутри окна Container mainContainer = frame.getContentPane(); mainContainer.setLayout(new BorderLayout()); Box panel = Box.createHorizontalBox(); //контейнер, в котором элементы располагаются // горизонтально // поле для вывода лога выполнения задач area = new JTextArea( 50, 80); area.setLineWrap(true); // параметры переноса слов area.setWrapStyleWord(true); Box leftPanel = createLeftPanel(); // создаем левую панель в другом методе mainContainer.add(leftPanel, BorderLayout.WEST); // эта панель будет слева //строка состояния statusPanel = new JPanel(); statusPanel.setBorder(new BevelBorder(BevelBorder.LOWERED)); frame.add(statusPanel, BorderLayout.SOUTH); statusPanel.setPreferredSize(new Dimension(frame.getWidth(), 16)); statusPanel.setLayout(new BoxLayout(statusPanel, BoxLayout.X_AXIS)); //элементы строки состояния statusLabel = new JLabel(); statusLabel.setHorizontalAlignment(SwingConstants.LEFT); statusPanel.add(statusLabel); panel.add(new JScrollPane(area)); //panel.add (progressBar) ; mainContainer.add(panel); } private Box createLeftPanel() { Box panel = Box.createVerticalBox(); // вертикальный Box // Box это контейнер, в котором элементы выстраиваются в одном порядке JLabel title = new JLabel("<html>Проведение эксперимента</html>"); // чтобы добавить перевод строки в тексте, нужно писать в тегах <html> title.setFont(new Font(null, Font.BOLD, 12)); // изменяем шрифт panel.add(title); panel.add(Box.createVerticalStrut(20)); //в Box можно добавлять отступы panel.add(new JLabel("Имя")); nameTextField = new JTextField(""); // поле ввода названия nameTextField.setMaximumSize(new Dimension(300, 30)); // чтобы не был слишком большим panel.add(nameTextField); panel.add(new JLabel("Фамилия")); famyliTextField = new JTextField(""); famyliTextField.setMaximumSize(new Dimension(300, 30)); // чтобы не был слишком большим panel.add(famyliTextField); panel.add(new JLabel("результат:")); resultTextField = new JLabel(""); panel.add(resultTextField); panel.add(Box.createVerticalGlue()); // также в Box можно добавлять заполнитель пустого места button = new JButton("Пуск"); // Кнопка panel.add(button); button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { logic.click(0); } }); return panel; } }
package com.ic.SysAgenda.repository; import org.springframework.data.repository.CrudRepository; import com.ic.SysAgenda.model.Pessoa; public interface PessoaRepository extends CrudRepository<Pessoa, Long>{ }
package guo.ping.taotao.search.mapper; import guo.ping.taotao.search.pojo.SearchItem; import java.util.List; /** * Solr服务的导入数据 */ public interface ItemMapper { List<SearchItem> getItemList(); }
package rent.common.entity; import javax.persistence.*; /** * Помещение */ @Entity @Table(name = ApartmentEntity.TABLE_NAME, indexes = { @Index(columnList = ApartmentEntity.Columns.ID), @Index(columnList = ApartmentEntity.Columns.BUILDING), @Index(columnList = ApartmentEntity.Columns.APARTMENT), }) public class ApartmentEntity extends AbstractEntity { public static final String TABLE_NAME = "address_apartments"; public interface Columns extends AbstractEntity.Columns { String BUILDING = "building_id"; String ENTRANCE = "entrance"; String FLOOR = "floor"; String APARTMENT = "apartment"; String APARTMENT_NUMBER = "apartment_number"; String APARTMENT_LETTER = "apartment_letter"; String TOTAL_AREA = "total_area"; String LIVING_AREA = "living_area"; String ROOMS_NUMBER = "rooms_number"; } /** * строение */ @JoinColumn(name = Columns.BUILDING) @ManyToOne(fetch = FetchType.LAZY) private BuildingEntity building; /** * подъезд */ @Column(name = Columns.ENTRANCE) private Integer entrance; /** * этаж */ @Column(name = Columns.FLOOR) private Integer floor; /** * квартира */ @Column(name = Columns.APARTMENT) private String apartment; /** * номер квартиры */ @Column(name = Columns.APARTMENT_NUMBER) private Integer apartmentNumber; /** * литера квартиры */ @Column(name = Columns.APARTMENT_LETTER) private String apartmentLetter; /** * общая площадь */ @Column(name = Columns.TOTAL_AREA) private Double totalArea; /** * жилая площадь */ @Column(name = Columns.LIVING_AREA) private Double livingArea; /** * кол-во комнат */ @Column(name = Columns.ROOMS_NUMBER) private Integer roomsNumber; public BuildingEntity getBuilding() { return building; } public void setBuilding(BuildingEntity building) { this.building = building; } public Integer getEntrance() { return entrance; } public void setEntrance(Integer entrance) { this.entrance = entrance; } public Integer getFloor() { return floor; } public void setFloor(Integer floor) { this.floor = floor; } public String getApartment() { return apartment; } public void setApartment(String apartment) { this.apartment = apartment; } public Integer getApartmentNumber() { return apartmentNumber; } public void setApartmentNumber(Integer apartmentNumber) { this.apartmentNumber = apartmentNumber; } public String getApartmentLetter() { return apartmentLetter; } public void setApartmentLetter(String apartmentLetter) { this.apartmentLetter = apartmentLetter; } public Double getTotalArea() { return totalArea; } public void setTotalArea(Double totalArea) { this.totalArea = totalArea; } public Double getLivingArea() { return livingArea; } public void setLivingArea(Double livingArea) { this.livingArea = livingArea; } public Integer getRoomsNumber() { return roomsNumber; } public void setRoomsNumber(Integer roomsNumber) { this.roomsNumber = roomsNumber; } }
package com.services.utils.thread; import java.util.concurrent.*; /** * 异步执行类 */ public final class SyncExcutor { private static final int corePoolSize = 100;//核心线程数量 private static final int maximumPoolSize = 1000;//最大线程数量 private static final int CAPACITY = 1000;//队列任务最大数量 private static final long keepAliveTime = 60L;//超过核心线程最大空闲时间,过了空闲时间就回收 public static final ThreadPoolExecutor pool = new ThreadPoolExecutor( corePoolSize, maximumPoolSize, keepAliveTime, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(CAPACITY)); static { //是否允许核心线程空闲退出 默认false pool.allowCoreThreadTimeOut(true); } /*** * 异步执行关心执行结果 * * @param task * @return */ public static Future<?> excute(Callable<?> task) { try { if (null == task) { return null; } return pool.submit(task); } catch (Exception e) { e.printStackTrace(); } return null; } /*** * 异步执行不需要关心执行结果 * * @param taskList */ public static void excute(Runnable... taskList) { if (null == taskList) { return; } for (Runnable task : taskList) { pool.execute(task); } } /*** * 得到异步执行结果 * * @param future * @param timeOut 超时设置 单位毫秒 * @return * @throws RuntimeException */ public static Object getExcuteResult(Future<?> future, long timeOut) throws RuntimeException { if (null == future) { return null; } try { return future.get(timeOut, TimeUnit.MILLISECONDS); } catch (InterruptedException e) { throw new RuntimeException(SyncExcutor.class + " 中断异常"); } catch (ExecutionException e) { throw new RuntimeException(SyncExcutor.class + " 执行异常"); } catch (TimeoutException e) { throw new RuntimeException(SyncExcutor.class + " 超时异常"); } } /*** * 得到异步执行结果 默认超时时间 10 秒 * * @param future * @return * @throws RuntimeException */ public static Object getExcuteResult(Future<?> future) throws RuntimeException { return getExcuteResult(future, 10000L); } public static void shutDown() { if (!pool.isShutdown()) { pool.shutdown(); } } }
package com.e6soft.bpm.action; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.beans.factory.NoSuchBeanDefinitionException; import com.e6soft.api.bpm.BpmAction; import com.e6soft.api.bpm.BpmInterface; import com.e6soft.api.bpm.dto.BpmFormData; import com.e6soft.api.form.FormFilter; import com.e6soft.core.util.ApplicationContextUtil; public class EndAction implements BpmAction{ public static final Log log = LogFactory.getLog(EndAction.class); @Override public void execute(BpmFormData bpmFormData) { BpmInterface bpmInterface = ApplicationContextUtil.getContext().getBean(BpmInterface.class); String businessFormCode = bpmInterface.getBusinessFormCodeById(bpmFormData.getBpmRunInfo().getFormId()); try{ FormFilter formFilter = (FormFilter)ApplicationContextUtil.getContext().getBean(businessFormCode+"Filter"); formFilter.saveFormData(bpmFormData); }catch(NoSuchBeanDefinitionException e){ log.info("EndAction Filter error ",e); } } }
package app.com.example.ozgur.sunny; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.preference.PreferenceManager; import android.support.v7.app.ActionBarActivity; import android.view.Menu; import android.view.MenuItem; public class MainActivity extends ActionBarActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); if (savedInstanceState == null) { getSupportFragmentManager().beginTransaction() .add(R.id.container, new ForecastFragment()) .commit(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. switch(item.getItemId()) { case R.id.action_settings: Intent intent = new Intent(this, SettingsActivity.class); startActivity(intent); return true; case R.id.action_test: Intent intent2 = new Intent(this, TestActivity.class); startActivity(intent2); return true; case R.id.action_map: String zipCode = PreferenceManager.getDefaultSharedPreferences(this).getString(getString(R.string.pref_location_key), getString(R.string.pref_location_default)); Uri loc = Uri.parse("geo:0,0?").buildUpon() .appendQueryParameter("q",zipCode).build(); showMap(loc); return true; default: return super.onOptionsItemSelected(item); } } public void showMap(Uri geoLocation) { Intent intent = new Intent(Intent.ACTION_VIEW); intent.setData(geoLocation); if (intent.resolveActivity(getPackageManager()) != null) { startActivity(intent); } } }
package com.vilio.nlbs.bms.dao; import java.util.List; import java.util.Map; /** * Created by dell on 2017/7/11/0011. */ public interface BmsDictionariesDao { public List<Map> queryDictionariesByType(String type) throws Exception; }
package com.tencent.mm.plugin.appbrand.dynamic.d; import android.os.Bundle; import android.os.Parcelable; import com.tencent.mm.ipcinvoker.f; import com.tencent.mm.model.u.b; import com.tencent.mm.plugin.appbrand.collector.CollectSession; import com.tencent.mm.plugin.appbrand.collector.c; import com.tencent.mm.plugin.appbrand.dynamic.h.d; import org.json.JSONObject; class b$a implements Runnable { String fvT; JSONObject fvU; b fvV; com.tencent.mm.u.b.b$a fvW; b fvX; String process; private b$a() { } /* synthetic */ b$a(byte b) { this(); } public final void run() { synchronized (this.fvX) { this.fvX.p(this.fvV.sF("lastTime"), Long.valueOf(System.currentTimeMillis())); } Parcelable bundle = new Bundle(); bundle.putString("viewId", this.fvT); bundle.putString("jsApiInvokeData", this.fvU.toString()); String j = d.j(this.fvU); CollectSession aZ = c.aZ(j, "after_jsapi_invoke"); bundle.putString("__session_id", j); bundle.putParcelable("__cost_time_session", aZ); f.a(this.process, bundle, b.b.class, new com.tencent.mm.ipcinvoker.c<Bundle>() { public final /* synthetic */ void at(Object obj) { Bundle bundle = (Bundle) obj; b$a.this.fvW.aA(b$a.this.fvV.a(bundle.getBoolean("ret"), bundle.getString("reason", ""), null)); } }); } }
public abstract class Account{ protected String owner; protected double balance; protected int IBAN; public Account(String owner,double bal,int ban){ this.owner=owner; balance=bal; IBAN=ban;} public double deposit(double amount){ balance+=amount; System.out.println("The current balance is: "+balance); return balance;} public abstract double withdraw(double amount); public abstract void compoundIntrest(); public String toString(){ return "Owner: "+owner+"\nBalance: "+balance+"\nIBAN: "+IBAN;}}
package com.farhath.web; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.farhath.web.dao.DatabaseConnector; import com.farhath.web.model.SignupModel; /** * Servlet implementation class SignupContainer */ public class SignupContainer extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public SignupContainer() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub response.getWriter().append("Served at: ").append(request.getContextPath()); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub DatabaseConnector dbc = new DatabaseConnector(); dbc.connect(); String fname, lname, address, credit_card, gender, phone, email, password1, password2; password1=request.getParameter("password"); password2=request.getParameter("password2"); if(password1.equals(password2)){ fname=request.getParameter("fname"); lname=request.getParameter("lname"); address=request.getParameter("address"); credit_card=request.getParameter("ccard"); gender=request.getParameter("gender"); phone=request.getParameter("phone"); email=request.getParameter("email"); SignupModel sm = new SignupModel(fname, lname, address, credit_card, gender, phone, email, password1); int result = dbc.signup(sm); //PrintWriter pw = response.getWriter(); //pw.println(sm.fname+" " + sm.gender); response.sendRedirect("home.jsp"); }else{ response.sendError(401,"Passwords donot match"); } } }
package co.nos.noswallet.ui.home.adapter; import android.content.Context; import android.graphics.drawable.Drawable; import android.support.annotation.DrawableRes; import android.support.graphics.drawable.VectorDrawableCompat; import android.support.v7.widget.RecyclerView; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import co.nos.noswallet.NOSApplication; import co.nos.noswallet.R; import co.nos.noswallet.network.nosModel.AccountHistory; import co.nos.noswallet.network.websockets.currencyFormatter.CryptoCurrencyFormatter; public class HistoryViewHolder extends RecyclerView.ViewHolder { ImageView icon; TextView balance, account; View rootView; public HistoryViewHolder(View itemView, @DrawableRes int resId) { super(itemView); rootView = itemView.findViewById(R.id.item_history_root); if (NOSApplication.isBelowLollipop()) { Context context = itemView.getContext(); final Drawable drawable = VectorDrawableCompat.create(context.getResources(), resId, context.getTheme()); rootView.setBackground(drawable); } else { rootView.setBackgroundResource(resId); } icon = itemView.findViewById(R.id.item_send_receive_icon); balance = itemView.findViewById(R.id.item_history_balance); account = itemView.findViewById(R.id.item_history_account); } public void bind(AccountHistory accountHistory, CryptoCurrencyFormatter currencyFormatter) { if (accountHistory.isPending()) { icon.setImageResource(R.drawable.sync); } else if (accountHistory.isSend()) { icon.setImageResource(R.drawable.ic_send); icon.setRotation(180); } else { icon.setImageResource(R.drawable.ic_receive); icon.setRotation(0); } balance.setText(currencyFormatter.rawtoUiWithTicker(accountHistory.amount)); account.setText(currencyFormatter.createShortAdddressForRepresentation(accountHistory.account)); } }
package com.tt.miniapp.msg; import com.tt.frontendapiinterface.a; import com.tt.frontendapiinterface.b; import com.tt.miniapp.thread.ThreadUtil; import com.tt.miniapp.titlebar.TitleBarControl; import com.tt.miniapphost.util.DebugUtil; import com.tt.option.e.e; import org.json.JSONException; import org.json.JSONObject; public class ApiSetMenuButtonVisibilityCtrl extends b { public ApiSetMenuButtonVisibilityCtrl(String paramString, int paramInt, e parame) { super(paramString, paramInt, parame); } public void act() { try { final JSONObject jsonObject = new JSONObject(this.mArgs); ThreadUtil.runOnUIThread(new Runnable() { public void run() { TitleBarControl.getInst().forceSetCapsuleButtonState(jsonObject.optBoolean("visible", true)); ApiSetMenuButtonVisibilityCtrl.this.callbackOk(); } }); return; } catch (JSONException jSONException) { DebugUtil.outputError("ApiSetMenuButtonVisibilityCtrl", new Object[] { jSONException }); callbackFail(a.a(this.mArgs)); return; } } public String getActionName() { return "setMenuButtonVisibility"; } } /* Location: C:\Users\august\Desktop\tik\df_miniapp\classes.jar!\com\tt\miniapp\msg\ApiSetMenuButtonVisibilityCtrl.class * Java compiler version: 6 (50.0) * JD-Core Version: 1.1.3 */
package com.tencent.mm.pluginsdk.ui; import android.graphics.Bitmap; public interface h { public interface c { void bQ(long j); void pV(String str); } void SL(); void SM(); boolean ac(float f); boolean ajG(); void ajY(); void ajZ(); void c(boolean z, String str, int i); int getCacheTimeSec(); int getCurrPosMs(); int getCurrPosSec(); int getPlayerType(); int getVideoDurationSec(); boolean isPlaying(); boolean kW(int i); boolean pause(); void setCover(Bitmap bitmap); void setFullDirection(int i); void setIsShowBasicControls(boolean z); void setMute(boolean z); void setScaleType(d dVar); void setVideoFooterView(g gVar); void start(); void stop(); boolean x(int i, boolean z); }
package com.sdk4.boot.fileupload; import com.alibaba.fastjson.JSON; import com.google.common.collect.Lists; import com.sdk4.common.id.IdUtils; import lombok.extern.slf4j.Slf4j; import org.joda.time.DateTime; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartHttpServletRequest; import org.springframework.web.multipart.commons.CommonsMultipartResolver; import javax.servlet.http.HttpServletRequest; import java.io.File; import java.io.IOException; import java.util.Iterator; import java.util.List; /** * @author sh */ @Slf4j public class FileUploadHelper { private FileUploadHelper() { throw new IllegalStateException("Utility class"); } private static final String FMT_FN = "yyyyMMdd/HH"; private static FileUploadConfig fileUploadConfig; public static void loadConfig(FileUploadConfig config) { FileUploadHelper.fileUploadConfig = config; } public static FileTypeConfig getFileTypeConfig(String type) { return fileUploadConfig.getFiles().get(type); } public static StorageProvider getStorageProvider(String provider) { return fileUploadConfig.getProvider().get(provider); } public static List<FileUploadInfo> getFileUploadInfos(HttpServletRequest request) { List<FileUploadInfo> files = Lists.newArrayList(); CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext()); if (multipartResolver.isMultipart(request)) { MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request; Iterator<String> filenames = multiRequest.getFileNames(); while (filenames.hasNext()) { MultipartFile file = multiRequest.getFile(filenames.next()); if (file != null) { FileUploadInfo fileInfo = new FileUploadInfo(); fileInfo.setFileKey(file.getName()); fileInfo.setOriginalFilename(file.getOriginalFilename()); fileInfo.setContentType(file.getContentType()); fileInfo.setSuffix(FileSuffixUtils.getFileSuffix(file.getContentType())); fileInfo.setFileSize(file.getSize()); fileInfo.setFile(file); files.add(fileInfo); } } } return files; } public static FileSaveInfo saveFile(String type, FileUploadInfo fileInfo) { FileSaveInfo result = null; FileTypeConfig fileTypeConfig = getFileTypeConfig(type); StorageProvider storageProvider = fileTypeConfig == null ? null : getStorageProvider(fileTypeConfig.getProvider()); if (fileTypeConfig != null && storageProvider != null) { if (StorageMode.local == storageProvider.getMode()) { String objectKey = getObjectKey(type); File path = new File(getPath(objectKey, storageProvider)); if (!path.exists()) { path.mkdirs(); } String fileId = IdUtils.fastUUID().toString(); try { objectKey = objectKey + "/" + fileId + "." + fileInfo.getSuffix(); fileInfo.getFile().transferTo(new File(path, fileId)); result = new FileSaveInfo(objectKey, fileId, getFileUrl(objectKey)); } catch (IOException e) { log.error("上传文件保存失败:{}", JSON.toJSONString(fileInfo), e); } } } return result; } public static File readFile(String type, String objectKey) { FileTypeConfig fileTypeConfig = getFileTypeConfig(type); StorageProvider storageProvider = fileTypeConfig == null ? null : getStorageProvider(fileTypeConfig.getProvider()); if (fileTypeConfig != null && storageProvider != null) { return new File(getPath(objectKey, storageProvider)); } return null; } public static String getFileUrl(String objectKey) { StringBuilder url = new StringBuilder(fileUploadConfig.getAccessBaseUrl()); if (!fileUploadConfig.getAccessBaseUrl().endsWith("/")) { url.append('/'); } url.append(objectKey); return url.toString(); } private static String getPath(String objectKey, StorageProvider storageProvider) { StringBuilder path = new StringBuilder(); path.append(storageProvider.getLocalPath()); if (!storageProvider.getLocalPath().endsWith(File.separator)) { path.append(File.separator); } path.append(objectKey); return path.toString(); } private static String getObjectKey(String type) { StringBuilder objectKey = new StringBuilder(); objectKey.append(type); objectKey.append("/"); objectKey.append(new DateTime().toString(FMT_FN)); return objectKey.toString(); } }
public class MergeTwoSortedLists { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub } } class ListNode { int val; ListNode next; ListNode(int x) { val = x; } } class SolutionMergeTwoLists { public ListNode mergeTwoLists(ListNode l1, ListNode l2) { ListNode pivot1 = l1; ListNode pivot2 = l2; if (pivot1.val == pivot2.val) { l1.next = pivot2; } else if (pivot1.val < pivot2.val) { pivot1 = l1.next; } return null; } } /* * public ListNode mergeTwoLists(ListNode l1, ListNode l2){ if(l1 == null) return l2; if(l2 == null) return l1; if(l1.val < l2.val){ l1.next = mergeTwoLists(l1.next, l2); return l1; } else{ l2.next = mergeTwoLists(l1, l2.next); return l2; } } * * * */
package com.ifinance.controller.follow; import com.ifinance.base.BaseController; import com.ifinance.model.Customer; public class FollowController extends BaseController { /** * 客户跟单列表 */ public void listCustomer() { String respone = FollowService.service.listCustomers(this); renderJson(respone); } /** * 创建Customer */ public void createCustomer() { String respone = FollowService.service.createCustomer(this); renderJson(respone); } /** * 更新Customer */ public void updateCustomer() { String respone = FollowService.service.updateCustomer(this); renderJson(respone); } /** * 新建跟单详细 */ public void createFollowDetail() { String respone = FollowService.service.createFollowDetail(this); renderJson(respone); } /** * 客户跟单详细列表 */ public void getHistoryList() { String respone = FollowService.service.getFollowHistoryList(this); renderJson(respone); } }
package com.hema.www.myscrolltrack.scroll; import android.animation.ObjectAnimator; import android.support.v7.widget.RecyclerView; import android.view.View; import android.view.ViewParent; /** * Created by Administrator on 2016/5/6. */ public class BottomTrackListener extends RecyclerView.OnScrollListener { private static final String TAG = BottomTrackListener.class.getSimpleName(); private View mTargetView = null; private boolean isAlreadyHide = false, isAlreadyShow = false; private ObjectAnimator mAnimator = null; private int mLastDy = 0; public BottomTrackListener(View target) { if (target == null) { throw new IllegalArgumentException("target shouldn't be null!"); } mTargetView = target; } @Override public void onScrollStateChanged(RecyclerView recyclerView, int newState) { super.onScrollStateChanged(recyclerView, newState); if (newState == RecyclerView.SCROLL_STATE_IDLE) { final float transY = mTargetView.getTranslationY(); if (transY == 0 || transY == getDistance()) { return; } if (mLastDy > 0) { mAnimator = animateHide(mTargetView); } else { mAnimator = animateShow(mTargetView); } } else { if (mAnimator != null && mAnimator.isRunning()) { mAnimator.cancel(); } } } @Override public void onScrolled(RecyclerView recyclerView, int dx, int dy) { super.onScrolled(recyclerView, dx, dy); mLastDy = dy; final float transY = mTargetView.getTranslationY(); float newsTransY = transY + dy; final int distance = getDistance(); if (newsTransY < 0) newsTransY = 0; else if (newsTransY > distance) newsTransY = distance; if (newsTransY == 0 && isAlreadyShow) return; if (newsTransY == distance && isAlreadyHide) return; mTargetView.setTranslationY(newsTransY); isAlreadyHide = newsTransY == distance; isAlreadyShow = newsTransY == 0; } private int getDistance() { ViewParent parent = mTargetView.getParent(); if (parent instanceof View) { return ((View) parent).getHeight() - mTargetView.getTop(); } return 0; } private ObjectAnimator animateShow(View view) { return animatorFromTo(view, view.getTranslationY(), 0); } private ObjectAnimator animateHide(View view) { return animatorFromTo(view, view.getTranslationY(), getDistance()); } private ObjectAnimator animatorFromTo(View view, float start, float end) { String propertyName = "translationY"; ObjectAnimator animator = ObjectAnimator.ofFloat(view, propertyName, start, end); animator.start(); return animator; } }
package com.ntxdev.zuptecnico.fragments.reports; import android.app.Dialog; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.v4.app.DialogFragment; import android.support.v7.app.AlertDialog; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ListView; import com.ntxdev.zuptecnico.R; import com.ntxdev.zuptecnico.adapters.ReportCategoriesAdapter; import com.ntxdev.zuptecnico.entities.ReportCategory; /** * Created by igorlira on 7/20/15. */ public class ReportCategorySelectorDialog extends DialogFragment implements AdapterView.OnItemClickListener { View confirmButton; ListView listView; public interface OnReportCategorySetListener { void onReportCategorySet(int categoryId); } OnReportCategorySetListener listener; ReportCategoriesAdapter adapter; public ReportCategorySelectorDialog() { adapter = new ReportCategoriesAdapter(); } public void setListener(OnReportCategorySetListener listener) { this.listener = listener; } @NonNull @Override public Dialog onCreateDialog(Bundle savedInstanceState) { AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); builder.setTitle(null); builder.setView(createView(getActivity().getLayoutInflater(), null, savedInstanceState)); return builder.create(); } View createView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.dialog_createreport, container, false); listView = (ListView) view.findViewById(R.id.listView); confirmButton = view.findViewById(R.id.confirm); confirmButton.setVisibility(View.INVISIBLE); listView.setAdapter(adapter); listView.setDividerHeight(0); listView.setOnItemClickListener(this); confirmButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { confirm(adapter.getSelectedItemId()); } }); return view; } @Override public void onItemClick(AdapterView<?> adapterView, View view, final int i, long l) { ReportCategory category = adapter.getItem(i); adapter.clickCategory(category); if (adapter.getSelectedItemId() >= 0) { confirmButton.setVisibility(View.VISIBLE); } if (category.subcategories != null && category.subcategories.length > 0) { int newIndex = adapter.getItemIndex(category); listView.smoothScrollToPositionFromTop(newIndex, 0); } } void confirm(int id) { if (this.listener != null) this.listener.onReportCategorySet(id); dismiss(); } }
/* * 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.webbeans.test.component.decorator.clean; import java.math.BigDecimal; import jakarta.enterprise.context.RequestScoped; import jakarta.enterprise.inject.Default; @RequestScoped @Default public class AccountComponent implements Account { private BigDecimal amount; private BigDecimal balance; @Override public void deposit(BigDecimal amount) { } @Override public BigDecimal getBalance() { return this.balance; } @Override public void withdraw(BigDecimal amount) { } /** * @return the amount */ public BigDecimal getAmount() { return amount; } /** * @param amount the amount to set */ public void setAmount(BigDecimal amount) { this.amount = amount; } /** * @param balance the balance to set */ public void setBalance(BigDecimal balance) { this.balance = balance; } }
package com.lubarov.daniel.web.http.parsing; import com.lubarov.daniel.data.dictionary.KeyValuePair; import com.lubarov.daniel.data.table.sequential.SequentialTable; import org.junit.Test; import java.nio.charset.StandardCharsets; import static org.junit.Assert.assertEquals; public class CookieHeaderParserTest { @Test public void testTryParse_basic() { String cookieHeader = "$Version=1; Skin=new;"; byte[] cookieHeaderBytes = cookieHeader.getBytes(StandardCharsets.US_ASCII); SequentialTable<String, String> result = CookieHeaderParser.singleton.tryParse(cookieHeaderBytes, 0) .getOrThrow().getValue(); assertEquals(2, result.getSize()); assertEquals(new KeyValuePair<>("$Version", "1"), result.get(0)); assertEquals(new KeyValuePair<>("Skin", "new"), result.get(1)); } @Test public void testTryParse_googleAnalytics() { String cookieHeader = "__utma=11106849.1694674570.1364289598.1364289598.1364289598.1; __utmc=11106849; __utmz=11106849.1364289598.1.1.utmcsr=stackoverflow.com|utmccn=(referral)|utmcmd=referral|utmcct=/users/714009/daniel"; byte[] cookieHeaderBytes = cookieHeader.getBytes(StandardCharsets.US_ASCII); SequentialTable<String, String> result = CookieHeaderParser.singleton .tryParse(cookieHeaderBytes, 0).getOrThrow().getValue(); assertEquals(3, result.getSize()); assertEquals( new KeyValuePair<>("__utma", "11106849.1694674570.1364289598.1364289598.1364289598.1"), result.get(0)); assertEquals( new KeyValuePair<>("__utmc", "11106849"), result.get(1)); assertEquals( new KeyValuePair<>("__utmz", "11106849.1364289598.1.1.utmcsr=stackoverflow.com|utmccn=(referral)|utmcmd=referral|utmcct=/users/714009/daniel"), result.get(2)); } }
package com.red.gotrade.db.gen; import android.database.Cursor; import android.database.sqlite.SQLiteStatement; import org.greenrobot.greendao.AbstractDao; import org.greenrobot.greendao.Property; import org.greenrobot.greendao.internal.DaoConfig; import org.greenrobot.greendao.database.Database; import org.greenrobot.greendao.database.DatabaseStatement; import com.red.gotrade.model.AuthorModel; // THIS CODE IS GENERATED BY greenDAO, DO NOT EDIT. /** * DAO for table "AUTHOR_MODEL". */ public class AuthorModelDao extends AbstractDao<AuthorModel, Long> { public static final String TABLENAME = "AUTHOR_MODEL"; /** * Properties of entity AuthorModel.<br/> * Can be used for QueryBuilder and for referencing column names. */ public static class Properties { public final static Property Id = new Property(0, Long.class, "id", true, "_id"); public final static Property Author_token = new Property(1, String.class, "author_token", false, "AUTHOR_TOKEN"); public final static Property Address = new Property(2, String.class, "address", false, "ADDRESS"); public final static Property Author_nickname = new Property(3, String.class, "author_nickname", false, "AUTHOR_NICKNAME"); public final static Property Phone = new Property(4, String.class, "phone", false, "PHONE"); public final static Property Status = new Property(5, int.class, "status", false, "STATUS"); } public AuthorModelDao(DaoConfig config) { super(config); } public AuthorModelDao(DaoConfig config, DaoSession daoSession) { super(config, daoSession); } /** Creates the underlying database table. */ public static void createTable(Database db, boolean ifNotExists) { String constraint = ifNotExists? "IF NOT EXISTS ": ""; db.execSQL("CREATE TABLE " + constraint + "\"AUTHOR_MODEL\" (" + // "\"_id\" INTEGER PRIMARY KEY AUTOINCREMENT ," + // 0: id "\"AUTHOR_TOKEN\" TEXT," + // 1: author_token "\"ADDRESS\" TEXT," + // 2: address "\"AUTHOR_NICKNAME\" TEXT," + // 3: author_nickname "\"PHONE\" TEXT," + // 4: phone "\"STATUS\" INTEGER NOT NULL );"); // 5: status } /** Drops the underlying database table. */ public static void dropTable(Database db, boolean ifExists) { String sql = "DROP TABLE " + (ifExists ? "IF EXISTS " : "") + "\"AUTHOR_MODEL\""; db.execSQL(sql); } @Override protected final void bindValues(DatabaseStatement stmt, AuthorModel entity) { stmt.clearBindings(); Long id = entity.getId(); if (id != null) { stmt.bindLong(1, id); } String author_token = entity.getAuthor_token(); if (author_token != null) { stmt.bindString(2, author_token); } String address = entity.getAddress(); if (address != null) { stmt.bindString(3, address); } String author_nickname = entity.getAuthor_nickname(); if (author_nickname != null) { stmt.bindString(4, author_nickname); } String phone = entity.getPhone(); if (phone != null) { stmt.bindString(5, phone); } stmt.bindLong(6, entity.getStatus()); } @Override protected final void bindValues(SQLiteStatement stmt, AuthorModel entity) { stmt.clearBindings(); Long id = entity.getId(); if (id != null) { stmt.bindLong(1, id); } String author_token = entity.getAuthor_token(); if (author_token != null) { stmt.bindString(2, author_token); } String address = entity.getAddress(); if (address != null) { stmt.bindString(3, address); } String author_nickname = entity.getAuthor_nickname(); if (author_nickname != null) { stmt.bindString(4, author_nickname); } String phone = entity.getPhone(); if (phone != null) { stmt.bindString(5, phone); } stmt.bindLong(6, entity.getStatus()); } @Override public Long readKey(Cursor cursor, int offset) { return cursor.isNull(offset + 0) ? null : cursor.getLong(offset + 0); } @Override public AuthorModel readEntity(Cursor cursor, int offset) { AuthorModel entity = new AuthorModel( // cursor.isNull(offset + 0) ? null : cursor.getLong(offset + 0), // id cursor.isNull(offset + 1) ? null : cursor.getString(offset + 1), // author_token cursor.isNull(offset + 2) ? null : cursor.getString(offset + 2), // address cursor.isNull(offset + 3) ? null : cursor.getString(offset + 3), // author_nickname cursor.isNull(offset + 4) ? null : cursor.getString(offset + 4), // phone cursor.getInt(offset + 5) // status ); return entity; } @Override public void readEntity(Cursor cursor, AuthorModel entity, int offset) { entity.setId(cursor.isNull(offset + 0) ? null : cursor.getLong(offset + 0)); entity.setAuthor_token(cursor.isNull(offset + 1) ? null : cursor.getString(offset + 1)); entity.setAddress(cursor.isNull(offset + 2) ? null : cursor.getString(offset + 2)); entity.setAuthor_nickname(cursor.isNull(offset + 3) ? null : cursor.getString(offset + 3)); entity.setPhone(cursor.isNull(offset + 4) ? null : cursor.getString(offset + 4)); entity.setStatus(cursor.getInt(offset + 5)); } @Override protected final Long updateKeyAfterInsert(AuthorModel entity, long rowId) { entity.setId(rowId); return rowId; } @Override public Long getKey(AuthorModel entity) { if(entity != null) { return entity.getId(); } else { return null; } } @Override public boolean hasKey(AuthorModel entity) { return entity.getId() != null; } @Override protected final boolean isEntityUpdateable() { return true; } }
package com.zngcloudcms.utils.cache; public enum CACHE_ENUM { USERNAME, USER, PROJECTS }
/* * Copyright (c) 2013 University of Tartu */ package org.jpmml.evaluator; import org.dmg.pmml.*; class NeuronClassificationMap extends EntityClassificationMap<Entity> { NeuronClassificationMap(){ super(Type.PROBABILITY); } NeuronClassificationMap(Entity entity){ super(Type.PROBABILITY, entity); } }
package com.project.backend.controller; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import com.project.backend.entità.TypeStrutturaSt; import com.project.backend.repository.TypeStrutturaStRepository; @RestController @CrossOrigin public class TypeStrutturaStController { @Autowired private TypeStrutturaStRepository type; @GetMapping("/typeStrutturaSt") public List<TypeStrutturaSt> getCaratteristiche() { return (List<TypeStrutturaSt>) type.findAll(); } }
package Model; /** * * @author User */ public class Company { private int id_company; private String name_company; private String cnpj; private String city; private String phone; private String email; private String img; public Company(int id_company, String name_company, String cnpj, String city, String phone, String email, String img) { this.id_company = id_company; this.name_company = name_company; this.cnpj = cnpj; this.city = city; this.phone = phone; this.email = email; this.img = img; } public Company(String name_company, String cnpj, String city, String phone, String email, String img) { this.name_company = name_company; this.cnpj = cnpj; this.city = city; this.phone = phone; this.email = email; this.img = img; } public int getId_company() { return id_company; } public void setId_company(int id_company) { this.id_company = id_company; } public String getName_company() { return name_company; } public void setName_company(String name_company) { this.name_company = name_company; } public String getCnpj() { return cnpj; } public void setCnpj(String cnpj) { this.cnpj = cnpj; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getImg() { return img; } public void setImg(String img) { this.img = img; } }
package com.cyberdust.automation.application.ServerOutput; import java.awt.Color; import java.io.IOException; import java.io.OutputStream; import javax.swing.JTextPane; import javax.swing.text.BadLocationException; import javax.swing.text.Style; import javax.swing.text.StyleConstants; import javax.swing.text.StyleContext; public class ConsoleErrorOutput extends OutputStream { private StyleContext context = new StyleContext(); private JTextPane textPane; public ConsoleErrorOutput(JTextPane textPane) { this.textPane = textPane; } @Override public void write(int b) throws IOException { Style style = context.addStyle("errorOutput", null); StyleConstants.setForeground(style, Color.RED); try { textPane.getStyledDocument().insertString(textPane.getDocument().getLength(), String.valueOf((char)b), style); textPane.setCaretPosition(textPane.getDocument().getLength()); } catch (BadLocationException ignored) {} } }
package api.repository.usuario; import api.model.Usuario; import org.hibernate.boot.jaxb.hbm.spi.EntityInfo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.jpa.repository.support.JpaEntityInformation; import org.springframework.data.jpa.repository.support.JpaEntityInformationSupport; import org.springframework.data.repository.core.EntityInformation; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import javax.persistence.EntityManager; /** * Created by Gustavo Galvao on 23/07/2018. */ @Service public class UsuarioRepositoryImpl implements UsuarioRepositoryCustomizado { @Autowired private PasswordEncoder passwordEncoder; @Autowired private EntityManager entityManager; @Transactional public Usuario save(Usuario usuario){ JpaEntityInformation<Usuario, ?> entityInformation = JpaEntityInformationSupport.getEntityInformation(Usuario.class, entityManager); if(entityInformation.isNew(usuario)) { usuario.setSenha(passwordEncoder.encode(usuario.getSenha())); entityManager.persist(usuario); return usuario; } else { return entityManager.merge(usuario); } } }
package com.rc.portal.dao; import java.sql.SQLException; import java.util.List; import com.rc.portal.vo.TPhysician; import com.rc.portal.vo.TPhysicianExample; public interface TPhysicianDAO { int countByExample(TPhysicianExample example) throws SQLException; int deleteByExample(TPhysicianExample example) throws SQLException; int deleteByPrimaryKey(Long id) throws SQLException; Long insert(TPhysician record) throws SQLException; Long insertSelective(TPhysician record) throws SQLException; List selectByExample(TPhysicianExample example) throws SQLException; TPhysician selectByPrimaryKey(Long id) throws SQLException; int updateByExampleSelective(TPhysician record, TPhysicianExample example) throws SQLException; int updateByExample(TPhysician record, TPhysicianExample example) throws SQLException; int updateByPrimaryKeySelective(TPhysician record) throws SQLException; int updateByPrimaryKey(TPhysician record) throws SQLException; }
package Client; public class BlackAndWhiteCameraRoll implements CameraRoll { public void processing() { System.out.println("-1 чёрно-белый кадр"); } }
package de.allmaennitta.mindware.conceptmap.node; import java.util.List; import org.springframework.data.neo4j.annotation.Query; import org.springframework.data.neo4j.repository.Neo4jRepository; public interface NodeRepository extends Neo4jRepository<Node, Long> { Node findByName(String name); @Query("MATCH (n:Node) return n") List<Node> getAllNodes(); @Query("MATCH (n:Node) WHERE n.label=='start' return n LIMIT 1") List<Node> getFirst(); }
/** * CommonFramework * * Copyright (C) 2017 Black Duck Software, Inc. * http://www.blackducksoftware.com/ * * 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 com.blackducksoftware.tools.commonframework.standard.datatable; import static org.junit.Assert.*; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import com.blackducksoftware.tools.commonframework.standard.datatable.FieldDef; import com.blackducksoftware.tools.commonframework.standard.datatable.FieldType; import com.blackducksoftware.tools.commonframework.standard.datatable.RecordDef; public class RecordDefTest { @BeforeClass public static void setUpBeforeClass() throws Exception { } @AfterClass public static void tearDownAfterClass() throws Exception { } @Test public void test() { // Create the record definition List<FieldDef> fieldDefs = new ArrayList<FieldDef>(); fieldDefs.add(new FieldDef("applicationName", FieldType.STRING, "Application Name")); fieldDefs.add(new FieldDef("applicationVersion", FieldType.STRING, "Application Version")); fieldDefs.add(new FieldDef("componentName", FieldType.STRING, "Component Name")); fieldDefs.add(new FieldDef("componentVersion", FieldType.STRING, "Component Version")); fieldDefs.add(new FieldDef("cveName", FieldType.STRING, "CVE Name")); fieldDefs.add(new FieldDef("vulnerabilityDescription", FieldType.STRING, "Vulnerability Description")); fieldDefs.add(new FieldDef("link", FieldType.HYPERLINK, "Link")); RecordDef recordDef = new RecordDef(fieldDefs); assertEquals(7, recordDef.size()); assertEquals("applicationName", recordDef.getFieldDef(0).getName()); // Get an iterator that will let us iterate thru the record's FieldDefs Iterator<FieldDef> fieldDefIter = recordDef.iterator(); assertTrue(fieldDefIter.hasNext()); assertEquals("applicationName", fieldDefIter.next().getName()); assertEquals("applicationVersion", fieldDefIter.next().getName()); assertEquals("componentName", fieldDefIter.next().getName()); assertEquals("componentVersion", fieldDefIter.next().getName()); assertEquals("cveName", fieldDefIter.next().getName()); assertEquals("vulnerabilityDescription", fieldDefIter.next().getName()); assertTrue(fieldDefIter.hasNext()); assertEquals("link", fieldDefIter.next().getName()); assertFalse(fieldDefIter.hasNext()); } @Test public void testDateField() { // Create the record definition List<FieldDef> fieldDefs = new ArrayList<FieldDef>(); fieldDefs.add(new FieldDef("applicationName", FieldType.STRING, "Application Name")); fieldDefs.add(new FieldDef("publishedDate", FieldType.DATE, "Published Date", "yyyy-MM-dd HH:mm:ss.0")); RecordDef recordDef = new RecordDef(fieldDefs); assertEquals(2, recordDef.size()); assertEquals("applicationName", recordDef.getFieldDef(0).getName()); assertEquals("publishedDate", recordDef.getFieldDef(1).getName()); // Get an iterator that will let us iterate thru the record's FieldDefs Iterator<FieldDef> fieldDefIter = recordDef.iterator(); assertTrue(fieldDefIter.hasNext()); assertEquals("applicationName", fieldDefIter.next().getName()); assertEquals("publishedDate", fieldDefIter.next().getName()); assertFalse(fieldDefIter.hasNext()); } }
package Day12; public class Day12_2 { private String 성명; public String 아이디; String 연락처; protected String 성별; }
/* 1: */ package org.linphone.core; /* 2: */ /* 3: */ import org.linphone.mediastream.video.AndroidVideoWindowImpl; import java.util.Vector; /* 4: */ /* 5: */ /* 6: */ public abstract interface LinphoneCore /* 7: */ { /* 8: */ public abstract void setContext(Object paramObject); /* 9: */ /* 10: */ public abstract void clearProxyConfigs(); /* 11: */ /* 12: */ public abstract void addProxyConfig(LinphoneProxyConfig paramLinphoneProxyConfig) /* 13: */ throws LinphoneCoreException; /* 14: */ /* 15: */ public abstract void removeProxyConfig(LinphoneProxyConfig paramLinphoneProxyConfig); /* 16: */ /* 17: */ public abstract void setDefaultProxyConfig(LinphoneProxyConfig paramLinphoneProxyConfig); /* 18: */ /* 19: */ public abstract LinphoneProxyConfig getDefaultProxyConfig(); /* 20: */ /* 21: */ public abstract LinphoneAuthInfo[] getAuthInfosList(); /* 22: */ /* 23: */ public abstract LinphoneAuthInfo findAuthInfo(String paramString1, String paramString2, String paramString3); /* 24: */ /* 25: */ public abstract void removeAuthInfo(LinphoneAuthInfo paramLinphoneAuthInfo); /* 26: */ /* 27: */ public abstract void clearAuthInfos(); /* 28: */ /* 29: */ public abstract void addAuthInfo(LinphoneAuthInfo paramLinphoneAuthInfo); /* 30: */ /* 31: */ public abstract LinphoneAddress interpretUrl(String paramString) /* 32: */ throws LinphoneCoreException; /* 33: */ /* 34: */ public abstract LinphoneCall invite(String paramString) /* 35: */ throws LinphoneCoreException; /* 36: */ /* 37: */ public abstract LinphoneCall invite(LinphoneAddress paramLinphoneAddress) /* 38: */ throws LinphoneCoreException; /* 39: */ /* 40: */ public abstract void terminateCall(LinphoneCall paramLinphoneCall); /* 41: */ /* 42: */ public abstract void declineCall(LinphoneCall paramLinphoneCall, Reason paramReason); /* 43: */ /* 44: */ public abstract LinphoneCall getCurrentCall(); /* 45: */ /* 46: */ public abstract LinphoneAddress getRemoteAddress(); /* 47: */ /* 48: */ public abstract boolean isIncall(); /* 49: */ /* 50: */ public abstract boolean isInComingInvitePending(); /* 51: */ /* 52: */ public abstract void iterate(); /* 53: */ /* 54: */ public abstract void acceptCall(LinphoneCall paramLinphoneCall) /* 55: */ throws LinphoneCoreException; /* 56: */ /* 57: */ public abstract void acceptCallWithParams(LinphoneCall paramLinphoneCall, LinphoneCallParams paramLinphoneCallParams) /* 58: */ throws LinphoneCoreException; /* 59: */ /* 60: */ public abstract void acceptCallUpdate(LinphoneCall paramLinphoneCall, LinphoneCallParams paramLinphoneCallParams) /* 61: */ throws LinphoneCoreException; /* 62: */ /* 63: */ public abstract void deferCallUpdate(LinphoneCall paramLinphoneCall) /* 64: */ throws LinphoneCoreException; /* 65: */ /* 66: */ public abstract LinphoneCallLog[] getCallLogs(); /* 67: */ /* 68: */ public abstract void setNetworkReachable(boolean paramBoolean); /* 69: */ /* 70: */ public abstract boolean isNetworkReachable(); /* 71: */ /* 72: */ public abstract void destroy(); /* 73: */ /* 74: */ public abstract void setPlaybackGain(float paramFloat); /* 75: */ /* 76: */ public abstract float getPlaybackGain(); /* 77: */ /* 78: */ public abstract void setPlayLevel(int paramInt); /* 79: */ /* 80: */ public abstract int getPlayLevel(); /* 81: */ /* 82: */ public abstract void muteMic(boolean paramBoolean); /* 83: */ /* 84: */ public abstract boolean isMicMuted(); /* 85: */ /* 86: */ public abstract void sendDtmf(char paramChar); /* 87: */ /* 88: */ public abstract void playDtmf(char paramChar, int paramInt); /* 89: */ /* 90: */ public abstract void stopDtmf(); /* 91: */ /* 92: */ public abstract void clearCallLogs(); /* 93: */ /* 94: */ public abstract PayloadType findPayloadType(String paramString, int paramInt1, int paramInt2); /* 95: */ /* 96: */ public abstract PayloadType findPayloadType(String paramString, int paramInt); /* 97: */ /* 98: */ public abstract PayloadType findPayloadType(String paramString); /* 99: */ /* 100: */ public abstract void enablePayloadType(PayloadType paramPayloadType, boolean paramBoolean) /* 101: */ throws LinphoneCoreException; /* 102: */ /* 103: */ public abstract boolean isPayloadTypeEnabled(PayloadType paramPayloadType); /* 104: */ /* 105: */ public abstract boolean payloadTypeIsVbr(PayloadType paramPayloadType); /* 106: */ /* 107: */ public abstract void setPayloadTypeBitrate(PayloadType paramPayloadType, int paramInt); /* 108: */ /* 109: */ public abstract int getPayloadTypeBitrate(PayloadType paramPayloadType); /* 110: */ /* 111: */ public abstract void setPayloadTypeNumber(PayloadType paramPayloadType, int paramInt); /* 112: */ /* 113: */ public abstract int getPayloadTypeNumber(PayloadType paramPayloadType); /* 114: */ /* 115: */ public abstract void enableAdaptiveRateControl(boolean paramBoolean); /* 116: */ /* 117: */ public abstract boolean isAdaptiveRateControlEnabled(); /* 118: */ /* 119: */ public abstract void setAdaptiveRateAlgorithm(AdaptiveRateAlgorithm paramAdaptiveRateAlgorithm); /* 120: */ /* 121: */ public abstract AdaptiveRateAlgorithm getAdaptiveRateAlgorithm(); /* 122: */ /* 123: */ public abstract void enableEchoCancellation(boolean paramBoolean); /* 124: */ /* 125: */ public abstract boolean isEchoCancellationEnabled(); /* 126: */ /* 127: */ public abstract boolean isEchoLimiterEnabled(); /* 128: */ /* 129: */ public abstract void setSignalingTransportPorts(Transports paramTransports); /* 130: */ /* 131: */ public abstract Transports getSignalingTransportPorts(); /* 132: */ /* 133: */ public abstract void setSipDscp(int paramInt); /* 134: */ /* 135: */ public abstract int getSipDscp(); /* 136: */ /* 137: */ public abstract void enableSpeaker(boolean paramBoolean); /* 138: */ /* 139: */ public abstract boolean isSpeakerEnabled(); /* 140: */ /* 141: */ public abstract void addFriend(LinphoneFriend paramLinphoneFriend) /* 142: */ throws LinphoneCoreException; /* 143: */ /* 144: */ public abstract LinphoneFriend[] getFriendList(); /* 145: */ /* 146: */ /* 149: */ public abstract void setPresenceInfo(int paramInt, String paramString, OnlineStatus paramOnlineStatus); /* 150: */ /* 154: */ public abstract OnlineStatus getPresenceInfo(); /* 155: */ /* 156: */ public abstract void setPresenceModel(PresenceModel paramPresenceModel); /* 157: */ /* 158: */ public abstract PresenceModel getPresenceModel(); /* 159: */ /* 160: */ public abstract LinphoneChatRoom getOrCreateChatRoom(String paramString); /* 161: */ /* 162: */ public abstract void setVideoWindow(Object paramObject); /* 163: */ /* 164: */ public abstract void setPreviewWindow(Object paramObject); /* 165: */ /* 166: */ public abstract void setDeviceRotation(int paramInt); /* 167: */ /* 168: */ public abstract void setVideoDevice(int paramInt); /* 169: */ /* 170: */ public abstract int getVideoDevice(); /* 171: */ /* 172: */ public abstract boolean isVideoSupported(); /* 173: */ /* 174: */ public abstract void enableVideo(boolean paramBoolean1, boolean paramBoolean2); /* 175: */ /* 176: */ public abstract boolean isVideoEnabled(); /* 177: */ /* 178: */ public abstract void setStunServer(String paramString); /* 179: */ /* 180: */ public abstract String getStunServer(); /* 181: */ /* 182: */ public abstract void setFirewallPolicy(FirewallPolicy paramFirewallPolicy); /* 183: */ /* 184: */ public abstract FirewallPolicy getFirewallPolicy(); /* 185: */ /* 186: */ public abstract LinphoneCall inviteAddressWithParams(LinphoneAddress paramLinphoneAddress, LinphoneCallParams paramLinphoneCallParams) /* 187: */ throws LinphoneCoreException; /* 188: */ /* 189: */ public abstract int updateCall(LinphoneCall paramLinphoneCall, LinphoneCallParams paramLinphoneCallParams); /* 190: */ /* 191: */ public abstract LinphoneCallParams createDefaultCallParameters(); /* 192: */ /* 193: */ public abstract void setRing(String paramString); /* 194: */ /* 195: */ public abstract String getRing(); /* 196: */ /* 197: */ public abstract void setRootCA(String paramString); /* 198: */ /* 199: */ public abstract void setRingback(String paramString); /* 200: */ /* 201: */ public abstract void setUploadBandwidth(int paramInt); /* 202: */ /* 203: */ public abstract void setDownloadBandwidth(int paramInt); /* 204: */ /* 205: */ public abstract void setDownloadPtime(int paramInt); /* 206: */ /* 207: */ public abstract void setUploadPtime(int paramInt); /* 208: */ /* 209: */ public abstract void setPreferredVideoSize(VideoSize paramVideoSize); /* 210: */ /* 211: */ public abstract void setPreferredVideoSizeByName(String paramString); /* 212: */ /* 213: */ public abstract VideoSize getPreferredVideoSize(); /* 214: */ /* 215: */ public abstract void setPreferredFramerate(float paramFloat); /* 216: */ /* 217: */ public abstract float getPreferredFramerate(); /* 218: */ /* 219: */ public abstract PayloadType[] getAudioCodecs(); /* 220: */ /* 221: */ public abstract void setAudioCodecs(PayloadType[] paramArrayOfPayloadType); /* 222: */ /* 223: */ public abstract PayloadType[] getVideoCodecs(); /* 224: */ /* 225: */ public abstract void setVideoCodecs(PayloadType[] paramArrayOfPayloadType); /* 226: */ /* 227: */ public abstract void enableKeepAlive(boolean paramBoolean); /* 228: */ /* 229: */ public abstract boolean isKeepAliveEnabled(); /* 230: */ /* 231: */ public abstract void startEchoCalibration(LinphoneCoreListener paramLinphoneCoreListener) /* 232: */ throws LinphoneCoreException; /* 233: */ /* 234: */ public abstract boolean needsEchoCalibration(); /* 235: */ /* 236: */ public abstract boolean needsEchoCanceler(); /* 237: */ /* 238: */ public abstract void enableIpv6(boolean paramBoolean); /* 239: */ /* 240: */ public abstract boolean isIpv6Enabled(); /* 241: */ /* 242: */ /* 245: */ public abstract void adjustSoftwareVolume(int paramInt); /* 246: */ /* 247: */ public abstract boolean pauseCall(LinphoneCall paramLinphoneCall); /* 248: */ /* 249: */ public abstract boolean resumeCall(LinphoneCall paramLinphoneCall); /* 250: */ /* 251: */ public abstract boolean pauseAllCalls(); /* 252: */ /* 253: */ public abstract void setZrtpSecretsCache(String paramString); /* 254: */ /* 255: */ public abstract void enableEchoLimiter(boolean paramBoolean); /* 256: */ /* 257: */ public abstract boolean isInConference(); /* 258: */ /* 259: */ public abstract boolean enterConference(); /* 260: */ /* 261: */ public abstract void leaveConference(); /* 262: */ /* 263: */ public abstract void addToConference(LinphoneCall paramLinphoneCall); /* 264: */ /* 265: */ public abstract void removeFromConference(LinphoneCall paramLinphoneCall); /* 266: */ /* 267: */ public abstract void addAllToConference(); /* 268: */ /* 269: */ public abstract void terminateConference(); /* 270: */ /* 271: */ public abstract int getConferenceSize(); /* 272: */ /* 273: */ public abstract void startConferenceRecording(String paramString); /* 274: */ /* 275: */ public abstract void stopConferenceRecording(); /* 276: */ /* 277: */ public abstract void terminateAllCalls(); /* 278: */ /* 279: */ public abstract LinphoneCall[] getCalls(); /* 280: */ /* 281: */ public abstract int getCallsNb(); /* 282: */ /* 283: */ public abstract void transferCall(LinphoneCall paramLinphoneCall, String paramString); /* 284: */ /* 285: */ public abstract void transferCallToAnother(LinphoneCall paramLinphoneCall1, LinphoneCall paramLinphoneCall2); /* 286: */ /* 287: */ public abstract LinphoneCall startReferedCall(LinphoneCall paramLinphoneCall, LinphoneCallParams paramLinphoneCallParams); /* 288: */ /* 289: */ public abstract LinphoneCall findCallFromUri(String paramString); /* 290: */ /* 291: */ public abstract int getMaxCalls(); /* 292: */ /* 293: */ public abstract void setMaxCalls(int paramInt); /* 294: */ /* 295: */ /* 298: */ public abstract boolean isMyself(String paramString); /* 299: */ /* 300: */ public abstract boolean soundResourcesLocked(); /* 301: */ /* 302: */ public abstract boolean mediaEncryptionSupported(MediaEncryption paramMediaEncryption); /* 303: */ /* 304: */ public abstract void setMediaEncryption(MediaEncryption paramMediaEncryption); /* 305: */ /* 306: */ public abstract MediaEncryption getMediaEncryption(); /* 307: */ /* 308: */ public abstract void setMediaEncryptionMandatory(boolean paramBoolean); /* 309: */ /* 310: */ public abstract boolean isMediaEncryptionMandatory(); /* 311: */ /* 312: */ public abstract void setPlayFile(String paramString); /* 313: */ /* 314: */ /* 317: */ public abstract void tunnelEnable(boolean paramBoolean); /* 318: */ /* 319: */ public abstract void tunnelSetMode(TunnelMode paramTunnelMode); /* 320: */ /* 321: */ public abstract TunnelMode tunnelGetMode(); /* 322: */ /* 323: */ public abstract void tunnelEnableSip(boolean paramBoolean); /* 324: */ /* 325: */ public abstract boolean tunnelSipEnabled(); /* 326: */ /* 327: */ /* 330: */ public abstract void tunnelAutoDetect(); /* 331: */ /* 332: */ public abstract void tunnelCleanServers(); /* 333: */ /* 334: */ public abstract void tunnelSetHttpProxy(String paramString1, int paramInt, String paramString2, String paramString3); /* 335: */ /* 336: */ public abstract void tunnelAddServerAndMirror(String paramString, int paramInt1, int paramInt2, int paramInt3); /* 337: */ /* 338: */ public abstract void tunnelAddServer(TunnelConfig paramTunnelConfig); /* 339: */ /* 340: */ public abstract TunnelConfig[] tunnelGetServers(); /* 341: */ /* 342: */ public abstract boolean isTunnelAvailable(); /* 343: */ /* 344: */ public abstract LinphoneProxyConfig[] getProxyConfigList(); /* 345: */ /* 346: */ public abstract void setVideoPolicy(boolean paramBoolean1, boolean paramBoolean2); /* 347: */ /* 348: */ public abstract boolean getVideoAutoInitiatePolicy(); /* 349: */ /* 350: */ public abstract boolean getVideoAutoAcceptPolicy(); /* 351: */ /* 352: */ public abstract void setStaticPicture(String paramString); /* 353: */ /* 354: */ public abstract void setUserAgent(String paramString1, String paramString2); /* 355: */ /* 356: */ public abstract void setCpuCount(int paramInt); /* 357: */ /* 358: */ public abstract void removeCallLog(LinphoneCallLog paramLinphoneCallLog); /* 359: */ /* 360: */ public abstract int getMissedCallsCount(); /* 361: */ /* 362: */ public abstract void resetMissedCallsCount(); /* 363: */ /* 364: */ public abstract void refreshRegisters(); /* 365: */ /* 366: */ public abstract String getVersion(); /* 367: */ /* 368: */ public abstract void removeFriend(LinphoneFriend paramLinphoneFriend); /* 369: */ /* 370: */ public abstract LinphoneFriend findFriendByAddress(String paramString); /* 371: */ /* 372: */ public abstract void setAudioPort(int paramInt); /* 373: */ /* 374: */ public abstract void setAudioPortRange(int paramInt1, int paramInt2); /* 375: */ /* 376: */ public abstract void setAudioDscp(int paramInt); /* 377: */ /* 378: */ public abstract int getAudioDscp(); /* 379: */ /* 380: */ public abstract void setVideoPort(int paramInt); /* 381: */ /* 382: */ public abstract void setVideoPortRange(int paramInt1, int paramInt2); /* 383: */ /* 384: */ public abstract void setVideoDscp(int paramInt); /* 385: */ /* 386: */ public abstract int getVideoDscp(); /* 387: */ /* 388: */ public abstract void setIncomingTimeout(int paramInt); /* 389: */ /* 390: */ public abstract void setInCallTimeout(int paramInt); /* 391: */ /* 392: */ public abstract void setMicrophoneGain(float paramFloat); /* 393: */ /* 394: */ public abstract void setPrimaryContact(String paramString); /* 395: */ /* 396: */ public abstract String getPrimaryContact(); /* 397: */ /* 398: */ public abstract void setPrimaryContact(String paramString1, String paramString2); /* 399: */ /* 400: */ public abstract String getPrimaryContactUsername(); /* 401: */ /* 402: */ public abstract String getPrimaryContactDisplayName(); /* 403: */ /* 404: */ public abstract void setUseSipInfoForDtmfs(boolean paramBoolean); /* 405: */ /* 406: */ public abstract boolean getUseSipInfoForDtmfs(); /* 407: */ /* 408: */ public abstract void setUseRfc2833ForDtmfs(boolean paramBoolean); /* 409: */ /* 410: */ public abstract boolean getUseRfc2833ForDtmfs(); /* 411: */ /* 412: */ public abstract LpConfig getConfig(); /* 413: */ /* 414: */ public abstract boolean upnpAvailable(); /* 415: */ /* 416: */ public abstract UpnpState getUpnpState(); /* 417: */ /* 418: */ public abstract String getUpnpExternalIpaddress(); /* 419: */ /* 420: */ public abstract LinphoneInfoMessage createInfoMessage(); /* 421: */ /* 422: */ public abstract LinphoneEvent subscribe(LinphoneAddress paramLinphoneAddress, String paramString, int paramInt, LinphoneContent paramLinphoneContent); /* 423: */ /* 424: */ public abstract LinphoneEvent createSubscribe(LinphoneAddress paramLinphoneAddress, String paramString, int paramInt); /* 425: */ /* 426: */ public abstract LinphoneEvent createPublish(LinphoneAddress paramLinphoneAddress, String paramString, int paramInt); /* 427: */ /* 428: */ public abstract LinphoneEvent publish(LinphoneAddress paramLinphoneAddress, String paramString, int paramInt, LinphoneContent paramLinphoneContent); /* 429: */ /* 430: */ public abstract void setChatDatabasePath(String paramString); /* 431: */ /* 432: */ public abstract LinphoneChatRoom[] getChatRooms(); /* 433: */ /* 434: */ public abstract String[] getSupportedVideoSizes(); /* 435: */ /* 436: */ public abstract int migrateToMultiTransport(); /* 437: */ /* 438: */ public abstract boolean acceptEarlyMedia(LinphoneCall paramLinphoneCall); /* 439: */ /* 440: */ public abstract boolean acceptEarlyMediaWithParams(LinphoneCall paramLinphoneCall, LinphoneCallParams paramLinphoneCallParams); /* 441: */ /* 442: */ public abstract LinphoneProxyConfig createProxyConfig(); /* 443: */ /* 444: */ public abstract LinphoneProxyConfig createProxyConfig(String paramString1, String paramString2, String paramString3, boolean paramBoolean) /* 445: */ throws LinphoneCoreException; /* 446: */ /* 447: */ public abstract void setCallErrorTone(Reason paramReason, String paramString); /* 448: */ /* 449: */ public abstract void setTone(ToneID paramToneID, String paramString); /* 450: */ /* 451: */ public abstract void setMtu(int paramInt); /* 452: */ /* 453: */ public abstract int getMtu(); /* 454: */ /* 455: */ public abstract void enableSdp200Ack(boolean paramBoolean); /* 456: */ /* 457: */ public abstract boolean isSdp200AckEnabled(); /* 458: */ /* 459: */ public abstract void disableChat(Reason paramReason); /* 460: */ /* 461: */ public abstract void enableChat(); /* 462: */ /* 463: */ public abstract boolean chatEnabled(); /* 464: */ /* 465: */ public abstract void stopRinging(); /* 466: */ /* 467: */ public abstract void setAudioJittcomp(int paramInt); /* 468: */ /* 469: */ public abstract void setVideoJittcomp(int paramInt); /* 470: */ /* 471: */ public abstract void setFileTransferServer(String paramString); /* 472: */ /* 473: */ public abstract String getFileTransferServer(); /* 474: */ /* 475: */ public abstract LinphonePlayer createLocalPlayer(AndroidVideoWindowImpl paramAndroidVideoWindowImpl); /* 476: */ /* 477: */ public abstract void addListener(LinphoneCoreListener paramLinphoneCoreListener); /* 478: */ /* 479: */ public abstract void removeListener(LinphoneCoreListener paramLinphoneCoreListener); /* 480: */ /* 481: */ public abstract void setRemoteRingbackTone(String paramString); /* 482: */ /* 483: */ public abstract String getRemoteRingbackTone(); /* 484: */ /* 485: */ public abstract void uploadLogCollection(); /* 486: */ /* 487: */ public abstract void resetLogCollection(); /* 488: */ /* 489: */ public abstract void setAudioMulticastAddr(String paramString) /* 490: */ throws LinphoneCoreException; /* 491: */ /* 492: */ public abstract void setVideoMulticastAddr(String paramString) /* 493: */ throws LinphoneCoreException; /* 494: */ /* 495: */ public abstract String getAudioMulticastAddr(); /* 496: */ /* 497: */ public abstract String getVideoMulticastAddr(); /* 498: */ /* 499: */ public abstract void setAudioMulticastTtl(int paramInt) /* 500: */ throws LinphoneCoreException; /* 501: */ /* 502: */ public abstract void setVideoMulticastTtl(int paramInt) /* 503: */ throws LinphoneCoreException; /* 504: */ /* 505: */ public abstract int getAudioMulticastTtl(); /* 506: */ /* 507: */ public abstract int getVideoMulticastTtl(); /* 508: */ /* 509: */ public abstract void enableAudioMulticast(boolean paramBoolean); /* 510: */ /* 511: */ public abstract boolean audioMulticastEnabled(); /* 512: */ /* 513: */ public abstract void enableVideoMulticast(boolean paramBoolean); /* 514: */ /* 515: */ public abstract boolean videoMulticastEnabled(); /* 516: */ /* 517: */ public abstract void enableDnsSrv(boolean paramBoolean); /* 518: */ /* 519: */ public abstract boolean dnsSrvEnabled(); /* 520: */ /* 521: */ public static class GlobalState /* 522: */ { /* 523: 40 */ private static Vector<GlobalState> values = new Vector(); /* 524: 44 */ public static GlobalState GlobalOff = new GlobalState(0, "GlobalOff"); /* 525: 48 */ public static GlobalState GlobalStartup = new GlobalState(1, "GlobalStartup"); /* 526: 52 */ public static GlobalState GlobalOn = new GlobalState(2, "GlobalOn"); /* 527: 56 */ public static GlobalState GlobalShutdown = new GlobalState(3, "GlobalShutdown"); /* 528: 60 */ public static GlobalState GlobalConfiguring = new GlobalState(4, "GlobalConfiguring"); /* 529: */ private final int mValue; /* 530: */ private final String mStringValue; /* 531: */ /* 532: */ private GlobalState(int value, String stringValue) /* 533: */ { /* 534: 67 */ this.mValue = value; /* 535: 68 */ values.addElement(this); /* 536: 69 */ this.mStringValue = stringValue; /* 537: */ } /* 538: */ /* 539: */ public static GlobalState fromInt(int value) /* 540: */ { /* 541: 73 */ for (int i = 0; i < values.size(); i++) /* 542: */ { /* 543: 74 */ GlobalState state = (GlobalState)values.elementAt(i); /* 544: 75 */ if (state.mValue == value) { /* 545: 75 */ return state; /* 546: */ } /* 547: */ } /* 548: 77 */ throw new RuntimeException("state not found [" + value + "]"); /* 549: */ } /* 550: */ /* 551: */ public String toString() /* 552: */ { /* 553: 80 */ return this.mStringValue; /* 554: */ } /* 555: */ } /* 556: */ /* 557: */ public static class RemoteProvisioningState /* 558: */ { /* 559: 88 */ private static Vector<RemoteProvisioningState> values = new Vector(); /* 560: 92 */ public static RemoteProvisioningState ConfiguringSuccessful = new RemoteProvisioningState(0, "ConfiguringSuccessful"); /* 561: 96 */ public static RemoteProvisioningState ConfiguringFailed = new RemoteProvisioningState(1, "ConfiguringFailed"); /* 562: 100 */ public static RemoteProvisioningState ConfiguringSkipped = new RemoteProvisioningState(2, "ConfiguringSkipped"); /* 563: */ private final int mValue; /* 564: */ private final String mStringValue; /* 565: */ /* 566: */ private RemoteProvisioningState(int value, String stringValue) /* 567: */ { /* 568: 107 */ this.mValue = value; /* 569: 108 */ values.addElement(this); /* 570: 109 */ this.mStringValue = stringValue; /* 571: */ } /* 572: */ /* 573: */ public static RemoteProvisioningState fromInt(int value) /* 574: */ { /* 575: 113 */ for (int i = 0; i < values.size(); i++) /* 576: */ { /* 577: 114 */ RemoteProvisioningState state = (RemoteProvisioningState)values.elementAt(i); /* 578: 115 */ if (state.mValue == value) { /* 579: 115 */ return state; /* 580: */ } /* 581: */ } /* 582: 117 */ throw new RuntimeException("state not found [" + value + "]"); /* 583: */ } /* 584: */ /* 585: */ public String toString() /* 586: */ { /* 587: 120 */ return this.mStringValue; /* 588: */ } /* 589: */ } /* 590: */ /* 591: */ public static class RegistrationState /* 592: */ { /* 593: 129 */ private static Vector<RegistrationState> values = new Vector(); /* 594: 133 */ public static RegistrationState RegistrationNone = new RegistrationState(0, "RegistrationNone"); /* 595: 137 */ public static RegistrationState RegistrationProgress = new RegistrationState(1, "RegistrationProgress"); /* 596: 141 */ public static RegistrationState RegistrationOk = new RegistrationState(2, "RegistrationOk"); /* 597: 145 */ public static RegistrationState RegistrationCleared = new RegistrationState(3, "RegistrationCleared"); /* 598: 149 */ public static RegistrationState RegistrationFailed = new RegistrationState(4, "RegistrationFailed"); /* 599: */ private final int mValue; /* 600: */ private final String mStringValue; /* 601: */ /* 602: */ private RegistrationState(int value, String stringValue) /* 603: */ { /* 604: 155 */ this.mValue = value; /* 605: 156 */ values.addElement(this); /* 606: 157 */ this.mStringValue = stringValue; /* 607: */ } /* 608: */ /* 609: */ public static RegistrationState fromInt(int value) /* 610: */ { /* 611: 161 */ for (int i = 0; i < values.size(); i++) /* 612: */ { /* 613: 162 */ RegistrationState state = (RegistrationState)values.elementAt(i); /* 614: 163 */ if (state.mValue == value) { /* 615: 163 */ return state; /* 616: */ } /* 617: */ } /* 618: 165 */ throw new RuntimeException("state not found [" + value + "]"); /* 619: */ } /* 620: */ /* 621: */ public String toString() /* 622: */ { /* 623: 168 */ return this.mStringValue; /* 624: */ } /* 625: */ } /* 626: */ /* 627: */ public static class FirewallPolicy /* 628: */ { /* 629: 177 */ private static Vector<FirewallPolicy> values = new Vector(); /* 630: 181 */ public static FirewallPolicy NoFirewall = new FirewallPolicy(0, "NoFirewall"); /* 631: 185 */ public static FirewallPolicy UseNatAddress = new FirewallPolicy(1, "UseNatAddress"); /* 632: 189 */ public static FirewallPolicy UseStun = new FirewallPolicy(2, "UseStun"); /* 633: 193 */ public static FirewallPolicy UseIce = new FirewallPolicy(3, "UseIce"); /* 634: 197 */ public static FirewallPolicy UseUpnp = new FirewallPolicy(4, "UseUpnp"); /* 635: */ private final int mValue; /* 636: */ private final String mStringValue; /* 637: */ /* 638: */ private FirewallPolicy(int value, String stringValue) /* 639: */ { /* 640: 204 */ this.mValue = value; /* 641: 205 */ values.addElement(this); /* 642: 206 */ this.mStringValue = stringValue; /* 643: */ } /* 644: */ /* 645: */ public static FirewallPolicy fromInt(int value) /* 646: */ { /* 647: 210 */ for (int i = 0; i < values.size(); i++) /* 648: */ { /* 649: 211 */ FirewallPolicy state = (FirewallPolicy)values.elementAt(i); /* 650: 212 */ if (state.mValue == value) { /* 651: 212 */ return state; /* 652: */ } /* 653: */ } /* 654: 214 */ throw new RuntimeException("state not found [" + value + "]"); /* 655: */ } /* 656: */ /* 657: */ public String toString() /* 658: */ { /* 659: 217 */ return this.mStringValue; /* 660: */ } /* 661: */ /* 662: */ public int value() /* 663: */ { /* 664: 220 */ return this.mValue; /* 665: */ } /* 666: */ } /* 667: */ /* 668: */ public static class Transports /* 669: */ { /* 670: */ public int udp; /* 671: */ public int tcp; /* 672: */ public int tls; /* 673: */ /* 674: */ public Transports() {} /* 675: */ /* 676: */ public Transports(Transports t) /* 677: */ { /* 678: 245 */ this.udp = t.udp; /* 679: 246 */ this.tcp = t.tcp; /* 680: 247 */ this.tls = t.tls; /* 681: */ } /* 682: */ /* 683: */ public String toString() /* 684: */ { /* 685: 250 */ return "udp[" + this.udp + "] tcp[" + this.tcp + "] tls[" + this.tls + "]"; /* 686: */ } /* 687: */ } /* 688: */ /* 689: */ public static final class MediaEncryption /* 690: */ { /* 691: 259 */ private static Vector<MediaEncryption> values = new Vector(); /* 692: 263 */ public static final MediaEncryption None = new MediaEncryption(0, "None"); /* 693: 267 */ public static final MediaEncryption SRTP = new MediaEncryption(1, "SRTP"); /* 694: 271 */ public static final MediaEncryption ZRTP = new MediaEncryption(2, "ZRTP"); /* 695: 275 */ public static final MediaEncryption DTLS = new MediaEncryption(3, "DTLS"); /* 696: */ protected final int mValue; /* 697: */ private final String mStringValue; /* 698: */ /* 699: */ private MediaEncryption(int value, String stringValue) /* 700: */ { /* 701: 281 */ this.mValue = value; /* 702: 282 */ values.addElement(this); /* 703: 283 */ this.mStringValue = stringValue; /* 704: */ } /* 705: */ /* 706: */ public static MediaEncryption fromInt(int value) /* 707: */ { /* 708: 287 */ for (int i = 0; i < values.size(); i++) /* 709: */ { /* 710: 288 */ MediaEncryption menc = (MediaEncryption)values.elementAt(i); /* 711: 289 */ if (menc.mValue == value) { /* 712: 289 */ return menc; /* 713: */ } /* 714: */ } /* 715: 291 */ throw new RuntimeException("MediaEncryption not found [" + value + "]"); /* 716: */ } /* 717: */ /* 718: */ public String toString() /* 719: */ { /* 720: 294 */ return this.mStringValue; /* 721: */ } /* 722: */ } /* 723: */ /* 724: */ public static final class AdaptiveRateAlgorithm /* 725: */ { /* 726: 299 */ private static Vector<AdaptiveRateAlgorithm> values = new Vector(); /* 727: 303 */ public static final AdaptiveRateAlgorithm Simple = new AdaptiveRateAlgorithm(0, "Simple"); /* 728: 307 */ public static final AdaptiveRateAlgorithm Stateful = new AdaptiveRateAlgorithm(1, "Stateful"); /* 729: */ protected final int mValue; /* 730: */ private final String mStringValue; /* 731: */ /* 732: */ private AdaptiveRateAlgorithm(int value, String stringValue) /* 733: */ { /* 734: 313 */ this.mValue = value; /* 735: 314 */ values.addElement(this); /* 736: 315 */ this.mStringValue = stringValue; /* 737: */ } /* 738: */ /* 739: */ public static AdaptiveRateAlgorithm fromString(String value) /* 740: */ { /* 741: 319 */ for (int i = 0; i < values.size(); i++) /* 742: */ { /* 743: 320 */ AdaptiveRateAlgorithm alg = (AdaptiveRateAlgorithm)values.elementAt(i); /* 744: 321 */ if (alg.mStringValue.equalsIgnoreCase(value)) { /* 745: 321 */ return alg; /* 746: */ } /* 747: */ } /* 748: 323 */ throw new RuntimeException("AdaptiveRateAlgorithm not found [" + value + "]"); /* 749: */ } /* 750: */ /* 751: */ public String toString() /* 752: */ { /* 753: 326 */ return this.mStringValue; /* 754: */ } /* 755: */ } /* 756: */ /* 757: */ public static class EcCalibratorStatus /* 758: */ { /* 759: 334 */ private static Vector<EcCalibratorStatus> values = new Vector(); /* 760: */ public static final int IN_PROGRESS_STATUS = 0; /* 761: */ public static final int DONE_STATUS = 1; /* 762: */ public static final int FAILED_STATUS = 2; /* 763: */ public static final int DONE_NO_ECHO_STATUS = 3; /* 764: 344 */ public static EcCalibratorStatus InProgress = new EcCalibratorStatus(0, "InProgress"); /* 765: 348 */ public static EcCalibratorStatus Done = new EcCalibratorStatus(1, "Done"); /* 766: 352 */ public static EcCalibratorStatus Failed = new EcCalibratorStatus(2, "Failed"); /* 767: 356 */ public static EcCalibratorStatus DoneNoEcho = new EcCalibratorStatus(3, "DoneNoEcho"); /* 768: */ private final int mValue; /* 769: */ private final String mStringValue; /* 770: */ /* 771: */ private EcCalibratorStatus(int value, String stringValue) /* 772: */ { /* 773: 363 */ this.mValue = value; /* 774: 364 */ values.addElement(this); /* 775: 365 */ this.mStringValue = stringValue; /* 776: */ } /* 777: */ /* 778: */ public static EcCalibratorStatus fromInt(int value) /* 779: */ { /* 780: 369 */ for (int i = 0; i < values.size(); i++) /* 781: */ { /* 782: 370 */ EcCalibratorStatus status = (EcCalibratorStatus)values.elementAt(i); /* 783: 371 */ if (status.mValue == value) { /* 784: 371 */ return status; /* 785: */ } /* 786: */ } /* 787: 373 */ throw new RuntimeException("status not found [" + value + "]"); /* 788: */ } /* 789: */ /* 790: */ public String toString() /* 791: */ { /* 792: 376 */ return this.mStringValue; /* 793: */ } /* 794: */ /* 795: */ public int value() /* 796: */ { /* 797: 379 */ return this.mValue; /* 798: */ } /* 799: */ } /* 800: */ /* 801: */ public static class UpnpState /* 802: */ { /* 803: 384 */ private static Vector<UpnpState> values = new Vector(); /* 804: 388 */ public static UpnpState Idle = new UpnpState(0, "Idle"); /* 805: 392 */ public static UpnpState Pending = new UpnpState(1, "Pending"); /* 806: 396 */ public static UpnpState Adding = new UpnpState(2, "Adding"); /* 807: 400 */ public static UpnpState Removing = new UpnpState(3, "Removing"); /* 808: 404 */ public static UpnpState NotAvailable = new UpnpState(4, "Not available"); /* 809: 408 */ public static UpnpState Ok = new UpnpState(5, "Ok"); /* 810: 412 */ public static UpnpState Ko = new UpnpState(6, "Ko"); /* 811: 416 */ public static UpnpState Blacklisted = new UpnpState(7, "Blacklisted"); /* 812: */ protected final int mValue; /* 813: */ private final String mStringValue; /* 814: */ /* 815: */ private UpnpState(int value, String stringValue) /* 816: */ { /* 817: 422 */ this.mValue = value; /* 818: 423 */ values.addElement(this); /* 819: 424 */ this.mStringValue = stringValue; /* 820: */ } /* 821: */ /* 822: */ public static UpnpState fromInt(int value) /* 823: */ { /* 824: 427 */ for (int i = 0; i < values.size(); i++) /* 825: */ { /* 826: 428 */ UpnpState mstate = (UpnpState)values.elementAt(i); /* 827: 429 */ if (mstate.mValue == value) { /* 828: 429 */ return mstate; /* 829: */ } /* 830: */ } /* 831: 431 */ throw new RuntimeException("UpnpState not found [" + value + "]"); /* 832: */ } /* 833: */ /* 834: */ public String toString() /* 835: */ { /* 836: 434 */ return this.mStringValue; /* 837: */ } /* 838: */ } /* 839: */ /* 840: */ public static class LogCollectionUploadState /* 841: */ { /* 842: 442 */ private static Vector<LogCollectionUploadState> values = new Vector(); /* 843: 446 */ public static LogCollectionUploadState LogCollectionUploadStateInProgress = new LogCollectionUploadState(0, "LinphoneCoreLogCollectionUploadStateInProgress"); /* 844: 450 */ public static LogCollectionUploadState LogCollectionUploadStateDelivered = new LogCollectionUploadState(1, "LinphoneCoreLogCollectionUploadStateDelivered"); /* 845: 454 */ public static LogCollectionUploadState LogCollectionUploadStateNotDelivered = new LogCollectionUploadState(2, "LinphoneCoreLogCollectionUploadStateNotDelivered"); /* 846: */ private final int mValue; /* 847: */ private final String mStringValue; /* 848: */ /* 849: */ private LogCollectionUploadState(int value, String stringValue) /* 850: */ { /* 851: 460 */ this.mValue = value; /* 852: 461 */ values.addElement(this); /* 853: 462 */ this.mStringValue = stringValue; /* 854: */ } /* 855: */ /* 856: */ public static LogCollectionUploadState fromInt(int value) /* 857: */ { /* 858: 466 */ for (int i = 0; i < values.size(); i++) /* 859: */ { /* 860: 467 */ LogCollectionUploadState state = (LogCollectionUploadState)values.elementAt(i); /* 861: 468 */ if (state.mValue == value) { /* 862: 468 */ return state; /* 863: */ } /* 864: */ } /* 865: 470 */ throw new RuntimeException("state not found [" + value + "]"); /* 866: */ } /* 867: */ /* 868: */ public String toString() /* 869: */ { /* 870: 473 */ return this.mStringValue; /* 871: */ } /* 872: */ } /* 873: */ /* 874: */ public static enum TunnelMode /* 875: */ { /* 876:1394 */ disable(0), enable(1), auto(2); /* 877: */ /* 878: */ private final int value; /* 879: */ /* 880: */ private TunnelMode(int value) /* 881: */ { /* 882:1400 */ this.value = value; /* 883: */ } /* 884: */ /* 885: */ public static int enumToInt(TunnelMode enum_mode) /* 886: */ { /* 887:1403 */ return enum_mode.value; /* 888: */ } /* 889: */ /* 890: */ public static TunnelMode intToEnum(int value) /* 891: */ { /* 892:1406 */ switch (value) /* 893: */ { /* 894: */ case 0: /* 895:1407 */ return disable; /* 896: */ case 1: /* 897:1408 */ return enable; /* 898: */ case 2: /* 899:1409 */ return auto; /* 900: */ } /* 901:1410 */ return disable; /* 902: */ } /* 903: */ } /* 904: */ } /* Location: E:\DO-AN\Libraries\linphone-android-sdk-2.4.0\libs\LinLinphone\linphone.jar * Qualified Name: org.linphone.core.LinphoneCore * JD-Core Version: 0.7.0.1 */
package structures.graph.list.model; import com.herz.structures.graph.list.model.GraphLinkedList; public enum GraphDataTypes { INTEGERINTEGER { @Override public GraphLinkedList<Integer, Integer> createGraph() { return new GraphLinkedList<>(); } }, INTEGERFLOAT { @Override public GraphLinkedList<Integer, Float> createGraph() { return new GraphLinkedList<>(); } }, INTEGERCHARACTER { @Override public GraphLinkedList<Integer, Character> createGraph() { return new GraphLinkedList<>(); } }, INTEGERBOOLEAN { @Override public GraphLinkedList<Integer, Boolean> createGraph() { return new GraphLinkedList<>(); } }, INTEGERSTRING { @Override public GraphLinkedList<Integer, String> createGraph() { return new GraphLinkedList<>(); } }, FLOATINTEGER { @Override public GraphLinkedList<Float, Integer> createGraph() { return new GraphLinkedList<>(); } }, FLOATFLOAT { @Override public GraphLinkedList<Float, Float> createGraph() { return new GraphLinkedList<>(); } }, FLOATCHARACTER { @Override public GraphLinkedList<Float, Character> createGraph() { return new GraphLinkedList<>(); } }, FLOATBOOLEAN { @Override public GraphLinkedList<Float, Boolean> createGraph() { return new GraphLinkedList<>(); } }, FLOATSTRING { @Override public GraphLinkedList<Float, String> createGraph() { return new GraphLinkedList<>(); } }, CHARACTERINTEGER { @Override public GraphLinkedList<Character, Integer> createGraph() { return new GraphLinkedList<>(); } }, CHARACTERFLOAT { @Override public GraphLinkedList<Character, Float> createGraph() { return new GraphLinkedList<>(); } }, CHARACTERCHARACTER { @Override public GraphLinkedList<Character, Character> createGraph() { return new GraphLinkedList<>(); } }, CHARACTERBOOLEAN { @Override public GraphLinkedList<Character, Boolean> createGraph() { return new GraphLinkedList<>(); } }, CHARACTERSTRING { @Override public GraphLinkedList<Character, String> createGraph() { return new GraphLinkedList<>(); } }, BOOLEANINTEGER { @Override public GraphLinkedList<Boolean, Integer> createGraph() { return new GraphLinkedList<>(); } }, BOOLEANFLOAT { @Override public GraphLinkedList<Boolean, Float> createGraph() { return new GraphLinkedList<>(); } }, BOOLEANCHARACTER { @Override public GraphLinkedList<Boolean, Character> createGraph() { return new GraphLinkedList<>(); } }, BOOLEANBOOLEAN { @Override public GraphLinkedList<Boolean, Boolean> createGraph() { return new GraphLinkedList<>(); } }, BOOLEANSTRING { @Override public GraphLinkedList<Boolean, String> createGraph() { return new GraphLinkedList<>(); } }, STRINGINTEGER { @Override public GraphLinkedList<String, Integer> createGraph() { return new GraphLinkedList<>(); } }, STRINGFLOAT { @Override public GraphLinkedList<String, Float> createGraph() { return new GraphLinkedList<>(); } }, STRINGCHARACTER { @Override public GraphLinkedList<String, Character> createGraph() { return new GraphLinkedList<>(); } }, STRINGBOOLEAN { @Override public GraphLinkedList<String, Boolean> createGraph() { return new GraphLinkedList<>(); } }, STRINGSTRING { @Override public GraphLinkedList<String, String> createGraph() { return new GraphLinkedList<>(); } }; public abstract GraphLinkedList createGraph(); }
package net.minecraft.entity.passive; import javax.annotation.Nullable; import net.minecraft.block.Block; import net.minecraft.block.BlockCarrot; import net.minecraft.block.properties.IProperty; import net.minecraft.block.state.IBlockState; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityAgeable; import net.minecraft.entity.EntityCreature; import net.minecraft.entity.EntityLiving; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.IEntityLivingData; import net.minecraft.entity.SharedMonsterAttributes; import net.minecraft.entity.ai.EntityAIAttackMelee; import net.minecraft.entity.ai.EntityAIAvoidEntity; import net.minecraft.entity.ai.EntityAIBase; import net.minecraft.entity.ai.EntityAIHurtByTarget; import net.minecraft.entity.ai.EntityAIMate; import net.minecraft.entity.ai.EntityAIMoveToBlock; import net.minecraft.entity.ai.EntityAINearestAttackableTarget; import net.minecraft.entity.ai.EntityAIPanic; import net.minecraft.entity.ai.EntityAISwimming; import net.minecraft.entity.ai.EntityAITempt; import net.minecraft.entity.ai.EntityAIWanderAvoidWater; import net.minecraft.entity.ai.EntityAIWatchClosest; import net.minecraft.entity.ai.EntityJumpHelper; import net.minecraft.entity.ai.EntityMoveHelper; import net.minecraft.entity.monster.EntityMob; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.init.Blocks; import net.minecraft.init.Items; import net.minecraft.init.SoundEvents; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.network.datasync.DataParameter; import net.minecraft.network.datasync.DataSerializers; import net.minecraft.network.datasync.EntityDataManager; import net.minecraft.pathfinding.Path; import net.minecraft.util.DamageSource; import net.minecraft.util.EnumParticleTypes; import net.minecraft.util.ResourceLocation; import net.minecraft.util.SoundCategory; import net.minecraft.util.SoundEvent; import net.minecraft.util.datafix.DataFixer; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.MathHelper; import net.minecraft.util.math.Vec3d; import net.minecraft.util.text.translation.I18n; import net.minecraft.world.DifficultyInstance; import net.minecraft.world.World; import net.minecraft.world.biome.Biome; import net.minecraft.world.storage.loot.LootTableList; public class EntityRabbit extends EntityAnimal { private static final DataParameter<Integer> RABBIT_TYPE = EntityDataManager.createKey(EntityRabbit.class, DataSerializers.VARINT); private int jumpTicks; private int jumpDuration; private boolean wasOnGround; private int currentMoveTypeDuration; private int carrotTicks; public EntityRabbit(World worldIn) { super(worldIn); setSize(0.4F, 0.5F); this.jumpHelper = new RabbitJumpHelper(this); this.moveHelper = new RabbitMoveHelper(this); setMovementSpeed(0.0D); } protected void initEntityAI() { this.tasks.addTask(1, (EntityAIBase)new EntityAISwimming((EntityLiving)this)); this.tasks.addTask(1, (EntityAIBase)new AIPanic(this, 2.2D)); this.tasks.addTask(2, (EntityAIBase)new EntityAIMate(this, 0.8D)); this.tasks.addTask(3, (EntityAIBase)new EntityAITempt((EntityCreature)this, 1.0D, Items.CARROT, false)); this.tasks.addTask(3, (EntityAIBase)new EntityAITempt((EntityCreature)this, 1.0D, Items.GOLDEN_CARROT, false)); this.tasks.addTask(3, (EntityAIBase)new EntityAITempt((EntityCreature)this, 1.0D, Item.getItemFromBlock((Block)Blocks.YELLOW_FLOWER), false)); this.tasks.addTask(4, (EntityAIBase)new AIAvoidEntity<>(this, EntityPlayer.class, 8.0F, 2.2D, 2.2D)); this.tasks.addTask(4, (EntityAIBase)new AIAvoidEntity<>(this, EntityWolf.class, 10.0F, 2.2D, 2.2D)); this.tasks.addTask(4, (EntityAIBase)new AIAvoidEntity<>(this, EntityMob.class, 4.0F, 2.2D, 2.2D)); this.tasks.addTask(5, (EntityAIBase)new AIRaidFarm(this)); this.tasks.addTask(6, (EntityAIBase)new EntityAIWanderAvoidWater((EntityCreature)this, 0.6D)); this.tasks.addTask(11, (EntityAIBase)new EntityAIWatchClosest((EntityLiving)this, EntityPlayer.class, 10.0F)); } protected float getJumpUpwardsMotion() { if (!this.isCollidedHorizontally && (!this.moveHelper.isUpdating() || this.moveHelper.getY() <= this.posY + 0.5D)) { Path path = this.navigator.getPath(); if (path != null && path.getCurrentPathIndex() < path.getCurrentPathLength()) { Vec3d vec3d = path.getPosition((Entity)this); if (vec3d.yCoord > this.posY + 0.5D) return 0.5F; } return (this.moveHelper.getSpeed() <= 0.6D) ? 0.2F : 0.3F; } return 0.5F; } protected void jump() { super.jump(); double d0 = this.moveHelper.getSpeed(); if (d0 > 0.0D) { double d1 = this.motionX * this.motionX + this.motionZ * this.motionZ; if (d1 < 0.010000000000000002D) func_191958_b(0.0F, 0.0F, 1.0F, 0.1F); } if (!this.world.isRemote) this.world.setEntityState((Entity)this, (byte)1); } public float setJumpCompletion(float p_175521_1_) { return (this.jumpDuration == 0) ? 0.0F : ((this.jumpTicks + p_175521_1_) / this.jumpDuration); } public void setMovementSpeed(double newSpeed) { getNavigator().setSpeed(newSpeed); this.moveHelper.setMoveTo(this.moveHelper.getX(), this.moveHelper.getY(), this.moveHelper.getZ(), newSpeed); } public void setJumping(boolean jumping) { super.setJumping(jumping); if (jumping) playSound(getJumpSound(), getSoundVolume(), ((this.rand.nextFloat() - this.rand.nextFloat()) * 0.2F + 1.0F) * 0.8F); } public void startJumping() { setJumping(true); this.jumpDuration = 10; this.jumpTicks = 0; } protected void entityInit() { super.entityInit(); this.dataManager.register(RABBIT_TYPE, Integer.valueOf(0)); } public void updateAITasks() { if (this.currentMoveTypeDuration > 0) this.currentMoveTypeDuration--; if (this.carrotTicks > 0) { this.carrotTicks -= this.rand.nextInt(3); if (this.carrotTicks < 0) this.carrotTicks = 0; } if (this.onGround) { if (!this.wasOnGround) { setJumping(false); checkLandingDelay(); } if (getRabbitType() == 99 && this.currentMoveTypeDuration == 0) { EntityLivingBase entitylivingbase = getAttackTarget(); if (entitylivingbase != null && getDistanceSqToEntity((Entity)entitylivingbase) < 16.0D) { calculateRotationYaw(entitylivingbase.posX, entitylivingbase.posZ); this.moveHelper.setMoveTo(entitylivingbase.posX, entitylivingbase.posY, entitylivingbase.posZ, this.moveHelper.getSpeed()); startJumping(); this.wasOnGround = true; } } RabbitJumpHelper entityrabbit$rabbitjumphelper = (RabbitJumpHelper)this.jumpHelper; if (!entityrabbit$rabbitjumphelper.getIsJumping()) { if (this.moveHelper.isUpdating() && this.currentMoveTypeDuration == 0) { Path path = this.navigator.getPath(); Vec3d vec3d = new Vec3d(this.moveHelper.getX(), this.moveHelper.getY(), this.moveHelper.getZ()); if (path != null && path.getCurrentPathIndex() < path.getCurrentPathLength()) vec3d = path.getPosition((Entity)this); calculateRotationYaw(vec3d.xCoord, vec3d.zCoord); startJumping(); } } else if (!entityrabbit$rabbitjumphelper.canJump()) { enableJumpControl(); } } this.wasOnGround = this.onGround; } public void spawnRunningParticles() {} private void calculateRotationYaw(double x, double z) { this.rotationYaw = (float)(MathHelper.atan2(z - this.posZ, x - this.posX) * 57.29577951308232D) - 90.0F; } private void enableJumpControl() { ((RabbitJumpHelper)this.jumpHelper).setCanJump(true); } private void disableJumpControl() { ((RabbitJumpHelper)this.jumpHelper).setCanJump(false); } private void updateMoveTypeDuration() { if (this.moveHelper.getSpeed() < 2.2D) { this.currentMoveTypeDuration = 10; } else { this.currentMoveTypeDuration = 1; } } private void checkLandingDelay() { updateMoveTypeDuration(); disableJumpControl(); } public void onLivingUpdate() { super.onLivingUpdate(); if (this.jumpTicks != this.jumpDuration) { this.jumpTicks++; } else if (this.jumpDuration != 0) { this.jumpTicks = 0; this.jumpDuration = 0; setJumping(false); } } protected void applyEntityAttributes() { super.applyEntityAttributes(); getEntityAttribute(SharedMonsterAttributes.MAX_HEALTH).setBaseValue(3.0D); getEntityAttribute(SharedMonsterAttributes.MOVEMENT_SPEED).setBaseValue(0.30000001192092896D); } public static void registerFixesRabbit(DataFixer fixer) { EntityLiving.registerFixesMob(fixer, EntityRabbit.class); } public void writeEntityToNBT(NBTTagCompound compound) { super.writeEntityToNBT(compound); compound.setInteger("RabbitType", getRabbitType()); compound.setInteger("MoreCarrotTicks", this.carrotTicks); } public void readEntityFromNBT(NBTTagCompound compound) { super.readEntityFromNBT(compound); setRabbitType(compound.getInteger("RabbitType")); this.carrotTicks = compound.getInteger("MoreCarrotTicks"); } protected SoundEvent getJumpSound() { return SoundEvents.ENTITY_RABBIT_JUMP; } protected SoundEvent getAmbientSound() { return SoundEvents.ENTITY_RABBIT_AMBIENT; } protected SoundEvent getHurtSound(DamageSource p_184601_1_) { return SoundEvents.ENTITY_RABBIT_HURT; } protected SoundEvent getDeathSound() { return SoundEvents.ENTITY_RABBIT_DEATH; } public boolean attackEntityAsMob(Entity entityIn) { if (getRabbitType() == 99) { playSound(SoundEvents.ENTITY_RABBIT_ATTACK, 1.0F, (this.rand.nextFloat() - this.rand.nextFloat()) * 0.2F + 1.0F); return entityIn.attackEntityFrom(DamageSource.causeMobDamage((EntityLivingBase)this), 8.0F); } return entityIn.attackEntityFrom(DamageSource.causeMobDamage((EntityLivingBase)this), 3.0F); } public SoundCategory getSoundCategory() { return (getRabbitType() == 99) ? SoundCategory.HOSTILE : SoundCategory.NEUTRAL; } public boolean attackEntityFrom(DamageSource source, float amount) { return isEntityInvulnerable(source) ? false : super.attackEntityFrom(source, amount); } @Nullable protected ResourceLocation getLootTable() { return LootTableList.ENTITIES_RABBIT; } private boolean isRabbitBreedingItem(Item itemIn) { return !(itemIn != Items.CARROT && itemIn != Items.GOLDEN_CARROT && itemIn != Item.getItemFromBlock((Block)Blocks.YELLOW_FLOWER)); } public EntityRabbit createChild(EntityAgeable ageable) { EntityRabbit entityrabbit = new EntityRabbit(this.world); int i = getRandomRabbitType(); if (this.rand.nextInt(20) != 0) if (ageable instanceof EntityRabbit && this.rand.nextBoolean()) { i = ((EntityRabbit)ageable).getRabbitType(); } else { i = getRabbitType(); } entityrabbit.setRabbitType(i); return entityrabbit; } public boolean isBreedingItem(ItemStack stack) { return isRabbitBreedingItem(stack.getItem()); } public int getRabbitType() { return ((Integer)this.dataManager.get(RABBIT_TYPE)).intValue(); } public void setRabbitType(int rabbitTypeId) { if (rabbitTypeId == 99) { getEntityAttribute(SharedMonsterAttributes.ARMOR).setBaseValue(8.0D); this.tasks.addTask(4, (EntityAIBase)new AIEvilAttack(this)); this.targetTasks.addTask(1, (EntityAIBase)new EntityAIHurtByTarget((EntityCreature)this, false, new Class[0])); this.targetTasks.addTask(2, (EntityAIBase)new EntityAINearestAttackableTarget((EntityCreature)this, EntityPlayer.class, true)); this.targetTasks.addTask(2, (EntityAIBase)new EntityAINearestAttackableTarget((EntityCreature)this, EntityWolf.class, true)); if (!hasCustomName()) setCustomNameTag(I18n.translateToLocal("entity.KillerBunny.name")); } this.dataManager.set(RABBIT_TYPE, Integer.valueOf(rabbitTypeId)); } @Nullable public IEntityLivingData onInitialSpawn(DifficultyInstance difficulty, @Nullable IEntityLivingData livingdata) { livingdata = super.onInitialSpawn(difficulty, livingdata); int i = getRandomRabbitType(); boolean flag = false; if (livingdata instanceof RabbitTypeData) { i = ((RabbitTypeData)livingdata).typeData; flag = true; } else { livingdata = new RabbitTypeData(i); } setRabbitType(i); if (flag) setGrowingAge(-24000); return livingdata; } private int getRandomRabbitType() { Biome biome = this.world.getBiome(new BlockPos((Entity)this)); int i = this.rand.nextInt(100); if (biome.isSnowyBiome()) return (i < 80) ? 1 : 3; if (biome instanceof net.minecraft.world.biome.BiomeDesert) return 4; return (i < 50) ? 0 : ((i < 90) ? 5 : 2); } private boolean isCarrotEaten() { return (this.carrotTicks == 0); } protected void createEatingParticles() { BlockCarrot blockcarrot = (BlockCarrot)Blocks.CARROTS; IBlockState iblockstate = blockcarrot.withAge(blockcarrot.getMaxAge()); this.world.spawnParticle(EnumParticleTypes.BLOCK_DUST, this.posX + (this.rand.nextFloat() * this.width * 2.0F) - this.width, this.posY + 0.5D + (this.rand.nextFloat() * this.height), this.posZ + (this.rand.nextFloat() * this.width * 2.0F) - this.width, 0.0D, 0.0D, 0.0D, new int[] { Block.getStateId(iblockstate) }); this.carrotTicks = 40; } public void handleStatusUpdate(byte id) { if (id == 1) { createRunningParticles(); this.jumpDuration = 10; this.jumpTicks = 0; } else { super.handleStatusUpdate(id); } } static class AIAvoidEntity<T extends Entity> extends EntityAIAvoidEntity<T> { private final EntityRabbit entityInstance; public AIAvoidEntity(EntityRabbit rabbit, Class<T> p_i46403_2_, float p_i46403_3_, double p_i46403_4_, double p_i46403_6_) { super((EntityCreature)rabbit, p_i46403_2_, p_i46403_3_, p_i46403_4_, p_i46403_6_); this.entityInstance = rabbit; } public boolean shouldExecute() { return (this.entityInstance.getRabbitType() != 99 && super.shouldExecute()); } } static class AIEvilAttack extends EntityAIAttackMelee { public AIEvilAttack(EntityRabbit rabbit) { super((EntityCreature)rabbit, 1.4D, true); } protected double getAttackReachSqr(EntityLivingBase attackTarget) { return (4.0F + attackTarget.width); } } static class AIPanic extends EntityAIPanic { private final EntityRabbit theEntity; public AIPanic(EntityRabbit rabbit, double speedIn) { super((EntityCreature)rabbit, speedIn); this.theEntity = rabbit; } public void updateTask() { super.updateTask(); this.theEntity.setMovementSpeed(this.speed); } } static class AIRaidFarm extends EntityAIMoveToBlock { private final EntityRabbit rabbit; private boolean wantsToRaid; private boolean canRaid; public AIRaidFarm(EntityRabbit rabbitIn) { super((EntityCreature)rabbitIn, 0.699999988079071D, 16); this.rabbit = rabbitIn; } public boolean shouldExecute() { if (this.runDelay <= 0) { if (!this.rabbit.world.getGameRules().getBoolean("mobGriefing")) return false; this.canRaid = false; this.wantsToRaid = this.rabbit.isCarrotEaten(); this.wantsToRaid = true; } return super.shouldExecute(); } public boolean continueExecuting() { return (this.canRaid && super.continueExecuting()); } public void updateTask() { super.updateTask(); this.rabbit.getLookHelper().setLookPosition(this.destinationBlock.getX() + 0.5D, (this.destinationBlock.getY() + 1), this.destinationBlock.getZ() + 0.5D, 10.0F, this.rabbit.getVerticalFaceSpeed()); if (getIsAboveDestination()) { World world = this.rabbit.world; BlockPos blockpos = this.destinationBlock.up(); IBlockState iblockstate = world.getBlockState(blockpos); Block block = iblockstate.getBlock(); if (this.canRaid && block instanceof BlockCarrot) { Integer integer = (Integer)iblockstate.getValue((IProperty)BlockCarrot.AGE); if (integer.intValue() == 0) { world.setBlockState(blockpos, Blocks.AIR.getDefaultState(), 2); world.destroyBlock(blockpos, true); } else { world.setBlockState(blockpos, iblockstate.withProperty((IProperty)BlockCarrot.AGE, Integer.valueOf(integer.intValue() - 1)), 2); world.playEvent(2001, blockpos, Block.getStateId(iblockstate)); } this.rabbit.createEatingParticles(); } this.canRaid = false; this.runDelay = 10; } } protected boolean shouldMoveTo(World worldIn, BlockPos pos) { Block block = worldIn.getBlockState(pos).getBlock(); if (block == Blocks.FARMLAND && this.wantsToRaid && !this.canRaid) { pos = pos.up(); IBlockState iblockstate = worldIn.getBlockState(pos); block = iblockstate.getBlock(); if (block instanceof BlockCarrot && ((BlockCarrot)block).isMaxAge(iblockstate)) { this.canRaid = true; return true; } } return false; } } public class RabbitJumpHelper extends EntityJumpHelper { private final EntityRabbit theEntity; private boolean canJump; public RabbitJumpHelper(EntityRabbit rabbit) { super((EntityLiving)rabbit); this.theEntity = rabbit; } public boolean getIsJumping() { return this.isJumping; } public boolean canJump() { return this.canJump; } public void setCanJump(boolean canJumpIn) { this.canJump = canJumpIn; } public void doJump() { if (this.isJumping) { this.theEntity.startJumping(); this.isJumping = false; } } } static class RabbitMoveHelper extends EntityMoveHelper { private final EntityRabbit theEntity; private double nextJumpSpeed; public RabbitMoveHelper(EntityRabbit rabbit) { super((EntityLiving)rabbit); this.theEntity = rabbit; } public void onUpdateMoveHelper() { if (this.theEntity.onGround && !this.theEntity.isJumping && !((EntityRabbit.RabbitJumpHelper)this.theEntity.jumpHelper).getIsJumping()) { this.theEntity.setMovementSpeed(0.0D); } else if (isUpdating()) { this.theEntity.setMovementSpeed(this.nextJumpSpeed); } super.onUpdateMoveHelper(); } public void setMoveTo(double x, double y, double z, double speedIn) { if (this.theEntity.isInWater()) speedIn = 1.5D; super.setMoveTo(x, y, z, speedIn); if (speedIn > 0.0D) this.nextJumpSpeed = speedIn; } } public static class RabbitTypeData implements IEntityLivingData { public int typeData; public RabbitTypeData(int type) { this.typeData = type; } } } /* Location: C:\Users\BSV\AppData\Local\Temp\Rar$DRa6216.20396\Preview\Preview.jar!\net\minecraft\entity\passive\EntityRabbit.class * Java compiler version: 8 (52.0) * JD-Core Version: 1.1.3 */
package dao; import entity.PersonalHasUser; public interface PersonalHasUserDAO { }
package monopoly.controller; import javafx.beans.binding.Bindings; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.concurrent.Task; import javafx.concurrent.Worker; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.fxml.Initializable; import javafx.scene.Node; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.control.*; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.image.WritableImage; import javafx.scene.input.MouseEvent; import javafx.stage.FileChooser; import javafx.stage.Stage; import javafx.stage.StageStyle; import javafx.util.StringConverter; import javafx.util.converter.IntegerStringConverter; import monopoly.model.dice.MultipleDiceResult; import monopoly.model.field.Property; import monopoly.model.field.UpgradeableField; import monopoly.model.player.Player; import monopoly.viewmodel.ViewModel; import java.io.File; import java.io.IOException; import java.net.URL; import java.util.*; public class Controller implements Initializable { private final ViewModel viewModel; private Random rand; private static Image pieceBlueImage = new Image(Controller.class.getResourceAsStream("/Images/pieceBlue.png")); private static Image pieceGreenImage = new Image(Controller.class.getResourceAsStream("/Images/pieceGreen.png")); private static Image pieceRedImage = new Image(Controller.class.getResourceAsStream("/Images/pieceRed.png")); private static Image pieceYellowImage = new Image(Controller.class.getResourceAsStream("/Images/pieceYellow.png")); private static WritableImage emptyImage = new WritableImage(50, 68); private static ObservableList<Image> diceImageList = FXCollections.observableArrayList( new Image(Controller.class.getResourceAsStream("/Images/diceOne.png")), new Image(Controller.class.getResourceAsStream("/Images/diceTwo.png")), new Image(Controller.class.getResourceAsStream("/Images/diceThree.png")), new Image(Controller.class.getResourceAsStream("/Images/diceFour.png")), new Image(Controller.class.getResourceAsStream("/Images/diceFive.png")), new Image(Controller.class.getResourceAsStream("/Images/diceSix.png"))); //region FXML stuff @FXML private javafx.scene.control.ListView logPropertyList; @FXML private TextField sendButtonTextField; @FXML private TextArea chatTextArea; @FXML private ImageView field5_player2; @FXML private ImageView field5_player1; @FXML private ImageView field34_player0; @FXML private ImageView field5_player3; @FXML private ImageView field34_player2; @FXML private ImageView field34_player1; @FXML private ImageView field5_player0; @FXML private ImageView field34_player3; @FXML private ImageView field38_player3; @FXML private ImageView field38_player2; @FXML private ImageView field38_player1; @FXML private ImageView field9_player3; @FXML private ImageView field9_player1; @FXML private ImageView field9_player2; @FXML private ImageView field9_player0; @FXML private ImageView field38_player0; @FXML private ImageView field19_player2; @FXML private ImageView field21_player1; @FXML private ImageView field19_player3; @FXML private ImageView field21_player2; @FXML private ImageView field21_player0; @FXML private ImageView field19_player0; @FXML private ImageView field21_player3; @FXML private Label player2MoneyLabel; @FXML private javafx.scene.control.ListView player2PropertyList; @FXML private ImageView field19_player1; @FXML private Tab player3Tab; @FXML private ImageView field12_player2; @FXML private ImageView field28_player1; @FXML private ImageView field12_player1; @FXML private ImageView field28_player0; @FXML private ImageView field28_player3; @FXML private ImageView field12_player3; @FXML private ImageView field28_player2; @FXML private ImageView field12_player0; @FXML private ImageView field24_player0; @FXML private ImageView field16_player3; @FXML private ImageView field24_player1; @FXML private ImageView field16_player2; @FXML private ImageView field24_player2; @FXML private ImageView field16_player1; @FXML private ImageView field24_player3; @FXML private ImageView field16_player0; @FXML private ImageView field1_player3; @FXML private ImageView field1_player2; @FXML private Label player1MoneyLabel; @FXML private javafx.scene.control.ListView player1PropertyList; @FXML private ImageView field1_player1; @FXML private ImageView field31_player0; @FXML private ImageView field31_player1; @FXML private ImageView field31_player2; @FXML private ImageView field31_player3; @FXML private Button buyPropertyButton; @FXML private ImageView field1_player0; @FXML private ImageView field35_player2; @FXML private ImageView field35_player3; @FXML private ImageView field35_player0; @FXML private ImageView field35_player1; @FXML private ImageView field20_player2; @FXML private ImageView field20_player3; @FXML private ImageView field20_player0; @FXML private ImageView field20_player1; @FXML private ImageView field39_player2; @FXML private ImageView field39_player1; @FXML private ImageView field39_player0; @FXML private Label player0MoneyLabel; @FXML private javafx.scene.control.ListView player0PropertyList; @FXML private ImageView field18_player0; @FXML private ImageView field18_player1; @FXML private ImageView field18_player2; @FXML private ImageView field6_player1; @FXML private ImageView field18_player3; @FXML private ImageView field6_player0; @FXML private ImageView field6_player3; @FXML private ImageView field6_player2; @FXML private ImageView field11_player1; @FXML private ImageView field27_player0; @FXML private ImageView field11_player0; @FXML private ImageView field11_player3; @FXML private ImageView field11_player2; @FXML private ImageView field15_player3; @FXML private ImageView field15_player2; @FXML private ImageView field2_player3; @FXML private ImageView field15_player1; @FXML private ImageView field2_player2; @FXML private ImageView field15_player0; @FXML private ImageView field2_player1; @FXML private ImageView field2_player0; @FXML private Label player3MoneyLabel; @FXML private javafx.scene.control.ListView player3PropertyList; @FXML private ImageView field27_player2; @FXML private ImageView field27_player1; @FXML private Tab player0Tab; @FXML private ImageView field27_player3; @FXML private ImageView field36_player3; @FXML private ImageView field39_player3; @FXML private ImageView field7_player3; @FXML private ImageView field3_player3; @FXML private ImageView field32_player0; @FXML private ImageView field32_player1; @FXML private ImageView field32_player2; @FXML private ImageView field32_player3; @FXML private ImageView field3_player0; @FXML private ImageView field3_player1; @FXML private ImageView field3_player2; @FXML private ImageView field23_player0; @FXML private ImageView field17_player0; @FXML private ImageView field17_player1; @FXML private ImageView field23_player3; @FXML private ImageView field17_player2; @FXML private ImageView field23_player2; @FXML private ImageView field17_player3; @FXML private ImageView field23_player1; @FXML private ImageView field7_player1; @FXML private ImageView field7_player2; @FXML private ImageView field7_player0; @FXML private ImageView field36_player1; @FXML private ImageView field36_player2; @FXML private ImageView field36_player0; @FXML private Button sellPropertyButton; @FXML private Button endTurnButton; @FXML private ImageView field14_player3; @FXML private ImageView field26_player1; @FXML private ImageView field26_player0; @FXML private ImageView field10_player3; @FXML private ImageView field10_player0; @FXML private ImageView field10_player2; @FXML private ImageView field10_player1; @FXML private ImageView field14_player1; @FXML private ImageView field26_player3; @FXML private Tab player2Tab; @FXML private ImageView field14_player2; @FXML private ImageView field26_player2; @FXML private ImageView field14_player0; @FXML private ImageView field4_player0; @FXML private ImageView field4_player1; @FXML private ImageView field4_player2; @FXML private ImageView field4_player3; @FXML private Button mortgageButton; @FXML private ImageView field37_player2; @FXML private ImageView field37_player3; @FXML private ImageView field33_player3; @FXML private ImageView field33_player2; @FXML private ImageView field8_player2; @FXML private ImageView field8_player3; @FXML private ImageView field33_player1; @FXML private ImageView field33_player0; @FXML private Button rollDiceButton; @FXML private ImageView field8_player0; @FXML private ImageView field8_player1; @FXML private ImageView field37_player0; @FXML private ImageView field37_player1; @FXML private ImageView field22_player3; @FXML private ImageView field22_player2; @FXML private ImageView field22_player1; @FXML private ImageView field22_player0; @FXML private Tab player1Tab; @FXML private ImageView field29_player3; @FXML private ImageView field29_player1; @FXML private ImageView field29_player2; @FXML private ImageView field29_player0; @FXML private ImageView field25_player0; @FXML private ImageView field25_player1; @FXML private ImageView field25_player2; @FXML private ImageView field0_player1; @FXML private ImageView field30_player0; @FXML private ImageView field0_player0; @FXML private ImageView field25_player3; @FXML private ImageView field13_player2; @FXML private ImageView field13_player3; @FXML private ImageView field30_player3; @FXML private ImageView field0_player3; @FXML private ImageView field13_player0; @FXML private ImageView field30_player2; @FXML private ImageView field0_player2; @FXML private ImageView field13_player1; @FXML private ImageView field30_player1; @FXML private ImageView firstDiceImage; @FXML private ImageView secondDiceImage; @FXML private ImageView jailField_player0; @FXML private ImageView jailField_player1; @FXML private ImageView jailField_player2; @FXML private ImageView jailField_player3; @FXML private TabPane playersTabPane; @FXML private Label currentPlayerLabel; @FXML private Label bankMoneyLabel; @FXML private Label bankHousesLabel; @FXML private Label bankHotelsLabel; @FXML private Button buyHouseButton; @FXML private Button sellHouseButton; @FXML private Label propertyNameLabel; @FXML private Label propertyHotelsLabel; @FXML private Label propertyPriceLabel; @FXML private Label propertyW2Label; @FXML private Label propertyWHLabel; @FXML private Label propertyHousesLabel; @FXML private Label propertyW4Label; @FXML private Label propertyW3Label; @FXML private Label propertyHouseCostLabel; @FXML private Label propertyRentLabel; @FXML private Label propertyW1Label; @FXML private Label purple1Label; @FXML private Label purple2Label; @FXML private Label teal1Label; @FXML private Label teal2Label; @FXML private Label teal3Label; @FXML private Label pink1Label; @FXML private Label pink2Label; @FXML private Label pink3Label; @FXML private Label brown1Label; @FXML private Label brown2Label; @FXML private Label brown3Label; @FXML private Label crimson1Label; @FXML private Label crimson2Label; @FXML private Label crimson3Label; @FXML private Label gold1Label; @FXML private Label gold2Label; @FXML private Label gold3Label; @FXML private Label green1Label; @FXML private Label green2Label; @FXML private Label green3Label; @FXML private Label blue1Label; @FXML private Label blue2Label; //endregion public Controller(ViewModel viewModel) { this.viewModel = viewModel; rand = new Random(); //TODO: Randomizer? } @Override public void initialize(URL url, ResourceBundle resourceBundle) { StringConverter<? extends Number> converter = new IntegerStringConverter(); player0MoneyLabel.textProperty().bindBidirectional(viewModel.getPlayerMoneyProperty(0), (StringConverter<Number>) converter); player1MoneyLabel.textProperty().bindBidirectional(viewModel.getPlayerMoneyProperty(1), (StringConverter<Number>) converter); player2MoneyLabel.textProperty().bindBidirectional(viewModel.getPlayerMoneyProperty(2), (StringConverter<Number>) converter); player3MoneyLabel.textProperty().bindBidirectional(viewModel.getPlayerMoneyProperty(3), (StringConverter<Number>) converter); //Bind player MonopolyProperties player0PropertyList.itemsProperty().bindBidirectional(viewModel.getPlayerPropertiesProperty(0)); player1PropertyList.itemsProperty().bindBidirectional(viewModel.getPlayerPropertiesProperty(1)); player2PropertyList.itemsProperty().bindBidirectional(viewModel.getPlayerPropertiesProperty(2)); player3PropertyList.itemsProperty().bindBidirectional(viewModel.getPlayerPropertiesProperty(3)); //Bind with the logger //logPropertyList.itemsProperty().bindBidirectional(model.getMonopolyLogger().getMonopolyLogObservable()); TODO //Bind with the logger //chatTextArea.textProperty().bindBidirectional(model.getMonopolyChat().getMonopolyChatObservable()); TODO bankMoneyLabel.textProperty().bindBidirectional(viewModel.getBankMoneyProperty(), (StringConverter<Number>) converter); bankHousesLabel.textProperty().bindBidirectional(viewModel.getBankHouseCountProperty(), (StringConverter<Number>) converter); bankHotelsLabel.textProperty().bindBidirectional(viewModel.getBankHotelCountProperty(), (StringConverter<Number>) converter); player0Tab.textProperty().bindBidirectional(viewModel.getPlayerNameProperty(0)); player1Tab.textProperty().bindBidirectional(viewModel.getPlayerNameProperty(1)); player2Tab.textProperty().bindBidirectional(viewModel.getPlayerNameProperty(2)); player3Tab.textProperty().bindBidirectional(viewModel.getPlayerNameProperty(3)); //region Ugly stepPlayer bindings field0_player0.imageProperty().bind(Bindings.when(viewModel.getPlayerPositionProperty(0).isEqualTo(0)).then(pieceBlueImage).otherwise(emptyImage)); field1_player0.imageProperty().bind(Bindings.when(viewModel.getPlayerPositionProperty(0).isEqualTo(1)).then(pieceBlueImage).otherwise(emptyImage)); field2_player0.imageProperty().bind(Bindings.when(viewModel.getPlayerPositionProperty(0).isEqualTo(2)).then(pieceBlueImage).otherwise(emptyImage)); field3_player0.imageProperty().bind(Bindings.when(viewModel.getPlayerPositionProperty(0).isEqualTo(3)).then(pieceBlueImage).otherwise(emptyImage)); field4_player0.imageProperty().bind(Bindings.when(viewModel.getPlayerPositionProperty(0).isEqualTo(4)).then(pieceBlueImage).otherwise(emptyImage)); field5_player0.imageProperty().bind(Bindings.when(viewModel.getPlayerPositionProperty(0).isEqualTo(5)).then(pieceBlueImage).otherwise(emptyImage)); field6_player0.imageProperty().bind(Bindings.when(viewModel.getPlayerPositionProperty(0).isEqualTo(6)).then(pieceBlueImage).otherwise(emptyImage)); field7_player0.imageProperty().bind(Bindings.when(viewModel.getPlayerPositionProperty(0).isEqualTo(7)).then(pieceBlueImage).otherwise(emptyImage)); field8_player0.imageProperty().bind(Bindings.when(viewModel.getPlayerPositionProperty(0).isEqualTo(8)).then(pieceBlueImage).otherwise(emptyImage)); field9_player0.imageProperty().bind(Bindings.when(viewModel.getPlayerPositionProperty(0).isEqualTo(9)).then(pieceBlueImage).otherwise(emptyImage)); field10_player0.imageProperty().bind(Bindings.when(viewModel.getPlayerPositionProperty(0).isEqualTo(10)).then(pieceBlueImage).otherwise(emptyImage)); field11_player0.imageProperty().bind(Bindings.when(viewModel.getPlayerPositionProperty(0).isEqualTo(11)).then(pieceBlueImage).otherwise(emptyImage)); field12_player0.imageProperty().bind(Bindings.when(viewModel.getPlayerPositionProperty(0).isEqualTo(12)).then(pieceBlueImage).otherwise(emptyImage)); field13_player0.imageProperty().bind(Bindings.when(viewModel.getPlayerPositionProperty(0).isEqualTo(13)).then(pieceBlueImage).otherwise(emptyImage)); field14_player0.imageProperty().bind(Bindings.when(viewModel.getPlayerPositionProperty(0).isEqualTo(14)).then(pieceBlueImage).otherwise(emptyImage)); field15_player0.imageProperty().bind(Bindings.when(viewModel.getPlayerPositionProperty(0).isEqualTo(15)).then(pieceBlueImage).otherwise(emptyImage)); field16_player0.imageProperty().bind(Bindings.when(viewModel.getPlayerPositionProperty(0).isEqualTo(16)).then(pieceBlueImage).otherwise(emptyImage)); field17_player0.imageProperty().bind(Bindings.when(viewModel.getPlayerPositionProperty(0).isEqualTo(17)).then(pieceBlueImage).otherwise(emptyImage)); field18_player0.imageProperty().bind(Bindings.when(viewModel.getPlayerPositionProperty(0).isEqualTo(18)).then(pieceBlueImage).otherwise(emptyImage)); field19_player0.imageProperty().bind(Bindings.when(viewModel.getPlayerPositionProperty(0).isEqualTo(19)).then(pieceBlueImage).otherwise(emptyImage)); field20_player0.imageProperty().bind(Bindings.when(viewModel.getPlayerPositionProperty(0).isEqualTo(20)).then(pieceBlueImage).otherwise(emptyImage)); field21_player0.imageProperty().bind(Bindings.when(viewModel.getPlayerPositionProperty(0).isEqualTo(21)).then(pieceBlueImage).otherwise(emptyImage)); field22_player0.imageProperty().bind(Bindings.when(viewModel.getPlayerPositionProperty(0).isEqualTo(22)).then(pieceBlueImage).otherwise(emptyImage)); field23_player0.imageProperty().bind(Bindings.when(viewModel.getPlayerPositionProperty(0).isEqualTo(23)).then(pieceBlueImage).otherwise(emptyImage)); field24_player0.imageProperty().bind(Bindings.when(viewModel.getPlayerPositionProperty(0).isEqualTo(24)).then(pieceBlueImage).otherwise(emptyImage)); field25_player0.imageProperty().bind(Bindings.when(viewModel.getPlayerPositionProperty(0).isEqualTo(25)).then(pieceBlueImage).otherwise(emptyImage)); field26_player0.imageProperty().bind(Bindings.when(viewModel.getPlayerPositionProperty(0).isEqualTo(26)).then(pieceBlueImage).otherwise(emptyImage)); field27_player0.imageProperty().bind(Bindings.when(viewModel.getPlayerPositionProperty(0).isEqualTo(27)).then(pieceBlueImage).otherwise(emptyImage)); field28_player0.imageProperty().bind(Bindings.when(viewModel.getPlayerPositionProperty(0).isEqualTo(28)).then(pieceBlueImage).otherwise(emptyImage)); field29_player0.imageProperty().bind(Bindings.when(viewModel.getPlayerPositionProperty(0).isEqualTo(29)).then(pieceBlueImage).otherwise(emptyImage)); field30_player0.imageProperty().bind(Bindings.when(viewModel.getPlayerPositionProperty(0).isEqualTo(30)).then(pieceBlueImage).otherwise(emptyImage)); field31_player0.imageProperty().bind(Bindings.when(viewModel.getPlayerPositionProperty(0).isEqualTo(31)).then(pieceBlueImage).otherwise(emptyImage)); field32_player0.imageProperty().bind(Bindings.when(viewModel.getPlayerPositionProperty(0).isEqualTo(32)).then(pieceBlueImage).otherwise(emptyImage)); field33_player0.imageProperty().bind(Bindings.when(viewModel.getPlayerPositionProperty(0).isEqualTo(33)).then(pieceBlueImage).otherwise(emptyImage)); field34_player0.imageProperty().bind(Bindings.when(viewModel.getPlayerPositionProperty(0).isEqualTo(34)).then(pieceBlueImage).otherwise(emptyImage)); field35_player0.imageProperty().bind(Bindings.when(viewModel.getPlayerPositionProperty(0).isEqualTo(35)).then(pieceBlueImage).otherwise(emptyImage)); field36_player0.imageProperty().bind(Bindings.when(viewModel.getPlayerPositionProperty(0).isEqualTo(36)).then(pieceBlueImage).otherwise(emptyImage)); field37_player0.imageProperty().bind(Bindings.when(viewModel.getPlayerPositionProperty(0).isEqualTo(37)).then(pieceBlueImage).otherwise(emptyImage)); field38_player0.imageProperty().bind(Bindings.when(viewModel.getPlayerPositionProperty(0).isEqualTo(38)).then(pieceBlueImage).otherwise(emptyImage)); field39_player0.imageProperty().bind(Bindings.when(viewModel.getPlayerPositionProperty(0).isEqualTo(39)).then(pieceBlueImage).otherwise(emptyImage)); field0_player1.imageProperty().bind(Bindings.when(viewModel.getPlayerPositionProperty(1).isEqualTo(0)).then(pieceGreenImage).otherwise(emptyImage)); field1_player1.imageProperty().bind(Bindings.when(viewModel.getPlayerPositionProperty(1).isEqualTo(1)).then(pieceGreenImage).otherwise(emptyImage)); field2_player1.imageProperty().bind(Bindings.when(viewModel.getPlayerPositionProperty(1).isEqualTo(2)).then(pieceGreenImage).otherwise(emptyImage)); field3_player1.imageProperty().bind(Bindings.when(viewModel.getPlayerPositionProperty(1).isEqualTo(3)).then(pieceGreenImage).otherwise(emptyImage)); field4_player1.imageProperty().bind(Bindings.when(viewModel.getPlayerPositionProperty(1).isEqualTo(4)).then(pieceGreenImage).otherwise(emptyImage)); field5_player1.imageProperty().bind(Bindings.when(viewModel.getPlayerPositionProperty(1).isEqualTo(5)).then(pieceGreenImage).otherwise(emptyImage)); field6_player1.imageProperty().bind(Bindings.when(viewModel.getPlayerPositionProperty(1).isEqualTo(6)).then(pieceGreenImage).otherwise(emptyImage)); field7_player1.imageProperty().bind(Bindings.when(viewModel.getPlayerPositionProperty(1).isEqualTo(7)).then(pieceGreenImage).otherwise(emptyImage)); field8_player1.imageProperty().bind(Bindings.when(viewModel.getPlayerPositionProperty(1).isEqualTo(8)).then(pieceGreenImage).otherwise(emptyImage)); field9_player1.imageProperty().bind(Bindings.when(viewModel.getPlayerPositionProperty(1).isEqualTo(9)).then(pieceGreenImage).otherwise(emptyImage)); field10_player1.imageProperty().bind(Bindings.when(viewModel.getPlayerPositionProperty(1).isEqualTo(10)).then(pieceGreenImage).otherwise(emptyImage)); field11_player1.imageProperty().bind(Bindings.when(viewModel.getPlayerPositionProperty(1).isEqualTo(11)).then(pieceGreenImage).otherwise(emptyImage)); field12_player1.imageProperty().bind(Bindings.when(viewModel.getPlayerPositionProperty(1).isEqualTo(12)).then(pieceGreenImage).otherwise(emptyImage)); field13_player1.imageProperty().bind(Bindings.when(viewModel.getPlayerPositionProperty(1).isEqualTo(13)).then(pieceGreenImage).otherwise(emptyImage)); field14_player1.imageProperty().bind(Bindings.when(viewModel.getPlayerPositionProperty(1).isEqualTo(14)).then(pieceGreenImage).otherwise(emptyImage)); field15_player1.imageProperty().bind(Bindings.when(viewModel.getPlayerPositionProperty(1).isEqualTo(15)).then(pieceGreenImage).otherwise(emptyImage)); field16_player1.imageProperty().bind(Bindings.when(viewModel.getPlayerPositionProperty(1).isEqualTo(16)).then(pieceGreenImage).otherwise(emptyImage)); field17_player1.imageProperty().bind(Bindings.when(viewModel.getPlayerPositionProperty(1).isEqualTo(17)).then(pieceGreenImage).otherwise(emptyImage)); field18_player1.imageProperty().bind(Bindings.when(viewModel.getPlayerPositionProperty(1).isEqualTo(18)).then(pieceGreenImage).otherwise(emptyImage)); field19_player1.imageProperty().bind(Bindings.when(viewModel.getPlayerPositionProperty(1).isEqualTo(19)).then(pieceGreenImage).otherwise(emptyImage)); field20_player1.imageProperty().bind(Bindings.when(viewModel.getPlayerPositionProperty(1).isEqualTo(20)).then(pieceGreenImage).otherwise(emptyImage)); field21_player1.imageProperty().bind(Bindings.when(viewModel.getPlayerPositionProperty(1).isEqualTo(21)).then(pieceGreenImage).otherwise(emptyImage)); field22_player1.imageProperty().bind(Bindings.when(viewModel.getPlayerPositionProperty(1).isEqualTo(22)).then(pieceGreenImage).otherwise(emptyImage)); field23_player1.imageProperty().bind(Bindings.when(viewModel.getPlayerPositionProperty(1).isEqualTo(23)).then(pieceGreenImage).otherwise(emptyImage)); field24_player1.imageProperty().bind(Bindings.when(viewModel.getPlayerPositionProperty(1).isEqualTo(24)).then(pieceGreenImage).otherwise(emptyImage)); field25_player1.imageProperty().bind(Bindings.when(viewModel.getPlayerPositionProperty(1).isEqualTo(25)).then(pieceGreenImage).otherwise(emptyImage)); field26_player1.imageProperty().bind(Bindings.when(viewModel.getPlayerPositionProperty(1).isEqualTo(26)).then(pieceGreenImage).otherwise(emptyImage)); field27_player1.imageProperty().bind(Bindings.when(viewModel.getPlayerPositionProperty(1).isEqualTo(27)).then(pieceGreenImage).otherwise(emptyImage)); field28_player1.imageProperty().bind(Bindings.when(viewModel.getPlayerPositionProperty(1).isEqualTo(28)).then(pieceGreenImage).otherwise(emptyImage)); field29_player1.imageProperty().bind(Bindings.when(viewModel.getPlayerPositionProperty(1).isEqualTo(29)).then(pieceGreenImage).otherwise(emptyImage)); field30_player1.imageProperty().bind(Bindings.when(viewModel.getPlayerPositionProperty(1).isEqualTo(30)).then(pieceGreenImage).otherwise(emptyImage)); field31_player1.imageProperty().bind(Bindings.when(viewModel.getPlayerPositionProperty(1).isEqualTo(31)).then(pieceGreenImage).otherwise(emptyImage)); field32_player1.imageProperty().bind(Bindings.when(viewModel.getPlayerPositionProperty(1).isEqualTo(32)).then(pieceGreenImage).otherwise(emptyImage)); field33_player1.imageProperty().bind(Bindings.when(viewModel.getPlayerPositionProperty(1).isEqualTo(33)).then(pieceGreenImage).otherwise(emptyImage)); field34_player1.imageProperty().bind(Bindings.when(viewModel.getPlayerPositionProperty(1).isEqualTo(34)).then(pieceGreenImage).otherwise(emptyImage)); field35_player1.imageProperty().bind(Bindings.when(viewModel.getPlayerPositionProperty(1).isEqualTo(35)).then(pieceGreenImage).otherwise(emptyImage)); field36_player1.imageProperty().bind(Bindings.when(viewModel.getPlayerPositionProperty(1).isEqualTo(36)).then(pieceGreenImage).otherwise(emptyImage)); field37_player1.imageProperty().bind(Bindings.when(viewModel.getPlayerPositionProperty(1).isEqualTo(37)).then(pieceGreenImage).otherwise(emptyImage)); field38_player1.imageProperty().bind(Bindings.when(viewModel.getPlayerPositionProperty(1).isEqualTo(38)).then(pieceGreenImage).otherwise(emptyImage)); field39_player1.imageProperty().bind(Bindings.when(viewModel.getPlayerPositionProperty(1).isEqualTo(39)).then(pieceGreenImage).otherwise(emptyImage)); field1_player2.imageProperty().bind(Bindings.when(viewModel.getPlayerPositionProperty(2).isEqualTo(1)).then(pieceRedImage).otherwise(emptyImage)); field2_player2.imageProperty().bind(Bindings.when(viewModel.getPlayerPositionProperty(2).isEqualTo(2)).then(pieceRedImage).otherwise(emptyImage)); field3_player2.imageProperty().bind(Bindings.when(viewModel.getPlayerPositionProperty(2).isEqualTo(3)).then(pieceRedImage).otherwise(emptyImage)); field0_player2.imageProperty().bind(Bindings.when(viewModel.getPlayerPositionProperty(2).isEqualTo(0)).then(pieceRedImage).otherwise(emptyImage)); field4_player2.imageProperty().bind(Bindings.when(viewModel.getPlayerPositionProperty(2).isEqualTo(4)).then(pieceRedImage).otherwise(emptyImage)); field5_player2.imageProperty().bind(Bindings.when(viewModel.getPlayerPositionProperty(2).isEqualTo(5)).then(pieceRedImage).otherwise(emptyImage)); field6_player2.imageProperty().bind(Bindings.when(viewModel.getPlayerPositionProperty(2).isEqualTo(6)).then(pieceRedImage).otherwise(emptyImage)); field7_player2.imageProperty().bind(Bindings.when(viewModel.getPlayerPositionProperty(2).isEqualTo(7)).then(pieceRedImage).otherwise(emptyImage)); field8_player2.imageProperty().bind(Bindings.when(viewModel.getPlayerPositionProperty(2).isEqualTo(8)).then(pieceRedImage).otherwise(emptyImage)); field9_player2.imageProperty().bind(Bindings.when(viewModel.getPlayerPositionProperty(2).isEqualTo(9)).then(pieceRedImage).otherwise(emptyImage)); field10_player2.imageProperty().bind(Bindings.when(viewModel.getPlayerPositionProperty(2).isEqualTo(10)).then(pieceRedImage).otherwise(emptyImage)); field11_player2.imageProperty().bind(Bindings.when(viewModel.getPlayerPositionProperty(2).isEqualTo(11)).then(pieceRedImage).otherwise(emptyImage)); field12_player2.imageProperty().bind(Bindings.when(viewModel.getPlayerPositionProperty(2).isEqualTo(12)).then(pieceRedImage).otherwise(emptyImage)); field13_player2.imageProperty().bind(Bindings.when(viewModel.getPlayerPositionProperty(2).isEqualTo(13)).then(pieceRedImage).otherwise(emptyImage)); field14_player2.imageProperty().bind(Bindings.when(viewModel.getPlayerPositionProperty(2).isEqualTo(14)).then(pieceRedImage).otherwise(emptyImage)); field15_player2.imageProperty().bind(Bindings.when(viewModel.getPlayerPositionProperty(2).isEqualTo(15)).then(pieceRedImage).otherwise(emptyImage)); field16_player2.imageProperty().bind(Bindings.when(viewModel.getPlayerPositionProperty(2).isEqualTo(16)).then(pieceRedImage).otherwise(emptyImage)); field17_player2.imageProperty().bind(Bindings.when(viewModel.getPlayerPositionProperty(2).isEqualTo(17)).then(pieceRedImage).otherwise(emptyImage)); field18_player2.imageProperty().bind(Bindings.when(viewModel.getPlayerPositionProperty(2).isEqualTo(18)).then(pieceRedImage).otherwise(emptyImage)); field19_player2.imageProperty().bind(Bindings.when(viewModel.getPlayerPositionProperty(2).isEqualTo(19)).then(pieceRedImage).otherwise(emptyImage)); field20_player2.imageProperty().bind(Bindings.when(viewModel.getPlayerPositionProperty(2).isEqualTo(20)).then(pieceRedImage).otherwise(emptyImage)); field21_player2.imageProperty().bind(Bindings.when(viewModel.getPlayerPositionProperty(2).isEqualTo(21)).then(pieceRedImage).otherwise(emptyImage)); field22_player2.imageProperty().bind(Bindings.when(viewModel.getPlayerPositionProperty(2).isEqualTo(22)).then(pieceRedImage).otherwise(emptyImage)); field23_player2.imageProperty().bind(Bindings.when(viewModel.getPlayerPositionProperty(2).isEqualTo(23)).then(pieceRedImage).otherwise(emptyImage)); field24_player2.imageProperty().bind(Bindings.when(viewModel.getPlayerPositionProperty(2).isEqualTo(24)).then(pieceRedImage).otherwise(emptyImage)); field25_player2.imageProperty().bind(Bindings.when(viewModel.getPlayerPositionProperty(2).isEqualTo(25)).then(pieceRedImage).otherwise(emptyImage)); field26_player2.imageProperty().bind(Bindings.when(viewModel.getPlayerPositionProperty(2).isEqualTo(26)).then(pieceRedImage).otherwise(emptyImage)); field27_player2.imageProperty().bind(Bindings.when(viewModel.getPlayerPositionProperty(2).isEqualTo(27)).then(pieceRedImage).otherwise(emptyImage)); field28_player2.imageProperty().bind(Bindings.when(viewModel.getPlayerPositionProperty(2).isEqualTo(28)).then(pieceRedImage).otherwise(emptyImage)); field29_player2.imageProperty().bind(Bindings.when(viewModel.getPlayerPositionProperty(2).isEqualTo(29)).then(pieceRedImage).otherwise(emptyImage)); field30_player2.imageProperty().bind(Bindings.when(viewModel.getPlayerPositionProperty(2).isEqualTo(30)).then(pieceRedImage).otherwise(emptyImage)); field31_player2.imageProperty().bind(Bindings.when(viewModel.getPlayerPositionProperty(2).isEqualTo(31)).then(pieceRedImage).otherwise(emptyImage)); field32_player2.imageProperty().bind(Bindings.when(viewModel.getPlayerPositionProperty(2).isEqualTo(32)).then(pieceRedImage).otherwise(emptyImage)); field33_player2.imageProperty().bind(Bindings.when(viewModel.getPlayerPositionProperty(2).isEqualTo(33)).then(pieceRedImage).otherwise(emptyImage)); field34_player2.imageProperty().bind(Bindings.when(viewModel.getPlayerPositionProperty(2).isEqualTo(34)).then(pieceRedImage).otherwise(emptyImage)); field35_player2.imageProperty().bind(Bindings.when(viewModel.getPlayerPositionProperty(2).isEqualTo(35)).then(pieceRedImage).otherwise(emptyImage)); field36_player2.imageProperty().bind(Bindings.when(viewModel.getPlayerPositionProperty(2).isEqualTo(36)).then(pieceRedImage).otherwise(emptyImage)); field37_player2.imageProperty().bind(Bindings.when(viewModel.getPlayerPositionProperty(2).isEqualTo(37)).then(pieceRedImage).otherwise(emptyImage)); field38_player2.imageProperty().bind(Bindings.when(viewModel.getPlayerPositionProperty(2).isEqualTo(38)).then(pieceRedImage).otherwise(emptyImage)); field39_player2.imageProperty().bind(Bindings.when(viewModel.getPlayerPositionProperty(2).isEqualTo(39)).then(pieceRedImage).otherwise(emptyImage)); field1_player3.imageProperty().bind(Bindings.when(viewModel.getPlayerPositionProperty(3).isEqualTo(1)).then(pieceYellowImage).otherwise(emptyImage)); field2_player3.imageProperty().bind(Bindings.when(viewModel.getPlayerPositionProperty(3).isEqualTo(2)).then(pieceYellowImage).otherwise(emptyImage)); field3_player3.imageProperty().bind(Bindings.when(viewModel.getPlayerPositionProperty(3).isEqualTo(3)).then(pieceYellowImage).otherwise(emptyImage)); field0_player3.imageProperty().bind(Bindings.when(viewModel.getPlayerPositionProperty(3).isEqualTo(0)).then(pieceYellowImage).otherwise(emptyImage)); field4_player3.imageProperty().bind(Bindings.when(viewModel.getPlayerPositionProperty(3).isEqualTo(4)).then(pieceYellowImage).otherwise(emptyImage)); field5_player3.imageProperty().bind(Bindings.when(viewModel.getPlayerPositionProperty(3).isEqualTo(5)).then(pieceYellowImage).otherwise(emptyImage)); field6_player3.imageProperty().bind(Bindings.when(viewModel.getPlayerPositionProperty(3).isEqualTo(6)).then(pieceYellowImage).otherwise(emptyImage)); field7_player3.imageProperty().bind(Bindings.when(viewModel.getPlayerPositionProperty(3).isEqualTo(7)).then(pieceYellowImage).otherwise(emptyImage)); field8_player3.imageProperty().bind(Bindings.when(viewModel.getPlayerPositionProperty(3).isEqualTo(8)).then(pieceYellowImage).otherwise(emptyImage)); field9_player3.imageProperty().bind(Bindings.when(viewModel.getPlayerPositionProperty(3).isEqualTo(9)).then(pieceYellowImage).otherwise(emptyImage)); field10_player3.imageProperty().bind(Bindings.when(viewModel.getPlayerPositionProperty(3).isEqualTo(10)).then(pieceYellowImage).otherwise(emptyImage)); field11_player3.imageProperty().bind(Bindings.when(viewModel.getPlayerPositionProperty(3).isEqualTo(11)).then(pieceYellowImage).otherwise(emptyImage)); field12_player3.imageProperty().bind(Bindings.when(viewModel.getPlayerPositionProperty(3).isEqualTo(12)).then(pieceYellowImage).otherwise(emptyImage)); field13_player3.imageProperty().bind(Bindings.when(viewModel.getPlayerPositionProperty(3).isEqualTo(13)).then(pieceYellowImage).otherwise(emptyImage)); field14_player3.imageProperty().bind(Bindings.when(viewModel.getPlayerPositionProperty(3).isEqualTo(14)).then(pieceYellowImage).otherwise(emptyImage)); field15_player3.imageProperty().bind(Bindings.when(viewModel.getPlayerPositionProperty(3).isEqualTo(15)).then(pieceYellowImage).otherwise(emptyImage)); field16_player3.imageProperty().bind(Bindings.when(viewModel.getPlayerPositionProperty(3).isEqualTo(16)).then(pieceYellowImage).otherwise(emptyImage)); field17_player3.imageProperty().bind(Bindings.when(viewModel.getPlayerPositionProperty(3).isEqualTo(17)).then(pieceYellowImage).otherwise(emptyImage)); field18_player3.imageProperty().bind(Bindings.when(viewModel.getPlayerPositionProperty(3).isEqualTo(18)).then(pieceYellowImage).otherwise(emptyImage)); field19_player3.imageProperty().bind(Bindings.when(viewModel.getPlayerPositionProperty(3).isEqualTo(19)).then(pieceYellowImage).otherwise(emptyImage)); field20_player3.imageProperty().bind(Bindings.when(viewModel.getPlayerPositionProperty(3).isEqualTo(20)).then(pieceYellowImage).otherwise(emptyImage)); field21_player3.imageProperty().bind(Bindings.when(viewModel.getPlayerPositionProperty(3).isEqualTo(21)).then(pieceYellowImage).otherwise(emptyImage)); field22_player3.imageProperty().bind(Bindings.when(viewModel.getPlayerPositionProperty(3).isEqualTo(22)).then(pieceYellowImage).otherwise(emptyImage)); field23_player3.imageProperty().bind(Bindings.when(viewModel.getPlayerPositionProperty(3).isEqualTo(23)).then(pieceYellowImage).otherwise(emptyImage)); field24_player3.imageProperty().bind(Bindings.when(viewModel.getPlayerPositionProperty(3).isEqualTo(24)).then(pieceYellowImage).otherwise(emptyImage)); field25_player3.imageProperty().bind(Bindings.when(viewModel.getPlayerPositionProperty(3).isEqualTo(25)).then(pieceYellowImage).otherwise(emptyImage)); field26_player3.imageProperty().bind(Bindings.when(viewModel.getPlayerPositionProperty(3).isEqualTo(26)).then(pieceYellowImage).otherwise(emptyImage)); field27_player3.imageProperty().bind(Bindings.when(viewModel.getPlayerPositionProperty(3).isEqualTo(27)).then(pieceYellowImage).otherwise(emptyImage)); field28_player3.imageProperty().bind(Bindings.when(viewModel.getPlayerPositionProperty(3).isEqualTo(28)).then(pieceYellowImage).otherwise(emptyImage)); field29_player3.imageProperty().bind(Bindings.when(viewModel.getPlayerPositionProperty(3).isEqualTo(29)).then(pieceYellowImage).otherwise(emptyImage)); field30_player3.imageProperty().bind(Bindings.when(viewModel.getPlayerPositionProperty(3).isEqualTo(30)).then(pieceYellowImage).otherwise(emptyImage)); field31_player3.imageProperty().bind(Bindings.when(viewModel.getPlayerPositionProperty(3).isEqualTo(31)).then(pieceYellowImage).otherwise(emptyImage)); field32_player3.imageProperty().bind(Bindings.when(viewModel.getPlayerPositionProperty(3).isEqualTo(32)).then(pieceYellowImage).otherwise(emptyImage)); field33_player3.imageProperty().bind(Bindings.when(viewModel.getPlayerPositionProperty(3).isEqualTo(33)).then(pieceYellowImage).otherwise(emptyImage)); field34_player3.imageProperty().bind(Bindings.when(viewModel.getPlayerPositionProperty(3).isEqualTo(34)).then(pieceYellowImage).otherwise(emptyImage)); field35_player3.imageProperty().bind(Bindings.when(viewModel.getPlayerPositionProperty(3).isEqualTo(35)).then(pieceYellowImage).otherwise(emptyImage)); field36_player3.imageProperty().bind(Bindings.when(viewModel.getPlayerPositionProperty(3).isEqualTo(36)).then(pieceYellowImage).otherwise(emptyImage)); field37_player3.imageProperty().bind(Bindings.when(viewModel.getPlayerPositionProperty(3).isEqualTo(37)).then(pieceYellowImage).otherwise(emptyImage)); field38_player3.imageProperty().bind(Bindings.when(viewModel.getPlayerPositionProperty(3).isEqualTo(38)).then(pieceYellowImage).otherwise(emptyImage)); field39_player3.imageProperty().bind(Bindings.when(viewModel.getPlayerPositionProperty(3).isEqualTo(39)).then(pieceYellowImage).otherwise(emptyImage)); jailField_player0.imageProperty().bind(Bindings.when(viewModel.getPlayerPositionProperty(0).isEqualTo(-1)).then(pieceBlueImage).otherwise(emptyImage)); jailField_player1.imageProperty().bind(Bindings.when(viewModel.getPlayerPositionProperty(1).isEqualTo(-1)).then(pieceGreenImage).otherwise(emptyImage)); jailField_player2.imageProperty().bind(Bindings.when(viewModel.getPlayerPositionProperty(2).isEqualTo(-1)).then(pieceRedImage).otherwise(emptyImage)); jailField_player3.imageProperty().bind(Bindings.when(viewModel.getPlayerPositionProperty(3).isEqualTo(-1)).then(pieceYellowImage).otherwise(emptyImage)); //endregion currentPlayerLabel.textProperty().bind(viewModel.getCurrentPlayerNameProperty()); //region Ugly rollDiceButton listeners viewModel.currentPlayerIndexProperty().addListener((obs, oldValue, newValue) -> { if (viewModel.getCurrentPlayer().getDiceRollsLeft() == 0) { rollDiceButton.disableProperty().set(true); }else{ rollDiceButton.disableProperty().set(false); } }); viewModel.playerDiceRollsLeftProperty(0).addListener((obs, oldValue, newValue) -> { if (viewModel.getCurrentPlayerIndex() == 0) { if (viewModel.getPlayer(0).getDiceRollsLeft() == 0) { rollDiceButton.disableProperty().set(true); }else{ rollDiceButton.disableProperty().set(false); } } }); viewModel.playerDiceRollsLeftProperty(1).addListener((obs, oldValue, newValue) -> { if (viewModel.getCurrentPlayerIndex() == 1) { if (viewModel.getPlayer(1).getDiceRollsLeft() == 0) { rollDiceButton.disableProperty().set(true); }else{ rollDiceButton.disableProperty().set(false); } } }); viewModel.playerDiceRollsLeftProperty(2).addListener((obs, oldValue, newValue) -> { if (viewModel.getCurrentPlayerIndex() == 2) { if (viewModel.getPlayer(2).getDiceRollsLeft() == 0) { rollDiceButton.disableProperty().set(true); }else{ rollDiceButton.disableProperty().set(false); } } }); viewModel.playerDiceRollsLeftProperty(3).addListener((obs, oldValue, newValue) -> { if (viewModel.getCurrentPlayerIndex() == 3) { if (viewModel.getPlayer(3).getDiceRollsLeft() == 0) { rollDiceButton.disableProperty().set(true); }else{ rollDiceButton.disableProperty().set(false); } } }); //endregion viewModel.getFirstDiceValueProperty().addListener((obs, oldValue, newValue) -> { if((Integer)newValue == 0){ firstDiceImage.setImage(emptyImage); }else{ firstDiceImage.setImage(diceImageList.get((Integer)newValue - 1)); } }); viewModel.getSecondDiceValueProperty().addListener((obs, oldValue, newValue) -> { if((Integer)newValue == 0){ secondDiceImage.setImage(emptyImage); }else{ secondDiceImage.setImage(diceImageList.get((Integer)newValue - 1)); } }); player0PropertyList.setOnMouseClicked(new EventHandler<MouseEvent>() { @Override public void handle(MouseEvent event) { Object selectedItem = player0PropertyList.getSelectionModel().getSelectedItem(); if(selectedItem == null) return; UpgradeableField prop = viewModel.getFieldByName(selectedItem.toString()); if(prop != null) updatePropertyDescription(prop); } }); player1PropertyList.setOnMouseClicked(new EventHandler<MouseEvent>() { @Override public void handle(MouseEvent event) { Object selectedItem = player1PropertyList.getSelectionModel().getSelectedItem(); if(selectedItem == null) return; UpgradeableField prop = viewModel.getFieldByName(selectedItem.toString()); if(prop != null) updatePropertyDescription(prop); } }); player2PropertyList.setOnMouseClicked(new EventHandler<MouseEvent>() { @Override public void handle(MouseEvent event) { Object selectedItem = player2PropertyList.getSelectionModel().getSelectedItem(); if(selectedItem == null) return; UpgradeableField prop = viewModel.getFieldByName(selectedItem.toString()); if(prop != null) updatePropertyDescription(prop); } }); player3PropertyList.setOnMouseClicked(new EventHandler<MouseEvent>() { @Override public void handle(MouseEvent event) { Object selectedItem = player3PropertyList.getSelectionModel().getSelectedItem(); if(selectedItem == null) return; UpgradeableField prop = viewModel.getFieldByName(selectedItem.toString()); if(prop != null) updatePropertyDescription(prop); } }); Map<Integer, Label> houseLabels = new HashMap<>(); houseLabels.put(1, purple1Label); houseLabels.put(3, purple2Label); houseLabels.put(6, teal1Label); houseLabels.put(8, teal2Label); houseLabels.put(9, teal3Label); houseLabels.put(11, pink1Label); houseLabels.put(13, pink2Label); houseLabels.put(14, pink3Label); houseLabels.put(16, brown1Label); houseLabels.put(18, brown2Label); houseLabels.put(19, brown3Label); houseLabels.put(21, crimson1Label); houseLabels.put(23, crimson2Label); houseLabels.put(24, crimson3Label); houseLabels.put(26, gold1Label); houseLabels.put(27, gold2Label); houseLabels.put(29, gold3Label); houseLabels.put(31, green1Label); houseLabels.put(32, green2Label); houseLabels.put(34, green3Label); houseLabels.put(37, blue1Label); houseLabels.put(39, blue2Label); for (Map.Entry<Integer, Label> e : houseLabels.entrySet()) { (viewModel.getLevelProperty(e.getKey())).addListener((obs, oldValue, newValue) -> { switch ((Integer) newValue) { case 0: e.getValue().setText(""); break; case 1: e.getValue().setText("H x 1"); break; case 2: e.getValue().setText("H x 2"); break; case 3: e.getValue().setText("H x 3"); break; case 4: e.getValue().setText("H x 4"); break; case 5: e.getValue().setText("Hotel"); break; } }); } } private void updatePropertyDescription(UpgradeableField field){ propertyNameLabel.setText(field.getName()); propertyPriceLabel.setText(Integer.toString(field.getPrice())); propertyHousesLabel.setText(Integer.toString(field.getHouseCount())); propertyHotelsLabel.setText(Integer.toString(field.getHotelCount())); propertyHouseCostLabel.setText(Integer.toString(field.getUpgradePrice())); propertyRentLabel.setText(Integer.toString(field.getRentLevel0())); propertyW1Label.setText(Integer.toString(field.getRentLevel1())); propertyW2Label.setText(Integer.toString(field.getRentLevel2())); propertyW3Label.setText(Integer.toString(field.getRentLevel3())); propertyW4Label.setText(Integer.toString(field.getRentLevel4())); propertyWHLabel.setText(Integer.toString(field.getRentLevel5())); } @FXML void newGameMenuItemClicked(ActionEvent event) { //TODO } @FXML void saveGameMenuItemClicked(ActionEvent event) { FileChooser fileChooser = new FileChooser(); fileChooser.setTitle("Save game"); File file = fileChooser.showSaveDialog((Stage) ((Node) rollDiceButton).getScene().getWindow()); if (file != null) { //viewModel.saveGame(file); } } @FXML void loadGameMenuItemClicked(ActionEvent event) { //TODO } @FXML void exitMenuItemClicked(ActionEvent event) { Alert alert = new Alert(Alert.AlertType.CONFIRMATION, "Save game before exit?", ButtonType.YES, ButtonType.NO); alert.setHeaderText(null); alert.showAndWait(); if (alert.getResult() == ButtonType.YES) { FileChooser fileChooser = new FileChooser(); fileChooser.setTitle("Save game"); File file = fileChooser.showSaveDialog((Stage) ((Node) rollDiceButton).getScene().getWindow()); if (file != null) { //TODO: Create save file } } Stage stage = (Stage) rollDiceButton.getScene().getWindow(); stage.close(); } @FXML void rulesMenuItemClicked(ActionEvent event) throws IOException { FXMLLoader loader = new FXMLLoader(); loader.setLocation(getClass().getResource("/Monopoly/View/RulesWindow.fxml")); Stage primaryStage = new Stage(); Parent root = loader.load(); primaryStage.setTitle("Rules"); primaryStage.setResizable(true); primaryStage.setWidth(620); primaryStage.setHeight(400); Scene scene = new Scene(root); primaryStage.setScene(scene); primaryStage.show(); } @FXML void aboutMenuItemClicked(ActionEvent event) { //TODO } @FXML void rollDiceButtonClicked(ActionEvent event) { MultipleDiceResult result = (MultipleDiceResult) viewModel.roll(); int tmpDiceRollsLeft = viewModel.getCurrentPlayer().getDiceRollsLeft(); viewModel.getCurrentPlayer().setDiceRollsLeft(0); int stepValue = result.getRollValue(); //Task for step animation Task<Void> task = new Task<Void>() { @Override public Void call() throws Exception { for (int i = 0; i < stepValue; i++) { updateMessage(String.valueOf(i)); Thread.sleep(250); } return null; } }; task.messageProperty().addListener((obs, oldMessage, newMessage) -> viewModel.moveCurrentPlayer(1)); task.stateProperty().addListener((observableValue, oldState, newState) -> { if (newState == Worker.State.SUCCEEDED) { if(viewModel.isCurrentPlayersFieldChanceCard()) { Alert alert = new Alert(Alert.AlertType.INFORMATION); alert.setTitle("Chance Card"); alert.setHeaderText(null); alert.setContentText(viewModel.drawChanceCard()); alert.showAndWait(); } else if (viewModel.isCurrentPlayersFieldCommunityChest()) { Alert alert = new Alert(Alert.AlertType.INFORMATION); alert.setTitle("Community Chest"); alert.setHeaderText(null); alert.setContentText(viewModel.drawCommunityCard()); alert.showAndWait(); } else if (viewModel.isCurrentPlayersFieldGoToJail()) { Alert alert = new Alert(Alert.AlertType.INFORMATION); alert.setTitle("Go To Jail"); alert.setHeaderText(null); alert.setContentText("Go To Jail!"); alert.showAndWait(); viewModel.lockPlayerToJail(viewModel.getCurrentPlayerIndex()); } else if (viewModel.isCurrentPlayersFieldIncomeTax()) { Alert alert = new Alert(Alert.AlertType.INFORMATION); alert.setTitle("Income Tax"); alert.setHeaderText(null); alert.setContentText("Pay 200$!"); alert.showAndWait(); viewModel.reducePlayerMoney(viewModel.getCurrentPlayerIndex(),200); } else if (viewModel.isCurrentPlayersFieldLuxuryTax()) { Alert alert = new Alert(Alert.AlertType.INFORMATION); alert.setTitle("Luxury Tax"); alert.setHeaderText(null); alert.setContentText("Pay 100$!"); alert.showAndWait(); viewModel.reducePlayerMoney(viewModel.getCurrentPlayerIndex(),100); } updateBuyPropertyButton(); endTurnButton.setDisable(false); viewModel.getCurrentPlayer().setDiceRollsLeft(tmpDiceRollsLeft); //enable dRB if player rolled double viewModel.payRental(); } }); buyPropertyButton.setDisable(true); endTurnButton.setDisable(true); new Thread(task).start(); } void updateBuyPropertyButton() { if (viewModel.isCurrentPlayersFieldBuyable()) { buyPropertyButton.setDisable(false); } else { buyPropertyButton.setDisable(true); } } @FXML void buyPropertyButtonClicked(ActionEvent event) { if (!(viewModel.getCurrentPlayersField() instanceof Property)) { throw new RuntimeException("Current players field is not a property"); } if (viewModel.getCurrentPlayer().hasEnoughMoneyFor(((Property) viewModel.getCurrentPlayersField()).getPrice())) { viewModel.buyProperty(); buyPropertyButton.setDisable(true); } else { Alert alert = new Alert(Alert.AlertType.INFORMATION, "You don't have enough money to buy this property!"); alert.setHeaderText(null); alert.show(); } } @FXML void sellPropertyButtonClicked(ActionEvent event) { boolean hasSelected = false; if (viewModel.getCurrentPlayerIndex() == 0) { hasSelected = player0PropertyList.getSelectionModel().getSelectedItem() != null; } else if (viewModel.getCurrentPlayerIndex() == 1) { hasSelected = player1PropertyList.getSelectionModel().getSelectedItem() != null; } else if (viewModel.getCurrentPlayerIndex() == 2) { hasSelected = player2PropertyList.getSelectionModel().getSelectedItem() != null; } else if (viewModel.getCurrentPlayerIndex() == 3) { hasSelected = player3PropertyList.getSelectionModel().getSelectedItem() != null; } if (!hasSelected) { showErrorDialog("There is no selected property for the active player!"); } else { String propertyName = null; if (viewModel.getCurrentPlayerIndex() == 0) { propertyName = player0PropertyList.getSelectionModel().getSelectedItem().toString(); } else if (viewModel.getCurrentPlayerIndex() == 1) { propertyName = player1PropertyList.getSelectionModel().getSelectedItem().toString(); } else if (viewModel.getCurrentPlayerIndex() == 2) { propertyName = player2PropertyList.getSelectionModel().getSelectedItem().toString(); } else if (viewModel.getCurrentPlayerIndex() == 3) { propertyName = player3PropertyList.getSelectionModel().getSelectedItem().toString(); } if (!viewModel.canSellProperty((Property) viewModel.getFieldByName(propertyName))) { showErrorDialog("Sell all buildings on properties in this color-group first!"); return; } TextInputDialog dialog = new TextInputDialog("100"); dialog.setTitle("Sell the property"); dialog.setHeaderText("How much money do you want for this property?"); dialog.setContentText("Enter the property price:"); Optional<String> result = dialog.showAndWait(); if (result.isPresent()) { int resMoney = Integer.parseInt(result.get()); java.util.List<String> playerNames = new ArrayList<>(); for (int i = 0; i < 4; i++) { if (i == viewModel.getCurrentPlayerIndex()) continue; playerNames.add(viewModel.getPlayer(i).getName()); } ChoiceDialog<String> cDialog = new ChoiceDialog<>(playerNames.get(0), playerNames); cDialog.setTitle("Sell " + propertyName); cDialog.setHeaderText("To which player do you want to sell the " + propertyName + " for " + resMoney + "$ ?"); cDialog.setContentText("Sell the property to:"); Optional<String> resultChoice = cDialog.showAndWait(); if (resultChoice.isPresent()) { String buyerName = resultChoice.get(); Player buyer = viewModel.getPlayerByName(buyerName); if (buyer.hasEnoughMoneyFor(resMoney)) { Alert alert = new Alert(Alert.AlertType.CONFIRMATION); alert.setTitle("Confirmation"); alert.setHeaderText("Check " + buyerName + " confirmation"); alert.setContentText(buyerName + " do you want to buy " + propertyName + " for " + resMoney + "$ ?"); Button okButton = (Button) alert.getDialogPane().lookupButton( ButtonType.OK ); okButton.setText("Yes"); Button cancelButton = (Button) alert.getDialogPane().lookupButton( ButtonType.CANCEL ); cancelButton.setText("No"); Optional<ButtonType> resultConf = alert.showAndWait(); if (resultConf.isPresent() && resultConf.get() == ButtonType.OK) { viewModel.buyProperty(buyer, (Property) viewModel.getFieldByName(propertyName), resMoney); } else { showErrorDialog(buyerName + " does not want to buy this property for " + resMoney + "$"); } } else { showErrorDialog(buyerName + " does not have enough money!"); } } } } } @FXML void buyHouseButtonClicked(ActionEvent event) { boolean hasSelected = false; if (viewModel.getCurrentPlayerIndex() == 0) { hasSelected = player0PropertyList.getSelectionModel().getSelectedItem() != null; } else if (viewModel.getCurrentPlayerIndex() == 1) { hasSelected = player1PropertyList.getSelectionModel().getSelectedItem() != null; } else if (viewModel.getCurrentPlayerIndex() == 2) { hasSelected = player2PropertyList.getSelectionModel().getSelectedItem() != null; } else if (viewModel.getCurrentPlayerIndex() == 3) { hasSelected = player3PropertyList.getSelectionModel().getSelectedItem() != null; } if (!hasSelected) { showErrorDialog("There is no selected property for the active player!"); } else { //Get active players selected property String propertyName = ""; if (viewModel.getCurrentPlayerIndex() == 0) { propertyName = player0PropertyList.getSelectionModel().getSelectedItem().toString(); } else if (viewModel.getCurrentPlayerIndex() == 1) { propertyName = player1PropertyList.getSelectionModel().getSelectedItem().toString(); } else if (viewModel.getCurrentPlayerIndex() == 2) { propertyName = player2PropertyList.getSelectionModel().getSelectedItem().toString(); } else if (viewModel.getCurrentPlayerIndex() == 3) { propertyName = player3PropertyList.getSelectionModel().getSelectedItem().toString(); } Property propToUpgrade = (Property) viewModel.getFieldByName(propertyName); if (viewModel.canUpgradeProperty((Property) viewModel.getFieldByName(propertyName))) { if (viewModel.currentPlayerHasEnoughMoney(propToUpgrade.getUpgradePrice())) { if (viewModel.canBankGiveBuilding(propToUpgrade)) { viewModel.buyBuilding(propToUpgrade); } else { showErrorDialog("No house/hotel left in the bank!"); } } else { showErrorDialog("You don't have enough money to upgrade that property!"); } } else { showErrorDialog("Buy every property from this color-group first\n\nAND\n\nBuy houses on properties with fewer houses first"); } } } @FXML void sellHouseButtonClicked(ActionEvent event) { boolean hasSelected = false; if (viewModel.getCurrentPlayerIndex() == 0) { hasSelected = player0PropertyList.getSelectionModel().getSelectedItem() != null; } else if (viewModel.getCurrentPlayerIndex() == 1) { hasSelected = player1PropertyList.getSelectionModel().getSelectedItem() != null; } else if (viewModel.getCurrentPlayerIndex() == 2) { hasSelected = player2PropertyList.getSelectionModel().getSelectedItem() != null; } else if (viewModel.getCurrentPlayerIndex() == 3) { hasSelected = player3PropertyList.getSelectionModel().getSelectedItem() != null; } if (!hasSelected) { showErrorDialog("There is no selected property for the active player!"); } else { //Get active players selected property String propertyName = null; if (viewModel.getCurrentPlayerIndex() == 0) { propertyName = player0PropertyList.getSelectionModel().getSelectedItem().toString(); } else if (viewModel.getCurrentPlayerIndex() == 1) { propertyName = player1PropertyList.getSelectionModel().getSelectedItem().toString(); } else if (viewModel.getCurrentPlayerIndex() == 2) { propertyName = player2PropertyList.getSelectionModel().getSelectedItem().toString(); } else if (viewModel.getCurrentPlayerIndex() == 3) { propertyName = player3PropertyList.getSelectionModel().getSelectedItem().toString(); } Property propToDowngrade = (Property) viewModel.getFieldByName(propertyName); if (viewModel.canDowngradeProperty(propToDowngrade)) { if (propToDowngrade.getLevel() == 5) { if (viewModel.bankHasEnoughMoney(propToDowngrade.getUpgradePrice() * 5 / 2)) { if (viewModel.getBankHouseCount() >= 4) { viewModel.sellBuilding(propToDowngrade); //model.getMonopolyLogger().writeToLogger(model.getName(model.getCurrentPlayerIndex()) + " sold a hotel"); } else { showErrorDialog("The bank has not enough house!"); } } else { showErrorDialog("The bank has not enough money to buy back your hotel!"); } } else { if (viewModel.bankHasEnoughMoney(propToDowngrade.getUpgradePrice() / 2)) { viewModel.sellBuilding(propToDowngrade); //model.getMonopolyLogger().writeToLogger(model.getName(model.getCurrentPlayerIndex()) + " sold a house"); } else { showErrorDialog("The bank has not enough money to buy back your house!"); } } } else { showErrorDialog("No buildings to sell\n\nOR\n\nSell other buildings in this color-group first!"); } } } @FXML void endTurnButtonClicked(ActionEvent event) { String currentPlayerName = viewModel.getCurrentPlayer().getName(); if (viewModel.endTurn() == null) { Alert alert = new Alert(Alert.AlertType.INFORMATION); alert.setTitle("End of Game"); alert.setHeaderText(null); alert.setContentText("Congratulation! "+ currentPlayerName + " won the game!" ); alert.showAndWait(); System.exit(0); } else { playersTabPane.getSelectionModel().select(viewModel.getCurrentPlayerIndex()); showJailOptions(); updateBuyPropertyButton(); } } void showJailOptions() { if (viewModel.getCurrentPlayer().isInJail()) { if (viewModel.getCurrentPlayer().getTurnsLeftInJail() > 0) { Alert alert = new Alert(Alert.AlertType.CONFIRMATION); alert.setTitle("Your options"); alert.setHeaderText("Choose one:"); alert.setContentText("Choose your option."); alert.initStyle(StageStyle.UNDECORATED); ButtonType buttonTypeOne = new ButtonType("Use a card"); ButtonType buttonTypeTwo = new ButtonType("Pay $50 fine"); ButtonType buttonTypeThree = new ButtonType("Roll the dice"); alert.getButtonTypes().setAll(buttonTypeOne, buttonTypeTwo, buttonTypeThree); alert.getDialogPane().lookupButton(buttonTypeOne).setDisable(viewModel.getCurrentPlayer().getFreeFormJailCardCount() > 0); alert.getDialogPane().lookupButton(buttonTypeOne).setDisable(viewModel.getCurrentPlayer().getMoney() >= 50); Optional<ButtonType> result = alert.showAndWait(); if (result.get() == buttonTypeOne) { //Use a card viewModel.freeCurrentPlayerFromJail(1); return; } else if (result.get() == buttonTypeTwo) { //Pay the fine viewModel.freeCurrentPlayerFromJail(2); return; } else if (result.get() == buttonTypeThree) { //Roll the dice viewModel.freeCurrentPlayerFromJail(3); } else { //Pay the fine viewModel.freeCurrentPlayerFromJail(2); } } else { viewModel.freeCurrentPlayerFromJail(2); } } } @FXML void sendButtonClicked(ActionEvent event) { /*model.getMonopolyChat().writeToChat("[" + model.getPlayer(model.getCurrentPlayerIndex()).getName() + "]: " + sendButtonTextField.getText()); sendButtonTextField.setText("");*/ } private void showErrorDialog(String errorMsg) { Alert alert = new Alert(Alert.AlertType.ERROR); alert.setTitle("Error!"); alert.setHeaderText("Error happened!"); alert.setContentText(errorMsg); alert.showAndWait(); } }
package com.cambot.league.models; import lombok.Data; @Data public class ErrorResponse { private int errorCode; private String message = "An error has occurred. Please try again later."; }
package LessonsJavaCore_8; import LessonsJavaCore_8.Local.Eng.ConsoleEng; import LessonsJavaCore_8.Local.Ua.ConsoleUa; import LessonsJavaCore_9.WrongInputConsoleParametersException; import java.util.Scanner; public class ConsoleMain { public static void main(String[] args){ Scanner scanner = new Scanner (System.in); ConsoleUa consoleUa = new ConsoleUa (); ConsoleEng consoleEng = new ConsoleEng (); String s = ""; System.out.println ( "\n" + "***** Виберіть Мову *****\n" + "***** Select Language *****\n" + "***** 1 - Українська *****\n" + "***** 2 - English *****" ); Integer number = scanner.nextInt (); if(number.equals(s)){ try { throw new WrongInputConsoleParametersException ("ведіть цифри"); }catch (WrongInputConsoleParametersException parameter){ parameter.getMessage ("ведіть цифри"); } } switch ( number ){ case 1:{ System.out.println("***** Українська *****"); consoleUa.Console (); break; } case 2:{ System.out.println ("***** English *****"); consoleEng.Console (); break; } case 11:{ break; } } } }
package com.tencent.mm.plugin.appbrand.page; import android.app.Activity; import android.content.Context; import com.tencent.mm.plugin.appbrand.q.a; class m$3 extends a { final /* synthetic */ m gmG; final /* synthetic */ Context val$context; m$3(m mVar, Context context) { this.gmG = mVar; this.val$context = context; } public final void onActivityPaused(Activity activity) { if (activity == this.val$context) { activity.getApplication().unregisterActivityLifecycleCallbacks(this); if (this.gmG.gmE != null && this.gmG.gmE.isShowing()) { this.gmG.gmE.bzW(); } } } }
package star.orf.app; import java.text.MessageFormat; import javax.swing.JLabel; import javax.swing.JPanel; public class Length extends JPanel implements EventListener { private static final long serialVersionUID = 1L; float length = 0; JLabel label; @Override public void addNotify() { super.addNotify(); label = new JLabel(); updateLabel(); add(label); Main.addListener(this); } public void event(Object evt) { if (evt instanceof Model) { length = ((Model) evt).forwardBases.length; updateLabel(); } } private void updateLabel() { label.setText(MessageFormat.format("<html><center>Sequence length is<br> {0} bp</html>", length)); } }
package com.lolRiver.river.models; import org.apache.commons.lang3.StringUtils; /** * @author mxia (mxia@lolRiver.com) * 10/2/13 */ public class Role { public enum Name { NONE, // for ARAM TOP, MID, JUNG, SUPP, ADC } private Name name; public Role(Name name) { this.name = name; } public static Role fromString(String roleName) { if (StringUtils.isBlank(roleName)) { return null; } return new Role(Role.Name.valueOf(roleName)); } public Role partnerRole() { if (name == Name.SUPP) { return new Role(Name.ADC); } else if (name == Name.ADC) { return new Role(Name.SUPP); } return null; } public Name getName() { return name; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof Role)) { return false; } Role role = (Role)o; if (name != role.name) { return false; } return true; } @Override public int hashCode() { return name != null ? name.hashCode() : 0; } @Override public String toString() { return "Role{" + "name=" + name + '}'; } }
package com.ibanity.apis.client.helpers; import org.apache.commons.io.IOUtils; import java.io.IOException; import java.nio.charset.Charset; import static java.util.Objects.requireNonNull; public class IbanityTestHelper { private static final Charset UTF8_ENCODING = Charset.forName("UTF-8"); public static String loadFile(String filePath) throws IOException { return IOUtils.toString( requireNonNull(IbanityTestHelper.class.getClassLoader().getResourceAsStream(filePath)), UTF8_ENCODING); } }
package com.cts.projectManagement.repository; import java.util.List; import org.springframework.data.repository.CrudRepository; import org.springframework.stereotype.Repository; import com.cts.projectManagement.entity.User; @Repository public interface UserRepository extends CrudRepository<User,Long> { List<User> findAll(); User findByUserId(Long id); }
package com.yinghai.a24divine_user.callback; /** * @author Created by:fanson * Created Time: 2017/10/27 9:53 * Describe:监听Adapter里的点击事件 */ public interface OnAdapterListener { /** * 点击Adapter的某项 * @param object 序号/Model */ void clickItem(Object... object); }
package com.canfield010.mygame.item; import com.canfield010.mygame.mapsquare.MapSquare; import java.awt.*; public abstract class Item { public byte count; public final byte maximumCount; public String name; public String description = ""; public Item(String name, byte maxCount) { this.name = name; this.maximumCount = maxCount; } public abstract void use(MapSquare square); public abstract boolean isUseful(MapSquare square); public abstract Image getImage(); }
package pl.sda.spring.decouplinginterface; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.context.annotation.Primary; import org.springframework.stereotype.Component; @Component @Primary @Qualifier("account") public class Account implements Transferable{ private String type; public String transferMoney(){ return "transferred from account"; } }
package com.smclaughlin.tps.entities; import javax.persistence.Column; import javax.persistence.Entity; import java.util.Objects; /** * Created by sineadmclaughlin on 24/11/2016. */ @Entity(name = "Account_Details") public class AccountDetails extends AbstractEntity{ private String accountName; private String accountWebsite; private String username; private String passwordSalt; private String passwordHash; public AccountDetails() { this.accountName = ""; this.accountWebsite = ""; this.username = ""; this.passwordSalt = ""; this.passwordHash = ""; } public String getAccountName() { return accountName; } public void setAccountName(String accountName) { this.accountName = accountName; } public String getAccountWebsite() { return accountWebsite; } public void setAccountWebsite(String accountWebsite) { this.accountWebsite = accountWebsite; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPasswordSalt() { return passwordSalt; } public void setPasswordSalt(String passwordSalt) { this.passwordSalt = passwordSalt; } public String getPasswordHash() { return passwordHash; } public void setPasswordHash(String passwordHash) { this.passwordHash = passwordHash; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null ||!(o instanceof AccountDetails)) return false; AccountDetails that = (AccountDetails) o; return Objects.equals(id, that.id) && Objects.equals(accountName, that.accountName) && Objects.equals(accountWebsite, that.accountWebsite) && Objects.equals(username, that.username) && Objects.equals(passwordSalt, that.passwordSalt) && Objects.equals(passwordHash, that.passwordHash) && Objects.equals(uuid, that.uuid); } @Override public int hashCode() { return Objects.hash(id, accountName, accountWebsite, username, passwordSalt, passwordHash, uuid); } }
package pl.jrkn.legacyofthevoidapi.model.character; public class StatPoints { private int currentHitPoints; private int maxHitPoints; private int defence; private int resistance; private int damage; private int damageMin; private int damageMax; private int dodgeChance; private int criticalStrikeChance; private boolean dodge; private boolean criticalStrike; private Character character; public StatPoints(Character character) { this.character = character; } public int getCurrentHitPoints() { return currentHitPoints; } public int getMaxHitPoints() { return maxHitPoints = character.getAttributes().getStamina() * 5 + character.getCharacterDetails().getLevel() * 16; } public int getDefence() { return character.getAttributes().getStamina() / 2; } public int getResistance(int intelligence) { return character.getAttributes().getIntelligence() / 2; } public int getDamageFromAttributes() { CharacterClass characterClass = character.getCharacterClass(); Attributes attributes = character.getAttributes(); damage = (int) ( attributes.getStrength() * characterClass.getStrengthMultiplier() + attributes.getDexterity() * characterClass.getDexterityMultiplier() + attributes.getIntelligence() * characterClass.getIntelligenceMultiplier() + attributes.getLuck() * characterClass.getLuckMultiplier()); return damage; } public int getDamageMin() { return damageMin; } public int getDamageMax() { return damageMax; } public int getDodgeChance() { return PercentageChanceOfSuccess.getChanceOfSuccess(character.getAttributes().getDexterity()); } public int getCriticalStrikeChance() { return PercentageChanceOfSuccess.getChanceOfSuccess(character.getAttributes().getLuck()); } public boolean isDodge(int dexterity) { return PercentageChanceOfSuccess.chanceOfSuccess(dexterity); } public boolean isCriticalStrike(int luck) { return PercentageChanceOfSuccess.chanceOfSuccess(luck); } }
package views; import java.awt.GridLayout; import java.awt.event.ActionListener; import java.util.ArrayList; import javax.swing.JPanel; public class PanelContainer extends JPanel{ private PanelLeft panelLeft; private PanelRight panelRight; private PanelResult panelResult; public PanelContainer(ArrayList<String> departaments, ActionListener controller) { setLayout(new GridLayout(0, 3)); panelLeft = new PanelLeft(controller); add(panelLeft); panelResult = new PanelResult(); add(panelResult); panelRight = new PanelRight(departaments,controller); add(panelRight); } public int getVotesNumber() { return panelRight.getVotesNumber(); } public String getDepartament() { return panelRight.getDepartament(); } public void registorVotes(String votes) { panelResult.registorVotes(votes); } public void cleanSpinn() { panelRight.cleanSpinn(); } public void goalSucessfull() { panelResult.goalSucessFull(); } public void sayFail() { panelResult.sayFail(); } }
/* * Copyright The OpenTelemetry Authors * SPDX-License-Identifier: Apache-2.0 */ package io.opentelemetry.baggage.spi; import io.opentelemetry.baggage.BaggageManager; import javax.annotation.concurrent.ThreadSafe; /** * BaggageManagerFactory is a service provider for {@link BaggageManager}. Fully qualified class * name of the implementation should be registered in {@code * META-INF/services/io.opentelemetry.baggage.spi.BaggageManagerFactory}. <br> * <br> * A specific implementation can be selected by a system property {@code * io.opentelemetry.baggage.spi.BaggageManagerFactory} with value of fully qualified class name. * * @see io.opentelemetry.OpenTelemetry */ @ThreadSafe public interface BaggageManagerFactory { /** * Creates a new {@code BaggageManager} instance. * * @return a {@code BaggageManager} instance. */ BaggageManager create(); }
package com.tencent.mm.ui; import com.tencent.mm.sdk.platformtools.ad; public interface e$b { public static final String tht = ad.getPackageName(); }
package com.pedidovenda.controller; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import javax.faces.bean.ViewScoped; import javax.inject.Inject; import javax.inject.Named; import com.pedidovenda.model.Grupo; import com.pedidovenda.model.Usuario; import com.pedidovenda.repository.GruposRepository; import com.pedidovenda.service.CadastroUsuarioService; import com.pedidovenda.util.jsf.FacesUtil; @ViewScoped @Named public class CadastroUsuarioBean implements Serializable { private static final long serialVersionUID = 1L; @Inject private CadastroUsuarioService usuarioService; @Inject private GruposRepository gruposRepository; private List<Grupo> grupos; private Usuario usuario; private List<Grupo> gruposSelecionados = new ArrayList<>(); public CadastroUsuarioBean() { this.usuario = new Usuario(); this.grupos = new ArrayList<>(); } public void inicializar() { grupos = gruposRepository.findAll(); } public void salvar() { try { usuarioService.salvar(this.usuario); FacesUtil.addInfoMessage("Usuário Salvo com Sucesso."); } catch (Exception e) { FacesUtil.addErrorMessage("Erro ao Cadastrar o Usuário. " + e.getMessage()); } } public List<Grupo> getGrupos() { return grupos; } public void setGrupos(List<Grupo> grupos) { this.grupos = grupos; } public Usuario getUsuario() { return this.usuario; } public void setUsuario(Usuario usuario) { this.usuario = usuario; } public boolean isEditando() { return this.usuario.getId() != null; } public List<Grupo> getGruposSelecionados() { return this.gruposSelecionados; } public void setGruposSelecionados(List<Grupo> gruposSelecionados) { this.gruposSelecionados = gruposSelecionados; } }
package edu.buet.cse.spring.ch02; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import edu.buet.cse.spring.ch02.spel.SystemProperties; public class App17 { public static void main(String... args) { ApplicationContext appContext = new ClassPathXmlApplicationContext("/edu/buet/cse/spring/ch02/spring-beans.xml"); SystemProperties sysProps = (SystemProperties) appContext.getBean("sysProps"); System.out.printf("java.home = %s%n", sysProps.getJavaHome()); System.out.printf("line.separator = %s%n", sysProps.getLineSeparator()); System.out.printf("java.vendor = %s%n", sysProps.getJavaVendor()); } }
package dao; import com.zhao.RunBoot; import com.zhao.entity.City; import com.zhao.repository.CityRepository; import org.apache.shardingsphere.api.hint.HintManager; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import javax.annotation.Resource; import java.util.List; @RunWith(SpringRunner.class) @SpringBootTest(classes = RunBoot.class) public class TestHint { @Resource CityRepository cityRepository; @Test public void testHint() { HintManager hintManager = HintManager.getInstance(); hintManager.setDatabaseShardingValue(0L); List<City> list = cityRepository.findAll(); System.out.println("主库表大小" + list.size()); hintManager.setDatabaseShardingValue(1L); List<City> list1 = cityRepository.findAll(); System.out.println("从库表大小" + list1.size()); } }
package July26; import java.util.Random; import static java.lang.Math.*; public class Sample1 { public static void main(String[] args) { System.out.println("just trying math methods"); System.out.println((abs(-2.3))); System.out.println((max(-2.3,3))); System.out.println(acos(0)); Random rand=new Random(); int j=rand.nextInt(11); System.out.println(j); } }
package com.packagename.myapp.Views; import com.packagename.myapp.Controllers.PersonasController; import com.packagename.myapp.Models.Personas; import com.packagename.myapp.Views.Windows.Delete_User; import com.packagename.myapp.Views.Windows.Editar_User; import com.vaadin.flow.component.button.Button; import com.vaadin.flow.component.button.ButtonVariant; import com.vaadin.flow.component.dialog.Dialog; import com.vaadin.flow.component.html.H3; import com.vaadin.flow.component.html.Image; import com.vaadin.flow.component.icon.Icon; import com.vaadin.flow.component.icon.VaadinIcon; import com.vaadin.flow.component.orderedlayout.HorizontalLayout; import com.vaadin.flow.component.orderedlayout.VerticalLayout; import com.vaadin.flow.component.textfield.TextField; import com.vaadin.flow.server.StreamResource; import java.io.ByteArrayInputStream; public class Opciones extends HorizontalLayout { public Opciones(Personas personas) { setWidthFull(); Image image = new Image(); if(personas.getImagen()==null) if(personas.getSexo().equals("Masculino")) image.setSrc("/img/user.jpg"); else image.setSrc("/img/user2.jpg"); else { StreamResource resource = new StreamResource("Image", () -> {return new ByteArrayInputStream(personas.getImagen());}); image.setSrc(resource); } image.addClassName("opciones-image"); VerticalLayout datos = new VerticalLayout(); datos.setPadding(false); datos.setSpacing(false); datos.setWidthFull(); H3 title = new H3("DATOS PERSONALES"); HorizontalLayout bloques = new HorizontalLayout(); bloques.setSizeFull(); VerticalLayout bloque1 = new VerticalLayout(); bloque1.setPadding(false); bloque1.setSpacing(false); bloque1.setWidthFull(); TextField cedula = new TextField(); cedula.setValue("Cédula: "+ personas.getCedula()); cedula.setPrefixComponent(new Icon(VaadinIcon.USER_CARD)); cedula.setReadOnly(true); TextField name = new TextField(); name.setValue("Nombre: "+personas.getNombre() + " "+personas.getApellido()); name.setPrefixComponent(new Icon (VaadinIcon.USER)); name.setReadOnly(true); TextField fecha_nacimiento = new TextField(); fecha_nacimiento.setValue("Fecha de Nacimiento: "+personas.getFecha_nacimiento()); fecha_nacimiento.setPrefixComponent(new Icon(VaadinIcon.CALENDAR_USER)); fecha_nacimiento.setReadOnly(true); TextField direccion = new TextField(); direccion.setValue("Dirección: "+personas.getDireccion()); direccion.setPrefixComponent(new Icon(VaadinIcon.HOME)); direccion.setReadOnly(true); bloque1.add(title, cedula, name, fecha_nacimiento, direccion); bloque1.setAlignItems(Alignment.STRETCH); VerticalLayout bloque2 = new VerticalLayout(); bloque2.setPadding(false); bloque2.setSpacing(false); bloque2.setWidthFull(); TextField telefono = new TextField(); telefono.setValue("Teléfono: "+ personas.getTelefono()); telefono.setPrefixComponent(new Icon(VaadinIcon.PHONE)); telefono.setReadOnly(true); TextField correo = new TextField(); correo.setValue("Correo: "+personas.getCorreo()); correo.setPrefixComponent(new Icon (VaadinIcon.AT)); correo.setReadOnly(true); TextField sexo = new TextField(); sexo.setValue("Sexo: "+personas.getSexo()); if(personas.getSexo().equals("Femenino")) sexo.setPrefixComponent(new Icon(VaadinIcon.FEMALE)); else sexo.setPrefixComponent(new Icon(VaadinIcon.MALE)); sexo.setReadOnly(true); bloque2.add(telefono, correo, sexo); bloque2.setAlignItems(Alignment.STRETCH); bloques.add(bloque1, bloque2); datos.add(title, bloques); datos.setAlignItems(Alignment.CENTER); VerticalLayout botones = new VerticalLayout(); botones.setPadding(false); botones.setWidth("18%"); Button modificar = new Button("Modificar"); modificar.setIcon(new Icon(VaadinIcon.EDIT)); modificar.addThemeVariants(ButtonVariant.LUMO_PRIMARY); modificar.addClickListener(e->{ Dialog dialog = new Dialog(); dialog.add(new Editar_User(personas)); dialog.open(); }); Button eliminar = new Button("Eliminar"); eliminar.setIcon(new Icon(VaadinIcon.TRASH)); eliminar.addThemeVariants(ButtonVariant.LUMO_ERROR); eliminar.addClickListener(e-> { Delete_User delete = new Delete_User(personas); delete.open(); }); botones.add(image, modificar, eliminar); botones.setAlignItems(Alignment.STRETCH); botones.setAlignSelf(Alignment.CENTER, image); botones.setJustifyContentMode(JustifyContentMode.END); add(datos, botones); setFlexGrow(0,botones); setFlexGrow(50, datos); } }
package jumpingalien.model; import jumpingalien.model.Position; import jumpingalien.part3.programs.Program; import jumpingalien.util.Sprite; import jumpingalien.util.Util; import be.kuleuven.cs.som.annotate.Basic; import be.kuleuven.cs.som.annotate.Immutable; import be.kuleuven.cs.som.annotate.Raw; /** * Class representing each living creature. * Link to repository: https://github.com/ProjectOOPvJDenPJB/JumpingAlien * * @author Joren Dhont (Ingenieurswetenschappen: Computerwetenschappen - Elektrotechniek) * & Pieterjan Beerden (Ingenieurswetenschappen: Elektrotechniek - Computerwetenschappen) * @version 0.1 */ public abstract class LivingCreatures extends GameObject { /** * Initialize this new living creature with given position, horizontal velocity, vertical velocity, * horizontal acceleration, vertical acceleration, initial horizontal velocity, * maximum horizontal velocity, world, sprites and hitpoints. * * @param XPosition * The position on the X-axis of the leftmost pixel for this new living creature. * @param YPosition * The position on the Y-axis of the bottom pixel for this new living creature. * @param horizontalVelocity * The horizontal velocity for this new living creature. * @param verticalVelocity * The vertical velocity for this new living creature. * @param horizontalAcceleration * The horizontal acceleartion for this new living creature. * @param verticalAcceleration * The vertical acceleration for this new living creature. * @param initialHorizontalVelocity * The initial horizontal velocity for this new living creature. * @param maximumHorizontalVelocity * The maximum horizontal velocity for this new living creature. * @param world * The world for this new living creature. * @param sprites * The array of sprites for this new living creature. * @param hitpoints * The hitpoints for this new living creature. * @pre The given spirteArray must be a valid spriteArray. * | isValidSpriteArray(sprites,this) * @pre The maximum horizontal velocity must be a valid one for this living creature. * | isValidMaximumHorizontalVelocity(maximumHorizontalVelocity, initialHorizontalVelocity) * @pre The initial horizontal velocity must be a valid one for this living creature. * | isValidInitialVelocity(initialHorizontalVelocity, maximumHorizontalVelocity) * @post The initial horizontal velocity of this living creature is set to the given * initial horizontal velocity. * | new.getInitialHorizontalVelocity() == initialHorizontalVelocity * @post The new sprite array for this living creature is set to the given sprite array. * | new.getSpriteArray() == sprites * @effect The new world for this world is set to the given world. * | this.setWorld(world) * @effect The new maximum horizontal velocity for this living creature * is set to the given maximum horizontal velocity. * | this.setMaximumHorizontalVelocity(maximumHorizontalVelocity) * @effect The horizontal velocity for this living creature is set to * the given horizontal velocity * | this.setHorizontalVelocity(horizontalVelocity); * @effect The new vertical velocity for this living creature is set to * the given vertical velocity * | this.setVerticalVelocity(verticalVelocity) * @effect The new hitpoints for this living creature are set to the given hitpoints * | this.setHP(hitpoints) * @effect The new horizontal acceleration for this living creature is set to * the given horizontal acceleration. * | this.setHorizontalAcceleration(horizontalAcceleration) * @effect The new vertical acceleration for this living creature is set to * the given vertical acceleration. * | this.setVerticalAcceleration(verticalAcceleration) * @effect The new position for this living creature is set to the given position. * | this.setPosition(XPosition, YPosition) */ protected LivingCreatures(int XPosition, int YPosition,double horizontalVelocity, double verticalVelocity, double horizontalAcceleration,double verticalAcceleration, double initialHorizontalVelocity, double maximumHorizontalVelocity, World world, Sprite[] sprites,int hitpoints){ this.setWorld(world); assert LivingCreatures.isValidSpriteArray(sprites,this); assert isValidMaximumHorizontalVelocity(maximumHorizontalVelocity, initialHorizontalVelocity); assert isValidInitialVelocity(initialHorizontalVelocity, maximumHorizontalVelocity); this.initialHorizontalVelocity = initialHorizontalVelocity; this.setMaximumHorizontalVelocity(maximumHorizontalVelocity); this.setHorizontalVelocity(horizontalVelocity); this.setVerticalVelocity(verticalVelocity); this.setHP(hitpoints); this.setHorizontalAcceleration(horizontalAcceleration); this.setVerticalAcceleration(verticalAcceleration); this.spriteArray = sprites; this.setPosition(XPosition, YPosition); } /** * Initialize this new living creature with given position, horizontal velocity, vertical velocity, * horizontal acceleration, maximum horizontal velocity, world, sprites and hitpoints. * * @param XPosition * The position on the X-axis of the leftmost pixel for this new living creature. * @param YPosition * The position on the Y-axis of the bottom pixel for this new living creature. * @param horizontalVelocity * The horizontal velocity for this new living creature. * @param verticalVelocity * The vertical velocity for this new living creature. * @param horizontalAcceleration * The horizontal acceleartion for this new living creature. * @param maximumHorizontalVelocity * The maximum horizontal velocity for this new living creature. * @param world * The world for this new living creature. * @param sprites * The array of sprites for this new living creature. * @param hitpoints * The hitpoints for this new living creature. * @effect The new LivingCreature is initialized with given position, horizontal velocity, * vertical velocity, horizontal acceleration, maximum horizontal velocity, * world, sprite array and hitpoints. The vertical acceleration and initial * horizontal velocity is set to 0. * | this(XPosition,YPosition,horizontalVelocity,verticalVelocity, horizontalAcceleration, * | 0, 0, maximumHorizontalVelocity, world, sprites, hitpoints) */ protected LivingCreatures(int XPosition, int YPosition, double horizontalVelocity, double verticalVelocity, double horizontalAcceleration, double maximumHorizontalVelocity, World world, Sprite[] sprites, int hitpoints){ this(XPosition,YPosition,horizontalVelocity,verticalVelocity, horizontalAcceleration, 0, 0, maximumHorizontalVelocity, world, sprites, hitpoints); } /** * Initialize this new living creature with given position, horizontal velocity, vertical velocity, * maximum horizontal velocity, world, sprites and hitpoints. * * @param XPosition * The position on the X-axis of the leftmost pixel for this new living creature. * @param YPosition * The position on the Y-axis of the bottom pixel for this new living creature. * @param horizontalVelocity * The horizontal velocity for this new living creature. * @param verticalVelocity * The vertical velocity for this new living creature. * @param maximumHorizontalVelocity * The maximum horizontal velocity for this new living creature. * @param world * The world for this new living creature. * @param sprites * The array of sprites for this new living creature. * @param hitpoints * The hitpoints for this new living creature. * @effect The new LivingCreature is initialized with given position, horizontal velocity, * vertical velocity, maximum horizontal velocity, * world, sprite array and hitpoints. The horizontal acceleration is set to 0. * | this(XPosition,YPosition,horizontalVelocity,verticalVelocity, 0, maximumHorizontalVelocity, * | world, sprites, hitpoints) */ protected LivingCreatures(int XPosition, int YPosition, double horizontalVelocity, double verticalVelocity, double maximumHorizontalVelocity, World world, Sprite[] sprites, int hitpoints){ this(XPosition,YPosition,horizontalVelocity,verticalVelocity, 0, maximumHorizontalVelocity, world, sprites, hitpoints); } /** * Initialize this new living creature with given position, world, sprites and hitpoints. * * @param XPosition * The position on the X-axis of the leftmost pixel for this new living creature. * @param YPosition * The position on the Y-axis of the bottom pixel for this new living creature. * @param world * The world for this new living creature. * @param sprites * The array of sprites for this new living creature. * @param hitpoints * The hitpoints for this new living creature. * @effect The new LivingCreature is initialized with given position, world, * sprite array and hitpoints. The horizontal velocity and vertical velocity * are set to 0. The maximum horizontal velocity is set to 3. * | this(XPosition,YPosition,0,0, 3,world, sprites, hitpoints) */ protected LivingCreatures(int XPosition, int YPosition,World world, Sprite[] sprites, int hitpoints){ this(XPosition,YPosition,0,0, 3,world, sprites, hitpoints); } /** * Initialize this new living creature with given position, sprites and hitpoints. * * @param XPosition * The position on the X-axis of the leftmost pixel for this new living creature. * @param YPosition * The position on the Y-axis of the bottom pixel for this new living creature. * @param sprites * The array of sprites for this new living creature. * @param hitpoints * The hitpoints for this new living creature. * @effect The new LivingCreature is initialized with given position, * sprite array and hitpoints. The world is set to null. * | this(XPosition,YPosition, null, sprites, hitpoints) */ protected LivingCreatures(int XPosition, int Yposition,Sprite[] sprites, int hitpoints) { this(XPosition,Yposition, null,sprites, hitpoints); } /** * Initialize this new living creature with given sprites and hitpoints. * * @param sprites * The array of sprites for this new living creature. * @param hitpoints * The hitpoints for this new living creature. * @effect The new LivingCreature is initialized with given sprite array * and hitpionts. The position is set to (0,0) * | this(0,0,sprites, hitpoints) */ protected LivingCreatures(Sprite[] sprites, int hitpoints) { this(0,0,sprites, hitpoints); } /** * Return the X position of this living creature. * The position is the actual position of the left X pixel of * the living creature character in the gameworld. */ public double getXPosition() { return getPosition().getXPosition(); } /** * Return the Y position of this living creature. * The position is the actual position of the bottom Y pixel of * the living creature character in the gameworld. */ public double getYPosition () { return getPosition().getYPosition(); } /** * Return the position of this living creature. * The position is represented as an object of the Position value class. */ @Basic public Position getPosition() { return position; } /** * Variable registering the position of this living creature as an object * of the Position value class. */ protected Position position = new Position(); /** * Set the X position of this living creature to the given X position. * @param xPosition * The new position on the X-axis of the leftmost pixel for this living creature. * @post If the given position was a valid position in regards to the world this creature is in, * the new position is set to the given position. * | new.getPosition().getPosition() == [positionLeftX, positionBottomY] * @post If the given position is not a valid position, the creature is set to be out of bounds and * is terminated. * | new.getOutOfBounds == true && (new.isDead() || new.isDying()) */ @Basic @Raw public void setPosition(double positionLeftX, double positionBottomY) { try { this.position = new Position(positionLeftX,positionBottomY,getWorld()); } catch (IllegalXPositionException | IllegalYPositionException exc) { this.setOutOfBounds(true); this.terminate(); } } /** * Sets the new X position of this creature to the given X position. * @param positionLeftX * The new X position to be set. * @effect The new position of this creature is set to the given X position and * current Y position * | setPosition(positionLeftX, getYPosition()) */ public void setXPosition(double positionLeftX) { setPosition(positionLeftX, getYPosition()); } /** * Sets the new Y position of this creature to the given Y position. * @param positionBottomY * The new Y position to be set. * @effect The new position of this creature is set to the current X position * and the given Y position. * | setPosition(getXPosition(), positionBottomY */ public void setYPosition(double positionBottomY) { setPosition(getXPosition(), positionBottomY); } /** * Return whether this creature is out of bounds or not. */ public boolean getOutOfBounds() { return this.outOfBounds; } /** * Variable registering whether this creature is out of bounds or not. */ public boolean outOfBounds; /** * Sets the outOfBounds boolean to the given flag. * @param flag * The flag to be set, either true or false. */ public void setOutOfBounds(boolean flag) { this.outOfBounds = true; } /** * Return the horizontal velocity of this creature. */ @Basic public double getHorizontalVelocity() { return this.horizontalVelocity; } /** * Variable registering the horizontal velocity of this creature. * The standard horizontal velocity is 0. */ private double horizontalVelocity = 0; /** * Sets the horizontal velocity of this creature to the given horizontal velocity. * * @param horizontalVelocity * The new horizontal velocity for this creature. * @post If the given horizontalVelocity is greater than or equal to zero and smaller or equal to * the maximumHorizontalVelocity then the horizontalVelocity of this creature is equal to * the given horizontalVelocity. * | if (horizontalVelocity >= 0) * | && (horizontalVelocity <= this.getMaximumHorizontalVelocity()) * | then new.getHorizontalVelocity() == horizontalVelocity * @post If the given horizontalVelocity is smaller than zero then the horizontalVelocity of this creature * is equal to zero. * | if (horizontalVelocity < 0) * | then new.getHorizontalVelocity() == 0 * @post If the given horizontalVelocity is greater than the maximumHorizontalVelocity then the * horizontalVelocity of this creature is equal to the maximumHorizontalVelocity. * | if (horizontalVelocity > this.getMaximumHorizontalVelocity()) * | then new.getHorizontalVelocity() == this.getMaximumHorizontalVelocity() */ @Raw public void setHorizontalVelocity(double horizontalVelocity) { if (horizontalVelocity < 0) { this.horizontalVelocity = 0; } else if (Util.fuzzyGreaterThanOrEqualTo(horizontalVelocity,this.getMaximumHorizontalVelocity())) { this.horizontalVelocity = this.getMaximumHorizontalVelocity(); } else { this.horizontalVelocity = horizontalVelocity; } } /** * Return the initial horizontal velocity of this creature. */ @Immutable public double getInitialHorizontalVelocity() { return this.initialHorizontalVelocity; } /** * Check whether the given initial horizontal velocity is a valid initial horizontal velocity. * * @param initialHorizontalVelocity * The initial horizontal velocity to check. * @param maximumHorizontalVelocity * The maximum horizontal velocity to check the initial velocity against. * @return True if the given initial horizontal velocity is a valid initial horizontal velocity. * | result == * | (initialHorizontalVelocity >= 1) && (initialHorizontalVelocity < maximumHorizontalVelocity) * */ public static boolean isValidInitialVelocity(double initialHorizontalVelocity, double maximumHorizontalVelocity) { return (Util.fuzzyGreaterThanOrEqualTo(initialHorizontalVelocity, 1)) && (initialHorizontalVelocity < maximumHorizontalVelocity); } /** * Variable registering the initial horizontal velocity of this creature. */ private double initialHorizontalVelocity; /** *Set the initial horizontal acceleration of this creature. */ public void setInitialHorizontalVelocity(double velocity){ this.initialHorizontalVelocity = velocity; } /** * Return the initial horizontal acceleration of this creature. */ public double getInitialHorizontalAcceleration(){ return this.initialHorizontalAcceleration; } /** * Variable registering the initial Horizontal acceleration of this creature. */ private double initialHorizontalAcceleration; public void setInitialHorizontalAcceleration(double acceleration){ this.initialHorizontalAcceleration = acceleration; } /** * Return the vertical velocity of this creature. */ public double getVerticalVelocity(){ return this.verticalVelocity; } /** * Checks whether the current vertical velocity is a valid vertical velocity. * @param verticalVelocity * @return The verticalVelocity must be a finite number. * | result == Double.isFinite(verticalVelocity) */ public boolean isValidVerticalVelocity(double verticalVelocity) { return (Double.isFinite(verticalVelocity)); } /** * Variable registering the vertical velocity of this living creature. * The standard vertical velocity is 0. */ private double verticalVelocity = 0; /** * Sets the vertical velocity of this living creature to the given vertical velocity. * * @param verticalVelocity * The new vertical velocity for this living creature. * @pre The given verticalVelocity is a valid velocity for this living creature. * | isValidVerticalVelocity(verticalVelocity) * @post The new vertical velocity is equal to the * given vertical velocity. * | then new.verticalVelocity = verticalVelocity */ @Raw public void setVerticalVelocity(double verticalVelocity){ assert isValidVerticalVelocity(verticalVelocity); this.verticalVelocity = verticalVelocity; } /** * Return the horizontal acceleration of this living creature. */ public double getHorizontalAcceleration(){ return this.horizontalAcceleration; } /** * Checks whether the given horizontalAcceleration is a valid one for this creature. * @param horizontalAcceleration * The horizontal acceleration to check. * @return True if and only if the given acceleration is positive or zero. * | result == (horizontalAcceleration >= 0) */ public static boolean isValidHorizontalAcceleration(double horizontalAcceleration) { return horizontalAcceleration >= 0; } /** * Variable registering the horizontal acceleration of this living creature. */ private double horizontalAcceleration; /** * Sets the horizontal acceleration of this living creature to the given horizontal acceleration. * * @param horizontalVelocity * The new horizontal acceleration for this living creature. * @pre The given horizontalAcceleration is a valid acceleration for this living creature. * | isValidHorizontalAcceleration(horizontalAcceleration) * @post The new horizontal acceleration is equal to the * given horizontal acceleration. * | then new.horizontalAcceleration = horizontalAcceleration */ @Raw public void setHorizontalAcceleration(double horizontalAcceleration){ assert isValidHorizontalAcceleration(horizontalAcceleration); this.horizontalAcceleration = horizontalAcceleration; } /** * Return the vertical acceleration of this living creature. */ public double getVerticalAcceleration(){ return this.verticalAcceleration; } /** * Checks whether the given verticalAcceleartion is a valid one for a creature. * @param verticalAcceleration * The vertical acceleration to check. * @return If the verticalAcceleration is 0 or -10 it is valid. * | result == * | (verticalAcceleration == 0) || (verticalAcceleration == -10) */ public static boolean isValidVerticalAcceleration(double verticalAcceleration) { return (verticalAcceleration) == 0 || (verticalAcceleration == -10); } /** * Variable registering the vertical acceleration of this living creature. * The standard vertical acceleration is 0. */ private double verticalAcceleration = 0; /** * Sets the vertical acceleration of this living creature to the given vertical acceleration. * * @param horizontalVelocity * The new vertical acceleration for this living creature. * @pre The given verticalAcceleration is a valid acceleration for this living creature. * @post The new vertical acceleration is equal to the * given vertical acceleration. * | then new.verticalAcceleration = verticalAcceleration */ @Raw public void setVerticalAcceleration(double verticalAcceleration){ assert isValidVerticalAcceleration(verticalAcceleration); this.verticalAcceleration = verticalAcceleration; } /** * Return world in which the living creature is located. */ public World getWorld(){ return this.world; } /** * Variable registering the world of this creature. */ protected World world; /** * Set the world for this living creature to the given world. * @param world * The new world for this living creature. * @post The new world for the living creature is equal to the * given world. * | new.getWorld() == world */ @Raw public void setWorld(World world){ assert canHaveAsWorld(world); this.world = world; } /** * Checks whether this creature is in a world. * @return The world must not be of null type. * | result == (world != null) */ public boolean isInWorld(){ return (world != null); } /** * Checks whether the given world is the world in which the creature * is located. * @param world * The world to check. * @return True if the given world is the world of this creature, false otherwise. * | result == (getWorld() == world) */ public boolean hasAsWorld(World world) { try { return this.getWorld() == world; } catch (NullPointerException exc) { // This creature doesn't inhabit a world. assert (world == null); return false; } } /** * Checks whether this creature can have the given world as world. * @param world * The world to check * @return The world must not be null and the world must be able to have * this creature as an object. * | result == * | (world != null) && (world.canHaveAsObject(this)) */ public boolean canHaveAsWorld(World world) { return (world != null) && (world.canHaveAsObject(this)); } /** * Return a clone of the spriteArray of this living creature. */ public Sprite[] getSpriteArray() { return this.spriteArray.clone(); } /** * Checks whether the given spriteArray is a valid spriteArray. * * @param spriteArray * The spriteArray to check against. * @effect If the object is of type Mazub, then the checker of the Mazub class is invoked. * | if (object instanceof Mazub) * | then Mazub.isValidSpriteArray(spriteArray) * @return True if the spriteArray is a valid spriteArray for a creature apart from Mazub. * These spriteArrays must be of length 2. * | result == (spriteArray.length == 2) */ @Raw public static boolean isValidSpriteArray(Sprite[] spriteArray,Object object) { if (object instanceof Mazub) return Mazub.isValidSpriteArray(spriteArray); else { int length = spriteArray.length; return (length == 2); } } /** * Variable registering the spriteArray of this living creature. */ private final Sprite[] spriteArray; public Sprite getCurrentSprite() { if (getDirection() == Direction.RIGHT) return getSpriteArray()[1]; else return getSpriteArray()[0]; } /** * Return the direction of this creature. */ public Direction getDirection() { return this.direction; } /** * Variable registering the direction of this living creature. */ private Direction direction = Direction.RIGHT; /** * Sets the direction of this living creature to the given direction. * * @param direction * The new direction of this living creature. * @post If the given direction is LEFT then the new direction of this living creature is left. * | if (direction == LEFT) * | then new.getDirection() == LEFT * @post If the given direction is RIGHT then the new direction of this living creature is right. * | if (direction == RIGHT) * | then new.getDirection() == RIGHT */ public void setDirection(Direction direction) { this.direction = direction; } /** * Sets the direction of this living creature to the given integer direction. * A 1 resembles right and a -1 resembles left. * @param direction * The new direction of this living creature in form of an integer. * @post If the given direction integer was 1, then the new direction of this creature is right. * | if (direction == 1) * | then new.getDirection() == RIGHT * @post If the given direction integer was -1, then the new direction of this creature is left. * | if (direction == -1) * | then new.getDirection() == LEFT * @post If the given direction integer was not 1 or -1, nothing happens. * | if (direction != 1) && (direction != -1) * | then new.getDirection() == old.getDirection() */ public void setDirection(int direction){ if (direction == 1){ this.direction = Direction.RIGHT; } if (direction == -1){ this.direction = Direction.LEFT; } } /** * Return the boolean indicating whether this living creature is moving * horizontally or not. */ @Basic public boolean getMoving(){ return this.moving; } /** * Variable registering whether this living creature is moving horizontally or not. */ private boolean moving = false; /** * Sets the boolean indicating whether this living creature is moving horizontally. * @param flag * The new boolean that indicates whether or not living creature is moving horizontally. * @post The new moving state of this living creature is equal to the * given flag. * | new.getMoving == flag */ @Basic public void setMoving(boolean flag) { this.moving = flag; } /** * Return the hitpoints of this living creature. */ public int getHP() { return this.hitpoints; } /** * Variable registering the hitpoints of this living creature. */ private int hitpoints; /** * Sets the hitpoints of this living creature to the given hitpoints. * @param HP * The new hitpoints to be set for this living creature. * @post If the hitpoints are lower than the minimum hitpoints for this creature * then the creature is terminated and the hitpoints are set to the minimum hitpoints. * | if (HP <= getMinHp()) * | then ((isDead()) || (isDying())) && new.getHP() == getMinHP() * @post If the hitpoints are higher than the maximum hitpoints of this creature, then the hitpoints * are set to the maximum hitpoints. * | if (HP > getMaxHP()) * | then new.getHP() == getMaxHP() * @post If the hitpoints are neither lower than the minimum hitpoints or higher than the maximum hitpoints * then the hitpoints are set to the given hitpoints. * | if (HP <= getMaxHP()) && (HP > getMinHP()) * | then new.getHP() == HP */ @Raw public void setHP(int HP) { if (HP <= getMinHP()) { hitpoints = getMinHP(); this.terminate(); } else if (HP > getMaxHP()) hitpoints = getMaxHP(); else hitpoints = HP; } /** * Terminates this living creature. */ public abstract void terminate(); /** * Return the maximum hitpoints this creature can have as an integer. */ public abstract int getMaxHP(); /** * Return the minimum hitpoints this creature can have as an integer. */ public abstract int getMinHP(); /** * Variable registering the minimum hitpoints of this living creature. */ public static final int MIN_HP = 0; /** * Adds the given hit points to the current hit points of this living creature * @param HP * The given hit points to add * @post The hit points for this living creature are added with the given hit points * |new.setHP(getHP() + HP); * @post If the given hit point are smaller then zero and the living creature * is a slime. Then one hit point is subtracted from every other slime in the * same school as the living creature. */ public void addHP(int HP) { this.setHP(getHP() + HP); } /** * @return the time since this living creature was hit by an enemy */ public double getHitTimer(){ return this.hitTimer; } /** * The time since the living creature was hit by an enemy * The initial value is set so the creature can immediatly interact * with other creatures. */ private double hitTimer = 0.6; /** * sets the time since last hit by an enemy to the given time * @param time * The given time * @post Sets the hit timer to the given time * |new.getHitTimer() = time; */ public void setHitTimer(double time){ this.hitTimer = time; } /** * @return the time since the last terrain damage */ protected double getTerrainTimer() { return this.terrainTimer; } /** * The time since the last terrain damage */ protected double terrainTimer; /** * Sets the time since the last terrain damage to the given time * @param time * The given time * @post Sets the terrain timer to the given time * |new.getTerrainTimer() = time; */ protected void setTerrainTimer(double time) { assert isValidTimerValue(time); terrainTimer = time; } /** * Checks whether the given time is a valid time * @param time * The time to check * @return True if the time is valid otherwise returns false */ public static boolean isValidTimerValue(double time) { return Util.fuzzyGreaterThanOrEqualTo(time, 0); } /** * applies magma damage to the living creature * @param timeInterval * The given time interval * @Post Fifty hit point are subtracted from the * current hit point of the living creature if it hasn't received any terrain damage * in the last 0.2 seconds. * |if (Util.fuzzyGreaterThanOrEqualTo(getTerrainTimer(), 0.2))) * |new.getHP() = old.getHP() - 50 * |new.getTerrainTimer = 0; * @Post The living creature has received any terrain damage the last 0.2 seconds * so no damage is applied and the terrainTimer goes up * |if (getTerrainTimer() < 0.2) * |this.setTerrainTimer(this.getTerrainTimer() + timeInterval); */ private void applyMagmaDamage(double timeInterval) { if (Util.fuzzyGreaterThanOrEqualTo(getTerrainTimer(), 0.2)){ addHP(-50); this.setTerrainTimer(0); }else{ this.setTerrainTimer(this.getTerrainTimer() + timeInterval); } } /** * applies water damage to the living creature * @param timeInterval * The given time interval * @Post Two hit point are subtracted from the current hit point * of the living creature if it hasn't received any terrain damage * in the last 0.2 seconds. * |if (Util.fuzzyGreaterThanOrEqualTo(getTerrainTimer(), 0.2))) * |new.getHP() = old.getHP() - 2 * |new.getTerrainTimer() = 0 * @Post The living creature has received any terrain damage the last 0.2 seconds * so no damage is applied and the terrainTimer goes up * |if (getTerrainTimer() < 0.2) * |this.setTerrainTimer(this.getTerrainTimer() + timeInterval); */ private void applyWaterDamage(double timeInterval) { if ((Util.fuzzyGreaterThanOrEqualTo(getTerrainTimer(), 0.2))){ addHP(-2); this.setTerrainTimer(0); }else{ this.setTerrainTimer(this.getTerrainTimer() + timeInterval); } } /** * applies air damage to the living creature * @param timeInterval * The given time interval * @Post Six hit point are subtracted from the * current hit point of the living creature if it hasn't received any terrain damage * in the last 0.2 seconds. * |if (Util.fuzzyGreaterThanOrEqualTo(getTerrainTimer(), 0.2))) * |new.getHP() = old.getHP() - 6 * |new.getTerrainTimer = 0; * @Post The living creature has received any terrain damage the last 0.2 seconds * so no damage is applied and the terrainTimer goes up * |if (getTerrainTimer() < 0.2) * |this.setTerrainTimer(this.getTerrainTimer() + timeInterval); */ private void applyAirDamage(double timeInterval){ if ((Util.fuzzyGreaterThanOrEqualTo(getTerrainTimer(), 0.2))){ addHP(-6); this.setTerrainTimer(0); }else{ this.setTerrainTimer(this.getTerrainTimer() + timeInterval); } } /** * Advances the time and alters all time related aspects of this living creature * according to the given time interval. */ public abstract void advanceTime(double dt); /** * Return the runtimer of this living creature. */ protected double getRunTime() { return this.runTime; } /** * Variable registering the time since living creature stopped running when living creature is not moving horizontally. * When living creature moves horizontally, the variable registers the time since the last spritechange. */ protected double runTime = 1; /** * Sets the runTimer of this living creature to the given time. * * @param runTimer * The new time for the runTimer for this living creature. * @post The new runTimer for this living creature is equal to the given * runTimer. * | new.getRunTime == runTime */ protected void setRunTime(double runTime) { assert isValidTimerValue(runTime); this.runTime = runTime; } /** * Checks whether the given timeInterval is a valid timeInterval for this living creature. * * @param timeInterval * The timeInterval to be checked. * @return True if and only if the time interval is between 0 ands 0.2. * | result == * | (timeInterval >= 0) && (timeInterval <= 0.2) */ public static boolean isValidTimeInterval(double timeInterval) { return Util.fuzzyGreaterThanOrEqualTo(timeInterval, 0) && Util.fuzzyLessThanOrEqualTo(timeInterval, 0.2); } /** * In-class enumeration of the different States of a living creature. */ protected static enum State { ALIVE,DYING,DEAD; } /** * Return the current state of this living creature */ protected State getState() { return this.state; } /** * Variable registering the current state of this living creature. * The default value is ALIVE */ protected State state = State.ALIVE; /** * Sets the current state for the living creature the given state * @param state * The given state * @post Sets the current state for the living creature the given state * | new.state = state; */ protected void setState(State state) { assert (state != null); this.state = state; } /** * Check whether the living creature is dead or not. * @return True of the state of this creature is DEAD. * | result == * | (this.getState() == DEAD) */ public boolean isDead() { return (this.getState() == State.DEAD); } /** * Check whether the living creatures is dying or not. * @return True of the state of this creature is DYING. * | result ==é * | (this.getState() == DYING) */ public boolean isDying() { return (this.getState() == State.DYING); } /** * Check whether the living creature is alive or not. * @return True of the state of this creature is ALIVE. * | result == * | (this.getState() == ALIVE) */ public boolean isAlive() { return (this.getState() == State.ALIVE); } /** * @param timeInterval * The time interval in which the position of this creature has changed. * @post The new X position of this Mazub is equal to the current X position added to the horizontal distance * travelled calculated with a formula using the given time interval. * new.getXPosition = this.getXPosition() + distanceCalculated */ public void changeHorizontalPosition(double timeInterval,double horizontalAcceleration){ this.setHorizontalAcceleration(horizontalAcceleration); if (Util.fuzzyGreaterThanOrEqualTo(horizontalVelocity,this.getMaximumHorizontalVelocity())){ this.setHorizontalAcceleration(0); } double newPositionX = this.getXPosition() + this.getDirection().getInt() * (100 * this.getHorizontalVelocity()*timeInterval + 50 * this.getHorizontalAcceleration()*timeInterval*timeInterval); double oldPositionX = this.getXPosition(); setXPosition(newPositionX); if (Interaction.collidesWithTerrainHorizontal(this, 1)){ setXPosition(oldPositionX); } if (Interaction.interactWithMovementBlockingCreature(this,this.getWorld())) { Interaction.interactWithOtherCreatures(this); setXPosition(oldPositionX); } if (this instanceof Slime) { if (noTerrainUnderSidesOfObject()) { setXPosition(oldPositionX); } } if (!this.collidesWithTerrainThroughBottomBorder()){ this.startFall(-10); } } /** * @param timeInterval * The time interval in which the position of this creature has changed. * @post The new Y position of this Mazub is equal to the current Y position added to the vertical distance * travelled calculated with a formula using the given time interval. * new.getYPosition = this.getYPosition() + distanceCalculated */ public void changeVerticalPosition(double timeInterval) { if ((this instanceof Shark) && (this.getMovingVertical()) && (this.getVerticalVelocity() < 0)) { if (Interaction.collidesWithTerrainTopSide(this, 2) && Interaction.collidesWithTerrainBottomSide(this, 2)) { this.setVerticalAcceleration(0); this.setVerticalVelocity(0); } } double oldPositionY = this.getYPosition(); double newPositionY = this.getYPosition() + 100 * this.getVerticalVelocity() * timeInterval + 50 * this.getVerticalAcceleration() * timeInterval * timeInterval; setYPosition(newPositionY); boolean creatureBlock = Interaction.interactWithMovementBlockingCreature(this,this.getWorld()); if (Interaction.collidesWithTerrainVertical(this, 1) || creatureBlock){ if (creatureBlock) { Interaction.interactWithOtherCreatures(this); } setYPosition(oldPositionY); this.endJump(); if (this.collidesWithTerrainThroughBottomBorder() || creatureBlock){ this.setMovingVertical(false); this.setVerticalAcceleration(0); this.setVerticalVelocity(0); } } } /** * Calculates the timeInterval needed for this living creature to travel just 1 pixel. * @param dt * The original timeInterval. * @return The minimum of the time interval to travel 1 pixel horizontal and the time interval to * travel 1 pixel vertically. * | result == * | min( * | (0.01 / (this.getHorizontalVelocity() + this.getHorizontalAcceleration() * dt)), * | abs(0.01 / (this.getVerticalVelocity() + this.getVerticalAcceleration() * dt)) * | ) */ public double getSmallestDT(double dt) { double horizontalDT = 0.01 / (this.getHorizontalVelocity() + this.getHorizontalAcceleration() * dt); double verticalDT = Math.abs(0.01 / (this.getVerticalVelocity() + this.getVerticalAcceleration() * dt)); return Math.min(Math.min(horizontalDT, verticalDT), dt); } /** * Return the boolean indicating whether this Mazub is moving * vertically or not. */ @Basic public boolean getMovingVertical() { return this.movingVertical; } /** * Variable registering whether this Mazub is moving vertically or not. */ private boolean movingVertical = false; /** * Sets the boolean indicating whether this Mazub is moving vertically. * * @param flag * The new boolean that indicates wether or not Mazub is moving vertically. * @post The new movingVertical state of this Mazub is equal to the * given flag. * | new.getMovingVertical == flag */ @Basic public void setMovingVertical(boolean flag) { this.movingVertical = flag; } /** * start a move to the given direction as the current movement of this LivingCreature * * @post The new direction is opposite to the current direction, * the horizontal velocity is reset to zero and the horizontal acceleration is set to 1.5. * | new.getDirection() == direction * | new.getHorizontalVelocity == this.getInitialHorizontalVelocity() * | new.getHorizontalAcceleration == this.getInitialHorizontalAcceleration() */ public void startMove(double velocity,double horizontalAcceleration,Direction direction){ this.setHorizontalAcceleration(horizontalAcceleration); this.setHorizontalVelocity(velocity); this.setMoving(true); this.setDirection(direction); this.setRunTime(0); } /** * start a move to the given direction as the current movement of this LivingCreature * * @post The new direction is opposite to the current direction, * the horizontal velocity is reset to zero and the horizontal acceleration is set to 1.5. * | new.getDirection() == direction * | new.getHorizontalVelocity == this.getInitialHorizontalVelocity() * | new.getHorizontalAcceleration == this.getInitialHorizontalAcceleration() */ public void startMove(Direction direction){ this.setHorizontalAcceleration(this.getInitialHorizontalAcceleration()); this.setHorizontalVelocity(this.getInitialHorizontalVelocity()); this.setMoving(true); this.setDirection(direction); this.setRunTime(0); } /** * Initializes vertical movment. * * @param velocity * The initial vertical velocity to start the jump with. * @param acceleration * The vertical acceleration of this jump. * @post If this creature is not moving vertical then * the new vertical velocity is set to the given velocity, * the new vertical acceleration is set to the given acceleration * and the boolean movingVertical is set to true. * | if (! getMovingVertical()) * | then new.getVerticalVelocity() == velocity * | && new.getVerticalAcceleration() == acceleration * | && new.getMovingVertical() == true */ public void startJump(double velocity,double acceleration){ if (! getMovingVertical()){ this.setVerticalVelocity(velocity); this.setVerticalAcceleration(acceleration); this.setMovingVertical(true); } } /** * Ends horizontal movement in the direction Mazub is facing. * * @param horizontalAcceleration * The new horizontal acceleration for this Mazub. * @pre The given horizontal acceleration must be a valid horizontal acceleration. * | isValidHorizontalAcceleration(horizontalAcceleration) * @post The new horizontal velocity of this Mazub is equal to zero, * the new horizontal acceleration is set to the given horizontalAcceleration, * the boolean moving is set to false and the runTime is set to zero. * | new.getHorizontalVelocity() == 0 && new.getMoving == false * | && new.getRunTime == 0 */ public void endMove(double horizontalAcceleration) { assert isValidHorizontalAcceleration(horizontalAcceleration); this.setHorizontalVelocity(0); this.setHorizontalAcceleration(horizontalAcceleration); this.setMoving(false); this.setRunTime(0); } /** * Ends horizontal movement in the direction Mazub is facing. * @post The new horizontal velocity of this Mazub is equal to zero, * the new horizontal acceleration is set to 0, * the boolean moving is set to false and the runTime is set to zero. * | new.getHorizontalVelocity() == 0 && new.getMoving == false * | && new.getRunTime == 0 */ public void endMove() { this.setHorizontalVelocity(0); this.setHorizontalAcceleration(0); this.setMoving(false); this.setRunTime(0); } /** * Ends vertical movement. * * @post If the vertical velocity is greater than zero then * the new vertical velocity is set to zero. * | if (this.getVerticalVelocity() > 0) * | then new.getVerticalVelocity() == 0 */ public void endJump(){ if (this.getVerticalVelocity() > 0){ this.setVerticalVelocity(0); } } /** * Initializes the falling motion of this living creature. * @param acceleration * The vertical acceleration with which this living creature falls. * @post The new vertical acceleration is set to the given acceleration and * the boolean movingVertical is set to true. * | new.getVerticalAcceleration() == acceleration * | && new.getMovingVertical() == true */ public void startFall(double acceleration){ this.setVerticalAcceleration(acceleration); this.setMovingVertical(true); } /** * Return the maximum horizontal velocity of this Mazub. */ @Basic public double getMaximumHorizontalVelocity() { return this.maximumHorizontalVelocity; } /** * Check whether the given maximum horizontal velocity is a valid maximum horizontal velocity. * * @param maximumHorizontalVelocity * The maximum horizontal velocity to check. * @param initialHorizontalVelocity * The initial horizontal velocity to check the maximum horizontal velocity against. * @return True if the given maximum horizontal velocity is a valid maximum horizontal velocity. * | result == (maximumHorizontalVelocity > initialHorizontalVelocity) */ public static boolean isValidMaximumHorizontalVelocity(double maximumHorizontalVelocity, double initialHorizontalVelocity) { return maximumHorizontalVelocity > initialHorizontalVelocity; } /** * Variable registering the maximum horizontal velocity of this Mazub. */ protected double maximumHorizontalVelocity; /** * Sets the maximum horizontal velocity of this Mazub to the given maximum horizontal velocity. * @param maximumHorizontalVelocity * The new maximum horizontal velocity for this Mazub. * @pre The given maximum horizontal velocity must be a valid maximum horizontal velocity * for this Mazub. * | isValidMaximumHorizontalVelocity(maximumHorizontalVelocity, this.getInitialHorizontalVelocity()) * @post The new maximum horizontal velocity of this Mazub is equal to the given maximum horizontal velocity. * | new.getMaximumHorizontalVelocity() == maximumHorizontalVelocity */ @Raw protected void setMaximumHorizontalVelocity(double maximumHorizontalVelocity) { assert isValidMaximumHorizontalVelocity(maximumHorizontalVelocity, this.getInitialHorizontalVelocity()); this.maximumHorizontalVelocity = maximumHorizontalVelocity; } /** * Returns the width of this creature. */ public int getWidth() throws IllegalSizeException { int size = getCurrentSprite().getWidth(); if (! isValidSize(size)) throw new IllegalSizeException(size); return size; } /** * Returns the height of this creature. */ public int getHeight() throws IllegalSizeException { int size = getCurrentSprite().getHeight(); if (! isValidSize(size)) throw new IllegalSizeException(size); return size; } /** * Returns the size of a sprite of this creature. * @param sprite * The sprite of which the size must be determined. * @return Returns the size of the given sprite in an array of type int. * this array consists of two elements, the height and width respectively. * @throws IllegalSizeException * The size of this sprite is not a valid size for a sprite of this Mazub. * | (! isValidSize([sprite.getHeight(),sprite.getWidth()])) */ public int[] getSize() throws IllegalSizeException { int[] size = new int[2]; try { size[0] = getWidth(); size[1] = getHeight(); } catch (IllegalSizeException exc) { throw exc; } return size; } /** * Checks whether the given size is a valid size for this creature. * * @param size * The size to be checked. * @return True if and only if the size is greater or equal to 0. * | result == * | (size > 0) */ public static boolean isValidSize(int size) { return Util.fuzzyGreaterThanOrEqualTo(size, 0); } /** * Checks whether there is a part of the bottom border of this creature that is on top of a solid tile. * @return If the bottom left pixel or the bottom right pixel of this creature is on top of a solid tile, true is returned. * If the creature is of type Shark, whether the shark is submerged or not is returned. * | if (this instanceof Shark) * | then result == this.getSubmerged() * | if (this.getWorld().getTileType(getXPosition(),getYPosition()) == 1) * | || (this.getWorld().getTileType(getXPosition()+getSize()[0],getYPosition()) == 1) * | then result == true */ public boolean collidesWithTerrainThroughBottomBorder(){ World world = this.getWorld(); if (this instanceof Shark) { return this.getSubmerged(); } try{ if ((world.getTileType((int)this.getXPosition()+1, (int)this.getYPosition()) != 1) && ((world.getTileType((int)(this.getXPosition() + this.getSize()[0]), (int)(this.getYPosition())) != 1))){ return false; } }catch (NullPointerException exc){ } return true; } /** * Checks whether there is a part of the bottom border of this creature that is not on top of solid terrain. * @return If the bottom left pixel or the bottom right pixel of this creature is not on top of a solid tile, true is returned. * | if (this.getWorld().getTileType(getXPosition(),getYPosition()-1) != 1) * | || (this.getWorld().getTileType(getXPosition()+getSize()[0],getYPosition()-1) != 1) * | then result == true */ public boolean noTerrainUnderSidesOfObject(){ World world = this.getWorld(); try{ if ((world.getTileType((int)this.getXPosition(), (int)this.getYPosition()-1) != 1) || ((world.getTileType((int)(this.getXPosition() + this.getSize()[0]), (int)(this.getYPosition())-1) != 1))){ return true; } }catch(NullPointerException exc){ } return false; } /** * Checks whether this living creature is submerged in water. * @return If the bottom and top border of this creature collide with water, then true is returned. * | result == * | (Interaction.collidesWithTerrainTopSide(this, 2) | && Interaction.collidesWithTerrainBottomSide(this, 2) */ private boolean getSubmerged() { return (Interaction.collidesWithTerrainTopSide(this, 2) && Interaction.collidesWithTerrainBottomSide(this, 2)); } /** * @return the current death timer of this living creature */ protected double getDeathTimer() { return this.deathTimer; } protected double deathTimer; /** * Sets the death timer to the given time. * @param time * The given time for the death timer * @post The death timer is set to the given time * | new.getDeathTimer() = time; */ protected void setDeathTimer(double time) { assert isValidTimerValue(time); this.deathTimer = time; } /** * Applies terrain damage to the living creature if needed * @param timeInterval * The current timeInterval since the last change of position */ public void applyTerrainDmg(double timeInterval){ if (Interaction.collidesWithTerrain(this, 3)){ this.applyMagmaDamage(timeInterval); }else if (Interaction.collidesWithTerrain(this, 2)){ if (!(this instanceof Shark)){ this.applyWaterDamage(timeInterval); }else{ this.setTerrainTimer(0); } }else{ if (!(this instanceof Shark)){ this.setTerrainTimer(this.getTerrainTimer() + timeInterval); }else{ this.applyAirDamage(timeInterval); } } } public Program getProgram(){ return this.program; } private Program program = null; public void setProgram(Program program){ this.program = program; program.setPossessedObject(this); } }
package com.mysender; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; public class MyOrderedSender extends Activity { private static final String MyAction = "com.mybroadcast.action.OrderedAction"; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); //取得發送廣播系統的按鈕 Button btn = (Button)this.findViewById(R.id.btn); //委任點選按鈕的事件 btn.setOnClickListener(new OnClickListener(){ public void onClick(View view) { //建立包裹廣播資訊的物件 Intent intent = new Intent(); //設定物件的識別碼 intent.setAction(MyAction); //設定要廣播的資訊 intent.putExtra("myOrderedMsg", "廣播開始!"); //進行廣播 //MyOrderedSender.this.sendOrderedBroadcast(intent, "android.permission.myBroadcastPermission"); MyOrderedSender.this.sendOrderedBroadcast(intent, null); } }); } }
/* * 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 asos.p8_aop; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.ProceedingJoinPoint; import org.springframework.util.StopWatch; /** * * @author vsa */ public class MyAspectBean { public void myBeforeAdvice(JoinPoint jp) { System.out.println("\tmy before advice"); System.out.println("\tMethod Signature: " + jp.getSignature()); } /* vypise navratovu hodnotu */ public void myReturnAdvice(JoinPoint jp, Object result) { System.out.println("\tmy return advice"); System.out.println("\tResult in advice: " + result); } /* zisti a vypise dobu vykonavania volanej metody */ public Object myAroundAdvice(ProceedingJoinPoint call, String message) throws Throwable { System.out.println("\tmy around advice " + message); StopWatch clock = new StopWatch("\tProfiling"); try { clock.start(call.toShortString()); return call.proceed(); // mozeme dokonca zmenit aj argumenty alebo navratovu hodnotu // Object[] par = {"ahoj"}; // return call.proceed(par); } finally { clock.stop(); System.out.println(clock.prettyPrint()); } } }
package com.ibeiliao.statement.impl.entity; import java.io.Serializable; import java.util.Date; /** * t_pay_bank_unmatch * * <pre> * 自动生成代码: 表名 t_pay_bank_unmatch, 日期: 2016-08-17 * unmatch_id <PK> bigint(20) * sum_id bigint(20) * pay_id bigint(20) * bill_no varchar(50) * bill_amount bigint(20) * bill_amount_type tinyint(4) * bill_time datetime(19) * pay_amount bigint(20) * pay_amount_type tinyint(4) * pay_time datetime(19) * unmatch_type smallint(6) * pay_type smallint(6) * match_flag tinyint(4) * match_date date(10) * stat_date date(10) * create_time datetime(19) * </pre> */ public class PayBankUnmatchPO implements Serializable { private static final long serialVersionUID = -3074457344134848664L; /** unmatchId */ private long unmatchId; /** sumId */ private long sumId; /** payId */ private long payId; /** billNo */ private String billNo; /** billAmount */ private long billAmount; /** billAmountType */ private short billAmountType; /** billTime */ private Date billTime; /** payAmount */ private long payAmount; /** payAmountType */ private short payAmountType; /** payTime */ private Date payTime; /** unmatchType */ private short unmatchType; /** payType */ private short payType; /** matchFlag */ private short matchFlag; /** matchDate */ private Date matchDate; /** statDate */ private Date statDate; /** 创建时间 */ private Date createTime; public void setUnmatchId(long unmatchId) { this.unmatchId = unmatchId; } public long getUnmatchId() { return unmatchId; } public void setSumId(long sumId) { this.sumId = sumId; } public long getSumId() { return sumId; } public void setPayId(long payId) { this.payId = payId; } public long getPayId() { return payId; } public void setBillNo(String billNo) { this.billNo = billNo; } public String getBillNo() { return billNo; } public void setBillAmount(long billAmount) { this.billAmount = billAmount; } public long getBillAmount() { return billAmount; } public void setBillAmountType(short billAmountType) { this.billAmountType = billAmountType; } public short getBillAmountType() { return billAmountType; } public void setBillTime(Date billTime) { this.billTime = billTime; } public Date getBillTime() { return billTime; } public void setPayAmount(long payAmount) { this.payAmount = payAmount; } public long getPayAmount() { return payAmount; } public void setPayAmountType(short payAmountType) { this.payAmountType = payAmountType; } public short getPayAmountType() { return payAmountType; } public void setPayTime(Date payTime) { this.payTime = payTime; } public Date getPayTime() { return payTime; } public void setUnmatchType(short unmatchType) { this.unmatchType = unmatchType; } public short getUnmatchType() { return unmatchType; } public void setPayType(short payType) { this.payType = payType; } public short getPayType() { return payType; } public void setMatchFlag(short matchFlag) { this.matchFlag = matchFlag; } public short getMatchFlag() { return matchFlag; } public void setMatchDate(Date matchDate) { this.matchDate = matchDate; } public Date getMatchDate() { return matchDate; } public void setStatDate(Date statDate) { this.statDate = statDate; } public Date getStatDate() { return statDate; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public Date getCreateTime() { return createTime; } }
package com.tencent.mm.plugin.setting.model; public interface a$a { void vK(int i); }
package cn.xeblog.design.patterns.decorator.code.other; /** * 迪迦装饰者 * * @author anlingyi * @date 2021/4/17 10:46 下午 */ public abstract class TigaDecorator implements TigaService { private TigaService tigaService; public TigaDecorator(TigaService tigaService) { this.tigaService = tigaService; } @Override public void fist() { this.tigaService.fist(); } @Override public void leg() { this.tigaService.leg(); } @Override public void fly() { this.tigaService.fly(); } }
package L3.task4; import java.util.ArrayList; public class Job implements Runnable { MFU mfu; ArrayList<Integer> job; public Job(MFU mfu, ArrayList<Integer> job) { this.mfu = mfu; this.job = job; } public void run() { mfu.print(job); } }
package com.andy.weexlab.activity; /** * Created by Andy on 2017/9/12. */ public class EventPageActivity extends BaseWXActivity { @Override public boolean renderLocal() { return false; } @Override public String urlRend() { return null; } }
public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World"); String st = "how r you"; System.out.println("String is : " + st); } }
package ua.kiev.doctorvera; import java.util.ArrayList; import java.util.HashMap; import java.util.Locale; import java.util.Random; import android.content.Intent; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.os.Bundle; import android.preference.PreferenceManager; import android.support.v4.view.ViewPager; import android.support.v7.app.ActionBar; import android.support.v7.app.ActionBarActivity; import android.util.Log; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.Window; import android.widget.ListView; /* * Main activity creates three tabs * <ul> * <li>Archive - shows list of sent SMS</li> * <li>New SMS - tab where you can create new SMS</li> * <li>Templates - shows list of saved SMS templates</li> * </ul> * <p>Adapters, and listeners are connected to tabs here</p> * <p>This class creates menu items and handles menu actions </p> * @author Volodymyr Bodnar * @version %I%, %G% * @since 1.0 */ public class MainActivity extends ActionBarActivity { // Declare Tab Variable private ActionBar.Tab tab1, tab2, tab3; private ViewPager viewPager; // Main activity view private TabsPagerAdapter mAdapter; // Handling tabs and swipe private ActionBar actionBar; private SMS_DAO smsDao = new SMS_DAO(this); // Object to manipulate SMS // objects inside the database private final String LOG_TAG = "MyLogs MainActivity"; private SharedPreferences sPref; /* * (non-Javadoc) * * @see android.support.v7.app.ActionBarActivity#onCreate(android.os.Bundle) */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS); requestWindowFeature(Window.FEATURE_PROGRESS); //Initializing Shared Preferenses sPref = PreferenceManager.getDefaultSharedPreferences(this); //Setting Locale Utils.setLocale(this, sPref.getString("LANGUAGE", Locale.getDefault().toString())); //Generating ID for Application if (sPref.getString("ID", null)==null){ Editor ed = sPref.edit(); Integer id = new Random().nextInt(Integer.MAX_VALUE); ed.putString("ID", "" + id); ed.commit(); Log.d(LOG_TAG, "Generated new Program ID: " + id); } //Check Settings, if empty call Settings Activity if (sPref.getString("LOGIN", null)==null && sPref.getString("PASSWORD", null)==null && sPref.getString("ALPHA NAME", null)==null && sPref.getString("MY LICENSE", null)==null){ Log.d(LOG_TAG, "Authentification settings are empty, calling Settings Activity "); Intent intent = new Intent(this, SettingsActivity.class); startActivity(intent); } // Initilization setContentView(R.layout.activity_main); viewPager = (ViewPager) findViewById(R.id.activity_main); actionBar = getSupportActionBar(); mAdapter = new TabsPagerAdapter(getSupportFragmentManager(), savedInstanceState, this); viewPager.setAdapter(mAdapter); viewPager.setOnPageChangeListener(mAdapter); actionBar.setHomeButtonEnabled(false); actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS); // Set Tab Titles tab1 = actionBar.newTab().setText(R.string.tab1_header); tab2 = actionBar.newTab().setText(R.string.tab2_header); tab3 = actionBar.newTab().setText(R.string.tab3_header); // Set Tab Tag tab1.setTag("ArchiveTab"); tab2.setTag("NewSMSTab"); tab3.setTag("TemplateTab"); // Set Tab Listeners tab1.setTabListener(mAdapter); tab2.setTabListener(mAdapter); tab3.setTabListener(mAdapter); // Add tabs to actionbar actionBar.addTab(tab1); actionBar.addTab(tab2, true); // Active Tab actionBar.addTab(tab3); getActionBar().show(); } // onCreate /* * Creating menu items * * @see android.app.Activity#onCreateOptionsMenu(android.view.Menu) */ public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.main_menu, menu); return super.onCreateOptionsMenu(menu); } /* * Refreshing menu items depending on the active tab * * @see android.app.Activity#onPrepareOptionsMenu(android.view.Menu) */ public boolean onPrepareOptionsMenu(Menu menu) { MenuItem deleteChecked = (MenuItem) menu.findItem(R.id.delete_checked); MenuItem deleteAll = (MenuItem) menu.findItem(R.id.clear_all); int tab = getActionBar().getSelectedTab().getPosition(); // Log.d("tab#",""+tab); switch (tab) { case 0: deleteChecked.setVisible(true); deleteAll.setVisible(true); break; case 1: deleteChecked.setVisible(false); deleteAll.setVisible(false); break; case 2: deleteChecked.setVisible(true); deleteAll.setVisible(true); break; } return super.onPrepareOptionsMenu(menu); } /* * Handling menu options * * @see android.app.Activity#onOptionsItemSelected(android.view.MenuItem) */ public boolean onOptionsItemSelected(MenuItem item) { super.onOptionsItemSelected(item); // Find which Menu Item has been selected switch (item.getItemId()) { // Check for each known Menu Item //Settings activity case (R.id.action_settings): Intent intent = new Intent(this, SettingsActivity.class); startActivity(intent); return true; //Quit button case (R.id.quit): System.exit(0); return true; // Delete checked SMS case (R.id.delete_checked): deleteChecked(); return true; //Depending on the tab selected delete Template SMS or Archived SMS case (R.id.clear_all): int tab = getActionBar().getSelectedTab().getPosition(); deleteConfirm(tab); return true; // Return false if you have not handled the Menu Item default: return false; } } /* * Creating confirmation dialog for deleting SMS * @param tab indicates the state of SMS to be deleted: 2 - templates, 0 - all other */ private void deleteConfirm(int tab) { ArrayList<SMS> smsToDelete = new ArrayList<SMS>(); switch (tab){ case 0: smsToDelete.addAll(smsDao.getAllSMS((byte)3)); smsToDelete.addAll(smsDao.getAllSMS((byte)4)); smsToDelete.addAll(smsDao.getAllSMS((byte)5)); smsToDelete.addAll(smsDao.getAllSMS((byte)6)); if (smsToDelete.size() > 0) { DialogDeleteSMS dialog = new DialogDeleteSMS((ListView) findViewById(R.id.archive_list)); dialog.setSMStoDelete(smsToDelete); dialog.show(getSupportFragmentManager(), "delete_all_sms"); } break; case 2: smsToDelete.addAll(smsDao.getAllSMS((byte)2)); if (smsToDelete.size() > 0) { DialogDeleteSMS dialog = new DialogDeleteSMS((ListView) findViewById(R.id.template_list)); dialog.setSMStoDelete(smsToDelete); dialog.show(getSupportFragmentManager(), "delete_all_sms"); } break; } } /* * Searches for checked list items depending on the active tab, and retrieves proper SMS object */ @SuppressWarnings("unchecked") private void deleteChecked() { ArrayList<SMS> smsToDelete = new ArrayList<SMS>(); int tab = getActionBar().getSelectedTab().getPosition(); //active tab ListView lvMain = null; if (tab == 2) lvMain = (ListView) findViewById(R.id.template_list); if (tab == 0) lvMain = (ListView) findViewById(R.id.archive_list); //Searching for checked HashMap<String, Object> item; for (int i = 0; i < lvMain.getCount(); i++) { item = (HashMap<String, Object>) lvMain.getItemAtPosition(i); // Log.d("myLog", "" + item); if (item.containsKey("checked") && item.get("checked").equals(true)) smsToDelete.add(smsDao.getSMS((Integer) item.get("id"))); } //Creating confirmation dialog for deleting checked SMS if (smsToDelete.size() > 0) { DialogDeleteSMS dialog = new DialogDeleteSMS(lvMain); dialog.setSMStoDelete(smsToDelete); dialog.show(getSupportFragmentManager(), "delete_sms"); } } }
package practice; import java.util.Scanner; public class AddDigit { public static void main(String[] args) { int num, temp,rem=0,sum=0; Scanner scan=new Scanner(System.in); System.out.println("Enter any number: "); num=scan.nextInt(); temp=num; while(num>0){ rem=num%10; sum=sum+rem; num=num/10; } System.out.println("Sum of digits of "+temp+" is: "+sum); } }