text
stringlengths
10
2.72M
package global.dao; import global.model.Office; import global.model.View_office; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; public class Viewofficeaccess { public static ArrayList<View_office> getoffice(String d_id) { // 生成查找“Office”表的select查询语句 String sql = "SELECT * FROM view_office"; // 如果传入的部门编号不为空,则SQL语句添加查找条件为根据部门编号查找“Office”视图数据 if (!(d_id == null || d_id.equals(""))) { sql += " WHERE d_id='" + d_id + "'"; } // 初始化“Office”类的数组列表对象 ArrayList<View_office> officelist = new ArrayList<View_office>(); // 取得数据库的连接 Connection con = null; ResultSet rs = null; try { con = Databaseconnection.getconnection(); // 如果数据库的连接为空,则返回空 if (con == null) return null; // 生成数据库声明对象 Statement st = con.createStatement(); // 声明对象执行SQL语句,返回满足条件的结果集 rs = st.executeQuery(sql); // 如果结果集有数据 while (rs.next()) { // 取出结果集对应字段数据 d_id = rs.getString("d_id"); String d_name = rs.getString("d_name"); String o_id = rs.getString("o_id"); String o_name = rs.getString("o_name"); // 根据结果集的数据生成“Office”类对象 View_office of = new View_office(d_id, d_name, o_id, o_name); // 将“Office”类对象添加到“Office”类的数组列表对象中 officelist.add(of); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { try { rs.close(); con.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } // System.out.println(officelist); // 返回“View_teacher”类的数组列表对象 return officelist; } }
//import java.util.Arrays; //import java.util.Scanner; // //public class MultiplicationTable { // // public static void main(String[] args) { // // Scanner input = new Scanner(System.in); // // int[][] table = new int[10][10]; // for (int i = 0; i < table.length; i++) { // for (int j = 0; j < table[i].length; j++) { // table[i][j] = (i + 1) * (j + 1); // } // } // // for (int[] a: table) { // for (int i: a) { // System.out.print(i + "\t"); // } // System.out.print("\n"); // } // System.out.println(); // // // // System.out.print("Enter first number (start number): "); // int first = Integer.parseInt(input.nextLine()); // // System.out.print("Enter second number (stop number): "); // int second = Integer.parseInt(input.nextLine()); // // int[][] userTable = new int[second-first+1][second-first+1]; // for (int i = 0; i < userTable.length; i++) { // for (int j = 0; j < userTable[i].length; j++) { // userTable[i][j] = (i + first) * (j + first); // } // } // for (int i = first; i <= second; i++) { // System.out.print(i + "\t"); // } // System.out.println("\n--------------------------------------"); // // for (int i = first; i <= second; i++) { // System.out.println(i + "|" + "\t"); // for (int[] a: userTable) { // for (int num: a) { // System.out.print(num + "\t"); // } // System.out.print("\n"); // } // } // } //} //
package com.citibank.ods.persistence.pl.dao; import java.math.BigInteger; import com.citibank.ods.common.dataset.DataSet; import com.citibank.ods.entity.pl.TplProductMovEntity; /** * Esta interface declara os método abstratos(Insert, List, Update, * Delete,List, find e nstantiateFromResultSet para a tabelaTplProductMov, * separando o comportamento das operações independente do modo como. os dados * são acessados(Oracle, SQL, XML, etc). * @author leonardo.nakada * @date 04/04/2007 */ public interface TplProductMovDAO extends BaseTplProductDAO { /** * Métodos Abstratos * */ public TplProductMovEntity insert( TplProductMovEntity tplProductMovEntity_ ); public TplProductMovEntity update( TplProductMovEntity tplProductMovEntity_ ); public TplProductMovEntity delete( TplProductMovEntity tplProductMovEntity_ ); public DataSet list( String prodCode_, BigInteger prodFamlCode_, String prodName_, BigInteger prodQlfyCode_, BigInteger prodRiskCatCode_, BigInteger prodSubFamlCode_, String lastUpdUserId_ ); public boolean exists( TplProductMovEntity tplProductMovEntity_ ); }
/** * Copyright (C) 2008 Atlassian * * 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.atlassian.theplugin.idea.jira.tree; import com.atlassian.connector.commons.jira.beans.JIRAProject; import com.atlassian.connector.commons.jira.beans.JIRAProjectBean; import com.atlassian.connector.commons.jira.rss.JIRAException; import com.atlassian.theplugin.commons.jira.JiraServerData; import com.atlassian.theplugin.idea.IdeaHelper; import com.atlassian.theplugin.idea.ui.DialogWithDetails; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.DialogWrapper; import com.intellij.ui.ListSpeedSearch; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.awt.*; /** * @author pmaruszak * date Mar 24, 2010 */ public class SelectJiraProjectDialog extends DialogWrapper { private JPanel panel = new JPanel (new BorderLayout()); private JList list; private DefaultListModel listModel = new DefaultListModel(); private final Project project; private final JiraServerData jiraServer; public SelectJiraProjectDialog(Project project, JiraServerData jiraServer) { super(project, false); this.project = project; this.jiraServer = jiraServer; list = new JList(listModel); ListSpeedSearch speedList = new ListSpeedSearch(list); list.setModel(listModel); list.setVisibleRowCount(20); list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); JScrollPane listScroller = new JScrollPane(speedList.getComponent()); listScroller.setPreferredSize(new Dimension(380, 320)); listScroller.setMinimumSize(new Dimension(350, 320)); setModal(true); panel.add(listScroller, BorderLayout.CENTER); updateModel(); setTitle("Select Project"); init(); } @Override protected JComponent createCenterPanel() { return panel; } @Nullable public JIRAProjectBean getSelectedProject() { return list.getSelectedValue() != null ? ((JiraProjectWrapper)list.getSelectedValue()).getJiraProject() : null; } private void updateModel() { try { for (JIRAProject p : IdeaHelper.getJIRAServerModel(project).getProjects(jiraServer)) { if (p.getKey() != null) { listModel.addElement(new JiraProjectWrapper((JIRAProjectBean) p)); } } } catch (JIRAException e) { DialogWithDetails.showExceptionDialog(project, "Cannot retrieve project from server", ""); } } @Override protected void doOKAction() { super.doOKAction(); } private class JiraProjectWrapper { private final JIRAProjectBean jiraProject; private JiraProjectWrapper(JIRAProjectBean jiraProject) { this.jiraProject = jiraProject; } public JIRAProjectBean getJiraProject() { return jiraProject; } @Override public String toString() { return jiraProject.getName() + " (" + jiraProject.getKey() + ")"; } } }
package WebView; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.util.ResourceBundle; import javafx.concurrent.Worker; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.control.Button; import javafx.scene.control.Tab; import javafx.scene.control.TabPane; import javafx.scene.control.TextField; import javafx.scene.web.WebEngine; import javafx.scene.web.WebView; public class Controller implements Initializable { String htlink = ""; @FXML Button btnGo; @FXML TextField addressBar; @FXML WebView web; WebView current; Button refresh; WebEngine engine, currentEngine; Tab currentTab; String addressLink = ""; @FXML TabPane tabs; @FXML Button addNewTab; String refreshLink = ""; Button back; @FXML Button forward, viewSource; @FXML public void go(ActionEvent event) throws IOException { current = new WebView(); currentEngine = new WebEngine(); current.setPrefSize(web.getPrefWidth(), web.getPrefHeight()); //set preferences from the first tab //get the selected tab currentTab = tabs.getSelectionModel().getSelectedItem(); current = (WebView) currentTab.getContent(); //get the webview associated with the tab currentEngine = current.getEngine(); addressLink = addressBar.getText().toString(); if (!addressLink.contains("http")) { if (checkUrlExists("http://" + addressLink)) { addressLink = "http://" + addressLink; } else { addressLink = "https://duckduckgo.com/?t=ffab&q=" + addressLink; } } //load site currentEngine.load(addressLink); currentEngine.setUserAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:84.0) Gecko/20100101 Firefox/84.0 "); //if site has finished loading! addressBar.setText(currentEngine.getLocation().toString()); setName(); listenToChange(); } /*Start of browser*/ @Override public void initialize(URL location, ResourceBundle resources) { currentEngine = web.getEngine(); currentEngine.load("https://broow.neocities.org"); currentEngine.setUserAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.86 Safari/537.36"); currentTab = tabs.getSelectionModel().getSelectedItem(); setName(); System.out.println(currentTab.onSelectionChangedProperty().getName()); updateAdBar(currentEngine.getLocation().toString()); } /*Listen to changes in activity*/ public void listenToChange() { tabs.getSelectionModel().selectedItemProperty().addListener((ov, oldTab, newTab) -> { currentTab = tabs.getSelectionModel().getSelectedItem(); current = (WebView) currentTab.getContent(); //get the webview associated with current tab currentEngine = current.getEngine(); System.out.println(currentEngine.getTitle().toString()); setTabName(currentEngine.getTitle().toString()); updateAdBar(currentEngine.getLocation().toString()); }); currentEngine.getLoadWorker().stateProperty().addListener((obs, oldState, newState) -> { { if (oldState != newState) { updateAdBar(currentEngine.getLocation().toString()); } } }); setName(); } /*Add Tab Button*/ @FXML public void addTab(ActionEvent event) { Tab tab = new Tab(); tab.setText("New Tab"); WebView newTab = new WebView(); WebEngine newTabEngine = newTab.getEngine(); newTabEngine.load("https://broow.neocities.org"); tab.setContent(newTab); tabs.getTabs().add(tab); updateAdBar(currentEngine.getLocation().toString()); } /*Add new Tab for source viewing : Default is Google for now*/ public void addTab(String code) { Tab tab = new Tab(); tab.setText("Source Code"); WebView newTab = new WebView(); WebEngine newTabEngine = newTab.getEngine(); newTabEngine.loadContent(code, "text/plain"); tab.setContent(newTab); tabs.getTabs().add(tab); updateAdBar(currentEngine.getLocation().toString()); } /*Set Tab Name*/ public void setTabName(String name) { currentTab.setText(name); updateAdBar(currentEngine.getLocation().toString()); } /*Refresh Page*/ public void refresh() { currentEngine.reload(); setName(); updateAdBar(currentEngine.getLocation().toString()); } /*Set Name of Tab*/ public void setName() { currentEngine.getLoadWorker().stateProperty().addListener((obs, oldState, newState) -> { if (newState == Worker.State.SUCCEEDED) { String name = currentEngine.titleProperty().toString(); setTabName(name.substring(name.indexOf("value: ") + "value: ".length(), name.lastIndexOf("-"))); } }); } /*Update the address bar*/ public void updateAdBar(String address) { addressBar.setText(address); } @FXML public void viewSource() throws IOException { Tab tab = new Tab(); tab.setText("Github"); WebView newTab = new WebView(); WebEngine newTabEngine = newTab.getEngine(); newTabEngine.load("https://github.com/slaxeea"); tab.setContent(newTab); tabs.getTabs().add(tab); updateAdBar(currentEngine.getLocation().toString()); } /*Check if URL exists */ public boolean checkUrlExists(String url) throws IOException { URL urlToCheck = new URL(url); HttpURLConnection huc = (HttpURLConnection) urlToCheck.openConnection(); huc.setRequestMethod("GET"); int code; try { huc.connect(); code = huc.getResponseCode(); } catch (Exception e) //url does not exist { code = -1232; //please don't judge } if (code == -1232) { return false; } return true; } }
package edu.cb.sweezy.kenneth; import edu.jenks.dist.cb.TestableArray; public class ArrayTester implements TestableArray { private int[][] array; public ArrayTester() { array = new int[0][0]; } public ArrayTester(int[][] arr) { array = arr; } public boolean containsDuplicates(int[] arr) { for (int i : arr) { if (howMany(arr, i) > 1) { return true; } } return false; } public int[] getColumn(int[][] arr2D, int c) { int[] temp = new int[arr2D.length]; for (int i = 0; i < temp.length; i++) { temp[i] = arr2D[i][c]; // System.out.print(arr2D[i][c] + ",\n"); } return temp; } public boolean hasAllValues(int[] arr1, int[] arr2) { int count = 0; for (int i : arr1) { if (contains(arr2, i)) { count++; } } if (count == arr1.length) { return true; } else { return false; } } public boolean isLatin(int[][] a) { if (containsDuplicates(a[0])) { return false; } else { for (int[] element : a) { if (hasAllValues(a[0], element)) { for (int j = 0; j < a[0].length; j++) { if (hasAllValues(a[0], getColumn(a, j))) { return true; } else { return false; } } } else { return false; } } } return false; } public static void main(String[] args) { ArrayTester testing = new ArrayTester(); // getColumn() testing /* * int count = 0; int[][] testArr = new int[3][3]; for (int i = 0; i < * testArr.length; i++) { for (int j = 0; j < testArr[i].length; j++) { * testArr[i][j] = count; count++; } } ArrayTester testing = new * ArrayTester(testArr); testing.print2DArr(); int[] columnTest = * testing.getColumn(testArr, 0); for (int i : columnTest) { * System.out.print(i); } */ // hasAllValues() testing /* * testing int[] arr1 = new int[] { 1, 2, 3 }; int[] arr2 = new int[] { 1, 4, 3 * }; System.out.println(testing.hasAllValues(arr1, arr2)); */ // containsDuplicates() testing /* * int[] testingArr = new int[] { 1, 1, 2 }; * System.out.println(testing.containsDuplicates(testingArr)); */ int[][] testingArr = new int[][] { { 1, 2 }, { 1, 2 } }; System.out.println(testing.isLatin(testingArr)); } private void print2DArr() { System.out.print("["); for (int[] iO : array) { System.out.print("["); for (int iT : iO) { System.out.print(iT + ", "); } System.out.print("], "); } System.out.print("]"); } private boolean contains(int[] arr, int num2Check) { for (int i : arr) { if (i == num2Check) { return true; } } return false; } private int howMany(int[] a, int toFind) { int count = 0; for (int i : a) { if (i == toFind) { ++count; } } return count; } }
package com.phicomm.account.main; import android.accounts.AccountAuthenticatorActivity; import java.io.StringReader; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.xml.sax.InputSource; import com.phicomm.account.R; import com.phicomm.account.provider.DatabaseHelper; import com.phicomm.account.provider.Person; import com.phicomm.account.provider.Provider; import com.phicomm.account.register.FindPwdWebView; import com.phicomm.account.register.RegWebView; import com.phicomm.account.util.FxConstants; import com.phicomm.account.util.MCrypt; import com.phicomm.account.util.MD5; import com.phicomm.account.util.NetworkUtilities; import com.phicomm.account.util.ReadDoc; import com.phicomm.account.util.Result; import android.accounts.Account; import android.accounts.AccountManager; import android.content.ContentValues; import android.content.Intent; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Color; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.text.TextUtils; import android.util.Base64; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import android.app.ActionBar; import android.view.Menu; import android.view.MenuItem; import android.app.AlertDialog; import android.app.AlertDialog.Builder; import android.content.DialogInterface; import com.phicomm.account.util.FxDisplayAuthInfo; import android.text.TextWatcher; import android.text.Editable; import android.text.InputType; import android.view.View.OnFocusChangeListener; import com.phicomm.account.util.ClearEditText; public class AuthenticatorActivity extends AccountAuthenticatorActivity { private String TAG = "AuthenticatorActivity"; private String mUsername, mPassword; private ClearEditText mUsernameEdit; private ClearEditText mPasswordEdit; private UserLoginTask mAuthTask; private AccountManager mAccountManager; private TextView mLoginView; private TextView mFindPassword; private View mEye; private Result resultFromService; private TextView mAccountInfo; //modified for bug:CBBAT-1120. private View mUserView; private View mPasswordView; //end private static final int ID = 1; @Override protected void onCreate(Bundle icicle) { // TODO Auto-generated method stub super.onCreate(icicle); setContentView(R.layout.login_activity); mUsernameEdit = (ClearEditText) findViewById(R.id.username); mPasswordEdit = (ClearEditText) findViewById(R.id.password); mLoginView = (TextView) findViewById(R.id.account_login); mFindPassword = (TextView) findViewById(R.id.find_password); mEye = (View) findViewById(R.id.eye); mUserView = (View) findViewById(R.id.user_view); mPasswordView = (View) findViewById(R.id.password_view); mFindPassword.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub Intent intent = new Intent(); intent.setClass(AuthenticatorActivity.this, FindPwdWebView.class); startActivity(intent); } }); mLoginView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub handleLogin(); } }); mEye.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub //modified for bug:CBBAT-1122. if (mPasswordEdit.getInputType() == 129) { mPasswordEdit .setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD); } else { mPasswordEdit.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD); } } }); mAccountInfo = (TextView) findViewById(R.id.account_info); mAccountInfo.setTextColor(Color.RED); //modified for bug:CBBAT-1120. mUsernameEdit.setOnFocusChangeListener(mUsernameFocusChangeListener); mPasswordEdit.setOnFocusChangeListener(mPasswordFocusChangeListener); mAccountManager = AccountManager.get(this); } //modified for bug:CBBAT-1120. private OnFocusChangeListener mUsernameFocusChangeListener = new OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { if (hasFocus) { mUserView .setBackgroundResource(R.drawable.icon_contact_pressed); } else { mUserView.setBackgroundResource(R.drawable.icon_contact); } } }; private OnFocusChangeListener mPasswordFocusChangeListener = new OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { if (hasFocus) { mPasswordView .setBackgroundResource(R.drawable.icon_contact_lock); } else { mPasswordView .setBackgroundResource(R.drawable.ic_cancle_lock_normal); } } }; //end public void handleLogin() { mUsername = mUsernameEdit.getText().toString(); mPassword = mPasswordEdit.getText().toString(); if (TextUtils.isEmpty(mUsername) || TextUtils.isEmpty(mPassword)) { //modified for bug:CBBAT-1123. if (TextUtils.isEmpty(mUsername) && !TextUtils.isEmpty(mPassword)) { mAccountInfo.setText(getResources().getString( R.string.nameisNull)); } else if (!TextUtils.isEmpty(mUsername) && TextUtils.isEmpty(mPassword)) { mAccountInfo.setText(getResources().getString( R.string.passwordIsNull)); } else { mAccountInfo.setText(getResources().getString( R.string.psdOrNameisNull)); } } else { // Show a progress dialog, and kick off a background task to perform // the user login attempt. mAuthTask = new UserLoginTask(); // mAuthTask.execute(); Log.i(TAG, "Fx mAuthTask.execute():" + mAuthTask.execute()); } } public class UserLoginTask extends AsyncTask<Void, Void, String> { @Override protected String doInBackground(Void... params) { // We do the actual work of authenticating the user // in the NetworkUtilities class. try { Log.i(TAG, "Fx UserLoginTask"); return NetworkUtilities.authenticate(getApplicationContext() ,mUsername, mPassword); } catch (Exception ex) { Log.e(TAG, "UserLoginTask.doInBackground: failed to authenticate"); Log.i(TAG, ex.toString()); return "error"; } } @Override protected void onPostExecute(final String authToken) { // On a successful authentication, call back into the Activity to // communicate the authToken (or null for an error). Log.i(TAG, "onPostExecute authToken:" + authToken); onAuthenticationResult(authToken); } @Override protected void onCancelled() { // If the action was canceled (by the user clicking the cancel // button in the progress dialog), then call back into the // activity to let it know. // onAuthenticationCancel(); } } public void onAuthenticationResult(String authToken) { // TODO Auto-generated method stub if ("error".equals(authToken)) { popDialog(); return; } try { Log.i(TAG, "Fx authToken:" + authToken); StringReader sr = new StringReader(authToken); InputSource is = new InputSource(sr); DocumentBuilderFactory factory = DocumentBuilderFactory .newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); org.w3c.dom.Document doc = builder.parse(is); resultFromService = ReadDoc.readXML(doc); Log.i(TAG, "Fx resultFromService.getStatusCode():" + resultFromService.getStatusCode()); if (resultFromService.getStatusCode().equals("0")) { setDataToDataBases(resultFromService); } else { FxDisplayAuthInfo.displayUserInfo(mUsername, mPassword, mAccountInfo, resultFromService, mUserView, mPasswordView); } } catch (Exception e) { e.printStackTrace(); } } private void popDialog() { Builder builder = new AlertDialog.Builder(this); builder.setTitle(R.string.prompt); builder.setMessage(R.string.prompt_info); builder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // TODO Auto-generated method stub dialog.dismiss(); startActivity(new Intent( android.provider.Settings.ACTION_WIFI_SETTINGS)); } }); builder.create().show(); } private void setDataToDataBases(Result resultFromService) { // TODO Auto-generated method stub Person p = new Person(); String isStringNull = getResources().getString(R.string.isStringNull); String isMale = getResources().getString(R.string.isMale); String isFemale = getResources().getString(R.string.isFemale); if (TextUtils.isEmpty(resultFromService.getUserName()) || resultFromService.getUserName() == null) { p.name = isStringNull; } else { p.name = resultFromService.getUserName(); } if (TextUtils.isEmpty(resultFromService.getUserId()) || resultFromService.getUserId() == null) { p.userId = isStringNull; } else { p.userId = resultFromService.getUserId(); } if (TextUtils.isEmpty(resultFromService.getUserEmail()) || resultFromService.getUserEmail() == null) { p.userEmail = isStringNull; } else { p.userEmail = resultFromService.getUserEmail(); } if (TextUtils.isEmpty(resultFromService.getPhone()) || resultFromService.getPhone() == null || resultFromService.getPhone().equals("null")) { p.phone = isStringNull; } else { p.phone = resultFromService.getPhone(); } if (TextUtils.isEmpty(resultFromService.getUserTrueName()) || resultFromService.getUserTrueName() == null) { p.trueName = isStringNull; } else { p.trueName = resultFromService.getUserTrueName(); } if (resultFromService.getUserSex().equals("0")) { p.userSex = isMale; } else { p.userSex = isFemale; } if (TextUtils.isEmpty(resultFromService.getUserBirth()) || resultFromService.getUserBirth() == null) { p.userBirth = isStringNull; } else { p.userBirth = resultFromService.getUserBirth(); } if (TextUtils.isEmpty(resultFromService.getNickName()) || resultFromService.getNickName() == null) { p.nickName = isStringNull; } else { p.userBirth = resultFromService.getNickName(); } if (TextUtils.isEmpty(resultFromService.getUserAddress()) || resultFromService.getUserAddress() == null) { p.userAddress = isStringNull; } else { p.userAddress = resultFromService.getUserAddress(); } if (TextUtils.isEmpty(resultFromService.getImage()) || resultFromService.getImage() == null) { p.userImage = isStringNull; } else { p.userImage = resultFromService.getImage(); } if (TextUtils.isEmpty(resultFromService.getUserCreateTime()) || resultFromService.getUserCreateTime() == null) { p.createTime = isStringNull; } else { p.createTime = resultFromService.getUserCreateTime(); } if (TextUtils.isEmpty(resultFromService.getUserAge()) || resultFromService.getUserAge() == null) { p.age = isStringNull; } else { p.age = resultFromService.getUserAge(); } if (TextUtils.isEmpty(resultFromService.getKeyuserKey()) || resultFromService.getKeyuserKey() == null) { p.userKey = isStringNull; } else { p.userKey = resultFromService.getKeyuserKey(); } if (TextUtils.isEmpty(resultFromService.getJssessionid()) || resultFromService.getJssessionid() == null) { p.jssessionid = isStringNull; } else { p.jssessionid = resultFromService.getJssessionid(); } if (TextUtils.isEmpty(resultFromService.getSyncTime()) || resultFromService.getSyncTime() == null) { p.syncTime = ""; } else { p.syncTime = resultFromService.getSyncTime(); } p.contactSwitcherSelected = 0; p.password = mPasswordEdit.getText().toString(); getContentResolver().delete(Provider.PersonColumns.CONTENT_URI, null, null); insert(p); Intent intent = new Intent(); Bundle bl = new Bundle(); bl.putString("userImage", p.userImage); bl.putString("userName", p.name); bl.putString("userId", p.userId); intent.putExtras(bl); intent.setClass(AuthenticatorActivity.this, UserInfoActivity.class); startActivity(intent); finish(); } private void insert(Person person) { ContentValues values = new ContentValues(); values.put(Provider.PersonColumns.USER_KEY, person.userKey); values.put(Provider.PersonColumns.AGE, person.age); values.put(Provider.PersonColumns.USER_ID, person.userId); values.put(Provider.PersonColumns.JSSESSIONID, person.jssessionid); values.put(Provider.PersonColumns.NAME, person.name); values.put(Provider.PersonColumns.TRUE_NAME, person.trueName); values.put(Provider.PersonColumns.USER_SEX, person.userSex); values.put(Provider.PersonColumns.USER_BIRTH, person.userBirth); values.put(Provider.PersonColumns.USER_ADDRESS, person.userAddress); values.put(Provider.PersonColumns.USER_EMAIL, person.userEmail); values.put(Provider.PersonColumns.CREATETIME, person.createTime); values.put(Provider.PersonColumns.PHONE, person.phone); values.put(Provider.PersonColumns.USER_IMAGE, person.userImage); values.put(Provider.PersonColumns.NICK_NAME, person.nickName); values.put(Provider.PersonColumns.PASSWORD, person.password); values.put(Provider.PersonColumns.SYNC_TIME, person.syncTime); values.put(Provider.PersonColumns.CONTACT_SWITCHER_SELECTED, person.contactSwitcherSelected); Uri uri = getContentResolver().insert( Provider.PersonColumns.CONTENT_URI, values); Log.i(TAG, "insert uri=" + uri); String lastPath = uri.getLastPathSegment(); if (TextUtils.isEmpty(lastPath)) { Log.i(TAG, "insert failure!"); } else { Log.i(TAG, "insert success! the id is " + lastPath); } } private void finishLogin(Result authToken) { final Account account = new Account(mUsername, FxConstants.ACCOUNT_TYPE); mAccountManager.addAccountExplicitly(account, mPassword, null); // mAccountManager.setPassword(account, mPassword); final Intent intent = new Intent(); intent.putExtra(AccountManager.KEY_ACCOUNT_NAME, mUsername); intent.putExtra(AccountManager.KEY_ACCOUNT_TYPE, FxConstants.ACCOUNT_TYPE); setAccountAuthenticatorResult(intent.getExtras()); setResult(RESULT_OK, intent); } @Override protected void onStart() { super.onStart(); ActionBar actionBar = this.getActionBar(); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.action_register: Intent intent = new Intent(); intent.setClass(AuthenticatorActivity.this, RegWebView.class); startActivity(intent); return true; default: return super.onOptionsItemSelected(item); } } }
package com.god.gl.vaccination.service; import android.app.IntentService; import android.content.Intent; import android.os.Handler; import android.support.annotation.Nullable; import com.god.gl.vaccination.util.LogX; import com.god.gl.vaccination.util.SoundPlayUtils; /** * @author gl * @date 2018/12/15 * @desc */ public class PlayService extends IntentService { private Handler mHandler; public PlayService() { super("PlayService"); } public PlayService(String name) { super(name); } @Override public void onCreate() { super.onCreate(); mHandler = new Handler(getMainLooper()); SoundPlayUtils.init(getApplicationContext()); } @Override protected void onHandleIntent(@Nullable Intent intent) { mHandler.post(new Runnable() { @Override public void run() { SoundPlayUtils.play(1); } }); } @Override public void onDestroy() { super.onDestroy(); LogX.e("onDestroy","onDestroy"); } }
package com.demo.mydishgame.controller; import java.util.Optional; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import com.demo.mydishgame.controller.food.FoodQuizController; import com.demo.mydishgame.model.DishQuestion; import com.demo.mydishgame.model.FoodQuestionTree; import com.demo.mydishgame.model.FoodTypeQuestion; class FoodQuizControllerTest { @Test void checkIfGetFirstSubjectAfterReset() { final FoodTypeQuestion chineseFoodQuestion = new FoodTypeQuestion("Chinese food"); final DishQuestion springRollQuestion = new DishQuestion("Spring Rolls"); final DishQuestion appleQuestion = new DishQuestion("Apple"); chineseFoodQuestion.setQuestionForAnswerYes(springRollQuestion); chineseFoodQuestion.setQuestionForAnswerNo(appleQuestion); final FoodQuestionTree foodQuestionTree = new FoodQuestionTree(chineseFoodQuestion); final FoodQuizController foodQuizController = new FoodQuizController(foodQuestionTree); foodQuizController.updateForAnswer(true); foodQuizController.updateForAnswer(false); foodQuizController.reset(); Assertions.assertFalse(foodQuizController.isFinished()); } @Test void checkIfUnfinishedAfterReset() { final FoodTypeQuestion chineseFoodQuestion = new FoodTypeQuestion("Chinese food"); final DishQuestion springRollQuestion = new DishQuestion("Spring Rolls"); final DishQuestion appleQuestion = new DishQuestion("Apple"); chineseFoodQuestion.setQuestionForAnswerYes(springRollQuestion); chineseFoodQuestion.setQuestionForAnswerNo(appleQuestion); final FoodQuestionTree foodQuestionTree = new FoodQuestionTree(chineseFoodQuestion); final FoodQuizController foodQuizController = new FoodQuizController(foodQuestionTree); foodQuizController.updateForAnswer(true); foodQuizController.updateForAnswer(false); foodQuizController.reset(); Assertions.assertEquals("Chinese food", foodQuizController.getActualQuestionSubject()); } @Test void checkIfUpdateQuestionTreeAfterExtending() { final FoodTypeQuestion chineseFoodQuestion = new FoodTypeQuestion("Chinese food"); final DishQuestion springRollQuestion = new DishQuestion("Spring Rolls"); final DishQuestion appleQuestion = new DishQuestion("Apple"); chineseFoodQuestion.setQuestionForAnswerYes(springRollQuestion); chineseFoodQuestion.setQuestionForAnswerNo(appleQuestion); final FoodQuestionTree foodQuestionTree = new FoodQuestionTree(chineseFoodQuestion); final FoodQuizController foodQuizController = new FoodQuizController(foodQuestionTree); foodQuizController.updateForAnswer(true); foodQuizController.updateForAnswer(false); final FoodTypeQuestion friedQuestion = new FoodTypeQuestion("Fried"); final DishQuestion friedShrimpQuestion = new DishQuestion("Fried Shrimp"); foodQuizController.extendQuiz(friedQuestion, friedShrimpQuestion); foodQuizController.reset(); foodQuizController.updateForAnswer(true); foodQuizController.updateForAnswer(true); Assertions.assertEquals("Fried Shrimp", foodQuizController.getActualQuestionSubject()); } @Test void getWinnerMessageAfterTheMatch() { final FoodTypeQuestion chineseFoodQuestion = new FoodTypeQuestion("Chinese food"); final DishQuestion springRollQuestion = new DishQuestion("Spring Rolls"); final DishQuestion appleQuestion = new DishQuestion("Apple"); chineseFoodQuestion.setQuestionForAnswerYes(springRollQuestion); chineseFoodQuestion.setQuestionForAnswerNo(appleQuestion); final FoodQuestionTree foodQuestionTree = new FoodQuestionTree(chineseFoodQuestion); final FoodQuizController foodQuizController = new FoodQuizController(foodQuestionTree); foodQuizController.updateForAnswer(true); foodQuizController.updateForAnswer(true); final Optional<String> winnerMessage = foodQuizController.getWinnerMessage(); Assertions.assertEquals("I won again!", winnerMessage.get()); } @Test void shouldBeCorrectWhenWin() { final FoodTypeQuestion chineseFoodQuestion = new FoodTypeQuestion("Chinese food"); final DishQuestion springRollQuestion = new DishQuestion("Spring Rolls"); final DishQuestion appleQuestion = new DishQuestion("Apple"); chineseFoodQuestion.setQuestionForAnswerYes(springRollQuestion); chineseFoodQuestion.setQuestionForAnswerNo(appleQuestion); final FoodQuestionTree foodQuestionTree = new FoodQuestionTree(chineseFoodQuestion); final FoodQuizController foodQuizController = new FoodQuizController(foodQuestionTree); foodQuizController.updateForAnswer(true); foodQuizController.updateForAnswer(true); final Optional<Boolean> correct = foodQuizController.isCorrect(); Assertions.assertTrue(correct.get()); } @Test void shouldBeFinishedtAfterAllQuestions() { final FoodTypeQuestion chineseFoodQuestion = new FoodTypeQuestion("Chinese food"); final DishQuestion springRollQuestion = new DishQuestion("Spring Rolls"); final DishQuestion appleQuestion = new DishQuestion("Apple"); chineseFoodQuestion.setQuestionForAnswerYes(springRollQuestion); chineseFoodQuestion.setQuestionForAnswerNo(appleQuestion); final FoodQuestionTree foodQuestionTree = new FoodQuestionTree(chineseFoodQuestion); final FoodQuizController foodQuizController = new FoodQuizController(foodQuestionTree); foodQuizController.updateForAnswer(true); foodQuizController.updateForAnswer(false); Assertions.assertTrue(foodQuizController.isFinished()); } @Test void shouldBeIncorrectWhenLose() { final FoodTypeQuestion chineseFoodQuestion = new FoodTypeQuestion("Chinese food"); final DishQuestion springRollQuestion = new DishQuestion("Spring Rolls"); final DishQuestion appleQuestion = new DishQuestion("Apple"); chineseFoodQuestion.setQuestionForAnswerYes(springRollQuestion); chineseFoodQuestion.setQuestionForAnswerNo(appleQuestion); final FoodQuestionTree foodQuestionTree = new FoodQuestionTree(chineseFoodQuestion); final FoodQuizController foodQuizController = new FoodQuizController(foodQuestionTree); foodQuizController.updateForAnswer(true); foodQuizController.updateForAnswer(false); final Optional<Boolean> correct = foodQuizController.isCorrect(); Assertions.assertFalse(correct.get()); } @Test void shouldBeUnfinishedtWhenThereAreMoreQuestions() { final FoodTypeQuestion chineseFoodQuestion = new FoodTypeQuestion("Chinese food"); final DishQuestion springRollQuestion = new DishQuestion("Spring Rolls"); final DishQuestion appleQuestion = new DishQuestion("Apple"); chineseFoodQuestion.setQuestionForAnswerYes(springRollQuestion); chineseFoodQuestion.setQuestionForAnswerNo(appleQuestion); final FoodQuestionTree foodQuestionTree = new FoodQuestionTree(chineseFoodQuestion); final FoodQuizController foodQuizController = new FoodQuizController(foodQuestionTree); foodQuizController.updateForAnswer(true); Assertions.assertFalse(foodQuizController.isFinished()); } @Test void shouldReturnActualQuestionSubject() { final FoodTypeQuestion chineseFoodQuestion = new FoodTypeQuestion("Chinese food"); final FoodQuestionTree foodQuestionTree = new FoodQuestionTree(chineseFoodQuestion); final FoodQuizController foodQuizController = new FoodQuizController(foodQuestionTree); Assertions.assertEquals("Chinese food", foodQuizController.getActualQuestionSubject()); } @Test void testReturnActualQuestionSubjectAfterUpdate() { final FoodTypeQuestion chineseFoodQuestion = new FoodTypeQuestion("Chinese food"); final DishQuestion springRollQuestion = new DishQuestion("Spring Rolls"); final DishQuestion appleQuestion = new DishQuestion("Apple"); chineseFoodQuestion.setQuestionForAnswerYes(springRollQuestion); chineseFoodQuestion.setQuestionForAnswerNo(appleQuestion); final FoodQuestionTree foodQuestionTree = new FoodQuestionTree(chineseFoodQuestion); final FoodQuizController foodQuizController = new FoodQuizController(foodQuestionTree); foodQuizController.updateForAnswer(true); Assertions.assertEquals("Spring Rolls", foodQuizController.getActualQuestionSubject()); } @Test void shouldReturnActualQuestionText() { final FoodTypeQuestion chineseFoodQuestion = new FoodTypeQuestion("Chinese food"); final FoodQuestionTree foodQuestionTree = new FoodQuestionTree(chineseFoodQuestion); final FoodQuizController foodQuizController = new FoodQuizController(foodQuestionTree); Assertions.assertEquals("The dish that are you thinking is Chinese food?", foodQuizController.getActualQuestionText()); } @Test void testReturnActualQuestionTextAfterUpdate() { final FoodTypeQuestion chineseFoodQuestion = new FoodTypeQuestion("Chinese food"); final DishQuestion springRollQuestion = new DishQuestion("Spring Rolls"); final DishQuestion appleQuestion = new DishQuestion("Apple"); chineseFoodQuestion.setQuestionForAnswerYes(springRollQuestion); chineseFoodQuestion.setQuestionForAnswerNo(appleQuestion); final FoodQuestionTree foodQuestionTree = new FoodQuestionTree(chineseFoodQuestion); final FoodQuizController foodQuizController = new FoodQuizController(foodQuestionTree); foodQuizController.updateForAnswer(false); Assertions.assertEquals("The dish that are you thinking is Apple?", foodQuizController.getActualQuestionText()); } }
import java.util.*; class ques2d26 { public static void main(String args[]) { Scanner sc=new Scanner(System.in); System.out.print("Enter size of array : "); int n=sc.nextInt(); System.out.println("Enter elements of array : "); int a[]=new int[n]; for(int i=0;i<n;i++) a[i]=sc.nextInt(); int c=0; for(int i=1;i<n;i++) { while(a[i]<a[i-1]) { a[i]+=1; c+=1; } } System.out.println("OUTPUT : "+c); } }
package md2k.mCerebrum.cStress.Library; import md2k.mCerebrum.cStress.Structs.DataPoint; import java.util.ArrayList; import java.util.Date; /** * Copyright (c) 2015, The University of Memphis, MD2K Center * - Timothy Hnat <twhnat@memphis.edu> * All rights reserved. * <p/> * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * <p/> * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * <p/> * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * <p/> * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ public class Time { public static long nextEpochTimestamp(long timestamp) { long previousMinute = timestamp / (60 * 1000); Date date = new Date((previousMinute + 1) * (60 * 1000)); return date.getTime(); } public static ArrayList<DataPoint[]> window(ArrayList<DataPoint> data, int size) { ArrayList<DataPoint[]> result = new ArrayList<DataPoint[]>(); if(data.size() > 0) { long startTime = nextEpochTimestamp(data.get(0).timestamp) - 60 * 1000; //Get next minute window and subtract a minute to arrive at the appropriate startTime ArrayList<DataPoint> tempArray = new ArrayList<DataPoint>(); DataPoint[] temp; for (DataPoint dp : data) { if (dp.timestamp < startTime + size) { tempArray.add(dp); } else { temp = new DataPoint[tempArray.size()]; for (int i = 0; i < temp.length; i++) { temp[i] = tempArray.get(i); } result.add(temp); tempArray = new ArrayList<DataPoint>(); startTime += size; } } temp = new DataPoint[tempArray.size()]; for (int i = 0; i < temp.length; i++) { temp[i] = tempArray.get(i); } result.add(temp); } return result; } }
/* * 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 centro.de.computo; import java.io.IOException; import java.net.URL; import java.sql.SQLException; import java.util.List; import java.util.ResourceBundle; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.fxml.Initializable; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.ContextMenu; import javafx.scene.control.Label; import javafx.scene.control.MenuItem; import javafx.scene.control.TableColumn; import javafx.scene.control.TableView; import javafx.scene.control.cell.PropertyValueFactory; import javafx.scene.input.ContextMenuEvent; import javafx.stage.Stage; import javax.swing.JOptionPane; import logica.Equipo; import logica.InterfaceInventarioHardware; import logica.InventarioHardware; /** * FXML Controller class Controlador de InventarioHardware. * * @author PREDATOR 15 G9-78Q */ public class InventarioHardwareController implements Initializable { @FXML private TableView<Equipo> tvInventario; @FXML private TableColumn<Equipo, Integer> tcId; @FXML private TableColumn<Equipo, String> tcTipoEquipo; @FXML private TableColumn<Equipo, String> tcModelo; @FXML private TableColumn<Equipo, String> tcMarca; @FXML private TableColumn<Equipo, Integer> tcNumeroSerie; @FXML private TableColumn<Equipo, String> tcResponsable; @FXML private TableColumn<Equipo, String> tcEstado; @FXML private Button bttRegistrarEquipo; private InterfaceInventarioHardware inventario = new InventarioHardware(); private final String mensajeError = "El sistema no está disponible por el momento, inténtelo más tarde"; /** * Initializes the controller class. */ @Override public void initialize(URL url, ResourceBundle rb) { this.tcId.setCellValueFactory(new PropertyValueFactory<>("identificador")); this.tcTipoEquipo.setCellValueFactory(new PropertyValueFactory<>("tipoEquipo")); this.tcModelo.setCellValueFactory(new PropertyValueFactory<>("modelo")); this.tcNumeroSerie.setCellValueFactory(new PropertyValueFactory<>("numeroSerie")); this.tcResponsable.setCellValueFactory(new PropertyValueFactory<>("responsableUbicacion")); this.tcEstado.setCellValueFactory(new PropertyValueFactory<>("disponibilidad")); this.tcMarca.setCellValueFactory(new PropertyValueFactory<>("marca")); Label labelMenu = new Label(); ContextMenu contextMenu = new ContextMenu(); MenuItem item1 = new MenuItem("Cambiar responsable"); item1.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { labelMenu.setText("Cambiar responsable"); cambiarResponsable(tvInventario.getSelectionModel().getSelectedItem().getModelo(), tvInventario.getSelectionModel().getSelectedItem().getIdentificador()); } }); MenuItem item2 = new MenuItem("Registrar dictamen de mantenimiento"); item2.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { labelMenu.setText("Registrar dictamen de mantenimiento"); registrarDictamen(tvInventario.getSelectionModel().getSelectedItem().getIdentificador()); } }); if (User.getPuesto().equalsIgnoreCase("tecnico")) { contextMenu.getItems().addAll(item2); this.bttRegistrarEquipo.setVisible(false); } else { contextMenu.getItems().addAll(item1, item2); } tvInventario.setOnContextMenuRequested(new EventHandler<ContextMenuEvent>() { @Override public void handle(ContextMenuEvent event) { contextMenu.show(tvInventario, event.getScreenX(), event.getScreenY()); } }); try { this.llenarLista(this.inventario.consultarListaEquipo()); } catch (SQLException ex) { JOptionPane.showMessageDialog(null, this.mensajeError); } } private void llenarLista(List<Equipo> listaEquipo) { tvInventario.getItems().clear(); for (Equipo equipo : listaEquipo) { tvInventario.getItems().add(equipo); } } @FXML private void clickRegistrar(ActionEvent event) { this.abrirVentana("RegistrarEquipo.fxml"); } @FXML private void clickConsultar(ActionEvent event) { try { this.llenarLista(this.inventario.consultarListaEquipo()); } catch (SQLException ex) { JOptionPane.showMessageDialog(null, this.mensajeError); } } private void cambiarResponsable(String modelo, String id) { CambiarResponsableController.mandarModeloNumeroSerie(modelo, id); this.abrirVentana("CambiarResponsable.fxml"); } private void registrarDictamen(String idEquipo) { RegistrarDictamenController.setIdEquipo(idEquipo); this.abrirVentana("RegistrarDictamen.fxml"); } private void abrirVentana(String ventana) { Stage stageEquipo = new Stage(); Parent paneEquipo; try { paneEquipo = FXMLLoader.load(getClass().getResource(ventana)); Scene sceneEquipo = new Scene(paneEquipo); stageEquipo.setScene(sceneEquipo); stageEquipo.show(); } catch (IOException ex) { JOptionPane.showMessageDialog(null, this.mensajeError); } } }
package org.softRoad.models; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import org.softRoad.models.query.QueryUtils; import javax.persistence.*; import javax.validation.constraints.NotNull; import java.util.HashSet; import java.util.Set; @Entity @Table(name = "consultant_profiles") public class ConsultantProfile extends SoftRoadModel { @Transient public final static String ID = "id"; @Transient public final static String BIO = "bio"; @Transient public final static String DESCRIPTION = "description"; @Transient public final static String USER = "user_id"; @Transient public final static String NATIONAL_ID = "national_id"; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) public Integer id; @NotNull @Column(name = "national_id", unique = true, nullable = false) public String nationalID; // TODO: 1/7/2021 nationalCode validation @Transient public Double rate; public String bio; public String description; @OneToMany(mappedBy = "consultant") @JsonIgnore public Set<Consultation> consultations = new HashSet<>(); @OneToMany(mappedBy = "consultant", cascade = CascadeType.REMOVE) @JsonIgnore public Set<Fee> fees = new HashSet<>(); @ManyToMany @JoinTable(name = "consultant_profile_category", joinColumns = @JoinColumn(name = "consultant_id", referencedColumnName = "id"), inverseJoinColumns = @JoinColumn(name = "category_id", referencedColumnName = "id")) public Set<Category> categories = new HashSet<>(); @ManyToMany @JoinTable(name = "consultant_profile_tag", joinColumns = @JoinColumn(name = "consultant_id", referencedColumnName = "id"), inverseJoinColumns = @JoinColumn(name = "tag_id", referencedColumnName = "id")) @JsonIgnore public Set<Tag> tags = new HashSet<>(); @NotNull @OneToOne(fetch = FetchType.LAZY) @JoinColumn(name = "user_id", unique = true, nullable = false) @JsonIgnoreProperties(value = {"roles", "password", "enabled"}) public User user; public void setId(Integer id) { this.id = id; presentFields.add("id"); } public void setBio(String bio) { this.bio = bio; presentFields.add("bio"); } public void setDescription(String description) { this.description = description; presentFields.add("description"); } public void setNationalID(String nationalID) { this.nationalID = nationalID; presentFields.add("nationalID"); } public void setUser(User user) { this.user = user; presentFields.add("user"); } public Double getRate() { // TODO: 1/7/2021 calculate avg. rate from database return rate; } public static String fields(String fieldName, String... fieldNames) { return QueryUtils.fields(ConsultantProfile.class, fieldName, fieldNames); } }
/* * 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 teste; import java.util.Date; import javax.faces.bean.ManagedBean; import javax.faces.bean.RequestScoped; /** * * @author tiago.lucas */ @ManagedBean @RequestScoped public class ExemploMB { /** * Creates a new instance of ExemploMB */ public ExemploMB() { } private Date data; public Date getData() { return data; } public void setData(Date data) { this.data = data; } }
package registraclinic.aluno; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import javax.swing.table.AbstractTableModel; import registraclinic.util.Util; public class AlunoTableModel extends AbstractTableModel { private List<Aluno> aluno = new ArrayList<>(); private String[] colunas = {"Código", "Nome", "Matrícula", "Login", "Senha", "Sexo", "Cidade", "Endereço", "Telefone", "Email"}; public AlunoTableModel(List<Aluno> aluno) { this.aluno = aluno; } @Override /*get row pega o numero de linhas.*/ public int getRowCount() { return aluno.size(); } @Override public int getColumnCount() { return colunas.length; } // private String converterDataString(Date date) { // SimpleDateFormat f = new SimpleDateFormat("dd/MM/yyyy"); // return f.format(date); // } @Override public Object getValueAt(int rowIndex, int columnIndex) { Aluno alunos = aluno.get(rowIndex); switch (columnIndex) { case 0: return alunos.getIdPessoa(); case 1: return alunos.getNomePessoa(); case 2: return alunos.getMatriculaAluno(); case 3: return alunos.getLoginUsuario(); case 4: return alunos.getSenhaUsuario(); case 5: return alunos.getSexoPessoa(); case 6: return alunos.getCidade().getNomeCidade(); case 7: return alunos.getEnderecoPessoa(); case 8: return alunos.getTelefonePessoa(); case 9: return alunos.getEmailUsuario(); } return null; } @Override public String getColumnName(int index) { switch (index) { case 0: return colunas[0]; case 1: return colunas[1]; case 2: return colunas[2]; case 3: return colunas[3]; case 4: return colunas[4]; case 5: return colunas[5]; case 6: return colunas[6]; case 7: return colunas[7]; case 8: return colunas[8]; case 9: return colunas[9]; } return null; } }
package com.ipincloud.iotbj.face.service; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; public interface FaceService { Object syncAcsdev(JSONObject jsonObj); Object gatewayadd(JSONArray jsonObj); Object gatewayup(JSONObject jsonObj); Object regionlist(JSONObject jsonObj); Object gatewaylist(JSONObject jsonObj); Object gatewaydel(JSONArray jsonObj); Object policyadd(JSONObject jsonObj); Object policylist(JSONObject jsonObj); Object gatewayopen(JSONObject jsonObj); Object policydel(JSONArray jsonObj); Object visithistorylist(JSONObject jsonObj); Object visitpersonadd(JSONObject jsonObj); Object visitpersoncheck(JSONObject jsonObj); Object userlist(JSONObject jsonObj); Object visitList(JSONObject jsonObj); Object visitpersonup(JSONObject jsonObj); Object visitpersondel(JSONArray jsonObj); Object visitresult(JSONObject jsonOb); Object visitallow(JSONObject jsonObj); Object visitprohibit(JSONObject jsonObj); Object cardadd(JSONObject jsonObj); Object carddel(JSONArray jsonArray); Object cardstart(JSONArray jsonArray); Object cardstop(JSONArray jsonArray); Object cardlist(JSONObject jsonObject); }
package sample; import javafx.scene.control.Button; import javafx.scene.control.TextArea; import java.util.HashSet; public class Controller { public Button btn; public TextArea txt; public void Submit() { HashSet<Integer> SNTArray = new HashSet<>(); while (SNTArray.size() < 100){ int x = 30; if (x < 2){ return; } int squareRoot = (int) Math.sqrt(x); for (int i =2; i < squareRoot; i++){ if (x % i == 0){ return; } } return; } String str = ""; for (Integer a: SNTArray){ str += a+"\n"; } txt.setText(str); } }
package com.pykj.v2.spring.framework.aop; public interface PYAopProxy { Object getProxy(); Object getProxy(ClassLoader classLoader); }
import java.io.*; import javax.security.auth.*; public class ChunkReader implements Destroyable { private File m_file; private TerrainData m_TerrainData; private TerrainReader m_TerrainReader; private boolean isAvaliable = true; public ChunkReader(File file, boolean is32) { m_file = file; if (!is32){ m_TerrainReader = new TerrainReader124(); }else { m_TerrainReader = new TerrainReader129(); } } public boolean load(World.Option opt){ if (!isAvaliable) { return false; } m_TerrainReader.load(m_file.getAbsolutePath()); m_TerrainData = new TerrainData(opt.origin, opt.chunkCount); loadTerrain(); return true; } public File save(){ return m_file; } @Override public boolean isDestroyed() { return isAvaliable; } @Override public void destroy() throws DestroyFailedException { try { m_TerrainReader.close(); isAvaliable = false; } catch (IOException e) { throw new DestroyFailedException(e.getMessage()); } } public TerrainData TerrainData() { return m_TerrainData; } private void loadTerrain() { final int endx = m_TerrainData.ChunkCount + m_TerrainData.originChunkX; final int endy = m_TerrainData.ChunkCount + m_TerrainData.originChunkY; for (int x = m_TerrainData.originChunkX; x < endx; x++) { for (int y = m_TerrainData.originChunkY; y < endy; y++) { m_TerrainReader.getChunk(new Point(x, y), m_TerrainData); } } } }
package com.biblio.api.core; import java.util.Date; import javax.persistence.*; @Entity @Table(name = "ligneEmprunt", schema= "public") public class LigneEmprunt extends AbstractDomainObject { /** * */ private static final long serialVersionUID = 5381760553406265295L; @Column(name = "dateFin") private Date dateFin; @Column(name = "dateRetour") private Date dateRetour; @Column(name = "statut") private boolean statut = false; @Column(name = "relance") private int relance = 0; @ManyToOne @JoinColumn private Exemplaire exemplaire; @ManyToOne @JoinColumn private Emprunt emprunt; public LigneEmprunt (){ } public LigneEmprunt ( Date dateFin, boolean statut, int relance){ this.dateFin = dateFin; this.statut = statut; this.relance = relance; } public Date getDateFin() { return dateFin; } public void setDateFin(Date dateFin) { this.dateFin = dateFin; } public boolean getStatut() { return statut; } public void setStatut(boolean statut) { this.statut = statut; } public int getRelance() { return relance; } public void setRelance(int relance) { this.relance = relance; } public Exemplaire getExemplaire() { return exemplaire; } public void setExemplaire(Exemplaire exemplaire) { this.exemplaire = exemplaire; } public Emprunt getEmprunt() { return emprunt; } public void setEmprunt(Emprunt emprunt) { this.emprunt = emprunt; } public Date getDateRetour() { return dateRetour; } public void setDateRetour(Date dateRetour) { this.dateRetour = dateRetour; } public void relancer () { if(this.relance == 0) { this.dateFin = dateFinQuatreSemaine(); this.relance++; } } private Date dateFinQuatreSemaine() { // TODO Auto-generated method stub return null; } }
package net.gasfrog.orbinator; /** * Author: Michael Luther * Date: 4/14/2016 * </p> * Description: */ public class Configuration { public static int NUM_PKGS = 10; public static String BALL_TYPE = "Any"; }
package project; public class Demo { public static void main(String[] args) { int [] arr = {25,4,8,9,3,5}; for(int i = 0; i<arr.length;i++) { for(int j =i+1; j<arr.length; j++) { if(arr[i] <arr[j]) { int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } } } for(int i : arr) { System.out.println(i + " "); } } }
import java.text.SimpleDateFormat; import java.util.Date; public class SaleRecord { private Customer customer; private TrolleyItem item; private Date date; private double totalAmount; public SaleRecord(Customer customer, TrolleyItem item, double totalAmount) { this.customer = customer; this.item = item; date = new Date(); this.totalAmount = totalAmount; } public String toString() { SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss"); String strDate = formatter.format(date); int quantity = item.getQuantity(); Product product = item.getProduct(); return strDate + " " + product.getName() + "*" + quantity + " " + customer.getName() + " ($" + totalAmount + " in total)"; } }
/* * Copyright (C) 2012 Capricorn * * 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.criptext; import android.annotation.SuppressLint; import android.content.Context; import android.content.res.TypedArray; import android.graphics.drawable.Drawable; import android.os.Handler; import android.os.Vibrator; import android.util.AttributeSet; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.view.animation.AlphaAnimation; import android.view.animation.Animation; import android.view.animation.AnimationSet; import android.view.animation.DecelerateInterpolator; import android.view.animation.RotateAnimation; import android.view.animation.ScaleAnimation; import android.view.animation.Transformation; import android.view.animation.Animation.AnimationListener; import android.widget.ImageView; import android.widget.RelativeLayout; public class ArcMenu extends RelativeLayout{ protected ArcLayout mArcLayout; private float startX = 0, startY = 0; private boolean isLeft = false, isUp = false; private long timeStamp, startTime, deltaT; private boolean blocked = false, out = false; private View circle; final float maxSize = getResources().getDimension(R.dimen.max_circle); final float maxLength = getResources().getDimension(R.dimen.max_Height); private boolean _allowVibration = false; private int gestureType; public static final int GESTURE_LEFT = 0; public static final int GESTURE_UP = 1; public static final int GESTURE_RELEASED = 2; final Handler handler = new Handler(); Runnable mLongPressed = new Runnable() { @SuppressLint("NewApi") public void run() { ; vibrate(); animateCircle(); mArcLayout.switchState(true); handler.removeCallbacks(this); out = true; } }; public int getMaxLength() { return (int) maxLength; } public boolean isOut() { return out; } public void setCircle(View circle) { this.circle = circle; } public void resetTimeStamp() { System.out.println("UNLOCKED"); timeStamp = System.nanoTime() - 1200000000L; } public ArcMenu(Context context) { super(context); init(context); } public ArcMenu(Context context, View v) { super(context); circle = v; init(context); } public ArcMenu(Context context, AttributeSet attrs) { super(context, attrs); init(context); applyAttrs(attrs); } public ArcMenu allowVibration(boolean allowVibration) { this._allowVibration = allowVibration; return this; } @SuppressLint("NewApi") @SuppressWarnings("deprecation") public void setImage(Drawable d){ ImageView pic = (ImageView)findViewById(R.id.picture); pic.setImageDrawable(d); } public Long getBlockedTime(){ return 500000000L; } private void init(Context context) { timeStamp = System.nanoTime() - getBlockedTime(); LayoutInflater li = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); li.inflate(R.layout.arc_menu, this); mArcLayout = (ArcLayout) findViewById(R.id.item_layout); View control = findViewById(R.id.control_layout); control.setOnTouchListener(new OnTouchListener(){ @Override public boolean onTouch(View v, MotionEvent event) { if(event.getPointerCount() == 1){ if (event.getAction() == MotionEvent.ACTION_DOWN) { if(System.nanoTime() - timeStamp < getBlockedTime()) blocked = true; else blocked = false; if(blocked){ System.out.println("BLOCKED"); return true; } startTime = System.nanoTime(); startX = event.getRawX(); startY = event.getRawY(); handler.postDelayed(mLongPressed, 400); /** handler.postDelayed(runnable, 300); handler.sendEmptyMessage(6); */ onGesturePress(); } else if(event.getAction() == MotionEvent.ACTION_UP ){ if(blocked){ System.out.println("BLOCKED"); return true; } deltaT = System.nanoTime() - startTime; float dy = event.getRawY() - startY; float dx = event.getRawX() - startX; timeStamp = System.nanoTime(); if(!out){ handler.removeCallbacks(mLongPressed); if(dx < -maxLength*1.4){ onGestureLeft(); } else if(dy < -maxLength*1.4){ onGestureUp(); } else if(dy > maxLength){ //Algo si me voy abajo del boton }else onGestureRelease(); } else{ if(dx < -maxLength*1.4){ gestureType = GESTURE_LEFT; } else if(dy < -maxLength*1.4){ gestureType = GESTURE_UP; } else if(dy > maxLength){ //Algo si me voy abajo del boton }else gestureType = GESTURE_RELEASED; animateCircle(); mArcLayout.switchState(true); out = false; } }else if (event.getAction() == MotionEvent.ACTION_MOVE){ if(blocked){ System.out.println("BLOCKED"); return true; } float dy = event.getRawY() - startY; float dx = event.getRawX() - startX; //handler.removeCallbacks(mLongPressed); if(dx < -maxLength*1.4){ isUp = false; if(!isLeft){ vibrate(); isLeft = true; } } else{ isLeft = false; if(dy < -maxLength*1.4){ if(!isUp){ vibrate(); isUp = true; } } else isUp = false; } }else if (event.getAction() == MotionEvent.ACTION_CANCEL){ if(blocked){ return true; } //handler.removeCallbacks(mLongPressed); } } return true; } }); } public long getDeltaT() { return deltaT; } public void vibrate(){ if (_allowVibration) { Vibrator v = (Vibrator) getContext().getSystemService(getContext().VIBRATOR_SERVICE); // Vibrate for 50 milliseconds v.vibrate(50); } } private void applyAttrs(AttributeSet attrs) { if (attrs != null) { TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.ArcLayout, 0, 0); float fromDegrees = a.getFloat(R.styleable.ArcLayout_fromDegrees, ArcLayout.DEFAULT_FROM_DEGREES); float toDegrees = a.getFloat(R.styleable.ArcLayout_toDegrees, ArcLayout.DEFAULT_TO_DEGREES); mArcLayout.setArc(fromDegrees, toDegrees); int defaultChildSize = mArcLayout.getChildSize(); int newChildSize = a.getDimensionPixelSize(R.styleable.ArcLayout_childSize, defaultChildSize); mArcLayout.setChildSize(newChildSize); a.recycle(); } } public void addItem(View item, OnClickListener listener) { mArcLayout.addView(item); // item.setOnClickListener(getItemClickListener(listener)); } private Animation bindItemAnimation(final View child, final boolean isClicked, final long duration) { Animation animation = createItemDisapperAnimation(duration, isClicked); child.setAnimation(animation); return animation; } private void itemDidDisappear() { final int itemCount = mArcLayout.getChildCount(); for (int i = 0; i < itemCount; i++) { View item = mArcLayout.getChildAt(i); item.clearAnimation(); } mArcLayout.switchState(false); } private static Animation createItemDisapperAnimation(final long duration, final boolean isClicked) { AnimationSet animationSet = new AnimationSet(true); animationSet.addAnimation(new ScaleAnimation(1.0f, isClicked ? 2.0f : 0.0f, 1.0f, isClicked ? 2.0f : 0.0f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f)); animationSet.addAnimation(new AlphaAnimation(1.0f, 0.0f)); animationSet.setDuration(duration); animationSet.setInterpolator(new DecelerateInterpolator()); animationSet.setFillAfter(true); return animationSet; } private static Animation createHintSwitchAnimation(final boolean expanded) { Animation animation = new RotateAnimation(expanded ? 45 : 0, expanded ? 0 : 45, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f); animation.setStartOffset(0); animation.setDuration(100); animation.setInterpolator(new DecelerateInterpolator()); animation.setFillAfter(true); return animation; } //addItem con OnTouchListener public void addItem(View item) { mArcLayout.addView(item); final ViewGroup controlLayout = (ViewGroup) findViewById(R.id.control_layout); item.setVisibility(View.GONE); } public void onGestureUp(){ } public void onGestureLeft(){ } public void onGestureRelease(){ } public void onGesturePress(){ } private void fadeChildren(){ /* //Animation animation = bindItemAnimation(true, true, 400); animation.setAnimationListener(new AnimationListener() { @Override public void onAnimationStart(Animation animation) { } @Override public void onAnimationRepeat(Animation animation) { } @Override public void onAnimationEnd(Animation animation) { postDelayed(new Runnable() { @Override public void run() { itemDidDisappear(); } }, 0); } }); */ final int itemCount = mArcLayout.getChildCount(); for (int i = 0; i < itemCount; i++) { View item = mArcLayout.getChildAt(i); bindItemAnimation(item, false, 300); } mArcLayout.invalidate(); } private void animateCircle(){ CircleTransformation ct = new CircleTransformation(circle.getWidth(), circle.getHeight(), !out); if(!out) ct.setDuration(64); else{ ct.setDuration(800); ct.setAnimationListener( new AnimationListener(){ @Override public void onAnimationEnd(Animation arg0) { switch(gestureType){ case GESTURE_LEFT: onGestureLeft(); break; case GESTURE_UP: onGestureUp(); break; case GESTURE_RELEASED: onGestureRelease(); break; } } @Override public void onAnimationRepeat(Animation arg0) { // TODO Auto-generated method stub } @Override public void onAnimationStart(Animation arg0) { // TODO Auto-generated method stub } }); } circle.startAnimation(ct); } public class CircleTransformation extends Animation { boolean expand; private int initialHeight, initialWidth; public CircleTransformation(int x, int y, boolean expand) { initialHeight = y; initialWidth = x; this.expand = expand; } @Override protected void applyTransformation(float interpolatedTime, Transformation t) { int newHeight, newWidth; //double funct = Math.pow(interpolatedTime, 0.90); if(expand){ newHeight = (int)(maxSize * interpolatedTime); newWidth = (int)(maxSize * interpolatedTime); } else{ float compTime = 1.0f - (float)interpolatedTime; newHeight = (int)(maxSize * compTime); newWidth = (int)(maxSize * compTime); } circle.getLayoutParams().height = newHeight; circle.getLayoutParams().width = newWidth; circle.requestLayout(); } @Override public void initialize(int width, int height, int parentWidth, int parentHeight) { super.initialize(width, height, parentWidth, parentHeight); } @Override public boolean willChangeBounds() { return true; } } }
package pack; import java.io.IOException; import java.nio.file.FileVisitResult; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.SimpleFileVisitor; import java.util.HashMap; import java.nio.file.attribute.*; /** * @author BingelJ ModellAlleDateien ist abgeleitet vom typsicheren * SimpleFileVisitor und bildet das erste Model des MVP-Entwurfmusters. * Alle Dateien unter einem bestimmten Pfad werden in einer HashMap * verwaltet. * */ public class ModelAlleDateien extends SimpleFileVisitor<Path> { private int fortlaufendeNr; private String path; private HashMap<Integer, ModelDatei> alleDateien; /** * Konstruktor instanziiert die HashMap<>, sodass sie befuellt werden kann. */ public ModelAlleDateien() { alleDateien = new HashMap<>(); } /** * Prueft den uebergebenen Pfad und setzt ihn, wenn er existiert als Attribut * und returned true, sonst false. * * @param path Pfad, der geprueft und gesetzt werden soll. * @return Boolean, ob der Pfad existiert. */ public boolean pruefeUndSetzePfad(String path) { if (Files.exists(Paths.get(path))) { this.path = path; return true; } else { return false; } } /** * Aufruf der Files.WalkFileTree-Methode. Zuvor wird die HashMap noch geleert * und die fortlaufendeNr auf 1 gesetzt, sodass ein mehrmaliges Aufrufen keine * FolgeFehler oder vorige Elemente enthaelt. * * @return HashMap<Integer, ModelDatei> die alle ModelDateien enthaelt */ public HashMap<Integer, ModelDatei> walkFiles() { this.alleDateien.clear(); try { this.fortlaufendeNr = 1; Files.walkFileTree(Paths.get(this.path), this); } catch (IOException e) { e.printStackTrace(); } return alleDateien; } /** * (non-Javadoc) Ueberschriebene vistiFile-methode, die die * Informationen/Eigenschaften jeder einzelnen Datei in eine ModelDatei * schreibt, die der ArrayList hinzugefuegt wird. * * @see java.nio.file.SimpleFileVisitor#visitFile(java.lang.Object, * java.nio.file.attribute.BasicFileAttributes) */ @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { ModelDatei neueDatei = new ModelDatei(); neueDatei.setNr(this.fortlaufendeNr++); neueDatei.setName(file.getFileName().toString()); neueDatei.setPfad(file.getParent().toString()); neueDatei.setGroesse(attrs.size()); alleDateien.put(neueDatei.getNr(), neueDatei); return FileVisitResult.CONTINUE; } @Override public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException { return FileVisitResult.CONTINUE; } @Override public FileVisitResult visitFileFailed(Path arg0, IOException arg1) throws IOException { return FileVisitResult.SKIP_SUBTREE; } }
package com.example.dbtest; import android.app.Dialog; import android.content.Intent; import android.content.res.Resources; import android.graphics.Point; import android.graphics.drawable.ColorDrawable; import android.graphics.drawable.Drawable; import android.media.Image; import android.os.Build; import android.os.Bundle; import android.os.CountDownTimer; import android.os.Handler; import android.util.DisplayMetrics; import android.view.Display; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.widget.Button; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; import androidx.appcompat.app.AlertDialog; import androidx.appcompat.app.AppCompatActivity; import org.w3c.dom.Text; import java.util.ArrayList; public class KitchenActivity extends AppCompatActivity { Button iceCup, iceWater, iceMilk,hotCup, hotWater, hotMilk, blender, recipeBook, btnMake,trash; ImageView icon0,icon1,icon2,icon3,icon4,icon5,icon6, icon7, icon8; ImageView selectCup, selectWM, selectIng,selectIng2,selectBlen, imageView15, setting, help; TextView bil1, bil2, bil3,bil4; private BackPressCloseHandler backPressCloseHandler; private CountDownTimer ktimer; ArrayList<Drawable> drawables = new ArrayList<Drawable>(); Handler handler = new Handler(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_kitchen); //소프트키(네비게이션바) 없애기 시작 View decorView = getWindow().getDecorView(); backPressCloseHandler = new BackPressCloseHandler(this); CountClass countclass = (CountClass) getApplication(); int uiOption = getWindow().getDecorView().getSystemUiVisibility(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) uiOption |= View.SYSTEM_UI_FLAG_HIDE_NAVIGATION; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) uiOption |= View.SYSTEM_UI_FLAG_FULLSCREEN; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) uiOption |= View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY; decorView.setSystemUiVisibility(uiOption); //소프트키(네비게이션바) 없애기 ktimer = new CountDownTimer(15*1000, 1000) { @Override public void onTick(long millisUntilFinished) { } @Override public void onFinish() { //엔딩 화면 넣기 Intent intent = new Intent(KitchenActivity.this, WrongEndingActivity.class); startActivity(intent); finish(); } }; icon0 = (ImageView) findViewById(R.id.icon0); icon1 = (ImageView) findViewById(R.id.icon1); icon2 = (ImageView) findViewById(R.id.icon2); icon3 = (ImageView) findViewById(R.id.icon3); icon4 = (ImageView) findViewById(R.id.icon4); icon5 = (ImageView) findViewById(R.id.icon5); icon6 = (ImageView) findViewById(R.id.icon6); icon7 = (ImageView) findViewById(R.id.icon7); icon8 = (ImageView) findViewById(R.id.icon8); setting = (ImageView) findViewById(R.id.setting); help = (ImageView) findViewById(R.id.help); iceCup = (Button) findViewById(R.id.iceCup); hotCup = (Button) findViewById(R.id.hotCup); iceWater = (Button) findViewById(R.id.iceWater); hotWater = (Button) findViewById(R.id.hotWater); iceMilk = (Button) findViewById(R.id.iceMilk); hotMilk = (Button) findViewById(R.id.hotMilk); blender = (Button) findViewById(R.id.blender); recipeBook = (Button) findViewById(R.id.recipeBook); btnMake = (Button) findViewById(R.id.btnMake); selectCup = (ImageView) findViewById(R.id.selectCup); selectWM = (ImageView) findViewById(R.id.selectWM); selectBlen = (ImageView) findViewById(R.id.selectBlen); selectIng = (ImageView) findViewById(R.id.selectIng); selectIng2 = (ImageView) findViewById(R.id.selectIng2); imageView15 = (ImageView) findViewById(R.id.imageView15); bil1 = (TextView) findViewById(R.id.bil1); bil2 = (TextView) findViewById(R.id.bil2); bil3 = (TextView) findViewById(R.id.bil3); bil4 = (TextView) findViewById(R.id.bil4); Intent intent = getIntent(); trash = (Button) findViewById(R.id.trash); Resources resources = getResources(); drawables.add(resources.getDrawable(R.drawable.bar5)); drawables.add(resources.getDrawable(R.drawable.bar4)); drawables.add(resources.getDrawable(R.drawable.bar3)); drawables.add(resources.getDrawable(R.drawable.bar2)); drawables.add(resources.getDrawable(R.drawable.bar1)); drawables.add(resources.getDrawable(R.drawable.bar0)); String a = intent.getExtras().getString("bil1"); bil1.setText(a); String b = intent.getExtras().getString("bil2"); bil2.setText(b); String c = intent.getExtras().getString("bil3"); bil3.setText(c); String d = intent.getExtras().getString("bil4"); bil4.setText(d); setting.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { setting.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(KitchenActivity.this, SettingActivity.class); startActivity(intent); } }); } }); help.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent1 = new Intent(KitchenActivity.this, HelpActivity.class); startActivity(intent1); } }); iceCup.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Resources res = getResources(); final Drawable drawable = res.getDrawable(R.drawable.icecup_on); selectCup.setImageDrawable(drawable); } }); hotCup.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Resources res = getResources(); final Drawable drawable = res.getDrawable(R.drawable.hotcup_on); selectCup.setImageDrawable(drawable); } }); iceWater.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Resources res = getResources(); final Drawable drawable = res.getDrawable(R.drawable.coldwater_on); selectWM.setImageDrawable(drawable); } }); hotWater.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Resources res = getResources(); final Drawable drawable = res.getDrawable(R.drawable.hotwater_on); selectWM.setImageDrawable(drawable); } }); iceMilk.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Resources res = getResources(); final Drawable drawable = res.getDrawable(R.drawable.coldmilk_on); selectWM.setImageDrawable(drawable); } }); hotMilk.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Resources res = getResources(); final Drawable drawable = res.getDrawable(R.drawable.hotmilk_on); selectWM.setImageDrawable(drawable); } }); icon0.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Resources res = getResources(); final Drawable drawable = res.getDrawable(R.drawable.ice_on); selectIng.setImageDrawable(drawable); if (selectIng != null) { icon0.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { selectIng2.setVisibility(View.VISIBLE); selectIng2.setImageDrawable(drawable); } }); } } }); icon1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Resources res = getResources(); final Drawable drawable = res.getDrawable(R.drawable.coffee_on); selectIng.setImageDrawable(drawable); icon1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (selectIng != null) { selectIng2.setVisibility(View.VISIBLE); selectIng2.setImageDrawable(drawable); } } }); } }); icon2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Resources res = getResources(); final Drawable drawable = res.getDrawable(R.drawable.vanil_on); selectIng.setImageDrawable(drawable); icon2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (selectIng != null) { selectIng2.setVisibility(View.VISIBLE); selectIng2.setImageDrawable(drawable); } } }); } }); icon3.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Resources res = getResources(); final Drawable drawable = res.getDrawable(R.drawable.choco_on); selectIng.setImageDrawable(drawable); icon3.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (selectIng != null) { selectIng2.setVisibility(View.VISIBLE); selectIng2.setImageDrawable(drawable); } } }); } }); icon4.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Resources res = getResources(); final Drawable drawable = res.getDrawable(R.drawable.straw_on); selectIng.setImageDrawable(drawable); icon4.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (selectIng != null) { selectIng2.setVisibility(View.VISIBLE); selectIng2.setImageDrawable(drawable); } } }); } }); icon5.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Resources res = getResources(); final Drawable drawable = res.getDrawable(R.drawable.banana_on); selectIng.setImageDrawable(drawable); icon5.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (selectIng != null) { selectIng2.setVisibility(View.VISIBLE); selectIng2.setImageDrawable(drawable); } } }); icon6.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Toast.makeText(KitchenActivity.this, "이 재료는 사용할 수 없어요", Toast.LENGTH_SHORT).show(); } }); icon7.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Toast.makeText(KitchenActivity.this, "이 재료는 사용할 수 없어요", Toast.LENGTH_SHORT).show(); } }); icon8.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Toast.makeText(KitchenActivity.this, "이 재료는 사용할 수 없어요", Toast.LENGTH_SHORT).show(); } }); blender.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Resources res = getResources(); final Drawable drawable = res.getDrawable(R.drawable.blender_on); selectBlen.setImageDrawable(drawable); } }); trash.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { selectCup.setImageDrawable(null); selectWM.setImageDrawable(null); selectIng.setImageDrawable(null); selectIng2.setImageDrawable(null); selectIng2.setVisibility(View.GONE); selectBlen.setImageDrawable(null); } }); recipeBook.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(KitchenActivity.this, RecipebookActivity.class); startActivity(intent); } }); btnMake.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { LoadingDialog loadingDialog; DisplayMetrics dm = getApplicationContext().getResources().getDisplayMetrics(); //디바이스 화면크기를 구하기위해 int width = dm.widthPixels; //디바이스 화면 너비 int height = dm.heightPixels; //디바이스 화면 높이 //로딩이미지 gif 형식 loadingDialog = new LoadingDialog(getApplicationContext()); WindowManager.LayoutParams wm = loadingDialog.getWindow().getAttributes(); //다이얼로그의 높이 너비 설정하기위해 wm.copyFrom(loadingDialog.getWindow().getAttributes()); //여기서 설정한값을 그대로 다이얼로그에 넣겠다는의미 wm.width = (int)(width *0.5); //화면 너비의 절반 wm.height = (int)(height *0.5); loadingDialog.show(); // 제조 성공하면 //Intent intent = new Intent(KitchenActivity.this, MakesuccessActivity.class); //startActivity(intent); ktimer.cancel(); // Dialog dialog = new Dialog(KitchenActivity.this); // dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); // // makesuccessActivity = new MakesuccessActivity(getApplicationContext()); // dialog.setContentView(R.layout.activity_makesuccess); // dialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT)); // dialog.show(); // // Display display = getWindowManager().getDefaultDisplay(); // Point size = new Point(); // display.getSize(size); // // Window window = dialog.getWindow(); // // int x = (int) (size.x * 0.5f); // int y = (int) (size.y * 0.7f); // // window.setLayout(x, y); // // 제조 실패하면 // } }); } }); // switch (countclass.peopleCount) { // // case 10: // Intent intent1 = new Intent(KitchenActivity.this, DayActivity.class); // startActivity(intent1); // finish(); // break; // case 5: // Intent intent2 = new Intent(KitchenActivity.this, DayActivity.class); // startActivity(intent2); // finish(); // break; // // case 15: // Intent intent3 = new Intent(KitchenActivity.this, DayActivity.class); // startActivity(intent3); // finish(); // break; // } } @Override public void onBackPressed() { backPressCloseHandler.onBackPressed(); } @Override protected void onStart() { super.onStart(); final AnimThread thread = new AnimThread(); thread.start(); ktimer.start(); } class AnimThread extends Thread { public void run() { int index = 0; for (int i = 0; i < 10; i++) { final Drawable drawable; drawable = drawables.get(index); index += 1; if (index >= 6) { index = 0; } handler.post(new Runnable() { @Override public void run() { imageView15.setBackground(drawable); } }); try { Thread.sleep(2900); } catch (InterruptedException e) { e.printStackTrace(); } } finish(); } } }
package com.geekband.snap.moran.util; import android.content.Context; import android.net.ConnectivityManager; import android.net.NetworkInfo; public class NetworkStatus { public static boolean isNetworkConnected(Context context){ if(context != null){ ConnectivityManager mConnectivityManager = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo(); if(mNetworkInfo != null){ return mNetworkInfo.isAvailable(); } } return false; } }
package seedu.project.logic.commands; import static java.util.Objects.requireNonNull; import static seedu.project.model.Model.PREDICATE_SHOW_ALL_PROJECTS; import static seedu.project.model.Model.PREDICATE_SHOW_ALL_TASKS; import seedu.project.logic.CommandHistory; import seedu.project.logic.LogicManager; import seedu.project.logic.commands.exceptions.CommandException; import seedu.project.model.Model; /** * Reverts the {@code model}'s project to its previous state. */ public class UndoCommand extends Command { public static final String COMMAND_WORD = "undo"; public static final String COMMAND_ALIAS = "u"; public static final String MESSAGE_SUCCESS = "Undo success!"; public static final String MESSAGE_FAILURE = "No more commands to undo!"; @Override public CommandResult execute(Model model, CommandHistory history) throws CommandException { requireNonNull(model); if (!LogicManager.getState()) { if (!model.canUndoProjectList()) { throw new CommandException(MESSAGE_FAILURE); } model.undoProjectList(); model.updateFilteredProjectList(PREDICATE_SHOW_ALL_PROJECTS); return new CommandResult(MESSAGE_SUCCESS); } else { if (!model.canUndoProject()) { throw new CommandException(MESSAGE_FAILURE); } model.undoProject(); model.updateFilteredTaskList(PREDICATE_SHOW_ALL_TASKS); return new CommandResult(MESSAGE_SUCCESS); } } }
/* * (C) Mississippi State University 2009 * * The WebTOP employs two licenses for its source code, based on the intended use. The core license for WebTOP applications is * a Creative Commons GNU General Public License as described in http://*creativecommons.org/licenses/GPL/2.0/. WebTOP libraries * and wapplets are licensed under the Creative Commons GNU Lesser General Public License as described in * http://creativecommons.org/licenses/*LGPL/2.1/. Additionally, WebTOP uses the same licenses as the licenses used by Xj3D in * all of its implementations of Xj3D. Those terms are available at http://www.xj3d.org/licenses/license.html. */ //FPRound.java //Davis Herring //Defines the FPRound class, which provides static methods for rounding floating-point numbers. //Created September 5 2001 //Updated February 15 2003 //Version 1.3a (cosmetically different from 1.3) //Methods: [value may be float or double] //logfloor10(value) returns what exponent value would have in scientific // notation. //toSigVal(value,digits) will round value to <digits> significant digits. //toFixVal(value,places) will round value to <places> decimal places after the // integer part displayed by Number.toString(), except for numbers in the // interval +/-[0.001,1) which are rounded to <places> significant digits. //toDelExpVal(value,deltaExp) will round value to the closest number which is // equal to some integer divided by 10^deltaExp. It's called by the other two // methods and is rarely particularly useful by itself. package org.sdl.math; public abstract class FPRound { public static final double log10=Math.log(10); public static final int logfloor10(double value) { double absLog=Math.log(Math.abs(value)); return (int)Math.floor((Double.isInfinite(absLog)?0:absLog)/log10); } public static float toSigVal(float value, int sigDigits) {return toDelExpVal(value,sigDigits-1-logfloor10(value));} public static String showZeros(float value, int sigDigits) { //sigDigits refers to digits after decimal point String output; float rounded; String decimal; //portion of number after decimal point int logfloor = logfloor10(value); if (logfloor>=0 && logfloor<=6) rounded = toDelExpVal(value,sigDigits); else rounded = toDelExpVal(value,sigDigits); System.out.println("value: "+value+" exp: "+logfloor); output = String.valueOf(rounded); int periodIndex; periodIndex = output.indexOf("."); decimal = output.substring(periodIndex+1); for(int i = 0; i < (sigDigits - decimal.length()); i++){ output = output.concat("0"); } return output; } public static double toSigVal(double value, int sigDigits) {return toDelExpVal(value,sigDigits-1-logfloor10(value));} public static float toFixVal(float value, int fixPlaces) { int logfloor=logfloor10(value); if(logfloor>=-3 && logfloor<=-1) return toDelExpVal(value,fixPlaces-1-logfloor); //To treat decimals like .0032f properly else if(logfloor>=0 && logfloor<=6) return toDelExpVal(value,fixPlaces); else return toDelExpVal(value,fixPlaces-logfloor); } public static double toFixVal(double value, int fixPlaces) { int logfloor=logfloor10(value); if(logfloor>=-3 && logfloor<=-1) return toDelExpVal(value,fixPlaces-1-logfloor); //To treat decimals like .0032 properly else if(logfloor>=0 && logfloor<=6) return toDelExpVal(value,fixPlaces); else return toDelExpVal(value,fixPlaces-logfloor); } public static float toDelExpVal(float value, int deltaExp) {return (float)(Math.rint(value*Math.pow(10,deltaExp))/Math.pow(10,deltaExp));} public static double toDelExpVal(double value, int deltaExp) {return Math.rint(value*Math.pow(10,deltaExp))/Math.pow(10,deltaExp);} }
package control.rewardSystem.lossCheckManAspect; import java.awt.event.ActionEvent; import control.DynamicSystem; import control.rewardSystem.RewardControl; import model.data.employeeData.rewardEmployeeData.LossCheckManData; import view.insuranceSystemView.rewardView.lossChecker.LossCheckTaskSelectView; import view.panel.BasicPanel; public class LossCheckTaskSelectControl extends RewardControl { // Association private LossCheckManData user; // Constructor public LossCheckTaskSelectControl(LossCheckManData user) {this.user=user;} @Override public BasicPanel getView() {return new LossCheckTaskSelectView (this.user, this.actionListener, this.rewardDataList);} @Override public DynamicSystem processEvent(ActionEvent e) { if(e.getActionCommand().equals("")) {return null;} return new ShowLossCheckInfosControl(this.user, Integer.parseInt(e.getActionCommand())); } }
package com.karya.dao.impl; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Root; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; import com.karya.dao.ICRMspDao; import com.karya.model.CrmOppo001MB; import com.karya.model.CrmspContact001MB; import com.karya.model.CrmspCust001MB; import com.karya.model.CrmspLead001MB; @Repository @Transactional public class CRMspDaoImpl implements ICRMspDao{ @PersistenceContext private EntityManager entityManager; public void addcrmsplead(CrmspLead001MB crmspleadl001MB) { entityManager.merge(crmspleadl001MB); } @SuppressWarnings("unchecked") public List<CrmspLead001MB> listcrmsplead() { CriteriaBuilder builder = entityManager.getCriteriaBuilder(); CriteriaQuery<CrmspLead001MB> cq = builder.createQuery(CrmspLead001MB.class); Root<CrmspLead001MB> root = cq.from(CrmspLead001MB.class); cq.select(root); return entityManager.createQuery(cq).getResultList(); } public CrmspLead001MB getcrmsplead(int slineId) { CrmspLead001MB crmspleadl001MB = entityManager.find(CrmspLead001MB.class, slineId); return crmspleadl001MB; } public void deletecrmsplead(int slineId) { CrmspLead001MB crmspleadl001MB = entityManager.find(CrmspLead001MB.class, slineId); entityManager.remove(crmspleadl001MB); } //CRM CONTACT public void addcrmspcontact(CrmspContact001MB crmspcontactl001MB) { entityManager.merge(crmspcontactl001MB); } @SuppressWarnings("unchecked") public List<CrmspContact001MB> listcrmspcontact() { CriteriaBuilder builder = entityManager.getCriteriaBuilder(); CriteriaQuery<CrmspContact001MB> cq = builder.createQuery(CrmspContact001MB.class); Root<CrmspContact001MB> root = cq.from(CrmspContact001MB.class); cq.select(root); return entityManager.createQuery(cq).getResultList(); } public CrmspContact001MB getcrmspcontact(int contId) { CrmspContact001MB crmspcontactl001MB = entityManager.find(CrmspContact001MB.class, contId); return crmspcontactl001MB; } public void deletecrmspcontact(int contId) { CrmspContact001MB crmspcontactl001MB = entityManager.find(CrmspContact001MB.class, contId); entityManager.remove(crmspcontactl001MB); } //CRM Oppo public void addcrmoppo(CrmOppo001MB crmoppol001MB) { entityManager.merge(crmoppol001MB); } @SuppressWarnings("unchecked") public List<CrmOppo001MB> listcrmoppo() { CriteriaBuilder builder = entityManager.getCriteriaBuilder(); CriteriaQuery<CrmOppo001MB> cq = builder.createQuery(CrmOppo001MB.class); Root<CrmOppo001MB> root = cq.from(CrmOppo001MB.class); cq.select(root); return entityManager.createQuery(cq).getResultList(); } public CrmOppo001MB getcrmoppo(int oppId) { CrmOppo001MB crmoppol001MB = entityManager.find(CrmOppo001MB.class, oppId); return crmoppol001MB; } public void deletecrmoppo(int oppId) { CrmOppo001MB crmoppol001MB = entityManager.find(CrmOppo001MB.class, oppId); entityManager.remove(crmoppol001MB); } //CRM Customer public void addcrmcust(CrmspCust001MB crmcust001MB) { entityManager.merge(crmcust001MB); } @SuppressWarnings("unchecked") public List<CrmspCust001MB> listcrmcust() { CriteriaBuilder builder = entityManager.getCriteriaBuilder(); CriteriaQuery<CrmspCust001MB> cq = builder.createQuery(CrmspCust001MB.class); Root<CrmspCust001MB> root = cq.from(CrmspCust001MB.class); cq.select(root); return entityManager.createQuery(cq).getResultList(); } public CrmspCust001MB getcrmcust(int custId) { CrmspCust001MB crmcust001MB = entityManager.find(CrmspCust001MB.class, custId); return crmcust001MB; } public void deletecrmcust(int custId) { CrmspCust001MB crmcust001MB = entityManager.find(CrmspCust001MB.class, custId); entityManager.remove(crmcust001MB); } }
package br.odb.disksofdoom; import java.util.LinkedList; import br.odb.disksofdoom.DisksOfDoomMainApp.Disk; import br.odb.gameapp.ConsoleApplication; import br.odb.gameapp.UserMetaCommandLineAction; public class SolveCommand extends UserMetaCommandLineAction { class SolutionMove { public SolutionMove( int n, int p0, int p2, int p1) { problemSize = n; fromPole = p0; toPole = p2; usingPole = p1; } int problemSize; int fromPole; int toPole; int usingPole; } public SolveCommand( ConsoleApplication app ) { super( app ); } @Override public String getHelp() { // TODO Auto-generated method stub return null; } @Override public int requiredOperands() { // TODO Auto-generated method stub return 1; } public void moveFrom( DisksOfDoomMainApp game, int n, LinkedList< Disk > from, int index0, LinkedList< Disk> to, int index1, LinkedList< Disk > using, int index2 ) { Disk d; System.out.println( "solving from n = " + n + " from " + index0 + " to " + index1 + " using " + index2 ); if ( n == 1 ) { d = from.pop(); System.out.println( "moving disk = " + d.size + " from " + index0 + " to " + index1 ); to.push( d ); updateVisuals( game); } else { moveFrom( game, n - 1, from, index0, using, index2, to, index1 ); d = from.pop(); System.out.println( "moving disk = " + d.size + " from " + index0 + " to " + index1 ); to.push( d ); updateVisuals( game); moveFrom( game, n - 1, using, index2, to, index1, from, index0 ); } } @Override public void run(ConsoleApplication app, String operand) throws Exception { DisksOfDoomMainApp game = (DisksOfDoomMainApp) app; new NewGameCommand( game ).run(app, operand ); int disks = Integer.parseInt( operand ); if ( disks < 1 || disks > 10 ) { return; } updateVisuals( game ); moveFrom( game, disks, game.pole[ 0 ], 0, game.pole[ 2 ], 2, game.pole[ 1 ], 1 ); // LinkedList< SolutionMove > moves = new LinkedList< SolutionMove >(); // // moves.push( new SolutionMove( 2, 0, 2, 1 ) ); // // SolutionMove currentMove; // Disk disk; // // while ( !moves.isEmpty() ) { // // currentMove = moves.pop(); // // System.out.println( "solving from n = " + currentMove.problemSize + " from " + currentMove.fromPole + " to " + currentMove.toPole + " using " + currentMove.usingPole ); // // if ( currentMove.problemSize == 1 ) { // disk = game.pole[ currentMove.fromPole ].pop(); // System.out.println( "moving disk = " + disk.size + " from " + currentMove.fromPole + " to " + currentMove.toPole ); // game.pole[ currentMove.toPole ].push( disk ); // } else { // // moves.push( new SolutionMove( currentMove.problemSize - 1, currentMove.fromPole, currentMove.usingPole, currentMove.toPole ) ); // //// disk = game.pole[ currentMove.fromPole ].pop(); //// game.pole[ currentMove.toPole ].push( disk ); // // moves.push( new SolutionMove( currentMove.problemSize - 1, currentMove.fromPole,currentMove.toPole, currentMove.usingPole ) ); // // moves.push( new SolutionMove( currentMove.problemSize - 1, currentMove.usingPole,currentMove.toPole, currentMove.fromPole ) ); // } // } } private void updateVisuals(DisksOfDoomMainApp game) { game.updateVisuals( game ); } @Override public String toString() { // TODO Auto-generated method stub return "solve"; } }
package matrixstudio.model; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.text.ParseException; import java.util.List; import java.util.function.BiFunction; import matrixstudio.formula.EvaluationException; import matrixstudio.kernel.SExpModelLoader; import matrixstudio.kernel.SExpModelSaver; import org.junit.Assert; import org.junit.Test; public class SExpModelTest { protected Model loadAndSave(Model source) throws IOException, EvaluationException, ParseException { Path modelPath = Files.createTempDirectory("loadAndSave" + source.hashCode()); SExpModelSaver saver = new SExpModelSaver(source, modelPath); saver.saveModel(); SExpModelLoader loader = new SExpModelLoader(modelPath); Model loaded = loader.readModel(); Assert.assertEquals(source.getParameterCount(), loaded.getParameterCount()); for (int i = 0; i < loaded.getParameterCount(); i++) { Parameter loadedParameter = loaded.getParameter(i); Parameter sourceParameter = source.getParameter(i); Assert.assertEquals(sourceParameter.getName(), loadedParameter.getName()); Assert.assertEquals(sourceParameter.getFormula(), loadedParameter.getFormula()); } Assert.assertEquals(source.getCodeCount(), loaded.getCodeCount()); for (int i = 0; i < loaded.getCodeCount(); i++) { Code loadedCode = loaded.getCode(i); Code sourceCode = source.getCode(i); Assert.assertEquals(sourceCode.getName(), loadedCode.getName()); Assert.assertEquals(sourceCode.getContents(), loadedCode.getContents()); } Assert.assertEquals(source.getMatrixCount(), loaded.getMatrixCount()); for (int i = 0; i < loaded.getMatrixCount(); i++) { Matrix loadedMatrix = loaded.getMatrix(i); Matrix sourceMatrix = source.getMatrix(i); Assert.assertEquals(sourceMatrix.getClass(), loadedMatrix.getClass()); Assert.assertEquals(sourceMatrix.getName(), loadedMatrix.getName()); Assert.assertEquals(sourceMatrix.isRandom(), loadedMatrix.isRandom()); Assert.assertEquals(sourceMatrix.getSizeX(), loadedMatrix.getSizeX()); Assert.assertEquals(sourceMatrix.getSizeY(), loadedMatrix.getSizeY()); Assert.assertEquals(sourceMatrix.getSizeZ(), loadedMatrix.getSizeZ()); if (!loadedMatrix.isRandom()) { if (loadedMatrix instanceof MatrixInteger) { Assert.assertArrayEquals(((MatrixInteger) sourceMatrix).getMatrixInit(), ((MatrixInteger) loadedMatrix).getMatrixInit()); Assert.assertArrayEquals(((MatrixInteger) sourceMatrix).getMatrix(), ((MatrixInteger) loadedMatrix).getMatrix()); } else if (loadedMatrix instanceof MatrixFloat) { Assert.assertArrayEquals(((MatrixFloat) sourceMatrix).getMatrixInit(), ((MatrixFloat) loadedMatrix).getMatrixInit(), 1e-5f); Assert.assertArrayEquals(((MatrixFloat) sourceMatrix).getMatrix(), ((MatrixFloat) loadedMatrix).getMatrix(), 1e-5f); } else if (loadedMatrix instanceof MatrixULong) { Assert.assertArrayEquals(((MatrixULong) sourceMatrix).getMatrixInit(), ((MatrixULong) loadedMatrix).getMatrixInit()); Assert.assertArrayEquals(((MatrixULong) sourceMatrix).getMatrix(), ((MatrixULong) loadedMatrix).getMatrix()); } } } Scheduler sourceScheduler = source.getScheduler(); Scheduler loadedScheduler = loaded.getScheduler(); Assert.assertEquals(sourceScheduler.getTaskCount(), loadedScheduler.getTaskCount()); for (int i = 0; i < loadedScheduler.getTaskCount(); i++) { Task loadedTask = loadedScheduler.getTask(i); Task sourceTask = sourceScheduler.getTask(i); Assert.assertEquals(sourceTask.getKernelCount(), loadedTask.getKernelCount()); Assert.assertEquals(sourceTask.getTaskInCount(), loadedTask.getTaskInCount()); Assert.assertEquals(sourceTask.getTaskOutCount(), loadedTask.getTaskOutCount()); Assert.assertArrayEquals(sourceTask.getPosition(), loadedTask.getPosition(), 1e-5f); } return loaded; } @Test public void loadAndSaveEmpty() throws Exception { loadAndSave(new Model()); } @Test public void createLoadAndSaveParameter() throws Exception { Model source = new Model(); source.addParameterAndOpposite(createParameter("p1", "42")); source.addParameterAndOpposite(createParameter("p2", "42+42")); loadAndSave(source); } @Test public void createLoadAndSaveSchedulerAndCode() throws Exception { Model source = new Model(); source.addCodeAndOpposite(createLibrary("Library1", "// Code here for lib 1")); source.addCodeAndOpposite(createLibrary("Library2", "// Code here for lib 2")); source.addCodeAndOpposite(createKernel("Kernel1", "// Kernel 1")); source.addCodeAndOpposite(createKernel("Kernel2", "// Kernel 2")); createScheduler(source); loadAndSave(source); } @Test public void createLoadAndSaveMatrices() throws Exception { Model source = new Model(); source.addMatrixAndOpposite(createMatrixInteger("Matrix1", 50, 50, (i,j) -> i%2==0 ? i+j : j%2== 0 ? Integer.MAX_VALUE-1 : Integer.MIN_VALUE+1)); source.addMatrixAndOpposite(createMatrixFloat("Matrix2", 50, 50, (i,j) -> (float) Math.sqrt(i+j))); source.addMatrixAndOpposite(createMatrixULong("Matrix3", 50, 50, (i,j) -> i%2==0 ? (long) i+j : j%2== 0 ? Long.MAX_VALUE-1 : Long.MIN_VALUE+1)); loadAndSave(source); } @Test public void createLoadAndSaveMatricesWithParameters() throws Exception { Model source = new Model(); source.addParameterAndOpposite(createParameter("SX", "30")); source.addParameterAndOpposite(createParameter("SY", "30")); MatrixInteger matrix1 = new MatrixInteger(); matrix1.setSizeX("SX"); matrix1.setSizeY("SY"); matrix1.setSizeZ("0"); matrix1.setRandom(true); source.addMatrixAndOpposite(matrix1); loadAndSave(source); } @Test public void createLoadAndSaveAll() throws Exception { Model source = new Model(); source.addParameterAndOpposite(createParameter("p1", "42")); source.addParameterAndOpposite(createParameter("p2", "42+42")); source.addCodeAndOpposite(createLibrary("Library", "// Code here")); source.addCodeAndOpposite(createKernel("Kernel1", "// Kernel 1")); source.addCodeAndOpposite(createKernel("Kernel2", "// Kernel 2")); createScheduler(source); source.addMatrixAndOpposite(createMatrixInteger("Matrix1", 50, 50, (i,j) -> i%2==0 ? i+j : j%2== 0 ? Integer.MAX_VALUE-1 : Integer.MIN_VALUE+1)); source.addMatrixAndOpposite(createMatrixFloat("Matrix2", 50, 50, (i,j) -> (float) Math.sqrt(i+j))); source.addMatrixAndOpposite(createMatrixULong("Matrix3", 50, 50, (i,j) -> i%2==0 ? (long) i+j : j%2== 0 ? Long.MAX_VALUE-1 : Long.MIN_VALUE+1)); loadAndSave(source); } private Parameter createParameter(String name, String formula) { Parameter parameter = new Parameter(); parameter.setName(name); parameter.setFormula(formula); return parameter; } private Kernel createKernel(String name, String contents) { Kernel kernel = new Kernel(); kernel.setName(name); kernel.setContents(contents); return kernel; } private Library createLibrary(String name, String contents) { Library library = new Library(); library.setName(name); library.setContents(contents); return library; } protected MatrixInteger createMatrixInteger(String name, int x, int y, BiFunction<Integer, Integer, Integer> filler) { MatrixInteger matrix = new MatrixInteger(); matrix.setRandom(false); matrix.setName(name); matrix.setSizeX(Integer.toString(x)); matrix.setSizeY(Integer.toString(y)); matrix.setSizeZ(Integer.toString(1)); matrix.initBlank(true); for (int i = 0; i < x; i++) { for (int j = 0; j < y; j++) { matrix.setInitValueAt(i, j, 0, filler.apply(i, j)); } } matrix.setToInitialValues(); return matrix; } protected MatrixFloat createMatrixFloat(String name, int x, int y, BiFunction<Integer, Integer, Float> filler) { MatrixFloat matrix = new MatrixFloat(); matrix.setRandom(false); matrix.setName(name); matrix.setSizeX(Integer.toString(x)); matrix.setSizeY(Integer.toString(y)); matrix.setSizeZ(Integer.toString(1)); matrix.initBlank(true); for (int i = 0; i < x; i++) { for (int j = 0; j < y; j++) { matrix.setInitValueAt(i, j, 0, filler.apply(i, j)); } } matrix.setToInitialValues(); return matrix; } protected MatrixULong createMatrixULong(String name, int x, int y, BiFunction<Integer, Integer, Long> filler) { MatrixULong matrix = new MatrixULong(); matrix.setRandom(false); matrix.setName(name); matrix.setSizeX(Integer.toString(x)); matrix.setSizeY(Integer.toString(y)); matrix.setSizeZ(Integer.toString(1)); matrix.initBlank(true); for (int i = 0; i < x; i++) { for (int j = 0; j < y; j++) { matrix.setInitValueAt(i, j, 0, filler.apply(i, j)); } } matrix.setToInitialValues(); return matrix; } private void createScheduler(Model model) { Task task1 = new Task(); task1.setPosition(new float[] {100f,200f}); Task task2 = new Task(); task2.setPosition(new float[] {300f,100f}); Task task3 = new Task(); task3.setPosition(new float[] {300f,300f}); Task task4 = new Task(); task4.setPosition(new float[] {500f,200f}); task1.addTaskOut(task2); task1.addTaskOut(task3); task2.addTaskIn(task1); task2.addTaskOut(task4); task3.addTaskIn(task1); task3.addTaskOut(task4); task4.addTaskIn(task1); task4.addTaskIn(task2); Scheduler scheduler = model.getScheduler(); scheduler.addTaskAndOpposite(task1); scheduler.addTaskAndOpposite(task2); scheduler.addTaskAndOpposite(task3); scheduler.addTaskAndOpposite(task4); int current = 0; List<Kernel> kernelList = model.getKernelList(); for (Task task : scheduler.getTaskList()) { if (current < kernelList.size()) { task.addKernel(kernelList.get(current)); current += 1; } if (current >= kernelList.size()) { current = 0; } } } }
package ro.ase.csie.cts.g1093.assignment2.exceptions; public class InvalidLoanValueException extends Exception { public String message; public InvalidLoanValueException(String errorMessage) { this.message = errorMessage; } }
package com.ddsolutions.rsvp.utility; import com.ddsolutions.rsvp.domain.RSVPEventRecord; import org.springframework.stereotype.Component; import java.io.*; import java.util.List; import java.util.stream.Stream; @Component public class FileUtil { private JsonUtility jsonUtility = new JsonUtility(); public byte[] write(List<RSVPEventRecord> rsvpEventRecords) throws IOException { try (ByteArrayOutputStream stream = new ByteArrayOutputStream()) { for (RSVPEventRecord rsvpEventRecord : rsvpEventRecords) { stream.write(jsonUtility.convertToString(rsvpEventRecord).getBytes()); stream.write("\n".getBytes()); } return GzipUtility.compressData(stream.toByteArray()); } } public Stream<RSVPEventRecord> read(byte[] compressedData) throws IOException { byte[] decompressedData = GzipUtility.decompress(compressedData); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(decompressedData))); return bufferedReader.lines().map(rsvpRecord -> { try { return jsonUtility.convertFromJson(rsvpRecord, RSVPEventRecord.class); } catch (IOException e) { throw new RuntimeException(e); } }); } }
package com.smartsampa.busapi; /** * Created by ruan0408 on 5/07/2016. */ final class NullCorridor implements Corridor { private static final Corridor ourInstace = new NullCorridor(); private NullCorridor() {} static Corridor getInstance() { return ourInstace; } @Override public int getId() { return 0; } @Override public int getCodCot() { return 0; } @Override public String getName() { return null; } }
public class Test { public static void main (String[] args){ Prova(); //nome del file in cui andare a salvare String nomefile = "libri.est"; //est sarà = .bin per chi utilizza il file di byte // = .json // = .csv Autore collodi = new Autore("Carlo", "Collodi"); Autore perrault = new Autore("Charles","Perrault"); Libreria libreria = new Libreria(); Libro l1 = new Libro("Pinocchio", collodi, 150); Libro l2 = new Libro("Pollicino", perrault, 80); Libro l3 = new Libro("La bella addormentata nel bosco", perrault, 50); // inserimento volumi libreria.addVolume(l1); libreria.addVolume(l2); libreria.addVolume(l3); //cambio il prezzo a pagina Libro.setCostoPagina(0.01); System.out.println(libreria); // salvataggio libreria su file METODO DA IMPLEMENTARE libreria.salvaLibreria ("libreria.json"); } private static void Prova() { /*String strJson; String libro2; Libreria libreriaTommy = new Libreria(); Autore carrisi = new Autore("Donato", "Carrisi"); Autore lippincott = new Autore("Rachel", "Lippincott"); Libro l4 = new Libro("La ragazza della nebbia", carrisi, 370); Libro.setCostoPagina(0.03); Gson gson= new Gson(); strJson = gson.toJson(l4); System.out.println(strJson + "\n"); Libro l5 = new Libro("Five feet apart", lippincott, 276); Libro.setCostoPagina(0.05); Gson gson1= new Gson(); libro2 = gson1.toJson(l5); System.out.println(libro2 + "\n"); libreriaTommy.addVolume(l4); libreriaTommy.addVolume(l5); System.out.println(libreriaTommy); */} }
/* * 8- Calcular e mostrar a média aritmética dos números pares compreendidos entre * 13 e 73. Utilize o laço que lhe for mais conveniente. */ package Lista2; public class Exercicio8 { public static void main(String[] args) { for(int i=13;i<73;i++){ int pares= i%2; if(pares==0){ System.out.println(i); } } } }
package com.example.administrator.cookman.ui.adapter; import android.content.Context; import android.view.View; import android.view.ViewGroup; import android.widget.RelativeLayout; import android.widget.TextView; import com.example.administrator.cookman.CookManApplication; import com.example.administrator.cookman.R; import com.example.administrator.cookman.model.entity.CookEntity.CategoryInfo; import java.util.ArrayList; import java.util.List; import butterknife.Bind; /** * Created by Administrator on 2017/2/25. */ public class CookCategoryFirAdapter extends BaseRecyclerAdapter<CookCategoryFirAdapter.CookCategoryFirStruct>{ public CookCategoryFirAdapter(OnCookCategoryFirListener onCookCategoryFirListener){ this.onCookCategoryFirListener = onCookCategoryFirListener; } @Override public CommonHolder<CookCategoryFirStruct> setViewHolder(ViewGroup parent) { return new CookCategoryFirHolder(parent.getContext(), parent); } class CookCategoryFirHolder extends CommonHolder<CookCategoryFirStruct>{ @Bind(R.id.ralative_bg) public RelativeLayout relativeBg; @Bind(R.id.text_select) public TextView textSelect; @Bind(R.id.text_category) public TextView textCategory; public CookCategoryFirHolder(Context context, ViewGroup root) { super(context, root, R.layout.item_cook_category_fir); } @Override public void bindData(final CookCategoryFirStruct cook) { if(cook.isSelect){ textSelect.setVisibility(View.VISIBLE); relativeBg.setBackgroundColor(CookManApplication.getContext().getResources().getColor(R.color.white)); } else{ textSelect.setVisibility(View.GONE); relativeBg.setBackgroundColor(CookManApplication.getContext().getResources().getColor(R.color.black_alpha_light)); } textCategory.setText(getCategoryName(cook.data.getName())); itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String id = cook.data.getCtgId(); if(onCookCategoryFirListener != null){ onCookCategoryFirListener.onCookCategoryFirClick(id); } for(CookCategoryFirStruct item : dataList){ if(item.data.getCtgId().equals(id)){ item.isSelect = true; } else{ item.isSelect = false; } } notifyDataSetChanged(); } }); } } public static class CookCategoryFirStruct{ private CategoryInfo data; private boolean isSelect; public CookCategoryFirStruct(CategoryInfo data){ this.data = data; this.isSelect = false; } } private OnCookCategoryFirListener onCookCategoryFirListener; public interface OnCookCategoryFirListener{ public void onCookCategoryFirClick(String ctgId); } private static String getCategoryName(String name){ return name.replace("按", "").replace("选择菜谱", ""); } public static List<CookCategoryFirStruct> createDatas(ArrayList<CategoryInfo> datas){ List<CookCategoryFirStruct> dstDatas = new ArrayList<>(); for(CategoryInfo item : datas){ dstDatas.add(new CookCategoryFirStruct(item)); } if(dstDatas.size() > 0) dstDatas.get(0).isSelect = true; return dstDatas; } }
package org.weborganic.berlioz.ps; import java.io.IOException; import com.topologi.diffx.xml.XMLWritable; import com.topologi.diffx.xml.XMLWriter; /** * A simple Java Object to represents a PageSeeder xref and serialise it as XML. * * @author Christophe Lauret * @version 19 July 2010 */ public final class XRef implements XMLWritable { /** XRef Title (if entered manually) */ private final String title; /** Fragment ID */ private String frag; /** Display type */ private String display; /** Type of xref */ private String type; /** True is is a reverselink */ private boolean isReverseLink; /** Address */ private String href; /** ID of target URI */ private long uriid; /** Title of target URI */ private String urititle; // XXX: reversetitle="Schemas" reversetype="None" /** * Returns the ID of target URI. * * @return the ID of target URI. */ public long uriId() { return this.uriid; } /** * The address of the target URI. * * @return the address of the target URI. */ public String href() { return this.href; } /** * Creates an xref from an xref builder. * * @param builder a XRef builder. */ private XRef(Builder builder) { this.title = builder._title; this.frag = builder._frag; this.display = builder._display; this.type = builder._type; this.isReverseLink = builder._isReverseLink; this.href = builder._href; this.uriid = builder._uriid; this.urititle = builder._urititle; } /** * Writes an XML representation of this xref preserving the markup in the source document. * * {@inheritDoc} */ public void toXML(XMLWriter xml) throws IOException { xml.openElement("xref"); xml.attribute("title", this.title); xml.attribute("uriid", Long.toString(this.uriid)); xml.attribute("frag", this.frag); xml.attribute("display", this.display); xml.attribute("type", this.type); xml.attribute("reverselink", Boolean.toString(this.isReverseLink)); xml.attribute("href", this.href); xml.attribute("urititle", this.urititle); String text = (this.title != null && !"".equals(this.title))? this.title : this.urititle; xml.writeText(text); xml.closeElement(); } /** * A builder for xrefs for better filtering of bad class attributes. * * @author Christophe Lauret * @version 19 July 2010 */ static class Builder { private String _title; private String _frag; private String _display; private String _type; private boolean _isReverseLink; private String _href; private long _uriid; private String _urititle; /** * Sets the title for the xref. * * @param title * @return this builder. */ public Builder title(String title) { this._title = title; return this; } /** * Sets the fragment for the xref. * * @param title * @return this builder. */ public Builder frag(String frag) { this._frag = frag; return this; } public Builder display(String display) { this._display = display; return this; } public Builder type(String type) { this._type = type; return this; } public Builder isReserseLink(String reserselink) { this._isReverseLink = "true".equals(reserselink); return this; } public Builder href(String href) { if (href == null) throw new IllegalArgumentException("The specified HREF was null."); this._href = href; return this; } public Builder uriId(String uriid) { try { this._uriid = Long.parseLong(uriid); } catch (NumberFormatException ex) { throw new IllegalArgumentException("The specified URI ID was not a valid long"); } return this; } public Builder uriTitle(String urititle) { this._urititle = urititle; return this; } /** * Resets this builder with the default values. */ public void reset() { this._title = null; this._frag = "default"; this._display = "document"; this._type = "None"; this._isReverseLink = false; this._href = null; this._uriid = -1; this._urititle = null; } /** * Builds an xref from the builder in its current state. * * @return an xref from the builder in its current state. * * @throws IllegalStateException If the the builder's state does not allow an xref to be build. */ public XRef build() throws IllegalStateException { // Check required attributes if (this._href == null) throw new IllegalStateException("Cannot build xref: the 'href' has not been specified"); if (this._uriid == -1) throw new IllegalStateException("Cannot build xref: the 'uriid' has not been specified"); if (this._urititle == null) throw new IllegalStateException("Cannot build xref: the 'urititle' has not been specified"); return new XRef(this); } } }
package com.android.zjshare.widget; import android.content.Context; import android.util.AttributeSet; import android.view.View; import android.widget.RelativeLayout; import android.widget.TextView; import com.android.zjshare.R; import com.android.zjshare.entity.ProductDetailBean; import com.android.zjshare.entity.ProductDetailDataBean; import java.util.ArrayList; import java.util.List; public class ProductDetailView extends RelativeLayout { private TextView mTvSubTitle, mTvPrice, mTvTitle; private List<String> mBannerUrls = new ArrayList<>(); ProductDetailBean productDetailBean; private int mInventory;//库存 最大购买 private int minBuy;//起批 public ProductDetailView(Context context) { this(context, null); } public ProductDetailView(Context context, AttributeSet attrs) { this(context, attrs, 0); } public ProductDetailView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(); } private void init() { View.inflate(getContext(), R.layout.fragment_product_introduce, this); mTvSubTitle = (TextView) findViewById(R.id.tv_sub_title); mTvPrice = findViewById(R.id.tv_price); mTvTitle = findViewById(R.id.tv_title); } /** * 商品详情 * * @param bean */ public void setProductDetailData(final ProductDetailBean bean) { if (bean == null) { return; } mBannerUrls.clear(); setProductData(bean); } /** * 商品信息 * * @param bean */ private void setProductData(ProductDetailBean bean) { if (bean == null) { return; } this.productDetailBean = bean; if (productDetailBean.getLimitNumber() > 0) mInventory = productDetailBean.getLimitNumber(); else mInventory = productDetailBean.getTotalGoodsStock(); if (productDetailBean.getSalesNumber() > 0) minBuy = productDetailBean.getSalesNumber(); else minBuy = 1; if (mInventory < minBuy) { mInventory = minBuy; } mTvTitle.setText(productDetailBean.getGoodsName()); mTvSubTitle.setText(productDetailBean.getGoodsTitle()); } }
package com.michaelkatan.PowerMath; import android.animation.Animator; import android.app.ActionBar; import android.app.Activity; import android.content.Intent; import android.content.SharedPreferences; import android.os.Build; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import com.airbnb.lottie.LottieAnimationView; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.firebase.auth.AuthResult; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; /** * Created by MichaelKatan on 06/01/2018. */ public class FirstScreen extends Activity { ActionBar bar; Window window; EditText first_email_et; EditText first_pass_et; Button first_signUp; Button first_signIn; String email; String pass; LottieAnimationView loadingAnim; LottieAnimationView chackedgAnim; LottieAnimationView warning_sign; Boolean test = true; private FirebaseAuth myAuth; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.first_screen); first_pass_et = findViewById(R.id.first_pass); first_email_et = findViewById(R.id.first_et_email); first_signUp = findViewById(R.id.first_signup_btn); first_signIn = findViewById(R.id.first_signin_btn); loadingAnim = findViewById(R.id.first_loadingAnim_view); loadingAnim.setAnimation("loading.json"); loadingAnim.loop(true); loadingAnim.setVisibility(View.GONE); warning_sign=findViewById(R.id.first_warning_view); warning_sign.loop(false); chackedgAnim = findViewById(R.id.first_ChackAnim_view); chackedgAnim.setVisibility(View.GONE); loadingAnim.loop(false); myAuth = FirebaseAuth.getInstance(); SharedPreferences sharedPreferences = getSharedPreferences("users", MODE_PRIVATE); first_email_et.setText(sharedPreferences.getString("email", "")); /* Firebase Signup System, */ first_signUp.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { loadingAnim.setVisibility(View.VISIBLE); loadingAnim.playAnimation(); first_signUp.setClickable(false); email = first_email_et.getText().toString(); pass = first_pass_et.getText().toString(); if (!(email.equals("")) && !(pass.equals(""))) { myAuth.createUserWithEmailAndPassword(email, pass).addOnCompleteListener(new OnCompleteListener<AuthResult>() { @Override public void onComplete(Task<AuthResult> task) { if (task.isSuccessful()) { Log.d("Signup", "createUserWithEmail:success"); FirebaseUser user = myAuth.getCurrentUser(); Intent intent = new Intent(FirstScreen.this, MainActivity.class); intent.putExtra("email", user.getEmail()); intent.putExtra("ID", user.getUid()); startActivity(intent); first_signIn.setClickable(true); first_signUp.setClickable(true); loadingAnim.pauseAnimation(); loadingAnim.setVisibility(View.GONE); first_signUp.setClickable(true); } else { Log.w("Signup", "createUserWithEmail:failure", task.getException()); Toast.makeText(FirstScreen.this, "" + task.getException(), Toast.LENGTH_SHORT).show(); loadingAnim.pauseAnimation(); loadingAnim.setVisibility(View.GONE); first_signUp.setClickable(true); } } }); } } }); /* Firebase signing System. */ first_signIn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { loadingAnim.setVisibility(View.VISIBLE); loadingAnim.playAnimation(); first_signIn.setClickable(false); email = first_email_et.getText().toString(); pass = first_pass_et.getText().toString(); if (!(email.equals("")) && !(pass.equals(""))) { myAuth.signInWithEmailAndPassword(email, pass).addOnCompleteListener(new OnCompleteListener<AuthResult>() { @Override public void onComplete(Task<AuthResult> task) { if (task.isSuccessful()) { Log.d("Signin", "signInWithEmail:success"); FirebaseUser user = myAuth.getCurrentUser(); final Intent intent = new Intent(FirstScreen.this, MainActivity.class); intent.putExtra("email", user.getEmail()); intent.putExtra("ID", user.getUid()); loadingAnim.cancelAnimation(); chackedgAnim.addAnimatorListener(new Animator.AnimatorListener() { @Override public void onAnimationStart(Animator animation) { } @Override public void onAnimationEnd(Animator animation) { startActivity(intent); first_signIn.setClickable(true); first_signUp.setClickable(true); chackedgAnim.setVisibility(View.GONE); } @Override public void onAnimationCancel(Animator animation) { } @Override public void onAnimationRepeat(Animator animation) { } }); chackedgAnim.playAnimation(); } else { Log.w("Signin", "signInWithEmail:failure", task.getException()); Toast.makeText(FirstScreen.this, "" + task.getException(), Toast.LENGTH_SHORT).show(); loadingAnim.pauseAnimation(); loadingAnim.setVisibility(View.INVISIBLE); warning_sign.setVisibility(View.VISIBLE); warning_sign.playAnimation(); first_signIn.setClickable(true); } } }); } } }); /* Hide the actionBar And Change the status bar color */ bar = getActionBar(); bar.hide(); window = this.getWindow(); changeStatusBarColor(R.color.colorPrimaryDark); loadingAnim.addAnimatorListener(new Animator.AnimatorListener() { @Override public void onAnimationStart(Animator animation) { warning_sign.setVisibility(View.INVISIBLE); chackedgAnim.setVisibility(View.INVISIBLE); } @Override public void onAnimationEnd(Animator animation) { loadingAnim.setVisibility(View.GONE); chackedgAnim.setVisibility(View.VISIBLE); } @Override public void onAnimationCancel(Animator animation) { } @Override public void onAnimationRepeat(Animator animation) { } }); loadingAnim.addAnimatorListener(new Animator.AnimatorListener() { @Override public void onAnimationStart(Animator animation) { } @Override public void onAnimationEnd(Animator animation) { } @Override public void onAnimationCancel(Animator animation) { } @Override public void onAnimationRepeat(Animator animation) { } }); } public void changeStatusBarColor(int color) { window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { window.setStatusBarColor(getResources().getColor(color)); } } /* Save the lase string that was enterd in the email edit text */ @Override protected void onStop() { super.onStop(); SharedPreferences sharedPreferences = getSharedPreferences("users", MODE_PRIVATE); SharedPreferences.Editor editor = sharedPreferences.edit(); editor.putString("email", first_email_et.getText().toString()); editor.commit(); } }
package org.silverpeas.looks.aurora; import org.silverpeas.core.web.look.Shortcut; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Created by Nicolas on 19/07/2017. */ public class NextEvents extends ListOfContributions { private List<NextEventsDate> nextEventsDates; public NextEvents(final List<NextEventsDate> nextEventsDates) { this.nextEventsDates = nextEventsDates; processShortcuts(); } public List<NextEventsDate> getNextEventsDates() { return nextEventsDates; } private void processShortcuts() { Map<String, Shortcut> map = new HashMap<>(); for (NextEventsDate date : nextEventsDates) { for (Event event : date.getEvents()) { String componentId = event.getDetail().getInstanceId(); Shortcut appShortcut = map.computeIfAbsent(componentId, this::getAppShortcut); event.setAppShortcut(appShortcut); } } setAppShortcuts(new ArrayList<>(map.values())); } }
package pt.utl.ist.bw.worklistmanager; import pt.utl.ist.bw.bwactivitymanager.BWActivityManager; import pt.utl.ist.bw.bwgoalmanager.BWGoalManager; import pt.utl.ist.bw.messages.TaskInfo; public class ActivityWorklistManager { private static ActivityWorklistManager instance = null; private ActivityWorklistManager() {} public static ActivityWorklistManager get() { if(instance == null) { instance = new ActivityWorklistManager(); } return instance; } protected boolean receiveActivitySpec(String specID, String specInString) { // send the spec to BWActivityManager return BWActivityManager.get().receiveActivitySpec(specID, specInString); } public void registerActiveTask(String taskURI) { // register task CaseManager.get().addActiveTask(taskURI); if(WorklistManager.get().app == null) { WorklistManager._log.error("The interface is not registered in the Worklist Manager"); } String taskForDisplay = CaseManager.get().getTaskIDToDisplayFromTaskURI(taskURI); // send task info to interface WorklistManager.get().app.addTask(taskForDisplay); } public void registerSkippedTask(String taskName) { WorklistManager._log.info("Skipping task " + taskName); if(WorklistManager.get().app == null) { WorklistManager._log.error("The interface is not registered in the Worklist Manager"); return; } if(!CaseManager.get().isTaskActive(taskName)) { WorklistManager._log.error("Task " + taskName + " is not registered as active. Cannot skip it."); return; } //remove task from the interface //WorklistManager.get().app.removeTask(taskName); // send information about skipped task to BWActivity Manager String taskURI = CaseManager.get().getTaskURIFromTaskIDForDisplay(taskName); BWActivityManager.get().skipTask(taskURI); CaseManager.get().registerSkippedTask(taskName); } public void executeTask(String taskName) { WorklistManager._log.info("Executing task " + taskName); if(WorklistManager.get().app == null) { WorklistManager._log.error("The interface is not registered in the Worklist Manager"); return; } // get task info from BWActivityManager TaskInfo taskInfo = BWActivityManager.get().startEnabledTask(taskName); if(taskInfo != null) { // change the task name (to the interface name) String taskIDForDisplay = CaseManager.get().getTaskIDToDisplayFromTaskURI(taskName); if(taskInfo.getTaskIDForDisplay().contains("[PRE]")) { taskInfo.setTaskIDForDisplay("[PRE]" + taskIDForDisplay); } else { taskInfo.setTaskIDForDisplay(taskIDForDisplay); } //send it to the interface WorklistManager.get().app.executeTask(taskInfo, true); } } public void continueExecutingTask(TaskInfo taskInfo) { if(taskInfo != null && WorklistManager.get().app != null) { //send it to the interface String taskName = taskInfo.getTaskIDForDisplay(); String taskIDForDisplay = CaseManager.get().getTaskIDToDisplayFromTaskURI(taskName); taskInfo.setTaskIDForDisplay(taskIDForDisplay); WorklistManager.get().app.executeTask(taskInfo, true); } } public void removeTaskFromInterface(String taskURI) { if(WorklistManager.get().app == null) { WorklistManager._log.error("The interface is not registered in the Worklist Manager"); return; } String taskIDForDisplay = CaseManager.get().getTaskIDToDisplayFromTaskURI(taskURI); WorklistManager.get().app.removeTask(taskIDForDisplay); } }
package org.usfirst.frc.team178.robot; import edu.wpi.first.wpilibj.Joystick; import edu.wpi.first.wpilibj.buttons.Button; import org.usfirst.frc.team178.robot.commands.*; import edu.wpi.first.wpilibj.buttons.JoystickButton; /** * This class is the glue that binds the controls on the physical operator * interface to the commands and command groups that allow control of the robot. */ public class OI { Joystick TriggerHappy = new Joystick(RobotMap.JoystickPort); Button button1 = new JoystickButton (TriggerHappy, 1); Button button2 = new JoystickButton (TriggerHappy, 2); Button button3 = new JoystickButton (TriggerHappy, 3); Button button4 = new JoystickButton(TriggerHappy, 4); Button button5 = new JoystickButton(TriggerHappy, 5); Button button6 = new JoystickButton(TriggerHappy, 6); Button button7 = new JoystickButton(TriggerHappy,7); Button button8 = new JoystickButton(TriggerHappy, 8); public Joystick TriggerSappy = new Joystick(RobotMap.JoystickPortXbox); Button buttonA = new JoystickButton(TriggerSappy, 1); Button buttonX = new JoystickButton(TriggerSappy, 3); Button buttonY = new JoystickButton(TriggerSappy, 4); public Button lBumper = new JoystickButton(TriggerSappy, 6); public Button rBumper = new JoystickButton(TriggerSappy, 5); Button buttonB = new JoystickButton(TriggerSappy, 2); //// CREATING BUTTONS // One type of button is a joystick button which is any button on a joystick. // You create one by telling it which joystick it's on and which button // number it is. // Joystick stick = new Joystick(port); // Button button = new JoystickButton(stick, buttonNumber); public OI (){ /*button3.whenPressed(new ChangeLightColor("enforcers")); button4.whenPressed(new ChangeLightColor("off"));*/ buttonA.whenPressed(new Kick()); buttonB.whenPressed(new HoldBall()); buttonY.whenPressed(new ToggleIntakeLocation(-0.5)); buttonX.whenPressed(new ToggleIntakeLocation(0.5)); lBumper.whileHeld(new SpinIntake(1)); rBumper.whileHeld(new SpinIntake(-1)); button2.whenPressed(new AutoAim()); } // There are a few additional built in buttons you can use. Additionally, // by subclassing Button you can create custom triggers and bind those to // commands the same as any other Button. public double getX (){ return TriggerHappy.getX(); } public double getY (){ return TriggerHappy.getY(); } public double getTwist (){ return TriggerHappy.getRawAxis(3);// } public boolean isTSPressed (int ButtonNumber){ return TriggerSappy.getRawButton(ButtonNumber); } //// TRIGGERING COMMANDS WITH BUTTONS // Once you have a button, it's trivial to bind it to a button in one of // three ways: // Start the command when the button is pressed and let it run the command // until it is finished as determined by it's isFinished method. // button.whenPressed(new ExampleCommand()); // Run the command while the button is being held down and interrupt it once // the button is released. // button.whileHeld(new ExampleCommand()); // Start the command when the button is released and let it run the command // until it is finished as determined by it's isFinished method. // button.whenReleased(new ExampleCommand()); }
public class D extends C { public D() { System.out.println("Construtor D"); } }
package com.beike.action.trx.partner; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.util.Arrays; import java.util.Date; import java.util.Enumeration; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.TreeMap; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import com.beike.action.pay.BaseTrxAction; import com.beike.common.bean.trx.partner.Par1mallOrderGenerator; import com.beike.common.bean.trx.partner.Par1mallOrderParam; import com.beike.common.bean.trx.partner.Par360buyOrderGenerator; import com.beike.common.bean.trx.partner.Par360buyOrderParam; import com.beike.common.bean.trx.partner.Par58OrderParam; import com.beike.common.bean.trx.partner.ParErrorMsgUtil; import com.beike.common.bean.trx.partner.ParT800OrderParam; import com.beike.common.bean.trx.partner.ParTaobaoOrderParam; import com.beike.common.bean.trx.partner.PartnerInfo; import com.beike.common.enums.trx.PartnerApiType; import com.beike.core.service.trx.partner.PartnerCommonService; import com.beike.core.service.trx.partner.PartnerGoodsService; import com.beike.core.service.trx.partner.PartnerService; import com.beike.core.service.trx.partner.PartnerServiceFactory; import com.beike.core.service.trx.soa.proxy.TrxSoaService; import com.beike.dao.trx.soa.proxy.GoodsSoaDao; import com.beike.entity.goods.Goods; import com.beike.service.goods.GoodsService; import com.beike.util.Amount; import com.beike.util.Configuration; import com.beike.util.DateUtils; import com.beike.util.HttpUtils; import com.beike.util.PartnerUtil; import com.beike.util.StringUtils; import com.beike.util.img.JsonUtil; /** * @Title: ParTrxOrderAction.java * @Package com.beike.action.trx.partner * @Description: 合作分销商API订单相关Action * @date 5 30, 2012 2:16:47 PM * @author wh.cheng * @version v1.0 */ @Controller public class ParTrxOrderAction extends BaseTrxAction { @Resource(name = "partnerServiceFactory") private PartnerServiceFactory partnerServiceFactory; @Resource(name = "partnerCommonService") private PartnerCommonService partnerCommonService; private final Log logger = LogFactory.getLog(ParTrxOrderAction.class); @Resource(name = "partnerGoodsService") private PartnerGoodsService partnerGoodsService; @Resource(name = "goodsService") private GoodsService goodsService; @Autowired private TrxSoaService trxSoaService; @Autowired private GoodsSoaDao goodsSoaDao; /** * 订单同步 * * @return */ @RequestMapping("/partner/synchroTrxOrder.do") public void synchroTrxOrder(HttpServletRequest request, HttpServletResponse response) { Map<String, Object> map = new HashMap<String, Object>(); String apiType = PartnerApiType.TC58.name(); PartnerService partnerService = null; String keyValue = ""; String rspCode = ""; String partnerNo = getPartnerNo(request); String desStr = getPartnerdDes(request); logger.info("++++++++++++++++++++/partner/synchroTrxOrder.do++++++++++++++++++"); try { PartnerInfo partnerInfo = partnerCommonService.qryAvaParterByNoInMem(partnerNo); List<Long> userIdList = partnerCommonService.qryAllUserIdByNoInMem(partnerNo); logger.info("++++++++++++++desStr=" + desStr + "++++++++++partnerNo=" + partnerNo); apiType = partnerInfo.getApiType(); keyValue = partnerInfo.getKeyValue(); String reqIP = StringUtils.getIpAddr(request);// 获取服务器IP Long userId = partnerInfo.getUserId(); partnerService = partnerServiceFactory.getPartnerService(apiType); // 传入密文和商家编号以及与预置IP String paramInfo = partnerService.checkHmacData(desStr, partnerInfo, reqIP); if ("10100".equals(paramInfo)) { map.put("status", paramInfo); map.put("msg", ParErrorMsgUtil.getParErrorMsgByCode(paramInfo, apiType)); map.put("data", ""); } else { // 调用58参数数据转换工具类 Par58OrderParam par58OrderParam = (Par58OrderParam) partnerService.transReqInfo(paramInfo); par58OrderParam.setUserId(userId); par58OrderParam.setUserIdList(userIdList); par58OrderParam.setClientIp(StringUtils.getIpAddr(request)); String jsonStrArr = partnerService.synchroTrxOrder(par58OrderParam, partnerNo); if (StringUtils.isEmpty(jsonStrArr)) { rspCode = "10100"; } else { rspCode = "10000"; } map.put("status", rspCode); map.put("msg", ParErrorMsgUtil.getParErrorMsgByCode(rspCode, apiType)); map.put("data", jsonStrArr); } } catch (Exception e) { map.put("status", "10100"); map.put("msg", ParErrorMsgUtil.getParErrorMsgByCode("10100", apiType)); map.put("data", ""); e.printStackTrace(); } logger.info("++++++++partnerNo=" + partnerNo + "+++++++++++++++++dataReturn=" + map); String dataReturn = partnerService.generateRspHmac(map, keyValue); try { response.getWriter().write(dataReturn); } catch (Exception e) { e.printStackTrace(); } return; } /** * 订单修改(退款、过期) * * @return */ @RequestMapping("/partner/modifyTrxOrder.do") public void modifyTrxOrder(HttpServletRequest request, HttpServletResponse response) { logger.info("++++++++++++++++++++/partner/modifyTrxOrder.do++++++++++++++++++"); String dataReturn = ""; Map<String, Object> jodnMap = new HashMap<String, Object>(); String apiType = ""; String keyValue = ""; String partnerNo = getPartnerNo(request); String desStr = getPartnerdDes(request); PartnerService partnerService = null; try { PartnerInfo partnerInfo = partnerCommonService.qryAvaParterByNoInMem(partnerNo); List<Long> userIdList = partnerCommonService.qryAllUserIdByNoInMem(partnerNo); apiType = partnerInfo.getApiType(); keyValue = partnerInfo.getKeyValue(); partnerService = partnerServiceFactory.getPartnerService(apiType); String reqIp = StringUtils.getIpAddr(request);// 获取服务器IP if (PartnerApiType.TC58.name().equals(apiType)) { // 传入密文和商家编号以及与预置IP String paramInfo = partnerService.checkHmacData(desStr, partnerInfo, reqIp); // 调用58参数数据转换工具类 Par58OrderParam par58OrderParam = (Par58OrderParam) partnerService.transReqInfo(paramInfo); par58OrderParam.setUserIdList(userIdList);// 隶属该分销商的所有userId String trxStatus = par58OrderParam.getStatus(); if ("10".equals(trxStatus) || "11".equals(trxStatus)) { // 跟去券信息查询券状态是否符合 // 调用退款接口TODO String modify = partnerService.processTrxOrder(par58OrderParam); if ("SUCCESS".equals(modify)) { String rspCodes = "10000"; jodnMap.put("status", rspCodes); jodnMap.put("msg", ParErrorMsgUtil.getParErrorMsgByCode(rspCodes, apiType)); jodnMap.put("data", "SUCCESS"); } else { jodnMap.put("status", modify); jodnMap.put("msg", ParErrorMsgUtil.getParErrorMsgByCode(modify, apiType)); jodnMap.put("data", ""); } } else { logger.info("++++++++partnerNo=" + partnerNo + "+++++++++++++++++par58OrderParam.getStatus()=" + par58OrderParam.getStatus() + "++++++++"); // 请求券状态不符合 jodnMap.put("status", "10100"); jodnMap.put("msg", ParErrorMsgUtil.getParErrorMsgByCode("10100", apiType)); jodnMap.put("data", ""); } } else { logger.info("++++++++partnerNo=" + partnerNo + "+++++++++++++++++分销商不符++++++++"); jodnMap.put("status", "10100"); jodnMap.put("msg", ParErrorMsgUtil.getParErrorMsgByCode("10100", apiType)); jodnMap.put("data", ""); } logger.info("++++++++partnerNo=" + partnerNo + "+++++++++++++++++dataReturn=" + jodnMap); } catch (Exception e) { logger.info("++++++++partnerNo=" + partnerNo + "+++++++++++++++++分销商不符++++++++"); jodnMap.put("status", "10100"); jodnMap.put("msg", ParErrorMsgUtil.getParErrorMsgByCode("10100", apiType)); jodnMap.put("data", ""); e.printStackTrace(); } try { dataReturn = partnerService.generateRspHmac(jodnMap, keyValue); response.getWriter().write(dataReturn); } catch (IOException e) { e.printStackTrace(); } return; } /** * 基于券ids进行券信息查询接口-58 * * @param request * @param response * @return */ @RequestMapping("/partner/qryVouBySn.do") public void qryVouBySn(HttpServletRequest request, HttpServletResponse response) { Map<String, Object> map = new HashMap<String, Object>(); String dataReturn = "";// 返回值 String apiType = "";// api类型 String partnerNo = getPartnerNo(request); String desStr = getPartnerdDes(request); PartnerInfo partnerInfo = null; PartnerService partnerService = null; try { partnerInfo = partnerCommonService.qryAvaParterByNoInMem(partnerNo);// 根据partnerNo从mem中获取生效分销商信息 apiType = partnerInfo.getApiType(); String reqIp = StringUtils.getIpAddr(request); partnerService = partnerServiceFactory.getPartnerService(apiType);// 获取工厂服务实现 String paramInfo = partnerService.checkHmacData(desStr, partnerInfo, reqIp);// //检查验签、加密以及IP.只做3DES验证 if (!"10100".equals(paramInfo) && paramInfo.length() > 0 && paramInfo != null) { // 调用58参数转换工具类 Par58OrderParam par58OrderParam = (Par58OrderParam) partnerService.transReqInfo(paramInfo);// 转换并组装分销商请求相关参数 String voucherId = par58OrderParam.getVoucherId();// 58的第三方券ID // "["和"]"必须只能出现一次,而且"["在开始位置,"]"在结束位置 int i = voucherId.indexOf("["); int j = voucherId.lastIndexOf("["); int m = voucherId.indexOf("]"); int n = voucherId.lastIndexOf("]"); if (voucherId == null || voucherId.length() == 0 || i != j || m != n || m != (voucherId.length() - 1) || i != 0) { map.put("status", "10201"); map.put("msg", ParErrorMsgUtil.getParErrorMsgByCode("10201", apiType)); map.put("data", ""); } else { String jsonStrArr = partnerService.findVouInfoByVouId(partnerNo, voucherId);// 获取凭证信息-58的券信息 if (!"10100".equals(jsonStrArr) && jsonStrArr != null && jsonStrArr.length() > 0) { String rspCode = "10000"; map.put("status", rspCode); map.put("msg", ParErrorMsgUtil.getParErrorMsgByCode(rspCode, apiType)); map.put("data", jsonStrArr); } else { map.put("status", jsonStrArr); map.put("msg", ParErrorMsgUtil.getParErrorMsgByCode(jsonStrArr, apiType)); map.put("data", jsonStrArr); } } } } catch (Exception e) { logger.debug(e); map.put("status", "10100"); map.put("msg", ParErrorMsgUtil.getParErrorMsgByCode("10100", apiType)); map.put("data", ""); e.printStackTrace(); } finally { logger.info("++++++++partnerNo=" + partnerNo + "+++++++++++++++++dataReturn=" + map); dataReturn = partnerService.generateRspHmac(map, partnerInfo.getKeyValue());// 响应的密文或者签名数据 } try { response.getWriter().write(dataReturn); } catch (Exception e) { e.printStackTrace(); } return; } /** * 基于券新建时间进行券信息查询接口-58 * * @param request * @param response * @return */ @RequestMapping("/partner/qryVouByActiveDate.do") public void qryVouByActiveDate(HttpServletRequest request, HttpServletResponse response) { Map<String, Object> map = new HashMap<String, Object>(); String dataReturn = "";// 返回值 String apiType = "";// api类型 String partnerNo = getPartnerNo(request); String desStr = getPartnerdDes(request); PartnerInfo partnerInfo = null;// 分销商信息 PartnerService partnerService = null; try { partnerInfo = partnerCommonService.qryAvaParterByNoInMem(partnerNo);// 根据partnerNo从mem中取出PartnerInfo apiType = partnerInfo.getApiType(); String reqIp = StringUtils.getIpAddr(request);// 获取服务器IP地址 partnerService = partnerServiceFactory.getPartnerService(apiType);// 获取工厂业务实现 String paramInfo = partnerService.checkHmacData(desStr, partnerInfo, reqIp);// 检查验签、加密以及IP. if (!"10100".equals(paramInfo) && paramInfo.length() > 0 && paramInfo != null) { Par58OrderParam par58OrderParam = (Par58OrderParam) partnerService.transReqInfo(paramInfo); Date startTime = par58OrderParam.getStartTime();// 获取创建时间 Date endTime = par58OrderParam.getEndTime();// 获取失效时间 String trxStatus = par58OrderParam.getStatus(); if (startTime == null || endTime == null || trxStatus == null || trxStatus.length() == 0) { map.put("status", "10201"); map.put("msg", ParErrorMsgUtil.getParErrorMsgByCode("10201", apiType)); map.put("data", ""); } else { String sTime = DateUtils.toString(startTime, "yyyy-MM-dd"); String eTime = DateUtils.toString(endTime, "yyyy-MM-dd"); if (DateUtils.getDistinceMonth(sTime, eTime) <= 3) { // 根据创建时间查询凭证信息 String jsonStrArr = partnerService.findVouInfoByActiveDate(partnerNo, startTime, endTime, trxStatus); if (!"[10202]".equals(jsonStrArr) && jsonStrArr != null && jsonStrArr.length() > 0) { String rspCode = "10000"; map.put("status", rspCode); map.put("msg", ParErrorMsgUtil.getParErrorMsgByCode(rspCode, apiType)); map.put("data", jsonStrArr); } else { logger.info("++++++partnerNo=" + partnerNo + "++++++++++rspCode=" + jsonStrArr + "++++++++++++++++++++++"); map.put("status", jsonStrArr); map.put("msg", ParErrorMsgUtil.getParErrorMsgByCode(jsonStrArr, apiType)); map.put("data", ""); } } else { logger.info("++++++++partnerNo=" + partnerNo + "++++++++" + startTime + "+++++and+++" + endTime + "++++error+++++++++++++++++"); map.put("status", "10100"); map.put("msg", ParErrorMsgUtil.getParErrorMsgByCode("10100", apiType)); map.put("data", ""); } } } } catch (Exception e) { logger.debug(e); map.put("status", "10100"); map.put("msg", ParErrorMsgUtil.getParErrorMsgByCode("10100", apiType)); map.put("data", ""); e.printStackTrace(); } finally { logger.info("++++partnerNo=" + partnerNo + "+++++++jsonMap=" + map + "+++++++++++++++++++"); dataReturn = partnerService.generateRspHmac(map, partnerInfo.getKeyValue());// 响应的密文或者签名数据 } try { response.getWriter().write(dataReturn); } catch (Exception e) { e.printStackTrace(); } return; } /** * 基于券修改时间进行券信息查询接口-58 * * @param request * @param response * @return */ @RequestMapping("/partner/qryVouByUpDate.do") public void qryVouByLastUpdateDate(HttpServletRequest request, HttpServletResponse response) { Map<String, Object> map = new HashMap<String, Object>(); String apiType = "";// api类型 String dataReturn = "";// 返回值 String partnerNo = getPartnerNo(request); String desStr = getPartnerdDes(request); PartnerInfo partnerInfo = null;// 分销商信息 PartnerService partnerService = null; try { partnerInfo = partnerCommonService.qryAvaParterByNoInMem(partnerNo);// 根据partnerNo从mem中取出PartnerInfo apiType = partnerInfo.getApiType(); String reqIp = StringUtils.getIpAddr(request); partnerService = partnerServiceFactory.getPartnerService(apiType);// 获取工厂业务实现 String paramInfo = partnerService.checkHmacData(desStr, partnerInfo, reqIp);// 检查验签、加密以及IP.只做3DES验证 if (!"10100".equals(paramInfo) && paramInfo.length() > 0 && paramInfo != null) { Par58OrderParam par58OrderParam = (Par58OrderParam) partnerService.transReqInfo(paramInfo); Date startTime = par58OrderParam.getStartTime(); Date endTime = par58OrderParam.getEndTime(); String trxStatus = par58OrderParam.getStatus(); if (startTime == null || endTime == null || trxStatus == null || trxStatus.length() == 0) { map.put("status", "10201"); map.put("msg", ParErrorMsgUtil.getParErrorMsgByCode("10201", apiType)); map.put("data", ""); } else { String sTime = DateUtils.toString(startTime, "yyyy-MM-dd"); String eTime = DateUtils.toString(endTime, "yyyy-MM-dd"); if (DateUtils.getDistinceMonth(sTime, eTime) <= 3) {// 判断更新时间的时间差小于等于三个月 String jsonStrArr = partnerService.findVouInfoByLastUpdateDate(partnerNo, startTime, endTime, trxStatus); if (!"[10202]".equals(jsonStrArr) && jsonStrArr != null && jsonStrArr.length() > 0) { String rspCode = "10000"; map.put("status", rspCode); map.put("msg", ParErrorMsgUtil.getParErrorMsgByCode(rspCode, apiType)); map.put("data", jsonStrArr); } else { logger.info("++++++partnerNo=" + partnerNo + "++++++++++rspCode=" + jsonStrArr + "++++++++++++++++++++++"); map.put("status", jsonStrArr); map.put("msg", ParErrorMsgUtil.getParErrorMsgByCode(jsonStrArr, apiType)); map.put("data", ""); } } else { logger.info("++++++++partnerNo=" + partnerNo + "+++++++++" + startTime + "+++++and+++" + endTime + "++++error++++"); map.put("status", "10100"); map.put("msg", ParErrorMsgUtil.getParErrorMsgByCode("10100", apiType)); map.put("data", ""); } } } } catch (Exception e) { logger.debug(e); map.put("status", "10100"); map.put("msg", ParErrorMsgUtil.getParErrorMsgByCode("10100", apiType)); map.put("data", ""); e.printStackTrace(); } finally { logger.info("++++partnerNo=" + partnerNo + "+++++++jsonMap=" + map + "+++++++++++++++++++"); dataReturn = partnerService.generateRspHmac(map, partnerInfo.getKeyValue());// 响应的密文或者签名数据 } try { response.getWriter().write(dataReturn); } catch (Exception e) { e.printStackTrace(); } return; } /** * 淘宝分销商统一入口 * * @return */ /** * @param request * @param response * @return */ @SuppressWarnings("unchecked") @RequestMapping("/partner/synchroTaobaoTrxOrder.do") public void synchroTaobaoTrxOrder(HttpServletRequest request, HttpServletResponse response) { try { // 淘宝请求参数为GBK request.setCharacterEncoding("GBK"); } catch (UnsupportedEncodingException e1) { e1.printStackTrace(); } String method = request.getParameter("method");// 淘宝请求类型 logger.info("+++++++++++synchroTaobaoTrxOrder.do:method=" + method + "+++++++++++++++++++"); String dataReturn = "";// 淘宝响应状态值 Map<String, Object> map = new HashMap<String, Object>(); try { StringBuilder paramBuilder = new StringBuilder(); Enumeration<String> enume = request.getParameterNames(); while (enume.hasMoreElements()) { String key = enume.nextElement(); String[] value = request.getParameterValues(key); if (paramBuilder.toString().length() > 0) { paramBuilder.append("&"); } logger.info("+++++++++++value[0]=" + value[0] + "+++++++++++++++++++"); paramBuilder.append(key).append("=").append(value[0]); } String queryString = paramBuilder.toString(); logger.info("+++++++++++queryString-->" + queryString + "+++++++++++++++++++"); String partnerNo = request.getParameter("taobao_sid"); PartnerInfo partnerInfo = partnerCommonService.qryAvaParterByNoInMem(partnerNo); List<Long> userIdList = partnerCommonService.qryAllUserIdByNoInMem(partnerNo); String apiType = partnerInfo.getApiType(); String reqIp = StringUtils.getIpAddr(request);// 获取服务器IP PartnerService partnerService = partnerServiceFactory.getPartnerService(apiType); String paramInfo = partnerService.checkHmacData(queryString.toString(), partnerInfo, reqIp);// 传入密文和商家编号以及与请求IP if ("10100".equals(paramInfo)) { dataReturn = "500"; } else { logger.info("++++++++ip AND sign is SUCCESS+++++++++paramInfo=" + paramInfo); ParTaobaoOrderParam parTaobaoOrderParam = (ParTaobaoOrderParam) partnerService.transReqInfo(paramInfo); parTaobaoOrderParam.setUserId(partnerInfo.getUserId().toString());// 当前有效user_id parTaobaoOrderParam.setUserIdList(userIdList);// 隶属该分销商的所有userId parTaobaoOrderParam.setSession(partnerInfo.getSessianKey()); parTaobaoOrderParam.setAppKey(partnerInfo.getDescription()); parTaobaoOrderParam.setKeyValue(partnerInfo.getKeyValue()); parTaobaoOrderParam.setNoticeKeyValue(partnerInfo.getNoticeKeyValue()); parTaobaoOrderParam.setClientIp(StringUtils.getIpAddr(request)); if ("send".equals(method)) { // 调用下单接口 dataReturn = partnerService.synchroTrxOrder(parTaobaoOrderParam, partnerNo); } else if ("resend".equals(method)) { // 接收重新发码通知 dataReturn = partnerService.noTscResendVoucher(parTaobaoOrderParam); } else if ("cancel".equals(method)) { // 接收退款成功通知 dataReturn = partnerService.processTrxOrder(parTaobaoOrderParam); } else if ("modified".equals(method)) { // 接收用户修改手机通知 dataReturn = partnerService.noTscResendVoucher(parTaobaoOrderParam); } /* * else if("mrights".equals(method)){ //接受维权成功通知 } */ } } catch (Exception e) { dataReturn = "500"; e.printStackTrace(); } map.put("code", dataReturn); String jsonMapStr = JsonUtil.getJsonStringFromMap(map); // request.setAttribute("status",jsonMapStr); logger.info("++++++++partnerNo=" + request.getParameter("taobao_sid") + "+++++++++++++++++jsonMapStr=" + jsonMapStr); try { response.getWriter().write(jsonMapStr); } catch (Exception e) { e.printStackTrace(); } return; } /** * 基于券id进行查询58订单 * * @param request * @param response * @return */ @SuppressWarnings("unchecked") @RequestMapping("/partner/qryByVoucherId.do") public void qryByVoucherId(HttpServletRequest request, HttpServletResponse response) { // 调用58查询接口 String ticketId = String.valueOf(request.getParameter("voucherId")); String tickets[] = new String[] { ticketId }; Map<String, Object> jsonMap = new HashMap<String, Object>(); ticketId = Arrays.toString(tickets); jsonMap.put("ticketIds", ticketId); String jsonStrArr = JsonUtil.getJsonStringFromMap(jsonMap); jsonStrArr = jsonStrArr.replace("\\", ""); jsonStrArr = jsonStrArr.replace("\"[", "[\""); jsonStrArr = jsonStrArr.replace("]\"", "\"]"); String param = PartnerUtil.cryptDes(jsonStrArr, "304faa16a5c74484b33ce57427a2c13b"); Map<String, String> map = new HashMap<String, String>(); map.put("m", "emc.groupbuy.ticket.findinfo.byid"); map.put("sn", "1"); map.put("appid", "100532"); map.put("f", "json"); map.put("param", param); logger.info("+++++++++++++58TC++++++++++qryVouBy+++map:" + map); List<String> responseStr = null; try { responseStr = HttpUtils.URLPost("http://eapi.58.com/api/rest", map); logger.info("++++++++++++responseStr=++++" + responseStr); if (responseStr.size() == 0 || responseStr == null) { response.getWriter().write("responseStr.size() == 0 || responseStr == null"); } else { String status = "";// 返回数据状态 String msg = "";// 返回数据状态信息 String data = "";// 返回数据信息 // String trxStatus = "";//返回数据订单信息状态 // String result = "";//验券成功与否 String currentResult = responseStr.get(0); Map<String, Object> objMap = JsonUtil.getMapFromJsonString(currentResult); if (objMap.get("status") != null) { status = objMap.get("status").toString(); } if (objMap.get("msg") != null) { msg = objMap.get("msg").toString(); } data = objMap.get("data").toString(); // String desryptStr = // PartnerUtil.decryptDes(currentResult,partnerInfo.getKeyValue()); logger.info("+++++58TC++++++++++qryVoucherInfoToPar++++++++ticketId=" + ticketId + "+++++++++" + "++++++++"); if ("10000".equals(status)) { if (data == null || data.equals("")) { response.getWriter().write("data == null || data.equals(\"\")"); } else { String returnJson = PartnerUtil.decryptDes(data, "304faa16a5c74484b33ce57427a2c13b"); returnJson = returnJson.replace("[", ""); returnJson = returnJson.replace("]", ""); logger.info("+++++58TC++++++++++qryVoucherInfoToPar++++++++returnJson=" + returnJson + "+++++++++++++++++"); // 58订单状态判断 response.getWriter().write(returnJson + "<br>状态对应表:0 未使用 1 已使用 2 已退款 3退款中4 已锁定9 过期 10未使用退款,11已过期退款,12已消费退款(58责任),13已消费退款(商家责任)"); } } else { /* * 0 未使用 1 已使用 2 已退款 3退款中 4 已锁定 9 过期 * 10未使用退款,11已过期退款,12已消费退款(58责任),13已消费退款(商家责任) */ response.getWriter().write("!\"10000\".equals(status)+" + status); logger.info("++++++++++++status=" + status + "++++++++msg=" + msg); } } } catch (IOException e) { e.printStackTrace(); } } /** * 京东分销商统一入口 * * @param request * @param response * @return */ @RequestMapping("/partner/synchro360buyTrxOrder.do") public void synchro360buyTrxOrder(HttpServletRequest request, HttpServletResponse response) { logger.info("++++++++++++++++++++/partner=360buy/synchro360buyTrxOrder.do++++++++++++"); String partnerNo = ""; try { String sourceMessage = Par360buyOrderGenerator.get360buyReqMessage(request.getInputStream()); partnerNo = Par360buyOrderGenerator.getPartnerNo(sourceMessage); // 获得报文传来的partnerNo logger.info("+++++++++++++++partnerNo=" + partnerNo + "nchro360buyTrxOrder request message:" + sourceMessage.toString()); PartnerInfo partnerInfo = partnerCommonService.qryAvaParterByNoInMem(partnerNo); List<Long> userIdList = partnerCommonService.qryAllUserIdByNoInMem(partnerNo); PartnerService partenerService = partnerServiceFactory.getPartnerService(PartnerApiType.BUY360.name()); // 获得京东分销商service String reqIp = StringUtils.getIpAddr(request);// 获取服务器IP logger.info("+++++++++++++++partnerNo=" + partnerNo + "++++reqIp=" + reqIp); // 校验报文合法性 String paramInfo = partenerService.checkHmacData(sourceMessage, partnerInfo, reqIp); // 错误返回 -校验失败 if ("10100".equals(paramInfo)) { Par360buyOrderParam responseParam = new Par360buyOrderParam(); // 响应报文 responseParam.setVenderId(partnerInfo.getPartnerNo()); // 分销商号 responseParam.setResultCode("-100"); // 返回码-- 身份验证失败 responseParam.setResultMessage("illegal request"); // 返回信息 String resMessage = partenerService.generateRspHmac(responseParam, partnerInfo.getKeyValue()); response.getWriter().write(resMessage); return; } Par360buyOrderParam par360buyParam = (Par360buyOrderParam) partenerService.transReqInfo(paramInfo); par360buyParam.setUserId(partnerInfo.getUserId()); par360buyParam.setUserIdList(userIdList); par360buyParam.setPartnerNo(partnerNo); par360buyParam.setClientIp(reqIp); String data = ""; String resultCode = "-1"; String resultMessage = "interface handle error"; // 请求名称不存在 if (null != par360buyParam && !"".equals(StringUtils.toTrim(par360buyParam.getMessage()))) { // 订单同步 if (par360buyParam.getMessage().endsWith("SendOrderRequest")) { data = partenerService.synchroTrxOrder(par360buyParam, partnerNo); resultCode = "200"; resultMessage = "success"; } // 接收退款成功通知 else if (par360buyParam.getMessage().endsWith("SendOrderRefundRequest")) { data = partenerService.processTrxOrder(par360buyParam); resultCode = "200"; resultMessage = "success"; } // 团购销量查询接口 else if (par360buyParam.getMessage().endsWith("QueryTeamSellCountRequest")) { data = partnerGoodsService.processGoodsSellCount(par360buyParam); resultCode = "200"; resultMessage = "success"; } } Par360buyOrderParam responseParam = new Par360buyOrderParam(); // 响应报文 responseParam.setVenderId(partnerInfo.getPartnerNo()); // 分销商号 responseParam.setData(data); responseParam.setResultCode(resultCode); // 返回码-- 接口调用异常 responseParam.setResultMessage(resultMessage); // 返回信息--接口调用异常 String resMessage = partenerService.generateRspHmac(responseParam, partnerInfo.getKeyValue()); response.getWriter().write(resMessage); return; } catch (Exception e) { logger.error("partnerNo:" + partnerNo + "360buy interface handle error", e); Par360buyOrderParam resParam = new Par360buyOrderParam(); // 响应报文 resParam.setVenderId(""); // 分销商号 resParam.setResultCode("-1"); // 返回码-- 接口调用异常 resParam.setResultMessage("interface handle error"); // 返回信息--接口调用异常 resParam.setData(""); String resMessage = Par360buyOrderGenerator.packageResponseMsg(resParam, "error"); try { response.getWriter().write(resMessage); } catch (IOException e1) { e1.printStackTrace(); } return; } } /** * 统一查询接口 * * @param request * @param response */ @RequestMapping("/partner/queryGoodsBeforePay.do") public void queryGoodsBeforePay(HttpServletRequest request, HttpServletResponse response) { logger.info("===into queryGoodsBeforePay==="); String sign = request.getParameter("sign"); String params = request.getParameter("params"); // 做为partnerNO String publicKey = request.getParameter("appKey"); response.setCharacterEncoding("UTF-8"); String apiType = PartnerApiType.TUAN800.name(); Map<String, Object> map = new HashMap<String, Object>(); PartnerService partnerService = null; try { PartnerInfo partnerInfo = partnerCommonService.qryAvaParterByNoInMem(publicKey); if (partnerInfo != null) { apiType = partnerInfo.getApiType(); } String reqIP = StringUtils.getIpAddr(request);// 获取服务器IP partnerService = partnerServiceFactory.getPartnerService(apiType); // 传入密文和商家编号以及与预置IP String paramInfo = partnerService.checkHmacData(params, publicKey, sign, partnerInfo, reqIP); if (ParErrorMsgUtil.T800_OTHER_ERROR.equals(paramInfo) || ParErrorMsgUtil.T800_SIGN_MISMATCH.equals(paramInfo)) { map.put("ret", paramInfo); map.put("msg", ParErrorMsgUtil.getParErrorMsgByCode(paramInfo, apiType)); } else { // 调用团800参数数据转换工具类 ParT800OrderParam par800OrderParam = (ParT800OrderParam) partnerService.transReqInfo(paramInfo); Map<String, Object> maxcountMap = trxSoaService.getMaxCountAndIsAvbByIdInMem(Long.parseLong(par800OrderParam.getGoodsId())); Long maxCount = Long.parseLong(maxcountMap.get("maxcount").toString()); // 是否下线:0表示下线不可用 String isavaliable = maxcountMap.get("isavaliable").toString(); if ("0".equals(isavaliable)) { map.put("ret", ParErrorMsgUtil.T800_OFF_LINE); map.put("msg", ParErrorMsgUtil.getParErrorMsgByCode(ParErrorMsgUtil.T800_OFF_LINE, apiType)); } else { List<Map<String, Object>> salesCountMapList = goodsSoaDao.getGoodsProfileByGoodsid(par800OrderParam.getGoodsId());// 商品已经购买量 Long salesCount = Long.valueOf(salesCountMapList.get(0).get("salesCount").toString()); Long allowBuyCount = maxCount - salesCount > 0 ? maxCount - salesCount : 0;// 总量限购如果为负,则归零 if (Long.parseLong(par800OrderParam.getProdCount()) > allowBuyCount.longValue()) { map.put("ret", ParErrorMsgUtil.T800_SALE_OUT); map.put("msg", ParErrorMsgUtil.getParErrorMsgByCode(ParErrorMsgUtil.T800_SALE_OUT, apiType)); } else { Goods goods = goodsService.findById(Long.parseLong(par800OrderParam.getGoodsId())); if (goods != null) { if (goods.getSendRules() != 0) { map.put("ret", ParErrorMsgUtil.T800_SALE_OUT); map.put("msg", ParErrorMsgUtil.getParErrorMsgByCode(ParErrorMsgUtil.T800_SALE_OUT, apiType)); } else { map.put("ret", ParErrorMsgUtil.T800_SUCCESS); } } else { map.put("ret", ParErrorMsgUtil.T800_OFF_LINE); map.put("msg", ParErrorMsgUtil.getParErrorMsgByCode(ParErrorMsgUtil.T800_OFF_LINE, apiType)); } } } } } catch (Exception e) { map.put("ret", ParErrorMsgUtil.T800_OFF_LINE); map.put("msg", ParErrorMsgUtil.getParErrorMsgByCode(ParErrorMsgUtil.T800_OFF_LINE, apiType)); e.printStackTrace(); } try { String jsonStr = JsonUtil.getJsonStringFromMap(map); response.getWriter().write(jsonStr); } catch (Exception e) { e.printStackTrace(); } } /** * 团800订单同步 * * @param request * @param response * @author wz.gu for tuan800 synchro order 2012-11-08 */ @RequestMapping("/partner/synchroTuan800TrxOrder.do") public void synchroTuan800TrxOrder(HttpServletRequest request, HttpServletResponse response) { String sign = request.getParameter("sign"); String params = request.getParameter("params"); // 做为partnerNO String publicKey = request.getParameter("appKey"); response.setCharacterEncoding("UTF-8"); Map<String, Object> map = new HashMap<String, Object>(); String apiType = PartnerApiType.TUAN800.name(); PartnerService partnerService = null; String dataReturn = null; String keyValue = ""; logger.info("++++++++++++++++++++/partner/synchroTuan800TrxOrder.do++++++++++++++++++"); try { PartnerInfo partnerInfo = partnerCommonService.qryAvaParterByNoInMem(publicKey); logger.info("++++++++++++++params=" + params + "++++++++++partnerNo=" + publicKey); if (partnerInfo != null) { apiType = partnerInfo.getApiType(); keyValue = partnerInfo.getKeyValue(); } String reqIP = StringUtils.getIpAddr(request);// 获取服务器IP Long userId = partnerInfo.getUserId(); partnerService = partnerServiceFactory.getPartnerService(apiType); // 传入密文和商家编号以及与预置IP String paramInfo = partnerService.checkHmacData(params, publicKey, sign, partnerInfo, reqIP); if (ParErrorMsgUtil.T800_OTHER_ERROR.equals(paramInfo) || ParErrorMsgUtil.T800_SIGN_MISMATCH.equals(paramInfo)) { map.put("ret", paramInfo); map.put("msg", ParErrorMsgUtil.getParErrorMsgByCode(paramInfo, apiType)); } else { // 调用团800参数数据转换工具类 ParT800OrderParam par800OrderParam = (ParT800OrderParam) partnerService.transReqInfo(paramInfo); String payPrice = par800OrderParam.getPayPrice(); String totalPrice = par800OrderParam.getTotalPrice(); String prdCount = par800OrderParam.getProdCount(); double payPriceDou = Double.parseDouble(payPrice); double totalPriceDou = Double.parseDouble(totalPrice); if (totalPriceDou < Amount.mul(payPriceDou, Double.parseDouble(prdCount))) { map.put("ret", ParErrorMsgUtil.T800_AMOUNT_MISMATCH); map.put("msg", ParErrorMsgUtil.getParErrorMsgByCode(ParErrorMsgUtil.T800_AMOUNT_MISMATCH, apiType)); } else { List<Long> userIdList = partnerCommonService.qryAllUserIdByNoInMem(publicKey); par800OrderParam.setUserId(userId); par800OrderParam.setUserIdList(userIdList); par800OrderParam.setClientIp(StringUtils.getIpAddr(request)); dataReturn = partnerService.synchroTrxOrder(par800OrderParam, publicKey); if (StringUtils.isEmpty(dataReturn) || ParErrorMsgUtil.T800_OTHER_ERROR.equals(dataReturn)) { map.put("ret", ParErrorMsgUtil.T800_OTHER_ERROR); map.put("msg", ParErrorMsgUtil.getParErrorMsgByCode(ParErrorMsgUtil.T800_OTHER_ERROR, apiType)); } } } } catch (Exception e) { map.put("ret", ParErrorMsgUtil.T800_OTHER_ERROR); map.put("msg", ParErrorMsgUtil.getParErrorMsgByCode(ParErrorMsgUtil.T800_OTHER_ERROR, apiType)); e.printStackTrace(); } if (map != null && !map.isEmpty()) { dataReturn = partnerService.generateRspHmac(map, keyValue); } logger.info("++++++++partnerNo=" + publicKey + "+++++++++++++++++dataReturn=" + dataReturn); try { response.getWriter().write(dataReturn); } catch (Exception e) { e.printStackTrace(); } } /** * @param request * @param response * @author wz.gu for tuan800 refund order 2012-11-08 */ @RequestMapping("/partner/refundT800TrxOrder.do") public void refundT800TrxOrder(HttpServletRequest request, HttpServletResponse response) { String sign = request.getParameter("sign"); String params = request.getParameter("params"); // 即partnerNO String publicKey = request.getParameter("appKey"); logger.info("++++++++++++++++++++/partner/refundTuan800TrxOrder.do++++++++++++++++++"); response.setCharacterEncoding("UTF-8"); String apiType = PartnerApiType.TUAN800.name(); PartnerService partnerService = null; String keyValue = ""; String dataReturn = ""; Map<String, Object> jsonMap = new HashMap<String, Object>(); try { PartnerInfo partnerInfo = partnerCommonService.qryAvaParterByNoInMem(publicKey); if (partnerInfo != null) { apiType = partnerInfo.getApiType(); keyValue = partnerInfo.getKeyValue(); } partnerService = partnerServiceFactory.getPartnerService(apiType); String reqIp = StringUtils.getIpAddr(request);// 获取服务器IP if (PartnerApiType.TUAN800.name().equals(apiType)) { // 传入密文和商家编号以及与预置IP String paramInfo = partnerService.checkHmacData(params, publicKey, sign, partnerInfo, reqIp); if (ParErrorMsgUtil.T800_OTHER_ERROR.equals(paramInfo) || ParErrorMsgUtil.T800_SIGN_MISMATCH.equals(paramInfo)) { jsonMap.put("ret", paramInfo); jsonMap.put("msg", ParErrorMsgUtil.getParErrorMsgByCode(paramInfo, apiType)); } else { // 调用团800参数数据转换工具类 ParT800OrderParam parT800OrderParam = (ParT800OrderParam) partnerService.transReqInfo(paramInfo); List<Long> userIdList = partnerCommonService.qryAllUserIdByNoInMem(publicKey); parT800OrderParam.setUserIdList(userIdList);// 隶属该分销商的所有userId if (!StringUtils.isEmpty(org.apache.commons.lang.StringUtils.trim(parT800OrderParam.getOrderId())) || !StringUtils.isEmpty(org.apache.commons.lang.StringUtils.trim(parT800OrderParam.getVoucherCode()))) { dataReturn = partnerService.processTrxOrder(parT800OrderParam); } else { logger.info("++++++++partnerNo=" + publicKey + "+++++++++++++++++请求数据异常" + "++++++++"); // 数据不正确 jsonMap.put("ret", ParErrorMsgUtil.T800_OTHER_ERROR); jsonMap.put("msg", ParErrorMsgUtil.getParErrorMsgByCode(ParErrorMsgUtil.T800_OTHER_ERROR, apiType)); } } } else { logger.info("++++++++partnerNo=" + publicKey + "+++++++++++++++++分销商不符++++++++"); jsonMap.put("ret", ParErrorMsgUtil.T800_OTHER_ERROR); jsonMap.put("msg", ParErrorMsgUtil.getParErrorMsgByCode(ParErrorMsgUtil.T800_OTHER_ERROR, apiType)); } } catch (Exception e) { logger.info("++++++++partnerNo=" + publicKey + "+++++++++++++++++系统异常++++++++"); jsonMap.put("ret", ParErrorMsgUtil.T800_OTHER_ERROR); jsonMap.put("msg", ParErrorMsgUtil.getParErrorMsgByCode(ParErrorMsgUtil.T800_OTHER_ERROR, apiType)); e.printStackTrace(); } if (jsonMap != null && !jsonMap.isEmpty()) { dataReturn = partnerService.generateRspHmac(jsonMap, keyValue); } logger.info("++++++++partnerNo=" + publicKey + "+++++++++++++++++dataReturn=" + dataReturn); try { response.getWriter().write(dataReturn); } catch (IOException e) { e.printStackTrace(); } } /** * 为团800提供订单查询接口 * * @param request * @param response * @author wz.gu */ @RequestMapping("/partner/queryTrxOrderFromT800.do") public void queryTrxOrderFromT800(HttpServletRequest request, HttpServletResponse response) { String sign = request.getParameter("sign"); String params = request.getParameter("params"); // 即partnerNo String publicKey = request.getParameter("appKey"); logger.info("++++++++++++++++++++/partner/queryTrxOrderFromT800.do++++++++++++++++++"); response.setCharacterEncoding("UTF-8"); Map<String, Object> map = new HashMap<String, Object>(); String apiType = PartnerApiType.TUAN800.name(); PartnerService partnerService = null; String keyValue = ""; String dataReturn = ""; try { PartnerInfo partnerInfo = partnerCommonService.qryAvaParterByNoInMem(publicKey); if (partnerInfo != null) { keyValue = partnerInfo.getKeyValue(); apiType = partnerInfo.getApiType(); } partnerService = partnerServiceFactory.getPartnerService(apiType); String reqIp = StringUtils.getIpAddr(request);// 获取服务器IP if (PartnerApiType.TUAN800.name().equals(apiType)) { // 传入密文和商家编号以及与预置IP String paramInfo = partnerService.checkHmacData(params, publicKey, sign, partnerInfo, reqIp); if (ParErrorMsgUtil.T800_OTHER_ERROR.equals(paramInfo) || ParErrorMsgUtil.T800_SIGN_MISMATCH.equals(paramInfo)) { map.put("ret", paramInfo); map.put("msg", ParErrorMsgUtil.getParErrorMsgByCode(paramInfo, apiType)); } else { // 调用团800参数数据转换工具类 ParT800OrderParam parT800OrderParam = (ParT800OrderParam) partnerService.transReqInfo(paramInfo); if (!StringUtils.isEmpty(parT800OrderParam.getOrderId()) || !StringUtils.isEmpty(parT800OrderParam.getVoucherCode())) { dataReturn = partnerService.findTrxorder(parT800OrderParam, publicKey); if (ParErrorMsgUtil.T800_OTHER_ERROR.equals(dataReturn)) { map.put("ret", ParErrorMsgUtil.T800_OTHER_ERROR); map.put("msg", ParErrorMsgUtil.getParErrorMsgByCode(dataReturn, apiType)); } } else {// 传过来的数据不正确 map.put("ret", ParErrorMsgUtil.T800_OTHER_ERROR); map.put("msg", ParErrorMsgUtil.getParErrorMsgByCode(ParErrorMsgUtil.T800_OTHER_ERROR, apiType)); } } } else { logger.info("++++++++++++++++++++分销商不符++++++++++++++++++"); map.put("ret", ParErrorMsgUtil.T800_OTHER_ERROR); map.put("msg", ParErrorMsgUtil.getParErrorMsgByCode(ParErrorMsgUtil.T800_OTHER_ERROR, apiType)); } } catch (Exception e) { map.put("ret", ParErrorMsgUtil.T800_OTHER_ERROR); map.put("msg", ParErrorMsgUtil.getParErrorMsgByCode(ParErrorMsgUtil.T800_OTHER_ERROR, apiType)); e.printStackTrace(); } if (map != null && !map.isEmpty()) { dataReturn = partnerService.generateRspHmac(map, keyValue); } try { response.getWriter().write(dataReturn); } catch (Exception e) { e.printStackTrace(); } } /** * 调用团800接口查询订单 * * @param request * @param response */ @SuppressWarnings("unchecked") @RequestMapping("/partner/queryTrxOrderToT800.do") public void queryTrxOrderToT800(HttpServletRequest request, HttpServletResponse response) { response.setCharacterEncoding("UTF-8"); // 团800提供的URL String url = Configuration.getInstance().getValue("tuan800_queryurl");// "http://110.173.1.14:8020/client-api/query-order"; // 即 partnerNO String publicKey = Configuration.getInstance().getValue("tuan800_publicKey");// "859de8d7112c4bc7b6c768760102ca62"; String orderId = request.getParameter("orderId"); String vouCode = request.getParameter("voucherCode"); Map<String, Object> paramMap = new TreeMap<String, Object>(); if (!StringUtils.isEmpty(orderId)) { paramMap.put("site_order_no", orderId); } if (!StringUtils.isEmpty(vouCode)) { paramMap.put("coupons", vouCode); } String apiType = PartnerApiType.TUAN800.name(); PartnerService partnerService = null; logger.info("++++++++++++++++++++/partner/queryTrxOrderToT800.do++++++++++++++++++"); try { PartnerInfo partnerInfo = partnerCommonService.qryAvaParterByNoInMem(publicKey); if (partnerInfo != null) { apiType = partnerInfo.getApiType(); partnerService = partnerServiceFactory.getPartnerService(apiType); if (!paramMap.isEmpty()) { String params = JsonUtil.getJsonStringFromMap(paramMap); params = params.replace("\\", ""); params = params.replace("\"[", "[\""); params = params.replace("]\"", "\"]"); String sign = partnerService.checkHmacData(params, publicKey, partnerInfo.getKeyValue()); Map<String, Object> map = new HashMap<String, Object>(); map.put("params", params); map.put("sign", sign); map.put("appKey", publicKey); List<String> responseStr = null; responseStr = HttpUtils.URLPost(url, map); logger.info("++++++++++++responseStr=++++" + responseStr); if (responseStr.size() == 0 || responseStr == null) { response.getWriter().write("responseStr.size() == 0 || responseStr == null"); } else { String result = ""; // 请求返回的结果状态 String msg = ""; // 请求返回的消息 String data = "";// 请求返回的数据 String currentResult = responseStr.get(0); Map<String, Object> objMap = JsonUtil.getMapFromJsonString(currentResult); if (objMap.get("ret") != null) { result = objMap.get("ret").toString(); } if (objMap.get("msg") != null) { msg = objMap.get("msg").toString(); } if (objMap.get("data") != null) { data = objMap.get("data").toString(); } logger.info("++++++++++++++queryTrxOrderToT800+++++++++result=" + result + "+++++++++++++++"); if ("0".equals(result)) { if (data == null || data.equals("")) { response.getWriter().write("data == null || data.equals(\"\")"); } else { logger.info("++++++++++++++queryTrxOrderToT800++++++++data = " + data + "+++++++++"); // TODO 数据如何展示,未定 response.getWriter().write(data); } } else { /** * 0 请求成功 1 失败 */ response.getWriter().write("获取信息失败"); logger.info("++++++++++++result=" + result + "++++++++msg=" + msg); } } } } else { response.getWriter().write("此分销商不存在"); } } catch (IOException e) { e.printStackTrace(); } } /** * 1号店分销商统一入口 * * @param request * @param response * @return */ @SuppressWarnings("unchecked") @RequestMapping("/partner/synchro1mallTrxOrder.do") public void synchro1mallTrxOrder(HttpServletRequest request, HttpServletResponse response) { String method = StringUtils.toTrim(request.getParameter("method"));// 一号店请求类型 String format = StringUtils.toTrim(request.getParameter("format")); logger.info("+++++++++++++++synchro1mallTrxOrder+++++++++++method=" + method); // 一号店编码为UTF-8 response.setCharacterEncoding("UTF-8"); Par1mallOrderParam param; try { StringBuilder paramBuilder = new StringBuilder(); Enumeration<String> enume = request.getParameterNames(); while (enume.hasMoreElements()) { String key = enume.nextElement(); String[] value = request.getParameterValues(key); if (paramBuilder.toString().length() > 0) { paramBuilder.append("&"); } paramBuilder.append(key).append("=").append(value[0]); } logger.info("++++++++1mall request message=" + paramBuilder.toString()); String partnerNo = StringUtils.toTrim(request.getParameter("merchantId")); // 获得一号店发送的partnerNo if ("".equals(partnerNo)) {// 一号店无商家ID直接赋值 partnerNo = Par1mallOrderGenerator.PARTERNO_1MALL; } PartnerInfo partnerInfo = partnerCommonService.qryAvaParterByNoInMem(partnerNo); List<Long> userIdList = partnerCommonService.qryAllUserIdByNoInMem(partnerNo); PartnerService partenerService = partnerServiceFactory.getPartnerService(PartnerApiType.YHD.name()); // 获得一号店分销商service String reqIp = StringUtils.getIpAddr(request);// 获取服务器IP logger.info("+++++++++++++++partnerNo=" + partnerNo + "++++reqIp=" + reqIp); String paramInfo = partenerService.checkHmacData(paramBuilder.toString(), partnerInfo, reqIp);// 传入密文和商家编号以及与请求IP logger.info("++++++1mall checkHmacData.... paramInfo=" + paramInfo + "+++++++++"); if ("10100".equals(paramInfo)) { param = new Par1mallOrderParam(); param.setErrorCount(1); param.setUpdateCount(0); param.setErrorCode("invalid.request"); param.setErrorDes("非法的请求报文"); param.setPkInfo("sign"); } else { logger.info("+++++++++++++1mall+++message check ok+++++++++"); param = (Par1mallOrderParam) partenerService.transReqInfo(paramBuilder.toString()); param.setUserIdList(userIdList); param.setUserId(partnerInfo.getUserId()); param.setPartnerNo(partnerNo); param.setClientIp(reqIp); String resMessage = ""; // 订单信息通知接口 if (method.equals("yhd.group.buy.order.inform")) { logger.info("+++++++++++++1mall+++synchroTrxOrder+++++++++"); param.setCheckCode(partnerInfo.getKeyValue()); param.setSecretKey(partnerInfo.getSessianKey()); resMessage = partenerService.synchroTrxOrder(param, partnerNo); } // 消费券退款申请 else if (method.equals("yhd.group.buy.refund.request")) { logger.info("+++++++++++++1mall+++processTrxOrder+++++++++"); param.setCheckCode(partnerInfo.getKeyValue()); param.setSecretKey(partnerInfo.getSessianKey()); resMessage = partenerService.processTrxOrder(param); } // 消费券短信重新发送 else if (method.equals("yhd.group.buy.voucher.resend")) { logger.info("+++++++++++++1mall+++noTscResendVoucher+++++++++"); resMessage = partenerService.noTscResendVoucher(param); } // 查询消费券信息 else if (method.equals("yhd.group.buy.vouchers.get")) { logger.info("+++++++++++++1mall+++findVoucher+++++++++"); resMessage = partenerService.findVoucher(param, partnerNo); } try { logger.info("+++++1mall response message=" + resMessage); response.getWriter().write(resMessage); } catch (IOException e1) { logger.error(e1); } return; } } catch (Exception e) { logger.error("++++++++++++++1mall interface handle error", e); param = new Par1mallOrderParam(); param.setErrorCount(1); param.setUpdateCount(0); param.setTotalCount(0); param.setFormat(format.equals("") ? Par1mallOrderGenerator.FORMAT_JSON : format); param.setErrorCode("yhd.invoices.invalid.message"); param.setErrorDes("请求报文非法或请求参数有误"); param.setPkInfo(""); } String resMessage = Par1mallOrderGenerator.packageResponseMsg(param); logger.info("+++++1mall response message=" + resMessage); try { response.getWriter().write(resMessage); } catch (IOException e1) { logger.error(e1); } return; } }
package com.dokyme.alg4.sorting.application; import com.dokyme.alg4.sorting.quick.Quick; import edu.princeton.cs.algs4.StdOut; import java.util.Arrays; /** * Created by intellij IDEA.But customed by hand of Dokyme. * * @author dokym * @date 2018/5/27-12:19 * Description: */ public class Dedup { public static String[] dedup(String[] a) { new Quick().sort(a); String[] res = new String[a.length]; int size = 0; for (int i = 0; i < a.length; ) { String current = a[i++]; while (i < a.length && current.equals(a[i])) { i++; } res[size++] = current; } String[] newRes = new String[size]; System.arraycopy(res, 0, newRes, 0, size); return newRes; } public static void main(String[] args) { String[] a = new String[]{"a", "b", "c", "a", "aa", "b", "a", "f"}; a = dedup(a); StdOut.println(Arrays.toString(a)); } }
package com.cogs189.chad.bci.main; import android.bluetooth.BluetoothAdapter; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.FragmentTransaction; import android.view.Window; import android.widget.Toast; import com.cogs189.chad.bci.BaseActivity; import com.cogs189.chad.bci.R; import com.cogs189.chad.bci.controllers.navigation.NavigationControllerObserver; import com.cogs189.chad.bci.controllers.navigation.Page; import com.neurosky.AlgoSdk.NskAlgoDataType; import com.neurosky.AlgoSdk.NskAlgoSdk; import com.neurosky.connection.ConnectionStates; import com.neurosky.connection.TgStreamHandler; import com.neurosky.connection.TgStreamReader; public class MainActivity extends BaseActivity implements NavigationControllerObserver { private static final Page START_PAGE = Page.MAIN_HOME; private BluetoothAdapter mBluetoothAdapter; private TgStreamReader tgStreamReader; private NskAlgoSdk nskAlgoSdk; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); this.requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.activity_main); } @Override protected void onStart() { super.onStart(); getControllerFactory().getNavigationController().addObserver(this); openStartFragment(); } @Override protected void onStop() { if (getControllerFactory() != null) { getControllerFactory().getNavigationController().removeObserver(this); } super.onStop(); } private void transitionToStreamActivity() { getControllerFactory().getNavigationController().removeObserver(this); Intent intent = new Intent(this, StreamActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP|Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(intent); finish(); } @Override protected void onDestroy() { super.onDestroy(); } private void openStartFragment() { Page currentPage = getControllerFactory().getNavigationController().getCurrentPage(); getControllerFactory().getNavigationController().transitionToPage(currentPage, START_PAGE); } @Override public void onPageTransition(Page fromPage, Page toPage) { if(toPage == Page.MINDWAVE_STREAM ) { getControllerFactory().getNavigationController().overrideCurrentPage(fromPage); transitionToStreamActivity(); return; } FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction(); switch(toPage) { case MAIN_HOME: fragmentTransaction.replace(R.id.activity_main, HomeFragment.getInstance(), HomeFragment.TAG); break; case MAIN_TEST: break; } fragmentTransaction.addToBackStack(toPage.name()); fragmentTransaction.commit(); } private TgStreamHandler callback = new TgStreamHandler() { @Override public void onStatesChanged(int connectionStates) { // TODO Auto-generated method stub switch (connectionStates) { case ConnectionStates.STATE_CONNECTING: // Do something when connecting break; case ConnectionStates.STATE_CONNECTED: // Do something when connected tgStreamReader.start(); showToast("Connected", Toast.LENGTH_SHORT); break; case ConnectionStates.STATE_WORKING: // Do something when working //(9) demo of recording raw data , stop() will call stopRecordRawData, //or you can add a button to control it tgStreamReader.startRecordRawData(); break; case ConnectionStates.STATE_GET_DATA_TIME_OUT: // Do something when getting data timeout //(9) demo of recording raw data, exception handling tgStreamReader.stopRecordRawData(); showToast("Get data time out!", Toast.LENGTH_SHORT); break; case ConnectionStates.STATE_STOPPED: // Do something when stopped // We have to call tgStreamReader.stop() and tgStreamReader.close() much more than // tgStreamReader.connectAndstart(), because we have to prepare for that. break; case ConnectionStates.STATE_DISCONNECTED: // Do something when disconnected break; case ConnectionStates.STATE_ERROR: // Do something when you get error message break; case ConnectionStates.STATE_FAILED: // Do something when you get failed message // It always happens when open the BluetoothSocket error or timeout // Maybe the device is not working normal. // Maybe you have to try again break; } } @Override public void onRecordFail(int flag) { // You can handle the record error message here } @Override public void onChecksumFail(byte[] payload, int length, int checksum) { // You can handle the bad packets here. } @Override public void onDataReceived(int datatype, int data, Object obj) { // You can handle the received data here // You can feed the raw data to algo sdk here if necessary. //Log.i(TAG,"onDataReceived"); short attValue[] = {(short)data}; nskAlgoSdk.NskAlgoDataStream(NskAlgoDataType.NSK_ALGO_DATA_TYPE_ATT.value, attValue, 1); } }; public void showToast(final String msg, final int timeStyle) { MainActivity.this.runOnUiThread(new Runnable() { public void run() { Toast.makeText(getApplicationContext(), msg, timeStyle).show(); } }); } }
/* * 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.nuance.expertassistant; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.PrintWriter; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.logging.Level; import java.util.logging.Logger; import org.apache.commons.lang3.StringEscapeUtils; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; /** * * @author abhishek_rohatgi */ public class ContentExtractor { static PrintWriter writer = null; public static void startDocument(String Title, String Filepath) { try { writer = new PrintWriter(Filepath, "UTF-8"); writer.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "<document xmlns:fo=\"http://www.w3.org/1999/XSL/Format\"\n" + " xmlns:xs=\"http://www.w3.org/2001/XMLSchema\"\n" + " xmlns:fn=\"http://www.w3.org/2005/xpath-functions\"\n" + " xmlns:xdt=\"http://www.w3.org/2005/xpath-datatypes\"\n" + " docid=\"a382247e\"\n" + " title=\"" + Title + "\">"); } catch (final FileNotFoundException ex) { Logger.getLogger(ContentExtractor.class.getName()).log( Level.SEVERE, null, ex); } catch (final UnsupportedEncodingException ex) { Logger.getLogger(ContentExtractor.class.getName()).log( Level.SEVERE, null, ex); } } public static void extract(String URL) { try { final Document doc = Jsoup.connect(URL).timeout(0).get(); extract(doc); } catch (final IOException ex) { Logger.getLogger(ContentExtractor.class.getName()).log( Level.SEVERE, null, ex); } } public static void extract(File file, String charsetName) { try { final Document doc = Jsoup.parse(file, charsetName); extract(doc); } catch (final IOException ex) { Logger.getLogger(ContentExtractor.class.getName()).log( Level.SEVERE, null, ex); } } public static void extract(Document doc) { final Elements links = doc.getElementsByTag("a"); final Elements ps = doc.select("p"); final String title = doc.title(); print("<section id =\"{}\" title =\"" + stripNonValidXMLCharacters(doc.title()) + "\">"); final Elements elements = doc.select("*"); final ArrayList<String> openHeaderList = new ArrayList<String>(); for (final Element element : elements) { if (element.ownText() == null || element.ownText().isEmpty() || element.ownText().trim() == "") { } else if (element.tagName().toString().contains("a")) { } else if (element.tagName().contains("h1") && element.text() != null && !element.text().isEmpty()) { if (openHeaderList.contains("h1")) { openHeaderList.remove("h1"); print("</section>"); } if (openHeaderList.contains("h2")) { openHeaderList.remove("h2"); print("</section>"); } if (openHeaderList.contains("h3")) { openHeaderList.remove("h3"); print("</section>"); } if (openHeaderList.contains("h4")) { openHeaderList.remove("h4"); print("</section>"); } print("<section id =\"{}\" title =\"" + stripNonValidXMLCharacters(element.text()) + "\">"); openHeaderList.add("h1"); } else if (element.tagName().contains("h2") && element.text() != null && !element.text().isEmpty()) { if (openHeaderList.contains("h2")) { openHeaderList.remove("h2"); print("</section>"); } if (openHeaderList.contains("h3")) { openHeaderList.remove("h3"); print("</section>"); } if (openHeaderList.contains("h4")) { openHeaderList.remove("h4"); print("</section>"); } print("<section id =\"{}\" title =\"" + stripNonValidXMLCharacters(element.text()) + "\">"); openHeaderList.add("h2"); } else if (element.tagName().contains("h3") && element.text() != null && !element.text().isEmpty()) { if (openHeaderList.contains("h3")) { openHeaderList.remove("h3"); print("</section>"); } if (openHeaderList.contains("h4")) { openHeaderList.remove("h4"); print("</section>"); } print("<section id =\"{}\" title =\"" + stripNonValidXMLCharacters(element.text()) + "\">"); openHeaderList.add("h3"); } else if (element.tagName().contains("h4") && element.text() != null && !element.text().isEmpty()) { if (openHeaderList.contains("h4")) { openHeaderList.remove("h4"); print("</section>"); } print("<section id =\"{}\" title =\"" + stripNonValidXMLCharacters(element.text()) + "\">"); openHeaderList.add("h4"); } else { print("<para>"); print(stripNonValidXMLCharacters(element.ownText())); print("</para>"); } /* * if (element.tagName().contains("img")) { print("<img src=\"" + * element.attr("src") + "\"></img>"); } */ } if (openHeaderList.contains("h1")) { openHeaderList.remove("h1"); print("</section>"); } if (openHeaderList.contains("h2")) { openHeaderList.remove("h2"); print("</section>"); } if (openHeaderList.contains("h3")) { openHeaderList.remove("h3"); print("</section>"); } if (openHeaderList.contains("h4")) { openHeaderList.remove("h4"); print("</section>"); } print("</section>"); } private static synchronized void print(String msg) { try { writer.println(msg); } catch (final Exception e) { e.printStackTrace(); System.out.println("Exception cause while writing to file"); } } public static void endDocument() { writer.println("</document>"); writer.close(); } public static String stripNonValidXMLCharacters(String in) { String output = in.replaceAll(">>", ""); output = output.replaceAll(">>", "").replaceAll("\n", "") .replaceAll("\"", "").replaceAll("\u201c", "") .replaceAll("\u201d", "").replaceAll("\u2022", "") .replaceAll("&", ""); return StringEscapeUtils.escapeXml(output); /* * StringBuffer out = new StringBuffer(); // Used to hold the output. * char current; // Used to reference the current character. * * if (in == null || in.equalsIgnoreCase("")) { return null; } * * for (int i = 0; i < in.length(); i++) { current = in.charAt(i); // * NOTE: No IndexOutOfBoundsException caught here; it should not happen. * if ((current == 0x9) || (current == 0xA) || (current == 0xD) || * ((current >= 0x20) && (current <= 0xD7FF)) || ((current >= 0xE000) && * (current <= 0xFFFD)) || ((current >= 0x10000) && (current <= * 0x10FFFF))) { out.append(current); } } * * return out.toString().replaceAll(">>", ""); */ } }
package com.example.usser.moneycatch; import android.Manifest; import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.content.pm.PackageManager; import android.os.Handler; import android.provider.ContactsContract; import android.provider.MediaStore; import android.support.v4.app.ActivityCompat; import android.support.v4.content.ContextCompat; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.Gravity; import android.view.View; import android.widget.Button; import android.widget.ImageButton; import android.widget.Toast; public class FirstviewActivity extends Activity { String Tag = "퍼스트 액티비티"; // 로그 검색용 ImageButton self; ImageButton call; ImageButton finish; ImageButton start; // void dialogshow(){ // 다이얼로그 만들기 // final AlertDialog.Builder builder = new AlertDialog.Builder(this); // builder.setTitle("나는 광고창이지롱"); // builder.setMessage("약오르지 광고나와서"); // builder.setPositiveButton("네", new DialogInterface.OnClickListener() { // @Override // public void onClick(DialogInterface dialogInterface, int i) { // // } // }); // builder.setNegativeButton("아니요", new DialogInterface.OnClickListener() { // @Override // public void onClick(DialogInterface dialogInterface, int i) { // // } // }); // builder.show(); // // } // 다이얼로그 종료 void addialogshow(){ // 다이얼로그 만들기 final AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle("2번 뒤로가기하면 나온다"); builder.setMessage("나왔으니까 이제 안나온다"); builder.setPositiveButton("네", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { } }); builder.setNegativeButton("아니요", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { } }); builder.show(); } // 다이얼로그 종료 @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_firstview); self = (ImageButton)findViewById(R.id.camerabtn); // 카메라버튼 call = (ImageButton) findViewById(R.id.callbtn); // 전화버튼 finish = (ImageButton) findViewById(R.id.finishbtn); // no 버튼 start = (ImageButton) findViewById(R.id.startbtn); // Yes 버튼 final Toast hellow = Toast.makeText(getApplicationContext(),"안녕하세요",Toast.LENGTH_LONG); start.setOnClickListener(new View.OnClickListener() { // 시작하기 버튼을 누르면 메인 액티비티 띄우기 @Override public void onClick(View view) { // yes 버튼 누를시 메인 액티비티 전환 Intent intent = new Intent(getApplicationContext(),MainActivity.class); startActivity(intent); hellow.show(); onPause(); // hellow.setGravity(Gravity.TOP,0,0); 토스트 위치값 조정 } }); //startbtn 끝 finish.setOnClickListener(new View.OnClickListener() { // 종료하기 버튼 누르면 앱이 종료되기 @Override public void onClick(View view) { // No 버튼 누를시 앱 종료 onPause(); android.os.Process.killProcess(android.os.Process.myPid()); moveTaskToBack(true); } });// finish 끝 self.setOnClickListener(new View.OnClickListener() { //카메라 앱 구동 @Override public void onClick(View view) { // 카메라 앱 불러오기 // 사용자에게 권한 묻기 int permissioncheck = ContextCompat.checkSelfPermission(FirstviewActivity.this, Manifest.permission.CAMERA); if(permissioncheck== PackageManager.PERMISSION_DENIED){ //DENIED는 권한이 없을 때 ActivityCompat.requestPermissions(FirstviewActivity.this,new String[]{Manifest.permission.CAMERA},0); }else{ //권한이 있다면 카메라 앱 작동 Intent picture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); startActivity(picture); } } }); // 카메라 끝 call.setOnClickListener(new View.OnClickListener() { // 전화걸기 앱으로 연결 @Override public void onClick(View view) { // 전화앱 실행시키기 Intent call = new Intent(Intent.ACTION_DIAL); startActivity(call); } }); // 전화 앱 끝 Log.e(Tag,"oncreate"); } //ocreate 끝 // int a = 0; @Override protected void onStart() { super.onStart(); // a++; // if (a==3){ // addialogshow(); // } Log.e(Tag,"onstart"); } @Override protected void onResume() { super.onResume(); Log.e(Tag,"onresume"); } @Override protected void onPause() { super.onPause(); Log.e(Tag,"onpause"); } @Override protected void onStop() { super.onStop(); Log.e(Tag,"onstop"); } @Override protected void onDestroy() { super.onDestroy(); Log.e(Tag,"ondestroy"); } @Override protected void onRestart() { super.onRestart(); Log.e(Tag,"onrestart"); } } // 메인 끝
package toba.business; import java.io.Serializable; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.ManyToOne; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; /** * * @author Jake */ @Entity public class Transaction implements Serializable { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long transactionId; @ManyToOne private Account source; @ManyToOne private Account dest; private float amount; public Transaction () { this.source = null; this.dest = null; this.amount = 0.0f; } public Transaction (Account source, Account dest, float amount) { this.source = source; this.dest = dest; this.amount = amount; } public Long getTransactionId () { return this.transactionId; } public void setTransactionId (Long transactionId) { this.transactionId = transactionId; } public Account getSource () { return this.source; } public void setSource (Account source) { this.source = source; } public Account getDest () { return this.dest; } public void setDest (Account dest) { this.dest = dest; } public float getAmount () { return this.amount; } public void setAmount (float amount) { this.amount = amount; } }
package com.soa.rest.resource; import com.soa.domain.UserData; import com.soa.domain.hero.Dragon; import com.soa.domain.hero.Elf; import com.soa.domain.hero.Mag; import com.soa.rest.service.TranslateService; import com.soa.service.DataAccessService; import com.soa.ws.hero.WSDragon; import com.soa.ws.hero.WSElf; import com.soa.ws.hero.WSMag; import com.soa.ws.hero.response.WSDragonResponse; import com.soa.ws.hero.response.WSElfResponse; import com.soa.ws.hero.response.WSMagResponse; import javax.ejb.EJB; import javax.inject.Inject; import javax.ws.rs.GET; import javax.ws.rs.HeaderParam; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import java.security.Principal; import java.util.List; import java.util.stream.Collectors; @Path("/heroes") public class HeroResource { public static final MediaType PL_APPLICATION_JSON = new MediaType("application", "json-pl"); @EJB private DataAccessService dataService; @Inject private Principal principal; @EJB private TranslateService transalateService; @GET @Path("/dragons") @Produces(MediaType.APPLICATION_JSON) public Response dragons(@HeaderParam("Content-Type") MediaType mediaType) { List<Dragon> allDragons = dataService.findAllDragons(); if (PL_APPLICATION_JSON.equals(mediaType)) { List<WSDragonResponse> wsDragons = allDragons.stream() .map(WSDragonResponse::new) .map(transalateService::translate) .collect(Collectors.toList()); return Response.ok(wsDragons).build(); } List<WSDragonResponse> wsDragons = allDragons.stream() .map(WSDragonResponse::new) .collect(Collectors.toList()); return Response.ok(wsDragons).build(); } @GET @Path("/elves") @Produces(MediaType.APPLICATION_JSON) public Response elves(@HeaderParam("Content-Type") MediaType mediaType) { List<Elf> allElves = dataService.findAllElfs(); if (PL_APPLICATION_JSON.equals(mediaType)) { List<WSElfResponse> wsElves = allElves.stream() .map(WSElfResponse::new) .map(transalateService::translate) .collect(Collectors.toList()); return Response.ok(wsElves).build(); } List<WSElfResponse> wsElves = allElves.stream() .map(WSElfResponse::new) .collect(Collectors.toList()); return Response.ok(wsElves).build(); } @GET @Path("/mags") @Produces(MediaType.APPLICATION_JSON) public Response mags(@HeaderParam("Content-Type") MediaType mediaType) { List<Mag> mags = dataService.findAllMags(); if (PL_APPLICATION_JSON.equals(mediaType)) { List<WSMagResponse> wsMags = mags.stream() .map(WSMagResponse::new) .map(transalateService::translate) .collect(Collectors.toList()); return Response.ok(wsMags).build(); } List<WSMagResponse> wsMags = mags.stream() .map(WSMagResponse::new) .collect(Collectors.toList()); return Response.ok(wsMags).build(); } @GET @Path("/dragons/{dragonId}") @Produces(MediaType.APPLICATION_JSON) public Response dragonById(@HeaderParam("Content-Type") MediaType mediaType, @PathParam("dragonId") Long dragonId) { Dragon dragonById = dataService.findDragonById(dragonId); if (dragonById == null) { return Response.status(404).build(); } if (PL_APPLICATION_JSON.equals(mediaType)) { return Response.ok(transalateService.translate(new WSDragonResponse(dragonById))).build(); } return Response.ok(new WSDragonResponse(dragonById)).build(); } @GET @Path("/elves/{elfId}") @Produces(MediaType.APPLICATION_JSON) public Response elfById(@HeaderParam("Content-Type") MediaType mediaType, @PathParam("elfId") Long elfId) { Elf elfById = dataService.findElfById(elfId); if (elfById == null) { return Response.status(404).build(); } if (PL_APPLICATION_JSON.equals(mediaType)) { return Response.ok(transalateService.translate(new WSElfResponse(elfById))).build(); } return Response.ok(new WSElfResponse(elfById)).build(); } @GET @Path("/mags/{magId}") @Produces(MediaType.APPLICATION_JSON) public Response magById(@HeaderParam("Content-Type") MediaType mediaType, @PathParam("magId") Long magId) { Mag magById = dataService.findMagById(magId); if (magById == null) { return Response.status(404).build(); } if (PL_APPLICATION_JSON.equals(mediaType)) { return Response.ok(transalateService.translate(new WSMagResponse(magById))).build(); } return Response.ok(new WSMagResponse(magById)).build(); } @POST @Path("/dragons") @Produces(MediaType.APPLICATION_JSON) public Response dragons(WSDragon dragonRequest) { Dragon dragon = dragonRequest.toDragon(); dragon.setCave(dataService.findCaveById(dragonRequest.getCaveId())); UserData user = dataService.findUserDataByLogin(principal.getName()); if (user.getRole() != UserData.UserRole.ADMIN) { if (!user.getId().equals(dragon.getOwner().getId())) { return Response.status(403).build(); } } dataService.save(dragon); return Response.accepted().build(); } @POST @Path("/elves") @Produces(MediaType.APPLICATION_JSON) public Response elves(WSElf elfRequest) { Elf elf = elfRequest.toElf(); elf.setForest(dataService.findForestById(elfRequest.getForestId())); UserData user = dataService.findUserDataByLogin(principal.getName()); if (user.getRole() != UserData.UserRole.ADMIN) { if (!user.getId().equals(elf.getOwner().getId())) { return Response.status(403).build(); } } dataService.save(elf); return Response.accepted().build(); } @POST @Path("/mags") @Produces(MediaType.APPLICATION_JSON) public Response mags(WSMag magRequest) { Mag mag = magRequest.toMag(); mag.setTower(dataService.findTowerById(magRequest.getTowerId())); UserData user = dataService.findUserDataByLogin(principal.getName()); if (user.getRole() != UserData.UserRole.ADMIN) { if (!user.getId().equals(mag.getOwner().getId())) { return Response.status(403).build(); } } dataService.save(mag); return Response.accepted().build(); } }
package io.t99.philesd.cli; import java.util.Scanner; public final class CLI implements Runnable { static Scanner inputStream = new Scanner(System.in); private static Context context; private static CLIStream baseStream = new CLIStream("base", Context.BASE); public static CLIStream focus = baseStream; public void run() { while(true) { //processCommand(inputStream.nextLine()); } } // I guess I got rid of a couple of classes somewhere along the way? meh, not my concern rn -- TODO // public static void processCommand(String input) { // // CommandResource commandResource = CommandInterpreter.interpret(input); // // try { // // CommandManager.execute(commandResource.getCommand()); // // } catch (CommandNotFoundException e) { // // System.out.println("Could not find command: `" + commandResource.getCommand() + "`"); // // } // // } public static void clearConsole() { try { final String os = System.getProperty("os.name"); if (os.contains("Windows")) { new ProcessBuilder("cmd", "/c", "cls").inheritIO().start().waitFor(); } else { Runtime.getRuntime().exec("clear"); } } catch (final Exception e) { // Handle any exceptions. } } public static void setContext(Context newContext) { context = newContext; } public static Context getContext() { return context; } }
package com.gtambit.gt.app.record; import android.app.Activity; import android.app.ProgressDialog; import android.content.DialogInterface; import android.content.DialogInterface.OnCancelListener; import android.content.Intent; import android.graphics.Bitmap; import android.os.Bundle; import android.os.Handler; import android.view.View; import android.view.View.OnClickListener; import android.webkit.WebSettings; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.ImageView; import android.widget.ProgressBar; import android.widget.RelativeLayout; import android.widget.TextView; import com.gtambit.gt.app.api.GtApi; import com.gtambit.gt.app.mission.api.TaskApi; import com.gtambit.gt.app.mission.api.TaskRequestApi; import com.gtambit.gt.app.mission.obj.RecordTradeDetailType; import com.hyxen.analytics.AnalyticsTracker; import com.ambit.city_guide.R; import com.tms.lazytip.DrawerActivity; import ur.ui_component.drawer.URMenuType; public class TaskRecordGiftDetail extends DrawerActivity { private String tradeId; private Bitmap mGiftBitmap; private int isRead; // private ImageView mImageView_Picture; // private TextView mTextView_GiftName; // private TextView mTextView_GiftPoint; // private TextView mTextView_Number; // private TextView mTextView_Point; // private TextView mTextView_Name; // private TextView mTextView_Address; // private TextView mTextView_Phone; // private TextView mTextView_Date; // private RelativeLayout mRelativeLayout_Sent; // private TextView mTextView_SendDate; private ProgressDialog progressDialog; private Handler mHandler = new Handler(); private WebView mWebView; @Override public URMenuType onCurrentMenuType() { return null; } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.t_record_gift_detail); readBundle(); initialLayout(); setTradeInfo(); setTitleName(getString(R.string.ur_f_record_detail_title)); setBackBtn(true, null); } private void readBundle() { Intent intent = getIntent(); Bundle bundle = intent.getExtras(); tradeId = bundle.getString("tradeId"); isRead = bundle.getInt("isRead"); } private void initialLayout() { // findViewById(R.id.ImageButtonBack).setOnClickListener(this); // mImageView_Picture = (ImageView) findViewById(R.id.ImageView_Picture); // mTextView_GiftName = (TextView) findViewById(R.id.TextView_GiftName); // mTextView_GiftPoint = (TextView) findViewById(R.id.TextView_GiftPoint); // mTextView_Number = (TextView) findViewById(R.id.TextView_Number); // mTextView_Point = (TextView) findViewById(R.id.TextView_Point); // mTextView_Name = (TextView) findViewById(R.id.TextView_Name); // mTextView_Address = (TextView) findViewById(R.id.TextView_Address); // mTextView_Phone = (TextView) findViewById(R.id.TextView_Phone); // mTextView_Date = (TextView) findViewById(R.id.TextView_Date); // mRelativeLayout_Sent = (RelativeLayout) findViewById(R.id.RelativeLayout_Sent); // mTextView_SendDate = (TextView) findViewById(R.id.TextView_SendDate); final ProgressBar mProgressBar = (ProgressBar) findViewById(R.id.ProgressBar); mWebView = (WebView) findViewById(R.id.WebView); mWebView.setBackgroundColor(0); mWebView.setHorizontalScrollBarEnabled(false); WebSettings bs = mWebView.getSettings(); bs.setJavaScriptEnabled(true); mWebView.setWebViewClient(new WebViewClient(){ @Override public void onPageStarted(WebView view, String url, Bitmap favicon) { mHandler.post(new Runnable() { @Override public void run() { mProgressBar.setVisibility(View.VISIBLE); } }); super.onPageStarted(view, url, favicon); } @Override public void onPageFinished(WebView view, String url) { mHandler.post(new Runnable() { @Override public void run() { mProgressBar.setVisibility(View.GONE); } }); super.onPageFinished(view, url); } }); } private void setTradeInfo() { progressDialog = ProgressDialog.show(this, "", getString(R.string.reading), false, true, new OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { } }); Thread t = new Thread(){ @Override public void run() { final RecordTradeDetailType mRecordTradeDetailType = TaskRequestApi.getTradeRecordDetail(TaskRecordGiftDetail.this, tradeId); if (mRecordTradeDetailType != null && mRecordTradeDetailType.giftPicture != null) { mGiftBitmap = TaskApi.downloadImage(mRecordTradeDetailType.giftPicture); } mHandler.post(new Runnable() { @Override public void run() { progressDialog.dismiss(); if (mRecordTradeDetailType != null) { if (mGiftBitmap != null) { ImageView mImageView_Picture = (ImageView) findViewById(R.id.ImageView_Picture); mImageView_Picture.setImageBitmap(mGiftBitmap); } TextView mTextView_GiftName = (TextView) findViewById(R.id.TextView_GiftName); mTextView_GiftName.setText(mRecordTradeDetailType.giftName); TextView mTextView_Number = (TextView) findViewById(R.id.TextView_Number); mTextView_Number.setText(mRecordTradeDetailType.tradeQuantity); TextView mTextView_Point = (TextView) findViewById(R.id.TextView_Point); mTextView_Point.setText(mRecordTradeDetailType.tradePoint); TextView mTextView_GiftPoint = (TextView) findViewById(R.id.TextView_GiftPoint); mTextView_GiftPoint.setText(mRecordTradeDetailType.giftPoint); TextView mTextView_Name = (TextView) findViewById(R.id.TextView_Name); mTextView_Name.setText(mRecordTradeDetailType.name); TextView mTextView_Address = (TextView) findViewById(R.id.TextView_Address); mTextView_Address.setText(mRecordTradeDetailType.address); TextView mTextView_Phone = (TextView) findViewById(R.id.TextView_Phone); mTextView_Phone.setText(mRecordTradeDetailType.phone); TextView mTextView_Date = (TextView) findViewById(R.id.TextView_Date); mTextView_Date.setText(TaskApi.getDateFromTs(mRecordTradeDetailType.tradeTs*1000)); // if (mRecordTradeDetailType.taxId != null && mRecordTradeDetailType.taxId.length()>9) { String start = mRecordTradeDetailType.taxId.substring(0, 3); String end = mRecordTradeDetailType.taxId.substring(7, 10); String taxId = start + "****" + end; TextView mTextView_IdNum = (TextView) findViewById(R.id.TextView_IdNum); mTextView_IdNum.setText(taxId); } if (mRecordTradeDetailType.lineId != null && !mRecordTradeDetailType.lineId.equals("")) { findViewById(R.id.LinearLayout_LineId).setVisibility(View.GONE); TextView mTextView_LineId = (TextView) findViewById(R.id.TextView_LineId); mTextView_LineId.setText(mRecordTradeDetailType.lineId); } if (mRecordTradeDetailType.email != null && !mRecordTradeDetailType.email.equals("")) { findViewById(R.id.LinearLayout_Email).setVisibility(View.GONE); TextView mTextView_Email = (TextView) findViewById(R.id.TextView_Email); mTextView_Email.setText(mRecordTradeDetailType.email); } mWebView.loadDataWithBaseURL ("http://zerocard.tw/", mRecordTradeDetailType.giftHtml, "text/html", "utf-8", "http://zerocard.tw/"); if (mRecordTradeDetailType.isSent == 0) //0未送出, 1已送出 { RelativeLayout mRelativeLayout_Sent = (RelativeLayout) findViewById(R.id.RelativeLayout_Sent); mRelativeLayout_Sent.setVisibility(View.INVISIBLE); } else { RelativeLayout mRelativeLayout_Sent = (RelativeLayout) findViewById(R.id.RelativeLayout_Sent); mRelativeLayout_Sent.setVisibility(View.VISIBLE); // // TextView mTextView_SendDate = (TextView) findViewById(R.id.TextView_SendDate); // mTextView_SendDate.setText(TaskApi.getDateFromTs(mRecordTradeDetailType.sentTs*1000)); } } else { GtApi.alertOKMessage(TaskRecordGiftDetail.this, "", getString(R.string.t_read_fail), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { isRead = 0; finish(); } }); } } }); } }; t.start(); } @Override public void finish() { if (isRead == 1) { Intent intent = new Intent(); setResult(RESULT_OK, intent); } super.finish(); } }
package io.jrevolt.sysmon.common; import java.net.InetAddress; import java.net.URI; import java.net.UnknownHostException; import java.util.function.Consumer; /** * @author <a href="mailto:patrikbeno@gmail.com">Patrik Beno</a> */ public class Utils { static public <T> T get(T[] array, int index) { return array != null && array.length > index ? array[index] : null; } static public InetAddress getLocalHost() { try { return InetAddress.getLocalHost(); } catch (UnknownHostException e) { throw new UnsupportedOperationException(e); } } static public InetAddress getInetAddress(byte[] address) { try { return InetAddress.getByAddress(null, address); } catch (UnknownHostException never) { throw new AssertionError(never); } } static public String resolveHost(URI uri) { if (uri.getHost() != null) { return uri.getHost(); } return address(uri).getHost(); } static public int resolvePort(URI uri) { int port = uri.getPort(); if (port != -1) { return port; } if (uri.getHost() != null) { port = uri.getScheme().equals("http") ? 80 : uri.getScheme().equals("https") ? 443 : 0; return port; } return address(uri).getPort(); } static public URI address(URI uri) { if (uri.getHost() != null) { return uri; } URI tmp = URI.create("tcp://"+uri.toASCIIString().replaceFirst( "^(?:\\p{Alnum}+:)+//(?:[^@]*@)?([^:]+)(?::(\\p{Digit}+))?.*", "$1:$2")); return tmp; } static public String getExceptionDesription(Throwable t) { StringBuilder sb = new StringBuilder(); for (; t != null; t = t.getCause()) { if (sb.length() > 0) { sb.append("Caused by "); } sb.append(t.toString()).append("\n"); } return sb.toString(); } public static void runGuarded(Runnable r) { guarded(r).run(); } static public Runnable guarded(Runnable r) { return () -> { try { r.run(); } catch (Exception e) { e.printStackTrace(); Log.debug(r, e.toString()); } }; } static public <T> T with(T t, Consumer<T> consumer) { if (t != null) { consumer.accept(t); } return t; } static public void doif(boolean condition, Runnable action) { if (condition) { action.run(); } } }
package fr.eni.groupe2.servlets; import java.io.IOException; import java.util.ArrayList; import java.util.List; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import fr.eni.groupe2.bll.EnchereManager; import fr.eni.groupe2.bo.Categorie; import fr.eni.groupe2.bo.Enchere; import fr.eni.groupe2.bo.Utilisateur; import fr.eni.groupe2.dal.jdbc.CategorieDAOJdbcImpl; import fr.eni.groupe2.messages.BusinessException; import fr.eni.groupe2.messages.DALException; /** * Servlet implementation class TraitementAccueilSession */ @WebServlet("/TraitementAccueilSession") public class TraitementAccueilSession extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.getServletContext().getRequestDispatcher("/WEB-INF/pageAccueilTest.jsp").forward(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { List<Enchere> listeEncheres = new ArrayList<Enchere>() ; List<Categorie> listeCategories = new ArrayList<Categorie>() ; Utilisateur utilisateurConnecter = new Utilisateur(); String errorMessage =""; String description =""; String categorie =""; String checkChoix=""; String etatAchat=""; // Récupération de la session HttpSession session = request.getSession(); utilisateurConnecter = (Utilisateur) session.getAttribute("utilisateurConnecter"); description = request.getParameter("description"); categorie =request.getParameter("categorie"); try { if(!description.isEmpty()) { listeEncheres= EnchereManager.listerEnchereParMot(description); } if(!categorie.isEmpty()) { listeEncheres= EnchereManager.listerEnchereParCategorie(categorie); } if(checkChoix.equals("Ventes")) { listeEncheres= EnchereManager.listerEnchereParPseudo(utilisateurConnecter.getPseudo()); } if(checkChoix.equals("Achat")) { listeEncheres= EnchereManager.listerEnchere(); } listeCategories= CategorieDAOJdbcImpl.selectAll(); } catch (DALException|BusinessException e) { errorMessage =e.getMessage(); } if (!errorMessage.isEmpty()) { request.setAttribute("errorMessage", errorMessage); }else { request.setAttribute("listeEncheres", listeEncheres); request.setAttribute("listeCategories", listeCategories); } this.getServletContext().getRequestDispatcher("/WEB-INF/pageAccueilTest.jsp").forward(request, response); } }
package com.sportzcourt.booking.model.events; /** * Created by Narasimha.HS on 12/7/2015. * * To be posted as a sticky event after successful login. The user will land at Main Screen if he is already logged in. * If the user clears the app from Recent Apps Screen/app's process is killed by the system, event will be cleared away * and the user will land at the Login Screen when the app is opened later. */ public class UserCredsEvent { public final boolean loggedIn; public final String userName; public UserCredsEvent(boolean loggedIn, String userName){ this.loggedIn = loggedIn; this.userName = userName; } }
package cn.edu.swufe.myapp; import android.util.Log; public class Helper { String result; private final String TAG = "Helper"; public Helper() { result = ""; } public Helper(String res) { result = res; } public String getResult() { Log.i(TAG, "getResult: "+result); return result; } public void setResult(String result) { this.result = result; } }
/** * Created by Shin on 2017-05-26. */ public class Tactic { private String name; private int offence; // int : 1~5 private int defence; // int : 1~5 public Tactic(String name, int offence, int defence) { this.name = name; this.offence = offence; this.defence = defence; } public String getName() { return name; } public double getOffence() { return offence; } public double getDefence() { return defence; } }
package com.yf.accountmanager; import android.app.ActionBar; import android.app.Activity; import android.content.ContentValues; import android.database.Cursor; import android.os.Bundle; import android.text.TextUtils; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.ImageButton; import android.widget.LinearLayout; import com.yf.accountmanager.adapter.PickerAdapter; import com.yf.accountmanager.common.IConstants; import com.yf.accountmanager.sqlite.ISQLite.AccountColumns; import com.yf.accountmanager.sqlite.AccountService; import com.yf.accountmanager.ui.CustomizedDialog; import com.yf.accountmanager.util.CommonUtils; public class AccountDetailActivity extends Activity implements OnClickListener { private int resId = R.layout.activity_accountdetail, editButtonId = 0x11; private EditText mailBox, password, username, passport, sitename, phoneNum, website, identifyingCode, ask, answer,group; private Button mailBoxDisposer, passwordDisposer, usernameDisposer, passportDisposer, sitenameDisposer, phoneNumDisposer, websiteDisposer, identifyingCodeDisposer, askDisposer, answerDisposer, groupDisposer,save; private ImageButton pickMailBox, pickPassword, pickUsername, pickPassport, pickSite, pickPhoneNum, pickWebsite, pickIdentifyingCode, pickAsk, pickAnswer,pickGroup; private LinearLayout container; private ContentValues content; private View[] ableGroup, visibleGroup; private EditText[] textSequence; private String[] columnSequence = new String[] { AccountColumns.MAILBOX, AccountColumns.PASSWORD, AccountColumns.USERNAME, AccountColumns.PASSPORT, AccountColumns.SITENAME, AccountColumns.PHONENUM, AccountColumns.WEBSITE, AccountColumns.IDENTIFYING_CODE, AccountColumns.ASK, AccountColumns.ANSWER,AccountColumns.GROUP }; private CustomizedDialog picker; private PickerAdapter pickerAdapter; private boolean contentChanged=false; protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(resId); getActionBar().setDisplayOptions( ActionBar.DISPLAY_SHOW_HOME | ActionBar.DISPLAY_HOME_AS_UP); init(); if (content == null) { if (savedInstanceState == null) CommonUtils.requetFocus(container, ableGroup,textSequence); save.setText("保存信息"); save.setBackgroundResource(R.drawable.selector_blue_radius_button); } else { if (savedInstanceState == null) CommonUtils.blockFocus(container, ableGroup, visibleGroup,textSequence); fillInfos(); save.setText("更新信息"); save.setBackgroundResource(R.drawable.selector_blue_button); } bindListeners(); } private void init() { container = (LinearLayout) findViewById(R.id.linearLayout1); mailBoxDisposer = (Button) findViewById(R.id.button1); passwordDisposer = (Button) findViewById(R.id.button2); usernameDisposer = (Button) findViewById(R.id.button3); passportDisposer = (Button) findViewById(R.id.button4); sitenameDisposer = (Button) findViewById(R.id.button5); phoneNumDisposer = (Button) findViewById(R.id.button6); websiteDisposer = (Button) findViewById(R.id.button7); identifyingCodeDisposer = (Button) findViewById(R.id.button8); askDisposer = (Button) findViewById(R.id.button9); answerDisposer = (Button) findViewById(R.id.button10); groupDisposer = (Button) findViewById(R.id.button11); save = (Button) findViewById(R.id.button16); pickMailBox = (ImageButton) findViewById(R.id.imageButton1); pickPassword = (ImageButton) findViewById(R.id.imageButton2); pickUsername = (ImageButton) findViewById(R.id.imageButton3); pickPassport = (ImageButton) findViewById(R.id.imageButton4); pickSite = (ImageButton) findViewById(R.id.imageButton5); pickPhoneNum = (ImageButton) findViewById(R.id.imageButton6); pickWebsite = (ImageButton) findViewById(R.id.imageButton7); pickIdentifyingCode = (ImageButton) findViewById(R.id.imageButton8); pickAsk = (ImageButton) findViewById(R.id.imageButton9); pickAnswer = (ImageButton) findViewById(R.id.imageButton10); pickGroup = (ImageButton) findViewById(R.id.imageButton11); mailBox = (EditText) findViewById(R.id.editText1); password = (EditText) findViewById(R.id.editText2); username = (EditText) findViewById(R.id.editText3); passport = (EditText) findViewById(R.id.editText4); sitename = (EditText) findViewById(R.id.editText5); phoneNum = (EditText) findViewById(R.id.editText6); website = (EditText) findViewById(R.id.editText7); identifyingCode = (EditText) findViewById(R.id.editText8); ask = (EditText) findViewById(R.id.editText9); answer = (EditText) findViewById(R.id.editText10); group = (EditText) findViewById(R.id.editText11); content = (ContentValues) getIntent().getParcelableExtra( IConstants.ACCOUNT); ableGroup = new View[] { pickMailBox, pickPassword, pickUsername, pickPassport, pickSite, pickPhoneNum, pickWebsite, pickIdentifyingCode, pickAsk, pickAnswer,pickGroup, save }; visibleGroup = new View[] { mailBoxDisposer, passwordDisposer, usernameDisposer, passportDisposer, sitenameDisposer, phoneNumDisposer, websiteDisposer, identifyingCodeDisposer, askDisposer, answerDisposer,groupDisposer }; textSequence = new EditText[] { mailBox, password, username, passport, sitename, phoneNum, website, identifyingCode, ask, answer,group }; } public void onClick(View v) { if (v == save) { String site = sitename.getText().toString(); if (TextUtils.isEmpty(site)) { CommonUtils.toast("站点名称必须填写"); sitename.requestFocus(); return; } if (content == null) saveAccount(); else updateAccount(); } else { showPicker(v); } } private void showPicker(View v) { int index = indexOfViewInAbleGroup(v); if(index==-1||index>columnSequence.length-1) return; if (picker == null) { picker = CustomizedDialog.initOptionDialog(this); picker.lv.setAdapter(pickerAdapter=new PickerAdapter(this)); picker.lv.setOnItemClickListener(new OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View self, int position, long id) { textSequence[indexOfColumn(pickerAdapter.getCursor().getColumnName(0))].setText (pickerAdapter.getCursor().getString(0)); picker.dismiss(); } }); } Cursor cursor=AccountService.queryDistinctColumnWithId(columnSequence[index]); pickerAdapter.changeCursor(cursor); picker.title.setText(columnSequence[index]); picker.show(); } private int indexOfColumn(String str){ for(int i=0;i<columnSequence.length;i++){ if(str.equalsIgnoreCase(columnSequence[i])) return i; } return -1; } private int indexOfViewInAbleGroup(View v) { for(int i=0;i<ableGroup.length;i++){ if(v==ableGroup[i]) return i; } return -1; } private void saveAccount() { ContentValues cv = encapsulateAccountInfo(); if (AccountService.addAccount(cv) > 0) { CommonUtils.toast("保存成功"); CommonUtils.blockFocus(container, ableGroup, visibleGroup,textSequence); contentChanged=true; } else { CommonUtils.toast("保存失败"); } } private void updateAccount() { ContentValues cv = encapsulateAccountInfo(); if (AccountService.updateAccount(cv, content.getAsInteger(AccountColumns.ID))) { CommonUtils.toast("更新成功"); CommonUtils.blockFocus(container, ableGroup, visibleGroup,textSequence); contentChanged=true; } else { CommonUtils.toast("更新失败"); } } private ContentValues encapsulateAccountInfo() { ContentValues cv = new ContentValues(); cv.put(AccountColumns.MAILBOX, mailBox.getText().toString()); cv.put(AccountColumns.PASSPORT, passport.getText().toString()); cv.put(AccountColumns.PASSWORD, password.getText().toString()); cv.put(AccountColumns.PHONENUM, phoneNum.getText().toString()); cv.put(AccountColumns.SITENAME, sitename.getText().toString()); cv.put(AccountColumns.USERNAME, username.getText().toString()); cv.put(AccountColumns.WEBSITE, website.getText().toString()); cv.put(AccountColumns.IDENTIFYING_CODE, identifyingCode.getText() .toString()); cv.put(AccountColumns.ASK, ask.getText().toString()); cv.put(AccountColumns.ANSWER, answer.getText().toString()); cv.put(AccountColumns.GROUP, group.getText().toString()); return cv; } private void bindListeners() { for (View v : ableGroup) v.setOnClickListener(this); CommonUtils.bindEditTextNtextDisposer(mailBox, mailBoxDisposer); CommonUtils.bindEditTextNtextDisposer(password, passwordDisposer); CommonUtils.bindEditTextNtextDisposer(username, usernameDisposer); CommonUtils.bindEditTextNtextDisposer(passport, passportDisposer); CommonUtils.bindEditTextNtextDisposer(sitename, sitenameDisposer); CommonUtils.bindEditTextNtextDisposer(phoneNum, phoneNumDisposer); CommonUtils.bindEditTextNtextDisposer(website, websiteDisposer); CommonUtils.bindEditTextNtextDisposer(identifyingCode, identifyingCodeDisposer); CommonUtils.bindEditTextNtextDisposer(ask, askDisposer); CommonUtils.bindEditTextNtextDisposer(answer, answerDisposer); CommonUtils.bindEditTextNtextDisposer(group, groupDisposer); } private void fillInfos() { mailBox.setText(content.getAsString(AccountColumns.MAILBOX)); password.setText(content.getAsString(AccountColumns.PASSWORD)); username.setText(content.getAsString(AccountColumns.USERNAME)); passport.setText(content.getAsString(AccountColumns.PASSPORT)); sitename.setText(content.getAsString(AccountColumns.SITENAME)); phoneNum.setText(content.getAsString(AccountColumns.PHONENUM)); website.setText(content.getAsString(AccountColumns.WEBSITE)); identifyingCode.setText(content .getAsString(AccountColumns.IDENTIFYING_CODE)); ask.setText(content.getAsString(AccountColumns.ASK)); answer.setText(content.getAsString(AccountColumns.ANSWER)); group.setText(content.getAsString(AccountColumns.GROUP)); } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); if (id == android.R.id.home) { backOperation(); return true; } else if (id == editButtonId) { CommonUtils.toggleFocusStatus(container, ableGroup, visibleGroup,textSequence); return true; } else return super.onOptionsItemSelected(item); } @Override public boolean onCreateOptionsMenu(Menu menu) { menu.add(0, editButtonId, 0, R.string.edit) .setIcon(android.R.drawable.ic_menu_edit) .setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS); return true; } @Override protected void onSaveInstanceState(Bundle outState) { outState.putBoolean("block", save.getVisibility()==View.GONE); if(picker!=null) picker.dismiss(); super.onSaveInstanceState(outState); } @Override protected void onRestoreInstanceState(Bundle savedInstanceState) { super.onRestoreInstanceState(savedInstanceState); if (savedInstanceState.getBoolean("block")) { CommonUtils.blockFocus(container, ableGroup, visibleGroup,textSequence); } else { CommonUtils.requetFocus(container, ableGroup,textSequence); } } @Override protected void onPause() { super.onPause(); if(pickerAdapter!=null) pickerAdapter.changeCursor(null); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if(keyCode==KeyEvent.KEYCODE_BACK){ backOperation(); return true; }else return super.onKeyDown(keyCode, event); } private void backOperation() { if(contentChanged) setResult(1); finish(); } }
/* * 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 witchinn; import environment.Actor; import environment.Velocity; import images.ResourceTools; import java.awt.Dimension; import java.awt.Image; import java.awt.Point; /** * * @author Shayla */ public class Cauldron extends Actor { private Dimension preferredSize; public static Image loadImage(String path) { return ResourceTools.loadImageFromResource(path); } { setImage(ResourceTools.loadImageFromResource("resources/EmptyC.PNG").getScaledInstance(400, 150, Image.SCALE_FAST)); } public Cauldron(Point position, Velocity velocity) { super(position, velocity); } private Image getScaledImage() { return super.getImage().getScaledInstance(preferredSize.width, preferredSize.height, Image.SCALE_FAST); } public Dimension getPreferredSize() { Dimension preferredSize = null; return preferredSize; } /** * @param preferredSize the preferredSize to set */ public void setPreferredSize(Dimension preferredSize) { this.preferredSize = preferredSize; } }
class ForLoop { public static void main(String[] args) { //String myVar = " Nothing "; StringBuilder sb = new StringBuilder(10); sb.append("Nothing"); System.out.println("sb:" + sb); //for (int i = 1; i <= 10; ++i) { //System.out.println("Line " + i); } } }
package comp1110.ass2.model; import java.util.ArrayList; import java.util.List; import java.util.UUID; /** * User: u6613739 * Date: 2019/5/4 * Time: 14:41 * Description: */ public class Player { /** * the uuid of player to identify player. */ private UUID id; /** * the player name */ public String playerName; /** * the round index. */ public int round = 0; /** * the player's board. */ private Board board = new Board(); /** * the player's boardString. */ private String boardString = ""; /** * the square player putted. * the element is a list which contains 3 String of placement :like A0B01,XXXXX,XXXXX */ private List<List<String>> roundPlacementList = new ArrayList<>(); /** * the number of used S tile */ public int usedSpeicalTile = 0; /** * player tpye: AI or HUMAN */ public EnumTypePlayer playerType ; /** * AI difficulty, only use in AI mode. */ private EnumTypeDifficulty difficulty ; /** * final score. */ private int finalScore; public EnumTypeDifficulty getDifficulty() { return difficulty; } public void setFinalScore(int finalScore) { this.finalScore = finalScore; } public int getFinalScore() { return this.finalScore; } public String getPlayerName(){ return playerName; } public Player(String playerName, String playerType, String difficulty) { id = UUID.randomUUID(); if (playerName.equals("")) { this.playerName = "default"; } else { this.playerName = playerName; } if (playerType.toUpperCase().equals("HUMAN")) { this.playerType = EnumTypePlayer.HUMAN; } else { this.playerType = EnumTypePlayer.AI; } switch (difficulty.toUpperCase()) { case "EASY": this.difficulty = EnumTypeDifficulty.EASY; break; case "HARD": this.difficulty = EnumTypeDifficulty.HARD; break; default: this.difficulty = EnumTypeDifficulty.EASY; break; } } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("id: "+id+"; playerName: "+playerName+"; playerType: "+playerType+"; difficulty: "+difficulty+" ; round: "+round+";"); return sb.toString(); } public String getBoardString() { return this.boardString; } public void appendBoardString(String placementString) { this.boardString += placementString; } public void setBoardString(String newBoardString) { this.boardString = newBoardString; } public Board getBoard() { return this.board; } public void setBoard(Board newBoard) { this.board = newBoard; } public String getPlayerType() { if (playerType == playerType.HUMAN) { return "Human"; } else return "AI"; } }
public class Hello { public static void main() { System.out.println("123321\n1234567"); } }
/** * Transaction Manager class handles input and output * @author Ben Plotnick * @author Michael Sherbine **/ import java.util.InputMismatchException; import java.util.Scanner; public class TransactionManager { AccountDatabase database = new AccountDatabase(); /** * method to run program */ public void run() { Scanner myObj = new Scanner(System.in); String input; // create Account Database System.out.println("Transaction processing starts....."); while (!((input = myObj.nextLine()).equals("Q"))) {// while user does not input "Q" keep listening for input String[] inputString = input.split("\\s+"); // split input string into array try { handleInput(inputString); } catch (Exception e) { System.out.println(e.getMessage()); } } System.out.println("Transaction processing complete."); myObj.close(); } /** * Handles input from user * @param input to be processed */ public void handleInput(String[] input) { String error = "Input data type mismatch"; String accountDoesNotExist = "Account does not exist"; String command = input[0]; if (command.equals("OC")) {// open Checking account if (input.length != 6 || (!(input[5].equalsIgnoreCase("true")) && !(input[5].equalsIgnoreCase("false")))) {//check if input is less than expected and if last word is a boolean throw new InputMismatchException(error); } checkAccountFormat(input); String[] date = input[4].split("/"); int month = Integer.parseInt(date[0]); int day = Integer.parseInt(date[1]); int year = Integer.parseInt(date[2]); Date openDate = new Date(year, month, day); double balance = Double.parseDouble(input[3]); Account account = new Checking(Boolean.parseBoolean(input[5]), openDate, balance, input[2], input[1]); Boolean added = database.add(account); if (!added) { System.out.println("Account already exists."); } else { System.out.println("Account opened and added to the database"); } } else if (command.equals("OS")) {//Open savings account if (input.length != 6 || (!(input[5].equalsIgnoreCase("true")) && !(input[5].equalsIgnoreCase("false")))) { throw new InputMismatchException(error); } checkAccountFormat(input); String[] date = input[4].split("/"); int month = Integer.parseInt(date[0]); int day = Integer.parseInt(date[1]); int year = Integer.parseInt(date[2]); Date openDate = new Date(year, month, day); double balance = Double.parseDouble(input[3]); Account account = new Savings(Boolean.parseBoolean(input[5]), openDate, balance, input[2], input[1]); Boolean added = database.add(account); if (!added) { System.out.println("Account already exists."); } else { System.out.println("Account opened and added to the database"); } } else if (command.equals("OM")) { // Open money market account if (input.length < 5) { throw new InputMismatchException(error); } checkAccountFormat(input); String[] date = input[4].split("/"); int month = Integer.parseInt(date[0]); int day = Integer.parseInt(date[1]); int year = Integer.parseInt(date[2]); Date openDate = new Date(year, month, day); double balance = Double.parseDouble(input[3]); Account account = new MoneyMarket(openDate, balance, input[2], input[1]); Boolean added = database.add(account); if (!added) { System.out.println("Account already exists."); } else { System.out.println("Account opened and added to the database"); } } else if (command.equals("CC")) { // Close checking account if (input.length < 3) { throw new InputMismatchException(error); } Account account = new Checking(input[1], input[2]); if (database.remove(account)) { System.out.println("Account closed and removed from database"); } else { System.out.println("Account does not exist"); } } else if (command.equals("CS")) {// close savings account if (input.length < 3) { throw new InputMismatchException(error); } Account account = new Savings(input[1], input[2]); if (database.remove(account)) { System.out.println("Account closed and removed from database"); } else { System.out.println("Account does not exist"); } } else if (command.equals("CM")) { //close money market account if (input.length < 5) { throw new InputMismatchException(error); } Account account = new MoneyMarket(input[1], input[2]); if (database.remove(account)) { System.out.println("Account closed and removed from database"); } else { System.out.println("Account does not exist"); } } else if (command.equals("DC")) { // Deposit to checking if (input.length < 4) { throw new InputMismatchException(error); } try { Double.parseDouble(input[3]); } catch (NumberFormatException e) { throw new NumberFormatException("Input data type mismatch"); } Account account = new Checking(input[1], input[2]); if (!database.deposit(account, Double.parseDouble(input[3]))) { System.out.println(accountDoesNotExist); } else { System.out.println(input[3] + " deposited to account"); } } else if (command.equals("DS")) { //deposit to savings account if (input.length < 4) { throw new InputMismatchException(error); } try { Double.parseDouble(input[3]); } catch (NumberFormatException e) { throw new NumberFormatException("Input data type mismatch"); } Account account = new Savings(input[1], input[2]); if (!database.deposit(account, Double.parseDouble(input[3]))) { System.out.println(accountDoesNotExist); } else { System.out.println(input[3] + " deposited to account"); } } else if (command.equals("DM")) { //deposit to money market account if (input.length < 4) { throw new InputMismatchException(error); } try { Double.parseDouble(input[3]); } catch (NumberFormatException e) { throw new NumberFormatException("Input data type mismatch"); } Account account = new MoneyMarket(input[1], input[2]); if (!database.deposit(account, Double.parseDouble(input[3]))) { System.out.println(accountDoesNotExist); } else { System.out.println(input[3] + " deposited to account"); } } else if (command.equals("WC")) {//withdraw from checking account if (input.length < 4) { throw new InputMismatchException(error); } try { Double.parseDouble(input[3]); } catch (NumberFormatException e) { throw new NumberFormatException("Input data type mismatch"); } Account account = new Checking(input[1], input[2]); int withdraw = database.withdrawal(account, Double.parseDouble(input[3])); if (withdraw == -1) { System.out.println(accountDoesNotExist); } else if (withdraw == 1) { System.out.println("Insufficient funds."); } else { System.out.println(input[3] + " withdrawn from account."); } } else if (command.equals("WS")) { // withdraw from savings account if (input.length < 4) { throw new InputMismatchException(error); } try { Double.parseDouble(input[3]); } catch (NumberFormatException e) { throw new NumberFormatException("Input data type mismatch"); } Account account = new Savings(input[1], input[2]); int withdraw = database.withdrawal(account, Double.parseDouble(input[3])); if (withdraw == -1) { System.out.println(accountDoesNotExist); } else if (withdraw == 1) { System.out.println("Insufficient funds."); } else { System.out.println(input[3] + " withdrawn from account."); } } else if (command.equals("WM")) { // withdraw from money market account if (input.length < 4) { throw new InputMismatchException(error); } try { Double.parseDouble(input[3]); } catch (NumberFormatException e) { throw new NumberFormatException("Input data type mismatch"); } Account account = new MoneyMarket(input[1], input[2]); int withdraw = database.withdrawal(account, Double.parseDouble(input[3])); if (withdraw == -1) { System.out.println(accountDoesNotExist); } else if (withdraw == 1) { System.out.println("Insufficient funds."); } else if (withdraw == 0) { System.out.println(input[3] + " withdrawn from account."); } } else if (command.equals("PA")) {//print all database.printAccounts(); } else if (command.equals("PD")) {//print by date database.printByDateOpen(); } else if (command.equals("PN")) { //print by name database.printByLastName(); } else { throw new InputMismatchException("Command " + "'" + command + "' not supported!"); // if command is not valid throw exception } } /** * checks if the input entered is valid when opening an account * @param input to be checked */ public void checkAccountFormat(String[] input) { try { Double.parseDouble(input[3]); String[] date = input[4].split("/"); int month = Integer.parseInt(date[0]); int day = Integer.parseInt(date[1]); int year = Integer.parseInt(date[2]); Date openDate = new Date(year, month, day); if (!openDate.isValid()) { throw new Exception(openDate.toString() + " is not a valid date!"); } } catch (NumberFormatException e) { throw new NumberFormatException("Input data type mismatch"); } catch (InputMismatchException e) { throw new InputMismatchException("test"); } catch (Exception e) { System.out.println(e.getMessage()); } } }
package example.com.stepsapp; import android.content.Context; import android.content.DialogInterface; import android.database.Cursor; import android.os.Bundle; import android.provider.BaseColumns; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.app.ListFragment; import android.support.v7.app.AlertDialog; import android.view.ContextMenu; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.EditText; import android.widget.ListAdapter; import android.widget.SimpleCursorAdapter; import android.widget.Spinner; import static example.com.stepsapp.DatabaseHelper.COL1; import static example.com.stepsapp.DatabaseHelper.COL2; import static example.com.stepsapp.DatabaseHelper.COL3; import static example.com.stepsapp.DatabaseHelper.COL4; import static example.com.stepsapp.DatabaseHelper.COL5; import static example.com.stepsapp.DatabaseHelper.COL6; import static example.com.stepsapp.DatabaseHelper.TABLE_NAME; public class ActivityHistoryFragment extends ListFragment { public ActivityHistoryFragment() { } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } private void updateLog() { Cursor constantsCursor = MainActivity.activityLog.rawQuery("SELECT " + BaseColumns._ID + ", " + COL1 + ", " + COL2 + ", " + COL3 + ", " + COL4 + ", " + COL5 + ", " + COL6 + " FROM " + TABLE_NAME + " ORDER BY " + COL2, null); ListAdapter adapter = new SimpleCursorAdapter(getContext(), R.layout.fragment_activity_history, constantsCursor, new String[] {COL1, COL2, COL3, COL4, COL5, COL6}, new int[]{R.id.list_activity_name, R.id.list_startTime, R.id.list_latitude, R.id.list_longtitude, R.id.list_duration, R.id.list_category}, 0); setListAdapter(adapter); registerForContextMenu(getListView()); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return super.onCreateView(inflater, container, savedInstanceState); } @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); updateLog(); } @Override public void onAttach(Context context) { super.onAttach(context); } @Override public void onDetach() { super.onDetach(); } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) { AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo; menu.setHeaderTitle("Activity edit"); String[] menuItems = {"Edit", "Delete"}; menu.add(Menu.NONE, 0, 0, menuItems[0]); menu.add(Menu.NONE, 1, 1, menuItems[1]); } @Override public boolean onContextItemSelected(MenuItem item) { AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo(); int idx = info.position; final Cursor activitiesHistoryCursor = MainActivity.activityLog.rawQuery("SELECT " + BaseColumns._ID + ", " + COL1 + ", " + COL2 + ", " + COL3 + ", " + COL4 + ", " + COL5 + ", " + COL6 + " FROM " + TABLE_NAME + " ORDER BY " + COL2, null); activitiesHistoryCursor.moveToFirst(); activitiesHistoryCursor.move(idx); int menuItemIdx = item.getItemId(); switch (menuItemIdx) { case 0: final View dialogView = getActivity().getLayoutInflater().inflate(R.layout.history_edit_dialog, null); final EditText editTextView = dialogView.findViewById(R.id.historyEditDialogNameField); final Spinner categorySpinner = dialogView.findViewById(R.id.historyEditDialogCategorySpinner); ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(getContext(), R.array.categories, android.R.layout.simple_spinner_item); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); categorySpinner.setAdapter(adapter); new AlertDialog.Builder(getContext()) .setTitle("Edit activity") .setView(dialogView) .setPositiveButton("OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { String[] stringCats = getResources().getStringArray(R.array.categories); MainActivity.activityLog.execSQL("UPDATE activity_table SET activity_name = \'" + editTextView.getText().toString() + "\', category = \'" + stringCats[categorySpinner.getSelectedItemPosition()] + "\' WHERE start_time LIKE \'" + activitiesHistoryCursor.getString(activitiesHistoryCursor.getColumnIndex(COL2)) + "\'"); updateLog(); } }) .setNegativeButton("Cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }) .show(); break; case 1: MainActivity.activityLog.execSQL("DELETE FROM " + TABLE_NAME + " WHERE " + COL2 + " = \'" + activitiesHistoryCursor.getString(activitiesHistoryCursor.getColumnIndex(COL2)) + "\'"); updateLog(); break; } return true; } }
/* ThemeProvider.java Purpose: Description: History: Thu Nov 1 14:22:12 2007, Created by tomyeh Copyright (C) 2007 Potix Corporation. All Rights Reserved. {{IS_RIGHT This program is distributed under LGPL Version 2.1 in the hope that it will be useful, but WITHOUT ANY WARRANTY. }}IS_RIGHT */ package org.zkoss.zk.ui.util; import java.util.Collection; import java.util.List; import org.zkoss.web.servlet.StyleSheet; import org.zkoss.zk.ui.Execution; import org.zkoss.zk.ui.sys.Attributes; /** * Used to replace the theme defined in the language definitions * (lang.xml and lang-addon.xml) and the configuration * (the <code>theme-uri</code> elements in web.xml). * * <p>When a desktop is about to be rendered, {@link #getThemeURIs} will * be called to allow developer to rename, add or remove CSS/WCS files. * * <p>When loading each WCS (Widget CSS descriptor) file (excluding CSS files), {@link #beforeWCS} * will be called to allow developer to rename or remove the WCS file. * * <p>When a WCS file is about to load the CSS file of a widget, * {@link #beforeWidgetCSS} will be called to allow developer to rename * or remove the CSS file associated with a widget. * * <p>To allow the client to cache the WCS file, you can inject a special * fragment into the URI of the WCS file such that a different URI represents * a different theme. To inject, you can use @{link Aide#injectURI} when * preprocessing URIs in {@link #getThemeURIs}. * Therefore, we can rertrieve the injected fragment in {@link #beforeWCS} * by use of {@link Aide#decodeURI}. * * @author tomyeh * @since 3.0.0 */ public interface ThemeProvider { /** Returns a list of the theme's URIs of the specified execution, * or null if no theme shall be generated. * Each item could be an instance of either {@link String} or {@link StyleSheet}. * If you want to specify the <code>media</code> attribute, use {@link StyleSheet}. * * <p>It is called when a desktop is about to be rendered. * It is called only once for each desktop. * * <p>Notice that {@link StyleSheet} is allowed since 5.0.3. * * @param exec the current execution (never null), where you can retrieve * the desktop, request and response. * Note: if your Web application supports multiple devices, you have * to check {@link org.zkoss.zk.ui.Desktop#getDevice}. * @param uris the default set of theme's URIs, * i.e., the themes defined in language definitions (lang.xml and lang-addon.xml) * and the configuration (the <code>theme-uri</code> elements in web.xml). * Each URI is an instance of of either {@link String} or {@link StyleSheet}. * Notice that, unless it is customized by application specific lang-addon, * all URIs are, by default, String instances. * @return the collection of the theme's URIs * that the current desktop shall use. * Each URI is an instance of of either {@link String} or {@link StyleSheet}. */ public Collection getThemeURIs(Execution exec, List uris); /** Returns the number of hours that the specified WCS * (Widget CSS descriptor) file won't be changed. * In other words, the client is allowed to cache the file until * the returned hours expires. * * @param uri the URI of the WCS file, e.g., ~./zul/css/zk.wcs * @return number of hours that the WCS file is allowed to cache. * If it is never changed until next ZK upgrade, you could return 8760 * (the default if ThemeProvider is not specified). * If you don't want the client to cache, return a nonpostive number. */ public int getWCSCacheControl(Execution exec, String uri); /** Called when a WCS (Widget CSS descriptor) file is about to be loaded. * This method then returns the real URI of the WCS file to load. * If no need to change, just return the <code>uri</code> parameter. * * <p>If you want to change the font size, you can set the attributes * of the execution accordingly as follows. * * <dl> * <dt>fontSizeM</dt> * <dd>The default font size. Default: 12px</dd> * <dt>fontSizeMS</dt> * <dd>The font size for menus. Default: 11px</dd> * <dt>fontSizeS</dt> * <dd>The font size for smaller fonts, such as toolbar. Default: 11px</dd> * <dt>fontSizeXS</dt> * <dd>The font size for extreme small fonts. Default 10px</dd> * <dt>fontFamilyT</dt> * <dd>The font family for titles. Default: arial, sans-serif</dd> * <dt>fontFamilyC</dt> * <dd>The font family for content. Default: arial, sans-serif</dd> * </dl> * * <p>For example, * <pre><code>String beforeWCS(Execution exec, String uri) { * exec.setAttribute("fontSizeM", "15px"); * return uri; *}</code></pre> * * @param exec the current executioin (never null), where you can retrieve * the request ad responsne. However, unlike * {@link #getThemeURIs}, the desktop might not be available when this * method is called. * @param uri the URI of the WCS file, e.g., ~./zul/css/zk.wcs * @return the real URI of the WCS file to load. * If null is returned, the WCS file is ignored. * @since 5.0.0 */ public String beforeWCS(Execution exec, String uri); /** Called when a WCS (Widget CSS descriptor) file is about to load the CSS file associated * with a widget. * This method then returns the real URI of the WCS file to load. * If no need to change, just return the <code>uri</code> parameter. * * <p>This method is usually overriden to load the CSS files from * a different directory. For example, * <pre><code>String beforeWidgetCSS(Execution exec, String uri) { * return uri.startsWith("~./") ? "~./foo/" + uri.substring(3): uri; *}</code></pre> * * @param exec the current executioin (never null), where you can retrieve * the request ad responsne. However, unlike * {@link #getThemeURIs}, the desktop might not be available when this * method is called. * @param uri the URI of the CSS file associated with a widget, e.g., * ~./js/zul/wgt/css/a.css.dsp * @return the real URI of the CSS file to load * If null is returned, the CSS file is ignored. * @since 5.0.0 */ public String beforeWidgetCSS(Execution exec, String uri); /** Utilties to help the implementation of {@link ThemeProvider} * to manipulate the URI such that it is able to use a different URI * for a different theme. */ public static class Aide { /** Injects a fragment into the specified URI, and returns * the injected URI. * @param uri the URI to be modified * @param fragment the fragment that will be injected <code>uri</code>. */ public static String injectURI(String uri, String fragment) { if (uri.startsWith("~./")) { //rename / to - for (int j = 0, k; (k = fragment.indexOf("/", j)) >= 0;) { fragment = fragment.substring(0, k) + '-' + fragment.substring(k + 1); j = k + 1; } return "~./" + Attributes.INJECT_URI_PREFIX + fragment + uri.substring(2); } return uri; } /** Decodes the injected URI and returns a two-element array. * The first element is the original URI, while the second * element is the fragment. * <p>Notice that it returns null if no injection is found. */ public static String[] decodeURI(String uri) { if (uri.startsWith("~./") && uri.substring(3).startsWith(Attributes.INJECT_URI_PREFIX)) { final int j = 3 + Attributes.INJECT_URI_PREFIX.length(), k = uri.indexOf('/', j); if (k > 0) return new String[] { "~./" + uri.substring(k + 1), uri.substring(j, k) }; } return null; } } }
package com.feng.UDP; import org.junit.Test; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; public class test1 { @Test public void sender() throws Exception { DatagramSocket ds = new DatagramSocket(); InetAddress ia = InetAddress.getByName("localhost"); String str = "今天是2021-06-13 11:16 今天晴天,很热"; byte[] bytes = str.getBytes(); DatagramPacket datagramPacket = new DatagramPacket(bytes,0,bytes.length,ia,9090); ds.send(datagramPacket); ds.close(); } @Test public void receiver() throws Exception { DatagramSocket datagramSocket = new DatagramSocket(9090); byte[] buffer = new byte[100]; DatagramPacket datagramPacket = new DatagramPacket(buffer,0,buffer.length); datagramSocket.receive(datagramPacket); System.out.println(new String(datagramPacket.getData(),0,datagramPacket.getLength())); } }
package com.shiro.controller; import javax.servlet.http.HttpServletRequest; import org.apache.shiro.SecurityUtils; import org.apache.shiro.authc.AuthenticationException; import org.apache.shiro.authc.UsernamePasswordToken; import org.apache.shiro.authz.annotation.RequiresRoles; import org.apache.shiro.subject.Subject; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; @Controller public class LoginController { @RequestMapping("goLogin.html") public String goLogin(){ return "login"; } @RequestMapping("login.html") public String login(String username,String password,HttpServletRequest request){ Subject subject = SecurityUtils.getSubject(); UsernamePasswordToken token = new UsernamePasswordToken(username,password); try { subject.login(token); return "redirect:index.html"; } catch (AuthenticationException e) { e.printStackTrace(); request.setAttribute("error", "用户名或者密码错误"); return "login"; } } @RequestMapping("/logout.html") public String logout(){ Subject subject = SecurityUtils.getSubject(); subject.logout(); return "login"; } }
package br.com.sgcraft.listeners; import org.bukkit.Material; import org.bukkit.entity.EntityType; import org.bukkit.entity.Slime; import org.bukkit.entity.Zombie; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.entity.CreatureSpawnEvent; import org.bukkit.event.entity.EntityDeathEvent; public class MobsFix implements Listener{ @EventHandler public void onCreatureSpawn(CreatureSpawnEvent event) { if (event.getEntity().getType() == EntityType.ZOMBIE) { Zombie zombie = (Zombie) event.getEntity(); if(zombie.isBaby()) { event.setCancelled(true); zombie.setBaby(false); } } } @EventHandler public void onCreatureSpawn2(CreatureSpawnEvent event) { if (event.getEntity().getType() == EntityType.PIG_ZOMBIE) { Zombie zombie_pig = (Zombie) event.getEntity(); if(zombie_pig.isBaby()) { event.setCancelled(true); zombie_pig.setBaby(false); } } } @EventHandler public void onSpawn(final CreatureSpawnEvent e) { if (e.getEntityType() == EntityType.SLIME) { final Slime slime = (Slime)e.getEntity(); slime.setSize(1); } } @EventHandler public void onZombiePigmanDead(final EntityDeathEvent e) { if (e.getEntity().getType() != EntityType.PIG_ZOMBIE) { return; } e.getDrops().removeIf(is -> is.getType() == Material.GOLD_SWORD); e.getDrops().removeIf(is -> is.getType() == Material.GOLD_INGOT); } }
package com.example.prog3.alkasaffollowup.SqliTe; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; public class DbUtil extends SQLiteOpenHelper { public DbUtil(Context context) { super(context, Data.Db_Name, null, Data.Db_Version); } @Override public void onCreate(SQLiteDatabase db) { String sql="create table "+Data.Db_Table+" ( "+ Data.Key_ProjName+" text , "+Data.Key_ProjRef+" text , "+ Data.Key_Sn+" text ) "; db.execSQL(sql); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { String sql="drop table "+Data.Db_Table; db.execSQL(sql); onCreate(db); } }
package com.jd.jarvisdemonim.ui.testadapteractivity; import android.animation.Animator; import android.animation.ObjectAnimator; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.View; import android.widget.TextView; import com.jd.jarvisdemonim.R; import com.jd.jarvisdemonim.base.BaseActivity; import com.jd.jdkit.elementkit.utils.system.DateFormatUtils; import com.jd.jdkit.elementkit.utils.system.ScreenUtils; import com.jd.myadapterlib.common.RecyCarlendarAdapter; import java.util.Date; import butterknife.Bind; /** * Auther: Jarvis Dong * Time: on 2017/1/16 0016 * Name: * OverView:自定义适配器实现日历; * Usage: 使用view的包装类; */ public class NormalTestCalendarAdapterActivity extends BaseActivity { @Bind(R.id.recyclerview_date) RecyclerView mRecyData; @Bind(R.id.tv_date_selected) TextView mDisplay; ViewWrapper wrapper; GridLayoutManager glm; RecyCarlendarAdapter mCarAdapter; private boolean isAll = true; Handler handler = new Handler() { @Override public void handleMessage(Message msg) { super.handleMessage(msg); mRecyData.scrollBy(0, msg.arg1); } }; @Override public int getContentViewId() { return R.layout.activity_date_test; } @Override protected void initView(Bundle savedInstanceState) { wrapper = new ViewWrapper(mRecyData); mCarAdapter = new RecyCarlendarAdapter(mRecyData, R.layout.calendar_item); glm = new GridLayoutManager(this, 7); } @Override protected void initVariable() { mRecyData.setHasFixedSize(true); mRecyData.setLayoutManager(glm); mRecyData.setAdapter(mCarAdapter); } @Override protected void processLogic(Bundle savedInstanceState) { mDisplay.setText(DateFormatUtils.long2StringByYYYYMD(new Date().getTime())); mCarAdapter.chooseTime(new Date().getTime(), 1); mCarAdapter.setOnCalendarItemClickListener(new RecyCarlendarAdapter.OnCalendarItemClickListener() { @Override public void calendarItem(int pos, long time, RecyCarlendarAdapter.DateState state, View view) { if (isAll) { doZoomDown(pos ,time ,view); } else { doZoomUp(pos ,time ,view); } isAll = !isAll; } }); } private void doZoomUp(final int pos, long time, View view) { mRecyData.smoothScrollToPosition(pos); ObjectAnimator anim = ObjectAnimator.ofInt(wrapper, "Height", ScreenUtils.dpToPx(50), ScreenUtils.dpToPx(250)); anim.setDuration(300); // anim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { // @Override // public void onAnimationUpdate(ValueAnimator animation) { // // } // }); anim.addListener(new Animator.AnimatorListener() { @Override public void onAnimationStart(Animator animation) { } @Override public void onAnimationEnd(Animator animation) { mRecyData.smoothScrollToPosition(pos); } @Override public void onAnimationCancel(Animator animation) { } @Override public void onAnimationRepeat(Animator animation) { } }); anim.start(); } private void doZoomDown(final int pos, long time, View view) { if (mCarAdapter.chooseTime(time, 1)) { mDisplay.setText(DateFormatUtils.long2StringByYYYYMD(time)); } int[] location1 = new int[2]; int[] location2 = new int[2]; view.getLocationOnScreen(location1); final int y = location1[1];//点击itemview的y方向位置; mRecyData.getLocationOnScreen(location2); final int yy = location2[1];//recyclerview的y方向位置; new Thread(new Runnable() { @Override public void run() { for (int i = 0; i < 50; i++) { Message msg = new Message(); msg.arg1 = (y - yy) / 50; // recyclerviewDate.smoothScrollBy(0,(y-yy)/10); handler.sendMessage(msg); try { Thread.sleep(15); } catch (InterruptedException e) { e.printStackTrace(); } } } }).start(); ObjectAnimator anim = ObjectAnimator.ofInt(wrapper, "Height", ScreenUtils.dpToPx(250), ScreenUtils.dpToPx(50)); anim.setDuration(1000); anim.addListener(new Animator.AnimatorListener() { @Override public void onAnimationStart(Animator animation) { } @Override public void onAnimationEnd(Animator animation) { mRecyData.smoothScrollToPosition(pos); } @Override public void onAnimationCancel(Animator animation) { } @Override public void onAnimationRepeat(Animator animation) { } }); anim.start(); } /** * view的包装类; * 其实就是属性动画: * 解决方法: * 1.加get,set; * 2.用一个类包装原始对象,间接为其提供get,set方法; * 3.采用valueAnimator,监听动画过程实现属性的改变; */ private class ViewWrapper { private View mTargetView; public ViewWrapper(View mTargetView) { this.mTargetView = mTargetView; } public int getHeight() { return mTargetView.getLayoutParams().height; } public void setHeight(int height) { mTargetView.getLayoutParams().height = height; mTargetView.requestLayout(); } } }
package com.example; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = TryconcourseApplication.class) @WebAppConfiguration public class TryconcourseApplicationTests { @Autowired MyService myService; @Test public void unitTest() { org.junit.Assert.assertEquals("hi", myService.greeting()); } }
package com.zxt.compplatform.authority.service; import java.util.List; import java.util.Map; import com.zxt.compplatform.authority.entity.FieldGrant; public interface FieldGrantService { /** * 执行添加操作 * */ public void addFieldGrant(FieldGrant fieldGrant); /** * 根据 角色RID,删除该角色所有操作 * @param id */ public void deleteFieldGrant(Long rid); /** * 根据角色ID,得到其所有表名和字段 * @param id */ public List getAllByRid(Long rid); /** * 根据角色ID,得到其所属表名称 * select tableName from T_FIELD_GRANT where rid=2 group by tableName * 如果flag==0时,则让其查所有表名称。rid不起作用。如果是其它,flag不起作用 */ public List getTableNameByRid(Long rid,int flag); /** * 根据角色ID,和表名,得到其所有表名和字段 * @param id * select * from T_FIELD_GRANT where RID='55' AND tableName='LS_PUTBIOLOGY' */ public List getAllByRidAndTableName(Long rid,String tableName); /** * 加载 cache * GUOWEIXIN * @param url * @return */ public Map<Long,Map> load_service(Long rid); /** * 更新 cache * GUOWEIXIN * @param url * @return */ public Map<Long,Map> update_service(Long rid); }
package m2cci.pi01.cybertheatre.ctrlers; import org.springframework.web.bind.annotation.RestController; import java.nio.file.Paths; import java.util.HashMap; import java.util.Map; import static spark.Spark.post; import static spark.Spark.port; import static spark.Spark.staticFiles; import com.google.gson.Gson; import com.stripe.Stripe; import com.stripe.model.checkout.Session; import com.stripe.param.checkout.SessionCreateParams; /** * * @author Ltifi */ @RestController public class PaymentController { /*@PostMapping("/create-payment-intent") public void createPaymentIntent() { response.type("application/json"); CreatePayment postBody = gson.fromJson(request.body(), CreatePayment.class); PaymentIntentCreateParams createParams = new PaymentIntentCreateParams.Builder().setCurrency("usd").setAmmount(new Long(calculateOrderAmmount(postBody.getItems()))).build(); PaymentIntent intent =PaymentIntent.create(createParams); createPaymentResponse = new CreatePaymentResponse(intent.getClientSecret()); return gson.toJson(paymentResponse); }*/ private static Gson gson = new Gson(); public static void main(String[] args) { port(4242); // This is your real test secret API key. Stripe.apiKey = "pk_test_51J6CxVCkLlQznzQ3cygztskZ6BeFfvFYHpGTQf1Vz6d2ss5tva7EXESfwdyAbUPWAbDnadPXQsPZPKa23lgrs5BL004oz9QErh"; staticFiles.externalLocation( Paths.get("").toAbsolutePath().toString()); post("/create-checkout-session", (request, response) -> { response.type("application/json"); final String YOUR_DOMAIN = "http://localhost:4242"; SessionCreateParams params = SessionCreateParams.builder() .addPaymentMethodType(SessionCreateParams.PaymentMethodType.CARD) .setMode(SessionCreateParams.Mode.PAYMENT) .setSuccessUrl(YOUR_DOMAIN + "/success.html") .setCancelUrl(YOUR_DOMAIN + "/cancel.html") .addLineItem( SessionCreateParams.LineItem.builder() .setQuantity(1L) .setPriceData( SessionCreateParams.LineItem.PriceData.builder() .setCurrency("usd") .setUnitAmount(2000L) .setProductData( SessionCreateParams.LineItem.PriceData.ProductData.builder() .setName("Stubborn Attachments") .build()) .build()) .build()) .build(); Session session = Session.create(params); HashMap<String, String> responseData = new HashMap<String, String>(); responseData.put("id", session.getId()); return gson.toJson(responseData); }); } }
package com.zzping.fix.model; import com.zzping.fix.util.Constant; public class FixCampusModel { private String campus; private String campusPlace; private String finalCampusPlaceName; private String campusPlaceNo; public String getCampus() { return campus; } public void setCampus(String campus) { this.campus = campus; } public String getCampusPlace() { return campusPlace; } public void setCampusPlace(String campusPlace) { this.campusPlace = campusPlace; } public String getFinalCampusPlaceName() { String campusStr ; if(campus.equals(Constant.松山湖校区)){ campusStr = "松山湖校区"; }else{ campusStr = "莞城校区"; } return campusStr+" "+campusPlace; } public void setFinalCampusPlaceName(String finalCampusPlaceName) { this.finalCampusPlaceName = finalCampusPlaceName; } public String getCampusPlaceNo() { return campusPlaceNo; } public void setCampusPlaceNo(String campusPlaceNo) { this.campusPlaceNo = campusPlaceNo; } }
package com.jgw.supercodeplatform.trace.service.tracefun; import com.alibaba.fastjson.JSONObject; import com.jgw.supercodeplatform.exception.SuperCodeException; import com.jgw.supercodeplatform.trace.common.util.CommonUtil; import com.jgw.supercodeplatform.trace.config.es.IndexAndType; import com.jgw.supercodeplatform.trace.dao.mapper1.tracefun.TraceBatchRelationMapper; import com.jgw.supercodeplatform.trace.pojo.tracefun.TraceBatchRelation; import org.apache.ibatis.annotations.Param; import org.elasticsearch.action.index.IndexResponse; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.action.search.SearchType; import org.elasticsearch.client.transport.TransportClient; import org.elasticsearch.index.query.QueryBuilder; import org.elasticsearch.index.query.QueryBuilders; import org.elasticsearch.rest.RestStatus; import org.elasticsearch.search.SearchHit; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.core.task.TaskExecutor; import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.List; import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder; /** * ElasticSearch中的批次关联关系数据管理 * * @author wzq * @date: 2019-03-28 */ @Service public class TraceBatchRelationEsService extends CommonUtil { @Autowired private TransportClient eClient; @Autowired private ThreadPoolTaskExecutor taskExecutor; @Autowired private TraceBatchRelationMapper traceBatchRelationMapper; private static Logger logger= LoggerFactory.getLogger(TraceBatchRelationEsService.class); @Value("${elastic.enable}") private boolean enableElastic; /** * 新增批次关联数据,同时异步写入ElasticSearch * @param traceBatchRelation * @throws Exception */ public void insertTraceBatchRelation(TraceBatchRelation traceBatchRelation) throws Exception { traceBatchRelation.setSysId(getSysId()); traceBatchRelationMapper.insertTraceBatchRelation(traceBatchRelation); if(enableElastic){ taskExecutor.execute(()->{ try{ insertTraceBatchRelationToEs(traceBatchRelation); }catch (Exception e){ logger.error("批次关系写入es失败",e); e.printStackTrace(); } }); } } /** * 批次关联数据写入ElasticSearch * @param traceBatchRelation * @throws Exception */ private void insertTraceBatchRelationToEs(TraceBatchRelation traceBatchRelation) throws Exception{ IndexResponse indexResponse=eClient.prepareIndex(IndexAndType.TRACE_INDEX,IndexAndType.TRACE_BATCHRELATION_TYPE).setSource( jsonBuilder().startObject() .field("batchRelationId",traceBatchRelation.getBatchRelationId()) .field("currentBatchId",traceBatchRelation.getCurrentBatchId()) .field("parentBatchId",traceBatchRelation.getParentBatchId()) .field("createDate",traceBatchRelation.getCreateDate()) .field("updateDate",traceBatchRelation.getUpdateDate()) .field("currentBatchType",traceBatchRelation.getCurrentBatchType()) .field("parentBatchType",traceBatchRelation.getParentBatchType()) .endObject() ).get(); if(indexResponse.status().getStatus() != RestStatus.CREATED.getStatus()){ throw new SuperCodeException("新增装箱流水es记录失败"); } } /** * 根据批次Id从ElasticSearch中查询批次关联数据 * @param batchId * @return */ public List<TraceBatchRelation> selectByBatchId(String batchId){ if(enableElastic){ SearchResponse response=eClient.prepareSearch(IndexAndType.TRACE_INDEX) .setSearchType(SearchType.DFS_QUERY_THEN_FETCH) .setTypes(IndexAndType.TRACE_BATCHRELATION_TYPE) .setQuery(QueryBuilders.boolQuery() .must(QueryBuilders.termQuery("currentBatchId.keyword",batchId)) ).get(); SearchHit[] hits=response.getHits().getHits(); List<TraceBatchRelation> traceBatchRelations=new ArrayList<TraceBatchRelation>() ; for(SearchHit searchHit:hits){ TraceBatchRelation traceBatchRelation= JSONObject.parseObject(JSONObject.toJSONString(searchHit.getSourceAsMap()),TraceBatchRelation.class); traceBatchRelations.add(traceBatchRelation); } return traceBatchRelations; } return null; } }
package quiz02; public class Calculator { //method // 1. 결과타입 : 결과값이 없다. (void) // 2. 메소드명 : addtion // 3. 매개변수 : 전달되는 2개의 int 값이 있다. // 4. 역할 : 전달된 인수의 합계 결과를 아래와 같은 형식으로 벼웝니다. // 1 + 2 = 3 void addition(int a, int b) { System.out.println(a + "+" + b + "=" + (a+ b)); } // 1. 결과타입 : 결과값의 타입이 int입니다. // 2. 메소드명 : subtraction // 3. 매개변수 : 전될되는 2개의 int값이 있다. // 4. 역할 :전달된 인수의 뺄셈 결과를 반환합니다. //다만, 항상 큰 수에서 작은 수를 뺍니다. int subtraction(int a, int b) { return (a >= b ? a-b : b-a);} }//return과 int는 거의 세트 /*if(c<d) { System.out.println(d - c); }else { System.out.println(c- d); } }*/
package com.cedo.cat2shop.config; import com.baomidou.mybatisplus.core.injector.AbstractMethod; import com.baomidou.mybatisplus.core.injector.AbstractSqlInjector; import com.baomidou.mybatisplus.core.injector.methods.*; import com.baomidou.mybatisplus.extension.injector.methods.additional.InsertBatchSomeColumn; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; /** * mybatis plus sql注入器 * @Author chendong * @date 19-3-1 下午3:25 */ public class MybatisPlusSqlInjector extends AbstractSqlInjector { @Override public List<AbstractMethod> getMethodList() { return Stream.of( new Insert(), new InsertBatchSomeColumn(t -> true), new Delete(), new DeleteById(), new Update(), new UpdateById(), new UpdateAllColumnById(), new SelectById(), new SelectCount(), new SelectObjs(), new SelectList(), new SelectPage(), new SelectOne() ).collect(Collectors.toList()); } }
import interfaces.TFFreqs; import interfaces.TFWords; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.InvocationTargetException; import java.util.*; public class Nineteen{ static String wordsPluginPath; static String freqPluginPath; public static void loadPlugins() { Properties config = new Properties(); InputStream fileInputStream = null; try { fileInputStream = new FileInputStream("./config.properties"); config.load(fileInputStream); wordsPluginPath = config.getProperty("words"); freqPluginPath = config.getProperty("frequencies"); } catch (IOException ex) { ex.printStackTrace(); } finally { if (fileInputStream != null) { try { fileInputStream.close(); } catch (IOException e) { e.printStackTrace(); } } } } public static void main(String args[]) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException, IOException { loadPlugins(); ArrayList<Map.Entry<String, Integer>> wordFreqs = new ArrayList<Map.Entry<String, Integer>>(); TFWords tfwords = (TFWords) Class.forName(wordsPluginPath).getDeclaredConstructor().newInstance(); TFFreqs tffreqs = (TFFreqs) Class.forName(freqPluginPath).getDeclaredConstructor().newInstance(); wordFreqs = tffreqs.top25(tfwords.extractWords(args[0])); for(Map.Entry<String, Integer> entry : wordFreqs.subList(0, 25)) { System.out.println(entry.getKey() + " - " + entry.getValue()); } } }
import java.io.IOException; import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Mapper; public class Map extends Mapper<LongWritable, Text, Text, IntWritable>{ private Text key = new Text(); private static IntWritable one = new IntWritable(1); public void map(LongWritable Key, Text Value,Context context) throws IOException, InterruptedException { String line = Value.toString(); for(int i=0;i<line.length();i++) { key.set(Character.toString(line.charAt(i))); context.write(key, one); } } }
package thread;/** * Created by DELL on 2018/8/17. */ /** * user is **/ public class test { }
package fr.epsi.b3.gostyle.service; import static org.junit.Assert.*; import org.junit.Test; import org.mockito.Mockito; import fr.epsi.b3.gostyle.model.Qrcode; import fr.epsi.b3.gostyle.exception.QrcodeNotFoundException; public class QrcodeServiceTest { @Test public void recuperationDUnQrcodeParSonId() throws Exception { Integer id = 1; QrcodeService qrcodeService = Mockito.mock(QrcodeService.class); Qrcode qrcode = new Qrcode(); qrcode.setLibelle("test"); qrcode.setMontant(15); Mockito.when(qrcodeService.find(1)).thenReturn(qrcode); Qrcode result = qrcodeService.find(id); assertEquals(1,result.getID()); Mockito.verify(qrcodeService).find(1); } @Test(expected= QrcodeNotFoundException.class) public void tentativeRecuperationDUnQrcodeQuiNExistePas() throws QrcodeNotFoundException { Integer id = 78; QrcodeService qrcodeService = Mockito.mock(QrcodeService.class); Mockito.when(qrcodeService.find(78)).thenThrow(QrcodeNotFoundException.class); Qrcode qrcode = qrcodeService.find(id); fail("QrcodeNotFoundException expected"); } }
package com.example.administrator.cookman.ui.adapter; import android.content.Context; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import com.example.administrator.cookman.R; import com.example.administrator.cookman.model.entity.CookEntity.CategoryChildInfo2; import com.example.administrator.cookman.model.entity.CookEntity.CategoryInfo; import java.util.ArrayList; import java.util.List; import butterknife.Bind; /** * Created by Administrator on 2017/2/25. */ public class CookCategorySndAdapter extends BaseRecyclerAdapter<CookCategorySndAdapter.CookCategorySndStruct>{ public CookCategorySndAdapter(OnCookCategorySndListener onCookCategorySndListener){ this.onCookCategorySndListener = onCookCategorySndListener; } @Override public CommonHolder<CookCategorySndStruct> setViewHolder(ViewGroup parent) { return new CookCategoryFirHolder(parent.getContext(), parent); } class CookCategoryFirHolder extends CommonHolder<CookCategorySndStruct>{ @Bind(R.id.btn_tag_1) public Button btnTag1; @Bind(R.id.btn_tag_2) public Button btnTag2; @Bind(R.id.btn_tag_3) public Button btnTag3; public CookCategoryFirHolder(Context context, ViewGroup root) { super(context, root, R.layout.item_cook_category_snd); } @Override public void bindData(final CookCategorySndStruct cook){ if(cook.data1 != null){ btnTag1.setVisibility(View.VISIBLE); btnTag1.setText(cook.data1.getName()); if(cook.isSelect == 1) btnTag1.setSelected(true); else btnTag1.setSelected(false); btnTag1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(onCookCategorySndListener != null){ updateSelection(cook, 1); onCookCategorySndListener.onCookCategorySndClick(cook.data1.getCtgId(), cook.data1.getName()); } } }); if(cook.data2 == null){ btnTag2.setVisibility(View.GONE); btnTag3.setVisibility(View.GONE); return ; } btnTag2.setVisibility(View.VISIBLE); btnTag2.setText(cook.data2.getName()); if(cook.isSelect == 2) btnTag2.setSelected(true); else btnTag2.setSelected(false); btnTag2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { updateSelection(cook, 2); if(onCookCategorySndListener != null){ onCookCategorySndListener.onCookCategorySndClick(cook.data2.getCtgId(), cook.data2.getName()); } } }); if(cook.data3 == null){ btnTag3.setVisibility(View.GONE); return ; } btnTag3.setVisibility(View.VISIBLE); btnTag3.setText(cook.data3.getName()); if(cook.isSelect == 3) btnTag3.setSelected(true); else btnTag3.setSelected(false); btnTag3.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { updateSelection(cook, 3); if(onCookCategorySndListener != null){ onCookCategorySndListener.onCookCategorySndClick(cook.data3.getCtgId(), cook.data3.getName()); } } }); } } } private CookCategorySndStruct oldCook; private void updateSelection(CookCategorySndStruct newCook, int position){ if(oldCook != null) oldCook.isSelect = 0; newCook.isSelect = position; oldCook = newCook; notifyDataSetChanged(); } public static class CookCategorySndStruct{ public CategoryInfo data1; public CategoryInfo data2; public CategoryInfo data3; public int isSelect = 0; public CookCategorySndStruct(){ } public CookCategorySndStruct(CategoryInfo data1, CategoryInfo data2, CategoryInfo data3){ this.data1 = data1; this.data2 = data2; this.data3 = data3; this.isSelect = 0; } public void add(CategoryInfo data){ if(null == data1) { data1 = data; return ; } if(null == data2) { data2 = data; return ; } if(null == data3) { data3 = data; return ; } } } private OnCookCategorySndListener onCookCategorySndListener; public interface OnCookCategorySndListener{ public void onCookCategorySndClick(String ctgId, String name); } public static List<CookCategorySndStruct> createDatas(ArrayList<CategoryChildInfo2> datas){ List<CookCategorySndStruct> dstDatas = new ArrayList<>(); int size = datas.size(); int shi = size / 3; int ge = size % 3; if(0 == shi){ if(0 == ge) return dstDatas; CookCategorySndStruct item = new CookCategorySndStruct(); for(int i = 0; i < ge; i++) item.add(datas.get(i).getCategoryInfo()); dstDatas.add(item); return dstDatas; } int index = 0; for(int i = 0; i < shi; i++){ CookCategorySndStruct item = new CookCategorySndStruct( datas.get(index).getCategoryInfo(), datas.get(index + 1).getCategoryInfo(), datas.get(index + 2).getCategoryInfo() ); dstDatas.add(item); index += 3; } if(0 == ge) return dstDatas; CookCategorySndStruct item = new CookCategorySndStruct(); for(int i = 0; i < ge; i++) item.add(datas.get(index + i).getCategoryInfo()); dstDatas.add(item); return dstDatas; } }
package com.vvv.kodilan.service; import com.vvv.kodilan.view.pub.TagView; public interface ITagService { TagView getPublicTagView(Integer page); }
/** * */ package nnets; import java.awt.BorderLayout; import java.awt.Color; import java.awt.EventQueue; import java.util.ArrayList; import javax.swing.JFrame; import org.jfree.chart.ChartFactory; import org.jfree.chart.ChartPanel; import org.jfree.chart.JFreeChart; import org.jfree.chart.axis.NumberAxis; import org.jfree.chart.axis.NumberTickUnit; import org.jfree.chart.plot.PlotOrientation; import org.jfree.chart.plot.XYPlot; import org.jfree.chart.renderer.xy.XYItemRenderer; import org.jfree.data.xy.XYDataset; import org.jfree.data.xy.XYSeries; import org.jfree.data.xy.XYSeriesCollection; /** * @author I.C Ricardo Alfredo Macias Olvera - TIJUANA * * - Clustering using SNN * -It uses 2 groups with Gaussian distribution with zero as mean * Each group has 8 Random - values * -It uses a method to learn in a supervised way with * axonal delays. The weights are equals to 1 * * -Out classes : 2 * -Codification : Linear with one neuron as a reference * -Receptive Fields : 0 * -Type of Synapses : simples */ public class SimpleClusterV2 extends JFrame{ private static final long serialVersionUID = 1L; /** * @param args */ private static final int NUM_CLUSTERS = 2; private static final double[][] SAMPLES = { { (Math.random()*((10.0-1.0)+1))+ 1.0, (Math.random()*((10.0-1.0)+1))+ 1.0 }, { (Math.random()*((10.0-1.0)+1))+ 1.0, (Math.random()*((10.0-1.0)+1))+ 1.0 }, { (Math.random()*((10.0-1.0)+1))+ 1.0, (Math.random()*((10.0-1.0)+1))+ 1.0 }, { (Math.random()*((10.0-1.0)+1))+ 1.0, (Math.random()*((10.0-1.0)+1))+ 1.0 }, { (Math.random()*((10.0-1.0)+1))+ 1.0, (Math.random()*((10.0-1.0)+1))+ 1.0 }, { (Math.random()*((10.0-1.0)+1))+ 1.0, (Math.random()*((10.0-1.0)+1))+ 1.0 }, { (Math.random()*((10.0-1.0)+1))+ 1.0, (Math.random()*((10.0-1.0)+1))+ 1.0 }, { (Math.random()*((10.0-1.0)+1))+ 1.0, (Math.random()*((10.0-1.0)+1))+ 1.0 } }; private static final int TOTAL_DATA = SAMPLES.length; //Total Data static double[][] N_SAMPLES = null; private static ArrayList<Data> dataSet = new ArrayList<Data>(); static ArrayList<DataA> dataSetAumented = null; static int tam; // number of points static int in_neu; // number of input neurons static int out_neu; // number of output neurons static double rho; // time static double tau; // Time EPSP static int maxd; // encoded interval static int tmax; // max interval static double teta; private static final String title = "Simple Cluster SNN"; XYSeriesCollection xySeriesCollection = new XYSeriesCollection(); //XYSeries Delays = new XYSeries("DelaysData"); XYSeries Class_A_Added = new XYSeries("Class_A"); XYSeries Class_B_Added = new XYSeries("Class_B"); public SimpleClusterV2(String title) { final ChartPanel chart_Delay_Panel = createDelayPanel(); this.add(chart_Delay_Panel, BorderLayout.CENTER); } private ChartPanel createDelayPanel() { JFreeChart jfreechart = ChartFactory.createScatterPlot( title, "X", "Y", createDelayData(), PlotOrientation.VERTICAL, true, true, false); XYPlot xyPlot = (XYPlot) jfreechart.getPlot(); xyPlot.setDomainCrosshairVisible(true); xyPlot.setRangeCrosshairVisible(true); XYItemRenderer renderer = xyPlot.getRenderer(); renderer.setSeriesPaint(0, Color.blue); NumberAxis domain = (NumberAxis) xyPlot.getDomainAxis(); domain.setRange(0.00, 1.00); domain.setTickUnit(new NumberTickUnit(0.1)); domain.setVerticalTickLabels(true); NumberAxis rangep = (NumberAxis) xyPlot.getRangeAxis(); rangep.setRange(0.0, 1.0); rangep.setTickUnit(new NumberTickUnit(0.1)); return new ChartPanel(jfreechart); } private XYDataset createDelayData() { // Print out clustering results. for(int i = 0; i < NUM_CLUSTERS; i++) { for(int j = 0; j < TOTAL_DATA; j++) { if(dataSetAumented.get(j).cluster() == i){ if (i ==0) { Class_A_Added.add(dataSetAumented.get(j).X(), dataSetAumented.get(j).Y()); } if (i ==1) { Class_B_Added.add(dataSetAumented.get(j).X(), dataSetAumented.get(j).Y()); } } } // j System.out.println(); } // i xySeriesCollection.addSeries(Class_A_Added); xySeriesCollection.addSeries(Class_B_Added); return xySeriesCollection; } public static void Initialize() { tam = SAMPLES.length; in_neu = SAMPLES[0].length + 1; out_neu = 2; rho = 0.1; tau = 1.84; maxd = 10; tmax = 6; teta = 1.5; } public static void Training() { int tra = 2; int trb = (tam / 2) + tra; double ca, cb; ArrayList<Data> aus = kodieren_ln(); // encoding inputs double sum = 0; for (int i = 0; i < tra; i++) { sum = sum + (aus.get(i).X() + aus.get(i).Y()); } System.out.println(" sum -> "+ sum); ca = Math.round(((sum / tra) / rho) * rho); // means of class 1 System.out.println("\n ca -> " + ca); System.out.println("trb -> " + trb); sum = 0; // change here for (int i = tra +1; i < trb; i++) { sum = sum + (aus.get(i).X() + aus.get(i).Y()); } cb = Math.round(((sum / tra) / rho) * rho); // means of class 2 System.out.println("\n cb -> " + cb); double[] d = { maxd - ca, maxd - cb, maxd - maxd }; for (int i = 0; i < d.length; i++) { System.out.println(" d[ " + i + " ] -> " + d[i]); } double[] w = { 1, 1, 1 }; int sampleNumber = 0; dataSetAumented = new ArrayList<DataA>(); DataA newData = null; System.out.println(" aus.size() -> " + aus.size()); while (dataSetAumented.size() < TOTAL_DATA) { newData = new DataA(N_SAMPLES[sampleNumber][0], N_SAMPLES[sampleNumber][1], 1 *maxd); dataSetAumented.add(newData); sampleNumber++; } System.out.println("\n dataSetAumented " + dataSetAumented.size() + " tam-> " + tam + "\n"); for (int j = 0; j < dataSetAumented.size(); j++) System.out.println("X -> " + dataSetAumented.get(j).X() + " Y -> " + dataSetAumented.get(j).Y() + " Z -> " + dataSetAumented.get(j).Z()); double dt = 0, sai = 0; double t = 0; double[] out = null; // new double[out_neu]; int neu=0; for (int k = 0; k < dataSetAumented.size(); k++) { t = 0; neu=0; while ( neu == 0 && t <= tmax) { out = new double[in_neu]; for (int j = 0; j < NUM_CLUSTERS; j++) { for (int i = 0; i < in_neu; i++) { if (i == 0) dt = t - dataSetAumented.get(k).X(); if (i == 1) dt = t - dataSetAumented.get(k).Y(); if (i == 2) dt = t - dataSetAumented.get(k).Z(); sai = w[i] * ((dt - d[i]) / tau) * Math.exp(1 - ((dt - d[i]) / tau)); if (sai < 0) sai = 0; out[i] = out[i] + sai; System.out.println("out[ " + i + " ] - > " + out[i]); } // in_neu System.out.println(""); } // out neu double max = max(out); System.out.println(" max -> "+ max); if (max >= teta) { for (int to = 0; to < out.length ; to++) { if (out[to] == max) { neu = to; } } } // max t = t + rho; } // while System.out.println("neu -> "+ neu); dataSetAumented.get(k).cluster(neu); } // tam sampleNumber = 0; for (int i = 0; i < NUM_CLUSTERS; i++) { System.out.println("Cluster " + i + " includes: "); for (int j = 0; j < TOTAL_DATA; j++) { if (dataSetAumented.get(j).cluster() == i) { System.out.println(" (" + dataSetAumented.get(j).X() + ", " + dataSetAumented.get(j).Y() + ")"); } } System.out.println(); } } // linear encoding public static ArrayList<Data> kodieren_ln() { int sampleNumber = 0; Data newData = null; Data normalData = null; while (dataSet.size() < TOTAL_DATA) { newData = new Data(SAMPLES[sampleNumber][0], SAMPLES[sampleNumber][1]); dataSet.add(newData); sampleNumber++; } double[] vecX = new double[dataSet.size()]; double[] vecY = new double[dataSet.size()]; double[] range = new double[SAMPLES[0].length]; double[] max = new double[SAMPLES[0].length]; double[] min = new double[SAMPLES[0].length]; N_SAMPLES = new double[SAMPLES.length][SAMPLES[0].length]; for (int s = 0; s < SAMPLES[0].length; s++) for (int i = 0; i < dataSet.size(); i++) { if (s == 0) vecX[i] = dataSet.get(i).X(); if (s == 1) vecY[i] = dataSet.get(i).Y(); } for (int s = 0; s < SAMPLES[0].length; s++) { if (s == 0) { max[s] = max(vecX); min[s] = min(vecX); range[s] = max[s] - min[s]; } if (s == 1) { max[s] = max(vecY); min[s] = min(vecY); range[s] = max[s] - min[s]; } } for (int s = 0; s < SAMPLES[0].length; s++) { for (int i = 0; i < dataSet.size(); i++) { if (s == 0) N_SAMPLES[i][s] = (vecX[i] - min[s]) / range[s]; if (s == 1) N_SAMPLES[i][s] = (vecY[i] - min[s]) / range[s]; } } sampleNumber = 0; ArrayList<Data> dataSetNormal = new ArrayList<Data>(); while (dataSetNormal.size() < TOTAL_DATA) { normalData = new Data(N_SAMPLES[sampleNumber][0], N_SAMPLES[sampleNumber][1]); dataSetNormal.add(normalData); sampleNumber++; } System.out.println("\nNormal dataSet [0-1]\n"); for (int j = 0; j < dataSetNormal.size(); j++) System.out.println("X -> " + dataSetNormal.get(j).X() + " Y -> " + dataSetNormal.get(j).Y()); ArrayList<Data> dataSetDelays = dataSetNormal; for (int j = 0; j < dataSetNormal.size(); j++) { dataSetDelays.get(j).X(Math.round(((dataSetNormal.get(j).X() * maxd) / rho) * rho)); dataSetDelays.get(j).Y(Math.round(((dataSetNormal.get(j).Y() * maxd) / rho) * rho)); } System.out.println("\n dataSetDelays \n"); for (int j = 0; j < dataSetDelays.size(); j++) System.out.println("X -> " + dataSetDelays.get(j).X() + " Y -> " + dataSetDelays.get(j).Y()); return dataSetDelays; } public static void main(String[] args) { // TODO Auto-generated method stub Initialize(); Training(); EventQueue.invokeLater(new Runnable() { @Override public void run() { SimpleClusterV2 demo = new SimpleClusterV2(title); demo.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); demo.pack(); demo.setLocationRelativeTo(null); demo.setVisible(true); } }); } private static class Data { private double mX = 0; private double mY = 0; private int mCluster = 0; public Data(double x, double y) { this.X(x); this.Y(y); } public void X(double x) { this.mX = x; return; } public double X() { return this.mX; } public void Y(double y) { this.mY = y; return; } public double Y() { return this.mY; } public void cluster(int clusterNumber) { this.mCluster = clusterNumber; return; } public int cluster() { return this.mCluster; } } private static class DataA { private double mX = 0; private double mY = 0; private double mZ = 0; private int mCluster = 0; public DataA(double x, double y, double z) { this.X(x); this.Y(y); this.Z(z); } public void X(double x) { this.mX = x; return; } public double X() { return this.mX; } public void Y(double y) { this.mY = y; return; } public double Y() { return this.mY; } public void Z(double z) { this.mZ = z; return; } public double Z() { return this.mZ; } public void cluster(int clusterNumber) { this.mCluster = clusterNumber; return; } public int cluster() { return this.mCluster; } } public static double max(double[] vec) { double ele = vec[0]; double max = 0; for (int x = 1; x < vec.length; x++) { double vectmp = vec[x]; if (ele > vectmp) { max = ele; } else max = vectmp; ele = max; } return max; } public static double min(double[] vec) { double ele = vec[0]; double min = 0; for (int x = 1; x < vec.length; x++) { double vectmp = vec[x]; if (ele < vectmp) { min = ele; } else min = vectmp; ele = min; } return min; } }
package com.developworks.jvmcode; /** * <p>Title: dadd</p> * <p>Description: double类型数据相加</p> * <p>Author: ouyp </p> * <p>Date: 2018-05-19 16:10</p> */ public class dadd { public void dadd(double d1, double d2) { d2 = d1 + d2; } } /** * public void dadd(double, double); * Code: * 0: dload_1 * 1: dload_3 * 2: dadd * 3: dstore_3 * 4: return */
/* * Copyright (c) 2013 ICM Uniwersytet Warszawski All rights reserved. * See LICENCE file for licensing information. */ package pl.edu.icm.unity.stdext.identity; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import pl.edu.icm.unity.MessageSource; import pl.edu.icm.unity.exceptions.IllegalIdentityValueException; import pl.edu.icm.unity.server.utils.UnityMessageSource; import pl.edu.icm.unity.stdext.attr.StringAttribute; import pl.edu.icm.unity.stdext.attr.StringAttributeSyntax; import pl.edu.icm.unity.types.basic.Attribute; import pl.edu.icm.unity.types.basic.AttributeType; import pl.edu.icm.unity.types.basic.AttributeVisibility; import pl.edu.icm.unity.types.basic.IdentityParam; /** * Simple username identity type definition * @author K. Benedyczak */ @Component public class UsernameIdentity extends AbstractStaticIdentityTypeProvider { public static final String ID = "userName"; private Set<AttributeType> EXTRACTED; private static final String EXTRACTED_NAME = "uid"; @Autowired public UsernameIdentity(UnityMessageSource msg) { EXTRACTED = new HashSet<AttributeType>(); EXTRACTED.add(new AttributeType(EXTRACTED_NAME, new StringAttributeSyntax(), msg)); EXTRACTED = Collections.unmodifiableSet(EXTRACTED); } public UsernameIdentity() { } /** * {@inheritDoc} */ @Override public String getId() { return ID; } /** * {@inheritDoc} */ @Override public String getDefaultDescription() { return "Username"; } /** * {@inheritDoc} */ @Override public Set<AttributeType> getAttributesSupportedForExtraction() { return EXTRACTED; } /** * {@inheritDoc} */ @Override public void validate(String value) throws IllegalIdentityValueException { if (value == null || value.trim().length() == 0) { throw new IllegalIdentityValueException("Username must be non empty"); } } @Override public IdentityParam convertFromString(String stringRepresentation, String remoteIdp, String translationProfile) throws IllegalIdentityValueException { return super.convertFromString(stringRepresentation.trim(), remoteIdp, translationProfile); } /** * {@inheritDoc} */ @Override public String getComparableValue(String from, String realm, String target) { return from; } /** * {@inheritDoc} */ @Override public List<Attribute<?>> extractAttributes(String from, Map<String, String> toExtract) { String desiredName = toExtract.get(EXTRACTED_NAME); if (desiredName == null) return Collections.emptyList(); Attribute<?> ret = new StringAttribute(desiredName, "/", AttributeVisibility.full, from); List<Attribute<?>> retL = new ArrayList<Attribute<?>>(); retL.add(ret); return retL; } /** * {@inheritDoc} */ @Override public String toPrettyStringNoPrefix(IdentityParam from) { return from.getValue(); } @Override public String getHumanFriendlyDescription(MessageSource msg) { return msg.getMessage("UsernameIdentity.description"); } @Override public boolean isDynamic() { return false; } @Override public String getHumanFriendlyName(MessageSource msg) { return msg.getMessage("UsernameIdentity.name"); } }
package pl.edu.uj.fais.amsi.gfx; import java.awt.Font; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.RenderingHints; import static java.awt.SystemColor.text; import java.awt.font.FontRenderContext; import java.awt.font.TextLayout; import java.awt.geom.AffineTransform; import java.awt.geom.Rectangle2D; import javax.swing.JPanel; import static pl.edu.uj.fais.amsi.gfx.GameWindow.BSIZE; import static pl.edu.uj.fais.amsi.gfx.GameWindow.COLOURBACK; import static pl.edu.uj.fais.amsi.gfx.GameWindow.board; /** * * @author Michal Szura & Bartosz Bereza */ class DrawingPanel extends JPanel { public DrawingPanel() { setBackground(COLOURBACK); MouseListener ml = new MouseListener(this); addMouseListener(ml); } @Override public void paintComponent(Graphics g) { Graphics2D g2 = (Graphics2D) g; g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g.setFont(new Font("TimesRoman", Font.PLAIN, 20)); FontRenderContext frc = g2.getFontRenderContext(); Font font = g.getFont(); String hexText = " "; super.paintComponent(g2); //draw grid for (int i = 0; i < BSIZE; i++) { for (int j = 0; j < BSIZE; j++) { HexOperations.drawHex(i, j, g2); } } //fill in hexes for (int i = 0; i < BSIZE; i++) { for (int j = 0; j < BSIZE; j++) { if (!board[i][j].equals("")) { hexText = board[i][j]; } TextLayout layout = new TextLayout(hexText, font, frc); Rectangle2D bounds = layout.getBounds(); double w = bounds.getWidth(); double h = bounds.getHeight(); HexOperations.fillHex(i, j, w, h, board[i][j], i, j, g2); } } } }
package com.zju.courier.service.impl; import com.zju.courier.dao.UserDao; import com.zju.courier.entity.User; import com.zju.courier.service.UserService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class UserServiceImpl implements UserService { private Logger logger = LoggerFactory.getLogger(this.getClass()); @Autowired private UserDao userDao; @Override public User query(String username, String passwd) { return userDao.query(username, passwd); } @Override public void insert(User user) { userDao.insertUser(user); } }
package com.leetcode; public class L111_Minimum_Depth_of_Binary_Tree { public static void main(String args[]) { TreeNode node1 = new TreeNode(1); TreeNode node2 = new TreeNode(2); TreeNode node3 = new TreeNode(2); TreeNode node4 = new TreeNode(3); TreeNode node5 = new TreeNode(3); TreeNode node6 = new TreeNode(4); TreeNode node7 = new TreeNode(4); node1.left = node2; node1.right = node3; node2.left = node4; node2.right = node5; node4.left = node6; node4.right = node7; System.out.println(minDepth(node1)); } public static int minDepth(TreeNode root) { if (root == null) return 0; if (root.left == null && root.right == null) return 1; int left = root.left == null ? Integer.MAX_VALUE : minDepth(root.left); int right = root.right == null ? Integer.MAX_VALUE : minDepth(root.right); return Math.min(left, right) + 1; } }
import java.util.Scanner; public class untitled3 { public static void main(String[] args) { Scanner scn = new Scanner(System.in); String str=scn.nextLine(); char ch1=scn.next().charAt(0); char ch2=scn.next().charAt(0); System.out.println(str.replace(ch1,ch2)); } }
package io.snice.protocol; import java.util.Optional; public class ResponseSupport<O, T> extends TransactionSupport<O, T> implements Response<O, T> { private final boolean isFinal; protected ResponseSupport(final TransactionId transactionId, final O owner, final boolean isFinal, final Optional<T> payload) { super(transactionId, owner, payload); this.isFinal = isFinal; } protected ResponseSupport(final TransactionId transactionId, final O owner, final boolean isFinal) { super(transactionId, owner); this.isFinal = isFinal; } protected ResponseSupport(final TransactionId transactionId, final O owner) { super(transactionId, owner); this.isFinal = true; } @Override public boolean isFinal() { return isFinal; } public static class BuilderSupport<O, T> implements Response.Builder<O, T> { private final TransactionId transactionId; private final O owner; private final Optional<T> payload; private boolean isFinal = true; protected BuilderSupport(final TransactionId transactionId, final O owner, final Optional<T> payload) { this.transactionId = transactionId; this.owner = owner; this.payload = payload; } @Override public Builder<O, T> isFinal(final boolean value) { this.isFinal = value; return this; } @Override public final Response<O, T> build() { return internalBuild(transactionId, owner, payload, isFinal); } /** * Meant for sub-classes to override in order to return a more specific {@link Response} class. * * @param id * @param owner * @param payload * @param isFinal * @return */ protected Response<O, T> internalBuild(final TransactionId id, final O owner, final Optional<T> payload, final boolean isFinal) { return new ResponseSupport<O, T>(id, owner, isFinal, payload); } } }
package com.docker.storage.adapters; import chat.errors.CoreException; import com.docker.data.DockerStatus; import com.docker.data.Service; import org.bson.Document; /** * 管理服务器在线状态的接口 * * 使用Lan里的MongoDB数据库 * * @author aplombchen * */ public interface ServersService { Document getServerConfig(String serverType) throws CoreException; }
package payment.domain.service; import lombok.NonNull; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import payment.domain.model.Payment; import payment.domain.repository.PaymentRepository; /** * @author claudioed on 26/06/17. Project docker-aws-devry */ @Component public class PaymentService { private final PaymentRepository paymentRepository; @Autowired public PaymentService(PaymentRepository paymentRepository) { this.paymentRepository = paymentRepository; } public Payment load(@NonNull String id){ return this.paymentRepository.payment(id); } }
package _22_structural_design_pattern.adapter_pattern; import java.util.ArrayList; import java.util.List; import java.util.Random; import java.util.Set; public class Client { public static void main(String[] args) { int count = 0; Random random = new Random(); CollectionUtilsAdapter util = new CollectionUtilsAdapter(); List<Integer> listNumber = new ArrayList<>(); while (count < 50) { listNumber.add(random.nextInt(10)); count++; } util.printList(listNumber); util.printMaxValue(listNumber); } }
package com.hcl.neo.eloader.filesystem.handler.impl; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.util.zip.GZIPInputStream; import java.util.zip.GZIPOutputStream; import org.apache.commons.compress.archivers.tar.TarArchiveEntry; import org.apache.commons.compress.archivers.tar.TarArchiveInputStream; import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream; import org.apache.commons.compress.archivers.zip.ZipArchiveEntry; import org.apache.commons.compress.archivers.zip.ZipArchiveInputStream; import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream; abstract class ArchiveFactory { protected static TarArchiveInputStream createTgzArchiveInputStream(File sourceFile) throws FileNotFoundException, IOException{ return new TarArchiveInputStream(new GZIPInputStream(new BufferedInputStream(new FileInputStream(sourceFile))), "UTF-8"); } protected static TarArchiveInputStream createTarArchiveInputStream(File sourceFile) throws FileNotFoundException, IOException{ return new TarArchiveInputStream(new BufferedInputStream(new FileInputStream(sourceFile)), "UTF-8"); } protected static ZipArchiveInputStream createZipArchiveInputStream(File sourceFile) throws FileNotFoundException, IOException{ return new ZipArchiveInputStream(new BufferedInputStream(new FileInputStream(sourceFile))); } protected static GZIPInputStream createGzipArchiveInputStream(File sourceFile) throws FileNotFoundException, IOException{ return new GZIPInputStream(new BufferedInputStream(new FileInputStream(sourceFile))); } protected static TarArchiveOutputStream createTgzArchiveOutputStream(File sourceFile) throws FileNotFoundException, IOException{ return new TarArchiveOutputStream(new GZIPOutputStream(new BufferedOutputStream(new FileOutputStream(sourceFile))), "UTF-8"); } protected static TarArchiveOutputStream createTarArchiveOutputStream(File sourceFile) throws FileNotFoundException, IOException{ return new TarArchiveOutputStream(new BufferedOutputStream(new FileOutputStream(sourceFile)), "UTF-8"); } protected static ZipArchiveOutputStream createZipArchiveOutputStream(File sourceFile) throws FileNotFoundException, IOException{ return new ZipArchiveOutputStream(new BufferedOutputStream(new FileOutputStream(sourceFile))); } protected static GZIPOutputStream createGzipArchiveOutputStream(File sourceFile) throws FileNotFoundException, IOException{ return new GZIPOutputStream(new BufferedOutputStream(new FileOutputStream(sourceFile))); } protected static TarArchiveEntry createTarArchiveEntry(String entryName){ return new TarArchiveEntry(entryName); } protected static ZipArchiveEntry createZipArchiveEntry(String entryName){ return new ZipArchiveEntry(entryName); } }
package com.cai.seckill.service; import com.cai.seckill.pojo.Order; import com.cai.seckill.pojo.User; import com.cai.seckill.redis.RedisService; import com.cai.seckill.redis.keys.SeckillKey; import com.cai.seckill.util.MD5Util; import com.cai.seckill.util.UUIDUtil; import com.cai.seckill.vo.GoodsVo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import javax.script.ScriptEngine; import javax.script.ScriptEngineManager; import java.awt.*; import java.awt.image.BufferedImage; import java.util.Random; @Service public class SeckillService { @Autowired private GoodsService goodsService; @Autowired private OrderService orderService; @Autowired private RedisService redisService; @Transactional public Order doSeckill(User user, GoodsVo goods){ //减库存 boolean success = goodsService.reducestock(goods); if(success){ //生成订单项进入数据库中 Order order = orderService.createOrder(user, goods); return order; }else { //如果减库存失败,说明没库存了,秒杀失败,设置标志位 setOverFlag(goods.getId()); return null; } } public long getSeckillResult(long userId,long goodsId){ Order order = orderService.getOrderByGoodsId(0,goodsId); //订单不为空说明秒杀成功,返回商品id if(order != null){ return goodsId; }else { //订单为空有两种情况,一种是没库存了,另外一种是还在队列中排队处理,要分开处理 boolean over = getOverFlag(goodsId); if(over == true){ return -1; }else { return 0; } } } //用来判断秒杀是结束了还是在排队 private void setOverFlag(Long id) { redisService.set(SeckillKey.getGoodsOverFlag,""+id,true); } private boolean getOverFlag(long goodsId) { return redisService.exists(SeckillKey.getGoodsOverFlag,""+goodsId); } //随机创建地址 public String createSeckillPath(Long userId, long goodsId) { String path = MD5Util.md5(UUIDUtil.uuid()+"123456"); redisService.set(SeckillKey.getSeckillPath,""+userId+"_"+goodsId,path); return path; } //验证地址 public boolean checkPath(Long userId, long goodsId, String path) { if(redisService.get(SeckillKey.getSeckillPath,""+userId+"_"+goodsId,String.class).equals(path)){ return true; }else{ return false; } } //生成验证码 public BufferedImage createVerifyCode(User user, long goodsId) { if(user == null || goodsId <=0) { return null; } int width = 80; int height = 32; //create the image BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); Graphics g = image.getGraphics(); // set the background color g.setColor(new Color(0xDCDCDC)); g.fillRect(0, 0, width, height); // draw the border g.setColor(Color.black); g.drawRect(0, 0, width - 1, height - 1); // create a random instance to generate the codes Random rdm = new Random(); // make some confusion for (int i = 0; i < 50; i++) { int x = rdm.nextInt(width); int y = rdm.nextInt(height); g.drawOval(x, y, 0, 0); } // generate a random code String verifyCode = generateVerifyCode(rdm); g.setColor(new Color(0, 100, 0)); g.setFont(new Font("Candara", Font.BOLD, 24)); g.drawString(verifyCode, 8, 24); g.dispose(); //把验证码存到redis中 int rnd = calc(verifyCode); redisService.set(SeckillKey.getMiaoshaVerifyCode, user.getId()+","+goodsId, rnd); //输出图片 return image; } //验证验证码是否正确 public boolean checkVerifyCode(User user, long goodsId, int verifyCode) { if(user == null || goodsId <=0) { return false; } Integer codeOld = redisService.get(SeckillKey.getMiaoshaVerifyCode, user.getId()+","+goodsId, Integer.class); if(codeOld == null || codeOld - verifyCode != 0 ) { return false; } redisService.delete(SeckillKey.getMiaoshaVerifyCode, user.getId()+","+goodsId); return true; } private static int calc(String exp) { try { ScriptEngineManager manager = new ScriptEngineManager(); ScriptEngine engine = manager.getEngineByName("JavaScript"); return (Integer)engine.eval(exp); }catch(Exception e) { e.printStackTrace(); return 0; } } private static char[] ops = new char[] {'+', '-', '*'}; /** * + - * * */ private String generateVerifyCode(Random rdm) { int num1 = rdm.nextInt(10); int num2 = rdm.nextInt(10); int num3 = rdm.nextInt(10); char op1 = ops[rdm.nextInt(3)]; char op2 = ops[rdm.nextInt(3)]; String exp = ""+ num1 + op1 + num2 + op2 + num3; return exp; } }
package de.hofuniversity.webbean; import javax.faces.bean.ManagedBean; import javax.faces.bean.ViewScoped; import javax.naming.directory.InitialDirContext; import de.hofuniversity.ejbbean.bean.TeamDetailsRemote; import de.hofuniversity.ejbbean.data.TeamDetailsSummaryData; /** * * @author Markus Exner * */ @ManagedBean @ViewScoped public class WebTeamDetailBean { private TeamDetailsRemote teamRemote = null; private TeamDetailsRemote thisGetTeamDetail() { if (teamRemote == null) { try { teamRemote = (TeamDetailsRemote) new InitialDirContext().lookup(TeamDetailsRemote.MAPPED_NAME); } catch (Exception e) { e.printStackTrace(); } } return teamRemote; } public TeamDetailsSummaryData getTeamDetails(int id) { return thisGetTeamDetail().getTeamDetails(id); } }