text
stringlengths 10
2.72M
|
|---|
package geometry;
// @author Raphaël
public class RotatedEllipse extends Shape2D
{
protected double centerX, centerY, halfWidth, squaredHalfWidth, halfHeight, squaredHalfHeight,
theta, cosTheta, sinTheta;
public RotatedEllipse(double centerX, double centerY, double halfWidth, double halfHeight, double theta)
{
this.centerX = centerX;
this.centerY = centerY;
this.halfWidth = halfWidth;
squaredHalfWidth = halfWidth*halfWidth;
this.halfHeight = halfHeight;
squaredHalfHeight = halfHeight*halfHeight;
this.theta = theta;
cosTheta = Math.cos(theta);
sinTheta = Math.sin(theta);
}
public RotatedEllipse(Vector2D center, double halfWidth, double halfHeight, double theta)
{
this(center.getX(), center.getY(), halfWidth, halfHeight, theta);
}
@Override
public double getxMin()
{
return 0;
}
@Override
public double getxMax()
{
return 0;
}
@Override
public double getyMin()
{
return 0;
}
@Override
public double getyMax()
{
return 0;
}
@Override
public Shape2D getTranslatedInstance(double Dx, double Dy)
{
return null;
}
@Override
public Shape2D getRelativelyRotatedInstance(double Dtheta)
{
return null;
}
@Override
public Shape2D getAbsolutelyRotatedInstance(double theta)
{
return null;
}
@Override
public Shape2D getSimplifiedInstance()
{
return null;
}
@Override
public boolean strictlyContains(double x, double y)
{
double xPrime = cosTheta*(x-centerX)+sinTheta*(y-centerY),
yPrime = cosTheta*(y-centerY)-sinTheta*(x-centerX);
return xPrime*xPrime/squaredHalfWidth + yPrime*yPrime/squaredHalfHeight < 1;
}
@Override
public boolean contains(double x, double y)
{
double xPrime = cosTheta*(x-centerX)+sinTheta*(y-centerY),
yPrime = cosTheta*(y-centerY)-sinTheta*(x-centerX);
return xPrime*xPrime/squaredHalfWidth + yPrime*yPrime/squaredHalfHeight <= 1;
}
}
|
package br.com.AMGiv.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import br.com.AMGiv.beans.Cliente;
/**
* The Class ClienteDAO.
*/
public class ClienteDAO {
/**
* Cadastrar cliente.
* @author Givs
* @version 1.0
* @since 1.0
* @param c de Cliente da classe Cliente.java
* @param conexao de Connection (conexao com banco de dados)
* @return String com mensagem de sucesso
* @throws Sql Exception
* @throws Exception
*/
public String cadastrarCliente(Cliente c,Connection conexao) throws Exception {
String sql = "INSERT INTO T_AM_GIV_CLIENTE (CD_CLIENTE,NR_CPF, NR_RG,DT_NASCIMENTO,NR_QUARTO_PREFERIDO,DS_EMAIL,DS_SENHA,NM_PESSOA)"
+ " VALUES (SQ_AM_PESSOA.nextval,?,?,?,?,?,?,?)";
try {
PreparedStatement estrutura = conexao.prepareStatement(sql);
estrutura.setFloat(2, c.getCpf());
estrutura.setString(3, c.getRg());
estrutura.setString(4, c.getDataNascimento());
estrutura.setInt(5, c.getQuartoPreferido());
estrutura.setString(6, c.getEmail());
estrutura.setString(7, c.getSenha());
estrutura.setString(8, c.getNome());
estrutura.execute();
estrutura.close();
} catch (SQLException e) {
e.printStackTrace();
}
return "gravado com sucesso";
}
/**
* Gets pesquisar cliente.
* @author Rafael Paulo da Silva Queiros
* @version 1.0
* @since 1.0
* @param codCliente de cod cliente da classe Cliente.java
* @param conexao de Connection (conexão com banco de dados)
* @return Um objeto cliente
* @throws Exception
* @throws Sql Exception
*/
public Cliente getPesquisarCliente(int codCliente,Connection conexao) throws Exception {
Cliente cliente = new Cliente();
PreparedStatement estrutura = conexao.prepareStatement("select C.CD_CLIENTE,C.DS_EMAIL,C.DS_SENHA,C.DT_NASCIMENTO, C.NR_CPF,C.NR_QUARTO_PREFERIDO,C.NR_RG,P.NM_PESSOA "
+ " from T_AM_GIV_CLIENTE C INNER JOIN T_AM_GIV_PESSOA P"
+ " ON (C.CD_CLIENTE = P.CD_PESSOA) WHERE CD_CLIENTE = ?");
estrutura.setInt(1, codCliente);
ResultSet resultadoDados = estrutura.executeQuery();
if (resultadoDados.next()) {
cliente.setCodCliente(resultadoDados.getInt("CD_CLIENTE"));
cliente.setCpf(resultadoDados.getLong("NR_CPF"));
cliente.setRg(resultadoDados.getString("NR_RG"));
cliente.setDataNascimento(resultadoDados.getString("DT_NASCIMENTO"));
cliente.setQuartoPreferido(resultadoDados.getInt("NR_QUARTO_PREFERIDO"));
cliente.setEmail(resultadoDados.getString("DS_EMAIL"));
cliente.setSenha(resultadoDados.getString("DS_SENHA"));
cliente.setNome(resultadoDados.getString("NM_PESSOA"));
}
resultadoDados.close();
estrutura.close();
return cliente;
}
/**
* Deletar cliente.
* @author Rafael Paulo da Silva Queiros
* @version 1.0
* @since 1.0
* @param codCliente de cod cliente da classe Cliente.java
* @param conexao de Connection (conexão com banco de dados)
* @return um um inteiro com o resultado dos dados
* @throws Exception the exception
*/
public int deletarCliente(int codCliente, Connection conexao) throws Exception {
PreparedStatement estrutura = conexao
.prepareStatement("delete from T_AM_GIV_CLIENTE where CD_CLIENTE = ?");
estrutura.setInt(1, codCliente);
int resultadoDados = estrutura.executeUpdate();
estrutura.close();
return resultadoDados;
}
}
|
package com.pmm.sdgc.model;
import com.pmm.sdgc.converter.BooleanConverter;
import com.pmm.sdgc.converter.LocalDateConverter;
import com.pmm.sdgc.converter.LocalDateConverter1;
import java.io.Serializable;
import java.time.LocalDate;
import java.util.Objects;
import javax.persistence.Column;
import javax.persistence.Convert;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import javax.persistence.Transient;
import org.hibernate.annotations.NotFound;
import org.hibernate.annotations.NotFoundAction;
/**
*
* @author dreges
*/
@Entity
@Table(name = "historico_funcional")
public class Funcional implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@Column(name = "id")
private String id;
@Column(name = "matricula")
private String matricula;
@Column(name = "data_admissao")
@Convert(converter = LocalDateConverter1.class)
private LocalDate dataAdmissao;
@Column(name = "permutado")
private String permutado;
@Column(name = "acumula")
@Convert(converter = BooleanConverter.class)
private Boolean acumula;
@Column(name = "acumula_qual")
private String acumulaQual;
@Column(name = "acumula_onde")
private String acumulaOnde;
@Column(name = "cessao")
@Convert(converter = BooleanConverter.class)
private Boolean cessao;
@Column(name = "cessao_sentido")
private String cessaoSentido;
@Column(name = "data_confi")
@Convert(converter = LocalDateConverter.class)
private LocalDate dataConfi;
@Column(name = "controle")
private Character controle;
@Transient
private Boolean podeCriarUsuario;
@ManyToOne
@JoinColumn(name = "id_info", referencedColumnName = "id")
@NotFound(action = NotFoundAction.IGNORE)
private Pessoa pessoa;
@ManyToOne
@JoinColumn(name = "id_vinculo", referencedColumnName = "id_vinculo")
private Vinculo vinculo;
@ManyToOne(optional = true)
@JoinColumn(name = "id_cargo_com", referencedColumnName = "id", nullable = true)
@NotFound(action = NotFoundAction.IGNORE)
private CargoCom cargoCom;
@ManyToOne
@JoinColumn(name = "id_regime", referencedColumnName = "id_regime")
@NotFound(action = NotFoundAction.IGNORE)
private Regime regime;
@ManyToOne
@JoinColumn(name = "id_cargo", referencedColumnName = "id")
@NotFound(action = NotFoundAction.IGNORE)
private Cargo cargo;
@ManyToOne
@JoinColumn(name = "id_situacao", referencedColumnName = "id_situacao")
@NotFound(action = NotFoundAction.IGNORE)
private Situacao situacao;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getMatricula() {
return matricula;
}
public void setMatricula(String matricula) {
this.matricula = matricula;
}
public LocalDate getDataAdmissao() {
return dataAdmissao;
}
public void setDataAdmissao(LocalDate dataAdmissao) {
this.dataAdmissao = dataAdmissao;
}
public String getPermutado() {
return permutado;
}
public void setPermutado(String permutado) {
this.permutado = permutado;
}
public Boolean getAcumula() {
return acumula;
}
public void setAcumula(Boolean acumula) {
this.acumula = acumula;
}
public String getAcumulaQual() {
return acumulaQual;
}
public void setAcumulaQual(String acumulaQual) {
this.acumulaQual = acumulaQual;
}
public String getAcumulaOnde() {
return acumulaOnde;
}
public void setAcumulaOnde(String acumulaOnde) {
this.acumulaOnde = acumulaOnde;
}
public Boolean getCessao() {
return cessao;
}
public void setCessao(Boolean cessao) {
this.cessao = cessao;
}
public String getCessaoSentido() {
return cessaoSentido;
}
public void setCessaoSentido(String cessaoSentido) {
this.cessaoSentido = cessaoSentido;
}
public Vinculo getVinculo() {
return vinculo;
}
public void setVinculo(Vinculo vinculo) {
this.vinculo = vinculo;
}
public CargoCom getCargoCom() {
return cargoCom;
}
public void setCargoCom(CargoCom cargoCom) {
this.cargoCom = cargoCom;
}
public Regime getRegime() {
return regime;
}
public void setRegime(Regime regime) {
this.regime = regime;
}
public Cargo getCargo() {
return cargo;
}
public void setCargo(Cargo cargo) {
this.cargo = cargo;
}
public Pessoa getPessoa() {
return pessoa;
}
public void setPessoa(Pessoa pessoa) {
this.pessoa = pessoa;
}
public LocalDate getDataConfi() {
return dataConfi;
}
public void setDataConfi(LocalDate dataConfi) {
this.dataConfi = dataConfi;
}
public Character getControle() {
return controle;
}
public void setControle(Character controle) {
this.controle = controle;
}
public Situacao getSituacao() {
return situacao;
}
public void setSituacao(Situacao situacao) {
this.situacao = situacao;
}
public Boolean getPodeCriarUsuario() {
return podeCriarUsuario;
}
public void setPodeCriarUsuario(Boolean podeCriarUsuario) {
this.podeCriarUsuario = podeCriarUsuario;
}
@Override
public int hashCode() {
int hash = 5;
return hash;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Funcional other = (Funcional) obj;
if (!Objects.equals(this.id, other.id)) {
return false;
}
return true;
}
@Override
public String toString() {
return "Funcional{" + "id=" + id + ", matricula=" + matricula + ", cargo=" + cargo + '}';
}
}
|
package com.qumla.scheduler;
import java.util.concurrent.Callable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import com.qumla.service.impl.QuestionDaoMapper;
public class CountryStatScheduler implements Callable<Object> {
private static final Logger log = LoggerFactory.getLogger(CountryStatScheduler.class);
@Autowired
private QuestionDaoMapper questionDaoMapper;
@Override
public Object call() throws Exception {
return null;
}
public void init() {
/**
ScheduledFuture<CountryStatScheduler> schedule = reloadEventsScheduler.schedule(this, 1000,
TimeUnit.MILLISECONDS);
try {
log.debug("reschedule events:" + schedule.get());
} catch (Exception e) {
log.error("execution Exception", e);
}
**/
}
}
|
package com.mohmedhassan.cleaningapp.Register;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.mohmedhassan.cleaningapp.APIUrl;
import com.mohmedhassan.cleaningapp.Edit_ProfileUser.country_intity_Country;
import com.mohmedhassan.cleaningapp.HTTP_GET.HttpCall_Get;
import com.mohmedhassan.cleaningapp.HTTP_GET.HttpRequest_Get;
import com.mohmedhassan.cleaningapp.Login.LoginActivity;
import com.mohmedhassan.cleaningapp.R;
import com.mohmedhassan.cleaningapp.SideMenuActivity;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.HashMap;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.X509TrustManager;
public class RegisterActivity extends AppCompatActivity {
private static final String KEY_EMPTY = "";
ProgressBar progressBar;
String NameHolder, EmailHolder, PasswordHolder,Country;
EditText Ed_username_register, Ed_email_register, Ed_password_register;
TextView Login_Register, Tv_name, Tv_email, Tv_password,Tv_Country;
Spinner SpCountry;
private ArrayAdapter<CharSequence> arrayAdapter_country;
Button Btn_Register;
String LanguageApp;
ArrayList<country_intity_Country> countryList = new ArrayList<>();
ArrayList<String> spinnercountry = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
DevineView();
SetOnClickListener();
// GetCountry();
}
private void GetCountry() {
LanguageApp = "ar";
HashMap<String, String> params = new HashMap<>();
//Log.d("Verification","Mail: "+mail+" , code: "+verfication_num);
params.put("lang", LanguageApp);
initializeGetCountry(false, params);
}
@SuppressLint("StaticFieldLeak")
private void initializeGetCountry(final boolean loadMore, HashMap<String, String> params) {
// try {
// getJSONObjectFromURL("https://api2.x4to.com/adduser?password=ddd&name=aaa&email=xx");
// } catch (IOException e) {
// e.printStackTrace();
// } catch (JSONException e) {
// e.printStackTrace();
// }
// progressBar.setVisibility(View.VISIBLE);
HttpCall_Get httpCall_get = new HttpCall_Get();
httpCall_get.setMethodtype(HttpCall_Get.GET);
httpCall_get.setUrl(APIUrl.BASE_URL + "getContriesRegister");
httpCall_get.setParams(params);
String vv = httpCall_get.getUrl() + params;
new HttpRequest_Get() {
@Override
public void onResponse(StringBuilder response) {
super.onResponse(response);
// try {
try {
String Country_id = "";
String country = "";
// sp_countryName = Sp_Country.getSelectedItem().toString().trim();
JSONTokener Xobject = new JSONTokener(response.toString());
JSONObject Code = new JSONObject(Xobject);
String C = Code.getString("code");
if (C.contains("101")) {
Toast.makeText(getApplicationContext(), " Country already exist ..", Toast.LENGTH_LONG).show();
// progressBar.setVisibility(View.GONE);
return;
}
// progressBar.setVisibility(View.GONE);
JSONTokener tokener = new JSONTokener(response.toString());
JSONObject data = new JSONObject(tokener);
JSONArray object = data.getJSONArray("data");
for (int i = 0; i < object.length(); i++) {
JSONObject itemCountry = object.getJSONObject(i); //gets the ith Json object of JSONArray
country = itemCountry.getString("country_name");
Country_id = itemCountry.getString("id");
countryList.add(new country_intity_Country(country, Country_id));
// Toast.makeText(Edit_ProfileUserActivity.this, country, Toast.LENGTH_SHORT).show();
spinnercountry.add(country);
}
ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(RegisterActivity.this,
android.R.layout.simple_spinner_item, spinnercountry); //selected item will look like a spinner set from XML
spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
SpCountry.setAdapter(spinnerArrayAdapter);
// Toast.makeText(RegisterActivity.this, country, Toast.LENGTH_SHORT).show();
Tv_Country.setVisibility(View.VISIBLE);
// Toast.makeText(Edit_ProfileUserActivity.this, Country_id, Toast.LENGTH_SHORT).show();
// Toast.makeText(Edit_ProfileUserActivity.this, country, Toast.LENGTH_SHORT).show();
} catch (JSONException e) {
e.printStackTrace();
}
// } catch (JSONException e) {
// e.printStackTrace();
// }
}
}.execute(httpCall_get);
}
private void DevineView() {
Btn_Register = findViewById(R.id.btn_register);
Login_Register = findViewById(R.id.tv_login_register);
Ed_username_register = findViewById(R.id.ed_username_register);
Ed_email_register = findViewById(R.id.ed_email_register);
Ed_password_register = findViewById(R.id.ed_password_register);
Tv_name = findViewById(R.id.tv_username_register);
Tv_email = findViewById(R.id.tv_eamil_register);
Tv_password = findViewById(R.id.tv_password_register);
SpCountry = findViewById(R.id.sp_country_register);
Tv_Country = findViewById(R.id.tv_country_register);
progressBar = findViewById(R.id.m_progress_register);
}
private void SetOnClickListener() {
SpCountry.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
Ed_email_register.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
Tv_email.setVisibility(View.VISIBLE);
}
@Override
public void afterTextChanged(Editable s) {
}
});
Ed_username_register.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
Tv_name.setVisibility(View.VISIBLE);
}
@Override
public void afterTextChanged(Editable s) {
}
});
Ed_password_register.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
Tv_password.setVisibility(View.VISIBLE);
}
@Override
public void afterTextChanged(Editable s) {
}
});
arrayAdapter_country = ArrayAdapter.createFromResource(this,
R.array.country , android.R.layout.simple_spinner_item);
arrayAdapter_country.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
SpCountry.setAdapter(arrayAdapter_country);
Btn_Register.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
/* EmailHolder = Ed_email_register.getText().toString();
NameHolder = Ed_username_register.getText().toString();
PasswordHolder = Ed_password_register.getText().toString();
Country = SpCountry.getSelectedItem().toString();
if(validateInputs()){
HashMap<String,String> params = new HashMap<>();
//Log.d("Verification","Mail: "+mail+" , code: "+verfication_num);
params.put("email",EmailHolder);
params.put("name",NameHolder);
params.put("password",PasswordHolder);
params.put("country_id",Country);
initializeRegister(false,params);*/
Intent intent = new Intent(RegisterActivity.this, SideMenuActivity.class);
startActivity(intent);
}
});
Login_Register.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(RegisterActivity.this, LoginActivity.class);
startActivity(intent);
}
});
}
public void trustEveryone() {
try {
HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier(){
public boolean verify(String hostname, SSLSession session) {
return true;
}});
SSLContext context = SSLContext.getInstance("TLS");
context.init(null, new X509TrustManager[]{new X509TrustManager(){
public void checkClientTrusted(X509Certificate[] chain,
String authType) throws CertificateException {}
public void checkServerTrusted(X509Certificate[] chain,
String authType) throws CertificateException {}
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}}}, new SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(
context.getSocketFactory());
} catch (Exception e) { // should never happen
e.printStackTrace();
}
}
public JSONObject getJSONObjectFromURL(String urlString) throws IOException, JSONException {
HttpURLConnection urlConnection = null;
URL url = new URL(urlString);
trustEveryone();
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setReadTimeout(10000 /* milliseconds */ );
urlConnection.setConnectTimeout(15000 /* milliseconds */ );
urlConnection.setDoOutput(true);
urlConnection.connect();
BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line + "\n");
}
br.close();
String jsonString = sb.toString();
System.out.println("JSON: " + jsonString);
return new JSONObject(jsonString);
}
@SuppressLint("StaticFieldLeak")
private void initializeRegister(final boolean loadMore, HashMap<String, String> params) {
// try {
// getJSONObjectFromURL("https://api2.x4to.com/adduser?password=ddd&name=aaa&email=xx");
// } catch (IOException e) {
// e.printStackTrace();
// } catch (JSONException e) {
// e.printStackTrace();
// }
progressBar.setVisibility(View.VISIBLE);
HttpCall_Get httpCall_get = new HttpCall_Get();
httpCall_get.setMethodtype(HttpCall_Get.GET);
httpCall_get.setUrl(APIUrl.BASE_URL_LoginAndRegister+"adduser");
httpCall_get.setParams(params);
String vv= httpCall_get.getUrl() + params ;
new HttpRequest_Get() {
@Override
public void onResponse(StringBuilder response) {
super.onResponse(response);
// try {
try {
String User_id = "" ;
String User_name = "" ;
JSONTokener Xobject = new JSONTokener(response.toString());
JSONObject Code = new JSONObject(Xobject);
String C = Code.getString("code");
if (C.contains("101") ) {
Toast.makeText(getApplicationContext()," Email already exist ..",Toast.LENGTH_LONG).show();
progressBar.setVisibility(View.GONE);
return;
}
progressBar.setVisibility(View.GONE);
JSONTokener tokener = new JSONTokener(response.toString());
JSONObject data = new JSONObject(tokener);
JSONArray object = data.getJSONArray("data");
for(int i=0; i<object.length(); i++) {
JSONObject item = object.getJSONObject(i); //gets the ith Json object of JSONArray
User_id = item.getString("id");
User_name = item.getString("name");
}
Toast.makeText(getApplicationContext(),User_id,Toast.LENGTH_LONG).show();
Toast.makeText(getApplicationContext(),User_name,Toast.LENGTH_LONG).show();
Ed_email_register.setText(" ");
Ed_username_register.setText(" ");
Ed_password_register.setText(" ");
} catch (JSONException e) {
e.printStackTrace();
}
// } catch (JSONException e) {
// e.printStackTrace();
// }
}
}.execute(httpCall_get);
}
private boolean validateInputs() {
if (KEY_EMPTY.equals(EmailHolder)) {
Ed_email_register.setError("Email cannot be empty");
Ed_email_register.requestFocus();
return false;
}
if (KEY_EMPTY.equals(NameHolder)) {
Ed_username_register.setError("NameItem cannot be empty");
Ed_username_register.requestFocus();
return false;
}
if (KEY_EMPTY.equals(PasswordHolder)) {
Ed_password_register.setError("Password cannot be empty");
Ed_password_register.requestFocus();
return false;
}
if (!EmailHolder.matches("[a-zA-Z0-9._-]+@[a-z]+.[a-z]+")) {
Ed_email_register.setError("Invalid Email Address");
Ed_email_register.requestFocus();
return false;
}
return true;
}
}
|
package pojo;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
@Entity
@Table( name="BookTable")
public class Book
{
private Integer bookId;
private String subjectName;
private String bookName;
private String authorName;
private float price;
private Date publishDate;
public Book() {
}
public Book(Integer bookId, String subjectName, String bookName, String authorName, float price, Date publishDate) {
this.bookId = bookId;
this.subjectName = subjectName;
this.bookName = bookName;
this.authorName = authorName;
this.price = price;
this.publishDate = publishDate;
}
@Id
@Column(name="book_id")
public Integer getBookId() {
return bookId;
}
public void setBookId(Integer bookId) {
this.bookId = bookId;
}
@Column(name="subject_name", length=50)
public String getSubjectName() {
return subjectName;
}
public void setSubjectName(String subjectName) {
this.subjectName = subjectName;
}
@Column(name="book_name", length=50, unique=true)
public String getBookName() {
return bookName;
}
public void setBookName(String bookName) {
this.bookName = bookName;
}
@Column(name="author_name", length=50)
public String getAuthorName() {
return authorName;
}
public void setAuthorName(String authorName) {
this.authorName = authorName;
}
@Column(columnDefinition="float(10,2)")
public float getPrice() {
return price;
}
public void setPrice(float price) {
this.price = price;
}
@Temporal(TemporalType.DATE)
@Column(name="publish_date")
public Date getPublishDate() {
return publishDate;
}
public void setPublishDate(Date publishDate) {
this.publishDate = publishDate;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + bookId;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Book other = (Book) obj;
if (bookId != other.bookId)
return false;
return true;
}
@Override
public String toString() {
return String.format("%-30s%-30s%-10.2f", this.bookName, this.authorName, this.price);
}
}
|
package com.example.testproj;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;
public class StartService{
public static void startService(Context context){
PendingIntent pendingIntent;
Intent intent=new Intent(context,AlaramReceiver.class);
pendingIntent=PendingIntent.getBroadcast(context, 0, intent, 0);
AlarmManager manager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
int interval = 1000;
manager.setInexactRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), interval, pendingIntent);
}
}
|
public class Array2 {
public int countEvens(int[] nums) {
int count = 0;// c1
for (int n : nums) {// c2 + c3*n
if (n % 2 == 0) {// c4 + c5*n
count++; // c6
}
}
return count; //c7
//c1+c2+c3*n+c4+c5*n+c6+c7
//Complejidad O(n)
}
public int[] post4(int[] nums) {
for (int i = nums.length-1; i >= 0; i--) { //c1 + c2*n + c3*n
if (nums[i] == 4) { // c4 + c5*n
int[] foo; // c6
foo = new int[nums.length-i-1]; //c7*n
for (int j = 0; j < foo.length; j++) { //c8 + c9*n + c10*n
foo[j] = nums[i+j+1]; //c11*n + c12*n
}
return foo; //c13
}
}
int[] bar; // c14
bar = new int[0]; //c15*n
return bar; //c16
//c1+c2*n+c3*n+c4+c5*n+c6+c7*n+c8 + c9*n + c10*n+ c11*n + c12*n+ c13+c14+c15*n+c16
//Complejidad O(n^2)
}
public boolean only14(int[] nums) {
boolean T = true; //c1
for(int i = 0; i<nums.length; i++){ //c2+c3*n+c4*n
if(nums[i] != 1 && nums[i] != 4) //c5+c6*n + c7*n
T = false; //c8
}
return T; //c9
//c1 +c2 + c3*n + c4*n + c5 + c6*n + c7*n + c8 + c9
//Complejidad O(n)
}
public String[] fizzArray2(int n) {
String[] r = new String[n]; // c1*n + c2*n
for(int i = 0; i<n ; i++){ //c3+c4*n
r[i] = String.valueOf(i); // c5*n + c6*n
}
return r; //c7
//c1*n + c2*n + c3 + c4*n + c5*n + c6*n + c7
//Complejidad O(n)
}
public boolean has12(int[] nums) {
boolean f = false; //c1
boolean f1 = false; //c2
for(int i = 0; i<nums.length; i++){ //c3+c4*n
if(nums[i] == 1) // c5 + c6*n
f = true; //c7
if(nums[i] == 2 && f) // c8 + c9*n + c10
f1 = true; //c11
}
return f1; //c12
//c1 + c2 + c3 + c4*n + c5 + c6*n + c7 + c8 + c9*n + c10 + c11 + c12
//Complejidad O(n)
}
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package main.java.spatialrelex.util;
/*
* Copyright 2007 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @author ycoppel@google.com (Yohann Coppel)
*
* @param <T>
* Object's type in the tree.
*/
public class Tree<T>{
private T head;
private List<Tree<T>> leaves = new ArrayList<>();
private Tree<T> parent = null;
private Map<T, Tree<T>> locate = new HashMap<>();
public Tree(T head) {
this.head = head;
locate.put(head, this);
}
public void addLeaf(T root, T leaf) {
if (locate.containsKey(root)) {
locate.get(root).addLeaf(leaf);
} else {
addLeaf(root).addLeaf(leaf);
}
}
public Tree<T> addLeaf(T leaf) {
Tree<T> t = new Tree<>(leaf);
leaves.add(t);
t.parent = this;
t.locate = this.locate;
locate.put(leaf, t);
return t;
}
public T getHead() {
return head;
}
public Tree<T> getTree(T element) {
return locate.get(element);
}
public Tree<T> getParent() {
return parent;
}
public Collection<T> getSuccessorsNames(T root) {
Collection<T> successors = new ArrayList<>();
Tree<T> tree = getTree(root);
if (null != tree) {
for (Tree<T> leaf : tree.leaves) {
successors.add(leaf.head);
}
}
return successors;
}
public Collection<Tree<T>> getSuccessors(T root) {
Collection<Tree<T>> successors = new ArrayList<>();
Tree<T> tree = getTree(root);
if (null != tree) {
for (Tree<T> leaf : tree.leaves) {
successors.add(leaf);
}
}
return successors;
}
public Collection<T> getAncestorsNames(T node) {
Collection<T> ancestors = new ArrayList<>();
Tree<T> tree = getTree(node);
if (null != tree) {
while (null != tree.getParent()) {
ancestors.add(tree.getParent().head);
tree = tree.getParent();
}
}
return ancestors;
}
public Collection<Tree<T>> getAncestors(T node) {
Collection<Tree<T>> ancestors = new ArrayList<>();
Tree<T> tree = getTree(node);
if (null != tree) {
while (null != tree.getParent()) {
ancestors.add(tree.getParent());
tree = tree.getParent();
}
}
return ancestors;
}
public boolean DFS(T key) {
boolean found = false;
for(int i = 0; i < leaves.size() && !found; i++) {
Tree<T> child = leaves.get(i);
String val = child.head.toString();
if(val.equals(key.toString()))
found = true;
else
found = child.DFS(key);
}
return found;
}
public void DFS () {
for (Tree<T> child : leaves) {
child.DFS();
System.out.println(child.head);
}
}
@Override
public String toString() {
return printTree(0);
}
private static final int indent = 2;
private String printTree(int increment) {
String s = "";
String inc = "";
for (int i = 0; i < increment; ++i) {
inc = inc + " ";
}
s = inc + head;
for (Tree<T> child : leaves) {
s += "\n" + child.printTree(increment + indent);
}
return s;
}
}
|
package com.infohold.bdrp.authority.shiro.web;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
/**
* 为了 绕过spring boot 对类型为filter的bean自动注册为过滤器所做的封装
*
* @author xiaweiyi
*
*/
public interface PathMatchShiroFilterWrapper extends ShiroFilterWrapper {
public boolean isEnabled();
public void setName(String name);
public FilterConfig getFilterConfig();
public void setFilterConfig(FilterConfig filterConfig);
public void setEnabled(boolean enabled);
public ServletContext getServletContext();
public void setServletContext(ServletContext servletContext);
}
|
package com.company.warehouse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class GenericMapList {
private Map<Class<?>, List<?>> map = new HashMap<Class<?>, List<?>>();
public <T> void put(Class<T> key, T value) {
List<T> list = (List<T>) map.get(key);
if (list == null) {
list = new ArrayList<T>();
}
// list.add(key.cast(value));
list.add(value);
map.put(key, list);
}
public <T> List<T> get(Class<T> key) {
if (key == null) {
return null;
}
return (List<T>)map.get(key);
// List<T> list = (List<T>)map.get(key);
// if(list == null) {
// return null;
// }
//
// return key.cast(list.get(0));
}
public <T> T getRemoveFirst(Class<T> key) {
if (key == null) {
return null;
}
List<T> list = (List<T>)map.get(key);
if(list == null || list.size() == 0) {
return null;
}
return key.cast(list.remove(0));
}
public Set<Class<?>> keySet() {
return map.keySet();
}
public int size() {
return keySet().size();
}
public String toString() {
StringBuilder sb = new StringBuilder();
for (Class<?> key : map.keySet()) {
sb.append(key.getSimpleName() + " : ");
sb.append(get(key));
sb.append(System.lineSeparator());
}
return sb.toString();
}
}
|
package problems;
import lib.PrimesGenerator;
/**
* Problem 5: Smallest multiple
*
* 2520 is the smallest number that can be divided by each of the
* numbers from 1 to 10 without any remainder.
*
* What is the smallest positive number that is evenly divisible by
* all of the numbers from 1 to 20?
*
* @author John Shearer
*
*/
public class Problem5 extends EulerProblem {
public static int problemNumber = 5;
public static String title = "Smallest multiple";
public static String instructions =
"2520 is the smallest number that can be divided by each of the\n" +
"numbers from 1 to 10 without any remainder.\n\n" +
"What is the smallest positive number that is evenly divisible by\n" +
"all of the numbers from 1 to 20?";
// instance properties
int ceiling;
/**
* Euler Problem 5 class
*/
public Problem5() {
this(20);
}
public Problem5(int ceiling) {
this.ceiling = ceiling;
}
@Override
public String toString() {
return this.toString(problemNumber, title, instructions);
}
@Override
public Object solve() {
PrimesGenerator primes = new PrimesGenerator();
long product = 1;
while (true) {
long p = primes.next();
if (p > ceiling) {
break;
}
/*
* First pass: for each of the primes p less than or equal to n,
* see which of our numbers has the highest power of p as a
* factor, and multiply the running product total by that amount
*/
// // high-water mark of the exponent for our current prime
// int exp = 0;
// // cycle through each of the multiples of p up to n and check how
// // many times p will go into it
// for (long number = p; number < ceiling + 1; number += p) {
// int count = 0;
// while (number % Math.pow(p, count + 1) == 0) {
// count++;
// }
// if (count > exp) {
// exp = count;
// }
// }
/*
* second go: way simpler, but only works if all of the numbers up
* to n are used, i.e. it wouldn't work with some sub-set of
* numbers, or an arbitrary set of numbers
*/
int exp = (int)(Math.log(ceiling) / Math.log(p));
product *= Math.pow(p, exp);
}
return product;
}
}
|
package ch5;
import java.util.Arrays;
public class ArrayEx1 {
public static void main(String[] args) {
int[] score = new int[5];
int k = 1;
score[0] = 50;
score[1] = 60;
score[k+1] = 70; // socre[2]=70
score[3] = 80;
score[4] = 90;
int tmp = score[k+2] + score[4]; //score[3] + score[4] = 80 + 90 = 170
for(int i=0; i<5; i++) {
System.out.printf("score[%d] = %d%n", i, score[i]);
}
System.out.println("score[] = "+Arrays.toString(score));
System.out.println("temp = "+tmp);
//System.out.printf("score[%d] = %d%n", 7, score[7]); 에러
}
}
|
package com.brainacademy.decorator;
public class Main {
public static void main(String[] args) {
Printable printable = new MainPrintable();
Printable decorator1 = new QuotePrintableDecorator(printable);
Printable decorator2 = new QuotePrintableDecorator(decorator1);
Printable decorator3 = new BracketPrintableDecorator(printable);
Printable decorator4 = new BracketPrintableDecorator(decorator1);
Printable decorator5 = new BracketPrintableDecorator(decorator2);
System.out.println(printable.getResult());
System.out.println(decorator1.getResult());
System.out.println(decorator2.getResult());
System.out.println(decorator3.getResult());
System.out.println(decorator4.getResult());
System.out.println(decorator5.getResult());
}
}
|
package com.egame.beans;
import org.json.JSONObject;
import com.egame.utils.ui.IconBeanImpl;
/**
* @desc 游戏分类的实体
*
* @Copyright lenovo
*
* @Project EGame4th
*
* @Author zhangrh@lenovo-cw.com
*
* @timer 2011-12-29
*
* @Version 1.0.0
*
* @JDK version used 6.0
*
* @Modification history none
*
* @Modified by none
*/
public class GameSortBean extends IconBeanImpl{
/**
* 类型名称
* */
private String typeName;
/**
* 类型代码
* */
private int typeCode;
/**
* 子类名称(允许为空)
* */
private String gameClassName;
/**
* 子类代码(允许为空)
* */
private int classCode;
// /**
// * 图片地址
// * */
// private String picturePath;
/**
* 游戏数量
* */
private int totalNumber;
/**
* 分类默认排序
* */
private int orderType;
/**
* 分类默认排序(升序/降序)
* */
private String orderDesc;
public GameSortBean(JSONObject obj){
super(obj.optString("picturePath"));
this.typeName=obj.optString("typeName");
this.typeCode=obj.optInt("typeCode");
this.gameClassName=obj.optString("className");
this.classCode=obj.optInt("classCode");
// this.picturePath=obj.optString("picturePath");
this.totalNumber=obj.optInt("totalNumber");
this.orderType=obj.optInt("orderType");
this.orderDesc=obj.optString("orderDesc");
}
/**
* @return 返回 orderType
*/
public int getOrderType() {
return orderType;
}
/**
* @param 对orderType进行赋值
*/
public void setOrderType(int orderType) {
this.orderType = orderType;
}
/**
* @return 返回 orderDesc
*/
public String getOrderDesc() {
return orderDesc;
}
/**
* @param 对orderDesc进行赋值
*/
public void setOrderDesc(String orderDesc) {
this.orderDesc = orderDesc;
}
/**
* @return 返回 typeName
*/
public String getTypeName() {
return typeName;
}
/**
* @param 对typeName进行赋值
*/
public void setTypeName(String typeName) {
this.typeName = typeName;
}
/**
* @return 返回 typeCode
*/
public int getTypeCode() {
return typeCode;
}
/**
* @param 对typeCode进行赋值
*/
public void setTypeCode(int typeCode) {
this.typeCode = typeCode;
}
/**
* @return 返回 gameClassName
*/
public String getGameClassName() {
return gameClassName;
}
/**
* @param 对gameClassName进行赋值
*/
public void setGameClassName(String gameClassName) {
this.gameClassName = gameClassName;
}
/**
* @return 返回 classCode
*/
public int getClassCode() {
return classCode;
}
/**
* @param 对classCode进行赋值
*/
public void setClassCode(int classCode) {
this.classCode = classCode;
}
// /**
// * @return 返回 picturePath
// */
// public String getPicturePath() {
// return picturePath;
// }
// /**
// * @param 对picturePath进行赋值
// */
// public void setPicturePath(String picturePath) {
// this.picturePath = picturePath;
// }
/**
* @return 返回 totalNumber
*/
public int getTotalNumber() {
return totalNumber;
}
/**
* @param 对totalNumber进行赋值
*/
public void setTotalNumber(int totalNumber) {
this.totalNumber = totalNumber;
}
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package vista;
import javax.swing.JFrame;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javafx.scene.layout.Border;
/**
*
* @author user
*/
public class Inicial extends JFrame{
private JMenuBar barraMenu;
private JMenu menu0, menu1, menu2,menu3;
private JMenuItem item0, item1,item2,item3, item4,item5,item6,item7,item8,item9;
private JDesktopPane JDpanel;
private Container contenedor;
public Inicial(){
iniciarComponentes();
}
public void iniciarComponentes(){
setVisible(true);
setTitle("Manager Hotel 0.0.1 ");
setExtendedState(6);
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setIconImage(new ImageIcon(getClass().getResource("/imagenes/hotel.png")).getImage());
barraMenu=new JMenuBar();
setJMenuBar(barraMenu);
menu0=new JMenu("Menu 0");
menu1=new JMenu("Huespedes");
menu2=new JMenu("Menu 2");
menu3=new JMenu("Menu 3");
item0=new JMenuItem("Item 0");
item1=new JMenuItem("Item 1");
item2=new JMenuItem("Item 2");
item3=new JMenuItem("Item 3");
item4=new JMenuItem("Item 4");
item5=new JMenuItem("Gestionar Huspedes");
item6=new JMenuItem("Reservar");
item7=new JMenuItem("Item 7");
item8=new JMenuItem("Item 8");
item9=new JMenuItem("Salir");
menu0.add(item0);menu0.add(item1);menu0.add(item2);
menu1.add(item3);menu1.add(item4);menu1.add(item5);
menu2.add(item6);menu2.add(item7);menu2.add(item7);
menu3.add(item8);menu3.add(item9);
barraMenu.add(menu0);barraMenu.add(menu1);barraMenu.add(menu2);barraMenu.add(menu3);
JDpanel=new JDesktopPane();
contenedor=getContentPane();
contenedor.add(JDpanel);
JDpanel.setBorder(new ImagenFondo());
item9.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(ActionEvent e) {
dispose();
}
});
item5.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(ActionEvent e) {
VHuespedes v=new VHuespedes();
int x = (JDpanel.getWidth() / 2) - v.getWidth() /2;
int y = (JDpanel.getHeight() / 2) - v.getHeight() /2;
if (v.isShowing()){
v.setLocation(x,y);
}
else{
JDpanel.add(v);
v.setLocation(x,y);
v.setVisible(true);
}
}
});
item6.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(ActionEvent e) {
VReserva v=new VReserva();
int x = (JDpanel.getWidth() / 2) - v.getWidth() /2;
int y = (JDpanel.getHeight() / 2) - v.getHeight() /2;
if (v.isShowing()){
v.setLocation(x,y);
}
else{
JDpanel.add(v);
v.setLocation(x,y);
v.setVisible(true);
}
}
});
item8.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(ActionEvent e) {
VFacturaciones v=new VFacturaciones();
int x = (JDpanel.getWidth() / 2) - v.getWidth() /2;
int y = (JDpanel.getHeight() / 2) - v.getHeight() /2;
if (v.isShowing()){
v.setLocation(x,y);
}
else{
JDpanel.add(v);
v.setLocation(x,y);
v.setVisible(true);
}
}
});
}
}
|
package myapp.com.callrecorder;
import android.Manifest;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;
import myapp.com.callrecorder.Database.Customer;
import myapp.com.callrecorder.Database.Database;
import static myapp.com.callrecorder.Constants.Constants.baseUrlRegistration;
import static myapp.com.callrecorder.Constants.Constants.isNetworkAvailable;
import static myapp.com.callrecorder.Constants.Constants.progressDialog;
public class RegistrationActivity extends AppCompatActivity {
Button BtnRegister;
EditText EdtUserName, EdtMobileNumber;
String AccessToken, UserName, MobNumber;
String result = null;
String strStatus;
int status;
int responseUserId;
ProgressDialog progress;
List<Customer> custcount;
int count;
Database db = new Database(this);
int PERMISSION_ALL = 1;
String[] PERMISSIONS = {Manifest.permission.RECORD_AUDIO, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.PROCESS_OUTGOING_CALLS, Manifest.permission.ACCESS_NETWORK_STATE, Manifest.permission.CALL_PHONE, Manifest.permission.READ_PHONE_STATE, Manifest.permission.READ_CONTACTS};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_registration);
progress = new ProgressDialog(RegistrationActivity.this);
EdtUserName = (EditText) findViewById(R.id.username);
EdtMobileNumber = (EditText) findViewById(R.id.mob_no);
BtnRegister = (Button) findViewById(R.id.register_button);
if (!hasPermissions(this, PERMISSIONS)) {
ActivityCompat.requestPermissions(this, PERMISSIONS, PERMISSION_ALL);
}
BtnRegister.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
ActionRegister();
}
});
}
public void ActionRegister() {
UserName = EdtUserName.getText().toString();
MobNumber = EdtMobileNumber.getText().toString();
if (isNetworkAvailable(RegistrationActivity.this)) {
if (UserName == null || UserName.equals("") || MobNumber == null || MobNumber.equals("")) {
Toast.makeText(getApplicationContext(), "Enter all valid fields", Toast.LENGTH_LONG).show();
} else if (EdtUserName.getText().toString().trim().isEmpty()) {
Toast.makeText(getApplicationContext(), "Enter User Name", Toast.LENGTH_LONG).show();
} else if (MobNumber.length() < 10) {
Toast.makeText(getApplicationContext(), "Enter correct Mobile number", Toast.LENGTH_LONG).show();
} else {
if (!hasPermissions(this, PERMISSIONS)) {
ActivityCompat.requestPermissions(this, PERMISSIONS, PERMISSION_ALL);
} else {
new SendRegistrationDetails(UserName, MobNumber).execute();
progressDialog(progress, "Loading", "Please wait...");
}
}
} else {
Toast.makeText(getApplicationContext(), "Please check network connection", Toast.LENGTH_LONG).show();
}
}
public static boolean hasPermissions(Context context, String... permissions) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && context != null && permissions != null) {
for (String permission : permissions) {
if (ActivityCompat.checkSelfPermission(context, permission) != PackageManager.PERMISSION_GRANTED) {
return false;
}
}
}
return true;
}
@Override
protected void onStart() {
super.onStart();
custcount = db.getAllCustomers();
count = 0;
for (Customer cn : custcount) {
count++;
}
if (count > 0) {
// Intent i = new Intent(RegistrationActivity.this,MainActivity.class);
// startActivity(i);
//Code to exit from app
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
startActivity(intent);
}
}
public class SendRegistrationDetails extends AsyncTask<String, Void, String> {
private final String mUserName;
private final String mMobileNo;
SendRegistrationDetails(String username, String mobno) {
mUserName = username;
mMobileNo = mobno;
}
@Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
try {
// code to consume wcf service which sends the details to the server
String url = baseUrlRegistration + "Register";
// 1. create HttpClient
HttpClient httpclient = new DefaultHttpClient();
// 2. make POST request to the given URL
HttpPost httpPost = new HttpPost(url);
String json = "";
// 3. build jsonObject
JSONObject jsonObject = new JSONObject();
jsonObject.accumulate("UserName", UserName);
jsonObject.accumulate("MobileNo", MobNumber);
jsonObject.accumulate("grant_type", "password");
json = jsonObject.toString();
httpPost.setEntity(new StringEntity("grant_type=password&UserName=" + mUserName + "&MobileNo=" + mMobileNo, "UTF-8"));
// 7. Set some headers to inform server about the type of the content
httpPost.setHeader("Accept", "application/x-www-form-urlencoded");
httpPost.setHeader("Content-type", "application/x-www-form-urlencoded");
HttpResponse response = httpclient.execute(httpPost);
status = response.getStatusLine().getStatusCode();
if (status == 200) {
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
JSONObject othposjsonobj = new JSONObject(data);
// strStatus = othposjsonobj.getString("Status");
// if (strStatus.equals("success")) {
strStatus = othposjsonobj.getString("Status");
if (strStatus.equals("success")) {
responseUserId = Integer.parseInt(othposjsonobj.getString("UserID"));
AccessToken = othposjsonobj.getString("access_token");
}
} else {
// result = "Did not work!";
}
} catch (Exception e) {
DateFormat df = new SimpleDateFormat("EEE, d MMM yyyy, HH:mm");
String date = df.format(Calendar.getInstance().getTime());
Log.d("InputStream", e.getLocalizedMessage());
e.printStackTrace();
//appendLog(LoginActivity.this, "1 LoginActivity " + e.toString() + date);
}
return result;
}
@Override
protected void onPostExecute(String result) {
try {
if (status == 401) {
Toast.makeText(getApplicationContext(), "401 Unauthorized!,Please login again.", Toast.LENGTH_LONG).show();
} else if (status == 503) {
Toast.makeText(getApplicationContext(), " 503 Service not available!,Please login again.", Toast.LENGTH_LONG).show();
} else if (status == 200) {
if (strStatus.equals("success")) {
db.addCustomer(new Customer(responseUserId, AccessToken, UserName, MobNumber));
// Intent i = new Intent(RegistrationActivity.this, MainActivity.class);
// startActivity(i);
//Code to exit from app
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
startActivity(intent);
}
} else if (strStatus.equals("fail")) {
Toast.makeText(RegistrationActivity.this, "Connection Fail!", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(RegistrationActivity.this, "Service not available!,Please login again.", Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
DateFormat df = new SimpleDateFormat("EEE, d MMM yyyy, HH:mm");
String date = df.format(Calendar.getInstance().getTime());
Log.d("InputStream", e.getLocalizedMessage());
e.printStackTrace();
//appendLog(LoginActivity.this, "3 LoginActivity " + e.toString() + date);
}
if (progress.isShowing()) {
progress.dismiss();
}
}
}
}
|
package dec26;
public class Sequence {
public static void main(String[] args) {
String str1="iam a good person";
System.out.println(str1.contains("od"));
System.out.println(str1.contains("person"));
System.out.println(str1.contains("iam"));
System.out.println(str1.contains("bad"));
}
}
|
package caris.modular.handlers;
import java.util.HashMap;
import caris.framework.basehandlers.MessageHandler;
import caris.framework.basereactions.MultiReaction;
import caris.framework.basereactions.Reaction;
import caris.framework.events.MessageEventWrapper;
import caris.framework.library.Constants;
import caris.framework.reactions.ReactionMessage;
public class GreetingHandler extends MessageHandler {
private String[] greetingsInput = new String[] {
"Hello",
"Hi ",
"Hi,",
"Howdy",
"G'day",
"Gday",
"Good morn",
"Good even",
"Good aftern",
"Good day",
"Morning",
"Evening",
"Afternoon",
"Hey",
"Yo ",
"Yo,",
"Sup ",
"Sup,",
"'Sup",
"Salutations",
"Greetings",
"Hiya",
"Hi-ya",
"What's up",
"Whats up"
};
private String[] greetingsOutput = new String[] {
"Hello",
"Hi",
"Hey",
"Salutations",
"Greetings",
"Hiya",
};
private String[] correctionOutput = new String[] {
"Actually, it's pronounced *Care*-is.",
"The capital of France is pronounced *Pair* Is, not *Par* Is!",
"Mikki, we've been over this.",
"Mikki please.",
"Do you want me to start pronouncing your name *Made*-ison??",
"You hurt me with your mispronounciations."
};
public GreetingHandler() {
super("Greeting");
}
@Override
protected boolean isTriggered(MessageEventWrapper messageEventWrapper) {
return startsWithAGreeting(messageEventWrapper.message) && mentioned(messageEventWrapper);
}
@Override
protected Reaction process(MessageEventWrapper messageEventWrapper) {
MultiReaction returnGreeting = new MultiReaction(0);
if( messageEventWrapper.getAuthor().getLongID() == Constants.MIKKI_ID ) {
returnGreeting.reactions.add(new ReactionMessage(getRandomCorrection(), messageEventWrapper.getChannel(), 0));
} else {
returnGreeting.reactions.add(new ReactionMessage(getRandomGreeting() + ", " + messageEventWrapper.getAuthor().getDisplayName(messageEventWrapper.getGuild()) + "!", messageEventWrapper.getChannel(), 0));
}
return returnGreeting;
}
private boolean startsWithAGreeting(String message) {
for( String greeting : greetingsInput ) {
if( message.toLowerCase().startsWith(greeting.toLowerCase()) ) {
return true;
}
}
return false;
}
private String getRandomGreeting() {
return (greetingsOutput.length > 0) ? greetingsOutput[(int) (Math.random()*greetingsOutput.length)] : "Hello";
}
private String getRandomCorrection() {
return (correctionOutput.length > 0) ? correctionOutput[(int) (Math.random()*correctionOutput.length)] : "Actually, it's pronounced *Care*-is.";
}
@Override
public String getDescription() {
return "Makes " + Constants.NAME + " say hi back to you!";
}
@Override
public HashMap<String, String> getUsage() {
HashMap<String, String> usage = new HashMap<String, String>();
usage.put("Hello " + Constants.NAME + "!", "Produces a random greeting");
return usage;
}
}
|
/*
* Copyright (C) 2016-2017 Joaquin Rodriguez Felici <joaquinfelici at gmail.com>
* Copyright (C) Rodrigo Castro
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.petrinator.auxiliar;
import org.petrinator.editor.Root;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.RenderingHints;
import java.awt.Stroke;
import java.awt.geom.AffineTransform;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import javax.swing.*;
public class GraphPanel extends JPanel
{
private int width = 600;
private int heigth = 500;
private int padding = 25;
private int labelPadding = 25;
private int shiftLeft = 25;
private Root root;
private Color gridColor = new Color(200, 200, 200, 200);
private static final Stroke GRAPH_STROKE = new BasicStroke(2f);
private int pointWidth = 4;
private int numberYDivisions = 10;
private List<List<Double>> vectors;
private List<Color> colors = new ArrayList<Color>();
private List<String> names = new ArrayList<String>();
public GraphPanel(Root root, List<List<Double>> vectors, List<String> names)
{
this.vectors = vectors;
this.names = names;
this.root = root;
colors.add(new Color(25, 7, 99));
colors.add(new Color(180,4,5));
colors.add(new Color(0, 150, 39));
colors.add(new Color(0, 141, 150));
colors.add(new Color(190, 174, 0));
shiftLeft = 25 + getLongestLabel() * 8;
width += getLongestLabel() * 12;
setUp();
}
private void setUp()
{
this.setPreferredSize(new Dimension(width, heigth));
JDialog frame = new JDialog(root.getParentFrame(), "Places history");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(this);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
@Override
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
double xScale = ((double) getWidth()-shiftLeft - (2 * padding) - labelPadding) / (Collections.max(vectors.get(0)));
double yScale = ((double) getHeight() - 2 * padding - labelPadding) / (getMaxScore() - getMinScore());
// Draw white background
g2.setColor(Color.WHITE);
g2.fillRect(padding + labelPadding, padding, getWidth()-shiftLeft - (2 * padding) - labelPadding, getHeight() - 2 * padding - labelPadding);
g2.setColor(Color.BLACK);
// Create hatch marks and grid lines for y axis.
for (int i = 0; i < numberYDivisions + 1; i++)
{
int x0 = padding + labelPadding;
int x1 = pointWidth + padding + labelPadding;
int y0 = getHeight() - ((i * (getHeight() - padding * 2 - labelPadding)) / numberYDivisions + padding + labelPadding);
int y1 = y0;
if (vectors.get(1).size() > 0)
{
g2.setColor(gridColor);
g2.drawLine(padding + labelPadding + 1 + pointWidth, y0, getWidth()-shiftLeft - padding, y1);
g2.setColor(Color.BLACK);
String yLabel = ((int) ((getMinScore() + (getMaxScore() - getMinScore()) * ((i * 1.0) / numberYDivisions)) * 100)) / 100.0 + "";
FontMetrics metrics = g2.getFontMetrics();
int labelWidth = metrics.stringWidth(yLabel);
g2.drawString(yLabel, x0 - labelWidth - 5, y0 + (metrics.getHeight() / 2) - 3);
}
g2.drawLine(x0, y0, x1, y1);
}
// For x axis
int numberXDivisions = 15;
if(vectors.get(0).size() < numberXDivisions)
numberXDivisions = vectors.get(0).size();
for (int i = 0; i < numberXDivisions; i++) {
if (vectors.get(1).size() > 1) {
int x0 = i * (getWidth()-shiftLeft - padding * 2 - labelPadding) / (numberXDivisions-1) + padding + labelPadding;
int x1 = x0;
int y0 = getHeight() - padding - labelPadding;
int y1 = y0 - pointWidth;
if ((i % ((int) ((numberXDivisions / 20.0)) + 1)) == 0) {
g2.setColor(gridColor);
g2.drawLine(x0, getHeight() - padding - labelPadding - 1 - pointWidth, x1, padding);
g2.setColor(Color.BLACK);
String xLabel = vectors.get(0).get(i) + "";
FontMetrics metrics = g2.getFontMetrics();
int labelWidth = metrics.stringWidth(xLabel);
g2.drawString(xLabel, x0 - labelWidth / 2, y0 + metrics.getHeight() + 3);
if(i == numberXDivisions - 1)
{
g2.drawString("[s]", x0 - labelWidth / 2 + 35, y0 + metrics.getHeight() + 3);
}
else if(i == 3)
{
g2.drawString("[tokens vs. seconds]", x0 - labelWidth / 2 + 50, y0 + metrics.getHeight() + 22);
}
}
g2.drawLine(x0, y0, x1, y1);
}
}
// Create x and y axes
g2.drawLine(padding + labelPadding, getHeight() - padding - labelPadding, padding + labelPadding, padding);
g2.drawLine(padding + labelPadding, getHeight() - padding - labelPadding, getWidth()-shiftLeft - padding, getHeight() - padding - labelPadding);
int count = 35;
// Draw the dots and lines according to the arrays in the vectors list
for(int k = 1; k < vectors.size(); k++)
{
List<Point> graphPoints = new ArrayList<>();
for (int i = 0; i < vectors.get(k).size(); i++)
{
int x1 = (int) (vectors.get(0).get(i) * xScale + padding + labelPadding);
int y1 = (int) ((getMaxScore() - vectors.get(k).get(i)) * yScale + padding);
if(i != 0) // Add point to get a squared wave
{
int y2 = (int) ((getMaxScore() - vectors.get(k).get(i-1)) * yScale + padding); // The point has the same x position as the new one and the same y position as the last one.
graphPoints.add(new Point(x1,y2));
}
graphPoints.add(new Point(x1, y1)); // Add normal point
}
Stroke oldStroke = g2.getStroke();
g2.setColor(colors.get((k-1)%5));
g2.setStroke(GRAPH_STROKE);
for (int i = 0; i < graphPoints.size() - 1; i++) {
int x1 = graphPoints.get(i).x;
int y1 = graphPoints.get(i).y;
int x2 = graphPoints.get(i + 1).x;
int y2 = graphPoints.get(i + 1).y;
g2.drawLine(x1, y1, x2, y2);
if(i == graphPoints.size()-2)
{
g2.drawString(names.get(k), x2+33, count);
g2.fillRect(x2+15, count-10, 8, 8);
count += 20;
}
//g2.drawString(names.get(k), x2+6, y2+5);
}
g2.setStroke(oldStroke);
g2.setColor(colors.get((k-1)%5));
for (int i = 0; i < graphPoints.size(); i++) {
int x = graphPoints.get(i).x - pointWidth / 2;
int y = graphPoints.get(i).y - pointWidth / 2;
int ovalW = pointWidth;
int ovalH = pointWidth;
// g2.fillOval(x, y, ovalW, ovalH); // Draw circle on each point
}
}
}
private double getMinScore()
{
double minScore = Double.MAX_VALUE;
for(List<Double> vector : vectors)
{
if(vectors.indexOf(vector) != 0)
{
for (Double score : vector)
{
minScore = Math.min(minScore, score);
}
}
}
return minScore;
}
public int getLongestLabel()
{
int longest = names.get(0).length();
for(String label : names)
{
if(label.length() > longest)
longest = label.length();
}
return longest;
}
private double getMaxScore()
{
double maxScore = Double.MIN_VALUE;
for(List<Double> vector : vectors)
{
if(vectors.indexOf(vector) != 0)
{
for (Double score : vector)
{
maxScore = Math.max(maxScore, score);
}
}
}
return maxScore;
}
}
|
import java.time.LocalDate;
public class Faktura {
private Zamowienie zamowienie;
private Kontrahent sprzedajacy;
private Kontrahent kupujacy;
private LocalDate dataWystawienia;
private LocalDate dataZaplaty;
private String numerFaktury;
private static int counter = 0;
public Faktura(Zamowienie zamowienie, Kontrahent sprzedajacy, Kontrahent kupujacy) {
this.zamowienie = zamowienie;
this.numerFaktury = generujNumerFaktury();
counter++;
this.sprzedajacy = sprzedajacy;
this.kupujacy = kupujacy;
this.dataWystawienia = LocalDate.now();
this.dataZaplaty = LocalDate.now().plusDays(30);
}
public Zamowienie getZamowienie() {
return zamowienie;
}
public Kontrahent getSprzedajacy() {
return sprzedajacy;
}
public Kontrahent getKupujacy() {
return kupujacy;
}
public LocalDate getDataWystawienia() {
return dataWystawienia;
}
public LocalDate getDataZaplaty() {
return dataZaplaty;
}
public String getNumerFaktury() {
return numerFaktury;
}
public String generujNumerFaktury() {
this.numerFaktury = "F/" + LocalDate.now().getYear() + "/" + LocalDate.now().getMonthValue() + "/" + counter;
return this.numerFaktury;
}
@Override
public String toString() {
StringBuilder tekstFaktury = new StringBuilder();
tekstFaktury.append("Faktura nr " + generujNumerFaktury() + "\n" +
"Data wystawienia: " + this.dataWystawienia + "\n\n" +
"Sprzedający:\n" + this.sprzedajacy.toString() + "\n" +
"Kupujący:\n" + this.kupujacy.toString() + "\n"
+ this.zamowienie.toString() + "\nData sprzedaży: " + zamowienie.getDataZamowienia() +
"\nTermin zapłaty: " + this.dataZaplaty);
return tekstFaktury.toString();
}
}
|
package com.qa.test;
public class ProductCategoryPage {
}
|
import java.awt.*;
import java.applet.*;
public class emp2 extends Applet
{
String ename;
Long ecode;
float basic,da,hra,ma,gross,itax,net;
TextField t1,t2,t3;
public void init()
{
t1= new TextField(20);
t2= new TextField(20);
t3= new TextField(20);
add(t1);
add(t2);
add(t3);
}//close of init()
public void paint(Graphics g)
{
g.drawString("1.Enter employee name",40,60);
g.drawString("Enter each value of each box",40,40);
g.drawString("2.Enter Employee code",40,80);
g.drawString("3.Enter Employee Basic",40,100);
ename=(t1.getText());
ecode=Long.parseLong(t2.getText());
basic=Float.valueOf(t3.getText());
da=basic*20/100;
hra=basic*10/100;
ma=basic*12/100;
gross=basic+da+hra+ma;
itax=gross*5/100;
net=gross-itax;
g.drawString("**********************Sallery********************",40,120);
g.drawString("Employee name:- "+ename,40,140 );
g.drawString("Employee code:- "+ecode,40,160 );
g.drawString("Employee basic:- "+basic,40,180 );
g.drawString("Dearrneass allowance:- "+da,40,200 );
g.drawString("House rent allowance:- "+hra,40,220 );
g.drawString("Madical allowance:- "+ma,40,240 );
g.drawString("========================================",40,260 );
g.drawString("Gross sallery:- "+gross,40,280 );
g.drawString("Income Tax deduction in Rs:- "+da,40,300 );
g.drawString("=========================================",40,320 );
g.drawString("Net Sallery in Rs:- "+net,40,340 );
}//close of paint
public boolean action(Event e,Object obj)
{
repaint();
return(true);
}//close of action
}//close of class
|
package com.openfarmanager.android.filesystem;
import android.text.Html;
import com.openfarmanager.android.model.Bookmark;
import com.openfarmanager.android.utils.Extensions;
import com.openfarmanager.android.utils.FileUtilsExt;
import org.apache.jackrabbit.webdav.MultiStatusResponse;
import org.apache.jackrabbit.webdav.property.DavPropertySet;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import jcifs.smb.SmbException;
/**
* @author Vlad Namashko
*/
public class WebDavFile implements FileProxy {
private static SimpleDateFormat sFormat = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss zzz");
private String mName;
private boolean mIsDirectory;
private long mSize;
private long mLastModified;
private String mFullPath;
private String mParentPath;
public WebDavFile(MultiStatusResponse response, String currentPath) throws SmbException {
DavPropertySet set = response.getProperties(200);
String href = response.getHref();
try {
href = FileUtilsExt.removeLastSeparator(URLDecoder.decode(href, "UTF-8"));
} catch (UnsupportedEncodingException e) {
href = response.getHref();
}
mName = FileUtilsExt.removeFirstSeparator(href.substring(href.indexOf(currentPath) + currentPath.length()));
mIsDirectory = set.get("getcontenttype").getValue().equals("httpd/unix-directory");
if (!mIsDirectory) {
mSize = Integer.parseInt((String) set.get("getcontentlength").getValue());
try {
mLastModified = sFormat.parse((String) set.get("getlastmodified").getValue()).getTime();
} catch (ParseException e) {
}
}
mFullPath = href;
mParentPath = currentPath;
}
public WebDavFile(String path) {
path = FileUtilsExt.removeLastSeparator(path);
mName = FileUtilsExt.getFileName(path);
mIsDirectory = true;
mSize = 0;
mLastModified = System.currentTimeMillis();
mFullPath = path;
mParentPath = FileUtilsExt.getParentPath(path);
}
@Override
public String getId() {
return getFullPath();
}
@Override
public String getName() {
return mName;
}
@Override
public boolean isDirectory() {
return mIsDirectory;
}
@Override
public long getSize() {
return mSize;
}
@Override
public long lastModifiedDate() {
return mLastModified;
}
@Override
public List getChildren() {
return new ArrayList();
}
@Override
public String getFullPath() {
return mFullPath;
}
@Override
public String getFullPathRaw() {
return mFullPath;
}
@Override
public String getParentPath() {
return mParentPath;
}
@Override
public boolean isUpNavigator() {
return false;
}
@Override
public boolean isRoot() {
return getName().equals("..") && Extensions.isNullOrEmpty(mParentPath);
}
@Override
public boolean isVirtualDirectory() {
return false;
}
@Override
public boolean isBookmark() {
return false;
}
@Override
public Bookmark getBookmark() {
return null;
}
@Override
public String getMimeType() {
return null;
}
}
|
package com.charlie.ssm.demo.service;
import com.charlie.ssm.demo.common.entity.ResultEntity;
import com.charlie.ssm.demo.entity.UserEntity;
/**
*
*/
public interface IUserService {
/**
* 用户登录
* @param userEntity
* @return
*/
ResultEntity login(UserEntity userEntity);
/**
* 用户注册
* @param userEntity
* @return
*/
ResultEntity register(UserEntity userEntity);
/**
* 删除用户
* @param userEntity
* @return
*/
ResultEntity delete(UserEntity userEntity);
}
|
package com.bhagi.backend.reposiitory;
import com.bhagi.backend.model.Role;
import org.springframework.data.jpa.repository.JpaRepository;
public interface RoleRepository extends JpaRepository<Role, Long> {
}
|
package com.company;
import javax.swing.JFrame;
public class Frame {
public static void main(String [] args){
JFrame f = new JFrame();
Paint p = new Paint();
f.add(p);
f.setVisible(true);
f.setSize(800, 250);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setLocationRelativeTo(null);
}
}
|
package com.thoughtworks.demo.service;
import com.thoughtworks.demo.BaseTest;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
public class MusicTest extends BaseTest{
@Autowired
private MiniMusic miniMusic;
@Test
void name() {
miniMusic.play();
}
}
|
package dlmbg.pckg.sistem.akademik;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;
public class CekDosenActivity extends Activity {
TextView ket;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.panel_cek_dosen);
ket = (TextView) findViewById(R.id.txt_keterangan);
ket.setText("Under Construction\nBelum sempat ane buat gan, silahkan diisi sendiri :p");
}
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.opt_menu, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.url:
Intent intent = null;
intent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://stikombanyuwangi.ac.id"));
startActivity(intent);
return true;
case R.id.tentang:
AlertDialog alertDialog;
alertDialog = new AlertDialog.Builder(this).create();
alertDialog.setTitle("SIAKAD STIKOM BANYUWANGI");
alertDialog.setMessage("Aplikasi SIAKAD berbasis Android ini merupakan salah satu dari sekian banyak proyek 2M" +
" serta segelintir penelitian yang saya kerjakan di kampus. Semoga aplikasi ini bisa bermanfaat untuk " +
" kita semua.\n\nSalam, Gede Lumbung\nhttp://gedelumbung.com");
alertDialog.setButton("#OKOK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDialog.show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
|
/**
* 问题:已知两个链表head1和head2各自有序,
* 请把它们合并成一个链表依然有序。结果链表要包含head1和head2的所有节点,即使节点值相同。
*
* @author Cyrus
* @version v1.0, 2018/3/19 下午8:41
*/
public class OrderedLinkList {
private static class Node {
public Node next;
public int value;
}
/**
* 递归实现,分解,每次都找出头结点,当前节点的下一个节点就是下一轮的头节点
*/
public static Node mergeOrderedLinkList(Node one, Node two) {
Node head;
if (one == null) {
head = two;
} else if (two == null) {
head = one;
} else {
if (one.value <= two.value) {
head = one;
head.next = mergeOrderedLinkList(one.next, two);
} else {
head = two;
head.next = mergeOrderedLinkList(one, two.next);
}
}
return head;
}
public static Node loopMerge(Node one, Node two) {
Node head;
if (one == null) {
return two;
} else if (two == null) {
return one;
} else {
if (one.value <= two.value) {
head = one;
one = head.next;
} else {
head = two;
two = head.next;
}
Node curr = head;
while (two != null && one != null) {
if (one.value <= two.value) {
curr.next = one;
one = one.next;
} else {
curr.next = two;
two = two.next;
}
}
if (one == null) {
curr.next = two;
} else {
curr.next = one;
}
}
return head;
}
public static void main(String[] args) {
Node one = new Node();
one.value = 6;
Node one2 = new Node();
one2.value = 4;
one2.next = one;
Node one3 = new Node();
one3.value = 2;
one3.next = one2;
Node oneTmp = one3;
System.out.println("One");
while (oneTmp != null) {
System.out.println(oneTmp.value);
oneTmp = oneTmp.next;
}
Node two = new Node();
two.value = 5;
Node two2 = new Node();
two2.value = 3;
two2.next = two;
Node two3 = new Node();
two3.value = 1;
two3.next = two2;
Node twoTmp = two3;
System.out.println("Two");
while (twoTmp != null) {
System.out.println(twoTmp.value);
twoTmp = twoTmp.next;
}
/* System.out.println("Merge");
Node merge = mergeOrderedLinkList(one3, two3);
while (merge != null) {
System.out.println(merge.value);
merge = merge.next;
}*/
System.out.println("Loop");
Node loop = mergeOrderedLinkList(one3, two3);
while (loop != null) {
System.out.println(loop.value);
loop = loop.next;
}
}
}
|
package heylichen.alg.graph.components;
import heylichen.alg.graph.structure.EdgeWeightedGraphSource;
import heylichen.alg.graph.structure.weighted.EdgeWeightedGraph;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.io.IOException;
/**
* @author lichen
* @date 2020/4/8 16:12
* @desc
*/
@Configuration
public class EdgeWeightedGraphConfig {
@Bean
public EdgeWeightedGraph tinyEWG() throws IOException {
EdgeWeightedGraphSource gs = EdgeWeightedGraphSource.create("alg/graph/weighted/tinyEWG.txt");
return new EdgeWeightedGraph(gs);
}
@Bean
public EdgeWeightedGraph mediumEWG() throws IOException {
EdgeWeightedGraphSource gs = EdgeWeightedGraphSource.create("alg/graph/weighted/mediumEWG.txt");
return new EdgeWeightedGraph(gs);
}
}
|
package pl.edu.pw.elka.etherscan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
class EtherscanConfiguration {
@Bean
EtherscanFacade etherscanFacade() {
final RealEtherscanConnector etherscanConnector = new RealEtherscanConnector();
final EthereumAddressValidator ethereumAddressValidator = new EthereumAddressValidator();
return new EtherscanFacade(etherscanConnector, ethereumAddressValidator);
}
}
|
package com.shadow.domain;
import javax.persistence.Entity;
import javax.persistence.Table;
/**
* Created by qq65827 on 2015/1/26.
*/
@Entity
@Table(name = "imageFile")
public class ImageFile extends BaseObject {
public ImageFile() {
}
public ImageFile(String name, String comment) {
this.name = name;
this.comment = comment;
}
private String name;
private String comment;
private Long size;
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 Long getSize() {
return size;
}
public long getUserId() {
return userId;
}
public void setUserId(long userId) {
this.userId = userId;
}
public void setSize(Long size) {
this.size = size;
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
private String path;
private long userId;
}
|
package com.lenovohit.ssm.payment.web.rest;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.lenovohit.core.dao.Page;
import com.lenovohit.core.exception.BaseException;
import com.lenovohit.core.manager.GenericManager;
import com.lenovohit.core.utils.JSONUtils;
import com.lenovohit.core.utils.StringUtils;
import com.lenovohit.core.web.MediaTypes;
import com.lenovohit.core.web.rest.BaseRestController;
import com.lenovohit.core.web.utils.Result;
import com.lenovohit.core.web.utils.ResultUtils;
import com.lenovohit.ssm.payment.model.PayAccount;
/**
* 支付账户管理
*
*/
@RestController
@RequestMapping("/ssm/payment/account")
public class PayAccountController extends BaseRestController {
@Autowired
private GenericManager<PayAccount, String> payAccountManager;
@RequestMapping(value = "/info/{id}", method = RequestMethod.GET, produces = MediaTypes.JSON_UTF_8)
public Result forInfo(@PathVariable("id") String id){
PayAccount model = payAccountManager.get(id);
return ResultUtils.renderPageResult(model);
}
@RequestMapping(value = "/page/{start}/{limit}", method = RequestMethod.GET, produces = MediaTypes.JSON_UTF_8)
public Result forPage(@PathVariable("start") String start, @PathVariable("limit") String limit){
Page page = new Page();
page.setStart(start);
page.setPageSize(limit);
page.setQuery("from PayAccount where 1=1 payAccount by sort");
payAccountManager.findPage(page);
return ResultUtils.renderPageResult(page);
}
@RequestMapping(value = "/list", method = RequestMethod.GET, produces = MediaTypes.JSON_UTF_8)
public Result forList(@RequestParam(value = "data", defaultValue = "") String data) {
List<PayAccount> list = payAccountManager.findAll();
return ResultUtils.renderSuccessResult(list);
}
@RequestMapping(value="/create",method = RequestMethod.POST, produces = MediaTypes.JSON_UTF_8/*TEXT_PLAIN_UTF_8*/)
public Result forCreate(@RequestBody String data){
PayAccount model = JSONUtils.deserialize(data, PayAccount.class);
//TODO 校验
PayAccount saved = this.payAccountManager.save(model);
return ResultUtils.renderSuccessResult(saved);
}
@RequestMapping(value = "/update", method = RequestMethod.POST, produces = MediaTypes.JSON_UTF_8)
public Result forUpdate(@RequestBody String data) {
PayAccount model = JSONUtils.deserialize(data, PayAccount.class);
if(model==null || StringUtils.isBlank(model.getId())){
return ResultUtils.renderFailureResult();
}
this.payAccountManager.save(model);
return ResultUtils.renderSuccessResult();
}
@RequestMapping(value = "/remove/{id}",method = RequestMethod.DELETE, produces = MediaTypes.JSON_UTF_8)
public Result forDelete(@PathVariable("id") String id){
try {
this.payAccountManager.delete(id);
} catch (Exception e) {
throw new BaseException("删除失败");
}
return ResultUtils.renderSuccessResult();
}
}
|
/*
SQL Schema Migration Toolkit
Copyright (C) 2015 Cédric Tabin
This file is part of ssmt, a tool used to maintain database schemas up-to-date.
The author can be contacted on http://www.astorm.ch/blog/index.php?contact
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the
distribution.
3. The names of the authors may not be used to endorse or promote
products derived from this software without specific prior
written permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``AS IS'' AND ANY EXPRESS
OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package ch.astorm.ssmt.module.mysql;
import ch.astorm.ssmt.module.Module;
import ch.astorm.ssmt.module.Outputter;
import ch.astorm.ssmt.module.Parser;
import ch.astorm.ssmt.module.mysql.outputter.MySQLOutputter;
import ch.astorm.ssmt.module.mysql.parser.MySQLParser;
import java.io.PrintStream;
import java.util.Map;
/**
* Entry point of the MySQL module.
*/
public class MySQLModule implements Module {
/**
* Represents the module name.
*/
public static final String MODULE_NAME = "mysql";
/**
* Represents the module version.
*/
public static final String MODULE_VERSION = "0.1";
/**
* Returns {@link #MODULE_NAME}.
*/
@Override
public String getName() {
return MODULE_NAME;
}
/**
* Returns {@link #MODULE_VERSION}.
*/
@Override
public String getVersion() {
return MODULE_VERSION;
}
/**
* Returns a new {@code MySQLParser} instance.
*/
@Override
public Parser createParser(Map<String, String> cmdOptions) {
return new MySQLParser();
}
/**
* Returns a new {@code MySQLOutputter} instance.
*/
@Override
public Outputter createOutputter(Map<String, String> cmdOptions) {
return new MySQLOutputter();
}
/**
* Prints the available options.
*/
@Override
public void help(PrintStream out) {
out.print("No option is supported for the module "+MODULE_NAME+" (v"+MODULE_VERSION+")");
}
}
|
package io.gtrain.unit.registration;
import io.gtrain.domain.model.dto.LoginForm;
import io.gtrain.domain.model.dto.RegistrationForm;
import io.gtrain.domain.validator.RegistrationFormValidator;
import io.gtrain.unit.base.ApplicationUnitTestBase;
import org.junit.jupiter.api.Test;
import java.time.LocalDateTime;
import static org.assertj.core.api.Assertions.assertThat;
/**
* @author William Gentry
*/
public class RegistrationFormValidatorTest extends ApplicationUnitTestBase {
private RegistrationFormValidator registrationFormValidator = new RegistrationFormValidator();
@Test
public void registrationFormValidator_ShouldSupportRegistrationForm() {
assertThat(registrationFormValidator.supports(RegistrationForm.class)).isTrue();
}
@Test
public void registrationFormValidator_ShouldNotSupportAnyOtherClass() {
assertThat(registrationFormValidator.supports(LoginForm.class)).isFalse();
assertThat(registrationFormValidator.supports(String.class)).isFalse();
assertThat(registrationFormValidator.supports(LocalDateTime.class)).isFalse();
}
}
|
package com.sevael.lgtool.dao;
import java.io.InputStream;
import java.util.List;
import org.bson.Document;
import com.google.gson.JsonObject;
public interface EmailRequestDao {
String emailRequest(JsonObject requestDetails);
List<Document> getAllRequeter();
String uploadPdfFile(InputStream inputStream, String filename, String certificationid);
}
|
package fr.unice.polytech.isa.polyevent.cli.commands;
import fr.unice.polytech.isa.polyevent.cli.framework.Command;
import fr.unice.polytech.isa.polyevent.cli.framework.CommandBuilder;
import fr.unice.polytech.isa.polyevent.cli.framework.Context;
import fr.unice.polytech.isa.polyevent.stubs.DemandeReservationSalle;
import fr.unice.polytech.isa.polyevent.stubs.TypeSalle;
import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.XMLGregorianCalendar;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class AddReservation implements Command
{
private static final Identifier IDENTIFIER = Identifier.ADD_RESERVATION;
private final List<DemandeReservationSalle> demandeReservations;
private TypeSalle typeSalle;
private XMLGregorianCalendar dateDebut;
private XMLGregorianCalendar dateFin;
private AddReservation(List<DemandeReservationSalle> demandeReservations)
{
this.demandeReservations = demandeReservations;
}
private static String availableRoomType()
{
return Arrays.stream(TypeSalle.values()).map(Enum::name).collect(Collectors.joining(", "));
}
@Override
public void load(List<String> args) throws Exception
{
if (args.size() < 3)
{
String message = String.format("%s expects 3 arguments: %s TYPE_ROOM START_DATE END_DATE", IDENTIFIER, IDENTIFIER);
throw new IllegalArgumentException(message);
}
String value = args.get(0);
try
{
typeSalle = TypeSalle.valueOf(value);
}
catch (IllegalArgumentException e)
{
throw new IllegalArgumentException(String.format("The room type \"%s\" does not exist.%n" +
"Choose one type from the following list: %s.%nType help %s for more details.",
value, availableRoomType(), IDENTIFIER));
}
try
{
DatatypeFactory datatypeFactory = DatatypeFactory.newInstance();
dateDebut = datatypeFactory.newXMLGregorianCalendar(args.get(1));
dateFin = datatypeFactory.newXMLGregorianCalendar(args.get(2));
}
catch (IllegalArgumentException e)
{
throw new IllegalArgumentException(String.format("Illegal date format: %s", e.getMessage()));
}
}
@Override
public void execute()
{
DemandeReservationSalle demandeReservationSalle = new DemandeReservationSalle();
demandeReservationSalle.setTypeSalle(typeSalle);
demandeReservationSalle.setDateDebut(dateDebut);
demandeReservationSalle.setDateFin(dateFin);
demandeReservations.add(demandeReservationSalle);
}
public static class Builder implements CommandBuilder<AddReservation>
{
private final List<DemandeReservationSalle> demandeReservations;
Builder(List<DemandeReservationSalle> demandeReservations)
{
this.demandeReservations = demandeReservations;
}
@Override
public String identifier()
{
return IDENTIFIER.keyword;
}
@Override
public String describe()
{
return IDENTIFIER.description;
}
@Override
public String help()
{
return String.format("Usage: %s TYPE_ROOM START_DATE END_DATE%n" +
"Select a type room from the following list: %s%n" +
"Example: %s AMPHI 2018-12-03T16:00:00 2018-12-03T18:00:00",
IDENTIFIER, availableRoomType(), IDENTIFIER);
}
@Override
public AddReservation build(Context context)
{
return new AddReservation(demandeReservations);
}
}
}
|
package com.cloubiot.buddyWAPI.dao;
import org.springframework.data.repository.CrudRepository;
import com.cloubiot.buddyWAPI.model.dbentity.Channel;
public interface ChannelRepository extends CrudRepository<Channel, String>{
}
|
package au.gov.nsw.records.digitalarchive.struts.action;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import au.gov.nsw.records.digitalarchive.ORM.Publication;
import au.gov.nsw.records.digitalarchive.ORM.UploadedFile;
import au.gov.nsw.records.digitalarchive.base.BaseAction;
import au.gov.nsw.records.digitalarchive.service.FileService;
import au.gov.nsw.records.digitalarchive.service.FileServiceImpl;
public class UploadedFileAction extends BaseAction {
public ActionForward moveDown(ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response)
{
ActionForward forward = null;
if (!("").equalsIgnoreCase(request.getParameter("id")))
{
Integer fileID = new Integer(request.getParameter("id"));
String pageType = request.getParameter("pageType");
try
{
FileService fs = new FileServiceImpl();
UploadedFile topFile = fs.loadFile(fileID);
topFile.setFileOrder(topFile.getFileOrder()+1);
fs.updateFile(topFile);
Publication pub = fs.findPubViaFile(fileID);
UploadedFile downFile = fs.loadFileViaOrder(topFile.getFileOrder(), pub.getPublicationId(), fileID);
downFile.setFileOrder(downFile.getFileOrder() - 1);
fs.updateFile(downFile);
if (("edit").equals(pageType))
forward = new ActionForward("/agency_pages/publicationEdit.jsp?id=" + pub.getPublicationId());
else
forward = new ActionForward("/agency_pages/newPublication.jsp?id=" + pub.getPublicationId());
}catch(Exception ex)
{
logger.info("In class UploadedFileAction:moveDown()\n");
ex.printStackTrace();
}
}else
{
forward = mapping.findForward("home");
}
return forward;
}
public ActionForward moveUp(ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response)
{
ActionForward forward = null;
if (!("").equalsIgnoreCase(request.getParameter("id")))
{
Integer fileID = new Integer(request.getParameter("id"));
String pageType = request.getParameter("pageType");
try
{
FileService fs = new FileServiceImpl();
UploadedFile topFile = fs.loadFile(fileID);
topFile.setFileOrder(topFile.getFileOrder() - 1);
fs.updateFile(topFile);
Publication pub = fs.findPubViaFile(fileID);
UploadedFile downFile = fs.loadFileViaOrder(topFile.getFileOrder(), pub.getPublicationId(), fileID);
downFile.setFileOrder(downFile.getFileOrder() + 1);
fs.updateFile(downFile);
if (("edit").equals(pageType))
forward = new ActionForward("/agency_pages/publicationEdit.jsp?id=" + pub.getPublicationId());
else
forward = new ActionForward("/agency_pages/newPublication.jsp?id=" + pub.getPublicationId());
}catch(Exception ex)
{
logger.info("In class UploadedFileAction:moveUp()\n");
ex.printStackTrace();
}
}else
{
forward = mapping.findForward("home");
}
return forward;
}
}
|
package controles;
import java.util.ArrayList;
import juego.Escenario;
import objetos.aeronaves.*;
import objetos.powerUps.PowerUp;
import objetos.proyectiles.Proyectil;
/*
* Control que se encarga de recorrer las listas de objetos no controlados,
* removiendo los objetos que est�n destruidos.
*/
public class ControlRemoverDestruidos implements Control {
public void ejecutar() {
this.removerCivilesMuertos();
this.removerEnemigosMuertos();
this.removerProyectilesAliadosMuertos();
this.removerProyectilesEnemigosMuertos();
this.removerPowerUpsMuertos();
}
private void removerCivilesMuertos() {
ArrayList<Civil> civiles = Escenario.getInstance().getCiviles();
int largo = civiles.size();
Civil civil;
ArrayList<Civil> muertos = new ArrayList<Civil>();
for (int i = 0; i < largo; i++) {
civil = civiles.get(i);
if (civil.estaDestruido()) {
muertos.add(civil);
}
}
for (int i = 0; i < muertos.size(); i++) {
civiles.remove(muertos.get(i));
}
}
private void removerEnemigosMuertos() {
ArrayList<Enemigo> enemigos = Escenario.getInstance().getEnemigos();
int largo = enemigos.size();
Enemigo enemigo;
ArrayList<Enemigo> muertos = new ArrayList<Enemigo>();
for (int i = 0; i < largo; i++) {
enemigo = enemigos.get(i);
if (enemigo.estaDestruido()) {
muertos.add(enemigo);
}
}
for (int i = 0; i < muertos.size(); i++) {
enemigos.remove(muertos.get(i));
}
}
private void removerProyectilesAliadosMuertos() {
ArrayList<Proyectil> proyectiles = Escenario.getInstance()
.getProyectilesDelAlgo42();
int largo = proyectiles.size();
Proyectil proyectil;
ArrayList<Proyectil> muertos = new ArrayList<Proyectil>();
for (int i = 0; i < largo; i++) {
proyectil = proyectiles.get(i);
if (proyectil.estaDestruido()) {
muertos.add(proyectil);
}
}
for (int i = 0; i < muertos.size(); i++) {
proyectiles.remove(muertos.get(i));
}
}
private void removerProyectilesEnemigosMuertos() {
ArrayList<Proyectil> proyectiles = Escenario.getInstance()
.getProyectilesEnemigos();
int largo = proyectiles.size();
Proyectil proyectil;
ArrayList<Proyectil> muertos = new ArrayList<Proyectil>();
for (int i = 0; i < largo; i++) {
proyectil = proyectiles.get(i);
if (proyectil.estaDestruido()) {
muertos.add(proyectil);
}
}
for (int i = 0; i < muertos.size(); i++) {
proyectiles.remove(muertos.get(i));
}
}
private void removerPowerUpsMuertos() {
ArrayList<PowerUp> powerUps = Escenario.getInstance().getPowerUps();
int largo = powerUps.size();
PowerUp powerUp;
ArrayList<PowerUp> muertos = new ArrayList<PowerUp>();
for (int i = 0; i < largo; i++) {
powerUp = powerUps.get(i);
if (powerUp.estaDestruido()) {
muertos.add(powerUp);
}
}
for (int i = 0; i < muertos.size(); i++) {
powerUps.remove(muertos.get(i));
}
}
}
|
package edu.westga.retirement.test;
import static org.junit.Assert.*;
import org.junit.Test;
import edu.westga.retirement.model.SavingsYear;
/**
* Test the SavingsYear class getNextYear method
* @author Kenji Okamoto
* @version 20151120
*
*/
public class SavingsYearGetNextYearTest {
/**
* Test getNextYear creates a new year using this year's end balance
*/
@Test
public void testGetNextYearHasBeginBalanceEqualToCurrentEndBalance() {
SavingsYear previousYear = new SavingsYear(40, 5000, 2000, .06);
SavingsYear testYear = previousYear.getNextYear();
assertEquals(previousYear.getEndBalance(), testYear.getBeginBalance());
}
/**
* Test getNextYear will use the same appreciation rate
*/
@Test
public void testGetNextYearUsesSameAppreciationRate() {
SavingsYear previousYear = new SavingsYear(40, 1000, 0, .1);
SavingsYear testYear = previousYear.getNextYear();
assertEquals(110, testYear.getAppreciation());
}
/**
* Test getNextYear uses the same contribution amount
*/
@Test
public void testGetNextYearUsesSameContribution() {
SavingsYear previousYear = new SavingsYear(40, 1000, 97, 0);
SavingsYear testYear = previousYear.getNextYear();
assertEquals(97, testYear.getContribution());
}
/**
* Test getNextYear uses the same contribution amount when calculating end balance
*/
@Test
public void testGetNextYearUsesSameContributionInCalculations() {
SavingsYear previousYear = new SavingsYear(40, 1000, 100, 0);
SavingsYear testYear = previousYear.getNextYear();
assertEquals(1200, testYear.getEndBalance());
}
/**
* Test getNextYear will use the same appreciationRate and contribution
*/
@Test
public void testGetNextYearUsesSameAppreciationRateAndContribution() {
SavingsYear previousYear = new SavingsYear(40, 1839, 237, .07);
SavingsYear testYear = previousYear.getNextYear();
assertEquals(2595, testYear.getEndBalance());
}
/**
* Test getNextYear will return a year with age incremented
*/
@Test
public void testGetNextYearReturnsNextYearWithAgeIncremented() {
SavingsYear previousYear = new SavingsYear(40, 1839, 237, .07);
SavingsYear testYear = previousYear.getNextYear();
assertEquals(41, testYear.getAge());
}
}
|
package pp.model;
import pp.model.enums.BtlType;
/**
* @author alexander.sokolovsky.a@gmail.com
*/
public class Btl extends AModel {
private Boolean prepare;
private Boolean check;
private Boolean back;
private Boolean fight;
private String vars;
private BtlType type;
private Long limitGlad;
private Long limitSkl;
private Long maxLevel;
private String xml;
private Long timeLeft;
private String gladTip;
private Long fvid;
private String user1Login;
private String user2Login;
private String tourmentTitle;
private Long champ;
private Long minAwardFee;
private String tut;
private String user1Url;
private String user2Url;
private String armorLevels;
private String url;
private boolean timeOut;
private long oppGuild;
public Boolean getPrepare() {
return prepare;
}
public void setPrepare(final Boolean prepare) {
this.prepare = prepare;
}
public Boolean getCheck() {
return check;
}
public void setCheck(final Boolean check) {
this.check = check;
}
public Boolean getBack() {
return back;
}
public void setBack(final Boolean back) {
this.back = back;
}
public Boolean getFight() {
return fight;
}
public void setFight(final Boolean fight) {
this.fight = fight;
}
public String getVars() {
return vars;
}
public void setVars(final String vars) {
this.vars = vars;
}
public BtlType getType() {
return type;
}
public void setType(final BtlType type) {
this.type = type;
}
public Long getLimitGlad() {
return limitGlad;
}
public void setLimitGlad(final Long limitGlad) {
this.limitGlad = limitGlad;
}
public Long getLimitSkl() {
return limitSkl;
}
public void setLimitSkl(final Long limitSkl) {
this.limitSkl = limitSkl;
}
public Long getMaxLevel() {
return maxLevel;
}
public void setMaxLevel(final Long maxLevel) {
this.maxLevel = maxLevel;
}
public String getXml() {
return xml;
}
public void setXml(final String xml) {
this.xml = xml;
}
public Long getTimeLeft() {
return timeLeft;
}
public void setTimeLeft(final Long timeLeft) {
this.timeLeft = timeLeft;
}
public String getGladTip() {
return gladTip;
}
public void setGladTip(final String gladTip) {
this.gladTip = gladTip;
}
public Long getFvid() {
return fvid;
}
public void setFvid(final Long fvid) {
this.fvid = fvid;
}
public String getUser1Login() {
return user1Login;
}
public void setUser1Login(final String user1Login) {
this.user1Login = user1Login;
}
public String getUser2Login() {
return user2Login;
}
public void setUser2Login(final String user2Login) {
this.user2Login = user2Login;
}
public String getTourmentTitle() {
return tourmentTitle;
}
public void setTourmentTitle(final String tourmentTitle) {
this.tourmentTitle = tourmentTitle;
}
public Long getChamp() {
return champ;
}
public void setChamp(final Long champ) {
this.champ = champ;
}
public Long getMinAwardFee() {
return minAwardFee;
}
public void setMinAwardFee(final Long minAwardFee) {
this.minAwardFee = minAwardFee;
}
public String getTut() {
return tut;
}
public void setTut(final String tut) {
this.tut = tut;
}
public String getUser1Url() {
return user1Url;
}
public void setUser1Url(final String user1Url) {
this.user1Url = user1Url;
}
public String getUser2Url() {
return user2Url;
}
public void setUser2Url(final String user2Url) {
this.user2Url = user2Url;
}
public String getArmorLevels() {
return armorLevels;
}
public void setArmorLevels(final String armorLevels) {
this.armorLevels = armorLevels;
}
public String getUrl() {
return url;
}
public void setUrl(final String url) {
this.url = url;
}
@Override
public String toString() {
return "Btl{" +
"id=" + id +
", prepare=" + prepare +
", check=" + check +
", back=" + back +
", fight=" + fight +
", type=" + type +
", limitGlad=" + limitGlad +
", limitSkl=" + limitSkl +
", maxLevel=" + maxLevel +
", user1Login='" + user1Login + '\'' +
", user2Login='" + user2Login + '\'' +
", tourmentTitle='" + tourmentTitle + '\'' +
'}';
}
public void setTimeOut(boolean timeOut) {
this.timeOut = timeOut;
}
public boolean isTimeOut() {
return timeOut;
}
public void setOppGuild(long oppGuild) {
this.oppGuild = oppGuild;
}
public long getOppGuild() {
return oppGuild;
}
}
|
package com.jarvis.rocketmq.controller;
import com.jarvis.rocketmq.jms.JMSConfig;
import com.jarvis.rocketmq.jms.PayProducer;
import com.jarvis.rocketmq.model.ProductOrder;
import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.remoting.exception.RemotingException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.HashMap;
import java.util.List;
@RestController
public class PayController {
Logger logger = LoggerFactory.getLogger(this.getClass());
@Autowired
private PayProducer payProducer;
/*默认不会自动创建topic, 需要手动自行创建,或者修改broker的配置,可以自动创建*/
// private static final String topic = "jarvis_pay_test_topic";
/**
* 出现了sendDefaultImpl call timeout的异常有可能是多网卡的问题(内网和公网)
* 需要在broker中配置broker.conf配置公网网卡ip
* 顺序消息的作用,加入多个消息, a消费完才能消费b的情况,需要顺序消息,全局顺序的话性能差,在交易情况可能用
* 局部顺序性能强,但是需要生产段和消费端配合使用,取唯一的东西作为选取队列id凭证
* 顺序消息不能在异步发送和广播模式使用
* */
@RequestMapping("/api/v1/pay_cub")
public Object callback() throws InterruptedException, RemotingException, MQClientException, MQBrokerException {
//key的话相当于id
Message message = new Message(JMSConfig.TOPIC, "a", "hello jarvis22".getBytes());
message.setDelayTimeLevel(2);
// SendResult sendResult = payProducer.getProducer().send(message);//同步发送
//里边的arg对应的是外层的arg
SendResult sendResult = payProducer.getProducer().send(message, (mqs, msg, arg)->{
// Integer queueNumber = (Integer) arg;
Integer queueNum = Integer.parseInt(arg.toString());
return mqs.get(queueNum);
}, 0);
payProducer.getProducer().send(message, (mqs, msg, arg) -> {
// Integer queueNumber = (Integer) arg;
Integer queueNum = Integer.parseInt(arg.toString());
return mqs.get(queueNum);
}, 3, new SendCallback() {
@Override
public void onSuccess(SendResult sendResult) {
System.out.printf("异步发送:%s \n", sendResult);
}
@Override
public void onException(Throwable e) {
}
});
/*//异步发送
payProducer.getProducer().send(message, new SendCallback(){
@Override
public void onSuccess(SendResult sendResult) {
System.out.println(sendResult);
}
@Override
public void onException(Throwable e) {
}
});*/
logger.info("sendResult,{}", sendResult);
return sendResult;
}
@RequestMapping("orderList")
public Object orderList() throws InterruptedException, RemotingException, MQClientException, MQBrokerException {
List<ProductOrder> list= ProductOrder.getOrderList();
for(ProductOrder order : list){
Message message = new Message(JMSConfig.ORDER_TEST_TOPIC, "",
String.valueOf(order.getOrderid()), order.toString().getBytes());
SendResult result = payProducer.getProducer().send(message, (mqs, msg, args)->{
Long id = (Long) args;
long index = id % mqs.size();
return mqs.get((int) index);
}, order.getOrderid());
logger.info("sendOrderly:{}", result);
}
return new HashMap<>();
}
}
|
package io.github.jitinsharma.insplore.adapter;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.ArrayList;
import io.github.jitinsharma.insplore.R;
import io.github.jitinsharma.insplore.model.OnPlacesClick;
import io.github.jitinsharma.insplore.model.TopDestinationObject;
import io.github.jitinsharma.insplore.utilities.AnimationUtilities;
/**
* Created by jitin on 28/06/16.
*/
public class TopDestinationAdapter extends RecyclerView.Adapter<TopDestinationAdapter.TopDestinationVH> {
Context context;
ArrayList<TopDestinationObject> topDestinationObjects;
LayoutInflater layoutInflater;
int duration = 700;
OnPlacesClick onPlacesClick;
public TopDestinationAdapter(Context context, ArrayList<TopDestinationObject> topDestinationObjects, OnPlacesClick onPlacesClick) {
this.context = context;
this.topDestinationObjects = topDestinationObjects;
this.onPlacesClick = onPlacesClick;
}
@Override
public TopDestinationVH onCreateViewHolder(ViewGroup parent, int viewType) {
layoutInflater = LayoutInflater.from(context);
View view = layoutInflater.inflate(R.layout.item_top_destination, parent, false);
return new TopDestinationVH(view);
}
@Override
public void onBindViewHolder(TopDestinationVH holder, int position) {
TopDestinationObject current = topDestinationObjects.get(position);
holder.details.setVisibility(View.GONE);
if (current.isPlaceEnabled()){
holder.details.setVisibility(View.VISIBLE);
}
else{
holder.details.setVisibility(View.GONE);
}
holder.cityName.setText(current.getCityName());
holder.noOfFlights.setText(current.getNoOfFlights());
holder.noOfPax.setText(current.getNoOfPax());
AnimationUtilities.setAdapterSlideAnimation(holder.itemView, context, position, duration);
duration = duration + 100;
}
@Override
public int getItemCount() {
return topDestinationObjects.size();
}
class TopDestinationVH extends RecyclerView.ViewHolder {
TextView cityName;
TextView noOfFlights;
TextView noOfPax;
TextView details;
public TopDestinationVH(View itemView) {
super(itemView);
itemView.setClickable(true);
cityName = (TextView)itemView.findViewById(R.id.top_dest_city);
noOfFlights = (TextView) itemView.findViewById(R.id.top_dest_flights);
noOfPax = (TextView)itemView.findViewById(R.id.top_dest_passengers);
details = (TextView)itemView.findViewById(R.id.top_dest_detail);
details.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
onPlacesClick.onClick(getAdapterPosition());
}
});
}
}
}
|
package com.github.binarywang.wxpay.bean.result;
import lombok.Data;
import lombok.NoArgsConstructor;
import me.chanjar.weixin.common.util.ToStringUtils;
import java.io.Serializable;
import java.util.List;
@Data
@NoArgsConstructor
public class WxPayBillResult implements Serializable {
private static final long serialVersionUID = -7687458652694204070L;
@Override
public String toString() {
return ToStringUtils.toSimpleString(this);
}
/**
* 对账返回对象
*/
private List<WxPayBillBaseResult> wxPayBillBaseResultLst;
/**
* 总交易单数
*/
private String totalRecord;
/**
* 总交易额
*/
private String totalFee;
/**
* 总退款金额
*/
private String totalRefundFee;
/**
* 总代金券或立减优惠退款金额
*/
private String totalCouponFee;
/**
* 手续费总金额
*/
private String totalPoundageFee;
}
|
package de.cuuky.varo.listener.helper.cancelable;
public enum CancelAbleType {
FREEZE, MUTE, PROTECTION;
}
|
package wirusy;
public class Symulacja {
private final Szczepionka szczepionka;
private final Wirus wirus;
public Symulacja(Wirus wirus, Szczepionka szczepionka) {
this.szczepionka = szczepionka;
this.wirus = wirus;
}
public boolean czyWirusPodatnyPoSymulacji(int ileMiesiecy) {
for (int i = 0; i < ileMiesiecy; i++) {
this.wirus.symulujMiesiac();
}
return wirus.czyPodatnyNaGenerowanePrzeciwcialo(szczepionka);
}
}
|
/*
* Created on Jul 25, 2015
*/
package basics;
import javafx.application.Application;
import javafx.geometry.HPos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.Priority;
import javafx.stage.Stage;
public class BasicJavaFXEvents extends Application {
private int count = 0;
@Override
public void start(Stage stage) {
Button button = new Button("Increment");
Label counter = new Label(Integer.toString(count));
button.setOnAction(ae -> {
count++;
counter.setText(Integer.toString(count));
});
GridPane root = new GridPane();
root.add(button, 0, 0);
root.add(counter, 1, 0);
GridPane.setVgrow(button, Priority.ALWAYS);
GridPane.setHalignment(counter, HPos.RIGHT);
GridPane.setHgrow(counter, Priority.ALWAYS);
button.prefHeightProperty().bind(root.heightProperty());
Scene scene = new Scene(root,200,50);
stage.setScene(scene);
stage.show();
}
public static void main(String[] args) {
launch(args);
}
}
|
/**
* Created by DELL on 2018/10/19.
*
* javac:将jvva文件编译成class文件,使用方式:javac xxx.java,执行这个命令时,要能保证在默认classpath(理解成一个根目录)下,能找到这个文件,
* 默认情况下,classpath为执行命令的当前目录。如果以当前目录开始找不到那个java文件的话,就出现文件找不的错误。与文件的包名没有关系,只要使用classpath和文件拼接起来的绝对路径
* 能够找到这个文件,就可以对其进行编译。
* 如果被编译的java文件中依赖由其他的java文件,要先编译依赖的那个java文件,那么就从classpath指定的路径开始出发找这个依赖的java文件,从classpath出发去哪找呢?
* 这个就依靠import指定的包名对应的目录或者使用这个依赖的类明确指定的包名对用的目录里面找,如果没有import,在引用时也没有指定包名的话,那就表示两者在同一个包中,
* 那么就从被编译的类所在包指定的目录里面找。如果没有找到的话,就会报错,找不到符号,如果找到了这个文件,还要进一步验证找到的这个类是否就是包指定的那个,
* 验证方式就是这个文件的目录是否和包一样,如果不一样的,会出现验证错误。
*
* java:执行class文件,执行这个命令时,一定要保证classpath为class的包的的上一级目录才可以。
*
*
*/
package commondliine;
|
package com.company.lesson08;
// for while do/while
public class Test {
public static void main(String[] args) {
for(int i = 0; i < 3; i++){
int j = 0;
while (j < 5) {
System.out.println("inner " + j);
j++;
}
System.out.println("text " + i);
}
/* int i = 0;
while (i < 10){
System.out.println("text " + i);
i++;
int j = 0;
while (j < 10) {
System.out.println("text " + j);
j++;
}
}
int j = 0;
do{
System.out.println("text " + j);
j++;
}while (j < 10);*/
}
}
|
package com.pisen.ott.launcher.message;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.izy.widget.BaseListAdapter;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import cn.jpush.android.api.JPushInterface;
import com.pisen.ott.launcher.R;
import com.pisen.ott.launcher.base.DefaultActivity;
import com.pisen.ott.launcher.utils.DateUtils;
import com.pisen.ott.launcher.widget.FocusListView;
/**
* 注册静态广播接收 {@link JPushInterface}
*
* @author mahuan
* @version 1.0 2015年2月12日 下午5:30:16
* @updated [2015 下午5:30:16]:
*/
public class MessageCenterActivity extends DefaultActivity implements OnItemClickListener {
public final static String MESSAGE_RECEIVED_ACTION = "com.pisen.ott.launcher.message.MESSAGE_RECEIVED_ACTION";
public static final String KEY = "MSG";
private FocusListView lstMsgCenter;
private BaseListAdapter<MessageInfo> msgAdapter;
private List<MessageInfo> mListInfos = new ArrayList<MessageInfo>();
private TextView txtMsgTip;
public static Boolean isForeground = false;
private UpdateMsgReceiver mUpdateMsgReceiver;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.message_center);
// 初始化View
initView();
// 异步加载数据
new QueryMessageTask().execute();
// 注册消息通知
registerMessageReceiver();
}
private void initView() {
lstMsgCenter = (FocusListView) findViewById(R.id.lvMsgCenter);
txtMsgTip = (TextView) findViewById(R.id.txt_msg_tip);
msgAdapter = new MsgAdapter(this);
lstMsgCenter.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
lstMsgCenter.setAdapter(msgAdapter);
lstMsgCenter.setOnItemClickListener(this);
}
public void registerMessageReceiver() {
mUpdateMsgReceiver = new UpdateMsgReceiver();
IntentFilter filter = new IntentFilter();
filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
filter.addAction(MESSAGE_RECEIVED_ACTION);
registerReceiver(mUpdateMsgReceiver, filter);
}
@Override
protected void onResume() {
isForeground = true;
super.onResume();
}
@Override
protected void onDestroy() {
isForeground = false;
unregisterReceiver(mUpdateMsgReceiver);
super.onDestroy();
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
MessageInfo info = (MessageInfo) parent.getItemAtPosition(position);
MessageManager msgMgr = MessageManager.getInstance(MessageCenterActivity.this);
msgMgr.updateMessage(MessageInfo.Table.MSG_READ_FLAG, MessageInfo.MESSAGE_READ, info.id);
msgMgr.updateMessage(MessageInfo.Table.MSG_READ_TIME, DateUtils.getCurrentTimeMillis(), info.id);
info.read_flag = MessageInfo.MESSAGE_READ;
info.read_time = String.valueOf(DateUtils.getCurrentTimeMillis());
msgAdapter.notifyDataSetChanged();
startActivity(info);
}
/**
* @desc 消息中心在前端,接收新消息广播
*/
class UpdateMsgReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (MESSAGE_RECEIVED_ACTION.equals(intent.getAction())) {
MessageInfo info = (MessageInfo) intent.getSerializableExtra(MessageInfo.MESSAGE_NEW);
if (null != info && msgAdapter != null) {
msgAdapter.getData().add(0, info);
}
msgAdapter.notifyDataSetChanged();
}
}
}
/**
* @author mahuan
* @version 1.0 2015年2月12日 下午5:48:27
* @updated 适配器类
*/
class MsgAdapter extends BaseListAdapter<MessageInfo> {
public MsgAdapter(Context context) {
super();
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
ViewHolder viewHolder;
if (view == null) {
view = LayoutInflater.from(parent.getContext()).inflate(R.layout.messsage_center_item_file, null);
view.setTag(viewHolder = new ViewHolder());
viewHolder.imgMsgIcon = (ImageView) view.findViewById(R.id.imgMsgIcon);
viewHolder.txtNewsTitle = (TextView) view.findViewById(R.id.txtNewsTitle);
viewHolder.imgArrows = (ImageView) view.findViewById(R.id.imgArrows);
} else {
viewHolder = (ViewHolder) view.getTag();
}
// 可以通过消息类型进一步判断
viewHolder.txtNewsTitle.setText(getItem(position).title);
MessageInfo info = getItem(position);
if (info.read_flag == 1) {
viewHolder.imgMsgIcon.setImageResource(R.drawable.msg_ic_gray);
viewHolder.txtNewsTitle.setTextColor(Color.GRAY);
} else {
viewHolder.imgMsgIcon.setImageResource(R.drawable.msg_ic_light);
viewHolder.txtNewsTitle.setTextColor(Color.WHITE);
}
return view;
}
class ViewHolder {
ImageView imgArrows, imgMsgIcon;
TextView txtNewsTitle;
}
}
class QueryMessageTask extends AsyncTask<Void, Void, List<MessageInfo>> {
@Override
protected List<MessageInfo> doInBackground(Void... params) {
return MessageManager.getInstance(MessageCenterActivity.this).getNewSortMessage();
}
@Override
protected void onPostExecute(List<MessageInfo> result) {
super.onPostExecute(result);
mListInfos.clear();
mListInfos.addAll(result);
msgAdapter.setData(mListInfos);
lstMsgCenter.setEmptyView(txtMsgTip);
}
}
/**
* @describtion 跳转详细消息
* @param obj
*/
public void startActivity(Serializable obj) {
Intent intent = new Intent();
Bundle bundle = new Bundle();
bundle.putSerializable(KEY, obj);
intent.putExtras(bundle);
intent.setClass(this, MessageDetailActivity.class);
startActivity(intent);
overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
}
}
|
package ExcelDemo;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.testng.annotations.Test;
public class CreateWorkbookDemo
{
@Test
public void f() throws IOException
{
//create blank Workbook
XSSFWorkbook wbObj = new XSSFWorkbook();
//Create file DemoDDT
FileOutputStream outObj = new FileOutputStream(new File("Demo.xlsx"));
//to perform Write operation on Workbook
wbObj.write(outObj);
outObj.close();
System.out.println("DemoDDT create successfully!");
}
}
|
package com.material.service;
import java.util.List;
import com.material.bean.MaterialCategoryBean;
import com.material.bean.MaterialTypeBean;
import com.material.bean.UnitBean;
public interface MaterialService {
MaterialCategoryBean getMaterialCategoryById(String categoryId);
List<MaterialCategoryBean> getMaterialCategories();
UnitBean getUnitById(String unitId);
List<UnitBean> getUnits();
MaterialTypeBean getMaterialTypeById(String typeId);
List<MaterialTypeBean> getMaterialTypes();
public List<UnitBean> findUnitByName(String categoryId);
public List<MaterialTypeBean> findMaterialTypeByName(String categoryId);
MaterialCategoryBean getMaterialCategoryByName(String categoryId);
}
|
package com.kingbom.rabbitmq.producer.dto;
import com.kingbom.rabbitmq.producer.model.Transaction;
import java.util.List;
/**
* Created by bombay on 2/6/2018 AD.
*/
public class TransactionRequest {
private List<Transaction> transactions;
public List<Transaction> getTransactions() {
return transactions;
}
public void setTransactions(List<Transaction> transactions) {
this.transactions = transactions;
}
}
|
package telas;
import componentes.MeuCampoComboBox;
import componentes.MeuCampoData;
import componentes.MeuCampoMonetario;
import componentes.MeuCampoTextArea;
import componentes.MeuJTextField;
import java.math.BigDecimal;
import javax.swing.event.InternalFrameAdapter;
import javax.swing.event.InternalFrameEvent;
public class TelaContasAReceber extends TelaCadastro implements Runnable{
public static TelaContasAReceber telaContasAReceber;
public String[][] parcelas = {
{"", "1"},
{"", "2"},
{"", "3"},
{"", "4"},
{"", "5"},
{"", "6"},
{"", "7"},
{"", "8"},
{"", "9"},
{"", "10"},
{"", "11"},
{"", "12"}
};
private MeuJTextField campoCliente = new MeuJTextField(true, "Nome do Cliente", 30, "[^A-Z|^ |^^|^~|^´|^`]");
private MeuCampoComboBox campoParcela = new MeuCampoComboBox(true, "Quantidade de Parcelas", parcelas, true);
private MeuCampoMonetario campoParcelaAPagar = new MeuCampoMonetario(true, "Valor da(s) Parcela(s)", false, 8);
private MeuCampoMonetario campoTotal = new MeuCampoMonetario(true, "Total", false, 8);
private MeuCampoData campoDataPag = new MeuCampoData(true, "Data de Pagamento", 8);
private MeuCampoTextArea campoDescPag = new MeuCampoTextArea(true, "Descrição da Conta", 400, 150);
public TelaContasAReceber() {
super("Contas a Receber");
montarTela();
IconeFrame("/icone/Contas a Receber.png");
minimoTamanhoTela();
}
public void montarTela() {
adicionaComponentes(1, 1, 1, 1, campoCliente);
adicionaComponentes(1, 3, 1, 1, campoParcela);
adicionaComponentes(1, 5, 1, 1, campoParcelaAPagar);
adicionaComponentes(3, 1, 1, 1, campoDescPag);
adicionaComponentes(3, 3, 1, 1, campoDataPag);
adicionaComponentes(5, 1, 1, 1, campoTotal);
//adicionaComponentes(5, 1, 1, 1, campoDescPag);
pack();
habilitaComponentes(false);
}
public static TelaCadastro getTela() { //Estático para poder ser chamado de outras classes sem a necessidade de ter criado um objeto anteriormente.
if (telaContasAReceber == null) { //Tela não está aberta, pode criar uma nova tela
telaContasAReceber = new TelaContasAReceber();
telaContasAReceber.addInternalFrameListener(new InternalFrameAdapter() { //Adiciona um listener para verificar quando a tela for fechada, fazendo assim a remoção da mesma junto ao JDesktopPane da TelaSistema e setando a variável tela = null para permitir que a tela possa ser aberta novamente em outro momento. Basicamente o mesmo controle efetuado pela tela de pesquisa, porém de uma forma um pouco diferente.
@Override
public void internalFrameClosed(InternalFrameEvent e) {
TelaSistema.jdp.remove(telaContasAReceber);
telaContasAReceber = null;
}
});
TelaSistema.jdp.add(telaContasAReceber);
}
//Depois do teste acima, independentemente dela já existir ou não, ela é selecionada e movida para frente
TelaSistema.jdp.setSelectedFrame(telaContasAReceber);
TelaSistema.jdp.moveToFront(telaContasAReceber);
return telaContasAReceber;
}
/**
*
*/
@Override
public void run() {
BigDecimal parcela = new BigDecimal((double) campoParcela.getValor());
BigDecimal valorParcela = new BigDecimal((char[]) campoParcelaAPagar.getValor());
BigDecimal total = parcela.multiply(valorParcela);
campoTotal.setValor(total);
}
}
|
package shoplistgener.domain;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
/**
* Ingredient encapsulates a single ingredient used in a recipe, and
* offers methods for manipulating them
*/
public class Ingredient implements Comparable<Ingredient> {
private String name;
private Unit unit;
private Integer requestedQuantity;
/**
* Constructor
* @param name name of the ingredient
* @param unit Enum Type associated with an ingredient (e.g., KG)
*/
public Ingredient(String name, Unit unit) {
this.name = name;
this.unit = unit;
this.requestedQuantity = null;
}
/**
* Alternative constructor
* @param name name of the ingredient
* @param unit Enum Type associated with an ingredient (e.g., KG)
* @param quantity how much of a given unit the recipe calls for
*/
public Ingredient(String name, Unit unit, Integer quantity) {
this(name, unit);
this.setRequestedQuantity(quantity);
}
/**
* Combines two Ingredient-objects into a single Ingredient-object
* @param first the first Ingredient-object to be merged
* @param second the second Ingredient-object to be merged
* @return Ingredient-object that retains the name and unit of the first, but
* combines the quantities of both
*/
public static Ingredient combineIngredients(Ingredient first, Ingredient second) {
return new Ingredient(first.name, first.unit, first.requestedQuantity + second.requestedQuantity);
}
@Override
public int compareTo(Ingredient other) {
return this.name.compareTo(other.name);
}
@Override
public boolean equals(Object other) {
if (this == other) {
return true;
}
if (!(other instanceof Ingredient)) {
return false;
}
Ingredient otherIngredient = (Ingredient) other;
if (this.name.equals(otherIngredient.name)) {
return true;
}
return false;
}
public String getName() {
return this.name;
}
public Unit getUnit() {
return this.unit;
}
public Integer getRequestedQuantity() {
return this.requestedQuantity;
}
@Override
public int hashCode() {
return this.name.hashCode();
}
public void setRequestedQuantity(Integer quantity) {
this.requestedQuantity = quantity;
}
/**
* Returns an alphabetically sorted list of ingredients, in which duplicates have been combined
* @param ingredients List of Ingredient-objects
* @return sorted and duplicate-free List of Ingredient-objects
*/
public static List<Ingredient> sortIngredients(List<Ingredient> ingredients) {
//solve edge case that came up with unit testing:
if (ingredients.size() <= 1) {
return ingredients;
}
List<Ingredient> ingredientsSorted = ingredients.stream()
.sorted()
.collect(Collectors.toCollection(ArrayList::new));
List<Ingredient> combinedIngredients = new ArrayList<Ingredient>();
Ingredient previous = new Ingredient("", Unit.CL, 0);
for (int i = 1; i < ingredientsSorted.size(); i++) {
if (ingredientsSorted.get(i).equals(ingredientsSorted.get(i - 1))) {
if (ingredientsSorted.get(i).equals(previous)) {
combinedIngredients.get(combinedIngredients.size() - 1).setRequestedQuantity(ingredientsSorted.get(i).getRequestedQuantity() + combinedIngredients.get(combinedIngredients.size() - 1).getRequestedQuantity());
continue;
}
combinedIngredients.add(Ingredient.combineIngredients(ingredientsSorted.get(i), ingredientsSorted.get(i - 1)));
previous = ingredientsSorted.get(i - 1);
} else {
if (!combinedIngredients.contains(ingredientsSorted.get(i - 1))) {
combinedIngredients.add(ingredientsSorted.get(i - 1));
}
}
}
//add the last ingredient only if not duplicate
if (!ingredientsSorted.get(ingredientsSorted.size() - 1).equals(combinedIngredients.get(combinedIngredients.size() - 1))) {
combinedIngredients.add(ingredientsSorted.get(ingredientsSorted.size() - 1));
}
return combinedIngredients;
}
/**
* Subtract the contents of the second parameter from the contents of the first parameter
* @param original list of Ingredient-objects
* @param subtract list of Ingredients-objects
* @return subtracted list of Ingredient-objects
*/
public static List<Ingredient> subtractIngredients(List<Ingredient> original, List<Ingredient> subtract) {
//O(n^2) algorithm, no optimization required :)
List<Ingredient> removed = new ArrayList<Ingredient>();
for (Ingredient ing : subtract) {
for (Ingredient orig : original) {
if (ing.equals(orig)) {
if (ing.getRequestedQuantity() > orig.getRequestedQuantity()) {
removed.add(orig);
} else {
int leftoverQuantity = orig.getRequestedQuantity() - ing.getRequestedQuantity();
orig.setRequestedQuantity(leftoverQuantity);
}
}
}
}
for (Ingredient ing : removed) {
original.remove(ing);
}
return Ingredient.sortIngredients(original);
}
@Override
public String toString() {
return this.name + ";" + String.valueOf(this.requestedQuantity) + ";" + this.unit.toString().toLowerCase();
}
}
|
package com.voter.info.service;
import java.util.List;
import java.util.Map;
import com.voter.info.model.UserRequest;
import com.voter.info.model.Voter;
/**
* Service layer interface
*
* @author Shyam | catch.shyambaitmangalkar@gmail.com
*
*/
public interface VoterService {
public abstract List<Voter> findVoter(UserRequest request);
public abstract List<String> getAllDistricts();
public abstract List<String> getAllAssemblyConstituencies(String districtName);
public abstract Map<String, List<String>> getDistrictsWithAssemblyConstituencies();
}
|
package com.example.jadynai.particle;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
public class MainActivity extends AppCompatActivity {
private View mLizi1;
private View mLizi2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mLizi1 = findViewById(R.id.lizi1);
mLizi2 = findViewById(R.id.lizi2);
findViewById(R.id.btn).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
click();
}
});
}
public void click() {
if (mLizi1.getVisibility() == View.VISIBLE) {
mLizi1.setVisibility(View.GONE);
mLizi2.setVisibility(View.VISIBLE);
} else {
mLizi1.setVisibility(View.VISIBLE);
mLizi2.setVisibility(View.GONE);
}
}
}
|
package com.javarush.task.task18.task1803;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
/*
Самые частые байты
*/
public class Solution {
public static void main(String[] args) throws Exception {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String file = reader.readLine();
FileInputStream fileInputStream = new FileInputStream(file);
List<Integer> list = new ArrayList<>();
int[] array = new int[256];
while(fileInputStream.available() > 0){
array[fileInputStream.read()]++;
}
int max = 0;
for (int i : array){
if(i > max){
max = i;
}
}
for (int i = 0; i < array.length; i++) {
if(array[i] == max){
list.add(i);
}
}
for (Integer x : list){
System.out.print(x + " ");
}
fileInputStream.close();
}
}
|
package otf.obj;
import java.io.Serializable;
/**
* @author ⋈
*
*/
public class FoodEntity implements Serializable
{
private Long id;
private int weight;
private int carbohydrates;
private String name;
/**
* @return the id
*/
public Long getId()
{
return this.id;
}
/**
* @param id
* the id to set
*/
public void setId(Long id)
{
this.id = id;
}
/**
* @return the weight
*/
public int getWeight()
{
return this.weight;
}
/**
* @param weight
* the weight to set
*/
public void setWeight(int weight)
{
this.weight = weight;
}
/**
* @return the carbohydrates
*/
public int getCarbohydrates()
{
return this.carbohydrates;
}
/**
* @param carbohydrates
* the carbohydrates to set
*/
public void setCarbohydrates(int carbohydrates)
{
this.carbohydrates = carbohydrates;
}
/**
* @return the name
*/
public String getName()
{
return this.name;
}
/**
* @param name
* the name to set
*/
public void setName(String name)
{
this.name = name;
}
}
|
package io.github.kilmajster.controller;
import io.github.kilmajster.model.HelloMessage;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.concurrent.atomic.AtomicInteger;
@RestController
@RequestMapping("/")
public class MainController {
private AtomicInteger counter = new AtomicInteger(0);
@GetMapping("/")
public @ResponseBody HelloMessage index(HttpServletRequest request) {
System.out.println("Request from " + request.getRemoteHost());
return HelloMessage.builder()
.id(Long.valueOf(counter.incrementAndGet()))
.message("Hello " + request.getRemoteAddr())
.currentTime(new Date())
.build();
}
}
|
package co.sblock.events.session;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.logging.Logger;
import org.bukkit.plugin.Plugin;
import org.bukkit.scheduler.BukkitRunnable;
import org.bukkit.scheduler.BukkitTask;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import co.sblock.Sblock;
import co.sblock.events.Events;
/**
* Checks and updates Status from Minecraft's servers.
*
* @author Jikoo
*/
public class StatusCheck extends BukkitRunnable {
private Plugin plugin;
@Override
public void run() {
boolean session = false;
boolean login = false;
JSONParser parser = new JSONParser();
try {
JSONObject data = (JSONObject) parser.parse(new BufferedReader(new InputStreamReader(
new URL("http://status.mojang.com/check?service=session.minecraft.net").openStream())));
session = data.get("session.minecraft.net").equals("red");
data = (JSONObject) parser.parse(new BufferedReader(new InputStreamReader(
new URL("http://status.mojang.com/check?service=auth.mojang.com").openStream())));
login = data.get("auth.mojang.com").equals("red");
} catch (IOException | ParseException | ClassCastException | NullPointerException e) {
// ClassCast/NPE happens occasionally when JSON appears to be parsed incorrectly.
// This check is run every minute, and 99.9% of the time we are casting correctly. I blame Mojang.
Logger.getLogger("Session").warning("Unable to check http://status.mojang.com/check - status unavailable.");
return;
}
Status status;
if (login) {
if (session) {
status = Status.BOTH;
} else {
status = Status.LOGIN;
}
} else {
if (session) {
status = Status.SESSION;
} else {
status = Status.NEITHER;
}
}
if (plugin != null && plugin.isEnabled()) {
new BukkitRunnable() {
@Override
public void run() {
((Sblock) plugin).getModule(Events.class).changeStatus(status);
}
}.runTask(plugin);
}
}
@Override
public synchronized BukkitTask runTask(Plugin plugin) throws IllegalArgumentException,
IllegalStateException {
this.plugin = plugin;
return super.runTask(plugin);
}
@Override
public synchronized BukkitTask runTaskAsynchronously(Plugin plugin)
throws IllegalArgumentException, IllegalStateException {
this.plugin = plugin;
return super.runTaskAsynchronously(plugin);
}
@Override
public synchronized BukkitTask runTaskLater(Plugin plugin, long delay)
throws IllegalArgumentException, IllegalStateException {
this.plugin = plugin;
return super.runTaskLater(plugin, delay);
}
@Override
public synchronized BukkitTask runTaskLaterAsynchronously(Plugin plugin, long delay)
throws IllegalArgumentException, IllegalStateException {
this.plugin = plugin;
return super.runTaskLaterAsynchronously(plugin, delay);
}
@Override
public synchronized BukkitTask runTaskTimer(Plugin plugin, long delay, long period)
throws IllegalArgumentException, IllegalStateException {
this.plugin = plugin;
return super.runTaskTimer(plugin, delay, period);
}
@Override
public synchronized BukkitTask runTaskTimerAsynchronously(Plugin plugin, long delay, long period)
throws IllegalArgumentException, IllegalStateException {
this.plugin = plugin;
return super.runTaskTimerAsynchronously(plugin, delay, period);
}
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package domain;
/**
*
* @author Marcos
*/
public class Empleado extends Persona{
private Integer idEmpleado;
private String direccion;
private String telefono;
private String email;
public Integer getIdEmpleado() {
return idEmpleado;
}
public void setIdEmpleado(Integer idEmpleado) {
this.idEmpleado = idEmpleado;
}
public String getDireccion() {
return direccion;
}
public void setDireccion(String direccion) {
this.direccion = direccion;
}
public String getTelefono() {
return telefono;
}
public void setTelefono(String telefono) {
this.telefono = telefono;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
|
package sg.edu.rp.c346.simpleclick;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Button;
import android.widget.ToggleButton;
public class MainActivity extends AppCompatActivity {
//Step 1
TextView tvDisplay;
Button btnDisplay;
EditText etInput;
ToggleButton tbtnEnabled;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Step 2:Link the field variables to UI components in layout
tvDisplay = (TextView)findViewById(R.id.textViewDisplay);
btnDisplay =(Button)findViewById(R.id.buttonDisplay);
etInput =(EditText)findViewById(R.id.editText3);
tbtnEnabled =(ToggleButton) findViewById(R.id.buttonCheck);
btnDisplay.setOnClickListener(new View.OnClickListener( ) {
@Override
public void onClick(View v) {
// Code for the action
etInput.getText().toString();
String stringResponse = etInput.getText().toString();
tvDisplay.setText(stringResponse);
}
});
tbtnEnabled.setOnClickListener(new View.OnClickListener( ) {
@Override
public void onClick(View v) {
if (tbtnEnabled.isChecked()){
etInput.setEnabled(true);
}
else {
etInput.setEnabled(false);
}
}
});
}
}
|
package com.clone.mango.dbdata;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
@NoArgsConstructor
@AllArgsConstructor
@Getter @Setter
@Builder
@ToString
@Entity(name = "reivew_image")
public class ReviewImage {
@Id
@GeneratedValue
private Long id;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn( name = "review_id", referencedColumnName = "id")
private Review review;
private String reviewImageUrl;
}
|
package br.ufsc.ine5605.clavicularioeletronico.telasgraficas;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.TableModel;
/**
*
* @author Flávio
*/
public abstract class TelaBaseTable<E> extends JFrame {
protected JTable table;
protected JScrollPane spTable;
protected JButton btInclui;
protected JButton btAltera;
protected JButton btExclui;
protected ActionManager actManager;
protected final List<ITelaBaseTableObserver> observers;
protected List<E> lista;
public TelaBaseTable(String title) {
super(title);
this.lista = new ArrayList<>();
this.observers = new ArrayList<>();
init();
}
public void addObserver(ITelaBaseTableObserver observer) {
if (!this.observers.contains(observer)) {
this.observers.add(observer);
}
}
public void removeObserver(ITelaBaseTableObserver observer) {
this.observers.remove(observer);
}
public void setLista(List<E> lista) {
this.lista = lista;
this.atualizaDados();
}
protected E getItemSelecionado() {
int row = this.table.getSelectedRow();
if (row > -1) {
return this.lista.get(row);
}
return null;
}
private void notificaInclui() {
for (ITelaBaseTableObserver observer : this.observers) {
observer.inclui();
}
}
private void notificaAltera() {
E item = this.getItemSelecionado();
if (item != null) {
for (ITelaBaseTableObserver observer : this.observers) {
observer.altera(item);
}
} else {
JOptionPane.showMessageDialog(null, "Nenhum item selecionado!");
}
}
private void notificaExclui() {
E item = this.getItemSelecionado();
if (item != null) {
for (ITelaBaseTableObserver observer : this.observers) {
observer.exclui(item);
}
} else {
JOptionPane.showMessageDialog(null, "Nenhum item selecionado!");
}
}
protected abstract Dimension getTamanhoTela();
protected abstract TableModel getTableModel();
protected abstract int getTableGridY();
protected void init() {
Container container = getContentPane();
container.setLayout(new GridBagLayout());
this.actManager = new ActionManager();
Dimension tamanhoTela = this.getTamanhoTela();
this.table = new JTable();
this.table.setPreferredScrollableViewportSize(new Dimension(tamanhoTela.width - 100, tamanhoTela.height - 200));
this.table.setDefaultEditor(Object.class, null);
//this.table.setPreferredScrollableViewportSize(new Dimension(300, 200));
this.table.setFillsViewportHeight(true);
GridBagConstraints constraint = new GridBagConstraints();
int y = getTableGridY();
constraint.fill = GridBagConstraints.CENTER;
constraint.gridwidth = 4;
constraint.gridheight = 3;
constraint.gridx = 0;
constraint.gridy = y++;
y += constraint.gridheight - 1;
this.spTable = new JScrollPane(this.table);
container.add(this.spTable, constraint);
this.btInclui = new JButton("Inclui");
this.btInclui.setActionCommand(AcoesCadastro.ACAO_INCLUI);
this.btInclui.addActionListener(actManager);
constraint.gridwidth = 1;
constraint.gridheight = 1;
constraint.gridx = 0;
constraint.gridy = y;
container.add(this.btInclui, constraint);
this.btAltera = new JButton("Altera");
this.btAltera.setActionCommand(AcoesCadastro.ACAO_ALTERA);
this.btAltera.addActionListener(actManager);
constraint.gridwidth = 1;
constraint.gridheight = 1;
constraint.gridx = 1;
constraint.gridy = y;
container.add(this.btAltera, constraint);
this.btExclui = new JButton("Exclui");
this.btExclui.setActionCommand(AcoesCadastro.ACAO_EXCLUI);
this.btExclui.addActionListener(actManager);
constraint.gridwidth = 1;
constraint.gridheight = 1;
constraint.gridx = 2;
constraint.gridy = y;
container.add(this.btExclui, constraint);
this.atualizaDados();
this.setSize(tamanhoTela);
setLocationRelativeTo(null);
}
protected void atualizaDados() {
this.table.setModel(this.getTableModel());
this.repaint();
}
private class ActionManager implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
String comando = e.getActionCommand();
if (AcoesCadastro.ACAO_INCLUI.equals(comando)) {
notificaInclui();
} else if (AcoesCadastro.ACAO_ALTERA.equals(comando)) {
notificaAltera();
} else if (AcoesCadastro.ACAO_EXCLUI.equals(comando)) {
notificaExclui();
}
}
}
}
|
package com.jpeng.demo.diarys;
import android.Manifest;
import android.app.Activity;
import android.app.KeyguardManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.graphics.PixelFormat;
import android.hardware.fingerprint.FingerprintManager;
import android.os.Build;
import android.os.CancellationSignal;
import android.support.annotation.RequiresApi;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
import com.jpeng.demo.ActivityCollector;
import com.jpeng.demo.R;
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
public class Fingerprint extends FragmentActivity {
boolean isClose=false;
Activity activity;
ImageView imageView;
FingerprintManager manager;
KeyguardManager mKeyManager;
private final static int REQUEST_CODE_CONFIRM_DEVICE_CREDENTIALS = 0;
private final static String TAG = "finger_log";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setWindow();
setContentView(R.layout.activity_fingerprint);
ActivityCollector.addActivity(this);
activity=this;
manager = (FingerprintManager) this.getSystemService(Context.FINGERPRINT_SERVICE);
mKeyManager = (KeyguardManager) this.getSystemService(Context.KEYGUARD_SERVICE);
imageView=(ImageView)findViewById(R.id.finger_id);
if (isFinger()) {
Toast.makeText(Fingerprint.this, "请进行指纹识别", Toast.LENGTH_LONG).show();
Log(TAG, "keyi");
startListening(null);
}
}
private void setWindow() {
requestWindowFeature(Window.FEATURE_NO_TITLE);// 去掉标题栏
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);// 设置全屏
// 设置竖屏显示
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
// 选择支持半透明模式,在有surfaceview的activity中使用。
getWindow().setFormat(PixelFormat.TRANSLUCENT);
}
@Override
protected void onDestroy() {
super.onDestroy();
finish();
ActivityCollector.removeActivity(this);
}
public boolean isFinger() {
//android studio 上,没有这个会报错
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.USE_FINGERPRINT) != PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, "没有指纹识别权限", Toast.LENGTH_SHORT).show();
return false;
}
Log(TAG, "有指纹权限");
//判断硬件是否支持指纹识别
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (!manager.isHardwareDetected()) {
Toast.makeText(this, "没有指纹识别模块", Toast.LENGTH_SHORT).show();
return false;
}
}
Log(TAG, "有指纹模块");
//判断 是否开启锁屏密码
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
if (!mKeyManager.isKeyguardSecure()) {
Toast.makeText(this, "没有开启锁屏密码", Toast.LENGTH_SHORT).show();
return false;
}
}
Log(TAG, "已开启锁屏密码");
//判断是否有指纹录入
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (!manager.hasEnrolledFingerprints()) {
Toast.makeText(this, "没有录入指纹", Toast.LENGTH_SHORT).show();
return false;
}
}
Log(TAG, "已录入指纹");
return true;
}
CancellationSignal mCancellationSignal = new CancellationSignal();
//回调方法
FingerprintManager.AuthenticationCallback mSelfCancelled = new FingerprintManager.AuthenticationCallback() {
@Override
public void onAuthenticationError(int errorCode, CharSequence errString) {
//但多次指纹密码验证错误后,进入此方法;并且,不能短时间内调用指纹验证
Toast.makeText(Fingerprint.this, errString, Toast.LENGTH_SHORT).show();
showAuthenticationScreen();
}
@Override
public void onAuthenticationHelp(int helpCode, CharSequence helpString) {
Toast.makeText(Fingerprint.this, helpString, Toast.LENGTH_SHORT).show();
}
@Override
public void onAuthenticationSucceeded(FingerprintManager.AuthenticationResult result) {
Toast.makeText(Fingerprint.this, "指纹识别成功", Toast.LENGTH_SHORT).show();
imageView.setImageResource(R.drawable.fingerprint_fill);
finish();
ActivityCollector.removeActivity(activity);
Intent intent=new Intent(Fingerprint.this,Diary.class);
startActivity(intent);
}
@Override
public void onAuthenticationFailed() {
Toast.makeText(Fingerprint.this, "指纹识别失败", Toast.LENGTH_SHORT).show();
}
};
public void startListening(FingerprintManager.CryptoObject cryptoObject) {
//android studio 上,没有这个会报错
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.USE_FINGERPRINT) != PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, "没有指纹识别权限", Toast.LENGTH_SHORT).show();
return;
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
manager.authenticate(cryptoObject, mCancellationSignal, 0, mSelfCancelled, null);
}
}
/**
* 锁屏密码
*/
private void showAuthenticationScreen() {
Intent intent = null;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
intent = mKeyManager.createConfirmDeviceCredentialIntent("finger", "测试指纹识别");
}
if (intent != null) {
startActivityForResult(intent, REQUEST_CODE_CONFIRM_DEVICE_CREDENTIALS);
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_CODE_CONFIRM_DEVICE_CREDENTIALS) {
// Challenge completed, proceed with using cipher
if (resultCode == RESULT_OK) {
Toast.makeText(this, "识别成功", Toast.LENGTH_SHORT).show();
finish();
ActivityCollector.removeActivity(activity);
Intent intent=new Intent(Fingerprint.this,Diary.class);
startActivity(intent);
} else {
Toast.makeText(this, "识别失败", Toast.LENGTH_SHORT).show();
finish();
ActivityCollector.removeActivity(activity);
}
}
}
private void Log(String tag, String msg) {
if (isClose){
Log.d(tag, msg);
}
}
}
|
package ru.steagle.utils;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Environment;
import android.os.Vibrator;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.widget.Toast;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Set;
import ru.steagle.R;
import ru.steagle.config.Config;
import ru.steagle.service.SteagleService;
public class Utils {
private static final String TAG = Utils.class.getName();
/**
* Получение номера формы существительного для заданного количества.
*
* @param number количество
* @return номер формы: 0 - попугай, 1 - попугая, 2 - попугаев
*/
public static int getDeclinationIndex(int number) {
number = number % 100;
if (number >= 11 && number <= 19) {
return 2;
} else {
number = number % 10;
switch (number) {
case 1:
return 0;
case 2:
case 3:
case 4:
return 1;
default:
return 2;
}
}
}
public static boolean isObjectInSet(String object, Set<SteagleService.Dictionary> set) {
for (SteagleService.Dictionary d : set)
if (d.toString().equals(object))
return true;
return false;
}
public static Date getDay(Date d) {
Calendar c = GregorianCalendar.getInstance();
c.setTime(d);
Calendar day = GregorianCalendar.getInstance();
day.clear();
day.set(c.get(Calendar.YEAR), c.get(Calendar.MONTH), c.get(Calendar.DAY_OF_MONTH));
return day.getTime();
}
public static Date getNextDay(Date d) {
Calendar c = GregorianCalendar.getInstance();
c.setTime(d);
Calendar day = GregorianCalendar.getInstance();
day.clear();
day.set(c.get(Calendar.YEAR), c.get(Calendar.MONTH), c.get(Calendar.DAY_OF_MONTH));
day.add(Calendar.DAY_OF_MONTH, 1);
return day.getTime();
}
public static Date getNextMs(Date d) {
Calendar c = GregorianCalendar.getInstance();
c.setTime(d);
c.add(Calendar.MILLISECOND, 1);
return c.getTime();
}
public static void showConfirmDialog(Context context, String title, String message, String yesButtonText, String noButtonText, final Runnable onYesClick) {
AlertDialog.Builder builder = new AlertDialog.Builder(context)
.setMessage(message)
.setCancelable(true)
.setPositiveButton(yesButtonText, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
onYesClick.run();
}
})
.setNegativeButton(noButtonText, null);
if (title != null)
builder.setTitle(title);
builder.show();
}
public static ProgressDialog getProgressDialog(Context context) {
ProgressDialog dialog = new ProgressDialog(context);
dialog.setMessage(context.getResources().getString(R.string.sending_request));
dialog.setIndeterminate(true);
dialog.setCancelable(false);
return dialog;
}
public static void showServiceConnectionError(Context context) {
Toast.makeText(context, R.string.service_connection_error, Toast.LENGTH_LONG).show();
}
public static void showNetworkError(Context context) {
Toast.makeText(context, R.string.network_error, Toast.LENGTH_LONG).show();
}
public static boolean detectWiFi(Context context) {
ConnectivityManager connManager = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo mWifi = connManager
.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
return mWifi != null && mWifi.isConnected();
}
public static boolean detect3G(Context context) {
ConnectivityManager connManager = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo mMobile = connManager
.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
return mMobile != null && mMobile.isConnected();
}
public static boolean inRoaming(Context context) {
TelephonyManager telephonyManager = (TelephonyManager) context
.getSystemService(Context.TELEPHONY_SERVICE);
return telephonyManager != null && telephonyManager.isNetworkRoaming();
}
public static String getStackTrace(Throwable e) {
StringWriter stackTrace = new StringWriter();
e.printStackTrace(new PrintWriter(stackTrace));
return stackTrace.toString();
}
public static void writeLogMessage(String message, boolean append) {
if (append)
return;
try {
File log = new File(Environment.getExternalStorageDirectory(), "steagle.txt");
Writer out = new BufferedWriter(new FileWriter(log, true));
out.write(message);
out.close();
} catch (Exception e) {
Log.e(TAG, "Error creating log file", e);
}
}
public static boolean isNetworkAvailable(Context context) {
boolean isWifiOn = Utils.detectWiFi(context);
// Log.d(TAG, "Wifi is " + (isWifiOn ? "ON" : "OFF"));
if (isWifiOn)
return true;
else if (Config.isWifiOnly(context)) {
// Log.d(TAG, "can use only WifiOnly -> no network is available");
return false;
} else {
// Log.d(TAG, "can use 3G");
boolean is3GOn = Utils.detect3G(context);
// Log.d(TAG, "3G is " + (is3GOn ? "ON" : "OFF"));
return is3GOn;
}
}
public static void vibrate(Context context) {
Vibrator v = (Vibrator) context
.getSystemService(Context.VIBRATOR_SERVICE);
if (v != null)
v.vibrate(50);
}
}
|
package com.eomcs.basic.oop.ex02;
public class testSungjuk {
public static class sungjuk {
String name;
int kor;
int eng;
int math;
int sum;
float aver;
}
public static void main(String[] args) {
sungjuk s1 = new sungjuk();
sungjuk s2 = createScore("홍길동", 100, 100, 100);
s1.name = "홍길동";
s1.kor = 100;
s1.eng = 90;
s1.math = 85;
printScore(s1);
}
static void printScore(sungjuk s1) {
s1.sum = s1.kor + s1.eng + s1.math;
s1.aver = s1.sum / 3;
System.out.printf("%s: %d, %d, %d ,%d %.1f\n",
s1.name, s1.kor, s1.eng, s1.math, s1.sum, s1.aver);
}
static sungjuk createScore(String name, int kor, int eng, int math) {
sungjuk s1 = new sungjuk();
s1.name = "홍길동";
s1.kor = 100;
s1.eng = 90;
s1.math = 80;
return s1;
}
}
|
package patterns.behavioral.memento.black;
public class Originator
{
private String state;
public String getState()
{
return state;
}
public void setState(String state)
{
this.state = state;
}
public MementoIf createMemento()
{
return new Memento(state);
}
public void restoreMemento(MementoIf mementoIf)
{
this.setState(((Memento) mementoIf).getState());
}
private class Memento implements MementoIf
{
private String state;
public Memento(String state)
{
this.state = state;
}
public String getState()
{
return state;
}
public void setState(String state)
{
this.state = state;
}
}
}
|
package cn.gouzao;
/**
* 多例设计模式
* @author Administrator
*
*/
class Sex{
private String title;
private static final Sex MALE = new Sex("男");
private static final Sex FEMALE = new Sex("女");
private Sex(String title){ //构造私有化
this.title = title;
}
public String toString(){
return this.title;
}
public static Sex getInstance(int ch){
switch(ch){
case 1:
return MALE;
case 2:
return FEMALE;
default:
return null;
}
}
}
interface Choose{
public int MAN = 1;
public int WOMAN =2;
}
public class duoli {
public static void main(String[] args) {
// TODO Auto-generated method stub
Sex sex = Sex.getInstance(Choose.MAN); //避免传入1 或 2的问题
System.out.println(sex);
}
}
|
package pers.yoko.aopdemo.entity;
import lombok.Data;
import javax.persistence.*;
/**
* @author yoko
* @date 2021/9/3 14:59
* @since 1.0
*/
@Entity
@Table(name = "t_dept")
@Data
public class Dept{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String deptName;
public Dept() {}
public Dept(int id, String deptName) {
this.id = id;
this.deptName = deptName;
}
}
|
package com.fun.driven.development.fun.unified.payments.api.domain;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
import javax.persistence.*;
import javax.validation.constraints.*;
import java.io.Serializable;
import java.time.Instant;
import com.fun.driven.development.fun.unified.payments.api.domain.enumeration.UnavailableType;
@Entity
@Table(name = "payment_method_unavailable")
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
public class PaymentMethodUnavailable implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "sequenceGenerator")
@SequenceGenerator(name = "sequenceGenerator")
private Long id;
@NotNull
@Enumerated(EnumType.STRING)
@Column(name = "type", nullable = false)
private UnavailableType type;
@NotNull
@Column(name = "fun_from", nullable = false)
private Instant from;
@Column(name = "until")
private Instant until;
@ManyToOne(optional = false)
@NotNull
@JsonIgnoreProperties(value = "paymentMethodUnavailables", allowSetters = true)
private PaymentMethod paymentMethod;
// jhipster-needle-entity-add-field - JHipster will add fields here
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public UnavailableType getType() {
return type;
}
public PaymentMethodUnavailable type(UnavailableType type) {
this.type = type;
return this;
}
public void setType(UnavailableType type) {
this.type = type;
}
public Instant getFrom() {
return from;
}
public PaymentMethodUnavailable from(Instant from) {
this.from = from;
return this;
}
public void setFrom(Instant from) {
this.from = from;
}
public Instant getUntil() {
return until;
}
public PaymentMethodUnavailable until(Instant until) {
this.until = until;
return this;
}
public void setUntil(Instant until) {
this.until = until;
}
public PaymentMethod getPaymentMethod() {
return paymentMethod;
}
public PaymentMethodUnavailable paymentMethod(PaymentMethod paymentMethod) {
this.paymentMethod = paymentMethod;
return this;
}
public void setPaymentMethod(PaymentMethod paymentMethod) {
this.paymentMethod = paymentMethod;
}
// jhipster-needle-entity-add-getters-setters - JHipster will add getters and setters here
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof PaymentMethodUnavailable)) {
return false;
}
return id != null && id.equals(((PaymentMethodUnavailable) o).id);
}
@Override
public int hashCode() {
return 31;
}
// prettier-ignore
@Override
public String toString() {
return "PaymentMethodUnavailable{" +
"id=" + getId() +
", type='" + getType() + "'" +
", from='" + getFrom() + "'" +
", until='" + getUntil() + "'" +
"}";
}
}
|
/**
* Infrastructure for handler method processing.
*/
@NonNullApi
@NonNullFields
package org.springframework.web.reactive.result.method;
import org.springframework.lang.NonNullApi;
import org.springframework.lang.NonNullFields;
|
package com.mining.mine;
import android.view.View;
import android.widget.LinearLayout;
import com.example.administrator.mining.R;
import com.mining.Login.LoginActivity;
import com.mining.modle.base.BaseFragment;
import butterknife.BindView;
import butterknife.OnClick;
public class PersonPageFragment extends BaseFragment{
@BindView(R.id.news_btn)
LinearLayout news_btn;//消息按钮
@Override
protected int getLayoutResId() {
return R.layout.fragment_main_home_page;
}
@Override
protected void setListener() {
}
@Override
protected void initViews(View view) {
}
/*消息页面*/
@OnClick(R.id.news_btn) void news_btn() {
startActivity(NewsCenterActivity.class);
}
/*安全设置*/
@OnClick(R.id.save_set) void save_set() {
startActivity(SecuritySettingActivity.class);
}
/*个人主页*/
@OnClick(R.id.phone_number) void phone_number() {
startActivity(PersonCenterActivity.class);
}
/*收款方式*/
@OnClick(R.id.payment_method) void payment_method() {
startActivity(PaymentMethodActivity.class);
}
/*红包**/
@OnClick(R.id.red_id) void red_id() {
startActivity(RedEnvelopesActivity.class);
}
/*邀请返佣**/
@OnClick(R.id.inva_money) void inva_money() {
startActivity(InvitationReturnActivity.class);
}
/*提交工单**/
@OnClick(R.id.tj_gd_id) void tj_gd_id() {
startActivity(SubmitWorkActivity.class);
}
/*已购算力*/
@OnClick(R.id.yg_sl_id) void yg_sl_id() {
startActivity(PurchaseHistoryActivity.class);
}
/*挖矿收益*/
@OnClick(R.id.wk_sy_id) void wk_sy_id() {
startActivity(MiningProfitActivity.class);
}
/*关于我们**/
@OnClick(R.id.about_us_id) void about_us_id() {
startActivity(AboutUsActivity.class);
}
/*退出登录**/
@OnClick(R.id.btn_login_ok) void btn_login_ok() {
startActivity(LoginActivity.class);
}
}
|
package draughts.library.managers;
import draughts.library.boardmodel.Piece;
import draughts.library.boardmodel.Tile;
import draughts.library.exceptions.NoPieceFoundInRequestedTileException;
import draughts.library.movemodel.Capture;
import draughts.library.movemodel.Hop;
import draughts.library.movemodel.Move;
import java.util.ArrayList;
public class BaseTest {
protected BoardManager boardManager;
public Piece getPiece(int index) {
try {
return boardManager.findPieceByIndex(index);
} catch (NoPieceFoundInRequestedTileException ex) {
ex.printStackTrace();
return null;
}
}
public Tile getTile(int index) {
return boardManager.findTileByIndex(index);
}
public Move<Hop> generateMove(int source, int destination) {
Piece movingPiece = getPiece(source);
Tile sourceTile = getTile(source);
Tile destinationTile = getTile(destination);
Move<Hop> move = new Move<>(movingPiece, new Hop(sourceTile, destinationTile));
move.classify();
return move;
}
public Move<Capture> generateMoveWithCaptures(int source, ArrayList<Integer> jumpDestinations,
ArrayList<Integer> takenPawns) {
Piece movingPiece = getPiece(source);
Move<Capture> move = new Move<>(movingPiece);
Capture capture;
for (int i = 0; i < jumpDestinations.size(); i++) {
Tile sourceTile;
if (i == 0) sourceTile = getTile(source);
else sourceTile = getTile(jumpDestinations.get(i - 1));
Tile destinationTile = getTile(jumpDestinations.get(i));
Piece takenPiece = getPiece(takenPawns.get(i));
capture = new Capture(sourceTile, destinationTile, takenPiece);
move.addHop(capture);
}
move.classify();
return move;
}
}
|
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import opennlp.tools.cmdline.parser.ParserTool;
import opennlp.tools.parser.Parse;
import opennlp.tools.parser.Parser;
import opennlp.tools.parser.ParserFactory;
import opennlp.tools.parser.ParserModel;
public class Program {
public static void main(String[] args) throws ClassNotFoundException {
try {
//try one sentence
String sentence = "Don was always knowledgeable and professional";
String sentence2 = "Don has created the most positive and unique experience for my family and I.";
String sentence3 = "Mrs. Jenkins was very knowledgeable of the area market of the residents we were selling.";
String sentence4 = " LSU tests its emergency text messaging system twice a year.";
OpenNLP.Parse(sentence2);
// try one sentence
Class.forName("com.mysql.jdbc.Driver");
// setup the connection with the DB.
Connection connect = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/HUDList", "root", "password");
PreparedStatement ps = connect.prepareStatement("insert into HUDList.Review values (default, ?, ?, ?, ?)");
//PreparedStatement ps2 = connect.prepareStatement("insert into HUDList.Review (Review) values (?)");
List<List<Parse[]>> parsesListsLists = new ArrayList<List<Parse[]>>();
FileInputStream fis = new FileInputStream("/home/alex/Dropbox/WorkSpace/CrawlerDanwei/Reviews.txt");
InputStreamReader isr = new InputStreamReader(fis, "UTF8");
BufferedReader br = new BufferedReader(isr);
String strRead = "";
List<String> reviewraw = new ArrayList<String>();
while ((strRead = br.readLine()) != null) {
//ps2.setString(1, strRead);
//ps2.addBatch();
reviewraw.add(strRead);
parsesListsLists.add(OpenNLP.Parsepa(strRead));
}
//ps2.executeBatch(); // insert remaining records
//ps2.close();
//List<List<String>> resultslistAdj = new ArrayList<List<String>>();
List<String> resultsAdj = new ArrayList<String>();
String resultAdj = null;
//List<List<String>> resultslistVP = new ArrayList<List<String>>();
List<String> resultsVP = new ArrayList<String>();
String resultVP = null;
String[] temp = null;
List<String> triplets = new ArrayList<String>();
String triplet = null;
String temp2 = null;
Set<String> verbsCandidates = new HashSet<String>();
verbsCandidates.add("previewed");
verbsCandidates.add("provided");
verbsCandidates.add("assisted");
verbsCandidates.add("created");
verbsCandidates.add("exceeded");
verbsCandidates.add("helped");
verbsCandidates.add("protect");
verbsCandidates.add("utilized");
verbsCandidates.add("advised");
verbsCandidates.add("displayed");
verbsCandidates.add("kept");
verbsCandidates.add("contacted");
verbsCandidates.add("was");
verbsCandidates.add("gave");
for (List<Parse[]> parsesLists : parsesListsLists) {
for (int i = 0; i < parsesLists.size(); i++) {
// out put parse trees for each sentence
for (Parse p : parsesLists.get(i)) {
p.show();
}
// print triplets;
temp2= ExtractTriplets.findTriplets(parsesLists.get(i));
if (i == 0) {
triplet = temp2;
}
else {
triplet += temp2;
}
temp = ExtractTriplets.findInfo(parsesLists.get(i), verbsCandidates);
if (i == 0) {
resultAdj = temp[0];
resultVP = temp[1];
}
else {
resultAdj += temp[0];
resultVP += temp[1];
}
if (i < parsesLists.size() - 1) {
if (temp[0] != "") {
resultAdj += ", ";
}
if (temp[1] != "") {
resultVP += ", ";
}
}
}
// used to print triplets;
System.out.println();
//System.out.println("resultAdj: " + resultAdj);
//System.out.println("resultVP: " + resultVP);
triplets.add(triplet);
resultsAdj.add(resultAdj);
resultsVP.add(resultVP);
}
System.out.println();
System.out.println("Adj is: ");
for (String result1 : resultsAdj) {
System.out.println(result1);
}
System.out.println();
System.out.println("VP is: ");
for (String result2 : resultsVP) {
System.out.println(result2);
}
// bulk insert
final int batchSize = 1000;
int count = 0;
for (int i = 0; i < resultsAdj.size(); i++) {
ps.setString(1, reviewraw.get(i));
ps.setString(2, triplets.get(i));
ps.setString(3, resultsAdj.get(i));
ps.setString(4, resultsVP.get(i));
ps.addBatch();
if(++count % batchSize == 0) {
ps.executeBatch();
}
}
ps.executeBatch(); // insert remaining records
ps.close();
connect.close();
br.close();
} catch(SQLException se){
//Handle errors for JDBC
se.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
finally {
}
}
}
|
package bn.messages;
public interface MessageSet<MessageType extends Message> extends Iterable<MessageType>
{
public int size();
public MessageType get(int index);
public void remove(int index);
public void removeAll();
}
|
package com.artauction.domain;
import java.util.Date;
import lombok.Data;
@Data
public class MypageVO {
private int gno;
private String gname;
private Date enddate;
private char flag;
private int nowprice;
private String userid;
private int tprice;
private String uuid;
private String uploadpath;
private String filename;
}
|
package com.gaoshin.onsalelocal.search;
import java.util.Arrays;
import java.util.Comparator;
import common.geo.PostalAddress;
import common.geo.PostalAddressParser;
public class AddressFormater {
public static PostalAddress formatAddress(String address, String city, String state) {
PostalAddress pa = PostalAddressParser.parse(address, city, state);
return pa;
}
public static String formatStreet(String address, String city, String state) {
return formatAddress(address, city, state).getSignature();
}
public static String formatName(String name1) {
if (name1 == null) return null;
name1 = name1.toUpperCase();
name1 = name1.replaceAll("[^A-Z0-9 ]+", "");
String[] array1 = name1.split("[ ]+");
Arrays.sort(array1, new Comparator<String>() {
public int compare(String o1, String o2) {
return o1.compareTo(o2);
}
});
StringBuilder sb = new StringBuilder();
for (String s : array1) {
sb.append(s);
}
name1 = sb.toString();
return name1;
}
public static String formatPhone(String phone) {
if(phone == null || phone.trim().length() == 0)
return null;
phone = phone.replaceAll("[\\+\\.\\(\\) \\-]+", "");
if(phone.length() == 0 || "NULL".equalsIgnoreCase(phone)) {
return null;
}
phone = phone.replaceAll("[a|A|b|B|c|C]", "2");
phone = phone.replaceAll("[d|e|f|D|E|F]", "3");
phone = phone.replaceAll("[g|h|i|G|H|I]", "4");
phone = phone.replaceAll("[j|k|l|J|K|L]", "5");
phone = phone.replaceAll("[m|n|o|M|N|O]", "6");
phone = phone.replaceAll("[p|q|r|s|P|Q|R|S]", "7");
phone = phone.replaceAll("[t|u|v|T|U|V]", "8");
phone = phone.replaceAll("[w|x|y|z|W|X|Y|Z]", "9");
phone = phone.replace(":", "");
if(phone.startsWith("1") && phone.length() == 11) {
return phone;
}
if(phone.length() == 10) {
return "1" + phone;
}
if(!phone.startsWith("1")) {
phone = "1" + phone;
}
return phone.length() > 11 ? phone.substring(0,11) : phone;
}
}
|
public class BallAndHats {
public int getHat(String hats, int numSwaps) {
double[] current = new double[3];
for(int i = 0; i < hats.length(); i++) {
if(hats.charAt(i) == '.') {
current[i] = 0;
} else {
current[i] = 1d;
}
}
for(int i = 0; i < numSwaps; i++) {
double[] next = new double[3];
next[0] += current[1] * .5;
next[1] += current[0];
next[1] += current[2];
next[2] += current[1] * .5;
current = next;
}
double max = current[0];
int maxIndex = 0;
for(int i = 1; i < 3; i++) {
if(max < current[i]) {
max = current[i];
maxIndex = i;
}
}
return maxIndex;
}
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package deloitte.forecastsystem_bih.repository;
import java.util.Date;
import java.util.List;
import java.util.Optional;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.Param;
import deloitte.forecastsystem_bih.model.WeatherForecast;
import deloitte.forecastsystem_bih.model.WeatherForecastDaily;
/**
*
* @author Vladimir
*/
public interface WeatherForecastDailyRepository extends CrudRepository<WeatherForecastDaily, Long>{
@Override
public List<WeatherForecastDaily> findAll();
@Override
public Optional<WeatherForecastDaily> findById(Long id);
@Override
public <S extends WeatherForecastDaily> S save(S s);
@Override
public void delete(WeatherForecastDaily t);
@Query("SELECT wfd FROM WeatherForecastDaily wfd WHERE weatherForecast=:p_weatherForecast")
public List<WeatherForecastDaily> findByDate(@Param("p_weatherForecast") WeatherForecast p_weatherForecast);
@Query("SELECT wfd FROM WeatherForecastDaily wfd WHERE dayForecast=:p_Day_forecast ORDER BY id DESC")
public List<WeatherForecastDaily> findByDay(@Param("p_Day_forecast") Date p_Day_forecast);
}
|
package java.com.kaizenmax.taikinys_icl.presenter;
import com.kaizenmax.taikinys_icl.model.MobileDatabase;
import com.kaizenmax.taikinys_icl.presenter.DemoL3ProtocolPresenterInterface;
import com.kaizenmax.taikinys_icl.view.DemoL3Activity_Protocol;
import java.util.List;
public class DemoL3ProtocolPresenter implements DemoL3ProtocolPresenterInterface {
MobileDatabase dbHelper =new MobileDatabase(DemoL3Activity_Protocol.getInstance());
@Override
public void insertDemoL3Protocoldata_Update(String dateOfProtocol_entered, String cropCategory_entered,
String cropFocus_entered, String meetingPurpose_entered,
List<String> selectedProductList, Integer demoL3SerialId,
String uploadFlagStatus, String modifyDate_string,
Integer stage) throws Exception {
dbHelper.insertDemoL3Protocoldata_Update(dateOfProtocol_entered,cropCategory_entered,
cropFocus_entered, meetingPurpose_entered,
selectedProductList, demoL3SerialId,
uploadFlagStatus, modifyDate_string, stage);
}
}
|
package com.gaoshin.beans;
public enum ObjectLocationType {
Fixed,
Latest, ;
}
|
package com.xianzaishi.wms.tmscore.dao.impl;
import com.xianzaishi.wms.common.dao.impl.BaseDaoAdapter;
import com.xianzaishi.wms.common.exception.BizException;
import com.xianzaishi.wms.tmscore.dao.itf.IDistributionDao;
public class DistributionDaoImpl extends BaseDaoAdapter implements
IDistributionDao {
public String getVOClassName() {
return "DistributionDO";
}
public Boolean reset(Long id) {
Boolean flag = false;
try {
if (id != null && id > 0) {
int no = simpleSqlMapClientTemplate.update(getVOClassName()
+ ".reset", id);
if (no == 1) {
flag = true;
} else if (no > 1) {
throw new BizException("影响的数据大于1条。");
} else {
throw new BizException("数据不存在。");
}
} else {
throw new BizException("更新数据失败,ID错误:ID = " + id);
}
} catch (Exception e) {
throw new BizException("更新数据失败。", e);
}
return flag;
}
}
|
import java.util.ArrayList;
import java.util.List;
public class ex2A {
public static void main(String[] args) {
String courseTitle = "Java Reskilling";
int nbrDays = 20;
double pricePerDay = 195.99;
boolean priorKnowledgeRequired = false;
List<String> instructors = new ArrayList<String>();
instructors.add("Sandy");
instructors.add("Guy");
System.out.println("Course title: " +courseTitle+ "\nNumber of days: " +nbrDays+ "\nPrice per day: " +pricePerDay+ "\nPrior knowledge requested : " +priorKnowledgeRequired);
System.out.println("Number of instructors: " +instructors.size());
}
}
|
package org.sunbeam.dao;
import org.hibernate.SessionFactory;
import org.hibernate.query.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.sunbeam.pojo.Customer;
@Repository
public class CustomerDaoImplementation implements CustomerDao
{
@Autowired
private SessionFactory sessionFactory;
@Override
public Integer insertCustomer(Customer customer)
{
return (Integer) this.sessionFactory.getCurrentSession().save(customer);
}
@Override
public Customer validateCustomer(String email, String password) {
String hql = "select c from Customer c where c.email=:Email and c.password=:Password";
Query<Customer> query = this.sessionFactory.getCurrentSession().createQuery(hql, Customer.class);
query.setParameter("Email", email);
query.setParameter("Password", password);
Customer customer= query.getSingleResult();
return customer;
/*return this.sessionFactory.getCurrentSession().createQuery("select c from Customer c where c.email=:Email and c.password=:Password", Customer.class).setParameter("Email", email).setParameter("Password", password).getSingleResult();*/
}
}
|
package com.gaoshin.onsaleflyer.service.impl;
import javax.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.gaoshin.onsaleflyer.dao.FlyerDao;
import com.gaoshin.onsaleflyer.service.FlyerService;
@Service
@Transactional(readOnly=true)
public class FlyerServiceImpl extends ServiceBaseImpl implements FlyerService {
@Autowired private FlyerDao flyerDao;
private String flyerHome;
@PostConstruct
public void init() {
flyerHome = configDao.get("flyer.home");
}
}
|
package com.intel.iot.balconygardener;
public class WateringLog {
String timestamp;
String trigger;
String action;
double duration;
public void init() {
timestamp = "";
trigger = "";
action = "";
duration = 0.;
}
}
|
package com.huich.roque.app.recomiendo_app.fragments;
import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.LocationSource;
import com.google.android.gms.maps.MapView;
import com.google.android.gms.maps.MapsInitializer;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.internal.ICameraUpdateFactoryDelegate;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.firebase.firestore.DocumentChange;
import com.google.firebase.firestore.EventListener;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.FirebaseFirestoreException;
import com.google.firebase.firestore.QuerySnapshot;
import com.huich.roque.app.recomiendo_app.R;
import com.huich.roque.app.recomiendo_app.adapters.CustomInfoWindowAdapter;
import com.huich.roque.app.recomiendo_app.models.Site;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
/**
* A simple {@link Fragment} subclass.
*/
public class HomeFragment extends Fragment implements OnMapReadyCallback {
private GoogleMap mGoogleMap;
private MapView mMapView;
private View mView;
private FirebaseFirestore mFirestore;
private List<Site> mSiteList;
public HomeFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
mView = inflater.inflate(R.layout.fragment_home, container, false);
mFirestore = FirebaseFirestore.getInstance();
mSiteList = new ArrayList<>();
return mView;
}
@Override
public void onViewCreated(@NonNull View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mMapView = (MapView) mView.findViewById(R.id.map_main_huariques);
if (mMapView != null) {
mMapView.onCreate(null);
mMapView.onResume();
mMapView.getMapAsync(this);
}
}
@Override
public void onMapReady(GoogleMap googleMap) {
MapsInitializer.initialize(getContext());
mGoogleMap = googleMap;
mGoogleMap.getUiSettings().setZoomControlsEnabled(true);
mGoogleMap.setMinZoomPreference(11);
mFirestore = FirebaseFirestore.getInstance();
mSiteList = new ArrayList<>();
mFirestore.collection("Sitios").addSnapshotListener(getActivity(), new EventListener<QuerySnapshot>() {
@Override
public void onEvent(QuerySnapshot documentSnapshots, FirebaseFirestoreException e) {
for (DocumentChange documentChange : documentSnapshots.getDocumentChanges()) {
if (documentChange.getType() == DocumentChange.Type.ADDED) {
String siteId = documentChange.getDocument().getId();
Site site = documentChange.getDocument().toObject(Site.class).withId(siteId);
Site infoSite = new Site();
infoSite.setNombre(site.getNombre());
infoSite.setUrl_imagen(site.getUrl_imagen());
infoSite.setDescripcion(site.getDescripcion());
CustomInfoWindowAdapter infoWindowAdapter = new CustomInfoWindowAdapter(getActivity());
mGoogleMap.setInfoWindowAdapter(infoWindowAdapter);
LatLng latLng = new LatLng(site.getLatitud(), site.getLongitud());
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng)
.title(site.getNombre())
.snippet(site.getDescripcion())
.position(latLng)
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_ORANGE));
Marker marker = mGoogleMap.addMarker(markerOptions);
marker.setTag(infoSite);
marker.showInfoWindow();
mGoogleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
float zoon = 8;
mGoogleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, zoon));
}
}
}
});
}
}
|
package controller;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Date;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import model.DAO.UserDAO;
import model.object.User;
import model.utils.MailSender;
import model.utils.Random;
@WebServlet( "/resetPassword")
public class ResetPassword extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// set up response
response.setContentType("text/html;charset=UTF-8");
response.setCharacterEncoding("UTF-8");
// processing
String email = request.getParameter("email");
String randomKey = request.getParameter("key");
User user = UserDAO.getUserByEmail(email);
// response
response.sendRedirect(checkAndSendEmail(user, randomKey));
}
private String checkAndSendEmail(User user, String randomKey) {
if (user != null && user.getRandomKey().contentEquals(randomKey) && UserDAO.checkGetPassTimeByEmail(user.getEmail(), 30 * 60 * 1000)) {
String newPass = new Random().createRandomString(8);
if (UserDAO.resetPassByEmail(user.getEmail(), newPass) && new MailSender().sendNewPassMail(user.getEmail(), newPass)) {
if (user.getRoleId() == 1) {
return "default?page=home";
} else {
return "default?page=staffHome";
}
}
}
return "default?page=login";
}
}
|
package appkg.kg.servicekg.database;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.provider.BaseColumns;
import java.util.ArrayList;
import appkg.kg.servicekg.model.Info;
/**
* Created by Suimonkul on 04.06.2016.
*/
public class DataHelper extends SQLiteOpenHelper implements BaseColumns {
public static final String ADVERT_ID = "product_id";
public static final String TITLE = "title";
public static final String DESC = "desc";
public static final String PRICE_SOM = "price_som";
public static final String PHONE = "phone";
private static final String DB_NAME = "service_kg.db";
private static final String TABLE_NAME = "favorite";
private static final int DB_VERSION = 1;
public DataHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
String CREATE_SCRIPT = "create table " + TABLE_NAME + " (" +
BaseColumns._ID + " integer primary key autoincrement, " +
ADVERT_ID + " text, " +
TITLE + " text, " +
DESC + " text, " +
PRICE_SOM + " text, " +
PHONE + " text);";
db.execSQL(CREATE_SCRIPT);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
public void removeAdvert(int advertId) {
getWritableDatabase().delete(TABLE_NAME, ADVERT_ID + " = " + advertId, null);
}
public void saveAdvert(Info info) {
ContentValues values = new ContentValues();
values.put(ADVERT_ID, info.getId());
values.put(TITLE, info.getName());
values.put(DESC, info.getDescription());
values.put(PHONE, info.getPhone());
getWritableDatabase().insert(TABLE_NAME, null, values);
}
public ArrayList<Info> getProducts() {
ArrayList<Info> list = new ArrayList<>();
try {
if (getWritableDatabase() == null) return list;
Cursor cursor = getReadableDatabase().query(TABLE_NAME,
null, null, null,
null, null, BaseColumns._ID + " DESC");
if (cursor != null && cursor.getCount() > 0) {
while (cursor.moveToNext()) {
Info info = new Info(cursor.getInt(cursor.getColumnIndex(ADVERT_ID)));
info.setId(cursor.getInt(cursor.getColumnIndex(BaseColumns._ID)));
info.setName(cursor.getString(cursor.getColumnIndex(TITLE)));
info.setDescription(cursor.getString(cursor.getColumnIndex(DESC)));
info.setPhone(cursor.getString(cursor.getColumnIndex(PHONE)));
list.add(info);
}
}
if (cursor != null) cursor.close();
} catch (NullPointerException e) {
e.printStackTrace();
}
return list;
}
public boolean isExist(int advertId) {
boolean isExist = false;
String selection = ADVERT_ID + " = " + advertId;
Cursor cursor = getReadableDatabase().query(TABLE_NAME, null, selection, null, null, null, null);
if (cursor != null) {
if (cursor.getCount() > 0) isExist = true;
cursor.close();
}
return isExist;
}
}
|
class Node {
int data;
Node left;
Node right;
Node(int data) {
this.data = data;
left = null;
right = null;
}
}
public class CreateBSTFromSortedArray {
//function to create BST from sorted array
public static Node creatBST(int[] arr, int start, int end) {
if(arr.length == 0) {
return null;
}
if(start > end) {
return null;
}
int mid = (start + end) / 2;
Node node = new Node(arr[mid]);
/* Recursively construct the left subtree and make it left child of root */
node.left = creatBST(arr, start, mid - 1);
/* Recursively construct the right subtree and make it right child of the root */
node.right = creatBST(arr, mid + 1, end);
return node;
}
// a utility function to create preorder traversal of BST
public static void preOrder(Node node) {
if(node == null) {
return;
}
System.out.print(node.data);
preOrder(node.left);
preOrder(node.right);
}
//main method
public static void main(String args[]) {
int[] arr = {1, 2, 3, 4, 5, 6, 7};
int start = 0;
int end = arr.length - 1;
Node node = creatBST(arr, start, end);
preOrder(node);
}
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package projecteuler;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
/**
*
* @author Sachin tripathi
*/
public class EvenFibonacci {
/**
* @param args the command line arguments
*/
public static void main(String[] args) throws IOException {
// TODO code application logic here
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
String sum="";
for(int i=0;i<n ;i++){
sum+=fibonacci(i) + ",";
}
System.out.println(sum);
//sum= sum.substring(0,sum.length());
System.out.println("sum "+sum);
String num[]=sum.split(",");
int temp=0;
for(int i=0; i<num.length; i++){
if(i%2==0){
temp=temp+Integer.parseInt(num[i]);
}
}
System.out.println(temp);
}
public static int fibonacci(int n){
if(n==0)
return 0;
else if(n==1)
return 1;
else
return fibonacci(n-1)+fibonacci(n-2);
}
}
|
package com.miyatu.tianshixiaobai.entity;
public class RightAllServiceTypeEntity {
public int viewType;
public int position = -1;
private String cate_id;
private String class_name;
private String pid;
private String status;
private String class_img;
private String sort;
private String intro;
private String addtime;
public String getCate_id() {
return cate_id;
}
public void setCate_id(String cate_id) {
this.cate_id = cate_id;
}
public String getClass_name() {
return class_name;
}
public void setClass_name(String class_name) {
this.class_name = class_name;
}
public String getPid() {
return pid;
}
public void setPid(String pid) {
this.pid = pid;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getClass_img() {
return class_img;
}
public void setClass_img(String class_img) {
this.class_img = class_img;
}
public String getSort() {
return sort;
}
public void setSort(String sort) {
this.sort = sort;
}
public String getIntro() {
return intro;
}
public void setIntro(String intro) {
this.intro = intro;
}
public String getAddtime() {
return addtime;
}
public void setAddtime(String addtime) {
this.addtime = addtime;
}
}
|
package everything.java8.examples;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
public class StreamStuff extends CommonStuff {
public void runStreamExample() {
List<Person> persons = new ArrayList<>();
persons.add(new Person("111-11-1111", "tolga", 42, "snowboarding", "camping", "painting"));
persons.add(new Person("222-22-2222", "emre", 40, "fishing", "camping"));
persons.add(new Person("222-22-2222", "emre", 40, "fishing", "camping"));
persons.add(new Person("333-33-3333", "ozge", 36, "playing", "snowboarding"));
persons.add(new Person("444-44-4444", "tolga", 3, "playing", "painting"));
persons.add(new Person("555-55-5555", "hande", 3, "playing"));
persons.add(new Person("666-66-6666", "hande", 40, "painting"));
pr("All persons:");
persons
.stream()
.forEach(p -> pr("\t" + p));
pr("count: " + persons.stream().count());
pr("Persons younger than 40 years old:");
persons
.stream()
.filter((p) -> p.age < 40)
.forEach((p) -> pr("\t" + p));
pr("Distinct persons:");
persons
.stream()
.distinct()
.forEach(p -> pr("\t" + p));
pr("allMatch: age < 100: \n\t" + persons.stream().allMatch(p -> p.age < 100));
pr("allMatch: age < 33: \n\t" + persons.stream().allMatch(p -> p.age < 33));
pr("anyMatch: age < 33: \n\t" + persons.stream().anyMatch(p -> p.age < 33));
pr("anyMatch: age < 0: \n\t" + persons.stream().anyMatch(p -> p.age < 0));
pr("findAny: \n\t" + persons.stream().findAny());
pr("findFirst: \n\t" + persons.stream().findFirst());
pr("Limit to 3");
persons.stream().limit(3).forEach(p -> pr("\t" + p));
pr("min by age : " + persons.stream().min((p1, p2) -> p1.age - p2.age));
pr("max by ssn: " + persons.stream().max((p1, p2) -> p1.ssn.compareTo(p2.ssn)));
pr("counter:");
AtomicInteger counter = new AtomicInteger(0);
persons.stream().peek(p -> counter.incrementAndGet()).forEach(p -> pr("\1" + counter.get() + ": " + p));
pr("flatmap");
persons.stream().flatMap(p -> p.getHobbies().stream()).forEach(p -> pr("\t" + p));
pr("collectors.counting:\n\t" + persons.stream().collect(Collectors.counting()));
pr("collectors.map(age).list");
persons.stream().map(Person::getAge).collect(Collectors.toList()).forEach(age -> pr("\t" + age));
pr("unfold");
persons
.stream()
.flatMap(p -> p.hobbies.stream().map(hobby -> new Object[] {hobby, p.name}))
.collect(Collectors.groupingBy(o -> o[0]))
.forEach((k, v) -> {
System.out.print("\n\t" + k + "\n\t\t");
v.stream().forEach(v1 -> System.out.print("," + v1[1]));
});
pr("");
}
public void runOptionalExamples() {
Person zzz = new Person("999-99-9999", "Mr. Z", 99, "reading");
Person zzz2 = new Person("999-99-9999", "Mr. Z", 99, "reading");
Person yyy = new Person("888-888-8888", "Mr. Y", 88, "hobby");
Person nul = new Person(null, null, 0);
Optional<Person> o1 = Optional.of(zzz);
Optional<Person> o2 = Optional.ofNullable(null);
Optional<Person> o3 = Optional.empty();
Optional<Person> z1 = Optional.of(zzz);
Optional<Person> z2 = Optional.of(zzz2);
Optional<Person> y = Optional.of(yyy);
Optional<Person> onul = Optional.of(nul);
pr("isPresent");
pr("\to1: " + o1.isPresent());
pr("\to2: " + o2.isPresent());
pr("\to3: " + o3.isPresent());
pr("ifPresent");
o1.ifPresent(p -> pr("\tfound: " + p));
pr("z1 equals z2: " + z1.equals(z2));
pr("z1 equals zzz: " + z1.equals(zzz));
pr("z1 equals y : " + z1.equals(y));
pr("filter(age=99) : " + z1.filter(p -> p.age == 99));
pr("filter(age=77) : " + z1.filter(p -> p.age == 77));
pr("map.age: " + z1.map(p -> p.age));
pr("map.ssn: " + onul.map(p -> p.ssn));
pr("orElse(z1): " + z1.orElseGet(Person::new));
pr("orElse(o3): " + o3.orElseGet(Person::new));
}
}
|
package mine.fan;
public abstract class PowerSwitch extends StartStopDevice {
private String name;
public PowerSwitch(String name) {
this.name = name;
}
public void start() {
System.out.println(this.name + " is being short-circuted ");
}
public void stop() {
System.out.println(this.name + " is being opened");
}
}
|
package com.git.cloud.resmgt.compute.dao.impl;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import com.git.cloud.common.dao.CommonDAOImpl;
import com.git.cloud.common.exception.RollbackableBizException;
import com.git.cloud.resmgt.compute.dao.ICmPortGroupDao;
import com.git.cloud.resmgt.compute.model.po.CmPortGroupPo;
public class CmPortGroupDaoImpl extends CommonDAOImpl implements ICmPortGroupDao{
@Override
public CmPortGroupPo findCmPortGroupPoByVmHostId(Map<String,String> pMap)
throws RollbackableBizException {
List<CmPortGroupPo> list = this.getSqlMapClientTemplate().queryForList("findCmPortGroupPoByVmHostId", pMap);
if(list.size() > 0){
return list.get(0);
}
else{
return null;
}
}
@Override
public CmPortGroupPo getCmPortGroupPoByVmHostId(Map<String, String> pMap) throws RollbackableBizException {
List<CmPortGroupPo> list = this.getSqlMapClientTemplate().queryForList("listCmPortGroupPoByVmHostId", pMap);
for (CmPortGroupPo cmPortGroupPo:list) {
//如果分布式存在分布式交换机,则直接返回,否则
if (StringUtils.isNotEmpty(cmPortGroupPo.getDvcSwitchHostId())) {
return cmPortGroupPo;
}
}
if (list.size() > 0) {
return list.get(0);
} else {
return null;
}
}
}
|
/*
* Copyright 2002-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://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.springframework.util;
import java.io.File;
import java.io.FileNotFoundException;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLConnection;
import org.springframework.lang.Nullable;
/**
* Utility methods for resolving resource locations to files in the
* file system. Mainly for internal use within the framework.
*
* <p>Consider using Spring's Resource abstraction in the core package
* for handling all kinds of file resources in a uniform manner.
* {@link org.springframework.core.io.ResourceLoader}'s {@code getResource()}
* method can resolve any location to a {@link org.springframework.core.io.Resource}
* object, which in turn allows one to obtain a {@code java.io.File} in the
* file system through its {@code getFile()} method.
*
* @author Juergen Hoeller
* @since 1.1.5
* @see org.springframework.core.io.Resource
* @see org.springframework.core.io.ClassPathResource
* @see org.springframework.core.io.FileSystemResource
* @see org.springframework.core.io.UrlResource
* @see org.springframework.core.io.ResourceLoader
*/
public abstract class ResourceUtils {
/** Pseudo URL prefix for loading from the class path: "classpath:". */
public static final String CLASSPATH_URL_PREFIX = "classpath:";
/** URL prefix for loading from the file system: "file:". */
public static final String FILE_URL_PREFIX = "file:";
/** URL prefix for loading from a jar file: "jar:". */
public static final String JAR_URL_PREFIX = "jar:";
/** URL prefix for loading from a war file on Tomcat: "war:". */
public static final String WAR_URL_PREFIX = "war:";
/** URL protocol for a file in the file system: "file". */
public static final String URL_PROTOCOL_FILE = "file";
/** URL protocol for an entry from a jar file: "jar". */
public static final String URL_PROTOCOL_JAR = "jar";
/** URL protocol for an entry from a war file: "war". */
public static final String URL_PROTOCOL_WAR = "war";
/** URL protocol for an entry from a zip file: "zip". */
public static final String URL_PROTOCOL_ZIP = "zip";
/** URL protocol for an entry from a WebSphere jar file: "wsjar". */
public static final String URL_PROTOCOL_WSJAR = "wsjar";
/** URL protocol for an entry from a JBoss jar file: "vfszip". */
public static final String URL_PROTOCOL_VFSZIP = "vfszip";
/** URL protocol for a JBoss file system resource: "vfsfile". */
public static final String URL_PROTOCOL_VFSFILE = "vfsfile";
/** URL protocol for a general JBoss VFS resource: "vfs". */
public static final String URL_PROTOCOL_VFS = "vfs";
/** File extension for a regular jar file: ".jar". */
public static final String JAR_FILE_EXTENSION = ".jar";
/** Separator between JAR URL and file path within the JAR: "!/". */
public static final String JAR_URL_SEPARATOR = "!/";
/** Special separator between WAR URL and jar part on Tomcat. */
public static final String WAR_URL_SEPARATOR = "*/";
/**
* Return whether the given resource location is a URL:
* either a special "classpath" pseudo URL or a standard URL.
* @param resourceLocation the location String to check
* @return whether the location qualifies as a URL
* @see #CLASSPATH_URL_PREFIX
* @see java.net.URL
*/
public static boolean isUrl(@Nullable String resourceLocation) {
if (resourceLocation == null) {
return false;
}
if (resourceLocation.startsWith(CLASSPATH_URL_PREFIX)) {
return true;
}
try {
toURL(resourceLocation);
return true;
}
catch (MalformedURLException ex) {
return false;
}
}
/**
* Resolve the given resource location to a {@code java.net.URL}.
* <p>Does not check whether the URL actually exists; simply returns
* the URL that the given location would correspond to.
* @param resourceLocation the resource location to resolve: either a
* "classpath:" pseudo URL, a "file:" URL, or a plain file path
* @return a corresponding URL object
* @throws FileNotFoundException if the resource cannot be resolved to a URL
*/
public static URL getURL(String resourceLocation) throws FileNotFoundException {
Assert.notNull(resourceLocation, "Resource location must not be null");
if (resourceLocation.startsWith(CLASSPATH_URL_PREFIX)) {
String path = resourceLocation.substring(CLASSPATH_URL_PREFIX.length());
ClassLoader cl = ClassUtils.getDefaultClassLoader();
URL url = (cl != null ? cl.getResource(path) : ClassLoader.getSystemResource(path));
if (url == null) {
String description = "class path resource [" + path + "]";
throw new FileNotFoundException(description +
" cannot be resolved to URL because it does not exist");
}
return url;
}
try {
// try URL
return toURL(resourceLocation);
}
catch (MalformedURLException ex) {
// no URL -> treat as file path
try {
return new File(resourceLocation).toURI().toURL();
}
catch (MalformedURLException ex2) {
throw new FileNotFoundException("Resource location [" + resourceLocation +
"] is neither a URL not a well-formed file path");
}
}
}
/**
* Resolve the given resource location to a {@code java.io.File},
* i.e. to a file in the file system.
* <p>Does not check whether the file actually exists; simply returns
* the File that the given location would correspond to.
* @param resourceLocation the resource location to resolve: either a
* "classpath:" pseudo URL, a "file:" URL, or a plain file path
* @return a corresponding File object
* @throws FileNotFoundException if the resource cannot be resolved to
* a file in the file system
*/
public static File getFile(String resourceLocation) throws FileNotFoundException {
Assert.notNull(resourceLocation, "Resource location must not be null");
if (resourceLocation.startsWith(CLASSPATH_URL_PREFIX)) {
String path = resourceLocation.substring(CLASSPATH_URL_PREFIX.length());
String description = "class path resource [" + path + "]";
ClassLoader cl = ClassUtils.getDefaultClassLoader();
URL url = (cl != null ? cl.getResource(path) : ClassLoader.getSystemResource(path));
if (url == null) {
throw new FileNotFoundException(description +
" cannot be resolved to absolute file path because it does not exist");
}
return getFile(url, description);
}
try {
// try URL
return getFile(toURL(resourceLocation));
}
catch (MalformedURLException ex) {
// no URL -> treat as file path
return new File(resourceLocation);
}
}
/**
* Resolve the given resource URL to a {@code java.io.File},
* i.e. to a file in the file system.
* @param resourceUrl the resource URL to resolve
* @return a corresponding File object
* @throws FileNotFoundException if the URL cannot be resolved to
* a file in the file system
*/
public static File getFile(URL resourceUrl) throws FileNotFoundException {
return getFile(resourceUrl, "URL");
}
/**
* Resolve the given resource URL to a {@code java.io.File},
* i.e. to a file in the file system.
* @param resourceUrl the resource URL to resolve
* @param description a description of the original resource that
* the URL was created for (for example, a class path location)
* @return a corresponding File object
* @throws FileNotFoundException if the URL cannot be resolved to
* a file in the file system
*/
public static File getFile(URL resourceUrl, String description) throws FileNotFoundException {
Assert.notNull(resourceUrl, "Resource URL must not be null");
if (!URL_PROTOCOL_FILE.equals(resourceUrl.getProtocol())) {
throw new FileNotFoundException(
description + " cannot be resolved to absolute file path " +
"because it does not reside in the file system: " + resourceUrl);
}
try {
// URI decoding for special characters such as spaces.
return new File(toURI(resourceUrl).getSchemeSpecificPart());
}
catch (URISyntaxException ex) {
// Fallback for URLs that are not valid URIs (should hardly ever happen).
return new File(resourceUrl.getFile());
}
}
/**
* Resolve the given resource URI to a {@code java.io.File},
* i.e. to a file in the file system.
* @param resourceUri the resource URI to resolve
* @return a corresponding File object
* @throws FileNotFoundException if the URL cannot be resolved to
* a file in the file system
* @since 2.5
*/
public static File getFile(URI resourceUri) throws FileNotFoundException {
return getFile(resourceUri, "URI");
}
/**
* Resolve the given resource URI to a {@code java.io.File},
* i.e. to a file in the file system.
* @param resourceUri the resource URI to resolve
* @param description a description of the original resource that
* the URI was created for (for example, a class path location)
* @return a corresponding File object
* @throws FileNotFoundException if the URL cannot be resolved to
* a file in the file system
* @since 2.5
*/
public static File getFile(URI resourceUri, String description) throws FileNotFoundException {
Assert.notNull(resourceUri, "Resource URI must not be null");
if (!URL_PROTOCOL_FILE.equals(resourceUri.getScheme())) {
throw new FileNotFoundException(
description + " cannot be resolved to absolute file path " +
"because it does not reside in the file system: " + resourceUri);
}
return new File(resourceUri.getSchemeSpecificPart());
}
/**
* Determine whether the given URL points to a resource in the file system,
* i.e. has protocol "file", "vfsfile" or "vfs".
* @param url the URL to check
* @return whether the URL has been identified as a file system URL
*/
public static boolean isFileURL(URL url) {
String protocol = url.getProtocol();
return (URL_PROTOCOL_FILE.equals(protocol) || URL_PROTOCOL_VFSFILE.equals(protocol) ||
URL_PROTOCOL_VFS.equals(protocol));
}
/**
* Determine whether the given URL points to a resource in a jar file.
* i.e. has protocol "jar", "war, ""zip", "vfszip" or "wsjar".
* @param url the URL to check
* @return whether the URL has been identified as a JAR URL
*/
public static boolean isJarURL(URL url) {
String protocol = url.getProtocol();
return (URL_PROTOCOL_JAR.equals(protocol) || URL_PROTOCOL_WAR.equals(protocol) ||
URL_PROTOCOL_ZIP.equals(protocol) || URL_PROTOCOL_VFSZIP.equals(protocol) ||
URL_PROTOCOL_WSJAR.equals(protocol));
}
/**
* Determine whether the given URL points to a jar file itself,
* that is, has protocol "file" and ends with the ".jar" extension.
* @param url the URL to check
* @return whether the URL has been identified as a JAR file URL
* @since 4.1
*/
public static boolean isJarFileURL(URL url) {
return (URL_PROTOCOL_FILE.equals(url.getProtocol()) &&
url.getPath().toLowerCase().endsWith(JAR_FILE_EXTENSION));
}
/**
* Extract the URL for the actual jar file from the given URL
* (which may point to a resource in a jar file or to a jar file itself).
* @param jarUrl the original URL
* @return the URL for the actual jar file
* @throws MalformedURLException if no valid jar file URL could be extracted
*/
public static URL extractJarFileURL(URL jarUrl) throws MalformedURLException {
String urlFile = jarUrl.getFile();
int separatorIndex = urlFile.indexOf(JAR_URL_SEPARATOR);
if (separatorIndex != -1) {
String jarFile = urlFile.substring(0, separatorIndex);
try {
return toURL(jarFile);
}
catch (MalformedURLException ex) {
// Probably no protocol in original jar URL, like "jar:C:/mypath/myjar.jar".
// This usually indicates that the jar file resides in the file system.
if (!jarFile.startsWith("/")) {
jarFile = "/" + jarFile;
}
return toURL(FILE_URL_PREFIX + jarFile);
}
}
else {
return jarUrl;
}
}
/**
* Extract the URL for the outermost archive from the given jar/war URL
* (which may point to a resource in a jar file or to a jar file itself).
* <p>In the case of a jar file nested within a war file, this will return
* a URL to the war file since that is the one resolvable in the file system.
* @param jarUrl the original URL
* @return the URL for the actual jar file
* @throws MalformedURLException if no valid jar file URL could be extracted
* @since 4.1.8
* @see #extractJarFileURL(URL)
*/
public static URL extractArchiveURL(URL jarUrl) throws MalformedURLException {
String urlFile = jarUrl.getFile();
int endIndex = urlFile.indexOf(WAR_URL_SEPARATOR);
if (endIndex != -1) {
// Tomcat's "war:file:...mywar.war*/WEB-INF/lib/myjar.jar!/myentry.txt"
String warFile = urlFile.substring(0, endIndex);
if (URL_PROTOCOL_WAR.equals(jarUrl.getProtocol())) {
return toURL(warFile);
}
int startIndex = warFile.indexOf(WAR_URL_PREFIX);
if (startIndex != -1) {
return toURL(warFile.substring(startIndex + WAR_URL_PREFIX.length()));
}
}
// Regular "jar:file:...myjar.jar!/myentry.txt"
return extractJarFileURL(jarUrl);
}
/**
* Create a URI instance for the given URL,
* replacing spaces with "%20" URI encoding first.
* @param url the URL to convert into a URI instance
* @return the URI instance
* @throws URISyntaxException if the URL wasn't a valid URI
* @see java.net.URL#toURI()
*/
public static URI toURI(URL url) throws URISyntaxException {
return toURI(url.toString());
}
/**
* Create a URI instance for the given location String,
* replacing spaces with "%20" URI encoding first.
* @param location the location String to convert into a URI instance
* @return the URI instance
* @throws URISyntaxException if the location wasn't a valid URI
*/
public static URI toURI(String location) throws URISyntaxException {
return new URI(StringUtils.replace(location, " ", "%20"));
}
/**
* Create a URL instance for the given location String,
* going through URI construction and then URL conversion.
* @param location the location String to convert into a URL instance
* @return the URL instance
* @throws MalformedURLException if the location wasn't a valid URL
* @since 6.0
*/
@SuppressWarnings("deprecation") // on JDK 20
public static URL toURL(String location) throws MalformedURLException {
try {
// Prefer URI construction with toURL conversion (as of 6.1)
return toURI(StringUtils.cleanPath(location)).toURL();
}
catch (URISyntaxException | IllegalArgumentException ex) {
// Lenient fallback to deprecated (on JDK 20) URL constructor,
// e.g. for decoded location Strings with percent characters.
return new URL(location);
}
}
/**
* Create a URL instance for the given root URL and relative path,
* going through URI construction and then URL conversion.
* @param root the root URL to start from
* @param relativePath the relative path to apply
* @return the relative URL instance
* @throws MalformedURLException if the end result is not a valid URL
* @since 6.0
*/
public static URL toRelativeURL(URL root, String relativePath) throws MalformedURLException {
// # can appear in filenames, java.net.URL should not treat it as a fragment
relativePath = StringUtils.replace(relativePath, "#", "%23");
return toURL(StringUtils.applyRelativePath(root.toString(), relativePath));
}
/**
* Set the {@link URLConnection#setUseCaches "useCaches"} flag on the
* given connection, preferring {@code false} but leaving the
* flag at {@code true} for JNLP based resources.
* @param con the URLConnection to set the flag on
*/
public static void useCachesIfNecessary(URLConnection con) {
con.setUseCaches(con.getClass().getSimpleName().startsWith("JNLP"));
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.