text
stringlengths
10
2.72M
/** * @(#)ServiceRegistry.java, 2020/7/8. * <p/> * Copyright 2020 Netease, Inc. All rights reserved. * NETEASE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. */ package com.xx.rpc.registry; import org.apache.zookeeper.*; import org.apache.zookeeper.data.Stat; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.List; import java.util.concurrent.CountDownLatch; // 服务注册,使用zk public class ServiceRegistry { private static final Logger logger = LoggerFactory.getLogger(ServiceRegistry.class); private CountDownLatch latch = new CountDownLatch(1); private String registryAddress; public ServiceRegistry(String registryAddress){ this.registryAddress = registryAddress; } // 服务注册 public void register(String data){ if (data != null){ ZooKeeper zk = connectServer(); if (zk != null){ addRootNode(zk); createNode(zk,data); } } } // zk连接的方法 public ZooKeeper connectServer(){ ZooKeeper zk = null; try { zk = new ZooKeeper(registryAddress, Constant.ZK_SESSION_TIMEOUT, new Watcher() { @Override public void process(WatchedEvent event) { if (event.getState() == Event.KeeperState.SyncConnected){ logger.info("connect zk server"); latch.countDown(); } } }); // 阻塞住 latch.await(); } catch (IOException e) { logger.error("",e); } catch (InterruptedException e) { logger.error("",e); } return zk; } // 若父节点没有,就进行创建 private void addRootNode(ZooKeeper zk){ try { Stat stat = zk.exists(Constant.ZK_REGISTRY_PATH, false); if (stat == null){ zk.create(Constant.ZK_REGISTRY_PATH,new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE,CreateMode.PERSISTENT); } } catch (KeeperException e) { logger.error(e.toString()); } catch (InterruptedException e) { logger.error(e.toString()); } } // 创建子节点,临时有序 private void createNode(ZooKeeper zk, String data){ try { byte[] bytes = data.getBytes(); String path = zk.create(Constant.ZK_DATA_PATH, bytes, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL); logger.info("create zk node ({} -> {})",path,data); } catch (KeeperException e) { logger.error(e.toString()); } catch (InterruptedException e) { logger.error(e.toString()); } } public List<String> getNode(ZooKeeper zk){ List<String> children = null; try { children = zk.getChildren(Constant.ZK_REGISTRY_PATH, false); return children; } catch (KeeperException e) { logger.error(e.toString()); } catch (InterruptedException e) { logger.error(e.toString()); } return children; } }
package com.libedi.demo; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import org.junit.Before; import org.junit.Test; import org.modelmapper.ModelMapper; import org.modelmapper.TypeMap; import lombok.Builder; import lombok.Getter; import lombok.Setter; public class ModelMapperTest { private ModelMapper modelMapper; @Getter @Setter @Builder static class User { private String name; private String address; } @Getter @Setter static class UserDto { private String userNm; private String userAddr; } @Before public void before() { modelMapper = new ModelMapper(); } @Test public void testNoTypeMap() { User user = User.builder().name("nam1").address("addr1").build(); UserDto dto = modelMapper.map(user, UserDto.class); assertNull(dto.getUserNm()); assertNull(dto.getUserAddr()); } @Test public void testTypeMap() { final TypeMap<User, UserDto> typeMap = modelMapper.createTypeMap(User.class, UserDto.class); typeMap.addMappings(mapper -> mapper.map(User::getName, UserDto::setUserNm)) .addMappings(mapper -> mapper.map(User::getAddress, UserDto::setUserAddr)) ; User user = User.builder().name("nam1").address("addr1").build(); UserDto dto = modelMapper.map(user, UserDto.class); assertEquals(user.getName(), dto.getUserNm()); assertEquals(user.getAddress(), dto.getUserAddr()); } }
/* * Created by Devlomi on 2021 */ package net.trejj.talk; import android.app.Notification; import android.app.NotificationChannel; import android.app.NotificationManager; import android.app.PendingIntent; import android.app.Service; import android.app.TaskStackBuilder; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.os.Build; import android.os.IBinder; import android.util.Log; import androidx.annotation.Nullable; import androidx.core.app.NotificationCompat; import net.trejj.talk.activities.CallScreenActivity; import net.trejj.talk.activities.main.MainActivity; public class CallRunningService extends Service { public static final String CHANNEL_ID = "ForegroundServiceChannel"; @Override public void onCreate() { super.onCreate(); } @Override public int onStartCommand(Intent intent, int flags, int startId) { // String input = intent.getStringExtra("inputExtra"); createNotificationChannel(); SharedPreferences preferences = this.getSharedPreferences("net.trejj.talk", Context.MODE_PRIVATE); String number = preferences.getString("number",""); String callername = preferences.getString("callername",""); Intent notificationIntent = new Intent(this, CallScreenActivity.class) .putExtra("callername",callername).putExtra("number",number) .putExtra("isCallInProgress",true); PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0); Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID) .setContentTitle("Trejj Talk") .setContentText("Call in progress") .setSmallIcon(R.drawable.ic_call) .setContentIntent(pendingIntent) .build(); Log.i("starrrr","start"); startForeground(1, notification); //do heavy work on a background thread //stopSelf(); return START_STICKY; } @Override public void onDestroy() { super.onDestroy(); Log.i("starrrr","destroy"); } @Nullable @Override public IBinder onBind(Intent intent) { return null; } private void createNotificationChannel() { Log.i("starrrr","noti"); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { NotificationChannel serviceChannel = new NotificationChannel( CHANNEL_ID, "Foreground Service Channel", NotificationManager.IMPORTANCE_DEFAULT ); NotificationManager manager = getSystemService(NotificationManager.class); manager.createNotificationChannel(serviceChannel); } } }
package gameGraphics; //import java.awt.event.MouseAdapter; //same as below import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.WindowEvent; //import java.awt.event.WindowAdapter; //maybe change to adapter later if some Events are not needed import java.awt.event.WindowListener; public class ListenerHandler { public static WindowListener getMainFrameWindowListener(GameGraphics gGraph) { return new WindowListener() { @Override public void windowClosing(WindowEvent e) { //TODO: display "do you want to quit?" -> send signal to GameMechanics System.exit(0); } @Override public void windowOpened(WindowEvent e) { // TODO Auto-generated method stub } @Override public void windowClosed(WindowEvent e) { // TODO Auto-generated method stub } @Override public void windowIconified(WindowEvent e) { // TODO Auto-generated method stub System.out.println("minimized"); } @Override public void windowDeiconified(WindowEvent e) { // TODO Auto-generated method stub System.out.println("unminimized"); } @Override public void windowActivated(WindowEvent e) { // TODO Auto-generated method stub } @Override public void windowDeactivated(WindowEvent e) { // TODO Auto-generated method stub } }; } public static MouseListener getMainFrameMouseListener(final GameGraphics gGraph) { return new MouseListener() { @Override public void mouseClicked(MouseEvent e) { // TODO Send signal to GameMechanics gGraph.getGameMechanics(); System.out.println("click"); } @Override public void mousePressed(MouseEvent e) { // TODO Send signal to GameMechanics gGraph.getGameMechanics(); } @Override public void mouseReleased(MouseEvent e) { // TODO Send signal to GameMechanics } @Override public void mouseEntered(MouseEvent e) { // TODO Send signal to GameMechanics } @Override public void mouseExited(MouseEvent e) { // TODO Send signal to GameMechanics } }; } public static KeyListener getMainFrameKeyListener() { return new KeyListener() { @Override public void keyTyped(KeyEvent e) { // TODO Auto-generated method stub } @Override public void keyPressed(KeyEvent e) { // TODO Auto-generated method stub } @Override public void keyReleased(KeyEvent e) { // TODO Auto-generated method stub } }; } }
package com.studio.saradey.aplicationvk.model.view; import android.view.View; import android.widget.RelativeLayout; import com.studio.saradey.aplicationvk.R; import com.studio.saradey.aplicationvk.ui.holder.BaseViewHolder; import butterknife.BindView; import butterknife.ButterKnife; /** * @author jtgn on 14.08.2018 */ public class InfoContactsViewModel extends BaseViewModel { @Override public LayoutTypes getType() { return LayoutTypes.InfoContacts; } @Override public InfoContactsViewHolder onCreateViewHolder(View view) { return new InfoContactsViewHolder(view); } static class InfoContactsViewHolder extends BaseViewHolder<InfoContactsViewModel> { @BindView(R.id.rv_contacts) RelativeLayout rvContacts; public InfoContactsViewHolder(View itemView) { super(itemView); ButterKnife.bind(this, itemView); } @Override public void bindViewHolder(InfoContactsViewModel infoContactsViewModel) { } @Override public void unbindViewHolder() { } } }
package com.suirui.drouter.circle.router.service; import android.content.Context; import com.suirui.drouter.annotation.Route; import com.suirui.drouter.core.ZRouter; import org.suirui.drouter.common.module.circle.path.CirclePathContant; import org.suirui.drouter.common.module.circle.service.CircleService; @Route(path = CirclePathContant.PATH_SERVICE_CIRCLE) public class CircleServiceImpl implements CircleService { @Override public void startToCircle() { ZRouter.getsInstance().build(CirclePathContant.PATH_VIEW_CIRCLE).navigation(); } @Override public void init(Context context) { } }
package com.yoeki.kalpnay.hrporatal.EventAndTraining; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.DefaultItemAnimator; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.View; import android.widget.ImageView; import com.yoeki.kalpnay.hrporatal.R; import java.util.ArrayList; public class EventTrainingHome extends AppCompatActivity implements View.OnClickListener{ RecyclerView rcy_eventandtraining; ImageView img_eventtraingback; ArrayList<EventModel>arrayList; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_event_training_home); arrayList=new ArrayList<>(); initialize(); adddata(); img_eventtraingback.setOnClickListener(this); } @Override public void onClick(View v) { switch (v.getId()){ case R.id.img_eventtraingback: finish(); break; } } public void initialize(){ rcy_eventandtraining=findViewById(R.id.rcy_eventandtraining); img_eventtraingback=findViewById(R.id.img_eventtraingback); } public void adddata(){ EventModel data=new EventModel(); data.setTitle("Holi Event"); data.setDiscription("Dipawali event "); data.setLocation("Noida"); data.setVendor("Genger Hotel"); data.setFromdate("04/04/2019"); data.setTodate("06/04/2019"); data.setFromtime("10:00 AM"); data.setTotime("4:00 PM"); data.setDuration("6 hrs"); arrayList.add(data); EventModel data1=new EventModel(); data1.setTitle("Dot Net Training"); data1.setDiscription("Dot net training ."); data1.setLocation("Noida"); data1.setVendor("AMY Softtech"); data1.setFromdate("04/04/2019"); data1.setTodate("06/04/2019"); data1.setFromtime("10:00 AM"); data1.setTotime("4:00 PM"); data1.setDuration("6 hrs"); arrayList.add(data1); EventModel data2=new EventModel(); data2.setTitle("Holi Event"); data2.setDiscription("Dipawali event "); data2.setLocation("Noida"); data2.setVendor("Genger Hotel"); data2.setFromdate("04/04/2019"); data2.setTodate("06/04/2019"); data2.setFromtime("10:00 AM"); data2.setTotime("4:00 PM"); data2.setDuration("6 hrs"); arrayList.add(data2); EventModel data3=new EventModel(); data3.setTitle("Dot Net Training"); data3.setDiscription("Dot net training ."); data3.setLocation("Noida"); data3.setVendor("AMY Softtech"); data3.setFromdate("04/04/2019"); data3.setTodate("06/04/2019"); data3.setFromtime("10:00 AM"); data3.setTotime("4:00 PM"); data3.setDuration("6 hrs"); arrayList.add(data3); EventAdapter adapter = new EventAdapter(EventTrainingHome.this, arrayList); rcy_eventandtraining.setLayoutManager(new LinearLayoutManager(EventTrainingHome.this, LinearLayoutManager.VERTICAL, false)); // rec_leavereqattachment.setLayoutManager(new Hori); rcy_eventandtraining.setItemAnimator(new DefaultItemAnimator()); rcy_eventandtraining.setAdapter(adapter); } }
package com.gabriel.paiva.cursomc.cursomc.services; import com.gabriel.paiva.cursomc.cursomc.domains.Categoria; import com.gabriel.paiva.cursomc.cursomc.domains.Pedido; import com.gabriel.paiva.cursomc.cursomc.domains.Produto; import com.gabriel.paiva.cursomc.cursomc.exceptions.ObjectNotFoundException; import com.gabriel.paiva.cursomc.cursomc.repositories.CategoriaRepository; import com.gabriel.paiva.cursomc.cursomc.repositories.PedidoRepository; import com.gabriel.paiva.cursomc.cursomc.repositories.ProdutoRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Sort; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.List; import java.util.Optional; @Service public class ProdutoService { @Autowired private ProdutoRepository produtoRepository; @Autowired private CategoriaRepository categoriaRepository; public Produto buscar (Integer id){ Optional<Produto> produto = produtoRepository.findById(id); return produto.orElseThrow(() -> new ObjectNotFoundException("Objeto com ID (" + id + ") não encontrado.") ); } public Page<Produto> search(String nome, List<Integer> ids,Integer page, Integer linesPerPage, String orderBy, String direction){ PageRequest pageRequest = PageRequest.of(page,linesPerPage, Sort.Direction.valueOf(direction),orderBy); List<Categoria> categorias = categoriaRepository.findAllById(ids); return produtoRepository.findDistinctByNomeContainingAndCategoriasIn(pageRequest,nome, categorias); } }
package com.yangql; import java.util.Hashtable; import java.util.Map; import java.util.Random; public class Game { //global private static Map<Long, String>pendingGames=new Hashtable<Long, String>(); private static Map<Long, Game>activeGames=new Hashtable<Long, Game>(); private static long gameIdSequence = 1L; //class member private long id; private String player1; private String player2; private Player whoFirst = Player.random(); private boolean over; public Game(long id,String player1,String player2) { this.id=id; this.player1=player1; this.player2=player2; } public static Map<Long, String> getPendingGames() { return pendingGames; } public static long queueGame(String user1) { long id = gameIdSequence++; pendingGames.put(id, user1); return id; } public static void removeQueuedGame(long queuedId) { pendingGames.remove(queuedId); } public static Game startGames(long queuedId, String user2) { String user1 = pendingGames.remove(queuedId); Game game = new Game(queuedId, user1, user2); activeGames.put(queuedId, game); return game; } public static Game getActiveGame(long gameId) { return activeGames.get(gameId); } //游戏是否结束 public void setOver() { this.over=true; } public boolean isOver() { return over; } //中途退出 public synchronized void forfeit(Player player) { Game.activeGames.remove(this.id); this.over = true; } //getter public long getId() { return id; } public String getPlayer1() { return player1; } public String getPlayer2() { return player2; } //决定开球者 public String getWhoFirst() { return whoFirst == Player.PLAYER1 ? player1 : player2; } public enum Player { PLAYER1, PLAYER2; private static final Random random = new Random(); private static Player random() { return Player.random.nextBoolean() ? PLAYER1 : PLAYER2; } } }
package com.yqwl.controller; import java.sql.Timestamp; import java.text.SimpleDateFormat; import java.util.Map; import javax.annotation.Resource; import javax.servlet.http.HttpSession; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.multipart.MultipartFile; import com.yqwl.common.utils.Constants; import com.yqwl.common.utils.FastJsonUtil; import com.yqwl.pojo.News; import com.yqwl.pojo.NewsImg; import com.yqwl.pojo.User; import com.yqwl.service.NewsService; @Controller @RequestMapping("news") @Scope("prototype") public class NewsController { @Resource private NewsService newsService; private final Logger logger = LoggerFactory.getLogger(getClass()); @RequestMapping(value = "list", method = RequestMethod.GET, produces = Constants.HTML_PRODUCE_TYPE) public String list() { return "views/back/NewsManagement/CompanyManagement"; } @RequestMapping(value = "add", method = RequestMethod.GET, produces = Constants.HTML_PRODUCE_TYPE) public String add() { return "views/back/NewsManagement/addNewsManagement"; } /** * * @Title: addNews * @description: 插入新闻咨讯 * * @param news * @param session * @return * @return String * * @author HanMeng * @createDate 2019年2月18日-下午3:56:16 */ @ResponseBody @RequestMapping(value = "insert", method = RequestMethod.POST) public String addNews(@RequestBody News news, HttpSession session) { int code = 0; String msg = null; try { User admin = (User) session.getAttribute("login_user"); if (admin != null) { int i = newsService.insert(news); if (i != 0) { code = 0; msg = "新增咨讯成功"; return FastJsonUtil.getResponseJson(code, msg, null); } code = 1; msg = "新增咨讯失败"; return FastJsonUtil.getResponseJson(code, msg, null); } else { code = 2; msg = "您没有登录账号!"; return FastJsonUtil.getResponseJson(code, msg, null); } } catch (Exception e) { code = -1; msg = "系统异常"; logger.error(e.getMessage(), e); return FastJsonUtil.getResponseJson(code, msg, e); } } /** * * @Title: addGoodsImg * @description: 添加新闻咨讯图片 * * @param file * @param id * @param session * @return * @return String * * @author HanMeng * @createDate 2019年2月18日-下午3:56:34 */ @ResponseBody @RequestMapping(value = "addNewsImg", method = RequestMethod.POST) public String addNewsImg(@RequestBody NewsImg newsImg, HttpSession session) { int code = 0; String msg = null; try { User admin = (User) session.getAttribute("login_user"); if (admin != null) { int i = newsService.addNewsImg(newsImg); if (i != 0) { code = 0; msg = "新增成功"; return FastJsonUtil.getResponseJson(code, msg, i); } code = 1; msg = "新增失败"; return FastJsonUtil.getResponseJson(code, msg, null); } else { code = 2; msg = "未登录"; return FastJsonUtil.getResponseJson(code, msg, null); } } catch (Exception e) { code = -1; msg = "系统异常"; logger.error(e.getMessage(), e); return FastJsonUtil.getResponseJson(code, msg, e); } } /** * * @Title: deleteNewsImg * @description: 删除咨讯图片 * * @param id * @param session * @return * @return String * * @author HanMeng * @createDate 2019年2月18日-下午3:58:36 */ @ResponseBody @RequestMapping(value = "deleteNewsImg", method = RequestMethod.POST, produces = Constants.HTML_PRODUCE_TYPE) public String deleteNewsImg(Long id, HttpSession session) { int code = 0; String msg = null; try { User admin = (User) session.getAttribute("login_user"); if (admin != null) { int i = newsService.deleteNewsImg(id); if (i != 0) { code = 0; msg = "删除成功"; return FastJsonUtil.getResponseJson(code, msg, null); } code = 1; msg = "删除失败"; return FastJsonUtil.getResponseJson(code, msg, null); } else { code = 2; msg = "未登录"; return FastJsonUtil.getResponseJson(code, msg, null); } } catch (Exception e) { code = -1; msg = "系统异常"; logger.error(e.getMessage(), e); return FastJsonUtil.getResponseJson(code, msg, e); } } /** * * @Title: updates * @description 用一句话描述这个方法的作用 * * @param @return * @return String * * @author 姓名全拼 * @createDate 2019年4月15日 */ @RequestMapping(value = "updates", method = RequestMethod.GET, produces = Constants.HTML_PRODUCE_TYPE) public String update(Long id,Model model) { try { News news = newsService.getById(id); SimpleDateFormat sdf =new SimpleDateFormat("yyyy-MM-dd HH:mm:ss" ); String str = sdf.format(news.getTime()); model.addAttribute("time", str); model.addAttribute("news", news); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return "views/back/NewsManagement/updateNewsManagement"; } /** * * @Title: update * @description: 修改咨讯 * * @param news * @param session * @return * @return String * * @author HanMeng * @createDate 2019年2月18日-下午3:58:49 */ @ResponseBody @RequestMapping(value = "update") public String update(@RequestBody News news, HttpSession session) { int code = 0; String msg = null; try { User admin = (User) session.getAttribute("login_user"); if (admin != null) { int i = newsService.update(news); if (i != 0) { code = 0; msg = "修改案例成功"; return FastJsonUtil.getResponseJson(code, msg, i); } code = 1; msg = "修改案例失败"; return FastJsonUtil.getResponseJson(code, msg, null); } else { code = 2; msg = "未登录"; return FastJsonUtil.getResponseJson(code, msg, null); } } catch (Exception e) { code = -1; msg = "系统异常"; logger.error(e.getMessage(), e); return FastJsonUtil.getResponseJson(code, msg, e); } } /** * * @Title: updates * @description: 修改咨讯 * * @param news * @param session * @return * @return String * * @author HanMeng * @createDate 2019年2月18日-下午3:58:49 */ @ResponseBody @RequestMapping(value = "updateStatus", method = RequestMethod.POST) public String updateStatus(@RequestBody News news, HttpSession session) { int code = 0; String msg = null; try { User admin = (User) session.getAttribute("login_user"); if (admin != null) { int i = newsService.updateStatus(news); if (i != 0) { code = 0; msg = "修改案例成功"; return FastJsonUtil.getResponseJson(code, msg, i); } code = 1; msg = "修改案例失败"; return FastJsonUtil.getResponseJson(code, msg, null); } else { code = 2; msg = "未登录"; return FastJsonUtil.getResponseJson(code, msg, null); } } catch (Exception e) { code = -1; msg = "系统异常"; logger.error(e.getMessage(), e); return FastJsonUtil.getResponseJson(code, msg, e); } } /** * * @Title: delete * @description: 根据主键删除咨讯 * * @param id * @param session * @return * @return String * * @author HanMeng * @createDate 2019年2月17日-下午1:25:50 */ @ResponseBody @RequestMapping(value = "delete", method = RequestMethod.POST, produces = Constants.HTML_PRODUCE_TYPE) public String update(Long id, HttpSession session) { int code = 0; String msg = null; try { User admin = (User) session.getAttribute("login_user"); if (admin != null) { int i = newsService.deleteByPrimaryKey(id); if (i != 0) { code = 0; msg = "删除咨讯成功"; return FastJsonUtil.getResponseJson(code, msg, i); } code = 1; msg = "删除咨讯失败"; return FastJsonUtil.getResponseJson(code, msg, null); } else { code = 2; msg = "未登录"; return FastJsonUtil.getResponseJson(code, msg, null); } } catch (Exception e) { code = -1; msg = "系统异常"; logger.error(e.getMessage(), e); return FastJsonUtil.getResponseJson(code, msg, e); } } /** * * @Title: getById * @description: 根据id查询咨讯 * * @param id * @param session * @return * @return String * * @author HanMeng * @createDate 2019年2月17日-下午1:34:05 */ @ResponseBody @RequestMapping(value = "getById", method = RequestMethod.POST, produces = Constants.HTML_PRODUCE_TYPE) public String getById(Long id) { int code = 0; String msg = null; try { News news = newsService.getById(id); System.out.println(news); if (news != null) { code = 0; msg = "查询成功"; return FastJsonUtil.getResponseJson(code, msg, news); } code = 1; msg = "查询失败"; return FastJsonUtil.getResponseJson(code, msg, null); } catch (Exception e) { code = -1; msg = "系统异常"; logger.error(e.getMessage(), e); return FastJsonUtil.getResponseJson(code, msg, e); } } /** * * @Title: listAll * @description: 分页查询所有咨讯 * * @param page * @param limit * @param session * @return * @return String * * @author HanMeng * @createDate 2019年2月18日-上午10:09:18 */ @ResponseBody @RequestMapping(value = "listAll", method = RequestMethod.POST, produces = Constants.HTML_PRODUCE_TYPE) public String listAll(Integer page, Integer limit) { int code = 0; String msg = null; try { Map<String, Object> news = newsService.listAll(page, limit); if (news.size() != 0) { code = 0; msg = "查询成功"; return FastJsonUtil.getResponseJson(code, msg, news); } code = 1; msg = "查询失败"; return FastJsonUtil.getResponseJson(code, msg, null); } catch (Exception e) { code = -1; msg = "系统异常"; logger.error(e.getMessage(), e); return FastJsonUtil.getResponseJson(code, msg, e); } } /** * * @Title: listAll * @description: 分页查询所有咨讯 * * @param page * @param limit * @param session * @return * @return String * * @author HanMeng * @createDate 2019年2月18日-上午10:09:18 */ @ResponseBody @RequestMapping(value = "listMovement", method = RequestMethod.POST, produces = Constants.HTML_PRODUCE_TYPE) public String getBusinessMovement(Integer page, Integer limit) { int code = 0; String msg = null; try { Map<String, Object> news = newsService.getBusinessMovement("企业动态", page, limit); //System.out.println(news.get("list")); if (news.size() != 0) { code = 0; msg = "查询成功"; return FastJsonUtil.getResponseJson(code, msg, news); } code = 1; msg = "查询失败"; return FastJsonUtil.getResponseJson(code, msg, null); } catch (Exception e) { code = -1; msg = "系统异常"; logger.error(e.getMessage(), e); return FastJsonUtil.getResponseJson(code, msg, e); } } }
/** * Copyright 2013-present febit.org (support@febit.org) * * 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.febit.leancloud; import java.io.Serializable; /** * * @author zqq90 */ public abstract class Entity implements Serializable { public class ACL { //FIXME: } // objectId protected String id; protected ACL ACL; protected String createdAt; protected String updatedAt; public String id() { return id; } public void id(String id) { this.id = id; } public boolean _isPersistent() { return this.id != null; } @Override public int hashCode() { return id != null ? id.hashCode() : 0; } @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (obj == null || this.getClass() != obj.getClass()) { return false; } final String eid = ((Entity) obj).id(); final String myId = id(); if ((myId == null) || (eid == null)) { return false; } return myId.equals(eid); } public String getId() { return id; } public void setId(String id) { this.id = id; } /** * @param id * @deprecated only for json parser */ @Deprecated public void setObjectId(String id) { this.id = id; } public ACL getACL() { return ACL; } public void setACL(ACL ACL) { this.ACL = ACL; } public String getCreatedAt() { return createdAt; } public void setCreatedAt(String createdAt) { this.createdAt = createdAt; } public String getUpdatedAt() { return updatedAt; } public void setUpdatedAt(String updatedAt) { this.updatedAt = updatedAt; } @Override public String toString() { return this.getClass().getSimpleName() + "[ id=" + id() + " ]"; } }
/* * [y] hybris Platform * * Copyright (c) 2017 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.commerceservices.consent.interceptors; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import de.hybris.bootstrap.annotations.IntegrationTest; import de.hybris.platform.basecommerce.model.site.BaseSiteModel; import de.hybris.platform.commerceservices.consent.dao.impl.DefaultConsentTemplateDao; import de.hybris.platform.commerceservices.model.consent.ConsentModel; import de.hybris.platform.commerceservices.model.consent.ConsentTemplateModel; import de.hybris.platform.core.model.user.CustomerModel; import de.hybris.platform.servicelayer.ServicelayerTest; import de.hybris.platform.servicelayer.model.ModelService; import de.hybris.platform.servicelayer.user.UserService; import de.hybris.platform.site.BaseSiteService; import javax.annotation.Resource; import org.apache.commons.lang.StringUtils; import org.junit.Before; import org.junit.Test; @IntegrationTest public class DefaultConsentPrepareInterceptorTest extends ServicelayerTest { private static final String CONSENT_TEMPLATE_ID = "CONSENT_TEMPLATE_1"; private static final String TEST_BASESITE_UID = "testSite"; private static final String TEST_CUSTOMER_UID = "testcustomer"; // must be lower case! @Resource private DefaultConsentTemplateDao defaultConsentTemplateDao; @Resource private UserService userService; @Resource private ModelService modelService; @Resource private BaseSiteService baseSiteService; private BaseSiteModel baseSite; private CustomerModel customer; @Before public void setUp() throws Exception { // importing test csv importCsv("/commerceservices/test/testConsents.impex", "utf-8"); baseSite = baseSiteService.getBaseSiteForUID(TEST_BASESITE_UID); customer = userService.getUserForUID(TEST_CUSTOMER_UID, CustomerModel.class); } @Test public void shouldVerifyWhetherConsentCodeIsGenerated() { final ConsentTemplateModel consentTemplate = defaultConsentTemplateDao .findLatestConsentTemplateByIdAndSite(CONSENT_TEMPLATE_ID, baseSite); assertNotNull("consentTemplate should not be null", consentTemplate); final ConsentModel consent = modelService.create(ConsentModel.class); consent.setConsentTemplate(consentTemplate); consent.setCustomer(customer); assertTrue("Consent Code should be blank", StringUtils.isBlank(consent.getCode())); modelService.save(consent); modelService.refresh(consent); assertTrue("Consent Code should not be blank", StringUtils.isNotBlank(consent.getCode())); } }
package mk.petrovski.weathergurumvp.ui.about; /** * Created by Nikola Petrovski on 2/14/2017. */ public class AboutPresenter { }
import java.io.IOException; import java.util.Scanner; public class Main { private static Scanner scanner; private static String stringOrFile; public static void main(String[] args) throws IOException { SwitchStringFile switchStringFile = new SwitchStringFile(); do { System.out.println("What do you want to do? \n1 - work whit strings\n2 - work whit files"); scanner = new Scanner( System.in ); stringOrFile = scanner.nextLine(); if(stringOrFile.equals( "1" )) { System.out.println("Strings"); switchStringFile.SwitchString(); }else if (stringOrFile.equals( "2" )){ System.out.println("Files"); switchStringFile.SwitchFile(); } }while (!stringOrFile.equals( "1" ) && !stringOrFile.equals( "2" )); } }
/** * This file is part of * * CRAFTY - Competition for Resources between Agent Functional TYpes * * Copyright (C) 2014 School of GeoScience, University of Edinburgh, Edinburgh, UK * * CRAFTY is free software: You can redistribute it and/or modify it under the * terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * CRAFTY is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * School of Geoscience, University of Edinburgh, Edinburgh, UK */ package org.volante.abm.serialization; import java.awt.event.WindowAdapter; import java.util.ArrayList; import java.util.List; import javax.swing.BoxLayout; import javax.swing.JFrame; import org.apache.commons.cli.BasicParser; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.OptionBuilder; import org.apache.commons.cli.Options; import org.apache.log4j.Logger; import org.volante.abm.institutions.global.GlobalInstitutionsRegistry; import org.volante.abm.param.RandomPa; import org.volante.abm.schedule.PrePreTickAction; import org.volante.abm.schedule.RunInfo; import org.volante.abm.schedule.ScheduleThread; import org.volante.abm.visualisation.ScheduleControls; import org.volante.abm.visualisation.TimeDisplay; import de.cesr.lara.components.model.impl.LModel; import de.cesr.more.basic.MManager; import de.cesr.more.util.MVersionInfo; import de.cesr.parma.core.PmParameterManager; import mpi.MPI; public class ModelRunner { static final String CONFIG_LOGGER_NAME = "crafty.config"; /** * Logger */ static private Logger logger = Logger.getLogger(ModelRunner.class); static private Logger clogger = Logger.getLogger(CONFIG_LOGGER_NAME); /** * loader and interactive controls for further use (by ABS in 2020) */ static private ScenarioLoader loader; static public JFrame interactiveControls; public static void clog(String property, String value) { clogger.info(property + ": \t" + value); } public static Logger getConfigLogger() { return clogger; } protected static RunInfo rInfo = null; public static void main(String[] args) throws Exception { logger.info("Start CRAFTY CoBRA"); String[] realArgs = null; try { Class.forName("mpi.MPI"); realArgs = MPI.Init(args); } catch (NoClassDefFoundError e) { logger.error("No MPI in classpath (this message can be ignored if not running in parallel)!"); realArgs = args; } catch (ClassNotFoundException e) { logger.error("No MPI in classpath (this message can be ignored if not running in parallel)!"); realArgs = args; } catch (UnsatisfiedLinkError e) { logger.error( "MPI is in classpath but not linked to shared libraries correctly (this message can be ignored if not running in parallel)!"); realArgs = args; } CommandLineParser parser = new BasicParser(); CommandLine cmd = parser.parse(manageOptions(), realArgs); if (cmd.hasOption('h')) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("CRAFTY", manageOptions()); System.exit(0); } boolean interactive = cmd.hasOption("i"); String filename = cmd.hasOption("f") ? cmd.getOptionValue('f') : "xml/test-scenario.xml"; String directory = cmd.hasOption("d") ? cmd.getOptionValue('d') : "data"; int start = cmd.hasOption("s") ? Integer.parseInt(cmd.getOptionValue('s')) : Integer.MIN_VALUE; int end = cmd.hasOption("e") ? Integer.parseInt(cmd.getOptionValue('e')) : Integer.MIN_VALUE; int numRuns = cmd.hasOption("n") ? Integer.parseInt(cmd.getOptionValue('n')) : 1; int startRun = cmd.hasOption("sr") ? Integer.parseInt(cmd.getOptionValue("sr")) : 0; int numOfRandVariation = cmd.hasOption("r") ? Integer.parseInt(cmd.getOptionValue('r')) : 1; clog("Scenario-File", filename); clog("DataDir", directory); clog("StartTick", "" + (start == Integer.MIN_VALUE ? "<ScenarioFile>" : start)); clog("EndTick", "" + (end == Integer.MIN_VALUE ? "<ScenarioFile>" : end)); clog("CRAFY_CoBRA Revision", CVersionInfo.REVISION_NUMBER); clog("CRAFY_CoBRA BuildDate", CVersionInfo.TIMESTAMP); clog("MoRe Revision", MVersionInfo.revisionNumber); clog("MoRe BuildDate", MVersionInfo.timeStamp); if (end < start) { logger.error("End tick must not be larger than start tick!"); System.exit(0); } if (startRun > numRuns) { logger.error("StartRun must not be larger than number of runs!"); System.exit(0); } for (int i = startRun; i < numRuns; i++) { for (int j = 0; j < numOfRandVariation; j++) { int randomSeed = cmd.hasOption('o') ? (j + Integer.parseInt(cmd.getOptionValue('o'))) : (int) System.currentTimeMillis(); // Worry about random seeds here... rInfo = new RunInfo(); rInfo.setNumRuns(numRuns); rInfo.setNumRandomVariations(numOfRandVariation); rInfo.setCurrentRun(i); rInfo.setCurrentRandomSeed(randomSeed); ABMPersister.getInstance().setBaseDir(directory); if (cmd.hasOption("se") ? BatchRunParser.parseInt(cmd.getOptionValue("se"), rInfo) == 1 : true) { clog("CurrentRun", "" + i); clog("TotalRuns", "" + numRuns); clog("CurrentRandomSeed", "" + randomSeed); clog("TotalRandomSeeds", "" + numOfRandVariation); PmParameterManager.getInstance(null).setParam(RandomPa.RANDOM_SEED, randomSeed); doRun(filename, start, end, interactive); rInfo = null; } } } try { Class.forName("mpi.MPI"); MPI.Finalize(); } catch (ClassNotFoundException e) { logger.info("Error during MPI finilization. No MPI in classpath!"); // e.printStackTrace(); } catch (NoClassDefFoundError ncde) { logger.info("Error during MPI finilization. No MPI class linked!"); // ncde.printStackTrace(); } catch (Exception exception) { logger.info("Error during MPI finilization: " + exception.getMessage()); exception.printStackTrace(); } } public RunInfo EXTprepareRrun(String[] args) throws Exception { logger.info("Start CRAFTY CoBRA"); String[] realArgs = null; try { Class.forName("mpi.MPI"); realArgs = MPI.Init(args); } catch (NoClassDefFoundError e) { logger.error("No MPI in classpath (this message can be ignored if not running in parallel)!"); realArgs = args; } catch (ClassNotFoundException e) { logger.error("No MPI in classpath (this message can be ignored if not running in parallel)!"); realArgs = args; } catch (UnsatisfiedLinkError e) { logger.error( "MPI is in classpath but not linked to shared libraries correctly (this message can be ignored if not running in parallel)!"); realArgs = args; } CommandLineParser parser = new BasicParser(); CommandLine cmd = parser.parse(manageOptions(), realArgs); if (cmd.hasOption('h')) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("CRAFTY", manageOptions()); return (null); } boolean interactive = cmd.hasOption("i"); String filename = cmd.hasOption("f") ? cmd.getOptionValue('f') : "xml/test-scenario.xml"; String directory = cmd.hasOption("d") ? cmd.getOptionValue('d') : "data"; int start = cmd.hasOption("s") ? Integer.parseInt(cmd.getOptionValue('s')) : Integer.MIN_VALUE; int end = cmd.hasOption("e") ? Integer.parseInt(cmd.getOptionValue('e')) : Integer.MIN_VALUE; int numRuns = cmd.hasOption("n") ? Integer.parseInt(cmd.getOptionValue('n')) : 1; int startRun = cmd.hasOption("sr") ? Integer.parseInt(cmd.getOptionValue("sr")) : 0; if (numRuns - startRun != 1) { logger.error("CRAFTY R-JAVA API does not allow multiple runs in one call (yet in 2020)."); return (null); } int numOfRandVariation = cmd.hasOption("r") ? Integer.parseInt(cmd.getOptionValue('r')) : 1; if (numOfRandVariation > 1) { logger.error("CRAFTY R-JAVA API does not allow multiple random variations in one call (yet in 2020)."); return (null); } clog("Scenario-File", filename); clog("DataDir", directory); clog("StartTick", "" + (start == Integer.MIN_VALUE ? "<ScenarioFile>" : start)); clog("EndTick", "" + (end == Integer.MIN_VALUE ? "<ScenarioFile>" : end)); clog("CRAFY_CoBRA Revision", CVersionInfo.REVISION_NUMBER); clog("CRAFY_CoBRA BuildDate", CVersionInfo.TIMESTAMP); clog("MoRe Revision", MVersionInfo.revisionNumber); clog("MoRe BuildDate", MVersionInfo.timeStamp); if (end < start) { logger.error("End tick must not be larger than start tick!"); return (null); } if (startRun > numRuns) { logger.error("StartRun must not be larger than number of runs!"); return (null); } // for (int i = startRun; i < numRuns; i++) { // for (int j = 0; j < numOfRandVariation; j++) { int i = startRun; int j = numOfRandVariation; int randomSeed = cmd.hasOption('o') ? (j + Integer.parseInt(cmd.getOptionValue('o'))) : (int) System.currentTimeMillis(); // Worry about random seeds here... rInfo = new RunInfo(); rInfo.setNumRuns(numRuns); rInfo.setNumRandomVariations(numOfRandVariation); rInfo.setCurrentRun(i); rInfo.setCurrentRandomSeed(randomSeed); ABMPersister.getInstance().setBaseDir(directory); if (cmd.hasOption("se") ? BatchRunParser.parseInt(cmd.getOptionValue("se"), rInfo) == 1 : true) { clog("CurrentRun", "" + i); clog("TotalRuns", "" + numRuns); clog("CurrentRandomSeed", "" + randomSeed); clog("TotalRandomSeeds", "" + numOfRandVariation); PmParameterManager.getInstance(null).setParam(RandomPa.RANDOM_SEED, randomSeed); logger.info("doRuninR"); logger.info("SetLoader to setup a run"); setLoader(setupRun(filename, start, end)); return (rInfo); } start = start == Integer.MIN_VALUE ? loader.startTick : start; end = end == Integer.MIN_VALUE ? loader.endTick : end; // when no run was done rInfo = null; return (rInfo); } public ScenarioLoader EXTsetSchedule(int start, int end) { logger.info( String.format("Running from %s to %s\n", (start == Integer.MIN_VALUE ? "<ScenarioFile>" : start + ""), (end == Integer.MIN_VALUE ? "<ScenarioFile>" : end + ""))); ScenarioLoader loader = getLoader(); if (end != Integer.MIN_VALUE) { if (start != Integer.MIN_VALUE) { logger.info("Starting run for set number of ticks"); logger.info("Start: " + start + ", End: " + end); // loader.schedule.runFromTo(start, end); should not use because it finalises loader.schedule.setStartTick(start); loader.schedule.setEndTick(end); } } return (loader); } public int EXTtick() { ScenarioLoader loader = getLoader(); loader.schedule.tick(); int currentTick = loader.schedule.getCurrentTick(); return (currentTick); } public static boolean EXTcloseRrun() { getLoader().schedule.finish(); setLoader(null); finalActions(); try { Class.forName("mpi.MPI"); MPI.Finalize(); } catch (ClassNotFoundException e) { logger.info("Error during MPI finilization. No MPI in classpath!"); // e.printStackTrace(); } catch (NoClassDefFoundError ncde) { logger.info("Error during MPI finilization. No MPI class linked!"); // ncde.printStackTrace(); } catch (Exception exception) { logger.info("Error during MPI finilization: " + exception.getMessage()); exception.printStackTrace(); } return true; } public static void doRun(String filename, int start, int end, boolean interactive) throws Exception { setLoader(setupRun(filename, start, end)); if (interactive) { interactiveRun(getLoader()); } else { noninteractiveRun(getLoader(), start == Integer.MIN_VALUE ? getLoader().startTick : start, end == Integer.MIN_VALUE ? getLoader().endTick : end); setLoader(null); finalActions(); } } public static void noninteractiveRun(ScenarioLoader loader, int start, int end) { logger.info("do noninteractiveRun"); logger.info( String.format("Running from %s to %s\n", (start == Integer.MIN_VALUE ? "<ScenarioFile>" : start + ""), (end == Integer.MIN_VALUE ? "<ScenarioFile>" : end + ""))); if (end != Integer.MIN_VALUE) { if (start != Integer.MIN_VALUE) { loader.schedule.runFromTo(start, end); } else { loader.schedule.runUntil(end); loader.schedule.finish(); } } else { loader.schedule.run(); loader.schedule.finish(); } } public static void interactiveRun(final ScenarioLoader loader) { logger.info("Setting up interactive run"); ScheduleThread thread = new ScheduleThread(loader.schedule); thread.start(); interactiveControls = new JFrame(); TimeDisplay td = new TimeDisplay(loader.schedule); loader.schedule.registerListeners(td); ScheduleControls sc = new ScheduleControls(loader.schedule); interactiveControls.getContentPane() .setLayout(new BoxLayout(interactiveControls.getContentPane(), BoxLayout.Y_AXIS)); interactiveControls.add(td); interactiveControls.add(sc); interactiveControls.pack(); interactiveControls.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); java.awt.event.WindowListener wl = new java.awt.event.WindowAdapter() { @Override public void windowClosing(java.awt.event.WindowEvent windowEvent) { // int confirm = JOptionPane.showOptionDialog(frame, // "Are You Sure to Close this Application?", // "Exit Confirmation", JOptionPane.YES_NO_OPTION, // JOptionPane.QUESTION_MESSAGE, null, null, null); // if (confirm == JOptionPane.YES_OPTION) { //// System.exit(1); // } ModelRunner.finalActions(); } }; interactiveControls.addWindowListener(wl); interactiveControls.setVisible(true); } public static ScenarioLoader setupRun(String filename, int start, int end) throws Exception { // TODO override persister method ScenarioLoader loader = ABMPersister.getInstance().readXML(ScenarioLoader.class, filename, null); loader.setRunID(rInfo.getCurrentRun() + "-" + rInfo.getCurrentRandomSeed()); loader.initialise(rInfo); loader.schedule.setRegions(loader.regions); return loader; } @SuppressWarnings("static-access") protected static Options manageOptions() { Options options = new Options(); options.addOption( OptionBuilder.withDescription("Display usage").withLongOpt("help").isRequired(false).create("h")); options.addOption(OptionBuilder.withDescription("Interactive mode?").withLongOpt("interactive") .isRequired(false).create("i")); options.addOption(OptionBuilder.withArgName("dataDirectory").hasArg() .withDescription("Location of data directory").withLongOpt("directory").isRequired(false).create("d")); options.addOption(OptionBuilder.withArgName("scenarioFilename").hasArg() .withDescription("Location and name of scenario file relative to directory").withLongOpt("filename") .isRequired(false).create("f")); options.addOption(OptionBuilder.withArgName("startTick").hasArg().withDescription("Start tick of simulation") .withType(Integer.class).withLongOpt("start").isRequired(false).create("s")); options.addOption(OptionBuilder.withArgName("endTick").hasArg().withDescription("End tick of simulation") .withType(Integer.class).withLongOpt("end").isRequired(false).create("e")); options.addOption(OptionBuilder.withArgName("numOfRuns").hasArg() .withDescription("Number of runs with distinct configuration").withType(Integer.class) .withLongOpt("runs").isRequired(false).create("n")); options.addOption(OptionBuilder.withArgName("startRun").hasArg() .withDescription("Number of run to start with (first one is 0)").withType(Integer.class) .withLongOpt("startRun").isRequired(false).create("sr")); options.addOption(OptionBuilder.withArgName("numOfRandVariation").hasArg() .withDescription("Number of runs of each configuration with distinct random seed)") .withType(Integer.class).withLongOpt("randomVariations").isRequired(false).create("r")); options.addOption(OptionBuilder.withArgName("offset").hasArg().withDescription("Random seed offset") .withType(Integer.class).withLongOpt("randomseedoffset").isRequired(false).create("o")); options.addOption(OptionBuilder.withArgName("subset").hasArg() .withDescription("Expression that is checked to return 1 for each started run.").withType(Integer.class) .withLongOpt("subsetExpression").isRequired(false).create("se")); return options; } protected static void finalActions() { // rInfo is null when called from other awt threads (ABS, Jan 2020) // System.out.println(mRunner.getRunInfo().toString()); // mRunner.getRunInfo().getOutputs().removeClosingOutputThreads(); rInfo.getOutputs().removeClosingOutputThreads(); rInfo = null; ABMPersister.reset(); GlobalInstitutionsRegistry.reset(); PmParameterManager.reset(); MManager.reset(); LModel.reset(); } /** * @return the run info */ public static RunInfo getRunInfo() { return rInfo; } /** * @return the loader */ public static ScenarioLoader getLoader() { return loader; } /** * @param loader * the loader to set */ private static void setLoader(ScenarioLoader loader) { ModelRunner.loader = loader; } }
package com.lazydeveloper.web.service.domain.posts; import java.util.stream.Stream; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; /** * 보통 ibatis/MyBatis 등에서 Dao라고 불리는 DB Layer 접근자입니다. JPA에선 Repository라고 부르며 인터페이스로 생성합니다. 단순히 인터페이스를 생성후, JpaRepository<Entity클래스, PK타입>를 상속하면 기본적인 CRUD 메소드가 자동생성 됩니다. 특별히 <code>@Repository</code>를 추가할 필요도 없습니다. * @author LEE JONG HWA * @created 2018. 7. 18. * @product vEPG-SI * @sw_block */ public interface PostsRepository extends JpaRepository<Posts, Long>{ // 굳이 @Query를 쓴 이유는, SpringDataJpa에서 제공하지 않는 메소드는 위처럼 쿼리로 작성해도 되는것을 보여주기 위함입니다. // Tip) // 규모가 있는 프로젝트에서의 데이터 조회는 FK의 조인, 복잡한 조건등으로 인해 이런 Entity 클래스만으로 처리하기 어려워 조회용 프레임워크를 추가로 사용합니다. // 대표적 예로 querydsl, jooq, MyBatis 등이 있습니다. // 조회는 위 3가지 프레임워크중 하나를 통해 조회하고, 등록/수정/삭제 등은 SpringDataJpa를 통해 진행합니다. // (개인적으로는 querydsl를 강추합니다.) // JPA, querydsl에 대한 더 자세한 내용은 김영한님의 자바 ORM 표준 JPA 프로그래밍 을 참고하시면 아주 좋습니다. @Query("SELECT p FROM Posts p ORDER BY p.id DESC") Stream<Posts> finadAllDesc(); }
package homework3; //Name : Nupur Dixit //Instructor : Bineet Sharma //Date : May 7,2016 //Description: This program will give the user prompt to enter two float (or double) values. // If the values input are correct then display the input two values. // If user enters characters instead of numbers or if they enter invalid numbers // then the program will display the error message and ask the user to re-enter the correct values // again. It only exits when the correct input is received and displayed. import java.util.Scanner; public class UserFloat { public static void main(String[] args) { // Create a Scanner Scanner input=new Scanner(System.in); String value1,value2; double floatValue1,floatValue2; System.out.print("Please enter two float numbers separated by space and press enter: "); //Exception Handling for NumberFormatException which may arise while converting string to double do{ //Prompts user to enter two String values which are then converted to float variables value1=input.next(); value2=input.nextLine(); try{ //convert the string to double floatValue1=Double.parseDouble(value1); floatValue2=Double.parseDouble(value2); break; }catch(final NumberFormatException e){ System.out.print("\nError reading your input.Please try again:"); //input.nextLine(); } }while(true); //Display the successful message System.out.println("\nYou entered"+" " +floatValue1+" "+"and"+" "+floatValue2+" "+"successfully"); System.out.println("Press enter key to continue . . ."); input.nextLine(); } }
package br.com.pcmaker.entity; import java.util.ArrayList; import java.util.List; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.OneToMany; import javax.persistence.Table; import com.fasterxml.jackson.annotation.JsonIgnore; @Entity @Table(name = "avaria") public class Avaria extends AutoIncrementIdEntity { /** * */ private static final long serialVersionUID = 1L; @Column(name = "nome", nullable = false) private String nome; private List<OrdemServicoAvaria> ordemServicoAvaria = new ArrayList<OrdemServicoAvaria>(0); public String getNome() { return nome; } public void setNome(String nome) { this.nome = nome; } @JsonIgnore @OneToMany(fetch=FetchType.LAZY, mappedBy="avaria") public List<OrdemServicoAvaria> getOrdemServicoAvaria() { return ordemServicoAvaria; } public void setOrdemServicoAvaria(List<OrdemServicoAvaria> ordemServicoAvaria) { this.ordemServicoAvaria = ordemServicoAvaria; } @Override public String toString() { return nome; } }
package com.incident.polyandroid.fragment; import android.app.ProgressDialog; import android.content.Context; import android.os.Handler; import android.support.v4.app.Fragment; import android.widget.Toast; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; public class BaseFragment extends Fragment { private ProgressDialog mProgressDialog; public void showProgressDialog(Context context) { if (mProgressDialog == null) { mProgressDialog = new ProgressDialog(context); mProgressDialog.setCancelable(false); mProgressDialog.setMessage("Loading..."); } timerDelayRemoveDialog(2500,context); mProgressDialog.show(); } public void hideProgressDialog() { if (mProgressDialog != null && mProgressDialog.isShowing()) { mProgressDialog.dismiss(); } } public DatabaseReference getFireBaseRoot() { return FirebaseDatabase.getInstance().getReference(); } public void timerDelayRemoveDialog(long time, final Context context){ new Handler().postDelayed(new Runnable() { public void run() { mProgressDialog.dismiss(); int duration = Toast.LENGTH_LONG; } }, time); } }
package com.ar.cmsistemas.dao; import java.sql.CallableStatement; import java.sql.Connection; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import java.sql.Date; import java.sql.ResultSet; import com.ar.cmsistemas.db.DataSource; import com.ar.cmsistemas.db.JDBCUtils; import com.ar.cmsistemas.domain.Propiedad; import com.ar.cmsistemas.domain.TipoDeOperacion; import com.ar.cmsistemas.helper.CommonHelper; import com.ar.cmsistemas.service.CiudadService; import com.ar.cmsistemas.service.ImagenService; import com.ar.cmsistemas.service.TipoDeOperaciónService; import com.ar.cmsistemas.service.TipoDePropiedadService; import oracle.jdbc.OracleCallableStatement; import oracle.jdbc.OracleTypes; public class PropiedadDao{ public void save(Propiedad p) throws SQLException, Exception{ Connection connection = null; CallableStatement cs = null; try { connection = DataSource.getInstance().getConnection(); String call = "{call tp_dba.abm_inmobiliaria.insert_propiedad(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)}"; // Testing Purposes // String call = "{call tp_dba.abm_inmobiliaria.insert_proooopiedad(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)}"; cs = connection.prepareCall(call); cs.setString(1, p.getDireccion()); cs.setString(2, p.getDesc()); cs.setInt(3, p.getAmbientes()); cs.setInt(4, p.getBanios()); cs.setInt(5, p.getSuperficieCubierta()); cs.setInt(6, p.getPrecio()); cs.setInt(7,p.getTipoDeOperacion().getId()); cs.setInt(8,p.getTipoDePropiedad().getId()); cs.setString(9, CommonHelper.convertToOracleBoolean(p.getActivo())); cs.setInt(10, p.getCiudad().getId()); cs.setInt(11, p.getHabitaciones()); cs.setInt(12, p.getSuperficieTotal()); cs.setDate(13, (new Date(p.getFechaDeConstruccion().getTime()))); cs.setFloat(14, p.getLongitud().floatValue()); cs.setFloat(15, p.getLatitud().floatValue()); cs.setDate(16, (new Date(p.getCreateDate().getTime()))); cs.setString(17, p.getCreateUser()); cs.setString(18, p.getUpdateUser()); cs.setDate(19, null); cs.execute(); } catch (SQLException s) { System.out.println("Error: "); System.out.println(s.getMessage() + " - " + "SQLState: "+s.getSQLState()); s.printStackTrace(); throw s; } catch (Exception e) { System.out.println("Error: "); System.out.println(e.getMessage()); e.printStackTrace(); throw e; }finally { if (cs != null) try { cs.close(); } catch (SQLException e) {e.printStackTrace();} if (connection != null) try { connection.close(); } catch (SQLException e) {e.printStackTrace();} } } public List<Propiedad> getPropiedadesByOperacion(Integer op) { Connection connection = null; CallableStatement cs = null; ResultSet rs = null; List<Propiedad> propiedades = new ArrayList<Propiedad>(); CiudadService ciudadService = new CiudadService(); ImagenService imagenService = new ImagenService(); TipoDeOperaciónService tipoDeOperacionService = new TipoDeOperaciónService(); TipoDePropiedadService tipoDePropiedadService = new TipoDePropiedadService(); try { connection = DataSource.getInstance().getConnection(); String call = "{call tp_dba.consultas_inmobiliaria.get_props_by_operacion(?,?)}"; cs = connection.prepareCall(call); connection.prepareCall(call); cs.setInt(1, op); cs.registerOutParameter(2, OracleTypes.CURSOR); cs.execute(); rs = (ResultSet)cs.getObject(2); while(rs.next()){ Propiedad p = new Propiedad(); p.setId(rs.getInt("propiedad_id")); p.setActivo(CommonHelper.convertToJavaBoolean(rs.getString("active"))); p.setAmbientes(rs.getInt("ambientes")); p.setBanios(rs.getInt("banios")); //Setear ciudad p.setCiudad(ciudadService.getCiudadById(rs.getInt("ciudad_id"))); p.setCreateDate(rs.getDate("create_date")); // Usuario de create p.setCreateUser(rs.getString("create_user")); p.setDesc(rs.getString("descripcion")); p.setDireccion(rs.getString("direccion")); p.setFechaDeConstruccion(rs.getDate("fecha_de_construccion")); p.setHabitaciones(rs.getInt("habitaciones")); p.setId(rs.getInt("propiedad_id")); p.setLatitud(Double.valueOf(rs.getFloat("latitud"))); p.setLongitud(Double.valueOf(rs.getFloat("longitud"))); p.setPrecio(rs.getInt("precio")); p.setSuperficieCubierta(rs.getInt("superficie_cubierta")); p.setSuperficieTotal(rs.getInt("superficie_total")); p.setImagenes(imagenService.getImagenesByProp(p.getId())); // Tipo de Op y Tipo de Prop p.setTipoDeOperacion(tipoDeOperacionService.getTipoDeOperacionById(rs.getInt("tipo_de_operacion_id"))); p.setTipoDePropiedad(tipoDePropiedadService.getTipoDePropiedadById(rs.getInt("tipo_de_propiedad_id"))); p.setUpdateDate(rs.getDate("update_date")); // Usuario de update p.setUpdateUser(rs.getString("update_user")); propiedades.add(p); } } catch (SQLException s) { System.out.println("Error: "); s.printStackTrace(); } catch (Exception e) { System.out.println("Error: "); e.printStackTrace(); }finally { if (rs != null) try { rs.close(); } catch (SQLException e) {e.printStackTrace();} if (cs != null) try { cs.close(); } catch (SQLException e) {e.printStackTrace();} if (connection != null) try { connection.close(); } catch (SQLException e) {e.printStackTrace();} } return propiedades; } public Propiedad getPropiedadById(Integer id) { Connection connection = null; CallableStatement cs = null; ResultSet rs = null; Propiedad propiedad = new Propiedad(); CiudadService ciudadService = new CiudadService(); ImagenService imagenService = new ImagenService(); TipoDeOperaciónService tipoDeOperacionService = new TipoDeOperaciónService(); TipoDePropiedadService tipoDePropiedadService = new TipoDePropiedadService(); try { connection = DataSource.getInstance().getConnection(); String call = "{call tp_dba.consultas_inmobiliaria.get_prop_by_id(?,?)}"; cs = connection.prepareCall(call); cs.setInt(1, id); cs.registerOutParameter(2, OracleTypes.CURSOR); cs.execute(); rs = (ResultSet)cs.getObject(2); while(rs.next()){ propiedad.setId(rs.getInt("propiedad_id")); propiedad.setActivo(CommonHelper.convertToJavaBoolean(rs.getString("active"))); propiedad.setAmbientes(rs.getInt("ambientes")); propiedad.setBanios(rs.getInt("banios")); //Setear ciudad propiedad.setCiudad(ciudadService.getCiudadById(rs.getInt("ciudad_id"))); propiedad.setCreateDate(rs.getDate("create_date")); // Usuario de create propiedad.setCreateUser(rs.getString("create_user")); propiedad.setDesc(rs.getString("descripcion")); propiedad.setDireccion(rs.getString("direccion")); propiedad.setFechaDeConstruccion(rs.getDate("fecha_de_construccion")); propiedad.setHabitaciones(rs.getInt("habitaciones")); propiedad.setId(rs.getInt("propiedad_id")); propiedad.setLatitud(Double.valueOf(rs.getFloat("latitud"))); propiedad.setLongitud(Double.valueOf(rs.getFloat("longitud"))); propiedad.setPrecio(rs.getInt("precio")); propiedad.setSuperficieCubierta(rs.getInt("superficie_cubierta")); propiedad.setSuperficieTotal(rs.getInt("superficie_total")); propiedad.setImagenes(imagenService.getImagenesByProp(id)); // Tipo de Op y Tipo de Prop propiedad.setTipoDeOperacion(tipoDeOperacionService.getTipoDeOperacionById(rs.getInt("tipo_de_operacion_id"))); propiedad.setTipoDePropiedad(tipoDePropiedadService.getTipoDePropiedadById(rs.getInt("tipo_de_propiedad_id"))); propiedad.setUpdateDate(rs.getDate("update_date")); // Usuario de update propiedad.setUpdateUser(rs.getString("update_user")); } } catch (SQLException s) { System.out.println("Error: "); s.printStackTrace(); } catch (Exception e) { System.out.println("Error: "); e.printStackTrace(); }finally { if (rs != null) try { rs.close(); } catch (SQLException e) {e.printStackTrace();} if (cs != null) try { cs.close(); } catch (SQLException e) {e.printStackTrace();} if (connection != null) try { connection.close(); } catch (SQLException e) {e.printStackTrace();} } return propiedad; } public List<Propiedad> getPropiedades() { Connection connection = null; CallableStatement cs = null; ResultSet rs = null; List<Propiedad> props = new ArrayList<Propiedad>(); CiudadService ciudadService = new CiudadService(); ImagenService imagenService = new ImagenService(); TipoDeOperaciónService tipoDeOperacionService = new TipoDeOperaciónService(); TipoDePropiedadService tipoDePropiedadService = new TipoDePropiedadService(); try { connection = DataSource.getInstance().getConnection(); String call = "{call tp_dba.consultas_inmobiliaria.get_props(?)}"; cs = connection.prepareCall(call); cs.registerOutParameter(1, OracleTypes.CURSOR); cs.execute(); rs = (ResultSet)cs.getObject(1); while(rs.next()){ Propiedad propiedad = new Propiedad(); propiedad.setId(rs.getInt("propiedad_id")); propiedad.setActivo(CommonHelper.convertToJavaBoolean(rs.getString("active"))); propiedad.setAmbientes(rs.getInt("ambientes")); propiedad.setBanios(rs.getInt("banios")); //Setear ciudad propiedad.setCiudad(ciudadService.getCiudadById(rs.getInt("ciudad_id"))); propiedad.setCreateDate(rs.getDate("create_date")); // Usuario de create //p.setCreateUser(rs.getString("create_user")); propiedad.setDesc(rs.getString("descripcion")); propiedad.setDireccion(rs.getString("direccion")); propiedad.setFechaDeConstruccion(rs.getDate("fecha_de_construccion")); propiedad.setHabitaciones(rs.getInt("habitaciones")); propiedad.setId(rs.getInt("propiedad_id")); propiedad.setLatitud(Double.valueOf(rs.getFloat("latitud"))); propiedad.setLongitud(Double.valueOf(rs.getFloat("longitud"))); propiedad.setPrecio(rs.getInt("precio")); propiedad.setSuperficieCubierta(rs.getInt("superficie_cubierta")); propiedad.setSuperficieTotal(rs.getInt("superficie_total")); propiedad.setImagenes(imagenService.getImagenesByProp(propiedad.getId())); // Tipo de Op y Tipo de Prop propiedad.setTipoDeOperacion(tipoDeOperacionService.getTipoDeOperacionById(rs.getInt("tipo_de_operacion_id"))); propiedad.setTipoDePropiedad(tipoDePropiedadService.getTipoDePropiedadById(rs.getInt("tipo_de_propiedad_id"))); propiedad.setUpdateDate(rs.getDate("update_date")); // Usuario de update propiedad.setUpdateUser(rs.getString("update_user")); props.add(propiedad); } } catch (SQLException s) { System.out.println("Error: "); s.printStackTrace(); } catch (Exception e) { System.out.println("Error: "); e.printStackTrace(); }finally { if (rs != null) try { rs.close(); } catch (SQLException e) {e.printStackTrace();} if (cs != null) try { cs.close(); } catch (SQLException e) {e.printStackTrace();} if (connection != null) try { connection.close(); } catch (SQLException e) {e.printStackTrace();} } return props; } public void update(Propiedad p) throws SQLException,Exception { Connection connection = null; CallableStatement cs = null; try { connection = DataSource.getInstance().getConnection(); String call = "{call tp_dba.abm_inmobiliaria.update_propiedad(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)}"; cs = connection.prepareCall(call); cs.setInt(1, p.getId()); // prop_id IN NUMBER, cs.setString(2, p.getDireccion()); //v_direccion IN VARCHAR2, cs.setString(3, p.getDesc()); //v_descripcion IN VARCHAR2, cs.setInt(4, p.getAmbientes()); //v_ambientes IN NUMBER, cs.setInt(5, p.getBanios()); //v_banios IN NUMBER, cs.setInt(6, p.getSuperficieCubierta()); //v_superficie_cubierta IN NUMBER, cs.setInt(7, p.getPrecio()); //v_precio IN NUMBER, cs.setInt(8,p.getTipoDeOperacion().getId()); //v_tipo_de_operacion_id IN NUMBER, cs.setInt(9,p.getTipoDePropiedad().getId()); //v_tipo_de_propiedad_id IN NUMBER, cs.setString(10, CommonHelper.convertToOracleBoolean(p.getActivo())); //v_active IN VARCHAR2, cs.setInt(11, p.getCiudad().getId()); //v_ciudad_id IN NUMBER, cs.setInt(12, p.getHabitaciones()); //v_habitaciones IN NUMBER, cs.setInt(13, p.getSuperficieTotal()); //v_superficie_total IN NUMBER, cs.setDate(14, new Date(p.getFechaDeConstruccion().getTime())); //v_fecha_de_construccion IN DATE, cs.setFloat(15, p.getLongitud().floatValue()); //v_longitud IN FLOAT, cs.setFloat(16, p.getLatitud().floatValue()); //v_latitud IN FLOAT, cs.setDate(17, new Date(p.getCreateDate().getTime())); //v_create_date IN DATE, cs.setString(18, p.getCreateUser()); //v_create_user IN VARCHAR2, cs.setDate(19, new Date(p.getUpdateDate().getTime())); //v_update_date IN DATE, cs.setString(20, p.getUpdateUser()); //v_update_user IN VARCHAR2 cs.execute(); } catch (SQLException s) { System.out.println("Error: "); System.out.println(s.getMessage() + " - " + "SQLState: "+s.getSQLState()); s.printStackTrace(); throw s; } catch (Exception e) { System.out.println("Error: "); System.out.println(e.getMessage()); e.printStackTrace(); throw e; }finally { if (cs != null) try { cs.close(); } catch (SQLException e) {e.printStackTrace();} if (connection != null) try { connection.close(); } catch (SQLException e) {e.printStackTrace();} } } }
package vehiculos; public class Coche { //CARACTERISTICAS DE LA CLASE private String marca; private String modelo; protected int velocidad; protected int velocidadMaxima; protected boolean estadoArrancado; //CONSTRUCTOR DEL COCHE public Coche() { this.velocidad = 0; this.velocidadMaxima = 160; this.estadoArrancado = false; } public Coche(String marca, String modelo) { this.velocidad = 0; this.velocidadMaxima = 160; this.estadoArrancado = false; this.marca = marca; this.modelo = modelo; } //SOBRESCRIBIMOS EL METODO toString() //PARA DEVOLVER LA MARCA Y MODELO DEL COCHE @Override public String toString() { return this.marca + " " + this.modelo; } public String getMarca() { return marca; } public void setMarca(String marca) { this.marca = marca; } public String getModelo() { return modelo; } public void setModelo(String modelo) { this.modelo = modelo; } //ACCIONES SOBRE EL COCHE public void arrancar() { if (this.estadoArrancado == true) { System.out.println("El coche está en marcha!!!"); } else { this.estadoArrancado = true; System.out.println("El coche ha arrancado"); } } public void acelerar() { if (this.estadoArrancado == false) { System.out.println("Primero tienes que arrancar el coche"); } else { this.velocidad += 20; if (this.velocidad >= this.velocidadMaxima) { System.out.println("Velocidad máxima del coche: " + this.velocidadMaxima); this.velocidad = this.velocidadMaxima; } else { System.out.println("Acelerando..." + this.velocidad + " km/h"); } } } public void frenar() { this.velocidad = this.velocidad - 20; if (this.velocidad <= 0) { this.velocidad = 0; System.out.println("Ya estas parado, velocidad " + this.velocidad); } else { System.out.println("Frenando..." + this.velocidad + " km/h"); } } public void frenar(int presion) { this.velocidad = this.velocidad - presion; if (this.velocidad <= 0) { this.velocidad = 0; System.out.println("Ya estás parado"); } else { System.out.println("Frenando..." + this.velocidad + " km/h"); } } }
package yangsu; public class TrainNumber_and_Time{ public String TrainNumber; public int deph, depm; public int desh, desm; public TrainNumber_and_Time(){ } public TrainNumber_and_Time(String a, int sh, int sm, int eh, int em){ TrainNumber = new String(a); deph = sh; depm = sm; desh = eh; desm = em; } }
package com.mundo.core.support; import com.mundo.core.util.JsonUtil; import com.mundo.core.util.ObjectUtil; import org.apache.commons.lang3.builder.Builder; import javax.annotation.concurrent.NotThreadSafe; import java.util.HashMap; import java.util.Map; import java.util.Objects; import java.util.function.BiPredicate; import java.util.function.Supplier; /** * MapBuilder * * @author maomao * @since 2017/3/5 */ @NotThreadSafe public class MapBuilder<K, V> implements Builder<Map<K, V>> { private Map<K, V> map; private MapBuilder() { throw new AssertionError("No com.mundo.core.support.MapBuilder instances for you!"); } private MapBuilder(Map<K, V> map) { this.map = map; } public static <K, V> MapBuilder<K, V> create() { return create(HashMap::new); } public static <K, V> MapBuilder<K, V> create(int capacity) { return create(() -> new HashMap<K, V>(capacity)); } public static <K, V> MapBuilder<K, V> create(Supplier<Map<K, V>> supplier) { return new MapBuilder<>(supplier.get()); } public MapBuilder<K, V> put(K k, V v) { map.put(k, v); return this; } public MapBuilder<K, V> putIfAbsent(K k, V v) { return putIf(k, v, (key, val) -> !map.keySet().contains(key) && !map.values().contains(val)); } public MapBuilder<K, V> putIfKeyAbsent(K k, V v) { return putIf(k, v, (key, val) -> !map.keySet().contains(key)); } public MapBuilder<K, V> putIfValAbsent(K k, V v) { return putIf(k, v, (key, val) -> !map.values().contains(val)); } public MapBuilder<K, V> putIfNonNull(K k, V v) { return putIf(k, v, (key, val) -> ObjectUtil.allNotNull(key, val)); } public MapBuilder<K, V> putIfKeyNonNull(K k, V v) { return putIf(k, v, (key, val) -> Objects.nonNull(key)); } public MapBuilder<K, V> putIfValNonNull(K k, V v) { return putIf(k, v, (key, val) -> Objects.nonNull(val)); } public MapBuilder<K, V> putIf(K k, V v, BiPredicate<K, V> biPredicate) { if (biPredicate.test(k, v)) { map.put(k, v); } return this; } @Override public Map<K, V> build() { return map; } public String toJson() { return JsonUtil.toJson(map); } @Override public String toString() { return map.toString(); } }
package com.mx.profuturo.bolsa.service.home; import com.mx.profuturo.bolsa.model.service.dto.ContenidoHomeDTO; import com.mx.profuturo.bolsa.model.service.dto.ImagenGaleriaDTO; import com.mx.profuturo.bolsa.model.vo.home.ContenidoVO; import com.mx.profuturo.bolsa.util.exception.custom.GenericStatusException; import java.io.FileNotFoundException; import java.io.IOException; public interface HomeService { ContenidoVO getHomeContent() throws GenericStatusException; boolean saveHomeContent(ContenidoHomeDTO contenidoHomeInput) throws GenericStatusException; boolean uploadGalleryImage(ImagenGaleriaDTO imagen) throws IOException, FileNotFoundException; }
package Grant_Application_page; import helper.Wait.WaitHelper; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.interactions.Actions; import org.openqa.selenium.support.FindBy; import org.openqa.selenium.support.PageFactory; import configreader.ObjectRepo; public class Proposal_page { WebDriver driver; //private final Logger log = LoggerHelper.getLogger(Create_new_account_page.class); WaitHelper waitHelper; Actions actions; @FindBy(xpath=".//span[text()='Proposal']") WebElement Proposal; @FindBy(xpath=".//input[@id='react-project-title']") WebElement Project_title; @FindBy(xpath=".//input[@id='react-project-start_date']") WebElement Project_start_Date; @FindBy(xpath=".//input[@id='react-project-end_date']") WebElement Project_end_Date; @FindBy(xpath=".//textarea[@id='react-project-description']") WebElement Project_Description; @FindBy(xpath=".//span[text()='Proposal']") WebElement Proceed_button; @FindBy(xpath=".//span[@id='react-select-project-activity--value']") WebElement Activity_Drop_down; @FindBy(xpath=".//span[text()='Market Entry']") WebElement Activity_select_Drop_down; public Proposal_page(WebDriver driver) { this.driver = driver; PageFactory.initElements(driver, this); waitHelper = new WaitHelper(driver); // } public void Activity_Value() throws InterruptedException { waitHelper.waitForElement(driver, Activity_Drop_down,ObjectRepo.reader.getPageLoadTimeOut()); waitHelper.waitForElement(driver, Activity_Drop_down,ObjectRepo.reader.getExplicitWait()); actions = new Actions(driver); actions.moveToElement(Activity_Drop_down); actions.click().build().perform(); } public void Activity_Drop_down(String Activity_Drop_down) throws InterruptedException { //log.info("entering sigin_password." + sigin_password); this.Activity_Drop_down.sendKeys(Activity_Drop_down); } public void Project_Description(String Project_Description) throws InterruptedException { //log.info("entering sigin_password." + sigin_password); this.Project_Description.clear(); this.Project_Description.sendKeys(Project_Description); } public void Project_end_Date(String Project_end_Date) throws InterruptedException { //log.info("entering sigin_password." + sigin_password); this.Project_end_Date.clear(); this.Project_end_Date.sendKeys(Project_end_Date); } public void Project_start_Date(String Project_start_Date) throws InterruptedException { //log.info("entering sigin_password." + sigin_password); this.Project_start_Date.clear(); this.Project_start_Date.sendKeys(Project_start_Date); } public void offer_address() throws InterruptedException { waitHelper.waitForElement(driver, Proposal,ObjectRepo.reader.getPageLoadTimeOut()); waitHelper.waitForElement(driver, Proposal,ObjectRepo.reader.getExplicitWait()); actions = new Actions(driver); actions.moveToElement(Proposal); actions.click().build().perform(); } public void Project_title(String Project_title) throws InterruptedException { //log.info("entering sigin_password." + sigin_password); this.Project_title.clear(); this.Project_title.sendKeys(Project_title); } public void Proceed_button() throws InterruptedException { waitHelper.waitForElement(driver, Proceed_button,ObjectRepo.reader.getPageLoadTimeOut()); waitHelper.waitForElement(driver, Proceed_button,ObjectRepo.reader.getExplicitWait()); actions = new Actions(driver); actions.moveToElement(Proceed_button); actions.click().build().perform(); } public void Activity_Drop_down() throws InterruptedException { waitHelper.waitForElement(driver, Activity_Drop_down,ObjectRepo.reader.getPageLoadTimeOut()); waitHelper.waitForElement(driver, Activity_Drop_down,ObjectRepo.reader.getExplicitWait()); actions = new Actions(driver); actions.moveToElement(Activity_Drop_down); actions.click().build().perform(); } }
package org.murinrad.android.musicmultiply.receiver.qos; import android.util.Log; import org.murinrad.android.musicmultiply.org.murinrad.util.Tuple; import org.murinrad.android.musicmultiply.receiver.MainActivity; import org.murinrad.android.musicmultiply.receiver.Receiver; import java.lang.ref.WeakReference; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.Queue; import java.util.Set; import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; /** * Created by Radovan Murin on 26.4.2015. */ public class QoSController { public static final int THRESHOLD_FOR_PACKET_RESENDING = 3; private static final int QoS_SCHEDULE = 5000; BlockingQueue<Long> delayReportQueue; BlockingQueue<Tuple<Integer, Integer>> packetLossQueue; Thread delayProcessor, packetLossProcessor; Timer sendReportsTask; QosMessenger messenger; boolean isThereNewData = false; Thread.UncaughtExceptionHandler handlerOfThreadExceptions = new QoSControllerExceptionHandler(); Set<WeakReference<QoSEventReceiver>> eventReceivers = new HashSet<>(); private int averageDelay = 0; private int packetLoss = 0; public QoSController() { delayReportQueue = new ArrayBlockingQueue<Long>(150); packetLossQueue = new ArrayBlockingQueue<>(150); delayProcessor = new Thread(new DelayAnalyser()); delayProcessor.setUncaughtExceptionHandler(handlerOfThreadExceptions); packetLossProcessor = new Thread(new PacketLossAnalyser()); packetLossProcessor.setUncaughtExceptionHandler(handlerOfThreadExceptions); // readLock = new ReentrantLock(); messenger = new QosMessenger(null); //register a logger to the events eventReceivers.add(new WeakReference<QoSEventReceiver>(new LoggerForQosEvents())); } public void setServer(String server) { messenger = new QosMessenger(server); } public void reportDelay(long delay) { delayReportQueue.offer(delay); } public void reportPacketLoss(int lastReceived, int nowHave) { Tuple<Integer, Integer> tuple = new Tuple<>(lastReceived, nowHave); packetLossQueue.offer(tuple); } public void start() { delayProcessor.start(); packetLossProcessor.start(); sendReportsTask = new Timer(true); sendReportsTask.schedule(new QosSender(), 0, QoS_SCHEDULE); } public void stop() { delayProcessor.interrupt(); packetLossProcessor.interrupt(); sendReportsTask.cancel(); } public void registerEventReceiver(QoSEventReceiver receiver) { eventReceivers.add(new WeakReference<QoSEventReceiver>(receiver)); } public void deregisterEventReceiver(QoSEventReceiver receiver) { Iterator iterator = eventReceivers.iterator(); boolean removed = false; while (iterator.hasNext()) { WeakReference<QoSEventReceiver> item = (WeakReference<QoSEventReceiver>) iterator.next(); if (item.get() != null) { if (item.get() == receiver) { iterator.remove(); removed = true; break; } } else { iterator.remove(); } } if (!removed) { Log.w("QosController", "Attempted to remove a QoSEventReceiver which was not registered."); } } private class PacketLossAnalyser implements Runnable { private static final int WINDOWS_SIZE = 150; boolean timeKeeperDeactivated = false; private Queue<Integer> data = new LinkedList<>(); @Override public void run() { try { while (!Thread.interrupted()) { Tuple<Integer, Integer> tuple = packetLossQueue.take(); int lostPackets = tuple.getSecond() - tuple.getFirst(); data.add(lostPackets); // boolean release = readLock.tryLock(); isThereNewData = true; packetLoss += lostPackets; if (data.size() >= WINDOWS_SIZE) { packetLoss -= data.remove(); } if (lostPackets >= THRESHOLD_FOR_PACKET_RESENDING) { messenger.requestPacketResend(tuple.getFirst(), tuple.getSecond()); } // if (release) // readLock.unlock(); } } catch (InterruptedException e) { e.printStackTrace(); } } } private class DelayAnalyser implements Runnable { private int delayReports = 0; private long totalDelay = 0; @Override public void run() { try { while (!Thread.interrupted()) { long delay = delayReportQueue.take(); delayReports++; totalDelay += delay; // boolean release = readLock.tryLock(); isThereNewData = true; averageDelay = Math.round((float) totalDelay / (float) delayReports); // if (release) readLock.unlock(); } } catch (InterruptedException e) { e.printStackTrace(); } } } private class QosSender extends TimerTask { @Override public void run() { if (!isThereNewData) return; // readLock.lock(); try { isThereNewData = false; messenger.sendQoSMessage(averageDelay, packetLoss); } catch (Exception ex) { Log.w(MainActivity.APP_TAG, "QosSender failure", ex); } // readLock.unlock(); } } private class QoSControllerExceptionHandler implements Thread.UncaughtExceptionHandler { @Override public void uncaughtException(Thread thread, Throwable ex) { Log.e(Receiver.APP_TAG, "Uncaught exception in thread", ex); } } private class LoggerForQosEvents implements QoSEventReceiver { @Override public void onPacketLossIncrease() { Log.i("LoggerForQosEvents", "onPacketLossIncrease called"); } @Override public void onPacketLossRecovery() { Log.i("LoggerForQosEvents", "onPacketLossIncrease called"); } @Override public void onDelayTooLong() { Log.i("LoggerForQosEvents", "onPacketLossIncrease called"); } } }
package soduku.main; import java.lang.reflect.Array; import java.util.ArrayList; public class TestHelper { final int ROWCOORDSMIN = 0; final int ROWCOORDSMAX = 8; final int COLUMNCOORDSMIN = 0; final int COLUMNCOORDSMAX = 8; public int getRandomNumberFromArrayListOrArray(ArrayList<Integer> arrayList){ int randomPos = (int)(Math.random() * (arrayList.size() - 1)); return arrayList.get(randomPos); } public int getRandomNumberFromArrayListOrArray(int[] array){ int randomPos = (int)(Math.random() * array.length - 1); return array[randomPos]; } public ArrayList<Integer> makeArrayListWithAllNumbers() { ArrayList<Integer> result = new ArrayList<Integer>(); for(int i=0; i<9;i++){ int tmp = i+1; result.add(tmp); } return result; } public Coordinates randomValidCoords(){ int randomRow = ROWCOORDSMIN + (int)(Math.random() * ROWCOORDSMAX); int randomColumn = COLUMNCOORDSMIN + (int)(Math.random() * COLUMNCOORDSMAX); return new Coordinates(randomRow, randomColumn); } }
package utils; import com.google.api.client.auth.oauth2.Credential; import com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp; import com.google.api.client.extensions.jetty.auth.oauth2.LocalServerReceiver; import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow; import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets; import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport; import com.google.api.client.http.HttpTransport; import com.google.api.client.json.JsonFactory; import com.google.api.client.json.jackson2.JacksonFactory; import com.google.api.client.util.store.FileDataStoreFactory; import com.google.api.services.sheets.v4.Sheets; import com.google.api.services.sheets.v4.SheetsScopes; import com.google.api.services.sheets.v4.model.AppendValuesResponse; import com.google.api.services.sheets.v4.model.ValueRange; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import java.io.*; import java.text.SimpleDateFormat; import java.util.Arrays; import java.util.Date; import java.util.List; public class GoogleSheetsHelper { private static Log log = LogFactory.getLog(GoogleSheetsHelper.class); /** Application name. */ private static final String APPLICATION_NAME = "Google Sheets API Java Quickstart"; /** Directory to store user credentials for this application. */ private static final java.io.File DATA_STORE_DIR = new java.io.File( System.getProperty("user.dir"), ".credentials/sheets.googleapis.com-java-quickstart"); /** Global instance of the {@link FileDataStoreFactory}. */ private static FileDataStoreFactory DATA_STORE_FACTORY; /** Global instance of the JSON factory. */ private static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance(); /** Global instance of the HTTP transport. */ private static HttpTransport HTTP_TRANSPORT; /** Global instance of the scopes required by this quickstart. * * If modifying these scopes, delete your previously saved credentials * at ~/.credentials/sheets.googleapis.com-java-quickstart */ private static final List<String> SCOPES = Arrays.asList(SheetsScopes.SPREADSHEETS); static { try { HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport(); DATA_STORE_FACTORY = new FileDataStoreFactory(DATA_STORE_DIR); } catch (Throwable t) { t.printStackTrace(); System.exit(1); } } /** * Creates an authorized Credential object. * @return an authorized Credential object. * @throws IOException */ public static Credential authorize() throws IOException { // Load client secrets. InputStream in = new FileInputStream(new File(System.getProperty("user.dir") + "/client_secret.json")); GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(in)); // Build flow and trigger user authorization request. GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder( HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, SCOPES) .setDataStoreFactory(DATA_STORE_FACTORY) .setAccessType("offline") .build(); Credential credential = new AuthorizationCodeInstalledApp( flow, new LocalServerReceiver()).authorize("user"); System.out.println( "Credentials saved to " + DATA_STORE_DIR.getAbsolutePath()); return credential; } /** * Build and return an authorized Sheets API client service. * @return an authorized Sheets API client service * @throws IOException */ public static Sheets getSheetsService() { try { Credential credential = authorize(); return new Sheets.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential) .setApplicationName(APPLICATION_NAME) .build(); } catch (IOException e) { log.error(e.toString()); } return null; } public static void appendOrder(String project, String orderNumber, String cardHolder, String cardInfo) { // Build a new authorized API client service. Sheets service = getSheetsService(); // https://docs.google.com/spreadsheets/d/1X8iujEhzOkb3S7VzIrda30v8VvjdqHEtSFim--TCbzw/edit String spreadsheetId = "1X8iujEhzOkb3S7VzIrda30v8VvjdqHEtSFim--TCbzw"; String range = "'2017 Automation New Orders'!A2:H2"; // Formatting current date to Google Sheets date format SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy"); ValueRange values = new ValueRange().setValues(Arrays.asList(Arrays.asList( project, dateFormat.format(new Date()), orderNumber, cardHolder, cardInfo))); AppendValuesResponse response = null; try { response = service.spreadsheets().values().append(spreadsheetId, range, values).setValueInputOption("USER_ENTERED").execute(); log.info("Google API response: " + response.toString()); } catch (IOException e) { log.error("Google API error: \n" + e.toString()); } } // public static void main(String[] args) throws IOException { // appendOrder("project", "order", "cardHolder", "cardInfo"); // } }
package classic_algorithms; import java.util.LinkedList; import entity.Edge; import entity.Graph; import entity.Vertex; import entity.VertexGroup; import helpers.VertexGroupToGraphConverterService; import jsonConverter.ObjectToJsonService; /** * Kernighan-Lin - splitting a graph into * two groups where the weights of the edges between groups (cutting cost) is minimised * @author Vanesa Georgieva * */ public class KernighanLinAlgorithm implements IKernighanLinAlgorithm { private static VertexGroup partitionA; private static VertexGroup partitionB; private VertexGroup unswappedA, unswappedB; public static VertexGroup getGroupA() { return partitionA; } public static VertexGroup getGroupB() { return partitionB; } private Graph graph; public Graph getGraph() { return graph; } private int partitionSize; /** Performs KerninghanLin on the given graph **/ public KernighanLinAlgorithm(Graph g) { processGraph(g); System.out.println("Kernighan Lin Algorithm"); System.out.println("Cluster 1"); System.out.println(getGroupA()); System.out.println("Cluster 2"); System.out.println(getGroupB()); } public void processGraph(Graph g) { this.graph = g; this.partitionSize = g.getVertices().size() / 2; partitionA = new VertexGroup(); partitionB = new VertexGroup(); // Split vertices into partitionA and partitionB int i = 0; for (Vertex v : g.getVertices()) { (++i > partitionSize ? partitionB : partitionA).add(v); } // create new unSwapped groups for processing unswappedA = new VertexGroup(partitionA); unswappedB = new VertexGroup(partitionB); doAllSwaps(); } /** Performs swaps(half of graph vertices) and chooses the one with least cut cost one **/ public void doAllSwaps() { LinkedList<Edge> swaps = new LinkedList<Edge>(); double minCost = Double.POSITIVE_INFINITY; int minId = -1; for (int i = 0; i < partitionSize; i++) { double cost = doSingleSwap(swaps); if (cost < minCost) { minCost = cost; minId = i; } } // Unwind swaps while (swaps.size()-1 > minId) { Edge pair = swaps.pop(); // unswap swapVertices(partitionA, pair.two, partitionB, pair.one); } } /** Chooses the least cost swap and performs it **/ public double doSingleSwap(LinkedList<Edge> swaps) { Edge maxPair = null; double maxGain = Double.NEGATIVE_INFINITY; for (Vertex v_a : unswappedA) { for (Vertex v_b : unswappedB) { Edge e = graph.findConnected(v_a, v_b); double edge_cost = (e != null) ? e.weight : 0; // Calculate the gain in cost if these vertices were swappeds double gain = getVertexCost(v_a) + getVertexCost(v_b) - 2 * edge_cost; if (gain > maxGain) { maxPair = new Edge(v_a, v_b); maxGain = gain; } } } swapVertices(partitionA, maxPair.one, partitionB, maxPair.two); swaps.push(maxPair); unswappedA.remove(maxPair.one); unswappedB.remove(maxPair.two); return getCutCost(); } /** Returns the difference of external cost and internal cost of this vertex. * When moving a vertex from within group A, all internal edges become external * edges and the opposite **/ public double getVertexCost(Vertex v) { double cost = 0; boolean v1isInA = partitionA.contains(v); for (Vertex v2 : graph.getVertices()) { boolean v2isInA = partitionA.contains(v2); Edge edge = graph.findConnected(v, v2); double edge_cost = (edge != null) ? edge.weight : 0; if (v1isInA != v2isInA) // external cost += edge_cost; else cost -= edge_cost; } return cost; } /** Returns the sum of the costs of all edges between A and B **/ public double getCutCost() { double cost = 0; for (Edge edge : graph.getEdges()) { boolean firstInA = partitionA.contains(edge.one); boolean secondInA= partitionA.contains(edge.two); if (firstInA != secondInA) // external cost += edge.weight; } return cost; } /** Swaps va and vb in groups a and b **/ public void swapVertices(VertexGroup a, Vertex va, VertexGroup b, Vertex vb) { if (!a.contains(va) || a.contains(vb) || !b.contains(vb) || b.contains(va)) throw new RuntimeException("Invalid swap"); a.remove(va); a.add(vb); b.remove(vb); b.add(va); } }
package eiti.sag.facebookcrawler.accessor; public class FetchUserFailedException extends RuntimeException { public FetchUserFailedException(Throwable cause) { super(cause); } }
package css.viewpager; import androidx.appcompat.app.AppCompatActivity; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import androidx.viewpager2.widget.ViewPager2; import android.os.Bundle; // https://www.geeksforgeeks.org/image-slider-in-android-using-viewpager/ public class MainActivity extends AppCompatActivity { ViewPager2 viewPage; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Set up the ImagePageAdaoter similar to other RecycleView Adapters viewPage = (ViewPager2) findViewById(R.id.viewPagerMain); ImagePagerAdapter adapter = new ImagePagerAdapter(); viewPage.setAdapter(adapter); adapter.notifyDataSetChanged(); } }
package com.facebook.react.packagerconnection; import android.os.Handler; import android.os.Looper; import com.facebook.common.e.a; import g.i; import java.io.IOException; import java.util.concurrent.TimeUnit; import okhttp3.ac; import okhttp3.ae; import okhttp3.ai; import okhttp3.aj; import okhttp3.y; public final class ReconnectingWebSocket extends aj { private static final String TAG = ReconnectingWebSocket.class.getSimpleName(); private boolean mClosed; private ConnectionCallback mConnectionCallback; private final Handler mHandler; private MessageCallback mMessageCallback; private boolean mSuppressConnectionErrors; private final String mUrl; private ai mWebSocket; public ReconnectingWebSocket(String paramString, MessageCallback paramMessageCallback, ConnectionCallback paramConnectionCallback) { this.mUrl = paramString; this.mMessageCallback = paramMessageCallback; this.mConnectionCallback = paramConnectionCallback; this.mHandler = new Handler(Looper.getMainLooper()); } private void abort(String paramString, Throwable paramThrowable) { String str = TAG; StringBuilder stringBuilder = new StringBuilder("Error occurred, shutting down websocket connection: "); stringBuilder.append(paramString); a.c(str, stringBuilder.toString(), paramThrowable); closeWebSocketQuietly(); } private void closeWebSocketQuietly() { ai ai1 = this.mWebSocket; if (ai1 != null) { try { ai1.b(1000, "End of session"); } catch (Exception exception) {} this.mWebSocket = null; } } private void reconnect() { if (!this.mClosed) { if (!this.mSuppressConnectionErrors) { String str = TAG; StringBuilder stringBuilder = new StringBuilder("Couldn't connect to \""); stringBuilder.append(this.mUrl); stringBuilder.append("\", will silently retry"); a.b(str, stringBuilder.toString()); this.mSuppressConnectionErrors = true; } this.mHandler.postDelayed(new Runnable() { public void run() { ReconnectingWebSocket.this.delayedReconnect(); } }, 2000L); return; } throw new IllegalStateException("Can't reconnect closed client"); } public final void closeQuietly() { this.mClosed = true; closeWebSocketQuietly(); this.mMessageCallback = null; ConnectionCallback connectionCallback = this.mConnectionCallback; if (connectionCallback != null) connectionCallback.onDisconnected(); } public final void connect() { if (!this.mClosed) { (new y.a()).a(10L, TimeUnit.SECONDS).c(10L, TimeUnit.SECONDS).b(0L, TimeUnit.MINUTES).a().a((new ac.a()).a(this.mUrl).c(), this); return; } throw new IllegalStateException("Can't connect closed client"); } public final void delayedReconnect() { // Byte code: // 0: aload_0 // 1: monitorenter // 2: aload_0 // 3: getfield mClosed : Z // 6: ifne -> 13 // 9: aload_0 // 10: invokevirtual connect : ()V // 13: aload_0 // 14: monitorexit // 15: return // 16: astore_1 // 17: aload_0 // 18: monitorexit // 19: aload_1 // 20: athrow // Exception table: // from to target type // 2 13 16 finally } public final void onClosed(ai paramai, int paramInt, String paramString) { // Byte code: // 0: aload_0 // 1: monitorenter // 2: aload_0 // 3: aconst_null // 4: putfield mWebSocket : Lokhttp3/ai; // 7: aload_0 // 8: getfield mClosed : Z // 11: ifne -> 34 // 14: aload_0 // 15: getfield mConnectionCallback : Lcom/facebook/react/packagerconnection/ReconnectingWebSocket$ConnectionCallback; // 18: ifnull -> 30 // 21: aload_0 // 22: getfield mConnectionCallback : Lcom/facebook/react/packagerconnection/ReconnectingWebSocket$ConnectionCallback; // 25: invokeinterface onDisconnected : ()V // 30: aload_0 // 31: invokespecial reconnect : ()V // 34: aload_0 // 35: monitorexit // 36: return // 37: astore_1 // 38: aload_0 // 39: monitorexit // 40: aload_1 // 41: athrow // Exception table: // from to target type // 2 30 37 finally // 30 34 37 finally } public final void onFailure(ai paramai, Throwable paramThrowable, ae paramae) { // Byte code: // 0: aload_0 // 1: monitorenter // 2: aload_0 // 3: getfield mWebSocket : Lokhttp3/ai; // 6: ifnull -> 16 // 9: aload_0 // 10: ldc 'Websocket exception' // 12: aload_2 // 13: invokespecial abort : (Ljava/lang/String;Ljava/lang/Throwable;)V // 16: aload_0 // 17: getfield mClosed : Z // 20: ifne -> 43 // 23: aload_0 // 24: getfield mConnectionCallback : Lcom/facebook/react/packagerconnection/ReconnectingWebSocket$ConnectionCallback; // 27: ifnull -> 39 // 30: aload_0 // 31: getfield mConnectionCallback : Lcom/facebook/react/packagerconnection/ReconnectingWebSocket$ConnectionCallback; // 34: invokeinterface onDisconnected : ()V // 39: aload_0 // 40: invokespecial reconnect : ()V // 43: aload_0 // 44: monitorexit // 45: return // 46: astore_1 // 47: aload_0 // 48: monitorexit // 49: aload_1 // 50: athrow // Exception table: // from to target type // 2 16 46 finally // 16 39 46 finally // 39 43 46 finally } public final void onMessage(ai paramai, i parami) { // Byte code: // 0: aload_0 // 1: monitorenter // 2: aload_0 // 3: getfield mMessageCallback : Lcom/facebook/react/packagerconnection/ReconnectingWebSocket$MessageCallback; // 6: ifnull -> 19 // 9: aload_0 // 10: getfield mMessageCallback : Lcom/facebook/react/packagerconnection/ReconnectingWebSocket$MessageCallback; // 13: aload_2 // 14: invokeinterface onMessage : (Lg/i;)V // 19: aload_0 // 20: monitorexit // 21: return // 22: astore_1 // 23: aload_0 // 24: monitorexit // 25: aload_1 // 26: athrow // Exception table: // from to target type // 2 19 22 finally } public final void onMessage(ai paramai, String paramString) { // Byte code: // 0: aload_0 // 1: monitorenter // 2: aload_0 // 3: getfield mMessageCallback : Lcom/facebook/react/packagerconnection/ReconnectingWebSocket$MessageCallback; // 6: ifnull -> 19 // 9: aload_0 // 10: getfield mMessageCallback : Lcom/facebook/react/packagerconnection/ReconnectingWebSocket$MessageCallback; // 13: aload_2 // 14: invokeinterface onMessage : (Ljava/lang/String;)V // 19: aload_0 // 20: monitorexit // 21: return // 22: astore_1 // 23: aload_0 // 24: monitorexit // 25: aload_1 // 26: athrow // Exception table: // from to target type // 2 19 22 finally } public final void onOpen(ai paramai, ae paramae) { // Byte code: // 0: aload_0 // 1: monitorenter // 2: aload_0 // 3: aload_1 // 4: putfield mWebSocket : Lokhttp3/ai; // 7: aload_0 // 8: iconst_0 // 9: putfield mSuppressConnectionErrors : Z // 12: aload_0 // 13: getfield mConnectionCallback : Lcom/facebook/react/packagerconnection/ReconnectingWebSocket$ConnectionCallback; // 16: ifnull -> 28 // 19: aload_0 // 20: getfield mConnectionCallback : Lcom/facebook/react/packagerconnection/ReconnectingWebSocket$ConnectionCallback; // 23: invokeinterface onConnected : ()V // 28: aload_0 // 29: monitorexit // 30: return // 31: astore_1 // 32: aload_0 // 33: monitorexit // 34: aload_1 // 35: athrow // Exception table: // from to target type // 2 28 31 finally } public final void sendMessage(i parami) throws IOException { // Byte code: // 0: aload_0 // 1: monitorenter // 2: aload_0 // 3: getfield mWebSocket : Lokhttp3/ai; // 6: ifnull -> 23 // 9: aload_0 // 10: getfield mWebSocket : Lokhttp3/ai; // 13: aload_1 // 14: invokeinterface d : (Lg/i;)Z // 19: pop // 20: aload_0 // 21: monitorexit // 22: return // 23: new java/nio/channels/ClosedChannelException // 26: dup // 27: invokespecial <init> : ()V // 30: athrow // 31: astore_1 // 32: aload_0 // 33: monitorexit // 34: aload_1 // 35: athrow // Exception table: // from to target type // 2 20 31 finally // 23 31 31 finally } public final void sendMessage(String paramString) throws IOException { // Byte code: // 0: aload_0 // 1: monitorenter // 2: aload_0 // 3: getfield mWebSocket : Lokhttp3/ai; // 6: ifnull -> 23 // 9: aload_0 // 10: getfield mWebSocket : Lokhttp3/ai; // 13: aload_1 // 14: invokeinterface b : (Ljava/lang/String;)Z // 19: pop // 20: aload_0 // 21: monitorexit // 22: return // 23: new java/nio/channels/ClosedChannelException // 26: dup // 27: invokespecial <init> : ()V // 30: athrow // 31: astore_1 // 32: aload_0 // 33: monitorexit // 34: aload_1 // 35: athrow // Exception table: // from to target type // 2 20 31 finally // 23 31 31 finally } public static interface ConnectionCallback { void onConnected(); void onDisconnected(); } public static interface MessageCallback { void onMessage(i param1i); void onMessage(String param1String); } } /* Location: C:\Users\august\Desktop\tik\df_rn_kit\classes.jar.jar!\com\facebook\react\packagerconnection\ReconnectingWebSocket.class * Java compiler version: 6 (50.0) * JD-Core Version: 1.1.3 */
class Solution { int max = 0; int len = 0; String ans; public String longestPalindrome(String s) { if(s.length() == 1) { return s; } for (int i = 0; i < s.length(); i++) { isPalindrome(i,i, s.length(), s, 0, new StringBuilder()); isPalindrome(i,i+1, s.length(), s, 0, new StringBuilder()); } return ans; } void isPalindrome(int i, int j, int len, String s, int cur, StringBuilder sb) { if(i < 0 || j >= s.length()) { return; } if(s.charAt(i) == s.charAt(j)) { if(i != j) { cur +=2; sb.append(s.charAt(i)); sb.insert(0, s.charAt(j)); } else { cur += 1; sb.append(s.charAt(i)); } if(cur > max) { max = cur; ans = sb.toString(); } isPalindrome(--i, ++j, len, s, cur, sb); } } }
package az.com.socar.workerpermission.persistance.repository; import az.com.socar.workerpermission.persistance.entity.User; import az.com.socar.workerpermission.persistance.service.WorkerPermissionService; import az.com.socar.workerpermission.persistance.service.impl.WorkerPermissionServiceImpl; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.CommandLineRunner; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Service; import java.util.Arrays; import java.util.List; //@Service public class UserDbInit implements CommandLineRunner{ private WorkerPermissionService permissionService = new WorkerPermissionServiceImpl(); private UserRepository userRepository; @Autowired private PasswordEncoder passwordEncoder; public UserDbInit(UserRepository userRepository) { this.userRepository = userRepository; } @Override public void run(String... args) throws Exception { // this.userRepository.deleteAll(); User u = new User("user@gmail.com", passwordEncoder.encode("1"), "User", "ddd", permissionService.getPositionById(1L), 1L, 0L); User a = new User("admin@gmail.com", passwordEncoder.encode("123"), "Admin", "dddd", permissionService.getPositionById(1L), 1L, 0L); List<User> userList = Arrays.asList(u, a); System.out.println("Users + " + userList); this.userRepository.saveAll(userList); } }
package stepDefinitions; import cucumber.api.Scenario; import cucumber.api.java.After; import cucumber.api.java.Before; /** * @author rahulr * * This class performs Before and After Scenario operations * */ public class BaseDefinitions extends Hooks { @Before() public void before(Scenario scenario){ setupwebdriver(); } @After public void after(Scenario scenario){ embedScreenshot(scenario); closeDriver(); } }
package ir.nrdc.model.repository; import com.mysql.cj.util.StringUtils; import ir.nrdc.model.entity.Author; import ir.nrdc.model.entity.Book; import org.springframework.data.jpa.domain.Specification; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Join; import javax.persistence.criteria.Predicate; import java.util.ArrayList; import java.util.List; import java.util.Objects; public class BookSpecifications { public static Specification<Book> findMaxMatch(String name, String isbn, Author author) { return (Specification<Book>) (root, criteriaQuery, builder) -> { CriteriaQuery<Book> resultCriteria = builder.createQuery(Book.class); List<Predicate> predicates = new ArrayList<>(); if (Objects.nonNull(author)) { Join<Object, Object> bookJoin = root.join("author"); if (!StringUtils.isNullOrEmpty(author.getName())) { predicates.add(builder.equal(bookJoin.get("name"), author.getName())); } if (!StringUtils.isNullOrEmpty(author.getFamily())) { predicates.add(builder.equal(bookJoin.get("family"), author.getFamily())); } } if (!StringUtils.isNullOrEmpty(name)) { predicates.add(builder.equal(root.get("name"), name)); } if (!StringUtils.isNullOrEmpty(isbn)) { predicates.add(builder.equal(root.get("isbn"), isbn)); } resultCriteria.select(root).where(predicates.toArray(new Predicate[0])); return resultCriteria.getRestriction(); }; } }
package com.example.akasztofa; import androidx.annotation.NonNull; import androidx.appcompat.app.AlertDialog; import androidx.appcompat.app.AppCompatActivity; import android.content.DialogInterface; import android.graphics.Color; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import java.util.ArrayList; public class MainActivity extends AppCompatActivity { private Button btnLe, btnFel, btnTippel; private TextView textBetu, textSzoveg; private String[] betuk, szavak; private ArrayList<String> valasztottBetuk = new ArrayList<>(); private int betuPoz, akasztottAllapot; private String kitalalandoSzo, vonalszo; private ImageView imgAkasztofa; private AlertDialog.Builder uzenet; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); init(); UjJatek(); btnLe.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (betuPoz == 0) { betuPoz = betuk.length - 1; } else { betuPoz--; } textBetu.setText(betuk[betuPoz]); //színezés if (valasztottBetuk.contains(betuk[betuPoz])) { textBetu.setTextColor(Color.BLACK); } else { textBetu.setTextColor(Color.RED); } } }); btnFel.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (betuPoz == betuk.length - 1) { betuPoz = 0; } else { betuPoz++; } textBetu.setText(betuk[betuPoz]); //színezés if (valasztottBetuk.contains(betuk[betuPoz])) { textBetu.setTextColor(Color.BLACK); } else { textBetu.setTextColor(Color.RED); } } }); btnTippel.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //ha már volt tippelve a betű if (valasztottBetuk.contains(betuk[betuPoz])) { Toast.makeText(MainActivity.this, "Ezt a betűt már választottad.", Toast.LENGTH_SHORT).show(); } else { valasztottBetuk.add(betuk[betuPoz]); textBetu.setTextColor(Color.BLACK); String valasztottBetu = String.valueOf(textBetu.getText()); //jó tipp if (kitalalandoSzo.contains(valasztottBetu)) { Toast.makeText(MainActivity.this, "Jó tipp!", Toast.LENGTH_SHORT).show(); for (int i = 0; i < kitalalandoSzo.length(); i++) { if (kitalalandoSzo.charAt(i) == valasztottBetu.charAt(0)) { vonalszo = vonalszo.substring(0, i) + valasztottBetu + vonalszo.substring(i + 1); textSzoveg.setText(vonalszo); } } } //rossz tipp else { Toast.makeText(MainActivity.this, "Rossz tipp!", Toast.LENGTH_SHORT).show(); akasztottAllapot++; } switch (akasztottAllapot) { case 0: imgAkasztofa.setImageResource(R.drawable.akasztofa00);break; case 1: imgAkasztofa.setImageResource(R.drawable.akasztofa01);break; case 2: imgAkasztofa.setImageResource(R.drawable.akasztofa02);break; case 3: imgAkasztofa.setImageResource(R.drawable.akasztofa03);break; case 4: imgAkasztofa.setImageResource(R.drawable.akasztofa04);break; case 5: imgAkasztofa.setImageResource(R.drawable.akasztofa05);break; case 6: imgAkasztofa.setImageResource(R.drawable.akasztofa06);break; case 7: imgAkasztofa.setImageResource(R.drawable.akasztofa07);break; case 8: imgAkasztofa.setImageResource(R.drawable.akasztofa08);break; case 9: imgAkasztofa.setImageResource(R.drawable.akasztofa09);break; case 10: imgAkasztofa.setImageResource(R.drawable.akasztofa10);break; case 11: imgAkasztofa.setImageResource(R.drawable.akasztofa11);break; case 12: imgAkasztofa.setImageResource(R.drawable.akasztofa12);break; case 13: imgAkasztofa.setImageResource(R.drawable.akasztofa13);break; } //Alertdialog if (akasztottAllapot < 13 && !vonalszo.contains("_")) { uzenet.setTitle("Megmenekültél!"); AlertDialog dialog = uzenet.create(); dialog.show(); } else if (akasztottAllapot == 13 && vonalszo.contains("_")) { uzenet.setTitle("Felakasztottak!"); AlertDialog dialog = uzenet.create(); dialog.show(); } } } }); } private void init() { btnLe = findViewById(R.id.btnLe); btnFel = findViewById(R.id.btnFel); btnTippel = findViewById(R.id.btnTippel); textBetu = findViewById(R.id.textBetu); textSzoveg = findViewById(R.id.textSzoveg); imgAkasztofa = findViewById(R.id.imgAkasztofa); betuk = new String[]{"A", "Á", "B", "C", "D", "E", "É", "F", "G", "H", "I", "Í", "J", "K", "L", "M", "N", "O", "Ó", "Ö", "Ő", "P", "Q", "R", "S", "T", "U", "Ú", "Ü", "Ű", "V", "W", "X", "Y", "Z"}; //a magyar ABC minden betűje benne van szavak = new String[]{"PRÓBA", "TÜCSÖK", "DÉLIBÁB", "ŰRHAJÓ", "MORZE", "FOGÍNY", "QUEEN", "FŐNIX", "WHISKY", "ÚJVÁROS"}; uzenet = new AlertDialog.Builder(MainActivity.this); uzenet.setCancelable(false).setMessage("Szeretnél új játékot játszani?"); uzenet.setPositiveButton("Igen", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { UjJatek(); } }); uzenet.setNegativeButton("Nem", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { finish(); } }); } private void UjJatek() { imgAkasztofa.setImageResource(R.drawable.akasztofa00); textBetu.setText(String.valueOf("A")); valasztottBetuk.clear(); akasztottAllapot = 0; betuPoz = 0; kitalalandoSzo = szavak[(int)(Math.random() * szavak.length)]; vonalszo = ""; for (int i = 0; i < kitalalandoSzo.length(); i++) { vonalszo = vonalszo + "_"; } textSzoveg.setText(vonalszo); } @Override protected void onSaveInstanceState(@NonNull Bundle outState) { outState.putInt("betuPoz", betuPoz); outState.putInt("akasztottAllapot", akasztottAllapot); outState.putString("kitalalandoSzo", kitalalandoSzo); outState.putString("vonalszo", vonalszo); outState.putStringArrayList("valasztottBetuk", valasztottBetuk); super.onSaveInstanceState(outState); } @Override protected void onRestoreInstanceState(@NonNull Bundle savedInstanceState) { super.onRestoreInstanceState(savedInstanceState); betuPoz = savedInstanceState.getInt("betuPoz"); textBetu.setText(betuk[betuPoz]); akasztottAllapot = savedInstanceState.getInt("akasztottAllapot"); switch (akasztottAllapot) { case 0: imgAkasztofa.setImageResource(R.drawable.akasztofa00);break; case 1: imgAkasztofa.setImageResource(R.drawable.akasztofa01);break; case 2: imgAkasztofa.setImageResource(R.drawable.akasztofa02);break; case 3: imgAkasztofa.setImageResource(R.drawable.akasztofa03);break; case 4: imgAkasztofa.setImageResource(R.drawable.akasztofa04);break; case 5: imgAkasztofa.setImageResource(R.drawable.akasztofa05);break; case 6: imgAkasztofa.setImageResource(R.drawable.akasztofa06);break; case 7: imgAkasztofa.setImageResource(R.drawable.akasztofa07);break; case 8: imgAkasztofa.setImageResource(R.drawable.akasztofa08);break; case 9: imgAkasztofa.setImageResource(R.drawable.akasztofa09);break; case 10: imgAkasztofa.setImageResource(R.drawable.akasztofa10);break; case 11: imgAkasztofa.setImageResource(R.drawable.akasztofa11);break; case 12: imgAkasztofa.setImageResource(R.drawable.akasztofa12);break; case 13: imgAkasztofa.setImageResource(R.drawable.akasztofa13);break; } kitalalandoSzo = savedInstanceState.getString("kitalalandoSzo"); vonalszo = savedInstanceState.getString("vonalszo"); textSzoveg.setText(vonalszo); valasztottBetuk = savedInstanceState.getStringArrayList("valasztottBetuk"); } }
package tasks; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.interactions.Actions; class Task4 { void mainMethodTask4() { System.setProperty("webdriver.chrome.driver", "/home/antihixy/Desktop/chromedriver"); WebDriver driver = new ChromeDriver(); driver.get("https://news.mail.ru/incident/33094804/"); WebElement element = driver.findElement(By.xpath("//iframe[@id = 'instagram-embed-0']")); Actions actions = new Actions(driver); driver.switchTo().frame(element); WebElement instagrambutton = driver.findElement(By.xpath("/html/body/div/div[2]/div/div/a")); actions.moveToElement(instagrambutton).click().pause(1000).build().perform(); } }
package pl.smilu.fasada; public interface Czynnosci { public void idzDoPiwnicy(); public void wyjmijRower(); public void wyjdzNaPrzejazdzke(); public void jedz(); public void wrocDoDomu(); public void schowajRower(); public void napijSieElektrolitow(); }
package com.example.mvpclean.source.entity; import android.graphics.Bitmap; import android.os.Build; import java.util.Objects; import java.util.UUID; import javax.annotation.Nonnull; import androidx.annotation.NonNull; import androidx.annotation.RequiresApi; import androidx.room.ColumnInfo; import androidx.room.Entity; import androidx.room.Ignore; import androidx.room.Index; import androidx.room.PrimaryKey; /** * api 콜 이후 local Database에 저장. */ @Entity(tableName = "categories", indices = {@Index(value = {"caetgory_name", "caetgory_type"}, unique = true)}) public class Categories { @PrimaryKey @NonNull @ColumnInfo(name = "entry_id") private String mId; @Nonnull @ColumnInfo(name = "caetgory_name") private final String mName; @Nonnull @ColumnInfo(name = "caetgory_type") private final int mCategoryType; @Nonnull @ColumnInfo(name = "low_url") private final String mLowUrl; @Nonnull @ColumnInfo(name = "mid_url") private final String mMidUrl; @Nonnull @ColumnInfo(name = "high_url") private final String mHighurl; @Ignore Bitmap images; public Categories(@Nonnull String mName, int mCategoryType, @Nonnull String mLowUrl, @Nonnull String mMidUrl, @Nonnull String mHighurl) { this.mId = UUID.randomUUID().toString(); this.mName = mName; this.mCategoryType = mCategoryType; this.mLowUrl = mLowUrl; this.mMidUrl = mMidUrl; this.mHighurl = mHighurl; } @NonNull public String getId() { return mId; } @Nonnull public String getName() { return mName; } public int getCategoryType() { return mCategoryType; } @Nonnull public String getLowUrl() { return mLowUrl; } @Nonnull public String getMidUrl() { return mMidUrl; } @Nonnull public String getHighurl() { return mHighurl; } public Bitmap getImages() { return images; } @RequiresApi(api = Build.VERSION_CODES.KITKAT) @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Categories that = (Categories) o; return mCategoryType == that.mCategoryType && Objects.equals(mId, that.mId) && Objects.equals(mName, that.mName); } @RequiresApi(api = Build.VERSION_CODES.KITKAT) @Override public int hashCode() { return Objects.hash(mId, mName, mCategoryType); } public void setImages(Bitmap images) { this.images = images; } public void setId(@NonNull String mId) { this.mId = mId; } }
package codesum.lm.topicsum; import java.io.Serializable; import com.esotericsoftware.kryo.DefaultSerializer; import com.esotericsoftware.kryo.serializers.JavaSerializer; import com.google.common.collect.HashMultiset; import com.google.common.collect.Multiset; @DefaultSerializer(JavaSerializer.class) public class Topic implements Serializable { private static final long serialVersionUID = -6737290631881566109L; // Topic type IDs protected static final int[] BACKGROUND = new int[] { 0, 1, 2 }; public static final int nBackTopics = 3; public static final int CONTENT = 3; public static final int DOCUMENT = 4; // public static final int SENTENCE; public static final int nTopics = 5; // Multiset of all tokens assigned to this topic private final Multiset<Integer> tokens; // The type assigned to this topic (background, content, etc.) private final int topicID; public Topic(final int topicID) { this.tokens = HashMultiset.create(); this.topicID = topicID; } public void decrementTokenCount(final int token) { tokens.remove(token); } public void incrementTokenCount(final int token) { tokens.add(token); } public Multiset<Integer> getTokenMultiSet() { return tokens; } /** * @param token * (as an integer) * @return the number of times the token is assigned to this topic */ public int getTokenCount(final int token) { return tokens.count(token); } public int getTotalTokenCount() { return tokens.size(); } /** * @return TopicID of the token distribution in this topic */ public int getTopicID() { return topicID; } }
package com.davemorrissey.labs.subscaleview.view; import android.graphics.Bitmap; import com.davemorrissey.labs.subscaleview.a.c; public interface SubsamplingScaleImageView$e { void a(c cVar); void b(c cVar); void c(c cVar); void f(Bitmap bitmap); void hO(); void hP(); }
package at.fhj.swd.remoteFacade; import java.util.Hashtable; import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.NamingException; // The JNDI lookup name for a stateless session bean has the syntax of: // ejb:<appName>/<moduleName>/<distinctName>/<beanName>!<viewClassName> // // <appName> The application name is the name of the EAR that the EJB is // deployed in // (without the .ear). If the EJB JAR is not deployed in an EAR then this is // blank. The app name can also be specified in the EAR's application.xml // // <moduleName> By the default the module name is the name of the EJB JAR // file (without the // .jar suffix). The module name might be overridden in the ejb-jar.xml // // <distinctName> : WildFly allows each deployment to have an (optional) // distinct name. // This example does not use this so leave it blank. // // <beanName> : The name of the session been to be invoked. // // <viewClassName>: The fully qualified classname of the remote interface. // Must include // the whole package name. // "ejb:/wildfly-ejb-remote-server-side/CalculatorBean!" + // RemoteCalculator.class.getName() // java:global/EJB-Calculator-RemoteTest/CalculatorTestBean!org.se.lab.Calculator // ejb:/EJB-Calculator-RemoteTest/CalculatorTestBean!org.se.lab.Calculator /** * Instantiates remote object on JBoss server * @author Thomas Ascher * */ public class RemoteFactory { public static Object create(final String beanName, final String interfaceName) throws NamingException { Context context = createContext(); final String jndiName = "ejb:/fhj-ws2014-sd12-pse/" + beanName + "!" + interfaceName; return context.lookup(jndiName); } private static Context createContext() throws NamingException { final Hashtable<String, String> jndiProperties = new Hashtable<String, String>(); jndiProperties.put(Context.URL_PKG_PREFIXES, "org.jboss.ejb.client.naming"); return new InitialContext(jndiProperties); } }
package com.liferay.mobile.screens.messageboardscreenlet.view; import android.content.Context; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.AttributeSet; import android.util.Log; import com.liferay.mobile.screens.base.list.BaseListScreenlet; /** * Created by darshan on 20/8/15. */ public class MyGridView extends MyListView { private String TAG = "MyGridView"; public MyGridView(Context context) { super(context); } public MyGridView(Context context, AttributeSet attributes) { super(context, attributes); } public MyGridView(Context context, AttributeSet attributes, int defaultStyle) { super(context, attributes, defaultStyle); } @Override protected void onFinishInflate() { super.onFinishInflate(); // final StaggeredGridLayoutManager mLayoutManager = // new StaggeredGridLayoutManager(StaggeredGridLayoutManager.GAP_HANDLING_MOVE_ITEMS_BETWEEN_SPANS, StaggeredGridLayoutManager // .VERTICAL); final GridLayoutManager mLayoutManager = new GridLayoutManager(context, 2, GridLayoutManager.VERTICAL, false); _recyclerView.setLayoutManager(mLayoutManager); _recyclerView.setOnScrollListener(new RecyclerView.OnScrollListener() { @Override public void onScrollStateChanged(RecyclerView recyclerView, int newState) { super.onScrollStateChanged(recyclerView, newState); } @Override public void onScrolled(RecyclerView recyclerView, int dx, int dy) { visibleItemCount = mLayoutManager.getChildCount(); totalItemCount = mLayoutManager.getItemCount(); pastVisiblesItems = mLayoutManager.findFirstVisibleItemPosition(); if (checkForLoadMore) { if ((visibleItemCount + pastVisiblesItems + BOTTOM_OFFSET) >= totalItemCount) { checkForLoadMore = false; Log.d(TAG, "load next page"); currentRow++; ((BaseListScreenlet) getParent()).loadPage(currentRow); } } super.onScrolled(recyclerView, dx, dy); } }); } }
package com.level01.ÇÏ»þµå¼ö; public class MTest { public static void main(String[] args) { int arr = 10; Solution solution = new Solution(); System.out.println(solution.solution(arr)); } } class Solution { public boolean solution(int x) { boolean answer = true; int tmp = 0; String [] xArr = (x+"").split(""); for(int i = 0; i < xArr.length; i++){ tmp += Integer.parseInt(xArr[i]); } if(!(x % tmp == 0)){ answer = false; } return answer; } }
package ast; import ui.Main; import javax.script.ScriptException; import java.io.FileNotFoundException; import java.io.UnsupportedEncodingException; import java.util.HashMap; import java.util.Map; public class DISPLAY extends STATEMENT { NAME name; Boolean graph = false; Boolean everyone = false; @Override public void parse() { tokenizer.getNext(); if (tokenizer.checkToken("graph")) graph = true; else if (!tokenizer.checkToken("text")) System.exit(0); tokenizer.getNext(); tokenizer.getAndCheckNext(" for "); if (tokenizer.checkToken("everyone")) { everyone = true; tokenizer.getNext(); } else { name = new NAME(); name.parse(); } if(!tokenizer.checkToken(",")) System.exit(0); } @Override public String evaluate() throws FileNotFoundException, UnsupportedEncodingException, ScriptException { int root = Main.displayGraphCount; if(graph){ if(everyone) { //keep track of value of each node based on name HashMap<String, Integer> nameNumber= new HashMap<String, Integer>(); //need to loop through each entry in symbol table and add anything that is a negative number for (Map.Entry<String, HashMap<String, Float>> current: Main.symbolTable.entrySet()) { HashMap<String, Float> d = current.getValue(); String n = current.getKey(); for (Map.Entry<String, Float> entry : d.entrySet()) { if (entry.getValue() <= 0) { Integer positionFrom = nameNumber.get(n); Integer positionTo = nameNumber.get(entry.getKey()); /*check if nodes already have a number associated with name, or if we need to create a new number this is due to the fact that nodes are identified by their name, so we have to assign numbers to nodes based on the current graph. */ if (positionFrom == null) { nameNumber.put(n, Main.displayGraphCount); positionFrom = Main.displayGraphCount; Main.displayGraphCount++; } if (positionTo == null) { nameNumber.put(entry.getKey(), Main.displayGraphCount); positionTo = Main.displayGraphCount; Main.displayGraphCount++; } Float temp = Math.abs(entry.getValue()); String amountOwed = String.format("%.2f", temp); createNodeEdge(positionFrom, n, positionTo, entry.getKey(),amountOwed); } } } //clear map so that next time "display debts for everyone is called", those results aren't merged with this current graph nameNumber.clear(); } else { //return dot program string a -> b thing String n = name.evaluate(); HashMap<String, Float> d = Main.symbolTable.get(n); //loop through each entry in for (Map.Entry<String, Float> entry : d.entrySet()) { Float temp = Math.abs(entry.getValue()); String amountOwed = String.format("%.2f", temp); if (entry.getValue() <= 0) { Main.displayGraphCount++; createNodeEdge(root, n, Main.displayGraphCount, entry.getKey(), amountOwed); Main.displayGraphCount++; } else { Main.displayGraphCount++; createNodeEdge(Main.displayGraphCount, entry.getKey(), root, n, amountOwed); Main.displayGraphCount++; } System.out.println(entry.getKey() + " = " + entry.getValue()); } writer.println(root + " [fontcolor = \"red\"];"); } } else { //return what it would look like as a text if (everyone) { writer.println(Main.displayTextCount + " [shape = box label =\" everyone\'s debts\"];"); writer.println((Main.displayTextCount-0.5) + " [shape = box label =\""); //need to loop through each entry in symbol table and add anything that is a negative number for (Map.Entry<String, HashMap<String, Float>> current: Main.symbolTable.entrySet()) { HashMap<String, Float> d = current.getValue(); String n = current.getKey(); for (Map.Entry<String, Float> entry : d.entrySet()) { if (entry.getValue() <= 0) { Float temp = Math.abs(entry.getValue()); String amountOwed = String.format("%.2f", temp); createTextForm(n, entry.getKey(), amountOwed); } } } writer.print("\"];\n"); writer.println(Main.displayTextCount + "->" + (Main.displayTextCount-0.5) + ";"); Main.displayTextCount--; } else { String n = name.evaluate(); HashMap<String, Float> d = Main.symbolTable.get(n); writer.println(Main.displayTextCount + " [shape = box label =\"" + n + "\'s debts\"];"); writer.println((Main.displayTextCount-0.5) + " [shape = box label =\""); for (Map.Entry<String, Float> entry : d.entrySet()) { Float temp = Math.abs(entry.getValue()); String amountOwed = String.format("%.2f", temp); if (entry.getValue() <= 0) { createTextForm(n, entry.getKey(), amountOwed); } else { createTextForm(entry.getKey(), n,amountOwed); } } writer.print("\"];\n"); writer.println(Main.displayTextCount + "->" + (Main.displayTextCount-0.5) + ";"); Main.displayTextCount--; } } return null; } private void createNodeEdge(Integer from, String fromLabel, Integer to, String toLabel, String edgeValue) { writer.println(from + " [label = \"" + fromLabel + "\"];"); writer.println(to + " [label = \"" + toLabel + "\"];"); writer.println(from + "->" + to + " [label = \"" + edgeValue + "\"];"); if (everyone) { writer.println(from + " [fontcolor = \"blue\"];"); writer.println(to + " [fontcolor = \"blue\"];"); } } private void createTextForm(String owes, String isOwed, String amount) { writer.print(owes + " owes " + isOwed + " $" + amount + " \n "); } }
package com.diozero.devices.imu.invensense; /* * #%L * Organisation: diozero * Project: diozero - IMU device classes * Filename: MPU9150Constants.java * * This file is part of the diozero project. More information about this project * can be found at https://www.diozero.com/. * %% * Copyright (C) 2016 - 2023 diozero * %% * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * #L% */ // MPU9150 (or MPU6050 w/ AK8975 on the auxiliary bus) public interface MPU9150Constants { // 16bit signed value (-32,768 to 32,767) static final int HARDWARE_UNIT = ((int)Math.pow(2, 16)) / 2; // ((2^16)/2 = 32,768) // TODO Validate the scale of the Quaternion data static final double QUATERNION_SCALE = 1.0 / (HARDWARE_UNIT/2); // From https://github.com/pocketmoon/MPU-6050-Arduino-Micro-Head-Tracker/blob/master/MPUReset/MPU6050Reset.ino //private static final double QUATERNION_SCALE = 1.0 / 16384; static final byte BIT_I2C_MST_VDDIO = (byte)0x80; static final byte BIT_FIFO_EN = 0x40; static final byte BIT_DMP_EN = (byte)0x80; static final byte BIT_FIFO_RST = 0x04; static final byte BIT_DMP_RST = 0x08; static final byte BIT_FIFO_OVERFLOW = 0x10; static final byte BIT_DATA_RDY_EN = 0x01; static final byte BIT_DMP_INT_EN = 0x02; static final byte BIT_MOT_INT_EN = 0x40; static final byte BITS_FSR = 0x18; static final byte BITS_LPF = 0x07; static final byte BITS_HPF = 0x07; static final byte BITS_CLK = 0x07; static final byte BIT_FIFO_SIZE_1024 = 0x40; static final byte BIT_FIFO_SIZE_2048 = (byte)0x80; static final byte BIT_FIFO_SIZE_4096 = (byte)0xC0; static final byte BIT_RESET = (byte)0x80; static final byte BIT_SLEEP = 0x40; static final byte BIT_S0_DELAY_EN = 0x01; static final byte BIT_S2_DELAY_EN = 0x04; static final byte BITS_SLAVE_LENGTH = 0x0F; static final byte BIT_SLAVE_BYTE_SW = 0x40; static final byte BIT_SLAVE_GROUP = 0x10; static final byte BIT_SLAVE_EN = (byte)0x80; static final byte BIT_I2C_READ = (byte)0x80; static final byte BITS_I2C_MASTER_DLY = 0x1F; static final byte BIT_AUX_IF_EN = 0x20; static final byte BIT_ACTL = (byte)0x80; static final byte BIT_LATCH_EN = 0x20; static final byte BIT_ANY_RD_CLR = 0x10; static final byte BIT_BYPASS_EN = 0x02; static final byte BITS_WOM_EN = (byte)0xC0; static final byte BIT_LPA_CYCLE = 0x20; static final byte BIT_STBY_XA = 0x20; static final byte BIT_STBY_YA = 0x10; static final byte BIT_STBY_ZA = 0x08; static final byte BIT_STBY_XG = 0x04; static final byte BIT_STBY_YG = 0x02; static final byte BIT_STBY_ZG = 0x01; static final byte BIT_STBY_XYZA = (byte)(BIT_STBY_XA | BIT_STBY_YA | BIT_STBY_ZA); static final byte BIT_STBY_XYZG = (byte)(BIT_STBY_XG | BIT_STBY_YG | BIT_STBY_ZG); static final byte INV_TEMP = (byte)0x80; static final byte INV_X_GYRO = 0x40; static final byte INV_Y_GYRO = 0x20; static final byte INV_Z_GYRO = 0x10; static final byte INV_XYZ_GYRO = INV_X_GYRO | INV_Y_GYRO | INV_Z_GYRO; static final byte INV_XYZ_ACCEL = 0x08; static final byte INV_XYZ_COMPASS = 0x01; static final int MAX_COMPASS_SAMPLE_RATE = 100; // MUP-9150 main I2C address static final int MPU9150_ADDRESS_AD0_LOW = 0x68; // address pin low (GND), default for InvenSense evaluation board static final int MPU9150_ADDRESS_AD0_HIGH = 0x69; // address pin high (VCC) static final int MPU9150_DEFAULT_ADDRESS = MPU9150_ADDRESS_AD0_LOW; // Accelerometer and gyroscope registers static final int MPU9150_RA_SMPL_RATE_DIV = 0x19; static final int MPU9150_RA_CONFIG = 0x1A; static final int MPU9150_RA_GYRO_CONFIG = 0x1B; static final int MPU9150_RA_ACCEL_CONFIG = 0x1C; static final int MPU9150_RA_FF_THR = 0x1D; static final int MPU9150_RA_FF_DUR = 0x1E; static final int MPU9150_RA_MOT_THR = 0x1F; static final int MPU9150_RA_MOT_DUR = 0x20; static final int MPU9150_RA_ZRMOT_THR = 0x21; static final int MPU9150_RA_ZRMOT_DUR = 0x22; static final int MPU9150_RA_FIFO_EN = 0x23; static final int MPU9150_RA_I2C_MST_CTRL = 0x24; static final int MPU9150_RA_I2C_SLV0_ADDR = 0x25; static final int MPU9150_RA_I2C_SLV0_REG = 0x26; static final int MPU9150_RA_I2C_SLV0_CTRL = 0x27; static final int MPU9150_RA_I2C_SLV1_ADDR = 0x28; static final int MPU9150_RA_I2C_SLV1_REG = 0x29; static final int MPU9150_RA_I2C_SLV1_CTRL = 0x2A; static final int MPU9150_RA_I2C_SLV2_ADDR = 0x2B; static final int MPU9150_RA_I2C_SLV2_REG = 0x2C; static final int MPU9150_RA_I2C_SLV2_CTRL = 0x2D; static final int MPU9150_RA_I2C_SLV3_ADDR = 0x2E; static final int MPU9150_RA_I2C_SLV3_REG = 0x2F; static final int MPU9150_RA_I2C_SLV3_CTRL = 0x30; static final int MPU9150_RA_I2C_SLV4_ADDR = 0x31; static final int MPU9150_RA_I2C_SLV4_REG = 0x32; static final int MPU9150_RA_I2C_SLV4_DO = 0x33; static final int MPU9150_RA_I2C_SLV4_CTRL = 0x34; static final int MPU9150_RA_I2C_SLV4_DI = 0x35; static final int MPU9150_RA_I2C_MST_STATUS = 0x36; static final int MPU9150_RA_INT_PIN_CFG = 0x37; static final int MPU9150_RA_INT_ENABLE = 0x38; static final int MPU9150_RA_DMP_INT_STATUS = 0x39; static final int MPU9150_RA_INT_STATUS = 0x3A; static final int MPU9150_RA_ACCEL_XOUT_H = 0x3B; static final int MPU9150_RA_ACCEL_XOUT_L = 0x3C; static final int MPU9150_RA_ACCEL_YOUT_H = 0x3D; static final int MPU9150_RA_ACCEL_YOUT_L = 0x3E; static final int MPU9150_RA_ACCEL_ZOUT_H = 0x3F; static final int MPU9150_RA_ACCEL_ZOUT_L = 0x40; static final int MPU9150_RA_TEMP_OUT_H = 0x41; static final int MPU9150_RA_TEMP_OUT_L = 0x42; static final int MPU9150_RA_GYRO_XOUT_H = 0x43; static final int MPU9150_RA_GYRO_XOUT_L = 0x44; static final int MPU9150_RA_GYRO_YOUT_H = 0x45; static final int MPU9150_RA_GYRO_YOUT_L = 0x46; static final int MPU9150_RA_GYRO_ZOUT_H = 0x47; static final int MPU9150_RA_GYRO_ZOUT_L = 0x48; static final int MPU9150_RA_EXT_SENS_DATA_00 = 0x49; static final int MPU9150_RA_EXT_SENS_DATA_01 = 0x4A; static final int MPU9150_RA_EXT_SENS_DATA_02 = 0x4B; static final int MPU9150_RA_EXT_SENS_DATA_03 = 0x4C; static final int MPU9150_RA_EXT_SENS_DATA_04 = 0x4D; static final int MPU9150_RA_EXT_SENS_DATA_05 = 0x4E; static final int MPU9150_RA_EXT_SENS_DATA_06 = 0x4F; static final int MPU9150_RA_EXT_SENS_DATA_07 = 0x50; static final int MPU9150_RA_EXT_SENS_DATA_08 = 0x51; static final int MPU9150_RA_EXT_SENS_DATA_09 = 0x52; static final int MPU9150_RA_EXT_SENS_DATA_10 = 0x53; static final int MPU9150_RA_EXT_SENS_DATA_11 = 0x54; static final int MPU9150_RA_EXT_SENS_DATA_12 = 0x55; static final int MPU9150_RA_EXT_SENS_DATA_13 = 0x56; static final int MPU9150_RA_EXT_SENS_DATA_14 = 0x57; static final int MPU9150_RA_EXT_SENS_DATA_15 = 0x58; static final int MPU9150_RA_EXT_SENS_DATA_16 = 0x59; static final int MPU9150_RA_EXT_SENS_DATA_17 = 0x5A; static final int MPU9150_RA_EXT_SENS_DATA_18 = 0x5B; static final int MPU9150_RA_EXT_SENS_DATA_19 = 0x5C; static final int MPU9150_RA_EXT_SENS_DATA_20 = 0x5D; static final int MPU9150_RA_EXT_SENS_DATA_21 = 0x5E; static final int MPU9150_RA_EXT_SENS_DATA_22 = 0x5F; static final int MPU9150_RA_EXT_SENS_DATA_23 = 0x60; static final int MPU9150_RA_MOT_DETECT_STATUS= 0x61; static final int MPU9150_RA_I2C_SLV0_DO = 0x63; static final int MPU9150_RA_I2C_SLV1_DO = 0x64; static final int MPU9150_RA_I2C_SLV2_DO = 0x65; static final int MPU9150_RA_I2C_SLV3_DO = 0x66; static final int MPU9150_RA_I2C_MST_DELAY_CTRL= 0x67; static final int MPU9150_RA_SIGNAL_PATH_RESET= 0x68; static final int MPU9150_RA_MOT_DETECT_CTRL = 0x69; static final int MPU9150_RA_USER_CTRL = 0x6A; static final int MPU9150_RA_PWR_MGMT_1 = 0x6B; static final int MPU9150_RA_PWR_MGMT_2 = 0x6C; static final int MPU9150_RA_BANK_SEL = 0x6D; static final int MPU9150_RA_MEM_START_ADDR = 0x6E; static final int MPU9150_RA_MEM_R_W = 0x6F; static final int MPU9150_RA_DMP_CFG_1 = 0x70; static final int MPU9150_RA_DMP_CFG_2 = 0x71; static final int MPU9150_RA_FIFO_COUNTH = 0x72; static final int MPU9150_RA_FIFO_COUNTL = 0x73; static final int MPU9150_RA_FIFO_R_W = 0x74; static final int MPU9150_RA_WHO_AM_I = 0x75; // Undocumented registers? static final int MPU9150_RA_XG_OFFS_TC = 0x00; //[7] PWR_MODE, [6:1] XG_OFFS_TC, [0] OTP_BNK_VLD static final int MPU9150_RA_YG_OFFS_TC = 0x01; //[7] PWR_MODE, [6:1] YG_OFFS_TC, [0] OTP_BNK_VLD static final int MPU9150_RA_ZG_OFFS_TC = 0x02; //[7] PWR_MODE, [6:1] ZG_OFFS_TC, [0] OTP_BNK_VLD static final int MPU9150_RA_X_FINE_GAIN = 0x03; //[7:0] X_FINE_GAIN static final int MPU9150_RA_Y_FINE_GAIN = 0x04; //[7:0] Y_FINE_GAIN static final int MPU9150_RA_Z_FINE_GAIN = 0x05; //[7:0] Z_FINE_GAIN static final int MPU9150_RA_XA_OFFS_H = 0x06; //[15:0] XA_OFFS static final int MPU9150_RA_XA_OFFS_L_TC = 0x07; static final int MPU9150_RA_YA_OFFS_H = 0x08; //[15:0] YA_OFFS static final int MPU9150_RA_YA_OFFS_L_TC = 0x09; static final int MPU9150_RA_ZA_OFFS_H = 0x0A; //[15:0] ZA_OFFS static final int MPU9150_RA_ZA_OFFS_L_TC = 0x0B; static final int MPU9150_RA_XG_OFFS_USRH = 0x13; //[15:0] XG_OFFS_USR static final int MPU9150_RA_XG_OFFS_USRL = 0x14; static final int MPU9150_RA_YG_OFFS_USRH = 0x15; //[15:0] YG_OFFS_USR static final int MPU9150_RA_YG_OFFS_USRL = 0x16; static final int MPU9150_RA_ZG_OFFS_USRH = 0x17; //[15:0] ZG_OFFS_USR static final int MPU9150_RA_ZG_OFFS_USRL = 0x18; static final int MPU9150_TC_PWR_MODE_BIT = 7; static final int MPU9150_TC_OFFSET_BIT = 6; static final int MPU9150_TC_OFFSET_LENGTH = 6; static final int MPU9150_TC_OTP_BNK_VLD_BIT = 0; static final int MPU9150_VDDIO_LEVEL_VLOGIC = 0; static final int MPU9150_VDDIO_LEVEL_VDD = 1; static final int MPU9150_CFG_EXT_SYNC_SET_BIT = 5; static final int MPU9150_CFG_EXT_SYNC_SET_LENGTH = 3; static final int MPU9150_CFG_DLPF_CFG_BIT = 2; static final int MPU9150_CFG_DLPF_CFG_LENGTH = 3; static final int MPU9150_EXT_SYNC_DISABLED = 0x0; static final int MPU9150_EXT_SYNC_TEMP_OUT_L = 0x1; static final int MPU9150_EXT_SYNC_GYRO_XOUT_L = 0x2; static final int MPU9150_EXT_SYNC_GYRO_YOUT_L = 0x3; static final int MPU9150_EXT_SYNC_GYRO_ZOUT_L = 0x4; static final int MPU9150_EXT_SYNC_ACCEL_XOUT_L = 0x5; static final int MPU9150_EXT_SYNC_ACCEL_YOUT_L = 0x6; static final int MPU9150_EXT_SYNC_ACCEL_ZOUT_L = 0x7; static final int MPU9150_DLPF_BW_256 = 0x00; static final int MPU9150_DLPF_BW_188 = 0x01; static final int MPU9150_DLPF_BW_98 = 0x02; static final int MPU9150_DLPF_BW_42 = 0x03; static final int MPU9150_DLPF_BW_20 = 0x04; static final int MPU9150_DLPF_BW_10 = 0x05; static final int MPU9150_DLPF_BW_5 = 0x06; static final int MPU9150_GCONFIG_FS_SEL_BIT = 4; static final int MPU9150_GCONFIG_FS_SEL_LENGTH = 2; static final int MPU9150_GYRO_FS_250 = 0x00; static final int MPU9150_GYRO_FS_500 = 0x01; static final int MPU9150_GYRO_FS_1000 = 0x02; static final int MPU9150_GYRO_FS_2000 = 0x03; static final int MPU9150_ACONFIG_XA_ST_BIT = 7; static final int MPU9150_ACONFIG_YA_ST_BIT = 6; static final int MPU9150_ACONFIG_ZA_ST_BIT = 5; static final int MPU9150_ACONFIG_AFS_SEL_BIT = 4; static final int MPU9150_ACONFIG_AFS_SEL_LENGTH = 2; static final int MPU9150_ACONFIG_ACCEL_HPF_BIT = 2; static final int MPU9150_ACONFIG_ACCEL_HPF_LENGTH = 3; static final int MPU9150_ACCEL_FS_2 = 0x00; static final int MPU9150_ACCEL_FS_4 = 0x01; static final int MPU9150_ACCEL_FS_8 = 0x02; static final int MPU9150_ACCEL_FS_16 = 0x03; static final int MPU9150_DHPF_RESET = 0x00; static final int MPU9150_DHPF_5 = 0x01; static final int MPU9150_DHPF_2P5 = 0x02; static final int MPU9150_DHPF_1P25 = 0x03; static final int MPU9150_DHPF_0P63 = 0x04; static final int MPU9150_DHPF_HOLD = 0x07; static final int MPU9150_TEMP_FIFO_EN_BIT = 7; static final int MPU9150_XG_FIFO_EN_BIT = 6; static final int MPU9150_YG_FIFO_EN_BIT = 5; static final int MPU9150_ZG_FIFO_EN_BIT = 4; static final int MPU9150_ACCEL_FIFO_EN_BIT = 3; static final int MPU9150_SLV2_FIFO_EN_BIT = 2; static final int MPU9150_SLV1_FIFO_EN_BIT = 1; static final int MPU9150_SLV0_FIFO_EN_BIT = 0; static final int MPU9150_MULT_MST_EN_BIT = 7; static final int MPU9150_WAIT_FOR_ES_BIT = 6; static final int MPU9150_SLV_3_FIFO_EN_BIT = 5; static final int MPU9150_I2C_MST_P_NSR_BIT = 4; static final int MPU9150_I2C_MST_CLK_BIT = 3; static final int MPU9150_I2C_MST_CLK_LENGTH = 4; static final int MPU9150_CLOCK_DIV_348 = 0x0; static final int MPU9150_CLOCK_DIV_333 = 0x1; static final int MPU9150_CLOCK_DIV_320 = 0x2; static final int MPU9150_CLOCK_DIV_308 = 0x3; static final int MPU9150_CLOCK_DIV_296 = 0x4; static final int MPU9150_CLOCK_DIV_286 = 0x5; static final int MPU9150_CLOCK_DIV_276 = 0x6; static final int MPU9150_CLOCK_DIV_267 = 0x7; static final int MPU9150_CLOCK_DIV_258 = 0x8; static final int MPU9150_CLOCK_DIV_500 = 0x9; static final int MPU9150_CLOCK_DIV_471 = 0xA; static final int MPU9150_CLOCK_DIV_444 = 0xB; static final int MPU9150_CLOCK_DIV_421 = 0xC; static final int MPU9150_CLOCK_DIV_400 = 0xD; static final int MPU9150_CLOCK_DIV_381 = 0xE; static final int MPU9150_CLOCK_DIV_364 = 0xF; static final int MPU9150_I2C_SLV_RW_BIT = 7; static final int MPU9150_I2C_SLV_ADDR_BIT = 6; static final int MPU9150_I2C_SLV_ADDR_LENGTH = 7; static final int MPU9150_I2C_SLV_EN_BIT = 7; static final int MPU9150_I2C_SLV_BYTE_SW_BIT = 6; static final int MPU9150_I2C_SLV_REG_DIS_BIT = 5; static final int MPU9150_I2C_SLV_GRP_BIT = 4; static final int MPU9150_I2C_SLV_LEN_BIT = 3; static final int MPU9150_I2C_SLV_LEN_LENGTH = 4; static final int MPU9150_I2C_SLV4_RW_BIT = 7; static final int MPU9150_I2C_SLV4_ADDR_BIT = 6; static final int MPU9150_I2C_SLV4_ADDR_LENGTH = 7; static final int MPU9150_I2C_SLV4_EN_BIT = 7; static final int MPU9150_I2C_SLV4_INT_EN_BIT = 6; static final int MPU9150_I2C_SLV4_REG_DIS_BIT = 5; static final int MPU9150_I2C_SLV4_MST_DLY_BIT = 4; static final int MPU9150_I2C_SLV4_MST_DLY_LENGTH = 5; static final int MPU9150_MST_PASS_THROUGH_BIT = 7; static final int MPU9150_MST_I2C_SLV4_DONE_BIT = 6; static final int MPU9150_MST_I2C_LOST_ARB_BIT = 5; static final int MPU9150_MST_I2C_SLV4_NACK_BIT = 4; static final int MPU9150_MST_I2C_SLV3_NACK_BIT = 3; static final int MPU9150_MST_I2C_SLV2_NACK_BIT = 2; static final int MPU9150_MST_I2C_SLV1_NACK_BIT = 1; static final int MPU9150_MST_I2C_SLV0_NACK_BIT = 0; static final int MPU9150_INTCFG_INT_LEVEL_BIT = 7; static final int MPU9150_INTCFG_INT_OPEN_BIT = 6; static final int MPU9150_INTCFG_LATCH_INT_EN_BIT = 5; static final int MPU9150_INTCFG_INT_RD_CLEAR_BIT = 4; static final int MPU9150_INTCFG_FSYNC_INT_LEVEL_BIT = 3; static final int MPU9150_INTCFG_FSYNC_INT_EN_BIT = 2; static final int MPU9150_INTCFG_I2C_BYPASS_EN_BIT = 1; static final int MPU9150_INTCFG_CLKOUT_EN_BIT = 0; static final int MPU9150_INTMODE_ACTIVEHIGH = 0x00; static final int MPU9150_INTMODE_ACTIVELOW = 0x01; static final int MPU9150_INTDRV_PUSHPULL = 0x00; static final int MPU9150_INTDRV_OPENDRAIN = 0x01; static final int MPU9150_INTLATCH_50USPULSE = 0x00; static final int MPU9150_INTLATCH_WAITCLEAR = 0x01; static final int MPU9150_INTCLEAR_STATUSREAD = 0x00; static final int MPU9150_INTCLEAR_ANYREAD = 0x01; static final int MPU9150_INTERRUPT_FF_BIT = 7; static final int MPU9150_INTERRUPT_MOT_BIT = 6; static final int MPU9150_INTERRUPT_ZMOT_BIT = 5; static final int MPU9150_INTERRUPT_FIFO_OFLOW_BIT = 4; static final int MPU9150_INTERRUPT_I2C_MST_INT_BIT = 3; static final int MPU9150_INTERRUPT_PLL_RDY_INT_BIT = 2; static final int MPU9150_INTERRUPT_DMP_INT_BIT = 1; static final int MPU9150_INTERRUPT_DATA_RDY_BIT = 0; // TODO: figure out what these actually do // UMPL source code is not very obvious static final int MPU9150_DMPINT_5_BIT = 5; static final int MPU9150_DMPINT_4_BIT = 4; static final int MPU9150_DMPINT_3_BIT = 3; static final int MPU9150_DMPINT_2_BIT = 2; static final int MPU9150_DMPINT_1_BIT = 1; static final int MPU9150_DMPINT_0_BIT = 0; static final int MPU9150_MOTION_MOT_XNEG_BIT = 7; static final int MPU9150_MOTION_MOT_XPOS_BIT = 6; static final int MPU9150_MOTION_MOT_YNEG_BIT = 5; static final int MPU9150_MOTION_MOT_YPOS_BIT = 4; static final int MPU9150_MOTION_MOT_ZNEG_BIT = 3; static final int MPU9150_MOTION_MOT_ZPOS_BIT = 2; static final int MPU9150_MOTION_MOT_ZRMOT_BIT = 0; static final int MPU9150_DELAYCTRL_DELAY_ES_SHADOW_BIT = 7; static final int MPU9150_DELAYCTRL_I2C_SLV4_DLY_EN_BIT = 4; static final int MPU9150_DELAYCTRL_I2C_SLV3_DLY_EN_BIT = 3; static final int MPU9150_DELAYCTRL_I2C_SLV2_DLY_EN_BIT = 2; static final int MPU9150_DELAYCTRL_I2C_SLV1_DLY_EN_BIT = 1; static final int MPU9150_DELAYCTRL_I2C_SLV0_DLY_EN_BIT = 0; static final int MPU9150_PATHRESET_GYRO_RESET_BIT = 2; static final int MPU9150_PATHRESET_ACCEL_RESET_BIT = 1; static final int MPU9150_PATHRESET_TEMP_RESET_BIT = 0; static final int MPU9150_DETECT_ACCEL_ON_DELAY_BIT = 5; static final int MPU9150_DETECT_ACCEL_ON_DELAY_LENGTH = 2; static final int MPU9150_DETECT_FF_COUNT_BIT = 3; static final int MPU9150_DETECT_FF_COUNT_LENGTH = 2; static final int MPU9150_DETECT_MOT_COUNT_BIT = 1; static final int MPU9150_DETECT_MOT_COUNT_LENGTH = 2; static final int MPU9150_DETECT_DECREMENT_RESET = 0x0; static final int MPU9150_DETECT_DECREMENT_1 = 0x1; static final int MPU9150_DETECT_DECREMENT_2 = 0x2; static final int MPU9150_DETECT_DECREMENT_4 = 0x3; static final int MPU9150_USERCTRL_DMP_EN_BIT = 7; static final int MPU9150_USERCTRL_FIFO_EN_BIT = 6; static final int MPU9150_USERCTRL_I2C_MST_EN_BIT = 5; static final int MPU9150_USERCTRL_I2C_IF_DIS_BIT = 4; static final int MPU9150_USERCTRL_DMP_RESET_BIT = 3; static final int MPU9150_USERCTRL_FIFO_RESET_BIT = 2; static final int MPU9150_USERCTRL_I2C_MST_RESET_BIT = 1; static final int MPU9150_USERCTRL_SIG_COND_RESET_BIT = 0; static final int MPU9150_PWR1_DEVICE_RESET_BIT = 7; static final int MPU9150_PWR1_SLEEP_BIT = 6; static final int MPU9150_PWR1_CYCLE_BIT = 5; static final int MPU9150_PWR1_TEMP_DIS_BIT = 3; static final int MPU9150_PWR1_CLKSEL_BIT = 2; static final int MPU9150_PWR1_CLKSEL_LENGTH = 3; static final int MPU9150_CLOCK_INTERNAL = 0x00; static final int MPU9150_CLOCK_PLL_XGYRO = 0x01; static final int MPU9150_CLOCK_PLL_YGYRO = 0x02; static final int MPU9150_CLOCK_PLL_ZGYRO = 0x03; static final int MPU9150_CLOCK_PLL_EXT32K = 0x04; static final int MPU9150_CLOCK_PLL_EXT19M = 0x05; static final int MPU9150_CLOCK_KEEP_RESET = 0x07; static final int MPU9150_PWR2_LP_WAKE_CTRL_BIT = 7; static final int MPU9150_PWR2_LP_WAKE_CTRL_LENGTH = 2; static final int MPU9150_PWR2_STBY_XA_BIT = 5; static final int MPU9150_PWR2_STBY_YA_BIT = 4; static final int MPU9150_PWR2_STBY_ZA_BIT = 3; static final int MPU9150_PWR2_STBY_XG_BIT = 2; static final int MPU9150_PWR2_STBY_YG_BIT = 1; static final int MPU9150_PWR2_STBY_ZG_BIT = 0; static final int MPU9150_WAKE_FREQ_1P25 = 0x0; static final int MPU9150_WAKE_FREQ_2P5 = 0x1; static final int MPU9150_WAKE_FREQ_5 = 0x2; static final int MPU9150_WAKE_FREQ_10 = 0x3; static final int MPU9150_BANKSEL_PRFTCH_EN_BIT = 6; static final int MPU9150_BANKSEL_CFG_USER_BANK_BIT = 5; static final int MPU9150_BANKSEL_MEM_SEL_BIT = 4; static final int MPU9150_BANKSEL_MEM_SEL_LENGTH = 5; static final int MPU9150_WHO_AM_I_BIT = 6; static final int MPU9150_WHO_AM_I_LENGTH = 6; static final int MPU9150_DMP_MEMORY_BANKS = 8; static final int bank_size = 256; static final int MPU9150_DMP_MEMORY_BANK_SIZE = 256; static final int MPU9150_DMP_MEMORY_CHUNK_SIZE = 16; }
package com.github.johrstrom.workshop.person; /** * A very simple representation of a person. Fields are age, which is a double (mostly just to have that type) * height in centimeters, weight in kilograms and hair color which is a free form string. * * @author jeff ohrstrom * */ public class Person { private double age; private int height; private int weight; private String hairColor; /** * Default constructor sets everything to 0 and hair color to the empty string. */ public Person() { this(0,0,0,""); } public Person(double age, int height, int weight, String hairColor) { this.setAge(age); this.setHeight(height); this.setWeight(weight); this.setHairColor(hairColor); } public String getHairColor() { return hairColor; } public void setHairColor(String hairColor) { this.hairColor = hairColor; } public int getWeight() { return weight; } public void setWeight(int weight) { this.weight = weight; } public int getHeight() { return height; } public void setHeight(int height) { this.height = height; } public double getAge() { return age; } public void setAge(double age) { this.age = age; } /** * A very poorly written function to return this object in json format. * * @return a json representation of this object */ public String toJsonString() { StringBuilder sb = new StringBuilder(); sb.append("{").append("\"age\": ").append(this.getAge()).append(", "); sb.append("\"height\": ").append(this.getHeight()).append(", "); sb.append("\"weight\": ").append(this.getWeight()).append(", "); sb.append("\"haircolor\": \"").append(this.getHairColor()).append("\"").append("}"); return sb.toString(); } /** * Two Person objects are equal iff they have the same age, hair color, * height and weight. * * @param other * @return true iff they're equal as stated above. false otherwise */ public boolean equals(Person other) { return this.getAge() == other.getAge() && this.getHairColor().equals(other.getHairColor()) && this.getHeight() == other.getHeight() && this.getWeight() == other.getWeight(); } }
package amlsim.model.normal; import amlsim.*; import amlsim.model.AbstractTransactionModel; import java.util.List; import java.util.Random; /** * Return money to one of the previous senders */ public class MutualTransactionModel extends AbstractTransactionModel { private Random random; public MutualTransactionModel( AccountGroup accountGroup, Random random ) { this.accountGroup = accountGroup; this.random = random; } public void setParameters(int interval, long start, long end){ super.setParameters(interval, start, end); if(this.startStep < 0){ // decentralize the first transaction step this.startStep = generateStartStep(interval); } } @Override public String getModelName() { return "Mutual"; } @Override public void sendTransactions(long step, Account account) { if((step - this.startStep) % interval != 0)return; Account counterpart = account.getPrevOrig(); if(counterpart == null){ List<Account> origs = account.getOrigList(); if(origs.isEmpty()) { return; }else{ counterpart = origs.get(0); } } TargetedTransactionAmount transactionAmount = new TargetedTransactionAmount(account.getBalance(), random); if(!account.getBeneList().contains(counterpart)) { account.addBeneAcct(counterpart); // Add a new destination } makeTransaction(step, transactionAmount.doubleValue(), account, counterpart); } }
package model.dao.impl; import model.dao.*; import model.dao.connection.ConnectionFactory; import model.dao.connection.impl.ConnectionFactoryImpl; public class DAOFactoryImpl implements DAOFactory { private static DAOFactory instance; private ConnectionFactory connectionFactory; private DAOFactoryImpl() { connectionFactory = ConnectionFactoryImpl.getInstance(); } @Override public AdminDAO getAdminDAO() { return new AdminDAOImpl(connectionFactory); } @Override public DriverDAO getDriverDAO() { return new DriverDAOImpl(connectionFactory); } @Override public BusDAO getBusDAO() { return new BusDAOImpl(connectionFactory); } @Override public RouteDAO getRouteDAO() { return new RouteDAOImpl(connectionFactory); } @Override public UserDAO getUserDAO() { return new UserDAOImpl(connectionFactory); } @Override public ScheduleDAO getScheduleDAO() { return new ScheduleDAOImpl(connectionFactory); } public static DAOFactory getInstance(){ if (instance == null){ synchronized (DAOFactory.class){ instance = new DAOFactoryImpl(); } } return instance; } }
/* * 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 FShareCommon; import java.net.InetAddress; import java.util.ArrayList; /** * * @author Ardhinata Juari <ardhinata.juari@gmail.com> */ public class ServerResponse extends CommunicationObject{ private boolean onServer=false; private ArrayList<InetAddress> listNode=new ArrayList<>(); public ServerResponse(int classEnum) { super(classEnum); } public ServerResponse() { super(5); } public boolean GetOnServer(){ return this.onServer; } public ArrayList<InetAddress> GetListNode(){ return this.listNode; } public void SetOnServer(boolean onServer){ this.onServer=onServer; } public void SetListNode(ArrayList<InetAddress> listNode){ this.listNode=listNode; } }
public abstract class StoreCash { Data d; public abstract void StoreCash(); }
package com.norana.numberplace.sudoku; import java.util.*; public class Sudoku implements Cloneable{ private int[][] numbers; // numbers of sudoku // 0 means blank private boolean[][] fixedNumbers; // boolean matrix that denies change of numbers private int size; // size of one block. So there are // size*size rows and size*size cols /** * Constructor to make initialized sudoku (all numbers are 0) */ public Sudoku(int size){ this.size = size; numbers = new int[size*size][size*size]; fixedNumbers = new boolean[size*size][size*size]; // create sudoku which is yet to be initialized and set them unfixed // (all numbers are zero) for (int i = 0; i < size*size; i++){ for (int j = 0; j < size*size; j++){ numbers[i][j] = 0; } } } /** * Constructor to make sudoku from 2d-array */ public Sudoku(int nums[][], int size){ this.size = size; numbers = new int[size*size][size*size]; fixedNumbers = new boolean[size*size][size*size]; if (nums.length == size*size && nums[0].length == size*size){ for (int i = 0; i < size*size; i++){ for (int j = 0; j < size*size; j++){ numbers[i][j] = nums[i][j]; fixedNumbers[i][j] = true; } } } else{ System.out.println("The size mismatch"); for (int i = 0; i < size*size; i++){ for (int j = 0; j < size*size; j++){ numbers[i][j] = 0; } } } } /** * Constructor to make sudoku from 2 kind of 2d-array */ public Sudoku(int nums[][], boolean fnums[][], int size){ this.size = size; numbers = new int[size*size][size*size]; fixedNumbers = new boolean[size*size][size*size]; if (nums.length == size*size && nums[0].length == size*size){ for (int i = 0; i < size*size; i++){ for (int j = 0; j < size*size; j++){ numbers[i][j] = nums[i][j]; fixedNumbers[i][j] = fnums[i][j]; } } } else{ System.out.println("The size mismatch"); } } @Override public String toString(){ int numDigits = size / 10 + 1; String s = ""; // delimiter between size x size squares String delimiter = ""; // formatted String to add to s String format = "%" + numDigits + "d"; for (int i = 0; i < (numDigits+1)*size*size+2*(size-1); i++){ delimiter += "-"; } for (int i = 0; i < size*size; i++){ if (i != 0 && i % size == 0){ s += delimiter; s += "\n"; } for (int j = 0; j < size*size; j++){ if (j != 0 && j % size == 0){ s += "| "; } s += String.format(format, numbers[i][j]) + " "; } s += "\n"; } return s; } @Override public boolean equals(Object obj){ if (obj instanceof Sudoku){ Sudoku s = (Sudoku)obj; for (int i = 0; i < size*size; i++){ if (!(this.numbers[i].equals(s.numbers[i]))){ return false; } } return true; } return false; } @Override public int hashCode(){ return size; } @Override public Object clone(){ Sudoku copy = new Sudoku(this.size); for (int i = 0; i < size*size; i++){ for (int j = 0; j < size*size; j++){ copy.numbers[i][j] = this.numbers[i][j]; copy.fixedNumbers[i][j] = this.fixedNumbers[i][j]; } } return copy; } /** * returns copy of sudoku * * @return copy of sudoku */ public Sudoku copy(){ return (Sudoku) this.clone(); } /** * returns string of fixedNumbers */ public String fixedNumbersToString(){ int numDigits = size / 10 + 1; StringBuilder builder = new StringBuilder(); // delimiter between size x size squares String delimiter = ""; for (int i = 0; i < (numDigits+1)*size*size+2*(size-1); i++){ delimiter += "-"; } for (int i = 0; i < size*size; i++){ if (i != 0 && i % size == 0){ builder.append(delimiter); builder.append("\n"); } for (int j = 0; j < size*size; j++){ if (j != 0 && j % size == 0){ builder.append("| "); } if (fixedNumbers[i][j]) builder.append("x "); else builder.append("o "); } builder.append("\n"); } return builder.toString(); } /** * returns size of sudoku (for example, if 9x9 sudoku size is 3) * * @return size of sudoku */ public int getSize(){ return size; } /** * returns ith row * * @return int-array of ith row */ public int[] getRow(int i){ return Arrays.copyOf(numbers[i], size*size); } /** * returns ith row as List * * @return Integer-List of ith row */ public List<Integer> getRowAsList(int i){ List<Integer> row = new ArrayList<Integer>(size*size); for (int j = 0; j < size*size; j++){ row.add(numbers[i][j]); } return row; } /** * returns jth column * * @return int-array of jth column */ public int[] getCol(int j){ int[] col = new int[size*size]; for (int i = 0; i < size*size; i++){ col[i] = numbers[i][j]; } return col; } /** * returns jth column as List * * @return Integer-List of jth column */ public List<Integer> getColAsList(int j){ List<Integer> col = new ArrayList<Integer>(size*size); for (int i = 0; i < size*size; i++){ col.add(numbers[i][j]); } return col; } /** * returns int at numbers[i][j] * * @return int at (i,j) of sudoku */ public int getElement(int i, int j){ return numbers[i][j]; } /** * returns int at the cell */ public int getElement(Pair<Integer, Integer> cell){ return numbers[cell.getFirst()][cell.getSecond()]; } /** * sets n at numbers[i][j] regardless of fixedNumbers */ public void setElement(int i, int j, int n){ numbers[i][j] = n; } /** * sets n at the cell regardless of fixedNumbers */ public void setElement(Pair<Integer, Integer> cell, int n){ numbers[cell.getFirst()][cell.getSecond()] = n; } /** * sets n at numbers[i][j] if the cell is not fixed and return whether succeeded */ public boolean setNumber(int i, int j, int n){ if (!fixedNumbers[i][j]) { numbers[i][j] = n; return true; } else return false; } /** * sets n at the cell if the cell is not fixed cell and return whether succeeded */ public boolean setNumber(Pair<Integer, Integer> cell, int n){ return setNumber(cell.getFirst(), cell.getSecond(), n); } /** * returns matrix of numbers in bth block * * @return 2d-array of int in bth block */ public int[][] getBlock(int b){ int[][] block = new int[size][size]; for (int i = 0; i < size; i++){ for (int j = 0; j < size; j++){ block[i][j] = numbers[i+size*(b/size)] [j+size*(b%size)]; } } return block; } /** * returns array of numbers in bth block * * @return 1d-array of int in bth block */ public int[] getBlockAsArray(int b){ int n = 0; int[] block = new int[size*size]; for (int i = size*(b/size); i < size*(b/size+1); i++){ for (int j = size*(b%size); j < size*(b%size+1); j++){ block[n] = numbers[i][j]; n++; } } return block; } /** * returns List of numbers in bth block * * @return List of Integers in bth block */ public List<Integer> getBlockAsList(int b){ List<Integer> block = new ArrayList<Integer>(size*size); for (int i = size*(b/size); i < size*(b/size+1); i++){ for (int j = size*(b%size); j < size*(b%size+1); j++){ block.add(numbers[i][j]); } } return block; } /** * sets matrix of numbers in bth block */ public void setBlock(int b, int block[][]){ for (int i = 0; i < size; i++){ for (int j = 0; j < size; j++){ numbers[i+size*(b/size)][j+size*(b%size)] = block[i][j]; } } } /** * fix the cell (i, j) */ public void fixCell(int i, int j, boolean b){ fixedNumbers[i][j] = b; } /** * fix the cell */ public void fixCell(Pair<Integer, Integer> cell, boolean b){ fixedNumbers[cell.getFirst()][cell.getSecond()] = b; } /** * return if the cell (i, j) is fixed */ public boolean isFixedCell(int i, int j){ return fixedNumbers[i][j]; } /** * return if the cell is fixed */ public boolean isFixedCell(Pair<Integer, Integer> cell){ return fixedNumbers[cell.getFirst()][cell.getSecond()]; } /** * fix cells where some number is already set */ public void fixNumbers(){ for (int i = 0; i < size*size; i++){ for (int j = 0; j < size*size; j++){ if (numbers[i][j] != 0) fixedNumbers[i][j] = true; } } } /** * reset fixedNumbers to allow any change */ public void resetFixedNumbers(){ for (int i = 0; i < size*size; i++) for (int j = 0; j < size*size; j++) fixedNumbers[i][j] = false; } /** * reset sudoku, that is set all unfixed numbers 0 */ public void resetSudoku(){ for (int i = 0; i < size*size; i++){ for (int j = 0; j < size*size; j++){ if (!fixedNumbers[i][j]) numbers[i][j] = 0; } } } /** * checks if the sudoku is already solved * * @return true if the sudoku is already solved */ public boolean isSolved(){ // if any of row, col, and block contains 1,2,...,size*size, // then the sudoku is solved List<Integer> correctArray = new ArrayList<Integer>(size*size); for (int i = 0; i < size*size; i++){ correctArray.add(i+1); } for (int n = 0; n < size*size; n++){ if (!(this.getRowAsList(n).containsAll(correctArray))) return false; if (!(this.getColAsList(n).containsAll(correctArray))) return false; if (!(this.getBlockAsList(n).containsAll(correctArray))) return false; } return true; } }
package com.fpmislata.banco.business.service.impl; import com.fpmislata.banco.business.domain.BancoCentral; import com.fpmislata.banco.business.service.BancoCentralProvider; import com.fpmislata.banco.core.BusinessException; public class BancoCentralProviderImplManual implements BancoCentralProvider { @Override public BancoCentral getBancoCentralAnswer(BancoCentral bancoCentral) throws BusinessException { BancoCentral bancoCentralDevuelto = new BancoCentral(); int codigoEntidadCuentaCorriente = Integer.parseInt(bancoCentral.getCodigoCuentaCorriente().substring(0, 4)); int codigoEntidadBancariaComprobar = Integer.parseInt(bancoCentral.getCodigoEntidadBancaria()); bancoCentralDevuelto.setCodigoCuentaCorriente(bancoCentral.getCodigoCuentaCorriente()); bancoCentralDevuelto.setCodigoEntidadBancaria(bancoCentral.getCodigoEntidadBancaria()); if (codigoEntidadBancariaComprobar >= 0 && codigoEntidadBancariaComprobar <= 999 && bancoCentral.getPin().equalsIgnoreCase("0000")) { System.out.println("grupo 1"); if (codigoEntidadCuentaCorriente >= 0 && codigoEntidadCuentaCorriente <= 999) { bancoCentralDevuelto.setUrl("http://banco-pedrodelbarrio.rhcloud.com/banco_api/api/retirar"); bancoCentralDevuelto.setPin("0000"); } else if (codigoEntidadCuentaCorriente >= 1000 && codigoEntidadCuentaCorriente <= 1999) { bancoCentralDevuelto.setUrl("http://ecobanco-juankza.rhcloud.com/api/retirar"); bancoCentralDevuelto.setPin("1111"); } else if (codigoEntidadCuentaCorriente >= 2000 && codigoEntidadCuentaCorriente <= 2999) { bancoCentralDevuelto.setUrl("http://banco-samuvl.rhcloud.com/banktastic-banco-api/api/retirar"); bancoCentralDevuelto.setPin("2045"); } else { throw new BusinessException("Entidad Bancaria", "Ha introducido una entidad internacional y no trabajamos con ellas."); } } else if (codigoEntidadBancariaComprobar >= 1000 && codigoEntidadBancariaComprobar <= 1999 && bancoCentral.getPin().equalsIgnoreCase("1111")) { System.out.println("grupo 2"); if (codigoEntidadCuentaCorriente >= 0 && codigoEntidadCuentaCorriente <= 999) { bancoCentralDevuelto.setUrl("http://banco-pedrodelbarrio.rhcloud.com/banco_api/api/retirar"); bancoCentralDevuelto.setPin("0000"); } else if (codigoEntidadCuentaCorriente >= 1000 && codigoEntidadCuentaCorriente <= 1999) { bancoCentralDevuelto.setUrl("http://ecobanco-juankza.rhcloud.com/api/retirar"); bancoCentralDevuelto.setPin("1111"); } else if (codigoEntidadCuentaCorriente >= 2000 && codigoEntidadCuentaCorriente <= 2999) { bancoCentralDevuelto.setUrl("http://banco-samuvl.rhcloud.com/banktastic-banco-api/api/retirar"); bancoCentralDevuelto.setPin("2045"); } else { throw new BusinessException("Entidad Bancaria", "Ha introducido una entidad internacional y no trabajamos con ellas."); } } else if (codigoEntidadBancariaComprobar >= 2000 && codigoEntidadBancariaComprobar <= 2999 && bancoCentral.getPin().equalsIgnoreCase("2045")) { System.out.println("grupo 3"); if (codigoEntidadCuentaCorriente >= 0 && codigoEntidadCuentaCorriente <= 999) { bancoCentralDevuelto.setUrl("http://banco-pedrodelbarrio.rhcloud.com/banco_api/api/retirar"); bancoCentralDevuelto.setPin("0000"); } else if (codigoEntidadCuentaCorriente >= 1000 && codigoEntidadCuentaCorriente <= 1999) { bancoCentralDevuelto.setUrl("http://ecobanco-vicentedaw2.rhcloud.com/api/retirar"); bancoCentralDevuelto.setPin("1111"); } else if (codigoEntidadCuentaCorriente >= 2000 && codigoEntidadCuentaCorriente <= 2999) { bancoCentralDevuelto.setUrl("http://banco-samuvl.rhcloud.com/banktastic-banco-api/api/retirar"); bancoCentralDevuelto.setPin("2045"); } else { throw new BusinessException("Entidad Bancaria", "Ha introducido una entidad internacional y no trabajamos con ellas."); } } else { throw new BusinessException("Pin", "El codigo enviado al BancoCentral no coincide con su entidad."); } return bancoCentralDevuelto; } }
package huawei; import java.util.Scanner; /** * @author kangkang lou */ public class Main_38 { static int checkNet(String mask, String ip1, String ip2) { int result; if (checkMask(mask) && check(ip1) && check(ip2)) { int m = ip2num(mask); int a = ip2num(ip1); int b = ip2num(ip2); int r1 = m & a; int r2 = m & b; if (r1 == r2) { result = 0; } else { result = 2; } } else { //输入非法 result = 1; } return result; } static boolean isValid(String num) { try { int n = Integer.parseInt(num); return n >= 0 && n <= 255; } catch (Exception e) { return false; } } static boolean checkMask(String mask) { boolean result = true; String[] arr = mask.split("\\."); for (int i = 0; i < arr.length; i++) { if (!isValid(arr[i])) { result = false; break; } } String str = mask.replaceAll("\\.", ""); if (str.lastIndexOf(".") >= str.indexOf("0")) { result = false; } return result; } static boolean check(String ip) { String[] arr = ip.split("\\."); if (arr.length == 4) { if (isValid(arr[0]) && isValid(arr[1]) && isValid(arr[2]) && isValid(arr[3])) { return true; } else { return false; } } else { return false; } } static int ip2num(String ip) { String[] arr = ip.split("\\."); StringBuilder sb = new StringBuilder(); for (int i = 0; i < arr.length; i++) { sb.append(Integer.toBinaryString(Integer.parseInt(arr[i]))); } return Integer.parseInt(sb.toString(), 2); } public static void main(String[] args) { Scanner in = new Scanner(System.in); while (in.hasNext()) { String mask = in.next(); String ip1 = in.next(); String ip2 = in.next(); System.out.println(checkNet(mask, ip1, ip2)); } } }
package org.acme.resteasy.services; import org.acme.resteasy.Database.dbClass; import org.acme.resteasy.model.Student; import java.util.ArrayList; import java.util.Calendar; import java.util.List; import java.util.Map; public class StudentService { private Map<Long, Student> students = dbClass.getStudents(); public StudentService(){ students.put(1L, new Student(1,"hassan",2006,"CS")); students.put(2L, new Student(2,"AHMED",2002,"BUS")); students.put(3L, new Student(3,"Amr",2003,"CS")); students.put(4L, new Student(4,"Youmna",2005,"ENG")); students.put(5L, new Student(5,"Hatem",2001,"MCM")); } public List<Student> getAllStudents(){ return new ArrayList<Student>(students.values()); } public List<Student> getAllStudentByYear(int year){ List<Student> studByYear = new ArrayList<>(); Calendar cal = Calendar.getInstance(); for(Student s : students.values()){ //cal.setTime(s.get(reated())); if (cal.get(Calendar.YEAR) == year){ studByYear.add(s); } } return studByYear; } public List<Student> getAllStudentsPagination(int start, int size){ ArrayList<Student> list = new ArrayList<Student>(students.values()); if (start + size == list.size()) return new ArrayList<Student>(); return list.subList(start,start+size); } public Student getStudent(long id){ return students.get(id); } public Student newStudent(Student student){ student.setId(students.size() + 1); students.put(student.getId(), student); return student; } public Student updateStudent(Student student){ if (student.getId() <= 0){ return null; } students.put(student.getId(),student); return student; } public Student deleteStudent(long id){ return students.remove(id); } }
package com.leysoft.app.entity; import java.io.Serializable; import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; import javax.validation.constraints.NotEmpty; @Entity @Table(name = "libros") public class Libro implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @NotEmpty @Column private String titulo; @Temporal(value = TemporalType.DATE) @Column private Date fechaPublicacion; @ManyToOne @JoinColumn(name = "id_autor") private Autor autor; public Libro() {} public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getTitulo() { return titulo; } public void setTitulo(String titulo) { this.titulo = titulo; } public Date getFechaPublicacion() { return fechaPublicacion; } public void setFechaPublicacion(Date fechaPublicacion) { this.fechaPublicacion = fechaPublicacion; } public Autor getAutor() { return autor; } public void setAutor(Autor autor) { this.autor = autor; } }
package 컬렉션; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; public class Adddd { public static void main(String[] args) { HashSet a = new HashSet(); a.add("디자이너"); a.add("디자이너"); a.add("프로그래머"); a.add("DB관리자"); a.add("디자이너"); a.add("디자이너"); System.out.println(a); LinkedList queue = new LinkedList(); queue.add("상한우유"); queue.add("싱싱우유"); queue.remove(); System.out.println(queue); HashMap c = new HashMap(); c.put("1번은", " 엄마"); c.put("2번은", " 아빠"); c.put("3번은", " 친구"); c.put("4번은", " 동생"); System.out.println(c.get("2번은")); LinkedList b = new LinkedList(); b.add("국어"); b.add("수학"); b.add("영어"); b.add("컴퓨터"); b.remove(); System.out.println("1날" + b); b.remove(); System.out.println("2날" + b); b.remove(); System.out.println("3날" + b); } }
package org.sagebionetworks.object.snapshot.worker.utils; import static org.junit.Assert.assertEquals; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import java.io.IOException; import java.util.Arrays; import java.util.Date; import org.junit.Before; import org.junit.Test; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; import org.sagebionetworks.asynchronous.workers.sqs.MessageUtils; import org.sagebionetworks.audit.dao.ObjectRecordDAO; import org.sagebionetworks.audit.utils.ObjectRecordBuilderUtils; import org.sagebionetworks.common.util.progress.ProgressCallback; import org.sagebionetworks.repo.manager.UserManager; import org.sagebionetworks.repo.manager.entity.EntityAuthorizationManager; import org.sagebionetworks.repo.manager.trash.EntityInTrashCanException; import org.sagebionetworks.repo.model.AccessRequirementDAO; import org.sagebionetworks.repo.model.AccessRequirementStats; import org.sagebionetworks.repo.model.AuthorizationConstants.BOOTSTRAP_PRINCIPAL; import org.sagebionetworks.repo.model.EntityType; import org.sagebionetworks.repo.model.Node; import org.sagebionetworks.repo.model.NodeDAO; import org.sagebionetworks.repo.model.ObjectType; import org.sagebionetworks.repo.model.RestrictableObjectType; import org.sagebionetworks.repo.model.UserInfo; import org.sagebionetworks.repo.model.audit.DeletedNode; import org.sagebionetworks.repo.model.audit.NodeRecord; import org.sagebionetworks.repo.model.audit.ObjectRecord; import org.sagebionetworks.repo.model.auth.UserEntityPermissions; import org.sagebionetworks.repo.model.jdo.KeyFactory; import org.sagebionetworks.repo.model.message.ChangeMessage; import org.sagebionetworks.repo.model.message.ChangeType; import org.springframework.test.util.ReflectionTestUtils; import com.amazonaws.services.sqs.model.Message; public class NodeObjectRecordWriterTest { @Mock private NodeDAO mockNodeDAO; @Mock private UserManager mockUserManager; @Mock private AccessRequirementDAO mockAccessRequirementDao; @Mock private EntityAuthorizationManager mockEntityAuthorizationManager; @Mock private UserEntityPermissions mockPermissions; @Mock private UserInfo mockUserInfo; @Mock private ObjectRecordDAO mockObjectRecordDao; @Mock private ProgressCallback mockCallback; private NodeObjectRecordWriter writer; private NodeRecord node; private AccessRequirementStats stats; private boolean canPublicRead; @Before public void setup() { MockitoAnnotations.initMocks(this); writer = new NodeObjectRecordWriter(); ReflectionTestUtils.setField(writer, "nodeDAO", mockNodeDAO); ReflectionTestUtils.setField(writer, "userManager", mockUserManager); ReflectionTestUtils.setField(writer, "accessRequirementDao", mockAccessRequirementDao); ReflectionTestUtils.setField(writer, "entityAuthorizationManager", mockEntityAuthorizationManager); ReflectionTestUtils.setField(writer, "objectRecordDAO", mockObjectRecordDao); node = new NodeRecord(); node.setId("123"); when(mockNodeDAO.getNode("123")).thenReturn(node); when(mockUserManager.getUserInfo(BOOTSTRAP_PRINCIPAL.THE_ADMIN_USER.getPrincipalId())) .thenReturn(mockUserInfo); when(mockEntityAuthorizationManager.getUserPermissionsForEntity(mockUserInfo, node.getId())) .thenReturn(mockPermissions); when(mockNodeDAO.getEntityPathIds(node.getId())).thenReturn(Arrays.asList(KeyFactory.stringToKey(node.getId()))); stats = new AccessRequirementStats(); stats.setHasACT(true); stats.setHasToU(false); when(mockAccessRequirementDao.getAccessRequirementStats(Arrays.asList(KeyFactory.stringToKey(node.getId())), RestrictableObjectType.ENTITY)) .thenReturn(stats); canPublicRead = true; when(mockPermissions.getCanPublicRead()).thenReturn(canPublicRead); } @Test public void deleteChangeMessage() throws IOException { Long timestamp = System.currentTimeMillis(); String nodeId = "123"; Message message = MessageUtils.buildMessage(ChangeType.DELETE, nodeId, ObjectType.ENTITY, "etag", timestamp); ChangeMessage changeMessage = MessageUtils.extractMessageBody(message); writer.buildAndWriteRecords(mockCallback, Arrays.asList(changeMessage)); DeletedNode deletedNode = new DeletedNode(); deletedNode.setId(nodeId); ObjectRecord expected = ObjectRecordBuilderUtils.buildObjectRecord(deletedNode, timestamp);; Mockito.verify(mockObjectRecordDao).saveBatch(Mockito.eq(Arrays.asList(expected)), Mockito.eq(expected.getJsonClassName())); } @Test (expected=IllegalArgumentException.class) public void invalidObjectType() throws IOException { Message message = MessageUtils.buildMessage(ChangeType.CREATE, "123", ObjectType.TABLE, "etag", System.currentTimeMillis()); ChangeMessage changeMessage = MessageUtils.extractMessageBody(message); writer.buildAndWriteRecords(mockCallback, Arrays.asList(changeMessage)); } @Test public void publicRestrictedAndControlledTest() throws IOException { Long timestamp = System.currentTimeMillis(); Message message = MessageUtils.buildMessage(ChangeType.UPDATE, "123", ObjectType.ENTITY, "etag", timestamp); ChangeMessage changeMessage = MessageUtils.extractMessageBody(message); node.setIsPublic(canPublicRead); node.setIsControlled(stats.getHasACT()); node.setIsRestricted(stats.getHasToU()); ObjectRecord expected = ObjectRecordBuilderUtils.buildObjectRecord(node, timestamp); writer.buildAndWriteRecords(mockCallback, Arrays.asList(changeMessage)); verify(mockNodeDAO).getNode(eq("123")); verify(mockObjectRecordDao).saveBatch(eq(Arrays.asList(expected)), eq(expected.getJsonClassName())); } @Test public void buildNodeRecordTest() { Node node = new Node(); node.setId("id"); node.setParentId("parentId"); node.setNodeType(EntityType.file); node.setCreatedOn(new Date(0)); node.setCreatedByPrincipalId(1L); node.setModifiedOn(new Date()); node.setModifiedByPrincipalId(2L); node.setVersionNumber(3L); node.setFileHandleId("fileHandleId"); node.setName("name"); NodeRecord record = NodeObjectRecordWriter.buildNodeRecord(node,"benefactorId", "projectId"); assertEquals(node.getId(), record.getId()); assertEquals("benefactorId", record.getBenefactorId()); assertEquals("projectId", record.getProjectId()); assertEquals(node.getParentId(), record.getParentId()); assertEquals(node.getNodeType(), record.getNodeType()); assertEquals(node.getCreatedOn(), record.getCreatedOn()); assertEquals(node.getCreatedByPrincipalId(), record.getCreatedByPrincipalId()); assertEquals(node.getModifiedOn(), record.getModifiedOn()); assertEquals(node.getModifiedByPrincipalId(), record.getModifiedByPrincipalId()); assertEquals(node.getVersionNumber(), record.getVersionNumber()); assertEquals(node.getFileHandleId(), record.getFileHandleId()); assertEquals(node.getName(), record.getName()); } @Test public void testNodeInTrashCan() throws IOException { EntityInTrashCanException exception = new EntityInTrashCanException(""); when(mockPermissions.getCanPublicRead()).thenThrow(exception); Long timestamp = System.currentTimeMillis(); String nodeId = "123"; Message message = MessageUtils.buildMessage(ChangeType.UPDATE, nodeId, ObjectType.ENTITY, "etag", timestamp); ChangeMessage changeMessage = MessageUtils.extractMessageBody(message); writer.buildAndWriteRecords(mockCallback, Arrays.asList(changeMessage)); DeletedNode deletedNode = new DeletedNode(); deletedNode.setId(nodeId); ObjectRecord expected = ObjectRecordBuilderUtils.buildObjectRecord(deletedNode, timestamp);; verify(mockObjectRecordDao).saveBatch(eq(Arrays.asList(expected)), eq(expected.getJsonClassName())); } }
package convalida.validators; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.when; /** * @author WellingtonCosta on 25/04/18. */ public class CpfValidatorTest extends BaseTest { // Cpf generated on https://www.4devs.com.br/gerador_de_cpf @Test public void required_emtpyValue() { CpfValidator validator = new CpfValidator( mockEditText, errorMessage, true, true ); when(mockEditText.getText().toString()).thenReturn(""); assertEquals(validator.validate(), false); } @Test public void required_invalidCpf() { CpfValidator validator = new CpfValidator( mockEditText, errorMessage, true, true ); when(mockEditText.getText().toString()).thenReturn("11122233300"); assertEquals(validator.validate(), false); } @Test public void required_validCpf() { CpfValidator validator = new CpfValidator( mockEditText, errorMessage, true, true ); when(mockEditText.getText().toString()).thenReturn("32454401037"); assertEquals(validator.validate(), true); } @Test public void nonRequired_emtpyValue() { CpfValidator validator = new CpfValidator( mockEditText, errorMessage, true, false ); when(mockEditText.getText().toString()).thenReturn(""); assertEquals(validator.validate(), true); } @Test public void nonRequired_invalidCpf() { CpfValidator validator = new CpfValidator( mockEditText, errorMessage, true, false ); when(mockEditText.getText().toString()).thenReturn("11122233300"); assertEquals(validator.validate(), false); } @Test public void nonRequired_invalidCpfWithChars() { CpfValidator validator = new CpfValidator( mockEditText, errorMessage, true, false ); when(mockEditText.getText().toString()).thenReturn("111abc33300"); assertEquals(validator.validate(), false); } @Test public void nonRequired_invalidCpfDigits() { CpfValidator validator = new CpfValidator( mockEditText, errorMessage, true, false ); when(mockEditText.getText().toString()).thenReturn("32454401017"); assertEquals(validator.validate(), false); } @Test public void nonRequired_validCpf() { CpfValidator validator = new CpfValidator( mockEditText, errorMessage, true, false ); when(mockEditText.getText().toString()).thenReturn("32454401037"); assertEquals(validator.validate(), true); } @Test public void nonRequired_cpfWithInvalidSize() { CpfValidator validator = new CpfValidator( mockEditText, errorMessage, true, false ); when(mockEditText.getText().toString()).thenReturn("123456789"); assertEquals(validator.validate(), false); } @Test public void nonRequired_invalidCpf_BlackList() { CpfValidator validator = new CpfValidator( mockEditText, errorMessage, true, false ); when(mockEditText.getText().toString()).thenReturn("12345678909"); assertEquals(validator.validate(), false); } @Test public void nonRequired_invalidCpf_BlackList_2() { CpfValidator validator = new CpfValidator( mockEditText, errorMessage, true, false ); when(mockEditText.getText().toString()).thenReturn("11111111111"); assertEquals(validator.validate(), false); } }
package com.epam; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.nio.charset.Charset; import java.util.logging.Level; import java.util.logging.Logger; import static java.lang.System.in; /** * Creating String containing content of passed through constructor URL. */ public class CreateContent { //is it a uses-a..?? :P HandleConnection openConn; protected HttpURLConnection connection; private Logger logger = Logger.getLogger("CreateContent.class"); public CreateContent(URL website) { openConn = new HandleConnection(website); connection = openConn.openConnection(); } public String createContent() { StringBuilder sb = new StringBuilder(); if (connection != null) connection.setReadTimeout(60 * 1000); try (InputStreamReader in = new InputStreamReader(connection.getInputStream(), Charset.defaultCharset())) { BufferedReader bufferedReader = new BufferedReader(in); if (bufferedReader != null) { int cp; while ((cp = bufferedReader.read()) != -1) { sb.append((char) cp); } bufferedReader.close(); } } catch (IOException e) { logger.log(Level.WARNING, "cannot create Input Stream"); } return sb.toString(); } }
package com.epam.bar.command.impl; import com.epam.bar.command.*; import com.epam.bar.command.marker.UserCommandMarker; import com.epam.bar.entity.User; import com.epam.bar.exception.ServiceException; import com.epam.bar.service.UserService; import com.epam.bar.util.LocalizationMessage; import com.epam.bar.validator.ChainValidator; import com.epam.bar.validator.impl.NameValidator; import lombok.extern.log4j.Log4j2; import java.util.HashMap; import java.util.Map; import java.util.Optional; /** * Changing the user's{@link User} first and last name * * @author Kirill Karalionak * @version 1.0.0 */ @Log4j2 public class RestEditUserProfileCommand implements Command, UserCommandMarker { private final static String CONFIRMATION_MESSAGE = "serverMessage.editUserSuccess"; private final UserService service; /** * @param service the service */ public RestEditUserProfileCommand(UserService service) { this.service = service; } @Override public CommandResult execute(RequestContext requestContext) { CommandResult commandResult; User user = (User) requestContext.getSessionAttributes().get(RequestParameter.USER); String firstName = requestContext.getRequestParameters().get(RequestParameter.FIRST_NAME); String lastName = requestContext.getRequestParameters().get(RequestParameter.LAST_NAME); ChainValidator validator = new NameValidator(firstName, lastName); Optional<String> serverMessage = validator.validate(); if (serverMessage.isEmpty()) { user.setFirstName(firstName); user.setLastName(lastName); try { serverMessage = service.updateUser(user); if (serverMessage.isEmpty()) { commandResult = new CommandResult(Map.of(RequestAttribute.CONFIRMATION_MESSAGE, LocalizationMessage.localize(requestContext.getLocale(), CONFIRMATION_MESSAGE), RequestAttribute.REDIRECT_COMMAND, CommandType.TO_PROFILE.getCommandName()), new HashMap<>()); } else { commandResult = new CommandResult(Map.of(RequestAttribute.SERVER_MESSAGE, LocalizationMessage.localize(requestContext.getLocale(), serverMessage.get()), RequestAttribute.REDIRECT_COMMAND, CommandType.TO_PROFILE.getCommandName()), new HashMap<>()); } } catch (ServiceException e) { log.error("Edit user failed" + e); commandResult = new CommandResult(Map.of(RequestAttribute.REDIRECT_COMMAND, CommandType.ERROR.getCommandName()), new HashMap<>()); } } else { commandResult = new CommandResult(Map.of(RequestAttribute.SERVER_MESSAGE, LocalizationMessage.localize(requestContext.getLocale(), serverMessage.get()), RequestAttribute.REDIRECT_COMMAND, CommandType.TO_PROFILE.getCommandName()), new HashMap<>()); } return commandResult; } }
package ru.cscenter.practice.recsys.database; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.support.rowset.SqlRowSet; import ru.cscenter.practice.recsys.Language; import java.sql.Types; public class LanguageDao implements IAirBnbObjectDao<Language> { private final JdbcTemplate dbAccess; public LanguageDao(JdbcTemplate template) { dbAccess = template; } public int put(final Language language) { final String query = "insert into language(value) values (?)"; Object[] params = new Object[]{language.getLanguage()}; int[] types = new int[]{Types.VARCHAR}; return dbAccess.update(query, params, types); } public Language get(int id) { final String query = "select value from language where id = ?"; Object[] params = new Object[]{id}; int[] types = new int[]{Types.INTEGER}; SqlRowSet result = dbAccess.queryForRowSet(query, params, types); return result.next() ? Language.getInstance(result.getString("value")) : null; } public int getId(final Language language) { final String query = "select id from language where value = ?"; Object[] params = new Object[]{language.getLanguage()}; int[] types = new int[]{Types.VARCHAR}; SqlRowSet result = dbAccess.queryForRowSet(query, params, types); return result.next() ? result.getInt("id") : -1; } }
package com.wq.newcommunitygovern.mvp.presenter; import android.app.Application; import androidx.recyclerview.widget.LinearLayoutManager; import com.alibaba.android.arouter.launcher.ARouter; import com.blankj.utilcode.util.AppUtils; import com.blankj.utilcode.util.ObjectUtils; import com.chad.library.adapter.base.provider.BaseItemProvider; import com.google.gson.Gson; import com.jess.arms.integration.AppManager; import com.jess.arms.di.scope.FragmentScope; import com.jess.arms.integration.IRepositoryManager; import com.jess.arms.mvp.BasePresenter; import com.jess.arms.http.imageloader.ImageLoader; import me.jessyan.rxerrorhandler.core.RxErrorHandler; import timber.log.Timber; import javax.inject.Inject; import com.jess.arms.utils.ArmsUtils; import com.weique.commonres.adapter.ProviderMultiAdapter; import com.weique.commonres.adapter.provider.ProviderFactory; import com.weique.commonres.adapter.provider.ProviderStore; import com.weique.commonres.base.commonbean.BaseBinderAdapterBean; import com.weique.commonres.base.commonbean.CommonCollectBean; import com.weique.commonres.base.commonbean.DynamicFormEnum; import com.weique.commonres.base.commonbean.RecordsBean; import com.weique.commonres.constans.Constants; import com.weique.commonres.core.RouterHub; import com.weique.commonres.dialog.LookPicDialog; import com.weique.commonres.utils.globalutils.UserInfoUtils; import com.weique.commonservice.zongzhi.bean.UserInfoBean; import com.wq.newcommunitygovern.R; import com.wq.newcommunitygovern.mvp.contract.MyContract; import com.wq.newcommunitygovern.mvp.model.entity.InspectionRecordBean; import com.wq.newcommunitygovern.mvp.ui.binds.InspectionItemBinder; import java.util.ArrayList; import java.util.List; import static com.weique.commonres.base.commonbean.DynamicFormEnum.Behavior.LIST; import static com.wq.newcommunitygovern.mvp.model.api.MainInterfaceService.EDIT_EMPLOYEE; /** * ================================================ * Description: * <p> * Created by MVPArmsTemplate on 11/19/2020 15:28 * <a href="mailto:jess.yan.effort@gmail.com">Contact me</a> * <a href="https://github.com/JessYanCoding">Follow me</a> * <a href="https://github.com/JessYanCoding/MVPArms">Star me</a> * <a href="https://github.com/JessYanCoding/MVPArms/wiki">See me</a> * <a href="https://github.com/JessYanCoding/MVPArmsTemplate">模版请保持更新</a> * ================================================ * * @author Administrator */ @FragmentScope public class MyPresenter extends BasePresenter<MyContract.Model, MyContract.View> { @Inject RxErrorHandler mErrorHandler; @Inject Application mApplication; @Inject ImageLoader mImageLoader; @Inject AppManager mAppManager; @Inject IRepositoryManager mRepositoryManager; @Inject Gson gson; private LookPicDialog lookPicDialog = null; private ProviderMultiAdapter adapter; private CommonCollectBean commonCollectBean; @Inject MyPresenter(MyContract.Model model, MyContract.View rootView) { super(model, rootView); } @Override public void onDestroy() { super.onDestroy(); this.mErrorHandler = null; this.mAppManager = null; this.mImageLoader = null; this.mApplication = null; this.gson = null; this.adapter = null; this.lookPicDialog = null; this.commonCollectBean = null; } /** * 初始化adapter */ public void initAdapter() { adapter = new ProviderMultiAdapter(mImageLoader, gson); ArmsUtils.configRecyclerView(mRootView.getRecyclerView(), new LinearLayoutManager(mRootView.getContext())); mRootView.getRecyclerView().setClipToPadding(false); mRootView.getRecyclerView().setAdapter(adapter); adapter.addChildClickViewIds(R.id.mShadowLayout, R.id.name, R.id.tv_info, R.id.ll_info, R.id.headShadowLayout); adapter.setOnItemChildClickListener((adapter, view, position) -> { try { RecordsBean recordsBean = (RecordsBean) adapter.getData().get(position); switch (recordsBean.getType()) { case "list": commonCollectBean = new CommonCollectBean(); commonCollectBean.setTitle(recordsBean.getCategory()); commonCollectBean.setPath(recordsBean.getChangeType()); commonCollectBean.setType(LIST); List<BaseBinderAdapterBean> list = new ArrayList<>(); list.add(new BaseBinderAdapterBean(InspectionRecordBean.class, new InspectionItemBinder(), null)); commonCollectBean.setBindBeanList(list); commonCollectBean.setClassName(InspectionRecordBean.class); ARouter.getInstance().build(RouterHub.DYNAMIC_COMMON_REFRESH_ACTIVITY) .withParcelable(Constants.COMMON_COLLECTION, commonCollectBean). navigation(); break; case "personal_info": UserInfoBean userInfoBean = UserInfoUtils.getInstance().getUserInfo(); Timber.e(view.getId() + ""); if (view.getId() == R.id.headShadowLayout) { if (ObjectUtils.isNotEmpty(userInfoBean.getHeadUrl())) { if (ObjectUtils.isEmpty(lookPicDialog)) { lookPicDialog = new LookPicDialog(mRootView.getContext()); } lookPicDialog.setListData(userInfoBean.getHeadUrl()); if (!lookPicDialog.isShowing()) { lookPicDialog.showPopupWindow(); } } else { /* 跳转 个人信息 * */ } } else { /* 跳转 个人信息 * */ commonCollectBean = new CommonCollectBean(); commonCollectBean.setTitle("我的信息"); List<RecordsBean> recordSettinglist = new ArrayList<>(); recordSettinglist.add(new RecordsBean(DynamicFormEnum.ItemFlagEnum.NULL_VIEW, "", "", "", "{\"height\":30,\"visibleView\":true}", "")); RecordsBean recordsBean1 = new RecordsBean(DynamicFormEnum.ItemFlagEnum.SETTING_ITEM_CLICK_TEXT, "头像", "HeadUrl", "", "{\"topMargin\":30,\"visibleView\":true}", "HeadUrl"); recordsBean1.setChangeType(EDIT_EMPLOYEE); recordSettinglist.add(recordsBean1); recordsBean1 = new RecordsBean(DynamicFormEnum.ItemFlagEnum.EDIT_ITEM, "姓名", "Name", "请填写姓名", "{\"visibleView\":true}", "popup_edit"); recordsBean1.setChangeType(EDIT_EMPLOYEE); recordSettinglist.add(recordsBean1); recordsBean1 = new RecordsBean(DynamicFormEnum.ItemFlagEnum.SETTING_ITEM_CLICK_TEXT, "性别", "Gender", "请选择性别", "{\"visibleView\":true}", "popup_select"); recordsBean1.setChangeType(EDIT_EMPLOYEE); recordsBean1.setCategory("EnumGender"); recordSettinglist.add(recordsBean1); recordsBean1 = new RecordsBean(DynamicFormEnum.ItemFlagEnum.SETTING_ITEM_CLICK_TEXT, "出生日期", "BirthDate", "请选择出生日期", "{\"visibleView\":true}", "popup_time"); recordsBean1.setChangeType(EDIT_EMPLOYEE); recordSettinglist.add(recordsBean1); recordsBean1 = new RecordsBean(DynamicFormEnum.ItemFlagEnum.EDIT_ITEM, "电话", "Tel", "请填写手机号", "{\"visibleView\":true,\"inputType\":\"phone\"}", "popup_edit"); recordsBean1.setChangeType(EDIT_EMPLOYEE); recordSettinglist.add(recordsBean1); recordsBean1 = new RecordsBean(DynamicFormEnum.ItemFlagEnum.EDIT_ITEM, "身份证号码", "SID", "请填写身份证号码", "{\"visibleView\":false,\"inputType\":\"id_number\"}", "popup_edit"); recordsBean1.setChangeType(EDIT_EMPLOYEE); recordsBean1.setEdit(true); recordSettinglist.add(recordsBean1); recordSettinglist.add(new RecordsBean(DynamicFormEnum.ItemFlagEnum.NULL_VIEW, "", "", "", "{\"height\":30,\"visibleView\":true}", "")); recordsBean1 = new RecordsBean(DynamicFormEnum.ItemFlagEnum.EDIT_ITEM, "部门", "DepartName", "", "{\"visibleView\":true,\"inputType\":\"id_number\"}", "popup_edit"); recordsBean1.setEdit(false); recordSettinglist.add(recordsBean1); recordsBean1 = new RecordsBean(DynamicFormEnum.ItemFlagEnum.EDIT_ITEM, "党组织", "PartyDepartmentName", "", "{\"visibleView\":true,\"inputType\":\"id_number\"}", "popup_edit"); recordsBean1.setEdit(false); recordSettinglist.add(recordsBean1); recordsBean1 = new RecordsBean(DynamicFormEnum.ItemFlagEnum.EDIT_ITEM, "区域", "DepartmentName", "", "{\"visibleView\":false,\"inputType\":\"id_number\"}", "popup_edit"); recordsBean1.setEdit(false); recordSettinglist.add(recordsBean1); try { Timber.e(gson.toJson(commonCollectBean)); } catch (Exception e) { e.printStackTrace(); } commonCollectBean.setList(recordSettinglist); commonCollectBean.setPath("APP/Login/getUserInfo"); ARouter.getInstance().build(RouterHub.APP_COMMON_ACTIVITY) .withParcelable(Constants.COMMON_COLLECTION, commonCollectBean). navigation(); } break; case "video": commonCollectBean = new CommonCollectBean(); commonCollectBean.setTitle("视频会商"); List<RecordsBean> recordlist = new ArrayList<>(); recordlist.add(new RecordsBean(DynamicFormEnum.ItemFlagEnum.PERSONAL_INFORMATION, "", "", "", "{\"height\":30}", "personal_info")); recordlist.add(new RecordsBean(DynamicFormEnum.ItemFlagEnum.NULL_VIEW, "", "", "", "{\"height\":30,\"visibleView\":true}", "")); recordlist.add(new RecordsBean(DynamicFormEnum.ItemFlagEnum.SETTING_ITEM_CLICK, "打卡签到", "", "", "{\"img\":\"public_my_icon_sign_in\",\"visibleView\":true}", "")); recordlist.add(new RecordsBean(DynamicFormEnum.ItemFlagEnum.SETTING_ITEM_CLICK, "视频会商", "", "", "{\"background\":\"\",\"img\":\"public_video_consult\",\"visibleView\":false}", "")); recordlist.add(new RecordsBean(DynamicFormEnum.ItemFlagEnum.NULL_VIEW, "", "", "", "{\"height\":30}", "")); recordlist.add(new RecordsBean(DynamicFormEnum.ItemFlagEnum.SETTING_ITEM_CLICK, "设置", "", "", "{\"background\":\"\",\"img\":\"public_my_icon_settings\",\"visibleView\":false}", "jump")); commonCollectBean.setList(recordlist); ARouter.getInstance().build(RouterHub.APP_COMMON_ACTIVITY) .withParcelable(Constants.COMMON_COLLECTION, commonCollectBean). navigation(); break; case "jump": commonCollectBean = new CommonCollectBean(); commonCollectBean.setTitle("设置"); List<RecordsBean> recordSettinglist = new ArrayList<>(); recordSettinglist.add(new RecordsBean(DynamicFormEnum.ItemFlagEnum.SETTING_ITEM_CLICK_TEXT, "版本信息(二维码)", "", AppUtils.getAppVersionName(), "{\"img\":\"public_qrcode\",\"visibleView\":true}", "qr_code")); recordSettinglist.add(new RecordsBean(DynamicFormEnum.ItemFlagEnum.SETTING_ITEM_CLICK_TEXT, "版本更新", "", "检测", "{\"visibleView\":true}", "")); RecordsBean recordsBean1 = new RecordsBean(DynamicFormEnum.ItemFlagEnum.SETTING_ITEM_CLICK_TEXT, "修改密码", "", "", "{\"visibleView\":false}", "jump"); recordsBean1.setChangeType("changePassword"); recordSettinglist.add(recordsBean1); recordSettinglist.add(new RecordsBean(DynamicFormEnum.ItemFlagEnum.NULL_VIEW, "", "", "", "{\"height\":30}", "")); recordSettinglist.add(new RecordsBean(DynamicFormEnum.ItemFlagEnum.TEXT_VIEW_ONE, "安全退出", "", "", "{\"background\":\"\",\"img\":\"public_my_icon_settings\",\"visibleView\":false}", "logout")); commonCollectBean.setList(recordSettinglist); ARouter.getInstance().build(RouterHub.APP_COMMON_ACTIVITY) .withParcelable(Constants.COMMON_COLLECTION, commonCollectBean). navigation(); default: break; } } catch (Exception e) { e.printStackTrace(); } }); } /** * 根据不同布局 生成列表 */ public void setInterfaceData(CommonCollectBean commonCollectBean) { try { List<RecordsBean> recordsBeans = commonCollectBean.getList(); List<BaseItemProvider> itemProviderList = new ArrayList<>(); //供应者商店 ProviderStore providerStore = new ProviderStore(new ProviderFactory()); for (RecordsBean bean : recordsBeans) { itemProviderList.add(providerStore.shipment(bean.getParamtype(), bean.getStyle())); } adapter.addItemProvider(itemProviderList); adapter.setNewInstance(recordsBeans); } catch (Exception e) { e.printStackTrace(); } } // /** // * 获取分类 // */ // public void getElementType() { // Map map = new HashMap(2); // map.put("TypeName", "金矿"); // NetworkUtils.commonGetNetworkData(mRepositoryManager.obtainRetrofitService(MainInterfaceService.class) // .getElementTypeForRecordBean(SignUtil.addParamSign(map)), mErrorHandler, // mRootView, t -> { // Timber.e(t.toString()); // },false); // // } }
package com.mes.old.meta; // Generated 2017-5-22 1:25:24 by Hibernate Tools 5.2.1.Final import java.math.BigDecimal; import java.sql.Clob; import java.util.HashSet; import java.util.Set; /** * Jbpm4Deployment generated by hbm2java */ public class Jbpm4Deployment implements java.io.Serializable { private BigDecimal dbid; private Clob name; private BigDecimal timestamp; private String state; private Set jbpm4Deployprops = new HashSet(0); private Set jbpm4Lobs = new HashSet(0); public Jbpm4Deployment() { } public Jbpm4Deployment(BigDecimal dbid) { this.dbid = dbid; } public Jbpm4Deployment(BigDecimal dbid, Clob name, BigDecimal timestamp, String state, Set jbpm4Deployprops, Set jbpm4Lobs) { this.dbid = dbid; this.name = name; this.timestamp = timestamp; this.state = state; this.jbpm4Deployprops = jbpm4Deployprops; this.jbpm4Lobs = jbpm4Lobs; } public BigDecimal getDbid() { return this.dbid; } public void setDbid(BigDecimal dbid) { this.dbid = dbid; } public Clob getName() { return this.name; } public void setName(Clob name) { this.name = name; } public BigDecimal getTimestamp() { return this.timestamp; } public void setTimestamp(BigDecimal timestamp) { this.timestamp = timestamp; } public String getState() { return this.state; } public void setState(String state) { this.state = state; } public Set getJbpm4Deployprops() { return this.jbpm4Deployprops; } public void setJbpm4Deployprops(Set jbpm4Deployprops) { this.jbpm4Deployprops = jbpm4Deployprops; } public Set getJbpm4Lobs() { return this.jbpm4Lobs; } public void setJbpm4Lobs(Set jbpm4Lobs) { this.jbpm4Lobs = jbpm4Lobs; } }
package com.example.alejandro.proyectoganadorxd; import android.content.Intent; import android.os.Bundle; import com.google.android.material.floatingactionbutton.FloatingActionButton; import com.google.android.material.snackbar.Snackbar; import android.view.View; import androidx.core.view.GravityCompat; import androidx.appcompat.app.ActionBarDrawerToggle; import android.view.MenuItem; import com.google.android.material.navigation.NavigationView; import androidx.drawerlayout.widget.DrawerLayout; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.Toolbar; import android.view.Menu; import android.widget.ImageButton; public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener { ImageButton imageButton; ImageButton buttondos; ImageButton buttontres; ImageButton buttoncuatro; ImageButton buttoncinco; ImageButton buttonseis; ImageButton buttonsiete; ImageButton buttonocho; ImageButton buttonnueve; ImageButton buttondiez; ImageButton buttononce; ImageButton buttondoce; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); imageButton = findViewById(R.id.button2); imageButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent a = new Intent(MainActivity.this, ApartadoUno.class); startActivity(a); } }); buttondos = findViewById(R.id.button4); buttondos.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent a = new Intent(MainActivity.this,Activity_Buscador.class); startActivity(a); } }); buttontres = findViewById(R.id.button6); buttontres.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent a = new Intent(MainActivity.this,ApartadoTres.class); startActivity(a); } }); buttoncuatro = findViewById(R.id.button8); buttoncuatro.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent a = new Intent(MainActivity.this,ApartadoCuatro.class); startActivity(a); } }); buttoncinco = findViewById(R.id.button10); buttoncinco.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent a = new Intent(MainActivity.this,ApartadoCinco.class); startActivity(a); } }); buttonseis = findViewById(R.id.button12); buttonseis.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent a = new Intent(MainActivity.this,ApartadoSeis.class); startActivity(a); } }); buttonsiete = findViewById(R.id.button14); buttonsiete.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent a = new Intent(MainActivity.this,ApartadoSiete.class); startActivity(a); } }); buttonocho = findViewById(R.id.button16); buttonocho.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent a = new Intent(MainActivity.this,ApartadoOcho.class); startActivity(a); } }); buttonnueve = findViewById(R.id.button18); buttonnueve.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent a = new Intent(MainActivity.this,ApartadoNueve.class); startActivity(a); } }); buttondiez = findViewById(R.id.button20); buttondiez.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent a = new Intent(MainActivity.this,ApartadoDiez.class); startActivity(a); } }); buttononce = findViewById(R.id.button22); buttononce.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent a = new Intent(MainActivity.this,ApartadoOnce.class); startActivity(a); } }); buttondoce = findViewById(R.id.button24); buttondoce.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent a = new Intent(MainActivity.this,ApartadoDoce.class); startActivity(a); } }); /* ImageButton imagenuno = (ImageButton) findViewById(R.id.button2); Picasso.with(this) .load("https://i.ytimg.com/vi/sO7U78pUr34/maxresdefault.jpg") .error(R.mipmap.ic_launcher) .fit() .into(imagenuno); ImageButton imagendos = (ImageButton) findViewById(R.id.button4); Picasso.with(this) .load("https://www.mexicodesconocido.com.mx/wp-content/uploads/2019/06/Mayas.jpg") .error(R.mipmap.ic_launcher) .fit() .into(imagendos); ImageButton imagentres = (ImageButton) findViewById(R.id.button6); Picasso.with(this) .load("https://expertvagabond.com/wp-content/uploads/chichen-itza-ruins-blog-1.jpg") .error(R.mipmap.ic_launcher) .fit() .into(imagentres); ImageButton imagencuatro = (ImageButton) findViewById(R.id.button8); Picasso.with(this) .load("https://cdn.pixabay.com/photo/2018/04/26/17/59/chichen-itza-3352580_1280.jpg") .error(R.mipmap.ic_launcher) .fit() .into(imagencuatro); ImageButton imagencinco = (ImageButton) findViewById(R.id.button10); Picasso.with(this) .load("https://i2.wp.com/historiasdelahistoria.com/wordpress-2.3.1-ES-0.1-FULL/wp-content/uploads/2019/06/Chichen-Itza.jpg?resize=801%2C451&ssl=1") .error(R.mipmap.ic_launcher) .fit() .into(imagencinco); */ Toolbar toolbar = findViewById(R.id.toolbar); setSupportActionBar(toolbar); FloatingActionButton fab = findViewById(R.id.fab); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Snackbar.make(view, "Bienvenido al mejor proyecto", Snackbar.LENGTH_LONG) .setAction("Action", null).show(); } }); DrawerLayout drawer = findViewById(R.id.drawer_layout); NavigationView navigationView = findViewById(R.id.nav_view); ActionBarDrawerToggle toggle = new ActionBarDrawerToggle( this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close); drawer.addDrawerListener(toggle); toggle.syncState(); navigationView.setNavigationItemSelectedListener(this); } @Override public void onBackPressed() { DrawerLayout drawer = findViewById(R.id.drawer_layout); if (drawer.isDrawerOpen(GravityCompat.START)) { drawer.closeDrawer(GravityCompat.START); } else { super.onBackPressed(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } @SuppressWarnings("StatementWithEmptyBody") @Override public boolean onNavigationItemSelected(MenuItem item) { // Handle navigation view item clicks here. int id = item.getItemId(); if (id == R.id.nav_home) { // Handle the camera action } else if (id == R.id.nav_gallery) { } else if (id == R.id.nav_slideshow) { } else if (id == R.id.nav_tools) { } else if (id == R.id.nav_share) { } else if (id == R.id.nav_send) { } DrawerLayout drawer = findViewById(R.id.drawer_layout); drawer.closeDrawer(GravityCompat.START); return true; } }
package si.exec; import si.modelo.Carro.Carro; public class Principal { public static void main(String[] args) { Carro meuCarro = new Carro(); meuCarro.darPartida(); meuCarro.buzinar(); meuCarro.acelerar(); meuCarro.acelerar(); System.out.println(meuCarro.velocidade); meuCarro.frear(); System.out.println(meuCarro.velocidade); Carro outrocarro = new Carro(); for (int i = 0; i<100; i++) { outrocarro.acelerar (); } meuCarro.acelerar(); System.out.println("velocidade do meu carro " +meuCarro.velocidade); System.out.println("velocidade do outro carro " +outrocarro.velocidade); Carro c1 = new Carro(); System.out.println("ano "+c1.ano+ " cor "+c1.cor+ " velocidade " +c1.velocidade); } }
package botenanna.game; import botenanna.math.Vector3; import rlbot.flat.BoostPadState; public class BoostPad { public static final int PAD_RADIUS = 165; public static final int COUNT_BIG_PADS = 6; public static final int COUNT_SMALL_PADS = 28; public static final int COUNT_TOTAL_PADS = COUNT_BIG_PADS + COUNT_SMALL_PADS; public static final int AMOUNT_SMALL = 12; public static final int AMOUNT_BIG = 100; public static final int RESPAWN_TIME_BIG = 10; public static final int RESPAWN_TIME_SMALL = 3; private Vector3 position; private double respawnTimeLeft; private boolean isBigBoostPad; public BoostPad(BoostPad from) { position = from.getPosition(); setRespawnTimeLeft(respawnTimeLeft); isBigBoostPad = from.isBigBoostPad; } public BoostPad(rlbot.flat.BoostPad boostPad, BoostPadState state) { position = Vector3.convert(boostPad.location()).withZ(0); setRespawnTimeLeft(state.timer()); // TODO BoostPadState timer does not respawn timer isBigBoostPad = boostPad.isFullBoost(); } public BoostPad(Vector3 position, boolean isBig) { this.position = position; respawnTimeLeft = 0; isBigBoostPad = isBig; } @Override public String toString() { return "BoostPad(x: " + position.x + ", y: " + position.y + ". t: " + respawnTimeLeft + ", big: " + isBigBoostPad + ")"; } public Vector3 getPosition() { return position; } public Boolean isActive() { return respawnTimeLeft <= 0; } public double getRespawnTimeLeft() { return respawnTimeLeft; } public void setRespawnTimeLeft(double respawnTimeLeft) { this.respawnTimeLeft = Math.max(0, respawnTimeLeft); } /** @return whether the BoostPad is active after the reduction. */ public boolean reduceRespawnTimeLeft(double amount) { setRespawnTimeLeft(respawnTimeLeft - amount); return isActive(); } public void refreshRespawnTimer() { respawnTimeLeft = isBigBoostPad ? RESPAWN_TIME_BIG : RESPAWN_TIME_SMALL; } public void setActive() { respawnTimeLeft = 0; } public int getBoostAmount() { return isBigBoostPad ? AMOUNT_BIG : AMOUNT_SMALL; } }
package com.ebupt.portal.shiro.entity; import lombok.Getter; import lombok.Setter; import javax.persistence.*; import java.io.Serializable; @Entity @Table(name = "eb_role_menu") @Setter @Getter public class RoleMenuEntity implements Serializable { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id; @Column(columnDefinition = "varchar(50) comment '角色ID'") private String roleId; @Column(columnDefinition = "varchar(50) comment '菜单ID'") private String menuId; }
/* * 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 eu.stoehler.botapi.data; import eu.stoehler.botapi.data.Command; import java.util.ArrayDeque; import java.util.Deque; /** * * @author joern */ public final class Transaction implements Command{ private final Deque<Command> commands = new ArrayDeque<>(); private final Deque<Command> executed = new ArrayDeque<>(); private Command current = null; private boolean done = false; public Transaction() { } public synchronized Transaction enqueueAndExecute(Command cmd) throws Exception{ enqueue(cmd); execute(); return this; } public synchronized Transaction enqueueAndExecuteOrUndo(Command cmd) throws Exception { enqueue(cmd); executeOrUndo(); return this; } public synchronized Transaction executeOrUndo() throws Exception { try{ execute(); } catch (Exception ex) { undoPartially(ex); throw ex; } return this; } public synchronized Transaction enqueue(Command cmd) { assertNotDone(); commands.add(cmd); return this; } @Override public synchronized void execute() throws Exception{ assertNotDone(); while(!commands.isEmpty()) { current = commands.removeFirst(); try { current.execute(); executed.addLast(current); current = null; } catch (Exception ex) { throw ex; } } } @Override public void undoPartially(Exception ex) { // undo in reverse order if (current != null) { current.undoPartially(ex); current = null; } while(!executed.isEmpty()) { Command last = executed.removeLast(); last.undo(); } done = true; } @Override public synchronized void undo() { while(!executed.isEmpty()) { Command last = executed.removeLast(); last.undo(); } done = true; } private synchronized void assertNotDone() { if(done){ throw new RuntimeException("Transaction was already completed."); } } }
package com.ahmetkizilay.yatlib4j.lists; import com.ahmetkizilay.yatlib4j.oauthhelper.OAuthHolder; public class GetListStatuses { private static final String BASE_URL = "https://api.twitter.com/1.1/lists/statuses.json"; private static final String HTTP_METHOD = "GET"; public static GetListStatuses.Response sendRequest(GetListStatuses.Parameters params, OAuthHolder oauthHolder) { throw new UnsupportedOperationException(); } public static class Response { } public static class Parameters { } }
package com.mygdx.game.com.mygdx.game.cave; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.Input; import com.badlogic.gdx.Screen; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.OrthographicCamera; import com.badlogic.gdx.graphics.g2d.BitmapFont; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.graphics.glutils.ShapeRenderer; import com.badlogic.gdx.math.RandomXS128; import com.mygdx.game.TestGame; import com.mygdx.game.TestScreen; import javax.security.auth.callback.TextInputCallback; import java.util.ArrayList; import java.util.List; /** * Created by on 04.08.14. */ public class MapDebugScreen implements Screen { private final TestGame game; OrthographicCamera camera; ShapeRenderer renderer; TestMap map; RandomXS128 rand ; List<Miner> miners; Phase1Remover phase1remover; int minerCount = 0; int generationPhase = 99; private Phase2Remover phase2remover; public MapDebugScreen(final TestGame game){ this.game = game; this.camera = new OrthographicCamera(); camera.setToOrtho(false, 500, 500); renderer = new ShapeRenderer(); map = new TestMap(500,500,0); miners = new ArrayList<Miner>(); miners.add(new Miner(250, 250, map)); GetSeedInput listener = new GetSeedInput(); Gdx.input.getTextInput(listener, "Enter seed for map generation", "0"); //rand = new RandomXS128(1234, 9999); } private class GetSeedInput implements Input.TextInputListener { @Override public void input(String text) { rand = new RandomXS128(Integer.parseInt(text),42); generationPhase = 0; } @Override public void canceled() { rand = new RandomXS128(42,42); generationPhase = 0; } } @Override public void render(float delta) { Gdx.gl.glClearColor(0.8f,0.8f,1,1); Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT); camera.update(); renderer.setProjectionMatrix(camera.combined); map.render(renderer); switch(generationPhase){ case 0: for(int i = 0; i < 1000; i++){ runMiners(); } break; case 1: for(int i = 0; i < 1000; i++){ if(runRemover1()){ break; } } break; case 2: phase2remover.render(renderer); for(int i = 0; i < 5000; i++){ if(runRemover2()){ break; } } break; case 3: if(Gdx.input.isKeyPressed(Input.Keys.SPACE)){ startGame(); } game.batch.begin(); game.font.draw(game.batch,"Press space", 100, 100); game.batch.end(); break; } } private boolean runRemover1() { if(phase1remover.step()) { System.out.println("PHASE 1 OVER"); startPhase2(); return true; } return false; } private boolean runRemover2() { if(phase2remover.step()){ System.out.println("PHASE 2 OVER"); generationPhase = 3; return true; } return false; } private void startGame() { game.setScreen(new TestScreen(game, map)); } private void runMiners(){ ArrayList<Miner> toAdd = new ArrayList<Miner>(); ArrayList<Miner> toRemove = new ArrayList<Miner>(); for(Miner miner : miners){ boolean success = miner.dig(rand); if(success){ int next = rand.nextInt(100); if(next > 92){ toAdd.add(miner.spawnNew(rand.nextInt(4))); } } else { if(miners.size() - toRemove.size() > 1){ toRemove.add(miner); minerCount++; } else { if(minerCount > 400){ toRemove.add(miner); startPhase2(); } else { miner.goToRandom(rand); } } } } miners.addAll(toAdd); miners.removeAll(toRemove); } private void startPhase1() { generationPhase = 1; phase1remover = new Phase1Remover(map); } private void startPhase2() { generationPhase = 2; phase2remover = new Phase2Remover(map); } @Override public void resize(int width, int height) { } @Override public void show() { } @Override public void hide() { } @Override public void pause() { } @Override public void resume() { } @Override public void dispose() { } }
package techquizapp.pojo; public class StudentScore { private String language; private double perc; public String getLanguage() { return language; } public void setLanguage(String language) { this.language = language; } public double getPerc() { return perc; } public void setPerc(double perc) { this.perc = perc; } }
package com.manuanand.clouddrive; import java.util.Date; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; @Entity // This tells Hibernate to make a table out of this class public class File { @Id @GeneratedValue(strategy=GenerationType.AUTO) private Integer id; private Integer userId; private String title; private String description; private String path; private String remotePath; private String contents; private String md5Sum; private Date uploadDate; private Integer version; private Boolean isDeleted; public Integer getId() { return id; } public void setId(Integer 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 String getPath() { return path; } public void setPath(String path) { this.path = path; } public String getContents() { return contents; } public void setContents(String contents) { this.contents = contents; } public String getMd5Sum() { return md5Sum; } public void setMd5Sum(String md5Sum) { this.md5Sum = md5Sum; } public Date getUploadDate() { return uploadDate; } public void setUploadDate(Date uploadDate) { this.uploadDate = uploadDate; } public Integer getVersion() { return version; } public void setVersion(Integer version) { this.version = version; } public Boolean getIsDeleted() { return isDeleted; } public void setIsDeleted(Boolean isDeleted) { this.isDeleted = isDeleted; } public String getRemotePath() { return remotePath; } public void setRemotePath(String remotePath) { this.remotePath = remotePath; } public Integer getUserId() { return userId; } public void setUserId(Integer userId) { this.userId = userId; } }
package kata.wallet; import kata.wallet.model.Stock; import lombok.Getter; import lombok.Setter; import java.math.BigDecimal; import java.math.RoundingMode; import java.util.List; @Getter @Setter public class Wallet { private final List<Stock> portfolio; public Wallet(List<Stock> portfolio) { this.portfolio = portfolio; } public BigDecimal value(BigDecimal currencyRate) { BigDecimal portfolioValue = BigDecimal.valueOf(0); for (Stock stock : portfolio) { Integer quantity = stock.getQuantity(); BigDecimal value = stock.getType().getValue(); BigDecimal totalValues = value.multiply(BigDecimal.valueOf(quantity)); portfolioValue = portfolioValue.add(totalValues); } return portfolioValue.multiply(currencyRate).setScale(2, RoundingMode.CEILING); } }
package java00; import java.util.Scanner; public class java0090 { public static void main(String[] args) { // TODO Auto-generated method stub Scanner scn = new Scanner(System.in); int n = 0; int m = 0; System.out.println("Input n and m:"); n = scn.nextInt(); m = scn.nextInt(); System.out.println("Average:" + myrand(n, m)); } public static float myrand(float v1, float v2) { float average = 0; float result = 0; int data[] = new int[(int) v1]; for (int i = 0; i <= (int) v1 - 1; i++) { int val = (int) (Math.random() * v2); data[i] = val; } for (int j = 0; j <= v1 - 1; j++) { result = data[j] + result; } average = result / v1; return average; } }
package its.TextAnalysisGUI; import javax.swing.JPanel; import javax.swing.JLabel; import javax.swing.JTextField; import java.awt.GridLayout; import java.awt.Color; public class TextAnalysisPanel extends JPanel{ private JLabel lastTextLabel ; private JLabel numberOfEsLabel ; private JLabel numberOfTextLabel ; private JTextField inputField ; private TextAnalysisModel analysisModel ; private JLabel totalNumberOfEs ; private JLabel totalNumberOfTexts ; public TextAnalysisPanel () { // Подключаем модель анализа текста analysisModel = new TextAnalysisModel (); // Задаем цвет фона панели и количество // строк и столбцов, растояние между ними this.setBackground(Color.yellow) ; this.setLayout(new GridLayout (5, 2, 10, 10) ) ; // Задаем метки JLabel questionLabel = new JLabel ("Enter text: ") ; JLabel replyLabel = new JLabel ("Current text: ") ; JLabel numberTextLabel = new JLabel ("No. of Es in current text: ") ; JLabel totalEsLabel = new JLabel ("Total No. of Es : ") ; JLabel totalNumberText = new JLabel ("Total No. Text : ") ; lastTextLabel = new JLabel (""); numberOfEsLabel = new JLabel ("--"); inputField = new JTextField (""); totalNumberOfEs = new JLabel (""); totalNumberOfTexts = new JLabel (""); // Задаем параметры меток непрозрачность, цвет фона и текста setLabelParams (questionLabel) ; setLabelParams (replyLabel) ; setLabelParams (numberTextLabel) ; setLabelParams (totalEsLabel) ; setLabelParams (totalNumberText) ; // Добавляем метки и текстовое поле в панель this.add (questionLabel) ; this.add (inputField) ; this.add (replyLabel) ; this.add (lastTextLabel) ; this.add (numberTextLabel) ; this.add (numberOfEsLabel) ; this.add (totalEsLabel) ; this.add (totalNumberOfEs) ; this.add (totalNumberText) ; this.add (totalNumberOfTexts) ; } public void startAnalysisAndDisplayResult() { String text = inputField.getText () ; analysisModel.analyse(text) ; lastTextLabel.setText (analysisModel.getCurrentText()) ; int noOfEs = analysisModel.getCurrentNumbersOfEs() ; numberOfEsLabel.setText(Integer.toString (noOfEs) ) ; inputField.setText ("") ; int totalOfEs = analysisModel.getTotalNumbersOfEs(); totalNumberOfEs.setText(Integer.toString (totalOfEs) ) ; int NumberOfTexts = analysisModel.getTotalNumbersOfTexts(); totalNumberOfTexts.setText(Integer.toString (NumberOfTexts) ) ; } public void resetResult() { analysisModel.resetTextAnalysisModel() ; lastTextLabel.setText ("") ; numberOfEsLabel.setText("") ; inputField.setText ("") ; totalNumberOfEs.setText("") ; totalNumberOfTexts.setText("") ; } public void setLabelParams (JLabel x ) { x.setBackground(Color.black) ; x.setForeground(Color.white) ; x.setOpaque(true) ; } }
package com.workorder.ticket.persistence.dao; import java.util.List; import org.apache.ibatis.annotations.Param; import com.workorder.ticket.controller.vo.common.OpLog; import com.workorder.ticket.persistence.dto.BizLogQueryDto; import com.workorder.ticket.persistence.entity.BizLog; public interface BizLogDao { int deleteByPrimaryKey(Long id); int insert(BizLog record); int insertSelective(BizLog record); BizLog selectByPrimaryKey(Long id); List<BizLog> getList(@Param("bizId") Long bizId, @Param("bizType") Integer bizType); int updateByPrimaryKeySelective(BizLog record); int updateByPrimaryKey(BizLog record); List<OpLog> getOpLogList(BizLogQueryDto queryDto); }
package logic; public enum EnumWrongInputUserProfile { USER_NAME, EMAIL, AGE, GENDER }
package com.psl.flashnotes.bean; import java.util.Date; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.OneToOne; import org.hibernate.annotations.Type; @Entity public class Answer { @Id @GeneratedValue private int answerId; @Type(type="text") private String answerContent; private int likes; private Date dateCreated; private Date lastUpdated; @ManyToOne @JoinColumn(name = "queryId") private Queries query; @OneToOne @JoinColumn(name = "userId") private User user; public Answer() { } public Answer(int answerId, String answerContent, int likes, Queries query, User user) { super(); this.answerId = answerId; this.answerContent = answerContent; this.likes = likes; this.query = query; this.user = user; } public int getAnswerId() { return answerId; } public void setAnswerId(int answerId) { this.answerId = answerId; } public String getAnswerContent() { return answerContent; } public void setAnswerContent(String answerContent) { this.answerContent = answerContent; } public int getLikes() { return likes; } public void setLikes(int likes) { this.likes = likes; } public Date getDateCreated() { return dateCreated; } public void setDateCreated(Date date) { this.dateCreated = date; } public Date getLastUpdated() { return lastUpdated; } public void setLastUpdated() { this.lastUpdated = new Date(); } public Queries getQuery() { return query; } public void setQuery(Queries query) { this.query = query; } public User getUser() { return user; } public void setUser(User user) { this.user = user; } public void setLastUpdated(Date lastUpdated) { this.lastUpdated = lastUpdated; } @Override public String toString() { return "Answer [answerId=" + answerId + ", answerContent=" + answerContent + ", likes=" + likes + "]"; } }
package com.stem.entity; public class WxNewsItem { private Integer id; private String title; private String thumbMediaId; //0不显示 1显示 private Integer showCoverPic; private String digest; private String url; private String contentSourceUrl; private String content; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getThumbMediaId() { return thumbMediaId; } public void setThumbMediaId(String thumbMediaId) { this.thumbMediaId = thumbMediaId; } public Integer getShowCoverPic() { return showCoverPic; } public void setShowCoverPic(Integer showCoverPic) { this.showCoverPic = showCoverPic; } public String getDigest() { return digest; } public void setDigest(String digest) { this.digest = digest; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getContentSourceUrl() { return contentSourceUrl; } public void setContentSourceUrl(String contentSourceUrl) { this.contentSourceUrl = contentSourceUrl; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } }
package com.rockwellcollins.atc.limp.translate.lustre.limp2lustre; import java.io.File; import java.util.ArrayList; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import jkind.lustre.Node; import jkind.lustre.RecordType; import jkind.lustre.Type; import jkind.lustre.TypeDef; import com.rockwellcollins.atc.limp.InputArg; import com.rockwellcollins.atc.limp.LocalArg; import com.rockwellcollins.atc.limp.LocalProcedure; import com.rockwellcollins.atc.limp.OutputArg; import com.rockwellcollins.atc.limp.translate.basicblocks.limp.BasicBlock; import com.rockwellcollins.atc.limp.translate.basicblocks.limp.TranslateBasicBlocks; import com.rockwellcollins.atc.limp.translate.basicblocks.lustre.BasicBlockToDot; import com.rockwellcollins.atc.limp.translate.basicblocks.lustre.LustreBasicBlock; import com.rockwellcollins.atc.limp.translate.basicblocks.lustre.LustreBlocksToNodes; import com.rockwellcollins.atc.limp.translate.basicblocks.lustre.LustrePostcondition; import com.rockwellcollins.atc.limp.translate.basicblocks.lustre.LustrePrecondition; import com.rockwellcollins.atc.limp.translate.basicblocks.lustre.StaticSingleAssignment; import com.rockwellcollins.atc.limp.utils.LimpUtilities; /** * LocalProcedureToLustre * * This class will take a LocalProcedure and * 1. Generate a LimpBasicBlock representation. * 2. Optimize the LimpBasicBlock representation. * 3. Translate the LimpBasicBlock representation to LustreBasicBlocks. * 4. Apply StaticSingleAssignment * 5. Translate each LustreBlock to a Lustre node. * 6. Generate the main node to execute the LustreBasicBlock nodes in the proper order (LocalProcedureToLustre) * */ public class LocalProcedureToLustre { public static Pair<BasicBlock,List<Node>> translateLocalProcedure(LocalProcedure lp, LimpToLustre l2l, File pdfFile, MangleList mangleList) { LocalProcedureToLustre procedureToLustre = new LocalProcedureToLustre(lp,l2l,pdfFile, mangleList); if(!procedureToLustre.state.isEmpty()) { TypeDef stateTypeDef = procedureToLustre.createStateRecordTypeDef(); procedureToLustre.limpToLustre.typedefs.put(stateTypeDef.id, stateTypeDef.type); } if(!procedureToLustre.limpToLustre.globals.isEmpty()) { TypeDef globalTypeDef = procedureToLustre.createGlobalRecordTypeDef(); procedureToLustre.limpToLustre.typedefs.put(globalTypeDef.id, globalTypeDef.type); } procedureToLustre.computeBlocks(lp); procedureToLustre.blockNodes = LustreBlocksToNodes.generateNodes(procedureToLustre); procedureToLustre.mainNode = LocalProcedureToMainNode.crunch(procedureToLustre, mangleList); List<Node> nodes = new ArrayList<>(procedureToLustre.blockNodes); Node main = procedureToLustre.mainNode; nodes.add(main); Pair<BasicBlock,List<Node>> pair = new Pair<BasicBlock,List<Node>>(procedureToLustre.firstLimpBlock,nodes); return pair; } public LocalProcedure main; public LimpToLustre limpToLustre; public Map<String,Type> state = new LinkedHashMap<>(); public List<LustrePrecondition> mainNodePreconditions = new ArrayList<>(); public List<LustrePostcondition> mainNodePostconditions = new ArrayList<>(); public LustreBasicBlock firstBlock; public List<Node> blockNodes = new ArrayList<>(); public Node mainNode; public String stateRecordTypeId; public String globalRecordTypeId; public BasicBlock firstLimpBlock; public MangleList mangleList; private File pdfFile; private LocalProcedureToLustre(LocalProcedure lp, LimpToLustre l2l, File pdfFile, MangleList mangleList) { this.main = lp; this.pdfFile = pdfFile; this.limpToLustre = l2l; this.state = generateStateMap(lp); this.mangleList = mangleList; } public RecordType getStateRecordType() { return (RecordType) limpToLustre.typedefs.get(stateRecordTypeId); } public RecordType getGlobalRecordType() { return (RecordType) limpToLustre.typedefs.get(globalRecordTypeId); } private static Map<String, Type> generateStateMap(LocalProcedure lp) { Map<String, Type> map = new LinkedHashMap<>(); for (InputArg iarg : lp.getInputs().getInputArgs()) { map.put(iarg.getName(), LimpTypeToLustreType.translateType(iarg.getType())); } for (LocalArg larg : LimpUtilities.getLocalsFromVarBlock(lp.getVarBlock())) { map.put(larg.getName(), LimpTypeToLustreType.translateType(larg.getType())); } for (OutputArg oarg : lp.getOutputs().getOutputArgs()) { map.put(oarg.getName(), LimpTypeToLustreType.translateType(oarg.getType())); } return map; } public Set<String> getGlobalIdentifiers() { Set<String> usedIds = new HashSet<>(); usedIds.addAll(limpToLustre.typedefs.keySet()); usedIds.addAll(limpToLustre.functions.keySet()); usedIds.addAll(limpToLustre.procedures.keySet()); return usedIds; } public Set<String> getLocalIdentifiers() { Set<String> usedIds = new HashSet<>(); usedIds.addAll(state.keySet()); usedIds.addAll(limpToLustre.globals.keySet()); return usedIds; } private TypeDef createStateRecordTypeDef() { String suffix = "_state_type"; String name = main.getName() + suffix; Integer current = 0; Set<String> usedIds = getGlobalIdentifiers(); while (usedIds.contains(name)) { name = main.getName() + suffix + current; current++; } RecordType stateRecordType = new RecordType(name, state); TypeDef stateTypeDef = new TypeDef(name, stateRecordType); this.stateRecordTypeId = name; List<String> li = new ArrayList<>(); for (Entry<String, Type> entry : state.entrySet()){ li.add(entry.getKey()); } mangleList.add(new Pair<List<String>,String>(li, name)); return stateTypeDef; } private TypeDef createGlobalRecordTypeDef() { String suffix = "_global_type"; String name = main.getName() + suffix; Integer current = 0; Set<String> usedIds = getGlobalIdentifiers(); while (usedIds.contains(name)) { name = main.getName() + suffix + current; } RecordType globalRecordType = new RecordType(name, limpToLustre.globals); TypeDef globalTypeDef = new TypeDef(name, globalRecordType); this.globalRecordTypeId = name; List<String> li = new ArrayList<>(); for (Entry<String, Type> entry : limpToLustre.globals.entrySet()){ li.add(entry.getKey()); } mangleList.add(new Pair<List<String>, String>(li, name)); return globalTypeDef; } private void computeBlocks(LocalProcedure lp) { BasicBlock first = GenerateCFG.get(lp); firstLimpBlock = first; // translate the Limp basic blocks to Lustre basic blocks this.firstBlock = TranslateBasicBlocks.translate(first,this); printBasicBlocks(this.firstBlock); this.firstBlock = StaticSingleAssignment.transform(this.firstBlock,this); } private void printBasicBlocks(LustreBasicBlock first) { try { BasicBlockToDot.display(first,pdfFile); } catch (Exception e) { System.err.println("Error creating DOT PDF file."); e.printStackTrace(); } } }
package com.tencent.mm.ui.chatting; import com.tencent.mm.R; import com.tencent.mm.sdk.platformtools.x; import com.tencent.mm.ui.chatting.ChattingSendDataToDeviceUI.a.1; class ChattingSendDataToDeviceUI$a$1$1 implements Runnable { final /* synthetic */ 1 tLQ; ChattingSendDataToDeviceUI$a$1$1(1 1) { this.tLQ = 1; } public final void run() { this.tLQ.tLI.tNv.setProgress(0); this.tLQ.tLI.tNv.setVisibility(4); this.tLQ.tLI.tLN.setText(this.tLQ.tLP.tLG.getText(R.l.chatting_send_success)); this.tLQ.tLI.tLN.setTextColor(this.tLQ.tLP.tLG.getResources().getColor(R.e.send_data_sending)); this.tLQ.tLJ.bLZ = "send_data_sucess"; this.tLQ.tLJ.progress = 0; ChattingSendDataToDeviceUI.d(this.tLQ.tLP.tLG).put(this.tLQ.tLJ.deviceID, this.tLQ.tLJ); x.i("MicroMsg.ChattingSendDataToDeviceUI", " deviceId %s SEND_DATA_SUCCESS!", new Object[]{this.tLQ.tLJ.deviceID}); } }
package com.github.emailtohl.integration.core.user.employee; import org.springframework.stereotype.Repository; import com.github.emailtohl.integration.core.user.entities.Employee; import com.github.emailtohl.lib.jpa.AuditedRepository; /** * Employee的历史信息 * @author HeLei */ @Repository class EmployeeAuditImpl extends AuditedRepository<Employee, Long> implements EmployeeAudit { }
/* * SYSTEMi Copyright 2000-2015, MetricStream, Inc. All rights reserved. * @Author: narayana * @Created: 12/12/01 * $Id$ */ package com.util; import static com.util.Check.anyNull; import static com.util.Check.hasContent; import static com.util.Check.noContent; import java.io.PrintWriter; import java.io.StringWriter; import java.util.ArrayList; import java.util.Calendar; import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.Locale; import java.util.Properties; import java.util.Set; import java.util.SimpleTimeZone; import java.util.Stack; import java.util.StringTokenizer; import java.util.TimeZone; /** * set of util methods to manipulate and extend data structure operations */ public class AroundString { public static final String EMPTY_STRING = ""; private static final String DOUBLE_QUOTE_STR = "\""; private static final String TWO_DOUBLE_QUOTE_STR = "\"\""; private static final char DOUBLE_QUOTE_CHAR = '"'; private static final char COMMA_CHAR = ','; public static boolean isWhitespaceInside(String _value) { if (_value == null) { return false; } char[] ca = _value.toCharArray(); int len = ca.length; for (int i = 0; i < len; ++i) { if (Character.isWhitespace(ca[i])) { return true; } } return false; } public static String quoteAndTrimAsNeeded(String _value) { return quoteAndTrimAsNeeded(_value, false); } /* * removes whitespace at beginning and end, and adds quotes if it contains * inner whitespace. */ public static String quoteAndTrimAsNeeded(String _value, boolean _single) { if (_value == null) { return ""; } _value = _value.replaceAll("^\\s+|\\s+$", ""); if (_value.matches(".+\\s.+")) { String q = _single ? "'" : "\""; _value = q + _value + q; } return _value; } /** * Translates string locale presentation in form lang_COUNTRY to Locale * object * * @param String * locale in format lang_COUNTRY, for example en_US if value is * null, or can't be present as Locale, then default returned * @return Locale locale from string * @exception no * exceptions rose */ public static Locale localeFromString(String _locale) { if (isEmptyOrNull(_locale)) { return Locale.getDefault(); } String[] l = _locale.split("_"); switch (l.length) { case 1: return new Locale(l[0], "", ""); case 2: return new Locale(l[0], l[1]); default: return new Locale(l[0], l[1], l[2]); } } /** * builds TimeZone from String presentation * * @param String * present timezone in form of _-speparated values that are used as SimpleTimeZone constructor parameter. The last token be Y or N and controls whether to use daylight saving * @return TimeZone for string or default if null or invalid * @exception no */ public static TimeZone timeZoneFromString(String _tzs) { if (_tzs == null) { return TimeZone.getDefault(); } String[] split = _tzs.split("_"); if (split.length >= 9) { try { int offs = Integer.parseInt(split[0]); String code = split[1]; int startm = Integer.parseInt(split[2]); int startd = Integer.parseInt(split[3]); int startt = Integer.parseInt(split[4]); int endm = Integer.parseInt(split[5]); int endd = Integer.parseInt(split[6]); int endt = Integer.parseInt(split[7]); if ("Y".equals(split[8])) { return new SimpleTimeZone(offs * 60 * 1000, code, startm, startd, -Calendar.SUNDAY, startt, endm, -endd, Calendar.SUNDAY, endt); } else { return new SimpleTimeZone(offs * 60 * 1000, code); } } catch (Exception e) { } } return TimeZone.getDefault(); } /** * Implements String.split method from JDK 1.4 and up, convert string to * string array by separators boundaries. This differs from String.split() * in that the separator is not used as a regular expression, and that * this split supresses empty strings * * @param some * string * @param separators * @return array of string components devided by separators, no actual * separators in result string */ public static String[] split(String _s, String _sep) { if (_s == null) { return null; } StringTokenizer st = new StringTokenizer(_s, _sep); int nt = st.countTokens(); String[] result = new String[nt]; for (int i = 0; i < nt; i++) { result[i] = st.nextToken(); } return result; } /** * Splits the string at the separator, puts each token in a list and returns * a list returns an empty list if any of the input parameters is null * * @param String * delimited string * @param String * separator * @return List list of string components divided by separators */ public static List<String> stringToList(String _s, String _sep) { List<String> list = new ArrayList<>(); if (_s == null || _sep == null) { return list; } StringTokenizer st = new StringTokenizer(_s, _sep); while (st.hasMoreTokens()) { list.add(st.nextToken()); } return list; } /** * Forms a string of all the items in the list separated by the separator * returns an empty string if any of the input parameters is null * * @param List * list of items to be concatenated (list of only strings) * @param String * separator * @return String string of list items separated by the separator */ @Deprecated // use joinToString instead public static <T> String listToString(List<T> _list, String _sep) { return joinToString(_list, null, _sep); } /** * Build a string of all the items in the list separated by the separator. * Each items in the list enclosed by the <code>ecnclose</code> * * @param data * List of input data * @param enclose * Wrapper used to enclose each data in the list * @param separator * Used to separate each data in the list * @return The string of data */ @Deprecated // use joinToString instead public static <T> String listToString(Collection<T> data, String enclose, String separator) { return joinToString(data, enclose, separator); } /** * @param dataList * @return String array from the list */ public static String[] listToStringArray(ArrayList<?> dataList) { String[] values = null; if (dataList != null) { values = new String[dataList.size()]; for (int i = 0; i < dataList.size(); i++) { if (dataList.get(i) != null) { values[i] = dataList.get(i).toString(); } } } return values; } /** * @param dataList * @return double array from the list */ public static double[] listToDoubleArray(List<?> dataList) { double[] values = null; if (dataList != null) { values = new double[dataList.size()]; for (int i = 0; i < dataList.size(); i++) { if (dataList.get(i) != null) { String curValue = dataList.get(i).toString(); if ("HOLE".equals(curValue) || "NoValue".equals(curValue)) { values[i] = 0.0; } else { values[i] = Double.parseDouble(curValue); } } } } return values; } /** * Used for getting int value from property with default. It actually * duplicates standard property method and should be not used. * * @param properties * which have int values * @param property * name to retrieve * @param default int value if absent, or can't be converted to in * @return int value of property _name, or default value if property doesn't * exist or not int */ public static int getIntProperty(Properties _properties, String _name, int _defaultVal) { try { return Integer.parseInt(_properties.getProperty(_name, "" + _defaultVal)); } catch (Exception e) { } return _defaultVal; } /** * replaces all occurence of regExp by repl in in string */ @Deprecated public static String replaceAll(String _inString, String _regExp, String _repl) { return _inString.replaceAll(_regExp, _repl); } /** * This method takes a input string (inStr) and replaces all occurences of a * given substring (_old), within the input string with the given * replacement string (_new). The replaced string is returned. This method * returns the input string as is, if any one of the following conditions is * true: 1) input string is null or empty 2) substring to search for is null * or empty 3) replacement substring is null * * @param String * inStr * @param String * _old * @param String * _new * @return String replaced string */ public static String replaceAllPlain(String _inStr, String _old, String _new) { if (noContent(_inStr) || noContent(_old) || isNull(_new)) { return _inStr; } return _inStr.replace(_old, _new); } /** * A helper method to parse int without raising an exception and using a * default value instead of * * @param String * value to parse * @param int default value * @return int value of parsed string or default value if an exception * happened * @exception none */ @Deprecated public static int parseIntWithDefault(String _sint, int _def) { return Integer.parseInt(_sint, _def); } // TODO: This should better be called limitToLength public static String assureLength(String _s, int _len) { if (_s == null || _len <= 0 || _s.length() < _len) { return _s; } return _s.substring(0, _len); } /** * Replaces all the characters that are not used for filename with * underscore. Characters include /, \, :, *, ?, |, ", <, > */ public static String replaceSpecialCharsInString(String _s) { return replaceSpecialCharsInString(_s, "_"); } /** * Replaces all the characters that are not used for filename with _with. * Characters include /, \, :, *, ?, |, ", <, > */ public static String replaceSpecialCharsInString(String _s, String _with) { char[] spChars = new char[] { '/', '\\', ':', '*', '?', '"', '|', '>', '<' }; return replaceSpecialCharsInString(_s, spChars, _with); } /** * Replaces all the characters that are in spChars with _with. */ public static String replaceSpecialCharsInString(String _s, char[] spChars, String _with) { if (_s == null) { return ""; } char[] ca = _s.toCharArray(); StringBuilder sb = new StringBuilder(); for (int i = 0; i < ca.length; i++) { boolean _found = false; for (int j = 0; j < spChars.length; j++) { if (ca[i] == spChars[j]) { _found = true; break; } } sb.append(_found ? _with : ca[i]); } return sb.toString(); } /** * Checks if the given string is present in the given array of strings * * @param _array * @param _toSearch * @param _ignoreCase * @return boolean true if string is in the array, false otherwise. returns * false if either param is null */ public static boolean contains(String[] _array, String _toSearch, boolean _ignoreCase) { if (anyNull(_array, _toSearch)) { return false; } for (int i = 0; i < _array.length; i++) { if (_ignoreCase) { if (_toSearch.equalsIgnoreCase(_array[i])) { return true; } } else { if (_toSearch.equals(_array[i])) { return true; } } } return false; } /** * Checks if the given string contains any of the strings given in the * string array. Can be used to check if a string contains some special * chars by passing the chars as an array of strings * * @param String * _str string to scan * @param String * [] _array string array * @return boolean true if the string contains any of the strings given in * the array, false otherwise */ public static boolean contains(String _str, String[] _array) { if (anyNull(_str, _array)) { return false; } int len = _array.length; for (int i = 0; i < len; i++) { if (_str.indexOf(_array[i]) != -1) { return true; } } return false; } /** * Checks if the given string contains any of the chars given in the * char array. Can be used to check if a string contains some special * chars by passing the chars as an array of strings * * @param String * _str string to scan * @param String * [] _array char array * @return boolean true if the string contains any of the chars given in * the array, false otherwise */ public static boolean contains(String _str, char[] _array) { if (anyNull(_str, _array)) { return false; } int len = _array.length; for (int i = 0; i < len; i++) { if (_str.indexOf(_array[i]) != -1) { return true; } } return false; } /** * This method takes a Column value as a String (inStr) and strips the * leading & trailing double quote character (") and strips all double quote * chars used for escaping the double quote literal in the column value * (normalization). * * This method returns an empty String if any one of the following * conditions is true: 1) input String is null or empty 2) input String * contains only 2 double quote characters * * @param String * inStr * @return String the normalized column value as String */ private static String normalizeToken(String inStr) { String retVal = (inStr == null) ? "" : inStr.trim(); if (retVal.length() <= 0) { return retVal; } if (retVal.indexOf(DOUBLE_QUOTE_STR) >= 0) { // if the entire token is enclosed in double quote chars then strip // the // first & last double quote chars if (retVal.startsWith(DOUBLE_QUOTE_STR)) { int len = retVal.length(); if (len > 2) { retVal = retVal.substring(1, (len - 1)); // Strip all double quote chars used for escaping the double // quote literal // in the token retVal = replaceAllPlain(retVal, TWO_DOUBLE_QUOTE_STR, DOUBLE_QUOTE_STR); } else { // If a string starts with a double quote and is only 2 // chars long // then it is an empty string retVal = ""; } } } return retVal; } /** * This method takes a record in CSV format as a String (inRec) and parses * the record and returns a List of the column values. All column Values are * returned as Strings. * * This method returns an empty list if any one of the following conditions * is true: 1) input string is null or empty 2) an exception is encountered * while parsing the input record * * @param String * inRec * @return List list of Column values (each element in the list is of type * String) */ public static List<String> parseCsvRecord(String inRec) { return parseRecord(inRec, COMMA_CHAR); } /** * This method takes a record in a predefined character delimited format as * a String (inRec) and parses the record and returns a List of the column * values. All column Values are returned as Strings. * * This method returns an empty list if any one of the following conditions * is true: 1) input string is null or empty 2) an exception is encountered * while parsing the input record * * @param String * inRec * @param char inSeparator * @return List list of Column values (each element in the list is of type * String) */ public static List<String> parseRecord(String inRec, char inSeparator) { List<String> retVal = new ArrayList<>(16); try { inRec = (inRec == null) ? "" : inRec; inRec = (!Character.isWhitespace(inSeparator)) ? inRec.trim() : inRec; if (inRec.length() <= 0) { return retVal; } boolean stackPush = true; int startIndex = 0; int iIndex; Stack<String> stack = new Stack<>(); // to keep track of (") char[] charArray = inRec.toCharArray(); // parse the CSV record for (iIndex = 0; iIndex < charArray.length; iIndex++) { if (charArray[iIndex] == DOUBLE_QUOTE_CHAR) { stackPush = !(stackPush); } else if ((charArray[iIndex] == inSeparator) && (stack.empty())) { // if it is a separator char and the stack is empty then // this indicates the end of a token String token = new String(charArray, startIndex, (iIndex - startIndex)); startIndex = iIndex + 1; // Normalize each column value retVal.add(normalizeToken(token)); } } // Add the last token String token = new String(charArray, startIndex, (iIndex - startIndex)); retVal.add(normalizeToken(token)); } catch (Exception e) { // Probably add a log statement here retVal.clear(); } return retVal; } /** * Trims all the first and last occurances of the specified character * * @param String * Target string for trimming * @param char Character to be trimmed from the target string * @return */ public static String trim(String _str, char _token) { if (noContent(_str)) { return _str; } _str = _str.trim(); while (_str.startsWith(String.valueOf(_token))) { _str = _str.substring(1); } while (_str.endsWith(String.valueOf(_token))) { _str = _str.substring(0, _str.length() - 1); } return _str; } /** * Normalizes back slash character to forward slash Removes special * characters that are not allowed in directory names Removes multiple * forward slash characters * * This method will always retain a trailing forward slash at the end Eg: * /abc*\\\\\\\\\\def?//\\//fgd\\dd\\e/ will become /abc/def/fgd/dd/e/ * * @param _toNormalize * @return */ public static String normalizeDirectoryName(String _toNormalize) { if (_toNormalize == null) { return _toNormalize; } _toNormalize = _toNormalize.replaceAll("[:*?\"|><,;]", ""); _toNormalize = _toNormalize.replaceAll("[/\\\\]+", "/"); _toNormalize = _toNormalize.replace("../", ""); _toNormalize = trim(_toNormalize, '/'); return _toNormalize + "/"; } @Deprecated public static String normalizeBackSlash(String string) { return string; } public static boolean isEmptyOrNull(String value) { return value == null || "".equals(value.trim()); } public static boolean isTrueOrYes(String val) { return "TRUE".equalsIgnoreCase(val) || "YES".equalsIgnoreCase(val); } /** * This function is used to check if a given string is not "null" and not * "blank". * * @param value * String * @return boolean */ public static boolean isNonEmpty(String value) { return value != null && !"".equals(value.trim()); } /** * This function is used to check if given string is not null and is blank. * * @param value * String * @return boolean */ public static boolean isEmpty(String value) { return value != null && "".equals(value.trim()); } /** * Converts the {@link Throwable} object stack into {@link String} form. * * @param _t * @return {@link String} form of {@link Throwable} object stack */ public static String normalizeException(Throwable _t) { StringWriter _writer = new StringWriter(); _t.printStackTrace(new PrintWriter(_writer)); return _writer.toString(); } /** * Retrieves index value from given String array or last index value if * index is out of bounds, -1 if array is null or index is less than 0 * * @param array * - String source array * @param index * - int index number * @return String - value of index in String array */ public static String getArrayIndexValue(String[] array, int index) { if (array == null || index < 0) { return "-1"; } int length = array.length; if (index >= length) { index = length -1; } return array[index]; } public static String[] listToStringArrayWithReplace(List<?> dataList) { String[] values = null; if (dataList != null) { values = new String[dataList.size()]; for (int i = 0; i < dataList.size(); i++) { if (dataList.get(i) != null) { String value = (String) dataList.get(i); value = value.substring(1, value.length() - 1); values[i] = value; } } } return values; } /** * This method replaces with the given regular expressions if string starts * with given _repStr. * * @param _inString * -- String need to be replaced * @param _repStr * -- String used to check if string starts with specified * characters or not. * @param _regExp * -- RegularExpression for replacing String * @return */ public static String replaceStringForFirstOccurance(String _inString, String _repStr, String _regExp) { if (isEmptyOrNull(_regExp)) { _regExp = _repStr; } if (isNonEmpty(_inString) && _inString.startsWith(_repStr)) { return _inString.replaceFirst(_regExp, ""); } return _inString; } /** * @param t * @return */ public static <T> boolean isNull(T t) { return t == null; } /** * @param t * @return */ public static <T> boolean isNotNull(T t) { return t != null; } /** * @param string * @param str * @return */ public static boolean isYes(String string, String str) { if (isNull(string)) { string = str; } if (isNull(string) || string.length() != 1 && string.length() != 3) { return false; } string = string.toUpperCase(); return "Y".equals(string) || "YES".equals(string); } /** * @param string * @return */ public static boolean isYes(String string) { return isYes(string, null); } public static int[] toIntArray(String string, String separator, int defaultInt) { if (isEmptyOrNull(string)) { return new int[0]; } else { String[] strings = string.split(separator); int[] values = new int[strings.length]; for (int i = 0; i < strings.length; i++) { try { values[i] = Integer.parseInt(strings[i]); } catch (NumberFormatException e) { values[i] = defaultInt; } } return values; } } public static int[] toIntArray(String string, String separator) { return toIntArray(string, separator, 0); } public static String getContentDisposition(String fileName) { return "attachment; filename=\"" + fileName + "\""; } public static String getFileExtension(String strFileName) { if (strFileName != null) { final int dot = strFileName.lastIndexOf("."); if (dot != -1) { return strFileName.substring(dot + 1); } } return ""; } /** * Splits the string at the separator, puts each token in a set and returns * a set returns an empty set if any of the input parameters is null * * @param String * delimited string * @param String * separator * @return Set set of string components divided by separator */ public static Set<String> stringToSet(String _s, String _sep) { Set<String> set = new HashSet<String>(); if (_s == null || _sep == null) { return set; } StringTokenizer st = new StringTokenizer(_s, _sep); while (st.hasMoreTokens()) { set.add(st.nextToken()); } return set; } /** * /** * Forms a string of all the items in the set separated by the separator * returns an empty string if any of the input parameters is null * * @param Set * set of items to be concatenated (set of only strings) * @param String * separator * @return String string of list items separated by the separator */ @Deprecated // use joinToString instead public static <T> String setToString(Set<T> data, String separator) { return joinToString(data, "", separator); } public static <T> String joinToString(Collection<T> data, String separator) { return joinToString(data, "", separator); } public static <T> String joinToString(Collection<T> data) { return joinToString(data, "", ","); } /** * /** * Forms a string of all the items in the set separated by the separator. * null values in data are ignored * * @param data * collection of items to be joined * @param enclose * added as prefix and postfix for each item * @param separator * added between enclosed items * @return string of joined items */ public static <T> String joinToString(Collection<T> data, String enclose, String separator) { if (noContent(data)) { return ""; } if (enclose == null) { enclose = ""; } if (separator == null) { separator = ","; } StringBuilder builder = new StringBuilder(); String sep = ""; for (T object : data) { if (object != null) { builder.append(sep).append(enclose).append(object).append(enclose); sep = separator; } } return builder.toString(); } /** * Forms a string of all the items in the set separated by the separator. * null values in data are ignored * * @param separator * added between items. Default is ',' * @param args * items to be joined * @return string of joined items */ public static <T> String joinToString(String separator, String... args) { if (noContent(args)) { return ""; } if (separator == null) { separator = ","; } StringBuilder sb = new StringBuilder(); for (int i = 0; i < args.length; i++) { if (hasContent(args[i])) { if (i > 0) { sb.append(separator); } sb.append(args[i]); } } return sb.toString(); } public static String removeComments(String content){ // String result=content.replaceAll("/\\*([^*]|[\r\n]|(\\*+([^*/]|[\r\n])))*\\*+/",""); String result = content.replaceAll( "//.*|(\"(?:\\\\[^\"]|\\\\\"|.)*?\")|(?s)/\\*.*?\\*/", "$1 " ); return result; } public static void main(String ar[]){ String data = "In java /*Mydata /* is */ dddd" + " comment */ do you know */ */*//**** */*how comments */ written" + " for "; System.out.println(removeComments(data)); } }
package ru.moneydeal.app.checks; import android.content.Context; import android.os.AsyncTask; import android.util.Log; import androidx.annotation.NonNull; import androidx.lifecycle.LiveData; import androidx.lifecycle.MutableLiveData; import java.util.ArrayList; import java.util.List; import ru.moneydeal.app.ApplicationModified; import ru.moneydeal.app.network.ApiRepo; import ru.moneydeal.app.network.BaseResponse; import ru.moneydeal.app.network.CheckApi; import ru.moneydeal.app.network.ErrorResponse; import ru.moneydeal.app.network.ResponseCallback; public class CheckRepo { private final ApiRepo mApiRepo; private GroupChecks mLoadedChecks; public CheckRepo(ApplicationModified context) { mApiRepo = context.getApis(); } @NonNull public static CheckRepo getInstance(Context context) { return ApplicationModified.from(context).getCheckRepo(); } public LiveData<GroupChecks> fetchChecks(String groupId) { MutableLiveData<GroupChecks> liveData = new MutableLiveData<>(); mLoadedChecks = new GroupChecks(); liveData.setValue(mLoadedChecks); processFetchChecks(liveData, groupId); return liveData; } public CheckEntity getLoadedCheck(String checkId) { if (mLoadedChecks == null || mLoadedChecks.entities == null) { return null; } for (CheckEntity checkEntity : mLoadedChecks.entities) { if (checkEntity.id.equals(checkId)) { return checkEntity; } } return null; } public LiveData<Progress> createCheck(BaseCheckEntity check) { MutableLiveData<Progress> liveData = new MutableLiveData<>(); liveData.setValue(Progress.IN_PROGRESS); if (check == null) { liveData.setValue(Progress.FAILED); return liveData; } ArrayList<CheckApi.CheckChunk> chunks = new ArrayList<>(); for (CheckChunkEntity chunk : check.chunks) { chunks.add(new CheckApi.CheckChunk( chunk.userId, chunk.amount )); } AsyncTask.execute(() -> mApiRepo .getCheckApi() .createCheck(new CheckApi.CreateCheckBody( check.name, check.description, check.groupId, chunks )) .enqueue(new CheckCreateResponseCallback(liveData))); return liveData; } private void processFetchChecks(MutableLiveData<GroupChecks> liveData, String groupId) { AsyncTask.execute(() -> mApiRepo .getCheckApi() .fetchChecks(groupId) .enqueue(new ChecksResponseCallback(liveData))); } public enum Progress { IN_PROGRESS, SUCCESS, FAILED } public class GroupChecks { public Progress progress; public List<CheckEntity> entities; public GroupChecks() { this(Progress.IN_PROGRESS, new ArrayList<>()); } public GroupChecks(Progress progress, List<CheckEntity> entities) { this.progress = progress; this.entities = entities; } } public class ChecksResponseCallback extends ResponseCallback<CheckApi.ChecksGetResponse> { private final MutableLiveData<GroupChecks> mLiveData; public ChecksResponseCallback(MutableLiveData<GroupChecks> liveData) { this.mLiveData = liveData; } @Override public void onOk(CheckApi.ChecksGetResponse response) { try { ArrayList<CheckEntity> checkEntities = new ArrayList<>(); List<CheckApi.Check> checks = response.data.checks; for (CheckApi.Check check : checks) { ArrayList<CheckChunkEntity> checkChunkEntities = new ArrayList<>(); Integer amount = 0; for (CheckApi.CheckChunk chunk : check.chunks) { checkChunkEntities.add(new CheckChunkEntity( check._id, chunk.user_id, chunk.amount )); amount += chunk.amount; } CheckEntity checkEntity = new CheckEntity( check._id, check.name, check.description, check.group_id, check.user_id, amount, checkChunkEntities ); checkEntities.add(checkEntity); } Log.d("CheckRepo", "fetch ok with check count" + checks.size()); mLoadedChecks = new GroupChecks(Progress.SUCCESS, checkEntities); } catch (Exception e) { Log.d("CheckRepo", "fetch error " + e.getMessage()); mLoadedChecks = new GroupChecks(Progress.FAILED, new ArrayList<>()); } mLiveData.postValue(mLoadedChecks); } @Override public void onError(ErrorResponse response) { Log.d("CheckRepo", "fetch error " + response.data.message); mLoadedChecks = new GroupChecks(Progress.FAILED, new ArrayList<>()); mLiveData.postValue(mLoadedChecks); } } public class CheckCreateResponseCallback extends ResponseCallback<BaseResponse> { private final MutableLiveData<Progress> mLiveData; CheckCreateResponseCallback(MutableLiveData<Progress> liveData) { mLiveData = liveData; } @Override public void onOk(BaseResponse response) { mLiveData.postValue(Progress.SUCCESS); } @Override public void onError(ErrorResponse response) { mLiveData.postValue(Progress.FAILED); } } }
package com.tencent.mm.e.b; final class e$b implements Runnable { final /* synthetic */ e bEC; e$b(e eVar) { this.bEC = eVar; } /* JADX WARNING: inconsistent code. */ /* Code decompiled incorrectly, please refer to instructions dump. */ public final void run() { /* r11 = this; r2 = -1; r10 = 1; r9 = 2; r3 = 0; r0 = "MicroMsg.RecordModeAsyncRead"; r1 = "RecordThread started. frameSize:%d"; r4 = new java.lang.Object[r10]; r5 = r11.bEC; r5 = r5.bEm; r5 = java.lang.Integer.valueOf(r5); r4[r3] = r5; com.tencent.mm.sdk.platformtools.x.i(r0, r1, r4); r0 = -123456789; // 0xfffffffff8a432eb float:-2.6642794E34 double:NaN; r1 = r11.bEC; r1 = r1.bDQ; if (r0 == r1) goto L_0x0043; L_0x0022: r0 = "MicroMsg.RecordModeAsyncRead"; r1 = new java.lang.StringBuilder; r4 = "set priority to "; r1.<init>(r4); r4 = r11.bEC; r4 = r4.bDQ; r1 = r1.append(r4); r1 = r1.toString(); com.tencent.mm.sdk.platformtools.x.i(r0, r1); r0 = r11.bEC; r0 = r0.bDQ; android.os.Process.setThreadPriority(r0); L_0x0043: r0 = r11.bEC; r1 = r0.bEv; monitor-enter(r1); r0 = r11.bEC; Catch:{ all -> 0x009f } r0 = r0.mStatus; Catch:{ all -> 0x009f } if (r10 == r0) goto L_0x006a; L_0x004e: r0 = "MicroMsg.RecordModeAsyncRead"; r2 = new java.lang.StringBuilder; Catch:{ all -> 0x009f } r3 = "status is not inited, now status: "; r2.<init>(r3); Catch:{ all -> 0x009f } r3 = r11.bEC; Catch:{ all -> 0x009f } r3 = r3.mStatus; Catch:{ all -> 0x009f } r2 = r2.append(r3); Catch:{ all -> 0x009f } r2 = r2.toString(); Catch:{ all -> 0x009f } com.tencent.mm.sdk.platformtools.x.e(r0, r2); Catch:{ all -> 0x009f } monitor-exit(r1); Catch:{ all -> 0x009f } L_0x0069: return; L_0x006a: r0 = r11.bEC; Catch:{ all -> 0x009f } r4 = 2; r0.mStatus = r4; Catch:{ all -> 0x009f } monitor-exit(r1); Catch:{ all -> 0x009f } r0 = r11.bEC; r0 = r0.bEm; r0 = new byte[r0]; L_0x0076: r1 = r11.bEC; r1 = r1.mStatus; if (r9 != r1) goto L_0x0095; L_0x007c: r1 = r11.bEC; r1 = r1.bEu; monitor-enter(r1); r4 = r11.bEC; Catch:{ all -> 0x00c1 } r4 = r4.mIsPause; Catch:{ all -> 0x00c1 } if (r4 == 0) goto L_0x00a2; L_0x0087: r4 = r11.bEC; Catch:{ InterruptedException -> 0x0245 } r4 = r4.bEu; Catch:{ InterruptedException -> 0x0245 } r4.wait(); Catch:{ InterruptedException -> 0x0245 } L_0x008e: r4 = r11.bEC; Catch:{ all -> 0x00c1 } r4 = r4.mStatus; Catch:{ all -> 0x00c1 } if (r9 == r4) goto L_0x00a2; L_0x0094: monitor-exit(r1); Catch:{ all -> 0x00c1 } L_0x0095: r0 = "MicroMsg.RecordModeAsyncRead"; r1 = "RecordThread exited."; com.tencent.mm.sdk.platformtools.x.i(r0, r1); goto L_0x0069; L_0x009f: r0 = move-exception; monitor-exit(r1); Catch:{ all -> 0x009f } throw r0; L_0x00a2: monitor-exit(r1); Catch:{ all -> 0x00c1 } r1 = r11.bEC; r1 = r1.bEa; if (r1 != 0) goto L_0x00c4; L_0x00a9: r0 = "MicroMsg.RecordModeAsyncRead"; r1 = "mAudioRecord is null, so stop record."; com.tencent.mm.sdk.platformtools.x.i(r0, r1); r0 = r11.bEC; r1 = r0.bEv; monitor-enter(r1); r0 = r11.bEC; Catch:{ all -> 0x00be } r2 = 3; r0.mStatus = r2; Catch:{ all -> 0x00be } monitor-exit(r1); Catch:{ all -> 0x00be } goto L_0x0095; L_0x00be: r0 = move-exception; monitor-exit(r1); Catch:{ all -> 0x00be } throw r0; L_0x00c1: r0 = move-exception; monitor-exit(r1); Catch:{ all -> 0x00c1 } throw r0; L_0x00c4: r1 = r11.bEC; r1 = r1.bDM; if (r1 == 0) goto L_0x00d0; L_0x00ca: r0 = r11.bEC; r0 = r0.bEm; r0 = new byte[r0]; L_0x00d0: r1 = r11.bEC; r4 = r11.bEC; r4 = r4.bED; r4 = r4 + 1; r1.bED = r4; r1 = new com.tencent.mm.compatible.util.g$a; r1.<init>(); r1 = r11.bEC; r1 = r1.bEa; r4 = r11.bEC; r4 = r4.bEm; r1 = r1.read(r0, r3, r4); r4 = r11.bEC; r4 = r4.mStatus; if (r9 != r4) goto L_0x0095; L_0x00f1: r4 = r11.bEC; r4 = r4.bEi; if (r4 == 0) goto L_0x00fe; L_0x00f7: r4 = r11.bEC; r4 = r4.bEi; r4.d(r1, r0); L_0x00fe: r4 = r11.bEC; r4 = r4.bEm; if (r4 == r1) goto L_0x011a; L_0x0104: r4 = "MicroMsg.RecordModeAsyncRead"; r5 = new java.lang.StringBuilder; r6 = "read len "; r5.<init>(r6); r5 = r5.append(r1); r5 = r5.toString(); com.tencent.mm.sdk.platformtools.x.i(r4, r5); L_0x011a: r4 = r11.bEC; r4 = r4.bEm; if (r1 >= r4) goto L_0x012e; L_0x0120: r4 = "MicroMsg.RecordModeAsyncRead"; r5 = "read too fast? sleep 10 ms"; com.tencent.mm.sdk.platformtools.x.i(r4, r5); r4 = 10; java.lang.Thread.sleep(r4); Catch:{ InterruptedException -> 0x0242 } L_0x012e: r4 = r11.bEC; r4 = r4.bEs; if (r4 == 0) goto L_0x0076; L_0x0134: if (r1 <= 0) goto L_0x0076; L_0x0136: r4 = r0.length; if (r1 <= r4) goto L_0x013a; L_0x0139: r1 = r0.length; L_0x013a: r4 = r11.bEC; r4 = r4.bEr; if (r4 == 0) goto L_0x022a; L_0x0140: r4 = r11.bEC; r4 = r4.mIsMute; if (r4 == 0) goto L_0x0149; L_0x0146: java.util.Arrays.fill(r0, r3, r1, r3); L_0x0149: r4 = r11.bEC; r5 = r4.bEr; if (r1 <= 0) goto L_0x0162; L_0x014f: r4 = r5.daJ; if (r4 == 0) goto L_0x0158; L_0x0153: r4 = r5.daK; r4.lock(); L_0x0158: r4 = r5.daH; r6 = r5.daI; if (r4 != r6) goto L_0x0186; L_0x015e: r4 = r5.daE; L_0x0160: if (r1 <= r4) goto L_0x01c0; L_0x0162: r1 = r2; L_0x0163: if (r1 == 0) goto L_0x0076; L_0x0165: r4 = "MicroMsg.RecordModeAsyncRead"; r5 = "WriteToBuffer Failed, ret:%d AudioBuffer length: %d"; r6 = new java.lang.Object[r9]; r1 = java.lang.Integer.valueOf(r1); r6[r3] = r1; r1 = r11.bEC; r1 = r1.bEr; r1 = r1.yx(); r1 = java.lang.Integer.valueOf(r1); r6[r10] = r1; com.tencent.mm.sdk.platformtools.x.e(r4, r5, r6); goto L_0x0076; L_0x0186: r4 = r5.daI; r4 = r4 + 1; r6 = r5.daE; r4 = r4 % r6; r6 = r5.daH; if (r4 != r6) goto L_0x0193; L_0x0191: r4 = r3; goto L_0x0160; L_0x0193: r4 = r5.daH; r6 = r5.daI; if (r4 >= r6) goto L_0x01af; L_0x0199: r4 = r5.daI; r6 = r5.daH; r4 = r4 - r6; r5.daF = r4; L_0x01a0: r4 = r5.daJ; if (r4 == 0) goto L_0x01a9; L_0x01a4: r4 = r5.daK; r4.unlock(); L_0x01a9: r4 = r5.daE; r6 = r5.daF; r4 = r4 - r6; goto L_0x0160; L_0x01af: r4 = r5.daH; r6 = r5.daI; if (r4 <= r6) goto L_0x01a0; L_0x01b5: r4 = r5.daI; r6 = r5.daE; r4 = r4 + r6; r6 = r5.daH; r4 = r4 - r6; r5.daF = r4; goto L_0x01a0; L_0x01c0: r4 = r5.daI; r4 = r4 + r1; r6 = r5.daE; r4 = r4 % r6; r6 = r5.daH; if (r4 != r6) goto L_0x01cc; L_0x01ca: r1 = r2; goto L_0x0163; L_0x01cc: r4 = r5.daJ; if (r4 == 0) goto L_0x01d5; L_0x01d0: r4 = r5.daK; r4.lock(); L_0x01d5: r4 = r5.daH; r6 = r5.daI; if (r4 >= r6) goto L_0x021a; L_0x01db: r4 = r5.daE; r6 = r5.daI; r4 = r4 - r6; if (r1 <= r4) goto L_0x021a; L_0x01e2: r4 = r5.daG; r6 = r5.daI; r7 = r5.daE; r8 = r5.daI; r7 = r7 - r8; java.lang.System.arraycopy(r0, r3, r4, r6, r7); r4 = r5.daE; r6 = r5.daI; r4 = r4 - r6; r6 = r5.daG; r7 = r5.daE; r8 = r5.daI; r7 = r7 - r8; r7 = r1 - r7; java.lang.System.arraycopy(r0, r4, r6, r3, r7); r4 = r5.daE; r6 = r5.daI; r4 = r4 - r6; r1 = r1 - r4; r5.daI = r1; r1 = r5.daI; r4 = r5.daE; r1 = r1 % r4; r5.daI = r1; L_0x020e: r1 = r5.daJ; if (r1 == 0) goto L_0x0217; L_0x0212: r1 = r5.daK; r1.unlock(); L_0x0217: r1 = r3; goto L_0x0163; L_0x021a: r4 = r5.daG; r6 = r5.daI; java.lang.System.arraycopy(r0, r3, r4, r6, r1); r4 = r5.daI; r1 = r1 + r4; r4 = r5.daE; r1 = r1 % r4; r5.daI = r1; goto L_0x020e; L_0x022a: r4 = r11.bEC; r4 = r4.bEs; if (r4 == 0) goto L_0x0076; L_0x0230: r4 = r11.bEC; r4 = r4.mIsMute; if (r4 == 0) goto L_0x0239; L_0x0236: java.util.Arrays.fill(r0, r3, r1, r3); L_0x0239: r4 = r11.bEC; r4 = r4.bEs; r4.s(r0, r1); goto L_0x0076; L_0x0242: r4 = move-exception; goto L_0x012e; L_0x0245: r4 = move-exception; goto L_0x008e; */ throw new UnsupportedOperationException("Method not decompiled: com.tencent.mm.e.b.e$b.run():void"); } }
package com.nationsky.vote; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import java.net.URISyntaxException; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Properties; import java.util.Random; import org.apache.commons.lang3.StringUtils; import org.flywaydb.core.Flyway; import org.flywaydb.core.api.FlywayException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.ds.framework.cache.CachePool; import com.ds.framework.db.DataBasePool; import com.ds.framework.fdfs.FdfsPool; import com.ds.framework.task.BaseTask; import com.ds.framework.task.TaskMsgFactroy; import com.nationsky.vote.component.Constants; import com.nationsky.vote.tasks.http.TaskHttp; import com.nationsky.vote.tasks.vote.VoteConstants; import com.nationsky.vote.tasks.vote.http.VoteHttp; import com.nationsky.vote.tasks.votefile.task.VoteFileTask; import com.nationsky.vote.util.CommonUtil; import com.nationsky.vote.util.FileUtil; import com.nationsky.vote.util.JsonUtil; import ch.qos.logback.classic.LoggerContext; import ch.qos.logback.classic.joran.JoranConfigurator; import ch.qos.logback.core.joran.spi.JoranException; import ch.qos.logback.core.util.StatusPrinter; public class Main { static Logger log = LoggerFactory.getLogger(Main.class); /** * 是否为开发环境 */ private static boolean isDev = false; /** * 节点ID */ public static String nodeId; /** * 是否启动完毕 */ public static boolean startFinished; /** * 配置文件 */ public static Config configProperties; /** * 中文国际化文件 */ public static Properties cnProperties = new Properties(); /** * 英文国际化文件 */ public static Properties enProperties = new Properties(); public static String DBURL = ""; /** * 启动服务器 * * @throws Exception */ public static void startup() throws Exception { startFinished = false; nodeId = newNodeId(); LOG.info("节点ID:" + nodeId); File homeDir = new File(Class.class.getResource("/").toURI()).getParentFile(); File configDir = new File(homeDir, "configs"); File i18nDir = new File(homeDir, "i18n"); loadConfig(configDir); loadProperties(i18nDir, "rspmsg-en.properties", enProperties); loadProperties(i18nDir, "rspmsg-zh_cn.properties", cnProperties); loadLogback(configDir); loadFramework(); loadAllTasks(); migrate(); Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { LOG.info("vote关闭"); } }); startFinished = true; } /** * * @param propertiesDir * @param filename * @param properties * @throws Exception */ private static void loadProperties(File propertiesDir, String fileName, Properties properties) throws Exception { String cnConfigFile = new File(propertiesDir, fileName).getAbsolutePath(); try { InputStream input = null; try { input = new FileInputStream(cnConfigFile);// 加载Java项目根路径下的配置文件 properties.load(input);// 加载属性文件 } finally { if (input != null) { input.close(); } } } catch (Exception e) { LOG.error("vote配置文件加载失败", e); throw e; } } /** * 加载logback配置文件 * * @throws JoranException */ private static void loadLogback(File configDir) throws JoranException { LoggerContext lc = (LoggerContext)LoggerFactory.getILoggerFactory(); JoranConfigurator configurator = new JoranConfigurator(); configurator.setContext(lc); lc.reset(); configurator.doConfigure(new File(configDir, "logback.xml")); StatusPrinter.printInCaseOfErrorsOrWarnings(lc); } /** * 配置文件加载 * * @throws URISyntaxException */ private static void loadConfig(File configDir) throws URISyntaxException { String configFile = null; if (isDev) { configFile = new File(configDir, "config-dev.json").getAbsolutePath(); } else { configFile = new File(configDir, "config.json").getAbsolutePath(); } String configText = FileUtil.readStringFromFile(Constants.CHARSET_UTF8, configFile); configProperties = (Config)JsonUtil.jsonToObject(configText, Config.class); /** * 数据库文件 */ if (StringUtils.isBlank(configProperties.getSqlite_db())) { DBURL = "jdbc:sqlite:" + Main.class.getClass().getResource("/").getPath() + "vote.db"; } else { DBURL = "jdbc:sqlite:" + configProperties.getSqlite_db(); } } /** * 模块加载 */ private static void loadAllTasks() { List<BaseTask> taskLists = new ArrayList<BaseTask>(); taskLists.add(new TaskHttp(Constants.TASKNAME_HTTP, Constants.TASKTYPE_FIXEDTHREAD, 10)); taskLists.add(new VoteHttp(VoteConstants.TASKNAME_VOTE, Constants.TASKTYPE_FIXEDTHREAD, 10)); taskLists.add(new VoteFileTask(VoteConstants.TASKNAME_VOTEFILE, Constants.TASKTYPE_SINGLETHREAD, 0)); TaskMsgFactroy.getInstance().addTasks(taskLists); } /** * 数据库版本 migrate * * @throws SQLException * @throws ClassNotFoundException */ private static void migrate() throws ClassNotFoundException, SQLException, FlywayException { checkSqlite(); Flyway flyway = new Flyway(); // Point it to the database flyway.setDataSource(DBURL, "", null); // Start the migration // flyway.setLocations("classpath:db/sqlite"); flyway.setTable("vote_schema_version");// 设置存放flyway metadata数据的表名.默认小写的schema_version flyway.setBaselineOnMigrate(true);// 设置基线,已经开发过一段时间的数据库需要设置为true flyway.setLocations("classpath:db.sqlite"); // 设置flyway扫描sql升级脚本、java升级脚本的目录路径或包路径。脚本命名规约详见flyway官网 flyway.setEncoding("UTF-8"); // 设置sql脚本文件的编码 flyway.migrate(); } /** * 数据库文件校验 * * @throws SQLException * @throws ClassNotFoundException */ private static void checkSqlite() throws SQLException, ClassNotFoundException { Class.forName("org.sqlite.JDBC");// 加载驱动,连接sqlite的jdbc Connection connection = DriverManager.getConnection(DBURL);// 连接数据库zhou.db,不存在则创建 connection.close();// 关闭数据库连接 } /** * 框架加载 */ private static void loadFramework() { if (StringUtils.isNotBlank(configProperties.getRedis_url())) { CachePool.initCachePool(configProperties.getRedis_url(), configProperties.getRedis_password(), configProperties.getRedis_index()); } if (StringUtils.isNotBlank(configProperties.getFdfs_tracker())) { FdfsPool.initFdfsPool(configProperties.getFdfs_tracker()); } // configProperties.setDb_url(DBURL + "?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true"); configProperties.setDb_url(DBURL); DataBasePool.initDbPool(configProperties.getDb_url(), configProperties.getDb_username(), configProperties.getDb_password()); } /** * * @param args */ public static void main(String[] args) { if (args != null && args.length > 0 && Arrays.asList(args).contains("-dev")) { isDev = true; } try { startup(); } catch (Exception e) { LOG.error("vote启动失败", e); System.exit(1); } } /** * * @return */ public static String newNodeId() { return Constants.NODE_ID + "_" + CommonUtil.newShortUUID() + "_" + new Random().nextInt(1000000); } /** * LOG */ private static final Logger LOG = LoggerFactory.getLogger(Main.class); }
/** Copyright [plter] [xtiqin] http://plter.sinaapp.com 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. This is a part of PlterAndroidLib on http://plter.sinaapp.com/?cat=14 */ package com.plter.lib.android.java.anim; import android.graphics.Camera; import android.view.animation.Animation; import android.view.animation.Transformation; /** * 3D变换类 * @author xtiqin * @see <a href="http://plter.sinaapp.com">plter</a> * */ public class Translate3DAnim extends Animation { /** * 翻转时远去 */ public static final int MOVE_FAR=1; /** * 翻转时靠近 */ public static final int MOVE_NEAR=2; /** * 翻转时位置不动 */ public static final int DONOT_MOVE=3; /** * 构建一个3D变换动画效果 * @param fromAngle 旋转起始角度 * @param endAngle 旋转结束角度 * @param moveMode 移动模式,为MOVE_FAR,MOVE_NEAR,DONOT_MOVE三者之一 */ public Translate3DAnim(float fromAngle,float endAngle,int moveMode) { this.fromAngle=fromAngle; this.endAngle=endAngle; this.moveMode=moveMode; setDuration(350); setFillAfter(true); } // private int width=0; // private int height=0; private int parentWidth=0; private int parentHeight=0; private float maxDepth=0; private float fromAngle=0; private int moveMode=3; private Camera camera; public float getFromAngle() { return fromAngle; } public float getEndAngle() { return endAngle; } private float endAngle=0; public void initialize(int width, int height, int parentWidth, int parentHeight) { // this.width=width; // this.height=height; this.parentHeight=parentHeight; this.parentWidth=parentWidth; maxDepth=parentWidth; camera=new Camera(); super.initialize(width, height, parentWidth, parentHeight); } protected void applyTransformation(float interpolatedTime, Transformation t) { camera.save(); switch (moveMode) { case MOVE_FAR: camera.translate(0, 0, maxDepth*interpolatedTime/3*2); break; case MOVE_NEAR: camera.translate(0, 0, maxDepth*(1-interpolatedTime)/3*2); break; } camera.rotateY(fromAngle+(endAngle-fromAngle)*interpolatedTime); camera.getMatrix(t.getMatrix()); camera.restore(); t.getMatrix().preTranslate(-parentWidth/2, -parentHeight/2); t.getMatrix().postTranslate(parentWidth/2, parentHeight/2); super.applyTransformation(interpolatedTime, t); } }
package swexpert; import java.util.Scanner; import algo_basic.day1.io.ScannerTest; public class SWEA_2058_D1_자릿수더하기 { public static void main(String[] args) { // TODO Auto-generated method stub Scanner s = new Scanner(System.in); String src = s.next(); String[] splited = src.split(""); int sum = 0; for (int i = 0; i < splited.length; i++) { sum += Integer.parseInt(splited[i]); } System.out.println(sum); } }
package com.tencent.mm.ui.chatting; import android.os.Bundle; import com.tencent.mm.sdk.e.k; class ar$1 extends k<ad, Bundle> { ar$1() { } protected final /* synthetic */ void q(Object obj, Object obj2) { ((ad) obj).ag((Bundle) obj2); } }
package com.sunteam.library.db; import com.sunteam.library.utils.DatabaseConstants; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.database.sqlite.SQLiteDatabase.CursorFactory; //创建图书馆数据库 public class LibraryDBHelper extends SQLiteOpenHelper { public static final String CREATE_CATEGORY_TABLE = //创建分类表 "create table if not exists " + DatabaseConstants.CATEGORY_TABLE_NAME + " (_id integer PRIMARY KEY AUTOINCREMENT," + DatabaseConstants.RESOURCE_TYPE + " integer," + DatabaseConstants.CATEGORY_FATHER + " integer," + DatabaseConstants.CATEGORY_SEQ + " integer," + DatabaseConstants.CATEGORY_LEVEL + " integer," + DatabaseConstants.CATEGORY_NAME + " varchar(128)," + DatabaseConstants.CATEGORY_CODE + " varchar(128)," + DatabaseConstants.CATEGORY_TYPE + " varchar(128))"; public static final String CREATE_RESOURCE_TABLE = //创建资源表 "create table if not exists " + DatabaseConstants.RESOURCE_TABLE_NAME + " (_id integer PRIMARY KEY AUTOINCREMENT," + DatabaseConstants.RESOURCE_TYPE + " integer," + DatabaseConstants.RESOURCE_CATEGORYCODE + " varchar(128)," + DatabaseConstants.RESOURCE_DBCODE + " varchar(128)," + DatabaseConstants.RESOURCE_SYSID + " varchar(128)," + DatabaseConstants.RESOURCE_TITLE + " varchar(128)," + DatabaseConstants.RESOURCE_AUTHOR + " varchar(128)," + DatabaseConstants.RESOURCE_KEYWORDS + " varchar(128)," + DatabaseConstants.RESOURCE_ABS + " varchar(1024)," + DatabaseConstants.RESOURCE_PUBLISH + " varchar(128)," + DatabaseConstants.RESOURCE_IDENTIFIER + " varchar(128))"; public static final String CREATE_CHAPTER_TABLE = //创建章节表 "create table if not exists " + DatabaseConstants.CHAPTER_TABLE_NAME + " (_id integer PRIMARY KEY AUTOINCREMENT," + DatabaseConstants.RESOURCE_TYPE + " integer," + DatabaseConstants.CHAPTER_FATHER + " integer," + DatabaseConstants.CHAPTER_SEQ + " integer," + DatabaseConstants.CHAPTER_LEVEL + " integer," + DatabaseConstants.CHAPTER_DBCODE + " varchar(128)," + DatabaseConstants.CHAPTER_SYSID + " varchar(128)," + DatabaseConstants.CHAPTER_IDENTIFIER + " varchar(128)," + DatabaseConstants.CHAPTER_INDEX + " varchar(128)," + DatabaseConstants.CHAPTER_NAME + " varchar(512)," + DatabaseConstants.CHAPTER_URL + " varchar(1024))"; public static final String CREATE_INFO_TABLE = //创建资源表 "create table if not exists " + DatabaseConstants.INFO_TABLE_NAME + " (_id integer PRIMARY KEY AUTOINCREMENT," + DatabaseConstants.RESOURCE_TYPE + " integer," + DatabaseConstants.INFO_TITLE + " varchar(512)," + DatabaseConstants.INFO_DATE + " varchar(32))"; public static final String CREATE_HISTORY_TABLE = //创建历史表 "create table if not exists " + DatabaseConstants.HISTORY_TABLE_NAME + " (_id integer PRIMARY KEY AUTOINCREMENT," + DatabaseConstants.HISTORY_ID + " integer," + DatabaseConstants.HISTORY_RESTYPE + " integer," + DatabaseConstants.HISTORY_LCINDEX + " integer," + DatabaseConstants.HISTORY_USERNAME + " varchar(64)," + DatabaseConstants.HISTORY_TITLE + " varchar(128)," + DatabaseConstants.HISTORY_DBCODE + " varchar(128)," + DatabaseConstants.HISTORY_SYSID + " varchar(128)," + DatabaseConstants.HISTORY_ENTERPOINT + " varchar(16)," + DatabaseConstants.HISTORY_URL + " varchar(1024)," + DatabaseConstants.HISTORY_CTIME + " varchar(128)," + DatabaseConstants.HISTORY_UTIME + " varchar(128)," + DatabaseConstants.HISTORY_BOOKTITLE + " varchar(128)," + DatabaseConstants.HISTORY_COVERURL + " varchar(1024)," + DatabaseConstants.HISTORY_PERCENT + " varchar(16)," + DatabaseConstants.HISTORY_CFULLNAME + " varchar(1024)," + DatabaseConstants.HISTORY_CATEGORYCODE + " varchar(128))"; public static final String CREATE_BOOKMARK_TABLE = //创建书签表 "create table if not exists " + DatabaseConstants.BOOKMARK_TABLE_NAME + " (_id integer PRIMARY KEY AUTOINCREMENT," + DatabaseConstants.BOOKMARK_ID + " integer," + DatabaseConstants.BOOKMARK_BEGIN + " integer," + DatabaseConstants.BOOKMARK_CHAPTER_INDEX + " integer," + DatabaseConstants.BOOKMARK_USERNAME + " varchar(64)," + DatabaseConstants.BOOKMARK_BOOKID + " varchar(128)," + DatabaseConstants.BOOKMARK_ADDEDTIME + " varchar(128)," + DatabaseConstants.BOOKMARK_CHAPTER_TITLE + " varchar(1024)," + DatabaseConstants.BOOKMARK_MARKNAME + " varchar(1024)," + DatabaseConstants.BOOKMARK_PERCENT + " varchar(64))"; public static final String CREATE_COLLECT_CATEGORY_TABLE = //创建收藏分类表 "create table if not exists " + DatabaseConstants.COLLECT_CATEGORY_TABLE_NAME + " (_id integer PRIMARY KEY AUTOINCREMENT," + DatabaseConstants.COLLECT_CATEGORY_ID + " integer," + DatabaseConstants.COLLECT_CATEGORY_RESTYPE + " integer," + DatabaseConstants.COLLECT_CATEGORY_USERNAME + " varchar(64)," + DatabaseConstants.COLLECT_CATEGORY_NAME + " varchar(128)," + DatabaseConstants.COLLECT_CATEGORY_FULLNAME + " varchar(1024)," + DatabaseConstants.COLLECT_CATEGORY_CODE + " varchar(128))"; public static final String CREATE_COLLECT_RESOURCE_TABLE = //创建收藏资源表 "create table if not exists " + DatabaseConstants.COLLECT_RESOURCE_TABLE_NAME + " (_id integer PRIMARY KEY AUTOINCREMENT," + DatabaseConstants.COLLECT_RESOURCE_ID + " integer," + DatabaseConstants.COLLECT_RESOURCE_RESTYPE + " integer," + DatabaseConstants.COLLECT_RESOURCE_USERNAME + " varchar(64)," + DatabaseConstants.COLLECT_RESOURCE_TITLE + " varchar(128)," + DatabaseConstants.COLLECT_RESOURCE_DBCODE + " varchar(128)," + DatabaseConstants.COLLECT_RESOURCE_SYSID + " varchar(128)," + DatabaseConstants.COLLECT_RESOURCE_FULLNAME + " varchar(1024)," + DatabaseConstants.COLLECT_RESOURCE_COVERURL + " varchar(1024)," + DatabaseConstants.COLLECT_RESOURCE_CREATETIME + " varchar(64))"; public static final String CREATE_DOWNLOAD_RESOURCE_TABLE = //创建下载资源表 "create table if not exists " + DatabaseConstants.DOWNLOAD_RESOURCE_TABLE_NAME + " (_id integer PRIMARY KEY AUTOINCREMENT," + DatabaseConstants.DOWNLOAD_RESOURCE_CHAPTER_COUNT + " integer," + DatabaseConstants.DOWNLOAD_RESOURCE_RESTYPE + " integer," + DatabaseConstants.DOWNLOAD_RESOURCE_STATUS + " integer," + DatabaseConstants.DOWNLOAD_RESOURCE_USERNAME + " varchar(64)," + DatabaseConstants.DOWNLOAD_RESOURCE_TITLE + " varchar(128)," + DatabaseConstants.DOWNLOAD_RESOURCE_DBCODE + " varchar(128)," + DatabaseConstants.DOWNLOAD_RESOURCE_SYSID + " varchar(128)," + DatabaseConstants.DOWNLOAD_RESOURCE_IDENTIFIER + " varchar(128)," + DatabaseConstants.DOWNLOAD_RESOURCE_CATEGORYCODE + " varchar(128)," + DatabaseConstants.DOWNLOAD_RESOURCE_FULLNAME + " varchar(1024))"; public static final String CREATE_DOWNLOAD_CHAPTER_TABLE = //创建下载章节表 "create table if not exists " + DatabaseConstants.DOWNLOAD_CHAPTER_TABLE_NAME + " (_id integer PRIMARY KEY AUTOINCREMENT," + DatabaseConstants.DOWNLOAD_CHAPTER_RECORDID + " integer," + DatabaseConstants.DOWNLOAD_CHAPTER_INDEX + " integer," + DatabaseConstants.DOWNLOAD_CHAPTER_STATUS + " integer," + DatabaseConstants.DOWNLOAD_CHAPTER_NAME + " varchar(128)," + DatabaseConstants.DOWNLOAD_CHAPTER_PATH + " varchar(1024)," + DatabaseConstants.DOWNLOAD_CHAPTER_URL + " varchar(1024))"; public LibraryDBHelper( Context context, String name, CursorFactory factory, int version ) { super(context, name, factory, version); } @Override public void onCreate(SQLiteDatabase db) { // TODO Auto-generated method stub db.execSQL(CREATE_CATEGORY_TABLE); //创建分类表 db.execSQL(CREATE_RESOURCE_TABLE); //创建资源表 db.execSQL(CREATE_CHAPTER_TABLE); //创建章节表 db.execSQL(CREATE_INFO_TABLE); //创建资讯表 db.execSQL(CREATE_HISTORY_TABLE); //创建历史表 db.execSQL(CREATE_BOOKMARK_TABLE); //创建书签表 db.execSQL(CREATE_COLLECT_CATEGORY_TABLE); //创建收藏分类表 db.execSQL(CREATE_COLLECT_RESOURCE_TABLE); //创建收藏资源表 db.execSQL(CREATE_DOWNLOAD_RESOURCE_TABLE); //创建下载资源表 db.execSQL(CREATE_DOWNLOAD_CHAPTER_TABLE); //创建下载章节表 } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { // TODO Auto-generated method stub } }
package de.rwth.i9.palm.persistence; import java.util.List; import java.util.Map; import de.rwth.i9.palm.model.Event; import de.rwth.i9.palm.model.EventGroup; public interface EventDAO extends GenericDAO<Event>, InstantiableDAO { /** * Trigger batch indexing using Hibernate search powered by Lucene * * @throws InterruptedException */ public void doReindexing() throws InterruptedException; /** * Get the map of events * * @return Hashmap with event notation as key and event as its value */ Map<String, Event> getNotationEventMaps(); /** * Get all event in pagination * * @param pageNo * @param maxResult * @return */ public Map<String, Object> getEventWithPaging( int pageNo, int maxResult ); /** * Apply fulltext search with Hibernate search * * @param queryString * @return list of all related event */ public List<Event> getEventByFullTextSearch( String queryString ); /** * Apply fulltext search with Hibernate search with paging * * @param queryString * @return Map<String, Object> Map< "count", Int numberOfMatchingEvent > - * the total number of matching events Map< "result", List <Event> > * - the event list */ public Map<String, Object> getEventByFullTextSearchWithPaging( String query, int page, int maxResult ); /** * Get List of event using Lucene Fuzzy Query given threshold and * prefixlength * * @param name * @param threshold * @param prefixLength * @return */ public List<EventGroup> getEventViaFuzzyQuery( String name, float threshold, int prefixLength ); /** * Get event given event notation/name and year * * @param eventNameOrNotation * @param year * @return */ public Event getEventByEventNameOrNotationAndYear( String eventNameOrNotation, String year ); }
/* * 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 Memoria; /** * * @author JP */ public class Matriz { private MNodo Inicio; public Matriz(){ Inicio = null; } public void Crear(int x, int y){ Ingresar(x-1,y-1); } public void Ingresar(int x, int y){ if(MatrizVacia()) { MNodo nuevo = new MNodo(); nuevo.setX(0); nuevo.setY(0); Inicio = nuevo; MNodo aux; MNodo aux1; MNodo aux2; MNodo tmp = Inicio; while(tmp != null) { aux = tmp; if(tmp.getSiguiente() != null) { aux2 = tmp.getSiguiente(); if(tmp.getAtras() != null) { aux1 = tmp.getAtras(); while(aux != null) { if(aux.getY() < y && aux.getArriba() == null) { MNodo n = new MNodo(); n.setY(aux.getY()+1); n.setX(aux.getX()); aux.setArriba(n); n.setAbajo(aux); n.setAtras(aux1.getArriba()); aux1.getArriba().setSiguiente(n); n.setSiguiente(aux2.getArriba()); aux2.getArriba().setAtras(n); } aux = aux.getArriba(); aux1 = aux1.getArriba(); aux2 = aux2.getArriba(); } }else{ while(aux != null) { if(aux.getY() < y && aux.getArriba() == null) { MNodo n = new MNodo(); n.setY(aux.getY()+1); n.setX(aux.getX()); aux.setArriba(n); n.setAbajo(aux); n.setSiguiente(aux2.getArriba()); aux2.getArriba().setAtras(n); } aux = aux.getArriba(); aux2 = aux2.getArriba(); } } }else{ if(tmp.getAtras() != null) { aux1 = tmp.getAtras(); while(aux != null) { if(aux.getY() < y && aux.getArriba() == null) { MNodo n = new MNodo(); n.setY(aux.getY()+1); n.setX(aux.getX()); aux.setArriba(n); n.setAbajo(aux); n.setAtras(aux1.getArriba()); aux1.getArriba().setSiguiente(n); } aux = aux.getArriba(); aux1 = aux1.getArriba(); } }else{ while(aux != null) { if(aux.getY() < y && aux.getArriba() == null) { MNodo n = new MNodo(); n.setY(aux.getY()+1); n.setX(aux.getX()); aux.setArriba(n); n.setAbajo(aux); } aux = aux.getArriba(); } } } if(tmp.getX() < x && tmp.getSiguiente() == null) { MNodo n = new MNodo(); n.setY(tmp.getY()); n.setX(tmp.getX()+1); n.setAtras(tmp); tmp.setSiguiente(n); } tmp = tmp.getSiguiente(); } }else{ MNodo aux; MNodo aux1; MNodo aux2; MNodo tmp = Inicio; while(tmp != null) { aux = tmp; if(tmp.getSiguiente() != null) { aux2 = tmp.getSiguiente(); if(tmp.getAtras() != null) { aux1 = tmp.getAtras(); while(aux != null) { if(aux.getY() < y && aux.getArriba() == null) { MNodo n = new MNodo(); n.setY(aux.getY()+1); n.setX(aux.getX()); aux.setArriba(n); n.setAbajo(aux); n.setAtras(aux1.getArriba()); aux1.getArriba().setSiguiente(n); } aux = aux.getArriba(); aux1 = aux1.getArriba(); } }else{ while(aux != null) { if(aux.getY() < y && aux.getArriba() == null) { MNodo n = new MNodo(); n.setY(aux.getY()+1); n.setX(aux.getX()); aux.setArriba(n); n.setAbajo(aux); } aux = aux.getArriba(); } } }else{ if(tmp.getAtras() != null) { aux1 = tmp.getAtras(); while(aux != null) { if(aux.getY() < y && aux.getArriba() == null) { MNodo n = new MNodo(); n.setY(aux.getY()+1); n.setX(aux.getX()); aux.setArriba(n); n.setAbajo(aux); n.setAtras(aux1.getArriba()); aux1.getArriba().setSiguiente(n); } aux = aux.getArriba(); aux1 = aux1.getArriba(); } }else{ while(aux != null) { if(aux.getY() < y && aux.getArriba() == null) { MNodo n = new MNodo(); n.setY(aux.getY()+1); n.setX(aux.getX()); aux.setArriba(n); n.setAbajo(aux); } aux = aux.getArriba(); } } } if(tmp.getX() < x && tmp.getSiguiente() == null) { MNodo n = new MNodo(); n.setY(tmp.getY()); n.setX(tmp.getX()+1); n.setAtras(tmp); tmp.setSiguiente(n); } tmp = tmp.getSiguiente(); } } } public void Mostrar(){ MNodo aux = Inicio; MNodo tmp; while(aux != null) { tmp = aux; while(tmp != null) { System.out.print("("+tmp.getX()+","+tmp.getY()+")"); tmp = tmp.getSiguiente(); } System.out.println(" "); aux = aux.getArriba(); } } public boolean MatrizVacia(){ return Inicio == null; } public void EliminarFila(){ if(!MatrizVacia()) { MNodo aux = Inicio; while(aux.getArriba() != null) { aux = aux.getArriba(); } MNodo tmp = aux.getSiguiente(); while(aux != null) { if(tmp != null) { aux.getAbajo().setArriba(null); tmp.setAtras(null); aux = null; aux = tmp; tmp = tmp.getSiguiente(); }else{ if(aux.getAbajo() != null) { aux.getAbajo().setArriba(null); aux = null; }else{ Inicio = aux = null; } } } } } public void EliminarColumna(){ if(!MatrizVacia()) { MNodo aux = Inicio; while(aux.getSiguiente() != null) { aux = aux.getSiguiente(); } MNodo tmp = aux.getArriba(); while(aux != null) { if(tmp != null) { aux.getAtras().setSiguiente(null); tmp.setAbajo(null); aux = null; aux = tmp; tmp = tmp.getArriba(); }else{ if(aux.getAtras() != null) { aux.getAtras().setSiguiente(null); aux = null; }else{ Inicio = aux = null; } } } } } public MNodo getInicio() { return Inicio; } public void setInicio(MNodo Inicio) { this.Inicio = Inicio; } }
package com.okason.profileimagedemo.Adapter; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ImageView; import android.widget.TextView; import com.okason.profileimagedemo.Model.Customer; import com.okason.profileimagedemo.R; import java.util.List; /** * Created by Valentine on 4/16/2015. */ public class CustomerAdapter extends ArrayAdapter<Customer>{ private Context mContext; private List<Customer> mCustomers; public CustomerAdapter(Context context, List<Customer> customers) { super(context, R.layout.row_customer_list, customers); context = mContext; mCustomers = customers; } @Override public int getCount() { return mCustomers.size(); } @Override public Customer getItem(int position) { if (position < mCustomers.size()) { return mCustomers.get(position); } return null; } @Override public long getItemId(int position) { return position; } public class Holder{ private TextView Name; private TextView Email; private ImageView Thumbnail; } public void Add(Customer customer) { mCustomers.add(customer); this.notifyDataSetChanged(); } public void Update() { mCustomers.clear(); this.notifyDataSetChanged(); } @Override public View getView(int position, View convertView, ViewGroup parent) { View view = convertView; Holder mHolder; Customer customer= getItem(position); if (view == null){ view = LayoutInflater.from(getContext()).inflate(R.layout.row_customer_list, null); mHolder = new Holder(); mHolder.Name = (TextView) view.findViewById(R.id.textCustomerName); mHolder.Email = (TextView) view.findViewById(R.id.textCustomerEmail); mHolder.Thumbnail = (ImageView) view.findViewById(R.id.customer_image_thumbnail); view.setTag(mHolder); }else { mHolder = (Holder)view.getTag(); } //Set the customer name if (mHolder.Name != null) { mHolder.Name.setText(customer.getName()); } //Set the customer email if (mHolder.Email != null) { mHolder.Email.setText(customer.getEmailAddress()); } //set the customer thumbnail if (mHolder.Thumbnail != null){ mHolder.Thumbnail.setImageDrawable(customer.getThumbnail(getContext())); } return view; } }
package org.jcarvajal.webapp.repositories; import java.util.HashMap; import java.util.Map; import org.jcarvajal.webapp.model.AccessToken; import org.jcarvajal.webapp.model.User; public class UserRepositoryImpl implements UserRepository { private Map<String, AccessToken> accessTokens = new HashMap<String, AccessToken>(); private Map<String, User> users = new HashMap<String, User>(); public AccessToken getAccessToken(String token) { return accessTokens.get(token); } public void addAccessToken(AccessToken accessToken) { accessTokens.put(accessToken.getToken(), accessToken); } public void deleteAccessToken(AccessToken accessToken) { accessTokens.remove(accessToken.getToken()); } public void addUser(String username, String pass, String role) { User user = new User(); user.setUsername(username); user.setPassword(pass); user.setRole(role); users.put(username, user); } public User getUser(String username, String pass) { User found = null; User user = users.get(username); if (user != null && user.getPassword().equals(pass)) { found = user; } return found; } }
package com.ybg.base.util; import com.ybg.rbac.user.domain.User; /** 系统常量类 **/ public class UserConstant { /** 判断当前角色是超管 **/ public boolean IsAdmin() { User user = Common.findUserSession(); if (user != null && user.getRoleid().equals("1")) { return true; } return false; } /** 判断当前角色是企业管理员 **/ public boolean IsCompanyAdmin() { User user = Common.findUserSession(); if (user != null && user.getRoleid().equals("2")) { return true; } return false; } /** 判断当前角色是企业员工 **/ public boolean IsCompanyEmployee() { User user = Common.findUserSession(); if (user != null && user.getRoleid().equals("3")) { return true; } return false; } private UserConstant() { // 禁止实例化 } }
package net.minecraft.tileentity; import net.minecraft.block.BlockDaylightDetector; import net.minecraft.util.ITickable; public class TileEntityDaylightDetector extends TileEntity implements ITickable { public void update() { if (this.world != null && !this.world.isRemote && this.world.getTotalWorldTime() % 20L == 0L) { this.blockType = getBlockType(); if (this.blockType instanceof BlockDaylightDetector) ((BlockDaylightDetector)this.blockType).updatePower(this.world, this.pos); } } } /* Location: C:\Users\BSV\AppData\Local\Temp\Rar$DRa6216.20396\Preview\Preview.jar!\net\minecraft\tileentity\TileEntityDaylightDetector.class * Java compiler version: 8 (52.0) * JD-Core Version: 1.1.3 */
/* * 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.webbeans.test.concepts.alternatives.tests; import java.lang.annotation.Annotation; import java.util.ArrayList; import java.util.Collection; import jakarta.enterprise.util.AnnotationLiteral; import org.junit.Assert; import org.apache.webbeans.test.AbstractUnitTest; import org.apache.webbeans.test.concepts.alternatives.common.AlternativeOnClassAndProducerMethodBean; import org.apache.webbeans.test.concepts.alternatives.common.AlternativeOnClassOnlyBean; import org.apache.webbeans.test.concepts.alternatives.common.DefaultBeanProducer; import org.apache.webbeans.test.concepts.alternatives.common.DefaultBeanProducerWithoutDisposes; import org.apache.webbeans.test.concepts.alternatives.common.IProducedBean; import org.apache.webbeans.test.concepts.alternatives.common.QualifierProducerBased; import org.junit.Test; import org.junit.Ignore; public class AlternativeProducerMethodTest extends AbstractUnitTest { private static final String PACKAGE_NAME = AlternativeProducerMethodTest.class.getPackage().getName(); @Test public void testNotEnabledAlternativeOnClassOnlyBean() { Collection<Class<?>> beanClasses = new ArrayList<Class<?>>(); beanClasses.add(DefaultBeanProducer.class); // available but not enabled in beans.xml beanClasses.add(AlternativeOnClassOnlyBean.class); startContainer(beanClasses, null); Annotation[] anns = new Annotation[1]; anns[0] = new AnnotationLiteral<QualifierProducerBased>() { }; IProducedBean model = getInstance(IProducedBean.class, anns); Assert.assertNotNull(model); Assert.assertEquals("default", model.getProducerType()); shutDownContainer(); } @Test @Ignore("need to clarify this with the EG") //X TODO It's not yet clear how paragraph 5.1.1 is to be interpreted public void testAlternativeOnClassOnlyBean() { Collection<String> beanXmls = new ArrayList<String>(); beanXmls.add(getXmlPath(PACKAGE_NAME, "AlternativeOnClassOnly")); Collection<Class<?>> beanClasses = new ArrayList<Class<?>>(); beanClasses.add(DefaultBeanProducer.class); beanClasses.add(AlternativeOnClassOnlyBean.class); startContainer(beanClasses, null); Annotation[] anns = new Annotation[1]; anns[0] = new AnnotationLiteral<QualifierProducerBased>() { }; IProducedBean model = getInstance(IProducedBean.class, anns); Assert.assertNotNull(model); Assert.assertEquals("AlternativeOnClassOnlyBean", model.getProducerType()); shutDownContainer(); } @Test public void testAlternativeOnClassAndProducerMethodBean() { Collection<String> beanXmls = new ArrayList<String>(); beanXmls.add(getXmlPath(PACKAGE_NAME, "AlternativeOnClassAndProducerMethod")); Collection<Class<?>> beanClasses = new ArrayList<Class<?>>(); beanClasses.add(IProducedBean.class); beanClasses.add(DefaultBeanProducerWithoutDisposes.class); // available but not enabled in beans.xml beanClasses.add(AlternativeOnClassAndProducerMethodBean.class); startContainer(beanClasses, beanXmls); IProducedBean producedBean = getInstance(IProducedBean.class, new AnnotationLiteral<QualifierProducerBased>(){}); Assert.assertNotNull(producedBean); Assert.assertEquals("AlternativeOnClassAndProducerMethodBean", producedBean.getProducerType()); shutDownContainer(); } //X TODO add tests for disposal methods }
package com.hua.mvp.global; /** * 全局常量 */ public class C { public static final String ACTION_PICTURE_ACTIVITY = "ACTION_PICTURE_ACTIVITY"; public static final String EXTRA_PICTURE_ID = "EXTRA_PICTURE_ID"; public static final class ImageUrl{ public static final int DEFAULT_ROWS = 10; /**所有数据请求的基地址 */ public static final String BASE_URL = "http://www.tngou.net/tnfs/api/"; /**图片的基地址 */ public static final String BASE_IMAGE_URL = "http://tnfs.tngou.net/image"; } }