text stringlengths 10 2.72M |
|---|
package com.siicanada.article.controller;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import com.siicanada.article.model.ArticleModel;
import com.siicanada.article.service.ArticleService;
import java.util.ArrayList;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
/**
* Classe de test de la classe {@link ArticleController}
*/
@RunWith(MockitoJUnitRunner.class)
@WebMvcTest(TagController.class)
@AutoConfigureMockMvc
public class TagControllerTest {
@InjectMocks
private TagController tagController;
private MockMvc mockMvc;
@Mock
private ArticleService articleService;
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
this.mockMvc = MockMvcBuilders.standaloneSetup(tagController).build();
}
@Test
public void getArticlesByTagDescriptionShouldReturnArticleListAndStatusCode200()
throws Exception {
String jsonExpected = "[{\"id\":1,\"title\":\"Bienvenue\",\"intro\":\"Ceci est une intro\",\"text\":null,\"picture\":null,\"picture_description\":null,\"tags\":null}]";
ArticleModel articleModel = new ArticleModel();
articleModel.setId(1);
articleModel.setTitle("Bienvenue");
articleModel.setIntro("Ceci est une intro");
List<ArticleModel> articleModelList = new ArrayList<>();
articleModelList.add(articleModel);
when(articleService.getArticlesByTagDescription("sport")).thenReturn(articleModelList);
mockMvc.perform(get("/tags/{description}/articles", "sport"))
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(content().json(jsonExpected))
.andExpect(status().isOk());
verify(articleService, times(1)).getArticlesByTagDescription("sport");
}
@Test
public void getArticlesWithUnknownDescriptionPathShouldReturnStatusCode404() throws Exception {
mockMvc.perform(get("/tags/{description}/article", "TV"))
.andExpect(status().isNotFound());
}
}
|
package core.event.handlers.hero;
import cards.Card.Color;
import core.event.game.basic.AttackLockedTargetSkillsCheckEvent;
import core.event.handlers.AbstractEventHandler;
import core.heroes.skills.YujinOriginalHeroSkill;
import core.player.PlayerCompleteServer;
import core.server.game.BattleLog;
import core.server.game.GameDriver;
import core.server.game.GameInternal;
import core.server.game.controllers.AbstractSingleStageGameController;
import core.server.game.controllers.mechanics.AttackResolutionGameController.AttackResolutionStage;
import exceptions.server.game.GameFlowInterruptedException;
public class YujinAttackCheckEventHandler extends AbstractEventHandler<AttackLockedTargetSkillsCheckEvent> {
public YujinAttackCheckEventHandler(PlayerCompleteServer player) {
super(player);
}
@Override
public Class<AttackLockedTargetSkillsCheckEvent> getEventClass() {
return AttackLockedTargetSkillsCheckEvent.class;
}
@Override
protected void handleIfActivated(AttackLockedTargetSkillsCheckEvent event, GameDriver game) throws GameFlowInterruptedException {
if (this.player != event.target) {
return;
}
if (event.controller.getAttackCard().getColor() == Color.BLACK) {
game.pushGameController(new AbstractSingleStageGameController() {
@Override
protected void handleOnce(GameInternal game) throws GameFlowInterruptedException {
// skip Attack Resolution
event.controller.setStage(AttackResolutionStage.END);
game.log(BattleLog.playerASkillPassivelyTriggered(player, new YujinOriginalHeroSkill(), "Attack is blocked"));
}
});
}
}
}
|
package org.bsns.server.board.approval;
import java.sql.SQLException;
import java.util.List;
import org.apache.log4j.Logger;
import org.bsns.server.common.Condition;
import org.bsns.server.common.SqlMapClientConfig;
import org.bsns.server.domain.ApprovalVO;
import org.springframework.stereotype.Repository;
@Repository("ApprovalDAO")
public class ApprovalDAOImpl
extends SqlMapClientConfig
implements ApprovalDAO{
private static final String NAMESPACE = "Approval.";
private Logger log = Logger.getLogger(this.getClass());
@Override
public void create(ApprovalVO approval) throws SQLException {
log.debug("===== ApprovalDAOImpl Class Create start =====");
getSqlMapClient().insert(NAMESPACE + "create", approval);
log.debug("===== ApprovalDAOImpl Class Create end =====");
}
@Override
public ApprovalVO read(Condition condition) throws SQLException {
log.debug("===== ApprovalDAOImpl Class Read start =====");
ApprovalVO approval = (ApprovalVO)getSqlMapClient().queryForObject(NAMESPACE + "read", condition);
log.debug("approval value : " + approval);
log.debug("===== ApprovalDAOImpl Class Read end =====");
return approval;
}
@Override
public void update(ApprovalVO approval) throws SQLException {
log.debug("===== ApprovalDAOImpl Class Update start =====");
getSqlMapClient().update(NAMESPACE + "update", approval);
log.debug("===== ApprovalDAOImpl Class Update end =====");
}
@Override
public void delete(Condition condition) throws SQLException {
log.debug("===== ApprovalDAOImpl Class Delete start =====");
log.debug(condition);
getSqlMapClient().delete(NAMESPACE + "delete", condition);
log.debug("===== ApprovalDAOImpl Class Delete end =====");
}
// @Override
// public List<ApprovalVO> list(Condition condition) throws SQLException {
// log.debug("===== ApprovalDAOImpl Class List start =====");
// List<ApprovalVO> list = (List<ApprovalVO>)getSqlMapClient().queryForList(NAMESPACE + "list", condition);
// log.debug("list value : " + list);
// log.debug("===== ApprovalDAOImpl Class List end =====");
// return list;
// }
}
|
package com.wipro.arrays;
import java.util.*;
public class Ex6 {
public static void main(String[] args) {
// TODO Auto-generated method stub
int n=args.length;
int[] a=new int[n];
for(int i=0;i<n;i++)
a[i]=Integer.parseInt(args[i]);
Arrays.sort(a);
for(int i=0;i<n;i++)
System.out.print(a[i]+" ");
}
}
|
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
public class Atomic {
private AtomicInteger count = new AtomicInteger(0);
public int incrementAndGet() {
return count.incrementAndGet();
}
public int getCount() {
return count.get();
}
}
class AtomicIntegerExample {
public static void main(String[] args) throws InterruptedException {
ExecutorService executorService = Executors.newFixedThreadPool(2);
Atomic atomicCounter = new Atomic();
for(int i = 0; i < 2000; i++) {
executorService.submit(() -> atomicCounter.incrementAndGet());
}
executorService.shutdown();
executorService.awaitTermination(60, TimeUnit.SECONDS);
System.out.println("Final Count is : " + atomicCounter.getCount());
}
}
|
package com.leo_sanchez.itunestopalbums.Activities.Main;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import com.leo_sanchez.itunestopalbums.Activities.Album.AlbumActivity;
import com.leo_sanchez.itunestopalbums.Activities.DownloadJsonActivity;
import com.leo_sanchez.itunestopalbums.Models.Album;
import com.leo_sanchez.itunestopalbums.R;
import java.util.ArrayList;
public class MainActivity extends DownloadJsonActivity {
ListFragment mListFragment;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startPreload();
}
@Override
protected void handleAlbumsInformation(ArrayList<Album> albums) {
mListFragment = ListFragment.newInstance(albums);
getSupportFragmentManager()
.beginTransaction()
.add(R.id.fragment_container, mListFragment)
.commit();
}
public void handleAlbumClick(View view) {
TextView albumId = (TextView) view.findViewById(R.id.albumId);
Intent intent = new Intent(getBaseContext(), AlbumActivity.class);
intent.putExtra("ALBUM_ID", albumId.getText());
startActivity(intent);
}
} |
package walnoot.dodgegame;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.g2d.ParticleEffect;
import com.badlogic.gdx.graphics.g2d.ParticleEffectPool;
import com.badlogic.gdx.graphics.g2d.ParticleEffectPool.PooledEffect;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.utils.Array;
public class ParticleHandler{
private boolean loaded;
private ParticleEffectPool pool;
private Array<PooledEffect> effects = new Array<PooledEffect>(8);
public void load(){
ParticleEffect shine = new ParticleEffect();
// shine.load(Gdx.files.internal("effects/shine.dat"), Util.ATLAS);
shine.loadEmitters(Gdx.files.internal("effects/shine.dat"));
shine.getEmitters().get(0).setSprite(Util.ATLAS.createSprite("Gameplay/dollarsign"));
//TODO: automate this
pool = new ParticleEffectPool(shine, 2, 8);
loaded = true;
}
public void addShineEffect(float x, float y){
PooledEffect effect = pool.obtain();
effect.setPosition(x, y);
effects.add(effect);
}
public void render(SpriteBatch batch){
for(int i = effects.size - 1; i >= 0; i--){
PooledEffect effect = effects.get(i);
effect.draw(batch, Gdx.graphics.getDeltaTime());
if(effect.isComplete()){
effect.free();
effects.removeIndex(i);
}
}
}
public void update(){
}
public boolean isLoaded(){
return loaded;
}
}
|
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class WelcomePanel extends JPanel{
public WelcomePanel() {
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
JLabel welcome = new JLabel("Welcome");
add(welcome, gbc);
gbc.gridx = 0;
gbc.gridy++;
BufferedImage bankjpg = null;
try
{
bankjpg = ImageIO.read(new File("bank.jpg"));
}
catch (IOException e1)
{
e1.printStackTrace();
}
JLabel lblHome = new JLabel(new ImageIcon(bankjpg));
add(lblHome, gbc);
}
}
|
package com.bloodl1nez.analytics.vk.service.analytics;
import com.bloodl1nez.analytics.vk.job.ProfileJobRunner;
import com.bloodl1nez.analytics.vk.model.entity.AnalyseProgress;
import com.bloodl1nez.analytics.vk.model.entity.User;
import com.bloodl1nez.analytics.vk.model.repository.ProgressRepository;
import com.bloodl1nez.analytics.vk.web.request.AnalyseSettings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class VkAnalyticsServiceImpl implements VkAnalyticsService {
private final ProgressRepository progressRepository;
private final ProfileJobRunner analyser;
@Autowired
public VkAnalyticsServiceImpl(
ProgressRepository progressRepository, ProfileJobRunner analyser) {
this.analyser = analyser;
this.progressRepository = progressRepository;
}
@Override
public AnalyseProgress analyse(User performer, User analyzed, AnalyseSettings settings, String token) {
AnalyseProgress progress = new AnalyseProgress();
progress.setPerformer(performer);
progress = progressRepository.save(progress);
analyser.run(performer, analyzed, settings, progress, token);
return progress;
}
}
|
package com.isteel.myfaceit.ui.players;
import android.content.Context;
import androidx.recyclerview.widget.LinearLayoutManager;
import dagger.Module;
import dagger.Provides;
@Module
public class PlayerModule {
/*@Provides
PlayerAdapter providePlayerAdapter() {
return new PlayerAdapter(new ArrayList<>());
}
*/
@Provides
LinearLayoutManager provideLinearLayoutManager(Context context) {
return new LinearLayoutManager(context);
}
}
|
package com.example.qunxin.erp.activity;
import android.app.Dialog;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import com.alibaba.fastjson.JSON;
import com.example.qunxin.erp.R;
import com.example.qunxin.erp.UserBaseDatus;
import com.example.qunxin.erp.modle.ShangpinBaseDatus;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import swipedelete.utils.CommonAdapter;
import swipedelete.utils.ViewHolder;
public class AddjinhuoYixuanshangpinActivity extends AppCompatActivity implements View.OnClickListener {
View backBtn;
View editBtn;
TextView cangkuText;
View shangpinText;
ListView listView;
Button finishBtn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_addjinhuo_yixuanshangpin);
initView();
}
String dateList;
String depot;
String depotName;
String supplier;
String supplierName;
void initView(){
backBtn=findViewById(R.id.back);
editBtn=findViewById(R.id.edit_pen);
cangkuText=findViewById(R.id.cangku);
shangpinText=findViewById(R.id.shangpin);
listView=findViewById(R.id.listview);
finishBtn=findViewById(R.id.finish);
backBtn.setOnClickListener(this);
editBtn.setOnClickListener(this);
cangkuText.setOnClickListener(this);
shangpinText.setOnClickListener(this);
finishBtn.setOnClickListener(this);
Intent intent=getIntent();
dateList=intent.getStringExtra("dateList");
depotName=intent.getStringExtra("depotName");
depot=intent.getStringExtra("depot");
supplier=intent.getStringExtra("supplier");
supplierName=intent.getStringExtra("supplierName");
cangkuText.setText(depotName);
jsonParse();
loadView();
TextChange();
}
List<ShangpinBaseDatus> lists=new ArrayList<>();
void jsonParse(){
if("".equals(dateList)){
lists.clear();
return;
}
try {
JSONArray jsonArray=new JSONArray(dateList);
for (int i=0;i<jsonArray.length();i++){
JSONObject jsonObject=jsonArray.getJSONObject(i);
String proName=jsonObject.getString("proName");
String price=jsonObject.getString("price");
String proId=jsonObject.getString("proId");
String norms=jsonObject.getString("norms");
String property=jsonObject.getString("property");
String remarks=jsonObject.getString("remarks");
String total=jsonObject.getString("total");
String totalAmount=jsonObject.getString("totalAmount");
String unit=jsonObject.getString("unit");
ShangpinBaseDatus datus = new ShangpinBaseDatus();
datus.setPrice(Float.parseFloat(price));
datus.setProName(proName);
datus.setProId(proId);
datus.setNorms(norms);
datus.setProperty(property);
datus.setRemarks(remarks);
datus.setTotal(Integer.parseInt(total));
datus.setTotalAmount(Float.parseFloat(totalAmount));
datus.setUnit(unit);
datus.setImgRes(R.mipmap.shop_icon);
lists.add(datus);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
String jsonToString() {
StringBuffer buffer=new StringBuffer();
for (int i=0;i<lists.size();i++){
JSONObject jsonObject=new JSONObject();
try {
if(lists.get(i).getTotal()==0) break;
jsonObject.put("norms",lists.get(i).getNorms());
jsonObject.put("property",lists.get(i).getProperty());
jsonObject.put("price",lists.get(i).getPrice());
jsonObject.put("proId",lists.get(i).getProId());
jsonObject.put("proName",lists.get(i).getProName());
jsonObject.put("remarks",lists.get(i).getRemarks());
jsonObject.put("total",lists.get(i).getTotal());
jsonObject.put("totalAmount",lists.get(i).getTotalAmount());
jsonObject.put("unit",lists.get(i).getUnit());
jsonObject.put("proNo",lists.get(i).getProNo());
String content=String.valueOf(jsonObject);
buffer.append(content).append(",");
} catch (JSONException e) {
e.printStackTrace();
}
}
String s= buffer.toString();
if("".equals(s)){
return "";
}
return "["+s.substring(0,s.length()-1)+"]";
}
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.back:
finish();
break;
case R.id.edit_pen:
Intent intent1=new Intent(AddjinhuoYixuanshangpinActivity.this,EditYixuanshangpinActivity.class);
dateList=jsonToString();
intent1.putExtra("dateList",dateList);
startActivityForResult(intent1,1);
break;
case R.id.cangku:
show();
break;
case R.id.shangpin:
Intent intent=new Intent(AddjinhuoYixuanshangpinActivity.this,AddJinhuodanXuanzeshangpinActivity.class);
intent.putExtra("supplier",supplier);
intent.putExtra("depot",depot);
intent.putExtra("depotName",depotName);
intent.putExtra("supplierName",supplierName);
intent.putExtra("isAuto",true);
startActivityForResult(intent,1);
break;
case R.id.finish:
finishBtn();
break;
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode){
case 1:
if(resultCode==1){
lists.clear();
dateList=data.getStringExtra("lists");
jsonParse();
loadView();
}
if(resultCode==2){
lists.clear();
dateList=data.getStringExtra("dateList");
jsonParse();
loadView();
TextChange();
}
break;
}
}
Dialog dialog;
public void show(){
dialog = new Dialog(this,R.style.ActionSheetDialogStyle);
//填充对话框的布局
LinearLayout inflate = (LinearLayout) LayoutInflater.from(this).inflate(R.layout.bottom_cangku, null);
//初始化控件
Button closeBtn=inflate.findViewById(R.id.closeBtn);
closeBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dialog.dismiss();
}
});
final ListView listView=inflate.findViewById(R.id.listview);
//宽高
listView.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
//设置Padding
listView.setPadding(0,00,0,0);
//将布局设置给Dialog
dialog.setContentView(inflate);
Window dialogWindow = dialog.getWindow();
//设置Dialog从窗体底部弹出
dialogWindow.setGravity( Gravity.BOTTOM);
//获得窗体的属性
WindowManager.LayoutParams lp = dialogWindow.getAttributes();
//lp.y = 20;//设置Dialog距离底部的距离
// 将属性设置给窗体
lp.x = 0; // 新位置X坐标
lp.y = 0; // 新位置Y坐标
lp.width = (int) getResources().getDisplayMetrics().widthPixels; // 宽度
inflate.measure(0, 0);
//lp.height = inflate.getMeasuredHeight();
lp.alpha = 9f; // 透明度
dialogWindow.setAttributes(lp);
dialog.show();//显示对话框
new Thread(new Runnable() {
@Override
public void run() {
loadModel(listView);
}
}).start();
}
List<Map<String, String>> listitem = new ArrayList<Map<String, String>>();
void loadModel(final ListView listView){
listitem.clear();
final String contentTypeList = "application/json";
final String url= UserBaseDatus.getInstance().url+"api/app/depot/pageList";
Map<String, String> jsonMap = new HashMap<>();
jsonMap.put("pageNum", "1");
jsonMap.put("pageSize", "10");
jsonMap.put("signa", UserBaseDatus.getInstance().getSign());
String jsonString = JSON.toJSONString(jsonMap);
Map map=UserBaseDatus.getInstance().isSuccessPost(url, jsonString, contentTypeList);
if((boolean)(map.get("isSuccess"))){
JSONObject json=(JSONObject) map.get("json");
try {
JSONObject jsonData=json.getJSONObject("data");
JSONArray jsonArray=jsonData.getJSONArray("rows");
for (int i=0;i<jsonArray.length();i++){
JSONObject jsonObject=jsonArray.getJSONObject(i);
String name=jsonObject.getString("name");
String id=jsonObject.getString("id");
Map<String,String> map1=new HashMap<>();
map1.put("name",name);
map1.put("id",id);
listitem.add(map1);
}
runOnUiThread(new Runnable() {
@Override
public void run() {
loadBottomCangkuListView(listView);
}
});
} catch (JSONException e) {
e.printStackTrace();
}
}
}
void loadBottomCangkuListView(final ListView listView) {
SimpleAdapter myAdapter = new SimpleAdapter(getApplicationContext(),listitem,
R.layout.item_bottom_cangku,new String[]{"name"},
new int[]{R.id.name});
listView.setAdapter(myAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
dialog.dismiss();
cangkuText.setText(listitem.get(position).get("name"));
if(listitem.get(position).get("name")!=depotName){
depotName=listitem.get(position).get("name");
depot=listitem.get(position).get("id");
lists.clear();
loadView();
TextChange();
}
}
});
}
void loadView(){
listView.setAdapter(new CommonAdapter<ShangpinBaseDatus>(AddjinhuoYixuanshangpinActivity.this,lists, R.layout.item_yixuanshangpin) {
@Override
public void convert(final ViewHolder holder, ShangpinBaseDatus shangpinDatus,final int position, View convertView) {
holder.setText(R.id.name,shangpinDatus.getProName());
holder.setText(R.id.totalAmount,shangpinDatus.getTotalAmount()+"");
holder.setText(R.id.unit,shangpinDatus.getUnit());
holder.setText(R.id.count,shangpinDatus.getTotal()+"");
holder.setText(R.id.detail,"¥"+shangpinDatus.getPrice()+"*"+shangpinDatus.getTotal()+shangpinDatus.getUnit());
holder.setOnClickListener(R.id.ll_content, new View.OnClickListener() {
@Override
public void onClick(View v) {
}
});
final int[] amount = {shangpinDatus.getTotal()};
final TextView etAmount=holder.getView(R.id.count);
holder.setOnClickListener(R.id.btnIncrease, new View.OnClickListener() {
@Override
public void onClick(View v) {
amount[0]++;
etAmount.setText(amount[0]+"");
ShangpinBaseDatus datus=lists.get(position);
datus.setTotal(Integer.parseInt(etAmount.getText().toString()));
datus.setTotalAmount(datus.getPrice()*datus.getTotal());
holder.setText(R.id.totalAmount,datus.getTotalAmount()+"");
holder.setText(R.id.detail,"¥"+datus.getPrice()+"*"+datus.getTotal()+datus.getUnit());
TextChange();
}
});
holder.setOnClickListener(R.id.btnDecrease, new View.OnClickListener() {
@Override
public void onClick(View v) {
if(amount[0] <=0){
return;
}
amount[0]--;
etAmount.setText(amount[0]+"");
ShangpinBaseDatus datus=lists.get(position);
datus.setTotal(Integer.parseInt(etAmount.getText().toString()));
datus.setTotalAmount(datus.getTotal()*datus.getPrice());
holder.setText(R.id.totalAmount,datus.getTotalAmount()+"");
holder.setText(R.id.detail,"¥"+datus.getPrice()+"*"+datus.getTotal()+datus.getUnit());
TextChange();
}
});
}
});
}
int getTotal(){
int total=0;
for(int i=0;i<lists.size();i++){
total+=lists.get(i).getTotal();
}
return total;
}
float getTotalAmount(){
int totalAmount=0;
for(int i=0;i<lists.size();i++){
totalAmount+=lists.get(i).getTotal()*lists.get(i).getPrice();
}
return totalAmount;
}
void TextChange(){
int size=lists.size();
int total=getTotal();
float totalAmount=getTotalAmount();
String s="结算({0}种共{1}件,¥{2})";
finishBtn.setText(MessageFormat.format(s,size,total,totalAmount));
}
@Override
protected void onResume() {
super.onResume();
TextChange();
}
void finishBtn(){
if(lists.size()==0){
Toast.makeText(this, "请添加商品", Toast.LENGTH_SHORT).show();
String s="结算({0}种共{1}件,¥{2})";
finishBtn.setText(MessageFormat.format(s,lists.size(),0,0));
return;
}
if(getTotal()==0){
Toast.makeText(this, "请添加商品", Toast.LENGTH_SHORT).show();
String s="结算({0}种共{1}件,¥{2})";
finishBtn.setText(MessageFormat.format(s,0,0,0));
return;
}
Intent intent=new Intent();
dateList=jsonToString();
intent.putExtra("dateList",dateList);
intent.putExtra("count",getTotal());
intent.putExtra("totalAmount",getTotalAmount());
intent.putExtra("depot",depot);
intent.putExtra("depotName",depotName);
setResult(3,intent);
finish();
}
}
|
package com.example.logs.controller;
import com.alibaba.fastjson.JSON;
import com.example.logs.mapper.ReportMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;
@Slf4j
@Controller
@RequestMapping("/chart")
public class ChartsController extends BaseController{
@Autowired
private ReportMapper reportMapper;
@RequestMapping("/line")
public String line(HttpServletResponse response , Model model) throws IOException {
log.debug("-------------画折线图------------");
return "pages/echarts/line";
}
@RequestMapping("/bar")
public String bar(Model model, HttpServletRequest request, HttpServletResponse response) throws IOException {
log.debug("-------------画柱状图------------");
return "pages/echarts/bar";
}
@RequestMapping("/pie")
public String pie(Model model, HttpServletRequest request, HttpServletResponse response) throws IOException {
log.debug("-------------画饼图------------");
return "pages/echarts/pie";
}
@GetMapping("/getLine")
@ResponseBody
public String getLine() {
List<Map<String, Object>> result = reportMapper.getChartLine();
Map<String, List<Map<String, Object>>> groupBy = result.stream().collect(Collectors.groupingBy(e -> e.get("time").toString()));
List<Map<String, Object>> project = reportMapper.getProjectGroup();
List title = new ArrayList<>();
for (int i=0 ;i<project.size();i++){
if(i>4){
break;
}
title.add(project.get(i).get("name"));
}
System.err.println("groupBy:"+groupBy);
List dateList = new ArrayList();
groupBy.forEach((k,v)-> {
dateList.add(k);
});
Collections.sort(dateList);
List dataList = new ArrayList();
for (int j= 0 ;j<title.size(); j++){
List<Integer> res = new ArrayList<>();
for (int k=0;k<dateList.size();k++){
List<Map<String, Object>> d = groupBy.get(dateList.get(k));
if (d==null||d.size()==0){
break;
}
boolean f = false;
for (int l=0 ;l<d.size();l++){
if (d.get(l).get("projectName").equals(title.get(j).toString())){
Long t = (Long) d.get(l).get("total");
res.add(t.intValue());
f=true;
break;
}
}
if (!f){
res.add(0);
}
}
Map<String, Object> map = new HashMap<>();
map.put("name",title.get(j).toString());
map.put("type","line");
map.put("stack","总量");
map.put("data",res);
dataList.add(map);
}
Map map = new HashMap();
map.put("title",title);
map.put("date",dateList);
map.put("data",dataList);
return JSON.toJSONString(map);
}
@GetMapping("/getBar")
@ResponseBody
public String getBar() {
List<Map<String, Object>> result = reportMapper.getChartBar();
Map<String, List<Map<String, Object>>> groupBy = result.stream().collect(Collectors.groupingBy(e -> e.get("name").toString()));
List dimensions = new ArrayList();
List source = new ArrayList();
List<Map<String, Object>> fisrt = groupBy.get(getFirstOrNull(groupBy));
dimensions.add("product");
fisrt.stream().forEach(o->{
if(fisrt.indexOf(o)>2){
return;
}
dimensions.add(o.get("version"));
});
groupBy.forEach((k,v)->{
LinkedHashMap data = new LinkedHashMap();
data.put("product",k);
for (int i=1;i<dimensions.size(); i++){
String ver = dimensions.get(i).toString();
boolean f = false;
for (int j = 0 ;j<v.size() ; j++){
String s = v.get(j).get("version").toString();
if (ver.equals(s)){
data.put(ver,v.get(j).get("total"));
f = true;
break;
}
}
if(!f){
data.put(ver,0);
}
}
source.add(data);
System.out.println(data);
});
LinkedHashMap map = new LinkedHashMap(16);
map.put("dimensions",dimensions);
map.put("source",source);
return JSON.toJSONString(map);
}
@GetMapping("/getPie")
@ResponseBody
public String getPie() {
List<Map<String, Object>> result = reportMapper.getChartPie();
Map map = new HashMap();
List name = new ArrayList();
result.stream().forEach(o->{
name.add(o.get("name"));
});
map.put("name",name);
map.put("data",result);
return JSON.toJSONString(map);
}
/**
* 获取map中第一个数据值
*
* @param <K> Key的类型
* @param <V> Value的类型
* @param map 数据源
* @return 返回的值
*/
public static <K, V> K getFirstOrNull(Map<K, V> map) {
K obj = null;
for (Map.Entry<K, V> entry : map.entrySet()) {
obj = entry.getKey();
if (obj != null) {
break;
}
}
return obj;
}
}
|
package ma.jit.service;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.stream.Stream;
import javax.transaction.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import ma.jit.dao.ICategorieRepository;
import ma.jit.dao.ICinemaRepository;
import ma.jit.dao.IFilmRepository;
import ma.jit.dao.IPlaceRepository;
import ma.jit.dao.IProjectionRepository;
import ma.jit.dao.ISalleRepository;
import ma.jit.dao.ISeanceRepository;
import ma.jit.dao.ITicketRepository;
import ma.jit.dao.IVilleRepository;
import ma.jit.entites.Categorie;
import ma.jit.entites.Cinema;
import ma.jit.entites.Film;
import ma.jit.entites.Place;
import ma.jit.entites.Projection;
import ma.jit.entites.Salle;
import ma.jit.entites.Seance;
import ma.jit.entites.Ticket;
import ma.jit.entites.Ville;
@Service
@Transactional
public class CinemaInitServiceImpl implements ICinemaInitService {
@Autowired
private IVilleRepository villeRepo;
@Autowired
private ICinemaRepository cinemaRepo;
@Autowired
private ISalleRepository salleRepo;
@Autowired
private IPlaceRepository placeRepo;
@Autowired
private ISeanceRepository seanceRepo;
@Autowired
private IFilmRepository filmRepo;
@Autowired
private IProjectionRepository projectionRepo;
@Autowired
private ICategorieRepository categoriesRepo;
@Autowired
private ITicketRepository ticketRepo;
@Override
public void initVilles() {
Stream.of("Casablanca","Marrakech","Rabat","Tanger").forEach(v->{
Ville ville = new Ville();
ville.setName(v);
villeRepo.save(ville);
});
}
@Override
public void initCinemas() {
villeRepo.findAll().forEach(v->{
Stream.of("Megarama","IMax","FOUNOUN","CHAHRAZAD","DAOULIZ")
.forEach(nameCinema->{
Cinema cinema = new Cinema();
cinema.setName(nameCinema);
cinema.setVille(v);
cinema.setNombreSalle(3+(int)(Math.random()*7));
cinemaRepo.save(cinema);
});
});
}
@Override
public void initSalles() {
cinemaRepo.findAll().forEach(cinema ->{
for(int i=0;i<cinema.getNombreSalle();i++) {
Salle salle = new Salle();
salle.setName("Salle "+(i+1));
salle.setCinema(cinema);
salle.setNombrePlace(15+(int)(Math.random()*20));
salleRepo.save(salle);
}
});
}
@Override
public void initPlace() {
salleRepo.findAll().forEach(salle ->{
for(int i=0;i<salle.getNombrePlace();i++) {
Place place= new Place();
place.setNumero(i+1);
place.setSalle(salle);
placeRepo.save(place);
}
});
}
@Override
public void initSeances() {
DateFormat dateFormat=new SimpleDateFormat("HH:mm");
Stream.of("12:00","15:00","17:00","19:00","21:00").forEach(s->{
Seance seance = new Seance();
try {
seance.setHeureDebut(dateFormat.parse(s));
seanceRepo.save(seance);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
});
}
@Override
public void initCategories() {
Stream.of("Histoire","Action","Drama","Fiction").forEach(cat->{
Categorie categorie= new Categorie();
categorie.setName(cat);
categoriesRepo.save(categorie);
});
}
@Override
public void initFilms() {
double[] durees = new double [] {1,1.5,2,2.5,3};
List<Categorie> categories = categoriesRepo.findAll();
Stream.of("12Homme En Colere","Forrest Gump","Green Book","Green Mile","Le Parrain","Le Seigneur Des Anneaux")
.forEach(f->{
Film film = new Film();
film.setTitre(f);
film.setDuree(durees[new Random().nextInt(durees.length)]);
film.setPhoto(f.replaceAll(" ", "")+".jpg");
film.setCategorie(categories.get(new Random().nextInt(categories.size())));
filmRepo.save(film);
});
}
@Override
public void initProjections() {
double[] prices = new double [] {30,50,60,70,90,100};
List<Film> films = filmRepo.findAll();
villeRepo.findAll().forEach(ville->{
ville.getCinema().forEach(cinema->{
cinema.getSalles().forEach(salles->{
int index = new Random().nextInt(films.size());
Film film= films.get(index);
seanceRepo.findAll().forEach(seance->{
Projection projection = new Projection();
projection.setDateProjection(new Date());
projection.setFilm(film);
projection.setPrix(prices[new Random().nextInt(prices.length)]);
projection.setSalle(salles);
projection.setSeance(seance);
projectionRepo.save(projection);
});
});
});
});
}
@Override
public void initTickets() {
projectionRepo.findAll().forEach(p->{
p.getSalle().getPlaces().forEach(place->{
Ticket ticket = new Ticket();
ticket.setPlace(place);
ticket.setPrix(p.getPrix());
ticket.setProjection(p);
ticket.setReserve(false);
ticketRepo.save(ticket);
});
});
}
}
|
package pers.mrxiexie.card;
import java.io.File;
import java.io.IOException;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
/**
* Created by Cocas on 2017/8/18.
*/
public class RequestUtil {
private static OkHttpClient okHttpClient;
static {
okHttpClient = new OkHttpClient.Builder()
.connectTimeout(60, TimeUnit.SECONDS)
.writeTimeout(60, TimeUnit.SECONDS)
.readTimeout(60, TimeUnit.SECONDS)
.build();
}
/**
* 同步 GET 请求,结果再 return 处返回
*
* @param URL
* @param params
* @param header
* @return
* @throws IOException
*/
public static String GET_SYN(String URL, Map<String, String> params, Map<String, String> header) throws IOException {
Request.Builder builder = new Request.Builder();
if (header != null && !header.isEmpty()) {
Set<Map.Entry<String, String>> entries = header.entrySet();
for (Map.Entry<String, String> entry : entries) {
builder.addHeader(entry.getKey(), entry.getValue());
}
}
URL = setGETParam(params, URL);
Request request = builder.get().url(URL).build();
return dealSYNRespond(request);
}
/**
* 同步 POST 请求,结果再 return 中返回
*
* @param URL
* @param params
* @param header
* @return
* @throws IOException
*/
public static String POST_SYN(String URL, Map<String, String> params, Map<String, String> header) throws IOException {
Request.Builder builder = new Request.Builder();
if (header != null && !header.isEmpty()) {
Set<Map.Entry<String, String>> entries = header.entrySet();
for (Map.Entry<String, String> entry : entries) {
builder.addHeader(entry.getKey(), entry.getValue());
}
}
FormBody.Builder formBodyBuilder = new FormBody.Builder();
if (params != null && !params.isEmpty()) {
Set<Map.Entry<String, String>> entries = params.entrySet();
for (Map.Entry<String, String> entry : entries) {
formBodyBuilder.add(entry.getKey(), entry.getValue());
}
}
Request request = builder.post(formBodyBuilder.build()).url(URL).build();
return dealSYNRespond(request);
}
/**
* 发送同步 JSON POST 请求
* @param URL
* @param json
* @return
* @throws IOException
*/
public static String POST_JSON_SYN(String URL, String json) throws IOException {
MediaType mediaType = MediaType.parse("application/json");
Request.Builder builder = new Request.Builder();
RequestBody requestBody = RequestBody.create(mediaType, json);
Request request = builder.url(URL).post(requestBody).build();
return dealSYNRespond(request);
}
private static String setGETParam(Map<String, String> params, String URL) {
if (params != null && !params.isEmpty()) {
StringBuilder SB = new StringBuilder("?");
Set<Map.Entry<String, String>> entries = params.entrySet();
for (Map.Entry<String, String> entry : entries) {
SB.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
}
SB.deleteCharAt(SB.length() - 1);
URL += SB.toString();
}
return URL;
}
/**
* Get请求
*
* @param URL 请求地址
* @param params 请求参数
* @param header 请求头
* @param requestCallBack 请求回调
*/
public static void GET(String URL, Map<String, String> params, Map<String, String> header, final RequestCallBack requestCallBack) {
Request.Builder builder = new Request.Builder();
if (header != null && !header.isEmpty()) {
Set<Map.Entry<String, String>> entries = header.entrySet();
for (Map.Entry<String, String> entry : entries) {
builder.addHeader(entry.getKey(), entry.getValue());
}
}
URL = setGETParam(params, URL);
Request request = builder.get().url(URL).build();
dealRespond(request, requestCallBack);
}
/**
* Post请求
*
* @param URL 请求地址
* @param params 请求参数
* @param header 请求头
* @param requestCallBack 请求回调
*/
public static void POST(String URL, Map<String, String> params, Map<String, String> header, RequestCallBack requestCallBack) {
Request.Builder builder = new Request.Builder();
if (header != null && !header.isEmpty()) {
Set<Map.Entry<String, String>> entries = header.entrySet();
for (Map.Entry<String, String> entry : entries) {
builder.addHeader(entry.getKey(), entry.getValue());
}
}
FormBody.Builder formBodyBuilder = new FormBody.Builder();
if (params != null && !params.isEmpty()) {
Set<Map.Entry<String, String>> entries = params.entrySet();
for (Map.Entry<String, String> entry : entries) {
formBodyBuilder.add(entry.getKey(), entry.getValue());
}
}
Request request = builder.post(formBodyBuilder.build()).url(URL).build();
dealRespond(request, requestCallBack);
}
/**
* 上传文件
*
* @param URL 请求地址
* @param params 上传的文件或字符串
* @param header 请求头
* @param fileName 文件名
* @param requestCallBack 请求回调
*/
public static void uploadFile(String URL,
Map<String, Object> params,
Map<String, String> header,
String fileName,
RequestCallBack requestCallBack) {
Request.Builder requestBuilder = new Request.Builder();
MultipartBody.Builder builder = new MultipartBody.Builder();
builder.setType(MultipartBody.FORM);
if (params != null && !params.isEmpty()) {
Set<Map.Entry<String, Object>> entries = params.entrySet();
for (Map.Entry<String, Object> entry : entries) {
String key = entry.getKey();
Object value = entry.getValue();
if (value instanceof File) {
File file = (File) value;
builder.addFormDataPart(key,
null == fileName ? file.getName() : fileName,
MultipartBody.create(MediaType.parse("application/octet-stream"), file));
} else {
builder.addFormDataPart(key, value + "");
}
}
}
MultipartBody multipartBody = builder.build();
Request request = requestBuilder.url(URL).post(multipartBody).build();
dealRespond(request, requestCallBack);
}
public static String uploadFile_SYN(String URL,
Map<String, Object> params,
Map<String, String> header,
String fileName) throws IOException {
Request.Builder requestBuilder = new Request.Builder();
MultipartBody.Builder builder = new MultipartBody.Builder();
builder.setType(MultipartBody.FORM);
if (params != null && !params.isEmpty()) {
Set<Map.Entry<String, Object>> entries = params.entrySet();
for (Map.Entry<String, Object> entry : entries) {
String key = entry.getKey();
Object value = entry.getValue();
if (value instanceof File) {
File file = (File) value;
builder.addFormDataPart(key,
null == fileName ? file.getName() : fileName,
MultipartBody.create(MediaType.parse("application/octet-stream"), file));
} else {
builder.addFormDataPart(key, value + "");
}
}
}
MultipartBody multipartBody = builder.build();
Request request = requestBuilder.url(URL).post(multipartBody).build();
return dealSYNRespond(request);
}
/**
* @param request
* @return
* @throws IOException
*/
private static String dealSYNRespond(Request request) throws IOException {
Response response = okHttpClient.newCall(request).execute();
if (response.isSuccessful()) {
return response.body().string();
} else {
return "服务器异常";
}
}
/**
* 处理响应
*
* @param request
* @param requestCallBack
*/
private static void dealRespond(final Request request, final RequestCallBack requestCallBack) {
okHttpClient.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, final IOException e) {
requestCallBack.error("服务器异常");
}
@Override
public void onResponse(final Call call, final Response response) throws IOException {
final String result = response.body().string();
if (!response.isSuccessful()) {
requestCallBack.error("服务器异常");
} else {
requestCallBack.success(result, "ResponseResult : " + result);
}
}
});
}
public interface RequestCallBack {
void success(String data, String msg) throws IOException;
void error(String error);
}
}
|
package ng.mobilea.airvoucher.utilities;
import android.content.Context;
import android.telephony.TelephonyManager;
import android.util.Patterns;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.math.RoundingMode;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import ng.mobilea.airvoucher.R;
/**
* Created by Hp on 6/8/2017.
*/
public class DataFactory {
private static final String PATTERN = "(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*[!@#$%^&+=])(?=\\S+$).{8,}";
public static final String objectToString(Object object) {
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
.configure(JsonParser.Feature.ALLOW_UNQUOTED_CONTROL_CHARS, true);
try {
String jsonData = mapper.writeValueAsString(object);
return jsonData;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public static String formatDouble(double value) {
NumberFormat format = DecimalFormat.getInstance();
format.setRoundingMode(RoundingMode.FLOOR);
format.setMinimumFractionDigits(0);
format.setMaximumFractionDigits(3);
return format.format(value).replace(",", "");
}
public static final String[] splitString(String input, String criteria) {
String[] outPut = input.split("\\" + criteria);
return outPut;
}
public static final String formatDate(Date date) throws Exception {
DateFormat dFormat = new SimpleDateFormat("dd/MM/yyy", Locale.getDefault());
return dFormat.format(date);
}
public static final String formatDateTime(Date date) throws Exception {
DateFormat dFormat = new SimpleDateFormat("yyy-MM-dd HH:mm:ss", Locale.getDefault());
return dFormat.format(date);
}
public static final Date parseDateTime(String date) throws Exception {
DateFormat dFormat = new SimpleDateFormat("yyy-MM-dd HH:mm:ss", Locale.getDefault());
return dFormat.parse(date);
}
public static final Date parseStringDateTime(String date) throws Exception {
DateFormat dFormat = new SimpleDateFormat("yyy-MM-dd HH:mm:ss", Locale.getDefault());
return dFormat.parse(date);
}
public static final List<Object> stringToObjectList(Class className, String jsonString) {
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
.configure(JsonParser.Feature.ALLOW_UNQUOTED_CONTROL_CHARS, true);
try {
return mapper.readValue(jsonString, mapper.getTypeFactory().constructCollectionType(List.class, className));
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static final Object stringToObject(Class className, String jsonString) {
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
.configure(JsonParser.Feature.ALLOW_UNQUOTED_CONTROL_CHARS, true);
try {
return mapper.readValue(jsonString, className);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public static boolean isValidEmail(String target) {
return target != null && Patterns.EMAIL_ADDRESS.matcher(target).matches();
}
public static boolean isValidPhone(String target) {
return target != null && Patterns.PHONE.matcher(target).matches();
}
public static String formatPhone(String phone, Context context) throws Exception {
String countryCode = getCountryZipCode(context);
if (countryCode.equals("250")) {
String firstDigit = phone.substring(0, 3);
if (phone.length() >= 12 && firstDigit.equals("250"))
return phone;
else if (phone.length() <= 10 && !firstDigit.equals("250")) {
if (phone.substring(0, 1).contains("0"))
return "25" + phone;
else
return "250" + phone;
} else
throw new Exception("Invalid phone");
} else {
String inPutCode = phone.substring(0, countryCode.length() - 1);
if (!countryCode.equals(inPutCode)) {
throw new Exception("prefix " + countryCode);
}
if (isValidPhone(phone))
return phone;
else
throw new Exception("Invalid phone");
}
}
public static String getCountryZipCode(Context context) {
String countryID = "";
String countryZipCode = "";
TelephonyManager manager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
//getNetworkCountryIso
countryID = manager.getNetworkCountryIso().toUpperCase();
String[] rl = context.getResources().getStringArray(R.array.CountryCodes);
for (int i = 0; i < rl.length; i++) {
String[] g = rl[i].split(",");
if (g[1].trim().equals(countryID.trim())) {
countryZipCode = g[0];
break;
}
}
return countryZipCode;
}
public static boolean isStrongPassword(String password)
{
return password.matches(PATTERN);
}
}
|
package com.bofsoft.laio.customerservice.Activity.Select;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import com.bofsoft.laio.customerservice.Activity.BaseVehicleActivity;
import com.bofsoft.laio.customerservice.Adapter.IdTypeAdapter;
import com.bofsoft.laio.customerservice.Config.Config;
import com.bofsoft.laio.customerservice.Config.ConfigallCostomerService;
import com.bofsoft.laio.customerservice.DataClass.db.IdTypeData;
import com.bofsoft.laio.customerservice.Database.DBCallBack;
import com.bofsoft.laio.customerservice.Database.PublicDBManager;
import com.bofsoft.laio.customerservice.Database.TableManager;
import com.bofsoft.laio.customerservice.R;
import com.bofsoft.sdk.widget.base.Event;
import java.util.List;
/**
* 身份证明类型
*
* @author admin
*/
public class SelectIdTypeActivity extends BaseVehicleActivity {
private ListView mList;
private List<IdTypeData> list;
private IdTypeAdapter mAdapter;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState, true);
setContentView(R.layout.activity_text_single_list);
initView();
getList();
}
public void initView() {
mList = (ListView) findViewById(R.id.list_text_single);
mAdapter = new IdTypeAdapter(this);
mList.setAdapter(mAdapter);
mList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent();
intent.putExtra(ConfigallCostomerService.Result_Key, mAdapter.getItem(position));
setResult(RESULT_OK, intent);
finish();
}
});
}
public void getList() {
// DBAsyncOperation.execute(new DBCallBack<Object>() {
// @Override
// public Object doThingInBack() {
// list =
// PublicDBManager.getIntance(SelectIdTypeActivity.this).queryDataList(IdTypeData.class,
// TableManager.Type_IdType, null, null, null, null, null);
// return null;
// }
//
// @Override
// public void onCallBack(Object result) {
// mAdapter.setmList(list);
// }
// });
PublicDBManager.getInstance(this).queryList(IdTypeData.class, TableManager.Laio_IdType,
new DBCallBack<IdTypeData>() {
@Override
public void onCallBackList(List<IdTypeData> list) {
mAdapter.setmList(list);
}
});
}
@Override
protected void setTitleFunc() {
setTitle("身份证类型");
}
@Override
protected void setActionBarButtonFunc() {
addLeftButton(Config.abBack.clone());
}
@Override
protected void actionBarButtonCallBack(int id, View v, Event e) {
switch (id) {
case 0:
setResult(RESULT_CANCELED);
finish();
break;
}
}
}
|
package cn.kim.common.shiro.cache;
import org.apache.shiro.cache.CacheException;
import java.util.Collection;
import java.util.Set;
/**
* Created by 余庚鑫 on 2019/12/3
* 重写cache
*/
public interface Cache<K, V> extends org.apache.shiro.cache.Cache {
/**
* redission 模糊搜索
*
* @param keyPattern
* @return
*/
Collection<V> values(String keyPattern);
Collection<V> values(String keyPattern, int count);
}
|
package com.tandon.tanay.locationtracker.constants;
/**
* Created by tanaytandon on 18/09/17.
*/
public interface DbConfig {
String NAME = "LocationTracker";
}
|
/**
* https://www.hackerearth.com/practice/basic-programming/bit-manipulation/basics-of-bit-manipulation/practice-problems/algorithm/monk-and-binary-array-1/
* #bit-manipulation
*/
/*
0 1 2 3 4 5 6 7 8 9
1 1 0 0 1 1 0 0 0 1
preSum 1 2 2 2 3 4 4 4 4 5
L R
---------------
-----
0 1 1 1 2 3 3 3 3 4
------------
[L, R] preSum[R] - preSum[L - 1] - > XOR = 1
0 1 2 3 4
oneList: 0 1 4 5 9
-> flip bit
0 1 2 3 4 5 6 7 8 9
1 1 0 0 1 1 0 0 0 1
|
*/
import java.util.Scanner;
class MonkBinaryArray {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int sz = n + 1;
int[] arr = new int[sz];
int[] oneArr = new int[sz];
int val;
for (int i = 1; i < sz; i++) {
val = sc.nextInt();
arr[i] = val;
}
int ans = 0;
for (int i = 1; i < arr.length; i++) {
// attempt to flip bit
arr[i] ^= 1;
// calculate
int sum = 0;
// for (int j=1; j < arr.length; j++) {
// if (arr[j] == 1) {
// oneArr[j] = oneArr[j-1] + 1;
// } else {
// oneArr[j] = oneArr[j-1];
// }
// }
int numEven = 1;
int numOdd = 0;
int tot = 0;
for (int r = 1; r < oneArr.length; r++) {
if (arr[r] == 1) {
tot++;
}
if ((tot & 1) == 1) { // odd
sum += numEven;
numOdd++;
} else {
sum += numOdd;
numEven++;
}
}
if (ans < sum) {
ans = sum;
}
// reset
arr[i] ^= 1;
}
System.out.println(ans);
// Complexity:
// Space: O(N)
// Time: O(N^2)
// for (int i=1; i < arr.length; i++) {
// // attempt to flip bit
// arr[i] ^= 1;
// // calculate
// int sum = 0;
// for (int j=1; j < arr.length; j++) {
// if (arr[j] == 1) {
// oneArr[j] = oneArr[j-1] + 1;
// } else {
// oneArr[j] = oneArr[j-1];
// }
// }
// int numEven = 1;
// int numOdd = 0;
// for (int r = 1; r < oneArr.length; r++) {
// if (oneArr[r] & 1 == 1) { // odd
// sum += numEven;
// numOdd++;
// }
// else {
// sum += numOdd;
// numEven++;
// }
// // for (int l = 1; l <= r; l++) {
// // if ((oneArr[r] - oneArr[l - 1]) & 1 == 1) {
// // sum += 1;
// // }
// // }
// }
// if (ans < sum) {
// ans = sum;
// }
// // reset
// arr[i] ^= 1;
// }
}
}
|
package com.xianzaishi.wms.tmscore.manage.impl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import com.xianzaishi.wms.common.exception.BizException;
import com.xianzaishi.wms.tmscore.dao.itf.IPickBasketDao;
import com.xianzaishi.wms.tmscore.manage.itf.IPickBasketManage;
import com.xianzaishi.wms.tmscore.vo.PickBasketQueryVO;
import com.xianzaishi.wms.tmscore.vo.PickBasketVO;
public class PickBasketManageImpl implements IPickBasketManage {
@Autowired
private IPickBasketDao pickBasketDao = null;
private void validate(PickBasketVO pickBasketVO) {
if (pickBasketVO.getBasketId() == null
|| pickBasketVO.getBasketId() <= 0) {
throw new BizException("basketID error:"
+ pickBasketVO.getBasketId());
}
if (pickBasketVO.getPickId() == null || pickBasketVO.getPickId() <= 0) {
throw new BizException("pickID error:" + pickBasketVO.getPickId());
}
}
private void validate(Long id) {
if (id == null || id <= 0) {
throw new BizException("ID error:" + id);
}
}
public IPickBasketDao getPickBasketDao() {
return pickBasketDao;
}
public void setPickBasketDao(IPickBasketDao pickBasketDao) {
this.pickBasketDao = pickBasketDao;
}
public Boolean addPickBasketVO(PickBasketVO pickBasketVO) {
validate(pickBasketVO);
pickBasketDao.addDO(pickBasketVO);
return true;
}
public List<PickBasketVO> queryPickBasketVOList(
PickBasketQueryVO pickBasketQueryVO) {
return pickBasketDao.queryDO(pickBasketQueryVO);
}
public PickBasketVO getPickBasketVOByID(Long id) {
return (PickBasketVO) pickBasketDao.getDOByID(id);
}
public Boolean modifyPickBasketVO(PickBasketVO pickBasketVO) {
return pickBasketDao.updateDO(pickBasketVO);
}
public Boolean deletePickBasketVOByID(Long id) {
return pickBasketDao.delDO(id);
}
}
|
package com.tuskiomi.TSSUS.graphics;
import org.newdawn.slick.Graphics;
public interface Lighting {
public void render(Graphics g);
}
|
package br.com.alura.loja;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.WebTarget;
import static org.junit.Assert.*;
import org.junit.Test;
public class ClienteTestProjeto {
@Test
public void testaQueAConexaoComOServidorFunciona() {
Client client = ClientBuilder.newClient();
WebTarget target = client.target("http://localhost:8080");
String conteudo = target.path("/projetos").request().get(String.class);
assertTrue(conteudo.contains("<nome>Minha loja</nome>"));
}
}
|
package com.tessoft.nearhere.fragments;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.tessoft.common.Constants;
import com.tessoft.domain.APIResponse;
import com.tessoft.domain.User;
import com.tessoft.domain.UserMessage;
import com.tessoft.nearhere.R;
import com.tessoft.nearhere.R.anim;
import com.tessoft.nearhere.R.id;
import com.tessoft.nearhere.activities.UserMessageActivity;
import com.tessoft.nearhere.adapters.MessageBoxListAdapter;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.type.TypeReference;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
public class MessageBoxFragment extends BaseListFragment {
MessageBoxListAdapter adapter = null;
RelativeLayout layoutFooter = null;
protected View fragmentRootView = null;
// TODO: Rename and change types and number of parameters
public static MessageBoxFragment newInstance() {
MessageBoxFragment fragment = new MessageBoxFragment();
Bundle args = new Bundle();
return fragment;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
try
{
super.onCreateView(inflater, container, savedInstanceState);
if ( fragmentRootView == null )
{
fragmentRootView = rootView;
rootView.findViewById(id.titleBar).setVisibility(ViewGroup.GONE);
footer = getActivity().getLayoutInflater().inflate(R.layout.fragment_messagebox_footer, null);
layoutFooter = (RelativeLayout) footer.findViewById(id.layoutFooter);
layoutFooter.setVisibility(ViewGroup.GONE);
TextView txtView = (TextView) layoutFooter.findViewById(id.txtGuide);
txtView.setText("메시지내역이 없습니다.");
listMain = (ListView) rootView.findViewById(id.listMain);
adapter = new MessageBoxListAdapter(getActivity(), 0);
listMain.addFooterView(footer, null, false );
listMain.setAdapter(adapter);
inquiryMessage();
listMain.setOnItemClickListener( new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
UserMessage um = (UserMessage) arg1.getTag();
goUserChatActivity( um );
}
});
setTitle("쪽지함");
Button btnRefresh = (Button) rootView.findViewById(id.btnRefresh);
btnRefresh.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
try {
inquiryMessage();
} catch ( Exception ex ) {
// TODO Auto-generated catch block
catchException(this, ex);
}
}
});
}
}
catch( Exception ex )
{
catchException(this, ex);
}
return fragmentRootView;
}
private void inquiryMessage() throws IOException, JsonGenerationException,
JsonMappingException {
User user = application.getLoginUser();
rootView.findViewById(id.marker_progress).setVisibility(ViewGroup.VISIBLE);
listMain.setVisibility(ViewGroup.GONE);
sendHttp("/taxi/getUserMessageList.do", mapper.writeValueAsString(user), 1);
}
@Override
public void doPostTransaction(int requestCode, Object result) {
// TODO Auto-generated method stub
try
{
rootView.findViewById(id.marker_progress).setVisibility(ViewGroup.GONE);
if ( Constants.FAIL.equals(result) )
{
showOKDialog("통신중 오류가 발생했습니다.\r\n다시 시도해 주십시오.", null);
return;
}
listMain.setVisibility(ViewGroup.VISIBLE);
super.doPostTransaction(requestCode, result);
APIResponse response = mapper.readValue(result.toString(), new TypeReference<APIResponse>(){});
if ( "0000".equals( response.getResCode() ) )
{
String noticeListString = mapper.writeValueAsString( response.getData() );
List<UserMessage> messageList = mapper.readValue( noticeListString , new TypeReference<List<UserMessage>>(){});
adapter.setItemList(messageList);
adapter.notifyDataSetChanged();
if ( messageList.size() == 0 )
layoutFooter.setVisibility(ViewGroup.VISIBLE);
else
layoutFooter.setVisibility(ViewGroup.GONE);
}
else
{
showOKDialog("경고", response.getResMsg(), null);
return;
}
}
catch( Exception ex )
{
catchException(this, ex);
}
}
public void goUserChatActivity( UserMessage message )
{
try
{
HashMap hash = new HashMap();
hash.put("fromUserID", message.getUser().getUserID() );
hash.put("userID", application.getLoginUser().getUserID() );
Intent intent = new Intent( getActivity(), UserMessageActivity.class);
intent.putExtra("messageInfo", hash );
startActivity(intent);
getActivity().overridePendingTransition(anim.slide_in_from_right, anim.slide_out_to_left);
}
catch( Exception ex )
{
catchException(this, ex);
}
}
//This is the handler that will manager to process the broadcast intent
private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
try
{
inquiryMessage();
}
catch( Exception ex )
{
catchException(this, ex);
}
}
};
@Override
public void onStart() {
// TODO Auto-generated method stub
super.onStart();
try
{
getActivity().registerReceiver(mMessageReceiver, new IntentFilter("updateUnreadCount"));
inquiryMessage();
}
catch( Exception ex )
{
catchException(this, ex);
}
}
@Override
public void onStop() {
// TODO Auto-generated method stub
super.onStop();
getActivity().unregisterReceiver(mMessageReceiver);
}
}
|
package de.mq.phone.web.person;
import java.util.Map;
import org.springframework.core.convert.converter.Converter;
import de.mq.phone.domain.person.Person;
import de.mq.vaadin.util.Mapper;
interface MapToPersonMapper extends Mapper<Map<String,?>, Person>, Converter<Person,Map<String,Object>> {
Person mapInto(Map<String, ?> mapValues, Person person);
Map<String, Object> convert(Person source);
} |
package architecture.exception;
public class BoardPostingNotFoundException extends RuntimeException{
//
private static final long serialVersionUID = 112989079055962932L;
public BoardPostingNotFoundException(String message){
//
super(message);
}
}
|
package com.example.snapup_android.service;
import com.example.snapup_android.dao.SeatMapper;
import com.example.snapup_android.pojo.Seat;
import java.util.Date;
public class SeatServiceImpl implements SeatService{
private SeatMapper seatMapper;
private TrainRunService trainRunService;
public void setSeatMapper(SeatMapper seatMapper) {
this.seatMapper = seatMapper;
}
public void setTrainRunService(TrainRunService trainRunService) {
this.trainRunService = trainRunService;
}
public void createTrainSerialSeat(Date date, String run_code) {
int seat_num = trainRunService.getSeatNum(run_code);
int coach_num = trainRunService.getCoachNum(run_code);
int train_type = trainRunService.getTrainType(run_code);
if(train_type == 'D')
for(int i=0;i<coach_num;i++){
//两节一等座(30人/节)
if(i == 0 || i == 1)
for(int j=0;j<30;j++){
seatMapper.createSeat(new Seat(run_code, i+1, j+1, '1'));
}
//剩下全是二等座
else
for(int j=0;j<(seat_num-2*30)/(coach_num-2);j++){
seatMapper.createSeat(new Seat(run_code, i+1, j+1, '2'));
}
}
else
for(int i=0;i<coach_num;i++){
//两节一等座(50人/节)
if(i == 0 || i == 1)
for(int j=0;j<50;j++){
seatMapper.createSeat(new Seat(run_code, i+1, j+1, '1'));
}
//剩下全是二等座
else
for(int j=0;j<(seat_num-2*50)/(coach_num-2);j++){
seatMapper.createSeat(new Seat(run_code, i+1, j+1, '2'));
}
}
}
public void deleteTrainSerialSeat(Date date, String run_code) {
}
}
|
//ввод названия месяца словом вывод месяца числом
package Tasks;
import java.io.*;
import java.util.*;
public class Task44 {
public static void main(String[] args) throws Exception{
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
ArrayList<String> months = new ArrayList<String>();
months.add("January");
months.add("February");
months.add("March");
months.add("April");
months.add("May");
months.add("June");
months.add("July");
months.add("August");
months.add("September");
months.add("October");
months.add("November");
months.add("December");
String month = reader.readLine();
int i = 1;
for(String a: months){
if(a.equals(month)){
System.out.println(a + " is the " + i + " month");
break;
}
i++;
}
}
}
|
package com.docker.data;
import com.docker.storage.mongodb.CleanDocument;
import org.bson.Document;
import script.memodb.ObjectId;
import java.util.HashMap;
import java.util.Map;
/**
* Created by wenqi on 2018/12/4
*/
public class ServiceAnnotation {
public static final String TYPE = "type";
public static final String ANNOTATIONPARAMS = "params";
public static final String CLASSNAME = "classname";
public static final String METHODNAME = "methodname";
private String type; //serviceAnnotationType, name of Annotation, like TransactionTry
private Map<String, Object> annotationParams;
private String className;
private String methodName;
public void fromDocument(Document document) {
type = document.getString(TYPE);
annotationParams = document.get(ANNOTATIONPARAMS, Map.class);
className = document.getString(CLASSNAME);
methodName = document.getString(METHODNAME);
}
public Document toDocument() {
CleanDocument document = new CleanDocument();
document.append(TYPE, type)
.append(ANNOTATIONPARAMS, annotationParams)
.append(CLASSNAME, className)
.append(METHODNAME, methodName);
return document;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public Map<String, Object> getAnnotationParams() {
return annotationParams;
}
public void setAnnotationParams(Map<String, Object> annotationParams) {
this.annotationParams = annotationParams;
}
public String getClassName() {
return className;
}
public void setClassName(String className) {
this.className = className;
}
public String getMethodName() {
return methodName;
}
public void setMethodName(String methodName) {
this.methodName = methodName;
}
}
|
package com.demo.model;
import javax.validation.constraints.Size;
import com.demo.helloController.isValidSubject;
public class SubjectMarks {
private int marks;
@Size(min=2,max=10) @isValidSubject(listOfValidSubjects = "physics|maths|chemistry") //This will be caught in isValidSubject
private String subject;
public int getMarks() {
return marks;
}
public void setMarks(int marks) {
this.marks = marks;
}
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
}
|
package com.briup.apps.poll.service.Impl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.briup.apps.poll.bean.Options;
import com.briup.apps.poll.bean.Question;
import com.briup.apps.poll.bean.QuestionExample;
import com.briup.apps.poll.bean.extend.QuestionVM;
import com.briup.apps.poll.dao.OptionsMapper;
import com.briup.apps.poll.dao.QuestionMapper;
import com.briup.apps.poll.dao.extend.QuestionVMMapper;
import com.briup.apps.poll.service.IQuestionService;
import com.briup.apps.poll.util.MsgResponse;
@Service
public class QuestionServiceImpl implements IQuestionService {
@Autowired
private QuestionVMMapper questionVMMapper;
@Autowired
private QuestionMapper questionMapper;
@Autowired
private OptionsMapper optionsMapper;
public void saveOrUpdateVM(QuestionVM questionVM) throws Exception {
//从questionVM中查分出来question options
Question question=new Question();
question.setId(questionVM.getId());
question.setName(questionVM.getName());
question.setQuestiontype(questionVM.getQuestionType());
List<Options> options=questionVM.getOptions();
if (question.getId() != null) {
questionVMMapper.update(questionVM);
} else {
questionMapper.insert(question);
Long id=question.getId();
for(Options option:options){
option.setQuestionId(id);
optionsMapper.insert(option);
}
}
}
@Override
public List<Question> findAll() throws Exception {
// TODO Auto-generated method stub
QuestionExample example = new QuestionExample();
return questionMapper.selectByExample(example);
}
@Override
public List<QuestionVM> findAllQuestionVM() throws Exception {
// TODO Auto-generated method stub
return questionVMMapper.findAll();
}
}
|
/*
* Copyright 2002-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://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.springframework.http.codec;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import org.reactivestreams.Publisher;
import reactor.core.publisher.Mono;
import org.springframework.core.MethodParameter;
import org.springframework.core.ResolvableType;
import org.springframework.http.MediaType;
import org.springframework.http.ReactiveHttpOutputMessage;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.lang.Nullable;
/**
* Strategy for encoding a stream of objects of type {@code <T>} and writing
* the encoded stream of bytes to an {@link ReactiveHttpOutputMessage}.
*
* @author Rossen Stoyanchev
* @author Arjen Poutsma
* @author Sebastien Deleuze
* @since 5.0
* @param <T> the type of objects in the input stream
*/
public interface HttpMessageWriter<T> {
/**
* Return the list of media types supported by this Writer. The list may not
* apply to every possible target element type and calls to this method should
* typically be guarded via {@link #canWrite(ResolvableType, MediaType)
* canWrite(elementType, null)}. The list may also exclude media types
* supported only for a specific element type. Alternatively, use
* {@link #getWritableMediaTypes(ResolvableType)} for a more precise list.
* @return the general list of supported media types
*/
List<MediaType> getWritableMediaTypes();
/**
* Return the list of media types supported by this Writer for the given type
* of element. This list may differ from {@link #getWritableMediaTypes()}
* if the Writer doesn't support the element type, or if it supports it
* only for a subset of media types.
* @param elementType the type of element to encode
* @return the list of media types supported for the given class
* @since 5.3.4
*/
default List<MediaType> getWritableMediaTypes(ResolvableType elementType) {
return (canWrite(elementType, null) ? getWritableMediaTypes() : Collections.emptyList());
}
/**
* Whether the given object type is supported by this writer.
* @param elementType the type of object to check
* @param mediaType the media type for the write (possibly {@code null})
* @return {@code true} if writable, {@code false} otherwise
*/
boolean canWrite(ResolvableType elementType, @Nullable MediaType mediaType);
/**
* Write a given stream of object to the output message.
* @param inputStream the objects to write
* @param elementType the type of objects in the stream which must have been
* previously checked via {@link #canWrite(ResolvableType, MediaType)}
* @param mediaType the content type for the write (possibly {@code null} to
* indicate that the default content type of the writer must be used)
* @param message the message to write to
* @param hints additional information about how to encode and write
* @return indicates completion or error
*/
Mono<Void> write(Publisher<? extends T> inputStream, ResolvableType elementType,
@Nullable MediaType mediaType, ReactiveHttpOutputMessage message, Map<String, Object> hints);
/**
* Server-side only alternative to
* {@link #write(Publisher, ResolvableType, MediaType, ReactiveHttpOutputMessage, Map)}
* with additional context available.
* @param actualType the actual return type of the method that returned the
* value; for annotated controllers, the {@link MethodParameter} can be
* accessed via {@link ResolvableType#getSource()}.
* @param elementType the type of Objects in the input stream
* @param mediaType the content type to use (possibly {@code null} indicating
* the default content type of the writer should be used)
* @param request the current request
* @param response the current response
* @return a {@link Mono} that indicates completion of writing or error
*/
default Mono<Void> write(Publisher<? extends T> inputStream, ResolvableType actualType,
ResolvableType elementType, @Nullable MediaType mediaType, ServerHttpRequest request,
ServerHttpResponse response, Map<String, Object> hints) {
return write(inputStream, elementType, mediaType, response, hints);
}
}
|
package org.zeos.cafe.exception;
/**
* Created by alxev on 09.07.2017.
*/
public class AlreadyClosedException extends Exception {
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.victuxbb.javatest.security.service;
import com.victuxbb.javatest.security.token.InMemoryUserTokenRepository;
import com.victuxbb.javatest.security.token.UserToken;
import com.victuxbb.javatest.security.token.UserTokenNotFoundException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import rx.Observable;
/**
*
* @author victux
*/
public class UserTokenService {
private InMemoryUserTokenRepository inMemoryUserToken;
private static UserTokenService instance;
public UserTokenService() {
this.inMemoryUserToken = InMemoryUserTokenRepository.getInstance();
}
public Observable<UserToken> getUserToken(HttpServletRequest req) throws UserTokenNotFoundException
{
Cookie cookie = getCookie(AuthenticationService.SESSION_COOKIE_NAME, req);
String tokenId = cookie.getValue();
return this.inMemoryUserToken.findByUuid(tokenId);
}
private Cookie getCookie(String cookieName , HttpServletRequest request) throws UserTokenNotFoundException{
Cookie[] cookies = request.getCookies();
for (Cookie cooky : cookies) {
if( cooky.getName().equals(cookieName) ){
return cooky;
}
}
throw new UserTokenNotFoundException("SESSION NOT FOUND");
}
public static UserTokenService getInstance()
{
if(null == instance){
instance = new UserTokenService();
}
return instance;
}
}
|
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.sql.SQLException;
@WebServlet("/auth")
public class LoginServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String login = request.getParameter("login");
String password = request.getParameter("password");
HttpSession session = null;
RequestDispatcher dispatcher = null;
session = request.getSession();
session.setAttribute("user", login);
dispatcher = request.getRequestDispatcher("logout.jsp");
try {
/* добавляем пользователя в базу данных */
ConToDb.createUser(login, password);
/* Устанавливаем куки */
response.addCookie(new Cookie("login", login));
} catch (SQLException e) {
e.printStackTrace();
}
dispatcher.forward(request, response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
getServletContext().getRequestDispatcher("/login.jsp").forward(request, response);
}
}
|
import java.lang.*;
class high
{
public static void main(String args[]){
int a=20,b=10,c=4;
if(a>b)
if(a>c)
System.out.print("Highest value="+a);
else
System.out.print("\nHighest value="+b);
else if(b>c)
System.out.print("\nHighest value="+b);
else
System.out.print("\nHighest value="+c);
}
} |
package com.smokescreem.shash.popularmovies.ui.adapters;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import com.smokescreem.shash.popularmovies.R;
import com.smokescreem.shash.popularmovies.data.models.Movie;
import com.smokescreem.shash.popularmovies.data.provider.Columns;
import com.smokescreem.shash.popularmovies.data.provider.MovieProvider;
import com.smokescreem.shash.popularmovies.utils.Constants;
import com.squareup.picasso.Picasso;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
/**
* Created by Shash on 12/17/2016.
*/
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.ViewHolder> {
private List<Movie> mMovieList;
private Context mContext = null;
public RecyclerAdapter(List<Movie> movieList, Context context){
mMovieList = movieList;
mContext = context;
}
public void updateData(List<Movie> movieList){
mMovieList.clear();
mMovieList.addAll(movieList);
notifyDataSetChanged();
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.list_card_movie,parent,false);
ViewHolder viewHolder = new ViewHolder(v);
return viewHolder;
}
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
Movie movieData = mMovieList.get(position);
if(movieData !=null){
ImageView imageView = holder.imageView;
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
Uri builtUri = Uri.parse(Constants.MOVIESDB_IMAGES_BASE_URL).buildUpon().
appendEncodedPath(movieData.getPosterPath())
.build();
Picasso.with(imageView.getContext())
.load(builtUri.toString())
.resize(400,400)
.into(imageView);
}
}
@Override
public int getItemCount() {
return mMovieList.size();
}
class ViewHolder extends RecyclerView.ViewHolder{
@BindView(R.id.list_item_movie_image_view) ImageView imageView;
public ViewHolder(View itemView) {
super(itemView);
ButterKnife.bind(this,itemView);
itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
int position = getAdapterPosition();
Movie movieData = mMovieList.get(position);
Bundle bundle = new Bundle();
bundle.putParcelable(Constants.MOVIE_DATA, movieData);
Cursor cursor = null;
try {
cursor = mContext.getContentResolver().query(
MovieProvider.Movies.CONTENT_URI,
null,
Columns.TITLE + "=?",
new String[]{movieData.getTitle()},
null
);
} finally {
if (cursor != null)
cursor.close();
}
bundle.putBoolean("is_favorite", cursor.getCount() > 0);
((DetailsCallback)mContext).onItemSelected(bundle);
}
});
}
}
public interface DetailsCallback{
public void onItemSelected(Bundle bundle);
}
}
|
package org.cruise.service;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.cruise.model.Preach;
import org.cruise.repositories.CompanyRepository;
import org.cruise.repositories.PreachRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
/**
* Created by Cruise on 4/28/15.
*/
@Service
@Transactional
public class PreachService {
private static Logger logger = Logger.getLogger(PreachService.class);
@Autowired
private PreachRepository preachRepository;
@Autowired
private CompanyRepository companyRepository;
public List<Preach> findAllPreach(){
return preachRepository.findAll();
}
public Preach findOne(Long id){
return preachRepository.findOne(id);
}
public Page<Preach> search(String keyword,String pageNo){
int pageNo2 ;
if (StringUtils.isBlank(pageNo) || Integer.parseInt(pageNo) < 0){
pageNo2 = 1;
}else{
pageNo2 = Integer.parseInt(pageNo);
}
int pageSize = 18;
PageRequest page = new PageRequest(pageNo2,pageSize);
// return preachRepository.searchLike(keyword,page);
logger.info("Keyword is : " + keyword);
return preachRepository.findByTitleLike("%" + keyword + "%", page);
}
}
|
package com.example.daryl.error404;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
public class AdminService extends AppCompatActivity {
DatabaseReference db;
EditText name, price;
String _name;
double _price;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_admin_service);
db= FirebaseDatabase.getInstance().getReference("service");
}
public void addOnClick(View view){
price= findViewById(R.id.priceEdit);
name=findViewById(R.id.nameEdit);
_name= name.getText().toString();
try{
_price= Double.parseDouble(price.getText().toString());}
catch(NumberFormatException e){
Toast.makeText(this,"Please enter the price correctly", Toast.LENGTH_SHORT).show();
}
if(_price<0){Toast.makeText(this,"The price cannot be negative",Toast.LENGTH_SHORT).show(); }
else{
Service service= new Service(_name,_price);
db.child(db.push().getKey()).setValue(service);}
Toast.makeText(this,"Service added", Toast.LENGTH_SHORT).show();
name.setText("");
price.setText("");
}
}
|
package com.example.studentmanagment;
import android.app.Application;
public class GlobalClass extends Application {
private String collegeId;
private String facultyId;
public String getCollegeId() {
return collegeId;
}
public void setCollegeId(String collegeId) {
this.collegeId = collegeId;
}
public String getFacultyId() {
return facultyId;
}
public void setFacultyId(String facultyId) {
this.facultyId = facultyId;
}
}
|
package com.infinite.study.repository.post;
import com.infinite.study.model.Id;
import com.infinite.study.model.posts.Post;
import com.infinite.study.model.user.User;
import java.util.List;
import java.util.Optional;
public interface PostRepository {
Post insert(Post post);
void update(Post post);
Optional<Post> findById(Id<Post, Long> postId, Id<User, Long> writerId, Id<User, Long> userId);
List<Post> findAll(Id<User, Long> writerId, Id<User, Long> userId, long offset, int limit);
}
|
package com.xinhua.api.domain.xDCBBean;
import java.io.Serializable;
/**
* Created by tanghao on 2015/12/21.
* 新单承保-响应
* 险种现金价值表
*/
public class XzAmtTableListResponse implements Serializable {
private String polBenefitCount;
private String cashValueCount;
private String count;
private String prnt;
private String year;
private String end;
private String cash;
private String aciDeathBenefitAmt;
private String illDeathBenefitAmt;
private String live;
private String surrenderPctFY;
private String surrenderPctSY;
private String paidAmt;
private String cashValueDescription;
public String getPolBenefitCount() {
return polBenefitCount;
}
public void setPolBenefitCount(String polBenefitCount) {
this.polBenefitCount = polBenefitCount;
}
public String getCashValueCount() {
return cashValueCount;
}
public void setCashValueCount(String cashValueCount) {
this.cashValueCount = cashValueCount;
}
public String getCount() {
return count;
}
public void setCount(String count) {
this.count = count;
}
public String getPrnt() {
return prnt;
}
public void setPrnt(String prnt) {
this.prnt = prnt;
}
public String getYear() {
return year;
}
public void setYear(String year) {
this.year = year;
}
public String getEnd() {
return end;
}
public void setEnd(String end) {
this.end = end;
}
public String getCash() {
return cash;
}
public void setCash(String cash) {
this.cash = cash;
}
public String getAciDeathBenefitAmt() {
return aciDeathBenefitAmt;
}
public void setAciDeathBenefitAmt(String aciDeathBenefitAmt) {
this.aciDeathBenefitAmt = aciDeathBenefitAmt;
}
public String getIllDeathBenefitAmt() {
return illDeathBenefitAmt;
}
public void setIllDeathBenefitAmt(String illDeathBenefitAmt) {
this.illDeathBenefitAmt = illDeathBenefitAmt;
}
public String getLive() {
return live;
}
public void setLive(String live) {
this.live = live;
}
public String getSurrenderPctFY() {
return surrenderPctFY;
}
public void setSurrenderPctFY(String surrenderPctFY) {
this.surrenderPctFY = surrenderPctFY;
}
public String getSurrenderPctSY() {
return surrenderPctSY;
}
public void setSurrenderPctSY(String surrenderPctSY) {
this.surrenderPctSY = surrenderPctSY;
}
public String getPaidAmt() {
return paidAmt;
}
public void setPaidAmt(String paidAmt) {
this.paidAmt = paidAmt;
}
public String getCashValueDescription() {
return cashValueDescription;
}
public void setCashValueDescription(String cashValueDescription) {
this.cashValueDescription = cashValueDescription;
}
@Override
public String toString() {
return "XzxjtableListResponse{" +
"polBenefitCount='" + polBenefitCount + '\'' +
", cashValueCount='" + cashValueCount + '\'' +
", count='" + count + '\'' +
", prnt='" + prnt + '\'' +
", year='" + year + '\'' +
", end='" + end + '\'' +
", cash='" + cash + '\'' +
", aciDeathBenefitAmt='" + aciDeathBenefitAmt + '\'' +
", illDeathBenefitAmt='" + illDeathBenefitAmt + '\'' +
", live='" + live + '\'' +
", surrenderPctFY='" + surrenderPctFY + '\'' +
", surrenderPctSY='" + surrenderPctSY + '\'' +
", paidAmt='" + paidAmt + '\'' +
", cashValueDescription='" + cashValueDescription + '\'' +
'}';
}
}
|
package hopper.interpreter;
import hopper.Coordinate;
/**
* The CollectCommand class encapsulates the '<code>-collect</code>' command
* passed on by the user to the application via the terminal.
*
* A <code>CollectCommand</code> object contains a property which is an array of
* two <code>Coordinate</code>s, both delimiting the garbage drop area.
*
* @author Team Hopper
*
*/
public class CollectCommand extends Command {
private Coordinate[] coordinates;
private static final int NUMBER_OF_COORDINATES = 2;
/**
* Creates a new instance of the object.
*/
public CollectCommand() {
super(Command.kCommandCollect);
this.coordinates = new Coordinate[NUMBER_OF_COORDINATES];
}
/**
* Creates a new CollectCommand instance with two given coordinates.
* @param coord1 the first garbage-disposal coordinate.
* @param coord2 the second garbage-disposal coordinate.
*/
public CollectCommand(Coordinate coord1, Coordinate coord2) {
this();
this.coordinates[0] = coord1;
this.coordinates[1] = coord2;
}
/**
* Returns the garbage disposal coordinates associated with the command.
* @return the garbage disposal coordinates associated with the command.
*/
public Coordinate[] getCoordinates() {
return this.coordinates;
}
}
|
package com.myvodafone.android.model.service;
import java.io.Serializable;
public class BAInfo implements Serializable {
public String billingAccountId;
public String activeConnections;
public BAInfo() {
this.billingAccountId = "";
this.activeConnections = "";
}
public String getBillingAccountId() {
// TODO check if this improvement causes sideeffects
if (billingAccountId.length() > 0 && billingAccountId.contains(":")) {
return billingAccountId.split(":")[0];
} else {
return billingAccountId;
}
}
public void setBillingAccountId(String billingAccountId) {
this.billingAccountId = billingAccountId;
}
public String getBillingAccountIdShow() {
return billingAccountId.replace(":", "");
}
public String getActiveConnections() {
return activeConnections;
}
public void setActiveConnections(String activeConnections) {
this.activeConnections = activeConnections;
}
@Override
public String toString() {
return getBillingAccountIdShow();
}
// PRINT
// public void print() {
// StaticTools.Log("ITEM BANNER:: ", "billingAccountId-- " + billingAccountId);
// StaticTools.Log("ITEM BANNER:: ", "activeConnections-- " + activeConnections);
//
// }
}
|
package com.tscloud.address.server.provider;
import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.PageInfo;
import com.tscloud.address.domain.entity.DistrictEntity;
import com.tscloud.address.domain.entity.SearchParams;
import com.tscloud.address.domain.provider.IDistrictProvider;
import com.tscloud.address.domain.service.IDistrictService;
import com.tscloud.common.framework.Exception.DubboProviderException;
import com.tscloud.common.framework.Exception.ServiceException;
import com.tscloud.common.framework.dubbo.impl.DubboBaseInterfaceImpl;
import com.tscloud.common.framework.service.IBaseInterfaceService;
import org.springframework.beans.factory.annotation.Autowired;
@Service
public class DistrictProviderImpl extends DubboBaseInterfaceImpl<DistrictEntity> implements IDistrictProvider {
@Autowired
private IDistrictService districtService;
@Override
public IBaseInterfaceService<DistrictEntity> getBaseInterfaceService() {
return this.districtService;
}
@Override
public PageInfo<DistrictEntity> findAllByPage(SearchParams params) throws DubboProviderException {
try {
return districtService.findAllByPage(params);
}catch (ServiceException e){
log.error("DistrictProviderImpl.findAllByPage error ", e);
throw new DubboProviderException(e.getMessage(), e);
}
}
@Override
public PageInfo<DistrictEntity> getDistrict(SearchParams params) throws DubboProviderException {
try {
return districtService.getDistrict(params);
}catch (ServiceException e){
log.error("DistrictProviderImpl.getDistrict error ", e);
throw new DubboProviderException(e.getMessage(), e);
}
}
@Override
public PageInfo<DistrictEntity> getVillage(SearchParams params) throws DubboProviderException {
try {
return districtService.getVillage(params);
}catch (ServiceException e){
log.error("DistrictProviderImpl.getVillage error ", e);
throw new DubboProviderException(e.getMessage(), e);
}
}
@Override
public PageInfo<DistrictEntity> getRoad(SearchParams params) throws DubboProviderException {
try {
return districtService.getRoad(params);
}catch (ServiceException e){
log.error("DistrictProviderImpl.getRoad error ", e);
throw new DubboProviderException(e.getMessage(), e);
}
}
@Override
public PageInfo<DistrictEntity> getStreetno(SearchParams params) throws DubboProviderException {
try {
return districtService.getStreetno(params);
}catch (ServiceException e){
log.error("DistrictProviderImpl.getStreetno error ", e);
throw new DubboProviderException(e.getMessage(), e);
}
}
@Override
public PageInfo<DistrictEntity> getCommunity(SearchParams params) throws DubboProviderException {
try {
return districtService.getCommunity(params);
}catch (ServiceException e){
log.error("DistrictProviderImpl.getCommunity error ", e);
throw new DubboProviderException(e.getMessage(), e);
}
}
@Override
public PageInfo<DistrictEntity> getLandmark(SearchParams params) throws DubboProviderException {
try {
return districtService.getLandmark(params);
}catch (ServiceException e){
log.error("DistrictProviderImpl.getLandmark error ", e);
throw new DubboProviderException(e.getMessage(), e);
}
}
@Override
public PageInfo<DistrictEntity> getBuilding(SearchParams params) throws DubboProviderException {
try {
return districtService.getBuilding(params);
}catch (ServiceException e){
log.error("DistrictProviderImpl.getBuilding error ", e);
throw new DubboProviderException(e.getMessage(), e);
}
}
}
|
package com.example.yuanbaodianfrontend.dao;
import com.example.yuanbaodianfrontend.pojo.QuestionVo;
import com.example.yuanbaodianfrontend.pojo.YbdExchanageMall;
import com.example.yuanbaodianfrontend.pojo.YbdQuestionBack;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface QuestionBackDao {
//我的消息
List<QuestionVo> MyMessage();
//消息详情
List<QuestionVo> MyMessage_2(Integer id);
//我的收藏
List<YbdQuestionBack> myFavorite(@Param("infoIdStr") String infoIdStr);
//我的错题
List<YbdQuestionBack> myCovenant(String id);
//查询错题选项
String findError(@Param("id") Integer id,@Param("createUser") Integer createUser);
//查询我的礼物
List<YbdExchanageMall> queryConvertRecord(String id);
//首页我的礼物
List<YbdExchanageMall> queryConvertRecord2(String id);
//查询积分记录
List<YbdExchanageMall> myContract(String id);
}
|
package com.mbti.board.service;
import com.mbti.board.dao.BoardReplyDAO;
import com.mbti.board.vo.BoardReplyVO;
import com.mbti.main.controller.Service;
public class BoardReplyUpdateService implements Service{
private BoardReplyDAO dao;
@Override
public Object service(Object obj) throws Exception {
// TODO Auto-generated method stub
return dao.replyUpdate((BoardReplyVO) obj);
}
@Override
public void setDAO(Object dao) {
// TODO Auto-generated method stub
this.dao=(BoardReplyDAO) dao;
}
}
|
package generic;
public class Path<T> {
<D> Path<D> get() {
return new Path<>();
}
}
|
package kr.co.people_gram.app;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;
/**
* Created by 광희 on 2015-09-18.
*/
public class SubPeopleListHideAdapter extends BaseAdapter{
private Context mContext;
private int layout;
private final ArrayList<SubPeopleListDTO> peoplelist;
LayoutInflater inf;
private ViewHolder viewHolder = null;
public String[] uid_check;
public boolean[] isCheckedConfrim;
public SubPeopleListHideAdapter(Context mContext, int layout, ArrayList<SubPeopleListDTO> peoplelist)
{
this.mContext = mContext;
this.layout = layout;
this.peoplelist = peoplelist;
inf = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View convertView = inf.inflate(layout, null);
this.isCheckedConfrim = new boolean[peoplelist.size()];
this.uid_check = new String[peoplelist.size()];
}
@Override
public int getCount() {
return peoplelist.size();
}
@Override
public Object getItem(int position) {
return peoplelist.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
public void setChecked(int position) {
SubPeopleListDTO dto = peoplelist.get(position);
if(isCheckedConfrim[position] == true) {
uid_check[position] = "";
} else {
uid_check[position] = dto.get_profile_uid();
}
isCheckedConfrim[position] = !isCheckedConfrim[position];
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView == null) {
viewHolder = new ViewHolder();
convertView = inf.inflate(layout, null);
viewHolder.cBox = (CheckBox) convertView.findViewById(R.id.hide_delete);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder)convertView.getTag();
}
viewHolder.cBox.setClickable(false);
viewHolder.cBox.setFocusable(false);
//viewHolder.cBox.setText(sArrayList.get(position));
//viewHolder.cBox.setChecked(isCheckedConfrim[position]);
SubPeopleListDTO dto = peoplelist.get(position);
viewHolder.cBox.setChecked(isCheckedConfrim[position]);
TextView listview_people_list_username = (TextView) convertView.findViewById(R.id.listview_people_list_username);
TextView listview_people_list_email = (TextView) convertView.findViewById(R.id.listview_people_list_email);
ImageView listview_proplelist_img = (ImageView) convertView.findViewById(R.id.listview_proplelist_img);
listview_people_list_username.setText(dto.get_profile_username());
listview_people_list_email.setText(dto.get_profile_email());
String people_type = dto.get_profile_type();
switch (people_type) {
case "A":
listview_proplelist_img.setImageResource(R.mipmap.peoplelist_type_a);
break;
case "I":
listview_proplelist_img.setImageResource(R.mipmap.peoplelist_type_i);
break;
case "E":
listview_proplelist_img.setImageResource(R.mipmap.peoplelist_type_e);
break;
case "D":
listview_proplelist_img.setImageResource(R.mipmap.peoplelist_type_d);
break;
case "":
listview_proplelist_img.setImageResource(R.mipmap.peoplelist_type_default);
break;
/*
default:
listview_proplelist_img.setVisibility(View.GONE);
break;
*/
}
//listview_proplelist_img.setTag(position);
/*
listview_proplelist_img.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(mContext,SubMyType_Activity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra("mytype", people_type);
mContext.startActivity(intent);
}
});
*/
return convertView;
}
class ViewHolder {
// 새로운 Row에 들어갈 CheckBox
private CheckBox cBox = null;
}
}
|
package com.ytf.zk.nameservice;
import com.ytf.zk.constant.ClientBase;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.ZooKeeper;
import java.io.IOException;
/**
* Created by yutianfang
* DATE: 17/4/23星期日.
*/
public class Naming {
private static final int CLIENT_PORT = 2181;
private static final String ROOT_PATH = "/root";
private static final String CHILD_PATH = "/root/childPath";
private static final String CHILD_PATH_2 = "/root/childPath2";
static ZooKeeper zk = null;
public static void main(String[] args) throws Exception{
try {
zk = new ZooKeeper("localhost:" + CLIENT_PORT, ClientBase.CONNECTION_TIMEOUT, (watchedEvent) ->{
System.out.println(watchedEvent.getPath() + "触发了" + watchedEvent.getType() + "事件!" + "data:" + Naming.getData(watchedEvent.getPath()));
}
);
// 创建根目录
zk.create(ROOT_PATH, ROOT_PATH.getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
System.out.println(zk.getChildren(ROOT_PATH, true));
// 创建子目录
zk.create(CHILD_PATH, "childPath".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
// 取出子目录节点
System.out.println(ROOT_PATH + "子节点: " + zk.getChildren(ROOT_PATH, true));
System.out.println(CHILD_PATH + "数据: " + new String(zk.getData(CHILD_PATH,true,null)));
// 修改子目录节点数据
zk.setData(CHILD_PATH, "modification".getBytes(), -1);
System.out.println(new String(zk.getData(CHILD_PATH,true,null)));
zk.setData(CHILD_PATH, "modification2".getBytes(), -1);
zk.delete(CHILD_PATH,-1);
// 删除父目录节点
zk.delete(ROOT_PATH,-1);
// 关闭连接
zk.close();
} catch (KeeperException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static String getData(String path){
if(path == null){
return null;
}
try {
return new String(zk.getData(path,false,null));
} catch (KeeperException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
return null;
}
}
|
package heylichen.alg.graph.tasks;
import heylichen.alg.graph.structure.SymbolGraph;
import heylichen.test.AppTestContext;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
@Slf4j
public class DegreesOfSeparationTest extends AppTestContext {
@Autowired
private SymbolGraph moviesSymbolGraph;
@Test
public void name() {
DegreesOfSeparation degreesOfSeparation = new DegreesOfSeparation(moviesSymbolGraph, "Cruise, Tom");
testViewPath(degreesOfSeparation, "Kidman, Nicole");
testViewPath(degreesOfSeparation, "Carrey, Jim");
testViewPath(degreesOfSeparation, "Jay, Tony");
}
private void testViewPath(DegreesOfSeparation degreesOfSeparation, String target) {
log.info("---------path to {}", target);
Iterable<String> path = degreesOfSeparation.shortestPathTo(target);
viewPath(path);
}
private void viewPath(Iterable<String> path) {
for (String s : path) {
log.info("\t{}", s);
}
}
} |
package models;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.Objects;
@AllArgsConstructor
@NoArgsConstructor
@Data
@JsonIgnoreProperties(ignoreUnknown = true)
public class FileDto {
private String content;
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
if (!super.equals(o)) return false;
FileDto file = (FileDto) o;
return Objects.equals(content, file.content);
}
@Override
public int hashCode() {
return Objects.hash(super.hashCode(), content);
}
}
|
package com.youthlin.example.chat.protocol.request;
import com.youthlin.example.chat.protocol.Command;
import com.youthlin.example.chat.protocol.Packet;
import lombok.Data;
/**
* 创建: youthlin.chen
* 时间: 2018-11-13 20:17
*/
@Data
public class LogoutRequestPacket extends Packet {
private static final long serialVersionUID = -7070352806872870755L;
@Override
public byte command() {
return Command.LOGOUT_REQUEST;
}
}
|
package com.hwj.service;
import com.hwj.entity.student;
public interface IStudentService extends IBaseService<student>{
}
|
package cj.oshopping.user.admin.web;
import java.util.List;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.core.convert.ConversionService;
import org.springframework.core.convert.TypeDescriptor;
import org.springframework.validation.Errors;
import org.springframework.validation.FieldError;
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.RestController;
import cj.oshopping.common.model.Json;
import cj.oshopping.common.mybatis.model.MergedPaging;
import cj.oshopping.common.setting.adminweb.config.AdminObjectConversionConfig;
import cj.oshopping.user.admin.model.request.UserAccountSearchParam;
import cj.oshopping.user.admin.model.result.AdUserAccount;
import cj.oshopping.user.core.service.UserAccountService;
import cj.oshopping.user.model.entity.UserAccount;
@RestController
@RequestMapping("/user/ajax")
public class UserAccountController {
@Autowired
private UserAccountService userAccountService;
@Autowired
@Qualifier(AdminObjectConversionConfig.CONVERSION_SERVICE_QUALIFIER)
private ConversionService conversionService;
@SuppressWarnings("unchecked")
@RequestMapping(value="/accounts", method={RequestMethod.POST})
public Json<?> getAccounts(@Valid @RequestBody UserAccountSearchParam userAccountSearchParam,
Errors errors) {
if(errors.hasErrors()) {
StringBuilder sb = new StringBuilder();
List<FieldError> fieldErrors = errors.getFieldErrors();
for(FieldError fieldError : fieldErrors) {
sb.append(String.format("%s.%s - %s\n",
fieldError.getObjectName(),
fieldError.getField(),
fieldError.getDefaultMessage()));
}
throw new IllegalArgumentException(sb.toString());
}
MergedPaging<UserAccount> userAccounts = userAccountService.getUserAccountsByNameAndPhoneNumber(userAccountSearchParam.getName(),
userAccountSearchParam.getPhoneNumber(),
userAccountSearchParam.getTotalCountExecute(),
userAccountSearchParam.getPageNumber(),
userAccountSearchParam.getLimit());
MergedPaging<AdUserAccount> adUserAccounts = (MergedPaging<AdUserAccount>)conversionService.convert(userAccounts,
TypeDescriptor.collection(MergedPaging.class, TypeDescriptor.valueOf(UserAccount.class)),
TypeDescriptor.collection(MergedPaging.class, TypeDescriptor.valueOf(AdUserAccount.class)));
return Json.createJson(adUserAccounts);
}
}
|
package org.usfirst.frc.team319.robot;
import org.usfirst.frc.team319.robot.subsystems.Drivetrain;
import org.usfirst.frc.team319.robot.subsystems.Pneumatics;
import org.usfirst.frc.team319.robot.subsystems.Wrist;
import org.usfirst.frc.team319.utils.VisionHelper;
import org.usfirst.frc.team319.robot.subsystems.Acubeulator;
import org.usfirst.frc.team319.robot.subsystems.Collector;
import edu.wpi.first.wpilibj.TimedRobot;
import edu.wpi.first.wpilibj.command.Command;
import edu.wpi.first.wpilibj.command.Scheduler;
import edu.wpi.first.wpilibj.smartdashboard.SendableChooser;
import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard;
public class Robot extends TimedRobot {
Command autonomousCommand;
SendableChooser<String> autoChooser;
public static final Drivetrain drivetrain = new Drivetrain();
public static final Acubeulator acubeulator = new Acubeulator();
public static final Wrist wrist = new Wrist();
public static final Collector collector = new Collector();
public static final Pneumatics pneumatics = new Pneumatics();
public static final VisionHelper vision = new VisionHelper();
public static OI oi;
@Override
public void robotInit() {
oi = new OI();
autoChooser = new SendableChooser<String>();
autoChooser.addDefault("Example Auto", "Example Auto");
SmartDashboard.putData("Autonomous Chooser", autoChooser);
}
@Override
public void disabledInit() {
}
@Override
public void disabledPeriodic() {
Scheduler.getInstance().run();
//SmartDashboard.putNumber("Driver Left Trigger", Robot.oi.driverController.triggers.getLeft());
//SmartDashboard.putNumber("Operator Left Stick Y", Robot.oi.operatorController.leftStick.getY());
}
@Override
public void autonomousInit() {
}
/**
* This function is called periodically during autonomous.
*/
@Override
public void autonomousPeriodic() {
Scheduler.getInstance().run();
}
@Override
public void teleopInit() {
if (autonomousCommand != null) {
autonomousCommand.cancel();
}
}
/**
* This function is called periodically during operator control.
*/
@Override
public void teleopPeriodic() {
Scheduler.getInstance().run();
drivetrain.returnLimelight();
}
@Override
public void testPeriodic() {
}
}
|
package be.mxs.common.util.io;
import java.awt.image.BufferedImage;
import java.io.File;
import java.net.URL;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Timestamp;
import javax.imageio.ImageIO;
import org.apache.commons.io.FileUtils;
import org.dcm4che2.data.DicomObject;
import org.dcm4che2.data.Tag;
import org.dcm4che2.data.VR;
import be.mxs.common.util.db.MedwanQuery;
import be.mxs.common.util.system.Debug;
import be.mxs.common.util.system.ScreenHelper;
import be.openclinic.archiving.DcmSnd;
import be.openclinic.archiving.Dicom;
import be.openclinic.system.SH;
import uk.org.primrose.vendor.standalone.PrimroseLoader;
public class SpoolMPIDocuments {
public static String getParam(String[] args,String name, String defaultValue) {
for(int n=0;n<args.length;n++) {
if(args[n].equals(name) && n<args.length-1) {
return args[n+1];
}
}
return defaultValue;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
PrimroseLoader.load(getParam(args, "--config", "/var/tomcat/conf/db.cfg"), true);
while(true) {
if(getParam(args,"--debug" ,"1").equalsIgnoreCase("1")) {
Debug.enabled=true;
}
//Remove transmission logs older than x days
Connection conn = MedwanQuery.getInstance(false).getOpenclinicConnection();
PreparedStatement ps = conn.prepareStatement("delete from oc_mpidocuments where oc_mpidocument_sentdatetime<?");
ps.setTimestamp(1, new java.sql.Timestamp(new java.util.Date().getTime()-ScreenHelper.getTimeDay()*MedwanQuery.getInstance().getConfigInt("numberOfDaysBeforeDeletingDocumentsFromSpooler",7)));
ps.execute();
ps = conn.prepareStatement("select * from oc_mpidocuments where oc_mpidocument_sentdatetime is null");
ResultSet rs = ps.executeQuery();
while(rs.next()) {
String direction = rs.getString("oc_mpidocument_direction");
if(direction.equalsIgnoreCase("uploadDICOM")) {
//Upload the dicom file to the destionation MPI server
String id=rs.getString("oc_mpidocument_id");
//First set the patient ID to the mpiid
String filename = rs.getString("oc_mpidocument_url");
try {
DicomObject obj = Dicom.getDicomObject(filename);
obj.putString(Tag.PatientID, VR.LO, id.split("\\$")[2]);
File toFile = new File(filename);
Dicom.writeDicomObject(obj, toFile);
System.out.println("[SpoolMPIDocuments] Trying to send "+filename);
if(DcmSnd.isSendTest( getParam(args, "--aetitle", "OCPX"),
getParam(args, "--pacshost", SH.cs("MPIPACSServerHost","cloud.hnrw.org")),
Integer.parseInt(getParam(args, "--pacsport", SH.cs("MPIPACSServerPort","10555"))),
filename)) {
System.out.println("[SpoolMPIDocuments] "+filename+" sent");
PreparedStatement ps2 = conn.prepareStatement("update oc_mpidocuments set oc_mpidocument_sentdatetime=? where oc_mpidocument_id=?");
ps2.setTimestamp(1,new java.sql.Timestamp(new java.util.Date().getTime()));
ps2.setString(2,id);
ps2.execute();
ps2.close();
}
else {
System.out.println("Error while sending "+filename+". Will retry later.");
}
}
catch(Exception ee) {
ee.printStackTrace();
}
}
if(direction.equalsIgnoreCase("downloadDICOM")) {
//Download the dicom files and store it in the document scanner 'from' directory
String id=rs.getString("oc_mpidocument_id");
String url = rs.getString("oc_mpidocument_url");
System.out.println("[SpoolMPIDocuments] Trying to fetch "+url);
try {
String toFile=MedwanQuery.getInstance(false).getConfigString("scanDirectoryMonitor_basePath","/var/tomcat/webapps/openclinic/scan")+"/"+MedwanQuery.getInstance(false).getConfigString("scanDirectoryMonitor_dirFrom","from")+"/"+id+".dcm";
FileUtils.copyURLToFile(new URL(url), new File(toFile));
PreparedStatement ps2 = conn.prepareStatement("delete from oc_mpidocuments where oc_mpidocument_id=?");
ps2.setString(1,id);
ps2.execute();
ps2.close();
System.out.println("[SpoolMPIDocuments] Fetched "+url);
}
catch(Exception ee) {
ee.printStackTrace();
}
}
}
rs.close();
ps.close();
conn.close();
Thread.sleep(5000);
}
}
catch (Exception e) {
e.printStackTrace();
}
System.exit(0);
}
}
|
package com.corneliouzbett.mpesasdk.exception;
public class MpesaException extends RuntimeException {
private static final long serialVersionUID = 2516935680980388130L;
public MpesaException(final String message) {
super(message);
}
public MpesaException(final String message, final Throwable cause) {
super(message, cause);
}
}
|
package fr.perrine.starlove;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
public class AskActivity extends AppCompatActivity {
public final static int GALLERY = 123;
private String mGenre;
private Uri mFileUri = null;
private String mGetImageUrl = "";
private String mUid;
private DatabaseReference mDatabaseUsers;
private ImageView mAvatar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ask);
TextView app = findViewById(R.id.tv_title);
FontHelper.setFont(app, "Starjhol.ttf");
final EditText editUser = findViewById(R.id.edit_user);
final EditText editSpecies = findViewById(R.id.edit_species);
final EditText editMass = findViewById(R.id.edit_mass);
final EditText editHeight = findViewById(R.id.edit_height);
Button btnValidate = findViewById(R.id.button_validate);
final RadioButton male = findViewById(R.id.radiobtn_male);
final RadioButton female = findViewById(R.id.radiobtn_female);
mAvatar = findViewById(R.id.img_profile);
FirebaseAuth auth = FirebaseAuth.getInstance();
FirebaseDatabase firebaseDatabase = FirebaseDatabase.getInstance();
mUid = FirebaseAuth.getInstance().getCurrentUser().getUid();
if (auth.getCurrentUser() == null) {
Intent intent = new Intent(AskActivity.this, ConnexionActivity.class);
startActivity(intent);
finish();
}
mAvatar.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(AskActivity.this);
builder.setTitle(R.string.my_profile_pic)
.setPositiveButton("Gallery", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Intent.ACTION_PICK,
MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, GALLERY);
}
})
.show();
}
});
mDatabaseUsers = firebaseDatabase.getReference("users").child(mUid);
btnValidate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String username = editUser.getText().toString();
String species = editSpecies.getText().toString();
String strMass = editMass.getText().toString();
String strHeight = editHeight.getText().toString();
if (male.isChecked()) {
mGenre = "male";
} else if (female.isChecked()) {
mGenre = "female";
}
if (username.isEmpty() || species.isEmpty()) {
Toast.makeText(AskActivity.this, R.string.please_fill_all_fields, Toast.LENGTH_SHORT).show();
} else {
int mass = Integer.parseInt(strMass);
double height = Double.parseDouble(strHeight);
StorageReference ref = FirebaseStorage.getInstance().getReference().child(mUid).child("avatar.jpg");
ref.putFile(mFileUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Uri downloadUri = taskSnapshot.getDownloadUrl();
FirebaseDatabase.getInstance().getReference("users")
.child(mUid).child("avatar").setValue(downloadUri.toString());
}
});
ProfileModel model = new ProfileModel(username, mGenre, species, mass, height);
mDatabaseUsers.setValue(model);
Intent intent = new Intent(AskActivity.this, AccueilActivity.class);
startActivity(intent);
finish();
}
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case GALLERY:
try {
if (resultCode == RESULT_OK) {
mFileUri = data.getData();
Glide.with(this).load(mFileUri).into(mAvatar);
mGetImageUrl = mFileUri.getPath();
}
} catch (Exception e) {
e.printStackTrace();
}
break;
}
}
}
|
package com.thomson.dp.principle.zen.lsp.domain;
/**
* AUG狙击枪
*
* @author Thomson Tang
*/
public class AUG extends Rifle {
//狙击枪会携带一个精准的望远镜,这就是子类AUG特有的个性方法
public void zoomOut() {
System.out.println("用望远镜瞄准敌人......");
}
@Override public void shoot() {
System.out.println("用AUG狙击枪射击......");
}
}
|
package org.xaab.springmvc;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Controller
public class LoginController
{
private static final Logger logger = LoggerFactory.getLogger(LoginController.class);
@RequestMapping(value="/app/login.do", method=RequestMethod.GET)
public String login() {
logger.info("INSIDE LOGIN!");
return "login";
}
}
|
package io.github.yanhu32.xpathkit.converter;
import io.github.yanhu32.xpathkit.utils.Strings;
/**
* @author yh
* @since 2021/4/22
*/
public class DoubleTextConverter implements TextConverter<Double> {
@Override
public Double apply(String text) {
if (Strings.isEmpty(text)) {
return null;
}
return Double.valueOf(text);
}
}
|
package com.soa.soap;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for wsElf complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="wsElf">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="arrowCount" type="{http://www.w3.org/2001/XMLSchema}int" minOccurs="0"/>
* <element name="bowType" type="{http://soap.soa.com/}bowType" minOccurs="0"/>
* <element name="forestId" type="{http://www.w3.org/2001/XMLSchema}long" minOccurs="0"/>
* <element name="id" type="{http://www.w3.org/2001/XMLSchema}long" minOccurs="0"/>
* <element name="name" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="power" type="{http://soap.soa.com/}power" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "wsElf", propOrder = {
"arrowCount",
"bowType",
"forestId",
"id",
"name",
"power"
})
public class WsElf {
protected Integer arrowCount;
@XmlSchemaType(name = "string")
protected BowType bowType;
protected Long forestId;
protected Long id;
protected String name;
@XmlSchemaType(name = "string")
protected Power power;
/**
* Gets the value of the arrowCount property.
*
* @return
* possible object is
* {@link Integer }
*
*/
public Integer getArrowCount() {
return arrowCount;
}
/**
* Sets the value of the arrowCount property.
*
* @param value
* allowed object is
* {@link Integer }
*
*/
public void setArrowCount(Integer value) {
this.arrowCount = value;
}
/**
* Gets the value of the bowType property.
*
* @return
* possible object is
* {@link BowType }
*
*/
public BowType getBowType() {
return bowType;
}
/**
* Sets the value of the bowType property.
*
* @param value
* allowed object is
* {@link BowType }
*
*/
public void setBowType(BowType value) {
this.bowType = value;
}
/**
* Gets the value of the forestId property.
*
* @return
* possible object is
* {@link Long }
*
*/
public Long getForestId() {
return forestId;
}
/**
* Sets the value of the forestId property.
*
* @param value
* allowed object is
* {@link Long }
*
*/
public void setForestId(Long value) {
this.forestId = value;
}
/**
* Gets the value of the id property.
*
* @return
* possible object is
* {@link Long }
*
*/
public Long getId() {
return id;
}
/**
* Sets the value of the id property.
*
* @param value
* allowed object is
* {@link Long }
*
*/
public void setId(Long value) {
this.id = value;
}
/**
* Gets the value of the name property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getName() {
return name;
}
/**
* Sets the value of the name property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setName(String value) {
this.name = value;
}
/**
* Gets the value of the power property.
*
* @return
* possible object is
* {@link Power }
*
*/
public Power getPower() {
return power;
}
/**
* Sets the value of the power property.
*
* @param value
* allowed object is
* {@link Power }
*
*/
public void setPower(Power value) {
this.power = value;
}
}
|
package highscore;
import java.io.IOException;
import gui.GUIApplication;
import mainGame.components.Song;
public class HighscoreGui extends GUIApplication{
/**
*
*/
private static final long serialVersionUID = 1L;
private HighscoreScreen highscore;
public static void main(String[] args)
{
HighscoreGui g = new HighscoreGui(960,540);
Thread runner = new Thread(g);
runner.start();
}
public HighscoreGui(int width, int height) {
super(width, height);
setVisible(true);
}
@Override
public void initScreen() {
Song a=new Song("resources/realMaps/DreadnoughtMastermind(xi+nora2r)-HD.csv");
a.addScoreAndAccuracy(444, (float) 4.53);
a.addScoreAndAccuracy(999999, (float) 43);
a.addScoreAndAccuracy(999299, (float) 43);
highscore = new HighscoreScreen(getWidth(), getHeight(), false, 999999, 49.27, a, a);
setScreen(highscore);
}
}
|
package com.github.andlyticsproject;
import android.os.Bundle;
import android.preference.CheckBoxPreference;
import android.preference.Preference;
import android.preference.Preference.OnPreferenceChangeListener;
import android.preference.PreferenceCategory;
import android.preference.PreferenceManager;
import com.actionbarsherlock.app.SherlockPreferenceActivity;
import com.actionbarsherlock.view.MenuItem;
// See PreferenceActivity for warning suppression justification
@SuppressWarnings("deprecation")
public class NotificationPreferenceActivity extends SherlockPreferenceActivity {
private CheckBoxPreference downloadsPref;
private CheckBoxPreference ratingsPref;
private CheckBoxPreference commentsPref;
private PreferenceCategory notificationSignalPrefCat;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
PreferenceManager prefMgr = getPreferenceManager();
prefMgr.setSharedPreferencesName(Preferences.PREF);
addPreferencesFromResource(R.xml.notification_preferences);
// Get a reference to the notification triggers so that we can visually disable the other
// notification preferences when all the triggers are disabled
// TODO: Can we do this all using one generic listener?
ratingsPref = (CheckBoxPreference) getPreferenceScreen().findPreference(
Preferences.NOTIFICATION_CHANGES_RATING);
ratingsPref.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
Boolean notificationsEnabled = (Boolean) newValue || commentsPref.isChecked()
|| downloadsPref.isChecked();
notificationSignalPrefCat.setEnabled(notificationsEnabled);
return true;
}
});
commentsPref = (CheckBoxPreference) getPreferenceScreen().findPreference(
Preferences.NOTIFICATION_CHANGES_COMMENTS);
commentsPref.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
Boolean notificationsEnabled = (Boolean) newValue || ratingsPref.isChecked()
|| downloadsPref.isChecked();
notificationSignalPrefCat.setEnabled(notificationsEnabled);
return true;
}
});
downloadsPref = (CheckBoxPreference) getPreferenceScreen().findPreference(
Preferences.NOTIFICATION_CHANGES_DOWNLOADS);
downloadsPref.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
Boolean notificationsEnabled = (Boolean) newValue || ratingsPref.isChecked()
|| commentsPref.isChecked();
notificationSignalPrefCat.setEnabled(notificationsEnabled);
return true;
}
});
// Notification signal
notificationSignalPrefCat = (PreferenceCategory) getPreferenceScreen().findPreference(
"prefCatNotificationSignal");
// Set initial enabled state based on the triggers
Boolean notificationsEnabled = commentsPref.isChecked() || ratingsPref.isChecked()
|| downloadsPref.isChecked();
notificationSignalPrefCat.setEnabled(notificationsEnabled);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
|
import java.util.Scanner;
public class Uri1060{
public static void main(String args[]){
Scanner teclado = new Scanner(System.in);
float N;
int qtd=0;
for (int cont = 1; cont <=6; cont++){
N = teclado.nextFloat();
if (N > 0){
//System.out.println("Numero digitado é positivo");
qtd = qtd + 1;
}
}
System.out.println(qtd + " valores positivos");
}
} |
package fileManager;
public class Node {
String key;
Node left, right;
public Node (String item) {
key = item;
left = right = null;
}
public String toString() {
return "good";
}
}
|
package kompressor.huffman.structures;
import kompressor.huffman.TreeBuilder;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
public class HuffmanTreeTest {
private HuffmanTree tree;
public HuffmanTreeTest() {
}
@Test
public void testSearchCode() {
tree = TreeBuilder.createTreeFromUnencodedBytes("cbboooiiiieeeee".getBytes());
IntQueue list = tree.searchCode('e');
assertEquals(1, list.pop().intValue());
assertEquals(1, list.pop().intValue());
list = tree.searchCode('i');
assertEquals(1, list.pop().intValue());
assertEquals(0, list.pop().intValue());
list = tree.searchCode('o');
assertEquals(0, list.pop().intValue());
assertEquals(0, list.pop().intValue());
list = tree.searchCode('b');
assertEquals(0, list.pop().intValue());
assertEquals(1, list.pop().intValue());
assertEquals(1, list.pop().intValue());
list = tree.searchCode('c');
assertEquals(0, list.pop().intValue());
assertEquals(1, list.pop().intValue());
assertEquals(0, list.pop().intValue());
}
}
|
package al.ahgitdevelopment.municion;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import java.util.ArrayList;
/**
* Created by Alberto on 11/04/2016.
*/
public class GuiaAdapter extends ArrayAdapter<Guia> {
Context context;
public GuiaAdapter(Context activity, ArrayList<Guia> guias) {
super(activity, R.layout.guia_item, guias);
context = activity;
}
@Override
public int getCount() {
return super.getCount();
}
@Override
public Guia getItem(int position) {
return super.getItem(position);
}
@Override
public long getItemId(int position) {
return super.getItemId(position);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
Guia item = getItem(position);
if (convertView == null)
convertView = LayoutInflater.from(context).inflate(R.layout.guia_item, null);
TextView nombreGuia = (TextView) convertView.findViewById(R.id.item_nombre_guia);
TextView municion = (TextView) convertView.findViewById(R.id.item_precio);
TextView porcentaje = (TextView) convertView.findViewById(R.id.item_cartuchos_comprados);
nombreGuia.setText(getItem(position).getNombreArma());
municion.setText(item.getCartuchosGastados() + "\\" + item.getCartuchosTotales());
float percentValue = (float) item.cartuchosGastados * 100 / item.cartuchosTotales;
porcentaje.setText(percentValue + "%");
return convertView;
}
}
|
package generics;
/**
* Created by user on 05.12.16.
*/
public class Car extends Machine {
public Long model;
public Long year;
} |
package cn.tedu.annotation;
@Apple(s = 6.6, value = "大牛")
public class TestDome {
String name;
public void play() {
System.out.println("普通方法");
}
}
|
package jesk.system;
import java.awt.Image;
import java.io.File;
import java.lang.reflect.Method;
import javax.swing.ImageIcon;
import javax.swing.filechooser.FileSystemView;
public class ShellFolder {
private final File file;
private final Object shell;
public ShellFolder(File file) {
this.file = file;
Object shell = null;
try {
Class<?> shellFolder = Class.forName("sun.awt.shell.ShellFolder");
Method getShellFolder = shellFolder.getMethod("getShellFolder", File.class);
getShellFolder.setAccessible(true);
shell = getShellFolder.invoke(null, file);
} catch (Exception ex) {
// TODO implement error handling
}
this.shell = shell;
}
public File getFile() {
return file;
}
public boolean hasShell() {
return shell != null;
}
public Object getShell() {
return shell;
}
public String getDisplayName() {
if (hasShell()) {
return safeInvoke(safeGetMethod(shell, "getDisplayName"), shell);
} else {
return OperatingSystem.makeDisplayName(file);
}
}
public Image getIcon(boolean large) {
if (hasShell()) {
return safeInvoke(safeGetMethod(shell, "getIcon", boolean.class), shell, large);
} else {
return ((ImageIcon) FileSystemView.getFileSystemView().getSystemIcon(file)).getImage();
}
}
private static Method safeGetMethod(Object instance, String method, Class<?>... parameterTypes) {
try {
return instance != null ? instance.getClass().getMethod(method, parameterTypes) : null;
} catch (Exception ex) {
return null;
}
}
@SuppressWarnings("unchecked")
private static <T> T safeInvoke(Method method, Object instance, Object... args) {
if (method == null)
return null;
try {
method.setAccessible(true);
Object o = method.invoke(instance, args);
return (T) o;
} catch (Exception ex) {
return null;
}
}
} |
package hwarang.artg.manager.service;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import hwarang.artg.common.model.CriteriaDTO;
import hwarang.artg.mapper.ManagerMainMapper;
import hwarang.artg.member.model.MemberVO;
import hwarang.artg.rrboard.model.ReviewBoardVO;
@Service
public class ManagerMainService {
@Autowired
private ManagerMainMapper dao;
public Map<String, Object> MangerMainResults(){
return dao.getTotals();
}
//New memberList for a week
public List<MemberVO> newMemberList(){
return dao.getNewMember();
}
//총 멤버수
public int totalMemCount(CriteriaDTO cri) {
return dao.getTotalMemCount(cri);
}
public List<MemberVO> pagingList(CriteriaDTO cri){
return dao.getListWithPaging(cri);
}
//Review 미리보기
public List<ReviewBoardVO> getReviewsTop(){
return dao.getReviews();
}
}
|
package component;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import dbConstant.DBConstant;
public class MySQLStub {
// Attribute
private java.sql.Statement statement;
// Constructor
public MySQLStub() {this.login(DBConstant.URL, DBConstant.USER, DBConstant.PW); this.useDB(DBConstant.DB);}
// Any Time Use
public void login(String url, String user, String pw) {
try { // Set Attribute
Connection connect = DriverManager.getConnection(url, user, pw);
this.statement = connect.createStatement();
} catch (SQLException e) {e.printStackTrace();}
}
public void useDB(String dbName) {try {this.statement.executeQuery("use "+dbName+";");} catch (SQLException e) {e.printStackTrace();}}
public int insert(String tableName, Object...values) {
String instruction = "insert into "+tableName+ " values(";
for(Object value : values) {instruction += (this.objectToString(value)+", ");}
instruction = instruction.substring(0, instruction.length() - 2) + ");"; // 마지막 ", "를 제거
try {this.statement.execute(instruction);} catch (SQLException e) {e.printStackTrace();}
try {
ResultSet rs = this.statement.executeQuery("select last_insert_id() as last_id from "+tableName);
if(rs.next()) {return Integer.parseInt(rs.getString("last_id"));}
} catch (SQLException e) {e.printStackTrace();}
System.err.println("MySQLStub - insert err");
return 0;
}
public ResultSet select(String tableName, String pkName, int id) {
String instruction = "select * from " + tableName + " where "+ pkName+" = "+id+";";
try {return this.statement.executeQuery(instruction);} catch (SQLException e) {e.printStackTrace(); return null;}
}
public void update (String tableName, String pkName, int id, String name, Object value) {
String instruction = "update " + tableName + " set " + name + " = " + this.objectToString(value) + " where "+pkName+" = " + id + ";";
try {this.statement.execute(instruction);} catch (SQLException e) {e.printStackTrace();}
}
public void delete(String tableName, String pkName, int id) {
String instruction = "delete from " + tableName + " where "+ pkName+" = "+id+";";
try {this.statement.execute(instruction);} catch (SQLException e) {e.printStackTrace();}
}
public String objectToString(Object value) {
if(value instanceof Integer) {return (Integer.toString((Integer)value));}
else if(value instanceof Double) {return (Double.toString((Double)value));}
else if(value instanceof Boolean) {if((boolean) value) {return "TRUE";}else {return "FALSE";}}
else if(value instanceof String) {return ("\""+value+"\" ");} // 고정적이라 "" 달아놓음
else {return null;}
}
public String getString(String tableName, String pkName, int id, String columName) {
try {ResultSet rs = this.select(tableName, pkName, id); if(rs.next()) {return rs.getString(columName);}}catch (SQLException e) {e.printStackTrace();}
System.err.println("MySQL Stub - Get String ERR");
return null;
}
public int getInt(String tableName, String pkName, int id, String columName) {
try {ResultSet rs = this.select(tableName, pkName, id); if(rs.next()) {return rs.getInt(columName);}}catch (SQLException e) {e.printStackTrace();}
System.err.println("MySQL Stub - Get Int ERR");
return -1;
}
public double getDouble(String tableName, String pkName, int id, String columName) {
try {ResultSet rs = this.select(tableName, pkName, id); if(rs.next()) {return rs.getDouble(columName);}}catch (SQLException e) {e.printStackTrace();}
System.err.println("MySQL Stub - Get Double ERR");
return -1;
}
public boolean getBoolean(String tableName, String pkName, int id, String columName) {
try {ResultSet rs = this.select(tableName, pkName, id); if(rs.next()) {return rs.getBoolean(columName);}}catch (SQLException e) {e.printStackTrace();}
System.err.println("MySQL Stub - Get Boolean ERR");
return false;
}
}
|
package pet_shop.DAO;
import java.util.ArrayList;
import pet_shop.negocio.beans.Produto;
public class ProdutoDAO {
private ArrayList<Produto> repositorioProduto;
private static ProdutoDAO instance;
private ProdutoDAO() {
this.repositorioProduto = new ArrayList<>();
}
public static ProdutoDAO getInstance() {
if (instance == null) {
instance = new ProdutoDAO();
}
return instance;
}
public void cadastrarProduto(Produto p) {
this.repositorioProduto.add(p);
}
public void alterarProduto(Produto p) {
boolean achou = false;
for (int i = 0; i < this.repositorioProduto.size() && achou == false; i++) {
if (this.repositorioProduto.get(i).getId() == p.getId()) {
this.repositorioProduto.remove(i);
this.repositorioProduto.add(i, p);
achou = true;
}
}
}
public void excluirProduto(long id) {
boolean achou = false;
for (int i = 0; i < this.repositorioProduto.size() && achou == false; i++) {
if (this.repositorioProduto.get(i).getId() == id) {
this.repositorioProduto.remove(i);
achou = true;
}
}
}
public Produto listarProduto(long id) {
boolean achou = false;
Produto busca = null;
for (int i = 0; i < this.repositorioProduto.size() && achou == false; i++) {
if (this.repositorioProduto.get(i).getId() == id) {
busca = this.repositorioProduto.get(i);
achou = true;
}
}
return busca;
}
public ArrayList<Produto> listarTudo() {
return this.repositorioProduto;
}
public boolean existe(Produto p) {
boolean verificar = false;
for (int i = 0; i < this.repositorioProduto.size() && verificar == false; i++) {
if (p.equals(this.repositorioProduto.get(i))) {
verificar = true;
}
}
return verificar;
}
}
|
package com.example.spring05.model.member.dao;
import com.example.spring05.model.member.dto.MemberDTO;
public interface MemberDAO {
public boolean loginCheck(MemberDTO dto);
public MemberDTO viewMember(String userid);
}
|
/*
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://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.springframework.core.io.buffer;
import java.io.IOException;
import java.io.OutputStream;
import org.springframework.util.Assert;
/**
* An {@link OutputStream} that writes to a {@link DataBuffer}.
*
* @author Arjen Poutsma
* @since 6.0
* @see DataBuffer#asOutputStream()
*/
final class DataBufferOutputStream extends OutputStream {
private final DataBuffer dataBuffer;
private boolean closed;
public DataBufferOutputStream(DataBuffer dataBuffer) {
Assert.notNull(dataBuffer, "DataBuffer must not be null");
this.dataBuffer = dataBuffer;
}
@Override
public void write(int b) throws IOException {
checkClosed();
this.dataBuffer.ensureWritable(1);
this.dataBuffer.write((byte) b);
}
@Override
public void write(byte[] b, int off, int len) throws IOException {
checkClosed();
if (len > 0) {
this.dataBuffer.ensureWritable(len);
this.dataBuffer.write(b, off, len);
}
}
@Override
public void close() {
if (this.closed) {
return;
}
this.closed = true;
}
private void checkClosed() throws IOException {
if (this.closed) {
throw new IOException("DataBufferOutputStream is closed");
}
}
}
|
package com.xcafe.bank.service.repository;
import com.xcafe.bank.entity.Account;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.ResultSetExtractor;
import java.sql.ResultSet;
import java.sql.SQLException;
public class AccountExtractor implements ResultSetExtractor<Account> {
@Override
public Account extractData(ResultSet resultSet) throws SQLException, DataAccessException {
Account account = null;
if (resultSet.next()) {
account = new Account(resultSet.getString("number"));
account.setId(resultSet.getLong("id"));
account.setBalance(resultSet.getLong("balance"));
}
return account;
}
}
|
package az.omar.staticfragmentexplain;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentManager;
import android.os.Bundle;
import java.util.Stack;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FragmentManager fragmentManager = getSupportFragmentManager();
BodyPartFragment headFragment = new BodyPartFragment(AndroidImageAssets.getHeads());
fragmentManager.beginTransaction().add(R.id.head_fr, headFragment).commit();
BodyPartFragment bodyFragment = new BodyPartFragment(AndroidImageAssets.getBodies());
fragmentManager.beginTransaction().add(R.id.body_fr, bodyFragment).commit();
BodyPartFragment legFragment = new BodyPartFragment(AndroidImageAssets.getLegs());
fragmentManager.beginTransaction().add(R.id.leg_fr, legFragment).commit();
}
} |
//
// Decompiled by Procyon v0.5.36
//
package com.davivienda.sara.tablas.transportadora.session;
import java.util.Collection;
import javax.annotation.PostConstruct;
import com.davivienda.sara.tablas.transportadora.servicio.TransportadoraServicio;
import javax.persistence.PersistenceContext;
import javax.persistence.EntityManager;
import javax.ejb.Stateless;
import com.davivienda.sara.entitys.Transportadora;
import com.davivienda.sara.base.BaseAdministracionTablas;
@Stateless
public class TransportadoraSessionBean extends BaseAdministracionTablas<Transportadora> implements TransportadoraSessionLocal
{
@PersistenceContext
private EntityManager em;
private TransportadoraServicio transportadoraServicio;
@PostConstruct
public void postConstructor() {
this.transportadoraServicio = new TransportadoraServicio(this.em);
super.servicio = this.transportadoraServicio;
}
@Override
public Collection<Transportadora> getTodos(final Integer pagina, final Integer regsPorPagina) throws Exception {
return this.servicio.consultarPorQuery(pagina, regsPorPagina, "Transportadora.Todos");
}
}
|
/*
* 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 services;
import dataaccess.CategoriesDB;
import dataaccess.ItemsDBException;
import java.util.List;
import models.Category;
public class CategoryService
{
public List<Category> getCategories()
{
CategoriesDB cdb = new CategoriesDB();
List <Category> catList = cdb.getAll();
return catList;
}
public void update(int id, String categ) throws Exception
{
CategoriesDB cdb = new CategoriesDB();
Category f = cdb.getCategoryByID(id);
f.setCategoryName(categ);
cdb.update(f);
}
public Category getCategory (int id)
{
CategoriesDB cdb = new CategoriesDB();
Category h = cdb.getCategoryByID(id);
return h;
}
public int insert (String name) throws Exception
{
CategoriesDB cdb = new CategoriesDB();
Category g = new Category();
g.setCategoryName(name);
g.setCategoryID(0);
int r = cdb.insert(g);
if(r == 0)
{
throw new ItemsDBException("Error: Can't insert new category ;(");
}
return r;
}
}
|
/*
* class SuiteTest version 1.0
* Fecha de creación: 29/05/2021 Fecha de Última modificación: 29/05/2021
*
* Copyright (c) David Jiménez Riscardo, 2021
* Módulo: DISEÑO DE INTERFACES Ejercicio ejemplo para el Examen Final de Junio
*/
package calculator;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
@RunWith(value = Suite.class)
@Suite.SuiteClasses({
//Incluimos todos los nombres de las clases que componen la Suite de pruebas
CalculatorTest.class
})
/**
*
* @author AntDVD
*/
public class SuiteTest {
}
|
package br.cefetrj.sca.infra.cargadados;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.Query;
import jxl.Sheet;
import jxl.Workbook;
import jxl.WorkbookSettings;
import jxl.read.biff.BiffException;
import br.cefetrj.sca.dominio.Aluno;
import br.cefetrj.sca.dominio.Disciplina;
import br.cefetrj.sca.dominio.PeriodoLetivo;
import br.cefetrj.sca.dominio.PeriodoLetivo.EnumPeriodo;
import br.cefetrj.sca.dominio.Turma;
import br.cefetrj.sca.dominio.VersaoCurso;
/**
* Essa classe faz a carga de objetos <code>Turma</code>.
*
* @author Eduardo Bezerra
*
*/
public class ImportadorInscricoes {
private final String colunas[] = { "NOME_UNIDADE", "NOME_PESSOA", "CPF",
"DT_SOLICITACAO", "DT_PROCESS", "COD_DISCIPLINA",
"NOME_DISCIPLINA", "PERIODO_IDEAL", "PRIOR_TURMA", "PRIOR_DISC",
"ORDEM_MATR", "SITUACAO", "COD_TURMA", "COD_CURSO", "VERSAO_CURSO",
"MATR_ALUNO", "PERIODO_ATUAL", "SITUACAO_ITEM", "ANO", "PERIODO",
"IND_GERADA", "ID_PROCESSAMENTO", "HR_SOLICITACAO" };
/**
* Dicionário turmas --> versões de curso.
*
* chave: codigo da turma + código da disciplina,
*
* valor: código da versão do curso
*/
private HashMap<String, String> mapaTurmasVersoesCurso;
/**
* Dicionário turmas --> versões de curso.
*
* chave: codigo da turma + código da disciplina,
*
* valor: sigla do curso
*/
private HashMap<String, String> mapaTurmasCursos;
/**
* Dicionário alunos --> nomes.
*
* chave: matrícula do aluno,
*
* valor: nome do aluno
*/
private HashMap<String, String> mapaAlunosNomes;
/**
* Dicionário alunos --> CPFs.
*
* chave: matrícula do aluno,
*
* valor: CPF do aluno
*/
private HashMap<String, String> mapaAlunosCPFs;
/**
* Dicionário turmas --> períodos letivos.
*
* chave: codigo da turma + código da disciplina,
*
* valor: período letivo { ano, período }
*/
private HashMap<String, PeriodoLetivo> mapaTurmasParaPeriodos;
/**
* Dicionário turmas --> disciplinas.
*
* chave: codigo da turma + código da disciplina,
*
* valor: código da disciplina
*/
private HashMap<String, String> mapaTurmasDisciplinas;
/**
* Dicionário turmas --> alunos.
*
* chave: codigo da turma + código da disciplina,
*
* valor: matrícula do aluno
*/
private HashMap<String, Set<String>> mapaTurmasAlunos;
/**
* Dicionário turmas --> códigos das turmas.
*
* chave: codigo da turma + código da disciplina,
*
* valor: código da turma
*/
private HashMap<String, String> mapaTurmasCodigos;
public ImportadorInscricoes() {
mapaTurmasVersoesCurso = new HashMap<>();
mapaTurmasCursos = new HashMap<>();
mapaAlunosNomes = new HashMap<>();
mapaAlunosCPFs = new HashMap<>();
mapaTurmasParaPeriodos = new HashMap<>();
mapaTurmasDisciplinas = new HashMap<>();
mapaTurmasAlunos = new HashMap<>();
mapaTurmasCodigos = new HashMap<>();
}
public void run() {
try {
File folder = new File("./planilhas/matriculas");
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++) {
mapaTurmasVersoesCurso.clear();
mapaTurmasCursos.clear();
mapaAlunosNomes.clear();
mapaAlunosCPFs.clear();
mapaTurmasParaPeriodos.clear();
mapaTurmasDisciplinas.clear();
mapaTurmasAlunos.clear();
mapaTurmasCodigos.clear();
if (listOfFiles[i].isFile()) {
if (!listOfFiles[i].getName().startsWith("_")) {
System.out
.println("Importando inscrições da planilha \""
+ listOfFiles[i].getName());
String arquivoPlanilha = "./planilhas/matriculas/"
+ listOfFiles[i].getName();
importarPlanilha(arquivoPlanilha);
gravarDadosImportados();
}
} else if (listOfFiles[i].isDirectory()) {
System.out
.println("Diretório: " + listOfFiles[i].getName());
}
}
} catch (BiffException | IOException e) {
System.err.println("Erro fatal!");
e.printStackTrace();
System.exit(1);
}
System.out.println("Feito!");
}
public void importarPlanilha(String inputFile) throws BiffException,
IOException {
File inputWorkbook = new File(inputFile);
importarPlanilha(inputWorkbook);
}
public void importarPlanilha(File inputWorkbook) throws BiffException,
IOException {
Workbook w;
List<String> colunasList = Arrays.asList(colunas);
WorkbookSettings ws = new WorkbookSettings();
ws.setEncoding("Cp1252");
w = Workbook.getWorkbook(inputWorkbook, ws);
Sheet sheet = w.getSheet(0);
EntityManager em = ImportadorTudo.emf.createEntityManager();
for (int i = 1; i < sheet.getRows(); i++) {
String aluno_matricula = sheet.getCell(
colunasList.indexOf("MATR_ALUNO"), i).getContents();
/**
* No Moodle, o CPF do aluno é armazenado sem os pontos separadores,
* enquanto que os valores de CPFs provenientes do SIE possuem
* pontos. A instrução a seguir tem o propósito de uniformizar a
* representação.
*/
String disciplina_codigo = sheet.getCell(
colunasList.indexOf("COD_DISCIPLINA"), i).getContents();
String turma_codigo = sheet.getCell(
colunasList.indexOf("COD_TURMA"), i).getContents();
String semestre_ano = sheet.getCell(colunasList.indexOf("ANO"), i)
.getContents();
String semestre_periodo = sheet.getCell(
colunasList.indexOf("PERIODO"), i).getContents();
int ano = Integer.parseInt(semestre_ano);
PeriodoLetivo.EnumPeriodo periodo = null;
if (semestre_periodo.equals("1º Semestre")) {
periodo = EnumPeriodo.PRIMEIRO;
} else if (semestre_periodo.equals("2º Semestre")) {
periodo = EnumPeriodo.SEGUNDO;
}
/**
* O código não é único dentro de um período letivo. Por exemplo,
* pode haver várias turmas com código igual a "EXTRA" mas de
* disciplinas diferentes. Por conta disso, tive que montar uma
* chave para identificar unicamente uma turma dentro de um período
* letivo, conforme atribuição a seguir.
*/
String chaveTurma = turma_codigo + " - " + disciplina_codigo;
PeriodoLetivo semestre = new PeriodoLetivo(ano, periodo);
mapaTurmasParaPeriodos.put(chaveTurma, semestre);
mapaTurmasDisciplinas.put(chaveTurma, disciplina_codigo);
mapaTurmasCodigos.put(chaveTurma, turma_codigo);
String numVersaoCurso = sheet.getCell(
colunasList.indexOf("VERSAO_CURSO"), i).getContents();
String siglaCurso = sheet.getCell(colunasList.indexOf("COD_CURSO"),
i).getContents();
mapaTurmasVersoesCurso.put(chaveTurma, numVersaoCurso);
mapaTurmasCursos.put(chaveTurma, siglaCurso);
String situacao = sheet.getCell(colunasList.indexOf("SITUACAO"), i)
.getContents();
if (situacao.equals("Aceita/Matriculada")) {
if (!mapaTurmasAlunos.containsKey(chaveTurma)) {
mapaTurmasAlunos.put(chaveTurma, new HashSet<String>());
}
mapaTurmasAlunos.get(chaveTurma).add(aluno_matricula);
}
String matricula_aluno = sheet.getCell(
colunasList.indexOf("MATR_ALUNO"), i).getContents();
if (obterAlunoPorMatricula(em, matricula_aluno) == null) {
String nome_aluno = sheet.getCell(
colunasList.indexOf("NOME_PESSOA"), i).getContents();
mapaAlunosNomes.put(matricula_aluno, nome_aluno);
String cpf_aluno = sheet.getCell(colunasList.indexOf("CPF"), i)
.getContents();
mapaAlunosCPFs.put(matricula_aluno, cpf_aluno);
}
}
em.close();
}
public void gravarDadosImportados() {
EntityManager em = ImportadorTudo.emf.createEntityManager();
em.getTransaction().begin();
/**
* Realiza a persistência de objetos <code>Turma</code> e dos
* respectivos objetos <code>Inscricao</code>.
*/
Set<String> turmasIt = mapaTurmasParaPeriodos.keySet();
int qtdInscricoes = 0;
int qtdTurmas = 0;
for (String chaveTurma : turmasIt) {
PeriodoLetivo semestre = mapaTurmasParaPeriodos.get(chaveTurma);
String codigoDisciplina = mapaTurmasDisciplinas.get(chaveTurma);
Set<String> matriculas = mapaTurmasAlunos.get(chaveTurma);
String numeroVersaoCurso = mapaTurmasVersoesCurso.get(chaveTurma);
String codCurso = mapaTurmasCursos.get(chaveTurma);
String codTurma = mapaTurmasCodigos.get(chaveTurma);
Disciplina disciplina = obterDisciplina(em, codigoDisciplina,
codCurso, numeroVersaoCurso);
if (disciplina != null) {
int capacidadeMaxima = 80;
Turma turma = new Turma(disciplina, codTurma, capacidadeMaxima,
semestre);
qtdTurmas++;
if (matriculas != null) {
for (String matricula : matriculas) {
Aluno aluno = obterAlunoPorMatricula(em, matricula);
if (aluno != null) {
try {
turma.inscreverAluno(aluno);
} catch (IllegalStateException e) {
String erro = "Código turma/nome disciplina -->"
+ turma.getCodigo()
+ "/"
+ turma.getNomeDisciplina();
throw new IllegalStateException(erro, e);
}
} else {
System.err
.println("Aluno não encontrado (matrícula): "
+ matricula
+ ". Inserindo aluno...");
String aluno_cpf = mapaAlunosCPFs.get(matricula);
String aluno_nome = mapaAlunosNomes.get(matricula);
aluno = criarAluno(aluno_nome, matricula,
aluno_cpf, codCurso, numeroVersaoCurso, em);
em.persist(aluno);
System.err.println("Aluno inserido com sucesso: "
+ aluno.toString());
}
}
}
em.persist(turma);
qtdInscricoes += turma.getQtdInscritos();
}
}
em.getTransaction().commit();
em.close();
System.out.println("Foram importadas " + qtdTurmas + " turmas.");
System.out
.println("Foram importadas " + qtdInscricoes + " inscrições.");
}
public Aluno criarAluno(String nomeAluno, String matriculaAluno,
String cpfAluno, String siglaCurso, String numeroVersaoCurso,
EntityManager em) {
String str = "FROM VersaoCurso v WHERE v.curso.sigla = ?1 and v.numero = ?2";
Query q = em.createQuery(str);
q.setParameter(1, siglaCurso);
q.setParameter(2, numeroVersaoCurso);
VersaoCurso versaoCurso = (VersaoCurso) q.getSingleResult();
if (versaoCurso == null) {
throw new IllegalArgumentException(
"Versão do curso não encontrada. Sigla: " + siglaCurso
+ "; Versão: " + numeroVersaoCurso);
}
Aluno aluno = new Aluno(nomeAluno, cpfAluno, matriculaAluno,
versaoCurso);
return aluno;
}
private Aluno obterAlunoPorMatricula(EntityManager em, String matricula) {
Query query = em
.createQuery("from Aluno a where a.matricula = :matricula");
query.setParameter("matricula", matricula);
try {
return (Aluno) query.getSingleResult();
} catch (NoResultException ex) {
return null;
}
}
private Disciplina obterDisciplina(EntityManager em,
String codigoDisciplina, String codCurso, String numeroVersaoCurso) {
Query query = em
.createQuery("from Disciplina d where d.codigo = :codigoDisciplina "
+ "and d.versaoCurso.numero = :numeroVersaoCurso and d.versaoCurso.curso.sigla = :codCurso");
query.setParameter("codigoDisciplina", codigoDisciplina);
query.setParameter("codCurso", codCurso);
query.setParameter("numeroVersaoCurso", numeroVersaoCurso);
Disciplina disciplina = null;
try {
disciplina = (Disciplina) query.getSingleResult();
} catch (NoResultException e) {
System.err.println("Disciplina não encontrada (código - versão): "
+ codigoDisciplina + " - " + numeroVersaoCurso);
}
return disciplina;
}
}
|
import java.util.ArrayList;
public class Task1_1 {
/* Составить линейную программу, печатающую значение true если сумма двух первых чисел заданного четырехзначного
числа равна сумме двух его последних цифр, и false - в противном случае
*/
public static void main(String[] args) {
final String HELP_MESSAGE = "Input a four-digit integer number as an argument";
if (args.length < 1) { //проверка количества введенных аргументов
System.out.println(HELP_MESSAGE);
} else {
int number = 0;
try {
number = Integer.parseInt(args[0]);
} catch (NumberFormatException e) {
System.out.println(e.getMessage());
}
number = Math.abs(number);
ArrayList<Integer> digits = new ArrayList<>();
while (number >= 1) { // формируем коллекцию чисел из цифр числа
digits.add(number % 10);
number = number / 10;
}
if (digits.size() == 4) { // работаем только с четырехзначным числом
System.out.println(digits.get(0) + digits.get(1) == digits.get(2) + digits.get(3));
} else {
System.out.println(HELP_MESSAGE);
}
}
}
}
|
public enum VehicleType {
SUV(1000),SEDAN(100),MOTOR_CYCLE(10),MPV(1500),TRUCK(3000),VAN(2000);
private int rate;
private VehicleType(int rate)
{
this.rate = rate;
}
public int getRate()
{
return this.rate;
}
}
|
package itemData;
public class buff {
public String showName = null;
public buff(String buffType){
showName = buffType;
}
}
|
package cn.wormholestack.eventnice.annotation;
import java.lang.annotation.*;
/**
* @description: Annotation:标识一个方法为事件接收器方法
* @Author MRyan
* @Date 2021/10/7 22:50
* @Version 1.0
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@Documented
public @interface EventReceive {
}
|
package de.deeprobin.amethyst_mod;
import net.fabricmc.api.ModInitializer;
import net.minecraft.block.*;
import net.minecraft.entity.EquipmentSlot;
import net.minecraft.item.*;
import net.minecraft.structure.rule.BlockMatchRuleTest;
import net.minecraft.util.Identifier;
import net.minecraft.util.registry.BuiltinRegistries;
import net.minecraft.util.registry.Registry;
import net.minecraft.world.gen.feature.ConfiguredFeature;
import net.minecraft.world.gen.feature.Feature;
import net.minecraft.world.gen.feature.OreFeatureConfig;
/**
* The mod initializer of the amethyst mod
* @author Robin Lindner
* @see net.fabricmc.api.ModInitializer
*/
public final class AmethystMod implements ModInitializer {
public static final ToolMaterial TOOL_MATERIAL = new AmethystMaterial();
public static final ArmorMaterial ARMOR_MATERIAL = new AmethystArmorMaterial();
public static final Item AMETHYST_SWORD = new SwordItem(TOOL_MATERIAL, 4, -1.8F, (new Item.Settings()).group(ItemGroup.COMBAT));
public static final Item AMETHYST_PICKAXE = new AmethystPickaxe(TOOL_MATERIAL, 2, -2.2F, (new Item.Settings()).group(ItemGroup.TOOLS));
public static final Item AMETHYST_AXE = new AmethystAxe(TOOL_MATERIAL, 6.0F, -2.8F, (new Item.Settings()).group(ItemGroup.TOOLS));
public static final Item AMETHYST_SHOVEL = new ShovelItem(TOOL_MATERIAL, 2.5F, -2.8F, (new Item.Settings()).group(ItemGroup.TOOLS));
public static final Item AMETHYST_HOE = new AmethystHoe(TOOL_MATERIAL, 0, -2.8F, (new Item.Settings()).group(ItemGroup.TOOLS));
public static final Item AMETHYST_HELMET = new ArmorItem(ARMOR_MATERIAL, EquipmentSlot.HEAD, (new Item.Settings().group(ItemGroup.COMBAT)));
public static final Item AMETHYST_CHESTPLATE = new ArmorItem(ARMOR_MATERIAL, EquipmentSlot.CHEST, (new Item.Settings().group(ItemGroup.COMBAT)));
public static final Item AMETHYST_LEGGINGS = new ArmorItem(ARMOR_MATERIAL, EquipmentSlot.LEGS, (new Item.Settings().group(ItemGroup.COMBAT)));
public static final Item AMETHYST_BOOTS = new ArmorItem(ARMOR_MATERIAL, EquipmentSlot.FEET, (new Item.Settings().group(ItemGroup.COMBAT)));
public static final Item AMETHYST_HORSE_ARMOR = new HorseArmorItem(14, "amethyst", (new Item.Settings()).maxCount(1).group(ItemGroup.MISC));
public static final Item AMETHYST = new Item(new Item.Settings().group(ItemGroup.MATERIALS));
public static final Block AMETHYST_BLOCK = new Block(Block.Settings.of(Material.METAL, MaterialColor.RED).strength(5.0F, 5.0F));
public static final Block AMETHYST_ORE = new OreBlock(Block.Settings.of(Material.STONE).strength(3.0F, 3.0F));
public static final Block THE_END_AMETHYST_ORE = new OreBlock(Block.Settings.of(Material.STONE).strength(3.0F, 3.0F));
public static final ConfiguredFeature<?,?> AMETHYST_ORE_FEATURE = Feature.ORE.configure(new OreFeatureConfig(OreFeatureConfig.Rules.BASE_STONE_OVERWORLD, AMETHYST_ORE.getDefaultState(), 6)).method_30377(128).spreadHorizontally().repeat(20);
public static final ConfiguredFeature<?,?> THE_END_AMETHYST_ORE_FEATURE = Feature.ORE.configure(new OreFeatureConfig(new BlockMatchRuleTest(Blocks.END_STONE), THE_END_AMETHYST_ORE.getDefaultState(), 24)).method_30377(16).spreadHorizontally().repeatRandomly(24);
@Override
public void onInitialize() {
Registry.register(Registry.ITEM, new Identifier("amethyst_mod", "amethyst"), AMETHYST);
Registry.register(Registry.ITEM, new Identifier("amethyst_mod", "amethyst_sword"), AMETHYST_SWORD);
Registry.register(Registry.ITEM, new Identifier("amethyst_mod", "amethyst_pickaxe"), AMETHYST_PICKAXE);
Registry.register(Registry.ITEM, new Identifier("amethyst_mod", "amethyst_axe"), AMETHYST_AXE);
Registry.register(Registry.ITEM, new Identifier("amethyst_mod", "amethyst_shovel"), AMETHYST_SHOVEL);
Registry.register(Registry.ITEM, new Identifier("amethyst_mod", "amethyst_hoe"), AMETHYST_HOE);
Registry.register(Registry.ITEM, new Identifier("amethyst_mod", "amethyst_helmet"), AMETHYST_HELMET);
Registry.register(Registry.ITEM, new Identifier("amethyst_mod", "amethyst_chestplate"), AMETHYST_CHESTPLATE);
Registry.register(Registry.ITEM, new Identifier("amethyst_mod", "amethyst_leggings"), AMETHYST_LEGGINGS);
Registry.register(Registry.ITEM, new Identifier("amethyst_mod", "amethyst_boots"), AMETHYST_BOOTS);
Registry.register(Registry.ITEM, new Identifier("amethyst_mod", "amethyst_horse_armor"), AMETHYST_HORSE_ARMOR);
Registry.register(Registry.BLOCK, new Identifier("amethyst_mod", "amethyst_block"), AMETHYST_BLOCK);
Registry.register(Registry.BLOCK, new Identifier("amethyst_mod", "amethyst_ore"), AMETHYST_ORE);
Registry.register(Registry.BLOCK, new Identifier("amethyst_mod", "end_amethyst_ore"), THE_END_AMETHYST_ORE);
Registry.register(Registry.ITEM, new Identifier("amethyst_mod", "amethyst_block"), new BlockItem(AMETHYST_BLOCK, new Item.Settings().group(ItemGroup.BUILDING_BLOCKS)));
Registry.register(Registry.ITEM, new Identifier("amethyst_mod", "amethyst_ore"), new BlockItem(AMETHYST_ORE, new Item.Settings().group(ItemGroup.BUILDING_BLOCKS)));
Registry.register(Registry.ITEM, new Identifier("amethyst_mod", "end_amethyst_ore"), new BlockItem(THE_END_AMETHYST_ORE, new Item.Settings().group(ItemGroup.BUILDING_BLOCKS)));
Registry.register(BuiltinRegistries.CONFIGURED_FEATURE, new Identifier("amethyst_mod", "ore_amethyst"), AMETHYST_ORE_FEATURE);
Registry.register(BuiltinRegistries.CONFIGURED_FEATURE, new Identifier("amethyst_mod", "ore_amethyst_end"), THE_END_AMETHYST_ORE_FEATURE);
}
}
|
package Project;
import java.util.*;
public class Student extends User implements Function, java.io.Serializable {
//initialize variable
private ArrayList<Course> regCourse = new ArrayList<Course>();
//default constructor
public Student() {
super();
}
//constructor for new student
public Student(String un, String pw, String fn, String ln) {
super(un, pw, fn, ln);
}
//getter and setter
public ArrayList<Course> getRC() {
return regCourse;
}
public void SetRC(ArrayList<Course> rc) {
regCourse = rc;
}
//Print all courses
public void printAllCourse(ArrayList<Course> AC) {
for(Course c:AC)
System.out.println(c);
}
//Print all courses that are not full
public void printMatchCourse(ArrayList<Course> AC) {
for(Course c:AC) {
if (!c.ifFull())
System.out.println(c);
}
}
//Register on a course
public void RegCourse(Course c) {
regCourse.add(c);
c.setCNS(c.getCNS()+1);
ArrayList<String> curRegStudent = c.getCRS();
curRegStudent.add(getFN() + " " + getLN());
c.setCRS(curRegStudent);
}
//Withdraw from a course
public void witCourse(Course c) {
regCourse.remove(c);
c.setCNS(c.getCNS()-1);
ArrayList<String> curRegStudent = c.getCRS();
curRegStudent.remove(getFN() + " " + getLN());
c.setCRS(curRegStudent);
}
}
|
/*
* Copyright 2002-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://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.springframework.jms.core;
import java.util.Map;
import jakarta.jms.Destination;
import org.springframework.lang.Nullable;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessagingException;
import org.springframework.messaging.core.MessagePostProcessor;
import org.springframework.messaging.core.MessageReceivingOperations;
import org.springframework.messaging.core.MessageRequestReplyOperations;
import org.springframework.messaging.core.MessageSendingOperations;
/**
* A specialization of {@link MessageSendingOperations}, {@link MessageReceivingOperations}
* and {@link MessageRequestReplyOperations} for JMS related operations that allow to specify
* a destination name rather than the actual {@link jakarta.jms.Destination}.
*
* @author Stephane Nicoll
* @since 4.1
* @see org.springframework.jms.core.JmsTemplate
* @see org.springframework.messaging.core.MessageSendingOperations
* @see org.springframework.messaging.core.MessageReceivingOperations
* @see org.springframework.messaging.core.MessageRequestReplyOperations
*/
public interface JmsMessageOperations extends MessageSendingOperations<Destination>,
MessageReceivingOperations<Destination>, MessageRequestReplyOperations<Destination> {
/**
* Send a message to the given destination.
* @param destinationName the name of the target destination
* @param message the message to send
*/
void send(String destinationName, Message<?> message) throws MessagingException;
/**
* Convert the given Object to serialized form, possibly using a
* {@link org.springframework.messaging.converter.MessageConverter},
* wrap it as a message and send it to the given destination.
* @param destinationName the name of the target destination
* @param payload the Object to use as payload
*/
void convertAndSend(String destinationName, Object payload) throws MessagingException;
/**
* Convert the given Object to serialized form, possibly using a
* {@link org.springframework.messaging.converter.MessageConverter},
* wrap it as a message with the given headers and send it to
* the given destination.
* @param destinationName the name of the target destination
* @param payload the Object to use as payload
* @param headers the headers for the message to send
*/
void convertAndSend(String destinationName, Object payload, Map<String, Object> headers)
throws MessagingException;
/**
* Convert the given Object to serialized form, possibly using a
* {@link org.springframework.messaging.converter.MessageConverter},
* wrap it as a message, apply the given post processor, and send
* the resulting message to the given destination.
* @param destinationName the name of the target destination
* @param payload the Object to use as payload
* @param postProcessor the post processor to apply to the message
*/
void convertAndSend(String destinationName, Object payload, MessagePostProcessor postProcessor)
throws MessagingException;
/**
* Convert the given Object to serialized form, possibly using a
* {@link org.springframework.messaging.converter.MessageConverter},
* wrap it as a message with the given headers, apply the given post processor,
* and send the resulting message to the given destination.
* @param destinationName the name of the target destination
* @param payload the Object to use as payload
* @param headers the headers for the message to send
* @param postProcessor the post processor to apply to the message
*/
void convertAndSend(String destinationName, Object payload, @Nullable Map<String, Object> headers,
@Nullable MessagePostProcessor postProcessor) throws MessagingException;
/**
* Receive a message from the given destination.
* @param destinationName the name of the target destination
* @return the received message, possibly {@code null} if the message could not
* be received, for example due to a timeout
*/
@Nullable
Message<?> receive(String destinationName) throws MessagingException;
/**
* Receive a message from the given destination and convert its payload to the
* specified target class.
* @param destinationName the name of the target destination
* @param targetClass the target class to convert the payload to
* @return the converted payload of the reply message, possibly {@code null} if
* the message could not be received, for example due to a timeout
*/
@Nullable
<T> T receiveAndConvert(String destinationName, Class<T> targetClass) throws MessagingException;
/**
* Send a request message and receive the reply from the given destination.
* @param destinationName the name of the target destination
* @param requestMessage the message to send
* @return the reply, possibly {@code null} if the message could not be received,
* for example due to a timeout
*/
@Nullable
Message<?> sendAndReceive(String destinationName, Message<?> requestMessage) throws MessagingException;
/**
* Convert the given request Object to serialized form, possibly using a
* {@link org.springframework.messaging.converter.MessageConverter}, send
* it as a {@link Message} to the given destination, receive the reply and convert
* its body of the specified target class.
* @param destinationName the name of the target destination
* @param request payload for the request message to send
* @param targetClass the target type to convert the payload of the reply to
* @return the payload of the reply message, possibly {@code null} if the message
* could not be received, for example due to a timeout
*/
@Nullable
<T> T convertSendAndReceive(String destinationName, Object request, Class<T> targetClass) throws MessagingException;
/**
* Convert the given request Object to serialized form, possibly using a
* {@link org.springframework.messaging.converter.MessageConverter}, send
* it as a {@link Message} with the given headers, to the specified destination,
* receive the reply and convert its body of the specified target class.
* @param destinationName the name of the target destination
* @param request payload for the request message to send
* @param headers the headers for the request message to send
* @param targetClass the target type to convert the payload of the reply to
* @return the payload of the reply message, possibly {@code null} if the message
* could not be received, for example due to a timeout
*/
@Nullable
<T> T convertSendAndReceive(String destinationName, Object request, @Nullable Map<String, Object> headers, Class<T> targetClass)
throws MessagingException;
/**
* Convert the given request Object to serialized form, possibly using a
* {@link org.springframework.messaging.converter.MessageConverter},
* apply the given post processor and send the resulting {@link Message} to the
* given destination, receive the reply and convert its body of the given
* target class.
* @param destinationName the name of the target destination
* @param request payload for the request message to send
* @param targetClass the target type to convert the payload of the reply to
* @param requestPostProcessor post process to apply to the request message
* @return the payload of the reply message, possibly {@code null} if the message
* could not be received, for example due to a timeout
*/
@Nullable
<T> T convertSendAndReceive(String destinationName, Object request, Class<T> targetClass,
MessagePostProcessor requestPostProcessor) throws MessagingException;
/**
* Convert the given request Object to serialized form, possibly using a
* {@link org.springframework.messaging.converter.MessageConverter},
* wrap it as a message with the given headers, apply the given post processor
* and send the resulting {@link Message} to the specified destination, receive
* the reply and convert its body of the given target class.
* @param destinationName the name of the target destination
* @param request payload for the request message to send
* @param targetClass the target type to convert the payload of the reply to
* @param requestPostProcessor post process to apply to the request message
* @return the payload of the reply message, possibly {@code null} if the message
* could not be received, for example due to a timeout
*/
@Nullable
<T> T convertSendAndReceive(String destinationName, Object request, Map<String, Object> headers,
Class<T> targetClass, MessagePostProcessor requestPostProcessor) throws MessagingException;
}
|
package org.abrahamalarcon.datastream.controller;
import org.abrahamalarcon.datastream.service.DatastoreService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.messaging.handler.annotation.DestinationVariable;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.messaging.simp.SimpMessageSendingOperations;
import org.springframework.messaging.simp.stomp.StompFrameHandler;
import org.springframework.messaging.simp.stomp.StompHeaders;
import org.springframework.messaging.simp.stomp.StompSession;
import org.springframework.messaging.simp.stomp.StompSessionHandlerAdapter;
import org.springframework.stereotype.Controller;
import org.springframework.util.concurrent.ListenableFuture;
import org.springframework.web.socket.WebSocketHttpHeaders;
import org.springframework.web.socket.client.standard.StandardWebSocketClient;
import org.springframework.web.socket.messaging.WebSocketStompClient;
import org.springframework.web.socket.sockjs.client.SockJsClient;
import org.springframework.web.socket.sockjs.client.Transport;
import org.springframework.web.socket.sockjs.client.WebSocketTransport;
import org.springframework.web.socket.sockjs.frame.Jackson2SockJsMessageCodec;
import java.lang.reflect.Type;
import java.util.Collections;
import java.util.List;
import java.util.logging.Logger;
@Controller
public class SubscriptionController
{
private static Logger logger = Logger.getLogger(SubscriptionController.class.getName());
@Autowired SimpMessageSendingOperations messagingTemplate;
@Autowired DatastoreService datastoreService;
@Value("${exposed.route.hostname}")
private String host;
@Value("${exposed.route.port}")
private int port;
private ListenableFuture<StompSession> connect()
{
Transport webSocketTransport = new WebSocketTransport(new StandardWebSocketClient());
List<Transport> transports = Collections.singletonList(webSocketTransport);
SockJsClient sockJsClient = new SockJsClient(transports);
sockJsClient.setMessageCodec(new Jackson2SockJsMessageCodec());
WebSocketStompClient stompClient = new WebSocketStompClient(sockJsClient);
String url = "ws://{host}:{port}/ws";
WebSocketHttpHeaders headers = new WebSocketHttpHeaders();
return stompClient.connect(url, headers, new MyHandler(), host, port);
}
private class MyHandler extends StompSessionHandlerAdapter
{
public void afterConnected(StompSession stompSession, StompHeaders stompHeaders)
{
logger.info("Now connected");
}
}
/**
* Client must create a subscription, indicating the output required (graphql)
*/
@MessageMapping("/{clientId}/{eventId}")
public void subscribeToEvent(@DestinationVariable String clientId,
@DestinationVariable String eventId,
@Payload String subscription) throws Exception
{
String toReply = String.format("/instream/%s/%s", clientId, eventId);
String toSubscribe = String.format("/queue/subscription/%s/%s", clientId, eventId);
try
{
//subscribe to toSubscribe and listen, on message send it to toReply queue
connect().get().subscribe(toSubscribe, new StompFrameHandler()
{
public Type getPayloadType(StompHeaders stompHeaders)
{
return byte[].class;
}
public void handleFrame(StompHeaders stompHeaders, Object o)
{
logger.info("Received " + new String((byte[]) o));
messagingTemplate.convertAndSend(toReply, new String((byte[]) o));
}
});
}
catch(Exception e)
{
Object obj = new Object(){ public String getMessage(){return e.getMessage();}};
messagingTemplate.convertAndSend(toReply, obj);
}
}
}
|
package dao.impl;
import java.util.List;
import javax.annotation.Resource;
import org.springframework.stereotype.Repository;
import model.User;
import model.UserComic;
import dao.IUserComicDao;
import dao.common.AbstractHibernateDao;
@Repository("userComicDao")
public class UserComicDao extends AbstractHibernateDao<UserComic> implements
IUserComicDao {
public UserComicDao() {
super();
setClazz(UserComic.class);
}
}
|
package com.metoo.foundation.domain;
import java.math.BigDecimal;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
import com.metoo.core.constant.Globals;
import com.metoo.core.domain.IdEntity;
/**
*
* <p>
* Title: ReturnGoodsLog.java
* </p>
*
* <p>
* Description: 退货商品日志类,用来记录所有退货操作
* </p>
*
* <p>
* Copyright: Copyright (c) 2015
* </p>
*
* <p>
* Company: 沈阳网之商科技有限公司 www.koala.com
* </p>
*
* @author jinxinzhe
*
* @date 2014-5-12
*
*
* @version koala_b2b2c v2.0 2015版
*/
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
@Entity
@Table(name = Globals.DEFAULT_TABLE_SUFFIX + "returngoods_log")
public class ReturnGoodsLog extends IdEntity {
private String return_service_id; // 退货服务单号
private Long goods_id;// 退货的商品id
private String goods_name;// 商品的名称
private String goods_count;// 商品数量
private String goods_price;// 商品价格
private String goods_all_price;// 商品总价格
private String goods_mainphoto_path;// 商品图片路径
@Column(precision = 12, scale = 2)
private BigDecimal goods_commission_rate;// 退货商品的佣金比例
private String goods_return_status;// 退货商品状态 -2为超过退货时间未能输入退货物流 -1为申请被拒绝
// 1为可以退货 5为退货申请中 6为审核通过可进行退货 7为退货中
// 10为退货完成,等待退款,11为平台退款完成
private long return_order_id;// 商品对应的订单id
private int goods_type;// 商品的类型 0为自营 1为第三方经销商
private String return_content;// 退货描述
private String user_name;// 申请退货的用户姓名
private Long store_id; // 商品对应的店铺id
private Long user_id;// 所属用户id
private String self_address;// 收货时向买家发送的收货地址,买家通过此将货物发送给卖家
@Column(columnDefinition = "LongText")
private String return_express_info;// 退货物流公司信息json{"express_company_id":1,"express_company_name":"顺丰快递","express_company_mark":"shunfeng","express_company_type":"EXPRESS"}
private String express_code;// 快递号
@Column(columnDefinition = "int default 0")
private int refund_status;// 退款状态 0为未退款 1为退款完成
public ReturnGoodsLog() {
super();
// TODO Auto-generated constructor stub
}
public ReturnGoodsLog(Long id, Date addTime) {
super(id, addTime);
// TODO Auto-generated constructor stub
}
public Long getStore_id() {
return store_id;
}
public void setStore_id(Long store_id) {
this.store_id = store_id;
}
public BigDecimal getGoods_commission_rate() {
return goods_commission_rate;
}
public void setGoods_commission_rate(BigDecimal goods_commission_rate) {
this.goods_commission_rate = goods_commission_rate;
}
public int getRefund_status() {
return refund_status;
}
public void setRefund_status(int refund_status) {
this.refund_status = refund_status;
}
public String getReturn_express_info() {
return return_express_info;
}
public void setReturn_express_info(String return_express_info) {
this.return_express_info = return_express_info;
}
public String getReturn_service_id() {
return return_service_id;
}
public void setReturn_service_id(String return_service_id) {
this.return_service_id = return_service_id;
}
public Long getUser_id() {
return user_id;
}
public void setUser_id(Long user_id) {
this.user_id = user_id;
}
public String getExpress_code() {
return express_code;
}
public void setExpress_code(String express_code) {
this.express_code = express_code;
}
public String getSelf_address() {
return self_address;
}
public void setSelf_address(String self_address) {
this.self_address = self_address;
}
public String getUser_name() {
return user_name;
}
public void setUser_name(String user_name) {
this.user_name = user_name;
}
public String getReturn_content() {
return return_content;
}
public void setReturn_content(String return_content) {
this.return_content = return_content;
}
public int getGoods_type() {
return goods_type;
}
public void setGoods_type(int goods_type) {
this.goods_type = goods_type;
}
public long getReturn_order_id() {
return return_order_id;
}
public void setReturn_order_id(long return_order_id) {
this.return_order_id = return_order_id;
}
public Long getGoods_id() {
return goods_id;
}
public void setGoods_id(Long goods_id) {
this.goods_id = goods_id;
}
public String getGoods_name() {
return goods_name;
}
public void setGoods_name(String goods_name) {
this.goods_name = goods_name;
}
public String getGoods_count() {
return goods_count;
}
public void setGoods_count(String goods_count) {
this.goods_count = goods_count;
}
public String getGoods_price() {
return goods_price;
}
public void setGoods_price(String goods_price) {
this.goods_price = goods_price;
}
public String getGoods_all_price() {
return goods_all_price;
}
public void setGoods_all_price(String goods_all_price) {
this.goods_all_price = goods_all_price;
}
public String getGoods_mainphoto_path() {
return goods_mainphoto_path;
}
public void setGoods_mainphoto_path(String goods_mainphoto_path) {
this.goods_mainphoto_path = goods_mainphoto_path;
}
public String getGoods_return_status() {
return goods_return_status;
}
public void setGoods_return_status(String goods_return_status) {
this.goods_return_status = goods_return_status;
}
}
|
package com.gamzat;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner Bender = new Scanner(System.in);
double FirstNumber;
double SecondNumber;
double Result;
//double FirstNumber, SecondNumber, Result
System.out.println("Введите первое число: ");
FirstNumber = Bender.nextDouble();
System.out.println("Введите второе число: ");
SecondNumber = Bender.nextDouble();
Result = FirstNumber + SecondNumber;
System.out.println("Сумма равна: " + Result);
}
}
|
package com.strategy.entity;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.Date;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Account {
String strategy;
String email;
Date placementDate;
OfferTag offerTag;
TreatmentTool treatmentTool;
StrategyId strategyId;
}
|
package com.mytechia.robobo.framework.hri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import com.mytechia.robobo.framework.RoboboManager;
import com.mytechia.robobo.framework.activity.DefaultRoboboActivity;
import com.mytechia.robobo.framework.exception.ModuleNotFoundException;
import com.mytechia.robobo.hri.R;
import com.mytechia.robobo.hri.speech.production.ITtsVoice;
import com.mytechia.robobo.hri.speech.production.VoiceNotFoundException;
import com.mytechia.robobo.hri.speech.production.android.AndroidSpeechProductionModule;
import com.mytechia.robobo.hri.speech.production.android.TtsVoice;
import java.util.Collection;
public class MainActivityTTS extends AppCompatActivity {
//TODO MIRAR SI VOZ ESTA DESCARGADA
int index =0;
TtsVoice actualVoice = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/*final AndroidSpeechProductionModule aspm = new AndroidSpeechProductionModule();
try {
aspm.startupTest(this.getApplicationContext());
} catch (InternalErrorException e) {
e.printStackTrace();
}*/
AndroidSpeechProductionModule speechM = null;
try {
speechM = RoboboManager.getInstance().getModuleInstance(AndroidSpeechProductionModule.class);
} catch (ModuleNotFoundException e) {
e.printStackTrace();
}
final AndroidSpeechProductionModule aspm = speechM;
final TextView tv = (TextView) findViewById(R.id.textView);
final EditText inputText = (EditText) findViewById(R.id.editText);
final Button nextButton = (Button) findViewById(R.id.nextButton);
final Button prevButton = (Button) findViewById(R.id.prevButton);
final Button talkButton = (Button) findViewById(R.id.talkButton);
final Button setButton = (Button) findViewById(R.id.setVoiceButton);
// final ArrayList<String> test =new ArrayList<String>(aspm.getVoices());
try {
talkButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
aspm.sayText(inputText.getText().toString(), AndroidSpeechProductionModule.PRIORITY_HIGH);
inputText.clearComposingText();
}
});
nextButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
final Collection<ITtsVoice> voiceCol =aspm.getVoices();
if (index < voiceCol.size()) {
index = index + 1;
}
TtsVoice auxVoice =(TtsVoice) (voiceCol.toArray()[index]);
tv.setText(auxVoice.getVoiceName());
actualVoice = auxVoice;
}
});
prevButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
final Collection<ITtsVoice> voiceCol =aspm.getVoices();
if (index != 0) {
index = index - 1;
}
TtsVoice auxVoice =(TtsVoice) (voiceCol.toArray()[index]);
tv.setText(auxVoice.getVoiceName());
actualVoice = auxVoice;
}
});
setButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try {
aspm.selectVoice(actualVoice.getVoiceName());
} catch (VoiceNotFoundException vnfe){
tv.setText("Voice not found :(");
}
}
});
} catch (NullPointerException e) {
e.printStackTrace();
}
}
}
|
package com.txxlc.SystemConfig.securityConfig.Properties;
public class ImageCodeproperties {
private int width = 67;
private int height = 23;
private int length = 4;
private int expirIN = 60;
private String url = "/login";//需要验证码的路径
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public int getWidth() {
return width;
}
public void setWidth(int width) {
this.width = width;
}
public int getHeight() {
return height;
}
public void setHeight(int height) {
this.height = height;
}
public int getLength() {
return length;
}
public void setLength(int length) {
this.length = length;
}
public int getExpirIN() {
return expirIN;
}
public void setExpirIN(int expirIN) {
this.expirIN = expirIN;
}
}
|
package com.capgemini.swissbank.ui;
import java.util.List;
import java.util.Scanner;
import com.capgemini.swissbank.bean.AccMasterBean;
import com.capgemini.swissbank.bean.AccountType;
import com.capgemini.swissbank.bean.CustomerBean;
import com.capgemini.swissbank.bean.PayeeBean;
import com.capgemini.swissbank.bean.TransactionBean;
import com.capgemini.swissbank.bean.UserTable;
import com.capgemini.swissbank.exception.BankException;
import com.capgemini.swissbank.service.AdminServiceImpl;
import com.capgemini.swissbank.service.CustomerServiceImpl;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
public class Bankapp {
public static Scanner in=new Scanner(System.in);
public static Logger logger=Logger.getRootLogger();
public static void main(String[] args) {
PropertyConfigurator.configure("resources//log4j.properties");
int uid;
String password;
UserTable validUser = null;
boolean userCheck = false;
boolean isOpen=false;
char uType;
int count=0;
CustomerServiceImpl serviceCustomer = new CustomerServiceImpl();
//Scanner input = new Scanner(System.in);
System.out.println(
"+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
System.out.println();
System.out.println(" MMMMMMMMMMMMMMMMMMMMWOc.,cxXMMMMMMMMMMMMMMMMMMMMMM CCCCCCCCCCCCC GGGGGGGGGGGGG \n"
+ " MMMMMMMMMMMMMMMMMWKd; .ckNMMMMMMMMMMMMMMMMMMM CCC::::::::::::C GGG::::::::::::G \n"
+ " MMMMMMMMMMMMMWXkl,. 'cxKNMMMMMMMMMMMMMMM CC:::::::::::::::C GG:::::::::::::::G \n"
+ " MMMMMMMMMNKkl;. .'cdOXWMMMMMMMMMM C:::::CCCCCCCC::::C G:::::GGGGGGGG::::G \n"
+ " MMMMWXko:'. .;lx0NMMMMMM C:::::C CCCCCC G:::::G GGGGGG \n"
+ " MMXx:. .,l0WMMM C:::::C G:::::G \n"
+ " WO, .lXMM C:::::C G:::::G \n"
+ " Nc .kMM C:::::C G:::::G GGGGGGGGGG \n"
+ " M0;. .dNMM C:::::C G:::::G G::::::::G \n"
+ " MMN0o:'.. ..'' .,.. ..;lkXMMMM C:::::C G:::::G GGGGG::::G \n"
+ " MMMMMMNX0OkxxxxkO0KO; .dKKOOkxxxkk0KNWMMMMMMM C:::::C G:::::G G::::G \n"
+ " MMMMMMMMMMMMMMMMNOl. ;xXWMMMMMMMMMMMMMMMMM C:::::C CCCCCC G:::::G G::::G \n"
+ " MMMMMMMMMMMMMNOl;. .':dKMMMMMMMMMMMMMMM C:::::CCCCCCCC::::C G:::::GGGGGGGG::::G \n"
+ " MMMMMMMMMMMMMNOdddddddddddddddddddKMMMMMMMMMMMMMMM CC:::::::::::::::C GG:::::::::::::::G \n"
+ " CCC::::::::::::C GGG::::::GGG:::G \n"
+ " CCCCCCCCCCCCC GGGGGG GGGG \n");
System.out.println(
"+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
System.out.println();
System.out.println("-----------");
System.out.println("WELCOME");
System.out.println("-----------");
do {
System.out.println("Please Enter User ID to login:");
uid = in.nextInt();
in.nextLine();
try {
boolean isValid=serviceCustomer.validateUser(uid);
if(isValid){
isOpen=serviceCustomer.getUserStatus(uid);
if(isOpen){
do{
System.out.println("Please Enter your password: (forgot password ? press Y/y)");
password = in.nextLine();
//if user forgets password
if(password.equalsIgnoreCase("Y"))
{
String[] secret=serviceCustomer.getSecretQuestion(uid);
System.out.println("Please Answer the secret question: \n"+secret[0]);
String secretAnswer = in.nextLine();
if(secretAnswer.equals(secret[1]))
{
serviceCustomer.changePassword(uid, "sbq500#");
System.out.println("Your password is sbq500#\nUse this to login.\nChange your password on next login");
}
else{
try {
serviceCustomer.updateLockStatus(uid);
System.out.println("Your answer is wrong.\nLooks like an unauthorised access......... Your account has been locked\n Please Contact the Admin for further assistance");
System.exit(-1);
} catch (BankException e) {
logger.error(e.getMessage());
e.printStackTrace();
}
}
}
else{
validUser=serviceCustomer.validateUser(uid, password);
if (validUser != null) {
userCheck = true;
}
else {
count++;
if(count<3&&count>0){
System.out.println("Incorrect password entered "+(3-count)+" tries left ");
}
else{
try {
serviceCustomer.updateLockStatus(uid);
System.out.println("Sorry Your account got locked\nContact the Admin for further assistance");
System.exit(-1);
} catch (BankException e) {
logger.error(e.getMessage());
e.printStackTrace();
}
}
}
}
}while(count<3&&userCheck==false);
}
else{
System.out.println("Sorry Your account is locked.\nPlease Contact Admin for further assistance");
System.exit(-1);
}
}
else{
System.out.println("Invalid User ID");
}
} catch (BankException e) {
logger.error(e.getMessage());
e.printStackTrace();
}
} while (userCheck == false);
if (validUser.getType().equals("A")) {
openAdminPage(validUser); // opens admin page
} else {
openUserPage(validUser); // opens customer page
}
}
private static void openAdminPage(UserTable admin) {
int choice = 0;
System.out.println("Welcome back" + admin.getUserName() );
System.out.println("What would you like to do today ?");
do {
System.out.println("1. Create Account");
System.out.println("2. View Transactions");
System.out.println("3. Exit");
choice=in.nextInt();
in.nextLine();
switch (choice) {
case 1:
createAccount(admin);
break;
case 2:
viewTransactions(admin);
case 3:
System.out.println("Thank you! Have a nice day.");
break;
default:
System.out.println("Wrong option entered please try again");
break;
}
} while (choice !=3 );
}
private static void openUserPage(UserTable user) {
int selection = 0;
System.out.println("Welcome " + user.getUserName() + " please enter your choice");
//Scanner input1 = new Scanner(System.in);
do {
// some cosmetics to be done here
System.out.println("1. View Bank statement");
System.out.println("2. Change password");
System.out.println("3. Change address and/or phone number");
System.out.println("4. Fund transfer");
System.out.println("5. Issue new cheque");
System.out.println("6. Track chequebook/card delivery status");
System.out.println("7. Exit");
selection = in.nextInt();
in.nextLine();
switch (selection) {
case 1:
//System.out.println("here's your statement");
showBankStatement(user);
break;
case 2:
//System.out.println("password changed");
changePassword(user);
break;
case 3:
//System.out.println("address and phone number changed");
changeDetails(user);
break;
case 4:
//System.out.println("fund transferred to blah");
fundTransfer(user);
break;
case 5:
//System.out.println("new cheque");
newChequeBook(user);
break;
case 6:
trackStatus(user);
break;
case 7:
System.out.println("Thank you have a nice day :-)");
break;
default:
System.out.println("Invalid option entered. Please try again");
break;
}
} while (selection != 7);
//input1.close();
}
private static void showBankStatement(UserTable user) {
int choice = 0;
//Scanner sc = new Scanner(System.in);
do {
System.out.println("1. Mini bank statement");
System.out.println("2. Detailed statement");
choice = in.nextInt();
switch (choice) {
case 1:
miniBankStatement(user);
break;
case 2:
detailedBankStatement(user);
break;
default:
System.out.println("Invalid option");
System.out.println("please try again");
break;
}
} while (choice != 1 && choice != 2);
//sc.close();
}
private static void miniBankStatement(UserTable user) {
CustomerServiceImpl serviceCustomer = new CustomerServiceImpl();
int accId = user.getAccId();
List<TransactionBean> list = null;
try {
list = serviceCustomer.viewMiniStatement(accId);
} catch (BankException e) {
logger.error(e.getMessage());
e.printStackTrace();
}
for (TransactionBean transactionBean : list) {
System.out.println(transactionBean);
}
}
private static void detailedBankStatement(UserTable user) {
CustomerServiceImpl serviceCustomer = new CustomerServiceImpl();
int accId = user.getAccId();
List<TransactionBean> list = null;
try {
list = serviceCustomer.viewDetailedStatement(accId);
} catch (BankException e) {
logger.error(e.getMessage());
e.printStackTrace();
}
for (TransactionBean transactionBean : list) {
System.out.println(transactionBean);
}
}
private static void changePassword(UserTable user) {
int accId = user.getAccId();
String checkOldPwd = user.getPassword();
String checkNewPwd;
String oldPwd;
String newPwd;
boolean changeStatus = false;
CustomerServiceImpl serviceCustomer = new CustomerServiceImpl();
//Scanner sc1 = new Scanner(System.in);
System.out.println("Please enter your current password");
oldPwd = in.nextLine();
// compare if he's entered his old pwd right
// this validation should be performed in the service layer
Out:
if (checkOldPwd.equals(oldPwd)) {
System.out.println("Enter your new password");
newPwd = in.nextLine();
do {
System.out.println("Reenter your new password");
checkNewPwd = in.nextLine();
if(!(newPwd.equals(checkNewPwd))) {
System.out.println("passwords don't match ! ");
System.out.println("Please check and try again");
}
} while (!(newPwd.equals(checkNewPwd)));
System.out.println("Are you sure you want to continue ? (y/n)");
String answer=in.nextLine();
if(answer.equals("Y")||answer.equals("y"))
{
try {
changeStatus = serviceCustomer.changePassword(accId, oldPwd, newPwd);
} catch (BankException e) {
logger.error(e.getMessage());
e.printStackTrace();
}
if (changeStatus) {
System.out.println("Password successfully changed");
} else {
System.out.println("Unable to change password");
}
}else
break Out;
} else {
System.out.println("Unable to proceed further as wrong password is entered");
}
//sc1.close();
}
private static void changeDetails(UserTable user) {
int choice = 0;
//Scanner sc2 = new Scanner(System.in);
do {
System.out.println("1. Change address");
System.out.println("2. Change phone number");
choice = in.nextInt();
in.nextLine();
switch (choice) {
case 1:
changeAddress(user);
break;
case 2:
changePhoneNumber(user);
break;
default:
System.out.println("Invalid option !");
System.out.println("please try again");
break;
}
}
while (choice != 1 && choice != 2);
//sc2.close();
}
private static void changeAddress(UserTable user) {
int accId = user.getAccId();
String newAddress;
boolean isChanged = false;
CustomerServiceImpl serviceCustomer = new CustomerServiceImpl();
//Scanner sc = new Scanner(System.in);
System.out.println("Please enter your new address");
newAddress = in.nextLine();
try {
isChanged = serviceCustomer.changeAddress(accId, newAddress);
} catch (BankException e) {
logger.error(e.getMessage());
e.printStackTrace();
}
if(isChanged) {
System.out.println("New address updated successfully");
}else {
System.out.println("Something went wrong. Could not update the address. Please try after sometime");
}
//sc.close();
}
private static void changePhoneNumber(UserTable user) {
int accId = user.getAccId();
String newPhoneNumber;
boolean isChanged = false;
CustomerServiceImpl serviceCustomer = new CustomerServiceImpl();
//Scanner sc = new Scanner(System.in);
System.out.println("Please enter your new Phone number");
newPhoneNumber = in.nextLine();
try {
isChanged = serviceCustomer.changePhoneNumber(accId, newPhoneNumber);
} catch (BankException e) {
logger.error(e.getMessage());
e.printStackTrace();
}
if(isChanged) {
System.out.println("New phone number updated successfully");
}else {
System.out.println("Something went wrong. Could not update the phone number. Please try after sometime");
}
//sc.close();
}
private static void fundTransfer(UserTable user) {
CustomerServiceImpl serviceCustomer = new CustomerServiceImpl();
System.out.println("Please Choose the type of fund transfer : ");
System.out.println("1. With in the Bank");
System.out.println("2. To other Banks");
int choice=in.nextInt();
in.nextLine();
switch (choice) {
case 1:
inFundTransfer(user);
break;
case 2:
System.out.println("1.Add Payee");
System.out.println("2.Select Payee");
int key=in.nextInt();
in.nextLine();
switch (key) {
case 1:
System.out.println("Enter Payee Account Id:");
int payeeAccountId=in.nextInt();
in.nextLine();
System.out.println("Enter Payee Nickname:");
String nickName=in.nextLine();
try {
boolean isInserted=serviceCustomer.insertPayee(user.getAccId(), payeeAccountId, nickName);
if(isInserted)
System.out.println("Payee added successfully.");
} catch (BankException e) {
logger.error(e.getMessage());
e.printStackTrace();
}
break;
case 2:
System.out.println("The list of payees registered are:");
try {
List<PayeeBean> payeeList=serviceCustomer.viewPayee(user.getAccId());
for (PayeeBean payeeBean : payeeList) {
System.out.println(payeeBean);
}
System.out.println("Please Enter Transaction password");
String transactionPassword=in.nextLine();
if(serviceCustomer.validateTransactionPassword(transactionPassword, user))
{
System.out.println("Please Enter payee AccountID");
int payeeAccountNumber=in.nextInt();
in.nextLine();
System.out.println("Please Enter the amount");
double transactionAmount=in.nextDouble();
in.nextLine();
if(serviceCustomer.validateTransactionAmount(transactionAmount)){
double balance=serviceCustomer.outFundTransfer(user.getAccId(), payeeAccountNumber, transactionPassword, transactionAmount);
System.out.println("Transaction successful\nyour current balance is "+balance);
}
else{
System.out.println("Can not transact more than Rs. 1000000");
}
}
else{
System.out.println("Invalid Transaction password");
}
} catch (BankException e) {
logger.error(e.getMessage());
e.printStackTrace();
}
break;
default:
System.out.println("Invalid option entered. Please try again ");
break;
}
break;
default:
break;
}
}
private static void newChequeBook(UserTable user) {
CustomerServiceImpl serviceCustomer = new CustomerServiceImpl();
try {
int requisitionId=serviceCustomer.generateCheque(user.getAccId());
System.out.println("Your requisition id is"+requisitionId);
} catch (BankException e) {
logger.error(e.getMessage());
e.printStackTrace();
}
}
private static void trackStatus(UserTable user) {
CustomerServiceImpl serviceCustomer = new CustomerServiceImpl();
System.out.println("Please enter the requisition Id");
int requisitionId=in.nextInt();
in.nextLine();
try {
String status=serviceCustomer.trackStatus(requisitionId);
System.out.println("Your Service status is "+status);
} catch (BankException e) {
logger.error(e.getMessage());
e.printStackTrace();
}
}
private static void inFundTransfer(UserTable user){
CustomerServiceImpl serviceCustomer = new CustomerServiceImpl();
System.out.println("Please Enter payee Account Id");
int accountIdTo=in.nextInt();
in.nextLine();
System.out.println("Please Enter Transaction amount");
double transactionAmount=in.nextDouble();
in.nextLine();
try {
double balance=serviceCustomer.inFundTransfer(accountIdTo, user.getAccId(), transactionAmount);
System.out.println("Transaction is successful.\nYour Balance is "+balance);
} catch (BankException e) {
logger.error(e.getMessage());
e.printStackTrace();
}
}
private static void createAccount(UserTable admin){
CustomerBean newCustomer = new CustomerBean() ;
AccMasterBean masterSheet = new AccMasterBean();
AdminServiceImpl serviceAdmin = new AdminServiceImpl();
UserTable newValidCustomer = new UserTable();
String addLine1;
String addLine2;
String addLine3;
List<String> errorList = null;
do {
errorList = null;// check to done here if empty or null
System.out.println("Please enter the following details to create the account");
System.out.println("Enter the name of the customer");
newCustomer.setCustomerName(in.nextLine());
System.out.println("Enter the address (line 1)"); // sad part is that address is in one line
addLine1 = in.nextLine();
System.out.println("Enter the adress (line 2)");
addLine2 = in.nextLine();
System.out.println("Enter the address (line 3)");
addLine3 = in.nextLine();
newCustomer.setAddress(addLine1 + "\n" + addLine2 + "\n" + addLine3);
System.out.println("Enter phone number");
newCustomer.setPhoneNumber(in.nextLine());
System.out.println("Enter emailId");
newCustomer.setEmail(in.nextLine());
System.out.println("Enter the type of account (savings/current)");
// do cross check this statement later
masterSheet.setType(AccountType.valueOf(in.nextLine()));
System.out.println("Enter the opening balance.");
System.out.println(" Minimum balance should be 3000 Rs");
masterSheet.setAccBalance(in.nextDouble());
in.nextLine();
System.out.println("Enter PAN card number");
newCustomer.setPanNUm(in.nextLine());
// pan number details not entered
errorList = serviceAdmin.isValidNewCustomer(newCustomer, masterSheet);
if (!errorList.isEmpty()) {
System.out.println("Customer details entered are not valid");
System.out.println("Please refer the errors and reenter the details ");
for (String errors : errorList) {
System.out.println(errors);
}
}
} while (!errorList.isEmpty());
try {
newValidCustomer = serviceAdmin.createUser(masterSheet, newCustomer);
System.out.println("account created successfully!!!");
System.out.println("Account number : " + newValidCustomer.getAccId());
System.out.println("Custome name :" + newCustomer.getCustomerName());
// why the heck should admin know dummy password?
// to do generate password of 8 characters write a seperate method
System.out.println(" dummy password has been sent to " + newCustomer.getPhoneNumber());
} catch (BankException e) {
logger.error(e.getMessage());
e.printStackTrace();
}
}
private static void viewTransactions(UserTable admin){
int choice = 0;
AdminServiceImpl serviceAdmin = new AdminServiceImpl();
List<TransactionBean> list = null;
do {
System.out.println("Enter the type of transactions to be viewed");
System.out.println("1. daily transction");
System.out.println("2. weekly transaction");
System.out.println("3. monthly transcations");
choice = in.nextInt();
in.nextLine();
switch (choice) {
case 1:
try {
list = serviceAdmin.getTransactionsDaily();
if(list==null){
System.out.println("No transactions performed today");
}
else{
for (TransactionBean transactionBean : list) {
System.out.println(transactionBean);
}
}
} catch (BankException e) {
logger.error(e.getMessage());
e.printStackTrace();
}
break;
case 2:
try {
list = serviceAdmin.getTransactionsWeekly();
if(list==null){
System.out.println("No transactions performed in this week");
}
else{
for (TransactionBean transactionBean : list) {
System.out.println(transactionBean);
}
}
} catch (BankException e) {
logger.error(e.getMessage());
e.printStackTrace();
}
break;
case 3:
try {
list = serviceAdmin.getTransactionsMonthly();
if(list==null){
System.out.println("No transactions performed in this month");
}
else{
for (TransactionBean transactionBean : list) {
System.out.println(transactionBean);
}
}
} catch (BankException e) {
logger.error(e.getMessage());
e.printStackTrace();
}
break;
default:
System.out.println("Wrong option entered, please try again");
break;
}
} while (choice!=1 || choice!=2 || choice!=3);
}
}
|
package ui;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Point;
import javax.swing.ImageIcon;
import javax.swing.JPanel;
public class JPanelStTwo extends JPanel implements Runnable{
private static final long serialVersionUID = 1L;
private JPanelSettingNext jpstn;
private JMainFrame jMainFrame;
Point[] points=new Point[]{new Point(0,0),new Point(200,0)};
private int blockStyle;
private ImageIcon[] IMG_BLOCK=new ImageIcon[]{new ImageIcon("graphics/setting/block1.png"),new ImageIcon("graphics/setting/block2.png")};
public JPanelStTwo(JPanelSettingNext jpstn,JMainFrame jframe){
this.jMainFrame = jframe;
this.jpstn = jpstn;
this.setLayout(null);
this.setBounds(168,195,185,43);
this.setVisible(true);
blockStyle = jMainFrame.getBlockStyle();
jpstn.add(this);
this.repaint();
}
public void paintComponent(Graphics g){
g.drawImage(IMG_BLOCK[0].getImage(),points[0].x,points[0].y,null);
g.drawImage(IMG_BLOCK[1].getImage(),points[1].x,points[1].y,null);
}
public void run(){
if(blockStyle==0){
while(points[1].x>0){
points[1].x-=10;
points[0].x-=10;
this.repaint();
jpstn.repaint();
try {
Thread.sleep(15);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
points[0].x = -200;
points[1].x = 0;
}else{
while(points[1].x<200){
points[1].x+=10;
points[0].x+=10;
this.repaint();
jpstn.repaint();
try {
Thread.sleep(15);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
points[0].x = 0;
points[1].x = 200;
}
blockStyle = 1-blockStyle;
jMainFrame.setBlockStyle(blockStyle);
}
}
|
package mx.redts.adendas.service;
import java.util.Date;
import java.util.List;
import mx.redts.adendas.dao.IOpenBravoDAO;
import mx.redts.adendas.model.FeDetalle;
import mx.redts.adendas.model.FeDirFiscal;
import mx.redts.adendas.model.FeDirReceptor;
import mx.redts.adendas.model.FeEncabezado;
import mx.redts.adendas.model.FeLugarEntrega;
import mx.redts.adendas.model.FeSumario;
/**
*
* User Service
*
* @author Andres Cabrera
* @since 25 Mar 2012
* @version 1.0.0
*
*/
public class OBService implements IOBService {
private IOpenBravoDAO openBravoDAO;
public List<FeDetalle> findDetalle(String idob3) {
return openBravoDAO.findDetalle(idob3);
}
@Override
public List<FeDirFiscal> findDirFiscal(String idob3) {
// TODO Auto-generated method stub
return openBravoDAO.findDirFiscal(idob3);
}
@Override
public List<FeDirReceptor> findDirReceptor(String idob3) {
// TODO Auto-generated method stub
return openBravoDAO.findDirReceptor(idob3);
}
@Override
public List<FeEncabezado> findFactHeaderBy(String org, String cliente,
String folio, String tipoDoc, Date fechaInicial, Date fechafinal) {
// TODO Auto-generated method stub
return openBravoDAO.findFactHeaderBy(org, cliente, folio, tipoDoc,
fechaInicial, fechafinal);
}
public List<FeEncabezado> findFactHeaderByID(String idOb3) {
// TODO Auto-generated method stub
return openBravoDAO.findFactHeaderByID(idOb3);
}
@Override
public List<FeLugarEntrega> findLugarEntrega(String idob3) {
// TODO Auto-generated method stub
return openBravoDAO.findLugarEntrega(idob3);
}
@Override
public List<FeSumario> findSumario(String idob3) {
// TODO Auto-generated method stub
return openBravoDAO.findSumario(idob3);
}
/**
* @return the openBravoDAO
*/
public IOpenBravoDAO getOpenBravoDAO() {
return openBravoDAO;
}
/**
* @param openBravoDAO
* the openBravoDAO to set
*/
public void setOpenBravoDAO(IOpenBravoDAO openBravoDAO) {
this.openBravoDAO = openBravoDAO;
}
} |
package gamez;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Game extends JPanel {
private Hamdy hamdy;
private Assignment a1, a2, a3;
private Boss boss;
private BG bg;
private int speed;
public Game() {
speed = 10;
setSize(450,750);
hamdy = new Hamdy(0,650);
a1 = new Assignment(150, 690, 580, 690);
a2 = new Assignment(150, 425, 350, 425);
a3 = new Assignment(150, 80, 0, 80);
boss = new Boss(0,20);
bg = new BG();
add(bg);
add(hamdy);
add(a1);
add(a2);
add(a3);
add(boss);
setFocusable(true);
requestFocusInWindow();
KeyListener controls = new Controls();
addKeyListener(controls);
ActionListener time = new TimeListener();
Timer t = new Timer(33, time);
t.start();
}
public boolean checkCollision(Assignment a) {
if(((hamdy.getXP()+50)>a.getXP() && hamdy.getXP()<(a.getXP()+85)) && ((a.getYP()+18)>hamdy.getYP() && a.getYP()<hamdy.getYP()+60)) {
return true;
}
return false;
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
bg.paint(g);
drawLevel(g);
a1.paint(g);
a2.paint(g);
a3.paint(g);
boss.paint(g);
hamdy.paint(g);
}
public void drawLevel(Graphics g) {
g.setColor(Color.BLACK);
g.fillRect(0, 100, 450, 20);
g.fillRect(0, 215, 450, 20);
g.fillRect(0, 330, 450, 20);
g.fillRect(0, 445, 450, 20);
g.fillRect(0, 560, 450, 20);
g.setColor(Color.RED);
g.fillRect(350, 560, 15, 150);
g.fillRect(50, 445, 15, 115);
g.fillRect(325, 330, 15, 115);
g.fillRect(130, 215, 15, 115);
g.fillRect(400, 100, 15, 115);
}
class Controls implements KeyListener {
public void keyPressed(KeyEvent e) {
if(e.getKeyCode()==39) {
if(hamdy.checkWin()) {
JOptionPane.showMessageDialog(null,"Congrats, you won against the evil assignments!");
System.exit(0);
}
if(hamdy.checkSecretWin()) {
JOptionPane.showMessageDialog(null,"You ran away from the assignments alright :) !");
System.exit(0);
}
if(!hamdy.checkLadder()) {
hamdy.moveHamdy(speed, 0);
hamdy.setRight(true);
hamdy.setHam();
repaint();
}
}
else if(e.getKeyCode()==37) {
if(hamdy.checkWin()) {
JOptionPane.showMessageDialog(null,"Congrats, you won against the evil assignments!");
System.exit(0);
}
if(hamdy.checkSecretWin()) {
JOptionPane.showMessageDialog(null,"You ran away from the assignments alright :) !");
System.exit(0);
}
if(!hamdy.checkLadder()) {
hamdy.moveHamdy(-speed, 0);
hamdy.setRight(false);
hamdy.setHam();
repaint();
}
}
else if(e.getKeyCode()==38) {
if(hamdy.checkLadder()) {
hamdy.moveHamdy(0,-speed/2);
repaint();
}
}
else if(e.getKeyCode()==40) {
if(hamdy.checkLadder()) {
hamdy.moveHamdy(0,speed/2);
repaint();
}
}
}
public void keyReleased(KeyEvent e) {
hamdy.moveHamdy(0,0);
}
public void keyTyped(KeyEvent e) {}
}
class TimeListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
a1.moveAss();
a2.moveAss();
a3.moveAss();
if(checkCollision(a1)) {
JOptionPane.showMessageDialog(null,"You Lose...");
System.exit(0);
}
if(checkCollision(a2)) {
JOptionPane.showMessageDialog(null,"You Lose...");
System.exit(0);
}
if(checkCollision(a3)) {
JOptionPane.showMessageDialog(null,"You Lose...");
System.exit(0);
}
repaint();
}
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.