text
stringlengths 10
2.72M
|
|---|
package com.blog.util;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
public class HibernateSessionFactory {
//引入sessionFactory工厂
private static SessionFactory sessionFactory;
//构造Configuration配置
private static Configuration configuration = new Configuration();
//定义一个threadlocal对象用于存放session
private static ThreadLocal<Session> threadLocal =new ThreadLocal<>();
//构建SessionFactory的静态块
static {
//读取放在classpath下的全局文件 .cgf.xml
configuration.configure();
//构造serviceRegistry对象(注册服务),通过classpath下的全局文件.cgf.xml的配置建立起注册服务
StandardServiceRegistry serviceRegistry= new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
//生成一个sessionFactory
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
}
//获取session对象
public static Session getSession() {
Session session = threadLocal.get();
if(null==session||session.isOpen()) {
if(sessionFactory==null) {
rebuildSessionFactory();
}
}
//如果sessionFactory不为空,就打开session,然后将其赋给session
session=(sessionFactory!=null)?sessionFactory.openSession():null;
//将session设置到threadlocal中
threadLocal.set(session);
return session;
}
//重建sessionFactory
private static void rebuildSessionFactory() {
configuration.configure();
StandardServiceRegistry serviceRegistry= new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
}
//关闭session、SessionFactory
public static void close() {
/**
* 将threadlocal的值赋给session然后将threadlocal的值设为空,如果session的值不为空则关闭session
*/
Session session = threadLocal.get();
threadLocal.set(null);
if(session!=null) {
session.close();
}
sessionFactory.close();
}
}
|
package GUI;
import Controller.HelperObjects.RegistrarFacilityDBEntry;
import Controller.HelperObjects.RegistrarUserDBEntry;
import Controller.RegistrarController;
import javafx.application.Platform;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.scene.control.Alert;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import java.util.ArrayList;
public class AppController {
private RegistrarController registrarController;
@FXML
TableView authenticatedUsersTableView;
@FXML
TableView authenticatedFacilitiesTableView;
public void setRegistrarController(RegistrarController registrarController) {
this.registrarController = registrarController;
}
public void showAuthenticatedUsers(ArrayList<RegistrarUserDBEntry> allRegisteredUsers) {
try {
Platform.runLater(new Runnable() {
@Override public void run() {
TableColumn userIdentifierColumn = new TableColumn("User identifier");
userIdentifierColumn.setMinWidth(100);
userIdentifierColumn.setCellValueFactory(
new PropertyValueFactory<RegistrarUserDBEntry, String>("userIdentifier"));
ObservableList entries = FXCollections.observableArrayList(allRegisteredUsers);
authenticatedUsersTableView.getColumns().clear();
authenticatedUsersTableView.getItems().clear();
authenticatedUsersTableView.getColumns().addAll(userIdentifierColumn);
authenticatedUsersTableView.getItems().addAll(entries);
}
});
} catch (Exception e) {
Alert alert = new Alert(Alert.AlertType.ERROR);
alert.setTitle("ERROR");
alert.setHeaderText(null);
alert.setContentText(e.getMessage());
alert.show();
return;
}
}
public void showAuthenticatedFacilities(ArrayList<RegistrarFacilityDBEntry> allRegisteredFacilities) {
Platform.runLater(new Runnable() {
@Override public void run() {
TableColumn facilityIdentifierColumn = new TableColumn("Facility identifier");
facilityIdentifierColumn.setMinWidth(100);
facilityIdentifierColumn.setCellValueFactory(
new PropertyValueFactory<RegistrarUserDBEntry, String>("facilityIdentifier"));
ObservableList entries = FXCollections.observableArrayList(allRegisteredFacilities);
authenticatedFacilitiesTableView.getColumns().clear();
authenticatedFacilitiesTableView.getItems().clear();
authenticatedFacilitiesTableView.getColumns().addAll(facilityIdentifierColumn);
authenticatedFacilitiesTableView.getItems().addAll(entries);
registrarController.refreshPrimaryStage();
}
});
}
}
|
package com.Igor.SpringMPS;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
public class SpringMPSServiceServletInitializer extends SpringBootServletInitializer {
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder builder){
return builder.sources(SpringMpsApplication.class);
}
}
|
package com.hit.neuruimall.controller;
import com.hit.neuruimall.model.UserModel;
import com.hit.neuruimall.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import java.util.Date;
import java.util.List;
@RestController
public class UserController {
@Autowired
private IUserService userService;
@GetMapping("/getAllUser")
public List<UserModel> getAllUser() {
return userService.getByAll();
}
@GetMapping("/getAllId")
public List<Integer> getAllId() {
return userService.getAllId();
}
@GetMapping("/getAddress")
public List<UserModel> getAllUserWithAddress() {
return userService.getByAllWithAddress();
}
@GetMapping("/getById")
public UserModel getById(Integer id) {
return userService.getById(id);
}
@PostMapping("/insertUser")
public boolean insertUser(UserModel userModel) {
// System.out.println(userModel);
userService.insert(userModel);
return true;
}
@PostMapping("/updateUser")
public boolean updateUser(UserModel userModel) {
userService.update(userModel);
return true;
}
@RequestMapping("/deleteUser/{id}")
public List<UserModel> deleteById(@PathVariable("id") Integer id) {
// System.out.println(id);
userService.deleteById(id);
return userService.getByAll();
}
@PostMapping("/getUserDynamic")
public List<UserModel> getDynamic(String username, Integer minAge, Integer maxAge, @RequestParam(required=false) @DateTimeFormat(pattern="yyyy/MM/dd") Date startDate, @RequestParam(required=false) @DateTimeFormat(pattern="yyyy/MM/dd") Date endDate) {
return userService.getDynamic(username, minAge, maxAge, startDate, endDate);
}
}
|
package com.example.mrlago.myapplicationone;
import android.content.Intent;
import android.database.Cursor;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class AlterActivity extends AppCompatActivity {
EditText nome;
EditText telefone;
Button alterar;
Button deletar;
Cursor cursor;
BaseController crud;
String codigo;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_alter);
codigo = this.getIntent().getStringExtra("codigo");
crud = new BaseController(getBaseContext());
nome = (EditText)findViewById(R.id.nomeAltera);
telefone = (EditText)findViewById(R.id.telefoneAltera);
alterar = (Button)findViewById(R.id.buttonAlterar);
cursor = crud.carregaDadoById(Integer.parseInt(codigo));
nome.setText(cursor.getString(cursor.getColumnIndexOrThrow(DatabaseUtil.NOME)));
telefone.setText(cursor.getString(cursor.getColumnIndexOrThrow(DatabaseUtil.TELEFONE)));
deletar = (Button)findViewById(R.id.buttonDeletar);
deletar.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
crud.deletaRegistro(Integer.parseInt(codigo));
Intent intent = new Intent(AlterActivity.this, SecondActivity.class);
startActivity(intent);
finish();
}
});
}
public void alteraDados(View view){
crud.alteraRegistro(Integer.parseInt(codigo), nome.getText().toString(),telefone.getText().toString());
Intent intent = new Intent(this,SecondActivity.class);
startActivity(intent);
finish();
}
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package it.geosolutions.fra2015.services.rest.exception;
import javax.ws.rs.core.Response;
/**
*
* @author marco
*/
public class IllegalAccessWebExpection extends Fra2015WebEx {
public IllegalAccessWebExpection(String message) {
super(Response.Status.UNAUTHORIZED, message);
}
}
|
/*
* created 03.04.2005
*
* $Id: TableTreeEditPart.java 3 2005-11-02 03:04:20Z csell $
*/
package com.byterefinery.rmbench.editparts;
import org.eclipse.gef.editparts.AbstractTreeEditPart;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.swt.graphics.Image;
import org.eclipse.ui.plugin.AbstractUIPlugin;
import com.byterefinery.rmbench.EventManager;
import com.byterefinery.rmbench.RMBenchConstants;
import com.byterefinery.rmbench.RMBenchPlugin;
import com.byterefinery.rmbench.EventManager.Event;
import com.byterefinery.rmbench.model.schema.Table;
/**
* edit part to represent table objects in the tree outline view. The outline only
* shows tables to allow easy navigation in the diagram. Columns are not shown
*
* @author cse
*/
public class TableTreeEditPart extends AbstractTreeEditPart {
private EventManager.Listener tableListener = new EventManager.Listener() {
public void eventOccurred(int eventType, Event event) {
if(event.element != getTable())
return;
if(event.info == EventManager.Properties.NAME)
refreshVisuals();
}
public void register() {
RMBenchPlugin.getEventManager().addListener(TABLE_MODIFIED, this);
}
};
public TableTreeEditPart(TableEditPart mainPart) {
super(mainPart.getTable());
}
public void activate() {
super.activate();
tableListener.register();
}
public void deactivate() {
super.deactivate();
tableListener.unregister();
}
protected Image getImage() {
ImageDescriptor desc =
AbstractUIPlugin.imageDescriptorFromPlugin(
RMBenchConstants.PLUGIN_ID, "icons/table.gif");
return desc.createImage();
}
protected String getText() {
return getTable().getName();
}
private Table getTable() {
return (Table)getModel();
}
}
|
package com.fuxinyu.service.login;
import com.fuxinyu.domain.UserLogin;
/**
* @author: fuxinyu
* Date: 2019/9/30
* Time: 9:40
* Description:
*/
public interface IUserLoginService {
int deleteByPrimaryKey(Integer id);
int insert(UserLogin record);
int insertSelective(UserLogin record);
UserLogin selectByPrimaryKey(Integer id);
int updateByPrimaryKeySelective(UserLogin record);
int updateByPrimaryKey(UserLogin record);
UserLogin getUserByName(String userName);
}
|
package com.pangpang6.utils;
import org.apache.commons.codec.binary.Base64;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
/**
* Created by jiangjg on 2017/4/11.
*/
public class Base64Utils {
public static void main(String[] args) throws UnsupportedEncodingException {
byte[] bytes = Base64.encodeBase64("chloro.userprofile.downstream.http.queue.size".getBytes("utf-8"));
System.out.println(new String(bytes));
byte[] aa = Base64.decodeBase64(bytes);
System.out.println(new String(aa));
String ss = URLEncoder.encode("chloro.userprofile.downstream.http.queue.size", "UTF-8");
System.out.println(ss);
}
}
|
package org.henix.workshop.qlearn.impl;
import org.henix.workshop.qlearn.concepts.*;
import java.util.*;
/*
Matrix-based implementation of Grid
*/
public class MatrixGrid implements Grid {
public static final int MAX_MOVE_CNT = Grid.SIZE_X * Grid.SIZE_Y;
private final CellState state[][];
int _movecount = 0;
private List<int[]> _x_moves = new ArrayList<>(5);
private List<int[]> _o_moves = new ArrayList<>(5);
MatrixGrid(CellState state[][]){
this.state = state;
// also must update the corresponding moves
for (int x=0; x<Grid.SIZE_X; x++) for (int y=0; y<Grid.SIZE_Y; y++){
int[] move = new int[]{x,y};
switch (state[x][y]){
case X: _x_moves.add(move); break;
case O: _o_moves.add(move); break;
default: break;
}
}
_movecount = _x_moves.size() + _o_moves.size();
}
public MatrixGrid(){
state = new CellState[Grid.SIZE_X][Grid.SIZE_Y];
for (int x=0; x<Grid.SIZE_X; x++) for (int y=0; y<Grid.SIZE_Y; y++) state[x][y] = CellState.EMPTY;
}
@Override
public void play(int x, int y, Token token) {
play(new Move(x, y, token));
}
@Override
public void play(Move move) {
CellState moveState = fromToken(move.token);
CellState current = state[move.x][move.y];
if (current != CellState.EMPTY) throw new RuntimeException("Hey, you can't play that cell because there's already a "+current + " here !");
state[move.x][move.y] = moveState;
// update internal state variables
int[] pos = new int[]{move.x, move.y};
if (moveState == CellState.X) _x_moves.add(pos); else _o_moves.add(pos);
_movecount++;
}
@Override
public CellState[][] getState() {
CellState copy[][] = new CellState[Grid.SIZE_X][Grid.SIZE_Y];
for (int x=0; x<Grid.SIZE_X; x++) for (int y=0; y<Grid.SIZE_Y; y++) copy[x][y] = state[x][y];
return copy;
}
@Override
public List<Move> getAvailableMoveFor(Player player) {
List<Move> moves = new ArrayList<>();
for (int x=0; x<Grid.SIZE_X; x++) for (int y=0; y<Grid.SIZE_Y; y++){
if (state[x][y] == CellState.EMPTY) moves.add(new Move(x, y, player.getToken()));
}
return moves;
}
@Override
public boolean isGameOver() {
return getOutcome().isGameOver();
}
@Override
public GameOutcome getOutcome() {
CellState winnertoken = searchWinner();
if (winnertoken == CellState.X) return GameOutcome.PLAYER_X_WINS;
if (winnertoken == CellState.O) return GameOutcome.PLAYER_O_WINS;
if (_movecount >= MAX_MOVE_CNT) return GameOutcome.DRAW;
return GameOutcome.NOT_OVER_YET;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder
.append(" |0|1|2\n")
.append("-+-+-+-\n")
.append(String.format("0|%s|%s|%s\n", state[0][0], state[0][1], state[0][2]))
.append("-+-+-+-\n")
.append(String.format("1|%s|%s|%s\n", state[1][0], state[1][1], state[1][2]))
.append("-+-+-+-\n")
.append(String.format("2|%s|%s|%s\n", state[2][0], state[2][1], state[2][2]))
.append("-+-+-+-\n");
return builder.toString();
}
//************ private stuffs *************
private static int _x = 0;
private static int _y = 1;
// returns null if there is no winner yet
private CellState searchWinner(){
// shortcut : if less than 5 moves were played,
// there can be no winner
if (_movecount < 5) return null;
if (areWiningMoves(_x_moves)) return CellState.X;
if (areWiningMoves(_o_moves)) return CellState.O;
return null;
}
/*
* Search within that position list if the victory condition is met.
* We do that by inspecting all triplets and check that the following properties :
* - all their 'x' component are either the same, either all different
* - all their 'y' component are either the same, either all different
* - in the special case both 'x' and 'y' components meet the criteria 'all different', the central position (1,1) must also belong to the set.
*/
private boolean areWiningMoves(List<int[]> positionList){
int len = positionList.size();
boolean isWin = false;
// jeu caché :
// - je paye un coca à celui qui lit ça
// - et un deuxième s'il me dit ce que c'est que ce outerloop
outerloop:
for (int i1 = 0; i1 < len-2; i1++)
for (int i2 = i1+1; i2 < len-1; i2++)
for (int i3 = i2+1; i3 < len; i3++){
int[] p1 = positionList.get(i1);
int[] p2 = positionList.get(i2);
int[] p3 = positionList.get(i3);
isWin = arePositionAligned(p1, p2, p3);
if (isWin) {
break outerloop;
}
}
return isWin;
}
boolean arePositionAligned(int[] p1, int[] p2, int[] p3){
boolean diffX = allDifferent(p1[_x], p2[_x], p3[_x]);
boolean diffY = allDifferent(p1[_y], p2[_y], p3[_y]);
if (diffX && diffY){
return hasCenter(p1, p2, p3);
}
else{
boolean conditionX = areXEither(p1, p2, p3, this::allSame, this::allDifferent);
boolean conditionY = areYEither(p1, p2, p3, this::allSame, this::allDifferent);
return (conditionX && conditionY);
}
}
private boolean allSame(int v1, int v2, int v3){
return (v1==v2) && (v2==v3);
}
private boolean allDifferent(int v1, int v2, int v3){
if (v1 == v2) return false;
if (v2 == v3) return false;
if (v3 == v1) return false;
return true;
}
private boolean hasCenter(int[] ...positions){
for (int[] p : positions) {
if (p[_x] == 1 && p[_y] == 1) return true;
}
return false;
}
private boolean areXEither(int[] p1, int[] p2, int[] p3, AlignmentPredicate...predicates){
for (AlignmentPredicate p : predicates){
if (p.predict(p1[_x], p2[_x], p3[_x])) return true;
}
return false;
}
private boolean areYEither(int[] p1, int[] p2, int[] p3, AlignmentPredicate...predicates){
for (AlignmentPredicate p : predicates){
if (p.predict(p1[_y], p2[_y], p3[_y])) return true;
}
return false;
}
@FunctionalInterface
private interface AlignmentPredicate {
boolean predict(int v1, int v2, int v3);
}
private CellState fromToken(Token token){
return (token == Token.X) ? CellState.X : CellState.O;
}
}
|
package com.klg.newpolice.ui.comment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.View;
import com.klg.newpolice.R;
import com.klg.newpolice.util.ActivityUtils;
public class CommentActivity extends AppCompatActivity {
private int mChildId;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_comment);
Bundle extras = getIntent().getExtras();
assert extras != null;
mChildId = extras.getInt(getString(R.string.id_miss_child));
updateViewDependencies();
CommentFragment statisticsFragment = (CommentFragment) getSupportFragmentManager()
.findFragmentById(R.id.frame_layout_comment);
if (statisticsFragment == null) {
statisticsFragment = CommentFragment.newInstance();
ActivityUtils.addFragmentToActivity(getSupportFragmentManager(),
statisticsFragment, R.id.frame_layout_comment);
}
}
private void updateViewDependencies() {
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
if (getSupportActionBar() != null){
getSupportActionBar().setTitle(R.string.comments);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
}
}
public int getChildId() {
return mChildId;
}
@Override
public void onBackPressed() {
super.onBackPressed();
}
@Override
public boolean onSupportNavigateUp() {
onBackPressed();
return true;
}
}
|
package vista;
import javax.swing.*;
import org.math.plot.Plot2DPanel;
import javax.swing.JComboBox;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JPanel;
import javax.swing.border.LineBorder;
import java.awt.Color;
import javax.swing.JTextField;
import java.awt.Button;
import java.awt.event.ActionListener;
import java.awt.Dimension;
import javax.swing.JRadioButton;
import java.awt.Font;
public class Ventana {
private JFrame frmProgramacinEvolutiva;
private JPanel panelTorneo;
private JLabel labelTorneo;
private JTabbedPane grafPanel;
private int numberofgrafs=0;
private Button lanzaButton;
private Button relanzaButton;
private Button eliminaButton;
private JRadioButton elitismoRadio;
private JRadioButton IFRadio;
private JComboBox<String> seleccionCB;
private JComboBox<String> mutationCB;
private JComboBox<String> inicializacionCB;
private JComboBox<String> bloatingCB;
private JComboBox<String> calcTamCB;
private JTextField poblacionTextField;
private JTextField iteracionesTextField;
private JTextField crucesTextField;
private JTextField mutacionTextField;
private JTextField semillaTextField;
private JTextField mejorTextField;
private JTextField entreTextField;
private JTextField profundidadTextField;
private JLabel lblMejorAbsoluto;
private JLabel lblProfundidadMax;
private JLabel calcTam;
private JTextArea cromosomaFinal;
public Ventana() {
initialize();
frmProgramacinEvolutiva.setVisible(true);
}
private void initialize() {
frmProgramacinEvolutiva = new JFrame();
frmProgramacinEvolutiva.setBackground(Color.WHITE);
frmProgramacinEvolutiva.setTitle("Programacion evolutiva");
frmProgramacinEvolutiva.getContentPane().setPreferredSize(new Dimension(600, 400));
frmProgramacinEvolutiva.setBounds(100, 100, 11500, 695);
frmProgramacinEvolutiva.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
panel.setOpaque(false);
panel.setBounds(0, 0, 1362, 640);
panel.setPreferredSize(new Dimension(40, 40));
panel.setMaximumSize(new Dimension(50000, 50000));
JLabel lblPoblacion = new JLabel("Poblacion");
lblPoblacion.setBounds(10, 99, 102, 14);
poblacionTextField = new JTextField();
poblacionTextField.setText("50");
poblacionTextField.setBounds(122, 96, 189, 20);
poblacionTextField.setColumns(10);
JLabel lblIteraciones = new JLabel("Iteraciones");
lblIteraciones.setBounds(10, 190, 83, 14);
iteracionesTextField = new JTextField();
iteracionesTextField.setText("100");
iteracionesTextField.setBounds(122, 187, 189, 20);
iteracionesTextField.setColumns(10);
JLabel lblCruces = new JLabel("% Cruces");
lblCruces.setBounds(10, 215, 83, 14);
crucesTextField = new JTextField();
crucesTextField.setText("70");
crucesTextField.setBounds(122, 212, 189, 20);
crucesTextField.setColumns(10);
JLabel lblMutation = new JLabel("% Mutacion");
lblMutation.setBounds(10, 271, 83, 14);
mutacionTextField = new JTextField();
mutacionTextField.setText("10");
mutacionTextField.setBounds(122, 268, 189, 20);
mutacionTextField.setColumns(10);
JLabel lblSemilla = new JLabel("Semilla");
lblSemilla.setBounds(10, 296, 68, 14);
semillaTextField = new JTextField();
semillaTextField.setText("0");
semillaTextField.setBounds(122, 293, 189, 20);
semillaTextField.setColumns(10);
seleccionCB = new JComboBox<String>();
seleccionCB.setBounds(122, 318, 189, 20);
seleccionCB.setModel(new DefaultComboBoxModel<String>(new String[] {
"Torneo Probabilistico", "Torneo Deterministico",
"Universal Estocastico", "Ruleta" }));
seleccionCB.setSelectedIndex(3);
JLabel lblSeleccion = new JLabel("Seleccion ");
lblSeleccion.setBounds(11, 321, 82, 14);
labelTorneo = new JLabel("Torneo Prob.");
labelTorneo.setOpaque(true);
labelTorneo.setBounds(10, 340, 83, 14);
panelTorneo = new JPanel();
panelTorneo.setOpaque(false);
panelTorneo.setBounds(10, 349, 301, 63);
frmProgramacinEvolutiva.getContentPane().setLayout(null);
panelTorneo.setLayout(null);
JLabel lblmejor = new JLabel("%Mejor");
lblmejor.setBounds(10, 15, 46, 14);
panelTorneo.add(lblmejor);
JLabel lblNewLabel = new JLabel("Entre");
lblNewLabel.setBounds(10, 38, 70, 14);
panelTorneo.add(lblNewLabel);
mejorTextField = new JTextField();
mejorTextField.setText("60.0");
mejorTextField.setBounds(112, 12, 179, 20);
panelTorneo.add(mejorTextField);
mejorTextField.setColumns(10);
entreTextField = new JTextField();
entreTextField.setText("3");
entreTextField.setBounds(112, 35, 179, 20);
panelTorneo.add(entreTextField);
entreTextField.setColumns(10);
lanzaButton = new Button("Iniciar");
lanzaButton.setBounds(38, 531, 273, 31);
relanzaButton = new Button("Reiniciar");
relanzaButton.setBounds(38, 568, 273, 34);
relanzaButton.setVisible(false);
eliminaButton = new Button("Eliminar");
eliminaButton.setBounds(38, 608, 273, 32);
panel.setLayout(null);
panel.add(lblPoblacion);
panel.add(poblacionTextField);
panel.add(lblIteraciones);
panel.add(iteracionesTextField);
panel.add(lblCruces);
panel.add(crucesTextField);
panel.add(lblMutation);
panel.add(mutacionTextField);
panel.add(lblSemilla);
panel.add(semillaTextField);
panel.add(seleccionCB);
panel.add(lblSeleccion);
panel.add(labelTorneo);
panel.add(panelTorneo);
panel.add(lanzaButton);
panel.add(relanzaButton);
panel.add(eliminaButton);
frmProgramacinEvolutiva.getContentPane().add(panel);
JLabel lblElitismo = new JLabel("Elitismo");
lblElitismo.setBounds(10, 48, 102, 14);
panel.add(lblElitismo);
elitismoRadio = new JRadioButton("");
elitismoRadio.setBounds(189, 48, 38, 23);
panel.add(elitismoRadio);
grafPanel = new JTabbedPane(JTabbedPane.TOP);
grafPanel.setBounds(438, 53, 886, 509);
panel.add(grafPanel);
JLabel lblMutacin = new JLabel("Mutaci\u00F3n");
lblMutacin.setBounds(10, 240, 80, 14);
panel.add(lblMutacin);
mutationCB = new JComboBox<String>();
mutationCB.setModel(new DefaultComboBoxModel<String>(new String[] {"Terminal simple", "Funcional simple", "Mutacion de arbol", "Permutacion"}));
mutationCB.setSelectedIndex(1);
mutationCB.setBounds(122, 237, 189, 20);
panel.add(mutationCB);
JLabel lblInicializacin = new JLabel("Inicializaci\u00F3n");
lblInicializacin.setBounds(10, 74, 102, 14);
panel.add(lblInicializacin);
inicializacionCB= new JComboBox<String>();
inicializacionCB.setModel(new DefaultComboBoxModel<String>(new String[] {"Inicializacion completa", "Inicializacion creciente", "Ramped and half"}));
inicializacionCB.setSelectedIndex(2);
inicializacionCB.setBounds(122, 71, 189, 20);
panel.add(inicializacionCB);
JLabel lblBloating = new JLabel("Bloating");
lblBloating.setBounds(10, 423, 83, 14);
panel.add(lblBloating);
bloatingCB = new JComboBox<String>();
bloatingCB.setModel(new DefaultComboBoxModel<String>(new String[] {"Metodo Tarpeian", "Penalizacion bien fundamentada"}));
bloatingCB.setBounds(122, 420, 189, 20);
panel.add(bloatingCB);
lblProfundidadMax = new JLabel("Profundidad max");
lblProfundidadMax.setBounds(10, 124, 102, 14);
panel.add(lblProfundidadMax);
profundidadTextField = new JTextField();
profundidadTextField.setText("6");
profundidadTextField.setBounds(122, 121, 190, 20);
panel.add(profundidadTextField);
profundidadTextField.setColumns(10);
JLabel lblUsarIf = new JLabel("Usar IF");
lblUsarIf.setBounds(10, 149, 83, 14);
panel.add(lblUsarIf);
IFRadio = new JRadioButton("");
IFRadio.setBounds(189, 148, 109, 23);
panel.add(IFRadio);
JLabel lblMejorCromosoma = new JLabel("Salida");
lblMejorCromosoma.setBounds(438, 559, 258, 31);
panel.add(lblMejorCromosoma);
cromosomaFinal = new JTextArea();
cromosomaFinal.setBounds(438, 596, 886, 50);
panel.add(cromosomaFinal);
calcTam = new JLabel("Calculo tam.");
calcTam.setBounds(10, 448, 83, 14);
panel.add(calcTam);
calcTamCB = new JComboBox<String>();
calcTamCB.setModel(new DefaultComboBoxModel<String>(new String[] {"Profundidad", "Num. nodos"}));
calcTamCB.setBounds(122, 445, 189, 20);
panel.add(calcTamCB);
}
public void addGraphPanel(double ejeGeneracion [],double[] mediait, double[] mejorit,double[] mejorabsoluto,String best) {
Plot2DPanel plot = new Plot2DPanel();
plot.setPreferredSize(new Dimension(800,600));
plot.setAxisLabel(0, "Generacion");
plot.setAxisLabel(1, "Valor");
plot.setLegendOrientation("SOUTH");
plot.addLinePlot("Media Poblacion", Color.GREEN, ejeGeneracion, mediait);
plot.addLinePlot("Mejor Generacion", Color.RED, ejeGeneracion, mejorit);
plot.addLinePlot("Mejor Absoluto", Color.BLUE, ejeGeneracion, mejorabsoluto);
best += "\n=========================================================================\n";
best += "Aptitud MEJOR : "+ Double.toString(mejorabsoluto[mejorabsoluto.length-1]) +"\n";
cromosomaFinal.setText(best);
numberofgrafs++;
grafPanel.addTab( "AG"+numberofgrafs, null, plot, "");
grafPanel.setSelectedIndex(numberofgrafs-1);
}
public void borrarGrafActivo(){
if(grafPanel.getSelectedIndex()>=0){
grafPanel.removeTabAt(grafPanel.getSelectedIndex());
numberofgrafs--;
}
}
public void setVisibilityTorneo(boolean visible) {
panelTorneo.setVisible(visible);
labelTorneo.setVisible(visible);
}
public int getPoblacionText() {
return Integer.parseInt(poblacionTextField.getText());
}
public int getProfundidadText() {
return Integer.parseInt(profundidadTextField.getText());
}
public int getIteracionesText() {
return Integer.parseInt(iteracionesTextField.getText());
}
public Double getCrucesText() {
return Double.parseDouble(crucesTextField.getText()) / 100;
}
public Double getMutacionText() {
return Double.parseDouble(mutacionTextField.getText()) / 100;
}
public int getSemillaText() {
return Integer.parseInt(semillaTextField.getText());
}
public Double getMejorTextField() {
return Double.parseDouble(mejorTextField.getText()) / 100;
}
public int getEntreTextField() {
return Integer.parseInt(entreTextField.getText());
}
public String getInitializationTextField() {
return (String) inicializacionCB.getSelectedItem();
}
public boolean getElitismoButton() {
return elitismoRadio.isSelected();
}
public boolean getIFButton() {
return IFRadio.isSelected();
}
public int getSeleccionCBIndex() {
return seleccionCB.getSelectedIndex();
}
public int getMutationCBIndex() {
return mutationCB.getSelectedIndex();
}
public int getBloatingCBIndex() {
return bloatingCB.getSelectedIndex();
}
public int getCalcTamCBIndex() {
return calcTamCB.getSelectedIndex();
}
public void setSeleccionCBListener(ActionListener a) {
seleccionCB.addActionListener(a);
}
public void setLanzaButtonListener(ActionListener a) {
lanzaButton.addActionListener(a);
}
public void setRelanzaButtonListener(ActionListener a) {
relanzaButton.addActionListener(a);
}
public void setEliminaButtonListener(ActionListener a) {
eliminaButton.addActionListener(a);
}
public void setVisibilityRelanza(boolean b) {
relanzaButton.setVisible(b);
}
}
|
package com.coutomariel.prime.bean;
import java.io.Serializable;
import java.util.List;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import com.coutomariel.prime.model.Usuario;
import com.coutomariel.prime.util.JPAUtil;
@ManagedBean
@ViewScoped
public class UsuarioBean implements Serializable {
private static final long serialVersionUID = 1L;
private Usuario usuario = new Usuario();
private List<Usuario> usuarios;
public List<Usuario> getUsuarios() {
EntityManager em = JPAUtil.getEntityManager();
Query query = em.createQuery("select a from Usuario a", Usuario.class);
List<Usuario> usuarios = query.getResultList();
return usuarios;
}
public void setUsuarios(List<Usuario> usuarios) {
this.usuarios = usuarios;
}
public void cadastrar() {
this.usuario.salvar(usuario);
}
public Usuario getUsuario() {
return usuario;
}
public void setUsuario(Usuario usuario) {
this.usuario = usuario;
}
}
|
package com.bvan.javastart.lessons1_2;
/**
* @author bvanchuhov
*/
public class TypeCasting {
public static void main(String[] args) {
int x = 200;
byte b = (byte) x;
System.out.println(b); // -56
}
}
|
package spacely.fireit.MyObjects;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Preferences;
import com.badlogic.gdx.audio.Sound;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.math.Vector3;
import java.util.Random;
import spacely.fireit.Asset;
import spacely.fireit.GameStates.MenuState;
import spacely.fireit.Helpers.MyRatio;
/**
* Created by Workspace on 21.04.2017.
*/
public class Ball {
private Sprite sprite;
private Texture texture;
private Vector3 position,velocity;
private static int GRAVITY = ((int)MyRatio.getHeight(1.7f))*(-1);
private boolean earth = false;
private Random random;
private int rotate = 10;
private Sound ball_sound;
public static int soundtrue = 0;
public static int gameover_sound_true = 0;
public static boolean gameover = false;
private Sound gameover_sound;
public static int point = 0;
private float height_pos = 0;
private float pos_y;
private float pos_x;
private Preferences preferences;
public static int high_score = 0;
public static String HIGHSCORE = "HighScore";
public static String SCORE = "Score";
public Ball(){
height_pos = MyRatio.getHeight(2.6f);
texture = Asset.manager.get(Asset.ball_txtr,Texture.class);
pos_x = texture.getWidth() * MyRatio.getHeight(0.13f);
pos_y = texture.getHeight() * MyRatio.getHeight(0.13f);
sprite = new Sprite();
sprite.setSize(pos_x, pos_y);
sprite.setPosition(Gdx.graphics.getWidth()/2+(pos_x /2),height_pos);
sprite.setOriginCenter();
velocity = new Vector3(0,0,0);
position = new Vector3((int)(Gdx.graphics.getWidth()/2+(pos_x /2)),height_pos,0);
random = new Random();
ball_sound = Asset.manager.get(Asset.ball_sound,Sound.class);
gameover_sound = Asset.manager.get(Asset.gameover_sound,Sound.class);
}
public void draw(SpriteBatch batch){
sprite.setRegion(texture);
sprite.draw(batch);
}
public void falling(float dt){
if (!earth) {
velocity.add(0, GRAVITY, 0);
velocity.scl(dt);
position.add(velocity.x, velocity.y, 0);
velocity.scl(1 / dt);
sprite.setPosition(position.x, position.y);
sprite.rotate(dt*rotate);
}
if (position.y<=height_pos){
earth = true;
position.y = height_pos;
sprite.setPosition(position.x,position.y);
gameover = true;
//point = 0;
gameover_sound_true++;
Button.setEnabled(true);
if (gameover_sound_true == 1) {
gameover_sound.play();
}
}
}
public void kick(){
if (!gameover) {
if (position.y < MyRatio.getHeight(8.6f) && position.y > MyRatio.getHeight(5.6f) && position.x < Gdx.graphics.getWidth()/2+(pos_x /2)) {
velocity.y = MyRatio.getHeight(31.25f) + random.nextInt((int)MyRatio.getHeight(26.042f));
//velocity.x = MyRatio.getHeight(31.25f) + random.nextInt((int)MyRatio.getHeight(26.042f));
rotate = random.nextInt(200) - 100;
soundtrue++;
if (soundtrue == 1) {
ball_sound.play();
point++;
soundtrue++;
}
}else if (position.y < MyRatio.getHeight(4.8f) && position.y > height_pos&& position.x < Gdx.graphics.getWidth()/2+(pos_x /2)){
velocity.y = MyRatio.getHeight(31.25f) + random.nextInt((int)MyRatio.getHeight(26.042f));
velocity.x = MyRatio.getHeight(5.25f) + random.nextInt((int)MyRatio.getHeight(8.042f));
rotate = random.nextInt(220) - 120;
soundtrue++;
if (soundtrue == 1) {
ball_sound.play();
point++;
soundtrue++;
}
}
}else {
}
}
public void respawn(){
gameover_sound_true = 0;
//gameover = false;
earth = false;
position.x = (int)(Gdx.graphics.getWidth()/2+(pos_x /2));
velocity.x = 0;
velocity.y = MyRatio.getHeight(62.5f) + random.nextInt((int)MyRatio.getHeight(10.42f));
soundtrue++;
if (soundtrue == 1) {
ball_sound.play();
}
}
}
|
package net.youzule.java.http.file.utils.excel;
/**
* @param <E>
* @Title: ExcelDataCell.java
* @Description:
* @author:zhaodahai
* @date 2018年9月19日 下午4:20:40
*/
public class ExcelDataCell extends ExcelCell {
private Object value;//数据的值
public ExcelDataCell (String type) {
this.setType(type);
}
public Object getValue() {
return value;
}
public void setValue(Object value) {
this.value = value;
}
}
|
package view;
public class CollectionView {
private ClientMainView generalView;
private F1CreateNewPersonView f1CreateNewPersonView1;
private F2ListPersonsView f2ListPersonsView;
private F3SavePersonsView f3SavePersonsView;
private F4DownloadPersonsView f4DownloadPersonsView;
private F5SortPersonsInMemoryView f5SortPersonsInMemoryView;
private F6NumberingServiceView f6NumberingServiceView;
private F7LeaveProgrammView f7LeaveProgrammView;
private F8ServerSettingView f8ServerSettingView;
public F8ServerSettingView getF8ServerSettingView() {
return f8ServerSettingView;
}
public void setF8ServerSettingView(F8ServerSettingView f8ServerSettingView) {
this.f8ServerSettingView = f8ServerSettingView;
}
public F6NumberingServiceView getF6NumberingServiceView() {
return f6NumberingServiceView;
}
public void setF6NumberingServiceView(F6NumberingServiceView f6NumberingServiceView) {
this.f6NumberingServiceView = f6NumberingServiceView;
}
public F5SortPersonsInMemoryView getF5SortPersonsInMemoryView() {
return f5SortPersonsInMemoryView;
}
public void setF5SortPersonsInMemoryView(F5SortPersonsInMemoryView f5SortPersonsInMemoryView) {
this.f5SortPersonsInMemoryView = f5SortPersonsInMemoryView;
}
public F4DownloadPersonsView getF4DownloadPersonsView() {
return f4DownloadPersonsView;
}
public void setF4DownloadPersonsView(F4DownloadPersonsView f4DownloadPersonsView) {
this.f4DownloadPersonsView = f4DownloadPersonsView;
}
public F3SavePersonsView getF3SavePersonsView() {
return f3SavePersonsView;
}
public void setF3SavePersonsView(F3SavePersonsView f3SavePersonsView) {
this.f3SavePersonsView = f3SavePersonsView;
}
public ClientMainView getGeneralView() {
return generalView;
}
public void setGeneralView(ClientMainView generalView) {
this.generalView = generalView;
}
public F1CreateNewPersonView getF1CreateNewPersonView() {
return f1CreateNewPersonView1;
}
public void setF1CreateNewPersonView1(F1CreateNewPersonView f1CreateNewPersonView1) {
this.f1CreateNewPersonView1 = f1CreateNewPersonView1;
}
public F2ListPersonsView getF2ListPersonsView() {
return f2ListPersonsView;
}
public void setF2ListPersonsView(F2ListPersonsView f2ListPersonsView) {
this.f2ListPersonsView = f2ListPersonsView;
}
public F7LeaveProgrammView getF7LeaveProgrammView() {
return f7LeaveProgrammView;
}
public void setF7LeaveProgrammView(F7LeaveProgrammView f7LeaveProgrammView) {
this.f7LeaveProgrammView = f7LeaveProgrammView;
}
}
|
package acwing.背包问题;
import java.util.Scanner;
public class 背包问题01_2 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();//物品的数量
int m = sc.nextInt();//背包的容积
int[] v = new int[n + 1];
int[] w = new int[n + 1];
for (int i = 1; i <= n; i++) {
v[i] = sc.nextInt();
w[i] = sc.nextInt();
}
System.out.println(dpMethod(m, n, v, w));
}
public static int dpMethod(int m, int n, int[] v, int[] w) {
/*
v[i]是体积 w[i]是价值
*/
int[][] dp = new int[n + 1][m + 1];
for (int i = 1; i < dp.length; i++) {
for (int j = 0; j < dp[0].length; j++) {
dp[i][j] = dp[i - 1][j];
/*
是 >= 不是 >
dp[i - 1][j - v[i]] + w[i] 而不是 dp[i][j - w[i]] + v[i]
*/
if (j >= v[i]) {
//也可以写成:dp[i][j] = Math.max(dp[i][j], dp[i - 1][j - v[i]] + w[i]);
dp[i][j] = Math.max(dp[i - 1][j], dp[i - 1][j - v[i]] + w[i]);
}
}
}
return dp[dp.length - 1][dp[0].length - 1];
}
/*
https://blog.csdn.net/qie_wei/article/details/81320229
dp[i]的状态只和 dp[i-1]有关,所以可以使用一维的数组求解
dp[i - 1][j - v[i]] dp[i - 1][j]
dp[i-x][j] dp[i][j] dp[i+x][j]
计算dp[i][j]时候依赖的相对位置,计算完 dp[i][j] 后,就会将 dp[i - 1][j] 覆盖为 dp[i][j]
如果循环第二层的时候, 从小到大计算,那么接下来计算 dp[i+x][j] 如果依赖dp[i - 1][j],但是dp[i - 1][j]已经被覆盖
从大到小计算,那么接下来计算 dp[i-x][j] 不会用到 dp[i - 1][j],所以依然可以得到正确的结果
第一层,我们知道dp[i]依赖于dp[i-1]所以从小到大循环
*/
public static int dpMethod2(int m, int n, int[] v, int[] w) {
int[]dp=new int[m+1];
for (int i = 1; i <=n ; i++) {
for (int j = m; j >=v[i] ; j--) {
// dp[j] 而不是 dp[i]
dp[j]=Math.max(dp[j],dp[j-v[i]]+w[i]);
}
}
return dp[m];
}
}
|
package com.duanxr.yith.easy;
/**
* @author 段然 2021/5/21
*/
public class CheckIfANumberIsMajorityElementInASortedArray {
/**
* Given an array nums sorted in non-decreasing order, and a number target, return True if and only if target is a majority element.
*
* A majority element is an element that appears more than N/2 times in an array of length N.
*
*
*
* Example 1:
*
* Input: nums = [2,4,5,5,5,5,5,6,6], target = 5
* Output: true
* Explanation:
* The value 5 appears 5 times and the length of the array is 9.
* Thus, 5 is a majority element because 5 > 9/2 is true.
* Example 2:
*
* Input: nums = [10,100,101,101], target = 101
* Output: false
* Explanation:
* The value 101 appears 2 times and the length of the array is 4.
* Thus, 101 is not a majority element because 2 > 4/2 is false.
*
*
* Constraints:
*
* 1 <= nums.length <= 1000
* 1 <= nums[i] <= 10^9
* 1 <= target <= 10^9
*
* 给出一个按 非递减 顺序排列的数组 nums,和一个目标数值 target。假如数组 nums 中绝大多数元素的数值都等于 target,则返回 True,否则请返回 False。
*
* 所谓占绝大多数,是指在长度为 N 的数组中出现必须 超过 N/2 次。
*
*
*
* 示例 1:
*
* 输入:nums = [2,4,5,5,5,5,5,6,6], target = 5
* 输出:true
* 解释:
* 数字 5 出现了 5 次,而数组的长度为 9。
* 所以,5 在数组中占绝大多数,因为 5 次 > 9/2。
* 示例 2:
*
* 输入:nums = [10,100,101,101], target = 101
* 输出:false
* 解释:
* 数字 101 出现了 2 次,而数组的长度是 4。
* 所以,101 不是 数组占绝大多数的元素,因为 2 次 = 4/2。
*
*
* 提示:
*
* 1 <= nums.length <= 1000
* 1 <= nums[i] <= 10^9
* 1 <= target <= 10^9
*
*/
class Solution {
public boolean isMajorityElement(int[] nums, int target) {
int votes = 0;
for (int n : nums) {
votes += n == target ? 1 : -1;
}
return votes > 0;
}
}
}
|
// ================================
// POO JAVA - IMAC 2 - ANIK Myriam
// TP 1 - Exo 04
// Pour (dé)commenter un bloc : Cmd+Shift+/ ou Ctrl + Shift + /
// ================================
import java.lang.Integer;
import java.util.*;
public class Sum
{
public static int[] charTointArray(String[] strAr)
{
System.out.println("===== TABLEAU =====");
int intAr[] = new int[strAr.length];
for(int i = 0; i <= strAr.length-1; i++)
{
intAr[i]= Integer.parseInt(strAr[i]);
System.out.println(intAr[i]);
}
return intAr;
}
public static int sumArray(int[] intAr)
{
int sum=0;
for(int i = 0; i <= intAr.length-1; i++)
{
sum+=intAr[i];
}
return sum;
}
public static void main(String[] args)
{
System.out.println("===== SOMME ===== "+ System.getProperty("line.separator") + sumArray(charTointArray(args)));
}
}
// 2 - Que veut dire statique pour une méthode ?
// Statique permet d'appeler une fonction sans avoir besoin d'instancier la classe.
// 3 - Que se passe-t'il lorsqu'un mot pris en argument n'est pas un nombre ?
// Ça lance une exception, c'est magique !
|
package com.rivierasoft.palestinianuniversitiesguide.Adapters;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.cardview.widget.CardView;
import androidx.recyclerview.widget.RecyclerView;
import com.rivierasoft.palestinianuniversitiesguide.OnRVIClickListener;
import com.rivierasoft.palestinianuniversitiesguide.R;
import com.rivierasoft.palestinianuniversitiesguide.Models.Result;
import java.util.ArrayList;
public class ResultAdapter extends RecyclerView.Adapter<ResultAdapter.AdapterViewHolder> {
private ArrayList<Result> results;
private int activityType;
private int login;
private OnRVIClickListener listener;
private OnRVIClickListener listener2;
public ResultAdapter(ArrayList<Result> results, int activityType, int login, OnRVIClickListener listener, OnRVIClickListener listener2) {
this.results = results;
this.activityType = activityType;
this.login = login;
this.listener = listener;
this.listener2 = listener2;
}
@NonNull
@Override
public AdapterViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.result, parent,false);
return new AdapterViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull AdapterViewHolder holder, int position) {
Result result = results.get(position);
holder.programTV.setText(result.getProgram());
holder.degreeTV.setText(result.getDegree());
holder.universityTV.setText(result.getUniversity());
if (result.isSave())
holder.saveUnSaveIV.setImageResource(R.drawable.ic_unsave);
else holder.saveUnSaveIV.setImageResource(R.drawable.ic_save);
}
@Override
public int getItemCount() {
return results.size();
}
class AdapterViewHolder extends RecyclerView.ViewHolder {
CardView cardView;
TextView programTV, degreeTV, universityTV;
ImageView saveUnSaveIV;
public AdapterViewHolder(@NonNull View itemView) {
super(itemView);
cardView = itemView.findViewById(R.id.cv_result);
programTV = itemView.findViewById(R.id.tv_result_program);
degreeTV = itemView.findViewById(R.id.tv_result_degree);
universityTV = itemView.findViewById(R.id.tv_result_university);
saveUnSaveIV = itemView.findViewById(R.id.iv_save_unsave);
cardView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
listener.OnClickListener(getAdapterPosition());
}
});
saveUnSaveIV.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int position = getAdapterPosition();
Result result = results.get(position);
listener2.OnClickListener(getAdapterPosition());
if (activityType == 1) {
if (result.isSave()) {
result.setSave(false);
} else if (!result.isSave()){
result.setSave(true);
}
notifyItemChanged(position);
} else {
results.remove(position);
notifyItemRemoved(position);
}
}
});
}
}
}
|
package gem.java;
public class PackDemo{
int a=2;
public static void main(String [] args){
System.out.println("hello package");
}
}
|
package sixkyu.spinwords;
import java.util.Arrays;
import java.util.stream.Collectors;
public class SpinWords {
private static final int LETTER_LIMIT_FOR_REVERSE = 5;
private static final String DELIMITER = " ";
public String spinWords(String sentence) {
return Arrays.stream(sentence.split(DELIMITER))
.map(this::reverseLongWords)
.collect(Collectors.joining(DELIMITER));
}
private String reverseLongWords(String word) {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(word);
if (word.length() >= LETTER_LIMIT_FOR_REVERSE) {
stringBuilder.reverse();
}
return stringBuilder.toString();
}
}
|
package ru.gadjets.comppartapp.dao.utils;
public class Pager {
private int page;
private int rowPerPage;
private int countRows;
private int countPage;
public Pager(int page) {
this.page = page;
rowPerPage = 10;
}
public void setRowPerPage(int rowPerPage) {
this.rowPerPage = rowPerPage;
}
public String pageToSqlLimit(){
return page > 0 ? (" LIMIT " + (page-1)*rowPerPage + ", " + rowPerPage) : "";
}
public void setCountRows(int countRows) {
this.countRows = countRows;
countPage = countRows / rowPerPage;
countPage += countRows % rowPerPage > 0 ? 1 : 0;
}
@Override
public String toString() {
return "Pager{" +
"page=" + page +
", rowPerPage=" + rowPerPage +
", countRows=" + countRows +
", countPage=" + countPage +
'}';
}
public int getPage() {
return page;
}
public int getRowPerPage() {
return rowPerPage;
}
public int getCountRows() {
return countRows;
}
public int getCountPage() {
return countPage;
}
}
|
package org.gmart.devtools.java.serdes.codeGenExample.featuresTestExample.generatedFiles;
import java.lang.String;
import javax.annotation.processing.Generated;
import org.gmart.devtools.java.serdes.codeGen.javaGen.model.EnumSpecification;
@Generated("")
public enum SchemaType implements EnumSpecification.EnumValueFromYaml {
object,
integer;
public String toOriginalValue() {
return toString();
}
}
|
package pl.java.scalatech.jms;
import javax.jms.Message;
import javax.jms.MessageListener;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
/**
* @author przodownik
* Module name : jmsSpringKata
* Creating time : 10:22:23 PM
*/
@Transactional
@Slf4j
public class QueueReceiver implements MessageListener {
@Autowired
private Counter counter;
@Override
public void onMessage(Message message) {
log.info("+++ MDB -----> receive a message : {}", message);
counter.getCountMessage().getAndIncrement();
}
}
|
package lv.ctco.seabattle.web.servlets;
import lv.ctco.seabattle.game.User;
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;
@WebServlet(name = "NewUserServlet", urlPatterns = "/newuser")
public class NewUserServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
User user = new User();
String userName = request.getParameter("username");
user.setName(userName);
request.getSession().setAttribute("user", user);
response.sendRedirect("/seabattle/userlist.jsp");
}
}
|
package decision;
import platform.Agent;
import sensorySystem.LightSensor;
public class Braitenberg extends Decision{
public Braitenberg(Agent a){
super(a);
}
// define the list of sensors needed for this decision system
public void defineSensors(){
}
// get the interaction to enact
public double[] decision(float[] enacted){
double[] command=new double[8];
for (int i=0;i<8;i++){
command[i]=0;
}
command[3]=1;
command[4]=1;
command[5]=1;
if (enacted[2]==0){
// read light sensor inputs
float valG=10*agent.getSensor(0);
float valD=10*agent.getSensor(1);
command[1]=Math.min(0.2,0.05+valG+valD);
// if wall at left side, turn rigth
if (enacted[3]!=0) command[2]=-Math.PI/100;
else{
command[2]=(valG-valD)*Math.abs(valG-valD)/Math.max(valG*valG+0.001,valD*valD+0.001)/10;
}
}
else{
// if wall in front, rotate right
command[2]=-Math.PI/20;
}
return command;
}
}
|
package quizzlr.backend.UnitTests;
import org.junit.*;
import quizzlr.backend.*;
public class AchievementTest {
@Test
public void achievementTest() {
/*
* TODO: something like:
* User.addAchievement(new SomethingAchievement());
* verify that SomethingAchievement is part of users's achievements
* User.removeAchievement(new SomethingAchievement())
* verify that SomethingAchievement is no longer part of achievements
*/
}
}
|
package com.trs.om.bean;
public class Possession {
private Long id;
private String possessionName;
private UserGroup userGroup;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public void setPossessionName(String possessionName) {
this.possessionName = possessionName;
}
public String getPossessionName() {
return possessionName;
}
public void setUserGroup(UserGroup userGroup) {
this.userGroup = userGroup;
}
public UserGroup getUserGroup() {
return userGroup;
}
}
|
/*
* [y] hybris Platform
*
* Copyright (c) 2018 SAP SE or an SAP affiliate company. All rights reserved.
*
* This software is the confidential and proprietary information of SAP
* ("Confidential Information"). You shall not disclose such Confidential
* Information and shall use it only in accordance with the terms of the
* license agreement you entered into with SAP.
*/
package de.hybris.platform.cmsfacades.pagescontentslotscomponents.validator.predicate;
import de.hybris.platform.cmsfacades.dto.ComponentAndContentSlotValidationDto;
import java.util.Objects;
import java.util.function.Predicate;
/**
* Predicate to test if a component is already in the given slot.
* <p>
* Returns <tt>TRUE</tt> if the component is already in the slot; <tt>FALSE</tt> otherwise.
* </p>
*/
public class ComponentAlreadyInContentSlotPredicate implements Predicate<ComponentAndContentSlotValidationDto>
{
@Override
public boolean test(final ComponentAndContentSlotValidationDto target)
{
if (Objects.isNull(target) || Objects.isNull(target.getContentSlot())
|| Objects.isNull(target.getContentSlot().getCmsComponents()))
{
return Boolean.FALSE;
}
else
{
return target.getContentSlot().getCmsComponents().contains(target.getComponent());
}
}
}
|
/**
* DNet eBusiness Suite
* Copyright: 2010-2013 Nan21 Electronics SRL. All rights reserved.
* Use is subject to license terms.
*/
package net.nan21.dnet.module.bd.business.impl.attr;
import java.util.List;
import javax.persistence.EntityManager;
import net.nan21.dnet.core.api.session.Session;
import net.nan21.dnet.core.business.service.entity.AbstractEntityService;
import net.nan21.dnet.module.bd.business.api.attr.IAttributeService;
import net.nan21.dnet.module.bd.domain.impl.attr.Attribute;
import net.nan21.dnet.module.bd.domain.impl.attr.AttributeCategory;
import net.nan21.dnet.module.bd.domain.impl.uom.Uom;
/**
* Repository functionality for {@link Attribute} domain entity. It contains
* finder methods based on unique keys as well as reference fields.
*
*/
public class Attribute_Service extends AbstractEntityService<Attribute>
implements
IAttributeService {
public Attribute_Service() {
super();
}
public Attribute_Service(EntityManager em) {
super();
this.setEntityManager(em);
}
@Override
public Class<Attribute> getEntityClass() {
return Attribute.class;
}
/**
* Find by unique key
*/
public Attribute findByCode(String code) {
return (Attribute) this
.getEntityManager()
.createNamedQuery(Attribute.NQ_FIND_BY_CODE)
.setParameter("clientId",
Session.user.get().getClient().getId())
.setParameter("code", code).getSingleResult();
}
/**
* Find by reference: category
*/
public List<Attribute> findByCategory(AttributeCategory category) {
return this.findByCategoryId(category.getId());
}
/**
* Find by ID of reference: category.id
*/
public List<Attribute> findByCategoryId(String categoryId) {
return (List<Attribute>) this
.getEntityManager()
.createQuery(
"select e from Attribute e where e.clientId = :clientId and e.category.id = :categoryId",
Attribute.class)
.setParameter("clientId",
Session.user.get().getClient().getId())
.setParameter("categoryId", categoryId).getResultList();
}
/**
* Find by reference: uom
*/
public List<Attribute> findByUom(Uom uom) {
return this.findByUomId(uom.getId());
}
/**
* Find by ID of reference: uom.id
*/
public List<Attribute> findByUomId(String uomId) {
return (List<Attribute>) this
.getEntityManager()
.createQuery(
"select e from Attribute e where e.clientId = :clientId and e.uom.id = :uomId",
Attribute.class)
.setParameter("clientId",
Session.user.get().getClient().getId())
.setParameter("uomId", uomId).getResultList();
}
}
|
package ch.springcloud.lite.core.model;
import java.util.List;
import lombok.Data;
@Data
public class CloudClientSnapshot {
CloudServerSnapshot self;
List<CloudServerSnapshot> servers;
int version;
}
|
package manager;
import hibernate.HibernateUtil;
import java.util.ArrayList;
import java.util.List;
import model.Product;
import org.hibernate.criterion.DetachedCriteria;
public class ProductManager {
// a. Product class method: C R U D
public static ArrayList<Product> getAllProducts() {
ArrayList<Product> products = new ArrayList<Product>();
DetachedCriteria dc = DetachedCriteria.forClass(Product.class);
List<Object> list = HibernateUtil.detachedCriteriaReturnList(dc);
for (Object o : list) {
products.add((Product) o);
}
return products;
}
public static Product getProductById(long id) {
return (Product) HibernateUtil.get(Product.class, id);
}
public static void addProduct(Product product) {
HibernateUtil.save(product);
}
public static void modifyProduct(Product modifiedProduct) {
HibernateUtil.update(modifiedProduct);
}
public static void deleteProduct(Product product) {
HibernateUtil.delete(product);
}
}
|
package com.cpz.Demo13;
import java.util.ArrayList;
import java.util.Collections;
public class DouDiZhu {
public static void main(String[] args) {
ArrayList<String> pokei = new ArrayList<>();
pokei.add("大王");
pokei.add("小王");
String[] colos = {"♠","♣","♥","♦"};
String[] number = {"2","A","K","Q","J","10","9","8","7","6","5","4","3"};
for (String s : number) {
for (String colo : colos) {
pokei.add(colo+s);
}
}
Collections.shuffle(pokei);//打乱集合顺序
ArrayList<String> play01=new ArrayList<>();
ArrayList<String> play02=new ArrayList<>();
ArrayList<String> play03=new ArrayList<>();
ArrayList<String> dipai=new ArrayList<>();
for (int i = 0; i < pokei.size(); i++) {
String p = pokei.get(i);
if (i>=51){
dipai.add(p);
}else if (i%3==0){
play01.add(p);
}else if (i%3==1){
play02.add(p);
}else if (i%3==2){
play03.add(p);
}
}
System.out.println("李白的:"+play01);
System.out.println("杜甫的:"+play02);
System.out.println("苏轼的:"+play03);
System.out.println("底牌:"+dipai);
}
}
|
package com.beiyelin.commonwx.common.http;
import com.beiyelin.commonwx.common.http.apache.ApacheHttpClientSimpleGetRequestExecutor;
public abstract class SimpleGetRequestExecutor<H, P> implements RequestExecutor<String, String> {
protected RequestHttp<H, P> requestHttp;
public SimpleGetRequestExecutor(RequestHttp requestHttp) {
this.requestHttp = requestHttp;
}
public static RequestExecutor<String, String> create(RequestHttp requestHttp) {
// switch (requestHttp.getRequestType()) {
// case APACHE_HTTP:
return new ApacheHttpClientSimpleGetRequestExecutor(requestHttp);
// case JODD_HTTP:
// return new JoddHttpSimpleGetRequestExecutor(requestHttp);
// case OK_HTTP:
// return new OkHttpSimpleGetRequestExecutor(requestHttp);
// default:
// throw new IllegalArgumentException("非法请求参数");
// }
}
}
|
package es.uma.sportjump.sjs.web.ajax;
import java.util.Date;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import es.uma.sportjump.sjs.model.entities.CalendarEvent;
import es.uma.sportjump.sjs.model.entities.Team;
import es.uma.sportjump.sjs.model.entities.Training;
import es.uma.sportjump.sjs.service.services.CalendarService;
import es.uma.sportjump.sjs.service.services.ExerciseService;
import es.uma.sportjump.sjs.service.services.TrainingService;
import es.uma.sportjump.sjs.service.services.UserService;
import es.uma.sportjump.sjs.web.ajax.exceptions.AjaxException;
import es.uma.sportjump.sjs.web.beans.EventBean;
import es.uma.sportjump.sjs.web.beans.EventCalendarBean;
import es.uma.sportjump.sjs.web.beans.TrainingBean;
import es.uma.sportjump.sjs.web.beans.mappings.CalendarEventBeanMapping;
import es.uma.sportjump.sjs.web.beans.mappings.TrainingBeanMapping;
@Controller
@RequestMapping("/ajax/planning")
public class PlanningAjax<E> {
@Autowired
TrainingService trainingService;
@Autowired
ExerciseService exerciseService;
@Autowired
UserService userService;
@Autowired
CalendarService calendarService;
@RequestMapping(value ="/group/{idGroup}" , method = RequestMethod.GET)
@ResponseStatus(HttpStatus.OK)
public @ResponseBody List<EventCalendarBean> getTrainingDay(@PathVariable("idGroup") Long idGroup){
Team team = userService.findTeam(idGroup);
List<CalendarEvent> calendarEventList = calendarService.findAllEventByTeam(team);
List<EventCalendarBean> eventList = CalendarEventBeanMapping.fillEvents(calendarEventList);
return eventList;
}
@RequestMapping(value ="/save" , method = RequestMethod.POST)
@ResponseStatus(HttpStatus.OK)
public @ResponseBody String saveEvent(@ModelAttribute("eventBean") EventBean eventBean) throws AjaxException{
String result = null;
Date eventDate = eventBean.getDate();
Training training = trainingService.findTrainingLight(Long.valueOf(eventBean.getIdTraining()));
Team team = userService.findTeam(Long.valueOf(eventBean.getIdGroup()));
try{
CalendarEvent calendarEvent = calendarService.setNewEvent(eventDate, training, team, false);
result = String.valueOf(calendarEvent.getIdEvent());
}catch (Exception e) {
throw new AjaxException();
}
return result;
}
@RequestMapping(value ="/{idEvent}" , method = RequestMethod.GET)
@ResponseStatus(HttpStatus.OK)
public @ResponseBody TrainingBean getTraining(@PathVariable("idEvent") Long idEvent){
CalendarEvent calendarEvent = calendarService.findEvent(idEvent);
if(calendarEvent == null){
throw new EmptyResultDataAccessException("Event not found", 1);
}
Training training = trainingService.findTraining(calendarEvent.getTraining().getIdTraining());
if (training == null){
throw new EmptyResultDataAccessException("Training element not found", 1);
}
TrainingBean result = TrainingBeanMapping.fillTrainingBean(training);
return result;
}
@RequestMapping(value="/{idEvent}", method = RequestMethod.DELETE)
@ResponseStatus(HttpStatus.OK)
public void removeEvent(@PathVariable("idEvent") Long idEvent) throws AjaxException{
CalendarEvent calendarEvent = calendarService.findEventLight(idEvent);
if (calendarEvent != null){
calendarService.removeEvent(calendarEvent);
}else{
throw new AjaxException();
}
}
@RequestMapping(value ="/{idEvent}" , method = RequestMethod.PUT)
@ResponseStatus(HttpStatus.OK)
public void modifyEvent(@PathVariable("idEvent") Long idEvent, @RequestBody EventBean eventBean) throws AjaxException{
CalendarEvent newCalendarEvent = new CalendarEvent();
newCalendarEvent.setIdEvent(idEvent);
newCalendarEvent.setEventDate(eventBean.getDate());
calendarService.modifyEventDate(idEvent, eventBean.getDate(), userService.findTeam(Long.valueOf(eventBean.getIdGroup())));
}
@ExceptionHandler(AjaxException.class)
@ResponseStatus(value = HttpStatus.BAD_REQUEST, reason = "Error peticion")
public void notFound() {
}
@ExceptionHandler(RuntimeException.class)
@ResponseStatus(value = HttpStatus.BAD_REQUEST, reason = "Error peticion")
public void error() {
}
}
|
package com.tencent.mm.plugin.messenger.foundation.a;
import com.tencent.mm.storage.bd;
@Deprecated
public interface k {
String I(bd bdVar);
}
|
package com.github.emailtohl.integration.core.role;
import java.util.List;
import javax.transaction.Transactional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import com.github.emailtohl.lib.jpa.QueryInterface;
/**
* 访问角色的自定义接口
* @author HeLei
*/
interface RoleRepositoryCustomization extends QueryInterface<Role, Long> {
/**
* 根据角色名和权限名组合查询
* @param roleName
* @param authorityName
* @param pageable
* @return
*/
Page<Role> query(String roleName, String authorityName, Pageable pageable);
/**
* 根据角色名和权限名组合查询
* @param roleName
* @param authorityName
* @return
*/
List<Role> getRoleList(String roleName, String authorityName);
/**
* 检查该roleName是否存在
* @param roleName
* @return
*/
@Transactional
boolean exist(String roleName);
/**
* 通过id查找角色的名字
* @param id 角色id
* @return 角色名
*/
String getRoleName(Long id);
}
|
package apitests;
import static org.junit.Assert.*;
import java.io.IOException;
import org.codehaus.jackson.JsonProcessingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jettison.json.JSONArray;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;
import org.junit.Before;
import org.junit.Test;
import webservice.TransactionApi;
import data.TransactionsList;
public class testTransactionApi {
private TransactionApi transactionApi = new TransactionApi();
ObjectMapper mapper = new ObjectMapper();
@Before
public void setUp() {
try {
TransactionsList.addTransaction(1, 1000, "car", 10);
TransactionsList.addTransaction(12, 7000, "car", 1);
TransactionsList.addTransaction(3, 1000, "phone", 1);
TransactionsList.addTransaction(8, 1000, "car", 12);
TransactionsList.addTransaction(10, 5000, "TV");
TransactionsList.addTransaction(11, 10000, "TV", 10);
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
@Test
public void testGetTransactionDetails() throws JsonProcessingException,
IOException, JSONException {
assertEquals(
mapper.readTree("{\"amount\":1000,\"type\":\"car\",\"parent_id\":10 }"),
mapper.readTree(((JSONObject) transactionApi
.getTransactionDetails(1).getEntity()).toString()));
}
@Test
public void testAddToListOfTransactionsWithoutParent() throws JSONException, JsonProcessingException, IOException {
long transactionId = 7L;
String requestBody = "{\"amount\":5000,\"type\":\"cars\"}";
assertEquals(transactionApi.addTransaction(transactionId, requestBody).getStatus(), 200);
assertEquals(mapper.readTree(((JSONObject) transactionApi
.getTransactionDetails(transactionId).getEntity()).toString()).toString(),
requestBody);
}
@Test
public void testAddToListOfTransactionsWithParent() throws JSONException, JsonProcessingException, IOException {
long transactionId = 7L;
String requestBody = "{\"amount\":5000,\"type\":\"cars\",\"parent_id\":36}";
assertEquals(transactionApi.addTransaction(transactionId, requestBody).getStatus(), 200);
assertEquals(mapper.readTree(((JSONObject) transactionApi
.getTransactionDetails(transactionId).getEntity()).toString()).toString(),
requestBody);
}
@Test
public void testSumOfTransactions() throws JsonProcessingException,
IOException, JSONException {
assertEquals(mapper.readTree("{\"sum\":25000}"),
mapper.readTree(((JSONObject) transactionApi
.getSumOfTransactionsById(10).getEntity()).toString()));
assertEquals(mapper.readTree("{\"sum\":10000}"),
mapper.readTree(((JSONObject) transactionApi
.getSumOfTransactionsById(11).getEntity()).toString()));
}
@Test
public void testTransactionTypes() throws JsonProcessingException,
IOException, JSONException {
assertEquals(mapper.readTree("[1,8,12]"),
mapper.readTree(((JSONArray) transactionApi
.getListOfTransactionTypes("car").getEntity())
.toString()));
}
}
|
package com.tencent.mm.plugin.remittance.bankcard.ui;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
class BankRemitHistoryUI$2 implements OnScrollListener {
final /* synthetic */ BankRemitHistoryUI mvI;
BankRemitHistoryUI$2(BankRemitHistoryUI bankRemitHistoryUI) {
this.mvI = bankRemitHistoryUI;
}
public final void onScrollStateChanged(AbsListView absListView, int i) {
}
public final void onScroll(AbsListView absListView, int i, int i2, int i3) {
if (BankRemitHistoryUI.b(this.mvI).getLastVisiblePosition() == BankRemitHistoryUI.b(this.mvI).getCount() - 1 && BankRemitHistoryUI.b(this.mvI).getCount() > 0 && !BankRemitHistoryUI.c(this.mvI) && !BankRemitHistoryUI.d(this.mvI)) {
BankRemitHistoryUI.e(this.mvI);
}
}
}
|
package thsst.calvis.simulatorvisualizer.animation.instruction.gp;
import thsst.calvis.configuration.model.engine.Calculator;
import thsst.calvis.configuration.model.engine.Memory;
import thsst.calvis.configuration.model.engine.RegisterList;
import thsst.calvis.configuration.model.engine.Token;
import javafx.collections.ObservableList;
import javafx.scene.Node;
import javafx.scene.control.ScrollPane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.scene.text.FontWeight;
import javafx.scene.text.Text;
import javafx.util.Duration;
import thsst.calvis.simulatorvisualizer.model.CalvisAnimation;
import thsst.calvis.simulatorvisualizer.model.TimeLineFunction;
/**
* Created by Goodwin Chua on 9 Jul 2016.
*/
public class Pop extends CalvisAnimation {
@Override
public void animate(ScrollPane tab) {
this.root.getChildren().clear();
tab.setContent(root);
RegisterList registers = currentInstruction.getRegisters();
Memory memory = currentInstruction.getMemory();
TimeLineFunction timeFunc = new TimeLineFunction(timeline, root, registers, memory, finder);
Calculator c = new Calculator(registers, memory);
Token[] tokens = currentInstruction.getParameterTokens();
Token des = tokens[0];
int operandSize = timeFunc.getBitSize(des);
String desVal = timeFunc.getValue(des, operandSize);
ObservableList<Node> parent = this.root.getChildren();
Rectangle fake = timeFunc.createRectangle(0, 0, Color.WHITE);
Rectangle desRec = timeFunc.createRectangle(140, 90, Color.web("#e9d66b"));
Text desLabel = timeFunc.generateText(new Text(des.getValue()), 15, "#3d2b1f", FontWeight.NORMAL, "Elephant");
Text desValue = timeFunc.generateText(new Text(desVal), 13, "#3d2b1f", FontWeight.NORMAL, "Elephant");
Text desValueMoving = timeFunc.generateText(new Text(desVal), 13, "#3d2b1f", FontWeight.NORMAL, "Elephant");
Rectangle stackRec = timeFunc.createRectangle(140, 90, Color.web("#6e7f80"));
Text stackLabel = timeFunc.generateText(new Text("STACK"), 18, "#3d2b1f", FontWeight.EXTRA_BOLD, "Elephant");
Text espLabel = timeFunc.generateText(new Text("ESP"), 15, "#b31b1b", FontWeight.BOLD, "Elephant");
Text pushLabel = timeFunc.generateText(new Text("POPPED VALUE"), 14, "#b31b1b", FontWeight.BOLD, "Elephant");
Text espVal = timeFunc.generateText(new Text(registers.get("ESP")), 13, "#3d2b1f", FontWeight.NORMAL, "Elephant");
Text insLabel = timeFunc.generateText(new Text("<= Value will be popped to"), 15, "#b31b1b", FontWeight.BOLD, "Elephant");
parent.addAll(insLabel, fake, desRec, desLabel, stackRec, espVal, stackLabel, desValueMoving, espLabel, pushLabel, desValue);
//Timeline animations
desValue.setX(stackRec.getLayoutBounds().getWidth()/2 - desValueMoving.getLayoutBounds().getWidth()/2 + 400);
desValue.setY(100);
desValueMoving.setVisible(false);
timeFunc.addTimeline(desRec.getLayoutBounds().getWidth()/2 - desValueMoving.getLayoutBounds().getWidth()/2 + 20 , 80, 3000, desValueMoving);
timeFunc.addTimeline(stackRec.getLayoutBounds().getWidth()/2 - desValueMoving.getLayoutBounds().getWidth()/2 + 400 , 100, 0, desValueMoving);
desLabel.setX(desRec.getLayoutBounds().getWidth()/2 - desLabel.getLayoutBounds().getWidth()/2 + 20);
desLabel.setY(50);
stackRec.setX(400);
stackRec.setY(20);
espVal.setX(stackRec.getLayoutBounds().getWidth()/2 - espVal.getLayoutBounds().getWidth()/2 + 400);
espVal.setY(55);
stackLabel.setX(stackRec.getLayoutBounds().getWidth()/2 - stackLabel.getLayoutBounds().getWidth()/2 + 400);
stackLabel.setY(15);
desRec.setX(20);
desRec.setY(20);
espLabel.setX(stackRec.getLayoutBounds().getWidth()/2 - espLabel.getLayoutBounds().getWidth()/2 + 400);
espLabel.setY(35);
pushLabel.setX(stackRec.getLayoutBounds().getWidth()/2 - pushLabel.getLayoutBounds().getWidth()/2 + 400);
pushLabel.setY(80);
insLabel.setX(stackRec.getLayoutBounds().getWidth()/2 + 100 + 5);
insLabel.setY(70);
timeFunc.hideshowElement(desValueMoving, 1000 / 5, true);
timeFunc.hideshowElement(desValue, 1000 / 5 + 3000 - 250, false);
timeFunc.hideshowElement(pushLabel, 1000 / 5 + 3000 - 250, false);
timeline.setDelay(Duration.millis(2000));
timeline.setCycleCount(1);
timeline.play();
}
}
|
/*
* LumaQQ - Java QQ Client
*
* Copyright (C) 2004 luma <stubma@163.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package edu.tsinghua.lumaqq.ui.jobs;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import edu.tsinghua.lumaqq.models.ModelRegistry;
import edu.tsinghua.lumaqq.models.User;
import edu.tsinghua.lumaqq.qq.QQ;
import edu.tsinghua.lumaqq.qq.QQPort;
import edu.tsinghua.lumaqq.qq.beans.CustomHead;
import edu.tsinghua.lumaqq.qq.events.QQEvent;
import edu.tsinghua.lumaqq.qq.net.IConnection;
import edu.tsinghua.lumaqq.qq.packets.in._03.GetCustomHeadInfoReplyPacket;
import edu.tsinghua.lumaqq.ui.MainShell;
import edu.tsinghua.lumaqq.ui.helper.FaceRegistry;
/**
* 得到自定义头像信息的任务
*
* @author luma
*/
public class GetCustomHeadInfoJob extends AbstractJob {
private static Log log = LogFactory.getLog(GetCustomHeadInfoJob.class);
private List<Integer> friends;
private List<CustomHead> headInfo;
private IConnection conn;
private int page;
private static final int MAX_INFO = 20;
@Override
public void prepare(MainShell m) {
super.prepare(m);
headInfo = new ArrayList<CustomHead>();
main.getClient().addQQListener(this);
}
@Override
public Object getLinkArgument() {
return headInfo;
}
@Override
public void clear() {
if(conn != null) {
main.getClient().releaseConnection(conn.getId());
conn = null;
}
main.getClient().removeQQListener(this);
}
@Override
public boolean isSuccess() {
return true;
}
@Override
protected boolean canRun() {
// 创建一个port
try {
conn = QQPort.CUSTOM_HEAD_INFO.create(main.getClient(), new InetSocketAddress(QQ.QQ_SERVER_DOWNLOAD_CUSTOM_HEAD, 4000), null, true);
} catch(IOException e) {
log.error("无法连接到自定义头像下载服务器");
return false;
}
// 得到有自定义头像好友的列表
friends = new ArrayList<Integer>();
Iterator<User> iter = ModelRegistry.getUserIterator();
while(iter.hasNext()) {
User u = iter.next();
if(u.hasCustomHead)
friends.add(u.qq);
}
// 判断列表是否大于0
if(friends.isEmpty())
return false;
return true;
}
@Override
protected void preLoop() {
// 排序列表
Collections.sort(friends, new Comparator<Integer>() {
public int compare(Integer o1, Integer o2) {
return o1 - o2;
}
});
// 开始请求自定义头像信息
log.debug("请求大小:" + friends.size());
page = 1;
main.getClient().customHead_GetInfo(friends.subList(0, Math.min(MAX_INFO, friends.size())), conn.getId());
}
@Override
protected void OnQQEvent(QQEvent e) {
switch(e.type) {
case QQEvent.USER_GET_CUSTOM_HEAD_INFO_OK:
processGetCustomHeadInfoSuccess(e);
break;
case QQEvent.SYS_TIMEOUT_03:
switch(e.operation) {
case QQ.QQ_03_CMD_GET_CUSTOM_HEAD_INFO:
processGetCustomHeadInfoTimeout(e);
break;
}
break;
}
}
/**
* 处理得到自定义头像信息成功事件
*
* @param e
*/
private synchronized void processGetCustomHeadInfoSuccess(QQEvent e) {
GetCustomHeadInfoReplyPacket packet = (GetCustomHeadInfoReplyPacket)e.getSource();
FaceRegistry reg = FaceRegistry.getInstance();
for(CustomHead head : packet.heads) {
User u = ModelRegistry.getUser(head.qq);
if(u.customHeadTimestamp < head.timestamp || !reg.hasFace(reg.getMd5ById(u.customHeadId)))
headInfo.add(head);
}
postGetCustomHeadInfo();
}
/**
* 处理得到自定义头像信息超时事件
*
* @param e
*/
private synchronized void processGetCustomHeadInfoTimeout(QQEvent e) {
postGetCustomHeadInfo();
}
/**
* 在得到自定义头像信息之后调用。判断是否已经得到所有好友自定义头像信息,如果是,开始请求自定义头像数据
*/
private void postGetCustomHeadInfo() {
if(friends.size() > page * MAX_INFO) {
main.getClient().customHead_GetInfo(friends.subList(page * MAX_INFO, Math.min(friends.size(), page * MAX_INFO + MAX_INFO)), conn.getId());
page++;
} else {
wake();
}
}
}
|
package com.tuitaking.point2offer;
/**
* 数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。
* 你可以假设数组是非空的,并且给定的数组总是存在多数元素。
* 示例1:
* 输入: [1, 2, 3, 2, 2, 2, 5, 4, 2]
* 输出: 2
* 来源:力扣(LeetCode)
* 链接:https://leetcode-cn.com/problems/shu-zu-zhong-chu-xian-ci-shu-chao-guo-yi-ban-de-shu-zi-lcof
* 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
*/
public class MajorityElement_39 {
public int majorityElement(int[] nums) {
int res = nums[0];
int count = 1;
for (int i = 1; i < nums.length; i++) {
if (nums[i] == res) {
count++;
} else {
count--;
if (count == 0) {
res = nums[i];
count++;
}
}
}
return res;
}
}
|
package com.dpka.Service;
import com.dpka.Dao.UserDao;
import com.dpka.Entity.User;
import com.dpka.Model.UserPojo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.transaction.Transactional;
@Service
@Transactional
public class UserServiceImpl implements UserService {
@Autowired
UserDao userDao;
@Override
public UserPojo createUser(int id, String firstname, String lastname, String username, String email, String password) {
User user = new User(id,firstname,lastname,username,email,password);
userDao.createUser(user);
UserPojo userPojo=new UserPojo();
userPojo.setId(user.getId());
userPojo.setFirstname(user.getFirstname());
userPojo.setLastname(user.getLastname());
userPojo.setUsername(user.getUsername());
userPojo.setEmail(user.getEmail());
userPojo.setPassword(user.getPassword());
return userPojo;
}
@Override
public UserPojo getUser(String email, String password) {
User user= userDao.getUser(email);
UserPojo userPojo=new UserPojo();
userPojo.setId(user.getId());
userPojo.setFirstname(user.getFirstname());
userPojo.setLastname(user.getLastname());
userPojo.setUsername(user.getUsername());
userPojo.setEmail(user.getEmail());
userPojo.setPassword(user.getPassword());
return userPojo;
}
}
|
package com.tencent.mm.plugin.appbrand.jsapi.file;
public final class s extends c<ao> {
private static final int CTRL_INDEX = -1;
private static final String NAME = "isdirSync";
public s() {
super(new ao());
}
}
|
package ai.boundless.reward.particle.initializers;
import java.util.Random;
import ai.boundless.reward.particle.Particle;
/**
* The type Xy acceleration initializer.
*/
public class XyAccelerationInitializer implements ParticleInitializer {
private float mXValue;
private float mYValue;
/**
* Instantiates a new Xy acceleration initializer.
*
* @param xValue the x value
* @param yValue the y value
*/
public XyAccelerationInitializer(float xValue, float yValue) {
mXValue = xValue;
mYValue = yValue;
}
@Override
public void initParticle(Particle p, Random r) {
p.mAccelerationX = mXValue;
p.mAccelerationY = mYValue;
}
}
|
public class TestStacktrace{
public static void main(String[] args){
test();
}
static void test(){
try{
StackTraceElement[] elems = Thread.currentThread().getStackTrace();
System.out.println(java.util.Arrays.toString(elems));
}catch(Exception e){}
}
}
|
package com.tianlang.controller;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
public class TwoServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 通过request索要全局作用域对象
ServletContext application = request.getServletContext();
// 获取application里的数据
Integer money = (Integer) application.getAttribute("key01");
response.setContentType("text/html;charset=utf-8");
PrintWriter out = response.getWriter();
out.println("<font style = 'color:red;font-size:40'>"+money+"</font>");
}
}
|
package pl.edu.wat.wcy.pz.project.server.rabbit;
import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import pl.edu.wat.wcy.pz.project.server.dto.EmailDTO;
@AllArgsConstructor
@Component
@NoArgsConstructor
public class RabbitProducer {
private static final Logger LOGGER = LoggerFactory.getLogger(RabbitProducer.class);
@Value("${rabbitmq.exchange}")
private String exchange;
@Value("${rabbitmq.routingkey}")
private String routingKey;
@Autowired
private AmqpTemplate amqpTemplate;
public void sendToQueue(EmailDTO dto) {
try {
amqpTemplate.convertAndSend(exchange, routingKey, dto);
LOGGER.info("Message sent to queue");
} catch (AmqpException e) {
LOGGER.error("Exception in RabbitProducer " + e.getMessage());
}
}
}
|
package mk.ukim.finki.os.synchronization.juni17;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.Semaphore;
public class Scheduler {
public static Random random = new Random();
static List<Process> scheduled = new ArrayList<>();
public static Semaphore semafor=new Semaphore(0);
public static void main(String[] args)
{
Process procesi;
for(int i=0;i<100;i++)
{
try {
procesi=new Process();
register(procesi);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Scheduler sh=new Scheduler();
sh.run();
// TODO: kreirajte 100 Process nitki i registrirajte gi
// TODO: kreirajte Scheduler i startuvajte go negovoto pozadinsko izvrsuvanje
}
public static void register(Process process) {
scheduled.add(process);
}
public Process next() {
if (!scheduled.isEmpty()) {
return scheduled.remove(0);
}
return null;
}
public void run() {
try {
while (!scheduled.isEmpty()) {
Thread.sleep(100);
System.out.print(".");
this.next().execute();
semafor.acquire();
if(semafor.availablePermits()==1)
{
System.out.println("Terminated processing");
semafor.acquire();
}
else if(semafor.availablePermits()==0)
{
System.out.println("Finished processing");
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Done scheduling!");
}
}
class Process extends Thread {
public Integer duration;
public Process() throws InterruptedException {
this.duration = Scheduler.random.nextInt(1000);
Thread.sleep(this.duration);
}
public void execute() throws InterruptedException {
System.out.println("Executing[" + this + "]: " + duration);
this.start();
if(this.duration>700)
{
this.interrupt();
Scheduler.semafor.release(2);
}else{
Scheduler.semafor.release(1);
}
this.join();
// TODO: startuvajte go pozadinskoto izvrsuvanje
}
}
|
package com.kh.member.model.dao;
<<<<<<< HEAD
public class MemberDao {
=======
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import com.kh.common.JDBCTemplate;
<<<<<<< HEAD
=======
import com.kh.member.model.vo.Member;
>>>>>>> ee340be8a12028d82746491911757d9be61f64d7
import com.kh.member.model.vo.MemberPage;
import com.kh.member.model.vo.Profile;
public class MemberDao {
public ArrayList<MemberPage> rankingView(Connection conn) {
PreparedStatement pstmt = null;
ResultSet rset = null;
ArrayList<MemberPage> list = new ArrayList<MemberPage>();
String query = "select * from (select * from member join profile using(member_id) order by heart desc) where rownum <= 12";
try {
pstmt = conn.prepareStatement(query);
rset = pstmt.executeQuery();
while(rset.next()) {
Profile p = new Profile();
p.setId(rset.getString("member_id"));
p.setBlood(rset.getString("blood"));
p.setCity(rset.getString("city"));
p.setHeart(rset.getInt("heart"));
p.setHeight(rset.getInt("height"));
p.setHobby(rset.getString("hobby"));
p.setIntro(rset.getString("intro"));
p.setJob(rset.getString("profile_job"));
p.setReligion(rset.getString("religion"));
p.setSmoke(rset.getString("smoke"));
MemberPage mp = new MemberPage();
mp.setProfile(p);
mp.setAge(rset.getInt("age"));
mp.setPhoto(rset.getString("photopath"));
mp.setHeart(rset.getInt("heart"));
list.add(mp);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
JDBCTemplate.close(rset);
JDBCTemplate.close(pstmt);
}return list;
}
public ArrayList<MemberPage> randomView(Connection conn, int[] lotto) {
PreparedStatement pstmt = null;
ResultSet rset = null;
ArrayList<MemberPage> list = new ArrayList<MemberPage>();
String query = "select * from (select rownum rn,n.* from (select * from member join profile using(member_id)) n ) where rn in(?,?,?,?,?,?,?,?,?,?,?,?)";
try {
pstmt = conn.prepareStatement(query);
for(int i=0;i<12;i++) {
pstmt.setInt(i+1, lotto[i]);
}
rset = pstmt.executeQuery();
while(rset.next()) {
Profile p = new Profile();
p.setId(rset.getString("member_id"));
p.setBlood(rset.getString("blood"));
p.setCity(rset.getString("city"));
p.setHeart(rset.getInt("heart"));
p.setHeight(rset.getInt("height"));
p.setHobby(rset.getString("hobby"));
p.setIntro(rset.getString("intro"));
p.setJob(rset.getString("profile_job"));
p.setReligion(rset.getString("religion"));
p.setSmoke(rset.getString("smoke"));
MemberPage mp = new MemberPage();
mp.setProfile(p);
mp.setAge(rset.getInt("age"));
mp.setPhoto(rset.getString("photopath"));
mp.setHeart(rset.getInt("heart"));
list.add(mp);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
JDBCTemplate.close(rset);
JDBCTemplate.close(pstmt);
}return list;
}
public int heart() {
PreparedStatement pstmt = null;
int result = 0;
String query = "insert into heart values(?,?,sysdate)";
String query = "UPDATE PROFILE SET HEART = (heart)+? WHERE MEMBER_ID = '?'";
}
public int insertHeart(Connection conn, String toId, String fromId) {
PreparedStatement pstmt = null;
int result = 0;
String query = "insert into heart values(?,?,sysdate)";
try {
pstmt = conn.prepareStatement(query);
pstmt.setString(1, toId);
pstmt.setString(2, fromId);
result = pstmt.executeUpdate();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
JDBCTemplate.close(pstmt);
}return result;
}
public int insertMember(Connection conn, Member m) {
PreparedStatement pstmt = null;
int result = 0;
String query = "insert into member values(?, ?, ?, ?, ?, ?, ?, ?, 'standard', sysdate, ?, 0, ?, ?)";
try {
pstmt = conn.prepareStatement(query);
//Member m = new Member(id, pw, name, birth, gender, phone, email, city, "standard", null, 0, 0, null, photoname);
pstmt.setString(1, m.getId());
pstmt.setString(2, m.getPw());
pstmt.setString(3, m.getName());
pstmt.setDate(4, m.getBirth());
pstmt.setString(5, m.getGender());
pstmt.setString(6, m.getPhone());
pstmt.setString(7, m.getEmail());
pstmt.setString(8, m.getCity());
pstmt.setInt(9, m.getAge());
pstmt.setString(10, m.getPhotopath());
pstmt.setString(11, m.getPhotoname());
result = pstmt.executeUpdate();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
JDBCTemplate.close(pstmt);
}
return result;
}
public Member selectOne(Connection conn, String id) {
Member m = null;
PreparedStatement pstmt = null;
ResultSet rset = null;
String query = "select * from member where id = ?";
try {
pstmt = conn.prepareStatement(query);
pstmt.setString(1, id);
rset = pstmt.executeQuery();
if(rset.next()) {
m = new Member();
m.setId(rset.getString("id"));
m.setPw(rset.getString("pw"));
m.setName(rset.getString("name"));
m.setBirth(rset.getDate("birth"));
m.setGender(rset.getString("gender"));
m.setPhone(rset.getString("phone"));
m.setEmail(rset.getString("email"));
m.setCity(rset.getString("city"));
m.setGrade(rset.getString("grade"));
m.setEnrollDate(rset.getDate("enroll_date"));
m.setAge(rset.getInt("age"));
m.setBlockCount(rset.getInt("block_count"));
m.setPhotopath(rset.getString("photopath"));
m.setPhotoname(rset.getString("photoname"));
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
JDBCTemplate.close(rset);
JDBCTemplate.close(pstmt);
}
return m;
}
public int selectEmail(Connection conn, String emailAddr) {
PreparedStatement pstmt = null;
ResultSet rset = null;
int result = 0;
String query = "select * from member where email = ?";
try {
pstmt = conn.prepareStatement(query);
pstmt.setString(1, emailAddr);
rset = pstmt.executeQuery();
if(rset.next()) {
result = 1;
}else {
result = 0;
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
JDBCTemplate.close(rset);
JDBCTemplate.close(pstmt);
}
return result;
}
public Member login(Connection conn, String id, String pw) {
Member m = null;
PreparedStatement pstmt = null;
ResultSet rset = null;
String query = "select * from member where id = ? and pw = ?";
try {
pstmt = conn.prepareStatement(query);
pstmt.setString(1, id);
pstmt.setString(2, pw);
rset = pstmt.executeQuery();
if(rset.next()) {
m = new Member();
m.setId(rset.getString("id"));
m.setPw(rset.getString("pw"));
m.setName(rset.getString("name"));
m.setBirth(rset.getDate("birth"));
m.setGender(rset.getString("gender"));
m.setPhone(rset.getString("phone"));
m.setEmail(rset.getString("email"));
m.setCity(rset.getString("city"));
m.setGrade(rset.getString("grade"));
m.setEnrollDate(rset.getDate("enroll_date"));
m.setAge(rset.getInt("age"));
m.setBlockCount(rset.getInt("block_count"));
m.setPhotopath(rset.getString("photopath"));
m.setPhotoname(rset.getString("photoname"));
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
JDBCTemplate.close(rset);
JDBCTemplate.close(pstmt);
}
return m;
}
public int delete(Connection conn, String id) {
PreparedStatement pstmt = null;
int result = 0;
String query = "delete from member where id = ?";
try {
pstmt = conn.prepareStatement(query);
pstmt.setString(1, id);;
result = pstmt.executeUpdate();
System.out.println("삭제 "+result);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
JDBCTemplate.close(pstmt);
}
return result;
}
>>>>>>> d2ea2537b9be55e62062b94e1074354f41cb6858
}
|
package com.example.comprale;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import java.util.ArrayList;
import java.util.List;
public class FragmentCarrito extends Fragment {
ListView ListaCompas;
Button btnPagar;
ArrayList<String> ListaImagen=new ArrayList<>();
ArrayList<String> ListaNombres=new ArrayList<>();
ArrayList<Double> ListaPrecios=new ArrayList<>();
ArrayList<Integer> ListaCantidad=new ArrayList<>();
ListaComprasAdapter adapter = null;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
final View vista = inflater.inflate(R.layout.fragment_carrito, container, false);
ListaCompas=(ListView)vista.findViewById(R.id.listaCompra);
btnPagar = (Button)vista.findViewById(R.id.btnPagar);
CargarLista();
btnPagar.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(getContext(), MainActivitPago.class);
startActivity(intent);
}
});
return vista;
}
public void CargarLista(){
ListaImagen.clear();
ListaCantidad.clear();
ListaPrecios.clear();
ListaNombres.clear();
for (int i=0; i<3; i++){
ListaImagen.add("https://static.miweb.padigital.es/var/m_3/3f/3f5/46132/631340-no-disponible.jpg");
ListaNombres.add("Nombre del producto " + (i+1));
ListaPrecios.add(35.56+i);
ListaCantidad.add(50-i*2);
}
adapter = new ListaComprasAdapter(getContext(), ListaImagen);
ListaCompas.setAdapter(adapter);
}
public class ListaComprasAdapter extends BaseAdapter {
Context contexto;
List<String> ListaImagenes;
public ListaComprasAdapter(Context contexto, List<String> listaImagenes) {
this.contexto = contexto;
ListaImagenes = listaImagenes;
}
@Override
public int getCount() {
return ListaImagenes.size();
}
@Override
public Object getItem(int i) {
return ListaImagenes.get(i);
}
@Override
public long getItemId(int i) {
return 0;
}
@Override
public View getView(final int i, View view, ViewGroup viewGroup) {
View vista = view;
LayoutInflater inflate = LayoutInflater.from(contexto);
vista = inflate.inflate(R.layout.lista_compras,null);
ImageView imgProducto = (ImageView) vista.findViewById(R.id.imgProducto);
TextView txtNombre = (TextView)vista.findViewById(R.id.txtNombre);
TextView txtPrecio = (TextView)vista.findViewById(R.id.txtPrecio);
final TextView txtCantidad = (TextView)vista.findViewById(R.id.cantidad);
TextView btnEliminar = (TextView)vista.findViewById(R.id.btnEliminar);
Button btnMas=(Button)vista.findViewById(R.id.btnMas);
Button btnMenos=(Button)vista.findViewById(R.id.btnMenos);
Glide.with(imgProducto.getContext()).load(ListaImagenes.get(i)).into(imgProducto);
txtNombre.setText(ListaNombres.get(i));
txtPrecio.setText("$"+ListaPrecios.get(i).toString());
txtCantidad.setText(ListaCantidad.get(i).toString());
btnEliminar.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//ListaImagenes.remove(i);
ListaImagen.remove(i);
ListaNombres.remove(i);
ListaPrecios.remove(i);
ListaCantidad.remove(i);
adapter.notifyDataSetChanged();
}
});
btnMenos.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (Integer.parseInt(txtCantidad.getText().toString())>1){
txtCantidad.setText(""+(Integer.parseInt(txtCantidad.getText().toString())-1));
}
}
});
btnMas.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
txtCantidad.setText(""+(Integer.parseInt(txtCantidad.getText().toString())+1));
}
});
return vista;
}
}
}
|
package pers.pbyang.impl;
import java.sql.Connection;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import pers.pbyang.dao.TextInfoDao;
import pers.pbyang.entity.TextInfo;
public class TextInfoDaoImpl implements TextInfoDao {
private Connection conn = null;
private java.sql.PreparedStatement pstmt = null;
public TextInfoDaoImpl(Connection conn) {
this.conn = conn;
}
@Override
public boolean delete(int textid) throws Exception {
// TODO Auto-generated method stub
boolean flag = false;
String sql = "delete from text_info where text_id=?";
this.pstmt = this.conn.prepareStatement(sql);
this.pstmt.setInt(1, textid);
if (this.pstmt.executeUpdate() > 0) {
flag = true;
}
this.pstmt.close();
return flag;
}
@Override
public boolean insert(TextInfo text) throws Exception {
// TODO Auto-generated method stub
boolean flag = false;
String sql = "insert into text_info(text_name,type,up_mem,down_total,upTime,place,filesize,pdf) value (?,?,?,?,?,?,?,?)";
this.pstmt = this.conn.prepareStatement(sql);
this.pstmt.setString(1, text.getTextName());
this.pstmt.setString(2, text.getType());
this.pstmt.setString(3, text.getUpMem());
this.pstmt.setInt(4, text.getDownTotal());
this.pstmt.setDate(5, text.getUpTime());
this.pstmt.setString(6, text.getPlace());
this.pstmt.setInt(7, text.getFilesize());
this.pstmt.setString(8, text.getPdf());
if (this.pstmt.executeUpdate() > 0) {
flag = true;
}
this.pstmt.close();
return flag;
}
@Override
public boolean update(TextInfo text, int textid) throws Exception {
// TODO Auto-generated method stub
boolean flag = false;
// text_name,type,up_mem,down_total,upTime,place
String sql = "update text_info set text_name=?,type=?,up_mem=?,down_total=?,upTime=?,place=? ,filesize=? where text_id=?";
this.pstmt = this.conn.prepareStatement(sql);
this.pstmt.setInt(8, textid);
this.pstmt.setString(1, text.getTextName());
this.pstmt.setString(2, text.getType());
this.pstmt.setString(3, text.getUpMem());
this.pstmt.setInt(4, text.getDownTotal());
this.pstmt.setDate(5, text.getUpTime());
this.pstmt.setString(6, text.getPlace());
this.pstmt.setInt(7, text.getFilesize());
if (this.pstmt.executeUpdate() > 0) {
flag = true;
}
this.pstmt.close();
return flag;
}
@Override
public List<TextInfo> finAll() throws Exception {
List<TextInfo> all = new ArrayList<TextInfo>();
String sql = "select text_id, text_name,type,up_mem,down_total,upTime,place,filesize,pdf from text_info order by upTime desc";
this.pstmt = this.conn.prepareStatement(sql);
ResultSet rs = this.pstmt.executeQuery();
TextInfo text = null;
while (rs.next()) {
text = new TextInfo();
text.setTextId(rs.getInt(1));
text.setTextName(rs.getString(2));
text.setType(rs.getString(3));
text.setUpMem(rs.getString(4));
text.setDownTotal(rs.getInt(5));
text.setUpTime(rs.getDate(6));
text.setPlace(rs.getString(7));
text.setFilesize(rs.getInt(8));
text.setPdf(rs.getString(9));
all.add(text);
}
this.pstmt.close();
return all;
}
@Override
public TextInfo findByNumid(int textid) throws Exception {
// TODO Auto-generated method stub
TextInfo text = null;
String sql = "select text_name,type,up_mem,down_total,upTime,place,filesize,pdf from text_info where text_id=?";
this.pstmt = this.conn.prepareStatement(sql);
this.pstmt.setInt(1, textid);
ResultSet rs = this.pstmt.executeQuery();
if (rs.next()) {
text = new TextInfo();
text.setTextName(rs.getString(1));
text.setType(rs.getString(2));
text.setUpMem(rs.getString(3));
text.setDownTotal(rs.getInt(4));
text.setUpTime(rs.getDate(5));
text.setPlace(rs.getString(6));
text.setFilesize(rs.getInt(7));
text.setPdf(rs.getString(8));
}
this.pstmt.close();
return text;
}
@Override
public List<TextInfo> finAll1(String sql) throws Exception {
// TODO Auto-generated method stub
String sqll = null;
if ((sql != null) && (sql != "")) {
sqll = sql;
} else {
sqll = "select text_id, text_name,type,up_mem,down_total,upTime,place,filesize,pdf from text_info order by upTime desc";
}
List<TextInfo> all = new ArrayList<TextInfo>();
this.pstmt = this.conn.prepareStatement(sqll);
ResultSet rs = this.pstmt.executeQuery();
TextInfo text = null;
while (rs.next()) {
text = new TextInfo();
text.setTextId(rs.getInt(1));
text.setTextName(rs.getString(2));
text.setType(rs.getString(3));
text.setUpMem(rs.getString(4));
text.setDownTotal(rs.getInt(5));
text.setUpTime(rs.getDate(6));
text.setPlace(rs.getString(7));
text.setFilesize(rs.getInt(8));
text.setPdf(rs.getString(9));
all.add(text);
}
this.pstmt.close();
return all;
}
@Override
public List<TextInfo> finAll2() throws Exception {
List<TextInfo> all = new ArrayList<TextInfo>();
String sql = "select text_id, text_name,type,up_mem,down_total,upTime,place,filesize,pdf from text_info order by down_total desc ";
this.pstmt = this.conn.prepareStatement(sql);
ResultSet rs = this.pstmt.executeQuery();
TextInfo text = null;
while (rs.next()) {
text = new TextInfo();
text.setTextId(rs.getInt(1));
text.setTextName(rs.getString(2));
text.setType(rs.getString(3));
text.setUpMem(rs.getString(4));
text.setDownTotal(rs.getInt(5));
text.setUpTime(rs.getDate(6));
text.setPlace(rs.getString(7));
text.setFilesize(rs.getInt(8));
text.setPdf(rs.getString(9));
all.add(text);
}
this.pstmt.close();
return all;
}
}
|
package com.gtfs.action;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import com.gtfs.bean.LicBrnhHubPicPodDtls;
import com.gtfs.bean.LicOblApplicationMst;
import com.gtfs.bean.LicPolicyDtls;
import com.gtfs.bean.LicPolicyMst;
import com.gtfs.bean.LicRequirementDtls;
import com.gtfs.bean.UserMst;
import com.gtfs.service.interfaces.LicBrnhHubPicPodDtlsService;
import com.gtfs.service.interfaces.LicRequirementDtlsService;
import com.gtfs.service.interfaces.UserMstService;
@Component
@Scope("session")
public class HubPicLicPodForReqAction implements Serializable{
private Logger log = Logger.getLogger(HubPicLicPodForReqAction.class);
@Autowired
private LicRequirementDtlsService licRequirementDtlsService;
@Autowired
private UserMstService userMstService;
@Autowired
private LoginAction loginAction;
@Autowired
private LicBrnhHubPicPodDtlsService licBrnhHubPicPodDtlsService;
private List<Long> dispatchLists = new ArrayList<Long>();
private Long dispatchListNo;
private String deliveryMode;
private Boolean courierFlag;
private Boolean handFlag;
private Long empCode;
private String empName;
private UserMst employee;
private String podNo;
private String courierName;
private Boolean renderedListPanel;
private List<LicRequirementDtls> licRequirementDtlsList = new ArrayList<LicRequirementDtls>();
public void refresh(){
try{
dispatchListNo = null;
deliveryMode = null;
empCode = null;
empName = null;
handFlag = false;
courierFlag = false;
renderedListPanel = false;
if(licRequirementDtlsList!=null){
licRequirementDtlsList.clear();
}
if(dispatchLists!=null){
dispatchLists.clear();
}
dispatchLists = licRequirementDtlsService.findPodRequirmentForPicDispatch(loginAction.findHubForProcess("POS"));
}catch(Exception e){
log.info("HubPicLicPodForReqAction refresh Error : ", e);
}
}
public void searchForPod(){
try{
licRequirementDtlsList = licRequirementDtlsService.findRequirmentByDispatchListForPicDispatch(dispatchListNo, loginAction.getUserList().get(0).getBranchMst());
renderedListPanel = true;
}catch(Exception e){
log.info("HubPicLicPodForReqAction searchForPod Error : ", e);
}
}
public void deliveryModeChange(){
if(deliveryMode.equals("H")){
handFlag = true;
courierFlag = false;
}else if(deliveryMode.equals("P")){
handFlag = false;
courierFlag = true;
}else{
handFlag = false;
courierFlag = false;
}
}
public void findEmployee(){
try{
List<UserMst> list = userMstService.findActiveUserByUserId(empCode);
if(!(list == null || list.size()==0)){
employee = list.get(0);
empName = list.get(0).getUserName();
}else{
licRequirementDtlsList.clear();
empName = null;
}
}catch(Exception e){
log.info("HubPicLicPodForReqAction findEmployee Error : ", e);
}
}
public void save(){
try{
Date now = new Date();
LicBrnhHubPicPodDtls licBrnhHubPicPodDtls = new LicBrnhHubPicPodDtls();
licBrnhHubPicPodDtls.setBranchHubPicFlag("H2P");
licBrnhHubPicPodDtls.setPodNo(podNo!=null ?podNo: (now.getTime()+loginAction.getUserList().get(0).getUserid()+""));
licBrnhHubPicPodDtls.setPodDate(now);
licBrnhHubPicPodDtls.setEmployee(employee);
licBrnhHubPicPodDtls.setCourierName(courierName);
licBrnhHubPicPodDtls.setCreatedBy(loginAction.getUserList().get(0).getUserid());
licBrnhHubPicPodDtls.setModifiedBy(loginAction.getUserList().get(0).getUserid());
licBrnhHubPicPodDtls.setCreatedDate(now);
licBrnhHubPicPodDtls.setModifiedDate(now);
licBrnhHubPicPodDtls.setDeleteFlag("N");
licBrnhHubPicPodDtls.setLicRequirementDtlses(licRequirementDtlsList);
for(LicRequirementDtls licRequirementDtls:licRequirementDtlsList){
licRequirementDtls.setLicBrnhHubPicPodDtls(licBrnhHubPicPodDtls);
}
Long id = licBrnhHubPicPodDtlsService.saveForHubPicPodDtls(licBrnhHubPicPodDtls);
if (id > 0) {
refresh();
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO,
"Save Successful : ", "PID POD Successfully"));
onLoad();
} else {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR,
"Save Unsuccessful : ", "PID POD Unsuccessful"));
}
}catch(Exception e){
log.info("HubPicLicPodForReqAction save Error : ", e);
}
}
public String onLoad(){
refresh();
return "/licHubActivity/hubPicLicPodForReq.xhtml";
}
/* GETTER SETTER */
public List<Long> getDispatchLists() {
return dispatchLists;
}
public void setDispatchLists(List<Long> dispatchLists) {
this.dispatchLists = dispatchLists;
}
public Long getDispatchListNo() {
return dispatchListNo;
}
public void setDispatchListNo(Long dispatchListNo) {
this.dispatchListNo = dispatchListNo;
}
public String getDeliveryMode() {
return deliveryMode;
}
public void setDeliveryMode(String deliveryMode) {
this.deliveryMode = deliveryMode;
}
public Boolean getCourierFlag() {
return courierFlag;
}
public void setCourierFlag(Boolean courierFlag) {
this.courierFlag = courierFlag;
}
public Boolean getHandFlag() {
return handFlag;
}
public void setHandFlag(Boolean handFlag) {
this.handFlag = handFlag;
}
public Long getEmpCode() {
return empCode;
}
public void setEmpCode(Long empCode) {
this.empCode = empCode;
}
public String getEmpName() {
return empName;
}
public void setEmpName(String empName) {
this.empName = empName;
}
public UserMst getEmployee() {
return employee;
}
public void setEmployee(UserMst employee) {
this.employee = employee;
}
public String getPodNo() {
return podNo;
}
public void setPodNo(String podNo) {
this.podNo = podNo;
}
public String getCourierName() {
return courierName;
}
public void setCourierName(String courierName) {
this.courierName = courierName;
}
public List<LicRequirementDtls> getLicRequirementDtlsList() {
return licRequirementDtlsList;
}
public void setLicRequirementDtlsList(
List<LicRequirementDtls> licRequirementDtlsList) {
this.licRequirementDtlsList = licRequirementDtlsList;
}
public Boolean getRenderedListPanel() {
return renderedListPanel;
}
public void setRenderedListPanel(Boolean renderedListPanel) {
this.renderedListPanel = renderedListPanel;
}
}
|
package mdpm.oscar;
import static org.junit.Assert.*;
import org.junit.Test;
public class DatatypeTest extends SqlParserTest {
@Test
public void parseCharacterDatatypes() {
parse("char").datatype();
parse("char(1)").datatype();
parse("char(1 char)").datatype();
parse("char(1 byte)").datatype();
parse("char(1024 char)").datatype();
parse("char(2000)");
parse("nchar").datatype();
parse("nchar(1)").datatype();
parse("nchar(1024)").datatype();
try { parse("nchar(1 byte)").datatype(); fail("no `byte`"); } catch (SqlParserException ex) {};
parse("character(1)").datatype();
parse("character(1024)").datatype();
parse("national character(1)").datatype();
parse("national character(1024)").datatype();
parse("national char (1)").datatype();
parse("national char (1024)").datatype();
parse("character varying (1)").datatype();
parse("character varying (2024)").datatype();
parse("varchar2(1)").datatype();
parse("varchar2(1 char)").datatype();
parse("varchar2(1024 char)").datatype();
parse("varchar2(4000 char)").datatype();
parse("char varying (1)").datatype();
parse("char varying (2024)").datatype();
parse("nchar varying (1)").datatype();
parse("nchar varying (2024)").datatype();
parse("nvarchar2(1)").datatype();
parse("nvarchar2(1024)").datatype();
parse("nvarchar2(4000)").datatype();
parse("national character varying (1)").datatype();
parse("national character varying (2024)").datatype();
parse("national char varying (1)").datatype();
parse("national char varying (1024)").datatype();
parse("varchar(1)").datatype();
parse("varchar(1024)").datatype();
}
@Test
public void parseNumberDatatype() {
parse("number").datatype();
parse("number(1)").datatype();
parse("number(1,4)").datatype();
parse("number(1,-4)").datatype();
parse("numeric").datatype();
parse("numeric(1)").datatype();
parse("numeric(1,1)").datatype();
parse("decimal").datatype();
parse("decimal(1)").datatype();
parse("decimal(1,1)").datatype();
parse("dec").datatype();
parse("dec(1)").datatype();
parse("dec(1,1)").datatype();
parse("float").datatype();
parse("float(1)").datatype();
parse("binary_float").datatype();
parse("binary_double").datatype();
parse("integer").datatype();
parse("int").datatype();
parse("smallint").datatype();
parse("double").datatype();
parse("double precision").datatype();
parse("real").datatype();
}
@Test
public void parseLongAndRawDatatype() {
parse("long").datatype();
parse("long raw").datatype();
parse("raw(1)").datatype();
parse("raw(1024)").datatype();
}
@Test
public void parseDatetimeDatatype() {
parse("date").datatype();
parse("timestamp").datatype();
parse("timestamp(0)").datatype();
parse("timestamp(1)").datatype();
parse("timestamp with time zone").datatype();
parse("timestamp with local time zone").datatype();
parse("timestamp(0) with time zone").datatype();
parse("timestamp(1) with time zone").datatype();
parse("timestamp(0) with local time zone").datatype();
parse("timestamp(1) with local time zone").datatype();
parse("interval year to month").datatype();
parse("interval year(1) to month").datatype();
parse("interval day to second").datatype();
parse("interval day(1) to second").datatype();
parse("interval day to second(0)").datatype();
parse("interval day to second(1)").datatype();
parse("interval day(1) to second(1)").datatype();
//parse("interval year(0) to month");
//parse("interval year(1024) to month");
//parse("interval day(0) to second");
//parse("interval day(1024) to second");
//parse("interval day to second(1024)");
//parse("interval day(0) to second(0)");
//parse("interval day(1024) to second(1024)");
}
@Test
public void parseLargeObjectDatatypes() {
parse("blob").datatype();
parse("clob").datatype();
parse("nclob").datatype();
parse("bfile").datatype();
}
@Test
public void parseRowIdDatatypes() {
parse("rowid").datatype();
parse("urowid").datatype();
parse("urowid(1)").datatype();
parse("urowid(1024)").datatype();
}
@Test
public void parseOracleSuppliedDatatype() {
parse("SYS.AnyData").datatype();
parse("SYS.AnyType").datatype();
parse("SYS.AnyDataSet").datatype();
parse("XMLType").datatype();
parse("URIType").datatype();
parse("SDO_Geometry").datatype();
parse("SDO_Topo_Geometry").datatype();
parse("SDO_GeoRaster").datatype();
parse("ORDAudio").datatype();
parse("ORDImage").datatype();
parse("ORDVideo").datatype();
parse("ORDDoc").datatype();
parse("ORDDicom").datatype();
parse("SI_StillImage").datatype();
parse("SI_AverageColor").datatype();
parse("SI_PositionalColor").datatype();
parse("SI_ColorHistogram").datatype();
parse("SI_Texture").datatype();
parse("SI_FeatureList").datatype();
parse("SI_Color").datatype();
}
}
|
/* given an array of numbers and a value 'k', find the pairs in the array whose sum = k
Eg: a[] = 1, 2, 3, 4, 5, 6
k = 6
pairs: [2,4], [3,3]*/
import java.util.*;
class TestClass {
public static void main(String args[] ) throws Exception {
Scanner sc = new Scanner(System.in);
String str = sc.nextLine();
int k = sc.nextInt();
HashMap<Integer, Integer> map= new HashMap<Integer, Integer>();
HashMap<Integer, Integer> out= new HashMap<Integer, Integer>();
HashMap<Integer, Integer> count = new HashMap<Integer,Integer>();
int size = 1;
for(String s: str.split(" "))
{
map.put(Integer.parseInt(s),k-Integer.parseInt(s));
if(count.containsKey(Integer.parseInt(s)))
{
count.put(Integer.parseInt(s),count.get(Integer.parseInt(s))+1);
}
else
count.put(Integer.parseInt(s),size);
}
Iterator<Map.Entry<Integer,Integer>> itr = map.entrySet().iterator();
while(itr.hasNext())
{
Map.Entry<Integer,Integer> entry = itr.next();
// System.out.println("Key:"+entry.getKey()+"Value:"+entry.getValue());
if(map.containsKey(entry.getValue()))
{
// System.out.println("["+entry.getKey()+","+entry.getValue()+"]");
if(!out.containsKey(entry.getValue()) && !out.containsValue(entry.getValue()))
{
if (entry.getValue()==entry.getKey() && count.get(entry.getKey())>1)
out.put(entry.getKey(),entry.getValue());
else if(entry.getValue()!=entry.getKey())
out.put(entry.getKey(),entry.getValue());
}
}
}
Iterator<Map.Entry<Integer,Integer>> itr1 = out.entrySet().iterator();
while(itr1.hasNext())
{
Map.Entry<Integer,Integer> entry = itr1.next();
System.out.println("["+entry.getKey()+","+entry.getValue()+"]");
}
}
}
|
package xyz.maksimenko.iqbuzztt.service;
import java.util.List;
import xyz.maksimenko.iqbuzztt.Place;
public interface PlaceService {
public List<Place> getPlaces(long movieId);
}
|
package plp.orientadaObjetos3;
import plp.expressions2.memory.VariavelJaDeclaradaException;
import plp.expressions2.memory.VariavelNaoDeclaradaException;
import plp.orientadaObjetos1.comando.Comando;
import plp.orientadaObjetos1.excecao.declaracao.ClasseJaDeclaradaException;
import plp.orientadaObjetos1.excecao.declaracao.ClasseNaoDeclaradaException;
import plp.orientadaObjetos1.excecao.declaracao.ObjetoJaDeclaradoException;
import plp.orientadaObjetos1.excecao.declaracao.ObjetoNaoDeclaradoException;
import plp.orientadaObjetos1.excecao.declaracao.ProcedimentoJaDeclaradoException;
import plp.orientadaObjetos1.excecao.declaracao.ProcedimentoNaoDeclaradoException;
import plp.orientadaObjetos1.excecao.execucao.EntradaInvalidaException;
import plp.orientadaObjetos1.excecao.execucao.EntradaNaoFornecidaException;
import plp.orientadaObjetos1.memoria.colecao.ListaValor;
import plp.orientadaObjetos2.declaracao.ConstrutorNaoDeclaradoException;
import plp.orientadaObjetos3.declaracao.ListaDeclaracaoOO3;
import plp.orientadaObjetos3.excecao.declaracao.ModuloJaDeclaradoException;
import plp.orientadaObjetos3.memoria.AmbienteCompilacaoOO3;
import plp.orientadaObjetos3.memoria.AmbienteExecucaoOO3;
public class Programa {
private ListaDeclaracaoOO3 declaracoesOO;
private Comando comando;
public Programa(ListaDeclaracaoOO3 dec, Comando comando) {
this.declaracoesOO = dec;
this.comando = comando;
}
public ListaValor executar(AmbienteExecucaoOO3 ambiente)
throws VariavelJaDeclaradaException, VariavelNaoDeclaradaException,
ObjetoJaDeclaradoException, ObjetoNaoDeclaradoException,
ProcedimentoNaoDeclaradoException,
ProcedimentoJaDeclaradoException, ClasseJaDeclaradaException,
EntradaInvalidaException, EntradaNaoFornecidaException,
ConstrutorNaoDeclaradoException, ClasseNaoDeclaradaException {
if (ambiente == null)
throw new EntradaNaoFornecidaException();
ambiente.incrementa();
ambiente = (AmbienteExecucaoOO3) comando.executar(declaracoesOO
.elabora(ambiente));
ambiente.restaura();
return ambiente.getSaida();
}
public boolean checaTipo(AmbienteCompilacaoOO3 ambiente)
throws VariavelNaoDeclaradaException, VariavelJaDeclaradaException,
ProcedimentoNaoDeclaradoException,
ProcedimentoJaDeclaradoException, ClasseJaDeclaradaException,
EntradaNaoFornecidaException,
ConstrutorNaoDeclaradoException, ModuloJaDeclaradoException, ClasseNaoDeclaradaException {
boolean resposta;
if (ambiente == null) {
throw new EntradaNaoFornecidaException();
}
ambiente.incrementa();
resposta = declaracoesOO.checaTipo((AmbienteCompilacaoOO3) ambiente)
&& comando.checaTipo(ambiente);
ambiente.restaura();
return resposta;
}
}
|
package com.lrs.admin.es.dao;
import java.util.Map;
import com.lrs.admin.plugin.Page;
import com.lrs.admin.util.ParameterMap;
public interface Dao {
public String save(ParameterMap pm,String index,String type);
public int update(ParameterMap pm,String index,String type);
public int deltele(String id,String index,String type);
public Map<String, Object> find(String id,String index,String type);
public Object query(ParameterMap pm,String index,String type,Page page);
public Object multiMatchQuery(ParameterMap pm,String index,String type,Page page);
}
|
package 자바기본;
import java.util.ArrayList;
import java.util.Scanner;
public class 기본입출력8 {
public static void main(String[] args) {
// 시작할 값 입력, 종료할 값 입력
// 5의 배수만 더해서 출력
Scanner sc = new Scanner(System.in);
System.out.print("시작값 ");
int start = sc.nextInt();
System.out.print("종료값 ");
int end = sc.nextInt();
int sum = 0;
ArrayList<Integer> list = new ArrayList<>();
for (int i = start; i < end; i++) {
if (i % 5 == 0) {
sum += i ;
list.add(i);
}
}
double avg = (double)sum / list.size();
System.out.println("합 " + sum);
System.out.println("목록 " + list.size());
System.out.println("평균 " + avg);
System.out.println("카운트 " + list);
sc.close();
}
}
|
package layout;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import edu.cnm.deepdive.navdrawerfragments.R;
public class AlternateFragment extends Fragment {
private NavigationActivity activity;
public AlternateFragment() {
// Required empty public constructor
}
public static AlternateFragment newInstance() {
AlternateFragment fragment = new AlternateFragment();
Bundle args = new Bundle();
// Add args as necessary
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
// Handle arguments
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_alternate, container, false);
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
activity = (NavigationActivity) context;
}
@Override
public void onDetach() {
super.onDetach();
activity = null;
}
}
|
package com.takshine.wxcrm.service.impl;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import com.takshine.core.service.exception.CRMException;
import com.takshine.marketing.domain.Activity;
import com.takshine.marketing.domain.ActivityParticipant;
import com.takshine.marketing.domain.Participant;
import com.takshine.marketing.service.ActivityService;
import com.takshine.marketing.service.ParticipantService;
import com.takshine.wxcrm.base.common.Constants;
import com.takshine.wxcrm.base.common.ErrCode;
import com.takshine.wxcrm.base.util.DateTime;
import com.takshine.wxcrm.base.util.HttpClient3Post;
import com.takshine.wxcrm.base.util.MailUtils;
import com.takshine.wxcrm.base.util.PropertiesUtil;
import com.takshine.wxcrm.base.util.SenderInfor;
import com.takshine.wxcrm.base.util.ServiceUtils;
import com.takshine.wxcrm.base.util.StringUtils;
import com.takshine.wxcrm.base.util.WxHttpConUtil;
import com.takshine.wxcrm.base.util.WxUtil;
import com.takshine.wxcrm.base.util.ZJDateUtil;
import com.takshine.wxcrm.base.util.ZJWKUtil;
import com.takshine.wxcrm.base.util.cache.RedisCacheUtil;
import com.takshine.wxcrm.base.util.runtime.SMSSentThread;
import com.takshine.wxcrm.base.util.runtime.ThreadExecute;
import com.takshine.wxcrm.base.util.runtime.ThreadRun;
import com.takshine.wxcrm.domain.BusinessCard;
import com.takshine.wxcrm.domain.Comments;
import com.takshine.wxcrm.domain.DcCrmOperator;
import com.takshine.wxcrm.domain.NoticeReport;
import com.takshine.wxcrm.domain.OperatorMobile;
import com.takshine.wxcrm.domain.Organization;
import com.takshine.wxcrm.domain.WorkReport;
import com.takshine.wxcrm.message.oauth.AccessToken;
import com.takshine.wxcrm.message.resp.Article;
import com.takshine.wxcrm.message.sugar.ContactAdd;
import com.takshine.wxcrm.message.sugar.ExpenseAdd;
import com.takshine.wxcrm.message.sugar.GatheringAdd;
import com.takshine.wxcrm.message.sugar.GatheringReq;
import com.takshine.wxcrm.message.sugar.OpptyAdd;
import com.takshine.wxcrm.message.sugar.ScheduleAdd;
import com.takshine.wxcrm.message.sugar.ScheduleReq;
import com.takshine.wxcrm.message.sugar.UserAdd;
import com.takshine.wxcrm.message.sugar.UserReq;
import com.takshine.wxcrm.message.sugar.UsersResp;
import com.takshine.wxcrm.service.BusinessCardService;
import com.takshine.wxcrm.service.CommentsService;
import com.takshine.wxcrm.service.LovUser2SugarService;
import com.takshine.wxcrm.service.OperatorMobileService;
import com.takshine.wxcrm.service.OrganizationService;
import com.takshine.wxcrm.service.ScheduledScansService;
import com.takshine.wxcrm.service.UserPerferencesService;
import com.takshine.wxcrm.service.WorkPlanService;
import com.takshine.wxcrm.service.WxRespMsgService;
import com.takshine.wxcrm.service.WxUserinfoService;
import com.takshine.wxcrm.service.ZJWKSystemTaskService;
@Service("scheduledScansService")
public class ScheduledScansServiceImpl implements ScheduledScansService {
// 日志
protected Logger logger = Logger.getLogger(ScheduledScansServiceImpl.class);
//----------------------------------------------微信公众号命令菜单接口使用---------------------------------
@Autowired
@Qualifier("wxUserinfoService")
private WxUserinfoService wxUserinfoService;
@Autowired
@Qualifier("zjwkSystemTaskService")
private ZJWKSystemTaskService wxZJWKSystemTaskService;
@Autowired
@Qualifier("wxRespMsgService")
private WxRespMsgService wxZJWKRespMsgService;
//---------------------------------------------------------------------------------------
private WxHttpConUtil util;
private OrganizationService organizationService;
private WxRespMsgService wxRespMsgService;
private OperatorMobileService operatorMobileService;
private BusinessCardService businessCardService;
private ZJWKSystemTaskService zjwkSystemTaskService;
private ActivityService activityService;
private ParticipantService participantService;
private UserPerferencesService userPerferencesService;
private CommentsService commentsService;
private WorkPlanService workPlanService;
public WorkPlanService getWorkPlanService() {
return workPlanService;
}
public void setWorkPlanService(WorkPlanService workPlanService) {
this.workPlanService = workPlanService;
}
private LovUser2SugarService lovUser2SugarService;
public void setLovUser2SugarService(LovUser2SugarService lovUser2SugarService) {
this.lovUser2SugarService = lovUser2SugarService;
}
public void setCommentsService(CommentsService commentsService) {
this.commentsService = commentsService;
}
public UserPerferencesService getUserPerferencesService() {
return userPerferencesService;
}
public void setUserPerferencesService(
UserPerferencesService userPerferencesService) {
this.userPerferencesService = userPerferencesService;
}
public void setParticipantService(ParticipantService participantService) {
this.participantService = participantService;
}
public void setActivityService(ActivityService activityService) {
this.activityService = activityService;
}
public ZJWKSystemTaskService getZjwkSystemTaskService() {
return zjwkSystemTaskService;
}
public void setZjwkSystemTaskService(ZJWKSystemTaskService zjwkSystemTaskService) {
this.zjwkSystemTaskService = zjwkSystemTaskService;
}
public BusinessCardService getBusinessCardService() {
return businessCardService;
}
public void setBusinessCardService(BusinessCardService businessCardService) {
this.businessCardService = businessCardService;
}
public OrganizationService getOrganizationService() {
return organizationService;
}
public void setOrganizationService(OrganizationService organizationService) {
this.organizationService = organizationService;
}
public WxHttpConUtil getUtil() {
return util;
}
public void setUtil(WxHttpConUtil util) {
this.util = util;
}
public WxRespMsgService getWxRespMsgService() {
return wxRespMsgService;
}
public void setWxRespMsgService(WxRespMsgService wxRespMsgService) {
this.wxRespMsgService = wxRespMsgService;
}
public OperatorMobileService getOperatorMobileService() {
return operatorMobileService;
}
public void setOperatorMobileService(
OperatorMobileService operatorMobileService) {
this.operatorMobileService = operatorMobileService;
}
/**
* 定时扫描通知信息(每天早上九点)并发邮件通知
*/
@SuppressWarnings("unchecked")
public void noticeWorks() {
Organization obj = new Organization();
obj.setCurrpages(0);
obj.setPagecounts(10000);
// 调用后台查询数据库
List<Organization> orgList = (List<Organization>) organizationService.findObjListByFilter(obj);
if (orgList != null && orgList.size() > 0) {
for (Organization organization : orgList) {
String crmurl = organization.getCrmurl();
if (StringUtils.isNotNullOrEmptyStr(crmurl)) {
GatheringReq greq = new GatheringReq();
greq.setModeltype(Constants.MODEL_TYPE_NOTICE);
greq.setType(Constants.ACTION_SEARCH);
greq.setCrmaccount(Constants.CRMID);
// 转换为json
String jsonStrGath = JSONObject.fromObject(greq).toString();
logger.info("noticeWork jsonStrGath => jsonStrGath is : "+ jsonStrGath);
// 多次调用sugar接口
String rstGath = util.postJsonData(crmurl,Constants.MODEL_URL_NOTICE, jsonStrGath,Constants.INVOKE_MULITY);
logger.info("noticeWork rst => rstGath is : " + rstGath);
JSONObject jsonGath = JSONObject.fromObject(rstGath.substring(rstGath.indexOf("{")));
List<GatheringAdd> glist = new ArrayList<GatheringAdd>();
List<ScheduleAdd> slist = new ArrayList<ScheduleAdd>();
List<ExpenseAdd> elist = new ArrayList<ExpenseAdd>();
List<OpptyAdd> olist = new ArrayList<OpptyAdd>();
List<ContactAdd> clist = new ArrayList<ContactAdd>();
if (!jsonGath.containsKey("errcode")) {
if (StringUtils.isNotNullOrEmptyStr(jsonGath.getString("tasks"))) {
slist = (List<ScheduleAdd>) JSONArray.toCollection(jsonGath.getJSONArray("tasks"),ScheduleAdd.class);
}
if (StringUtils.isNotNullOrEmptyStr(jsonGath.getString("gathering"))) {
glist = (List<GatheringAdd>) JSONArray.toCollection(jsonGath.getJSONArray("gathering"),GatheringAdd.class);
}
if (StringUtils.isNotNullOrEmptyStr(jsonGath.getString("expense"))) {
elist = (List<ExpenseAdd>) JSONArray.toCollection(jsonGath.getJSONArray("expense"),ExpenseAdd.class);
}
if (StringUtils.isNotNullOrEmptyStr(jsonGath.getString("opptys"))) {
olist = (List<OpptyAdd>) JSONArray.toCollection(jsonGath.getJSONArray("opptys"),OpptyAdd.class);
}
if (StringUtils.isNotNullOrEmptyStr(jsonGath.getString("contacts"))) {
clist = (List<ContactAdd>) JSONArray.toCollection(jsonGath.getJSONArray("contacts"),ContactAdd.class);
}
} else {
// 错误代码和消息
String errcode = jsonGath.getString("errcode");
String errmsg = jsonGath.getString("errmsg");
logger.info("noticeWork jsonGath errcode => errcode is : "+ errcode);
logger.info("noticeWork jsonGath errmsg => errmsg is : "+ errmsg);
}
// 邮件模板
String mainMailModule = PropertiesUtil.getMailContext("mainMailModule");
String branchMailModule = PropertiesUtil.getMailContext("branchMailModule");
String signature = PropertiesUtil.getMailContext("signature");
String link = PropertiesUtil.getMailContext("link");
// 封装的邮件内容与邮箱地址
Map<String, StringBuffer> map = new HashMap<String, StringBuffer>();
StringBuffer stringBuffer = new StringBuffer();
// 封装的wx推送消息与责任人
Map<String, StringBuffer> mapWx = new HashMap<String, StringBuffer>();
StringBuffer sbWx = new StringBuffer();
// email为key,content为value
// Map<String, String> mapKey = new HashMap<String,
// String>();
// 回款
if (glist != null && glist.size() > 0) {
String email = "";
// String ccemail = "";
Map<String, List<GatheringAdd>> mapGath = new HashMap<String, List<GatheringAdd>>();
List<GatheringAdd> list = new ArrayList<GatheringAdd>();
for (int i = 0; i < glist.size(); i++) {
GatheringAdd gatheringAdd = glist.get(i);
GatheringAdd gathering = new GatheringAdd();
boolean flag = true;
// String planDate =
// gatheringAdd.getPlanDate();//计划收款日期
email = gatheringAdd.getEmail();// 邮箱地址
// if(email==null){
// email="dengbo@takshine.com";
// }
// ccemail=gatheringAdd.getCcemail();//抄送人邮件地址
// 判断实际收款日期与当前日期是否相差三天
// if(DateTime.comDate(planDate)){
if (mapGath.keySet() != null&& mapGath.keySet().size() > 0&& !mapGath.keySet().contains(email)) {
list = new ArrayList<GatheringAdd>();
flag = false;
}
gathering.setAssigner(gatheringAdd.getAssigner());
gathering.setContractName(gatheringAdd.getContractName());
gathering.setPlanDate(gatheringAdd.getPlanDate());
gathering.setPlanAmount(gatheringAdd.getPlanAmount());
gathering.setReceivedAmount(gatheringAdd.getReceivedAmount());
gathering.setAssignid(gatheringAdd.getAssignid());
if (StringUtils.isNotNullOrEmptyStr(email)) {
if (i == 0 || !flag) {
list.add(gathering);
mapGath.put(email, list);
} else {
List<GatheringAdd> lists = mapGath.get(email);
lists.add(gatheringAdd);
mapGath.put(email, lists);
}
// mapKey.put(email, ccemail);
}
}
if (mapGath != null && mapGath.size() > 0) {
for (String key : mapGath.keySet()) {
int i = 1;
String content = "";
String str = "";
for (GatheringAdd gatheringAdd : mapGath.get(key)) {
str += "<div>" + (i++) + "、关于合同【"+ gatheringAdd.getContractName()+ "】:计划于"+ gatheringAdd.getPlanDate()+ "收款¥"+ gatheringAdd.getPlanAmount()+ "万元";
if (StringUtils.isNotNullOrEmptyStr(gatheringAdd.getReceivedAmount())) {
str += ",目前已收¥"+ gatheringAdd.getReceivedAmount()+ "万元";
}
str += ";</div></br>";
}
String assigner = mapGath.get(key).get(0).getAssigner();
content = branchMailModule.replaceAll("@@count@@",mapGath.get(key).size()+ "笔回款需要催收,请及时跟进! ").replaceAll("@@list@@", str).replaceAll("@@assigner@@", assigner);
stringBuffer.append(content);
map.put(key, stringBuffer);
// SenderInfor senderInfor = new SenderInfor();
// String
// string=mainMailModule.replaceAll("@@content@@",
// content).replaceAll("@@link@@",link).replaceAll("@@signature@@",
// signature);
// senderInfor.setContent(string);
// senderInfor.setSubject("收款通知");
// senderInfor.setToEmails(key.split(";")[1]);
// MailUtils.sendEmail(senderInfor);
stringBuffer = new StringBuffer();
// 微信推送消息
String assignerId = mapGath.get(key).get(0).getAssignid();
String planDate = mapGath.get(key).get(0).getPlanDate();
String cont = "您今天有" + mapGath.get(key).size()+ "笔回款需要催收,";
String detailUrl = "/gathering/list?viewtype=analyticsview&assignerId="+ assignerId+ "&startDate="+ planDate+ "&endDate=" + planDate;
sbWx.append(cont + "___" + detailUrl + ";");
mapWx.put(assignerId, sbWx);
sbWx = new StringBuffer();
// wxRespMsgService.respCommCustMsgByCrmId(assignerId,cont,detailUrl,operatorMobileService);
}
}
}
// 报销
if (elist != null && elist.size() > 0) {
String email = "";
Map<String, List<ExpenseAdd>> mapExpe = new HashMap<String, List<ExpenseAdd>>();
List<ExpenseAdd> list = new ArrayList<ExpenseAdd>();
for (int i = 0; i < elist.size(); i++) {
ExpenseAdd expenseAdd = elist.get(i);
boolean flag = true;
ExpenseAdd expense = new ExpenseAdd();
email = expenseAdd.getEmail();// 邮箱地址
if (mapExpe.keySet() != null&& mapExpe.keySet().size() > 0&& !mapExpe.keySet().contains(email)) {
list = new ArrayList<ExpenseAdd>();
flag = false;
}
expense.setAssigner(expenseAdd.getAssigner());// 经办人
// expense.setExpenseamount(expenseAdd.getExpenseamount());//报销金额
// expense.setExpensesubtypename(expenseAdd.getExpensesubtypename());
// expense.setExpensedate(expenseAdd.getExpensedate());
expense.setAssignid(expenseAdd.getAssignid());
expense.setExpensestatus(expenseAdd.getExpensestatus());
if (StringUtils.isNotNullOrEmptyStr(email)) {
if (i == 0 || !flag) {
list.add(expense);
mapExpe.put(email, list);
} else {
List<ExpenseAdd> lists = mapExpe.get(email);
lists.add(expense);
mapExpe.put(email, lists);
}
}
}
if (mapExpe != null && mapExpe.size() > 0) {
for (String key : mapExpe.keySet()) {
int i = 1;
String content = "";
// 微信推送消息
String assignerId = mapExpe.get(key).get(0).getAssignid();
// String str="map2.get(string)+"笔报销费用"+";
String string = "";
Map<String, String> map2 = new HashMap<String, String>();
for (ExpenseAdd expenseAdd : mapExpe.get(key)) {
map2.put(expenseAdd.getExpensestatus(),(i++) + "");
}
if (map2.keySet().contains("approving")) {
String detailUrl = "/expense/list?viewtype=approvalview&viewtypesel=approvalview";
string += map2.get("approving")+ "笔报销费用需要审批;";
if (mapWx != null && mapWx.size() > 0) {
if (mapWx.containsKey(assignerId)) {
sbWx = mapWx.get(assignerId);
sbWx.append("您今天有" + string+ "____" + detailUrl + ";");
mapWx.put(assignerId, sbWx);
sbWx = new StringBuffer();
} else {
mapWx.put(assignerId,new StringBuffer().append("您今天有"+ string+ "___"+ detailUrl+ ";"));
}
}
// wxRespMsgService.respCommCustMsgByCrmId(assignerId,"您今天有报销费用需要审批,",detailUrl,operatorMobileService);
}
if (map2.keySet().contains("reject")) {
String detailUrl = "/expense/list?viewtype=myview&viewtypesel=myview_reject&approval=reject";
string += map2.get("reject") + "笔报销费用被驳回;";
if (mapWx.containsKey(assignerId)) {
sbWx = mapWx.get(assignerId);
sbWx.append("您今天有" + string + "___"+ detailUrl + ";");
mapWx.put(assignerId, sbWx);
sbWx = new StringBuffer();
} else {
mapWx.put(assignerId,new StringBuffer().append("您今天有" + string+ "___"+ detailUrl+ ";"));
}
// wxRespMsgService.respCommCustMsgByCrmId(assignerId,"您今天有报销费用被驳回,",detailUrl,operatorMobileService);
}
content = branchMailModule.replaceAll("@@count@@", string).replaceAll("@@list@@", "");
if (map.keySet().contains(key)) {
content = content.replaceFirst("@@assigner@@,您好!</br>", "");
stringBuffer = map.get(key);
stringBuffer.append(content);
map.put(key, stringBuffer);
stringBuffer = new StringBuffer();
} else {
content = content.replaceAll("@@assigner@@", mapExpe.get(key).get(0).getAssigner());
map.put(key,new StringBuffer().append(content));
}
}
// for(String key : mapExpe.keySet()){
// int i=1;
// String content="";
// String str="";
// String string="";
// for(ExpenseAdd expenseAdd:mapExpe.get(key)){
// if("approved".equals(expenseAdd.getExpensestatus())){
// string="需要您审批;";
// }else
// if("reject".equals(expenseAdd.getExpensestatus())){
// string="被驳回;";
// }
// str +=
// "<div>"+(i++)+"、"+expenseAdd.getAssigner()+"于"+expenseAdd.getExpensedate()+",在"+expenseAdd.getDepartment()+expenseAdd.getParenttype()+"【"+expenseAdd.getParentname()+"】过程中产生了一笔"+expenseAdd.getExpensesubtypename()+"(¥"+expenseAdd.getExpenseamount()+")"+string+"</div>";
// }
// content=branchMailModule.replaceAll("@@count@@",mapExpe.get(key).size()+"笔报销费用"+string).replaceAll("@@list@@",
// str).replaceAll("@@assigner@@",mapExpe.get(key).get(0).getAssigner());
// if(map!=null&&map.keySet().size()>0&&map.keySet().contains(key)){
// stringBuffer.append(content);
// map.put(key, stringBuffer.toString());
// }else{
// map.put(key,content);
// }
// }
}
}
// 任务
if (slist != null && slist.size() > 0) {
String email = "";
Map<String, List<ScheduleAdd>> mapSche = new HashMap<String, List<ScheduleAdd>>();
List<ScheduleAdd> list = new ArrayList<ScheduleAdd>();
for (int i = 0; i < slist.size(); i++) {
boolean flag = true;
ScheduleAdd scheduleAdd = slist.get(i);
ScheduleAdd schedule = new ScheduleAdd();
email = scheduleAdd.getEmail();// 邮箱地址
schedule.setAssigner(scheduleAdd.getAssigner());// 责任人
schedule.setStartdate(scheduleAdd.getStartdate());// 开始时间
schedule.setTitle(scheduleAdd.getTitle());// 主题
schedule.setAssignerid(scheduleAdd.getAssignerid());
if (mapSche.keySet() != null&& mapSche.keySet().size() > 0&& !mapSche.keySet().contains(email)) {
list = new ArrayList<ScheduleAdd>();
flag = false;
}
if (StringUtils.isNotNullOrEmptyStr(email)) {
if (i == 0 || !flag) {
list.add(schedule);
mapSche.put(email, list);
} else {
List<ScheduleAdd> lists = mapSche.get(email);
lists.add(schedule);
mapSche.put(email, lists);
}
}
}
if (mapSche != null && mapSche.size() > 0) {
for (String key : mapSche.keySet()) {
int i = 1;
String content = "";
String str = "";
for (ScheduleAdd scheduleAdd : mapSche.get(key)) {
str += "<div>" + (i++) + "、【"+ scheduleAdd.getTitle() + "】:开始于"+ scheduleAdd.getStartdate()+ ";</div></br>";
}
content = branchMailModule.replaceAll("@@count@@",mapSche.get(key).size() + "个任务,请及时查看!").replaceAll("@@list@@", str);
if (map.keySet().contains(key)) {
content = content.replaceFirst("@@assigner@@,您好!</br>", "");
stringBuffer = map.get(key);
stringBuffer.append(content);
map.put(key, stringBuffer);
stringBuffer = new StringBuffer();
} else {
content = content.replaceAll("@@assigner@@", mapSche.get(key).get(0).getAssigner());
map.put(key,new StringBuffer().append(content));
}
// 微信推送消息
String assignerId = mapSche.get(key).get(0).getAssignerid();
String cont = "您今天有" + mapSche.get(key).size()+ "个任务,";
String detailUrl = "/schedule/list?viewtype=todayview";
if (mapWx.containsKey(assignerId)) {
sbWx = mapWx.get(assignerId);
sbWx.append(cont + "___" + detailUrl + ";");
mapWx.put(assignerId, sbWx);
sbWx = new StringBuffer();
} else {
mapWx.put(assignerId,new StringBuffer().append(cont+ "___" + detailUrl + ";"));
}
// wxRespMsgService.respCommCustMsgByCrmId(assignerId,cont,detailUrl,operatorMobileService);
}
}
}
// 业务机会
if (olist != null && olist.size() > 0) {
String email = "";
Map<String, List<OpptyAdd>> mapOpp = new HashMap<String, List<OpptyAdd>>();
List<OpptyAdd> list = new ArrayList<OpptyAdd>();
for (int i = 0; i < olist.size(); i++) {
boolean flag = true;
OpptyAdd opptyAdd = olist.get(i);
OpptyAdd oppty = new OpptyAdd();
email = opptyAdd.getEmail();// 邮箱地址
oppty.setAssigner(opptyAdd.getAssigner());// 责任人
oppty.setAssignerid(opptyAdd.getAssignerid());
oppty.setName(opptyAdd.getName());// 业务机会名称
oppty.setDateclosed(opptyAdd.getDateclosed());// 业务机会结束时间
oppty.setSalesstagename(opptyAdd.getSalesstagename());// 业务机会阶段名称
if (mapOpp.keySet() != null&& mapOpp.keySet().size() > 0&& !mapOpp.keySet().contains(email)) {
list = new ArrayList<OpptyAdd>();
flag = false;
}
if (StringUtils.isNotNullOrEmptyStr(email)) {
if (i == 0 || !flag) {
list.add(oppty);
mapOpp.put(email, list);
} else {
List<OpptyAdd> lists = mapOpp.get(email);
lists.add(oppty);
mapOpp.put(email, lists);
}
}
}
if (mapOpp != null && mapOpp.size() > 0) {
for (String key : mapOpp.keySet()) {
int i = 1;
String content = "";
String str = "";
for (OpptyAdd opptyAdd : mapOpp.get(key)) {
str += "<div>" + (i++) + "、【"+ opptyAdd.getName() + "】:处于"+ opptyAdd.getSalesstagename()+ "阶段,预期关闭时间:"+ opptyAdd.getDateclosed()+ "</div></br>";
}
content = branchMailModule.replaceAll("您今天有@@count@@","您有" + mapOpp.get(key).size()+ "个业务机会停留时间过长,请及时查看!").replaceAll("@@list@@", str);
if (map.keySet().contains(key)) {
content = content.replaceFirst("@@assigner@@,您好!</br>", "");
stringBuffer = map.get(key);
stringBuffer.append(content);
map.put(key, stringBuffer);
stringBuffer = new StringBuffer();
} else {
content = content.replaceAll("@@assigner@@", mapOpp.get(key).get(0).getAssigner());
map.put(key,new StringBuffer().append(content));
}
// 微信推送消息
String assignerId = mapOpp.get(key).get(0).getAssignerid();
String cont = "您有" + mapOpp.get(key).size()+ "个业务机会停留时间过长,";
String detailUrl = "/analytics/oppty/salestage?assignerId="+ assignerId;
if (mapWx.containsKey(assignerId)) {
sbWx = mapWx.get(assignerId);
sbWx.append(cont + "___" + detailUrl + ";");
mapWx.put(assignerId, sbWx);
sbWx = new StringBuffer();
} else {
mapWx.put(assignerId,new StringBuffer().append(cont+ "___" + detailUrl + ";"));
}
// wxRespMsgService.respCommCustMsgByCrmId(assignerId,cont,detailUrl,operatorMobileService);
}
}
}
// 联系人
if (clist != null && clist.size() > 0) {
String email = "";
Map<String, List<ContactAdd>> mapCon = new HashMap<String, List<ContactAdd>>();
List<ContactAdd> list = new ArrayList<ContactAdd>();
for (int i = 0; i < clist.size(); i++) {
ContactAdd contactAdd = clist.get(i);
ContactAdd contact = new ContactAdd();
email = contactAdd.getEmail();// 邮箱地址
contact.setAssigner(contactAdd.getAssigner());// 责任人
contact.setConname(contactAdd.getConname());// 联系人姓名
contact.setPhonemobile(contactAdd.getPhonemobile());// 联系人电话
contact.setAssignerId(contactAdd.getAssignerId());
contact.setTimefre(contactAdd.getTimefre());
if (null == email) {
continue;
}
if (mapCon.keySet() == null
|| !mapCon.keySet().contains(email)) {
list = new ArrayList<ContactAdd>();
list.add(contact);
mapCon.put(email, list);
} else {
List<ContactAdd> lists = mapCon.get(email);
lists.add(contact);
mapCon.put(email, lists);
}
}
if (mapCon != null && mapCon.size() > 0) {
for (String key : mapCon.keySet()) {
int i = 1;
String content = "";
String str = "";
for (ContactAdd contactAdd : mapCon.get(key)) {
str += "<div>" + (i++) + "、【"+ contactAdd.getConname() + "】";
if (StringUtils.isNotNullOrEmptyStr(contactAdd.getPhonemobile())) {
str += ",电话号码:"+ contactAdd.getPhonemobile();
}
str += ";</div></br>";
}
content = branchMailModule.replaceAll("您今天有@@count@@","您有" + mapCon.get(key).size()+ "个联系人长时间没联系了,请及时查看!")
.replaceAll("@@list@@", str);
if (map.keySet().contains(key)) {
content = content.replaceFirst("@@assigner@@,您好!</br>", "");
stringBuffer = map.get(key);
stringBuffer.append(content);
map.put(key, stringBuffer);
stringBuffer = new StringBuffer();
} else {
content = content.replaceAll("@@assigner@@", mapCon.get(key).get(0).getAssigner());
map.put(key,new StringBuffer().append(content));
}
// 微信推送消息
String assignerId = mapCon.get(key).get(0).getAssignerId();
String timefre = mapCon.get(key).get(0).getTimefre();
String cont = "您有" + mapCon.get(key).size()+ "个联系人长时间没联系了,";
String date = DateTime.currentTime(DateTime.DateFormat1);
String detailUrl = "/contact/clist?viewtype=myview&datetime="+ date+ "&assignerid="+ assignerId+ "&timefre=" + timefre;
if (mapWx.containsKey(assignerId)) {
sbWx = mapWx.get(assignerId);
sbWx.append(cont + "___" + detailUrl + ";");
mapWx.put(assignerId, sbWx);
sbWx = new StringBuffer();
} else {
mapWx.put(assignerId,new StringBuffer().append(cont+ "___" + detailUrl + ";"));
}
// wxRespMsgService.respCommCustMsgByCrmId(assignerId,cont,detailUrl,operatorMobileService);
}
}
}
// 推送消息
if (mapWx != null && mapWx.size() > 0) {
for (String key : mapWx.keySet()) {
String str = mapWx.get(key).toString();
String[] strs = str.split(";");
wxRespMsgService.respCommCustMsgByCrmId(key, strs,operatorMobileService);
}
}
// 發送郵件
if (map != null && map.size() > 0) {
for (String key : map.keySet()) {
SenderInfor senderInfor = new SenderInfor();
senderInfor.setToEmails(key);
String content = map.get(key).toString();
// String ccemail = mapKey.get(key);
// senderInfor.setCcemail(ccemail);
String str = mainMailModule.replaceAll("@@content@@", content).replaceAll("@@link@@", link).replaceAll("@@signature@@", signature);
senderInfor.setContent(str);
senderInfor.setSubject("信息通知");
String mailDerail = PropertiesUtil.getMailContext("mail.derail");
if ("1".equals(mailDerail)) {
MailUtils.sendEmail(senderInfor);
}
}
}
}
}
}
}
/**
* 定时扫描通知信息(每天早上九点)并推送图文消息
*/
@SuppressWarnings("unchecked")
public void noticeWork() {
SenderInfor senderInfor1 = new SenderInfor();
senderInfor1.setContent("每日简报九点定时启动");
senderInfor1.setSubject("每日简报九点定时启动");
senderInfor1.setToEmails("pengmd@takshine.com");
String mailDerail1 = PropertiesUtil.getMailContext("mail.derail");
if ("1".equals(mailDerail1)) {
MailUtils.sendEmail(senderInfor1);
}
Organization obj = new Organization();
obj.setCurrpages(0);
obj.setPagecounts(10000);
// 调用后台查询数据库
List<Organization> orgList = (List<Organization>) organizationService.findObjListByFilter(obj);
if (orgList != null && orgList.size() > 0) {
for (Organization organization : orgList) {
String crmurl = organization.getCrmurl();
logger.info("ScheduledScansServiceImpl crmurl is ==>" + crmurl);
if (StringUtils.isNotNullOrEmptyStr(crmurl)) {
GatheringReq greq = new GatheringReq();
greq.setModeltype(Constants.MODEL_TYPE_NOTICE);
greq.setType(Constants.ACTION_SEARCH);
greq.setCrmaccount(Constants.CRMID);
// 转换为json
String jsonStrNotice = JSONObject.fromObject(greq).toString();
logger.info("ScheduledScansServiceImpl noticeWork jsonStrnotice => jsonStrNotice is : "+ jsonStrNotice);
// 多次调用sugar接口
try {
String rstNotice = util.postJsonData(crmurl,Constants.MODEL_URL_NOTICE, jsonStrNotice,Constants.INVOKE_SINGLE,30000);
logger.info("ScheduledScansServiceImpl noticeWork rst => rstNotice is : "+ rstNotice);
JSONObject jsonGath = JSONObject.fromObject(rstNotice.substring(rstNotice.indexOf("{")));
List<GatheringAdd> glist = new ArrayList<GatheringAdd>();
List<ScheduleAdd> slist = new ArrayList<ScheduleAdd>();
List<ExpenseAdd> elist = new ArrayList<ExpenseAdd>();
List<OpptyAdd> olist = new ArrayList<OpptyAdd>();
List<ContactAdd> clist = new ArrayList<ContactAdd>();
List<DcCrmOperator> dclist = new ArrayList<DcCrmOperator>();
if (!jsonGath.containsKey("errcode")) {
if (StringUtils.isNotNullOrEmptyStr(jsonGath.getString("tasks"))) {
slist = (List<ScheduleAdd>) JSONArray.toCollection(jsonGath.getJSONArray("tasks"),ScheduleAdd.class);
}
if (StringUtils.isNotNullOrEmptyStr(jsonGath.getString("gathering"))) {
glist = (List<GatheringAdd>) JSONArray.toCollection(jsonGath.getJSONArray("gathering"),GatheringAdd.class);
}
if (StringUtils.isNotNullOrEmptyStr(jsonGath.getString("expense"))) {
elist = (List<ExpenseAdd>) JSONArray.toCollection(jsonGath.getJSONArray("expense"),ExpenseAdd.class);
}
if (StringUtils.isNotNullOrEmptyStr(jsonGath.getString("opptys"))) {
olist = (List<OpptyAdd>) JSONArray.toCollection(jsonGath.getJSONArray("opptys"),OpptyAdd.class);
}
if (StringUtils.isNotNullOrEmptyStr(jsonGath.getString("contacts"))) {
clist = (List<ContactAdd>) JSONArray.toCollection(jsonGath.getJSONArray("contacts"),ContactAdd.class);
}
if (StringUtils.isNotNullOrEmptyStr(jsonGath.getString("emails"))) {
dclist = (List<DcCrmOperator>) JSONArray.toCollection(jsonGath.getJSONArray("emails"),DcCrmOperator.class);
}
} else {
// 错误代码和消息
String errcode = jsonGath.getString("errcode");
String errmsg = jsonGath.getString("errmsg");
logger.info("ScheduledScansServiceImpl noticeWork jsonGath errcode => errcode is : "+ errcode);
logger.info("ScheduledScansServiceImpl noticeWork jsonGath errmsg => errmsg is : "+ errmsg);
}
// 定义一个全局map变量
Map<String, List<Article>> map = new HashMap<String, List<Article>>();
// 邮件全局变量
Map<String, String> mailMap = new HashMap<String, String>();
List<Article> list = new ArrayList<Article>();
String date = DateTime.currentDate("yyyy年MM月dd日");
String projectname = PropertiesUtil.getAppContext("app.content");
// 定义简报的标题
Article article = new Article();
article.setTitle("【" + date + "简报" + "】");
article.setDescription("【" + date + "简报" + "】");
article.setPicUrl(projectname+ "/image/title_report_manager.png");
article.setUrl("");
String title = "";// 图文消息名称
String desc = "";// 描述
String url = "";// 地址
String picurl = "";// 图片地址
String string = "";// 邮件详细内容
logger.info("ScheduledScansServiceImpl each expenselist start....");
logger.info("ScheduledScansServiceImpl expenselist size ==>"+ elist.size());
// 报销费用
for (int i = 0; i < elist.size(); i++) {
Article article1 = new Article();
ExpenseAdd expenseAdd = elist.get(i);
String assignerid = expenseAdd.getAssignid();
String noticetype = expenseAdd.getNoticetype();
String nums = expenseAdd.getNums();
if (StringUtils.isNotNullOrEmptyStr(noticetype)) {
if (noticetype.contains("expense_reject")) {
title = "我的被驳回的报销(" + nums + ")";
desc = "我的被驳回的报销";
picurl = "/image/list_expense_reject.png";
url = "/expense/list?viewtype=myview&viewtypesel=myview_reject&approval=reject&";
string = "<div>-- " + nums+ "条被驳回的报销;</div>";
} else if (noticetype.contains("expense_approving")) {
title = "需要我审批的报销(" + nums + ")";
desc = "需要我审批的报销";
picurl = "/image/list_expense_wait.png";
url = "/expense/list?viewtype=approvalview&viewtypesel=approvalview&";
string = "<div>-- " + nums+ "条需要我审批的报销;</div>";
}
article1.setTitle(title);
article1.setDescription(desc);
article1.setPicUrl(projectname + picurl);
article1.setUrl(projectname + url);
}
if (map.keySet() == null|| !map.keySet().contains(assignerid)) {
list = new ArrayList<Article>();
list.add(article);
list.add(article1);
map.put(assignerid, list);
mailMap.put(assignerid, string);
} else {
List<Article> artlist = map.get(assignerid);
artlist.add(article1);
map.put(assignerid, artlist);
String str = mailMap.get(assignerid);
str += string;
mailMap.put(assignerid, str);
}
}
logger.info("ScheduledScansServiceImpl each opptylist start.....");
logger.info("ScheduledScansServiceImpl opptylist size ====>"
+ olist.size());
// 商机
for (int i = 0; i < olist.size(); i++) {
Article article1 = new Article();
OpptyAdd opptyAdd = olist.get(i);
String assignerid = opptyAdd.getAssignerid();
String noticetype = opptyAdd.getNoticetype();
String nums = opptyAdd.getNums();
if (StringUtils.isNotNullOrEmptyStr(noticetype)) {
if (noticetype.contains("oppty_delay")) {
title = "超过15天未跟进的业务机会(" + nums + ")";
desc = "超过15天未跟进的业务机会";
picurl = "/image/list_oppty_flow.png";
url = "/oppty/opptylist?viewtype=noticeview&";
string = "<div>-- " + nums+ "个超过15天未跟进的业务机会;</div>";
} else if (noticetype.contains("oppty_closed")) {
title = "过期未关闭的业务机会(" + nums + ")";
desc = "过期未关闭的业务机会";
picurl = "/image/list_oppty_unflow.png";
url = "/oppty/opptylist?viewtype=noclosedview&";
string = "<div>-- " + nums+ "个过期未关闭的业务机会;</div>";
}
article1.setTitle(title);
article1.setDescription(desc);
article1.setPicUrl(projectname + picurl);
article1.setUrl(projectname + url);
}
if (map.keySet() == null|| !map.keySet().contains(assignerid)) {
list = new ArrayList<Article>();
list.add(article);
list.add(article1);
map.put(assignerid, list);
mailMap.put(assignerid, string);
} else {
List<Article> artlist = map.get(assignerid);
artlist.add(article1);
map.put(assignerid, artlist);
String str = mailMap.get(assignerid);
str += string;
mailMap.put(assignerid, str);
}
}
logger.info("ScheduledScansServiceImpl each tasklist start.....");
logger.info("ScheduledScansServiceImpl tasklist size====>"
+ slist.size());
// 任务
for (int i = 0; i < slist.size(); i++) {
Article article1 = new Article();
ScheduleAdd scheduleAdd = slist.get(i);
String assignerid = scheduleAdd.getAssignerid();
String noticetype = scheduleAdd.getNoticetype();
String nums = scheduleAdd.getNums();
if (StringUtils.isNotNullOrEmptyStr(noticetype)) {
if (noticetype.contains("task_today")) {
title = "今日任务(" + nums + ")";
desc = "今日任务";
picurl = "/image/list_task_today.png";
url = "/schedule/list?viewtype=todayview&";
string = "<div>-- " + nums + "个今日任务;</div>";
} else if (noticetype.contains("task_history")) {
title = "延期未完成任务(" + nums + ")";
desc = "延期未完成任务";
picurl = "/image/list_task_uncomplete.png";
url = "/schedule/list?viewtype=noticeview&";
string = "<div>-- " + nums+ "个延期未完成的任务;</div>";
}
article1.setTitle(title);
article1.setDescription(desc);
article1.setPicUrl(projectname + picurl);
article1.setUrl(projectname + url);
}
if (map.keySet() == null|| !map.keySet().contains(assignerid)) {
list = new ArrayList<Article>();
list.add(article);
list.add(article1);
map.put(assignerid, list);
mailMap.put(assignerid, string);
} else {
List<Article> artlist = map.get(assignerid);
artlist.add(article1);
map.put(assignerid, artlist);
String str = mailMap.get(assignerid);
str += string;
mailMap.put(assignerid, str);
}
}
logger.info("ScheduledScansServiceImpl each contactlist start.....");
logger.info("ScheduledScansServiceImpl contactlist size===>"
+ clist.size());
// 联系人
for (int i = 0; i < clist.size(); i++) {
Article article1 = new Article();
ContactAdd contactAdd = clist.get(i);
String assignerid = contactAdd.getAssignerId();
String noticetype = contactAdd.getNoticetype();
String nums = contactAdd.getNums();
if (StringUtils.isNotNullOrEmptyStr(noticetype)) {
if (noticetype.contains("contact_freq")) {
title = "长期未联系的人(" + nums + ")";
desc = "长期未联系的人";
picurl = "/image/list_accnt_my.png";
url = "/contact/clist?viewtype=noticeview&";
string = "<div>-- " + nums+ "个长期未联系的人;</div>";
}
article1.setTitle(title);
article1.setDescription(desc);
article1.setPicUrl(projectname + picurl);
article1.setUrl(projectname + url);
}
if (map.keySet() == null|| !map.keySet().contains(assignerid)) {
list = new ArrayList<Article>();
list.add(article);
list.add(article1);
map.put(assignerid, list);
mailMap.put(assignerid, string);
} else {
List<Article> artlist = map.get(assignerid);
artlist.add(article1);
map.put(assignerid, artlist);
String str = mailMap.get(assignerid);
str += string;
mailMap.put(assignerid, str);
}
}
Map<String, String> eMap = new HashMap<String, String>();
logger.info("ScheduledScansServiceImpl each dclist start......");
logger.info("ScheduledScansServiceImpl dclist size===>"
+ dclist.size());
// 邮件列表
for (int i = 0; i < dclist.size(); i++) {
DcCrmOperator dcCrmOperator = dclist.get(i);
String email = dcCrmOperator.getOpEmail();
String assignername = dcCrmOperator.getOpName();
String assignerid = dcCrmOperator.getOpId();
if (StringUtils.isNotNullOrEmptyStr(assignerid)) {
eMap.put(assignerid, assignername + "-" + email);
}
}
logger.info("ScheduledScansServiceImpl each map start......");
// 发送图文消息
if (map != null && map.size() > 0) {
logger.info("ScheduledScansServiceImpl map size ===>"+ map.size());
for (String key : map.keySet()) {
List<Article> articles = map.get(key);
OperatorMobile oper = new OperatorMobile();
oper.setCrmId(key);
List<OperatorMobile> operlist = operatorMobileService.getOperMobileListByPara(oper);
String mailstr = eMap.get(key);
String assignername = "";
String email = "";
if (StringUtils.isNotNullOrEmptyStr(mailstr)&& mailstr.contains("-")) {
assignername = mailstr.split("-")[0];
email = mailstr.split("-")[1];
}
String mailmodule = PropertiesUtil.getMailContext("mailModule");
String mailcontent = mailMap.get(key);
logger.info("ScheduledScansServiceImpl send assignerid is ===>"+ key);
logger.info("ScheduledScansServiceImpl send assignername is ===>"+ assignername);
logger.info("ScheduledScansServiceImpl send email is ===>"+ email);
logger.info("ScheduledScansServiceImpl send mailcontent is ===>"+ mailcontent);
if (operlist != null && operlist.size() > 0) {
AccessToken at = WxUtil.getAccessToken(Constants.APPID,Constants.APPSECRET);
logger.info("ScheduledScansServiceImpl post wxuser at ===>"+ at);
OperatorMobile op = (OperatorMobile) operlist.get(0);
String openId = op.getOpenId();
String publicId = op.getPublicId();
logger.info("ScheduledScansServiceImpl post wxuser openId ===>"+ openId);
logger.info("ScheduledScansServiceImpl post wxuser publicId ===>"+ publicId);
// 追加的后缀参数
String tpUrl = "openId=" + op.getOpenId()+ "&publicId=" + publicId;
logger.info("ScheduledScansServiceImpl post wxuser tpUrl ===>"+ tpUrl);
WxUtil.customArticleMsgSend(at.getToken(),openId, articles, tpUrl);
String loginTime = RedisCacheUtil.getString(Constants.LOGINTIME_KEY+ "_" + key);
logger.info("ScheduledScansServiceImpl post wxuser loginTime ===>"+ loginTime);
if (StringUtils.isNotNullOrEmptyStr(loginTime)&& DateTime.comDate(loginTime,PropertiesUtil.getMailContext("mail.differtime"),DateTime.DateTimeFormat1)) {
logger.info("ScheduledScansServiceImpl send assigneremail start ===>");
SenderInfor senderInfor = new SenderInfor();
senderInfor.setContent(mailmodule.replaceAll("@@assigner@@",assignername).replaceAll("@@content@@",mailcontent));
senderInfor.setSubject(date + "简报");
if (StringUtils.isNotNullOrEmptyStr(email)) {
senderInfor.setToEmails(email);
logger.info("ScheduledScansServiceImpl send assigneremail email (longtime)===>"+ email);
String mailDerail = PropertiesUtil.getMailContext("mail.derail");
if ("1".equals(mailDerail)) {
MailUtils.sendEmail(senderInfor);
}
}
}
} else {
logger.info("ScheduledScansServiceImpl send email start ===>");
SenderInfor senderInfor = new SenderInfor();
senderInfor.setContent(mailmodule.replaceAll("@@assigner@@",assignername).replaceAll("@@content@@", mailcontent));
senderInfor.setSubject(date + "简报");
if (StringUtils.isNotNullOrEmptyStr(email)) {
senderInfor.setToEmails(email);
logger.info("ScheduledScansServiceImpl send email is ===>"+ email);
String mailDerail = PropertiesUtil.getMailContext("mail.derail");
if ("1".equals(mailDerail)) {
MailUtils.sendEmail(senderInfor);
}
}
}
}
}
} catch (Exception e) {
logger.error(e);
continue;
}
}
}
}
}
@SuppressWarnings("unused")
private int getUnderlingPlanNoEvalCount(String openId,String name) throws Exception
{
int n = 0;
List<String> rstuid = new ArrayList<String>();
/* List<String> crmIds = zjwkSystemTaskService.getCrmIdArr(openId, PropertiesUtil.getAppContext("app.publicId"), "Default Organization");
log.info("crmIds size = >" + crmIds.size());
for (int i = 0; i < crmIds.size(); i++) {
String crmid = crmIds.get(i);
log.info("crmid = >" + crmid);*/
//查询接口 获取人的数据列表
UserReq uReq = new UserReq();
//uReq.setCrmaccount(crmid);
uReq.setCurrpage("1");
uReq.setPagecount("9999");
//uReq.setFlag("");
uReq.setOpenId(openId);
uReq.setFlag("direct_subordinates");
uReq.setViewtype(Constants.SEARCH_VIEW_TYPE_TEAMVIEW);
//UsersResp uResp = cRMService.getSugarService().getLovUser2SugarService().getUserList(uReq);
UsersResp uResp = lovUser2SugarService.getUserList(uReq,util);
String errorCode = uResp.getErrcode();
if(ErrCode.ERR_CODE_0.equals(errorCode)){
String count = uResp.getCount();
List<UserAdd> ulist = uResp.getUsers();
if(null!=uResp.getUsers()&&uResp.getUsers().size()>0){
for(UserAdd userAdd:uResp.getUsers()){
String userid = userAdd.getUserid();
rstuid.add(userid) ;
}
}
/*if(count != null && Integer.parseInt(count) > 0){
for (int j = 0; j < ulist.size(); j++) {
UserAdd ua = ulist.get(j);
String uid = ua.getUserid();
log.info("uid = >" + uid);
rstuid.add(uid);
}
}*/
}
//}
for(int j=0;j<rstuid.size();j++){
Comments comments= new Comments();
comments.setAssignerid(rstuid.get(j));
comments.setCreator(name);
comments.setEval_type("lead");
n+= commentsService.findWorkReportNoEvalCount(comments);
}
return n;
}
/**
* 每日消息推送
* 1. 消息推送方式为微信
* 2. 每天早上9点定时发送
* 3. 推送内容包括:日程、未读通知、工作计划评价
*/
public void processMessages(){
try{
//获取所有用户信息
NoticeReport bc = new NoticeReport();
bc.setCurrpages(Constants.ZERO);
bc.setPagecounts(999999);
List<NoticeReport> cardList = zjwkSystemTaskService.searchAllSystemCard(bc);
sendMessage(cardList);
}catch(Exception ec){
logger.error(ec);
}
try{
//2015-04-16 新增 活动提醒
Activity act = new Activity();
String date = DateTime.preDayTime(DateTime.DateFormat1, 1);
act.setStart_date(date);
List<Activity> list = ServiceUtils.getCRMService().getDbService().getActivityService().searchAllActivity(act);
if(null!=list && list.size()>0){
String url = PropertiesUtil.getMsgContext("service.url1");
for(Activity activity : list){
String title = activity.getTitle();
String id = activity.getId();
String type = activity.getType();
String place = activity.getPlace();
String surl = "";
if("meet".equals(type)){
surl = "/zjwkactivity/new_meetdetail?id="+id+"&type=sms";
}else{
surl = "/zjwkactivity/new_detail?id="+id+"&type=sms";
}
ActivityParticipant ap = new ActivityParticipant();
ap.setActivityid(id);
List<Participant> parList = participantService.getParticipantListByActivity(ap);
if(null!=parList&&parList.size()>0){
for(Participant participant : parList){
String opMobile = participant.getOpMobile();
if(StringUtils.isNotNullOrEmptyStr(opMobile)){
String opName = participant.getOpName();
String content = "亲爱的"+opName+"您好,您报名的活动【"+title+"】将于明天在"+place+"举办。点此查看详情" + PropertiesUtil.getAppContext("zjwk.short.url") + ZJWKUtil.shortUrl(PropertiesUtil.getAppContext("app.content") + surl);
/*Map<String, Object> msgMap = new HashMap<String, Object>();
msgMap.put("mobile", opMobile);
msgMap.put("content", content);
msgMap.put("code", "231231");
HttpClient3Post.request(url, msgMap);*/
ThreadRun thread = new SMSSentThread("231231", opMobile,content);
ThreadExecute.push(thread);
}
}
}
}
}
}catch(Exception e){
logger.error(e);
}
}
public void sendMessage(List<NoticeReport> cardList){
Map<String,String> cityMap = new HashMap<String,String>();
final Map<String,String> messages = new HashMap<String,String>();
String currdate = "今天是"+DateTime.currentDate("MM月dd日") + "" + ZJDateUtil.getWeekOfDate(new Date()) +"。";
if(null != cardList){
for(NoticeReport bc : cardList){
try{
String responseData = "";
String weather = "";
responseData += "亲爱的"+bc.getName() + " 早安!\r\n" + currdate;
if(StringUtils.isNotNullOrEmptyStr(bc.getCity())){
if(null == cityMap.get(bc.getCity())){
weather = ZJWKUtil.getWeatherByCity(bc.getCity());
cityMap.put(bc.getCity(), weather);
}else{
weather = cityMap.get(bc.getCity());
}
if(StringUtils.isNotNullOrEmptyStr(weather)){
responseData += bc.getCity() +":" + weather +"\r\n";
}
}
if(bc.getMsgcount() >0){
responseData += "<a href=\""+PropertiesUtil.getAppContext("app.content")+"/home/index\">您一共有"+bc.getMsgcount() +"条未读通知。(回复字母T查看相关通知)</a> \r\n";
}
if(bc.getEvalcount() >0){
responseData += "<a href=\""+PropertiesUtil.getAppContext("app.content")+"/workplan/list\">您昨天共收到"+bc.getEvalcount() +"个工作计划评价。(回复字母P查看相关评价)</a> \r\n";
}
/* if(bc.getOwnerNoEvalCount() >0){
responseData += "<a href=\""+PropertiesUtil.getAppContext("app.content")+"/workplan/list\">您今天还有"+bc.getOwnerNoEvalCount() +"个工作计划未自我评价。(P)</a> \r\n";
}
Integer n = getUnderlingPlanNoEvalCount(bc.getOpenId(),bc.getName());
if(n >0){
responseData += "<a href=\""+PropertiesUtil.getAppContext("app.content")+"/workplan/list\">您今天还有"+bc.getOwnerNoEvalCount() +"个工作计划未自我评价。(P)</a> \r\n";
}
*/ if(bc.getActivitycount() >0){
responseData += "<a href=\""+PropertiesUtil.getAppContext("app.content")+"/zjactivity/noticelist\">您一共有"+bc.getActivitycount() +"个关注活动将要开始。(回复字母H查看相关活动)</a> \r\n";
}
if(bc.getTaskcount() >0 && bc.getUntaskcount() >0){
responseData += "<a href=\""+PropertiesUtil.getAppContext("app.content")+"/calendar/calendar\">您今天有"+bc.getTaskcount() +"个任务,"+bc.getUntaskcount()+"个延期任务。(回复字母R查看相关任务)</a> \r\n";
}
else if(bc.getUntaskcount() >0){
responseData +="<a href=\""+PropertiesUtil.getAppContext("app.content")+"/calendar/calendar\">您还有"+bc.getUntaskcount()+"个延期任务。(回复字母R查看相关任务)</a> \r\n";
}
responseData += "\r\n 您的朋友:小薇";
responseData += "\r\n "+DateTime.currentDate("yyyy-MM-dd");
messages.put(bc.getOpenId(), responseData);
}catch(Exception ec){
logger.error(ec);
}
}
}
for(String openid : messages.keySet()){
try{
wxRespMsgService.respReportByOpenId(openid,messages.get(openid));
}catch(Exception ec){
logger.error(ec);
}
}
}
/**
* 每日消息推送
* 1. 消息推送方式为微信
* 2. 每天早上9点定时发送
* 3. 推送内容包括:日程、未读通知、工作计划评价
*/
public void processMessagesByWxMenuKey(String openId){
String partyId = wxUserinfoService.getWxuserInfo(openId).getParty_row_id();
//获取所有用户信息
NoticeReport bc = new NoticeReport();
bc.setCurrpages(Constants.ZERO);
bc.setPagecounts(999999);
bc.setPartyId(partyId);
List<NoticeReport> cardList = wxZJWKSystemTaskService.searchAllSystemCard(bc);
sendMessage(cardList);
}
/**
* 提醒,每隔十五分钟扫描一次,并推送文字消息
*/
public void scanTask() {
Organization obj = new Organization();
obj.setCurrpages(0);
obj.setPagecounts(10000);
// 调用后台查询数据库
List<Organization> orgList = (List<Organization>) organizationService.findObjListByFilter(obj);
if (orgList != null && orgList.size() > 0) {
for (Organization organization : orgList) {
String crmurl = organization.getCrmurl();
if (StringUtils.isNotNullOrEmptyStr(crmurl)) {
ScheduleReq sreq = new ScheduleReq();
sreq.setModeltype(Constants.MODEL_TYPE_NOTICE);
sreq.setType(Constants.ACTION_SEARCH);
sreq.setCrmaccount(Constants.CRMID);
// 转换为json
String jsonStrNotice = JSONObject.fromObject(sreq).toString();
logger.info("scanTask jsonStrnotice => jsonStrNotice is : "+ jsonStrNotice);
// 多次调用sugar接口
String rstNotice = util.postJsonData(crmurl,Constants.MODEL_URL_NOTICE, jsonStrNotice,Constants.INVOKE_MULITY);
logger.info("scanTask rst => rstNotice is : " + rstNotice);
JSONObject jsonTask = JSONObject.fromObject(rstNotice.substring(rstNotice.indexOf("{")));
List<ScheduleAdd> slist = new ArrayList<ScheduleAdd>();
if (!jsonTask.containsKey("errcode")) {
if (StringUtils.isNotNullOrEmptyStr(jsonTask.getString("tasks"))) {
slist = (List<ScheduleAdd>) JSONArray.toCollection(jsonTask.getJSONArray("tasks"),ScheduleAdd.class);
}
} else {
// 错误代码和消息
String errcode = jsonTask.getString("errcode");
String errmsg = jsonTask.getString("errmsg");
logger.info("scanTask jsonTask errcode => errcode is : "+ errcode);
logger.info("scanTask jsonTask errmsg => errmsg is : "+ errmsg);
}
if (slist != null && slist.size() > 0) {
for (ScheduleAdd scheduleAdd : slist) {
String assignerid = scheduleAdd.getAssignerid();
String assigner = scheduleAdd.getAssigner();
String title = scheduleAdd.getTitle();
String rowid = scheduleAdd.getRowid();
// 微信推送消息
String cont = assigner + "您好!您在十五分钟之后有一个【" + title+ "】任务需要您参与,";
String detailUrl = "/schedule/detail?rowId="+ rowid;
String[] strs = new String[] { cont + "___"+ detailUrl };
wxRespMsgService.respCommCustMsgByCrmId(assignerid,strs, operatorMobileService);
}
}
}
}
}
}
/**
* 发送短信
*/
public void sendMsg() throws Exception{
Map<String, String> map = RedisCacheUtil.getStringMapAll(Constants.ZJWK_NOTICE_SEND);
if(null!=map&&map.keySet().size()>0){
BusinessCard bc = new BusinessCard();
String content = PropertiesUtil.getMsgContext("message.model3");
for(String key : map.keySet()){
bc.setOpenId(key);
String str = map.get(key);
String cardSize = str.split(";")[0];
String taskSize = str.split(";")[1];
content = content.replaceAll("$$cardsize", cardSize).replaceAll("$$tasksize", taskSize);
List<BusinessCard> list = businessCardService.getList(bc);
if(list!=null&&list.size()>0){
BusinessCard businessCard = list.get(0);
String phone = businessCard.getPhone();
if(StringUtils.isNotNullOrEmptyStr(phone)){
/*Map<String, Object> map1 = new HashMap<String, Object>();
map1.put("phone", phone);
map1.put("content", content);
HttpClient3Post.request(null, map1);*/
ThreadRun thread = new SMSSentThread("", phone,content);
ThreadExecute.push(thread);
}
}
}
}
}
/**
* 发送邮件
*/
public void sendEmail(){
Map<String, String> map = RedisCacheUtil.getStringMapAll(Constants.ZJWK_NOTICE_SEND);
if(null!=map&&map.keySet().size()>0){
BusinessCard bc = new BusinessCard();
String mainMailModule = PropertiesUtil.getMailContext("noticemailmodule");
for(String key : map.keySet()){
bc.setOpenId(key);
String str = map.get(key);
String cardSize = str.split(";")[0];
String taskSize = str.split(";")[1];
List<BusinessCard> list = businessCardService.getList(bc);
if(list!=null&&list.size()>0){
BusinessCard businessCard = list.get(0);
String email = businessCard.getEmail();
if(StringUtils.isNotNullOrEmptyStr(email)){
SenderInfor senderInfor = new SenderInfor();
senderInfor.setToEmails(email);
String content = mainMailModule.replaceAll("$$cardsize", cardSize).replaceAll("$$tasksize", taskSize);
senderInfor.setContent(content);
senderInfor.setSubject("消息通知");
String mailDerail = PropertiesUtil.getMailContext("mail.derail");
if ("1".equals(mailDerail)) {
MailUtils.sendEmail(senderInfor);
}
}
}
}
}
}
protected String getNoticeActivityMessage(int num){
try{
if (num == 0) return "";
StringBuffer sb = new StringBuffer();
sb.append("<a href=\"");
sb.append(PropertiesUtil.getAppContext("app.content"));
sb.append(String.format("/zjactivity/list?viewtype=owner\">您关注了%d个活动。(H)</a>",num));
return sb.toString();
}catch(Exception ec){
return "";
}
}
/**
* 导出评价(周),发送邮件
*/
public void exportWeekAppraise(){
try {
//取前一个自然周时间段
Calendar cal2 = Calendar.getInstance();
//cal2.setFirstDayOfWeek(Calendar.MONDAY);
cal2.add(Calendar.DAY_OF_WEEK, -7);
cal2.set(Calendar.HOUR_OF_DAY, 0);
cal2.set(Calendar.MINUTE, 0);
cal2.set(Calendar.SECOND, 0);
Calendar cal4 = Calendar.getInstance();
//cal2.setFirstDayOfWeek(Calendar.MONDAY);
cal4.set(Calendar.HOUR_OF_DAY, 0);
cal4.set(Calendar.MINUTE, 0);
cal4.set(Calendar.SECOND, 0);
cal4.add(Calendar.SECOND, -1);
Date start = cal2.getTime();
Date end = cal4.getTime();
ServiceUtils.getCRMService().getBusinessService().getWorkPlanService().exportAppraise(start,end);
} catch (CRMException e) {
logger.error(e);
}
}
/**
* 导出评价(月),发送邮件
*/
public void exportMonthAppraise(){
try {
//取前一个自然月时间段
Calendar cal1 = Calendar.getInstance();
cal1.add(Calendar.MONTH, -1);
cal1.set(Calendar.DAY_OF_MONTH, 1);
cal1.set(Calendar.HOUR_OF_DAY, 0);
cal1.set(Calendar.MINUTE, 0);
cal1.set(Calendar.SECOND, 0);
Calendar cal3 = Calendar.getInstance();
cal3.set(Calendar.DAY_OF_MONTH, 1);
cal3.set(Calendar.HOUR_OF_DAY, 0);
cal3.set(Calendar.MINUTE, 0);
cal3.set(Calendar.SECOND, 0);
cal3.add(Calendar.SECOND, -1);
Date start = cal1.getTime();
Date end = cal3.getTime();
ServiceUtils.getCRMService().getBusinessService().getWorkPlanService().exportAppraise(start,end);
} catch (CRMException e) {
logger.error(e);
}
}
/**
* 自动创建周工作计划
*/
public void autoWorkReportWeek() throws Exception{
userPerferencesService.updateAutoWeekWorkRerportByParam();
List<WorkReport> wReportList = new ArrayList<WorkReport>();
WorkReport wr = new WorkReport();
wr.setType("week");
wr.setStatus("draft");
Date d = new java.util.Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String create_time = sdf.format(d);
wr.setCreate_time(create_time);
wr.setRemark("自动生成工作计划");
wReportList = workPlanService.searchWorkPlanList(wr);
if(wReportList!=null&&wReportList.size()>0){
String responseData = "";
for(int i=0;i<wReportList.size();i++){
wr = wReportList.get(i);
responseData = "系统已经自动为您创建了周工作计划:"+wr.getTitle();
String detailUrl = "/workplan/detail?rowId="+ wr.getId()+"&viewtype=myview";
String assignerid = wr.getCrmId();
String[] strs = new String[] { responseData + "___"+ detailUrl };
wxRespMsgService.respCommCustMsgByCrmId(assignerid,strs, operatorMobileService);
}
}
}
/**
* 自动创建日工作计划
*/
public void autoWorkReportDay() throws Exception{
userPerferencesService.updateAutoDayWorkRerportByParam();
List<WorkReport> wReportList = new ArrayList<WorkReport>();
WorkReport wr = new WorkReport();
wr.setType("day");
wr.setStatus("draft");
Date d = new java.util.Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String create_time = sdf.format(d);
wr.setCreate_time(create_time);
wr.setRemark("自动生成工作计划");
wReportList = workPlanService.searchWorkPlanList(wr);
if(wReportList!=null&&wReportList.size()>0){
String responseData = "";
for(int i=0;i<wReportList.size();i++){
wr = wReportList.get(i);
responseData = "系统已经自动为您创建了日工作计划:"+wr.getTitle();
String detailUrl = "/workplan/detail?rowId="+ wr.getId()+"&viewtype=myview";
String assignerid = wr.getCrmId();
String[] strs = new String[] { responseData + "___"+ detailUrl };
wxRespMsgService.respCommCustMsgByCrmId(assignerid,strs, operatorMobileService);
}
}
}
}
|
package com.example.healthmanage.ui.activity.qualification;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import androidx.lifecycle.Observer;
import androidx.recyclerview.widget.LinearLayoutManager;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.example.healthmanage.BR;
import com.example.healthmanage.R;
import com.example.healthmanage.adapter.RightAdapter;
import com.example.healthmanage.adapter.SelectOfficeAdapter;
import com.example.healthmanage.base.BaseActivity;
import com.example.healthmanage.databinding.ActivitySelectOfficeBinding;
import com.example.healthmanage.ui.activity.qualification.response.DepartmentResponse;
import java.util.ArrayList;
import java.util.List;
/**
* 选择科室
*/
public class SelectDepartmentActivity extends BaseActivity<ActivitySelectOfficeBinding,DepartMentViewModel> {
private SelectOfficeAdapter selectOfficeAdapter;
private RightAdapter secondOfficeAdapter;
private int perPosition;
private List<DepartmentResponse.DataBean> firstBeanList;
private List<DepartmentResponse.DataBean> rightList;
@Override
protected void initData() {
initView();
viewModel.getDepartmentList();
}
private void initView() {
firstBeanList = new ArrayList<>();
dataBinding.mainRecycleView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
dataBinding.secondRecycleView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
selectOfficeAdapter = new SelectOfficeAdapter(firstBeanList,SelectDepartmentActivity.this);
dataBinding.mainRecycleView.setAdapter(selectOfficeAdapter);
rightList = new ArrayList<>();
secondOfficeAdapter = new RightAdapter(rightList,SelectDepartmentActivity.this);
dataBinding.secondRecycleView.setAdapter(secondOfficeAdapter);
selectOfficeAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
@Override
public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
if (perPosition != position){
firstBeanList.get(perPosition).setSelect(false);
firstBeanList.get(position).setSelect(true);
selectOfficeAdapter.notifyDataSetChanged();
//设置右列表数据,如果网络请求需添加一个id用于下方查询填值
initSecondList(position);
secondOfficeAdapter.notifyDataSetChanged();
perPosition = position;
}
}
});
secondOfficeAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
@Override
public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
Intent intent = new Intent();
intent.putExtra("department",rightList.get(position).getName());
intent.putExtra("departmentId",rightList.get(position).getId());
setResult(RESULT_OK,intent);
//跳转fragment
// startActivity(intent);
finish();
// Toast.makeText(SelectOfficeActivity.this, secondList.get(position).getOfficeName(), Toast.LENGTH_SHORT).show();
secondOfficeAdapter.notifyDataSetChanged();
}
});
dataBinding.edtSearchDepartment.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
if (s.length()>0){
viewModel.getDepartMentByName(s.toString());
}else {
rightList.clear();
secondOfficeAdapter.notifyDataSetChanged();
}
}
});
}
private void initSecondList(int position) {
if (rightList != null && rightList.size()>0){
rightList.clear();
}
if (firstBeanList.get(position).getList()!=null && firstBeanList.get(position).getList().size()>0){
for (DepartmentResponse.DataBean dataBean : firstBeanList.get(position).getList()){
rightList.add(dataBean);
}
}else {
rightList.add(null);
}
// secondOfficeAdapter.setNewData(secondDatas);
}
@Override
public void initViewListener() {
super.initViewListener();
viewModel.departmentMutableLiveData.observe(this, new Observer<List<DepartmentResponse.DataBean>>() {
@Override
public void onChanged(List<DepartmentResponse.DataBean> dataBeans) {
if (firstBeanList != null && firstBeanList.size()>0){
firstBeanList.clear();
}
dataBeans.get(0).setSelect(true);
firstBeanList.addAll(dataBeans);
selectOfficeAdapter.setNewData(firstBeanList);
selectOfficeAdapter.notifyDataSetChanged();
//左边的recycleview成功获取数据之后才可以给右边的赋值
initSecondList(0);
}
});
viewModel.departmentRightMutableData.observe(this, new Observer<List<DepartmentResponse.DataBean>>() {
@Override
public void onChanged(List<DepartmentResponse.DataBean> dataBeans) {
if (rightList != null && rightList.size()>0){
rightList.clear();
}
rightList.addAll(dataBeans);
secondOfficeAdapter.notifyDataSetChanged();
}
});
}
@Override
protected void registerUIChangeEventObserver() {
super.registerUIChangeEventObserver();
dataBinding.ivBack.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
}
@Override
protected int initVariableId() {
return BR.ViewModel;
}
@Override
protected int setContentViewSrc(Bundle savedInstanceState) {
return R.layout.activity_select_office;
}
}
|
package lildoop.mapReduce.client;
import java.io.IOException;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class Messenger {
private static final String MASTER_ADDRESS = "http://localhost:8080/LilDoop/restful";
private static final String PORT = "8081";
public static HttpURLConnection postJSON(String url, String json)
throws MalformedURLException, IOException {
HttpURLConnection connection = (HttpURLConnection) new URL(MASTER_ADDRESS + url).openConnection();
connection.setDoOutput(true);
connection.setRequestProperty("Content-type", "application/json");
connection.setRequestProperty("Accept-Charset", "UTF-8");
connection.setRequestMethod("POST");
OutputStream outputStream = connection.getOutputStream();
outputStream.write(json.getBytes("UTF-8"));
outputStream.flush();
outputStream.close();
return connection;
}
public static HttpURLConnection requestJSON(String url) throws MalformedURLException, IOException {
HttpURLConnection connection = (HttpURLConnection) new URL(MASTER_ADDRESS + url).openConnection();
connection.setRequestProperty("Content-type", "text/plain");
connection.setRequestProperty("Accept-Charset", "UTF-8");
connection.setRequestMethod("GET");
connection.connect();
return connection;
}
public static HttpURLConnection postJSONToAddress(String address, String url, String json)
throws MalformedURLException, IOException {
// HttpURLConnection connection = (HttpURLConnection) new URL(replacePort(address) + url).openConnection();
HttpURLConnection connection = (HttpURLConnection) new URL(address + url).openConnection();
connection.setDoOutput(true);
connection.setRequestProperty("Content-type", "application/json");
connection.setRequestProperty("Accept-Charset", "UTF-8");
connection.setRequestMethod("POST");
OutputStream outputStream = connection.getOutputStream();
outputStream.write(json.getBytes("UTF-8"));
outputStream.flush();
outputStream.close();
return connection;
}
public static HttpURLConnection requestJSONFromAddress(String address, String url) throws MalformedURLException, IOException {
// HttpURLConnection connection = (HttpURLConnection) new URL(replacePort(address) + url).openConnection();
HttpURLConnection connection = (HttpURLConnection) new URL(address + url).openConnection();
connection.setRequestProperty("Content-type", "text/plain");
connection.setRequestProperty("Accept-Charset", "UTF-8");
connection.setRequestMethod("GET");
return connection;
}
// private static String replacePort(String address) {
// int colonFirstIndex = address.indexOf(':');
// int colonIndex = address.indexOf(':', colonFirstIndex + 1);
// String firstPart = address.substring(0, colonIndex + 1);
// String secondPart = address.substring(colonIndex + 5);
// System.out.println(firstPart + "8081" + secondPart);
// return firstPart + "8081" + secondPart;
// }
}
|
package com.theksmith.steeringwheelinterface;
import com.theksmith.steeringwheelinterface.R;
import android.app.Activity;
import android.os.Bundle;
import android.preference.Preference;
import android.preference.Preference.OnPreferenceChangeListener;
import android.preference.Preference.OnPreferenceClickListener;
import android.preference.PreferenceFragment;
import android.preference.PreferenceManager;
/**
* A simple settings screen (the app's only UI).
*
* @author Kristoffer Smith <stuff@theksmith.com>
*/
public class SteeringWheelInterfaceSettings extends PreferenceFragment {
protected Activity mParentActivity;
@Override
public void onAttach(Activity activity){
super.onAttach(activity);
mParentActivity = activity;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.pref_general);
//actions (prefs acting only as buttons)
Preference exit = findPreference("action_exit");
exit.setOnPreferenceClickListener(mExitOnClickListener);
//for textbox type prefs
bindTxtPrefSummaryToValue(findPreference("scantool_baud"));
bindTxtPrefSummaryToValue(findPreference("scantool_device_number"));
bindTxtPrefSummaryToValue(findPreference("scantool_monitor_command"));
//TODO: create bindListPrefSummaryToValue() type functionality for the "scantool_protocol" pref
}
protected OnPreferenceClickListener mExitOnClickListener = new OnPreferenceClickListener() {
@Override
public boolean onPreferenceClick(Preference preference) {
mParentActivity.finish();
return false;
}
};
protected void bindTxtPrefSummaryToValue(Preference preference) {
preference.setOnPreferenceChangeListener(mTxtPrefChangeListener);
mTxtPrefChangeListener.onPreferenceChange(
preference,
PreferenceManager.getDefaultSharedPreferences(preference.getContext()).getString(preference.getKey(), ""));
}
protected OnPreferenceChangeListener mTxtPrefChangeListener = new Preference.OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object value) {
String stringValue = value.toString();
preference.setSummary(stringValue);
return true;
}
};
}
|
package com.hackaton.compgenblockdocs.repository;
import com.hackaton.compgenblockdocs.model.UserModel;
import org.springframework.data.mongodb.repository.MongoRepository;
public interface UserRepository extends MongoRepository<UserModel, String> {
}
|
package io.github.Theray070696.raycore.network;
import io.github.Theray070696.raycore.RayCore;
import io.netty.buffer.ByteBuf;
import net.minecraft.client.Minecraft;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.SoundEvent;
import net.minecraftforge.fml.common.network.ByteBufUtils;
import net.minecraftforge.fml.common.network.simpleimpl.IMessage;
import net.minecraftforge.fml.common.network.simpleimpl.IMessageHandler;
import net.minecraftforge.fml.common.network.simpleimpl.MessageContext;
/**
* Created by Theray070696 on 1/5/2017.
*/
public class PacketPlaySoundToAll implements IMessage
{
private String soundName;
public PacketPlaySoundToAll()
{
}
public PacketPlaySoundToAll(String soundName)
{
this.soundName = soundName;
}
@Override
public void fromBytes(ByteBuf buf)
{
this.soundName = ByteBufUtils.readUTF8String(buf);
}
@Override
public void toBytes(ByteBuf buf)
{
ByteBufUtils.writeUTF8String(buf, this.soundName);
}
public static class Handler implements IMessageHandler<PacketPlaySoundToAll, IMessage>
{
@Override
public IMessage onMessage(PacketPlaySoundToAll message, MessageContext ctx)
{
Minecraft.getMinecraft().addScheduledTask(new Runnable()
{
@Override
public void run()
{
if(RayCore.proxy.getSide().isClient())
{
if(Minecraft.getMinecraft().player != null)
{
if(SoundEvent.REGISTRY.containsKey(new ResourceLocation(message.soundName)) && SoundEvent.REGISTRY.getObject(new
ResourceLocation(message.soundName)) != null)
{
Minecraft.getMinecraft().player.playSound(SoundEvent.REGISTRY.getObject(new ResourceLocation(message.soundName)),
1.0f, 1.0f);
}
}
}
}
});
return null;
}
}
}
|
package com.company.task_003;
/**
* Created on 18.12.2019 10:50.
*
* @author Aleks Sidorenko (e-mail: alek.sidorenko@gmail.com).
* @version Id$.
* @since 0.1.
*/
public class Test {
@Save public int a;
@Save private String b;
public long c;
public int getA() {
return a;
}
public void setA(int a) {
this.a = a;
}
public String getB() {
return b;
}
public void setB(String b) {
this.b = b;
}
public long getC() {
return c;
}
public void setC(long c) {
this.c = c;
}
}
|
import java.net.*;
import java.io.*;
class ServerSide
{
public static void main(String args[]) throws Exception
{
int choice,a,b,c=0;
ServerSocket ss=new ServerSocket(1024);
Socket s=ss.accept();
BufferedReader br=new BufferedReader(new InputStreamReader(s.getInputStream()));
choice=Integer.parseInt(br.readLine());
a=Integer.parseInt(br.readLine());
b=Integer.parseInt(br.readLine());
switch(choice)
{
case 1:c=a+b;
break;
case 2:c=a-b;
break;
case 3:c=a*b;
break;
case 4:c=a/b;;
break;
case 5:c=(a%b);
break;
}
PrintStream pr=new PrintStream(s.getOutputStream());
pr.println(c);
ss.close();
s.close();
}
}
|
public class ComedianInfo {
protected Comedian comedianData;
protected int videoCount;
protected String comedianName;
ComedianInfo(){};
ComedianInfo(Comedian comedian, int videoCount){
this.comedianData = comedian;
this.videoCount = videoCount;
this.comedianName = comedianData.getFirstName() + " " + comedianData.getLastName();
}
public int getVideoCount() {
return this.videoCount;
}
public void setVideoCount(int videoCount) {
this.videoCount = videoCount;
}
public Comedian getComedianData() {
return this.comedianData;
}
public String getComedianName() {
return this.comedianName;
}
}
|
package com.dbc.ubiquity.Constant;
public class Str {
public static final String ACCOUNT_ERROR = "账户不存在";
public static final String PWD_ERROR = "账户不存在";
}
|
package com.tencent.mm.g.a;
public final class ni$a {
public String appId;
public String bYo;
public String byT;
public String mediaTagName;
}
|
package customer.gajamove.com.gajamove_customer.adapter;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import java.util.List;
import customer.gajamove.com.gajamove_customer.R;
import customer.gajamove.com.gajamove_customer.models.PriceService;
public class PriceServiceListAdapter extends BaseAdapter {
List<PriceService> priceServiceList;
Context context;
public PriceServiceListAdapter(List<PriceService> priceServiceList, Context context) {
this.priceServiceList = priceServiceList;
this.context = context;
}
@Override
public int getCount() {
return priceServiceList.size();
}
@Override
public Object getItem(int i) {
return null;
}
@Override
public long getItemId(int i) {
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup viewGroup) {
if (convertView==null)
convertView = LayoutInflater.from(context).inflate(R.layout.services_price_lay,null);
TextView service_name = convertView.findViewById(R.id.service_name);
TextView service_price = convertView.findViewById(R.id.service_price);
service_name.setText(priceServiceList.get(position).getService_name());
service_price.setText("RM"+priceServiceList.get(position).getService_price());
return convertView;
}
}
|
package com.debie.model;
|
import java.text.SimpleDateFormat;
import com.rabbitmq.client.Channel;
public class Globals {
public static final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
public static final String QUEUE_NAME = "publisher";
public static int id;
public static Channel channel;
}
|
package utils;
public class ProductCount{
private Integer productCount;
public ProductCount(){
}
public ProductCount(Integer productCount){
this.productCount = productCount;
}
}
|
package com.tencent.mm.protocal;
import com.tencent.mm.protocal.c.g;
public class c$cf extends g {
public c$cf() {
super("getLatestAddress", "get_recently_used_address", 46, true);
}
}
|
package com.shaoye.controller;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import com.shaoye.pojo.User;
import com.shaoye.service.IUserService;
/**
*
* @author hufan
*
*/
@Controller
@RequestMapping(value = "/user")
public class UserController {
private static Log log = LogFactory.getLog(UserController.class);
@Autowired
private IUserService userService;
@RequestMapping(value = "/index")
public String indexPage() {
log.info("enter the index page");
return "/user/index";
}
@RequestMapping(value = "/login")
public String loginPage() {
log.info("enter the login page");
return "/user/login";
}
@RequestMapping(value = "/register")
public String registerPage() {
log.info("enter the register page");
return "/user/register";
}
@RequestMapping(value = "doLogin", method = RequestMethod.POST)
public ModelAndView doLogin(@RequestParam("username") String username,
@RequestParam("password") String password,
HttpServletRequest request, HttpServletResponse response) {
ModelAndView model = new ModelAndView();
User user = new User();
user.setUsername(username);
user.setPassword(password);
boolean result = userService.getUserByUserName(user);
if(!result) {
model.setViewName("/user/fail");
model.addObject("user", user);
return model;
}
model.setViewName("/user/success");
model.addObject("user", user);
return model;
}
@RequestMapping(value = "doRegister")
public ModelAndView doRegister(@RequestParam("username") String username,
@RequestParam("password") String password,
@RequestParam("email") String email) {
ModelAndView model = new ModelAndView();
User user = new User();
user.setUsername(username);
user.setPassword(password);
return model;
}
@RequestMapping(value = "/get/{id}",method = RequestMethod.GET)
public ModelAndView gainUserById(@PathVariable("id") int id) {
ModelAndView modelAndView = new ModelAndView();
User user = userService.getUserById(id);
if (user != null) {
modelAndView.addObject("user", user);
modelAndView.setViewName("/user/message");
} else {
modelAndView.setViewName("/user/index");
}
return modelAndView;
}
}
|
/*
* [y] hybris Platform
*
* Copyright (c) 2000-2016 SAP SE
* All rights reserved.
*
* This software is the confidential and proprietary information of SAP
* 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 SAP Hybris.
*/
package com.cnk.travelogix.sapintegrations.converters.populator;
import de.hybris.platform.converters.Populator;
import de.hybris.platform.servicelayer.dto.converter.ConversionException;
import java.util.ArrayList;
import java.util.List;
import org.apache.log4j.Logger;
import org.springframework.beans.BeanUtils;
import com.cnk.travelogix.commons.error.Error;
import com.cnk.travelogix.constants.SapintegrationsConstants;
import com.cnk.travelogix.custom.zif.erp.ws.custmastercreate.ZifErpStStatusC;
import com.cnk.travelogix.custom.zif.erp.ws.custmastercreate.ZifTerpPartnerSaveResponse;
import com.cnk.travelogix.sapintegrations.zif.erp.ws.custmastercreate.data.ZifErpStStatusCData;
import com.cnk.travelogix.sapintegrations.zif.erp.ws.custmastercreate.data.ZifErpTtStatusCData;
import com.cnk.travelogix.sapintegrations.zif.erp.ws.custmastercreate.data.ZifTerpPartnerSaveDataResponse;
/**
*
*/
public class DefaultCustomerMasterCreateResponseDataPopulator extends AbstractErrorResponsePopulator
implements Populator<ZifTerpPartnerSaveResponse, ZifTerpPartnerSaveDataResponse>
{
private final Logger LOG = Logger.getLogger(getClass());
@Override
public void populate(final ZifTerpPartnerSaveResponse source, final ZifTerpPartnerSaveDataResponse target)
throws ConversionException
{
try
{
final ZifErpTtStatusCData zifErpTtStatusCData = new ZifErpTtStatusCData();
final List<ZifErpStStatusC> statues = source.getStatus() == null ? new ArrayList() : source.getStatus().getItem();
for (final ZifErpStStatusC statusC : statues)
{
final ZifErpStStatusCData zifErpStStatusCData = new ZifErpStStatusCData();
BeanUtils.copyProperties(statusC, zifErpStStatusCData);
zifErpTtStatusCData.getItem().add(zifErpStStatusCData);
if (SapintegrationsConstants.ERROR_STATUS.equalsIgnoreCase(statusC.getStatus()))
{
final Error er = populateError(statusC.getStatus(), statusC.getMessage());
target.getErrors().add(er);
}
}
target.setStatus(zifErpTtStatusCData);
}
catch (final Exception e)
{
LOG.error(e.getMessage(), e);
}
}
}
|
package org.km.common.domain;
import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.Calendar;
public class MfDate {
private java.util.Date date;
public MfDate(){
date = new java.util.Date();
}
public MfDate(Date date) {
this.date = new Date(date.getTime());
}
public Date toSqlDate() {
return new Date(date.getTime());
}
public MfDate addDays(int days) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.DATE, days);
return new MfDate(new Date(calendar.getTime().getTime()));
}
public boolean after(MfDate date) {
return getDate(this.date) > getDate(date.date);
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((date == null) ? 0 : date.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;
MfDate other = (MfDate) obj;
if (date == null) {
if (other.date != null)
return false;
} else if (!getDate(date).equals(getDate(other.date)))
return false;
return true;
}
private Integer getDate(java.util.Date date){
return new Integer(new SimpleDateFormat("yyyyMMdd").format(date));
}
}
|
package com.yulikexuan.organization.api.v1.controllers;
import com.yulikexuan.organization.api.v1.model.IOrganizationMapper;
import com.yulikexuan.organization.api.v1.model.OrganizationDTO;
import com.yulikexuan.organization.config.IServiceConfig;
import com.yulikexuan.organization.services.IOrganizationService;
import com.yulikexuan.organization.services.ResourceNotFoundException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@Slf4j
@RestController
@RequestMapping(value = "/v1/organizations")
public class OrganizationController {
private final IOrganizationService organizationService;
private final IServiceConfig serviceConfig;
@Autowired
public OrganizationController(IOrganizationService organizationService,
IServiceConfig serviceConfig) {
this.organizationService = organizationService;
this.serviceConfig = serviceConfig;
}
@GetMapping
@RequestMapping(value = "/{organizationId}")
public OrganizationDTO getOrganizationById(
@PathVariable Long organizationId) {
this.printConfigProperties();
return this.organizationService.getOrganizationById(organizationId)
.map(IOrganizationMapper.INSTANCE::toOrganizationDTO)
.orElseThrow(ResourceNotFoundException::new);
}
private void printConfigProperties() {
log.info(String.format("-------> The current example.property is %s.",
this.serviceConfig.getExampleProperty()));
log.info(String.format("-------> The current author.email is %s.",
this.serviceConfig.getAuthorEmail()));
}
}
|
package com.api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.dao.UserDAO;
@RestController
@RequestMapping("/api")
public class Api {
@Autowired
private UserDAO dao;
@PostMapping("/delete")
public String delete(@RequestParam("id") int id) {
if(dao.deleteUser(id))
return "1";
else
return "0";
}
}
|
/*
* Copyright (C) 2015 Miquel Sas
*
* This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public
* License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later
* version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with this program. If not, see
* <http://www.gnu.org/licenses/>.
*/
package com.qtplaf.library.trading.server.feed;
import java.util.EventObject;
import com.qtplaf.library.trading.data.Data;
import com.qtplaf.library.trading.data.Instrument;
import com.qtplaf.library.trading.data.Period;
import com.qtplaf.library.trading.server.OfferSide;
/**
* Data price feed event.
*
* @author Miquel Sas
*/
public class DataEvent extends EventObject {
/**
* Instrument.
*/
private Instrument instrument;
/**
* Period.
*/
private Period period;
/**
* Offer side.
*/
private OfferSide offerSide;
/**
* The price data.
*/
private Data data;
/**
* Constructor assigning fields.
*
* @param source Event source.
* @param instrument The instrument.
* @param period The period.
* @param offerSide Offer side.
* @param data The data.
*/
public DataEvent(Object source, Instrument instrument, Period period, OfferSide offerSide, Data data) {
super(source);
this.instrument = instrument;
this.period = period;
this.offerSide = offerSide;
this.data = data;
}
/**
* Returns the instrument.
*
* @return The instrument.
*/
public Instrument getInstrument() {
return instrument;
}
/**
* Returns the period.
*
* @return The period.
*/
public Period getPeriod() {
return period;
}
/**
* Returns the offer side.
*
* @return The offer side.
*/
public OfferSide getOfferSide() {
return offerSide;
}
/**
* Returns the price data.
*
* @return The price data.
*/
public Data getData() {
return data;
}
/**
* Returns a string representation of this event.
*
* @return A string representation.
*/
@Override
public String toString() {
StringBuilder b = new StringBuilder();
b.append(getSource().getClass().getSimpleName());
b.append(", ");
b.append(getInstrument().getDescription());
b.append(", ");
b.append(getPeriod());
b.append(", ");
b.append(getOfferSide());
b.append(", ");
b.append(getData());
return b.toString();
}
}
|
package com.abst;
public class Ham extends Sandwich {
int calorie = 290;
int sugar = 8;
int protein = 18;
int fat = 1;
int natrium = 800;
@Override
void make() {
System.out.println("Add 4 Ham slice!");
System.out.println("Add 2 cheeze!");
System.out.println("Add mayo score!");
System.out.println("Well Done!");
System.out.println();
}
@Override
void nutrition() {
System.out.println("natrium is " + natrium + "mg");
System.out.println("sugar is " + sugar+"g");
System.out.println("protein is " + protein+"g");
System.out.println("fat is " + fat+"g");
System.out.println();
}
@Override
void calorie() {
System.out.println("calorie is " + calorie +"kcal");
System.out.println();
}
}
|
package Classes;
import java.util.Comparator;
import java.util.Scanner;
import java.util.Set;
import java.util.TreeSet;
public class Schedule {
private Set<Seance> set;
public Schedule() {
this.set =new TreeSet<>();
}
public Set<Seance> getSet() {
return set;
}
public void addSeance(Seance ...s){
for (Seance sea : s) {
set.add(sea);
}
}
public void removeSeance(Seance s){
set.remove(s);
}
public void Output_seance() {
if (set.size()==0){
System.out.println( "Schedule on this day is empty");
}
else
for (Seance s : set) {
System.out.println(s);
}
}
}
|
package models;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.OneToOne;
import play.db.jpa.Model;
@Entity
public class Item extends Model {
private int quantity;
private float tax;
@OneToOne(cascade=CascadeType.ALL)
public Product product;
public Item(Product p, int qty)
{
this.product = p;
this.quantity = qty;
this.tax = TaxCalculator.getInstance().calculateTaxes(this.product.getCode(), this.product.getPrice(), qty);
}
public float calculateSubTotal() {
float x = 3;
return x;
}
public void decreaseStock() {
}
public float getTax()
{
return this.tax;
}
}
|
package com.tt.miniapp.util;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.media.ExifInterface;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import com.tt.b.a;
import com.tt.b.c;
import com.tt.miniapphost.host.HostDependManager;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
public class ImageUtil {
private static final String[] PATH_PROJECTION = new String[] { "_data" };
private static int calculateInSampleSize(BitmapFactory.Options paramOptions, int paramInt1, int paramInt2) {
int k = paramOptions.outHeight;
int m = paramOptions.outWidth;
int j = 1;
int i = 1;
if (k > paramInt2 || m > paramInt1) {
k /= 2;
m /= 2;
while (true) {
j = i;
if (k / i >= paramInt2) {
j = i;
if (m / i >= paramInt1) {
i *= 2;
continue;
}
}
break;
}
}
return j;
}
public static File compressImage(File paramFile, int paramInt1, int paramInt2, Bitmap.CompressFormat paramCompressFormat, int paramInt3, String paramString) throws IOException {
File file = (new File(paramString)).getParentFile();
if (!file.exists())
file.mkdirs();
try {
FileOutputStream fileOutputStream = new FileOutputStream(paramString);
} finally {
paramCompressFormat = null;
}
if (paramFile != null) {
paramFile.flush();
paramFile.close();
}
throw paramCompressFormat;
}
public static Bitmap cropCenterBitmap(Bitmap paramBitmap) {
int j = paramBitmap.getWidth();
int k = paramBitmap.getHeight();
int i = j;
if (j >= k)
i = k;
return Bitmap.createBitmap(paramBitmap, (paramBitmap.getWidth() - i) / 2, (paramBitmap.getHeight() - i) / 2, i, i);
}
public static Bitmap decodeSampledBitmapFromFile(File paramFile, int paramInt1, int paramInt2) throws IOException {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(paramFile.getAbsolutePath(), options);
options.inSampleSize = calculateInSampleSize(options, paramInt1, paramInt2);
options.inJustDecodeBounds = false;
Bitmap bitmap2 = BitmapFactory.decodeFile(paramFile.getAbsolutePath(), options);
Bitmap bitmap1 = bitmap2;
if (bitmap2 != null) {
Matrix matrix = new Matrix();
paramInt1 = (new ExifInterface(paramFile.getAbsolutePath())).getAttributeInt("Orientation", 0);
if (paramInt1 == 6) {
matrix.postRotate(90.0F);
} else if (paramInt1 == 3) {
matrix.postRotate(180.0F);
} else if (paramInt1 == 8) {
matrix.postRotate(270.0F);
}
bitmap1 = Bitmap.createBitmap(bitmap2, 0, 0, bitmap2.getWidth(), bitmap2.getHeight(), matrix, true);
}
return bitmap1;
}
public static String getVideoThumbPath(Context paramContext, int paramInt) {
Context context = null;
try {
Cursor cursor = paramContext.getContentResolver().query(MediaStore.Video.Thumbnails.EXTERNAL_CONTENT_URI, PATH_PROJECTION, "kind = 1 AND video_id = ?", new String[] { String.valueOf(paramInt) }, null);
return null;
} finally {
paramContext = context;
if (paramContext != null)
paramContext.close();
}
}
public static void loadBitmap(Context paramContext, String paramString, Rect paramRect, final BitmapCallback cb) {
if (paramContext != null) {
if (TextUtils.isEmpty(paramString))
return;
final ImageView imageView = new ImageView(paramContext);
c c = (new c(paramString)).a(new a() {
public final void onFail(Exception param1Exception) {
ImageUtil.BitmapCallback bitmapCallback = cb;
if (bitmapCallback == null)
return;
bitmapCallback.onFailed();
}
public final void onSuccess() {
if (cb == null)
return;
Drawable drawable = imageView.getDrawable();
if (drawable instanceof BitmapDrawable) {
cb.onSucceed(((BitmapDrawable)drawable).getBitmap());
return;
}
cb.onFailed();
}
});
if (paramRect != null)
c.a(paramRect.width(), paramRect.height());
c.a((View)imageView);
HostDependManager.getInst().loadImage(imageView.getContext(), c);
}
}
public static void loadBitmap(Context paramContext, String paramString, BitmapCallback paramBitmapCallback) {
loadBitmap(paramContext, paramString, null, paramBitmapCallback);
}
public static Bitmap rotaingImageView(int paramInt, Bitmap paramBitmap) {
Matrix matrix = new Matrix();
matrix.postRotate(paramInt);
Bitmap bitmap = Bitmap.createBitmap(paramBitmap, 0, 0, paramBitmap.getWidth(), paramBitmap.getHeight(), matrix, true);
if (bitmap != paramBitmap && paramBitmap != null && !paramBitmap.isRecycled())
paramBitmap.recycle();
return bitmap;
}
public static interface BitmapCallback {
void onFailed();
void onSucceed(Bitmap param1Bitmap);
}
}
/* Location: C:\Users\august\Desktop\tik\df_miniapp\classes.jar!\com\tt\miniap\\util\ImageUtil.class
* Java compiler version: 6 (50.0)
* JD-Core Version: 1.1.3
*/
|
package com.vrktech.springboot.gitactivities.entities;
import java.io.Serializable;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;
@Entity
public class RepoDetails implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@Column(name = "repo_id")
private Integer repoId;
@Column(name = "repo_name")
private String name;
@Column(name = "created_at")
private String createdAt;
@Column(name = "updated_at")
private String updatedAt;
@Column(name = "repo_owner")
private String ownerName;
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
@JoinColumn(name = "repoId", referencedColumnName = "repo_id", nullable = false)
public Set<WeeklyStatistics> weeklyStatistics;
public RepoDetails() {
super();
}
public RepoDetails(Integer repoId, String name, String createdAt, String updatedAt,
String ownerName) {
super();
this.repoId = repoId;
this.name = name;
this.createdAt = createdAt;
this.updatedAt = updatedAt;
this.ownerName = ownerName;
}
public Integer getRepoId() {
return repoId;
}
public void setRepoId(Integer repoId) {
this.repoId = repoId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCreatedAt() {
return createdAt;
}
public void setCreatedAt(String createdAt) {
this.createdAt = createdAt;
}
public String getUpdatedAt() {
return updatedAt;
}
public void setUpdatedAt(String updatedAt) {
this.updatedAt = updatedAt;
}
public String getOwnerName() {
return ownerName;
}
public void setOwnerName(String ownerName) {
this.ownerName = ownerName;
}
public Set<WeeklyStatistics> getWeeklyStatistics() {
return weeklyStatistics;
}
public void setWeeklyStatistics(Set<WeeklyStatistics> weeklyStatistics) {
this.weeklyStatistics = weeklyStatistics;
}
}
|
package Deck;
import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.ArrayList;
import java.util.Arrays;
public class Deck implements Externalizable {
static ArrayList<String> rates = new ArrayList<>();
static ArrayList<Card> cards = new ArrayList<>();
static ArrayList<Card> shuffledDeck = new ArrayList<>();
//Генерация колоды карт
public static void generateDeck(){
rates.addAll(Arrays.asList("2","3","4","5","6","7","8","9","10","11","12","13","14"));//0-12
for(int i=0; i<rates.size(); i++){
cards.add(new Clubs(rates.get(i)));
cards.add(new Hearts(rates.get(i)));
cards.add(new Diamonds(rates.get(i)));
cards.add(new Spades(rates.get(i)));
}
//System.out.println(cards.size());
}
//Излечь из колоды 1 карту
public static Card extractCard(){
return shuffledDeck.remove(0);
}
//Перемешать карты
public static void shuffleCards(){
while (cards.size()>0){
int index = (int)(Math.random()*cards.size());
Card card = cards.get(index);
shuffledDeck.add(card);
cards.remove(index);
}
//System.out.println(cards.size()+" в новой колоде");
//System.out.println(shuffledDeck.size()+" размер shuffledDeck");
/*for(Card card: shuffledDeck) {
if (card instanceof Clubs) {
System.out.println(((Clubs) card).getRate()+" "+((Clubs) card).getSUIT());
} else if (card instanceof Hearts) {
System.out.println(((Hearts) card).getRate()+" "+((Hearts) card).getSUIT());
} else if (card instanceof Diamonds) {
System.out.println(((Diamonds) card).getRate()+" "+((Diamonds) card).getSUIT());
} else if (card instanceof Spades) {
System.out.println(((Spades) card).getRate()+" "+((Spades) card).getSUIT());
}
}*/
}
@Override
public void writeExternal(ObjectOutput out) throws IOException {
out.writeObject(extractCard());
}
@Override
public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
}
}
|
package com.rishi.baldawa.iq;
import org.junit.Test;
import java.util.Arrays;
import static org.junit.Assert.assertEquals;
public class PascalTriangleGenerateTest {
@Test
public void generateTriangle() throws Exception {
assertEquals(new PascalTriangleGenerate().solution(5), Arrays.asList(
Arrays.asList(1),
Arrays.asList(1, 1),
Arrays.asList(1, 2, 1),
Arrays.asList(1, 3, 3, 1),
Arrays.asList(1, 4, 6, 4, 1)
));
assertEquals(new PascalTriangleGenerate().solution(1), Arrays.asList(
Arrays.asList(1)
));
}
}
|
package com.niit.ShoppingCart;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import com.niit.ShoppingCart.DAO.LoginDAO;
import com.niit.ShoppingCart.DAO.UserDetailsDAO;
import com.niit.ShoppingCart.model.Login;
import com.niit.ShoppingCart.model.UserDetails;
@Controller
public class HomeController
{
@Autowired
UserDetailsDAO ud;
@Autowired
LoginDAO ld;
@RequestMapping("/")
public ModelAndView home()
{
ModelAndView m1=new ModelAndView("Home");
return m1;
}
@RequestMapping("/reg")
public ModelAndView regi()
{
ModelAndView m1=new ModelAndView("Register");
return m1;
}
@ModelAttribute("UserDetails")
public UserDetails registerUser() {
return new UserDetails();
}
@RequestMapping(value = "storeUser", method = RequestMethod.POST)
public String addUser(@Valid @ModelAttribute("UserDetails") UserDetails registeruser,BindingResult result) {
if (result.hasErrors()) {
System.out.println("Errors");
return "register";
}
System.out.println(registeruser.getUsername());
ud.save(registeruser);
Login loginuser = new Login();
loginuser.setId(registeruser.getId());
loginuser.setUsername(registeruser.getUsername());
loginuser.setPassword(registeruser.getPassword());
loginuser.setStatus(registeruser.isStatus());
ld.save(loginuser);
return "register";
}
}
|
package com.zhouyi.business.core.model;
import java.io.Serializable;
import java.util.Date;
/**
* 订单信息
*
*
*/
public class PayOrderInfo implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
private Long id;
private String checkRemark;
private Integer totalBalance;
private Integer type;
private Integer status;
private Integer checkStatus;
private Integer channel;
private Long userId;
private String wxOpenid;
private Date updateTime;
private Date createTime;
private Long updateBy;
private String orderNo;
private String ipAddress;
private String remark;
private String channelSerialNum;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getUserId() {
return userId;
}
public void setUserId(Long userId) {
this.userId = userId;
}
public Date getUpdateTime() {
return updateTime;
}
public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public Long getUpdateBy() {
return updateBy;
}
public void setUpdateBy(Long updateBy) {
this.updateBy = updateBy;
}
public String getCheckRemark() {
return checkRemark;
}
public void setCheckRemark(String checkRemark) {
this.checkRemark = checkRemark;
}
public Integer getTotalBalance() {
return totalBalance;
}
public void setTotalBalance(Integer totalBalance) {
this.totalBalance = totalBalance;
}
public Integer getType() {
return type;
}
public void setType(Integer type) {
this.type = type;
}
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
public Integer getChannel() {
return channel;
}
public void setChannel(Integer channel) {
this.channel = channel;
}
public String getWxOpenid() {
return wxOpenid;
}
public void setWxOpenid(String wxOpenid) {
this.wxOpenid = wxOpenid;
}
public Integer getCheckStatus() {
return checkStatus;
}
public void setCheckStatus(Integer checkStatus) {
this.checkStatus = checkStatus;
}
public String getOrderNo() {
return orderNo;
}
public void setOrderNo(String orderNo) {
this.orderNo = orderNo;
}
public String getIpAddress() {
return ipAddress;
}
public void setIpAddress(String ipAddress) {
this.ipAddress = ipAddress;
}
public String getRemark() {
return remark;
}
public void setRemark(String remark) {
this.remark = remark;
}
public String getChannelSerialNum() {
return channelSerialNum;
}
public void setChannelSerialNum(String channelSerialNum) {
this.channelSerialNum = channelSerialNum;
}
}
|
package com.zhouyi.business.core.model;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.util.Date;
/**
* @author 李秸康
* @ClassNmae: SysUserRoleDto
* @Description: TODO 封装用户角色模型
* @date 2019/8/8 16:09
* @Version 1.0
**/
@Data
@ApiModel("角色模型")
public class SysUserRoleDto {
@ApiModelProperty(value = "角色关联主键")
private String pkId;
@ApiModelProperty(value = "角色Id")
private String roleId;
@ApiModelProperty(value = "删除标志")
private String deleteFlag;
@ApiModelProperty(value = "创建人Id")
private String createUserId;
@ApiModelProperty(value = "创建人姓名")
private String createUserName;
@ApiModelProperty(value = "创建时间")
private Date createDatetime;
@ApiModelProperty(value = "修改人id")
private String updateUserId;
@ApiModelProperty(value = "修改人姓名")
private String updateUserName;
@ApiModelProperty(value = "修改时间")
private Date updateDatetime;
@ApiModelProperty(value = "角色详情")
private SysRole sysRole;
}
|
public class ChuckleClickerRunner {
public static void main(String[] args) {
ChuckleClicker CC=new ChuckleClicker();
CC.makeButtons();
}
}
|
package com.pybeta.daymatter.ui;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.LoaderManager.LoaderCallbacks;
import android.support.v4.content.Loader;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.AdapterView.OnItemLongClickListener;
import com.actionbarsherlock.app.SherlockFragment;
import com.google.api.client.extensions.android.http.AndroidHttp;
import com.google.api.client.http.GenericUrl;
import com.google.api.client.http.HttpHeaders;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpResponse;
import com.google.api.client.http.HttpResponseException;
import com.google.api.client.http.HttpTransport;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.pybeta.daymatter.BuildConfig;
import com.pybeta.daymatter.HistoryToday;
import com.pybeta.daymatter.IContants;
import com.pybeta.daymatter.R;
import com.pybeta.daymatter.core.DataManager;
import com.pybeta.daymatter.utils.UtilityHelper;
import com.pybeta.ui.utils.ItemListAdapter;
import com.pybeta.ui.utils.ItemView;
import com.pybeta.util.AsyncLoader;
public class HistoryTodayFragement extends SherlockFragment implements LoaderCallbacks<List<HistoryToday>> {
protected View mMatterListView;
protected ListView mListView;
protected TextView mEmptyView;
protected ProgressBar mProgressBar;
private HistoryTodayAdapter mListAdapter;
private List<HistoryToday> mHistoryList = Collections.emptyList();
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if (mHistoryList != null && mHistoryList.size() > 0) {
setListShown(true);
}
getLoaderManager().initLoader(0, null, this);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
getSherlockActivity().getSupportActionBar().setTitle(R.string.title_activity_history_today);
return inflater.inflate(R.layout.fragment_history_today, null);
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mMatterListView = view.findViewById(R.id.matter_list);
mListView = (ListView) view.findViewById(android.R.id.list);
mListView.setOnItemLongClickListener(new OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
HistoryToday content = mListAdapter.getItem(position);
String mouth = content.getMmdd().substring(0, 2);
String day = content.getMmdd().substring(2);
UtilityHelper.share(getSherlockActivity(), getString(R.string.share_intent_subject),
String.format(getString(R.string.history_today_share_format), mouth, day, content.getContent()), null);
return false;
}
});
mProgressBar = (ProgressBar) view.findViewById(R.id.pb_loading);
mEmptyView = (TextView) view.findViewById(android.R.id.empty);
mListAdapter = new HistoryTodayAdapter(R.layout.history_item_view, LayoutInflater.from(getSherlockActivity()));
mListAdapter.setItems(mHistoryList.toArray());
mListView.setAdapter(mListAdapter);
}
public static class HistoryTodayLoader extends AsyncLoader<List<HistoryToday>> {
private Context mContext;
public HistoryTodayLoader(Context context) {
super(context);
mContext = context;
}
@Override
public List<HistoryToday> loadInBackground() {
Date today = new Date();
SimpleDateFormat format = new SimpleDateFormat("MMdd");
String todayStr = format.format(today);
String lang = IContants.COMMOM_LANG_EN;
Locale locale = UtilityHelper.getCurrentLocale(mContext);
if (locale != null && locale.equals(Locale.TRADITIONAL_CHINESE)) {
lang = IContants.COMMOM_LANG_TW;
} else if (locale != null && locale.equals(Locale.SIMPLIFIED_CHINESE)) {
lang = IContants.COMMOM_LANG_CN;
}
DataManager dataMgr = DataManager.getInstance(mContext);
List<HistoryToday> list = dataMgr.getHistoryDataByDate(todayStr + lang);
if (list == null || list.size() == 0) {
GenericUrl url = new GenericUrl(String.format(IContants.BASE_HISTORY_TODAY_URL, todayStr, lang));
HttpTransport httpTransport = AndroidHttp.newCompatibleTransport();
try {
HttpRequest request = httpTransport.createRequestFactory().buildGetRequest(url);
request.setHeaders(new HttpHeaders().setAccept("utf-8")
.setBasicAuthentication(IContants.REQUEST_PARAM_1, IContants.REQUEST_PARAM_2));
HttpResponse response = request.execute();
list = new Gson().fromJson(response.parseAsString(), new TypeToken<List<HistoryToday>>(){}.getType());
dataMgr.putHistoryData(todayStr + lang, list);
if (BuildConfig.DEBUG) System.out.println(list);
} catch (HttpResponseException e) {
if (BuildConfig.DEBUG) System.err.println("http status code: " + e.getStatusCode());
} catch (IOException e) {
if (BuildConfig.DEBUG) e.printStackTrace();
} catch (Exception e) {
if (BuildConfig.DEBUG) e.printStackTrace();
}
}
return list;
}
}
class HistoryTodayAdapter extends ItemListAdapter<HistoryToday, HistoryTodayView> {
public HistoryTodayAdapter(int viewId, LayoutInflater inflater) {
super(viewId, inflater);
}
@Override
protected void update(int position, HistoryTodayView view, HistoryToday item) {
view.mContent.setText(item.getContent());
}
@Override
protected HistoryTodayView createView(View view) {
return new HistoryTodayView(view);
}
}
class HistoryTodayView extends ItemView {
TextView mContent;
public HistoryTodayView(View view) {
super(view);
mContent = textView(view, R.id.tv_history_content);
}
}
@Override
public Loader<List<HistoryToday>> onCreateLoader(int id, Bundle args) {
return new HistoryTodayLoader(getSherlockActivity());
}
@Override
public void onLoadFinished(Loader<List<HistoryToday>> loader, List<HistoryToday> data) {
if (data == null) {
mHistoryList = Collections.emptyList();
} else {
mHistoryList = data;
}
mListAdapter.setItems(mHistoryList.toArray());
setListShown(true);
}
@Override
public void onLoaderReset(Loader<List<HistoryToday>> arg0) {
}
@Override
public void onDestroyView() {
mEmptyView = null;
mProgressBar = null;
mListView = null;
super.onDestroyView();
}
public void setListShown(boolean shown) {
if (shown) {
mProgressBar.setVisibility(View.GONE);
mMatterListView.setVisibility(View.VISIBLE);
if (mHistoryList != null && !mHistoryList.isEmpty()) {
mEmptyView.setVisibility(View.GONE);
} else {
mEmptyView.setVisibility(View.VISIBLE);
}
} else {
mProgressBar.setVisibility(View.VISIBLE);
mMatterListView.setVisibility(View.GONE);
}
}
}
|
package com.e6soft.bpm.dao.impl;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import com.e6soft.core.mybatis.BaseEntityDao;
import com.e6soft.core.mybatis.Query;
import com.e6soft.bpm.dao.NodeTemplateDao;
import com.e6soft.bpm.model.NodeTemplate;
@Transactional
@Repository("nodeTemplateDao")
public class NodeTemplateDaoImpl extends BaseEntityDao<NodeTemplate,String> implements NodeTemplateDao {
public NodeTemplateDaoImpl() {
super(NodeTemplate.class);
}
public String getTemplateIdByFormIdAndNodeId(String businessFormId, String nodeId) {
NodeTemplate template = new NodeTemplate();
template.setBusinessFormId(businessFormId);
template.setNodeId(nodeId);
Query<NodeTemplate> query = this.createQuery();
List<NodeTemplate> list = query.filterBean(template).list();
if(list.size()>0){
return list.get(0).getTemplateId();
}else
return "";
};
@Override
public String getFormIdByTemplateIdAndNodeId(String templateId,
String nodeId) {
NodeTemplate template = new NodeTemplate();
template.setTemplateId(templateId);
template.setNodeId(nodeId);
Query<NodeTemplate> query = this.createQuery();
List<NodeTemplate> list = query.filterBean(template).list();
if(list.size()>0){
return list.get(0).getBusinessFormId();
}else
return "";
}
@Override
public void deleteByBusinessFormId(String businessFormId) {
String statement = NodeTemplateDao.class.getName()+".deleteByBusinessFormId";
Map<String,String> map = new HashMap<String,String>();
map.put("businessFormId", businessFormId);
this.getSqlSession().delete(statement,map);
}
}
|
package com.haibo.mapper;
import com.haibo.pojo.Score;
import org.apache.ibatis.annotations.Param;
/**
* Created with IDEA.
* User:haibo.
* DATE:2018/4/25/025
*/
public interface ScoreMapper {
//用户成绩查询根据idcard查询
public String queryChengji(
@Param("s_useridcard") String s_useridcard);
// @Param("s_score") String s_score);
}
|
/*
* Copyright (C) 2021-2023 Hedera Hashgraph, 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.hedera.mirror.monitor.properties;
import com.google.common.collect.Lists;
import jakarta.inject.Named;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import lombok.extern.log4j.Log4j2;
@Log4j2
@Named
public class ScenarioPropertiesAggregatorImpl implements ScenarioPropertiesAggregator {
private static final Pattern LIST_PATTERN_END = Pattern.compile("(\\w+)\\.\\d+");
@Override
@SuppressWarnings("unchecked")
public Map<String, Object> aggregateProperties(Map<String, String> properties) {
// List properties are loaded in as property.0, property.1, etc. This puts them into a list for
// deserialization.
Map<String, Object> correctedProperties = new HashMap<>();
for (Map.Entry<String, String> entry : properties.entrySet()) {
Matcher matcher = LIST_PATTERN_END.matcher(entry.getKey());
if (matcher.matches()) {
String propertyName = matcher.group(1);
log.debug("Converting property {} into list {}", entry.getKey(), propertyName);
correctedProperties.merge(propertyName, Lists.newArrayList(entry.getValue()), (e, n) -> {
if (e instanceof List<?> existingList && n instanceof Collection<?> newList) {
((List<Object>) existingList).addAll(newList);
} else {
log.warn("Unable to merge {} to {}", n, e);
}
return e;
});
} else {
correctedProperties.put(entry.getKey(), entry.getValue());
}
}
return correctedProperties;
}
}
|
package Manufacturing.Ingredient;
import Presentation.Protocol.IOManager;
/**
* 基础原料,指只有一种内含物的原料
* <b>作为 Composite模式 的一部分</b>
*
* @author 卓正一
*/
public abstract class BaseIngredient implements Ingredient {
@Override
public String showContents() {
return IOManager.getInstance().selectStringForCurrentLanguage(
zhCnDescription(),
zhTwDescription(),
enDescription()
);
}
@Override
public String showContentsWithWeight() {
String weightString = String.format("%.2f", weight);
return IOManager.getInstance().selectStringForCurrentLanguage(
zhCnDescription() + "{质量 = " + weightString + '}',
zhTwDescription() + "{質量 = " + weightString + '}',
enDescription() + "{weight = " + weightString + '}'
);
}
/**
* 设置多语言名字
*
* @author 卓正一
* @since 2021-10-12 4:17 PM
*/
public void setName(String zhCnName, String zhTwName, String enName) {
this.zhCnName = zhCnName;
this.zhTwName = zhTwName;
this.enName = enName;
}
/**
* 以下三属性是为了多语言输出准备的。
*
* @since 2021-10-11 11:02 PM
*/
private String zhCnName;
private String zhTwName;
private String enName;
@Override
public String zhCnDescription() {
return zhCnName;
}
@Override
public String zhTwDescription() {
return zhTwName;
}
@Override
public String enDescription() {
return enName;
}
protected double cost;
protected double weight;
@Override
public void setCost(double cost) {
this.cost = cost;
}
@Override
public void setWeight(double weight) {
this.weight = weight;
}
@Override
public double getCost() {
return cost;
}
@Override
public double getWeight() {
return weight;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.