text
stringlengths
10
2.72M
package gov.nih.mipav.view.renderer.J3D.volumeview; import gov.nih.mipav.model.file.*; import gov.nih.mipav.model.structures.*; import gov.nih.mipav.view.*; import java.io.*; import javax.media.j3d.*; import javax.swing.*; import javax.vecmath.*; /** * Implementation of Volume Sculpting for the RayCast and ShearWarp Volume Renderers. See Sculptor.java. * * @author Alexandra Bokinsky, Ph.D. Under contract from Magic Software. * @see ViewJFrameVolumeView * @see RayCastVolumeRenderer * @see ShearWarpVolumeRenderer */ public class VolumeSculptor extends Sculptor { //~ Instance fields ------------------------------------------------------------------------------------------------ /** DOCUMENT ME! */ protected boolean m_bShear = false; /** The volume renderer that is currently rendering the volume data:. */ protected VolumeRenderer m_kVolumeRenderer; /** References to the sculpt image. */ private ModelImage kImageAref = null; /** DOCUMENT ME! */ private ModelImage kImageBref = null; //~ Constructors --------------------------------------------------------------------------------------------------- /** * Constructor: * * @param kVolumeRenderer reference to current renderer * @param iSculptWidth Canvas Width * @param iSculptHeight Canvas Height */ public VolumeSculptor(VolumeRenderer kVolumeRenderer, int iSculptWidth, int iSculptHeight) { m_kVolumeRenderer = kVolumeRenderer; m_bShear = kVolumeRenderer instanceof VolumeRendererShearWarp; m_kCanvas3D = kVolumeRenderer.getCanvas(); } //~ Methods -------------------------------------------------------------------------------------------------------- /** * applySculpt: called by ViewJFrameVolumeView when the user presses the "Apply Sculpt" button. This function has * several steps: 1. Getting the ModelImage volume data and correctly calculating the center of the volume and the * spacing of the volume. 2. Calculating the viewing Transformations. 3. Determining which voxels in the volume fall * within the sculpt region drawn on the screen, and setting those values to the minimum voxel value. * * @return DOCUMENT ME! */ public boolean applySculpt() { /* Disable drawing the sculpt region outline: */ m_bSculptEnabled = false; boolean bVolumeChanged = false; if (m_kVolumeRenderer == null) { return false; } if (m_bSculptDrawn == false) { return false; } /* Get the current width of the Canvas, which may have changed. The * width of the canvas is used to set the field of view for the * displayed image. */ int iCanvasWidth = m_kCanvas3D.getWidth(); /* * 1. Access the volume data and calculate the bounds of the data, center, and spacing parameters: */ /* The ModelImages that will be changed by the sculpturing: */ kImageAref = null; kImageBref = null; kImageAref = m_kVolumeRenderer.getImageA(); kImageBref = m_kVolumeRenderer.getImageB(); /* The size of the ModelImage for indexing: */ int iXBound = kImageAref.getExtents()[0]; int iYBound = kImageAref.getExtents()[1]; int iZBound = kImageAref.getExtents()[2]; int iSliceSize = iXBound * iYBound; /* Half the sizes of the ModelImage volume, used to translate the * volume so that the center of the volume is at the origin: */ float fXHalf = (float) ((iXBound - 1) / 2.0); float fYHalf = (float) ((iYBound - 1) / 2.0); float fZHalf = (float) ((iZBound - 1) / 2.0); /* The following is used to calculate the "stretch" or "compression" * of the volume in 3Space. The ModelImage volume slices may be spaced differently than is represented by * indexing into the ModelImage volume array -- an implied spacing of 1,1,1 in each of the x,y,z directions. The * actual spacing may be different in any of the directions, and that spacing is important in the raytracing * step for producing a correctly rendered volume. The values must be reproduced here, since the rotation of the * volume is reversed before projecting the volume onto the 2D Sculpt Image for * sculpturing. */ float fXDelta = kImageAref.getFileInfo(0).getResolutions()[0]; float fYDelta = kImageAref.getFileInfo(0).getResolutions()[1]; float fZDelta = kImageAref.getFileInfo(0).getResolutions()[2]; if ((fXDelta <= 0.0f) || (fYDelta <= 0.0f) || (fZDelta <= 0.0f)) { fXDelta = 1.0f; fYDelta = 1.0f; fZDelta = 1.0f; } float fMinRes = fXDelta; if (fYDelta < fMinRes) { fMinRes = fYDelta; } if (fZDelta < fMinRes) { fMinRes = fZDelta; } fXDelta = fXDelta / fMinRes; fYDelta = fYDelta / fMinRes; fZDelta = fZDelta / fMinRes; /* Final Delta values used to correctly project the volume onto the 2D * Sculpt Image: */ float fInvXDelta = 1.0f / fXDelta; float fInvYDelta = 1.0f / fYDelta; float fInvZDelta = 1.0f / fZDelta; /* When the volume is sculpted, the removed voxels are set to the * lowest (zero-value) in the volume. This step calculates the minimum * value in the ModelImage volume data:*/ calculateMinMaxValues(kImageAref, kImageBref); /* * 2. Get the viewing transformations. * * Rotation is applied to the volume as a whole, and is performed in the raytracing step. The rotation matrix is * retrieved from the ViewJComponentRayCastRenderImage componentImageXY in the VolumeRenderer. * * Once the volume is raytraced, the 2D image is texture-mapped onto a 2D polygon and displayed in 3D world * coordinates. Translation and Zoom are preformed by translating the polygon in the x,y, or z-directions (for * zoom). These values are retrieved from the TransformGroup objTransXY in the VolumeRenderer. */ /* Get the componentImageXY from the VolumeRenderer. The * componentImageXY is used to access the raytracer which renders the * volume as well as the current rotation matrix for the volume: */ ViewJComponentRenderImage kRenderImageXY = null; kRenderImageXY = (ViewJComponentRenderImage) (m_kVolumeRenderer.getComponentImageXY()); if (kRenderImageXY == null) { return false; } /* Setup the inverse of the rotation matrix, to unrotate the * volume. Rotation is preformed in the raytracer, before raytracing the volume. The endresult of the raytraced * volume is a 2D texture, which is texture-mapped onto a 2D polygon in world space. Translation and Zoom * (scale) are performed as operations on * the 2D polygon and are separate from the raytracing step: */ Matrix3d kRotateMatrix = null; kRotateMatrix = new Matrix3d(kRenderImageXY.getRayTracerA().getAxis(0).x, kRenderImageXY.getRayTracerA().getAxis(0).y, kRenderImageXY.getRayTracerA().getAxis(0).z, kRenderImageXY.getRayTracerA().getAxis(1).x, kRenderImageXY.getRayTracerA().getAxis(1).y, kRenderImageXY.getRayTracerA().getAxis(1).z, kRenderImageXY.getRayTracerA().getAxis(2).x, kRenderImageXY.getRayTracerA().getAxis(2).y, kRenderImageXY.getRayTracerA().getAxis(2).z); kRotateMatrix.invert(); /* Zooming and Translating is done with the TransformGroup * objTransXY. Both are done after the volume is raytraced, and the operations are performed on a texture-mapped * polygon in world-space. matrixZoomTranslate is the final value used in this * function: */ TransformGroup kObjTransXY = null; kObjTransXY = m_kVolumeRenderer.getObjTransXY(); Transform3D kTransform = new Transform3D(); kObjTransXY.getTransform(kTransform); /* Get the zoom-translate matrix from the transform: */ Matrix4d kMatrixZoomTranslate = new Matrix4d(); kTransform.get(kMatrixZoomTranslate); /* * Zooming is done as a translation in Z, the value is an ofset from the original Z-position, which is stored in * the TransformGroup setup in the simple universe. This step gets that transform, and copies the final value * into matrixNormalizedCoords. */ TransformGroup kTransGroup = null; kTransGroup = m_kVolumeRenderer.getUniverse().getViewingPlatform().getViewPlatformTransform(); kTransGroup.getTransform(kTransform); Matrix4d kZoomMatrix = new Matrix4d(); kTransform.get(kZoomMatrix); /* float fZoom = kRenderImageXY.getRayTracerA().getZoom(); */ /* fImageScale represents the scaling that is done by the raytracer. */ float fImageScale = 1.0f; fImageScale = kRenderImageXY.getRayTracerA().getExtreme() / (float) (m_kVolumeRenderer.getImageComponent().getWidth() / 2.0); fImageScale *= (float) iCanvasWidth / (float) m_iOriginalWidth; /* fTexScale represents the scaling that occurs when the 2D image * produced by the raytracer is texture mapped onto the polygon. Since all textures are mapped onto a square of * size 2, larger textures * are "shrunk" to fit and smaller textures are "stretched" to fit. */ float fTexScale = (float) (iXBound) / 256.0f; /* fZoomScale represents zooming, which is done as a relative * translation of the polygon in Z, relative to the original translation, which is stored in kZoomMatrix.m23. * The amount of scale is proportional to the change in the z-distance to * the polygon. */ double fZoomScale = kZoomMatrix.m23 / (kZoomMatrix.m23 - kMatrixZoomTranslate.m23); ; /* Calculate the overall scale, so that the multiplies and divides are * done once per volume: */ float fScale = (float) (fImageScale * fZoomScale / fTexScale); /* Translation amounts are in image space: */ float fXTranslate = (float) (kMatrixZoomTranslate.m03 * fZoomScale * (float) iCanvasWidth / 2.0f); float fYTranslate = (float) (kMatrixZoomTranslate.m13 * fZoomScale * (float) iCanvasWidth / 2.0f); /* Perform the actual sculpting step: */ /* Input and output points for the rotation step */ Point3d kInput3 = new Point3d(); Point3d kOutput3 = new Point3d(); /* Step over every voxel in the volume, transforming the voxel into * image space: */ int iMod = iYBound / 10; for (int iY = 0; iY < iYBound; iY++) { int iIndexY = iY * iXBound; /* Update progress bar: */ if (((iY % iMod) == 0) || (iY == (iYBound - 1))) { if (iY == (iYBound - 1)) { m_kProgress.setValue(100); } else { m_kProgress.setValue(Math.round((float) (iY) / (iYBound - 1) * 100)); m_kProgress.update(m_kProgress.getGraphics()); } } for (int iX = 0; iX < iXBound; iX++) { for (int iZ = 0; iZ < iZBound; iZ++) { /* Translate the volume so that the origin is at the * center of the volume: */ if (m_bShear) { fInvXDelta = 1; fInvYDelta = 1; fInvZDelta = 1; } kInput3.x = (iX - fXHalf) / fInvXDelta; kInput3.y = (iY - fYHalf) / fInvYDelta; kInput3.z = (iZ - fZHalf) / fInvZDelta; /* Rotate the volume, according to the trackballl * rotation: */ kRotateMatrix.transform(kInput3, kOutput3); /* Scale: */ kOutput3.x *= fScale; kOutput3.y *= fScale; /* Translate */ if (!m_bShear) { kOutput3.x -= fXTranslate; } else { kOutput3.x += fXTranslate; } kOutput3.y -= fYTranslate; int iIndexZ = iZ * iSliceSize; int iIndex = iIndexZ + iIndexY + iX; /* Calculate the index into the 2D Sculpt Image: */ int iXIndex = 0; if (!m_bShear) { iXIndex = (int) ((m_iSculptImageWidth / 2) - kOutput3.x); } else { iXIndex = (int) (kOutput3.x + ((m_iSculptImageWidth) / 2)); } int iYIndex = (int) (kOutput3.y + ((m_iSculptImageHeight) / 2)); /* If the index is inside the sculpt image: */ if ((iXIndex >= 0) && (iXIndex < m_iSculptImageWidth) && (iYIndex >= 0) && (iYIndex < m_iSculptImageHeight)) { /* If the voxel index falls inside the sculpt * region: */ if (m_kSculptImageOpaque.getRGB(iXIndex, iYIndex) == m_iColorSculpt) { sculptImage(kImageAref, kImageBref, iIndex); bVolumeChanged = true; } } } } } kRotateMatrix = null; kMatrixZoomTranslate = null; kZoomMatrix = null; kInput3 = null; kOutput3 = null; return bVolumeChanged; } /** * clearSculpt: called by ViewJFrameVolumeView when the user presses the "Clear Ouline" button, clearing the sculpt * outline from the canvas image. The function disables sculpting and reactivates the mouse events for the * m_kVolumeRenderer. */ public void clearSculpt() { super.clearSculpt(); if (m_kVolumeRenderer != null) { m_kVolumeRenderer.setEnableMouseBehaviors(true); m_kVolumeRenderer.updateImage(); } } /** * Sets all variables to null, disposes, and garbage collects. * * @param flag DOCUMENT ME! */ public void disposeLocal(boolean flag) { m_kSculptImage = null; m_kSculptImageOpaque = null; m_aiImageA_backup = null; m_aiImageB_backup = null; m_aiXPoints = null; m_aiYPoints = null; m_kVolumeRenderer = null; kImageAref = null; kImageBref = null; } /** * enableSculpt: called by the ViewJFrameVolumeView object when the Draw Sculpt button is pressed. This function * deactivates the m_kVolumeRenderer's mouse response, so the mouse can be used to draw the sculpt outline. * * @param bEnabled DOCUMENT ME! */ public void enableSculpt(boolean bEnabled) { super.enableSculpt(bEnabled); if (m_kVolumeRenderer != null) { m_kVolumeRenderer.setEnableMouseBehaviors(!m_bSculptEnabled); backupImage(m_kVolumeRenderer.getImageA(), m_kVolumeRenderer.getImageB()); } } /** * Calls disposeLocal. * * @throws Throwable DOCUMENT ME! */ public void finalize() throws Throwable { this.disposeLocal(false); super.finalize(); } /** * Creates save dialog so that the image can be saved // This should be moved to imageModel.save(); * * @param options File-write options. * @param filterType only used if >= 0 */ public void save(FileWriteOptions options, int filterType) { String fileName = null; String extension = null; String directory = null; String suffix = null; int fileType = FileUtility.UNDEFINED; ModelImage img = null; ViewImageFileFilter vFilter = null; int i; if (kImageAref != null) { img = kImageAref; } else if (kImageBref != null) { img = kImageBref; } else { return; } if (options.isSaveAs()) { // save into its own subdirectory when on SaveAs. // (preferrably used in multi-file formats., ie DICOM) options.setSaveInSubdirectory(true); if (options.isSet()) { fileName = options.getFileName(); directory = options.getFileDirectory(); } else { try { ViewFileChooserBase fileChooser = new ViewFileChooserBase(true, true); JFileChooser chooser = fileChooser.getFileChooser(); // chooser.setName("Save image as"); if (ViewUserInterface.getReference().getDefaultDirectory() != null) { chooser.setCurrentDirectory(new File(ViewUserInterface.getReference().getDefaultDirectory())); } else { chooser.setCurrentDirectory(new File(System.getProperties().getProperty("user.dir"))); } if (filterType >= 0) { chooser.addChoosableFileFilter(new ViewImageFileFilter(filterType)); } else { chooser.addChoosableFileFilter(new ViewImageFileFilter(ViewImageFileFilter.ALL)); chooser.addChoosableFileFilter(new ViewImageFileFilter(ViewImageFileFilter.GEN)); chooser.addChoosableFileFilter(new ViewImageFileFilter(ViewImageFileFilter.TECH)); } int returnVal = chooser.showSaveDialog(m_kVolumeRenderer); if (returnVal == JFileChooser.APPROVE_OPTION) { fileName = chooser.getSelectedFile().getName(); if (filterType >= 0) { i = fileName.lastIndexOf('.'); if ((i > 0) && (i < (fileName.length() - 1))) { extension = fileName.substring(i + 1).toLowerCase(); vFilter = new ViewImageFileFilter(filterType); if (!vFilter.accept(extension)) { MipavUtil.displayError("Extension does not match filter type"); return; } } // if ( i > 0 && i < fileName.length() - 1 ) else if (i < 0) { switch (filterType) { case ViewImageFileFilter.AVI: fileName = fileName + ".avi"; break; case ViewImageFileFilter.VOI: fileName = fileName + ".voi"; break; case ViewImageFileFilter.FUNCT: fileName = fileName + ".fun"; break; case ViewImageFileFilter.LUT: fileName = fileName + ".lut"; break; case ViewImageFileFilter.PLOT: fileName = fileName + ".plt"; break; case ViewImageFileFilter.CLASS: fileName = fileName + ".class"; break; case ViewImageFileFilter.SCRIPT: fileName = fileName + ".sct"; break; case ViewImageFileFilter.SURFACE: fileName = fileName + ".sur"; break; case ViewImageFileFilter.FREESURFER: fileName = fileName + ".asc"; break; } } // else if (i < 0) } // if (filterType >= 0) directory = String.valueOf(chooser.getCurrentDirectory()) + File.separatorChar; ViewUserInterface.getReference().setDefaultDirectory(directory); } else { return; } } catch (OutOfMemoryError error) { MipavUtil.displayError("Out of memory: ViewJFrameBase.save"); Preferences.debug("Out of memory: ViewJFrameBase.save\n", Preferences.DEBUG_COMMS); return; } } } else { fileName = img.getFileInfo(0).getFileName(); directory = img.getFileInfo(0).getFileDirectory(); } /* * I'm not sure why this wasn't done before.... if we do a save-as we should also update the name of the file */ // if (options.isSaveAs()) { // img.setImageName(fileName.substring(0, fileName.length()-4)); // } options.setFileName(fileName); options.setFileDirectory(directory); if (!options.isSaveAs()) { if (img.getNDims() == 3) { options.setBeginSlice(0); options.setEndSlice(img.getExtents()[2] - 1); } else if (img.getNDims() == 4) { options.setBeginSlice(0); options.setEndSlice(img.getExtents()[2] - 1); options.setBeginTime(0); options.setEndTime(img.getExtents()[3] - 1); } } if (fileName != null) { FileIO fileIO = new FileIO(); fileIO.writeImage(img, options); } // if the SaveAllOnSave preference flag is set, then // save all the files associated with this image (VOIs, LUTs, etc.) if (Preferences.is(Preferences.PREF_SAVE_ALL_ON_SAVE)) { // Since the options may have changed the filename // and the directory --- get new fileName and directory // from options String fName = options.getFileName(); // if you use the name from img, then DICOM has funny names //String dirName = img.getFileInfo(0).getFileDirectory(); String filebase; int ind = fName.lastIndexOf("."); if (ind > 0) { filebase = fName.substring(0, fName.lastIndexOf(".")); } else { filebase = new String(fName); } if (options.getFileType() == FileUtility.DICOM) { int newIndex = filebase.length(); for (i = filebase.length() - 1; i >= 0; i--) { char myChar = filebase.charAt(i); if (Character.isDigit(myChar)) { newIndex = i; } else { break; } // as soon as something is NOT a digit, leave loop } if (newIndex > 0) { filebase = filebase.substring(0, newIndex); } } } // set the new fileName and directory in the fileInfo for the img -- so that it's // updated correctly in memory as well -- don't move this before the saveAllOnSave loop -- // that needs to look at the former settings! FileInfoBase[] fileInfo = img.getFileInfo(); if (suffix == null) { suffix = FileUtility.getExtension(fileName); fileType = FileUtility.getFileType(fileName, directory, false); } // now, get rid of any numbers at the end of the name (these // are part of the dicom file name, but we only want the 'base' // part of the name String baseName = new String(fileName); if (fileType == FileUtility.DICOM) { int index = fileName.lastIndexOf("."); if (index > 0) { baseName = fileName.substring(0, index); } int newIndex = baseName.length(); for (i = baseName.length() - 1; i >= 0; i--) { char myChar = baseName.charAt(i); if (Character.isDigit(myChar)) { newIndex = i; } else { break; } // as soon as something is NOT a digit, leave loop } if (newIndex > 0) { baseName = baseName.substring(0, newIndex); } fileName = new String(baseName + ".dcm"); if (!directory.endsWith(baseName)) { directory = new String(directory + baseName + File.separator); } } for (i = 0; i < fileInfo.length; i++) { fileInfo[i].setFileDirectory(directory); if (fileType == FileUtility.DICOM) { fileInfo[i].setFileName(baseName + (i + 1) + ".dcm"); } else { fileInfo[i].setFileName(fileName); } fileInfo[i].setFileSuffix(suffix); // fileInfo[i].setFileFormat (fileType); } } /** * undoSculpt: called by the ViewJFrameVolumeView object when the user presses the "Undo Sculpt" button. It resets * the volume data back to the original values, using the data stored in the m_aiImage_backup data members. */ public void undoSculpt() { /* The RendererImage component from the VolumeRenderer */ //ViewJComponentRenderImage kRenderImageXY = null; /* The original ModelImages */ ModelImage kImageAref = null; ModelImage kImageBref = null; if (m_kVolumeRenderer != null) { //kRenderImageXY = (ViewJComponentRenderImage) (m_kVolumeRenderer.getComponentImageXY()); kImageAref = m_kVolumeRenderer.getImageA(); kImageBref = m_kVolumeRenderer.getImageB(); } undoSculpt(kImageAref, kImageBref); } /** * Update the underlying volume and rerender. This function is called when the volume has changed. */ public void update() { m_bSculptEnabled = false; if (m_kVolumeRenderer == null) { return; } /* Get the componentImageXY from the VolumeRenderer. The * componentImageXY is used to access the raytracer which renders the * volume as well as the current rotation matrix for the volume: */ ViewJComponentRenderImage kRenderImageXY = null; kRenderImageXY = (ViewJComponentRenderImage) (m_kVolumeRenderer.getComponentImageXY()); if (kRenderImageXY == null) { return; } updateRenderedVolume(kRenderImageXY); } /** * This sequence causes the m_kVolumeRenderer to rerender the volume data, from the current ModelImage, not the data * that is stored in the Renderer. * * @param kRenderImageXY DOCUMENT ME! */ private void updateRenderedVolume(ViewJComponentRenderImage kRenderImageXY) { kRenderImageXY.getRayTracerA().reloadInputData(true); kRenderImageXY.show(0, null, null, true, true); m_kVolumeRenderer.getImageComponent().set(kRenderImageXY.getImage()); kRenderImageXY.getRayTracerA().reloadInputData(false); /* Reactivate mouse behavior in the m_kVolumeRenderer */ m_kVolumeRenderer.setEnableMouseBehaviors(true); } }
package jsoup.bean; public class LinkTypeData { private int id; private String linkHref; private String linkText; private String summary; private String content; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getLinkHref() { return linkHref; } public void setLinkHref(String linkHref) { this.linkHref = linkHref; } public String getLinkText() { return linkText; } public void setLinkText(String linkText) { this.linkText = linkText; } public String getSummary() { return summary; } public void setSummary(String summary) { this.summary = summary; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } }
package com.example.awesoman.owo2_comic.utils; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import java.lang.ref.SoftReference; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Created by Awesome on 2017/3/18. */ public class MyImageLoader { private static MyImageLoader imageLoader ; private MyImageLoader(){ } public static MyImageLoader getInstance(){ if(imageLoader==null) imageLoader = new MyImageLoader(); return imageLoader; } private List<String> comicPicPathList = new ArrayList<>(); private Map<String,SoftReference<Bitmap>> imageCache = new HashMap<String,SoftReference<Bitmap>>(); //加入单张Bitmap public void addBitmapToCache(String path){ BitmapFactory.Options options = new BitmapFactory.Options(); options.inSampleSize = 32; //强引用Bitmap对象 Bitmap bitmap = BitmapFactory.decodeFile(path,options); if(bitmap!=null) LogUtil.i("addBitmapToCache",bitmap.getByteCount()+""); //软引用Bitmap对象 SoftReference<Bitmap> softBitmap = new SoftReference<Bitmap>(bitmap); imageCache.put(path,softBitmap); } //取出单张Bitmap public Bitmap getBitmapByPath(String path){ //从缓存中取软引用的Bitmap对象 SoftReference<Bitmap> softBitmap =imageCache.get(path); if(softBitmap == null) { LogUtil.i("getBitmapByPath","null"); return null; } LogUtil.i("getBitmapByPath",path); Bitmap bitmap = softBitmap.get(); return bitmap; } //按照List<String> comicPicPathList 加入Bitmap public void addBitmapsToCache(List<String> paths){ for(String path:paths) { LogUtil.i("addBitmapsToCache",path); addBitmapToCache(path); } } }
import java.util.Scanner; public class LargestNumber{ public static void main(String[] args){ Scanner input = new Scanner(System.in); System.out.print("Enter the first number "); int firstNumber = input.nextInt(); System.out.print("Enter the second number "); int secondNumber = input.nextInt(); System.out.print("Enter the third number "); int thirdNumber = input.nextInt(); int largest = 0; if(firstNumber > secondNumber){ largest = firstNumber; } if (firstNumber > thirdNumber){ largest = firstNumber; } if (secondNumber > firstNumber){ largest = secondNumber; } if(secondNumber > thirdNumber){ largest = secondNumber; } if(thirdNumber > firstNumber){ largest = thirdNumber; } if(thirdNumber > secondNumber){ largest = thirdNumber; } System.out.println("The Largest number is " + largest); } }
package com.nisira.core.dao; import com.nisira.core.entity.*; import java.util.List; import android.database.sqlite.SQLiteDatabase; import com.nisira.core.database.DataBaseClass; import android.content.ContentValues; import android.database.Cursor; import com.nisira.core.util.ClaveMovil; import java.util.ArrayList; import java.util.LinkedList; import java.text.SimpleDateFormat; import java.util.Date; public class UnimedidaDao extends BaseDao<Unimedida> { public UnimedidaDao() { super(Unimedida.class); } public UnimedidaDao(boolean usaCnBase) throws Exception { super(Unimedida.class, usaCnBase); } public Boolean insert(Unimedida unimedida) { Boolean resultado = false; SQLiteDatabase mDb = SQLiteDatabase.openDatabase(DataBaseClass.PATH_DATABASE,null, SQLiteDatabase.NO_LOCALIZED_COLLATORS); try{ SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); ContentValues initialValues = new ContentValues(); initialValues.put("IDEMPRESA",unimedida.getIdempresa()); initialValues.put("IDMEDIDA",unimedida.getIdmedida()); initialValues.put("DESCRIPCION",unimedida.getDescripcion()); initialValues.put("NOMBRE_CORTO",unimedida.getNombre_corto()); initialValues.put("ESTADO",unimedida.getEstado()); initialValues.put("SINCRONIZA",unimedida.getSincroniza()); initialValues.put("FECHACREACION",dateFormat.format(unimedida.getFechacreacion() ) ); initialValues.put("CODIGO_SUNAT",unimedida.getCodigo_sunat()); initialValues.put("UNIDVIAJE",unimedida.getUnidviaje()); initialValues.put("UNIDTARIFA",unimedida.getUnidtarifa()); initialValues.put("IDREGISTRO_SUNAT",unimedida.getIdregistro_sunat()); initialValues.put("TIEMPO",unimedida.getTiempo()); initialValues.put("UNIDTIEMPO",unimedida.getUnidtiempo()); initialValues.put("CODIGO_ADUANA",unimedida.getCodigo_aduana()); initialValues.put("REDONDEO_DRAWBACK",unimedida.getRedondeo_drawback()); initialValues.put("TIPO_REDONDEO",unimedida.getTipo_redondeo()); initialValues.put("DECIMAL_REDONDEO",unimedida.getDecimal_redondeo()); initialValues.put("COMPANIA",unimedida.getCompania()); resultado = mDb.insert("UNIMEDIDA",null,initialValues)>0; } catch (Exception e) { }finally { mDb.close(); } return resultado; } public Boolean update(Unimedida unimedida,String where) { Boolean resultado = false; SQLiteDatabase mDb = SQLiteDatabase.openDatabase(DataBaseClass.PATH_DATABASE,null, SQLiteDatabase.NO_LOCALIZED_COLLATORS); try{ SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); ContentValues initialValues = new ContentValues(); initialValues.put("IDEMPRESA",unimedida.getIdempresa()) ; initialValues.put("IDMEDIDA",unimedida.getIdmedida()) ; initialValues.put("DESCRIPCION",unimedida.getDescripcion()) ; initialValues.put("NOMBRE_CORTO",unimedida.getNombre_corto()) ; initialValues.put("ESTADO",unimedida.getEstado()) ; initialValues.put("SINCRONIZA",unimedida.getSincroniza()) ; initialValues.put("FECHACREACION",dateFormat.format(unimedida.getFechacreacion() ) ) ; initialValues.put("CODIGO_SUNAT",unimedida.getCodigo_sunat()) ; initialValues.put("UNIDVIAJE",unimedida.getUnidviaje()) ; initialValues.put("UNIDTARIFA",unimedida.getUnidtarifa()) ; initialValues.put("IDREGISTRO_SUNAT",unimedida.getIdregistro_sunat()) ; initialValues.put("TIEMPO",unimedida.getTiempo()) ; initialValues.put("UNIDTIEMPO",unimedida.getUnidtiempo()) ; initialValues.put("CODIGO_ADUANA",unimedida.getCodigo_aduana()) ; initialValues.put("REDONDEO_DRAWBACK",unimedida.getRedondeo_drawback()) ; initialValues.put("TIPO_REDONDEO",unimedida.getTipo_redondeo()) ; initialValues.put("DECIMAL_REDONDEO",unimedida.getDecimal_redondeo()) ; initialValues.put("COMPANIA",unimedida.getCompania()) ; resultado = mDb.update("UNIMEDIDA",initialValues,where,null)>0; } catch (Exception e) { }finally { mDb.close(); } return resultado; } SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); public Boolean delete(String where) { Boolean resultado = false; SQLiteDatabase mDb = SQLiteDatabase.openDatabase(DataBaseClass.PATH_DATABASE,null, SQLiteDatabase.NO_LOCALIZED_COLLATORS); try{ resultado = mDb.delete("UNIMEDIDA",where,null)>0; } catch (Exception e) { }finally { mDb.close(); } return resultado; } public ArrayList<Unimedida> listar(String where,String order,Integer limit) { if(limit == null){ limit =0; } ArrayList<Unimedida> lista = new ArrayList<Unimedida>(); SQLiteDatabase mDb = SQLiteDatabase.openDatabase(DataBaseClass.PATH_DATABASE,null, SQLiteDatabase.NO_LOCALIZED_COLLATORS); try{ Cursor cur = mDb.query("UNIMEDIDA", new String[] { "IDEMPRESA" , "IDMEDIDA" , "DESCRIPCION" , "NOMBRE_CORTO" , "ESTADO" , "SINCRONIZA" , "FECHACREACION" , "CODIGO_SUNAT" , "UNIDVIAJE" , "UNIDTARIFA" , "IDREGISTRO_SUNAT" , "TIEMPO" , "UNIDTIEMPO" , "CODIGO_ADUANA" , "REDONDEO_DRAWBACK" , "TIPO_REDONDEO" , "DECIMAL_REDONDEO" , "COMPANIA" }, where, null, null, null, order); if (cur!=null){ cur.moveToFirst(); int i=0; while (cur.isAfterLast() == false) { int j=0; Unimedida unimedida = new Unimedida() ; unimedida.setIdempresa(cur.getString(j++)); unimedida.setIdmedida(cur.getString(j++)); unimedida.setDescripcion(cur.getString(j++)); unimedida.setNombre_corto(cur.getString(j++)); unimedida.setEstado(cur.getDouble(j++)); unimedida.setSincroniza(cur.getString(j++)); unimedida.setFechacreacion(dateFormat.parse(cur.getString(j++)) ); unimedida.setCodigo_sunat(cur.getString(j++)); unimedida.setUnidviaje(cur.getDouble(j++)); unimedida.setUnidtarifa(cur.getDouble(j++)); unimedida.setIdregistro_sunat(cur.getString(j++)); unimedida.setTiempo(cur.getString(j++)); unimedida.setUnidtiempo(cur.getDouble(j++)); unimedida.setCodigo_aduana(cur.getString(j++)); unimedida.setRedondeo_drawback(cur.getDouble(j++)); unimedida.setTipo_redondeo(cur.getString(j++)); unimedida.setDecimal_redondeo(cur.getDouble(j++)); unimedida.setCompania(cur.getInt(j++)); lista.add(unimedida); i++; if(i == limit){ break; } cur.moveToNext(); } cur.close(); } } catch (Exception e) { }finally { mDb.close(); } return lista; } }
package com.kamer.validationsinspringboot.javaxvalidationsconstraints; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; /** * Created on September, 2019 * * @author kamer */ @Getter @Setter @NoArgsConstructor @AllArgsConstructor public class CustomValidationEntity { private String email; private Long departmentId; public Boolean existManagerByDepartmentId(Long departmentId) { return false; } public Boolean existEmployeeWithMail(String email) { return true; } }
// File: TestSwing17.java (Module 9b) // // Author: Rahul Simha // Created: October 21, 1998 // // A simple quit button - using paintComponent. import java.awt.*; import javax.swing.*; // Extend JPanel to override paintComponent () class NewPanel extends JPanel { public NewPanel () { this.setBackground (Color.cyan); } public void paintComponent (Graphics g) { super.paintComponent (g); JButton b = new JButton ("QUIT"); // Add the button to the panel this.add (b); this.validate (); } } // End of NewPanel class NewFrame extends JFrame { // Constructor. public NewFrame (int width, int height) { // Set the title and other frame parameters. this.setTitle ("Button example"); this.setResizable (true); this.setSize (width, height); // Create and add the panel. NewPanel panel = new NewPanel (); this.getContentPane().add (panel); // Show the frame. this.setVisible (true); } } // End of class "NewFrame" public class TestSwing17 { public static void main (String[] argv) { NewFrame nf = new NewFrame (300, 200); } }
package com.oranjeclick.veganapp.models; import android.content.Context; import android.graphics.drawable.Drawable; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; public class MenuItems { @SerializedName("menu_id") @Expose private String menuId; @SerializedName("fk_restaurant_id") @Expose private String fk_restaurant_id; @SerializedName("name") @Expose private String name; @SerializedName("picture") @Expose private String picture; @SerializedName("ingredients") @Expose private String ingredients; public String getMenuId() { return menuId; } public void setMenuId(String menuId) { this.menuId = menuId; } public String getFk_restaurant_id() { return fk_restaurant_id; } public void setFk_restaurant_id(String fk_restaurant_id) { this.fk_restaurant_id = fk_restaurant_id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPicture() { return picture; } public void setPicture(String picture) { this.picture = picture; } public String getIngredients() { return ingredients; } public void setIngredients(String ingredients) { this.ingredients = ingredients; } public static MenuItems[] fromJsonArray(String jsonArray) { Gson gson = new GsonBuilder().serializeNulls().create(); MenuItems[] data = gson.fromJson(jsonArray, MenuItems[].class); return data; } public String getImage(String id) { id="http://www.oranje-tech.com/demo/v4vegon/api"+"/getMenuItems"+getPicture(); return id; } }
// Licensed to Cloudera, Inc. under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. Cloudera, Inc. licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.cloudera.director.client.latest.model; import java.util.Objects; import com.cloudera.director.client.latest.model.TimeSeriesCrossEntityMetadata; import com.google.gson.TypeAdapter; import com.google.gson.annotations.JsonAdapter; import com.google.gson.annotations.SerializedName; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.io.IOException; /** * TimeSeriesAggregateStatistics */ public class TimeSeriesAggregateStatistics { @SerializedName("sampleTime") private Long sampleTime = null; @SerializedName("sampleValue") private Double sampleValue = null; @SerializedName("count") private Long count = null; @SerializedName("min") private Double min = null; @SerializedName("minTime") private Long minTime = null; @SerializedName("max") private Double max = null; @SerializedName("maxTime") private Long maxTime = null; @SerializedName("mean") private Double mean = null; @SerializedName("stdDev") private Double stdDev = null; @SerializedName("crossEntityMetadata") private TimeSeriesCrossEntityMetadata crossEntityMetadata = null; public TimeSeriesAggregateStatistics() { // Do nothing } private TimeSeriesAggregateStatistics(TimeSeriesAggregateStatisticsBuilder builder) { this.sampleTime = builder.sampleTime; this.sampleValue = builder.sampleValue; this.count = builder.count; this.min = builder.min; this.minTime = builder.minTime; this.max = builder.max; this.maxTime = builder.maxTime; this.mean = builder.mean; this.stdDev = builder.stdDev; this.crossEntityMetadata = builder.crossEntityMetadata; } public static TimeSeriesAggregateStatisticsBuilder builder() { return new TimeSeriesAggregateStatisticsBuilder(); } public static class TimeSeriesAggregateStatisticsBuilder { private Long sampleTime = null; private Double sampleValue = null; private Long count = null; private Double min = null; private Long minTime = null; private Double max = null; private Long maxTime = null; private Double mean = null; private Double stdDev = null; private TimeSeriesCrossEntityMetadata crossEntityMetadata = null; public TimeSeriesAggregateStatisticsBuilder sampleTime(Long sampleTime) { this.sampleTime = sampleTime; return this; } public TimeSeriesAggregateStatisticsBuilder sampleValue(Double sampleValue) { this.sampleValue = sampleValue; return this; } public TimeSeriesAggregateStatisticsBuilder count(Long count) { this.count = count; return this; } public TimeSeriesAggregateStatisticsBuilder min(Double min) { this.min = min; return this; } public TimeSeriesAggregateStatisticsBuilder minTime(Long minTime) { this.minTime = minTime; return this; } public TimeSeriesAggregateStatisticsBuilder max(Double max) { this.max = max; return this; } public TimeSeriesAggregateStatisticsBuilder maxTime(Long maxTime) { this.maxTime = maxTime; return this; } public TimeSeriesAggregateStatisticsBuilder mean(Double mean) { this.mean = mean; return this; } public TimeSeriesAggregateStatisticsBuilder stdDev(Double stdDev) { this.stdDev = stdDev; return this; } public TimeSeriesAggregateStatisticsBuilder crossEntityMetadata(TimeSeriesCrossEntityMetadata crossEntityMetadata) { this.crossEntityMetadata = crossEntityMetadata; return this; } public TimeSeriesAggregateStatistics build() { return new TimeSeriesAggregateStatistics(this); } } public TimeSeriesAggregateStatisticsBuilder toBuilder() { return builder() .sampleTime(sampleTime) .sampleValue(sampleValue) .count(count) .min(min) .minTime(minTime) .max(max) .maxTime(maxTime) .mean(mean) .stdDev(stdDev) .crossEntityMetadata(crossEntityMetadata) ; } public TimeSeriesAggregateStatistics sampleTime(Long sampleTime) { this.sampleTime = sampleTime; return this; } /** * Sample time * @return sampleTime **/ @ApiModelProperty(required = true, value = "Sample time") public Long getSampleTime() { return sampleTime; } public void setSampleTime(Long sampleTime) { this.sampleTime = sampleTime; } public TimeSeriesAggregateStatistics sampleValue(Double sampleValue) { this.sampleValue = sampleValue; return this; } /** * Sample value * @return sampleValue **/ @ApiModelProperty(required = true, value = "Sample value") public Double getSampleValue() { return sampleValue; } public void setSampleValue(Double sampleValue) { this.sampleValue = sampleValue; } public TimeSeriesAggregateStatistics count(Long count) { this.count = count; return this; } /** * Count * @return count **/ @ApiModelProperty(required = true, value = "Count") public Long getCount() { return count; } public void setCount(Long count) { this.count = count; } public TimeSeriesAggregateStatistics min(Double min) { this.min = min; return this; } /** * Minimum value * @return min **/ @ApiModelProperty(required = true, value = "Minimum value") public Double getMin() { return min; } public void setMin(Double min) { this.min = min; } public TimeSeriesAggregateStatistics minTime(Long minTime) { this.minTime = minTime; return this; } /** * Timestamp for minimum value * @return minTime **/ @ApiModelProperty(required = true, value = "Timestamp for minimum value") public Long getMinTime() { return minTime; } public void setMinTime(Long minTime) { this.minTime = minTime; } public TimeSeriesAggregateStatistics max(Double max) { this.max = max; return this; } /** * Maximum value * @return max **/ @ApiModelProperty(required = true, value = "Maximum value") public Double getMax() { return max; } public void setMax(Double max) { this.max = max; } public TimeSeriesAggregateStatistics maxTime(Long maxTime) { this.maxTime = maxTime; return this; } /** * Timestamp for maximum value * @return maxTime **/ @ApiModelProperty(required = true, value = "Timestamp for maximum value") public Long getMaxTime() { return maxTime; } public void setMaxTime(Long maxTime) { this.maxTime = maxTime; } public TimeSeriesAggregateStatistics mean(Double mean) { this.mean = mean; return this; } /** * Mean * @return mean **/ @ApiModelProperty(required = true, value = "Mean") public Double getMean() { return mean; } public void setMean(Double mean) { this.mean = mean; } public TimeSeriesAggregateStatistics stdDev(Double stdDev) { this.stdDev = stdDev; return this; } /** * Standard deviation * @return stdDev **/ @ApiModelProperty(required = true, value = "Standard deviation") public Double getStdDev() { return stdDev; } public void setStdDev(Double stdDev) { this.stdDev = stdDev; } public TimeSeriesAggregateStatistics crossEntityMetadata(TimeSeriesCrossEntityMetadata crossEntityMetadata) { this.crossEntityMetadata = crossEntityMetadata; return this; } /** * Cross-entity metadata * @return crossEntityMetadata **/ @ApiModelProperty(value = "Cross-entity metadata") public TimeSeriesCrossEntityMetadata getCrossEntityMetadata() { return crossEntityMetadata; } public void setCrossEntityMetadata(TimeSeriesCrossEntityMetadata crossEntityMetadata) { this.crossEntityMetadata = crossEntityMetadata; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } TimeSeriesAggregateStatistics timeSeriesAggregateStatistics = (TimeSeriesAggregateStatistics) o; return Objects.equals(this.sampleTime, timeSeriesAggregateStatistics.sampleTime) && Objects.equals(this.sampleValue, timeSeriesAggregateStatistics.sampleValue) && Objects.equals(this.count, timeSeriesAggregateStatistics.count) && Objects.equals(this.min, timeSeriesAggregateStatistics.min) && Objects.equals(this.minTime, timeSeriesAggregateStatistics.minTime) && Objects.equals(this.max, timeSeriesAggregateStatistics.max) && Objects.equals(this.maxTime, timeSeriesAggregateStatistics.maxTime) && Objects.equals(this.mean, timeSeriesAggregateStatistics.mean) && Objects.equals(this.stdDev, timeSeriesAggregateStatistics.stdDev) && Objects.equals(this.crossEntityMetadata, timeSeriesAggregateStatistics.crossEntityMetadata); } @Override public int hashCode() { return Objects.hash(sampleTime, sampleValue, count, min, minTime, max, maxTime, mean, stdDev, crossEntityMetadata); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class TimeSeriesAggregateStatistics {\n"); sb.append(" sampleTime: ").append(toIndentedString(sampleTime)).append("\n"); sb.append(" sampleValue: ").append(toIndentedString(sampleValue)).append("\n"); sb.append(" count: ").append(toIndentedString(count)).append("\n"); sb.append(" min: ").append(toIndentedString(min)).append("\n"); sb.append(" minTime: ").append(toIndentedString(minTime)).append("\n"); sb.append(" max: ").append(toIndentedString(max)).append("\n"); sb.append(" maxTime: ").append(toIndentedString(maxTime)).append("\n"); sb.append(" mean: ").append(toIndentedString(mean)).append("\n"); sb.append(" stdDev: ").append(toIndentedString(stdDev)).append("\n"); sb.append(" crossEntityMetadata: ").append(toIndentedString(crossEntityMetadata)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
package com.rengu.operationsoanagementsuite.Entity; import com.fasterxml.jackson.annotation.JsonFormat; import org.springframework.format.annotation.DateTimeFormat; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.ManyToOne; import javax.persistence.Transient; import java.io.Serializable; import java.util.Date; import java.util.UUID; @Entity public class DeployLogDetailEntity implements Serializable { @Id private String id = UUID.randomUUID().toString(); @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8") private Date createTime = new Date(); private String destPath; @Transient private ComponentEntity componentEntity; @ManyToOne private ComponentDetailEntity componentDetailEntity; public DeployLogDetailEntity() { } public DeployLogDetailEntity(String destPath, ComponentEntity componentEntity, ComponentDetailEntity componentDetailEntity) { this.destPath = destPath; this.componentEntity = componentEntity; this.componentDetailEntity = componentDetailEntity; } public String getId() { return id; } public void setId(String id) { this.id = id; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public String getDestPath() { return destPath; } public void setDestPath(String destPath) { this.destPath = destPath; } public ComponentEntity getComponentEntity() { return componentEntity; } public void setComponentEntity(ComponentEntity componentEntity) { this.componentEntity = componentEntity; } public ComponentDetailEntity getComponentDetailEntity() { return componentDetailEntity; } public void setComponentDetailEntity(ComponentDetailEntity componentDetailEntity) { this.componentDetailEntity = componentDetailEntity; } }
package com.scf.module.security.matcher; import javax.servlet.http.HttpServletRequest; /** * 请求matcher * @author wubin * @date 2016年8月3日 上午10:21:20 * @version V1.1.0 */ public interface RequestMatcher { boolean matches(HttpServletRequest request); }
import java.util.Scanner; import java.lang.Math; class Lesson_1_Activity_One { public static void main(String[] args) { System.out.println(" Abram Gallegos"); } }
package com.gaoshin.onsalelocal.yipit.resource; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.QueryParam; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import com.gaoshin.onsalelocal.api.OfferDetailsList; import com.gaoshin.onsalelocal.yipit.service.YipitService; import common.util.web.GenericResponse; import common.util.web.JerseyBaseResource; @Path("/ws/yipit") @Component public class YipitResource extends JerseyBaseResource { @Autowired private YipitService yipitService; @Path("seed-divisions") @GET public GenericResponse seedDivisions() throws Exception { yipitService.seedDivisions(); return new GenericResponse(); } @Path("seed-sources") @GET public GenericResponse seedSources() throws Exception { yipitService.seedSources(); return new GenericResponse(); } @Path("seed-division-tasks") @GET public GenericResponse seedDivisionTasks() throws Exception { yipitService.seedDivisionTasks(); return new GenericResponse(); } @Path("seed-city-tasks") @GET public GenericResponse seedCityTasks() throws Exception { yipitService.seedCityTasks(); return new GenericResponse(); } @Path("deals-by-geo") @GET public OfferDetailsList searchOffer(@QueryParam("lat") float lat, @QueryParam("lng") float lng, @QueryParam("radius") int radius) throws Exception { return yipitService.searchOffer(lat, lng, radius); } }
package logicaJuego; public class Entidad { private int x; private int y; public Entidad() { } public Entidad(int x, int y) { this.x=x; this.y=y; } public int getX() { return x; } public int getY() { return y; } public boolean esBloque() { return false; } public boolean esBomba() { return false; } public boolean esBomberman() { return false; } }
package Interfaz; import Datos.Usuario; public class Principal extends Usuario{ public static void main (String [] args){ FichaUsuario miFicha; miFicha = new FichaUsuario(); miFicha.setVisible(true); Usuario miUsuario=new Usuario(); //Modificar miFicha.miUsuario = miUsuario; } }
package application.address.view; import java.util.Observable; import javafx.application.Platform; import javafx.beans.property.SimpleStringProperty; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.fxml.FXML; import javafx.scene.control.RadioButton; import javafx.scene.control.TableColumn; import javafx.scene.control.TableView; import javafx.scene.control.TextField; import javafx.scene.control.TableColumn.CellDataFeatures; import javafx.scene.control.cell.PropertyValueFactory; import javafx.stage.Stage; import org.controlsfx.dialog.Dialogs; import application.address.facade.Fachada; import application.address.model.User; import application.address.util.IteratorUser; import application.address.util.RepositoryUser; /** * Dialog to edit details of a person. * * @author Marco Jakob * */ public class IpEditDialogController { @FXML private TableView<User> userTable; @FXML private TableColumn<User, String> nameColumn; @FXML private TableColumn<User, String> IpColumn; @FXML private TextField postalCodeField; @FXML private TextField cityField; @FXML private TextField birthdayField; @FXML private TextField userName; @FXML private TextField localIp; @FXML private RadioButton onRadioButton; @FXML private RadioButton offRadioButton; private ObservableList<User> usersList = FXCollections .observableArrayList(); private Stage dialogStage; private boolean okClicked = false; private RepositoryUser usersRep; /** * Initializes the controller class. This method is automatically called * after the fxml file has been loaded. */ public IpEditDialogController() { // users = FXCollections.observableArrayList(); } @FXML private void initialize() { nameColumn.setCellValueFactory(cellData -> new SimpleStringProperty( cellData.getValue().getUsername())); IpColumn.setCellValueFactory((cellData -> new SimpleStringProperty( cellData.getValue().getIp()))); userTable.setItems(usersList); userTable .getSelectionModel() .selectedItemProperty() .addListener( (observable, oldValue, newValue) -> showUserDetails(newValue)); } public void enfiarParametro(RepositoryUser users, User eu, Stage stage){ this.userName.setText(eu.getUsername()); this.dialogStage = stage; this.localIp.setText(eu.getIp()); new Thread(new Runnable() { @Override public void run() { while(true){ Platform.runLater(new Runnable() { @Override public void run() { User selected = userTable.getSelectionModel().getSelectedItem(); usersList.setAll(users.getElements()); // System.out.println(users.getElements().size()); userTable.getSelectionModel().select(selected);; } }); try { Thread.sleep(200); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }).start(); } private Object showUserDetails(User newValue) { return null; } // private void thread(){ // new Thread(new Runnable() { // // @Override // public void run() { // while(true){ // IteratorUser iterator = (IteratorUser) usersRep.getIterator(); // while(iterator.hasNext()){ // users.add(iterator.next()); // } // try { // Thread.sleep(200); // } catch (InterruptedException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } // } // } // }).start(); // } /** * Sets the stage of this dialog. * * @param dialogStage */ public void setDialogStage(Stage dialogStage) { this.dialogStage = dialogStage; } /** * Sets the person to be edited in the dialog. * * @param person */ public void setPerson() { // firstNameField.setText(person.getFirstName()); // lastNameField.setText(person.getLastName()); // streetField.setText(person.getStreet()); // postalCodeField.setText(Integer.toString(person.getPostalCode())); // cityField.setText(person.getCity()); // birthdayField.setText(DateUtil.format(person.getBirthday())); // birthdayField.setPromptText("dd.mm.yyyy"); } /** * Returns true if the user clicked OK, false otherwise. * * @return */ public boolean isOkClicked() { return okClicked; } /** * Called when the user clicks ok. */ @FXML private void handleOk() { if (isInputValid()) { userTable.getSelectionModel().getSelectedItem(); okClicked = true; //fazer a conexăo p2p, tenho 2 usuários aqui. dialogStage.close(); } } /** * Called when the user clicks cancel. */ @FXML private void handleCancel() { dialogStage.close(); } /** * Validates the user input in the text fields. * * @return true if the input is valid */ private boolean isInputValid() { return false; } }
package com.yufei.sys.service.impl; import com.yufei.base.BaseDao; import com.yufei.base.BaseServiceImpl; import com.yufei.sys.dao.SysUserDao; import com.yufei.sys.model.SysUser; import com.yufei.sys.service.SysUserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @Service("sysUserService") @Transactional public class SysUserServiceImpl extends BaseServiceImpl<SysUser,String> implements SysUserService { @Autowired private SysUserDao sysUserDao; public BaseDao<SysUser, String> getEntityDao() { return this.sysUserDao; } }
// SPDX-License-Identifier: BSD-3-Clause package org.xbill.DNS; import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.IOException; import org.junit.jupiter.api.Test; import org.xbill.DNS.utils.base16; class SSHFPRecordTest { @Test void rdataFromString() throws IOException { Tokenizer t = new Tokenizer("2 1 CAFEBABE"); SSHFPRecord record = new SSHFPRecord(); record.rdataFromString(t, null); assertEquals(SSHFPRecord.Algorithm.DSS, record.getAlgorithm()); assertEquals(SSHFPRecord.Digest.SHA1, record.getDigestType()); assertArrayEquals(base16.fromString("CAFEBABE"), record.getFingerPrint()); } }
package com.pan.Concurrent.SynLockIn_1; public class MyThreadA2 extends Thread{ private Sub2 sub2; public MyThreadA2(Sub2 sub2) { this.sub2=sub2; } @Override public void run() { sub2.serviceMethod(); } }
package com.esum.ebms.v2.transaction; import java.util.ArrayList; import java.util.Enumeration; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import javax.management.MBeanServerConnection; import javax.management.MBeanServerInvocationHandler; import javax.management.MalformedObjectNameException; import javax.management.ObjectName; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.esum.ebms.v2.service.ServiceContext; import com.esum.ebms.v2.storage.RoutingInfoRecord; import com.esum.ebms.v2.storage.RoutingManager; import com.esum.framework.core.management.ManagementConstants; import com.esum.framework.core.management.ManagementException; import com.esum.framework.core.management.admin.XtrusAdminFactory; import com.esum.framework.core.management.mbean.queue.QueueControlMBean; import com.esum.framework.core.queue.JmsMessageHandler; import com.esum.framework.core.queue.QueueHandlerFactory; import com.esum.framework.jmx.MBeanQueryCreator; /** * Interface에 대한 메모리상의 Queue를 생성하여, ThreadPool로 관리하는 클래스 * * Copyright(c) eSum Technologies, Inc. All rights reserved. */ public class InterfaceTransactionGroup extends TransactionGroup { private Logger log = LoggerFactory.getLogger(InterfaceTransactionGroup.class); /** * CPA별 사용하는 채널에 대한 정보를 담고 있다. * CPA의 Queue별로 여러개의 Consumer가 등록될 수 있다. */ private Map<String, List<JmsMessageHandler>> transactionQueueMap; /** * CPA별로 Outbound를 처리하는 Transaction 목록 */ private List<Transaction> transactionList; private int consumerSize; private Object lock = new Object(); private ServiceContext serviceContext; /** * INTERFACE Transaction에 대해 설정한다. * * Adapter가 등록되었을때 CPA를 DB에서 검색하여 해당되는 CPA별로 queue를 하나씩 설정한다. <br> * 또한 각 queue에 대해 transaction을 처리하는 tsize만큼 생성된다. */ public InterfaceTransactionGroup(String nodeId, String groupName, int consumerSize) throws TransactionException { super(nodeId, groupName); if(transactionQueueMap == null) transactionQueueMap = new HashMap<String, List<JmsMessageHandler>>(); this.consumerSize = consumerSize; transactionList = new ArrayList<Transaction>(); if(log.isDebugEnabled()) log.debug(traceId+"OutboundTransactionGroup created."); } /** * 등록된 CPA들에 대한 Transaction들을 시작한다. */ public void initService(ServiceContext context) { this.serviceContext = context; Enumeration<RoutingInfoRecord> iterator = RoutingManager.getInstance().getRoutingInfoEnumeration(); if(iterator==null) return; while(iterator.hasMoreElements()) { RoutingInfoRecord info = iterator.nextElement(); String cpaId = info.getCpaId(); if(transactionQueueMap.containsKey(cpaId)) continue; try { startTransaction(cpaId); } catch (TransactionException ex) { log.error(traceId+"Transaction starting failed.", ex); } } } /** * 해당되는 CPA에 대한 TransactionQueue를 리턴한다. * @param cpaId id of CPA. * @return */ public JmsMessageHandler getQueueHandler(String cpaId) { if(!transactionQueueMap.containsKey(cpaId)) { synchronized(lock) { try { startTransaction(cpaId); } catch (Exception e) { log.error(traceId+"'"+cpaId+"' transaction start failed.", e); } } } return transactionQueueMap.get(cpaId).get(0); } /** * 특정 TransactionQueue와 cpaid에 대한 transaction processor(OutboundTransaction)을 start한다. * @throws TransactionException */ public void startTransaction(String cpaId) throws TransactionException { log.info(traceId+"Transaction Queue - cpaId("+cpaId+"), consumers("+this.consumerSize+")"); String channelName = "EBMS_OUT_"+cpaId; try { initChannel(channelName); List<JmsMessageHandler> cpaHandlers = new ArrayList<JmsMessageHandler>(); for(int i=0; i<consumerSize; i++) { String txId = cpaId+"-"+i; JmsMessageHandler queueHandler = QueueHandlerFactory.getInstance(channelName); cpaHandlers.add(queueHandler); InterfaceTransaction t = new InterfaceTransaction(this, txId); queueHandler.setMessageListener(t); transactionList.add(t); log.info(traceId+"New Outbound Transaction("+txId+") started."); } transactionQueueMap.put(cpaId, cpaHandlers); } catch (Exception e) { throw new TransactionException(TransactionException.ERROR_OUTBOUND_TRANSACTION_START, "startTransaction()", e); } } /** * Closing the transaction with a specific transaction name. */ public void close(String cpaId) { if(log.isDebugEnabled()) log.debug(traceId+"'"+cpaId+"' transaction closing."); List<JmsMessageHandler> handlers = this.transactionQueueMap.get(cpaId); for(int i=0;i<handlers.size();i++) { JmsMessageHandler handler = handlers.get(i); if(handler!=null) { String txId = cpaId+"-"+i; int removedCnt = removeTransaction(nodeId, txId); log.info("[" + getName() + "] "+removedCnt+" Transaction removed by '"+txId+"' CPA ID."); handler.close(); } } this.transactionQueueMap.remove(cpaId); handlers = null; log.info(traceId+"'"+cpaId+"' All Outbound transaction closed."); } private boolean initChannel(final String channelName) throws TransactionException { if(log.isDebugEnabled()) log.debug("Initialize '"+channelName+"' channel."); try { return XtrusAdminFactory.currentAdmin().query(new MBeanQueryCreator<Boolean>() { @Override public Boolean executeQuery(MBeanServerConnection connection) throws ManagementException, MalformedObjectNameException { ObjectName objectName = ObjectName.getInstance(ManagementConstants.OBJECT_NAME_QUEUE_CONTROL); QueueControlMBean queueControlMBean = MBeanServerInvocationHandler.newProxyInstance(connection, objectName, QueueControlMBean.class, true); queueControlMBean.createQueue(channelName, true); return true; } }); } catch (ManagementException e) { throw new TransactionException(TransactionException.ERROR_QUEUE_CREATION, "initChannel()", e); } } /** * TransactionGroup 내에서 실행 중인 트랜잭션을 중지한다. */ public void closeAll() { List<Transaction> txList = getTransactionList(); if (txList != null) { Iterator<Transaction> i = txList.iterator(); while(i.hasNext()) { Transaction t = i.next(); t.close(); } txList.clear(); } if(this.transactionQueueMap!=null) { Iterator<String> i = this.transactionQueueMap.keySet().iterator(); while(i.hasNext()) { String cpaId = i.next(); List<JmsMessageHandler> handlers = this.transactionQueueMap.get(cpaId); for(JmsMessageHandler h : handlers) { h.close(); } handlers = null; } this.transactionQueueMap.clear(); } log.info(traceId+"All Outbound Transaction closed."); } public Map<String, List<JmsMessageHandler>> getTransactionQueueMap() { return transactionQueueMap; } @Override public List<Transaction> getTransactionList() { return transactionList; } @Override public int getTransactionSize() { return consumerSize; } @Override public String getTransactionType() { return TransactionGroup.ADAPTER_TRANSACTION_TYPE; } }
package com.jgw.supercodeplatform.project.zaoyangpeach.controller; import com.jgw.supercodeplatform.project.zaoyangpeach.service.CodeService; import com.jgw.supercodeplatform.trace.common.model.RestResult; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import springfox.documentation.annotations.ApiIgnore; import java.util.Map; @RestController @RequestMapping("/trace/zaoyangpeach/coderelation") public class CodeRelationController { @Autowired private CodeService codeService; @GetMapping(value = "/record") public RestResult listRelationRecord(@ApiIgnore @RequestParam Map<String, Object> paramsMap) throws Exception{ return new RestResult(200, "success", codeService.listRelationRecord(paramsMap)); } }
package com.shop.serviceImpl; import com.shop.mapper.GoodsMapper; import com.shop.model.Goods; import com.shop.service.GoodsService; import com.shop.util.FileUtils; import com.shop.vo.GoodsVo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.multipart.MultipartFile; import javax.servlet.http.HttpServletRequest; import java.util.ArrayList; import java.util.List; @Service public class GoodsServiceImpl implements GoodsService { @Autowired private GoodsMapper goodsMapper; /** * 查询所有商品信息 * @return */ @Override public List<GoodsVo> listAllGoods() { List<GoodsVo> goodsVos = goodsMapper.listAllGoods(); return goodsVos; } /** * 查询类别下的所有商品 * @param cateId 类别id * @return */ @Override public List<GoodsVo> listByCate(Long cateId) { List<GoodsVo> goodsVos = goodsMapper.listByCate(cateId); return goodsVos; } /** * 通过关键字模糊查询商品 * @param key 关键字 * @return */ @Override public List<GoodsVo> getLike(String key) { List<GoodsVo> like = goodsMapper.getLike(key); return like; } /** * 根据商品id查找商品 * @param goodsId * @return */ @Override public GoodsVo getById(Long goodsId) { GoodsVo goodsVo = goodsMapper.getById(goodsId); return goodsVo; } /** * 商品新增 * @param goods * @return */ @Override @Transactional public boolean putGoods(Goods goods, MultipartFile file, HttpServletRequest request) { String newName = FileUtils.getNewName(file); goods.setGoodsPic(newName); boolean upload = FileUtils.upload(file, newName, request); Integer integer = goodsMapper.putGoods(goods); return integer==1; } /** * 商品删除 * @param id * @return */ @Override public Integer deleteGoods(Long id) { Integer integer = goodsMapper.deleteGoods(id); return integer; } @Override public List<GoodsVo> get4(){ return this.getHolder(); } private List<GoodsVo> getHolder(){ List<GoodsVo> goodsVos = this.listAllGoods(); List<GoodsVo> res = new ArrayList<>(); int size = goodsVos.size(); if(size<=4){ return goodsVos; }else { res.add(goodsVos.get((size>>1)+1)); res.add(goodsVos.get(size>>1)); res.add(goodsVos.get((size>>1)-1)); res.add(goodsVos.get((size>>1)+2)); } return res; } }
package com.soldevelo.vmi.config.acs.managers; import com.soldevelo.vmi.config.acs.model.Section; import java.util.HashMap; import java.util.Map; public abstract class SectionManager { private Map<String, Section> templates = new HashMap<String, Section>(); public Map<String, Section> getTemplates() { return templates; } protected void templateInheritance(Section section) { String parentName = section.getParentName(); Section template = getParent(parentName); if (template != null) { section.inherit(template); } } protected Section getParent(String name) { Section parent = templates.get(name); // inheritance amongst templates if (parent != null) { Section grandParent = getParent(parent.getParentName()); if (grandParent != null) { parent.inherit(grandParent); } } return parent; } }
package edu.banking.rhodes.maddux; import edu.jenks.dist.banking.AbstractCheckingAccount; import edu.jenks.dist.banking.Account; public class CheckingAccount extends AbstractCheckingAccount { public CheckingAccount() { } public CheckingAccount(double balance, double accountInterestAPR) { setAccountInterestAPR(accountInterestAPR); setBalance(balance); } public static void main(String[] args) { CheckingAccount ca = new CheckingAccount(25.0, 0.05); SavingsAccount sa = new SavingsAccount(500.00, 0.05); ca.setLinkedSavingsAccount(sa); ca.setOverdraftProtected(true); ca.setOverdraftMax(500.00); System.out.println("Balance before withdraw: " + ca.getBalance()); System.out.println(ca.withdraw(600.00)); System.out.println("Balance after withdraw: " + ca.getBalance()); System.out.println(ca.getNumberOverdrafts()); System.out.println(ca.getLinkedSavingsAccount().getBalance()); } public void payInterest(int days) { double interestAmt = getBalance() * (Math.exp( (getAccountInterestAPR()/100) * (days / (double) DAYS_IN_A_YEAR))); setBalance(interestAmt); } public double transfer(Account destination, double amount) { if(this.getBalance() < amount) { return 0.0; } else { destination.setBalance(destination.getBalance() + amount); if(getLinkedSavingsAccount() != null) { getLinkedSavingsAccount().setNumTransactions(getLinkedSavingsAccount().getNumTransactions() + 1); } this.setBalance(this.getBalance() - amount); return amount; } } public double withdraw(double requestedWithdrawal) { double acctBalance = getBalance(); double savingsBalance = 0; if (getLinkedSavingsAccount() != null) { System.out.println("Here1"); if (getLinkedSavingsAccount().getNumTransactions() < getLinkedSavingsAccount().getMaxMonthlyTransactions()) { System.out.println("Here2"); savingsBalance = getLinkedSavingsAccount().getBalance(); } } double max = acctBalance + savingsBalance; if (isOverdraftProtected()) { max += getOverdraftMax(); } if (requestedWithdrawal <= acctBalance) { System.out.println("Here3"); setBalance(acctBalance - requestedWithdrawal); return requestedWithdrawal; } else if (requestedWithdrawal > acctBalance && requestedWithdrawal <= (acctBalance + savingsBalance)) { System.out.println("Here4"); setBalance(0); getLinkedSavingsAccount().setBalance(savingsBalance - (requestedWithdrawal - acctBalance)); getLinkedSavingsAccount().setNumTransactions(getLinkedSavingsAccount().getNumTransactions() + 1); return requestedWithdrawal; } else if (requestedWithdrawal > (acctBalance + savingsBalance) && requestedWithdrawal <= max) { System.out.println("Here5"); if (isOverdraftProtected()) { double cover1 = requestedWithdrawal - acctBalance; setNumberOverdrafts(getNumberOverdrafts() + 1); setBalance(0); if(getLinkedSavingsAccount() != null) { getLinkedSavingsAccount().setNumTransactions(getLinkedSavingsAccount().getNumTransactions() + 1); getLinkedSavingsAccount().setBalance(0); } if(getLinkedSavingsAccount() != null) { cover1 -= savingsBalance; } setBalance(cover1 * -1); return requestedWithdrawal; } } return 0; } }
package com.online.web.spring.controller; import javax.servlet.http.HttpServletRequest; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import com.online.web.spring.companydao.CompanyDAO; import com.online.web.spring.model.Company; @Controller public class Companycontroller { int result = 0; boolean flag = false; @RequestMapping("/newUser.do") public String newUser() { System.out.println("newUser...."); return "newUser.jsp"; } @RequestMapping("/homePage.do") public String searchUser(HttpServletRequest request) { System.out.println("Searching User......."); Company cuser = new Company(); CompanyDAO cdao = new CompanyDAO(); cuser.setUser(request.getParameter("user")); cuser.setPassword(request.getParameter("password")); flag = cdao.searchUSer(cuser); if (flag) return "homePage.jsp"; else return "index.jsp"; } @RequestMapping("/creatUser.do") public String createUser(HttpServletRequest request) { System.out.println("CreateUser.........."); Company cuser = new Company(); CompanyDAO cdao = new CompanyDAO(); cuser.setUser(request.getParameter("user")); cuser.setPassword(request.getParameter("password")); result = cdao.creatUser(cuser); if (result > 0) { return "index.jsp"; } return "newUser.jsp"; } }
package com.example.demo; import com.example.demo.entity.Category; import com.example.demo.entity.Product; import com.example.demo.entity.Stock; import com.example.demo.repository.CategoryRepository; import com.example.demo.repository.ProductRepository; import com.example.demo.repository.StockRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.ApplicationArguments; import org.springframework.boot.ApplicationRunner; import org.springframework.stereotype.Component; import java.math.BigDecimal; @Component public class DataSeeder implements ApplicationRunner { @Autowired private ProductRepository productRepository; @Autowired private StockRepository stockRepository; @Autowired private CategoryRepository categoryRepository; @Override public void run(ApplicationArguments args) throws Exception { Category rootCategory = addCategory(null, "root"); Category category = addCategory(rootCategory, "category1"); Product product = addProduct(category); Stock stock = addStock(product); } private Category addCategory(Category parent, String name) { Category category = new Category(); category.setName(name); category.setParent(parent); return categoryRepository.save(category); } private Stock addStock(Product product) { Stock stock = new Stock(); stock.setProduct(product); stock.setQty(100L); return stockRepository.save(stock); } private Product addProduct(Category category) { Product product = new Product(); product.setBrand("brand1"); product.setName("name1"); product.setPrice(BigDecimal.valueOf(130)); product.setCategory(category); return productRepository.save(product); } }
/* * 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 pl.polsl.aei.io.turnieje.model.repository; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.Statement; import java.util.HashSet; import java.util.Set; import pl.polsl.aei.io.turnieje.model.datamodel.Discipline; /** * Realization of repository interface for disciplines * @author Piotr Uhl */ public class DisciplineRepository implements IDisciplineRepository { private final DBInterface dbInterface; DisciplineRepository(DBInterface dbInterface) { this.dbInterface = dbInterface; } @Override public Discipline add(String name) { try { PreparedStatement statement = dbInterface.createPreparedStatement("INSERT INTO Disciplines(discName) VALUES (?)", PreparedStatement.RETURN_GENERATED_KEYS); statement.setString(1, name); statement.execute(); ResultSet rs = statement.getGeneratedKeys(); if (rs.next()) { return new Discipline(rs.getInt(1), name); } } catch (Exception exc) { throw new RuntimeException(exc); } return null; } @Override public Set<Discipline> getAll() { try { Statement statement = dbInterface.createStatement(); ResultSet rs = statement.executeQuery("SELECT * FROM Disciplines"); Set<Discipline> set = new HashSet<>(); while (rs.next()) { Discipline discipline = new Discipline(rs.getInt("discId"), rs.getString("discName")); set.add(discipline); } return set; } catch (Exception exc) { throw new RuntimeException(exc); } } @Override public Discipline getByName(String name) { try { PreparedStatement statement = dbInterface.createPreparedStatement("SELECT * FROM Disciplines WHERE discName=?"); statement.setString(1, name); ResultSet rs = statement.executeQuery(); if (rs.next()) { return new Discipline(rs.getInt("discId"), rs.getString("discName")); } return null; } catch (Exception exc) { throw new RuntimeException(exc); } } @Override public boolean rename(Discipline discipline, String newName) { try { PreparedStatement statement = dbInterface.createPreparedStatement("UPDATE Disciplines SET discName=? WHERE discId=?"); statement.setString(1, newName); statement.setInt(2, discipline.id); return statement.executeUpdate() > 0; } catch (Exception exc) { throw new RuntimeException(exc); } } @Override public boolean rename(String oldName, String newName) { try { PreparedStatement statement = dbInterface.createPreparedStatement("UPDATE Disciplines SET discName=? WHERE discName=?"); statement.setString(1, newName); statement.setString(2, oldName); return statement.executeUpdate() > 0; } catch (Exception exc) { throw new RuntimeException(exc); } } }
import org.openqa.selenium.support.PageFactory; import org.testng.Assert; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import pages.OnlineCinemaPage; import java.util.List; public class GenreFieldTest extends TestBase { @DataProvider(name = "genreAndTab") public static Object[][] genreAndTab() { return new Object[][] { {"Сериалы", "Фэнтези"}, {"Фильмы", "Боевик"}, {"Мультфильмы", "Комедия"} }; } @Test(dataProvider = "genreAndTab") public void SetGenreTest(String movieTypeTab, String genre) { driver.get("https://afisha.tut.by/online-cinema/"); OnlineCinemaPage onlineCinemaPage = PageFactory.initElements(driver, OnlineCinemaPage.class); onlineCinemaPage.setMovieTypeTabAndGenre(movieTypeTab, genre); //Get List of Genres and Year text that displayed under movie's images List<String> moviesGenresYearList = onlineCinemaPage.getMoviesGenresAndYearList(); for (String e : moviesGenresYearList) { Assert.assertTrue(e.contains(genre), "Check Movies Genre is \"" + genre + "\" on \""+movieTypeTab+"\"tab"); } } }
package f.star.iota.milk.ui.xiuren.xiu; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.ViewGroup; import f.star.iota.milk.R; import f.star.iota.milk.base.BaseAdapter; public class XiuRenAdapter extends BaseAdapter<XiuRenViewHolder, XiuRenBean> { @Override public XiuRenViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { return new XiuRenViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_description, parent, false)); } @Override public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) { ((XiuRenViewHolder) holder).bindView(mBeans.get(position)); } }
package vo; public class Repository { private int rep_id; private String rep_name; private String rep_uri; public Repository () {} public Repository(int rep_id, String rep_name, String rep_uri) { super(); this.rep_id = rep_id; this.rep_name = rep_name; this.rep_uri = rep_uri; } public int getRep_id() { return rep_id; } public void setRep_id(int rep_id) { this.rep_id = rep_id; } public String getRep_name() { return rep_name; } public void setRep_name(String rep_name) { this.rep_name = rep_name; } public String getRep_uri() { return rep_uri; } public void setRep_uri(String rep_uri) { this.rep_uri = rep_uri; } @Override public String toString() { return "Repository [rep_id=" + rep_id + ", rep_name=" + rep_name + ", rep_uri=" + rep_uri + "]"; } }
package com.qa.rest; import static org.hamcrest.Matchers.containsString; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.when; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import java.util.ArrayList; import java.util.List; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.http.MediaType; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.MvcResult; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.web.client.RestTemplate; import com.fasterxml.jackson.databind.ObjectMapper; import com.qa.controller.AccountController; import com.qa.entity.Account; import com.qa.service.AccountService; @RunWith(SpringRunner.class) @WebMvcTest(AccountController.class) @AutoConfigureMockMvc public class WebMockTest { @Autowired private MockMvc mockMvc; @MockBean private AccountService service; @MockBean private RestTemplate restTemplate; private static final Account MOCK_ACCOUNT_1 = new Account(1L, "first", "last", "abc123", "prize"); private static final Account MOCK_ACCOUNT_2 = new Account(2L, "first2", "last2", "abc123", "prize"); @Test public void getAllTest() throws Exception { List<Account> MOCK_LIST = new ArrayList<>(); MOCK_LIST.add(MOCK_ACCOUNT_1); MOCK_LIST.add(MOCK_ACCOUNT_2); when(service.getAllAccounts()).thenReturn(MOCK_LIST); mockMvc.perform(get("/allAccounts")).andExpect(content().string(containsString(""))); } private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper(); @Test public void addAccountTest() throws Exception { String postValue = OBJECT_MAPPER.writeValueAsString(MOCK_ACCOUNT_1); // when(service.createCocktail(MOCK_COCKTAIL_1)).thenReturn(MOCK_COCKTAIL_1); doReturn(MOCK_ACCOUNT_1).when(service).addAccount(MOCK_ACCOUNT_1); mockMvc.perform(MockMvcRequestBuilders .post("/addAccount") .contentType(MediaType.APPLICATION_JSON).content(postValue)) .andExpect(status().isCreated()) .andDo(print()) .andReturn(); } }
package com.codigo.smartstore.sdk.core.checksum.crc; import java.util.zip.Checksum; import org.apache.log4j.Logger; /* * Known CRC algorihtms */ // http://www.sunshine2k.de/coding/javascript/crc/crc_js.html // TODO: zrobić to na podstawie template metod albo parametrów public abstract class AbstractCrc implements Checksum { private static final Logger log = Logger.getLogger(AbstractCrc.class); protected int[] lookupTable; // ----------------------------------------------------------------------------------------------------------------- protected ICrcParameter crcParameters; // ----------------------------------------------------------------------------------------------------------------- protected int value; // ----------------------------------------------------------------------------------------------------------------- public AbstractCrc(final ICrcParametrizable parametrized) { this.lookupTable = new int[256]; this.crcParameters = parametrized.getParameters(); this.buildLookupTable(); } public final int[] getLookupTable() { return this.lookupTable; // return new Iterator<Integer>() { // // private int index = 0; // // @Override // public boolean hasNext() { // return this.index < AbstractCrc.this.lookupTable.length; // } // // @Override // public Integer next() { // return AbstractCrc.this.lookupTable[this.index++]; // } // }; } // ----------------------------------------------------------------------------------------------------------------- private void buildLookupTable() { final int msbMask = 0x01 << (this.crcParameters.getLength() - 1), intShift = this.evalBitShift(); for (int divident = 0; divident < 256; divident++) { int currByte = (divident << (this.crcParameters.getLength() - 8)) & intShift; for (int bit = 0; bit < 8; bit++) if (0 != (currByte & msbMask)) { currByte <<= 1; currByte ^= this.crcParameters.getPolynomial(); } else currByte <<= 1; this.lookupTable[divident] = currByte & intShift; final String result = String.format("0x%08x", this.lookupTable[divident]) .toUpperCase(); if (0 == (divident % 8)) log.info('\n'); log.info(result + " "); } log.info('\n'); } // ----------------------------------------------------------------------------------------------------------------- @Override public void update(final byte[] buffer) { this.update(buffer, 0, buffer.length); } // ----------------------------------------------------------------------------------------------------------------- @Override public void update(final int b) { this.update(new byte[] { (byte) b }, 0, 1); } // ----------------------------------------------------------------------------------------------------------------- @Override public void update(final byte[] arg0, final int arg1, final int arg2) { int crc = this.crcParameters.getInitialValue(); for (final byte element : arg0) { int curByte = element & 0xFF; if (this.crcParameters.isInputReflected()) curByte = (int) AbstractCrc.reverseBits(curByte, this.crcParameters.getLength()); /* * update the MSB of crc value with next input byte */ crc = (crc ^ (curByte << (this.crcParameters.getLength() - 8))) & this.evalBitShift(); /* * this MSB byte value is the index into the lookup table */ final int pos = (crc >> (this.crcParameters.getLength() - 8)) & 0xFF; /* * shift out this index */ crc = (crc << 8) & this.evalBitShift(); /* * XOR-in remainder from lookup table using the calculated index */ crc = (crc ^ this.lookupTable[pos]) & this.evalBitShift(); } this.value = (crc ^ this.crcParameters.getFinalXorValue()) & this.evalBitShift(); } // ----------------------------------------------------------------------------------------------------------------- @Override public long getValue() { return this.value; } // ----------------------------------------------------------------------------------------------------------------- @Override public void reset() { this.value = this.crcParameters.getInitialValue(); } // ----------------------------------------------------------------------------------------------------------------- private int evalBitShift() { // TODO: dodać jako element klasy tą maskę switch (this.crcParameters.getLength()) { case 0x8: return 0xFF; case 0x10: return 0xFFFF; case 0x20: return 0xFFFFFFFF; default: return 0x00; } } /** * Metoda wykonuje zamianę pozycji poszczególnych bitów w wartości * <code>value</code>. Zamiana jest wykonywana na sposób "odbicia lustrzanego". * Najstarsze pozycje bitów są zamieniane z najmłodszymi pozycjami bitów. Patrz * na przykład poniżej: <code>1011(2)->11(10) => 1101(2)->13(10)</code> * * @param value Liczba dla której mamy wykonać odbicie lustrzane bitów * @param bitCount Ilość bitów podlegająca zamianie * @return Wartość numeryczna */ // TODO: przenieść funkcję do dykowanej klasy obsługi np. NumberRoutines private static long reverseBits(final long value, final int bitCount) { long reflection = 0L; for (int bitNumber = 0; bitNumber < bitCount; ++bitNumber) if (0L != (value & (1L << bitNumber))) reflection |= (1L << (bitCount - 1 - bitNumber)) & 0xFF; return reflection; } /** * Metoda wykonuje transformację wartości liczbowej na jej reprezentacje w * systemie dwójkowym * * @param number Wartość liczbowa * @param numberOfGroups Ilość grup reprezentacji wartości binarnej * @return Wartość liczbowa przedstawiona w systemie binarnym (dwójkowym) */ public static String longToBinary(final long number, final int numberOfGroups) { final StringBuilder bitsOutput = new StringBuilder(); final int sizeOfLong = Long.SIZE - 1; for (int bitNumber = sizeOfLong; bitNumber >= 0; --bitNumber) { long val = (((number) & (1L << bitNumber))); val = val != 0L ? 1L : 0L; bitsOutput.append(val); if (0 == (bitNumber % numberOfGroups)) bitsOutput.append(" "); } return bitsOutput.toString(); } }
package com.hyve.streams.exception; /** * Thrown when invalid input is passed * @author nive * */ public class InvalidInputPairException extends Exception { private static final long serialVersionUID = 1L; public InvalidInputPairException() { } // Constructor that accepts a message public InvalidInputPairException(String message) { super(message); } }
package com.example.beach; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.Toast; import com.google.android.material.floatingactionbutton.FloatingActionButton; import com.google.android.material.snackbar.Snackbar; public class MainActivity extends AppCompatActivity implements View.OnClickListener { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); FloatingActionButton btn = (FloatingActionButton) findViewById(R.id.button); btn.setOnClickListener(this); } @Override public void onClick(View v) { //Toast.makeText(this, "Ваше путешествие заказано", Toast.LENGTH_SHORT).show(); Snackbar.make(findViewById(R.id.coordinator), "Ваше путешествие заказано", Snackbar.LENGTH_LONG).show(); } }
/* * Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.secretsmanager.caching.cache; import java.util.HashMap; import org.testng.annotations.Test; import org.testng.Assert; public class LRUCacheTest { @Test public void putIntTest() { LRUCache<Integer, Integer> cache = new LRUCache<Integer, Integer>(); cache.put(1, 1); Assert.assertTrue(cache.containsKey(1)); Assert.assertEquals(cache.get(1), new Integer(1)); } @Test public void removeTest() { LRUCache<Integer, Integer> cache = new LRUCache<Integer, Integer>(); cache.put(1, 1); Assert.assertNotNull(cache.get(1)); Assert.assertTrue(cache.remove(1)); Assert.assertNull(cache.get(1)); Assert.assertFalse(cache.remove(1)); Assert.assertNull(cache.get(1)); } @Test public void removeAllTest() { int max = 100; LRUCache<Integer, Integer> cache = new LRUCache<Integer, Integer>(); for (int n = 0; n < max; ++n) { cache.put(n, n); } cache.removeAll(); for (int n = 0; n < max; ++n) { Assert.assertNull(cache.get(n)); } } @Test public void clearTest() { int max = 100; LRUCache<Integer, Integer> cache = new LRUCache<Integer, Integer>(); for (int n = 0; n < max; ++n) { cache.put(n, n); } cache.clear(); for (int n = 0; n < max; ++n) { Assert.assertNull(cache.get(n)); } } @Test public void getAndRemoveTest() { LRUCache<Integer, Integer> cache = new LRUCache<Integer, Integer>(); cache.put(1, 1); Assert.assertNotNull(cache.get(1)); Assert.assertEquals(cache.getAndRemove(1), new Integer(1)); Assert.assertNull(cache.get(1)); } @Test public void removeWithValueTest() { LRUCache<Integer, Integer> cache = new LRUCache<Integer, Integer>(); cache.put(1, 1); Assert.assertNotNull(cache.get(1)); Assert.assertFalse(cache.remove(1, 2)); Assert.assertNotNull(cache.get(1)); Assert.assertTrue(cache.remove(1, 1)); Assert.assertNull(cache.get(1)); } @Test public void putStringTest() { LRUCache<String, String> cache = new LRUCache<String, String>(); cache.put("a", "a"); Assert.assertTrue(cache.containsKey("a")); Assert.assertEquals(cache.get("a"), "a"); } @Test public void putIfAbsentTest() { LRUCache<String, String> cache = new LRUCache<String, String>(); Assert.assertTrue(cache.putIfAbsent("a", "a")); Assert.assertFalse(cache.putIfAbsent("a", "a")); } @Test public void maxSizeTest() { int maxCache = 5; int max = 100; LRUCache<Integer, Integer> cache = new LRUCache<Integer, Integer>(maxCache); for (int n = 0; n < max; ++n) { cache.put(n, n); } for (int n = 0; n < max - maxCache; ++n) { Assert.assertNull(cache.get(n)); } for (int n = max - maxCache; n < max; ++n) { Assert.assertNotNull(cache.get(n)); Assert.assertEquals(cache.get(n), new Integer(n)); } } @Test public void maxSizeLRUTest() { int maxCache = 5; int max = 100; LRUCache<Integer, Integer> cache = new LRUCache<Integer, Integer>(maxCache); for (int n = 0; n < max; ++n) { cache.put(n, n); Assert.assertEquals(cache.get(0), new Integer(0)); } for (int n = 1; n < max - maxCache; ++n) { Assert.assertNull(cache.get(n)); } for (int n = max - maxCache + 1; n < max; ++n) { Assert.assertNotNull(cache.get(n)); Assert.assertEquals(cache.get(n), new Integer(n)); } Assert.assertEquals(cache.get(0), new Integer(0)); } @Test public void getAndPutTest() { int max = 100; Integer prev = null; LRUCache<Integer, Integer> cache = new LRUCache<Integer, Integer>(); for (int n = 0; n < max; ++n) { Assert.assertEquals(cache.getAndPut(1, n), prev); prev = n; } } @Test public void putAllTest() { int max = 100; HashMap<Integer, Integer> m = new HashMap<Integer, Integer>(); LRUCache<Integer, Integer> cache = new LRUCache<Integer, Integer>(); for (int n = 0; n < max; ++n) { m.put(n, n); } cache.putAll(m); for (int n = 0; n < max; ++n) { Assert.assertEquals(cache.get(n), new Integer(n)); } } }
package com.jvschool.util; import com.jvschool.dto.SessionUser; import javax.servlet.*; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import java.io.IOException; public class RoleFilter implements Filter { @Override public void init(FilterConfig filterConfig) throws ServletException { // default implementation ignored } @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) servletRequest; HttpSession session = request.getSession(); SessionUser user = (SessionUser) session.getAttribute("user"); if (user == null) { session.setAttribute("user", new SessionUser()); } filterChain.doFilter(servletRequest, servletResponse); } @Override public void destroy() { // default implementation ignored } }
package org.openqa.safari; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class CommandHandlerFactory { public static CommandHandler getHandler(HttpServletRequest request, HttpServletResponse response){ String path = request.getPathInfo(); System.out.println(path); return new NewSessionCommandHandler(request,response); } }
import java.io.PrintWriter; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); int n = in.nextInt(); in.nextLine(); String s = in.nextLine(); int sum = 0; for (int i = 0; i < n; i++) { int si = s.charAt(i) - '0'; // out.println("si: " + si); if (si % 2 == 0) { sum += (i + 1); } } out.println(sum); out.close(); } }
import java.math.BigDecimal; import lombok.val; import net.baade.Animal; import net.baade.Cliente; import net.baade.atendimento.Procedimento; import net.baade.financas.Recibo; import org.junit.Assert; import cucumber.api.java.en.Given; import cucumber.api.java.en.Then; import cucumber.api.java.en.When; public class StepAtendimentoRotina { Recibo recibo = new Recibo(); Cliente cliente = new Cliente(); @Given( "^um cliente com nome \"([^\"]*)\" que tem um animal de nome \"([^\"]*)\"$" ) public void um_cliente_com_nome_que_tem_um_animal_de_nome( String arg1, String arg2 ) throws Throwable { BigDecimal fofo = cliente.getAnimais(); new Animal( arg2 ); cliente.setNomecliente( arg1 ); cliente.getAnimais().add( fofo ); } @Given( "^um servico de \"([^\"]*)\" que custa \"([^\"]*)\"$" ) public void um_servico_de_que_custa( String arg1, String arg2 ) throws Throwable { val valorItem = (val) new BigDecimal( arg2 ); recibo.listaItemAdd( new Procedimento( arg1, valorItem ) ); } @Given( "^um outro servico de \"([^\"]*)\" que custa \"([^\"]*)\"$" ) public void um_outro_servico_de_que_custa( String arg1, String arg2 ) throws Throwable { val valorItem = (val) new BigDecimal( arg2 ); recibo.listaItemAdd( new Procedimento( arg1, valorItem ) ); } @When( "^o cliente pagar em \"([^\"]*)\"$" ) public void o_cliente_pagar_em( String pagamento ) throws Throwable { Assert.assertTrue( pagamento.equals( "Dinheiro" ) ); } @Then( "^o recibo deve ter (\\d+) servicos$" ) public void o_recibo_deve_ter_servicos( Integer servicos ) throws Throwable { Assert.assertEquals( new Integer( ((Object) recibo.getItens()).size() ), servicos ); } @Then( "^o servico (\\d+) deve ser \"([^\"]*)\"$" ) public void o_servico_deve_ser( int arg1, String arg2 ) throws Throwable { switch ( arg1 ) { case 1: Assert.assertEquals( arg2, "consulta de rotina" ); break; default: Assert.assertEquals( arg2, "vacinacao contra raiva" ); break; } } @Then( "^o valor total do recibo deve ser \"([^\"]*)\"$" ) public void o_valor_total_do_recibo_deve_ser( String arg1 ) throws Throwable { val valorTotal = new BigDecimal( arg1 ); Assert.assertEquals( recibo.getValorAtendimento(), valorTotal ); } }
/** * */ package am.bizis.cds.dpfdp4; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.w3c.dom.Document; import org.w3c.dom.Element; import am.bizis.cds.IVeta; /** * Priloha c. 2 * @author alex */ public class VetaV implements IVeta { private final double kc_snizukon9, kc_zvysukon9,kc_prij9, kc_vyd9; private final VetaJ[] vetaJ; private VetaT vetaT; private double kc_rozdil9,kc_rezerv_k, kc_rezerv_z,kc_zd9p,prijmy10,vydaje10,rozdil10,rozdil; private boolean vyd9proc=false, spol_jm_manz=false; /** * @param kc_snizukon9 Úhrn částek podle § 5, § 23 zákona a ostatní úpravy podle zákona snižující rozdíl mezi příjmy a * výdaji nebo výsledkem hospodaření před zdaněním - (zisk, ztráta) * Uveďte úhrn částek snižujících rozdíl mezi příjmy a výdaji nebo výsledek hospodaření před zdaněním. * @param kc_zvysukon9 Úhrn částek podle § 5, § 23 zákona a ostatní úpravy podle zákona zvyšující rozdíl mezi příjmy a * výdaji nebo výsledek hospodaření před zdaněním - (zisk, ztráta) * Uveďte úhrn částek zvyšujících rozdíl mezi příjmy a výdaji nebo výsledek hospodaření před zdaněním. * @param kc_prij9 Příjmy podle § 9 zákona * Uveďte na ř. 201 příjmy z pronájmu evidované podle § 9 odst. 6 zákona v záznamech o příjmech a výdajích případně v * účetnictví. * @param kc_vyd9 Výdaje podle § 9 zákona * Uveďte na ř. 202 výdaje z pronájmu evidované podle § 9 odst. 6 zákona v záznamech o příjmech a výdajích případně v * účetnictví. * V případě, že se jedná o příjmy dosažené dvěma a více poplatníky z titulu spoluvlastnictví k věci, potom společné * výdaje vynaložené na jejich dosažení, zajištění a udržení se rozdělují mezi poplatníky podle jejich * spoluvlastnických podílů nebo podle poměru dohodnutého ve smlouvě. Pokud příjmy z pronájmu plynou manželům ze * společného jmění manželů, zdaňují se jen u jednoho z nich a ten je uvede ve svém DAP. Údaje se uvádějí před úpravou * o položky podle § 5, § 23 zákona a ostatní úpravy podle zákona. * @param vetaJ vety J */ public VetaV(double kc_snizukon9,double kc_zvysukon9,double kc_prij9,double kc_vyd9, VetaJ[] vetaJ) { this.kc_snizukon9=kc_snizukon9; this.kc_zvysukon9=kc_zvysukon9; this.kc_prij9=kc_prij9; this.kc_vyd9=kc_vyd9; this.vetaJ=vetaJ; } /** * @param kc_snizukon9 Úhrn částek podle § 5, § 23 zákona a ostatní úpravy podle zákona snižující rozdíl mezi příjmy a * výdaji nebo výsledkem hospodaření před zdaněním - (zisk, ztráta) * Uveďte úhrn částek snižujících rozdíl mezi příjmy a výdaji nebo výsledek hospodaření před zdaněním. * @param kc_zvysukon9 Úhrn částek podle § 5, § 23 zákona a ostatní úpravy podle zákona zvyšující rozdíl mezi příjmy a * výdaji nebo výsledek hospodaření před zdaněním - (zisk, ztráta) * Uveďte úhrn částek zvyšujících rozdíl mezi příjmy a výdaji nebo výsledek hospodaření před zdaněním. * @param kc_prij9 Příjmy podle § 9 zákona * Uveďte na ř. 201 příjmy z pronájmu evidované podle § 9 odst. 6 zákona v záznamech o příjmech a výdajích případně v * účetnictví. * @param kc_vyd9 Výdaje podle § 9 zákona * Uveďte na ř. 202 výdaje z pronájmu evidované podle § 9 odst. 6 zákona v záznamech o příjmech a výdajích případně v * účetnictví. * V případě, že se jedná o příjmy dosažené dvěma a více poplatníky z titulu spoluvlastnictví k věci, potom společné * výdaje vynaložené na jejich dosažení, zajištění a udržení se rozdělují mezi poplatníky podle jejich * spoluvlastnických podílů nebo podle poměru dohodnutého ve smlouvě. Pokud příjmy z pronájmu plynou manželům ze * společného jmění manželů, zdaňují se jen u jednoho z nich a ten je uvede ve svém DAP. Údaje se uvádějí před úpravou * o položky podle § 5, § 23 zákona a ostatní úpravy podle zákona. * @param vetaJ vety J * @param t Veta T */ public VetaV(double kc_snizukon9,double kc_zvysukon9,double kc_prij9,double kc_vyd9, VetaJ[] vetaJ,VetaT t){ this(kc_snizukon9,kc_zvysukon9,kc_prij9,kc_vyd9,vetaJ); this.vetaT=t; } /* (non-Javadoc) * @see am.bizis.cds.dpfdp4.IVeta#getElement() */ @Override public Element getElement() throws ParserConfigurationException { DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder=docFactory.newDocumentBuilder(); Document EPO=docBuilder.newDocument(); Element VetaV=EPO.createElement("VetaV"); //spocitame uhrn prijmu z vet J prijmy10=0; vydaje10=0; rozdil=0; for(VetaJ j:vetaJ){ prijmy10+=j.getPrijmy10(); vydaje10+=j.getVydaje10(); rozdil10=j.getRozdil10(); if(rozdil10>0) rozdil+=rozdil10; } if(prijmy10!=0){ VetaV.setAttribute("kc_prij10",prijmy10+""); if(rozdil>0){ VetaV.setAttribute("kc_vyd10", vydaje10+""); VetaV.setAttribute("kc_zd10p", (prijmy10-vydaje10)+""); }else{ VetaV.setAttribute("kc_vyd10", rozdil10+""); VetaV.setAttribute("kc_zd10p", (prijmy10-rozdil10)+""); } VetaV.setAttribute("uhrn_rozdil10",rozdil+""); VetaV.setAttribute("uhrn_prijmy10",prijmy10+""); VetaV.setAttribute("uhrn_vydaje10",vydaje10+""); } VetaV.setAttribute("kc_prij9",kc_prij9+""); if(kc_rezerv_k!=0) VetaV.setAttribute("kc_rezerv_k",kc_rezerv_k+""); if(kc_rezerv_z!=0) VetaV.setAttribute("kc_rezerv_z",kc_rezerv_z+""); kc_rozdil9=kc_prij9-kc_vyd9; VetaV.setAttribute("kc_rozdil9",kc_rozdil9+""); VetaV.setAttribute("kc_snizukon9",kc_snizukon9+""); VetaV.setAttribute("kc_vyd9",kc_vyd9+""); kc_zd9p=kc_rozdil9+kc_zvysukon9-kc_snizukon9; VetaV.setAttribute("kc_zd9p",kc_zd9p+""); VetaV.setAttribute("kc_zvysukon9",kc_zvysukon9+""); if(vyd9proc) VetaV.setAttribute("vyd9proc", "A"); if(spol_jm_manz) VetaV.setAttribute("spol_jm_manz","A"); if(vetaT!=null) VetaV.setAttribute("kc_zd7",vetaT.getKcZd7p()+""); return VetaV; } /* (non-Javadoc) * @see am.bizis.cds.dpfdp4.IVeta#getMaxPocet() */ @Override public int getMaxPocet() { return 1; } /* (non-Javadoc) * @see am.bizis.cds.dpfdp4.IVeta#getDependency() */ @Override public String[] getDependency() { return new String[]{"VetaJ","VetaO"}; } /** * @param spol_jm_manz Dosáhl jsem příjmů ze společného jmění manželů * Máte-li příjmy z pronájmu, které jste dosáhl ze společného jmění manželů (bez podílového spoluvlastnictví manželů), * označte křížkem v předtištěném rámečku. V opačném případě nevyplňujte. */ public void setSpol_jm_manz(boolean spol_jm_manz) { this.spol_jm_manz = spol_jm_manz; } /** * @param vyd9proc Uplatňuji výdaje procentem z příjmů (30 %) * Uplatňujete-li výdaje procentem z příjmů z pronájmu podle § 9 odst. 4 zákona (30 %), uveďte A, jinak uveďte N. * Položka obsahuje kritickou kontrolu: hodnota položky může být pouze A nebo N. */ public void setVyd9proc(boolean vyd9proc) { this.vyd9proc = vyd9proc; } /** * @param kc_rezerv_k Rezervy na konci zdaňovacího období */ public void setKc_rezerv_k(double kc_rezerv_k) { this.kc_rezerv_k = kc_rezerv_k; } /** * @param kc_rezerv_z Rezervy na začátku zdaňovacího období */ public void setKc_rezerv_z(double kc_rezerv_z) { this.kc_rezerv_z = kc_rezerv_z; } /** * @return Dílčí základ daně, daňová ztráta z pronájmu podle § 9 zákona (ř. 203 + ř. 204 - ř. 205) * Vypočtěte částku podle pokynů na řádku. Rozdíl menší než nula je dílčí ztrátou podle § 9 zákona. * Údaj přeneste na ř. 39, 2. oddílu, základní části DAP na str. 2. */ public double getKcZd9p(){ return (kc_prij9-kc_vyd9)+kc_zvysukon9-kc_snizukon9; } @Override public String toString(){ return "VetaV"; } }
package net.klonima.reddittechnicaltest.adapters; import android.content.Context; import android.graphics.Bitmap; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ImageView; import android.widget.ProgressBar; import android.widget.TextView; import net.klonima.reddittechnicaltest.R; import net.klonima.reddittechnicaltest.managers.ImageManager; import net.klonima.reddittechnicaltest.models.adapters.SubredditListItemDTO; import java.util.ArrayList; /** * Created by: * Oscar Andres Dussan Garcia - oadussang@gmail.com. * Bogota Colombia - 27/02/2017 */ public class subredditListAdapter extends ArrayAdapter<SubredditListItemDTO> { private Context context; private Bitmap bmp; public subredditListAdapter(Context context, ArrayList<SubredditListItemDTO> subredditList) { super(context, 0, subredditList); this.context = context; } @Override public View getView(int position, View convertView, ViewGroup parent) { // Get the data item for this position SubredditListItemDTO subreddit = getItem(position); if (convertView == null) { convertView = LayoutInflater.from(getContext()).inflate(R.layout.adapter_subreddit_list_item, parent, false); } ImageView iconIV = (ImageView) convertView.findViewById(R.id.subreddit_list_item_icon_iv); ProgressBar iconPB = (ProgressBar) convertView.findViewById(R.id.subreddit_list_item_icon_pb); TextView titleTV = (TextView) convertView.findViewById(R.id.subreddit_list_item_title_tv); TextView descriptionTV = (TextView) convertView.findViewById(R.id.subreddit_list_item_description_tv); TextView urlNameTV = (TextView) convertView.findViewById(R.id.subreddit_list_item_url_tv); TextView subscribersTV = (TextView) convertView.findViewById(R.id.subreddit_list_item_subscribers_tv); ImageView plus18IV = (ImageView) convertView.findViewById(R.id.subreddit_list_item_plus_18_iv); if (subreddit != null) { ImageManager.downloadImage(context, convertView, iconIV.getId(), iconPB.getId(), subreddit.iconUrl, ImageManager.ImageType.LIST_ICON); titleTV.setText(subreddit.title); descriptionTV.setText(subreddit.description); urlNameTV.setText(subreddit.urlName); subscribersTV.setText(subreddit.subscribers); if (subreddit.isPlus18Required) { plus18IV.setVisibility(View.VISIBLE); } } return convertView; } }
package com.rachelgrau.rachel.health4theworldstroke.Activities; import android.graphics.Typeface; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.Toolbar; import android.widget.GridLayout; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import com.rachelgrau.rachel.health4theworldstroke.R; public class illustrations extends AppCompatActivity { static String illName=""; static String language=""; int nameIll; String lang=""; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_illustrations); nameIll=this.getIntent().getIntExtra(illName, 0); lang=getIntent().getStringExtra(language); setUpToolbar(); if(nameIll==(R.string.Adductores)) { addVideoFooterWithTitle(R.string.Adductors_text); addImagesWithURI(R.drawable.adductors1, R.drawable.adductors2); } if(nameIll==(R.string.Hamstrings)) { addVideoFooterWithTitle(R.string.Hamstrings_text); addImagesWithURI(R.drawable.hamstrings1, R.drawable.hamstrings2); } if(nameIll==(R.string.Dorsiflexors)) { addVideoFooterWithTitle(R.string.Dorsiflexors_text); addImagesWithURI(R.drawable.dorsiflexors1, R.drawable.dorsiflexors2); } if(nameIll==(R.string.Hand_Stretch)) { addVideoFooterWithTitle(R.string.Hand_Stretch_text); addImagesWithURI(R.drawable.hand1, R.drawable.hand2); } if(nameIll==(R.string.Shoulder_Stretches)) { addVideoFooterWithTitle(R.string.Shoulder_Stretches_text); addImagesWithURI(R.drawable.shoulder1, R.drawable.shoulder2); } if(nameIll==(R.string.Arm_Stretch)) { addVideoFooterWithTitle(R.string.Arm_Stretch_text); addImagesWithURI(R.drawable.arm1, R.drawable.arm2); } } private void setUpToolbar() { Toolbar myToolbar = (Toolbar) findViewById(R.id.toolbar); myToolbar.setTitle(""); Typeface font = Typeface.createFromAsset(getAssets(), "Roboto-Light.ttf"); TextView toolbarTitle = (TextView) myToolbar.findViewById(R.id.toolbar_title); toolbarTitle.setText(nameIll); toolbarTitle.setTypeface(font); setSupportActionBar(myToolbar); } public void addImagesWithURI(int imgOne, int imgTwo) { LinearLayout layout = (LinearLayout) findViewById(R.id.illustrations); ImageView imageViewOne = new ImageView(this); //setting image resource imageViewOne.setImageResource(imgOne); //setting image position imageViewOne.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, 800)); ImageView imageViewTwo = new ImageView(this); //setting image resource imageViewTwo.setImageResource(imgTwo); //setting image position imageViewTwo.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, 800)); layout.addView(imageViewOne); layout.addView(imageViewTwo); } public void addVideoFooterWithTitle(int title) { LinearLayout layout = (LinearLayout) findViewById(R.id.illustrations); TextView header = new TextView(this); header.setTextSize(20); header.setText(title); LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(GridLayout.LayoutParams.MATCH_PARENT, GridLayout.LayoutParams.WRAP_CONTENT); layoutParams.setMargins(35, 35, 35, 35); header.setLayoutParams(layoutParams); layout.addView(header); } }
package 笔试题目.pdd; import java.util.ArrayList; import java.util.List; import java.util.Scanner; public class 迷宫寻路 { public int minLen = Integer.MAX_VALUE; public static void main(String[] args){ 迷宫寻路 solution = new 迷宫寻路(); char[][] graph = solution.generateGraph(); solution.search(graph); } public void search(char[][] graph){ int m = graph.length; int n = graph[0].length; boolean[][] visited = new boolean[graph.length][graph[0].length]; int start_x = 0, start_y = 0; for (int i = 0; i < m; i++){ for (int j = 0; j < n; j++){ if (graph[i][j] == '2'){ start_x = i; start_y = j; } } } List<Character> keys = new ArrayList<>(); dfs(graph, start_x, start_y, visited, keys, 0); } public void dfs(char[][] graph, int x, int y, boolean[][] visited, List<Character> keys, int currentLen){ if (x < 0 || y < 0 || x > graph.length || y > graph[0].length || visited[x][y] || graph[x][y] == '0'){ return; } if (graph[x][y] == '3'){ visited[x][y] = true; currentLen++; minLen = Math.min(currentLen, minLen); return; } if (graph[x][y] == '1'){ visited[x][y] = true; currentLen++; dfs(graph, x+1,y,visited,keys,currentLen); dfs(graph, x-1,y,visited,keys,currentLen); dfs(graph, x,y+1,visited,keys,currentLen); dfs(graph, x,y-1,visited,keys,currentLen); } if (graph[x][y] >= 'a' && graph[x][y] <= 'z'){ visited[x][y] = true; currentLen++; keys.add(graph[x][y]); dfs(graph, x+1,y,visited,keys,currentLen); dfs(graph, x-1,y,visited,keys,currentLen); dfs(graph, x,y+1,visited,keys,currentLen); dfs(graph, x,y-1,visited,keys,currentLen); } if (graph[x][y] >= 'A' && graph[x][y] <= 'Z'){ if ( keys.contains((char)(graph[x][y]+32))){ visited[x][y] = true; currentLen++; keys.remove((char)(graph[x][y]+32)); } dfs(graph, x+1,y,visited,keys,currentLen); dfs(graph, x-1,y,visited,keys,currentLen); dfs(graph, x,y+1,visited,keys,currentLen); dfs(graph, x,y-1,visited,keys,currentLen); } } public char[][] generateGraph(){ Scanner in = new Scanner(System.in); String mn = in.nextLine(); int m = Integer.parseInt(mn.split(" ")[0]); int n = Integer.parseInt(mn.split(" ")[1]); char[][] graph = new char[m][n]; System.out.println(m+","+n); for (int i = 0; i < m; i++){ String line = in.nextLine(); for (int j = 0; j < n; j++){ graph[i][j] = line.charAt(j); } } return graph; } }
import java.awt.BorderLayout; import java.awt.Button; import java.awt.Container; import java.awt.Font; import java.awt.Insets; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.util.ArrayList; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextField; /** * creates a new frame to select distance to shoot the ball * @author geraldo * */ public class SelectDistance { Game.State state; static boolean selectedDistance = false; Button login; JTextField selectNumber; Insets inset; static int index; Game game; String comboList; ArrayList <String> numbers = new ArrayList<String>(); String title; int number; JComboBox<String> combo; int sum = 0; /** * constructor the frame to select distance * @param title the title for the frame * @param Label the message it will show * @param n the number of distances to choose from */ public SelectDistance(String title, String Label, int n){ this.title = title; final JFrame frame = new JFrame(title); Container content = frame.getContentPane(); combo = new JComboBox<String>(); this.number= n; inset = content.getInsets(); JPanel userPanel = new JPanel(new BorderLayout()); JLabel userLabel = new JLabel(Label); userLabel.setDisplayedMnemonic(KeyEvent.VK_U); final JTextField selectNumber = new JTextField(); userLabel.setLabelFor(selectNumber); userPanel.add(userLabel, BorderLayout.WEST); userPanel.add(combo, BorderLayout.CENTER); for (int i = 0;i<number;i++){ numbers.add("" +(i +1)) ; } for (int i=0;i< numbers.size();i++){ comboList = numbers.get(i); combo.addItem(comboList); } combo.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent event) { } }); JButton login=new JButton("OK"); login.setFont(new Font ("Arial", Font.PLAIN, 40)); JPanel panel = new JPanel(new BorderLayout()); panel.add(userPanel, BorderLayout.NORTH); content.add(panel, BorderLayout.NORTH); content.add(login); login.setBounds(inset.left + 10, inset.top + 20, 30, 10); frame.add(login); frame.setSize(250, 150); frame.setVisible(true); frame.setLocationRelativeTo(null); frame.setResizable(false); login.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { selectedDistance = true; index = combo.getSelectedIndex(); frame.dispose(); new SelectAngle("Direction","Angle of", 360); } }); } }
package me.levylin.lib.base; import android.os.Bundle; import android.support.annotation.LayoutRes; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import com.levylin.loader.DataLoader; import com.levylin.loader.ILoaderView; import butterknife.ButterKnife; import me.levylin.lib.base.mvp.BasePresenter; import me.levylin.lib.base.mvp.IMVPView; /** * Fragment基类 * Created by LinXin on 2016/8/3 15:10. */ public abstract class BaseFragment extends Fragment implements IMVPView, ILoaderView { private View mainView; private DataLoader mDataLoader;//Loader总控,防止loader发现内存泄露 private BasePresenter mPresenter;//Presenter总控 @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { if (mainView == null) { mainView = inflater.inflate(getLayoutResId(), container, false); ButterKnife.bind(this, mainView); init(mainView); } else { ViewGroup parent = (ViewGroup) mainView.getParent(); if (parent != null) { parent.removeView(mainView); } } return mainView; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: getActivity().finish(); return true; } return super.onOptionsItemSelected(item); } /** * 获取布局ID * * @return 布局ID */ @LayoutRes protected abstract int getLayoutResId(); /** * 初始化界面视图 * * @param mainView 主视图 */ protected abstract void init(View mainView); @Override public void setDataLoader(DataLoader loader) { mDataLoader = loader; } @Override public void setPresenter(BasePresenter presenter) { mPresenter = presenter; } @Override public void destroyLoader() { if (mDataLoader != null) { mDataLoader.onDestroy(); mDataLoader = null; } } @Override public void destroyPresenter() { if (mPresenter != null) { mPresenter.onDestroy(); mPresenter = null; } } @Override public void onDestroy() { super.onDestroy(); destroyLoader(); destroyPresenter(); } @Override public void showLoadingDialog(boolean isShow) { } }
package com.itheima.day_02.homework.feeder; public class Sheep extends Animal { @Override void eat() { System.out.println("羊啃草"); } @Override void drink() { System.out.println("羊喝水"); } }
package byow.Core; import byow.TileEngine.TETile; import java.io.Serializable; import java.util.LinkedList; import java.util.List; import java.util.Random; public class HallwayGenerator implements Serializable { private List<Hallway> hallwayList; //list of hallways for cleaning private Random randomGenerator; public HallwayGenerator(Random rand) { this.hallwayList = new LinkedList<>(); this.randomGenerator = rand; } /** Returns list of hallways generated. */ public List<Hallway> getHallwayList() { return this.hallwayList; } /** * Adds either ONE hallway for vertical/horizontal rooms, or TWO for diagonal rooms. * * Note 1: Diagonal hallways consist of two hallways for the cleaning process. * Note 2: Diagonal hallways will need to have an extra block added in the outer corner * of the two joint hallways. May be ignored when cleaning. * Note 3: This will only work if method is called iteratively on sorted list, due * to start and end Positions. * */ public void addHallwayPath(TETile[][] world, Room start, Room end) { //randomly selecting two positions in the two rooms respectively Position r1 = start.ranPosInRoom(randomGenerator); Position r2 = end.ranPosInRoom(randomGenerator); if (r1.x() > r2.x()) { //ensure r1 has smaller x coordinate Position rTemp = r1; r1 = r2; r2 = rTemp; } //draw horizontal hallway first Position startH = r1; //the smaller x coordinate Position endH = new Position(r2.x(), r1.y()); //the larger x coordinate Hallway hallHToAdd = new Hallway(startH, endH, endH.x() - startH.x(), true); hallHToAdd.addHallway(world); this.hallwayList.add(hallHToAdd); if (endH.y() > r2.y()) { //ensure r1 has smaller y coordinate Position rTemp = endH; endH = r2; r2 = rTemp; } //draw vertical Position startV = new Position(endH.x(), endH.y() - 1); //the smaller y coordinate Position endV = new Position(startV.x(), r2.y() + 1); //the larger y coordinate Hallway hallVToAdd = new Hallway(startV, endV, endV.y() - startV.y(), false); hallVToAdd.addHallway(world); this.hallwayList.add(hallVToAdd); } public void fillAll(TETile[][] world) { for (Hallway h : this.hallwayList) { h.clean(world); //NOTE: do stuff here with this.world, make sure about the orientations! } } // /** Other Solution: "Please Bear With Mae." */ // int roomOrientation = roomOrientation(start, end); // // if (roomOrientation == 0) { //horizontal rooms // addHorizontalHallway(world, start, end); // } else if (roomOrientation == 1) { //vertical rooms // addVerticalHallway(world, start, end); // } else { //diagonal rooms // addDiagonalHallway(world, start, end); // } // // private void addHorizontalHallway(TETile[][] world, Room start, Room end) { // //Start room is on the right of End room // Room right = start; // Room left = end; // if (end.getStartX() > start.getStartX()) { // //Start room is actually on left; adjust for math. // right = end; // left = start; // } // int length = right.getStartX() - left.getEndX(); // int randomYRange = getRandomFromRange(right, left); // Hallway hallToAdd = new Hallway(new Position(left.getEndX(), randomYRange), // new Position(right.getStartX(), randomYRange), length, true); // hallToAdd.addHallway(world); // hallwayList.add(hallToAdd); // // } // // private void addVerticalHallway(TETile[][] world, Room start, Room end) { // //Start room is above the End room // Room above = start; // Room below = end; // if (end.getStartY() > start.getStartY()) { // //Start room is actually below; adjust for math. // above = end; // below = start; // } // Position aboveRandPos = above.ranPosInRoom(); // Position belowRandPos = below.ranPosInRoom(); // int length = above.getStartY() - below.getEndY(); // Hallway hallToAdd = new Hallway(aboveRandPos, // belowRandPos, length, false); // hallToAdd.addHallway(world); // hallwayList.add(hallToAdd); // } // // private void addDiagonalHallway(TETile[][] world, Room start, Room end) { // Room right = start; // Room left = end; // if (end.getStartX() > start.getStartX()) { // Start room is actually on left; adjust for math. // right = end; // left = start; // } // int horizontalLength = getRandomFromRange(above, below);; // // Room above = start; // Room below = end; // if (end.getStartY() > start.getStartY()) { // //Start room is actually below; adjust for math. // above = end; // below = start; // } // int verticalLength = ; // // // int length = right.getStartX() - left.getEndX(); // int randomYRange = getRandomFromRange(right, left); // Hallway hallToAdd = new Hallway(new Position(left.getEndX(), randomYRange), // new Position(right.getStartX(), randomYRange), length, true); // // Hallway verticalHallToAdd = new Hallway(new Position(randomXRange, above.getStartY()), // new Position(randomXRange, below.getEndY()), length, false); // Hallway horizontalHallToAdd = new Hallway(new Position(randomXRange, above.getStartY()), // new Position(randomXRange, below.getEndY()), length, false); // verticalHallToAdd.addHallway(world); // horizontalHallToAdd.addHallway(world); // hallwayList.add(hallToAdd); // } // // /** // * Returns x or y of a pixel picked randomly from an x or y range. // * Assumes start is UP/RIGHT and end is DOWN/LEFT. // * */ // private int getRandomFromRange(Room start, Room end) { // // } // // /** // * Returns // * // * 0: rooms are horizontally aligned to each other. // * 1: rooms are vertically aligned to each other. // * -1: rooms are diagonal to each other. // * For Diagonals: (Use starterRoom() to find horizontal, then vertical orientation.) // * // * Note: "a" should be "start", "b" should be "end" for consistency. // * */ // private int roomOrientation(Room a, Room b) { // if (a.getEndY() >= b.getStartY() && a.getStartY() <= b.getEndY()) { // return 0; // } else if (a.getEndX() >= b.getStartX() && a.getStartX() <= b.getEndX()) { // return 1; // } else { // return -1; // } // } }
package com.youthlin.example.kafka; import lombok.Data; /** * @author youthlin.chen * @date 2019-06-03 19:17 */ @Data public class Company { private String name; private String address; }
package edu.nmsu.Home; import edu.nmsu.Home.Devices.Actuator; import edu.nmsu.Home.Devices.Device; import edu.nmsu.Home.Devices.Sensor; import edu.nmsu.Home.LocalSolver.Solver; import edu.nmsu.Home.Rules.PredictiveModel; import edu.nmsu.Home.Rules.PredictiveModelFactory; import edu.nmsu.Home.Rules.RuleType; import edu.nmsu.Home.Rules.SchedulingRule; import edu.nmsu.problem.Parameters; import edu.nmsu.problem.Utilities; import org.json.JSONObject; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; /** * Created by nandofioretto on 11/4/16. */ public class Home { private String name; private ArrayList<Actuator> actuators; private ArrayList<Sensor> sensors; private ArrayList<PredictiveModel> predictiveModels; private ArrayList<SchedulingRule> schedulingRules; private Solver solver; public Home(String homeName) { name = homeName; actuators = new ArrayList<>(); sensors = new ArrayList<>(); predictiveModels = new ArrayList<>(); schedulingRules = new ArrayList<>(); readDevices(); createPredictiveModels(); } public void addRule(SchedulingRule rule) { schedulingRules.add(rule); } public void activatePassiveRules() { // Once all the scheduling rules have been read, we activate a "passive rule" R iff there // exists an "active rule" which involves devices whose actions influence the property of R. for (SchedulingRule pr : schedulingRules) { if (pr.getType() == RuleType.passive) { pr.setActive(false); boolean found = false; // for all the active rules, take the actuators they affect. for (SchedulingRule ar : schedulingRules) { if (ar.getType() == RuleType.passive) continue; for (Actuator actuator : ar.getPredictiveModel().getActuators()) { // if the actuators affect the property of the passive rule if (actuator.getSensorProperties().contains(pr.getProperty())) { pr.setActive(true); found = true; break; } } if (found) break; } } } } public ArrayList<SchedulingRule> getSchedulingRules() { return schedulingRules; } public String getName() { return name; } private void createPredictiveModels() { for (Sensor s : sensors) { PredictiveModel model = PredictiveModelFactory.create(s, actuators, name); predictiveModels.add(model); } } private void readDevices() { try { String content = Utilities.readFile(Parameters.getDeviceDictionaryPath()); JSONObject jObject = new JSONObject(content.trim()); JSONObject jDevices = jObject.getJSONObject("devices"); Iterator<?> keys = jDevices.keys(); while( keys.hasNext() ) { String key = (String)keys.next(); if ( jDevices.get(key) instanceof JSONObject ) { JSONObject device = jDevices.getJSONObject(key); Device d = Device.create(key, device); if (d instanceof Sensor) { sensors.add((Sensor) d); } else if (d instanceof Actuator) { actuators.add((Actuator) d); } } } } catch (IOException e) { e.printStackTrace(); } } @Override public String toString() { String str = " Home: " + name; for (Actuator a : actuators) { if (a.isActive()) str += a.toString() + "\n"; } for (Sensor s : sensors) { if (s.isActive()) str += s.toString() + "\n"; } for (PredictiveModel m : predictiveModels) { if (m.isActive()) str += m.toString() + "\n"; } for (SchedulingRule r : schedulingRules) { if (r.isActive()) str += r.toString() + "\n"; } return str; } }
/* * Copyright 2020 WeBank * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.webank.wedatasphere.schedulis.web.webapp.servlet; import static java.util.stream.Collectors.joining; import static java.util.stream.Collectors.toList; import azkaban.executor.AlerterHolder; import azkaban.executor.ExecutableFlow; import azkaban.executor.ExecutionControllerUtils; import azkaban.executor.ExecutorManagerAdapter; import azkaban.executor.ExecutorManagerException; import azkaban.executor.Status; import azkaban.project.Project; import azkaban.project.ProjectManager; import azkaban.server.session.Session; import azkaban.user.User; import azkaban.webapp.AzkabanWebServer; import azkaban.webapp.servlet.LoginAbstractAzkabanServlet; import com.webank.wedatasphere.schedulis.common.executor.ExecutionCycle; import com.webank.wedatasphere.schedulis.common.system.SystemManager; import com.webank.wedatasphere.schedulis.common.system.common.TransitionService; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.concurrent.CompletableFuture; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class CycleServlet extends LoginAbstractAzkabanServlet { private static final Logger logger = LoggerFactory.getLogger(CycleServlet.class.getName()); private static final long serialVersionUID = 1L; private ExecutorManagerAdapter executorManager; private ProjectManager projectManager; private TransitionService transitionService; private SystemManager systemManager; private AlerterHolder alerterHolder; @Override public void init(ServletConfig config) throws ServletException { super.init(config); final AzkabanWebServer server = (AzkabanWebServer) getApplication(); this.executorManager = server.getExecutorManager(); this.projectManager = server.getProjectManager(); this.transitionService = server.getTransitionService(); this.systemManager = transitionService.getSystemManager(); this.alerterHolder = server.getAlerterHolder(); } @Override protected void handleGet(HttpServletRequest req, HttpServletResponse resp, Session session) throws ServletException, IOException { if (hasParam(req, "ajax")) { handleAJAXAction(req, resp, session); } else { ajaxExecutionCyclePage(req, resp, session); } } @Override protected void handlePost(HttpServletRequest req, HttpServletResponse resp, Session session) throws ServletException { } private void handleAJAXAction(HttpServletRequest req, HttpServletResponse resp, Session session) throws ServletException, IOException { String ajaxName = getParam(req, "ajax"); if (ajaxName.equals("fetchCycleFlows")) { ajaxFetchExecutionCycle(req, resp, session); } else if (ajaxName.equals("stopAllCycleFlows")) { ajaxStopAllCycleFlows(resp, session); } } private void ajaxFetchExecutionCycle(HttpServletRequest req, HttpServletResponse resp, Session session) throws IOException { int pageNum = getIntParam(req, "page", 1); int pageSize = getIntParam(req, "pageSize", 20); int offset = (pageNum - 1) * pageSize; User user = session.getUser(); Set<String> roles = new HashSet<>(user.getRoles()); HashMap<String, Object> map = new HashMap<>(); int cycleFlowsTotal = 0; List<ExecutionCycle> cycleFlows = new ArrayList<>(); try { if (roles.contains("admin")) { cycleFlowsTotal = executorManager.getExecutionCycleTotal(Optional.empty()); cycleFlows = executorManager.listExecutionCycleFlows(Optional.empty(), offset, pageSize); } else if (systemManager.isDepartmentMaintainer(user)) { List<Integer> maintainedProjectIds = systemManager.getMaintainedProjects(user); cycleFlowsTotal = executorManager.getExecutionCycleTotal(user.getUserId(), maintainedProjectIds); cycleFlows = executorManager.listExecutionCycleFlows(user.getUserId(), maintainedProjectIds, offset, pageSize); } else { cycleFlowsTotal = executorManager.getExecutionCycleTotal(Optional.of(user.getUserId())); cycleFlows = executorManager.listExecutionCycleFlows(Optional.of(user.getUserId()), offset, pageSize); } } catch (ExecutorManagerException e) { map.put("error", "Error fetch execution cycle"); } map.put("total", cycleFlowsTotal); map.put("page",pageNum); map.put("pageSize", pageSize); map.put("executionCycleList", cycleFlows2ListMap(cycleFlows)); writeJSON(resp, map); } private void ajaxStopAllCycleFlows(HttpServletResponse resp, Session session) throws ServletException, IOException { try { Map<String, Object> map = new HashMap<>(); User user = session.getUser(); Set<String> roles = new HashSet<>(user.getRoles()); if (roles.contains("admin")) { List<ExecutionCycle> executionCycles = executorManager.getAllRunningCycleFlows(); logger.info("starting stop all cycle flows"); executorManager.stopAllCycleFlows(); logger.info("stopped all cycle flows successful"); alertOnCycleFlowInterrupt(executionCycles); map.put("result", "success"); } else { map.put("result", "failed, has no permission"); } writeJSON(resp, map); } catch (ExecutorManagerException e) { logger.error("ajax stop all cycle flows failed", e); throw new ServletException(e); } } private Object cycleFlows2ListMap(List<ExecutionCycle> cycleFlows) { return cycleFlows.stream() .map(flow -> { Map<String, Object> map = new HashMap<>(); map.put("id", flow.getId()); map.put("status", flow.getStatus()); map.put("currentExecId", flow.getCurrentExecId()); Project project = projectManager.getProject(flow.getProjectId()); map.put("projectName", project.getName()); map.put("flowId", flow.getFlowId()); map.put("submitUser", flow.getSubmitUser()); String proxyUsers = project.getProxyUsers().stream() .collect(joining(",", "[", "]")); map.put("proxyUsers", proxyUsers); return map; }) .collect(toList()); } private void alertOnCycleFlowInterrupt(List<ExecutionCycle> executionCycles) { CompletableFuture.runAsync(() -> { for (ExecutionCycle executionCycle: executionCycles) { if (executionCycle != null) { try { ExecutableFlow exFlow = this.executorManager.getExecutableFlow(executionCycle.getCurrentExecId()); executionCycle.setStatus(Status.KILLED); executionCycle.setEndTime(System.currentTimeMillis()); ExecutionControllerUtils.alertOnCycleFlowInterrupt(exFlow, executionCycle, alerterHolder); } catch (ExecutorManagerException e) { logger.error(String.format("alter cycle flow interrupt failed: flow: %s", executionCycle.getFlowId())); } } } }); } private void ajaxExecutionCyclePage(HttpServletRequest req, HttpServletResponse resp, Session session) { } }
/* * 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 com.services; import com.dao.ImplDao; import com.entity.Cliente; import com.entity.Tienda; import com.implDao.IUsuario; import static com.services.TiendaServices.getEmf; import static com.services.TiendaServices.getEntityManagger; import java.io.Serializable; import java.util.List; import javax.persistence.Query; /** * * @author DAC-PC */ public class UsuarioServices extends ImplDao<Cliente, Long> implements IUsuario, Serializable{ @Override public Cliente iniciarsesion(Cliente c) { Cliente clien = null; String consulta; try { consulta = "FROM Cliente c WHERE c.usuario = ?1 and c.contrasena = ?2"; Query query = getEmf().createEntityManager().createQuery(consulta); query.setParameter(1, c.getUsuario()); query.setParameter(2, c.getContrasena()); List<Cliente> lista =query.getResultList(); if(!lista.isEmpty()){ clien = lista.get(0); } } catch (Exception e) { throw e; }finally{ getEntityManagger().close(); } return clien; } }
package pl.kate.pogodynka.model; import com.fasterxml.jackson.annotation.*; import lombok.Data; import javax.annotation.Generated; import java.util.HashMap; import java.util.Map; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonPropertyOrder({ "speed", "deg" }) @Generated("jsonschema2pojo") @Data public class Wind { @JsonProperty("speed") private Double speed; @JsonProperty("deg") private Integer deg; @JsonIgnore private Map<String, Object> additionalProperties = new HashMap<String, Object>(); }
package Implement; import modle.Worker; public interface WorkerImp { // 添加员工 void addWorker(); // 删除员工 void removeWorkerById(); void removeWorkerByName(); // 查找员工 void searchWorkerById(); void searchWorkerByName(); // 修改员工信息 void modifyWorkerById(); void modifyWorkerByName(); }
import java.util.List; import java.util.ArrayList; public class ArrayListDemo { public static void main(String[] args){ List<Integer> L = new ArrayList<>(); L.add(5); L.add(10); System.out.println(L); } }
package com.karachevtsev.mayaghostsballs; import com.badlogic.gdx.graphics.g2d.Sprite; import com.badlogic.gdx.graphics.g2d.TextureAtlas; import java.util.HashMap; /** * Created by root on 27.01.2017. */ public class ResKeeper { private final TextureAtlas atlas; private final TextureAtlas ball; private final TextureAtlas spirit; private HashMap<String, Sprite> sprites = new HashMap<String, Sprite>(); public ResKeeper() { atlas = new TextureAtlas("maya_ghosts.txt"); ball = new TextureAtlas("ball.txt"); spirit = new TextureAtlas("spirit.txt"); } public Sprite getSprite(String name) { if( !sprites.containsKey(name) ) { Sprite newSprite = atlas.createSprite(name); sprites.put(name, newSprite); } return sprites.get(name); } public void dispose() { atlas.dispose(); ball.dispose(); spirit.dispose(); } }
package de.kfs.db; import com.google.inject.Guice; import com.google.inject.Injector; import de.kfs.db.di.KFSModule; import javafx.application.Application; import javafx.scene.Scene; import javafx.scene.control.TextField; import javafx.scene.layout.BorderPane; import javafx.stage.Stage; public class FXApp extends Application { private BorderPane tes = new BorderPane(); @Override public void start(Stage stage) { Injector injector = Guice.createInjector(new KFSModule()); SceneManagerFactory sceneManagerFactory = injector.getInstance(SceneManagerFactory.class); SceneManager sceneManager = sceneManagerFactory.create(stage); //showing first Scene sceneManager.showOpenScene(); } public static void main(String[] args) { launch(args); } }
package hw2; import hw2.Set; public class setTest { public static void main(String[] args) { System.out.println("\n \n Test 1 - Constructor & whoIsServeing"); System.out.println("----------------------------------------"); Set s = new Set(3,false); System.out.println("0 - " + s.whoIsServing()); System.out.println("\n \n Test 2 - fastForward(), isCurrentGameOver(), & player1GamesWon()"); System.out.println("----------------------------------------"); s.fastForward(0, 4); System.out.println("true - " + s.isCurrentGameOver()); System.out.println("1 - " + s.player1GamesWon()); } }
/* * 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 view; import java.sql.*; import javax.swing.*; import config.KoneksiDB; import config.UserSession; /** * * @author WINDOWS10 PRO */ public class Login extends javax.swing.JFrame { Connection con = KoneksiDB.getConnection();; ResultSet rs; /** * Creates new form Login */ public Login() { initComponents(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jTabbedPane1 = new javax.swing.JTabbedPane(); jPanel2 = new javax.swing.JPanel(); jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); ussername = new javax.swing.JTextField(); submit = new javax.swing.JButton(); cancel = new javax.swing.JButton(); password = new javax.swing.JPasswordField(); jPanel3 = new javax.swing.JPanel(); jLabel3 = new javax.swing.JLabel(); nisn = new javax.swing.JTextField(); submit_siswa = new javax.swing.JButton(); jLabel5 = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); jTabbedPane1.setFont(new java.awt.Font("Times New Roman", 1, 18)); // NOI18N jPanel2.setBackground(new java.awt.Color(0, 0, 255)); jPanel2.setFont(new java.awt.Font("Times New Roman", 1, 18)); // NOI18N jLabel1.setFont(new java.awt.Font("Times New Roman", 1, 24)); // NOI18N jLabel1.setText("USSERNAME"); jLabel2.setFont(new java.awt.Font("Times New Roman", 1, 24)); // NOI18N jLabel2.setText("PASSWORD"); submit.setFont(new java.awt.Font("Times New Roman", 1, 12)); // NOI18N submit.setText("Login"); submit.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { submitActionPerformed(evt); } }); cancel.setFont(new java.awt.Font("Times New Roman", 1, 12)); // NOI18N cancel.setText("cancel"); cancel.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cancelActionPerformed(evt); } }); javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2); jPanel2.setLayout(jPanel2Layout); jPanel2Layout.setHorizontalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addGap(149, 149, 149) .addComponent(submit, javax.swing.GroupLayout.PREFERRED_SIZE, 105, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 378, Short.MAX_VALUE) .addComponent(cancel, javax.swing.GroupLayout.PREFERRED_SIZE, 105, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(118, 118, 118)) .addGroup(jPanel2Layout.createSequentialGroup() .addGap(68, 68, 68) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel1) .addComponent(jLabel2)) .addGap(154, 154, 154) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(ussername, javax.swing.GroupLayout.DEFAULT_SIZE, 323, Short.MAX_VALUE) .addComponent(password)) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); jPanel2Layout.setVerticalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addGap(36, 36, 36) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel1) .addComponent(ussername, javax.swing.GroupLayout.DEFAULT_SIZE, 44, Short.MAX_VALUE)) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addGap(48, 48, 48) .addComponent(jLabel2)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup() .addGap(40, 40, 40) .addComponent(password, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 79, Short.MAX_VALUE) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(submit, javax.swing.GroupLayout.PREFERRED_SIZE, 44, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(cancel, javax.swing.GroupLayout.PREFERRED_SIZE, 44, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(25, 25, 25)) ); jTabbedPane1.addTab("PETUGAS", jPanel2); jPanel3.setBackground(new java.awt.Color(0, 0, 255)); jLabel3.setFont(new java.awt.Font("Times New Roman", 1, 24)); // NOI18N jLabel3.setText("NISN SISWA"); submit_siswa.setFont(new java.awt.Font("Times New Roman", 1, 14)); // NOI18N submit_siswa.setText("Login"); submit_siswa.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { submit_siswaActionPerformed(evt); } }); javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3); jPanel3.setLayout(jPanel3Layout); jPanel3Layout.setHorizontalGroup( jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel3Layout.createSequentialGroup() .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLabel3) .addGap(53, 53, 53) .addComponent(nisn, javax.swing.GroupLayout.PREFERRED_SIZE, 358, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(129, 129, 129)) .addGroup(jPanel3Layout.createSequentialGroup() .addGap(279, 279, 279) .addComponent(submit_siswa, javax.swing.GroupLayout.PREFERRED_SIZE, 128, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(448, Short.MAX_VALUE)) ); jPanel3Layout.setVerticalGroup( jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel3Layout.createSequentialGroup() .addGap(63, 63, 63) .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel3) .addComponent(nisn, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 110, Short.MAX_VALUE) .addComponent(submit_siswa, javax.swing.GroupLayout.PREFERRED_SIZE, 47, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(44, 44, 44)) ); jTabbedPane1.addTab("SISWA", jPanel3); getContentPane().add(jTabbedPane1, new org.netbeans.lib.awtextra.AbsoluteConstraints(320, 230, 860, 340)); jLabel5.setIcon(new javax.swing.ImageIcon(getClass().getResource("/image/login1.jpg"))); // NOI18N getContentPane().add(jLabel5, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, -1, -1)); pack(); setLocationRelativeTo(null); }// </editor-fold>//GEN-END:initComponents private void submitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_submitActionPerformed String user = ussername.getText(); String pass = password.getText(); try { Statement st = con.createStatement(); String sql = "SELECT * FROM petugas where username='"+user+"' and password='"+pass+"'"; rs = st.executeQuery(sql); if (rs.next()) { String id = rs.getString("id_petugas"); String username = rs.getString("username"); String nama = rs.getString("nama_petugas"); String level = rs.getString("level"); //set user data session UserSession.set_id(id); UserSession.set_username(username); UserSession.set_nama(nama); UserSession.set_level(level); switch (level) { case "admin": { JOptionPane.showMessageDialog(null, "Selamat datang "+ nama +" !"); Dashboard dsb = new Dashboard(); dsb.dashAdmin(); dsb.setVisible(true); dispose(); break; } case "petugas": { JOptionPane.showMessageDialog(null, "Selamat datang "+ nama +" !"); Dashboard dsb = new Dashboard(); dsb.dashPetugas(); dsb.setVisible(true); dispose(); break; } default: break; } } else { JOptionPane.showMessageDialog(null, "Username atau password salah"); } } catch (SQLException e) { System.out.println(e); } }//GEN-LAST:event_submitActionPerformed private void cancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelActionPerformed // TODO add your handling code here: System.exit(0); }//GEN-LAST:event_cancelActionPerformed private void submit_siswaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_submit_siswaActionPerformed String Get_nisn = nisn.getText(); try { String sql = "SELECT * FROM siswa where nisn='"+Get_nisn+"'"; rs = con.createStatement().executeQuery(sql); if (rs.next()) { String nisn = rs.getString("nisn"); String nama_siswa = rs.getString("nama"); //set user data session UserSession.set_nisn(nisn); UserSession.set_nama_siswa(nama_siswa); JOptionPane.showMessageDialog(null, "Selamat datang "+ nama_siswa +" !"); DashboardSiswa dsb = new DashboardSiswa(); dsb.setVisible(true); dispose(); } else { JOptionPane.showMessageDialog(null, "NISN tidak ditemukan"); } } catch (SQLException e) { System.out.println(e); } }//GEN-LAST:event_submit_siswaActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(Login.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(Login.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(Login.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(Login.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new Login().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton cancel; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel5; private javax.swing.JPanel jPanel2; private javax.swing.JPanel jPanel3; private javax.swing.JTabbedPane jTabbedPane1; private javax.swing.JTextField nisn; private javax.swing.JPasswordField password; private javax.swing.JButton submit; private javax.swing.JButton submit_siswa; private javax.swing.JTextField ussername; // End of variables declaration//GEN-END:variables }
package de.fred4jupiter.spring.boot.camel; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class SpringBootCamelApplication { public static void main(String[] args) { SpringApplication.run(SpringBootCamelApplication.class, args); } }
package com.ztstudio.ane.GeiliPay; import java.util.HashMap; import java.util.Map; import com.adobe.fre.FREContext; import com.adobe.fre.FREFunction; public class GLContext extends FREContext { public static final String GL_FUNCTION_BILL = "gl_function_bill"; @Override public void dispose() { // TODO Auto-generated method stub } public Map<String, FREFunction> getFunctions() { // TODO Auto-generated method stub Map<String, FREFunction> map = new HashMap<String, FREFunction>(); map.put(GL_FUNCTION_BILL, new GeiliPay()); return map; } }
/* ********************************************************************************** * MIT License * * * * Copyright (c) 2017 Josh Larson * * * * Permission is hereby granted, free of charge, to any person obtaining a copy * * of this software and associated documentation files (the "Software"), to deal * * in the Software without restriction, including without limitation the rights * * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * * copies of the Software, and to permit persons to whom the Software is * * furnished to do so, subject to the following conditions: * * * * The above copyright notice and this permission notice shall be included in all * * copies or substantial portions of the Software. * * * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * * SOFTWARE. * ********************************************************************************** */ package me.joshlarson.json; import java.io.IOException; import java.io.InputStream; /** * Provides convenience methods for stream operations that do automatic resource cleanup * * @author josh */ public class JSON { /** * Opens a new JSONInputStream with the specified InputStream and reads either a JSONObject or a JSONArray based on the input stream. After * reading, the input stream is closed * * @param is the input stream to read from * @param printError TRUE if exception stack traces should be printed, FALSE otherwise * @return the JSONObject read from the stream, or null if there was an exception */ public static Object readNext(InputStream is, boolean printError) { try (JSONInputStream in = new JSONInputStream(is)) { return in.readNext(); } catch (IOException | JSONException e) { if (printError) e.printStackTrace(); } return null; } /** * Opens a new JSONInputStream with the specified string and reads either a JSONObject or a JSONArray based on the string * * @param str the string to read from * @param printError TRUE if exception stack traces should be printed, FALSE otherwise * @return the JSONObject read from the stream, or null if there was an exception */ public static Object readNext(String str, boolean printError) { try (JSONInputStream in = new JSONInputStream(str)) { return in.readNext(); } catch (IOException | JSONException e) { if (printError) e.printStackTrace(); } return null; } /** * Opens a new JSONInputStream with the specified InputStream and reads a JSONObject. After reading, the input stream is closed * * @param is the input stream to read from * @param printError TRUE if exception stack traces should be printed, FALSE otherwise * @return the JSONObject read from the stream, or null if there was an exception */ public static JSONObject readObject(InputStream is, boolean printError) { try (JSONInputStream in = new JSONInputStream(is)) { return new JSONObject(in.readObject()); } catch (IOException | JSONException e) { if (printError) e.printStackTrace(); } return null; } /** * Opens a new JSONInputStream with the specified string and reads a JSONObject * * @param str the string to read from * @param printError TRUE if exception stack traces should be printed, FALSE otherwise * @return the JSONObject read from the string, or null if there was an exception */ public static JSONObject readObject(String str, boolean printError) { try (JSONInputStream in = new JSONInputStream(str)) { return new JSONObject(in.readObject()); } catch (IOException | JSONException e) { if (printError) e.printStackTrace(); } return null; } /** * Opens a new JSONInputStream with the specified InputStream and reads a JSONArray. After reading, the input stream is closed * * @param is the input stream to read from * @param printError TRUE if exception stack traces should be printed, FALSE otherwise * @return the JSONArray read from the stream, or null if there was an exception */ public static JSONArray readArray(InputStream is, boolean printError) { try (JSONInputStream in = new JSONInputStream(is)) { return new JSONArray(in.readArray()); } catch (IOException | JSONException e) { if (printError) e.printStackTrace(); } return null; } /** * Opens a new JSONInputStream with the specified string and reads a JSONArray * * @param str the string to read from * @param printError TRUE if exception stack traces should be printed, FALSE otherwise * @return the JSONArray read from the string, or null if there was an exception */ public static JSONArray readArray(String str, boolean printError) { try (JSONInputStream in = new JSONInputStream(str)) { return new JSONArray(in.readArray()); } catch (IOException | JSONException e) { if (printError) e.printStackTrace(); } return null; } /** * Opens a new JSONInputStream with the specified InputStream and reads a JSONObject or JSONArray. After reading, the input stream is closed * * @param is the input stream to read from * @return the JSONObject or JSONArray read from the stream, or null if there was an exception * @throws IOException if there is an exception within the input stream * @throws JSONException if there is a JSON parsing error */ public static Object readNext(InputStream is) throws IOException, JSONException { try (JSONInputStream in = new JSONInputStream(is)) { return in.readNext(); } } /** * Opens a new JSONInputStream with the specified string and reads a JSONObject * * @param str the string to read from * @return the JSONObject or JSONArray read from the stream * @throws IOException if there is an exception within the input stream * @throws JSONException if there is a JSON parsing error */ public static Object readNext(String str) throws IOException, JSONException { try (JSONInputStream in = new JSONInputStream(str)) { return in.readNext(); } } /** * Opens a new JSONInputStream with the specified InputStream and reads a JSONObject. After reading, the input stream is closed * * @param is the input stream to read from * @return the JSONObject read from the stream, or null if there was an exception * @throws IOException if there is an exception within the input stream * @throws JSONException if there is a JSON parsing error */ public static JSONObject readObject(InputStream is) throws IOException, JSONException { try (JSONInputStream in = new JSONInputStream(is)) { return new JSONObject(in.readObject()); } } /** * Opens a new JSONInputStream with the specified string and reads a JSONObject * * @param str the string to read from * @return the JSONObject read from the string, or null if there was an exception * @throws IOException if there is an exception within the input stream * @throws JSONException if there is a JSON parsing error */ public static JSONObject readObject(String str) throws IOException, JSONException { try (JSONInputStream in = new JSONInputStream(str)) { return new JSONObject(in.readObject()); } } /** * Opens a new JSONInputStream with the specified InputStream and reads a JSONArray. After reading, the input stream is closed * * @param is the input stream to read from * @return the JSONArray read from the stream * @throws IOException if there is an exception within the input stream * @throws JSONException if there is a JSON parsing error */ public static JSONArray readArray(InputStream is) throws IOException, JSONException { try (JSONInputStream in = new JSONInputStream(is)) { return new JSONArray(in.readArray()); } } /** * Opens a new JSONInputStream with the specified string and reads a JSONArray * * @param str the string to read from * @return the JSONArray read from the string * @throws IOException if there is an exception within the input stream * @throws JSONException if there is a JSON parsing error */ public static JSONArray readArray(String str) throws IOException, JSONException { try (JSONInputStream in = new JSONInputStream(str)) { return new JSONArray(in.readArray()); } } }
package com.evjeny.hackersimulator.game; /** * Created by Evjeny on 07.03.2018 6:21. */ public enum ActType { STORY, IMAGE, CODE }
package com.seleniumdemo; import java.lang.reflect.Constructor; import java.lang.reflect.Method; import org.testng.IAnnotationTransformer; import org.testng.annotations.ITestAnnotation; public class Mytransformer implements IAnnotationTransformer { public void transform(ITestAnnotation anno,Class cllass,Constructor couns,Method met) { anno.setRetryAnalyzer(retryfailedtestcases.class); } }
/** * Support package for the Java {@link java.util.ServiceLoader} facility. */ @NonNullApi @NonNullFields package org.springframework.beans.factory.serviceloader; import org.springframework.lang.NonNullApi; import org.springframework.lang.NonNullFields;
package com.coach.service.CoachService.entities; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonManagedReference; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import lombok.ToString; import javax.persistence.*; import java.util.Collection; import java.util.Date; import java.util.HashSet; import java.util.Set; @Entity @AllArgsConstructor @NoArgsConstructor @ToString @Data public class Coach { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @Column(length = 75) private String Code; private String photo; private String description; @Column(length = 75) private String first_name; @Column(length = 75) private String last_name; private Date birthday; @Column(length = 75) private String email; private String phonenumber; @Column(length = 285) private String address; @JsonIgnore @ManyToMany(fetch = FetchType.EAGER) private Set<Sport> SportsList ; }
package ch11; import java.util.Random; import java.util.TreeSet; public class TreeSetExam { public static void main(String[]args) { TreeSet ts=new TreeSet(); for(int i=0;i<5;i++) { Random ran=new Random(); int rand=ran.nextInt(50)+1; ts.add(rand); } System.out.println(ts);// TreeSet은 기본적으로 오름차순으로 출력함 System.out.println(ts.headSet(30));//이것보다 작은값만 찾을수도있고 System.out.println(ts.tailSet(20));//이것보다 큰값만 찾을수도 있다 System.out.println(ts.subSet(5, 35));//찾을 범위를 지정함 System.out.println(ts.subSet(37, 50));//찾을 범위를 지정함 } }
package com.bigdata.hadoop.mapreduce.fans; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.Mapper; import org.apache.hadoop.mapreduce.Reducer; import org.apache.hadoop.mapreduce.lib.input.FileInputFormat; import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat; import java.io.IOException; import java.util.Arrays; public class SharedFriendsStepTwo { static class SharedFriendsStepTwoMapper extends Mapper<LongWritable, Text, Text, Text> { @Override protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException { String line = value.toString(); String[] fans_persons = line.split("\t"); String fans = fans_persons[0]; String persons = fans_persons[1]; String[] pers = persons.split(","); Arrays.sort(pers); for (int i = 0; i < pers.length - 1; i++) { for (int j = i + 1; j < pers.length; j++) { // 发出 <人-人,好友> ,这样,相同的“人-人”对的所有好友就会到同1个reduce中去 context.write(new Text(pers[i] + "-" + pers[j]), new Text(fans)); } } } } static class SharedFriendsStepTwoReducer extends Reducer<Text, Text, Text, Text> { @Override protected void reduce(Text key, Iterable<Text> values, Context context) throws IOException, InterruptedException { StringBuffer sb = new StringBuffer(); for (Text fan : values) { sb.append(fan).append(" "); } context.write(key, new Text(sb.toString())); } } public static void main(String[] args) throws Exception { Configuration conf = new Configuration(); Job job = Job.getInstance(conf); job.setJarByClass(SharedFriendsStepTwo.class); job.setOutputKeyClass(Text.class); job.setOutputValueClass(Text.class); job.setMapperClass(SharedFriendsStepTwoMapper.class); job.setReducerClass(SharedFriendsStepTwoReducer.class); FileInputFormat.setInputPaths(job, new Path("D:/testhadoopdata/output/fansstepone/part-r-00000")); FileOutputFormat.setOutputPath(job, new Path("D:/testhadoopdata/output/fanssteptwo")); job.waitForCompletion(true); } }
package genericcode; import org.semanticweb.owlapi.model.OWLNamedIndividual; import org.semanticweb.owlapi.model.OWLOntology; import OWL.ClassIRI; public class PrimitiveType extends Type { private String typeName; public PrimitiveType(OWLOntology o, String iri) { super(o, iri); this.classAssertion(ClassIRI.PRIMITIVE_TYPE); // TODO Auto-generated constructor stub } public PrimitiveType(OWLOntology o, OWLNamedIndividual i) { super(o,i); } public String getTypeName() { return typeName; } public void setTypeName(String typeName) { this.typeName = typeName; } // public String java2Django() { // // } }
import java.util.ArrayList; import java.util.Scanner; public class HotelManager { static ArrayList<Hotel> hotelArrayList = new ArrayList<>(); private static final Scanner Sc = new Scanner(System.in); static { hotelArrayList.add(new Hotel(100000, 101, "Normal")); hotelArrayList.add(new Hotel(80000, 102, "Cheap")); hotelArrayList.add(new Hotel(120000, 103, "Vip")); hotelArrayList.add(new Hotel(140000, 104, "Vip1")); hotelArrayList.add(new Hotel(160000, 105, "Vip2")); } public static void add(int number, int chose) { String name = ScannerMethod.ScannerName(); int age = ScannerMethod.ScannerAge(); int id = ScannerMethod.ScannerId(); switch (chose) { case 1: if (checkRoom(101)) { try{ System.out.println("Input Time In"); hotelArrayList.get(0).setTimeIn(Sc.nextDouble()); } catch (Exception ex){ System.out.println("Input Int Number"); add(number,chose); } IsRoomNormal(number, chose, name, age, id); } else { for (Hotel hotel : hotelArrayList) { if (hotel.getCustomerArrayList().size() == 0) { System.out.println("Room is null :" + hotel.getId()); } } } break; case 2: try{ System.out.println("Input Time In"); hotelArrayList.get(1).setTimeIn(Sc.nextDouble()); } catch (Exception ex){ System.out.println("Input Int Number"); add(number,chose); } if (checkRoom(102)) { isRoomCheap(number, chose, name, age, id); } else { for (Hotel hotel : hotelArrayList) { if (hotel.getCustomerArrayList().size() == 0) { System.out.println("Room is null :" + hotel.getId()); } } } break; case 3: try{ System.out.println("Input Time In"); hotelArrayList.get(2).setTimeIn(Sc.nextDouble()); } catch (Exception ex){ System.out.println("Input Int Number"); add(number,chose); } if (checkRoom(103)) { isRoomVip(number, chose, name, age, id); } else { for (Hotel hotel : hotelArrayList) { if (hotel.getCustomerArrayList().size() == 0) { System.out.println("Room is null :" + hotel.getId()); } } } break; case 4: try{ System.out.println("Input Time In"); hotelArrayList.get(3).setTimeIn(Sc.nextDouble()); } catch (Exception ex){ System.out.println("Input Int Number"); add(number,chose); } if (checkRoom(104)) { isRoomVip1(number, chose, name, age, id); } else { for (Hotel hotel : hotelArrayList) { if (hotel.getCustomerArrayList().size() == 0) { System.out.println("Room is null :" + hotel.getId()); } } } break; case 5: try{ System.out.println("Input Time In"); hotelArrayList.get(4).setTimeIn(Sc.nextDouble()); } catch (Exception ex){ System.out.println("Input Int Number"); add(number,chose); } if (checkRoom(105)) { isRoomVip2(number, chose, name, age, id); } else { for (Hotel hotel : hotelArrayList) { if (hotel.getCustomerArrayList().size() == 0) { System.out.println("Room is null :" + hotel.getId()); } } } break; default: System.out.println("Out of room"); } } private static void isRoomVip2(int number, int chose, String name, int age, int id) { try { if (number == 1) { hotelArrayList.get(4).getCustomerArrayList().add(new customer(name, age, id)); } else if (number == 2) { hotelArrayList.get(4).getCustomerArrayList().add(new customer(name, age, id)); hotelArrayList.get(4).getCustomerArrayList().add(new customer(name, age, id)); } } catch (Exception ex) { System.out.println("Exceeded number of people"); add(number, chose); } } private static void isRoomVip1(int number, int chose, String name, int age, int id) { try { if (number == 1) { hotelArrayList.get(3).getCustomerArrayList().add(new customer(name, age, id)); } else if (number == 2) { hotelArrayList.get(3).getCustomerArrayList().add(new customer(name, age, id)); hotelArrayList.get(3).getCustomerArrayList().add(new customer(name, age, id)); } } catch (Exception ex) { System.out.println("Exceeded number of people"); add(number, chose); } } private static void isRoomVip(int number, int chose, String name, int age, int id) { try { if (number == 1) { hotelArrayList.get(2).getCustomerArrayList().add(new customer(name, age, id)); } else if (number == 2) { hotelArrayList.get(2).getCustomerArrayList().add(new customer(name, age, id)); hotelArrayList.get(2).getCustomerArrayList().add(new customer(name, age, id)); } } catch (Exception ex) { System.out.println("Exceeded number of people"); add(number, chose); } } private static void isRoomCheap(int number, int chose, String name, int age, int id) { try { if (number == 1) { hotelArrayList.get(1).getCustomerArrayList().add(new customer(name, age, id)); } else if (number == 2) { hotelArrayList.get(1).getCustomerArrayList().add(new customer(name, age, id)); hotelArrayList.get(1).getCustomerArrayList().add(new customer(name, age, id)); } } catch (Exception ex) { System.out.println("Exceeded number of people"); add(number, chose); } } private static void IsRoomNormal(int number, int chose, String name, int age, int id) { try { if (number == 1) { hotelArrayList.get(0).getCustomerArrayList().add(new customer(name, age, id)); } else if (number == 2) { hotelArrayList.get(0).getCustomerArrayList().add(new customer(name, age, id)); hotelArrayList.get(0).getCustomerArrayList().add(new customer(name, age, id)); } } catch (Exception ex) { System.out.println("Exceeded number of people"); add(number, chose); } } public static void delete(int id) { if (!checkRoom(id)) { for (Hotel hotel : hotelArrayList) { if (hotel.getId() == id) { hotel.getCustomerArrayList().clear(); } } } else { System.out.println("This room has no users"); } } public static void search(int id) { if (!checkRoom(id)) { for (Hotel hotel : hotelArrayList) { if (hotel.getId() == id) { for (int i = 0; i < hotelArrayList.get(i).getCustomerArrayList().size(); i++) { System.out.println("Name: "+hotelArrayList.get(i).getCustomerArrayList().get(i).getName()); System.out.println("Id: "+hotelArrayList.get(i).getCustomerArrayList().get(i).getId()); System.out.println("Age: "+hotelArrayList.get(i).getCustomerArrayList().get(i).getAge()); } break; } } } else { System.out.println("Room is not a users"); } } // public static void update() { // for (int i = 0; i < hotelArrayList.size(); i++) { // if (hotelArrayList.get(i).getCustomerArrayList().get(i).getId()) // } // } public static void ShowAll(){ System.out.println(hotelArrayList.toString()); } public static double priceCalculation(int id) { double price = 0; if (!checkRoom(id)){ System.out.println("Input Time Out"); for (int i = 0; i < hotelArrayList.size(); i++) { if (hotelArrayList.get(i).getId()==id){ hotelArrayList.get(i).setTimeOut(Sc.nextDouble()); price = (isResultTime(i) *(hotelArrayList.get(i).getPrice())); break; } } delete(id); } else { System.out.println("Room is not a User"); } return price; } private static double isResultTime(int i) { return hotelArrayList.get(i).getTimeOut() - hotelArrayList.get(i).getTimeIn(); } public static boolean checkRoom(int id) { boolean status = false; for (Hotel hotel : hotelArrayList) { if (hotel.getId() == id) { if (hotel.getCustomerArrayList().size() == 0) { status = true; break; } } } return status; } }
package com.cbsystematics.edu.internet_shop.service; import com.cbsystematics.edu.internet_shop.entity.Discount; import com.cbsystematics.edu.internet_shop.repository.IDiscountRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; @Service public class DiscountService { private final IDiscountRepository discountRepository; @Autowired public DiscountService(IDiscountRepository discountRepository) { this.discountRepository = discountRepository; } public Discount get(Integer id) { return discountRepository.get(id); } public Discount create(Discount discount) { return discountRepository.create(discount); } public Discount update(Discount discount) { return discountRepository.update(discount); } public void delete(Integer id) { discountRepository.delete(id); } public List<Discount> getAll() { return discountRepository.getAll(); } }
package com.example.forcatapp.Chat; import android.content.Intent; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import com.bumptech.glide.Glide; import com.bumptech.glide.request.RequestOptions; import com.example.forcatapp.R; import com.example.forcatapp.model.FriendModel; import com.example.forcatapp.model.UserModel; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.android.material.floatingactionbutton.FloatingActionButton; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener; import java.util.ArrayList; import java.util.List; public class FriendFragment extends Fragment { @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_friend,container,false); RecyclerView recyclerView = (RecyclerView)view.findViewById(R.id.friendfragment_recyclerview); recyclerView.setLayoutManager(new LinearLayoutManager(inflater.getContext())); recyclerView.setAdapter(new com.example.forcatapp.Chat.FriendFragment.FriendFragmentRecyclerViewAdapter()); FloatingActionButton floatingActionButton = (FloatingActionButton)view.findViewById(R.id.friendfragment_floatingButton); floatingActionButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { startActivity(new Intent(view.getContext(), SelectFriendActivity.class)); } }); return view; } class FriendFragmentRecyclerViewAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder>{ List<FriendModel> friendModels; //아이디가 추가되면 리사이클러뷰에 view아답터 형식으로 아이디 추가하고 새로고침 public FriendFragmentRecyclerViewAdapter() { friendModels= new ArrayList<>(); final String myUid= FirebaseAuth.getInstance().getCurrentUser().getUid(); FirebaseDatabase.getInstance().getReference().child("friends").child(myUid).addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { friendModels.clear(); for(DataSnapshot snapshot:dataSnapshot.getChildren()){ FriendModel friendModel = snapshot.getValue(FriendModel.class); friendModels.add(friendModel); } notifyDataSetChanged(); } @Override public void onCancelled(@NonNull DatabaseError error) { } }); // FirebaseDatabase.getInstance().getReference().child("friends").child(myUid).addValueEventListener(new ValueEventListener() { // @Override // public void onDataChange(@NonNull DataSnapshot dataSnapshot) { // friendModels.clear(); // // final String myUid = FirebaseAuth.getInstance().getCurrentUser().getUid(); // for(DataSnapshot snapshot :dataSnapshot.getChildren()){ // // FriendModel friendModel = snapshot.getValue(FriendModel.class); // // friendModels.add(friendModel); // } // notifyDataSetChanged();//새로고침 // } // // @Override // public void onCancelled(@NonNull DatabaseError error) { // // } // }); } @NonNull @Override public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_friend_list,parent,false); return new com.example.forcatapp.Chat.FriendFragment.FriendFragmentRecyclerViewAdapter.CustomViewHolder(view); } @Override public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) { if(friendModels.size()>0) { FirebaseDatabase.getInstance().getReference().child("users").child(friendModels.get(position).friendUid).addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { if (dataSnapshot.exists()) { UserModel userModel = dataSnapshot.getValue(UserModel.class); Glide.with (holder.itemView.getContext()) //이미지넣기 .load(userModel.profileImageUrl.toString()) .apply(new RequestOptions().circleCrop()) .into(((com.example.forcatapp.Chat.FriendFragment.FriendFragmentRecyclerViewAdapter.CustomViewHolder) holder).imageView); //유저이름 넣기 ((com.example.forcatapp.Chat.FriendFragment.FriendFragmentRecyclerViewAdapter.CustomViewHolder) holder).textView.setText(userModel.userName); //상태메세지 넣기 if (userModel.comment != null) { ((com.example.forcatapp.Chat.FriendFragment.FriendFragmentRecyclerViewAdapter.CustomViewHolder) holder).textView_comment.setText(userModel.comment); } } } @Override public void onCancelled(@NonNull DatabaseError error) { } }); } //이미지랑 유저이름 넣기 holder.itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(view.getContext(), MessageActivity.class); intent.putExtra("destinationUid",friendModels.get(position).friendUid); startActivity(intent); } }); } @Override public int getItemCount() { return friendModels.size(); } private class CustomViewHolder extends RecyclerView.ViewHolder { public ImageView imageView; public TextView textView; public TextView textView_comment; public CustomViewHolder(View view) { super(view); imageView=(ImageView) view.findViewById(R.id.friendlistitem_imageview); textView=(TextView) view.findViewById(R.id.friendlistitem_textview); textView_comment = (TextView)view.findViewById(R.id.friendlistitem_textview_comment); } } } }
package at.sync.model; import java.sql.Timestamp; import java.util.ArrayList; import java.util.List; import java.util.UUID; /** * Public transportation route */ public class TransportationRoute extends Entity implements IExternalReferenceable { private UUID id; private String name; private Timestamp validFrom; private Timestamp validUntil; private TransportationType type; private String operator; private String network; private String extRef; private String descriptionFrom; private String descriptionTo; private String description; private String routeNo; private List<Schedule> schedules = new ArrayList<>(); public TransportationRoute() { } public TransportationRoute(UUID id, String name, Timestamp validFrom, Timestamp validUntil, TransportationType type, String operator, String network, String extRef, String descriptionFrom, String descriptionTo, String description, String routeNo) { this.id = id; this.name = name; this.validFrom = validFrom; this.validUntil = validUntil; this.type = type; this.operator = operator; this.network = network; this.extRef = extRef; this.descriptionFrom = descriptionFrom; this.descriptionTo = descriptionTo; this.description = description; this.routeNo = routeNo; } public UUID getId() { return id; } public void setId(UUID id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Timestamp getValidFrom() { return validFrom; } public void setValidFrom(Timestamp validFrom) { this.validFrom = validFrom; } public Timestamp getValidUntil() { return validUntil; } public void setValidUntil(Timestamp validUntil) { this.validUntil = validUntil; } public TransportationType getType() { return type; } public void setType(TransportationType type) { this.type = type; } public String getOperator() { return operator; } public void setOperator(String operator) { this.operator = operator; } public String getNetwork() { return network; } public void setNetwork(String network) { this.network = network; } public String getExtRef() { return extRef; } public void setExtRef(String extRef) { this.extRef = extRef; } public String getDescriptionFrom() { return descriptionFrom; } public void setDescriptionFrom(String descriptionFrom) { this.descriptionFrom = descriptionFrom; } public String getDescriptionTo() { return descriptionTo; } public void setDescriptionTo(String descriptionTo) { this.descriptionTo = descriptionTo; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getRouteNo() { return routeNo; } public void setRouteNo(String routeNo) { this.routeNo = routeNo; } public List<Schedule> getSchedules() { return schedules; } public void setSchedules(List<Schedule> schedules) { this.schedules = schedules; } }
package com.legaoyi.message.rest; import java.io.File; import java.net.URLEncoder; import java.util.HashMap; import java.util.Map; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.lang3.StringUtils; import org.apache.commons.net.ftp.FTPClient; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import com.legaoyi.common.exception.BizProcessException; import com.legaoyi.common.util.Result; import com.legaoyi.gateway.message.model.DeviceHistoryMedia; import com.legaoyi.message.service.MessageService; import com.legaoyi.persistence.jpa.service.GeneralService; import com.legaoyi.platform.rest.BaseController; /** * @author gaoshengbo */ @RestController("mediaDataController") @RequestMapping(value = "/media", produces = {"application/json"}) public class MediaDataController extends BaseController { private static final Map<String, String> contentTypeMap = new HashMap<String, String>(); static { contentTypeMap.put("mp4", "video/mpeg4"); contentTypeMap.put("mp3", "audio/mp3"); contentTypeMap.put("wav", "audio/wav"); } @Autowired @Qualifier("messageService") private MessageService messageService; @Autowired @Qualifier("generalService") private GeneralService service; @RequestMapping(value = "/ftp/fileList/{id}", method = RequestMethod.GET) public Result getFtpFileList(@PathVariable String id) throws Exception { return new Result(messageService.getUploadFileList(id)); } @RequestMapping(value = "/ftp/download/{id}", method = RequestMethod.GET) public void download(@PathVariable String id, @RequestParam(required = false) String fileName, HttpServletRequest request, HttpServletResponse response) throws Exception { DeviceHistoryMedia deviceHistoryMedia = (DeviceHistoryMedia) service.get(DeviceHistoryMedia.ENTITY_NAME, id); if (deviceHistoryMedia == null || deviceHistoryMedia.getFilePath().endsWith(File.separator) && StringUtils.isBlank(fileName)) { throw new BizProcessException("非法请求,参数不合法"); } String filePath = deviceHistoryMedia.getFilePath(); if (!filePath.endsWith(File.separator)) { int index = filePath.lastIndexOf(File.separator) + 1; fileName = filePath.substring(index); filePath = filePath.substring(0, index); } FTPClient ftpClient = messageService.getFtpClient(); boolean bool = false; try { ftpClient.setControlEncoding("UTF-8"); // 中文支持 ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE); ftpClient.enterLocalPassiveMode(); String base = ftpClient.printWorkingDirectory(); if (ftpClient.changeWorkingDirectory(base.concat(filePath))) { response.setHeader("Content-Disposition", "attachment;filename*=UTF-8''" + URLEncoder.encode(fileName, "UTF-8")); String suffix = fileName.substring(fileName.lastIndexOf(".") + 1); response.setContentType(contentTypeMap.get(suffix.toLowerCase())); ServletOutputStream responseOutputStream = response.getOutputStream(); ftpClient.retrieveFile(fileName, responseOutputStream); responseOutputStream.flush(); bool = true; } } finally { ftpClient.logout(); } if (!bool) { throw new BizProcessException("下载失败"); } } }
package com.simplicity; import com.simplicity.Common; import java.io.*; import java.lang.reflect.Method; import java.net.URL; import java.net.URLClassLoader; import java.util.*; import java.util.jar.JarEntry; import java.util.jar.JarFile; import java.util.jar.JarInputStream; /** * */ public class Inspector { /** * * @return */ public static Inspector Create() { return new Inspector(); } /** * * @param targetJar * @return * @throws ClassNotFoundException * @throws IOException */ public Map<String, List<Method>> getMethodsInClasses(String targetJar) throws ClassNotFoundException, IOException { JarFile jarFile = new JarFile(targetJar); Enumeration<JarEntry> e = jarFile.entries(); URL[] urls = {new URL("jar:file:" + targetJar + "!/")}; URLClassLoader cl = URLClassLoader.newInstance(urls); Map<String, List<Method>> retval = new HashMap<String, List<Method>>(); while (e.hasMoreElements()) { JarEntry je = e.nextElement(); if (je.isDirectory() || !je.getName().endsWith(".class")) { continue; } // -6 because of .class String clsName = je.getName().substring(0, je.getName().length() - 6); clsName = clsName.toString().replace('/', '.'); Class c = cl.loadClass(clsName); retval.put(clsName, Arrays.asList(c.getMethods())); } return retval; } /*** * * @param ex * @return */ public static String extractExceptionDetails(Object ex) { String retval = ""; try { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); Exception jniEx = new Exception((Throwable) ex); jniEx.printStackTrace(pw); String stackTrace = sw.toString(); retval = String.format("Error: %s\nStackTrace: %s", jniEx.getMessage(), stackTrace); pw.close(); sw.close(); } catch(Exception e) { retval = "Unable to cast from JNI pointer - " + e.getCause().toString(); } return retval; } /** * * @param targetJar * @return * @throws IOException * @throws IllegalArgumentException */ public List<String> getClassesInJar(String targetJar) throws IOException, IllegalArgumentException { JarEntry jarEntry; List<String> retval = null; JarInputStream stream = null; if (!Common.IsNullOrEmpty(targetJar) && (new File(targetJar)).exists()) { try { retval = new ArrayList<String>(); stream = new JarInputStream(new FileInputStream(targetJar)); while ((jarEntry = stream.getNextJarEntry()) != null) { if (jarEntry.getName().endsWith(".class")) { String className = jarEntry.getName().replaceAll("/", "\\."); String newClassName = className.substring(0, className.lastIndexOf('.')); retval.add(newClassName); } } } catch (Exception ex) { retval = null; } finally { stream.close(); } } return retval; } /** * * @param s * @return * @throws Exception */ public static String addPath(String s) throws Exception { int before, after; File f = new File(s); URL u = f.toURL(); URLClassLoader urlClassLoader = (URLClassLoader) ClassLoader.getSystemClassLoader(); Class urlClass = URLClassLoader.class; Method method = urlClass.getDeclaredMethod("addURL", new Class[]{URL.class}); method.setAccessible(true); before = urlClassLoader.getURLs().length; method.invoke(urlClassLoader, new Object[]{u}); after = urlClassLoader.getURLs().length; return String.format("before:%d - after:%d", before, after); } }
/* * Created on 2004-12-2 * */ package com.aof.helpdesk.util; import java.sql.Connection; import java.sql.SQLException; import org.apache.log4j.Logger; /** * @author shilei * */ public class EmailUtil { static Logger log = Logger.getLogger(EmailUtil.class.getName()); static public boolean sendMail(final String email,final String title,final String content) throws SQLException { log.info("send email to:"+email); Connection conn=null; try { //conn=Database.getConn(); //CallableStatement call= conn.prepareCall("exec master..xp_sendmail @recipients=?, @subject=?, @message=?"); //call.setString(1,email); //call.setString(2,title); //call.setString(3,content); //return call.execute(); return true; } finally { if(conn!=null) { conn.close(); } } } }
package servlet; import bbdd.Pelicula; import bbdd.Proxy; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; /** * * @author jesus */ public class modificarPelicula extends HttpServlet { /** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); HttpSession sesion = request.getSession(); //Obtenemos los datos de la pelicula String nombre = request.getParameter("idPelicula"); String sinopsis = request.getParameter("sinopsis"); String pagina = request.getParameter("pagina"); String titulo = request.getParameter("titulo"); String genero = request.getParameter("genero"); String nacionalidad = request.getParameter("nacionalidad"); int duracion = Integer.valueOf(request.getParameter("duracion")); int ano = Integer.valueOf(request.getParameter("ano")); String distribuidora = request.getParameter("distribuidora"); String director = request.getParameter("director"); int clasificaicon = Integer.valueOf(request.getParameter("clasificacion")); String otros = request.getParameter("otros"); //Creamos la pelicula Pelicula pelicula = new Pelicula(); pelicula.setNombre(nombre); pelicula.setSinopsis(sinopsis); pelicula.setPagina(pagina); pelicula.setTitulo(titulo); pelicula.setGenero(genero); pelicula.setNacionalidad(nacionalidad); pelicula.setDuracion(duracion); pelicula.setAno(ano); pelicula.setDistribuidora(distribuidora); pelicula.setDirector(director); pelicula.setClasificacion(clasificaicon); pelicula.setOtros(otros); //Ahora lo modificamos Proxy bd = Proxy.getInstancia(); bd.modificarPelicula(pelicula); //Volvemos a la pelicula sesion.setAttribute("peliculaId", nombre); response.sendRedirect(response.encodeRedirectURL("/PracticaFinalWeb/pelicula.jsp")); } // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code."> /** * Handles the HTTP <code>GET</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Handles the HTTP <code>POST</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Returns a short description of the servlet. * * @return a String containing servlet description */ @Override public String getServletInfo() { return "Short description"; }// </editor-fold> }
package com.pwq.ThreadPool; import com.pwq.mavenT.TryTest; import org.junit.Test; import java.util.concurrent.Executor; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; /** * @Author:WenqiangPu * @Description * @Date:Created in 18:49 2017/8/1 * @Modified By: */ public class ThreadPoolTest { public static void main(String[] args) { System.out.println(Thread.activeCount()); ExecutorService executorService = Executors.newFixedThreadPool(10); System.out.println(Thread.activeCount()); System.out.println("-------"); WorkThread workThread = new WorkThread(); WorkThread workThread1 = new WorkThread(); for (int i = 0; i < 10; i++) { executorService.execute(new ThreadPool()); System.out.println("************* a" + i + " *************"); } executorService.shutdown(); // executorService.execute(new TestRunnable()); // executorService.execute(new TestRunnable()); System.out.println("我他妈已经结束了,你们2个干嘛"); // executorService.shutdown(); System.out.println(Thread.activeCount()); System.out.println(Thread.currentThread().getName()); System.out.println(Thread.activeCount()); executorService.shutdown(); } }
package DAO; import SQL.PostgreSQLJDBC; import models.Student; import models.User; import java.sql.Date; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; public class CookieDAO { private PostgreSQLJDBC postgreSQLJDBC = new PostgreSQLJDBC(); PreparedStatement preparedStatement = null; ResultSet resultSet = null; public User getUserByCookieSessionId(String cookieSessionId) { String orderToSql = "SELECT u.id, ud.login, ud.password, ud.first_name, ud.last_name, u.is_active, u.user_type_id FROM cookies as c JOIN users as u on u.id = c.user_id JOIN user_details as ud on u.user_details_id = ud.id WHERE c.sesion_id = ?"; User user = null; try { preparedStatement = postgreSQLJDBC.connect().prepareStatement(orderToSql); System.out.println(" getUserByCookieSesionId"); preparedStatement.setString(1, cookieSessionId); resultSet = preparedStatement.executeQuery(); if (resultSet.next()){ System.out.println("test"); int id = resultSet.getInt("id"); String login = resultSet.getString("login"); String password = resultSet.getString("password"); int userTypeId = resultSet.getInt("user_type_id"); boolean isActive = resultSet.getBoolean("is_active"); String firstName = resultSet.getString("first_name"); String lastName = resultSet.getString("last_name"); System.out.println(id+ "| " + login+ "| " + password+ "| " + userTypeId+ "| " + firstName+ "| " + lastName); user = new Student(id, login, password, userTypeId, isActive, firstName, lastName); } preparedStatement.executeQuery(); preparedStatement.close(); postgreSQLJDBC.disconnect(); }catch (SQLException e) { System.out.println(e); } postgreSQLJDBC.disconnect(); return user; } public Date getCookieExpireDate(String cookieSessionId) { String orderToSql = "SELECT c.expire_date FROM cookies as c JOIN users as u on u.id = c.user_id WHERE c.sesion_id = ?"; Date date = null; try { preparedStatement = postgreSQLJDBC.connect().prepareStatement(orderToSql); System.out.println(" getCookieExpireDate"); preparedStatement.setString(1, cookieSessionId); resultSet = preparedStatement.executeQuery(); if (resultSet.next()){ date = resultSet.getDate("expire_date"); postgreSQLJDBC.disconnect(); return date; } preparedStatement.executeQuery(); preparedStatement.close(); postgreSQLJDBC.disconnect(); }catch (SQLException e) { System.out.println(e); } postgreSQLJDBC.disconnect(); return date; } public void setNewExpireDateForCookie(String cookieSessionId, Date expireDate) { PostgreSQLJDBC postgreSQLJDBC = new PostgreSQLJDBC(); String orderForSql = ("UPDATE cookies SET expire_date = ? WHERE sesion_id = ? "); try { preparedStatement = postgreSQLJDBC.connect().prepareStatement(orderForSql); System.out.println(" setNewExpireDate"); preparedStatement.setDate(1, expireDate); preparedStatement.setString(2, cookieSessionId); preparedStatement.executeUpdate(); preparedStatement.close(); postgreSQLJDBC.disconnect(); } catch (SQLException e) { System.out.println(e); } postgreSQLJDBC.disconnect(); } public void putNewCookieToDB(String cookieSessionIdToAdd) { System.out.println("test3"); String sqlQuery = "INSERT INTO cookies (sesion_id, expire_date, user_id) VALUES(?, ?, null )"; try { preparedStatement = postgreSQLJDBC.connect().prepareStatement(sqlQuery); System.out.println(" putNewCookieToDB"); preparedStatement.setString(1, cookieSessionIdToAdd); preparedStatement.setDate(2, null); preparedStatement.executeUpdate(); preparedStatement.close(); postgreSQLJDBC.disconnect(); } catch (SQLException e) { e.printStackTrace(); } postgreSQLJDBC.disconnect(); } public void putUserIdToCookieInDB(int userId, String cookieSessionId) { PostgreSQLJDBC postgreSQLJDBC = new PostgreSQLJDBC(); String orderForSql = ("UPDATE cookies SET user_id = ? WHERE sesion_id = ? "); try { preparedStatement = postgreSQLJDBC.connect().prepareStatement(orderForSql); System.out.println(" putUserIdToCookieInDB"); preparedStatement.setInt(1, userId); preparedStatement.setString(2, cookieSessionId); preparedStatement.executeUpdate(); preparedStatement.close(); postgreSQLJDBC.disconnect(); } catch (SQLException e) { System.out.println(e); } postgreSQLJDBC.disconnect(); } public void setCookieForLogout(String cookieSessionId) { PostgreSQLJDBC postgreSQLJDBC = new PostgreSQLJDBC(); String orderForSql = ("UPDATE cookies SET expire_date = ? WHERE sesion_id = ? "); try { preparedStatement = postgreSQLJDBC.connect().prepareStatement(orderForSql); System.out.println(" setCookieForLogout"); preparedStatement.setDate(1, null); preparedStatement.setString(2, cookieSessionId); preparedStatement.executeUpdate(); preparedStatement.close(); postgreSQLJDBC.disconnect(); } catch (SQLException e) { System.out.println(e); } postgreSQLJDBC.disconnect(); } }
package com.blurack.fragments; import android.Manifest; import android.app.Activity; import android.content.pm.PackageManager; import android.graphics.Color; import android.location.Location; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.content.ContextCompat; import android.util.Log; import android.view.View; import com.blurack.AppController; import com.google.android.gms.maps.CameraUpdate; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.OnMapReadyCallback; import com.google.android.gms.maps.SupportMapFragment; import com.google.android.gms.maps.model.CameraPosition; import com.google.android.gms.maps.model.Circle; import com.google.android.gms.maps.model.CircleOptions; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.Marker; import com.google.android.gms.maps.model.MarkerOptions; /** * Created by RK on 19/04/16. */ public class LocationMapFragment extends SupportMapFragment implements OnMapReadyCallback,AppController.onLocationUpdateListener { public static LocationMapFragment newInstance() { Bundle args = new Bundle(); LocationMapFragment fragment = new LocationMapFragment(); fragment.setArguments(args); return fragment; } private GoogleMap mMap; private Marker currentMarker; @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); getMapAsync(this); } /** * Manipulates the map once available. * This callback is triggered when the map is ready to be used. * This is where we can add markers or lines, add listeners or move the camera. In this case, * we just add a marker near Sydney, Australia. * If Google Play services is not installed on the device, the user will be prompted to install * it inside the SupportMapFragment. This method will only be triggered once the user has * installed Google Play services and returned to the app. */ @Override public void onMapReady(GoogleMap googleMap) { mMap = googleMap; if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) { mMap.setMyLocationEnabled(true); } } @Override public void onAttach(Activity activity) { super.onAttach(activity); AppController.getInstance().setFragmentLocationAwareListener(this); } @Override public void onLocationUpdate(Location mCurrentLocation) { if(mCurrentLocation!=null) { Log.e("Loc","Location updated: "+mCurrentLocation.getLatitude()); LatLng sydney = new LatLng(mCurrentLocation.getLatitude(), mCurrentLocation.getLongitude()); // Add a marker in Sydney and move the camera if (mMap != null) { if (currentMarker != null) { currentMarker.remove(); } currentMarker = mMap.addMarker(new MarkerOptions().position(sydney).title("Current Location")); // CameraUpdate zoom=CameraUpdateFactory.zoomTo(16); mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney)); Circle circle = mMap.addCircle(new CircleOptions().center(sydney).radius(24140.2).strokeColor(Color.RED)); circle.setVisible(true); int zoomLevel = getZoomLevel(circle); CameraPosition cameraPosition = new CameraPosition.Builder() .target(sydney) // Sets the center of the map to Mountain View .zoom(zoomLevel) // Sets the zoom .bearing(90) // Sets the orientation of the camera to east .tilt(30) // Sets the tilt of the camera to 30 degrees .build(); // Creates a CameraPosition from the builder mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition)); } } } public int getZoomLevel(Circle circle) { int zoomLevel = 16; if (circle != null){ double radius = circle.getRadius(); double scale = radius / 500; zoomLevel =(int) (16 - Math.log(scale) / Math.log(2)); } return zoomLevel; } }
package com.example.demo; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.web.bind.annotation.RequestMapping; @SpringBootApplication public class Application { @RequestMapping("hello") public void hello(){ System.out.println("Welcome"); } public static void main(String[] args) { SpringApplication.run(Application.class, args); } //-Dspring.profile.active=PROD }
package rmi.chat.inf; import java.rmi.Remote; import java.rmi.RemoteException; // 서버용 interface public interface IChat extends Remote{ // 접속한 클라이언트 객체를 List에 추가하는 메서드 (클라이언트의 정보를 IChatClient를 받겠다는 거 ) public void setClient(IChatClient client) throws RemoteException; // 한 클라이언트가 보낸 메세지를 서버에 접속된 모든 클라이언트에게 메시지를 전달하는 메서드 public void setMessage(String msg) throws RemoteException; }
package pruebasUnitarias.pruebasArmas; import objetos.aeronaves.enemigos.Caza; import objetos.armas.LaserCannon; import objetos.proyectiles.LaserShoot; import org.junit.*; public class LaserCannonTest { Caza caza = new Caza(); LaserCannon laser = new LaserCannon(caza, true); LaserCannon laserDesactivado = new LaserCannon(caza, false); LaserShoot laserShot; @Test public void disparar() { laserShot = laser.disparar(); Assert.assertNotNull(laserShot); Assert.assertTrue(laserShot.getOrigen() == caza); System.out.println("El canion laser dispara bien"); } @Test public void disararDesactivado() { laserShot = laserDesactivado.disparar(); Assert.assertTrue(laserShot == null); System.out .println("El cannon laser no dispara cuando esta desactivado"); } }
package com.example.cape_medics; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.CheckBox; import android.widget.EditText; import android.widget.ImageView; import android.widget.ScrollView; import android.widget.Spinner; import android.widget.TextView; import android.widget.Toast; import com.github.aakira.expandablelayout.ExpandableRelativeLayout; import org.json.JSONException; import org.json.JSONObject; import java.util.Arrays; import java.util.Iterator; import java.util.List; public class VitalSigns extends Fragment { ExpandableRelativeLayout expandableRelativeLayout1, expandableRelativeLayout2,expandableRelativeLayout3, expandableRelativeLayout4; Button button1,button2,button3, button4; private ImageView imageView15; private CheckBox chkNA; private Button expBut1; private ScrollView scrl1; private ExpandableRelativeLayout expLay1; private TextView lblTime1; private EditText edtTime1; private TextView lblPulse1; private EditText edtPulse1; private TextView lblBp1; private EditText edtBp1; private TextView lblSpo1; private EditText edtSpo1; private TextView lblResp1; private EditText edtResp1; private TextView lblHgt1; private EditText edtHgt1; private TextView lblCO21; private EditText edtCO21; private TextView lblFlow1; private EditText edtFlow1; private TextView lblPearl1; private CheckBox chkLeft1; private CheckBox chkRight1; private TextView lblPupSize1; private TextView lblPupLeft1; private TextView lblPupRight1; private Spinner spnLeftSize1; private Spinner spnRightSize1; private Button expBut2; private ScrollView scrl2; private ExpandableRelativeLayout expLay2; private TextView lblTime2; private EditText edtTime2; private TextView lblPulse2; private EditText edtPulse2; private TextView lblBp2; private EditText edtBp2; private TextView lblSpo2; private EditText edtSpo2; private TextView lblResp2; private EditText edtResp2; private TextView lblHgt2; private EditText edtHgt2; private TextView lblCO22; private EditText edtCO22; private TextView lblFlow2; private EditText edtFlow2; private TextView lblPearl2; private CheckBox chkLeft2; private CheckBox chkRight2; private TextView lblPupSize2; private TextView lblPupLeft2; private TextView lblPupRight2; private Spinner spnLeftSize2; private Spinner spnRightSize2; private Button expBut3; private ScrollView scrl3; private ExpandableRelativeLayout expLay3; private TextView lblTime3; private EditText edtTime3; private TextView lblPulse3; private EditText edtPulse3; private TextView lblBp3; private EditText edtBp3; private TextView lblSpo3; private EditText edtSpo3; private TextView lblResp3; private EditText edtResp3; private TextView lblHgt3; private EditText edtHgt3; private TextView lblCO23; private EditText edtCO23; private TextView lblFlow3; private EditText edtFlow3; private TextView lblPearl3; private CheckBox chkLeft3; private CheckBox chkRight3; private TextView lblPupSize3; private TextView lblPupLeft3; private TextView lblPupRight3; private Spinner spnLeftSize3; private Spinner spnRightSize3; private Button expBut4; private ExpandableRelativeLayout expLay4; private TextView lblTime4; private EditText edtTime4; private TextView lblPulse4; private EditText edtPulse4; private TextView lblBp4; private EditText edtBp4; private TextView lblSpo4; private EditText edtSpo4; private TextView lblResp4; private EditText edtResp4; private TextView lblHgt4; private EditText edtHgt4; private TextView lblCO24; private EditText edtCO24; private TextView lblFlow4; private EditText edtFlow4; private TextView lblPearl4; private CheckBox chkLeft4; private CheckBox chkRight4; private TextView lblPupSize4; private TextView lblPupLeft4; private TextView lblPupRight4; private Spinner spnLeftSize4; private Spinner spnRightSize4; JSONObject vitalSigns; List<CheckBox> checkBoxList; Cache cache; String saved; JSONObject load; public VitalSigns() { // Required empty public constructor } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View view = inflater.inflate(R.layout.fragment_vital_signs, container, false); expandableRelativeLayout1 = (ExpandableRelativeLayout) view.findViewById(R.id.expLay1); expandableRelativeLayout2 = (ExpandableRelativeLayout) view.findViewById(R.id.expLay2); expandableRelativeLayout3 = (ExpandableRelativeLayout) view.findViewById(R.id.expLay3); expandableRelativeLayout4 = (ExpandableRelativeLayout) view.findViewById(R.id.expLay4); button1 = view.findViewById(R.id.expBut1); button2 = view.findViewById(R.id.expBut2); button3 = view.findViewById(R.id.expBut3); button4 = view.findViewById(R.id.expBut4); button1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { expandableRelativeLayout1.toggle(); } }); button2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { expandableRelativeLayout2.toggle(); } }); button3.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { expandableRelativeLayout3.toggle(); } }); button4.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { expandableRelativeLayout4.toggle(); } }); imageView15 = (ImageView)view.findViewById( R.id.imageView15 ); chkNA = (CheckBox)view.findViewById( R.id.chkNA ); expBut1 = (Button)view.findViewById( R.id.expBut1 ); scrl1 = (ScrollView)view.findViewById( R.id.scrl1 ); expLay1 = (ExpandableRelativeLayout)view.findViewById( R.id.expLay1 ); lblTime1 = (TextView)view.findViewById( R.id.lblTime1 ); edtTime1 = (EditText)view.findViewById( R.id.edtTime1 ); lblPulse1 = (TextView)view.findViewById( R.id.lblPulse1 ); edtPulse1 = (EditText)view.findViewById( R.id.edtPulse1 ); lblBp1 = (TextView)view.findViewById( R.id.lblBp1 ); edtBp1 = (EditText)view.findViewById( R.id.edtBp1 ); lblSpo1 = (TextView)view.findViewById( R.id.lblSpo1 ); edtSpo1 = (EditText)view.findViewById( R.id.edtSpo1 ); lblResp1 = (TextView)view.findViewById( R.id.lblResp1 ); edtResp1 = (EditText)view.findViewById( R.id.edtResp1 ); lblHgt1 = (TextView)view.findViewById( R.id.lblHgt1 ); edtHgt1 = (EditText)view.findViewById( R.id.edtHgt1 ); lblCO21 = (TextView)view.findViewById( R.id.lblCO21 ); edtCO21 = (EditText)view.findViewById( R.id.edtCO21 ); lblFlow1 = (TextView)view.findViewById( R.id.lblFlow1 ); edtFlow1 = (EditText)view.findViewById( R.id.edtFlow1 ); lblPearl1 = (TextView)view.findViewById( R.id.lblPearl1 ); chkLeft1 = (CheckBox)view.findViewById( R.id.chkLeft1 ); chkRight1 = (CheckBox)view.findViewById( R.id.chkRight1 ); lblPupSize1 = (TextView)view.findViewById( R.id.lblPupSize1 ); lblPupLeft1 = (TextView)view.findViewById( R.id.lblPupLeft1 ); lblPupRight1 = (TextView)view.findViewById( R.id.lblPupRight1 ); spnLeftSize1 = (Spinner)view.findViewById( R.id.spnLeftSize1 ); spnRightSize1 = (Spinner)view.findViewById( R.id.spnRightSize1 ); expBut2 = (Button)view.findViewById( R.id.expBut2 ); scrl2 = (ScrollView)view.findViewById( R.id.scrl2 ); expLay2 = (ExpandableRelativeLayout)view.findViewById( R.id.expLay2 ); lblTime2 = (TextView)view.findViewById( R.id.lblTime2 ); edtTime2 = (EditText)view.findViewById( R.id.edtTime2 ); lblPulse2 = (TextView)view.findViewById( R.id.lblPulse2 ); edtPulse2 = (EditText)view.findViewById( R.id.edtPulse2 ); lblBp2 = (TextView)view.findViewById( R.id.lblBp2 ); edtBp2 = (EditText)view.findViewById( R.id.edtBp2 ); lblSpo2 = (TextView)view.findViewById( R.id.lblSpo2 ); edtSpo2 = (EditText)view.findViewById( R.id.edtSpo2 ); lblResp2 = (TextView)view.findViewById( R.id.lblResp2 ); edtResp2 = (EditText)view.findViewById( R.id.edtResp2 ); lblHgt2 = (TextView)view.findViewById( R.id.lblHgt2 ); edtHgt2 = (EditText)view.findViewById( R.id.edtHgt2 ); lblCO22 = (TextView)view.findViewById( R.id.lblCO22 ); edtCO22 = (EditText)view.findViewById( R.id.edtCO22 ); lblFlow2 = (TextView)view.findViewById( R.id.lblFlow2 ); edtFlow2 = (EditText)view.findViewById( R.id.edtFlow2 ); lblPearl2 = (TextView)view.findViewById( R.id.lblPearl2 ); chkLeft2 = (CheckBox)view.findViewById( R.id.chkLeft2 ); chkRight2 = (CheckBox)view.findViewById( R.id.chkRight2 ); lblPupSize2 = (TextView)view.findViewById( R.id.lblPupSize2 ); lblPupLeft2 = (TextView)view.findViewById( R.id.lblPupLeft2 ); lblPupRight2 = (TextView)view.findViewById( R.id.lblPupRight2 ); spnLeftSize2 = (Spinner)view.findViewById( R.id.spnLeftSize2 ); spnRightSize2 = (Spinner)view.findViewById( R.id.spnRightSize2 ); expBut3 = (Button)view.findViewById( R.id.expBut3 ); scrl3 = (ScrollView)view.findViewById( R.id.scrl3 ); expLay3 = (ExpandableRelativeLayout)view.findViewById( R.id.expLay3 ); lblTime3 = (TextView)view.findViewById( R.id.lblTime3 ); edtTime3 = (EditText)view.findViewById( R.id.edtTime3 ); lblPulse3 = (TextView)view.findViewById( R.id.lblPulse3 ); edtPulse3 = (EditText)view.findViewById( R.id.edtPulse3 ); lblBp3 = (TextView)view.findViewById( R.id.lblBp3 ); edtBp3 = (EditText)view.findViewById( R.id.edtBp3 ); lblSpo3 = (TextView)view.findViewById( R.id.lblSpo3 ); edtSpo3 = (EditText)view.findViewById( R.id.edtSpo3 ); lblResp3 = (TextView)view.findViewById( R.id.lblResp3 ); edtResp3 = (EditText)view.findViewById( R.id.edtResp3 ); lblHgt3 = (TextView)view.findViewById( R.id.lblHgt3 ); edtHgt3 = (EditText)view.findViewById( R.id.edtHgt3 ); lblCO23 = (TextView)view.findViewById( R.id.lblCO23 ); edtCO23 = (EditText)view.findViewById( R.id.edtCO23 ); lblFlow3 = (TextView)view.findViewById( R.id.lblFlow3 ); edtFlow3 = (EditText)view.findViewById( R.id.edtFlow3 ); lblPearl3 = (TextView)view.findViewById( R.id.lblPearl3 ); chkLeft3 = (CheckBox)view.findViewById( R.id.chkLeft3 ); chkRight3 = (CheckBox)view.findViewById( R.id.chkRight3 ); lblPupSize3 = (TextView)view.findViewById( R.id.lblPupSize3 ); lblPupLeft3 = (TextView)view.findViewById( R.id.lblPupLeft3 ); lblPupRight3 = (TextView)view.findViewById( R.id.lblPupRight3 ); spnLeftSize3 = (Spinner)view.findViewById( R.id.spnLeftSize3 ); spnRightSize3 = (Spinner)view.findViewById( R.id.spnRightSize3 ); expBut4 = (Button)view.findViewById( R.id.expBut4 ); expLay4 = (ExpandableRelativeLayout)view.findViewById( R.id.expLay4 ); lblTime4 = (TextView)view.findViewById( R.id.lblTime4 ); edtTime4 = (EditText)view.findViewById( R.id.edtTime4 ); lblPulse4 = (TextView)view.findViewById( R.id.lblPulse4 ); edtPulse4 = (EditText)view.findViewById( R.id.edtPulse4 ); lblBp4 = (TextView)view.findViewById( R.id.lblBp4 ); edtBp4 = (EditText)view.findViewById( R.id.edtBp4 ); lblSpo4 = (TextView)view.findViewById( R.id.lblSpo4 ); edtSpo4 = (EditText)view.findViewById( R.id.edtSpo4 ); lblResp4 = (TextView)view.findViewById( R.id.lblResp4 ); edtResp4 = (EditText)view.findViewById( R.id.edtResp4 ); lblHgt4 = (TextView)view.findViewById( R.id.lblHgt4 ); edtHgt4 = (EditText)view.findViewById( R.id.edtHgt4 ); lblCO24 = (TextView)view.findViewById( R.id.lblCO24 ); edtCO24 = (EditText)view.findViewById( R.id.edtCO24 ); lblFlow4 = (TextView)view.findViewById( R.id.lblFlow4 ); edtFlow4 = (EditText)view.findViewById( R.id.edtFlow4 ); lblPearl4 = (TextView)view.findViewById( R.id.lblPearl4 ); chkLeft4 = (CheckBox)view.findViewById( R.id.chkLeft4 ); chkRight4 = (CheckBox)view.findViewById( R.id.chkRight4 ); lblPupSize4 = (TextView)view.findViewById( R.id.lblPupSize4 ); lblPupLeft4 = (TextView)view.findViewById( R.id.lblPupLeft4 ); lblPupRight4 = (TextView)view.findViewById( R.id.lblPupRight4 ); spnLeftSize4 = (Spinner)view.findViewById( R.id.spnLeftSize4 ); spnRightSize4 = (Spinner)view.findViewById( R.id.spnRightSize4 ); checkBoxList = Arrays.asList(chkLeft1,chkLeft2,chkLeft3,chkLeft4,chkRight1,chkRight2,chkRight3,chkRight4); cache = new Cache(getContext()); saved = cache.getStringProperty("vitalSigns"); if(saved != null ){ try { load = new JSONObject(saved); edtTime1.setText(vitalSigns.getString("Time1")); edtPulse1.setText(vitalSigns.getString("Pulse1")); edtBp1.setText(vitalSigns.getString("BP1")); edtSpo1.setText(vitalSigns.getString("spo21")); edtResp1.setText(vitalSigns.getString("resp1")); edtHgt1.setText(vitalSigns.getString("hgt1")); edtCO21.setText(vitalSigns.getString("co21")); edtFlow1.setText(vitalSigns.getString("peak1")); edtTime2.setText(vitalSigns.getString("Time2")); edtPulse2.setText(vitalSigns.getString("Pulse2")); edtBp2.setText(vitalSigns.getString("BP2")); edtSpo2.setText(vitalSigns.getString("spo22")); edtResp2.setText(vitalSigns.getString("resp2")); edtHgt2.setText(vitalSigns.getString("hgt2")); edtCO22.setText(vitalSigns.getString("co22")); edtFlow2.setText(vitalSigns.getString("peak2")); edtTime3.setText(vitalSigns.getString("Time3")); edtPulse3.setText(vitalSigns.getString("Pulse3")); edtBp3.setText(vitalSigns.getString("BP3")); edtSpo3.setText(vitalSigns.getString("spo23")); edtResp3.setText(vitalSigns.getString("resp3")); edtHgt3.setText(vitalSigns.getString("hgt3")); edtCO23.setText(vitalSigns.getString("co23")); edtFlow3.setText(vitalSigns.getString("peak3")); edtTime4.setText(vitalSigns.getString("Time4")); edtPulse4.setText(vitalSigns.getString("Pulse4")); edtBp4.setText(vitalSigns.getString("BP4")); edtSpo4.setText(vitalSigns.getString("spo24")); edtResp4.setText(vitalSigns.getString("resp4")); edtHgt4.setText(vitalSigns.getString("hgt4")); edtCO24.setText(vitalSigns.getString("co24")); edtFlow4.setText(vitalSigns.getString("peak4")); Iterator<String> keys = load.keys(); while(keys.hasNext()) { String key = keys.next(); String item = load.getString(key); for (int j = 0; j<checkBoxList.size();j++) { if (checkBoxList.get(j) != null) { if (item.equals(checkBoxList.get(j).getText().toString())) { checkBoxList.get(j).setChecked(true); } } } } } catch (JSONException e) { e.printStackTrace(); } } return view; } public JSONObject createJson(){ vitalSigns = new JSONObject(); String time1 = edtTime1.getText().toString(); String pulse1 = edtPulse1.getText().toString(); String BP1 = edtBp1.getText().toString(); String spo21 =edtSpo1.getText().toString(); String resp1 = edtResp1.getText().toString(); String hgt1 = edtHgt1.getText().toString(); String co21 = edtCO21.getText().toString(); String peak1 = edtFlow1.getText().toString(); String checkedLeft1 = null; if (chkLeft1.isChecked()){ checkedLeft1 = chkLeft1.getText().toString(); } String checkedRight1 = null; if(chkRight1.isChecked()){ checkedRight1 = chkRight1.getText().toString(); } try{ vitalSigns.put("Time1",time1); vitalSigns.put("Pulse1",pulse1); vitalSigns.put("BP1",BP1); vitalSigns.put("spo21",spo21); vitalSigns.put("resp1",resp1); vitalSigns.put("hgt1",hgt1); vitalSigns.put("co21",co21); vitalSigns.put("peak1",peak1); }catch (Exception e){ Toast.makeText(getContext(),e.getMessage(),Toast.LENGTH_SHORT).show(); } String time2 = edtTime2.getText().toString(); String pulse2 = edtPulse2.getText().toString(); String BP2 = edtBp2.getText().toString(); String spo22 =edtSpo2.getText().toString(); String resp2 = edtResp2.getText().toString(); String hgt2 = edtHgt2.getText().toString(); String co22 = edtCO22.getText().toString(); String peak2 = edtFlow2.getText().toString(); String checkedLeft2 = null; if (chkLeft2.isChecked()){ checkedLeft2 = chkLeft2.getText().toString(); } String checkedRight2 = null; if(chkRight2.isChecked()){ checkedRight2 = chkRight2.getText().toString(); } try{ vitalSigns.put("Time2",time2); vitalSigns.put("Pulse2",pulse2); vitalSigns.put("BP2",BP2); vitalSigns.put("spo22",spo22); vitalSigns.put("resp2",resp2); vitalSigns.put("hgt2",hgt2); vitalSigns.put("co22",co22); vitalSigns.put("peak2",peak2); }catch (Exception e){ Toast.makeText(getContext(),e.getMessage(),Toast.LENGTH_SHORT).show(); } String time3 = edtTime3.getText().toString(); String pulse3 = edtPulse3.getText().toString(); String BP3 = edtBp3.getText().toString(); String spo23 =edtSpo3.getText().toString(); String resp3 = edtResp3.getText().toString(); String hgt3= edtHgt3.getText().toString(); String co23 = edtCO23.getText().toString(); String peak3 = edtFlow3.getText().toString(); String checkedLeft3 = null; if (chkLeft3.isChecked()){ checkedLeft3 = chkLeft3.getText().toString(); } String checkedRight3 = null; if(chkRight1.isChecked()){ checkedRight3 = chkRight3.getText().toString(); } try{ vitalSigns.put("Time3",time3); vitalSigns.put("Pulse3",pulse3); vitalSigns.put("BP3",BP3); vitalSigns.put("spo23",spo23); vitalSigns.put("resp3",resp3); vitalSigns.put("hgt3",hgt3); vitalSigns.put("co23",co23); vitalSigns.put("peak3",peak3); }catch (Exception e){ Toast.makeText(getContext(),e.getMessage(),Toast.LENGTH_SHORT).show(); } String time4= edtTime4.getText().toString(); String pulse4 = edtPulse4.getText().toString(); String BP4 = edtBp4.getText().toString(); String spo24 =edtSpo4.getText().toString(); String resp4 = edtResp4.getText().toString(); String hgt4 = edtHgt4.getText().toString(); String co24 = edtCO24.getText().toString(); String peak4 = edtFlow4.getText().toString(); String checkedLeft4 = null; if (chkLeft4.isChecked()){ checkedLeft4 = chkLeft4.getText().toString(); } String checkedRight4 = null; if(chkRight4.isChecked()){ checkedRight4 = chkRight4.getText().toString(); } try{ vitalSigns.put("Time4",time4); vitalSigns.put("Pulse4",pulse4); vitalSigns.put("BP4",BP4); vitalSigns.put("spo24",spo24); vitalSigns.put("resp4",resp4); vitalSigns.put("hgt4",hgt4); vitalSigns.put("co24",co24); vitalSigns.put("peak4",peak4); }catch (Exception e){ Toast.makeText(getContext(),e.getMessage(),Toast.LENGTH_SHORT).show(); } cache.setStringProperty("vitalSigns",vitalSigns.toString()); return vitalSigns; } }
/* ObjectState -- a class within the Cellular Automaton Explorer. Copyright (C) 2005 David B. Bahr (http://academic.regis.edu/dbahr/) This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package cellularAutomata.cellState.model; import java.util.Random; import javax.swing.JOptionPane; import cellularAutomata.CAController; import cellularAutomata.CurrentProperties; import cellularAutomata.graphics.InitialStatesPanel; import cellularAutomata.reflection.ReflectionTool; import cellularAutomata.rules.templates.ObjectRuleTemplate; import cellularAutomata.util.math.RandomSingleton; /** * A cell state for a cellular automaton with arbitrary objects as states. * * @author David Bahr */ public class ObjectState extends CellState { // random generator private static Random random = RandomSingleton.getInstance(); // the empty state private Object emptyState = new Object(); // The full state private Object fullState = new Object(); // The full state private Object alternateState = new Object(); // for speed we place this here. private Object state = new Object(); /** * Sets an Object as the initial state. * * @param state * Any arbitrary Object to be used as the state. * @param alternateState * The state that is an alternate to the full state (and drawn by * a right mouse click on the grid). Most commonly is set to the * same Object as the fullState. * @param emptyState * The state corresponding to a "blank". * @param fullState * The state corresponding to a filled cell. */ public ObjectState(Object state, Object alternateState, Object emptyState, Object fullState) { if(checkState(state) && checkState(emptyState) && checkState(fullState)) { // save here for fast access this.state = state; this.alternateState = alternateState; this.emptyState = emptyState; this.fullState = fullState; // set state using the method from the super class setValue(state); } } /** * Check that the state is not null. If is null, throws an exception. * * @param state * The state being checked. * @return true if the state is ok. * @throws IllegalArgumentException * if is null. */ private boolean checkState(Object state) { // check to be sure is not null. if(state == null) { throw new IllegalArgumentException( "Class: ObjectState. Method: checkState. The state is null, \n" + "which is not allowed."); } // if get here then is ok return true; } /** * Creates a SHALLOW copy of this cellState; this method must return a * different instance of the cell state, but with all the same values. * <p> * The intent is that, for any CellState x, the expression: * <code> x.clone() != x </code> will be true, and that the expression: * <code> x.clone().getClass() == x.getClass() </code> will be true. Also: * <code> x.clone().equals(x) </code> will be true. * <p> * (Note this method is used in places where we need a copy of the cell's * state but that the same instance would cause unpredictable or incorrect * behavior.) * * @return A unique copy of the cell's state (must not return "this" * object). */ public CellState clone() { // note, can only create a shallow copy. Oh well. return new ObjectState(state, alternateState, emptyState, fullState); } /** * Tests if the value of two cell states are equal. * * @return true if the cell states have the same value. */ public boolean equals(CellState state) { return this.toString().equals(state.toString()); } /** * The state of the cell. * * @return The state. */ public Object getState() { return state; } /** * Tests if a given CellState is "alternate" by using the equals method to * compare the state to the alternateState. * * @return true if the state is alternate. * @see cellularAutomata.cellState.model.CellState#setToAlternateState() */ public boolean isAlternate() { return state.equals(alternateState); } /** * Tests if a given CellState is "empty". * * @return true if the state is empty. * @see cellularAutomata.cellState.model.IntegerCellState#setToEmptyState() */ public boolean isEmpty() { return state.equals(emptyState); } /** * Tests if a given CellState is "full". * * @return true if the state is full. * @see cellularAutomata.cellState.model.IntegerCellState#setToFullState() */ public boolean isFull() { return state.equals(fullState); } /** * Sets this cell state to the "alternate" state. */ public void setToAlternateState() { super.setValue(alternateState); state = alternateState; } /** * Sets this cell state to the "empty" state. */ public void setToEmptyState() { super.setValue(emptyState); state = emptyState; } /** * Sets this cell state to the "full" state. */ public void setToFullState() { super.setValue(fullState); state = fullState; } /** * Randomly selects a full or empty state for this cell state. * * @param probability * The probability that the cell will be occupied rather than * blank. */ public void setToRandomState(double probability) { if(random.nextDouble() < probability) { super.setValue(fullState); state = fullState; } else { super.setValue(emptyState); state = emptyState; } } /** * The state of the cell. * * @param state * The state, which may be any Object. */ public void setState(Object state) { // throw exception if not a valid value if(checkState(state)) { super.setValue(state); this.state = state; } } /** * Sets a String value for the cell's state. The user may wish to override * this method in a child class. */ public void setStateFromString(String state) { // note that this method eventually calls super.setValue(Object) (via // the setState() method) as required by the contract with this abstract // method. if(emptyState.toString().equals(state)) { setState(emptyState); } else if(fullState.toString().equals(state)) { setState(fullState); } else if(alternateState.toString().equals(state)) { setState(alternateState); } else { // if it is built from the ObjectRuleTemplate, then the method // createStateFromString() exists. It tells us how to convert the // string to an object. try { // find out what rule we are using String ruleClassName = CurrentProperties.getInstance() .getRuleClassName(); // get the rule -- note that if the rule is not extending the // ObjectRuleTemplate, then this cast will fail ObjectRuleTemplate rule = (ObjectRuleTemplate) ReflectionTool .instantiateMinimalRuleFromClassName(ruleClassName); // get the state from the string Object newState = rule.createStateFromString(state); // make sure this method returns a non-null state of the correct // type. Should maybe also check if // !rule.getFullState().getClass().equals(newState.getClass())??? if(newState == null) { throw new Exception(); } // set the state setState(newState); } catch(Exception e) { // could not cast to an ObjectRuleTemplate or the state was // null. So we use a default empty state. setState(emptyState); // Not possible in general to make the string to object // conversion because we don't know in advance what kind of // object will be used and whether or not it can be converted // from a String. Don't warn if we are in the EZ facade mode. if(!havePrintedImportDataWarning && !CurrentProperties.getInstance().isFacadeOn()) { havePrintedImportDataWarning = true; // make the JFrame look disabled if(CAController.getCAFrame() != null) { CAController.getCAFrame().setViewDisabled(true); } // warn the user String message = "Please check the " + InitialStatesPanel.INIT_STATES_TAB_TITLE + " tab. \n\n" + "You are importing data from a file. \n\n" + "The current rule is based on generic objects rather than " + "numbers. \n" + "Therefore, it cannot always import numerical images or data. \n" + "When the conversion is not possible, the cell states will be set \n" + "to a blank state instead.\n\n" + "You may resubmit with a different initial state if you prefer."; JOptionPane.showMessageDialog(CAController.getCAFrame() .getFrame(), message, "Import file warning", JOptionPane.WARNING_MESSAGE); // make the JFrame look enabled if(CAController.getCAFrame() != null) { CAController.getCAFrame().setViewDisabled(false); } } } } } /** * Sets a value for this cell state. Overrides the parent class * implementation so that we can save the state locally and convert to an * array. * * @param state * The new state of the cell. */ public void setValue(Object state) { if(checkState(state)) { super.setValue(state); this.state = state; } } /** * The state as an integer. * * @return The hashcode of the state. */ public int toInt() { return state.hashCode(); } }
/* * The MIT License (MIT) * Copyright © 2012 Remo Koch, http://rko.mit-license.org/ * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and * associated documentation files (the “Software”), to deal in the Software without restriction, * including without limitation the rights to use, copy, modify, merge, publish, distribute, * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial * portions of the Software. * * THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package io.rko.uzh.mailsys.proc; import io.rko.uzh.mailsys.base.Category; import io.rko.uzh.mailsys.base.IMessageSource; import io.rko.uzh.mailsys.base.IProcessor; public class CategoryProc implements IProcessor { @Override public void process(IMessageSource pMessage) { String subject = pMessage.getSubject(); // Extract category from subject String sCat = null; if ((subject != null) && !subject.isEmpty()) { String[] split = subject.split("[\\[\\]]", 3); if (split.length == 3) { sCat = split[1]; } } // Determine category from extracted string Category cat = Category.MISC; if ((sCat != null) && !sCat.isEmpty()) { Category c = Category.getByTitleIgnoreCase(sCat); if (c != null) { cat = c; } } pMessage.setCategory(cat); } }
package com.zantong.mobilecttx.card.bean; import com.zantong.mobilecttx.base.bean.Result; /** * Created by zhengyingbing on 16/9/13. */ public class BindCardResult extends Result { private BindCard RspInfo; public void setRspInfo(BindCard rspInfo) { RspInfo = rspInfo; } public BindCard getRspInfo() { return RspInfo; } public class BindCard { int cardflag; // 0 没有 1畅通卡不一致 2畅通卡一致 int mobileflag;//0 预留手机号不正确 1正确 int custcodeflag;// 0 证件号不一致 1一致 public int getCardflag() { return cardflag; } public void setCardflag(int cardflag) { this.cardflag = cardflag; } public int getMobileflag() { return mobileflag; } public void setMobileflag(int mobileflag) { this.mobileflag = mobileflag; } public int getCustcodeflag() { return custcodeflag; } public void setCustcodeflag(int custcodeflag) { this.custcodeflag = custcodeflag; } } }
package com.example.travelmatics; import android.content.Intent; import android.content.res.Resources; import android.net.Uri; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatActivity; import com.firebase.ui.auth.AuthUI; import com.google.android.gms.tasks.Continuation; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.OnFailureListener; import com.google.android.gms.tasks.OnSuccessListener; import com.google.android.gms.tasks.Task; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.storage.StorageReference; import com.google.firebase.storage.UploadTask; import com.squareup.picasso.Picasso; public class DealActivity extends AppCompatActivity { private FirebaseDatabase mFirebaseDatabase; private DatabaseReference mDatabaseReference; private static final int PICTURE_RESULT = 69; private static final int DEVICE_WIDTH = Resources.getSystem().getDisplayMetrics().widthPixels; EditText etTitle; EditText etPrice; EditText etDescription; ImageView imageView; Button btnImage; TravelDeal deal; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_deal); mFirebaseDatabase = FirebaseUtil.mFirebaseDatabase; mDatabaseReference = FirebaseUtil.mDatabaseReference; etTitle = (EditText) findViewById(R.id.etTitle); etPrice = (EditText) findViewById(R.id.etPrice); etDescription = (EditText) findViewById(R.id.etDescription); imageView = (ImageView) findViewById(R.id.iv_tour); btnImage = (Button) findViewById(R.id.btnImage); final Intent intent = getIntent(); TravelDeal deal = (TravelDeal) intent.getParcelableExtra("Deal"); if(deal == null) { this.deal = new TravelDeal(); } this.deal = deal; etTitle.setText(deal.getTitle()); etPrice.setText(deal.getPrice()); etDescription.setText(deal.getDescription()); if(!deal.getImageURL().isEmpty() && deal.getImageURL() != null){ Picasso.get() .load(deal.getImageURL()) .resize(DEVICE_WIDTH, DEVICE_WIDTH * 2/3) .centerCrop() .into(imageView); } btnImage.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent1 = new Intent(Intent.ACTION_GET_CONTENT); intent1.setType("image/jpeg"); intent1.putExtra(Intent.EXTRA_LOCAL_ONLY, true); startActivityForResult(Intent.createChooser(intent1, "Insert Picture"), PICTURE_RESULT); } }); } @Override protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) { super.onActivityResult(requestCode, resultCode, data); if(requestCode == PICTURE_RESULT && resultCode == RESULT_OK){ Uri imageUri = data.getData(); final StorageReference ref = FirebaseUtil.mStorageReference.child(imageUri.getLastPathSegment()); UploadTask uploadTask = ref.putFile(imageUri); Task<Uri> urlTask = uploadTask.continueWithTask(new Continuation<UploadTask.TaskSnapshot, Task<Uri>>() { @Override public Task<Uri> then(@NonNull Task<UploadTask.TaskSnapshot> task) throws Exception { if (!task.isSuccessful()) { throw task.getException(); } // Continue with the task to get the download URL return ref.getDownloadUrl(); } }).addOnCompleteListener(new OnCompleteListener<Uri>() { @Override public void onComplete(@NonNull Task<Uri> task) { if (task.isSuccessful()) { Uri downloadUri = task.getResult(); String url = downloadUri.toString(); String imageName = ref.getName(); Log.d("Nafiu", "imageName = " + imageName); Log.d("Nafiu", "downloadUrl = "+ url); deal.setImageURL(url); deal.setImageName(imageName); Picasso.get() .load(deal.getImageURL()) .resize(DEVICE_WIDTH, DEVICE_WIDTH * 2/3) .centerCrop() .into(imageView); } else { // Handle failures // ... } } }); } } @Override public boolean onOptionsItemSelected(@NonNull MenuItem item) { switch (item.getItemId()) { case R.id.save_menu: saveDeal(); Toast.makeText(this, "Travel Deal Saved", Toast.LENGTH_LONG).show(); backToList(); return true; case R.id.delete_deal: deleteDeal(); Toast.makeText(this, "Travel Deal Deleted", Toast.LENGTH_LONG).show(); backToList(); return true; case R.id.logout: AuthUI.getInstance() .signOut(this) .addOnCompleteListener(new OnCompleteListener<Void>(){ @Override public void onComplete(@NonNull Task<Void> task) { Log.d("Logout", "User Logged Out"); FirebaseUtil.attachListener(); } }); FirebaseUtil.detachListener(); return true; default: return super.onOptionsItemSelected(item); } } private void saveDeal() { deal.setTitle(etTitle.getText().toString()); deal.setPrice(etPrice.getText().toString()); deal.setDescription(etDescription.getText().toString()); if(deal.getId() == null){ mDatabaseReference.push().setValue(deal); }else{ mDatabaseReference.child(deal.getId()).setValue(deal); } } private void deleteDeal(){ if(deal != null){ mDatabaseReference.child(deal.getId()).removeValue(); if(deal.getImageName() != null && !deal.getImageName().isEmpty()){ StorageReference storageReference = FirebaseUtil.mStorageReference.child(deal.getImageName()); storageReference.delete().addOnSuccessListener(new OnSuccessListener<Void>() { @Override public void onSuccess(Void aVoid) { Log.d("Delete Deal", "File Deleted Successfully - file: " + deal.getImageName()); } }).addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { Log.d("Delete Deal", "File Deletion Failed - file: " + deal.getImageName()); } }); } } else { Toast.makeText(this, "Please save deal before deleting", Toast.LENGTH_LONG).show(); } return; } private void backToList(){ Intent intent = new Intent(this, ListActivity.class); startActivity(intent); } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater menuInflater = getMenuInflater(); menuInflater.inflate(R.menu.save_menu, menu); if(FirebaseUtil.isAdmin){ menu.findItem(R.id.save_menu).setVisible(true); menu.findItem(R.id.delete_deal).setVisible(true); enableText(true); } else { menu.findItem(R.id.save_menu).setVisible(false); menu.findItem(R.id.delete_deal).setVisible(false); enableText(false); } return true; } private void enableText(boolean isEnabled){ etTitle.setEnabled(isEnabled); etDescription.setEnabled(isEnabled); etPrice.setEnabled(isEnabled); btnImage.setVisibility( isEnabled ? View.VISIBLE: View.INVISIBLE ); } }
package com.atguigu.flowbean; import java.io.IOException; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Mapper; public class FlowBeanMapper extends Mapper<LongWritable, Text, Text, FlowBean>{ private Text out_key=new Text(); private FlowBean out_value=new FlowBean(); @Override protected void map(LongWritable key, Text value, Mapper<LongWritable, Text, Text, FlowBean>.Context context) throws IOException, InterruptedException { //设置分隔符 切片 String[] words = value.toString().split("\t"); //封装key out_key.set(words[1]); //封装value long upFlow = Long.parseLong(words[words.length-3]); long downFlow = Long.parseLong(words[words.length-2]); out_value.setUpFlow(upFlow); out_value.setDownFlow(downFlow); //写出 context.write(out_key, out_value); } }
import java.util.*; import java.io.*; public class Match { public static void main(String[] arg) { double startTime = System.currentTimeMillis(); Runtime runtime = Runtime.getRuntime(); String corpusSeq = null; String patternSeq = null; Scanner sc = new Scanner(System.in); System.out.println("Enter the path of corpus file:"); String corpus = sc.nextLine(); System.out.println("Enter the path of pattern file:"); String pattern = sc.nextLine(); corpusSeq = SeqReader.readSeq(corpus); patternSeq = SeqReader.readSeq(pattern); System.out.println("CORPUS: " + corpusSeq.length() + " bases"); System.out.println("PATTERN: " + patternSeq.length() + " bases"); System.out.print("Match length? "); int matchLength = sc.nextInt(); SimplifiedOpenAddressingBucketMapping<String,Integer> mapping = new SimplifiedOpenAddressingBucketMapping<String,Integer>(patternSeq.length()); for (int j = 0; j < patternSeq.length() - matchLength + 1; j++) { String tag = patternSeq.substring(j, j + matchLength); mapping.put(tag, new Integer(j)); } System.out.println("\nAfter creating the table, it holds " + mapping.getSize() + " sequences of length " + matchLength); System.out.println("The number of distinct substrings is " + mapping.getNumTags()); System.out.println("\nThe matches are:"); int numMatches = 0; int numTagMatches = 0; for (int j = 0; j < corpusSeq.length() - matchLength + 1; j++) { String tag = corpusSeq.substring(j, j + matchLength); Iterator loc = mapping.get(tag); if (loc != null) { numTagMatches++; while (loc.hasNext()) { System.out.println(j + " " + loc.next() + " " + tag); numMatches++; } } } System.out.print("\nThere were " + numMatches + " matches found "); System.out.println("among " + numTagMatches + " matching substrings."); long kb = 1024; double stopTime = System.currentTimeMillis(); double elapsedTime = stopTime - startTime; System.out.println("Running time :" + elapsedTime/1000 + " seconds."); long usedMemory = (runtime.totalMemory() - runtime.freeMemory()) / kb; System.out.println("Used Memory :" + usedMemory + " KB"); } } class SeqReader { public static String readSeq(String fileName) { BufferedReader r; try { InputStream is = new FileInputStream(fileName); r = new BufferedReader(new InputStreamReader(is)); } catch (IOException e) { System.out.println("IOException while opening " + fileName + "\n" + e); return null; } StringWriter buffer = new StringWriter(); try { boolean stop = false; while (!stop) { String nextline = r.readLine(); if (nextline == null) stop = true; else { String seq = nextline.trim(); buffer.write(seq.toLowerCase()); } } } catch (IOException e) { System.out.println("IOException while reading sequence from " + fileName + "\n" + e); return null; } return buffer.toString(); } } class TaggedElement<T,E> { T tag; ArrayList<E> positions; TaggedElement(T t){ tag = t; positions = new ArrayList<E>(1); } } //A limited version of an Open Addressing Bucket Mapping class SimplifiedOpenAddressingBucketMapping<T,E> { public static final Object EMPTY = new EmptySlot(); //sentinel for empty slot static class EmptySlot{} public static final Object DELETED = new DeletedElement(); //deleted sentinel static class DeletedElement{} public static final double DEFAULT_LOAD = 0.5; //default value for target load public static final int DEFAULT_CAPACITY = 8; //default capacity double targetLoad; //the desired value for size/table.length Object[] table; //the underlying array for the hash table int size = 0; //the number of elements put in the collection int d = 0; //the number of slots marked as deleted int numTags = 0; //the number of tags in the collection int minCapacity; // min capacity from parameter given in the constructor int highWaterMark;// max value for number of tags before increasing table size //Constructors public SimplifiedOpenAddressingBucketMapping(int capacity, double load){ if (load >= 1.0) throw new IllegalArgumentException("Load must be < 1"); this.targetLoad = load; int tableSize =(int) Math.pow(2,Math.ceil(Math.log(capacity/load)/Math.log(2))); table = new Object[tableSize]; Arrays.fill(table, EMPTY); minCapacity = capacity; highWaterMark = (int) (table.length*(1+targetLoad)/2); } public SimplifiedOpenAddressingBucketMapping(){ this(DEFAULT_CAPACITY, DEFAULT_LOAD); } public SimplifiedOpenAddressingBucketMapping(int capacity) { this(capacity, DEFAULT_LOAD); } // Accessors to return the number of tags or number of elements put into the collection public int getNumTags() { return numTags; } // Returns the number of elements that have been inserted into the bucket mapping public int getSize() { return size; } // Returns true exactly when slot is in use in the hash table boolean inUse(int slot){ return table[slot] != EMPTY && table[slot] != DELETED; } // primary hash function static double A = (Math.sqrt(5.0)-1)/2; //multiplier for hash function protected int hash(int hashCode) { double frac = (hashCode * A) - (int) (hashCode * A); //fractional part of x*A int hashValue = (int) (table.length * frac); //multiply by m if (hashValue < 0) // if this is negative add m to get hashValue += table.length; // hashValue mod m return hashValue; } //secondary hash function protected int stepHash(int hashCode) { int s = (hashCode % (table.length/2 - 1)); if (s < 0) s += (table.length/2 - 1); return 2*s + 1; } // internal method to locate the slot where a given tag is held or where it should be // inserted if the tag is not currently used by an element in the collection final int NONE = -1; @SuppressWarnings("unchecked") protected int locate(T target) { int hashCode = target.hashCode(); int index = hash(hashCode); //first slot in probe sequence int step = stepHash(hashCode); //step size between probes int insertPosition = NONE; while (table[index] != EMPTY) { //continue until an empty slot found if (table[index] != DELETED) { if (((TaggedElement<T,E>) table[index]).tag.equals(target)) return index; } else if (insertPosition == NONE) { insertPosition = index; } index = (index + step) % table.length; //move forward in probe sequence } if (insertPosition == NONE) insertPosition = index; return insertPosition; } // Returns true exactly when some element has the given tag. public boolean containsTag(T tag) { return inUse(locate(tag)); } // Returns an iterator over the bucket associated with the given tag (or null if // there is no element with this tag). @SuppressWarnings("unchecked") public Iterator<E> get(T tag) { int slot = locate(tag); if (inUse(slot)) return ((TaggedElement<T,E>) table[slot]).positions.iterator(); return null; } // Puts a new tagged element into the bucket mapping with the given tag and element. @SuppressWarnings("unchecked") public void put(T tag, E element) { size++; int slot = locate(tag); // get insert position if (!inUse(slot)) { // tag needs to be added numTags++; table[slot] = new TaggedElement<T,E>(tag); } ((TaggedElement<T,E>) table[slot]).positions.add(element); growTableAsNeeded(); } //Methods used to delete elements boolean clearSlot(int slot) { if (inUse(slot)) { table[slot] = DELETED; d++; size--; return true; } else return false; } public boolean removeBucket(T tag) { return clearSlot(locate(tag)); } // Methods to handle resizing the table to ensure that the true load isn't too high void growTableAsNeeded() { if (numTags > highWaterMark) resizeTable(Math.max(numTags, minCapacity)); } @SuppressWarnings("unchecked") void resizeTable(int desiredCapacity){ SimplifiedOpenAddressingBucketMapping<T,E> newTable = new SimplifiedOpenAddressingBucketMapping<T,E>(desiredCapacity, targetLoad); for (int slot = 0; slot < table.length; slot++) //insert all elements if (inUse(slot)) { TaggedElement<T,E> te = (TaggedElement<T,E>) table[slot]; int newSlot = newTable.locate((T) te.tag); // get insert position newTable.table[newSlot] = te; } this.table = newTable.table; d = 0; highWaterMark = (int) (table.length*(1+targetLoad)/2); } }
package com.chinasoft.education_manage.web.teacherservlet; import com.chinasoft.education_manage.domain.Class; import com.chinasoft.education_manage.service.TeacherService; import com.chinasoft.education_manage.service.impl.TeacherServiceImpl; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.List; @WebServlet("/teacherServlet") public class TeacherServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); TeacherService teacherService = new TeacherServiceImpl(); List<Class> list = teacherService.echoClass(); request.setAttribute("list",list); request.getRequestDispatcher("/addteacher.jsp").forward(request,response); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request,response); } }
package com.imooc.ioc.beanshuxingzhurufangshi; /** * @Author: Asher Huang * @Date: 2019-10-17 * @Description: com.imooc.ioc.beanshuxingzhurufangshi * @Version:1.0 */ public class Cat { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String toString() { return "Cat{" + "name='" + name + '\'' + '}'; } }
package com.cs192.foodwatch; import org.achartengine.ChartFactory; import org.achartengine.GraphicalView; import android.app.Activity; import android.content.Intent; import android.database.Cursor; import android.os.Bundle; import android.view.View; import android.view.ViewGroup.LayoutParams; import android.widget.LinearLayout; public class ViewWeightChart extends Activity { private GraphicalView targetView; String id; LinearLayout layout; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.activity_view_weight_chart); initializeVariables(); layout.removeAllViews(); Bundle bundle = getIntent().getExtras(); id = bundle.getString("ID"); long l = Long.parseLong(id); DatabaseManager database = new DatabaseManager(ViewWeightChart.this); database.open(); Cursor c = database.getDataAndReturnedAsQuery(id); String[] patientWeights = new String[c.getCount()]; String[] patientDate = new String[c.getCount()]; double[] weightInfo = new double[c.getCount()]; if(c.moveToFirst()) { for(int i=0;i<c.getCount();i++) { patientWeights[i] = c.getString(0); patientDate[i] = c.getString(1); c.moveToNext(); } } for(int i=0;i<c.getCount();i++) { weightInfo[i] = Double.parseDouble(patientWeights[i]); } String initWeight = database.getDataInitialWeight(l); double initialweight = Double.parseDouble(initWeight); c.close(); String tarWeight = database.getTargetWeight(id); String tarDate = database.getTargetDate(id); double targetWeight = Double.parseDouble(tarWeight); database.close(); CreateLineGraphWeightChart linegraph = new CreateLineGraphWeightChart(); linegraph.createLine(weightInfo, patientDate, initialweight,targetWeight,tarDate); targetView = ChartFactory.getLineChartView(this, linegraph.weightDataSet, linegraph.weightMultipleSeriesRenderer); layout.addView(targetView,new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)); } public void initializeVariables() { layout = (LinearLayout) findViewById(R.id.weightChartHolder); } public void updateChart(View view) { Intent intent = new Intent(getApplicationContext(), UpdateWeightChart.class); intent.putExtra("ID", id); startActivity(intent); } public void setTargetWeight(View view) { Intent intent = new Intent(getApplicationContext(), AddTarget.class); intent.putExtra("ID", id); startActivity(intent); } }
package com.zhicai.byteera.activity.community.topic.viewinterface; import android.app.Activity; import java.util.List; /** Created by bing on 2015/6/28. */ public interface TopicDetailIV<Data> { Activity getContext(); void refreshFinish(); void setTitleButtonEnable(boolean b); void hidePage(); void initListView(); void setLeftText(String s); void setMiddleText(String s); void setRIghtText(String s); void removeAllViews(); void addItem(Object item); void addAllItem(List<Data> items); void notifyDataSetChanged(); boolean titleButtonIsEnabled(); void showPage(int state); void openEditCommentView(); void setComment(String topicId, String opinionId, String user_id, String toUserId, int position, String nickName); void setZaning(boolean zaning, int position); void setRightTextGone(); void setLeftTextVisible(); void setRightTextVisible(); void setLeftTextGone(); }
/** * */ package de.hofuniversity.core.connect; import de.hofuniversity.core.Team; /** * @author Michael Jahn * */ public interface ConnectToHomeTeam { public void conntectToHomeTeam(Team team); }
package hr.bosak_turk.planetdemo.pojo; import android.os.Parcel; import android.os.Parcelable; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; public class Content implements Parcelable { @SerializedName("rendered") @Expose private String excerptText; public String getExcerptText() { return excerptText; } public void setExcerptText(String excerptText) { this.excerptText = excerptText; } protected Content(Parcel in) { excerptText = in.readString(); } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(excerptText); } @SuppressWarnings("unused") public static final Parcelable.Creator<Content> CREATOR = new Parcelable.Creator<Content>() { @Override public Content createFromParcel(Parcel in) { return new Content(in); } @Override public Content[] newArray(int size) { return new Content[size]; } }; }
/** * */ package com.isg.ifrend.core.controller; import org.zkoss.zk.ui.Component; import org.zkoss.zk.ui.util.GenericForwardComposer; /** * @author gerald.deguzman * */ @SuppressWarnings("rawtypes") public class AuthorizationsViewCtrl extends GenericForwardComposer { /** * */ private static final long serialVersionUID = 1L; /*private Window authorizations; private Listbox lst_history; private Listbox lst_pending_auths; private Listbox lst_todays_activity;*/ /** * * */ @SuppressWarnings("unchecked") @Override public void doAfterCompose(Component comp) throws Exception { super.doAfterCompose(comp); // TODO Auto-generated method stub /*Window window = (Window)Executions.createComponents( "/pages/authorization_reversal.zul", null, null); window.doModal();*/ } /*public void onSelect$lst_todays_activity()throws InterruptedException{ Window window = (Window)Executions.createComponents( "/pages/authorization_reversal.zul", null, null); window.doModal(); }*/ }
package levelDesigner; import java.awt.event.*; import javax.swing.JButton; @SuppressWarnings("serial") public class Button extends JButton{ private ButtonListener listener; private String label; private int identifier; public Button(String labl, int id, ButtonListener bl){ this.setText(labl); this.setSize(20,20); listener = bl; label = labl; identifier = id; this.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent ae){ System.out.println("Pressed button"); if(listener != null) listener.buttonPressed(identifier); else System.out.println("No Listener: mouseReleased"); } }); } }
package com.qfc.yft.ui; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import com.qfc.yft.R; public final class TreeViewHolder { private ImageView headImg; private TextView title; private TextView info; private boolean isSharing; private TextView time; private TextView chatBadge; private Button button; public TextView getChatBadge() { if (chatBadge == null) { chatBadge = (TextView) view.findViewById(R.id.chat_badge); } return chatBadge; } public boolean isSharing() { return isSharing; } public void setSharing(boolean isSharing) { this.isSharing = isSharing; } private View view; public TreeViewHolder(View view) { this.view = view; } public TextView getButton() { if (button == null) { // button = (Button) view.findViewById(R.id.add_butt); System.out.println("oh oh tree view holder"); } return button; } public TextView getTime() { if (time == null) { time = (TextView) view.findViewById(R.id.time); } return time; } public ImageView getImg() { if (headImg == null) { headImg = (ImageView) view.findViewById(R.id.head_img); } return headImg; } public TextView getTitle() { if (title == null) { title = (TextView) view.findViewById(R.id.title); } return title; } public TextView getInfo() { if (info == null) { info = (TextView) view.findViewById(R.id.info); } return info; } }
package ticTacToe; import java.util.InputMismatchException; import java.util.Scanner; public class PlayGame { public Scanner input; public void displayMenu() { System.out.println(); System.out.println(" Menu Tic Tac Toe"); System.out.println("1. Human VS Computer"); System.out.println("2. Human VS Human"); System.out.println("3. Computer VS Computer"); System.out.println("4. Exit game"); System.out.print("Enter mode: "); } public int userInput() { boolean index = false; int choice = 0; displayMenu(); input = new Scanner(System.in); while (!index) { try { choice = input.nextInt(); } catch (InputMismatchException in) { System.out.println("Wrong input, integers 1-3 allowed only."); System.out.println("Try again"); System.out.print("Enter mode: "); input.nextLine(); continue; } index = true; } return choice; } public static void main(String[] args) { PlayGame play = new PlayGame(); int in = 0; Game game = null; while (in != 4) { switch (in = play.userInput()) { case 1: game = new Game(new HumanPlayer(), new ComputerPlayer()); break; case 2: game = new Game(new HumanPlayer(), new HumanPlayer()); break; case 3: game = new Game(new ComputerPlayer(), new ComputerPlayer()); break; case 4: System.out.println(" Good Bye"); break; default: System.out.println("Wrong input, try again"); } if (in != 4) { game.startGame(); } } } }
package com.niit.backend.service; import java.util.List; import com.niit.backend.model.Employee; public interface EmpService { public List<Employee> getEmployeeList(); public Employee getEmployee(int emplId); public boolean addEmployee(Employee emp); public boolean updateEmployee(Employee emp); public boolean deleteEmployee(int emplId); public Employee findbyId (int emplId); }