text
stringlengths
10
2.72M
package mod.items.concretes; import mod.items.ModItemInfo; import mod.items.abstracts.ThisModItem; import net.minecraft.block.Block; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.potion.Potion; import net.minecraft.potion.PotionEffect; import net.minecraft.util.DamageSource; import net.minecraft.util.Icon; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; public class ItemBlade extends ThisModItem { public ItemBlade(int par1, String iconName, String unlocalizedName) { super(par1, iconName, unlocalizedName); setMaxStackSize(1); setNoRepair(); setFull3D(); } @Override public boolean hitEntity(ItemStack stack, EntityLivingBase target, EntityLivingBase attacker) { if(!attacker.worldObj.isRemote && target != null && attacker != null) { int y = (int)attacker.posY; while(y > 0 && attacker.worldObj.isAirBlock((int)attacker.posX, y--, (int)attacker.posZ)) { //loop down until you hit ground } attacker.setHealth(2); attacker.attackEntityFrom(DamageSource.fallingBlock, 10); if(attacker.getHealth() > 0) { target.setHealth(Math.max(1, target.getHealth() - 40)); target.attackEntityFrom(DamageSource.fallingBlock, 10); attacker.addPotionEffect(new PotionEffect(Potion.blindness.id, 50, 10)); attacker.addPotionEffect(new PotionEffect(Potion.moveSlowdown.id, 20, 10)); } } attacker.motionY = -50; return true; } @Override public boolean shouldRotateAroundWhenRendering() { return true; } @Override public ItemStack getContainerItemStack(ItemStack source) { return source; } @Override public String getUnlocalizedName(ItemStack s) { return "item." + this.unlocalizedName; } @SideOnly(Side.CLIENT) @Override public Icon getIconFromDamage(int dmg) { return icons[0]; } @Override public String getOreDictionaryName(int damageValue) { return ModItemInfo.BLADE_OREDICT; } @Override public int[] getDamagesForOreDict() { return new int[]{Short.MAX_VALUE}; } @Override public boolean doesSubItemWantToBeSeen(int damage) { return true; } @Override public int getSubItemCount() { return 1; } }
package com.polsl.edziennik.desktopclient.view.teacher.panels; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.BorderFactory; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JTextField; import com.jgoodies.forms.layout.CellConstraints; import com.jgoodies.forms.layout.FormLayout; import com.polsl.edziennik.desktopclient.controller.utils.factory.interfaces.IButton; import com.polsl.edziennik.desktopclient.controller.utils.factory.interfaces.ILabel; import com.polsl.edziennik.desktopclient.model.tables.ExamTaskTableModel; import com.polsl.edziennik.desktopclient.view.common.dialogs.ExamGradesDialog; import com.polsl.edziennik.desktopclient.view.common.panels.preview.PreviewPanel; import com.polsl.edziennik.modelDTO.exam.ExamDTO; import com.polsl.edziennik.modelDTO.exam.ExamTaskDTO; public class TeacherExamTaskPreviewPanel extends PreviewPanel { protected JLabel name; protected JLabel type; protected JLabel teacher; protected JTextField nameText; protected JTextField typeText; protected JTextField teacherText; protected ILabel label; protected IButton button; protected JButton grades; protected ExamTaskDTO currentExamTask; protected ExamDTO currentExam; protected ExamTaskTableModel model; public TeacherExamTaskPreviewPanel(String title, ExamTaskTableModel model) { this.model = model; setBorder(BorderFactory.createCompoundBorder(BorderFactory.createTitledBorder(title), BorderFactory.createEmptyBorder(0, 6, 6, 6))); FormLayout layout = new FormLayout( "pref,4dlu, 100dlu,10dlu", "pref, 2dlu, pref, 2dlu, pref,2dlu, pref, 2dlu, pref,2dlu, pref, 2dlu, pref,4dlu, pref, 8dlu, pref, 1dlu, pref,1dlu, pref, 10dlu, pref"); setLayout(layout); create(); setComponents(); setEnabled(false); setEditable(false); } public void create() { label = factory.createLabel(); button = factory.createTextButton(); name = label.getLabel("standardName"); type = label.getLabel("type"); teacher = label.getLabel("teacher"); nameText = new JTextField(TEXT_SIZE); typeText = new JTextField(TEXT_SIZE); teacherText = new JTextField(TEXT_SIZE); grades = button.getButton("gradesButton", "examTaskGradesHint"); grades.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { ExamTaskDTO et = model.get(selected); if (et != null) new ExamGradesDialog(et.getId(), et.getName()); } }); } @Override public void setComponents() { cc = new CellConstraints(); add(name, cc.xy(1, 1)); add(nameText, cc.xy(3, 1)); add(type, cc.xy(1, 3)); add(typeText, cc.xy(3, 3)); add(teacher, cc.xy(1, 5)); add(teacherText, cc.xy(3, 5)); add(grades, cc.xy(3, 7)); } @Override public void clear() { nameText.setText(""); typeText.setText(""); teacherText.setText(""); } @Override public void setEnabled(boolean b) { nameText.setEnabled(b); typeText.setEnabled(b); teacherText.setEnabled(b); grades.setEnabled(b); } @Override public void save() { // TODO Auto-generated method stub } @Override public void delete() { // TODO Auto-generated method stub } public void setEditable(boolean b) { nameText.setEditable(b); typeText.setEditable(b); teacherText.setEditable(b); } public void setData(ExamTaskDTO e, ExamDTO exam) { // nowy exam task if (e == null) { clear(); } else { if (e.getTeacher() != null) teacherText.setText(e.getTeacher().toString()); typeText.setText(e.getType()); nameText.setText(e.getName()); currentExam = exam; } currentExamTask = e; } }
package com.tencent.mm.protocal; public class c$hb extends c$g { public c$hb() { super("searchDataHasResult", "", 10000, false); } }
import javax.swing.*; /** * Created by Tomas on 4/14/16. */ public class UIBoard extends JPanel{ private Game game; public UIBoard(Game game) { this.game = game; } }
package com.phellipe.distanceCities.exception; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.Response; public class CityException extends WebApplicationException { private static final long serialVersionUID = 1L; public CityException() { super(Response.status(404).entity("City not Found").build()); } }
package com.mes.old.meta; // Generated 2017-5-22 1:25:24 by Hibernate Tools 5.2.1.Final import java.util.Date; /** * TChangeId generated by hbm2java */ public class TChangeId implements java.io.Serializable { private String partNumber; private String deptid; private long changetype; private String creator; private Date createtime; private long isupdate; private String uniqueid; public TChangeId() { } public TChangeId(String partNumber, String deptid, long changetype, long isupdate, String uniqueid) { this.partNumber = partNumber; this.deptid = deptid; this.changetype = changetype; this.isupdate = isupdate; this.uniqueid = uniqueid; } public TChangeId(String partNumber, String deptid, long changetype, String creator, Date createtime, long isupdate, String uniqueid) { this.partNumber = partNumber; this.deptid = deptid; this.changetype = changetype; this.creator = creator; this.createtime = createtime; this.isupdate = isupdate; this.uniqueid = uniqueid; } public String getPartNumber() { return this.partNumber; } public void setPartNumber(String partNumber) { this.partNumber = partNumber; } public String getDeptid() { return this.deptid; } public void setDeptid(String deptid) { this.deptid = deptid; } public long getChangetype() { return this.changetype; } public void setChangetype(long changetype) { this.changetype = changetype; } public String getCreator() { return this.creator; } public void setCreator(String creator) { this.creator = creator; } public Date getCreatetime() { return this.createtime; } public void setCreatetime(Date createtime) { this.createtime = createtime; } public long getIsupdate() { return this.isupdate; } public void setIsupdate(long isupdate) { this.isupdate = isupdate; } public String getUniqueid() { return this.uniqueid; } public void setUniqueid(String uniqueid) { this.uniqueid = uniqueid; } public boolean equals(Object other) { if ((this == other)) return true; if ((other == null)) return false; if (!(other instanceof TChangeId)) return false; TChangeId castOther = (TChangeId) other; return ((this.getPartNumber() == castOther.getPartNumber()) || (this.getPartNumber() != null && castOther.getPartNumber() != null && this.getPartNumber().equals(castOther.getPartNumber()))) && ((this.getDeptid() == castOther.getDeptid()) || (this.getDeptid() != null && castOther.getDeptid() != null && this.getDeptid().equals(castOther.getDeptid()))) && (this.getChangetype() == castOther.getChangetype()) && ((this.getCreator() == castOther.getCreator()) || (this.getCreator() != null && castOther.getCreator() != null && this.getCreator().equals(castOther.getCreator()))) && ((this.getCreatetime() == castOther.getCreatetime()) || (this.getCreatetime() != null && castOther.getCreatetime() != null && this.getCreatetime().equals(castOther.getCreatetime()))) && (this.getIsupdate() == castOther.getIsupdate()) && ((this.getUniqueid() == castOther.getUniqueid()) || (this.getUniqueid() != null && castOther.getUniqueid() != null && this.getUniqueid().equals(castOther.getUniqueid()))); } public int hashCode() { int result = 17; result = 37 * result + (getPartNumber() == null ? 0 : this.getPartNumber().hashCode()); result = 37 * result + (getDeptid() == null ? 0 : this.getDeptid().hashCode()); result = 37 * result + (int) this.getChangetype(); result = 37 * result + (getCreator() == null ? 0 : this.getCreator().hashCode()); result = 37 * result + (getCreatetime() == null ? 0 : this.getCreatetime().hashCode()); result = 37 * result + (int) this.getIsupdate(); result = 37 * result + (getUniqueid() == null ? 0 : this.getUniqueid().hashCode()); return result; } }
public class Consts { public static final String URL = "http://api.currencylayer.com"; public static final String TOKEN = "?access_key=cf23bd5c6958d36260ab64c976aaba39"; public static final String LIVE_ENDPOINT = "/live"; public static final String HISTORICAL_ENDPOINT = "/historical"; }
package com.tyss.cg.collections; public class CustomList { String[] list; int pointer = 0; public CustomList() { list = new String[10]; } public CustomList(int size) { list = new String[size]; } public void add(String element) { if(element != null) { if (pointer >= list.length - 2) { list[pointer] = element; pointer++; } else { String[] newList = new String[list.length + 6]; System.arraycopy(list, 0, newList, 0, list.length); list = newList; list[pointer] = element; pointer++; } } else { throw new NullPointerException(); } } public String get(int index) { return list[index]; } public int size() { int size = 0; for (int i = 0; i < list.length; i++) { if (list[i] == null) { return size; } else { size++; } } return size; } public boolean contains(String element) { boolean flag = false; for (int i = 0; i < pointer; i++) { if (list[i] != null && list[i].equalsIgnoreCase(element)) { flag = true; return flag; } } return flag; } public int getIndex(String element) { for (int i = 0; i < pointer; i++) { if(list[i].equalsIgnoreCase(element)) { return i; } } return -1; } }
package com.example.sean_duan.family_frag.fragment; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.design.widget.TabLayout; import android.support.v4.app.Fragment; import android.support.v4.view.ViewPager; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.example.sean_duan.family_frag.Adapter.UserMsgAdapter; import com.example.sean_duan.family_frag.activity.MainActivity; import com.example.sean_duan.family_frag.R; import java.util.List; /** * Created by sean-duan on 2017/7/20. */ public class History_msg_Fragment extends Fragment { private View view ; private TabLayout tabMsg ; private ViewPager mViewPager ; private List<Fragment> fragments ; private MainActivity mainActivity ; private String[] title ; private List<String> titles ; @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { view = inflater.inflate(R.layout.fragment_user_msg,container,false); //初始化数据 initData(); //初始化视图 initView(); //初始化适配器 initAdapter(); //绑定 bind(); return view; } private void bind() { tabMsg.setupWithViewPager(mViewPager); } private void initAdapter() { UserMsgAdapter adapter = new UserMsgAdapter(mainActivity.getSupportFragmentManager(),fragments,titles); } private void initData() { title = new String[]{"漂流瓶","帖子"}; for (int i = 0; i < title.length; i++) { titles.add(title[i]); } } private void initView() { tabMsg = (TabLayout) view.findViewById(R.id.tab_msg); mainActivity =(MainActivity) getActivity(); //添加Tab到TabLayout布局中 addTab(); } private void addTab() { for (int i = 0; i < title.length; i++) { Log.e("dffff","lalallalala"); tabMsg.addTab(tabMsg.newTab().setText(title[i])); } } }
/* * 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 test.com; import com.mycompany.myautotraderng.Calc; import static com.sun.org.apache.xalan.internal.lib.ExsltDatetime.year; import static com.sun.org.apache.xalan.internal.lib.ExsltDatetime.year; import static com.sun.org.apache.xalan.internal.lib.ExsltDatetime.year; import java.io.File; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.firefox.FirefoxOptions; import org.openqa.selenium.firefox.FirefoxProfile; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.Select; import org.openqa.selenium.support.ui.WebDriverWait; import static org.testng.Assert.*; import org.testng.annotations.AfterClass; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import org.openqa.selenium.support.ui.Select; /** * * @author shashi */ public class AutoTest { Calc calc; private WebDriver driver; private String baseUrl; public AutoTest() { } // TODO add test methods here. // The methods must be annotated with annotation @Test. For example: // @Test public void testadd() { assertEquals(calc.add(2,2), 4); } @Test public void testmul() { assertEquals(calc.mul(2,3), 6); } @BeforeClass public static void setUpClass() throws Exception { } @AfterClass public static void tearDownClass() throws Exception { } @BeforeMethod public void setUpMethod() throws Exception { calc = new Calc(); System.setProperty("webdriver.gecko.driver", "C:\\Users\\shashi\\Downloads\\geckodriver-v0.19.1-win64\\geckodriver.exe"); baseUrl ="https://www.autotrader.com//"; } @AfterMethod public void tearDownMethod() throws Exception { } @Test public void fillForm() { FirefoxProfile profile = new FirefoxProfile(new File("C:\\Users\\shashi\\AppData\\Roaming\\Mozilla\\Firefox\\Profiles\\z4lakrot.tester")); FirefoxOptions opt = new FirefoxOptions(); opt.setProfile(profile); driver = new FirefoxDriver(opt); driver.get(baseUrl); Select auto = new Select(driver.findElement(By.id("makeCodeListPlaceHolder"))); auto.selectByIndex(7); auto.selectByIndex(7); driver.findElement(By.id("modelCodeListPlaceHolder")).click(); driver.findElement(By.name("modelCodeListPlaceHolder")).sendKeys("5"); driver.findElement(By.name("zip")).clear(); driver.findElement(By.name("zip")).sendKeys("60107"); driver.findElement(By.id("Search")).click(); Select radius = new Select(driver.findElement(By.name("searchRadius"))); radius.selectByIndex(5); Select minyear = new Select(driver.findElement(By.name("startYear"))); minyear.selectByIndex(29); Select maxyear = new Select(driver.findElement(By.name("endYear"))); maxyear.selectByIndex(7); Select minprice = new Select(driver.findElement(By.name("minPrice"))); minprice.selectByIndex(25); Select maxprice = new Select(driver.findElement(By.name("maxPrice"))); maxprice.selectByIndex(7); Select mileage = new Select(driver.findElement(By.name("maxMileage"))); mileage.selectByIndex(3); Select sortby = new Select(driver.findElement(By.name("sortBy"))); sortby.selectByIndex(3); Select perpage = new Select(driver.findElement(By.name("numRecords"))); perpage.selectByIndex(0); WebDriverWait wait = new WebDriverWait(driver, 5); WebElement element = wait.until(ExpectedConditions.elementToBeClickable(By.xpath("html/body/div[1]/div/div[1]/header/div/div/nav/div/div[1]/div/div[1]/a/img[1]"))); driver.findElement(By.xpath("html/body/div[1]/div/div[1]/header/div/div/nav/div/div[1]/div/div[1]/a/img[1]")).click(); driver.quit(); { //year.selectByIndex(4); // driver.findElement(By.name("searchRadius")).sendKeys("5"); // driver.findElement(By.name("startYear")).sendKeys("22"); // driver.findElement(By.name("endYear")).sendKeys("28"); // driver.findElement(By.name("maxMileage")).click(); // driver.findElement(By.name("maxMileage")).sendKeys("Under 75,000"); // driver.findElement(By.name("sortBy")).sendKeys("5"); // // int i = 1; // while(i<40){ // //Select minprice = new Select(driver.findElement(By.name("minPrice"))); //minprice.selectByIndex(i); //Select maxprice = new Select(driver.findElement(By.name("maxPrice"))); //maxprice.selectByIndex(1); // //String min = driver.findElement(By.name("minPrice")).getAttribute("value"); //String max = driver.findElement(By.name("maxPrice")).getAttribute("value"); // //if(min.equals(max)) { //System.out.println("The Min and Max value of " + min + " match"); //} else { //System.out.println("Values don't match min= " + min + " max= " + max ); //} // //maxprice.selectByIndex(0); // Need to set this back to default so min price is sequenntial //i++; // WebDriverWait wait = new WebDriverWait(driver, 10); //wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("/html/body/div[1]/div/div[1]/header/div/div/nav/div/div[1]/div/div[1]/a/img[1]"))); //driver.findElement(By.className("display-none")).click(); // } } } // // driver.findElement(By.id("startYear2015")).click(); //driver.findElement(By.className("atcui-checkbox-input")).click(); //driver.findElement(By.id("j_id_1y1")).click(); //driver.findElement(By.className("input-label")).click(); //driver.findElement(By.className("atcui-selectOneMenu-styled")).sendKeys("2012"); //driver.findElement(By.className("atcui-selectOneMenu-styled")).sendKeys("2018"); // driver.findElement(By.id("j_id_2hy")).click(); //WebDriverWait(driver, 15); //driver.findElement(By.name("sortBy")).sendKeys("lowest-highest"); //driver.findElement(By.className("atcui-checkbox-input")).click(); //driver.findElement(By.className("atcui-checkbox-cell atcui-checkbox-label")).click(); //private void WebDriverWait(WebDriver driver, int i) { // throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
package com.example.x_b; import android.os.Bundle; import androidx.fragment.app.Fragment; import androidx.recyclerview.widget.DividerItemDecoration; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Toast; import com.example.x_b.db.BooleanBeanDao; import com.example.x_b.db.DatasBeanDao; import com.example.x_b.presetener.MIanpresetener; import com.example.x_b.view.Mianview; import org.greenrobot.eventbus.EventBus; import org.greenrobot.eventbus.Subscribe; import org.greenrobot.eventbus.ThreadMode; import java.util.ArrayList; import java.util.List; /** * A simple {@link Fragment} subclass. */ public class AFragment extends Fragment implements Mianview { private ArrayList<DatasBean> list; private Rvadapter rvadapter; private MIanpresetener mIanpresetener; private ArrayList<BooleanBean> booleanBeans; private BooleanBeanDao booleanBeanDao; public AFragment() { // Required empty public constructor } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View inflate = inflater.inflate(R.layout.fragment_a, container, false); mIanpresetener = new MIanpresetener(this); if(!EventBus.getDefault().isRegistered(this)){ EventBus.getDefault().register(this); } initview(inflate); return inflate; } @Override public void onDestroy() { super.onDestroy(); EventBus.getDefault().unregister(this); } @Subscribe(threadMode = ThreadMode.MAIN) public void getEvb(EvenBusBean busBean){ if(busBean.getType()==1) { // 添加到数据库 DatasBean datasBean = list.get(busBean.getId()); DatasBeanDao dao = BaseApp.getInstance().getDaoSession().getDatasBeanDao(); dao.insertOrReplace(datasBean); rvadapter.notifyDataSetChanged(); Toast.makeText(getContext(), "收藏成功", Toast.LENGTH_SHORT).show(); }else if(busBean.getType()==2) { // 删除数据库 Toast.makeText(getContext(), "取消插入", Toast.LENGTH_SHORT).show(); } } private void initview(View inflate) { RecyclerView rv = inflate.findViewById(R.id.rv); rv.setLayoutManager(new LinearLayoutManager(getContext())); rv.addItemDecoration(new DividerItemDecoration(getContext(),DividerItemDecoration.VERTICAL)); list = new ArrayList<>(); booleanBeans = new ArrayList<>(); rvadapter = new Rvadapter(list,getContext(),booleanBeans); rv.setAdapter(rvadapter); initdata(); } private void initdata() { mIanpresetener.getdtaa(); } @Override public void onsuccess(Bean bean) { // 获取数据 booleanBeanDao = BaseApp.getInstance().getDaoSession().getBooleanBeanDao(); List<DatasBean> datas = bean.getData().getDatas(); List<BooleanBean> all = booleanBeanDao.loadAll(); list.addAll(datas); booleanBeans.addAll(all); Log.d("tag","onsuccess"+datas.toString()); rvadapter.notifyDataSetChanged(); } }
public class Scope { public static void main(String[] args) { int x; x=10; if(x==10) { int y=20; System.out.println("x and y are: "+x + y); } //y=100; //x is still known here System.out.println("x is "+x); } }
package com.ebupt.portal.canyon.system.service.impl; import com.ebupt.portal.canyon.common.enums.UpdateEnum; import com.ebupt.portal.canyon.common.util.SystemConstant; import com.ebupt.portal.canyon.system.dao.UserRoleDao; import com.ebupt.portal.canyon.system.entity.UserRole; import com.ebupt.portal.canyon.system.service.UserRoleService; import com.ebupt.portal.canyon.system.vo.UserRoleVo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.Set; /** * 用户角色管理业务层实现 * * @author chy * @date 2019-03-08 16:57 */ @Service("userRoleService") public class UserRoleServiceImpl implements UserRoleService { private final UserRoleDao userRoleDao; @Autowired public UserRoleServiceImpl(UserRoleDao userRoleDao) { this.userRoleDao = userRoleDao; } @Override public Set<String> findByUserName(String userName) { return this.userRoleDao.findByUserName(userName); } @Override public UpdateEnum updateUserRoles(UserRoleVo userRoleVo) { String userName = userRoleVo.getUserName(); Set<String> roles = userRoleVo.getRoleIds(); if (SystemConstant.ADD.equals(userRoleVo.getOp())) { for (String roleId: roles) { UserRole userRole = new UserRole(userName, roleId); this.userRoleDao.save(userRole); } } else { this.userRoleDao.delete(userName, roles); } return UpdateEnum.SUCCESS; } @Override public UpdateEnum deleteByRoleId(String roleId) { this.userRoleDao.deleteByRoleId(roleId); return UpdateEnum.SUCCESS; } }
import java.io.Serializable; import java.util.ArrayList; import java.util.List; import javax.faces.bean.ManagedBean; import javax.faces.bean.SessionScoped; @ManagedBean @SessionScoped public class gererproblem implements Serializable { private int id; private Comment commt=new Comment(); private Solution solt=new Solution(); private Problem prob=new Problem(); private User userR=new User(); private Problem pr=new Problem(); private List<Solution> sol =new ArrayList<Solution>(); private List<Comment> comm =new ArrayList<Comment>(); private List<Problem> pros =new ArrayList<Problem>(); private List<Comment> comm_sol =new ArrayList<Comment>(); private Comment comv=new Comment(); public Comment getComv() { return comv; } public void setComv(Comment comv) { this.comv = comv; } public int getId() { return id; } public void setId(int id) { this.id = id; } public Problem getPr() { return pr; } public void setPr(Problem pr) { this.pr = pr; } public List<Comment> getComm() { return comm; } public void setComm(List<Comment> comm) { this.comm = comm; } public User getUserR() { return userR; } public void setUserR(User userR) { this.userR = userR; } public Problem getProb() { return prob; } public void setProb(Problem prob) { this.prob = prob; } public List<Comment> getComm_sol() { return comm_sol; } public void setComm_sol(List<Comment> comm_sol) { this.comm_sol = comm_sol; } public Comment getCommt() { return commt; } public void setCommt(Comment commt) { this.commt = commt; } public Solution getSolt() { return solt; } public void setSolt(Solution solt) { this.solt = solt; } public List<Solution> getSol() { return sol; } public void setSol(List<Solution> sol) { this.sol = sol; } public List<Problem> getPros() { return pros; } public void setPros(List<Problem> pros) { this.pros = pros; } public String detail(int id_prob) { comm_sol=new ArrayList<Comment>(); sol=new ArrayList<Solution>(); comm=new ArrayList<Comment>(); pros=new ArrayList<Problem>(); //System.out.println("yaaaayy je suis dans la fonction detail du problem:"+id_prob); id=id_prob; pr=ProblemDAO.getProblem(id_prob); //System.out.println("j'ai recuperer le probleme"); sol=ProblemDAO.getSolution(id_prob); //System.out.println("j'ai recuperer les solutions"); comm=ProblemDAO.getComments(id_prob); //System.out.println("j'ai recuperer les commentaires"); pros=ProblemDAO.getSousProblems(id_prob); //System.out.println("j'ai recuperer les sous problemes"); if(sol.size()!=0) { for(int i=0;i<sol.size();i++) { ArrayList<Comment> a=new ArrayList<Comment>(); a=ProblemDAO.getCommentSol(sol.get(i).getId_sol()); if(a.size()!=0) { for(int j=0;j<a.size();j++) { comm_sol.add(a.get(j)); System.out.println("la commentaire------------->id:"+a.get(j).getId()+"texte_commentaire:"+a.get(j).getText_comm()+"id_user"+a.get(j).getId_user()); } } } } return "probleme"; } public String AjouterComment(int id) { commt.setId_prob(pr.getId()); commt.setId_user(id); int id_c=ProblemDAO.addComment(commt); /*System.out.println("le id retourner par la fonction addComment est:"+id_c); System.out.println("La liste des commentaire est:"); for(int i=0;i<comm.size();i++) { System.out.println("la problem:"+comm.get(i).getId()+" "+comm.get(i).getText_comm()); } */ commt.setId(id_c); comm.add(commt); commt=new Comment(); return "probleme"; } public String SupprimerComment(int id_comment) { ProblemDAO.deleteComment(id_comment); ArrayList<Comment> c = new ArrayList<Comment>(); for(int i=0;i<comm.size();i++) { if(comm.get(i).getId()!=id_comment) { c.add(comm.get(i)); } } comm=c; return "probleme"; } public String addComSolution(int id_sol,int id) { comv.setId_sol(id_sol); comv.setId_user(id); System.out.println("le texte du commentaire:"+comv.getText_comm()); int id_c=SolutionDAO.addComment(comv); System.out.println("le id retourner par la fonction addComment est:"+id_c); System.out.println("La liste des commentaire est:"); comv.setId(id_c); comm_sol.add(comv); for(int i=0;i<comm_sol.size();i++) { System.out.println("le commentaire:"+comm_sol.get(i).getId()+" "+comm_sol.get(i).getText_comm()); } return "probleme"; } public String SupprimerSol(int id_sol) { SolutionDAO.DeleteSolution(id_sol); List<Solution> s=new ArrayList<Solution>(); if(sol.size()!=0) { for(int i=0;i<sol.size();i++) { if(sol.get(i).getId_sol()!=id_sol) { s.add(sol.get(i)); } } } sol=s; return "problem"; } public String SupprimerCom(int id) { CommentDAO.DeleteComment(id); List<Comment> s=new ArrayList<Comment>(); if(comm_sol.size()!=0) { for(int i=0;i<comm_sol.size();i++) { if(comm_sol.get(i).getId()!=id) { s.add(comm_sol.get(i)); } } } comm_sol=s; return "problem"; } public String AjouterSolution(int id) { solt.setId_prob(pr.getId()); solt.setId_user(id); int id_s=SolutionDAO.AddSolution(solt); solt.setId_sol(id_s); sol.add(solt); solt=new Solution(); return "problem"; } public String AjouterSousProb(int id) { prob.setId_user(id); int c=ProblemDAO.AddProbleme(prob); prob.setId(c); ProblemDAO.addRelationProb(pr.getId(),c); pros.add(prob); prob=new Problem(); return "problem"; } public String SupprimerSousProblem(int id) { System.out.println("je vais supprimer un probleme"); ProblemDAO.DeleteProblem(id); List<Problem> l=new ArrayList<Problem>(); for(int i=0;i<pros.size();i++) { if(pros.get(i).getId()!=id) { l.add(pros.get(i)); } } pros=l; return "problem"; } public String RechercheProblem() { System.out.println("je vais executer la fonction RechercheProblem "); pros=ProblemDAO.getProblemTitre(prob); for(int j=0;j<pros.size();j++) { System.out.println("pros: id="+pros.get(j).getId()); } return "ResultatRecherche"; } public String RechercheUser() { System.out.println("je vais executer la fonction RechercheUser "); pros=ProblemDAO.getProblemUser(userR); for(int j=0;j<pros.size();j++) { System.out.println("pros: id="+pros.get(j).getId()); } return "ResultatRecherche"; } }
package ip7.bathuniapp; import java.util.Date; /* * Simple getters and setters for a single task * in the user's to-do list */ public class Task { private long id; private String title; private int priority; private String description; private int parent_id; private Boolean complete; private Date date; public long getId() { return id; } public void setId(long id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public int getPriority() { return priority; } public void setPriority(int priority) { this.priority = priority; } public int getParent_id() { return parent_id; } public void setParent_id(int parent_id) { this.parent_id = parent_id; } public Boolean getComplete() { return complete; } public void setComplete(Boolean complete) { this.complete = complete; } public Date getDate() { return date; } public void setDate(Date date) { this.date = date; } // Will be used by the ArrayAdapter in the ListView @Override public String toString() { return title; } }
package edu.classm8web.services; import java.util.Vector; import edu.classm8web.dao.Database; import edu.classm8web.dto.M8; import edu.classm8web.exception.DatabaseException; public class UserService { private static UserService instance; public static UserService getInstance() { if (UserService.instance == null) { UserService.instance = new UserService(); } return UserService.instance; } private UserService() { } public void registerUser(M8 m8) throws DatabaseException { m8.setId(getHighestId() + 1); m8.setVotes(0); m8.setHasVoted(false); Database.getInstance().addStudent(m8); } public void updateUser(M8 newm8) throws DatabaseException { Database.getInstance().updateStudent(newm8); } public void deleteUser(long id) throws DatabaseException { Database.getInstance().removeStudentById((int) id); } private long getHighestId() throws DatabaseException { long id = 0; id = Database.getInstance().getMaxM8Id(); return id; } public M8 getM8(long m8id) throws DatabaseException { M8 mate = null; mate = Database.getInstance().getStudentById((int) m8id); return mate; } public Vector<M8> getAllM8s() throws DatabaseException { Vector<M8> mates = null; mates = Database.getInstance().getAllMates(); return mates; } }
package pl.czyzycki.towerdef.gameplay; import pl.czyzycki.towerdef.TowerDef.GameSound; import pl.czyzycki.towerdef.gameplay.entities.Tower; import pl.czyzycki.towerdef.gameplay.entities.Tower.Upgrade; import pl.czyzycki.towerdef.gameplay.entities.Tower.Upgradeable; import pl.czyzycki.towerdef.menus.OptionsScreen; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.g2d.Sprite; import com.badlogic.gdx.graphics.g2d.TextureAtlas; import com.badlogic.gdx.input.GestureDetector.GestureAdapter; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.math.Vector3; /** * Menu upgrade'owania wieżyczki * */ public class GameplayUpgradeGUI { class GameplayUpgradeGUIGestureListener extends GestureAdapter { @Override public boolean tap(int x, int y, int count) { Vector3 hudCord = new Vector3(x, y, 1); screen.gui.hudCamera.unproject(hudCord); return onTap(hudCord.x, hudCord.y); } } private GameplayScreen screen; private Tower selectedTower = null; private Vector2 upgradePos = new Vector2(); private Vector3 towerPos = new Vector3(); Sprite removeTowerSprite; Sprite rangeSprite; Sprite cooldownSprite; Sprite multiplierSprite; Sprite damageSprite; public GameplayUpgradeGUIGestureListener listener; private int getUpgradesCount() { if(selectedTower == null) return 0; if(selectedTower.upgrades == null) return 0; return selectedTower.upgrades.length; } GameplayUpgradeGUI(GameplayScreen screen) { this.screen = screen; listener = new GameplayUpgradeGUIGestureListener(); } void load(TextureAtlas texAtlas) { removeTowerSprite = texAtlas.createSprite("remove-tower"); rangeSprite = texAtlas.createSprite("upgrade-range"); cooldownSprite = texAtlas.createSprite("upgrade-cooldown"); multiplierSprite = texAtlas.createSprite("upgrade-multiplier"); damageSprite = texAtlas.createSprite("upgrade-damage"); } Tower getSelectedTower() { return selectedTower; } void setSelectedTower(Tower selectedTower) { this.selectedTower = selectedTower; } boolean isShowed() { return selectedTower != null; } void hide() { selectedTower = null; } void calcTowerPos() { // wzór na przekształcenie z przestrzeni world do hud: // towerPos * worldMatrix // towerPos * hudMatrix^-1 towerPos.x = selectedTower.getPos().x; towerPos.y = selectedTower.getPos().y; towerPos.z = 0; towerPos.mul(screen.camera.combined); // nie chcę liczyć macierzy odwrotnej, dlatego robię przekształcenia "ręcznie" towerPos.x += 1; towerPos.y += 1; towerPos.x /= 2.0f; towerPos.y /= 2.0f; towerPos.x *= screen.gui.hudCamera.viewportWidth; towerPos.y *= screen.gui.hudCamera.viewportHeight; } boolean onTap(float x, float y) { if(isShowed() == false) return false; float radius = removeTowerSprite.getWidth()/2.0f; calcTowerPos(); int upgradesCount = getUpgradesCount(); int buttonsCount = 1+upgradesCount; // bo jeszcze dodatkowo przycisk "remove tower" for(int i=0; i<buttonsCount; i++) { Vector2 pos = getUpgradeIconPos(i, buttonsCount); pos.x += towerPos.x; pos.y += towerPos.y; pos.x -= x; pos.y -= y; if(radius*radius > pos.x*pos.x + pos.y*pos.y) { // tap on upgrade if(OptionsScreen.vibrationEnabled()) Gdx.input.vibrate(30); if(i == 0) { // sell tower screen.sellTower(selectedTower); this.hide(); } else if(screen.maxUpgradeIsWorking() == false){ Upgrade upgrade = selectedTower.upgrades[i-1]; if(selectedTower.upgradeLevelIters[i-1]<upgrade.levels.length) { if(upgrade.levels[selectedTower.upgradeLevelIters[i-1]].cost < screen.money) { screen.money -= upgrade.levels[selectedTower.upgradeLevelIters[i-1]].cost; selectedTower.upgradeLevelIters[i-1]++; } } } screen.game.playSound(GameSound.CLICK); return true; } } this.hide(); return true; } Vector2 getUpgradeIconPos(int i, int count) { float radius = 40/screen.camera.zoom + removeTowerSprite.getWidth()/2.0f; float sn = (float) Math.sin(Math.PI*2.0f*i/count); float cs = (float) Math.cos(Math.PI*2.0f*i/count); upgradePos.x = -sn*radius; upgradePos.y = -cs*radius; return upgradePos; } void render(float dt) { if(selectedTower == null) return; calcTowerPos(); Vector2 pos; int upgradesCount = getUpgradesCount(); int buttonsCount = 1+upgradesCount; // bo jeszcze dodatkowo przycisk "remove tower" for(int i=0; i<buttonsCount; i++) { // wybór odpowiedniego sprite Sprite icon = null; Upgrade upgrade = null; if(i == 0) icon = removeTowerSprite; else { upgrade = selectedTower.upgrades[i-1]; if(upgrade.upgraded == Upgradeable.RANGE) { icon = rangeSprite; } else if(upgrade.upgraded == Upgradeable.COOLDOWN) { icon = cooldownSprite; } else if(upgrade.upgraded == Upgradeable.MULTIPLIER) { icon = multiplierSprite; } else icon = damageSprite; } pos = getUpgradeIconPos(i, buttonsCount); float halfW = icon.getWidth() / 2.0f; float halfH = icon.getHeight() / 2.0f; float iconX = towerPos.x+pos.x-halfW; float iconY = towerPos.y+pos.y-halfH; float iconCenter = towerPos.x + pos.x; icon.setPosition(iconX, iconY); icon.draw(screen.batch); if(upgrade != null) { float prevScale = screen.game.debugFont.getScaleX(); screen.game.debugFont.setScale(prevScale/2.0f); int upgradeLevel = selectedTower.upgradeLevelIters[i-1]; float ydiff = 20; if(screen.maxUpgradeIsWorking()) ydiff = 0; else { float sizeX = screen.game.debugFont.getBounds(upgradeLevel+"/"+upgrade.levels.length).width/2.0f; screen.game.debugFont.draw(screen.batch, upgradeLevel+"/"+upgrade.levels.length, iconCenter-sizeX, iconY); } if(upgradeLevel == upgrade.levels.length || screen.maxUpgradeIsWorking()) { float sizeX = screen.game.debugFont.getBounds("MAX").width/2.0f; screen.game.debugFont.draw(screen.batch, "MAX", iconCenter-sizeX, iconY-ydiff); } else { float sizeX = screen.game.debugFont.getBounds("$"+(int)(upgrade.levels[upgradeLevel].cost)).width/2.0f; screen.game.debugFont.draw(screen.batch, "$"+(int)(upgrade.levels[upgradeLevel].cost), iconCenter-sizeX, iconY-ydiff); } screen.game.debugFont.setScale(prevScale); } } } }
package com.yuan.dialog; import com.yuan.adapt.AdaptListUtils; import com.yuan.adapt.RadioAdapter; import com.yuan.adapt.ResolveListAdapter; import com.yuan.adapt.WeekCheckBoxAdapt; import com.yuan.control.CheckControl; import com.yuan.control.SettingControl; import com.yuan.graduate.R; import com.yuan.localServer.LocalManage; import com.yuan.model.M上班考勤表; import com.yuan.model.M下班考勤表; import com.yuan.model.M请假申请; import com.yuan.prefence.Constants; import com.yuan.prefence.FileConstants; import com.yuan.prefence.MsgKeys; import com.yuan.prefence.PreferenceKeys; import com.yuan.prefence.UrlConstants; import com.yuan.unit.BLog; import com.yuan.unit.PreferenceUtil; import com.yuan.unit.TimeUtils; import com.yuan.unit.ToastHelper; import org.json.JSONException; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.text.TextUtils; import android.view.View; import android.view.ViewGroup; import android.widget.Adapter; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.DatePicker; import android.widget.DatePicker.OnDateChangedListener; import android.widget.EditText; import android.widget.GridView; import android.widget.ListAdapter; import android.widget.ListView; import android.widget.TextView; import android.widget.TimePicker; import android.widget.TimePicker.OnTimeChangedListener; import java.util.Calendar; import java.util.List; import java.util.Map; /** * Dialog工具类 生成Dialog都在这个类 * * @author YUAN */ public class DialogUtil implements PreferenceKeys, Constants, UrlConstants, FileConstants { public static CustomDialog createCheckInDialog(final Context context, final Handler mHandler) { CustomDialog dialog = new CustomDialog(context); dialog.setTitle(R.string.check_in_title); String isChecked = ""; dialog.addContentView(R.layout.checkdialog); final EditText e_reason = (EditText) dialog.findViewById(R.id.e_reason); TextView t_reason = (TextView) dialog.findViewById(R.id.t_reason); if (!CheckControl.isCheckedInToday()) { isChecked = "今天上班尚未签到 \n"; String str = TimeUtils.getNowTime(); if (CheckControl.isRightChechinTime(str)) { e_reason.setVisibility(View.GONE); } String adress = LocalManage.getInstance().adress; str = String.format( context.getResources().getString(R.string.check_in_msg), str, adress); str = isChecked + str; t_reason.setText(str); dialog.setPositiveButton(R.string.ensure, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // TODO Auto-generated method stub if (e_reason.getVisibility() == View.VISIBLE) { String reason = e_reason.getText().toString().trim(); if (TextUtils.isEmpty(reason)) { ToastHelper.getInstance().shortToast(context, "请填写原因"); } else { M上班考勤表.getInstance().set备注("上班打卡异常,理由:" + reason); CheckControl.setCheckIn(context, mHandler); dialog.dismiss(); } } else { CheckControl.setCheckIn(context, mHandler); dialog.dismiss(); } } }); dialog.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // TODO Auto-generated method stub dialog.dismiss(); } }); } else { isChecked = "今天上班已经签到 不可重复签到 \n"; String str = M上班考勤表.getInstance().get日期(); e_reason.setVisibility(View.GONE); String adress = M上班考勤表.getInstance().get位置(); str = String.format( context.getResources().getString(R.string.check_in_msg), str, adress); str = isChecked + str; t_reason.setText(str); dialog.setNeutralButton(R.string.cancel, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // TODO Auto-generated method stub dialog.dismiss(); } }); } return dialog; } public static CustomDialog createCheckOutDialog(final Context context, final Handler mHandler) { CustomDialog dialog = new CustomDialog(context); dialog.setTitle(R.string.check_out_title); String isChecked = ""; dialog.addContentView(R.layout.checkdialog); final EditText e_reason = (EditText) dialog.findViewById(R.id.e_reason); TextView t_reason = (TextView) dialog.findViewById(R.id.t_reason); if (CheckControl.isRightChechoutTime(TimeUtils.getNowTime())) { e_reason.setVisibility(View.GONE); } if (!CheckControl.isCheckedOutToday()) { isChecked = "今天下班尚未签到\n"; String str = TimeUtils.getNowTime(); str = String.format( context.getResources().getString(R.string.check_out_msg), str, LocalManage.getInstance().adress); str = isChecked + str; t_reason.setText(str); dialog.setPositiveButton(R.string.ensure, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // TODO Auto-generated method stub if (e_reason.getVisibility() == View.VISIBLE) { String reason = e_reason.getText().toString().trim(); if (TextUtils.isEmpty(reason)) { ToastHelper.getInstance().shortToast(context, "请填写原因"); } else { M下班考勤表.getInstance().set备注("下班打卡异常,理由:" + reason); CheckControl.setCheckOut(context, mHandler); dialog.dismiss(); } } else { CheckControl.setCheckOut(context, mHandler); dialog.dismiss(); } } }); dialog.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // TODO Auto-generated method stub dialog.dismiss(); } }); } else { e_reason.setVisibility(View.GONE); isChecked = "今天下班已经签到 不可重复签到 \n"; String str = M下班考勤表.getInstance().get日期(); String adress = M下班考勤表.getInstance().get位置(); str = String.format( context.getResources().getString(R.string.check_out_msg), str, adress); str = isChecked + str; t_reason.setText(str); dialog.setNeutralButton(R.string.cancel, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // TODO Auto-generated method stub dialog.dismiss(); } }); } return dialog; } public static CustomDialog createChangeComnfigDialog(Context context) throws JSONException { final CustomDialog dialog = new CustomDialog(context); dialog.setTitle(R.string.choice_site); ListView listview = new ListView(context); final List<Map<String, Object>> list = AdaptListUtils.getInstance().getSystemConfig(); Adapter listItemAdapter = new RadioAdapter(context, list.size(), list, "companyname", SettingControl.getCompanyName()); listview.setAdapter((ListAdapter) listItemAdapter); dialog.addContentView(listview); dialog.setNeutralButton(R.string.cancel, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // TODO Auto-generated method stub dialog.dismiss(); } }); listview.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { // TODO Auto-generated method stub SettingControl.setCompanyName((String) list.get(position).get("companyname")); SettingControl.setCompanyUrl((String) list.get(position).get("url")); dialog.dismiss(); } }); return dialog; } public static final CustomDialog createFullAppShareDialog(final Context context) { final CustomDialog dialog = new CustomDialog(context); dialog.setTitle(R.string.share); dialog.addContentView(R.layout.share_other_dialog); GridView gridView = (GridView) dialog.findViewById(R.id.share_container); gridView.setAdapter(new ResolveListAdapter(context, buildOnlySendTextIntent(), null, null)); gridView.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { dialog.dismiss(); ResolveListAdapter adapter = (ResolveListAdapter) parent.getAdapter(); Intent intentForPosition = adapter.intentForPosition(position); context.startActivity(intentForPosition); } }); dialog.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); return dialog; } private static Intent buildOnlySendTextIntent() { Intent intent = new Intent(Intent.ACTION_SEND); intent.setType("text/plain"); intent.putExtra(Intent.EXTRA_SUBJECT, "移动考勤"); intent.putExtra(Intent.EXTRA_TEXT, "移动考勤,简单、高效、实用、便捷的手机考勤软件。访问网站了解详情:http://121.251.254.205:8088/"); return intent; } public static final CustomDialog createCommonDialog(final Context context, String title, String msg) { final CustomDialog dialog = new CustomDialog(context); dialog.setTitle(title); dialog.setMessage(msg); dialog.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); return dialog; } public static final CustomDialog createEnsureDialog(final Context context, String title, String msg, DialogInterface.OnClickListener ClickListener) { final CustomDialog dialog = new CustomDialog(context); dialog.setTitle(title); dialog.setMessage(msg); dialog.setPositiveButton(R.string.ensure, ClickListener); dialog.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); return dialog; } public static final CustomDialog createResetConfigDialog(final Context context, String title, String msg, DialogInterface.OnClickListener listen) { final CustomDialog dialog = new CustomDialog(context); dialog.setTitle(title); dialog.setMessage(msg); dialog.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); dialog.setPositiveButton(R.string.ensure, listen); return dialog; } public static final CustomDialog createStartWorkTimeInputDialog(final Context context, final Handler mHandler) { final CustomDialog dialog = new CustomDialog(context); dialog.addContentView(R.layout.custom_dialog_clock); dialog.setTitle(R.string.set_chechin_time); final EditText et_time = (EditText) dialog.findViewById(R.id.et_time); dialog.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); dialog.setPositiveButton(R.string.ensure, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { String str = et_time.getText().toString().trim(); if (CheckControl.isRightStartWorkTime(str)) { SettingControl.SetStartWorkTime(str); dialog.dismiss(); mHandler.sendEmptyMessage(MsgKeys.MAINSETTINGREFRESH); ToastHelper.getInstance().shortToast(context, R.string.setting_succeed); } else { ToastHelper.getInstance().shortToast(context, R.string.setting_failed); et_time.setText(""); } } }); return dialog; } public static final CustomDialog createEndWorkTimeInputDialog(final Context context, final Handler mHandler) { final CustomDialog dialog = new CustomDialog(context); dialog.addContentView(R.layout.custom_dialog_clock); dialog.setTitle(R.string.set_chechout_time); final EditText et_time = (EditText) dialog.findViewById(R.id.et_time); dialog.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); dialog.setPositiveButton(R.string.ensure, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { String str = et_time.getText().toString().trim(); if (CheckControl.isRightStartWorkTime(str)) { SettingControl.SetEndWorkTime(str); dialog.dismiss(); mHandler.sendEmptyMessage(MsgKeys.MAINSETTINGREFRESH); ToastHelper.getInstance().shortToast(context, R.string.setting_succeed); } else { ToastHelper.getInstance().shortToast(context, R.string.setting_failed); et_time.setText(""); } } }); return dialog; } public static final CustomDialog createCityChoiceDialog(final Context context, final Handler mHandler, String str) { final CustomDialog dialog = new CustomDialog(context); dialog.setTitle(R.string.choice_search_city); ListView listview = new ListView(context); final List<Map<String, Object>> list = AdaptListUtils.getInstance().getChinaCity(); Adapter listItemAdapter = new RadioAdapter(context, list.size(), list, "city", str); listview.setAdapter((ListAdapter) listItemAdapter); dialog.addContentView(listview); dialog.setNeutralButton(R.string.cancel, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // TODO Auto-generated method stub dialog.dismiss(); } }); listview.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { // TODO Auto-generated method stub Message msg = new Message(); msg.what = MsgKeys.CITYCHOICE; Bundle bundle = new Bundle(); String city = (String) list.get(position).get("city"); bundle.putString("city", city); msg.setData(bundle); mHandler.sendMessage(msg); dialog.dismiss(); } }); return dialog; } public static final CustomDialog createWorkAdressDialog(final Context context, final String str, final String lat, final String lng) { final CustomDialog dialog = new CustomDialog(context); dialog.setTitle(R.string.set_work_adress_title); String tempstr = String.format( context.getResources().getString(R.string.set_work_adress_msg), str); dialog.setMessage(tempstr); dialog.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // TODO Auto-generated method stub dialog.dismiss(); } }); dialog.setPositiveButton(R.string.ensure, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // TODO Auto-generated method stub SettingControl.SetWorkAdress(str); SettingControl.SetWorkLat(lat); SettingControl.SetWorkLng(lng); ToastHelper.getInstance().shortToast(context, R.string.setting_succeed); dialog.dismiss(); } }); return dialog; } public static final CustomDialog createWeekDialog(final Context context) { final CustomDialog dialog = new CustomDialog(context); dialog.setTitle(R.string.set_week); ListView listView = new ListView(context); Adapter mWeekCheckBoxAdapt = new WeekCheckBoxAdapt(context); listView.setAdapter((ListAdapter) mWeekCheckBoxAdapt); dialog.addContentView(listView); dialog.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // TODO Auto-generated method stub dialog.dismiss(); } }); dialog.setPositiveButton(R.string.ensure, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // TODO Auto-generated method stub ToastHelper.getInstance().shortToast(context, R.string.setting_succeed); dialog.dismiss(); } }); listView.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { // TODO Auto-generated method stub boolean flag = PreferenceUtil.getInstance().getBoolean(WEEK[position], false); PreferenceUtil.getInstance().putBoolean(WEEK[position], !flag); } }); return dialog; } public static final CustomDialog createOffLineMapDialog(final Context context, final Handler mHandler, String city) { final CustomDialog dialog = new CustomDialog(context); dialog.setTitle(R.string.off_line_map_title); String str = String.format( context.getResources().getString(R.string.off_line_map_msg), city); dialog.setMessage(str); dialog.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // TODO Auto-generated method stub PreferenceUtil.getInstance().putBoolean(AGREEN_TO_LOAD_MAP, false); dialog.dismiss(); } }); dialog.setPositiveButton(R.string.ensure, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // TODO Auto-generated method stub dialog.dismiss(); mHandler.sendEmptyMessage(MsgKeys.LOADMAP); } }); return dialog; } public static final CustomDialog createLeaveTypeDialog(final Context context, final Handler mHandler, final List<?> list) { final CustomDialog dialog = new CustomDialog(context); dialog.setTitle(R.string.choice_leave_type); ListView listview = new ListView(context); Adapter listItemAdapter = new RadioAdapter(context, list.size(), list, MARK.MARK_VALUE, null); listview.setAdapter((ListAdapter) listItemAdapter); dialog.addContentView(listview); dialog.setNeutralButton(R.string.cancel, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // TODO Auto-generated method stub dialog.dismiss(); } }); listview.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { // TODO Auto-generated method stub Message msg = new Message(); msg.what = MsgKeys.LEAVETYPE; M请假申请.getInstance().set请假类别( (String) ((Map<?, ?>) list.get(position)).get(MARK.MARK_MARK)); String str = (String) ((Map<?, ?>) list.get(position)).get(MARK.MARK_VALUE); msg.obj = str; mHandler.sendMessage(msg); dialog.dismiss(); } }); return dialog; } public static final CustomDialog createNoticePeopleDialog(final Context context, final Handler mHandler, final List<?> list, String po) { final CustomDialog dialog = new CustomDialog(context); dialog.setTitle(R.string.choice_notice_people); ListView listview = new ListView(context); Adapter listItemAdapter = new RadioAdapter(context, list.size(), list, "title", po); listview.setAdapter((ListAdapter) listItemAdapter); dialog.addContentView(listview); dialog.setNeutralButton(R.string.cancel, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // TODO Auto-generated method stub dialog.dismiss(); } }); listview.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { // TODO Auto-generated method stub Message msg = new Message(); msg.what = MsgKeys.NOTICEPEOPLE; String str = (String) ((Map<?, ?>) list.get(position)).get("title"); msg.obj = str; mHandler.sendMessage(msg); dialog.dismiss(); } }); return dialog; } public static final CustomDialog createPhotoDialog(final Context context, final Handler mHandler, final ListView mlistview) { final CustomDialog dialog = new CustomDialog(context); dialog.setTitle(R.string.choice_photo_type); dialog.addContentView(mlistview); dialog.setNeutralButton(R.string.cancel, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // TODO Auto-generated method stub dialog.dismiss(); } }); return dialog; } @SuppressWarnings("deprecation") public static final CustomDialog createTimeChoiceDialog(final Context context, final Handler mHandler, String title, final int what) { final CustomDialog dialog = new CustomDialog(context); DatePicker choice_time_dp; final TimePicker choice_time_tp; final StringBuffer dateSB = new StringBuffer(); final StringBuffer timeSB = new StringBuffer(); dialog.setTitle(title); dialog.addContentView(R.layout.choice_time); choice_time_dp = (DatePicker) dialog.findViewById(R.id.choice_time_dp); choice_time_tp = (TimePicker) dialog.findViewById(R.id.choice_time_tp); choice_time_tp.setIs24HourView(true); if (choice_time_tp != null) { ((ViewGroup) ((ViewGroup) choice_time_tp.getChildAt(0)).getChildAt(1)) .setVisibility(View.GONE); } Calendar ca = Calendar.getInstance(); int year = ca.get(Calendar.YEAR); int month = ca.get(Calendar.MONTH); int day = ca.get(Calendar.DATE); dateSB.append(year + "-"); if (month > 10) { dateSB.append(month + "-"); } else { dateSB.append("0" + month + "-"); } if (day > 10) { dateSB.append(day + ""); } else { dateSB.append("0" + day + ""); } timeSB.append(ca.getTime().getHours() + ":00"); choice_time_dp.init(year, month, day, new OnDateChangedListener() { @Override // 实现该接口 当用户点击改变日期是会被调用 public void onDateChanged(DatePicker view, int year, int monthOfYear, int dayOfMonth) { // TODO Auto-generated method stub monthOfYear++; dateSB.delete(0, dateSB.length()); dateSB.append(year + "-"); if (monthOfYear > 10) { dateSB.append(monthOfYear + "-"); } else { dateSB.append("0" + monthOfYear + "-"); } if (dayOfMonth > 10) { dateSB.append(dayOfMonth + ""); } else { dateSB.append("0" + dayOfMonth + ""); } BLog.d("yuanwei", "Date = " + dateSB.toString()); } }); choice_time_tp.setOnTimeChangedListener(new OnTimeChangedListener() { @Override public void onTimeChanged(TimePicker view, int hourOfDay, int minute) { // TODO Auto-generated method stub timeSB.delete(0, timeSB.length()); timeSB.append(hourOfDay + ":00"); BLog.d("yuanwei", "Date = " + timeSB.toString()); } }); dialog.setPositiveButton(R.string.ensure, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // TODO Auto-generated method stub Message msg = new Message(); msg.what = what; BLog.d("yuanwei", "time = " + (String) dateSB.toString() + " " + (String) choice_time_tp.toString()); msg.obj = (String) dateSB.toString() + " " + (String) timeSB.toString(); mHandler.sendMessage(msg); dialog.dismiss(); } }); dialog.setNeutralButton(R.string.cancel, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // TODO Auto-generated method stub dialog.dismiss(); } }); return dialog; } }
package com.example.headfirst.collection; import com.example.headfirst.collection.parttwo.MenuItem; import java.util.ArrayList; /** * create by Administrator : zhanghechun on 2020/4/4 */ public class PrintMenu { public static void main(String[] args) { PancakeHouseMenu pancakeHouseMenu = new PancakeHouseMenu(); ArrayList menuItems = pancakeHouseMenu.getMenuItems(); DinerMenu dinerMenu = new DinerMenu(); MenuItem[] menuItems1 = dinerMenu.getMenuItems(); for (int i = 0; i < menuItems.size(); i++) { MenuItem menuItem= (MenuItem) menuItems.get(i); System.out.println(menuItem.getName()+" "); System.out.println(menuItem.getDescription()+" "); System.out.println(menuItem.getPrice()+" "); System.out.println(menuItem.getDescription()); } for (int i = 0; i < menuItems1.length; i++) { MenuItem menuItem=menuItems1[i] ; System.out.println(menuItem.getName()+" "); System.out.println(menuItem.getDescription()+" "); System.out.println(menuItem.getPrice()+" "); System.out.println(menuItem.getDescription()); } } }
package com.example.fy.blog.ui; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.support.v7.widget.Toolbar; import android.view.MotionEvent; import android.view.View; import android.view.Window; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import com.example.fy.blog.R; import com.example.fy.blog.bean.Comment; import com.example.fy.blog.bean.User; import com.example.fy.blog.interfaces.OnSendCommentCallBack; import com.example.fy.blog.util.APIUtils; import com.example.fy.blog.util.LogUtil; import com.example.fy.blog.util.ShareUtils; import java.text.SimpleDateFormat; import java.util.Date; /** * Created by fy on 2016/6/7. */ public class WriteCommentActivity extends Activity{ public Toolbar toolbar; public TextView ok; public TextView cancel; public EditText tv_comment; public String blogId; public String commentId; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.wriite_comment); Intent intent = getIntent(); Bundle bundle = intent.getExtras(); blogId = bundle.getString("blogId"); commentId = new Integer(bundle.getInt("commentId")+1).toString(); LogUtil.d("WriteComment",blogId); LogUtil.d("WriteComment",commentId); initView(); } private void initView() { toolbar = (Toolbar)findViewById(R.id.toolbar); tv_comment = (EditText)findViewById(R.id.write_comment); ok = (TextView)findViewById(R.id.ok); cancel = (TextView)findViewById(R.id.cancel); ok.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { sendComment(); } }); cancel.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { finish(); } }); } //点击确定之后的数据处理 private void sendComment() { Intent intent = getIntent(); Bundle bundle = new Bundle(); User user = ShareUtils.getLoginInfo(); SimpleDateFormat formatter = new SimpleDateFormat("yyyy年MM月dd日 HH:mm "); Date curDate = new Date(System.currentTimeMillis());//获取当前时间 String time = formatter.format(curDate); Comment comment = new Comment(commentId,null,blogId, user.get_username(), user.get_portrait(),time,tv_comment.getText().toString()); bundle.putSerializable("Comment",comment); intent.putExtras(bundle); setResult(RESULT_OK,intent); APIUtils.sendComment(blogId, new OnSendCommentCallBack() { @Override public void OnSendCommentSuccess() { Toast.makeText(WriteCommentActivity.this,"评论成功",Toast.LENGTH_SHORT).show(); } @Override public void OnSendCommentFailed() { Toast.makeText(WriteCommentActivity.this,"评论失败",Toast.LENGTH_SHORT).show(); } }); finish(); } }
package com.Stephanie; /** * Created by Stephanie on 10/25/2016. */ public class LP extends Album { private int condition; //1 = barely playable, 5= mint public LP(String artist, String title, int condition, double price){ super(artist, title,price); //call the album constructor this.condition = condition; } @Override public String toString(){ return "Format = CD, Artist = "+artist+", Title= "+ title+"Condition="+condition+", Price $" + price; } }
package com.catnap.demo.core.model; import com.fasterxml.jackson.annotation.JsonPropertyOrder; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; import java.io.Serializable; /** * Created by Woody on 12/29/13. */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "Prices", propOrder = { "listPrice", "salePrice", "employeePrice", "formattedListPrice", "formattedSalePrice", "formattedEmployeePrice" }) @JsonPropertyOrder(alphabetic = true, value = { "listPrice", "salePrice", "employeePrice" }) public class ProductPrices implements Serializable { @XmlElement(name = "ListPrice", required = true) private Double listPrice; @XmlElement(name = "SalePrice") private Double salePrice; @XmlElement(name = "EmployeePrice", required = true) private Double employeePrice; @XmlElement(name = "FormattedListPrice", required = true) private String formattedListPrice; @XmlElement(name = "FormattedSalePrice") private String formattedSalePrice; @XmlElement(name = "FormattedEmployeePrice", required = true) private String formattedEmployeePrice; public Double getListPrice() { return listPrice; } public void setListPrice(Double listPrice) { this.listPrice = listPrice; } public Double getSalePrice() { return salePrice; } public void setSalePrice(Double salePrice) { this.salePrice = salePrice; } public Double getEmployeePrice() { return employeePrice; } public void setEmployeePrice(Double employeePrice) { this.employeePrice = employeePrice; } public String getFormattedListPrice() { return formattedListPrice; } public void setFormattedListPrice(String formattedListPrice) { this.formattedListPrice = formattedListPrice; } public String getFormattedSalePrice() { return formattedSalePrice; } public void setFormattedSalePrice(String formattedSalePrice) { this.formattedSalePrice = formattedSalePrice; } public String getFormattedEmployeePrice() { return formattedEmployeePrice; } public void setFormattedEmployeePrice(String formattedEmployeePrice) { this.formattedEmployeePrice = formattedEmployeePrice; } }
package com.lus.seansprototype.notifications; import java.util.ArrayList; import java.util.List; import java.util.Observable; public class ObservableNotifications extends Observable { private List<Notification> notifications; public ObservableNotifications(){ notifications = new ArrayList<>(); } public ObservableNotifications(List<Notification> notifications){ this.notifications = notifications; setChanged(); notifyObservers(); } public void setNotifications(List<Notification> notifications){ this.notifications = notifications; setChanged(); notifyObservers(); } public List<Notification> getNotifications(){ return notifications; } public void addNotification(Notification notification){ notifications.add(notification); setChanged(); notifyObservers(); } public void removeNotification(Notification notification){ //TODO implement proper filtering of removed item by comparing id's, possibly move to hashmap??? notifications.remove(notification.id); setChanged(); notifyObservers(); } public void modifyNotification(int id, Notification notification){ notifications.set(id,notification); setChanged(); notifyObservers(); } }
package net.iz44kpvp.kitpvp.Kits; import java.util.HashMap; import org.bukkit.Bukkit; import org.bukkit.Effect; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.entity.Item; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.block.Action; import org.bukkit.event.entity.PlayerDeathEvent; import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.plugin.Plugin; import org.bukkit.util.Vector; import net.iz44kpvp.kitpvp.Main; import net.iz44kpvp.kitpvp.Sistemas.API; import net.iz44kpvp.kitpvp.Sistemas.Cooldown; import net.iz44kpvp.kitpvp.Sistemas.Habilidade; public class C4 implements Listener { public static HashMap<String, Item> bomba; static { C4.bomba = new HashMap<String, Item>(); } @EventHandler public void aoBotar(final PlayerInteractEvent e) { final Player p = e.getPlayer(); if (Habilidade.getAbility(p).equalsIgnoreCase("C4")) { if (e.getAction() == Action.RIGHT_CLICK_AIR || e.getAction() == Action.RIGHT_CLICK_BLOCK) { if (p.getItemInHand().getType() == Material.SLIME_BALL) { if (Cooldown.add(p)) { API.MensagemCooldown(p); return; } final Location loc = p.getLocation(); final Vector vec = new Vector(0, 2, 0); final Location direc = loc.add(vec); final Item item = p.getWorld().dropItem(direc, new ItemStack(Material.TNT, 1)); item.setVelocity(p.getEyeLocation().getDirection()); C4.bomba.put(p.getName(), item); final ItemStack itemb = new ItemStack(Material.STONE_BUTTON); final ItemMeta itembm = itemb.getItemMeta(); itembm.setDisplayName("§7Kit §eC4"); itemb.setItemMeta(itembm); p.getInventory().setItemInHand(itemb); p.updateInventory(); p.sendMessage("§eBomba Armada"); } else if (p.getItemInHand().getType() == Material.STONE_BUTTON) { final ItemStack itemb2 = new ItemStack(Material.SLIME_BALL); final ItemMeta itembm2 = itemb2.getItemMeta(); itembm2.setDisplayName("§7Kit §eC4"); itemb2.setItemMeta(itembm2); p.getInventory().setItemInHand(itemb2); final Item item2 = C4.bomba.get(p.getName()); p.getWorld().createExplosion(item2.getLocation(), 2.5f); item2.getWorld().playEffect(item2.getLocation(), Effect.EXPLOSION_HUGE, 10); C4.bomba.remove(p.getName()); item2.remove(); p.updateInventory(); p.sendMessage("§aBomba Explodida"); Cooldown.add(p, 20); Bukkit.getScheduler().scheduleSyncDelayedTask((Plugin) Main.getInstance(), (Runnable) new Runnable() { @Override public void run() { p.sendMessage(API.fimcooldown); } }, 400L); } } else if ((e.getAction() == Action.LEFT_CLICK_AIR || e.getAction() == Action.LEFT_CLICK_BLOCK) && p.getItemInHand().getType() == Material.STONE_BUTTON) { if (Cooldown.add(p)) { API.MensagemCooldown(p); return; } final ItemStack itemb2 = new ItemStack(Material.SLIME_BALL); final ItemMeta itembm2 = itemb2.getItemMeta(); itembm2.setDisplayName("§7Kit §eC4"); itemb2.setItemMeta(itembm2); p.getInventory().setItemInHand(itemb2); final Item item2 = C4.bomba.get(p.getName()); C4.bomba.remove(p.getName()); item2.remove(); p.updateInventory(); p.sendMessage("§cBomba Desarmada"); } } } @EventHandler public void aomorrer(final PlayerDeathEvent e) { final Player p = e.getEntity(); if (C4.bomba.containsKey(p.getName())) { final Item item = C4.bomba.get(p.getName()); item.remove(); C4.bomba.remove(p.getName()); } } }
package com.sjain.couponduniatask.network.apimodel; import com.google.gson.annotations.SerializedName; import com.sjain.couponduniatask.model.TaskResponse; /** * Created by sjain on 31/10/17. */ public class APITaskResponse { @SerializedName("success") private Boolean success; @SerializedName("authenticated") private Boolean authenticated; @SerializedName("response") private TaskResponse response; public Boolean getSuccess() { return success; } public void setSuccess(Boolean success) { this.success = success; } public Boolean getAuthenticated() { return authenticated; } public void setAuthenticated(Boolean authenticated) { this.authenticated = authenticated; } public TaskResponse getResponse() { return response; } public void setResponse(TaskResponse response) { this.response = response; } }
i am learning how to use git. this is a test doc. hello world another modify stage of repository
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.mapred; import java.util.ArrayList; import java.util.List; import java.util.Random; import junit.framework.Assert; import org.junit.Test; public class TestSimulatorEventQueue { private Random random = new Random(); public class TestEvent extends SimulatorEvent { public TestEvent(SimulatorEventListener listener, long timeStamp) { super(listener, timeStamp); } } public class TestEventWithCount extends TestEvent { private int count; public TestEventWithCount(SimulatorEventListener listener, long timeStamp, int count) { super(listener, timeStamp); this.count = count; } public int getCount() { return count; } } public static class TestListener implements SimulatorEventListener { @Override public List<SimulatorEvent> accept(SimulatorEvent event) { if (event instanceof TestEvent) { return SimulatorEventQueue.EMPTY_EVENTS; } return null; } @Override public List<SimulatorEvent> init(long when) { return null; } } @Test public void testSimpleGetPut() { SimulatorEventQueue queue = new SimulatorEventQueue(); SimulatorEventListener listener = new TestListener(); SimulatorEvent event = new TestEvent(listener, 10); queue.add(event); SimulatorEvent first = queue.get(); Assert.assertEquals(first.getTimeStamp(), event.getTimeStamp()); Assert.assertEquals(first.getListener(), event.getListener()); } @Test public void testListPut() { SimulatorEventQueue queue = new SimulatorEventQueue(); SimulatorEventListener listener = new TestListener(); List<SimulatorEvent> listEvent = new ArrayList<SimulatorEvent>(); listEvent.add(new TestEvent(listener, 10)); listEvent.add(new TestEvent(listener, 11)); queue.addAll(listEvent); SimulatorEvent first = queue.get(); Assert.assertEquals(first.getTimeStamp(), 10); Assert.assertEquals(first.getListener(), listener); SimulatorEvent second = queue.get(); Assert.assertEquals(second.getTimeStamp(), 11); Assert.assertEquals(first.getListener(), listener); } @Test public void testKeepOrder() { SimulatorEventQueue queue = new SimulatorEventQueue(); SimulatorEventListener listener = new TestListener(); List<SimulatorEvent> listEvent = new ArrayList<SimulatorEvent>(); int count = 0; for (int i = 0; i < random.nextInt(100); i++) { listEvent.clear(); for (int j = 0; j < random.nextInt(5); j++) { listEvent.add(new TestEventWithCount(listener, random.nextInt(10), count++)); } queue.addAll(listEvent); } TestEventWithCount next; //dump(next); TestEventWithCount last = null; while((next = (TestEventWithCount) queue.get()) != null) { if (last != null && last.getTimeStamp() == next.getTimeStamp()) { Assert.assertTrue (last.getCount() < next.getCount()); //dump(next); } last = next; } } public void dump(TestEventWithCount event) { System.out.println("timestamp: " + event.getTimeStamp() + ", count: " + event.getCount()); } @Test public void testInsertEventIntoPast() { SimulatorEventQueue queue = new SimulatorEventQueue(); SimulatorEventListener listener = new TestListener(); queue.add(new TestEvent(listener, 10)); queue.get(); // current time is 10. try { // the event to insert happened at 5. It happens in the past because // current time is 10. queue.add(new TestEvent(listener, 5)); Assert.fail("Added Event occurred in the past"); } catch (Exception e) { } } }
package com.example.lib; import android.app.Activity; import android.content.Intent; import android.support.annotation.Keep; import android.support.v4.app.FragmentActivity; import android.util.Log; import com.lotus.annotation.LotusProxy; import com.example.framework.TestImpl; /** * Created by ljq on 2019/5/8 */ @LotusProxy(TestImpl.TAG) @Keep public class TestProxy { private String data; public String getData() { return data; } public void setData(String data) { this.data = data; Log.e("TAG", "setData:" + data); } public void startTestActivity(Activity activity) { activity.startActivity(new Intent(activity, TestActivity.class)); } }
package pt.pagamigo.ws; import static javax.xml.ws.BindingProvider.ENDPOINT_ADDRESS_PROPERTY; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.PasswordAuthentication; import java.net.SocketTimeoutException; import java.util.ArrayList; import java.util.Collection; import java.util.GregorianCalendar; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Set; import java.util.TreeMap; import java.security.KeyPair; import java.security.KeyPairGenerator; import java.sql.*; import javax.sql.*; import javax.annotation.PostConstruct; import javax.jws.*; import javax.transaction.xa.Xid; import javax.xml.datatype.DatatypeConfigurationException; import javax.xml.datatype.DatatypeFactory; import javax.xml.datatype.XMLGregorianCalendar; import javax.naming.NamingException; import javax.xml.namespace.QName; import javax.xml.registry.BulkResponse; import javax.xml.registry.BusinessQueryManager; import javax.xml.registry.Connection; import javax.xml.registry.ConnectionFactory; import javax.xml.registry.FindQualifier; import javax.xml.registry.JAXRException; import javax.xml.registry.RegistryService; import javax.xml.registry.infomodel.Organization; import javax.xml.registry.infomodel.Service; import javax.xml.registry.infomodel.ServiceBinding; import javax.xml.ws.*; import javax.xml.ws.handler.Handler; import javax.xml.ws.handler.HandlerResolver; import javax.xml.ws.handler.PortInfo; import javax.transaction.xa.XAResource; import javax.transaction.xa.Xid; import com.mysql.jdbc.jdbc2.optional.MysqlXADataSource; import pt.bank.ws.Bank; import pt.bank.ws.BankImplService; import security.CertificateAuthorityInterface; import security.CertificateAuthorityService; import pt.pagamigo.ws.handler.*; import pt.pagamigo.ws.xid.XidImpl; import static javax.xml.ws.BindingProvider.ENDPOINT_ADDRESS_PROPERTY; @HandlerChain(file="/handler-chain.xml") @WebService( endpointInterface="pt.pagamigo.ws.PagAmigoPortType", wsdlLocation="PagAmigo.1_0.wsdl", name="PagAmigo", portName="PagAmigoPort", targetNamespace="http://ws.pagamigo.pt/", serviceName="PagAmigoService" ) public class PagAmigoImpl implements PagAmigoPortType { private TreeMap<String, String> clients = new TreeMap<String, String>(); private TreeMap<String, ArrayList<MovimentoType> > movements = new TreeMap<String, ArrayList<MovimentoType> >(); private KeyPair keys; private CertificateAuthorityInterface ca; private Bank toBank = null; private Bank fromBank = null; private String gtrid; byte[] gtridBytes = new byte[] { 0x00, 0x00, 0x03, 0x04 }; @PostConstruct private void init() throws Exception{ clients.put("alice", "1008"); clients.put("bruno", "2002"); clients.put("carlos", "1003"); clients.put("mariazinha", "1005"); clients.put("zeninguem", "2005"); clients.put("ist", "1010"); clients.put("bn", "1009"); movements.put("alice", new ArrayList<MovimentoType>()); movements.put("bruno", new ArrayList<MovimentoType>()); movements.put("carlos",new ArrayList<MovimentoType>()); movements.put("mariazinha", new ArrayList<MovimentoType>()); movements.put("zeninguem", new ArrayList<MovimentoType>()); movements.put("ist", new ArrayList<MovimentoType>()); movements.put("bn", new ArrayList<MovimentoType>()); KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA"); keyGen.initialize(2048); keys = keyGen.generateKeyPair(); CertificateAuthorityService service = new CertificateAuthorityService(); ca = service.getCertificateAuthorityPort(); ca.setPAPublicKey(keys.getPublic().getEncoded()); } private static void writeFile(String path, byte[] content) throws FileNotFoundException, IOException { FileOutputStream fos = new FileOutputStream(path); fos.write(content); fos.close(); } /*Method for accessing to balance from an acount of the client with idciente*/ public int consultarSaldo(String idcliente) throws ClienteInexistente{ System.out.println("««««««««««««««««««««««««««« CONSULTAR SALDO »»»»»»»»»»»»»»»»»»»»»»»»»»»»"); gtridBytes[0]++; XidImpl.setXid(gtrid); int balance = -1; gtrid = ""; gtrid = javax.xml.bind.DatatypeConverter.printHexBinary(gtridBytes); boolean hasClient = clients.containsKey(idcliente); if(!hasClient){ throw new ClienteInexistente("Client " + idcliente + " does not exist!", new ClienteInexistenteType()); } String cliente = clients.get(idcliente); String banco = this.getNumBanco(cliente); String conta = this.getNumConta(cliente); fromBank = this.getBanco(banco); try{ balance = fromBank.getBalance(conta); } catch (WebServiceException e) { System.out.println(e.getLocalizedMessage()); } return balance; } /*Method for making an payment from clienteOrdenante to clienteBeneficiario*/ public Object efectuarPagamento(String clienteOrdenante, String clienteBeneficiario, int montante, String descritivo) throws ClienteInexistente, MontanteInvalido, SaldoInsuficiente{ System.out.println("««««««««««««««««««««««««««« EFECTUAR PAGAMENTO »»»»»»»»»»»»»»»»»»»»»»»»»»»»"); /*true if the ClienteOrdenante exists*/ boolean nClienteOrdenante; /*true if the ClienteBeneficiario exists*/ boolean nClienteBeneficiario; MovimentoType transaction1; MovimentoType transaction2; GregorianCalendar gc; XMLGregorianCalendar xgc; Comprovativo comprovativo = null; byte[] comprovativoEncriptado = new byte[256]; Object oComprovativoAssinado = null; if(montante < 0){ throw new MontanteInvalido("Invalid Amount!", new MontanteInvalidoType()); } nClienteOrdenante= clients.containsKey(clienteOrdenante); nClienteBeneficiario= clients.containsKey(clienteBeneficiario); if(!nClienteOrdenante || !nClienteBeneficiario){ throw new ClienteInexistente("One or both clients do not exist!", new ClienteInexistenteType()); } String cliente1 = clients.get(clienteOrdenante); String cliente2 = clients.get(clienteBeneficiario); String bank1NUM = this.getNumBanco(cliente1); String bank2NUM = this.getNumBanco(cliente2); String conta1 = this.getNumConta(cliente1); String conta2 = this.getNumConta(cliente2); gtridBytes[1]++; gtrid = javax.xml.bind.DatatypeConverter.printHexBinary(gtridBytes); XidImpl.setXid(gtrid); fromBank = this.getBanco(bank1NUM); toBank = this.getBanco(bank2NUM); /*GET BALANCE OF THE WITHDRAW ACCOUNT*/ if(fromBank.getBalance(conta1) < montante){ throw new SaldoInsuficiente("Not enough money!", new SaldoInsuficienteType()); } /*SEE IF TRANSACTION OCCURS IN THE SAME BANK*/ if(bank1NUM.equals(bank2NUM)){ if(fromBank.startLocalTransfer(conta1, conta2, montante)){ fromBank.endTransaction(true); }else{ fromBank.endTransaction(false); } }else{ /*Variable to count how many banks are ready to commit a transaction*/ int votes=0; int[] timedOut = new int[2]; boolean fromBankSuccess=false; boolean toBankSuccess=false; while(timedOut[0]< 3 && !fromBankSuccess){ try{ /*if Bank of clienteOrdenante is ready to commit votes is incremented*/ votes += fromBank.startWithdraw(conta1, montante); fromBankSuccess=true; System.out.println("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TRANSACCAO REALIZADA COM SUCESSO %%%%%%%%%%%%%%%%%%%%%%%%%%"); } catch (WebServiceException e) { timedOut[0]++; fromBankSuccess=false; fromBank.abortTransaction(); System.out.println("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TRANSACCAO FALHADA" + timedOut[0] +"vezes %%%%%%%%%%%%%%%%%%%%%%%%%%"); } } while(timedOut[1]< 3 && !toBankSuccess){ try{ /*if Bank of clienteOrdenante is ready to commit votes is incremented*/ votes += toBank.startDeposit(conta2, montante); toBankSuccess=true; System.out.println("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TRANSACCAO REALIZADA COM SUCESSO %%%%%%%%%%%%%%%%%%%%%%%%%%"); } catch (WebServiceException e) { timedOut[1]++; toBankSuccess=false; toBank.abortTransaction(); System.out.println("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TRANSACCAO FALHADA" + timedOut[1] +"vezes %%%%%%%%%%%%%%%%%%%%%%%%%%"); } } /*if votes == 2 the two banks are ready to commit and the transaction can be executed*/ if(votes==2){ fromBank.endTransaction(true); toBank.endTransaction(true); }else{ if(fromBankSuccess) fromBank.endTransaction(false); if(toBankSuccess) toBank.endTransaction(false); System.out.println("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TRANSACCAO FALHADA VOTOS < 2 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%"); return null; } } /*MAKE THE PROVE OF PAYMENT */ try { gc=new GregorianCalendar(); xgc = DatatypeFactory.newInstance().newXMLGregorianCalendar(gc); transaction1 = new MovimentoType(); transaction2 = new MovimentoType(); transaction1.setDataHora(xgc); transaction1.setDescritivo(descritivo); transaction1.setMontante(0-montante); movements.get(clienteOrdenante).add(transaction1); transaction2.setDataHora(xgc); transaction2.setDescritivo(descritivo); transaction2.setMontante(montante); movements.get(clienteBeneficiario).add(transaction2); comprovativo = new Comprovativo(xgc, clienteOrdenante, clienteBeneficiario, montante, descritivo); } catch (DatatypeConfigurationException e) { e.printStackTrace(); } /*ENCRYPT THE PROVE OF PAYMENT TO SEND*/ try{ comprovativoEncriptado = comprovativo.encrypt(keys.getPrivate()); System.out.println(comprovativoEncriptado.length); oComprovativoAssinado = ca.makeSignature(comprovativoEncriptado); } catch(Exception e){ e.printStackTrace(); } byte[] comprovativoAssinado = (byte[]) oComprovativoAssinado; System.out.println(comprovativoAssinado.length); return comprovativoAssinado; } public List<MovimentoType> consultarMovimentos(String idCliente) throws ClienteInexistente{ if(!clients.containsKey(idCliente)) throw new ClienteInexistente("Client " + idCliente + " does not exist!", new ClienteInexistenteType()); return movements.get(idCliente); } public Bank getBanco(String nomeBanco){ BankImplService service = new BankImplService(); service.setHandlerResolver(new PAHandlerResolver()); Bank port = service.getBankImplPort(); String endpointAddress = null; String organizationName = nomeBanco; System.out.println(" "); System.out.println("###############SEARCH IN UDDI##############"); System.out.println("Searching For Bank " + organizationName +" In UDDI Name Server(...)"); // get endpoint address try { String uddiURL = "http://localhost:8081"; ConnectionFactory connFactory = ConnectionFactory.newInstance(); // configure Connection Factory using properties Properties props = new Properties(); // Location of connection configuration file (should be // available at WEB-INF/classes on the .war file) props.setProperty("scout.juddi.client.config.file", "uddi.xml"); // search URL of UDDI registry props.setProperty("javax.xml.registry.queryManagerURL", uddiURL + "/juddiv3/services/inquiry"); // publication URL of UDDI registry props.setProperty("javax.xml.registry.lifeCycleManagerURL", uddiURL + "/juddiv3/services/publish"); // security manager URL of UDDI registry props.setProperty("javax.xml.registry.securityManagerURL", uddiURL + "/juddiv3/services/security"); // version of UDDI registry props.setProperty("scout.proxy.uddiVersion", "3.0"); // transport protocol used for communication with UDDI registry props.setProperty("scout.proxy.transportClass", "org.apache.juddi.v3.client.transport.JAXWSTransport"); connFactory.setProperties(props); Connection connection = connFactory.createConnection(); PasswordAuthentication passwdAuth = new PasswordAuthentication("username", "password".toCharArray()); Set<PasswordAuthentication> creds = new HashSet<PasswordAuthentication>(); creds.add(passwdAuth); connection.setCredentials(creds); RegistryService rs = connection.getRegistryService(); BusinessQueryManager businessQueryManager = rs.getBusinessQueryManager(); // ////////////////////////////////////////////////////// // Search for registered organization // ////////////////////////////////////////////////////// Organization org = null; Collection<String> findQualifiers = new ArrayList<String>(); findQualifiers.add(FindQualifier.SORT_BY_NAME_DESC); Collection<String> namePatterns = new ArrayList<String>(); namePatterns.add(organizationName); // Perform search BulkResponse r = businessQueryManager.findOrganizations(findQualifiers, namePatterns, null, null, null, null); @SuppressWarnings("unchecked") Collection<Organization> orgs = r.getCollection(); @SuppressWarnings("unchecked") Collection<Service> servs; @SuppressWarnings("unchecked") Collection<ServiceBinding> binds; //SEARCH FOR nomeBanco for (Organization o : orgs) { if (o.getName().getValue().equals(organizationName)) { servs = o.getServices(); for (Service s : servs) { if (s.getName().getValue().equals(organizationName)) { binds = s.getServiceBindings(); for (ServiceBinding b : binds) { if(endpointAddress==null) endpointAddress = b.getAccessURI(); } } } } } } catch (JAXRException e) { System.out.println("UDDI Error contacting Registry!"); System.out.println("################################################"); } System.out.println("Bank "+organizationName +" Found! Setting Endpoint To Target Server (...)"); System.out.println("################################################"); BindingProvider bindingProvider = (BindingProvider) port; Map<String, Object> requestContext = bindingProvider.getRequestContext(); requestContext.put( "javax.xml.ws.client.connectionTimeout", "2000" ); requestContext.put( "javax.xml.ws.client.receiveTimeout", "2000" ); // set endpoint address System.out.println(" "); System.out.println("###############SETTING ENDPOINT################"); System.out.println("Changing endpoint address from:"); System.out.println(requestContext.get(ENDPOINT_ADDRESS_PROPERTY)); System.out.println("to:"); System.out.println(endpointAddress); System.out.println(); requestContext.put(ENDPOINT_ADDRESS_PROPERTY, endpointAddress); System.out.println("################################################"); return port; } public String getNumConta(String c){ String num = c.substring(1,4); return num; } public String getNumBanco(String c){ String num = c.substring(0,1); return num; } }
package com.tencent.mm.g.a; import com.tencent.mm.sdk.b.b; public final class oy extends b { public a bZT; public oy() { this((byte) 0); } private oy(byte b) { this.bZT = new a(); this.sFm = false; this.bJX = null; } }
package com.dvt.example.producer; import java.util.UUID; import org.apache.activemq.artemis.api.core.client.ClientConsumer; import org.apache.activemq.artemis.api.core.client.ClientMessage; import org.apache.activemq.artemis.api.core.client.ClientProducer; import org.apache.activemq.artemis.api.core.client.ClientSession; import org.apache.activemq.artemis.api.core.client.ClientSessionFactory; import org.apache.activemq.artemis.api.core.client.ServerLocator; import org.apache.activemq.artemis.core.server.ActiveMQServer; import org.apache.activemq.artemis.api.core.RoutingType; import org.apache.activemq.artemis.tests.util.ActiveMQTestBase; import org.junit.Before; import org.junit.Test; /** * A simple test-case used for documentation purposes. */ public class SimpleTest extends ActiveMQTestBase { protected ActiveMQServer server; protected ClientSession session; protected ClientSessionFactory sf; protected ServerLocator locator; @Override @Before public void setUp() throws Exception { super.setUp(); server = createServer(false, createDefaultInVMConfig()); server.start(); locator = createInVMNonHALocator(); sf = createSessionFactory(locator); session = addClientSession(sf.createSession(false, true, true)); } @Test public void simpleTest() throws Exception { final String data = "Simple Text " + UUID.randomUUID().toString(); final String queueName = "simpleQueue"; final String addressName = "simpleAddress"; session.createQueue(addressName, RoutingType.ANYCAST, queueName); ClientProducer producer = session.createProducer(addressName); ClientMessage message = session.createMessage(false); message.getBodyBuffer().writeString(data); producer.send(message); producer.close(); ClientConsumer consumer = session.createConsumer(queueName); session.start(); message = consumer.receive(1000); assertNotNull(message); message.acknowledge(); assertEquals(data, message.getBodyBuffer().readString()); } }
package com.youthchina.mapper; import com.google.common.collect.Lists; import com.youthchina.dao.zhongyang.UserMapper; import com.youthchina.domain.zhongyang.Gender; import com.youthchina.domain.zhongyang.Role; import com.youthchina.domain.zhongyang.User; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.transaction.annotation.Transactional; import java.sql.Timestamp; import java.util.List; /** * Created by zhongyangwu on 11/12/18. */ @RunWith(SpringRunner.class) @SpringBootTest @Transactional public class UserMapperTest { @Autowired private UserMapper userMapper; @Test public void testGetUser() { User user = userMapper.findOne(2); Assert.assertEquals("Admin2", user.getFirstName()); Assert.assertEquals(true, user.getHired()); Assert.assertEquals(true, user.getMailVerified()); Assert.assertEquals("1970-01-01 00:00:00.0", user.getDateOfBirth().toString()); } @Test public void testInsert() { User user = new User(); user.setPassword("sldjflskjlksf"); user.setAvatarUrl(""); user.setEmail("test@test.com"); user.setPhonenumber("12321312334"); user.setFirstName("Test"); user.setLastName("test"); user.setRegisterTime(Timestamp.valueOf("2018-10-11 11:11:11")); user.setGender(Gender.MALE); user.setHired(false); user.setRole(Role.APPLICANT); userMapper.insert(user); Assert.assertNotNull(user.getId()); User createdUser = userMapper.findOne(user.getId()); Assert.assertNotNull(createdUser); Assert.assertEquals(createdUser.getEmail(), user.getEmail()); } @Test public void testDeleteUser() { User user = userMapper.findOne(2); Assert.assertNotNull(user); userMapper.delete(2); user = userMapper.findOne(2); Assert.assertNull(user); } @Test public void testUpdateUser() { User user = userMapper.findOne(3); Assert.assertNotNull(user); Assert.assertNotNull(user.getEmail()); userMapper.update(user); user = userMapper.findOne(3); } @Test public void testCanRegister() { User user = new User(); user.setPassword("sldjflskjlksf"); user.setAvatarUrl(""); user.setEmail("testNew!@test.com"); user.setPhonenumber("00000011112222"); user.setFirstName("Test"); user.setRegisterTime(Timestamp.valueOf("2018-10-11 11:11:11")); user.setGender(Gender.MALE); user.setRole(Role.APPLICANT); Assert.assertTrue(userMapper.canRegister(user)); } @Test public void testGetRoles() { List<Role> roles = userMapper.getRoles(1); Assert.assertTrue(roles.size() != 0); } @Test public void testSetRoles() { List<Role> roles = Lists.newArrayList(Role.HR, Role.ADMIN); userMapper.setRole(9, roles); } }
/* * 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 pe.gob.onpe.adan.service.Adan.impl; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import pe.gob.onpe.adan.dao.adan.ReporteDao; import pe.gob.onpe.adan.helper.Filtro; import pe.gob.onpe.adan.model.adan.Reporte; import pe.gob.onpe.adan.service.Adan.ReporteService; /** * * @author marrisueno */ @Service("reporteService") public class ReporteServiceImpl implements ReporteService{ @Autowired private ReporteDao dao; @Override public Reporte findById(int id) { return dao.findById(id); } @Override public List<Reporte> findAllReporte() { return dao.findAllReporte(); } @Override public List execute(String sql, Filtro filter, String url) { return dao.execute(sql, filter, url); } @Override public Reporte findByCodigo(String codigo){ return dao.findByCodigo(codigo); } @Override public List execute(String sql, String url) { return dao.execute(sql, url); } }
package zystudio.cases.prepare; /** * * 这个我得看看java编程思想关于异常那边了..,各种异常 的理解有待升华 */ public class CaseForRuntimeException { }
package org.leandropadua.knockknock; import static org.junit.Assert.*; import org.junit.*; import org.leandropadua.knockknock.controllers.TriangleTypeController; import org.leandropadua.knockknock.models.TriangleIdentifier; public class TriangleTypeTest { private TriangleTypeController triangleType = new TriangleTypeController(); @Test public void invalidTriangle() { int a = 1; int b = 2; int c = 3; String expectedType = TriangleIdentifier.INVALID_TRIANGLE; assertEquals(expectedType, triangleType.getTriangleType(a, b, c)); } @Test public void equilateralTriangle() { int a = 2; int b = 2; int c = 2; String expectedType = TriangleIdentifier.EQUILATERAL_TRIANGLE; assertEquals(expectedType, triangleType.getTriangleType(a, b, c)); } @Test public void isoscelesTriangle() { int a = 2; int b = 2; int c = 3; String expectedType = TriangleIdentifier.ISOSCELES_TRIANGLE; assertEquals(expectedType, triangleType.getTriangleType(a, b, c)); } @Test public void scaleneTriangle() { int a = 4; int b = 2; int c = 3; String expectedType = TriangleIdentifier.SCALENE_TRIANGLE; assertEquals(expectedType, triangleType.getTriangleType(a, b, c)); } }
package com.adm.utils.uft; import com.atlassian.bamboo.build.logger.BuildLogger; import com.atlassian.bamboo.task.TaskContext; import com.atlassian.bamboo.task.TaskResult; import com.atlassian.bamboo.task.TaskResultBuilder; public final class TaskUtils { private TaskUtils() { } /** * Add the error message in the logs when an exception occurs * * @param exception * @param buildLogger * @param taskContext * @return TaskResult object */ public static TaskResult logErrorMessage(final Exception exception, final BuildLogger buildLogger, final TaskContext taskContext) { buildLogger.addErrorLogEntry(exception.getMessage(), exception); return TaskResultBuilder.newBuilder(taskContext).failedWithError().build(); } public static TaskResult logErrorMessage(final String errorMessage, final BuildLogger buildLogger, final TaskContext taskContext) { buildLogger.addErrorLogEntry(errorMessage); return TaskResultBuilder.newBuilder(taskContext).failedWithError().build(); } }
package com.ytt.springcoredemo.config.datasource; import com.ytt.springcoredemo.dao.handler.OrderStateTypeHandler; import org.apache.ibatis.session.SqlSessionFactory; import org.mybatis.spring.SqlSessionFactoryBean; import org.mybatis.spring.SqlSessionTemplate; import org.mybatis.spring.annotation.MapperScan; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Primary; import org.springframework.core.io.support.PathMatchingResourcePatternResolver; import javax.sql.DataSource; @Configuration @MapperScan(basePackages = "com.ytt.springcoredemo.dao.mapper.base", sqlSessionFactoryRef = "baseSqlSessionFactory") public class BaseDataSourceConfig { // @Bean(name = "test1DataSource") // @ConfigurationProperties(prefix = "spring.datasource.spring") // @Primary // public DataSource testDataSource() { // return DataSourceBuilder.create().build(); // } @Bean(name = "baseSqlSessionFactory") @Primary public SqlSessionFactory sqlSessionFactory(@Qualifier("baseDataSource") DataSource dataSource) throws Exception { SqlSessionFactoryBean bean = new SqlSessionFactoryBean(); bean.setDataSource(dataSource); bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapping/base/*.xml")); return bean.getObject(); } // @Bean(name = "test1DataSource") // @Primary // public DataSource testDataSource(DBConfig1 config1) { // MysqlXADataSource mysqlXADataSource=new MysqlXADataSource(); // mysqlXADataSource.setUrl(config1.getJdbcUrl()); // mysqlXADataSource.setPassword(config1.getPassword()); // mysqlXADataSource.setUser(config1.getUsername()); // // AtomikosDataSourceBean atomikosDataSourceBean=new AtomikosDataSourceBean(); // atomikosDataSourceBean.setXaDataSource(mysqlXADataSource); // atomikosDataSourceBean.setUniqueResourceName("test1Datasource"); // return atomikosDataSourceBean; // // } // @Bean(name = "test1TransactionManager") // @Primary // public DataSourceTransactionManager testTransactionManager(@Qualifier("test1DataSource") DataSource dataSource) { // return new DataSourceTransactionManager(dataSource); // } @Bean(name = "baseSqlSessionTemplate") @Primary public SqlSessionTemplate sqlSessionTemplate( @Qualifier("baseSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception { return new SqlSessionTemplate(sqlSessionFactory); } }
/* * 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 bongden; import com.mysql.jdbc.PreparedStatement; import java.net.URL; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ResourceBundle; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.control.Alert; import javafx.scene.control.Label; import javafx.scene.control.PasswordField; import javafx.scene.control.TableColumn; import javafx.scene.control.TextField; import javafx.scene.control.TableView; import javafx.scene.control.cell.PropertyValueFactory; import javafx.scene.input.MouseEvent; /** * FXML Controller class * * @author DLC */ public class AdminController implements Initializable { /** * Initializes the controller class. */ @FXML private Label lblidad; @FXML private TextField txtTt; @FXML private TextField txtTsdt; @FXML private TextField txtTn; @FXML private TextField txtTk; @FXML private TextField txtMk; @FXML private TextField txtId; @FXML private TextField txtIdad; private PasswordField psMkc; private PasswordField psMkm; @FXML private TableView<User> tabShow; @FXML public TableColumn<User, Integer> colId; @FXML public TableColumn<User, String> colTenNv; @FXML public TableColumn<User, String> colTk; @FXML public TableColumn<User, String> colMk; @FXML public TableColumn<User, Integer> colSodt; @FXML public TableColumn<User, Integer> colSoNhan; @FXML public TableColumn<User, Integer> colIdad; private PasswordField psNl; @FXML private Label lblTt; @FXML private Label lblTen; private Label lblTt1; @FXML private Label lblSdt; @FXML private Label lblSn; private Connection con; private Statement st; private ResultSet rs; public ObservableList<User> data; @FXML private Label lblTen1; @Override public void initialize(URL url, ResourceBundle rb) { connection c = new connection(); Connection connect = c.dbConnect(); data = FXCollections.observableArrayList(); setCelltable(); loadData(); setCellValueFromTable(); } @FXML public void ThemnvClick() throws SQLException { connection c = new connection(); Connection connect = c.dbConnect(); try { String sql = "INSERT INTO `nguoivan`(`tenNv`, `soDt`, `soNhan`,`tenTk`,`matKhau`,`idAd`) VALUES ('" + txtTt.getText() + "','" + txtTsdt.getText() + "','" + txtTn.getText() + "','" + txtTk.getText() + "','" + txtMk.getText() + "','" + txtIdad.getText() + "')"; st = connect.createStatement(); st.executeUpdate(sql); lblTt.setText("Thêm thành công"); System.out.println("ag"); setCelltable(); loadData(); } catch (Exception e) { lblTt.setText("Nhập đầy đủ thông tin"); System.out.println("error " + e); } } public void setCelltable() { try { colId.setCellValueFactory(new PropertyValueFactory<User, Integer>("id")); colTenNv.setCellValueFactory(new PropertyValueFactory<User, String>("tenNv")); colSodt.setCellValueFactory(new PropertyValueFactory<User, Integer>("soDt")); colSoNhan.setCellValueFactory(new PropertyValueFactory<User, Integer>("soNhan")); colTk.setCellValueFactory(new PropertyValueFactory<User, String>("tenTk")); colMk.setCellValueFactory(new PropertyValueFactory<User, String>("matKhau")); colIdad.setCellValueFactory(new PropertyValueFactory<User, Integer>("idad")); tabShow.setItems(data); } catch (Exception e) { System.out.println("loi1256" + e); } } public void loadData() { data.clear(); try { connection c = new connection(); Connection connect = c.dbConnect(); st = connect.createStatement(); rs = st.executeQuery("SELECT * FROM `nguoivan`"); while (rs.next()) { int id = rs.getInt("idNv"); int sodt = rs.getInt("soDt"); int sonhan = rs.getInt("soNhan"); String tennv = rs.getString("tenNv"); String tentk=rs.getString("tenTk"); String matkhau=rs.getString("matKhau"); int idad= rs.getInt("idAd"); data.add(new User(id, sodt, sonhan, tennv, tentk, matkhau,idad)); } } catch (Exception e) { System.out.println("loi" + e); } tabShow.setItems(data); } public void deleteData(ActionEvent event) { String sql = "DELETE FROM `nguoivan` WHERE idNv='" + txtId.getText() + "'"; try { connection c = new connection(); Connection connect = c.dbConnect(); st = connect.createStatement(); st.executeUpdate(sql); lblTt.setText("Xóa thành công"); loadData(); clearTxt(); } catch (Exception e) { } } @FXML public void updateData(ActionEvent event) { try { connection c = new connection(); Connection connect = c.dbConnect(); String sql = "UPDATE `nguoivan` SET tenNv='" + txtTt.getText() + "', soDt='" + txtTsdt.getText() + "',soNhan='" + txtTn.getText() + "',tenTk='" + txtTk.getText() + "',matKhau='" + txtMk.getText() + "',idAd='" + txtIdad.getText() +"'WHERE idNv='" + txtId.getText() + "'"; st = connect.createStatement(); st.executeUpdate(sql); if (st.executeUpdate(sql) == 1) { lblTt.setText("Sửa thành công"); setCelltable(); loadData(); } } catch (Exception e) { System.out.println("error 223" + e); } } public void setCellValueFromTable() { tabShow.setOnMouseClicked(new EventHandler<MouseEvent>() { @Override public void handle(MouseEvent event) { try { User us = tabShow.getItems().get(tabShow.getSelectionModel().getSelectedIndex()); txtTt.setText(us.getTenNv()); txtTsdt.setText(String.valueOf(us.getSoDt())); txtTn.setText(String.valueOf(us.getSoNhan())); txtId.setText(String.valueOf(us.getId())); txtTk.setText(us.getTenTk()); txtMk.setText(us.getMatKhau()); txtIdad.setText(String.valueOf(us.getIdad())); } catch (Exception e) { System.out.println("loixaj"+e); } } }); } @FXML public void clearTxt() { txtTn.clear(); txtTsdt.clear(); txtId.clear(); txtTt.clear(); txtMk.clear(); txtTk.clear(); txtIdad.clear(); } public void clearPass() { psMkc.clear(); psMkm.clear(); psNl.clear(); } public void changePass() { connection c = new connection(); Connection connect = c.dbConnect(); String mkc=psMkc.getText(); String mkm=psMkm.getText(); String nl=psNl.getText(); try { st=connect.createStatement(); if(mkm.equals(nl)){ st.executeUpdate("UPDATE `admin` SET mKhau='" + psMkm.getText() + "'WHERE idAd=?"); lblTt1.setText("Đổi mật khẩu thành công"); } } catch (Exception e) { System.out.println("error12412"+e); } } public void getAd(String ad){ this.lblidad.setText(ad); } }
package LeetCode.ArraysAndStrings; public class MultiplyStrings { public String multiply(String num1, String num2) { int m = num1.length(); int n = num2.length(); int[] res = new int[m+n]; for(int i = m-1; i >=0; i--) { for(int j = n-1; j >= 0; j--) { int p1 = i+j; int p2 = i+j+1; int mul = (num1.charAt(i) - '0') * (num2.charAt(j) - '0'); int sum = mul + res[p2]; res[p1] += sum / 10; res[p2] = sum % 10; } } StringBuilder sb = new StringBuilder(); for (int i = 0; i < m+n; i++) { if(!(sb.length() == 0 && res[i] ==0)) { sb.append(res[i]); } } return sb.length() == 0 ? "0" : sb.toString(); } public static void main(String[] args) { MultiplyStrings m = new MultiplyStrings(); System.out.println(m.multiply("35", "22")); } }
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2017.01.28 at 02:11:12 PM CST // package org.mesa.xml.b2mml; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlSchemaType; import javax.xml.bind.annotation.XmlSeeAlso; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.XmlValue; import javax.xml.bind.annotation.adapters.CollapsedStringAdapter; import javax.xml.bind.annotation.adapters.NormalizedStringAdapter; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; /** * <p>Java class for AnyGenericValueType complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="AnyGenericValueType"> * &lt;simpleContent> * &lt;extension base="&lt;http://www.w3.org/2001/XMLSchema>string"> * &lt;attribute name="currencyID" type="{http://www.w3.org/2001/XMLSchema}normalizedString" /> * &lt;attribute name="currencyCodeListVersionID" type="{http://www.w3.org/2001/XMLSchema}normalizedString" /> * &lt;attribute name="encodingCode" type="{http://www.w3.org/2001/XMLSchema}normalizedString" /> * &lt;attribute name="format" type="{http://www.w3.org/2001/XMLSchema}string" /> * &lt;attribute name="characterSetCode" type="{http://www.w3.org/2001/XMLSchema}normalizedString" /> * &lt;attribute name="listID" type="{http://www.w3.org/2001/XMLSchema}normalizedString" /> * &lt;attribute name="listAgencyID" type="{http://www.w3.org/2001/XMLSchema}normalizedString" /> * &lt;attribute name="listAgencyName" type="{http://www.w3.org/2001/XMLSchema}string" /> * &lt;attribute name="listName" type="{http://www.w3.org/2001/XMLSchema}string" /> * &lt;attribute name="listVersionID" type="{http://www.w3.org/2001/XMLSchema}normalizedString" /> * &lt;attribute name="languageID" type="{http://www.w3.org/2001/XMLSchema}language" /> * &lt;attribute name="languageLocaleID" type="{http://www.w3.org/2001/XMLSchema}normalizedString" /> * &lt;attribute name="listURI" type="{http://www.w3.org/2001/XMLSchema}anyURI" /> * &lt;attribute name="listSchemaURI" type="{http://www.w3.org/2001/XMLSchema}anyURI" /> * &lt;attribute name="mimeCode" type="{http://www.w3.org/2001/XMLSchema}normalizedString" /> * &lt;attribute name="name" type="{http://www.w3.org/2001/XMLSchema}string" /> * &lt;attribute name="schemaID" type="{http://www.w3.org/2001/XMLSchema}normalizedString" /> * &lt;attribute name="schemaName" type="{http://www.w3.org/2001/XMLSchema}string" /> * &lt;attribute name="schemaAgencyID" type="{http://www.w3.org/2001/XMLSchema}normalizedString" /> * &lt;attribute name="schemaAgencyName" type="{http://www.w3.org/2001/XMLSchema}string" /> * &lt;attribute name="schemaVersionID" type="{http://www.w3.org/2001/XMLSchema}normalizedString" /> * &lt;attribute name="schemaDataURI" type="{http://www.w3.org/2001/XMLSchema}anyURI" /> * &lt;attribute name="schemaURI" type="{http://www.w3.org/2001/XMLSchema}anyURI" /> * &lt;attribute name="unitCode" type="{http://www.w3.org/2001/XMLSchema}normalizedString" /> * &lt;attribute name="unitCodeListID" type="{http://www.w3.org/2001/XMLSchema}normalizedString" /> * &lt;attribute name="unitCodeListAgencyID" type="{http://www.w3.org/2001/XMLSchema}normalizedString" /> * &lt;attribute name="unitCodeListAgencyName" type="{http://www.w3.org/2001/XMLSchema}string" /> * &lt;attribute name="unitCodeListVersionID" type="{http://www.w3.org/2001/XMLSchema}normalizedString" /> * &lt;attribute name="filename" type="{http://www.w3.org/2001/XMLSchema}string" /> * &lt;attribute name="uri" type="{http://www.w3.org/2001/XMLSchema}anyURI" /> * &lt;/extension> * &lt;/simpleContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "AnyGenericValueType", propOrder = { "value" }) @XmlSeeAlso({ ValueStringType.class, QuantityStringType.class }) public class AnyGenericValueType { @XmlValue protected String value; @XmlAttribute(name = "currencyID") @XmlJavaTypeAdapter(NormalizedStringAdapter.class) @XmlSchemaType(name = "normalizedString") protected String currencyID; @XmlAttribute(name = "currencyCodeListVersionID") @XmlJavaTypeAdapter(NormalizedStringAdapter.class) @XmlSchemaType(name = "normalizedString") protected String currencyCodeListVersionID; @XmlAttribute(name = "encodingCode") @XmlJavaTypeAdapter(NormalizedStringAdapter.class) @XmlSchemaType(name = "normalizedString") protected String encodingCode; @XmlAttribute(name = "format") protected String format; @XmlAttribute(name = "characterSetCode") @XmlJavaTypeAdapter(NormalizedStringAdapter.class) @XmlSchemaType(name = "normalizedString") protected String characterSetCode; @XmlAttribute(name = "listID") @XmlJavaTypeAdapter(NormalizedStringAdapter.class) @XmlSchemaType(name = "normalizedString") protected String listID; @XmlAttribute(name = "listAgencyID") @XmlJavaTypeAdapter(NormalizedStringAdapter.class) @XmlSchemaType(name = "normalizedString") protected String listAgencyID; @XmlAttribute(name = "listAgencyName") protected String listAgencyName; @XmlAttribute(name = "listName") protected String listName; @XmlAttribute(name = "listVersionID") @XmlJavaTypeAdapter(NormalizedStringAdapter.class) @XmlSchemaType(name = "normalizedString") protected String listVersionID; @XmlAttribute(name = "languageID") @XmlJavaTypeAdapter(CollapsedStringAdapter.class) @XmlSchemaType(name = "language") protected String languageID; @XmlAttribute(name = "languageLocaleID") @XmlJavaTypeAdapter(NormalizedStringAdapter.class) @XmlSchemaType(name = "normalizedString") protected String languageLocaleID; @XmlAttribute(name = "listURI") @XmlSchemaType(name = "anyURI") protected String listURI; @XmlAttribute(name = "listSchemaURI") @XmlSchemaType(name = "anyURI") protected String listSchemaURI; @XmlAttribute(name = "mimeCode") @XmlJavaTypeAdapter(NormalizedStringAdapter.class) @XmlSchemaType(name = "normalizedString") protected String mimeCode; @XmlAttribute(name = "name") protected String name; @XmlAttribute(name = "schemaID") @XmlJavaTypeAdapter(NormalizedStringAdapter.class) @XmlSchemaType(name = "normalizedString") protected String schemaID; @XmlAttribute(name = "schemaName") protected String schemaName; @XmlAttribute(name = "schemaAgencyID") @XmlJavaTypeAdapter(NormalizedStringAdapter.class) @XmlSchemaType(name = "normalizedString") protected String schemaAgencyID; @XmlAttribute(name = "schemaAgencyName") protected String schemaAgencyName; @XmlAttribute(name = "schemaVersionID") @XmlJavaTypeAdapter(NormalizedStringAdapter.class) @XmlSchemaType(name = "normalizedString") protected String schemaVersionID; @XmlAttribute(name = "schemaDataURI") @XmlSchemaType(name = "anyURI") protected String schemaDataURI; @XmlAttribute(name = "schemaURI") @XmlSchemaType(name = "anyURI") protected String schemaURI; @XmlAttribute(name = "unitCode") @XmlJavaTypeAdapter(NormalizedStringAdapter.class) @XmlSchemaType(name = "normalizedString") protected String unitCode; @XmlAttribute(name = "unitCodeListID") @XmlJavaTypeAdapter(NormalizedStringAdapter.class) @XmlSchemaType(name = "normalizedString") protected String unitCodeListID; @XmlAttribute(name = "unitCodeListAgencyID") @XmlJavaTypeAdapter(NormalizedStringAdapter.class) @XmlSchemaType(name = "normalizedString") protected String unitCodeListAgencyID; @XmlAttribute(name = "unitCodeListAgencyName") protected String unitCodeListAgencyName; @XmlAttribute(name = "unitCodeListVersionID") @XmlJavaTypeAdapter(NormalizedStringAdapter.class) @XmlSchemaType(name = "normalizedString") protected String unitCodeListVersionID; @XmlAttribute(name = "filename") protected String filename; @XmlAttribute(name = "uri") @XmlSchemaType(name = "anyURI") protected String uri; /** * Gets the value of the value property. * * @return * possible object is * {@link String } * */ public String getValue() { return value; } /** * Sets the value of the value property. * * @param value * allowed object is * {@link String } * */ public void setValue(String value) { this.value = value; } /** * Gets the value of the currencyID property. * * @return * possible object is * {@link String } * */ public String getCurrencyID() { return currencyID; } /** * Sets the value of the currencyID property. * * @param value * allowed object is * {@link String } * */ public void setCurrencyID(String value) { this.currencyID = value; } /** * Gets the value of the currencyCodeListVersionID property. * * @return * possible object is * {@link String } * */ public String getCurrencyCodeListVersionID() { return currencyCodeListVersionID; } /** * Sets the value of the currencyCodeListVersionID property. * * @param value * allowed object is * {@link String } * */ public void setCurrencyCodeListVersionID(String value) { this.currencyCodeListVersionID = value; } /** * Gets the value of the encodingCode property. * * @return * possible object is * {@link String } * */ public String getEncodingCode() { return encodingCode; } /** * Sets the value of the encodingCode property. * * @param value * allowed object is * {@link String } * */ public void setEncodingCode(String value) { this.encodingCode = value; } /** * Gets the value of the format property. * * @return * possible object is * {@link String } * */ public String getFormat() { return format; } /** * Sets the value of the format property. * * @param value * allowed object is * {@link String } * */ public void setFormat(String value) { this.format = value; } /** * Gets the value of the characterSetCode property. * * @return * possible object is * {@link String } * */ public String getCharacterSetCode() { return characterSetCode; } /** * Sets the value of the characterSetCode property. * * @param value * allowed object is * {@link String } * */ public void setCharacterSetCode(String value) { this.characterSetCode = value; } /** * Gets the value of the listID property. * * @return * possible object is * {@link String } * */ public String getListID() { return listID; } /** * Sets the value of the listID property. * * @param value * allowed object is * {@link String } * */ public void setListID(String value) { this.listID = value; } /** * Gets the value of the listAgencyID property. * * @return * possible object is * {@link String } * */ public String getListAgencyID() { return listAgencyID; } /** * Sets the value of the listAgencyID property. * * @param value * allowed object is * {@link String } * */ public void setListAgencyID(String value) { this.listAgencyID = value; } /** * Gets the value of the listAgencyName property. * * @return * possible object is * {@link String } * */ public String getListAgencyName() { return listAgencyName; } /** * Sets the value of the listAgencyName property. * * @param value * allowed object is * {@link String } * */ public void setListAgencyName(String value) { this.listAgencyName = value; } /** * Gets the value of the listName property. * * @return * possible object is * {@link String } * */ public String getListName() { return listName; } /** * Sets the value of the listName property. * * @param value * allowed object is * {@link String } * */ public void setListName(String value) { this.listName = value; } /** * Gets the value of the listVersionID property. * * @return * possible object is * {@link String } * */ public String getListVersionID() { return listVersionID; } /** * Sets the value of the listVersionID property. * * @param value * allowed object is * {@link String } * */ public void setListVersionID(String value) { this.listVersionID = value; } /** * Gets the value of the languageID property. * * @return * possible object is * {@link String } * */ public String getLanguageID() { return languageID; } /** * Sets the value of the languageID property. * * @param value * allowed object is * {@link String } * */ public void setLanguageID(String value) { this.languageID = value; } /** * Gets the value of the languageLocaleID property. * * @return * possible object is * {@link String } * */ public String getLanguageLocaleID() { return languageLocaleID; } /** * Sets the value of the languageLocaleID property. * * @param value * allowed object is * {@link String } * */ public void setLanguageLocaleID(String value) { this.languageLocaleID = value; } /** * Gets the value of the listURI property. * * @return * possible object is * {@link String } * */ public String getListURI() { return listURI; } /** * Sets the value of the listURI property. * * @param value * allowed object is * {@link String } * */ public void setListURI(String value) { this.listURI = value; } /** * Gets the value of the listSchemaURI property. * * @return * possible object is * {@link String } * */ public String getListSchemaURI() { return listSchemaURI; } /** * Sets the value of the listSchemaURI property. * * @param value * allowed object is * {@link String } * */ public void setListSchemaURI(String value) { this.listSchemaURI = value; } /** * Gets the value of the mimeCode property. * * @return * possible object is * {@link String } * */ public String getMimeCode() { return mimeCode; } /** * Sets the value of the mimeCode property. * * @param value * allowed object is * {@link String } * */ public void setMimeCode(String value) { this.mimeCode = value; } /** * Gets the value of the name property. * * @return * possible object is * {@link String } * */ public String getName() { return name; } /** * Sets the value of the name property. * * @param value * allowed object is * {@link String } * */ public void setName(String value) { this.name = value; } /** * Gets the value of the schemaID property. * * @return * possible object is * {@link String } * */ public String getSchemaID() { return schemaID; } /** * Sets the value of the schemaID property. * * @param value * allowed object is * {@link String } * */ public void setSchemaID(String value) { this.schemaID = value; } /** * Gets the value of the schemaName property. * * @return * possible object is * {@link String } * */ public String getSchemaName() { return schemaName; } /** * Sets the value of the schemaName property. * * @param value * allowed object is * {@link String } * */ public void setSchemaName(String value) { this.schemaName = value; } /** * Gets the value of the schemaAgencyID property. * * @return * possible object is * {@link String } * */ public String getSchemaAgencyID() { return schemaAgencyID; } /** * Sets the value of the schemaAgencyID property. * * @param value * allowed object is * {@link String } * */ public void setSchemaAgencyID(String value) { this.schemaAgencyID = value; } /** * Gets the value of the schemaAgencyName property. * * @return * possible object is * {@link String } * */ public String getSchemaAgencyName() { return schemaAgencyName; } /** * Sets the value of the schemaAgencyName property. * * @param value * allowed object is * {@link String } * */ public void setSchemaAgencyName(String value) { this.schemaAgencyName = value; } /** * Gets the value of the schemaVersionID property. * * @return * possible object is * {@link String } * */ public String getSchemaVersionID() { return schemaVersionID; } /** * Sets the value of the schemaVersionID property. * * @param value * allowed object is * {@link String } * */ public void setSchemaVersionID(String value) { this.schemaVersionID = value; } /** * Gets the value of the schemaDataURI property. * * @return * possible object is * {@link String } * */ public String getSchemaDataURI() { return schemaDataURI; } /** * Sets the value of the schemaDataURI property. * * @param value * allowed object is * {@link String } * */ public void setSchemaDataURI(String value) { this.schemaDataURI = value; } /** * Gets the value of the schemaURI property. * * @return * possible object is * {@link String } * */ public String getSchemaURI() { return schemaURI; } /** * Sets the value of the schemaURI property. * * @param value * allowed object is * {@link String } * */ public void setSchemaURI(String value) { this.schemaURI = value; } /** * Gets the value of the unitCode property. * * @return * possible object is * {@link String } * */ public String getUnitCode() { return unitCode; } /** * Sets the value of the unitCode property. * * @param value * allowed object is * {@link String } * */ public void setUnitCode(String value) { this.unitCode = value; } /** * Gets the value of the unitCodeListID property. * * @return * possible object is * {@link String } * */ public String getUnitCodeListID() { return unitCodeListID; } /** * Sets the value of the unitCodeListID property. * * @param value * allowed object is * {@link String } * */ public void setUnitCodeListID(String value) { this.unitCodeListID = value; } /** * Gets the value of the unitCodeListAgencyID property. * * @return * possible object is * {@link String } * */ public String getUnitCodeListAgencyID() { return unitCodeListAgencyID; } /** * Sets the value of the unitCodeListAgencyID property. * * @param value * allowed object is * {@link String } * */ public void setUnitCodeListAgencyID(String value) { this.unitCodeListAgencyID = value; } /** * Gets the value of the unitCodeListAgencyName property. * * @return * possible object is * {@link String } * */ public String getUnitCodeListAgencyName() { return unitCodeListAgencyName; } /** * Sets the value of the unitCodeListAgencyName property. * * @param value * allowed object is * {@link String } * */ public void setUnitCodeListAgencyName(String value) { this.unitCodeListAgencyName = value; } /** * Gets the value of the unitCodeListVersionID property. * * @return * possible object is * {@link String } * */ public String getUnitCodeListVersionID() { return unitCodeListVersionID; } /** * Sets the value of the unitCodeListVersionID property. * * @param value * allowed object is * {@link String } * */ public void setUnitCodeListVersionID(String value) { this.unitCodeListVersionID = value; } /** * Gets the value of the filename property. * * @return * possible object is * {@link String } * */ public String getFilename() { return filename; } /** * Sets the value of the filename property. * * @param value * allowed object is * {@link String } * */ public void setFilename(String value) { this.filename = value; } /** * Gets the value of the uri property. * * @return * possible object is * {@link String } * */ public String getUri() { return uri; } /** * Sets the value of the uri property. * * @param value * allowed object is * {@link String } * */ public void setUri(String value) { this.uri = value; } }
package com.theIronYard.factory; import com.theIronYard.repository.AnimalBreedRepository; import com.theIronYard.repository.AnimalRepository; import com.theIronYard.repository.AnimalTypeRepository; import com.theIronYard.repository.NoteRepository; import com.theIronYard.service.AnimalService; import java.io.IOException; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; /** * Created by chris on 9/15/16. */ public class ServiceFactory { // the JDBC url private static String jdbcUrl = "jdbc:postgresql://localhost:5432/animal2"; // the private animalService private static AnimalService animalService; /** * This method returns a single animalService that is shared among anything * that uses this method to load it. * @return AnimalService * @throws ClassNotFoundException * @throws SQLException * @throws IOException */ public static AnimalService getAnimalService() throws ClassNotFoundException, SQLException, IOException { // if the animal service hasn't been created yet, then we need to create it. if(ServiceFactory.animalService == null){ Class.forName("org.postgresql.Driver"); Connection connection = DriverManager.getConnection(jdbcUrl); AnimalRepository animalRepository = new AnimalRepository(connection); AnimalTypeRepository typeRepository = new AnimalTypeRepository(connection); AnimalBreedRepository breedRepository = new AnimalBreedRepository(connection); NoteRepository noteRepository = new NoteRepository(connection); ServiceFactory.animalService = new AnimalService( animalRepository, typeRepository, breedRepository, noteRepository); } return animalService; } }
package com.tencent.mm.plugin.exdevice.model; import com.tencent.mm.ab.b; import com.tencent.mm.ab.e; import com.tencent.mm.ab.l; import com.tencent.mm.network.k; import com.tencent.mm.network.q; import com.tencent.mm.sdk.platformtools.x; public final class p extends l implements k { public b diG; private e diJ; public final void a(int i, int i2, int i3, String str, q qVar, byte[] bArr) { x.i("MicroMsg.exdevice.NetSceneGetHardDeviceHelpUrl", "onGYNetEnd netId = " + i + " errType = " + i2 + " errCode = " + i3 + str); this.diJ.a(i2, i3, str, this); } public final int getType() { return 1719; } public final int a(com.tencent.mm.network.e eVar, e eVar2) { this.diJ = eVar2; return a(eVar, this.diG, this); } }
package com.myflappybird.control; import com.myflappybird.dto.GameDto; public class GameControl { /** * 数据传输层 */ GameDto dto; /** * 构造方法 */ public GameControl(GameDto dto) { this.dto = dto; } /** * 游戏开始 */ public void gameStart() { this.dto.setGamestart(true); } /** * 调用逻辑层小鸟向上飞的方法 */ public void birdUp() { if (this.dto.isBirdDead()) { return; } this.dto.setSpeed(-22.3); this.dto.getBird().flyMusic(); } /** * 设置游戏暂停为true */ public void pause() { this.dto.setPause(!this.dto.isPause()); } }
package com.example.test.blooth; import java.util.Calendar; import java.util.TimeZone; public abstract class Bong { abstract public Object getResult(String data); public String getStrTimeForHex(long time) { TimeZone CHINA_TIMEZONE = TimeZone.getTimeZone("GMT+08:00"); Calendar calendar = Calendar.getInstance(); calendar.setTimeInMillis(time); calendar.setTimeZone(CHINA_TIMEZONE); int year = calendar.get(Calendar.YEAR) % 100;// 只取2位年份 int month = calendar.get(Calendar.MONTH) + 1; int day = calendar.get(Calendar.DAY_OF_MONTH); int hour = calendar.get(Calendar.HOUR_OF_DAY); int minute = calendar.get(Calendar.MINUTE); return (year > 0xf ? "" : "0") + Integer.toHexString(year) + // 只取2位年份 (month > 0xf ? "" : "0") + Integer.toHexString(month) + (day > 0xf ? "" : "0") + Integer.toHexString(day) + (hour > 0xf ? "" : "0") + Integer.toHexString(hour) + (minute > 0xf ? "" : "0") + Integer.toHexString(minute); } }
package com.google.android.exoplayer2.c.c; import com.tencent.map.lib.mapstructure.MapRouteSectionWithName; import java.util.Arrays; final class i$a { static final byte[] anw = new byte[]{(byte) 0, (byte) 0, (byte) 1}; boolean anx; public int any; public byte[] data = new byte[MapRouteSectionWithName.kMaxRoadNameLength]; public int length; public final void d(byte[] bArr, int i, int i2) { if (this.anx) { int i3 = i2 - i; if (this.data.length < this.length + i3) { this.data = Arrays.copyOf(this.data, (this.length + i3) * 2); } System.arraycopy(bArr, i, this.data, this.length, i3); this.length = i3 + this.length; } } }
/** * Билтер для построения стратеги сортировки * * По-умолчанию выбраны стратегия и компаратор необходимые для задания */ import java.util.Comparator; public class SortStrategyBuilder { private SortStrategy strategy = new BubbleSort(); private Comparator<Book> comparator = new DefaultComparator(); private SortStrategyBuilder() { } public static SortStrategyBuilder newStrategy() { return new SortStrategyBuilder(); } public SortStrategyBuilder useNoSort() { this.strategy = new NoSort(); return this; } public SortStrategyBuilder useBubbleSort() { this.strategy = new BubbleSort(); return this; } public SortStrategyBuilder useDefaultComparator() { this.comparator = new DefaultComparator(); return this; } public SortStrategyBuilder useBaseComparator() { this.comparator = new BaseComparator(); return this; } public SortStrategyBuilder useFullComparator() { this.comparator = new FullComparator(); return this; } public SortStrategy buildStrategy() { strategy.setComparator(comparator); return strategy; } }
package org.smxknife.easypoi.view; import cn.afterturn.easypoi.excel.entity.ExportParams; import lombok.Getter; import lombok.Setter; import java.util.List; /** * @author smxknife * 2019/10/25 */ @Getter @Setter public class ExportView { private ExportParams exportParams; private List<?> dataList; private Class<?> cls; public ExportView(Builder builder) { this.exportParams = builder.exportParams; this.dataList = builder.dataList; this.cls = builder.cls; } public static class Builder { public ExportParams exportParams; public List<?> dataList; public Class<?> cls; public Builder exportParams(ExportParams exportParams) { this.exportParams = exportParams; return this; } public Builder dataList(List<?> dataList) { this.dataList = dataList; return this; } public Builder cls(Class<?> cls) { this.cls = cls; return this; } public ExportView create() { return new ExportView(this); } } }
package com.wangyi.wangyi_yanxuan.mapper; import com.sun.org.apache.xpath.internal.operations.Or; import com.wangyi.wangyi_yanxuan.domain.Order; import org.apache.ibatis.annotations.Param; import org.apache.ibatis.annotations.ResultType; import org.apache.ibatis.annotations.Select; import java.util.List; import java.util.Map; public interface OrderMapper { @Select("select * from t_order limit #{currPage,jdbcType=INTEGER},#{limit,jdbcType=INTEGER}") @ResultType(Order.class) List<Order> selectAllPage(@Param("currPage") int currPage,@Param("limit") int limit); @Select("select COUNT(1) from t_order") @ResultType(Integer.class) int countNumber(); }
package com.orca.util; import java.io.BufferedReader; import java.io.File; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import org.apache.commons.io.IOUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; public class FileUtils { protected Log log = LogFactory.getLog(this.getClass()); private static final String newLine = "\r\n"; public String readFile(File file) throws IOException { StringBuilder builder = new StringBuilder(); BufferedReader in = null; try { String string = null; in = new BufferedReader(new FileReader(file)); while ((string = in.readLine()) != null) { builder.append(string + newLine); } } catch (IOException e) { log.debug("Error reading file " + file.getName() + "......." + e); throw new IOException(e); } finally { IOUtils.closeQuietly(in); } return builder.toString(); } public void writeFile(File file, String string) throws IOException { FileOutputStream stream = null; try { stream = new FileOutputStream(file); stream.write(string.getBytes()); stream.flush(); } catch (IOException e) { log.debug("Error writing " + file.getName() + " to disk...." + e); throw new IOException(e); } finally { IOUtils.closeQuietly(stream); } } }
package dao; import model.Client; import java.sql.SQLException; import java.util.List; public interface ClientDAO { public Client find(int id); public void create(Client p); public void delete(Client p) throws SQLException; public void update(Client p); public List<Client> findAll(); public Client findAll(String key); public int getLastId(); }
package com.ld.baselibrary.util.app; import android.content.Context; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.os.Build; import android.provider.Settings; import com.ld.baselibrary.base.BaseApplication; public class AppVersionUtil { private static Object androidId; //版本名 public static String getVersionName(Context context) { if (getPackageInfo(context) == null) { return ""; } else { return getPackageInfo(context).versionName; } } //版本号 public static int getVersionCode(Context context) { return getPackageInfo(context).versionCode; } //手机厂家 public static String getManufactor() { return Build.MANUFACTURER; } private static PackageInfo getPackageInfo(Context context) { PackageInfo pi = null; try { PackageManager pm = context.getPackageManager(); pi = pm.getPackageInfo(context.getPackageName(), PackageManager.GET_CONFIGURATIONS); return pi; } catch (Exception e) { e.printStackTrace(); } return pi; } public static String getAndroidId() { //android设备唯一标识 String AndroidId = ""; String androidID = Settings.Secure.getString(BaseApplication.getInstance().getContentResolver(), Settings.Secure.ANDROID_ID); AndroidId = androidID + Build.SERIAL; return AndroidId; } }
package ru.otus.api.sessionmanager; public interface DatabaseSession { }
package com.tencent.mm.protocal.c; import f.a.a.b; import f.a.a.c.a; import java.util.LinkedList; public final class aag extends bhp { public anj rFL; public String rFM; public ane rFN; public int result; protected final int a(int i, Object... objArr) { int fS; if (i == 0) { a aVar = (a) objArr[0]; if (this.six == null) { throw new b("Not all required fields were included: BaseResponse"); } if (this.six != null) { aVar.fV(1, this.six.boi()); this.six.a(aVar); } if (this.rFL != null) { aVar.fV(2, this.rFL.boi()); this.rFL.a(aVar); } if (this.rFM != null) { aVar.g(3, this.rFM); } if (this.rFN != null) { aVar.fV(4, this.rFN.boi()); this.rFN.a(aVar); } aVar.fT(5, this.result); return 0; } else if (i == 1) { if (this.six != null) { fS = f.a.a.a.fS(1, this.six.boi()) + 0; } else { fS = 0; } if (this.rFL != null) { fS += f.a.a.a.fS(2, this.rFL.boi()); } if (this.rFM != null) { fS += f.a.a.b.b.a.h(3, this.rFM); } if (this.rFN != null) { fS += f.a.a.a.fS(4, this.rFN.boi()); } return fS + f.a.a.a.fQ(5, this.result); } else if (i == 2) { f.a.a.a.a aVar2 = new f.a.a.a.a((byte[]) objArr[0], unknownTagHandler); for (fS = bhp.a(aVar2); fS > 0; fS = bhp.a(aVar2)) { if (!super.a(aVar2, this, fS)) { aVar2.cJS(); } } if (this.six != null) { return 0; } throw new b("Not all required fields were included: BaseResponse"); } else if (i != 3) { return -1; } else { f.a.a.a.a aVar3 = (f.a.a.a.a) objArr[0]; aag aag = (aag) objArr[1]; int intValue = ((Integer) objArr[2]).intValue(); LinkedList IC; int size; byte[] bArr; f.a.a.a.a aVar4; boolean z; switch (intValue) { case 1: IC = aVar3.IC(intValue); size = IC.size(); for (intValue = 0; intValue < size; intValue++) { bArr = (byte[]) IC.get(intValue); fl flVar = new fl(); aVar4 = new f.a.a.a.a(bArr, unknownTagHandler); for (z = true; z; z = flVar.a(aVar4, flVar, bhp.a(aVar4))) { } aag.six = flVar; } return 0; case 2: IC = aVar3.IC(intValue); size = IC.size(); for (intValue = 0; intValue < size; intValue++) { bArr = (byte[]) IC.get(intValue); anj anj = new anj(); aVar4 = new f.a.a.a.a(bArr, unknownTagHandler); for (z = true; z; z = anj.a(aVar4, anj, bhp.a(aVar4))) { } aag.rFL = anj; } return 0; case 3: aag.rFM = aVar3.vHC.readString(); return 0; case 4: IC = aVar3.IC(intValue); size = IC.size(); for (intValue = 0; intValue < size; intValue++) { bArr = (byte[]) IC.get(intValue); ane ane = new ane(); aVar4 = new f.a.a.a.a(bArr, unknownTagHandler); for (z = true; z; z = ane.a(aVar4, ane, bhp.a(aVar4))) { } aag.rFN = ane; } return 0; case 5: aag.result = aVar3.vHC.rY(); return 0; default: return -1; } } } }
package com.jude.fuad.hackharvard2018v2; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class SplashScreenActivity extends Activity { // Splash screen timer private static int SPLASH_TIME_OUT = 750; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.splash_activity); new Handler().postDelayed(new Runnable() { /* * Showing splash screen with a timer. This will be useful when you * want to show case your app logo / company */ @Override public void run() { // This method will be executed once the timer is over // Start your app main activity String myName = ""; try { BufferedReader reader = new BufferedReader( new InputStreamReader(openFileInput("userInfo"))); String line = reader.readLine(); if(line != null) { myName = line; } } catch (IOException e) { System.out.println("error reading or writing to file"); e.printStackTrace(); } if(myName != "") { Intent i = new Intent(SplashScreenActivity.this, MainActivity.class); startActivity(i); finish(); } else { Intent i = new Intent(SplashScreenActivity.this, NewUserActivity.class); startActivity(i); finish(); } } }, SPLASH_TIME_OUT); } }
package csci152.adt_tests; import csci152.adt.SortedQueue; import csci152.impl.LinkedListSortedQueue; public class Main { public static void main(String[] args) { SortedQueue test = new LinkedListSortedQueue(); for(int i = 90; i>=10; i-=10) { test.insert(i); } print(test); print("Size: " + test.getSize()); try { test.dequeue(); test.dequeue(); test.dequeue(); } catch (Exception ex) { print(ex.getMessage()); } for(int i = 100; i<=900; i+=100) { test.insert(i); } print(test); print("Size: " + test.getSize()); try { test.dequeue(); test.dequeue(); test.dequeue(); test.dequeue(); } catch (Exception ex) { print(ex.getMessage()); } print(test); print("Size: " + test.getSize()); for(int i = 5; i<=915; i+=5) { test.insert(i); } print(test); print("Size: " + test.getSize()); /* A for loop to dequeue all items */ int size = test.getSize(); for(int i = 0; i<size; i++) { try { test.dequeue(); } catch (Exception ex) { print(ex.getMessage()); break; } } print(test); print("Size: " + test.getSize()); /* 3 integers of my choice inserted */ test.insert(123); test.insert(678); test.insert(456); print(test); print("Size: " + test.getSize()); /* Clear the queue and print */ test.clear(); print(test); print("Size: " + test.getSize()); /* Insert 4 more integers */ test.insert(123124); test.insert(123121); test.insert(123126); test.insert(124126); print(test); print("Size: " + test.getSize()); } public static void print(Object msg) { System.out.println(msg); } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package begining.gf4.web.servlet.jaxws; import begining.ws.jaxws.test.client.Test1WS453_Service; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.xml.ws.WebServiceRef; /** * * @author Eiichi Tanaka */ @WebServlet(name = "Test1WSClientServlet453", urlPatterns = {"/Test1WSClient453"}) public class Test1WSClientServlet453 extends HttpServlet { @WebServiceRef(wsdlLocation = "WEB-INF/wsdl/localhost_8080/Test1WS453/Test1WS453.wsdl") private Test1WS453_Service service; /** * Processes requests for both HTTP * <code>GET</code> and * <code>POST</code> methods. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); try { /* TODO output your page here. You may use following sample code. */ out.println("<!DOCTYPE html>"); out.println("<html>"); out.println("<head>"); out.println("<title>Servlet Test1WSClientServlet453</title>"); out.println("</head>"); out.println("<body>"); out.println("<h1>Servlet Test1WSClientServlet453 at " + request.getContextPath() + "</h1>"); out.println(hello("abcdefg")); out.println("</body>"); out.println("</html>"); } finally { out.close(); } } // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code."> /** * Handles the HTTP * <code>GET</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Handles the HTTP * <code>POST</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Returns a short description of the servlet. * * @return a String containing servlet description */ @Override public String getServletInfo() { return "Short description"; }// </editor-fold> /*************************************************************************** * Helloウェブサービスの呼び出し * ※注意 *  「Webサービスクライアント」を新規作成する際、 *  クライアントJavaアーティファクトを生成するパッケージ名をデフォルト *  にしてしまうと、Webサービスを利用するサーブレットで呼び出し時に例外 *  が発生してしまう。(IllegalException - not interface) *  必ずアーティファクトを生成するパッケージ名を指定すること * @param name * @return **************************************************************************/ private String hello(java.lang.String name) { begining.ws.jaxws.test.client.Test1WS453 port = service.getTest1WS453Port(); return port.hello(name); } }
package com.thyssenkrupp.tks.fls.qf.server.qcs.receive.xml.builder; import com.thyssenkrupp.tks.fls.qf.server.qcs.receive.xml.MaterialereignisHeaderType; import com.thyssenkrupp.tks.fls.qf.server.qcs.receive.xml.MaterialstueckType; import com.thyssenkrupp.tks.fls.qf.server.qcs.receive.xml.PlanmaterialdefinitionType; import java.io.StringWriter; import javax.xml.bind.JAXBElement; import javax.xml.bind.JAXBException; import javax.xml.namespace.QName; public class PlanmaterialdefinitionTypeBuilder { public static String marshal(PlanmaterialdefinitionType planmaterialdefinitionType) throws JAXBException { JAXBElement<PlanmaterialdefinitionType> jaxbElement = new JAXBElement<>(new QName("TESTING"), PlanmaterialdefinitionType.class , planmaterialdefinitionType); StringWriter stringWriter = new StringWriter(); return stringWriter.toString(); } private MaterialstueckType material; private MaterialereignisHeaderType header; public PlanmaterialdefinitionTypeBuilder setMaterial(MaterialstueckType value) { this.material = value; return this; } public PlanmaterialdefinitionTypeBuilder setHeader(MaterialereignisHeaderType value) { this.header = value; return this; } public PlanmaterialdefinitionType build() { PlanmaterialdefinitionType result = new PlanmaterialdefinitionType(); result.setMaterial(material); result.setHeader(header); return result; } }
package cdn; import java.io.IOException; import java.lang.Thread.UncaughtExceptionHandler; import java.net.InetAddress; import java.net.UnknownHostException; import java.nio.channels.Selector; import java.util.LinkedList; import java.util.List; import java.util.Timer; import java.util.TimerTask; import cdn.discovery.DiscoveryArgumentParser; import cdn.discovery.RouterManager; import cdn.shared.CommandListener; import cdn.shared.GlobalLogger; import cdn.shared.ICommandExecutor; import cdn.shared.ICommandRunner; import cdn.shared.IQueuedMessage; import cdn.shared.IWorker; import cdn.shared.MessagePrinter; import cdn.shared.QueueManager; import cdn.shared.message.MessageListener; import cdn.shared.message.MessageSender; public class Discovery implements ICommandRunner, UncaughtExceptionHandler { QueueManager<ICommandExecutor> commands = new QueueManager<ICommandExecutor>(); QueueManager<IQueuedMessage> messageQueue = new QueueManager<IQueuedMessage>(); List<IWorker> workers = new LinkedList<IWorker>(); List<Thread> threads = new LinkedList<Thread>(); private final int portNum; private int refreshInterval = 120; // seconds private final Timer refreshTimer; private final RouterManager routerManager; private Selector selector; private boolean running = true; public Discovery(int portNum, int refreshInterval) throws IOException { this.portNum = portNum; this.refreshInterval = refreshInterval; refreshTimer = new Timer(); routerManager = new RouterManager(); try { selector = Selector.open(); } catch (IOException ex) { GlobalLogger.severe(this, "Unable to open selector for server."); throw ex; } Thread.setDefaultUncaughtExceptionHandler(this); } public void run() { try { System.out.println("Starting up discovery at " + InetAddress.getLocalHost().getHostAddress() + ":" + portNum); } catch (UnknownHostException ex) { GlobalLogger.severe(this, "Failed to get localhost address."); } startMessageListener(); startMessageSender(); startCommandListener(); startRefreshTimer(); // TODO: put in logic to stop gracefully. while (running) { ICommandExecutor cmd = commands.getNextItem(500); if (cmd != null) { cmd.execute(); } } } /** * Adds valid commands to the command queue to be executed. * Some pre-conditions are that the command is already lower-case and that * arguments are split into the array. */ @Override public synchronized void handleCommand(String command, String[] args) { DiscoveryCommand cmd = DiscoveryCommand.fromString(command); switch(cmd) { case SETUP_CDN: System.out.println("Setting up cdn..."); if (args.length > 0) { try { int num = Integer.parseInt(args[0]); if (num >= routerManager.getRouters().length) { System.out.println("To ensure only one per each router, Cr must be less than number of nodes."); } else if (num == 1 && routerManager.getRouters().length != 2) { System.out.println("More connections are needed to create a network of this size."); } else if (num <= 0 || routerManager.getRouters().length <= 1) { System.out.println("Invalid parameters for a network."); } else { commands.queueItem(new SetupCdnCommand(routerManager, num), 500); commands.queueItem(new RefreshWeights(routerManager), 500); } } catch (NumberFormatException ex) { System.out.println(DiscoveryCommand.SETUP_CDN.getForm() + " requires a numeric argument."); } } else { System.out.println(DiscoveryCommand.SETUP_CDN.getForm() + " requires an argument."); } break; case LIST_ROUTERS: System.out.println("Registered routers:"); System.out.println(MessagePrinter.print(routerManager.getRouters())); break; case LIST_WEIGHTS: if (routerManager.isSetup()) { System.out.println(MessagePrinter.print(routerManager.getEdges())); } else { System.out.println("No CDN presently setup, try running " + DiscoveryCommand.SETUP_CDN.getForm() + " first."); } break; case QUIT: case EXIT: shutdown(); break; default: System.out.println("Unknown command."); System.out.print("Try one of "); for (DiscoveryCommand t : DiscoveryCommand.values()) { if (t != DiscoveryCommand.INVALID) { System.out.print(t.getForm() + " "); } } System.out.println(""); break; } } private void startMessageListener() { createThread(new MessageListener(portNum, messageQueue, selector), "MessageListener"); } private void startCommandListener() { createThread(new CommandListener(this), "CommandListener"); } private void startMessageSender() { createThread(new MessageSender(messageQueue, routerManager), "MessageSender"); } private void createThread(IWorker r, String name) { Thread newThread = new Thread(r, name); newThread.start(); workers.add(r); threads.add(newThread); } public void shutdown() { try { selector.close(); } catch (IOException ex) { } for (IWorker worker : workers) { worker.cancel(); } for (Thread thread : threads) { try { thread.join(1000); } catch (InterruptedException e) { GlobalLogger.severe(this, "Failed to join thread " + thread.getName() + " trying to join next."); } } refreshTimer.cancel(); running = false; } private void startRefreshTimer() { // Schedule a refresh of the edge weights at the passed in interval. refreshTimer.scheduleAtFixedRate(new RefreshWeightsTask(), refreshInterval * 1000, refreshInterval * 1000); } @Override public void uncaughtException(Thread arg0, Throwable arg1) { GlobalLogger.severe(this, "Received uncaught exception (" + arg1.toString() + ") from Thread: " + arg0.getName() + " with message:" + arg1.getMessage()); } private class RefreshWeightsTask extends TimerTask { @Override public void run() { GlobalLogger.debug(this, "Ran refresh timer."); commands.queueItem(new RefreshWeights(routerManager), refreshInterval * 1000 - 100); } } private static class RefreshWeights implements ICommandExecutor { private final RouterManager routerManager; public RefreshWeights(RouterManager routerManager) { this.routerManager = routerManager; } @Override public void execute() { routerManager.advertiseLinkWeights(); } } private class SetupCdnCommand implements ICommandExecutor { private final int numberOfPeers; private final RouterManager routerManager; public SetupCdnCommand(RouterManager routerManager, int numberOfPeers) { this.numberOfPeers = numberOfPeers; this.routerManager = routerManager; } @Override public void execute() { routerManager.advertisePeerList(numberOfPeers); } } private static enum DiscoveryCommand { LIST_ROUTERS("list-routers"), LIST_WEIGHTS("list-weights"), SETUP_CDN("setup-cdn"), EXIT("exit"), QUIT("quit"), INVALID(""); private final String form; private DiscoveryCommand(String form) { this.form = form; } public String getForm() { return form; } public static DiscoveryCommand fromString(String cmd) { for (int i = 0; i < DiscoveryCommand.values().length; i++) { if (DiscoveryCommand.values()[i].getForm().equals(cmd)) { return DiscoveryCommand.values()[i]; } } return INVALID; } } /** * @param args */ public static void main(String[] args) { DiscoveryArgumentParser parser = new DiscoveryArgumentParser(args); if (parser.isValid()) { Discovery main; try { main = new Discovery(parser.getPortNum(), parser.getRefreshInterval()); main.run(); } catch (IOException e) { return; } } } }
package org.inftel.pasos.modelo; import java.io.Serializable; import java.util.Observable; import org.inftel.pasos.R; import android.app.Activity; import android.content.Context; import android.content.SharedPreferences; public class Modelo extends Observable implements Serializable { private static final long serialVersionUID = 1L; private Boolean notifVibracion; private Boolean notifVoz; private int tema; private float tamTexto; private SharedPreferences prefs; private SharedPreferences.Editor editor; public Modelo(Context ctx) { prefs = ctx.getSharedPreferences("prefs", Activity.MODE_PRIVATE); editor = prefs.edit(); notifVibracion = prefs.getBoolean("vib", true); notifVoz = prefs.getBoolean("voz", true); tema = prefs.getInt("tema", R.style.tema1); tamTexto = prefs.getFloat("tam", 20); } public Boolean getNotifVibracion() { return notifVibracion; } public float getTamTexto() { return tamTexto; } public void setTamTexto(float tamTexto) { this.tamTexto = tamTexto; editor.putFloat("tam", tamTexto); if (editor.commit()) { setChanged(); notifyObservers(this); } } public void setNotifVibracion(Boolean notifVibracion) { this.notifVibracion = notifVibracion; editor.putBoolean("vib", notifVibracion); if (editor.commit()) { setChanged(); notifyObservers(this); } } public Boolean getNotifVoz() { return notifVoz; } public void setNotifVoz(Boolean notifVoz) { this.notifVoz = notifVoz; editor.putBoolean("voz", notifVoz); if (editor.commit()) { setChanged(); notifyObservers(this); } } public int getTema() { return tema; } public void setTema(int tema) { this.tema = tema; editor.putInt("tema", tema); if (editor.commit()) { setChanged(); notifyObservers(this); } } public static long getSerialversionuid() { return serialVersionUID; } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.model.dao; import com.model.entity.TipoVeiculo; import java.util.List; import javax.ejb.Local; /** * * @author renanmarceluchoa */ @Local public interface TipoVeiculoDao { public TipoVeiculo buscarPorDescricao(String descricao); public List<TipoVeiculo> listar(); }
package Selinium; public class Q23Position { public static void main(String[] args) { String s = "hh--ww--"; String s1 = "--yy--ru"; int sa[]= new int[s.length()]; int index= 0 ; int s1a[] = new int[s1.length()]; int index1=0; char c = '-'; for(int i=0;i<s.length();i++) { if(c==s.charAt(i)) { sa[index] = i; index++; } } for(int i=0;i<s1.length();i++) { if(c==s1.charAt(i)) { s1a[index1] = i; index1++; } } int ans = 0 ; for(int i=0;i<index;i++) { if(sa[i]==s1a[i]) { ans++; } } if(index==ans) { System.out.println("true"); } else { System.out.println("false"); } } }
package org.zacharylavallee.object; import org.junit.Before; import org.junit.Test; import static org.apache.commons.lang3.StringUtils.isNotEmpty; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; public class NameFormatterTest { private final NamePrefix prefix = NamePrefix.ADM; private Name name; @Before public void setup() { String first = "First"; String middle = "Middle"; String last = "Last"; String suffix = "III"; name = new NameBuilder().withFirstName(first).withLastName(last).withMiddleName(middle) .withPrefix(prefix).withSuffix(suffix).build(); } @Test public void getReplacementStringNotEmptyTest() { for (NameFormatter.FormatField formatField : NameFormatter.FormatField.values()) { assertTrue(isNotEmpty(formatField.getReplacementString(name))); } } @Test public void getPlaceholderNotEmptyTest() { for (NameFormatter.FormatField formatField : NameFormatter.FormatField.values()) { assertTrue(isNotEmpty(formatField.getPlaceholder())); } } @Test public void replaceSingleAllTest() { for (NameFormatter.FormatField formatField : NameFormatter.FormatField.values()) { String expected = formatField.getReplacementString(name); String actual = formatField.replace(name, formatField.getPlaceholder()); assertEquals(expected, actual); } } }
package me.jessepayne.pad4j.core.interfaces; import me.jessepayne.pad4j.core.enums.NoteColor; import me.jessepayne.pad4j.core.event.LaunchpadListener; import java.awt.*; public interface ILaunchPad { void setup(Runnable runnable); void noteOff(int note); void clearScreen(); void noteOn(int note, int r, int g, int b); void noteOn(int note, Color color); void text(NoteColor color, String text, boolean loop); void pulseLed(int note, NoteColor color); void flashLed(int note, NoteColor color); int registerListener(LaunchpadListener launchpadListener); boolean unregisterListener(int id); }
import java.util.Arrays; import java.util.List; import javafx.collections.FXCollections; import javafx.collections.ObservableList; public class DadosPersonagens{ public static ObservableList<String> getNumerosPersonagens(){ List<String> possibilidades = Arrays.asList("Random", "1", "2", "3", "4", "5", "6", "7", "8" ,"9", "10", "11", "12", "13", "14","15"); return FXCollections.observableList(possibilidades); } }
/* * 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 br.com.sistema.DAO; import auxiliares.Conexao; import auxiliares.Tratamentos; import br.com.sistema.cadastro.Cliente; import br.com.sistema.cadastro.ContasParaPagar; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; /** * * @author ts */ public class ContasParaPagarDAO { public void insert(ContasParaPagar contasParaPagar) throws Tratamentos { Connection conn = null; PreparedStatement ps = null; try { conn = Conexao.getConnection(); String sql = "insert into ContasParaPagar (id, descricao, valor, vencimento) values(?,?,?,?)"; ps = conn.prepareStatement(sql); ps.setString(1, contasParaPagar.getId()); ps.setString(2, contasParaPagar.getDescricao()); ps.setString(3, contasParaPagar.getValor()); ps.setString(4, contasParaPagar.getVencimento()); ps.execute(); conn.commit(); } catch(SQLException e) { System.out.println("ERRO: " + e.getMessage()); if(conn != null){ try { conn.rollback(); } catch (SQLException ex) { System.out.println("ERRO: " + ex.getMessage()); } } } finally { if( ps != null) { try { ps.close(); } catch (SQLException ex) { System.out.println("ERRO: " + ex.getMessage()); } } if(conn != null) { try { conn.close(); } catch (SQLException ex) { System.out.println("ERRO: " + ex.getMessage()); } } } } public void delete(ContasParaPagar contasParaPagar) throws Tratamentos { Connection conn = null; PreparedStatement ps = null; try { conn = Conexao.getConnection(); String sql = "delete from ContasParaPagar where id = ?"; ps = conn.prepareStatement(sql); ps.setString(1, contasParaPagar.getId()); ps.execute(); conn.commit(); } catch(SQLException e) { System.out.println("ERRO: " + e.getMessage()); if(conn != null){ try { conn.rollback(); } catch (SQLException ex) { System.out.println("ERRO: " + ex.getMessage()); } } } finally { if( ps != null) { try { ps.close(); } catch (SQLException ex) { System.out.println("ERRO: " + ex.getMessage()); } } if(conn != null) { try { conn.close(); } catch (SQLException ex) { System.out.println("ERRO: " + ex.getMessage()); } } } } }
package com.example.dllo.notestudio.DemoListView; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.TextView; import com.example.dllo.notestudio.R; import java.util.ArrayList; /** * Created by dllo on 16/10/29. */ public class ListViewAdapter extends BaseAdapter { private ArrayList<ListViewBean> data ; private Context context ; public ListViewAdapter(Context context) { this.context = context; } public void setData(ArrayList<ListViewBean> data) { this.data = data; notifyDataSetChanged(); } @Override public int getCount() { return data!= null &&data.size()>0?data.size():0; } @Override public Object getItem(int i) { return data!=null ?data.get(i):null; } @Override public long getItemId(int i) { return i; } @Override public View getView(int i, View view, ViewGroup viewGroup) { ViewHolderDemo holder = null ; if (view == null){ view = LayoutInflater.from(context).inflate(R.layout.demo_listview2,viewGroup,false); holder = new ViewHolderDemo(view); view.setTag(holder); }else { holder = (ViewHolderDemo) view.getTag(); } holder.tv1.setText(data.get(i).getNamebean()); holder.iv1.setImageResource(data.get(i).getPicbean()); return view; } class ViewHolderDemo { private TextView tv1 ; private ImageView iv1 ; public ViewHolderDemo(View view) { tv1 = (TextView) view.findViewById(R.id.demo_listview_tv1); iv1 = (ImageView) view.findViewById(R.id.demo_listview_iv1); } } }
package com.xingen.sqlitepractice.activity; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import android.widget.ListView; import com.xingen.sqlitepractice.R; import com.xingen.sqlitepractice.adapter.SelectCityAdapter; import com.xingen.sqlitepractice.adapter.SelectProvinceAdapter; import com.xingen.sqlitepractice.base.BaseApplication; import com.xingen.sqlitepractice.orm.DAO; import com.xingen.sqlitepractice.orm.WriterDBUtils; import com.xingen.sqlitepractice.orm.city.City; import com.xingen.sqlitepractice.orm.city.CityDao; import com.xingen.sqlitepractice.orm.province.Province; import com.xingen.sqlitepractice.orm.province.ProvinceDao; import java.util.List; import rx.Observable; import rx.Subscriber; import rx.Subscription; import rx.android.schedulers.AndroidSchedulers; import rx.functions.Action1; import rx.schedulers.Schedulers; import rx.subscriptions.CompositeSubscription; /** * Created by ${新根} on 2017/5/11 0011. * blog: http://blog.csdn.net/hexingen */ public class CitySelectActivity extends AppCompatActivity implements SelectProvinceAdapter.Callbck { private ListView provicesListView, cityListView; private DAO<Province> provinceDAO; private DAO<City> cityDAO; private CompositeSubscription compositeSubscription; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_selectcity); initConfig(); initView(); queryProvince(); } /** * 初始化配置 */ private void initConfig() { this.compositeSubscription=new CompositeSubscription(); this.provinceDAO=new ProvinceDao(BaseApplication.getAppContext()); this.cityDAO=new CityDao(BaseApplication.getAppContext()); } private SelectProvinceAdapter provinceAdapter; private SelectCityAdapter cityAdapter; /** * 初始化控件 */ private void initView() { provicesListView = (ListView)this.findViewById(R.id.selectcity_provices_listview); cityListView = (ListView) this.findViewById(R.id.selectcity_citys_listview); this.provinceAdapter=new SelectProvinceAdapter(this,this); this.cityAdapter=new SelectCityAdapter(this); this.provicesListView.setAdapter(this.provinceAdapter); this.cityListView.setAdapter(this.cityAdapter); this.provicesListView.setOnItemClickListener(provinceAdapter); } /** * 根据省份的pid查寻到对应的城市 * @param pid */ @Override public void queryCitys(final int pid) { Subscription subscription=Observable.create(new Observable.OnSubscribe<List<City>>(){ @Override public void call(Subscriber<? super List<City>> subscriber) { List<City> list=cityDAO.queryAction(WriterDBUtils.COLUMN_PID+"=?",new String[]{String.valueOf(pid)}); subscriber.onNext(list); } }).subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Action1<List<City>>() { @Override public void call(List<City> cities) { cityAdapter.addData(cities); } }); this.compositeSubscription.add(subscription); } /** * 查询省份信息 */ public void queryProvince(){ Subscription subscription= Observable.create(new Observable.OnSubscribe<List<Province>>() { @Override public void call(Subscriber<? super List<Province>> subscriber) { //执行查询操作 List<Province> list= provinceDAO.queryAll(); subscriber.onNext(list); } }).subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread())//订阅者执行的线程,UI线程 .subscribe(new Action1<List<Province>>() { @Override public void call(List<Province> provinces) { //更新UI provinceAdapter.addData(provinces); } }); this.compositeSubscription.add(subscription); } @Override protected void onDestroy() { this.compositeSubscription.clear(); super.onDestroy(); } }
package com.tencent.mm.plugin.downloader.model; import com.tencent.mm.plugin.appbrand.jsapi.appdownload.JsApiPauseDownloadTask; import com.tencent.mm.plugin.cdndownloader.c.a; import com.tencent.mm.plugin.downloader.e.b; import com.tencent.mm.sdk.platformtools.bi; import com.tencent.mm.sdk.platformtools.x; class a$4 implements Runnable { final /* synthetic */ a ibF; final /* synthetic */ long ibH; a$4(a aVar, long j) { this.ibF = aVar; this.ibH = j; } public final void run() { x.d("MicroMsg.FileCDNDownloader", JsApiPauseDownloadTask.NAME); FileDownloadTaskInfo cm = this.ibF.cm(this.ibH); if (cm != null && cm.status == 1) { a.aAk().yj(cm.url); a.a(this.ibF, cm.url); FileDownloadTaskInfo cm2 = this.ibF.cm(this.ibH); com.tencent.mm.plugin.downloader.c.a cs = c.cs(this.ibH); if (cs != null) { cs.field_status = 2; cs.field_downloadedSize = cm2.icq; c.e(cs); Long valueOf = Long.valueOf(bi.a((Long) a.b(this.ibF).get(cm2.url), cs.field_startTime)); if (valueOf != null) { b.a(cs.field_downloadId, ((((float) (cs.field_downloadedSize - Long.valueOf(bi.a((Long) a.a(this.ibF).get(cm2.url), cs.field_startSize)).longValue())) * 1000.0f) / ((float) (System.currentTimeMillis() - valueOf.longValue()))) / 1048576.0f, (int) ((((float) cs.field_downloadedSize) / ((float) cs.field_totalSize)) * 100.0f)); } } a.a(this.ibF).remove(cm2.url); a.b(this.ibF).remove(cm2.url); this.ibF.ibT.cq(this.ibH); } } }
package com.pzhu.topicsys.modules.department.service; import com.pzhu.topicsys.common.util.PageBounds; import com.pzhu.topicsys.common.util.PageResult; /** * Desc:院系管理Service * */ public interface DepartmentService { /** * Desc:查询院系列表 * * @param name * @param page * @return */ PageResult findDepartments(String name, PageBounds page); /** * Desc:新增/修改院系 * * @param departmentId * @param name * @return */ boolean save(String departmentId, String name); /** * Desc:院系停用 * * @param departmentId * @param enable * @return */ boolean enable(String departmentId, boolean enable); }
/* * 用动态代理类的格式输出: * ****************(静态) * 信息工程学院(静态) * ****************(静态) * 自动化(动态) * ****************(静态) * */ package day17; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; interface School { void perfession(String str); } // 被代理类 class Spcialty implements School { @Override public void perfession(String str) { System.out.println(" " + str); } } // 静态代理类 class Bift { public void bift1() { System.out.println("**********"); } public void bift2() { System.out.println(" 信息工程学院"); } } // 代理类 class Proxy1 implements InvocationHandler { Object obj; // 获取被代理类对象 public Object getProxy(Object obj) { this.obj = obj; return Proxy.newProxyInstance(obj.getClass().getClassLoader(), obj.getClass().getInterfaces(), this); } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { Bift bift = new Bift(); bift.bift1(); bift.bift2(); bift.bift1(); Object returnVal = method.invoke(obj, args); bift.bift1(); return returnVal; } } public class MyInvocationTest { public static void main(String[] args) { Spcialty spcialty = new Spcialty(); Proxy1 proxy = new Proxy1(); Object obj = proxy.getProxy(spcialty); School school = (School)obj; school.perfession("自动化"); } }
package com.app.LMS.Employee; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.Toolbar; import android.content.Intent; import android.database.Cursor; import android.os.Bundle; import android.view.MenuItem; import android.widget.*; import com.app.LMS.Database.ELMSHelper; import com.app.LMS.R; import com.google.android.material.textfield.TextInputLayout; public class EmployeeLogin extends AppCompatActivity { private EditText user_name, pass; private Button login; private ELMSHelper helper; private Intent i; private TextInputLayout nameLayout, passwordLayout; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_employee_login); Toolbar toolbar = findViewById(R.id.bar3); toolbar.setTitle("Employee"); setSupportActionBar(toolbar); getSupportActionBar().setDisplayHomeAsUpEnabled(true); user_name = findViewById(R.id.e_user); pass = findViewById(R.id.e_pass); login = findViewById(R.id.e_login); helper = new ELMSHelper(getApplicationContext()); nameLayout = findViewById(R.id.e_nameLayout); passwordLayout = findViewById(R.id.e_passLayout); nameLayout.requestFocus(); login.setOnClickListener(v -> { String userName = user_name.getText().toString().trim(); String password = pass.getText().toString(); if (user_name.length() == 0) { showError(nameLayout, "username cannot be empty"); passwordLayout.setErrorEnabled(false); } else if(pass.length() == 0) { showError(passwordLayout, "password cannot be empty"); nameLayout.setErrorEnabled(false); } else { Cursor cursor= helper.checkEmployeeLogin(userName,password); i= new Intent(getApplicationContext(),EmployeePanel.class); while (cursor.moveToNext()){ i.putExtra("empID", cursor.getString(0)); i.putExtra("empName", cursor.getString(1)); } if (cursor.getCount() > 0) { Toast.makeText(getApplicationContext(), "you are logged in successfully", Toast.LENGTH_SHORT).show(); nameLayout.setErrorEnabled(false); passwordLayout.setErrorEnabled(false); startActivity(i); } else if (!helper.checkEmployeeName(userName)){ showError(nameLayout, "user name is incorrect"); passwordLayout.setErrorEnabled(false); } else { showError(passwordLayout, "password is incorrect"); nameLayout.setErrorEnabled(false); } } }); pass.setOnClickListener(v -> { passwordLayout.setErrorEnabled(false); }); } public void showError(TextInputLayout view, String errorMsg) { view.setError(errorMsg); view.requestFocus(); } @Override protected void onRestart() { user_name.setText(""); pass.setText(""); nameLayout.requestFocus(); super.onRestart(); } @Override public boolean onOptionsItemSelected(@NonNull MenuItem item) { finish(); return true; } }
package com.example.demo.state.action; public interface TaskChoiceAction extends HonorAction { }
package Day02; public class Day02_3 { }
package dentistrymanager; import java.sql.*; public class RebuildDB { public static void main(String[] args) { try (Connection con = DBConnect.getConnection(true)){ DatabaseBuilder builder = new DatabaseBuilder(con); System.out.println(builder.checkIfAllTablesExist()); builder.resetTables(); builder.fillWithDefaultValues(); } catch (SQLException e) { DBConnect.printSQLError(e); } } }
package exhaustiveSearch; import java.util.ArrayList; import java.util.Arrays; /*Given a list of numbers that may has duplicate numbers, return all possible subsets * Example: * If S = [1,2,2], a solution is: [ [2], [1], [1,2,2], [2,2], [1,2], [] ] Note Each element in a subset must be in non-descending order. The ordering between two subsets is free. the solution set must not contain duplicate subsets. * */ /*needs review(remember) /* 递归解决。 1. 先对数组进行排序。 2. 在set中依次取一个数字出来即可,因为我们保持升序,所以不需要取当前Index之前的数字。 对于每一个指针start, 循环加入以S[start]为起始元素的subset, 一层for循环结束后, 把刚刚加入到临时子集中的元素remove掉, 也就是回溯 backtracking recursive time complexity: o(n*2^n) TIME: 227 ms */ public class SubSetsII { public static ArrayList<ArrayList<Integer>> subsetsNoDup(int[] source) { // new empty subsetList ArrayList<ArrayList<Integer>> subsetsList = new ArrayList<ArrayList<Integer>>(); // new subset ArrayList<Integer> subset = new ArrayList<Integer>(); // corner check if (source == null || source.length == 0) return subsetsList; // sort the array first Arrays.sort(source); // call help function subsetsHelper(subsetsList, subset, source, 0); return subsetsList; } public static void subsetsHelper(ArrayList<ArrayList<Integer>> result, ArrayList<Integer> list, int[] num, int pos) { result.add(new ArrayList<Integer>(list)); /* * i处所代表的变量即为某一层遍历中得「第一个元素」 i == position --> go depth, when we add * number, we don't care duplicates i != position means back tracking, * already remove one number, i++ which leads i!=position,(i>position * also works) that means second or third or more time, we care about * the duplicate numbers. As they are sorted, we abort and continue */ for (int i = pos; i < num.length; i++) { // // 控制树的分支 关键 : backtrack if (i != pos && num[i] == num[i - 1]) { continue; } list.add(num[i]); // 对于每一个指针start, 循环加入以S[start]为起始元素的subset // not: subsetsListPara.add(subsetPara) /* * pass by reference 这个自己也知道, 但是写的时候居然理所应当的直接add了lis 比如刚开始加进去是[], * 然后当加入[1]到result时, result实际上是{{1} , {1}}, 然后加入[2]到list后, result * add list变成了 {{1,2}{1,2}{1,2}}. 这显然是不对的” */ subsetsHelper(result, list, num, i + 1); // 一层for循环结束后, 把刚刚加入到临时子集中的元素remove掉, 也就是回溯backtrack。 list.remove(list.size() - 1);// why????? } } public static void main(String[] args) { // TODO Auto-generated method stub int[] S = { 1, 2, 2 }; System.out.println(subsetsNoDup(S)); } }
package com.progoth.synchrochat.client.gui.widgets; import java.util.LinkedList; import java.util.List; import com.google.gwt.event.dom.client.KeyCodes; import com.google.gwt.event.dom.client.KeyDownEvent; import com.google.gwt.event.dom.client.KeyDownHandler; import com.sencha.gxt.widget.core.client.form.HtmlEditor; public class SynchroHtmlEditor extends HtmlEditor { public static interface EditSendHandler { void onSendRequested(SynchroHtmlEditor source); } private final List<EditSendHandler> m_lists = new LinkedList<SynchroHtmlEditor.EditSendHandler>(); public SynchroHtmlEditor() { textArea.addKeyDownHandler(new KeyDownHandler() { @Override public void onKeyDown(final KeyDownEvent aEvent) { if (aEvent.getNativeKeyCode() == KeyCodes.KEY_ENTER && !aEvent.isAnyModifierKeyDown()) { aEvent.stopPropagation(); aEvent.preventDefault(); onSend(); } } }); } public void addListener(final EditSendHandler aList) { m_lists.add(aList); } protected void onSend() { for (final EditSendHandler list : m_lists) { list.onSendRequested(this); } } public void removeListener(final EditSendHandler aList) { m_lists.remove(aList); } }
package com.example.Lab21CoffeeShopUserRegistration; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; @Controller public class Usercontroller { @Autowired //private MenuItemDao menuItemDao; private UserDao user; @RequestMapping("/add/user") public ModelAndView showAddUser(User userItem ) { user.create(userItem); return new ModelAndView("redirect:/cart"); } }
/** * Project Name:WebScan * File Name:Client.java * Package Name:client * Date:2014年1月9日下午8:31:08 * Copyright (c) 2014, hzycaicai@163.com All Rights Reserved. * */ package client; import java.util.ArrayList; import java.util.Iterator; import java.util.Observable; import java.util.Observer; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.logging.Level; import java.util.logging.Logger; import databasesource.DatabaseSource; import databasesource.DatabaseSourceDriver; import databasesource.DatabaseSourceDriverFactory; import datachecker.DataChecker; import dataobject.CheckResult; import dataobject.ScanPlan; /** * ClassName:Client <br/> * Date: 2014年1月9日 下午8:31:08 <br/> * @author hzycaicai * @version */ public class Client implements Observer{ private static Logger logger = Logger.getLogger(Client.class.getName()); //private static final Client client = new Client(); private ArrayList<ScanPlan> scanPlanList = null; private String userName = "root"; private String passWd = "654321"; protected DatabaseSourceDriver databaseSourceDriver = null; protected DatabaseSource databaseSource = null; protected int poolSize = 10; protected ExecutorService pool = Executors.newFixedThreadPool(poolSize); /* * initilize the databaseSourceDriver and databaseSource */ public Client(){ this.databaseSourceDriver = DatabaseSourceDriverFactory.getDatabaseSourceDriver(userName,passWd); this.databaseSource = databaseSourceDriver.getNewDatabaseSource(); } /*public static Client getClient(){ return client; }*/ /* * every time this method is called, it prefetch the scanPlanList, mark their status to 1 * for each plan create a thread added to the threadpool to run the safey check tool and analyse the result * now the shutdown method is in the start method to shutdown the system safely */ public void start(){ if(databaseSourceDriver==null){ databaseSourceDriver = DatabaseSourceDriverFactory.getDatabaseSourceDriver(userName,passWd); } String filename = null; this.scanPlanList = databaseSource.getScanPlanList(); if(scanPlanList!=null){ for(Iterator<ScanPlan> it = scanPlanList.iterator();it.hasNext();){ ScanPlan scanPlan = it.next(); System.out.println("plan"+scanPlan.getId()+" "+scanPlan.getWebSite()); filename = "D:\\WebScan\\"+scanPlan.getId()+".xml"; DataChecker check = new DataChecker(scanPlan,filename); check.addObserver(this); Thread thread = new Thread(check); //thread.start(); this.pool.execute(thread); logger.log(Level.INFO,"add thread to the threadpool"); //System.out.println(filename+" "+scanPlan.getId()+" "+scanPlan.getWebSite()+" "+scanPlan.getDateTime()); } } shutdown(); } /* * shutdown the threadpool and waitfor all the thread to be terminated and then reset the database */ public void shutdown(){ pool.shutdown(); while(!pool.isTerminated()); reset(); } /* * @see java.util.Observer#update(java.util.Observable, java.lang.Object) * if the object is scanplan then update the status of the scanplan * if the object is checkresult list, then write back the result */ @Override public void update(Observable o, Object arg) { if(arg instanceof ScanPlan){ int Id = ((ScanPlan)arg).getId(); int status = ((ScanPlan)arg).getEndIbm(); System.out.println("Notification from Thread"+Id+" to change status to:"+status); databaseSourceDriver.updateScanPlan(Id,status); } else if(arg instanceof ArrayList<?>){ System.out.println("Notification of ArrayList"); ArrayList<CheckResult> resList = ((ArrayList<CheckResult>)arg); for(Iterator<CheckResult> it = resList.iterator();it.hasNext();){ CheckResult res = it.next(); System.out.println(res.getName()+" "+res.getRisk()); databaseSource.writeCheckRes(res); } } } /* * in case for the crash and some unexpected exceptions * To recover the status of the plans whose status is running while actually not * add to the GUI as a button,can only called after the threadpool is safely shutdown */ public void reset(){ System.out.println("reseting the database:"); ArrayList<Integer> list = databaseSource.getScannedList(); for(Iterator<Integer> it = list.iterator();it.hasNext();){ System.out.print(it.next()+" "); } System.out.println(); databaseSourceDriver.updateScanPlan(list); } }
package io.github.zkhan93.alarmandplayer.service.openweathermap.response; public class Weather { public int id; public String main; public String description; public String icon; @Override public String toString() { return "Weather{" + "id=" + id + ", main='" + main + '\'' + ", description='" + description + '\'' + ", icon='" + icon + '\'' + '}'; } }
/* * [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.common.service; import de.hybris.platform.core.model.ItemModel; import de.hybris.platform.servicelayer.search.SearchResult; import java.util.function.Function; /** * Service to convert {@link SearchResult} with results of type <code>Model</code> to results of type <code>Data</code> */ public interface SearchResultConverter { /** * Convert {@link SearchResult} of type <code>Model</code> to <code>Data</code> * * @param modelSearchResult * the search result containing model objects to be converted * @param convertFunction * the function used to convert the model object into the data object * @return the search result containing data objects; empty result list if <code>modelSearchResult</code> is * <tt>null</tt>; never <tt>null</tt> */ <S extends ItemModel, T> SearchResult<T> convert(final SearchResult<S> modelSearchResult, final Function<S, T> convertFunction); }
/* * 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 manejoarray; /** * * @author reroes */ public class ArregloUno { public static void main(String[] args) { // creación de un arreglo int[] arreglo = new int[5]; arreglo[0] = 10; arreglo[1] = 20; arreglo[2] = 30; arreglo[3] = 40; arreglo[4] = 50; // arreglo[5] = 60; for (int i = 0; i < arreglo.length; i++) { System.out.println(arreglo[i]); } } }
package com.travel_agency.controller; import com.travel_agency.config.Validator; import com.travel_agency.entity.Hotel; import com.travel_agency.entity.RoomBook; import com.travel_agency.service.CityService; import com.travel_agency.service.HotelService; import com.travel_agency.service.RoomBookService; import com.travel_agency.service.RoomService; import com.travel_agency.service.UserService; import lombok.AllArgsConstructor; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestParam; import javax.servlet.http.HttpServletRequest; import java.util.List; @Controller @AllArgsConstructor public class HotelController { private final HotelService hotelService; private final CityService cityService; private final RoomService roomService; private final RoomBookService roomBookService; private final UserService userService; @GetMapping(value = "/hotels") public String getAllHotels(ModelMap model) { model.addAttribute("hotels", hotelService.getAll()); return "home/findHotels"; } @PostMapping(value = "/hotel") public String hotel(@RequestParam int id, ModelMap model, HttpServletRequest request) { if (request.getParameter("check") != null) { model.addAttribute("hotelDto", hotelService.getHotelDtoById(id)); return "home/hotel"; } else if (request.getParameter("book") != null) { model.addAttribute("hotelDto", hotelService.getHotelDtoById(id)); return "home/hotel"; } return null; } @GetMapping("/hotel/available") public String getHotelWithAvailability( @RequestParam int id, String startDateAvailable, String endDateAvailable, ModelMap model) { Validator.validateAvailableDate(startDateAvailable, endDateAvailable); model.addAttribute( "hotelDto", hotelService.getHotelDtoWithAvailabilityById(id, startDateAvailable, endDateAvailable)); return "home/hotel"; } @PostMapping("hotel/book") public String bookRoomByHotelId(@RequestParam int roomId, String startDateAvailable, String endDateAvailable) { Validator.validateAvailableDate(startDateAvailable, endDateAvailable); final RoomBook roomBook = new RoomBook(); // set userID=1,because of security and can't get logIn userDetails to get Id which need to set roomBook.setUser(userService.getUserById(1)); roomBook.setRoom(roomService.getRoomById(roomId)); roomBook.setOrderStart(startDateAvailable); roomBook.setOrderEnd(endDateAvailable); roomBookService.add(roomBook); return "index"; } @GetMapping(value = "allCities") public String getAllCities(Model model) { model.addAttribute("cities", cityService.getAll()); return "management/chooseCity"; } @GetMapping("chooseCity") public String addHotel(@RequestParam int id, Model model) { model.addAttribute("hotel", new Hotel()); model.addAttribute("id", id); model.addAttribute("city", cityService.getById(id)); return "management/addHotel"; } @PostMapping("addHotelByCityId") public String addHotelByCityId(@RequestParam int id, @ModelAttribute Hotel hotel, Model model) { final List<Hotel> hotelsByCityId = hotelService.getHotelsByCityId(id); if (hotelsByCityId.stream().noneMatch(r -> hotel.getName().equals(r.getName()))) { hotel.setCity(cityService.getById(id)); hotelService.add(hotel); return "index"; } model.addAttribute("msg", "Hotel with this name already exist in this City"); model.addAttribute("rm", "Add another Hotel"); return "modules/error"; } }
package gdut.ff.controller; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; import com.alibaba.fastjson.JSONObject; import gdut.ff.domain.Ip; import gdut.ff.service.IpServiceImpl; import gdut.ff.utils.JsonUtil; /** * * @author liuffei * @date */ @RestController public class IpController { @Autowired private IpServiceImpl ipServiceImpl; /** * 添加记录 * @return * @throws Exception */ @PostMapping(value = "/ip") public JSONObject insertIp(@RequestBody Ip ip,HttpServletRequest request) throws Exception { if(ip.getId() > 0) { ipServiceImpl.updateIp(ip); }else { ipServiceImpl.insertIp(ip); } return JsonUtil.successJson(); } /** * 查询指定记录 * @param id * @return */ @GetMapping(value = "/ip/{id}") public JSONObject findIpById(@PathVariable String id, HttpServletRequest request, HttpServletResponse response) { Ip ip = ipServiceImpl.findIpById(id); JSONObject result = JsonUtil.successJson(); result.put("content", ip); return result; } /** * 更新指定的记录 * @param id * @return */ @PutMapping(value = "/ip/{id}") public JSONObject updateIpgById(@PathVariable String id, @RequestBody Ip ip) { ipServiceImpl.updateIp(ip); return JsonUtil.successJson(); } /** * 删除记录 * @param id * @return */ @DeleteMapping(value = "/ip/{id}") public JSONObject deleteIpById(@PathVariable String id) { ipServiceImpl.deleteIpById(id); return JsonUtil.successJson(); } /** * 查询全部 * @param id * @return */ @GetMapping(value = "/ips") public JSONObject finaAllIps() { List<Ip> ips = ipServiceImpl.findAllIp(null); JSONObject result = JsonUtil.successJson(); result.put("ips", ips); return result; } }
package com.design.pattern.abstractFactory.btn; /** * @author zhangbingquan * @desc 具体的widow系统,按钮实现类 * @time 2019/7/28 18:33 */ public class WindowButton implements Button { @Override public void click() { System.out.println("一个widow系统下的桌面按钮,提供点击操作"); } }
package H06; import java.applet.Applet; import java.awt.*; public class H061_GeldDelen extends Applet { double a, b, uitkomst; public void init() { a = 113; b = 4; uitkomst = a/b; } public void paint(Graphics g) { g.drawString("De uitkomst is: " + uitkomst, 20, 20); g.drawString("€28,25: Jan", 20, 60); g.drawString("€28,25: Ali", 20, 80); g.drawString("€28,25: Jeanette", 20, 100); g.drawString("€28,25: Shonté", 20, 120); } }
package uk.ac.dundee.computing.aec.instagrim.servlets; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.security.NoSuchAlgorithmException; import javax.servlet.RequestDispatcher; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.datastax.driver.core.BoundStatement; import com.datastax.driver.core.Cluster; import com.datastax.driver.core.PreparedStatement; import com.datastax.driver.core.ResultSet; import com.datastax.driver.core.Row; import com.datastax.driver.core.Session; import uk.ac.dundee.computing.aec.instagrim.lib.CassandraHosts; import uk.ac.dundee.computing.aec.instagrim.stores.Pic; /** * Servlet implementation class DepRet */ @WebServlet("/TranRet") public class TranRet extends HttpServlet { Cluster cluster=null; public void init(ServletConfig config) throws ServletException { // TODO Auto-generated method stub cluster = CassandraHosts.getCluster(); } /** /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String Accno = request.getParameter("Accno"); String Bal=request.getParameter("Bal"); try { Session session = cluster.connect("banknew"); PreparedStatement ps = session.prepare("SELECT Accno,Bal FROM savings where Accno=? ALLOW FILTERING"); ResultSet rs = null; BoundStatement boundStatement = new BoundStatement(ps); rs = session.execute( // this is where the query is executed boundStatement.bind( // here you are binding the 'boundStatement' Accno )); if (rs.isExhausted()) { System.out.println("No data found"); } else { for (Row row : rs) { Accno=row.getString("Accno"); Bal=row.getString("Bal"); //((ServletRequest) session).setAttribute("Acc", Acc); // ((ServletRequest) session).setAttribute("Bal", Bal); // RequestDispatcher rd=request.getRequestDispatcher("/Deposit.jsp"); // rd.forward(request,response); //We are assuming this always works. Also a transaction would be good here ! } } request.setAttribute("Accno", Accno); request.setAttribute("Bal", Bal); request.getRequestDispatcher("/Transfer.jsp").forward(request, response); } catch (Exception et){ System.out.println("Can't execute"); // TODO Auto-generated method stub } } }
package com.zhengsr.viewpagerhelper; import android.animation.ObjectAnimator; import android.animation.ValueAnimator; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import com.zhengsr.viewpagerhelper.activity.glide.GlideTransActivity; import com.zhengsr.viewpagerhelper.activity.glide.GlideZoomActivity; import com.zhengsr.viewpagerhelper.activity.glide.GlidenormalActivity; import com.zhengsr.viewpagerhelper.tab.TabActivity; import com.zhengsr.viewpagerlib.GlideManager; import com.zhengsr.viewpagerlib.view.ArcImageView; import com.zhengsr.viewpagerlib.view.ColorTextView; public class MainActivity extends AppCompatActivity { private static final String TAG = "zsr"; private static final int[] RES = {R.mipmap.guide1,R.mipmap.guide2,R.mipmap.guide3, R.mipmap.guide4 }; private ColorTextView mColorTextView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ArcImageView arcImageView = (ArcImageView) findViewById(R.id.arcimage); new GlideManager.Builder() .setContext(this) .setImgSource("http://img.mukewang.com/54bf7e1f000109c506000338-590-330.jpg") .setImageView(arcImageView) .builder(); mColorTextView = (ColorTextView) findViewById(R.id.colortext); } public void glide(View view) { startActivity(new Intent(this, GlidenormalActivity.class)); } public void glide_tran(View view) { startActivity(new Intent(this, GlideTransActivity.class)); } public void glide_scale(View view) { startActivity(new Intent(this, GlideZoomActivity.class)); } public void loop_max(View view) { startActivity(new Intent(this, LoopActivity.class)); } public void fragment(View view) { startActivity(new Intent(this,TabActivity.class)); } public void leftchange(View view) { ObjectAnimator animator = ObjectAnimator.ofFloat(mColorTextView,"progress",0,1); animator.setDuration(2000).start(); animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator animation) { float value = (float) animation.getAnimatedValue(); mColorTextView.setprogress(value,ColorTextView.DEC_LEFT); } }); } public void rightchange(View view) { ObjectAnimator animator = ObjectAnimator.ofFloat(mColorTextView,"progress",0,1); animator.setDuration(2000).start(); animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator animation) { float value = (float) animation.getAnimatedValue(); mColorTextView.setprogress(value,ColorTextView.DEC_RIGHT); } }); } }
package com.arkaces.aces_marketplace_api.services; import com.arkaces.aces_marketplace_api.service_category.ServiceCategoryEntity; import lombok.Data; import javax.persistence.*; @Data @Entity @Table(name = "service_category_links") public class ServiceCategoryLinkEntity { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long pid; @ManyToOne @JoinColumn(name="service_pid", nullable = false) private ServiceEntity serviceEntity; @ManyToOne @JoinColumn(name="service_category_pid", nullable = false) private ServiceCategoryEntity serviceCategoryEntity; }
package com.globalrelay.checker; import com.globalrelay.model.Connection; import com.globalrelay.model.HealthCheckConfiguration; import com.globalrelay.util.TCPServer; import org.junit.Test; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; public class TCPHealthCheckerTest { @Test public void testHappyPath(){ Runnable runnable = () -> new TCPServer(5000); new Thread(runnable).start(); HealthCheckConfiguration healthCheckConfiguration = new HealthCheckConfiguration(); Connection connection = new Connection( Protocol.TCP, "localhost", 5000); healthCheckConfiguration.setConnection(connection); assertTrue(new TCPHealthChecker().doCheck(healthCheckConfiguration)); } @Test public void testNonExistingServer(){ HealthCheckConfiguration healthCheckConfiguration = new HealthCheckConfiguration(); Connection connection = new Connection( Protocol.TCP, "localhost", 92121); healthCheckConfiguration.setConnection(connection); assertFalse(new TCPHealthChecker().doCheck(healthCheckConfiguration)); } }
/* * Copyright © 2019 The GWT Project Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.gwtproject.dom.client; import jsinterop.annotations.JsOverlay; import jsinterop.annotations.JsPackage; import jsinterop.annotations.JsProperty; import jsinterop.annotations.JsType; import jsinterop.base.Js; import org.gwtproject.core.client.JavaScriptObject; /** * Embedded image. * * @see <a href="http://www.w3.org/TR/1999/REC-html401-19991224/struct/objects.html#edef-IMG">W3C * HTML Specification</a> */ @JsType(isNative = true, name = "Object", namespace = JsPackage.GLOBAL) @TagName(ImageElement.TAG) public class ImageElement extends Element { @JsOverlay public static final String TAG = "img"; /** * Assert that the given {@link Element} is compatible with this class and automatically typecast * it. * * @param elem the element to assert is an instance of this type * @return the element, cast to this type */ @JsOverlay public static ImageElement as(Element elem) { assert is(elem); return (ImageElement) elem; } /** * Determines whether the given {@link JavaScriptObject} can be cast to this class. A <code>null * </code> object will cause this method to return <code>false</code>. * * @param o the object to check if it is an instance of this type * @return true of the object is an instance of this type, false otherwise */ @JsOverlay public static boolean is(JavaScriptObject o) { if (Element.is(o)) { return is((Element) o); } return false; } /** * Determine whether the given {@link Node} can be cast to this class. A <code>null</code> node * will cause this method to return <code>false</code>. * * @param node the node to check if it is an instance of this type * @return true if the node is an instance of this type, false otherwise */ @JsOverlay public static boolean is(Node node) { if (Element.is(node)) { return is((Element) node); } return false; } /** * Determine whether the given {@link Element} can be cast to this class. A <code>null</code> node * will cause this method to return <code>false</code>. * * @param elem the element to check if it is an instance of this type * @return true if the element is an instance of this type, false otherwise */ @JsOverlay public static boolean is(Element elem) { return elem != null && elem.hasTagName(TAG); } protected ImageElement() {} /** * Alternate text for user agents not rendering the normal content of this element. * * @see <a href="http://www.w3.org/TR/1999/REC-html401-19991224/struct/objects.html#adef-alt">W3C * HTML Specification</a> */ @JsProperty public final native String getAlt(); /** * Height of the image in pixels. * * @see <a * href="http://www.w3.org/TR/1999/REC-html401-19991224/struct/objects.html#adef-height-IMG">W3C * HTML Specification</a> */ @JsProperty public final native int getHeight(); /** * URI designating the source of this image. * * @see <a * href="http://www.w3.org/TR/1999/REC-html401-19991224/struct/objects.html#adef-src-IMG">W3C * HTML Specification</a> */ @JsProperty public final native String getSrc(); /** * The width of the image in pixels. * * @see <a * href="http://www.w3.org/TR/1999/REC-html401-19991224/struct/objects.html#adef-width-IMG">W3C * HTML Specification</a> */ @JsProperty public final native int getWidth(); /** * Use server-side image map. * * @see <a * href="http://www.w3.org/TR/1999/REC-html401-19991224/struct/objects.html#adef-ismap">W3C * HTML Specification</a> */ @JsOverlay public final boolean isMap() { return Js.isTruthy(this.isMap); } @JsProperty private boolean isMap; /** * Alternate text for user agents not rendering the normal content of this element. * * @see <a href="http://www.w3.org/TR/1999/REC-html401-19991224/struct/objects.html#adef-alt">W3C * HTML Specification</a> */ @JsProperty public final native void setAlt(String alt); /** * Height of the image in pixels. * * @see <a * href="http://www.w3.org/TR/1999/REC-html401-19991224/struct/objects.html#adef-height-IMG">W3C * HTML Specification</a> */ @JsProperty public final native void setHeight(int height); /** * Use server-side image map. * * @see <a * href="http://www.w3.org/TR/1999/REC-html401-19991224/struct/objects.html#adef-ismap">W3C * HTML Specification</a> */ @JsProperty public final native void setIsMap(boolean isMap); /** * URI designating the source of this image. * * @see <a * href="http://www.w3.org/TR/1999/REC-html401-19991224/struct/objects.html#adef-src-IMG">W3C * HTML Specification</a> */ @JsProperty public final native void setSrc(String src); /** * Use client-side image map. * * @see <a * href="http://www.w3.org/TR/1999/REC-html401-19991224/struct/objects.html#adef-usemap">W3C * HTML Specification</a> */ @JsProperty public final native void setUseMap(boolean useMap); /** * The width of the image in pixels. * * @see <a * href="http://www.w3.org/TR/1999/REC-html401-19991224/struct/objects.html#adef-width-IMG">W3C * HTML Specification</a> */ @JsProperty public final native void setWidth(int width); /** * Use client-side image map. * * @see <a * href="http://www.w3.org/TR/1999/REC-html401-19991224/struct/objects.html#adef-usemap">W3C * HTML Specification</a> */ @JsOverlay public final boolean useMap() { return Js.isTruthy(this.useMap); } @JsProperty(name = "useMap") private boolean useMap; }
package br.udesc.controller; import br.udesc.controller.tablemodel.VinculoModel; import br.udesc.model.dao.DisciplinaJpaController; import br.udesc.model.dao.ProfessorJpaController; import br.udesc.model.entidade.Disciplina; import br.udesc.model.entidade.Professor; import br.udesc.view.TelaTableVinculo; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JOptionPane; /** * Classe resposável pelo controle do modulo que exibe a tabela com os Vínculos já realizados. * @author PIN2 */ public class ControladorTelaTableVinculo { private TelaTableVinculo ttv; private Disciplina dis; private VinculoModel vm; private List<Disciplina> listaVinculo; private DisciplinaJpaController djc; /** * Construtor intanciando os objetos necessários e iniciando os componentes da Tela. */ public ControladorTelaTableVinculo() { ttv = new TelaTableVinculo(); dis = new Disciplina(); vm = new VinculoModel(); djc = new DisciplinaJpaController(); ttv.tabelaVinculacao.setModel(vm); iniciar(); carregarVinculo(); } /** * Método responsável por guardar a disciplina do vínculo selecionado na variável do "dis" do tipo Disciplina. * @param linha Linha da tabela. */ public void pegarLinha(int linha) { dis = djc.findDisciplina((long) ttv.tabelaVinculacao.getValueAt(linha, 0)); } /** * Método responsável por carregar vínculos existentes para a disciplina. */ public void carregarVinculo() { vm.limpar(); listaVinculo = djc.listarDisciplina(); for (Disciplina listaDisciplinas : listaVinculo) { vm.anuncioAdd(listaDisciplinas); } ttv.tabelaVinculacao.getSelectionModel().addSelectionInterval(0, 0); } /** * Método responsável por eliminar vínculo. */ public void tirarVinculo() { pegarLinha(ttv.tabelaVinculacao.getSelectedRow()); ProfessorJpaController pjc = new ProfessorJpaController(); Professor p = new Professor(); p = dis.getProfessor(); if (dis.getProfessor() != null) { //---------------caso esse não funcione tente o comentado ------------- p.getListaDisciplinaProfessor().remove(dis); dis.setProfessor(null); try { djc.edit(dis); pjc.edit(p); } catch (Exception ex) { ex.printStackTrace(); } } else { JOptionPane.showMessageDialog(null, "Erro, Disciplina sem professor", "Erro", JOptionPane.ERROR_MESSAGE); } carregarVinculo(); } /** * Método que inicia os componentes do JFrame (Botões etc). */ public void iniciar() { ttv.botaoAdicionar.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent ae) { ControladorTelaVinculo ctv = new ControladorTelaVinculo(); int linha = ttv.tabelaVinculacao.getSelectedRow(); pegarLinha(linha); ctv.carregarSelecionado(dis); ctv.executar(); ttv.dispose(); } }); ttv.botaoEditar1.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent ae) { ControladorTelaVinculo ctv = new ControladorTelaVinculo(); ctv.executar(); int linha = ttv.tabelaVinculacao.getSelectedRow(); pegarLinha(linha); ctv.editar(dis); ttv.dispose(); } }); ttv.boataoExcluir.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent ae) { tirarVinculo(); } }); ttv.botaoInicio.addActionListener( new ActionListener() { @Override public void actionPerformed(ActionEvent ae) { ControladorTelaInicio cti = new ControladorTelaInicio(); cti.executar(); ttv.dispose(); } } ); ttv.botaoProfessor.addActionListener( new ActionListener() { @Override public void actionPerformed(ActionEvent ae ) { ControladorTelaTableProfessor ctp = new ControladorTelaTableProfessor(); ctp.executar(); ttv.setVisible(false); } } ); ttv.botaoSala.addActionListener( new ActionListener() { @Override public void actionPerformed(ActionEvent ae ) { ControladorTelaTableSala ctts = new ControladorTelaTableSala(); ctts.executar(); ttv.setVisible(false); } } ); ttv.botaoDisciplina.addActionListener( new ActionListener() { @Override public void actionPerformed(ActionEvent e ) { ControladorTelaTableDisciplina cttd = new ControladorTelaTableDisciplina(); cttd.executar(); ttv.setVisible(false); } } ); ttv.botaoCurso.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { ControladorTelaTableCurso cttc = new ControladorTelaTableCurso(); cttc.executar(); ttv.dispose(); } }); } /** * Método responsável por inicializar a tela controlada por esta classe. */ public void executar() { ttv.setVisible(true); } }
class Test1 { Test1(int x) { System.out.println("Constructor called " + x); } } // This class contains an instance of Test1 class GFGtest { Test1 t1 = new Test1(10); GFGtest(int i) { t1 = new Test1(i); } public static void main(String[] args) { GFGtest t2 = new GFGtest(5); } }
package com.kh.efp.band.model.vo; import java.io.Serializable; import org.springframework.stereotype.Repository; @Repository public class Ban implements Serializable{ private int banid; private int bid; private int mid; private String bantype; private String banreason; public Ban(){} public Ban(int banid, int bid, int mid, String bantype, String banreason) { super(); this.banid = banid; this.bid = bid; this.mid = mid; this.bantype = bantype; this.banreason = banreason; } public int getBanid() { return banid; } public void setBanid(int banid) { this.banid = banid; } public int getBid() { return bid; } public void setBid(int bid) { this.bid = bid; } public int getMid() { return mid; } public void setMid(int mid) { this.mid = mid; } public String getBantype() { return bantype; } public void setBantype(String bantype) { this.bantype = bantype; } public String getBanreason() { return banreason; } public void setBanreason(String banreason) { this.banreason = banreason; } @Override public String toString() { return "Ban [banid=" + banid + ", bid=" + bid + ", mid=" + mid + ", bantype=" + bantype + ", banreason=" + banreason + "]"; } }
/* * Copyright 2006 Ameer Antar. * * 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.antfarmer.ejce.parameter.salt; import java.security.GeneralSecurityException; /** * Interface which allows for matching an expected salt byte array during the decryption process. * @author Ameer Antar */ public interface SaltMatcher { /** * Callback used to match the expected salt byte array with the one found in the enciphered message during * decryption. If the expected and actual data do not match, a <code>GeneralSecurityException</code> may be thrown * to prevent the decryption process. * @param cipherSalt the actual salt data found in the enciphered message * @throws GeneralSecurityException if the expected and actual salt data do not match */ void verifySaltMatch(byte[] cipherSalt) throws GeneralSecurityException; }
package base; import global.Global; /** * Created by admin.son.ton on 1/26/18. */ public class BaseSteps { @SuppressWarnings("unchecked") protected <T extends PageObject> void visit(Class<T> page){ Global.getBrowser().goTo(Global.getPageHierachy().getPageUrl(page)); } @SuppressWarnings("unchecked") protected <T extends PageObject> void visitWithParam(Class<T> page, String param){ Global.getBrowser().goTo(Global.getPageHierachy().getPageUrl(page)+param); } @SuppressWarnings("unchecked") protected <T extends PageObject>T on(Class<T> page){ return (T) Global.getPageHierachy().getPageInstance(page); } }
/* * Copyright (c) 2012, ubivent GmbH, Thomas Butter, Oliver Seuffert * All right reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. * * This software is based on RFC6386 * * Copyright (c) 2010, 2011, Google Inc. All rights reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be * found in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ package com.ubivent.vp8; public class Frame { public final static int VPX_PLANE_Y = 0; /** < Y (Luminance) plane */ public final static int VPX_PLANE_U = 1; /** < U (Chroma) plane */ public final static int VPX_PLANE_V = 2; /** < V (Chroma) plane */ public final static int VPX_PLANE_ALPHA = 3; /** < A (Transparency) plane */ int d_w; int d_h; byte img_data[]; int w; int h; int stride[] = new int[3]; int planes[] = new int[3]; public Frame(int d_w, int d_h) { this.d_w = d_w; this.d_h = d_h; int bps = 12; int align = (1 << 1) - 1; int w = (d_w + align) & ~align; align = (1 << 1) - 1; int h = (d_h + align) & ~align; int s = bps * w / 8; int stride_align = 16; s = (s + stride_align - 1) & ~(stride_align - 1); img_data = new byte[h * s]; this.w = w; this.h = h; /* Calculate strides */ stride[VPX_PLANE_Y] = stride[VPX_PLANE_ALPHA] = s; stride[VPX_PLANE_U] = stride[VPX_PLANE_V] = s >> 1; /* Default viewport to entire image */ vpx_img_set_rect(0, 0, d_w, d_h); } void vpx_img_set_rect(int x, int y, int w, int h) { if (x + w <= this.w && y + h <= this.h) { this.d_w = w; this.d_h = h; int offset = 0; planes[VPX_PLANE_Y] = x + y * stride[VPX_PLANE_Y]; offset += this.h * stride[VPX_PLANE_Y]; planes[VPX_PLANE_U] = offset + (x >> 1) + (y >> 1) * stride[VPX_PLANE_U]; offset += (this.h >> 1) * stride[VPX_PLANE_U]; planes[VPX_PLANE_V] = offset + (x >> 1) + (y >> 1) * stride[VPX_PLANE_V]; } } }
execute(src, registers, memory) { if ( src.isMemory() ) { String env = memory.read(src, 48); String tag = env.substring(0, 4); String status = env.substring(4, 8); String control = env.substring(8, 12); registers.x87().control().setValue(control); registers.x87().status().setValue(status); registers.x87().tag().setValue(tag); } }
package org.newdawn.slick.geom; public interface TexCoordGenerator { Vector2f getCoordFor(float paramFloat1, float paramFloat2); } /* Location: C:\Users\BSV\AppData\Local\Temp\Rar$DRa6216.20396\Preview\Preview.jar!\org\newdawn\slick\geom\TexCoordGenerator.class * Java compiler version: 8 (52.0) * JD-Core Version: 1.1.3 */
package com.romariogrohmann.sistemagestaodevisitas; public class UsuarioLogado { }
package me.lengyan.dapr.springboot.autoconfigure; import me.lengyan.dapr.grpc.DaprCallbackService; import me.lengyan.dapr.springboot.DaprGrpcAdaptorRunner; import org.springframework.boot.autoconfigure.AutoConfigureOrder; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @AutoConfigureOrder @Configuration @ConditionalOnWebApplication public class DaprAdaptorAutoConfiguration { private static final String SWITCH_PROPERTY = "dapr.enabled"; @Bean @ConditionalOnProperty(value = SWITCH_PROPERTY, havingValue = "true") public DaprGrpcAdaptorRunner grpcAdaptorRunner() { return new DaprGrpcAdaptorRunner(); } @Bean //@ConditionalOnBean(DaprGrpcAdaptorRunner.class) public DaprCallbackService daprCallbackService() { return new DaprCallbackService(); } // TODO add GrpcClientInterceptor, starter非官方, 客户端使用方式不确定, 如何自动配置? 还是让用户自己写SPI services文件? }