blob_id stringlengths 40 40 | language stringclasses 1
value | repo_name stringlengths 5 132 | path stringlengths 2 382 | src_encoding stringclasses 34
values | length_bytes int64 9 3.8M | score float64 1.5 4.94 | int_score int64 2 5 | detected_licenses listlengths 0 142 | license_type stringclasses 2
values | text stringlengths 9 3.8M | download_success bool 1
class |
|---|---|---|---|---|---|---|---|---|---|---|---|
ea8687bda96887a8a4958a53b15bdabd58b113b6 | Java | daaviidm10/ProgramacionClase2 | /src/com/programacion/segundaEval/Boletin12/Garaje.java | UTF-8 | 1,137 | 3.03125 | 3 | [] | no_license | package com.programacion.segundaEval.Boletin12;
import javax.swing.JOptionPane;
public class Garaje {
private int numeroCoche;
private float horas,recibido;
private String coche;
public Garaje() {
}
public int getNumeroCoche() {
return numeroCoche;
}
public void setNumeroCoche(int numeroCoche) {
this.numeroCoche = numeroCoche;
}
public float getHoras() {
return horas;
}
public void setHoras(float horas) {
this.horas = horas;
}
public String getCoche() {
return coche;
}
public void setCoche(String coche) {
this.coche = coche;
}
public void factura(){
System.out.println("FACTURA: \nMATRICULA COCHE "+coche+"\nTEMPO "+
horas+"H\nPrecio "+this.precio()+"€\nCARTOS RECIBIDOS "+recibido+
"€\nCARTOS DEVOLTOS "+this.devolto()+
"€\nGRACIAS POR USAR O NOSO APARCAMENTO");
}
private float precio(){
float p3=1.5f;
float p=1.5f+(horas-3)0.2f;
if(horas<=3){
return p3;
}else{
return p;
}
}
public void precio2(){
JOptionPane.showMessageDialog(null, "Precio de instacia "+this.precio()+"€");
}
public void recivido(float reci){
recibido=reci;
}
private float devolto(){
float dev=recibido-this.precio();
return dev;
}
} | true |
2c29a234e637ae38bc22622e8d209b4fcc1058fc | Java | ayebiahwea/mapbox-navigation-android | /libandroid-navigation/src/main/java/com/mapbox/services/android/navigation/v5/navigation/SdkVersionChecker.java | UTF-8 | 433 | 2.109375 | 2 | [
"MIT"
] | permissive | package com.mapbox.services.android.navigation.v5.navigation;
public class SdkVersionChecker {
private final int currentSdkVersion;
public SdkVersionChecker(int currentSdkVersion) {
this.currentSdkVersion = currentSdkVersion;
}
public boolean isGreaterThan(int sdkCode) {
return currentSdkVersion > sdkCode;
}
public boolean isEqualOrGreaterThan(int sdkCode) {
return currentSdkVersion >= sdkCode;
}
}
| true |
bb9c590f91f8e18978d4cc20bd3f950a77d82cf6 | Java | marcin-kosmalski/jee | /jeetest2/src/main/java/cdi/events/EmProducer.java | UTF-8 | 463 | 2.328125 | 2 | [] | no_license | package cdi.events;
import javax.enterprise.inject.Produces;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceUnit;
public class EmProducer {
@PersistenceUnit(unitName = "MyPU")
private EntityManagerFactory entityManagerFactory;
@Produces
public EntityManager produceEntityManager() {
System.out.println("em produced");
return entityManagerFactory.createEntityManager();
}
}
| true |
6dd007c454da54a4abb820903b213f1269cdc89b | Java | ivanxavier7/LaboratorioProgramacao | /Loto_Entrega3/JogoLoto_Monitor/src/gui/components/Bars.java | ISO-8859-1 | 3,194 | 2.71875 | 3 | [] | no_license | package gui.components;
import application.Jogo;
import gui.util.Controller;
import javafx.beans.property.StringProperty;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.FlowPane;
import javafx.scene.layout.GridPane;
import javafx.stage.Stage;
import model.entities.MonitorLoto;
/**
* Classe responsavel pelas barra superior e inferior da interface
*
* @author Ivan Xavier
* @version 1.0
* @since 1.0
*/
public class Bars {
/**
* Devolve a barra superior do jogo, permite organizar alguns objetos
* num formato de LinearLayout.
* Consituida por um titulo e um monitor que interliga o value com o
* value, para atualizar os valores escolhidos no monitor.
*
*
* @param value Valor para ser Binded a Label que guarda os numeros
* @return topBar Barra superior da aplicacao
*
* @see Controller#getLabel(String)
* @see Controller#createDisplayField(StringProperty)
*
* @author Ivan Xavier
* @since 1.0
*/
public static FlowPane getTopBar(StringProperty value) {
Label title = Controller.getLabel("Monitor de Loto");
FlowPane topBar = new FlowPane();
title.setId("title");
topBar.setHgap(20);
topBar.setVgap(20);
topBar.getChildren().addAll( title, Controller.createDisplayField(value));
return topBar;
}
/**
* Devolve a barra inferior do jogo, permite organizar alguns objetos
* num formato de LinearLayout.
* Consituida por um titulo do numero de jogadores, um campo de edicao para digitar o numero de jogadores,
* um botao de confirmacao e um botao para reiniciar o jogo.
*
* @param grid Grelha para guardar os botes
* @param primaryStage Container principal
* @param value Valor para ser Binded Label que guarda os numeros
* @param monitor Entidade que lida com a data associada ao Monitor dos numeros, na interface
*
* @return bottomBar Barra inferior da aplicacao
*
* @see Controller#createDisplayField(StringProperty)
* @see Controller#getLabel(String)
* @see Buttons#playerButton(TextField, MonitorLoto)
* @see Buttons#restartButton(Stage, StringProperty, MonitorLoto)
* @see Jogo#getLogger()
*
* @author Ivan Xavier
* @since 1.0
*/
public static FlowPane getBottomBar(Stage primaryStage, StringProperty userInfoValue, StringProperty value, MonitorLoto monitor, Label infoUsers) {
FlowPane bottomBar = new FlowPane() ;
TextField textField = Controller.createPlayersField();
bottomBar.setHgap(20);
bottomBar.setVgap(20);
bottomBar.getChildren().addAll(
//textField,
Buttons.playerButton(textField, monitor),
Buttons.restartButton(primaryStage, value, monitor),
Controller.getLabel("Informao dos Jogadores no formato: Dinheiro, Carto, ID;"),
Controller.createUserField(userInfoValue),
Jogo.getLogger()
);
return bottomBar;
}
}
| true |
43f3387b6b3295672b326f8bd0b537f12075e4cc | Java | P79N6A/icse_20_user_study | /methods/Method_1004245.java | UTF-8 | 96 | 2.390625 | 2 | [] | no_license | private static String pretty(Object obj){
return obj != null ? obj + "" : "not configured";
}
| true |
5b531dd95edb67d2aadffd86ccf514056b7f6683 | Java | licengceng/LianXi | /IdeaProjects/HolidayOne/src/February_14/文件.java | UTF-8 | 986 | 3.765625 | 4 | [] | no_license | package February_14;
import java.io.File;
//创建这个file后,只是封装了这个路径,与磁盘路径是否有这个文件无关
//文件和文件夹都是用File代表 使用绝对路径或者相对路径创建File对象
public class 文件 {
public static void main(String[] args) {
// 绝对路径
File f1 = new File("d:/LOLFolder");
System.out.println("f1的绝对路径:" + f1.getAbsolutePath());
System.out.println(f1.exists()); //判断物理文件是否真实存在
// 相对路径,相对于工作目录,如果在eclipse中,就是项目目录
File f2 = new File("LOL.exe");
System.out.println("f2的绝对路径:" + f2.getAbsolutePath());
System.out.println(f2.exists());
// 把f1作为父目录创建文件对象
File f3 = new File(f1, "LOL.exe");
System.out.println("f3的绝对路径:" + f3.getAbsolutePath());
System.out.println(f3.exists());
}
}
| true |
b0c260dd6b3dde310df72e9b2584eaa468d78eaa | Java | Volnus/Calculate-3-Scores-Get-Average | /ScottHartley_Lab03_TestScores.java | UTF-8 | 1,071 | 3.796875 | 4 | [] | no_license | import javax.swing.JOptionPane;
/**
* Scott Hartley
*
* This program calculates the average of 3 tests scores.
*
*/
public class ScottHartley_Lab03_TestScores {
public static void main (String [] args){
double score1; // Holds First Score
double score2; // Holds Second Score
double score3; // Holds Third Score
String input; // Holds String input
// Get The First Score
input = JOptionPane.showInputDialog ("Enter Your First Test Score");
score1 = Double.parseDouble(input);
// Get The Second Score
input = JOptionPane.showInputDialog ("Enter Your Second Test Score");
score2 = Double.parseDouble(input);
// Get The Third Score
input = JOptionPane.showInputDialog ("Enter Your Third Test Score");
score3 = Double.parseDouble(input);
// Prevent scores over 100
if (score1 >= 101) {
if (score2 >= 101)
if (score3 >= 101)
JOptionPane.showMessageDialog(null, "Your score must be between 0 and 100");
}
// Shows Average Score
JOptionPane.showMessageDialog(null, "Your average is " + (score1+score2+score3)/3);
}
}
| true |
572797a10af26b1342b4f1e72cf066eac925fc42 | Java | AndreLautee/SailingCourseLayoutApp | /app/src/main/java/com/example/sailinglayoutapp/NavMapGLRenderer.java | UTF-8 | 12,320 | 2.234375 | 2 | [] | no_license | package com.example.sailinglayoutapp;
import android.location.Location;
import android.location.LocationManager;
import android.opengl.GLES20;
import android.opengl.GLSurfaceView;
import android.opengl.Matrix;
import android.util.Log;
import java.util.ArrayList;
import java.util.List;
import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;
public class NavMapGLRenderer implements GLSurfaceView.Renderer {
private ArrayList<Location> coordinates;
List<Circle> circles;
Triangle triangle;
private ArrayList<Location> locations;
private int selectedMark;
private double bearingDirection;
public ArrayList<Location> getLocations() {
return locations;
}
public void setLocations(ArrayList<Location> locations) {
this.locations = locations;
}
public double getBearingDirection() {
return bearingDirection;
}
public void setBearingDirection(double bearing) {
this.bearingDirection = deg2rad(bearing);
}
public int getSelectedMark() {
return selectedMark;
}
public void setSelectedMark(int selectedMark) {
this.selectedMark = selectedMark;
}
NavMapGLRenderer(ArrayList<Location> coords, ArrayList<Location> lct, int sM, double bearing) {
coordinates = coords;
locations = lct;
selectedMark = sM;
bearingDirection = deg2rad(bearing);
}
public static int loadShader(int type, String shaderCode) {
// create a vertex shader type (GLES20.GL_VERTEX_SHADER)
// or a fragment shader type (GLES20.GL_FRAGMENT_SHADER)
int shader = GLES20.glCreateShader(type);
// add the source code to the shader and compile it
GLES20.glShaderSource(shader, shaderCode);
GLES20.glCompileShader(shader);
return shader;
}
@Override
public void onSurfaceCreated(GL10 gl, EGLConfig config) {
GLES20.glClearColor(0.92941176f, 0.96078431f, 1.0f, 1.0f);
createMap();
}
// vPMatrix is an abbreviation for "Model View Projection Matrix"
private final float[] vPMatrix = new float[16];
private final float[] projectionMatrix = new float[16];
private final float[] viewMatrix = new float[16];
private final float[] rotationMatrix = new float[16];
private final float[] scaleMatrix = new float[16];
private final float[] translationMatrix = new float[16];
private final float[] intermediateMatrix = new float[16];
private final float[] scratch = new float[16];
private final float[] modelMatrix = new float[16];
private final float[] compassMatrix = new float[16];
@Override
public void onSurfaceChanged(GL10 gl, int width, int height) {
GLES20.glViewport(0, 0, width, height);
float ratio = (float) width / height;
// this projection matrix is applied to object coordinates
// in the onDrawFrame() method
Matrix.frustumM(projectionMatrix, 0, -ratio, ratio, -1, 1, 3, 7);
}
@Override
public void onDrawFrame(GL10 gl) {
// Redraw background color
GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT);
// Set the camera position (View matrix)
Matrix.setLookAtM(viewMatrix, 0, 0, 0, 5, 0f, 0f, 0f, 0.0f, 1.0f, 0.0f);
// Calculate the projection and view transformation
Matrix.multiplyMM(vPMatrix, 0, projectionMatrix, 0, viewMatrix, 0);
// Create a rotation
Matrix.setRotateM(rotationMatrix, 0, mAngle, 0, 0, -1.0f);
// Create a scale
Matrix.setIdentityM(scaleMatrix,0);
Matrix.scaleM(scaleMatrix, 0, mScale, mScale, mScale);
// Create a translation
Matrix.setIdentityM(translationMatrix,0);
Matrix.translateM(translationMatrix, 0, mOffsetX, mOffsetY, 0);
// Model = scale * rotation * translation
Matrix.multiplyMM(intermediateMatrix, 0, scaleMatrix, 0, translationMatrix, 0);
Matrix.multiplyMM(modelMatrix,0,intermediateMatrix,0,rotationMatrix,0);
// Combine the model matrix with the projection and camera view
// Note that the vPMatrix factor *must be first* in order
// for the matrix multiplication product to be correct.
Matrix.multiplyMM(scratch, 0, vPMatrix, 0,modelMatrix,0);
for (int i=0; i < circles.size(); i++) {
circles.get(i).draw(scratch);
}
if (triangle != null) {
triangle.draw(scratch);
}
}
public volatile float mAngle;
public float getAngle() {
return mAngle;
}
public void setAngle(float angle) {
mAngle = angle;
}
public float mScale;
public void setScale(float scale) {
mScale = scale;
}
public float getScale() { return mScale; }
public float mOffsetX;
public float mOffsetY;
public void setOffsetX(float offsetX) {
mOffsetX += offsetX;
}
public void resetOffsetX() { mOffsetX = 0; }
public void setOffsetXUserCentre() { mOffsetX = getOffsetXUserCentre(); }
public float getOffsetX() { return mOffsetX; }
public void setOffsetY(float offsetY) {
mOffsetY += offsetY;
}
public void resetOffsetY() { mOffsetY = 0; }
public void setOffsetYUserCentre() { mOffsetY = getOffsetYUserCentre(); }
public float getOffsetY() { return mOffsetY; }
private double deg2rad(float deg) {return deg * (Math.PI/180);}
public float getOffsetXUserCentre() {
return (float) -(userX*Math.cos(deg2rad(-mAngle)) - userY*Math.sin(deg2rad(-mAngle)));
}
public float getOffsetYUserCentre() {
return (float) -(userY*Math.cos(deg2rad(-mAngle)) + userX*Math.sin(deg2rad(-mAngle)));
}
double centre_x = 0;
double centre_y = 0;
float x;
float y;
double ratio_x;
double ratio_y;
int j;
double leftmost_coord;
double rightmost_coord;
double upmost_coord;
double downmost_coord;
double max_xy_dispersion;
public void createMap() {
leftmost_coord = coordinates.get(0).getLongitude();
rightmost_coord = coordinates.get(0).getLongitude();
upmost_coord = coordinates.get(0).getLatitude();
downmost_coord = coordinates.get(0).getLatitude();
double xTotal = 0;
double yTotal = 0;
// Find left, right, up and down most coord
// These coords are used in calculations to find a ratio for drawing
for (int i = 0; i < coordinates.size(); i++) {
if (leftmost_coord > coordinates.get(i).getLongitude()) {
leftmost_coord = coordinates.get(i).getLongitude();
}
if (rightmost_coord < coordinates.get(i).getLongitude()) {
rightmost_coord = coordinates.get(i).getLongitude();
}
if (upmost_coord < coordinates.get(i).getLatitude()) {
upmost_coord = coordinates.get(i).getLatitude();
}
if (downmost_coord > coordinates.get(i).getLatitude()) {
downmost_coord = coordinates.get(i).getLatitude();
}
xTotal += coordinates.get(i).getLongitude();
yTotal += coordinates.get(i).getLatitude();
}
// Find centre coord to use as reference
centre_x = xTotal / coordinates.size();
centre_y = yTotal / coordinates.size();
// Find max dispersion from centre so a ratio can be determined
max_xy_dispersion = 0;
max_xy_dispersion = Math.sqrt(Math.pow(coordinates.get(0).getLongitude() - coordinates.get(1).getLongitude(),2)
+ Math.pow(coordinates.get(0).getLatitude() - coordinates.get(1).getLatitude(),2));
//For triangle course the max dispersion may not be the dispersion between marks 1 and 3
if (coordinates.size() == 3) {
if (max_xy_dispersion < (Math.sqrt(Math.pow(coordinates.get(2).getLongitude() - coordinates.get(1).getLongitude(),2)
+ Math.pow(coordinates.get(2).getLatitude() - coordinates.get(1).getLatitude(),2)))) {
max_xy_dispersion = Math.sqrt(Math.pow(coordinates.get(2).getLongitude() - coordinates.get(1).getLongitude(),2)
+ Math.pow(coordinates.get(2).getLatitude() - coordinates.get(1).getLatitude(),2));
}
}
// For trapezoid or optimist courses the max dispersion may not be dispersion between marks 1 and 4
// Check for this
if (coordinates.size() == 4) {
if (max_xy_dispersion < (Math.sqrt(Math.pow(coordinates.get(3).getLongitude() - coordinates.get(1).getLongitude(),2)
+ Math.pow(coordinates.get(3).getLatitude() - coordinates.get(1).getLatitude(),2)))) {
max_xy_dispersion = Math.sqrt(Math.pow(coordinates.get(3).getLongitude() - coordinates.get(1).getLongitude(),2)
+ Math.pow(coordinates.get(3).getLatitude() - coordinates.get(1).getLatitude(),2));
}
}
// Dispersion is from centre of screen so divide length by 2
max_xy_dispersion = max_xy_dispersion/2;
if (locations.size() > 0) {
positionTriangle();
}
positionCircles();
}
float userX = 0;
float userY = 0;
public void positionTriangle() {
float length = 0.15f;
x = 0.75f;
y = 0.75f;
if (locations.size() == 1) {
j = 0;
} else {
j = 1;
}
ratio_x = Math.abs((locations.get(j).getLongitude() - centre_x) / max_xy_dispersion);
ratio_y = Math.abs((locations.get(j).getLatitude() - centre_y) / max_xy_dispersion);
// Find x ratio to draw user location
if (locations.get(j).getLongitude() - centre_x < 0) {
x = (float) -(x * ratio_x);
} else if (locations.get(j).getLongitude() - centre_x > 0) {
x = (float) (x * ratio_x);
} else {
x = 0;
}
// Find y ratio to draw user location
if (locations.get(j).getLatitude() - centre_y < 0) {
y = (float) -(y * ratio_y);
} else if (locations.get(j).getLatitude() - centre_y > 0) {
y = (float) (y * ratio_y);
} else {
y = 0;
}
userX = x;
userY = y;
float XmidBase = (float) (-Math.sin(bearingDirection)*length) + x;
float YmidBase = (float) (-Math.cos(bearingDirection)*length) + y;
float x2 = (float) (Math.sin(bearingDirection + ((2*Math.PI)/3))*(length/2)) + XmidBase;
float y2 = (float) (Math.cos(bearingDirection + ((2*Math.PI)/3))*(length/2)) + YmidBase;
float x4 = (float) (Math.sin(bearingDirection - ((2*Math.PI)/3))*(length/2)) + XmidBase;
float y4 = (float) (Math.cos(bearingDirection - ((2*Math.PI)/3))*(length/2)) + YmidBase;
// Draw user location
triangle = new Triangle(new float[] {x,y,0.0f,x2,y2,0.0f,XmidBase, YmidBase, 0.0f,x4,y4,0.0f});
}
public void positionCircles() {
circles = new ArrayList<>();
for (int i = 0; i < coordinates.size(); i++) {
x = 0.75f;
y = 0.75f;
ratio_x = Math.abs((coordinates.get(i).getLongitude() - centre_x) / max_xy_dispersion);
ratio_y = Math.abs((coordinates.get(i).getLatitude() - centre_y) / max_xy_dispersion);
if (coordinates.get(i).getLongitude() - centre_x < 0) {
x = (float) -(x * ratio_x);
} else if (coordinates.get(i).getLongitude() - centre_x > 0) {
x = (float) (x * ratio_x);
} else {
x = 0;
}
if (coordinates.get(i).getLatitude() - centre_y < 0) {
y = (float) -(y * ratio_y);
} else if (coordinates.get(i).getLatitude() - centre_y > 0) {
y = (float) (y * ratio_y);
} else {
y = 0;
}
if (i == selectedMark) {
circles.add(new Circle(x,y,1, 0.06f));
circles.add(new Circle(x,y,-1,0.04f));
} else {
circles.add(new Circle(x,y,0,0.04f));
}
}
}
private double deg2rad(double deg) {
return (deg * Math.PI / 180.0);
}
}
| true |
b15cdbeeb7364b3c5141575fadf1fcb9ac438051 | Java | herdebran/gestamboWeb | /cristalView/src/main/java/ar/com/cristal/creditos/client/service/UsuarioRPCService.java | UTF-8 | 2,252 | 1.882813 | 2 | [] | no_license | package ar.com.cristal.creditos.client.service;
import java.util.List;
import ar.com.cristal.creditos.client.accesibilidad.ComponenteDePantallaDto;
import ar.com.cristal.creditos.client.accesibilidad.PerfilesDto;
import ar.com.cristal.creditos.client.dto.EstablecimientoDTO;
import ar.com.cristal.creditos.client.dto.UsuarioLogueadoDTO;
import ar.com.cristal.creditos.client.ui.usuarios.dto.UsuarioDTO;
import com.google.gwt.user.client.rpc.RemoteService;
import com.google.gwt.user.client.rpc.RemoteServiceRelativePath;
@RemoteServiceRelativePath("usuarioService")
public interface UsuarioRPCService extends RemoteService {
UsuarioLogueadoDTO obtenerUsuarioLogueado() throws Exception;
List<PerfilesDto> obtenerPerfiles() throws Exception;;
void borrarPerfil(int id);
PerfilesDto guardarPerfil(PerfilesDto p) throws Exception;
UsuarioDTO obtenerUsario(Long id);
UsuarioDTO persistirUsuario(UsuarioDTO usuarioActual) throws Exception;
List<UsuarioDTO> obtenerUsarios();
boolean validarNombreUsuario(UsuarioDTO usuarioActual) throws Exception;
void borrarUsuario(Long id);
List<ComponenteDePantallaDto> obtenerComponentes() throws Exception;
boolean tienePermisoAcceso(String componente) throws Exception;
List<UsuarioDTO> obtenerListadoOperadoresCallCenter();
String obtenerComponente(String gestionCausasLegalesEscritura);
List<UsuarioDTO> obtenerUsariosComercializadores();
public Boolean cambiarPasswordUsuario(String password,String nuevaPassword,String nuevaPassword2);
List<UsuarioDTO> obtenerListadoOperadoresMoraTardia();
boolean tienePermisoAprobacionFinanciacionDirecta() throws Exception;
boolean tienePermisoAltaReparticion() throws Exception;
UsuarioDTO obtenerUsuarioPorNombreUsuario(String nombreUsuario) throws Exception;
/***
* Devuelve todos los usuarios de johnny con la opción de incluir los borrados
* @param incluirBorrados
* @return
*/
List<UsuarioDTO> obtenerUsuarios(boolean incluirBorrados);
List<EstablecimientoDTO> obtenerEstablecimientosUsuarioLogueadoRPC();
EstablecimientoDTO obtenerEstablecimientoRPC(Long id);
UsuarioDTO setearEstablecimientoXUsuarioRPC(long usuarioId,
long establecimientoId);
}
| true |
43f54fe5d426cbb0be616401b2a6127c47621f78 | Java | jTrader17/Java_Apps_CS_372 | /HW_3/PR3_1/src/pr3_1/Data.java | UTF-8 | 1,309 | 3.609375 | 4 | [] | no_license | /*
* 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 pr3_1;
import java.util.ArrayList;
import java.util.Scanner;
/**
*
* @author jtrader17
* @version 1
*/
public class Data {
Data(){};
/**
*
* @param numItems integer of the amount of items you want to get
* @return myList an ArrayList of all the numbers
* process checks to make sure all entries are integers
*/
public static ArrayList<Integer> getData(int numItems){
Scanner myScan = new Scanner(System.in);
ArrayList<Integer> myList = new ArrayList<>();
for(int i = 0; i<numItems; i++){
boolean cont;
do{
cont = true;
System.out.printf("%d number please (integer): ", i+1);
int temp;
try{
temp = myScan.nextInt();
myList.add(temp);
}
catch(Exception ex){
myScan.nextLine();
System.out.println("Give me an integer please.");
cont = false;
}
}while(!cont);
}
return myList;
}
}
| true |
a4bdcdc38b90e64e4e60d9c93aae56488da0dbc5 | Java | jwnichols3/esm-essb | /platform/Monitoring/src/com/bgi/esm/monitoring/platform/notifier/.svn/text-base/OviNotifier.java.svn-base | UTF-8 | 4,692 | 2.078125 | 2 | [] | no_license | package com.bgi.esm.monitoring.platform.notifier;
import java.io.BufferedWriter;
import java.io.FileWriter;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.jms.Topic;
import javax.jms.TopicConnection;
import javax.jms.TopicConnectionFactory;
import javax.jms.TopicSession;
import javax.jms.TopicSubscriber;
import javax.naming.Context;
import javax.naming.InitialContext;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.bgi.esm.monitoring.platform.utility.EventMineQueue;
import com.bgi.esm.monitoring.platform.utility.SuppressionQueue;
import com.bgi.esm.monitoring.platform.utility.StaticConfiguration;
import com.bgi.esm.monitoring.platform.utility.XmlParser;
import com.bgi.esm.monitoring.platform.value.EventMineMessage;
import com.bgi.esm.monitoring.platform.value.OviMessage;
import com.bgi.esm.monitoring.platform.value.SuppressionMessage;
import com.bgi.esm.monitoring.platform.value.XmlIf;
/**
* OviNotifier is the bridge between OVO manager and JMS.
*
* <p>
* OviNotifier is a persistent process.
*
* @author G.S. Cole (guycole at gmail dot com)
*/
public class OviNotifier implements MessageListener {
/**
* ctor, initialize dump file, suppression queue and topic.
*/
public OviNotifier() throws Exception {
if (StaticConfiguration.getBoolean("notifier.dump.enable") == Boolean.TRUE) {
String file_name = StaticConfiguration.getString("notifier.dump.file");
_log.debug("creating dump file:" + file_name);
_bw = new BufferedWriter(new FileWriter(file_name));
}
//
// Event Mine Queue Setup
//
String queue_name = StaticConfiguration.getString("queue.event_mine.name");
_emq = new EventMineQueue(queue_name);
//
// Suppression Queue Setup
//
queue_name = StaticConfiguration.getString("queue.suppression.name");
_sq = new SuppressionQueue(queue_name);
//
// OVI Topic Setup
//
_topic_name = StaticConfiguration.getString("topic.msi.name");
Context context = new InitialContext();
Topic topic = (Topic) context.lookup(_topic_name);
String topic_factory = StaticConfiguration.getString("jms.topic.factory");
TopicConnectionFactory factory = (TopicConnectionFactory) context.lookup(topic_factory);
TopicConnection connection = factory.createTopicConnection();
TopicSession sub_session = connection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
String sub_name = StaticConfiguration.getString("topic.msi.subscription");
TopicSubscriber subscriber = sub_session.createDurableSubscriber(topic, sub_name);
// TopicSubscriber subscriber = sub_session.createSubscriber(topic);
subscriber.setMessageListener(this);
connection.start();
}
/**
* Service a fresh incoming message. All traffic written to dump file if enabled.
* Only "ovMessage" from OVI will be processed for Suppression.
*
* @param arg raw JMS message
*/
public void onMessage(Message arg) {
try {
TextMessage message = (TextMessage) arg;
String text = message.getText();
_log.debug(text);
System.out.println(text);
if (_bw != null) {
_bw.write(text);
_bw.newLine();
}
XmlParser xp = new XmlParser();
XmlIf candidate = xp.oviParser(text);
if (candidate == null) {
_log.debug("reject:" + text);
} else {
EventMineMessage emm = new EventMineMessage();
emm.setSource(_topic_name);
emm.setPayload(text);
_emq.eventMineQueueWriter(emm);
OviMessage om = (OviMessage) candidate;
SuppressionMessage sm = new SuppressionMessage();
sm.setTicketMessage(om.getTicketMessage());
_sq.queueWriter(sm);
}
} catch (Exception exception) {
_log.error("choke", exception);
}
}
/**
* No work here, everything done in onMessage()
*
* @throws Exception for anything
*/
public void execute() throws Exception {
// empty
}
/**
* Main entry point for the Notifier.
*
* @param args OVO message elements, must be 16
* @throws Exception for anything
*/
public static void main(String[] args) throws Exception {
OviNotifier notifier = new OviNotifier();
notifier.execute();
}
/**
* Dump file
*/
private BufferedWriter _bw;
/**
* Downstream queue to Suppression
*/
private final EventMineQueue _emq;
/**
* Downstream queue to Suppression
*/
private final SuppressionQueue _sq;
/**
* Topic name, required for EventMine messages
*/
private final String _topic_name;
/**
* Logger
*/
private final Log _log = LogFactory.getLog(OviNotifier.class);
}
/*
* Development Environment:
* Fedora 4
* Sun Java Developers Kit 1.5.0_06
*/
| true |
7321308e3610fc7584ad835b62c6dd0ca0cd8079 | Java | develician/android-homework-resolver | /app/src/main/java/com/killi8n/contentresolver/contentresolverexample/CRActivity.java | UTF-8 | 5,426 | 2.25 | 2 | [] | no_license | package com.killi8n.contentresolver.contentresolverexample;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.support.v4.widget.SimpleCursorAdapter;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
public class CRActivity extends AppCompatActivity {
SimpleCursorAdapter ca;
ContentResolver cr;
Cursor cursor;
ListView listView;
String COLUMN_ID;
String COLUMN_COUNTRY;
String COLUMN_CAPITAL;
private static final Uri CONTENT_URI = Uri.parse("content://com.sample.contentproviderexample/world");
private static final int MENU_INSERT= Menu.FIRST + 1;
private static final int MENU_UPDATE= Menu.FIRST + 2;
private static final int MENU_DELETE= Menu.FIRST + 3;
private static final int RQ_INSERT = 1;
private static final int RQ_UPDATE = 2;
private static final int RQ_DELETE = 3;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cr);
cr = getContentResolver();
cursor = cr.query(CONTENT_URI, null, null, null, null);
if(cursor != null) {
COLUMN_ID = cursor.getColumnName(0);
COLUMN_COUNTRY = cursor.getColumnName(1);
COLUMN_CAPITAL = cursor.getColumnName(2);
ca = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_2, cursor, new String[]{COLUMN_COUNTRY, COLUMN_CAPITAL}, new int[]{android.R.id.text1, android.R.id.text2});
listView = (ListView) findViewById(R.id.listView);
listView.setAdapter(ca);
registerForContextMenu(listView);
} else {
new AlertDialog.Builder(this)
.setTitle("error")
.setMessage("데이터를 가져올수 없습니다.\n 프로바이더를확인하세요.")
.setPositiveButton("확인", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
finish();
}
})
.show();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
menu.add(Menu.NONE, MENU_INSERT, Menu.NONE, "입력하기");
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case MENU_INSERT:
Intent intent = new Intent(CRActivity.this, InsertActivity.class);
startActivityForResult(intent, RQ_INSERT);
break;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
menu.add(Menu.NONE, MENU_UPDATE, Menu.NONE,"업데이트");
menu.add(Menu.NONE, MENU_DELETE, Menu.NONE,"삭제하기");
}
@Override
public boolean onContextItemSelected(MenuItem item) {
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
int position = info.position;
cursor.moveToPosition(position);
int id = cursor.getInt(0);
String str1 = cursor.getString(1);
String str2 = cursor.getString(2);
switch (item.getItemId()) {
case MENU_UPDATE:
Intent i = new Intent(CRActivity.this, InsertActivity.class);
i.putExtra(COLUMN_ID, id);
i.putExtra(COLUMN_COUNTRY, str1);
i.putExtra(COLUMN_CAPITAL, str2);
startActivityForResult(i, RQ_UPDATE);
break;
case MENU_DELETE:
cr.delete(CONTENT_URI, COLUMN_ID + "=" + id, null);
cursor.requery();
break;
}
return super.onContextItemSelected(item);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(RESULT_OK == resultCode) {
ContentValues row = new ContentValues();
row.put(COLUMN_COUNTRY, data.getStringExtra(COLUMN_COUNTRY));
row.put(COLUMN_CAPITAL, data.getStringExtra(COLUMN_CAPITAL));
switch(requestCode) {
case RQ_INSERT:
cr.insert(CONTENT_URI, row);
break;
case RQ_UPDATE:
cr.update(CONTENT_URI, row, COLUMN_ID + "=" + data.getIntExtra(COLUMN_ID, 0), null);
break;
}
cursor.requery();
}
}
}
| true |
681e9ba07efdfaa40a010a8df2dc08446a1fb3af | Java | AcademyCity/SSM- | /src/main/java/com/paymanage/serviceImpl/UserServiceImpl.java | UTF-8 | 562 | 1.742188 | 2 | [] | no_license | package com.paymanage.serviceImpl;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import com.paymanage.entity.User;
import com.paymanage.mapper.UserMapper;
import com.paymanage.service.IUserService;
@Service("userService")
public class UserServiceImpl implements IUserService {
@Resource
private UserMapper userMapper;
@Override
public User getUserById(int userId) {
// TODO Auto-generated method stub
return this.userMapper.selectByPrimaryKey(userId);
}
} | true |
e756df3617001dafdedc10081dd14d5a4d8b221b | Java | bagasdany/Android-Studio-Retrofit-Login-dan-Registrasi-dengan-MySQL-Database | /app/src/main/java/com/example/nayatiapp/MainActivity2.java | UTF-8 | 1,638 | 2.265625 | 2 | [] | no_license | package com.example.nayatiapp;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import com.example.nayatiapp.APIPackage.ApiClient;
import com.example.nayatiapp.APIPackage.ApiInterface;
import com.example.nayatiapp.LoginPackage.PrefConfig;
import com.example.nayatiapp.LoginPackage.RegistrationFragment;
public class MainActivity2 extends AppCompatActivity implements LoginFragment.OnLoginFormActivityListener {
public static PrefConfig prefConfig;
public static ApiInterface apiInterface;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
prefConfig = new PrefConfig(this);
apiInterface = ApiClient.getApiClient().create(ApiInterface.class);
if (findViewById(R.id.fragment_container)!=null);
{
if (savedInstanceState!=null)
{
return;
}
if (prefConfig.readLoginStatus())
{
getSupportFragmentManager().beginTransaction().add(R.id.fragment_container,new WelcomeFragment()).commit();
}else
{
getSupportFragmentManager().beginTransaction().add(R.id.fragment_container,new RegistrationFragment()).commit();
}
}
}
@Override
public void performRegister() {
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new RegistrationFragment()).addToBackStack(null).commit();
}
@Override
public void performLogin(String email) {
}
}
| true |
65087c0d96aa4e8829db193af3314dff71c2beb6 | Java | venuscupid/LeetcodeInEclipse | /src/v2/P21_GenerateParentheses.java | UTF-8 | 1,481 | 3.421875 | 3 | [] | no_license | package v2;
import java.util.ArrayList;
//
//修改了无数回, submit了无数回
//错误!应该先建立test case,写完后测一下,在submit,否则面试官早就不接受了
//所以有时候在纸上写反而好,因为在电脑上写,会一上来就写代码,忘记先想测试用例,或者写好后迫不及待想看正不正确,从而懒得测试
public class P21_GenerateParentheses
{
public ArrayList<String> generateParenthesis(int n) {
if(n == 0) return null;
ArrayList<String> result = new ArrayList<String>();
StringBuilder sb = new StringBuilder();
makeCombination(result, n, sb, n, n);
return result;
}
public void makeCombination(ArrayList<String> result, int n, StringBuilder sb, int countLeft, int countRight)
{
if(sb.length() == 2 * n){
result.add(sb.toString());
return;
}
// if can add left, add left
if(countLeft > 0){
sb.append("(");
makeCombination(result, n, sb, countLeft - 1, countRight);
// after permutation, step back
sb.setLength(sb.length() - 1);
}
// if can add right, add right
if(countRight > 0 && countLeft < countRight){ // left is more used than right, i.e. can add right
sb.append(")");
makeCombination(result, n, sb, countLeft, countRight - 1);
// after permutation, step back
sb.setLength(sb.length() - 1);
}
}
} | true |
42d9a00ff1270a18339845b1baa2528189e46e3f | Java | Prashanth320/01-Assignment | /FindSumpaires.java | UTF-8 | 486 | 3.21875 | 3 | [] | no_license | package com.pr.ArrAss;
public class FindSumpaires {
public static void findPairs(int a[], int n) {
System.out.println("Pairs of elements whose sum is " + n + " are : ");
for (int i = 0; i < a.length; i++) {
for (int j = i + 1; j < a.length; j++) {
if (a[i] + a[j] == n) {
System.out.println(a[i] + " + " + a[j] + " = " + n);
}
}
}
}
public static void main(String[] args) {
findPairs(new int[] { 3, 6, 8, -8, 10, 8 }, 16);
}
}
| true |
c4863899bace5c8dc374906c8ac2284e73561c59 | Java | David-BIQI/shiro | /src/main/java/com/biqi/web/PageJumpController.java | UTF-8 | 614 | 1.773438 | 2 | [] | no_license | package com.biqi.web;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
/**
* @author xiebq 2018/10/16
*/
@Controller
@Slf4j
@Api(tags = {"页面跳转Api文档"})
public class PageJumpController {
@RequestMapping("/login")
public String login(){
return "/login";
}
@RequestMapping("/login2")
public String login2(){
return "/login2";
}
@RequestMapping("/main")
public String main(){
return"/main";
}
}
| true |
9edcd7df6cdb979409b367383365de151d57faa4 | Java | miaoyunchun/clb-api | /clb-provider/src/main/java/com/clps/dp/service/impl/DpGxwfinstStlServiceImpl.java | UTF-8 | 8,191 | 1.851563 | 2 | [] | no_license | package com.clps.dp.service.impl;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.alibaba.dubbo.config.annotation.Reference;
import com.clps.gb.service.TxnJourGenService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.alibaba.dubbo.config.annotation.Service;
import com.clps.core.common.service.BaseService;
import com.clps.core.sys.util.DateTimeUtils;
import com.clps.core.sys.util.QueryListUtils;
import com.clps.cp.pojo.CpProdparm;
import com.clps.cp.pojo.CpSctintPo;
import com.clps.cp.service.CPSCTInterestRateService;
import com.clps.cp.service.ProductParamService;
import com.clps.dp.pojo.DpAcctPo;
import com.clps.dp.pojo.DpBalancePo;
import com.clps.dp.pojo.DpCardPo;
import com.clps.dp.pojo.DpGxregflfPo;
import com.clps.dp.service.BalanceAddService;
import com.clps.dp.service.CardAcctInqService;
import com.clps.dp.service.GxwfinstStl;
/**
* 分布式服务接口实现
*
* @author blessing
*/
@Component // 注解 2017年2月8日添加
@Transactional // spring事务注解
@Service(version = "1.0.0") // 分布式服务注解和版本号
public class DpGxwfinstStlServiceImpl extends BaseService implements GxwfinstStl{
// 日志对象
private Logger log = LoggerFactory.getLogger(getClass().getName());
@Reference(version = "1.0.0")
// dubbo的服务注解,内有版本号 自动生成号码服务
private TxnJourGenService GBJour;
@Reference(version = "1.0.0")
// dubbo的服务注解,内有版本号 卡片账户信息查询
private CardAcctInqService cardacctinfo;
@Reference(version = "1.0.0")
// dubbo的服务注解,内有版本号 产品信息查询
private ProductParamService queryProductParam;
@Reference(version = "1.0.0")
// dubbo的服务注解,内有版本号 利率表查询
private CPSCTInterestRateService QueryCPSCTInterestRateService;
@Reference(version = "1.0.0")
// dubbo的服务注解,内有版本号 账户存款
private BalanceAddService nocardBalAddService;
//定义返回map
Map<String, Object> resultMap = new HashMap<String,Object>();
//定义pojo
/* @Autowired
private DpCardPo dpcard;
@Autowired
private DpAcctPo dpacct;
@Autowired
private CpProdparm cpprodparm;
@Autowired
private CpSctintPo cpsctintPo;
@Autowired
private DpBalancePo dpbalanceadd;*/
@SuppressWarnings({ "unchecked", "unused" })
@Transactional(readOnly = false, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)//非只读事务,支持当前事务(常见),遇到异常Rollback
@Override
public Map<String, Object> acctGxwfinstStl(DpGxregflfPo gxregflf) throws Exception {
// TODO Auto-generated method stub
// 记录日志
//定义pojo
DpCardPo dpcard = new DpCardPo();
DpAcctPo dpacct = new DpAcctPo();
CpProdparm cpprodparm = new CpProdparm();
CpSctintPo cpsctintPo = new CpSctintPo();
DpBalancePo dpbalanceadd = new DpBalancePo();
log.info("调用单条查询服务实现");
//查询卡片信息
dpcard.setCard_number(gxregflf.getCard_nbr());
dpcard= cardacctinfo.cardNoPinInq(dpcard);
//查询账户信息
dpacct.setAcct_nbr(dpcard.getAssociate_acct_id());
dpacct= cardacctinfo.acctInfoInq(dpacct);
//查询产品信息
cpprodparm.setProduct_id(dpacct.getProd_id());
cpprodparm=queryProductParam.queryProductParam(cpprodparm);
log.info(">>>test");
log.info(cpprodparm.toString());
log.info(cpsctintPo.toString());
log.info(">>>test-end");
//查询利率信息
cpsctintPo.setSct_id(cpprodparm.getInterest_control());
cpsctintPo=QueryCPSCTInterestRateService.QueryCPSCTInterestRateService(cpsctintPo);
//计算日利
//double interest_daily = (Double) interestInfoMap.get("interest_rate") / 360;
double interest_daily = Double.valueOf(cpsctintPo.getInterest_rate()) / 360;
// BigDecimal b = new BigDecimal(interest_daily);
// double f1 = b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
//计算利息
//BigDecimal b = new BigDecimal((Double) acctInfoMap.get("aggr_bal") * interest_daily);
BigDecimal b = new BigDecimal(Double.valueOf(dpacct.getAggr_bal()) * interest_daily);
double interest = b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
//本金+利息
//double totalAmt = (Double) acctInfoMap.get("acct_curr_bal") + interest;
double totalAmt = Double.valueOf(dpacct.getAcct_curr_bal()) + interest;
//更新账户信息
dpbalanceadd.setAcct_nbr(dpacct.getAcct_nbr());
dpbalanceadd.setMoney_add(String.valueOf(interest));
dpbalanceadd.setCreate_user(gxregflf.getCreate_user());
dpbalanceadd.setUpdate_user(gxregflf.getUpdate_user());
nocardBalAddService.nocardBalAddService(dpbalanceadd);
/* resultMap.put("acct_bal",acctInfoMap.get("acct_curr_bal"));
acctInfoMap.put("acct_last_bal",acctInfoMap.get("acct_curr_bal"));
acctInfoMap.put("acct_curr_bal",totalAmt);
int a = dao.updateByMap("dpBalanceRedMapper.dpBalanceUpdMapper", acctInfoMap);
if (a != 1){
resultMap.put("RESP-CODE", "0003");
return resultMap;
}*/
//调用GB服务生成交易流水号
Map<String, Object> gbmap = new HashMap<String,Object>();
gbmap.put("create_user", "test");
gbmap.put("update_user", "test");
gbmap.put("initial", "");
gbmap.put("length", "11");
gbmap=GBJour.txnJourGen(gbmap);
//写入交易历史表
Map<String, Object> translogmap=new HashMap<String, Object>();
resultMap.put("trans_id",gbmap.get("jour_nbr").toString());
resultMap.put("trans_sequence","00000000"+gbmap.get("jour_nbr"));
resultMap.put("trans_card", dpcard.getCard_number());
resultMap.put("trans_acct", dpacct.getAcct_nbr());
resultMap.put("trans_code", "5001");
resultMap.put("trans_desc", "ACCT REVORKE INTEST SETTLE");
resultMap.put("trans_time", DateTimeUtils.changeToTime());
resultMap.put("trans_date", DateTimeUtils.changeToDate());
resultMap.put("amount_before_trans", dpacct.getAcct_curr_bal());
resultMap.put("amount_in_trans", interest);
resultMap.put("amount_after_trans", totalAmt);
resultMap.put("remark", "ACCT REVORKE INTEST SETTLE");
resultMap.put("create_time", DateTimeUtils.nowToSystem());
resultMap.put("update_time", DateTimeUtils.nowToSystem());
resultMap.put("create_user", gbmap.get("create_user"));
resultMap.put("update_user", gbmap.get("update_user"));
// dao.insertOneByMap("dpBalanceRedMapper.addTransLogService", translogmap);
//输出数据
resultMap.put("card_nbr",dpcard.getCard_number());
resultMap.put("acct_nbr",dpacct.getAcct_nbr());
resultMap.put("acct_ccy",dpacct.getCcy());
resultMap.put("acct_ints_amt",interest);
resultMap.put("acct_total_bal",totalAmt);
resultMap.put("acct_bal",dpacct.getAcct_curr_bal());
return resultMap;
}
/**
* 交易历史写入
*/
@SuppressWarnings({ "unchecked", "unused" })
@Transactional(readOnly = false, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)//非只读事务,支持当前事务(常见),遇到异常Rollback
@Override
public Map<String, Object> transLogAdd(Map<String, Object> map) throws Exception {
dao.insertOneByMap("dpBalanceRedMapper.addTransLogService", map);
return map;
}
}
| true |
90a9a3c2906d044c2489eed42a61139b06386535 | Java | privacyidea/privacyidea-authenticator | /app/src/main/java/it/netknights/piauthenticator/services/FCMReceiverService.java | UTF-8 | 11,066 | 1.671875 | 2 | [
"MIT",
"Apache-2.0"
] | permissive | /*
privacyIDEA Authenticator
Authors: Nils Behlen <nils.behlen@netknights.it>
Copyright (c) 2017-2019 NetKnights GmbH
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 it.netknights.piauthenticator.services;
import android.app.ActivityManager;
import android.app.Notification;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import androidx.annotation.Nullable;
import androidx.core.app.NotificationCompat;
import androidx.core.app.NotificationManagerCompat;
import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Random;
import it.netknights.piauthenticator.R;
import it.netknights.piauthenticator.model.PushAuthRequest;
import it.netknights.piauthenticator.model.Token;
import it.netknights.piauthenticator.utils.SecretKeyWrapper;
import it.netknights.piauthenticator.utils.Util;
import it.netknights.piauthenticator.viewcontroller.MainActivity;
import static it.netknights.piauthenticator.utils.AppConstants.CHANNEL_ID_HIGH_PRIO;
import static it.netknights.piauthenticator.utils.AppConstants.CHANNEL_ID_LOW_PRIO;
import static it.netknights.piauthenticator.utils.AppConstants.INTENT_FILTER;
import static it.netknights.piauthenticator.utils.AppConstants.NONCE;
import static it.netknights.piauthenticator.utils.AppConstants.NOTIFICATION_ID;
import static it.netknights.piauthenticator.utils.AppConstants.QUESTION;
import static it.netknights.piauthenticator.utils.AppConstants.SERIAL;
import static it.netknights.piauthenticator.utils.AppConstants.SIGNATURE;
import static it.netknights.piauthenticator.utils.AppConstants.SSL_VERIFY;
import static it.netknights.piauthenticator.utils.AppConstants.TITLE;
import static it.netknights.piauthenticator.utils.AppConstants.URL;
import static it.netknights.piauthenticator.utils.Util.logprint;
public class FCMReceiverService extends FirebaseMessagingService {
String question, nonce, serial, signature, title, url;
boolean sslVerify = true;
@Override
public void onMessageReceived(RemoteMessage message) {
// get the key-value pairs
Map<String, String> map = message.getData();
logprint("FCM message received: " + message.getData().toString());
if (map.containsKey(QUESTION)) {
question = map.get(QUESTION);
}
if (map.containsKey(NONCE)) {
nonce = map.get(NONCE);
}
if (map.containsKey(SERIAL)) {
serial = map.get(SERIAL);
}
if (map.containsKey(TITLE)) {
title = map.get(TITLE);
}
if (map.containsKey(URL)) {
url = map.get(URL);
}
if (map.containsKey(SIGNATURE)) {
signature = map.get(SIGNATURE);
}
if (map.containsKey(SSL_VERIFY)) {
try {
if (Integer.parseInt(map.get(SSL_VERIFY)) < 1) {
sslVerify = false;
}
} catch (NullPointerException | NumberFormatException e) {
sslVerify = true;
}
}
// Generate a random notification ID
Random random = new Random();
int notificationID = random.nextInt(9999 - 1000) + 1000;
PushAuthRequest req = new PushAuthRequest(nonce, url, serial, question, title, signature, notificationID, sslVerify);
// check if the token was deleted from within the app,
// if that is the case do not show any notification for it
// if the token is found, append the request so it will be loaded when loading the app, if closed before
try {
Util util = new Util(new SecretKeyWrapper(this.getApplicationContext()),
this.getFilesDir().getAbsolutePath());
boolean tokenExists = false;
ArrayList<Token> tokens = util.loadTokens();
for (Token t : tokens) {
if (t.getSerial().equals(serial)) {
t.addPushAuthRequest(req);
tokenExists = true;
break;
}
}
if (!tokenExists) {
return;
}
util.saveTokens(tokens);
} catch (GeneralSecurityException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// Build an intent which will update the running app
Intent update_intent = new Intent(INTENT_FILTER);
update_intent = packIntent(update_intent, notificationID);
sendBroadcast(update_intent);
// Start the service with the data from the push when the button in the notification is pressed
Intent service_intent = new Intent(this, PushAuthService.class);
service_intent = packIntent(service_intent, notificationID);
// Or start the Activity with the same data if the notification is pressed
Intent activity_intent = new Intent(this, MainActivity.class);
activity_intent = packIntent(activity_intent, notificationID);
Notification notification = buildNotificationFromPush(getApplicationContext(), notificationID, service_intent,
activity_intent, title, question, "Token: " + activity_intent.getStringExtra(SERIAL), getApplicationContext().getString(R.string.Allow));
if (notification != null) {
//if (!appInForeground(getApplicationContext())) {
NotificationManagerCompat.from(this).notify(notificationID, notification);
//}
}
}
private static boolean appInForeground(Context context) {
ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningAppProcessInfo> runningAppProcesses = activityManager.getRunningAppProcesses();
if (runningAppProcesses == null) {
return false;
}
for (ActivityManager.RunningAppProcessInfo runningAppProcess : runningAppProcesses) {
if (runningAppProcess.processName.equals(context.getPackageName()) &&
runningAppProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
return true;
}
}
return false;
}
/**
* Build the default notification for a Push Authentication Request.
* Showing the title, question, an optional subtext and a button.
* Pressing the button will the start the sepcified service.
* The intents for the activity and the service need to be filled beforehand.
*
* @param context app context
* @param notificationID notification ID
* @param service_intent intent to start the service with, getService will be called on this
* @param activity_intent intent to start the activity with, getActivity will be called on this
* @param title notification title
* @param contextText notification text
* @param subText notification subtext, optional
* @param buttonText button text
* @return notification
*/
static Notification buildNotificationFromPush(Context context, int notificationID, Intent service_intent, Intent activity_intent,
String title, String contextText, @Nullable String subText, String buttonText) {
if (context == null || service_intent.getExtras() == null || activity_intent.getExtras() == null) {
logprint("Building default notification failed - missing parameters");
return null;
}
// Build the PendingIntents with the random notificationID as request code so multiple PendingIntents can live simultaneously
PendingIntent pActivity_intent = PendingIntent.getActivity(context, notificationID, activity_intent, PendingIntent.FLAG_UPDATE_CURRENT);
PendingIntent pService_intent = PendingIntent.getService(context, notificationID, service_intent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Action action = new NotificationCompat.Action.Builder(0, buttonText, pService_intent).build();
// If the app is already in foreground, add the notification with low priority so it does not pop up
boolean isAppInForeground = appInForeground(context);
String channelID = isAppInForeground ? CHANNEL_ID_LOW_PRIO : CHANNEL_ID_HIGH_PRIO;
int priority = isAppInForeground ? NotificationCompat.PRIORITY_LOW : NotificationCompat.PRIORITY_MAX;
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context, channelID) // Android 8+ uses notification channels
.setSmallIcon(R.drawable.ic_pi_notification)
.setContentTitle(title)
.setContentText(contextText)
.setPriority(priority) // 7.1 and lower
.addAction(action) // Add the allow Button
.setAutoCancel(true) // Remove the notification after tabbing it
.setWhen(0)
.setContentIntent(pActivity_intent) // Intent for opening activity with the request
.setDefaults(Notification.DEFAULT_SOUND); // Play a sound/vibrate for push auth
if (subText != null) {
mBuilder.setSubText(subText);
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
mBuilder.setColor(context.getResources().getColor(R.color.PIBLUE, null));
}
return mBuilder.build();
}
/**
* Add the data from the FCM Message to the intent.
*
* @param intent intent to add data to
* @return the intent
*/
Intent packIntent(Intent intent, int notificationID) {
intent.putExtra(SERIAL, serial)
.putExtra(NONCE, nonce)
.putExtra(TITLE, title)
.putExtra(URL, url)
.putExtra(SIGNATURE, signature)
.putExtra(QUESTION, question)
.putExtra(SSL_VERIFY, sslVerify)
.putExtra(NOTIFICATION_ID, notificationID);
return intent;
}
@Override
public void onNewToken(String s) {
super.onNewToken(s);
logprint("New Token in FCMReceiver: " + s);
}
} | true |
b5074881aec105e3960c68e6e958ae0c0bb5b2ef | Java | nathalapooja/careership-master | /CareerShip/src/main/java/com/vjf/car/model/JobSeekerLogin.java | UTF-8 | 1,237 | 2.421875 | 2 | [] | no_license | package com.vjf.car.model;
public class JobSeekerLogin {
public String jName;
public String jPassword;
@Override
public String toString() {
return "JobSeekerLogin [jName=" + jName + ", jPassword=" + jPassword + "]";
}
public String getjName() {
return jName;
}
public void setjName(String jName) {
this.jName = jName;
}
public String getjPassword() {
return jPassword;
}
public void setjPassword(String jPassword) {
this.jPassword = jPassword;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((jName == null) ? 0 : jName.hashCode());
result = prime * result + ((jPassword == null) ? 0 : jPassword.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
JobSeekerLogin other = (JobSeekerLogin) obj;
if (jName == null) {
if (other.jName != null)
return false;
} else if (!jName.equals(other.jName))
return false;
if (jPassword == null) {
if (other.jPassword != null)
return false;
} else if (!jPassword.equals(other.jPassword))
return false;
return true;
}
}
| true |
e67e527a2e2e13f0a2426527da7edf3164c957a2 | Java | ShohichiNaitoh/JAVA_TRAINING | /java_training/JPL/ch16/ex16_03/ClassContents.java | UTF-8 | 1,285 | 3.75 | 4 | [] | no_license | package ch16.ex16_03;
import java.lang.reflect.Member;
import java.util.ArrayList;
public class ClassContents {
private static ArrayList<String> memberList = new ArrayList<String>();
/**
* @param args
*/
public static void main(String[] args) {
try{
Class<?> c = Class.forName(args[0]);
System.out.println(c);
printMembers(c.getFields());
printMembers(c.getDeclaredFields());
printMembers(c.getConstructors());
printMembers(c.getDeclaredConstructors());
printMembers(c.getMethods());
printMembers(c.getDeclaredMethods());
}catch(ClassNotFoundException e){
System.out.println("unkown class: " + args[0]);
}
}
private static void printMembers(Member[] mems){
for(Member m : mems){
if(m.getDeclaringClass() == Object.class){
continue;
}
String dec1 = m.toString();
boolean doDisplay = true;
for(String existMember : ClassContents.memberList){
if(dec1.equals(existMember)){
doDisplay = false;
}
}
ClassContents.memberList.add(dec1);
if(!doDisplay){
System.out.print(" ");
System.out.println(strip(dec1, "java.lang."));
}
}
}
private static String strip(String str , String stripedStr){
return str.replaceAll(stripedStr, "");
}
}
| true |
fcd6b6a56c73feb786269647aa0b25ea152e5abe | Java | jasokan/myplayground | /java-examples/src/test/java/com/jasokan/samples/JPower2.java | UTF-8 | 411 | 3.3125 | 3 | [] | no_license | package com.jasokan.samples;
import java.util.Scanner;
/**
* @author jasokan
*
*/
public class JPower2 {
public static void main(String[] args) {
Scanner userInput = new Scanner(System.in);
int inputNumber = userInput.nextInt();
if(Integer.bitCount(inputNumber) == 1) {
System.out.println("Power of 2");
} else {
System.out.println("Not Power of 2");
}
userInput.close();
}
}
| true |
d446c6a14cc22549af3354b2a442763ff870d6b0 | Java | dlghrms1992/DesignPatternStudy | /DesignPattern/src/FactoryPattern/FactoryPattern.java | UHC | 2,886 | 4.03125 | 4 | [] | no_license | package FactoryPattern;
/*
* ̿Ѵ ü
* 丮 - ٲ κ ĸȭ϶
* 丮 ҵ - 丮 ҵ Ͽ ü ϱ ̽ ϴµ Ŭ νϽ
* 丮 - ̽ ̿Ͽ , Ǵ ϴ ü Ŭ ʰ ִ.
* Ŭ ϰ , 丮 ҵ ̿ϸ Ŭ νϽ Ŭ ñ .
*
* Ŭ νϽ κ ãƳ ø̼ κκ и/ĸȭų ִ ? ü 丮
* 丮 Ͽ ü ĸȭѴ. 丮 ҵ Ͽ Ŭ Ŭ ϰ ν ü ĸȭѴ.
* ǰ, ΰ Ŭ ִٰ ϸ, Ŭ غ
*
* Ģ - ȭ Ϳ ϵ . Ŭ ϵ ʵ Ѵ.
* 丮 vs 丮
* - 丮 ҵ ؼ ü . Ŭ и ϴ. -> ü ϱ ̽ . Ŭ νϽ Ŭ ϵ Ѵ.
* - 丮 ҵ带 ̿ϸ νϽ Ŭ ̷ ִ.
* - 丮 ü ؼ . Ŭ ǵȴ. ̽ ؼ Ѵ.
*
* ü ĸȭؼ ø̼ ϰ Ư ϵ ִ. -> , Ǵ ü ̷ ǰ ϱ
* - ̽ . Ŭ Ŭ 巷
*
* ü Ģ
* - ٲ κ ĸȭѴ.
* - Ӻٴ ȰѴ.
* - ƴ ̽ 缭 αѴ.
* - ȣۿ ϴ ü ̿ ϸ ϰ ϴ ؾѴ.
* - Ŭ Ȯ忡 ؼ 濡 㼭 ־ Ѵ.
* - ȭ Ϳ ϶. Ŭ ʵ Ѵ.
*
* */
public class FactoryPattern {
}
| true |
27f579be889165401eaa18988e426b77ab946fe6 | Java | along1013/Observer | /src/main/java/ConcreateObserver.java | UTF-8 | 174 | 2.3125 | 2 | [] | no_license | /**
* Created by mangguo on 2016/4/25.
*/
public class ConcreateObserver implements Observer {
public void update(String str) {
System.out.printf(str);
}
}
| true |
6757f3d93809c7b21c3fb8eae69c690368c5ac15 | Java | spring-projects/spring-data-examples | /jpa/deferred/src/main/java/example/service/Customer243Service.java | UTF-8 | 221 | 1.65625 | 2 | [
"Apache-2.0"
] | permissive | package example.service;
import example.repo.Customer243Repository;
import org.springframework.stereotype.Service;
@Service
public class Customer243Service {
public Customer243Service(Customer243Repository repo) {}
}
| true |
fbed3b5c280b02cf017eb9edd89ab8f19e422cfd | Java | MayurSTechnoCredit/JAVATechnoJuly2021 | /src/akanksha_Jain/Assignment_34/Program_2.java | UTF-8 | 1,271 | 3.640625 | 4 | [] | no_license | /* Assignment - 34 : 11th Sep'2021
program 2 : place sum of triple after each triple which in sequence.
input = {1,3,4,5,7,3,9,10,11,14,44,67,1,2,3,99};
output = [1,3,4,5,12,7,3,9,10,11,30,14,44,67,1,2,3,6,99];
*/
package akanksha_Jain.Assignment_34;
import java.util.Arrays;
public class Program_2 {
int getTripleSeqCount(int[] arr) {
int count=0;
for(int index=0; index<arr.length-2; index++) {
if(arr[index+1]==arr[index]+1 && arr[index+2]==arr[index+1]+1) {
count ++;
}
}
return count;
}
void addTripleSeqSumAfterTripleSeq(int[] arr) {
int[] output = new int[arr.length+getTripleSeqCount(arr)];
int outputIndex = 2;
output[0]=arr[0];
output[1]=arr[1];
for(int index=2;index<arr.length;index++) {
output[outputIndex++]=arr[index];
if(arr[index-1]==arr[index-2]+1 && arr[index]==arr[index-1]+1)
output[outputIndex++]=arr[index] + arr [index-1] + arr[index-2];
}
System.out.println("After triple seqeunce, adding sum of triplets in given array-\n" +Arrays.toString(arr) + "\nThe output is " +Arrays.toString(output));
}
public static void main(String[] args) {
int[] arr = {1,3,4,5,7,3,9,10,11,14,44,67,1,2,3,99};
Program_2 program2 = new Program_2();
program2.addTripleSeqSumAfterTripleSeq(arr);
}
}
| true |
45bb157d852ccd8197b6e12cb6c82bee60dd4561 | Java | cckmit/cuppy | /hybris/bin/ext-integration/sap/productconfig/ysapproductconfigb2baddon/acceleratoraddon/web/src/de/hybris/platform/sap/productconfig/frontend/controllers/ConfigureProductController.java | UTF-8 | 5,902 | 1.523438 | 2 | [] | no_license | /*
* [y] hybris Platform
*
* Copyright (c) 2000-2016 hybris AG
* All rights reserved.
*
* This software is the confidential and proprietary information of hybris
* ("Confidential Information"). You shall not disclose such Confidential
* Information and shall use it only in accordance with the terms of the
* license agreement you entered into with hybris.
*
*
*/
package de.hybris.platform.sap.productconfig.frontend.controllers;
import de.hybris.platform.acceleratorstorefrontcommons.constants.WebConstants;
import de.hybris.platform.cms2.exceptions.CMSItemNotFoundException;
import de.hybris.platform.core.model.product.ProductModel;
import de.hybris.platform.sap.productconfig.facades.ConfigurationData;
import de.hybris.platform.sap.productconfig.facades.KBKeyData;
import de.hybris.platform.sap.productconfig.frontend.UiStatus;
import de.hybris.platform.sap.productconfig.frontend.breadcrumb.ProductConfigureBreadcrumbBuilder;
import de.hybris.platform.sap.productconfig.frontend.constants.Sapproductconfigb2baddonConstants;
import de.hybris.platform.sap.productconfig.frontend.util.impl.UiStatusSync;
import java.io.UnsupportedEncodingException;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
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;
@Controller
@RequestMapping()
public class ConfigureProductController extends AbstractProductConfigController
{
@Resource(name = "sapProductConfigBreadcrumbBuilder")
private ProductConfigureBreadcrumbBuilder productConfigurationBreadcrumbBuilder;
static private final Logger LOG = Logger.getLogger(ConfigureProductController.class);
@RequestMapping(value = "/**/{productCode:.*}/configEntry", method = RequestMethod.GET)
public String configureProduct(@PathVariable("productCode")
final String productCode) throws CMSItemNotFoundException, UnsupportedEncodingException
{
if (LOG.isDebugEnabled())
{
LOG.debug("Config GET received for '" + productCode + "' - Current Session: '"
+ getSessionService().getCurrentSession().getSessionId() + "'");
}
final UiStatus uiStatus = getSessionAccessFacade().getUiStatusForProduct(productCode);
final String selectedGroup = getSelectedGroup(uiStatus);
String redirectURL;
if (selectedGroup != null)
{
redirectURL = "redirect:/" + productCode + "/config?tab=" + selectedGroup;
}
else
{
redirectURL = "redirect:/" + productCode + "/config";
}
if (LOG.isDebugEnabled())
{
LOG.debug("Redirect to: '" + redirectURL + "'");
}
return redirectURL;
}
@RequestMapping(value = "/**/{productCode:.*}/config", method = RequestMethod.GET)
public String configureProduct(@PathVariable("productCode")
final String productCode, @RequestParam(value = "tab", required = false)
final String selectedGroup, final Model model, final HttpServletRequest request)
throws CMSItemNotFoundException, UnsupportedEncodingException
{
if (LOG.isDebugEnabled())
{
LOG.debug("Config GET received for '" + productCode + "' - Current Session: '"
+ getSessionService().getCurrentSession().getSessionId() + "'");
}
final ProductModel productmodel = getProductService().getProductForCode(productCode);
model.addAttribute(WebConstants.BREADCRUMBS_KEY, productConfigurationBreadcrumbBuilder.getBreadcrumbs(productmodel));
populateConfigurationModel(request, selectedGroup, model, productCode);
final String viewName = "addon:/" + Sapproductconfigb2baddonConstants.EXTENSIONNAME
+ "/pages/configuration/configurationPage";
return viewName;
}
protected void populateConfigurationModel(final HttpServletRequest request, final String selectedGroup, final Model model,
final String productCode) throws CMSItemNotFoundException
{
final ProductModel productModel = populateProductModel(productCode, model, request);
if (model.containsAttribute(Sapproductconfigb2baddonConstants.CONFIG_ATTRIBUTE))
{
return;
}
final KBKeyData kbKey = createKBKeyForProduct(productModel);
String configId = null;
final ConfigurationData configData;
final UiStatus uiStatus = getSessionAccessFacade().getUiStatusForProduct(productCode);
if (uiStatus != null)
{
configId = uiStatus.getConfigId();
configData = reloadConfiguration(kbKey, configId, selectedGroup, uiStatus);
}
else
{
configData = loadNewConfiguration(kbKey, selectedGroup, null);
}
final UiStatusSync uiStatusSync = new UiStatusSync();
uiStatusSync.compileGroupForDisplay(configData, uiStatus);
setCartItemPk(configData);
model.addAttribute(Sapproductconfigb2baddonConstants.CONFIG_ATTRIBUTE, configData);
final BindingResult errors = getBindingResultForConfig(configData, uiStatus);
model.addAttribute(BindingResult.MODEL_KEY_PREFIX + Sapproductconfigb2baddonConstants.CONFIG_ATTRIBUTE, errors);
countNumberOfUiErrorsPerGroup(configData.getGroups());
logModelmetaData(configData);
}
@RequestMapping(value = "/**/{productCode:.*}/addToCartPopup", method = RequestMethod.GET)
public String configAddToCartPopup(@PathVariable("productCode")
final String productCode, final Model model, final HttpServletRequest request) throws CMSItemNotFoundException
{
if (LOG.isDebugEnabled())
{
LOG.debug("Retrieving content for addToCartPopup via GET ('" + productCode + "')");
}
populateConfigurationModel(request, null, model, productCode);
final String fragmentURL = "addon:/" + Sapproductconfigb2baddonConstants.EXTENSIONNAME
+ "/fragments/configuration/configAddToCartPopup";
return fragmentURL;
}
}
| true |
3aaf3b9a3f724f77ff9491720da1a7e96e803d9e | Java | nimacgit/AP-assignment | /src/model/shape/animation/RectScale.java | UTF-8 | 6,111 | 2.28125 | 2 | [] | no_license | package model.shape.animation;
import model.shape.Rectangle;
import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import static model.panels.ViewPanel.isAnimating;
public class RectScale extends Animation {
double scale = 2;
JTextField attribScale;
JLabel attribScaleLable;
int fontSize = 40;
double dw;
double dh;
double endWidth;
double endHeight;
public RectScale(int duration, Rectangle rectangle) {
super(rectangle);
this.name = "RectScale";
this.durationTime = duration;
this.scale = scale;
endWidth = ((Rectangle) thisShape).getWidth() * scale;
endHeight = ((Rectangle) thisShape).getHeight() * scale;
attribScale = new JTextField("scale");
attribScaleLable = new JLabel("Scale");
attribScale.setHorizontalAlignment(SwingConstants.CENTER);
attribScale.setBackground(Color.YELLOW);
attribScale.setFont(new Font(null, 0, fontSize));
attribScale.setSelectedTextColor(Color.BLUE);
attribScaleLable.setFont(new Font(null,0,fontSize));
setButton.addMouseListener(new rectangleScaleActionListener());
dw = endWidth - ((Rectangle) thisShape).getWidth();
dw /= (100*durationTime);
dh = endHeight - ((Rectangle) thisShape).getHeight();
dh /= (100*durationTime);
}
@Override
public boolean step() {
if(enable) {
int sign = 1;
if (forwardOrBackward) {
if (Math.abs(((Rectangle) thisShape).getWidth() + dw - endWidth) > Math.abs(((Rectangle) thisShape).getWidth() - endWidth)) {
forwardOrBackward = false;
endWidth = endWidth / scale;
endHeight = endHeight / scale;
} else
sign = 1;
} else if (doesRepeat) {
if (Math.abs(((Rectangle) thisShape).getWidth() - dw - endWidth) > Math.abs(((Rectangle) thisShape).getWidth() - endWidth)) {
forwardOrBackward = true;
endWidth = endWidth * scale;
endHeight = endHeight * scale;
} else
sign = -1;
}
else
return false;
if ((sign == -1 && !forwardOrBackward) || (sign == 1 && forwardOrBackward)) {
((Rectangle) thisShape).setWidth(((Rectangle) thisShape).getWidth() + sign * dw);
((Rectangle) thisShape).setHeight(((Rectangle) thisShape).getHeight() + sign * dh);
return true;
}
}
return true;
}
@Override
public void reset() {
forwardOrBackward = true;
endWidth = ((Rectangle) thisShape).getWidth() * scale;
endHeight = ((Rectangle) thisShape).getHeight() * scale;
}
@SuppressWarnings("Duplicates")
@Override
public void setAnimationAttribPanel() {
thisShape.frame.menuPanel.animationMenu.animationAttribPanel.setLayout(new GridLayout(5,2));
if (thisShape.frame.menuPanel.animationMenu.animationAttribPanel != null) {
attribScale.setMaximumSize(new Dimension(thisShape.frame.menuPanel.animationMenu.animationAttribPanel.getSize().width / 2, thisShape.frame.menuPanel.animationMenu.animationAttribPanel.getSize().height / 3));
setButton.setMaximumSize(new Dimension(thisShape.frame.menuPanel.animationMenu.animationAttribPanel.getSize().width / 3, thisShape.frame.menuPanel.animationMenu.animationAttribPanel.getSize().height / 3));
repeatingBox.setMaximumSize(new Dimension(thisShape.frame.menuPanel.animationMenu.animationAttribPanel.getSize().width / 3, thisShape.frame.menuPanel.animationMenu.animationAttribPanel.getSize().height / 3));
}
attribScale.setText(String.valueOf(scale));
attribTime.setText(String.valueOf(durationTime));
repeatingBox.setSelected(doesRepeat);
enableBox.setSelected(enable);
thisShape.frame.menuPanel.animationMenu.animationAttribPanel.add(attribScaleLable);
thisShape.frame.menuPanel.animationMenu.animationAttribPanel.add(attribScale);
thisShape.frame.menuPanel.animationMenu.animationAttribPanel.add(attribTimeLable);
thisShape.frame.menuPanel.animationMenu.animationAttribPanel.add(attribTime);
thisShape.frame.menuPanel.animationMenu.animationAttribPanel.add(repeatingBox);
thisShape.frame.menuPanel.animationMenu.animationAttribPanel.add(enableBox);
thisShape.frame.menuPanel.animationMenu.animationAttribPanel.add(setButton);
}
class rectangleScaleActionListener extends MouseAdapter {
//stepDelay = duration;
@Override
public void mouseReleased(MouseEvent e) {
if (!isAnimating) {
if (forwardOrBackward) {
((Rectangle) thisShape).setWidth(endWidth / scale);
((Rectangle) thisShape).setHeight(endHeight / scale);
} else {
((Rectangle) thisShape).setWidth(endWidth);
((Rectangle) thisShape).setHeight(endHeight);
}
scale = Double.parseDouble(attribScale.getText());
double t = Double.parseDouble(attribTime.getText());
enable = enableBox.isSelected();
doesRepeat = repeatingBox.isSelected();
endWidth = ((Rectangle) thisShape).getWidth() * scale;
endHeight = ((Rectangle) thisShape).getHeight() * scale;
dw = endWidth - ((Rectangle) thisShape).getWidth();
dw /= (100 * t);
dh = endHeight - ((Rectangle) thisShape).getHeight();
dh /= (100 * t);
durationTime = t;
thisShape.frame.repaint();
thisShape.frame.revalidate();
}
}
}
}
| true |
11f7f2b023300cbcec0845d09a161e11bb77dc63 | Java | LWJGL/lwjgl3 | /modules/samples/src/test/java/org/lwjgl/demo/nuklear/GLFWDemo.java | UTF-8 | 25,552 | 2.03125 | 2 | [
"LGPL-2.0-or-later",
"BSD-3-Clause",
"LicenseRef-scancode-free-unknown",
"LicenseRef-scancode-public-domain",
"BSD-2-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | /*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
*/
package org.lwjgl.demo.nuklear;
import org.lwjgl.glfw.*;
import org.lwjgl.nuklear.*;
import org.lwjgl.opengl.*;
import org.lwjgl.stb.*;
import org.lwjgl.system.*;
import java.io.*;
import java.nio.*;
import java.util.*;
import static org.lwjgl.demo.util.IOUtil.*;
import static org.lwjgl.glfw.Callbacks.*;
import static org.lwjgl.glfw.GLFW.*;
import static org.lwjgl.nuklear.Nuklear.*;
import static org.lwjgl.opengl.ARBDebugOutput.*;
import static org.lwjgl.opengl.GL30C.*;
import static org.lwjgl.stb.STBTruetype.*;
import static org.lwjgl.system.MemoryStack.*;
import static org.lwjgl.system.MemoryUtil.*;
/**
* Nuklear demo using GLFW, OpenGL and stb_truetype for rendering.
*
* <p>This demo is a Java port of
* <a href="https://github.com/vurtun/nuklear/tree/master/demo/glfw_opengl3">https://github.com/vurtun/nuklear/tree/master/demo/glfw_opengl3</a>.</p>
*/
public class GLFWDemo {
private static final int BUFFER_INITIAL_SIZE = 4 * 1024;
private static final int MAX_VERTEX_BUFFER = 512 * 1024;
private static final int MAX_ELEMENT_BUFFER = 128 * 1024;
private static final NkAllocator ALLOCATOR;
private static final NkDrawVertexLayoutElement.Buffer VERTEX_LAYOUT;
static {
ALLOCATOR = NkAllocator.create()
.alloc((handle, old, size) -> nmemAllocChecked(size))
.mfree((handle, ptr) -> nmemFree(ptr));
VERTEX_LAYOUT = NkDrawVertexLayoutElement.create(4)
.position(0).attribute(NK_VERTEX_POSITION).format(NK_FORMAT_FLOAT).offset(0)
.position(1).attribute(NK_VERTEX_TEXCOORD).format(NK_FORMAT_FLOAT).offset(8)
.position(2).attribute(NK_VERTEX_COLOR).format(NK_FORMAT_R8G8B8A8).offset(16)
.position(3).attribute(NK_VERTEX_ATTRIBUTE_COUNT).format(NK_FORMAT_COUNT).offset(0)
.flip();
}
public static void main(String[] args) {
new GLFWDemo().run();
}
private final ByteBuffer ttf;
private long win;
private int
width,
height;
private int
display_width,
display_height;
private NkContext ctx = NkContext.create();
private NkUserFont default_font = NkUserFont.create();
private NkBuffer cmds = NkBuffer.create();
private NkDrawNullTexture null_texture = NkDrawNullTexture.create();
private int vbo, vao, ebo;
private int prog;
private int vert_shdr;
private int frag_shdr;
private int uniform_tex;
private int uniform_proj;
private final Demo demo = new Demo();
private final Calculator calc = new Calculator();
public GLFWDemo() {
try {
this.ttf = ioResourceToByteBuffer("demo/FiraSans.ttf", 512 * 1024);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private void run() {
GLFWErrorCallback.createPrint().set();
if (!glfwInit()) {
throw new IllegalStateException("Unable to initialize glfw");
}
glfwDefaultWindowHints();
glfwWindowHint(GLFW_VISIBLE, GLFW_FALSE);
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
if (Platform.get() == Platform.MACOSX) {
glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GLFW_TRUE);
}
glfwWindowHint(GLFW_OPENGL_DEBUG_CONTEXT, GLFW_TRUE);
int WINDOW_WIDTH = 640;
int WINDOW_HEIGHT = 640;
win = glfwCreateWindow(WINDOW_WIDTH, WINDOW_HEIGHT, "GLFW Nuklear Demo", NULL, NULL);
if (win == NULL) {
throw new RuntimeException("Failed to create the GLFW window");
}
glfwMakeContextCurrent(win);
GLCapabilities caps = GL.createCapabilities();
Callback debugProc = GLUtil.setupDebugMessageCallback();
if (caps.OpenGL43) {
GL43.glDebugMessageControl(GL43.GL_DEBUG_SOURCE_API, GL43.GL_DEBUG_TYPE_OTHER, GL43.GL_DEBUG_SEVERITY_NOTIFICATION, (IntBuffer)null, false);
} else if (caps.GL_KHR_debug) {
KHRDebug.glDebugMessageControl(
KHRDebug.GL_DEBUG_SOURCE_API,
KHRDebug.GL_DEBUG_TYPE_OTHER,
KHRDebug.GL_DEBUG_SEVERITY_NOTIFICATION,
(IntBuffer)null,
false
);
} else if (caps.GL_ARB_debug_output) {
glDebugMessageControlARB(GL_DEBUG_SOURCE_API_ARB, GL_DEBUG_TYPE_OTHER_ARB, GL_DEBUG_SEVERITY_LOW_ARB, (IntBuffer)null, false);
}
NkContext ctx = setupWindow(win);
int BITMAP_W = 1024;
int BITMAP_H = 1024;
int FONT_HEIGHT = 18;
int fontTexID = glGenTextures();
STBTTFontinfo fontInfo = STBTTFontinfo.create();
STBTTPackedchar.Buffer cdata = STBTTPackedchar.create(95);
float scale;
float descent;
try (MemoryStack stack = stackPush()) {
stbtt_InitFont(fontInfo, ttf);
scale = stbtt_ScaleForPixelHeight(fontInfo, FONT_HEIGHT);
IntBuffer d = stack.mallocInt(1);
stbtt_GetFontVMetrics(fontInfo, null, d, null);
descent = d.get(0) * scale;
ByteBuffer bitmap = memAlloc(BITMAP_W * BITMAP_H);
STBTTPackContext pc = STBTTPackContext.malloc(stack);
stbtt_PackBegin(pc, bitmap, BITMAP_W, BITMAP_H, 0, 1, NULL);
stbtt_PackSetOversampling(pc, 4, 4);
stbtt_PackFontRange(pc, ttf, 0, FONT_HEIGHT, 32, cdata);
stbtt_PackEnd(pc);
// Convert R8 to RGBA8
ByteBuffer texture = memAlloc(BITMAP_W * BITMAP_H * 4);
for (int i = 0; i < bitmap.capacity(); i++) {
texture.putInt((bitmap.get(i) << 24) | 0x00FFFFFF);
}
texture.flip();
glBindTexture(GL_TEXTURE_2D, fontTexID);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, BITMAP_W, BITMAP_H, 0, GL_RGBA, GL_UNSIGNED_INT_8_8_8_8_REV, texture);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
memFree(texture);
memFree(bitmap);
}
default_font
.width((handle, h, text, len) -> {
float text_width = 0;
try (MemoryStack stack = stackPush()) {
IntBuffer unicode = stack.mallocInt(1);
int glyph_len = nnk_utf_decode(text, memAddress(unicode), len);
int text_len = glyph_len;
if (glyph_len == 0) {
return 0;
}
IntBuffer advance = stack.mallocInt(1);
while (text_len <= len && glyph_len != 0) {
if (unicode.get(0) == NK_UTF_INVALID) {
break;
}
/* query currently drawn glyph information */
stbtt_GetCodepointHMetrics(fontInfo, unicode.get(0), advance, null);
text_width += advance.get(0) * scale;
/* offset next glyph */
glyph_len = nnk_utf_decode(text + text_len, memAddress(unicode), len - text_len);
text_len += glyph_len;
}
}
return text_width;
})
.height(FONT_HEIGHT)
.query((handle, font_height, glyph, codepoint, next_codepoint) -> {
try (MemoryStack stack = stackPush()) {
FloatBuffer x = stack.floats(0.0f);
FloatBuffer y = stack.floats(0.0f);
STBTTAlignedQuad q = STBTTAlignedQuad.malloc(stack);
IntBuffer advance = stack.mallocInt(1);
stbtt_GetPackedQuad(cdata, BITMAP_W, BITMAP_H, codepoint - 32, x, y, q, false);
stbtt_GetCodepointHMetrics(fontInfo, codepoint, advance, null);
NkUserFontGlyph ufg = NkUserFontGlyph.create(glyph);
ufg.width(q.x1() - q.x0());
ufg.height(q.y1() - q.y0());
ufg.offset().set(q.x0(), q.y0() + (FONT_HEIGHT + descent));
ufg.xadvance(advance.get(0) * scale);
ufg.uv(0).set(q.s0(), q.t0());
ufg.uv(1).set(q.s1(), q.t1());
}
})
.texture(it -> it
.id(fontTexID));
nk_style_set_font(ctx, default_font);
glfwShowWindow(win);
while (!glfwWindowShouldClose(win)) {
/* Input */
newFrame();
demo.layout(ctx, 50, 50);
calc.layout(ctx, 300, 50);
try (MemoryStack stack = stackPush()) {
IntBuffer width = stack.mallocInt(1);
IntBuffer height = stack.mallocInt(1);
glfwGetWindowSize(win, width, height);
glViewport(0, 0, width.get(0), height.get(0));
NkColorf bg = demo.background;
glClearColor(bg.r(), bg.g(), bg.b(), bg.a());
}
glClear(GL_COLOR_BUFFER_BIT);
/*
* IMPORTANT: `nk_glfw_render` modifies some global OpenGL state
* with blending, scissor, face culling, depth test and viewport and
* defaults everything back into a default state.
* Make sure to either a.) save and restore or b.) reset your own state after
* rendering the UI.
*/
render(NK_ANTI_ALIASING_ON, MAX_VERTEX_BUFFER, MAX_ELEMENT_BUFFER);
glfwSwapBuffers(win);
}
shutdown();
glfwFreeCallbacks(win);
if (debugProc != null) {
debugProc.free();
}
glfwTerminate();
Objects.requireNonNull(glfwSetErrorCallback(null)).free();
}
private void setupContext() {
String NK_SHADER_VERSION = Platform.get() == Platform.MACOSX ? "#version 150\n" : "#version 300 es\n";
String vertex_shader =
NK_SHADER_VERSION +
"uniform mat4 ProjMtx;\n" +
"in vec2 Position;\n" +
"in vec2 TexCoord;\n" +
"in vec4 Color;\n" +
"out vec2 Frag_UV;\n" +
"out vec4 Frag_Color;\n" +
"void main() {\n" +
" Frag_UV = TexCoord;\n" +
" Frag_Color = Color;\n" +
" gl_Position = ProjMtx * vec4(Position.xy, 0, 1);\n" +
"}\n";
String fragment_shader =
NK_SHADER_VERSION +
"precision mediump float;\n" +
"uniform sampler2D Texture;\n" +
"in vec2 Frag_UV;\n" +
"in vec4 Frag_Color;\n" +
"out vec4 Out_Color;\n" +
"void main(){\n" +
" Out_Color = Frag_Color * texture(Texture, Frag_UV.st);\n" +
"}\n";
nk_buffer_init(cmds, ALLOCATOR, BUFFER_INITIAL_SIZE);
prog = glCreateProgram();
vert_shdr = glCreateShader(GL_VERTEX_SHADER);
frag_shdr = glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(vert_shdr, vertex_shader);
glShaderSource(frag_shdr, fragment_shader);
glCompileShader(vert_shdr);
glCompileShader(frag_shdr);
if (glGetShaderi(vert_shdr, GL_COMPILE_STATUS) != GL_TRUE) {
throw new IllegalStateException();
}
if (glGetShaderi(frag_shdr, GL_COMPILE_STATUS) != GL_TRUE) {
throw new IllegalStateException();
}
glAttachShader(prog, vert_shdr);
glAttachShader(prog, frag_shdr);
glLinkProgram(prog);
if (glGetProgrami(prog, GL_LINK_STATUS) != GL_TRUE) {
throw new IllegalStateException();
}
uniform_tex = glGetUniformLocation(prog, "Texture");
uniform_proj = glGetUniformLocation(prog, "ProjMtx");
int attrib_pos = glGetAttribLocation(prog, "Position");
int attrib_uv = glGetAttribLocation(prog, "TexCoord");
int attrib_col = glGetAttribLocation(prog, "Color");
{
// buffer setup
vbo = glGenBuffers();
ebo = glGenBuffers();
vao = glGenVertexArrays();
glBindVertexArray(vao);
glBindBuffer(GL_ARRAY_BUFFER, vbo);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ebo);
glEnableVertexAttribArray(attrib_pos);
glEnableVertexAttribArray(attrib_uv);
glEnableVertexAttribArray(attrib_col);
glVertexAttribPointer(attrib_pos, 2, GL_FLOAT, false, 20, 0);
glVertexAttribPointer(attrib_uv, 2, GL_FLOAT, false, 20, 8);
glVertexAttribPointer(attrib_col, 4, GL_UNSIGNED_BYTE, true, 20, 16);
}
{
// null texture setup
int nullTexID = glGenTextures();
null_texture.texture().id(nullTexID);
null_texture.uv().set(0.5f, 0.5f);
glBindTexture(GL_TEXTURE_2D, nullTexID);
try (MemoryStack stack = stackPush()) {
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, 1, 1, 0, GL_RGBA, GL_UNSIGNED_INT_8_8_8_8_REV, stack.ints(0xFFFFFFFF));
}
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
}
glBindTexture(GL_TEXTURE_2D, 0);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
glBindVertexArray(0);
}
private NkContext setupWindow(long win) {
glfwSetScrollCallback(win, (window, xoffset, yoffset) -> {
try (MemoryStack stack = stackPush()) {
NkVec2 scroll = NkVec2.malloc(stack)
.x((float)xoffset)
.y((float)yoffset);
nk_input_scroll(ctx, scroll);
}
});
glfwSetCharCallback(win, (window, codepoint) -> nk_input_unicode(ctx, codepoint));
glfwSetKeyCallback(win, (window, key, scancode, action, mods) -> {
boolean press = action == GLFW_PRESS;
switch (key) {
case GLFW_KEY_ESCAPE:
glfwSetWindowShouldClose(window, true);
break;
case GLFW_KEY_DELETE:
nk_input_key(ctx, NK_KEY_DEL, press);
break;
case GLFW_KEY_ENTER:
nk_input_key(ctx, NK_KEY_ENTER, press);
break;
case GLFW_KEY_TAB:
nk_input_key(ctx, NK_KEY_TAB, press);
break;
case GLFW_KEY_BACKSPACE:
nk_input_key(ctx, NK_KEY_BACKSPACE, press);
break;
case GLFW_KEY_UP:
nk_input_key(ctx, NK_KEY_UP, press);
break;
case GLFW_KEY_DOWN:
nk_input_key(ctx, NK_KEY_DOWN, press);
break;
case GLFW_KEY_HOME:
nk_input_key(ctx, NK_KEY_TEXT_START, press);
nk_input_key(ctx, NK_KEY_SCROLL_START, press);
break;
case GLFW_KEY_END:
nk_input_key(ctx, NK_KEY_TEXT_END, press);
nk_input_key(ctx, NK_KEY_SCROLL_END, press);
break;
case GLFW_KEY_PAGE_DOWN:
nk_input_key(ctx, NK_KEY_SCROLL_DOWN, press);
break;
case GLFW_KEY_PAGE_UP:
nk_input_key(ctx, NK_KEY_SCROLL_UP, press);
break;
case GLFW_KEY_LEFT_SHIFT:
case GLFW_KEY_RIGHT_SHIFT:
nk_input_key(ctx, NK_KEY_SHIFT, press);
break;
case GLFW_KEY_LEFT_CONTROL:
case GLFW_KEY_RIGHT_CONTROL:
if (press) {
nk_input_key(ctx, NK_KEY_COPY, glfwGetKey(window, GLFW_KEY_C) == GLFW_PRESS);
nk_input_key(ctx, NK_KEY_PASTE, glfwGetKey(window, GLFW_KEY_P) == GLFW_PRESS);
nk_input_key(ctx, NK_KEY_CUT, glfwGetKey(window, GLFW_KEY_X) == GLFW_PRESS);
nk_input_key(ctx, NK_KEY_TEXT_UNDO, glfwGetKey(window, GLFW_KEY_Z) == GLFW_PRESS);
nk_input_key(ctx, NK_KEY_TEXT_REDO, glfwGetKey(window, GLFW_KEY_R) == GLFW_PRESS);
nk_input_key(ctx, NK_KEY_TEXT_WORD_LEFT, glfwGetKey(window, GLFW_KEY_LEFT) == GLFW_PRESS);
nk_input_key(ctx, NK_KEY_TEXT_WORD_RIGHT, glfwGetKey(window, GLFW_KEY_RIGHT) == GLFW_PRESS);
nk_input_key(ctx, NK_KEY_TEXT_LINE_START, glfwGetKey(window, GLFW_KEY_B) == GLFW_PRESS);
nk_input_key(ctx, NK_KEY_TEXT_LINE_END, glfwGetKey(window, GLFW_KEY_E) == GLFW_PRESS);
} else {
nk_input_key(ctx, NK_KEY_LEFT, glfwGetKey(window, GLFW_KEY_LEFT) == GLFW_PRESS);
nk_input_key(ctx, NK_KEY_RIGHT, glfwGetKey(window, GLFW_KEY_RIGHT) == GLFW_PRESS);
nk_input_key(ctx, NK_KEY_COPY, false);
nk_input_key(ctx, NK_KEY_PASTE, false);
nk_input_key(ctx, NK_KEY_CUT, false);
nk_input_key(ctx, NK_KEY_SHIFT, false);
}
break;
}
});
glfwSetCursorPosCallback(win, (window, xpos, ypos) -> nk_input_motion(ctx, (int)xpos, (int)ypos));
glfwSetMouseButtonCallback(win, (window, button, action, mods) -> {
try (MemoryStack stack = stackPush()) {
DoubleBuffer cx = stack.mallocDouble(1);
DoubleBuffer cy = stack.mallocDouble(1);
glfwGetCursorPos(window, cx, cy);
int x = (int)cx.get(0);
int y = (int)cy.get(0);
int nkButton;
switch (button) {
case GLFW_MOUSE_BUTTON_RIGHT:
nkButton = NK_BUTTON_RIGHT;
break;
case GLFW_MOUSE_BUTTON_MIDDLE:
nkButton = NK_BUTTON_MIDDLE;
break;
default:
nkButton = NK_BUTTON_LEFT;
}
nk_input_button(ctx, nkButton, x, y, action == GLFW_PRESS);
}
});
nk_init(ctx, ALLOCATOR, null);
ctx.clip()
.copy((handle, text, len) -> {
if (len == 0) {
return;
}
try (MemoryStack stack = stackPush()) {
ByteBuffer str = stack.malloc(len + 1);
memCopy(text, memAddress(str), len);
str.put(len, (byte)0);
glfwSetClipboardString(win, str);
}
})
.paste((handle, edit) -> {
long text = nglfwGetClipboardString(win);
if (text != NULL) {
nnk_textedit_paste(edit, text, nnk_strlen(text));
}
});
setupContext();
return ctx;
}
private void newFrame() {
try (MemoryStack stack = stackPush()) {
IntBuffer w = stack.mallocInt(1);
IntBuffer h = stack.mallocInt(1);
glfwGetWindowSize(win, w, h);
width = w.get(0);
height = h.get(0);
glfwGetFramebufferSize(win, w, h);
display_width = w.get(0);
display_height = h.get(0);
}
nk_input_begin(ctx);
glfwPollEvents();
NkMouse mouse = ctx.input().mouse();
if (mouse.grab()) {
glfwSetInputMode(win, GLFW_CURSOR, GLFW_CURSOR_HIDDEN);
} else if (mouse.grabbed()) {
float prevX = mouse.prev().x();
float prevY = mouse.prev().y();
glfwSetCursorPos(win, prevX, prevY);
mouse.pos().x(prevX);
mouse.pos().y(prevY);
} else if (mouse.ungrab()) {
glfwSetInputMode(win, GLFW_CURSOR, GLFW_CURSOR_NORMAL);
}
nk_input_end(ctx);
}
private void render(int AA, int max_vertex_buffer, int max_element_buffer) {
try (MemoryStack stack = stackPush()) {
// setup global state
glEnable(GL_BLEND);
glBlendEquation(GL_FUNC_ADD);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glDisable(GL_CULL_FACE);
glDisable(GL_DEPTH_TEST);
glEnable(GL_SCISSOR_TEST);
glActiveTexture(GL_TEXTURE0);
// setup program
glUseProgram(prog);
glUniform1i(uniform_tex, 0);
glUniformMatrix4fv(uniform_proj, false, stack.floats(
2.0f / width, 0.0f, 0.0f, 0.0f,
0.0f, -2.0f / height, 0.0f, 0.0f,
0.0f, 0.0f, -1.0f, 0.0f,
-1.0f, 1.0f, 0.0f, 1.0f
));
glViewport(0, 0, display_width, display_height);
}
{
// convert from command queue into draw list and draw to screen
// allocate vertex and element buffer
glBindVertexArray(vao);
glBindBuffer(GL_ARRAY_BUFFER, vbo);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ebo);
glBufferData(GL_ARRAY_BUFFER, max_vertex_buffer, GL_STREAM_DRAW);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, max_element_buffer, GL_STREAM_DRAW);
// load draw vertices & elements directly into vertex + element buffer
ByteBuffer vertices = Objects.requireNonNull(glMapBuffer(GL_ARRAY_BUFFER, GL_WRITE_ONLY, max_vertex_buffer, null));
ByteBuffer elements = Objects.requireNonNull(glMapBuffer(GL_ELEMENT_ARRAY_BUFFER, GL_WRITE_ONLY, max_element_buffer, null));
try (MemoryStack stack = stackPush()) {
// fill convert configuration
NkConvertConfig config = NkConvertConfig.calloc(stack)
.vertex_layout(VERTEX_LAYOUT)
.vertex_size(20)
.vertex_alignment(4)
.tex_null(null_texture)
.circle_segment_count(22)
.curve_segment_count(22)
.arc_segment_count(22)
.global_alpha(1.0f)
.shape_AA(AA)
.line_AA(AA);
// setup buffers to load vertices and elements
NkBuffer vbuf = NkBuffer.malloc(stack);
NkBuffer ebuf = NkBuffer.malloc(stack);
nk_buffer_init_fixed(vbuf, vertices/*, max_vertex_buffer*/);
nk_buffer_init_fixed(ebuf, elements/*, max_element_buffer*/);
nk_convert(ctx, cmds, vbuf, ebuf, config);
}
glUnmapBuffer(GL_ELEMENT_ARRAY_BUFFER);
glUnmapBuffer(GL_ARRAY_BUFFER);
// iterate over and execute each draw command
float fb_scale_x = (float)display_width / (float)width;
float fb_scale_y = (float)display_height / (float)height;
long offset = NULL;
for (NkDrawCommand cmd = nk__draw_begin(ctx, cmds); cmd != null; cmd = nk__draw_next(cmd, cmds, ctx)) {
if (cmd.elem_count() == 0) {
continue;
}
glBindTexture(GL_TEXTURE_2D, cmd.texture().id());
glScissor(
(int)(cmd.clip_rect().x() * fb_scale_x),
(int)((height - (int)(cmd.clip_rect().y() + cmd.clip_rect().h())) * fb_scale_y),
(int)(cmd.clip_rect().w() * fb_scale_x),
(int)(cmd.clip_rect().h() * fb_scale_y)
);
glDrawElements(GL_TRIANGLES, cmd.elem_count(), GL_UNSIGNED_SHORT, offset);
offset += cmd.elem_count() * 2;
}
nk_clear(ctx);
nk_buffer_clear(cmds);
}
// default OpenGL state
glUseProgram(0);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
glBindVertexArray(0);
glDisable(GL_BLEND);
glDisable(GL_SCISSOR_TEST);
}
private void destroy() {
glDetachShader(prog, vert_shdr);
glDetachShader(prog, frag_shdr);
glDeleteShader(vert_shdr);
glDeleteShader(frag_shdr);
glDeleteProgram(prog);
glDeleteTextures(default_font.texture().id());
glDeleteTextures(null_texture.texture().id());
glDeleteBuffers(vbo);
glDeleteBuffers(ebo);
nk_buffer_free(cmds);
GL.setCapabilities(null);
}
private void shutdown() {
Objects.requireNonNull(ctx.clip().copy()).free();
Objects.requireNonNull(ctx.clip().paste()).free();
nk_free(ctx);
destroy();
Objects.requireNonNull(default_font.query()).free();
Objects.requireNonNull(default_font.width()).free();
calc.numberFilter.free();
Objects.requireNonNull(ALLOCATOR.alloc()).free();
Objects.requireNonNull(ALLOCATOR.mfree()).free();
}
} | true |
4d2bee0a915b94e6d613b9515c71220aaf536dac | Java | goncalvesmail/archeionweb | / archeionweb/ArcheionWeb/ArcheionNegocio/src/br/com/archeion/negocio/enderecocaixa/EnderecoCaixaBOImpl.java | UTF-8 | 3,341 | 2.125 | 2 | [] | no_license | package br.com.archeion.negocio.enderecocaixa;
import java.sql.Connection;
import java.util.HashMap;
import java.util.List;
import net.sf.jasperreports.engine.JRException;
import util.Relatorio;
import br.com.archeion.exception.BusinessException;
import br.com.archeion.exception.CadastroDuplicadoException;
import br.com.archeion.modelo.caixa.Caixa;
import br.com.archeion.modelo.enderecocaixa.EnderecoCaixa;
import br.com.archeion.persistencia.caixa.CaixaDAO;
import br.com.archeion.persistencia.enderecocaixa.EnderecoCaixaDAO;
public class EnderecoCaixaBOImpl implements EnderecoCaixaBO {
private EnderecoCaixaDAO enderecoCaixaDAO;
private CaixaDAO caixaDAO;
public EnderecoCaixa persist(EnderecoCaixa enderecoCaixa) throws CadastroDuplicadoException, BusinessException {
validaEnderecoCaixa(enderecoCaixa);
return enderecoCaixaDAO.persist(enderecoCaixa);
}
public List<EnderecoCaixa> findAll() {
return enderecoCaixaDAO.findAll();
}
public void setEnderecoCaixaDAO(EnderecoCaixaDAO enderecoCaixaDAO) {
this.enderecoCaixaDAO = enderecoCaixaDAO;
}
public EnderecoCaixa findById(Long id) {
return enderecoCaixaDAO.findById(id);
}
public EnderecoCaixa merge(EnderecoCaixa enderecoCaixa) throws BusinessException, CadastroDuplicadoException {
validaEnderecoCaixa(enderecoCaixa);
return enderecoCaixaDAO.merge(enderecoCaixa);
}
public void remove(EnderecoCaixa enderecoCaixa) throws BusinessException {
//Verificar Caixa
List<Caixa> caixas = caixaDAO.findByEndereco(enderecoCaixa.getId());
if ( caixas!=null && caixas.size()>0 ) {
throw new BusinessException("enderecoCaixa.erro.caixa");
}
enderecoCaixaDAO.remove(enderecoCaixa);
}
public Relatorio getRelatorio(HashMap<String, Object> parameters,
String localRelatorio) {
Connection conn = enderecoCaixaDAO.getConnection();
try {
Relatorio relatorio = new Relatorio(conn,parameters,localRelatorio);
return relatorio;
} catch (JRException e) {
e.printStackTrace();
}
return null;
}
private void validaEnderecoCaixa(EnderecoCaixa enderecoCaixa) throws CadastroDuplicadoException, BusinessException {
EnderecoCaixa e = enderecoCaixaDAO.findByName(enderecoCaixa.getVao());
if ( enderecoCaixa.getVaoInicial()==0 ) {
throw new BusinessException("enderecoCaixa.err.inicial.zero");
}
else if( enderecoCaixa.getVaoInicial()>enderecoCaixa.getVaoFinal() ) {
throw new BusinessException("enderecoCaixa.err.inicial.menor");
}
else if ( enderecoCaixaDAO.findIntervalo(enderecoCaixa) !=null ) {
if ( enderecoCaixa.getId()==null || enderecoCaixa.getId()==0 ) {
throw new BusinessException("enderecoCaixa.err.intervalo");
}
else if ( enderecoCaixaDAO.findIntervalo(enderecoCaixa).getId().longValue() !=
enderecoCaixa.getId().longValue() ) {
throw new BusinessException("enderecoCaixa.err.intervalo");
}
}
else if(e != null) {
if ( enderecoCaixa.equals(e)) {
return;
}
throw new CadastroDuplicadoException();
}
}
public CaixaDAO getCaixaDAO() {
return caixaDAO;
}
public void setCaixaDAO(CaixaDAO caixaDAO) {
this.caixaDAO = caixaDAO;
}
public EnderecoCaixaDAO getEnderecoCaixaDAO() {
return enderecoCaixaDAO;
}
}
| true |
08609569950fbe94aab12d72d016aa6d8c81dbd6 | Java | nojiro15/Empleo-Digital-Fundacion-Telefonica | /JAVA/Inmobiliaria/src/Inmobiliaria/InmuebleEnAlquiler.java | ISO-8859-1 | 1,298 | 3.109375 | 3 | [] | no_license | package Inmobiliaria;
public class InmuebleEnAlquiler extends Inmueble{
private double precioAlquiler;
/**
* Constructores
*/
public InmuebleEnAlquiler(){
}
public InmuebleEnAlquiler(double superficie, boolean edificable, String direccion,String propietario, double precioAlquiler){
super(superficie,edificable,direccion,propietario);
this.precioAlquiler=precioAlquiler;
}
public InmuebleEnAlquiler(InmuebleEnAlquiler inmAlquiler){
super(inmAlquiler);
precioAlquiler = inmAlquiler.precioAlquiler;
}
/**
* Getter & Setter
*/
public void setPrecioAlquiler(double precioAlquiler) {
this.precioAlquiler = precioAlquiler;
}
public double getPrecio(){
return precioAlquiler;
}
/**
* Puesto que hay dos mtodos abstractos, es necesario definir los mtodos
* de la clase padre.
*/
public double getTipoIva(){
return 0;
}
public double getPrecioAlquiler() {
return precioAlquiler;
}
@Override
public String toString(){
return "\n\nSuperficie (m^2): " + superficie + "\nEdificable: "+ ((edificable==true)?"Si" : "No")+ "\nDireccin: " + direccion+ "\nPropietario del Inmueble: " + propietario + "\nPrecio de Alquiler: " + precioAlquiler;
}
@Override
public void setPrecio(double precio){
precioAlquiler = precio;
}
}
| true |
954f0d8a531b4469176a1ba571e49e0256abd4e5 | Java | abhilashgowda/chargeback-batch | /src/main/java/com/chargeback/batch/processor/PollingJobReader.java | UTF-8 | 1,576 | 2.4375 | 2 | [] | no_license | package com.chargeback.batch.processor;
import java.util.List;
import org.springframework.batch.item.ItemReader;
import org.springframework.batch.item.NonTransientResourceException;
import org.springframework.batch.item.ParseException;
import org.springframework.batch.item.UnexpectedInputException;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;
import com.chargeback.batch.vo.ChargeBackUsage;
public class PollingJobReader implements ItemReader<ChargeBackUsage> {
private List<ChargeBackUsage> chargeBackUsageList;
private int nextUsageIndex;
public PollingJobReader() {
super();
final String METRICS_URL = "http://chargeback-api.cglean.com/metrics/getInstanceMetrics";
RestTemplate restTemplate = new RestTemplate();
final ResponseEntity<List<ChargeBackUsage>> response = restTemplate.exchange(METRICS_URL, HttpMethod.GET, HttpEntity.EMPTY,
new ParameterizedTypeReference<List<ChargeBackUsage>>() {
});
chargeBackUsageList= response.getBody();
nextUsageIndex=0;
}
@Override
public ChargeBackUsage read()
throws Exception, UnexpectedInputException, ParseException, NonTransientResourceException {
ChargeBackUsage chargeBackUsage = null;
if (nextUsageIndex < chargeBackUsageList.size()) {
chargeBackUsage = chargeBackUsageList.get(nextUsageIndex);
nextUsageIndex++;
}
return chargeBackUsage;
}
}
| true |
f984b99544882882e5eb93a2f76fcac4fd450bda | Java | geekjuruo/THUSIGS_OOP | /EXP3_4/src/decorator.java | UTF-8 | 392 | 2.6875 | 3 | [] | no_license | // 装饰类
public class decorator {
public void chooseBrix(milkTea milktea, String brix) {
milktea.brix = brix;
}
public void chooseIce(milkTea milktea, String ice) {
milktea.ice = ice;
}
public void chooseMaterial(milkTea milktea, String material) {
milktea.material = material;
}
public void chooseScale(milkTea milktea, String scale) {
milktea.scale = scale;
}
}
| true |
ce3ba3aef0cd9f9d0c040fea35cb9ad04a2888ed | Java | abelidze/planner-server | /app/src/main/java/com/skillmasters/server/http/response/EventPatternResponse.java | UTF-8 | 269 | 1.84375 | 2 | [
"MIT"
] | permissive | package com.skillmasters.server.http.response;
import com.skillmasters.server.model.EventPattern;
public class EventPatternResponse extends Response<EventPattern, EventPatternResponse>
{
public EventPatternResponse()
{
super(EventPatternResponse.class);
}
} | true |
31d9e404704aca31c64f88fcd5d63b89436550a5 | Java | zzking1989/zongxiang | /src/main/java/com/zx/utils/WaterMarkGenerate.java | UTF-8 | 4,057 | 2.78125 | 3 | [
"MIT"
] | permissive | //package com.zx.utils;
//
//import com.sun.image.codec.jpeg.JPEGCodec;
//import com.sun.image.codec.jpeg.JPEGImageEncoder;
//
//import javax.imageio.ImageIO;
//import java.awt.*;
//import java.awt.image.BufferedImage;
//import java.io.File;
//import java.io.FileOutputStream;
//
///**
// * 添加水印类
// */
//public class WaterMarkGenerate {
// private static final String FONT_FAMILY="微软雅黑";//字体
// private static final int FONT_STYLE=Font.BOLD;//字体加粗
// private static final int FONT_SIZE=24;//字体大小
// private static final float ALPHA=0.7F;//水印透明度
//
// private static final int LOGO_WIDTH=200;//图片水印大小
//
// //添加文字水印
// /*tarPath:图片保存路径
// *contents:文字水印内容* */
// public static void generateWithTextMark(File srcFile,
// String tarPath,String contents) throws Exception{
// Image srcImage=ImageIO.read(srcFile);
// int width=srcImage.getWidth(null);
// int height=srcImage.getHeight(null);
// BufferedImage tarBuffImage=new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
// Graphics2D g=tarBuffImage.createGraphics();
// g.drawImage(srcImage, 0, 0, width,height,null);
//
// //计算
// int strWidth=FONT_SIZE*getTextLength(contents);
// int strHeight=FONT_SIZE;
//
// //水印位置
//// int x=width-strWidth;
//// int y=height-strHeight;
//
// int x=0,y=0;
//
// //设置字体和水印透明度
// g.setFont(new Font(FONT_FAMILY,FONT_STYLE,FONT_SIZE));
// g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP,ALPHA));
//// g.drawString(contents, x, y);
// //旋转图片
// g.rotate(Math.toRadians(-30),width/2,height/2);
// while(x < width*1.5){
// y = -height/2;
// while(y < height*1.5){
// g.drawString(contents,x,y);
// y += strHeight + 50;
// }
// x += strWidth + 50; //水印之间的间隔设为50
// }
// g.dispose();
//
// JPEGImageEncoder en = JPEGCodec.createJPEGEncoder(new FileOutputStream(tarPath));
// en.encode(tarBuffImage);
// }
//
// //添加图片水印
// /*
// * tarPath:图片保存路径
// * logoPath:logo文件路径
// * */
// public static void generateWithImageMark(File srcFile,
// String tarPath,String logoPath) throws Exception{
// Image srcImage=ImageIO.read(srcFile);
// int width=srcImage.getWidth(null);
// int height=srcImage.getHeight(null);
// //创建一个不带透明色的BufferedImage对象
// BufferedImage tarBuffImage=new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
// Graphics2D g=tarBuffImage.createGraphics();
// g.drawImage(srcImage, 0, 0, width,height,null);
//
// Image logoImage= ImageIO.read(new File(logoPath));
// int logoWidth=LOGO_WIDTH;
// int logoHeight=(LOGO_WIDTH*logoImage.getHeight(null))/logoImage.getWidth(null);
//
// int x=width-logoWidth;
// int y=height-logoHeight;
//
// g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP,ALPHA));
// g.drawImage(logoImage, x, y, logoWidth, logoHeight, null);
// g.dispose();
//
// JPEGImageEncoder en = JPEGCodec.createJPEGEncoder(new FileOutputStream(tarPath));
// en.encode(tarBuffImage);
// }
//
// //文本长度的处理:文字水印的中英文字符的宽度转换
// public static int getTextLength(String text){
// int length = text.length();
// for(int i=0;i<text.length();i++){
// String s = String.valueOf(text.charAt(i));
// if(s.getBytes().length>1){ //中文字符
// length++;
// }
// }
// length = length%2 == 0?length/2:length/2+1; //中文和英文字符的转换
// return length;
// }
//} | true |
4f381aa32a76b7582ea0d4b74c342fd63e7bf605 | Java | Georgi768/Data-processing | /Api/src/main/java/com/example/Api/WorldHappines/WorldHappinessController.java | UTF-8 | 3,258 | 2.15625 | 2 | [] | no_license | package com.example.Api.WorldHappines;
import com.example.Api.Covid.Covid19;
import com.example.Api.Exception.AlreadyExistException;
import com.example.Api.Exception.DoesNotExistException;
import com.example.Api.XmlJsonValidator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import com.networknt.schema.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import java.io.InputStream;
import java.util.List;
import java.util.Optional;
import java.util.Set;
@RestController
@RequestMapping(path = "api/happiness")
public class WorldHappinessController extends XmlJsonValidator {
private final WorldHappinessService worldHappinessService;
@Autowired
public WorldHappinessController(WorldHappinessService worldHappinessService) {
this.worldHappinessService = worldHappinessService;
}
@GetMapping(value = "/json", produces = MediaType.APPLICATION_JSON_VALUE)
public List<Worldhappiness> getAllCountiesJson() {
return this.worldHappinessService.getCountries();
}
@GetMapping(value = "/xml", produces = MediaType.APPLICATION_XML_VALUE)
public List<Worldhappiness> getAllCountiesXML() {
return this.worldHappinessService.getCountries();
}
@GetMapping(path = "json/{id}", produces = MediaType.APPLICATION_JSON_VALUE)
public Optional<Worldhappiness> getSpecificCountryJson(@PathVariable("id") long id) {
return this.worldHappinessService.getCountryById(id);
}
@GetMapping(path = "xml/{id}", produces = MediaType.APPLICATION_XML_VALUE)
public Optional<Worldhappiness> getSpecificCountryXML(@PathVariable("id") long id) {
return this.worldHappinessService.getCountryById(id);
}
@GetMapping(path = "/xml/name=/{name}" , produces = MediaType.APPLICATION_XML_VALUE)
public List<Worldhappiness> getCountryByNameInXml(@PathVariable("name") String countryName)
{
return this.worldHappinessService.getHappinessCountry(countryName);
}
@GetMapping(path = "/json/name=/{name}" , produces = MediaType.APPLICATION_JSON_VALUE)
public List<Worldhappiness> getCountryByNameInJSON(@PathVariable("name") String countryName)
{
return this.worldHappinessService.getHappinessCountry(countryName);
}
@PostMapping
public void addNewCountry(@RequestBody Worldhappiness worldhappiness) throws AlreadyExistException {
if(this.validateJson(this,worldhappiness,"Schemas/HappinessJSONSchema.JSON"))
{
this.worldHappinessService.addCountry(worldhappiness);
}
}
@DeleteMapping(path = "delete/{id}")
public void deleteCountry(@PathVariable("id") long id) throws DoesNotExistException {
this.worldHappinessService.deleteSpecificCountry(id);
}
@PutMapping(path = "updates/{id}")
public void updateCountryDetails(@PathVariable("id") long id, String country, String region) throws DoesNotExistException {
this.worldHappinessService.updateCountry(id, country, region);
}
}
| true |
36dbb5abf6d87ef5f70eadefe6d102f59c077fc6 | Java | Nishantkumar200/MiwokApp | /app/src/main/java/com/example/miwokapp/ColorsActivity.java | UTF-8 | 1,970 | 2.046875 | 2 | [] | no_license | package com.example.miwokapp;
import androidx.appcompat.app.AppCompatActivity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.List;
public class ColorsActivity extends AppCompatActivity {
List<Color> color = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_colors);
color.add(new Color("red", "weṭeṭṭi", R.drawable.red, R.raw.color_red));
color.add(new Color("green", "chokokki", R.drawable.green, R.raw.color_green));
color.add(new Color("brown", "ṭakaakki", R.drawable.brown, R.raw.color_brown));
color.add(new Color("gray", "ṭopoppi", R.drawable.gray, R.raw.color_gray));
color.add(new Color("black", "kululli", R.drawable.black, R.raw.color_black));
color.add(new Color("white", "kelelli", R.drawable.white, R.raw.color_white));
color.add(new Color("dusty yellow", "ṭopiisә", R.drawable.dusty_yellow, R.raw.color_dusty_yellow));
color.add(new Color("mustard yellow", "chiwiiṭә", R.drawable.mustard_yellow, R.raw.color_mustard_yellow));
ColorAdapter arrayAdapter = new ColorAdapter(this, 0, color);
final ListView colorlist = findViewById(R.id.colorsList);
colorlist.setAdapter(arrayAdapter);
colorlist.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Color colorpostion = color.get(position);
MediaPlayer mediaPlayer = MediaPlayer.create(ColorsActivity.this,colorpostion.getmColoraudioId());
mediaPlayer.start();
}
});
}
} | true |
de0429d2879d6f9bd16007d14ccae070a0bc4c29 | Java | rqshen/FuliDemo | /bcb/src/main/java/com/bcb/module/myinfo/myfinancial/myfinancialstate/MyFinancialStateFragment.java | UTF-8 | 6,028 | 1.960938 | 2 | [] | no_license | package com.bcb.module.myinfo.myfinancial.myfinancialstate;
import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.bcb.R;
import com.bcb.base.old.BaseFragment1;
import com.bcb.module.myinfo.myfinancial.myfinancialstate.adapter.MyFinancialStateAdapter;
import com.bcb.module.myinfo.myfinancial.myfinancialstate.myfinanciallist.MyFinancialListFragment;
import java.util.ArrayList;
/**
* 投资理财的状态,
* 持有中,已结束,ViewPager
*/
public class MyFinancialStateFragment extends BaseFragment1 implements View.OnClickListener {
private Context ctx;
public TextView ztbj;
public TextView yjsy;
private ViewPager vp;
private ArrayList<Fragment> fragmentsList;
private String Status;// 【 0稳赢,打包】【1涨薪宝,三标】
private static String EXTRA_STATUS = "status";
//******************************************************************************************
/**
* 构造时把传入的参数带进来,
*/
public static MyFinancialStateFragment newInstance(String Status) {
Bundle bundle = new Bundle();
bundle.putString(EXTRA_STATUS, Status);
MyFinancialStateFragment fragment = new MyFinancialStateFragment();
fragment.setArguments(bundle);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle bundle = getArguments();
if (bundle != null) {
Status = bundle.getString(EXTRA_STATUS);
}
}
//******************************************************************************************
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_tzjl_1, container, false);
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
this.ctx = view.getContext();
ztbj = (TextView) view.findViewById(R.id.ztbj);
yjsy = (TextView) view.findViewById(R.id.yjsy);
initUnderLine(view);
InitViewPager(view);
}
private void InitViewPager(View view) {
vp = (ViewPager) view.findViewById(R.id.vp);
fragmentsList = new ArrayList<Fragment>();
fragmentsList.add(MyFinancialListFragment.newInstance(Status, 1));
fragmentsList.add(MyFinancialListFragment.newInstance(Status, 2));
vp.setAdapter(new MyFinancialStateAdapter(getChildFragmentManager(), fragmentsList));
vp.setCurrentItem(0);
vp.setOffscreenPageLimit(2);
vp.setOnPageChangeListener(new MyOnPageChangeListener());
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.tv_unused:
vp.setCurrentItem(0);
break;
case R.id.tv_used:
vp.setCurrentItem(1);
break;
default:
break;
}
}
//********************************************************下面的一条红线**********************************
private TextView unusedTextView, usedTextView;
private int currIndex = 0;
private int bottomLineWidth;
private int offset = 0;
private int position_one;
private ImageView ivBottomLine;
private void initUnderLine(View view) {
unusedTextView = (TextView) view.findViewById(R.id.tv_unused);
usedTextView = (TextView) view.findViewById(R.id.tv_used);
unusedTextView.setOnClickListener(this);
usedTextView.setOnClickListener(this);
ivBottomLine = (ImageView) view.findViewById(R.id.red);
bottomLineWidth = ivBottomLine.getLayoutParams().width;
DisplayMetrics dmDisplayMetrics = new DisplayMetrics();
getActivity().getWindowManager().getDefaultDisplay().getMetrics(dmDisplayMetrics);
int screenW = dmDisplayMetrics.widthPixels;
offset = (int) ((screenW / 2.0 - bottomLineWidth) / 2);
position_one = (int) (screenW / 2.0);
LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) ivBottomLine.getLayoutParams();
params.leftMargin = offset;
params.rightMargin = 0;
ivBottomLine.setLayoutParams(params);
}
public class MyOnPageChangeListener implements ViewPager.OnPageChangeListener {
@Override
public void onPageScrollStateChanged(int arg0) {
}
@Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
@Override
public void onPageSelected(int arg0) {
//根据当前位置和将要移动到的位置创建动画
Animation animation = new TranslateAnimation(currIndex * position_one, arg0 * position_one, 0, 0);
//设置字体颜色
switch (arg0) {
case 0:
setTextColor();
unusedTextView.setTextColor(Color.RED);
break;
case 1:
setTextColor();
usedTextView.setTextColor(Color.RED);
break;
}
//将当前位置设置为目标位置
currIndex = arg0;
animation.setFillAfter(true);
animation.setDuration(100);
ivBottomLine.startAnimation(animation);
}
//设置所有的字体颜色为灰色
private void setTextColor() {
unusedTextView.setTextColor(Color.GRAY);
usedTextView.setTextColor(Color.GRAY);
}
}
} | true |
cb6f40f9c2b4e865938d5ae60d0de3d7c751417c | Java | patrikkj/blackbird | /src/main/models/Period.java | UTF-8 | 1,934 | 3.328125 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | permissive | package main.models;
/**
* Datamodel of an assistant-period.
* @author Sebastian
*/
public class Period {
private int periodID;
private String courseCode;
private String timeStamp; // timeStamp is on format 'yyyy-mm-dd hh:mm:ss' f.eks '2019-02-15 11:44:19'
private String professorUsername;
private String assistantUsername;
private String studentUsername;
public Period(int periodID, String courseCode, String timeStamp, String professorUsername, String assistantUsername, String studentUsername) {
this.periodID = periodID;
this.courseCode = courseCode;
this.timeStamp = timeStamp;
this.professorUsername = professorUsername;
this.assistantUsername = assistantUsername;
this.studentUsername = studentUsername;
}
public int getPeriodID() {
return periodID;
}
public String getCourseCode() {
return courseCode;
}
public String getTimeStamp() {
return timeStamp;
}
public String getProfessorUsername() {
return professorUsername;
}
public String getAssistantUsername() {
return assistantUsername;
}
public String getStudentUsername() {
return studentUsername;
}
/**
* Gives the status/type of a period.
* @return {@link PeriodType}-value:
* <br> {@code CREATED}, {@code BOOKABLE} or {@code BOOKED}.
*/
public PeriodType getPeriodType() {
if (( assistantUsername == null ) || ( assistantUsername.equals("") )) {
return PeriodType.CREATED;
} else if (( studentUsername == null ) || ( studentUsername.equals("") )) {
return PeriodType.BOOKABLE;
} else {
return PeriodType.BOOKED;
}
}
/**
* Simply checks if a period is of a given {@link PeriodType}.
* @param periodType
* @return boolean.
*/
public boolean isOfPeriodType(PeriodType periodType) {
return periodType == getPeriodType();
}
public enum PeriodType{
CREATED, BOOKABLE, BOOKED;
}
}
| true |
be9c994a247425d5b9cb579015fc6f19e256c54b | Java | wexpect/leetcode | /82_Remove_Duplicates_from_Sorted_List_II.java | UTF-8 | 1,503 | 3.65625 | 4 | [] | no_license | Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.
For example,
Given 1->2->3->3->4->4->5, return 1->2->5.
Given 1->1->1->2->3, return 2->3.
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode deleteDuplicates(ListNode head) {
if( head == null )
return head;
ListNode node = head;
HashMap<Integer, Integer> hashMap = new HashMap<Integer, Integer>();
while( node != null){
int val = node.val;
if( hashMap.containsKey( val) ) { // HashMap: containsKey()
hashMap.put( val, hashMap.get(val) + 1 ); // HashMap: put()
}
else{
hashMap.put( val, 1);
}
node = node.next;
}
node = head;
while( node.next != null ){
int val = node.next.val;
if( hashMap.get(val) >= 2 ){
node.next = node.next.next;
}
else{
node = node.next;
}
}
if( hashMap.get( head.val ) >= 2 )
return head.next;
else
return head;
}
}
| true |
933650e1d3d140d234c82190bf6f516829f7a688 | Java | mohamedT199/cinema | /app/src/main/java/com/example/posts/model/DataRealTime.java | UTF-8 | 994 | 2.296875 | 2 | [] | no_license | package com.example.posts.model;
public class DataRealTime {
String email , password , nickName , imageResource ;
public DataRealTime(String email, String password, String nickName, String imageResource) {
this.email = email;
this.password = password;
this.nickName = nickName;
this.imageResource = imageResource;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getNickName() {
return nickName;
}
public void setNickName(String nickName) {
this.nickName = nickName;
}
public String getImageResource() {
return imageResource;
}
public void setImageResource(String imageResource) {
this.imageResource = imageResource;
}
}
| true |
aeb55f6e4c881cfcc7e0e4cb08cdde470e884489 | Java | yolen/zhuantouren | /Android/BrickMan/app/src/main/java/com/brickman/app/module/main/MainActivity.java | UTF-8 | 11,247 | 1.679688 | 2 | [] | no_license | package com.brickman.app.module.main;
import android.Manifest;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.Toolbar;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TabHost;
import android.widget.TabWidget;
import android.widget.TextView;
import com.brickman.app.MApplication;
import com.brickman.app.R;
import com.brickman.app.common.base.Api;
import com.brickman.app.common.base.BaseActivity;
import com.brickman.app.common.base.PermissionsChecker;
import com.brickman.app.common.lbs.LocationManager;
import com.brickman.app.contract.MainContract;
import com.brickman.app.model.Bean.BannerBean;
import com.brickman.app.model.Bean.BrickBean;
import com.brickman.app.model.MainModel;
import com.brickman.app.module.brick.TopActivity;
import com.brickman.app.module.mine.MessageActivity;
import com.brickman.app.module.mine.PublishActivity;
import com.brickman.app.module.update.UpdateChecker;
import com.brickman.app.module.widget.view.ToastManager;
import com.brickman.app.presenter.MainPresenter;
import java.util.ArrayList;
import java.util.List;
import butterknife.BindView;
import butterknife.OnClick;
/**
* Created by mayu on 16/7/14,上午10:00.
*/
public class MainActivity extends BaseActivity<MainPresenter, MainModel> implements MainContract.View {
@BindView(R.id.title)
TextView title;
@BindView(R.id.toolbar)
Toolbar toolbar;
@BindView(android.R.id.tabcontent)
FrameLayout tabcontent;
@BindView(android.R.id.tabs)
TabWidget tabs;
@BindView(R.id.realtabcontent)
FrameLayout realtabcontent;
@BindView(android.R.id.tabhost)
TabHost tabhost;
@BindView(R.id.publish)
RelativeLayout publish;
@BindView(R.id.top)
RelativeLayout top;
@BindView(R.id.message)
ImageView messageIcon;
private LayoutInflater mInflator;
public TabHost mTabHost;
public TabManager mTabManager;
private String[] tabNames;
private Class[] clzzs = new Class[]{HomeFragment.class, MainFragment.class, UserFragment.class};
private int[] tabImgs = new int[]{R.drawable.tab_home, R.drawable.tab_brick, R.drawable.tab_user};
private static final int REQUEST_CODE = 0; // 请求码
private PermissionsChecker mPermissionsChecker; // 权限检测器
// 所需的全部权限
static final String[] PERMISSIONS = new String[]{
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.CAMERA,
Manifest.permission.ACCESS_COARSE_LOCATION,
Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.READ_PHONE_STATE
};
private boolean hasMessage=true;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
tabNames = getResources().getStringArray(R.array.tabNames);
toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.setTitle("");
setSupportActionBar(toolbar);
mPermissionsChecker = new PermissionsChecker(this);
title.setText(tabNames[0]);
mInflator = LayoutInflater.from(this);
mTabHost = (TabHost) findViewById(android.R.id.tabhost);
mTabHost.setup();
mTabManager = new TabManager(this, mTabHost, R.id.realtabcontent);
for (int i = 0; i < 3; i++) {
mTabManager.addTab(mTabHost.newTabSpec(tabNames[i]).setIndicator(getIndicatorView(tabNames[i], tabImgs[i])), clzzs[i], null);
}
title.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (mTabManager.getCurrentTab().equals(mTabManager.getTab(tabNames[0]))) {
// TODO ...
reload();
}
}
});
// 缺少权限时, 进入权限配置页面
if (mPermissionsChecker.lacksPermissions(PERMISSIONS)) {
startPermissionsActivity();
} else {
new LocationManager(this, new LocationManager.OnResultListener() {
@Override
public void getAddress(String city, String address) {
MApplication.setLocation(city, address);
}
}).startLocation();
}
// 自动检查更新
UpdateChecker.checkForDialog(this, Api.APP_UPDATE_SERVER_URL, false);
//获取消息
if (MApplication.mAppContext.mUser!=null) {
if (MApplication.mAppContext.mUser.token!=null)
mPresenter.loadMessageRemind(MApplication.mAppContext.mUser.token);
}
}
@Override
protected void onRestart() {
super.onRestart();
if (MApplication.mAppContext.mUser!=null) {
if (MApplication.mAppContext.mUser.token!=null)
mPresenter.loadMessageRemind(MApplication.mAppContext.mUser.token);
}
}
@Override
protected void onResume() {
super.onResume();
// 缺少权限时, 进入权限配置页面
if (mPermissionsChecker.lacksPermissions(PERMISSIONS)) {
startPermissionsActivity();
}
}
private void startPermissionsActivity() {
PermissionsActivity.startActivityForResult(this, REQUEST_CODE, PERMISSIONS);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// 拒绝时, 关闭页面, 缺少主要权限, 无法运行
if (requestCode == REQUEST_CODE) {
if(resultCode == PermissionsActivity.PERMISSIONS_DENIED){
finish();
} else if(resultCode == PermissionsActivity.PERMISSIONS_GRANTED){
new LocationManager(this, new LocationManager.OnResultListener() {
@Override
public void getAddress(String city, String address) {
MApplication.setLocation(city, address);
}
}).startLocation();
}
} else if (resultCode == RESULT_OK && requestCode == 1001) {
// 详情返回、注释不刷新
// ArrayList<Fragment> list = (ArrayList<Fragment>) ((HomeFragment) mTabManager.getTab(tabNames[0]).getFragment()).fragments;
// for (Fragment fg : list) {
// ((BrickListFragment) fg).reload();
// }
} else if (resultCode == RESULT_OK && requestCode == 1002) {
// 发布返回刷新
mTabHost.setCurrentTab(0);
ArrayList<Fragment> list = (ArrayList<Fragment>) ((HomeFragment) mTabManager.getTab(tabNames[0]).getFragment()).fragments;
((BrickListFragment)list.get(0)).reload();
}else if (requestCode==RESULT_OK&&requestCode==1003){
// 消息返回刷新
// messageIcon.setImageResource(R.mipmap.bm_nonemessage);
hasMessage=false;
messageIcon.setVisibility(View.GONE);
}
}
@Override
public void showMsg(String msg) {
showToast(msg);
}
@Override
public void loadMRSuccess(int messageSum) {
if (messageSum>=1){
messageIcon.setVisibility(View.VISIBLE);
messageIcon.setImageResource(R.mipmap.bm_message);
hasMessage=true;
}else {
hasMessage=false;
messageIcon.setVisibility(View.GONE);
}
}
@Override
public void loadSuccess(int fragmentId, List<BrickBean> brickList, int pageSize, boolean hasMore) {
((BrickListFragment) ((HomeFragment) mTabManager
.getTab(tabNames[0]).getFragment())
.mAdapter.getItem(fragmentId))
.loadSuccess(brickList, pageSize, hasMore);
}
@Override
public void loadFailed(int fragmentId) {
if (fragmentId == -1) {
AdFragment adFragment =(AdFragment) mTabManager.getTab(tabNames[1]).getFragment();
if(adFragment != null)
adFragment.loadFailed();
} else {
((BrickListFragment) ((HomeFragment) mTabManager
.getTab(tabNames[0]).getFragment())
.mAdapter.getItem(fragmentId))
.loadFailed();
}
}
@Override
public void loadADSuccess(int type, List<BannerBean> dataList, boolean hasMore) {
if (type == 2) {
((HomeFragment) mTabManager
.getTab(tabNames[0]).getFragment())
.loadBanner(dataList);
} else if (type == 3) {
((AdFragment) mTabManager.getTab(tabNames[1]).getFragment()).loadBanner(dataList);
} else if (type == 4) {
((AdFragment) mTabManager.getTab(tabNames[1]).getFragment()).loadList(dataList, hasMore);
}
}
// 设置TabBar、TabItem及样式
private View getIndicatorView(String t, int res) {
View v;
if (!t.equals(tabNames[1])) {
v = mInflator.inflate(R.layout.tab_view, null);
ImageView tabIcon = (ImageView) v.findViewById(R.id.icon);
TextView title = ((TextView) v.findViewById(R.id.title));
tabIcon.setImageResource(res);
title.setText(t);
} else {
v = mInflator.inflate(R.layout.tab_view2, null);
ImageView tabIcon = (ImageView) v.findViewById(R.id.icon);
tabIcon.setImageResource(res);
}
return v;
}
// <<<<<<<<<------------------->>>>>>>>>
@Override
protected int getLayoutId() {
return R.layout.activity_main;
}
private long exitTime = 0;
//重写 onKeyDown方法
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
//两秒之内按返回键就会退出
if ((System.currentTimeMillis() - exitTime) > 2000) {
ToastManager.showWithTxt(this, "再按一次退出程序");
exitTime = System.currentTimeMillis();
} else {
finish();
System.exit(0);
}
return true;
}
return super.onKeyDown(keyCode, event);
}
@OnClick({R.id.top, R.id.publish})
public void onClick(View view) {
switch (view.getId()) {
case R.id.top:
startActivityWithAnim(new Intent(this, TopActivity.class));
break;
case R.id.publish:
if (MApplication.mAppContext.mUser != null) {
if (hasMessage) {
startActivityForResultWithAnim(new Intent(this, MessageActivity.class),1003);
}
// startActivityForResultWithAnim();
} else {
startActivityWithAnim(new Intent(this, LoginActivity.class));
}
break;
}
}
}
| true |
c972df080b1dc99658cedcd8e19bcb5fcb3ef122 | Java | dbeaver/cloudbeaver | /server/bundles/io.cloudbeaver.server/src/io/cloudbeaver/service/sql/WebSQLQueryResultColumn.java | UTF-8 | 3,420 | 1.53125 | 2 | [
"Apache-2.0"
] | permissive | /*
* DBeaver - Universal Database Manager
* Copyright (C) 2010-2023 DBeaver Corp and others
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.cloudbeaver.service.sql;
import org.jkiss.dbeaver.Log;
import org.jkiss.dbeaver.model.DBPDataKind;
import org.jkiss.dbeaver.model.DBPEvaluationContext;
import org.jkiss.dbeaver.model.DBValueFormatting;
import org.jkiss.dbeaver.model.data.DBDAttributeBinding;
import org.jkiss.dbeaver.model.exec.DBCLogicalOperator;
import org.jkiss.dbeaver.model.exec.DBExecUtils;
import org.jkiss.dbeaver.model.meta.Property;
/**
* Web SQL query resultset.
*/
public class WebSQLQueryResultColumn {
private static final Log log = Log.getLog(WebSQLQueryResultColumn.class);
private final DBDAttributeBinding attrMeta;
public WebSQLQueryResultColumn(DBDAttributeBinding attrMeta) {
this.attrMeta = attrMeta;
}
DBDAttributeBinding getAttribute() {
return attrMeta;
}
@Property
public Integer getPosition() {
return attrMeta.getOrdinalPosition();
}
@Property
public String getName() {
return attrMeta.getFullyQualifiedName(DBPEvaluationContext.UI);
}
@Property
public String getLabel() {
if (attrMeta.getParentObject() != null && attrMeta.getParentObject().getDataKind() != DBPDataKind.DOCUMENT) {
return attrMeta.getParentObject().getFullyQualifiedName(DBPEvaluationContext.UI) + "." + attrMeta.getLabel();
}
return attrMeta.getLabel();
}
@Property
public String getIcon() {
return DBValueFormatting.getObjectImage(attrMeta).getLocation();
}
@Property
public String getEntityName() {
return attrMeta.getMetaAttribute().getEntityName();
}
@Property
public String getDataKind() {
return attrMeta.getDataKind().name();
}
@Property
public String getTypeName() {
return attrMeta.getTypeName();
}
@Property
public String getFullTypeName() {
return attrMeta.getFullTypeName();
}
@Property
public long getMaxLength() {
return attrMeta.getMaxLength();
}
@Property
public Integer getScale() {
return attrMeta.getScale();
}
@Property
public Integer getPrecision() {
return attrMeta.getPrecision();
}
@Property
public boolean isRequired() {
return attrMeta.isRequired();
}
@Property
public boolean isReadOnly() {
return DBExecUtils.isAttributeReadOnly(attrMeta);
}
@Property
public String getReadOnlyStatus() {
return DBExecUtils.getAttributeReadOnlyStatus(attrMeta);
}
@Property
public DBCLogicalOperator[] getSupportedOperations() {
return attrMeta.getValueHandler().getSupportedOperators(attrMeta);
}
@Override
public String toString() {
return attrMeta.getName();
}
}
| true |
a3a6e743411327342e5eb45aca3c9ac20c5e61b8 | Java | thecuriousvector/Big-Data-ML-Systems | /Assignment 1a/Hadoop/2b/Average/src/AverageMapper.java | UTF-8 | 1,319 | 2.328125 | 2 | [] | no_license | import java.io.IOException;
import java.util.StringTokenizer;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.DoubleWritable;
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 org.apache.hadoop.examples.SecondarySort.IntPair;
public class AverageMapper
extends Mapper<Object, Text, IntWritable, IntPair>{
private static final IntWritable one = new IntWritable(1);
//private int counter = 0;
private IntPair countSum = new IntPair();
public void map(Object key, Text value, Context context
) throws IOException, InterruptedException {
StringTokenizer itr = new StringTokenizer(value.toString());
int sum = 0;
int counter = 0;
while (itr.hasMoreTokens()) {
int temp = Integer.parseInt(itr.nextToken());
sum += temp;
counter += 1;
}
//CountSumPair countSum = new CountSumPair(counter, sum);
//IntPair countSum = new IntPair();
countSum.set(counter,sum);
context.write(one, countSum);
}
}
| true |
a6af62290d14d973a3cf3a90035b251c59e9a66d | Java | AustinGrey/crapo-CountBook | /app/src/main/java/com/example/corey/crapo_countbook/CounterStore.java | UTF-8 | 3,474 | 2.921875 | 3 | [] | no_license | /*
* CounterStore
*
* V 1.0
*
* September 27 2017
*
* Copyright (c) 2017. Austin Crapo. Permission is granted to the University of Alberta to
* compile, run, inspect or edit the code as required for grading purposes.
*/
package com.example.corey.crapo_countbook;
import android.content.Context;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.lang.reflect.Type;
import java.util.ArrayList;
/**
* CounterStore
*
* Manages a file which is meant to store an array of counters in JSON format.
*/
public class CounterStore {
private String FILENAME;
private Context context;
private ArrayList<Counter> counterList;
/**
* Contructs a CounterStore
* @param FILENAME file for writing to and reading from
* @param context app context managing this CounterStore
*/
public CounterStore(String FILENAME, Context context) {
this.FILENAME = FILENAME;
this.context = context;
}
/**
* Takes a counterList and writes it to file
* @param counterList list to write to file
*/
public void commit(ArrayList<Counter> counterList){
this.counterList = counterList;
saveInFile();
}
/**
* Loads an ArrayList of counters from file and returns it
* @return ArrayList of counters read from file
*/
public ArrayList<Counter> load(){
loadFromFile();
return this.counterList;
}
/**
* Returns the file name in use by this CounterStore. Useful for passing to another activity
* so it can have its own CounterStore reading from this file.
* @return filename in use by this counter store
*/
public String getFilename(){
return this.FILENAME;
}
/**
* Loads data from the file and converts it into an ArrayList of counters and then stores it
* in it's memory.
*/
private void loadFromFile() {
try {
FileInputStream fis = this.context.openFileInput(FILENAME);
BufferedReader in = new BufferedReader(new InputStreamReader(fis));
Gson gson = new Gson();
//Taken from https://stackoverflow.com/questions/12384064/gson-convert-from-json-to-a-typed-arraylistt
// 2017-09-19
Type listType = new TypeToken<ArrayList<Counter>>(){}.getType();
counterList = gson.fromJson(in, listType);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
counterList = new ArrayList<Counter>();
}
}
/**
* Writes the current in memory ArrayList of counters to file, overwriting contents.
*/
private void saveInFile() {
try {
FileOutputStream fos = this.context.openFileOutput(FILENAME,
Context.MODE_PRIVATE);
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(fos));
Gson gson = new Gson();
gson.toJson(counterList, out);
out.flush(); /*forces the buffer to be written*/
fos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
throw new RuntimeException();
}
}
}
| true |
eb0ff17175b4256072a90fab2deeb43197adf1ae | Java | ticou973/Choeur | /app/src/main/java/dedicace/com/data/database/Spectacle.java | UTF-8 | 3,366 | 2.25 | 2 | [] | no_license | package dedicace.com.data.database;
import android.arch.persistence.room.ColumnInfo;
import android.arch.persistence.room.Entity;
import android.arch.persistence.room.Ignore;
import android.arch.persistence.room.Index;
import android.arch.persistence.room.PrimaryKey;
import java.util.ArrayList;
import java.util.Date;
@Entity(indices = {@Index(value = {"spectacle_name"})})
public class Spectacle {
@PrimaryKey(autoGenerate = true)
private int spectacleId;
@ColumnInfo(name = "id_spectacle_cloud")
private String idSpectacleCloud;
@ColumnInfo(name = "spectacle_name")
private String spectacleName;
@ColumnInfo(name = "update_phone")
private Date updatePhone;
@ColumnInfo(name = "id_titres")
private ArrayList<String> idTitresSongs= new ArrayList<>();
@ColumnInfo(name = "spectacle_dates")
private ArrayList<Date> spectacleDates= new ArrayList<>();
@ColumnInfo(name = "spectacle_lieux")
private ArrayList<String> spectacleLieux= new ArrayList<>();
public Spectacle(int spectacleId, String idSpectacleCloud, String spectacleName, Date updatePhone, ArrayList<String> idTitresSongs, ArrayList<Date> spectacleDates, ArrayList<String> spectacleLieux) {
this.spectacleId = spectacleId;
this.idSpectacleCloud = idSpectacleCloud;
this.spectacleName = spectacleName;
this.updatePhone = updatePhone;
this.idTitresSongs = idTitresSongs;
this.spectacleDates = spectacleDates;
this.spectacleLieux = spectacleLieux;
}
@Ignore
public Spectacle() {
}
@Ignore
public Spectacle(String idSpectacle, String spectacleName, ArrayList<String> idSourceSongs, ArrayList<String> spectacleLieux, ArrayList<Date> spectacleDates, Date maj) {
this.idSpectacleCloud=idSpectacle;
this.spectacleName=spectacleName;
this.idTitresSongs=idSourceSongs;
this.spectacleLieux=spectacleLieux;
this.spectacleDates=spectacleDates;
this.updatePhone=maj;
}
public int getSpectacleId() {
return spectacleId;
}
public void setSpectacleId(int spectacleId) {
this.spectacleId = spectacleId;
}
public String getIdSpectacleCloud() {
return idSpectacleCloud;
}
public void setIdSpectacleCloud(String idSpectacleCloud) {
this.idSpectacleCloud = idSpectacleCloud;
}
public String getSpectacleName() {
return spectacleName;
}
public void setSpectacleName(String spectacleName) {
this.spectacleName = spectacleName;
}
public Date getUpdatePhone() {
return updatePhone;
}
public void setUpdatePhone(Date updatePhone) {
this.updatePhone = updatePhone;
}
public ArrayList<String> getIdTitresSongs() {
return idTitresSongs;
}
public void setIdTitresSongs(ArrayList<String> idTitresSongs) {
this.idTitresSongs = idTitresSongs;
}
public ArrayList<Date> getSpectacleDates() {
return spectacleDates;
}
public void setSpectacleDates(ArrayList<Date> spectacleDates) {
this.spectacleDates = spectacleDates;
}
public ArrayList<String> getSpectacleLieux() {
return spectacleLieux;
}
public void setSpectacleLieux(ArrayList<String> spectacleLieux) {
this.spectacleLieux = spectacleLieux;
}
}
| true |
94a835b63dcbf130a12ef5233e8edda636b4c8a0 | Java | sudheertalluri5/My_Java_Programs | /java_prog/CN-3.java | UTF-8 | 556 | 2.53125 | 3 | [] | no_license | class solution {
public static void main(String ar[]) throws InterruptedException
{
//Write code here
int sum=0,temp;
int arr[]={9,9,9};
for(int i=0;i<arr.length;i++){
sum+=arr[i];
}
System.out.println(sum);
while(sum%10!=sum){
temp=sum;
sum=0;
while(temp>0){
sum+=temp%10;
temp/=10;
}
System.out.println(sum);
Thread.sleep(1000);
}
System.out.println(sum);
}
}
| true |
c8d7cff4e788f727b82bba67db4c1817e9ed6189 | Java | aisensiy/demo-for-jackson | /src/main/java/com/example/demo/OrderWithStatus.java | UTF-8 | 807 | 2.8125 | 3 | [] | no_license | package com.example.demo;
import java.util.Objects;
public class OrderWithStatus {
private OrderStatus status;
private String id;
public OrderWithStatus(String id, OrderStatus status) {
this.status = status;
this.id = id;
}
private OrderWithStatus() {
}
public OrderStatus getStatus() {
return status;
}
public String getId() {
return id;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
OrderWithStatus that = (OrderWithStatus) o;
return status == that.status &&
Objects.equals(id, that.id);
}
@Override
public int hashCode() {
return Objects.hash(status, id);
}
}
| true |
1ca58a0bd92b2e133ac8d69637b7ea8863d5b676 | Java | windylcx/Dubbo-Spring-Mybatis-Generator | /generator-core/src/main/java/com/chunxiao/dev/config/dubbo/ProtocolConfig.java | UTF-8 | 590 | 2.1875 | 2 | [] | no_license | package com.chunxiao.dev.config.dubbo;
/**
* Created by chunxiaoli on 10/18/16.
*/
public class ProtocolConfig {
private String name;
private String owner;
private String port;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getOwner() {
return owner;
}
public void setOwner(String owner) {
this.owner = owner;
}
public String getPort() {
return port;
}
public void setPort(String port) {
this.port = port;
}
}
| true |
b2b347306bbb8c0a5452b90b61d4d649f974750c | Java | peng49/fly | /fly-web/src/main/java/fly/web/pojo/GiteeOauthResponse.java | UTF-8 | 709 | 1.703125 | 2 | [
"MIT"
] | permissive | package fly.web.pojo;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Data;
@Data
public class GiteeOauthResponse {
/**
* "access_token": "xxxxxxxxxxxxxxxx",
* "token_type": "bearer",
* "expires_in": 86400,
* "refresh_token": "xxxxxxxxxxxxxxxxxxxxxxxxxx",
* "scope": "user_info emails",
* "created_at": 1599991747
*/
@JsonProperty("access_token")
private String accessToken;
@JsonProperty("token_type")
private String tokenType;
@JsonProperty("expires_in")
private int expiresIn;
@JsonProperty("refresh_token")
private String refreshToken;
private String scope;
@JsonProperty("created_at")
private int createdAt;
}
| true |
36046fe84a81f126e555ce9dac7e70d48a9c7a5e | Java | pippo1980/DynamicAttributes4JPA | /src/main/java/com/sirius/jpa/dynamic/attribute/EntityDynamicAttributePersister.java | UTF-8 | 3,293 | 2.375 | 2 | [] | no_license | package com.sirius.jpa.dynamic.attribute;
import org.hibernate.Session;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.Serializable;
import java.lang.reflect.Field;
import java.util.HashSet;
import java.util.Set;
public class EntityDynamicAttributePersister {
private static final Logger LOGGER = LoggerFactory.getLogger(EntityDynamicAttributePersister.class);
@SuppressWarnings({"JpaQlInspection"})
private static final String UPDATE = "update com.sirius.jpa.dynamic.attribute.Attribute " +
"set attributeValue=:val " +
"where bizId=:bizId and groupName=:groupName and attributeKey=:attributeKey";
DynamicAttributePersister[] persisters;
public EntityDynamicAttributePersister(Class<?> clazz) {
Set<DynamicAttributePersister> persisters = new HashSet<>();
for (Field field : clazz.getDeclaredFields()) {
field.setAccessible(true);
DynamicAttributesGroup group = field.getAnnotation(DynamicAttributesGroup.class);
if (group == null || field.getType() != DynamicAttributes.class) {
continue;
}
persisters.add(new DynamicAttributePersister(group.name(), field));
}
this.persisters = persisters.toArray(new DynamicAttributePersister[0]);
}
public void persist(Session session, Serializable id, Object entity) {
for (DynamicAttributePersister persister : persisters) {
persister.persist(session, id, entity);
}
}
class DynamicAttributePersister {
public DynamicAttributePersister(String group, Field field) {
this.group = group;
this.field = field;
}
String group;
Field field;
void persist(Session session, Serializable id, Object entity) {
try {
Object fieldValue = field.get(entity);
if (fieldValue == null) {
return;
}
DynamicAttributes attributes = (DynamicAttributes) fieldValue;
if (entity == null || attributes.getAttributes() == null || attributes.getAttributes().size() == 0) {
return;
}
for (Attribute attribute : attributes.getAttributes()) {
int records = session.createQuery(UPDATE)
.setParameter("val", attribute.attributeValue)
.setParameter("bizId", id.toString())
.setParameter("groupName", group)
.setParameter("attributeKey", attribute.attributeKey)
.executeUpdate();
if (records == 0) {
attribute.setBizId(id.toString());
attribute.setGroupName(group);
session.save(attribute);
}
}
// TODO 字节码增强提高性能
field.set(entity, attributes);
} catch (Exception e) {
LOGGER.error("load dynamic attributes[{}/{}] due to error:[{}]", group, field.getName(), e);
}
}
}
}
| true |
fb11fe69fd5075b050a3862a35628da6678e83b0 | Java | wushangzhen/Projects | /lab3/src/OpPart.java | UTF-8 | 104 | 1.71875 | 2 | [] | no_license | package edu.neu.ccs.cs5010.lab3;
public interface OpPart {
public String asString(Visitor visitor);
}
| true |
28c497faea639997db911696d5a6c3965445a85e | Java | shreyas-redij/Neu_Hackers | /AdoptionApplication/src/userinterface/ParentsRole/ParentsWorkAreaJPanel.java | UTF-8 | 24,260 | 2.203125 | 2 | [
"GPL-1.0-or-later",
"GPL-2.0-only",
"MIT"
] | permissive | /*
* 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 userinterface.ParentsRole;
import static Business.ConfigureASystem.system;
import Business.Directory.BirthMother;
import Business.Directory.Parents;
import Business.Enterprise.Enterprise;
import Business.Organization.Organization;
import Business.UserAccount.UserAccount;
import java.awt.CardLayout;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
/**
*
* @author HP
*/
public class ParentsWorkAreaJPanel extends javax.swing.JPanel {
/**
* Creates new form ParentsWorkAreaJPanel
*/
private JPanel userProcessContainer;
private Organization organization;
private UserAccount userAccount;
private Enterprise enterprise;
private Parents parents;
private BirthMother mother;
private int value;
private int parentValue;
private int remaining;
private float percentage;
/**
* Creates new form ParentsWorkArea
*/
public ParentsWorkAreaJPanel(JPanel userProcessContainer, Enterprise enterprise, UserAccount account, Organization organization) {
initComponents();
this.userProcessContainer = userProcessContainer;
this.organization = organization;
this.enterprise = enterprise;
this.userAccount = account;
this.parents = account.getParent();
valueLabel.setText(enterprise.getName());
this.mother = this.parents.getBirthMother();
if(mother != null){
populateParentDetails();
}
draw();
}
private void populateParentDetails(){
lblName.setText(mother.getFirstName() +" "+ mother.getLastName());
lblAddress.setText(mother.getAddress());
lblEmail.setText(mother.getEmailId());
lblContact.setText(mother.getContactMother());
lblSupportAmount.setText(String.valueOf(parents.getFunds()));
if (lblSupportAmount == null){
lblSupportAmount.setText("0");
}
lblRemainingAmount.setText(String.valueOf(parents.getRemainingFunds()));
parentImg.setIcon(new ImageIcon(mother.getImgPath()));
}
private void draw(){
parentValue = parents.getFunds();
lblSupportAmount.setText(String.valueOf(parentValue));
int remainingValue = parents.getRemainingFunds();
remaining = remainingValue - value;
parents.setRemainingFunds(remaining);
lblRemainingAmount.setText(String.valueOf(remaining));
this.percentage = ((float)(parentValue - remaining)/parentValue)*100;
progressBar.setValue((int) percentage);
this.percentage = ((float)(parentValue - remaining)/parentValue)*100;
progressBar.setValue((int) percentage);
}
/**
* 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() {
jLabel1 = new javax.swing.JLabel();
enterpriseLabel = new javax.swing.JLabel();
valueLabel = new javax.swing.JLabel();
checkRequestsPending = new javax.swing.JButton();
btnViewFamily = new javax.swing.JButton();
jPanel1 = new javax.swing.JPanel();
progressBar = new javax.swing.JProgressBar();
jLabel6 = new javax.swing.JLabel();
lblSupportAmount = new javax.swing.JLabel();
jLabel8 = new javax.swing.JLabel();
lblRemainingAmount = new javax.swing.JLabel();
jLabel7 = new javax.swing.JLabel();
txtEnterFunds = new javax.swing.JTextField();
btnTransfer = new javax.swing.JButton();
jPanel2 = new javax.swing.JPanel();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
lblName = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
lblAddress = new javax.swing.JLabel();
jLabel5 = new javax.swing.JLabel();
lblContact = new javax.swing.JLabel();
jLabel9 = new javax.swing.JLabel();
lblEmail = new javax.swing.JLabel();
parentImg = new javax.swing.JLabel();
btnRefresh = new javax.swing.JButton();
setBackground(java.awt.SystemColor.activeCaption);
setMaximumSize(new java.awt.Dimension(1245, 1000));
setMinimumSize(new java.awt.Dimension(1245, 1000));
setPreferredSize(new java.awt.Dimension(1245, 1000));
jLabel1.setFont(new java.awt.Font("Times New Roman", 1, 24)); // NOI18N
jLabel1.setText("Parents Work Area");
enterpriseLabel.setFont(new java.awt.Font("Tahoma", 1, 24)); // NOI18N
enterpriseLabel.setText("ENTERPRISE:");
valueLabel.setFont(new java.awt.Font("Lucida Grande", 3, 24)); // NOI18N
valueLabel.setText("<value>");
checkRequestsPending.setFont(new java.awt.Font("Times New Roman", 1, 18)); // NOI18N
checkRequestsPending.setText("Check Birth Mother Request");
checkRequestsPending.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
checkRequestsPendingActionPerformed(evt);
}
});
btnViewFamily.setFont(new java.awt.Font("Times New Roman", 1, 18)); // NOI18N
btnViewFamily.setText("View/Update Family Profile");
btnViewFamily.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnViewFamilyActionPerformed(evt);
}
});
progressBar.setStringPainted(true);
jLabel6.setFont(new java.awt.Font("Times New Roman", 1, 18)); // NOI18N
jLabel6.setText("Contribution:");
lblSupportAmount.setText("jLabel7");
jLabel8.setFont(new java.awt.Font("Times New Roman", 1, 18)); // NOI18N
jLabel8.setText("Remaining:");
lblRemainingAmount.setText("jLabel7");
jLabel7.setFont(new java.awt.Font("Times New Roman", 1, 18)); // NOI18N
jLabel7.setText("Amount to Transfer:");
txtEnterFunds.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
txtEnterFundsActionPerformed(evt);
}
});
btnTransfer.setFont(new java.awt.Font("Lucida Grande", 1, 14)); // NOI18N
btnTransfer.setText("TRANSFER");
btnTransfer.setFocusPainted(false);
btnTransfer.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnTransferActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(62, 62, 62)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(progressBar, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 377, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jLabel6)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(lblSupportAmount))
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jLabel8)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(lblRemainingAmount)))
.addGap(110, 110, 110))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addComponent(jLabel7)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(txtEnterFunds, javax.swing.GroupLayout.PREFERRED_SIZE, 159, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(32, 32, 32)))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(93, 93, 93)
.addComponent(btnTransfer, javax.swing.GroupLayout.PREFERRED_SIZE, 191, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(93, 93, 93)))
.addContainerGap(82, Short.MAX_VALUE))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addComponent(progressBar, javax.swing.GroupLayout.PREFERRED_SIZE, 81, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel6)
.addComponent(lblSupportAmount))
.addGap(18, 18, 18)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel8)
.addComponent(lblRemainingAmount))
.addGap(18, 18, 18)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel7)
.addComponent(txtEnterFunds, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(31, 31, 31)
.addComponent(btnTransfer, javax.swing.GroupLayout.PREFERRED_SIZE, 44, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(38, Short.MAX_VALUE))
);
jLabel2.setFont(new java.awt.Font("Times New Roman", 1, 18)); // NOI18N
jLabel2.setText("MOTHER PROFILE :");
jLabel3.setBackground(new java.awt.Color(255, 255, 255));
jLabel3.setFont(new java.awt.Font("Lucida Grande", 1, 13)); // NOI18N
jLabel3.setForeground(new java.awt.Color(64, 151, 182));
jLabel3.setText("NAME:");
lblName.setText("jLabel8");
jLabel4.setBackground(new java.awt.Color(255, 255, 255));
jLabel4.setFont(new java.awt.Font("Lucida Grande", 1, 13)); // NOI18N
jLabel4.setForeground(new java.awt.Color(64, 151, 182));
jLabel4.setText("ADDRESS:");
lblAddress.setText("jLabel9");
jLabel5.setFont(new java.awt.Font("Lucida Grande", 1, 13)); // NOI18N
jLabel5.setForeground(new java.awt.Color(64, 151, 182));
jLabel5.setText("CONTACT:");
lblContact.setText("jLabel10");
jLabel9.setFont(new java.awt.Font("Lucida Grande", 1, 13)); // NOI18N
jLabel9.setForeground(new java.awt.Color(64, 151, 182));
jLabel9.setText("EMAIL:");
lblEmail.setText("jLabel11");
parentImg.setBackground(new java.awt.Color(102, 255, 102));
parentImg.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
.addContainerGap(76, Short.MAX_VALUE)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addGap(3, 3, 3)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel2)
.addComponent(jLabel3)
.addComponent(jLabel4)
.addComponent(lblName)
.addComponent(jLabel5)
.addComponent(lblAddress)
.addComponent(lblContact)))
.addComponent(lblEmail)
.addComponent(jLabel9))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(parentImg, javax.swing.GroupLayout.PREFERRED_SIZE, 225, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(73, 73, 73))
);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(parentImg, javax.swing.GroupLayout.PREFERRED_SIZE, 233, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(jPanel2Layout.createSequentialGroup()
.addComponent(jLabel2)
.addGap(18, 18, 18)
.addComponent(jLabel3)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(lblName)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel4)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(lblAddress)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel5)
.addGap(4, 4, 4)
.addComponent(lblContact)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel9)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(lblEmail)))
.addContainerGap(25, Short.MAX_VALUE))
);
btnRefresh.setFont(new java.awt.Font("Tahoma", 1, 16)); // NOI18N
btnRefresh.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/Refresh.jpg"))); // NOI18N
btnRefresh.setText("Refresh");
btnRefresh.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnRefreshActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(141, 141, 141)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(btnViewFamily, javax.swing.GroupLayout.PREFERRED_SIZE, 256, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(checkRequestsPending, javax.swing.GroupLayout.PREFERRED_SIZE, 256, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(119, 119, 119)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGroup(layout.createSequentialGroup()
.addGap(399, 399, 399)
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 212, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(275, 275, 275)
.addComponent(btnRefresh))
.addGroup(layout.createSequentialGroup()
.addGap(190, 190, 190)
.addComponent(enterpriseLabel)
.addGap(18, 18, 18)
.addComponent(valueLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 592, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap(170, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(54, 54, 54)
.addComponent(btnRefresh, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addGap(39, 39, 39)
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(38, 38, 38)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(enterpriseLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(valueLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 26, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 45, Short.MAX_VALUE)
.addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(152, 152, 152))
.addGroup(layout.createSequentialGroup()
.addGap(236, 236, 236)
.addComponent(checkRequestsPending, javax.swing.GroupLayout.PREFERRED_SIZE, 75, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(154, 154, 154)
.addComponent(btnViewFamily, javax.swing.GroupLayout.PREFERRED_SIZE, 82, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
);
}// </editor-fold>//GEN-END:initComponents
private void checkRequestsPendingActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_checkRequestsPendingActionPerformed
if(userAccount.getParent().getBloodGroup() == null){
JOptionPane.showMessageDialog(this, "Please complete your profile to view requests!");
return;
}
CardLayout layout = (CardLayout) userProcessContainer.getLayout();
userProcessContainer.add("ViewBirthMotherRequestsJPanel", new ViewBirthMotherRequestsJPanel(userProcessContainer, userAccount, organization, enterprise, system));
layout.next(userProcessContainer);
}//GEN-LAST:event_checkRequestsPendingActionPerformed
private void btnViewFamilyActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnViewFamilyActionPerformed
CardLayout layout = (CardLayout) userProcessContainer.getLayout();
userProcessContainer.add("ParentProfile", new ParentProfile(userAccount,organization,userProcessContainer));
layout.next(userProcessContainer);
}//GEN-LAST:event_btnViewFamilyActionPerformed
private void txtEnterFundsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtEnterFundsActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_txtEnterFundsActionPerformed
private void btnTransferActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnTransferActionPerformed
// TODO add your handling code here:
int remainingValue = parents.getRemainingFunds();
if(remainingValue > 0){
value = Integer.parseInt(txtEnterFunds.getText());
int total = mother.getBankBalance() + value;
mother.setBankBalance(total);
parentValue = parents.getFunds();
remaining = remainingValue - value;
parents.setRemainingFunds(remaining);
lblRemainingAmount.setText(String.valueOf(remaining));
this.percentage = ((float)(parentValue - remaining)/parentValue)*100;
progressBar.setValue((int) percentage);
}
else {
JOptionPane.showMessageDialog(this,"Remaining Amount is 0!");
return;
}
}//GEN-LAST:event_btnTransferActionPerformed
private void btnRefreshActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnRefreshActionPerformed
// TODO add your handling code here:
if(mother != null){
populateParentDetails();
}
draw();
}//GEN-LAST:event_btnRefreshActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton btnRefresh;
private javax.swing.JButton btnTransfer;
private javax.swing.JButton btnViewFamily;
private javax.swing.JButton checkRequestsPending;
private javax.swing.JLabel enterpriseLabel;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel7;
private javax.swing.JLabel jLabel8;
private javax.swing.JLabel jLabel9;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
private javax.swing.JLabel lblAddress;
private javax.swing.JLabel lblContact;
private javax.swing.JLabel lblEmail;
private javax.swing.JLabel lblName;
private javax.swing.JLabel lblRemainingAmount;
private javax.swing.JLabel lblSupportAmount;
private javax.swing.JLabel parentImg;
private javax.swing.JProgressBar progressBar;
private javax.swing.JTextField txtEnterFunds;
private javax.swing.JLabel valueLabel;
// End of variables declaration//GEN-END:variables
}
| true |
1a5328e8bd31f2e256fb84f67ebb92683a9f9fb4 | Java | 851822132/my-springboot | /src/main/java/com/test/myspringboot/config/SwaggerConfig.java | UTF-8 | 2,021 | 2.234375 | 2 | [] | no_license | package com.test.myspringboot.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
/**
* @author: ysh
* @date: 2019/3/20 16:04
* @Description:
* @Api:表示标识这个类是swagger的资源
* @ApiOperation:描述针对特定路径的操作或HTTP方法
* @ApiImplicitParam:表示API操作中的单个参数
* @ApiImplicitParams:允许多个ApiImplicitParam对象列表的包装器
* @ApiModel:提供关于Swagger模型的额外信息
* @ApiModelProperty:添加和操作模型属性的数据
* @ApiParam:为操作参数添加额外的元数据
* @ApiResponse:描述一个操作的可能响应
* @ApiResponses:允许多个ApiResponse对象列表的包装器
* @ResponseHeader:表示可以作为响应的一部分提供的标头
* @Authorization:声明要在资源或操作上使用的授权方案
* @AuthorizationScope:描述OAuth2授权范围
*/
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket createRestApi(){
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.test.myspringboot.controller"))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo(){
return new ApiInfoBuilder()
.title("springBoot测试")
.description("by ysh")
.termsOfServiceUrl("m.ahqyc.com")
.version("1.0")
.build();
}
}
| true |
3ac268f682f71d646d16dae22ac8f067838b8d79 | Java | fredska/Swarm | /Swarm/src/com/fska/swarm/entity/building/TownHall.java | UTF-8 | 702 | 2.5 | 2 | [
"Apache-2.0"
] | permissive | package com.fska.swarm.entity.building;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.Batch;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.math.Vector2;
import com.fska.swarm.entity.Building;
public class TownHall extends Building {
private TextureRegion buildingTexture;
public TownHall(Vector2 position) {
super(position);
buildingTexture = new TextureRegion(
new Texture(Gdx.files.internal("units/TownHall_1.png")));
}
@Override
public void draw(Batch batch) {
batch.draw(buildingTexture, super.getPosition().x, super.getPosition().y);
}
@Override
public void update() {
}
}
| true |
76fb10daa23ba298d3ee62061c04bfafbfea8ae1 | Java | rafaelweingartner/autonomiccs-platform | /autonomic-administration-plugin/src/main/java/br/com/autonomiccs/autonomic/administration/plugin/HypervisorManager.java | UTF-8 | 3,232 | 2.078125 | 2 | [
"Apache-2.0",
"LicenseRef-scancode-generic-cla",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | /*
* This program is part of Autonomiccs "autonomic-platform",
* an open source autonomic cloud computing management platform.
* Copyright (C) 2016 Autonomiccs, Inc.
*
* Licensed to the Autonomiccs, Inc. under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The Autonomiccs, 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 br.com.autonomiccs.autonomic.administration.plugin;
import java.util.List;
import javax.inject.Inject;
import org.springframework.stereotype.Component;
import com.cloud.host.Host;
import com.cloud.host.HostVO;
import com.cloud.utils.exception.CloudRuntimeException;
import br.com.autonomiccs.autonomic.administration.plugin.hypervisors.HypervisorHost;
import br.com.autonomiccs.autonomic.plugin.common.enums.HostAdministrationStatus;
import br.com.autonomiccs.autonomic.plugin.common.services.HostService;
/**
* Manages hypervisor's operations, passing the execution flow to the correct hypervisor facade.
*/
@Component(value = "hypervisorManager")
public class HypervisorManager {
@Inject
private HostService hostService;
@Inject
protected List<HypervisorHost> hypervisorHosts;
/**
* Executes the shutdownHost method of the {@link HostVO} hypervisor. If the
* hypervisor from {@link HostVO} does not supports shutdown, then it throws
* a {@link CloudRuntimeException}.
*/
public void shutdownHost(HostVO hostVo) {
if (!Host.Type.Routing.equals(hostVo.getType())) {
return;
}
for (HypervisorHost currentHypervisorHost : hypervisorHosts) {
if (currentHypervisorHost.supportsHypervisor(hostVo.getHypervisorType())) {
shutdown(hostVo, currentHypervisorHost);
return;
}
}
throw new CloudRuntimeException(
String.format("The the hypervisor[%s] from host[id=%d] does not support shutdown to consolidate", hostVo.getHypervisorType(), hostVo.getId()));
}
/**
* Calls the {@link HypervisorHost#shutdownHost(HostVO)} method and mark the
* host administration process as {@link HostAdministrationStatus#ShutDownToConsolidate} using
* {@link HostService#markHostAsShutdownByAdministrationAgent(long)}.
*/
protected void shutdown(HostVO hostVo, HypervisorHost currentHypervisorHost) {
hostService.loadHostDetails(hostVo);
currentHypervisorHost.shutdownHost(hostVo);
hostService.markHostAsShutdownByAdministrationAgent(hostVo.getId());
}
}
| true |
f733a61f0ef5f90c138ce222c22517c8b892a9d4 | Java | paulovictorcg/glam | /app/src/main/java/glam/android/minexp/glam/ui/Checkout.java | UTF-8 | 4,617 | 1.992188 | 2 | [] | no_license | package glam.android.minexp.glam.ui;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.RecyclerView.Adapter;
import android.support.v7.widget.RecyclerView.ViewHolder;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
//import com.glam.C0148R;
import glam.android.minexp.glam.CheckoutActivity;
import glam.android.minexp.glam.MainActivity;
import glam.android.minexp.glam.ProductDetail;
import glam.android.minexp.glam.custom.CustomFragment;
import glam.android.minexp.glam.custom.CustomActivity;
import glam.android.minexp.glam.model.Data;
import java.util.ArrayList;
import glam.android.minexp.glam.R;
public class Checkout extends CustomFragment {
private ArrayList<Data> iList;
private class CardAdapter extends Adapter<CardAdapter.CardViewHolder> {
class C01511 implements OnClickListener {
C01511() {
}
public void onClick(View v) {
Checkout.this.startActivity(new Intent(Checkout.this.getActivity(), ProductDetail.class));
}
}
public class CardViewHolder extends ViewHolder {
protected ImageView img;
protected TextView lbl1;
protected TextView lbl2;
protected TextView lbl3;
public CardViewHolder(View v) {
super(v);
this.lbl1 = (TextView) v.findViewById(R.id.lbl1);
this.lbl2 = (TextView) v.findViewById(R.id.lbl2);
this.lbl3 = (TextView) v.findViewById(R.id.lbl3);
this.img = (ImageView) v.findViewById(R.id.img);
}
}
private CardAdapter() {
}
public int getItemCount() {
return Checkout.this.iList.size();
}
public void onBindViewHolder(CardViewHolder vh, int i) {
Data d = (Data) Checkout.this.iList.get(i);
vh.lbl1.setText(d.getTexts()[0]);
vh.lbl2.setText(d.getTexts()[1]);
vh.lbl3.setText(d.getTexts()[2]);
vh.img.setImageResource(d.getResources()[0]);
}
public CardViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View itemView = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.grid_item1, viewGroup, false);
itemView.setOnClickListener(new C01511());
return new CardViewHolder(itemView);
}
}
@SuppressLint({"InflateParams", "InlinedApi"})
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.checkout, null);
if (getActivity() instanceof MainActivity) {
((MainActivity) getActivity()).toolbar.setTitle((CharSequence) "Checkout");
((MainActivity) getActivity()).toolbar.findViewById(R.id.spinner_toolbar).setVisibility(8);
} else {
((CheckoutActivity) getActivity()).getSupportActionBar().setTitle((CharSequence) "Checkout");
}
setTouchNClick(v.findViewById(R.id.btnDone));
setHasOptionsMenu(true);
setupView(v);
return v;
}
public void onClick(View v) {
super.onClick(v);
}
private void setupView(View v) {
loadDummyData();
RecyclerView recList = (RecyclerView) v.findViewById(R.id.cardList);
recList.setHasFixedSize(true);
LinearLayoutManager llm = new LinearLayoutManager(getActivity());
llm.setOrientation(0);
recList.setLayoutManager(llm);
recList.setAdapter(new CardAdapter());
}
private void loadDummyData() {
ArrayList<Data> al = new ArrayList();
al.add(new Data(new String[]{"Y.M.C. Spray Tee (Grey)", "$67", "Oi Polloi"}, new int[]{R.drawable.checking_img1}));
al.add(new Data(new String[]{"Ally Capellino", "$94", "Ally Capellino"}, new int[]{R.drawable.checking_img2}));
this.iList = new ArrayList(al);
this.iList.addAll(al);
this.iList.addAll(al);
this.iList.addAll(al);
this.iList.addAll(al);
this.iList.addAll(al);
}
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.cart, menu);
super.onCreateOptionsMenu(menu, inflater);
}
}
| true |
34de7a4ac3d44474fc93d5e40097de74e3f0acbc | Java | anhtuta/AndroidTutorial | /SQLiteDemo/main/java/com/bkhn/anhtu/sqlitedemo/MainActivity.java | UTF-8 | 5,886 | 2.296875 | 2 | [] | no_license | package com.bkhn.anhtu.sqlitedemo;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.ButtonBarLayout;
import android.support.v7.widget.ListViewCompat;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
String DATABASE_NAME = "db_contact.sqlite";
String TABLE_NAME = "table_contacts"; //ten table trong csdl db_contact
String DB_PATH_SUFFIX = "/database/";
SQLiteDatabase database = null;
ListView lvContact;
ArrayList<String> listContact;
ArrayAdapter<String> adapterContact;
Button btAdd, btUpdate;
EditText txtId, txtName, txtPhone;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
copyDBFromAssetsToMobileSystem();
addComponents();
addEvents();
try {
showAllContactsOnListView();
} catch (Exception e) {
Toast.makeText(this, "Error: "+e.getMessage(), Toast.LENGTH_LONG).show();
}
}
private void showAllContactsOnListView() {
//buoc 1: open database:
database = openOrCreateDatabase(DATABASE_NAME, MODE_PRIVATE, null);
//Cursor cursor = database.query(TABLE_NAME, null, null, null,null,null,null); //truy van
//cach 2:
Cursor cursor = database.rawQuery("select * from "+TABLE_NAME, null);
listContact.clear(); //xoa cai cu di
while(cursor.moveToNext()) {
int id = cursor.getInt(0);
String name = cursor.getString(1);
String phone = cursor.getString(2);
listContact.add(id+" - "+name+" - "+phone);
}
adapterContact.notifyDataSetChanged();
cursor.close();
}
private void addComponents() {
lvContact = (ListView)findViewById(R.id.lvContact);
listContact = new ArrayList<String>();
adapterContact = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1, listContact);
lvContact.setAdapter(adapterContact);
btAdd = (Button)findViewById(R.id.btAdd);
btUpdate = (Button)findViewById(R.id.btUpdate);
txtId = (EditText)findViewById(R.id.txtId);
txtName = (EditText)findViewById(R.id.txtName);
txtPhone = (EditText)findViewById(R.id.txtPhone);
}
private void addEvents() {
btAdd.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) { //add an object into table in database
//readMode();
ContentValues row = new ContentValues();
row.put("id", Integer.valueOf(txtId.getText().toString()));
row.put("name", txtName.getText().toString());
row.put("phone", txtPhone.getText().toString()); //chu y: ten cot phai giong trong database
long l = database.insert(TABLE_NAME, null, row);
if(l>0)
Toast.makeText(MainActivity.this, "Add successful", Toast.LENGTH_SHORT).show();
else Toast.makeText(MainActivity.this, "Add failed!", Toast.LENGTH_SHORT).show();
}
});
btUpdate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
ContentValues row = new ContentValues();
row.put("name", "Tu toc xu");
database.update(TABLE_NAME, row, "id=?", new String[]{"1001"});
showAllContactsOnListView();
}
});
lvContact.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
}
});
}
private void copyDBFromAssetsToMobileSystem() {
File dbFile = getDatabasePath(DATABASE_NAME);
if(!dbFile.exists()) {
try {
InputStream input = getAssets().open(DATABASE_NAME);
String outFileName = getStoredPath();
File f = new File(getApplicationInfo().dataDir + DB_PATH_SUFFIX); //lay duong dan thu muc goc + DB_PATH_SUFFIX
if(!f.exists()) {
f.mkdir();
}
OutputStream output = new FileOutputStream(outFileName);
byte[] buffer = new byte[1024];
int length;
while ((length = input.read(buffer)) > 0) {
output.write(buffer, 0, length);
}
output.flush();
output.close();
input.close();
Toast.makeText(this, "sao chep csdl thanh cong", Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(this, "ko the sao chep csdl. Loi: "+e.getMessage(), Toast.LENGTH_LONG).show();
}
}
else Toast.makeText(this, "this database already exist!", Toast.LENGTH_SHORT).show();
}
private String getStoredPath() { //lay duong dan phai luu tru
return getApplicationInfo().dataDir + DB_PATH_SUFFIX+ DATABASE_NAME;
}
public void readMode() {
txtId.setVisibility(View.INVISIBLE);
txtName.setVisibility(View.INVISIBLE);
txtPhone.setVisibility(View.INVISIBLE);
}
}
| true |
73a3cac40b4b4ecfa449987131e2d1fd15de8c41 | Java | mohnish82/auto-oauth-token | /src/main/java/com/desasha/autooauthtoken/config/OidcConfig.java | UTF-8 | 896 | 1.859375 | 2 | [] | no_license | package com.desasha.autooauthtoken.config;
import com.desasha.autooauthtoken.oidc.OidcDiscoveryService;
import com.desasha.autooauthtoken.oidc.OidcMetadata;
import com.nimbusds.openid.connect.sdk.op.OIDCProviderMetadata;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
@Configuration
public class OidcConfig {
@Bean
public OidcMetadata oidcMetadata(OidcDiscoveryService oidcDiscoveryService, Environment env) throws Exception {
String wellKnownUri = env.getProperty("spring.security.oauth2.client.provider.kc.oidc-well-known-uri");
OIDCProviderMetadata meta = oidcDiscoveryService.fetchProviderMetadata(wellKnownUri);
OidcMetadata result = new OidcMetadata(meta);
oidcDiscoveryService.fetchSigningKeys(meta).forEach(result::addSignatureKeys);
return result;
}
}
| true |
d2b679bd75c8ddc936c1206c40209874c3d57ca1 | Java | natanielpaiva/connecta-framework | /connecta-connectors/src/main/java/br/com/cds/connecta/framework/connector/endeca/endeca_server/sconfig/_3/_0/ValidatedSemanticEntity.java | UTF-8 | 3,428 | 1.945313 | 2 | [] | no_license |
package br.com.cds.connecta.framework.connector.endeca.endeca_server.sconfig._3._0;
import br.com.cds.connecta.framework.connector.endeca.mdex.eql_parser.types.Query;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
//import com.endeca.mdex.eql_parser.types.Query;
/**
* <p>Classe Java de validatedSemanticEntity complex type.
*
* <p>O seguinte fragmento do esquema especifica o conte\u00fado esperado contido dentro desta classe.
*
* <pre>
* <complexType name="validatedSemanticEntity">
* <complexContent>
* <extension base="{http://www.endeca.com/endeca-server/sconfig/3/0}semanticEntity">
* <sequence>
* <element name="parsedDefinition" type="{http://www.endeca.com/MDEX/eql_parser/types}Query"/>
* <element name="dependentSources" type="{http://www.endeca.com/endeca-server/sconfig/3/0}NonEmptyString" maxOccurs="unbounded" minOccurs="0"/>
* </sequence>
* <attribute name="isValid" use="required" type="{http://www.w3.org/2001/XMLSchema}boolean" />
* </extension>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "validatedSemanticEntity", propOrder = {
"parsedDefinition",
"dependentSources"
})
public class ValidatedSemanticEntity
extends SemanticEntity
{
@XmlElement(required = true)
protected Query parsedDefinition;
protected List<String> dependentSources;
@XmlAttribute(name = "isValid", required = true)
protected boolean isValid;
/**
* Obt\u00e9m o valor da propriedade parsedDefinition.
*
* @return
* possible object is
* {@link Query }
*
*/
public Query getParsedDefinition() {
return parsedDefinition;
}
/**
* Define o valor da propriedade parsedDefinition.
*
* @param value
* allowed object is
* {@link Query }
*
*/
public void setParsedDefinition(Query value) {
this.parsedDefinition = value;
}
/**
* Gets the value of the dependentSources property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the dependentSources property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getDependentSources().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link String }
*
*
*/
public List<String> getDependentSources() {
if (dependentSources == null) {
dependentSources = new ArrayList<String>();
}
return this.dependentSources;
}
/**
* Obt\u00e9m o valor da propriedade isValid.
*
*/
public boolean isIsValid() {
return isValid;
}
/**
* Define o valor da propriedade isValid.
*
*/
public void setIsValid(boolean value) {
this.isValid = value;
}
}
| true |
0fde704b32c38fca969013bb63c4a25b9f8e8bd1 | Java | daiyongbing/JBlock | /src/main/java/jblock/app/JBlock.java | UTF-8 | 3,507 | 3.046875 | 3 | [
"Apache-2.0"
] | permissive | package jblock.app;
import akka.actor.ActorSystem;
import akka.actor.Address;
import jblock.app.system.ClusterSystem;
import java.util.*;
public class JBlock {
public static void main(String[] args){
//创建系统实例
ClusterSystem sys1 = new ClusterSystem("1",ClusterSystem.InitType.MULTI_INIT,true);
sys1.init();//初始化(参数和配置信息)
Address joinAddress = sys1.getClusterAddr();//获取组网地址
sys1.joinCluster(joinAddress);//加入网络
sys1.enableWS();//开启API接口
sys1.start();//启动系统
ActorSystem cluster = sys1.getActorSys();//获取内部系统SystemActor实例
int node_min = 5;
//如果node_max>node_min 将启动node反复离网和入网的仿真,但是由于system离网后无法复用并重新加入
//运行一定时间会内存溢出
int node_max = 5;
boolean node_add = true;
Set<ClusterSystem> nodes = new HashSet<ClusterSystem>();
nodes.add(sys1); //入网
Set<ClusterSystem> nodes_off = new HashSet<ClusterSystem>();
for(int i =2; i <= node_max; i++) {
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
int len = nodes.size();
ClusterSystem sys = new ClusterSystem(String.valueOf(i),ClusterSystem.InitType.MULTI_INIT,true);
sys.init();
sys.joinCluster(joinAddress);
sys.start();
nodes.add(sys);
}
//node数量在最大和最小值之间振荡,仿真node入网和离网
//离网的system似乎无法复用,只能重新新建实例
if(node_max > node_min){
node_add = false;
for(int i=1; i<=1000; i++) {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
int len = nodes.size();
if(len >= node_max){
node_add=false;
}else if(len <= node_min){
node_add=true;
}
if(!node_add){
//Set不能直接取指定位置的元素,先将其转换为List后再取
List<ClusterSystem> list = new ArrayList<ClusterSystem>(nodes);
ClusterSystem nd_system = list.get(nodes.size()-1);
nd_system.leaveCluster(cluster);
try{
//Await.ready(nd_system.terminate(), Duration.Inf)
}catch(Exception e){
e.printStackTrace();
}
//Await.ready(nd_system.whenTerminated, 30.seconds)
//nd_system.terminate();
//nd_system.shutdown()
nodes.remove(nd_system);
//nodes_off += nd_system
} else{
//避免systemName重复
ClusterSystem sys = new ClusterSystem(String.valueOf(i),ClusterSystem.InitType.MULTI_INIT,true);
sys1.init();
joinAddress = sys1.getClusterAddr();
sys1.joinCluster(joinAddress);
sys1.start();
nodes.add(sys);
//nodes_off -= nd_system
}
}
}
}
}
| true |
40f14ba9a22d92c58a395e2a39c3298674479271 | Java | Somruethai02/Test_4jan | /app/src/main/java/com/example/rtc/somruethaianusa/test/b2Activity.java | UTF-8 | 682 | 1.757813 | 2 | [] | no_license | package com.example.rtc.somruethaianusa.test;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ImageButton;
public class b2Activity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_b2);
}
public void onClickno (View view) {
ImageButton btn_animal = (ImageButton)findViewById(R.id.imageButton23);
Intent intent = new Intent(b2Activity.this,b3Activity.class);
startActivity(intent);
finish();
}
}
| true |
9fd0764efc82668ceba97f633f22225654dc929f | Java | sawaikatyou/ContentProviderTest | /app/src/androidTest/java/com/sasakik/contentprovidertest/provider/MyMockContentResolver.java | UTF-8 | 943 | 2.015625 | 2 | [] | no_license | package com.sasakik.contentprovidertest.provider;
import android.content.ContentProvider;
import android.content.Context;
import android.content.pm.ProviderInfo;
import com.sasakik.contentprovidertest.provider.DBConstants;
import com.sasakik.contentprovidertest.provider.MainContentProvider;
/**
* Created by nine_eyes on 2016/06/05.
*/
public class MyMockContentResolver extends android.test.mock.MockContentResolver {
Context mParent;
public MyMockContentResolver(Context context) {
mParent = context;
ContentProvider provider = new MainContentProvider();
ProviderInfo providerInfo = new ProviderInfo();
providerInfo.authority = DBConstants.AUTHORITY;
providerInfo.enabled = true;
providerInfo.packageName = MainContentProvider.class.getPackage().getName();
provider.attachInfo(context, providerInfo);
super.addProvider(DBConstants.AUTHORITY, provider);
}
}
| true |
e25045efa954a9530b3055b1366e4c5507b30fe3 | Java | arcus-smart-home/arcusplatform | /platform/arcus-containers/platform-services/src/test/java/com/iris/platform/services/hub/TestHubRegistry.java | UTF-8 | 18,642 | 1.648438 | 2 | [
"Apache-2.0"
] | permissive | /*
* Copyright 2019 Arcus Project
*
* 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.iris.platform.services.hub;
import java.time.Clock;
import java.util.Collection;
import java.util.Date;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import org.apache.commons.lang3.StringUtils;
import org.easymock.EasyMock;
import org.eclipse.jdt.annotation.Nullable;
import org.junit.Before;
import org.junit.Test;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.inject.Inject;
import com.google.inject.Provides;
import com.iris.core.dao.HubDAO;
import com.iris.core.messaging.memory.InMemoryMessageModule;
import com.iris.core.messaging.memory.InMemoryPlatformMessageBus;
import com.iris.messages.PlatformMessage;
import com.iris.messages.address.Address;
import com.iris.messages.capability.Capability;
import com.iris.messages.capability.HubCapability;
import com.iris.messages.capability.HubConnectionCapability;
import com.iris.messages.model.Fixtures;
import com.iris.messages.model.Hub;
import com.iris.messages.type.Population;
import com.iris.platform.partition.DefaultPartition;
import com.iris.platform.partition.PartitionChangedEvent;
import com.iris.platform.partition.Partitioner;
import com.iris.population.PlacePopulationCacheManager;
import com.iris.test.IrisMockTestCase;
import com.iris.test.Mocks;
import com.iris.test.Modules;
@Modules(InMemoryMessageModule.class)
@Mocks({ HubDAO.class, Clock.class, Partitioner.class , PlacePopulationCacheManager.class})
public class TestHubRegistry extends IrisMockTestCase {
// unit under test
@Inject HubRegistry registry;
@Inject InMemoryPlatformMessageBus platformBus;
@Inject HubDAO mockHubDao;
@Inject Clock mockClock;
@Inject Partitioner mockPartitioner;
@Inject protected PlacePopulationCacheManager mockPopulationCacheMgr;
// data
Hub hub1, hub2;
@Provides
public HubRegistryConfig hubRegistryConfig() {
HubRegistryConfig config = new HubRegistryConfig();
// effectively disable the background task
config.setTimeoutIntervalSec(Integer.MAX_VALUE);
return config;
}
@Before
public void setUp() throws Exception {
super.setUp();
// reset the addListener call made by HubRegistry
EasyMock.reset(mockPartitioner);
hub1 = Fixtures.createHub();
hub1.setId("HUB-0001");
hub2 = Fixtures.createHub();
hub2.setId("HUB-0002");
EasyMock.expect(mockPopulationCacheMgr.getPopulationByPlaceId(EasyMock.anyObject(UUID.class))).andReturn(Population.NAME_GENERAL).anyTimes();
}
@Test
public void testEmptyPartitionsAssigned() {
EasyMock.expect(mockClock.millis()).andReturn(1000L);
expectStreamPartitionAndReturn(0, ImmutableList.of());
expectStreamPartitionAndReturn(1, ImmutableList.of());
expectStreamPartitionAndReturn(2, ImmutableList.of());
expectStreamPartitionAndReturn(3, ImmutableList.of());
replay();
PartitionChangedEvent event = new PartitionChangedEvent();
event.setAddedPartitions(ImmutableSet.of(0, 1, 2, 3));
event.setRemovedPartitions(ImmutableSet.of());
event.setPartitions(ImmutableSet.of(new DefaultPartition(0), new DefaultPartition(1), new DefaultPartition(2), new DefaultPartition(3)));
registry.onPartitionsChanged(event);
assertEquals(0, registry.getOnlineHubs());
assertNoMessages();
verify();
}
@Test
public void testPartitionAssigned() {
EasyMock.expect(mockClock.millis()).andReturn(1000L);
expectStreamPartitionAndReturn(0, ImmutableList.of(hub1, hub2));
replay();
PartitionChangedEvent event = new PartitionChangedEvent();
event.setAddedPartitions(ImmutableSet.of(0));
event.setRemovedPartitions(ImmutableSet.of());
event.setPartitions(ImmutableSet.of(new DefaultPartition(0)));
registry.onPartitionsChanged(event);
assertEquals(2, registry.getOnlineHubs());
assertNoMessages();
verify();
}
@Test
public void testPartitionAssignedThenRemoved() {
EasyMock.expect(mockClock.millis()).andReturn(1000L).anyTimes();
expectStreamPartitionAndReturn(0, ImmutableList.of(hub1));
expectStreamPartitionAndReturn(1, ImmutableList.of(hub2));
replay();
{
PartitionChangedEvent event = new PartitionChangedEvent();
event.setAddedPartitions(ImmutableSet.of(0, 1));
event.setRemovedPartitions(ImmutableSet.of());
event.setPartitions(ImmutableSet.of(new DefaultPartition(0), new DefaultPartition(1)));
registry.onPartitionsChanged(event);
assertEquals(2, registry.getOnlineHubs());
assertNoMessages();
}
{
PartitionChangedEvent event = new PartitionChangedEvent();
event.setAddedPartitions(ImmutableSet.of());
event.setRemovedPartitions(ImmutableSet.of(0));
event.setPartitions(ImmutableSet.of(new DefaultPartition(1)));
registry.onPartitionsChanged(event);
assertEquals(1, registry.getOnlineHubs());
assertNoMessages();
}
{
PartitionChangedEvent event = new PartitionChangedEvent();
event.setAddedPartitions(ImmutableSet.of());
event.setRemovedPartitions(ImmutableSet.of(1));
event.setPartitions(ImmutableSet.of());
registry.onPartitionsChanged(event);
assertEquals(0, registry.getOnlineHubs());
assertNoMessages();
}
verify();
}
@Test
public void testTimeout() throws Exception {
EasyMock.expect(mockClock.millis()).andReturn(1000L).once();
EasyMock.expect(mockClock.millis()).andReturn(2000L).once(); // not expired
EasyMock.expect(mockClock.millis()).andReturn(1000000L).once(); // expired
expectStreamPartitionAndReturn(0, ImmutableList.of(hub1, hub2));
expectGetHubByIdAndReturn(hub1);
expectDisconnected(hub1.getId());
expectGetHubByIdAndReturn(hub2);
expectDisconnected(hub2.getId());
replay();
PartitionChangedEvent event = new PartitionChangedEvent();
event.setAddedPartitions(ImmutableSet.of(0));
event.setRemovedPartitions(ImmutableSet.of());
event.setPartitions(ImmutableSet.of(new DefaultPartition(0)));
registry.onPartitionsChanged(event);
assertEquals(2, registry.getOnlineHubs());
assertNoMessages();
registry.timeout();
assertEquals(2, registry.getOnlineHubs());
assertNoMessages();
registry.timeout();
assertEquals(0, registry.getOnlineHubs());
// null because we can't verify order
assertDisconnected(null);
assertValueChangeDown(null);
assertDisconnected(null);
assertValueChangeDown(null);
assertNoMessages();
verify();
}
@Test
public void testHubTimesout() throws Exception {
EasyMock.expect(mockClock.millis()).andReturn(1000L).once();
EasyMock.expect(mockClock.millis()).andReturn(1000000L).once(); // heartbeat
EasyMock.expect(mockClock.millis()).andReturn(1000010L).once(); // expired
expectStreamPartitionAndReturn(0, ImmutableList.of(hub1, hub2));
expectGetHubByIdAndReturn(hub2);
expectDisconnected(hub2.getId());
replay();
PartitionChangedEvent event = new PartitionChangedEvent();
event.setAddedPartitions(ImmutableSet.of(0));
event.setRemovedPartitions(ImmutableSet.of());
event.setPartitions(ImmutableSet.of(new DefaultPartition(0)));
registry.onPartitionsChanged(event);
assertEquals(2, registry.getOnlineHubs());
assertNoMessages();
registry.online(hub1.getId(), 0, "hub-bridge-0");
assertEquals(2, registry.getOnlineHubs());
assertNoMessages();
registry.timeout();
assertEquals(1, registry.getOnlineHubs());
assertDisconnected(hub2);
assertValueChangeDown(hub2);
assertNoMessages();
verify();
}
@Test
public void testOnlineAddsHub() throws Exception {
expectConnected(hub1.getId(), HubCapability.STATE_DOWN);
EasyMock.expect(mockClock.millis()).andReturn(1000L).anyTimes();
expectStreamPartitionAndReturn(0, ImmutableList.of());
expectGetHubByIdAndReturn(hub1);
replay();
PartitionChangedEvent event = new PartitionChangedEvent();
event.setAddedPartitions(ImmutableSet.of(0));
event.setRemovedPartitions(ImmutableSet.of());
event.setPartitions(ImmutableSet.of(new DefaultPartition(0)));
registry.onPartitionsChanged(event);
assertEquals(0, registry.getOnlineHubs());
assertNoMessages();
registry.online(hub1.getId(), 1, "hub-bridge-0");
assertEquals(1, registry.getOnlineHubs());
assertValueChangeNormal(hub1);
assertNoMessages();
verify();
}
@Test
public void testOnlineThenTimeout() throws Exception {
expectConnected(hub1.getId());
EasyMock.expect(mockClock.millis()).andReturn(1000L).once(); // partitions assigned
EasyMock.expect(mockClock.millis()).andReturn(2000L).once(); // heartbeat
EasyMock.expect(mockClock.millis()).andReturn(3000L).once(); // timeout 1
EasyMock.expect(mockClock.millis()).andReturn(1000000L).once(); // timeout 2
expectStreamPartitionAndReturn(0, ImmutableList.of());
expectGetHubByIdAndReturn(hub1);
expectDisconnected(hub1.getId());
replay();
PartitionChangedEvent event = new PartitionChangedEvent();
event.setAddedPartitions(ImmutableSet.of(0));
event.setRemovedPartitions(ImmutableSet.of());
event.setPartitions(ImmutableSet.of(new DefaultPartition(0)));
registry.onPartitionsChanged(event);
assertEquals(0, registry.getOnlineHubs());
assertNoMessages();
registry.online(hub1.getId(), 0, "hub-bridge-0");
assertEquals(1, registry.getOnlineHubs());
assertNoMessages();
registry.timeout(); // shouldn't timeout
assertEquals(1, registry.getOnlineHubs());
assertNoMessages();
registry.timeout(); // should timeout
assertEquals(0, registry.getOnlineHubs());
assertDisconnected(hub1);
assertValueChangeDown(hub1);
assertNoMessages();
verify();
}
@Test
public void testOffline() throws Exception {
EasyMock.expect(mockClock.millis()).andReturn(1000L).once(); // partitions assigned
EasyMock.expect(mockClock.millis()).andReturn(1001L).once(); // timeout check
expectStreamPartitionAndReturn(0, ImmutableList.of(hub1));
expectGetHubByIdAndReturn(hub1);
expectDisconnected(hub1.getId());
replay();
PartitionChangedEvent event = new PartitionChangedEvent();
event.setAddedPartitions(ImmutableSet.of(0));
event.setRemovedPartitions(ImmutableSet.of());
event.setPartitions(ImmutableSet.of(new DefaultPartition(0)));
registry.onPartitionsChanged(event);
assertEquals(1, registry.getOnlineHubs());
assertNoMessages();
registry.offline(hub1.getId(), "hub-bridge-0");
assertEquals(0, registry.getOnlineHubs());
assertValueChangeDown(hub1);
assertNoMessages();
verify();
}
/*
* Verify that if one hub bridge erroneously thinks
* the hub is still connected it doesn't override the
* current one.
*/
@Test
public void testSwitchHubBridges() throws Exception {
expectConnected(hub1.getId()); // initial online
EasyMock.expect(mockClock.millis()).andReturn(1000L);
EasyMock.expect(mockClock.millis()).andReturn(2000L);
EasyMock.expect(mockClock.millis()).andReturn(3000L);
EasyMock.expect(mockClock.millis()).andReturn(4000L);
EasyMock.expect(mockClock.millis()).andReturn(5000L);
expectGetHubByIdAndReturn(hub1);
expectDisconnected(hub1.getId());
replay();
// come online on hub-bridge-0
registry.online(hub1.getId(), 0, "hub-bridge-0");
assertEquals(1, registry.getOnlineHubs());
assertNoMessages();
// switch to hub-bridge-1
registry.online(hub1.getId(), 0, "hub-bridge-1");
assertEquals(1, registry.getOnlineHubs());
assertNoMessages();
// hub-bridge-0 sends a heartbeat because it hasn't realized hub1 is offline yet
registry.online(hub1.getId(), 0, "hub-bridge-0");
assertEquals(1, registry.getOnlineHubs());
assertNoMessages();
// hub-bridge-0 sends offline when the connection finally times out
// BUT this shouldn't knock the hub offline because its on hub-bridge-1 now
registry.offline(hub1.getId(), "hub-bridge-0");
assertEquals(1, registry.getOnlineHubs());
assertNoMessages();
// now it should go offline
registry.offline(hub1.getId(), "hub-bridge-1");
assertEquals(0, registry.getOnlineHubs());
assertValueChangeDown(hub1);
assertNoMessages();
}
@Test
public void testTimeoutWhileSwitchingHubBridges() throws Exception {
HubRegistryConfig config = new HubRegistryConfig();
EasyMock.expect(mockClock.millis()).andReturn(1000L);
EasyMock.expect(mockClock.millis()).andReturn(2000L);
EasyMock.expect(mockClock.millis()).andReturn(TimeUnit.MINUTES.toMillis(config.getOfflineTimeoutMin()) + 1500);
expectConnected(hub1.getId());
expectGetHubByIdAndReturn(hub1);
expectDisconnected(hub1.getId());
replay();
// come online on hub-bridge-0
registry.online(hub1.getId(), 0, "hub-bridge-0");
assertEquals(1, registry.getOnlineHubs());
assertNoMessages();
// for whatever reason we don't get an offline from hub-bridge-0
// (most common case would be hub-bridge-0 reboot)
// switch to hub-bridge-1
registry.online(hub1.getId(), 0, "hub-bridge-1");
assertEquals(1, registry.getOnlineHubs());
assertNoMessages();
// hub-bridge-1 sends offline and hub-bridge-0 has timed out
registry.offline(hub1.getId(), "hub-bridge-1");
assertEquals(0, registry.getOnlineHubs());
assertValueChangeDown(hub1);
assertNoMessages();
}
private void expectConnected(String hubId) {
expectConnected(hubId, HubCapability.STATE_NORMAL);
}
private void expectConnected(String hubId, String oldState) {
EasyMock
.expect(mockHubDao.connected(hubId))
.andReturn(
HubCapability.STATE_DOWN.equals(oldState) ?
ImmutableMap.of(HubCapability.ATTR_STATE, HubCapability.STATE_NORMAL, HubConnectionCapability.ATTR_STATE, HubConnectionCapability.STATE_ONLINE, HubConnectionCapability.ATTR_LASTCHANGE, new Date()) :
ImmutableMap.of()
);
}
private void expectDisconnected(String hubId) {
EasyMock
.expect(mockHubDao.disconnected(hubId))
.andReturn(ImmutableMap.of(HubCapability.ATTR_STATE, HubCapability.STATE_DOWN, HubConnectionCapability.ATTR_STATE, HubConnectionCapability.STATE_OFFLINE, HubConnectionCapability.ATTR_LASTCHANGE, new Date()));
}
private void expectStreamPartitionAndReturn(int partitionId, Collection<Hub> result) {
EasyMock.expect(mockHubDao.streamByPartitionId(partitionId)).andReturn(result.stream());
}
private Hub expectGetHubByIdAndReturn(Hub hub) {
Hub value = hub.copy();
EasyMock
.expect(mockHubDao.findById(hub.getId()))
.andReturn(value);
return value;
}
private void assertNoMessages() {
assertNull(platformBus.poll());
}
private void assertDisconnected(@Nullable Hub hub) throws Exception {
PlatformMessage message = platformBus.take();
assertEquals(HubCapability.HubDisconnectedEvent.NAME, message.getMessageType());
assertEquals(Address.broadcastAddress(), message.getDestination());
if(hub != null) {
assertEquals(Address.hubService(hub.getId(), "hub"), message.getSource());
}
else {
assertTrue(message.getSource().isHubAddress());
}
}
private void assertValueChangeDown(@Nullable Hub hub) throws Exception {
PlatformMessage message = platformBus.take();
if(hub != null) {
assertEquals(Address.hubService(hub.getId(), "hub"), message.getSource());
assertEquals(hub.getPlace().toString(), message.getPlaceId());
}
else {
assertTrue(message.getSource().isHubAddress());
assertFalse(StringUtils.isEmpty(message.getPlaceId()));
}
assertEquals(Capability.EVENT_VALUE_CHANGE, message.getMessageType());
assertEquals(Address.broadcastAddress(), message.getDestination());
assertEquals(HubCapability.STATE_DOWN, message.getValue().getAttributes().get(HubCapability.ATTR_STATE));
assertEquals(HubConnectionCapability.STATE_OFFLINE, message.getValue().getAttributes().get(HubConnectionCapability.ATTR_STATE));
}
private void assertValueChangeNormal(@Nullable Hub hub) throws Exception {
PlatformMessage message = platformBus.take();
if(hub != null) {
assertEquals(Address.hubService(hub.getId(), "hub"), message.getSource());
assertEquals(hub.getPlace().toString(), message.getPlaceId());
}
else {
assertTrue(message.getSource().isHubAddress());
assertFalse(StringUtils.isEmpty(message.getPlaceId()));
}
assertEquals(Capability.EVENT_VALUE_CHANGE, message.getMessageType());
assertEquals(Address.broadcastAddress(), message.getDestination());
assertEquals(HubCapability.STATE_NORMAL, message.getValue().getAttributes().get(HubCapability.ATTR_STATE));
assertEquals(HubConnectionCapability.STATE_ONLINE, message.getValue().getAttributes().get(HubConnectionCapability.ATTR_STATE));
}
}
| true |
bdaba5e70fd1dcfbb47fbef618221c9471271c9b | Java | jasonakon/javafx_crypto_app | /src/main/java/org/example/crypto/PgpFileHelper.java | UTF-8 | 11,141 | 2.109375 | 2 | [] | no_license | package org.example.crypto;
import org.bouncycastle.bcpg.ArmoredOutputStream;
import org.bouncycastle.bcpg.HashAlgorithmTags;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.openpgp.*;
import org.bouncycastle.openpgp.operator.PGPContentSignerBuilder;
import org.bouncycastle.openpgp.operator.PublicKeyDataDecryptorFactory;
import org.bouncycastle.openpgp.operator.bc.BcKeyFingerprintCalculator;
import org.bouncycastle.openpgp.operator.bc.BcPGPContentSignerBuilder;
import org.bouncycastle.openpgp.operator.jcajce.JcaPGPContentVerifierBuilderProvider;
import org.bouncycastle.openpgp.operator.jcajce.JcePGPDataEncryptorBuilder;
import org.bouncycastle.openpgp.operator.jcajce.JcePublicKeyDataDecryptorFactoryBuilder;
import org.bouncycastle.openpgp.operator.jcajce.JcePublicKeyKeyEncryptionMethodGenerator;
import org.bouncycastle.util.io.Streams;
import java.io.*;
import java.security.Provider;
import java.security.SecureRandom;
import java.security.Security;
import java.util.Date;
import java.util.Iterator;
import static org.bouncycastle.bcpg.CompressionAlgorithmTags.ZIP;
import static org.bouncycastle.bcpg.SymmetricKeyAlgorithmTags.CAST5;
public class PgpFileHelper {
private static final int BUFFER_SIZE = 1 << 16; // should always be power of 2
private PgpFileHelper() {
throw new IllegalStateException("Utility class");
}
public static void encryptFile(OutputStream out, String fileName, PGPPublicKey encKey, boolean armor,
boolean withIntegrityCheck) throws IOException, PGPException {
Security.addProvider(new BouncyCastleProvider());
if (armor) {
out = new ArmoredOutputStream(out);
}
ByteArrayOutputStream bOut = new ByteArrayOutputStream();
PGPCompressedDataGenerator comData = new PGPCompressedDataGenerator(ZIP);
PGPUtil.writeFileToLiteralData(comData.open(bOut), PGPLiteralData.BINARY, new File(fileName));
comData.close();
JcePGPDataEncryptorBuilder dataEncryptor = new JcePGPDataEncryptorBuilder(CAST5).setWithIntegrityPacket(withIntegrityCheck).setSecureRandom(new SecureRandom()).setProvider("BC");
PGPEncryptedDataGenerator encryptedDataGenerator = new PGPEncryptedDataGenerator(dataEncryptor);
JcePublicKeyKeyEncryptionMethodGenerator methodGenerator = new JcePublicKeyKeyEncryptionMethodGenerator(encKey).setProvider(new BouncyCastleProvider()).setSecureRandom(new SecureRandom());
encryptedDataGenerator.addMethod(methodGenerator);
byte[] bytes = bOut.toByteArray();
try(
OutputStream cOut = encryptedDataGenerator.open(out, new byte[BUFFER_SIZE]);
) {
cOut.write(bytes);
encryptedDataGenerator.close();
}finally{
out.close();
bOut.close();
}
}
public static void writeToFile(byte[] data, String filename){
try(FileOutputStream out = new FileOutputStream(filename)){
out.write(data);
}catch(IOException e){
System.out.println(e.getMessage());
}
}
public static void decryptFile(InputStream in, OutputStream out, InputStream privKey, InputStream pubKey, char[] passwd) throws IOException, PGPException {
Security.addProvider(new BouncyCastleProvider());
in = PGPUtil.getDecoderStream(in);
PGPObjectFactory pgpF = new PGPObjectFactory(in, new BcKeyFingerprintCalculator());
PGPEncryptedDataList enc;
Object o = pgpF.nextObject();
//
// the first object might be a PGP marker packet.
//
if (o instanceof PGPEncryptedDataList) {
enc = (PGPEncryptedDataList) o;
} else {
enc = (PGPEncryptedDataList) pgpF.nextObject();
}
//
// find the secret key
//
Iterator<PGPEncryptedData> it = enc.getEncryptedDataObjects();
PGPPrivateKey sKey = null;
PGPPublicKeyEncryptedData pbe = null;
while (sKey == null && it.hasNext()) {
pbe = (PGPPublicKeyEncryptedData) it.next();
sKey = PgpHelper.findPrivateKey(privKey, pbe.getKeyID(), passwd);
}
if (sKey == null) {
throw new IllegalArgumentException("Secret key for message not found.");
}
PublicKeyDataDecryptorFactory b = new JcePublicKeyDataDecryptorFactoryBuilder().setProvider("BC").setContentProvider("BC").build(sKey);
InputStream clear = pbe.getDataStream(b);
PGPObjectFactory plainFact = new PGPObjectFactory(PGPUtil.getDecoderStream(clear), new BcKeyFingerprintCalculator());
PGPOnePassSignatureList onePassSignatureList = null;
PGPSignatureList signatureList = null;
Object message = plainFact.nextObject();
ByteArrayOutputStream actualOutput = new ByteArrayOutputStream();
while(message!=null) {
if (message instanceof PGPCompressedData) {
PGPCompressedData cData = (PGPCompressedData) message;
plainFact = new PGPObjectFactory(PGPUtil.getDecoderStream(cData.getDataStream()), null);
message = plainFact.nextObject();
}
if (message instanceof PGPLiteralData) {
PGPLiteralData ld = (PGPLiteralData) message;
InputStream unc = ld.getInputStream();
int ch;
while ((ch = unc.read()) >= 0) {
out.write(ch);
}
Streams.pipeAll(((PGPLiteralData) message).getInputStream(), actualOutput);
} else if (message instanceof PGPOnePassSignatureList) {
onePassSignatureList = (PGPOnePassSignatureList) message;
} else if (message instanceof PGPSignatureList) {
signatureList = (PGPSignatureList) message;
} else {
throw new PGPException("Message is not a simple encrypted file - type unknown.");
}
message = plainFact.nextObject();
}
if(onePassSignatureList!=null && signatureList!=null) {
boolean isVerified = verifySignature(onePassSignatureList,pubKey,new ByteArrayOutputStream().toByteArray(),signatureList);
System.out.println("isVerified: " +isVerified);
}
if (pbe.isIntegrityProtected()&&!pbe.verify()) {
throw new PGPException("Message failed integrity check");
}
actualOutput.close();
}
public static boolean verifySignature(PGPOnePassSignatureList onePassSignatureList, InputStream publicKeyIn, byte[] output, PGPSignatureList signatureList)throws IOException, PGPException{
boolean isVerified = false;
for (int i = 0; i < onePassSignatureList.size(); i++) {
PGPOnePassSignature ops = onePassSignatureList.get(0);
PGPPublicKeyRingCollection pgpRing = new PGPPublicKeyRingCollection(PGPUtil.getDecoderStream(publicKeyIn),new BcKeyFingerprintCalculator());
PGPPublicKey publicKey = pgpRing.getPublicKey(ops.getKeyID());
if (publicKey != null) {
ops.init(new JcaPGPContentVerifierBuilderProvider().setProvider("BC"), publicKey);
ops.update(output);
PGPSignature signature = signatureList.get(i);
if (ops.verify(signature)) {
return true;
}
}
}
return isVerified;
}
public static void signEncryptFile(OutputStream out, String fileName, PGPPublicKey publicKey,
PGPSecretKey secretKey, String password, boolean armor, boolean withIntegrityCheck) throws IOException, PGPException{
// Initialize Bouncy Castle security provider
Provider provider = new BouncyCastleProvider();
Security.addProvider(provider);
if (armor) {
out = new ArmoredOutputStream(out);
}
JcePGPDataEncryptorBuilder dataEncryptor = new JcePGPDataEncryptorBuilder(CAST5).setWithIntegrityPacket(withIntegrityCheck).setSecureRandom(new SecureRandom()).setProvider("BC");
PGPEncryptedDataGenerator encryptedDataGenerator = new PGPEncryptedDataGenerator(dataEncryptor);
JcePublicKeyKeyEncryptionMethodGenerator methodGenerator = new JcePublicKeyKeyEncryptionMethodGenerator(publicKey).setProvider(new BouncyCastleProvider()).setSecureRandom(new SecureRandom());
encryptedDataGenerator.addMethod( methodGenerator);
// Initialize compressed data generator
PGPCompressedDataGenerator compressedDataGenerator = new PGPCompressedDataGenerator(ZIP);
try(
OutputStream encryptedOut = encryptedDataGenerator.open(out, new byte[BUFFER_SIZE]);
OutputStream compressedOut = compressedDataGenerator.open(encryptedOut, new byte[BUFFER_SIZE]);
) {
// Initialize signature generator
PGPPrivateKey privateKey = PgpHelper.findPrivateKey(secretKey, password.toCharArray());
PGPContentSignerBuilder signerBuilder = new BcPGPContentSignerBuilder(secretKey.getPublicKey().getAlgorithm(), HashAlgorithmTags.SHA1);
PGPSignatureGenerator signatureGenerator = new PGPSignatureGenerator(signerBuilder);
signatureGenerator.init(PGPSignature.BINARY_DOCUMENT, privateKey);
boolean firstTime = true;
Iterator<String> it = secretKey.getPublicKey().getUserIDs();
while (it.hasNext() && firstTime) {
PGPSignatureSubpacketGenerator spGen = new PGPSignatureSubpacketGenerator();
spGen.setSignerUserID(false, it.next());
signatureGenerator.setHashedSubpackets(spGen.generate());
// Exit the loop after the first iteration
firstTime = false;
}
signatureGenerator.generateOnePassVersion(false).encode(compressedOut);
// Initialize literal data generator
PGPLiteralDataGenerator literalDataGenerator = new PGPLiteralDataGenerator();
try(
OutputStream literalOut = literalDataGenerator.open(compressedOut, PGPLiteralData.BINARY, fileName, new Date(),
new byte[BUFFER_SIZE]);
// Main loop - read the "in" stream, compress, encrypt and write to the "out" stream
FileInputStream in = new FileInputStream(fileName);
) {
byte[] buf = new byte[BUFFER_SIZE];
int len;
while ((len = in.read(buf)) > 0) {
literalOut.write(buf, 0, len);
signatureGenerator.update(buf, 0, len);
}
}
literalDataGenerator.close();
// Generate the signature, compress, encrypt and write to the "out" stream
signatureGenerator.generate().encode(compressedOut);
compressedDataGenerator.close();
encryptedDataGenerator.close();
}finally{
if (armor) {
out.close();
}
}
}
}
| true |
f9a3fdac88c271bc38e747d4722c3557de188e0c | Java | E-System/common-lib | /src/main/java/com/es/lib/common/email/EmailMessageBuilder.java | UTF-8 | 3,745 | 2.015625 | 2 | [
"Apache-2.0"
] | permissive | /*
* Copyright 2016 E-System LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.es.lib.common.email;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
/**
* @author Zuzoev Dmitry - zuzoev.d@ext-system.com
* @since 16.05.16
*/
public class EmailMessageBuilder {
private String backAddress;
private String from;
private String replyTo;
private String destinations;
private String subject;
private String message;
private Map<String, String> headers;
private Collection<EmailAttachment> attachments;
private Map<String, String> extensions;
private String id;
private EmailRootAttachment rootAttachment;
EmailMessageBuilder() {
this.attachments = new ArrayList<>();
this.headers = new HashMap<>();
this.extensions = new HashMap<>();
}
public static EmailMessageBuilder create() {
return new EmailMessageBuilder();
}
public EmailMessageBuilder backAddress(String backAddress) {
this.backAddress = backAddress;
return this;
}
public EmailMessageBuilder from(String from) {
this.from = from;
return this;
}
public EmailMessageBuilder replyTo(String replyTo) {
this.replyTo = replyTo;
return this;
}
public EmailMessageBuilder destinations(String destinations) {
this.destinations = destinations;
return this;
}
public EmailMessageBuilder subject(String subject) {
this.subject = subject;
return this;
}
public EmailMessageBuilder message(String message) {
this.message = message;
return this;
}
public EmailMessageBuilder headers(Map<String, String> headers) {
this.headers = headers;
return this;
}
public EmailMessageBuilder header(String key, String value) {
this.headers.put(key, value);
return this;
}
public EmailMessageBuilder attachments(Collection<EmailAttachment> attachments) {
this.attachments = attachments;
this.rootAttachment = null;
return this;
}
public EmailMessageBuilder attachment(EmailAttachment attachment) {
this.attachments.add(attachment);
this.rootAttachment = null;
return this;
}
public EmailMessageBuilder attachment(EmailRootAttachment attachment) {
this.rootAttachment = attachment;
this.attachments.clear();
return this;
}
public EmailMessageBuilder extensions(Map<String, String> extensions) {
this.extensions = extensions;
return this;
}
public EmailMessageBuilder extension(String key, String value) {
this.extensions.put(key, value);
return this;
}
public EmailMessageBuilder id(String id) {
this.id = id;
return this;
}
public EmailMessage build() {
return new EmailMessage(
backAddress,
from,
replyTo,
destinations,
subject,
message,
headers,
attachments,
extensions,
id,
rootAttachment
);
}
}
| true |
5b1c4124ac395078ab05c97108667779e83c999f | Java | doczir/DistributedRayTracer | /Common/src/com/base/raytracer/math/TransformUtils.java | UTF-8 | 5,024 | 2.90625 | 3 | [
"MIT"
] | permissive | package com.base.raytracer.math;
/**
* @author Róbert Dóczi
* Date: 2014.12.22.
*/
public final class TransformUtils {
private static Matrix4 tempMat = new Matrix4();
private TransformUtils() {
}
public static Matrix4 createTranslation(Vector3 translation) {
Matrix4 result = tempMat.initIdentity();
result.set(3, 0, translation.getX())
.set(3, 1, translation.getY())
.set(3, 2, translation.getZ());
return result;
}
public static Matrix4 createScaling(Vector3 scale) {
Matrix4 result = tempMat.initIdentity();
result.set(0, 0, scale.getX())
.set(1, 1, scale.getY())
.set(2, 2, scale.getZ());
return result;
}
public static Matrix4 createRotation(Vector3 axis, double angle) {
assert axis != Vector3.ZERO;
Matrix4 result = tempMat.initIdentity();
double c = Math.cos(angle);
double s = Math.sin(angle);
Vector3 v = axis.normalize();
result.set(0, 0, v.getX() * v.getX() * (1 - c) + c)
.set(1, 0, v.getX() * v.getY() * (1 - c) - v.getZ() * s)
.set(2, 0, v.getX() * v.getZ() * (1 - c) + v.getY() * s);
result.set(0, 1, v.getY() * v.getX() * (1 - c) + v.getZ() * s)
.set(1, 1, v.getY() * v.getY() * (1 - c) + c)
.set(2, 1, v.getY() * v.getZ() * (1 - c) - v.getX() * s);
result.set(0, 2, v.getX() * v.getZ() * (1 - c) - v.getY() * s)
.set(1, 2, v.getY() * v.getZ() * (1 - c) + v.getX() * s)
.set(2, 2, v.getZ() * v.getZ() * (1 - c) + c);
return result;
}
public static Matrix4 createOrtho2d(double left, double right, double bottom, double top, double zNear, double zFar) {
Matrix4 result = tempMat.initZero();
result.set(0, 0, 2 / (right - left))
.set(1, 1, 2 / (top - bottom))
.set(2, 2, -2 / (zFar - zNear))
.set(3, 0, -(right + left) / (right - left))
.set(3, 1, -(top + bottom) / (top - bottom))
.set(3, 2, -(zFar + zNear) / (zFar - zNear))
.set(3, 3, 1);
return result;
}
public static Matrix4 createFrustum(double left, double right, double bottom, double top, double zNear, double zFar) {
assert zFar > zNear;
Matrix4 result = tempMat.initZero();
result.set(0, 0, (2 * zNear) / (right - left))
.set(1, 1, (2 * zNear) / (top - bottom))
.set(2, 0, (right + left) / (right - left))
.set(2, 1, (top + bottom) / (top - bottom))
.set(2, 2, (zFar + zNear) / (zNear - zFar))
.set(2, 3, -1)
.set(3, 2, (-2 * zFar * zNear) / (zFar - zNear));
return result;
}
public static Matrix4 createPerspective(double fovy, double aspect, double zNear, double zFar) {
assert zFar > zNear;
Matrix4 result = tempMat.initZero();
double tanHalfFovy = Math.tan(Math.toRadians(fovy) / 2);
result.set(0, 0, 1 / (aspect * tanHalfFovy))
.set(1, 1, 1 / tanHalfFovy)
.set(2, 2, (zFar + zNear) / (zNear - zFar))
.set(2, 3, -1)
.set(3, 2, (-2 * zFar * zNear) / (zFar - zNear));
return result;
}
// public static Matrix4 createLookAt(Vector3 eye, Vector3 center, Vector3 up)
// {
// Matrix4 result = tempMat.initIdentity();
//
// final Vector3 f = center.subtract(eye).normalize();
// final Vector3 s = f.cross(up).normalize();
// final Vector3 u = s.cross(f);
//
// result.set(0, 0, s.x)
// .set(1, 0, s.y)
// .set(2, 0, s.z);
//
// result.set(0, 1, u.x)
// .set(1, 1, u.y)
// .set(2, 1, u.z);
//
// result.set(0, 2, -f.x)
// .set(1, 2, -f.y)
// .set(2, 2, -f.z);
//
// result.set(3, 0, -s.dot(eye))
// .set(3, 1, -u.dot(eye))
// .set(3, 2, f.dot(eye));
//
// return result;
// }
public static Matrix4 createRotation(Quaternion q) {
q = q.normalize();
Matrix4 result = tempMat.initIdentity();
double x2 = q.x * q.x;
double y2 = q.y * q.y;
double z2 = q.z * q.z;
double xy = q.x * q.y;
double xz = q.x * q.z;
double yz = q.y * q.z;
double wx = q.w * q.x;
double wy = q.w * q.y;
double wz = q.w * q.z;
result.set(0, 0, 1.0f - 2.0f * (y2 + z2))
.set(0, 1, 2.0f * (xy - wz))
.set(0, 2, 2.0f * (xz + wy));
result.set(1, 0, 2.0f * (xy + wz))
.set(1, 1, 1.0f - 2.0f * (x2 + z2))
.set(1, 2, 2.0f * (yz - wx));
result.set(2, 0, 2.0f * (xz - wy))
.set(2, 1, 2.0f * (yz + wx))
.set(2, 2, 1.0f - 2.0f * (x2 + y2));
return result;
}
}
| true |
f09a9fa828fe2bb7ffd881bbcfd4aca0607662d4 | Java | tsuzcx/qq_apk | /com.tencent.mobileqqi/classes.jar/SecurityAccountServer/MobileContactsDetailInfo.java | UTF-8 | 3,332 | 1.882813 | 2 | [] | no_license | package SecurityAccountServer;
import com.qq.taf.jce.JceInputStream;
import com.qq.taf.jce.JceOutputStream;
import com.qq.taf.jce.JceStruct;
public final class MobileContactsDetailInfo
extends JceStruct
{
public String QQ = "";
public int accountAbi = 0;
public long bindingDate = 0L;
public long isRecommend = 0L;
public String mobileCode = "";
public String mobileNo = "";
public String name = "";
public String nationCode = "";
public String nickname = "";
public long originBinder = 0L;
public String originMobileNo = "";
public short rmdScore = 0;
public MobileContactsDetailInfo() {}
public MobileContactsDetailInfo(String paramString1, String paramString2, String paramString3, long paramLong1, long paramLong2, String paramString4, String paramString5, String paramString6, String paramString7, long paramLong3, int paramInt, short paramShort)
{
this.QQ = paramString1;
this.mobileNo = paramString2;
this.name = paramString3;
this.bindingDate = paramLong1;
this.isRecommend = paramLong2;
this.nationCode = paramString4;
this.mobileCode = paramString5;
this.nickname = paramString6;
this.originMobileNo = paramString7;
this.originBinder = paramLong3;
this.accountAbi = paramInt;
this.rmdScore = paramShort;
}
public void readFrom(JceInputStream paramJceInputStream)
{
this.QQ = paramJceInputStream.readString(0, true);
this.mobileNo = paramJceInputStream.readString(1, true);
this.name = paramJceInputStream.readString(2, true);
this.bindingDate = paramJceInputStream.read(this.bindingDate, 3, false);
this.isRecommend = paramJceInputStream.read(this.isRecommend, 4, false);
this.nationCode = paramJceInputStream.readString(5, false);
this.mobileCode = paramJceInputStream.readString(6, false);
this.nickname = paramJceInputStream.readString(7, false);
this.originMobileNo = paramJceInputStream.readString(8, false);
this.originBinder = paramJceInputStream.read(this.originBinder, 9, false);
this.accountAbi = paramJceInputStream.read(this.accountAbi, 10, false);
this.rmdScore = paramJceInputStream.read(this.rmdScore, 11, false);
}
public void writeTo(JceOutputStream paramJceOutputStream)
{
paramJceOutputStream.write(this.QQ, 0);
paramJceOutputStream.write(this.mobileNo, 1);
paramJceOutputStream.write(this.name, 2);
paramJceOutputStream.write(this.bindingDate, 3);
paramJceOutputStream.write(this.isRecommend, 4);
if (this.nationCode != null) {
paramJceOutputStream.write(this.nationCode, 5);
}
if (this.mobileCode != null) {
paramJceOutputStream.write(this.mobileCode, 6);
}
if (this.nickname != null) {
paramJceOutputStream.write(this.nickname, 7);
}
if (this.originMobileNo != null) {
paramJceOutputStream.write(this.originMobileNo, 8);
}
paramJceOutputStream.write(this.originBinder, 9);
paramJceOutputStream.write(this.accountAbi, 10);
paramJceOutputStream.write(this.rmdScore, 11);
}
}
/* Location: L:\local\mybackup\temp\qq_apk\com.tencent.mobileqqi\classes2.jar
* Qualified Name: SecurityAccountServer.MobileContactsDetailInfo
* JD-Core Version: 0.7.0.1
*/ | true |
4222e4ac001527f0e15dd52d88660e9ed7b1a076 | Java | anton-gabriel/tehnologii-web | /Macao/src/main/java/utils/GameLogger.java | UTF-8 | 1,447 | 3.09375 | 3 | [] | no_license | package utils;
import java.io.File;
import java.io.IOException;
import java.util.logging.FileHandler;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.logging.SimpleFormatter;
/**
* The type My logger.
*/
public class GameLogger {
static private GameLogger singleInstance = null;
private Logger logger;
private FileHandler file;
private SimpleFormatter formatter;
private File directory;
private GameLogger() throws IOException {
logger = Logger.getLogger(Logger.GLOBAL_LOGGER_NAME);
directory = new File(String.format("%s/application.log", System.getProperty("user.dir")));
file = new FileHandler(directory.getAbsolutePath());
formatter = new SimpleFormatter();
file.setFormatter(formatter);
logger.addHandler(file);
}
/**
* Gets instance.
*
* @return the instance
*/
static public GameLogger getInstance() {
if (singleInstance == null) {
try {
singleInstance = new GameLogger();
} catch (IOException e) {
e.printStackTrace();
}
}
return singleInstance;
}
/**
* Log.
*
* @param level the level
* @param message the message
*/
public void log(Level level, String message) {
logger.log(level, message);
}
} | true |
b566a4ad86b6c331b14783ac708e7a9f3425182a | Java | alileohe/jingwei-all | /jingwei-webconsole/src/main/java/com/taobao/jingwei/webconsole/util/DataCacheMaintain.java | GB18030 | 6,313 | 1.898438 | 2 | [] | no_license | package com.taobao.jingwei.webconsole.util;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import com.taobao.jingwei.common.JingWeiConstants;
import com.taobao.jingwei.common.config.ChildChangeListener;
import com.taobao.jingwei.common.config.ConfigManager;
import com.taobao.jingwei.webconsole.biz.ao.JingweiGroupAO;
import com.taobao.jingwei.webconsole.biz.ao.JingweiMonitorAO;
import com.taobao.jingwei.webconsole.biz.ao.JingweiServerAO;
import com.taobao.jingwei.webconsole.biz.ao.JingweiTaskAO;
import com.taobao.jingwei.webconsole.biz.manager.JingweiZkConfigManager;
import com.taobao.jingwei.webconsole.model.JingweiAssembledMonitor;
import com.taobao.jingwei.webconsole.model.JingweiMonitorCriteria;
public class DataCacheMaintain implements JingWeiConstants {
private static Log log = LogFactory.getLog(DataCacheMaintain.class);
private static final String JINGWEI_SERVER = "servers";
@Autowired
private JingweiZkConfigManager jwConfigManager;
@Autowired
private JingweiTaskAO jwTaskAO;
@Autowired
private JingweiServerAO jwServerAO;
@Autowired
private JingweiMonitorAO jwMonitorAO;
@Autowired
private JingweiGroupAO jwGroupAO;
@Autowired
private EnvDataCache envDataCache;
public void init() {
build();
// עwatcherڵ㵽zk
for (String envKey : JingweiZkConfigManager.getKeys()) {
ConfigManager configManager = jwConfigManager.getZkConfigManager(envKey);
configManager.addChildChangesListener(JingWeiConstants.JINGWEI_TASK_ROOT_PATH, new ChildChangeListenerImpl(
JingWeiConstants.JINGWEI_SERVER_TASKS_NAME, envKey));
configManager.addChildChangesListener(JingWeiConstants.JINGWEI_SERVER_ROOT_PATH,
new ChildChangeListenerImpl(JINGWEI_SERVER, envKey));
configManager.addChildChangesListener(JingWeiConstants.JINGWEI_GROUP_ROOT_PATH,
new ChildChangeListenerImpl(JingWeiConstants.JINGWEI_GROUPS_NAME, envKey));
// e.g. /jingwei/monitors/tasks
String path = JINGWEI_MONITOR_ROOT_PATH + ZK_PATH_SEP + JINGWEI_MONITOR_TASKS_NAME;
configManager.addChildChangesListener(path, new ChildChangeListenerImpl(
JingWeiConstants.JINGWEI_MONITOR_MONITORS_NODE_NAME, envKey));
}
}
public void build() {
log.info("init datacache");
for (String envKey : JingweiZkConfigManager.getKeys()) {
// taskList
List<String> taskChildList = jwConfigManager.getChildList(envKey, JingWeiConstants.JINGWEI_TASK_ROOT_PATH);
envDataCache.getZkPathCache(envKey).put(DataCacheType.JingweiAssembledTask.toString(), taskChildList);
// server
List<String> serverChildList = jwConfigManager.getChildList(envKey,
JingWeiConstants.JINGWEI_SERVER_ROOT_PATH);
envDataCache.getZkPathCache(envKey).put(DataCacheType.JingweiAssembledServer.toString(), serverChildList);
// monitor
JingweiMonitorCriteria monitorCriteria = new JingweiMonitorCriteria();
List<JingweiAssembledMonitor> monitors = jwMonitorAO.getMonitors(monitorCriteria, envKey);
List<String> monitorChildList = new ArrayList<String>();
for (JingweiAssembledMonitor monitor : monitors) {
monitorChildList.add(monitor.getName());
}
envDataCache.getZkPathCache(envKey).put(DataCacheType.JingweiAssembledMonitor.toString(), monitorChildList);
// group
ConfigManager configManager = jwConfigManager.getZkConfigManager(envKey);
if (!configManager.exists(JINGWEI_GROUP_ROOT_PATH)) {
try {
configManager.publishData(JINGWEI_GROUP_ROOT_PATH, null, true);
} catch (Exception e) {
e.printStackTrace();
log.error("create " + JINGWEI_GROUP_ROOT_PATH + " erroe!" + e);
}
}
List<String> groupChildList = jwConfigManager
.getChildList(envKey, JingWeiConstants.JINGWEI_GROUP_ROOT_PATH);
envDataCache.getZkPathCache(envKey).put(DataCacheType.JingweiAssembledGroup.toString(), groupChildList);
}
log.info("datacache inited");
}
class ChildChangeListenerImpl extends ChildChangeListener {
private String nodeName;
private String envKey;
public ChildChangeListenerImpl(String nodeName, String envKey) {
this.nodeName = nodeName;
this.envKey = envKey;
}
//»
@Override
public void handleChild(String parentPath, List<String> currentChilds) {
if (JingWeiConstants.JINGWEI_SERVER_TASKS_NAME.equals(nodeName)) {
envDataCache.getZkPathCache(envKey).put(DataCacheType.JingweiAssembledTask.toString(), currentChilds);
} else if (JINGWEI_SERVER.equals(nodeName)) {
envDataCache.getZkPathCache(envKey).put(DataCacheType.JingweiAssembledServer.toString(), currentChilds);
} else if (JingWeiConstants.JINGWEI_GROUPS_NAME.equals(nodeName)) {
envDataCache.getZkPathCache(envKey).put(DataCacheType.JingweiAssembledGroup.toString(), currentChilds);
} else if (JingWeiConstants.JINGWEI_MONITOR_MONITORS_NODE_NAME.equals(nodeName)) {
List<JingweiAssembledMonitor> list = jwMonitorAO.getMonitors(new JingweiMonitorCriteria(), envKey);
List<String> tasks = new ArrayList<String>(list.size());
for (JingweiAssembledMonitor t : list) {
tasks.add(t.getName());
}
envDataCache.getZkPathCache(envKey).put(DataCacheType.JingweiAssembledMonitor.toString(), tasks);
}
}
}
public JingweiZkConfigManager getJwConfigManager() {
return jwConfigManager;
}
public void setJwConfigManager(JingweiZkConfigManager jwConfigManager) {
this.jwConfigManager = jwConfigManager;
}
public JingweiTaskAO getJwTaskAO() {
return jwTaskAO;
}
public void setJwTaskAO(JingweiTaskAO jwTaskAO) {
this.jwTaskAO = jwTaskAO;
}
public JingweiServerAO getJwServerAO() {
return jwServerAO;
}
public void setJwServerAO(JingweiServerAO jwServerAO) {
this.jwServerAO = jwServerAO;
}
public JingweiMonitorAO getJwMonitorAO() {
return jwMonitorAO;
}
public void setJwMonitorAO(JingweiMonitorAO jwMonitorAO) {
this.jwMonitorAO = jwMonitorAO;
}
public JingweiGroupAO getJwGroupAO() {
return jwGroupAO;
}
public void setJwGroupAO(JingweiGroupAO jwGroupAO) {
this.jwGroupAO = jwGroupAO;
}
public EnvDataCache getEnvDataCache() {
return envDataCache;
}
public void setEnvDataCache(EnvDataCache envDataCache) {
this.envDataCache = envDataCache;
}
}
| true |
97c76c88f5c19dbd266bf8f36a463c720b258066 | Java | sunhaipeng1997/npc_platform | /server/src/main/java/com/cdkhd/npc/api/SystemSettingApi.java | UTF-8 | 1,510 | 2.21875 | 2 | [] | no_license | package com.cdkhd.npc.api;
import com.cdkhd.npc.annotation.CurrentUser;
import com.cdkhd.npc.component.UserDetailsImpl;
import com.cdkhd.npc.entity.dto.LevelDto;
import com.cdkhd.npc.enums.LevelEnum;
import com.cdkhd.npc.service.SystemSettingService;
import com.cdkhd.npc.vo.RespBody;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping("/api/mobile/systemSetting")
public class SystemSettingApi {
private SystemSettingService systemSettingService;
@Autowired
public SystemSettingApi(SystemSettingService systemSettingService) {
this.systemSettingService = systemSettingService;
}
/**
* 获取系统配置
* @param userDetails
* @return
*/
@GetMapping("/getSystemSetting")
public ResponseEntity getSystemSetting(@CurrentUser UserDetailsImpl userDetails, LevelDto levelDto) {
String uid = "";
if (levelDto.getLevel().equals(LevelEnum.TOWN.getValue())){
uid = userDetails.getTown().getUid();
}else if (levelDto.getLevel().equals(LevelEnum.AREA.getValue())){
uid = userDetails.getArea().getUid();
}
RespBody body = systemSettingService.getSystemSettings(levelDto.getLevel(),uid);
return ResponseEntity.ok(body);
}
}
| true |
d8f699231b257618886d01481ee8d84a5f84172d | Java | aseparovic2/ChatApp-backend | /src/main/java/com/example/chat/task/service/ProjectServiceImpl.java | UTF-8 | 793 | 2.09375 | 2 | [] | no_license | package com.example.chat.task.service;
import com.example.chat.task.model.Project;
import com.example.chat.task.model.User;
import com.example.chat.task.repository.ProjectRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class ProjectServiceImpl implements ProjectService{
@Autowired
ProjectRepository projectRepository;
@Override
public List<Project> findAll(){
return projectRepository.findAll();
};
@Override
public List<Project> findByName(Project project){
return projectRepository.findByName(project);
}
@Override
public void saveOrUpdateProject(Project project){
projectRepository.save(project);
};
}
| true |
de46e47850209a29ed981633e6ebd327022651df | Java | dramane/ecolexpertEjb | /src/main/java/com/mycompany/ecolexpert/ejb/ViewFiliereEquipeFormationFacadeLocal.java | UTF-8 | 932 | 1.742188 | 2 | [] | no_license | /*
* 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.mycompany.ecolexpert.ejb;
import com.mycompany.ecolexpert.jpa.ViewFiliereEquipeFormation;
import java.util.List;
import javax.ejb.Local;
/**
*
* @author HP
*/
@Local
public interface ViewFiliereEquipeFormationFacadeLocal {
void create(ViewFiliereEquipeFormation viewFiliereEquipeFormation);
void edit(ViewFiliereEquipeFormation viewFiliereEquipeFormation);
void remove(ViewFiliereEquipeFormation viewFiliereEquipeFormation);
ViewFiliereEquipeFormation find(Object id);
List<ViewFiliereEquipeFormation> findAll();
List<ViewFiliereEquipeFormation> findRange(int[] range);
int count();
ViewFiliereEquipeFormation findByCodeFiliere(Object vCodeFiliere);
}
| true |
8a6ed27d7e619e5ea6074c793bbb771df79d7dea | Java | 857831494/gproject | /gproject-gate/src/main/java/com/gproject/gate/service/event/ThreadPoolService.java | UTF-8 | 432 | 2.015625 | 2 | [] | no_license | package com.gproject.gate.service.event;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.springframework.stereotype.Service;
@Service
public class ThreadPoolService {
final static int MAX_THREAD_NUM = 4;
private ExecutorService executorService = Executors.newFixedThreadPool(MAX_THREAD_NUM);
public ExecutorService getExecutorService() {
return executorService;
}
}
| true |
59147c142842257359025856650e71f0d916d697 | Java | reachkrishnaraj/logline | /log/src/main/java/com/vijayrc/supportguy/processor/Processor.java | UTF-8 | 214 | 1.804688 | 2 | [] | no_license | package com.vijayrc.supportguy.processor;
import com.vijayrc.supportguy.domain.Logs;
import java.text.ParseException;
public interface Processor {
void process(Logs linePayload) throws Exception;
}
| true |
82a9873b58f93beb5f90ec23be096e1db4c31b51 | Java | TeAmigo/pts | /ptscharts/src/main/java/ptscharts/indicators/Indicator.java | UTF-8 | 6,413 | 2.046875 | 2 | [] | no_license | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package ptscharts.indicators;
import com.tictactec.ta.lib.Core;
import com.tictactec.ta.lib.MAType;
import com.tictactec.ta.lib.MInteger;
import com.tictactec.ta.lib.RetCode;
import java.util.EnumSet;
/**
*
* @author rickcharon
*/
public class Indicator {
private Core lib;
private int startIdx;
private int endIdx;
private double[] inDouble = null;
private double[] inOpen = null;
private double[] inHigh = null;
private double[] inLow = null;
private double[] inClose = null;
private double[] inVolume = null;
private int optInTimePeriod;
private int optInFastPeriod;
private int optInSlowPeriod;
private MInteger outBegIdx = new MInteger();
private MInteger outNbElement = new MInteger();
double[] output = null;
private int lookback;
private RetCode retCode;
IndicatorGroup myGroup = null;
String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public IndicatorGroup getMyGroup() {
return myGroup;
}
public void setMyGroup(IndicatorGroup myGroup) {
this.myGroup = myGroup;
}
public MInteger getOutBegIdx() {
return outBegIdx;
}
public MInteger getOutNbElement() {
return outNbElement;
}
public int getEndIdx() {
return endIdx;
}
public void setEndIdx(int endIdx) {
this.endIdx = endIdx;
}
public double[] getInOpen() {
return inOpen;
}
public void setInOpen(double[] inOpen) {
this.inOpen = inOpen;
}
public double[] getInClose() {
return inClose;
}
public void setInClose(double[] inClose) {
this.inClose = inClose;
}
public void appendToInClose(double[] newVals) {
}
public double[] getInDouble() {
return inDouble;
}
public void setInDouble(double[] inDouble) {
this.inDouble = inDouble;
}
public double[] getInHigh() {
return inHigh;
}
public void setInHigh(double[] inHigh) {
this.inHigh = inHigh;
}
public double[] getInLow() {
return inLow;
}
public void setInLow(double[] inLow) {
this.inLow = inLow;
}
public double[] getInVolume() {
return inVolume;
}
public void setInVolume(double[] inVolume) {
this.inVolume = inVolume;
}
public int getLookback() {
return lookback;
}
public void setLookback(int lookback) {
this.lookback = lookback;
}
public int getOptInTimePeriod() {
return optInTimePeriod;
}
public void setOptInTimePeriod(int period) {
this.optInTimePeriod = period;
}
public int getOptInFastPeriod() {
return optInFastPeriod;
}
public void setOptInFastPeriod(int optInFastPeriod) {
this.optInFastPeriod = optInFastPeriod;
}
public int getOptInSlowPeriod() {
return optInSlowPeriod;
}
public void setOptInSlowPeriod(int optInSlowPeriod) {
this.optInSlowPeriod = optInSlowPeriod;
}
public int getStartIdx() {
return startIdx;
}
public void setStartIdx(int startIdx) {
this.startIdx = startIdx;
}
public double[] getOutput() {
return output;
}
public void setOutput(double[] output) {
this.output = output;
}
public Indicator() {
lib = new Core();
//output = new double[inClose.length];
outBegIdx = new MInteger();
outNbElement = new MInteger();
EnumSet es;
}
public String runIndicator(IndicatorType id) {
switch (id) {
case AD:
retCode = lib.ad(startIdx, endIdx, inHigh, inLow, inClose, inVolume, outBegIdx, outNbElement, output);
break;
case ADOSC:
retCode = lib.adOsc(startIdx, endIdx, inHigh, inLow, inClose, inVolume,
optInFastPeriod, optInSlowPeriod, outBegIdx, outNbElement, output);
break;
case BBANDS:
retCode = lib.bbands(startIdx, endIdx, inOpen, //Should be the avg of hi, lo, close
optInTimePeriod, // usually 20
optInTimePeriod, //optInNbDevUp deviations for upper bands?
optInTimePeriod, // optInNbDevDn deviations for lower bands?
MAType.Tema, // Moving average type
outBegIdx, outNbElement,
output, //outRealUpperBand
output, //outRealMiddleBand
output); //outRealLowerBand
case CCI:
retCode = lib.cci(startIdx, endIdx, inHigh, inLow, inClose, optInTimePeriod, outBegIdx, outNbElement, output);
break;
case SMA:
retCode = lib.sma(startIdx, endIdx, inClose, optInTimePeriod, outBegIdx, outNbElement, output);
break;
case DX:
retCode = lib.dx(startIdx, endIdx, inHigh, inLow, inClose, optInTimePeriod, outBegIdx, outNbElement, output);
break;
case ADX:
retCode = lib.adx(startIdx, endIdx, inHigh, inLow, inClose, optInTimePeriod, outBegIdx, outNbElement, output);
break;
case MINUSDI:
retCode = lib.minusDI(startIdx, endIdx, inHigh, inLow, inClose, optInTimePeriod, outBegIdx, outNbElement, output);
break;
case PLUSDI:
retCode = lib.plusDI(startIdx, endIdx, inHigh, inLow, inClose, optInTimePeriod, outBegIdx, outNbElement, output);
break;
}
return retCode.toString();
}
// 2/15/11 1:13 PM Currently only implemented in ChartIndicator,
public void intialRun() {
}
// 2/15/11 3:26 PM Currently only implemented in ChartIndicator,
public void jumpRun(int bars) {
}
public static void main(String args[]) {
Indicator ind = new Indicator();
double[] closePrice = new double[100];
for (int i = 0; i < closePrice.length; i++) {
closePrice[i] = (double) i;
}
ind.setInClose(closePrice);
ind.setOutput(new double[ind.getInClose().length]);
ind.setStartIdx(0);
ind.setEndIdx(ind.getInClose().length - 1);
ind.setOptInTimePeriod(30);
String retStr = ind.runIndicator(IndicatorType.SMA);
System.out.println("Return: " + retStr);
for (int i = 0; i < ind.getOutNbElement().value; i++) {
StringBuilder line = new StringBuilder();
line.append("Period #");
line.append(i + ind.outBegIdx.value);
line.append(" close= ");
line.append(closePrice[i + ind.getOutBegIdx().value]);
line.append(" mov avg= ");
line.append(ind.getOutput()[i]);
System.out.println(line.toString());
}
}
}
| true |
566db43dfb25143180a4358c4117eb1b059a2728 | Java | zhaowenfeng001/chezhihu | /src/main/java/com/ksc/kdts/taskmonitor/controller/DepartmentController.java | UTF-8 | 4,990 | 2.484375 | 2 | [] | no_license | package com.ksc.kdts.taskmonitor.controller;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.ksc.kdts.taskmonitor.model.*;
import com.ksc.kdts.taskmonitor.service.DepartmentService;
import org.apache.commons.lang3.time.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.text.ParseException;
import java.util.Date;
import java.util.List;
/**
* <p>
* 菜单权限表 前端控制器
* </p>
*
* @author Richard
* @since 2019-11-18
*/
@RestController
@RequestMapping("/department")
public class DepartmentController extends BaseController {
private static final Logger logger = LoggerFactory.getLogger(DepartmentController.class);
@Autowired
private DepartmentService departmentService;
/**
* 根据ID查询
* @param id
* @return
*/
@RequestMapping(value = "get")
public Response get(@RequestParam(value="id") Long id) {
Response response = new Response();
DepartmentDO departmentDO = departmentService.selectById(id);
response.setData(departmentDO);
return response.success();
}
/**
* 根据ID删除
* @param id
* @return
*/
@RequestMapping(value = "delete")
public Response delete(@RequestParam(value="id") Long id){
Response response = new Response();
DepartmentDO menu = departmentService.selectById(id);
if(menu == null){
return response.fail("菜单不存在");
}
// DepartmentQuery departmentQuery = new DepartmentQuery();
// departmentQuery.setPid(id);
// if(menu.getPid() == 0 && departmentService.count(departmentQuery) > 0){
// return response.fail("该菜单有子菜单,不能删除");
// }
SysRoleMenuQuery query = new SysRoleMenuQuery();
query.setMenuId(id);
departmentService.deleteById(id);
return response.success();
}
/**
* 添加
* @param department
* @return
*/
@RequestMapping(value = "insert")
public Response insert(Department department){
Response response = new Response();
DepartmentQuery departmentQuery = new DepartmentQuery();
departmentQuery.setDepartmentName(department.getDepartmentName());
List<DepartmentDO> departmentDOS = departmentService.searchByQuery(departmentQuery);
if(CollectionUtils.isNotEmpty(departmentDOS)){
return response.fail("部门名称重复,请检查");
}
department.setCreateTime(new Date());
try {
department.setEntryTime(DateUtils.parseDate(department.getEntryTimeStr(),"YYYY-MM-dd HH:mm:ss"));
} catch (ParseException e) {
e.printStackTrace();
}
departmentService.insert(department);
return response.success();
}
/**
* 修改
* @param department
* @return
*/
@RequestMapping(value = "update")
public Response update(@RequestBody Department department){
Response response = new Response();
// if(StringUtils.isEmpty(department.getName())){
// return response.fail("菜单名字不能为空");
// }
// DepartmentDO sourceMenu = departmentService.selectById(department.getId());
// if(sourceMenu == null){
// return response.fail("菜单不存在");
// }
// //判断是否有重名
// if(!sourceMenu.getName().equals(department.getName())){
// DepartmentQuery query = new DepartmentQuery();
// query.setName(department.getName());
// List<DepartmentDO> list = departmentService.searchByQuery(query);
// if(!CollectionUtils.isEmpty(list)){
// return response.fail("菜单名字已经存在");
// }
// }
departmentService.update(department);
return response.success();
}
/**
* 分页查询
* @param current 查询页
* @param size 每页显示条数
* @param query 查询参数
* @return
*/
@RequestMapping(value="page")
public Response page(Integer current, Integer size, DepartmentQuery query){
Response response = new Response();
Page<DepartmentDO> page = departmentService.page(new QueryPage(current,size),query);
response.setData(page);
return response.success();
}
/**
* 分页查询
* @param query 查询参数
* @return
*/
@RequestMapping("/list")
public Response list(DepartmentQuery query){
Response response = new Response();
List<DepartmentDO> list = departmentService.searchByQuery(query);
response.setData(list);
return response.success();
}
}
| true |
7b2f8bc1697ea5496d8d85cbebddc9c0f866f7ba | Java | jasencio/RentMap | /MainCore/src/com/consejo/cdi/general/impl/TestCierreSession.java | UTF-8 | 896 | 1.757813 | 2 | [] | no_license | package com.consejo.cdi.general.impl;
import javax.enterprise.context.RequestScoped;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.inject.Inject;
import javax.servlet.http.HttpSession;
import com.consejo.cdi.general.anotaciones.ITestCierreSession;
import com.consejo.cdi.general.interfaz.ICierreSession;
import com.dragonfly.bo.impl.ServicioAutenticacion;
@ITestCierreSession
@RequestScoped
public class TestCierreSession implements ICierreSession
{
@Inject
private ServicioAutenticacion servicioAutenticador;
public void cerrarSession() {
FacesContext context = FacesContext.getCurrentInstance();
ExternalContext externalContext = context.getExternalContext();
Object session = externalContext.getSession(false);
HttpSession httpSession = (HttpSession) session;
httpSession.invalidate();
}
}
| true |
d6b6c11d61d0828266ba102defb7d4be90bf08be | Java | G43riko/Bombercraft-2.0 | /src/main/java/org/bombercraft2/game/bots/BotPrototype.java | UTF-8 | 896 | 2.796875 | 3 | [] | no_license | package org.bombercraft2.game.bots;
import org.bombercraft2.core.Texts;
import org.json.JSONException;
import org.json.JSONObject;
public class BotPrototype {
private int speed;
private int maxHealth;
private int damage;
private BotFactory.Types type;
public BotPrototype(JSONObject data) {
try {
this.speed = data.getInt(Texts.SPEED);
this.damage = data.getInt(Texts.DAMAGE);
this.maxHealth = data.getInt(Texts.HEALTH);
this.type = BotFactory.Types.valueOf(data.getString(Texts.TYPE));
}
catch (JSONException e) {
e.printStackTrace();
}
}
public int getSpeed() {return speed;}
public int getMaxHealth() {return maxHealth;}
public int getDamage() {return damage;}
public BotFactory.Types getType() {return type;}
}
| true |
fa069626dc574226bdeb6c0963f173c92b2db29c | Java | ttthanhDC/BIDV-Tool | /BE/BIDVTool/src/main/java/com/ngs/controller/ApplicationController.java | UTF-8 | 6,294 | 2.234375 | 2 | [] | no_license | package com.ngs.controller;
import com.ngs.entity.Application;
import com.ngs.request.CreateApplicationRequest;
import com.ngs.request.UpdateApplicationRequest;
import com.ngs.response.CreateApplicationResponse;
import com.ngs.response.GetListApplicationResponse;
import com.ngs.response.UpdateApplicationResponse;
import com.ngs.service.ApplicationService;
import com.ngs.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.SerializationUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
@RestController
@RequestMapping("/application")
@Slf4j
@CrossOrigin("*")
public class ApplicationController {
@Autowired
ApplicationService applicationService;
@GetMapping
public ResponseEntity<GetListApplicationResponse> findAll() {
GetListApplicationResponse response = new GetListApplicationResponse();
try {
List<Application> applicationList = applicationService.getAll();
response.setApplications(applicationList);
HttpHeaders responseHeader = new HttpHeaders();
responseHeader.add("resultCode", "0");
responseHeader.add("resultDesc", "success");
responseHeader.add("responseTime", LocalDateTime.now().format(DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm:ss")));
return ResponseEntity.ok().headers(responseHeader).body(response);
} catch (Throwable e) {
e.printStackTrace();
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
}
}
@GetMapping("/{id}")
public ResponseEntity<Application> findById(@PathVariable Integer id) {
try {
Application application = applicationService.getById(id);
if (application != null) {
log.info(String.format("[%s] response: %s", "findById", StringUtil.toJsonString(application)));
return ResponseEntity.ok(application);
}
return ResponseEntity.badRequest().body(null);
} catch (Exception e) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
}
}
@PostMapping
public ResponseEntity<CreateApplicationResponse> insert(@RequestBody CreateApplicationRequest request) {
try {
// TODO validate request
Application application = Application.builder()
.bidvAppCode(request.getBidvAppCode())
.applicationName(request.getApplicationName())
.abbreviation(request.getAbbreviation())
.integrationAppCode(request.getIntegrationAppCode())
.inScope(request.isInScope())
.build();
applicationService.save(application);
CreateApplicationResponse response = CreateApplicationResponse.builder()
.bidvAppCode(application.getBidvAppCode())
.applicationName(application.getApplicationName())
.abbreviation(application.getAbbreviation())
.integrationAppCode(application.getIntegrationAppCode())
.build();
// TODO add to base
HttpHeaders responseHeader = new HttpHeaders();
responseHeader.add("resultCode", "0");
responseHeader.add("resultDesc", "success");
responseHeader.add("responseTime", LocalDateTime.now().format(DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm:ss")));
return ResponseEntity.ok().headers(responseHeader).body(response);
} catch (Exception e) {
e.printStackTrace();
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
}
}
@PutMapping("/{id}")
public ResponseEntity<UpdateApplicationResponse> update(@RequestBody UpdateApplicationRequest request, @PathVariable Integer id) {
UpdateApplicationResponse response = UpdateApplicationResponse.builder().build();
try {
// TODO validate request
Application application = applicationService.getById(id);
Application previousApp = SerializationUtils.clone(application);
if (application == null) {
return ResponseEntity.badRequest().body(null);
}
application.setApplicationName(request.getApplicationName());
application.setAbbreviation(request.getAbbreviation());
application.setBidvAppCode(request.getBidvAppCode());
application.setIntegrationAppCode(request.getIntegrationAppCode());
application.setInScope(request.isInScope());
applicationService.save(application);
response.setPreviousApplication(previousApp);
response.setUpdatedApplication(application);
// TODO add to base
HttpHeaders responseHeader = new HttpHeaders();
responseHeader.add("resultCode", "0");
responseHeader.add("resultDesc", "success");
responseHeader.add("responseTime", LocalDateTime.now().format(DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm:ss")));
log.info("[update] response: " + StringUtil.toJsonString(response));
return ResponseEntity.ok().headers(responseHeader).body(response);
} catch (Exception e) {
e.printStackTrace();
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
}
}
@DeleteMapping("/{id}")
public ResponseEntity<String> delete(@PathVariable Integer id) {
try {
Application application = applicationService.getById(id);
if (application != null) {
applicationService.delete(application);
}
return ResponseEntity.ok().body(null);
} catch (Exception e) {
e.printStackTrace();
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
}
}
}
| true |
de3333d7366fa3bd533476d366f234e385bd35c6 | Java | JarekDziuraDev/ToDoBook | /src/main/java/com/example/todobook/repository/SqlTaskGroupRepository.java | UTF-8 | 494 | 2.046875 | 2 | [
"Unlicense"
] | permissive | package com.example.todobook.repository;
import com.example.todobook.model.TaskGroup;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface SqlTaskGroupRepository extends TaskGroupRepository, JpaRepository<TaskGroup, Integer> {
@Override
@Query("from TaskGroup gr join fetch gr.tasks")
List<TaskGroup> findAll();
}
| true |
384610f26f609900d79d988e814b24bbeef11bee | Java | panhabot/webappSE3 | /filterCurrency/src/ExchangeServ.java | UTF-8 | 1,053 | 2.71875 | 3 | [] | no_license | import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
@WebServlet(name = "ExchangeServ")
public class ExchangeServ extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String curType = request.getParameter("curType");
float usd = Float.parseFloat(request.getParameter("usd"));
PrintWriter out = response.getWriter();
if (curType.equals("INR"))
out.println(usd * 71.22 + " Rupee");
else if (curType.equals("KHR"))
out.println(usd * 4000 + " riel");
else if (curType.equals("YUAN"))
out.println(usd * 7 + " Chinese Yuan");
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}
| true |
69b26a9c856ce4f7aefd3c56fbd2f5935d9901ae | Java | hdryx/gestion-materiel-informatique | /forms/Panel_peripherique.java | ISO-8859-1 | 59,454 | 1.921875 | 2 | [] | no_license | /*
* Panel_peripherique.java
*
* Created on __DATE__, __TIME__
*/
package forms;
import gestion_materiel.*;
import javax.swing.event.ListSelectionListener;
import javax.swing.event.TableModelEvent;
import javax.swing.table.*;
import java.util.*;
import java.awt.event.ActionListener;
import java.sql.*;
import javax.swing.event.TableModelListener;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPopupMenu;
import javax.swing.JFrame;
import javax.swing.JTextField;
import java.awt.event.ItemListener;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.text.*;
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Window;
import javax.swing.SwingUtilities;
import org.jdesktop.swingx.*;
import java.awt.event.ActionEvent;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.plaf.metal.MetalLookAndFeel;
import javax.swing.table.DefaultTableModel;
import javax.swing.*;
import java.awt.*;
import org.jdesktop.swingx.autocomplete.Configurator;
import org.jdesktop.swingx.border.DropShadowBorder;
import org.jdesktop.swingx.calendar.*;
import org.jdesktop.swingx.decorator.*;
import org.jdesktop.swingx.event.ProgressEvent;
import org.jdesktop.swingx.tips.*;
import org.jdesktop.swingx.treetable.*;
import org.jdesktop.swingx.tips.TipOfTheDayModel.*;
import org.jdesktop.swingx.decorator.Highlighter;
/**
*
* @author __USER__
*/
public class Panel_peripherique extends javax.swing.JPanel{
int id_pc=-1 ;
Vector v = new Vector();
JXTable jTable1;
JXTable jTable2;
Object [][] test =null;
Object [][] data2=null;
String [] titre = {"Propriet","Valeur"};
String [] titre2 = {"Id","Type","Nom","Slot","Num Srie","Pilote","Id_pc","Id_lieu"};
ListIterator lst;
ModelJTable mm;
Peripherique p1;
boolean a=true,ajout=false,modif=false,b=false,var=false;
MainForm m;
Type_lieu t;
private DefaultTableModel model;
private DefaultTableModel model2;
JTextField txtIdLieu = new JTextField(" ");
JTextField txtType = new JTextField(" ");
JTextField txtIdSlot = new JTextField(" ");
JTextField txtIdPc = new JTextField(" ");
JComboBox cmbIdLieu = new JComboBox(titre);
JComboBox cmbType = new JComboBox(titre);
JComboBox cmbIdSlot = new JComboBox(titre);
JComboBox cmbIdPc = new JComboBox(titre);
String s1 = "card1_text";
String s2 = "card1_box";
String s3 = "card2_text";
String s4 = "card2_box";
String s5 = "card3_text";
String s6 = "card3_box";
String s7 = "card4_text";
String s8 = "card4_box";
/** Creates new form Panel_peripherique */
public Panel_peripherique(MainForm m, int id) {
this.id_pc=id;
this.m = m;
jTable2 = new JXTable();
jTable2.setHighlighters(
new HighlighterPipeline(new Highlighter[] {AlternateRowHighlighter.beige}
));
jTable2.setRolloverEnabled(true);
jTable2.getHighlighters().addHighlighter(new RolloverHighlighter(Color.GRAY, Color.WHITE ));
jTable2.setColumnControlVisible(true);
jTable1 = new JXTable();
jTable1.setHighlighters(
new HighlighterPipeline(new Highlighter[] {AlternateRowHighlighter.quickSilver}
));
jTable1.setRolloverEnabled(true);
jTable1.getHighlighters().addHighlighter(new RolloverHighlighter(Color.GRAY, Color.WHITE ));
jTable1.setColumnControlVisible(true);
initComponents();
checkbox1.setEnabled(false);
model = new DefaultTableModel();
model2 = new DefaultTableModel();
model.addColumn("Id");
model.addColumn("Type");
model.addColumn("Nom");
model.addColumn("Slot");
model.addColumn("Num Srie");
model.addColumn("Pilote");
model.addColumn("Id_pc");
model.addColumn("Id_lieu");
model2.addColumn("Proptit");
model2.addColumn("Valeur");
txtIdLieu.setEditable(false);
txtType.setEditable(false);
txtIdSlot.setEditable(false);
txtIdPc.setEditable(false);
txtTypeLieu.setEditable(false);
txtLieu.setEditable(false);
cmbIdLieu.removeAllItems();
cmbIdLieu.addItem("Choisir un Lieu");
cmbIdLieu.addItem("");
cmbIdLieu.setSelectedItem("");
cmbIdPc.removeAllItems();
cmbIdPc.addItem("Choisir un PC");
cmbIdPc.addItem("");
cmbIdPc.setSelectedItem("");
cmbIdLieu.addItemListener(new java.awt.event.ItemListener() {
public void itemStateChanged(java.awt.event.ItemEvent evt) {
cmbIdLieuItemStateChanged(evt);
}
});
cmbIdPc.addItemListener(new java.awt.event.ItemListener() {
public void itemStateChanged(java.awt.event.ItemEvent evt) {
cmbIdPcItemStateChanged(evt);
}
});
jPanel7.setLayout(new CardLayout());
cardType.setLayout(new CardLayout());
cardSlot.setLayout(new CardLayout());
cardIdPc.setLayout(new CardLayout());
jPanel7.add(s1,txtIdLieu);
jPanel7.add(s2,cmbIdLieu);
cardType.add(s3,txtType);
cardType.add(s4,cmbType);
cardSlot.add(s5,txtIdSlot);
cardSlot.add(s6,cmbIdSlot);
cardIdPc.add(s7,txtIdPc);
cardIdPc.add(s8,cmbIdPc);
((CardLayout) jPanel7.getLayout()).show(jPanel7,s1);
((CardLayout) cardType.getLayout()).show(cardType,s3);
((CardLayout) cardSlot.getLayout()).show(cardSlot,s5);
((CardLayout) cardIdPc.getLayout()).show(cardIdPc,s7);
cmbType.addItemListener(new java.awt.event.ItemListener() {
public void itemStateChanged(java.awt.event.ItemEvent evt) {
cmbTypePeripheriqueItemStateChanged(evt);
}
});
//Bouton modifier
jbtModifier.addActionListener(new java.awt.event.ActionListener(){
public void actionPerformed(java.awt.event.ActionEvent e)
{
jbtModifierActionPerformed();
}
});
jTable2.getSelectionModel().addListSelectionListener(new ListSelectionListener()
{
public void valueChanged(ListSelectionEvent lse)
{
if (jTable2.getSelectedRow()!=-1 && ajout==false && modif==false)
{
int ligne = jTable2.getSelectedRow();
Peripherique pp = (Peripherique)v.elementAt(ligne);
txtIdPeripherique.setText(String.valueOf(pp.getId_peripherique()));
txtType.setText(pp.getType_peripherique().getType());
txtNomPeripherique.setText(pp.getNom());
txtSerial.setText(pp.getNumero_serie());
txtPilote.setText(pp.getPilote());
txtIdLieu.setText(String.valueOf(pp.getLieu().getId_lieu()));
txtTypeLieu.setText(pp.getLieu().getTypeLieu().getNom_type());
txtLieu.setText(pp.getLieu().getNom());
if (pp.getPc().getId_pc()!=0)
{
checkbox1.setState(true);
txtIdPc.setText(String.valueOf(pp.getPc().getId_pc()));
txtPc.setText(pp.getPc().getMarque()+" "+pp.getPc().getModele());
}
else
{
checkbox1.setState(false);
txtIdPc.setText("");
txtPc.setText("");
}
txtIdSlot.setText(String.valueOf(pp.getSlot().getType()));
Vector v2 = pp.getLesPeripherique_propriete();
Vector v3 = pp.getType_peripherique().getLesProprietes();
System.out.println(jTable1.getRowCount());
jTable1.setModel(model2);
while (jTable1.getRowCount()!=0)
model2.removeRow(0);
if (v2.size()!=0)
{
Object [][] data = new Object[v2.size()][2];
for (int i=0;i<v2.size();i++)
{
Peripherique_propriete pProp = (Peripherique_propriete)v2.elementAt(i);
Propriete prop = (Propriete)v3.elementAt(i);
data[i][0] = prop.getPropriete();
data[i][1] = pProp.getValeur();
System.out.println("prop.getpropriete="+prop.getPropriete()+"--prop.getValeur="+pProp.getValeur());
String []s = {prop.getPropriete(),pProp.getValeur()};
model2.addRow(s);
}
// test = data;
// jTable1.setModel(getModel());
}else
{
jTable1.setModel(new DefaultTableModel(titre,0));
}
}
}
});
recupererPeripheriques();
}
public void jbtModifierActionPerformed()
{
if (jTable2.getSelectedRowCount()!=0)
{
int ligne = jTable2.getSelectedRow();
System.out.println("LIGNE="+ligne);
if (modif==false)
{
modif=true;
jbtModifier.setText("Valider");
((CardLayout) jPanel7.getLayout()).show(jPanel7,s2);
((CardLayout) cardType.getLayout()).show(cardType,s4);
((CardLayout) cardSlot.getLayout()).show(cardSlot,s6);
((CardLayout) cardIdPc.getLayout()).show(cardIdPc,s8);
checkbox1.setEnabled(true);
txtNomPeripherique.setEnabled(true);
txtSerial.setEnabled(true);
txtPilote.setEnabled(true);
cmbIdSlot.removeAllItems();
Gbd gbd = new Gbd();
gbd.connecter();
String requete2 = "SELECT id_slot FROM slot";
ResultSet r2 = gbd.execQuery(requete2);
try
{
while (r2.next())
{
Slot s = new Slot();
s.construireSlot(r2.getInt("id_slot"));
cmbIdSlot.addItem(s.getType());
}
gbd.deconnecter();
}catch(Exception ex)
{
System.out.println(ex.toString());
}
cmbIdSlot.setSelectedItem(txtIdSlot.getText());
cmbType.removeAllItems();
gbd.connecter();
String requete = "SELECT id_type_peripherique FROM type_peripherique";
ResultSet r = gbd.execQuery(requete);
try
{
while (r.next())
{
Type_peripherique tp = new Type_peripherique();
tp.construireTypePeripherique(r.getInt("id_type_peripherique"));
cmbType.addItem(tp.getType());
System.out.println(tp.getType());
}
gbd.deconnecter();
}catch(Exception ex)
{
System.out.println(ex.toString());
JXErrorDialog.showDialog(null,"DataBase ERROR !!!",ex);
}
cmbType.setSelectedItem(txtType.getText());
for (int i=0; i<cmbIdLieu.getItemCount();i++)
{
if (cmbIdLieu.getItemAt(i)!="Choisir un Lieu")
cmbIdLieu.removeItem(i);
}
cmbIdLieu.addItem(txtIdLieu.getText());
cmbIdLieu.setSelectedItem(txtIdLieu.getText());
var=true;
for (int i=0; i<cmbIdPc.getItemCount();i++)
{
if (cmbIdPc.getItemAt(i)!="Choisir un PC")
cmbIdPc.removeItemAt(i);
}
cmbIdPc.addItem(txtIdPc.getText());
cmbIdPc.setSelectedItem(txtIdPc.getText());
var=false;
}
else //Modif=true
{
modif=false;
jbtModifier.setText("Modifier");
int reponse = JOptionPane.showConfirmDialog(this,"Etes vous sur de vouloir modifier ce piphrique ?","Modification",JOptionPane.YES_NO_OPTION);
if (reponse==0)
{
Peripherique p1 = (Peripherique)v.elementAt(ligne);
Type_peripherique t = new Type_peripherique();
t.construireTypePeripherique(cmbType.getSelectedItem().toString());
p1.setType_peripherique(t);
p1.setNom(txtNomPeripherique.getText());
p1.setNumero_serie(txtSerial.getText());
p1.setPilote(txtPilote.getText());
Slot s = new Slot();
s.construireSlot(cmbIdSlot.getSelectedItem().toString());
p1.setSlot(s);
Lieu l = new Lieu();
l.construireLieu(Integer.parseInt(cmbIdLieu.getSelectedItem().toString()));
p1.setLieu(l);
Pc pc = new Pc();
try
{
pc.construirePc(Integer.parseInt(cmbIdPc.getSelectedItem().toString()));
}catch (NumberFormatException e)
{
pc.setId_pc(null);
}
p1.setPc(pc);
Garantie g = new Garantie();
g.setId_garantie(1);
p1.setGarantie(g);
//Modification des caracteristiques
for (int i=0; i< jTable1.getRowCount();i++)
{
Propriete p = new Propriete();
p.construirePropriete(jTable1.getValueAt(i, 0).toString());
System.out.println(p.getId_propriete());
Gbd gbd2 = new Gbd();
gbd2.connecter();
String requete = "UPDATE peripherique_propriete SET valeur='"+
jTable1.getValueAt(i, 1).toString()+
"' WHERE id_peripherique="+p1.getId_peripherique()+
" AND id_propriete="+p.getId_propriete();
System.out.println(requete);
gbd2.execUpdate(requete);
}
int i = p1.modifierPeripherique();
if (i==1)
{
v.set(ligne, p1);
model.setValueAt(p1.getId_peripherique(), ligne, 0);
model.setValueAt(p1.getType_peripherique().getType(), ligne, 1);
model.setValueAt(p1.getNom(), ligne, 2);
model.setValueAt(p1.getSlot().getType(), ligne, 3);
model.setValueAt(p1.getNumero_serie(), ligne, 4);
model.setValueAt(p1.getPilote(), ligne, 5);
model.setValueAt(p1.getPc().getId_pc(), ligne, 6);
model.setValueAt(p1.getLieu().getId_lieu(), ligne, 7);
JOptionPane.showConfirmDialog(this, "Le priphrique a t modifi avec succs!","Modification",JOptionPane.DEFAULT_OPTION);
}
else
{
JOptionPane.showConfirmDialog(null, "Le priphrique n'a pas t modifi !!","Modification",JOptionPane.WARNING_MESSAGE);
}
}
else //Reponse de l'utilisateur = non
{
JOptionPane.showConfirmDialog(this, "Le priphrique n'a pas t modifi !","Modification",JOptionPane.DEFAULT_OPTION);
}
((CardLayout) jPanel7.getLayout()).show(jPanel7,s1);
((CardLayout) cardType.getLayout()).show(cardType,s3);
((CardLayout) cardSlot.getLayout()).show(cardSlot,s5);
((CardLayout) cardIdPc.getLayout()).show(cardIdPc,s7);
txtIdLieu.setEnabled(false);
txtIdPc.setEnabled(false);
txtIdSlot.setEnabled(false);
txtNomPeripherique.setEnabled(false);
txtPc.setEnabled(false);
txtPilote.setEnabled(false);
txtSerial.setEnabled(false);
checkbox1.setEnabled(false);
}
}
}
public void recupererPeripheriques()
{
String requete="";
Gbd gbd = new Gbd();
gbd.connecter();
if(this.id_pc==-1)
requete = "SELECT id_peripherique FROM peripherique";
else
requete ="SELECT id_peripherique FROM peripherique WHERE id_pc="+id_pc;
ResultSet r = gbd.execQuery(requete);
try{
while (r.next())
{
Peripherique p = new Peripherique();
p.construirePeripherique(r.getInt("id_peripherique"));
v.add(p);
}
}catch (SQLException e)
{
e.printStackTrace();
JXErrorDialog.showDialog(null,"DataBase ERROR !!!",e);
}
lst = v.listIterator();
System.out.println("SIZE="+v.size());
Object [][]data3 = new Object[v.size()][8];
for (int i=0;i<v.size();i++)
{
p1 = (Peripherique)lst.next();
data3[i][0] = p1.getId_peripherique();
data3[i][1] = p1.getType_peripherique().getType();
data3[i][2] = p1.getNom();
data3[i][3] = p1.getSlot().getType();
data3[i][4] = p1.getNumero_serie();
data3[i][5] = p1.getPilote();
data3[i][6] = p1.getLieu().getId_lieu();
data3[i][7] = p1.getPc().getId_pc();
String [] s = {String.valueOf(p1.getId_peripherique()),
p1.getType_peripherique().getType(),
p1.getNom(),
p1.getSlot().getType(),
p1.getNumero_serie(),
p1.getPilote(),
String.valueOf(p1.getPc().getId_pc()),
String.valueOf(p1.getLieu().getId_lieu())
};
model.addRow(s);
}
data2 = data3;
// jTable2.setModel(getModel2());
jTable2.setModel(model);
jTable1.setModel(new DefaultTableModel(titre,5));
//
}
public TableModel getModel()
{
return new ModelJTable(test,titre);
}
public TableModel getModel2()
{
return new ModelJTable(data2,titre2);
}
//
// <editor-fold defaultstate="collapsed" desc=" Generated Code ">//GEN-BEGIN:initComponents
private void initComponents() {
jLabel1 = new javax.swing.JLabel();
jPanel1 = new javax.swing.JPanel();
jLabel2 = new javax.swing.JLabel();
txtIdPeripherique = new javax.swing.JTextField();
jLabel3 = new javax.swing.JLabel();
txtNomPeripherique = new javax.swing.JTextField();
jLabel4 = new javax.swing.JLabel();
jLabel5 = new javax.swing.JLabel();
txtSerial = new javax.swing.JTextField();
jLabel6 = new javax.swing.JLabel();
jLabel9 = new javax.swing.JLabel();
txtPilote = new javax.swing.JTextField();
cardType = new javax.swing.JPanel();
cardSlot = new javax.swing.JPanel();
jPanel2 = new javax.swing.JPanel();
jScrollPane1 = new javax.swing.JScrollPane();
// jTable1 = new javax.swing.JTable();
jPanel4 = new javax.swing.JPanel();
jbtSupprimer = new javax.swing.JButton();
jbtModifier = new javax.swing.JButton();
jbtAjouter = new javax.swing.JButton();
jButton1 = new javax.swing.JButton();
jButton2 = new javax.swing.JButton();
jPanel3 = new javax.swing.JPanel();
jLabel7 = new javax.swing.JLabel();
jLabel10 = new javax.swing.JLabel();
txtPc = new javax.swing.JTextField();
cardIdPc = new javax.swing.JPanel();
checkbox1 = new java.awt.Checkbox();
jPanel6 = new javax.swing.JPanel();
jScrollPane2 = new javax.swing.JScrollPane();
// jTable2 = new javax.swing.JTable();
jPanel8 = new javax.swing.JPanel();
jPanel5 = new javax.swing.JPanel();
jLabel12 = new javax.swing.JLabel();
txtTypeLieu = new javax.swing.JTextField();
jLabel11 = new javax.swing.JLabel();
txtLieu = new javax.swing.JTextField();
jLabel8 = new javax.swing.JLabel();
jPanel7 = new javax.swing.JPanel();
jLabel1.setFont(new java.awt.Font("Tahoma", 1, 18));
jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel1.setText("P\u00e9riph\u00e9riques");
jPanel1.setBorder(javax.swing.BorderFactory
.createTitledBorder("Propri\u00e9t\u00e9s"));
jLabel2.setText("Id p\u00e9riph\u00e9rique");
txtIdPeripherique.setEnabled(false);
txtIdPeripherique
.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
txtIdPeripheriqueActionPerformed(evt);
}
});
jLabel3.setText("Type p\u00e9riph\u00e9rique");
txtNomPeripherique.setEnabled(false);
jLabel4.setText("Nom");
jLabel5.setText("Num\u00e9ro de s\u00e9rie");
txtSerial.setEnabled(false);
jLabel6.setText("Slot");
jLabel9.setText("Chemin du pilote");
txtPilote.setEnabled(false);
org.jdesktop.layout.GroupLayout cardTypeLayout = new org.jdesktop.layout.GroupLayout(
cardType);
cardType.setLayout(cardTypeLayout);
cardTypeLayout.setHorizontalGroup(cardTypeLayout.createParallelGroup(
org.jdesktop.layout.GroupLayout.LEADING).add(0, 201,
Short.MAX_VALUE));
cardTypeLayout.setVerticalGroup(cardTypeLayout.createParallelGroup(
org.jdesktop.layout.GroupLayout.LEADING).add(0, 20,
Short.MAX_VALUE));
org.jdesktop.layout.GroupLayout cardSlotLayout = new org.jdesktop.layout.GroupLayout(
cardSlot);
cardSlot.setLayout(cardSlotLayout);
cardSlotLayout.setHorizontalGroup(cardSlotLayout.createParallelGroup(
org.jdesktop.layout.GroupLayout.LEADING).add(0, 201,
Short.MAX_VALUE));
cardSlotLayout.setVerticalGroup(cardSlotLayout.createParallelGroup(
org.jdesktop.layout.GroupLayout.LEADING).add(0, 19,
Short.MAX_VALUE));
org.jdesktop.layout.GroupLayout jPanel1Layout = new org.jdesktop.layout.GroupLayout(
jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout
.setHorizontalGroup(jPanel1Layout
.createParallelGroup(
org.jdesktop.layout.GroupLayout.LEADING)
.add(
jPanel1Layout
.createSequentialGroup()
.addContainerGap()
.add(
jPanel1Layout
.createParallelGroup(
org.jdesktop.layout.GroupLayout.LEADING)
.add(jLabel5).add(
jLabel6).add(
jLabel4).add(
jLabel9).add(
jLabel2).add(
jLabel3))
.add(18, 18, 18)
.add(
jPanel1Layout
.createParallelGroup(
org.jdesktop.layout.GroupLayout.LEADING)
.add(
cardSlot,
org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
Short.MAX_VALUE)
.add(
cardType,
org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
Short.MAX_VALUE)
.add(
txtIdPeripherique,
org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
201,
Short.MAX_VALUE)
.add(
txtSerial,
org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
201,
Short.MAX_VALUE)
.add(
org.jdesktop.layout.GroupLayout.TRAILING,
txtNomPeripherique,
org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
201,
Short.MAX_VALUE)
.add(
txtPilote,
org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
201,
Short.MAX_VALUE))
.add(20, 20, 20)));
jPanel1Layout
.setVerticalGroup(jPanel1Layout
.createParallelGroup(
org.jdesktop.layout.GroupLayout.LEADING)
.add(
jPanel1Layout
.createSequentialGroup()
.add(
jPanel1Layout
.createParallelGroup(
org.jdesktop.layout.GroupLayout.BASELINE)
.add(jLabel2)
.add(
txtIdPeripherique,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,
org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(
org.jdesktop.layout.LayoutStyle.RELATED)
.add(
jPanel1Layout
.createParallelGroup(
org.jdesktop.layout.GroupLayout.LEADING)
.add(
cardType,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,
org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.add(jLabel3))
.addPreferredGap(
org.jdesktop.layout.LayoutStyle.RELATED)
.add(
jPanel1Layout
.createParallelGroup(
org.jdesktop.layout.GroupLayout.BASELINE)
.add(jLabel4)
.add(
txtNomPeripherique,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,
org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(
org.jdesktop.layout.LayoutStyle.RELATED)
.add(
jPanel1Layout
.createParallelGroup(
org.jdesktop.layout.GroupLayout.BASELINE)
.add(jLabel5)
.add(
txtSerial,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,
org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(
org.jdesktop.layout.LayoutStyle.RELATED,
org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
Short.MAX_VALUE)
.add(
jPanel1Layout
.createParallelGroup(
org.jdesktop.layout.GroupLayout.LEADING)
.add(jLabel6)
.add(
cardSlot,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,
org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(
org.jdesktop.layout.LayoutStyle.RELATED)
.add(
jPanel1Layout
.createParallelGroup(
org.jdesktop.layout.GroupLayout.BASELINE)
.add(jLabel9)
.add(
txtPilote,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,
org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
.add(138, 138, 138)));
jPanel2.setBorder(javax.swing.BorderFactory
.createTitledBorder("Caract\u00e9ristiques"));
jTable1
.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
public void propertyChange(
java.beans.PropertyChangeEvent evt) {
jTable1PropertyChange(evt);
}
});
jScrollPane1.setViewportView(jTable1);
org.jdesktop.layout.GroupLayout jPanel2Layout = new org.jdesktop.layout.GroupLayout(
jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(jPanel2Layout.createParallelGroup(
org.jdesktop.layout.GroupLayout.LEADING).add(jScrollPane1,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 213,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE));
jPanel2Layout.setVerticalGroup(jPanel2Layout.createParallelGroup(
org.jdesktop.layout.GroupLayout.LEADING).add(jScrollPane1,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 214,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE));
jbtSupprimer.setText("Supprimer");
jbtSupprimer.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jbtSupprimerActionPerformed(evt);
}
});
jbtModifier.setText("Modifier");
jbtModifier.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
// jbtModifierActionPerformed(evt);
}
});
jbtAjouter.setText("Nouveau");
jbtAjouter.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jbtAjouterActionPerformed(evt);
}
});
jButton1.setText("Intervention");
jButton2.setText("Rechercher");
org.jdesktop.layout.GroupLayout jPanel4Layout = new org.jdesktop.layout.GroupLayout(
jPanel4);
jPanel4.setLayout(jPanel4Layout);
jPanel4Layout.setHorizontalGroup(jPanel4Layout.createParallelGroup(
org.jdesktop.layout.GroupLayout.LEADING).add(
jPanel4Layout.createSequentialGroup().add(jbtSupprimer)
.addPreferredGap(
org.jdesktop.layout.LayoutStyle.RELATED).add(
jbtModifier).addPreferredGap(
org.jdesktop.layout.LayoutStyle.RELATED).add(
jbtAjouter).addPreferredGap(
org.jdesktop.layout.LayoutStyle.RELATED).add(
jButton1).addPreferredGap(
org.jdesktop.layout.LayoutStyle.RELATED).add(
jButton2)));
jPanel4Layout.setVerticalGroup(jPanel4Layout.createParallelGroup(
org.jdesktop.layout.GroupLayout.LEADING).add(
jPanel4Layout.createParallelGroup(
org.jdesktop.layout.GroupLayout.BASELINE).add(
jbtSupprimer).add(jbtModifier).add(jbtAjouter).add(
jButton1).add(jButton2)));
jPanel3.setBorder(javax.swing.BorderFactory.createTitledBorder("Pc"));
jLabel7.setText("Id PC");
jLabel10.setText("Nom");
txtPc.setEnabled(false);
txtPc.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
txtPcActionPerformed(evt);
}
});
org.jdesktop.layout.GroupLayout cardIdPcLayout = new org.jdesktop.layout.GroupLayout(
cardIdPc);
cardIdPc.setLayout(cardIdPcLayout);
cardIdPcLayout.setHorizontalGroup(cardIdPcLayout.createParallelGroup(
org.jdesktop.layout.GroupLayout.LEADING).add(0, 171,
Short.MAX_VALUE));
cardIdPcLayout.setVerticalGroup(cardIdPcLayout.createParallelGroup(
org.jdesktop.layout.GroupLayout.LEADING).add(0, 16,
Short.MAX_VALUE));
checkbox1.setFont(new java.awt.Font("Tahoma", 0, 11));
checkbox1
.setLabel(" Ce p\u00e9riph\u00e9rique apparient \u00e0 un Pc");
checkbox1.addItemListener(new java.awt.event.ItemListener() {
public void itemStateChanged(java.awt.event.ItemEvent evt) {
checkbox1ItemStateChanged(evt);
}
});
org.jdesktop.layout.GroupLayout jPanel3Layout = new org.jdesktop.layout.GroupLayout(
jPanel3);
jPanel3.setLayout(jPanel3Layout);
jPanel3Layout
.setHorizontalGroup(jPanel3Layout
.createParallelGroup(
org.jdesktop.layout.GroupLayout.LEADING)
.add(
jPanel3Layout
.createSequentialGroup()
.addContainerGap()
.add(
jPanel3Layout
.createParallelGroup(
org.jdesktop.layout.GroupLayout.TRAILING,
false)
.add(
org.jdesktop.layout.GroupLayout.LEADING,
checkbox1,
org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
Short.MAX_VALUE)
.add(
org.jdesktop.layout.GroupLayout.LEADING,
jPanel3Layout
.createSequentialGroup()
.add(
jPanel3Layout
.createParallelGroup(
org.jdesktop.layout.GroupLayout.LEADING)
.add(
jLabel10)
.add(
jLabel7))
.add(
13,
13,
13)
.add(
jPanel3Layout
.createParallelGroup(
org.jdesktop.layout.GroupLayout.LEADING,
false)
.add(
txtPc)
.add(
cardIdPc,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,
org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))))
.addContainerGap(58, Short.MAX_VALUE)));
jPanel3Layout
.setVerticalGroup(jPanel3Layout
.createParallelGroup(
org.jdesktop.layout.GroupLayout.LEADING)
.add(
org.jdesktop.layout.GroupLayout.TRAILING,
jPanel3Layout
.createSequentialGroup()
.add(
checkbox1,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,
org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(
org.jdesktop.layout.LayoutStyle.RELATED,
org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
Short.MAX_VALUE)
.add(
jPanel3Layout
.createParallelGroup(
org.jdesktop.layout.GroupLayout.TRAILING)
.add(jLabel7)
.add(
cardIdPc,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,
org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(
org.jdesktop.layout.LayoutStyle.RELATED)
.add(
jPanel3Layout
.createParallelGroup(
org.jdesktop.layout.GroupLayout.BASELINE)
.add(jLabel10)
.add(
txtPc,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,
org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
.add(126, 126, 126)));
jPanel6.setBorder(javax.swing.BorderFactory
.createTitledBorder("P\u00e9riph\u00e9riques"));
jTable2.setModel(new javax.swing.table.DefaultTableModel(
new Object[][] {
{ null, null, null, null, null, null, null, null },
{ null, null, null, null, null, null, null, null },
{ null, null, null, null, null, null, null, null },
{ null, null, null, null, null, null, null, null } },
new String[] { "ID", "Type", "Nom", "Slot", "Numro srie",
"Pilote", "Id_Pc", "Id_lieu" }));
jScrollPane2.setViewportView(jTable2);
org.jdesktop.layout.GroupLayout jPanel6Layout = new org.jdesktop.layout.GroupLayout(
jPanel6);
jPanel6.setLayout(jPanel6Layout);
jPanel6Layout.setHorizontalGroup(jPanel6Layout.createParallelGroup(
org.jdesktop.layout.GroupLayout.LEADING).add(jScrollPane2,
org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 608,
Short.MAX_VALUE));
jPanel6Layout.setVerticalGroup(jPanel6Layout.createParallelGroup(
org.jdesktop.layout.GroupLayout.LEADING).add(jScrollPane2,
org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 214,
Short.MAX_VALUE));
org.jdesktop.layout.GroupLayout jPanel8Layout = new org.jdesktop.layout.GroupLayout(
jPanel8);
jPanel8.setLayout(jPanel8Layout);
jPanel8Layout.setHorizontalGroup(jPanel8Layout.createParallelGroup(
org.jdesktop.layout.GroupLayout.LEADING).add(0, 0,
Short.MAX_VALUE));
jPanel8Layout.setVerticalGroup(jPanel8Layout.createParallelGroup(
org.jdesktop.layout.GroupLayout.LEADING).add(0, 0,
Short.MAX_VALUE));
jPanel5
.setBorder(javax.swing.BorderFactory
.createTitledBorder("Local"));
jLabel12.setText("Id Lieu");
jLabel11.setText("Type lieu");
jLabel8.setText("Lieu");
org.jdesktop.layout.GroupLayout jPanel7Layout = new org.jdesktop.layout.GroupLayout(
jPanel7);
jPanel7.setLayout(jPanel7Layout);
jPanel7Layout.setHorizontalGroup(jPanel7Layout.createParallelGroup(
org.jdesktop.layout.GroupLayout.LEADING).add(0, 152,
Short.MAX_VALUE));
jPanel7Layout.setVerticalGroup(jPanel7Layout.createParallelGroup(
org.jdesktop.layout.GroupLayout.LEADING).add(0, 18,
Short.MAX_VALUE));
org.jdesktop.layout.GroupLayout jPanel5Layout = new org.jdesktop.layout.GroupLayout(
jPanel5);
jPanel5.setLayout(jPanel5Layout);
jPanel5Layout
.setHorizontalGroup(jPanel5Layout
.createParallelGroup(
org.jdesktop.layout.GroupLayout.LEADING)
.add(
jPanel5Layout
.createSequentialGroup()
.addContainerGap()
.add(
jPanel5Layout
.createParallelGroup(
org.jdesktop.layout.GroupLayout.LEADING)
.add(
jPanel5Layout
.createSequentialGroup()
.add(
jLabel8)
.addContainerGap(
249,
Short.MAX_VALUE))
.add(
jPanel5Layout
.createSequentialGroup()
.add(
jPanel5Layout
.createParallelGroup(
org.jdesktop.layout.GroupLayout.LEADING)
.add(
jLabel11)
.add(
jLabel12))
.addPreferredGap(
org.jdesktop.layout.LayoutStyle.RELATED)
.add(
jPanel5Layout
.createParallelGroup(
org.jdesktop.layout.GroupLayout.LEADING)
.add(
jPanel7,
org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
Short.MAX_VALUE)
.add(
txtLieu,
org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
152,
Short.MAX_VALUE)
.add(
txtTypeLieu,
org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
152,
Short.MAX_VALUE))
.add(
69,
69,
69)))));
jPanel5Layout
.setVerticalGroup(jPanel5Layout
.createParallelGroup(
org.jdesktop.layout.GroupLayout.LEADING)
.add(
jPanel5Layout
.createSequentialGroup()
.add(
jPanel5Layout
.createParallelGroup(
org.jdesktop.layout.GroupLayout.LEADING)
.add(jLabel12)
.add(
jPanel7,
org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
Short.MAX_VALUE))
.addPreferredGap(
org.jdesktop.layout.LayoutStyle.RELATED)
.add(
jPanel5Layout
.createParallelGroup(
org.jdesktop.layout.GroupLayout.LEADING)
.add(jLabel11)
.add(
txtTypeLieu,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,
org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(
org.jdesktop.layout.LayoutStyle.RELATED)
.add(
jPanel5Layout
.createParallelGroup(
org.jdesktop.layout.GroupLayout.LEADING)
.add(jLabel8)
.add(
txtLieu,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,
org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
.addContainerGap()));
org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(
this);
this.setLayout(layout);
layout
.setHorizontalGroup(layout
.createParallelGroup(
org.jdesktop.layout.GroupLayout.LEADING)
.add(
layout
.createSequentialGroup()
.add(
layout
.createParallelGroup(
org.jdesktop.layout.GroupLayout.LEADING)
.add(
layout
.createSequentialGroup()
.add(
407,
407,
407)
.add(
jLabel1))
.add(
layout
.createSequentialGroup()
.addContainerGap()
.add(
jPanel6,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,
org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(
org.jdesktop.layout.LayoutStyle.RELATED)
.add(
jPanel2,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,
org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
.add(
layout
.createSequentialGroup()
.addContainerGap()
.add(
jPanel1,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,
org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.add(
59,
59,
59)
.add(
layout
.createParallelGroup(
org.jdesktop.layout.GroupLayout.LEADING,
false)
.add(
jPanel5,
org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
Short.MAX_VALUE)
.add(
jPanel3,
org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
Short.MAX_VALUE))
.add(
132,
132,
132)
.add(
jPanel8,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,
org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
.add(
layout
.createSequentialGroup()
.addContainerGap()
.add(
jPanel4,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,
org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)))
.addContainerGap(216, Short.MAX_VALUE)));
layout
.setVerticalGroup(layout
.createParallelGroup(
org.jdesktop.layout.GroupLayout.LEADING)
.add(
layout
.createSequentialGroup()
.addContainerGap(
org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
Short.MAX_VALUE)
.add(jLabel1)
.add(65, 65, 65)
.add(
layout
.createParallelGroup(
org.jdesktop.layout.GroupLayout.LEADING,
false)
.add(
org.jdesktop.layout.GroupLayout.TRAILING,
jPanel6,
org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
Short.MAX_VALUE)
.add(
org.jdesktop.layout.GroupLayout.TRAILING,
jPanel2,
org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
Short.MAX_VALUE))
.add(
layout
.createParallelGroup(
org.jdesktop.layout.GroupLayout.LEADING)
.add(
layout
.createSequentialGroup()
.add(
129,
129,
129)
.add(
jPanel8,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,
org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
.add(
layout
.createSequentialGroup()
.add(
6,
6,
6)
.add(
jPanel4,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,
org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.add(
26,
26,
26)
.add(
layout
.createParallelGroup(
org.jdesktop.layout.GroupLayout.LEADING)
.add(
layout
.createSequentialGroup()
.add(
jPanel3,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,
117,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(
org.jdesktop.layout.LayoutStyle.RELATED)
.add(
jPanel5,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,
org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
.add(
jPanel1,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,
197,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))))));
}// </editor-fold>//GEN-END:initComponents
private void checkbox1ItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_checkbox1ItemStateChanged
if (checkbox1.getState()==true)
{
cmbIdLieu.setEnabled(false);
cmbIdLieu.addItem("");
cmbIdLieu.setSelectedItem("");
txtTypeLieu.setText("");
txtLieu.setText("");
cmbIdPc.setEnabled(true);
}
else
{
cmbIdLieu.setEnabled(true);
txtTypeLieu.setText("");
cmbIdPc.setEnabled(false);
cmbIdPc.addItem("");
cmbIdPc.setSelectedItem("");
txtPc.setText("");
}
}//GEN-LAST:event_checkbox1ItemStateChanged
private void txtPcActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtPcActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_txtPcActionPerformed
public void cmbPcActionPerformed(java.awt.event.ActionEvent evt){
}
public void jTable1PropertyChange(java.beans.PropertyChangeEvent evt){
}
public void txtIdPeripheriqueActionPerformed(java.awt.event.ActionEvent evt){
}
private void cmbIdPcItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_cmbPcItemStateChanged
if (var==false)
if (cmbIdPc.getItemCount()!=0)
if (evt.getStateChange()==1)
if (cmbIdPc.getSelectedItem().toString()=="Choisir un PC")
{
Dialog_choixPc d = new Dialog_choixPc(m,true,this);
d.setVisible(true);
d.setLocationRelativeTo(this);
}
}
private void cmbIdLieuItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_cmbPcItemStateChanged
if (cmbIdLieu.getItemCount()!=0)
if (evt.getStateChange()==1)
if (cmbIdLieu.getSelectedItem().toString()=="Choisir un Lieu")
{
Dialog_choixLieu d = new Dialog_choixLieu(m,true,1);
d.pack();
d.setVisible(true);
d.setLocationRelativeTo(this);
}
}
private void jbtSupprimerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtSupprimerActionPerformed
int reponse=-1;
if (jTable2.getSelectedRowCount()!=0)
{ // 0 : OUI
// 1 : NON
reponse = JOptionPane.showConfirmDialog(this,"Etes vous sur de vouloir supprimer ce piphrique ?","Suppression",JOptionPane.YES_NO_OPTION);
if (reponse==0)
{
int id = Integer.parseInt(jTable2.getValueAt(jTable2.getSelectedRow(), 0).toString());
Peripherique periph = new Peripherique();
periph.setId_peripherique(id);
int res = periph.supprimerPeripherique();
System.out.println("id = "+id+" res="+res);
//int res=0;
if (res==1)
{
v.remove(jTable2.getSelectedRow());
model.removeRow(jTable2.getSelectedRow());
JOptionPane.showConfirmDialog(this, "Peripherique supprim avec succs","Suppression",JOptionPane.DEFAULT_OPTION);
//jTable1.setModel(new DefaultTableModel());
//Vider la JTable des proptietes
while (jTable1.getRowCount()!=0)
model2.removeRow(0);
//Restaurer les combobox a la place des TextFields
((CardLayout) jPanel7.getLayout()).show(jPanel7,s1);
((CardLayout) cardType.getLayout()).show(cardType,s3);
((CardLayout) cardSlot.getLayout()).show(cardSlot,s5);
((CardLayout) cardIdPc.getLayout()).show(cardIdPc,s7);
//Effacer le contenu des TextFields
txtIdPeripherique.setText("");
txtType.setText("");
txtNomPeripherique.setText("");
txtSerial.setText("");
txtPilote.setText("");
txtIdLieu.setText("");
txtTypeLieu.setText("");
txtLieu.setText("");
txtIdPc.setText("");
txtPc.setText("");
txtIdSlot.setText("");
}
else
{
JOptionPane.showConfirmDialog(null, "Le priphrique n'a pas t supprim !!","Suppression",JOptionPane.WARNING_MESSAGE);
}
}
}
}//GEN-LAST:event_jbtSupprimerActionPerformed
private void cmbTypePeripheriqueItemStateChanged(
java.awt.event.ItemEvent evt) {
if (evt.getStateChange()==1 && ajout==true)
{
Type_peripherique tp2 = new Type_peripherique();
tp2.construireTypePeripherique(cmbType.getSelectedItem().toString());
System.out.println("Type_peripherique = "+tp2.getType());
Vector lesTypes = tp2.getLesProprietes();
if (lesTypes.size()!=0)
{
Object[][] data = new Object[lesTypes.size()][2];
for (int i=0;i<lesTypes.size();i++)
{
Propriete propriete = (Propriete)lesTypes.elementAt(i);
data[i][0]=propriete.getPropriete();
System.out.println("Propriete "+i+" "+propriete.getPropriete());
}
this.test = data;
ModelJTable mt = new ModelJTable(data,titre);
mt.modifier=true;
jTable1.setModel(mt);
}
else
{
jTable1.setModel(new DefaultTableModel(titre,5));
}
}
}
/**
*
* L'ecouteur du bouton jbtAjouter (Ajouter)
*
* Il permet d'ajouter un peripherique a la base
*
*
**/
private void jbtAjouterActionPerformed(java.awt.event.ActionEvent evt) {
if (ajout==false)
{
ajout=true;
jbtAjouter.setText("Valider");
checkbox1.setEnabled(true);
txtIdPeripherique.setText("");
//txtIdPeripherique.setEditable(true);
//txtIdPeripherique.setEnabled(true);
txtNomPeripherique.setText("");
txtNomPeripherique.setEditable(true);
txtNomPeripherique.setEnabled(true);
txtPilote.setText("");
txtPilote.setEditable(true);
txtPilote.setEnabled(true);
txtSerial.setText("");
txtSerial.setEditable(true);
txtSerial.setEnabled(true);
((CardLayout) jPanel7.getLayout()).show(jPanel7,s2);
((CardLayout) cardType.getLayout()).show(cardType,s4);
((CardLayout) cardSlot.getLayout()).show(cardSlot,s6);
((CardLayout) cardIdPc.getLayout()).show(cardIdPc,s8);
cmbIdLieu.removeAllItems();
cmbIdLieu.addItem(" ");
cmbIdLieu.addItem("Choisir un Lieu");
cmbIdLieu.setEnabled(true);
cmbIdPc.removeAllItems();
cmbIdPc.addItem(" ");
cmbIdPc.addItem("Choisir un PC");
cmbIdPc.setEnabled(true);
cmbType.setEnabled(true);
cmbType.removeAllItems();
Gbd gbd = new Gbd();
gbd.connecter();
String requete = "SELECT id_type_peripherique FROM type_peripherique";
ResultSet r = gbd.execQuery(requete);
try
{
while (r.next())
{
Type_peripherique tp = new Type_peripherique();
tp.construireTypePeripherique(r.getInt("id_type_peripherique"));
cmbType.addItem(tp.getType());
System.out.println(tp.getType());
}
gbd.deconnecter();
}catch(Exception e)
{
System.out.println(e.toString());
JXErrorDialog.showDialog(null,"DataBase ERROR !!!",e);
}
cmbIdSlot.removeAllItems();
gbd.connecter();
String requete2 = "SELECT id_slot FROM slot";
ResultSet r2 = gbd.execQuery(requete2);
try
{
while (r2.next())
{
Slot s = new Slot();
s.construireSlot(r2.getInt("id_slot"));
cmbIdSlot.addItem(s.getType());
}
gbd.deconnecter();
}catch(Exception e)
{
System.out.println(e.toString());
}
Type_peripherique tp2 = new Type_peripherique();
tp2.construireTypePeripherique(cmbType.getSelectedItem().toString());
Vector lesTypes = tp2.getLesProprietes();
Object[][] data = new Object[lesTypes.size()][2];
for (int i=0;i<lesTypes.size();i++)
{
Propriete propriete = (Propriete)lesTypes.elementAt(i);
data[i][0]=propriete.getPropriete();
System.out.println(propriete.getPropriete());
}
ModelJTable m = new ModelJTable(data,titre);
m.modifier=true;
jTable1.setModel(m);
b=true;
}
else
{
ajout=false;
jbtAjouter.setText("Ajouter");
Peripherique p = new Peripherique();
try
{
p.setNom(txtNomPeripherique.getText());
p.setNumero_serie(txtSerial.getText());
p.setPilote(txtPilote.getText());
Lieu l = new Lieu();
l.setId_lieu(Integer.parseInt(cmbIdLieu.getSelectedItem().toString()));
p.setLieu(l);
Slot s = new Slot();
s.construireSlot(String.valueOf(cmbIdSlot.getSelectedItem()));
p.setSlot(s);
Garantie g = new Garantie();
g.setId_garantie(null);
p.setGarantie(g);
Type_peripherique t = new Type_peripherique();
t.construireTypePeripherique(cmbType.getSelectedItem().toString());
p.setType_peripherique(t);
Pc pc =new Pc();
if (cmbIdPc.getSelectedItem().toString()!="")
pc.setId_pc(Integer.parseInt(cmbIdPc.getSelectedItem().toString()));
else
pc.setId_pc(null);
p.setPc(pc);
}
catch(Exception e)
{
JXErrorDialog.showDialog(null,"Erreur",e);
}
int nb = p.insererPeripherique();
if (nb==1)
{
String requete = "SELECT max(id_peripherique) AS id FROM peripherique";
Gbd gbd = new Gbd();
gbd.connecter();
ResultSet r = gbd.execQuery(requete);
int id_peripherique=0;
try
{
r.next();
id_peripherique = r.getInt("id");
gbd.deconnecter();
}catch(Exception e)
{
System.out.println(e.toString());
}
for (int i=0;i<jTable1.getModel().getRowCount();i++)
{
System.out.println(jTable1.getModel().getValueAt(i,0)+"==>"+jTable1.getModel().getValueAt(i,1));
Propriete prop = new Propriete();
prop.construirePropriete(jTable1.getModel().getValueAt(i,0).toString());
Peripherique_propriete pp = new Peripherique_propriete();
pp.setId_peripherique(id_peripherique);
pp.setId_propriete(prop.getId_propriete());
pp.setValeur(jTable1.getModel().getValueAt(i,1).toString());
pp.insererPeripherique_propriete();
System.out.println("peripherique_propriete = "+pp.getId_peripherique()+"--"+pp.getId_propriete()+"--"+pp.getValeur());
}
Peripherique peripherique = new Peripherique();
peripherique.construirePeripherique(id_peripherique);
v.add(peripherique);
String [] ligne = {
String.valueOf(peripherique.getId_peripherique()),
peripherique.getType_peripherique().getType(),
peripherique.getNom(),
peripherique.getSlot().getType(),
peripherique.getNumero_serie(),
peripherique.getPilote(),
String.valueOf(peripherique.getLieu().getId_lieu()),
String.valueOf(peripherique.getPc().getId_pc())
};
JOptionPane.showConfirmDialog(this, "Le priphrique a t ajout avec succs!","Ajout",JOptionPane.DEFAULT_OPTION);
model.addRow(ligne);
System.out.println("jtable couunt = "+jTable2.getRowCount());
jTable2.setRowSelectionInterval(jTable2.getRowCount()-1, jTable2.getRowCount()-1);
((CardLayout) jPanel7.getLayout()).show(jPanel7,s1);
((CardLayout) cardType.getLayout()).show(cardType,s3);
((CardLayout) cardSlot.getLayout()).show(cardSlot,s5);
((CardLayout) cardIdPc.getLayout()).show(cardIdPc,s7);
txtIdLieu.setEnabled(false);
txtIdPc.setEnabled(false);
txtIdSlot.setEnabled(false);
txtNomPeripherique.setEnabled(false);
txtPc.setEnabled(false);
txtPilote.setEnabled(false);
txtSerial.setEnabled(false);
checkbox1.setEnabled(false);
ajout=false;
jbtAjouter.setText("Nouveau");
}
}
}
public void actionPerformed(java.awt.event.ActionEvent e)
{
if (e.getSource()== jTable1)
{
System.out.println("EVENEMENt !!!!");
}
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JPanel cardIdPc;
private javax.swing.JPanel cardSlot;
private javax.swing.JPanel cardType;
private java.awt.Checkbox checkbox1;
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel10;
private javax.swing.JLabel jLabel11;
private javax.swing.JLabel jLabel12;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel7;
private javax.swing.JLabel jLabel8;
private javax.swing.JLabel jLabel9;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
private javax.swing.JPanel jPanel3;
private javax.swing.JPanel jPanel4;
private javax.swing.JPanel jPanel5;
private javax.swing.JPanel jPanel6;
private javax.swing.JPanel jPanel7;
private javax.swing.JPanel jPanel8;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JScrollPane jScrollPane2;
// private javax.swing.JTable jTable1;
//
// private javax.swing.JTable jTable2;
private javax.swing.JButton jbtAjouter;
private javax.swing.JButton jbtModifier;
private javax.swing.JButton jbtSupprimer;
private javax.swing.JTextField txtIdPeripherique;
private javax.swing.JTextField txtLieu;
private javax.swing.JTextField txtNomPeripherique;
private javax.swing.JTextField txtPc;
private javax.swing.JTextField txtPilote;
private javax.swing.JTextField txtSerial;
private javax.swing.JTextField txtTypeLieu;
// End of variables declaration//GEN-END:variables
public JComboBox getCmbIdPc() {
return cmbIdPc;
}
public void setCmbIdPc(JComboBox cmbIdPc) {
this.cmbIdPc = cmbIdPc;
}
public javax.swing.JTextField getTxtPc() {
return txtPc;
}
public void setTxtPc(javax.swing.JTextField txtPc) {
this.txtPc = txtPc;
}
public javax.swing.JPanel getCardIdPc() {
return cardIdPc;
}
public void setCardIdPc(javax.swing.JPanel cardIdPc) {
this.cardIdPc = cardIdPc;
}
public JTextField getTxtIdLieu() {
return txtIdLieu;
}
public void setTxtIdLieu(JTextField txtIdLieu) {
this.txtIdLieu = txtIdLieu;
}
public javax.swing.JTextField getTxtLieu() {
return txtLieu;
}
public void setTxtLieu(javax.swing.JTextField txtLieu) {
this.txtLieu = txtLieu;
}
public javax.swing.JTextField getTxtTypeLieu() {
return txtTypeLieu;
}
public void setTxtTypeLieu(javax.swing.JTextField txtTypeLieu) {
this.txtTypeLieu = txtTypeLieu;
}
public JComboBox getCmbIdLieu() {
return cmbIdLieu;
}
public void setCmbIdLieu(JComboBox cmbIdLieu) {
this.cmbIdLieu = cmbIdLieu;
}
}
| true |
710b45e22649f2fd3091c3439b61f4b715a042aa | Java | anijadhav/Annotation-Hibernate-5.3.2-with-MySQL-8.0.11 | /Annotation-Hibernate-JDK8-Stream/src/main/java/com/model/Student.java | UTF-8 | 763 | 2.546875 | 3 | [] | no_license | package com.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table
public class Student {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column
private String name;
@Column
private Integer mark;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getMark() {
return mark;
}
public void setMark(Integer mark) {
this.mark = mark;
}
}
| true |
262cbf286e592a76581669d6ff3d18e4aeef0a88 | Java | axlbonnet/GASW | /src/main/java/fr/insalyon/creatis/gasw/execution/GaswMonitor.java | UTF-8 | 6,490 | 1.882813 | 2 | [] | no_license | /* Copyright CNRS-CREATIS
*
* Rafael Ferreira da Silva
* rafael.silva@creatis.insa-lyon.fr
* http://www.rafaelsilva.com
*
* This software is governed by the CeCILL license under French law and
* abiding by the rules of distribution of free software. You can use,
* modify and/ or redistribute the software under the terms of the CeCILL
* license as circulated by CEA, CNRS and INRIA at the following URL
* "http://www.cecill.info".
*
* As a counterpart to the access to the source code and rights to copy,
* modify and redistribute granted by the license, users are provided only
* with a limited warranty and the software's author, the holder of the
* economic rights, and the successive licensors have only limited
* liability.
*
* In this respect, the user's attention is drawn to the risks associated
* with loading, using, modifying and/or developing or reproducing the
* software by the user in light of its specific status of free software,
* that may mean that it is complicated to manipulate, and that also
* therefore means that it is reserved for developers and experienced
* professionals having in-depth computer knowledge. Users are therefore
* encouraged to load and test the software's suitability as regards their
* requirements in conditions enabling the security of their systems and/or
* data to be ensured and, more generally, to use and operate it in the
* same conditions as regards security.
*
* The fact that you are presently reading this means that you have had
* knowledge of the CeCILL license and that you accept its terms.
*/
package fr.insalyon.creatis.gasw.execution;
import fr.insalyon.creatis.gasw.GaswConfiguration;
import fr.insalyon.creatis.gasw.GaswException;
import fr.insalyon.creatis.gasw.bean.Job;
import fr.insalyon.creatis.gasw.dao.DAOException;
import fr.insalyon.creatis.gasw.dao.DAOFactory;
import fr.insalyon.creatis.gasw.dao.JobDAO;
import fr.insalyon.creatis.gasw.dao.NodeDAO;
import fr.insalyon.creatis.gasw.plugin.ListenerPlugin;
import java.util.Date;
import java.util.List;
/**
*
* @author Rafael Ferreira da Silva
*/
public abstract class GaswMonitor extends Thread {
private volatile static int INVOCATION_ID = 1;
protected JobDAO jobDAO;
protected NodeDAO nodeDAO;
protected GaswMonitor() {
try {
jobDAO = DAOFactory.getDAOFactory().getJobDAO();
nodeDAO = DAOFactory.getDAOFactory().getNodeDAO();
} catch (DAOException ex) {
// do nothing
}
}
/**
* Adds a job to the database.
*
* @param job
* @param fileName
*/
protected synchronized void add(Job job) throws GaswException {
try {
// Defining invocation ID
List<Job> list = jobDAO.getByParameters(job.getParameters());
if (!list.isEmpty()) {
job.setInvocationID(list.get(0).getInvocationID());
} else {
job.setInvocationID(INVOCATION_ID++);
}
job.setCreation(new Date());
jobDAO.add(job);
// Listeners notification
for (ListenerPlugin listener : GaswConfiguration.getInstance().getListenerPlugins()) {
listener.jobSubmitted(job);
}
} catch (DAOException ex) {
throw new GaswException(ex);
}
}
/**
* Adds a job to be monitored. It should constructs a Job object and invoke
* the protected method add(job).
*
* @param jobID
* @param symbolicName
* @param fileName
* @throws GaswException
*/
public abstract void add(String jobID, String symbolicName, String fileName,
String parameters) throws GaswException;
/**
* Updates the job status and notifies listeners.
*
* @param job
* @throws DAOException
*/
protected void updateStatus(Job job) throws GaswException, DAOException {
for (ListenerPlugin listener : GaswConfiguration.getInstance().getListenerPlugins()) {
listener.jobStatusChanged(job);
}
jobDAO.update(job);
}
/**
* Verifies if there are signaled jobs.
*/
protected void verifySignaledJobs() {
try {
// Replicate jobs
for (Job job : jobDAO.getJobs(GaswStatus.REPLICATE)) {
replicate(job);
}
// Kill job replicas
for (Job job : jobDAO.getJobs(GaswStatus.KILL_REPLICA)) {
job.setStatus(GaswStatus.CANCELLED_REPLICA);
jobDAO.update(job);
kill(job);
}
// Kill jobs
for (Job job : jobDAO.getJobs(GaswStatus.KILL)) {
kill(job);
}
// Reschedule jobs
for (Job job : jobDAO.getJobs(GaswStatus.RESCHEDULE)) {
reschedule(job);
}
// Resume held jobs
for (Job job : jobDAO.getJobs(GaswStatus.UNHOLD_ERROR)) {
job.setStatus(GaswStatus.ERROR);
jobDAO.update(job);
resume(job);
}
for (Job job : jobDAO.getJobs(GaswStatus.UNHOLD_STALLED)) {
job.setStatus(GaswStatus.STALLED);
jobDAO.update(job);
resume(job);
}
} catch (DAOException ex) {
// do nothing
}
}
/**
* Verifies if a job is replica and handles it in case it is.
*
* @param job
* @return
* @throws GaswException
* @throws DAOException
*/
protected boolean isReplica(Job job) throws GaswException, DAOException {
if (jobDAO.getNumberOfCompletedJobsByInvocationID(job.getInvocationID()) > 0) {
job.setStatus(GaswStatus.CANCELLED_REPLICA);
job.setEnd(new Date());
updateStatus(job);
return true;
}
return false;
}
/**
* Kills a job.
*
* @param jobID
*/
protected abstract void kill(Job job);
/**
* Reschedule a job.
*
* @param jobID
*/
protected abstract void reschedule(Job job);
/**
* Replicates a job.
*
* @param jobID
*/
protected abstract void replicate(Job job);
/**
* Kills job replicas.
*
* @param invocationID
*/
protected abstract void killReplicas(Job job);
/**
* Resumes a job.
*
* @param jobID
*/
protected abstract void resume(Job job);
}
| true |
d67d3f4a5016a93f1b666932775e08fe3ff59e0f | Java | bakhtiyar-s/NewsAppJavaEE | /newsapp-services/src/main/java/security/UserIdentityStore.java | UTF-8 | 1,535 | 2.453125 | 2 | [] | no_license | package security;
import entity.Role;
import entity.User;
import org.slf4j.Logger;
import service.UserService;
import javax.inject.Inject;
import javax.persistence.NoResultException;
import javax.security.auth.login.CredentialException;
import javax.security.enterprise.credential.Credential;
import javax.security.enterprise.credential.UsernamePasswordCredential;
import javax.security.enterprise.identitystore.CredentialValidationResult;
import javax.security.enterprise.identitystore.IdentityStore;
import java.util.Set;
import java.util.stream.Collectors;
import static javax.security.enterprise.identitystore.CredentialValidationResult.INVALID_RESULT;
public class UserIdentityStore implements IdentityStore {
@Inject
private UserService userService;
@Inject
private Logger logger;
@Override
public CredentialValidationResult validate(Credential credential) {
String caller = ((UsernamePasswordCredential)credential).getCaller();
try {
User user = userService.authenticate(caller, ((UsernamePasswordCredential)credential).getPasswordAsString());
Set<String> roles = user.getRoles().stream().map(Role::getRoleName).collect(Collectors.toSet());
return new CredentialValidationResult(caller, roles);
} catch (NoResultException e) {
logger.error("User {} not found", caller);
} catch (CredentialException e) {
logger.error("Wrong password for user {}", caller);
}
return INVALID_RESULT;
}
}
| true |
a8d4c516588497781885f3e96f7993c949535bf0 | Java | jojosif/submit | /submission/Support Analysis/src/Twitter3Mapper.java | UTF-8 | 3,777 | 2.390625 | 2 | [] | no_license | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;
import java.util.HashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.commons.lang.StringUtils;
public class Twitter3Mapper extends Mapper<Object, Text, Text, IntWritable> {
private HashMap<String, String> countryCodes;
@Override
protected void setup(Context context) throws IOException, InterruptedException {
countryCodes = new HashMap<String, String>();
// We know there is only one cache file, so we only retrieve that URI
URI fileUri = context.getCacheFiles()[0];
FileSystem fs = FileSystem.get(context.getConfiguration());
FSDataInputStream in = fs.open( new Path(fileUri) );
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String line = null;
try {
br.readLine();
while ((line = br.readLine()) != null) {
String [] arr= line.split(" ");
if(arr.length == 11){
String g = arr[0];
if(g.length() > 3){
String twoLetterCode = g.substring(g.length()-2);
String threeLetterCode = arr[2];
String fullName = g.substring(0,g.length()-2);
countryCodes.put(twoLetterCode, fullName);
countryCodes.put(threeLetterCode, fullName);
countryCodes.put(fullName, fullName);
}
} else if(arr.length == 12){
String g = arr[1];
if(g.length() > 3){
String twoLetterCode = g.substring(g.length()-2);
String threeLetterCode = arr[3];
String fullName = arr[0] + " " + g.substring(0,g.length()-2);
countryCodes.put(twoLetterCode, fullName);
countryCodes.put(threeLetterCode, fullName);
countryCodes.put(fullName, fullName);
}
}
}
br.close();
} catch (IOException e1) {
}
super.setup(context);
}
private final IntWritable one = new IntWritable(1);
private Text data = new Text();
public void map(Object key, Text value, Context context) throws IOException, InterruptedException {
// Format per tweet is id;date;hashtags;tweet;
String dump = value.toString();
int startIndex;
int endIndex;
if(StringUtils.ordinalIndexOf(dump,";",4)>-1){
startIndex = StringUtils.ordinalIndexOf(dump,";",2) + 1;
endIndex = StringUtils.ordinalIndexOf(dump,";",3) + 1;
String hashtags = dump.substring(startIndex, endIndex);
Pattern p = Pattern.compile("(go|team)(\\w+)");
Matcher m = p.matcher(hashtags);
String countryCode;
if(checkForAscii(hashtags)){
while (m.find()) {
countryCode = m.group(2);
if(countryCodes.containsKey(countryCode)){
data.set(countryCodes.get(countryCode));
context.write(data, one);
}
}
}
}
}
public static boolean checkForAscii(String tweet) {
for (char c: tweet.toCharArray()){
if (((int)c)>127){
return false;
}
}
return true;
}
} | true |
1227824aab35803b51077a2c48ac48b3ffa3066e | Java | zhangyangjing/weather | /app/src/main/java/com/zhangyangjing/weather/ui/ActivityGuide.java | UTF-8 | 3,682 | 1.90625 | 2 | [] | no_license | package com.zhangyangjing.weather.ui;
import android.accounts.Account;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import com.zhangyangjing.weather.R;
import com.zhangyangjing.weather.provider.weather.WeatherContract;
import com.zhangyangjing.weather.service.DataBootstrapService;
import com.zhangyangjing.weather.settings.SettingsUtil;
import com.zhangyangjing.weather.util.AccountUtil;
import butterknife.ButterKnife;
import butterknife.OnClick;
public class ActivityGuide extends AppCompatActivity {
private static final String TAG = ActivityGuide.class.getSimpleName();
private boolean mVisible = false;
private boolean mUIFinish = false;
private boolean mBGFinish = false;
private boolean mRegiested = false;
private MyBroadcastReceiver myBroadcastReceiver = new MyBroadcastReceiver();
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SettingsUtil.setCurrentCity(this, "CN101120501"); // TODO: JUST FOR TEST
if (false == DataBootstrapService.startDatastrapIfNecessary(this)) {
startMainActivityAndFinish();
return;
}
setContentView(R.layout.activity_guide);
ButterKnife.bind(this);
initSync();
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(DataBootstrapService.ACTION_IMPORT_FINISH);
registerReceiver(myBroadcastReceiver, intentFilter);
mRegiested = true;
}
@Override
protected void onResume() {
super.onPostResume();
mVisible = true;
startMainActivityAndFinishIFNeed();
}
@Override
protected void onPause() {
super.onPause();
mVisible = false;
}
@Override
protected void onDestroy() {
super.onDestroy();
if (mRegiested)
unregisterReceiver(myBroadcastReceiver);
}
@OnClick(R.id.dummy_button)
public void onClick(View view) {
mUIFinish = true;
startMainActivityAndFinishIFNeed();
}
private void startMainActivityAndFinishIFNeed() {
if (mUIFinish && mBGFinish)
startMainActivityAndFinish();
}
private void startMainActivityAndFinish() {
startActivity(new Intent(this, ActivityMain.class));
if (mRegiested) {
unregisterReceiver(myBroadcastReceiver);
mRegiested = false;
}
finish();
}
private void initSync() {
Account account = AccountUtil.getSyncAccount(this);
getContentResolver().setSyncAutomatically(account, WeatherContract.CONTENT_AUTHORITY, true);
getContentResolver().setIsSyncable(account, WeatherContract.CONTENT_AUTHORITY, 1);
getContentResolver().setMasterSyncAutomatically(true);
Bundle bundle = new Bundle();
getContentResolver().addPeriodicSync(account, WeatherContract.CONTENT_AUTHORITY, bundle, 1);
}
private class MyBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Log.v(TAG, "onReceive:" + intent.getAction());
if (false == intent.getAction().equals(DataBootstrapService.ACTION_IMPORT_FINISH))
return;
mBGFinish = true;
if (true == mVisible)
startMainActivityAndFinishIFNeed();
}
}
}
| true |
dbedc26227659942ab9dac979d66830b6425adc4 | Java | nostra/semimeter | /semimeter-web/src/main/java/org/semispace/semimeter/bean/DisplayIntent.java | UTF-8 | 227 | 2.140625 | 2 | [] | no_license | package org.semispace.semimeter.bean;
public class DisplayIntent {
private final String key;
public DisplayIntent(String key) {
this.key = key;
}
public String getKey() {
return key;
}
}
| true |
1fd267a24f32c88301319747401cdf872d2e75d1 | Java | leizixing0622/MyApplication2 | /app/src/main/java/com/example/john/myapplication/model/CardItem.java | UTF-8 | 590 | 2.90625 | 3 | [] | no_license | package com.example.john.myapplication.model;
/**
* Created by Administrator on 2017/5/6.
*/
public class CardItem {
private Fruit fruit;
private int amount;
public CardItem(int amount, Fruit fruit) {
this.amount = amount;
this.fruit = fruit;
}
public Fruit getFruit() {
return fruit;
}
public int getAmount() {
return amount;
}
@Override
public String toString() {
return "CardItem{" +
"fruit=" + fruit.toString() +
", amount=" + amount +
'}';
}
}
| true |
d91dd0076e0052a8b814516a61892f8fc2d0633d | Java | thetravisw/data-structures-and-algorithms | /Tests/OldStuff/Whiteboard04_LargestProduct/Whiteboard04_LargestProductTest.java | UTF-8 | 515 | 2.90625 | 3 | [
"MIT"
] | permissive | //package OldStuff.Whiteboard04_LargestProduct;
//
//import org.junit.jupiter.api.Test;
//
//import java.util.Collections;
//
//import static org.junit.jupiter.api.Assertions.*;
//
//class Whiteboard04_LargestProductTest {
//
// @Test
// void largestProduct() {
// int[][] data = {
// {1, 2, 1},
// {2, 4, 2},
// {3, 6, 8},
// {7, 8, 1}
// };
// int result = Collections.max(set);
// assertEquals(64, result);
// }
//} | true |
66c4bad11bd8028a4a9cbb23eb5d8848c384021b | Java | leimingfu/QQ_Chat | /app/src/main/java/com/example/SQLite/sql_exist.java | UTF-8 | 1,086 | 2.359375 | 2 | [] | no_license | package com.example.SQLite;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import com.example.Fragment.ChatDBOpenHelper;
import com.example.Login.Register;
import org.apache.http.client.fluent.Content;
public class sql_exist {
/**
* 判断某张表是否存在
* @param DBname 表名
* @return
*/
public static boolean tabbleIsExist(MyHelper myHelper,String DBname) {
boolean result = false;
if (DBname == null) {
return false;
}
SQLiteDatabase db = null;
Cursor cursor = null;
try {
db = myHelper.getReadableDatabase();
String sql = "select count(*) as c from Sqlite_master where type ='table' and name ='" + DBname.trim() + "' ";
cursor = db.rawQuery(sql, null);
if (cursor.moveToNext()) {
int count = cursor.getInt(0);
if (count > 0) {
result = true;
}
}
} catch (Exception e) {
}
return result;
}
}
| true |
f7e190b4d612a1b4967519326c180515aaef62fe | Java | toast-tk/toast-tk-agent | /toast-tk-web-agent/src/test/java/io/toast/tk/agent/record/FakeKryoServer.java | UTF-8 | 531 | 1.914063 | 2 | [
"Apache-2.0"
] | permissive | package io.toast.tk.agent.record;
import io.toast.tk.agent.web.IAgentServer;
import io.toast.tk.core.agent.interpret.WebEventRecord;
public class FakeKryoServer implements IAgentServer{
public WebEventRecord event;
@Override
public void sendEvent(WebEventRecord adjustedEvent, String ApiKey) {
this.event = adjustedEvent;
}
@Override
public boolean register(String ApiKey) {
// TODO Auto-generated method stub
return true;
}
@Override
public void unRegister() {
// TODO Auto-generated method stub
}
}
| true |
8d4b8d3a58b407f13a69228931c84222c17afbd4 | Java | sams2000/leetcode | /src/com/example/leet/PathOfConvertingPermutationWords.java | UTF-8 | 1,291 | 3.84375 | 4 | [] | no_license |
package com.example.leet;
import java.util.ArrayList;
/**
* Given two strings that are the permutation to each other. You can swap two
* adjacent character a time, print the path of how one string converts to
* another.
*
* @author bin zhou
* @since 2016-02-03
*/
public class PathOfConvertingPermutationWords {
public static void main(String[] args) {
System.out.println(pathSwap("ABCDE", "DEACB"));
}
public static ArrayList<String> pathSwap(String s1, String s2){
ArrayList<String> result = new ArrayList<String>();
result.add(s1);
char[] c1 = s1.toCharArray();
char[] c2 = s2.toCharArray();
int j=0; //as the destination string index
while (j<c2.length){
while(j<c2.length && c1[j] == c2[j]) j++;
int i=j;
while (i<c1.length && c1[i] != c2[j]) i++;
//swap s1 character at i with i-1
while (i>j){
char tmp = c1[i-1];
c1[i-1] = c1[i];
c1[i] = tmp;
result.add(new String(c1));
i--;
}
j++;
}
return result;
}
}
| true |
cc7729ba4e909c49679b7c1a1c0407a56a589fe5 | Java | Mclord1/LagosTourGuide | /app/src/main/java/com/example/android/tourguide/PlacesFragment.java | UTF-8 | 4,532 | 2.15625 | 2 | [] | no_license | package com.example.android.tourguide;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.AudioManager;
import android.media.MediaPlayer;
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.AdapterView;
import android.widget.ListView;
import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
/**
* A simple {@link Fragment} subclass.
*/
@SuppressWarnings("ALL")
public class PlacesFragment extends Fragment {
public PlacesFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.words_list, container, false);
// Get the description strings
String bogobiri = getResources().getString(R.string.bogobiri_text);
String freedomPark = getResources().getString(R.string.freedom_park);
String terraKulture = getResources().getString(R.string.terra_kulture);
String pattaya = getResources().getString(R.string.pattaya);
String emberCreek = getResources().getString(R.string.ember_creek);
String maryLandMall = getResources().getString(R.string.maryland_mall);
String tarkwaBay = getResources().getString(R.string.tarkwaBay);
String releArtGallery = getResources().getString(R.string.releArtGallery);
// Create an array of words
final ArrayList<CardItem> cardItems = new ArrayList<>();
cardItems.add(new CardItem("Bogobiri House", "Lagos", "9am - 9pm", R.drawable.bogobirihouse, bogobiri, "7 Maitama Sule Street, Lagos", "07030754382"));
cardItems.add(new CardItem("Freedom Park", "Lagos", "10am - 11pm", R.drawable.lagosfreedom, freedomPark, "1, Hospital Road, Old Prison Ground, Broad Street, Lagos Island, Lagos", "07030700082"));
cardItems.add(new CardItem("Maryland Mall", "Lagos", "10am - 9pm", R.drawable.marylandmall, maryLandMall, "350 – 360, Ikorodu Road, Anthony Village, Lagos", "07030700082"));
cardItems.add(new CardItem("Tarkwa Bay", "Lagos", "24 Hrs", R.drawable.tarkwabay, tarkwaBay, "Tarkwa Bay Island", "07030700082"));
cardItems.add(new CardItem("Terra Kulture", "Lagos", "9am - 9pm", R.drawable.terrakulture, terraKulture, "1376 Tiamiyu Savage Street, Victoria Island Lagos", "07030700082"));
cardItems.add(new CardItem("Lotus at Pattaya Bar-Lounge", "Lagos", "2pm - 12am", R.drawable.lotusatpattayabar, pattaya, "30, Adeola Hopewell, Victoria Island, Lagos", "07030700082"));
cardItems.add(new CardItem("Ember Creek Waterfront", "Lagos", "2pm - 5am", R.drawable.mbe, emberCreek, "32, Awolowo Road, Obalende, Ikoyi, Lagos", "07030700082"));
cardItems.add(new CardItem("Rele Art Gallery", "Lagos", "12pm - 6pm", R.drawable.releartgallery, releArtGallery, "5, Military Street, Onikan Environment, Lagos", "07030700082"));
CardItemAdapter itemsAdapter = new CardItemAdapter(getActivity(), cardItems);
ListView listView = (ListView) rootView.findViewById(R.id.list);
if (listView != null) {
listView.setAdapter(itemsAdapter);
}
if (listView != null) {
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
CardItem cardItem = cardItems.get(position);
// Create a new intent to open places activity
Intent newIntent = new Intent(getContext(), PlacesActivity.class);
newIntent.putExtra("TITLE", cardItem.getName());
newIntent.putExtra("ADDRESS" , cardItem.getAddress());
newIntent.putExtra("CITY", cardItem.getCity());
newIntent.putExtra("TIME", cardItem.getTime());
newIntent.putExtra("NUMBER", cardItem.getPhoneNumber());
newIntent.putExtra("DESCRIPTION", cardItem.getDescription());
newIntent.putExtra("IMAGE", cardItem.getImageResourceId());
startActivity(newIntent);
}
});
}
return rootView;
}
}
| true |
bbff4099a01f5582c8c87c807be83f1cd93d76ef | Java | asiekierka/Zetta-Industries | /src/main/java/com/bymarcin/zettaindustries/mods/ocwires/item/ItemTelecommunicationWire.java | UTF-8 | 7,309 | 1.851563 | 2 | [
"Zlib"
] | permissive | package com.bymarcin.zettaindustries.mods.ocwires.item;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import blusunrize.immersiveengineering.api.Lib;
import blusunrize.immersiveengineering.api.energy.wires.IImmersiveConnectable;
import blusunrize.immersiveengineering.api.energy.wires.IWireCoil;
import blusunrize.immersiveengineering.api.energy.wires.ImmersiveNetHandler;
import blusunrize.immersiveengineering.api.energy.wires.WireType;
import com.bymarcin.zettaindustries.ZettaIndustries;
import com.bymarcin.zettaindustries.basic.BasicItem;
import com.bymarcin.zettaindustries.mods.ocwires.TelecommunicationWireType;
import net.minecraft.block.state.IBlockState;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.EnumActionResult;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.EnumHand;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.Vec3d;
import net.minecraft.util.text.TextComponentTranslation;
import net.minecraft.util.text.translation.I18n;
import net.minecraft.world.World;
import blusunrize.immersiveengineering.api.TargetingInfo;
import blusunrize.immersiveengineering.common.IESaveData;
import blusunrize.immersiveengineering.common.blocks.metal.TileEntityConnectorLV;
import blusunrize.immersiveengineering.common.util.IEAchievements;
import blusunrize.immersiveengineering.common.util.ItemNBTHelper;
import blusunrize.immersiveengineering.common.util.Utils;
public class ItemTelecommunicationWire extends BasicItem implements IWireCoil {
public ItemTelecommunicationWire() {
super("telecommunicationwire");
setMaxStackSize(64);
setNoRepair();
}
@Override
public int getDamage(ItemStack stack) {
return 0;
}
@SuppressWarnings({ "unchecked", "rawtypes" })
@Override
public void addInformation(ItemStack stack, EntityPlayer player, List list, boolean adv)
{
list.add(I18n.translateToLocal("tooltip.coil.info0"));
list.add(I18n.translateToLocal("tooltip.coil.info1"));
if(stack.getTagCompound()!=null && stack.getTagCompound().hasKey("linkingPos"))
{
int[] link = stack.getTagCompound().getIntArray("linkingPos");
if(link!=null&&link.length>3)
list.add(I18n.translateToLocalFormatted("tooltip.coil.attachedTo", link[1],link[2],link[3],link[0]));
}
}
//copied from "vanilla" IE
@Override
public EnumActionResult onItemUseFirst(ItemStack stack, EntityPlayer player, World world, BlockPos pos, EnumFacing side, float hitX, float hitY, float hitZ, EnumHand hand) {
if(!world.isRemote) {
TileEntity tileEntity = world.getTileEntity(pos);
if(tileEntity instanceof IImmersiveConnectable && ((IImmersiveConnectable)tileEntity).canConnect()) {
TargetingInfo target = new TargetingInfo(side, hitX,hitY,hitZ);
WireType wire = getWireType(stack);
BlockPos masterPos = ((IImmersiveConnectable)tileEntity).getConnectionMaster(wire, target);
tileEntity = world.getTileEntity(masterPos);
if( !(tileEntity instanceof IImmersiveConnectable) || !((IImmersiveConnectable)tileEntity).canConnect()) {
return EnumActionResult.PASS;
}
if( !((IImmersiveConnectable)tileEntity).canConnectCable(wire, target)) {
player.addChatMessage(new TextComponentTranslation(Lib.CHAT_WARN+"wrongCable"));
return EnumActionResult.FAIL;
}
if(!ItemNBTHelper.hasKey(stack, "linkingPos")) {
ItemNBTHelper.setIntArray(stack, "linkingPos", new int[]{world.provider.getDimension(),masterPos.getX(),masterPos.getY(),masterPos.getZ()});
target.writeToNBT(stack.getTagCompound());
} else {
WireType type = getWireType(stack);
int[] array = ItemNBTHelper.getIntArray(stack, "linkingPos");
BlockPos linkPos = new BlockPos(array[1],array[2],array[3]);
TileEntity tileEntityLinkingPos = world.getTileEntity(linkPos);
int distanceSq = (int) Math.ceil( linkPos.distanceSq(masterPos) );
if(array[0]!=world.provider.getDimension()) {
player.addChatMessage(new TextComponentTranslation(Lib.CHAT_WARN+"wrongDimension"));
} else if(linkPos.equals(masterPos)) {
player.addChatMessage(new TextComponentTranslation(Lib.CHAT_WARN+"sameConnection"));
} else if( distanceSq > (type.getMaxLength()*type.getMaxLength())) {
player.addChatMessage(new TextComponentTranslation(Lib.CHAT_WARN+"tooFar"));
} else if(!(tileEntityLinkingPos instanceof IImmersiveConnectable)) {
player.addChatMessage(new TextComponentTranslation(Lib.CHAT_WARN+"invalidPoint"));
} else {
IImmersiveConnectable nodeHere = (IImmersiveConnectable)tileEntity;
IImmersiveConnectable nodeLink = (IImmersiveConnectable)tileEntityLinkingPos;
boolean connectionExists = false;
Set<ImmersiveNetHandler.Connection> outputs = ImmersiveNetHandler.INSTANCE.getConnections(world, Utils.toCC(nodeHere));
if(outputs!=null) {
for(ImmersiveNetHandler.Connection con : outputs) {
if(con.end.equals(Utils.toCC(nodeLink))) {
connectionExists = true;
}
}
}
if(connectionExists) {
player.addChatMessage(new TextComponentTranslation(Lib.CHAT_WARN+"connectionExists"));
} else {
Vec3d rtOff0 = nodeHere.getRaytraceOffset(nodeLink).addVector(masterPos.getX(), masterPos.getY(), masterPos.getZ());
Vec3d rtOff1 = nodeLink.getRaytraceOffset(nodeHere).addVector(linkPos.getX(), linkPos.getY(), linkPos.getZ());
Set<BlockPos> ignore = new HashSet<>();
ignore.addAll(nodeHere.getIgnored(nodeLink));
ignore.addAll(nodeLink.getIgnored(nodeHere));
boolean canSee = Utils.rayTraceForFirst(rtOff0, rtOff1, world, ignore)==null;
if(canSee) {
TargetingInfo targetLink = TargetingInfo.readFromNBT(stack.getTagCompound());
ImmersiveNetHandler.INSTANCE.addConnection(world, Utils.toCC(nodeHere), Utils.toCC(nodeLink), (int)Math.sqrt(distanceSq), type);
nodeHere.connectCable(type, target, nodeLink);
nodeLink.connectCable(type, targetLink, nodeHere);
IESaveData.setDirty(world.provider.getDimension());
player.addStat(IEAchievements.connectWire);
if(!player.capabilities.isCreativeMode) {
stack.stackSize--;
}
((TileEntity)nodeHere).markDirty();
world.addBlockEvent(masterPos, ((TileEntity) nodeHere).getBlockType(), -1, 0);
IBlockState state = world.getBlockState(masterPos);
world.notifyBlockUpdate(masterPos, state,state, 3);
((TileEntity)nodeLink).markDirty();
world.addBlockEvent(linkPos, ((TileEntity) nodeLink).getBlockType(), -1, 0);
state = world.getBlockState(linkPos);
world.notifyBlockUpdate(linkPos, state,state, 3);
} else {
player.addChatMessage(new TextComponentTranslation(Lib.CHAT_WARN+"cantSee"));
}
}
}
ItemNBTHelper.remove(stack, "linkingPos");
ItemNBTHelper.remove(stack, "side");
ItemNBTHelper.remove(stack, "hitX");
ItemNBTHelper.remove(stack, "hitY");
ItemNBTHelper.remove(stack, "hitZ");
}
return EnumActionResult.SUCCESS;
}
}
return EnumActionResult.PASS;
}
@Override
public WireType getWireType(ItemStack arg) {
return TelecommunicationWireType.TELECOMMUNICATION;
}
}
| true |
a5a0b0cab0622bb22996026af4b03330f1ee99be | Java | rvanasa/TerminalNumerics | /terminal-numerics/src/main/java/rchs/tsa/math/interpreter/sequence/OperatorResolver.java | UTF-8 | 866 | 2.5 | 2 | [] | no_license | package rchs.tsa.math.interpreter.sequence;
import net.anasa.util.Checks;
import net.anasa.util.data.resolver.IToken;
import net.anasa.util.data.resolver.ResolverException;
import rchs.tsa.math.expression.IOperator;
import rchs.tsa.math.expression.MathData;
import rchs.tsa.math.sequence.ExpressionTokenType;
public class OperatorResolver implements ITypeResolver<IOperator>
{
private final MathData mathData;
public OperatorResolver(MathData mathData)
{
this.mathData = mathData;
}
public MathData getMathData()
{
return mathData;
}
@Override
public ExpressionTokenType getType()
{
return ExpressionTokenType.OPERATOR;
}
@Override
public IOperator resolve(IToken item) throws ResolverException
{
return Checks.checkNotNull(getMathData().getOperator(item.getData()), new ResolverException("Invalid operator: " + item.getData()));
}
}
| true |
9ef8a93fa13b8c11a731a808885bb1120e27743b | Java | chu-Ian/SelfStudy_1 | /tensquare_base/src/main/java/com/tensquare/base/service/LabelService.java | UTF-8 | 878 | 2.25 | 2 | [] | no_license | package com.tensquare.base.service;
import com.tensquare.base.po.Label;
import org.springframework.data.domain.Page;
import java.util.List;
import java.util.Map;
public interface LabelService {
/**
* 保存一个标签
*
* @param label
*/
void saveLabel(Label label);
/**
* 更新一个标签
*
* @param label
*/
void updateLabel(Label label);
/**
* 删除一个标签
*
* @param id
*/
void deleteLabelById(String id);
/**
* 查询全部的标签
*
* @return
*/
List<Label> findLabelList();
/**
* 根据ID查询标签
*
* @param id
* @return
*/
Label findLabelById(String id);
List<Label> findLabelByParams(Map<String, Object> params);
Page<Label> findLabelByPage(Map<String, Object> params, int page, int size);
}
| true |
794641b7f6685a84f519ebd797d9918fcb92b54e | Java | Blizzard0409/gulimall | /gulimall_/gulimall-order/src/main/java/com/xmh/gulimall/order/service/OrderReturnApplyService.java | UTF-8 | 461 | 1.523438 | 2 | [
"Apache-2.0"
] | permissive | package com.xmh.gulimall.order.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.xmh.common.utils.PageUtils;
import com.xmh.gulimall.order.entity.OrderReturnApplyEntity;
import java.util.Map;
/**
* 订单退货申请
*
* @author xmh
* @email 1264551979@qq.com
* @date 2021-07-27 12:32:34
*/
public interface OrderReturnApplyService extends IService<OrderReturnApplyEntity> {
PageUtils queryPage(Map<String, Object> params);
}
| true |
e5074e8a066711407e4ad7353edae41769e6939c | Java | trmiller10/tiy-MicroblogSpring | /src/main/java/com/theironyard/MessageRepository.java | UTF-8 | 338 | 1.679688 | 2 | [] | no_license | package com.theironyard;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import java.util.List;
/**
* Created by Taylor on 5/21/16.
*/
public interface MessageRepository extends CrudRepository<Message, Integer> {
//List<Message> findById(String message, int id);
} | true |