text
stringlengths
10
2.72M
package br.com.sysprojsp.dao; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.ArrayList; import java.util.List; import br.com.sysprojsp.classes.model.Bandeira; import br.com.sysprojsp.classes.model.ProdutoCsv; import br.com.sysprojsp.connection.SingleConnection; public class DaoProdutoCsv { private Connection connection; public DaoProdutoCsv() { connection = SingleConnection.getConnection(); } public void save(ProdutoCsv procsv) { try { String sql = "INSERT INTO tbl_produtocsv(" + " revenda, cnpjrevenda, descricaoproduto, datacoleta, valorcompra, " + " valorvenda, quantidade, unidademedida, tipo, estado, cidade, id_bandeira) " + " VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);"; PreparedStatement statement = connection.prepareStatement(sql); statement.setString(1, procsv.getRevenda()); statement.setString(2, procsv.getCnpjRevenda()); statement.setString(3, procsv.getDescricaoProduto()); statement.setString(4, procsv.getDataColeta()); statement.setDouble(5, procsv.getValorCompra()); statement.setDouble(6, procsv.getValorVenda()); statement.setInt(7, procsv.getQuantidade()); statement.setString(8, procsv.getUnidadeMedida()); statement.setString(9, procsv.getTipo()); statement.setString(10, procsv.getEstado()); statement.setString(11, procsv.getCidade()); statement.setLong(12, procsv.getId_bandeira()); statement.execute(); connection.commit(); } catch (Exception e) { e.printStackTrace(); try { connection.rollback(); } catch (Exception ex) { ex.printStackTrace(); } } } public List<ProdutoCsv> listarTodosProdutosCsv(){ try { List<ProdutoCsv> produtoCsvs = new ArrayList<ProdutoCsv>(); String sql = "SELECT * FROM tbl_produtocsv order by id;"; PreparedStatement statement = connection.prepareStatement(sql); ResultSet rs = statement.executeQuery(); while (rs.next()) { ProdutoCsv procsv = new ProdutoCsv(); procsv.setId(rs.getLong("id")); procsv.setRevenda(rs.getString("revenda")); procsv.setCnpjRevenda(rs.getString("cnpjRevenda")); procsv.setDescricaoProduto(rs.getString("descricaoProduto")); procsv.setDataColeta(rs.getString("dataColeta")); procsv.setValorCompra(rs.getDouble("valorCompra")); procsv.setValorVenda(rs.getDouble("valorVenda")); procsv.setQuantidade(rs.getInt("quantidade")); procsv.setUnidadeMedida(rs.getString("unidadeMedida")); procsv.setTipo(rs.getString("tipo")); procsv.setEstado(rs.getString("estado")); procsv.setCidade(rs.getString("cidade")); procsv.setId_bandeira(rs.getLong("id_bandeira")); produtoCsvs.add(procsv); } return produtoCsvs; } catch (Exception e) { e.printStackTrace(); } return null; } public List<Bandeira> listarTodasBandeiras(){ try { List<Bandeira> bandeiras = new ArrayList<Bandeira>(); String sql = "SELECT * FROM tbl_bandeira order by id;"; PreparedStatement statement = connection.prepareStatement(sql); ResultSet rs = statement.executeQuery(); while (rs.next()) { Bandeira ban = new Bandeira(); ban.setId(rs.getLong("id")); ban.setNome(rs.getString("nome")); bandeiras.add(ban); } return bandeiras; } catch (Exception e) { e.printStackTrace(); } return null; } public ProdutoCsv consultarProdutoCsv(String id){ try { String sql = "SELECT * FROM tbl_produtocsv WHERE id = '" + id + "'"; PreparedStatement statement = connection.prepareStatement(sql); ResultSet rs = statement.executeQuery(); while (rs.next()) { ProdutoCsv procsv = new ProdutoCsv(); procsv.setId(rs.getLong("id")); procsv.setRevenda(rs.getString("revenda")); procsv.setCnpjRevenda(rs.getString("cnpjRevenda")); procsv.setDescricaoProduto(rs.getString("descricaoProduto")); procsv.setDataColeta(rs.getString("dataColeta")); procsv.setValorCompra(rs.getDouble("valorCompra")); procsv.setValorVenda(rs.getDouble("valorVenda")); procsv.setQuantidade(rs.getInt("quantidade")); procsv.setUnidadeMedida(rs.getString("unidadeMedida")); procsv.setTipo(rs.getString("tipo")); procsv.setEstado(rs.getString("estado")); procsv.setCidade(rs.getString("cidade")); procsv.setId_bandeira(rs.getLong("id_bandeira")); return procsv; } } catch (Exception e) { e.printStackTrace(); } return null; } public void update(ProdutoCsv procsv) { try { String sql = "UPDATE tbl_produtocsv " + " SET id=?, revenda=?, cnpjrevenda=?, descricaoproduto=?, datacoleta=?, " + " valorcompra=?, valorvenda=?, quantidade=?, unidademedida=?, tipo=?, " + " estado=?, cidade=?, id_bandeira=? " + " WHERE id = '" + procsv.getId() + "'"; PreparedStatement statement = connection.prepareStatement(sql); statement.setLong(1, procsv.getId()); statement.setString(2, procsv.getRevenda()); statement.setString(3, procsv.getCnpjRevenda()); statement.setString(4, procsv.getDescricaoProduto()); statement.setString(5, procsv.getDataColeta()); statement.setDouble(6, procsv.getValorCompra()); statement.setDouble(7, procsv.getValorVenda()); statement.setInt(8, procsv.getQuantidade()); statement.setString(9, procsv.getUnidadeMedida()); statement.setString(10, procsv.getTipo()); statement.setString(11, procsv.getEstado()); statement.setString(12, procsv.getCidade()); statement.setLong(13, procsv.getId_bandeira()); statement.executeUpdate(); connection.commit(); } catch (Exception e) { e.printStackTrace(); try { connection.rollback(); } catch (Exception ex) { ex.printStackTrace(); } } } public void delete(String id) { try { String sql = "DELETE FROM tbl_produtocsv WHERE id = '" + id + "';"; PreparedStatement statement = connection.prepareStatement(sql); statement.execute(); connection.commit(); } catch (Exception e) { e.printStackTrace(); try { connection.rollback(); } catch (Exception ex) { ex.printStackTrace(); } } } public boolean validarCnpj(String revendaCnpj) { try { String sql = "select count(1) as qtd from tbl_produtocsv where id = '" + revendaCnpj + "'"; PreparedStatement statement = connection.prepareStatement(sql); ResultSet resultado = statement.executeQuery(); /* * apůs buscar no banco e ter o resultado, verifica se existe o login procurado */ if (resultado.next()) { return resultado.getInt("qtd") <= 0;/*return true*/ } } catch (Exception e) { e.printStackTrace(); } return false; } }
package LC200_400.LC300_350; public class LC309_Best_Time_To_Buy_And_Sell_Stock_With_Cooldown { public int maxProfit(int[] prices) { if(prices.length == 1 || prices.length == 0) return 0; int[] dp = new int[prices.length]; int temp = prices[0]; int flag = 0; for(int j = 1; j < prices.length; ++j){ dp[j] = Math.max(dp[j-1], prices[j] - temp); if(j >= 2) temp = Math.min(temp, prices[j] - dp[j - 2]); else temp = Math.min(temp, prices[j] - dp[j - 1]); } return dp[prices.length - 1]; } }
package com.tencent.mm.plugin.appbrand.widget.input.c; public enum g { LEFT, RIGHT, CENTER; public static g wl(String str) { Enum h = d.h(str, g.class); g gVar = LEFT; if (h != null) { Enum gVar2 = h; } return gVar2; } }
package com.tencent.mm.ui.chatting; import android.content.Intent; import com.tencent.mm.R; import com.tencent.mm.pluginsdk.model.app.g; class u$5 implements Runnable { final /* synthetic */ Intent miG; final /* synthetic */ u tKV; u$5(u uVar, Intent intent) { this.tKV = uVar; this.miG = intent; } public final void run() { g.a(this.tKV.mContext, this.miG, this.tKV.mContext.getString(R.l.chatfooter_mail_without_unread_count), null, null); } }
package com.cookiesncrumbs.msalvio.cpe50_ay1718_1stsem_android; import android.content.DialogInterface; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.EditText; import android.widget.ListView; import android.widget.Toast; import java.util.ArrayList; public class SimpleListActivity extends AppCompatActivity { ListView listView; ArrayAdapter<String> adapter; ArrayList<String> list; EditText editText; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_simple_list); listView = (ListView) findViewById(R.id.list_view); editText = (EditText) findViewById(R.id.item_et); list = new ArrayList<String>(); adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, list); listView.setAdapter(adapter); listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() { @Override public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) { new AlertDialog.Builder(SimpleListActivity.this) .setMessage("Delete?") .setPositiveButton("Delete", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { list.remove(position); adapter.notifyDataSetChanged(); } }).create().show(); return true; } }); } public void add(View v){ String itemName = editText.getText().toString(); list.add(itemName); adapter.notifyDataSetChanged(); editText.setText(""); } }
package com.sdk4.boot.service; /** * @author sh */ public interface SequenceService { /** * 通用序号生成 * * @param type */ Long nextVal(String type); }
import java.util.*; class lifeline2 { static KBC obj = new KBC(); public static void main() { if (obj.cl == 2) { if(obj.l2==0) { obj.l2=1; System.out.println("Audiance voted option "+obj.correct+ " - 90%"); } else { System.out.println("You have used this lifeline once so it is not availabe."); } } } }
package gti310.tp3; import gti310.tp3.parser.*; import gti310.tp3.solver.*; import gti310.tp3.writer.*; /** * The Application class defines a template method to call the elements to * solve the problem Unreal-Networks is façing. * * @author François Caron <francois.caron.7@ens.etsmtl.ca> */ public class Application { /** * The Application's entry point. * * The main method makes a series of calls to find a solution to the * problem. The program awaits two arguments, the complete path to the * input file, and the complete path to the output file. * * @param args The array containing the arguments to the files. */ public static void main(String args[]) { System.out.println("Unreal Networks Solver !"); Parser<E> p = new ConcreteParser(); Solver<E, Eout> s = new ConcreteSolver(); Writer<Eout> w = new ConcreteWriter(); if ((args[0]==null) || (args[1]==null)) { System.out.println("Missing arguments"); } else { //parse data from the file E data = p.parse(args[0]); //find the solution if possible Eout solutions = s.solve(data); w.write(args[1], solutions); } } }
package cn.no7player.controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.servlet.ModelAndView; @RestController @RequestMapping("/index") public class HelloController { @RequestMapping("/hello") public ModelAndView greeting(@RequestParam(value="name", required=false, defaultValue="World") String name, Model model) { model.addAttribute("name", name); return new ModelAndView("error"); } }
/* * 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 bean; import DTOs.CustomerDTO; import DTOs.OrderDTO; import entity.Customer; import java.sql.Date; import javax.persistence.*; import javax.persistence.EntityManager; import entity.Orders; /** * * @author angeloron */ public class OrderHandler { @PersistenceContext(unitName = "com.awesome_ORM_Maven_jar_1.0-SNAPSHOTPU") private static EntityManagerFactory factory = Persistence.createEntityManagerFactory("com.awesome_ORM_Maven_jar_1.0-SNAPSHOTPU"); EntityManager em = factory.createEntityManager(); public OrderDTO getOrderById(int id) { Orders order = em.find(Orders.class, id); Customer customer = order.getCustomer(); CustomerDTO customerDTO = new CustomerDTO(customer.getCustomerid(), customer.getCompanyname(), customer.getAddress(), customer.getPhone()); OrderDTO orderDTO = new OrderDTO(order.getShipname(), order.getShipaddress(), order.getShipcity(), order.getShipcountry(), order.getOrderid(), order.getFreight(), customerDTO); return orderDTO; } // private static EntityManagerFactory factory = Persistence.createEntityManagerFactory("com.awesome_ORM_Maven_jar_1.0-SNAPSHOTPU"); // EntityManager em = factory.createEntityManager(); // public OrderDTO getOrderById(int id) { // Orders tempOrder = em.find(Orders.class, id); // OrderDTO temp2 = new OrderDTO(tempOrder.getCustomerid() , tempOrder.getShipname(), tempOrder.getShipcity(), // tempOrder.getOrderid(), tempOrder.getEmployeeid(), // tempOrder.getOrderdate()); // return temp2; // } // public void addCustomer(CustomerDTO customer) { // Customer customerTemp = new Customer(); // // customerTemp.setCustomerid(customer.getId()); // customerTemp.setCompanyname(customer.getCompanyName()); // customerTemp.setAddress(customer.getAddress()); // customerTemp.setPhone(customer.getPhone()); // // //defaults // customerTemp.setCity("Copenhagen"); // customerTemp.setContactname("Contact name"); // customerTemp.setContacttitle(null); // customerTemp.setCountry("Denmark"); // customerTemp.setFax("00223344"); // customerTemp.setPostalcode("2300"); // // em.getTransaction().begin(); // em.persist(customerTemp); // em.getTransaction().commit(); // // } // // public void editCustomer(CustomerDTO edited) { // Customer tempCust = em.find(Customer.class, edited.getId()); // tempCust.setCompanyname(edited.getCompanyName()); // tempCust.setAddress(edited.getAddress()); // tempCust.setPhone(edited.getPhone()); // em.getTransaction().begin(); // em.persist(tempCust); // em.getTransaction().commit(); // } // // public void deleteCustomer(CustomerDTO customer) { // Customer cust = em.find(Customer.class, customer.getId()); // em.getTransaction().begin(); // em.remove(cust); // em.getTransaction().commit(); // } }
package evm.dmc.api.model; public enum FunctionType { CLUSTERIZATION, NORAMLIZATION, PCA, STANDARDIZATION, CSV_DATASOURCE, CSV_DATADESTINATION, OTHER; }
/* * Copyright 2010 Kim A. Betti, Alexey Zhokhov * * 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 grails.plugin.sitemapper.artefact; import org.codehaus.groovy.grails.commons.AbstractGrailsClass; /** * @author <a href='mailto:kim@developer-b.com'>Kim A. Betti</a> */ public class DefaultSitemapperClass extends AbstractGrailsClass implements SitemapperClass { @SuppressWarnings("rawtypes") public DefaultSitemapperClass(Class clazz) { super(clazz, SitemapperArtefactHandler.SUFFIX); } }
import java.util.Arrays; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int m = scanner.nextInt(); int[][] count = new int[m][2];int[] max = new int[m+1]; for(int i=0;i<m;i++) { count[i][0] = scanner.nextInt(); count[i][1] = 0; max[i] = 0; } for (int i = 0; i < m; i++) { for (int j = 1; j <= m; j++) { if (max[j] + count[i][0] <= 100) { max[j] += count[i][0]; count[i][1] = j; break; } } } int temp=1; for(int i=0;i<m;i++) { if (count[i][1] > temp) { temp = count[i][1]; } } for(int i=0;i<m;i++) { System.out.println(count[i][0] + " " + count[i][1]); } System.out.println(temp); } }
package com.vijay.fragmetn; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; public class MainActivity extends AppCompatActivity implements View.OnClickListener { private static Button defaultFragment, argumentFragment; private static FragmentManager fragmentManager; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Log.e("MainActivity", "onCreate"); fragmentManager = getSupportFragmentManager();//Get Fragment Manager defaultFragment = findViewById(R.id.setDefaultFragment); argumentFragment = findViewById(R.id.setArgumentFragment); defaultFragment.setOnClickListener(this); argumentFragment.setOnClickListener(this); } @Override public void onClick(View view) { switch (view.getId()) { case R.id.setDefaultFragment: fragmentManager.beginTransaction().replace(R.id.fragmentContainer, new DefaultFragment()).commit(); break; case R.id.setArgumentFragment: Fragment fragment = new ArgumentFragment(); Bundle bundle = new Bundle(); bundle.putString("data", "This is Argument Fragment"); fragment.setArguments(bundle); fragmentManager.beginTransaction().replace(R.id.fragmentContainer, fragment).commit();//now replace the argument fragment /** Note: If you are passing argument in fragment then don't use below code always replace fragment * instance where we had set bundle as argument as we had done above else it will give exception **/ // fragmentManager.beginTransaction().replace(R.id.fragmentContainer, new ArgumentFragment()).commit(); break; } } @Override protected void onStart() { super.onStart(); Log.e("MainActivity", "onStart"); } @Override protected void onResume() { super.onResume(); Log.e("MainActivity", "onResume"); } @Override protected void onPause() { super.onPause(); Log.e("MainActivity", "onPause"); } @Override protected void onStop() { super.onStop(); Log.e("MainActivity", "onStop"); } @Override protected void onDestroy() { super.onDestroy(); Log.e("MainActivity", "onDestroy"); } // animation // back button // fragment flush // add and back fragment navigate }
package com.aslansari.rxjavastatemng.ui; public class SubmitAction { public String name; public SubmitAction(String name){ this.name = name; } }
package com.eazy.firda.eazy.adapter; import android.app.Activity; import android.content.Context; import android.content.res.ColorStateList; import android.graphics.Color; import android.os.Build; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.TextView; import com.android.volley.toolbox.ImageLoader; import com.eazy.firda.eazy.R; import com.eazy.firda.eazy.application.EazyApplication; import com.eazy.firda.eazy.models.Book; import java.util.List; /** * Created by firda on 3/1/2018. */ public class BookListAdapter extends BaseAdapter { private Activity activity; private LayoutInflater inflater; private List<Book> books; public String book_id; ImageLoader imageLoader = EazyApplication.getInstance().getImageLoader(); public BookListAdapter(Activity activity, List<Book> books){ this.activity = activity; this.books = books; } @Override public int getCount() {return books.size();} @Override public Object getItem(int position) {return books.get(position);} @Override public long getItemId(int position) {return position;} @Override public View getView(int position, View convertView, ViewGroup parent) { if(inflater == null){ inflater = (LayoutInflater) activity .getSystemService(Context.LAYOUT_INFLATER_SERVICE); } if(convertView == null){ //convertView = inflater.inflate(R.layout.book_row_list, null); convertView = inflater.inflate(R.layout.book_row_list_v2, null); } if(imageLoader == null){ imageLoader = EazyApplication.getInstance().getImageLoader(); } // NetworkImageView book_img = (NetworkImageView)convertView.findViewById(R.id.book_img); TextView book_name = (TextView)convertView.findViewById(R.id.book_name); TextView book_status = (TextView)convertView.findViewById(R.id.book_status); TextView book_location = (TextView)convertView.findViewById(R.id.book_location); TextView book_date = (TextView)convertView.findViewById(R.id.book_date); Book b = books.get(position); //book_img.setImageUrl(b.getCarImage(), imageLoader); book_name.setText(b.getName()); if ((Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1) && ((Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP))) { // your code here - is between 15-21 if(b.getStatus().equals("CONFIRMED")){book_status.setBackgroundColor(Color.parseColor("#43A047"));} else if(b.getStatus().equals("PENDING")){book_status.setBackgroundColor(Color.parseColor("#FB8C00"));} else if(b.getStatus().equals("REJECTED")){book_status.setBackgroundColor(Color.parseColor("#F44336"));} else if(b.getStatus().equals("COMPLETED")){book_status.setBackgroundColor(Color.parseColor("#2196F3"));} } else if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { // your code here - is api 21 if(b.getStatus().equals("CONFIRMED")){book_status.setBackgroundTintList (ColorStateList.valueOf(Color.parseColor("#43A047")));} else if(b.getStatus().equals("PENDING")){book_status.setBackgroundTintList (ColorStateList.valueOf(Color.parseColor("#FB8C00")));} else if(b.getStatus().equals("REJECTED")){book_status.setBackgroundTintList (ColorStateList.valueOf(Color.parseColor("#F44336")));} else if(b.getStatus().equals("COMPLETED")){book_status.setBackgroundTintList (ColorStateList.valueOf(Color.parseColor("#2196F3")));} } book_status.setText(b.getStatus()); book_location.setText(b.getLocation()); book_date.setText(b.getDate()); book_id = b.getId(); return convertView; } }
package kr.hs.emirim.sookhee.redonorpets; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatActivity; import androidx.core.content.res.ResourcesCompat; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import android.content.Intent; import android.content.SharedPreferences; import android.content.res.Resources; import android.graphics.Color; import android.os.Bundle; import android.text.TextUtils; import android.util.DisplayMetrics; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; import com.google.firebase.database.ChildEventListener; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.Query; import com.google.firebase.database.ValueEventListener; import com.squareup.picasso.Picasso; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import de.hdodenhof.circleimageview.CircleImageView; import kr.hs.emirim.sookhee.redonorpets.adapter.CommentAdapter; import kr.hs.emirim.sookhee.redonorpets.model.CommentData; import kr.hs.emirim.sookhee.redonorpets.model.StoryData; public class StoryDetailActivity extends AppCompatActivity { TextView tvTitle; TextView tvDate; TextView tvShelterName; TextView tvLikeCount; TextView tvCommentSubmit; EditText etComment; Button btnStoryLike; ImageView ivShelterImg; CircleImageView ivUserProfile; LinearLayout lStoryContent; View view; RecyclerView recyclerView; LinearLayoutManager mLayoutManager; CommentAdapter adapter; // Firebase private FirebaseDatabase FirebaseDatabase; private DatabaseReference storyDatabaseReference; private DatabaseReference shelterDatabaseReference; private DatabaseReference userDatabaseReference; private String storyPosition; private String shelterPosition; private boolean isLike = false; private String userEmail = ""; private int text = 0, img = 0; private int storyLikeCount, commentCount; final ArrayList<String> storyImgList = new ArrayList<>(); final ArrayList<String> storyTextList = new ArrayList<>(); private String userName = "temporary", userProfile, putUserIsLike = ""; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_story_detail); SharedPreferences pref = getSharedPreferences("pref", MODE_PRIVATE); userEmail = pref.getString("userEmail", ""); view = getLayoutInflater().from(this).inflate(R.layout.activity_story_detail, null); Intent intent = getIntent(); storyPosition = intent.getExtras().getString("storyPosition"); shelterPosition = intent.getExtras().getString("shelterPosition"); btnStoryLike = (Button) findViewById(R.id.storyLkeButton); tvLikeCount = findViewById(R.id.storyLikeCountTextView); recyclerView = (RecyclerView) findViewById(R.id.storyDetailCommentLayout); ivUserProfile = findViewById(R.id.storyDetailCommentUserProfileImageView); FirebaseDatabase = FirebaseDatabase.getInstance(); lStoryContent = (LinearLayout) findViewById(R.id.storyContentLayout); //사용자 정보 불러오기 userDatabaseReference = FirebaseDatabase.getReference("user"); Query userQuery = userDatabaseReference.orderByChild("email").equalTo(userEmail); userQuery.addChildEventListener(new ChildEventListener() { @Override public void onChildAdded(@NonNull DataSnapshot dataSnapshot, @Nullable String s) { userName = dataSnapshot.child("id").getValue(String.class); userProfile = dataSnapshot.child("profileImg").getValue(String.class); Picasso.get().load(userProfile).into(ivUserProfile); putUserIsLike = (userName + "/isLike"); } @Override public void onChildChanged(@NonNull DataSnapshot dataSnapshot, @Nullable String s) { } @Override public void onChildRemoved(@NonNull DataSnapshot dataSnapshot) { String key = dataSnapshot.getKey(); adapter.deleteDataAndUpdate(key); } @Override public void onChildMoved(@NonNull DataSnapshot dataSnapshot, @Nullable String s) { } @Override public void onCancelled(@NonNull DatabaseError databaseError) { } }); //스토리 기본 정보 불러오기 storyDatabaseReference = FirebaseDatabase.getReference("story").child(storyPosition); storyDatabaseReference.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { tvTitle = findViewById(R.id.titleTextView); tvTitle.setText(dataSnapshot.child("title").getValue(String.class)); tvDate = findViewById(R.id.dateTextView); tvDate.setText(dataSnapshot.child("date").getValue(String.class)); commentCount = dataSnapshot.child("commentCount").getValue(int.class); storyLikeCount = dataSnapshot.child("likeCount").getValue(int.class); tvLikeCount.setText(storyLikeCount + "명이 응원합니다!"); } @Override public void onCancelled(@NonNull DatabaseError databaseError) { } }); // 스토리 컨텐츠(text) 불러오기 storyDatabaseReference.child("text").addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) { String text = postSnapshot.getValue(String.class); storyTextList.add(text); } } @Override public void onCancelled(@NonNull DatabaseError databaseError) { } }); // 스토리 컨텐츠(img) 불러오기 storyDatabaseReference.child("img").addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) { String img = postSnapshot.getValue(String.class); storyImgList.add(img); } setStoryContentLayout(0, 0); } @Override public void onCancelled(@NonNull DatabaseError databaseError) { } }); // 보호소 프로필 불러오기 shelterDatabaseReference = FirebaseDatabase.getReference("shelter").child(shelterPosition); shelterDatabaseReference.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { String img = dataSnapshot.child("profileImg").getValue(String.class); tvShelterName = findViewById(R.id.shelterNameTextView); tvShelterName.setText(dataSnapshot.child("name").getValue(String.class)); ivShelterImg = findViewById(R.id.shelterProfileImageView); Picasso.get().load(img).into(ivShelterImg); } @Override public void onCancelled(@NonNull DatabaseError databaseError) { } }); //스토리 좋아요 버튼 기능 구현 Query storyLikeQuery = storyDatabaseReference.child("liker").child(userName); storyDatabaseReference.child("liker").child("sookhee").addChildEventListener(new ChildEventListener() { @Override public void onChildAdded(@NonNull DataSnapshot dataSnapshot, @Nullable String s) { boolean isLike = (Boolean) dataSnapshot.getValue(); if (isLike == true) { btnStoryLike.setBackgroundResource(R.drawable.icon_like_blue); setIsLike(true); } else { btnStoryLike.setBackgroundResource(R.drawable.icon_like_gray); setIsLike(false); } } @Override public void onChildChanged(@NonNull DataSnapshot dataSnapshot, @Nullable String s) { boolean isLike = (boolean) dataSnapshot.getValue(); if (isLike == true) { btnStoryLike.setBackgroundResource(R.drawable.icon_like_blue); setIsLike(true); } else { btnStoryLike.setBackgroundResource(R.drawable.icon_like_gray); setIsLike(false); } } @Override public void onChildRemoved(@NonNull DataSnapshot dataSnapshot) { } @Override public void onChildMoved(@NonNull DataSnapshot dataSnapshot, @Nullable String s) { } @Override public void onCancelled(@NonNull DatabaseError databaseError) { } }); btnStoryLike.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (isLike) { //true -> false Map<String, Object> isLikeMap = new HashMap<String, Object>(); isLikeMap.put(putUserIsLike, false); Map<String, Object> storyCountMap = new HashMap<String, Object>(); storyCountMap.put("likeCount", storyLikeCount - 1); storyDatabaseReference.child("liker").updateChildren(isLikeMap); storyDatabaseReference.updateChildren(storyCountMap); } else { //false -> true Map<String, Object> isLikeMap = new HashMap<String, Object>(); isLikeMap.put(putUserIsLike, true); Map<String, Object> storyCountMap = new HashMap<String, Object>(); storyCountMap.put("likeCount", storyLikeCount + 1); storyDatabaseReference.child("liker").updateChildren(isLikeMap); storyDatabaseReference.updateChildren(storyCountMap); } } }); // 스토리 댓글 기능 구현 storyDatabaseReference.child("comment").addChildEventListener(new ChildEventListener() { @Override public void onChildAdded(@NonNull DataSnapshot dataSnapshot, @Nullable String s) { String key = dataSnapshot.getKey(); CommentData commentData = dataSnapshot.getValue(CommentData.class); adapter.addDataAndUpdate(key, commentData); } @Override public void onChildChanged(@NonNull DataSnapshot dataSnapshot, @Nullable String s) { String key = dataSnapshot.getKey(); CommentData commentData = dataSnapshot.getValue(CommentData.class); adapter.addDataAndUpdate(key, commentData); } @Override public void onChildRemoved(@NonNull DataSnapshot dataSnapshot) { String key = dataSnapshot.getKey(); adapter.deleteDataAndUpdate(key); } @Override public void onChildMoved(@NonNull DataSnapshot dataSnapshot, @Nullable String s) { } @Override public void onCancelled(@NonNull DatabaseError databaseError) { } }); adapter = new CommentAdapter(this); mLayoutManager = new LinearLayoutManager(this); mLayoutManager.setReverseLayout(true); mLayoutManager.setStackFromEnd(true); recyclerView.setLayoutManager(mLayoutManager); recyclerView.setAdapter(adapter); // 댓글 작성 etComment = findViewById(R.id.storyDetailCommentEditText); tvCommentSubmit = findViewById(R.id.storyDetailCommentSubmitButton); tvCommentSubmit.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String message = etComment.getText().toString(); if (!TextUtils.isEmpty(message)) { etComment.setText(""); CommentData commentData = new CommentData(); commentData.setName(userName); commentData.setContent(message); commentData.setImg(userProfile); storyDatabaseReference.child("comment").push().setValue(commentData); Map<String, Object> commentCountMap = new HashMap<String, Object>(); commentCountMap.put("commentCount", commentCount + 1); storyDatabaseReference.updateChildren(commentCountMap); } } }); } public void onBackClick(View v) { super.onBackPressed(); } public void setIsLike(boolean isLike) { this.isLike = isLike; } public void onShelterProfileClick(View v) { Intent intent; intent = new Intent(v.getContext(), ShelterProfileActivity.class); intent.putExtra("shelterPosition", shelterPosition); startActivity(intent); } public void setStoryContentLayout(int text, int img) { lStoryContent.removeAllViews(); do { if (text < storyTextList.size()) { TextView tv = new TextView(this); tv.setText(storyTextList.get(text)); tv.setLineSpacing(0, 1.1f); tv.setPadding(0, (int) convertDpToPixel(15), 0, 0); tv.setTypeface(ResourcesCompat.getFont(this, R.font.notosanscjkkr_regular)); tv.setIncludeFontPadding(false); tv.setTextColor(Color.BLACK); lStoryContent.addView(tv); } if (img < storyImgList.size()) { ImageView iv = new ImageView(this); Picasso.get().load(storyImgList.get(img)).into(iv); iv.setScaleType(ImageView.ScaleType.CENTER_CROP); iv.setPadding(0, (int) convertDpToPixel(15), 0, 0); lStoryContent.addView(iv); } text++; img++; } while (text < storyTextList.size() || img < storyImgList.size()); } public float convertDpToPixel(float dp) { Resources resources = this.getResources(); DisplayMetrics metrics = resources.getDisplayMetrics(); float px = dp * ((float) metrics.densityDpi / DisplayMetrics.DENSITY_DEFAULT); return px; } }
/** * @ExServ.java (Lab 4 - CSC583B) *@Using the ExecutorService Interface * * @Geoffrey Paulsen * @2011/9/28 */ import java.io.*; import java.security.*; import java.util.*; import java.util.concurrent.Executors; import java.util.concurrent.ExecutorService; public class ExServ { private File d; //constructor method receives directory of files as arg public ExServ (File directory) { d = directory; //ExecutorService interface creates a pool of 5 threads ExecutorService pool = Executors.newFixedThreadPool(5); //each file in directory is passed through the handler for(File file : d.listFiles()) { Handler h = new Handler (file); pool.execute(h); } //close pool when there are no more files to process pool.shutdown(); } public static void main(String[] args) { //main method gets directory of files input from user Scanner in = new Scanner(System.in); System.out.print("Enter file directory to process: "); String filePath = in.nextLine(); System.out.println("Digest for each file:"); File dir = new File(filePath); if (!dir.isDirectory()) System.out.println("\nSelected file is not a directory or does not exist.\n"); //constructor method is called with directory of files passed as arg ExServ es = new ExServ(dir); } ///inner class creates runnable object class Handler implements Runnable { private File f; Handler (File f) { this.f = f; } //section of code from Lab 3 solution employed here public void run() { try { FileInputStream in = new FileInputStream(f); MessageDigest sha = MessageDigest.getInstance("SHA"); DigestInputStream din = new DigestInputStream(in, sha); int b; while ((b = din.read()) != -1) ; din.close(); byte[] digest = sha.digest(); StringBuffer result = new StringBuffer(f.toString()); result.append(": "); for (int i = 0; i < digest.length; i++) { result.append(digest[i] + " "); } System.out.println(result); } catch (IOException e) { System.err.println(e); } catch (NoSuchAlgorithmException e) { System.err.println(e); } } } }
package com.kgitbank.spring.domain.model.mapper; import java.util.List; import org.apache.ibatis.annotations.Select; import com.kgitbank.spring.domain.model.MemberVO; public interface MemberMapper { public List<MemberVO> selectAll(); public void insertMember(MemberVO member); }
package crundle.qralarmclock; import java.io.Serializable; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; public class Alarm implements Comparable, Serializable { private String alarmTime; //string of the alarmTime in 24 hour format private boolean isActive; private int hour; //1-12 private int min; //0-60 private boolean AM; private String alarm_id; // 0 = Sun, 1 = Mon, 2 = Tues, etc. boolean[] daysActive = new boolean[]{false,false,false,false,false,false,false}; public String getAlarmTime() { return alarmTime; } public void setAlarmTime(String alarmTime) { this.alarmTime = alarmTime; } public void setHour(int a){ hour = a; } public int getHour(){ return hour; } public void setAM(boolean a){ AM = a; } public boolean getAM(){ return AM; } public void setMin(int a){ min = a; } public int getMin(){ return min; } public boolean isActive() { return isActive; } public void setActive(boolean active) { isActive = active; } public boolean getDaysActive(int i) { return daysActive[i]; } // i = day of the week. // 0 = Sun, 1 = Mon, 2 = Tues, etc. public void setDaysActive(int i) { if (daysActive[i] == false){ daysActive[i] = true; } else { daysActive[i] = false; } } //returns 1 if this is after a, 0 if equal, and -1 if this is before a, @Override public int compareTo(Object o){ Alarm a = (Alarm)o; String thisTime = alarmTime; String aTime = a.getAlarmTime(); SimpleDateFormat sdf = new SimpleDateFormat("HH:mm"); Date d1 = null; Date d2 = null; try { d1 = sdf.parse(thisTime); d2 = sdf.parse(aTime); } catch (ParseException e) { e.printStackTrace(); } long difference = d2.getTime() - d1.getTime(); int result; if(difference > 0) result = -1; else if(difference < 0) result = 1; else result = 0; return result; } public String getAlarm_id() { return alarm_id; } public void setAlarm_id(String alarm_id) { this.alarm_id = alarm_id; } }
package nl.jtosti.hermes.location; import nl.jtosti.hermes.company.Company; import java.util.List; public interface LocationServiceInterface { Location getLocationById(Long id); List<Location> getAllLocations(); boolean exists(Long id); Location save(Location location); List<Location> getLocationsByCompanyId(Long companyId); Location update(Location location); void delete(Long id); Location removeAdvertisingCompanyFromLocation(Location location, Company company); List<Location> getAdvertisingLocationsByCompanyId(Long companyId); List<Location> getAdvertisingLocationsByUserId(Long userId); List<Location> getPersonalLocationsByUserId(Long userId); List<Location> getAllLocationsByUserId(Long userId); }
package com.fleet.sqlite.service; import com.fleet.sqlite.entity.User; import java.util.List; public interface UserService { int insert(User user); int delete(Long id); int update(User user); User get(Long id); List<User> list(); }
package com.tencent.mm.plugin.appbrand.config; import com.tencent.mm.ab.v; import com.tencent.mm.plugin.appbrand.app.e; import com.tencent.mm.protocal.c.byl; import com.tencent.mm.protocal.c.zc; import com.tencent.mm.protocal.c.zd; import com.tencent.mm.protocal.c.ze; import com.tencent.mm.sdk.platformtools.bi; import com.tencent.mm.sdk.platformtools.x; import java.util.Iterator; import java.util.LinkedList; public final class m { public static class a { private static String as(String str, int i) { return String.format("%s_%s_local_version", new Object[]{str, Integer.valueOf(i)}); } public static String at(String str, int i) { return String.format("%s_%s_server_version", new Object[]{str, Integer.valueOf(i)}); } private static String au(String str, int i) { return String.format("%s_%s_config", new Object[]{str, Integer.valueOf(i)}); } public static void A(String str, int i, int i2) { if (e.abf() != null) { e.abf().bd(as(str, i), String.valueOf(i2)); } } public static void B(String str, int i, int i2) { if (e.abf() != null) { e.abf().bd(at(str, i), String.valueOf(i2)); } } public static void h(String str, int i, String str2) { if (e.abf() != null) { e.abf().bd(au(str, i), str2); } } public static int av(String str, int i) { if (e.abf() == null) { return 0; } return bi.getInt(e.abf().get(as(str, i), "0"), 0); } public static String aw(String str, int i) { if (e.abf() == null) { return ""; } return e.abf().get(au(str, i), ""); } } public interface b { void a(int i, int i2, String str, com.tencent.mm.ab.b bVar); } public interface c { void qR(String str); } public static void a(String str, LinkedList<byl> linkedList) { a(str, linkedList, true); } public static void a(String str, LinkedList<byl> linkedList, boolean z) { if (bi.oW(str)) { x.e("MicroMsg.CommonConfigManager", "setVersion, app_id is null"); } else if (linkedList == null || linkedList.size() == 0) { x.e("MicroMsg.CommonConfigManager", "setVersion, versionItems is empty"); } else { LinkedList linkedList2 = new LinkedList(); Iterator it = linkedList.iterator(); while (it.hasNext()) { byl byl = (byl) it.next(); x.d("MicroMsg.CommonConfigManager", "versionItem.version:%d,version.type:%d", new Object[]{Integer.valueOf(byl.version), Integer.valueOf(byl.type)}); int av = a.av(str, byl.type); int i = byl.version; a.B(str, byl.type, i); if (i != 0) { if (i > av) { linkedList2.add(z(str, byl.type, byl.version)); } else if (i != av) { x.i("MicroMsg.CommonConfigManager", "local_version:%d, server_version:%d", new Object[]{Integer.valueOf(av), Integer.valueOf(i)}); if (bi.oW(a.aw(str, byl.type))) { linkedList2.add(z(str, byl.type, byl.version)); } } else if (bi.oW(a.aw(str, byl.type))) { linkedList2.add(z(str, byl.type, byl.version)); } } } x.i("MicroMsg.CommonConfigManager", "setVersion appid:%s,versionItems.size:%d,getAppConfigItems.size:%d", new Object[]{str, Integer.valueOf(linkedList.size()), Integer.valueOf(linkedList2.size())}); if (z && linkedList2.size() != 0) { x.d("MicroMsg.CommonConfigManager", "setVersion appid:%s, need sync from server", new Object[]{str}); a(linkedList2, new 1(str)); } } } private static zc z(String str, int i, int i2) { zc zcVar = new zc(); zcVar.jQb = str; zcVar.hcE = i; zcVar.rcV = i2; return zcVar; } public static String a(String str, int i, int i2, c cVar, boolean z) { if (e.abf() == null) { return ""; } boolean z2; int av = a.av(str, i); int i3 = e.abf() == null ? 0 : bi.getInt(e.abf().get(a.at(str, i), "0"), 0); String aw = a.aw(str, i); if (i3 == 0 || (!bi.oW(aw) && i3 <= av)) { z2 = false; } else { z2 = true; } x.i("MicroMsg.CommonConfigManager", "getConfig the server_version is %d ,the local_version is %d", new Object[]{Integer.valueOf(i3), Integer.valueOf(av)}); x.i("MicroMsg.CommonConfigManager", "the config is \n %s \n isShouldSyncFromServer:%b", new Object[]{aw, Boolean.valueOf(z2)}); if (!z2) { cVar.qR(aw); } else if (z) { b 2 = new 2(cVar, str); LinkedList linkedList = new LinkedList(); zc zcVar = new zc(); zcVar.jQb = str; zcVar.hcE = i; zcVar.rcV = i3; zcVar.rFj = i2; linkedList.add(zcVar); a(linkedList, 2); } return aw; } private static void a(LinkedList<zc> linkedList, b bVar) { com.tencent.mm.ab.b.a aVar = new com.tencent.mm.ab.b.a(); aVar.dIF = 1138; aVar.uri = "/cgi-bin/mmbiz-bin/wxausrevent/getappconfig"; aVar.dIH = new ze(); aVar.dII = 0; aVar.dIJ = 0; zd zdVar = new zd(); zdVar.rFk = linkedList; aVar.dIG = zdVar; v.a(aVar.KT(), new 3(bVar), true); } }
package com.ssgl.util; /* * 功能: * User: jiajunkang * email:jiajunkang@outlook.com * Date: 2018/1/5 0005 * Time: 20:14 */ import java.util.ArrayList; import java.util.List; public class StringUtils { /** * 字符串转换为list * @param string * @return */ public static List<String> stringConvertList(String string){ String[] ids = string.split(","); List<String> list = new ArrayList<>(); for (int i = 0;i<ids.length;i++){ list.add(ids[i]); } return list; } }
package com.cy.pj.sys.dao; import java.util.List; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Param; import org.apache.ibatis.annotations.Update; import com.cy.pj.common.vo.SysUserDeptVo; import com.cy.pj.sys.entity.SysUser; @Mapper public interface SysUserDao { /* * 说明: 1>当DAO中方法参数多余一个时尽量使用@Param注解进行修饰并指定名字,然后在Mapper文件中便可以通过类似#{username}方式进行获取,否则只能通过#{arg0},#{arg1}或者#{param1},#{param2}等方式进行获取。 2>当DAO方法中的参数应用在动态SQL中时无论多少个参数,尽量使用@Param注解进行修饰并定义。 3>jdk8后可以不用,可变参数时需要用到,如果没有使用@Param,则需要在映射的生sql文件中需要用array来接收 */ @Update("update sys_users set password=#{password},salt=#{salt},modifiedTime=now() where username=#{username}") int updatePassword(String username,String password,String salt); SysUser findUserByUserName(String username); /** * 根据username来查询 * @param username * @return */ int getRowCount(@Param("username")String username); /** * 页面数据呈现的查询 * @param username * @return */ List<SysUserDeptVo> findPageObjects(String username); /** * 启动、禁用的更改 * @param id * @param valid * @param modifiedUser * @return */ int validById(@Param("id") Integer id,@Param("valid") Integer valid,@Param("modifiedUser") String modifiedUser); /** * 数据的添加 * @param entity * @return */ int insertObject(SysUser entity); /** * 根据id查询 * @param id * @return */ SysUserDeptVo findObjectById(Integer id); /** * 根据id更新数据 * @param id * @return */ int updateObjectById(SysUser entity); }
package orcsoft.todo.fixupappv2.Activities; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.design.widget.Snackbar; import android.support.v7.app.AppCompatActivity; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.TextView; import org.androidannotations.annotations.AfterViews; import org.androidannotations.annotations.Background; import org.androidannotations.annotations.Click; import org.androidannotations.annotations.EActivity; import org.androidannotations.annotations.ViewById; import java.util.ArrayList; import java.util.List; import java.util.Map; import orcsoft.todo.fixupappv2.Adapters.AbstractItemsAdapter; import orcsoft.todo.fixupappv2.Entity.AbstractItem; import orcsoft.todo.fixupappv2.Entity.CloseOrderRequest; import orcsoft.todo.fixupappv2.Entity.Order; import orcsoft.todo.fixupappv2.Entity.Product; import orcsoft.todo.fixupappv2.Entity.Service; import orcsoft.todo.fixupappv2.Operations; import orcsoft.todo.fixupappv2.R; import orcsoft.todo.fixupappv2.Utils.NetHelper; import orcsoft.todo.fixupappv2.Utils.NetHelper_; @EActivity(R.layout.activity_order_closing) public class OrderClosingActivity extends AppCompatActivity implements AbstractItemsAdapter.OnAdapterInteractionListener { private Order currentOrder; private List<Service> services; private List<Product> products; private NetHelper netHelper; private List<AbstractItem> abstractItems = new ArrayList<AbstractItem>(); private AbstractItemsAdapter abstractItemsAdapter; @ViewById(R.id.items_list_view) protected ListView listView; @ViewById(R.id.sum_value) protected TextView sumValue; @ViewById(R.id.parent_layout) protected LinearLayout parentLaoyut; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); currentOrder = getIntent().getParcelableExtra(Operations.ORDER_ENTITY); netHelper = NetHelper_.getInstance_(getBaseContext()); init(); } @AfterViews protected void initList() { abstractItemsAdapter = new AbstractItemsAdapter(abstractItems, this); listView.setAdapter(abstractItemsAdapter); sumValue.setText("0"); } @Background protected void init() { try { services = netHelper.getServices(); products = netHelper.getProducts(); } catch (Exception e) { e.printStackTrace(); } } @Click(R.id.add_service) protected void buttonAddService() { AlertDialog.Builder builder = new AlertDialog.Builder(this); String[] items = new String[services.size()]; for (int i = 0; i < services.size(); ++i) { Service service = services.get(i); items[i] = (service.getTitle() + " - " + service.getCost()); } builder.setTitle("Услуги") .setItems(items, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { abstractItems.add(services.get(which)); abstractItemsAdapter.notifyDataSetChanged(); } }) .create() .show(); } @Click(R.id.add_product) protected void buttonAddProduct() { AlertDialog.Builder builder = new AlertDialog.Builder(this); String[] items = new String[products.size()]; for (int i = 0; i < products.size(); ++i) { Product product = products.get(i); items[i] = (product.getTitle() + " - " + product.getCost()); } builder.setTitle("Продукты") .setItems(items, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { abstractItems.add(products.get(which)); abstractItemsAdapter.notifyDataSetChanged(); } }) .create() .show(); } @Override public void onAdapterInteraction() { Map<Integer, Integer> counts = abstractItemsAdapter.getCounts(); Integer sumCount = 0; for (int i = 0; i < abstractItems.size(); ++i) { if (counts.containsKey(i)) { sumCount += counts.get(i) * abstractItems.get(i).getCost(); } } sumValue.setText(String.valueOf(sumCount)); } @Background @Click(R.id.close_order) protected void closeOrder() { Map<Integer, Integer> counts = abstractItemsAdapter.getCounts(); for (int i = 0; i < abstractItems.size(); ++i) { if (counts.containsKey(i)) { abstractItems.get(i).setCount(counts.get(i)); } } if(abstractItems.isEmpty()){ Snackbar.make(parentLaoyut, R.string.error_message_empty_items, Snackbar.LENGTH_LONG).show(); return; } List<Product> productsForRequest = new ArrayList<Product>(); List<Service> servicesForRequest = new ArrayList<Service>(); for (AbstractItem abstractItem : abstractItems) { if (Product.class.equals(abstractItem.getClass())) { productsForRequest.add((Product) abstractItem); } else if (Service.class.equals(abstractItem.getClass())) { servicesForRequest.add((Service) abstractItem); } else { throw new IllegalArgumentException(); } } CloseOrderRequest closeOrderRequest = new CloseOrderRequest(productsForRequest, servicesForRequest); try { NetHelper.CommonResponseMessage responseMessage = NetHelper_.getInstance_(this).closeOrder(currentOrder, closeOrderRequest); if(0 != responseMessage.code){ Snackbar.make(parentLaoyut, responseMessage.code + " " + responseMessage.message, Snackbar.LENGTH_LONG).show(); } else { Bundle bundle = new Bundle(); bundle.putString(Operations.ORDERS_FRAGMENT_WITH_RELOAD, Operations.YES); MenuActivity_.intent(this) .flags(Intent.FLAG_ACTIVITY_CLEAR_TOP) .extra(Operations.ORDERS_FRAGMENT_WITH_RELOAD, Operations.YES) .start(); } } catch (Exception e) { e.printStackTrace(); Snackbar.make(parentLaoyut, e.getMessage(), Snackbar.LENGTH_LONG).show(); } } }
//William Suter //The purpose of this project is to create a program that will store and display loved ones wish lists and special dates. //The program will also display this information requested by the user import java.io.File; import java.io.IOException; public class GroupGProject { public static void main(String[] args) { File initDirectory = new File("C:\\GroupGProject"); if(!initDirectory.exists()) { initDataBase(); } UserGui begin = new UserGui(); begin.startGui(); } //This will initialize the database if it does not exist public static void initDataBase() { String parent = "C:\\GroupGProject"; File directory = new File(parent); directory.mkdir(); String personList = parent + File.separator + "Names.txt"; String tempList = parent + File.separator + "temp.txt"; File nameList = new File(personList); File temp = new File(tempList); try { if(!nameList.exists()) { nameList.createNewFile(); temp.createNewFile(); } } catch(IOException e){} } }
package com.niloy.dxball_new; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.Window; import android.view.WindowManager; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN); } @Override protected void onResume(){ super.onResume(); try{ setContentView(new GameCanvas(this)); } catch (Exception e){ Log.d("Exception",e.getMessage()); } } @Override protected void onStart(){ super.onStart(); } }
package co.th.aten.football.ui.report; import java.awt.BorderLayout; import java.awt.Color; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.image.BufferedImage; import java.io.File; import java.io.FileOutputStream; import javax.imageio.ImageIO; import javax.swing.BorderFactory; import javax.swing.Box; import javax.swing.BoxLayout; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JComponent; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.UIManager; import com.jensoft.sw2d.core.democomponent.ImageResource; import com.jensoft.sw2d.core.democomponent.Sw2dDemo; import com.jensoft.sw2d.core.view.View2D; import com.jensoft.core.view.View; public class TemplateReportFrame extends JFrame { private static final long serialVersionUID = 156889765687899L; private Sw2dDemo demo; private View2D view; public void show(Sw2dDemo demo) { this.demo = demo; try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (Exception e) { } ImageIcon iconFrame = new ImageIcon(System.getProperty("user.dir") + "/img" + File.separator + "jensoft.png"); setIconImage(iconFrame.getImage()); setTitle("M7"); getContentPane().removeAll(); getContentPane().setLayout(new BorderLayout()); // setDefaultCloseOperation(EXIT_ON_CLOSE); JPanel masterPane = new JPanel(); masterPane.setBackground(Color.BLACK); masterPane.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20)); masterPane.setLayout(new BorderLayout()); // ComandBar cbar = new ComandBar(); // cbar.setTitle("Report"); // ComandGroup c1 = new ComandGroup("Report"); // c1.setTabColor(Color.DARK_GRAY); // ImageIcon icon1 = // ImageResource.getInstance().createImageIcon("/icons/jensoft.png", // ""); // c1.setTabIcon(icon1); // cbar.addComandTab(c1, demo.createView2D()); // c1.setSelected(true); masterPane.add(demo.createView2D(), BorderLayout.CENTER); masterPane.add(new PanelButton(), BorderLayout.NORTH); getContentPane().add(masterPane, BorderLayout.CENTER); setVisible(true); } public void show(View view) { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (Exception e) { } ImageIcon iconFrame = new ImageIcon(System.getProperty("user.dir") + "/img" + File.separator + "jensoft.png"); setIconImage(iconFrame.getImage()); setTitle("M7"); getContentPane().removeAll(); getContentPane().setLayout(new BorderLayout()); // setDefaultCloseOperation(EXIT_ON_CLOSE); JPanel masterPane = new JPanel(); masterPane.setBackground(Color.BLACK); masterPane.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20)); masterPane.setLayout(new BorderLayout()); masterPane.add(view, BorderLayout.CENTER); masterPane.add(new PanelButton(), BorderLayout.NORTH); getContentPane().add(masterPane, BorderLayout.CENTER); setVisible(true); } class PanelButton extends JComponent { public PanelButton() { setLayout(new BoxLayout(this, BoxLayout.X_AXIS)); setOpaque(false); JButton copy = new JButton("Save"); copy.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // Display display = new Display(); // Shell shell = new Shell(display); // FileDialog dialog = new FileDialog(shell, SWT.SAVE); // dialog.setFilterPath("c:\\"); // Windows path // dialog.setFilterExtensions(new String[] { "*.png" }); // System.out.println("Save to: " + dialog.open()); // // String name = dialog.getFileName(); // try { // View2D v = view; // // int w = (int) view.getBounds().getWidth(); // int h = (int) view.getBounds().getHeight(); // // BufferedImage image = v.getImageView(w, h); // String portfolioDirectory = dialog.getFilterPath(); // File portfolioDir = new File(portfolioDirectory); // portfolioDir.mkdirs(); // try { // FileOutputStream out = new FileOutputStream(portfolioDirectory // + File.separator + name); // ImageIO.write(image, "png".toLowerCase(), out); // out.close(); // display.dispose(); // } catch (Exception ex) { // ex.printStackTrace(); // } // } catch (Throwable ex) { // ex.printStackTrace(); // } // // JOptionPane.showMessageDialog(null, "save image // // complete"); } }); add(Box.createGlue()); add(copy); add(Box.createHorizontalStrut(40)); } } public View2D getView() { return view; } public void setView(View2D view) { this.view = view; } }
package com.redhat.examples.iot.sensor; import javax.annotation.PostConstruct; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; import com.redhat.examples.iot.model.Measure; @Component(SensorType.GPS) @Scope("prototype") public class GpsSensor implements Sensor { @Value("${sensor.gps.enabled}") private boolean enabled; @Value("${sensor.gps.frequency}") private int frequency; @Value("${sensor.gps.initialLatitude}") private double initialLatitude; @Value("${sensor.gps.initialLongitude}") private double initialLongitude; @Value("${sensor.gps.iterationLongitude}") private double iterationLatitude; @Value("${sensor.gps.iterationLongitude}") private double iterationLongitude; @Value("${sensor.gps.finalLatitude}") private double finalLatitude; @Value("${sensor.gps.finalLongitude}") private double finalLongitude; private double currentLongitude; private double currentLatitude; private int count = 0; @PostConstruct @Override public void initAndReset() { currentLongitude = initialLongitude; currentLatitude = initialLatitude; } @Override public int getFrequency() { return frequency; } @Override public String getType() { return SensorType.GPS; } @Override public boolean isEnabled() { return enabled; } @Override public Measure calculateCurrentMeasure(Measure measure) { if(count > 0) { currentLatitude = currentLatitude + iterationLatitude; currentLongitude = currentLongitude + iterationLongitude; if(currentLatitude <= finalLatitude && currentLongitude <= finalLongitude) { initAndReset(); } } String payload = formatPayload(currentLatitude, currentLongitude); measure.setType(getType()); measure.setPayload(String.valueOf(payload)); ++count; return measure; } private String formatPayload(double latitude, double longitude) { StringBuilder sb = new StringBuilder(); sb.append(latitude); sb.append("|"); sb.append(longitude); return sb.toString(); } }
/* * Ada Sonar Plugin * Copyright (C) 2010 Akram Ben Aissi * dev@sonar.codehaus.org * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 */ package org.sonar.plugins.ada.lexer; import java.util.List; import org.apache.commons.lang.ArrayUtils; import org.sonar.channel.Channel; import org.sonar.channel.CodeReader; import org.sonar.channel.EndMatcher; /** * */ abstract class AbstractTokenizer<T extends List<Node>> extends Channel<T> { private final class EndTokenMatcher implements EndMatcher { private final CodeReader codeReader; private boolean quoting; private int nesting; private EndTokenMatcher(CodeReader codeReader) { this.codeReader = codeReader; } public boolean match(int endFlag) { if (endFlag == '"') { quoting = !quoting; } if ( !quoting) { boolean started = ArrayUtils.isEquals(codeReader.peek(startChars.length), startChars); if (started) { nesting++; } else { boolean ended = ArrayUtils.isEquals(codeReader.peek(endChars.length), endChars); if (ended) { nesting--; return nesting < 0; } } } return false; } } private final char[] endChars; private final char[] startChars; public AbstractTokenizer(String startChars, String endChars) { this.startChars = startChars.toCharArray(); this.endChars = endChars.toCharArray(); } protected void addNode(List<Node> nodeList, Node node) { nodeList.add(node); } @Override public boolean consume(CodeReader codeReader, T nodeList) { if (ArrayUtils.isEquals(codeReader.peek(startChars.length), startChars)) { Node node = createNode(); setStartPosition(codeReader, node); StringBuilder stringBuilder = new StringBuilder(); codeReader.popTo(new EndTokenMatcher(codeReader), stringBuilder); for (int i = 0; i < endChars.length; i++) { codeReader.pop(stringBuilder); } node.setCode(stringBuilder.toString()); setEndPosition(codeReader, node); addNode(nodeList, node); return true; } else { return false; } } abstract Node createNode(); protected final void setEndPosition(CodeReader code, Node node) { node.setEndLinePosition(code.getLinePosition()); node.setEndColumnPosition(code.getColumnPosition()); } protected final void setStartPosition(CodeReader code, Node node) { node.setStartLinePosition(code.getLinePosition()); node.setStartColumnPosition(code.getColumnPosition()); } }
package br.com.univag.dao; import br.com.univag.exception.DaoException; import br.com.univag.fabricaConexao.Conexao; import br.com.univag.model.VeiculoVo; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; /** * * @author CRISTIANO */ public class VeiculoDao { Connection con; private PreparedStatement stm; private ResultSet rs; public VeiculoDao(Connection con) { this.con = con; } public void salvarVeiculo(VeiculoVo veiculo) throws DaoException { String sql = "insert into veiculo(placa_veiculo,status_veiculo) values (?,?)"; int i = 1; try { stm = con.prepareStatement(sql, PreparedStatement.RETURN_GENERATED_KEYS); stm.setString(i++, veiculo.getPlaca()); stm.setInt(i++, veiculo.getStatus()); stm.executeUpdate(); rs = stm.getGeneratedKeys(); while (rs.next()) { veiculo.setCodigo(rs.getInt(1)); } } catch (Exception e) { e.getMessage(); throw new DaoException("Erro no Dao cadastro de veiculos", e.getCause()); } finally { Conexao.close(stm, rs); } } @SuppressWarnings("null") public VeiculoVo selecionarVeiculoVoPorPlaca(String placa) throws DaoException { String sql = "select * from veiculo where placa_veiculo = ?"; VeiculoVo veiculo = null; int i = 0; try { stm = con.prepareStatement(sql); stm.setString(1, placa); rs = stm.executeQuery(); while (rs.next()) { veiculo = new VeiculoVo(); veiculo.setCodigo(rs.getInt(1)); veiculo.setPlaca(rs.getString(2)); veiculo.setStatus(rs.getInt(3)); i++; } if (i > 1) { throw new DaoException("Retornou mais de um registro"); } } catch (SQLException ex) { throw new DaoException("Erro retorno veiculo pela placa", ex.getCause()); } finally { Conexao.close(stm, rs); } return veiculo; } @SuppressWarnings("null") public VeiculoVo selecionarVeiculoVoByCodigo(int codigo) throws DaoException { String sql = "select * from veiculo where id_veiculo = ?"; VeiculoVo veiculo = new VeiculoVo(); int i = 0; try { stm = con.prepareStatement(sql); stm.setInt(1, codigo); rs = stm.executeQuery(); while (rs.next()) { veiculo.setCodigo(rs.getInt(1)); veiculo.setPlaca(rs.getString(2)); veiculo.setStatus(rs.getInt(3)); i++; } if (i > 1) { throw new DaoException("Retornou mais de um registro"); } } catch (SQLException ex) { throw new DaoException("Erro retorno veiculo pelo codigo", ex.getCause()); } finally { Conexao.close(stm, rs); } return veiculo; } public List<VeiculoVo> listVeiculoVo() throws DaoException { String sql = "select * from veiculo"; List<VeiculoVo> lista = new ArrayList<>(); try { stm = con.prepareStatement(sql); rs = stm.executeQuery(); while (rs.next()) { VeiculoVo vo = new VeiculoVo(); vo.setCodigo(rs.getInt(1)); vo.setPlaca(rs.getString(2)); vo.setStatus(rs.getInt(3)); lista.add(vo); } } catch (SQLException ex) { throw new DaoException("Erro na listagem de veiculos", ex.getCause()); } finally { Conexao.close(stm, rs); } if (lista.size() > 0) { return lista; } return null; } public void updateStatusVeiculoVo(VeiculoVo vo) throws DaoException { String sql = "update veiculo set status_veiculo=? where id_veiculo=?"; try { stm = con.prepareStatement(sql); stm.setInt(1, vo.getStatus()); stm.setInt(2, vo.getCodigo()); stm.executeUpdate(); } catch (SQLException ex) { throw new DaoException("Erro ao alterar veiculo", ex.getCause()); } finally { Conexao.close(stm); } } public void deleteVeiculoVo(int codigo) throws DaoException { String sql = "delete from veiculo where id_veiculo = ?"; try { stm = con.prepareStatement(sql); stm.setInt(1, codigo); stm.executeUpdate(); } catch (SQLException ex) { throw new DaoException("Erro ao excluir veiculo", ex.getCause()); } finally { Conexao.close(stm); } } public int totalVeiculoVoAtivo() throws DaoException { String sql = "SELECT Count(*) AS quantidade FROM veiculo where status_veiculo = 1 "; int total = 0; try { stm = con.prepareStatement(sql); rs = stm.executeQuery(); if (rs.next()) { total = rs.getInt("quantidade"); } } catch (SQLException ex) { throw new DaoException("Erro ao contar tabela veiculo", ex.getCause()); } return total; } }
package com.beebox.blood.shewalfare; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.LinearLayout; import android.widget.Toast; import com.beardedhen.androidbootstrap.BootstrapButton; import com.google.android.gms.ads.AdListener; import com.google.android.gms.ads.AdRequest; import com.google.android.gms.ads.AdView; import com.google.android.gms.ads.InterstitialAd; /** * A simple {@link Fragment} subclass. */ public class BlankFragment extends Fragment implements View.OnClickListener { LinearLayout linearLayout; BootstrapButton button1,button2,button3; ConnectionDetector cd; Boolean isInternetPresent = false; InterstitialAd minterstital; public BlankFragment() { // Required empty public constructor } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { linearLayout = (LinearLayout)inflater.inflate(R.layout.fragment_blank, container, false); button1 = (BootstrapButton)linearLayout.findViewById(R.id.donorfragment1); button2 = (BootstrapButton)linearLayout.findViewById(R.id.donorfragment2); button3 = (BootstrapButton)linearLayout.findViewById(R.id.donorfragment3); minterstital = new InterstitialAd(getContext()); minterstital.setAdUnitId(getResources().getString(R.string.interstitial_ad_unit_id)); final AdRequest adRequest = new AdRequest.Builder().build(); minterstital.loadAd(adRequest); minterstital.setAdListener(new AdListener() { @Override public void onAdLoaded() { super.onAdLoaded(); minterstital.show(); } }); button1.setOnClickListener(this); button2.setOnClickListener(this); button3.setOnClickListener(this); cd = new ConnectionDetector(getContext()); // Inflate the layout for this fragment return linearLayout; } @Override public void onClick(View v) { isInternetPresent = cd.isConnectingToInternet(); if (v.getId() == R.id.donorfragment1) { if (!isInternetPresent) { Toast.makeText(getContext(), "Please Check Your Internet Connection", Toast.LENGTH_LONG).show(); } else { getActivity().finish(); startActivity(new Intent(getContext(), MainActivity.class)); } } if (v.getId() == R.id.donorfragment2) { getActivity().finish(); startActivity(new Intent(getContext(),add_donations.class)); } if (v.getId() == R.id.donorfragment3) { getActivity().finish(); startActivity(new Intent(getContext(), my_donations.class)); } } }
package com.tencent.mm.plugin.recharge.ui; import com.tencent.mm.sdk.platformtools.x; import com.tencent.mm.ui.base.h.a; import java.util.List; class PhoneRechargeUI$13 implements a { final /* synthetic */ PhoneRechargeUI mqa; final /* synthetic */ List mqe; final /* synthetic */ String mqf; PhoneRechargeUI$13(PhoneRechargeUI phoneRechargeUI, List list, String str) { this.mqa = phoneRechargeUI; this.mqe = list; this.mqf = str; } public final void vh(int i) { x.d("MicroMsg.PhoneRechargeUI", "choose: %d", new Object[]{Integer.valueOf(i)}); PhoneRechargeUI.b(this.mqa).setInput(new com.tencent.mm.plugin.recharge.model.a((String) this.mqe.get(i), this.mqf, 1)); PhoneRechargeUI.n(this.mqa); } }
package com.ht.springboot_shiro.domain; /** * @company 宏图 * @User Kodak * @create 2019-06-03 -10:26 * @Email:2270301642@qq.com */ public class User { private Integer id; private String name; private String pwd; private String perms; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPwd() { return pwd; } public void setPwd(String pwd) { this.pwd = pwd; } public String getPerms() { return perms; } public void setPerms(String perms) { this.perms = perms; } }
package com.li.xiaomi.xiaomi_core.net; import android.content.Context; import com.li.xiaomi.xiaomi_core.net.callback.IError; import com.li.xiaomi.xiaomi_core.net.callback.IFailure; import com.li.xiaomi.xiaomi_core.net.callback.IRequest; import com.li.xiaomi.xiaomi_core.net.callback.ISuccess; import com.li.xiaomi.xiaomi_core.ui.LatteLoader; import com.li.xiaomi.xiaomi_core.ui.LoaderStyle; import java.io.File; import java.util.WeakHashMap; import okhttp3.MediaType; import okhttp3.RequestBody; /** * 作者:dell or Xiaomi Li * 时间: 2018/3/20 * 内容:建造者 * 最后修改: */ public class RestClientBuilder { private String mUrl; private static final WeakHashMap<String, Object> PARAMS = RestCreator.getParams(); private static final WeakHashMap<String, String> HEADS = RestCreator.getHeads(); private static String mDownloadFileName; private static String mDownloadFilePath; private static String mDownloadFileExtensionName; private IRequest mIrequest; private ISuccess mIsuccess; private IFailure mIfailure; private IError mIerror; private RequestBody mRequestBody; private File mFile; private Context mContext; private LoaderStyle mLoaderStyle; public RestClientBuilder() { } public final RestClientBuilder url(String url) { this.mUrl = url; return this; } public final RestClientBuilder heads(WeakHashMap<String, String> heads) { this.HEADS.putAll(heads); return this; } public final RestClientBuilder head(String key, String value) { this.HEADS.put(key, value); return this; } public final RestClientBuilder params(WeakHashMap<String, Object> params) { this.PARAMS.putAll(params); return this; } public final RestClientBuilder param(String key, Object value) { this.PARAMS.put(key, value); return this; } /** * 传递json串进来 * * @param raw * @return */ public final RestClientBuilder raw(String raw) { this.mRequestBody = RequestBody.create(MediaType.parse("application/json;charset=UTF-8"), raw); return this; } public final RestClientBuilder success(ISuccess iSuccess) { this.mIsuccess = iSuccess; return this; } public final RestClientBuilder request(IRequest iRequest) { this.mIrequest = iRequest; return this; } public final RestClientBuilder failure(IFailure iFailure) { this.mIfailure = iFailure; return this; } public final RestClientBuilder error(IError iError) { this.mIerror = iError; return this; } public final RestClientBuilder loadStyle(Context context, LoaderStyle loaderStyle) { this.mContext = context; this.mLoaderStyle = loaderStyle; return this; } public final RestClientBuilder loadStyle(Context context) { this.mContext = context; this.mLoaderStyle = LatteLoader.DEFAULT_LOADER; return this; } public final RestClientBuilder file(File file) { this.mFile = file; return this; } public final RestClientBuilder file(String filePath) { this.mFile = new File(filePath); return this; } public final RestClientBuilder downloadFileExtensionName(String downloadFileExtensionName) { this.mDownloadFileExtensionName = downloadFileExtensionName; return this; } public final RestClientBuilder downloadFileName(String downloadFileName) { this.mDownloadFileName = downloadFileName; return this; } public final RestClientBuilder downloadFilePath(String downloadFilePath) { this.mDownloadFilePath = downloadFilePath; return this; } public final RestClient build() { return new RestClient(mUrl, HEADS, PARAMS,mDownloadFileName,mDownloadFilePath,mDownloadFileExtensionName, mIrequest, mIsuccess, mIfailure, mIerror, mRequestBody, mFile, mContext, mLoaderStyle); } }
/** * */ package com.cnk.travelogix.mdmbackoffice.workflow; import de.hybris.platform.core.model.ItemModel; import de.hybris.platform.servicelayer.model.ModelService; import de.hybris.platform.servicelayer.user.UserService; import de.hybris.platform.workflow.WorkflowProcessingService; import de.hybris.platform.workflow.WorkflowService; import de.hybris.platform.workflow.WorkflowTemplateService; import de.hybris.platform.workflow.jobs.AutomatedWorkflowTemplateJob; import de.hybris.platform.workflow.model.WorkflowActionModel; import de.hybris.platform.workflow.model.WorkflowModel; import de.hybris.platform.workflow.model.WorkflowTemplateModel; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.List; import org.apache.log4j.Logger; import com.cnk.travelogix.masterdata.core.enums.ApprovalWorkFlowStatus; public abstract class AbstractWorkflowSubmitActionJob implements AutomatedWorkflowTemplateJob { private WorkflowTemplateService workflowTemplateService; private WorkflowProcessingService workflowProcessingService; private UserService userService; private ModelService modelService; private WorkflowService workflowService; private static final Logger LOG = Logger.getLogger(AbstractWorkflowSubmitActionJob.class); protected ItemModel getSubmitRequest(final WorkflowActionModel action) { final List<ItemModel> attachments = action.getAttachmentItems(); if (attachments != null && attachments.size() == 1) { return attachments.get(0); } return null; } protected void setworkFlowStatus(final ItemModel item, final ApprovalWorkFlowStatus status) { Method method = null; try { method = item.getClass().getMethod("setWorkFlowStatus", ApprovalWorkFlowStatus.class); } catch (NoSuchMethodException | SecurityException e1) { LOG.error(e1); } try { if (method != null) { method.invoke(item, status); modelService.save(item); modelService.refresh(item); } } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { LOG.error(e); } } protected Object getWorkFlowStatus(final ItemModel item) { Method method = null; try { method = item.getClass().getMethod("getWorkFlowStatus"); } catch (NoSuchMethodException | SecurityException e1) { LOG.error(e1); } try { if (method != null) { return method.invoke(item); } } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { LOG.error(e); } return null; } /** * */ protected void startTheNextTemplateWorkflow(final ItemModel itemModel, final String templateCode) { final WorkflowTemplateModel workflowTemplate = this.workflowTemplateService.getWorkflowTemplateForCode(templateCode); if (workflowTemplate != null) { final WorkflowModel workflow = workflowService.createWorkflow(workflowTemplate, itemModel, userService.getUserForUID(workflowTemplate.getOwner().getUid())); modelService.save(itemModel); for (final WorkflowActionModel action : workflow.getActions()) { modelService.save(action); } this.workflowProcessingService.startWorkflow(workflow); LOG.info("*********** workflow started ************* "); } else { LOG.info("*********** workflow template missing ! ************* "); } } /** * @return the workflowService */ public WorkflowService getWorkflowService() { return workflowService; } /** * @param workflowService * the workflowService to set */ public void setWorkflowService(final WorkflowService workflowService) { this.workflowService = workflowService; } /** * @return the workflowTemplateService */ public WorkflowTemplateService getWorkflowTemplateService() { return workflowTemplateService; } /** * @param workflowTemplateService * the workflowTemplateService to set */ public void setWorkflowTemplateService(final WorkflowTemplateService workflowTemplateService) { this.workflowTemplateService = workflowTemplateService; } /** * @return the workflowProcessingService */ public WorkflowProcessingService getWorkflowProcessingService() { return workflowProcessingService; } /** * @param workflowProcessingService * the workflowProcessingService to set */ public void setWorkflowProcessingService(final WorkflowProcessingService workflowProcessingService) { this.workflowProcessingService = workflowProcessingService; } /** * @return the userService */ public UserService getUserService() { return userService; } /** * @param userService * the userService to set */ public void setUserService(final UserService userService) { this.userService = userService; } /** * @return the modelService */ public ModelService getModelService() { return modelService; } /** * @param modelService * the modelService to set */ public void setModelService(final ModelService modelService) { this.modelService = modelService; } }
package generated.main; import de.fhg.iais.roberta.runtime.*; import de.fhg.iais.roberta.runtime.ev3.*; import de.fhg.iais.roberta.mode.general.*; import de.fhg.iais.roberta.mode.action.*; import de.fhg.iais.roberta.mode.sensor.*; import de.fhg.iais.roberta.mode.action.ev3.*; import de.fhg.iais.roberta.mode.sensor.ev3.*; import de.fhg.iais.roberta.components.*; import java.util.LinkedHashSet; import java.util.HashMap; import java.util.Set; import java.util.Map; import java.util.List; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import lejos.remote.nxt.NXTConnection; public class NEPOprog { private static Configuration brickConfiguration; private Set<UsedSensor> usedSensors = new LinkedHashSet<UsedSensor>(); private Hal hal = new Hal(brickConfiguration, usedSensors); public static void main(String[] args) { try { brickConfiguration = new EV3Configuration.Builder() .setWheelDiameter(5.6) .setTrackWidth(18.0) .build(); new NEPOprog().run(); } catch ( Exception e ) { Hal.displayExceptionWaitForKeyPress(e); } } ArrayList<Float> ___nl = new ArrayList<>(); ArrayList<Boolean> ___bl = new ArrayList<>(); ArrayList<String> ___sl = new ArrayList<>(); ArrayList<Float> ___nl3 = new ArrayList<>(Arrays.asList((float) 1, (float) 2, (float) 9)); ArrayList<Boolean> ___bl3 = new ArrayList<>(Arrays.<Boolean>asList(true, true, false)); ArrayList<String> ___sl3 = new ArrayList<>(Arrays.<String>asList("a", "b", "c")); float ___n = 0; boolean ___b = true; String ___s = ""; public void run() throws Exception { // Basis List Operations START if ( ___nl.isEmpty() ) { ___nl = new ArrayList<>(Arrays.asList((float) 3, (float) 4, (float) 5, (float) 6, (float) 7, (float) 8)); ___nl3.add((int) ((___nl3.size() - 1) - 1), ___nl.remove( (int) (0)));; } if ( ___bl.isEmpty() ) { ___bl = new ArrayList<>(Arrays.<Boolean>asList(true, false, true)); ___bl = new ArrayList<>(Arrays.<Boolean>asList(___bl.get( (int) (0)).equals(___bl.get( (int) (___bl.size() - 1))), ___bl.get( (int) (1)).equals(___bl.get( (int) ((___bl.size() - 1) - 1))), ___bl.get( (int) (___bl.size() - 1)).equals(___bl.get( (int) (0))))); } if ( ___sl.isEmpty() ) { ___sl = new ArrayList<>(Arrays.<String>asList("d", "e", "f")); } ___n = ___nl.size(); ___n = new ArrayList<>(___nl.subList(0, ___nl.size())).size(); ___n = new ArrayList<>(___nl.subList(0, ___nl.size())).size() + new ArrayList<>(___nl.subList((int) 1, (int) 3)).size(); ___n = ___sl.indexOf("b"); ___n = new ArrayList<>(Collections.nCopies( (int) 5, (float) 5)).get( (int) (new ArrayList<>(Collections.nCopies( (int) 5, (float) 5)).size() - 1)); ___s = new ArrayList<>(Collections.nCopies( (int) 5, "copy")).get( (int) ((new ArrayList<>(Collections.nCopies( (int) 5, "copy")).size() - 1) - 5)); while ( ! ! ___sl.isEmpty() ) { ___sl3.set((int) (___sl3.size() - 1), ___sl.remove( (int) (0)));; } while ( ! (___nl3.size() <= 9) ) { ___nl3.add((int) ((___nl3.size() - 1) - 1), ___nl.remove( (int) (0)));; } new ArrayList<>(___nl3.subList((int) 2, (___nl3.size() - 1) - (int) 5)).set(0, ___nl3.indexOf( (float) ___n)); // Basis List Operations END } }
/** * Copyright (C) 2013-2014 EaseMob Technologies. All rights reserved. * * 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.pineapple.mobilecraft.tumcca.activity; import android.app.Activity; import android.app.ProgressDialog; import android.content.Intent; import android.os.Bundle; import android.text.Editable; import android.text.TextUtils; import android.text.TextWatcher; import android.view.View; import android.view.Window; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import com.pineapple.mobilecraft.R; import com.pineapple.mobilecraft.tumcca.data.Profile; import com.pineapple.mobilecraft.tumcca.manager.UserManager; import com.pineapple.mobilecraft.tumcca.mediator.IRegister; import com.pineapple.mobilecraft.tumcca.server.IUserServer; import com.pineapple.mobilecraft.tumcca.server.UserServer; import com.pineapple.mobilecraft.utils.PATextUtils; /** * 注册页 * 测试用例: * 1 用户名的手机号或者邮箱格式不正确,要注册失败,且弹出提示。 * 2 注册重复的用户名,要弹出提示 * 3 注册完成后要能够自动登录,登录后首页显示默认头像和用户填写的/斋号昵称 */ public class RegisterActivity extends Activity implements IRegister, TextWatcher { private EditText userNameEditText; private EditText passwordEditText; private EditText pseudonymEditText; private Button registerButton; public static void startActivity(Activity activity, int requestCode) { Intent intent = new Intent(activity, RegisterActivity.class); activity.startActivityForResult(intent, requestCode); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.activity_register); addUsernameView(); addPasswordView(); addPseudonymView(); registerButton = (Button) findViewById(R.id.button_register); registerButton.setEnabled(false); registerButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { confirm(); } }); } /** * 注册 */ public void register() { final String username = userNameEditText.getText().toString().trim(); final String pwd = passwordEditText.getText().toString().trim(); final String pseudonym = pseudonymEditText.getEditableText().toString(); //String confirm_pwd = confirmPwdEditText.getText().toString().trim(); if (!PATextUtils.isValidEmail(username) && !PATextUtils.isValidPhoneNumber(username)) { Toast.makeText(this, getString(R.string.please_enter_correct_phone_or_email), Toast.LENGTH_SHORT).show(); userNameEditText.requestFocus(); return; } else if (TextUtils.isEmpty(pwd)) { Toast.makeText(this, getString(R.string.password_cannot_be_empty), Toast.LENGTH_SHORT).show(); passwordEditText.requestFocus(); return; } else if (TextUtils.isEmpty(pseudonym)) { Toast.makeText(this, getString(R.string.pseudonym_cannot_be_empty), Toast.LENGTH_SHORT).show(); passwordEditText.requestFocus(); return; } final ProgressDialog pd = new ProgressDialog(this); pd.setMessage(getString(R.string.registering)); pd.show(); new Thread(new Runnable() { public void run() { try { IUserServer.RegisterResult registerResult = IUserServer.RegisterResult.getFailResult(); if (PATextUtils.isValidEmail(username)) { registerResult = UserManager.getInstance().register(null, username, pwd); } else if (PATextUtils.isValidPhoneNumber(username)) { registerResult = UserManager.getInstance().register(username, null, pwd); } if (registerResult.message.equals(IUserServer.REGISTER_SUCCESS)) { loginAfterRegister(username, pwd); uploadPseudonym(pseudonym); toastMessage(getString(R.string.register_success)); setResult(RESULT_OK); finish(); } else if (registerResult.message.equals(IUserServer.REGISTER_ACCOUNT_EXIST)) { toastMessage(getString(R.string.account_exist)); } else if (registerResult.message.equals(IUserServer.REGISTER_FAILED)||registerResult==null) { toastMessage(getString(R.string.register_failed)); } runOnUiThread(new Runnable() { public void run() { if (!RegisterActivity.this.isFinishing()) pd.dismiss(); } }); } catch (final Exception e) { } } }).start(); } public void back(View view) { finish(); } @Override public void addUsernameView() { userNameEditText = (EditText) findViewById(R.id.username); userNameEditText.addTextChangedListener(this); } @Override public void addPasswordView() { passwordEditText = (EditText) findViewById(R.id.password); passwordEditText.addTextChangedListener(this); } public void addPseudonymView() { pseudonymEditText = (EditText) findViewById(R.id.pseudonym); pseudonymEditText.addTextChangedListener(this); } @Override public void confirm() { register(); } @Override public void cancel() { finish(); } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } @Override public void afterTextChanged(Editable s) { if ((userNameEditText.getEditableText().length() > 0) && (passwordEditText.getEditableText().length() > 0) && (pseudonymEditText.getEditableText().length() > 0)) { registerButton.setEnabled(true); } else { registerButton.setEnabled(false); } } private void toastMessage(final String message) { runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show(); } }); } private void loginAfterRegister(String username, String password){ UserManager.getInstance().login(username, password); UserManager.getInstance().saveLoginInfo(username, password); } private void uploadPseudonym(String pseudonym){ Profile profile = Profile.createDefaultProfile(); profile.pseudonym = pseudonym; UserServer.getInstance().updateUser(profile, UserManager.getInstance().getCurrentToken(null)); } }
package com.mes.old.meta; // Generated 2017-5-22 1:25:24 by Hibernate Tools 5.2.1.Final import java.math.BigDecimal; import java.util.Date; /** * TvParttaskPrjId generated by hbm2java */ public class TvParttaskPrjId implements java.io.Serializable { private String taskuid; private String model; private String batchnum; private String partNumber; private Date latefinish; private Date earlystart; private Long priority; private BigDecimal planqty; private BigDecimal completeqty; private String deptid; private String mastershop; private BigDecimal taskstate; private Byte locked; private String partName; private String drawingid; private Long plangrade; public TvParttaskPrjId() { } public TvParttaskPrjId(String taskuid, String partNumber, String deptid) { this.taskuid = taskuid; this.partNumber = partNumber; this.deptid = deptid; } public TvParttaskPrjId(String taskuid, String model, String batchnum, String partNumber, Date latefinish, Date earlystart, Long priority, BigDecimal planqty, BigDecimal completeqty, String deptid, String mastershop, BigDecimal taskstate, Byte locked, String partName, String drawingid, Long plangrade) { this.taskuid = taskuid; this.model = model; this.batchnum = batchnum; this.partNumber = partNumber; this.latefinish = latefinish; this.earlystart = earlystart; this.priority = priority; this.planqty = planqty; this.completeqty = completeqty; this.deptid = deptid; this.mastershop = mastershop; this.taskstate = taskstate; this.locked = locked; this.partName = partName; this.drawingid = drawingid; this.plangrade = plangrade; } public String getTaskuid() { return this.taskuid; } public void setTaskuid(String taskuid) { this.taskuid = taskuid; } public String getModel() { return this.model; } public void setModel(String model) { this.model = model; } public String getBatchnum() { return this.batchnum; } public void setBatchnum(String batchnum) { this.batchnum = batchnum; } public String getPartNumber() { return this.partNumber; } public void setPartNumber(String partNumber) { this.partNumber = partNumber; } public Date getLatefinish() { return this.latefinish; } public void setLatefinish(Date latefinish) { this.latefinish = latefinish; } public Date getEarlystart() { return this.earlystart; } public void setEarlystart(Date earlystart) { this.earlystart = earlystart; } public Long getPriority() { return this.priority; } public void setPriority(Long priority) { this.priority = priority; } public BigDecimal getPlanqty() { return this.planqty; } public void setPlanqty(BigDecimal planqty) { this.planqty = planqty; } public BigDecimal getCompleteqty() { return this.completeqty; } public void setCompleteqty(BigDecimal completeqty) { this.completeqty = completeqty; } public String getDeptid() { return this.deptid; } public void setDeptid(String deptid) { this.deptid = deptid; } public String getMastershop() { return this.mastershop; } public void setMastershop(String mastershop) { this.mastershop = mastershop; } public BigDecimal getTaskstate() { return this.taskstate; } public void setTaskstate(BigDecimal taskstate) { this.taskstate = taskstate; } public Byte getLocked() { return this.locked; } public void setLocked(Byte locked) { this.locked = locked; } public String getPartName() { return this.partName; } public void setPartName(String partName) { this.partName = partName; } public String getDrawingid() { return this.drawingid; } public void setDrawingid(String drawingid) { this.drawingid = drawingid; } public Long getPlangrade() { return this.plangrade; } public void setPlangrade(Long plangrade) { this.plangrade = plangrade; } public boolean equals(Object other) { if ((this == other)) return true; if ((other == null)) return false; if (!(other instanceof TvParttaskPrjId)) return false; TvParttaskPrjId castOther = (TvParttaskPrjId) other; return ((this.getTaskuid() == castOther.getTaskuid()) || (this.getTaskuid() != null && castOther.getTaskuid() != null && this.getTaskuid().equals(castOther.getTaskuid()))) && ((this.getModel() == castOther.getModel()) || (this.getModel() != null && castOther.getModel() != null && this.getModel().equals(castOther.getModel()))) && ((this.getBatchnum() == castOther.getBatchnum()) || (this.getBatchnum() != null && castOther.getBatchnum() != null && this.getBatchnum().equals(castOther.getBatchnum()))) && ((this.getPartNumber() == castOther.getPartNumber()) || (this.getPartNumber() != null && castOther.getPartNumber() != null && this.getPartNumber().equals(castOther.getPartNumber()))) && ((this.getLatefinish() == castOther.getLatefinish()) || (this.getLatefinish() != null && castOther.getLatefinish() != null && this.getLatefinish().equals(castOther.getLatefinish()))) && ((this.getEarlystart() == castOther.getEarlystart()) || (this.getEarlystart() != null && castOther.getEarlystart() != null && this.getEarlystart().equals(castOther.getEarlystart()))) && ((this.getPriority() == castOther.getPriority()) || (this.getPriority() != null && castOther.getPriority() != null && this.getPriority().equals(castOther.getPriority()))) && ((this.getPlanqty() == castOther.getPlanqty()) || (this.getPlanqty() != null && castOther.getPlanqty() != null && this.getPlanqty().equals(castOther.getPlanqty()))) && ((this.getCompleteqty() == castOther.getCompleteqty()) || (this.getCompleteqty() != null && castOther.getCompleteqty() != null && this.getCompleteqty().equals(castOther.getCompleteqty()))) && ((this.getDeptid() == castOther.getDeptid()) || (this.getDeptid() != null && castOther.getDeptid() != null && this.getDeptid().equals(castOther.getDeptid()))) && ((this.getMastershop() == castOther.getMastershop()) || (this.getMastershop() != null && castOther.getMastershop() != null && this.getMastershop().equals(castOther.getMastershop()))) && ((this.getTaskstate() == castOther.getTaskstate()) || (this.getTaskstate() != null && castOther.getTaskstate() != null && this.getTaskstate().equals(castOther.getTaskstate()))) && ((this.getLocked() == castOther.getLocked()) || (this.getLocked() != null && castOther.getLocked() != null && this.getLocked().equals(castOther.getLocked()))) && ((this.getPartName() == castOther.getPartName()) || (this.getPartName() != null && castOther.getPartName() != null && this.getPartName().equals(castOther.getPartName()))) && ((this.getDrawingid() == castOther.getDrawingid()) || (this.getDrawingid() != null && castOther.getDrawingid() != null && this.getDrawingid().equals(castOther.getDrawingid()))) && ((this.getPlangrade() == castOther.getPlangrade()) || (this.getPlangrade() != null && castOther.getPlangrade() != null && this.getPlangrade().equals(castOther.getPlangrade()))); } public int hashCode() { int result = 17; result = 37 * result + (getTaskuid() == null ? 0 : this.getTaskuid().hashCode()); result = 37 * result + (getModel() == null ? 0 : this.getModel().hashCode()); result = 37 * result + (getBatchnum() == null ? 0 : this.getBatchnum().hashCode()); result = 37 * result + (getPartNumber() == null ? 0 : this.getPartNumber().hashCode()); result = 37 * result + (getLatefinish() == null ? 0 : this.getLatefinish().hashCode()); result = 37 * result + (getEarlystart() == null ? 0 : this.getEarlystart().hashCode()); result = 37 * result + (getPriority() == null ? 0 : this.getPriority().hashCode()); result = 37 * result + (getPlanqty() == null ? 0 : this.getPlanqty().hashCode()); result = 37 * result + (getCompleteqty() == null ? 0 : this.getCompleteqty().hashCode()); result = 37 * result + (getDeptid() == null ? 0 : this.getDeptid().hashCode()); result = 37 * result + (getMastershop() == null ? 0 : this.getMastershop().hashCode()); result = 37 * result + (getTaskstate() == null ? 0 : this.getTaskstate().hashCode()); result = 37 * result + (getLocked() == null ? 0 : this.getLocked().hashCode()); result = 37 * result + (getPartName() == null ? 0 : this.getPartName().hashCode()); result = 37 * result + (getDrawingid() == null ? 0 : this.getDrawingid().hashCode()); result = 37 * result + (getPlangrade() == null ? 0 : this.getPlangrade().hashCode()); return result; } }
package rs.jug.rx.resultset.dao; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; import java.util.Arrays; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.ResultSetExtractor; import org.springframework.jdbc.datasource.DataSourceUtils; import rs.jug.rx.resultset.dao.function.CallDatabaseFunction; import rs.jug.rx.resultset.dao.function.CustomerResultSetExtractor; import rs.jug.rx.resultset.dao.function.ReleaseConnectionFunction; import rs.jug.rx.resultset.dao.function.ResultsetObserverFunction; import rx.Observable; import rx.observables.AsyncOnSubscribe; public class ReactiveCustomerDAO implements CustomerDAO { private static final Logger log = LoggerFactory.getLogger(BlockingCustomerDAO.class); private JdbcTemplate jdbcTemplate; public ReactiveCustomerDAO(JdbcTemplate jdbcTemplate) { this.jdbcTemplate = jdbcTemplate; } private Observable<Customer> doQueryDatabase(String sql, ResultSetExtractor<Customer> extractor) { Connection con = DataSourceUtils.getConnection(jdbcTemplate.getDataSource()); try { PreparedStatement statement = con.prepareStatement(sql); return Observable .create(AsyncOnSubscribe.createStateful(new CallDatabaseFunction(statement), new ResultsetObserverFunction<Customer>(extractor), new ReleaseConnectionFunction(con, jdbcTemplate.getDataSource()))); } catch (SQLException e) { DataSourceUtils.releaseConnection(con, jdbcTemplate.getDataSource()); throw new RuntimeException("Couldn't create statement", e); } } @Override public void queryDatabase() { log.info("Querying for customer records where first_name = 'Josh':"); Observable<Customer> customers = doQueryDatabase("SELECT id, first_name, last_name FROM customers WHERE first_name = 'Josh'", new CustomerResultSetExtractor()); customers.subscribe(customer -> log.info(customer.toString())); } @Override public void insertData() { Observable.from(Arrays.asList("John Woo", "Jeff Dean", "Josh Bloch", "Josh Long")).subscribe(name -> { String[] firstAndLast = name.split(" "); log.info(String.format("Inserting customer record for %s %s", firstAndLast[0], firstAndLast[1])); jdbcTemplate.update("INSERT INTO customers(first_name, last_name) VALUES (?,?)", firstAndLast[0], firstAndLast[1]); }); } @Override public void setUpDatabase() { log.info("Creating tables"); jdbcTemplate.execute("DROP TABLE customers IF EXISTS"); jdbcTemplate.execute("CREATE TABLE customers(" + "id SERIAL, first_name VARCHAR(255), last_name VARCHAR(255))"); } }
package smart.config; import smart.storage.LocalStorage; import org.springframework.context.annotation.Configuration; import org.springframework.http.CacheControl; import org.springframework.lang.NonNull; import org.springframework.web.method.support.HandlerMethodArgumentResolver; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.List; import java.util.concurrent.TimeUnit; @Configuration public class WebMvcConfigurer extends WebMvcConfigurationSupport { @Override public void addArgumentResolvers(List<HandlerMethodArgumentResolver> resolvers) { resolvers.add(new SessionArgumentResolvers()); resolvers.add(new UserTokenArgumentResolvers()); } @Override protected void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(new HttpInterceptor()); } @Override public void addResourceHandlers(@NonNull ResourceHandlerRegistry registry) { super.addResourceHandlers(registry); registry.addResourceHandler("/**") .addResourceLocations("classpath:/static/") .setCacheControl(CacheControl .maxAge(10, TimeUnit.MINUTES) .cachePublic()) .resourceChain(true); // upload directory mapping Path pathUploadDir = Paths.get(LocalStorage.UPLOAD_DIR); if (Files.notExists(pathUploadDir)) { try { Files.createDirectory(pathUploadDir); } catch (IOException e) { e.printStackTrace(); } } registry.addResourceHandler("/img/**") .addResourceLocations("file:" + LocalStorage.UPLOAD_DIR) .setCacheControl(CacheControl .maxAge(10, TimeUnit.MINUTES) .cachePublic()) .resourceChain(true); } }
package com.bowlong.sql.jdbc; import java.sql.CallableStatement; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.sql.Statement; import java.text.SimpleDateFormat; import java.util.Arrays; import java.util.Calendar; import java.util.Collections; import java.util.Date; import java.util.HashSet; import java.util.Hashtable; import java.util.List; import java.util.Map; import java.util.Set; import java.util.Vector; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import javax.sql.DataSource; import javax.sql.RowSet; import javax.sql.rowset.CachedRowSet; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.bowlong.lang.StrEx; import com.bowlong.lang.task.MyThreadFactory; import com.bowlong.objpool.StringBufPool; import com.bowlong.sql.SqlEx; import com.bowlong.third.FastJSON; import com.bowlong.util.ListEx; import com.bowlong.util.MapEx; import com.bowlong.util.NewSet; import com.bowlong.util.StrBuilder; import com.sun.rowset.CachedRowSetImpl; @SuppressWarnings("all") public class _JdbcBackup { // ///////////////////////// /*** 缓存查询过后的字段 **/ private static final Map<String, PrepareSQLResult> SQLCHCHE = newMap(); /*** 处理查询结果 **/ private static final Map<Class, ResultSetHandler> RSHCHCHE = newMap(); /*** 记录数据连接对象目录下的所有表名称 **/ private static final Map<String, NewSet<String>> TABLES = newMap(); // 数据库连接模式[conn如果不为空,则只有一个连接] Connection conn; // 单链接模式 DataSource ds_r; // 读写分离模式(读数据源) DataSource ds_w; // 读写分离模式(写数据源) // 检索此 Connection 对象的当前目录名称。 private String catalog_r; // 检索此 Connection 对象的当前目录名称。 private String catalog_w; public static final Log getLog(Class<?> clazz) { return LogFactory.getLog(clazz); } private static final ResultSetHandler getRsh(Class c) throws Exception { ResultSetHandler rsh = RSHCHCHE.get(c); if (rsh == null) { rsh = (ResultSetHandler) c.newInstance(); RSHCHCHE.put(c, rsh); } return rsh; } public _JdbcBackup(final Connection conn) { this.conn = conn; } public _JdbcBackup(final DataSource ds) { this.ds_r = ds; this.ds_w = ds; } public _JdbcBackup(final DataSource ds_r, final DataSource ds_w) { this.ds_r = ds_r; this.ds_w = ds_w; } public DataSource ds_r() { return ds_r; } public DataSource ds_w() { return ds_w; } public String catalog_r() throws SQLException { if (!StrEx.isEmpty(catalog_r)) return catalog_r; Connection conn = null; try { conn = conn_r(); catalog_r = conn.getCatalog(); return catalog_r; } finally { closeNoExcept(conn); } } public String catalog_w() throws SQLException { if (!StrEx.isEmpty(catalog_w)) return catalog_w; Connection conn = null; try { conn = conn_w(); catalog_w = conn.getCatalog(); return catalog_w; } finally { closeNoExcept(conn); } } // ///////////////////////// public void close() throws SQLException { try { if (this.conn != null && !this.conn.isClosed()) { this.conn.close(); } } finally { this.conn = null; this.ds_r = null; this.ds_w = null; } } private final void closeNoExcept(final Connection conn) { try { close(conn); } catch (Exception e) { } } private final void close(final Connection conn) throws SQLException { if (this.conn != null) // 如果是单链接模式则不关闭链接 return; conn.close(); } // ///////////////////////// public final Connection conn_r() throws SQLException { if (this.conn != null) return this.conn; return ds_r.getConnection(); } public final Connection conn_w() throws SQLException { if (this.conn != null) return this.conn; return ds_w.getConnection(); } // ///////////////////////// public void execute(final String sql) throws SQLException { Connection conn = conn_w(); try { PreparedStatement stmt = conn.prepareStatement(sql); stmt.execute(); stmt.close(); } catch (SQLException e) { throw rethrow(e, sql); } finally { close(conn); } } public CachedRowSet query(final String sql) throws SQLException { Connection conn = conn_r(); try { PreparedStatement stmt = conn.prepareStatement(sql); ResultSet rs = stmt.executeQuery(); CachedRowSet crs = new CachedRowSetImpl(); crs.populate(rs); rs.close(); stmt.close(); return crs; } catch (SQLException e) { throw rethrow(e, sql); } finally { close(conn); } } // private <T> T query(String sql, Class c) throws Exception { // ResultSetHandler rsh = getRsh(c); // return query(sql, rsh); // } private <T> T query(final String sql, final ResultSetHandler rsh) throws SQLException { Connection conn = conn_r(); try { T r2 = null; PreparedStatement stmt = conn.prepareStatement(sql); ResultSet rs = stmt.executeQuery(); if (rs.next()) r2 = (T) rsh.handle(rs); rs.close(); stmt.close(); return r2; } catch (SQLException e) { throw rethrow(e, sql); } finally { close(conn); } } public <T> T queryForObject(final String sql, final Class c) throws Exception { ResultSetHandler rsh = getRsh(c); return queryForObject(sql, rsh); } public final <T> T queryForObject(final String sql, final ResultSetHandler rsh) throws SQLException { return query(sql, rsh); } public Map queryForMap(final String sql) throws SQLException { Connection conn = conn_r(); try { Map r2 = null; PreparedStatement stmt = conn.prepareStatement(sql); ResultSet rs = stmt.executeQuery(); if (rs.next()) r2 = toMap(rs); rs.close(); stmt.close(); return r2; } catch (SQLException e) { throw rethrow(e, sql); } finally { close(conn); } } public List<Map> queryForList(final String sql) throws SQLException { Connection conn = conn_r(); try { List<Map> r2 = null; PreparedStatement stmt = conn.prepareStatement(sql); ResultSet rs = stmt.executeQuery(); r2 = toMaps(rs); rs.close(); stmt.close(); return r2; } catch (SQLException e) { throw rethrow(e, sql); } finally { close(conn); } } public <T> List<T> queryForKeys(final String sql) throws SQLException { Connection conn = conn_r(); try { List<T> r2 = null; PreparedStatement stmt = conn.prepareStatement(sql); ResultSet rs = stmt.executeQuery(); r2 = toKeys(rs); rs.close(); stmt.close(); return r2; } catch (SQLException e) { throw rethrow(e, sql); } finally { close(conn); } } public <T> List<T> queryForList(final String sql, final Class c) throws Exception { ResultSetHandler rsh = getRsh(c); return queryForList(sql, rsh); } public <T> List<T> queryForList(final String sql, final ResultSetHandler rsh) throws SQLException { Connection conn = conn_r(); try { PreparedStatement stmt = conn.prepareStatement(sql); ResultSet rs = stmt.executeQuery(); List<T> result = newList(); while (rs.next()) { T v = (T) rsh.handle(rs); result.add(v); } rs.close(); stmt.close(); return result; } catch (SQLException e) { throw rethrow(e, sql); } finally { close(conn); } } public long queryForLong(final String sql) throws SQLException { Connection conn = conn_r(); try { long r2 = 0; PreparedStatement stmt = conn.prepareStatement(sql); ResultSet rs = stmt.executeQuery(); if (rs.next()) r2 = rs.getLong(1); rs.close(); stmt.close(); return r2; } catch (SQLException e) { throw rethrow(e, sql); } finally { close(conn); } } public int queryForInt(final String sql) throws SQLException { Connection conn = conn_r(); try { int r2 = 0; PreparedStatement stmt = conn.prepareStatement(sql); ResultSet rs = stmt.executeQuery(); if (rs.next()) r2 = rs.getInt(1); rs.close(); stmt.close(); return r2; } catch (SQLException e) { throw rethrow(e, sql); } finally { close(conn); } } public final RowSet queryForRowSet(final String sql) throws SQLException { return query(sql); } public int update(final String sql) throws SQLException { Connection conn = conn_w(); try { int r2 = 0; PreparedStatement stmt = conn.prepareStatement(sql); r2 = stmt.executeUpdate(); stmt.close(); return r2; } catch (SQLException e) { throw rethrow(e, sql); } finally { close(conn); } } public int[] batchUpdate(final String as[]) throws SQLException { Connection conn = conn_w(); try { int r2[] = null; Statement stmt = conn.createStatement(); for (String sql : as) { stmt.addBatch(sql); } r2 = stmt.executeBatch(); stmt.close(); return r2; } finally { close(conn); } } /*** * CallableStatement接口扩展 PreparedStatement,用来调用存储过程 * 调用已储存过程的语法:{call 过程名[(?, ?, ...)]} * 不带参数的已储存过程的语法:{call 过程名} * 返回结果参数的过程的语法:{? = call 过程名[(?, ?, ...)]} * **/ public void call(final String sql) throws SQLException { Connection conn = conn_w(); try { CallableStatement stmt = conn.prepareCall(sql); stmt.execute(); stmt.close(); } catch (SQLException e) { throw rethrow(e, sql); } finally { close(conn); } } public List<Map> queryByCall(final String sql) throws SQLException { Connection conn = conn_w(); try { List<Map> r2 = null; CallableStatement stmt = conn.prepareCall(sql); ResultSet rs = stmt.executeQuery(); r2 = toMaps(rs); rs.close(); stmt.close(); return r2; } catch (SQLException e) { throw rethrow(e, sql); } finally { close(conn); } } // ///////////////////////// private static final PrepareSQLResult prepareKeys(final String sql) { if (SQLCHCHE.containsKey(sql)) { // 从缓存中读取 return SQLCHCHE.get(sql); } PrepareSQLResult result = new PrepareSQLResult(); List<String> keys = new Vector<String>(); // 没有缓存,则从头获取 String sql2 = sql; int index = 0; int times = 10000; while (true) { if (times-- <= 0) break; index++; int p1 = sql2.indexOf(":"); if (p1 < 0) break; p1 = p1 + ":".length(); int p2 = sql2.indexOf(",", p1); int p3 = sql2.indexOf(" ", p1); int p4 = sql2.indexOf(")", p1); int p5 = sql2.length(); if (p3 > 0) p2 = (p2 >= 0 && p2 < p3) ? p2 : p3; if (p4 > 0) p2 = (p2 >= 0 && p2 < p4) ? p2 : p4; if (p5 > 0) p2 = (p2 >= 0 && p2 < p5) ? p2 : p5; String key = sql2.substring(p1, p2).trim(); String okey = String.format(":%s", key); sql2 = sql2.replaceFirst(okey, "?"); keys.add(key); } result.setSql(sql2); result.setKeys(keys); // 写入缓存 SQLCHCHE.put(sql, result); return result; } private static final PreparedStatement prepareMap( final PreparedStatement stmt, final List<String> keys, final Map m) throws SQLException { int index = 0; for (String key : keys) { index++; Object var = m.get(key); stmt.setObject(index, var); } return stmt; } // ///////////////////////// public void execute(final String sql, final Map params) throws SQLException { Connection conn = conn_w(); try { PrepareSQLResult sr = prepareKeys(sql); PreparedStatement stmt = conn.prepareStatement(sr.sql); prepareMap(stmt, sr.keys, params); stmt.execute(); stmt.close(); } catch (SQLException e) { throw rethrow(e, sql, params); } finally { close(conn); } } public Map insert(final String sql, final Map params) throws SQLException { Connection conn = conn_w(); try { Map r2 = null; PrepareSQLResult sr = prepareKeys(sql); PreparedStatement stmt = conn.prepareStatement(sr.sql, PreparedStatement.RETURN_GENERATED_KEYS); prepareMap(stmt, sr.keys, params); int r = stmt.executeUpdate(); if (r < 0) throw new SQLException(" r = 0"); ResultSet rs = stmt.getGeneratedKeys(); if (rs.next()) r2 = toMap(rs); rs.close(); stmt.close(); return r2; } catch (SQLException e) { throw rethrow(e, sql, params); } finally { close(conn); } } public int insert2(final String sql, final Map params) throws SQLException { Connection conn = conn_w(); try { int r2 = 0; PrepareSQLResult sr = prepareKeys(sql); PreparedStatement stmt = conn.prepareStatement(sr.sql, PreparedStatement.RETURN_GENERATED_KEYS); prepareMap(stmt, sr.keys, params); int r = stmt.executeUpdate(); if (r < 0) throw new SQLException(" r = 0"); ResultSet rs = stmt.getGeneratedKeys(); if (rs.next()) r2 = rs.getInt(1); rs.close(); stmt.close(); return r2; } catch (SQLException e) { throw rethrow(e, sql, params); } finally { close(conn); } } public int[] insert(final String sql, final List<Map> list) throws SQLException { Connection conn = conn_w(); try { int[] r2 = new int[list.size()]; PrepareSQLResult sr = prepareKeys(sql); // PreparedStatement stmt = conn.prepareStatement(sr.sql); PreparedStatement stmt = conn.prepareStatement(sr.sql, PreparedStatement.RETURN_GENERATED_KEYS); for (Map map : list) { prepareMap(stmt, sr.keys, map); stmt.addBatch(); } // r2 = stmt.executeBatch(); stmt.executeBatch(); ResultSet rs = stmt.getGeneratedKeys(); int i = 0; while (rs.next()) { r2[i++] = rs.getInt(1); } stmt.close(); return r2; } catch (SQLException e) { throw rethrow(e, sql, list); } finally { close(conn); } } public CachedRowSet query(final String sql, final Map params) throws SQLException { Connection conn = conn_r(); try { PrepareSQLResult sr = prepareKeys(sql); PreparedStatement stmt = conn.prepareStatement(sr.sql); prepareMap(stmt, sr.keys, params); ResultSet rs = stmt.executeQuery(); CachedRowSet crs = new CachedRowSetImpl(); crs.populate(rs); rs.close(); stmt.close(); return crs; } catch (SQLException e) { throw rethrow(e, sql, params); } finally { close(conn); } } public final <T> T query(final String sql, final Map params, final Class c) throws Exception { ResultSetHandler rsh = getRsh(c); return query(sql, params, rsh); } public <T> T query(final String sql, final Map params, final ResultSetHandler rsh) throws SQLException { Connection conn = conn_r(); try { T r2 = null; PrepareSQLResult sr = prepareKeys(sql); PreparedStatement stmt = conn.prepareStatement(sr.sql); prepareMap(stmt, sr.keys, params); ResultSet rs = stmt.executeQuery(); if (rs.next()) r2 = (T) rsh.handle(rs); rs.close(); stmt.close(); return r2; } catch (SQLException e) { throw rethrow(e, sql, params); } finally { close(conn); } } public final <T> T queryForObject(final String sql, final Map params, final Class c) throws Exception { ResultSetHandler rsh = getRsh(c); return queryForObject(sql, params, rsh); } public final <T> T queryForObject(final String sql, final Map params, final ResultSetHandler rsh) throws SQLException { return query(sql, params, rsh); } public Map queryForMap(final String sql, final Map params) throws SQLException { Connection conn = conn_r(); try { Map r2 = null; PrepareSQLResult sr = prepareKeys(sql); PreparedStatement stmt = conn.prepareStatement(sr.sql); prepareMap(stmt, sr.keys, params); ResultSet rs = stmt.executeQuery(); if (rs.next()) r2 = toMap(rs); rs.close(); stmt.close(); return r2; } catch (SQLException e) { throw rethrow(e, sql, params); } finally { close(conn); } } public List<Map> queryForList(final String sql, final Map params) throws SQLException { Connection conn = conn_r(); try { List<Map> r2 = null; PrepareSQLResult sr = prepareKeys(sql); PreparedStatement stmt = conn.prepareStatement(sr.sql); prepareMap(stmt, sr.keys, params); ResultSet rs = stmt.executeQuery(); r2 = toMaps(rs); rs.close(); stmt.close(); return r2; } catch (SQLException e) { throw rethrow(e, sql, params); } finally { close(conn); } } public <T> List<T> queryForKeys(final String sql, final Map params) throws SQLException { Connection conn = conn_r(); try { List<T> r2 = null; PrepareSQLResult sr = prepareKeys(sql); PreparedStatement stmt = conn.prepareStatement(sr.sql); prepareMap(stmt, sr.keys, params); ResultSet rs = stmt.executeQuery(); r2 = toKeys(rs); rs.close(); stmt.close(); return r2; } catch (SQLException e) { throw rethrow(e, sql, params); } finally { close(conn); } } public final <T> List<T> queryForList(final String sql, final Map params, final Class c) throws Exception { ResultSetHandler rsh = getRsh(c); return queryForList(sql, params, rsh); } public <T> List<T> queryForList(final String sql, final Map params, final ResultSetHandler rsh) throws SQLException { Connection conn = conn_r(); try { PrepareSQLResult sr = prepareKeys(sql); PreparedStatement stmt = conn.prepareStatement(sr.sql); prepareMap(stmt, sr.keys, params); ResultSet rs = stmt.executeQuery(); List<T> result = newList(); while (rs.next()) { T v = (T) rsh.handle(rs); result.add(v); } rs.close(); stmt.close(); return result; } catch (SQLException e) { throw rethrow(e, sql, params); } finally { close(conn); } } public long queryForLong(final String sql, final Map params) throws SQLException { Connection conn = conn_r(); try { long r2 = 0; PrepareSQLResult sr = prepareKeys(sql); PreparedStatement stmt = conn.prepareStatement(sr.sql); prepareMap(stmt, sr.keys, params); ResultSet rs = stmt.executeQuery(); if (rs.next()) r2 = rs.getLong(1); rs.close(); stmt.close(); return r2; } catch (SQLException e) { throw rethrow(e, sql, params); } finally { close(conn); } } public int queryForInt(final String sql, final Map params) throws SQLException { Connection conn = conn_r(); try { int r2 = 0; PrepareSQLResult sr = prepareKeys(sql); PreparedStatement stmt = conn.prepareStatement(sr.sql); prepareMap(stmt, sr.keys, params); ResultSet rs = stmt.executeQuery(); if (rs.next()) r2 = rs.getInt(1); rs.close(); stmt.close(); return r2; } catch (SQLException e) { throw rethrow(e, sql, params); } finally { close(conn); } } public final RowSet queryForRowSet(final String sql, final Map params) throws SQLException { return query(sql, params); } public int update(final String sql, final Map params) throws SQLException { Connection conn = conn_w(); try { int r2 = 0; PrepareSQLResult sr = prepareKeys(sql); PreparedStatement stmt = conn.prepareStatement(sr.sql); prepareMap(stmt, sr.keys, params); r2 = stmt.executeUpdate(); stmt.close(); return r2; } catch (SQLException e) { throw rethrow(e, sql, params); } finally { close(conn); } } public int[] batchUpdate(final String sql, final List<Map> list) throws SQLException { Connection conn = conn_w(); try { int r2[] = null; PrepareSQLResult sr = prepareKeys(sql); PreparedStatement stmt = conn.prepareStatement(sr.sql); for (Map map : list) { prepareMap(stmt, sr.keys, map); stmt.addBatch(); } r2 = stmt.executeBatch(); stmt.close(); return r2; } catch (SQLException e) { throw rethrow(e, sql, list); } finally { close(conn); } } public void call(final String sql, final Map params) throws SQLException { Connection conn = conn_w(); try { PrepareSQLResult sr = prepareKeys(sql); CallableStatement stmt = conn.prepareCall(sr.sql); prepareMap(stmt, sr.keys, params); stmt.execute(); stmt.close(); } catch (SQLException e) { throw rethrow(e, sql, params); } finally { close(conn); } } public List<Map> queryByCall(final String sql, final Map params) throws SQLException { Connection conn = conn_w(); try { List<Map> r2 = null; PrepareSQLResult sr = prepareKeys(sql); CallableStatement stmt = conn.prepareCall(sr.sql); prepareMap(stmt, sr.keys, params); ResultSet rs = stmt.executeQuery(); r2 = toMaps(rs); rs.close(); stmt.close(); return r2; } catch (SQLException e) { throw rethrow(e, sql, params); } finally { close(conn); } } // ///////////////////////// public void execute(final String sql, final BeanSupport x) throws SQLException { Connection conn = conn_w(); Map params = null; try { params = x.toBasicMap(); PrepareSQLResult sr = prepareKeys(sql); PreparedStatement stmt = conn.prepareStatement(sr.sql); prepareMap(stmt, sr.keys, params); stmt.execute(); stmt.close(); } catch (SQLException e) { throw rethrow(e, sql, params); } finally { close(conn); } } public Map insert(final String sql, final BeanSupport x) throws SQLException { Connection conn = conn_w(); Map r2 = null; Map params = null; try { params = x.toBasicMap(); PrepareSQLResult sr = prepareKeys(sql); PreparedStatement stmt = conn.prepareStatement(sr.sql, PreparedStatement.RETURN_GENERATED_KEYS); prepareMap(stmt, sr.keys, params); int r = stmt.executeUpdate(); if (r < 0) throw new SQLException(" r = 0"); ResultSet rs = stmt.getGeneratedKeys(); if (rs.next()) r2 = toMap(rs); rs.close(); stmt.close(); return r2; } catch (SQLException e) { throw rethrow(e, sql, params); } finally { close(conn); } } public int insert2(final String sql, final BeanSupport x) throws SQLException { Connection conn = conn_w(); Map params = null; try { int r2 = 0; params = x.toBasicMap(); PrepareSQLResult sr = prepareKeys(sql); PreparedStatement stmt = conn.prepareStatement(sr.sql, PreparedStatement.RETURN_GENERATED_KEYS); prepareMap(stmt, sr.keys, params); int r = stmt.executeUpdate(); if (r < 0) throw new SQLException(" r = 0"); ResultSet rs = stmt.getGeneratedKeys(); if (rs.next()) r2 = rs.getInt(1); rs.close(); stmt.close(); return r2; } catch (SQLException e) { throw rethrow(e, sql, params); } finally { close(conn); } } public int[] batchInsert(final String sql, final List list) throws SQLException { Connection conn = conn_w(); try { int[] r2 = new int[list.size()]; PrepareSQLResult sr = prepareKeys(sql); // PreparedStatement stmt = conn.prepareStatement(sr.sql); PreparedStatement stmt = conn.prepareStatement(sr.sql, PreparedStatement.RETURN_GENERATED_KEYS); for (Object x : list) { Map params = ((BeanSupport) x).toBasicMap(); prepareMap(stmt, sr.keys, params); stmt.addBatch(); } stmt.executeBatch(); ResultSet rs = stmt.getGeneratedKeys(); int i = 0; while (rs.next()) { r2[i++] = rs.getInt(1); } stmt.close(); return r2; } catch (SQLException e) { throw rethrow(e, sql, list); } finally { close(conn); } } public CachedRowSet query(final String sql, final BeanSupport x) throws SQLException { Connection conn = conn_r(); Map params = null; try { params = x.toBasicMap(); PrepareSQLResult sr = prepareKeys(sql); PreparedStatement stmt = conn.prepareStatement(sr.sql); prepareMap(stmt, sr.keys, params); ResultSet rs = stmt.executeQuery(); CachedRowSet crs = new CachedRowSetImpl(); crs.populate(rs); rs.close(); stmt.close(); return crs; } catch (SQLException e) { throw rethrow(e, sql, params); } finally { close(conn); } } public final <T> T query(final String sql, final BeanSupport x, final Class c) throws Exception { ResultSetHandler rsh = getRsh(c); return query(sql, x, rsh); } public <T> T query(final String sql, final BeanSupport x, final ResultSetHandler rsh) throws SQLException { Connection conn = conn_r(); Map params = null; try { T r2 = null; params = x.toBasicMap(); PrepareSQLResult sr = prepareKeys(sql); PreparedStatement stmt = conn.prepareStatement(sr.sql); prepareMap(stmt, sr.keys, params); ResultSet rs = stmt.executeQuery(); if (rs.next()) r2 = (T) rsh.handle(rs); rs.close(); stmt.close(); return r2; } catch (SQLException e) { throw rethrow(e, sql, params); } finally { close(conn); } } public final <T> T queryForObject(final String sql, final BeanSupport x, final Class c) throws Exception { ResultSetHandler rsh = getRsh(c); return query(sql, x, rsh); } public final <T> T queryForObject(final String sql, final BeanSupport x, final ResultSetHandler rsh) throws SQLException { Map params = x.toBasicMap(); return query(sql, params, rsh); } public Map queryForMap(final String sql, final BeanSupport x) throws SQLException { Connection conn = conn_r(); Map params = null; try { Map r2 = null; params = x.toBasicMap(); PrepareSQLResult sr = prepareKeys(sql); PreparedStatement stmt = conn.prepareStatement(sr.sql); prepareMap(stmt, sr.keys, params); ResultSet rs = stmt.executeQuery(); if (rs.next()) r2 = toMap(rs); rs.close(); stmt.close(); return r2; } catch (SQLException e) { throw rethrow(e, sql, params); } finally { close(conn); } } public List<Map> queryForList(final String sql, final BeanSupport x) throws SQLException { Connection conn = conn_r(); Map params = null; try { List<Map> r2 = null; params = x.toBasicMap(); PrepareSQLResult sr = prepareKeys(sql); PreparedStatement stmt = conn.prepareStatement(sr.sql); prepareMap(stmt, sr.keys, params); ResultSet rs = stmt.executeQuery(); r2 = toMaps(rs); rs.close(); stmt.close(); return r2; } catch (SQLException e) { throw rethrow(e, sql, params); } finally { close(conn); } } public final <T> List<T> queryForList(final String sql, final BeanSupport x, final Class c) throws Exception { ResultSetHandler rsh = getRsh(c); return queryForList(sql, x, rsh); } public <T> List<T> queryForList(final String sql, final BeanSupport x, final ResultSetHandler rsh) throws SQLException { Connection conn = conn_r(); Map params = null; try { params = x.toBasicMap(); PrepareSQLResult sr = prepareKeys(sql); PreparedStatement stmt = conn.prepareStatement(sr.sql); prepareMap(stmt, sr.keys, params); ResultSet rs = stmt.executeQuery(); List<T> result = newList(); while (rs.next()) { T v = (T) rsh.handle(rs); result.add(v); } rs.close(); stmt.close(); return result; } catch (SQLException e) { throw rethrow(e, sql, params); } finally { close(conn); } } public long queryForLong(final String sql, final BeanSupport x) throws SQLException { Connection conn = conn_r(); Map params = null; try { long r2 = 0; params = x.toBasicMap(); PrepareSQLResult sr = prepareKeys(sql); PreparedStatement stmt = conn.prepareStatement(sr.sql); prepareMap(stmt, sr.keys, params); ResultSet rs = stmt.executeQuery(); if (rs.next()) r2 = rs.getLong(1); rs.close(); stmt.close(); return r2; } catch (SQLException e) { throw rethrow(e, sql, params); } finally { close(conn); } } public int queryForInt(final String sql, final BeanSupport x) throws SQLException { Connection conn = conn_r(); Map params = null; try { int r2 = 0; params = x.toBasicMap(); PrepareSQLResult sr = prepareKeys(sql); PreparedStatement stmt = conn.prepareStatement(sr.sql); prepareMap(stmt, sr.keys, params); ResultSet rs = stmt.executeQuery(); if (rs.next()) r2 = rs.getInt(1); rs.close(); stmt.close(); return r2; } catch (SQLException e) { throw rethrow(e, sql, params); } finally { close(conn); } } public final RowSet queryForRowSet(final String sql, final BeanSupport x) throws SQLException { Map params = x.toBasicMap(); return query(sql, params); } public int update(final String sql, final BeanSupport x) throws SQLException { Connection conn = conn_w(); Map params = null; try { int r2 = 0; params = x.toBasicMap(); PrepareSQLResult sr = prepareKeys(sql); PreparedStatement stmt = conn.prepareStatement(sr.sql); prepareMap(stmt, sr.keys, params); r2 = stmt.executeUpdate(); stmt.close(); return r2; } catch (SQLException e) { throw rethrow(e, sql, params); } finally { close(conn); } } public int[] batchUpdate2(final String sql, final List list) throws SQLException { Connection conn = conn_w(); try { int r2[] = null; PrepareSQLResult sr = prepareKeys(sql); PreparedStatement stmt = conn.prepareStatement(sr.sql); for (Object x : list) { Map map = ((BeanSupport) x).toBasicMap(); prepareMap(stmt, sr.keys, map); stmt.addBatch(); } r2 = stmt.executeBatch(); stmt.close(); return r2; } catch (SQLException e) { throw rethrow(e, sql, list); } finally { close(conn); } } public void call(final String sql, final BeanSupport x) throws SQLException { Connection conn = conn_w(); Map params = null; try { params = x.toBasicMap(); PrepareSQLResult sr = prepareKeys(sql); CallableStatement stmt = conn.prepareCall(sr.sql); prepareMap(stmt, sr.keys, params); stmt.execute(); stmt.close(); } catch (SQLException e) { throw rethrow(e, sql, params); } finally { close(conn); } } public List<Map> queryBycall(final String sql, final BeanSupport x) throws SQLException { Connection conn = conn_w(); Map params = null; try { List<Map> r2 = null; params = x.toBasicMap(); PrepareSQLResult sr = prepareKeys(sql); CallableStatement stmt = conn.prepareCall(sr.sql); prepareMap(stmt, sr.keys, params); ResultSet rs = stmt.executeQuery(); r2 = toMaps(rs); rs.close(); stmt.close(); return r2; } catch (SQLException e) { throw rethrow(e, sql, params); } finally { close(conn); } } // ///////////////////////// public static final List singletonEmptyList() { return ListEx.singletonEmptyList; } public static final Map singletonEmptyMap() { return MapEx.singletonEmptyMap; } public static final Set singletonEmptySet() { return NewSet.singletonEmptySet; } public static final List newList() { return new Vector(); } public static final Map newMap() { return new Hashtable(); } public static final Set newSet() { return Collections.synchronizedSet(new HashSet()); } // ///////////////////////// // 错误堆栈的内容 public static final String e2s(final Throwable e) { return e2s(e, null, new Object[0]); } public static final String e2s(final Throwable e, final Object obj) { return e2s(e, String.valueOf(obj), new Object[0]); } public static String e2s(final Throwable e, final String fmt, final Object... args) { StringBuffer sb = StringBufPool.borrowObject(); try { sb.append(e); if (fmt != null && !fmt.isEmpty() && args.length <= 0) sb.append(" - ").append(fmt); if (fmt != null && !fmt.isEmpty() && args.length > 0) { String str = StrBuilder.builder().ap(fmt, args).str(); sb.append(" - ").append(str); } sb.append("\r\n"); for (StackTraceElement ste : e.getStackTrace()) { sb.append("at "); sb.append(ste); sb.append("\r\n"); } return sb.toString(); } finally { StringBufPool.returnObject(sb); } } // /////////////////////////////////////////////////// public static final boolean isTimeout(final long LASTTIME, final long TIMEOUT) { long l2 = System.currentTimeMillis(); return isTimeout(l2, LASTTIME, TIMEOUT); } public static final boolean isTimeout(final long TIME1, final long TIME2, final long TIMEOUT) { if (TIMEOUT <= 0) return false; long l2 = TIME1; long t = l2 - TIME2; return (t > TIMEOUT); } public static final boolean isTimeout(final Date DLASTTIME, final long TIMEOUT) { if (DLASTTIME == null) return false; long LASTTIME = DLASTTIME.getTime(); return isTimeout(TIMEOUT, LASTTIME); } // /////////////////////////////////////////////////// public static final List<Map> toMaps(final ResultSet rs) throws SQLException { List<Map> result = new Vector(); while (rs.next()) { Map m = toMap(rs); result.add(m); } return result; } public static final <T> List<T> toKeys(final ResultSet rs) throws SQLException { List<T> result = new Vector(); while (rs.next()) { Object o = rs.getObject(1); result.add((T) o); } return result; } public static final Map toMap(final ResultSet rs) throws SQLException { Map result = newMap(); ResultSetMetaData rsmd = rs.getMetaData(); int cols = rsmd.getColumnCount(); for (int i = 1; i <= cols; i++) result.put(rsmd.getColumnName(i), rs.getObject(i)); return result; } // /////////////////////////////////////////////////////////////////////// public static final int pageCount(final int count, final int pageSize) { int page = count / pageSize; page = count == page * pageSize ? page : page + 1; return page; } public static final List getPage(final List v, final int page, final int pageSize) { int count = v.size(); int begin = page * pageSize; int end = begin + pageSize; if (begin > count || begin < 0 || end < 0) return new Vector(); end = count < end ? count : end; if (end <= begin) new Vector(); return v.subList(begin, end); } // /////////////////////////////////////////////////////////////////////// public void truncate(final String TABLENAME2) throws SQLException { String sql = "TRUNCATE TABLE `" + TABLENAME2 + "`"; this.update(sql); } public void repair(final String TABLENAME2) throws SQLException { String sql = "REPAIR TABLE `" + TABLENAME2 + "`"; this.update(sql); } public void optimize(final String TABLENAME2) throws SQLException { String sql = "OPTIMIZE TABLE `" + TABLENAME2 + "`"; this.update(sql); } public void dropTable(final String TABLENAME2) throws SQLException { String sql = "DROP TABLE IF EXISTS `" + TABLENAME2 + "`"; this.update(sql); } public static void main(String[] args) throws Exception { // DataSource ds = Dbcp.newMysql("fych").dataSource(); // JdbcTemplate jt = new JdbcTemplate(ds); // String TABLENAME2 = "Copyright"; // String sql = // "INSERT INTO Copyright (name, version) VALUES (:name, :version)"; // Copyright c = Copyright.newCopyright(0L, "name -- 0", "version"); // ResultSet rs = jt.insert(sql, c); // System.out.println(SqlEx.toMaps(rs)); // String sql = "SELECT id, name, version FROM " + TABLENAME2 // + " WHERE id = :id"; // // Copyright x = Copyright.newCopyright(200L, "name -- 0", "version"); // Copyright c2 = jt.queryForObject(sql, x, // new ResultSetHandler<Copyright>() { // public Copyright handle(ResultSet rs) throws SQLException { // Map e = SqlEx.toMap(rs); // return Copyright.mapTo(e); // } // }); // System.out.println(c2); } // ////////////////////////////////////////////////////////// // static ScheduledExecutorService _executor = null; // // public static void setExecutor(ScheduledExecutorService ses) { // _executor = ses; // } // // protected static ScheduledExecutorService executor() { // if (_executor == null) // _executor = Executors.newScheduledThreadPool(8, // new MyThreadFactory("JdbcTemplate", false)); // return _executor; // } // ////////////////////////////////////////////////////////// ScheduledExecutorService _single_executor = null; public void setSingleExecutor(ScheduledExecutorService ses) { this._single_executor = ses; } protected synchronized ScheduledExecutorService executor(final String name) { if (_single_executor == null) _single_executor = Executors .newSingleThreadScheduledExecutor(new MyThreadFactory(name, false)); return _single_executor; } // ////////////////////////////////////////////////////////// public boolean exist_r(String TABLENAME2) { boolean ret = false; Connection conn = null; try { String catalog = catalog_r(); NewSet<String> tables = TABLES.get(catalog); if (tables != null) { if (tables.contains(TABLENAME2)) return true; } else { tables = new NewSet<String>(); TABLES.put(catalog, tables); } conn = conn_r(); List<Map> maps = SqlEx.getTables(conn); for (Map map : maps) { String str = MapEx.getString(map, "TABLE_NAME"); if (tables.contains(str)) continue; tables.Add(str); ret = ret || (str.equals(TABLENAME2)); } } catch (Exception e) { ret = false; } finally { closeNoExcept(conn); } return ret; } public boolean exist_w(String TABLENAME2) { boolean ret = false; Connection conn = null; try { String catalog = catalog_w(); NewSet<String> tables = TABLES.get(catalog); if (tables != null) { if (tables.contains(TABLENAME2)) return true; } else { tables = new NewSet<String>(); TABLES.put(catalog, tables); } conn = conn_w(); List<Map> maps = SqlEx.getTables(conn); for (Map map : maps) { String str = MapEx.getString(map, "TABLE_NAME"); if (tables.contains(str)) continue; tables.Add(str); ret = ret || (str.equals(TABLENAME2)); } } catch (Exception e) { ret = false; } finally { closeNoExcept(conn); } return ret; } protected SQLException rethrow(SQLException cause, String sql) throws SQLException { String causeMessage = cause.getMessage(); if (causeMessage == null) { causeMessage = ""; } StringBuffer msg = new StringBuffer(causeMessage); msg.append("\r\n"); msg.append(" Query: "); msg.append("\r\n"); msg.append(sql); msg.append("\r\n"); SQLException e = new SQLException(msg.toString(), cause.getSQLState(), cause.getErrorCode()); e.setNextException(cause); return e; } public static SQLException rethrow(SQLException cause, String sql, Object... params) { String causeMessage = cause.getMessage(); if (causeMessage == null) { causeMessage = ""; } StringBuffer msg = new StringBuffer(causeMessage); msg.append("\r\n"); msg.append(" Query: "); msg.append("\r\n"); msg.append(sql); msg.append("\r\n"); msg.append(" Parameters: "); msg.append("\r\n"); if (params == null) { msg.append("[]"); } else { msg.append(Arrays.deepToString(params)); } msg.append("\r\n"); SQLException e = new SQLException(msg.toString(), cause.getSQLState(), cause.getErrorCode()); e.setNextException(cause); return e; } protected SQLException rethrow(SQLException cause, String sql, Map params) throws SQLException { String causeMessage = cause.getMessage(); if (causeMessage == null) { causeMessage = ""; } StringBuffer msg = new StringBuffer(causeMessage); msg.append("\r\n"); msg.append(" Query: "); msg.append("\r\n"); msg.append(sql); msg.append("\r\n"); msg.append(" Parameters: "); msg.append("\r\n"); if (params == null) { msg.append("{}"); } else { msg.append(FastJSON.prettyFormat(params)); // msg.append(JSON.toJSONStringNotExcept(params)); } msg.append("\r\n"); SQLException e = new SQLException(msg.toString(), cause.getSQLState(), cause.getErrorCode()); e.setNextException(cause); return e; } protected SQLException rethrow(SQLException cause, String sql, List params) throws SQLException { String causeMessage = cause.getMessage(); if (causeMessage == null) { causeMessage = ""; } StringBuffer msg = new StringBuffer(causeMessage); msg.append("\r\n"); msg.append(" Query: "); msg.append("\r\n"); msg.append(sql); msg.append("\r\n"); msg.append(" Parameters: "); msg.append("\r\n"); if (params == null) { msg.append("[]"); } else { msg.append(FastJSON.prettyFormat(params)); // msg.append(JSON.toJSONStringNotExcept(params)); } msg.append("\r\n"); SQLException e = new SQLException(msg.toString(), cause.getSQLState(), cause.getErrorCode()); e.setNextException(cause); return e; } }
package com.dazhi.naming.utils; public class UtilAndComs { // public static final String VERSION = "Nacos-Java-Client:v" + VersionUtils.VERSION; public static String WEB_CONTEXT = "/nacos"; public static String NACOS_URL_BASE = WEB_CONTEXT + "/v1/ns"; public static String NACOS_URL_INSTANCE = NACOS_URL_BASE + "/instance"; public static String NACOS_URL_SERVICE = NACOS_URL_BASE + "/service"; public static final String ENCODING = "UTF-8"; public static final String ENV_LIST_KEY = "envList"; public static final String ALL_IPS = "000--00-ALL_IPS--00--000"; public static final String FAILOVER_SWITCH = "00-00---000-VIPSRV_FAILOVER_SWITCH-000---00-00"; public static final String DEFAULT_NAMESPACE_ID = "public"; public static final int REQUEST_DOMAIN_RETRY_COUNT = 3; public static final String NACOS_NAMING_LOG_NAME = "com.alibaba.nacos.naming.log.filename"; public static final String NACOS_NAMING_LOG_LEVEL = "com.alibaba.nacos.naming.log.level"; public static final String SERVER_ADDR_IP_SPLITER = ":"; public static final int DEFAULT_CLIENT_BEAT_THREAD_COUNT = Runtime.getRuntime() .availableProcessors() > 1 ? Runtime.getRuntime().availableProcessors() / 2 : 1; public static final int DEFAULT_POLLING_THREAD_COUNT = Runtime.getRuntime() .availableProcessors() > 1 ? Runtime.getRuntime().availableProcessors() / 2 : 1; public static final String HTTP = "http://"; public static final String HTTPS = "https://"; }
/* * [y] hybris Platform * * Copyright (c) 2000-2016 SAP SE * All rights reserved. * * This software is the confidential and proprietary information of SAP * Hybris ("Confidential Information"). You shall not disclose such * Confidential Information and shall use it only in accordance with the * terms of the license agreement you entered into with SAP Hybris. */ package com.cnk.travelogix.sapintegrations.converters.populator; import de.hybris.platform.converters.Populator; import de.hybris.platform.servicelayer.dto.converter.ConversionException; import java.util.ArrayList; import java.util.List; import org.apache.log4j.Logger; import com.cnk.travelogix.commons.error.Error; import com.cnk.travelogix.constants.SapintegrationsConstants; import com.cnk.travelogix.custom.zif.erp.ws.complaints.feedback.ZifTerpComplaintsResponse; import com.cnk.travelogix.custom.zif.erp.ws.complaints.feedback.ZifTerpComplaintsStatus; import com.cnk.travelogix.sapintegrations.zif.erp.ws.complaints.feedback.data.ZifTerpComplaintsDataResponse; import com.cnk.travelogix.sapintegrations.zif.erp.ws.complaints.feedback.data.ZifTerpComplaintsStatusData; import com.cnk.travelogix.sapintegrations.zif.erp.ws.complaints.feedback.data.ZttTerpComplaintsStatusData; public class DefaultComplaintsFeedbackResponseDataPopulator extends AbstractErrorResponsePopulator implements Populator<ZifTerpComplaintsResponse, ZifTerpComplaintsDataResponse> { private final Logger LOG = Logger.getLogger(getClass()); @Override public void populate(final ZifTerpComplaintsResponse source, final ZifTerpComplaintsDataResponse target) throws ConversionException { LOG.info("DefaultComplaintsFeedbackResponseDataPopulator - populate "); try { final ZttTerpComplaintsStatusData targetStatusData = new ZttTerpComplaintsStatusData(); final List<ZifTerpComplaintsStatus> srcStatusLst = source.getStatus() == null ? new ArrayList() : source.getStatus().getItem(); final List<ZifTerpComplaintsStatusData> targetStatusDataLst = targetStatusData.getItem(); for (final ZifTerpComplaintsStatus zifTerpComplaintsStatus : srcStatusLst) { final String status = zifTerpComplaintsStatus.getStatus(); final ZifTerpComplaintsStatusData statusData = new ZifTerpComplaintsStatusData(); statusData.setComplaintNo(zifTerpComplaintsStatus.getComplaintNo()); statusData.setFeedbackNo(zifTerpComplaintsStatus.getFeedbackNo()); statusData.setMessage(zifTerpComplaintsStatus.getMessage()); statusData.setMessagetype(zifTerpComplaintsStatus.getMessagetype()); statusData.setStatus(status); statusData.setSysubrc(zifTerpComplaintsStatus.getSysubrc()); statusData.setUniqid(zifTerpComplaintsStatus.getUniqid()); targetStatusDataLst.add(statusData); if (SapintegrationsConstants.ERROR_STATUS.equalsIgnoreCase(zifTerpComplaintsStatus.getStatus())) { final Error er = populateError(status, zifTerpComplaintsStatus.getMessage()); target.getErrors().add(er); } } target.setStatus(targetStatusData); } catch (final Exception e) { LOG.error(e.getMessage(), e); } } }
package pso.coco; import java.io.IOException; import java.io.InputStream; import java.nio.file.Files; import java.nio.file.Paths; import java.nio.file.StandardOpenOption; import java.util.Arrays; import java.util.Properties; public class PropertiesBBOBExperimentConfigurator implements BBOBExperimentConfigurator { private String bbobFunctionStr; private String dimensionsStr; private String experimentName; private boolean functionMappingExperiment; private String buildId; public PropertiesBBOBExperimentConfigurator() { final Properties properties = new Properties(); try { try { InputStream inputStream = Files.newInputStream(Paths.get("bbob.properties"), StandardOpenOption.READ); properties.load(inputStream); inputStream.close(); } catch (IOException e1) { InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("bbob.default.properties"); assert inputStream != null; properties.load(inputStream); inputStream.close(); } dimensionsStr = properties.getProperty("bbob.dimensions"); bbobFunctionStr = properties.getProperty("bbob.function"); functionMappingExperiment = Boolean.parseBoolean(properties.getProperty("bbob.map.function")); experimentName = properties.getProperty("experiment.name"); try { InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("git.properties"); Properties gitProperties = new Properties(); assert inputStream != null; gitProperties.load(inputStream); buildId = gitProperties.getProperty("git-commit"); } catch (IOException e) { e.printStackTrace(); } } catch (IOException e) { e.printStackTrace(); } } @Override public String getExperimentName() { return experimentName; } @Override public String getBuildId() { return buildId; } @Override public boolean isFunctionMappingExperiment() { return functionMappingExperiment; } @Override public String[] getFunctionsList() { return bbobFunctionStr .split(","); } @Override public int[] getDimensionsList() { return Arrays.stream( dimensionsStr .split(",")) .mapToInt(Integer::parseInt) .toArray() ; } }
/** * Copyright 2007 Jens Dietrich 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 nz.org.take.compiler.util; import java.util.HashMap; import java.util.Map; import java.util.StringTokenizer; import nz.org.take.AggregationFunction; import nz.org.take.AnnotationKeys; import nz.org.take.Predicate; import nz.org.take.Query; import nz.org.take.compiler.NameGenerator; /** * Default name generator implementation. * @author <a href="http://www-ist.massey.ac.nz/JBDietrich/">Jens Dietrich</a> */ public class DefaultNameGenerator implements NameGenerator { private Map<String,String> methodNames = new HashMap<String,String>(); private Map<String,String> classNames = new HashMap<String,String>(); /* (non-Javadoc) * @see org.mandarax.compiler.NameGenerator#getClassName(org.mandarax.kernel.Predicate) */ public String getClassName(Predicate p){ String key = this.createHash(p); String value = this.classNames.get(key); if (value==null) { value = p.getAnnotation(AnnotationKeys.TAKE_GENERATE_CLASS); if (value==null) { value = p.getName(); value = this.createJavaName(value,null); } this.classNames.put(key, value); } return p.isNegated()?("not_"+value):value; } /* (non-Javadoc) * @see org.mandarax.compiler.NameGenerator#getAccessorNameForSlot(org.mandarax.kernel.Predicate, int) */ public String getAccessorNameForSlot(Predicate p,int slot) { String s = getVariableNameForSlot(p,slot); return this.createJavaName(s,"get"); } /* (non-Javadoc) * @see org.mandarax.compiler.NameGenerator#getMutatorNameForSlot(org.mandarax.kernel.Predicate, int) */ public String getMutatorNameForSlot(Predicate p,int slot) { String s = getVariableNameForSlot(p,slot); return this.createJavaName(s,"set"); } /* (non-Javadoc) * @see org.mandarax.compiler.NameGenerator#getVariableNameForSlot(org.mandarax.kernel.Predicate, int) */ public String getVariableNameForSlot(Predicate p,int slot) { String s = p.getSlotNames()[slot]; String annotated = p.getAnnotation(AnnotationKeys.TAKE_GENERATE_SLOTS); if (annotated!=null) { StringTokenizer tokenizer = new StringTokenizer(annotated,","); int counter=0; if (slot<tokenizer.countTokens()) { while (tokenizer.hasMoreTokens() && counter<slot) { tokenizer.nextToken(); counter=counter+1; } s = tokenizer.nextToken(); } } return createJavaName(s,null); } /** * Create a java name. * @param s a string * @param prefix a prefix * @return a java name */ private String createJavaName(String s,String prefix) { StringBuffer b = new StringBuffer(); if (prefix!=null) b.append(prefix); boolean firstToUpper = prefix!=null; //char[] cc = s.toCharArray(); for (char c:s.toCharArray()) { if (Character.isWhitespace(c)) c = '_'; if (firstToUpper) { b.append(Character.toUpperCase(c)); firstToUpper = false; } else b.append(c); } return b.toString(); } public String getMethodName(Query q) { String key = this.createHash(q); String value = this.methodNames.get(key); Predicate p = q.getPredicate(); if (value==null) { String s = q.getAnnotation(AnnotationKeys.TAKE_GENERATE_METHOD); if (s==null) s = p.getAnnotation(AnnotationKeys.TAKE_GENERATE_METHOD); StringBuffer b = new StringBuffer(); if (s==null) { boolean[] inputParam = q.getInputParams(); char[] name = p.getName().toCharArray(); for (char ch : name) if (!Character.isWhitespace(ch)) b.append(ch); else b.append("_"); b.append("_"); for (boolean f : inputParam) b.append( f ? "1" : "0" ); } else { b.append(s); } value = b.toString(); this.methodNames.put(key, value); } return p.isNegated()?("not_"+value):value; } public String getMethodName(AggregationFunction f) { StringBuffer b = new StringBuffer(); char[] name = f.getName().toCharArray(); for (char ch : name) if (!Character.isWhitespace(ch)) b.append(ch); else b.append("_"); return b.toString(); } public String getConstantRegistryClassName() { return "Constants"; } public String getExpressionRegistryClassName() { return "Expressions"; } public String getAggregationFunctionsRegistryClassName() { return "Aggregations"; } public String getFactStoreRegistryClassName() { return "FactStores"; } /** * Generate the name of the class that has the methods * generated for a query * @param q a query * @return a class name */ public synchronized String getKBFragementName(Query q) { return "KBFragement_"+getMethodName(q); } /** * Create a string identifying a query. * @param q * @return */ private String createHash(Query q) { StringBuffer b = new StringBuffer(); b.append(q.getPredicate().getName()); b.append('_'); for (boolean f:q.getInputParams()) { b.append(f?'1':'0'); } return b.toString(); } /** * Create a string identifying a predicate. * @param p * @return */ private String createHash(Predicate p) { StringBuffer b = new StringBuffer(); b.append(p.getName()); b.append('_'); for (Class c:p.getSlotTypes()) { b.append('_'); b.append(c.getName()); } return b.toString(); } /** * Reset cached information. Thsi method should be called before reusing name generators. */ public void reset(){ this.methodNames.clear(); this.classNames.clear(); } }
package chap03.sec04.exam01_arithmetic; public class AccuracyExample2 { public static void main(String[] args) { /* int apple = 1; int number = 7; int totalPieces = apple * 10; int temp = totalPieces - number; double result = temp / 10.0; System.out.println(result); */ // 10씩 곱해진 값을 대신 사용한다 int apple = 10; double pieceUnit = 1; int number = 7; double result = apple - number * pieceUnit; // 결과값에 마지막으로 10을 나눠준다 result = result / 10; System.out.println(result); } }
package com.pangpang6.books.offer.chapter2; import com.google.common.collect.Maps; import com.pangpang6.books.offer.structure.BinaryTreeNode; import java.util.Map; /** * 根据前序和中序序列(不含有重复的数字),构建一棵二叉树 * <p> */ public class b06_重建二叉树 { public static BinaryTreeNode constructBinaryTree(int[] pre, int[] in) { if (pre == null || in == null || pre.length != in.length || in.length <= 0) { return null; } //中序遍历的值 map 节点顺讯 Map<Integer, Integer> map = Maps.newHashMap(); for (int i = 0, size = in.length; i < size; i++) { map.put(in[i], i); } return construct(pre, 0, pre.length - 1, 0, map); } public static BinaryTreeNode construct(int[] preArr, int preStart, int preEnd, int inStart, Map<Integer, Integer> inMap) { //开始位置大于结束位置,说明已经没有需要处理的元素了 if (preStart > preEnd) { return null; } //取前序遍历的第一个数字,就是当前的根结点 int rootValue = preArr[preStart]; // 在中序遍历的数组中找根结点的位置 int inRootIndex = inMap.get(rootValue); //创建当前根节点 BinaryTreeNode head = new BinaryTreeNode(rootValue); //递归: //左边开始的节点=原开始节点+1 int leftStart = preStart + 1; //左边结束的节点=原开始节点 + 中序根节点-中序开始节点 int leftEnd = preStart + inRootIndex - inStart; //右边开始节点=原开始节点 + 1 + 中序根节点-中序开始节点 int rightStart = preStart + 1 + inRootIndex - inStart; //右边结束节点=原结束节点 int rightEnd = preEnd; head.left = construct(preArr, leftStart, leftEnd, inStart, inMap); head.right = construct(preArr, rightStart, rightEnd, inRootIndex + 1, inMap); return head; } public static void main(String[] args) { test1(); System.out.println(); test2(); System.out.println(); test3(); System.out.println(); test4(); System.out.println(); test5(); System.out.println(); test6(); System.out.println(); // test7(); } // 普通二叉树 // 1 // / \ // 2 3 // / / \ // 4 5 6 // \ / // 7 8 private static void test1() { int[] pre = {1, 2, 4, 7, 3, 5, 6, 8}; int[] in = {4, 7, 2, 1, 5, 3, 8, 6}; BinaryTreeNode root = constructBinaryTree(pre, in); System.out.println(root); } // 所有结点都没有右子结点 // 1 // / // 2 // / // 3 // / // 4 // / // 5 private static void test2() { int[] pre = {1, 2, 3, 4, 5}; int[] in = {5, 4, 3, 2, 1}; BinaryTreeNode root = constructBinaryTree(pre, in); } // 所有结点都没有左子结点 // 1 // \ // 2 // \ // 3 // \ // 4 // \ // 5 private static void test3() { int[] pre = {1, 2, 3, 4, 5}; int[] in = {1, 2, 3, 4, 5}; BinaryTreeNode root = constructBinaryTree(pre, in); } // 树中只有一个结点 private static void test4() { int[] pre = {1}; int[] in = {1}; BinaryTreeNode root = constructBinaryTree(pre, in); } // 完全二叉树 // 1 // / \ // 2 3 // / \ / \ // 4 5 6 7 private static void test5() { int[] pre = {1, 2, 4, 5, 3, 6, 7}; int[] in = {4, 2, 5, 1, 6, 3, 7}; BinaryTreeNode root = constructBinaryTree(pre, in); } // 输入空指针 private static void test6() { constructBinaryTree(null, null); } // 输入的两个序列不匹配 private static void test7() { int[] pre = {1, 2, 4, 5, 3, 6, 7}; int[] in = {4, 2, 8, 1, 6, 3, 7}; BinaryTreeNode root = constructBinaryTree(pre, in); } }
package com.example.demo.services; import org.springframework.stereotype.*; @Service public class VisitorsServices { public static final Integer LOGIN_STATUS_ACVTIVE=1; public static final Integer LOGIN_STATUS_BLOCKED=2; }
package swexpert; import java.util.Scanner; public class SWEA_2068_D1_최대수_구하기 { public static void main(String[] args) { // TODO Auto-generated method stub Scanner s = new Scanner(System.in); StringBuilder sb = new StringBuilder(); int TC = s.nextInt(); for (int i = 1; i <= TC; i++) { sb.append("#").append(i).append(" "); int max = Integer.MIN_VALUE; for(int j=1;j <=10; j++) { int num = s.nextInt(); if(num >max) max =num; } sb.append(max).append("\n"); } System.out.println(sb); } }
package com.literature.service.impl; import com.literature.common.JsonApi; import com.literature.entity.*; import com.literature.repository.*; import com.literature.service.IBookService; import com.literature.vo.CommentVo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; @Service public class BookService implements IBookService { @Autowired private BookRepository bookRepository; @Autowired private CommentRepository commentRepository; @Autowired private NominateRepository nominateRepository; @Autowired private CollectionsRepository collectionsRepository; @Autowired private CustomerInfoRepository customerInfoRepository; @Override public List<Books> find(String title, Integer page, Integer size) { return bookRepository.find(title,page,size); } @Override public void addBook(Books book) { bookRepository.save(book); } @Override public void deleteById(String id) { bookRepository.deleteById(id); } @Override public Books findById(String id) { return bookRepository.findBooksById(id); } @Override public void updateBook(Books books) { bookRepository.save(books); } @Override public List<Books> findBooksByTitle(String title) { return bookRepository.findBooksByTitle(title); } @Override public List<Comments> findComment(String title, Integer page, Integer size) { return commentRepository.find(title,page,size); } @Override public List<Comments> findCommentByTitle(String title) { return commentRepository.findByTitle(title); } @Override public List<Comments> findCommentAll() { return commentRepository.findAll(); } @Override public Comments findComnentById(String id) { return commentRepository.findCommentsById(id); } @Override public void deleteCommentById(String id) { commentRepository.deleteById(id); } @Override public void setNominate(Nominate nominate) { nominateRepository.save(nominate); } @Override public List<Comments> findCustComment(String title, String id, Integer page, Integer size) { return commentRepository.findCust(title,id,page,10); } @Override public List<Comments> findCustCommentByTitle(String title, String id) { return commentRepository.findCustByTitle(title,id); } @Override public Map findCustBook(String title, String userid, Integer page) { Map map = new HashMap(); map.put("total",bookRepository.findCustTitle(title,userid).size()); map.put("bookList",bookRepository.findCustByUserid(title,userid,page)); return map; } @Override public void deleteCollections(String bid, String uid) { collectionsRepository.deleteCollection(bid,uid); } @Override public void addCollection(Collections collections) { collectionsRepository.save(collections); } @Override public List<Books> getBookListByNominate(Integer page) { Nominate nominate = nominateRepository.findAll().get(0); List<Books> bookList = new ArrayList<>(); if (null!=nominate && nominate.getCondition().equals("rating")) { bookList = bookRepository.getListByRating(page); }else if (null!=nominate && nominate.getCondition().equals("collection")) { bookList = bookRepository.getListByCollection(page); }else { // 如果没有设置推荐条件默认评分推荐 bookList = bookRepository.getListByRating(page); } return bookList; } @Override public void addComment(Comments comments) { commentRepository.save(comments); } @Override public JsonApi getBooks(String id) { Map map = new HashMap(); Books books = bookRepository.findBooksById(id); String score = bookRepository.getBookRating(id); map.put("book",books); map.put("score",score); return new JsonApi(map); } @Override public List<CommentVo> getComments(String id,Integer page) { List<Comments> list = new ArrayList<>(); if (null!=page && page==1) { list = commentRepository.findCommentsByBookId(id,0); }else { list = commentRepository.findCommentsByBookId(id,(page-1)*10); } List<CommentVo> commentList = new ArrayList<>(); for (Comments c1 :list) { CustomerInfo c = customerInfoRepository.findCustomerInfoById(c1.getUserId()); CommentVo cv = new CommentVo(); cv.setId(c1.getId()); cv.setTitle(c1.getTitle()); if (null!=c){ cv.setUsername(c.getUsername()); } cv.setUserid(c1.getUserId()); cv.setContent(c1.getContent()); cv.setCreated(c1.getCreated()); cv.setRating(c1.getRating()); commentList.add(cv); } return commentList; } @Override public List<String> getUsersId(String id) { return collectionsRepository.getUsersId(id); } }
/* * 2012-3 Red Hat Inc. and/or its affiliates and other contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.overlord.rtgov.ep.jpa; import static org.junit.Assert.fail; import java.net.URL; import org.hibernate.Session; import org.junit.Test; import org.overlord.rtgov.common.jpa.JpaStore; import org.overlord.rtgov.common.jpa.JpaStore.JpaWork; public class JPAEventProcessorTest { @Test public void testPersistEvent() { URL configXml = JPAEventProcessorTest.class.getClassLoader().getResource("hibernate-test.cfg.xml"); JpaStore jpaStore = new JpaStore(configXml); JPAEventProcessor eventProcessor = new JPAEventProcessor(jpaStore); doTest(jpaStore, eventProcessor); } @Test public void testPersistEventWithConfig() { JPAEventProcessor eventProcessor = new JPAEventProcessor(); eventProcessor.setConfiguration("hibernate-test.cfg.xml"); ClassLoader cl=Thread.currentThread().getContextClassLoader(); try { Thread.currentThread().setContextClassLoader(JPAEventProcessorTest.class.getClassLoader()); eventProcessor.init(); } catch (Exception e) { fail("Failed to initialize the JPA event processor: "+e); } finally { Thread.currentThread().setContextClassLoader(cl); } doTest(eventProcessor.getJpaStore(), eventProcessor); } @Test public void testPersistEventJpa() { JpaStore jpaStore = new JpaStore("overlord-rtgov-ep-jpa"); JPAEventProcessor eventProcessor = new JPAEventProcessor(jpaStore); doTest(jpaStore, eventProcessor); } private void doTest(JpaStore jpaStore, JPAEventProcessor eventProcessor) { TestEvent te1=new TestEvent(); te1.setId("1"); te1.setDescription("Hello"); try { eventProcessor.process(null, te1, 1); } catch (Exception e) { e.printStackTrace(); fail("Failed to process test event 1 with JPA event processor: "+e); } TestEvent te2=new TestEvent(); te2.setId("2"); te2.setDescription("World"); try { eventProcessor.process(null, te2, 1); } catch (Exception e) { fail("Failed to process test event 2 with JPA event processor: "+e); } TestEvent result = jpaStore.withJpa(new JpaWork<TestEvent>() { public TestEvent perform(Session s) { return (TestEvent) s.get(TestEvent.class, "1"); } }); if (result == null) { fail("Result is null"); } if (!result.getDescription().equals("Hello")) { fail("Expecting 'Hello', but got: "+result.getDescription()); } } }
package com.yida.design.model.impl; import com.yida.design.model.HummerModel; /** ********************* * @author yangke * @version 1.0 * @created 2018年4月20日 下午5:37:02 *********************** */ public class HummerH1Model extends HummerModel { @Override public void start() { System.out.println("悍马H1发动..."); } @Override public void stop() { System.out.println("悍马H1停车..."); } @Override public void alarm() { System.out.println("悍马H1鸣笛..."); } @Override public void engineBoom() { System.out.println("悍马H1引擎声音是这样的..."); } }
package br.ita.sem2dia1.AprofundandoClassesJava.escola; public class Aluno { public int bim1; public int bim2; public int bim3; public int bim4; public char[] media() { // TODO Auto-generated method stub return null; } public char[] passouDeAno() { // TODO Auto-generated method stub return null; } }
package kr.ko.nexmain.server.MissingU.msgbox.dao; import java.util.List; import java.util.Map; import kr.ko.nexmain.server.MissingU.common.model.CommReqVO; import kr.ko.nexmain.server.MissingU.msgbox.model.LnkMsgboxMsgVO; import kr.ko.nexmain.server.MissingU.msgbox.model.MsgBoxConversSendVO; import kr.ko.nexmain.server.MissingU.msgbox.model.MsgBoxConversVO; import kr.ko.nexmain.server.MissingU.msgbox.model.MsgBoxVO; import kr.ko.nexmain.server.MissingU.msgbox.model.MsgListReqVO; import kr.ko.nexmain.server.MissingU.msgbox.model.MsgVO; public interface MsgBoxDao { ///----------------------------------------------------------------------------------------------------------------------------------------/// /// 새로 개발되는 쪽지함(시작) ///----------------------------------------------------------------------------------------------------------------------------------------/// /** 쪽지 리스트 조회 */ public List<Map<String, Object>> selectMessageBoxListByMemberId(Integer memberId); /** 쪽지 대화 리스트 조회 */ public List<Map<String, Object>> selectMessageBoxConversationByMemberId(MsgBoxConversVO msgBoxConverVO); /** 쪽지 읽음 처리 */ public int updateMessageBoxReadAll(MsgBoxConversVO msgBoxConverVO); /** 쪽지 발송 */ public long insertMessageBoxMsg(MsgBoxConversSendVO msgBoxConverSendVO); /** 쪽지 발송 : 동일한 내용이지만 수신자 발신자를 복사해서 반대로 넣어둔다.(운영상의 이점이 있음) */ public long insertMessageBoxMsgEcho(MsgBoxConversSendVO msgBoxConverSendVO); /** 쪽지 삭제 */ public int deleteConversMsg(MsgBoxConversVO msgBoxConverVO); /** 쪽지 보기 */ public Map<String, Object> selectMsgConvers(MsgBoxConversSendVO msgBoxConversSendVO); ///----------------------------------------------------------------------------------------------------------------------------------------/// /// 새로 개발되는 쪽지함(끝) ///----------------------------------------------------------------------------------------------------------------------------------------/// /** 쪽지함 리스트 조회 */ public List<Map<String,Object>> selectMsgBoxListByMemberId(Integer memberId); /** 쪽지함 조회 */ public Map<String,Object> selectMsgboxByMemberIdAndSenderId(MsgBoxVO inputVO); /** 쪽지 리스트 조회 */ public List<Map<String,Object>> selectMsgListByMsgboxId(MsgListReqVO inputVO); /** 쪽지함 Insert */ public Long insertIntoMsgbox(MsgBoxVO inputVO); /** 쪽지 Insert*/ public Long insertIntoMsg(MsgVO inputVO); /** 링크_쪽지함_쪽지 Insert*/ public int insertIntoLnkMsgboxMsg(LnkMsgboxMsgVO inputVO); /** 링크_쪽지함_쪽지 Delete*/ public int deleteLnkMsgboxMsgByMsgId(LnkMsgboxMsgVO inputVO); /** 쪽지함 Status 업데이트*/ public int updateMsgboxStatus(MsgBoxVO inputVO); /** 쪽지 읽기여부 업데이트*/ public int updateMsgAsRead(Long msgboxId); /** 쪽지 읽기여부 업데이트*/ public int updateMsgAsReadByMsgId(Long msgId); /** 쪽지 읽기여부 업데이트*/ public int updateMsgAsReadYNToogleByMsgId(Long msgId); /** 미확인 쪽지 수 */ Integer selectUnreadMsgCntByMemberId(Integer memberId); /** 내 쪽지 리스트 조회 */ public List<Map<String,Object>> selectMyMsgList(CommReqVO inputVO); /** 쪽지 조회 */ public Map<String,Object> selectMsgByMsgId(Long msgId); /** 쪽지확인 여부 조회 */ Integer selectUnreadMsgCntByMsgId(Long msgId); }
package me.jessepayne.pad4j.visualizer.swing.theme; import me.jessepayne.pad4j.visualizer.swing.VirtualUIManager; import java.util.Timer; public class ThemeManager { private VirtualUIManager uiManager; private LPTheme theme = LPTheme.AQUA; private Timer fadeTimer = new Timer(); private boolean fadeRunning = false; public ThemeManager(VirtualUIManager uiManager){ this.uiManager = uiManager; } public VirtualUIManager getUiManager(){ return uiManager; } public LPTheme getTheme(){ return theme; } public boolean fadeTheme(LPTheme newTheme){ if(fadeRunning){ System.out.println("Fade is already running!"); return false; }else{ if(newTheme.equals(theme)){ System.out.println("You can't fade to the theme that is already selected!"); return false; } ThemeChangeTask task = new ThemeChangeTask(this, 55, theme, newTheme); fadeTimer.scheduleAtFixedRate(task, 0L, 50L); return true; } } public void setTheme(LPTheme theme){ this.theme = theme; uiManager.update(); } public boolean switchTheme(LPTheme theme){ if(fadeRunning){ System.out.println("Cannot switch theme while fade is running!"); return false; }else{ setTheme(theme); return true; } } public void setIsFading(boolean isFading){ fadeRunning = isFading; } public boolean isFadeRunning(){ return fadeRunning; } }
/* import java.applet.Applet; import java.awt.Button; import java.awt.Graphics; import java.awt.Label; import java.awt.TextFeild; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; /* * <applet code="AppletLoan" width=280 height=200> </applet> public class AppletLoan extends Applet implements ActionListener{ TextField amountText, paymentText, periodText, rateText; Button doIt; double principal; // original princial double intRate; // interest rate double numYears; // length of loan in years int pay = 12; public void init(){ } } */ import java.applet.Applet; import java.awt.Button; import java.awt.Graphics; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Label; import java.awt.TextField; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.text.NumberFormat; /* * <applet code="RegPay" width=280 height=200> </applet> */ public class RegPay extends Applet implements ActionListener { TextField amountText, paymentText, periodText, rateText; Button doIt; double principal; // original princial double intRate; // interest rate double numYears; // length of loan in years /* * Number of payments per year. You could allow this value to be set by the * user. */ final int payPerYear = 12; NumberFormat nf; public void init() { // Use a grid bag layout. GridBagLayout gbag = new GridBagLayout(); GridBagConstraints gbc = new GridBagConstraints(); setLayout(gbag); Label heading = new Label("Compute Monthly Loan Payments"); Label amountLab = new Label("Principal"); Label periodLab = new Label("Years"); Label rateLab = new Label("Interest Rate"); Label paymentLab = new Label("Monthly Payments"); amountText = new TextField(16); periodText = new TextField(16); paymentText = new TextField(16); rateText = new TextField(16); // Payment field for display only. paymentText.setEditable(false); doIt = new Button("Compute"); // Define the grid bag. gbc.weighty = 1.0; // use a row weight of 1 gbc.gridwidth = GridBagConstraints.REMAINDER; gbc.anchor = GridBagConstraints.NORTH; gbag.setConstraints(heading, gbc); // Anchor most components to the right. gbc.anchor = GridBagConstraints.EAST; gbc.gridwidth = GridBagConstraints.RELATIVE; gbag.setConstraints(amountLab, gbc); gbc.gridwidth = GridBagConstraints.REMAINDER; gbag.setConstraints(amountText, gbc); gbc.gridwidth = GridBagConstraints.RELATIVE; gbag.setConstraints(periodLab, gbc); gbc.gridwidth = GridBagConstraints.REMAINDER; gbag.setConstraints(periodText, gbc); gbc.gridwidth = GridBagConstraints.RELATIVE; gbag.setConstraints(rateLab, gbc); gbc.gridwidth = GridBagConstraints.REMAINDER; gbag.setConstraints(rateText, gbc); gbc.gridwidth = GridBagConstraints.RELATIVE; gbag.setConstraints(paymentLab, gbc); gbc.gridwidth = GridBagConstraints.REMAINDER; gbag.setConstraints(paymentText, gbc); gbc.anchor = GridBagConstraints.CENTER; gbag.setConstraints(doIt, gbc); // Add all the components. add(heading); add(amountLab); add(amountText); add(periodLab); add(periodText); add(rateLab); add(rateText); add(paymentLab); add(paymentText); add(doIt); // Register to receive action events. amountText.addActionListener(this); periodText.addActionListener(this); rateText.addActionListener(this); doIt.addActionListener(this); nf = NumberFormat.getInstance(); nf.setMinimumFractionDigits(2); nf.setMaximumFractionDigits(2); } /* * User pressed Enter on a text field or pressed Compute. */ public void actionPerformed(ActionEvent ae) { repaint(); } // Display the result if all fields are completed. public void paint(Graphics g) { double result = 0.0; String amountStr = amountText.getText(); String periodStr = periodText.getText(); String rateStr = rateText.getText(); try { if (amountStr.length() != 0 && periodStr.length() != 0 && rateStr.length() != 0) { principal = Double.parseDouble(amountStr); numYears = Double.parseDouble(periodStr); intRate = Double.parseDouble(rateStr) / 100; result = compute(); paymentText.setText(nf.format(result)); } showStatus(""); // erase any previous error message } catch (NumberFormatException exc) { showStatus("Invalid Data"); paymentText.setText(""); } } // Compute the loan payment. double compute() { double numer; double denom; double b, e; numer = intRate * principal / payPerYear; e = -(payPerYear * numYears); b = (intRate / payPerYear) + 1.0; denom = 1.0 - Math.pow(b, e); return numer / denom; } }
import java.awt.BorderLayout; import java.awt.Container; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.util.ArrayList; import java.util.Arrays; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JTextField; import javax.swing.SwingConstants; public class StartMenu extends Menu{ Menu menu = new Menu(); //ArrayList<Customer> customerList = menu.returnArray(); CustomerAccount acc = Menu.returnAcc(); MenuButtons button = new MenuButtons(); MenuGUI menugui = new MenuGUI(); public void newCustomerGUI() { createNewCustomerFrame = new JFrame("Create New Customer"); createNewCustomerFrame.setSize(400, 300); createNewCustomerFrame.setLocation(200, 200); Container content = createNewCustomerFrame.getContentPane(); content.setLayout(new BorderLayout()); firstNameLabel = new JLabel("First Name:", SwingConstants.RIGHT); surnameLabel = new JLabel("Surname:", SwingConstants.RIGHT); pPPSLabel = new JLabel("PPS Number:", SwingConstants.RIGHT); dOBLabel = new JLabel("Date of birth", SwingConstants.RIGHT); firstNameTextField = new JTextField(20); surnameTextField = new JTextField(20); pPSTextField = new JTextField(20); dOBTextField = new JTextField(20); JPanel panel = new JPanel(new GridLayout(6, 2)); panel.add(firstNameLabel); panel.add(firstNameTextField); panel.add(surnameLabel); panel.add(surnameTextField); panel.add(pPPSLabel); panel.add(pPSTextField); panel.add(dOBLabel); panel.add(dOBTextField); panel2 = new JPanel(); add = new JButton("Add"); add.addActionListener(new ActionListener( ) { public void actionPerformed(ActionEvent ae) { newCustomer(); } }); JButton cancel = new JButton("Cancel"); cancel.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { button.returnButton(); } }); panel2.add(add); panel2.add(cancel); content.add(panel, BorderLayout.CENTER); content.add(panel2, BorderLayout.SOUTH); createNewCustomerFrame.setVisible(true); } public void administrator() { boolean checkAdminUsername = true, checkAdminPassword = true; boolean cont = false; while(checkAdminUsername) { Object adminUsername = JOptionPane.showInputDialog(menu.userTypeFrame, "Enter Administrator Username:"); if(!adminUsername.equals("admin")) { int reply = JOptionPane.showConfirmDialog(null, null, "Incorrect Username. Try again?", JOptionPane.YES_NO_OPTION); if (reply == JOptionPane.YES_OPTION) { checkAdminUsername = true; } else if(reply == JOptionPane.NO_OPTION) { menu.createNewCustomerFrame.dispose(); checkAdminUsername = false; checkAdminPassword = false; button.returnButton(); } } else { checkAdminUsername = false; } } while(checkAdminPassword) { Object adminPassword = JOptionPane.showInputDialog(menu.userTypeFrame, "Enter Administrator Password;"); if(!adminPassword.equals("admin11")){ int reply = JOptionPane.showConfirmDialog(null, null, "Incorrect Password. Try again?", JOptionPane.YES_NO_OPTION); if (reply == JOptionPane.YES_OPTION) { } else if(reply == JOptionPane.NO_OPTION){ checkAdminPassword = false; button.returnButton(); } } else { checkAdminPassword =false; cont = true; } } if(cont) { checkAdminUsername = false; button.returnAdmin(); } } public void existingCustomer() { Customer customer = null; boolean checkCustomerId = true, checkCustomerPassword = true, cont = false, found = false; //testCustomer(); while(checkCustomerId){ Object customerID = JOptionPane.showInputDialog(menu.userTypeFrame, "Enter Customer ID:"); for (Customer aCustomer: menu.customerList){ if(aCustomer.getCustomerID().equals(customerID)) { found = true; customer = aCustomer; } } if(found == false) { int reply = JOptionPane.showConfirmDialog(null, null, "User not found. Try again?", JOptionPane.YES_NO_OPTION); if (reply == JOptionPane.YES_OPTION) { checkCustomerId = true; } else if(reply == JOptionPane.NO_OPTION) { checkCustomerId = false; checkCustomerPassword = false; button.returnButton(); } }else{ checkCustomerId = false; } } while(checkCustomerPassword){ Object customerPassword = JOptionPane.showInputDialog(menu.userTypeFrame, "Enter Customer Password;"); if(!customer.getPassword().equals(customerPassword)) { int reply = JOptionPane.showConfirmDialog(null, null, "Incorrect password. Try again?", JOptionPane.YES_NO_OPTION); if (reply == JOptionPane.YES_OPTION) { } else if(reply == JOptionPane.NO_OPTION){ checkCustomerPassword = false; button.returnButton(); } } else { checkCustomerPassword =false; cont = true; } } if(cont) { checkCustomerId = false; button.returnCustomer(); } } public void newCustomer() { PPS = pPSTextField.getText(); firstName = firstNameTextField.getText(); surname = surnameTextField.getText(); DOB = dOBTextField.getText(); setPassword(""); CustomerID = "ID" + PPS; boolean passwordCorrect = true; while(passwordCorrect){ String password = JOptionPane.showInputDialog(userTypeFrame, "Enter 7 character Password;"); if(password.length() != 7) { JOptionPane.showMessageDialog(null, null, "Password must be 7 charatcers long", JOptionPane.OK_OPTION); }else { passwordCorrect = false; } } ArrayList<CustomerAccount> accounts = new ArrayList<CustomerAccount> (); Customer customer = new Customer(PPS, surname, firstName, DOB, CustomerID, getPassword(), accounts); //customerList.add(customer); addCustomer(customer); JOptionPane.showMessageDialog(userTypeFrame, "CustomerID = " + CustomerID + "\n Password = " + getPassword(), "Customer created.", JOptionPane.INFORMATION_MESSAGE); menuStart(); userTypeFrame.dispose(); } public void closeWindow() { userTypeFrame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent we) { System.exit(0); } }); } // public ArrayList testCustomer() { // //populating customerList for testing purpose //// ArrayList<CustomerAccount> ca = new ArrayList<>(Arrays.asList(new CustomerDepositAccount(1.5,"D1234", 2000.0, new ArrayList<AccountTransaction>()))); //// ca.add(new CustomerCurrentAccount(new ATMCard(1234, true),"C1234",1000.0, new ArrayList<AccountTransaction>())); //// ArrayList customerList = new ArrayList<>(Arrays.asList(new Customer ("1234","Joe","Bloggs","11061998","ID1234","1234",ca))); // //customerList.add( // return ; // } }
package se.gareth.swm; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.RectF; public class WorldIcon extends Button { private static Sprite mIconSprite; private static Sprite mIconSpriteDisabled; private Animation mIconAnimation; private Animation mIconDisabledAnimation; private RectF mThumbnailRect; private final TextDrawable mWorldNameText; private final TextDrawable mHighScoreText; private final TextDrawable mLevelsText; private final WorldDescriptor mWorldDescriptor; private final Bitmap mMapThumbnail; private Paint mMapPaint; public WorldIcon(GameBase gameBase, WorldDescriptor worldDescriptor) { super(gameBase); mWorldDescriptor = worldDescriptor; mWorldNameText = new TextDrawable(gameBase.gameView.font); mWorldNameText.setTextSize(game.res.getDimension(R.dimen.SmallFontSize), true); mWorldNameText.setOutline(game.res.getDimension(R.dimen.SmallFontOutline), game.res.getColor(R.color.NormalOutlineColor)); mWorldNameText.setColor(game.res.getColor(R.color.LightFontColor)); mWorldNameText.setTextAlign(TextDrawable.Align.CENTER); mWorldNameText.setText(worldDescriptor.getName()); mHighScoreText = new TextDrawable(gameBase.gameView.font); mHighScoreText.setTextSize(game.res.getDimension(R.dimen.NormalFontSize), false); mHighScoreText.setColor(Color.rgb(0xfe, 0xda, 0xdb)); mHighScoreText.setTextAlign(TextDrawable.Align.CENTER); mLevelsText = new TextDrawable(gameBase.gameView.font); mLevelsText.setTextSize(game.res.getDimension(R.dimen.HugeFontSize), false); mLevelsText.setColor(game.res.getColor(R.color.LightFontColor)); mLevelsText.setTextAlign(TextDrawable.Align.CENTER); if (mIconSprite == null) { mIconSprite = new Sprite(BitmapFactory.decodeResource(game.res, R.drawable.world_icon), 1); } if (mIconSpriteDisabled == null) { mIconSpriteDisabled = new Sprite(BitmapFactory.decodeResource(game.res, R.drawable.world_icon_disabled), 1); } mIconAnimation = new Animation(mIconSprite, 0, 0); mIconDisabledAnimation = new Animation(mIconSpriteDisabled, 0, 0); setAnimation(mIconAnimation); mMapPaint = new Paint(); /* get map thumbnail */ Background background = worldDescriptor.getBackground(); mMapThumbnail = background.getThumbnail(); mThumbnailRect = new RectF(); setAlpha(255); } public WorldDescriptor getDescriptor() { return mWorldDescriptor; } public void setStats(boolean disable, int highscore, int currentLevel) { if (highscore >= 0) { mHighScoreText.setText("" + highscore); } else { mHighScoreText.setText("-"); } mLevelsText.setText(currentLevel + "/"+ mWorldDescriptor.getNumLevels()); if (disable) { disable(); setAnimation(mIconDisabledAnimation); mWorldNameText.setColor(game.res.getColor(R.color.GreyFontColor)); } else { enable(); setAnimation(mIconAnimation); mWorldNameText.setColor(game.res.getColor(R.color.LightFontColor)); } } @Override public void setAlpha(int alpha) { super.setAlpha(alpha); mWorldNameText.setAlpha(alpha); mHighScoreText.setAlpha(alpha); mLevelsText.setAlpha((int)((double)alpha * 0.5)); if (this.isEnable()) { mMapPaint.setAlpha((int)((double)alpha * 0.75)); } else { mMapPaint.setAlpha((int)((double)alpha * 0.15)); } } @Override public void update(final TimeStep timeStep) { super.update(timeStep); mWorldNameText.setPosition(getX(-0.15), getTop() + mWorldNameText.getHeight() / 1.4); mLevelsText.setPosition(getX(-0.15), getY(0.1)); mHighScoreText.setPosition(getX(0.348), getY(0.1)); } @Override public void draw(Canvas canvas) { super.draw(canvas); if (mVisible) { mThumbnailRect.set((float)getX(-0.47), (float)getY(-0.36), (float)getX(0.18), (float)getY(0.4)); if (mMapThumbnail != null) { canvas.drawBitmap(mMapThumbnail, null, mThumbnailRect, mMapPaint); } if (this.isEnable()) { mHighScoreText.draw(canvas); mLevelsText.draw(canvas); } mWorldNameText.draw(canvas); } } }
package geg; public class World{ private long oxygenLevel = 0; private long generation = 0; public World(){ } // GETTERS AND SETTERS public void setOxygenLevel(long ogyxenLevel){ if(byte < 0 || byte > 100){ throw new IllegalArgumentException("invalid range, 0 - 100 inclusive"); } this.oxygen = percentage; } public long getOxygenLevel(){ return oxygenLevel; } private void setGeneration(long generation){ } public long getGeneration(){ return generation; } }
package fr.bodysplash.bwish.server; import java.io.IOException; import javax.jdo.PersistenceManager; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import com.google.inject.Inject; import com.google.inject.Injector; import com.google.inject.Singleton; @Singleton public class FermerSessionFilter implements Filter{ @Inject private Injector injector; @Override public void destroy() { } @Override public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2) throws IOException, ServletException { PersistenceManager instance = injector.getInstance(PersistenceManager.class); arg2.doFilter(arg0, arg1); instance.close(); } @Override public void init(FilterConfig arg0) throws ServletException { } }
package Commons; public class Validate { }
/* * [y] hybris Platform * * Copyright (c) 2018 SAP SE or an SAP affiliate company. All rights reserved. * * This software is the confidential and proprietary information of SAP * ("Confidential Information"). You shall not disclose such Confidential * Information and shall use it only in accordance with the terms of the * license agreement you entered into with SAP. */ package de.hybris.platform.cmsfacades.synchronization.itemvisitors.impl; import static com.google.common.collect.Lists.newArrayList; import de.hybris.platform.cms2.model.navigation.CMSNavigationEntryModel; import de.hybris.platform.core.model.ItemModel; import de.hybris.platform.servicelayer.model.visitor.ItemVisitor; import java.util.List; import java.util.Map; /** * Concrete implementation of {@link ItemVisitor} to visit items of the {@link CMSNavigationEntryModel} type. * * Returns the items from {@link CMSNavigationEntryModel#getItem()} * */ public class CMSNavigationEntryModelVisitor implements ItemVisitor<CMSNavigationEntryModel> { @Override public List<ItemModel> visit(CMSNavigationEntryModel source, List<ItemModel> path, Map<String, Object> ctx) { return newArrayList(source.getItem()); } }
package csci152; public class Student { private String firstName; private String lastName; private int id; private int year; public Student(String firstName, String lastName, int id) { this.firstName = firstName; this.lastName = lastName; this.id = id; this.year = 1; } public void incrementYear() { this.year++; } public String getFirstName() { return this.firstName; } public String getLastName() { return this.lastName; } public int getId() { return this.id; } public int getYear() { return this.year; } @Override public String toString() { return "Full name: " + firstName + " " + lastName + "\n" +"ID: " + id + "\n" + "Year: " + year + "\n"; } }
package com.tencent.mm.plugin.sns.ui; import android.view.MotionEvent; import android.view.View; import android.view.View.OnTouchListener; class SnsMsgUI$17 implements OnTouchListener { final /* synthetic */ SnsMsgUI nYl; SnsMsgUI$17(SnsMsgUI snsMsgUI) { this.nYl = snsMsgUI; } public final boolean onTouch(View view, MotionEvent motionEvent) { switch (motionEvent.getAction()) { case 0: this.nYl.YC(); SnsMsgUI.j(this.nYl)[0] = (int) motionEvent.getRawX(); SnsMsgUI.j(this.nYl)[1] = (int) motionEvent.getRawY(); break; } return false; } }
package com.chuxin.family.parse.been; import com.chuxin.family.parse.been.data.CxMateProfileDataField; /** * 用户结对的对方的资料获取类 * @author shichao.wang * */ public class CxMateProfile extends CxParseBasic{ private CxMateProfileDataField data; public CxMateProfileDataField getData() { return data; } public void setData(CxMateProfileDataField data) { this.data = data; } }
package com.tencent.mm.plugin.music.model.c; import android.os.Handler; import android.os.Looper; import android.os.SystemClock; import com.google.android.exoplayer2.Format; import com.google.android.exoplayer2.g.b; import com.google.android.exoplayer2.h.k; import com.google.android.exoplayer2.metadata.Metadata; import com.google.android.exoplayer2.source.f; import com.google.android.exoplayer2.v; import com.tencent.mars.smc.IDKey; import com.tencent.mm.an.d; import com.tencent.mm.g.a.jt; import com.tencent.mm.plugin.music.model.h; import com.tencent.mm.protocal.c.avq; import com.tencent.mm.sdk.platformtools.ah; import com.tencent.mm.sdk.platformtools.x; import com.tenpay.android.wechat.PayuSecureEncrypt$EncrptType; import java.util.ArrayList; public final class a extends com.tencent.mm.plugin.music.model.e.a implements com.google.android.exoplayer2.h.d.a, com.google.android.exoplayer2.metadata.e.a { private long aBL; int aBN = 0; protected String aBr; boolean auM = false; protected com.tencent.mm.an.a bTF; int dGs = 0; public Handler fLN = new 1(this, Looper.myLooper()); boolean lxb; private String lxf = ""; private long lxh = 0; avq lyK; private d lyL; int lyM = 0; public v lyN; public b lyO; private k lyP; public com.google.android.exoplayer2.h.f.a lyQ; public f lyR; f lyS = new f((byte) 0); public a lyT = new a(this, (byte) 0); e lyU = new e(this, (byte) 0); d lyV = new d(this, (byte) 0); b lyW = new c(); public boolean lyX = false; public class c implements b { public final void bik() { x.i("MicroMsg.Music.ExoMusicPlayer", "onPrepared"); if (a.this.lyK != null) { a.this.n(a.this.lyK); } if (a.this.dGs > 0) { x.i("MicroMsg.Music.ExoMusicPlayer", "onPrepared, seekTo startTime:%d,", new Object[]{Integer.valueOf(a.this.dGs)}); a.this.if(a.this.dGs); } if (a.this.dGs == 0 && !a.this.lyN.iC()) { x.i("MicroMsg.Music.ExoMusicPlayer", "onPrepared, set play when ready"); a.this.lyN.af(true); } } public final void bil() { x.i("MicroMsg.Music.ExoMusicPlayer", "onStart"); if (a.this.lyK != null) { a.this.o(a.this.lyK); } } public final void bim() { x.i("MicroMsg.Music.ExoMusicPlayer", "onPause"); if (a.this.lyK != null && !a.this.lyN.iC()) { a.this.q(a.this.lyK); } } public final void bin() { x.i("MicroMsg.Music.ExoMusicPlayer", "onStop"); if (a.this.lyK != null) { a.this.r(a.this.lyK); } } public final void bio() { x.i("MicroMsg.Music.ExoMusicPlayer", "onSeekComplete"); if (a.this.lyK != null) { a.this.s(a.this.lyK); } if (a.this.dGs > 0 && a.this.lyN != null && !a.this.lyN.iC()) { x.i("MicroMsg.Music.ExoMusicPlayer", "onSeekComplete, stay play hls"); a.this.dGs = 0; a.this.lyN.af(true); } } public final void bip() { x.i("MicroMsg.Music.ExoMusicPlayer", "onComplete"); if (a.this.lyK != null) { a.this.u(a.this.lyK); } a.this.lxb = false; a.this.fLN.removeMessages(100); } public final void tF(int i) { x.i("MicroMsg.Music.ExoMusicPlayer", "onBufferingUpdate, percent:%d", new Object[]{Integer.valueOf(i)}); } public final void cZ(int i, int i2) { a aVar; x.i("MicroMsg.Music.ExoMusicPlayer", "onError what:%d, extra:%d", new Object[]{Integer.valueOf(i), Integer.valueOf(i2)}); if (a.this.lyK != null) { int i3; aVar = a.this; avq avq = a.this.lyK; x.i("MicroMsg.Music.ExoMusicPlayer", "onErrorEvent with extra:%d, errCode:%d", new Object[]{Integer.valueOf(i), Integer.valueOf(i2)}); aVar.lzq = "error"; jt jtVar = new jt(); jtVar.bTE.action = 4; jtVar.bTE.bTy = avq; jtVar.bTE.state = "error"; jtVar.bTE.duration = (long) aVar.getDuration(); jtVar.bTE.bTG = true; com.tencent.mm.g.a.jt.a aVar2 = jtVar.bTE; x.i("MicroMsg.Music.ExoPlayerErrorHandler", "getErrCodeType, errType: %d", new Object[]{Integer.valueOf(i)}); switch (i) { case -4999: i3 = -1; break; case -4005: case -4004: case -4003: case -4002: i3 = 10001; break; case -4001: i3 = 10004; break; case -4000: i3 = 10002; break; default: i3 = 0; break; } aVar2.errCode = i3; com.tencent.mm.g.a.jt.a aVar3 = jtVar.bTE; StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append("errCode:" + i2 + ", err:"); switch (i2) { case -4004: stringBuilder.append("load error"); break; case -4003: stringBuilder.append("MediaCodec decoder init exception"); break; case -4002: stringBuilder.append("illegal state exception"); break; case -4001: stringBuilder.append("UnrecognizedInputFormatException"); break; case -43: stringBuilder.append("error url format"); break; case -42: stringBuilder.append("stop error"); break; case -41: stringBuilder.append("prepare error"); break; case -30: stringBuilder.append(" network error"); break; case -13: stringBuilder.append(" network respCode 502"); break; case -12: stringBuilder.append(" network respCode 500"); break; case -11: stringBuilder.append(" network respCode 404"); break; case PayuSecureEncrypt$EncrptType.HASHED_PASSWORD /*-10*/: stringBuilder.append(" network respCode 403"); break; case -3: stringBuilder.append("connect fail"); break; case -2: stringBuilder.append(" no network"); break; case -1: stringBuilder.append("unknow exception"); break; } aVar3.Yy = stringBuilder.toString(); com.tencent.mm.sdk.b.a.sFg.a(jtVar, Looper.getMainLooper()); } if (a.this.lyN != null) { a.this.lyN.af(false); a.this.lyN.stop(); } a.this.lxb = false; a.this.fLN.removeMessages(100); aVar = a.this; aVar.aBN++; if (a.this.aBN == 1) { a.a(a.this.bTF, i, i2); } } } private class e implements com.google.android.exoplayer2.a.e { private e() { } /* synthetic */ e(a aVar, byte b) { this(); } public final void c(com.google.android.exoplayer2.b.d dVar) { x.i("MicroMsg.Music.ExoMusicPlayer", "audioEnabled [" + a.this.bij() + "]"); } public final void cb(int i) { x.i("MicroMsg.Music.ExoMusicPlayer", "audioSessionId [" + i + "]"); } public final void b(String str, long j, long j2) { x.i("MicroMsg.Music.ExoMusicPlayer", "audioDecoderInitialized [" + a.this.bij() + ", " + str + "]"); } public final void d(Format format) { x.i("MicroMsg.Music.ExoMusicPlayer", "audioFormatChanged [" + a.this.bij() + ", " + Format.a(format) + "]"); } public final void d(com.google.android.exoplayer2.b.d dVar) { x.i("MicroMsg.Music.ExoMusicPlayer", "audioDisabled [" + a.this.bij() + "]"); } public final void c(int i, long j, long j2) { x.printErrStackTrace("MicroMsg.Music.ExoMusicPlayer", null, "internalError [" + a.this.bij() + ", " + ("audioTrackUnderrun [" + i + ", " + j + ", " + j2 + "]") + "]", new Object[0]); } } public a() { com.tencent.mm.plugin.music.b.b.a.biB(); } public final void j(com.tencent.mm.an.a aVar) { long currentTimeMillis = System.currentTimeMillis(); long j = currentTimeMillis - this.lxh; if (this.bTF != null && this.bTF.a(aVar) && j <= 1000) { this.bTF = aVar; x.e("MicroMsg.Music.ExoMusicPlayer", "startPlay, is playing for music src:%s, don't play again in 3 second, interval:%d", new Object[]{this.lxf, Long.valueOf(j)}); } else if (aVar == null) { x.e("MicroMsg.Music.ExoMusicPlayer", "music is null"); } else { com.tencent.mm.plugin.music.model.f.a(aVar, false); this.lxh = currentTimeMillis; this.bTF = aVar; x.i("MicroMsg.Music.ExoMusicPlayer", "startPlay, currentTime:%d, startTime:%d", new Object[]{Long.valueOf(currentTimeMillis), Integer.valueOf(aVar.field_startTime)}); if (this.lyN != null && PY()) { this.lyN.stop(); } this.aBN = 0; this.dGs = aVar.field_startTime; this.aBL = SystemClock.elapsedRealtime(); this.lyK = aVar.PV(); m(this.lyK); x.i("MicroMsg.Music.ExoMusicPlayer", "startPlay startTime:%d", new Object[]{Integer.valueOf(this.dGs)}); ah.A(new 2(this)); } } public final void pause() { this.lyX = false; x.i("MicroMsg.Music.ExoMusicPlayer", "pause"); if (this.lyN != null) { this.lyM = 2; this.lyN.af(false); } } public final boolean bho() { return this.lxb && this.lyX; } public final void bhn() { this.lyX = true; x.i("MicroMsg.Music.ExoMusicPlayer", "passivePause"); if (this.lyN != null) { this.lyM = 2; this.lyN.af(false); } } public final void bhB() { x.i("MicroMsg.Music.ExoMusicPlayer", "pauseAndAbandonFocus"); pause(); h.big().bhO(); } public final void resume() { this.aBN = 0; boolean bhC = bhC(); boolean PY = PY(); x.i("MicroMsg.Music.ExoMusicPlayer", "resume, isPreparing:%b, isPlayingMusic:%b", new Object[]{Boolean.valueOf(bhC), Boolean.valueOf(PY)}); if (this.lyN != null) { if (h.big().requestFocus()) { this.lyM = 1; this.lyN.af(true); p(this.lyK); } else { x.e("MicroMsg.Music.ExoMusicPlayer", "request focus error"); } this.lxb = true; } } public final boolean PY() { if (this.lyN == null) { return false; } switch (this.lyN.iB()) { case 1: case 3: return this.lyN.iC(); default: return false; } } private boolean bhC() { if (this.lyN != null) { return this.lyN.iD(); } return false; } public final boolean PZ() { return this.lxb && !bhC(); } public final void stopPlay() { x.i("MicroMsg.Music.ExoMusicPlayer", "stopPlay"); try { if (this.lyN != null) { this.lyM = 3; this.lyN.af(false); this.lyN.stop(); r(this.lyK); } } catch (Throwable e) { x.printErrStackTrace("MicroMsg.Music.ExoMusicPlayer", e, "stopPlay", new Object[0]); a(this.bTF.PV(), 504); a(this.bTF, -4005, -42); } h.big().bhO(); this.lxb = false; this.lyX = false; this.fLN.removeMessages(100); } public final int getDuration() { if (this.lyN != null) { return (int) this.lyN.getDuration(); } return 0; } public final int getDownloadPercent() { if (this.lyN != null) { return this.lyN.getBufferedPercentage(); } return 0; } public final boolean if(int i) { boolean z = false; int duration = getDuration(); x.i("MicroMsg.Music.ExoMusicPlayer", "seekToMusic pos:%d, duration:%d", new Object[]{Integer.valueOf(i), Integer.valueOf(duration)}); if (duration < 0 || i > duration) { x.e("MicroMsg.Music.ExoMusicPlayer", "position is invalid, position:%d, duration:%d", new Object[]{Integer.valueOf(i), Integer.valueOf(duration)}); return false; } else if (this.lyN == null) { return true; } else { t(this.bTF.PV()); f fVar = this.lyS; if ((this.lyS.lyZ[3] & -268435456) != 0) { z = true; } fVar.p(z, 100); this.lyM = 4; this.lyN.seekTo((long) i); return true; } } public final d bhq() { int i = 0; int duration = getDuration(); int currentPosition = this.lyN != null ? (int) this.lyN.getCurrentPosition() : 0; boolean PY = PY(); int downloadPercent = getDownloadPercent(); if (downloadPercent < 0) { downloadPercent = 0; } if ((this.lyR instanceof com.google.android.exoplayer2.source.b.h) && !this.auM) { duration = 0; } if (this.lyL != null) { d dVar = this.lyL; if (PY) { i = 1; } dVar.j(duration, currentPosition, i, downloadPercent); } else { if (PY) { i = 1; } this.lyL = new d(duration, currentPosition, i, downloadPercent); } this.lyL.bTG = true; this.lyL.ebh = this.lzq; return this.lyL; } public final boolean bhp() { return true; } final void cX(int i, int i2) { x.i("MicroMsg.Music.ExoMusicPlayer", "notifyOnError what:%d, extra:%d", new Object[]{Integer.valueOf(i), Integer.valueOf(i2)}); if (this.lyW != null) { this.lyW.cZ(i, i2); } } final void cY(int i, int i2) { x.i("MicroMsg.Music.ExoMusicPlayer", "notifyOnInfo [" + i + "," + i2 + "]"); if (this.lyW == null) { return; } if (i == 701 || i == 702) { this.lyW.tF(i2); } } public final void a(Metadata metadata) { x.i("MicroMsg.Music.ExoMusicPlayer", "onMetadata ["); com.tencent.mm.plugin.music.b.b.a.a(metadata, " "); x.i("MicroMsg.Music.ExoMusicPlayer", "]"); } final String bij() { return com.tencent.mm.plugin.music.b.b.a.ee(SystemClock.elapsedRealtime() - this.aBL); } static void a(com.tencent.mm.an.a aVar, int i, int i2) { IDKey iDKey = new IDKey(); iDKey.SetID(797); iDKey.SetKey(2); iDKey.SetValue(1); IDKey iDKey2 = new IDKey(); iDKey2.SetID(797); int i3 = aVar.field_musicType; x.i("MicroMsg.Music.ExoPlayIdkeyReport", "getExoMusicPlayerErrIdKeyByMusicType, musicType:" + i3); switch (i3) { case 0: i3 = 62; break; case 1: i3 = 63; break; case 4: i3 = 64; break; case 6: i3 = 65; break; case 7: i3 = 66; break; case 8: i3 = 67; break; case 9: i3 = 68; break; case 10: i3 = 69; break; case 11: i3 = 70; break; default: i3 = 71; break; } iDKey2.SetKey(i3); iDKey2.SetValue(1); IDKey iDKey3 = new IDKey(); iDKey3.SetID(797); x.i("MicroMsg.Music.ExoPlayIdkeyReport", "getExoMusicPlayerErrTypeIdKey, errType:" + i); switch (i) { case -4999: i3 = 9; break; case -4005: i3 = 8; break; case -4004: i3 = 7; break; case -4003: i3 = 6; break; case -4002: i3 = 5; break; case -4001: i3 = 4; break; case -4000: i3 = 3; break; default: i3 = 9; break; } iDKey3.SetKey(i3); iDKey3.SetValue(1); IDKey iDKey4 = new IDKey(); iDKey4.SetID(797); x.i("MicroMsg.Music.ExoPlayIdkeyReport", "getExoMusicPlayerErrIdKey, errCode:" + i2); switch (i2) { case -43: i3 = 25; break; case -42: i3 = 24; break; case -41: i3 = 23; break; case -40: i3 = 22; break; case -30: i3 = 21; break; case -13: i3 = 20; break; case -12: i3 = 19; break; case -11: i3 = 18; break; case PayuSecureEncrypt$EncrptType.HASHED_PASSWORD /*-10*/: i3 = 17; break; case -3: i3 = 16; break; case -2: i3 = 15; break; case -1: i3 = 14; break; default: i3 = 14; break; } iDKey4.SetKey(i3); iDKey4.SetValue(1); ArrayList arrayList = new ArrayList(); arrayList.add(iDKey); arrayList.add(iDKey2); arrayList.add(iDKey3); arrayList.add(iDKey4); com.tencent.mm.plugin.report.service.h.mEJ.b(arrayList, true); } }
package marche.traitement.Acteurs; import marche.traitement.Acteurs.ChoixAcheteur.StrategyChoixAcheteur; import marche.traitement.Initialisation.Initialisation; import marche.traitement.Marche.LivreDuMarche; import marche.traitement.Marche.Offre; import marche.traitement.Produit.Produit; import java.util.ArrayList; import java.util.List; /** * */ public class VendeurAcheteur extends Acteur { protected List<Produit> stocks = new ArrayList<Produit>(); /** * Default constructor */ public VendeurAcheteur(double solde, String nom) { super(solde, nom); Initialisation.listeVendeurAcheteur.add(this); } protected VendeurAcheteur() {} /** * Creer une offre selon le prix et le Produit (vend tout le produit) * @param //int quantite * @param //int prix * @param //Produit produit * @return */ public void creerUneOffre(int prix, Produit produit, StrategyChoixAcheteur strategyChoixAcheteur, LivreDuMarche marche)throws ArithmeticException,IllegalArgumentException { try { if(prix<0) throw new ArithmeticException("prix négatif"); if(produit == null) throw new IllegalArgumentException("rentrez un produit valide"); if(stocks.contains(produit)){ Offre offre = new Offre(prix,produit,this,strategyChoixAcheteur, marche); if(marche.getControleur().validerOffre(offre)){ stocks.remove(produit); marche.ajouterOffre(offre); }else{ throw new IllegalArgumentException("votre offre a été rejeté par l'amf"); } } else { throw new IllegalArgumentException("rentrez un produit valide"); } } catch (Exception e) { System.out.println(e.getMessage()); } } /** * Creer une offre selon la quantité le prix et le Produit * @param //int quantite * @param //int prix * @param //Produit produit * @return */ public void creerUneOffre(int prix, Produit produit, StrategyChoixAcheteur strategyChoixAcheteur, LivreDuMarche marche,int quantite)throws ArithmeticException,IllegalArgumentException { try { if(prix<0) throw new ArithmeticException("prix négatif"); if(produit == null) throw new IllegalArgumentException("rentrez un produit valide"); if (stocks.contains(produit) && quantite < produit.getQuantite()) { Produit copy = produit.clone(); copy.setQuantite(quantite); Offre offre = new Offre(prix,copy,this,strategyChoixAcheteur,marche); if (marche.getControleur().validerOffre(offre)) { produit.setQuantite(produit.getQuantite()-quantite); marche.ajouterOffre(offre); } else throw new IllegalArgumentException("votre offre a été rejeté par l'amf"); } else { throw new IllegalArgumentException("rentrez un produit vali"); } } catch (Exception e) { System.out.println(e.getMessage()); } } /** * si le produit est du même type, date de péremption et unité qu'un produit dans le stock * on combine les produits, sinon on ajoute le produit au stock dans une autre case * @param produit */ public void ajouterAuStock(Produit produit){ boolean dejaDansLeStock = false; for (Produit stock: stocks ) { if( stock.getNom().equals(produit.getNom()) && stock.getDateDePeremption() == produit.getDateDePeremption()&& stock.getUnite().equals(produit.getUnite())){ stock.ajouterQuantite(produit.getQuantite()); dejaDansLeStock = true; } } if(!dejaDansLeStock ){ stocks.add(produit); } } /** * Retourne la quantitée totale des produits * @param * @return quantiteTotale */ public double getQuantiteStock() { double quantiteTotale = 0; for (Produit produit:stocks) { quantiteTotale += produit.getQuantite(); } return quantiteTotale; } /** * Affiche de manière détailler le stock d'un acheteur vendeur */ public String afficherStock() { int compteur = 1; StringBuilder contenuStock = new StringBuilder(); if (stocks.size() != 0) { for (Produit produit : stocks) { contenuStock.append(") "); contenuStock.append(produit.getQuantite()); contenuStock.append(" kilo de "); contenuStock.append(produit.getNom()); contenuStock.append(" / périme le : "); contenuStock.append(produit.getDateDePeremption()); compteur++; } } else contenuStock.append("vide"); return contenuStock.toString(); } /** * Retourne le produit qui se situe au ième rang du stock */ public Produit getElementStock(int i) { return stocks.get(i-1); } @Override public void transaction(Offre o){ super.transaction(o); ajouterAuStock(o.getProduit()); System.out.println(" Le produit a été ajouté à votre stock et vous pouvez le revendre"); } public List<Produit> getStocks() { return stocks; } public String toString(){ if (getQuantiteStock() == 0) return getNom() + "{" + "kg" + ", stocks=" + afficherStock() + "}\n"; return getNom() + "{" + "kg" + ", stocks=" + getQuantiteStock() + "kg" + afficherStock() + "}\n"; } }
import java.util.Scanner; public class Example { public static void main(String[] args) { //System.out.println("Hello World"); // a=a^b; // b=a^b; // a=a^b; // a=a+b; // b=a-b; // a=a-b; // System.out.println("a="+a+" b="+b+" after swap "); // int i=2; // int k=i++; // int z= ++i; // int u=10; // int j=--u; // System.out.println(k); // System.out.println(z); // System.out.println(j); Scanner s=new Scanner(System.in); System.out.println("Enter a:"); int a=s.nextInt(); System.out.println("Enter b:"); int b=s.nextInt(); System.out.println("Enter b:"); int c=s.nextInt(); // if (a == b) { // System.out.println("a not equal to b"); // } // else if (a<b) // System.out.println("b is greater"); // else if (a>b) // System.out.println("a is greater"); // else // System.out.println("not equal"); if ((a==b)||(a==c)) System.out.println("a equal to b, or a equal to c"); } }
package com.gustavoaz7.flappybird; import com.badlogic.gdx.ApplicationAdapter; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.OrthographicCamera; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.g2d.BitmapFont; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.math.Circle; import com.badlogic.gdx.math.Intersector; import com.badlogic.gdx.math.Rectangle; import com.badlogic.gdx.utils.viewport.StretchViewport; import com.badlogic.gdx.utils.viewport.Viewport; import java.util.Random; public class FlappyBird extends ApplicationAdapter { private SpriteBatch batch; private Texture[] birds; private Texture background; private Texture pipeBottom; private Texture pipeTop; private Texture gameOverText; private Random rand; private BitmapFont font; private BitmapFont restartMessage; private Circle birdCircle; private Rectangle pipeBottomRect; private Rectangle pipeTopRect; private int screenWidth; private int screenHeight; private int fallSpeed = 0; private int birdX; private int birdY; private int pipeX; private int passageHeight; private int passagePositionY; private int score = 0; private float index = 0; private boolean gameStarted = false; private boolean gameOver = false; private boolean scored = false; private OrthographicCamera camera; private Viewport viewport; private final int VIRTUAL_WIDTH = 768; private final int VIRTUAL_HEIGHT = 1024; @Override public void create () { batch = new SpriteBatch(); birds = new Texture[3]; birds[0] = new Texture("bird1.png"); birds[1] = new Texture("bird2.png"); birds[2] = new Texture("bird3.png"); background = new Texture("background.png"); pipeBottom = new Texture("pipe_bottom.png"); pipeTop = new Texture("pipe_top.png"); gameOverText = new Texture("game_over.png"); rand = new Random(); birdCircle = new Circle(); pipeBottomRect = new Rectangle(); pipeTopRect = new Rectangle(); font = new BitmapFont(); font.setColor(Color.WHITE); font.getData().setScale(6); restartMessage = new BitmapFont(); restartMessage.setColor(Color.WHITE); restartMessage.getData().setScale(4); camera = new OrthographicCamera(); camera.position.set(VIRTUAL_WIDTH / 2, VIRTUAL_HEIGHT / 2, 0); viewport = new StretchViewport(VIRTUAL_WIDTH, VIRTUAL_HEIGHT, camera); screenWidth = VIRTUAL_WIDTH; screenHeight = VIRTUAL_HEIGHT; birdX = (int) (screenWidth * 0.2); birdY = screenHeight / 2 - birds[0].getHeight() / 2; pipeX = screenWidth; passageHeight = 300; } @Override public void render () { camera.update(); // Clear previous frames Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT); float deltaTime = Gdx.graphics.getDeltaTime(); index += deltaTime * 9; if (index >= 3) { index = 0; } if (!gameStarted) { if (Gdx.input.justTouched()) { gameStarted = true; } } else { fallSpeed++; if (birdY > 0) { birdY -= fallSpeed; } if (!gameOver) { pipeX -= deltaTime * 600; if (Gdx.input.justTouched()) { fallSpeed = -15; } if (pipeX < -pipeBottom.getWidth()) { pipeX = screenWidth; passagePositionY = rand.nextInt(400) - 200; scored = false; } if (pipeX < birdX) { if (!scored) { score++; scored = true; } } } else { if (Gdx.input.justTouched()) { gameOver = false; gameStarted = false; score = 0; fallSpeed = 0; birdY = screenHeight / 2 - birds[0].getHeight() / 2; pipeX = screenWidth; } } } int pipeBottomY = - passageHeight / 2 + passagePositionY; int pipeTopY = screenHeight / 2 + passageHeight / 2 + passagePositionY; int centerWidth = screenWidth / 2; int centerHeight = screenHeight / 2; batch.setProjectionMatrix(camera.combined); batch.begin(); batch.draw(background, 0, 0, screenWidth, screenHeight); batch.draw(pipeTop, pipeX, pipeTopY); batch.draw(pipeBottom, pipeX, pipeBottomY ); batch.draw(birds[(int) index], birdX, birdY); font.draw(batch, String.valueOf(score), centerWidth, (int) (screenHeight - screenHeight * 0.1)); if (gameOver) { batch.draw(gameOverText, (float) (centerWidth - gameOverText.getWidth() / 2), centerHeight); restartMessage.draw(batch, "Touch to restart the game", centerWidth - 320, centerHeight - 30); } batch.end(); birdCircle.set(birdX + (float) birds[0].getWidth() / 2, (float) (birdY + birds[0].getHeight() / 2), (float) birds[0].getWidth() / 2); pipeBottomRect.set(pipeX, pipeBottomY, pipeBottom.getWidth(), pipeBottom.getHeight()); pipeTopRect.set(pipeX, pipeTopY, pipeTop.getWidth(), pipeTop.getHeight()); if (Intersector.overlaps(birdCircle, pipeBottomRect) || Intersector.overlaps(birdCircle, pipeTopRect) || birdY <= 0 || birdY >= screenHeight) { gameOver = true; } } @Override public void resize(int width, int height) { viewport.update(width, height); } }
package com.facebook.react.uimanager.events; import com.facebook.react.bridge.Arguments; import com.facebook.react.bridge.WritableMap; import com.facebook.react.uimanager.PixelUtil; public class ContentSizeChangeEvent extends Event<ContentSizeChangeEvent> { private final int mHeight; private final int mWidth; public ContentSizeChangeEvent(int paramInt1, int paramInt2, int paramInt3) { super(paramInt1); this.mWidth = paramInt2; this.mHeight = paramInt3; } public void dispatch(RCTEventEmitter paramRCTEventEmitter) { WritableMap writableMap = Arguments.createMap(); writableMap.putDouble("width", PixelUtil.toDIPFromPixel(this.mWidth)); writableMap.putDouble("height", PixelUtil.toDIPFromPixel(this.mHeight)); paramRCTEventEmitter.receiveEvent(getViewTag(), "topContentSizeChange", writableMap); } public String getEventName() { return "topContentSizeChange"; } } /* Location: C:\Users\august\Desktop\tik\df_rn_kit\classes.jar.jar!\com\facebook\reac\\uimanager\events\ContentSizeChangeEvent.class * Java compiler version: 6 (50.0) * JD-Core Version: 1.1.3 */
package com.dkwig0.yeybook.jpa.repositories; import com.dkwig0.yeybook.jpa.entities.ChatRoom; import com.dkwig0.yeybook.jpa.entities.User; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import java.util.List; import java.util.Set; @Repository public interface ChatRoomRepository extends JpaRepository<ChatRoom, Long> { Set<ChatRoom> findByUsersIn(List<User> users); Set<ChatRoom> findByUsersContains(User user); ChatRoom findByUsersContainsAndUsersContains(User user1, User user2); }
package com.ai.slp.order.api.notice.interfaces; import javax.ws.rs.Consumes; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import com.ai.opt.base.exception.BusinessException; import com.ai.opt.base.exception.SystemException; import com.ai.opt.base.vo.BaseResponse; @Path("/paynotice") @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON, MediaType.TEXT_XML }) public interface IPayNoticeSV { /** * 支付通知 * @param request * @return * @throws BusinessException * @throws SystemException * @author zhanglh * @ApiCode NOTICE_001 * @RestRelativeURL paynotice/notice */ @POST @Path("/notice") public BaseResponse getPayNotice(String xmlbody,String signMsg,String header) throws BusinessException,SystemException; }
package kyle.game.besiege.panels; import com.badlogic.gdx.scenes.scene2d.Actor; import com.badlogic.gdx.scenes.scene2d.InputEvent; import com.badlogic.gdx.scenes.scene2d.InputListener; import kyle.game.besiege.Assets; import kyle.game.besiege.party.Soldier; import kyle.game.besiege.party.Squad; /** * A soldier table specifically for SquadManagementScreen, allowing player to manage squads. */ public class SquadSoldierTable extends SoldierTable { SquadManagementScreen squadManagementScreen; private boolean entered; private Squad squad; public SquadSoldierTable(SquadManagementScreen squadManagementScreen, SquadPanel panel, Squad squad) { super(panel, null, false, null, null, null, squad); this.squad = squad; this.squadManagementScreen = squadManagementScreen; this.setLockSoldierExpand(true); this.squadSoldierTable = true; this.addListener(); this.update(); } @Override public void select(Soldier soldier) { super.select(soldier); squadManagementScreen.notifySelect(soldier, this); } @Override public void deselect() { super.deselect(); squadManagementScreen.notifyDeselect(); } // Add listener for entering/exiting the soldierTable private void addListener() { this.addListener(new InputListener() { @Override public void enter(InputEvent event, float x, float y, int pointer, Actor fromActor) { SquadSoldierTable.this.enter(); } @Override public void exit(InputEvent event, float x, float y, int pointer, Actor fromActor) { SquadSoldierTable.this.exit(); } }); } // Notify this panel that a soldier is being released. // If this panel is currently being dragged over, add the soldier to this party and release it from the other party. // returns true if released public boolean notifySoldierReleased(Soldier soldier) { if (entered) { if (!this.squad.isFull()) { if (soldier.squad != null) soldier.squad.removeSoldier(soldier); this.squad.addSoldier(soldier); exit(); this.update(); // TODO update squads on the battle map if they've already been placed. return true; } } return false; } private void enter() { if (squadManagementScreen.getSoldierBeingDragged() != null && squadManagementScreen.getSoldierBeingDragged().squad != squad) { this.entered = true; soldierTable.setBackground(Assets.ninepatchBackgroundLightGray); } } private void exit() { this.entered = false; soldierTable.setBackground(Assets.ninepatchBackgroundDarkGray); } public boolean entered() { return entered; } }
public class WildCardSquare extends Square{ public WildCardSquare(String name, int position) { super(name, position); } @Override public boolean isOwned() { return false; } public void execute(Player player) { System.out.println(StdIO.printSquareLandedOn(player, this.getName())); WildCard wildCardDrawn = BackFromTheBrink.board.draw(); System.out.println(StdIO.printDrawnWildCard(wildCardDrawn, player)); wildCardDrawn.execute(player); } }
package test.mart; public class Cpu { }
package bean.item.name; public class ItemNameDTO { private int num; private String name; private String url; private String maintag; private String subtag; private String imgurl; public int getNum() { return num; } public void setNum(int num) { this.num = num; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getMaintag() { return maintag; } public void setMaintag(String maintag) { this.maintag = maintag; } public String getSubtag() { return subtag; } public void setSubtag(String subtag) { this.subtag = subtag; } public String getImgurl() { return imgurl; } public void setImgurl(String imgurl) { this.imgurl = imgurl; } }
package lesson35.controller; import lesson35.model.Hotel; import lesson35.repository.UserDAO; import lesson35.service.HotelService; import java.nio.file.AccessDeniedException; public class HotelController { private HotelService hotelService = new HotelService(); /* only for administrators */ public void addHotel(Hotel hotel) throws Exception { if (!UserDAO.isAdmin()) throw new AccessDeniedException("User do not have permission"); hotelService.addHotel(hotel); } /* only for administrators */ public void deleteHotel(long hotelId) throws Exception { if (!UserDAO.isAdmin()) throw new AccessDeniedException("User do not have permission"); hotelService.deleteHotel(hotelId); } /* for users */ public Hotel findHotelByName(String name) throws Exception { return hotelService.findHotelByName(name); } /* for users */ public Hotel findHotelByCity(String city) throws Exception { return hotelService.findHotelByCity(city); } }
/** * Copyright 2013 Cloudera Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kitesdk.data.hbase.avro; import org.kitesdk.data.DatasetException; import org.kitesdk.data.SchemaValidationException; import org.kitesdk.data.hbase.impl.EntityComposer; import org.kitesdk.data.hbase.impl.EntitySchema.FieldMapping; import org.kitesdk.data.hbase.impl.MappingType; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import org.apache.avro.Schema; import org.apache.avro.Schema.Field; import org.apache.avro.generic.IndexedRecord; /** * An EntityComposer implementation for Avro records. It will handle both * SpecificRecord entities and GenericRecord entities. * * @param <E> * The type of the entity */ public class AvroEntityComposer<E extends IndexedRecord> implements EntityComposer<E> { /** * The Avro schema for the Avro records this EntityComposer will compose. */ private final AvroEntitySchema avroSchema; /** * Boolean to indicate whether this is a specific record or generic record * composer. TODO: Eventually use an enum type when we support more than two * types of Avro records. */ private final boolean specific; /** * An AvroRecordBuilderFactory that can produce AvroRecordBuilders for this * composer to compose Avro entities. */ private final AvroRecordBuilderFactory<E> recordBuilderFactory; /** * A mapping of entity field names to AvroRecordBuilderFactories for any * keyAsColumn mapped fields that are Avro record types. These are needed to * get builders that can construct the keyAsColumn field values from their * parts. */ private final Map<String, AvroRecordBuilderFactory<E>> kacRecordBuilderFactories; /** * The number of key parts in the entity schema. */ private final int keyPartCount; /** * AvroEntityComposer constructor. * * @param avroEntitySchema * The schema for the Avro entities this composer composes. * @param specific * True if this composer composes Specific records. Otherwise, it * composes Generic records. */ public AvroEntityComposer(AvroEntitySchema avroEntitySchema, boolean specific) { this.avroSchema = avroEntitySchema; this.specific = specific; this.recordBuilderFactory = buildAvroRecordBuilderFactory(avroEntitySchema .getAvroSchema()); this.kacRecordBuilderFactories = new HashMap<String, AvroRecordBuilderFactory<E>>(); int keyPartCount = 0; for (FieldMapping fieldMapping : avroEntitySchema.getFieldMappings()) { if (fieldMapping.getMappingType() == MappingType.KEY) { keyPartCount++; } } this.keyPartCount = keyPartCount; initRecordBuilderFactories(); } @Override public Builder<E> getBuilder() { return new Builder<E>() { private final AvroRecordBuilder<E> recordBuilder = recordBuilderFactory .getBuilder(); @Override public org.kitesdk.data.hbase.impl.EntityComposer.Builder<E> put( String fieldName, Object value) { recordBuilder.put(fieldName, value); return this; } @Override public E build() { return recordBuilder.build(); } }; } @Override public Object extractField(E entity, String fieldName) { Schema schema = avroSchema.getAvroSchema(); Field field = schema.getField(fieldName); if (field == null) { throw new SchemaValidationException("No field named " + fieldName + " in schema " + schema); } Object fieldValue = entity.get(field.pos()); if (fieldValue == null) { // if the field value is null, and the field is a primitive type, // we should make the field represent java's default type. This // can happen when using GenericRecord. SpecificRecord has it's // fields represented by members of a class, so a SpecificRecord's // primitive fields will never be null. We are doing this so // GenericRecord acts like SpecificRecord in this case. fieldValue = getDefaultPrimitive(field); } return fieldValue; } @SuppressWarnings("unchecked") @Override public Map<CharSequence, Object> extractKeyAsColumnValues(String fieldName, Object fieldValue) { Schema schema = avroSchema.getAvroSchema(); Field field = schema.getField(fieldName); if (field == null) { throw new SchemaValidationException("No field named " + fieldName + " in schema " + schema); } if (field.schema().getType() == Schema.Type.MAP) { return new HashMap<CharSequence, Object>( (Map<CharSequence, Object>) fieldValue); } else if (field.schema().getType() == Schema.Type.RECORD) { Map<CharSequence, Object> keyAsColumnValues = new HashMap<CharSequence, Object>(); IndexedRecord avroRecord = (IndexedRecord) fieldValue; for (Field avroRecordField : avroRecord.getSchema().getFields()) { keyAsColumnValues.put(avroRecordField.name(), avroRecord.get(avroRecordField.pos())); } return keyAsColumnValues; } else { throw new SchemaValidationException( "Only MAP or RECORD type valid for keyAsColumn fields. Found " + field.schema().getType()); } } @Override public Object buildKeyAsColumnField(String fieldName, Map<CharSequence, Object> keyAsColumnValues) { Schema schema = avroSchema.getAvroSchema(); Field field = schema.getField(fieldName); if (field == null) { throw new SchemaValidationException("No field named " + fieldName + " in schema " + schema); } Schema.Type fieldType = field.schema().getType(); if (fieldType == Schema.Type.MAP) { Map<CharSequence, Object> retMap = new HashMap<CharSequence, Object>(); for (Entry<CharSequence, Object> entry : keyAsColumnValues.entrySet()) { retMap.put(entry.getKey(), entry.getValue()); } return retMap; } else if (fieldType == Schema.Type.RECORD) { AvroRecordBuilder<E> builder = kacRecordBuilderFactories.get(fieldName) .getBuilder(); for (Entry<CharSequence, Object> keyAsColumnEntry : keyAsColumnValues .entrySet()) { builder.put(keyAsColumnEntry.getKey().toString(), keyAsColumnEntry.getValue()); } return builder.build(); } else { throw new SchemaValidationException( "Only MAP or RECORD type valid for keyAsColumn fields. Found " + fieldType); } } /** * Initialize the AvroRecordBuilderFactories for all keyAsColumn mapped fields * that are record types. We need to be able to get record builders for these * since the records are broken across many columns, and need to be * constructed by the composer. */ private void initRecordBuilderFactories() { for (FieldMapping fieldMapping : avroSchema.getFieldMappings()) { if (fieldMapping.getMappingType() == MappingType.KEY_AS_COLUMN) { String fieldName = fieldMapping.getFieldName(); Schema fieldSchema = avroSchema.getAvroSchema().getField(fieldName) .schema(); Schema.Type fieldSchemaType = fieldSchema.getType(); if (fieldSchemaType == Schema.Type.RECORD) { AvroRecordBuilderFactory<E> factory = buildAvroRecordBuilderFactory(fieldSchema); kacRecordBuilderFactories.put(fieldName, factory); } } } } /** * Build the appropriate AvroRecordBuilderFactory for this instance. Avro has * many different record types, of which we support two: Specific and Generic. * * @param schema * The Avro schema needed to construct the AvroRecordBuilderFactory. * @return The constructed AvroRecordBuilderFactory. */ @SuppressWarnings({ "unchecked", "rawtypes" }) private AvroRecordBuilderFactory<E> buildAvroRecordBuilderFactory( Schema schema) { if (specific) { Class<E> specificClass; String className = schema.getFullName(); try { specificClass = (Class<E>) Class.forName(className); } catch (ClassNotFoundException e) { throw new DatasetException("Could not get Class instance for " + className); } return new SpecificAvroRecordBuilderFactory(specificClass); } else { return (AvroRecordBuilderFactory<E>) new GenericAvroRecordBuilderFactory( schema); } } /** * Get's the default value for the primitive types. This matches the default * Java would assign to the following primitive types: * * int, long, boolean, float, and double. * * If field is any other type, this method will return null. * * @param field * The Schema field * @return The default value for the schema field's type, or null if the type * of field is not a primitive type. */ private Object getDefaultPrimitive(Schema.Field field) { Schema.Type type = field.schema().getType(); if (type == Schema.Type.INT) { return 0; } else if (type == Schema.Type.LONG) { return 0L; } else if (type == Schema.Type.BOOLEAN) { return false; } else if (type == Schema.Type.FLOAT) { return 0.0f; } else if (type == Schema.Type.DOUBLE) { return 0.0d; } else { // not a primitive type, so return null return null; } } @Override public List<Object> getPartitionKeyParts(E entity) { Object[] parts = new Object[keyPartCount]; for (FieldMapping fieldMapping : avroSchema.getFieldMappings()) { if (fieldMapping.getMappingType() == MappingType.KEY) { int pos = avroSchema.getAvroSchema() .getField(fieldMapping.getFieldName()).pos(); parts[Integer.parseInt(fieldMapping.getMappingValue())] = entity.get(pos); } } return Arrays.asList(parts); } }
package model; import java.io.Serializable; import model.obstacle.Obstacle; import model.obstacle.ObstacleType; import model.obstacle.Unit; import model.terrain.Terrain; import model.terrain.TerrainType; /** * A grid of Cells<br> * * <hr> * Date created: Jun 6, 2010<br> * Date last modified: Jun 6, 2010<br> * <hr> * @author Glen Watson */ public class Map implements Serializable { private static final long serialVersionUID = 1L; private Cell[][] cells; private int[][] playerPieces; /** * Creates a new map <br> * * <hr> * Date created: Jun 6, 2010 <br> * Date last modified: Jun 6, 2010 <br> * * <hr> * @param terArray - the terrains on the map * @param obsArray - the obstacles on the map * @param pieces - who owns what piece */ public Map(TerrainType[][] terArray, ObstacleType[][] obsArray, int[][] pieces) { cells = new Cell[terArray.length][terArray[0].length]; playerPieces = new int[terArray.length][terArray[0].length]; for(int x=0; x<terArray.length; x++) { for(int y=0; y<terArray[0].length; y++) { cells[x][y] = new Cell(terArray[x][y], obsArray[x][y]); // playerPieces[x][y] = pieces[x][y]; } } playerPieces = pieces; } // public ObstacleType[][] getObstacles() // { // return // } /** * Moves a cell's obstacle <br> * * <hr> * Date created: Jun 6, 2010 <br> * Date last modified: Jun 6, 2010 <br> * * <hr> * @param fromX - the x-coord to move from * @param fromY - the y-coord to move from * @param toX - the x-coord to move to * @param toY - the y-coord to move to */ public void moveCell(int fromX, int fromY, int toX, int toY) { playerPieces[toX][toY] = playerPieces[fromX][fromY]; playerPieces[fromX][fromY] = -1; cells[toX][toY].setObstacle(cells[fromX][fromY].getObstacle()); cells[fromX][fromY].setObstacle(null); } /** * gets the cell at the corrds <br> * * <hr> * Date created: Jun 6, 2010 <br> * Date last modified: Jun 6, 2010 <br> * * <hr> * @param row - the row of the cell * @param col -the column of the cell * @return - the cell at the specified coord */ public Cell getCellAt(int row, int col) { return cells[row][col]; } /** * gets the terrain at that cell <br> * * <hr> * Date created: Jun 6, 2010 <br> * Date last modified: Jun 6, 2010 <br> * * <hr> * @param row - y-coord * @param col - x-coord * @return - the Terrain at that cell */ public Terrain getTerrainAt(int row, int col) { return cells[row][col].getTerrain(); } /** * gets the obstacles at that cell <br> * * <hr> * Date created: Jun 6, 2010 <br> * Date last modified: Jun 6, 2010 <br> * * <hr> * @param row - the y-coord * @param col - x-coord * @return - the obstacle at that cell, null if there isn't one */ public Obstacle getObstacleAt(int row, int col) { return cells[row][col].getObstacle(); } /** * gets the width of the map <br> * * <hr> * Date created: Jun 6, 2010 <br> * Date last modified: Jun 6, 2010 <br> * * <hr> * @return - the width of the map */ public int getWidth() { return cells.length; } /** * gets the height of the map <br> * * <hr> * Date created: Jun 6, 2010 <br> * Date last modified: Jun 6, 2010 <br> * * <hr> * @return - the height of the map */ public int getHeight() { return cells[0].length; } /** * gets who owns what pieces <br> * * <hr> * Date created: Jun 6, 2010 <br> * Date last modified: Jun 6, 2010 <br> * * <hr> * @return - a 2-Dimensional int array of who owns what piece */ public int[][] getPlayerPieces() { return playerPieces; } /** * Sets the next active cells to true <br> * * <hr> * Date created: Jun 6, 2010 <br> * Date last modified: Jun 6, 2010 <br> * * <hr> * @param turn - who's turn is next */ public void endTurn(int turn) { for(int x=0; x<cells.length; x++) { for(int y=0; y<cells[0].length; y++) { if(turn == playerPieces[x][y] && cells[x][y].getObstacle() instanceof Unit) { ((Unit) cells[x][y].getObstacle()).setActive(true); } } } } /** * deletes a player's units <br> * * <hr> * Date created: Jun 6, 2010 <br> * Date last modified: Jun 6, 2010 <br> * * <hr> * @param eliminatedPlayer - the eliminated player's number */ public void playerEliminated(int eliminatedPlayer) { for(int x=0; x<getWidth(); x++) { for(int y=0; y<getHeight(); y++) { if(playerPieces[x][y] == eliminatedPlayer) { playerPieces[x][y] = -1; cells[x][y].setObstacle(null); } } } } /** * overridden toString <br> * * <hr> * Date created: Jun 6, 2010 <br> * Date last modified: Jun 6, 2010 <br> * * <hr> * @return - 3 maps of the obstacles, terrain, and players * @see java.lang.Object#toString() */ public String toString() { StringBuilder columnHeader = new StringBuilder(); for(int i=0; i<cells.length; i++) { columnHeader.append(" "); columnHeader.append(i); } columnHeader.append("\n"); StringBuilder sb = new StringBuilder(); sb.append("-------------------MAP-------------------\n"); sb.append(" Terrain\n"); sb.append(columnHeader.toString()); for( int i=0; i<cells.length; i++) { sb.append(i+" "); for( int j=0; j<cells[i].length; j++) { sb.append("["); sb.append(cells[i][j].getTerrain()); sb.append("] "); } sb.append("\n"); } sb.append(columnHeader.toString()); sb.append(" Players\n"); sb.append(" 0 1 2 3 4 5 6 7 8 9\n"); for( int i=0; i<playerPieces.length; i++) { sb.append(i+" "); for( int j=0; j<playerPieces[i].length; j++) { sb.append("["); if(playerPieces[i][j] == -1) sb.append(" "); else sb.append(playerPieces[i][j]); sb.append("] "); } sb.append("\n"); } sb.append(columnHeader.toString()); sb.append(" Obstacles\n"); sb.append(" 0 1 2 3 4 5 6 7 8 9\n"); for( int i=0; i<cells.length; i++) { sb.append(i+" "); for( int j=0; j<cells[i].length; j++) { sb.append("["); if(cells[i][j].getObstacle() == null) sb.append(" "); else sb.append(cells[i][j].getObstacle()); sb.append("] "); } sb.append("\n"); } return sb.toString(); } }
package com.tencent.mm.plugin.bottle.ui; import android.os.Message; import com.tencent.mm.R; import com.tencent.mm.sdk.platformtools.ag; class ThrowBottleAnimUI$4 extends ag { final /* synthetic */ ThrowBottleAnimUI hnb; ThrowBottleAnimUI$4(ThrowBottleAnimUI throwBottleAnimUI) { this.hnb = throwBottleAnimUI; } public final void handleMessage(Message message) { super.handleMessage(message); if (ThrowBottleAnimUI.i(this.hnb) == null && ThrowBottleAnimUI.a(this.hnb) != null) { ThrowBottleAnimUI.a(this.hnb, (SprayLayout) ThrowBottleAnimUI.a(this.hnb).findViewById(R.h.bottle_spray_fl)); } if (ThrowBottleAnimUI.i(this.hnb) != null) { ThrowBottleAnimUI.i(this.hnb).stop(); } if (ThrowBottleAnimUI.m(this.hnb) != null) { ThrowBottleAnimUI.m(this.hnb).auA(); } } }
import java.util.Scanner; class input { public static void main(String[] args){ Scanner scrobj = new Scanner(System.in); System.out.println("enter your first name :"); String firstname = scrobj.next(); System.out.println("enter your last name :"); String lastname = scrobj.next(); System.out.println("your full name is "+firstname+""+ lastname); } }
package com.solidbeans.courses.java8.future; import com.solidbeans.courses.java8.client.FuturesClient; import org.junit.Before; import org.junit.Test; import java.time.Duration; import java.time.Instant; import java.util.concurrent.CompletableFuture; import java.util.concurrent.Executor; import java.util.concurrent.Executors; import java.util.concurrent.ForkJoinPool; import static com.solidbeans.courses.java8.Utils.log; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; public class FuturesClientTest { private FuturesClient client; @Before public void setUp() { Executor executor = Executors.newFixedThreadPool(10); client = new FuturesClient(executor); } @Test public void it_should_call_the_client_and_wait_for_the_first_one_to_finish() { Instant start = Instant.now(); CompletableFuture<Integer> a = client.replyAfter(3); CompletableFuture<Integer> b = client.replyAfter(5); CompletableFuture<Integer> c = client.replyAfter(2); // Add some stuff to make the test pass CompletableFuture.anyOf(a, b, c).join(); Duration elapsed = Duration.between(start, Instant.now()); log("elapsed = " + elapsed); assertThat(elapsed.getSeconds(), is(2L)); } @Test public void it_should_call_the_client_and_wait_for_the_last_one_to_finish() { Instant start = Instant.now(); CompletableFuture<Integer> a = client.replyAfter(3); CompletableFuture<Integer> b = client.replyAfter(5); CompletableFuture<Integer> c = client.replyAfter(2); // Add some stuff to make the test pass CompletableFuture.allOf(a, b, c).join(); Duration elapsed = Duration.between(start, Instant.now()); log("elapsed = " + elapsed); assertThat(elapsed.getSeconds(), is(5L)); } @Test public void it_should_do_stuff() throws Exception { int ten = client.replyAfter(3) .thenApply(i -> i + 5) .thenApply(i -> i + 2) .join(); assertThat(ten, is(10)); } @Test public void it_should_do_some_more_stuff() throws Exception { int ten = client.replyAfter(3) .thenCompose(i -> client.replyAfter(i + 5)) .thenCompose(i -> client.replyAfter(i + 2)) .join(); assertThat(ten, is(10)); } @Test public void it_should_do_even_more_stuff() throws Exception { CompletableFuture<Integer> three = client.replyAfter(3); CompletableFuture<Integer> five = client.replyAfter(5); int plus = three.thenCombine(five, (t, f) -> t + f).join(); assertThat(plus, is(8)); } }
package com.tencent.mm.plugin.fts.b; import com.tencent.mm.ab.e; import com.tencent.mm.kernel.g; import com.tencent.mm.plugin.fts.a.a.a; import com.tencent.mm.plugin.fts.a.a.i; import com.tencent.mm.plugin.fts.a.b; import com.tencent.mm.plugin.fts.a.m; import com.tencent.mm.plugin.fts.a.n; import com.tencent.mm.sdk.b.c; import com.tencent.mm.sdk.platformtools.x; import java.util.List; public final class f extends b { private e dKj = new 2(this); m dhW; c juU = new 1(this); String[] juV; List<String> juW; public final String getName() { return "SearchTestLogic"; } protected final boolean onCreate() { if (((n) g.n(n.class)).isFTSContextReady()) { x.i("MicroMsg.FTS.FTSSearchTestLogic", "Create Success!"); this.dhW = ((n) g.n(n.class)).getFTSTaskDaemon(); this.juU.cht(); return true; } x.i("MicroMsg.FTS.FTSSearchTestLogic", "Create Fail!"); return false; } public final a a(i iVar) { a fVar; switch (iVar.jsn) { case 65521: fVar = new f(this, iVar.jss); break; case 65523: fVar = new e(this, iVar); break; case 65524: fVar = new d(this, (byte) 0); break; default: fVar = new a(this, (byte) 0); break; } return this.dhW.a(-65536, fVar); } protected final boolean BT() { g.DF().b(30, this.dKj); return false; } }
package piefarmer.immunology.block; import cpw.mods.fml.common.registry.GameRegistry; import cpw.mods.fml.common.registry.LanguageRegistry; import piefarmer.immunology.lib.Ids; import piefarmer.immunology.lib.Names; import net.minecraft.block.Block; import net.minecraft.block.material.Material; public class Blocks { public static BlockCustomFlower plantBlueBell; public static Block blockMedResearchTable; public static Block blockDiagTable; public static Block blockRock; public static Block torchWoodLit; public static Block torchWoodNotLit; public static void init() { plantBlueBell = (BlockCustomFlower) new BlockCustomFlower(Ids.blockcustomflowerID_actual).setHardness(0.0F).setStepSound(Block.soundGrassFootstep) .setUnlocalizedName(Names.bluebellBlock_unlocalizedName); blockMedResearchTable = (new BlockMedicalResearchTable(Ids.blockmedrestblID_actual)).setHardness(0.1F).setStepSound(Block.soundMetalFootstep) .setUnlocalizedName(Names.medresBlock_unlocalizedName); blockDiagTable = (new BlockDiagnosticTable(Ids.blockdiatblID_actual)).setHardness(0.1F).setStepSound(Block.soundMetalFootstep) .setUnlocalizedName(Names.diagBlock_unlocalizedName); blockRock = (new BlockRock(Ids.blockrockID_actual, Material.rock)).setHardness(1.5F).setStepSound(Block.soundStoneFootstep) .setUnlocalizedName(Names.rockBlock_unlocalizedName); torchWoodNotLit = (new BlockCustomTorch(Ids.blocktorchID_actual, false)).setHardness(0.0F).setLightValue(0).setStepSound(Block.soundWoodFootstep) .setUnlocalizedName(Names.unlittorchBlock_unlocalizedName); torchWoodLit = (new BlockCustomTorch(50, true)).setHardness(0.0F).setLightValue(0.9375F).setStepSound(Block.soundWoodFootstep) .setUnlocalizedName("torch"); } public static void addNames() { LanguageRegistry.addName(plantBlueBell, Names.bluebellBlock_name); LanguageRegistry.addName(blockMedResearchTable, Names.medreBlock_name); LanguageRegistry.addName(blockDiagTable, Names.diagBlock_name); LanguageRegistry.addName(blockRock, Names.rockBlock_name); LanguageRegistry.addName(torchWoodNotLit, Names.unlittorchBlock_name); } public static void registerBlocks() { GameRegistry.registerBlock(plantBlueBell, "immunologybluebell"); GameRegistry.registerBlock(blockMedResearchTable, "medicalresearchtable"); GameRegistry.registerBlock(blockDiagTable, "diagnostictable"); GameRegistry.registerBlock(torchWoodLit, "Lit Torch"); GameRegistry.registerBlock(torchWoodNotLit, "Unlit Torch"); GameRegistry.registerBlock(blockRock, "Rock"); } }
import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.Test; public class Model { private int frameHeight; private int frameWidth; private int imgHeight; private int imgWidth; private int xloc, yloc; private int xVector, yVector; private int direction; private int health; //updateLocationAndDirection() will contain the logic that allows the bird to move in the x or y direction based on user input public void updateLocationAndDirection() { } //detectCollisions() will contain the logic that determines if the bird model has collided with objects such as the ground and other obstacles public boolean detectCollisions() { return false; } public int getFrameHeight() { return frameHeight; } public void setFrameHeight(int frameHeight) { this.frameHeight = frameHeight; } public int getFrameWidth() { return frameWidth; } public void setFrameWidth(int frameWidth) { this.frameWidth = frameWidth; } public int getImgHeight() { return imgHeight; } public void setImgHeight(int imgHeight) { this.imgHeight = imgHeight; } public int getImgWidth() { return imgWidth; } public void setImgWidth(int imgWidth) { this.imgWidth = imgWidth; } public int getXloc() { return xloc; } public void setXloc(int xloc) { this.xloc = xloc; } public int getYloc() { return yloc; } public void setYloc(int yloc) { this.yloc = yloc; } public int getxVector() { return xVector; } public void setxVector(int xVector) { this.xVector = xVector; } public int getyVector() { return yVector; } public void setyVector(int yVector) { this.yVector = yVector; } public int getDirection() { return direction; } public void setDirection(int direction) { this.direction = direction; } public int getHealth() { return health; } public void setHealth(int health) { this.health = health; } } //----------------------------------------------------------------------------------------------------- //JUnit Tests class ModelTest { @Test public void testUpdateLocationAndDirection() { Model test = new Model(); test.setXloc(0); test.setxVector(1); test.updateLocationAndDirection(); assertNotEquals(0, test.getXloc()); assertNotEquals(1, test.getxVector()); } @Test public void testDetectCollisions() { Model test = new Model(); assertEquals(false, test.detectCollisions()); assertFalse(test.detectCollisions()); } }
package com.xiaoxiao; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import org.springframework.cloud.openfeign.EnableFeignClients; /** * @project_name:bz_parent * @date:2019/9/20:21:55 * @author:shinelon * @Describe: 单点登录服务 */ @SpringBootApplication @EnableDiscoveryClient @EnableFeignClients public class SSOApp { public static void main(String[] args) { SpringApplication.run(SSOApp.class, args); } }
package com.CoreJava; import static org.junit.Assert.*; import org.junit.Test; import junit.framework.TestCase; public class CalculatorTest extends TestCase { public CalculatorTest(String name) { super(name); } public void testAddCalculator() { Calculator m1=new Calculator(); assertEquals(120,m1.factorial(5)); } }
/** * <pre> * * Author: * Brandon Mota * * * Description: * This class is the child class to Geom. * It provides the necessary methods for * a rectangle object. * * * * </pre> */ public class Rectangle extends Geom { private double base, height; /** * <pre> * Description: * This is the constructor for the class. * Pre: * none. * Post: * Rectangle is created. * </pre> * */ public Rectangle() { super("Rectangle"); base = 0; height = 0; } /** * <pre> * Description: * This provides a new instance of Rectangle. * Pre: * none. * Post: * A new Rectangle is created. * </pre> * */ public Rectangle(double base, double height) { super("Rectangle"); this.base = base; this.height = height; } /** * <pre> * Description: * This returns the base caller. * Pre: * none. * Post: * Base is returned. * </pre> * */ public double getbase() { return base; } /** * <pre> * Description: * This returns the height back to the caller. * Pre: * none. * Post: * Height is returned. * </pre> * */ public double getheight() { return height; } /** * <pre> * Description: * This calculated the area of the shape and returns it. * Pre: * none. * Post: * Area is returned. * </pre> * */ public double computeArea() { return base * height; } /** * <pre> * Description: * This prints the shape data. * Pre: * none. * Post: * Shape data is printed. * </pre> * */ public void print() { System.out.println("rec " + base + " " + height + " " + computeArea()); } }
package entidades.abstractas; import java.util.Random; import javax.swing.Icon; import GUI.Gui; import entidades.concretas.PremioBomba; import entidades.concretas.PremioOro; import entidades.concretas.PremioProteccion; import entidades.concretas.PremioRestaurar; import entidades.concretas.PremioVelocidad; import juego.Juego; import visitor.Visitor; import visitor.VisitorEnemigo; public abstract class Enemigo extends Personaje { protected int velocidad; protected int puntaje; protected Icon spriteMovimiento; protected Icon spriteAtaque; protected Enemigo(int x, int y, int vida, int vel, int cooldown, int puntaje) { super(x, y, vida, cooldown); velocidad = vel; this.puntaje = puntaje; setVisitor(); } protected void setVisitor() { miVisitor = new VisitorEnemigo(this); } public void accept(Visitor v) { v.visit(this); } public void morir() { super.morir(); Juego.getJuego().sumarPuntos(puntaje); Random r = new Random(); int value = r.nextInt(100); if (value<15) { Juego.getJuego().agregarEntidad(dropPremio(r)); } } public abstract void atacar(Atacable entidad); public void mover() { if (!sprite.getIcon().equals(spriteMovimiento)) { sprite.setIcon(spriteMovimiento); } int velActual = estado.getVelocidad(velocidad); if ((x-velActual)/Gui.spriteSize<x/Gui.spriteSize) { //Cambio de celda en el mapa if (Juego.getJuego().getEntidad((x-velActual)/Gui.spriteSize, y/Gui.spriteSize)==null) {//No hay entidad en la siguiente celda Juego.getJuego().setEntidad(x/Gui.spriteSize, y/Gui.spriteSize, null); Juego.getJuego().setEntidad((x-velActual)/Gui.spriteSize, y/Gui.spriteSize, this); x-= velActual; sprite.setBounds(x, y, Gui.spriteSize, Gui.spriteSize); } } else { //Movimiento normal x-= velActual; sprite.setBounds(x, y, Gui.spriteSize, Gui.spriteSize); } } public int getCoste() { return puntaje; } protected Objeto dropPremio(Random r) { int value = r.nextInt(100); Objeto premio = null; if (value<20) { premio = new PremioBomba(x/Gui.spriteSize, y/Gui.spriteSize); } else if (value<40) { premio = new PremioOro(x/Gui.spriteSize, y/Gui.spriteSize); } else if (value<60) { premio = new PremioProteccion(x/Gui.spriteSize, y/Gui.spriteSize); } else if (value<80) { premio = new PremioRestaurar(x/Gui.spriteSize, y/Gui.spriteSize); } else { premio = new PremioVelocidad(x/Gui.spriteSize, y/Gui.spriteSize); } return premio; } }
package com.training.day11.loops; public class TwelvePrime { public static void main(String[] args) { int num = 9; // if (args != null && args.length > 0) { // num = Integer.parseInt(args[0]); // } boolean isPrime = true; int temp; for (int i = 2; i <= num/2 ; i++) { temp = num%i; if (temp == 0) { isPrime = false; break; } } if (isPrime) { System.out.println(num + " is a prime number"); } else { System.out.println(num + " is not a prime number"); } } }
package br.com.home.servlets; import br.com.home.dao.ContatoDao; import br.com.home.domain.Contato; import br.com.home.domain.builder.ContatoBuilder; import br.com.home.infra.ConnectionDatabaseFactory; import br.com.home.util.ApplicationUtil; import javax.servlet.AsyncContext; import javax.servlet.AsyncEvent; import javax.servlet.AsyncListener; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.FileReader; import java.io.IOException; import java.util.Calendar; import java.util.Properties; @WebServlet(asyncSupported = true, urlPatterns = {"/adicioneContato"}) public class AdicionaContatoServlet extends HttpServlet { private ContatoDao dao; @Override public void init() throws ServletException { try { FileReader file = new FileReader(getServletContext() .getResource("./WEB-INF/properties/app.properties") .getPath()); Properties prop = new Properties(); prop.load(file); System.out.println("Imprimindo propriedades lidas durante init:"); System.out.println(prop.getProperty("login")); System.out.println(prop.getProperty("senha")); } catch (IOException e) { throw new ServletException(e); } } @Override protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { AsyncContext asyncContext = req.startAsync(req, resp); try { System.out.println("AGUARDANDO 5 SEGUNDOS EM THREAD SEPARADA"); Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } asyncContext.addListener(new AsyncListener() { @Override public void onComplete(AsyncEvent asyncEvent) throws IOException { System.out.println("DISPACHANDO PARA HELLO SERVLETHELLO"); try { asyncEvent.getAsyncContext().getRequest().getRequestDispatcher("/WEB-INF/jsp/hello.jsp") .forward(req, resp); } catch (ServletException e) { e.printStackTrace(); } } @Override public void onTimeout(AsyncEvent asyncEvent) throws IOException { } @Override public void onError(AsyncEvent asyncEvent) throws IOException { } @Override public void onStartAsync(AsyncEvent asyncEvent) throws IOException { } }); Integer id = ApplicationUtil.toInteger(req.getParameter("id")); String nome = req.getParameter("nome"); String email = req.getParameter("email"); String endereco = req.getParameter("endereco"); String dataEmTexto = req.getParameter("dataNascimento"); Calendar dataNascimento = ApplicationUtil.toCalendar(dataEmTexto); Contato contato = ContatoBuilder.getInstance() .comId(id) .comNome(nome) .comEmail(email) .comEndereco(endereco) .comDataNascimento(dataNascimento) .build(); if (dao == null) { dao = new ContatoDao(ConnectionDatabaseFactory.getPostgreSQLConnection()); } dao.adicione(contato); asyncContext.complete(); getServletContext().getRequestDispatcher("/contato-adicionado.jsp") .forward(req, resp); } @Override public void destroy() { dao.close(); super.destroy(); } }
package com.yc.biz.impl; import java.util.HashMap; import java.util.List; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Isolation; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import com.yc.bean.Attribute; import com.yc.bean.Attrvalue; import com.yc.biz.AttrvalueBiz; import com.yc.dao.BaseDao; @Service public class AttrvalueBizImpl implements AttrvalueBiz { @Autowired private BaseDao BaseDao; @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, readOnly = true) @Override public List<Attrvalue> getAttrvalueByPid(Integer attribute_id) { Map<String, Object> map = new HashMap<String, Object>(); map.put("attribute_id", attribute_id); return BaseDao.findAll(Attrvalue.class, "getAttrvalueByPid", map); } }
package com.mobcrush.internship; /** * * @author Ushang-PC */ public class Purchase { private long customerId; private long productId; /** * * @return the id of the customer who made the purchase */ public long getCustomerId() { return customerId; } /** * * @param customerId the id of the customer who made the purchase */ public void setCustomerId(long customerId) { this.customerId = customerId; } /** * * @return the id of the product whose purchase was made */ public long getProductId() { return productId; } /** * * @param productId the id of the product which was purchased */ public void setProductId(long productId) { this.productId = productId; } }
package com.ibeiliao.statement.impl.enums; /** * * 提现对账类型 * Created by jingyesi on 16/8/15. */ public enum WithdrawStatType { APPLY((short)1, "申请"), REJECT((short)2, "拒绝"), FINISH((short)3, "完成"); private WithdrawStatType(short type, String name){ this.type = type; this.name = name; } /** * 类型 */ private short type; /** * 类型名称 */ private String name; public short getType() { return type; } public String getName() { return name; } public static WithdrawStatType from(short type){ for(WithdrawStatType tmp :WithdrawStatType.values()){ if(tmp.getType() == type){ return tmp; } } return null; } }
package Assigment2; import java.util.ArrayList; //class Employee { // // int salary = 10000; // int totalSal; // // public int getSalary(int salary) { // return this.salary; // } // // public int totalEmployeesSalary(ArrayList<Integer> employeeSalaries) { // // for (int i : employeeSalaries) { // totalSal += i; // } // return totalSal; // } //} // //class Manager extends Employee { // @Override // public int getSalary(int salary) { // int incentive = 5000; // int total = incentive + salary; // return total; // } //} // //class Labour extends Employee { // @Override // public int getSalary(int salary) { // int overtime = 500; // int total = overtime + salary; // return total; // } //} //public class Assignment2Q2 { // // public static void main(String[] args) { // } //} class Manager extends Assignment2Q2 { @Override public int getSalary(int salary) { int incentive = 5000; int total = incentive + salary; return total; } } class Labour extends Assignment2Q2 { @Override public int getSalary(int salary) { int overtime = 500; int total = overtime + salary; return total; } } public class Assignment2Q2 { int salary = 10000; int totalSal; public int getSalary(int salary) { return this.salary; } public int totalEmployeesSalary(ArrayList<Integer> employeeSalaries) { for (Integer i : employeeSalaries) { totalSal += i; } return totalSal; } public static void main(String[] args) { } }
package ru.otus.l151.db; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import ru.otus.l151.app.MessageSystemContext; import ru.otus.l151.dataset.UserDataSet; import ru.otus.l151.messageSystem.Address; import ru.otus.l151.messageSystem.MessageSystem; public class DBServiceImplTest { private DBServiceImpl dbService; public static final String USER_NAME = "user"; @Before public void setUp() throws Exception { MessageSystem messageSystem = new MessageSystem(); MessageSystemContext context = new MessageSystemContext(messageSystem); Address dbAddress = new Address("DB"); context.setDbAddress(dbAddress); dbService = new DBServiceImpl(context, dbAddress); dbService.init(); } @After public void tearDown() throws Exception { dbService = null; } @Test public void getUserId() { UserDataSet expectedUserDataSet = new UserDataSet( 1, USER_NAME, "password", null ); dbService.save(expectedUserDataSet); UserDataSet testUserDataSet = dbService.load(1, UserDataSet.class); Assert.assertEquals(expectedUserDataSet, testUserDataSet); } }
package ua.kiev.doctorvera; import java.util.ArrayList; import java.util.Arrays; import java.util.concurrent.ExecutionException; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.os.Bundle; import android.preference.PreferenceManager; import android.support.v4.app.NavUtils; import android.support.v7.app.ActionBarActivity; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.Spinner; import android.widget.Toast; /* * Form to set settings * @author Volodymyr Bodnar * @version %I%, %G% * @since 1.0 */ public class SettingsActivity extends ActionBarActivity implements OnClickListener { // Declare Variables private EditText loginField, passwordField, alphaNameField; private Button saveSettingsButton, cancelButton; private Spinner languageSpinner; private final String PARAM_NAME_LOGIN="LOGIN"; private final String PARAM_NAME_PASSWORD="PASSWORD"; private final String PARAM_NAME_ALPHA_NAME="ALPHA_NAME"; private final String PARAM_NAME_LANGUAGE="LANGUAGE"; private final String PARAM_NAME_MY_LICENSE="MY LICENSE"; private final String DEFAULT_LOGIN="android"; private final String DEFAULT_PASSWORD="849Wyn4hdjpcklnqwg"; private final String DEFAULT_ALPHA_NAME="Doctor Vera"; private final String DEFAULT_LANGUAGE="English"; private String LAST_LOGIN; private String LAST_PASSWORD; private String LAST_ALPHA_NAME; private String LAST_LANGUAGE; private SharedPreferences sPref; private final String LOG_TAG = "myLogs Settings"; private LicensingService licenseService; /* * (non-Javadoc) * * @see android.support.v7.app.ActionBarActivity#onCreate(android.os.Bundle) */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.settings_layout); licenseService = new LicensingService(this); // Get View-elements loginField = (EditText) findViewById(R.id.login_field); passwordField = (EditText) findViewById(R.id.password_field); alphaNameField = (EditText) findViewById(R.id.alpha_name_field); languageSpinner = (Spinner)findViewById(R.id.language_spinner); saveSettingsButton = (Button) findViewById(R.id.save_settings_button); cancelButton = (Button) findViewById(R.id.cancel_button); // Create an ArrayAdapter using the string array and a default spinner layout ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.languages, android.R.layout.simple_spinner_item); // Specify the layout to use when the list of choices appears adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // Apply the adapter to the spinner languageSpinner.setAdapter(adapter); //languageSpinner.setOnItemSelectedListener(this); //Setting button listeners saveSettingsButton.setOnClickListener(this); cancelButton.setOnClickListener(this); //Displaying back button getActionBar().setDisplayHomeAsUpEnabled(true); loadPreferences(); fillFields(); } // onCreate @Override public void onClick(View v) { switch (v.getId()) { case R.id.cancel_button: loadPreferences(); NavUtils.navigateUpFromSameTask(this); break; case R.id.save_settings_button: String login = loginField.getText().toString(); String password = passwordField.getText().toString(); String alphaName = alphaNameField.getText().toString(); String language = languageSpinner.getSelectedItem().toString(); if(checkFieldsNotNull()){ checkAuth(login, password, alphaName, language); checkMyLicense(login); //Check Google License licenseService.checkGoogleLicense(); } break; } } //Checks if the fields are filled private Boolean checkFieldsNotNull(){ //Checking fields data if (loginField.getText().toString().trim().equalsIgnoreCase("")) { loginField.setError(getString(R.string.field_empty_error)); Log.d(LOG_TAG,"Settings changing failed: loginField is empty"); return false; } else if (passwordField.getText().toString().trim().equalsIgnoreCase("")) { passwordField.setError(getString(R.string.field_empty_error)); Log.d(LOG_TAG,"Settings changing failed: passwordField is empty"); return false; } else if (alphaNameField.getText().toString().trim().equalsIgnoreCase("")) { alphaNameField.setError(getString(R.string.field_empty_error)); Log.d(LOG_TAG,"Settings changing failed: alphaNameField is empty"); return false; } else { loginField.setError(null); passwordField.setError(null); alphaNameField.setError(null); return true; } } private void checkAuth(final String login, final String password, final String alphaName, final String language){ Boolean isNetworkConnected = false; Boolean isInternetAvailable = false; try { isNetworkConnected = (Boolean)new SMSGatewayConnect(SettingsActivity.this).execute("isNetworkConnected").get(); isInternetAvailable = (Boolean)new SMSGatewayConnect(SettingsActivity.this).execute("isInternetAvailable").get(); } catch (InterruptedException e) { Log.e(LOG_TAG, e.getMessage()); } catch (ExecutionException e) { Log.e(LOG_TAG, e.getMessage()); } //Checking Internet connection if(isNetworkConnected && isInternetAvailable){ Boolean checkGatewayAuth = false; try { checkGatewayAuth = (Boolean)new SMSGatewayConnect(SettingsActivity.this).execute("checkGatewayAuth",login, password,alphaName).get(); } catch (InterruptedException e) { Log.e(LOG_TAG, e.getMessage()); } catch (ExecutionException e) { Log.e(LOG_TAG, e.getMessage()); } //Trying to connect to Gateway if(checkGatewayAuth){ //Auth is successful Saving Params saveSettings(login,password,alphaName,language); }else{ //If Connection check failed set errors loginField.setError(getString(R.string.login_password_error)); passwordField.setError(getString(R.string.login_password_error)); alphaNameField.setError(getString(R.string.login_password_error)); Log.d(LOG_TAG,"Authentification failed"); } }else Toast.makeText(getApplicationContext(), R.string.internet_connection_error, Toast.LENGTH_LONG).show(); } private void saveSettings(final String login, final String password, final String alphaName, final String language){ Editor ed = sPref.edit(); ed.putString(PARAM_NAME_LOGIN, login); ed.putString(PARAM_NAME_PASSWORD, password); ed.putString(PARAM_NAME_ALPHA_NAME, alphaName); ed.putString(PARAM_NAME_LANGUAGE, language); ed.commit(); Log.d(LOG_TAG,"Settings changed: "); Log.d(LOG_TAG," Login=" + login); Log.d(LOG_TAG," Password=" + password); Log.d(LOG_TAG," Alpha Name=" + alphaName); Log.d(LOG_TAG," Language=" + language); Toast.makeText(getApplicationContext(), R.string.settings_saved_notice, Toast.LENGTH_LONG).show(); } private void checkMyLicense(final String login){ setProgressBarIndeterminateVisibility(true); Boolean isNetworkConnected = false; Boolean isInternetAvailable = false; try { isNetworkConnected = (Boolean)new SMSGatewayConnect(this).execute("isNetworkConnected").get(); isInternetAvailable = (Boolean)new SMSGatewayConnect(this).execute("isInternetAvailable").get(); } catch (InterruptedException e) { Log.e(LOG_TAG, e.getMessage()); } catch (ExecutionException e) { Log.e(LOG_TAG, e.getMessage()); } //Checking Internet connection if(isNetworkConnected && isInternetAvailable) { Boolean isLicenseActive = false; try { isLicenseActive = (Boolean)new SMSGatewayConnect(this).execute("isLicenseActive",login).get(); } catch (InterruptedException e) { Log.e(LOG_TAG, e.getMessage()); } catch (ExecutionException e) { Log.e(LOG_TAG, e.getMessage()); } //Getting My License if (isLicenseActive){ Editor ed = sPref.edit(); ed.putString(PARAM_NAME_MY_LICENSE, "" + true); ed.commit(); Log.d(LOG_TAG,"My License is Active"); Toast.makeText(getApplicationContext(), R.string.drvera_valid, Toast.LENGTH_LONG).show(); } else { Editor ed = sPref.edit(); ed.putString(PARAM_NAME_MY_LICENSE, "" + false); ed.commit(); Log.d(LOG_TAG,"My License is NOT Active"); Toast.makeText(getApplicationContext(), R.string.license_error, Toast.LENGTH_LONG).show(); } } else Toast.makeText(getApplicationContext(), R.string.internet_connection_error, Toast.LENGTH_LONG).show(); setProgressBarIndeterminateVisibility(false); } private void loadPreferences(){ //Initializing preferences sPref = PreferenceManager.getDefaultSharedPreferences(this); LAST_LOGIN = sPref.getString(PARAM_NAME_LOGIN, DEFAULT_LOGIN); LAST_PASSWORD = sPref.getString(PARAM_NAME_PASSWORD, DEFAULT_PASSWORD); LAST_ALPHA_NAME = sPref.getString(PARAM_NAME_ALPHA_NAME, DEFAULT_ALPHA_NAME); LAST_LANGUAGE = sPref.getString(PARAM_NAME_LANGUAGE, DEFAULT_LANGUAGE); } private void fillFields(){ if(LAST_LOGIN!=null && LAST_PASSWORD!=null && LAST_ALPHA_NAME!=null && LAST_LANGUAGE!=null){ loginField.setText(LAST_LOGIN); passwordField.setText(LAST_PASSWORD); alphaNameField.setText(LAST_ALPHA_NAME); ArrayList<String> languages = new ArrayList<String>(); languages.addAll(Arrays.asList(getResources().getStringArray(R.array.languages))); for(int i=0; i<languages.size();i++) if (languages.get(i).equals(LAST_LANGUAGE)) languageSpinner.setSelection(i); } } @Override protected void onDestroy() { super.onDestroy(); licenseService.onDestroy(); } }
package com.tencent.mm.ui.chatting.b; import android.content.DialogInterface; import android.content.DialogInterface.OnClickListener; class ac$4 implements OnClickListener { final /* synthetic */ ac tRo; ac$4(ac acVar) { this.tRo = acVar; } public final void onClick(DialogInterface dialogInterface, int i) { if (ac.a(this.tRo) != null) { ac.a(this.tRo).dismiss(); } } }