text
stringlengths 10
2.72M
|
|---|
package br.com.pcmaker.service;
import java.util.List;
import br.com.pcmaker.entity.Equipamento;
public interface EquipamentoService extends CrudService<Equipamento>{
List<Equipamento> query(String nome);
}
|
package bonimed.vn.login;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Paint;
import android.net.Uri;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import org.json.JSONException;
import org.json.JSONObject;
import bonimed.vn.MainActivity;
import bonimed.vn.R;
import bonimed.vn.api.FastNetworking;
import bonimed.vn.base.BaseActivity;
import bonimed.vn.listener.DialogOneButtonCallBackListener;
import bonimed.vn.listener.DialogTwoButtonCallBackListener;
import bonimed.vn.listener.JsonObjectCallBackListener;
import bonimed.vn.util.Constants;
import bonimed.vn.util.DialogUtil;
import bonimed.vn.util.Network;
import bonimed.vn.util.PrefManager;
import bonimed.vn.util.ProgressDialogUtils;
import bonimed.vn.util.Utils;
/**
* Created by mac on 10/24/17.
*/
public class LoginActivity extends BaseActivity implements View.OnClickListener {
private EditText mEdtUsername, mEdtPassword;
private Button mBtnSignIn;
private TextView mTvLicenseUrl;
private ProgressDialogUtils mProgress;
private UserLogin mUserLogin;
private Gson mGson;
private String mVersionApp;
@Override
protected int getLayoutView() {
return R.layout.activity_login;
}
@Override
protected void initViews() {
mEdtUsername = (EditText) findViewById(R.id.edt_username);
mEdtPassword = (EditText) findViewById(R.id.edt_password);
mBtnSignIn = (Button) findViewById(R.id.btn_login);
mTvLicenseUrl = (TextView) findViewById(R.id.tv_license_url);
mTvLicenseUrl.setPaintFlags(mTvLicenseUrl.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG);
}
@Override
protected void initListeners() {
mBtnSignIn.setOnClickListener(this);
mTvLicenseUrl.setOnClickListener(this);
mEdtUsername.setOnFocusChangeListener(new MyOnFocusChangeListener());
mEdtPassword.setOnFocusChangeListener(new MyOnFocusChangeListener());
mProgress = new ProgressDialogUtils(this);
}
@Override
protected void initDatas(Bundle saveInstanceStatte) {
String jsonUserLogin = PrefManager.getJsonObjectUserLogin(this);
mGson = new Gson();
if (!TextUtils.isEmpty(jsonUserLogin)) {
mUserLogin = mGson.fromJson(jsonUserLogin, UserLogin.class);
}
try {
mVersionApp = getPackageManager().getPackageInfo(getPackageName(), 0).versionName;
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
if (PrefManager.getLoginState(LoginActivity.this) == 1 && mUserLogin != null
&& !TextUtils.isEmpty(mUserLogin.versionApp) && mUserLogin.versionApp.equalsIgnoreCase(mVersionApp)) {
startActivityAnim(MainActivity.class, null);
finish();
return;
}
}
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.btn_login:
if (!validateName()) {
return;
}
if (Network.isOnline(this)) {
callApiLogin(mEdtUsername.getText().toString(), mEdtPassword.getText().toString());
} else {
DialogUtil.showAlertDialogOneButtonClicked(this, getString(R.string.title_no_connection)
, getString(R.string.message_no_connection), getString(R.string.text_positive), null);
}
break;
case R.id.tv_license_url:
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(Constants.URL_BONIMED));
startActivity(i);
break;
}
}
private void callApiLogin(String username, String password) {
mProgress.showDialog();
final Gson gson = new Gson();
UserLogin userLogin = new UserLogin();
userLogin.userName = username;
userLogin.password = password;
final String json = gson.toJson(userLogin);
try {
JSONObject jsonObject = new JSONObject(json);
FastNetworking fastNetworking = new FastNetworking(this, new JsonObjectCallBackListener() {
@Override
public void onResponse(final JSONObject jsonObject) {
mProgress.hideDialog();
UserLogin userLoginSuccess = gson.fromJson(jsonObject.toString(), UserLogin.class);
Log.d("TUDA", "user = " + userLoginSuccess);
if (userLoginSuccess.securityToken != null) {
DialogUtil.showAlertDialogButtonClicked(LoginActivity.this, ""
, getString(R.string.message_save_data), getString(R.string.text_positive), getString(R.string.text_negative), new DialogTwoButtonCallBackListener() {
@Override
public void onPositiveButtonClick() {
PrefManager.putLoginState(LoginActivity.this);
loginSuccess(jsonObject.toString());
}
@Override
public void onNegativeButtonClick() {
loginSuccess(jsonObject.toString());
}
});
}
}
@Override
public void onError(String messageError) {
mProgress.hideDialog();
}
});
fastNetworking.callApiLogin(jsonObject);
} catch (JSONException e) {
e.printStackTrace();
mProgress.hideDialog();
}
}
private void loginSuccess(String jsonObject) {
UserLogin userLogin = mGson.fromJson(jsonObject, UserLogin.class);
userLogin.versionApp = mVersionApp;
String json = mGson.toJson(userLogin);
PrefManager.putJsonObjectUserLogin(LoginActivity.this, json);
startActivityAnim(MainActivity.class, null);
finish();
}
private class MyOnFocusChangeListener implements View.OnFocusChangeListener {
@Override
public void onFocusChange(View view, boolean b) {
if (!b) {
Utils.hideKeyboard(LoginActivity.this, view);
}
}
}
private boolean validateName() {
if (TextUtils.isEmpty(mEdtUsername.getText().toString().trim())) {
mEdtUsername.setError(getString(R.string.err_msg_username));
requestFocus(mEdtUsername);
return false;
}
return true;
}
private void requestFocus(View view) {
if (view.requestFocus()) {
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
}
}
}
|
package br.usp.memoriavirtual.controle;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.ejb.EJB;
import javax.el.ELResolver;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletResponse;
import br.usp.memoriavirtual.modelo.entidades.Multimidia;
import br.usp.memoriavirtual.modelo.entidades.Usuario;
import br.usp.memoriavirtual.modelo.entidades.bempatrimonial.BemArqueologico;
import br.usp.memoriavirtual.modelo.entidades.bempatrimonial.BemArquitetonico;
import br.usp.memoriavirtual.modelo.entidades.bempatrimonial.BemNatural;
import br.usp.memoriavirtual.modelo.entidades.bempatrimonial.BemPatrimonial;
import br.usp.memoriavirtual.modelo.fachadas.ModeloException;
import br.usp.memoriavirtual.modelo.fachadas.remoto.RealizarBuscaSimplesRemote;
import br.usp.memoriavirtual.utils.MensagensDeErro;
@ManagedBean(name = "realizarBuscaSimplesMB")
@SessionScoped
public class RealizarBuscaSimplesMB implements Serializable, BeanComMidia {
/**
*
*/
private static final long serialVersionUID = 4130356176853401265L;
@EJB
private RealizarBuscaSimplesRemote realizarBuscaEJB;
private String busca;
private List<BemPatrimonial> bens = new ArrayList<BemPatrimonial>();
private BemPatrimonial bem;
private BemArqueologico bemArqueologico = null;
private BemArquitetonico bemArquitetonico = null;
private BemNatural bemNatural = null;
private boolean arquitetonico;
private boolean arqueologico;
private boolean natural;
private ArrayList<Integer> apresentaMidias = new ArrayList<Integer>();
public RealizarBuscaSimplesMB() {
}
public String buscar() {
try {
this.bens = realizarBuscaEJB.buscar(this.busca);
} catch (Exception e) {
e.printStackTrace();
MensagensDeErro.getErrorMessage("realizarBuscaSimplesErro",
"resultado");
return null;
}
return "resultadosbusca";
}
public String excluir() {
// Inicializando Managed Bean
FacesContext facesContext = FacesContext.getCurrentInstance();
ELResolver resolver = facesContext.getApplication().getELResolver();
ExcluirBemPatrimonialMB managedBean = (ExcluirBemPatrimonialMB) resolver
.getValue(facesContext.getELContext(), null,
"excluirBemPatrimonialMB");
managedBean.selecionarBem(this.bem);
return "/restrito/selecionarbemexclusao.jsf";
}
public String editar() {
// Inicializando Managed Bean
FacesContext facesContext = FacesContext.getCurrentInstance();
ELResolver resolver = facesContext.getApplication().getELResolver();
EditarBemPatrimonialMB managedBean = (EditarBemPatrimonialMB) resolver
.getValue(facesContext.getELContext(), null,
"editarBemPatrimonialMB");
managedBean.anexarBemPatrimonial(this.bem);
return "/restrito/editarbempatrimonial.jsf";
}
public boolean permissao() {
Usuario usuario = (Usuario) FacesContext.getCurrentInstance()
.getExternalContext().getSessionMap().get("usuario");
if (usuario == null)
return false;
try {
if (usuario.isAdministrador())
return true;
else if (this.realizarBuscaEJB.possuiAcesso(usuario,
this.bem.getInstituicao()))
return true;
else
return false;
} catch (ModeloException m) {
m.printStackTrace();
}
return false;
}
public String resultado(BemPatrimonial b) {
this.bem = b;
this.determinaTipo();
for (int i = 0; i < this.bem.getContainerMultimidia().getMultimidia()
.size(); ++i) {
this.apresentaMidias.add(i, i);
this.apresentaMidias.trimToSize();
}
if (this.bem.getTipoDoBemPatrimonial().equals("BemArqueologico")) {
try {
this.bemArqueologico = this.realizarBuscaEJB
.buscarBemArqueologico(this.bem);
} catch (ModeloException m) {
m.printStackTrace();
}
}
if (this.bem.getTipoDoBemPatrimonial().equals("BemArquitetonico")) {
try {
this.bemArquitetonico = this.realizarBuscaEJB
.buscarBemArquitetonico(this.bem);
} catch (ModeloException m) {
m.printStackTrace();
}
}
if (this.bem.getTipoDoBemPatrimonial().equals("BemNatural")) {
try {
this.bemNatural = this.realizarBuscaEJB
.buscarBemNatural(this.bem);
} catch (ModeloException m) {
m.printStackTrace();
}
}
return "bempatrimonial";
}
public String voltar() {
this.apresentaMidias.clear();
return this.buscar();
}
public void determinaTipo() {
if (this.bem.getTipoDoBemPatrimonial().equalsIgnoreCase("arqueologico")) {
this.arqueologico = true;
this.arquitetonico = false;
this.natural = false;
try {
this.bemArqueologico = realizarBuscaEJB
.buscarBemArqueologico(bem);
} catch (ModeloException e) {
MensagensDeErro.getErrorMessage("erro", "resultado");
}
} else if (this.bem.getTipoDoBemPatrimonial().equalsIgnoreCase(
"arquitetonico")) {
this.arqueologico = false;
this.arquitetonico = true;
this.natural = false;
try {
this.bemArquitetonico = realizarBuscaEJB
.buscarBemArquitetonico(bem);
} catch (ModeloException e) {
MensagensDeErro.getErrorMessage("erro", "resultado");
}
} else if (this.bem.getTipoDoBemPatrimonial().equalsIgnoreCase(
"natural")) {
this.arqueologico = false;
this.arquitetonico = false;
this.natural = true;
try {
this.bemNatural = realizarBuscaEJB.buscarBemNatural(bem);
} catch (ModeloException e) {
MensagensDeErro.getErrorMessage("erro", "resultado");
}
}
}
public void download(Integer index) {
FacesContext facesContext = FacesContext.getCurrentInstance();
ExternalContext externalContext = facesContext.getExternalContext();
HttpServletResponse response = (HttpServletResponse) externalContext
.getResponse();
Multimidia midia = this.bem.getContainerMultimidia().getMultimidia()
.get(index);
response.reset();
response.setContentType(midia.getContentType());
response.setHeader("Content-disposition", "attachment; filename="
+ midia.getNome());
BufferedInputStream input = null;
BufferedOutputStream output = null;
try {
input = new BufferedInputStream(new ByteArrayInputStream(
midia.getContent()));
output = new BufferedOutputStream(response.getOutputStream());
for (int length; (length = input.read(midia.getContent())) > 0;)
output.write(midia.getContent(), 0, length);
input.close();
output.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public String getBusca() {
return busca;
}
public void setBusca(String busca) {
this.busca = busca;
}
public List<BemPatrimonial> getBens() {
return bens;
}
public void setBens(List<BemPatrimonial> bens) {
this.bens = bens;
}
public boolean isRendSair() {
FacesContext context = FacesContext.getCurrentInstance();
Usuario usuario = (Usuario) context.getExternalContext()
.getSessionMap().get("usuario");
if (usuario != null) {
return true;
} else {
return false;
}
}
public boolean isRendLogin() {
FacesContext context = FacesContext.getCurrentInstance();
Usuario usuario = (Usuario) context.getExternalContext()
.getSessionMap().get("usuario");
if (usuario != null) {
return false;
} else {
return true;
}
}
public BemPatrimonial getBem() {
return bem;
}
public void setBem(BemPatrimonial bem) {
this.bem = bem;
}
public BemArqueologico getBemArqueologico() {
return bemArqueologico;
}
public void setBemArqueologico(BemArqueologico bemArqueologico) {
this.bemArqueologico = bemArqueologico;
}
public BemArquitetonico getBemArquitetonico() {
return bemArquitetonico;
}
public void setBemArquitetonico(BemArquitetonico bemArquitetonico) {
this.bemArquitetonico = bemArquitetonico;
}
public BemNatural getBemNatural() {
return bemNatural;
}
public void setBemNatural(BemNatural bemNatural) {
this.bemNatural = bemNatural;
}
public boolean isArquitetonico() {
return arquitetonico;
}
public void setArquitetonico(boolean arquitetonico) {
this.arquitetonico = arquitetonico;
}
public boolean isArqueologico() {
return arqueologico;
}
public void setArqueologico(boolean arqueologico) {
this.arqueologico = arqueologico;
}
public boolean isNatural() {
return natural;
}
public void setNatural(boolean natural) {
this.natural = natural;
}
@Override
public List<Multimidia> recuperaColecaoMidia() {
return this.bem.getContainerMultimidia().getMultimidia();
}
@Override
public void adicionarMidia(Multimidia midia) {
}
@Override
public String removeMidia(Multimidia midia) {
return null;
}
@Override
public String removeMidia(int index) {
return null;
}
@Override
public ArrayList<Integer> getApresentaMidias() {
return this.apresentaMidias;
}
@Override
public void setApresentaMidias(ArrayList<Integer> apresentaMidias) {
this.apresentaMidias = apresentaMidias;
}
@Override
public boolean isRenderCell(int index) {
return false;
}
public String url(Integer index) {
return "/multimidia?bean=realizarBuscaSimplesMB&indice="
+ index.toString() + "&thumb=true&type=false";
}
}
|
package com.codeclan.example.shopkeep;
/**
* Created by user on 25/02/2017.
*/
public class PaymentMethod {
private double balance;
private String cardName;
public PaymentMethod(String name, double openingBalance) {
this.balance = openingBalance;
this.cardName = name;
}
public void chargeToPaymentMethod(double cost) {
adjustBalance(-cost);
}
public void refundToPaymentMethod(double cost) {
adjustBalance(cost);
}
private void adjustBalance(double amount) {
balance += amount;
}
public String getName() {
return cardName;
}
public double getBalance() {
return balance;
}
}
|
package Estructuras;
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;
class NivelesTest {
void testNivel1() {
Niveles n = new Niveles();
Linked_List m = n.Nivel1();
int j = m.getLenght();
assertEquals(15, j);
}
}
|
package uo.sdi.dto.rest;
import java.io.Serializable;
import java.util.Date;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import alb.util.date.DateUtil;
@XmlRootElement(name = "task")
public class RestClientTask implements Serializable, Comparable<RestClientTask> {
private static final long serialVersionUID = -5194439578090536982L;
private Long id;
private String title;
private String comments;
private Date created = DateUtil.today();
private Date planned;
private Date finished;
private RestClientCategory category;
@XmlElement
public Long getId() {
return id;
}
public RestClientTask setId(Long id) {
this.id = id;
return this;
}
@XmlElement
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
@XmlElement
public String getComments() {
return comments;
}
public void setComments(String comments) {
this.comments = comments;
}
@XmlElement
public Date getCreated() {
return created;
}
public RestClientTask setCreated(Date created) {
this.created = created;
return this;
}
@XmlElement
public Date getPlanned() {
return planned;
}
public void setPlanned(Date planned) {
this.planned = planned;
}
@XmlElement
public Date getFinished() {
return finished;
}
public RestClientTask setFinished(Date finished) {
this.finished = finished;
return this;
}
@Override
public String toString() {
return "TaskDto [id=" + id + ", title=" + title + ", comments="
+ comments + ", created=" + created + ", planned=" + planned
+ ", finished=" + finished + ", category=" + category + "]";
}
@Override
public int compareTo(RestClientTask o) {
if (o.getPlanned() != null && getPlanned() != null)
return getPlanned().compareTo(o.getPlanned());
else if (o.getPlanned() == null)
return -1;
else
return 1;
}
}
|
package com.espendwise.manta.web.forms;
import com.espendwise.manta.model.data.BusEntityData;
import com.espendwise.manta.util.SelectableObjects;
import java.util.List;
public class UserAccountFilterResultForm extends AbstractFilterResult<SelectableObjects.SelectableObject<BusEntityData>> {
private SelectableObjects<BusEntityData> accounts;
private Boolean removeSitesWithAccounts;
public SelectableObjects<BusEntityData> getAccounts() {
return accounts;
}
public void setAccounts(SelectableObjects<BusEntityData> accounts) {
this.accounts = accounts;
}
@Override
public List<SelectableObjects.SelectableObject<BusEntityData>> getResult() {
return accounts != null ? accounts.getSelectableObjects() : null;
}
@Override
public void reset() {
super.reset();
this.accounts = null;
this.removeSitesWithAccounts = false;
}
public Boolean getRemoveSitesWithAccounts() {
return removeSitesWithAccounts;
}
public void setRemoveSitesWithAccounts(Boolean removeSitesWithAccounts) {
this.removeSitesWithAccounts = removeSitesWithAccounts;
}
}
|
package com.tencent.mm.plugin.game.model;
import android.os.Build.VERSION;
import com.tencent.mm.ab.b;
import com.tencent.mm.ab.b.a;
import com.tencent.mm.ab.e;
import com.tencent.mm.ab.l;
import com.tencent.mm.kernel.g;
import com.tencent.mm.network.k;
import com.tencent.mm.network.q;
import com.tencent.mm.plugin.game.a.c;
import com.tencent.mm.plugin.game.d.aw;
import com.tencent.mm.plugin.game.d.ax;
import com.tencent.mm.plugin.game.d.d;
import com.tencent.mm.sdk.platformtools.ad;
import com.tencent.mm.sdk.platformtools.bi;
import com.tencent.mm.sdk.platformtools.w;
import com.tencent.mm.sdk.platformtools.x;
public final class au extends l implements k {
private e diJ;
private final b ivx;
public au() {
a aVar = new a();
aVar.dIG = new aw();
aVar.dIH = new ax();
aVar.uri = "/cgi-bin/mmgame-bin/getgamecenterglobalsetting";
aVar.dIF = 1311;
aVar.dII = 0;
aVar.dIJ = 0;
this.ivx = aVar.KT();
aw awVar = (aw) this.ivx.dID.dIL;
awVar.jRj = w.chP();
String dz = f.dz(ad.getContext());
if (bi.oW(dz)) {
dz = bi.fS(ad.getContext());
}
awVar.eJQ = dz;
awVar.jRk = com.tencent.mm.sdk.platformtools.e.bxk;
awVar.jRl = new d();
awVar.jRl.jPa = VERSION.SDK_INT;
awVar.jRl.jPb = com.b.a.a.b.V(ad.getContext());
x.i("MicroMsg.NetSceneGetGameGlobalConfig", "lang=%s, country=%s, releaseChannel=%s, osVersion = %d, deviceLevel = %d", new Object[]{awVar.jRj, awVar.eJQ, Integer.valueOf(awVar.jRk), Integer.valueOf(awVar.jRl.jPa), Integer.valueOf(awVar.jRl.jPb)});
}
public final void a(int i, int i2, int i3, String str, q qVar, byte[] bArr) {
x.i("MicroMsg.NetSceneGetGameGlobalConfig", "errType = " + i2 + ", errCode = " + i3 + ", errMsg = " + str);
if (i2 == 0 && i3 == 0) {
ax axVar = (ax) ((b) qVar).dIE.dIL;
if (axVar == null) {
this.diJ.a(i2, i3, str, this);
return;
}
((c) g.l(c.class)).aSk().a("pb_game_global_config", axVar);
h.aTL().Zy();
this.diJ.a(i2, i3, str, this);
return;
}
this.diJ.a(i2, i3, str, this);
}
public final int getType() {
return 1311;
}
public final int a(com.tencent.mm.network.e eVar, e eVar2) {
this.diJ = eVar2;
return a(eVar, this.ivx, this);
}
}
|
/**
*
*/
package ucl.cs.testingEmulator.contexNotifierScripts;
import javax.swing.JFrame;
import ucl.cs.testingEmulator.core.Script;
import ucl.cs.testingEmulator.time.VirtualClock;
import ucl.cs.testingEmulator.time.VirtualClockStatus;
/**
* @author -Michele Sama- aka -RAX-
*
* University College London
* Dept. of Computer Science
* Gower Street
* London WC1E 6BT
* United Kingdom
*
* Email: M.Sama (at) cs.ucl.ac.uk
*
* Group:
* Software Systems Engineering
*
*/
public class TestingAdaptiveReminder implements Script {
/* (non-Javadoc)
* @see ucl.cs.testingEmulator.core.Script#getName()
*/
public String getName() {
return TestingAdaptiveReminder.class.getSimpleName();
}
/* (non-Javadoc)
* @see java.lang.Runnable#run()
*/
public void run() {
VirtualClock.getInstance().setStatus(VirtualClockStatus.TIME_STOPPED_STATUS);
VirtualClock.setSimulatedTime(0);
JFrame frame=new JFrame(this.getName());
frame.getContentPane().add(new CommandJPanel());
frame.pack();
frame.setVisible(true);
}
}
|
/**
* Copyright (c) 2004-2011 QOS.ch
* All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
*/
package org.slf4j.reload4j;
import static org.slf4j.event.EventConstants.NA_SUBST;
import java.io.Serializable;
import org.apache.log4j.Level;
import org.apache.log4j.spi.LocationInfo;
import org.apache.log4j.spi.ThrowableInformation;
import org.slf4j.Logger;
import org.slf4j.Marker;
import org.slf4j.event.DefaultLoggingEvent;
import org.slf4j.event.LoggingEvent;
import org.slf4j.event.SubstituteLoggingEvent;
import org.slf4j.helpers.LegacyAbstractLogger;
import org.slf4j.helpers.MessageFormatter;
import org.slf4j.helpers.NormalizedParameters;
import org.slf4j.helpers.SubstituteLogger;
import org.slf4j.spi.LocationAwareLogger;
import org.slf4j.spi.LoggingEventAware;
import org.slf4j.spi.LoggingEventBuilder;
/**
* A wrapper over {@link org.apache.log4j.Logger org.apache.log4j.Logger}
* conforming to the {@link Logger} interface.
*
* <p>
* Note that the logging levels mentioned in this class refer to those defined
* in the <a href=
* "http://logging.apache.org/log4j/docs/api/org/apache/log4j/Level.html">
* <code>org.apache.log4j.Level</code></a> class.
*
* <p>This class is a copy-and-paste of Log4j12LoggerAdapter from the
* slf4j-log4j12 module.</p>
*
* @author Ceki Gülcü
* @since 2.0.0-alpha6
*/
public final class Reload4jLoggerAdapter extends LegacyAbstractLogger implements LocationAwareLogger, LoggingEventAware, Serializable {
private static final long serialVersionUID = 6989384227325275811L;
final transient org.apache.log4j.Logger logger;
final static String FQCN_NOMINAL = org.slf4j.helpers.AbstractLogger.class.getName();
final static String FQCN_SUBSTITUE = FQCN_NOMINAL;
final static String FQCN_FLUENT = org.slf4j.spi.DefaultLoggingEventBuilder.class.getName();
// WARN: Reload4jLoggerAdapter constructor should have only package access so
// that only Reload4jLoggerFactory be able to create one.
Reload4jLoggerAdapter(org.apache.log4j.Logger logger) {
this.logger = logger;
this.name = logger.getName();
}
/**
* Is this logger instance enabled for the TRACE level?
*
* @return True if this Logger is enabled for level TRACE, false otherwise.
*/
public boolean isTraceEnabled() {
return logger.isTraceEnabled();
}
/**
* Is this logger instance enabled for the DEBUG level?
*
* @return True if this Logger is enabled for level DEBUG, false otherwise.
*/
public boolean isDebugEnabled() {
return logger.isDebugEnabled();
}
/**
* Is this logger instance enabled for the INFO level?
*
* @return True if this Logger is enabled for the INFO level, false otherwise.
*/
public boolean isInfoEnabled() {
return logger.isInfoEnabled();
}
/**
* Is this logger instance enabled for the WARN level?
*
* @return True if this Logger is enabled for the WARN level, false otherwise.
*/
public boolean isWarnEnabled() {
return logger.isEnabledFor(Level.WARN);
}
/**
* Is this logger instance enabled for level ERROR?
*
* @return True if this Logger is enabled for level ERROR, false otherwise.
*/
public boolean isErrorEnabled() {
return logger.isEnabledFor(Level.ERROR);
}
@Override
public void log(Marker marker, String callerFQCN, int level, String msg, Object[] arguments, Throwable t) {
Level log4jLevel = toLog4jLevel(level);
NormalizedParameters np = NormalizedParameters.normalize(msg, arguments, t);
String formattedMessage = MessageFormatter.basicArrayFormat(np.getMessage(), np.getArguments());
logger.log(callerFQCN, log4jLevel, formattedMessage, np.getThrowable());
}
@Override
protected void handleNormalizedLoggingCall(org.slf4j.event.Level level, Marker marker, String msg, Object[] arguments, Throwable throwable) {
Level log4jLevel = toLog4jLevel(level.toInt());
String formattedMessage = MessageFormatter.basicArrayFormat(msg, arguments);
logger.log(getFullyQualifiedCallerName(), log4jLevel, formattedMessage, throwable);
}
/**
* Called by {@link SubstituteLogger} or by {@link LoggingEventBuilder} instances
* @param event
*/
public void log(LoggingEvent event) {
Level log4jLevel = toLog4jLevel(event.getLevel().toInt());
if (!logger.isEnabledFor(log4jLevel))
return;
org.apache.log4j.spi.LoggingEvent log4jevent = event2Log4jEvent(event, log4jLevel);
logger.callAppenders(log4jevent);
}
private org.apache.log4j.spi.LoggingEvent event2Log4jEvent(LoggingEvent event, Level log4jLevel) {
String formattedMessage = MessageFormatter.basicArrayFormat(event.getMessage(), event.getArgumentArray());
LocationInfo locationInfo = null;
String fqcn = null;
if (event instanceof SubstituteLoggingEvent) {
locationInfo = new LocationInfo(NA_SUBST, NA_SUBST, NA_SUBST, "0");
fqcn = FQCN_SUBSTITUE;
} else {
fqcn = FQCN_FLUENT;
}
ThrowableInformation ti = null;
Throwable t = event.getThrowable();
if (t != null)
ti = new ThrowableInformation(t);
if(event instanceof DefaultLoggingEvent) {
DefaultLoggingEvent defaultLoggingEvent = (DefaultLoggingEvent) event;
defaultLoggingEvent.setTimeStamp(System.currentTimeMillis());
}
org.apache.log4j.spi.LoggingEvent log4jEvent = new org.apache.log4j.spi.LoggingEvent(fqcn, logger, event.getTimeStamp(), log4jLevel, formattedMessage,
event.getThreadName(), ti, null, locationInfo, null);
return log4jEvent;
}
private Level toLog4jLevel(int slf4jLevelInt) {
Level log4jLevel;
switch (slf4jLevelInt) {
case LocationAwareLogger.TRACE_INT:
log4jLevel = Level.TRACE;
break;
case LocationAwareLogger.DEBUG_INT:
log4jLevel = Level.DEBUG;
break;
case LocationAwareLogger.INFO_INT:
log4jLevel = Level.INFO;
break;
case LocationAwareLogger.WARN_INT:
log4jLevel = Level.WARN;
break;
case LocationAwareLogger.ERROR_INT:
log4jLevel = Level.ERROR;
break;
default:
throw new IllegalStateException("Level number " + slf4jLevelInt + " is not recognized.");
}
return log4jLevel;
}
@Override
protected String getFullyQualifiedCallerName() {
return FQCN_NOMINAL;
}
}
|
import textio.TextIO;
import java.math.BigInteger;
public class BigIntegerThreeN {
public static void main (String [] args) {
System.out.println ("This program will print out the 3N + 1 sequence for starting values that you specify using BigInteger objects.");
System.out.println ();
String line;
BigInteger number;
while (true) {
System.out.println ("Please enter a positive number or enter a blank line if you no longer wish to continue.");
line = TextIO.getln ();
if (line.length () == 0) {
break;
}
try {
number = new BigInteger (line);
print3NSequence (number);
}
catch (NumberFormatException e) {
System.out.println (e.getMessage ());
System.out.println ("Invalid response. Try again.");
System.out.println ();
continue;
}
}
}
private static void print3NSequence (BigInteger n) {
if (n.signum () != 1) {
throw new NumberFormatException ("Initial number must be positive.");
}
int count;
int onLine;
BigInteger m;
count = 1;
onLine = 1;
m = new BigInteger ("1");
System.out.println ("The 3N + 1 sequence starting from " + n.toString ());
System.out.println ();
System.out.print (n.toString ());
System.out.print (' ');
while (! (n.equals (m) && n.signum () == 1)) {
n = nextN (n);
count ++;
if (onLine == 5) {
System.out.println ();
onLine = 0;
}
System.out.print (n.toString ());
System.out.print (' ');
onLine ++;
}
System.out.println ();
System.out.println ();
System.out.println ("There were " + count + " terms in the sequence.");
}
private static BigInteger nextN (BigInteger currentN) {
BigInteger m;
BigInteger o;
if (currentN.testBit (0)) {
m = new BigInteger ("3");
o = new BigInteger ("1");
currentN = currentN.multiply (m);
currentN = currentN.add (o);
return currentN;
}
else {
m = new BigInteger ("2");
return currentN.divide (m);
}
}
}
|
/*---------------------------------------------------------------------------*/
/**
* @(#)$Id: FileOperater.java 9495 2014-09-28 10:24:19Z shiyongping $
* @(#) Implementation file of class Area.
* @author SearchNLP
* (c) SUNTEC CORPORATION 2013
* All Rights Reserved.
*/
package hhc.common.utils.io;
import org.apache.log4j.Logger;
import java.io.*;
public class FileOperater {
static Logger logger = Logger.getLogger(FileOperater.class);
public static void readline(String path, Class<? extends Operations> doThing, Object object)
throws InstantiationException, IllegalAccessException, InterruptedException {
BufferedReader br;
try {
br = new BufferedReader(new InputStreamReader(new FileInputStream(path), "utf-8"));
// int count = 0;
for (String line = br.readLine(); line != null; line = br.readLine()) {
// System.out.println(count++);
// System.out.print(count++);
doThing.newInstance().operation(line, object);
// Thread.sleep(500);
// System.out.println(line);
}
br.close();
} catch (Exception e) {
// TODO Auto-generated catch block
logger.error(e.getMessage());
}
}
public static void readline(String path, MyCallBack object) {
BufferedReader br;
try {
br = new BufferedReader(new InputStreamReader(new FileInputStream(path), "utf-8"));
// int count = 0;
for (String line = br.readLine(); line != null; line = br.readLine()) {
// System.out.println(count++);
// System.out.print(count++);
object.operation(line, null);
// Thread.sleep(500);
// System.out.println(line);
}
br.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
logger.error(e.getMessage());
}
}
/**
*
* @param
* @param object
*/
public static void readline(InputStream inputStream, MyCallBack object) {
BufferedReader br;
try {
br = new BufferedReader(new InputStreamReader(inputStream, "utf-8"));
// int count = 0;
for (String line = br.readLine(); line != null; line = br.readLine()) {
// System.out.println(count++);
// System.out.print(count++);
object.operation(line, null);
// Thread.sleep(500);
// System.out.println(line);
}
br.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
logger.error(e.getMessage());
}
}
public static void readline(String path, MyCallBack object,String encode) {
BufferedReader br;
try {
br = new BufferedReader(new InputStreamReader(new FileInputStream(path), encode));
// int count = 0;
for (String line = br.readLine(); line != null; line = br.readLine()) {
// System.out.println(count++);
// System.out.print(count++);
object.operation(line, null);
// Thread.sleep(500);
// System.out.println(line);
}
br.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
logger.error(e.getMessage());
}
}
public static String read(String path) throws IOException {
File file = new File(path);
if (!file.exists() || file.isDirectory())
throw new FileNotFoundException();
FileInputStream fis = new FileInputStream(file);
byte[] buf = new byte[1024];
StringBuffer sb = new StringBuffer();
while ((fis.read(buf)) != -1) {
sb.append(new String(buf));
buf = new byte[1024];// 閲嶆柊鐢熸垚锛岄伩鍏嶅拰涓婃璇诲彇鐨勬暟鎹�??��澶�
}
fis.close();
return sb.toString();
}
public static void write(final String path, String print) {
try {
File file = new File(path);
if (!file.exists())
file.createNewFile();
FileOutputStream out = new FileOutputStream(file, true);
StringBuffer sb = new StringBuffer();
sb.append(print + "\n");
out.write(sb.toString().getBytes("utf-8"));
// }
out.close();
} catch (Exception e) {
logger.error(e.getMessage());
}
}
public static void writeStrings(final String path, String[] prints) {
try {
File file = new File(path);
if (!file.exists())
file.createNewFile();
FileOutputStream out = new FileOutputStream(file, true);
StringBuffer sb = new StringBuffer();
for(String print:prints){
sb.append(print + "\n");
}
out.write(sb.toString().getBytes("utf-8"));
// }
out.close();
} catch (Exception e) {
logger.error(e.getMessage());
}
}
/**
*
* @param
*/
public static String readFile(InputStream inputStream) {
StringBuilder sb=new StringBuilder();
BufferedReader br;
try {
br = new BufferedReader(new InputStreamReader(inputStream, "utf-8"));
// int count = 0;
for (String line = br.readLine(); line != null; line = br.readLine()) {
// System.out.println(count++);
// System.out.print(count++);
sb.append(line);
// Thread.sleep(500);
// System.out.println(line);
}
br.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
logger.error(e.getMessage());
}
return sb.toString();
}
}
|
package Concurrency;/**
* Created by pc on 2018/2/26.
*/
/**
* describe:
*
* @author xxx
* @date4 {YEAR}/02/26
*/
|
/*
* 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 tictactoe_game;
import java.awt.Color;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.HeadlessException;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.Observer;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
/**
*
* @author vongenae
*/
public class TicTacToeFrame extends JFrame {
private final JLabel messageLabel = new JLabel("");
private static char PlayerMark;
private static char OpponentMark;
private Color PlayerColor;
private Color OpponentColor;
private Square[] board = new Square[9];
private Square currentSquare;
private int currentPosition;
private final Font LabelFont = new Font("Arial", Font.BOLD, 16);
private final ArrayList<Observer> o = new ArrayList<>();
public TicTacToeFrame() throws HeadlessException {
super("Tic Tac Toe");
// Layout GUI
messageLabel.setBackground(Color.lightGray);
getContentPane().add(messageLabel, "South");
JPanel boardPanel = new JPanel();
boardPanel.setBackground(Color.black);
boardPanel.setLayout(new GridLayout(3, 3, 2, 2));
for (int i = 0; i < board.length; i++) {
final int j = i;
board[i] = new Square();
board[i].addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
// current square is the square clicked by the mouse
currentSquare = board[j];
currentPosition = j;
for(Observer ob : o) {
ob.update(null, null);
}
}
});
boardPanel.add(board[i]);
}
getContentPane().add(boardPanel, "Center");
}
protected boolean wantsToPlayAgain() {
int response = JOptionPane.showConfirmDialog(this,
"Want to play again?",
"Tic Tac Toe is Fun",
JOptionPane.YES_NO_OPTION);
return response == JOptionPane.YES_OPTION;
}
protected void setMark(char mark) {
PlayerMark = mark == 'X' ? 'X' : 'O';
PlayerColor = mark == 'X' ? Color.RED : Color.BLUE;
OpponentMark = mark == 'X' ? 'O' : 'X';
OpponentColor = mark == 'X' ? Color.BLUE : Color.RED;
setTitle("Tic Tac Toe - Player " + mark);
}
protected void validMove() {
messageLabel.setText("Valid move --> PLEASE WAIT");
currentSquare.label.setFont(LabelFont);
currentSquare.label.setForeground(PlayerColor);
currentSquare.label.setText(Character.toString(PlayerMark));
}
protected void opponentMoved(int loc) {
messageLabel.setText("Opponent moved --> YOUR TURN");
board[loc].label.setFont(LabelFont);
board[loc].label.setForeground(OpponentColor);
board[loc].label.setText(Character.toString(OpponentMark));
}
protected boolean end(String tekst) {
messageLabel.setText(tekst);
boolean nog = wantsToPlayAgain();
clear();
return nog;
}
protected void bericht(String tekst) {
messageLabel.setText(tekst);
}
protected int getPosition() {
return currentPosition;
}
protected void addListener(Observer ob) {
o.add(ob);
}
private void clear() {
for(Square s : board) {
s.label.setText("");
}
}
/**
* Graphical square in the client window. Each square is a white panel
* containing an X or O.
*/
class Square extends JPanel {
JLabel label = new JLabel();
public Square() {
setBackground(Color.WHITE);
add(label);
}
}
}
|
package gui;
import gui.PlayerDisplayInfo.PlayerType;
import java.awt.Color;
import java.util.List;
import state.Initialisable;
import state.PlayerVisualisable;
import state.Point;
import state.Visualisable;
import state.Initialisable.TicketType;
public class PlayerInformationReader {
private PlayerVisualisable playerVisualisable;
private Visualisable visualisable;
boolean isVisualisable = false;
boolean isPlayerVisualisable = false;
public PlayerInformationReader(PlayerVisualisable pv, Visualisable v)
{
if(pv != null)
{
playerVisualisable = pv;
isPlayerVisualisable = true;
}
if(v != null)
{
visualisable = v;
isVisualisable = true;
}
}
private boolean isMrX(int id)
{
for(int val : playerVisualisable.getMrXIdList())
{
if(val == id) return true;
}
return false;
}
private void isPlayerStillInGame(PlayerDisplayInfo player)
{
if(player.getType() == PlayerType.MrX)
{
player.setActive(true);
return;
}
List<Integer> detectiveIds = playerVisualisable.getDetectiveIdList();
for(int id : detectiveIds)
{
if(player.getId() == id)
{
player.setActive(true);
return;
}
}
player.setActive(false);
}
private void setPlayerVisualisableInfo(PlayerDisplayInfo player, boolean drawMrX)
{
// get the playerVisualisable Information
int id = player.getId();
int location = 0;
if(player.getType() == PlayerType.Detective ||
drawMrX)
{
location = playerVisualisable.getActualPosition(id);
}
else
{
location = playerVisualisable.getNodeId(id);
//System.out.println("Getting Hidden " + location);
}
player.setLocation(location);
player.getPlayerLocationHistory().add(location);
//player.setLocation(location);
//player.getPlayerLocationHistory().add(location);
/*
//if(player.getType() == PlayerType.Detective ||
// drawMrX || visualisable.isVisible(id))
{
player.setLocation(location);
}
else
{
player.setLocation(playerVisualisable.getNodeId(id));
}
*/
if(isMrX(id)) player.setType(PlayerType.MrX);
else player.setType(PlayerType.Detective);
int currentPlayer = visualisable.getNextPlayerToMove();
if(currentPlayer == id) player.setCurrentTurn(true);
else player.setCurrentTurn(false);
Point playerPosition = new Point(
playerVisualisable.getLocationX(player.getLocation()),
playerVisualisable.getLocationY(player.getLocation()));
//if(player.getType() == PlayerType.Detective ||
// drawMrX || visualisable.isVisible(id))
//{
player.setPlayerPosition(playerPosition);
//}
isPlayerStillInGame(player);
}
private void setPlayerColours(PlayerDisplayInfo player)
{
player.setPlayerTextColour(PlayerDisplayInfo.LIGHT_TEXT);
// check for mr x
if(isMrX(player.getId()))
{
player.setPlayerColour(PlayerDisplayInfo.MR_X_COLOUR);
player.setPreviousColour(new Color(150,150,150));
player.setType(PlayerType.MrX);
}
else
{
int colourIndex = 0;
List<Integer> detectiveIds = playerVisualisable.getDetectiveIdList();
for(int i = 0; i < detectiveIds.size(); i++)
{
if(player.getId() == detectiveIds.get(i)) colourIndex = i;
}
player.setPlayerColour(PlayerDisplayInfo.PLAYER_COLOURS[colourIndex]);
if(colourIndex == 0) player.setPreviousColour(new Color(150,150,150));
else player.setPreviousColour(PlayerDisplayInfo.PLAYER_COLOURS[colourIndex-1]);
}
}
private void setVisualisableInfo(PlayerDisplayInfo player)
{
int id = player.getId();
int taxi = visualisable.getNumberOfTickets(TicketType.Taxi, id);
int bus = visualisable.getNumberOfTickets(TicketType.Bus, id);
int underground = visualisable.getNumberOfTickets(TicketType.Underground, id);
int secret = visualisable.getNumberOfTickets(TicketType.SecretMove, id);
int doubleMove = visualisable.getNumberOfTickets(TicketType.DoubleMove, id);
// assign the tickets
player.setTickets(Initialisable.TicketType.Taxi, taxi);
player.setTickets(Initialisable.TicketType.Bus, bus);
player.setTickets(Initialisable.TicketType.Underground, underground);
player.setTickets(Initialisable.TicketType.SecretMove, secret);
player.setTickets(Initialisable.TicketType.DoubleMove, doubleMove);
player.setTicketHistory(visualisable.getMoveList(id));
player.getPlayerVisualisableHistory().add(visualisable.isVisible(id));
}
public PlayerDisplayInfo createPlayerDisplayInfo(int playerId, boolean drawMrX)
{
PlayerDisplayInfo playerDisplay = new PlayerDisplayInfo();
playerDisplay.setId(playerId);
// get the relevant information from the visualisable interface
if(!isPlayerVisualisable) return playerDisplay;
setPlayerVisualisableInfo(playerDisplay, drawMrX);
setPlayerColours(playerDisplay);
// check if we have the visualisable interface
if(!isVisualisable) return playerDisplay;
setVisualisableInfo(playerDisplay);
return playerDisplay;
}
public void updatePlayerDisplayInfo(PlayerDisplayInfo player, boolean drawMrX)
{
if(isPlayerVisualisable) setPlayerVisualisableInfo(player, drawMrX);
if(isVisualisable) setVisualisableInfo(player);
}
}
|
package problemInfo;
public enum ProblemType {
GEO,
PLANAR
}
|
/*
* Copyright 2015, Alexandre Lewandowski
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.sonar.plugins.oauth2.provider;
import org.apache.oltu.oauth2.client.request.OAuthClientRequest;
import org.apache.oltu.oauth2.common.OAuthProviderType;
import org.sonar.api.config.Settings;
public class GoogleProvider extends GenericProvider {
public static String SCOPE = "https://www.googleapis.com/auth/userinfo.profile";
public GoogleProvider() {
super(OAuthProviderType.GOOGLE);
}
@Override
public OAuthClientRequest.AuthenticationRequestBuilder createRedirectRequestBuilder(Settings settings) {
OAuthClientRequest.AuthenticationRequestBuilder redirectRequestBuilder;
redirectRequestBuilder = super.createRedirectRequestBuilder(settings);
redirectRequestBuilder.setParameter("response_type", "code");
redirectRequestBuilder.setParameter("scope", SCOPE);
redirectRequestBuilder.setParameter("access_type", "offline");
return redirectRequestBuilder;
}
}
|
package com.onplan.dao;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.onplan.adviser.strategy.system.IntegrationTestStrategy;
import com.onplan.domain.configuration.StrategyConfiguration;
import com.onplan.persistence.StrategyConfigurationDao;
import com.onplan.util.TestingConstants;
import java.util.List;
import static com.onplan.adviser.StrategyConfigurationFactory.createStrategyConfiguration;
public class TestingStrategyConfigurationDao
extends TestingAbstractDao<StrategyConfiguration> implements StrategyConfigurationDao {
public TestingStrategyConfigurationDao() throws Exception {
removeAll();
insertAll(getSampleStrategiesConfiguration());
}
@Override
public List<StrategyConfiguration> getSampleStrategiesConfiguration() {
return ImmutableList.of(
createStrategyConfiguration(
IntegrationTestStrategy.class,
TestingConstants.INSTRUMENT_EURUSD_ID,
ImmutableMap.of()),
createStrategyConfiguration(
IntegrationTestStrategy.class,
TestingConstants.INSTRUMENT_AUDUSD_ID,
ImmutableMap.of()),
createStrategyConfiguration(
IntegrationTestStrategy.class,
TestingConstants.INSTRUMENT_DAX_ID,
ImmutableMap.of()),
createStrategyConfiguration(
IntegrationTestStrategy.class,
TestingConstants.INSTRUMENT_FTSE100_ID,
ImmutableMap.of()));
}
}
|
package cn.gzcc.feibao.repository;
import cn.gzcc.feibao.entity.Order_A;
import org.springframework.data.repository.CrudRepository;
public interface AorderRepository extends CrudRepository<Order_A,Integer> {
}
|
/*
* Copyright 1999-2012 Alibaba Group.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.cobar.jdbc;
import java.sql.Connection;
import java.sql.DriverPropertyInfo;
import java.sql.SQLException;
import java.util.Properties;
import com.mysql.jdbc.NonRegisteringDriver;
import java.sql.SQLFeatureNotSupportedException;
import java.util.logging.Logger;
/**
* 在使用集群时提供负载均衡的功能,其他情况和MySQLDriver一样。
*
* <pre>
* 使用方法:
* Class.forName("com.alibaba.cobar.jdbc.Driver");
* String url = "jdbc:cobar://host:port/dbname?user=xxx&password=xxx";
* ...
* </pre>
*
* @author xianmao.hexm 2012-4-27
*/
public class Driver extends NonRegisteringDriver implements java.sql.Driver {
public static final String VERSION = "1.0.0";
/**
* Register ourselves with the DriverManager
*/
static {
try {
java.sql.DriverManager.registerDriver(new Driver());
} catch (SQLException E) {
throw new RuntimeException("Can't register driver!");
}
}
/**
* Construct a new driver and register it with DriverManager
*
* @throws SQLException if a database error occurs.
*/
public Driver() throws SQLException {
// Required for Class.forName().newInstance()
}
@Override
public Connection connect(String url, Properties info) throws SQLException {
return super.connect(UrlProvider.getUrl(url, info), info);
}
@Override
public boolean acceptsURL(String url) throws SQLException {
return super.acceptsURL(UrlProvider.getMySQLUrl(url));
}
@Override
public DriverPropertyInfo[] getPropertyInfo(String url, Properties info) throws SQLException {
return super.getPropertyInfo(UrlProvider.getMySQLUrl(url), info);
}
public Logger getParentLogger() throws SQLFeatureNotSupportedException {
throw new SQLFeatureNotSupportedException("Not supported yet.");
}
}
|
package com.smxknife.kafka.demo02;
import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import java.time.Duration;
import java.util.Collections;
import java.util.Properties;
import java.util.concurrent.BlockingDeque;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.TimeUnit;
/**
* @author smxknife
* 2020/8/31
*/
public class _02_3_Consumer_Mock_LostData {
public static void main(String[] args) throws InterruptedException {
Properties properties = KafkaProperties.consumer();
properties.put(ConsumerConfig.INTERCEPTOR_CLASSES_CONFIG, _02_2_ConsumerInterceptor.class.getName());
KafkaConsumer<String, String> consumer = new KafkaConsumer<String, String>(properties);
String topic = "offset-test";
consumer.subscribe(Collections.singleton(topic));
BlockingDeque<String> deque = new LinkedBlockingDeque<>();
new Thread(() -> {
// 该线程模拟业务消费数据,消费速度较慢,消费者不断循环poll操作,拉取了大量的数据,每次执行poll都会进行自动提交offset操作
// offset已经提交了,但是拉取的数据还没有被真正的业务系统消费,如果业务系统出现异常,那么下次重启时就会从新的offset的位置拉取数据
// 业务系统还没来的及处理的数据(deque中的数据)因为重启而丢失了,那么就造成了数据丢失
while(true) {
if (deque.size() > 20) {
throw new RuntimeException("too large exception");
}
try {
String message = deque.take();
System.out.println(" ** handle message " + message);
TimeUnit.SECONDS.sleep(3);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
while (true) {
ConsumerRecords<String, String> consumerRecords = consumer.poll(Duration.ofSeconds(1));
for (ConsumerRecord<String, String> consumerRecord : consumerRecords) {
System.out.println("-- receive record : value = " + consumerRecord.value() + " | offset = " + consumerRecord.offset());
deque.offer(consumerRecord.value());
}
}
}
}
|
package com.zitrojjdev.sampleapp1;
import android.os.Parcel;
import android.os.Parcelable;
public class Book implements Parcelable {
private String name, author, imageURL, description;
private int pages;
public Book(String name, String author, String imageURL, String description, int pages) {
this.name = name;
this.author = author;
this.imageURL = imageURL;
this.description = description;
this.pages = pages;
}
protected Book(Parcel in) {
name = in.readString();
author = in.readString();
imageURL = in.readString();
description = in.readString();
pages = in.readInt();
}
public static final Creator<Book> CREATOR = new Creator<Book>() {
@Override
public Book createFromParcel(Parcel in) {
return new Book(in);
}
@Override
public Book[] newArray(int size) {
return new Book[size];
}
};
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getImageURL() {
return imageURL;
}
public void setImageURL(String imageURL) {
this.imageURL = imageURL;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public int getPages() {
return pages;
}
public void setPages(int pages) {
this.pages = pages;
}
@Override
public String toString() {
return "Book{" +
"name='" + name + '\'' +
", author='" + author + '\'' +
", imageURL='" + imageURL + '\'' +
", description='" + description + '\'' +
", pages=" + pages +
'}';
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel parcel, int i) {
parcel.writeString(name);
parcel.writeString(author);
parcel.writeString(imageURL);
parcel.writeString(description);
parcel.writeInt(pages);
}
}
|
package pe.gob.sunarp.trabajoseguroapp;
import pe.gob.sunarp.trabajoseguroapp.view.IncidenciaMainView;
public class TrabajoSeguroApp {
public static void main(String[] args) {
IncidenciaMainView.main(args);
}
}
|
package com.rishi.baldawa.iq;
import org.junit.Test;
import static org.junit.Assert.*;
public class StringToIntegerTest {
@Test
public void myAtoi() throws Exception {
assertEquals(new StringToInteger().myAtoi("25"), 25);
assertEquals(new StringToInteger().myAtoi("-25"), -25);
assertEquals(new StringToInteger().myAtoi("0"), 0);
assertEquals(new StringToInteger().myAtoi("00000"), 0);
assertEquals(new StringToInteger().myAtoi("00025"), 25);
assertEquals(new StringToInteger().myAtoi("-00025"), -25);
assertEquals(new StringToInteger().myAtoi("1"), 1);
assertEquals(new StringToInteger().myAtoi("+1"), 1);
assertEquals(new StringToInteger().myAtoi(" 010"), 10);
assertEquals(new StringToInteger().myAtoi(" -0012a42"), -12);
assertEquals(new StringToInteger().myAtoi("2147483648"), 2147483647);
assertEquals(new StringToInteger().myAtoi("9223372036854775809"), 2147483647);
}
}
|
package com.baizhi.service;
import java.util.List;
import com.baizhi.entity.Book;
import com.baizhi.entity.Category;
public interface CategoryService {
public List<Category> selectAll();
public List<Book> selectFirstBook(Integer pageindex,Integer pagesize,Integer category_id );
public List<Book> selectSecondBook(Integer pageindex,Integer pagesize,Integer category_id );
public Category selectFirstCategory(Integer id);
public Category selectSecondCategory(Integer id);
public Integer selectFirstCount(Integer id);
public Integer selectSecondCount(Integer id);
public Integer SelectFatherId(Integer id);
public String selectcategory_name(Integer id);
}
|
package com.kite.common.utils.date;
import java.util.Calendar;
import java.util.Date;
public class DateUtils {
/**
* 将日期转换为YYYYMM
* @param date
* @return
*/
public static String transformDateToYYYYMM(Date date) {
Calendar calendar=Calendar.getInstance();
calendar.setTime(date);
String y = String.valueOf(calendar.get(Calendar.YEAR));
String m = String.valueOf(calendar.get(Calendar.MONTH) + 1);
String ym = y + m;
return ym;
}
/**
* 将对当前整形转换为十万位,带零
* @param i
* @return
*/
public static String transformNumString(int i) {
String iStr = String.valueOf(i);
if(iStr.length() == 1) {
return "000000" + iStr;
}
else if(iStr.length() == 2) {
return "00000" + iStr;
}
else if(iStr.length() == 3) {
return "0000" + iStr;
}
else if(iStr.length() == 4) {
return "000" + iStr;
}
else if(iStr.length() == 5) {
return "00" + iStr;
}
else if(iStr.length() == 6) {
return "0" + iStr;
}
else if(iStr.length() == 7) {
return iStr;
}
else {
return iStr;
}
}
/**
* 将对当前整形转换为千位,带零
* @param i
* @return
*/
public static String transformThousandBitNumString(int i) {
String iStr = String.valueOf(i);
if(iStr.length() == 1) {
return "000" + iStr;
}
else if(iStr.length() == 2) {
return "00" + iStr;
}
else if(iStr.length() == 3) {
return "0" + iStr;
}
else if(iStr.length() == 4) {
return iStr;
}
else {
return iStr;
}
}
/**
* 获取指定日期当天开始时间
* @param date
* @return
*/
public static Date getTimesmorning(Date date) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.MILLISECOND, 0);
return cal.getTime();
}
/**
* 获取指定日期当天结束时间
* @param date
* @return
*/
public static Date getTimesevening(Date date) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.set(Calendar.HOUR_OF_DAY, 23);
cal.set(Calendar.SECOND, 59);
cal.set(Calendar.MINUTE, 59);
cal.set(Calendar.MILLISECOND, 0);
return cal.getTime();
}
/**
* 指定日期当月第一天
* @param date
* @return
*/
public static Date firstDateInMonth(Date date) {
Calendar cal = Calendar.getInstance();
cal = Calendar.getInstance();
cal.add(Calendar.MONTH, 0);
cal.set(Calendar.DAY_OF_MONTH, 1);
Date firstday = cal.getTime();
return firstday;
}
/**
* 指定日期当月最后一天
* @param date
* @return
*/
public static Date lastDateInMonth(Date date) {
Calendar cal = Calendar.getInstance();
cal = Calendar.getInstance();
cal.add(Calendar.MONTH, 1);
cal.set(Calendar.DAY_OF_MONTH, 0);
Date lastday = cal.getTime();
return lastday;
}
}
|
package net.liuzd.spring.boot.v2;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.Resource;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import io.reactivex.Flowable;
import io.reactivex.Maybe;
import io.reactivex.Single;
import net.liuzd.spring.boot.v2.domain.Person;
import net.liuzd.spring.boot.v2.repository.RxJava2PersonRepository;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
public class RxJava2PersonRepositoryTest {
private final Logger logger = LoggerFactory.getLogger(getClass());
@Resource
private RxJava2PersonRepository rxJava2PersonRepository;
@Test
public void testAdd() throws Exception {
// 创建多个User,并验证User总数
int size = 20;
List<Person> pps = new ArrayList<>();
for (int i = 1; i <= size; i++) {
Person p = new Person("liu" + i, "felix" + i, 22 + i);
pps.add(p);
}
//
Flowable<Person> f = rxJava2PersonRepository.saveAll(pps);
this.logger.info(f.blockingFirst().toString());
}
@Test
public void testDel() throws Exception {
// 删除一个Person
Person p = new Person("liu", "zidong", 22);
Single<Person> s = rxJava2PersonRepository.save(p);
Person person = rxJava2PersonRepository.findById(s.blockingGet().getId()).blockingGet();
this.logger.info(person.toString());
rxJava2PersonRepository.delete(person);
}
@Test
public void testFindMore() throws Exception {
//
Flowable<Person> f_person = rxJava2PersonRepository.findByLastname("felix");
this.logger.info("Flowable>" + f_person.toString());
Maybe<Person> m_person = rxJava2PersonRepository.findByFirstnameAndLastname("liu0", "felix0");
this.logger.info("Maybe>" + m_person.toString());
//
Single<String> lastname = null;
f_person = rxJava2PersonRepository.findByLastname(lastname);
this.logger.info("Single>" + f_person.toString());
//
m_person = rxJava2PersonRepository.findByFirstnameAndLastname("liu", "felix0");
this.logger.info("Flux>" + m_person.toString());
//
f_person = rxJava2PersonRepository.findWithTailableCursorBy();
this.logger.info("Flux>findWithTailableCursorBy>" + m_person.toString());
}
}
|
package calculadora.operadoresmatrizes;
import calculadora.colecoes.Matriz;
import calculadora.excecoes.MatrizInvalidaException;
public class SolucaoSistemasLineares<T> extends EliminacaoGaussiana<T> {
@Override
public Matriz<T> calcula(Matriz<T> m) {
avalia(m);
m = m.clona();
aplicaEliminacaoGaussiana(m, false);
return copiaColuna(m, m.getTamanhoColunas() - 1);
}
protected Matriz<T> copiaColuna(Matriz<T> m, int c) {
Matriz<T> mRes = m.getNovaInstancia(m.getTamanhoLinhas(), 1);
for (int i = 0; i < m.getTamanhoLinhas(); i++) {
mRes.setElemento(i, 0, m.getElemento(i, c));
}
return mRes;
}
protected void avalia(Matriz<T> m) {
if (m.getTamanhoLinhas() == m.getTamanhoColunas())
throw new MatrizInvalidaException(
"A matriz não pode ser quadrada, é preciso ter uma coluna para os resultados.");
else if (m.getTamanhoLinhas() > m.getTamanhoColunas())
throw new MatrizInvalidaException(
"Há mais linhas do que colunas na matriz.");
}
}
|
package resources;
import common.Responses;
import common.Student;
import common.Subject;
import services.StudentService;
import javax.ws.rs.*;
import javax.ws.rs.core.*;
import java.util.Set;
@Consumes({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public class StudentResource {
private StudentService studentService = StudentService.getInstance();
@Context
UriInfo uriInfo;
@GET
public Student getStudent(@PathParam("index") int index) {
return studentService.getStudent(index);
}
@PUT
public Response updateStudent(@PathParam("index") int index, Student student) {
studentService.updateStudent(index, student);
return Responses.ok();
}
@DELETE
public Response deleteSubject(@PathParam("index") int index) {
Student student = studentService.getStudent(index);
if (student == null)
return Responses.notFound();
studentService.deleteStudent(student);
return Responses.noContent();
}
@Path("/marks")
public MarksResource getStudentMarks(@PathParam("index") int index) {
return new MarksResource(index);
}
@Path("/subjects")
public Response getStudentSubjects(@PathParam("index") int index) {
Student student = studentService.getStudent(index);
if (student == null)
return Responses.notFound();
return Responses.ok(new GenericEntity<Set<Subject>>(studentService.getStudentSubjects(student)) {
});
}
}
|
package com.team.vo;
import java.util.List;
import lombok.Data;
@Data
public class ProjectMember {
private int projectNo;
private String email;
public ProjectMember() {};
public ProjectMember(int projectNo, String email) {
this.projectNo = projectNo;
this.email = email;
}
}
|
package gerenciador.matricula;
public class EstadoMensalidade {
/**
* Método construtor. Você deve utiliza-lo para criar o registro de um novo
* author .
*
* @param estadoMensalidadeId id da EstadoMensalidade
* @param estadoMensalidadeNome nome da EstadoMensalidade
* @author
*/
private int estadoMensalidadeId;
private String estadoMensalidadeNome;
// Declaração do construtor da classe estadoMensalidade//
public EstadoMensalidade(int estadoMensalidadeId,
String estadoMensalidadeNome) {
this.estadoMensalidadeId = estadoMensalidadeId;
this.estadoMensalidadeNome = estadoMensalidadeNome;
}
// Declaração do construtor da classe estadoMensalidade//
public EstadoMensalidade(String estadoMensalidadeNome) {
this.estadoMensalidadeNome = estadoMensalidadeNome;
}
//Declaração do método estadoMensalidadeId
public void setEstadoMensalidadeId(int estadoMensalidadeId) {
this.estadoMensalidadeId = estadoMensalidadeId;
// Altera a variavel estadoMensalidadeId da classe EstadoMensalidade
//para o parametro passado
}
//Declaração do método setEstadoMensalidadeNome
public void setEstadoMensalidadeNome(String estadoMensalidadeNome) {
this.estadoMensalidadeNome = estadoMensalidadeNome;
// Altera a variavel estadoMensalidadeNome da classe EstadoMensalidade para o parametro passado
}
//Declaração do método getEstadoMensalidadeId
public int getEstadoMensalidadeId() {
return estadoMensalidadeId;
//retorna o Valor da Variavel estadoMensalidadeId
}
//Declaração do método getEstadoMensalidadeNome
public String getEstadoMensalidadeNome() {
return estadoMensalidadeNome;
//retorna o Valor da Variavel estadoMensalidadeNome
}
}
|
public class Barang {
public String kode;
public String namaBarang;
public int hargaDasar;
public float diskon;
public int hitungHargaJual() {
int hargaJual = (int) (hargaDasar - ((diskon * hargaDasar) / 100));
return hargaJual;
}
public void tampilData() {
System.out.println("\n-----------------------------------");
System.out.println("Kode barang : " + kode);
System.out.println("Nama barang : " + namaBarang);
System.out.println("Harga dasar : Rp. " + hargaDasar);
System.out.println("Diskon : " + diskon + "%");
}
}
|
package 문제풀이;
import java.util.Scanner;
public class 문제 {
public static void main(String[] args) {
int[] num = new int[5];
Scanner sc = new Scanner(System.in);
for (int i = 0; i < num.length; i++) {
System.out.println("숫자 입력>>");
num[i] = sc.nextInt();
}
System.out.println(num[0] + num[2]);
sc.close(); // 스트림(연결통로)를 닫아라
}
}
|
package com.hk.xia.mybatisplus.generator.code.dao;
import com.hk.xia.mybatisplus.generator.code.pojo.Employee;
/**
* 通用 Mapper 代码生成器
*
* @author mapper-generator
*/
public interface EmployeeDao extends tk.mybatis.mapper.common.Mapper<Employee> {
}
|
package controllers;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class ShowProductPicServlet extends HttpServlet{
public void doGet(HttpServletRequest request,HttpServletResponse response)throws IOException,ServletException{
String picPath = "WEB-INF/uploads/"+request.getParameter("product_pic");
InputStream is = getServletContext().getResourceAsStream(picPath);
OutputStream os = response.getOutputStream();
byte[] arr = new byte[1024];
int count = 0;
while((count=is.read(arr))!=-1){
os.write(arr);
}
os.flush();
os.close();
}
}
|
package com.canfield010.mygame.mapsquare.uppermapsquare;
public interface Door {
public boolean open();
public boolean isOpen = false;
public boolean close();
}
|
package com.data.rhis2;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.location.Location;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.SimpleAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.TimePicker;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import Common.Connection;
import Common.Global;
/**
* Created by Nisan on 5/1/2016.
*/
public class Delivfpi extends Activity {
boolean netwoekAvailable = false;
Location currentLocation;
double currentLatitude, currentLongitude;
Location currentLocationNet;
double currentLatitudeNet, currentLongitudeNet;
//Disabled Back/Home key
//--------------------------------------------------------------------------------------------------
@Override
public boolean onKeyDown(int iKeyCode, KeyEvent event) {
if (iKeyCode == KeyEvent.KEYCODE_BACK || iKeyCode == KeyEvent.KEYCODE_HOME) {
return false;
} else {
return true;
}
}
//Top menu
//--------------------------------------------------------------------------------------------------
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.mnuclose, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
AlertDialog.Builder adb = new AlertDialog.Builder(Delivfpi.this);
switch (item.getItemId()) {
case R.id.menuClose:
adb.setTitle("Close");
adb.setMessage("আপনি কি এই ফর্ম থেকে বের হতে চান?");
adb.setNegativeButton("না", null);
adb.setPositiveButton("হ্যাঁ", new AlertDialog.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
finish();
Intent f2 = new Intent(getApplicationContext(), MemberListFPI.class);
startActivity(f2);
}
});
adb.show();
return true;
}
return false;
}
String VariableID;
private int hour;
private int minute;
private int mDay;
private int mMonth;
private int mYear;
static final int DATE_DIALOG = 1;
static final int TIME_DIALOG = 2;
Connection C;
Global g;
SimpleAdapter dataAdapter;
ArrayList<HashMap<String, String>> dataList = new ArrayList<HashMap<String, String>>();
private String TableName;
private String TableNameFPI;
private String TableNamePNC;
private String ChildTableName;
private String MemberTable;
LinearLayout seclbldelete;
LinearLayout secDiv;
TextView VlblDiv;
EditText txtDiv;
LinearLayout secDist;
TextView VlblDist;
EditText txtDist;
LinearLayout secUpz;
TextView VlblUpz;
EditText txtUpz;
LinearLayout secUN;
TextView VlblUN;
EditText txtUN;
LinearLayout secMouza;
TextView VlblMouza;
EditText txtMouza;
LinearLayout secVill;
TextView VlblVill;
EditText txtVill;
LinearLayout seclblH;
TextView lblHlblH;
TextView lblHealthID;
TextView txtHealthID;
LinearLayout secSl;
TextView txtSLNo;
TextView VlblSLNo;
TextView VlblSNo;
TextView txtSNo;
TextView txtElCONo;
LinearLayout secName;
TextView VlblName;
TextView txtName;
LinearLayout secHusName;
TextView VlblHusName;
TextView txtHusName;
TextView txtAgeYrHus;
LinearLayout secAge;
TextView VlblAge;
TextView txtAge;
LinearLayout secOutcome;
TextView VlblOutcome;
RadioGroup rdogrpOutcome;
RadioButton rdoOutcomeLB;
RadioButton rdoOutcomeSB;
RadioButton rdoOutcomeAbo;
LinearLayout secLivebirth;
TextView VlblLivebirth;
EditText txtLivebirthNum1;
EditText txtLivebirthNum2;
LinearLayout secOutcomeDT;
TextView VlblOutcomeDT;
EditText dtpOutcomeDT;
ImageButton btnOutcomeDT;
ImageButton btnDOPNCCh1;
LinearLayout secBPlace;
TextView VlblBPlace;
Spinner spnBPlace;
LinearLayout secBAtten;
TextView VlblBAtten;
Spinner spnBAtten;
LinearLayout secBType;
TextView VlblBType;
RadioGroup rdogrpBType;
RadioButton rdoBTypeNor;
RadioButton rdoBTypeSeg;
LinearLayout secMiso;
TextView VlblMiso;
RadioGroup rdogrpMiso;
RadioButton rdoMisoYes;
RadioButton rdoMisoNo;
LinearLayout seclivebirth;
//..............FPI.............
RadioGroup rdogrpbirthdeathabortion1;
RadioButton rdobirthdeathabortion1;
RadioButton rdobirthdeathabortion2;
RadioGroup rdogrpOutcomeDT;
RadioButton rdoOutcomeDT1;
RadioButton rdoOutcomeDT2;
RadioGroup rdogrpBPlace;
RadioButton rdoBPlace1;
RadioButton rdoBPlace2;
RadioGroup rdogrpBAtten;
RadioButton rdoBAtten1;
RadioButton rdoBAtten2;
RadioGroup rdogrpBType1;
RadioButton rdoBType11;
RadioButton rdoBType12;
RadioGroup rdogrpMiso1;
RadioButton rdoMiso11;
RadioButton rdoMiso12;
Button cmdSave;
ImageButton cmdSavePNC;
String StartTime;
TextView VlblChildList;
CheckBox chklivebirth;
CheckBox chkdeathbirth;
CheckBox chkabortion;
EditText dtpDOPNCCh1;
String sqlnew = "";
String sqlupdate = "";
String pregnancyNo;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try {
setContentView(R.layout.delivfpi);
C = new Connection(this);
g = Global.getInstance();
StartTime = g.CurrentTime24();
TableName = "delivery";
TableNameFPI = "deliveryFPI";
TableNamePNC = "pncServiceMother";
ChildTableName = "newBorn";
MemberTable = "Member";
ELCOProfile e = new ELCOProfile();
e.ELCOProfile(this, g.getGeneratedId());
//call from elco
if (g.getCallFrom().equals("elco")) {
pregnancyNo = e.CurrentPregNumber(this, g.getGeneratedId());
}
//call from register
else if (g.getCallFrom().equals("regis")) {
pregnancyNo = e.LastPregNumber(this, g.getGeneratedId());
} else if (g.getCallFrom().equals("1")) {
pregnancyNo = e.LastPregNumber(this, g.getGeneratedId());
}
/*
seclblH = (LinearLayout) findViewById(R.id.seclblH);
lblHlblH = (TextView) findViewById(R.id.lblHlblH);
lblHealthID = (TextView) findViewById(R.id.lblHealthID);
txtHealthID = (TextView) findViewById(R.id.txtHealthID);
secSl = (LinearLayout) findViewById(R.id.secSl);
VlblSNo = (TextView) findViewById(R.id.VlblSNo);
txtSNo = (TextView) findViewById(R.id.txtSNo);
VlblSLNo = (TextView) findViewById(R.id.VlblSNo);
txtSLNo = (TextView) findViewById(R.id.txtSLNo);
txtSLNo.setText(GetCountSLNoNumber());
VlblSNo.setVisibility(View.GONE);
txtSNo.setVisibility(View.GONE);
txtAge = (TextView) findViewById(R.id.txtAge);
secName = (LinearLayout) findViewById(R.id.secName);
VlblName = (TextView) findViewById(R.id.VlblName);
txtName = (TextView) findViewById(R.id.txtName);
secHusName = (LinearLayout) findViewById(R.id.secHusName);
VlblHusName = (TextView) findViewById(R.id.VlblHusName);
txtHusName = (TextView) findViewById(R.id.txtHusName);
txtAgeYrHus = (TextView) findViewById(R.id.txtAgeYrHus);
*/
seclivebirth = (LinearLayout) findViewById(R.id.seclivebirth);
secOutcome = (LinearLayout) findViewById(R.id.secOutcome);
txtLivebirthNum1 = (EditText) findViewById(R.id.txtLivebirthNum1);
txtLivebirthNum1.setEnabled(false);
txtLivebirthNum2 = (EditText) findViewById(R.id.txtLivebirthNum2);
txtLivebirthNum2.setEnabled(false);
VlblChildList = (TextView) findViewById(R.id.VlblChildList);
chklivebirth = (CheckBox) findViewById(R.id.chklivebirth);
chkdeathbirth = (CheckBox) findViewById(R.id.chkdeathbirth);
chkabortion = (CheckBox) findViewById(R.id.chkabortion);
//dtpDOPNCCh1 = (EditText) findViewById(R.id.dtpDOPNCCh1);
//((LinearLayout)findViewById(R.id.secPNCCh12)).setVisibility(View.GONE);
chklivebirth.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if (b) {
txtLivebirthNum1.setEnabled(true);
//txtLivebirthNum1.setText("1");
VlblOutcomeDT.setText("প্রসবের তারিখ");
chkabortion.setChecked(!b);
} else {
txtLivebirthNum1.setText("");
txtLivebirthNum1.setEnabled(false);
}
}
});
chkdeathbirth.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if (b) {
txtLivebirthNum2.setEnabled(true);
//txtLivebirthNum2.setText("1");
VlblOutcomeDT.setText("প্রসবের তারিখ");
chkabortion.setChecked(!b);
} else {
txtLivebirthNum2.setEnabled(false);
txtLivebirthNum2.setText("");
}
}
});
chkabortion.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if (b) {
txtLivebirthNum1.setEnabled(false);
txtLivebirthNum2.setEnabled(false);
VlblOutcomeDT.setText("গর্ভপাতের তারিখ");
chklivebirth.setChecked(!b);
chkdeathbirth.setChecked(!b);
VlblBAtten.setText("কে গর্ভপাত করিয়েছেন");
VlblBPlace.setText("কোথায় গর্ভপাত হয়েছে");
secBType.setVisibility(View.GONE);
rdogrpBType.clearCheck();
secMiso.setVisibility(View.GONE);
rdogrpMiso.clearCheck();
} else {
secBType.setVisibility(View.VISIBLE);
secMiso.setVisibility(View.VISIBLE);
VlblBAtten.setText("কে প্রসব করিয়েছেন");
VlblBPlace.setText("কোথায় প্রসব হয়েছে");
}
}
});
secOutcomeDT = (LinearLayout) findViewById(R.id.secOutcomeDT);
VlblOutcomeDT = (TextView) findViewById(R.id.VlblOutcomeDT);
dtpOutcomeDT = (EditText) findViewById(R.id.dtpOutcomeDT);
btnOutcomeDT = (ImageButton) findViewById(R.id.btnOutcomeDT);
btnDOPNCCh1 = (ImageButton) findViewById(R.id.btnDOPNCCh1);
secBPlace = (LinearLayout) findViewById(R.id.secBPlace);
VlblBPlace = (TextView) findViewById(R.id.VlblBPlace);
spnBPlace = (Spinner) findViewById(R.id.spnBPlace);
secBType = (LinearLayout) findViewById(R.id.secBType);
VlblBType = (TextView) findViewById(R.id.VlblBType);
rdogrpBType = (RadioGroup) findViewById(R.id.rdogrpBType);
rdoBTypeNor = (RadioButton) findViewById(R.id.rdoBTypeNor);
rdoBTypeSeg = (RadioButton) findViewById(R.id.rdoBTypeSeg);
secMiso = (LinearLayout) findViewById(R.id.secMiso);
VlblMiso = (TextView) findViewById(R.id.VlblMiso);
rdogrpMiso = (RadioGroup) findViewById(R.id.rdogrpMiso);
rdoMisoYes = (RadioButton) findViewById(R.id.rdoMisoYes);
rdoMisoNo = (RadioButton) findViewById(R.id.rdoMisoNo);
List<String> listBPlace = new ArrayList<String>();
listBPlace.add("");
listBPlace.add("01-বাড়িতে");
listBPlace.add("02-উপজেলা স্বাস্থ্য কমপ্লেক্স");
listBPlace.add("03-ইউনিয়ন স্বাস্থ্য ও পরিবার কল্যাণ কেন্দ্র");
listBPlace.add("04-মা ও শিশু কল্যাণ কেন্দ্র");
listBPlace.add("05-জেলা সদর ও অন্যান্য \n সরকারী হাসপাতাল");
listBPlace.add("06-এনজিও ক্লিনিক বা হাসপাতাল");
listBPlace.add("07-প্রাইভেট ক্লিনিক বা হাসপাতাল");
listBPlace.add("77-অন্যান্য");
ArrayAdapter<String> BPlace = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, listBPlace);
spnBPlace.setAdapter(BPlace);
spnBPlace.setEnabled(false);
spnBPlace.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
String val = (spnBPlace.getSelectedItemPosition() == 0 ? "" : Global.Left(spnBPlace.getSelectedItem().toString(), 2));
if (val.length() > 0) {
if (val.equalsIgnoreCase("01")) {
rdoBTypeNor.setChecked(true);
rdoBTypeSeg.setEnabled(false);
spnBAtten.setAdapter(null);
FillSpinner(true);
} else {
rdogrpBType.clearCheck();
rdoBTypeNor.setEnabled(true);
rdoBTypeSeg.setEnabled(true);
spnBAtten.setAdapter(null);
FillSpinner(false);
//Select ' 'as attendantCode union
}
}
}
@Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
secBAtten = (LinearLayout) findViewById(R.id.secBAtten);
VlblBAtten = (TextView) findViewById(R.id.VlblBAtten);
spnBAtten = (Spinner) findViewById(R.id.spnBAtten);
//..............FPI.............
rdogrpbirthdeathabortion1 = (RadioGroup) findViewById(R.id.rdogrpbirthdeathabortion1);
rdobirthdeathabortion1 = (RadioButton) findViewById(R.id.rdobirthdeathabortion1);
rdobirthdeathabortion2 = (RadioButton) findViewById(R.id.rdobirthdeathabortion2);
rdogrpOutcomeDT = (RadioGroup) findViewById(R.id.rdogrpOutcomeDT);
rdoOutcomeDT1 = (RadioButton) findViewById(R.id.rdoOutcomeDT1);
rdoOutcomeDT2 = (RadioButton) findViewById(R.id.rdoOutcomeDT2);
rdogrpBPlace = (RadioGroup) findViewById(R.id.rdogrpBPlace);
rdoBPlace1 = (RadioButton) findViewById(R.id.rdoBPlace1);
rdoBPlace2 = (RadioButton) findViewById(R.id.rdoBPlace2);
rdogrpBAtten = (RadioGroup) findViewById(R.id.rdogrpBAtten);
rdoBAtten1 = (RadioButton) findViewById(R.id.rdoBAtten1);
rdoBAtten2 = (RadioButton) findViewById(R.id.rdoBAtten2);
rdogrpBType1 = (RadioGroup) findViewById(R.id.rdogrpBType1);
rdoBType11 = (RadioButton) findViewById(R.id.rdoBType11);
rdoBType12 = (RadioButton) findViewById(R.id.rdoBType12);
rdogrpMiso1 = (RadioGroup) findViewById(R.id.rdogrpMiso1);
rdoMiso11 = (RadioButton) findViewById(R.id.rdoMiso11);
rdoMiso12 = (RadioButton) findViewById(R.id.rdoMiso12);
// spnBAtten.setEnabled(false);
/*List<String> listBAtten = new ArrayList<String>();
listBAtten.add("");
listBAtten.add("01-ডাক্তার");
listBAtten.add("02-নার্স");
listBAtten.add("03-স্যাকমো");
listBAtten.add("04-এফ ডব্লিউ ভি");
listBAtten.add("05-প্যারামেডিক্স");
listBAtten.add("06-সি এস বি এ");
listBAtten.add("77-অন্যান্য");
ArrayAdapter<String> BAtten = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, listBAtten);
spnBAtten.setAdapter(BAtten);*/
cmdSave = (Button) findViewById(R.id.cmdSave);
//cmdSavePNC = (ImageButton) findViewById(R.id.cmdSavePNC);
//((LinearLayout)findViewById(R.id.List)).setVisibility(View.GONE);
/*btnDOPNCCh1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
VariableID = "btnDOPNCCh1";
showDialog(DATE_DIALOG);
}
});
*/
DeliverySearch(g.getGeneratedId(), pregnancyNo);
FPIDataSearch(g.getGeneratedId(), pregnancyNo);
//DisplayChildlist();
btnOutcomeDT.setEnabled(false);
btnOutcomeDT.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
VariableID = "btnOutcomeDT";
showDialog(DATE_DIALOG);
}
});
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
cmdSave.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
DataSave();
/*if (txtLivebirthNum1.getText().length() == 0 & txtLivebirthNum2.getText().length() == 0 & chkabortion.isChecked() == false) {
Connection.MessageBox(Deliv.this, "প্রসবের ফলাফল সিলেক্ট করুন।");
return;
}*/
/* if (txtLivebirthNum1.getText().length() == 0 & txtLivebirthNum2.getText().length() == 0 & chkabortion.isChecked() == false) {
Connection.MessageBox(Delivfpi.this, "প্রসবের ফলাফল কি ।");
return;
}
if(chklivebirth.isChecked() || chkdeathbirth.isChecked() || chkabortion.isChecked())
{
String NumberofBirth1 = "";
String NumberofBirth2 = "";
NumberofBirth1 = txtLivebirthNum1.getText().toString();
NumberofBirth2 = txtLivebirthNum2.getText().toString();
if(NumberofBirth1.length()==0)
{
NumberofBirth1 = "0";
}
if(NumberofBirth2.length()==0)
{
NumberofBirth2 = "0";
}
if(Integer.parseInt(NumberofBirth1)>2 || Integer.parseInt(NumberofBirth2)>2)
{
AlertDialog.Builder adb = new AlertDialog.Builder(Delivfpi.this);
adb.setTitle("নিশ্চিত করুন");
adb.setMessage("আপনি কি শিশুর সংখ্যা নিশ্চিত[হাঁ/না]?");
adb.setNegativeButton("No", new AlertDialog.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
adb.setPositiveButton("Yes", new AlertDialog.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
DataSave();
}
});
adb.show();
}
else
{
DataSave();
}
}*/
}
});
/*
DisplayPNCVisits();
cmdSavePNC.setOnClickListener(new View.OnClickListener(){
public void onClick(View v)
{
DataSavePNC();
DisplayPNCVisits();
}
//test
});
*/
} catch (Exception e) {
Connection.MessageBox(Delivfpi.this, e.getMessage());
return;
}
}
private void DataSave() {
try {
String SQL = "";
String AG = "";
// String ServiceId = serviceID(pregnancyNo);
if (!rdobirthdeathabortion1.isChecked() & !rdobirthdeathabortion2.isChecked() & seclivebirth.isShown()) {
Connection.MessageBox(Delivfpi.this, "প্রসব ফলাফল যাচাই করুন ।");
rdobirthdeathabortion1.requestFocus();
return;
} else if (!rdoOutcomeDT1.isChecked() & !rdoOutcomeDT2.isChecked() & secOutcomeDT.isShown()) {
Connection.MessageBox(Delivfpi.this, "প্রসব/গর্ভপাতের তারিখ যাচাই করুন ।");
rdoOutcomeDT1.requestFocus();
return;
} else if (!rdoBPlace1.isChecked() & !rdoBPlace2.isChecked() & secBPlace.isShown()) {
Connection.MessageBox(Delivfpi.this, "কোথায় প্রসব হয়েছে যাচাই করুন ।");
rdoBPlace1.requestFocus();
return;
} else if (!rdoBAtten1.isChecked() & !rdoBAtten2.isChecked() & secBAtten.isShown()) {
Connection.MessageBox(Delivfpi.this, "কে প্রসব করিয়েছেন যাচাই করুন ।");
rdoBAtten1.requestFocus();
return;
} else if (!rdoBType11.isChecked() & !rdoBType12.isChecked() & secBAtten.isShown()) {
Connection.MessageBox(Delivfpi.this, "প্রসবের ধরণ যাচাই করুন ।");
rdoBType11.requestFocus();
return;
} else if (!rdoMiso11.isChecked() & !rdoMiso12.isChecked() & secMiso.isShown()) {
Connection.MessageBox(Delivfpi.this, "মিসোপ্রোস্টোল বড়ি পেয়েছেন কিনা যাচাই করুন ।");
rdoMiso11.requestFocus();
return;
}
if (!C.Existence("Select healthId from " + TableNameFPI + " Where healthId='" + g.getGeneratedId() + "' AND pregNo ='" + pregnancyNo + "'")) {
SQL = "Insert into " + TableNameFPI + "(HealthID,pregNo,providerId,systemEntryDate,Upload)Values('" + g.getGeneratedId() + "','" + pregnancyNo + "','" + g.getProvCode() + "','" + Global.DateTimeNowYMDHMS() + "','2')";
C.Save(SQL);
}
SQL = "Update " + TableNameFPI + " Set Upload='2',";
if (chklivebirth.isChecked() == true) {
SQL += "liveBirth = '" + (rdobirthdeathabortion1.isChecked() ? "1" : (rdobirthdeathabortion2.isChecked() ? "2" : "")) + "',";
} else if (chkdeathbirth.isChecked() == true) {
SQL += "stillBirth = '" + (rdobirthdeathabortion1.isChecked() ? "1" : (rdobirthdeathabortion2.isChecked() ? "2" : "")) + "',";
} else if (chkabortion.isChecked() == true) {
SQL += "abortion = '" + (rdobirthdeathabortion1.isChecked() ? "1" : (rdobirthdeathabortion2.isChecked() ? "2" : "")) + "',";
}
SQL += "outcomeDate = '" + (rdoOutcomeDT1.isChecked() ? "1" : (rdoOutcomeDT1.isChecked() ? "2" : "")) + "',";
SQL += "outcomePlace = '" + (rdoBPlace1.isChecked() ? "1" : (rdoBPlace2.isChecked() ? "2" : "")) + "',";
SQL += "attendantDesignation = '" + (rdoBAtten1.isChecked() ? "1" : (rdoBAtten2.isChecked() ? "2" : "")) + "',";
SQL += "outcomeType = '" + (rdoBType11.isChecked() ? "1" : (rdoBType11.isChecked() ? "2" : "")) + "',";
SQL += "misoprostol = '" + (rdoMiso11.isChecked() ? "1" : (rdoMiso12.isChecked() ? "2" : "")) + "'";
SQL += " Where healthId='" + g.getGeneratedId() + "' AND pregNo ='" + pregnancyNo + "'";
C.Save(SQL);
Connection.MessageBox(Delivfpi.this, "তথ্য সফলভাবে সংরক্ষণ হয়েছে।");
//finish();
} catch (Exception e) {
Connection.MessageBox(Delivfpi.this, e.getMessage());
return;
}
}
private void FPIDataSearch(String generatedId, String pregnancyNo) {
try {
RadioButton rb;
String SQL1 = "";
SQL1 = "Select ifnull(healthId,'') as HealthID,ifnull(liveBirth,'') as liveBirth,ifnull(stillBirth,'') as stillBirth,ifnull(abortion,'') as abortion,ifnull(outcomeDate,'') as outcomeDate,ifnull(outcomePlace,'') as outcomePlace,ifnull(attendantDesignation,'') as attendantDesignation,ifnull(outcomeType,'') as outcomeType,ifnull(misoprostol,'') as misoprostol\n" +
"from deliveryFPI FPI Where HealthID='" + generatedId + "' AND pregNo ='" + pregnancyNo + "'";
/*SQL += " ifnull(NameBang,'') as NameBang, ifnull(Rth,'') as Rth, ifnull(HaveNID,'') as HaveNID, ifnull(NID,'') as NID, ifnull(NIDStatus,'') as NIDStatus, ifnull(HaveBR,'') as HaveBR, ifnull(BRID,'') as BRID, ifnull(BRIDStatus,'') as BRIDStatus, ifnull(MobileNo1,'') as MobileNo1,";
SQL += " ifnull(MobileNo2,'') as MobileNo2, ifnull(MobileYN,'')as MobileYN, ifnull(DOB,'') as DOB, ifnull(cast(((julianday(date('now'))-julianday(DOB))/365)as int),'') as Age, ifnull(DOBSource,'') as DOBSource, ifnull(BPlace,'') as BPlace, ifnull(FNo,'') as FNo, ifnull(Father,'') as Father, ifnull(FDontKnow,'')as FDontKnow, ifnull(MNo,'') as MNo, ifnull(Mother,'') as Mother,ifnull(MDontKnow,'')as MDontKnow,";
SQL += " ifnull(Sex,'') as Sex, ifnull(MS,'') as MS, ifnull(SPNO1,'') as SPNO1,ifnull(SPNO2,'') as SPNO2,ifnull(SPNO3,'') as SPNO3,ifnull(SPNO4,'') as SPNO4, ifnull(ELCONo,'') as ELCONo, ifnull(ELCODontKnow,'') as ELCODontKnow, ifnull(EDU,'') as EDU, ifnull(Rel,'') as Rel, ifnull(Nationality,'') as Nationality, ifnull(OCP,'') as OCP";*/
//SQL1 += " from MemberFPI Where Dist='"+ Dist +"' and Upz='"+ Upz +"' and UN='"+ UN +"' and Mouza='"+ Mouza +"' and Vill='"+ Vill +"' and HHNo='"+ HHNo +"' and SNo='"+ SNo +"'";
Cursor cur1 = C.ReadData(SQL1);
cur1.moveToFirst();
while (!cur1.isAfterLast()) {
/*for (int i = 0; i < rdogrpNameEng.getChildCount(); i++)
{
rb = (RadioButton)rdogrpNameEng.getChildAt(i);
if (Global.Left(rb.getText().toString(), 1).equalsIgnoreCase(cur1.getString(cur1.getColumnIndex("NameEngStatus"))))
rb.setChecked(true);
else
rb.setChecked(false);
}*/
//-----------FPI Retrived-------------------
if (cur1.getString(cur1.getColumnIndex("liveBirth")).replace("null", "").toString().equalsIgnoreCase("1")) {
rdobirthdeathabortion1.setChecked(true);
} else if (cur1.getString(cur1.getColumnIndex("liveBirth")).replace("null", "").toString().equalsIgnoreCase("2")) {
rdobirthdeathabortion2.setChecked(true);
}
if (cur1.getString(cur1.getColumnIndex("stillBirth")).replace("null", "").toString().equalsIgnoreCase("1")) {
rdobirthdeathabortion1.setChecked(true);
} else if (cur1.getString(cur1.getColumnIndex("stillBirth")).replace("null", "").toString().equalsIgnoreCase("2")) {
rdobirthdeathabortion2.setChecked(true);
}
if (cur1.getString(cur1.getColumnIndex("abortion")).replace("null", "").toString().equalsIgnoreCase("1")) {
rdobirthdeathabortion1.setChecked(true);
} else if (cur1.getString(cur1.getColumnIndex("abortion")).replace("null", "").toString().equalsIgnoreCase("2")) {
rdobirthdeathabortion2.setChecked(true);
}
if (cur1.getString(cur1.getColumnIndex("outcomeDate")).replace("null", "").toString().equalsIgnoreCase("1")) {
rdoOutcomeDT1.setChecked(true);
} else if (cur1.getString(cur1.getColumnIndex("outcomeDate")).replace("null", "").toString().equalsIgnoreCase("2")) {
rdoOutcomeDT2.setChecked(true);
}
if (cur1.getString(cur1.getColumnIndex("outcomePlace")).replace("null", "").toString().equalsIgnoreCase("1")) {
rdoBPlace1.setChecked(true);
} else if (cur1.getString(cur1.getColumnIndex("outcomePlace")).replace("null", "").toString().equalsIgnoreCase("2")) {
rdoBPlace2.setChecked(true);
}
if (cur1.getString(cur1.getColumnIndex("attendantDesignation")).replace("null", "").toString().equalsIgnoreCase("1")) {
rdoBAtten1.setChecked(true);
} else if (cur1.getString(cur1.getColumnIndex("attendantDesignation")).replace("null", "").toString().equalsIgnoreCase("2")) {
rdoBAtten1.setChecked(true);
}
if (cur1.getString(cur1.getColumnIndex("outcomeType")).replace("null", "").toString().equalsIgnoreCase("1")) {
rdoBType11.setChecked(true);
} else if (cur1.getString(cur1.getColumnIndex("outcomeType")).replace("null", "").toString().equalsIgnoreCase("2")) {
rdoBType11.setChecked(true);
}
if (cur1.getString(cur1.getColumnIndex("misoprostol")).replace("null", "").toString().equalsIgnoreCase("1")) {
rdoMiso11.setChecked(true);
} else if (cur1.getString(cur1.getColumnIndex("misoprostol")).replace("null", "").toString().equalsIgnoreCase("2")) {
rdoMiso12.setChecked(true);
}
cur1.moveToNext();
}
cur1.close();
} catch (Exception e) {
Connection.MessageBox(Delivfpi.this, e.getMessage());
return;
}
}
private void FillSpinner(boolean isathome) {
spnBAtten.setAdapter(null);
if (isathome) {
spnBAtten.setAdapter(C.getArrayAdapter("Select ' 'as attendantCode union Select substr('0' ||attendantCode, -2, 2)||'-'||attendantDesig as attendantCode from AttendantDesignation order by attendantCode asc"));
} else {
spnBAtten.setAdapter(C.getArrayAdapter("Select ' 'as attendantCode union Select substr('0' ||attendantCode, -2, 2)||'-'||attendantDesig as attendantCode from AttendantDesignation where substr('0' ||attendantCode, -2, 2) in('01','02','03','04','05','06','77') order by attendantCode asc"));
}
}
private void setDelivery(String DeliveryType) {
}
private void DeliverySearch(String HealthId, String PregNo) {
try {
String SQL = "";
SQL = "Select healthId, pregNo, providerId, outcomePlace, outcomeDate, outcomeType, liveBirth, stillBirth," +
" stillBirthFresh, stillBirthMacerated, misoprostol, abortion , systemEntryDate, modifyDate, attendantDesignation " +
" FROM delivery where HealthId='" + g.getGeneratedId() + "' AND pregNo = '" + PregNo + "'";
Cursor cur = C.ReadData(SQL);
cur.moveToFirst();
while (!cur.isAfterLast()) {
txtLivebirthNum1.setText(cur.getString(cur.getColumnIndex("liveBirth")));
txtLivebirthNum2.setText(cur.getString(cur.getColumnIndex("stillBirth")));
if (!txtLivebirthNum1.getText().toString().equalsIgnoreCase("")) {
chklivebirth.setChecked(true);
}
if (!txtLivebirthNum2.getText().toString().equalsIgnoreCase("")) {
chkdeathbirth.setChecked(true);
}
dtpOutcomeDT.setText(Global.DateConvertDMY(cur.getString(cur.getColumnIndex("outcomeDate"))));
if (cur.getString(cur.getColumnIndex("outcomePlace")).length() >= 1) {
if (cur.getString(cur.getColumnIndex("outcomePlace")).equalsIgnoreCase("01")) {
FillSpinner(true);
if (cur.getString(cur.getColumnIndex("attendantDesignation")).length() >= 2) {
Global.SetSpinnerItem(spnBAtten, cur.getString(cur.getColumnIndex("attendantDesignation")));
} else {
Global.SetSpinnerItem(spnBAtten, cur.getString(cur.getColumnIndex("attendantDesignation")));
}
} else {
FillSpinner(false);
}
Global.SetSpinnerItem(spnBPlace, "0" + cur.getString(cur.getColumnIndex("outcomePlace")));
if (cur.getString(cur.getColumnIndex("attendantDesignation")).length() >= 2) {
Global.SetSpinnerItem(spnBAtten, cur.getString(cur.getColumnIndex("attendantDesignation")));
} else {
Global.SetSpinnerItem(spnBAtten, cur.getString(cur.getColumnIndex("attendantDesignation")));
}
} else {
Global.SetSpinnerItem(spnBPlace, "0" + cur.getString(cur.getColumnIndex("outcomePlace")));
}
/*if(cur.getString(cur.getColumnIndex("attendantDesignation")).length()>=2)
{
Global.SetSpinnerItem(spnBAtten, cur.getString(cur.getColumnIndex("attendantDesignation")));
}
else
{
Global.SetSpinnerItem(spnBAtten, cur.getString(cur.getColumnIndex("attendantDesignation")));
}*/
//Global.SetSpinnerItem(spnBAtten, cur.getString(cur.getColumnIndex("attendantDesignation")));
if (cur.getString(cur.getColumnIndex("outcomeType")).equals("1")) {
rdoBTypeNor.setChecked(true);
secBType.setVisibility(View.VISIBLE);
} else if (cur.getString(cur.getColumnIndex("outcomeType")).equals("2")) {
rdoBTypeSeg.setChecked(true);
secBType.setVisibility(View.VISIBLE);
}
if (cur.getString(cur.getColumnIndex("misoprostol")).equals("1")) {
rdoMisoYes.setChecked(true);
secMiso.setVisibility(View.VISIBLE);
} else if (cur.getString(cur.getColumnIndex("misoprostol")).equals("2")) {
rdoMisoNo.setChecked(true);
secMiso.setVisibility(View.VISIBLE);
}
if (cur.getString(cur.getColumnIndex("abortion")).equals("1")) {
chkabortion.setChecked(true);
secBType.setVisibility(View.GONE);
rdogrpBType.clearCheck();
secMiso.setVisibility(View.GONE);
rdogrpMiso.clearCheck();
}
cur.moveToNext();
}
cur.close();
} catch (Exception e) {
Connection.MessageBox(Delivfpi.this, e.getMessage());
return;
}
}
private boolean validateDeliveryDate() {
String sq = String.format("Select LMP from PregWomen where healthId = '%s' and pregNo = '%s'", g.getGeneratedId(), pregnancyNo);
if (C.Existence(sq)) {
String LmpDate = C.ReturnSingleValue("Select LMP from PregWomen where healthId = '" + g.getGeneratedId() + "' AND pregNo = '" + pregnancyNo + "'");
if (Global.DateDifferenceDays(dtpOutcomeDT.getText().toString(), Global.DateConvertDMY(LmpDate)) < 1) {
return true;
}
}
return false;
}
private boolean validateDeliveryDateAgainstSystemDate() {
if ((Global.DateDifferenceDays(dtpOutcomeDT.getText().toString(), Global.DateNowDMY()) >= 1)) {
return true;
}
return false;
}
private boolean validateLMPDateIsMoreThan24Weeks() {
String sq = String.format("Select LMP from PregWomen where healthId = '%s' and pregNo = '%s'", g.getGeneratedId(), pregnancyNo);
if (C.Existence(sq)) {
String LmpDate = C.ReturnSingleValue("Select LMP from PregWomen where healthId = '" + g.getGeneratedId() + "' AND pregNo = '" + pregnancyNo + "'");
if (Global.DateDifferenceDays(dtpOutcomeDT.getText().toString(), Global.DateConvertDMY(LmpDate)) < 168) {
return true;
}
}
return false;
}
/*private void DataSave() {
try {
if (txtLivebirthNum1.getText().length() == 0 & txtLivebirthNum2.getText().length() == 0 & chkabortion.isChecked() == false) {
Connection.MessageBox(Delivfpi.this, "প্রসবের ফলাফল কি ।");
return;
}
//txtLivebirthNum1
if (dtpOutcomeDT.getText().length() == 0) {
Connection.MessageBox(Delivfpi.this, "ফলাফলের তারিখ কত লিখুন।");
dtpOutcomeDT.requestFocus();
return;
} else if (spnBPlace.getSelectedItemPosition() == 0) {
Connection.MessageBox(Delivfpi.this, "প্রসবের স্থান কোথায় ছিল লিখুন");
spnBPlace.requestFocus();
return;
} else if (spnBAtten.getSelectedItemPosition() == 0) {
Connection.MessageBox(Delivfpi.this, "কে প্রসব করিয়েছে লিখুন।");
secBAtten.requestFocus();
return;
} else if (!rdoBTypeSeg.isChecked() & !rdoBTypeNor.isChecked() & secBType.isShown()) {
Connection.MessageBox(Delivfpi.this, "প্রসবের ধরণ কি ছিল লিখুন।");
rdoBTypeSeg.requestFocus();
return;
} else if (!rdoMisoYes.isChecked() & !rdoMisoNo.isChecked() & secMiso.isShown()) {
Connection.MessageBox(Delivfpi.this, "মিসোপ্রোস্টল বড়ি খেয়েছে কি না লিখুন");
rdoMisoYes.requestFocus();
return;
}
if(chklivebirth.isChecked()) {
if (validateLMPDateIsMoreThan24Weeks()) {
Connection.MessageBox(Delivfpi.this, "প্রসব/গর্ভপাত, শেষ মাসিকের তারিখ হতে ২৪ সপ্তাহ এর বেশি হবে");
return;
}
}
if(validateDeliveryDate())
{
Connection.MessageBox(Delivfpi.this, "প্রসব/গর্ভপাত, শেষ মাসিকের তারিখ হতে বেশি হবে");
return;
}
if(validateDeliveryDateAgainstSystemDate())
{
Connection.MessageBox(Delivfpi.this, "প্রসব/গর্ভপাত, আজকের তারিখ হতে বেশি হবে");
return;
}
String SQL = "";
//String sq = String.format("Select healthId, pregNo from PregWomen where healthId = '%s' and pregNo = '%s'", g.getGeneratedId(),pregnancyNo);
String sqdel = String.format("Select healthId, pregNo from delivery where healthId = '%s' and pregNo = '%s'", g.getGeneratedId(), pregnancyNo);
String VisitNo=VisitNumber(g.getGeneratedId());
String NumberofBirth1 = "";
String NumberofBirth2 = "";
String NumberofBirth3 = "";
NumberofBirth1 = txtLivebirthNum1.getText().toString();
NumberofBirth2 = txtLivebirthNum2.getText().toString();
if (chkabortion.isChecked()) {
NumberofBirth3 = "1";
if(!C.Existence("Select healthid from elcoVisit Where healthid='"+ g.getGeneratedId() +"' and Visit='"+ VisitNo +"'"))// and currStatus = '"+ Global.Left(spnMethod.getSelectedItem().toString(), 2) +"'
{
String sqlnew1="";
sqlnew1 = "Insert into elcoVisit(healthId,providerId,visit,systemEntryDate,modifyDate,pregNo)Values(";
sqlnew1 += "'" + g.getGeneratedId() + "',";
sqlnew1 += "'" + g.getProvCode() + "',";
sqlnew1 += "'" + VisitNo + "',";
sqlnew1 += "'" + Global.DateTimeNowYMDHMS() + "',";
sqlnew1 += "'" + Global.DateTimeNowYMDHMS() + "',";
sqlnew1 += "'" + pregnancyNo + "')";
C.Save(sqlnew1);
}
String sqlupdate1="";
sqlupdate1 = "Update elcoVisit Set pregNo = '" + pregnancyNo + "' , ";
sqlupdate1 += "vDate = '" + Global.DateConvertYMD(dtpOutcomeDT.getText().toString()) + "',";//Global.DateTimeNowYMDHMS()
sqlupdate1 += "visitStatus = '1',";
sqlupdate1 += "currStatus = '14',";
sqlupdate1 += "newOld = '',";
sqlupdate1 += "mDate = '',";
sqlupdate1 += "sSource = '',";
sqlupdate1 += "qty = '',";
sqlupdate1 += "unit = '',";
sqlupdate1 += "brand = '',";
sqlupdate1 += "referPlace = '',";
sqlupdate1 += "validity = '',";
sqlupdate1 += "dayMonYear = '',";
sqlupdate1 += "MRDate = '',";
sqlupdate1 += "syrinsQty = ''";
sqlupdate1 += " Where HealthID='" + g.getGeneratedId() + "' and Visit='" + VisitNo + "'";
C.Save(sqlupdate1);
} else {
NumberofBirth3 = "0";
}
if(!C.Existence(sqdel))
{
//Delivery Information
SQL = "Insert into " + TableName + "(healthId,pregNo,providerId,outcomePlace,outcomeDate,outcomeType,attendantDesignation,liveBirth,stillBirth," +
"abortion, systemEntryDate, upload, misoprostol )Values" +
"('" + g.getGeneratedId() + "','" + pregnancyNo + "','" + g.getProvCode() + "'" +
",'" + (spnBPlace.getSelectedItemPosition() == 0 ? "" : Integer.parseInt(Global.Left(spnBPlace.getSelectedItem().toString(), 2))) + "'" +
",'" + Global.DateConvertYMD(dtpOutcomeDT.getText().toString()) + "'" +
",'" + ((rdoBTypeNor.isChecked() ? "1" : "2")) + "'" +
",'" + (spnBAtten.getSelectedItemPosition() == 0 ? "" : Global.Left(spnBAtten.getSelectedItem().toString(), 2)) + "'" +
",'" + NumberofBirth1 + "'," +
"'" + NumberofBirth2 + "'," +
"'" + NumberofBirth3 + "'," +
"'" + Global.DateTimeNowYMDHMS() + "','2'," +
"'" + ((rdoMisoYes.isChecked() ? "1" : "2")) + "')";
C.Save(SQL);
//Child Information
//((LinearLayout)findViewById(R.id.secChildList)).setVisibility(View.VISIBLE);
int ChildNo = 0;
//String ChildHealthId=HealthIdNO();
//childHealthId
//,'" + ChildHealthId + "'
//Live Birth
if (!NumberofBirth1.equalsIgnoreCase("")) {
if (Integer.parseInt(NumberofBirth1) > 0) {
for (int i = 0; i < Integer.parseInt(NumberofBirth1); i++) {
AddChildToPRS();
ChildNo+=1;
SQL = "Insert into " + ChildTableName + "(healthId,pregNo,childNo,providerId,systemEntryDate,upload, outcomePlace," +
"outcomeDate," +
"outcomeTime," +
"outcomeType)Values" +
"('" + g.getGeneratedId() + "','" + pregnancyNo + "','" + String.valueOf(ChildNo) + "','" + g.getProvCode() + "'" +
",'" + Global.DateTimeNowYMDHMS() + "','2','"
+ (spnBPlace.getSelectedItemPosition() == 0 ? "" : Integer.parseInt(Global.Left(spnBPlace.getSelectedItem().toString(), 2))) + "','"
+ Global.DateConvertYMD(dtpOutcomeDT.getText().toString()) + "','" + Global.DateTimeNowYMDHMS() + "','" + ((rdoBTypeNor.isChecked() ? "1" : "2")) + "'" +")";
C.Save(SQL);
}
if(!C.Existence("Select healthid from elcoVisit Where healthid='"+ g.getGeneratedId() +"' and Visit='"+ VisitNo +"'"))// and currStatus = '"+ Global.Left(spnMethod.getSelectedItem().toString(), 2) +"'
{
String sqlnew1="";
sqlnew1 = "Insert into elcoVisit(healthId,providerId,visit,systemEntryDate,modifyDate, pregNo)Values(";
sqlnew1 += "'" + g.getGeneratedId() + "',";
sqlnew1 += "'" + g.getProvCode() + "',";
sqlnew1 += "'" + VisitNo + "',";
sqlnew1 += "'" + Global.DateTimeNowYMDHMS() + "',";
sqlnew1 += "'" + Global.DateTimeNowYMDHMS() + "',";
sqlnew1 += "'" + pregnancyNo + "')";
C.Save(sqlnew1);
}
String sqlupdate1="";
sqlupdate1 = "Update elcoVisit Set pregNo = '" + pregnancyNo + "',";
sqlupdate1 += "vDate = '" + Global.DateConvertYMD(dtpOutcomeDT.getText().toString()) + "',";//Global.DateTimeNowYMDHMS()
sqlupdate1 += "visitStatus = '1',";
sqlupdate1 += "currStatus = '13',";
sqlupdate1 += "newOld = '',";
sqlupdate1 += "mDate = '',";
sqlupdate1 += "sSource = '',";
sqlupdate1 += "qty = '',";
sqlupdate1 += "unit = '',";
sqlupdate1 += "brand = '',";
sqlupdate1 += "referPlace = '',";
sqlupdate1 += "validity = '',";
sqlupdate1 += "dayMonYear = '',";
sqlupdate1 += "MRDate = '',";
sqlupdate1 += "syrinsQty = ''";
sqlupdate1 += " Where HealthID='" + g.getGeneratedId() + "' and Visit='" + VisitNo + "'";
C.Save(sqlupdate1);
}
}
//Still Birth
if (!NumberofBirth2.equalsIgnoreCase("")) {
if (Integer.parseInt(NumberofBirth2) > 0) {
for (int i = 0; i < Integer.parseInt(NumberofBirth2); i++) {
//AddChildToPRS();
//String ChildNo=NewbornChildNo(txtHealthID.getText().toString());
SQL = "Insert into " + ChildTableName + "(healthId,pregNo,childNo,providerId,systemEntryDate,upload, outcomePlace," +
"outcomeDate," +
"outcomeTime," +
"outcomeType)Values" +
"('" + g.getGeneratedId() + "','" + pregnancyNo + "','" + String.valueOf(ChildNo + 1) + "','" + g.getProvCode() + "'" + //String.valueOf(i + 1)
",'" + Global.DateTimeNowYMDHMS() + "','2','"
+ (spnBPlace.getSelectedItemPosition() == 0 ? "" : Integer.parseInt(Global.Left(spnBPlace.getSelectedItem().toString(), 2))) + "','"
+ Global.DateConvertYMD(dtpOutcomeDT.getText().toString()) + "','" + Global.DateTimeNowYMDHMS() + "','" + ((rdoBTypeNor.isChecked() ? "1" : "2")) + "'" +")";
C.Save(SQL);
}
}
}
}
else
{
SQL = "Update " + TableName + " set upload='2'," +
"outcomePlace = '" + (spnBPlace.getSelectedItemPosition() == 0 ? "" : Integer.parseInt(Global.Left(spnBPlace.getSelectedItem().toString(), 2))) + "'," +
"outcomeDate = '" + Global.DateConvertYMD(dtpOutcomeDT.getText().toString()) + "'," +
"outcomeType = '" + ((rdoBTypeNor.isChecked() ? "1" : "2")) + "'," +
"attendantDesignation = '" + (spnBAtten.getSelectedItemPosition() == 0 ? "" : Global.Left(spnBAtten.getSelectedItem().toString(), 2)) + "'," +
"liveBirth = '" + NumberofBirth1 + "'," +
"stillBirth = '" + NumberofBirth2 + "'," +
"abortion = '" + NumberofBirth3 + "'," +
"misoprostol = '" + ((rdoMisoYes.isChecked() ? "1" : "2")) + "'," +
"modifyDate = '" + Global.DateTimeNowYMDHMS() + "'" +
" where healthId='"+ g.getGeneratedId() +"' and PregNo='"+ pregnancyNo +"'";
C.Save(SQL);
//need to update child information
}
Connection.MessageBox(Delivfpi.this, "তথ্য সফলভাবে সংরক্ষণ হয়েছে।");
} catch (Exception e) {
Connection.MessageBox(Delivfpi.this, e.getMessage());
return;
}
}*/
private String VisitNumber(String HealthID) {
String SQL = "";
SQL = "Select (ifnull(max(cast(Visit as int)),0)+1)MaxVisit from ELCOVisit";
SQL += " where healthid='" + HealthID + "'";
String VisitNo = Global.Right(("00" + C.ReturnSingleValue(SQL)), 2);
return VisitNo;
}
/* private void DataSearch(String healthId) {
try {
String SQL = "";
SQL = "Select SNo as SNo, ifnull(HealthID,'') as HealthID, ifnull(NameEng,'') as NameEng,ifnull(Age,'') as Age," +
"(select NameEng from member where ProvCode=(select ProvCode from member Where healthid = '"+healthId +"')" +
"and HHNo=(select HHNo from member Where healthid = '"+healthId +"')" +
"and SNo=(select SPNO1 from member Where healthid= '"+healthId +"'))as HusName," +
"(select Age from member where " +
" ProvCode=(select ProvCode from member Where healthid='"+healthId +"') " +
"and HHNo=(select HHNo from member Where healthid='"+healthId +"') " +
"and SNo=(select SPNO1 from member Where healthid='"+healthId +"'))as HusAge from " +
"Member where healthid='" + healthId +"'";
Cursor cur = C.ReadData(SQL);
cur.moveToFirst();
while (!cur.isAfterLast()) {
txtHealthID.setText(cur.getString(cur.getColumnIndex("HealthID")));
txtSNo.setText(cur.getString(cur.getColumnIndex("SNo")));
txtName.setText(cur.getString(cur.getColumnIndex("NameEng")));
txtAge.setText(cur.getString(cur.getColumnIndex("Age")));
txtHusName.setText(cur.getString(cur.getColumnIndex("HusName")));
txtAgeYrHus.setText(cur.getString(cur.getColumnIndex("HusAge")));
cur.moveToNext();
}
cur.close();
} catch (Exception e) {
// Connection.MessageBox(Deliv.this, e.getMessage());
return;
}
}*/
/* private void ELCONoSearch(String Dist, String Upz, String UN, String Mouza, String Vill, String HHNo, String SNo) {
try {
String SQL = "";
SQL = "select E.ELCONo as ELCONo from ELCO E Where E.healthId='" + g.getGeneratedId() + "'";
Cursor cur = C.ReadData(SQL);
cur.moveToFirst();
while (!cur.isAfterLast()) {
txtElCONo.setText(cur.getString(cur.getColumnIndex("ELCONo")));
cur.moveToNext();
}
cur.close();
} catch (Exception e) {
Connection.MessageBox(Deliv.this, e.getMessage());
return;
}
}
private String PregMaxPGNNo() {
String SQL = "";
String pregNo = "";
SQL = "select ifnull((select '0'||cast(max(pregNo) as string)),0) AS PregNo from PregWomen WHERE healthId=" + g.getGeneratedId();
pregNo = C.ReturnSingleValue(SQL);
return pregNo;
}*/
protected Dialog onCreateDialog(int id) {
final Calendar c = Calendar.getInstance();
hour = c.get(Calendar.HOUR_OF_DAY);
minute = c.get(Calendar.MINUTE);
Integer Y = g.mYear;
Integer M = g.mMonth;
Integer D = g.mDay;
switch (id) {
case DATE_DIALOG:
return new DatePickerDialog(this, mDateSetListener, Y, M - 1, D);
case TIME_DIALOG:
return new TimePickerDialog(this, timePickerListener, hour, minute, false);
}
return null;
}
private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
mYear = year;
mMonth = monthOfYear + 1;
mDay = dayOfMonth;
EditText dtpDate;
dtpDate = (EditText) findViewById(R.id.dtpOutcomeDT);
if (VariableID.equals("btnOutcomeDT")) {
dtpDate = (EditText) findViewById(R.id.dtpOutcomeDT);
}
/*if(VariableID.equals("btnDOPNCCh1"))
{
dtpDate = (EditText)findViewById(R.id.dtpDOPNCCh1);
}*/
dtpDate.setText(new StringBuilder()
.append(Global.Right("00" + mDay, 2)).append("/")
.append(Global.Right("00" + mMonth, 2)).append("/")
.append(mYear));
}
};
private TimePickerDialog.OnTimeSetListener timePickerListener = new TimePickerDialog.OnTimeSetListener() {
public void onTimeSet(TimePicker view, int selectedHour, int selectedMinute) {
hour = selectedHour;
minute = selectedMinute;
EditText tpTime;
}
};
private String NewbornPGNNo(String HealthId) {
String SQL = "";
SQL = "select (ifnull(cast(PregNo as int),0)) as pregNo from newborn ";
SQL += " where HealthId='" + g.getGeneratedId() + "'order by systementrydate asc limit 1";
String PGNNo = Global.Right(("0" + C.ReturnSingleValue(SQL)), 1);
return PGNNo;
}
private String NewbornChildNo(String HealthId) {
String SQL = "";
SQL = "select (ifnull(cast(childNo as int),0))+1 as childNo from newborn ";
SQL += " where HealthId='" + g.getGeneratedId() + "' and PregNo=(Select (ifnull(max(cast(PregNo as int)),0)) as pregNo from newborn where HealthId='" + g.getGeneratedId() + "')order by systementrydate asc limit 1";
String ChildNo = Global.Right(("0" + C.ReturnSingleValue(SQL)), 1);
return ChildNo;
}
private String MaxSNo() {
String SQL = "";
String MaxSNo = "";
SQL += "Select (ifnull(max(cast(SNo as int)),0)+1)MaxSNo from Member ";
SQL += "where dist='" + g.getDistrict() + "' and upz='" + g.getUpazila() + "' and un='" + g.getUnion() + "' and Mouza='" + g.getMouza() + "' and vill='" + g.getVillage() + "' and HHNo='" + g.getHouseholdNo() + "'";
MaxSNo = Global.Right(("00" + C.ReturnSingleValue(SQL)), 2);
return MaxSNo;
}
private String GetCountSLNoNumber() {
String SQL = "select ((cast(Count(*) as int))) as Totalno from delivery";
String Val = String.valueOf(C.ReturnSingleValue(SQL));
if (Val.equalsIgnoreCase("0")) {
return "1";
} else
return Val;
}
private String HealthIdNO() {
String HID = "";
String HealthID = "";
if (C.Existence("select HealthID from HealthidRepository where ifnull(status,'1')='1' order by healthid limit 1")) {
HID = C.ReturnSingleValue("select HealthID from HealthidRepository where ifnull(status,'1')='1' order by healthid limit 1");
} else {
Connection.MessageBox(Delivfpi.this, "Health ID এর তালিকা থেকে সকল আইডি ব্যবহার করা হয়ে গেছে, নতুন আইডির জন্য আপনার সুপারভাইজারের সাথে যোগাযোগ করুন।");
return HID;
}
return HID;
}
private String GetOutComeDate(String HealthId) {
String SQL = "";
String DOB = "";
SQL += "Select outcomeDate from delivery WHERE healthId = '" + g.getGeneratedId() + "'";// and PregNo=";
DOB = Global.Right(("00" + C.ReturnSingleValue(SQL)), 10);
return DOB;
}
public void AddChildToPRS() {
try {
String SQL = "";
String AG = "";
String MaxSNo = MaxSNo();
String DOB = GetOutComeDate(g.getGeneratedId());
String HealthId = HealthIdNO();
//Issue SNo and HealthID
if (!C.Existence("Select Dist,Upz,UN,Mouza,Vill,HHNo,SNo from " + MemberTable + " Where Dist='" + g.getDistrict() + "' and Upz='" + g.getUpazila() + "' and UN='" + g.getUnion() + "' and Mouza='" + g.getMouza() + "' and Vill='" + g.getVillage() + "' and HHNo='" + g.getHouseholdNo() + "' and SNo='" + MaxSNo + "'")) {
SQL = "Insert into " + MemberTable + "(Dist,Upz,UN,Mouza,Vill,ProvType,ProvCode,HHNo,SNo,HealthID,Lat,Lon,StartTime,EnType,EnDate,EndTime,ExType,ExDate,UserId,EnDt,upload)Values('" + g.getDistrict() + "','" + g.getUpazila() + "','" + g.getUnion() + "','" + g.getMouza() + "','" + g.getVillage() + "','" + g.getProvType() + "','" + g.getProvCode() + "','" + g.getHouseholdNo() + "','" + MaxSNo + "','" + HealthId + "','" + Double.toString(currentLatitude) + "','" + Double.toString(currentLongitude) + "','" + StartTime + "','','" + g.DateNowYMD() + "','" + g.CurrentTime24() + "','','','" + g.getUserID() + "','" + Global.DateTimeNowYMDHMS() + "','2')";
C.Save(SQL);
C.Save("Update HealthIDRepository Set Status='2' where HealthID='" + HealthId + "'");
}
String SQL1 = "";
SQL1 = "Select Dist, Upz, UN, Mouza, Vill, HHNo, SNo as MotherNo, ifnull(HealthID,'') as HealthID, ifnull(NameEng,'') as NameEng,";
SQL1 += " ifnull(NameBang,'') as NameBang, ifnull(Rth,'') as Rth, ifnull(HaveNID,'') as HaveNID, ifnull(NID,'') as NID, ifnull(NIDStatus,'') as NIDStatus, ifnull(HaveBR,'') as HaveBR, ifnull(BRID,'') as BRID, ifnull(BRIDStatus,'') as BRIDStatus, ifnull(MobileNo1,'') as MobileNo1,";
SQL1 += " ifnull(MobileNo2,'') as MobileNo2, ifnull(MobileYN,'')as MobileYN, ifnull(DOB,'') as DOB, ifnull(cast(((julianday(date('now'))-julianday(DOB))/365.25)as int),'') as Age, ifnull(DOBSource,'') as DOBSource, ifnull(BPlace,'') as BPlace, ifnull(FNo,'') as FNo, ifnull(Father,'') as Father, ifnull(FDontKnow,'')as FDontKnow, ifnull(MNo,'') as MNo, ifnull(Mother,'') as Mother,ifnull(MDontKnow,'')as MDontKnow,";
SQL1 += " ifnull(Sex,'') as Sex, ifnull(MS,'') as MS, ifnull(SPNO1,'') as SPNO1,ifnull(SPNO2,'') as SPNO2,ifnull(SPNO3,'') as SPNO3,ifnull(SPNO4,'') as SPNO4, ifnull(ELCONo,'') as ELCONo, ifnull(ELCODontKnow,'') as ELCODontKnow, ifnull(EDU,'') as EDU, ifnull(Rel,'') as Rel, ifnull(Nationality,'') as Nationality, ifnull(OCP,'') as OCP,";
SQL1 += " (select NameEng from member where ProvCode=(select ProvCode from member Where healthid ='" + g.getHealthID() + "')";
SQL1 += "and HHNo=(select HHNo from member Where healthid='" + g.getHealthID() + "')";
SQL1 += "and SNo=(select SPNO1 from member Where healthid='" + g.getHealthID() + "'))as HusName,";
SQL1 += "(select SNo from member where ProvCode=(select ProvCode from member Where healthid='" + g.getHealthID() + "')";
SQL1 += "and HHNo=(select HHNo from member Where healthid='" + g.getHealthID() + "')";
SQL1 += "and SNo=(select SPNO1 from member Where healthid='" + g.getHealthID() + "'))as FatherNo from Member where healthid='" + g.getHealthID() + "'";
Cursor cur = C.ReadData(SQL1);
cur.moveToFirst();
while (!cur.isAfterLast()) {
SQL = "Update " + MemberTable + " Set ";
String MotherName = cur.getString(cur.getColumnIndex("NameEng"));
String ChildOf = "Child of ";
SQL += "NameEng = '" + ChildOf + " " + MotherName + "',";
SQL += "NameBang = '',"; //convert english name to bangla
String RelationWithHead = cur.getString(cur.getColumnIndex("Rth"));
if (RelationWithHead.equalsIgnoreCase("02"))
SQL += "RTH = '03',";
else if (RelationWithHead.equalsIgnoreCase("15") | RelationWithHead.equalsIgnoreCase("12") | RelationWithHead.equalsIgnoreCase("03") | RelationWithHead.equalsIgnoreCase("13") | RelationWithHead.equalsIgnoreCase("16"))
SQL += "RTH = '08',";
else if (RelationWithHead.equalsIgnoreCase("05") | RelationWithHead.equalsIgnoreCase("14"))
SQL += "RTH = '16',";
else if (RelationWithHead.equalsIgnoreCase("04") | RelationWithHead.equalsIgnoreCase("11"))
SQL += "RTH = '05',";
else if (RelationWithHead.equalsIgnoreCase("06"))
SQL += "RTH = '05',";
else if (RelationWithHead.equalsIgnoreCase("10"))
SQL += "RTH = '09',";
else if (RelationWithHead.equalsIgnoreCase("17"))
SQL += "RTH = '16',";
else if (RelationWithHead.equalsIgnoreCase("18"))
SQL += "RTH = '77',";
else
SQL += "RTH = '77',";
SQL += "HaveNID = '2',";
SQL += "NID = '',";
SQL += "NIDStatus = '7',";
SQL += "HaveBR = '2',";
SQL += "BRID = '',";
SQL += "BRIDStatus = '7',";
SQL += "MobileNo1 = '',";
SQL += "MobileNo2 = '',";
SQL += "MobileYN = '',";
SQL += "DOB = '" + DOB + "',"; //Global.DateConvertYMD(dtpDOB.getText().toString())
SQL += "Age = '" + Global.DateDifferenceYears(Global.DateNowDMY(), Global.DateConvertDMY(DOB.toString())) + "',";
SQL += "DOBSource = '1',";
SQL += "BPlace = '" + g.getDistrict() + "',";
String FatherSNo = cur.getString(cur.getColumnIndex("FatherNo"));
SQL += "FNo = '" + FatherSNo + "',";
SQL += "Father = '',";
SQL += "FDontKnow = '2',";
String MatherSNo = cur.getString(cur.getColumnIndex("MotherNo"));
SQL += "MNo = '" + MatherSNo + "',";
SQL += "Mother = '',";
SQL += "MDontKnow = '2',";
SQL += "Sex = '',";
SQL += "MS = '1',";
SQL += "SPNo1 = '',";
SQL += "SPNo2 = '',";
SQL += "SPNo3 = '',";
SQL += "SPNo4 = '',";
SQL += "ELCONo = '',";
SQL += "ELCODontKnow = '1',";
SQL += "EDU = '99',";
String Religious = cur.getString(cur.getColumnIndex("Rel"));
SQL += "Rel = '" + Religious + "',";
String Nationality = cur.getString(cur.getColumnIndex("Nationality"));
SQL += "Nationality = '" + Nationality + "',";
SQL += "OCP = '88'";
SQL += " Where Dist='" + g.getDistrict() + "' and Upz='" + g.getUpazila() + "' and UN='" + g.getUnion() + "' and Mouza='" + g.getMouza() + "' and Vill='" + g.getVillage() + "' and ProvType='" + g.getProvType() + "' and ProvCode='" + g.getProvCode() + "' and HHNo='" + g.getHouseholdNo() + "' and SNo='" + MaxSNo + "'";
C.Save(SQL);
cur.moveToNext();
cur.close();
}
} catch (Exception e) {
Connection.MessageBox(Delivfpi.this, e.getMessage());
return;
}
}
private void DisplayPNCVisits() {
GridView gcount = (GridView) findViewById(R.id.gridPNC);
g.setImuCode(String.valueOf(gcount.getCount() + 1));
PNCVisits();
}
public void PNCVisits() {
GridView g1 = (GridView) findViewById(R.id.gridPNC);
g1.setAdapter(new PNC(this));
g1.setNumColumns(6);
}
public class PNC extends BaseAdapter {
private Context mContext;
String[][] vcode;
Integer totalRec;
public PNC(Context c) {
mContext = c;
}
public int getCount() {
return Integer.parseInt(C.ReturnSingleValue("Select count(*)total from pncServiceMother where healthid='" + g.getGeneratedId() + "' AND pregNo = '" + g.getPregNo() + "'"));
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return 0;
}
public View getView(final int position, View convertView, ViewGroup parent) {
View MyView = convertView;
if (convertView == null) {
LayoutInflater li = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
MyView = li.inflate(R.layout.anc_item_actual, null);
/*String SQL = "Select healthId, pregNo,serviceId, visitDate from pncServiceMother where healthid='" + g.getGeneratedId() + "' AND pregNo = '" + PGNNo() + "'" + " order by cast(visitDate as DATE) asc";*/
String SQL = "Select healthId, pregNo,serviceId, visitDate from pncServiceMother where healthid='" + g.getGeneratedId() + "' AND pregNo = '" + g.getPregNo() + "'" + " order by cast(visitDate as DATE) asc";
try {
Cursor cur = C.ReadData(SQL);
cur.moveToFirst();
totalRec = cur.getCount();
vcode = new String[4][totalRec];
int i = 0;
while (!cur.isAfterLast()) {
vcode[0][i] = "পরিদর্শন " + String.valueOf(i + 1) + " " + Global.DateConvertDMY(String.valueOf(cur.getString(cur.getColumnIndex("visitDate"))));
vcode[1][i] = String.valueOf(cur.getString(cur.getColumnIndex("serviceId")));
vcode[2][i] = String.valueOf(cur.getString(cur.getColumnIndex("visitDate")));
i += 1;
cur.moveToNext();
}
cur.close();
Button tv = (Button) MyView.findViewById(R.id.image_name);
tv.setTextSize(14);
tv.setText(vcode[0][position]);//+ "\n" + vcode[2][position]);
final Integer p = position;
tv.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String ServiceId = String.valueOf(vcode[1][position]);
DisplaySelectedPNCInfo(ServiceId);
}
});
} catch (Exception ex) {
Connection.MessageBox(Delivfpi.this, ex.getMessage());
}
}
return MyView;
}
}
private void DisplaySelectedPNCInfo(String ServiceId) {
String SQL = "Select visitDate from pncServiceMother where serviceId = '" + ServiceId + "'";
try {
Cursor cur = C.ReadData(SQL);
cur.moveToFirst();
while (!cur.isAfterLast()) {
// dtpVDate.setText(Global.DateConvertDMY(cur.getString(cur.getColumnIndex("visitDate"))));
if (!cur.getString(cur.getColumnIndex("visitDate")).equalsIgnoreCase("")) {
((EditText) findViewById(R.id.dtpDOPNCCh1)).setText(Global.DateConvertDMY(cur.getString(cur.getColumnIndex("visitDate"))));
}
cur.moveToNext();
}
cur.close();
} catch (Exception ex) {
Connection.MessageBox(Delivfpi.this, ex.getMessage());
}
}
private void DataSavePNC() {
try {
if (dtpDOPNCCh1.getText().toString().length() == 0 & dtpDOPNCCh1.isShown()) {
Connection.MessageBox(Delivfpi.this, "পি এন সি এর তারিখ কত লিখুন।");
dtpDOPNCCh1.requestFocus();
return;
}
if (validateDeliveryDate()) {
Connection.MessageBox(Delivfpi.this, "পি এন সি এর সঠিক তারিখ কত লিখুন।");
return;
}
String SQL = "";
SQL = "select healthId, pregNo, serviceId, providerId, visitDate, serviceSource, systemEntryDate, upload,modifyDate FROM pncServiceMother ";
SQL += " WHERE healthId = '" + g.getGeneratedId() + "' AND pregNo ='" + g.getPregNo() + "' and serviceId='" + GetServiceId() + "' ORDER BY visitDate";
String SQ = "select visitDate FROM pncServiceMother ";
SQ += " WHERE healthId = '" + g.getGeneratedId() + "' AND pregNo ='" + g.getPregNo() + "' and visitDate='" + Global.DateConvertYMD(dtpDOPNCCh1.getText().toString()) + "'";
if (!C.Existence(SQL) && !C.Existence(SQ)) {
SQL = "Insert into " + TableNamePNC + "(healthId, pregNo, serviceId, providerId, visitDate, serviceSource, systemEntryDate, upload)Values('" +
g.getGeneratedId() + "','" + g.getPregNo() + "','" + GetServiceId() + "','" + g.getProvCode() + "','" + Global.DateConvertYMD(dtpDOPNCCh1.getText().toString()) + "','" + "G','" + Global.DateTimeNowYMDHMS() + "','" + "2')";
C.Save(SQL);
((LinearLayout) findViewById(R.id.secChildList)).setVisibility(View.VISIBLE);
Connection.MessageBox(Delivfpi.this, "তথ্য সফলভাবে সংরক্ষণ হয়েছে।");
} else {
Connection.MessageBox(Delivfpi.this, "পি এন সি এর ভিসিট দেয়া আছে");
return;
}
} catch (Exception e) {
Connection.MessageBox(Delivfpi.this, e.getMessage());
return;
}
}
private String GetServiceId() {
String SQL = "";
SQL = "select '0'||(ifnull(max(cast(serviceId as int)),0))MaxserviceId from pncServiceMother";
SQL += " WHERE healthId = '" + g.getGeneratedId() + "' AND pregNo ='" + g.getPregNo() + "'";
String tempserviceID = C.ReturnSingleValue(SQL);
String serviceID = String.valueOf((Integer.parseInt(tempserviceID) + 1));
if (serviceID.equalsIgnoreCase("1")) {
return String.valueOf(g.getGeneratedId() + g.getPregNo() + serviceID);
} else {
return String.valueOf(serviceID);
}
}
private void PNCVisitSearch(String serviceId) {
try {
String SQL = "";
SQL = "select healthId, pregNo, serviceId, providerId, visitDate, serviceSource, systemEntryDate, upload,modifyDate FROM pncServiceMother ORDER BY visitDate";
SQL += " WHERE healthId = '" + g.getGeneratedId() + "' AND pregNo ='" + g.getPregNo() + "' and serviceId='" + serviceId + "'";
Cursor cur = C.ReadData(SQL);
cur.moveToFirst();
while (!cur.isAfterLast()) {
if (!cur.getString(cur.getColumnIndex("visitDate")).equals("null")) {
dtpDOPNCCh1.setText(Global.DateConvertDMY(cur.getString(cur.getColumnIndex("visitDate"))));
}
cur.moveToNext();
}
cur.close();
} catch (Exception e) {
Connection.MessageBox(Delivfpi.this, e.getMessage());
return;
}
}
}
|
/* Written in 2017 by Andrew Dawson
*
* To the extent possible under law, the author(s) have dedicated all copyright and related and
* neighboring rights to this software to the public domain worldwide. This software is distributed
* without any warranty.
*
* You should have received a copy of the CC0 Public Domain Dedication along with this software.
* If not, see <http://creativecommons.org/publicdomain/zero/1.0/>. */
package tech.bigfig.romachat.data.api;
import android.net.Uri;
import androidx.annotation.Nullable;
import java.util.ArrayList;
import java.util.List;
/**
* Represents one link and its parameters from the link header of an HTTP message.
*
* @see <a href="https://tools.ietf.org/html/rfc5988">RFC5988</a>
*/
public class HttpHeaderLink {
private static class Parameter {
public String name;
public String value;
}
private List<Parameter> parameters;
public Uri uri;
private HttpHeaderLink(String uri) {
this.uri = Uri.parse(uri);
this.parameters = new ArrayList<>();
}
private static int findAny(String s, int fromIndex, char[] set) {
for (int i = fromIndex; i < s.length(); i++) {
char c = s.charAt(i);
for (char member : set) {
if (c == member) {
return i;
}
}
}
return -1;
}
private static int findEndOfQuotedString(String line, int start) {
for (int i = start; i < line.length(); i++) {
char c = line.charAt(i);
if (c == '\\') {
i += 1;
} else if (c == '"') {
return i;
}
}
return -1;
}
private static class ValueResult {
String value;
int end;
ValueResult() {
end = -1;
}
void setValue(String value) {
value = value.trim();
if (!value.isEmpty()) {
this.value = value;
}
}
}
private static ValueResult parseValue(String line, int start) {
ValueResult result = new ValueResult();
int foundIndex = findAny(line, start, new char[] {';', ',', '"'});
if (foundIndex == -1) {
result.setValue(line.substring(start));
return result;
}
char c = line.charAt(foundIndex);
if (c == ';' || c == ',') {
result.end = foundIndex;
result.setValue(line.substring(start, foundIndex));
return result;
} else {
int quoteEnd = findEndOfQuotedString(line, foundIndex + 1);
if (quoteEnd == -1) {
quoteEnd = line.length();
}
result.end = quoteEnd;
result.setValue(line.substring(foundIndex + 1, quoteEnd));
return result;
}
}
private static int parseParameters(String line, int start, HttpHeaderLink link) {
for (int i = start; i < line.length(); i++) {
int foundIndex = findAny(line, i, new char[] {'=', ','});
if (foundIndex == -1) {
return -1;
} else if (line.charAt(foundIndex) == ',') {
return foundIndex;
}
Parameter parameter = new Parameter();
parameter.name = line.substring(line.indexOf(';', i) + 1, foundIndex).trim();
link.parameters.add(parameter);
ValueResult result = parseValue(line, foundIndex);
parameter.value = result.value;
if (result.end == -1) {
return -1;
} else {
i = result.end;
}
}
return -1;
}
/**
* @param line the entire link header, not including the initial "Link:"
* @return all links found in the header
*/
public static List<HttpHeaderLink> parse(@Nullable String line) {
List<HttpHeaderLink> linkList = new ArrayList<>();
if (line != null) {
for (int i = 0; i < line.length(); i++) {
int uriEnd = line.indexOf('>', i);
String uri = line.substring(line.indexOf('<', i) + 1, uriEnd);
HttpHeaderLink link = new HttpHeaderLink(uri);
linkList.add(link);
int parseEnd = parseParameters(line, uriEnd, link);
if (parseEnd == -1) {
break;
} else {
i = parseEnd;
}
}
}
return linkList;
}
/**
* @param links intended to be those returned by parse()
* @param relationType of the parameter "rel", commonly "next" or "prev"
* @return the link matching the given relation type
*/
@Nullable
public static HttpHeaderLink findByRelationType(List<HttpHeaderLink> links,
String relationType) {
for (HttpHeaderLink link : links) {
for (Parameter parameter : link.parameters) {
if (parameter.name.equals("rel") && parameter.value.equals(relationType)) {
return link;
}
}
}
return null;
}
}
|
package com.chris.utopia.module.idea.presenter;
import android.content.Context;
import com.chris.utopia.common.constant.Constant;
import com.chris.utopia.common.util.DateUtil;
import com.chris.utopia.common.util.SharedPrefsUtil;
import com.chris.utopia.entity.Idea;
import com.chris.utopia.entity.ThingClasses;
import com.chris.utopia.module.idea.activity.IdeaCreateActionView;
import com.chris.utopia.module.idea.interactor.IdeaInteractor;
import com.google.inject.Inject;
import java.sql.SQLException;
import java.util.Date;
/**
* Created by Chris on 2016/1/22.
*/
public class IdeaCreatePresenterImpl implements IdeaCreatePresenter {
private IdeaCreateActionView actionView;
private Context mContext;
@Inject
private IdeaInteractor interactor;
@Override
public void setActionView(IdeaCreateActionView actionView) {
this.actionView = actionView;
this.mContext = actionView.getContext();
}
@Override
public ThingClasses getThingClassById(Integer id) {
try {
return interactor.findThingClassessById(id);
} catch (SQLException e) {
e.printStackTrace();
return null;
}
}
@Override
public void addIdea(Idea idea) {
try {
int userId = SharedPrefsUtil.getIntValue(mContext, Constant.SP_KEY_LOGIN_USER_ID, 0);
String userName = SharedPrefsUtil.getStringValue(mContext, Constant.SP_KEY_LOGIN_USER_NAME, "");
idea.setUserId(userId);
idea.setCreateAt(DateUtil.toString(new Date(), Constant.DATETIME_FORMAT_6));
idea.setCreateBy(userName);
idea.setUpdateAt(DateUtil.toString(new Date(), Constant.DATETIME_FORMAT_6));
idea.setUpdateBy(userName);
interactor.addIdea(idea);
actionView.saveIdeaMessage("保存Idea成功");
} catch (SQLException e) {
e.printStackTrace();
actionView.saveIdeaMessage("保存Idea失败");
}
}
}
|
/*******************************************************************************
* Copyright 2021 Danny Kunz
*
* 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.
******************************************************************************/
/*
Copyright 2017 Danny Kunz
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.omnaest.genomics.ensembl.domain;
import java.util.List;
import java.util.stream.Stream;
/**
* Accessor for gene information
*
* @author omnaest
*/
public interface GeneAccessor
{
public String getName();
public String getDescription();
public String getDNASequence();
public GeneLocation getLocation();
public GeneLocation getLocation(String referenceAssembly);
public List<Variant> getVariants();
public List<Exon> getExons();
public Stream<String> getProteinSequences();
public Stream<ProteinTranscriptAccessor> getProteinTranscripts();
public String getUniprotId();
Stream<String> getcDNASequences();
}
|
package com.ss.android.ugc.aweme.miniapp;
import android.content.Context;
import com.ss.android.ugc.aweme.miniapp_api.b.g;
import com.ss.android.ugc.aweme.miniapp_api.model.b.b;
/* Location: C:\Users\august\Desktop\tik\df_miniapp\classes.jar!\com\ss\androi\\ugc\aweme\miniapp\k.class
* Java compiler version: 6 (50.0)
* JD-Core Version: 1.1.3
*/
|
package test_funzionali;
import static org.junit.Assert.*;
import java.util.ArrayList;
import java.util.Calendar;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import sistema.*;
public class UC05InserireUnNuovoSpettacoloNellaProgrammazioneDiUnCinema {
ApplicazioneAmministratoreSistema adminApp;
ApplicazioneGestoreCinema managerApp;
Calendar adminBirthday;
Calendar managerBirthday;
static ArrayList<String> actors;
static ArrayList<String> genre;
static String plot;
static ArrayList<String> tags;
Cinema cinema;
@BeforeClass
public static void setUpBeforeClass() throws Exception {
actors = new ArrayList<String>();
actors.add("Roberto Benigni");
actors.add("Nicoletta Braschi");
actors.add("Giorgio Cantarini");
actors.add("Giustino Durano");
genre = new ArrayList<String>();
genre.add("Drammatico");
genre.add("Commedia");
plot = "Seconda guerra mondiale. Guido, sua moglie Dora e suo figlio Giosuč vengono rinchiusi in un campo nazista. Guido dice al figlio che si trovano in un lagher per partecipare ad un gioco a premi, dove chi fa piů punti vince un carrarmato. In questo modo riesce a proteggere il figlio dall'orrore che stanno vivendo.";
tags = new ArrayList<String>();
tags.add("olocausto");
tags.add("guerra");
tags.add("oscar");
tags.add("amore");
}
@Before
public void setUp() throws Exception {
adminBirthday = Calendar.getInstance();
adminBirthday.set(1975, 2, 5);
managerBirthday = Calendar.getInstance();
managerBirthday.set(1980, 0, 1);
adminApp = new ApplicazioneAmministratoreSistema("Anna",
"Bianchi", "BNCNNA75C45D969Q", adminBirthday, "AnnaBianchi", "0000",
"anna.bianchi@gmail.com");
adminApp.login("AnnaBianchi", "0000");
adminApp.resetApplication();
// Inserimento di un film nel CircuitoCinema
adminApp.inserisciNuovoFilm("10.5240/5A58-58D4-01CB-C41D-6902-K",
"La vita č bella", "Roberto Benigni", actors, 120, 1997, genre,
"Melampo Cinematografica", plot, tags);
// Registrazione Gestore
adminApp.registraNuovoGestoreCinema("Luca", "Rossi", "RSSLCU80A01D969P",
managerBirthday, "luca.rossi@gmail.com");
managerApp = new ApplicazioneGestoreCinema();
managerApp.login("RSSLCU80A01D969P", "0000");
// Inserimento cinema e sala per il nuovo Gestore
cinema = new Cinema("Odeon", "Corso Buenos Aires, 83, 16129 Genova");
adminApp.addNewCinema("RSSLCU80A01D969P", cinema);
int id = managerApp.inserisciNuovaSala(cinema.getId(), "Sala A", 10, 10, 10);
assertNotEquals(-1, id);
}
// Scenario principale: Il Gestore Cinema inserisce un nuovo spettacolo
@Test
public void UC5test1() {
// 2. L’Applicazione Gestore Cinema mostra al Gestore Cinema la lista dei cinema
assertTrue(managerApp.printAllCinema());
// 3. L’Applicazione Gestore Cinema chiede al Gestore Cinema di inserire l’id del cinema
// 4. Il Gestore Cinema inserisce l’id del cinema in cui vuole aggiungere
// uno spettacolo in programmazione
// 5. L'Applicazione Gestore Cinema valida i dati immessi
assertTrue(managerApp.hasCinema(cinema.getId()));
// 6. L’Applicazione Gestore Cinema chiede al Gestore Cinema di inserire l’id del film
// 7. Il Gestore Cinema inserisce l’id del film di cui vuole aggiungere uno spettacolo
// in programmazione
Film film = ApplicazioneAmministratoreSistema.cercaFilmPerId("10.5240/5A58-58D4-01CB-C41D-6902-K");
// 8. L’Applicazione Gestore Cinema valida i dati inseriti
assertNotNull(film);
// 9. L’Applicazione Gestore Cinema chiede al Gestore Cinema i dati
// necessari all'inserimento
// (Non viene implementata una prima validazione dei dati, ad esempio verificare che
// la data sia corretta e futura o che il tempo di attrezzaggio sia minore di un certo valore.
// Questa validazione č lasciata ad una futura implementazione)
// 12. L’Applicazione Gestore Cinema mostra al Gestore Cinema le sale
// disponibili per i giorni specificati e nella fascia oraria richiesta
// basandosi sulla durata del film e sul tempo di attrezzaggio della sala
Calendar date = Calendar.getInstance();
date.set(2018, 6, 1, 10, 00);
date.add(Calendar.DAY_OF_MONTH, 5);
Spettacolo show = new Spettacolo(film, date, 10.0f);
ArrayList<Sala> rooms = null;
rooms = managerApp.verifyRoomsAvailability(cinema.getId(), show, 5);
assertNotNull(rooms);
managerApp.printRoomsFromList(rooms);
int salaId = rooms.get(0).getId();
// 16. L’Applicazione Gestore Cinema inserisce il nuovo spettacolo
assertTrue(managerApp.addShows(cinema.getId(), show, 5, salaId));
}
// Scenario alternativo 2a: L’Applicazione Gestore Cinema non trova alcun cinema registrato
@Test
public void UC5test2() {
// Rimozione cinema
adminApp.removeCinema("RSSLCU80A01D969P", cinema.getId());
// 2a. L’Applicazione Gestore Cinema non trova alcun cinema registrato
assertFalse(managerApp.printAllCinema());
return;
}
// Scenario alternativo 4a: Il Gestore Cinema decide di annullare l’operazione
@Test
public void UC5test3() {
// 2. L’Applicazione Gestore Cinema mostra al Gestore Cinema la lista dei cinema
assertTrue(managerApp.printAllCinema());
// 3. L’Applicazione Gestore Cinema chiede al Gestore Cinema di inserire l’id del cinema
// 4. Il Gestore Cinema decide di annullare l'operazione
return;
}
// Scenario alternativo 5a: L’Applicazione Gestore Cinema non valida i dati inseriti
@Test
public void UC5test4() {
// 2. L’Applicazione Gestore Cinema mostra al Gestore Cinema la lista dei cinema
assertTrue(managerApp.printAllCinema());
// 3. L’Applicazione Gestore Cinema chiede al Gestore Cinema di inserire l’id del cinema
// 4. Il Gestore Cinema inserisce l’id del cinema in cui vuole aggiungere
// uno spettacolo in programmazione
// 5a. L'Applicazione Gestore Cinema non valida i dati immessi
int wrongId = -36732839;
assertFalse(managerApp.hasCinema(wrongId));
// Andare al passo 3 dello scenario principale
}
// Scenario alternativo 7a: Il Gestore Cinema decide di annullare l’operazione
@Test
public void UC5test5() {
// 2. L’Applicazione Gestore Cinema mostra al Gestore Cinema la lista dei cinema
assertTrue(managerApp.printAllCinema());
// 3. L’Applicazione Gestore Cinema chiede al Gestore Cinema di inserire l’id del cinema
// 4. Il Gestore Cinema inserisce l’id del cinema in cui vuole aggiungere
// uno spettacolo in programmazione
// 5. L'Applicazione Gestore Cinema valida i dati immessi
assertTrue(managerApp.hasCinema(cinema.getId()));
// 6. L’Applicazione Gestore Cinema chiede al Gestore Cinema di inserire l’id del film
// 7a. Il Gestore Cinema decide di annullare l’operazione
return;
}
// Scenario alternativo 8a: L’Applicazione Gestore Cinema non valida i dati inseriti
@Test
public void UC5test6() {
// 2. L’Applicazione Gestore Cinema mostra al Gestore Cinema la lista dei cinema
assertTrue(managerApp.printAllCinema());
// 3. L’Applicazione Gestore Cinema chiede al Gestore Cinema di inserire l’id del cinema
// 4. Il Gestore Cinema inserisce l’id del cinema in cui vuole aggiungere
// uno spettacolo in programmazione
// 5. L'Applicazione Gestore Cinema valida i dati immessi
assertTrue(managerApp.hasCinema(cinema.getId()));
// 6. L’Applicazione Gestore Cinema chiede al Gestore Cinema di inserire l’id del film
// 7. Il Gestore Cinema inserisce l’id del film di cui vuole aggiungere uno spettacolo
// in programmazione
Film film = ApplicazioneAmministratoreSistema.cercaFilmPerId("WrongId");
// 8a. L’Applicazione Gestore Cinema non valida i dati inseriti
assertNull(film);
// Andare al passo 6 dello scenario principale
}
// Scenario alternativo 10a: Il Gestore Cinema decide di annullare l’operazione
@Test
public void UC5test7() {
// 2. L’Applicazione Gestore Cinema mostra al Gestore Cinema la lista dei cinema
assertTrue(managerApp.printAllCinema());
// 3. L’Applicazione Gestore Cinema chiede al Gestore Cinema di inserire l’id del cinema
// 4. Il Gestore Cinema inserisce l’id del cinema in cui vuole aggiungere
// uno spettacolo in programmazione
// 5. L'Applicazione Gestore Cinema valida i dati immessi
assertTrue(managerApp.hasCinema(cinema.getId()));
// 6. L’Applicazione Gestore Cinema chiede al Gestore Cinema di inserire l’id del film
// 7. Il Gestore Cinema inserisce l’id del film di cui vuole aggiungere uno spettacolo
// in programmazione
Film film = ApplicazioneAmministratoreSistema.cercaFilmPerId("10.5240/5A58-58D4-01CB-C41D-6902-K");
// 8. L’Applicazione Gestore Cinema valida i dati inseriti
assertNotNull(film);
// 9. L’Applicazione Gestore Cinema chiede al Gestore Cinema i dati
// necessari all'inserimento
// 10a. Il Gestore Cinema decide di annullare l'operazione
return;
}
// Scenario alternativo 11a e 12a: L’Applicazione Gestore Cinema non valida i dati inseriti
// o non trova sale disponibili per la fascia oraria richiesta per i giorni specificati
@Test
public void UC5test8() {
// Inserimento precedente di uno spettacolo per eseguire correttamente questo scenario
// alternativo
Calendar date = Calendar.getInstance();
date.set(2018, 6, 1, 10, 00);
date.add(Calendar.DAY_OF_MONTH, 5);
Spettacolo show = new Spettacolo(ApplicazioneAmministratoreSistema.cercaFilmPerId("10.5240/5A58-58D4-01CB-C41D-6902-K"), date, 10.0f);
ArrayList<Sala> rooms = null;
rooms = managerApp.verifyRoomsAvailability(cinema.getId(), show, 5);
assertFalse(rooms.isEmpty());
int salaId = rooms.get(0).getId();
assertTrue(managerApp.addShows(cinema.getId(), show, 5, salaId));
// 2. L’Applicazione Gestore Cinema mostra al Gestore Cinema la lista dei cinema
assertTrue(managerApp.printAllCinema());
// 3. L’Applicazione Gestore Cinema chiede al Gestore Cinema di inserire l’id del cinema
// 4. Il Gestore Cinema inserisce l’id del cinema in cui vuole aggiungere
// uno spettacolo in programmazione
// 5. L'Applicazione Gestore Cinema valida i dati immessi
assertTrue(managerApp.hasCinema(cinema.getId()));
// 7. Il Gestore Cinema inserisce l’id del film di cui vuole aggiungere uno spettacolo
// in programmazione
Film film = ApplicazioneAmministratoreSistema.cercaFilmPerId("10.5240/5A58-58D4-01CB-C41D-6902-K");
// 8. L’Applicazione Gestore Cinema valida i dati inseriti
assertNotNull(film);
// 9. L’Applicazione Gestore Cinema chiede al Gestore Cinema i dati
// necessari all'inserimento
// 11a/12a. L’Applicazione Gestore Cinema non valida i dati inseriti
// o non trova sale disponibili per la fascia oraria richiesta per i giorni specificati
show = new Spettacolo(film, date, 10.0f);
rooms = null;
rooms = managerApp.verifyRoomsAvailability(cinema.getId(), show, 5);
assertTrue(rooms.isEmpty());
// Andare al passo 9 dello scenario principale
}
// Scenario alternativo 15a: Il Gestore Cinema decide di non confermare l'operazione
@Test
public void UC5test9() {
// 2. L’Applicazione Gestore Cinema mostra al Gestore Cinema la lista dei cinema
assertTrue(managerApp.printAllCinema());
// 3. L’Applicazione Gestore Cinema chiede al Gestore Cinema di inserire l’id del cinema
// 4. Il Gestore Cinema inserisce l’id del cinema in cui vuole aggiungere
// uno spettacolo in programmazione
// 5. L'Applicazione Gestore Cinema valida i dati immessi
assertTrue(managerApp.hasCinema(cinema.getId()));
// 7. Il Gestore Cinema inserisce l’id del film di cui vuole aggiungere uno spettacolo
// in programmazione
Film film = ApplicazioneAmministratoreSistema.cercaFilmPerId("10.5240/5A58-58D4-01CB-C41D-6902-K");
// 8. L’Applicazione Gestore Cinema valida i dati inseriti
assertNotNull(film);
// 9. L’Applicazione Gestore Cinema chiede al Gestore Cinema i dati
// necessari all'inserimento
// 12. L’Applicazione Gestore Cinema mostra al Gestore Cinema le sale
// disponibili per i giorni specificati e nella fascia oraria richiesta
// basandosi sulla durata del film e sul tempo di attrezzaggio della sala
Calendar date = Calendar.getInstance();
date.set(2018, 6, 1, 10, 00);
date.add(Calendar.DAY_OF_MONTH, 5);
Spettacolo show = new Spettacolo(film, date, 10.0f);
ArrayList<Sala> rooms = null;
rooms = managerApp.verifyRoomsAvailability(cinema.getId(), show, 5);
assertNotNull(rooms);
managerApp.printRoomsFromList(rooms);
// 15a. Il Gestore Cinema decide di non confermare l'operazione
return;
}
}
|
package com.btg.pqr.entidades;
import java.util.Date;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
import org.springframework.data.mongodb.core.mapping.Field;
@Document(collection = "usuarios")
public class Usuario {
@Id
private String id;
private String usuario;
private String nombre;
private String apellido;
private Usuario usuario_registra;
private Date fecha_registro;
private Usuario usuario_actualiza;
private Date fecha_actualiza;
public Usuario(String id, String usuario, String nombre, String apellido, Usuario usuario_registra,
Date fecha_registro, Usuario usuario_actualiza, Date fecha_actualiza) {
super();
this.id = id;
this.usuario = usuario;
this.nombre = nombre;
this.apellido = apellido;
this.usuario_registra = usuario_registra;
this.fecha_registro = fecha_registro;
this.usuario_actualiza = usuario_actualiza;
this.fecha_actualiza = fecha_actualiza;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getUsuario() {
return usuario;
}
public void setUsuario(String usuario) {
this.usuario = usuario;
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public String getApellido() {
return apellido;
}
public void setApellido(String apellido) {
this.apellido = apellido;
}
public Usuario getUsuario_registra() {
return usuario_registra;
}
public void setUsuario_registra(Usuario usuario_registra) {
this.usuario_registra = usuario_registra;
}
public Date getFecha_registro() {
return fecha_registro;
}
public void setFecha_registro(Date fecha_registro) {
this.fecha_registro = fecha_registro;
}
public Usuario getUsuario_actualiza() {
return usuario_actualiza;
}
public void setUsuario_actualiza(Usuario usuario_actualiza) {
this.usuario_actualiza = usuario_actualiza;
}
public Date getFecha_actualiza() {
return fecha_actualiza;
}
public void setFecha_actualiza(Date fecha_actualiza) {
this.fecha_actualiza = fecha_actualiza;
}
}
|
import processing.core.*;
import processing.data.*;
import processing.event.*;
import processing.opengl.*;
import hype.*;
import processing.pdf.*;
import java.util.HashMap;
import java.util.ArrayList;
import java.io.File;
import java.io.BufferedReader;
import java.io.PrintWriter;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.IOException;
public class build extends PApplet {
boolean record = false;
//int [] colors = {#D64453, #5BA5CB};
String [] interesses = {"Azulejos", "Processing"};
public void setup(){
H.init(this).background(0xffD9CCC1);
//
float u = (0.7f*width)/10;//unit
float diameter =4*u;
int alpha=60;
for (int i=0;i<interesses.lenght;i++){
HText interesse = new HText(interesses[i]);
interesse
.loc((int) random (width), (int) random (height))
// .size(diameter)
// .anchorAt(H.CENTER)
// .noStroke()
// //.stroke(#CCCCCC)
// .fill(colors[1], alpha)//alpha 100
;
H.add(interesse);
}
H.drawStage();
}
public void draw() {
H.drawStage();
PGraphics tmp = null;
if (record) {
tmp = beginRecord(PDF, "render-slide2.pdf");
}
if (tmp == null) {
H.drawStage();
} else {
PGraphics g = tmp;
boolean uses3D = false;
float alpha = 1;
H.stage().paintAll(g, uses3D, alpha);
}
if (record) {
endRecord();
record = false;
}
}
public void keyPressed() {
if (key == 's') {
record = true;
draw();
}
}
public void settings() { size(1024,568); smooth(); }
static public void main(String[] passedArgs) {
String[] appletArgs = new String[] { "build" };
if (passedArgs != null) {
PApplet.main(concat(appletArgs, passedArgs));
} else {
PApplet.main(appletArgs);
}
}
}
|
import javax.lang.model.util.ElementScanner6;
// arr = [2, 5, 7, 13, 34, 41, 45, 56]. Target 7
// 2 element sum to equal to target
// 7 => 0, 1; 8 => -1, -1
// int[] arr = {2, 5, 7, 13, 34, 41, 45, 56}
// arr[4] arr.length
// int count = arr.length;
// int target = 8;
// , 17, 34, 41, 45, 56, 67
public class TwoSum{
public static void main (String[] args){
int[] arr = {2, 5, 7, 13, 17, 34, 41, 45, 56, 67};
int target = 123;
System.out.println(sum(arr, target));
}
public static int sum( int[] arr, int target){
for(int i = 0; i < arr.length - 1; i++){
for(int j = i + 1; j < arr.length; j++){
if(arr[i] + arr[j] == target){
return 1;
}
if(arr[i] + arr[j] > target){
break;
}
}
}
return -1;
}
}
|
package com.libedi.demo.web;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.libedi.demo.domain.Child;
import com.libedi.demo.domain.Parent;
import com.libedi.demo.dto.PostsSaveRequestDto;
import com.libedi.demo.dto.TestDto;
import com.libedi.demo.repository.ChildRepository;
import com.libedi.demo.repository.ParentRepository;
import com.libedi.demo.repository.PostsRepository;
import com.libedi.demo.service.PostService;
import com.libedi.demo.service.TestService;
import com.libedi.demo.service.TxService;
import com.libedi.demo.transform.PostsTransformer;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
@RestController
@RequiredArgsConstructor
@Slf4j
public class WebRestController {
private final PostService postService;
private final PostsRepository postsRepository;
private final TxService txService;
private final TestService testService;
private final ParentRepository parentRepository;
private final ChildRepository childRepository;
@GetMapping("/hello")
public String hello() {
return "HelloWorld";
}
@PostMapping("/posts")
public void savePosts(final PostsSaveRequestDto dto) {
log.info(dto.toString());
postsRepository.save(PostsTransformer.transform(dto));
}
@PutMapping("/posts/{id}")
public void updatePosts(@PathVariable final long id, @RequestBody final PostsSaveRequestDto dto) {
dto.setId(id);
log.info(dto.toString());
postService.update(dto);
}
@GetMapping("/test/{idx}")
public void transactionalTest(@PathVariable int idx) {
switch(idx) {
case 1:
txService.readOnly();
break;
case 2:
txService.notReadOnly();
break;
}
}
@PostMapping("/test/entity")
public void saveTest(@RequestBody final TestDto dto) {
testService.save(dto);
}
@GetMapping("/test-entity/{id}")
public TestDto getTestEntity(@PathVariable long id) {
return testService.getTestEntity(id);
}
@DeleteMapping("/test-entity/{id}")
public void deleteTest(@PathVariable long id) {
testService.delete(id);
}
@PostMapping("/parent")
public Parent saveParent() {
return parentRepository.save(Parent.builder().name("parent name").build());
}
@PostMapping("/child/{parentId}")
public Child saveChild(@PathVariable long parentId) {
return childRepository.save(Child.builder().content("child content")
.parent(parentRepository.findById(parentId).get()).build());
}
@GetMapping("/parent/{parentId}")
public Parent getParent(@PathVariable long parentId) {
return parentRepository.findById(parentId).get();
}
@PostMapping(value = "/test/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public void upload(@RequestPart MultipartFile file, @RequestPart PostsSaveRequestDto dto, @RequestPart TestDto test) {
System.out.println(dto.toString());
System.out.println(test.toString());
System.out.println(file.toString());
}
}
|
package edu.pucmm.modfaas;
import edu.pucmm.modfaas.entidades.Estudiante;
import edu.pucmm.modfaas.servicios.EstudianteService;
import java.util.List;
public class Main {
public static void main(String[] args) {
EstudianteService estudianteService = EstudianteService.getInstancia();
//borrando si existe.
estudianteService.removeEstudiante(20011136);
//creando el registro del estudiante
estudianteService.crearEstudiante(new Estudiante(20011136,
"Carlos Camacho",
"Telemática"));
//listando los estudiantes.
List<Estudiante> listaEstudiantes = estudianteService.getListaEstudiantes();
listaEstudiantes.forEach(e -> System.out.println(e.toString()));
//actualizando
estudianteService.actualizarEstudiante(new Estudiante(20011136,
"Carlos Camacho",
"Sistemas"));
//listando los estudiantes.
listaEstudiantes = estudianteService.getListaEstudiantes();
listaEstudiantes.forEach(e -> System.out.println(e.toString()));
}
}
|
/* 204. Count Primes
Count the number of prime numbers less than a non-negative number, n.
Example:
Input: 10
Output: 4
Explanation: There are 4 prime numbers less than 10, they are 2, 3, 5, 7.
*/
class Solution {
public int countPrimes(int n) {
int count = 0;
for (int i = 0; i < n; i++) {
if (i % 2 == 1 && isPrime(i) || i == 2) {
count++;
}
}
return count;
}
public boolean isPrime(int n) {
if (n == 1) return false;
for (int i = 2; i*i <= n; i++) {
if (n % i == 0) return false;
}
return true;
}
}
|
package com.tencent.mm.plugin.voip.model;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.Intent.ShortcutIconResource;
import android.content.SharedPreferences;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Build.VERSION;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.view.View;
import android.widget.CheckBox;
import android.widget.TextView;
import android.widget.Toast;
import com.tencent.map.geolocation.internal.TencentExtraKeys;
import com.tencent.mm.R;
import com.tencent.mm.compatible.b.f.a;
import com.tencent.mm.compatible.e.q;
import com.tencent.mm.compatible.util.b;
import com.tencent.mm.g.a.tr;
import com.tencent.mm.model.au;
import com.tencent.mm.plugin.appbrand.jsapi.JsApiGetSetting;
import com.tencent.mm.plugin.game.gamewebview.jsapi.biz.GameJsApiLaunchApplication;
import com.tencent.mm.plugin.report.service.h;
import com.tencent.mm.plugin.voip.HeadsetPlugReceiver;
import com.tencent.mm.plugin.voip.b.d;
import com.tencent.mm.plugin.voip.model.s.6;
import com.tencent.mm.plugin.voip.ui.c;
import com.tencent.mm.plugin.voip.video.CaptureView;
import com.tencent.mm.plugin.voip.video.OpenGlRender;
import com.tencent.mm.plugin.voip.video.e;
import com.tencent.mm.plugin.voip.video.g;
import com.tencent.mm.plugin.voip.video.i;
import com.tencent.mm.plugin.voip.video.k;
import com.tencent.mm.sdk.platformtools.SensorController;
import com.tencent.mm.sdk.platformtools.ad;
import com.tencent.mm.sdk.platformtools.ag;
import com.tencent.mm.sdk.platformtools.ah;
import com.tencent.mm.sdk.platformtools.al;
import com.tencent.mm.sdk.platformtools.ao;
import com.tencent.mm.sdk.platformtools.bi;
import com.tencent.mm.sdk.platformtools.x;
import com.tencent.mm.storage.ab;
import com.tencent.mm.storage.bd;
import com.tencent.mm.ui.base.MMTextureView;
import com.tencent.smtt.utils.TbsLog;
import com.tencent.tmassistantsdk.downloadservice.Downloads;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.Iterator;
import java.util.Map;
import java.util.Timer;
public final class o implements a, p$a, u, c, g, k.a, SensorController.a {
public b bEL;
public String cYO;
public ag guJ;
public SensorController hlW;
public TelephonyManager knT;
public PhoneStateListener knU = new PhoneStateListener() {
public final void onCallStateChanged(int i, String str) {
int i2 = 1;
super.onCallStateChanged(i, str);
x.d("MicroMsg.Voip.VoipMgr", "onCallStateChanged :%d, isStartVoip: %b", new Object[]{Integer.valueOf(i), Boolean.valueOf(o.this.oMn)});
if (!o.this.oMn) {
return;
}
if (i == 1) {
o.this.oMp = true;
i.bJI().yK(1);
} else if (i == 2) {
String string;
o.this.oMp = false;
x.i("MicroMsg.Voip.VoipMgr", "phone call coming now!");
if (o.this.oLU && !com.tencent.mm.plugin.voip.b.b.yU(o.this.oLL.mState)) {
s sVar = i.bJI().oNa;
x.i("MicroMsg.Voip.VoipServiceEx", "cancelCallByPhoneInter, roomId:" + sVar.oHa.oJX.kpo);
if (sVar.oHa.oJX.kpo != 0) {
sVar.oHa.oJX.oPS.oKQ = 102;
sVar.oHa.oJX.oPS.oLc = 6;
h.mEJ.a(11521, true, true, new Object[]{Integer.valueOf(i.bJI().oNa.oHa.oJX.kpo), Long.valueOf(i.bJI().bKT()), Long.valueOf(i.bJI().bKU()), Integer.valueOf(3), Long.valueOf(System.currentTimeMillis()), Long.valueOf(System.currentTimeMillis())});
sVar.bLg();
}
}
if (com.tencent.mm.plugin.voip.b.b.yU(o.this.oLL.mState)) {
string = ad.getContext().getString(R.l.voip_call_msg_chat_time, new Object[]{o.bx(bi.bG(o.this.oMa))});
} else {
string = ad.getContext().getString(R.l.voip_call_connection_failed);
}
s sVar2 = i.bJI().oNa;
x.i("MicroMsg.Voip.VoipServiceEx", "hangUpByPhoneInter");
if (sVar2.oHa.oJX.kpo == 0) {
sVar2.oHa.oJZ.bKe();
sVar2.reset();
} else {
sVar2.oHa.oJX.oPS.oKQ = 109;
sVar2.oHa.oJX.oPS.oLi = 4;
sVar2.bLi();
}
String str2 = o.this.oLT.field_username;
String str3 = o.this.oLV ? bd.tby : bd.tbx;
if (!o.this.oLU) {
i2 = 0;
}
q.a(str2, str3, i2, 6, string);
o.this.kZ(4107);
o.this.bKx();
bd bdVar = new bd();
bdVar.setType(10000);
bdVar.ay(System.currentTimeMillis());
bdVar.setStatus(6);
bdVar.setContent(ad.getContext().getString(R.l.voip_call_interrupted_by_other_app) + ", <a href=\"weixin://voip/callagain/?username=" + o.this.cYO + "&isvideocall=" + o.this.oLV + "\">" + ad.getContext().getString(R.l.voip_call_again) + "</a>");
if (!(o.this.cYO == null || o.this.cYO.equals(""))) {
bdVar.ep(o.this.cYO);
au.HU();
com.tencent.mm.model.c.FT().T(bdVar);
}
i.bJI().yK(2);
} else if (i == 0) {
i.bJI().yK(2);
if (1 == o.this.oLZ && com.tencent.mm.plugin.voip.b.b.yU(o.this.oLL.mState) && o.this.oMp) {
o.this.E(true, false);
}
o.this.oMp = false;
}
}
};
public com.tencent.mm.sdk.b.c knV = new 10(this);
private long kqk = 0;
private boolean lfX = false;
private boolean mIsMute = false;
private int mUIType;
public com.tencent.mm.plugin.voip.b.c oLL;
public HeadsetPlugReceiver oLM;
com.tencent.mm.plugin.voip.ui.b oLN;
private com.tencent.mm.plugin.voip.video.a oLO;
private CaptureView oLP;
private a oLQ = null;
private boolean oLR = false;
private Object oLS = new Object();
public ab oLT;
public boolean oLU;
public boolean oLV;
public boolean oLW = false;
private int oLX = Downloads.RECV_BUFFER_SIZE;
private boolean oLY = false;
public int oLZ = 1;
public HeadsetPlugReceiver.a oMA = new 12(this);
public com.tencent.mm.sdk.b.c oMB = new 9(this);
private long oMa = -1;
private boolean oMb = false;
public boolean oMc = false;
private boolean oMd = false;
private boolean oMe = false;
private int oMf = 0;
public k oMg = new k();
private al oMh = null;
private ah oMi;
private boolean oMj = false;
private boolean oMk = false;
private int oMl = 0;
private boolean oMm = false;
public boolean oMn = false;
private com.tencent.mm.plugin.voip.widget.b oMo;
private boolean oMp = false;
private boolean oMq = false;
public String oMr = null;
public boolean oMs = false;
public e oMt = null;
public int oMu = -1;
private long oMv = -1;
private boolean oMw = false;
private long oMx = 0;
private long oMy = -1;
public BroadcastReceiver oMz = new 1(this);
static /* synthetic */ void e(o oVar, boolean z) {
x.i("MicroMsg.Voip.VoipMgr", "do minimizeVoip");
if (2 != oVar.mUIType || VERSION.SDK_INT >= 24) {
oVar.mUIType = 2;
oVar.oMf++;
oVar.oMo = new com.tencent.mm.plugin.voip.widget.b(oVar, oVar.oLL.mState, oVar.oLT, oVar.oLV, oVar.oLU, z);
if (GameJsApiLaunchApplication.CTRL_BYTE == oVar.oLL.mState || 6 == oVar.oLL.mState) {
au.HU();
if (1 == com.tencent.mm.model.c.DT().getInt(327948, 0)) {
Toast.makeText(oVar.g(), oVar.g().getString(R.l.voip_video_mini_short_toast), 0).show();
} else {
Toast.makeText(oVar.g(), oVar.g().getString(R.l.voip_video_mini_long_toast), 1).show();
au.HU();
com.tencent.mm.model.c.DT().setInt(327948, 1);
}
}
if (oVar.oLL.mState == 0 || 2 == oVar.oLL.mState || 256 == oVar.oLL.mState) {
oVar.bKF();
}
i.bJI().stopRing();
i.bJI().F(true, z);
return;
}
x.e("MicroMsg.Voip.VoipMgr", "already is widget");
}
static /* synthetic */ void w(o oVar) {
if (com.tencent.mm.plugin.voip.b.b.yU(oVar.oLL.mState)) {
oVar.oMg.oVv = oVar.oMk;
oVar.oMg.mRotateAngle = oVar.oMl;
k kVar = oVar.oMg;
int[] iArr = new int[2];
if (oVar.oMm) {
iArr[0] = 1;
iArr[1] = 0;
} else {
iArr[0] = 0;
iArr[1] = 0;
}
ByteBuffer allocate = ByteBuffer.allocate(8);
allocate.asIntBuffer().put(iArr);
byte[] array = allocate.array();
if (kVar.oMN.setAppCmd(13, array, array.length) >= 0) {
int length = (array.length % 4 == 0 ? 0 : 1) + (array.length / 4);
ByteBuffer allocate2 = ByteBuffer.allocate(length * 4);
allocate2.put(array);
allocate2.order(ByteOrder.nativeOrder());
allocate2.rewind();
int[] iArr2 = new int[length];
allocate2.asIntBuffer().get(iArr2);
int i = iArr2[0];
length = iArr2[1];
if (i + length != 0) {
k.b bVar = new k.b(kVar);
bVar = new k.b(kVar);
bVar.oVy = i & 65535;
bVar.oVz = (i >> 16) & 65535;
bVar.oVA = length & 65535;
bVar.oVB = (length >> 16) & 65535;
x.d("MicroMsg.VoipFaceDetector", "detect face, location:%s", new Object[]{bVar});
Iterator it = kVar.hfT.iterator();
while (it.hasNext()) {
((k.a) it.next()).a(new int[]{bVar.oVy, bVar.oVz, bVar.oVA, bVar.oVB}, kVar.oVv, kVar.mRotateAngle);
}
return;
}
Iterator it2 = kVar.hfT.iterator();
while (it2.hasNext()) {
((k.a) it2.next()).a(null, kVar.oVv, kVar.mRotateAngle);
}
}
}
}
public final void dK(boolean z) {
x.i("MicroMsg.Voip.VoipMgr", "onSensorEvent, isON: %s, lastIsDeviceNear: %s, deviceSwitchNearScreenTick: %s", new Object[]{Boolean.valueOf(z), Boolean.valueOf(this.oMw), Long.valueOf(this.oMv)});
if (this.oLL == null) {
x.i("MicroMsg.Voip.VoipMgr", "onSensorEvent, not create stateMachine yet, ignore");
} else if (Math.abs(bi.VG() - this.oMy) >= 500 || this.oMy == -1) {
if (com.tencent.mm.plugin.voip.b.b.yU(this.oLL.mState) && (this.oMw != z || this.oMv == -1)) {
if (!(this.oMw || !z || com.tencent.mm.plugin.voip.b.b.yV(this.oLL.mState) || this.mUIType == 2 || this.oMv == -1)) {
x.i("MicroMsg.Voip.VoipMgr", "accumulate near screen time: %s", new Object[]{Long.valueOf(bi.bI(this.oMv))});
this.oMx = r0 + this.oMx;
}
this.oMv = bi.VG();
this.oMw = z;
}
if (this.oLN == null) {
x.i("MicroMsg.Voip.VoipMgr", "onSensorEvent, voipUI is null, ignore");
} else if ((this.oLU || com.tencent.mm.plugin.voip.b.b.yU(this.oLL.mState)) && !com.tencent.mm.plugin.voip.b.b.yV(this.oLL.mState) && this.mUIType != 2) {
x.d("MicroMsg.Voip.VoipMgr", "onSensorEvent, isOn: " + z);
this.oLN.setScreenEnable(z);
this.oMy = bi.VG();
}
} else {
x.d("MicroMsg.Voip.VoipMgr", "onSensorEvent time interval too small");
}
}
public final void ew(int i) {
x.d("MicroMsg.Voip.VoipMgr", "onBluetoothHeadsetStateChange status: %d, mBTRecoverSpeakerOn: %b", new Object[]{Integer.valueOf(i), Boolean.valueOf(this.oMc)});
switch (i) {
case 1:
if (!com.tencent.mm.plugin.voip.b.b.yV(this.oLL.mState)) {
if (1 == this.oLZ) {
this.oMc = true;
} else {
this.oMc = false;
}
}
au.HV().b(false, i.bJI().bJx(), false);
i.bJI().iJ(false);
i.bJI().iR(false);
yC(4);
this.oMs = false;
return;
case 2:
au.HV().yC();
bKk();
return;
case 3:
au.HV().yB();
this.oMs = false;
return;
case 4:
au.HV().yC();
au.HV().yA();
bKk();
return;
default:
return;
}
}
private void bKk() {
String str = "MicroMsg.Voip.VoipMgr";
String str2 = "setSpeakerAfterBluetoothDisconnected, isCheckBluetoothEnd: %s, isVideoState: %s, isRingStop: %s, mBTRecoverSpeakerOn: %s, isMini: %s";
Object[] objArr = new Object[5];
objArr[0] = Boolean.valueOf(this.oMs);
objArr[1] = Boolean.valueOf(com.tencent.mm.plugin.voip.b.b.yV(this.oLL.mState));
objArr[2] = Boolean.valueOf(i.bJI().bKY());
objArr[3] = Boolean.valueOf(this.oMc);
objArr[4] = Boolean.valueOf(2 == this.mUIType);
x.i(str, str2, objArr);
if (!this.oMs) {
if (com.tencent.mm.plugin.voip.b.b.yV(this.oLL.mState)) {
if (i.bJI().bKY()) {
E(true, true);
this.oLZ = 1;
} else {
E(false, false);
this.oLZ = 2;
}
} else if (i.bJI().bKY()) {
if (this.oMc || 2 == this.mUIType) {
E(true, true);
this.oLZ = 1;
} else {
this.oLZ = 2;
}
this.oMc = false;
} else {
E(false, false);
this.oLZ = 2;
}
yC(this.oLZ);
this.oMs = true;
}
}
private void yC(int i) {
this.oLZ = i;
if (this.oLN != null) {
this.oLN.yN(this.oLZ);
}
}
private void E(boolean z, boolean z2) {
x.k("MicroMsg.Voip.VoipMgr", "enableSpeaker: %s, ignoreBluetooth: %s", new Object[]{Boolean.valueOf(z), Boolean.valueOf(z2)});
this.oMb = z;
this.oMc = z;
x.d("MicroMsg.Voip.VoipMgr", "MMCore.getAudioManager() " + au.HV().yI());
if (!z2 && au.HV().yE()) {
z = false;
}
if (q.deN.dby) {
q.deN.dump();
if (q.deN.dbz > 0) {
i.bJI().iJ(z);
}
}
if (q.deN.dcb >= 0 || q.deN.dcc >= 0) {
i.bJI().iJ(z);
}
au.HV().b(z, i.bJI().bJx(), z2);
i.bJI().iR(z);
this.oMd = z;
}
public final void iO(boolean z) {
int i;
x.d("MicroMsg.Voip.VoipMgr", "onSpeakerStateChanged, isSpeakerOn: %b", new Object[]{Boolean.valueOf(z)});
if (i.bJI().bKY()) {
E(z, false);
} else {
s sVar = i.bJI().oNa;
if (sVar.oNt != null) {
sVar.oNt.iX(z);
}
}
if (z) {
i = 1;
} else {
i = 2;
}
yC(i);
h hVar = h.mEJ;
Object[] objArr = new Object[3];
objArr[0] = Integer.valueOf(2);
if (z) {
i = 1;
} else {
i = 2;
}
objArr[1] = Integer.valueOf(i);
objArr[2] = Integer.valueOf(0);
hVar.h(11080, objArr);
}
public final void gD(boolean z) {
int i = 1;
l lVar;
if (z) {
lVar = i.bJI().oNa.oHa.oJZ;
if (lVar.ltc != null) {
lVar.ltc.aO(true);
}
i.bJI().yw(9);
i.bJI().iQ(true);
} else {
lVar = i.bJI().oNa.oHa.oJZ;
if (lVar.ltc != null) {
lVar.ltc.aO(false);
}
i.bJI().yw(8);
i.bJI().iQ(false);
}
this.mIsMute = z;
h hVar = h.mEJ;
Object[] objArr = new Object[3];
objArr[0] = Integer.valueOf(2);
objArr[1] = Integer.valueOf(0);
if (z) {
i = 2;
}
objArr[2] = Integer.valueOf(i);
hVar.h(11080, objArr);
}
public final boolean bKl() {
if (!this.oLL.yX(4103)) {
return false;
}
yD(4103);
i.bJI().bLc();
return true;
}
public final boolean bKm() {
if (!this.oLL.yX(4101)) {
return false;
}
i.bJI().stopRing();
i.bJI().yw(1);
i.bJI().G(true, this.oLV);
h hVar = h.mEJ;
Object[] objArr = new Object[5];
objArr[0] = Integer.valueOf(1);
objArr[1] = Long.valueOf(i.bJI().bKT());
objArr[2] = Integer.valueOf(i.bJI().oNa.oHa.oJX.kpo);
objArr[3] = Integer.valueOf(0);
objArr[4] = Integer.valueOf(this.oLU ? 1 : 0);
hVar.h(11046, objArr);
h.mEJ.h(11080, new Object[]{Integer.valueOf(2), Integer.valueOf(0), Integer.valueOf(0)});
kZ(4111);
kZ(4101);
kZ(4100);
return true;
}
public final boolean bKn() {
int i = 0;
if (!this.oLL.yX(4099)) {
return false;
}
String str = this.oLT.field_username;
String str2 = this.oLV ? bd.tby : bd.tbx;
if (this.oLU) {
i = 1;
}
q.a(str, str2, i, 6, ad.getContext().getString(R.l.voip_callfrom_reject_msg));
i.bJI().stopRing();
i.bJI().oNa.bLh();
kZ(4099);
bKx();
return true;
}
public final boolean bKo() {
if (!this.oLL.yX(4100)) {
return false;
}
x.i("MicroMsg.Voip.VoipMgr", "onAcceptVideoInvite");
i.bJI().stopRing();
i.bJI().G(false, this.oLV);
kZ(4100);
return true;
}
public final boolean bKp() {
int i = 0;
if (!this.oLL.yX(4099)) {
return false;
}
x.i("MicroMsg.Voip.VoipMgr", "onRejectVoiceInvite");
String str = this.oLT.field_username;
String str2 = this.oLV ? bd.tby : bd.tbx;
if (this.oLU) {
i = 1;
}
q.a(str, str2, i, 6, ad.getContext().getString(R.l.voip_callfrom_reject_msg));
i.bJI().stopRing();
i.bJI().oNa.bLh();
kZ(4099);
bKx();
return true;
}
public final boolean bKq() {
if (!this.oLL.yX(4100)) {
return false;
}
x.i("MicroMsg.Voip.VoipMgr", "onAcceptVoiceInvite");
i.bJI().stopRing();
i.bJI().G(true, this.oLV);
kZ(4111);
kZ(4100);
return true;
}
public final boolean bKr() {
if (!this.oLL.yX(4098)) {
return false;
}
x.i("MicroMsg.Voip.VoipMgr", "onCancelVideoInvite");
yD(4098);
i.bJI().bLc();
return true;
}
public final boolean bKs() {
if (!this.oLL.yX(4098)) {
return false;
}
x.i("MicroMsg.Voip.VoipMgr", "onCancelVoiceInvite");
yD(4098);
i.bJI().bLc();
return true;
}
public final void a(com.tencent.mm.plugin.voip.ui.b bVar, int i) {
x.i("MicroMsg.Voip.VoipMgr", "onVoipUICreated");
if (1 == i && this.oLN != null) {
this.oLN.uninit();
}
this.oLN = bVar;
this.mUIType = i;
int i2 = 320;
int i3 = 240;
if (this.oLO == null && com.tencent.mm.plugin.voip.b.b.yV(this.oLL.mState)) {
this.oLP = new CaptureView(ad.getContext());
if (v2protocal.oOg) {
x.i("MicroMsg.Voip.VoipMgr", "steve: 640 capture!");
i2 = 640;
i3 = 480;
}
this.oLO = new com.tencent.mm.plugin.voip.video.a(i2, i3);
this.oLO.a(this, true);
this.oLO.a(this.oLP);
i.bJI().yI(this.oLO.bMd());
this.guJ.postDelayed(new Runnable() {
public final void run() {
x.d("MicroMsg.Voip.VoipMgr", "mCaptureRender == " + o.this.oLO);
if (o.this.oLO != null) {
o.this.oLO.bLY();
}
}
}, 50);
}
this.oLN.setCaptureView(this.oLP);
this.oLN.dQ(-1, this.oLL.mState);
this.oLN.setConnectSec(this.oMa);
this.oLN.yN(this.oLZ);
this.oLN.setMute(this.mIsMute);
x.i("MicroMsg.Voip.VoipMgr", "steve: voipMgr decMode:%d", new Object[]{Integer.valueOf(this.oMu)});
if (this.oMu != -1) {
this.oLN.setHWDecMode(this.oMu);
x.i("MicroMsg.Voip.VoipMgr", "steve: voipMgr setHWDecMode,decMode:%d", new Object[]{Integer.valueOf(this.oMu)});
}
}
public final void a(com.tencent.mm.plugin.voip.ui.b bVar) {
x.i("MicroMsg.Voip.VoipMgr", "onVoipUIDestroy");
if (this.oLN == bVar) {
x.d("MicroMsg.Voip.VoipMgr", "same VoipUI, clear it");
this.oLN = null;
}
if (this.guJ != null) {
this.guJ = null;
}
}
public final void bKt() {
x.i("MicroMsg.Voip.VoipMgr", "onSwitchCamera");
if (this.oLO != null) {
this.oLO.bLX();
}
h.mEJ.h(11079, new Object[]{Integer.valueOf(1)});
}
private void yD(int i) {
String string;
x.i("MicroMsg.Voip.VoipMgr", "hangupTalkingOrCancelInvite");
if (true == bKG()) {
this.oLX = i;
}
Context context = ad.getContext();
if (com.tencent.mm.plugin.voip.b.b.yU(this.oLL.mState)) {
string = context.getString(R.l.voip_call_msg_chat_time, new Object[]{bx(bi.bG(this.oMa))});
} else if (this.oLU) {
string = context.getString(R.l.voip_call_cancel_msg_to);
} else {
string = context.getString(R.l.voip_call_cancel_msg_from);
}
q.a(this.oLT.field_username, this.oLV ? bd.tby : bd.tbx, this.oLU ? 1 : 0, 6, string);
if (!this.oLU || com.tencent.mm.plugin.voip.b.b.yU(this.oLL.mState)) {
com.tencent.mm.sdk.f.e.post(new 14(this), "VoipMgr_play_end_sound");
this.oLR = true;
i.bJI().bKR();
if (Downloads.RECV_BUFFER_SIZE == this.oLX) {
kZ(i);
bKx();
return;
}
return;
}
i.bJI().stopRing();
if (this.oLU && !com.tencent.mm.plugin.voip.b.b.yU(this.oLL.mState)) {
x.i("MicroMsg.Voip.VoipMgr", "hangupVoipButton OnClick call cancelCall");
s sVar = i.bJI().oNa;
x.i("MicroMsg.Voip.VoipServiceEx", "cancelCall, roomId:" + sVar.oHa.oJX.kpo);
if (sVar.oHa.oJX.kpo == 0 && sVar.oHa.oJX.kpr == 0) {
sVar.reset();
} else {
sVar.oHa.oJX.oPS.oKQ = sVar.oHa.bJN();
sVar.oHa.oJX.oPS.oLc = 3;
if (sVar.oHa.mStatus < 6) {
sVar.oHa.oJX.oPS.oLe = 1;
}
h hVar = h.mEJ;
Object[] objArr = new Object[6];
objArr[0] = Integer.valueOf(i.bJI().oNa.oHa.oJX.kpo);
objArr[1] = Long.valueOf(i.bJI().bKT());
objArr[2] = Long.valueOf(i.bJI().bKU());
objArr[3] = Integer.valueOf(sVar.oHa.mStatus == 5 ? 2 : 1);
objArr[4] = Long.valueOf(System.currentTimeMillis());
objArr[5] = Long.valueOf(System.currentTimeMillis());
hVar.a(11521, true, true, objArr);
sVar.bLg();
}
}
x.i("MicroMsg.Voip.VoipMgr", "hangupVoipButton OnClick call hangUp");
i.bJI().bKR();
if (Downloads.RECV_BUFFER_SIZE == this.oLX) {
kZ(i);
bKx();
}
}
public final void a(MMTextureView mMTextureView) {
if (this.oMt != null) {
e eVar = this.oMt;
x.d("DecodeTextureView", "steve: init hwview, recreateView: " + mMTextureView);
eVar.oTL = mMTextureView;
eVar.oTL.setSurfaceTextureListener(eVar);
if (eVar.oTM != null) {
x.d("DecodeTextureView", "using saved st=" + eVar.oTM);
mMTextureView.setSurfaceTexture(eVar.oTM);
}
}
}
public final boolean bKu() {
if (i.bJI().oNa.oHa.oJX.kpo != 0) {
return bKv();
}
this.oLY = true;
return true;
}
private boolean bKv() {
int i = 4;
int i2 = 0;
if (!this.oLL.yX(4101)) {
return false;
}
Object[] objArr;
h hVar;
int i3;
Object[] objArr2;
int i4;
kZ(4101);
if (261 == this.oLL.mState || 7 == this.oLL.mState) {
i.bJI().yw(1);
h hVar2 = h.mEJ;
objArr = new Object[5];
objArr[0] = Integer.valueOf(2);
objArr[1] = Long.valueOf(i.bJI().bKT());
objArr[2] = Integer.valueOf(i.bJI().oNa.oHa.oJX.kpo);
objArr[3] = Integer.valueOf(0);
objArr[4] = Integer.valueOf(this.oLU ? 1 : 0);
hVar2.h(11046, objArr);
hVar = h.mEJ;
Object[] objArr3 = new Object[3];
objArr3[0] = Integer.valueOf(2);
objArr3[1] = Integer.valueOf(0);
i3 = 2;
objArr2 = objArr3;
objArr = objArr3;
i4 = 11080;
} else {
if (1 == this.oLL.mState || 3 == this.oLL.mState) {
i.bJI().yw(1);
hVar = h.mEJ;
i4 = 11046;
Object[] objArr4 = new Object[5];
objArr4[0] = Integer.valueOf(1);
objArr4[1] = Long.valueOf(i.bJI().bKT());
objArr4[2] = Integer.valueOf(i.bJI().oNa.oHa.oJX.kpo);
objArr4[3] = Integer.valueOf(0);
if (this.oLU) {
i2 = 1;
objArr2 = objArr4;
objArr = objArr4;
objArr2[i] = Integer.valueOf(i2);
hVar.h(i4, objArr);
} else {
i3 = 4;
objArr2 = objArr4;
objArr = objArr4;
}
}
i.bJI().bKV();
i.bJI().bKW();
return true;
}
i = i3;
objArr2[i] = Integer.valueOf(i2);
hVar.h(i4, objArr);
i.bJI().bKV();
i.bJI().bKW();
return true;
}
public final void bKw() {
x.i("MicroMsg.Voip.VoipMgr", "onRoomReady");
if (this.oLY && i.bJI().oNa.oHa.oJX.kpo != 0) {
this.oLY = false;
bKv();
}
if (this.oLU) {
kZ(4097);
}
}
private void kZ(final int i) {
x.k("MicroMsg.Voip.VoipMgr", "swtchState, action: %s, currentState: %s", new Object[]{com.tencent.mm.plugin.voip.b.b.yR(i), com.tencent.mm.plugin.voip.b.b.yR(this.oLL.mState)});
if (4101 == i && com.tencent.mm.plugin.voip.b.b.yV(this.oLL.mState)) {
bKF();
}
boolean z = 4111 == i ? true : 4101 == i && (com.tencent.mm.plugin.voip.b.b.yU(this.oLL.mState) || this.oLU);
if (z && 1 == this.mUIType && 1 == this.oLZ) {
this.oMq = true;
E(false, false);
yC(2);
}
com.tencent.mm.plugin.voip.b.c cVar = this.oLL;
if (cVar.yX(i)) {
x.d("MicroMsg.Voip.VoipStateMachine", "from oldState: %s to newState: %s, action: %s", new Object[]{com.tencent.mm.plugin.voip.b.b.yR(cVar.mState), com.tencent.mm.plugin.voip.b.b.yR(((Integer) ((Map) cVar.oSW.get(Integer.valueOf(cVar.mState))).get(Integer.valueOf(i))).intValue()), com.tencent.mm.plugin.voip.b.b.yR(i)});
cVar.mState = r0;
} else {
x.e("MicroMsg.Voip.VoipStateMachine", "can't tranform due to no such rule");
}
this.guJ.post(new Runnable() {
public final void run() {
if (o.this.oLN != null) {
o.this.oLN.dQ(i, o.this.oLL.mState);
}
}
});
if (6 == this.oLL.mState || GameJsApiLaunchApplication.CTRL_BYTE == this.oLL.mState) {
aJv();
}
switch (this.oLL.mState) {
case 258:
case 259:
yE(5);
return;
case 262:
yE(6);
return;
default:
return;
}
}
private static void yE(int i) {
tr trVar = new tr();
trVar.cfr.bIH = i;
com.tencent.mm.sdk.b.a.sFg.m(trVar);
}
public final void onError(int i, String str) {
if (this.oLV) {
i.bJI().dO(R.k.playend, 0);
} else {
i.bJI().dO(R.k.playend, 1);
}
if (i == 241 && bi.oW(str)) {
str = g().getString(R.l.voip_overload_protection_default_wording);
}
if (this.oLN != null) {
this.oLN.aL(i, str);
}
kZ(4109);
x.i("MicroMsg.Voip.VoipMgr", "onError, errCode: %s, roomId: %s", new Object[]{Integer.valueOf(i), Integer.valueOf(i.bJI().oNa.oHa.oJX.kpo)});
Context context = ad.getContext();
x.d("MicroMsg.Voip.VoipMgr", "getErrorMsgContent, errorCode" + i);
String string = i == 235 ? context.getString(R.l.voip_callout_error_msg_unsupport) : i == 233 ? context.getString(R.l.voip_call_fail) : i == 237 ? context.getString(R.l.voip_callout_error_msg_unsupport) : i == JsApiGetSetting.CTRL_INDEX ? context.getString(R.l.voip_call_fail) : i == 211 ? context.getString(R.l.voip_callout_error_msg_busy) : context.getString(R.l.voip_call_connection_failed);
String str2;
String str3;
int i2;
if (i.bJI().oNa.oHa.oJX.kpo != 0 && i.bJI().oNf.get(Integer.valueOf(i.bJI().oNa.oHa.oJX.kpo)) == null) {
str2 = this.oLT.field_username;
str3 = this.oLV ? bd.tby : bd.tbx;
i2 = this.oLU ? 1 : 0;
if (com.tencent.mm.plugin.voip.b.b.yU(this.oLL.mState)) {
string = ad.getContext().getString(R.l.voip_call_msg_chat_time_interrupt_by_err, new Object[]{bx(bi.bG(this.oMa))});
}
i.bJI().oNf.put(Integer.valueOf(i.bJI().oNa.oHa.oJX.kpo), Long.valueOf(q.a(str2, str3, i2, 6, string, true)));
} else if (i.bJI().oNa.oHa.oJX.kpo == 0) {
str2 = this.oLT.field_username;
str3 = this.oLV ? bd.tby : bd.tbx;
i2 = this.oLU ? 1 : 0;
if (com.tencent.mm.plugin.voip.b.b.yU(this.oLL.mState)) {
string = ad.getContext().getString(R.l.voip_call_msg_chat_time_interrupt_by_err, new Object[]{bx(bi.bG(this.oMa))});
}
q.a(str2, str3, i2, 6, string, true);
}
i.bJI().bLc();
bKx();
}
public final void aWJ() {
x.i("MicroMsg.Voip.VoipMgr", "on accept");
i.bJI().stopRing();
kZ(4100);
}
public final void onReject() {
x.i("MicroMsg.Voip.VoipMgr", "onReject");
kZ(4099);
q.a(this.oLT.field_username, this.oLV ? bd.tby : bd.tbx, this.oLU ? 1 : 0, 6, ad.getContext().getString(R.l.voip_callout_reject_msg));
bKx();
}
private void bKx() {
x.d("MicroMsg.Voip.VoipMgr", "delayFinish");
this.oMr = null;
this.guJ.postDelayed(new 16(this), 2000);
}
public final void fr(boolean z) {
r bJI;
x.i("MicroMsg.Voip.VoipMgr", "finish");
this.oMn = false;
this.oMp = false;
if (this.oMf != -1) {
h.mEJ.h(11700, new Object[]{Integer.valueOf(this.oMf), Long.valueOf(bi.bG(this.oMa))});
this.oMf = -1;
}
try {
ad.getContext().unregisterReceiver(this.oMz);
} catch (Exception e) {
}
com.tencent.mm.sdk.b.a.sFg.c(this.knV);
com.tencent.mm.sdk.b.a.sFg.c(this.oMB);
if (this.oLN != null) {
this.oLN.uninit();
this.oLN = null;
}
this.oLP = null;
this.oMt = null;
au.HV().b(this);
au.HV().yC();
if (i.bJI() != null) {
i.bJI().stopRing();
if (z) {
i.bJI().oNa.bLj();
} else {
i.bJI().bKR();
}
if (this.oLV) {
i.bJI().a(false, true, this.cYO);
} else {
i.bJI().a(false, false, this.cYO);
}
bJI = i.bJI();
Context context = ad.getContext();
s sVar = bJI.oNa;
if (context == sVar.oHa.gKE && this == sVar.oHa.oJY) {
sVar.oHa.gKE = null;
sVar.oHa.oJY = u.oNN;
com.tencent.mm.plugin.voip.b.a.eV("MicroMsg.Voip.VoipServiceEx", "detach ui........");
com.tencent.mm.plugin.voip.b.a.bLO();
} else {
com.tencent.mm.plugin.voip.b.a.eV("MicroMsg.Voip.VoipServiceEx", "cannot detach other's ui.");
}
}
bJI = i.bJI();
bJI.oNb = null;
bJI.oNj = null;
bJI.oNk = false;
if (this.oLR) {
this.oLQ = new a(this);
com.tencent.mm.sdk.f.e.post(this.oLQ, "VoipMgr_clean");
} else {
bKE();
}
if (!(this.knT == null || this.knU == null)) {
this.knT.listen(this.knU, 0);
this.knU = null;
}
if (this.oLM != null) {
this.oLM.ej(ad.getContext());
}
this.knT = null;
au.vv().xu();
p.bKK().bKM();
p.bKK().oMP = null;
au.getNotification().cancel(40);
if (this.hlW != null) {
x.d("MicroMsg.Voip.VoipMgr", "removeSensorCallBack");
this.hlW.ciL();
this.hlW = null;
this.oMw = false;
this.oMx = 0;
this.oMv = -1;
}
this.oMy = -1;
i.bJI().bLc();
}
public final void bKy() {
x.i("MicroMsg.Voip.VoipMgr", "onNoResp");
kZ(4105);
q.a(this.oLT.field_username, this.oLV ? bd.tby : bd.tbx, this.oLU ? 1 : 0, 4, ad.getContext().getString(R.l.voip_callout_no_resp));
h.mEJ.a(11518, true, true, new Object[]{Integer.valueOf(i.bJI().oNa.oHa.oJX.kpo), Long.valueOf(i.bJI().bKT()), Long.valueOf(i.bJI().bKU()), Integer.valueOf(6), Integer.valueOf(ao.getNetWorkType(g()))});
bKx();
}
public final void onConnected() {
kZ(4102);
this.oMa = bi.VE();
if (this.oLN != null) {
this.oLN.setConnectSec(this.oMa);
}
boolean bJR = i.bJI().oNa.oHa.bJR();
boolean bJQ = i.bJI().oNa.oHa.bJQ();
if (this.oLV && this.oLU && !bJQ && !bJR) {
i.bJI().yw(1);
}
if (!com.tencent.mm.plugin.voip.b.b.yV(this.oLL.mState)) {
h.mEJ.h(11080, new Object[]{Integer.valueOf(1), Integer.valueOf(0), Integer.valueOf(0)});
}
s sVar = i.bJI().oNa;
if (sVar.oNt != null) {
i iVar = sVar.oNt;
bi.t(iVar.mContext, iVar.mContext.getSharedPreferences(ad.chY(), 0).getBoolean("settings_shake", true));
}
r bJI = i.bJI();
int i = i.bJI().oNa.oHa.oJX.oOv;
s sVar2 = bJI.oNa;
sVar2.bnh = null;
sVar2.oNA = null;
sVar2.oNy = 0;
if (i > 0) {
s.oNw = i;
}
sVar2.bnh = (WifiManager) ad.getContext().getApplicationContext().getSystemService(TencentExtraKeys.LOCATION_SOURCE_WIFI);
sVar2.oNz = new Timer();
sVar2.oNz.schedule(new 6(sVar2), 0, (long) (s.oNw * TbsLog.TBSLOG_CODE_SDK_BASE));
TelephonyManager telephonyManager = (TelephonyManager) ad.getContext().getSystemService("phone");
if (telephonyManager != null) {
telephonyManager.listen(new s$5(sVar2, telephonyManager), 256);
}
p.bKK().bKL();
p.bKK().oMP = this;
}
public final void bKz() {
int i = 0;
h hVar = h.mEJ;
Object[] objArr = new Object[5];
objArr[0] = Integer.valueOf(i.bJI().oNa.oHa.oJX.kpo);
objArr[1] = Long.valueOf(i.bJI().bKT());
objArr[2] = Long.valueOf(i.bJI().bKU());
if (!this.oLU) {
i = 1;
}
objArr[3] = Integer.valueOf(i);
objArr[4] = Integer.valueOf(1);
hVar.a(11522, true, true, objArr);
}
public final void bKA() {
String string;
x.i("MicroMsg.Voip.VoipMgr", "onShutDown");
if (com.tencent.mm.plugin.voip.b.b.yU(this.oLL.mState)) {
string = ad.getContext().getString(R.l.voip_call_msg_chat_time, new Object[]{bx(bi.bG(this.oMa))});
} else {
string = ad.getContext().getString(R.l.voip_call_connection_failed);
}
if (this.oLU || com.tencent.mm.plugin.voip.b.b.yU(this.oLL.mState)) {
q.a(this.oLT.field_username, this.oLV ? bd.tby : bd.tbx, 0, 6, string);
}
if (this.oLV) {
i.bJI().dO(R.k.playend, 0);
} else {
i.bJI().dO(R.k.playend, 1);
}
if (bKG()) {
this.oLX = 4106;
} else {
kZ(4106);
bKx();
}
i.bJI().bLc();
}
public final void yF(int i) {
x.i("MicroMsg.Voip.VoipMgr", "remote voip mode changed, cmd:%d", new Object[]{Integer.valueOf(i)});
if (1 == i || 3 == i || 5 == i || 6 == i || 7 == i) {
kZ(4101);
i.bJI().bKV();
i.bJI().bKW();
}
}
public final void b(int i, int i2, int[] iArr) {
if (this.oLN != null) {
this.oLN.c(i, i2, iArr);
}
}
public final void bKB() {
if (this.oLN != null) {
this.oLN.bKB();
}
}
public final void setHWDecMode(int i) {
this.oMu = i;
if (this.oLN != null) {
this.oLN.setHWDecMode(i);
}
}
public final void yG(int i) {
boolean z = false;
x.i("MicroMsg.Voip.VoipMgr", "onSessionBeingCalled, callType: " + i);
if (this.oLL.yX(4110)) {
r bJI = i.bJI();
boolean z2 = i == 1;
if (i == 1) {
z = true;
}
bJI.G(z2, z);
i.bJI().stopRing();
if (i == 1 && com.tencent.mm.plugin.voip.b.b.yV(this.oLL.mState)) {
kZ(4101);
}
kZ(4110);
}
}
public final void bKC() {
boolean z = true;
x.d("MicroMsg.Voip.VoipMgr", "onPretreatmentForStartDev");
if (au.HV().yK() || au.HV().yE()) {
E(false, false);
return;
}
boolean z2 = 1 == this.oLZ;
if (this.oMq) {
z = false;
} else if (!this.oLV) {
z = z2;
}
E(z, false);
}
public final long bKD() {
x.l("MicroMsg.Voip.VoipMgr", "totalDeviceNearTime: %s", new Object[]{Long.valueOf(this.oMx)});
return this.oMx / 1000;
}
private static String bx(long j) {
return String.format("%02d:%02d", new Object[]{Long.valueOf(j / 60), Long.valueOf(j % 60)});
}
public final void c(byte[] bArr, long j, int i, int i2, int i3) {
if (!this.oMe) {
int i4 = this.oLO.bMb() ? OpenGlRender.oUJ : 0;
int i5 = this.oLO.bMc() ? OpenGlRender.oUI : OpenGlRender.oUH;
int b = i.bJI().oNa.oHa.oJZ.b(bArr, (int) j, i3, i, i2);
if (this.oLN != null) {
this.oLN.a(bArr, j, i, i2, i3, i4, i5, b);
}
this.oMk = i4 == OpenGlRender.oUJ;
this.oMl = i5 == OpenGlRender.oUI ? 270 : 90;
k kVar = this.oMg;
kVar.oVx = i2;
kVar.oVw = i;
}
}
private void bKE() {
synchronized (this.oLS) {
i.bJI().stopRing();
bKF();
au.HV().setMode(0);
if (this.bEL != null) {
this.bEL.zY();
}
}
}
private void bKF() {
x.k("MicroMsg.Voip.VoipMgr", "uninitCaptureRender", new Object[0]);
if (this.oLO != null) {
if (this.oMg != null) {
k kVar = this.oMg;
if (kVar.hfT.contains(this)) {
kVar.hfT.remove(this);
}
}
if (this.oMh != null) {
x.d("MicroMsg.Voip.VoipMgr", "stop face detect timer");
this.oMh.SO();
}
if (this.oMi != null) {
x.d("MicroMsg.Voip.VoipMgr", "quit face detect thread");
this.oMi.lnJ.getLooper().quit();
}
try {
this.oLO.bLZ();
com.tencent.mm.plugin.voip.video.a.bMa();
} catch (Exception e) {
x.d("MicroMsg.Voip.VoipMgr", "stop capture error:" + e.toString());
}
this.oLO = null;
}
}
public final void aWP() {
x.i("MicroMsg.Voip.VoipMgr", "onBadNetStatus");
if (this.oLN != null) {
this.oLN.bLE();
}
if (!com.tencent.mm.plugin.voip.b.b.yV(this.oLL.mState) && !this.oMd) {
long currentTimeMillis = System.currentTimeMillis();
if (currentTimeMillis - this.kqk > 30000) {
this.kqk = currentTimeMillis;
i.bJI().yJ(R.k.voip_bad_netstatus_hint);
}
}
}
public final void aWQ() {
x.i("MicroMsg.Voip.VoipMgr", "onResumeGoodNetStatus");
if (this.oLN != null) {
this.oLN.aYv();
}
}
private boolean bKG() {
if (!com.tencent.mm.plugin.voip.b.b.yU(this.oLL.mState)) {
return false;
}
SharedPreferences sharedPreferences = g().getSharedPreferences("voip_plugin_prefs", 0);
if (sharedPreferences.getBoolean("voip_shortcut_has_added", false)) {
return false;
}
String value = com.tencent.mm.k.g.AT().getValue("VOIPShortcutAutoadd");
x.i("MicroMsg.Voip.VoipMgr", "voip shortcut autoAdd is %s", new Object[]{value});
if (value != null && value.equals("0") && bi.bG(this.oMa) > 30) {
int i = sharedPreferences.getInt("voip_shortcut_prompt_times", 0);
boolean z = sharedPreferences.getBoolean("voip_shortcut_never_show_anymore", false);
if (i >= 3 || z) {
return false;
}
Context context = g();
View inflate = View.inflate(context, R.i.mm_alert_checkbox, null);
final CheckBox checkBox = (CheckBox) inflate.findViewById(R.h.mm_alert_dialog_cb);
checkBox.setChecked(false);
TextView textView = (TextView) inflate.findViewById(R.h.mm_alert_dialog_info);
if (1 == bi.getInt(com.tencent.mm.k.g.AT().getValue("VOIPCallType"), 0)) {
textView.setText(R.l.voip_add_short_cut_tip);
} else {
textView.setText(R.l.voip_add_short_cut_tip_audio);
}
com.tencent.mm.ui.base.h.a(context, false, context.getString(R.l.app_tip), inflate, context.getString(R.l.app_yes), context.getString(R.l.app_no), new 2(this), new OnClickListener() {
public final void onClick(DialogInterface dialogInterface, int i) {
if (checkBox != null) {
o.this.g().getSharedPreferences("voip_plugin_prefs", 0).edit().putBoolean("voip_shortcut_never_show_anymore", checkBox.isChecked()).commit();
}
if (Downloads.RECV_BUFFER_SIZE != o.this.oLX) {
o.this.kZ(o.this.oLX);
o.this.oLX = Downloads.RECV_BUFFER_SIZE;
}
o.this.guJ.post(new 1(this));
}
});
sharedPreferences.edit().putInt("voip_shortcut_prompt_times", i + 1).commit();
return true;
} else if (value == null || !value.equals("1") || bi.bG(this.oMa) <= 15) {
return false;
} else {
c(sharedPreferences);
return false;
}
}
private void c(SharedPreferences sharedPreferences) {
Intent intent = new Intent("com.android.launcher.action.INSTALL_SHORTCUT");
intent.putExtra("duplicate", false);
Object intent2 = new Intent("com.tencent.mm.action.BIZSHORTCUT");
intent2.addFlags(67108864);
if (1 == bi.getInt(com.tencent.mm.k.g.AT().getValue("VOIPCallType"), 0)) {
intent2.putExtra("LauncherUI.Shortcut.LaunchType", "launch_type_voip");
intent.putExtra("android.intent.extra.shortcut.NAME", g().getString(R.l.app_field_voip));
intent.putExtra("android.intent.extra.shortcut.ICON_RESOURCE", ShortcutIconResource.fromContext(g(), R.g.voip_camerachat));
intent.putExtra("shortcut_icon_resource_id", R.g.voip_camerachat);
} else {
intent2.putExtra("LauncherUI.Shortcut.LaunchType", "launch_type_voip_audio");
intent.putExtra("android.intent.extra.shortcut.NAME", g().getString(R.l.app_field_voipaudio));
intent.putExtra("android.intent.extra.shortcut.ICON_RESOURCE", ShortcutIconResource.fromContext(g(), R.g.voip_voicechat));
intent.putExtra("shortcut_icon_resource_id", R.g.voip_voicechat);
}
intent.putExtra("android.intent.extra.shortcut.INTENT", intent2);
com.tencent.mm.plugin.base.model.b.o(g(), intent);
sharedPreferences.edit().putBoolean("voip_shortcut_has_added", true).commit();
}
/* renamed from: getContext */
public final Context g() {
Context context = null;
if (this.oLN != null) {
context = this.oLN.bLD();
}
if (context == null) {
return ad.getContext();
}
return context;
}
public final boolean iP(final boolean z) {
if (!this.oMp || z) {
x.k("MicroMsg.Voip.VoipMgr", "miniOnlyHidenVoip: %b", new Object[]{Boolean.valueOf(z)});
x.i("MicroMsg.Voip.VoipMgr", "onMinimizeVoip, async to minimize");
if (this.oLN != null) {
this.oLN.uninit();
this.oLN = null;
}
this.guJ.post(new Runnable() {
public final void run() {
o.e(o.this, z);
}
});
return true;
}
x.i("MicroMsg.Voip.VoipMgr", "has phone call cannot mini!");
return false;
}
public final void bKH() {
if (256 == this.oLL.mState || 257 == this.oLL.mState) {
au.HU();
if (com.tencent.mm.model.c.DT().getInt(327945, 0) != 0 || this.oLN.bLD() == null) {
d.O(ad.getContext(), R.l.voip_ignore_warning);
bKJ();
return;
}
au.HU();
com.tencent.mm.model.c.DT().setInt(327945, 1);
com.tencent.mm.ui.widget.a.c a = com.tencent.mm.ui.base.h.a(this.oLN.bLD(), R.l.voip_ignore_warning, R.l.app_tip, new 5(this));
a.setCancelable(false);
a.setCanceledOnTouchOutside(false);
a.show();
}
}
public final void bKI() {
this.oMj = !this.oMj;
if (this.oMj) {
this.oMh.SO();
} else {
aJv();
}
}
public final void bKJ() {
i.bJI().oNg = i.bJI().oNa.oHa.oJX.kpo;
q.a(this.oLT.field_username, this.oLV ? bd.tby : bd.tbx, this.oLU ? 1 : 0, 6, ad.getContext().getString(R.l.voip_callfrom_ignore_msg));
i.bJI().stopRing();
kZ(4108);
this.guJ.postDelayed(new Runnable() {
public final void run() {
o.this.fr(true);
}
}, 2000);
}
public final void bgV() {
if (true == this.lfX || this.oLN == null || this.oLN.bLD() == null) {
x.d("MicroMsg.Voip.VoipMgr", "onCameraError, already show");
} else if (!Build.MANUFACTURER.equalsIgnoreCase("meizu") || com.tencent.mm.compatible.f.b.zV()) {
int i;
x.d("MicroMsg.Voip.VoipMgr", "onCameraError, show dialog");
h hVar = h.mEJ;
Object[] objArr = new Object[2];
if (this.oLV) {
i = 0;
} else {
i = 1;
}
objArr[0] = Integer.valueOf(i);
objArr[1] = Integer.valueOf(0);
hVar.h(11306, objArr);
com.tencent.mm.ui.widget.a.c i2 = com.tencent.mm.ui.base.h.i(this.oLN.bLD(), R.l.voip_no_record_video_permission, R.l.app_tip);
if (i2 == null) {
x.e("MicroMsg.Voip.VoipMgr", "new dialog failed");
return;
}
i2.setCancelable(false);
i2.setCanceledOnTouchOutside(false);
i2.show();
this.lfX = true;
} else {
x.d("MicroMsg.Voip.VoipMgr", "onCameraError, meizu machine");
}
}
private void aJv() {
if (this.oMh == null) {
this.oMi = new ah("faceDetect");
this.oMh = new al(this.oMi.lnJ.getLooper(), new 7(this), true);
}
this.oMh.J(2000, 2000);
this.oMj = false;
}
public final void a(int[] iArr, boolean z, int i) {
ah.A(new 8(this, iArr, z, i));
}
}
|
package org.opentosca.model.instancedata;
import java.net.URI;
import java.net.URISyntaxException;
/**
* Converts internal service and nodeInstanceIDS (the int values inside the DB)
* to external URIs which can be used by external services and vice-versa
*
* @author Marcus Eisele - marcus.eisele@gmail.com
*/
public class IdConverter {
public final static String containerApiRoot = "/containerapi";
public final static String nodeInstancePath = "/instancedata/nodeInstances/";
public final static String serviceInstancePath = "/instancedata/serviceInstances/";
public static Integer nodeInstanceUriToID(URI nodeInstanceID) {
String path = nodeInstanceID.getPath();
if (path.contains(nodeInstancePath) && path.contains(containerApiRoot)) {
path = path.replace(containerApiRoot, "");
path = path.replace(nodeInstancePath, "");
}
try {
return Integer.parseInt(path);
} catch (NumberFormatException e) {
return null;
}
}
public static Integer serviceInstanceUriToID(URI serviceInstanceID) {
String path = serviceInstanceID.getPath();
if (path.contains(containerApiRoot)
&& path.contains(serviceInstancePath)) {
path = path.replace(containerApiRoot, "");
path = path.replace(serviceInstancePath, "");
}
try {
return Integer.parseInt(path);
} catch (NumberFormatException e) {
return null;
}
}
public static URI nodeInstanceIDtoURI(int id) {
try {
return new URI(containerApiRoot + nodeInstancePath + id);
} catch (URISyntaxException e) {
return null;
}
}
public static URI serviceInstanceIDtoURI(int id) {
try {
return new URI(containerApiRoot + serviceInstancePath + id);
} catch (URISyntaxException e) {
return null;
}
}
/**
* Checks if <code>uri</code> is a valid serviceInstanceID-URI in the
* context of the InstanceDataAPI this means that it has one of the
* following formats f.ex. with ID=12345
*
* <pre>
* http://opentosca.org/servicetemplates/instances/12345
* http://localhost:1337/containerapi/instancedata/serviceInstances/12345
* 12345
* </pre>
*
* <b>NULL</b> is considered invalid!
*
* @param uri
* @return true - if uri is a valid serviceInstanceID false - if uri is
* null/invalid
*/
public static boolean isValidServiceInstanceID(URI uri) {
if (uri == null) {
return false;
}
Integer serviceInstanceUriToID = serviceInstanceUriToID(uri);
if (serviceInstanceUriToID != null) {
return true;
}
return false;
}
/**
* Checks if <code>uri</code> is a valid nodeInstanceID-URI in the context
* of the InstanceDataAPI this means that it has one of the following
* formats f.ex. with ID=12345
*
* <pre>
* http://opentosca.org/nodetemplates/instances/12345
* http://localhost:1337/containerapi/instancedata/nodeInstances/12345
* 12345
* </pre>
*
* <b>NULL</b> is considered invalid!
*
* @param uri
* @return true - if uri is a valid nodeInstanceID false - if uri is
* null/invalid
*/
public static boolean isValidNodeInstanceID(URI uri) {
if (uri == null) {
return false;
}
Integer nodeInstanceUriToID = nodeInstanceUriToID(uri);
if (nodeInstanceUriToID != null) {
return true;
}
return false;
}
}
|
package ru.android.messenger.model.utils;
import android.content.Context;
import android.graphics.Bitmap;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import ru.android.messenger.model.Model;
import ru.android.messenger.model.PreferenceManager;
import ru.android.messenger.model.dto.User;
import ru.android.messenger.model.dto.UserFromView;
import ru.android.messenger.model.utils.http.HttpUtils;
import ru.android.messenger.model.utils.http.OnPhotoLoadedListener;
import ru.android.messenger.view.interfaces.ViewWithUsersRecyclerView;
public class UserUtils {
private static List<UserFromView> userFromViewList = new ArrayList<>();
private UserUtils() {
}
public static String getUserPhotoUrl(String login) {
return Model.getServerUrl() + "/api/getUserPhoto/" + login;
}
public static <T extends ViewWithUsersRecyclerView> void convertAndSetUsersToView(
final List<User> users, final T view) {
Context context = view.getContext();
userFromViewList.clear();
for (final User user : users) {
HttpUtils.getUserPhotoAndExecuteAction(user.getLogin(), context,
new OnPhotoLoadedListener() {
@Override
public void onPhotoLoaded(Bitmap photo) {
UserFromView userFromView = createUserFromView(user, photo);
userFromViewList.add(userFromView);
if (userFromViewList.size() == users.size()) {
sortUsersFromFirstNameAndSurname();
view.setUsersList(userFromViewList);
}
}
});
}
}
public static void deleteCurrentUserFromUserList(List<User> users, Context context) {
String currentUserLogin = PreferenceManager.getLogin(context);
for (User user : users) {
if (user.getLogin().equals(currentUserLogin)) {
users.remove(user);
break;
}
}
}
private static void sortUsersFromFirstNameAndSurname() {
Collections.sort(userFromViewList, new Comparator<UserFromView>() {
@Override
public int compare(UserFromView firstUser, UserFromView secondUser) {
String firstName = firstUser.getFirstName() + " " + firstUser.getSurname();
String secondName = secondUser.getFirstName() + " " + secondUser.getSurname();
return firstName.compareToIgnoreCase(secondName);
}
});
}
private static UserFromView createUserFromView(User user, Bitmap userPhoto) {
UserFromView userFromView = new UserFromView();
userFromView.setFirstName(user.getFirstName());
userFromView.setSurname(user.getSurname());
userFromView.setLogin(user.getLogin());
userFromView.setUserPhoto(userPhoto);
return userFromView;
}
}
|
package com.ducph.consoledrawing.command;
public class QuitCommand implements Command {
public static String tipMessage = "Q: Quit the program.";
}
|
package com.it.userportrait.controller;
import com.alibaba.fastjson.JSONObject;
import com.it.userportrait.entity.SandianEntity;
import com.it.userportrait.util.ClickHouseUtils;
import com.it.userportrait.util.DateUtils;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import java.sql.ResultSet;
import java.text.ParseException;
import java.util.*;
@RestController
@RequestMapping("api")
@CrossOrigin
public class CarrierQushiControl {
@RequestMapping(value = "carrierQushiData",method = RequestMethod.POST)
public String sandianData(){
//最近一小时
String sql = "select userid,carrierString,timeinfoString,count(1) as nubmers from carrieruserinfo group by userid,carrierString,timeinfoString";
Set<String> dateSet = new HashSet<String>();
Map<String,Map<String,Long>> dataMap = new HashMap<String,Map<String,Long>>();
try {
ResultSet resultSet = ClickHouseUtils.getQueryResult("test",sql);
while(resultSet.next()){
String carrierString = resultSet.getString("carrierString");
String timeinfoString = resultSet.getString("timeinfoString");
long numbers = resultSet.getLong("nubmers");
dateSet.add(timeinfoString);
Map<String,Long> datainnerMap = dataMap.get(carrierString);
datainnerMap = datainnerMap==null?new HashMap<String,Long>():datainnerMap;
Long data =datainnerMap.get(timeinfoString)==null?0l:datainnerMap.get(timeinfoString);
data = data+ numbers;
datainnerMap.put(timeinfoString,data);
dataMap.put(carrierString,datainnerMap);
}
} catch (Exception e) {
e.printStackTrace();
}
List<String> sortList = new ArrayList<String>(dateSet);
Collections.sort(sortList, new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
int reuslt = 0;
try {
reuslt = DateUtils.compareDate(o1,o2,"yyyyMMddHHmm");
} catch (ParseException e) {
e.printStackTrace();
}
return reuslt;
}
});
Map<String,Long> dateMaptemp = new HashMap<String,Long>();
for(String timeinfoString:sortList){
dateMaptemp.put(timeinfoString,0l);
}
Set<Map.Entry<String,Map<String,Long>>> dataMapSet = dataMap.entrySet();
List<Map<String,Object>> datalist = new ArrayList<Map<String,Object>>();
List<Map<String,Object>> dataMapList = new ArrayList<Map<String,Object>>();//结果
List<List<Object>> listyidong = new ArrayList<List<Object>>();
List<List<Object>> datadianxin = new ArrayList<List<Object>>();
List<List<Object>> dataliantong = new ArrayList<List<Object>>();
for(Map.Entry<String,Map<String,Long>> entry:dataMapSet){
String name = entry.getKey();
Map<String,Long> datamap = entry.getValue();
Set<Map.Entry<String,Long>> setinner = datamap.entrySet();
Map<String,Long> deepCopy = new HashMap<String,Long>();
deepCopy.putAll(dateMaptemp);
for(Map.Entry<String,Long> innerMap : setinner){
String key = innerMap.getKey();
Long value = innerMap.getValue();
deepCopy.put(key,value);
}
for(int j=0;j<sortList.size();j++){
String datetime = sortList.get(j);
Long value = deepCopy.get(datetime);
List<Object> list1 = new ArrayList<Object>();
list1.add(j+1);
list1.add(value);
list1.add(datetime);
if(name.equals("移动")){
listyidong.add(list1);
}else if(name.equals("电信")){
datadianxin.add(list1);
}else if(name.equals("联通")){
dataliantong.add(list1);
}
}
}
List<String> dataList = new ArrayList<String>();
dataList.add("移动");
dataList.add("电信");
dataList.add("联通");
SandianEntity sandianEntity = new SandianEntity();
sandianEntity.setDataList(dataList);
sandianEntity.setList1(listyidong);
sandianEntity.setList2(datadianxin);
sandianEntity.setList3(dataliantong);
String result = JSONObject.toJSONString(sandianEntity);
return result;
}
}
|
package edu.sit.model;
public class Usuario {
private Integer id;
private String login;
private String senha;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public void setSenha(String senha) {
this.senha = senha;
}
public String getLogin() {
return login;
}
public void setLogin(String login) {
this.login = login;
}
public String getSenha() {
return senha;
}
@Override
public String toString() {
return "\nLogin\t\t: "+getLogin();
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((login == null) ? 0 : login.hashCode());
result = prime * result + ((senha == null) ? 0 : senha.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Usuario other = (Usuario) obj;
if (login == null) {
if (other.login != null)
return false;
} else if (!login.equals(other.login))
return false;
if (senha == null) {
if (other.senha != null)
return false;
} else if (!senha.equals(other.senha))
return false;
return true;
}
public Usuario(String login,String senha) {
setLogin(login);
setSenha(senha);
}
public Usuario(Integer id,String login,String senha) {
setLogin(login);
setSenha(senha);
setId(id);
}
}
|
package javax.vecmath;
import java.io.Serializable;
public class GMatrix implements Serializable, Cloneable {
static final long serialVersionUID = 2777097312029690941L;
private static final boolean debug = false;
int nRow;
int nCol;
double[][] values;
private static final double EPS = 1.0E-10D;
public GMatrix(int nRow, int nCol) {
int l;
this.values = new double[nRow][nCol];
this.nRow = nRow;
this.nCol = nCol;
int i;
for (i = 0; i < nRow; i++) {
for (int j = 0; j < nCol; j++)
this.values[i][j] = 0.0D;
}
if (nRow < nCol) {
l = nRow;
} else {
l = nCol;
}
for (i = 0; i < l; i++)
this.values[i][i] = 1.0D;
}
public GMatrix(int nRow, int nCol, double[] matrix) {
this.values = new double[nRow][nCol];
this.nRow = nRow;
this.nCol = nCol;
for (int i = 0; i < nRow; i++) {
for (int j = 0; j < nCol; j++)
this.values[i][j] = matrix[i * nCol + j];
}
}
public GMatrix(GMatrix matrix) {
this.nRow = matrix.nRow;
this.nCol = matrix.nCol;
this.values = new double[this.nRow][this.nCol];
for (int i = 0; i < this.nRow; i++) {
for (int j = 0; j < this.nCol; j++)
this.values[i][j] = matrix.values[i][j];
}
}
public final void mul(GMatrix m1) {
if (this.nCol != m1.nRow || this.nCol != m1.nCol)
throw new MismatchedSizeException(
VecMathI18N.getString("GMatrix0"));
double[][] tmp = new double[this.nRow][this.nCol];
for (int i = 0; i < this.nRow; i++) {
for (int j = 0; j < this.nCol; j++) {
tmp[i][j] = 0.0D;
for (int k = 0; k < this.nCol; k++)
tmp[i][j] = tmp[i][j] + this.values[i][k] * m1.values[k][j];
}
}
this.values = tmp;
}
public final void mul(GMatrix m1, GMatrix m2) {
if (m1.nCol != m2.nRow || this.nRow != m1.nRow || this.nCol != m2.nCol)
throw new MismatchedSizeException(
VecMathI18N.getString("GMatrix1"));
double[][] tmp = new double[this.nRow][this.nCol];
for (int i = 0; i < m1.nRow; i++) {
for (int j = 0; j < m2.nCol; j++) {
tmp[i][j] = 0.0D;
for (int k = 0; k < m1.nCol; k++)
tmp[i][j] = tmp[i][j] + m1.values[i][k] * m2.values[k][j];
}
}
this.values = tmp;
}
public final void mul(GVector v1, GVector v2) {
if (this.nRow < v1.getSize())
throw new MismatchedSizeException(
VecMathI18N.getString("GMatrix2"));
if (this.nCol < v2.getSize())
throw new MismatchedSizeException(
VecMathI18N.getString("GMatrix3"));
for (int i = 0; i < v1.getSize(); i++) {
for (int j = 0; j < v2.getSize(); j++)
this.values[i][j] = v1.values[i] * v2.values[j];
}
}
public final void add(GMatrix m1) {
if (this.nRow != m1.nRow)
throw new MismatchedSizeException(
VecMathI18N.getString("GMatrix4"));
if (this.nCol != m1.nCol)
throw new MismatchedSizeException(
VecMathI18N.getString("GMatrix5"));
for (int i = 0; i < this.nRow; i++) {
for (int j = 0; j < this.nCol; j++)
this.values[i][j] = this.values[i][j] + m1.values[i][j];
}
}
public final void add(GMatrix m1, GMatrix m2) {
if (m2.nRow != m1.nRow)
throw new MismatchedSizeException(
VecMathI18N.getString("GMatrix6"));
if (m2.nCol != m1.nCol)
throw new MismatchedSizeException(
VecMathI18N.getString("GMatrix7"));
if (this.nCol != m1.nCol || this.nRow != m1.nRow)
throw new MismatchedSizeException(
VecMathI18N.getString("GMatrix8"));
for (int i = 0; i < this.nRow; i++) {
for (int j = 0; j < this.nCol; j++)
this.values[i][j] = m1.values[i][j] + m2.values[i][j];
}
}
public final void sub(GMatrix m1) {
if (this.nRow != m1.nRow)
throw new MismatchedSizeException(
VecMathI18N.getString("GMatrix9"));
if (this.nCol != m1.nCol)
throw new MismatchedSizeException(
VecMathI18N.getString("GMatrix28"));
for (int i = 0; i < this.nRow; i++) {
for (int j = 0; j < this.nCol; j++)
this.values[i][j] = this.values[i][j] - m1.values[i][j];
}
}
public final void sub(GMatrix m1, GMatrix m2) {
if (m2.nRow != m1.nRow)
throw new MismatchedSizeException(
VecMathI18N.getString("GMatrix10"));
if (m2.nCol != m1.nCol)
throw new MismatchedSizeException(
VecMathI18N.getString("GMatrix11"));
if (this.nRow != m1.nRow || this.nCol != m1.nCol)
throw new MismatchedSizeException(
VecMathI18N.getString("GMatrix12"));
for (int i = 0; i < this.nRow; i++) {
for (int j = 0; j < this.nCol; j++)
this.values[i][j] = m1.values[i][j] - m2.values[i][j];
}
}
public final void negate() {
for (int i = 0; i < this.nRow; i++) {
for (int j = 0; j < this.nCol; j++)
this.values[i][j] = -this.values[i][j];
}
}
public final void negate(GMatrix m1) {
if (this.nRow != m1.nRow || this.nCol != m1.nCol)
throw new MismatchedSizeException(
VecMathI18N.getString("GMatrix13"));
for (int i = 0; i < this.nRow; i++) {
for (int j = 0; j < this.nCol; j++)
this.values[i][j] = -m1.values[i][j];
}
}
public final void setIdentity() {
int l;
int i;
for (i = 0; i < this.nRow; i++) {
for (int j = 0; j < this.nCol; j++)
this.values[i][j] = 0.0D;
}
if (this.nRow < this.nCol) {
l = this.nRow;
} else {
l = this.nCol;
}
for (i = 0; i < l; i++)
this.values[i][i] = 1.0D;
}
public final void setZero() {
for (int i = 0; i < this.nRow; i++) {
for (int j = 0; j < this.nCol; j++)
this.values[i][j] = 0.0D;
}
}
public final void identityMinus() {
int l;
int i;
for (i = 0; i < this.nRow; i++) {
for (int j = 0; j < this.nCol; j++)
this.values[i][j] = -this.values[i][j];
}
if (this.nRow < this.nCol) {
l = this.nRow;
} else {
l = this.nCol;
}
for (i = 0; i < l; i++)
this.values[i][i] = this.values[i][i] + 1.0D;
}
public final void invert() {
invertGeneral(this);
}
public final void invert(GMatrix m1) {
invertGeneral(m1);
}
public final void copySubMatrix(int rowSource, int colSource, int numRow, int numCol, int rowDest, int colDest, GMatrix target) {
if (this != target) {
for (int i = 0; i < numRow; i++) {
for (int j = 0; j < numCol; j++)
target.values[rowDest + i][colDest + j] =
this.values[rowSource + i][colSource + j];
}
} else {
double[][] tmp = new double[numRow][numCol];
int i;
for (i = 0; i < numRow; i++) {
for (int j = 0; j < numCol; j++)
tmp[i][j] = this.values[rowSource + i][colSource + j];
}
for (i = 0; i < numRow; i++) {
for (int j = 0; j < numCol; j++)
target.values[rowDest + i][colDest + j] = tmp[i][j];
}
}
}
public final void setSize(int nRow, int nCol) {
int maxRow, maxCol;
double[][] tmp = new double[nRow][nCol];
if (this.nRow < nRow) {
maxRow = this.nRow;
} else {
maxRow = nRow;
}
if (this.nCol < nCol) {
maxCol = this.nCol;
} else {
maxCol = nCol;
}
for (int i = 0; i < maxRow; i++) {
for (int j = 0; j < maxCol; j++)
tmp[i][j] = this.values[i][j];
}
this.nRow = nRow;
this.nCol = nCol;
this.values = tmp;
}
public final void set(double[] matrix) {
for (int i = 0; i < this.nRow; i++) {
for (int j = 0; j < this.nCol; j++)
this.values[i][j] = matrix[this.nCol * i + j];
}
}
public final void set(Matrix3f m1) {
if (this.nCol < 3 || this.nRow < 3) {
this.nCol = 3;
this.nRow = 3;
this.values = new double[this.nRow][this.nCol];
}
this.values[0][0] = m1.m00;
this.values[0][1] = m1.m01;
this.values[0][2] = m1.m02;
this.values[1][0] = m1.m10;
this.values[1][1] = m1.m11;
this.values[1][2] = m1.m12;
this.values[2][0] = m1.m20;
this.values[2][1] = m1.m21;
this.values[2][2] = m1.m22;
for (int i = 3; i < this.nRow; i++) {
for (int j = 3; j < this.nCol; j++)
this.values[i][j] = 0.0D;
}
}
public final void set(Matrix3d m1) {
if (this.nRow < 3 || this.nCol < 3) {
this.values = new double[3][3];
this.nRow = 3;
this.nCol = 3;
}
this.values[0][0] = m1.m00;
this.values[0][1] = m1.m01;
this.values[0][2] = m1.m02;
this.values[1][0] = m1.m10;
this.values[1][1] = m1.m11;
this.values[1][2] = m1.m12;
this.values[2][0] = m1.m20;
this.values[2][1] = m1.m21;
this.values[2][2] = m1.m22;
for (int i = 3; i < this.nRow; i++) {
for (int j = 3; j < this.nCol; j++)
this.values[i][j] = 0.0D;
}
}
public final void set(Matrix4f m1) {
if (this.nRow < 4 || this.nCol < 4) {
this.values = new double[4][4];
this.nRow = 4;
this.nCol = 4;
}
this.values[0][0] = m1.m00;
this.values[0][1] = m1.m01;
this.values[0][2] = m1.m02;
this.values[0][3] = m1.m03;
this.values[1][0] = m1.m10;
this.values[1][1] = m1.m11;
this.values[1][2] = m1.m12;
this.values[1][3] = m1.m13;
this.values[2][0] = m1.m20;
this.values[2][1] = m1.m21;
this.values[2][2] = m1.m22;
this.values[2][3] = m1.m23;
this.values[3][0] = m1.m30;
this.values[3][1] = m1.m31;
this.values[3][2] = m1.m32;
this.values[3][3] = m1.m33;
for (int i = 4; i < this.nRow; i++) {
for (int j = 4; j < this.nCol; j++)
this.values[i][j] = 0.0D;
}
}
public final void set(Matrix4d m1) {
if (this.nRow < 4 || this.nCol < 4) {
this.values = new double[4][4];
this.nRow = 4;
this.nCol = 4;
}
this.values[0][0] = m1.m00;
this.values[0][1] = m1.m01;
this.values[0][2] = m1.m02;
this.values[0][3] = m1.m03;
this.values[1][0] = m1.m10;
this.values[1][1] = m1.m11;
this.values[1][2] = m1.m12;
this.values[1][3] = m1.m13;
this.values[2][0] = m1.m20;
this.values[2][1] = m1.m21;
this.values[2][2] = m1.m22;
this.values[2][3] = m1.m23;
this.values[3][0] = m1.m30;
this.values[3][1] = m1.m31;
this.values[3][2] = m1.m32;
this.values[3][3] = m1.m33;
for (int i = 4; i < this.nRow; i++) {
for (int j = 4; j < this.nCol; j++)
this.values[i][j] = 0.0D;
}
}
public final void set(GMatrix m1) {
if (this.nRow < m1.nRow || this.nCol < m1.nCol) {
this.nRow = m1.nRow;
this.nCol = m1.nCol;
this.values = new double[this.nRow][this.nCol];
}
int i;
for (i = 0; i < Math.min(this.nRow, m1.nRow); i++) {
for (int j = 0; j < Math.min(this.nCol, m1.nCol); j++)
this.values[i][j] = m1.values[i][j];
}
for (i = m1.nRow; i < this.nRow; i++) {
for (int j = m1.nCol; j < this.nCol; j++)
this.values[i][j] = 0.0D;
}
}
public final int getNumRow() {
return this.nRow;
}
public final int getNumCol() {
return this.nCol;
}
public final double getElement(int row, int column) {
return this.values[row][column];
}
public final void setElement(int row, int column, double value) {
this.values[row][column] = value;
}
public final void getRow(int row, double[] array) {
for (int i = 0; i < this.nCol; i++)
array[i] = this.values[row][i];
}
public final void getRow(int row, GVector vector) {
if (vector.getSize() < this.nCol)
vector.setSize(this.nCol);
for (int i = 0; i < this.nCol; i++)
vector.values[i] = this.values[row][i];
}
public final void getColumn(int col, double[] array) {
for (int i = 0; i < this.nRow; i++)
array[i] = this.values[i][col];
}
public final void getColumn(int col, GVector vector) {
if (vector.getSize() < this.nRow)
vector.setSize(this.nRow);
for (int i = 0; i < this.nRow; i++)
vector.values[i] = this.values[i][col];
}
public final void get(Matrix3d m1) {
if (this.nRow < 3 || this.nCol < 3) {
m1.setZero();
if (this.nCol > 0) {
if (this.nRow > 0) {
m1.m00 = this.values[0][0];
if (this.nRow > 1) {
m1.m10 = this.values[1][0];
if (this.nRow > 2)
m1.m20 = this.values[2][0];
}
}
if (this.nCol > 1) {
if (this.nRow > 0) {
m1.m01 = this.values[0][1];
if (this.nRow > 1) {
m1.m11 = this.values[1][1];
if (this.nRow > 2)
m1.m21 = this.values[2][1];
}
}
if (this.nCol > 2 &&
this.nRow > 0) {
m1.m02 = this.values[0][2];
if (this.nRow > 1) {
m1.m12 = this.values[1][2];
if (this.nRow > 2)
m1.m22 = this.values[2][2];
}
}
}
}
} else {
m1.m00 = this.values[0][0];
m1.m01 = this.values[0][1];
m1.m02 = this.values[0][2];
m1.m10 = this.values[1][0];
m1.m11 = this.values[1][1];
m1.m12 = this.values[1][2];
m1.m20 = this.values[2][0];
m1.m21 = this.values[2][1];
m1.m22 = this.values[2][2];
}
}
public final void get(Matrix3f m1) {
if (this.nRow < 3 || this.nCol < 3) {
m1.setZero();
if (this.nCol > 0) {
if (this.nRow > 0) {
m1.m00 = (float)this.values[0][0];
if (this.nRow > 1) {
m1.m10 = (float)this.values[1][0];
if (this.nRow > 2)
m1.m20 = (float)this.values[2][0];
}
}
if (this.nCol > 1) {
if (this.nRow > 0) {
m1.m01 = (float)this.values[0][1];
if (this.nRow > 1) {
m1.m11 = (float)this.values[1][1];
if (this.nRow > 2)
m1.m21 = (float)this.values[2][1];
}
}
if (this.nCol > 2 &&
this.nRow > 0) {
m1.m02 = (float)this.values[0][2];
if (this.nRow > 1) {
m1.m12 = (float)this.values[1][2];
if (this.nRow > 2)
m1.m22 = (float)this.values[2][2];
}
}
}
}
} else {
m1.m00 = (float)this.values[0][0];
m1.m01 = (float)this.values[0][1];
m1.m02 = (float)this.values[0][2];
m1.m10 = (float)this.values[1][0];
m1.m11 = (float)this.values[1][1];
m1.m12 = (float)this.values[1][2];
m1.m20 = (float)this.values[2][0];
m1.m21 = (float)this.values[2][1];
m1.m22 = (float)this.values[2][2];
}
}
public final void get(Matrix4d m1) {
if (this.nRow < 4 || this.nCol < 4) {
m1.setZero();
if (this.nCol > 0) {
if (this.nRow > 0) {
m1.m00 = this.values[0][0];
if (this.nRow > 1) {
m1.m10 = this.values[1][0];
if (this.nRow > 2) {
m1.m20 = this.values[2][0];
if (this.nRow > 3)
m1.m30 = this.values[3][0];
}
}
}
if (this.nCol > 1) {
if (this.nRow > 0) {
m1.m01 = this.values[0][1];
if (this.nRow > 1) {
m1.m11 = this.values[1][1];
if (this.nRow > 2) {
m1.m21 = this.values[2][1];
if (this.nRow > 3)
m1.m31 = this.values[3][1];
}
}
}
if (this.nCol > 2) {
if (this.nRow > 0) {
m1.m02 = this.values[0][2];
if (this.nRow > 1) {
m1.m12 = this.values[1][2];
if (this.nRow > 2) {
m1.m22 = this.values[2][2];
if (this.nRow > 3)
m1.m32 = this.values[3][2];
}
}
}
if (this.nCol > 3 &&
this.nRow > 0) {
m1.m03 = this.values[0][3];
if (this.nRow > 1) {
m1.m13 = this.values[1][3];
if (this.nRow > 2) {
m1.m23 = this.values[2][3];
if (this.nRow > 3)
m1.m33 = this.values[3][3];
}
}
}
}
}
}
} else {
m1.m00 = this.values[0][0];
m1.m01 = this.values[0][1];
m1.m02 = this.values[0][2];
m1.m03 = this.values[0][3];
m1.m10 = this.values[1][0];
m1.m11 = this.values[1][1];
m1.m12 = this.values[1][2];
m1.m13 = this.values[1][3];
m1.m20 = this.values[2][0];
m1.m21 = this.values[2][1];
m1.m22 = this.values[2][2];
m1.m23 = this.values[2][3];
m1.m30 = this.values[3][0];
m1.m31 = this.values[3][1];
m1.m32 = this.values[3][2];
m1.m33 = this.values[3][3];
}
}
public final void get(Matrix4f m1) {
if (this.nRow < 4 || this.nCol < 4) {
m1.setZero();
if (this.nCol > 0) {
if (this.nRow > 0) {
m1.m00 = (float)this.values[0][0];
if (this.nRow > 1) {
m1.m10 = (float)this.values[1][0];
if (this.nRow > 2) {
m1.m20 = (float)this.values[2][0];
if (this.nRow > 3)
m1.m30 = (float)this.values[3][0];
}
}
}
if (this.nCol > 1) {
if (this.nRow > 0) {
m1.m01 = (float)this.values[0][1];
if (this.nRow > 1) {
m1.m11 = (float)this.values[1][1];
if (this.nRow > 2) {
m1.m21 = (float)this.values[2][1];
if (this.nRow > 3)
m1.m31 = (float)this.values[3][1];
}
}
}
if (this.nCol > 2) {
if (this.nRow > 0) {
m1.m02 = (float)this.values[0][2];
if (this.nRow > 1) {
m1.m12 = (float)this.values[1][2];
if (this.nRow > 2) {
m1.m22 = (float)this.values[2][2];
if (this.nRow > 3)
m1.m32 = (float)this.values[3][2];
}
}
}
if (this.nCol > 3 &&
this.nRow > 0) {
m1.m03 = (float)this.values[0][3];
if (this.nRow > 1) {
m1.m13 = (float)this.values[1][3];
if (this.nRow > 2) {
m1.m23 = (float)this.values[2][3];
if (this.nRow > 3)
m1.m33 = (float)this.values[3][3];
}
}
}
}
}
}
} else {
m1.m00 = (float)this.values[0][0];
m1.m01 = (float)this.values[0][1];
m1.m02 = (float)this.values[0][2];
m1.m03 = (float)this.values[0][3];
m1.m10 = (float)this.values[1][0];
m1.m11 = (float)this.values[1][1];
m1.m12 = (float)this.values[1][2];
m1.m13 = (float)this.values[1][3];
m1.m20 = (float)this.values[2][0];
m1.m21 = (float)this.values[2][1];
m1.m22 = (float)this.values[2][2];
m1.m23 = (float)this.values[2][3];
m1.m30 = (float)this.values[3][0];
m1.m31 = (float)this.values[3][1];
m1.m32 = (float)this.values[3][2];
m1.m33 = (float)this.values[3][3];
}
}
public final void get(GMatrix m1) {
int nc;
int nr;
if (this.nCol < m1.nCol) {
nc = this.nCol;
} else {
nc = m1.nCol;
}
if (this.nRow < m1.nRow) {
nr = this.nRow;
} else {
nr = m1.nRow;
}
int i;
for (i = 0; i < nr; i++) {
for (int k = 0; k < nc; k++)
m1.values[i][k] = this.values[i][k];
}
for (i = nr; i < m1.nRow; i++) {
for (int k = 0; k < m1.nCol; k++)
m1.values[i][k] = 0.0D;
}
for (int j = nc; j < m1.nCol; j++) {
for (i = 0; i < nr; i++)
m1.values[i][j] = 0.0D;
}
}
public final void setRow(int row, double[] array) {
for (int i = 0; i < this.nCol; i++)
this.values[row][i] = array[i];
}
public final void setRow(int row, GVector vector) {
for (int i = 0; i < this.nCol; i++)
this.values[row][i] = vector.values[i];
}
public final void setColumn(int col, double[] array) {
for (int i = 0; i < this.nRow; i++)
this.values[i][col] = array[i];
}
public final void setColumn(int col, GVector vector) {
for (int i = 0; i < this.nRow; i++)
this.values[i][col] = vector.values[i];
}
public final void mulTransposeBoth(GMatrix m1, GMatrix m2) {
if (m1.nRow != m2.nCol || this.nRow != m1.nCol || this.nCol != m2.nRow)
throw new MismatchedSizeException(
VecMathI18N.getString("GMatrix14"));
if (m1 == this || m2 == this) {
double[][] tmp = new double[this.nRow][this.nCol];
for (int i = 0; i < this.nRow; i++) {
for (int j = 0; j < this.nCol; j++) {
tmp[i][j] = 0.0D;
for (int k = 0; k < m1.nRow; k++)
tmp[i][j] = tmp[i][j] + m1.values[k][i] * m2.values[j][k];
}
}
this.values = tmp;
} else {
for (int i = 0; i < this.nRow; i++) {
for (int j = 0; j < this.nCol; j++) {
this.values[i][j] = 0.0D;
for (int k = 0; k < m1.nRow; k++)
this.values[i][j] = this.values[i][j] + m1.values[k][i] * m2.values[j][k];
}
}
}
}
public final void mulTransposeRight(GMatrix m1, GMatrix m2) {
if (m1.nCol != m2.nCol || this.nCol != m2.nRow || this.nRow != m1.nRow)
throw new MismatchedSizeException(
VecMathI18N.getString("GMatrix15"));
if (m1 == this || m2 == this) {
double[][] tmp = new double[this.nRow][this.nCol];
for (int i = 0; i < this.nRow; i++) {
for (int j = 0; j < this.nCol; j++) {
tmp[i][j] = 0.0D;
for (int k = 0; k < m1.nCol; k++)
tmp[i][j] = tmp[i][j] + m1.values[i][k] * m2.values[j][k];
}
}
this.values = tmp;
} else {
for (int i = 0; i < this.nRow; i++) {
for (int j = 0; j < this.nCol; j++) {
this.values[i][j] = 0.0D;
for (int k = 0; k < m1.nCol; k++)
this.values[i][j] = this.values[i][j] + m1.values[i][k] * m2.values[j][k];
}
}
}
}
public final void mulTransposeLeft(GMatrix m1, GMatrix m2) {
if (m1.nRow != m2.nRow || this.nCol != m2.nCol || this.nRow != m1.nCol)
throw new MismatchedSizeException(
VecMathI18N.getString("GMatrix16"));
if (m1 == this || m2 == this) {
double[][] tmp = new double[this.nRow][this.nCol];
for (int i = 0; i < this.nRow; i++) {
for (int j = 0; j < this.nCol; j++) {
tmp[i][j] = 0.0D;
for (int k = 0; k < m1.nRow; k++)
tmp[i][j] = tmp[i][j] + m1.values[k][i] * m2.values[k][j];
}
}
this.values = tmp;
} else {
for (int i = 0; i < this.nRow; i++) {
for (int j = 0; j < this.nCol; j++) {
this.values[i][j] = 0.0D;
for (int k = 0; k < m1.nRow; k++)
this.values[i][j] = this.values[i][j] + m1.values[k][i] * m2.values[k][j];
}
}
}
}
public final void transpose() {
if (this.nRow != this.nCol) {
int i = this.nRow;
this.nRow = this.nCol;
this.nCol = i;
double[][] tmp = new double[this.nRow][this.nCol];
for (i = 0; i < this.nRow; i++) {
for (int j = 0; j < this.nCol; j++)
tmp[i][j] = this.values[j][i];
}
this.values = tmp;
} else {
for (int i = 0; i < this.nRow; i++) {
for (int j = 0; j < i; j++) {
double swap = this.values[i][j];
this.values[i][j] = this.values[j][i];
this.values[j][i] = swap;
}
}
}
}
public final void transpose(GMatrix m1) {
if (this.nRow != m1.nCol || this.nCol != m1.nRow)
throw new MismatchedSizeException(
VecMathI18N.getString("GMatrix17"));
if (m1 != this) {
for (int i = 0; i < this.nRow; i++) {
for (int j = 0; j < this.nCol; j++)
this.values[i][j] = m1.values[j][i];
}
} else {
transpose();
}
}
public String toString() {
StringBuffer buffer = new StringBuffer(this.nRow * this.nCol * 8);
for (int i = 0; i < this.nRow; i++) {
for (int j = 0; j < this.nCol; j++)
buffer.append(this.values[i][j]).append(" ");
buffer.append("\n");
}
return buffer.toString();
}
private static void checkMatrix(GMatrix m) {
for (int i = 0; i < m.nRow; i++) {
for (int j = 0; j < m.nCol; j++) {
if (Math.abs(m.values[i][j]) < 1.0E-10D) {
System.out.print(" 0.0 ");
} else {
System.out.print(" " + m.values[i][j]);
}
}
System.out.print("\n");
}
}
public int hashCode() {
long bits = 1L;
bits = VecMathUtil.hashLongBits(bits, this.nRow);
bits = VecMathUtil.hashLongBits(bits, this.nCol);
for (int i = 0; i < this.nRow; i++) {
for (int j = 0; j < this.nCol; j++)
bits = VecMathUtil.hashDoubleBits(bits, this.values[i][j]);
}
return VecMathUtil.hashFinish(bits);
}
public boolean equals(GMatrix m1) {
try {
if (this.nRow != m1.nRow || this.nCol != m1.nCol)
return false;
for (int i = 0; i < this.nRow; i++) {
for (int j = 0; j < this.nCol; j++) {
if (this.values[i][j] != m1.values[i][j])
return false;
}
}
return true;
} catch (NullPointerException e2) {
return false;
}
}
public boolean equals(Object o1) {
try {
GMatrix m2 = (GMatrix)o1;
if (this.nRow != m2.nRow || this.nCol != m2.nCol)
return false;
for (int i = 0; i < this.nRow; i++) {
for (int j = 0; j < this.nCol; j++) {
if (this.values[i][j] != m2.values[i][j])
return false;
}
}
return true;
} catch (ClassCastException e1) {
return false;
} catch (NullPointerException e2) {
return false;
}
}
public boolean epsilonEquals(GMatrix m1, float epsilon) {
return epsilonEquals(m1, epsilon);
}
public boolean epsilonEquals(GMatrix m1, double epsilon) {
if (this.nRow != m1.nRow || this.nCol != m1.nCol)
return false;
for (int i = 0; i < this.nRow; i++) {
for (int j = 0; j < this.nCol; j++) {
double diff = this.values[i][j] - m1.values[i][j];
if (((diff < 0.0D) ? -diff : diff) > epsilon)
return false;
}
}
return true;
}
public final double trace() {
int l;
if (this.nRow < this.nCol) {
l = this.nRow;
} else {
l = this.nCol;
}
double t = 0.0D;
for (int i = 0; i < l; i++)
t += this.values[i][i];
return t;
}
public final int SVD(GMatrix U, GMatrix W, GMatrix V) {
if (this.nCol != V.nCol || this.nCol != V.nRow)
throw new MismatchedSizeException(
VecMathI18N.getString("GMatrix18"));
if (this.nRow != U.nRow || this.nRow != U.nCol)
throw new MismatchedSizeException(
VecMathI18N.getString("GMatrix25"));
if (this.nRow != W.nRow || this.nCol != W.nCol)
throw new MismatchedSizeException(
VecMathI18N.getString("GMatrix26"));
if (this.nRow == 2 && this.nCol == 2 &&
this.values[1][0] == 0.0D) {
U.setIdentity();
V.setIdentity();
if (this.values[0][1] == 0.0D)
return 2;
double[] sinl = new double[1];
double[] sinr = new double[1];
double[] cosl = new double[1];
double[] cosr = new double[1];
double[] single_values = new double[2];
single_values[0] = this.values[0][0];
single_values[1] = this.values[1][1];
compute_2X2(this.values[0][0], this.values[0][1], this.values[1][1],
single_values, sinl, cosl, sinr, cosr, 0);
update_u(0, U, cosl, sinl);
update_v(0, V, cosr, sinr);
return 2;
}
return computeSVD(this, U, W, V);
}
public final int LUD(GMatrix LU, GVector permutation) {
int size = LU.nRow * LU.nCol;
double[] temp = new double[size];
int[] even_row_exchange = new int[1];
int[] row_perm = new int[LU.nRow];
if (this.nRow != this.nCol)
throw new MismatchedSizeException(
VecMathI18N.getString("GMatrix19"));
if (this.nRow != LU.nRow)
throw new MismatchedSizeException(
VecMathI18N.getString("GMatrix27"));
if (this.nCol != LU.nCol)
throw new MismatchedSizeException(
VecMathI18N.getString("GMatrix27"));
if (LU.nRow != permutation.getSize())
throw new MismatchedSizeException(
VecMathI18N.getString("GMatrix20"));
int i;
for (i = 0; i < this.nRow; i++) {
for (int j = 0; j < this.nCol; j++)
temp[i * this.nCol + j] = this.values[i][j];
}
if (!luDecomposition(LU.nRow, temp, row_perm, even_row_exchange))
throw new SingularMatrixException(
VecMathI18N.getString("GMatrix21"));
for (i = 0; i < this.nRow; i++) {
for (int j = 0; j < this.nCol; j++)
LU.values[i][j] = temp[i * this.nCol + j];
}
for (i = 0; i < LU.nRow; i++)
permutation.values[i] = row_perm[i];
return even_row_exchange[0];
}
public final void setScale(double scale) {
int l;
if (this.nRow < this.nCol) {
l = this.nRow;
} else {
l = this.nCol;
}
int i;
for (i = 0; i < this.nRow; i++) {
for (int j = 0; j < this.nCol; j++)
this.values[i][j] = 0.0D;
}
for (i = 0; i < l; i++)
this.values[i][i] = scale;
}
final void invertGeneral(GMatrix m1) {
int size = m1.nRow * m1.nCol;
double[] temp = new double[size];
double[] result = new double[size];
int[] row_perm = new int[m1.nRow];
int[] even_row_exchange = new int[1];
if (m1.nRow != m1.nCol)
throw new MismatchedSizeException(
VecMathI18N.getString("GMatrix22"));
int i;
for (i = 0; i < this.nRow; i++) {
for (int j = 0; j < this.nCol; j++)
temp[i * this.nCol + j] = m1.values[i][j];
}
if (!luDecomposition(m1.nRow, temp, row_perm, even_row_exchange))
throw new SingularMatrixException(
VecMathI18N.getString("GMatrix21"));
for (i = 0; i < size; i++)
result[i] = 0.0D;
for (i = 0; i < this.nCol; i++)
result[i + i * this.nCol] = 1.0D;
luBacksubstitution(m1.nRow, temp, row_perm, result);
for (i = 0; i < this.nRow; i++) {
for (int j = 0; j < this.nCol; j++)
this.values[i][j] = result[i * this.nCol + j];
}
}
static boolean luDecomposition(int dim, double[] matrix0, int[] row_perm, int[] even_row_xchg) {
double[] row_scale = new double[dim];
int ptr = 0;
int rs = 0;
even_row_xchg[0] = 1;
int i = dim;
while (i-- != 0) {
double big = 0.0D;
int k = dim;
while (k-- != 0) {
double temp = matrix0[ptr++];
temp = Math.abs(temp);
if (temp > big)
big = temp;
}
if (big == 0.0D)
return false;
row_scale[rs++] = 1.0D / big;
}
int mtx = 0;
for (int j = 0; j < dim; j++) {
for (i = 0; i < j; i++) {
int target = mtx + dim * i + j;
double sum = matrix0[target];
int k = i;
int p1 = mtx + dim * i;
int p2 = mtx + j;
while (k-- != 0) {
sum -= matrix0[p1] * matrix0[p2];
p1++;
p2 += dim;
}
matrix0[target] = sum;
}
double big = 0.0D;
int imax = -1;
for (i = j; i < dim; i++) {
int target = mtx + dim * i + j;
double sum = matrix0[target];
int k = j;
int p1 = mtx + dim * i;
int p2 = mtx + j;
while (k-- != 0) {
sum -= matrix0[p1] * matrix0[p2];
p1++;
p2 += dim;
}
matrix0[target] = sum;
double temp;
if ((temp = row_scale[i] * Math.abs(sum)) >= big) {
big = temp;
imax = i;
}
}
if (imax < 0)
throw new RuntimeException(VecMathI18N.getString("GMatrix24"));
if (j != imax) {
int k = dim;
int p1 = mtx + dim * imax;
int p2 = mtx + dim * j;
while (k-- != 0) {
double temp = matrix0[p1];
matrix0[p1++] = matrix0[p2];
matrix0[p2++] = temp;
}
row_scale[imax] = row_scale[j];
even_row_xchg[0] = -even_row_xchg[0];
}
row_perm[j] = imax;
if (matrix0[mtx + dim * j + j] == 0.0D)
return false;
if (j != dim - 1) {
double temp = 1.0D / matrix0[mtx + dim * j + j];
int target = mtx + dim * (j + 1) + j;
i = dim - 1 - j;
while (i-- != 0) {
matrix0[target] = matrix0[target] * temp;
target += dim;
}
}
}
return true;
}
static void luBacksubstitution(int dim, double[] matrix1, int[] row_perm, double[] matrix2) {
int rp = 0;
for (int k = 0; k < dim; k++) {
int cv = k;
int ii = -1;
int i;
for (i = 0; i < dim; i++) {
int ip = row_perm[rp + i];
double sum = matrix2[cv + dim * ip];
matrix2[cv + dim * ip] = matrix2[cv + dim * i];
if (ii >= 0) {
int rv = i * dim;
for (int j = ii; j <= i - 1; j++)
sum -= matrix1[rv + j] * matrix2[cv + dim * j];
} else if (sum != 0.0D) {
ii = i;
}
matrix2[cv + dim * i] = sum;
}
for (i = 0; i < dim; i++) {
int ri = dim - 1 - i;
int rv = dim * ri;
double tt = 0.0D;
for (int j = 1; j <= i; j++)
tt += matrix1[rv + dim - j] * matrix2[cv + dim * (dim - j)];
matrix2[cv + dim * ri] = (matrix2[cv + dim * ri] - tt) / matrix1[rv + ri];
}
}
}
static int computeSVD(GMatrix mat, GMatrix U, GMatrix W, GMatrix V) {
int eLength, sLength, vecLength;
GMatrix tmp = new GMatrix(mat.nRow, mat.nCol);
GMatrix u = new GMatrix(mat.nRow, mat.nCol);
GMatrix v = new GMatrix(mat.nRow, mat.nCol);
GMatrix m = new GMatrix(mat);
if (m.nRow >= m.nCol) {
sLength = m.nCol;
eLength = m.nCol - 1;
} else {
sLength = m.nRow;
eLength = m.nRow;
}
if (m.nRow > m.nCol) {
vecLength = m.nRow;
} else {
vecLength = m.nCol;
}
double[] vec = new double[vecLength];
double[] single_values = new double[sLength];
double[] e = new double[eLength];
int rank = 0;
U.setIdentity();
V.setIdentity();
int nr = m.nRow;
int nc = m.nCol;
for (int si = 0; si < sLength; si++) {
if (nr > 1) {
double mag = 0.0D;
int k;
for (k = 0; k < nr; k++)
mag += m.values[k + si][si] * m.values[k + si][si];
mag = Math.sqrt(mag);
if (m.values[si][si] == 0.0D) {
vec[0] = mag;
} else {
vec[0] = m.values[si][si] + d_sign(mag, m.values[si][si]);
}
for (k = 1; k < nr; k++)
vec[k] = m.values[si + k][si];
double scale = 0.0D;
for (k = 0; k < nr; k++)
scale += vec[k] * vec[k];
scale = 2.0D / scale;
int j;
for (j = si; j < m.nRow; j++) {
for (int n = si; n < m.nRow; n++)
u.values[j][n] = -scale * vec[j - si] * vec[n - si];
}
for (k = si; k < m.nRow; k++)
u.values[k][k] = u.values[k][k] + 1.0D;
double t = 0.0D;
for (k = si; k < m.nRow; k++)
t += u.values[si][k] * m.values[k][si];
m.values[si][si] = t;
for (j = si; j < m.nRow; j++) {
for (int n = si + 1; n < m.nCol; n++) {
tmp.values[j][n] = 0.0D;
for (k = si; k < m.nCol; k++)
tmp.values[j][n] = tmp.values[j][n] + u.values[j][k] * m.values[k][n];
}
}
for (j = si; j < m.nRow; j++) {
for (int n = si + 1; n < m.nCol; n++)
m.values[j][n] = tmp.values[j][n];
}
for (j = si; j < m.nRow; j++) {
for (int n = 0; n < m.nCol; n++) {
tmp.values[j][n] = 0.0D;
for (k = si; k < m.nCol; k++)
tmp.values[j][n] = tmp.values[j][n] + u.values[j][k] * U.values[k][n];
}
}
for (j = si; j < m.nRow; j++) {
for (int n = 0; n < m.nCol; n++)
U.values[j][n] = tmp.values[j][n];
}
nr--;
}
if (nc > 2) {
double mag = 0.0D;
int k;
for (k = 1; k < nc; k++)
mag += m.values[si][si + k] * m.values[si][si + k];
mag = Math.sqrt(mag);
if (m.values[si][si + 1] == 0.0D) {
vec[0] = mag;
} else {
vec[0] = m.values[si][si + 1] +
d_sign(mag, m.values[si][si + 1]);
}
for (k = 1; k < nc - 1; k++)
vec[k] = m.values[si][si + k + 1];
double scale = 0.0D;
for (k = 0; k < nc - 1; k++)
scale += vec[k] * vec[k];
scale = 2.0D / scale;
int j;
for (j = si + 1; j < nc; j++) {
for (int n = si + 1; n < m.nCol; n++)
v.values[j][n] = -scale * vec[j - si - 1] * vec[n - si - 1];
}
for (k = si + 1; k < m.nCol; k++)
v.values[k][k] = v.values[k][k] + 1.0D;
double t = 0.0D;
for (k = si; k < m.nCol; k++)
t += v.values[k][si + 1] * m.values[si][k];
m.values[si][si + 1] = t;
for (j = si + 1; j < m.nRow; j++) {
for (int n = si + 1; n < m.nCol; n++) {
tmp.values[j][n] = 0.0D;
for (k = si + 1; k < m.nCol; k++)
tmp.values[j][n] = tmp.values[j][n] + v.values[k][n] * m.values[j][k];
}
}
for (j = si + 1; j < m.nRow; j++) {
for (int n = si + 1; n < m.nCol; n++)
m.values[j][n] = tmp.values[j][n];
}
for (j = 0; j < m.nRow; j++) {
for (int n = si + 1; n < m.nCol; n++) {
tmp.values[j][n] = 0.0D;
for (k = si + 1; k < m.nCol; k++)
tmp.values[j][n] = tmp.values[j][n] + v.values[k][n] * V.values[j][k];
}
}
for (j = 0; j < m.nRow; j++) {
for (int n = si + 1; n < m.nCol; n++)
V.values[j][n] = tmp.values[j][n];
}
nc--;
}
}
int i;
for (i = 0; i < sLength; i++)
single_values[i] = m.values[i][i];
for (i = 0; i < eLength; i++)
e[i] = m.values[i][i + 1];
if (m.nRow == 2 && m.nCol == 2) {
double[] cosl = new double[1];
double[] cosr = new double[1];
double[] sinl = new double[1];
double[] sinr = new double[1];
compute_2X2(single_values[0], e[0], single_values[1],
single_values, sinl, cosl, sinr, cosr, 0);
update_u(0, U, cosl, sinl);
update_v(0, V, cosr, sinr);
return 2;
}
compute_qr(0, e.length - 1, single_values, e, U, V);
rank = single_values.length;
return rank;
}
static void compute_qr(int start, int end, double[] s, double[] e, GMatrix u, GMatrix v) {
double[] cosl = new double[1];
double[] cosr = new double[1];
double[] sinl = new double[1];
double[] sinr = new double[1];
GMatrix m = new GMatrix(u.nCol, v.nRow);
int MAX_INTERATIONS = 2;
double CONVERGE_TOL = 4.89E-15D;
double c_b48 = 1.0D;
double c_b71 = -1.0D;
boolean converged = false;
double f = 0.0D;
double g = 0.0D;
for (int k = 0; k < 2 && !converged; k++) {
int j;
for (j = start; j <= end; j++) {
if (j == start) {
int sl;
if (e.length == s.length) {
sl = end;
} else {
sl = end + 1;
}
double shift = compute_shift(s[sl - 1], e[end], s[sl]);
f = (Math.abs(s[j]) - shift) * (
d_sign(c_b48, s[j]) + shift / s[j]);
g = e[j];
}
double r = compute_rot(f, g, sinr, cosr);
if (j != start)
e[j - 1] = r;
f = cosr[0] * s[j] + sinr[0] * e[j];
e[j] = cosr[0] * e[j] - sinr[0] * s[j];
g = sinr[0] * s[j + 1];
s[j + 1] = cosr[0] * s[j + 1];
update_v(j, v, cosr, sinr);
r = compute_rot(f, g, sinl, cosl);
s[j] = r;
f = cosl[0] * e[j] + sinl[0] * s[j + 1];
s[j + 1] = cosl[0] * s[j + 1] - sinl[0] * e[j];
if (j < end) {
g = sinl[0] * e[j + 1];
e[j + 1] = cosl[0] * e[j + 1];
}
update_u(j, u, cosl, sinl);
}
if (s.length == e.length) {
double r = compute_rot(f, g, sinr, cosr);
f = cosr[0] * s[j] + sinr[0] * e[j];
e[j] = cosr[0] * e[j] - sinr[0] * s[j];
s[j + 1] = cosr[0] * s[j + 1];
update_v(j, v, cosr, sinr);
}
while (end - start > 1 && Math.abs(e[end]) < 4.89E-15D)
end--;
for (int n = end - 2; n > start; n--) {
if (Math.abs(e[n]) < 4.89E-15D) {
compute_qr(n + 1, end, s, e, u, v);
end = n - 1;
while (end - start > 1 &&
Math.abs(e[end]) < 4.89E-15D)
end--;
}
}
if (end - start <= 1 && Math.abs(e[start + 1]) < 4.89E-15D)
converged = true;
}
if (Math.abs(e[1]) < 4.89E-15D) {
compute_2X2(s[start], e[start], s[start + 1], s,
sinl, cosl, sinr, cosr, 0);
e[start] = 0.0D;
e[start + 1] = 0.0D;
}
int i = start;
update_u(i, u, cosl, sinl);
update_v(i, v, cosr, sinr);
}
private static void print_se(double[] s, double[] e) {
System.out.println("\ns =" + s[0] + " " + s[1] + " " + s[2]);
System.out.println("e =" + e[0] + " " + e[1]);
}
private static void update_v(int index, GMatrix v, double[] cosr, double[] sinr) {
for (int j = 0; j < v.nRow; j++) {
double vtemp = v.values[j][index];
v.values[j][index] =
cosr[0] * vtemp + sinr[0] * v.values[j][index + 1];
v.values[j][index + 1] =
-sinr[0] * vtemp + cosr[0] * v.values[j][index + 1];
}
}
private static void chase_up(double[] s, double[] e, int k, GMatrix v) {
double[] cosr = new double[1];
double[] sinr = new double[1];
GMatrix t = new GMatrix(v.nRow, v.nCol);
GMatrix m = new GMatrix(v.nRow, v.nCol);
double f = e[k];
double g = s[k];
int i;
for (i = k; i > 0; i--) {
double r = compute_rot(f, g, sinr, cosr);
f = -e[i - 1] * sinr[0];
g = s[i - 1];
s[i] = r;
e[i - 1] = e[i - 1] * cosr[0];
update_v_split(i, k + 1, v, cosr, sinr, t, m);
}
s[i + 1] = compute_rot(f, g, sinr, cosr);
update_v_split(i, k + 1, v, cosr, sinr, t, m);
}
private static void chase_across(double[] s, double[] e, int k, GMatrix u) {
double[] cosl = new double[1];
double[] sinl = new double[1];
GMatrix t = new GMatrix(u.nRow, u.nCol);
GMatrix m = new GMatrix(u.nRow, u.nCol);
double g = e[k];
double f = s[k + 1];
int i;
for (i = k; i < u.nCol - 2; i++) {
double r = compute_rot(f, g, sinl, cosl);
g = -e[i + 1] * sinl[0];
f = s[i + 2];
s[i + 1] = r;
e[i + 1] = e[i + 1] * cosl[0];
update_u_split(k, i + 1, u, cosl, sinl, t, m);
}
s[i + 1] = compute_rot(f, g, sinl, cosl);
update_u_split(k, i + 1, u, cosl, sinl, t, m);
}
private static void update_v_split(int topr, int bottomr, GMatrix v, double[] cosr, double[] sinr, GMatrix t, GMatrix m) {
for (int j = 0; j < v.nRow; j++) {
double vtemp = v.values[j][topr];
v.values[j][topr] = cosr[0] * vtemp - sinr[0] * v.values[j][bottomr];
v.values[j][bottomr] = sinr[0] * vtemp + cosr[0] * v.values[j][bottomr];
}
System.out.println("topr =" + topr);
System.out.println("bottomr =" + bottomr);
System.out.println("cosr =" + cosr[0]);
System.out.println("sinr =" + sinr[0]);
System.out.println("\nm =");
checkMatrix(m);
System.out.println("\nv =");
checkMatrix(t);
m.mul(m, t);
System.out.println("\nt*m =");
checkMatrix(m);
}
private static void update_u_split(int topr, int bottomr, GMatrix u, double[] cosl, double[] sinl, GMatrix t, GMatrix m) {
for (int j = 0; j < u.nCol; j++) {
double utemp = u.values[topr][j];
u.values[topr][j] = cosl[0] * utemp - sinl[0] * u.values[bottomr][j];
u.values[bottomr][j] = sinl[0] * utemp + cosl[0] * u.values[bottomr][j];
}
System.out.println("\nm=");
checkMatrix(m);
System.out.println("\nu=");
checkMatrix(t);
m.mul(t, m);
System.out.println("\nt*m=");
checkMatrix(m);
}
private static void update_u(int index, GMatrix u, double[] cosl, double[] sinl) {
for (int j = 0; j < u.nCol; j++) {
double utemp = u.values[index][j];
u.values[index][j] =
cosl[0] * utemp + sinl[0] * u.values[index + 1][j];
u.values[index + 1][j] =
-sinl[0] * utemp + cosl[0] * u.values[index + 1][j];
}
}
private static void print_m(GMatrix m, GMatrix u, GMatrix v) {
GMatrix mtmp = new GMatrix(m.nCol, m.nRow);
mtmp.mul(u, mtmp);
mtmp.mul(mtmp, v);
System.out.println("\n m = \n" + toString(mtmp));
}
private static String toString(GMatrix m) {
StringBuffer buffer = new StringBuffer(m.nRow * m.nCol * 8);
for (int i = 0; i < m.nRow; i++) {
for (int j = 0; j < m.nCol; j++) {
if (Math.abs(m.values[i][j]) < 1.0E-9D) {
buffer.append("0.0000 ");
} else {
buffer.append(m.values[i][j]).append(" ");
}
}
buffer.append("\n");
}
return buffer.toString();
}
private static void print_svd(double[] s, double[] e, GMatrix u, GMatrix v) {
GMatrix mtmp = new GMatrix(u.nCol, v.nRow);
System.out.println(" \ns = ");
int i;
for (i = 0; i < s.length; i++)
System.out.println(" " + s[i]);
System.out.println(" \ne = ");
for (i = 0; i < e.length; i++)
System.out.println(" " + e[i]);
System.out.println(" \nu = \n" + u.toString());
System.out.println(" \nv = \n" + v.toString());
mtmp.setIdentity();
for (i = 0; i < s.length; i++)
mtmp.values[i][i] = s[i];
for (i = 0; i < e.length; i++)
mtmp.values[i][i + 1] = e[i];
System.out.println(" \nm = \n" + mtmp.toString());
mtmp.mulTransposeLeft(u, mtmp);
mtmp.mulTransposeRight(mtmp, v);
System.out.println(" \n u.transpose*m*v.transpose = \n" +
mtmp.toString());
}
static double max(double a, double b) {
if (a > b)
return a;
return b;
}
static double min(double a, double b) {
if (a < b)
return a;
return b;
}
static double compute_shift(double f, double g, double h) {
double ssmin, fa = Math.abs(f);
double ga = Math.abs(g);
double ha = Math.abs(h);
double fhmn = min(fa, ha);
double fhmx = max(fa, ha);
if (fhmn == 0.0D) {
ssmin = 0.0D;
if (fhmx != 0.0D)
double d = min(fhmx, ga) / max(fhmx, ga);
} else if (ga < fhmx) {
double as = fhmn / fhmx + 1.0D;
double at = (fhmx - fhmn) / fhmx;
double d__1 = ga / fhmx;
double au = d__1 * d__1;
double c = 2.0D / (Math.sqrt(as * as + au) + Math.sqrt(at * at + au));
ssmin = fhmn * c;
} else {
double au = fhmx / ga;
if (au == 0.0D) {
ssmin = fhmn * fhmx / ga;
} else {
double as = fhmn / fhmx + 1.0D;
double at = (fhmx - fhmn) / fhmx;
double d__1 = as * au;
double d__2 = at * au;
double c = 1.0D / (Math.sqrt(d__1 * d__1 + 1.0D) +
Math.sqrt(d__2 * d__2 + 1.0D));
ssmin = fhmn * c * au;
ssmin += ssmin;
}
}
return ssmin;
}
static int compute_2X2(double f, double g, double h, double[] single_values, double[] snl, double[] csl, double[] snr, double[] csr, int index) {
boolean swap;
double c_b3 = 2.0D;
double c_b4 = 1.0D;
double ssmax = single_values[0];
double ssmin = single_values[1];
double clt = 0.0D;
double crt = 0.0D;
double slt = 0.0D;
double srt = 0.0D;
double tsign = 0.0D;
double ft = f;
double fa = Math.abs(ft);
double ht = h;
double ha = Math.abs(h);
int pmax = 1;
if (ha > fa) {
swap = true;
} else {
swap = false;
}
if (swap) {
pmax = 3;
double temp = ft;
ft = ht;
ht = temp;
temp = fa;
fa = ha;
ha = temp;
}
double gt = g;
double ga = Math.abs(gt);
if (ga == 0.0D) {
single_values[1] = ha;
single_values[0] = fa;
clt = 1.0D;
crt = 1.0D;
slt = 0.0D;
srt = 0.0D;
} else {
boolean gasmal = true;
if (ga > fa) {
pmax = 2;
if (fa / ga < 1.0E-10D) {
gasmal = false;
ssmax = ga;
if (ha > 1.0D) {
ssmin = fa / ga / ha;
} else {
ssmin = fa / ga * ha;
}
clt = 1.0D;
slt = ht / gt;
srt = 1.0D;
crt = ft / gt;
}
}
if (gasmal) {
double l, r, d = fa - ha;
if (d == fa) {
l = 1.0D;
} else {
l = d / fa;
}
double m = gt / ft;
double t = 2.0D - l;
double mm = m * m;
double tt = t * t;
double s = Math.sqrt(tt + mm);
if (l == 0.0D) {
r = Math.abs(m);
} else {
r = Math.sqrt(l * l + mm);
}
double a = (s + r) * 0.5D;
if (ga > fa) {
pmax = 2;
if (fa / ga < 1.0E-10D) {
gasmal = false;
ssmax = ga;
if (ha > 1.0D) {
ssmin = fa / ga / ha;
} else {
ssmin = fa / ga * ha;
}
clt = 1.0D;
slt = ht / gt;
srt = 1.0D;
crt = ft / gt;
}
}
if (gasmal) {
d = fa - ha;
if (d == fa) {
l = 1.0D;
} else {
l = d / fa;
}
m = gt / ft;
t = 2.0D - l;
mm = m * m;
tt = t * t;
s = Math.sqrt(tt + mm);
if (l == 0.0D) {
r = Math.abs(m);
} else {
r = Math.sqrt(l * l + mm);
}
a = (s + r) * 0.5D;
ssmin = ha / a;
ssmax = fa * a;
if (mm == 0.0D) {
if (l == 0.0D) {
t = d_sign(c_b3, ft) * d_sign(c_b4, gt);
} else {
t = gt / d_sign(d, ft) + m / t;
}
} else {
t = (m / (s + t) + m / (r + l)) * (a + 1.0D);
}
l = Math.sqrt(t * t + 4.0D);
crt = 2.0D / l;
srt = t / l;
clt = (crt + srt * m) / a;
slt = ht / ft * srt / a;
}
}
if (swap) {
csl[0] = srt;
snl[0] = crt;
csr[0] = slt;
snr[0] = clt;
} else {
csl[0] = clt;
snl[0] = slt;
csr[0] = crt;
snr[0] = srt;
}
if (pmax == 1)
tsign = d_sign(c_b4, csr[0]) *
d_sign(c_b4, csl[0]) * d_sign(c_b4, f);
if (pmax == 2)
tsign = d_sign(c_b4, snr[0]) *
d_sign(c_b4, csl[0]) * d_sign(c_b4, g);
if (pmax == 3)
tsign = d_sign(c_b4, snr[0]) *
d_sign(c_b4, snl[0]) * d_sign(c_b4, h);
single_values[index] = d_sign(ssmax, tsign);
double d__1 = tsign * d_sign(c_b4, f) * d_sign(c_b4, h);
single_values[index + 1] = d_sign(ssmin, d__1);
}
return 0;
}
static double compute_rot(double f, double g, double[] sin, double[] cos) {
double cs, sn, r, safmn2 = 2.002083095183101E-146D;
double safmx2 = 4.9947976805055876E145D;
if (g == 0.0D) {
cs = 1.0D;
sn = 0.0D;
r = f;
} else if (f == 0.0D) {
cs = 0.0D;
sn = 1.0D;
r = g;
} else {
double f1 = f;
double g1 = g;
double scale = max(Math.abs(f1), Math.abs(g1));
if (scale >= 4.9947976805055876E145D) {
int count = 0;
while (scale >= 4.9947976805055876E145D) {
count++;
f1 *= 2.002083095183101E-146D;
g1 *= 2.002083095183101E-146D;
scale = max(Math.abs(f1), Math.abs(g1));
}
r = Math.sqrt(f1 * f1 + g1 * g1);
cs = f1 / r;
sn = g1 / r;
int i__1 = count;
for (int i = 1; i <= count; i++)
r *= 4.9947976805055876E145D;
} else if (scale <= 2.002083095183101E-146D) {
int count = 0;
while (scale <= 2.002083095183101E-146D) {
count++;
f1 *= 4.9947976805055876E145D;
g1 *= 4.9947976805055876E145D;
scale = max(Math.abs(f1), Math.abs(g1));
}
r = Math.sqrt(f1 * f1 + g1 * g1);
cs = f1 / r;
sn = g1 / r;
int i__1 = count;
for (int i = 1; i <= count; i++)
r *= 2.002083095183101E-146D;
} else {
r = Math.sqrt(f1 * f1 + g1 * g1);
cs = f1 / r;
sn = g1 / r;
}
if (Math.abs(f) > Math.abs(g) && cs < 0.0D) {
cs = -cs;
sn = -sn;
r = -r;
}
}
sin[0] = sn;
cos[0] = cs;
return r;
}
static double d_sign(double a, double b) {
double x = (a >= 0.0D) ? a : -a;
return (b >= 0.0D) ? x : -x;
}
public Object clone() {
GMatrix m1 = null;
try {
m1 = (GMatrix)super.clone();
} catch (CloneNotSupportedException e) {
throw new InternalError();
}
m1.values = new double[this.nRow][this.nCol];
for (int i = 0; i < this.nRow; i++) {
for (int j = 0; j < this.nCol; j++)
m1.values[i][j] = this.values[i][j];
}
return m1;
}
}
/* Location: C:\Users\BSV\AppData\Local\Temp\Rar$DRa6216.20396\Preview\Preview.jar!\javax\vecmath\GMatrix.class
* Java compiler version: 8 (52.0)
* JD-Core Version: 1.1.3
*/
|
import java.util.List;
import models.*;
import org.junit.After;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import play.Logger;
import play.test.Fixtures;
import play.test.UnitTest;
import utils.Helpers;
public class UserTest extends UnitTest {
@BeforeClass
public static void loadDB() {
Fixtures.deleteAllModels();
}
@Before
public void setup() {
// Testing on whole mockup database, more realistic data and even easier
// tests. Still testing properly because these data could contain situations
// which could be forgoten when setuping test data. Downside of this
// approach is that when the mockup database changes these tests need to be
// adjusted.
Helpers.fillData();
}
@After
public void teardown() {
Fixtures.deleteAllModels();
}
@Test
public void testCreation() {
assertEquals(9, User.findAll().size());
User user = new User("Name named", "donNot@spam.me", "iDonTkn0w", true);
user.save();
assertEquals(10, User.findAll().size());
}
@Test
public void testDeletion() {
User user = User.findByEmail("skyler@white.com");
// number blogs present in database is 5
assertEquals(5, Blog.findAll().size());
assertEquals(9, User.findAll().size());
List<User> all = User.findAll();
Logger.info("Deleting user " + user);
for (Blog myBlog : user.blogs) {
for (User someBody : all) {
if (someBody != user) {
// Logger.info("Checking user " + someBody + " if he is subscribed.");
if (someBody.subs.contains(myBlog)) {
Logger.info("Found user " + someBody + " subscribed to this blog (he is subscribed to " + someBody.subs.size() + " blogs).");
someBody.subs.remove(myBlog);
someBody.save();
Logger.info("He is subscribed to " + someBody.subs.size() + " blogs now.");
}
}
}
user.blogs.remove(myBlog);
myBlog.delete();
}
user.save();
// delete all users comments from other blog posts which are not in this
// object, but would reference back to this object
Logger.info("Deleting comments of user " + user);
List<Comment> comments = Comment.findAll();
for (Comment comment : comments) {
if (comment.user == user) {
comment.delete();
}
}
// delete all his friendships with anybody else again this is outside this
// object referencing back to it
// all subchilds object of this object will be destroyed automaticly, but we
// need to ensura nothing outside this object is referencing back to it
for (User someBody : all) {
if (someBody != user) {
if (someBody.friends.contains(user)) {
Logger.info("User has it as friend "+someBody.friends.size());
someBody.friends.remove(user);
someBody.save();
Logger.info("Updated number of friends "+someBody.friends.size());
}
}
}
// delete this user from sessions
Logged.cleanSessions();
user.delete();
assertEquals(8, User.findAll().size());
// number of posts should drop automaticly from 5 to 3
assertEquals(3, Blog.findAll().size());
}
}
|
package kr.ko.nexmain.server.MissingU.common.utils;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import kr.ko.nexmain.server.MissingU.common.Constants;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpMethod;
public class NetworkUtil {
protected static Logger log = LoggerFactory.getLogger(NetworkUtil.class);
public static final int BUFFER_SIZE = 4096;
public static class HttpResult {
boolean result;
String resultMsg;
int httpStatusCode;
String content;
public boolean isResult() {
return result;
}
public void setResult(boolean result) {
this.result = result;
}
public String getResultMsg() {
return resultMsg;
}
public void setResultMsg(String resultMsg) {
this.resultMsg = resultMsg;
}
public int getHttpStatusCode() {
return httpStatusCode;
}
public void setHttpStatusCode(int httpStatusCode) {
this.httpStatusCode = httpStatusCode;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
}
public static HttpResult requestHttp(HttpMethod method, String url, String content) {
HttpResult result = new HttpResult();
DefaultHttpClient client = new DefaultHttpClient();
String DEV_SERVER_URL = Constants.TSTORE.DEBUG_MODE ? Constants.TSTORE.RECEIPTS_VARIFICATION_URL_DEBUG : Constants.TSTORE.RECEIPTS_VARIFICATION_URL;
HttpPost httpPostRequest = new HttpPost(DEV_SERVER_URL);
StringEntity se;
try {
se = new StringEntity(content, "UTF-8");
httpPostRequest.setEntity(se);
httpPostRequest.setHeader("Content-type", "application/json");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
result.setResult(false);
result.setHttpStatusCode(-1);
result.setResultMsg("인코딩 오류 입니다.");
return result;
}
try {
HttpResponse resp = client.execute(httpPostRequest);
result.setHttpStatusCode(resp.getStatusLine().getStatusCode());
if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_OK)
{
HttpEntity respEntity = resp.getEntity();
if (respEntity != null)
{
try
{
InputStream ins = respEntity.getContent();
ByteArrayOutputStream bs = new ByteArrayOutputStream();
int i = ins.read();
while (i != -1) {
bs.write(i);
i = ins.read();
}
result.setResult(true);
result.setResultMsg("");
result.setContent(bs.toString());
} catch (IllegalStateException e) {
e.printStackTrace();
result.setResult(false);
result.setResultMsg("서버 오류 입니다. " + e.getMessage());
} catch (IOException e) {
e.printStackTrace();
result.setResult(false);
result.setResultMsg("서버 오류 입니다. " + e.getMessage());
}
}
}
} catch (ClientProtocolException e) {
e.printStackTrace();
result.setResult(false);
result.setResultMsg("서버 오류 입니다. " + e.getMessage());
} catch (IOException e) {
e.printStackTrace();
result.setResult(false);
result.setResultMsg("서버 오류 입니다. " + e.getMessage());
}
return result;
}
}
|
package com.company.annotation;
public class Apple {
@CustomAnnotation("张三")
@SuppressWarnings("unused")
private String name;
@SuppressWarnings("unused")
@CustomAnnotation("北京朝阳")
private String address ;
}
|
public class ListInventory {
// Constructor
public ListInventory(int id, String newName, String newDesc) {
this.id = id;
this.name = newName;
this.desc = newDesc;
}
//Getters
//Setters
public int getID() {
return this.id;
}
public String getName() {
return this.name;
}
public String getDesc() {
return this.desc;
}
public ListInventory getNext() {
return this.next;
}
public void setNext(ListInventory newNext) {
this.next = newNext;
}
public void buy(){
this.name = "";
this.desc = "";
}
public String toString() {
return this.id + ": " + this.name + " - " + this.desc;
}
//privates:
private int id;
private String name;
private String desc;
private ListInventory next = null;
}
|
package model;
public enum Hobby {
Sports,
Reading,
Music
}
|
package com.example.testhub.domain;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "tests")
@NoArgsConstructor
@AllArgsConstructor
@Getter
public class Test {
@Id
@Column(name = "id_test")
private Long id;
@Column(name = "test_name")
private String testName;
}
|
package com.tencent.recovery.storage;
import com.tencent.recovery.log.RecoveryLog;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel.MapMode;
public class MMappedFileStorage {
private int currentIndex;
private int vhG;
private File vhH;
private File vhI;
private MappedByteBuffer vhJ;
private RandomAccessFile vhK;
public final synchronized void f(byte[] bArr, boolean z) {
try {
if (this.vhK == null) {
if (!this.vhI.exists()) {
this.vhI.createNewFile();
}
this.vhK = new RandomAccessFile(this.vhI, "rw");
}
if (this.vhJ == null) {
this.vhJ = this.vhK.getChannel().map(MapMode.READ_WRITE, 0, (long) this.vhG);
}
if (!(this.vhI == null || this.vhJ == null)) {
if (this.currentIndex + bArr.length > this.vhG || z) {
this.vhJ.force();
try {
this.vhK.close();
} catch (IOException e) {
}
j(this.vhI, this.vhH);
this.currentIndex = 4;
this.vhI.delete();
this.vhI.createNewFile();
this.vhK = new RandomAccessFile(this.vhI, "rw");
this.vhJ = this.vhK.getChannel().map(MapMode.READ_WRITE, 0, (long) this.vhG);
this.vhJ.putInt(this.currentIndex - 4);
}
if (bArr.length >= 0) {
this.vhJ.position(this.currentIndex);
this.vhJ.put(bArr);
this.vhJ.position(0);
this.currentIndex += bArr.length;
this.vhJ.putInt(this.currentIndex - 4);
}
}
} catch (Throwable e2) {
RecoveryLog.printErrStackTrace("Recovery.MMappedFileStorage", e2, "appendToBuffer", new Object[0]);
}
return;
}
private static void j(File file, File file2) {
FileOutputStream fileOutputStream;
Throwable e;
int i = 0;
DataInputStream dataInputStream;
try {
int readInt;
dataInputStream = new DataInputStream(new FileInputStream(file));
try {
readInt = dataInputStream.readInt();
fileOutputStream = new FileOutputStream(file2, true);
} catch (Exception e2) {
e = e2;
fileOutputStream = null;
try {
RecoveryLog.printErrStackTrace("Recovery.MMappedFileStorage", e, "copyAppendTargetFile", new Object[0]);
if (dataInputStream != null) {
try {
dataInputStream.close();
} catch (IOException e3) {
}
}
if (fileOutputStream == null) {
try {
fileOutputStream.close();
} catch (IOException e4) {
}
}
} catch (Throwable th) {
e = th;
if (dataInputStream != null) {
try {
dataInputStream.close();
} catch (IOException e5) {
}
}
if (fileOutputStream != null) {
try {
fileOutputStream.close();
} catch (IOException e6) {
}
}
throw e;
}
} catch (Throwable th2) {
e = th2;
fileOutputStream = null;
if (dataInputStream != null) {
try {
dataInputStream.close();
} catch (IOException e52) {
}
}
if (fileOutputStream != null) {
try {
fileOutputStream.close();
} catch (IOException e62) {
}
}
throw e;
}
try {
byte[] bArr = new byte[1024];
while (true) {
int i2 = i;
if (i2 + 1024 > readInt) {
i = readInt - i2;
} else {
i = 1024;
}
if (i > 0) {
i = dataInputStream.read(bArr, 0, i);
if (i > 0) {
fileOutputStream.write(bArr, 0, i);
i += i2;
}
}
try {
dataInputStream.close();
} catch (IOException e7) {
}
try {
fileOutputStream.close();
return;
} catch (IOException e8) {
return;
}
}
} catch (Exception e9) {
e = e9;
RecoveryLog.printErrStackTrace("Recovery.MMappedFileStorage", e, "copyAppendTargetFile", new Object[0]);
if (dataInputStream != null) {
try {
dataInputStream.close();
} catch (IOException e32) {
}
}
if (fileOutputStream == null) {
try {
fileOutputStream.close();
} catch (IOException e42) {
}
}
}
} catch (Exception e10) {
e = e10;
fileOutputStream = null;
dataInputStream = null;
RecoveryLog.printErrStackTrace("Recovery.MMappedFileStorage", e, "copyAppendTargetFile", new Object[0]);
if (dataInputStream != null) {
try {
dataInputStream.close();
} catch (IOException e322) {
}
}
if (fileOutputStream == null) {
try {
fileOutputStream.close();
} catch (IOException e422) {
}
}
} catch (Throwable th3) {
e = th3;
fileOutputStream = null;
dataInputStream = null;
if (dataInputStream != null) {
try {
dataInputStream.close();
} catch (IOException e522) {
}
}
if (fileOutputStream != null) {
try {
fileOutputStream.close();
} catch (IOException e622) {
}
}
throw e;
}
}
}
|
package com.sbadc.survivalera.adapters;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ActivityOptions;
import android.content.Context;
import android.content.Intent;
import android.util.Pair;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.cardview.widget.CardView;
import androidx.recyclerview.widget.RecyclerView;
import com.sbadc.survivalera.R;
import com.sbadc.survivalera.TournamentDetailsActivity;
import com.sbadc.survivalera.models.ModelTournament;
import com.squareup.picasso.Picasso;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import cn.iwgang.countdownview.CountdownView;
public class AdapterTournament extends RecyclerView.Adapter<AdapterTournament.MyHolder>{
private Context context;
private List<ModelTournament> tournamentList;
public AdapterTournament(Context context, List<ModelTournament> tournamentList) {
this.context = context;
this.tournamentList = tournamentList;
}
@NonNull
@Override
public MyHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.row_tournament,parent,false);
return new MyHolder(view);
}
@SuppressLint("SetTextI18n")
@Override
public void onBindViewHolder(@NonNull final MyHolder holder, int position) {
// String uid = tournamentList.get(position).getUid();
// String phone = tournamentList.get(position).getPhone();
// String email = tournamentList.get(position).getEmail();
final String tourID = tournamentList.get(position).getTourID();
final String tourImage = tournamentList.get(position).getTourImage();
String tourName = tournamentList.get(position).getTourName();
String tourDate = tournamentList.get(position).getTourDate();
String tourTime = tournamentList.get(position).getTourTime();
String tourWinningPrize = tournamentList.get(position).getTourWinningPrize();
String tourPerKillPrize = tournamentList.get(position).getTourPerKillPrize();
String tourEntryFee = tournamentList.get(position).getTourEntryFee();
String tourVersion = tournamentList.get(position).getTourVersion();
String tourType = tournamentList.get(position).getTourType();
String tourMap = tournamentList.get(position).getTourMap();
// String tourCreatedTime = tournamentList.get(position).getTourCreatedTime();
String tourVerified = tournamentList.get(position).getTourVerified();
// String extraAdvice = tournamentList.get(position).getExtraAdvice();
final String playerJoined = tournamentList.get(position).getPlayerJoined();
final String totalPlayer = tournamentList.get(position).getTotalPlayer();
// String perfectTime = tournamentList.get(position).getPerfectTime();
/*
Calendar calendar = Calendar.getInstance(Locale.getDefault());
calendar.setTimeInMillis(Long.parseLong(tourDate));
final String formatedDate = android.text.format.DateFormat.format("dd/MM/yyy", calendar).toString();
Calendar calendar2 = Calendar.getInstance(Locale.getDefault());
calendar2.setTimeInMillis(Long.parseLong(tourDate));
final String formatedTime = android.text.format.DateFormat.format("hh:mm aa", calendar2).toString();
*/
holder.tourNameTV.setText(tourName);
holder.tourDateTV.setText("Date: "+tourDate);
holder.tourTimeTV.setText("Time: "+tourTime);
holder.tourWinningPrizeTV.setText(tourWinningPrize + " Rs.");
holder.tourPerKillPrizeTV.setText(tourPerKillPrize + " Rs.");
holder.tourEntryTV.setText(tourEntryFee + " Rs.");
holder.tourVersionTV.setText(tourVersion);
holder.tourTypeTV.setText(tourType);
holder.tourMapTV.setText(tourMap);
holder.playersJoinedTV.setText("Players Joined : " + playerJoined + " / " + totalPlayer);
if(tourImage.equals("noImage")){
holder.tournamentCardIV.setVisibility(View.GONE);
}else{
try{
Picasso.get().load(tourImage).placeholder(R.drawable.rupee_60px).into(holder.tournamentCardIV);
}catch (Exception e){
Toast.makeText(context, "Can't load the image.", Toast.LENGTH_SHORT).show();
}
}
/*if(!(extraAdvice.length() == 0)){
holder.extraAdviseTv.setVisibility(View.VISIBLE);
holder.extraAdviseTv.setText(extraAdvice);
holder.extraAdviseTv.setAlpha(1);
}else{
holder.extraAdviseTv.setAlpha(0);
holder.extraAdviseTv.setVisibility(View.GONE);
}*/
if(tourVerified.equals("yes")){
holder.joinTournamentButton.setEnabled(true);
holder.joinTournamentButton.setText("Join");
}else{
holder.joinTournamentButton.setEnabled(false);
holder.joinTournamentButton.setAlpha(0.5f);
holder.joinTournamentButton.setText("Coming Soon");
}
if (Integer.parseInt(playerJoined) >= Integer.parseInt(totalPlayer)){
holder.joinTournamentButton.setEnabled(false);
holder.joinTournamentButton.setAlpha(0.7f);
holder.joinTournamentButton.setText("Full");
}
/*HERE
OTHER
FUNCTIONALITY
WILL
COME
FROM
SURVIVAL
ERA
ADMIN
APP
PROJECT*/
holder.joinTournamentButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(context, TournamentDetailsActivity.class);
intent.putExtra("tourID",tourID);
Pair[] pairs = new Pair[11];
pairs[0] = new Pair<View, String >(holder.tournamentCardIV,"tourImage");
pairs[1] = new Pair<View, String >(holder.tourNameTV,"tourName");
pairs[2] = new Pair<View, String >(holder.tourDateTV,"tourDate");
pairs[3] = new Pair<View, String >(holder.tourTimeTV,"tourTime");
pairs[4] = new Pair<View, String >(holder.winningCV,"winningTran");
pairs[5] = new Pair<View, String >(holder.perkillCv,"perkillTran");
pairs[6] = new Pair<View, String >(holder.entryCV,"entryTran");
pairs[7] = new Pair<View, String >(holder.mapCV,"mapTran");
pairs[8] = new Pair<View, String >(holder.versionCV,"versionTran");
pairs[9] = new Pair<View, String >(holder.typeCV,"typeTran");
pairs[10] = new Pair<View, String >(holder.joinTournamentButton,"tourJoin");
ActivityOptions activityOptions = ActivityOptions.makeSceneTransitionAnimation((Activity)context,pairs);
context.startActivity(intent,activityOptions.toBundle());
}
});
}
@Override
public int getItemCount() {
return tournamentList.size();
}
static class MyHolder extends RecyclerView.ViewHolder{
ImageView tournamentCardIV;
TextView tourNameTV,tourDateTV,tourTimeTV,
tourWinningPrizeTV,tourPerKillPrizeTV,tourEntryTV,
tourVersionTV,tourTypeTV,tourMapTV,playersJoinedTV,extraAdviseTv;
Button joinTournamentButton;
//for using shared animation this code should be used.....
CardView winningCV,perkillCv,entryCV,mapCV,versionCV,typeCV;
MyHolder(@NonNull View itemView){
super(itemView);
tournamentCardIV = itemView.findViewById(R.id.tournamentCardImage);
tourNameTV = itemView.findViewById(R.id.tournamentCardGameName);
tourDateTV = itemView.findViewById(R.id.tournamentCardDate);
tourTimeTV = itemView.findViewById(R.id.tournamentCardTime);
tourWinningPrizeTV = itemView.findViewById(R.id.tournamentCardWinningPrize);
tourPerKillPrizeTV = itemView.findViewById(R.id.tournamentCardPerKillPrize);
tourMapTV = itemView.findViewById(R.id.tournamentCardMap);
tourVersionTV = itemView.findViewById(R.id.tournamentCardVersion);
tourTypeTV = itemView.findViewById(R.id.tournamentCardMatchType);
tourEntryTV = itemView.findViewById(R.id.tournamentCardEntryPrize);
playersJoinedTV = itemView.findViewById(R.id.playerJoinedTv);
// extraAdviseTv = itemView.findViewById(R.id.extraAdviseTv);
joinTournamentButton = itemView.findViewById(R.id.joinMatchBtn);
winningCV = itemView.findViewById(R.id.winningPrizeCV);
perkillCv = itemView.findViewById(R.id.perKillCV);
entryCV = itemView.findViewById(R.id.entryCV);
mapCV = itemView.findViewById(R.id.mapCV);
versionCV = itemView.findViewById(R.id.versionCV);
typeCV = itemView.findViewById(R.id.typeCV);
}
}
}
|
package com.tencent.mm.plugin.sns.ui;
import com.tencent.mm.g.a.qn;
import com.tencent.mm.sdk.b.b;
import com.tencent.mm.sdk.b.c;
class av$2 extends c<qn> {
final /* synthetic */ av ocj;
av$2(av avVar) {
this.ocj = avVar;
this.sFo = qn.class.getName().hashCode();
}
public final /* synthetic */ boolean a(b bVar) {
qn qnVar = (qn) bVar;
if (qnVar instanceof qn) {
String str = qnVar.cbc.id;
if (qnVar.cbc.type == 1) {
av.c(this.ocj, str);
} else if (qnVar.cbc.type == 2) {
av.d(this.ocj, qnVar.cbc.id);
}
}
return false;
}
}
|
package gr.james.influence.game;
import gr.james.influence.api.Graph;
import gr.james.influence.graph.ImmutableGraph;
import gr.james.influence.tournament.Utils;
import gr.james.influence.util.Finals;
import org.slf4j.Logger;
import java.util.ArrayList;
import java.util.List;
public abstract class Player {
public static final String L_PLAYER_EXCEPTION = "Player {} triggered exception on graph {} with definition {}\n{}";
public static final String L_PLAYER_WAITING = "Been waiting {} seconds for {} to terminate gracefully.";
protected static final Logger log = Finals.LOG; // TODO: This should probably be private
private final Object lock = new Object();
private boolean interrupted = false;
/**
* <p>Tests whether the player has been interrupted. The game mechanism requests player interruption when the
* player has exhausted the available time for execution. When this flag is set to {@code true}, further moves
* submitted by the player will be ignored and this is an indication that the player must terminate gracefully.
* This flag is an alternative way of time tracking besides {@link GameDefinition#getExecution() getExecution()}
* method. The interrupted status of the player is cleared by this method. In other words, if this method were to be
* called twice in succession, the second call would return {@code false} (unless the current player were
* interrupted again, after the first call had cleared its interrupted status and before the second call had
* examined it). This method is also called after the player has finished processing, in order to clear the
* interrupt flag.</p>
*
* @return {@code true} if the player was interrupted and must terminate, otherwise {@code false}
*/
protected final boolean isInterrupted() {
synchronized (lock) {
boolean last_interrupt = this.interrupted;
this.interrupted = false;
return last_interrupt;
}
}
/**
* <p>Sets the interrupt flag to {@code true}. The player needs to invoke {@link #isInterrupted()} to access this
* flag.</p>
*/
public final void interrupt() {
synchronized (lock) {
this.interrupted = true;
}
}
protected abstract void suggestMove(Graph g, GameDefinition d, MovePointer movePtr);
/**
* <p>Invokes {@link #suggestMove(Graph, GameDefinition, MovePointer)} on a separate thread.</p>
*
* @param g The {@link Graph} object that will be passed in {@code suggestMove()} as {@link ImmutableGraph}
* @param d The {@link GameDefinition} object that will be passed directly in {@code suggestMove()}
* @return the last move that was submitted in time from the player
*/
public final Move getMove(Graph g, GameDefinition d) {
final Graph finalGraph = ImmutableGraph.decorate(g);
final MovePointer movePtr = new MovePointer();
List<Throwable> thrown = new ArrayList<>();
Thread t = new Thread(() -> suggestMove(finalGraph, d, movePtr));
t.setUncaughtExceptionHandler((t1, e) -> thrown.add(e));
Move m;
try {
t.start();
t.join(d.getExecution());
this.interrupt();
m = movePtr.recall();
int count = 0;
while (t.isAlive()) {
if (count > 0) {
log.warn(L_PLAYER_WAITING, count * d.getExecution() / 1000, this.getClass().getSimpleName());
}
t.join(d.getExecution());
count++;
}
} catch (InterruptedException e) {
throw Utils.convertCheckedException(e);
}
this.isInterrupted(); // This is called to clear the interrupt flag
for (Throwable e : thrown) {
if ((e instanceof Error) && Utils.isAssertionEnabled()) {
throw new AssertionError(e);
} else {
Finals.LOG.warn(L_PLAYER_EXCEPTION, this.getClass().getSimpleName(), finalGraph, d,
Utils.getExceptionString(e));
}
}
return m;
}
@Override
public String toString() {
return this.getClass().getSimpleName();
}
}
|
package com.sarf.web;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.UUID;
import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.sarf.service.BoardServiceImpl;
import com.sarf.service.ReplyServiceImpl;
import com.sarf.vo.BoardVO;
import com.sarf.vo.MemberVO;
import com.sarf.vo.PageMaker;
import com.sarf.vo.ReplyVO;
import com.sarf.vo.SearchCriteria;
@Controller
@RequestMapping("/board/*")
public class BoardController {
private static final Logger logger = LoggerFactory.getLogger(BoardController.class);
@Inject
BoardServiceImpl service;
@Inject
ReplyServiceImpl replyService;
// 게시판 목록 조회
@RequestMapping(value = "/list", method = RequestMethod.GET)
public String list(Model model, @ModelAttribute("scri") SearchCriteria scri) throws Exception{
logger.info("박수빈");
model.addAttribute("list",service.list(scri));
PageMaker pageMaker = new PageMaker();
pageMaker.setCri(scri);
pageMaker.setTotalCount(service.listCount(scri));
model.addAttribute("pageMaker", pageMaker);
return "/board/list";
}
// 게시판 글 작성 화면
@RequestMapping(value = "/writeView", method = RequestMethod.GET)
public void writeView() throws Exception{
logger.info("작성화면");
}
// 게시판 글 작성
@RequestMapping(value="/write", method = RequestMethod.POST)
public String write(BoardVO boardVO, HttpSession session) throws Exception {
logger.info("작성완료");
MemberVO memberVO = (MemberVO) session.getAttribute("member");
String boardId = memberVO.getId();
boardVO.setName(boardId);
service.write(boardVO);
return "redirect:/board/list";
}
// 게시물 조회
@RequestMapping(value = "/view", method = RequestMethod.GET)
public String read(BoardVO boardVO, @ModelAttribute("scri") SearchCriteria scri, Model model) throws Exception{
logger.info("뷰");
model.addAttribute("read", service.read(boardVO.getBno()));
model.addAttribute("scri", scri);
List<ReplyVO> replyList = replyService.readReply(boardVO.getBno());
model.addAttribute("replyList", replyList);
return "board/view";
}
// 게시물 수정뷰
@RequestMapping(value = "/updateView", method = RequestMethod.GET)
public String updateView(BoardVO boardVO, Model model) throws Exception{
logger.info("없데이트뷰");
model.addAttribute("update", service.read(boardVO.getBno()));
return "board/updateView";
}
// 게시물 수정
@RequestMapping(value = "/update", method = RequestMethod.POST)
public String update(BoardVO boardVO) throws Exception{
logger.info("없데이트");
service.update(boardVO);
return "redirect:/board/view?bno=" + boardVO.getBno();
}
// 게시물 삭제
@RequestMapping(value = "/delete", method = RequestMethod.POST)
public String delete(BoardVO boardVO) throws Exception{
logger.info("딜리트");
service.delete(boardVO.getBno());
return "redirect:/board/list";
}
@RequestMapping("/multiupload")
public void multiplePhotoUpload(HttpServletRequest request, HttpServletResponse response){
try {
System.out.println("다중탔어~~~~~~");
//파일정보
String sFileInfo = "";
//파일명을 받는다 - 일반 원본파일명
String filename = request.getHeader("file-name");
//파일 확장자
String filename_ext = filename.substring(filename.lastIndexOf(".")+1);
//확장자를소문자로 변경
filename_ext = filename_ext.toLowerCase();
//파일 기본경로
String dftFilePath = request.getSession().getServletContext().getRealPath("/");
System.out.println("@@@@@파일 기본경로" + dftFilePath);
//파일 기본경로 _ 상세경로
String filePath = dftFilePath + "resources" + File.separator + "photo_upload" + File.separator;
System.out.println("@@@@@파일 상세경로" + filePath);
File file = new File(filePath);
if(!file.exists()) {
file.mkdirs();
}
String realFileNm = "";
SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
String today= formatter.format(new java.util.Date());
realFileNm = today+UUID.randomUUID().toString() + filename.substring(filename.lastIndexOf("."));
String rlFileNm = filePath + realFileNm;
System.out.println("@@@@@파일 경로, 파일명"+ rlFileNm);
///////////////// 서버에 파일쓰기 /////////////////
InputStream is = request.getInputStream();
OutputStream os=new FileOutputStream(rlFileNm);
int numRead;
byte b[] = new byte[Integer.parseInt(request.getHeader("file-size"))];
while((numRead = is.read(b,0,b.length)) != -1){
os.write(b,0,numRead);
}
if(is != null) {
is.close();
}
os.flush();
os.close();
///////////////// 서버에 파일쓰기 /////////////////
// 정보 출력
sFileInfo += "&bNewLine=true";
// img 태그의 title 속성을 원본파일명으로 적용시켜주기 위함
sFileInfo += "&sFileName="+ filename;;
sFileInfo += "&sFileURL="+"/resources/photo_upload/"+realFileNm;
PrintWriter print = response.getWriter();
print.print(sFileInfo);
print.flush();
print.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
|
package com.tencent.mm.plugin.card.ui.view;
import android.content.res.ColorStateList;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.StateListDrawable;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewStub;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.LinearLayout.LayoutParams;
import android.widget.TextView;
import com.tencent.mm.plugin.card.a.a;
import com.tencent.mm.plugin.card.a.d;
import com.tencent.mm.plugin.card.b.f;
import com.tencent.mm.plugin.card.d.l;
import com.tencent.mm.plugin.card.ui.a.g;
import com.tencent.mm.protocal.c.xk;
import com.tencent.mm.sdk.platformtools.bi;
import com.tencent.mm.sdk.platformtools.x;
import com.tencent.mm.ui.MMActivity;
public final class b extends i {
private MMActivity gKS;
private View hHn;
private TextView hHo;
private g hHp;
private com.tencent.mm.plugin.card.base.b htQ;
public final void initView() {
this.gKS = this.hHF.ayx();
this.hHp = this.hHF.ayz();
}
public final void destroy() {
super.destroy();
this.gKS = null;
this.hHp = null;
}
public final void update() {
if (this.hHn == null) {
this.hHn = ((ViewStub) findViewById(d.card_accept_layout_stub)).inflate();
this.hHn.findViewById(d.card_accept_btn).setOnClickListener(this.hHF.ayy());
}
this.htQ = this.hHF.ayu();
this.hHp = this.hHF.ayz();
boolean azh = this.hHp.azh();
boolean azi = this.hHp.azi();
if (azh) {
this.hHn.setVisibility(0);
x.i("MicroMsg.CardAcceptView", "updateAcceptView() acceptViewVisible:" + azh + " acceptViewEnabled:" + azi);
Button button = (Button) this.hHn.findViewById(d.card_accept_btn);
View findViewById = this.hHn.findViewById(d.card_accept_layout);
findViewById.setBackgroundDrawable(null);
findViewById.setOnClickListener(null);
int dimensionPixelSize = this.gKS.getResources().getDimensionPixelSize(com.tencent.mm.plugin.card.a.b.card_member_widget_bg_round_radius);
LayoutParams layoutParams;
LayoutParams layoutParams2;
if (azi) {
if (!TextUtils.isEmpty(this.htQ.awm().rnP)) {
button.setText(this.htQ.awm().rnP);
}
Drawable e;
Drawable cm;
Drawable stateListDrawable;
if (this.htQ.avT()) {
button.setTextColor(l.xV(this.htQ.awm().dxh));
e = l.e(this.gKS, l.xV(this.htQ.awm().dxh), dimensionPixelSize);
cm = l.cm(l.xV(this.htQ.awm().dxh), dimensionPixelSize);
stateListDrawable = new StateListDrawable();
stateListDrawable.addState(new int[]{16842919}, cm);
stateListDrawable.addState(new int[0], e);
int[] iArr = new int[]{this.gKS.getResources().getColor(a.white), l.xV(this.htQ.awm().dxh)};
int[][] iArr2 = new int[][]{new int[]{16842919, 16842910}, new int[0]};
button.setBackgroundDrawable(stateListDrawable);
button.setTextColor(new ColorStateList(iArr2, iArr));
layoutParams = (LayoutParams) this.hHn.getLayoutParams();
layoutParams.topMargin = this.gKS.getResources().getDimensionPixelSize(com.tencent.mm.plugin.card.a.b.card_card_accept_layout_top_margin_for_member_acceptable);
this.hHn.setLayoutParams(layoutParams);
this.hHn.findViewById(d.divider_line).setVisibility(8);
f ayC = this.hHF.ayC();
CheckBox checkBox = (CheckBox) this.hHn.findViewById(d.card_follow_cbx);
if (ayC.awL() == null || !ayC.awL().hvj) {
x.i("MicroMsg.CardAcceptView", "updateFollowBox() not show followbox");
checkBox.setVisibility(8);
} else {
x.i("MicroMsg.CardAcceptView", "updateFollowBox() show followbox");
checkBox.setVisibility(0);
xk xkVar = this.htQ.awm().roa;
if (xkVar == null || TextUtils.isEmpty(xkVar.text)) {
checkBox.setText(ayC.awL().title);
} else {
checkBox.setText(xkVar.text);
}
checkBox.setChecked(ayC.awL().hvk);
checkBox.setOnClickListener(new 1(this, ayC));
}
} else if (this.htQ.avU() || this.htQ.avS() || this.htQ.avV()) {
e = l.cm(l.xV(this.htQ.awm().dxh), dimensionPixelSize);
cm = l.cm(l.bc(this.htQ.awm().dxh, 175), dimensionPixelSize);
stateListDrawable = new StateListDrawable();
stateListDrawable.addState(new int[]{16842919}, cm);
stateListDrawable.addState(new int[0], e);
button.setBackgroundDrawable(stateListDrawable);
button.setTextColor(this.gKS.getResources().getColor(a.white_text_color_selector));
layoutParams2 = (LayoutParams) button.getLayoutParams();
layoutParams2.width = -1;
button.setLayoutParams(layoutParams2);
} else {
e = l.cm(l.xV(this.htQ.awm().dxh), dimensionPixelSize);
cm = l.cm(l.bc(this.htQ.awm().dxh, 175), dimensionPixelSize);
stateListDrawable = new StateListDrawable();
stateListDrawable.addState(new int[]{16842919}, cm);
stateListDrawable.addState(new int[0], e);
button.setBackgroundDrawable(stateListDrawable);
button.setTextColor(this.gKS.getResources().getColor(a.white_text_color_selector));
}
} else {
this.hHn.setEnabled(false);
findViewById.setEnabled(false);
button.setEnabled(false);
button.setText(this.htQ.avT() ? this.htQ.awm().rnP : this.hHp.aza());
if (this.htQ.avT()) {
button.setTextColor(l.bc(this.htQ.awm().dxh, 125));
button.setBackgroundDrawable(l.e(this.gKS, l.bc(this.htQ.awm().dxh, 125), dimensionPixelSize));
layoutParams = (LayoutParams) this.hHn.getLayoutParams();
layoutParams.topMargin = this.gKS.getResources().getDimensionPixelSize(com.tencent.mm.plugin.card.a.b.card_card_accept_layout_top_margin_for_member_unacceptable);
this.hHn.setLayoutParams(layoutParams);
this.hHn.findViewById(d.divider_line).setVisibility(8);
} else if (this.htQ.avU() || this.htQ.avS() || this.htQ.avV()) {
button.setTextColor(this.gKS.getResources().getColor(a.grey_background_text_color));
button.setBackgroundDrawable(l.A(this.gKS, this.gKS.getResources().getColor(a.card_accept_btn_disable_bg_color)));
layoutParams2 = (LayoutParams) button.getLayoutParams();
layoutParams2.width = -1;
button.setLayoutParams(layoutParams2);
} else {
button.setTextColor(this.gKS.getResources().getColor(a.grey_background_text_color));
button.setBackgroundDrawable(l.A(this.gKS, this.gKS.getResources().getColor(a.card_accept_btn_disable_bg_color)));
}
}
if (!this.htQ.avU() && !this.htQ.avS()) {
if (this.htQ.awm().rob != null && !bi.oW(this.htQ.awm().rob.text)) {
if (this.hHo == null) {
this.hHo = (TextView) this.hHn.findViewById(d.card_accept_guidance_tv);
}
this.hHo.setText(this.htQ.awm().rob.text);
if (!bi.oW(this.htQ.awm().rob.url)) {
this.hHo.setOnClickListener(this.hHF.ayy());
this.hHo.setTextColor(l.xV(this.htQ.awm().dxh));
}
this.hHo.setVisibility(0);
return;
} else if (this.hHo != null) {
this.hHo.setVisibility(8);
return;
} else {
return;
}
}
return;
}
x.i("MicroMsg.CardAcceptView", "updateAcceptView(), mAcceptCardView is Gone");
this.hHn.setVisibility(8);
}
public final void azI() {
this.hHn.setVisibility(8);
}
}
|
package aqua.blatt1.common.msgtypes;
import java.io.Serializable;
import java.net.InetSocketAddress;
@SuppressWarnings("serial")
public final class NeighborUpdate implements Serializable {
private final Neighbors neighbors;
public static final class Neighbors implements Serializable {
public Neighbors(InetSocketAddress leftNeighbor, InetSocketAddress rightNeighbor) {
this.leftNeighbor = leftNeighbor;
this.rightNeighbor = rightNeighbor;
}
private final InetSocketAddress leftNeighbor;
private final InetSocketAddress rightNeighbor;
public InetSocketAddress getLeftNeighbor() {
return leftNeighbor;
}
public InetSocketAddress getRightNeighbor() {
return rightNeighbor;
}
public boolean isRightNeighbor(InetSocketAddress toCompare) {
return rightNeighbor.equals(toCompare);
}
public boolean isLeftNeighbor(InetSocketAddress toCompare) {
return leftNeighbor.equals(toCompare);
}
}
public NeighborUpdate(InetSocketAddress leftNeighbor, InetSocketAddress rightNeighbor) {
this.neighbors = new Neighbors(leftNeighbor, rightNeighbor);
}
public Neighbors getNeighbors() {
return neighbors;
}
}
|
package com.zihui.cwoa.processone.service;
import com.zihui.cwoa.processone.config.BpmnCreateUtil;
import com.zihui.cwoa.system.common.RedisUtils;
import org.activiti.bpmn.BpmnAutoLayout;
import org.activiti.bpmn.model.BpmnModel;
import org.activiti.bpmn.model.Process;
import org.activiti.engine.*;
import org.activiti.engine.history.HistoricProcessInstance;
import org.activiti.engine.history.HistoricVariableInstance;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.activiti.image.impl.DefaultProcessDiagramGenerator;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.io.InputStream;
import java.util.*;
@Service("ProcessesService")
public class ProcessesService {
public static Logger logger = Logger.getLogger(ProcessesService.class);
@Autowired
private RepositoryService repositoryService;
@Autowired
private HistoryService historyService;
@Autowired
private IdentityService identityService;
@Autowired
private RuntimeService runtimeService;
@Autowired
private TaskService taskService;
//自定义的查询方法
@Autowired
private QueryService queryService;
@Resource
private RedisUtils redisUtils;
/**
* 部署流程
* @param processPath 传入流程定义文件路径
* @return 成功/失败 true/false
*/
public boolean deployProcess(String processPath){
try {
this.repositoryService.createDeployment().addClasspathResource(processPath).deploy();
redisUtils.del("selectProcessSelect");
return true;
} catch (Exception e) {
logger.error(e);
return false;
}
}
/**
* 启动流程
* @param processKey 流程的key
* @param variables 添加额外的参数 供整个流程去使用(从流程开始到结束 整个时间范围内都可以获取)
* @return 成功/失败 true/false
*/
public boolean startProcess(String processKey,Map<String, Object> variables){
//业务主键 businessKey
Long currentTimeMillis = System.currentTimeMillis();
String businessKey=currentTimeMillis.toString();
//启动流程
try {
//注意 在bpmn的 start节点里 要进行设置: activiti:initiator="applyuser"
identityService.setAuthenticatedUserId((String)variables.get("userId"));
runtimeService.startProcessInstanceByKey(processKey, businessKey, variables);
} catch (Exception e) {
logger.error(e);
return false;
}
return true;
}
/**
* 查询用户任务
* @param userId 用户ID
* @return 用户的任务信息
*/
public Map<String,Object> queryTask(String userId,int page, int num){
//根据用户ID获取该用户的任务
int size = queryService.queryTaskCountById(Integer.parseInt(userId));
Map<String,Object> map =new HashMap<>();
map.put("result",size);
if(size==0){
return map;
}
List<Task> tasks =
taskService.createTaskQuery().taskAssignee(userId).orderByTaskCreateTime().desc().listPage(page,num);
List<Map<String,Object>> queryResultList = new LinkedList<>();
for (Task task : tasks) {
Map<String, Object> variables = taskService.getVariables(task.getId());
variables.put("taskId",task.getId());
String processInstanceId = task.getProcessInstanceId();
variables.put("processInstanceId",processInstanceId);
ProcessInstance processInstance =
runtimeService.createProcessInstanceQuery().processInstanceId(processInstanceId).singleResult();
variables.put("startTime",processInstance.getStartTime());
variables.put("processName",processInstance.getProcessDefinitionName());
queryResultList.add(variables);
}
map.put("queryResultList",queryResultList);
return map;
}
/**
* 办理人同意流程执行到下一步
* @param taskId 用户ID
* @return 成功/失败 true/false
*/
public boolean completeTask(String taskId){
try {
taskService.complete(taskId);
return true;
} catch (Exception e) {
logger.error(e);
return false;
}
}
/**
* 办理人不同意流程执行到下一步 流程强制结束
* @param processInstanceId 流程实例Id
* @param reason 不同意的理由
* @return 成功/失败 true/false
*/
public boolean deleteProcessInstance(String processInstanceId,String reason){
try {
runtimeService.deleteProcessInstance(processInstanceId,reason);
return true;
} catch (Exception e) {
logger.error(e);
return false;
}
}
/**
* 根据用户ID查询他发起的还在审批中的流程
* @param userId 用户ID
* @return 查询结果
*/
public Map<String,Object> queryProcess(String userId,int page, int num) {
int size = queryService.queryActProCountById(userId);
Map<String,Object> map =new HashMap<>();
map.put("result", size);
if(size==0){
return map;
}
List<Map<String,Object>> list = new LinkedList<>();
List<ProcessInstance> proList =
runtimeService.createProcessInstanceQuery().startedBy(userId).listPage(page,num);
for (ProcessInstance pro: proList) {
String processInstanceId=pro.getProcessInstanceId();
Map<String, Object> variables=runtimeService.getVariables(processInstanceId);
variables.put("processInstanceId",processInstanceId);
variables.put("processName",pro.getProcessDefinitionName());
variables.put("processStatus",queryService.queryProStatusByProInstanceId(processInstanceId));
list.add(variables);
}
map.put("queryResultList",list);
return map;
}
/**
* 根据用户ID查询他发起的已经结束的流程
* @param userId 用户ID
* @param page 当前页码
* @param num 每页显示条数
* @return 查询结果
*/
public Map<String,Object> queryEndProcess(String userId,int page, int num){
int size = queryService.queryEndProCountById(userId);
Map<String,Object> map =new HashMap<>();
map.put("result",size);
if(size==0){
return map;
}
List<Map<String,Object>> list = new LinkedList<>();
List<HistoricProcessInstance> historicProcessInstanceList =
historyService.createHistoricProcessInstanceQuery()
.startedBy(userId).finished().orderByProcessInstanceEndTime().desc().listPage(page,num);
for (HistoricProcessInstance ins:historicProcessInstanceList) {
Map<String,Object> variables=new HashMap<>();
String processName=ins.getProcessDefinitionName();
String processInstanceId=ins.getId();
variables.put("processName",processName);
if("动态任务".equals(processName)){
String otherTalk = (String) historyService.createHistoricVariableInstanceQuery().
processInstanceId(processInstanceId).variableName("otherTalk").singleResult().getValue();
variables.put("otherTalk",otherTalk);
}
variables.put("processInstanceId",processInstanceId);
variables.put("startTime",ins.getStartTime());
variables.put("endTime",ins.getEndTime());
variables.put("deploymentId", ins.getDeploymentId());
String deleteReason = ins.getDeleteReason();
if(deleteReason!=null){
variables.put("deleteReason",deleteReason);
}else{
variables.put("deleteReason","同意申请");
}
list.add(variables);
}
map.put("queryResultList",list);
return map;
}
/**
* 查看流程详情
* @param processInstanceId 流程实例Id
* @return 查询结果
*/
public Map<String,Object> queryProcessDetail(String processInstanceId){
List<HistoricVariableInstance> hisList =
historyService.createHistoricVariableInstanceQuery().processInstanceId(processInstanceId).list();
Map<String,Object> variables=new HashMap<>();
if(hisList.isEmpty()){
variables.put("flag",false);
return variables;
}else {
variables.put("flag",true);
}
for (HistoricVariableInstance hisInstance:hisList) {
variables.put(hisInstance.getVariableName(),hisInstance.getValue());
}
HistoricProcessInstance ins
= historyService.createHistoricProcessInstanceQuery().processInstanceId(processInstanceId).singleResult();
variables.put("startTime",ins.getStartTime());
Date endTime = ins.getEndTime();
variables.put("endTime",endTime);
variables.put("processInstanceId",processInstanceId);
variables.put("processName",ins.getProcessDefinitionName());
String deleteReason = ins.getDeleteReason();
if(deleteReason!=null){
variables.put("deleteReason",deleteReason);
}else if(endTime!=null){
variables.put("deleteReason","同意申请");
}else{
variables.put("deleteReason","审批中");
}
return variables;
}
/**
* 查看带节点的流程图
* @param processInstanceId 流程实例Id
* @return 流程图的输出流
*/
public InputStream getPngStream(String processInstanceId) {
// 获得流程实例
HistoricProcessInstance processInstance =
historyService.createHistoricProcessInstanceQuery().processInstanceId(processInstanceId).singleResult();
// 获得流程定义id
String processDefinitionId = processInstance.getProcessDefinitionId();
BpmnModel bpmnModel = repositoryService.getBpmnModel(processDefinitionId);
List<String> list;
try {
list=runtimeService.getActiveActivityIds(processInstanceId);
} catch (Exception e) {
return getActivityPngStream(processInstance.getDeploymentId());
}
DefaultProcessDiagramGenerator processDiagramGenerator= new DefaultProcessDiagramGenerator();
return processDiagramGenerator.generateDiagram(bpmnModel, "png", list,
Collections.<String>emptyList(), "宋体","宋体",
"宋体", null, 1.0D);
}
/**
* 查看流程图
* @param deploymentId 流程部署Id
* @return 流程图的输出流
*/
public InputStream getActivityPngStream(String deploymentId) {
ProcessDefinition processDefinition =
repositoryService.createProcessDefinitionQuery().deploymentId(deploymentId).singleResult();
return repositoryService.getResourceAsStream(deploymentId, processDefinition.getDiagramResourceName());
}
/**
* 按条件查找流程
*/
public Map<String,Object> queryProcessByVo(String processDefinitionKey,String userId
,Long date,int page,int num) {
List<HistoricProcessInstance> list;
int size;
if (userId != null && userId!="") {
if (date != 0) {
Date dateOne = new Date(date-86400000);
Date dateTwo = new Date(date+86400000);
list = historyService.createHistoricProcessInstanceQuery()
.processDefinitionKey(processDefinitionKey)
.startedBy(userId)
.startedAfter(dateOne)
.startedBefore(dateTwo)
.orderByProcessInstanceStartTime()
.desc()
.listPage(page,num);
size = historyService.createHistoricProcessInstanceQuery()
.processDefinitionKey(processDefinitionKey)
.startedBy(userId)
.startedAfter(dateOne)
.startedBefore(dateTwo)
.orderByProcessInstanceStartTime()
.desc()
.list()
.size();
} else {
list = historyService.createHistoricProcessInstanceQuery()
.processDefinitionKey(processDefinitionKey)
.startedBy(userId)
.orderByProcessInstanceStartTime()
.desc()
.listPage(page,num);
size = historyService.createHistoricProcessInstanceQuery()
.processDefinitionKey(processDefinitionKey)
.startedBy(userId)
.orderByProcessInstanceStartTime()
.desc()
.list()
.size();
}
} else if (date != 0) {
Date dateOne = new Date(date-86400000);
Date dateTwo = new Date(date+86400000);
list = historyService.createHistoricProcessInstanceQuery()
.processDefinitionKey(processDefinitionKey)
.startedAfter(dateOne)
.startedBefore(dateTwo)
.orderByProcessInstanceStartTime()
.desc()
.listPage(page,num);
size = historyService.createHistoricProcessInstanceQuery()
.processDefinitionKey(processDefinitionKey)
.startedAfter(dateOne)
.startedBefore(dateTwo)
.orderByProcessInstanceStartTime()
.desc()
.list()
.size();
} else {
list = historyService.createHistoricProcessInstanceQuery()
.processDefinitionKey(processDefinitionKey)
.orderByProcessInstanceStartTime()
.desc()
.listPage(page,num);
size = historyService.createHistoricProcessInstanceQuery()
.processDefinitionKey(processDefinitionKey)
.orderByProcessInstanceStartTime()
.desc()
.list()
.size();
}
List<Map<String,Object>> resultList = new LinkedList<>();
for (HistoricProcessInstance ins : list) {
String processInstanceId=ins.getId();
List<HistoricVariableInstance> hisList =
historyService.createHistoricVariableInstanceQuery()
.processInstanceId(processInstanceId).list();
Map<String,Object> variables=new HashMap<>();
for (HistoricVariableInstance hisInstance:hisList) {
variables.put(hisInstance.getVariableName(),hisInstance.getValue());
}
variables.put("startTime", ins.getStartTime());
Date endTime = ins.getEndTime();
variables.put("endTime", endTime);
variables.put("processInstanceId", processInstanceId);
variables.put("processName", ins.getProcessDefinitionName());
String deleteReason = ins.getDeleteReason();
if (endTime == null) {
variables.put("deleteReason", "审批中");
} else if (deleteReason!=null) {
variables.put("deleteReason", deleteReason);
} else {
variables.put("deleteReason", "同意申请");
}
resultList.add(variables);
}
Map<String,Object> map =new HashMap<>();
map.put("result",size);
map.put("queryResultList",resultList);
return map;
}
/**
* 创建动态流程
* @return 成功/失败
*/
public boolean createLiveProcess(Map<String,Object> map){
List<Map<String,String>> userList= (List<Map<String,String>>) map.get("userList");
map.remove("userList");
int i=1;
// 1. Build up the model from scratch
BpmnModel model = new BpmnModel();
Process process = new Process();
model.addProcess(process);
process.setId("liveProcess");
process.setName("动态任务");
process.addFlowElement(BpmnCreateUtil.createStartEvent());
process.addFlowElement(BpmnCreateUtil.createParallelGateway("gateway1","gateway1"));
process.addFlowElement(BpmnCreateUtil.createParallelGateway("gateway2","gateway2"));
process.addFlowElement(BpmnCreateUtil.createEndEvent("end"));
process.addFlowElement(BpmnCreateUtil.createSequenceFlow("flowStart","flowStart","start", "gateway1"));
process.addFlowElement(BpmnCreateUtil.createSequenceFlow("flowEnd", "flowEnd","gateway2","end"));
for (Map<String,String> str: userList) {
process.addFlowElement(BpmnCreateUtil.createUserTask("task"+i, str.get("name")+"接受任务",String.valueOf(str.get("value")),null));
process.addFlowElement(BpmnCreateUtil.createSequenceFlow("st"+i, "st"+i,"gateway1","task"+i));
process.addFlowElement(BpmnCreateUtil.createSequenceFlow("te"+i, "te"+i,"task"+i,"gateway2"));
i++;
}
// 2. Generate graphical information
new BpmnAutoLayout(model).execute();
// 3. Deploy the process to the engine
repositoryService.createDeployment().addBpmnModel("liveProcess.bpmn", model).name("动态任务").deploy();
// 4. Start the process
return startProcess("liveProcess",map);
}
/**
* 创建多人任务
* @return 成功/失败
*/
public boolean startManyProcess(Map<String, Object> variables){
//业务主键 businessKey
Long currentTimeMillis = System.currentTimeMillis();
String businessKey=currentTimeMillis.toString();
List<Map<String,String>> userList= (List<Map<String,String>>) variables.get("userList");
variables.remove("userList");
//启动流程
for (Map<String,String> str: userList) {
try {
identityService.setAuthenticatedUserId((String)variables.get("userId"));
ProcessInstance taskProcess =
runtimeService.startProcessInstanceByKey("taskProcess", businessKey, variables);
queryService.setAssigned(taskProcess.getProcessInstanceId(),str.get("name")+"接受任务",str.get("value"));
} catch (Exception e) {
logger.error(e);
return false;
}
}
return true;
}
/**
* 拒绝动态任务
* @return 成功/失败
*/
public boolean rejectLiveTask(String processInstanceId, String reason,String taskId,String userId){
String userName = queryService.selectNameById(userId);
String otherTalk = (String) runtimeService.getVariable(processInstanceId, "otherTalk");
if (otherTalk==null){
otherTalk="";
}
otherTalk=otherTalk+"<span style=\"color:red\">"+userName+"拒绝了任务</span>:"+reason+"<br/>";
runtimeService.setVariable(processInstanceId,"otherTalk",otherTalk);
return completeTask(taskId);
}
/**
* 根据用户ID查询他审批过的流程
* @param userId 用户ID
* @param page 当前页码
* @param num 每页显示条数
*/
public Map<String,Object> queryCheckProcess(String userId,int page, int num){
int size = queryService.queryCheckCountById(userId);
Map<String,Object> map =new HashMap<>();
map.put("result",size);
if(size==0){
return map;
}
List<Map<String,Object>> list = new LinkedList<>();
List<Map<String, Object>> processList = queryService.queryCheckProcessById(userId, page, num);
for (Map<String, Object> process: processList) {
Map<String,Object> variables=new HashMap<>();
String processName= (String) process.get("processName");
variables.put("processName",processName);
String processInstanceId= (String) process.get("processInstanceId");
variables.put("processInstanceId",processInstanceId);
variables.put("startTime",process.get("startTime"));
variables.put("endTime",process.get("endTime"));
variables.put("deploymentId", process.get("deploymentId"));
variables.put("userName", process.get("userName"));
if("动态任务".equals(processName)){
String otherTalk = (String) historyService.createHistoricVariableInstanceQuery().
processInstanceId(processInstanceId).variableName("otherTalk").singleResult().getValue();
variables.put("otherTalk",otherTalk);
}
String deleteReason = (String) process.get("deleteReason");
if(deleteReason==null){
if(process.get("endTime")==null){
variables.put("deleteReason","审批中");
}else {
variables.put("deleteReason","同意申请");
}
}else{
variables.put("deleteReason",deleteReason);
}
list.add(variables);
}
map.put("queryResultList",list);
return map;
}
}
|
package com.gerray.fmsystem.Authentication;
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.widget.Button;
import android.widget.Toast;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import com.gerray.fmsystem.R;
import com.karumi.dexter.Dexter;
import com.karumi.dexter.MultiplePermissionsReport;
import com.karumi.dexter.PermissionToken;
import com.karumi.dexter.listener.PermissionRequest;
import com.karumi.dexter.listener.multi.MultiplePermissionsListener;
import java.util.List;
public class PermissionActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_permission);
if (ContextCompat.checkSelfPermission(PermissionActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
startActivity(new Intent(PermissionActivity.this, UserSelector.class));
finish();
return;
}
Button grant = findViewById(R.id.btn_grant);
grant.setOnClickListener(view -> Dexter.withActivity(PermissionActivity.this)
.withPermissions(Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE)
.withListener(new MultiplePermissionsListener() {
@Override
public void onPermissionsChecked(MultiplePermissionsReport multiplePermissionsReport) {
if (multiplePermissionsReport.areAllPermissionsGranted()) {
startActivity(new Intent(PermissionActivity.this, UserSelector.class));
finish();
} else {
showSettingsDialog();
}
}
@Override
public void onPermissionRationaleShouldBeShown(List<PermissionRequest> list, PermissionToken permissionToken) {
permissionToken.continuePermissionRequest();
}
})
.withErrorListener(dexterError -> Toast.makeText(getApplicationContext(), "Error occurred! " + dexterError.toString(), Toast.LENGTH_SHORT).show())
.onSameThread()
.check());
}
private void showSettingsDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(PermissionActivity.this);
builder.setTitle("Need Permissions");
builder.setMessage("This app needs permission to use this feature. You can grant them in app settings.");
builder.setPositiveButton("GOTO SETTINGS", (dialog, which) -> {
dialog.cancel();
openSettings();
});
builder.setNegativeButton("Cancel", (dialog, which) -> dialog.cancel());
builder.show();
}
private void openSettings() {
Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
Uri uri = Uri.fromParts("package", getPackageName(), null);
intent.setData(uri);
startActivityForResult(intent, 101);
}
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.ufc.poo.sorveteria.model;
import com.ufc.poo.sorveteria.model.enums.Tipo;
import java.sql.Timestamp;
import javax.management.BadAttributeValueExpException;
/**
*
* @author cristiano
*/
public class Produto {
private Integer id;
private String nome;
private Tipo tipo;
private Double preco;
private Timestamp createdAt;
private Timestamp updatedAt;
private Integer quantidadeDisponivel;
/**
* @return the id
*/
public Integer getId() {
return id;
}
/**
* @param id the id to set
*/
public void setId(Integer id) {
this.id = id;
}
/**
* @return the nome
*/
public String getNome() {
return nome;
}
/**
* @param nome the nome to set
*/
public void setNome(String nome) {
this.nome = nome;
}
/**
* @return the tipo
*/
public Tipo getTipo() {
return tipo;
}
/**
* @param tipo the tipo to set
*/
public void setTipo(Tipo tipo) {
this.tipo = tipo;
}
/**
* @return the preco
*/
public Double getPreco() {
return preco;
}
/**
* @param preco the preco to set
*/
public void setPreco(Double preco) {
this.preco = preco;
}
/**
* @return the createdAt
*/
public Timestamp getCreatedAt() {
return createdAt;
}
/**
* @param createdAt the createdAt to set
*/
public void setCreatedAt(Timestamp createdAt) {
this.createdAt = createdAt;
}
/**
* @return the updatedAt
*/
public Timestamp getUpdatedAt() {
return updatedAt;
}
/**
* @param updatedAt the updatedAt to set
*/
public void setUpdatedAt(Timestamp updatedAt) {
this.updatedAt = updatedAt;
}
/**
* @return the quantidadeDisponivel
*/
public Integer getQuantidadeDisponivel() {
return quantidadeDisponivel;
}
/**
* @param quantidadeDisponivel the quantidadeDisponivel to set
*/
public void setQuantidadeDisponivel(Integer quantidadeDisponivel) {
this.quantidadeDisponivel = quantidadeDisponivel;
}
public Boolean verificarProduto() throws BadAttributeValueExpException {
if (this.nome == null || this.nome.isEmpty() || this.nome.isBlank()) {
throw new BadAttributeValueExpException("Campo NOME em produto está inválido");
} else if (this.tipo == null) {
throw new BadAttributeValueExpException("Campo TIPO em produto está inválido");
} else if (this.preco == null || this.preco.isNaN()) {
throw new BadAttributeValueExpException("Campo PREÇO em produto está inválido.");
} else if (this.quantidadeDisponivel == null || this.quantidadeDisponivel < 0) {
throw new BadAttributeValueExpException("Campo QUANTIDADE DISPONÍVEL em produto está inválido.");
}
return true;
}
@Override
public String toString() {
return "---- Produto ---- \nID: " + this.id + "\nNome: " + this.nome + "\nPreço: " + this.preco + "\nEstoque: "
+ this.quantidadeDisponivel + "\n-----------------";
}
}
|
package ch.ubx.startlist.server.admin;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
import java.util.logging.Level;
import java.util.logging.Logger;
import ch.ubx.startlist.server.AirfieldDAOobjectify;
import ch.ubx.startlist.server.FlightEntryDAO2;
import ch.ubx.startlist.server.FlightEntryDAOobjectify2;
import ch.ubx.startlist.shared.Airfield;
import ch.ubx.startlist.shared.FeFlightEntry;
public class OlcImport {
private static AirfieldDAOobjectify airfieldDAO = new AirfieldDAOobjectify();
private static FlightEntryDAO2 flightEntryDAO = new FlightEntryDAOobjectify2();
private static final Logger log = Logger.getLogger(Olc2006AirfieldServlet.class.getName());
/**
* @param place
* @param year
* @param maxImportAtOnce
* @return List<FlightEntry>
*/
public static List<FeFlightEntry> importFromOLC(String place, int year, int maxImportAtOnce) {
List<FeFlightEntry> flightEntries = new ArrayList<FeFlightEntry>();
try {
Airfield airfield = airfieldDAO.getAirfield(place);
if (airfield != null) {
List<FeFlightEntry> storedFlightEntries = flightEntryDAO.listflightEntry(year - 1, year + 1, place);
OlcImportExtractPilotInfo olcImportExtractPilotInfo = new OlcImportExtractPilotInfo(storedFlightEntries);
olcImportExtractPilotInfo.setMaxImport(maxImportAtOnce); // avoid DeadlineExceededException, set amount per RPC call!
flightEntries = olcImportExtractPilotInfo.olcImportFromPlace(airfield.getId(), place, year, airfield.getCountry());
flightEntries = mergeAddFlightEntries(flightEntries);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return flightEntries;
}
/**
* Merge new FlightEntries with uncompleted FlightEntries in data store. If merge is not possible the new FlightEntry is added to the data store. <code>
* Conditions: 1) Date, pilot and place are the same.
* 2) New FlightEntries are complete and therefore used only once for a merge or add operation.
* 3) A modification of a FlightEntry in data store is done only by one new FlightEntry. Merge rules:
*
* OLC flight: +==============+
* Manual flight 1: ==|==============|==== copy start and end
* 2: +==|==============|== copy end
* 3: | +========= | copy end
* 4: ===|============+ | copy start
* 5: ===|==============|======+ copy start
* 6: | +===========|==+ ignore
* 7: +==|========+ | ignore
* 8: +==|==============|===+ ignore
* 9: | | +========+ add
* 10: +=====+ | | add
*
* Key: + defined start/end
* = open start/end
* | start/end OLC flight
*
* </code>
*
*
* @param flightEntries
* Contains new complete FlightEntries of the same place and year.
*/
private static List<FeFlightEntry> mergeAddFlightEntries(List<FeFlightEntry> flightEntries) {
List<FeFlightEntry> modifiedFlightEntries = new ArrayList<FeFlightEntry>();
List<FeFlightEntry> usedNewFlightEntries = new ArrayList<FeFlightEntry>();
// eliminate duplicates!
Set<FeFlightEntry> newFlightEntries = new TreeSet<FeFlightEntry>(flightEntries);
for (FeFlightEntry newFlightEntry : newFlightEntries) {
Calendar date = Calendar.getInstance(); // TODO - set timezone UTC?
date.setTimeInMillis(newFlightEntry.getStartTimeInMillis());
List<FeFlightEntry> storedFlightEntries = flightEntryDAO.listflightEntry(date, newFlightEntry.getPlace());
if (storedFlightEntries.size() == 0) {
modifiedFlightEntries.add(newFlightEntry);
} else {
for (FeFlightEntry storedFlightEntry : storedFlightEntries) {
if (!modifiedFlightEntries.contains(storedFlightEntry)
& (samePilot(newFlightEntry, storedFlightEntry) | samePlane(newFlightEntry, storedFlightEntry))) {
// 1:
if (!storedFlightEntry.isStartTimeValid() & !storedFlightEntry.isEndTimeGliderValid()) {
storedFlightEntry.setStartTimeInMillis(newFlightEntry.getStartTimeInMillis());
storedFlightEntry.setEndTimeGliderInMillis(newFlightEntry.getEndTimeGliderInMillis());
modifiedFlightEntries.add(storedFlightEntry);
usedNewFlightEntries.add(newFlightEntry);
log.log(Level.INFO, "Merge 1: Pilot: " + storedFlightEntry.getPilot() + " ,Plane: " + storedFlightEntry.getRegistrationGlider());
}
// 2+3:
else if (!storedFlightEntry.isEndTimeGliderValid()
& storedFlightEntry.getStartTimeInMillis() < newFlightEntry.getEndTimeGliderInMillis()) {
storedFlightEntry.setEndTimeGliderInMillis(newFlightEntry.getEndTimeGliderInMillis());
modifiedFlightEntries.add(storedFlightEntry);
usedNewFlightEntries.add(newFlightEntry);
log.log(Level.INFO, "Merge 2+3: Pilot: " + storedFlightEntry.getPilot() + " ,Plane: " + storedFlightEntry.getRegistrationGlider());
}
// 4+5:
else if (!storedFlightEntry.isStartTimeValid() & storedFlightEntry.getEndTimeGliderInMillis() > newFlightEntry.getStartTimeInMillis()) {
storedFlightEntry.setStartTimeInMillis(newFlightEntry.getStartTimeInMillis());
modifiedFlightEntries.add(storedFlightEntry);
usedNewFlightEntries.add(newFlightEntry);
log.log(Level.INFO, "Merge 4+5: Pilot: " + storedFlightEntry.getPilot() + " ,Plane: " + storedFlightEntry.getRegistrationGlider());
}
// 6..8:
else if (!(storedFlightEntry.getEndTimeGliderInMillis() < newFlightEntry.getStartTimeInMillis() & storedFlightEntry
.getStartTimeInMillis() > newFlightEntry.getEndTimeGliderInMillis())) {
usedNewFlightEntries.add(newFlightEntry);
log.log(Level.INFO, "Merge 6..8: Pilot: " + storedFlightEntry.getPilot() + " ,Plane: " + storedFlightEntry.getRegistrationGlider());
} // 9+10:
else if (!modifiedFlightEntries.contains(newFlightEntry)) {
modifiedFlightEntries.add(newFlightEntry);
log.log(Level.INFO, "Merge 9+10: Pilot: " + newFlightEntry.getPilot() + " ,Plane: " + newFlightEntry.getRegistrationGlider());
}
}
}
if (!usedNewFlightEntries.contains(newFlightEntry)) {
modifiedFlightEntries.add(newFlightEntry);
}
}
}
flightEntryDAO.addFlightEntries(modifiedFlightEntries);
final SimpleDateFormat timeFormat = new SimpleDateFormat("dd.MM.yyyy HH:mm z");
for (FeFlightEntry flightEntry : modifiedFlightEntries) {
log.log(Level.INFO, "Place: " + flightEntry.getPlace() + " ,Start: " + timeFormat.format(new Date(flightEntry.getStartTimeInMillis()))
+ " ,Pilot: " + flightEntry.getPilot() + " ,Plane: " + flightEntry.getRegistrationGlider());
}
return modifiedFlightEntries;
}
private static boolean samePilot(FeFlightEntry fe0, FeFlightEntry fe1) {
String name0 = fe0.getPilot();
String name1 = fe1.getPilot();
if (name0 != null && name1 != null) {
if (name0.equalsIgnoreCase(name1)) {
return true;
}
String[] x0 = name0.split(" ");
String[] x1 = name1.split(" ");
if (x0.length == 2 && x1.length == 2) {
return x0[0].equalsIgnoreCase(x1[1]) & x0[1].equalsIgnoreCase(x1[0]);
}
}
return false;
}
private static boolean samePlane(FeFlightEntry fe0, FeFlightEntry fe1) {
String name0 = fe0.getRegistrationGlider();
String name1 = fe1.getRegistrationGlider();
if (name0 != null && name1 != null) {
if (name0.equalsIgnoreCase(name1)) {
return true;
}
}
return false;
}
}
|
package com.tencent.mm.plugin.wallet_core.ui.ibg;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.widget.Toast;
import com.tencent.mm.plugin.wxpay.a.i;
import com.tencent.mm.pluginsdk.model.u$a;
class WalletIbgAdapterUI$1 implements OnClickListener {
final /* synthetic */ WalletIbgAdapterUI pzd;
WalletIbgAdapterUI$1(WalletIbgAdapterUI walletIbgAdapterUI) {
this.pzd = walletIbgAdapterUI;
}
public final void onClick(DialogInterface dialogInterface, int i) {
u$a.eQ(this.pzd);
Toast.makeText(this.pzd, this.pzd.getString(i.webview_tbs_download_start), 1).show();
this.pzd.finish();
}
}
|
package cn.xyz.service;
import java.io.IOException;
import org.json.simple.parser.ParseException;
import org.springframework.util.StringUtils;
import com.xiaomi.xmpush.server.Constants;
import com.xiaomi.xmpush.server.Message;
import com.xiaomi.xmpush.server.Message.Builder;
import com.xiaomi.xmpush.server.Result;
import com.xiaomi.xmpush.server.Sender;
import cn.xyz.commons.utils.StringUtil;
import cn.xyz.mianshi.utils.KSessionUtil;
import cn.xyz.mianshi.vo.MsgNotice;
//小米通知栏推送集成
public class XMPushService {
public static Sender sender = new Sender("shQBqQFN/rim0OTxEDBDxg==");// 申请到的AppSecret
public final static String PACKAGE_NAME = "com.luosi.letschat ";// 申请的包名
public static void pushToRegId(MsgNotice notice, String callNum) {
if (StringUtils.isEmpty(notice.getText()))
notice.setText("收到一条消息...");
String messagePayload = notice.getText();
String title = notice.getTitle();
String description = notice.getText();
if (1 == notice.getIsGroup()) {
description = notice.getText().replace(notice.getGroupName(), "");
title = notice.getTitle();
}
Message message = null;
Builder builder = new Message.Builder().title(title).description(description).payload(messagePayload)
.restrictedPackageName(PACKAGE_NAME)
.extra(Constants.EXTRA_PARAM_NOTIFY_EFFECT, Constants.NOTIFY_LAUNCHER_ACTIVITY);
// .extra(Constants.EXTRA_PARAM_INTENT_URI,
// "intent:#Intent;component=com.xiaomi.mipushdemo/.NewsActivity;end")
// 自定义参数
builder.extra("from", notice.getFrom() + "");
builder.extra("fromUserName", notice.getName() + "");
builder.extra("messageType", notice.getType() + "");
builder.extra("to", notice.getTo() + "");
if (120 == notice.getType() || 115 == notice.getType()) {
builder.extra("callNum", callNum + "");
builder.passThrough(1);
}
if (100 == notice.getType() || 110 == notice.getType())
builder.passThrough(0);
message = builder.notifyType(1) // 使用默认提示音提示
.build();
try {
String regId = KSessionUtil.getXMPushRegId(notice.getTo());
if (StringUtil.isEmpty(regId))
return;
Result result = sender.send(message, regId, 3);
System.out.println(result.toString());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void pushRegId(String regId,String fromUserName) {
Message message = null;
Builder builder = new Message.Builder().title("哦了提醒您").description("收到1条新消息").payload(fromUserName)
.restrictedPackageName(PACKAGE_NAME)
.extra(Constants.EXTRA_PARAM_NOTIFY_EFFECT, Constants.NOTIFY_LAUNCHER_ACTIVITY);
message = builder.notifyType(1) // 使用默认提示音提示
.build();
try {
if (StringUtil.isEmpty(regId))
return;
Result result = sender.send(message, regId, 3);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/*
* private String getRegId(Integer userId){
*
* }
*/
public static void sendTest(){
//String reg="mGa3TOgqZTizC5AwX4JKw0tjstqXHrsc+pWutNFFFwY=";
String reg="F2OBWpJcoE/49x1JHW1ljbUyFeT6vmoUCdiDbuR7nhI=";//38
//String reg="8M2Sh8oaQHSCv2tAOXqw2heAGFbgTCsfvC/Mh2RgADc=";//41
//String reg="clgkHyMMCQmdsxbTx19XvHp5TAPtSSX7RBscv/zN2ds=";//54
//String reg="3/N8GYhI0+34eT3f3twqUXNjH/rqPKCxqrrEMjdlXf8=";//47
Message message = null;
Builder builder = new Message.Builder().title("哦了提醒您").description("收到1条新消息").payload("测试内容")
.restrictedPackageName(PACKAGE_NAME)
.extra(Constants.EXTRA_PARAM_NOTIFY_EFFECT, Constants.NOTIFY_LAUNCHER_ACTIVITY);
//builder.passThrough(1);
message = builder.notifyType(1) // 使用默认提示音提示
.build();
try {
Result result = sender.send(message, reg, 3);
System.out.println(result);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String[] args) {
sendTest();
//pushRegId("x3PaWPx9ITzykQ+UYNrDoCv67lTNGsa3tTzkojjjCq4=", "小白");
}
}
|
// Generated code from Butter Knife. Do not modify!
package com.weicent.android.csma.ui.list;
import android.view.View;
import butterknife.ButterKnife.Finder;
import butterknife.ButterKnife.ViewBinder;
public class CommodityListActivity$$ViewBinder<T extends com.weicent.android.csma.ui.list.CommodityListActivity> implements ViewBinder<T> {
@Override public void bind(final Finder finder, final T target, Object source) {
View view;
view = finder.findRequiredView(source, 2131427493, "field 'layoutLoading'");
target.layoutLoading = finder.castView(view, 2131427493, "field 'layoutLoading'");
view = finder.findRequiredView(source, 2131427494, "field 'layoutMsg'");
target.layoutMsg = finder.castView(view, 2131427494, "field 'layoutMsg'");
view = finder.findRequiredView(source, 2131427495, "field 'textMsg'");
target.textMsg = finder.castView(view, 2131427495, "field 'textMsg'");
view = finder.findRequiredView(source, 2131427416, "field 'layoutContext'");
target.layoutContext = finder.castView(view, 2131427416, "field 'layoutContext'");
view = finder.findRequiredView(source, 2131427435, "field 'gridView'");
target.gridView = finder.castView(view, 2131427435, "field 'gridView'");
view = finder.findRequiredView(source, 2131427417, "field 'abPullToRefreshView'");
target.abPullToRefreshView = finder.castView(view, 2131427417, "field 'abPullToRefreshView'");
}
@Override public void unbind(T target) {
target.layoutLoading = null;
target.layoutMsg = null;
target.textMsg = null;
target.layoutContext = null;
target.gridView = null;
target.abPullToRefreshView = null;
}
}
|
package com.swqube.knowmalaria;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import database.Music;
public class LevelsActivity extends AppCompatActivity implements View.OnClickListener {
Button btnEasy, btnMedium, btnHard;
SharedPreferences prefs;
SharedPreferences.Editor editor;
boolean easy, medium, hard;
boolean btnClicked = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_levels);
prefs = PreferenceManager.getDefaultSharedPreferences(this);
editor = prefs.edit();
btnEasy = findViewById(R.id.btnEasy); btnEasy.setOnClickListener(this);
btnMedium = findViewById(R.id.btnMedium); btnMedium.setOnClickListener(this);
btnHard = findViewById(R.id.btnHard); btnHard.setOnClickListener(this);
}
@Override
public void onResume(){
super.onResume();
btnClicked = false;
Music.play(getApplicationContext(), R.raw.knowmal, true);
easy = prefs.getBoolean("EASY", true);
medium = prefs.getBoolean("MEDIUM", false);
hard = prefs.getBoolean("HARD", false);
}
@Override
public void onClick(View view) {
switch (view.getId()){
case R.id.btnEasy:
startActivity(new Intent(this, LevelOneActivity.class));
break;
case R.id.btnMedium:
if(!medium){
AlertDialog.Builder builder = new AlertDialog.Builder(this, R.style.Theme_AppCompat_Light_Dialog_Alert);
builder.setMessage("Not in a hurry. You have to complete easy level first.")
.setNegativeButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
//do nothing
}
})
.setCancelable(false)
.show();
}
else{
startActivity(new Intent(this, LevelTwoActivity.class));
}
break;
case R.id.btnHard:
if(!hard){
AlertDialog.Builder builder = new AlertDialog.Builder(this, R.style.Theme_AppCompat_Light_Dialog_Alert);
builder.setMessage("Not in a hurry. You have to complete medium level first.")
.setNegativeButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
//do nothing
}
})
.setCancelable(false)
.show();
}
else{
startActivity(new Intent(this, LevelThreeActivity.class));
}
break;
}
}
@Override
public void onStop(){
super.onStop();
if(!btnClicked)
Music.stop(getApplicationContext());
}
@Override
public void onBackPressed(){
btnClicked = true;
finish();
}
}
|
import java.util.Scanner;
public class Problem4_7 // Corner point coordinates
{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
// Prompt the user to enter the radius of the bounding circle
System.out.print("Enter the radius of the bounding circle:");
double radius = input.nextDouble();
// side s = 2*radius*sin PI/5;
double a1 = 2.0 * Math.PI / 5.0 ;
double a2 = 2.0 * Math.PI / 5.0 ;
double a3 = 2.0 * Math.PI / 5.0 ;
double a4 = 2.0 * Math.PI / 5.0 ;
double a5 = 2.0 * Math.PI / 5.0 ;
// Calculating coordinate
// by formula x = r * cos(alpha) y = r * sin(alpha)
double x1 = radius * Math.cos(a1);
double y1 = radius * Math.sin(a1);
double x2 = radius * Math.cos(a2);
double y2 = radius * Math.sin(a2);
double x3 = radius * Math.cos(a3);
double y3 = radius * Math.sin(a3);
double x4 = radius * Math.cos(a4);
double y4 = radius * Math.sin(a4);
double x5 = radius * Math.cos(a5);
double y5 = radius * Math.sin(a5);
System.out.println("The coordinates of five points on the pentagon are");
System.out.printf( "%2.5f %2.5f \n" , x1 , y1);
System.out.printf( "%2.5f %2.5f \n" , x2 , y2);
System.out.printf( "%2.5f %2.5f \n" , x3 , y3);
System.out.printf( "%2.5f %2.5f \n" , x4 , y4);
System.out.printf( "%2.5f %2.5f " , x5 , y5);
/*System.out.println(" The coordinates of five points on the pentagon are :");
for(int i = 0; i <=5; i++) {
double x = radius * Math.sin (2.0 *Math.PI/5.0 * i );
double y = radius * Math.cos( 2.0 * Math.PI/5.0 * i );
System.out.println(x +" " +y);*/
}
}
|
package com.qihoo.finance.chronus.protocol.dubbo.config;
import com.qihoo.finance.chronus.common.ChronusConstants;
import com.qihoo.finance.chronus.protocol.api.ChronusSdkFacadeFactory;
import com.qihoo.finance.chronus.protocol.dubbo.ChronusSdkFacadeFactoryImpl;
import org.apache.dubbo.spring.boot.autoconfigure.DubboAutoConfiguration;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* Created by xiongpu on 2019/8/28.
*/
@Configuration
@AutoConfigureAfter(DubboAutoConfiguration.class)
@ConditionalOnProperty(prefix = "dubbo", name = {"enabled"}, matchIfMissing = true)
public class DubboConfiguration {
@Bean(name = ChronusConstants.CHRONUS_SDK_FACADE_FACTORY + "#DUBBO")
public ChronusSdkFacadeFactory chronusSdkFacadeFactory() {
ChronusSdkFacadeFactory chronusSdkFacadeFactory = new ChronusSdkFacadeFactoryImpl();
return chronusSdkFacadeFactory;
}
}
|
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int a = scan.nextInt();
int x = 0;
int res = 0;
for (int i = 1; i <= a; i++) {
x = scan.nextInt();
int y = scan.nextInt();
if (x % 2 == 0) {
x += 1;
} else {
x = x;
}
for (int f = 1; f<= y; f++){
res = res+x;
x= x+2;
}
System.out.println(res);
res = 0;
}
}
}
|
public class Assignment8 {
public static void main(String[] args) {
double f1 = 105.678;
double f2 = 222.4655;
System.out.println(f1 + f2);
}
}
|
package com.countout.controller;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.countout.entity.MessageEntity;
import com.countout.service.MessageService;
import com.countout.vo.MessageVo;
import com.tang.util.page.Page;
/**
* 消息推送
* @author Mr.tang
*/
@Controller
@RequestMapping(value = "/message")
public class MessageController {
private final Logger logger = Logger.getLogger(MessageController.class);
// private Map<String, Object> result = new HashMap<String, Object>();
@Autowired
private MessageService messageService;
/**
* 分页查询
* @param request
* @param requestMap
* @return
*/
@ResponseBody
@RequestMapping(value = "page.do")
public Object pageQuery(HttpServletRequest request, @RequestBody Map<String, Object> requestMap){
Map<String, Object> result = new HashMap<String, Object>();
try {
Page<MessageEntity> userList = this.messageService.pageQuery(requestMap);
result.put("userList", userList);
result.put("msg", "推送消息查询成功查询成功");
} catch (Exception e) {
result.put("msg", "推送消息查询出现异常!");
result.put("flg", Boolean.FALSE);
logger.error("推送消息分页查询异常!"+e);
e.printStackTrace();
}
return result;
}
/**
* 新增要推送的消息
* @param map
* @return
*/
@ResponseBody
@RequestMapping(value = "/saveOrUpdate.do")
public Object saveOrUpdate(@RequestBody Map<String, Object> map){
Map<String, Object> result = new HashMap<String, Object>();
try {
this.messageService.saveOrUpdate(map);
result.put("msg", "操作成功!");
result.put("flg", Boolean.TRUE);
} catch (Exception e) {
result.put("msg", "操作出现异常!");
result.put("flg", Boolean.FALSE);
logger.error("新增或修改要推送的消息异常!"+e);
e.printStackTrace();
}
return result;
}
/**
* 推送消息审核操作
* @param 审核推送的消息
* @return
*/
@ResponseBody
@RequestMapping(value = "/pushMessage.do")
public Object pushMessage(@RequestBody Map<String, Object> map){
Map<String, Object> result = new HashMap<String, Object>();
try {
this.messageService.pushMessage(map);
result.put("msg", "操作成功!");
result.put("flg", Boolean.TRUE);
} catch (Exception e) {
result.put("flg", Boolean.FALSE);
result.put("msg", "操作出现异常!");
logger.error("推送消息审核操作异常!"+e);
e.printStackTrace();
}
return result;
}
/**
* 查询redis中推送审核通过的消息
* @return
*/
@ResponseBody
@RequestMapping(value = "/queryMessage.do")
public Object queryMessage(@RequestBody Map<String, Object> map){
Map<String, Object> result = new HashMap<String, Object>();
try {
List<MessageVo> listVo = this.messageService.queryMessage(map);
result.put("listVo", listVo);
result.put("msg", "操作成功!");
result.put("flg", Boolean.TRUE);
} catch (Exception e) {
result.put("flg", Boolean.FALSE);
result.put("msg", "操作出现异常!");
logger.error("查询redis中推送审核通过的消息异常!"+e);
e.printStackTrace();
}
return result;
}
}
|
package org.team3128.compbot.commands;
import org.team3128.common.drive.DriveCommandRunning;
import org.team3128.common.drive.DriveSignal;
import org.team3128.common.hardware.limelight.LEDMode;
import org.team3128.common.hardware.limelight.Pipeline;
import org.team3128.common.hardware.limelight.Limelight;
import org.team3128.common.hardware.limelight.LimelightData;
import org.team3128.common.hardware.limelight.LimelightKey;
import org.team3128.common.hardware.limelight.StreamMode;
import org.team3128.common.hardware.gyroscope.Gyro;
import org.team3128.common.narwhaldashboard.NarwhalDashboard;
import org.team3128.common.utility.Log;
import org.team3128.common.utility.RobotMath;
import org.team3128.common.utility.datatypes.PIDConstants;
import org.team3128.common.utility.units.Angle;
import edu.wpi.first.wpilibj.RobotController;
import edu.wpi.first.wpilibj.command.Command;
import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard;
import org.team3128.compbot.subsystems.Constants;
import org.team3128.compbot.subsystems.Arm.ArmState;
import org.team3128.compbot.subsystems.*;
import org.team3128.compbot.subsystems.Hopper.ActionState;
import com.kauailabs.navx.frc.AHRS;
import org.team3128.compbot.commands.*;
public class CmdAlignShoot extends Command {
FalconDrive drive;
Shooter shooter;
Hopper hopper;
Arm arm;
boolean gotDistance = false;
AHRS ahrs;
Limelight limelight;
double decelerationStartDistance, decelerationEndDistance;
DriveCommandRunning cmdRunning;
private PIDConstants visionPID;
private double goalHorizontalOffset;
private double currentHorizontalOffset;
private double currentError, previousError;
private double currentTime, previousTime;
private double feedbackPower;
private double leftPower, rightPower;
private double desiredRPM;
private double effective_distance;
private StateTracker stateTracker = StateTracker.getInstance();
private Command hopperShoot, organize;
int targetFoundCount;
int plateauReachedCount;
int numBallsShot;
int numBallsToShoot;
private enum HorizontalOffsetFeedbackDriveState {
SEARCHING, FEEDBACK; // , BLIND;
}
private HorizontalOffsetFeedbackDriveState aimState = HorizontalOffsetFeedbackDriveState.SEARCHING;
public CmdAlignShoot(FalconDrive drive, Shooter shooter, Arm arm, Hopper hopper, AHRS ahrs, Limelight limelight,
DriveCommandRunning cmdRunning, double goalHorizontalOffset, int numBallsToShoot) {
this.drive = drive;
this.shooter = shooter;
this.arm = arm;
this.hopper = hopper;
this.ahrs = ahrs;
this.limelight = limelight;
this.visionPID = Constants.VisionConstants.VISION_PID;
this.cmdRunning = cmdRunning;
this.goalHorizontalOffset = goalHorizontalOffset;
this.numBallsToShoot = numBallsToShoot;
}
@Override
protected void initialize() {
limelight.setLEDMode(LEDMode.ON);
cmdRunning.isRunning = false;
arm.setState(stateTracker.getState().targetArmState);
shooter.setState(stateTracker.getState().targetShooterState);
hopper.setAction(Hopper.ActionState.SHOOTING);
Log.info("CmdAlignShoot", "initialized limelight, aren't I cool!");
}
@Override
protected void execute() {
switch (aimState) {
case SEARCHING:
NarwhalDashboard.put("align_status", "searching");
if (limelight.hasValidTarget()) {
targetFoundCount += 1;
} else {
targetFoundCount = 0;
}
if (targetFoundCount > 5) {
Log.info("CmdAlignShoot", "Target found.");
Log.info("CmdAlignShoot", "Switching to FEEDBACK...");
LimelightData initData = limelight.getValues(Constants.VisionConstants.SAMPLE_RATE);
// double currLLAngle = arm.getAngle() + Constants.ArmConstants.LIMELIGHT_ARM_ANGLE + Constants.VisionConstants.BOTTOM_LIMELIGHT_ANGLE;
// // add
// double limelight_height = Constants.VisionConstants.PIVOT_HEIGHT + (Constants.ArmConstants.LIMELIGHT_ARM_LENGTH * RobotMath.sin(currLLAngle));
// double distance = (Constants.GameConstants.SHOOTER_TARGET_HEIGHT - limelight_height)
// / (RobotMath.tan(initData.ty()));
// effective_distance = distance / RobotMath.cos(initData.tx());
// SmartDashboard.putNumber("effective_distance", effective_distance);
// SmartDashboard.putNumber("curLLANgle", currLLAngle);
// SmartDashboard.putNumber("liemlight_height", limelight_height);
SmartDashboard.putNumber("ty", initData.ty());
desiredRPM = shooter.getRPMFromDistance();
shooter.setSetpoint(desiredRPM);
currentHorizontalOffset = limelight.getValue(LimelightKey.HORIZONTAL_OFFSET, 5);
previousTime = RobotController.getFPGATime();
previousError = goalHorizontalOffset - currentHorizontalOffset;
cmdRunning.isRunning = true;
aimState = HorizontalOffsetFeedbackDriveState.FEEDBACK;
}
break;
case FEEDBACK:
NarwhalDashboard.put("align_status", "feedback");
cmdRunning.isRunning = false;
if (!limelight.hasValidTarget()) {
Log.info("CmdAlignShoot", "No valid target.");
Log.info("CmdAlignShoot", "Returning to SEARCHING...");
aimState = HorizontalOffsetFeedbackDriveState.SEARCHING;
} else {
if (!gotDistance) {
LimelightData initData = limelight.getValues(Constants.VisionConstants.SAMPLE_RATE);
// double currLLAngle = arm.getAngle() + Constants.ArmConstants.LIMELIGHT_ARM_ANGLE + Constants.VisionConstants.BOTTOM_LIMELIGHT_ANGLE;
// double limelight_height = Constants.VisionConstants.PIVOT_HEIGHT + (Constants.ArmConstants.LIMELIGHT_ARM_LENGTH * RobotMath.sin(currLLAngle));
// double distance = (Constants.GameConstants.SHOOTER_TARGET_HEIGHT - limelight_height)
// / (RobotMath.tan(initData.ty()));
// effective_distance = distance / RobotMath.cos(initData.tx());
desiredRPM = shooter.getRPMFromDistance();
shooter.setSetpoint(desiredRPM);
// SmartDashboard.putNumber("effective_distance", effective_distance);
// SmartDashboard.putNumber("curLLANgle", currLLAngle);
// SmartDashboard.putNumber("liemlight_height", limelight_height);
SmartDashboard.putNumber("ty", initData.ty());
gotDistance = true;
}
currentHorizontalOffset = limelight.getValue(LimelightKey.HORIZONTAL_OFFSET, 5);
currentTime = RobotController.getFPGATime();
currentError = goalHorizontalOffset - currentHorizontalOffset;
/**
* PID feedback loop for the left and right powers based on the horizontal
* offset errors.
*/
feedbackPower = 0;
feedbackPower += visionPID.kP * currentError;
feedbackPower += visionPID.kD * (currentError - previousError) / (currentTime - previousTime);
leftPower = RobotMath.clamp(-feedbackPower, -1, 1);
rightPower = RobotMath.clamp(feedbackPower, -1, 1);
SmartDashboard.putNumber("Shooter Power", leftPower);
double leftSpeed = leftPower * Constants.DriveConstants.DRIVE_HIGH_SPEED;
double rightSpeed = rightPower * Constants.DriveConstants.DRIVE_HIGH_SPEED;
drive.setWheelPower(new DriveSignal(leftPower, rightPower));
previousTime = currentTime;
previousError = currentError;
}
break;
// case BLIND:
// NarwhalDashboard.put("align_status", "blind");
// currentAngle = gyro.getAngle();
// currentTime = RobotController.getFPGATime() / 1000000.0;
// currentError = -currentAngle;
// /**
// * PID feedback loop for the left and right powers based on the gyro angle
// */
// feedbackPower = 0;
// feedbackPower += blindPID.kP * currentError;
// feedbackPower += blindPID.kD * (currentError - previousError) / (currentTime
// - previousTime);
// rightPower = RobotMath.clamp(blindPID.kF - feedbackPower, -1, 1);
// leftPower = RobotMath.clamp(blindPID.kF + feedbackPower, -1, 1);
// Log.info("CmdAlignShoot", "L: " + leftPower + "; R: " + rightPower);
// drive.tankDrive(leftPower, rightPower);
// previousTime = currentTime;
// previousError = currentError;
// Log.info("CmdAlignShoot", "Error:" + currentError);
// break;
}
if ((Math.abs(currentError) < Constants.VisionConstants.TX_THRESHOLD) && shooter.isReady()) {
// Log.info("CmdAlignShoot", "Trying to shoot ball");
hopper.shoot();
} else {
hopper.unShoot();
// Log.info("CmdAlignShoot", "no longer ready to shoot ball");
// Log.info("CmdAlignShoot", "" + shooter.isReady());
// Log.info("CmdAlignShoot", "" + Math.abs(currentError));
}
}
@Override
protected boolean isFinished() {
if (hopper.isEmpty() || numBallsShot >= numBallsToShoot) {
return true;
} else {
return false;
}
}
@Override
protected void end() {
limelight.setLEDMode(LEDMode.OFF);
drive.stopMovement();
shooter.setSetpoint(0);
cmdRunning.isRunning = true;
Log.info("CmdAlignShoot", "Command Finished.");
hopper.setAction(Hopper.ActionState.ORGANIZING);
}
@Override
protected void interrupted() {
end();
}
}
|
package me.the_red_freak.bptf.commands;
import org.bukkit.Material;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemFlag;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
public class extra implements CommandExecutor {
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
Player p = (Player) sender;
ItemStack it = new ItemStack(Material.MAGMA_CREAM);
ItemMeta itm = it.getItemMeta();
itm.setDisplayName("§6Change the Floor!");
itm.addEnchant(Enchantment.DURABILITY, 0, true);
itm.addItemFlags(ItemFlag.HIDE_ENCHANTS);
it.setItemMeta(itm);
p.getInventory().addItem(it);
return true;
}
}
|
package com.bdb.struts.action;
import com.bdb.util.HttpUtils;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
public class BDBActionForm extends ActionForm {
/**
* Comment for <code>serialVersionUID</code>
*/
private static final long serialVersionUID = 1L;
public BDBActionForm() {
}
public final void validateRequired(ActionErrors errors, String property, Object value, boolean zeroIsEmpty) {
HttpUtils.validateRequired(errors, property, value, zeroIsEmpty);
}
public final void validateRequired(ActionErrors errors, String property, Object value) {
HttpUtils.validateRequired(errors, property, value, true);
}
public final void validateRequired(ActionErrors errors, String property, Object value, String valueAgregate) {
HttpUtils.validateRequired(errors, property, value, true,valueAgregate);
}
public final void validateFloat(ActionErrors errors, String property, Object value) {
HttpUtils.validateFloat(errors, property, value, false);
}
public final void validateEntero(ActionErrors errors, String property, Object value) {
HttpUtils.validateEntero(errors, property, value, false);
}
}
|
package org.fuusio.api.model;
public interface ModelObjectObserver {
void onModelObjectChanged(ModelObject object);
}
|
package magical.robot.main;
import ioio.lib.api.exception.ConnectionLostException;
import java.net.URL;
import magical.robot.global.Color;
import magical.robot.global.CubeInfo;
import magical.robot.ioio.MovmentSystem;
import magical.robot.ioio.RobotSettings;
import android.os.AsyncTask;
import android.util.Log;
/**
* The main control loop is here.
* Should run from a separate thread (via Android AsyncTask).
* @author Pavel Rubinson
*/
public class ExecutionTask extends AsyncTask<URL, Integer, Long>{
//Used for updating the calling UI thread. Currently not in use.
public AsyncResponse delegate = null;
//The robot movement module
private MovmentSystem _movmentSystem;
//True if some robot movement is currently happening
private boolean isMoving = false;
//The array of colors that we are searching for, in the order of their appearance in the tower.
//First member is the base cube.
private Color[] colorArr;
//The index (in colorArr) of the current color we are looking for
private int currColor;
//Horizontal center threshold (from -center to +center)
private int centerLimit = 50; //Should be 30
private int center = 230;//should be 230; //210;
//Stopping "distance" from the cube (roughly corresponds to cm, but not really)
private double distance = 0;
private double sensorDistance = 0.7;
//Robot speed values
private double moveSpeed = 1;
private double turnSpeed = 1;
//True if we are going to the base cube. False otherwise.
private boolean gotoBase;
private boolean lineTracking;
//Values to pass to the robotMove method
private final static int STOP = 0;
private final static int MOVE_SLOW = 7;
private final static int MOVE_NORMAL = 1;
private final static int MOVE_FAST = 10;
private final static int RIGHT_VERY_SLOW = 8;
private final static int RIGHT_SLOW = 3;
private final static int RIGHT_FAST = 2;
private final static int LEFT_SLOW = 4;
private final static int BACK = 5;
private final static int TAKE = 6;
private final static int PUT = 9;
//State values (possible robot states/behaviors)
private final static int SEARCH = 1;
private final static int CENTER_LEFT = 2;
private final static int CENTER_RIGHT = 3;
private final static int GOTO_BY_CAMERA_NORMAL = 4;
private final static int GOTO_BY_CAMERA_FAST = 10;
private final static int GOTO_BY_SENSOR_FORW = 5;
private final static int DONE = 6;
private final static int CENTER_RIGHT_SLOW = 7;
private final static int NOTHING = 8;
private final static int GOTO_BY_SENSOR_BACK = 9;
//True when navigating by camera. False when switching to proximity sensor.
private boolean byCamera = true;
//The current state of the robot
private int currState;
/**
*
* @param delegate An interface for updating a text view in the UI thread
* @param movmentSystem THe robot movement system/module
* @param colorArr The array of colors for the tower (first color = the base cube)
* @param lineTracking True if we want line tracking instead of tower building
*/
ExecutionTask(AsyncResponse delegate, MovmentSystem movmentSystem, Color[] colorArr, boolean lineTracking){
this.delegate = delegate;
_movmentSystem = movmentSystem;
this.colorArr = colorArr;
this.currColor = 1;
this.gotoBase = false;
this.lineTracking = lineTracking;
this.currState = SEARCH;
if (lineTracking){
this.moveSpeed = 0.8;
this.distance = 0;
this.centerLimit = 50;
} else {
this.moveSpeed = 0.6;
this.distance = 9;
this.centerLimit = 30;
}
}
@Override
/**
* Main execution loop of the thread
*/
protected Long doInBackground(URL... params) {
this.currColor = 1;
this.gotoBase = false;
try {
_movmentSystem.setRoverSpeed((float)moveSpeed);
_movmentSystem.initArm();
Thread.sleep(2000);
} catch (Exception e) {
e.printStackTrace();
}
Log.i("", "Starting main loop");
if (this.lineTracking){
CubeInfo.getInstance().setColor(Color.LINE_COLOR);
try {
this.magicalAlgorithm(false);
} catch (ConnectionLostException e1) {
e1.printStackTrace();
} catch (InterruptedException e1) {
e1.printStackTrace();
}
} else {
this.currColor = 1;
while (this.currColor <= this.colorArr.length){
if (isCancelled()){
Log.i("", "Task stopped");
try {
robotMove(STOP);
} catch (ConnectionLostException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
break;
}
if (this.gotoBase){
CubeInfo.getInstance().setColor(this.colorArr[0]);
Log.i("Color change", "Color index is now: " + 0);
this.gotoBase = false;
currColor++;
} else {
CubeInfo.getInstance().setColor(this.colorArr[currColor]);
Log.i("Color change", "Color index is now: " + String.valueOf(currColor));
this.gotoBase = true;
}
try {
Thread.sleep(500);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
try {
//Activate the movement algorithm
this.magicalAlgorithm(this.gotoBase);
} catch (ConnectionLostException e1) {
e1.printStackTrace();
} catch (InterruptedException e1) {
e1.printStackTrace();
}
}
}
return null;
}
/**
* Moves/turns/stops the robot.
* @param movement
* @throws ConnectionLostException
* @throws InterruptedException
*/
private void robotMove(int movement) throws ConnectionLostException, InterruptedException{
if (this.isMoving){
if (movement == STOP){
this.isMoving = false;
Log.i("", "Stop command issued");
this._movmentSystem.stop();
}
} else if (movement != STOP) {
this.isMoving = true;
_movmentSystem.setRoverSpeed((float)turnSpeed);
switch (movement){
case(MOVE_NORMAL):
Log.i("", "Issued move command");
_movmentSystem.setRoverSpeed((float)moveSpeed);
this._movmentSystem.moveForwardCont();
Thread.sleep(100);
this.robotMove(STOP);
Thread.sleep(20);
break;
case(MOVE_FAST):
Log.i("", "Issued move command");
_movmentSystem.setRoverSpeed((float)moveSpeed);
this._movmentSystem.moveForwardCont();
Thread.sleep(100);
this.robotMove(STOP);
Thread.sleep(100);
break;
case(MOVE_SLOW):
Log.i("", "Issued move slow command");
_movmentSystem.setRoverSpeed((float)moveSpeed);
this._movmentSystem.moveForwardCont();
Thread.sleep(50);
this.robotMove(STOP);
Thread.sleep(800);
break;
case(RIGHT_FAST):
Log.i("", "Issued turn right command");
this._movmentSystem.turnRight();
Thread.sleep(200);
this.robotMove(STOP);
Thread.sleep(50);
break;
case(RIGHT_SLOW):
Log.i("", "Issued turn right command");
this._movmentSystem.turnRight();
Thread.sleep(60);
this.robotMove(STOP);
Thread.sleep(150);
break;
case(RIGHT_VERY_SLOW):
Log.i("", "Issued turn right slow command");
this._movmentSystem.turnRight();
Thread.sleep(500);
this.robotMove(STOP);
Thread.sleep(500);
break;
case(LEFT_SLOW):
Log.i("", "Issued turn left command");
this._movmentSystem.turnLeft();
Thread.sleep(60);
this.robotMove(STOP);
Thread.sleep(150);
break;
case(BACK):
Log.i("", "Issued go back command");
this._movmentSystem.driveBackwardsCont();
Thread.sleep(80);
this.robotMove(STOP);
Thread.sleep(800);
break;
case(TAKE):
this.robotMove(STOP);
try {
_movmentSystem.takeCube();
} catch (NanExeption e) {
e.printStackTrace();
}
Thread.sleep(2000);
this.robotMove(STOP);
break;
case (PUT):
this.robotMove(STOP);
try {
_movmentSystem.placeCube(2);
} catch (NanExeption e) {
e.printStackTrace();
}
Thread.sleep(5000);
this.robotMove(STOP);
break;
}
}
}
/**
* The main movement algorithm
* @param take Specifies whether we should put the cube or take it. (True to take, false to put)
* @throws ConnectionLostException
* @throws InterruptedException
*/
private void magicalAlgorithm(boolean take) throws ConnectionLostException, InterruptedException{
this.currState = SEARCH;
while (this.currState != DONE){
if (isCancelled()){
this.robotMove(STOP);
break;
}
this.updateState();
switch (this.currState){
case(SEARCH):
this.robotMove(RIGHT_FAST);
break;
case(CENTER_LEFT):
this.robotMove(LEFT_SLOW);
break;
case(CENTER_RIGHT):
this.robotMove(RIGHT_SLOW);
break;
case(GOTO_BY_CAMERA_NORMAL):
this.robotMove(MOVE_NORMAL);
break;
case(GOTO_BY_CAMERA_FAST):
this.robotMove(MOVE_FAST);
break;
case (CENTER_RIGHT_SLOW):
this.robotMove(RIGHT_VERY_SLOW);
break;
case(GOTO_BY_SENSOR_FORW):
this.robotMove(MOVE_SLOW);
break;
case(NOTHING):
break;
case(GOTO_BY_SENSOR_BACK):
this.robotMove(BACK);
break;
case(DONE):
if (take){
this.robotMove(TAKE);
} else {
this.robotMove(PUT);
}
break;
}
}
}
/**
* Checks camera/sensor data and updates the state of the robot accordingly
* @throws ConnectionLostException
* @throws InterruptedException
*/
private void updateState() throws ConnectionLostException, InterruptedException{
double currHorizLoc = CubeInfo.getInstance().getHorizontalLocation();
double currDist = CubeInfo.getInstance().getDistance();
if (lineTracking || this.byCamera){
Log.i("IMPORTANT Camera distance","Status - Camera distance: " + String.valueOf(CubeInfo.getInstance().getDistance()));
if (!CubeInfo.getInstance().getFound()){
this.setState(SEARCH);
} else if (currHorizLoc < center-centerLimit){
this.setState(CENTER_LEFT);
} else if (currHorizLoc > center+centerLimit){
this.setState(CENTER_RIGHT);
} else if (currDist > this.distance+this.distance/2){
this.setState(GOTO_BY_CAMERA_FAST);
} else if (currDist > this.distance) {
this.setState(GOTO_BY_CAMERA_NORMAL);
} else {
this.setState(NOTHING);
Log.i("State update", "Status - Switching to 'NOTHING' with camera distance reading of " + String.valueOf(currDist));
this.byCamera = false;
}
} else { //Cube is centered by camera. Now moving using the distance sensor
double sensDist = CubeInfo.getInstance().getSensorDistanceAvg();
Log.i("IMPORTANT Sensor distance","Status - Sensor distance: " + String.valueOf(sensDist));
Log.i("IMPORTANT Camera distance","Status - Camera distance: " + String.valueOf(CubeInfo.getInstance().getDistance()));
Log.i("IMPORTANT Cube location", "Center location: " + String.valueOf(CubeInfo.getInstance().getHorizontalLocation()));
if (sensDist < this.sensorDistance-0.01){
this.setState(GOTO_BY_SENSOR_FORW);
} else if (sensDist > this.sensorDistance+0.01) {
this.setState(GOTO_BY_SENSOR_BACK);
} else {
Log.i("State update", "Status - Switching to 'DONE' with sensor distance reading of " + String.valueOf(sensDist));
this.setState(DONE);
this.byCamera = true;
}
}
}
/**
* Sets the state of the robot. Issuing "Stop" command between state changes.
* @param newState
* @throws ConnectionLostException
* @throws InterruptedException
*/
private void setState(int newState) throws ConnectionLostException, InterruptedException{
if (this.currState != newState){
robotMove(STOP);
this.currState = newState;
}
}
/**
* Used to update the UI thread
*/
protected void onProgressUpdate(Integer... progress) {
switch (progress[0]){
case (2):
delegate.processFinish("Turn right");
break;
case(-2):
delegate.processFinish("Turn left");
break;
case(1):
delegate.processFinish("Go!");
break;
case(0):
delegate.processFinish("Stop");
break;
default:
break;
}
}
/**
* Setter for the movement module
* @param _movmentSystem The robot movement module
*/
public void set_movmentSystem(MovmentSystem _movmentSystem) {
this._movmentSystem = _movmentSystem;
}
}
|
/**
* Copyright 2010-2015 四川数码物联网络科技有限责任公司. All Rights Reserved.
*/
package com.yida.poi;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
/**
*********************
* @author yangke
* @version 1.0
* @created 2018年5月28日 下午5:24:50
***********************
*/
public class Test {
public static void main(String[] args) {
ExportDoc exportDocService = new ExportDoc();
List<Map<String, Object>> dataset = new ArrayList<>();// 数据库查询数据集
for (int i = 0; i < 3; i++) {
Map<String, Object> map = new HashMap<>();
map.put("NAME", UUID.randomUUID());
map.put("ROADNAME", UUID.randomUUID());
map.put("STATE", UUID.randomUUID());
map.put("REMARK", UUID.randomUUID());
dataset.add(map);
}
List<Map<String, String>> headers = new ArrayList<>();// 字段类型
if (null != headers && !headers.isEmpty()) {
dataset = exportDocService.setDataFormatByFieldType(dataset, headers);// 通过字段类型规范数据输出
}
String templatePath = new File("src/main/resources/document/aaa.docx").getAbsolutePath();// 模板路径
String imgPath = new File("src/main/resources/images/office_1.jpg").getAbsolutePath();// 图片路径
String tempPath = "C:\\Users\\0\\Desktop\\temp\\doc\\bbb.docx";// 生成路径
Map<String, Object> contentMap = new HashMap<String, Object>();
contentMap.put("{Txt%Text%Txt}", "替换内容");
contentMap.put("{Pic%Picture%Pic}", imgPath);
contentMap.put("{Tab%table%Tab}", dataset);
try {
exportDocService.replaceContent(templatePath, tempPath, contentMap);
System.out.println("success");
} catch (IOException e) {
e.printStackTrace();
} // 替换模版内容
}
}
|
package com.tencent.mm.ui.contact.a;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.TextView;
import com.tencent.mm.bp.a;
import com.tencent.mm.kernel.g;
import com.tencent.mm.plugin.fts.a.a.l;
import com.tencent.mm.plugin.fts.a.n;
import com.tencent.mm.plugin.fts.ui.m;
import com.tencent.mm.plugin.selectcontact.a$e;
import com.tencent.mm.plugin.selectcontact.a.d;
import com.tencent.mm.plugin.selectcontact.a.f;
import java.util.regex.Pattern;
public final class c extends a {
private static final Pattern ums = Pattern.compile(";");
public CharSequence eCh;
public CharSequence eCi;
public l fyJ;
public CharSequence umt;
private b umu = new b();
a umv = new a(this);
public String username;
public class b extends com.tencent.mm.ui.contact.a.a.b {
public b() {
super(c.this);
}
public final View a(Context context, ViewGroup viewGroup) {
View inflate;
if (a.fi(context)) {
inflate = LayoutInflater.from(context).inflate(f.select_ui_listcontactitem_large, viewGroup, false);
} else {
inflate = LayoutInflater.from(context).inflate(f.select_ui_listcontactitem, viewGroup, false);
}
a aVar = c.this.umv;
aVar.eCl = (ImageView) inflate.findViewById(a$e.avatar_iv);
aVar.eCm = (TextView) inflate.findViewById(a$e.title_tv);
aVar.eCm.setMaxWidth(a.fromDPToPix(context, 200));
aVar.eCn = (TextView) inflate.findViewById(a$e.desc_tv);
aVar.jxy = (TextView) inflate.findViewById(a$e.tip_tv);
aVar.contentView = inflate.findViewById(a$e.select_item_content_layout);
aVar.eCo = (CheckBox) inflate.findViewById(a$e.select_cb);
if (c.this.hoR) {
aVar.contentView.setBackgroundResource(d.comm_list_item_selector_no_divider);
}
inflate.setTag(aVar);
return inflate;
}
public final void a(Context context, a.a aVar, a aVar2, boolean z, boolean z2) {
a aVar3 = (a) aVar;
c cVar = (c) aVar2;
if (cVar.username == null || cVar.username.length() <= 0) {
aVar3.eCl.setImageResource(d.default_avatar);
} else {
com.tencent.mm.pluginsdk.ui.a.b.a(aVar3.eCl, cVar.username);
}
m.a(cVar.eCh, aVar3.eCm);
m.a(cVar.eCi, aVar3.eCn);
m.a(cVar.umt, aVar3.jxy);
if (c.this.ujX) {
if (z) {
aVar3.eCo.setChecked(true);
aVar3.eCo.setEnabled(false);
} else {
aVar3.eCo.setChecked(z2);
aVar3.eCo.setEnabled(true);
}
aVar3.eCo.setVisibility(0);
return;
}
aVar3.eCo.setVisibility(8);
}
public final boolean Wi() {
if (c.this.fyJ != null) {
((n) g.n(n.class)).updateTopHitsRank(c.this.bWm, c.this.fyJ, 1);
}
return false;
}
}
public c(int i) {
super(3, i);
}
/* JADX WARNING: inconsistent code. */
/* Code decompiled incorrectly, please refer to instructions dump. */
public final void ck(android.content.Context r12) {
/*
r11 = this;
r10 = 2;
r4 = 0;
r1 = 1;
r2 = 0;
r0 = r11.fyJ;
if (r0 == 0) goto L_0x005b;
L_0x0008:
r0 = r11.guS;
if (r0 != 0) goto L_0x016c;
L_0x000c:
com.tencent.mm.kernel.g.Ek();
r0 = com.tencent.mm.plugin.messenger.foundation.a.i.class;
r0 = com.tencent.mm.kernel.g.l(r0);
r0 = (com.tencent.mm.plugin.messenger.foundation.a.i) r0;
r0 = r0.FR();
r3 = r11.fyJ;
r3 = r3.jrv;
r0 = r0.Yb(r3);
r11.guS = r0;
r0 = r11.guS;
if (r0 != 0) goto L_0x016c;
L_0x0029:
com.tencent.mm.kernel.g.Ek();
r0 = com.tencent.mm.plugin.messenger.foundation.a.i.class;
r0 = com.tencent.mm.kernel.g.l(r0);
r0 = (com.tencent.mm.plugin.messenger.foundation.a.i) r0;
r0 = r0.FR();
r3 = r11.fyJ;
r3 = r3.jrv;
r0 = r0.Yf(r3);
r11.guS = r0;
r0 = r1;
L_0x0043:
r3 = r11.guS;
if (r3 != 0) goto L_0x005d;
L_0x0047:
r0 = "MicroMsg.ChatroomDataItem";
r3 = "filling dataItem Occur Error Contact is null, position=%d";
r1 = new java.lang.Object[r1];
r4 = r11.position;
r4 = java.lang.Integer.valueOf(r4);
r1[r2] = r4;
com.tencent.mm.sdk.platformtools.x.i(r0, r3, r1);
L_0x005a:
return;
L_0x005b:
r0 = r2;
goto L_0x0043;
L_0x005d:
r3 = r11.guS;
r3 = r3.field_username;
r11.username = r3;
if (r0 == 0) goto L_0x0131;
L_0x0065:
r3 = r11.fyJ;
r5 = r11.guS;
r6 = r12.getResources();
r0 = com.tencent.mm.plugin.messenger.a.b.class;
r0 = com.tencent.mm.kernel.g.l(r0);
r0 = (com.tencent.mm.plugin.messenger.a.b) r0;
r7 = r5.field_username;
r7 = r0.a(r5, r7);
r0 = r3.jru;
switch(r0) {
case 1: goto L_0x0168;
case 2: goto L_0x00a5;
case 3: goto L_0x00a4;
case 5: goto L_0x0168;
case 6: goto L_0x00a5;
case 7: goto L_0x00a4;
case 38: goto L_0x00ad;
default: goto L_0x0080;
};
L_0x0080:
r0 = r2;
r3 = r2;
r1 = r2;
L_0x0083:
if (r1 == 0) goto L_0x0123;
L_0x0085:
r1 = com.tencent.mm.plugin.selectcontact.a.c.HintTextSize;
r1 = com.tencent.mm.bp.a.ad(r12, r1);
r1 = com.tencent.mm.pluginsdk.ui.d.j.a(r12, r7, r1);
r11.eCh = r1;
r1 = r11.eCh;
r2 = r11.jrx;
r0 = com.tencent.mm.plugin.fts.a.a.d.a(r1, r2, r3, r0);
r0 = com.tencent.mm.plugin.fts.a.f.a(r0);
r0 = r0.jrO;
r11.eCh = r0;
L_0x00a1:
r11.eCi = r4;
goto L_0x005a;
L_0x00a4:
r2 = r1;
L_0x00a5:
r0 = r2;
r3 = r1;
L_0x00a7:
r2 = com.tencent.mm.plugin.selectcontact.a.h.search_contact_tag_nickname;
r6.getString(r2);
goto L_0x0083;
L_0x00ad:
r0 = "SELECT memberlist FROM chatroom WHERE chatroomname=?;";
com.tencent.mm.kernel.g.Ek();
r8 = com.tencent.mm.kernel.g.Ei();
r8 = r8.dqq;
r9 = new java.lang.String[r1];
r5 = r5.field_username;
r9[r2] = r5;
r0 = r8.b(r0, r9, r10);
r5 = r0.moveToFirst();
if (r5 == 0) goto L_0x011e;
L_0x00c9:
r5 = r0.getString(r2);
r0.close();
if (r5 != 0) goto L_0x0117;
L_0x00d2:
r0 = r4;
L_0x00d3:
if (r0 == 0) goto L_0x00f2;
L_0x00d5:
r5 = r0.length;
if (r5 <= 0) goto L_0x00f2;
L_0x00d8:
r5 = new java.lang.StringBuilder;
r8 = "(";
r5.<init>(r8);
r8 = r0.length;
r5 = r5.append(r8);
r8 = ")";
r5 = r5.append(r8);
r5 = r5.toString();
r11.umt = r5;
L_0x00f2:
if (r0 == 0) goto L_0x0080;
L_0x00f4:
r5 = r3.jsH;
if (r5 == 0) goto L_0x0080;
L_0x00f8:
r3 = r3.jsH;
r4 = r11.jrx;
r5 = com.tencent.mm.plugin.fts.ui.b.c.jvz;
r0 = com.tencent.mm.plugin.fts.ui.m.a(r12, r3, r0, r4, r5);
r3 = com.tencent.mm.plugin.selectcontact.a.h.search_contact_tag_member;
r3 = r6.getString(r3);
r4 = new java.lang.CharSequence[r10];
r4[r2] = r3;
r4[r1] = r0;
r4 = android.text.TextUtils.concat(r4);
r0 = r2;
r3 = r2;
r1 = r2;
goto L_0x0083;
L_0x0117:
r0 = ums;
r0 = r0.split(r5);
goto L_0x00d3;
L_0x011e:
r0.close();
r0 = r4;
goto L_0x00d3;
L_0x0123:
r0 = com.tencent.mm.plugin.selectcontact.a.c.HintTextSize;
r0 = com.tencent.mm.bp.a.ad(r12, r0);
r0 = com.tencent.mm.pluginsdk.ui.d.j.a(r12, r7, r0);
r11.eCh = r0;
goto L_0x00a1;
L_0x0131:
r0 = com.tencent.mm.plugin.messenger.a.b.class;
r0 = com.tencent.mm.kernel.g.l(r0);
r0 = (com.tencent.mm.plugin.messenger.a.b) r0;
r1 = r11.guS;
r2 = r11.guS;
r2 = r2.field_username;
r0 = r0.a(r1, r2);
r11.eCh = r0;
r0 = r11.fyJ;
if (r0 == 0) goto L_0x005a;
L_0x0149:
r0 = new java.lang.StringBuilder;
r1 = "(";
r0.<init>(r1);
r1 = r11.fyJ;
r2 = r1.jsA;
r0 = r0.append(r2);
r1 = ")";
r0 = r0.append(r1);
r0 = r0.toString();
r11.umt = r0;
goto L_0x005a;
L_0x0168:
r0 = r2;
r3 = r2;
goto L_0x00a7;
L_0x016c:
r0 = r1;
goto L_0x0043;
*/
throw new UnsupportedOperationException("Method not decompiled: com.tencent.mm.ui.contact.a.c.ck(android.content.Context):void");
}
public final com.tencent.mm.ui.contact.a.a.b Wg() {
return this.umu;
}
protected final a.a Wh() {
return this.umv;
}
public final boolean aQi() {
return this.fyJ.jsK;
}
}
|
package com.xjy.person.controller;
import com.jfinal.core.Controller;
import org.pmw.tinylog.Logger;
/**
* 根控制器.
*/
public class IndexController extends Controller {
/**
* index方法.
*/
public void index() {
String id = getPara("id");
Logger.warn("index方法获取的参数id的值为:" + id);
renderText("Hello JFinal!id:" + id);
}
/**
* hello方法.
*/
public void hello() {
String id = getPara("id");
renderText("55555:" + id);
}
}
|
package com.qihoo.finance.chronus.support;
import com.qihoo.finance.chronus.common.NodeInfo;
import com.qihoo.finance.chronus.common.SupportConstants;
import com.qihoo.finance.chronus.common.ThreadFactory;
import com.qihoo.finance.chronus.common.job.AbstractTimerTask;
import com.qihoo.finance.chronus.master.bo.TaskAssignContext;
import com.qihoo.finance.chronus.master.config.MasterProperties;
import com.qihoo.finance.chronus.master.service.TaskAssignRefreshService;
import com.qihoo.finance.chronus.master.service.TaskAssignService;
import com.qihoo.finance.chronus.registry.api.MasterElectionService;
import lombok.extern.slf4j.Slf4j;
import javax.annotation.Resource;
import java.util.Objects;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
/**
* Created by xiongpu on 2019/7/28.
*/
@Slf4j
public class MasterSupport implements Support {
private static final ScheduledExecutorService TASK_ASSIGN_SCHEDULE = Executors.newSingleThreadScheduledExecutor(new ThreadFactory(SupportConstants.SUPPORT_NAME_MASTER, SupportConstants.MAIN));
private static ScheduledFuture TASK_ASSIGN_SCHEDULE_FUTURE;
@Resource
private MasterElectionService masterElectionService;
@Resource
private MasterProperties masterProperties;
@Resource
private TaskAssignRefreshService taskAssignRefreshService;
@Resource
private NodeInfo currentNode;
@Override
public void start() throws Exception {
if (TASK_ASSIGN_SCHEDULE_FUTURE != null && !TASK_ASSIGN_SCHEDULE_FUTURE.isCancelled()) {
TASK_ASSIGN_SCHEDULE_FUTURE.cancel(false);
}
TASK_ASSIGN_SCHEDULE_FUTURE = TASK_ASSIGN_SCHEDULE.scheduleWithFixedDelay(masterTimerTask, masterProperties.getTaskAssignTimerTaskInitialDelay(), masterProperties.getTaskAssignTimerTaskDelay(), TimeUnit.SECONDS);
}
private Runnable masterTimerTask = new AbstractTimerTask(SupportConstants.SUPPORT_NAME_MASTER, "taskAssign", true) {
@Override
public void process() throws Exception {
masterElectionService.setMasterGroupByTag(masterProperties.isMasterGroupByTag());
if (masterElectionService.isMaster()) {
TaskAssignService taskAssignService = TaskAssignService.create().init();
if (taskAssignService.isNeedAssign()) {
taskAssignService.taskAssign();
}
return;
}
log.debug("当前节点非Master,开始对现有Master进行检查...");
if (masterElectionService.isActiveMaster()) {
taskAssignRefreshService.shutdownRefreshTask();
return;
}
String masterNodeAddress = masterElectionService.election(currentNode.getAddress());
log.info("节点被选举为Master IP:{}", masterNodeAddress);
if (Objects.equals(currentNode.getAddress(), masterNodeAddress)) {
TaskAssignContext.clear();
taskAssignRefreshService.restartRefreshTask();
}
}
};
@Override
public void stop() {
if (TASK_ASSIGN_SCHEDULE_FUTURE != null && !TASK_ASSIGN_SCHEDULE_FUTURE.isCancelled()) {
TASK_ASSIGN_SCHEDULE_FUTURE.cancel(false);
}
taskAssignRefreshService.shutdownRefreshTask();
}
}
|
/*
* Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package jdk.experimental.bytecode;
public enum TypeTag implements Type {
/**
* byte
*/
B("B", 0, 1, 8),
/**
* short
*/
S("S", 0, 1, 9),
/**
* int
*/
I("I", 0, 1, 10),
/**
* float
*/
F("F", 2, 1, 6),
/**
* long
*/
J("J", 1, 2, 11),
/**
* double
*/
D("D", 3, 2, 7),
/**
* Reference type
*/
A("A", 4, 1, -1),
/**
* char
*/
C("C", 0, 1, 5),
/**
* boolean
*/
Z("Z", 0, 1, 4),
/**
* void
*/
V("V", -1, -1, -1),
/**
* Value type
*/
Q("Q", -1, 1, -1);
String typeStr;
int offset;
int width;
int newarraycode;
TypeTag(String typeStr, int offset, int width, int newarraycode) {
this.typeStr = typeStr;
this.offset = offset;
this.width = width;
this.newarraycode = newarraycode;
}
static TypeTag commonSupertype(TypeTag t1, TypeTag t2) {
if (t1.isIntegral() && t2.isIntegral()) {
int p1 = t1.ordinal();
int p2 = t2.ordinal();
return (p1 <= p2) ? t2 : t1;
} else {
return null;
}
}
public int width() {
return width;
}
boolean isIntegral() {
switch (this) {
case B:
case S:
case I:
return true;
default:
return false;
}
}
@Override
public TypeTag getTag() {
return this;
}
}
|
package me.urbanowicz.samuel.cloudytodos.data.store.local.model;
import org.junit.Assert;
import org.junit.Test;
import me.urbanowicz.samuel.cloudytodos.data.DomainMocks;
public class TodoLocalEntityTest {
@Test public void
equals_shouldReturnTrue() {
final TodoLocalEntity todoLocalEntity =
new TodoLocalEntity(DomainMocks.givenMockTodo(), false);
final TodoLocalEntity otherTodoLocalEntity =
new TodoLocalEntity(DomainMocks.givenMockTodo(), false);
Assert.assertEquals(todoLocalEntity, otherTodoLocalEntity);
}
@Test public void
equals_shouldReturnFalseIfDirtyFlagDiffers() {
// given 2 instances of TodoLocalEntity with equal fields
final TodoLocalEntity todoLocalEntity =
new TodoLocalEntity(DomainMocks.givenMockTodo(), false);
final TodoLocalEntity otherTodoLocalEntity =
new TodoLocalEntity(DomainMocks.givenMockTodo(), false);
// when one of them modified isDirty
otherTodoLocalEntity.setDirty(true);
//then equals should return false
Assert.assertTrue(!todoLocalEntity.equals(otherTodoLocalEntity));
}
@Test public void
equals_shouldReturnFalseIfTitleDiffers() {
// given 2 instances of TodoLocalEntity with equal fields
final TodoLocalEntity todoLocalEntity =
new TodoLocalEntity(DomainMocks.givenMockTodo(), false);
final TodoLocalEntity otherTodoLocalEntity =
new TodoLocalEntity(DomainMocks.givenMockTodo(), false);
// when one of them modified title
otherTodoLocalEntity.getTodo().setTitle("Rrrrrr");
//then equals should return false
Assert.assertTrue(!todoLocalEntity.equals(otherTodoLocalEntity));
}
@Test public void
equals_shouldReturnFalseIfTitleCompletedDiffers() {
// given 2 instances of TodoLocalEntity with equal fields
final TodoLocalEntity todoLocalEntity =
new TodoLocalEntity(DomainMocks.givenMockTodo(), false);
final TodoLocalEntity otherTodoLocalEntity =
new TodoLocalEntity(DomainMocks.givenMockTodo(), false);
// when one of them modified completed flag
otherTodoLocalEntity.getTodo().setCompleted(!todoLocalEntity.getTodo().getCompleted());
// then equals should return false
Assert.assertTrue(!todoLocalEntity.equals(otherTodoLocalEntity));
}
}
|
/******************************************************************************
* Copyright (C) 2015 ShenZhen Moze Information Technology Co.,Ltd
* All Rights Reserved.
* 本软件为深圳市么子信息技术有限公司开发研制,未经本公司正式书面同意,其他任何个人、团体
* 不得使用、复制、修改或发布本软件.
*****************************************************************************/
package com.tpshop.mallc.common;
/**
* @author wangqh E-mail:kingastrive22@gmail.com
* @version 创建时间:2015-5-18 下午1:58:52
* @Description 汽车说
* @category
*/
public class SPTableConstanct {
public final static String TABLE_NAME_ADDRESS = "sp_address";
public final static String CREATE_TABLE_ADDRESS = "CREATE TABLE IF NOT EXISTS sp_address(" +
"id integer, " +
"name text NOT NULL, " +
"parent_id integer NOT NULL , " +
"level integer NOT NULL) ";
public final static String TABLE_NAME_CATEGORY = "tp_goods_category";
public final static String CREATE_TABLE_CATEGORY = "CREATE TABLE IF NOT EXISTS "+TABLE_NAME_CATEGORY+"(" +
"id integer, " +
"name STRING NOT NULL, " +
"parent_id INTEGER NOT NULL , " +
"level INTEGER NOT NULL ," +
"image STRING ," +
"is_hot INTEGER , " +
"sort_order INTEGER) ";
}
|
package geometry;
import intersection.Intersection;
import intersection.Quadratic;
import type.None;
import type.ObjectType;
import utility.Color;
import utility.Ray;
import utility.Vector3D;
public abstract class GeometricObject
{
public Color color;
public ObjectType type = new None();
public Quadratic quadra;
public boolean isplane;
public abstract double hit(Ray ray);
public abstract Vector3D getNormal(Intersection intersection);
}
|
/*
* SUNSHINE TEAHOUSE PRIVATE LIMITED CONFIDENTIAL
* __________________
*
* [2015] - [2017] Sunshine Teahouse Private Limited
* All Rights Reserved.
*
* NOTICE: All information contained herein is, and remains
* the property of Sunshine Teahouse Private Limited and its suppliers,
* if any. The intellectual and technical concepts contained
* herein are proprietary to Sunshine Teahouse Private Limited
* and its suppliers, and are protected by trade secret or copyright law.
* Dissemination of this information or reproduction of this material
* is strictly forbidden unless prior written permission is obtained
* from Sunshine Teahouse Private Limited.
*/
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.11
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2015.12.24 at 05:01:33 PM IST
//
package www.chaayos.com.chaimonkbluetoothapp.domain.model.new_model;
import java.io.Serializable;
public class Address implements Serializable {
private String objectId;
private Long version;
/**
* Added to avoid a runtime error whereby the detachAll property is checked
* for existence but not actually used.
*/
private String detachAll;
/**
*
*/
private static final long serialVersionUID = 8075917195527246495L;
protected int id;
protected String line1;
protected String line2;
protected String line3;
protected String locality;
protected String city;
protected String state;
protected String country;
protected String zipCode;
protected String contact1;
protected String contact2;
protected String addressType;
protected String company;
protected String latitude;
protected String longitude;
protected Boolean preferredAddress;
/**
* Gets the value of the id property.
*
*/
public int getId() {
return id;
}
/**
* Sets the value of the id property.
*
*/
public void setId(int value) {
this.id = value;
}
/**
* Gets the value of the line1 property.
*
* @return possible object is {@link String }
*
*/
public String getLine1() {
return line1;
}
/**
* Sets the value of the line1 property.
*
* @param value
* allowed object is {@link String }
*
*/
public void setLine1(String value) {
this.line1 = value;
}
/**
* Gets the value of the line2 property.
*
* @return possible object is {@link String }
*
*/
public String getLine2() {
return line2;
}
/**
* Sets the value of the line2 property.
*
* @param value
* allowed object is {@link String }
*
*/
public void setLine2(String value) {
this.line2 = value;
}
/**
* Gets the value of the line3 property.
*
* @return possible object is {@link String }
*
*/
public String getLine3() {
return line3;
}
/**
* Sets the value of the line3 property.
*
* @param value
* allowed object is {@link String }
*
*/
public void setLine3(String value) {
this.line3 = value;
}
/**
* Gets the value of the locality property.
*
* @return possible object is {@link String }
*
*/
public String getLocality() {
return locality;
}
/**
* Sets the value of the locality property.
*
* @param value
* allowed object is {@link String }
*
*/
public void setLocality(String value) {
this.locality = value;
}
/**
* Gets the value of the city property.
*
* @return possible object is {@link String }
*
*/
public String getCity() {
return city;
}
/**
* Sets the value of the city property.
*
* @param value
* allowed object is {@link String }
*
*/
public void setCity(String value) {
this.city = value;
}
/**
* Gets the value of the state property.
*
* @return possible object is {@link String }
*
*/
public String getState() {
return state;
}
/**
* Sets the value of the state property.
*
* @param value
* allowed object is {@link String }
*
*/
public void setState(String value) {
this.state = value;
}
/**
* Gets the value of the country property.
*
* @return possible object is {@link String }
*
*/
public String getCountry() {
return country;
}
/**
* Sets the value of the country property.
*
* @param value
* allowed object is {@link String }
*
*/
public void setCountry(String value) {
this.country = value;
}
/**
* Gets the value of the zipCode property.
*
* @return possible object is {@link String }
*
*/
public String getZipCode() {
return zipCode;
}
/**
* Sets the value of the zipCode property.
*
* @param value
* allowed object is {@link String }
*
*/
public void setZipCode(String value) {
this.zipCode = value;
}
/**
* Gets the value of the contact1 property.
*
* @return possible object is {@link String }
*
*/
public String getContact1() {
return contact1;
}
/**
* Sets the value of the contact1 property.
*
* @param value
* allowed object is {@link String }
*
*/
public void setContact1(String value) {
this.contact1 = value;
}
/**
* Gets the value of the contact2 property.
*
* @return possible object is {@link String }
*
*/
public String getContact2() {
return contact2;
}
/**
* Sets the value of the contact2 property.
*
* @param value
* allowed object is {@link String }
*
*/
public void setContact2(String value) {
this.contact2 = value;
}
/**
* Gets the value of the addressType property.
*
* @return possible object is {@link String }
*
*/
public String getAddressType() {
return addressType;
}
/**
* Sets the value of the addressType property.
*
* @param value
* allowed object is {@link String }
*
*/
public void setAddressType(String value) {
this.addressType = value;
}
/**
* Gets the value of the company property.
*
* @return possible object is {@link String }
*
*/
public String getCompany() {
return company;
}
/**
* Sets the value of the company property.
*
* @param value
* allowed object is {@link String }
*
*/
public void setCompany(String value) {
this.company = value;
}
/**
* Gets the value of the latitude property.
*
* @return possible object is {@link String }
*
*/
public String getLatitude() {
return latitude;
}
/**
* Sets the value of the latitude property.
*
* @param value
* allowed object is {@link String }
*
*/
public void setLatitude(String value) {
this.latitude = value;
}
/**
* Gets the value of the longitude property.
*
* @return possible object is {@link String }
*
*/
public String getLongitude() {
return longitude;
}
/**
* Sets the value of the longitude property.
*
* @param value
* allowed object is {@link String }
*
*/
public void setLongitude(String value) {
this.longitude = value;
}
/**
* Gets the value of the preferredAddress property.
*
* @return possible object is {@link Boolean }
*
*/
public Boolean isPreferredAddress() {
return preferredAddress;
}
/**
* Sets the value of the preferredAddress property.
*
* @param value
* allowed object is {@link Boolean }
*
*/
public void setPreferredAddress(Boolean value) {
this.preferredAddress = value;
}
@Override
public String toString() {
return line1 + ", " + line2 + ", " + locality + ", " + city + ", state:" + state + ", " + country + ", zipcode:"
+ zipCode;
}
public String getObjectId() {
return objectId;
}
public void setObjectId(String _id) {
this.objectId = _id;
}
public Long getVersion() {
return version;
}
public void setVersion(Long version) {
this.version = version;
}
public String getDetachAll() {
return detachAll;
}
public void setDetachAll(String detachAll) {
this.detachAll = detachAll;
}
public Boolean getPreferredAddress() {
return preferredAddress;
}
}
|
package com.csc214.rebeccavandyke.socialnetworkingproject2.model;
/*
* Rebecca Van Dyke
* rvandyke@u.rochester.edu
* CSC 214 Project 2
* TA: Julian Weiss
*/
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import com.csc214.rebeccavandyke.socialnetworkingproject2.database.SocialNetworkCursorWrapper;
import com.csc214.rebeccavandyke.socialnetworkingproject2.database.SocialNetworkDBSchema;
import com.csc214.rebeccavandyke.socialnetworkingproject2.database.SocialNetworkDatabaseHelper;
import com.csc214.rebeccavandyke.socialnetworkingproject2.database.SocialNetworkDBSchema.PostTable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;
public class PostCollection {
private static final String TAG = "PostCollection";
private static PostCollection sPostCollection;
private Context mAppContext;
private final SQLiteDatabase mDatabase;
private final List<Post> mPostList;
private PostCollection(Context appContext){
mAppContext = appContext.getApplicationContext();
mDatabase = new SocialNetworkDatabaseHelper(mAppContext).getWritableDatabase();
mPostList = new ArrayList<>();
if(isEmpty()) {
Post welcomePost = new Post();
welcomePost.setUser("Admin");
welcomePost.setText("Empty feed? Try favoriting some other users!");
welcomePost.setTimestamp(new Date().getTime());
welcomePost.setImagePath("");
addPost(welcomePost);
}
} //PostCollection()
public static synchronized PostCollection get(Context c) {
if(sPostCollection == null){
sPostCollection = new PostCollection(c);
}
return sPostCollection;
} //get()
public boolean isEmpty(){
List<Post> posts = getPostList();
return posts.isEmpty();
} //isEmpty()
public List<Post> getPostList(){
mPostList.clear();
SocialNetworkCursorWrapper wrapper = queryPosts(null, null);
try{
wrapper.moveToFirst();
while(!wrapper.isAfterLast()) {
Post post = wrapper.getPost();
mPostList.add(post);
wrapper.moveToNext();
}
}
finally{
wrapper.close();
}
return mPostList;
} //getPostList()
public List<Post> getNewsFeed(User activeUser){
List<String> usersFavorited = activeUser.getUsersFavorited();
List<Post> newsFeed = new ArrayList<Post>();
SocialNetworkCursorWrapper wrapper = queryPosts(null, null);
try{
wrapper.moveToFirst();
while(!wrapper.isAfterLast()) {
Post post = wrapper.getPost();
if(usersFavorited.contains(post.getUser())){
newsFeed.add(post);
}
wrapper.moveToNext();
}
}
finally{
wrapper.close();
}
//sort posts chronologically
Collections.sort(newsFeed);
return newsFeed;
} //getNewsFeed()
private SocialNetworkCursorWrapper queryPosts(String where, String[] args){
Cursor cursor = mDatabase.query(
SocialNetworkDBSchema.PostTable.NAME,
null,
where,
args,
null,
null,
null
);
return new SocialNetworkCursorWrapper(cursor);
} //queryPosts()
public void addPost(Post post){
ContentValues values = getContentValues(post);
mDatabase.insert(PostTable.NAME, null, values);
Log.d(TAG, "addPost() called");
} //addPost()
private static ContentValues getContentValues(Post post){
ContentValues values = new ContentValues();
values.put(PostTable.Cols.ID, post.getId().toString());
values.put(PostTable.Cols.USER, post.getUser());
values.put(PostTable.Cols.POST_TEXT, post.getText());
values.put(PostTable.Cols.POST_PHOTO, post.getImagePath());
values.put(PostTable.Cols.TIMESTAMP, post.getTimestamp());
return values;
} //getContentValues()
} //end class
|
package com.rest.test.service;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.rest.test.entity.User;
import com.rest.test.exception.NoContentException;
import com.rest.test.exception.NotFoundException;
import com.rest.test.repository.UserRepository;
@Service
public class UserService {
@Autowired
private UserRepository userRepository;
public List<User> getAllUserInfo(User user) {
List<User> userList = new ArrayList<User>();
User userObj = new User();
userObj.setUserId(user.getUserId());
userObj.setUserName(user.getUserName());
userRepository.saveAll(userList);
if(userRepository.findAll().isEmpty()) {
throw new NoContentException("DB is empty");
}
return userRepository.findAll();
}
public User getUserByUserId(String userId) {
User usrObj = new User();
usrObj = userRepository.findById(userId).orElse(null);
if(null==usrObj) {
throw new NotFoundException("userId:", "userId-" + userId);
}else {
return usrObj;
}
}
public User createNewUser(User users) {
User objUser = new User();
objUser.setUserId(users.getUserId());
objUser.setUserName(users.getUserName());
return userRepository.save(objUser);
}
}
|
package com.itheima.ssm.service;
import com.itheima.ssm.domain.Permission;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public interface IPermissionService {
List<Permission> findAll() throws Exception;
void save(Permission permission)throws Exception;
Permission findById(String permissionId)throws Exception;
void deleteRole(String permissionId);
}
|
package prj.betfair.api.betting.operations;
import java.util.List;
import java.util.Set;
import prj.betfair.api.betting.datatypes.MarketFilter;
import prj.betfair.api.betting.datatypes.PlaceInstruction;
import prj.betfair.api.betting.datatypes.ReplaceInstruction;
import prj.betfair.api.betting.datatypes.SimpleTypes.BetStatus;
import prj.betfair.api.betting.datatypes.SimpleTypes.TimeGranularity;
import prj.betfair.api.betting.datatypes.UpdateInstruction;
import prj.betfair.api.common.Executor;
/**
* This class serves holds a collection of factory methods for the betting operations provided
* within this API. Each method will return a Builder for the corresponding operation with the
* preset operation executor provided at creation of the OperationBuilderFactory.
*/
public class OperationFactory {
private final Executor executor;
public OperationFactory(Executor executor) {
this.executor = executor;
}
/**
* Returns a cancelOrdersOperation builder with the OperationBuilderFactory's executor
*
* @return CancelOrdersOperation.Builder
*/
public CancelOrdersOperation.Builder cancelOrders() {
return new CancelOrdersOperation.Builder().withExecutor(executor);
}
/**
* Returns a listClearedOrdersOperation builder with the OperationBuilderFactory's executor
*
* @return ListClearedOrdersOperation.Builder
*/
public ListClearedOrdersOperation.Builder listClearedOrders(BetStatus betStatus) {
return new ListClearedOrdersOperation.Builder(betStatus).withExecutor(executor);
}
/**
* Returns a listCompetitionsOperation builder with the OperationBuilderFactory's executor
*
* @return ListCompetitionsOperation.Builder
*/
public ListCompetitionsOperation.Builder listCompetitions(MarketFilter marketFilter) {
return new ListCompetitionsOperation.Builder(marketFilter).withExecutor(executor);
}
/**
* Returns a listCountriesOperation builder with the OperationBuilderFactory's executor
*
* @return ListCompetitionsOperation.Builder
*/
public ListCountriesOperation.Builder listCountries(MarketFilter marketFilter) {
return new ListCountriesOperation.Builder(marketFilter).withExecutor(executor);
}
/**
* Returns a listCurrentOrdersOperation builder with the OperationBuilderFactory's executor
*
* @return ListCurrentOrdersOperation.Builder
*/
public ListCurrentOrdersOperation.Builder listCurrentOrder() {
return new ListCurrentOrdersOperation.Builder().withExecutor(executor);
}
/**
* Returns a listEventsOperation builder with the OperationBuilderFactory's executor
*
* @return ListEventsOperation.Builder
*/
public ListEventsOperation.Builder listEvents(MarketFilter marketFilter) {
return new ListEventsOperation.Builder(marketFilter).withExecutor(executor);
}
/**
* Returns a listEventTypesOperation builder with the OperationBuilderFactory's executor
*
* @return ListEventTypesOperation.Builder
*/
public ListEventTypesOperation.Builder listEventTypes(MarketFilter marketFilter) {
return new ListEventTypesOperation.Builder(marketFilter).withExecutor(executor);
}
/**
* Returns a listMarketBookOperation builder with the OperationBuilderFactory's executor
*
* @return ListMarketBookOperation.Builder
*/
public ListMarketBookOperation.Builder listMarketBook(List<String> marketIds) {
return new ListMarketBookOperation.Builder(marketIds).withExecutor(executor);
}
/**
* Returns a listMarketCatalogueOperation builder with the OperationBuilderFactory's executor
*
* @return ListMarketCatalogueOperation.Builder
*/
public ListMarketCatalogueOperation.Builder listMarketCatalogue(MarketFilter marketFilter,
int maxResults) {
return new ListMarketCatalogueOperation.Builder(marketFilter, maxResults)
.withExecutor(executor);
}
/**
* Returns a listMarketProfitAndLossOperation builder with the OperationBuilderFactory's executor
*
* @return ListMarketProfitAndLossOperation.Builder
*/
public ListMarketProfitAndLossOperation.Builder listMarketProfitAndLoss(Set<String> marketIds) {
return new ListMarketProfitAndLossOperation.Builder(marketIds).withExecutor(executor);
}
/**
* Returns a listMarketTypesOperation builder with the OperationBuilderFactory's executor
*
* @return ListMarketTypesOperation.Builder
*/
public ListMarketTypesOperation.Builder listMarketTypes(MarketFilter marketFilter) {
return new ListMarketTypesOperation.Builder(marketFilter).withExecutor(executor);
}
/**
* Returns a listTimeRangesOperation builder with the OperationBuilderFactory's executor
*
* @return ListTimeRangesOperation.Builder
*/
public ListTimeRangesOperation.Builder listTimeRanges(MarketFilter marketFilter,
TimeGranularity granularity) {
return new ListTimeRangesOperation.Builder(marketFilter, granularity).withExecutor(executor);
}
/**
* Returns a listVenuesOperation builder with the OperationBuilderFactory's executor
*
* @return ListVenuesOperation.Builder
*/
public ListVenuesOperation.Builder listVenues(MarketFilter marketFilter) {
return new ListVenuesOperation.Builder(marketFilter).withExecutor(executor);
}
/**
* Returns a placeOrdersOperation builder with the OperationBuilderFactory's executor
*
* @return PlaceOrdersOperation.Builder
*/
public PlaceOrdersOperation.Builder placeOrders(String marketId,
List<PlaceInstruction> instructions) {
return new PlaceOrdersOperation.Builder(instructions, marketId).withExecutor(executor);
}
/**
* Returns a replaceOrdersOperation builder with the OperationBuilderFactory's executor
*
* @return ReplaceOrdersOperation.Builder
*/
public ReplaceOrdersOperation.Builder replaceOrders(String marketId,
List<ReplaceInstruction> instructions) {
return new ReplaceOrdersOperation.Builder(instructions, marketId).withExecutor(executor);
}
/**
* Returns a updateOrdersOperation builder with the OperationBuilderFactory's executor
*
* @return UpdateOrdersOperation.Builder
*/
public UpdateOrdersOperation.Builder updateOrders(String marketId,
List<UpdateInstruction> instructions) {
return new UpdateOrdersOperation.Builder(instructions, marketId).withExecutor(executor);
}
}
|
package com.yougou.dto.input;
/**
* <p>Title: QueryCommodityInputDto</p>
* <p>Description: </p>
* @author: zheng.qq
* @date: 2016年6月12日
*/
public class QueryCommodityInputDto extends PageableInputDto{
private static final long serialVersionUID = 3239551005430432365L;
/**
* 商品编号
*/
private String commodity_no;
/**
* 查询的开始时间(修改时间)
*/
private String start_modified;
/**
* 查询的结束时间(修改时间)
*/
private String end_modified;
/**
* 商品状态
*/
private Integer status = 1;
public String getCommodity_no() {
return commodity_no;
}
public void setCommodity_no(String commodity_no) {
this.commodity_no = commodity_no;
}
public String getStart_modified() {
return start_modified;
}
public void setStart_modified(String start_modified) {
this.start_modified = start_modified;
}
public String getEnd_modified() {
return end_modified;
}
public void setEnd_modified(String end_modified) {
this.end_modified = end_modified;
}
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = (status == null)?1:status;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.