text stringlengths 10 2.72M |
|---|
package com.predix.feedback.service.impl;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import org.springframework.stereotype.Service;
import com.predix.feedback.dto.FeedbackRequestDto;
import com.predix.feedback.dto.FeedbackResponseDto;
import com.predix.feedback.service.IFeedbackService;
@Service
public class FeedbackService implements IFeedbackService{
@Override
public FeedbackResponseDto addFeedback(FeedbackRequestDto userFeedback) {
FeedbackResponseDto feedback = new FeedbackResponseDto();
// Make set of bad words
Set<String> badWords = new HashSet<>(Arrays.asList("bloody,hell,chinky,cocaine,dipshit,gays".split(",")));
String comment = userFeedback.getFeedback();
boolean isBadWord=false;
for(String word : comment.split(" ")) {
if(badWords.contains(word)) {
isBadWord=true;
break;
}
}
if(isBadWord) {
feedback.setFeedbackResponse("Feedback consists of explict langauge please Review");
}else {
feedback.setFeedbackResponse("Feedback Successfully submitted");
}
return feedback;
}
}
|
/**
* EasyFXML has full support for the module path!
*/
open module easyfxml.sample.helloworld {
requires easyfxml;
requires spring.boot.autoconfigure;
requires spring.context;
}
|
package remotecommand;
public class GarageDoorCommand implements Command {
private final GarageDoor door;
public GarageDoorCommand(GarageDoor d) {
door = d;
}
@Override
public void execute() {
door.open();
}
}
|
/**
*
*/
package com.fixit.core.data;
import com.fixit.core.data.mongo.MapArea;
/**
* @author Kostyantin
* @createdAt 2017/04/30 14:49:49 GMT+3
*/
public class MapAreaRepresentation {
public final String id;
public final String name;
public final ImmutableLatLng[][] polygons;
public MapAreaRepresentation(MapArea mapArea) {
this.id = mapArea.get_id().toHexString();
this.name = mapArea.getName();
double[][][] coords = mapArea.getGeometry().getCoordinates();
this.polygons = new ImmutableLatLng[coords.length][];
for(int polygonIndex = 0; polygonIndex < coords.length; polygonIndex++) {
double[][] polygonCoords = coords[polygonIndex];
this.polygons[polygonIndex] = new ImmutableLatLng[polygonCoords.length];
for(int coordsIndex = 0; coordsIndex < polygonCoords.length; coordsIndex++) {
this.polygons[polygonIndex][coordsIndex] = new ImmutableLatLng(polygonCoords[coordsIndex][1], polygonCoords[coordsIndex][0]);
}
}
}
}
|
package Farming;
@Product_Type
public class TomatSeedling extends Seedling{
public TomatSeedling(String name, Unit unit, double count, int price, int ripeness, double plods_weight) {
super(name, unit, count, price, ripeness, plods_weight);
}
}
|
/***************************************************************
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
****************************************************************/
package org.apache.flume.source;
import java.util.List;
import java.util.Map;
import org.apache.flume.conf.Configurable;
/**
* <PRE>
* 1. ClassName :
* 2. FileName : DirectoyTailModulable.java
* 3. Package : kr.co.cplanet.logcollector.flumeng.source
* 4. Comment :
* 5. @author : Jinoos Lee <jinoos@gmail.com>
* 6. 작성일 : 2013. 10. 25. 오전 12:51:16
* </PRE>
*/
public interface DirectoryTailParserModulable extends Configurable {
public void flush();
public void parse(String line, FileSet header);
public boolean isFirstLine(String line);
public boolean isLastLine(String line);
}
|
package gui;
import javax.swing.WindowConstants;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
import javax.swing.SwingUtilities;
import DTOs.InformeInsumoDTO;
import DTOs.ItemInformeInsumoDTO;
import DTOs.MateriaPrimaDTO;
import DTOs.StockMateriaPrimaDTO;
import cliente.Cliente;
import com.cloudgarden.layout.AnchorConstraint;
import com.cloudgarden.layout.AnchorLayout;
import java.awt.ItemSelectable;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import javax.swing.BorderFactory;
import javax.swing.ComboBoxModel;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
/**
* This code was edited or generated using CloudGarden's Jigloo
* SWT/Swing GUI Builder, which is free for non-commercial
* use. If Jigloo is being used commercially (ie, by a corporation,
* company or business for any purpose whatever) then you
* should purchase a license for each developer using Jigloo.
* Please visit www.cloudgarden.com for details.
* Use of Jigloo implies acceptance of these licensing terms.
* A COMMERCIAL LICENSE HAS NOT BEEN PURCHASED FOR
* THIS MACHINE, SO JIGLOO OR THIS CODE CANNOT BE USED
* LEGALLY FOR ANY CORPORATE OR COMMERCIAL PURPOSE.
*/
public class MostrarInformeInsumo extends javax.swing.JFrame {
{
//Set Look & Feel
try {
javax.swing.UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsClassicLookAndFeel");
} catch(Exception e) {
e.printStackTrace();
}
}
private JLabel lblSector;
private JPanel pnlDatos;
private JButton btnFinalizar;
private JScrollPane jScrollPane1;
private JTable tblInforme;
private JPanel pnlInforme;
private JButton btnBuscarInformes;
private JLabel lblBarra2;
private JLabel lblbarra;
private JTextField txtAnio;
private JTextField txtMes;
private JTextField txtDia;
private JLabel txtFecha;
private JComboBox cmbSectores;
public MostrarInformeInsumo(Cliente cliente) {
super();
initGUI(cliente);
}
private void initGUI(final Cliente cliente) {
try {
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
getContentPane().setLayout(null);
setTitle("Mostrar Informe Insumo");
{
btnFinalizar = new JButton();
getContentPane().add(btnFinalizar, new AnchorConstraint(917, 973, 974, 843, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL));
btnFinalizar.setText("Finalizar");
btnFinalizar.setBounds(403, 399, 111, 23);
btnFinalizar.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
dispose();
}
});
}
{
pnlInforme = new JPanel();
getContentPane().add(pnlInforme, new AnchorConstraint(256, 602, 930, 13, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL));
pnlInforme.setPreferredSize(new java.awt.Dimension(503, 275));
pnlInforme.setBorder(BorderFactory.createTitledBorder("Informe Insumo"));
pnlInforme.setBounds(11, 104, 503, 275);
{
jScrollPane1 = new JScrollPane();
pnlInforme.add(jScrollPane1);
jScrollPane1.setPreferredSize(new java.awt.Dimension(466, 238));
{
TableModel tblInformeModel =
new DefaultTableModel(
new String[][] { { "One", "Two" }, { "Three", "Four" } },
new String[] { "Sector", " Materia Prima", "Cantidad", "Recibida", "Dias Margen" });
tblInforme = new JTable();
jScrollPane1.setViewportView(tblInforme);
tblInforme.setModel(tblInformeModel);
tblInforme.setPreferredSize(new java.awt.Dimension(466, 238));
}
}
}
{
pnlDatos = new JPanel();
getContentPane().add(pnlDatos, new AnchorConstraint(33, 602, 204, 14, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL));
pnlDatos.setPreferredSize(new java.awt.Dimension(502, 70));
pnlDatos.setBorder(BorderFactory.createTitledBorder("Datos de busqueda"));
pnlDatos.setBounds(11, 13, 503, 70);
{
lblSector = new JLabel();
pnlDatos.add(lblSector);
lblSector.setText("Sector:");
}
{
ComboBoxModel cmbSectoresModel =
new DefaultComboBoxModel(
new String[] { "barra", "cafeteria", "cocina", "central" });
cmbSectores = new JComboBox();
pnlDatos.add(cmbSectores);
cmbSectores.setModel(cmbSectoresModel);
cmbSectores.setPreferredSize(new java.awt.Dimension(131, 21));
}
{
txtFecha = new JLabel();
pnlDatos.add(txtFecha);
txtFecha.setText("Fecha:");
txtFecha.setPreferredSize(new java.awt.Dimension(33, 14));
}
{
txtDia = new JTextField();
pnlDatos.add(txtDia);
txtDia.setText("dd");
txtDia.setPreferredSize(new java.awt.Dimension(27, 20));
}
{
lblbarra = new JLabel();
pnlDatos.add(lblbarra);
lblbarra.setText("/");
lblbarra.setPreferredSize(new java.awt.Dimension(9, 14));
}
{
txtMes = new JTextField();
pnlDatos.add(txtMes);
txtMes.setText("mm");
txtMes.setPreferredSize(new java.awt.Dimension(26, 20));
}
{
lblBarra2 = new JLabel();
pnlDatos.add(lblBarra2);
lblBarra2.setText("/");
lblBarra2.setPreferredSize(new java.awt.Dimension(9, 14));
}
{
txtAnio = new JTextField();
pnlDatos.add(txtAnio);
txtAnio.setText("yyyy");
txtAnio.setPreferredSize(new java.awt.Dimension(51, 20));
}
{
btnBuscarInformes = new JButton();
pnlDatos.add(btnBuscarInformes);
btnBuscarInformes.setText("Buscar Informe");
btnBuscarInformes.setPreferredSize(new java.awt.Dimension(116, 23));
btnBuscarInformes.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
if(cmbSectores.getSelectedItem() != null && !txtAnio.getText().equals("")
&& !txtDia.getText().equals("") && !txtMes.getText().equals("")){
Calendar c = Calendar.getInstance();
c.set(Integer.parseInt(txtAnio.getText()), Integer.parseInt(txtMes.getText())-1, Integer.parseInt(txtDia.getText()));
Date fecha = c.getTime();
String sector = (String) cmbSectores.getSelectedItem();
//Limpio la tabla y la lleno
if(!sector.equals("central")){
List<ItemInformeInsumoDTO> items = cliente.mostrarItemsInformeInsumo(sector, fecha);
DefaultTableModel modelo = (DefaultTableModel) tblInforme.getModel();
int filas=modelo.getRowCount();
for (int i = 0;filas>i; i++) {
modelo.removeRow(0);
}
for(ItemInformeInsumoDTO dto : items){
String[] filaNueva = new String[] {dto.getSector(),dto.getMateriaprima().getNombre(),
String.valueOf(dto.getCantidad()), String.valueOf(dto.getCantidadRecibida()), String.valueOf(dto.getDiferencia())};
modelo.addRow(filaNueva);
}
}else{
InformeInsumoDTO informe = cliente.mostrarInformeInsumo(sector, fecha);
DefaultTableModel modelo = (DefaultTableModel) tblInforme.getModel();
int filas=modelo.getRowCount();
for (int i = 0;filas>i; i++) {
modelo.removeRow(0);
}
for(ItemInformeInsumoDTO dto : informe.getItems()){
String[] filaNueva = new String[] {dto.getSector(),dto.getMateriaprima().getNombre(),
String.valueOf(dto.getCantidad()), String.valueOf(dto.getCantidadRecibida()), String.valueOf(dto.getDiferencia())};
modelo.addRow(filaNueva);
}
}
}
}
});
}
}
pack();
this.setSize(570, 467);
} catch (Exception e) {
//add your error handling code here
e.printStackTrace();
}
}
}
|
package com.juancrud.miscontactos.adapter;
import android.app.Activity;
import android.content.Intent;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.juancrud.miscontactos.db.ConstructorContactos;
import com.juancrud.miscontactos.pojo.Contacto;
import com.juancrud.miscontactos.DetalleContacto;
import com.juancrud.miscontactos.R;
import com.squareup.picasso.Picasso;
import java.lang.reflect.Constructor;
import java.util.ArrayList;
public class ContactoAdaptador extends RecyclerView.Adapter<ContactoAdaptador.ContactoViewHolder> {
private ArrayList<Contacto> contactos;
private Activity activity;
public ContactoAdaptador(ArrayList<Contacto> contactos, Activity activity){
this.contactos = contactos;
this.activity = activity;
}
//Inflar el layout y lo pasa al viewholder para que obtenga los views
@Override
public ContactoViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.cardview_grid_contacto, parent, false);
return new ContactoViewHolder(view);
}
//asocia cada elemento de la lista con cada view
@Override
public void onBindViewHolder(final ContactoViewHolder holder, int position) {
final Contacto contacto = contactos.get(position);
Picasso.with(activity).load(contacto.getUrlFoto()).placeholder(R.drawable.mario).into(holder.imgFotoCV);
//holder.imgFotoCV.setImageResource(contacto.getUrlFoto());
holder.tvLikes.setText(contacto.getLikes() + "");
holder.imgFotoCV.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(activity, DetalleContacto.class);
intent.putExtra(activity.getString(R.string.pContacto), contacto);
activity.startActivity(intent);
}
});
}
@Override
public int getItemCount() {
return contactos.size();
}
public static class ContactoViewHolder extends RecyclerView.ViewHolder {
private ImageView imgFotoCV;
private TextView tvLikes;
public ContactoViewHolder(View itemView) {
super(itemView);
imgFotoCV = (ImageView)itemView.findViewById(R.id.imgFotoCV);
tvLikes = (TextView)itemView.findViewById(R.id.tvLikes);
}
}
}
|
package com.example.joker.newsapp;
/**
* Created by joker on 24/1/18.
*/
public interface ClickListener {
public void DrawerClickListerner(String a);
}
|
package dev.liambloom.softwareEngineering.chapter5;
import java.util.Random;
public class Rand { // Cannot name this "Random" becuase it uses Random
public static final Random r = new Random();
public static int nextInt () {
return r.nextInt();
}
public static int nextInt (int max) {
return r.nextInt(max + 1);
}
public static int nextInt (int min, int max) { // min and max are inclusive
return r.nextInt((max - min) + 1) + min;
}
public static boolean nextBoolean () {
return r.nextBoolean();
}
public static char nextChar () {
return (char) nextInt(127);
}
public static char nextChar (char min, char max) {
return (char) nextInt((int) min, (int) max);
}
public static char nextLetter () {
return nextChar('A', 'z');
}
public static char nextUpperCase () {
return nextChar('A', 'Z');
}
public static char nextLowerCase () {
return nextChar('a', 'z');
}
public static String nextString (int length, char min, char max) {
String str = "";
for (int i = 0; i < length; i++) {
str += nextChar(min, max);
}
return str;
}
public static String nextWord (int length, boolean mixCases) {
return nextString(length, mixCases ? 'A' : 'a', 'z');
}
public static String nextWord (int length) {
return nextWord(length, false);
}
} |
/*
* This is based off of DefaultSwatchChooserPanel.java by Sun Microsystems.
*
* An alpha slider and spinner have been added.
*/
package colordialog;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.Icon;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSlider;
import javax.swing.JSpinner;
import javax.swing.SpinnerNumberModel;
import javax.swing.UIManager;
import javax.swing.border.Border;
import javax.swing.border.CompoundBorder;
import javax.swing.border.EmptyBorder;
import javax.swing.border.LineBorder;
import javax.swing.colorchooser.AbstractColorChooserPanel;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
/**
* Class <code>SwatchChooserPanel</code> is based off of the DefaultSwatchChooserPanel with
* an added slider and spinner for Alpha values (optional).
*
* @author "Austin Shoemaker" <austin@genome.arizona.edu>
* @see AbstractColorChooserPanel
* @see ChangeListener
* @see MouseListener
*/
@SuppressWarnings("serial") // Prevent compiler warning for missing serialVersionUID
public class SwatchChooserPanel extends AbstractColorChooserPanel implements ChangeListener, MouseListener {
private MainSwatchPanel swatchPanel;
private RecentSwatchPanel recentSwatchPanel;
private JSlider alphaSlider;
private JSpinner alphaSpinner;
private boolean isLocked; // for stopping an endless loop of changing the slider and updating the colors
private boolean doAlpha; // not allowing alpha changes
/**
* Creates a new <code>SwatchChooserPanel</code> instance in
* which alpha is enabled.
*
*/
public SwatchChooserPanel() {
this(true);
}
/**
* Creates a new <code>SwatchChooserPanel</code> instance.
*
* @param alphaEnabled a <code>boolean</code> value of true to allow for changing the alpha value
*/
public SwatchChooserPanel(boolean alphaEnabled) {
super();
doAlpha = alphaEnabled;
isLocked = false;
}
/**
* Method <code>getDisplayName</code> returns "Swatches"
*
* @return a <code>String</code> value
*/
public String getDisplayName() {
return "Swatches";
}
/**
* Method <code>getSmallDisplayIcon</code> returns null
*
* @return an <code>Icon</code> value of null
*/
public Icon getSmallDisplayIcon() {
return null;
}
/**
* Method <code>getLargeDisplayIcon</code> returns null
*
* @return an <code>Icon</code> value of null
*/
public Icon getLargeDisplayIcon() {
return null;
}
/**
* Method <code>buildChooser</code> sets up the view and the listeners
*
*/
protected void buildChooser() {
int alpha = getColorFromModel().getAlpha();
alphaSlider = new JSlider(JSlider.HORIZONTAL,0,255,alpha);
alphaSlider.setMajorTickSpacing(85);
alphaSlider.setMinorTickSpacing(17);
alphaSlider.setPaintTicks(true);
alphaSlider.setPaintLabels(true);
alphaSlider.addChangeListener(this);
alphaSpinner = new JSpinner(new SpinnerNumberModel(alpha,0,255,1));
alphaSpinner.addChangeListener(this);
JPanel alphaRow = new JPanel();
alphaRow.add(new JLabel("Alpha"));
alphaRow.add(alphaSlider);
alphaRow.add(alphaSpinner);
swatchPanel = new MainSwatchPanel(alpha);
recentSwatchPanel = new RecentSwatchPanel();
swatchPanel.addMouseListener(this);
recentSwatchPanel.addMouseListener(this);
JPanel superHolder = new JPanel(new BorderLayout());
JPanel mainHolder = new JPanel(new BorderLayout());
Border border = new CompoundBorder(new LineBorder(Color.black),new LineBorder(Color.white));
mainHolder.setBorder(border);
mainHolder.add(swatchPanel,BorderLayout.CENTER);
superHolder.add(mainHolder,BorderLayout.CENTER);
JPanel recentHolder = new JPanel(new BorderLayout());
recentHolder.setBorder(border);
recentHolder.add(recentSwatchPanel, BorderLayout.CENTER);
JPanel recentLabelHolder = new JPanel(new BorderLayout());
recentLabelHolder.add(recentHolder, BorderLayout.CENTER);
recentLabelHolder.add(new JLabel("Recent:"), BorderLayout.NORTH);
JPanel recentHolderHolder = new JPanel(new BorderLayout());
if (this.getComponentOrientation().isLeftToRight()) {
recentHolderHolder.setBorder(new EmptyBorder(2,10,2,2));
}
else {
recentHolderHolder.setBorder(new EmptyBorder(2,2,2,10));
}
recentHolderHolder.add(recentLabelHolder,BorderLayout.CENTER);
superHolder.add(recentHolderHolder,BorderLayout.AFTER_LINE_ENDS);
if (doAlpha) superHolder.add(alphaRow,BorderLayout.SOUTH);
add(superHolder);
}
/**
* Method <code>stateChanged</code> handles the changing of the alpha slider and alpha spinner.
*
* @param e a <code>ChangeEvent</code> value
*/
public void stateChanged(ChangeEvent e) {
if (!isLocked && e.getSource() == alphaSlider || e.getSource() == alphaSpinner) {
Color c = getColorFromModel();
int alpha;
if (e.getSource() == alphaSlider) {
alpha = alphaSlider.getValue();
}
else { // e.getSource() == alphaSpinner
alpha = ((Integer)alphaSpinner.getValue()).intValue();
}
swatchPanel.changeAlpha(alpha);
swatchPanel.repaint();
getColorSelectionModel().setSelectedColor(new Color(c.getRed(),c.getGreen(),c.getBlue(),alpha));
}
}
/**
* Method <code>updateChooser</code> updates the alpha slider and alpha spinner
* to the current color from the color model.
*
*/
public void updateChooser() {
if (!isLocked) {
isLocked = true;
int alpha = getColorFromModel().getAlpha();
alphaSlider.setValue(alpha);
alphaSpinner.setValue(new Integer(alpha));
isLocked = false;
}
}
/**
* Method <code>mousePressed</code> handles the mouse clicking on
* spots in the main color grid and the recent color grid.
*
* @param e a <code>MouseEvent</code> value
*/
public void mousePressed(MouseEvent e) {
if (e.getSource() == recentSwatchPanel) {
Color color = recentSwatchPanel.getColorForLocation(e.getX(), e.getY());
getColorSelectionModel().setSelectedColor(color);
}
else if (e.getSource() == swatchPanel) {
Color color = swatchPanel.getColorForLocation(e.getX(), e.getY());
getColorSelectionModel().setSelectedColor(color);
recentSwatchPanel.setMostRecentColor(color);
}
}
/**
* Method <code>mouseClicked</code> does nothing
*
* @param e a <code>MouseEvent</code> value
*/
public void mouseClicked(MouseEvent e) { }
/**
* Method <code>mouseEntered</code> does nothing
*
* @param e a <code>MouseEvent</code> value
*/
public void mouseEntered(MouseEvent e) { }
/**
* Method <code>mouseExited</code> does nothing
*
* @param e a <code>MouseEvent</code> value
*/
public void mouseExited(MouseEvent e) { }
/**
* Method <code>mouseReleased</code> does nothing
*
* @param e a <code>MouseEvent</code> value
*/
public void mouseReleased(MouseEvent e) { }
}
@SuppressWarnings("serial") // Prevent compiler warning for missing serialVersionUID
abstract class SwatchPanel extends JPanel {
protected Color[] colors;
protected Dimension swatchSize, numSwatches, gap;
public SwatchPanel() {
initValues();
initColors();
setToolTipText(""); // register for events
setOpaque(true);
setBackground(Color.white);
setRequestFocusEnabled(false);
}
protected abstract void initValues();
protected abstract void initColors();
public boolean isFocusTraversable() {
return false;
}
public void paintComponent(Graphics g) {
g.setColor(getBackground());
g.fillRect(0,0,getWidth(), getHeight());
for (int row = 0; row < numSwatches.height; row++) {
for (int column = 0; column < numSwatches.width; column++) {
g.setColor( getColorForCell(column, row) );
int x;
if ((!this.getComponentOrientation().isLeftToRight()) &&
(this instanceof RecentSwatchPanel)) {
x = (numSwatches.width - column - 1) * (swatchSize.width + gap.width);
}
else {
x = column * (swatchSize.width + gap.width);
}
int y = row * (swatchSize.height + gap.height);
g.fillRect(x, y, swatchSize.width, swatchSize.height);
g.setColor(Color.black);
g.drawLine(x+swatchSize.width-1, y, x+swatchSize.width-1, y+swatchSize.height-1);
g.drawLine(x, y+swatchSize.height-1, x+swatchSize.width-1, y+swatchSize.height-1);
}
}
}
public Dimension getPreferredSize() {
int x = numSwatches.width * (swatchSize.width + gap.width) - 1;
int y = numSwatches.height * (swatchSize.height + gap.height) - 1;
return new Dimension(x,y);
}
public String getToolTipText(MouseEvent e) {
Color color = getColorForLocation(e.getX(), e.getY());
return color.getRed()+", "+ color.getGreen() + ", " + color.getBlue();
}
public Color getColorForLocation(int x, int y) {
int column;
if ((!this.getComponentOrientation().isLeftToRight()) &&
(this instanceof RecentSwatchPanel)) {
column = numSwatches.width - x / (swatchSize.width + gap.width) - 1;
} else {
column = x / (swatchSize.width + gap.width);
}
int row = y / (swatchSize.height + gap.height);
return getColorForCell(column, row);
}
private Color getColorForCell( int column, int row) {
return colors[ (row * numSwatches.width) + column ];
}
}
class RecentSwatchPanel extends SwatchPanel {
protected void initValues() {
swatchSize = UIManager.getDimension("ColorChooser.swatchesRecentSwatchSize");
numSwatches = new Dimension(5,7);
gap = new Dimension(1,1);
}
protected void initColors() {
Color defaultRecentColor = UIManager.getColor("ColorChooser.swatchesDefaultRecentColor");
int numColors = numSwatches.width * numSwatches.height;
colors = new Color[numColors];
for (int i = 0; i < numColors ; i++) {
colors[i] = defaultRecentColor;
}
}
public void setMostRecentColor(Color c) {
System.arraycopy(colors, 0, colors, 1, colors.length-1);
colors[0] = c;
repaint();
}
}
class MainSwatchPanel extends SwatchPanel {
public MainSwatchPanel(int alpha) {
super();
changeAlpha(alpha);
}
public void changeAlpha(int alpha) {
Color old;
for (int i = 0; i < colors.length; i++) {
old = colors[i];
if (old != null)
colors[i] = new Color(old.getRed(),old.getGreen(),old.getBlue(),alpha);
}
}
protected void initValues() {
swatchSize = UIManager.getDimension("ColorChooser.swatchesSwatchSize");
numSwatches = new Dimension(31,9);
gap = new Dimension(1,1);
}
protected void initColors() {
int numColors = rawValues.length / 3;
colors = new Color[numColors];
for (int i = 0; i < numColors ; i++) {
colors[i] = new Color(rawValues[(i*3)], rawValues[(i*3)+1], rawValues[(i*3)+2]);
}
}
private static int[] rawValues = {
255, 255, 255, // first row.
204, 255, 255,
204, 204, 255,
204, 204, 255,
204, 204, 255,
204, 204, 255,
204, 204, 255,
204, 204, 255,
204, 204, 255,
204, 204, 255,
204, 204, 255,
255, 204, 255,
255, 204, 204,
255, 204, 204,
255, 204, 204,
255, 204, 204,
255, 204, 204,
255, 204, 204,
255, 204, 204,
255, 204, 204,
255, 204, 204,
255, 255, 204,
204, 255, 204,
204, 255, 204,
204, 255, 204,
204, 255, 204,
204, 255, 204,
204, 255, 204,
204, 255, 204,
204, 255, 204,
204, 255, 204,
204, 204, 204, // second row.
153, 255, 255,
153, 204, 255,
153, 153, 255,
153, 153, 255,
153, 153, 255,
153, 153, 255,
153, 153, 255,
153, 153, 255,
153, 153, 255,
204, 153, 255,
255, 153, 255,
255, 153, 204,
255, 153, 153,
255, 153, 153,
255, 153, 153,
255, 153, 153,
255, 153, 153,
255, 153, 153,
255, 153, 153,
255, 204, 153,
255, 255, 153,
204, 255, 153,
153, 255, 153,
153, 255, 153,
153, 255, 153,
153, 255, 153,
153, 255, 153,
153, 255, 153,
153, 255, 153,
153, 255, 204,
204, 204, 204, // third row
102, 255, 255,
102, 204, 255,
102, 153, 255,
102, 102, 255,
102, 102, 255,
102, 102, 255,
102, 102, 255,
102, 102, 255,
153, 102, 255,
204, 102, 255,
255, 102, 255,
255, 102, 204,
255, 102, 153,
255, 102, 102,
255, 102, 102,
255, 102, 102,
255, 102, 102,
255, 102, 102,
255, 153, 102,
255, 204, 102,
255, 255, 102,
204, 255, 102,
153, 255, 102,
102, 255, 102,
102, 255, 102,
102, 255, 102,
102, 255, 102,
102, 255, 102,
102, 255, 153,
102, 255, 204,
153, 153, 153, // fourth row
51, 255, 255,
51, 204, 255,
51, 153, 255,
51, 102, 255,
51, 51, 255,
51, 51, 255,
51, 51, 255,
102, 51, 255,
153, 51, 255,
204, 51, 255,
255, 51, 255,
255, 51, 204,
255, 51, 153,
255, 51, 102,
255, 51, 51,
255, 51, 51,
255, 51, 51,
255, 102, 51,
255, 153, 51,
255, 204, 51,
255, 255, 51,
204, 255, 51,
153, 244, 51,
102, 255, 51,
51, 255, 51,
51, 255, 51,
51, 255, 51,
51, 255, 102,
51, 255, 153,
51, 255, 204,
153, 153, 153, // Fifth row
0, 255, 255,
0, 204, 255,
0, 153, 255,
0, 102, 255,
0, 51, 255,
0, 0, 255,
51, 0, 255,
102, 0, 255,
153, 0, 255,
204, 0, 255,
255, 0, 255,
255, 0, 204,
255, 0, 153,
255, 0, 102,
255, 0, 51,
255, 0 , 0,
255, 51, 0,
255, 102, 0,
255, 153, 0,
255, 204, 0,
255, 255, 0,
204, 255, 0,
153, 255, 0,
102, 255, 0,
51, 255, 0,
0, 255, 0,
0, 255, 51,
0, 255, 102,
0, 255, 153,
0, 255, 204,
102, 102, 102, // sixth row
0, 204, 204,
0, 204, 204,
0, 153, 204,
0, 102, 204,
0, 51, 204,
0, 0, 204,
51, 0, 204,
102, 0, 204,
153, 0, 204,
204, 0, 204,
204, 0, 204,
204, 0, 204,
204, 0, 153,
204, 0, 102,
204, 0, 51,
204, 0, 0,
204, 51, 0,
204, 102, 0,
204, 153, 0,
204, 204, 0,
204, 204, 0,
204, 204, 0,
153, 204, 0,
102, 204, 0,
51, 204, 0,
0, 204, 0,
0, 204, 51,
0, 204, 102,
0, 204, 153,
0, 204, 204,
102, 102, 102, // seventh row
0, 153, 153,
0, 153, 153,
0, 153, 153,
0, 102, 153,
0, 51, 153,
0, 0, 153,
51, 0, 153,
102, 0, 153,
153, 0, 153,
153, 0, 153,
153, 0, 153,
153, 0, 153,
153, 0, 153,
153, 0, 102,
153, 0, 51,
153, 0, 0,
153, 51, 0,
153, 102, 0,
153, 153, 0,
153, 153, 0,
153, 153, 0,
153, 153, 0,
153, 153, 0,
102, 153, 0,
51, 153, 0,
0, 153, 0,
0, 153, 51,
0, 153, 102,
0, 153, 153,
0, 153, 153,
51, 51, 51, // eigth row
0, 102, 102,
0, 102, 102,
0, 102, 102,
0, 102, 102,
0, 51, 102,
0, 0, 102,
51, 0, 102,
102, 0, 102,
102, 0, 102,
102, 0, 102,
102, 0, 102,
102, 0, 102,
102, 0, 102,
102, 0, 102,
102, 0, 51,
102, 0, 0,
102, 51, 0,
102, 102, 0,
102, 102, 0,
102, 102, 0,
102, 102, 0,
102, 102, 0,
102, 102, 0,
102, 102, 0,
51, 102, 0,
0, 102, 0,
0, 102, 51,
0, 102, 102,
0, 102, 102,
0, 102, 102,
0, 0, 0, // ninth row
0, 51, 51,
0, 51, 51,
0, 51, 51,
0, 51, 51,
0, 51, 51,
0, 0, 51,
51, 0, 51,
51, 0, 51,
51, 0, 51,
51, 0, 51,
51, 0, 51,
51, 0, 51,
51, 0, 51,
51, 0, 51,
51, 0, 51,
51, 0, 0,
51, 51, 0,
51, 51, 0,
51, 51, 0,
51, 51, 0,
51, 51, 0,
51, 51, 0,
51, 51, 0,
51, 51, 0,
0, 51, 0,
0, 51, 51,
0, 51, 51,
0, 51, 51,
0, 51, 51,
51, 51, 51 };
}
|
package com.busekylin.springbootcluster.domain;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
@Data
@AllArgsConstructor
@NoArgsConstructor
@ToString
public class Person {
private String name;
private Integer age;
private String address;
} |
package Assignment1;
public class Ques6b {
public static void main(String[] args) {
int arr[] = {1,3,5,7,9};
System.out.println("Count of odd numbers is: " + countOdd(arr, 0));
}
public static int countOdd(int arr[], int pos) {
//Base Case
if (pos == arr.length)
return 0;
//Recursive Call
else {
if(arr[pos] % 2 != 0)
return 1 + countOdd(arr, pos+1);
else
return countOdd(arr, pos+1);
}
}
} |
package de.hdm.softwarepraktikum.client.gui;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.google.gwt.cell.client.AbstractCell;
import com.google.gwt.safehtml.shared.SafeHtmlBuilder;
import com.google.gwt.user.cellview.client.CellTree;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.view.client.ListDataProvider;
import com.google.gwt.view.client.ProvidesKey;
import com.google.gwt.view.client.SelectionChangeEvent;
import com.google.gwt.view.client.SingleSelectionModel;
import com.google.gwt.view.client.TreeViewModel;
import de.hdm.softwarepraktikum.client.ClientsideSettings;
import de.hdm.softwarepraktikum.client.Project_19.CurrentPerson;
import de.hdm.softwarepraktikum.shared.ShoppingListAdministrationAsync;
import de.hdm.softwarepraktikum.shared.bo.Group;
import de.hdm.softwarepraktikum.shared.bo.Person;
import de.hdm.softwarepraktikum.shared.bo.ShoppingList;
/**
* Die Klasse <code>CustomTreeModel</code> ist eine Erweiterung der Klasse <code>TreeViewModel</code>.
* Hierbei bietet das CustomTreeModel die Grundlage für die Navigation des im <code>NavigatorPanel</code> implementierten <code>CellTree</code>.
*
* @author Jan Duwe, Vincent Wengert
*
*/
public class CustomTreeModel implements TreeViewModel {
private ShoppingListAdministrationAsync administration = ClientsideSettings.getShoppinglistAdministration();;
/**
* SelectionModel, das für alle Knoten und Kindknoten im <code>CustomTreeModel</code> verwendet wird.
*
*/
private ObjectKeyProvider boKeyProvider = new ObjectKeyProvider();
private SingleSelectionModel<Object> selectionModel = new SingleSelectionModel<Object>(boKeyProvider);
private GroupForm gf;
private ShowShoppingListForm sslf;
private NewShoppingListForm nslf;
private CellTree tree = null;
private Boolean loadFavorites = false;
private ShoppingList selectedShoppingList = null;
private Group groupToDisplay = null;
private ArrayList<Group> groups = new ArrayList<Group>();
private ArrayList<ShoppingList> shoppinglists = new ArrayList<ShoppingList>();
ListDataProvider<Group> groupsDataProvider = new ListDataProvider<Group>();
/**
* Wird eine <code>Group</code> innerhalb des <code>CustomTreeModel</code> expandiert,
* so werden die darin enthaltenen <code>ShoppingList</code> hier vermerkt.
* Sie müssen bei erneutem erweitern des Baumes somit nicht erneut generiert werden.
*/
private Map<Group, ListDataProvider<ShoppingList>> shoppingListHolderDataProviders = null;
Person currentPerson = CurrentPerson.getPerson();
public CustomTreeModel() {
selectionModel.addSelectionChangeHandler(new SelectionChangeEventHandler());
shoppingListHolderDataProviders = new HashMap<Group, ListDataProvider<ShoppingList>>();
}
/**
* ************************* ABSCHNITT der Methoden *************************
*/
/**
* Methode zum Setzen des Boolean loadFavorites. Dieser Wert definiert
* ob bei einer neuen Instanz eines <code>ShoppingList</code> Objekts die
* favorisierten <code>Item</code> als <code>ListItem</code> hinzufügt.
*
* @param loadFavorites Boolean Wert um <code>Item</code> Objekte die als
* Favorit markiert wurden beim erstellen einer <code>ShoppingList</code>
* direkt zu laden.
*/
public void setLoadFavoriteItems(Boolean loadFavorites) {
this.loadFavorites = loadFavorites;
}
/**
* Methode zum Auslesen des Boolean loadFavorites. Dieser Wert definiert
* ob bei einer neuen Instanz eines <code>ShoppingList</code> Objekts die
* favorisierten <code>Item</code> als <code>ListItem</code> hinzufügt.
*
* @return Boolean Wert um <code>Item</code> Objekte die als
* Favorit markiert wurden beim erstellen einer <code>ShoppingList</code>.
* direkt zu laden.
*/
private Boolean getLoadFavoriteItems() {
return this.loadFavorites;
}
/**
* Methode zum Auslesen aller <code>Group</code> der <code>Person</code> innerhalb des <code>CustomTreeModel</code>.
*
* @return Alle <code>Group</code> des <code>Person</code>.
*/
public ArrayList<Group> getPersonGroups() {
return groups;
}
/**
* Methode zum Auslesen aller <code>ShoppingList</code> der <code>Group</code> innerhalb des <code>CustomTreeModel</code>.
*
* @return Alle <code>ShoppingList</code> der <code>Group</code>.
*/
public ArrayList<ShoppingList> getShoppingListsInGroups() {
return shoppinglists;
}
/**
* Methode zum Auslesen des SingleSelectionModel innerhalb des <code>CustomTreeModel</code>.
*
* @return
*/
public SingleSelectionModel<Object> getSelectionModel(){
return this.selectionModel;
}
/**
* Methode zum Setzen der <code>GroupForm</code> innerhalb des <code>CustomTreeModel</code>.
*
* @param groupForm die zu setzende <code>GroupForm</code>
*/
public void setGroupForm(GroupForm groupForm) {
this.gf = groupForm;
}
/**
* Methode zum Setzen der <code>ShowShoppingListForm</code> um die im <code>CellTree</code> ausgewählte
* <code>ShoppingList</code> darzustellen.
*
* @param sslf die <code>ShowShoppingListForm</code> um <code>ShoppingList</code> Objekt anzuzeigen.
*/
public void setShoppingListForm(ShowShoppingListForm sslf) {
this.sslf = sslf;
}
/**
* Methode zum Setzen der <code>NewShoppingListForm</code> innerhalb des <code>CustomTreeModel</code>.
*
* @param nslf die zu setzende <code>NewShoppingListForm</code>.
*/
public void setNewShoppingListForm(NewShoppingListForm nslf) {
this.nslf = nslf;
}
/**
* Methode zum Darstellen des im <code>CellTree</code> ausgewählten <code>Group</code> Objekts.
*
* @param g das darzustellende <code>Group</code> Objekts.
*/
public void setSelectedGroup(Group g) {
groupToDisplay = g;
gf.setEditable(false);
gf.setInitial(false);
RootPanel.get("Details").clear();
gf.setSelected(g);
RootPanel.get("Details").add(gf);
}
/**
* Methode zum Darstellen des im <code>CellTree</code> ausgewählten <code>ShoppingList</code> Objekts.
*
* @param sl das darzustellende <code>ShoppingList</code> Objekts.
*/
public void setSelectedShoppingList(ShoppingList sl) {
RootPanel.get("Details").clear();
// selectedShoppingList = sl;
sslf.setSelected(sl, loadFavorites);
RootPanel.get("Details").add(sslf);
selectedShoppingList=null;
}
/**
* Methode zum Setzen des <code>CellTree</code> Objekts innerhalb des <code>CustomTreeModel</code>.
*
* @param tree der zu setzende <code>CellTree</code>.
*/
public void setTree(CellTree tree) {
this.tree = tree;
}
/**
* Methode zum Auslesen des im <code>CellTree</code> ausgewählten <code>ShoppingList</code> Objekts.
*
* @return die ausgewählte <code>ShoppingList</code>.
*/
public ShoppingList getSelectedShoppingList() {
return selectedShoppingList;
}
/**
* Methode zum Auslesen aller <code>ShoppingList</code> Objekte eines <code>Group</code> Objekts.
* Zugriff erfolgt über innere Klasse <code>GetGroupShoppingListsCallback</code>
*
* @param g <code>Group</code> Objekt für das die ausgewählten <code>ShoppingList</code>
* Objekte geladen werden sollen.
*/
public void getGroupShoppingLists(Group g) {
administration.getAllShoppingListsByGroup(g, new GetGroupShoppingListsCallback());
}
/**
* Methode zum aktualisieren des ListDataProvider von <code>Group</code> Objekte wenn ein neues <code>Group</code> Objekt
* instanziiert wird.
*
* @param g die neu hinzugefügte <code>Group</code>.
*/
public void updateAddedGroup(Group g) {
this.getPersonGroups().add(g);
groupsDataProvider.setList(this.getPersonGroups());
groupsDataProvider.refresh();
selectionModel.setSelected(g, true);
}
/**
* Methode zum aktualisieren des ListDataProvider von <code>ShoppingList</code> Objekten wenn ein
* neues <code>ShoppingList</code> Objekt instanziiert und zu einem <code>Group</code> Objekt hinzugefügt wird.
*
* @param sl die neu hinzugefügte <code>ShoppingList</code>.
* @param g die <code>Group</code> in die hinzugefügt wird.
*/
public void updateShoppingListToGroup(ShoppingList sl, Group g) {
sslf.setGroup(g);
//node des celltrees öffnen
tree.getRootTreeNode().setChildOpen(groupsDataProvider.getList().indexOf(g), true);
//alle dataprovider f�r shoppinglists aktualisieren
for(Group group: shoppingListHolderDataProviders.keySet()) {
final Group tempg = group;
final ShoppingList tempsl = sl;
administration.getAllShoppingListsByGroup(group, new AsyncCallback<ArrayList<ShoppingList>>() {
@Override
public void onFailure(Throwable caught) {
Notification.show("failed");
}
@Override
public void onSuccess(ArrayList<ShoppingList> result) {
shoppingListHolderDataProviders.get(tempg).getList().clear();
shoppingListHolderDataProviders.get(tempg).getList().addAll(result);
shoppingListHolderDataProviders.get(tempg).refresh();
selectionModel.setSelected(tempsl, true);
}
});
}
}
/**
* Methode zum aktualisieren des ListDataProvider von <code>Group</code> Objekten wenn ein
* <code>Group</code> Objekt gelöscht wird.
*
* @param g die zu entfernende <code>Group</code>.
*/
public void updateRemovedGroup(Group g) {
groupsDataProvider.getList().remove(g);
this.getPersonGroups().remove(g);
groupsDataProvider.setList(this.getPersonGroups());
groupsDataProvider.refresh();
}
/**
* Methode zum Aktualisieren des ListDataProvider von <code>ShoppingList</code> Objekten
* wenn ein <code>ShoppingList</code> Objekt gelöscht wird.
*
* @param sl
*/
public void updateRemovedShoppingList(ShoppingList sl) {
for(Group group: shoppingListHolderDataProviders.keySet()) {
final Group tempg = group;
administration.getAllShoppingListsByGroup(group, new AsyncCallback<ArrayList<ShoppingList>>() {
@Override
public void onFailure(Throwable caught) {
Notification.show("failed");
}
@Override
public void onSuccess(ArrayList<ShoppingList> result) {
shoppingListHolderDataProviders.get(tempg).getList().clear();
shoppingListHolderDataProviders.get(tempg).getList().addAll(result);
shoppingListHolderDataProviders.get(tempg).refresh();
selectionModel.setSelected(null, false);
RootPanel.get("Details").clear();
}
});
}
}
/**
* Methode zum aktualisieren des ListDataProvider für <code>Group</code> Objekte nachdem
* ein Objekt der Klasse <code>Group</code> aktualisiert wurde.
*
* @param g die aktualisierte <code>Group</code>.
*/
public void updateGroup(Group g) {
groupsDataProvider.setList(this.getPersonGroups());
groupsDataProvider.refresh();
}
/**
* Methode zum aktualisieren des ListDataProvider für <code>ShoppingList</code> Objekte nachdem
* ein Objekt der Klasse <code>ShoppingList</code> aktualisiert wurde.
*
* @param sl die aktualisierte <code>ShoppingList</code>.
*/
public void updateShoppingList(ShoppingList sl) {
for(Group group: shoppingListHolderDataProviders.keySet()) {
final Group tempg = group;
final ShoppingList tempsl = sl;
administration.getAllShoppingListsByGroup(group, new AsyncCallback<ArrayList<ShoppingList>>() {
@Override
public void onFailure(Throwable caught) {
Notification.show("failed");
}
@Override
public void onSuccess(ArrayList<ShoppingList> result) {
shoppingListHolderDataProviders.get(tempg).getList().clear();
shoppingListHolderDataProviders.get(tempg).getList().addAll(result);
shoppingListHolderDataProviders.get(tempg).refresh();
selectionModel.setSelected(tempsl, true);
}
});
}
}
/**
* Prüfen ob das angezeigte Objekt ein Blattknoten ist.
* Blattknoten lassen sich nicht ausklappen.
*/
@Override
public boolean isLeaf(Object value) {
// The leaf nodes are the songs, which are Strings.
if (value instanceof ShoppingList) {
return true;
}
return false;
}
/**
* Auslesen der {@link NodeInfo} die die Werte für Kindknoten bereitstellt.
*/
public <T> NodeInfo<?> getNodeInfo(T value) {
if (value == null) {
administration.getAllGroupsByPerson(currentPerson, new AsyncCallback<ArrayList<Group>>() {
@Override
public void onFailure(Throwable caught) {
// TODO Auto-generated method stub
Notification.show("Es ist ein Fehler aufgetreten! +\n"+ caught.toString());
}
@Override
public void onSuccess(ArrayList<Group> groups) {
for (Group g: groups) {
CustomTreeModel.this.getPersonGroups().add(g);
groupsDataProvider.getList().add(g);
}
}
});
// Return a node info that pairs the data provider and the cell.
return new DefaultNodeInfo<Group>(groupsDataProvider, new GroupListCell(), selectionModel, null);
}
if (value instanceof Group) {
final ListDataProvider<ShoppingList> shoppinglistProvider = new ListDataProvider<ShoppingList>();
shoppingListHolderDataProviders.put((Group)value, shoppinglistProvider);
administration.getAllShoppingListsByGroup((Group)value, new AsyncCallback<ArrayList<ShoppingList>>() {
@Override
public void onFailure(Throwable caught) {
// TODO Auto-generated method stub
Notification.show("Fehler: " + caught.toString());
}
@Override
public void onSuccess(ArrayList<ShoppingList> shoppinglists) {
// TODO Auto-generated method stub
for (ShoppingList sl : shoppinglists ) {
ShoppingList shoppingList = new ShoppingList();
shoppingList.setTitle(sl.getTitle());
shoppingList.setId(sl.getId());
shoppinglistProvider.getList().add(sl);
}
}
});
return new DefaultNodeInfo<ShoppingList>(shoppinglistProvider, new ShoppingListCell(), selectionModel, null);
}
return null;
}
/**
* ************************* ABSCHNITT der Keyprovider *************************
*/
/**
* Versieht jedes darzustellende <code>Group</code> und <code>ShoppingList</code> Objekt
* mit einer eindeutigen ID.
*
*/
private class ObjectKeyProvider implements ProvidesKey<Object> {
@Override
public Integer getKey(Object object) {
if (object == null) {
return null;
}
else if (object instanceof Group) {
return ((Group) object).getId();
}
else if (object instanceof ShoppingList) {
return ((ShoppingList) object).getId();
}
return null;
}
}
/**
* ************************* ABSCHNITT der EventHandler *************************
*/
/**
* Ein SelectionHandler der das in dem SingleSelectionModel des <code>CustomTreeModel</code> ausgewählte
* <code>Group</code> oder <code>ShoppingList</code> Objekt als ausgewählt setzt.
*/
class SelectionChangeEventHandler implements SelectionChangeEvent.Handler {
@Override
public void onSelectionChange(SelectionChangeEvent event) {
Object selection = selectionModel.getSelectedObject();
if (selection instanceof Group) {
setSelectedGroup((Group) selection);
} else if (selection instanceof ShoppingList) {
setSelectedShoppingList((ShoppingList) selection);
}
}
}
/**
* ************************* ABSCHNITT der Callbacks *************************
*/
/**
*CallBack mit dem alle <code>ShoppingList</code> Einträge einer <code>Group</code> aus der Datenbank geladen werden.
* Anschließend werden alle geladenen Objekte der Variable sl hinzugefügt.
*/
private class GetGroupShoppingListsCallback implements AsyncCallback<ArrayList<ShoppingList>> {
@Override
public void onFailure(Throwable caught) {
Notification.show("Es wurden keine Einkaufslisten in den Gruppen gefunden:\n" + caught.toString());
}
@Override
public void onSuccess(ArrayList<ShoppingList> sl) {
// add item to cellist
// aicl.updateCellList();
shoppinglists = sl;
}
}
/**
* ************************* ABSCHNITT der Cells *************************
*/
/**
* <code>GroupListCell</code> Objekt zum Rendern der anzuzeigenden <code>Group</code> Objekte.
* Wird mit dem Namen der <code>Group</code> befüllt.
*/
public class GroupListCell extends AbstractCell<Group>{
@Override
public void render(Context context, Group g, SafeHtmlBuilder sb) {
if (g != null) {
sb.appendHtmlConstant("<div>");
sb.appendHtmlConstant(g.getTitle());
sb.appendHtmlConstant("</div>");
}
}
}
/**
* <code>ShoppingListCell</code> Objekt zum Rendern der anzuzeigenden <code>ShoppingList</code> Objekte.
* Wird mit dem Namen des <code>ShoppingList</code> befüllt.
*/
public class ShoppingListCell extends AbstractCell<ShoppingList>{
@Override
public void render(Context context, ShoppingList s, SafeHtmlBuilder sb) {
if (s != null) {
sb.appendHtmlConstant("<div>");
sb.appendHtmlConstant(s.getTitle());
sb.appendHtmlConstant("</div>");
}
}
}
} |
/*
MIT License
Copyright (c) 2016 Kent Randall
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
package org.point85.domain.schedule.test;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.List;
import org.junit.BeforeClass;
import org.point85.domain.schedule.ExceptionPeriod;
import org.point85.domain.schedule.Rotation;
import org.point85.domain.schedule.Shift;
import org.point85.domain.schedule.ShiftInstance;
import org.point85.domain.schedule.Team;
import org.point85.domain.schedule.WorkSchedule;
/**
* Base class for testing shift plans
*
* @author Kent
*
*/
public abstract class BaseTest {
protected static double DELTA2 = 0.01d;
protected static double DELTA3 = 0.001d;
protected static double DELTA4 = 0.0001d;
// reference date for start of shift rotations
protected final LocalDate referenceDate = LocalDate.of(2016, 10, 31);
// a later date and time
protected final LocalDate laterDate = LocalDate.of(2021, 10, 1);
protected final LocalTime laterTime = LocalTime.of(7, 0, 0);
// partial test flags
protected static boolean testToString = true;
protected static boolean testDeletions = true;
// a work schedule
protected WorkSchedule schedule;
@BeforeClass
public static void setFlags() {
testToString = true;
testDeletions = true;
}
private void testShifts(WorkSchedule ws) throws Exception {
assertTrue(ws.getShifts().size() > 0);
for (Shift shift : ws.getShifts()) {
Duration total = shift.getDuration();
LocalTime start = shift.getStart();
LocalTime end = shift.getEnd();
assertTrue(shift.getName().length() > 0);
assertTrue(shift.getDescription().length() > 0);
assertTrue(total.toMinutes() > 0);
assertTrue(shift.getBreaks() != null);
assertTrue(start != null);
assertTrue(end != null);
Duration worked = null;
boolean spansMidnight = shift.spansMidnight();
if (spansMidnight) {
// get the interval before midnight
worked = shift.calculateWorkingTime(start, end, true);
} else {
worked = shift.calculateWorkingTime(start, end);
}
assertTrue(worked.equals(total));
if (spansMidnight) {
worked = shift.calculateWorkingTime(start, start, true);
} else {
worked = shift.calculateWorkingTime(start, start);
}
// 24 hour shift on midnight is a special case
if (total.equals(Duration.ofHours(24))) {
assertTrue(worked.toHours() == 24);
} else {
assertTrue(worked.toHours() == 0);
}
if (spansMidnight) {
worked = shift.calculateWorkingTime(end, end, true);
} else {
worked = shift.calculateWorkingTime(end, end);
}
if (total.equals(Duration.ofHours(24))) {
assertTrue(worked.toHours() == 24);
} else {
assertTrue(worked.toHours() == 0);
}
try {
LocalTime t = start.minusMinutes(1);
worked = shift.calculateWorkingTime(t, end);
if (!total.equals(shift.getDuration())) {
fail("Bad working time");
}
} catch (Exception e) {
}
try {
LocalTime t = end.plusMinutes(1);
worked = shift.calculateWorkingTime(start, t);
if (!total.equals(shift.getDuration())) {
fail("Bad working time");
}
} catch (Exception e) {
}
}
}
private void testTeams(WorkSchedule ws, Duration hoursPerRotation, Duration rotationDays) throws Exception {
assertTrue(ws.getTeams().size() > 0);
for (Team team : ws.getTeams()) {
assertTrue(team.getName().length() > 0);
assertTrue(team.getDescription().length() > 0);
assertTrue(team.getDayInRotation(team.getRotationStart()) == 1);
Duration hours = team.getRotation().getWorkingTime();
assertTrue(hours.equals(hoursPerRotation));
assertTrue(team.getPercentageWorked() > 0.0f);
assertTrue(team.getRotationDuration().equals(rotationDays));
assertTrue(team.getRotationStart() != null);
Rotation rotation = team.getRotation();
assertTrue(rotation.getDuration().equals(rotationDays));
assertTrue(rotation.getPeriods().size() > 0);
assertTrue(rotation.getWorkingTime().getSeconds() <= rotation.getDuration().getSeconds());
}
assertTrue(ws.getExceptionPeriods() != null);
}
private void testShiftInstances(WorkSchedule ws, LocalDate instanceReference) throws Exception {
Rotation rotation = ws.getTeams().get(0).getRotation();
// shift instances
LocalDate startDate = instanceReference;
LocalDate endDate = instanceReference.plusDays(rotation.getDuration().toDays());
long days = endDate.toEpochDay() - instanceReference.toEpochDay() + 1;
LocalDate day = startDate;
for (long i = 0; i < days; i++) {
List<ShiftInstance> instances = ws.getShiftInstancesForDay(day);
for (ShiftInstance instance : instances) {
assertTrue(instance.getStartTime().isBefore(instance.getEndTime()));
assertTrue(instance.getShift() != null);
assertTrue(instance.getTeam() != null);
Shift shift = instance.getShift();
LocalTime startTime = shift.getStart();
LocalTime endTime = shift.getEnd();
assertTrue(shift.isInShift(startTime));
assertTrue(shift.isInShift(startTime.plusSeconds(1)));
Duration shiftDuration = instance.getShift().getDuration();
// midnight is special case
if (!shiftDuration.equals(Duration.ofHours(24))) {
assertFalse(shift.isInShift(startTime.minusSeconds(1)));
}
assertTrue(shift.isInShift(endTime));
assertTrue(shift.isInShift(endTime.minusSeconds(1)));
if (!shiftDuration.equals(Duration.ofHours(24))) {
assertFalse(shift.isInShift(endTime.plusSeconds(1)));
}
LocalDateTime ldt = LocalDateTime.of(day, startTime);
assertTrue(ws.getShiftInstancesForTime(ldt).size() > 0);
ldt = LocalDateTime.of(day, startTime.plusSeconds(1));
assertTrue(ws.getShiftInstancesForTime(ldt).size() > 0);
ldt = LocalDateTime.of(day, startTime.minusSeconds(1));
for (ShiftInstance si : ws.getShiftInstancesForTime(ldt)) {
if (!shiftDuration.equals(Duration.ofHours(24))) {
assertFalse(shift.getName().equals(si.getShift().getName()));
}
}
ldt = LocalDateTime.of(day, endTime);
assertTrue(ws.getShiftInstancesForTime(ldt).size() > 0);
ldt = LocalDateTime.of(day, endTime.minusSeconds(1));
assertTrue(ws.getShiftInstancesForTime(ldt).size() > 0);
ldt = LocalDateTime.of(day, endTime.plusSeconds(1));
for (ShiftInstance si : ws.getShiftInstancesForTime(ldt)) {
if (!shiftDuration.equals(Duration.ofHours(24))) {
assertFalse(shift.getName().equals(si.getShift().getName()));
}
}
}
day = day.plusDays(1);
}
}
protected void runBaseTest(WorkSchedule ws, Duration hoursPerRotation, Duration rotationDays,
LocalDate instanceReference) throws Exception {
// toString
if (testToString) {
System.out.println(ws.toString());
ws.printShiftInstances(instanceReference, instanceReference.plusDays(rotationDays.toDays()));
}
assertTrue(ws.getName().length() > 0);
assertTrue(ws.getDescription().length() > 0);
assertTrue(ws.getExceptionPeriods() != null);
// shifts
testShifts(ws);
// teams
testTeams(ws, hoursPerRotation, rotationDays);
// shift instances
testShiftInstances(ws, instanceReference.plusDays(rotationDays.toDays()));
if (testDeletions) {
testDeletions();
}
}
private void testDeletions() throws Exception {
// team deletions
Team[] teams = new Team[schedule.getTeams().size()];
schedule.getTeams().toArray(teams);
for (Team team : teams) {
schedule.deleteTeam(team);
}
assertTrue(schedule.getTeams().size() == 0);
// shift deletions
Shift[] shifts = new Shift[schedule.getShifts().size()];
schedule.getShifts().toArray(shifts);
for (Shift shift : shifts) {
schedule.deleteShift(shift);
}
assertTrue(schedule.getShifts().size() == 0);
// non-working period deletions
ExceptionPeriod[] periods = new ExceptionPeriod[schedule.getExceptionPeriods().size()];
schedule.getExceptionPeriods().toArray(periods);
for (ExceptionPeriod period : periods) {
schedule.deleteExceptionPeriod(period);
}
assertTrue(schedule.getExceptionPeriods().size() == 0);
}
protected boolean isCloseTo(double actualValue, double expectedValue, double delta) {
double diff = Math.abs(actualValue - expectedValue);
return (diff <= delta) ? true : false;
}
}
|
package com.gxtc.huchuan.im.bean.dao;
import com.gxtc.huchuan.im.bean.RemoteMessageBean;
import org.greenrobot.greendao.annotation.Entity;
import org.greenrobot.greendao.annotation.Id;
import org.greenrobot.greendao.annotation.Generated;
/**
* Created by Gubr on 2017/4/8.
*/
@Entity
public class MessageHistoryBean {
private String content;
private String dataTime;
private String fromUserId;
private String name;
private String objectName;
private long targetId;
private String targetType;
private String userCode;
@Id private long id;
public MessageHistoryBean(RemoteMessageBean messageBean) {
this.content = messageBean.getContent();
this.dataTime = messageBean.getDataTime();
this.fromUserId = messageBean.getFromUserId();
this.name = messageBean.getName();
this.objectName = messageBean.getObjectName();
this.targetId = Long.valueOf(messageBean.getTargetId());
this.targetType = messageBean.getTargetType();
this.userCode = messageBean.getUserCode();
this.id = Long.valueOf(messageBean.getId());
}
@Generated(hash = 171102149)
public MessageHistoryBean(String content, String dataTime, String fromUserId,
String name, String objectName, long targetId, String targetType,
String userCode, long id) {
this.content = content;
this.dataTime = dataTime;
this.fromUserId = fromUserId;
this.name = name;
this.objectName = objectName;
this.targetId = targetId;
this.targetType = targetType;
this.userCode = userCode;
this.id = id;
}
@Generated(hash = 830674591)
public MessageHistoryBean() {
}
public String getContent() {
return this.content;
}
public void setContent(String content) {
this.content = content;
}
public String getDataTime() {
return this.dataTime;
}
public void setDataTime(String dataTime) {
this.dataTime = dataTime;
}
public String getFromUserId() {
return this.fromUserId;
}
public void setFromUserId(String fromUserId) {
this.fromUserId = fromUserId;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public String getObjectName() {
return this.objectName;
}
public void setObjectName(String objectName) {
this.objectName = objectName;
}
public long getTargetId() {
return this.targetId;
}
public void setTargetId(long targetId) {
this.targetId = targetId;
}
public String getTargetType() {
return this.targetType;
}
public void setTargetType(String targetType) {
this.targetType = targetType;
}
public String getUserCode() {
return this.userCode;
}
public void setUserCode(String userCode) {
this.userCode = userCode;
}
public long getId() {
return this.id;
}
public void setId(long id) {
this.id = id;
}
} |
package org.rest.controller;
import java.util.Arrays;
import java.util.List;
import org.rest.dto.AnimalDto;
import org.rest.service.AnimalService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.ModelAttribute;
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.RestController;
@RestController
public class AnimalController {
@Autowired
AnimalService service;
@RequestMapping(value = "/welcome", produces = MediaType.APPLICATION_JSON_VALUE, method = RequestMethod.GET)
String welcomeAnimal() {
return "hello animal , hope you are good";
}
@RequestMapping(value = "/getAnimal", produces = MediaType.APPLICATION_JSON_VALUE, method = RequestMethod.GET)
AnimalDto getDummyAnimal() {
AnimalDto dto = new AnimalDto("human being", "yumraaj", 900);
return dto;
}
@RequestMapping(value = "/getListAnimal", produces = MediaType.APPLICATION_JSON_VALUE, method = RequestMethod.GET)
List<AnimalDto> getListOfAnimal() {
return Arrays.asList(new AnimalDto("human being", "yumraaj", 900) ,
new AnimalDto("dog", "entertimnet", 12),
new AnimalDto("cat", "tom", 2),
new AnimalDto("lion", "simba", 15));
}
@RequestMapping(value = "/saveAnimal", consumes = MediaType.APPLICATION_JSON_VALUE,
method = RequestMethod.POST)
AnimalDto saveAnimal(@RequestBody AnimalDto animal) {
System.out.println(animal);
return animal;
}
}
|
package com.perfect.web.service.impl;
import com.perfect.core.base.BaseServiceImpl;
import com.perfect.entity.Role;
import com.perfect.entity.mapper.RoleMapper;
import com.perfect.web.service.RoleService;
import org.springframework.stereotype.Service;
/**
* <p>
* 角色表 服务实现类
* </p>
*
* @author Ben.
* @since 2017-03-15
*/
@Service
public class RoleServiceImpl extends BaseServiceImpl<RoleMapper, Role> implements RoleService {
}
|
package com.hometask9.jdbc.dao;
import com.hometask9.jdbc.config.ConnectionPool;
import com.hometask9.jdbc.config.DB;
import com.hometask9.jdbc.entity.Author;
import com.hometask9.jdbc.entity.Book;
import com.hometask9.jdbc.util.Books;
import com.mysql.jdbc.jdbc2.optional.MysqlConnectionPoolDataSource;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.sql.*;
import java.util.*;
/**
* Created by kleba on 10.04.2018.
*/
public class BookDAOImpl implements BookDAO {
private Connection connection;
private ConnectionPool connectionPool;
final static Logger rootLogger = LogManager.getLogger(BookDAOImpl.class);
/*
* TRANSACTION_NONE- not supported in MySQL
* TRANSACTION_READ_UNCOMMITTED =1
* TRANSACTION_READ_COMMITTED=2
* TRANSACTION_REPEATABLE_READ=4
* TRANSACTION_SERIALIZABLE=8
* */
public void setTransactionType(int transactionType){
try {
connection.setTransactionIsolation(transactionType);
} catch (SQLException e) {
e.printStackTrace();
}
}
@Override
public Set<Book> checkBooks(Books books) {
Set<Book> repeatedBook= new HashSet<>();
List <Book> xmlBooks=new ArrayList<>(books.getBookList());
System.out.println(xmlBooks.toString());
List<Book> booksList=new ArrayList(getAllABooks());
Set<Book> bookSet = new HashSet<>();
for(int i=0;i<xmlBooks.size();i++){
boolean flag=false;
for(int j=0;j<booksList.size();j++){
if((xmlBooks.get(i).getName().equals(booksList.get(j).getName()))&&i!=j){
flag=true;
}
}
if(!flag){
System.out.println(xmlBooks.get(i));
bookSet.add(xmlBooks.get(i));
}else {
repeatedBook.add(xmlBooks.get(i));
}
}
if(bookSet.size()>0) {
addAuthorWithAllHisBooks(bookSet);
}
return repeatedBook;
}
public int getTransactionType(){
try {
return connection.getTransactionIsolation();
} catch (SQLException e) {
e.printStackTrace();
return -10;
}
}
public Connection connect(DB db) {
try {
connectionPool = new ConnectionPool(db,5);
connection= connectionPool.retrieve();
connection.setAutoCommit(false);
rootLogger.info("db connect");
} catch (SQLException e) {
rootLogger.error("Incorrect URL");
}
return connection;
}
@Override
public boolean writeXmlFile(String xml) {
String path="src\\main\\resources\\";
String name="output.xml";
File file = new File(path,name);
FileWriter fw=null;
try {
fw = new FileWriter(path+name);
fw.write(xml);
fw.flush();
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
}finally {
try {
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public boolean persist(Object o) {
if(o instanceof Author){
Author author= (Author) o;
PreparedStatement pr ;
int response = 0;
try {
pr = connection.prepareStatement("INSERT INTO Author(Name,Surname,Birthday) values(?,?,?)");
pr.setString(1,author.getName());
pr.setString(2,author.getSurname());
pr.setDate(3,author.getBirthday());
response=pr.executeUpdate();
rootLogger.info("Author inserted into DB");
connection.commit();
} catch (SQLException e) {
rootLogger.error("Incorrect Author arguments");
try {
connection.rollback();
} catch (SQLException e1) {
e1.printStackTrace();
}
}finally {
System.out.println(response);
}
}else if(o instanceof Book){
Book book= (Book) o;
System.out.println(book);
PreparedStatement pr ;
int response = 0;
try {
pr = connection.prepareStatement("INSERT INTO Book(Title,NumberOfPages,AuthorID) values(?,?,?)");
pr.setString(1,book.getName());
pr.setInt(2,book.getNumberOfPages());
pr.setLong(3,book.getAuthorId());
response=pr.executeUpdate();
connection.commit();
rootLogger.info("Book inserted into DB");
} catch (SQLException e) {
rootLogger.error("Incorrect Book arguments");
try {
connection.rollback();
} catch (SQLException e1) {
e1.printStackTrace();
}
}finally {
System.out.println(response);
}
}else{
rootLogger.error("Unknown object");
return false;
}
return true;
}
public List<Book>searchBooksByAuthor(String name,String surname){
List<Book> books = new ArrayList<>();
ResultSet rs = null;
try {
PreparedStatement pr = connection.prepareStatement("Select b.ID,b.title,b.NumberOfPages,b.AuthorID From Book b, Author a WHERE b.AuthorID=a.ID and a.Surname=? AND a.name like ?");
pr.setString(1,surname);
pr.setString(2,"%"+name+"%");
rs=pr.executeQuery();
connection.commit();
while(rs.next()){
Book b= new Book();
b.setId(rs.getLong(1));
b.setName(rs.getString(2));
b.setNumberOfPages(rs.getInt(3));
b.setAuthorId(rs.getLong(4));
books.add(b);
}
} catch (SQLException e) {
rootLogger.error("Incorrect arguments");
try {
connection.rollback();
} catch (SQLException e1) {
e1.printStackTrace();
}
return null;
}
return books;
}
public boolean deleteAuthorWithHisBooksById(long authorID){
PreparedStatement pr ;
int response=0;
try {
pr = connection.prepareStatement("DELETE FROM Author where ID=?");
pr.setLong(1,authorID);
response=pr.executeUpdate();
connection.commit();
rootLogger.info("Author with id "+ authorID+" was deleted");
} catch (SQLException e) {
rootLogger.error("Incorrect author id");
try {
connection.rollback();
} catch (SQLException e1) {
e1.printStackTrace();
}
return false;
}finally {
System.out.println(response);
}
return true;
}
public boolean updateBookNameByBookId(String newName,long bookId){
PreparedStatement pr ;
int response=0;
try {
pr = connection.prepareStatement("UPDATE Book set title=? where ID=?");
pr.setString(1,newName);
pr.setLong(2,bookId);
response=pr.executeUpdate();
rootLogger.info("Book name was updated");
} catch (SQLException e) {
rootLogger.error("Incorrect arguments");
try {
connection.rollback();
} catch (SQLException e1) {
e1.printStackTrace();
}
return false;
}finally {
System.out.println(response);
}
return true;
}
@Override
public boolean addAuthorWithAllHisBooks( Set<Book> bookSet) {
Savepoint savepoint=null;
boolean flag=false;
try {
for (Book book : bookSet) {
savepoint= connection.setSavepoint();
persist(book);
}
flag = true;
}catch (Exception e){
try {
connection.rollback(savepoint);
} catch (SQLException e1) {
e1.printStackTrace();
}
rootLogger.error("Can't add books");
flag = false;
} finally {
try {
connection.commit();
} catch (SQLException e) {
e.printStackTrace();
}
return flag;
}
}
public Set<Author> getAllAuthors(){
Set<Author> author = new HashSet<>();
ResultSet rs = null;
try {
Statement statement = connection.createStatement();
String sql="Select * From Author";
rs=statement.executeQuery(sql);
while(rs.next()){
Author a = new Author();
a.setId(rs.getLong(1));
a.setName(rs.getString(2));
a.setSurname(rs.getString(3));
a.setBirthday(rs.getDate(4));
author.add(a);
}
rootLogger.info(author.size()+"authors were found");
} catch (SQLException e) {
try {
connection.rollback();
} catch (SQLException e1) {
e1.printStackTrace();
}
rootLogger.error("Incorrect arguments");
return null;
}
return author;
}
public List<Book> getAllABooks(){
List<Book> books = new ArrayList<>();
ResultSet rs = null;
try {
Statement statement = connection.createStatement();
String sql="Select * From Book";
rs=statement.executeQuery(sql);
while(rs.next()){
Book b= new Book();
b.setId(rs.getLong(1));
b.setName(rs.getString(2));
b.setNumberOfPages(rs.getInt(3));
b.setAuthorId(rs.getLong(4));
books.add(b);
}
rootLogger.info(books.size()+"books were found");
} catch (SQLException e) {
rootLogger.error("Incorrect arguments");
try {
connection.rollback();
} catch (SQLException e1) {
e1.printStackTrace();
}
return null;
}
return books;
}
public Connection getConnection() {
return connection;
}
public boolean closeConnection(){
try {
connectionPool.putback(connection);
rootLogger.info("Connection closed");
return true;
} catch (Exception e) {
rootLogger.error("Connection wasn't closed");
try {
connection.rollback();
} catch (SQLException e1) {
e1.printStackTrace();
}
return false;
}
}
@Override
public String moneyCourse(String path) {
try (Scanner scanner = new Scanner(new URL(path).openStream(),
StandardCharsets.UTF_8.toString()))
{
scanner.useDelimiter("\\A");
return scanner.hasNext() ? scanner.next() : "";
} catch (MalformedURLException e) {
e.printStackTrace();
return null;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
}
|
import java.io.*;
import java.net.*;
import java.util.*;
import java.util.stream.Collectors;
public class CS245A1{
static Properties property = new Properties();
static String inputFile, outputFile;
static BSTSpellchecker treeBST;
static Trie treeTrie;
static boolean type = true; //true sets Trie, false sets BST
static ArrayList<String> dictionary, input;
static BufferedWriter output;
private static long start, end = 0;
public CS245A1(){
treeTrie = new Trie();
treeBST = new BSTSpellchecker();
dictionary = new ArrayList<String>();
input = new ArrayList<String>();
}
public static void main(String[] args){
InputStream file;
try{
String filePath = new File("").getAbsolutePath();
filePath = filePath.concat("/a1properties");
file = new FileInputStream(filePath);
property.load(file);
} catch (IOException e){
property.setProperty("storage", "trie");
}
if(property.getProperty("storage").equals("trie")){
type = true;
} else {
type = false;
}
if(args.length < 2){
System.out.println("Missing at least 1 Argument");
return;
}
CS245A1 assignment1 = new CS245A1();
assignment1.inputFile = args[0];
assignment1.outputFile = args[1];
//start = System.currentTimeMillis();
assignment1.createDictionary(type);
assignment1.readInput(type);
//end = System.currentTimeMillis();
//System.out.println("Total time needed "+ (end-start));
}
public static void createDictionary(boolean type){
try{
URL url = new URL("https://raw.githubusercontent.com/magsilva/jazzy/master/resource/dict/english.0"); //find URL
Scanner scan = new Scanner(url.openStream()); //Create scanner
long start = System.currentTimeMillis();
while (scan.hasNextLine()) {
String line = scan.nextLine();
if (!line.isEmpty()) {
dictionary.add(line); //store words in dictionary array
}
}
if (type == true){ //find correct tree to insert into given Type
while (scan.hasNext()){
String word = scan.next(); //Read file data into trie or bst depending on type.
treeTrie.insert(word);
}
long end = System.currentTimeMillis();
float sec = (end-start);
System.out.println(sec + "ms");
} else if (type == false){
while (scan.hasNext()){
String word1 = scan.next();
treeBST.insert(word1);
}
long end = System.currentTimeMillis();
float sec = (end-start);
System.out.println("Time needed:" +sec + "ms");
}
} catch (IOException e) {
e.printStackTrace();
}
}
public static void readInput(boolean type) {
try{
Scanner scan = new Scanner(new File(inputFile));
while(scan.hasNext()){
String word = scan.next();
if (word != null){
input.add(word); //add all words in input to input arraylist for use in correcting
}
}
}catch(FileNotFoundException e){
System.out.println("Input file not found.");
return;
}
if (type == true){
trieStore();
} else {
bstStore();
}
}
public static void trieStore(){
try{
File makeFile = new File(outputFile); //write an output file
output = new BufferedWriter(new FileWriter(makeFile));
for (int i = 0; i < input.size(); i++){
HashMap<String, Integer> mapDistance = new HashMap<String, Integer>(); //a map of strings in Dictionary + Leven. distance w/ input
String inWord = input.get(i);
if(treeTrie.search(inWord)){
output.write(inWord + "\n"); //if word spelled correctly write it out in the file.
} else {
for (int j = 0; j < dictionary.size(); j++){
String word = dictionary.get(j);
mapDistance.put(word, levenshtein(inWord, word, inWord.length(), word.length()));
}
//sort map distance by val
mapDistance = mapDistance.entrySet().stream().sorted(Map.Entry.comparingByValue()).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e1, LinkedHashMap::new));
Iterator<String> iterator = mapDistance.keySet().iterator();
for(int k = 0; k < 3; k++){ //write 3 elements in L.distance.
output.write(iterator.next() + " ");
}
output.write("\n");
}
}
output.close();
} catch (Exception e){
System.out.println(e.toString());
}
}
public static void bstStore(){
try{
File makeFile = new File(outputFile);
output = new BufferedWriter(new FileWriter(makeFile));
for (int i = 0; i < input.size(); i++){
HashMap<String, Integer> mapDistance = new HashMap<String, Integer>();
String inWord = input.get(i);
if(treeBST.search(inWord)){
output.write(inWord + "\n");
} else {
for (int j = 0; j < dictionary.size(); j++){
String word = dictionary.get(j);
mapDistance.put(word, levenshtein(inWord, word, inWord.length(), word.length()));
}
mapDistance = mapDistance.entrySet().stream().sorted(Map.Entry.comparingByValue()).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e1, LinkedHashMap::new));
Iterator<String> iterator = mapDistance.keySet().iterator();
for(int k = 0; k < 3; k++){
output.write(iterator.next() + " ");
}
output.write("\n");
}
}
output.close();
} catch (Exception e){
System.out.println(e.toString());
}
}
public static int levenshtein(String st1, String st2, int lt1, int lt2) { //enter two words + length of each
int[][] length = new int[lt1+1][lt2+1]; //create graph that stores distances
for(int i = 0; i <= lt1; i++){
for(int j = 0; j <= lt2; j++){ //nested for loops testing each element of st1 and st2
if(i==0){
length[i][j] = j;
} else if (j == 0){
length[i][j] = i;
} else {
length[i][j] = min(length[i - 1][j - 1]
+ costOfSubstitution(st1.charAt(i - 1), st2.charAt(j - 1)),
length[i - 1][j] + 1,
length[i][j - 1] + 1); //set length[i][j] tothe smallest element of the lengths of words -1 and the cost of substitition between said words
}
}
}
return length[lt1][lt2];
}
public static int costOfSubstitution(char a, char b){ //returns how many subsitutions required to create correct words.
return a==b ? 0:1;
}
public static int min(int ... numbers) //finds the minimym number of all vals.
{
return Arrays.stream(numbers).min().orElse(Integer.MAX_VALUE);
}
} |
package Setupas;
import io.github.bonigarcia.wdm.WebDriverManager;
import org.junit.Test;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class chrome_JUnit {
@Test
public void openChromeLocalWebDriver() throws InterruptedException {
System.setProperty("webdriver.chrome.driver", "C:\\WebDrivers\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
System.out.println("Testas prasidejo.");
driver.get("https://www.google.lt");
Thread.sleep(5000);
System.out.println("Testas baigesi.");
driver.quit();
}
@org.testng.annotations.Test
public void openChromeWebDriverManager() throws InterruptedException {
WebDriverManager.firefoxdriver().setup();
WebDriver driver = new FirefoxDriver();
System.out.println("Testas prasidejo.");
driver.get("http://www.google.lt");
Thread.sleep(5000);
System.out.println("Testas baigesi.");
driver.quit();
}
}
|
package br.com.features.java.eight;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
public class ExamplesJavaEight implements IntefaceJavaEight {
public ExamplesJavaEight() {
System.out.println("======= start example java 8 =======\n");
orderInList();
useDefaultMethod();
examplesLambda();
System.out.println("======= end example java 8 =======");
}
private void orderInList(){
System.out.println("******* start order in list *****");
List<String> words = Arrays.asList("rodrigo", "paulo", "caelum");
System.out.printf("list before sort: %s \n",words);
Comparator<String> comparator = new Comparator<String>() {
public int compare(String s1, String s2) {
return Integer.compare(s1.length(), s2.length());
}
};
words.sort(comparator); //OLD - Collections.sort(palavras, comparator);
System.out.printf("list before sort: %s \n",words);
System.out.println("******* end order in list *****\n");
}
private void useDefaultMethod(){
System.out.println("******* start default method *****");
System.out.println(isMethodDefault());
System.out.println("******* end default method *****\n");
}
private void examplesLambda(){
System.out.println("******* start example lambda with the same syntax *****");
List<String> words = Arrays.asList("rodrigo", "paulo", "caelum");
System.out.println(" fist exemplo lambda long");
Comparator<String> c1 = (s1, s2) -> {
return Integer.compare(s1.length(), s2.length());
};
words.sort(c1);
words.forEach(s -> {
System.out.println(s);
});
System.out.println("\n secund exemplo lambda middle");
Comparator<String> c2 = (s1, s2) -> Integer.compare(s1.length(), s2.length());
words.sort(c2);
words.forEach(s -> System.out.println(s));
System.out.println("\n third exemplo lambda small");
words.sort((s1, s2) -> Integer.compare(s1.length(), s2.length()));
words.forEach(System.out::println);
System.out.println("\n for exemplo lambda short");
words.sort(Comparator.comparing(s -> s.length()));
words.forEach(System.out::println);
System.out.println("\n five exemplo lambda more short");
words.sort(Comparator.comparing(String::length));
words.forEach(System.out::println);
System.out.println("******* end example lambda with the same syntax *****");
}
public void examplesLambda2(){
}
}
|
package gov.nih.nci.ctrp.importtrials.util;
import gov.nih.nci.ctrp.importtrials.dto.AgeDTO;
import gov.nih.nci.ctrp.importtrials.exception.ImportTrialException;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collection;
/**
* Created by kigonyapa on 3/27/17.
*/
@RunWith(Parameterized.class)
public class ImportTrialStringUtilsParseAgeValueTest {
@Parameterized.Parameter(value = 0)
public String ageStr;
@Parameterized.Parameter(value = 1)
public String expectedUnit;
@Parameterized.Parameter(value = 2)
public BigDecimal expectedAge;
@Parameterized.Parameter(value = 3)
public int precision;
@Parameterized.Parameter(value = 4)
public Boolean exceptionExpected;
@Parameterized.Parameters
public static Collection<Object[]> data() {
Collection<Object[]> params = new ArrayList<Object[]>();
// singulars
params.add(new Object[] {"180 Year", "Years", new BigDecimal(180), 3, Boolean.FALSE});
params.add(new Object[] {"18 Year", "Years", new BigDecimal(18), 2, Boolean.FALSE});
params.add(new Object[] {"180 Month", "Months", new BigDecimal(180), 3, Boolean.FALSE});
params.add(new Object[] {"18 Month", "Months", new BigDecimal(18), 2, Boolean.FALSE});
params.add(new Object[] {"1 Month", "Months", new BigDecimal(1), 1, Boolean.FALSE});
//plurals
params.add(new Object[] {"1 Decade", "Decade", new BigDecimal(1), 1, Boolean.TRUE});
params.add(new Object[] {"Years", "Decade", new BigDecimal(0), 1, Boolean.TRUE});
params.add(new Object[] {"9", "Decade", new BigDecimal(0), 1, Boolean.TRUE});
params.add(new Object[] {"180 Years", "Years", new BigDecimal(180), 3, Boolean.FALSE});
params.add(new Object[] {"18 Years", "Years", new BigDecimal(18), 2, Boolean.FALSE});
params.add(new Object[] {"180 Months", "Months", new BigDecimal(180), 3, Boolean.FALSE});
params.add(new Object[] {"18 Months", "Months", new BigDecimal(18), 2, Boolean.FALSE});
params.add(new Object[] {"1 Months", "Months", new BigDecimal(1), 1, Boolean.FALSE});
params.add(new Object[] {"N/A", "Months", new BigDecimal(1), 1, Boolean.FALSE});
// case
params.add(new Object[] {"18 YEAR", "Years", new BigDecimal(18), 2, Boolean.FALSE});
params.add(new Object[] {"YEARs", "Decade", new BigDecimal(0), 1, Boolean.TRUE});
params.add(new Object[] {"180 years", "Years", new BigDecimal(180), 3, Boolean.FALSE});
params.add(new Object[] {"180 months", "Months", new BigDecimal(180), 3, Boolean.FALSE});
return params;
}
@Test
public void test() {
try {
AgeDTO testDTO = ImportTrialStringUtils.parseAgeValue(ageStr);
if (testDTO != null) {
Assert.assertEquals(testDTO.getUnitCode(), expectedUnit);
Assert.assertEquals(testDTO.getValue(), expectedAge);
Assert.assertEquals(testDTO.getPrecision(), precision);
} else {
Assert.assertEquals(testDTO, null);
}
}
catch (ImportTrialException ite) {
if (!exceptionExpected)
Assert.fail("Exception not expected for parseAgeValue ageStr = " + ageStr);
}
}
} |
public class helloworld {
public static void main(String[] args){
System.out.println ("hello world with team Push branch master, Luki's version 01\n");
return;
}
}
|
package com.magic_chen_.jumperlib;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Parcelable;
import java.io.Serializable;
import java.lang.annotation.Annotation;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import static com.magic_chen_.jumperlib.ReflectUtils.checkGenericType;
import static com.magic_chen_.jumperlib.ReflectUtils.isSubclassOf;
/**
* Created by magic_chen_ on 2018/8/29.
* email:chenyouya@leigod.com
* project:BoheAccelerator_Android
*/
public class JumperInvokeHandler implements InvocationHandler {
final Context mContext;
public JumperInvokeHandler(Context context) {
mContext = context;
}
public static final HashMap<Class, Method> INTENT_PUT_EXTRA_MAP = new HashMap<Class, Method>() {
// 扩展类型 暂时用不上
// final Map<Class, Class> mCastMap = Collections.unmodifiableMap(new HashMap<Class, Class>() {
// {
// put(Byte.class, byte.class);
// put(Byte[].class, byte[].class);
//
// put(Boolean.class, boolean.class);
// put(Boolean[].class, boolean[].class);
//
// put(Character.class, char.class);
// put(Character[].class, char[].class);
//
// put(Short.class, short.class);
// put(Short[].class, short[].class);
//
// put(Integer.class, int.class);
// put(Integer[].class, int[].class);
//
// put(Long.class, long.class);
// put(Long[].class, long[].class);
//
// put(Float.class, float.class);
// put(Float[].class, float[].class);
//
// put(Double.class, double.class);
// put(Double[].class, double[].class);
// }
// });
//
// @Override
// public Method get(final Object key) {
// Method result = super.get(key);
// return result == null ? super.get(mCastMap.get(key)) : result;
// }
};
static {
Method[] methods = Intent.class.getMethods();
for (Method m : methods) {
if ("putExtra".equals(m.getName())) {
INTENT_PUT_EXTRA_MAP.put(m.getParameterTypes()[1], m);
}
}
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
final boolean needReturnIntent = method.getReturnType() == Intent.class;
final ActivityInfo aInfo = method.getAnnotation(ActivityInfo.class);
assert aInfo != null;
final Intent intent = new Intent();
if (aInfo.clz() != Activity.class) {
intent.setClass(mContext, aInfo.clz());
}
Annotation[][] parameterAnnotations = method.getParameterAnnotations();
LinkedList<ParamHolder> holderList = new LinkedList<ParamHolder>();
Type[] genericTypes = method.getGenericParameterTypes();
for (int i = 0, n = parameterAnnotations.length; i < n; ++i) {
if (parameterAnnotations[i] == null) {
continue;
}
final Annotation annotation = parameterAnnotations[i][0];
if (annotation == null) {
continue;
}
final Object arg = args[i];
if (arg == null) {
holderList.add(new ParamHolder(parameterAnnotations[i], i, genericTypes[i]));
} else if (annotation instanceof IntentParam) {
holderList.add(new ParamHolder(parameterAnnotations[i], i, genericTypes[i]));
}
}
for (ParamHolder holder : holderList) {
Object o = args[holder.index];
if (o == null) {
new Exception("intent param not null").printStackTrace();
return needReturnIntent ? intent : null;
}
final Class<?> clz = o.getClass();
final String key = holder.key;
final Method m = INTENT_PUT_EXTRA_MAP.get(clz);
if (m != null) {
m.invoke(intent, key, o);
} else if (isSubclassOf(clz, Serializable.class)) {
intent.putExtra(key, (Serializable) o);
} else if (isSubclassOf(clz, Parcelable.class)) {
intent.putExtra(key, (Parcelable) o);
} else if (isSubclassOf(clz, Parcelable[].class)) {
intent.putExtra(key, (Parcelable[]) o);
} else if (isSubclassOf(clz, ArrayList.class)) {
final Type listType = holder.genericType;
ArrayList list = (ArrayList) o;
if (checkGenericType(listType, String.class)) {
intent.putStringArrayListExtra(key, list);
} else if (checkGenericType(listType, Integer.class)) {
intent.putIntegerArrayListExtra(key, list);
} else if (checkGenericType(listType, CharSequence.class)) {
intent.putCharSequenceArrayListExtra(key, list);
} else if (checkGenericType(listType, o.getClass())) {
intent.putParcelableArrayListExtra(key, list);
}
}
}
if (needReturnIntent) {
return intent;
} else if (method.getReturnType() == BaseIntent.class) {
return new BaseIntent(intent);
}
return null;
}
static class ParamHolder {
String key;
int index;
Type genericType;
ParamHolder(Annotation[] annotations, int index, Type type) {
for (Annotation a : annotations) {
if (a instanceof IntentParam) {
IntentParam param = (IntentParam) a;
this.key = param.value();
break;
}
}
this.index = index;
this.genericType = type;
}
}
}
|
package com.jackpan.stockcomputer;
import android.app.Activity;
import android.util.Log;
import com.clickforce.ad.Listener.AdViewLinstener;
import com.google.ads.AdSize;
import com.google.ads.mediation.MediationAdRequest;
import com.google.ads.mediation.customevent.CustomEventBanner;
import com.google.ads.mediation.customevent.CustomEventBannerListener;
/**
* Created by YaoChang on 2017/7/20.
*/
public class DMCustomAD implements CustomEventBanner {
private com.clickforce.ad.AdView ad;
@Override
public void destroy() {
if (ad != null)
ad.releaseAd();
}
@Override
public void requestBannerAd(final CustomEventBannerListener listener,
final Activity activity, String label, String serverParameter,
AdSize adSize, MediationAdRequest request, Object customEventExtra) {
Log.d("label", label);
Log.d("Parameter", serverParameter);
ad = new com.clickforce.ad.AdView(activity);
ad.getAd(Integer.parseInt(serverParameter),320,50,0.8);
listener.onReceivedAd(ad);
ad.setOnAdViewLoaded(new AdViewLinstener() {
@Override
public void OnAdViewLoadFail() {
}
@Override
public void OnAdViewLoadSuccess() {
ad.show();
}
});
}
}
|
package week4.homework;
public abstract class Glider extends Aircraft {
public Glider(int maxSpeed, String type) {
super(maxSpeed, type);
}
public void glide(){
System.out.println("Gliding");
}
}
|
package kr.co.people_gram.app;
/**
* Created by 광희 on 2015-09-27.
*/
public class MyFilling_data {
public static String filling_comment = "";
public MyFilling_data()
{
}
public void set_filling_comment(String comment)
{
this.filling_comment = comment;
}
public String get_fillng_comment() {
return this.filling_comment;
}
}
|
package jp.ne.kenichi.testutils.dbunit;
public class AssertionDBUnitException extends Exception {
public AssertionDBUnitException() {
super();
}
public AssertionDBUnitException(String arg0) {
super(arg0);
}
public AssertionDBUnitException(Exception e) {
super(e);
}
}
|
package pr.actions;
import java.net.URL;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.dialogs.InputDialog;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.IWorkbenchWindowActionDelegate;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.browser.IWebBrowser;
import org.eclipse.ui.browser.IWorkbenchBrowserSupport;
public class OpenDIRT implements IWorkbenchWindowActionDelegate
{
private IWorkbenchWindow window;
public OpenDIRT()
{
}
@Override
public void run(final IAction action)
{
InputDialog dialog = new InputDialog(window.getShell(), "DIRT Item", null, null, null);
int code = dialog.open();
if (code == InputDialog.OK)
{
String dirtId = dialog.getValue();
String url = "https://dirt.cville.northgrum.com/view.php?id=" + dirtId;
openInBrowser(url);
}
}
private void openInBrowser(String url)
{
IWorkbench workbench = PlatformUI.getWorkbench();
try
{
IWorkbenchBrowserSupport browserSupport = workbench.getBrowserSupport();
IWebBrowser browser;
if (browserSupport.isInternalWebBrowserAvailable())
browser = browserSupport.createBrowser(this.getClass().getName()); // internal browser
else
browser = browserSupport.getExternalBrowser(); // external browser
browser.openURL(new URL(url));
}
catch (Exception x)
{
x.printStackTrace();
}
}
@Override
public void init(final IWorkbenchWindow w)
{
this.window = w;
}
@Override
public void dispose()
{
}
@Override
public void selectionChanged(IAction arg0, ISelection arg1)
{
}
}
|
package com.stk123.web.core.config;
import java.io.Serializable;
import java.util.HashMap;
public class MvcConfig implements Serializable {
protected String prefix = null;
protected HashMap<String,ForwardConfig> forwards = new HashMap<String,ForwardConfig>();
protected HashMap<String,ActionConfig> actions = new HashMap<String,ActionConfig>();
public String getPrefix() {
return prefix;
}
public void setPrefix(String prefix) {
this.prefix = prefix;
}
public HashMap<String,ActionConfig> getActions() {
return actions;
}
public void addActionConfig(ActionConfig action) {
this.actions.put(action.getPath(), action);
}
public HashMap<String,ForwardConfig> getForwards() {
return forwards;
}
public void addForward(ForwardConfig forward){
this.forwards.put(forward.getName(), forward);
}
}
|
package com.lidaye.shopIndex.domain.entity;
import lombok.Data;
import java.io.Serializable;
@Data
public class SubMenu1 implements Serializable {
private Integer subMenu1Id;
private String subMenu1Name;
private Integer categoryId;
}
|
package learn.sprsec.ssia0504form;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class Ssia0504formApplicationTests {
@Test
void contextLoads() {
}
}
|
package assertj.examples;
import java.util.Comparator;
public class Person implements Comparator<Person>{
public String name;
public double height;
public Home home = new Home();
public Person bestFriend;
public Person() {
super();
}
public Person(String name, double height) {
this.name = name;
this.height = height;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getHeight() {
return height;
}
public void setHeight(double height) {
this.height = height;
}
public Home getHome() {
return home;
}
public void setHome(Home home) {
this.home = home;
}
public Person getBestFriend() {
return bestFriend;
}
public void setBestFriend(Person bestFriend) {
this.bestFriend = bestFriend;
}
public int compare(Person p1, Person p2) {
return p1.getName().compareTo(p2.getName());
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Person person = (Person) o;
if (Double.compare(person.height, height) != 0) return false;
if (name != null ? !name.equals(person.name) : person.name != null) return false;
if (home != null ? !home.equals(person.home) : person.home != null) return false;
return bestFriend != null ? bestFriend.equals(person.bestFriend) : person.bestFriend == null;
}
@Override
public int hashCode() {
int result;
long temp;
result = name != null ? name.hashCode() : 0;
temp = Double.doubleToLongBits(height);
result = 31 * result + (int) (temp ^ (temp >>> 32));
result = 31 * result + (home != null ? home.hashCode() : 0);
result = 31 * result + (bestFriend != null ? bestFriend.hashCode() : 0);
return result;
}
}
|
package com.androidcorpo.lindapp.activities;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.androidcorpo.lindapp.Constant;
import com.androidcorpo.lindapp.LindAppUtils;
import com.androidcorpo.lindapp.R;
import com.androidcorpo.lindapp.elipticurve.EEC;
import com.androidcorpo.lindapp.model.MyKey;
import com.androidcorpo.lindapp.network.ApiClient;
import com.androidcorpo.lindapp.network.ApiInterface;
import com.androidcorpo.lindapp.network.response.PublicKeyResponse;
import com.androidcorpo.lindapp.resources.LindAppDbHelper;
import java.io.IOException;
import java.security.KeyPair;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class MainActivity extends AppCompatActivity {
int progressbarstatus = 0;
private Handler progressBarbHandler = new Handler();
private String myNumber;
private SharedPreferences pref;
private LindAppDbHelper lindAppDbHelper;
private ProgressBar pb;
private Context context;
private LinearLayout loginForm;
private Button button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
pref = getApplicationContext().getSharedPreferences(Constant.PREFERENCE, 0); // 0 - for private mode
context = this;
setContentView(R.layout.activity_main);
loginForm = findViewById(R.id.linear);
pb = findViewById(R.id.progressBar);
lindAppDbHelper = LindAppDbHelper.getInstance(this);
button = findViewById(R.id.save_contact);
final EditText editText = findViewById(R.id.my_contact);
if (pref.contains(Constant.MY_CONTACT)) {
loginForm.setVisibility(View.GONE);
animateProgressBar(pb);
} else {
pb.setVisibility(View.GONE);
loginForm.setVisibility(View.VISIBLE);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
myNumber = editText.getText().toString();
String cleanNumber = LindAppUtils.getCleanAdress(myNumber);
if (cleanNumber.isEmpty()) {
editText.setError("Please enter you number");
} else {
MyKey savedKey = null;
try {
savedKey = lindAppDbHelper.findByContact(cleanNumber);
} catch (IOException e) {
e.printStackTrace();
}
if (savedKey == null) {
KeyPair keyPair = EEC.keyGeneration();
MyKey myKey = new MyKey(cleanNumber, keyPair.getPrivate(), keyPair.getPublic());
try {
lindAppDbHelper.saveKey(myKey);
} catch (IOException e) {
e.printStackTrace();
}
postPublicKey(myKey);
}
}
}
});
}
}
private void animateProgressBar(final ProgressBar pb) {
new Thread(new Runnable() {
@Override
public void run() {
while (progressbarstatus < 100) {
progressbarstatus = progressbarstatus + 50;
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
progressBarbHandler.post(new Runnable() {
public void run() {
pb.setProgress(progressbarstatus);
}
});
}
if (progressbarstatus >= 100) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
finish();
Intent i = new Intent(context, MessagesActivity.class);
startActivity(i);
}
}
}).start();
}
private void postPublicKey(final MyKey key) {
pb.setVisibility(View.VISIBLE);
pb.setIndeterminate(true);
byte[] bytes = LindAppUtils.publicKeyToStream(key.getPublicKey());
ApiInterface apiService = ApiClient.getClient().create(ApiInterface.class);
Call<PublicKeyResponse> call = apiService.create(key.getContact(), EEC.bytesToHex(bytes));
call.enqueue(new Callback<PublicKeyResponse>() {
@Override
public void onResponse(Call<PublicKeyResponse> call, Response<PublicKeyResponse> response) {
pb.setIndeterminate(false);
pb.setVisibility(View.INVISIBLE);
PublicKeyResponse keyResponse = response.body();
if (response.isSuccessful() && keyResponse.getCode() == 200) {
savePreference(key.getContact());
Toast.makeText(context, " public key shared ok!!", Toast.LENGTH_LONG).show();
finish();
Intent i = new Intent(context, MessagesActivity.class);
context.startActivity(i);
} else {
Toast.makeText(context, " Request post fail -- Public Key -- ", Toast.LENGTH_LONG).show();
restartAct();
}
}
@Override
public void onFailure(Call<PublicKeyResponse> call, Throwable t) {
Toast.makeText(context, " Failed to post public key make sure you are connected", Toast.LENGTH_LONG).show();
loginForm.setVisibility(View.VISIBLE);
pb.setVisibility(View.INVISIBLE);
restartAct();
}
});
}
private void restartAct() {
Intent intent = getIntent();
finish();
startActivity(intent);
}
private void savePreference(String myContact) {
SharedPreferences.Editor editor = pref.edit();
editor.putString(Constant.MY_CONTACT, myContact);
editor.apply();
}
}
|
/*
* Application: Credit Card Management Service
*/
package com.mcp.ccard.service;
import org.springframework.http.ResponseEntity;
/**
* The Interface CreditCardMgmtService.
*/
public interface CreditCardMgmtService {
/**
* Find all credit card application by status.
*
* @param status the status
* @return the response entity
*/
public ResponseEntity<Object> findAllCreditCardApplicationByStatus(String status); ;
/**
* Process credit card application.
*
* @param applicationNumber the application number
* @return the response entity
* @throws Exception the exception
*/
public ResponseEntity<Object> processCreditCardApplication(String applicationNumber) throws Exception;
/**
* Find credit card application info.
*
* @param applicationNumber the application number
* @return the response entity
* @throws Exception the exception
*/
public ResponseEntity<Object> findCreditCardApplicationInfo(String applicationNumber)throws Exception;
/**
* Validate credit card application.
*
* @param applicationNumber the application number
* @return the response entity
* @throws Exception the exception
*/
public ResponseEntity<Object> validateCreditCardApplication(String applicationNumber) throws Exception;
}
|
package io.core9.plugin.widgets.datahandler;
import io.core9.core.boot.BootStrategy;
import io.core9.core.plugin.Core9Plugin;
import java.util.List;
public interface DataHandlerFactoryRegistry extends Core9Plugin, BootStrategy {
DataHandlerFactoryRegistry register(DataHandlerFactory<? extends DataHandlerFactoryConfig> factory);
DataHandlerFactoryRegistry register(String name, DataHandlerFactory<? extends DataHandlerFactoryConfig> factory);
DataHandlerFactory<? extends DataHandlerFactoryConfig> get(String name);
List<String> getDataHandlerFactories();
}
|
package com.ut.module_lock.dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.databinding.DataBindingUtil;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.View;
import com.ut.base.BaseDialog;
import com.ut.module_lock.R;
import com.ut.module_lock.databinding.DialogAddLockSuccessBinding;
import com.ut.module_lock.databinding.DialogUnlockSuccessBinding;
/**
* author : zhouyubin
* time : 2018/11/28
* desc :
* version: 1.0
*/
public class UnlockSuccessDialog extends BaseDialog {
private DialogUnlockSuccessBinding mBinding;
private Handler mHandler = null;
public UnlockSuccessDialog(Context context, boolean isShowTitle) {
super(context, isShowTitle);
initView();
mHandler = new Handler(Looper.getMainLooper()) {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
if (UnlockSuccessDialog.this.isShowing())
dismiss();
}
};
setTimout(3000);
setOnDismissListener(dialog -> mHandler.removeMessages(0));
}
public void setTimout(int timout) {
mHandler.sendEmptyMessageDelayed(0, timout);
}
private void initView() {
View view = getLayoutInflater().inflate(R.layout.dialog_unlock_success, null);
mBinding = DataBindingUtil.bind(view);
mBinding.iBtnClose.setOnClickListener(mOnClickListener);
setContentView(view);
}
private View.OnClickListener mOnClickListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
dismiss();
}
};
@Override
public void onDetachedFromWindow() {
super.onDetachedFromWindow();
mHandler.removeMessages(0);
}
}
|
package Sekcja6.Challenge.Challenge79;
public class Challenge79Constructors {
public static void main(String[] args) {
BankAccount bankAccount = new BankAccount();
bankAccount.setAccountNumber("12 2456 3333 3333 2222 1245 1245");
bankAccount.setCustomerName("Kornel W.");
bankAccount.setEmail("mlemmlem@mail.com");
bankAccount.setPhoneNumber("555-12-34-56");
BankAccount bobsAccount = new BankAccount("1234", 12.5, "Bob", "bob@email.com"," 12-432-4324-54");
System.out.println(bobsAccount.getAccountNumber());
System.out.println(bobsAccount.getCustomerName());
System.out.println(bobsAccount.getEmail());
System.out.println(bobsAccount.getPhoneNumber());
System.out.println(bobsAccount.getBalance());
System.out.println("-----------------------------");
System.out.println(bankAccount.getCustomerName());
System.out.println(bankAccount.getEmail());
System.out.println(bankAccount.getPhoneNumber());
System.out.println(bankAccount.getAccountNumber());
System.out.println("-------------------------------");
bankAccount.depositFunds(2000.49);
bankAccount.depositFunds(123);
//System.out.println(bankAccount.getBalance());
bankAccount.withdrawFunds(2123.49);
bankAccount.withdrawFunds(1);
}
}
|
package RegularProgramming;
import java.util.Scanner;
public class FibonacciWithRecurrsion {
public static void main(String arg[]){
Scanner sc=new Scanner(System.in);
System.out.println("Enter value");
System.out.println("Result --> "+ calculateFibonacci(sc.nextInt()));
}
private static int calculateFibonacci(int input){
int result=0;
if(input==1| input==2){
result =1;
}
else
result=calculateFibonacci(input-1)+calculateFibonacci(input-2);
return result;
}
}
|
package com.mod.loan.model.DTO;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import java.io.Serializable;
import java.util.List;
/**
* loan-pay 2019/4/22 huijin.shuailijie Init
*/
@Getter
@Setter
@ToString
@JsonIgnoreProperties(ignoreUnknown = true)
public class DecisionExecuteResDTO implements Serializable {
@JsonProperty("decision_no")
private String decision_no;
@JsonProperty("trans_id")
private String trans_id;
@JsonProperty("order_money")
private Long order_money;
@JsonProperty("orderStatus")
private String orderStatus;
@JsonProperty("fee")
private boolean fee;
@JsonProperty("code")
private String code;
@JsonProperty("desc")
private String desc;
@JsonProperty("res_score")
private Double res_score;
@JsonProperty("strategies")
private List<StrategyDTO> strategies;
}
|
package Sekcja5.Exercises;
public class Exercise18SharedDigit {
public static boolean hasSharedDigit(int numberOne, int numberTwo){
if ((numberOne < 10 || numberOne > 99) || (numberTwo < 10 || numberTwo > 99)){
return false;
}
int firstDigit = numberOne / 10;
int secondDigit = numberOne % 10;
int thirdDigit = numberTwo / 10;
int fourthDigit = numberTwo % 10;
return (firstDigit == thirdDigit) || (secondDigit == fourthDigit) || (firstDigit == fourthDigit) || (secondDigit == thirdDigit);
}
public static void main(String[] args) {
System.out.println(hasSharedDigit(9,99));
System.out.println(hasSharedDigit(99,9));
System.out.println(hasSharedDigit(10,99));
System.out.println(hasSharedDigit(11,21));
}
}
|
package lib.hyxen.ui;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentManager;
import android.view.View;
import java.util.Calendar;
/**
* Created by redjack on 15/6/18.
*/
public class SimplePicker extends DialogFragment implements AlertDialog.OnClickListener {
PickerType type;
TimePickerDialog.OnTimeSetListener timeSetListener;
DatePickerDialog.OnDateSetListener dateSetListener;
DialogInterface.OnClickListener onClickListener;
CustomViewReactListener reactListener;
String title;
String[] options;
View customView;
static public void showTimePicker(FragmentManager fragmentManager, String title, TimePickerDialog.OnTimeSetListener timeSetListener)
{
SimplePicker picker = new SimplePicker();
picker.title = title;
picker.type = PickerType.Time;
picker.timeSetListener = timeSetListener;
picker.show(fragmentManager, SimplePicker.class.toString());
}
static public void showDatePicker(FragmentManager fragmentManager, String title, DatePickerDialog.OnDateSetListener dateSetListener)
{
SimplePicker picker = new SimplePicker();
picker.title = title;
picker.type = PickerType.Date;
picker.dateSetListener = dateSetListener;
picker.show(fragmentManager, SimplePicker.class.toString());
}
static public void showOptionPicker(FragmentManager fragmentManager, String title, String[] options, DialogInterface.OnClickListener onClickListener)
{
SimplePicker picker = new SimplePicker();
picker.title = title;
picker.options = options;
picker.type = PickerType.Options;
picker.onClickListener = onClickListener;
picker.show(fragmentManager, SimplePicker.class.toString());
}
/**
* Will have cancel and confirm button.
*/
static public void showCustomPicker(FragmentManager fragmentManager, String title, View customView, CustomViewReactListener listener)
{
SimplePicker picker = new SimplePicker();
picker.title = title;
picker.type = PickerType.Custom;
picker.customView = customView;
picker.reactListener = listener;
picker.show(fragmentManager, SimplePicker.class.toString());
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
Dialog dialog = null;
switch (type)
{
case Date: dialog = datePicker(title, dateSetListener); break;
case Time: dialog = timePicker(title, timeSetListener); break;
case Options: dialog = optionDialog(title, options, onClickListener); break;
case Custom: dialog = customDialog(title, customView);
}
return dialog;
}
public DatePickerDialog datePicker(String title, DatePickerDialog.OnDateSetListener dateSetListener)
{
Calendar calendar = Calendar.getInstance();
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH);
int day = calendar.get(Calendar.DAY_OF_MONTH);
DatePickerDialog picker = new DatePickerDialog(getActivity(), dateSetListener, year, month, day);
picker.setTitle(title);
return picker;
}
public TimePickerDialog timePicker(String title, TimePickerDialog.OnTimeSetListener timeSetListener)
{
Calendar calendar = Calendar.getInstance();
int hour = calendar.get(Calendar.HOUR_OF_DAY);
int minute = calendar.get(Calendar.MINUTE);
TimePickerDialog picker = new TimePickerDialog(getActivity(), timeSetListener, hour, minute, true);
picker.setTitle(title);
return picker;
}
public AlertDialog optionDialog(String title, String[] options, DialogInterface.OnClickListener resultListener)
{
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setItems(options, resultListener);
builder.setTitle(title);
return builder.create();
}
public AlertDialog customDialog(String title, View customView)
{
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setView(customView);
builder.setTitle(title);
builder.setPositiveButton(getString(android.R.string.ok), this);
builder.setNegativeButton(getString(android.R.string.cancel), this);
return builder.create();
}
@Override
public void onClick(DialogInterface dialog, int which) {
if (reactListener == null) return;
if (which == -2) reactListener.onDialogCancel(customView);
else if (which == -1) reactListener.onDialogConfirm(customView);
}
public interface CustomViewReactListener
{
public void onDialogCancel(View customView);
public void onDialogConfirm(View customView);
}
public enum PickerType
{
Time, Date, Options, Custom;
}
}
|
package com.lmz;
public class HeapandStack {
public static void main(String[] args) {
//第一种使用new来创建的对象,它存放在堆中。每调用一次就创建一个新的对象。
String str1 = new String("abc");
String str2 = new String("abc");
System.out.println(str1 == str2);
//第二种是先在栈中创建对象的引用str2,然后查找栈中有没有存放“abc”,如果没有,则将“abc”存放进栈,并将str2指向“abc”,如果已经有“abc”, 则直接将str2指向“abc”。
String str3 = "abc";
String str4 = "abc";
System.out.println(str3 == str4);
System.out.println(str1 == str3);
}
}
|
package com.ua.dekhtiarenko.webapp.db.dao.classes;
import com.ua.dekhtiarenko.webapp.db.connection.DBManager;
import com.ua.dekhtiarenko.webapp.db.dao.constant.Request;
import com.ua.dekhtiarenko.webapp.db.dao.interfaces.UserDAO;
import com.ua.dekhtiarenko.webapp.db.entity.User;
import org.apache.log4j.Logger;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Dekhtiarenko-Daniil on 25.02.2021.
*/
public class UserDAOImpl implements UserDAO {
private final Logger logger = Logger.getLogger(UserDAOImpl.class);
private static Connection connection = null;
private static PreparedStatement preparedStatement = null;
private static ResultSet rs = null;
/**
* Insert user.
*
* @param user
*/
@Override
public void insertUser(User user) {
logger.info("Start insertUser");
try {
connection = DBManager.getConnection();
preparedStatement = connection.prepareStatement(Request.INSERT_INTO_USER);
preparedStatement.setString(1, user.getEmail());
preparedStatement.setString(2, user.getName());
preparedStatement.setString(3, user.getSurname());
preparedStatement.setBoolean(4, user.getLibrarian());
preparedStatement.setBoolean(5, user.getAdmin());
preparedStatement.setBoolean(6, user.getBlocked());
preparedStatement.setString(7, user.getPassword());
preparedStatement.executeUpdate();
} catch (SQLException sqlException) {
Logger.getLogger(sqlException.getMessage());
} finally {
closing(connection, preparedStatement, rs);
}
logger.info("Finished insertUser");
}
/**
* Return user by id.
*
* @param id
* @return user.
*/
@Override
public User getUserById(int id) {
logger.info("Start getUserById");
User user = new User();
try {
connection = DBManager.getConnection();
preparedStatement = connection.prepareStatement(Request.GET_USER_BY_ID);
preparedStatement.setInt(1, id);
rs = preparedStatement.executeQuery();
if (rs.next()) {
user.setId(rs.getInt("id_user"));
user.setEmail(rs.getString("email"));
user.setName(rs.getString("name"));
user.setSurname(rs.getString("surname"));
user.setLibrarian(rs.getBoolean("librarian"));
user.setAdmin(rs.getBoolean("admin"));
user.setBlocked(rs.getBoolean("blocked"));
user.setPassword(rs.getString("password"));
}
} catch (SQLException sqlException) {
Logger.getLogger(sqlException.getMessage());
} finally {
closing(connection, preparedStatement, rs);
}
logger.info("Finished getUserById");
return user;
}
/**
* Update user.
*
* @param user
*/
@Override
public void updateUser(User user) {
logger.info("Start updateUser");
try {
connection = DBManager.getConnection();
preparedStatement = connection.prepareStatement(Request.UPDATE_USER_NAME_SURNAME_PASS);
preparedStatement.setString(1, user.getName());
preparedStatement.setString(2, user.getSurname());
preparedStatement.setString(3, user.getPassword());
preparedStatement.setInt(4, user.getId());
preparedStatement.executeUpdate();
} catch (SQLException sqlException) {
Logger.getLogger(sqlException.getMessage());
} finally {
closing(connection, preparedStatement, rs);
}
logger.info("Finished updateUser");
}
/**
* Update user.
*
* @param user_id
*/
@Override
public void updateUser(User user, int user_id) {
logger.info("Start updateUser");
try {
connection = DBManager.getConnection();
preparedStatement = connection.prepareStatement(Request.UPDATE_USER);
preparedStatement.setString(1, user.getName());
preparedStatement.setString(2, user.getSurname());
preparedStatement.setBoolean(3, user.getLibrarian());
preparedStatement.setBoolean(4, user.getAdmin());
preparedStatement.setBoolean(5, user.getBlocked());
preparedStatement.setInt(6, user_id);
preparedStatement.executeUpdate();
} catch (SQLException sqlException) {
Logger.getLogger(sqlException.getMessage());
} finally {
closing(connection, preparedStatement, rs);
}
logger.info("Finished updateUser");
}
/**
* Return list of user.
*
* @return userList.
*/
@Override
public List<User> getUserList() {
logger.info("Start getUserList");
List<User> userList = new ArrayList<>();
try {
connection = DBManager.getConnection();
preparedStatement = connection.prepareStatement(Request.SELECT_FROM_USER);
rs = preparedStatement.executeQuery();
while (rs.next()) {
userList.add(readingResultSet(rs));
}
} catch (SQLException sqlException) {
Logger.getLogger(sqlException.getMessage());
} finally {
closing(connection, preparedStatement, rs);
}
logger.info("Finished getUserList");
return userList;
}
/**
* Returns book by resultSet.
*
* @param resultSet
* @return subscription book.
*/
@Override
public User readingResultSet(ResultSet resultSet) {
logger.info("Start readingResultSet");
User user = new User();
try {
user.setId(resultSet.getInt("id_user"));
user.setEmail(resultSet.getString("email"));
user.setName(resultSet.getString("name"));
user.setSurname(resultSet.getString("surname"));
user.setLibrarian(resultSet.getBoolean("librarian"));
user.setAdmin(resultSet.getBoolean("admin"));
user.setBlocked(resultSet.getBoolean("blocked"));
user.setPassword(resultSet.getString("password"));
} catch (SQLException sqlException) {
Logger.getLogger(sqlException.getMessage());
}
logger.info("Finished readingResultSet");
return user;
}
/**
* Return user id by email.
*
* @param email
* @return id
*/
@Override
public int getUserIdByEmail(String email) {
logger.info("Start getUserIdByEmail");
int id = 0;
try {
connection = DBManager.getConnection();
preparedStatement = connection.prepareStatement(Request.GET_ID_BY_EMAIL);
preparedStatement.setString(1, email);
rs = preparedStatement.executeQuery();
if (rs.next()) {
id = rs.getInt("id_user");
}
} catch (SQLException sqlException) {
Logger.getLogger(sqlException.getMessage());
} finally {
closing(connection, preparedStatement, rs);
}
logger.info("Finished getUserIdByEmail");
return id;
}
/**
* Return true or false auntification.
*
* @param name
* @return status
*/
@Override
public boolean exists(String name, String pass) {
logger.info("Start exists");
boolean status = false;
try {
connection = DBManager.getConnection();
preparedStatement = connection.prepareStatement(Request.VALIDATION_OF_USER);
preparedStatement.setString(1, name);
preparedStatement.setString(2, pass);
rs = preparedStatement.executeQuery();
status = rs.next();
} catch (Exception e) {
Logger.getLogger(e.getMessage());
}
logger.info("Finished exists");
return status;
}
/**
* Closes resources.
*/
@Override
public void closing(Connection connection, PreparedStatement preparedStatement, ResultSet rs) {
logger.info("Start closing");
try {
if (rs != null) {
rs.close();
preparedStatement.close();
connection.close();
}
} catch (SQLException sqlException) {
Logger.getLogger(sqlException.getMessage());
}
logger.info("Finished closing");
}
}
|
package de.lezleoh.mathgame.term;
import java.util.ArrayList;
public class TermQueue {
ArrayList<TermInt> terms;
int counter;
public TermQueue() {
super();
terms = new ArrayList<TermInt>();
counter = 0;
}
public void addTerm(TermInt term) {
terms.add(term);
}
public void removeTerm() {
if (!terms.isEmpty()) {
terms.remove(0);
}
}
public TermInt getNextTerm() {
counter++;
if (counter >= terms.size()) {
counter = 0;
}
if (!terms.isEmpty()) {
return terms.get(counter);
} else {
return new Number(new Integer(0));
}
}
public static TermInt randomTerm(int depth) {
//TODO construct random Term instead of fix term
Number summand11 = new Number(11);
Number summand12 = new Number(12);
Number summand13 = new Number(13);
Number summand21 = new Number(21);
Number summand22 = new Number(22);
Sum sum1 = new Sum();
Sum sum2 = new Sum();
sum1.addOperand(summand11);
sum1.addOperand(summand12);
sum1.addOperand(sum2);
sum1.addOperand(summand13);
sum2.addOperand(summand21);
sum2.addOperand(summand22);
return sum1;
}
}
|
/**
*
*/
package com.fixit.core.data.sql;
import java.util.Date;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
/**
* @author Kostyantin
* @createdAt 2017/06/01 16:24:41 GMT+3
*/
@Entity
@Table(name = "JobReason")
public class JobReason implements UpdateDateSqlModelObject<Integer> {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private Integer professionId;
private String name;
private String comment;
@Temporal(TemporalType.TIMESTAMP)
private Date updatedAt;
@Override
public Integer getId() {
return id;
}
@Override
public void setId(Integer id) {
this.id = id;
}
public Integer getProfessionId() {
return professionId;
}
public void setProfessionId(Integer professionId) {
this.professionId = professionId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getComment() {
return comment;
}
public void setComment(String comment) {
this.comment = comment;
}
public Date getUpdatedAt() {
return updatedAt;
}
public void setUpdatedAt(Date updatedAt) {
this.updatedAt = updatedAt;
}
@Override
public String toString() {
return "JobReason [id=" + id + ", professionId=" + professionId + ", name=" + name + ", comment=" + comment
+ ", updatedAt=" + updatedAt + "]";
}
}
|
package com.redpantssoft.cloudtodolist.client;
import android.accounts.Account;
import android.accounts.AccountManager;
import android.accounts.AccountManagerFuture;
import android.accounts.AuthenticatorException;
import android.accounts.OperationCanceledException;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import org.apache.http.HttpResponse;
import org.apache.http.ProtocolException;
import org.apache.http.auth.AuthenticationException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.client.params.ClientPNames;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.DefaultHttpClient;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
/**
* Implementation of a RestAuthenticator for Google App Engine hosted
* rest services.
* Authenticating with GAE follows these steps:
* <p/>
* 1. Request an auth token for the specified account using getAuthToken. Construction
* of the Authenticator requires the account object obtained from the Android AccountManager.
* Its up to the application to determine which account to use. The token generation is
* handled by the Android Google Authenticator, which also stores user credentials.
* <p/>
* 2. Make a login request using the auth token. All GAE apps have a login URI, relative to
* the app's URI, to login to google accounts. Specifying an authtoken in the query string
* will allow for non-interactive logins and does not require the credentials to be passed
* to the service.
* <p/>
* 3. If the request fails, it could be that the cached auth token is stale or the server
* not longer supports tokens of that type. The authenticator will call invalidateToken and
* attempt to get a fresh token from the AccountManager and retry the login operation.
*/
public class GaeAuthenticator implements HttpRestAuthenticator {
// Log Tag
private static final String TAG = "GaeAuthenticator";
// String representing the auth token type for GAE apps
private static final String authTokenType = "ah";
// String representing the auth cookie return for GAE apps logins
private String authCookieName = "ACSID";
// Login path for GAE app urls
private static final String ENTRIES_PATH = "/_ah/login";
// Reference to the system AccountManager
private final AccountManager accountManager;
// Account to use for authentication requests
private final Account account;
/**
* Constructor
*
* @param context context
* @param account account to use for authentication
*/
public GaeAuthenticator(Context context, Account account) {
this.accountManager = AccountManager.get(context);
this.account = account;
}
/**
* Handles requests to login to a Rest service.
* For Google App Engine Apps, the login is via an auth token. The
* Android Google Authenticator is capable of storing user credentials
* and requesting an auth token, so this request needs to validate the
* auth token by logging in and setting a auth cookie for all subsequent
* requests
*
* @param client HttpClient object to login with
* @param scheme scheme portion of the login uri for the GAE app
* @param authority authority scheme portion of the login uri for the GAE app
*/
@Override
public void login(final DefaultHttpClient client, final String scheme, final String authority)
throws AuthenticationException, IOException, URISyntaxException {
try {
String token = getAuthToken();
if (!loginWithAuthToken(client, token, scheme, authority)) {
invalidateAuthToken(token);
token = getAuthToken();
if (!loginWithAuthToken(client, token, scheme, authority)) {
String msg = "Server error during login, Invalid Credentials: " + account.name + "(" + account.type + ")";
Log.e(TAG, msg);
throw new IOException(msg);
}
}
} catch (OperationCanceledException e) {
Log.e(TAG, "login, operation cancelled: " + e.toString());
throw new AuthenticationException("login operation cancelled", e);
} catch (AuthenticatorException e) {
Log.e(TAG, "login, authenticator error: " + e.toString());
throw new AuthenticationException("authenticator error", e);
} catch (ProtocolException e) {
Log.e(TAG, "login, authentication error: " + e.toString());
throw new AuthenticationException("authentication error", e);
}
}
/**
* Handles authenticating each Rest operation.
* In the case of Google App Engine, all requests are authenticated
* with a auth cookie returned from login, so nothing to do here.
*
* @param request http request to add authentication info to
*/
@Override
public void addAuthenticationInfoToRequest(HttpRequestBase request) {
// nothing to do, the request is authenticated in the cookie
// returned from the login
}
/**
* Requests an auth token for the specified authenticator account
*
* @return authentication token
* @throws IOException usually because of network trouble
* @throws AuthenticatorException if the authenticator failed to respond
* @throws OperationCanceledException if the operation is canceled for any reason,
* incluidng the user canceling a credential request
*/
private String getAuthToken() throws IOException, AuthenticatorException, OperationCanceledException {
AccountManagerFuture<Bundle> result = accountManager.getAuthToken(
account, authTokenType, true, null, new Handler());
Bundle bundle = result.getResult();
return bundle.getString(AccountManager.KEY_AUTHTOKEN);
}
/**
* Invalidates a previously returned auth token.
* This will instruct the AccountManager to clear the token out of its cache
* and subsequent calls to getAuthToken will result in a new token being generated
*
* @param token stale auth token to invalidate
*/
private void invalidateAuthToken(String token) {
accountManager.invalidateAuthToken(account.type, token);
}
/**
* This will issue a login request, using a previously issued auth token.
* All GAE apps have a login URI relative the application URI. This routine will
* build that URI an attempt to login with the specified auth token. If it succeeds,
* the http client will have a GAE authentication cookie (ACSID) in its store. All
* subsequent requests will use the cookie to authenticate the request
*
* @param client HttpClient to use for login request
* @param authToken token to use for login operation
* @param scheme scheme portion of the login uri for the GAE app
* @param authority authority portion of the login uri for the GAE app
* @return true if the login succeeded, false if an authentication error occurred and the
* token may be stale
*/
private boolean loginWithAuthToken(DefaultHttpClient client, String authToken, String scheme, String authority)
throws ProtocolException, URISyntaxException, IOException {
/**
* Don't follow redirects, once the login is complete, a redirect to the
* the "continue" param in the query string, will be issued. Just ignore it
* and use it as an indication of success
*/
client.getParams().setBooleanParameter(ClientPNames.HANDLE_REDIRECTS, false);
HttpGet request = new HttpGet();
// Build the login URI, for the specified scheme and authority
request.setURI(new URI(scheme,
authority,
ENTRIES_PATH,
"continue=http://localhost/&auth=" + authToken,
null)
);
HttpResponse response = client.execute(request);
// Response should be a redirect on success
if (response.getStatusLine().getStatusCode() == 302) {
// The secure cookies are specific to the secure connection, and are
// prefixed by and S
if (scheme.equals("https"))
authCookieName = "S" + authCookieName;
for (Cookie cookie : client.getCookieStore().getCookies()) {
if (cookie.getName().equals(authCookieName))
return true;
}
return false;
}
return false;
}
}
|
package net.tascalate.async.examples.bank;
import static net.tascalate.async.api.AsyncCall.asyncResult;
import static net.tascalate.async.api.AsyncCall.await;
import java.math.BigDecimal;
import java.util.Date;
import java.util.concurrent.CompletionStage;
import net.tascalate.async.api.async;
import net.tascalate.async.examples.bank.FraudDetectionService.Result;
public class MoneyWithdrawalTask {
private BankAccount bankAccount;
private FraudDetectionService fraudDetectionService = new FraudDetectionService();
private AccountTransactionService accountTransactionService = new AccountTransactionService();
public MoneyWithdrawalTask(final BankAccount bankAccount) {
this.bankAccount = bankAccount;
}
private static String timeStamp(final String s) {
return new Date() + ": " + s;
}
private String formatOutput(final String operation) {
return "Transfer [" + operation + "] to/from bank account #" + bankAccount.accountNumber;
}
@async public CompletionStage<String> execute(final BigDecimal amount) throws InterruptedException {
class DemoPrint {
@async CompletionStage<Integer> go() {
System.out.println("Inner Class " + amount + " " + MoneyWithdrawalTask.this);
return asyncResult(10);
}
}
try {
await(
new DemoPrint().go()
);
final FraudDetectionService.Result fraudCheckResult = await(fraudDetectionService.checkFraud(bankAccount, amount));
final BigDecimal currentBalance = await(accountTransactionService.withdraw(bankAccount, amount));
if (fraudCheckResult == Result.DENY) {
throw new IllegalStateException("Fraud detected");
}
return asyncResult(timeStamp(formatOutput("withdraw")) + ": success, balance is " + currentBalance);
} catch (final InsufficientFundsException ex) {
return asyncResult(timeStamp(formatOutput("withdraw")) + ": failed, insufficient funds (" + bankAccount.amount + ")");
}
}
}
|
//Example to show how to extend interface in java
//Defining interface (style) named A
interface A{
void Adisp();
}
//Defining interface (style) named B
interface B extends A{
void Bdisp();
}
//Defining class that implemented interface (style)A
class C implements A{
public void Adisp(){
System.out.println("Style1 interface A implemented by class");
}
public void Bdisp(){
System.out.println("Style1 interface B implemented by class");
}
}//close of implemented class
class Extends{
public static void main(String args[]){
C ob=new C();
ob.Adisp();
ob.Bdisp();
}//close of main
}//close of main class
|
public class ExpressLoveException extends RuntimeException{
public ExpressLoveException(){
super("Fail to express love");
}
}
|
/*package com.bnrc.busapp;
import java.util.Calendar;
import org.json.JSONObject;
import android.app.ActionBar.LayoutParams;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;
import cn.domob.android.ads.AdEventListener;
import cn.domob.android.ads.AdView;
import cn.domob.android.ads.AdManager.ErrorCode;
import com.ab.activity.AbActivity;
import com.ab.global.AbConstant;
import com.ab.view.titlebar.AbTitleBar;
import com.ab.view.wheel.AbWheelAdapter;
import com.ab.view.wheel.AbWheelView;
import com.bnrc.busapp.R;
import com.bnrc.util.collectwifi.BaseActivity;
import com.umeng.analytics.MobclickAgent;
import com.umeng.analytics.onlineconfig.UmengOnlineConfigureListener;
import com.umeng.fb.FeedbackAgent;
import com.umeng.socialize.controller.UMSocialService;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.controller.UMServiceFactory;
import com.umeng.socialize.sso.QZoneSsoHandler;
import com.umeng.socialize.sso.SinaSsoHandler;
import com.umeng.socialize.sso.UMQQSsoHandler;
import com.umeng.socialize.weixin.controller.UMWXHandler;
public class UserSettingView extends BaseActivity {
private View selectSexView = null;
private View selectAgeView = null;
private TextView ageTextView = null;
private TextView sexTextView = null;
private View mAvatarView = null;
private String sexArr[] = { "男", "女" };
private String ageArr[] = { "1", "2", "3", "4", "5", "6", "7", "8", "9",
"10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20",
"21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31",
"32", "33", "34", "35", "36", "37", "38", "39", "40", "41", "42",
"43", "44", "45", "46", "47", "48", "49", "50", "51", "52", "53",
"54", "55", "56", "57", "58", "59", "60", "61", "62", "63", "64",
"65", "66", "67", "68", "68", "70", "71", "72", "73", "74", "75",
"76", "77", "78", "79", "80", "81", "82", "83", "84", "85", "86",
"87", "88", "89", "90", "91", "92", "93", "94", "95", "96", "97",
"98", "99", "100" };
RelativeLayout mAdContainer;
AdView mAdview;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setAbContentView(R.layout.user_setting_view);
AbTitleBar mAbTitleBar = this.getTitleBar();
mAbTitleBar.setTitleText("用户设置");
mAbTitleBar.setLogo(R.drawable.button_selector_back);
mAbTitleBar.setTitleBarBackground(R.drawable.top_bg);
mAbTitleBar.setTitleBarGravity(Gravity.CENTER, Gravity.CENTER);
initbase();
MobclickAgent.updateOnlineConfig(this);
MobclickAgent
.setOnlineConfigureListener(new UmengOnlineConfigureListener() {
@Override
public void onDataReceived(JSONObject data) {
}
});
String value = MobclickAgent.getConfigParams(UserSettingView.this,
"open_ad");
if (value.equals("1")) {
mAdContainer = (RelativeLayout) findViewById(R.id.adcontainer);
// Create ad view
mAdview = new AdView(this, "56OJzfwIuN7tr9LoSs",
"16TLmHWoAp8diNUdpuAEMYfi");
SharedPreferences mySharedPreferences = getSharedPreferences(
"setting", UserSettingView.MODE_PRIVATE);
String agString = mySharedPreferences.getString("userAge", "20");
String sexString = mySharedPreferences.getString("userSex", "女");
if (sexString.equals("女")) {
mAdview.setUserGender("female");
} else {
mAdview.setUserGender("male");
}
// mAdview.setKeyword("game");
Calendar mycalendar = Calendar.getInstance();// ��ȡ����ʱ��
String curYearString = String
.valueOf(mycalendar.get(Calendar.YEAR));// ��ȡ���
int age = Integer.parseInt(agString);
int birth = Integer.parseInt(curYearString) - age;
mAdview.setUserBirthdayStr(birth + "-08-08");
mAdview.setUserPostcode("123456");
mAdview.setAdEventListener(new AdEventListener() {
@Override
public void onAdOverlayPresented(AdView adView) {
Log.i("DomobSDKDemo", "overlayPresented");
}
@Override
public void onAdOverlayDismissed(AdView adView) {
Log.i("DomobSDKDemo", "Overrided be dismissed");
}
@Override
public void onAdClicked(AdView arg0) {
Log.i("DomobSDKDemo", "onDomobAdClicked");
}
@Override
public void onLeaveApplication(AdView arg0) {
Log.i("DomobSDKDemo", "onDomobLeaveApplication");
}
@Override
public Context onAdRequiresCurrentContext() {
return UserSettingView.this;
}
@Override
public void onAdFailed(AdView arg0, ErrorCode arg1) {
Log.i("DomobSDKDemo", "onDomobAdFailed");
}
@Override
public void onEventAdReturned(AdView arg0) {
Log.i("DomobSDKDemo", "onDomobAdReturned");
}
});
RelativeLayout.LayoutParams layout = new RelativeLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
layout.addRule(RelativeLayout.CENTER_HORIZONTAL);
mAdview.setLayoutParams(layout);
mAdContainer.addView(mAdview);
}
logoView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
// �����뾶ѡ����ѡ��Ľ���
selectSexView = mInflater.inflate(R.layout.choose_one, null);
// ���Ѿ���ѡ����ѡ��Ľ���
selectAgeView = mInflater.inflate(R.layout.choose_one, null);
sexTextView = (TextView) findViewById(R.id.sexTv);
ageTextView = (TextView) findViewById(R.id.ageTv);
// ʵ����SharedPreferences����һ����
SharedPreferences mySharedPreferences = getSharedPreferences("setting",
UserSettingView.MODE_PRIVATE);
ageTextView = (TextView) findViewById(R.id.ageTv);
ageTextView.setText(mySharedPreferences.getString("userAge", "20"));
sexTextView = (TextView) findViewById(R.id.sexTv);
sexTextView.setText(mySharedPreferences.getString("userSex", "女"));
sexTextView.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
showDialog(AbConstant.DIALOGBOTTOM, selectSexView, 40);
}
});
ageTextView.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
showDialog(AbConstant.DIALOGBOTTOM, selectAgeView, 40);
}
});
initWheelData1(selectSexView, sexTextView);
initWheelData2(selectAgeView, ageTextView);
}
// ��λ��ʾ����
public void initWheelData1(View mDataView, final TextView textView) {
final AbWheelView mWheelView1 = (AbWheelView) mDataView
.findViewById(R.id.wheelView1);
// mWheelView1.setAdapter(new AbNumericWheelAdapter(40, 190));
mWheelView1.setAdapter(new AbWheelAdapter() {
@Override
public int getMaximumLength() {
// TODO Auto-generated method stub
return sexArr.length;
}
@Override
public int getItemsCount() {
// TODO Auto-generated method stub
return sexArr.length;
}
@Override
public String getItem(int arg0) {
// TODO Auto-generated method stub
return sexArr[arg0];
}
});
// ��ѭ������
mWheelView1.setCyclic(false);
// �������
mWheelView1.setLabel(null);
// ��ʼ��ʱ��ʾ������
mWheelView1.setCurrentItem(40);
mWheelView1.setValueTextSize(35);
mWheelView1.setLabelTextSize(35);
mWheelView1.setLabelTextColor(0x80000000);
mWheelView1.setCenterSelectDrawable(this.getResources().getDrawable(
R.drawable.wheel_select));
Button okBtn = (Button) mDataView.findViewById(R.id.okBtn);
Button cancelBtn = (Button) mDataView.findViewById(R.id.cancelBtn);
okBtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
removeDialog(1);
int index = mWheelView1.getCurrentItem();
String val = mWheelView1.getAdapter().getItem(index);
textView.setText(val);
// ʵ����SharedPreferences����һ����
SharedPreferences mySharedPreferences = getSharedPreferences(
"setting", UserSettingView.MODE_PRIVATE);
// ʵ����SharedPreferences.Editor���ڶ�����
SharedPreferences.Editor editor = mySharedPreferences.edit();
// ��putString�����������
editor.putString("userSex", val);
// �ύ��ǰ����
editor.commit();
}
});
cancelBtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
removeDialog(1);
}
});
}
// ��λ��ʾ����
public void initWheelData2(View mDataView, final TextView textView) {
final AbWheelView mWheelView1 = (AbWheelView) mDataView
.findViewById(R.id.wheelView1);
// mWheelView1.setAdapter(new AbNumericWheelAdapter(40, 190));
mWheelView1.setAdapter(new AbWheelAdapter() {
@Override
public int getMaximumLength() {
// TODO Auto-generated method stub
return ageArr.length;
}
@Override
public int getItemsCount() {
// TODO Auto-generated method stub
return ageArr.length;
}
@Override
public String getItem(int arg0) {
// TODO Auto-generated method stub
return ageArr[arg0];
}
});
// ��ѭ������
mWheelView1.setCyclic(false);
// �������
mWheelView1.setLabel(null);
// ��ʼ��ʱ��ʾ������
mWheelView1.setCurrentItem(40);
mWheelView1.setValueTextSize(35);
mWheelView1.setLabelTextSize(35);
mWheelView1.setLabelTextColor(0x80000000);
mWheelView1.setCenterSelectDrawable(this.getResources().getDrawable(
R.drawable.wheel_select));
Button okBtn = (Button) mDataView.findViewById(R.id.okBtn);
Button cancelBtn = (Button) mDataView.findViewById(R.id.cancelBtn);
okBtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
removeDialog(1);
int index = mWheelView1.getCurrentItem();
String val = mWheelView1.getAdapter().getItem(index);
textView.setText(val);
// ʵ����SharedPreferences����һ����
SharedPreferences mySharedPreferences = getSharedPreferences(
"setting", UserSettingView.MODE_PRIVATE);
// ʵ����SharedPreferences.Editor���ڶ�����
SharedPreferences.Editor editor = mySharedPreferences.edit();
// ��putString�����������
editor.putString("userAge", val);
// �ύ��ǰ����
editor.commit();
}
});
cancelBtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
removeDialog(1);
}
});
}
public void onResume() {
super.onResume();
MobclickAgent.onPageStart("SplashScreen"); // ͳ��ҳ��
MobclickAgent.onResume(this); // ͳ��ʱ��
registerReceiver(mWifiReceiver, wifiFilter);
registerReceiver(mActivityReceiver, activityFilter);
}
public void onPause() {
super.onPause();
MobclickAgent.onPageEnd("SplashScreen"); // ��֤ onPageEnd ��onPause
// ֮ǰ����,��Ϊ onPause
// �лᱣ����Ϣ
MobclickAgent.onPause(this);
unregisterReceiver(mWifiReceiver);
unregisterReceiver(mActivityReceiver);
}
}
*/ |
/**
* Sencha GXT 3.0.1 - Sencha for GWT
* Copyright(c) 2007-2012, Sencha, Inc.
* licensing@sencha.com
*
* http://www.sencha.com/products/gxt/license/
*/
package com.sencha.gxt.desktopapp.client.utility;
import com.google.gwt.core.client.GWT;
import com.sencha.gxt.widget.core.client.Dialog;
import com.sencha.gxt.widget.core.client.Dialog.PredefinedButton;
import com.sencha.gxt.widget.core.client.box.AlertMessageBox;
import com.sencha.gxt.widget.core.client.box.ConfirmMessageBox;
import com.sencha.gxt.widget.core.client.event.HideEvent;
import com.sencha.gxt.widget.core.client.event.HideEvent.HideHandler;
public class PromptImpl extends Prompt {
/**
* Use a GWT.create() here to make it simple to hijack the default
* implementation.
*/
public static final Prompt INSTANCE = GWT.create(PromptImpl.class);
@Override
public void alert(String title, String text) {
alert(title, text, null);
}
@Override
public void alert(String title, String text, final Runnable runnable) {
AlertMessageBox alertMessageBox = new AlertMessageBox(title, text);
alertMessageBox.addHideHandler(new HideHandler() {
@Override
public void onHide(HideEvent event) {
if (runnable != null) {
runnable.run();
}
}
});
alertMessageBox.setWidth(300);
alertMessageBox.show();
}
@Override
public void confirm(String title, String text, final Runnable yesRunnable) {
confirm(title, text, yesRunnable, null);
}
@Override
public void confirm(String title, String text, final Runnable yesRunnable, final Runnable noRunnable) {
ConfirmMessageBox confirmMessageBox = new ConfirmMessageBox(title, text);
confirmMessageBox.addHideHandler(new HideHandler() {
@Override
public void onHide(HideEvent event) {
Dialog dialog = (Dialog) event.getSource();
boolean isYes = dialog.getHideButton() == dialog.getButtonById(PredefinedButton.YES.name());
if (isYes) {
if (yesRunnable != null) {
yesRunnable.run();
}
} else {
if (noRunnable != null) {
noRunnable.run();
}
}
}
});
confirmMessageBox.setWidth(300);
confirmMessageBox.show();
}
}
|
package Lector16.Task16_1;
import Other.ReadFromConsole;
import java.io.*;
import java.lang.reflect.Field;
public class MainTask16_1 {
public static void main(String[] args) {
OutputStreamWriter osw = null;
InputStreamReader isr = null;
int cycle = 5242880; // запись одного символа char в фаил что бы получилось 5 мБ
String locationFile = ReadFromConsole.findFile();
try {
osw = new OutputStreamWriter(new FileOutputStream(locationFile));
isr = new InputStreamReader(new FileInputStream(locationFile));
long temp1 = System.nanoTime();
for (int i = 0; i < cycle; i ++)
{
osw.write("a");
}
long temp2 =System.nanoTime();
while (isr.ready()){
isr.ready();
}
long temp3 = System.nanoTime();
System.out.printf("запись %d\nЧтение %d", temp2 - temp1, temp3 - temp2);
} catch (Exception excp){
excp.printStackTrace();
}
finally {
if (isr != null)
{
try {
isr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (osw != null)
{
try {
osw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
|
package fieldex;
public class MemberExample {
public static void main(String[] args) {
Member member = new Member();
member.name = "최하얀";
member.id = "white choi";
member.password = "1234";
member.age = 23;
System.out.println("이름: " + member.name);
System.out.println("id: " + member.id);
System.out.println("패스워드: " + member.password);
System.out.println("age: " + member.age);
}
}
|
/**
*
*/
package net.sf.taverna.t2.component.ui.menu.registry;
import static net.sf.taverna.t2.component.ui.menu.ComponentMenu.COMPONENT;
import java.net.URI;
import net.sf.taverna.t2.ui.menu.AbstractMenuSection;
/**
* @author alanrw
*
*/
public class ComponentRegistryMenuSection extends AbstractMenuSection {
public static final URI COMPONENT_REGISTRY_SECTION = URI
.create("http://taverna.sf.net/2008/t2workbench/menu#componentRegistrySection");
public ComponentRegistryMenuSection() {
super(COMPONENT, 100, COMPONENT_REGISTRY_SECTION);
}
}
|
package org.apidesign.gate.timing.server;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import java.util.NavigableSet;
import java.util.TreeSet;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.PostConstruct;
import javax.inject.Inject;
import javax.inject.Singleton;
import javax.ws.rs.Consumes;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.GET;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.container.AsyncResponse;
import javax.ws.rs.container.Suspended;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.apidesign.gate.timing.shared.Contact;
import org.apidesign.gate.timing.shared.Contacts;
import org.apidesign.gate.timing.shared.Event;
import org.apidesign.gate.timing.shared.Events;
import org.apidesign.gate.timing.shared.Run;
import org.apidesign.gate.timing.shared.Running;
import org.apidesign.gate.timing.shared.Settings;
import org.apidesign.gate.timing.shared.Runs;
@Path("/timing/") @Singleton
public final class TimingResource {
private static final Logger LOG = Main.LOG;
private final Map<AsyncResponse,Request> awaiting = new HashMap<>();
private final NavigableSet<Event> events = new TreeSet<>(Events.COMPARATOR);
private Running runs = new Running();
private int counter;
@Inject
private Storage storage;
@Inject
private ContactsResource contacts;
@Inject
private Settings settings;
public TimingResource() {
}
@PostConstruct
public void init() throws IOException {
reloadSettings();
}
void updateSettings(Settings s) {
settings.withName(s.getName());
settings.withDate(s.getDate());
settings.withMin(s.getMin());
settings.withMax(s.getMax());
try {
reloadSettings();
} catch (IOException ex) {
throw new WebApplicationException(ex.getMessage(), ex, Response.Status.NOT_FOUND);
}
}
private synchronized void reloadSettings() throws IOException {
runs = new Running().withSettings(settings);
events.clear();
storage.readInto(settings.getName(), Event.class, events);
for (Event e : events) {
if (e.getId() > counter) {
counter = e.getId();
}
}
if (events.isEmpty()) {
events.add(
new Event().withId(++counter).withWhen(System.currentTimeMillis()).withType(Events.INITIALIZED)
);
}
updateRunsAndReturnChanged();
// notify all
handleAwaiting(null, runs);
}
synchronized Settings settings() {
Settings s = settings.clone();
s.getMeasurements().clear();
s.getMeasurements().addAll(listMeasurements());
return s;
}
@GET @Produces(MediaType.APPLICATION_JSON)
public void allEvents(
@QueryParam("newerThan") @DefaultValue("0") long newerThan,
@Suspended AsyncResponse response
) {
allEvents(new Request(false, newerThan), response, null);
}
@GET @Produces(MediaType.APPLICATION_JSON)
@Path("runs")
public void allRuns(
@QueryParam("newerThan") @DefaultValue("0") long newerThan,
@Suspended AsyncResponse response
) {
allEvents(new Request(true, newerThan), response, null);
}
private synchronized void allEvents(
Request request, AsyncResponse response, Running changedRuns
) {
long first = events.isEmpty() ? -1L : events.iterator().next().getWhen();
if (first <= request.newerThan) {
LOG.log(Level.FINE, "allEvents awating: {0}", request.newerThan);
awaiting.put(response, request);
return;
}
deliverAllEvents(request, response, changedRuns);
}
private synchronized void deliverAllEvents(
Request request, AsyncResponse response, Running changedRuns
) {
abstract class Loop<T> {
abstract long when(T item);
abstract T[] array(int size);
abstract Object wrap(T[] arr);
final void produce(Collection<T> all) {
Collection<T> result = new ArrayList<>();
for (T item : all) {
final long when = when(item);
if (when > request.newerThan) {
result.add(item);
}
}
T[] arr = array(result.size());
result.toArray(arr);
response.resume(wrap(arr));
}
}
if (request.computeRuns) {
if (changedRuns == null) {
changedRuns = this.runs;
}
Running filterRuns = changedRuns.clone();
filterRuns.withSettings(settings());
new Loop<Run>() {
@Override
long when(Run r) {
return Long.MAX_VALUE;
}
@Override
Run[] array(int size) {
return new Run[size];
}
@Override
Object wrap(Run[] arr) {
return filterRuns.withRuns(arr);
}
}.produce(filterRuns.getRuns());
} else {
new Loop<Event>() {
long when(Event e) {
return e.getWhen();
}
Event[] array(int size) {
return new Event[size];
}
@Override
Object wrap(Event[] arr) {
return arr;
}
}.produce(events);
}
}
@GET @Produces({ MediaType.APPLICATION_JSON, MediaType.TEXT_PLAIN })
@Path("add")
public synchronized Response addEvent(
@HeaderParam("Accept") String accept,
@QueryParam("type") Events type,
@QueryParam("when") long when,
@QueryParam("who") String who,
@QueryParam("ref") @DefaultValue("-1") int ref
) {
LOG.log(Level.FINE, "addEvent Accept: {0} type {1} when {2} who {3} ref {4}", new Object[] { accept, type, when, who, ref });
if (when <= 0) {
when = System.currentTimeMillis();
}
String whoName;
Contact checkWho = Contacts.findById(contacts.allContacts(), who);
int whoNum;
if (checkWho != null) {
whoNum = checkWho.getId();
whoName = checkWho.getName();
} else {
whoName = "" + who;
if (who == null) {
whoNum = 0;
} else {
try {
whoNum = Integer.parseInt(who);
} catch (NumberFormatException ex) {
whoNum = Math.abs(who.hashCode()) | 0x7f000000;
contacts.pendingAliases(whoNum, who);
}
}
}
final Event newEvent = new Event().withId(++counter).
withWhen(when).
withRef(ref).
withWho(whoNum).
withType(type);
LOG.log(Level.FINE, " checkWho {0} event {1}", new Object[] { checkWho, newEvent });
events.add(newEvent);
storage.scheduleStore(settings.getName(), Event.class, events);
Running changed = updateRunsAndReturnChanged();
handleAwaiting(when, changed);
if (MediaType.TEXT_PLAIN.equals(accept)) {
return Response.ok(whoName).type(MediaType.TEXT_PLAIN_TYPE).build();
}
return Response.ok(newEvent).type(MediaType.APPLICATION_JSON_TYPE).build();
}
private Running updateRunsAndReturnChanged() {
Running newRunning = Runs.compute(events, settings().getMinMillis(), settings().getMaxMillis());
final List<Run> oldRuns = this.runs.getRuns();
List<Run> newRuns = newRunning.getRuns();
int at = newRuns.size() - 1;
synchronized (this) {
while (at >= 0) {
Run newR = newRuns.get(at);
int oldAt = at - newRuns.size() + oldRuns.size();
if (oldAt < 0) {
break;
}
Run oldR = oldRuns.get(oldAt);
if (!newR.equals(oldR)) {
break;
}
at--;
}
runs = newRunning;
}
Running justChanged = newRunning.clone();
justChanged.withSettings(settings());
justChanged.getRuns().clear();
justChanged.getRuns().addAll(newRuns.subList(0, at + 1));
return justChanged;
}
private void handleAwaiting(Long newest, Running changedRuns) {
assert Thread.holdsLock(this);
Iterator<Map.Entry<AsyncResponse, Request>> it;
for (it = awaiting.entrySet().iterator(); it.hasNext(); ) {
Map.Entry<AsyncResponse, Request> entry = it.next();
AsyncResponse ar = entry.getKey();
Request since = entry.getValue();
if (newest == null) {
it.remove();
deliverAllEvents(since, ar, changedRuns);
} else if (since.newerThan <= newest) {
it.remove();
allEvents(since, ar, changedRuns);
}
}
}
@Path("contacts")
public ContactsResource getContacts() {
return contacts;
}
@GET
@Produces("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
@Path("výsledky.xlsx")
public byte[] asXlsx() throws IOException {
XlsGenerator doc = XlsGenerator.create(runs, contacts.allContacts());
try (ByteArrayOutputStream os = new ByteArrayOutputStream()) {
doc.write(os);
return os.toByteArray();
}
}
@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("admin")
public Settings config(
@QueryParam("name") String name
) {
LOG.log(Level.FINE, "admin/config {0}", name);
Settings data = new Settings().withName(name);
return config(data);
}
@PUT
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Path("admin")
public Settings config(
@QueryParam("name") String name,
Settings data
) {
LOG.log(Level.FINE, "admin/config {0} = {1}", new Object[] { name, data });
if (name != null && !name.isEmpty()) {
data.setName(name);
}
return config(data);
}
private Settings config(Settings data) {
if (!isValidName(data.getName())) {
throw new WebApplicationException("Unacceptable name: " + data.getName(), Response.Status.NOT_ACCEPTABLE);
}
updateSettings(data);
return settings();
}
private List<String> listMeasurements() {
List<String> measurements = new LinkedList<>(Arrays.asList(storage.files()));
measurements.remove("people.json");
ListIterator<String> it = measurements.listIterator();
while (it.hasNext()) {
final String file = it.next();
if (!file.endsWith(".json")) {
it.remove();
continue;
}
String base = file.substring(0, file.length() - 5);
if (!isValidName(base)) {
it.remove();
} else {
it.set(base);
}
}
return measurements;
}
static boolean isValidName(String name) {
for (char ch : name.toCharArray()) {
if (Character.isAlphabetic(ch)) {
continue;
}
if (Character.isDigit(ch)) {
continue;
}
if (ch == ' ') {
continue;
}
return false;
}
return true;
}
private static final class Request {
final boolean computeRuns;
final long newerThan;
Request(boolean runs, long newerThan) {
this.computeRuns = runs;
this.newerThan = newerThan;
}
}
}
|
package com.edasaki.rpg.items;
import org.bukkit.ChatColor;
public class ItemBalance {
/*
* Sage
*/
public static final String[] SAGE_NAMES = {
// owner names
"Edasaki",
"Misaka",
"Frenda",
// Sages
"Aleister",
"Solomon",
"Aiwass",
"Silvia",
"Fenrir",
"Cendrillon",
"Etzali",
"Vasilisa",
"Acqua",
"Fiamma",
"Belle"
};
protected static final double SAGE_CHANCE = 0.0005;
/*
* Equip drop rates
*/
protected static final ChatColor[] ITEM_TIER_COLORS = {
ChatColor.GRAY,
ChatColor.DARK_AQUA,
ChatColor.DARK_GREEN,
ChatColor.LIGHT_PURPLE,
ChatColor.GOLD
};
/*
* Rarity
*/
protected static final double[] RARITY_CHANCES = { //check by doing Math.rand() and seeing if less than value
1.0,
0.06, //6% rare or better
0.03, //3% epic or better
0.01, //1% unique or better
0.003, //0.3% supreme or better
0.0008, //0.08% legendary or better
0.0001, //0.01% godlike (1 in 10000)
};
public static final String[] RARITY_NAMES = {
"", //0
"Rare", //1
"Epic", //2
"Unique", //3
"Supreme", //4
"Legendary", //5
"Godlike" //6
};
protected static final ChatColor[] RARITY_COLORS = {
ChatColor.GRAY, //normal
ChatColor.BLUE, //rare
ChatColor.RED, //epic
ChatColor.AQUA, //unique
ChatColor.LIGHT_PURPLE, //supreme
ChatColor.GREEN, //legendary
ChatColor.GOLD //godlike
};
public static String getRarityName(int rarityZeroIndexed) {
return RARITY_NAMES[rarityZeroIndexed];
}
public static ChatColor getRarityColor(int rarityZeroIndexed) {
return RARITY_COLORS[rarityZeroIndexed];
}
/*
* Prefixes
*/
protected static final double PREFIX_CHANCE = 0.8;
public static final String[] SET_PREFIXES = {
"Fancy",
"Shiny",
"Ancient",
"Traditional",
"Angelic",
"Demonic",
"Sakura",
"Gremlin",
"Revered",
"Battle",
"Dawn",
"Dusk",
"Barbaric",
"Elven",
"Scorched",
"Viridian"
};
private static final String[] TIER_PREFIXES_ARMOR = {
"Leather",
"Chainmail",
"Iron",
"Golden",
"Diamond"
};
public static final String getTierPrefixArmor(int level) {
return TIER_PREFIXES_ARMOR[getTierZeroIndex(level)];
}
private static final String[] TIER_PREFIXES_WEAPON = {
"Recruit",
"Novice",
"Apprentice",
"Veteran",
"Master"
};
public static final String getTierPrefixWeapon(int level) {
return TIER_PREFIXES_WEAPON[getTierZeroIndex(level)];
}
public static int getTierZeroIndex(int level) {
if (level < 20)
return 0;
else if (level < 40)
return 1;
else if (level < 60)
return 2;
else if (level < 80)
return 3;
else
return 4;
}
}
|
package com.arthur.leetcode;
/**
* @title: No190
* @Author ArthurJi
* @Date: 2021/3/20 12:58
* @Version 1.0
*/
public class No190 {
public static void main(String[] args) {
System.out.println(reverseBits(1010011100));
}
// you need treat n as an unsigned value
public static int reverseBits(int n) {
int ans = 0;
int power = 32;
// System.out.println(n);//实际上是二进制的
while (power-- != 0) {
ans += (n & 1) << power;
n >>= 1;
}
return ans;
// return Integer.reverse(n);
}
}
/*
190. 颠倒二进制位
颠倒给定的 32 位无符号整数的二进制位。
示例 1:
输入: 00000010100101000001111010011100
输出: 00111001011110000010100101000000
解释: 输入的二进制串 00000010100101000001111010011100 表示无符号整数 43261596,
因此返回 964176192,其二进制表示形式为 00111001011110000010100101000000。
示例 2:
输入:11111111111111111111111111111101
输出:10111111111111111111111111111111
解释:输入的二进制串 11111111111111111111111111111101 表示无符号整数 4294967293,
因此返回 3221225471 其二进制表示形式为 10111111111111111111111111111111 。
提示:
请注意,在某些语言(如 Java)中,没有无符号整数类型。在这种情况下,输入和输出都将被指定为有符号整数类型,并且不应影响您的实现,因为无论整数是有符号的还是无符号的,其内部的二进制表示形式都是相同的。
在 Java 中,编译器使用二进制补码记法来表示有符号整数。因此,在上面的 示例 2 中,输入表示有符号整数 -3,输出表示有符号整数 -1073741825。
*/
|
package io.jrevolt.sysmon.model;
import io.jrevolt.launcher.mvn.Artifact;
import io.jrevolt.sysmon.common.InstantConverter;
import io.jrevolt.sysmon.common.Version;
import com.thoughtworks.xstream.annotations.XStreamConverter;
import java.time.Instant;
/**
* @author <a href="mailto:patrikbeno@gmail.com">Patrik Beno</a>
*/
public class VersionInfo {
private String artifact;
private String version;
@XStreamConverter(value=InstantConverter.class)
private Instant buildTimestamp;
public VersionInfo() {
}
public VersionInfo(Version src) {
this.artifact = src.isUnknown() ? src.getArtifactUri() : Artifact.tryparse(src.getArtifactUri()).getArtifactId();
this.version = src.getArtifactVersion();
this.buildTimestamp = src.getTimestamp();
}
public String getArtifact() {
return artifact;
}
public void setArtifact(String artifact) {
this.artifact = artifact;
}
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
public Instant getBuildTimestamp() {
return buildTimestamp;
}
public void setBuildTimestamp(Instant buildTimestamp) {
this.buildTimestamp = buildTimestamp;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
VersionInfo that = (VersionInfo) o;
if (artifact != null ? !artifact.equals(that.artifact) : that.artifact != null) return false;
if (buildTimestamp != null ? !buildTimestamp.equals(that.buildTimestamp) : that.buildTimestamp != null)
return false;
if (version != null ? !version.equals(that.version) : that.version != null) return false;
return true;
}
@Override
public int hashCode() {
int result = artifact != null ? artifact.hashCode() : 0;
result = 31 * result + (version != null ? version.hashCode() : 0);
result = 31 * result + (buildTimestamp != null ? buildTimestamp.hashCode() : 0);
return result;
}
}
|
package com.gluo.pruebas.tests;
import com.gluo.pruebas.DefaultFragment;
import com.gluo.pruebas.test1.LocationFragment;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Helper class for providing sample content for user interfaces created by
* Android template wizards.
* <p/>
* TODO: Replace all uses of this class before publishing your app.
*/
public class TestContent {
/**
* An array of sample (dummy) items.
*/
public static List<TestItem> ITEMS = new ArrayList<TestItem>();
/**
* A map of sample (dummy) items, by ID.
*/
public static Map<String, TestItem> ITEM_MAP = new HashMap<String, TestItem>();
static {
// Add 3 sample items.
addItem(new TestItem("1", "Test 1 - Location", new LocationFragment()));
addItem(new TestItem("2", "Test 2"));
addItem(new TestItem("3", "Test 3"));
}
private static void addItem(TestItem item) {
ITEMS.add(item);
ITEM_MAP.put(item.id, item);
}
/**
* A dummy item representing a piece of content.
*/
public static class TestItem {
public String id;
public String content;
public DefaultFragment fragmentClass;
public TestItem(String id, String content) {
this.id = id;
this.content = content;
}
public TestItem(String id, String content, DefaultFragment fragmentClass) {
this.id = id;
this.content = content;
this.fragmentClass = fragmentClass;
}
@Override
public String toString() {
return content;
}
}
}
|
package me.aslammaududy.eresto.NetworkManager;
import java.util.List;
import me.aslammaududy.eresto.Model.Menu;
import retrofit2.Call;
import retrofit2.http.Body;
import retrofit2.http.GET;
import retrofit2.http.POST;
public interface Endpoints {
@POST("tambahmenu.php")
Call<List<Menu>> addMenu(@Body List<Menu> orderedMenu);
@GET("ambilmenu.php")
Call<List<Menu>> retrieveMenu();
}
|
package animals;
import Aviary.AviarySize;
import Except.WrongFoodException;
import food.Food;
public class Duck extends Herbivore implements Fly, Swim, Voice, Run {
public Duck() {
super();
}
public Duck(AviarySize inAviaries) {
this.inAviaries = inAviaries;
}
@Override
public String toString(){
return "Утка";
}
@Override
public void run() {
System.out.println("Утка бежит");
}
@Override
public String voice() {
return "Утка крякает";
}
@Override
public void swim() {
System.out.println("Утка плавает");
}
@Override
public void fly() {
System.out.println("Утка летает");
}
public void eat (Food food) throws WrongFoodException {
System.out.println("Утке дали " + food.toString());
super.eat(food);
}
@Override
public String getIdNumber() {
return idNumber;
}
}
|
package no.uninett.adc.neo.domain;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import org.junit.Test;
//@RunWith(SpringJUnit4ClassRunner.class)
public class EduObjectTest {
private static final String FEIDE_ID = "FEIDE-ID";
@Test
public void findDelete() {
EduPerson p1 = new EduPerson(FEIDE_ID);
ChangeSet cs = EduObject.diff(p1, null);
assertNotNull("There shall be a change set", cs);
assertEquals("The changeOperation shall be delete",
ChangeOperation.DELETE, cs.getOperation());
assertFalse(p1.isActive());
p1.setActive(true);
EduPerson p2 = new EduPerson(FEIDE_ID);
p2.setActive(false);
cs = EduObject.diff(p1, p2);
assertNotNull("There shall be a change set", cs);
assertEquals("The changeOperation shall be delete",
ChangeOperation.DELETE, cs.getOperation());
}
@Test
public void findCreate() {
EduPerson p1 = new EduPerson(FEIDE_ID);
ChangeSet cs = EduObject.diff(null, p1);
assertEquals("The changeOperation shall be create",
ChangeOperation.CREATE, cs.getOperation());
EduPerson p2 = new EduPerson(FEIDE_ID);
p2.setActive(false);
cs = EduObject.diff(p2, p1);
assertEquals("The changeOperation shall be create",
ChangeOperation.CREATE, cs.getOperation());
}
@Test
public void findEmptyUpdate() {
EduPerson p1 = new EduPerson(FEIDE_ID);
ChangeSet cs = EduObject.diff(p1, p1);
assertNull("There shall not be a change set", cs);
Attribute att = new Attribute("key", "value");
p1.addAttribute(att);
cs = EduObject.diff(p1, p1);
assertNull("There shall not be a change set", cs);
}
@Test
public void findUpdateWithOneChange() {
EduPerson p1 = new EduPerson(FEIDE_ID);
Attribute att = new Attribute("key", "value");
p1.addAttribute(att);
EduPerson p2 = new EduPerson(FEIDE_ID);
ChangeSet cs = EduObject.diff(p2, p1);
assertNotNull("There shall be a change set", cs);
assertEquals("The operation on the set does not fit:",
ChangeOperation.UPDATE, cs.getOperation());
assertEquals("There should be one change", 1, cs.getChanges().size());
Change c = cs.getChanges().iterator().next();
assertEquals("The operation on the change does not fit",
ChangeOperation.CREATE, c.getChangeOperation());
cs = EduObject.diff(p1, p2);
assertNotNull("There shall be a change set", cs);
assertEquals("The operation on the set does not fit:",
ChangeOperation.UPDATE, cs.getOperation());
assertEquals("There should be one change", 1, cs.getChanges().size());
c = cs.getChanges().iterator().next();
assertEquals("The operation on the change does not fit",
ChangeOperation.DELETE, c.getChangeOperation());
Attribute att2 = new Attribute("key", "anotherValue");
p2.addAttribute(att2);
cs = EduObject.diff(p1, p2);
assertNotNull("There shall be a change set", cs);
assertEquals("The operation on the set does not fit:",
ChangeOperation.UPDATE, cs.getOperation());
assertEquals("There should be one change", 1, cs.getChanges().size());
c = cs.getChanges().iterator().next();
assertEquals("The operation on the change does not fit",
ChangeOperation.UPDATE, c.getChangeOperation());
assertEquals("anotherValue", ((AttributeChange) c).getAttribute()
.getValue());
cs = EduObject.diff(p2, p1);
assertNotNull("There shall be a change set", cs);
assertEquals("The operation on the set does not fit:",
ChangeOperation.UPDATE, cs.getOperation());
assertEquals("There should be one change", 1, cs.getChanges().size());
c = cs.getChanges().iterator().next();
assertEquals("The operation on the change does not fit",
ChangeOperation.UPDATE, c.getChangeOperation());
assertEquals("value", ((AttributeChange) c).getAttribute().getValue());
}
}
|
package com.iti.mad.firstlab;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
public class CunterActivity extends AppCompatActivity {
int counter=0;
TextView counterTxt;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_counter);
counterTxt=findViewById(R.id.counterId);
}
@Override
protected void onStart() {
super.onStart();
}
@Override
protected void onRestart() {
super.onRestart();
counter--;
}
@Override
protected void onResume() {
super.onResume();
counterTxt.setText(counter+"");
}
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
counter= savedInstanceState.getInt("counter");
counter++;
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("counter", counter);
}
@Override
protected void onPause() {
super.onPause();
}
@Override
protected void onStop() {
super.onStop();
}
@Override
protected void onDestroy() {
super.onDestroy();
}
}
|
package com.sinotech.settle.utils;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* 账户相关属性验证工具
* @author haakon
*
*/
public class AccountValidatorUtil {
/**
* 正则表达式:验证用户名
*/
private static final String REGEX_USERNAME = "^[a-zA-Z]\\w{5,20}$";
/**
* 正则表达式:验证密码
*/
private static final String REGEX_PASSWORD = "^[a-zA-Z0-9]{6,20}$";
/**
* 正则表达式:验证手机号
*/
private static final String REGEX_MOBILE = "^((17[0-9])|(14[0-9])|(13[0-9])|(15[^4,\\D])|(18[0,5-9]))\\d{8}$";
/**
* 正则表达式:验证邮箱
*/
private static final String REGEX_EMAIL = "^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
/**
* 正则表达式:验证汉字
*/
private static final String REGEX_CHINESE = "^[\u4e00-\u9fa5],{0,}$";
/**
* 正则表达式:验证身份证
*/
private static final String REGEX_ID_CARD = "(^\\d{18}$)|(^\\d{15}$)";
/**
* 正则表达式:验证URL
*/
private static final String REGEX_URL = "http(s)?://([\\w-]+\\.)+[\\w-]+(/[\\w- ./?%&=]*)?";
/**
* 正则表达式:验证IP地址
*/
private static final String REGEX_IP_ADDR = "(25[0-5]|2[0-4]\\d|[0-1]\\d{2}|[1-9]?\\d)";
/**
* 校验用户名
*
* @param username
* @return 校验通过返回true,否则返回false
*/
public static boolean isUsername(String username) {
return Pattern.matches(REGEX_USERNAME, username);
}
/**
* 校验密码
*
* @param password
* @return 校验通过返回true,否则返回false
*/
public static boolean isPassword(String password) {
return Pattern.matches(REGEX_PASSWORD, password);
}
/**
* 校验手机号
*
* @param mobile
* @return 校验通过返回true,否则返回false
*/
public static boolean isMobile(String mobile) {
return Pattern.matches(REGEX_MOBILE, mobile);
}
/**
* 校验邮箱
*
* @param email
* @return 校验通过返回true,否则返回false
*/
public static boolean isEmail(String email) {
return Pattern.matches(REGEX_EMAIL, email);
}
/**
* 校验汉字
*
* @param chinese
* @return 校验通过返回true,否则返回false
*/
public static boolean isChinese(String chinese) {
return Pattern.matches(REGEX_CHINESE, chinese);
}
/**
* 校验身份证
*
* @param idCard
* @return 校验通过返回true,否则返回false
*/
public static boolean isIDCard(String idCard) {
return Pattern.matches(REGEX_ID_CARD, idCard);
}
/**
* 校验URL
*
* @param url
* @return 校验通过返回true,否则返回false
*/
public static boolean isUrl(String url) {
return Pattern.matches(REGEX_URL, url);
}
/**
* 校验IP地址
*
* @param ipAddr
* @return
*/
public static boolean isIPAddr(String ipAddr) {
return Pattern.matches(REGEX_IP_ADDR, ipAddr);
}
private static boolean isMatch(String regex, String orginal){
if (orginal == null || orginal.trim().equals("")) {
return false;
}
Pattern pattern = Pattern.compile(regex);
Matcher isNum = pattern.matcher(orginal);
return isNum.matches();
}
/**
* 校验正整数,可以带+号,第一个数字不能为0
* @param orginal
* @return
*/
public static boolean isPositiveInteger(String orginal) {
return isMatch("^\\+{0,1}[1-9]\\d*", orginal);
}
/**
* 校验负整数,必须带负号,第一个数字也不能为0
* @param orginal
* @return
*/
public static boolean isNegativeInteger(String orginal) {
return isMatch("^-[1-9]\\d*", orginal);
}
/**
* 校验整数,实际是由0,正整数和负整数组成的
* @param orginal
* @return
*/
public static boolean isWholeNumber(String orginal) {
return isMatch("[+-]{0,1}0", orginal) || isPositiveInteger(orginal) || isNegativeInteger(orginal);
}
/**
* 校验正小数,可以考带+号,并考虑两种情况,第一个数字为0和第一个数字不为0,第一个数字为0时,则小数点后面应该不为0,第一个数字不为0时,小数点后可以为任意数字
* @param orginal
* @return
*/
public static boolean isPositiveDecimal(String orginal){
return isMatch("\\+{0,1}[0]\\.[1-9]*|\\+{0,1}[1-9]\\d*\\.\\d*", orginal);
}
/**
* 判断是否是正数(可以小数点后两位)
* @param str
* @return
*/
public static boolean isNumeric(String str) {
Pattern pattern = Pattern.compile("[0-9]+.?[0-9]{1,2}+");
Matcher isNum = pattern.matcher(str);
if (!isNum.matches()) {
return false;
}
return true;
}
/**
* 判断是否是正数(整数或小数)
* @param str
* @return
*/
public static boolean isNum(String str) {
Pattern pattern = Pattern.compile("^\\d+(\\.\\d+)?$");
Matcher isNum = pattern.matcher(str);
if (!isNum.matches()) {
return false;
}
return true;
}
public static void main(String[] args) {
// System.out.println(DateUtil.getDateFormat(new Date(),"yyMM:HHmm").codePointCount(0, 4));
System.out.println(isNumeric(""));
}
/**
* 负小数,必须带负号,其余都同上
* @param orginal
* @return
*/
public static boolean isNegativeDecimal(String orginal){
return isMatch("^-[0]\\.[1-9]*|^-[1-9]\\d*\\.\\d*", orginal);
}
/**
* 小数,可以带正负号,并且带小数点就行了,但是至少保证小数点有一边不为空,所以这里还是分左边不为空和右边不为空的情况
* @param orginal
* @return
*/
public static boolean isDecimal(String orginal){
return isMatch("[-+]{0,1}\\d+\\.\\d*|[-+]{0,1}\\d*\\.\\d+", orginal);
}
/**
* 实数比较简单,,要么是整数,要么是小数
* @param orginal
* @return
*/
public static boolean isRealNumber(String orginal){
return isWholeNumber(orginal) || isDecimal(orginal);
}
}
|
package model;
/**
*
* @author rodrigoavellar
*/
public class Usuario {
private static int codGenerator = 1;
private int id;
private String nome;
private String email;
private String senha; // TODO Sistema temporário de senha...
/**
*
* @param nome
* @param email
* @param senha
*/
public Usuario(String nome, String email, String senha) {
this.id = codGenerator();
this.nome = nome;
this.email = email;
this.senha = senha;
}
/**
*
* @return
*/
public int getId() {
return id;
}
/**
*
* @return
*/
public String getName() {
return nome;
}
/**
*
* @param nome
*/
public void setName(String nome) {
this.nome = nome;
}
/**
*
* @return
*/
public String getEmail() {
return email;
}
/**
*
* @param email
*/
public void setEmail(String email) {
this.email = email;
}
/**
*
* @param novaSenha
*/
public void setPassord(String novaSenha) {
this.senha = novaSenha;
}
private int codGenerator(){
return(codGenerator++);
}
}
|
package boookmanager.addmember;
import boookaager.database.DatabaseHandler;
import boookmanager.listbook.BooklistController;
import boookmanager.listmembers.ListmemberController;
import boookmanager.listmembers.ListmemberController.Member;
import com.jfoenix.controls.JFXButton;
import com.jfoenix.controls.JFXTextField;
import java.net.URL;
import java.sql.SQLException;
import java.util.ResourceBundle;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Alert;
import javafx.scene.layout.AnchorPane;
import javafx.stage.Stage;
/**
* FXML Controller class
*
* @author mustafa
*/
public class AddmemberController implements Initializable {
DatabaseHandler handler;
@FXML
private AnchorPane rootPane;
@FXML
private JFXTextField id;
@FXML
private JFXTextField name;
@FXML
private JFXTextField mobile;
@FXML
private JFXTextField email;
@FXML
private JFXButton saveButton;
@FXML
private JFXButton cancelButton;
private boolean isInEditMode=false;
@Override
public void initialize(URL url, ResourceBundle rb) {
handler= DatabaseHandler.getInstance();
}
@FXML
private void addmember(ActionEvent event) {
String mName= name.getText();
String mId= id.getText();
String mMobile= mobile.getText();
String mEmail= email.getText();
if(mName.isEmpty()||mId.isEmpty()||mMobile.isEmpty()||mEmail.isEmpty())
{
Alert alert = new Alert(Alert.AlertType.ERROR);
alert.setHeaderText(null);
alert.setContentText("Please fill All the fields");
alert.showAndWait();
return;
}
if(isInEditMode)
{
try {
handleUpdateMember();
} catch (SQLException ex) {
Logger.getLogger(AddmemberController.class.getName()).log(Level.SEVERE, null, ex);
}
return;
}
String st="INSERT INTO MEMBER VALUES("+
"'"+mId +"',"+
"'"+mName +"',"+
"'"+mMobile +"',"+
"'"+mEmail +"'"+
")";
System.out.println(st);
if(handler.execAction(st)){
Alert alert = new Alert(Alert.AlertType.INFORMATION);
alert.setHeaderText(null);
alert.setContentText("Success");
alert.showAndWait();
}else
{
Alert alert = new Alert(Alert.AlertType.ERROR);
alert.setHeaderText(null);
alert.setContentText("Error Occured");
alert.showAndWait();
}
}
@FXML
private void cancel(ActionEvent event) {
Stage stage = (Stage) rootPane.getScene().getWindow();
stage.close();
}
public void passinfo(ListmemberController.Member member)
{
id.setText(member.getId());
name.setText(member.getName());
mobile.setText(member.getMobile());
email.setText(member.getEmail());
id.setEditable(false);
isInEditMode=true;
}
private void handleUpdateMember() throws SQLException {
Member member=new ListmemberController.Member(name.getText(),id.getText(),mobile.getText(),email.getText());
if(handler.updateMember(member))
{
Alert alert= new Alert(Alert.AlertType.INFORMATION);
alert.setTitle("Success");
alert.setHeaderText(null);
alert.setContentText("Member Updated Successfully");
alert.showAndWait();
}else
{
Alert alert= new Alert(Alert.AlertType.ERROR);
alert.setTitle("Failed");
alert.setHeaderText(null);
alert.setContentText("Can't Update Member");
alert.showAndWait();
}
}
}
|
package com.bwie.juan_mao.jingdong_kanglijuan.adapter;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.bwie.juan_mao.jingdong_kanglijuan.R;
import com.bwie.juan_mao.jingdong_kanglijuan.bean.ProductBean;
import com.bwie.juan_mao.jingdong_kanglijuan.bean.ShopperBean;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
/**
* Created by 卷猫~ on 2018/11/19.
*/
public class OrderShopperAdapter extends RecyclerView.Adapter<OrderShopperAdapter.ViewHolder> {
private Context context;
private List<ShopperBean<List<ProductBean>>> list;
public OrderShopperAdapter(Context context, List<ShopperBean<List<ProductBean>>> list) {
this.context = context;
this.list = list;
}
@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.item_order_shopper, parent, false);
ViewHolder holder = new ViewHolder(view);
return holder;
}
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
holder.txtShopperName.setText(list.get(position).getSellerName());
List<ProductBean> product = this.list.get(position).getList();
OrderProductAdapter adapter = new OrderProductAdapter(context, product);
holder.rvOrderProduct.setNestedScrollingEnabled(false);
holder.rvOrderProduct.setLayoutManager(new LinearLayoutManager(context));
holder.rvOrderProduct.addItemDecoration(new DividerItemDecoration(context, DividerItemDecoration.VERTICAL));
holder.rvOrderProduct.setAdapter(adapter);
}
@Override
public int getItemCount() {
return list.size();
}
class ViewHolder extends RecyclerView.ViewHolder {
@BindView(R.id.txt_shopper_name)
TextView txtShopperName;
@BindView(R.id.rv_order_product)
RecyclerView rvOrderProduct;
ViewHolder(View view) {
super(view);
ButterKnife.bind(this, view);
}
}
}
|
package models;
import play.libs.Json;
import javax.persistence.Entity;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.ebean.Finder;
import io.ebean.Model;
import javax.persistence.*;
import java.util.HashMap;
import java.util.Map;
/**
* The basic model for an item we're dealing with.
*/
@Entity
public class InventoryItem extends Model
{
@Id
public Long id;
public String name;
public Double price;
public Integer quantity;
public String imgPath;
public static Map<String, String> asMap(InventoryItem item)
{
Map<String, String> itemAsMap = new HashMap<String, String>();
itemAsMap.put("name", item.name);
itemAsMap.put("price", "" +item.price);
return itemAsMap;
}
public static ObjectNode asJsonNode(InventoryItem item)
{
ObjectNode node = Json.newObject();
node.put("name", item.name);
node.put("price", item.price);
return node;
}
public static Finder<String,InventoryItem> find = new Finder<>(InventoryItem.class);
}
|
package com.isg.iloan.model.dataEntry;
import java.util.Date;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
@Entity
@Table(name="SUPPLEMENTARY")
public class Supplementary {
@Id
@SequenceGenerator(name="SUPPLEMENTARY_SEQ",sequenceName="SUPPLEMENTARY_SEQ",allocationSize=1)
@GeneratedValue(generator="SUPPLEMENTARY_SEQ", strategy = GenerationType.SEQUENCE)
@Column(name="SUPP_ID")
private long supplementaryId;
@Column(name="FAMILYNAME")
private String familyName;
@Column(name="GIVENNAME")
private String givenName;
@Column(name="MIDDLENAME")
private String middleName;
@Column(name="CARDNAME")
private String nameOnCard;
@Column(name="REL_TO_PRINC")
private String relationToPrincipal;
@Column(name="NATIONALITY")
private String nationality;
@Column(name="OTHERNATIONAL")
private boolean otherNational;
@Column(name="BIRTHDATE")
private Date birthDate;
@Column(name="BIRTHPLACE")
private String birthPlace;
@Column(name="GENDER")
private String gender;
@OneToOne(cascade=CascadeType.ALL,fetch=FetchType.LAZY)
@JoinColumn(name="ADDRESS_ID")
private Address homeAddress;
//Constructors
public Supplementary(){}
public long getSupplementaryId() {
return supplementaryId;
}
public void setSupplementaryId(long supplementaryId) {
this.supplementaryId = supplementaryId;
}
public String getFamilyName() {
return familyName;
}
public void setFamilyName(String familyName) {
this.familyName = familyName;
}
public String getGivenName() {
return givenName;
}
public void setGivenName(String givenName) {
this.givenName = givenName;
}
public String getMiddleName() {
return middleName;
}
public void setMiddleName(String middleName) {
this.middleName = middleName;
}
public String getNameOnCard() {
return nameOnCard;
}
public void setNameOnCard(String nameOnCard) {
this.nameOnCard = nameOnCard;
}
public Address getHomeAddress() {
return homeAddress;
}
public void setHomeAddress(Address homeAddress) {
this.homeAddress = homeAddress;
}
public String getRelationToPrincipal() {
return relationToPrincipal;
}
public void setRelationToPrincipal(String relationToPrincipal) {
this.relationToPrincipal = relationToPrincipal;
}
public String getNationality() {
return nationality;
}
public void setNationality(String nationality) {
this.nationality = nationality;
}
public boolean isOtherNational() {
return otherNational;
}
public void setOtherNational(boolean otherNational) {
this.otherNational = otherNational;
}
public Date getBirthDate() {
return birthDate;
}
public void setBirthDate(Date birthDate) {
this.birthDate = birthDate;
}
public String getGender() {
return gender;
}
public void setGender(String gender){
this.gender = gender;
}
public String getBirthPlace() {
return birthPlace;
}
public void setBirthPlace(String birthPlace) {
this.birthPlace = birthPlace;
}
//Methods
//Inner classes
} //end class Supplementary
|
package com.appirio.service.member.resources;
import com.appirio.service.member.api.MemberProfile;
import com.appirio.service.member.api.PhotoContentType;
import com.appirio.service.member.api.PhotoTokenContentType;
import com.appirio.service.member.manager.MemberProfileManager;
import com.appirio.supply.ErrorHandler;
import com.appirio.tech.core.api.v3.request.FieldSelector;
import com.appirio.tech.core.api.v3.request.PostPutRequest;
import com.appirio.tech.core.api.v3.request.annotation.APIFieldParam;
import com.appirio.tech.core.api.v3.request.annotation.AllowAnonymous;
import com.appirio.tech.core.api.v3.response.ApiResponse;
import com.appirio.tech.core.api.v3.response.ApiResponseFactory;
import com.appirio.tech.core.auth.AuthUser;
import com.codahale.metrics.annotation.Timed;
import io.dropwizard.auth.Auth;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.validation.Valid;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.SecurityContext;
/**
* Represents the MemberProfileResource used to manage the user profile data
*
* <p>
* Changes in the version 1.1 (Topcoder Member Service - New Endpoint to Update Email Address Code Challenge v1.0)
* - modify updateMemeberProfile to send the email verificaiton
* - add the verifyUserEmail method
* </p>
*
* <p>
* Version 1.2 - Topcoder Member Service - New Endpoint to Update Email Address Code Challenge v1.0
* - add the verifyUserEmail method
* </p>
*
* <p>
* Version 1.3 - Topcoder Member Service - New Endpoint to Update Email Address Code Challenge v1.0
* - update updateMemberProfile to send verification email
* - add verifyUserEmail method
* </p>
*
* @author TCCoder
* @version 1.3
*
*/
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
@Path("members/{handle}")
public class MemberProfileResource {
/**
* Member profile manager
*/
private MemberProfileManager memberProfileManager;
/**
* Logger for the class
*/
private Logger logger = LoggerFactory.getLogger(MemberProfileResource.class);
/**
* Constructor for Member profile resource
* @param memberProfileManager Member profile manager
*/
public MemberProfileResource(MemberProfileManager memberProfileManager) {
this.memberProfileManager = memberProfileManager;
}
/**
* Get member profile
* @param handle Handle of the user
* @param selector selector
* @param securityContext the security context
* @return ApiResponse Api response
*/
@GET
@Timed
@AllowAnonymous
public ApiResponse getMemberProfile(@PathParam("handle") String handle,
@APIFieldParam(repClass = MemberProfile.class) FieldSelector selector, @Context SecurityContext
securityContext) {
try {
AuthUser authUser = (AuthUser)securityContext.getUserPrincipal();
logger.debug("getMemberProfile, handle : " + handle + " auth : " + authUser);
MemberProfile memberProfile = memberProfileManager.getMemberProfile(handle, authUser);
logger.info(memberProfile.getEmail());
if (memberProfile == null) {
return ApiResponseFactory.createResponse(memberProfile);
}
return ApiResponseFactory.createFieldSelectorResponse(memberProfile, selector);
} catch (Throwable ex) {
return ErrorHandler.handle(ex, logger);
}
}
/**
* Update profile
* @param handle Handle of the user
* @param authUser Authentication user
* @param putRequest Put request
* @return ApiResponse Api response
*/
@PUT
@Timed
public ApiResponse updateMemberProfile(@PathParam("handle") String handle, @Auth AuthUser authUser,
@Valid PostPutRequest<MemberProfile> putRequest) {
try {
logger.debug("updateMemberProfile, handle : " + handle + " auth : " + authUser);
MemberProfile memberProfile = putRequest.getParam();
MemberProfile resultMemberProfile = memberProfileManager.updateMemberProfile(handle, authUser, memberProfile);
return ApiResponseFactory.createResponse(resultMemberProfile);
} catch (Throwable ex) {
return ErrorHandler.handle(ex, logger);
}
}
/**
* Verify user email
*
* @param handle the handle to use
* @param newEmail the newEmail to use
* @param oldEmail the oldEmail to use
* @param token the token to use
* @param authUser the authUser to use
* @return the ApiResponse result
*/
@POST
@Path("/verify")
@Timed
public ApiResponse verifyUserEmail(@PathParam("handle") String handle, @QueryParam("newEmail") String newEmail, @QueryParam("oldEmail") String oldEmail,
@QueryParam("token") String token, @Auth AuthUser authUser) {
try {
logger.debug("verifyUserEmail, handle : " + handle + ", newEmail : " + newEmail + ", oldEmail : " +
oldEmail + ", token : " + token + " auth : " + authUser);
memberProfileManager.verifyUserEmail(handle, authUser, newEmail, oldEmail, token);
return ApiResponseFactory.createResponse(null);
} catch (Throwable ex) {
return ErrorHandler.handle(ex, logger);
}
}
/**
* Generate photo Upload url
* @param handle Handle of the user
* @param authUser Auth user
* @return ApiResponse Api response
*/
@POST
@Timed
@Path("photoUploadUrl")
public ApiResponse generatePhotoUploadUrl(@PathParam("handle") String handle, @Auth AuthUser authUser,
@Valid PostPutRequest<PhotoContentType> postPutRequest) {
try {
logger.debug("generatePhotoUploadUrl, handle : " + handle + " auth : " + authUser);
PhotoContentType photoContentType = postPutRequest.getParam();
return ApiResponseFactory.createResponse(memberProfileManager.
generatePhotoUploadUrl(handle, authUser, photoContentType));
} catch (Throwable ex) {
return ErrorHandler.handle(ex, logger);
}
}
/**
* Update photo
* @param handle Handle of the user
* @param authUser Auth user
* @return ApiResponse Api response
*/
@PUT
@Timed
@Path("photo")
public ApiResponse updatePhoto(@PathParam("handle") String handle, @Auth AuthUser authUser,
@Valid PostPutRequest<PhotoTokenContentType> postPutRequest) {
try {
logger.debug("updatePhoto, handle : " + handle + " auth : " + authUser);
PhotoTokenContentType photoTokenContentType = postPutRequest.getParam();
String photoURL = memberProfileManager.updatePhoto(handle, authUser, photoTokenContentType);
return ApiResponseFactory.createResponse(photoURL);
} catch (Throwable ex) {
return ErrorHandler.handle(ex, logger);
}
}
}
|
package com.example.qunxin.erp.activity;
import android.app.Dialog;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import com.alibaba.fastjson.JSON;
import com.example.qunxin.erp.R;
import com.example.qunxin.erp.UserBaseDatus;
import com.example.qunxin.erp.modle.ShangpinBaseDatus;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import swipedelete.utils.CommonAdapter;
import swipedelete.utils.ViewHolder;
public class AddcaigouYixuanshangpinActivity extends AppCompatActivity implements View.OnClickListener {
View backBtn;
ListView listView;
Button finishBtn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_addcaigou_yixuanshangpin);
initView();
}
String dateList;
String supplier;
void initView(){
backBtn=findViewById(R.id.back);
listView=findViewById(R.id.listview);
finishBtn=findViewById(R.id.finish);
backBtn.setOnClickListener(this);
finishBtn.setOnClickListener(this);
Intent intent=getIntent();
dateList=intent.getStringExtra("dateList");
supplier=intent.getStringExtra("supplier");
Log.d("dateList", dateList);
jsonParse();
loadView();
TextChange();
}
List<ShangpinBaseDatus> lists=new ArrayList<>();
void jsonParse(){
if("".equals(dateList)){
lists.clear();
return;
}
try {
JSONArray jsonArray=new JSONArray(dateList);
for (int i=0;i<jsonArray.length();i++){
JSONObject jsonObject=jsonArray.getJSONObject(i);
String proName=jsonObject.getString("proName");
String price=jsonObject.getString("price");
String proId=jsonObject.getString("proId");
String norms=jsonObject.getString("norms");
String property=jsonObject.getString("property");
String remarks=jsonObject.getString("remarks");
String total=jsonObject.getString("purchaseAmount");
String totalAmount=jsonObject.getString("totalAmount");
String unit=jsonObject.getString("unit");
ShangpinBaseDatus datus = new ShangpinBaseDatus();
datus.setPrice(Float.parseFloat(price));
datus.setProName(proName);
datus.setProId(proId);
datus.setNorms(norms);
datus.setProperty(property);
datus.setRemarks(remarks);
datus.setTotal(Integer.parseInt(total));
datus.setTotalAmount(Float.parseFloat(totalAmount));
datus.setUnit(unit);
datus.setImgRes(R.mipmap.shop_icon);
lists.add(datus);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
String jsonToString() {
StringBuffer buffer=new StringBuffer();
for (int i=0;i<lists.size();i++){
JSONObject jsonObject=new JSONObject();
try {
if(lists.get(i).getTotal()==0) break;
// jsonObject.put("norms",lists.get(i).getNorms());
// jsonObject.put("property",lists.get(i).getProperty());
// jsonObject.put("price",lists.get(i).getPrice());
// jsonObject.put("proId",lists.get(i).getProId());
// jsonObject.put("proName",lists.get(i).getProName());
// jsonObject.put("remarks",lists.get(i).getRemarks());
// jsonObject.put("total",lists.get(i).getTotal());
// jsonObject.put("totalAmount",lists.get(i).getTotalAmount());
// jsonObject.put("unit",lists.get(i).getUnit());
// jsonObject.put("proNo",lists.get(i).getProNo());
jsonObject.put("actualPurchaseQuantity",lists.get(i).getTotal());
jsonObject.put("applicationAllowance",0);
jsonObject.put("createBy",UserBaseDatus.getInstance().userId);
jsonObject.put("createTime","");
jsonObject.put("delFlag",0);
jsonObject.put("deliveryDate","");
jsonObject.put("id","");
jsonObject.put("marketAmount",lists.get(i).getPrice());
jsonObject.put("orderQuantity",lists.get(i).getTotal());
jsonObject.put("proId",lists.get(i).getProId());
jsonObject.put("purchaseId","");
jsonObject.put("purchaseAmount",lists.get(i).getTotal());
jsonObject.put("remark","");
jsonObject.put("searchValue","");
jsonObject.put("supplier",supplier);
jsonObject.put("updateBy",UserBaseDatus.getInstance().userId);
jsonObject.put("updateTime","");
jsonObject.put("norms",lists.get(i).getNorms());
jsonObject.put("proName",lists.get(i).getProName());
jsonObject.put("remarks",lists.get(i).getRemarks());
jsonObject.put("unit",lists.get(i).getUnit());
jsonObject.put("price",lists.get(i).getPrice());
jsonObject.put("totalAmount",lists.get(i).getPrice()*lists.get(i).getTotal());
jsonObject.put("property",lists.get(i).getProperty());
String content=String.valueOf(jsonObject);
buffer.append(content).append(",");
} catch (JSONException e) {
e.printStackTrace();
}
}
String s= buffer.toString();
if("".equals(s)){
return "";
}
return "["+s.substring(0,s.length()-1)+"]";
}
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.back:
finish();
break;
case R.id.finish:
finishBtn();
break;
}
}
void loadView(){
listView.setAdapter(new CommonAdapter<ShangpinBaseDatus>(AddcaigouYixuanshangpinActivity.this,lists, R.layout.item_yixuanshangpin) {
@Override
public void convert(final ViewHolder holder, ShangpinBaseDatus shangpinDatus, final int position, View convertView) {
holder.setText(R.id.name,shangpinDatus.getProName());
holder.setText(R.id.totalAmount,shangpinDatus.getTotalAmount()+"");
holder.setText(R.id.unit,shangpinDatus.getUnit());
holder.setText(R.id.count,shangpinDatus.getTotal()+"");
holder.setText(R.id.detail,"¥"+shangpinDatus.getPrice()+"*"+shangpinDatus.getTotal()+shangpinDatus.getUnit());
holder.setOnClickListener(R.id.ll_content, new View.OnClickListener() {
@Override
public void onClick(View v) {
}
});
final int[] amount = {shangpinDatus.getTotal()};
final TextView etAmount=holder.getView(R.id.count);
holder.setOnClickListener(R.id.btnIncrease, new View.OnClickListener() {
@Override
public void onClick(View v) {
amount[0]++;
etAmount.setText(amount[0]+"");
ShangpinBaseDatus datus=lists.get(position);
datus.setTotal(Integer.parseInt(etAmount.getText().toString()));
datus.setTotalAmount(datus.getPrice()*datus.getTotal());
holder.setText(R.id.totalAmount,datus.getTotalAmount()+"¥");
holder.setText(R.id.detail,"¥"+datus.getPrice()+"*"+datus.getTotal()+datus.getUnit());
TextChange();
}
});
holder.setOnClickListener(R.id.btnDecrease, new View.OnClickListener() {
@Override
public void onClick(View v) {
if(amount[0] <=0){
return;
}
amount[0]--;
etAmount.setText(amount[0]+"");
ShangpinBaseDatus datus=lists.get(position);
datus.setTotal(Integer.parseInt(etAmount.getText().toString()));
datus.setTotalAmount(datus.getTotal()*datus.getPrice());
holder.setText(R.id.totalAmount,datus.getTotalAmount()+"");
holder.setText(R.id.detail,"¥"+datus.getPrice()+"*"+datus.getTotal()+datus.getUnit());
TextChange();
}
});
}
});
}
int getTotal(){
int total=0;
for(int i=0;i<lists.size();i++){
total+=lists.get(i).getTotal();
}
return total;
}
float getTotalAmount(){
int totalAmount=0;
for(int i=0;i<lists.size();i++){
totalAmount+=lists.get(i).getTotal()*lists.get(i).getPrice();
}
return totalAmount;
}
void TextChange(){
int size=lists.size();
int total=getTotal();
float totalAmount=getTotalAmount();
String s="结算({0}种共{1}件,¥{2})";
finishBtn.setText(MessageFormat.format(s,size,total,totalAmount));
}
void finishBtn(){
if(lists.size()==0){
Toast.makeText(this, "请添加商品", Toast.LENGTH_SHORT).show();
String s="结算({0}种共{1}件,¥{2})";
finishBtn.setText(MessageFormat.format(s,lists.size(),0,0));
return;
}
if(getTotal()==0){
Toast.makeText(this, "请添加商品", Toast.LENGTH_SHORT).show();
String s="结算({0}种共{1}件,¥{2})";
finishBtn.setText(MessageFormat.format(s,0,0,0));
return;
}
Intent intent=new Intent();
dateList=jsonToString();
intent.putExtra("dateList",dateList);
intent.putExtra("count",getTotal());
intent.putExtra("totalAmount",getTotalAmount());
setResult(3,intent);
finish();
}
}
|
package com.orlanth23.popularmovie.fragment;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import com.orlanth23.popularmovie.R;
// This custom fragment adds a new method to Fragment class. Then we can change title depending on preferences.
public abstract class CustomFragment extends Fragment{
protected void changeTitleFragment(){
// change title depending on the preference
ActionBar actionBar = ((AppCompatActivity)getActivity()).getSupportActionBar();
if (actionBar != null){
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
String defaultValue = getString(R.string.popularMovies);
String switchValue = prefs.getString(getString(R.string.pref_key_list_sort), defaultValue);
switch (switchValue){
case "popularMovies":
actionBar.setTitle(R.string.pref_popular_movies_title);
break;
case "topRated":
actionBar.setTitle(R.string.pref_top_rated_title);
break;
case "favorite":
actionBar.setTitle(R.string.pref_favorite_title);
break;
}
}
}
}
|
package com.concurrent.retreiver;
import akka.dispatch.ExecutionContexts;
import akka.japi.JavaPartialFunction;
import com.concurrent.gateway.SiteReader;
import com.concurrent.gateway.SiteWriter;
import com.concurrent.usecase.SiteProcessor;
import com.google.common.collect.ImmutableList;
import org.jsoup.nodes.Document;
import scala.concurrent.Await;
import scala.concurrent.ExecutionContext;
import scala.concurrent.Future;
import scala.concurrent.duration.Duration;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import static akka.dispatch.Futures.future;
import static akka.dispatch.Futures.sequence;
import static com.google.common.collect.ImmutableList.Builder;
import static java.util.concurrent.TimeUnit.SECONDS;
public class ConcurrentHttpSiteProcessor implements SiteProcessor {
private final SiteReader reader;
private final SiteWriter writer;
private final int threadPool;
public ConcurrentHttpSiteProcessor(SiteReader reader, SiteWriter writer, int threadPool) {
this.reader = reader;
this.writer = writer;
this.threadPool = threadPool;
}
@Override
public void process(String url) {
process(new Builder<String>().add(url).build());
}
@Override
public void process(ImmutableList<String> urls) {
ExecutorService executor = Executors.newFixedThreadPool(threadPool);
ExecutionContext ec = ExecutionContexts.fromExecutorService(executor);
Builder<Future<Document>> builder = ImmutableList.builder();
for (final String url : urls) {
builder.add(createFuture(ec, url));
}
Future<Iterable<Document>> futuresSequence = sequence(builder.build(), ec);
futuresSequence.map(new JavaPartialFunction<Iterable<Document>, Object>() {
@Override
public Object apply(final Iterable<Document> docs, final boolean isCheck) throws Exception {
for (Document doc : docs) {
writer.write(doc);
}
return null;
}
}, ec);
try {
Await.result(futuresSequence, Duration.create(20, SECONDS));
} catch (Exception e) {
throw new RuntimeException();
}
executor.shutdown();
}
private Future<Document> createFuture(final ExecutionContext ec, final String url) {
return future(new Callable<Document>() {
public Document call() {
System.out.println("before sleep url: " + url);
try {
Thread.sleep((long) (Math.random() * 1000));
} catch (InterruptedException e) {
throw new RuntimeException("Problem sleeping");
}
System.out.println("after sleep url: " + url);
return reader.retrieve(url);
}
}, ec);
}
}
|
package com.group.etoko.Fragment.HomeFragment.adapter;
import android.content.Context;
import android.graphics.Paint;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.navigation.Navigation;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import com.group.etoko.Activity.main_activity.ClickListner.MyRecyclerItemClickListner;
import com.group.etoko.BuildConfig;
import com.group.etoko.R;
import com.group.etoko.util.Constants;
import com.group.etoko.Database.dao.CartDao;
import com.group.etoko.Database.dao.ProductDao;
import com.group.etoko.Database.db.LocalDatabase;
import com.group.etoko.model.Cart;
import com.group.etoko.model.Product;
import com.group.etoko.util.MySharedPreference;
import java.util.List;
import static com.group.etoko.util.Constants.CATEGORY;
import static com.group.etoko.util.Constants.PRODUCT_ID;
import static com.group.etoko.util.Constants.RECYCLER_ITEM_POSITION;
public class AdapterExclusiveOffer extends RecyclerView.Adapter<AdapterExclusiveOffer.ExclusiveViewHolder> {
private List<Product> products;
private MyRecyclerItemClickListner itemClickListner;
CartDao cartDao;
ProductDao productDao;
Cart cart=new Cart();
static int c=0;
LocalDatabase db;
private Context context;
public AdapterExclusiveOffer(List<Product> products,Context context) {
this.products = products;
db =LocalDatabase.getReferences(context);
cartDao=db.cartDao();
productDao= db.productDao();
this.context=context;
}
public AdapterExclusiveOffer(List<Product> products, MyRecyclerItemClickListner itemClickListner) {
this.products = products;
this.itemClickListner = itemClickListner;
}
@NonNull
@Override
public ExclusiveViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.item_home_product_adptr, parent, false);
return itemClickListner != null ? new ExclusiveViewHolder(view,itemClickListner):new ExclusiveViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull ExclusiveViewHolder holder, int position) {
Product product = products.get(position);
holder.Name.setText(product.getProductName());
holder.weight.setText(product.getProductMeasurement()+" "+product.getProductUnit());
holder.unitprice.setText(Constants.Taka_sign+product.getProductUnitPrice());
holder.BtnDecrease.setVisibility(View.INVISIBLE);
Glide.with(holder.itemView.getContext())
.load(BuildConfig.BASE_URL + product.getProductPrimaryImage())
.placeholder(R.drawable.placeholderimage)
.into(holder.productImage);
if(product.getProductIsFeatured().equals("1")){
holder.ItemFeaturedIv.setVisibility(View.VISIBLE);
}
// if have discount-----------
if (product.getProductIsDiscount().equals("1")) {
holder.orginalprice.setVisibility(View.VISIBLE);
holder.orginalprice.setText(Constants.Taka_sign +product.getProductOriginalPrice());
holder.orginalprice.setPaintFlags(holder.orginalprice.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
//discount amount------
holder.DiscountAmount.setVisibility(View.VISIBLE);
holder.DiscountAmount.setText(Constants.Taka_sign+product.getProductDiscountAmount()+" off");
}
else{
holder.orginalprice.setVisibility(View.INVISIBLE);
holder.DiscountAmount.setVisibility(View.INVISIBLE);
}
if (Integer.parseInt(product.getProductIsAvailable())==1){
//if product is in cart-----------
if(Integer.parseInt(product.getProductQty())>0 ){
holder.AddToBag.setVisibility(View.INVISIBLE);
holder.QTY.setVisibility(View.VISIBLE);
holder.QTY.setText(product.getProductQty());
holder.BtnIncrease.setVisibility(View.VISIBLE);
holder.BtnDecrease.setVisibility(View.VISIBLE);
}
else{
holder.AddToBag.setClickable(true);
holder.AddToBag.setVisibility(View.VISIBLE);
holder.QTY.setVisibility(View.INVISIBLE);
holder.AddToBag.setText("Add to Bag");
holder.BtnIncrease.setVisibility(View.VISIBLE);
}
}
else{
holder.AddToBag.setVisibility(View.VISIBLE);
holder.AddToBag.setClickable(false);
holder.AddToBag.setText("Out of Stock");
holder.QTY.setVisibility(View.GONE);
holder.BtnIncrease.setVisibility(View.GONE);
holder.BtnDecrease.setVisibility(View.GONE);
}
holder.BtnIncrease.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
int count=0;
count=Integer.parseInt(product.getProductQty());
holder.AddToBag.setVisibility(View.INVISIBLE);
holder.QTY.setVisibility(View.VISIBLE);
holder.BtnDecrease.setVisibility(View.VISIBLE);
count++;
cart.setProductCount(count);
cart.setProductId(product.getProductId());
if(count==1){
new InsertToCart(cartDao,productDao).execute(cart);
}
else {
new UpdateDeleteToCart(cartDao, productDao).execute(cart);
}
MySharedPreference.getInstance(context)
.edit()
.putInt(RECYCLER_ITEM_POSITION,position)
.apply();
product.setProductQty(String.valueOf(count));
holder.QTY.setText(String.valueOf(count));
}
});
holder.BtnDecrease.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
int count=0;
count=Integer.parseInt(product.getProductQty());
if(count>1){
count--;
cart.setProductCount(count);
cart.setProductId(product.getProductId());
new UpdateDeleteToCart(cartDao,productDao).execute(cart);
product.setProductQty(String.valueOf(count));
holder.QTY.setText(String.valueOf(count));
}
else if(count==1){
count--;
cart.setProductCount(count);
cart.setProductId(product.getProductId());
new UpdateDeleteToCart(cartDao,productDao).execute(cart);
product.setProductQty(String.valueOf(count));
holder.BtnDecrease.setVisibility(View.INVISIBLE);
holder.QTY.setVisibility(View.INVISIBLE);
holder.AddToBag.setVisibility(View.VISIBLE);
holder.AddToBag.setText("Add to Bag");
}
MySharedPreference.getInstance(context)
.edit()
.putInt(RECYCLER_ITEM_POSITION,position)
.apply();
}
});
}
@Override
public int getItemCount() {
if (products.size() < 20) {
return products.size();
}
return 20 - 1;
}
public class ExclusiveViewHolder extends RecyclerView.ViewHolder {
private TextView Name;
private TextView unitprice;
private TextView orginalprice;
private TextView weight;
private ImageView productImage;
private ImageView BtnIncrease;
private ImageView BtnDecrease,ItemFeaturedIv;
private TextView DiscountAmount;
private TextView AddToBag;
private TextView QTY;
private MyRecyclerItemClickListner itemClickListner;
public ExclusiveViewHolder(View itemView) {
super(itemView);
Name = itemView.findViewById(R.id.item_product_name_tv);
unitprice = itemView.findViewById(R.id.item_current_price_tv);
orginalprice = itemView.findViewById(R.id.item_prev_price_tv);
weight = itemView.findViewById(R.id.item_weight_tv);
productImage = itemView.findViewById(R.id.item_product_image);
DiscountAmount = itemView.findViewById(R.id.item_discount_tv);
ItemFeaturedIv=itemView.findViewById(R.id.item_featured_image);
BtnIncrease=itemView.findViewById(R.id.item_bt_increase);
BtnDecrease=itemView.findViewById(R.id.item_bt_decrease);
AddToBag=itemView.findViewById(R.id.item_add_to_cart_tv);
QTY=itemView.findViewById(R.id.item_in_cart_quantity_tv);
itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Bundle bundle=new Bundle();
bundle.putString(PRODUCT_ID,products.get(getAdapterPosition()).getProductId());
bundle.putString(CATEGORY,products.get(getAdapterPosition()).getCategoryID());
Navigation.findNavController(itemView).navigate(R.id.action_global_productDetailsFragment,bundle);
}
});
}
public ExclusiveViewHolder(View itemView, MyRecyclerItemClickListner itemClickListner) {
super(itemView);
Name = itemView.findViewById(R.id.item_product_name_tv);
unitprice = itemView.findViewById(R.id.item_current_price_tv);
orginalprice = itemView.findViewById(R.id.item_prev_price_tv);
weight = itemView.findViewById(R.id.item_weight_tv);
productImage = itemView.findViewById(R.id.item_product_image);
DiscountAmount = itemView.findViewById(R.id.item_discount_tv);
this.itemClickListner=itemClickListner;
itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
itemClickListner.item(getAdapterPosition(),v);
}
});
}
}
public class UpdateDeleteToCart extends AsyncTask<Cart,Void,Void > {
private CartDao cartDao;
private ProductDao productDao;
public UpdateDeleteToCart(CartDao cartDao, ProductDao productDao){
this.cartDao=cartDao;
this.productDao=productDao;
}
@Override
protected Void doInBackground(Cart... carts) {
productDao.updateQtyById(String.valueOf(carts[0].getProductCount()),String.valueOf(carts[0].getProductId()));
if(cart.getProductCount()<1){
cartDao.DeleteByProductId(carts[0].getProductId());
}
else{
cartDao.updateByProductId(carts[0].getProductCount(),carts[0].getProductId());
}
return null;
}
}
public class InsertToCart extends AsyncTask<Cart,Void,Void> {
private CartDao cartDao;
private ProductDao productDao;
public InsertToCart(CartDao cartDao,ProductDao productDao){
this.cartDao=cartDao;
this.productDao=productDao;
}
@Override
protected Void doInBackground(Cart... carts) {
productDao.updateQtyById(String.valueOf(carts[0].getProductCount()),String.valueOf(carts[0].getProductId()));
cartDao.insert(carts[0]);
return null;
}
}
}
|
package com.example.hyunyoungpark.flagquizapp;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Toast;
public class ResultDialog extends DialogFragment {
private int totalGuess = 1;
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder dialog = new AlertDialog.Builder(getActivity());
//totalGuess = getArguments().getInt("count");
totalGuess = MainActivityFragment.guessCount;
dialog.setMessage("Your score is " + 1000/totalGuess + " %. \n" + "You took "+ totalGuess + " times for guessing. \n\n Do you want to Restart the Quiz?")
.setPositiveButton("RESET_QUIZ", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
Activity activity = getActivity();
Intent intent = new Intent(activity, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); // completely cleared the entire stack and made the new activity the only one in the app
activity.finish();
startActivity(intent);
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
Toast.makeText(getContext(), "Cancel", Toast.LENGTH_SHORT);
}
});
return dialog.create();
}
} |
package com.bistel.storm.bolt.esper;
import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.zip.DataFormatException;
import org.slf4j.Logger;
import backtype.storm.task.OutputCollector;
import backtype.storm.task.TopologyContext;
import backtype.storm.topology.OutputFieldsDeclarer;
import backtype.storm.topology.base.BaseRichBolt;
import backtype.storm.tuple.Fields;
import backtype.storm.tuple.Tuple;
import com.bistel.ce.MessagingClient;
import com.bistel.ce.summarization.EsperEventsHelper;
import com.bistel.ce.summarization.SubstrateIdEsperEventSummarizer;
import com.bistel.configuration.ConfigConstants;
import com.bistel.configuration.ConfigurationManager;
import com.bistel.logging.util.LogUtil;
import com.bistel.tracereport.convertor.ServiceMessageConvertor;
import com.bistel.tracereport.model.EventParameterInfo;
import com.bistel.tracereport.model.ModuleTraceInfo;
import com.bistel.tracereport.model.ParameterItem;
import com.bistel.tracereport.model.TraceReportInfo;
import com.bistel.tracesummary.model.OnDemandTraceSummaryRequestInfo;
import com.bistel.util.CompressionUtils;
import com.bistel.util.ObjectConvertorUtils;
import com.espertech.esper.client.EPServiceProvider;
/**
* This Bolt uses Esper Engine to provide summarization for LOT ID Change and Substrate ID Change
*
*
*/
public class EsperEventBolt extends BaseRichBolt {
private static final long serialVersionUID = 5405324908183350416L;
ConfigurationManager cm = null;
OutputCollector _collector;
private static Logger _logger = LogUtil.getLogger(EsperEventBolt.class);
EPServiceProvider epService=null;
private Map<String,String> lotIdMap= null;
private Map<String,Long> lotStartTimeMap= null;
private Map<String,Long> lotEndTimeMap= null;
private Map<String,String> substrateIdMap= null;
private Map<String,AtomicInteger> moduleSubstrateMessagesCountMap=null;
private int moduleSubstrateMessageSkipThreshold;
private boolean sendAllModuleToEsperFlag=false;
@Override
public void prepare(Map conf, TopologyContext context, OutputCollector collector) {
if (_logger.isDebugEnabled()) {
_logger.debug("EsperEventBolt Prepare Method called");
}
cm = ConfigurationManager.getInstance(ConfigConstants.DEFAULT_RESOURCE_NAME);
// Get the Esper Instance which has all module windows intialized
epService = EsperEventsHelper.getEngineInstanceWithSummaryWindows(EsperEventBolt.class.getName());
lotIdMap = new HashMap<String, String>();
substrateIdMap = new HashMap<String, String>();
lotStartTimeMap = new HashMap<String, Long>();
lotEndTimeMap = new HashMap<String, Long>();
moduleSubstrateMessagesCountMap= new HashMap<String, AtomicInteger>();
moduleSubstrateMessageSkipThreshold= Integer.parseInt(cm.getConfiguration("bolt.esper.module.message.threshold"));
//IF the limit is configured negative or zero then send all modules to esper.
if(moduleSubstrateMessageSkipThreshold<=0){
sendAllModuleToEsperFlag=true;
}
_collector = collector;
}
@Override
public void execute(Tuple tuple) {
long startTime = System.currentTimeMillis();
Long previousStepEmitTime = tuple.getLong(3);
if(_logger.isWarnEnabled() && (System.currentTimeMillis() - previousStepEmitTime) > 10) {
_logger.warn("EsperBolt time difference in receiving the event:" + (System.currentTimeMillis() - previousStepEmitTime));
}
TraceReportInfo traceReportInfo = getTraceReportInfo(tuple);
checkForSummarization(traceReportInfo);
long endProcessTime = System.currentTimeMillis();
if( _logger.isWarnEnabled() && (endProcessTime - startTime) > 20 ) {
_logger.warn("Time taken in EsperEventBolt Process: "+ (endProcessTime - startTime));
}
_collector.ack(tuple);
long endTime = System.currentTimeMillis();
if( _logger.isWarnEnabled() && (endTime - startTime) > 20 ) {
_logger.warn("Time taken in EsperEventBolt Ack: "+ (endTime - startTime));
}
traceReportInfo=null;
}
private TraceReportInfo getTraceReportInfo(Tuple tuple) {
byte[] tracesummaryBytes= (byte[])tuple.getValue(2);
TraceReportInfo traceReportInfo = null;
try {
traceReportInfo = (TraceReportInfo) ObjectConvertorUtils.toObject(CompressionUtils.decompress(tracesummaryBytes));
} catch (IOException e) {
_logger.error("Error while deserialising object", e);
} catch (ClassNotFoundException e) {
_logger.error("Error while deserialising object", e);
} catch (DataFormatException e) {
_logger.error("Error while deserialising object", e);
}
return traceReportInfo;
}
@Override
public void declareOutputFields(OutputFieldsDeclarer declarer) {
}
/**
* Check for change in susbstrateId.
* If there is a change in the substrateId, the do the summarisation for the old substrateId.
*
* @param moduleKey
* @param module
*/
private void checkSubstrateIdChangeSummarizer(String moduleKey , ModuleTraceInfo module){
// Check for substrateid change
String oldSubstrateId= substrateIdMap.get(moduleKey);
if(null==oldSubstrateId){
oldSubstrateId= module.getSubstrateId();
substrateIdMap.put(moduleKey,oldSubstrateId);
//lotIdMap.put(moduleKey, module.getLotId());
}else if(!oldSubstrateId.equalsIgnoreCase(module.getSubstrateId())){ // Case when oldSubstrateId is not equal to current substrateId.
if (_logger.isDebugEnabled()) {
_logger.debug("Substrate ID changed for "+moduleKey+" from "+oldSubstrateId + " To "+module.getSubstrateId());
_logger.debug("Invoking SubstrateIdEsperEventSummarizer");
}
// Execute the summarization of parameters in a different thread.
SubstrateIdEsperEventSummarizer summarizer = new SubstrateIdEsperEventSummarizer(epService, module.getStepId(),module.getToolId(), module.getId(),lotIdMap.get(moduleKey),oldSubstrateId );
EsperEventsHelper.getSubstrateIdChangeExecutor().execute(summarizer);
// Increment the count for Running SubstrateChange Threads for this lot id.
//EsperEventsHelper.getSubstrateChangeRunningCount(lotId).incrementAndGet();
substrateIdMap.put(moduleKey,module.getSubstrateId());
//lotIdMap.put(moduleKey, module.getLotId());
if(!sendAllModuleToEsperFlag){
getModulSubstrateMessageCount(moduleKey).set(0);
}
}
}
/**
* Check for change in susbstrateId for the given lot.
* If there is a change in the substrateId, the do the summarisation for the old substrateId.
*
* @param moduleKey
* @param module
* @param lotId
*/
/*private void checkSubstrateIdChangeSummarizer(String moduleKey , ModuleTraceInfo module, String lotId){
// Check for substrateid change
String oldSubstrateId= substrateIdMap.get(moduleKey);
if(null==oldSubstrateId){
oldSubstrateId= module.getSubstrateId();
substrateIdMap.put(moduleKey,oldSubstrateId);
}else if(!oldSubstrateId.equalsIgnoreCase(module.getSubstrateId())){ // Case when oldSubstrateId is not equal to current substrateId.
if (_logger.isWarnEnabled()) {
_logger.warn("Substrate ID changed for "+moduleKey+" from "+oldSubstrateId + " To "+module.getSubstrateId());
_logger.warn("Invoking SubstrateIdEsperEventSummarizer");
}
// Execute the summarization of parameters in a different thread.
SubstrateIdEsperEventSummarizer summarizer = new SubstrateIdEsperEventSummarizer(epService, module.getStepId(),module.getToolId(), module.getId(),lotId,oldSubstrateId );
EsperEventsHelper.getSubstrateIdChangeExecutor().execute(summarizer);
// Increment the count for Running SubstrateChange Threads for this lot id.
//EsperEventsHelper.getSubstrateChangeRunningCount(lotId).incrementAndGet();
substrateIdMap.put(moduleKey,module.getSubstrateId());
}
}*/
/**
* Checks for the summarisation.
* If there is any change in the substrateId or lotId, then invoke the respective summarisation.
*
* @param tracereport
*/
private void checkForSummarization(TraceReportInfo tracereport){
String stepId = tracereport.getToolTraceInfo().getStep();
String toolId = tracereport.getToolTraceInfo().getTool();
// Identify which modules to be sent for real time analysis
Map<String,ModuleTraceInfo> modules= EsperEventsHelper.getModulesForEsper(tracereport) ;
if(null!=modules){
for(ModuleTraceInfo module: modules.values()){
String moduleKey= EsperEventsHelper.getModuleKey(stepId, toolId, module.getId());
checkSubstrateIdChangeSummarizer(moduleKey, module);
String oldLotId= lotIdMap.get(moduleKey);
// Detect the change in Lot Id for a module
if(null==oldLotId){
oldLotId=module.getLotId();
lotIdMap.put(moduleKey,oldLotId);
substrateIdMap.put(moduleKey,module.getSubstrateId());
lotStartTimeMap.put(moduleKey, module.getTracetime());
}else if( oldLotId.equalsIgnoreCase(module.getLotId())){
checkSubstrateIdChangeSummarizer(moduleKey, module);
}else{ // Case when oldLotId is not equal to current lotId.
if (_logger.isDebugEnabled()) {
_logger.debug("Lot ID changed for "+moduleKey+" from "+oldLotId + " To "+module.getLotId());
}
checkSubstrateIdChangeSummarizer(moduleKey, module);
// Send AdHOC Summarization request for LOTID Change summarization.
OnDemandTraceSummaryRequestInfo lotSumaryReqInfo= new OnDemandTraceSummaryRequestInfo();
lotSumaryReqInfo.setStepId(stepId);
lotSumaryReqInfo.setToolId(toolId);
lotSumaryReqInfo.setModuleId(module.getId());
lotSumaryReqInfo.setLotId(oldLotId);
lotSumaryReqInfo.setStartTime(lotStartTimeMap.get(moduleKey));
lotSumaryReqInfo.setEndTime(lotEndTimeMap.get(moduleKey));
EsperEventsHelper.sendAdHocLOTIDSummarizationRequest(lotSumaryReqInfo);
lotIdMap.put(moduleKey,module.getLotId());
lotStartTimeMap.put(moduleKey, module.getTracetime());
}
lotEndTimeMap.put(moduleKey, module.getTracetime());
/*for (ParameterItem item : module.getParameter().getItems().values()) {
EventParameterInfo paramInfo = new EventParameterInfo(stepId, toolId, module.getId(), module.getLotId(),
module.getSubstrateId(), null, item.getName(), (float)item.getValue(), item.getFault(), module.getTracetime());
epService.getEPRuntime().sendEvent(item);
}*/
if(sendAllModuleToEsperFlag){
module.setContext(null);
epService.getEPRuntime().sendEvent(module);
}else{
int moduleSubstrateMessageNum=getModulSubstrateMessageCount(moduleKey).incrementAndGet();
// Check if message needs to be sent to Esper window or not. if the value of moduleSubstrateMessageSkipThreshold is 180, then messages sent will be like 1, 181, 361 .... etc for a particular LOT
if((moduleSubstrateMessageNum%moduleSubstrateMessageSkipThreshold)==1){
if(_logger.isDebugEnabled()){
_logger.debug("Sending message to Esper Engine for message "+moduleSubstrateMessageNum +"for module"+moduleKey);
}
// Prepare a list of ParameterItem objects for module and reset Context and Parameter for module.
// As it has been observerd that Map for ParameterItem takes more memory in window.
/*List<ParameterItem> parameterList= new LinkedList<ParameterItem>(module.getParameter().getItems().values());
Collections.sort(parameterList);
module.setParameterItems(parameterList);
module.setParameter(null);*/
module.setContext(null);
epService.getEPRuntime().sendEvent(module);
}
}
}
}
}
/**
* The method returns count of messages for the module for the current running Substrate ID
* @param moduleKey
* @return AtomicInteger-count of messages for the module for the current running Substrate ID
*/
private AtomicInteger getModulSubstrateMessageCount(String moduleKey){
AtomicInteger moduleMessageCount = moduleSubstrateMessagesCountMap.get(moduleKey);
if(null == moduleMessageCount ){
moduleMessageCount = new AtomicInteger();
moduleSubstrateMessagesCountMap.put(moduleKey, moduleMessageCount);
}
return moduleMessageCount;
}
}
|
package basic.dialog;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.beans.value.WritableDoubleValue;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Menu;
import javafx.scene.control.MenuBar;
import javafx.scene.control.MenuItem;
import javafx.scene.control.SeparatorMenuItem;
import javafx.scene.control.TextArea;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.FlowPane;
import javafx.stage.FileChooser;
import javafx.stage.FileChooser.ExtensionFilter;
import javafx.stage.Stage;
public class DialogTest2 extends Application {
@Override
public void start(Stage primaryStage) {
BorderPane root = new BorderPane();
MenuBar menuBar = new MenuBar();
menuBar.prefWidthProperty().bind(primaryStage.widthProperty());
root.setTop(menuBar);
// textarea 만들어 주기
TextArea textarea = new TextArea();
menuBar.prefWidthProperty().bind(primaryStage.widthProperty());
root.setCenter(textarea);
// menu객체 생성
Menu fileMenu = new Menu("File");
// 새로만들기
MenuItem newMenuItem = new MenuItem("새로만들기");
newMenuItem.setOnAction(e->{
textarea.clear(); //textarea창을 지워주는 거
primaryStage.setTitle("NoName.txt");
});
// 열기
MenuItem openMenuItem = new MenuItem("열기");
openMenuItem.setOnAction(e->{
FileChooser fileChooser = new FileChooser();
fileChooser.getExtensionFilters().addAll(
new ExtensionFilter("Text File","*.txt"),
new ExtensionFilter("ALL Files", "*.*")
);
// 창이 열렸을 때 보여줄 폴더(디렉토리) 설정
File showDir = new File("d:/D_Other/");
fileChooser.setInitialDirectory(showDir);
// '열기' 창을 보여주고 사용자가 선택한 파일 정보를 반환한다.
File selectedFile = fileChooser.showOpenDialog(primaryStage);
String ss = null;
if(selectedFile !=null) {
try {
primaryStage.setTitle(selectedFile.getName());
FileInputStream fin = new FileInputStream(selectedFile);
int s = 0; // 읽어온 자료를 저장 할 변수
while((s=fin.read()) != -1) {
ss += (char)s;
}
textarea.setText(ss);
fin.close(); // 작업 완류 후 스트림 닫기
} catch (IOException e2) {
System.out.println("파일이 없거나 읽기 오류입니다.");
}
}
});
// 새이름으로 저장하기
MenuItem saveMenuItem = new MenuItem("새이름으로 저장");
saveMenuItem.setOnAction(e->{
// 파일 탐색기 같은 기능
FileChooser fileChooser = new FileChooser();
// 어떤 확장자를 선택할지를 결정
fileChooser.getExtensionFilters().addAll(
new ExtensionFilter("Text File", "*.txt"),
new ExtensionFilter("Image", "*.png","*.jpg","*.gif")
);
// 해당된 파일의 경로만 가지고 있는 거
File selectedFile = fileChooser.showSaveDialog(primaryStage);
if(selectedFile !=null) {
try {
// System.out.println(selectedFile.toString());
primaryStage.setTitle(selectedFile.getName());
FileOutputStream fout = new FileOutputStream(selectedFile);
fout.write(textarea.getText().getBytes());
fout.close();
} catch (IOException e2) {
// TODO: handle exception
}
}
});
// exit를 누르면 나가는거
MenuItem exitMenuItem = new MenuItem("닫기");
exitMenuItem.setOnAction(e->{
Platform.exit();
});
// menuBar에 file 붙이는거
menuBar.getMenus().addAll(fileMenu);
//filemenu에 붙이기
fileMenu.getItems().addAll(newMenuItem,openMenuItem,saveMenuItem,
new SeparatorMenuItem(),exitMenuItem);
Scene scene = new Scene(root,300,250);
primaryStage.setScene(scene);
primaryStage.setTitle("NoName.txt");
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
|
package RestAssured;
import java.util.HashMap;
import com.sun.xml.xsom.impl.scd.Iterators.Map;
public class ApiAutomation {
public static void main(String args[]){
String a ="AAABBCCCC444444EEEEe";
int intialLength =1;
StringBuilder string = new StringBuilder();
for(int i=1;i<a.length();i++){
if(a.charAt(i)==a.charAt(i-1))
{
intialLength++;
}
else{
string.append(a.charAt(i-1)).append(intialLength>=1?intialLength:"");
intialLength=1;
}
}
string.append(a.charAt(a.length()-1)).append(intialLength>=1?intialLength:"");
System.out.println(string.toString());
}
}
|
package com.nanyin.repository;
import com.nanyin.entity.Operate;
import org.springframework.data.jpa.repository.JpaRepository;
public interface OperateRepository extends JpaRepository<Operate,Integer> {
}
|
/**
* 37. Sudoku Solver
* 采用回溯法
*
* Created by mengwei on 2019/7/5.
*/
public class SudokuSolver {
// box size
int n = 3;
// row size
int N = n * n;
int [][] rows = new int[N][N + 1];
int [][] columns = new int[N][N + 1];
int [][] boxes = new int[N][N + 1];
char[][] board;
boolean sudokuSolved = false;
public boolean couldPlace(int d, int row, int col) {
/*
Check if one could place a number d in (row, col) cell
*/
int idx = (row / n ) * n + col / n;
return rows[row][d] + columns[col][d] + boxes[idx][d] == 0;
}
public void placeNumber(int d, int row, int col) {
/*
Place a number d in (row, col) cell
*/
int idx = (row / n ) * n + col / n;
rows[row][d]++;
columns[col][d]++;
boxes[idx][d]++;
board[row][col] = (char)(d + '0');
}
public void removeNumber(int d, int row, int col) {
/*
Remove a number which didn't lead to a solution
*/
int idx = (row / n ) * n + col / n;
rows[row][d]--;
columns[col][d]--;
boxes[idx][d]--;
board[row][col] = '.';
}
public void recursionNextNumbersDFS(int row, int col) {
/*
Call backtrack function in recursion
to continue to place numbers
till the moment we have a solution
*/
// if we're in the last cell
// that means we have the solution
if ((col == N - 1) && (row == N - 1)) {
sudokuSolved = true;
}
// if not yet
else {
// if we're in the end of the row
// go to the next row
if (col == N - 1) {
sloveDFS(row + 1, 0);
}
// go to the next column
else {
sloveDFS(row, col + 1);
}
}
}
public void sloveDFS(int row, int col) {
/*
Backtracking
*/
// if the cell is empty
if (board[row][col] == '.') {
// iterate over all numbers from 1 to 9
for (int d = 1; d < 10; d++) {
boolean flag = couldPlace(d, row, col);
if (flag) {
placeNumber(d, row, col);
recursionNextNumbersDFS(row, col);
// if sudoku is solved, there is no need to backtrack
// since the single unique solution is promised
if (!sudokuSolved) {
removeNumber(d, row, col);
}
}
}
}
else {
recursionNextNumbersDFS(row, col);
}
}
public void solveSudoku(char[][] board) {
this.board = board;
// init rows, columns and boxes
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
char num = board[i][j];
if (num != '.') {
int d = Character.getNumericValue(num);
placeNumber(d, i, j);
}
}
}
sloveDFS(0, 0);
}
public static void main(String[] args) {
char[][] boards = new char[][]{
{'5','3','.','.','7','.','.','.','.'},
{'6','.','.','1','9','5','.','.','.'},
{'.','9','8','.','.','.','.','6','.'},
{'8','.','.','.','6','.','.','.','3'},
{'4','.','.','8','.','3','.','.','1'},
{'7','.','.','.','2','.','.','.','6'},
{'.','6','.','.','.','.','2','8','.'},
{'.','.','.','4','1','9','.','.','5'},
{'.','.','.','.','8','.','.','7','9'}};
new SudokuSolver().solveSudoku(boards);
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
System.out.print("[" + boards[i][j] + "]");
}
System.out.println();
}
}
}
|
package com.navegg.challenge.CRUDApi;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.navegg.challenge.CRUDApi.model.Category;
import com.navegg.challenge.CRUDApi.model.Item;
import com.navegg.challenge.CRUDApi.model.Url;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import java.util.HashSet;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.collection.IsCollectionWithSize.hasSize;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
@ActiveProfiles("test")
public class CrudApiApplicationTests {
private static final ObjectMapper om = new ObjectMapper();
@Autowired
private MockMvc mockMvc;
@Test
public void findItemById() throws Exception {
mockMvc.perform(get("/item/1"))
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8))
.andExpect(status().isOk())
.andExpect(jsonPath("$.id", is("1")))
.andExpect(jsonPath("$.name", is("Site 1")))
.andExpect(jsonPath("$.urlList", hasSize(2)))
.andExpect(jsonPath("$.categoryList", hasSize(2)))
.andExpect(jsonPath("$.status", is("active")));
}
@Test
public void getAll() throws Exception {
mockMvc.perform(get("/item"))
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8))
.andExpect(status().isOk())
.andExpect(jsonPath("$", hasSize(11)))
.andExpect(jsonPath("$[0].id", is("1")))
.andExpect(jsonPath("$[0].name", is("Site 1")))
.andExpect(jsonPath("$[0].urlList", hasSize(2)))
.andExpect(jsonPath("$[0].categoryList", hasSize(2)))
.andExpect(jsonPath("$[0].status", is("active")))
.andExpect(jsonPath("$[1].id", is("2")))
.andExpect(jsonPath("$[1].name", is("Site 2")))
.andExpect(jsonPath("$[1].urlList", hasSize(1)))
.andExpect(jsonPath("$[1].categoryList", hasSize(3)))
.andExpect(jsonPath("$[1].status", is("active")));
}
@Test
public void itemNotFound() throws Exception {
mockMvc.perform(get("item/99"))
.andExpect(status().isNotFound());
}
@Test
public void saveItem() throws Exception {
Item item = new Item("Site 11", new HashSet<>(), new HashSet<>(), "active");
Category category = new Category("news");
Url url = new Url("game.com/nerd");
category.setItem(item);
url.setItem(item);
item.getCategoryList().add(category);
item.getUrlList().add(url);
mockMvc.perform(post("/item")
.content(om.writeValueAsString(item))
.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_UTF8))
.andExpect(status().isOk())
.andExpect(jsonPath("$.id", is("11")))
.andExpect(jsonPath("$.name", is("Site 11")))
.andExpect(jsonPath("$.urlList", hasSize(1)))
.andExpect(jsonPath("$.categoryList", hasSize(1)))
.andExpect(jsonPath("$.status", is("active")));
}
@Test
public void updateItem() throws Exception {
Item item = new Item("Site 11", new HashSet<>(), new HashSet<>(), "active");
Category category = new Category("news");
Url url = new Url("game.com/nerd");
category.setItem(item);
url.setItem(item);
item.getCategoryList().add(category);
item.getUrlList().add(url);
mockMvc.perform(patch("/item/2")
.content(om.writeValueAsString(item))
.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON))
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8))
.andExpect(status().isOk())
.andExpect(jsonPath("$.id", is("12")))
.andExpect(jsonPath("$.name", is("Site 11")))
.andExpect(jsonPath("$.urlList", hasSize(1)))
.andExpect(jsonPath("$.categoryList", hasSize(1)))
.andExpect(jsonPath("$.status", is("active")));
}
@Test
public void deleteItem() throws Exception {
mockMvc.perform(delete("/item/1"))
.andExpect(status().isOk());
}
} |
package com.aoharkov.soapproducing;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SoapProducingApplication {
public static void main(String[] args) {
SpringApplication.run(SoapProducingApplication.class, args);
}
}
|
package com.dpwn.newops.mobilgateway.machineinterface.model;
import com.fasterxml.jackson.annotation.JsonFormat;
import java.util.Date;
public class Status {
private String returnCode;
private String message;
@JsonFormat(pattern="yyyy-MM-dd HH:mm:ss,SSS")
private Date timeStamp;
public String getReturnCode() {
return returnCode;
}
public void setReturnCode(String returnCode) {
this.returnCode = returnCode;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public Date getTimeStamp() {
return timeStamp;
}
public void setTimeStamp(Date timeStamp) {
this.timeStamp = timeStamp;
}
}
|
package fabio.sicredi.evaluation.jms.sender;
import fabio.sicredi.evaluation.api.v1.model.PollDTO;
import fabio.sicredi.evaluation.api.v1.model.PollResultDTO;
import fabio.sicredi.evaluation.config.JmsConfig;
import fabio.sicredi.evaluation.domain.Duration;
import fabio.sicredi.evaluation.jms.model.PollResultMessage;
import fabio.sicredi.evaluation.services.VoteService;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.stereotype.Component;
import java.util.UUID;
@RequiredArgsConstructor
@Log4j2
@Component
public class PollResultSender {
private final JmsTemplate jmsTemplate;
@Autowired
private VoteService voteService;
public void sendMessage(final PollDTO pollDTO, final Duration duration) {
log.trace(String.format("Received Poll [%d] closure notification", pollDTO.getId()));
PollResultDTO voteResultDTO = voteService.countVotes(pollDTO);
voteResultDTO.setDuration(duration);
log.debug(String.format("Poll [%d] closure results collected", pollDTO.getId()));
PollResultMessage message = PollResultMessage
.builder()
.id(UUID.randomUUID())
.voteResultDTO(voteResultDTO)
.build();
log.debug(String.format("Sending Poll [%d] closure results", pollDTO.getId()));
jmsTemplate.convertAndSend(JmsConfig.QUEUE, message);
}
}
|
package com.meetingapp.android.model;
import com.intrusoft.sectionedrecyclerview.Section;
import java.util.List;
/**
* Created by apple on 11/7/16.
*/
public class SectionGroupHeader implements Section<Contact>, Comparable<SectionGroupHeader> {
private List<Contact> childList;
private String sectionText;
private int index;
private UserGroup userGroup;
public SectionGroupHeader(List<Contact> childList, String sectionText, int index, UserGroup userGroup) {
this.childList = childList;
this.sectionText = sectionText;
this.index = index;
this.userGroup = userGroup;
}
@Override
public List<Contact> getChildItems() {
return childList;
}
public String getSectionText() {
return sectionText;
}
@Override
public int compareTo(SectionGroupHeader another) {
if (this.index > another.index) {
return -1;
} else {
return 1;
}
}
public UserGroup getUserGroup() {
return userGroup;
}
public int getIndex() {
return index;
}
} |
package kr.co.people_gram.app;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.TextView;
public class SubPeopleContents_Activity extends AppCompatActivity {
private WebView people_content_webview;
private String matchNum = "0";
private String uid, mood, myname, mytype;
private String people_name, people_type, people_mood, people_uid, people_gubun1, people_gubun2;
private PeopleData pd;
private TextView popup_contents_title;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sub_people_contents_);
popup_contents_title = (TextView) findViewById(R.id.popup_contents_title);
Intent intent = getIntent();
if (intent != null) {
matchNum = intent.getStringExtra("matchNum");
}
//SubPeopleListSelect_Activity.my_sub_type;
switch (matchNum) {
case "1":
popup_contents_title.setText("상호 관계의 특징");
break;
case "2":
popup_contents_title.setText("나와 상대방의 차이점");
break;
case "3":
popup_contents_title.setText("두 사람 관계에서 내가 개선해야 할 점");
break;
case "4":
popup_contents_title.setText("좋은 관계를 맺을려면");
break;
case "5":
popup_contents_title.setText("많이 할수록 좋은 것(Do More)");
break;
case "6":
popup_contents_title.setText("피해야 할 것(Don't Do it)");
break;
}
uid = SharedPreferenceUtil.getSharedPreference(this, "uid");
myname = SharedPreferenceUtil.getSharedPreference(this, "username");
mytype = SharedPreferenceUtil.getSharedPreference(this, "mytype");
pd = new PeopleData();
people_uid = pd.get_people_uid();
people_name = pd.get_people_username();
people_type = pd.get_people_type();
people_mood = pd.get_people_mood();
people_gubun1 = pd.get_people_gubun1();
people_gubun2 = pd.get_people_gubun2();
people_content_webview = (WebView) findViewById(R.id.people_content_webview);
WebSettings webSettings = people_content_webview.getSettings();
webSettings.setJavaScriptEnabled(true);
people_content_webview.setWebViewClient(new WebViewClient() {
@Override
public void onPageFinished(WebView view, String url) {
people_content_webview.loadUrl("javascript:nameView('" + myname + "','" + people_name + "')");
super.onPageFinished(view, url);
}
});
if (people_gubun1.equals("F")) {
people_gubun2 = "A";
}
if (people_gubun1.equals("L")) {
people_gubun2 = "A";
}
if (SubPeopleListSelect_Activity.my_type_check == false && SubPeopleListSelect_Activity.people_type_check == false) {
people_content_webview.loadUrl("file:///android_asset/people_result/" + people_gubun1 + "/" + people_gubun1 + "_" + people_gubun2 + "_" + mytype + people_type + "_" + matchNum + ".html");
} else if (SubPeopleListSelect_Activity.my_type_check == true && SubPeopleListSelect_Activity.people_type_check == false) {
people_content_webview.loadUrl("file:///android_asset/people_result/" + people_gubun1 + "/" + people_gubun1 + "_" + people_gubun2 + "_" + SubPeopleListSelect_Activity.my_sub_type + people_type + "_" + matchNum + ".html");
} else if (SubPeopleListSelect_Activity.my_type_check == false && SubPeopleListSelect_Activity.people_type_check == true) {
people_content_webview.loadUrl("file:///android_asset/people_result/" + people_gubun1 + "/" + people_gubun1 + "_" + people_gubun2 + "_" + mytype + SubPeopleListSelect_Activity.people_sub_type + "_" + matchNum + ".html");
} else {
people_content_webview.loadUrl("file:///android_asset/people_result/" + people_gubun1 + "/" + people_gubun1 + "_" + people_gubun2 + "_" + SubPeopleListSelect_Activity.my_sub_type + SubPeopleListSelect_Activity.people_sub_type + "_" + matchNum + ".html");
}
}
public void closeBtn(View v) {
finish();
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_BACK:
finish();
break;
}
return super.onKeyDown(keyCode, event);
}
public void finish() {
super.finish();
overridePendingTransition(R.anim.slide_close_down_info, R.anim.slide_clode_up_info);
}
}
|
package com.openfarmanager.android.utils;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import io.reactivex.Observable;
/**
* @author Vlad Namashko.
*/
public class CommandLineUtils {
public final static int BUF_LEN = 64 * 1024;
public static Observable<String> executeReadCommand(final String command) {
return Observable.create(emitter -> {
BufferedReader bufferedReader = null;
try {
bufferedReader = new BufferedReader(new FileReader(command), BUF_LEN);
String line;
while ((line = bufferedReader.readLine()) != null) {
emitter.onNext(line);
}
} catch (IOException e) {
emitter.onError(e);
} finally {
emitter.onComplete();
try {
if (bufferedReader != null) {
bufferedReader.close();
}
} catch (IOException e) {
emitter.onError(e);
}
}
});
}
public static Observable<CommandLineCommandOutput> excecuteCommand(final String... command) {
return Observable.create(emitter -> {
try {
CommandLineCommandOutput commandOutput = new CommandLineCommandOutput();
commandOutput.args = command;
emitter.onNext(commandOutput);
ProcessBuilder processBuilder = new ProcessBuilder(commandOutput.args);
Process process = processBuilder.start();
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
commandOutput.process = process;
while ((line = reader.readLine()) != null) {
commandOutput.outputLine = line;
commandOutput.outputNum++;
emitter.onNext(commandOutput);
}
} catch (Exception e) {
emitter.onError(e);
}
});
}
public static class CommandLineCommandOutput {
public String[] args;
public String outputLine;
public int outputNum;
public Process process;
}
}
|
package net.mv.dao;
import java.util.List;
import org.hibernate.SessionFactory;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import javax.inject.Inject;
@Repository("employeeDaoImpl")
public class EmployeeDaoImpl implements EmployeeDao{
@Inject
private SessionFactory sessionFactory;
@Override
@Transactional
public void saveEmployee(Employee employee) {
this.sessionFactory.getCurrentSession().save(employee);
}
@Override
@Transactional
public Employee getEmployee(int id) {
return (Employee)this.sessionFactory.getCurrentSession().get(Employee.class, id);
}
@Override
@Transactional
public void updateEmployee(Employee employee) {
this.sessionFactory.getCurrentSession().update(employee);
}
@Override
@Transactional
public void deleteEmployee(Employee employee) {
this.sessionFactory.getCurrentSession().delete(employee);
}
@Override
@Transactional
public List<?> getAllEmployees(double salary) {
return this.sessionFactory.getCurrentSession().createQuery("from Employee where salary = " + salary).list();
}
}
|
package com.fypma.elvinlabs.parkme;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import io.socket.client.Socket;
/**
* Created by dileepa on 9/3/16.
*/
public class HelpActivity extends ActionBarActivity {
private Socket mSocket;
private String text = "test";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_help);
Button clickButton = (Button) findViewById(R.id.back);
clickButton.setOnClickListener( new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent(HelpActivity.this, MapsActivity.class);
startActivity(i);
finish();
}
});
}
@Override
protected void onDestroy() {
super.onDestroy();
}
} |
package com.java.lock;
import java.util.concurrent.locks.AbstractQueuedSynchronizer;
/**
* Created by Ness on 2017/7/6.
*/
public class Test06 {
public static void main(String[] args) {
// AbstractQueuedSynchronizer
// AbstractQueuedSynchronizer
}
}
|
package auton.scripts;
import java.util.ArrayList;
import auton.AutonCommand;
import auton.TurnCommand;
import auton.WaitCommand;
public class Position5 extends AutonScript{//script for obstacles in position 5
private static Position5 positionFive;
private ArrayList<AutonCommand> script = new ArrayList<AutonCommand>(){
@Override//change indexOf so it compares the names of the objects
public int indexOf(Object o){
if (o == null) {
for (int i = 0; i < script.size(); i++)
if (script.get(i) == null)
return i;
} else {
for (int i = 0; i < script.size(); i++)
if (script.get(i).equals(o))
return i;
}
return -1;
}
};
private Position5(){
//rough turn towards tower so the camera can see the target
script.add(new TurnCommand(20, "roughTurn"));
script.add(new WaitCommand(script.get(script.indexOf("roughTurn")), "waitRoughTurn"));
}
public static Position5 getInstance(){//get singelton instance
if(positionFive == null)
positionFive = new Position5();
return positionFive;
}
@Override
public ArrayList<AutonCommand> getScript() {
return script;
}
}
|
package com.oleksii.arrmy.CrewPortal.model;
import org.hibernate.annotations.CacheConcurrencyStrategy;
import javax.persistence.*;
@Entity
@Cacheable()
@org.hibernate.annotations.Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
public class Worker {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String name;
private int phoneNumber;
private int age;
private long yearIncome;
private String maritalStatus;
@org.hibernate.annotations.Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
@OneToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
@JoinColumn(name = "worker_location")
private Location location;
public Worker() {
}
public Location getLocation() {
return location;
}
public void setLocation(Location location) {
this.location = location;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(int phoneNumber) {
this.phoneNumber = phoneNumber;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public long getYearIncome() {
return yearIncome;
}
public void setYearIncome(long yearIncome) {
this.yearIncome = yearIncome;
}
public String getMaritalStatus() {
return maritalStatus;
}
public void setMaritalStatus(String maritalStatus) {
this.maritalStatus = maritalStatus;
}
}
|
package com.jme.puer.backoffice.common;
public class BackConstants {
//登录用户名
public static final String SESSION_LOGIN_USER_NAME = "login_username";
//验证码
public static final String SESSION_CODE_AUTO_IMG = "codeAuto";
//连续登录错误次数
public static final String SESSION_LOGIN_ERROR_COUNT = "login_error_count";
//登录用户名ID
public static final String SESSION_LOGIN_USER_ID = "login_user_id";
}
|
package com.logzc.webzic.orm.stmt.query.predicate;
import com.logzc.webzic.orm.dialect.Dialect;
import com.logzc.webzic.orm.stmt.query.BooleanOperator;
import com.logzc.webzic.orm.stmt.query.CriteriaBuilder;
import com.logzc.webzic.orm.stmt.query.Predicate;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;
/**
* Created by lishuang on 2016/8/26.
*/
public class CompoundPredicate implements Predicate {
CriteriaBuilder criteriaBuilder;
BooleanOperator operator;
Predicate leftPredicate;
Predicate rightPredicate;
String statement;
public CompoundPredicate(CriteriaBuilder criteriaBuilder, BooleanOperator operator, Predicate leftPredicate, Predicate rightPredicate) {
this.criteriaBuilder = criteriaBuilder;
this.operator = operator;
this.leftPredicate = leftPredicate;
this.rightPredicate = rightPredicate;
}
@Override
public String getStatement(Dialect dialect) {
if (statement == null) {
statement = " ( {0} {1} {2} ) ";
statement = MessageFormat.format(statement,leftPredicate.getStatement(dialect), operator.name(), rightPredicate.getStatement(dialect));
}
return statement;
}
@Override
public List<Object> getArgs() {
List<Object> args = new ArrayList<>();
args.addAll(leftPredicate.getArgs());
args.addAll(rightPredicate.getArgs());
return args;
}
}
|
package algorithms.strings.regexp;
import org.junit.Test;
public class RegexpTest {
@Test
public void compileTest() {
Regexp regexp = new Regexp();
regexp.compile("( ( A * B | A C ) D )");
System.out.println("ok");
}
@Test
public void recognizesTest() {
Regexp regexp = new Regexp();
regexp.compile("( C ( A * B | A C ) D )");
System.out.println(regexp.recognizes("CAABD"));
System.out.println(regexp.recognizes("CACD"));
System.out.println(regexp.recognizes("ACBD"));
System.out.println(regexp.recognizes("AABDA"));
}
} |
package com.gxtc.huchuan.ui.mine.classroom.directseedingbackground.usermanager;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.view.View;
import com.gxtc.commlibrary.base.BaseRecyclerAdapter;
import com.gxtc.commlibrary.base.BaseTitleActivity;
import com.gxtc.commlibrary.recyclerview.RecyclerView;
import com.gxtc.commlibrary.recyclerview.wrapper.LoadMoreWrapper;
import com.gxtc.commlibrary.utils.GotoUtil;
import com.gxtc.commlibrary.utils.LogUtil;
import com.gxtc.commlibrary.utils.ToastUtil;
import com.gxtc.huchuan.Constant;
import com.gxtc.huchuan.R;
import com.gxtc.huchuan.adapter.BannedOrBlackUserAdapter;
import com.gxtc.huchuan.bean.BannedOrBlackUserBean;
import com.gxtc.huchuan.data.UserManager;
import com.gxtc.huchuan.helper.RxTaskHelper;
import com.gxtc.huchuan.http.ApiCallBack;
import com.gxtc.huchuan.http.ApiObserver;
import com.gxtc.huchuan.http.ApiResponseBean;
import com.gxtc.huchuan.http.service.AllApi;
import com.gxtc.huchuan.http.service.LiveApi;
import com.gxtc.huchuan.im.provide.SilentMessage;
import com.gxtc.huchuan.pop.PopDiscuss;
import com.gxtc.huchuan.ui.mine.loginandregister.LoginAndRegisteActivity;
import com.gxtc.huchuan.utils.ImMessageUtils;
import com.gxtc.huchuan.widget.DividerItemDecoration;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import butterknife.BindView;
import io.rong.imlib.IRongCallback;
import io.rong.imlib.RongIMClient;
import io.rong.imlib.model.Message;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
/**
* Created by sjr on 2017/3/21.
* 禁言或取消黑名单用户列表
* 2017/3/21
* 接口商定,无下拉刷新 暂不需分页(可能二期要改)
*/
public class BannedOrBlackUserActivity extends BaseTitleActivity {
@BindView(R.id.rv_banned_user)
RecyclerView mRecyclerView;
List<BannedOrBlackUserBean> mDatas;
//系列课数
private BannedOrBlackUserAdapter mAdapter;
private int flag;
private String id;
private String chatType;
private int mStart = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_banned_user);
}
@Override
public void initData() {
mDatas = new ArrayList<>();
getBaseLoadingView().showLoading();
mRecyclerView.setLayoutMode(R.layout.model_footview_loadmore);
mRecyclerView.setOnLoadMoreListener(new LoadMoreWrapper.OnLoadMoreListener() {
@Override
public void onLoadMoreRequested() {
mStart = mStart + 15;
getList(id, chatType, mStart + "", "15");
}
});
initHeadView();
}
private void initHeadView() {
Intent intent = getIntent();
flag = intent.getIntExtra("flag", -1);
id = intent.getStringExtra(Constant.INTENT_DATA);
chatType = intent.getStringExtra("chatType");
//黑名单
if (1 == flag) {
getBaseHeadView().showTitle(getString(R.string.title_black_user));
getList(id,chatType,"0", "15");
//禁言
} else if (2 == flag) {
getBaseHeadView().showTitle(getString(R.string.title_banned_user));
getList(id,chatType,"0", "15");
}
getBaseHeadView().showBackButton(new View.OnClickListener() {
@Override
public void onClick(View v) {
BannedOrBlackUserActivity.this.finish();
}
});
}
/*
* type 1拉黑,2禁言
* chatId 课程ID
* chatType 1课程 2系列课
* start
* pageSize
* token
*/
private void getList(String chatId, String chatType, String start, String pageSize) {
if (UserManager.getInstance().isLogin()) {
HashMap<String, String> map = new HashMap<>();
map.put("type",flag + "");
map.put("chatId", chatId);
map.put("chatType", chatType);
map.put("start", start);
map.put("pageSize", pageSize);
map.put("token", UserManager.getInstance().getToken());
Subscription sub = AllApi.getInstance().bannedOrBalck(map)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new ApiObserver<ApiResponseBean<List<BannedOrBlackUserBean>>>(new ApiCallBack() {
@Override
public void onSuccess(Object data) {
if(mRecyclerView == null) return;
getBaseLoadingView().hideLoading();
mDatas = (List<BannedOrBlackUserBean>) data;
if (mDatas.size() == 0) {
getBaseEmptyView().showEmptyView();
return;
}
//黑名单
if(mStart == 0) {
if (1 == flag) {
mAdapter = new BannedOrBlackUserAdapter(BannedOrBlackUserActivity.this, BannedOrBlackUserActivity.this, mDatas, R.layout.item_banned_user, 1);
//禁言
} else if (2 == flag) {
mAdapter = new BannedOrBlackUserAdapter(BannedOrBlackUserActivity.this, BannedOrBlackUserActivity.this, mDatas, R.layout.item_banned_user, 2);
mRecyclerView.changeData(mDatas, mAdapter);
}
LinearLayoutManager manager = new LinearLayoutManager(BannedOrBlackUserActivity.this);
mRecyclerView.setLayoutManager(manager);
mRecyclerView.setAdapter(mAdapter);
mRecyclerView.addItemDecoration(new DividerItemDecoration(BannedOrBlackUserActivity.this, LinearLayoutManager.HORIZONTAL));
deleteBanned();
}else{
if(mDatas != null && mDatas.size() > 0)
mRecyclerView.changeData(mDatas, mAdapter);
else{
mRecyclerView.loadFinish();
}
}
}
@Override
public void onError(String errorCode, String message) {
getBaseLoadingView().hideLoading();
ToastUtil.showShort(BannedOrBlackUserActivity.this, message);
}
}));
RxTaskHelper.getInstance().addTask(BannedOrBlackUserActivity.this,sub);
} else GotoUtil.goToActivity(this, LoginAndRegisteActivity.class);
}
/**
* 取消禁言
*/
private void deleteBanned() {
mAdapter.setOnDelItemListener(new BannedOrBlackUserAdapter.OnDelItemListener() {
@Override
public void onDel(final BaseRecyclerAdapter.ViewHolder holder, final int position, final BannedOrBlackUserBean bean) {
String msg;
if(flag == 1){
msg = "已取消黑名单";
}else{
msg = "已解除禁言";
}
manageUser(id, chatType, flag+"", "0", bean.getUserCode(), position, msg);
// Subscription sub = AllApi.getInstance().cancelBannedOrBalck(UserManager.getInstance().getToken(), UserManager.getInstance().getChatRoomId(), String.valueOf(flag),
// bean.getUserCode())
// .subscribeOn(Schedulers.io())
// .observeOn(AndroidSchedulers.mainThread())
// .subscribe(new ApiObserver<ApiResponseBean<List<BannedOrBlackUserBean>>>(new ApiCallBack() {
// @Override
// public void onSuccess(Object data) {
// if (mAdapter == null) return;
// mAdapter.removeData(position);
// mAdapter.notifyDataSetChanged();
// //禁言
// if(flag == 2){
// silendMessage(bean);
// }
//
// //黑名单
// if(flag == 1){
//
// }
// }
//
// @Override
// public void onError(String errorCode, String message) {
// ToastUtil.showShort(BannedOrBlackUserActivity.this, message);
// }
// }));
//
// RxTaskHelper.getInstance().addTask(BannedOrBlackUserActivity.this,sub);
}
});
}
private void silendMessage(BannedOrBlackUserBean bean){
ImMessageUtils.silentMessage("false", bean.getUserCode(), id, new IRongCallback.ISendMessageCallback() {
@Override
public void onAttached(Message message) {}
@Override
public void onSuccess(Message message) {
LogUtil.i("发送禁言消息成功");
}
@Override
public void onError(Message message, RongIMClient.ErrorCode errorCode) {
LogUtil.i("发送禁言消息失败");
}
});
}
/**
*
* 拉黑/解除拉黑操作 禁言/解除禁言
* chatId 课程/系列课 id
* chatType 1课程 2系列课
* userCode 目标用户新媒号
* token 当前操作人token
* type 1拉黑/解除拉黑操作 2禁言/解除禁言操作
* state 0.解除 1.拉黑/禁言
*/
private void manageUser(String chatRoomId, String chatType, final String type, final String state, String userCode, final int position,final String msg) {
HashMap<String,String> map =new HashMap<>();
map.put("chatId", chatRoomId);
map.put("chatType", chatType);
map.put("userCode", userCode);
map.put("token", UserManager.getInstance().getToken());
map.put("type",type);
map.put("state", state);
LiveApi.getInstance().doJoinMemberBlacklistOrProhibitSpeaking(map)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new
ApiObserver<ApiResponseBean<Object>>
(new ApiCallBack() {
@Override
public void onSuccess(Object data) {
// callBack.onSuccess(new ArrayList<BannedOrBlackUserBean>());
//禁言
if(flag == 2){
BannedOrBlackUserBean bean = mAdapter.getList().get(position);
silendMessage(bean);
}
//黑名单
if(flag == 1){
}
if (mAdapter == null) return;
mAdapter.removeData(position);
mAdapter.notifyDataSetChanged();
if(mAdapter.getList().size() == 0){
getBaseEmptyView().showEmptyView();
}
ToastUtil.showShort(BannedOrBlackUserActivity.this, msg);
}
@Override
public void onError(String errorCode, String message) {
ToastUtil.showShort(BannedOrBlackUserActivity.this, message);
// callBack.onError(message);
}
}));
}
@Override
public void onDestroy() {
super.onDestroy();
RxTaskHelper.getInstance().cancelTask(this);
}
}
|
package com.soldevelo.vmi.scheduler.communication;
import com.soldevelo.vmi.communication.Producer;
import com.soldevelo.vmi.communication.Topics;
import com.soldevelo.vmi.communication.xml.XmlUtil;
import com.soldevelo.vmi.config.acs.AcsConfiguration;
import com.soldevelo.vmi.communication.params.TestRequestParams;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import javax.jms.JMSException;
@Component
public class TestRequestProducer extends Producer {
private static final int DEFAULT_RETRY_COUNT = 5;
private static final Logger LOG = LoggerFactory.getLogger(TestRequestProducer.class);
@Autowired
private AcsConfiguration configuration;
@PostConstruct
public void init() throws JMSException {
init(configuration.getBrokerUrl());
}
public boolean sendRequest(TestRequestParams testRequestParams) {
return sendRequest(testRequestParams, DEFAULT_RETRY_COUNT);
}
public boolean sendRequest(TestRequestParams testRequestParams, int retryCount) {
String xml = XmlUtil.toXml(testRequestParams);
boolean sent = false;
int retries = 0;
while (!sent && retries++ < retryCount) {
try {
sendMessage(xml);
sent = true;
} catch (JMSException e) {
LOG.error("JMS exception while sending test request", e);
}
}
return sent;
}
@Override
public String getTopicName() {
return Topics.TEST_REQUEST_TOPIC;
}
}
|
package com.fotoable.fotoime.utils;
import android.content.Context;
import com.fotoable.adloadhelper.ads.NativeAdViewManager;
/**
* Created by zhanglf on 2016/11/24.
*/
public class InterstitialAdUtil {
/**
* 弹出插屏广告
* 弹出时机: 1)第一次安装时, 退出锁屏提示框后弹出; 2)退出键盘预览时弹出
* 间隔时间为24小时
* @param applicationContext
*/
public static void loadInterstitialAd(Context applicationContext){
/** 是否移除广告 **/
if (SharedPreferenceHelper.hasRemoveAd()) return;
try {
NativeAdViewManager.getInstance().loadInterstitialAd(applicationContext,
MutableConstants.AD_IME_INTERSTITIAL);
} catch (Exception e) {
MobileUtil.dataCollectLog(DataCollectConstant.EXCEPTION_INTERSTITIA_AD);
} catch (OutOfMemoryError e) {
e.printStackTrace();
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.