blob_id
stringlengths
40
40
language
stringclasses
1 value
repo_name
stringlengths
5
132
path
stringlengths
2
382
src_encoding
stringclasses
34 values
length_bytes
int64
9
3.8M
score
float64
1.5
4.94
int_score
int64
2
5
detected_licenses
listlengths
0
142
license_type
stringclasses
2 values
text
stringlengths
9
3.8M
download_success
bool
1 class
e3d9921ec6c1ee76e33e17dc15abbc7b64052757
Java
houssam313/ControleTechnique
/src/main/java/fr/cda/controle/service/RecuService.java
UTF-8
1,729
2.25
2
[]
no_license
package fr.cda.controle.service; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import fr.cda.controle.beans.Recu; import fr.cda.controle.converter.RecuConverter; import fr.cda.controle.dto.RecuDTO; import fr.cda.controle.errors.AlreadyExistException; import fr.cda.controle.errors.NotFoundException; import fr.cda.controle.repositories.ExamenRepository; import fr.cda.controle.repositories.RecuRepository; @Service public class RecuService { @Autowired private RecuRepository recuRepository; @Autowired private RecuConverter recuConverter; @Autowired private ExamenRepository examenRepository; public RecuDTO getRecu(int id ) throws NotFoundException { Recu recu= recuRepository.findById(id).get(); if(recu== null) { throw new NotFoundException(); } return recuConverter.EntityToDTO(recu); } public List<RecuDTO> getAllRecu() throws NotFoundException { List<Recu> listRecu = recuRepository.findAll(); if(listRecu == null) { throw new NotFoundException(); } return recuConverter.EntityToDTO(listRecu); } public RecuDTO addRecu(RecuDTO recuDTO) throws AlreadyExistException{ Recu recu = recuRepository.findByDateAndExamen(recuDTO.getDate(),examenRepository.findById(recuDTO.getIdexamen()).get() ); if(recu == null) { recuRepository.save(recuConverter.dTOToEntity(recuDTO)); } else { throw new AlreadyExistException(); } return recuDTO; } public void delete(int id) throws NotFoundException { Recu recu = recuRepository.findById(id).get(); if(recu == null) { throw new NotFoundException(); } else { recuRepository.deleteById(id); } } }
true
7cb7495a268e66c4b72cc62d38a58d70688f0747
Java
Java-March-2021/JoshM-Assignments
/03-java-spring/02-spring-data-i/03-languages/languages copy/src/main/java/com/example/languages/controllers/HomeController.java
UTF-8
2,361
2.328125
2
[]
no_license
package com.example.languages.controllers; import java.util.List; import javax.validation.Valid; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import com.example.languages.models.Language; import com.example.languages.services.LanguageService; @Controller @RequestMapping("/languages") public class HomeController { @Autowired private LanguageService lService; @GetMapping("") public String index(Model viewModel) { List<Language> languages= this.lService.getAllLanguages(); viewModel.addAttribute("allLanguages", languages); return "index.jsp"; } @GetMapping("/add") public String add(@ModelAttribute("language") Language language) { return "index.jsp"; } @PostMapping("/addLanguage") public String addLanguage(@Valid @ModelAttribute("language") Language language, BindingResult result) { if(result.hasErrors()) { return "add-language"; }else { this.lService.createLanguage(language); return "redirect:/"; } } @GetMapping("{id}") public String show(@PathVariable("id") Long id, Model viewModel) { viewModel.addAttribute("language", this.lService.getOneLanguage(id)); return "show.jsp"; } @GetMapping("/delete/{id}") public String delete(@PathVariable("id") Long id) { this.lService.deleteLanguage(id); return "redirect:/"; } @GetMapping("/edit/{id}") public String edit(@ModelAttribute("language") Language language, Model viewModel,@PathVariable("id") Long id) { viewModel.addAttribute("language", this.lService.getOneLanguage(id)); return"edit.jsp"; } @PostMapping("/edit/{id}") public String postEdit(@Valid @ModelAttribute("language") Language language, BindingResult result, Model viewModel, @PathVariable("id") Long id) { if(result.hasErrors()) { viewModel.addAttribute("language", this.lService.getOneLanguage(id)); return "edit.jsp"; } this.lService.updateLanguage(id, language); return "redirect:/"; } }
true
fe069724c5901a3cf8a6a0a28cc074ab8c4d6ce3
Java
BeaconCGQ/JavaSenior
/exercise1/src/exer3/Demo.java
UTF-8
634
3.25
3
[]
no_license
package exer3; public class Demo { public static void main(String[] args) { Integer i1 = 128; Integer i2 = 128; int i3 = 128; int i4 = 128; System.out.println(i1 == i2); System.out.println(i3 == i4); System.out.println(i1 == i3);//包装类自动拆箱 Base b2 = new Sub(); } } class Base{ Base(){ method(100); } public void method(int i){ System.out.println("base : " + i); } } class Sub extends Base{ Sub(){ super.method(70); } public void method(int j){ System.out.println("sub : " + j); }}
true
79078a0fd7f08e6ec3b6df00c7fde12dfb19331c
Java
Sada28/Quiz
/app/src/main/java/com/example/QuizApp/MainActivity.java
UTF-8
5,440
2.546875
3
[]
no_license
package com.example.QuizApp; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.RadioButton; import android.widget.RadioGroup; import android.widget.TextView; public class MainActivity extends AppCompatActivity { EditText ed1; TextView tv1, tv2, tv3; RadioButton a, b, c, d; Button bt; RadioGroup rg; int q, s; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ed1 = (EditText) findViewById(R.id.name); tv1 = (TextView) findViewById(R.id.ques); tv2 = (TextView) findViewById(R.id.response); tv3 = (TextView) findViewById(R.id.score); rg = (RadioGroup) findViewById(R.id.optionGroup); a = (RadioButton) findViewById(R.id.option1); b = (RadioButton) findViewById(R.id.option2); c = (RadioButton) findViewById(R.id.option3); d = (RadioButton) findViewById(R.id.option4); bt = (Button) findViewById(R.id.next); q = 0; s = 0; } public void quiz(View v) { switch (q) { case 0: { rg.setVisibility(View.VISIBLE); a.setChecked(false); b.setChecked(false); c.setChecked(false); d.setChecked(false); tv2.setText(""); tv3.setText(""); a.setEnabled(true); b.setEnabled(true); c.setEnabled(true); d.setEnabled(true); ed1.setEnabled(true); bt.setText("Next"); s = 0; tv1.setText("1.When did India its independece?"); a.setText("1847"); b.setText("1947"); c.setText("1850"); d.setText("1950"); q = 1; break; } case 1: { ed1.setEnabled(false); tv1.setText("2.Who is India's father of nation?"); a.setText("Mahatma Gandhi"); b.setText("Lal Bahadur Shashtri"); c.setText("Jawaharlal Nehru"); d.setText("Subhash Chandra Bose"); if (b.isChecked()) { tv2.setText("Right Answer"); s = s + 10; } else { tv2.setText("Wrong Answer B was Right Answer"); } q = 2; a.setChecked(false); b.setChecked(false); c.setChecked(false); d.setChecked(false); break; } case 2: { tv1.setText("3.Who was the first lady CM of Uttar Pradesh?"); a.setText("Pratibha Singh Patil"); b.setText("Indira Gandhi"); c.setText("Sucheta Kriplani"); d.setText("Mayawati"); if (a.isChecked()) { s = s + 10; tv2.setText("Right Answer"); } else { tv2.setText("Wrong Answer A was Right Answer"); } q = 3; a.setChecked(false); b.setChecked(false); c.setChecked(false); d.setChecked(false); break; } case 3: { tv1.setText("4.Who was first Indian lady to go in space?"); a.setText("Mayawati"); b.setText("Kalpana Chawla"); c.setText("Kiran Bedi"); d.setText("Sunita Williams"); if (c.isChecked()) { s = s + 10; tv2.setText("Right Answer"); } else { tv2.setText("Wrong Answer C was Right Answer"); } q = 4; a.setChecked(false); b.setChecked(false); c.setChecked(false); d.setChecked(false); break; } case 4: { tv1.setText("5.Who designed India's national flag?"); a.setText("Rahul Gandhi"); b.setText("Bankim Chandra Chatterjee"); c.setText("Ishwar Chandra Vidyasagar"); d.setText("Pingali Venkayya"); if (b.isChecked()) { s = s + 10; tv2.setText("Right Answer"); } else { tv2.setText("Wrong Answer B was Right Answer"); } q = 5; a.setChecked(false); b.setChecked(false); c.setChecked(false); d.setChecked(false); bt.setText("Finish"); break; } case 5: { a.setEnabled(false); b.setEnabled(false); c.setEnabled(false); d.setEnabled(false); if (d.isChecked()) { s = s + 10; tv2.setText("Right Answer"); } else { tv2.setText("Wrong Answer D was Right Answer"); } tv3.setText(ed1.getText() + " final score is " + s); bt.setText("Restart"); q = 0; break; } } } }
true
b363611073e4ddd25a896ee65f2ab70952fab67c
Java
ZJUZWT/Android-Summer-Training
/ProjectDY2/app/src/main/java/com/example/projectdy2/InterfaceForInteract/OnViewPagerListener.java
UTF-8
323
2.015625
2
[]
no_license
package com.example.projectdy2.InterfaceForInteract; public interface OnViewPagerListener { /*初始化完成*/ void onInitComplete(); /*释放的监听*/ void onPageRelease(boolean isNext, int position); /*选中的监听以及判断是否滑动到底部*/ void onPageSelected(int position, boolean isBottom); }
true
f51e50c89368f663a84792dab4476f69c5c1de59
Java
pxai/entornos-desarrollo
/LoopsExercise2/src/org/cuatrovientos/loops/LoopExercise2.java
UTF-8
652
3.296875
3
[]
no_license
/** * */ package org.cuatrovientos.loops; import java.util.Scanner; /** * @author Administrador * */ public class LoopExercise2 { /** * @param args */ public static void main(String[] args) { int number; Scanner reader = new Scanner(System.in); String line = ""; System.out.println("Please, enter a number:"); line = reader.nextLine(); number = Integer.parseInt(line); if (number > 0 && number % 2 == 0) { for (int i = 0; i < number; i++) { System.out.print("*"); } } else { System.out.println("Invalid number"); //return; System.exit(0); } } }
true
344e1be7d4522aec725e751856496af27094d693
Java
HubertYoung/AcFun
/acfun5_7/src/main/java/com/alibaba/mtl/log/e/a.java
UTF-8
1,166
2.046875
2
[]
no_license
package com.alibaba.mtl.log.e; import android.text.TextUtils; import com.google.devtools.build.android.desugar.runtime.ThrowableExtension; import org.json.JSONObject; public class a { public static class a { public static a c = new a(); public boolean a = false; public String b = null; public boolean a() { return "E0102".equalsIgnoreCase(this.b); } public boolean b() { return "E0111".equalsIgnoreCase(this.b) || "E0112".equalsIgnoreCase(this.b); } } public static a a(String str) { a aVar = new a(); try { JSONObject jSONObject = new JSONObject(str); if (jSONObject.has("success")) { Object string = jSONObject.getString("success"); if (!TextUtils.isEmpty(string) && string.equals("success")) { aVar.a = true; } } if (jSONObject.has("ret")) { aVar.b = jSONObject.getString("ret"); } } catch (Throwable e) { ThrowableExtension.printStackTrace(e); } return aVar; } }
true
245449780ef936ac3274f7768406a86271941dde
Java
glromeo/spring-media-manager
/src/main/java/org/codebite/springmediamanager/jaxb/LocalDateTimeXmlAdapter.java
UTF-8
646
2.71875
3
[]
no_license
package org.codebite.springmediamanager.jaxb; import javax.xml.bind.annotation.adapters.XmlAdapter; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; public class LocalDateTimeXmlAdapter extends XmlAdapter<String, LocalDateTime> { private static DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); @Override public LocalDateTime unmarshal(String text) throws Exception { return LocalDateTime.parse(text, formatter); } @Override public String marshal(LocalDateTime localDateTime) throws Exception { return localDateTime.format(formatter); } }
true
76e0c11d1e991bf4cdd451ab867186e18d24a93a
Java
MaiAnhBao/MyTestApp
/app/src/main/java/com/example/hnnguyen/myapplication/exception/NotExistingKeyException.java
UTF-8
210
1.960938
2
[]
no_license
package com.example.hnnguyen.myapplication.exception; public class NotExistingKeyException extends Exception { public NotExistingKeyException(String detailMessage) { super(detailMessage); } }
true
e2a7e79f53c3a3f546bd985cfae458cd2585ac7f
Java
dimplezhkk/MyEP
/src/cn/zh/ep/service/impl/SongSheetServiceImpl.java
GB18030
2,256
2.25
2
[]
no_license
package cn.zh.ep.service.impl; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageInfo; import cn.zh.ep.mapper.SongsheetMapper; import cn.zh.ep.pojo.Songsheet; import cn.zh.ep.pojo.SongsheetExample; import cn.zh.ep.pojo.SongsheetExample.Criteria; import cn.zh.ep.service.SongSheetService; /** * @author ֣: * @version ʱ䣺2020211 10:15:47 * ˵ */ @Service public class SongSheetServiceImpl implements SongSheetService{ @Autowired private SongsheetMapper songsheetMapper; @Override public void addSongSheet(Songsheet songsheet) { songsheetMapper.insert(songsheet); } @Override public PageInfo<Songsheet> showSongSheetList(Integer page, Integer limit) { PageHelper.startPage(page, limit); SongsheetExample example = new SongsheetExample(); List<Songsheet> list = songsheetMapper.selectByExample(example); PageInfo<Songsheet> info = new PageInfo<Songsheet>(list); return info; } @Override public Songsheet selectSongSheetById(String songSheetId) { int parseInt = Integer.parseInt(songSheetId); Songsheet songSheet = songsheetMapper.selectByPrimaryKey(parseInt); return songSheet; } @Override public void editSongSheetById(Songsheet songSheet) { songsheetMapper.updateByPrimaryKey(songSheet); } @Override public void delSongSheetById(String songSheetId) { int parseInt = Integer.parseInt(songSheetId); songsheetMapper.deleteByPrimaryKey(parseInt); } @Override public PageInfo<Songsheet> searchResult(Integer page, Integer limit, String keyword) { PageHelper.startPage(page, limit); SongsheetExample example = new SongsheetExample(); Criteria criteria = example.createCriteria(); if (keyword != null && !"".equals(keyword)) { criteria.andCreatorLike("%"+keyword+"%"); } List<Songsheet> list = songsheetMapper.selectByExample(example); PageInfo<Songsheet> info = new PageInfo<>(list); return info; } @Override public Integer count() { SongsheetExample example = new SongsheetExample(); Integer songSheet = songsheetMapper.countByExample(example); return songSheet; } }
true
6eb64cbb4e89032c205142509e28c8682cfd2abb
Java
jerryTJ/qixing
/web/src/main/java/com/dream/qixing/control/action/qixing/QueryRoadBookListAction.java
UTF-8
1,747
2.140625
2
[]
no_license
package com.dream.qixing.control.action.qixing; import com.dream.qixing.control.action.BaseAction; import com.dream.qixing.mapping.ApiListField; import com.dream.qixing.config.ApiAction; import com.dream.qixing.mapping.ApiField; import com.dream.qixing.model.qixing.RoadBook; import java.util.ArrayList; import java.util.Date; import java.util.List; @ApiAction(value = "roadbook.list") public class QueryRoadBookListAction extends BaseAction { @ApiListField("books") @ApiField("book") private List<RoadBook> roadBookList; @Override public String execute() { if (this.getUserId() == 0) { this.setIsSuccessful(false); this.setStatusCode(400); this.setDescription("数据不存在!"); return ""; } roadBookList = new ArrayList<RoadBook>(); RoadBook book = new RoadBook(); book.setRoadBookId(1000); book.setCreateTime(new Date()); book.setName("昌平骑行"); book.setRoadName("南邵--> 昌平-->十三陵"); book.setStatusName("使用"); book.setStatus(1); book.setMileage(100); roadBookList.add(book); RoadBook book1 = new RoadBook(); book1.setRoadBookId(1000); book1.setCreateTime(new Date()); book1.setName("昌平骑行"); book1.setRoadName("南邵--> 昌平-->十三陵"); book1.setStatusName("未使用"); book1.setStatus(0); book1.setMileage(100); roadBookList.add(book1); this.setIsSuccessful(true); this.setStatusCode(200); this.setDescription("查询成功!"); return ""; } @Override public String getResponseName() { return null; } }
true
f01a8ca7f34157d4e48498354aa1e7fa2ec656e8
Java
tcf1207239873/Logi-KafkaManager
/kafka-manager-web/src/main/java/com/xiaojukeji/kafka/manager/web/api/versionone/op/OpGatewayConfigController.java
UTF-8
2,919
1.859375
2
[ "Apache-2.0" ]
permissive
package com.xiaojukeji.kafka.manager.web.api.versionone.op; import com.xiaojukeji.kafka.manager.bpm.common.entry.apply.gateway.OrderExtensionAddGatewayConfigDTO; import com.xiaojukeji.kafka.manager.bpm.common.entry.apply.gateway.OrderExtensionDeleteGatewayConfigDTO; import com.xiaojukeji.kafka.manager.bpm.common.entry.apply.gateway.OrderExtensionModifyGatewayConfigDTO; import com.xiaojukeji.kafka.manager.common.bizenum.gateway.GatewayConfigKeyEnum; import com.xiaojukeji.kafka.manager.common.constant.ApiPrefix; import com.xiaojukeji.kafka.manager.common.entity.Result; import com.xiaojukeji.kafka.manager.common.entity.ResultStatus; import com.xiaojukeji.kafka.manager.common.utils.JsonUtils; import com.xiaojukeji.kafka.manager.common.utils.ValidateUtils; import com.xiaojukeji.kafka.manager.service.service.gateway.GatewayConfigService; import com.xiaojukeji.kafka.manager.web.converters.GatewayModelConverter; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; @Api(tags = "OP-Gateway配置相关接口(REST)") @RestController @RequestMapping(ApiPrefix.API_V1_OP_PREFIX) public class OpGatewayConfigController { @Autowired private GatewayConfigService gatewayConfigService; @ApiOperation(value = "Gateway配置类型", notes = "") @GetMapping(value = "gateway-configs/type-enums") @ResponseBody public Result getClusterModesEnum() { return new Result<>(JsonUtils.toJson(GatewayConfigKeyEnum.class)); } @ApiOperation(value = "创建Gateway配置", notes = "") @PostMapping(value = "gateway-configs") @ResponseBody public Result createGatewayConfig(@RequestBody OrderExtensionAddGatewayConfigDTO dto) { if (ValidateUtils.isNull(dto) || !dto.legal()) { return Result.buildFrom(ResultStatus.PARAM_ILLEGAL); } return gatewayConfigService.insert(GatewayModelConverter.convert2GatewayConfigDO(dto)); } @ApiOperation(value = "修改Gateway配置", notes = "") @PutMapping(value = "gateway-configs") @ResponseBody public Result modifyGatewayConfig(@RequestBody OrderExtensionModifyGatewayConfigDTO dto) { if (ValidateUtils.isNull(dto) || !dto.legal()) { return Result.buildFrom(ResultStatus.PARAM_ILLEGAL); } return gatewayConfigService.updateById(GatewayModelConverter.convert2GatewayConfigDO(dto)); } @ApiOperation(value = "删除Gateway配置", notes = "") @DeleteMapping(value = "gateway-configs") @ResponseBody public Result deleteGatewayConfig(@RequestBody OrderExtensionDeleteGatewayConfigDTO dto) { if (ValidateUtils.isNull(dto) || !dto.legal()) { return Result.buildFrom(ResultStatus.PARAM_ILLEGAL); } return gatewayConfigService.deleteById(dto.getId()); } }
true
99a38c0d3b138fb7e93f090edec04a90a91dd124
Java
venugopalaraju/ChangeTheFlag
/src/main/java/com/epam/hackme/common/CommonConstants.java
UTF-8
3,897
1.960938
2
[]
no_license
package com.epam.hackme.common; public interface CommonConstants { String USER_ID="user_id"; String SUCCESS="success"; String NOT_SUCCESS="nosuccess"; String USERNAME="username"; String PASSWORD="password"; String ADMIN="admin"; String USER_LOGIN="/login"; String USER_LOGIN_DEFAULT="/"; String USER_LOGIN_VIEW="login"; String VALIDATE_USER="/validateuser"; String REGISTRATION="/register"; String USER="user"; String REGISTRATION_VIEW="register"; String REGISTRATION_USER="registeruser"; String CHALLENGE_ZERO="/challengelogin"; String HACK_ALL="/hackall"; String CLICK_HERE="/clickhere"; String VALIDATE_CHALLENGE_ZERO="validatechallengezero"; String VALIDATE_CHALLENGE_ONE="/validatechallenge1"; String CHALLENGE_TWO="/challenge2"; String VALIDATE_CHALLENGE_TWO="/validatechallenge2"; String CHALLENGE_THREE="/challenge3"; String VALIDATE_CHALLENGE_THREE="/validatechallenge3"; String CHALLENGE_FOUR="/challenge4"; String VALIDATE_CHALLENGE_FOUR="/validatechallenge4"; String CHALLENGE_FIVE=""; String VALIDATE_CHALLENGE_FIVE="/validatechallenge5"; String CHALLENGE_SIX=""; String VALIDATE_CHALLENGE_SIX="/validatechallenge6"; String CHALLENGE_SEVEN=""; String VALIDATE_CHALLENGE_SEVEN="/validatechallenge7"; String CHALLENGE_EIGHT=""; String VALIDATE_CHALLENGE_EIGHT="/validatechallenge8"; String CHALLENGE_NINE=""; String VALIDATE_CHALLENGE_NINE="/validatechallenge9"; String VALIDATE_CHALLENGE_NINE_PWD="/validatechallenge9pwd"; String CHALLENGE_TEN="/challenge10"; String VALIDATE_CHALLENGE_TEN="/validatechallenge10"; String CHALLENGE_ELEVEN="/challenge11"; String CHALLENGE_ELEVEN_VIEW="directories"; String CHALLENGE_ELEVEN_ADMIN="/challenge11admin"; String VALIDATE_CHALLENGE_ELEVEN = "/validatechallenge11"; String VALIDATE_CHALLENGE_TWELVE = "/validatechallenge12"; String CHALLENGE_ZERO_VIEW="challengelogin"; String CHALLENGE_ALL_VIEW="hack"; String INVALID_URL="Invalid URL"; String UPDATE_SCORE="/updatescore"; String GET_SCORES="/getscores"; String GET_MY_SCORE="/getmyscore"; String GET_MY_SCORE_CARD="/getmyscorecard"; String GET_CHALLENGE="/getchallenge"; String TRIVIA="/trivia"; String TRIVIA_VIEW="trivia"; String TRIVIA_SUBMIT="/triviasubmit"; String TRIVIA_SKIP="/triviaskip"; String TRIVIA_ONE_VIEW="triviachallengeone"; String TRIVIA_TWO_VIEW="triviachallengetwo"; String TRIVIA_THREE_VIEW="triviachallengethree"; String TRIVIA_FOUR_VIEW="triviachallengefour"; String TRIVIA_FIVE_VIEW="triviachallengefive"; String TRIVIA_ONE="/triviachallengeone"; String TRIVIA_TWO="/triviachallengetwo"; String TRIVIA_THREE="/triviachallengethree"; String TRIVIA_FOUR="/triviachallengefour"; String TRIVIA_FIVE="/triviachallengefive"; String TRIVIA_ONE_VALIDATE="/validatetriviachallengeone"; String TRIVIA_TWO_VALIDATE="/validatetriviachallengetwo"; String TRIVIA_THREE_VALIDATE="/validatetriviachallengethree"; String TRIVIA_FOUR_VALIDATE="/validatetriviachallengefour"; String TRIVIA_FIVE_VALIDATE="/validatetriviachallengefive"; String TRIVIA_ONE_SKIP_VALIDATE="/skipvalidatetriviachallengeone"; String TRIVIA_TWO_SKIP_VALIDATE="/skipvalidatetriviachallengetwo"; String TRIVIA_THREE_SKIP_VALIDATE="/skipvalidatetriviachallengethree"; String TRIVIA_FOUR_SKIP_VALIDATE="/skipvalidatetriviachallengefour"; String TRIVIA_FIVE_SKIP_VALIDATE="/skipvalidatetriviachallengefive"; String ERROR="error"; String ERROR_VIEW="globalerror"; String FORWARD="forward:"; String FLAG_Y="Y"; String FLAG_N="N"; String CHALLENGE_FLAG="challenge"; String TRIVIA_FLAG="trivia"; String MYSCORE_TR_1="<tr><td>User Id </td><td>"; String MYSCORE_TR_2="</td></tr><tr><td>Username </td><td>"; String MYSCORE_TR_3="</td></tr><tr><td>Score </td><td>"; String MYSCORE_TR_4="</td></tr>"; String PASSWORD_TXT="/password.txt"; String PASSWORD_TXT_FILE_PATH="password"; String CACHE_CONTROL="cache-control"; String NO_CACHE="No-cache"; String TEXT_PLAIN="text/plain"; String NO_COMMAND_ERROR="Please enter valid command"; }
true
e86ed81952f77d4b826abe162ffcf586aa844c15
Java
MRTangwin8/BigApp_Discuz_Android
/Clan/Clan/src/com/youzu/clan/main/android/PureAndroidMainActivity.java
UTF-8
7,498
1.648438
2
[ "Apache-2.0" ]
permissive
package com.youzu.clan.main.android; import android.graphics.Color; import android.os.Bundle; import android.support.v4.widget.DrawerLayout; import android.view.Gravity; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.widget.LinearLayout; import com.balysv.materialmenu.MaterialMenuDrawable; import com.balysv.materialmenu.MaterialMenuView; import com.kit.utils.intentutils.IntentUtils; import com.kit.widget.slidingtab.SlidingTabLayout; import com.youzu.android.framework.view.annotation.ContentView; import com.youzu.android.framework.view.annotation.ViewInject; import com.youzu.android.framework.view.annotation.event.OnClick; import com.youzu.clan.R; import com.youzu.clan.base.json.config.content.SearchSettings; import com.youzu.clan.base.util.AppSPUtils; import com.youzu.clan.base.util.ClanUtils; import com.youzu.clan.base.util.ToastUtils; import com.youzu.clan.base.util.theme.ThemeUtils; import com.youzu.clan.base.widget.SuperViewPager; import com.youzu.clan.main.base.activity.BaseMainActivity; import com.youzu.clan.main.qqstyle.OnEmptyDataListener; import com.youzu.clan.profile.MenuFragment; import com.youzu.clan.search.SearchActivity; import com.youzu.clan.thread.ThreadPublishActivity; @ContentView(R.layout.activity_pure_android_main) public class PureAndroidMainActivity extends BaseMainActivity implements OnClickListener { private boolean direction; private MaterialMenuView materialMenu; private int actionBarMenuState = MaterialMenuDrawable.IconState.BURGER.ordinal(); @ViewInject(R.id.slidingIndicator) private SlidingTabLayout slidingIndicator; private long exitTime; @ViewInject(R.id.drawer_layout) private DrawerLayout drawerLayout; @ViewInject(R.id.pager) private SuperViewPager viewPager; @ViewInject(R.id.llMenu) private LinearLayout llMenu; private OnEmptyDataListener mEmptyListener = new OnEmptyDataListener() { private boolean isFirstTime = true; @Override public void onEmpty() { if (isFirstTime) { slidingIndicator.setCurrentItem(1); // getSlidingMenu().setTouchModeAbove(SlidingMenu.TOUCHMODE_NONE); isFirstTime = false; } } }; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setTheme(R.style.PureAndroidActionBarTheme); // setActionBar(); ClanUtils.initCustomActionBar(this); materialMenu = (MaterialMenuView) getSupportActionBar().getCustomView().findViewById(R.id.action_bar_menu); materialMenu.setOnClickListener(this); setDrawerLayout(); viewPager.setAdapter(new PureAndroidTabAdapter(this, getSupportFragmentManager(), mEmptyListener)); slidingIndicator.setDividerColors(0); slidingIndicator.setSelectedIndicatorColors(ThemeUtils.getThemeColor(this)); slidingIndicator.setViewPager(viewPager); slidingIndicator.setCurrentItem(0); // 去除头部区域滑动显示侧边栏 // getSlidingMenu().addIgnoredView(mIndicator); getSupportFragmentManager().beginTransaction().replace(R.id.menuReplace, new MenuFragment()).commit(); } @Override protected void onDestroy() { super.onDestroy(); // PollingUtils.stopCheckNewMessage(this, mPreferenceListener); } @Override protected void onResume() { super.onResume(); // String avatar = AppSPUtils.getAvatartUrl(this); // displayMineAvatar(avatar); // int messageCount = AppSPUtils.getNewMessage(this); // mRedDotView.setVisibility(messageCount > 0 ? View.VISIBLE : View.GONE); } @Override protected void onRestart() { super.onRestart(); } @OnClick(R.id.action_bar_menu) @Override public void onClick(View v) { if (v.getId() == R.id.action_bar_menu) { // random state on click if (actionBarMenuState == MaterialMenuDrawable.IconState.BURGER.ordinal()) { int state = MaterialMenuDrawable.IconState.ARROW.ordinal(); materialMenu.animatePressedState(intToState(state)); drawerLayout.openDrawer(Gravity.START); actionBarMenuState = state; } else { int state = MaterialMenuDrawable.IconState.BURGER.ordinal(); materialMenu.animatePressedState(intToState(state)); drawerLayout.closeDrawers(); actionBarMenuState = state; } } } public void setDrawerLayout() { drawerLayout.setScrimColor(Color.parseColor("#66000000")); drawerLayout.setDrawerListener(new DrawerLayout.SimpleDrawerListener() { @Override public void onDrawerSlide(View drawerView, float slideOffset) { materialMenu.setTransformationOffset( MaterialMenuDrawable.AnimationState.BURGER_ARROW, direction ? 2 - slideOffset : slideOffset ); } @Override public void onDrawerOpened(android.view.View drawerView) { direction = true; } @Override public void onDrawerClosed(android.view.View drawerView) { direction = false; } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_pure_android, menu); SearchSettings searchSettings =AppSPUtils.getContentConfig(this).getSearchSetting(); if (!(searchSettings!=null&&!"1".equals(searchSettings.getEnable()))){ menu.findItem(R.id.action_search).setVisible(true); }else{ menu.findItem(R.id.action_search).setVisible(false); } return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.action_edit: IntentUtils.gotoNextActivity(this, ThreadPublishActivity.class); return true; case R.id.action_search: IntentUtils.gotoNextActivity(this, SearchActivity.class); return true; } return super.onOptionsItemSelected(item); } @Override public void onBackPressed() { long currentTime = System.currentTimeMillis(); if (currentTime - exitTime > 2000) { ToastUtils.show(this, R.string.click_to_exit); exitTime = currentTime; return; } this.finish(); } public static MaterialMenuDrawable.IconState intToState(int state) { switch (state) { case 0: return MaterialMenuDrawable.IconState.BURGER; case 1: return MaterialMenuDrawable.IconState.ARROW; case 2: return MaterialMenuDrawable.IconState.X; case 3: return MaterialMenuDrawable.IconState.CHECK; } throw new IllegalArgumentException("Must be a number [0,3)"); } }
true
49cdbf49cbfc60ac68e9fa544d505ed12c1b217f
Java
mohsenuss91/KGBANDROID
/src/com/google/a/b/f.java
UTF-8
3,465
2.015625
2
[]
no_license
// Decompiled by Jad v1.5.8e. Copyright 2001 Pavel Kouznetsov. // Jad home page: http://www.geocities.com/kpdus/jad.html // Decompiler options: braces fieldsfirst space lnc package com.google.a.b; import com.google.a.c.a; import com.google.a.s; import java.lang.reflect.Constructor; import java.lang.reflect.ParameterizedType; import java.util.Collection; import java.util.EnumSet; import java.util.Map; import java.util.Queue; import java.util.Set; import java.util.SortedMap; import java.util.SortedSet; // Referenced classes of package com.google.a.b: // l, g, k, m, // j, n, o, p, // q, r, h, i, // ae public final class f { private final Map a; public f(Map map) { a = map; } private ae a(Class class1) { l l1; try { Constructor constructor = class1.getDeclaredConstructor(new Class[0]); if (!constructor.isAccessible()) { constructor.setAccessible(true); } l1 = new l(this, constructor); } catch (NoSuchMethodException nosuchmethodexception) { return null; } return l1; } public final ae a(a a1) { java.lang.reflect.Type type = a1.b; Class class1 = a1.a; s s1 = (s)a.get(type); Object obj; if (s1 != null) { obj = new g(this, s1, type); } else { s s2 = (s)a.get(class1); if (s2 != null) { return new k(this, s2, type); } obj = a(class1); if (obj == null) { if (java/util/Collection.isAssignableFrom(class1)) { if (java/util/SortedSet.isAssignableFrom(class1)) { obj = new m(this); } else if (java/util/EnumSet.isAssignableFrom(class1)) { obj = new n(this, type); } else if (java/util/Set.isAssignableFrom(class1)) { obj = new o(this); } else if (java/util/Queue.isAssignableFrom(class1)) { obj = new p(this); } else { obj = new q(this); } } else if (java/util/Map.isAssignableFrom(class1)) { if (java/util/SortedMap.isAssignableFrom(class1)) { obj = new r(this); } else if ((type instanceof ParameterizedType) && !java/lang/String.isAssignableFrom(com.google.a.c.a.a(((ParameterizedType)type).getActualTypeArguments()[0]).a)) { obj = new h(this); } else { obj = new i(this); } } else { obj = null; } if (obj == null) { return new j(this, class1, type); } } } return ((ae) (obj)); } public final String toString() { return a.toString(); } }
true
30b6ff076df381eb8085be4c07f169d78bc8ace0
Java
kaizhiyu/skoop-server
/src/test/java/com/tsmms/skoop/skillgroup/SkillGroupRepositoryTests.java
UTF-8
2,920
2.4375
2
[ "MIT" ]
permissive
package com.tsmms.skoop.skillgroup; import org.assertj.core.api.Assertions; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.data.neo4j.DataNeo4jTest; import java.util.Optional; import static org.assertj.core.api.Assertions.assertThat; @DataNeo4jTest class SkillGroupRepositoryTests { @Autowired private SkillGroupRepository skillGroupRepository; @Test @DisplayName("Provides the existing skill group queried by its exact name") void providesSkillGroupByExactName() { // Given skillGroupRepository.save(SkillGroup.builder().id("123").name("Programming").description("programming languages group").build()); // When Optional<SkillGroup> skillGroup = skillGroupRepository.findByNameIgnoreCase("Programming"); // Then Assertions.assertThat(skillGroup).isNotEmpty(); assertThat(skillGroup.get().getId()).isEqualTo("123"); assertThat(skillGroup.get().getName()).isEqualTo("Programming"); assertThat(skillGroup.get().getDescription()).isEqualTo("programming languages group"); } @Test @DisplayName("Provides the existing skill group queried by its name ignoring case") // @Disabled("SDN 5.0.x does not support 'IgnoreCase' in finder methods yet. " + // "This will be implemented with SDN 5.1, " + // "see https://docs.spring.io/spring-data/neo4j/docs/5.1.0.RC2/reference/html/#_query_methods") void providesSkillGroupByNameIgnoringCase() { // Given skillGroupRepository.save(SkillGroup.builder().id("123").name("Programming").description("programming languages group").build()); // When Optional<SkillGroup> skillGroup = skillGroupRepository.findByNameIgnoreCase("prOgraMMinG"); // Then Assertions.assertThat(skillGroup).isNotEmpty(); assertThat(skillGroup.get().getId()).isEqualTo("123"); assertThat(skillGroup.get().getName()).isEqualTo("Programming"); assertThat(skillGroup.get().getDescription()).isEqualTo("programming languages group"); } @Test @DisplayName("Indicates that the skill group with a given name exists ignoring case") void indicatesExistingSkillGroupByNameIgnoringCase() { // Given skillGroupRepository.save(SkillGroup.builder().id("123").name("Programming").description("programming languages group").build()); // When Boolean skillGroupExists = skillGroupRepository.isSkillGroupExistByNameIgnoreCase("prOgraMMinG"); // Then assertThat(skillGroupExists).isTrue(); } @Test @DisplayName("Indicates that the skill with a given name does not exist") void indicatesNonExistingSkillGroupByName() { // Given skillGroupRepository.save(SkillGroup.builder().id("123").name("Programming").description("programming languages group").build()); // When Boolean skillExists = skillGroupRepository.isSkillGroupExistByNameIgnoreCase("spring"); // Then assertThat(skillExists).isFalse(); } }
true
1ff6c8e164d22315b62781b3fc7b6981fe2fe05c
Java
talandar/ManaFluidics
/src/main/java/derpatiel/manafluidics/spell/lvl4/MajorHealing.java
UTF-8
682
2.34375
2
[ "MIT" ]
permissive
package derpatiel.manafluidics.spell.lvl4; import derpatiel.manafluidics.spell.SpellAttribute; import derpatiel.manafluidics.spell.SpellBase; import derpatiel.manafluidics.spell.parameters.SpellParameterChoices; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.world.World; import java.util.Collection; public class MajorHealing extends SpellBase { public MajorHealing() { super("majorhealing", 4, 30, SpellAttribute.HEALING); } @Override public boolean doCast(World worldIn, EntityPlayer castingPlayer, boolean boosted, Collection<SpellParameterChoices> parameters) { castingPlayer.heal(10.0f); return true; } }
true
8ced093704e56c9f2a4647a69245b6231f91ce94
Java
xinsec/ta
/YssTaQs/src/main/java/com/yss/main/dataInterface/FileContentBean.java
GB18030
37,227
2
2
[]
no_license
package com.yss.main.dataInterface; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.ArrayList; import com.yss.dsub.BaseDataSettingBean; import com.yss.main.dao.IDataSetting; import com.yss.main.sysfunsetting.VocabularyBean; import com.yss.util.YssCons; import com.yss.util.YssException; import com.yss.util.YssFun; /** * @author ly * ݽӿļ */ public class FileContentBean extends BaseDataSettingBean implements IDataSetting{ public FileContentBean(){ } /** * ӿڴ */ private String cusCfgCode = ""; /** * ӿ */ private String cusCfgName = ""; /** * */ private String orderNum; /** * ȡ */ private String beginRow; /** * ȡλ */ private String loadIndex; /** * ȡ */ private String loadLen; /** * Ӧֶ */ private String tabField = ""; /** * ֶε */ private String fieldDesc = ""; /** * ֶεij */ private String fieldpre=""; /** * תʽ */ private String format = ""; /** * ļͷֵ */ private String fileInfoDict = ""; /** * ļͷֵ */ private String fileInfoDictName = ""; /** * */ private String desc = ""; /** * ַ */ private String insertString=""; /** * λ */ private String insertLocation=""; /** * ǷΪֶ */ private String moneyField = ""; /** * λ */ private String moneyUnit = ""; private FileContentBean filterType; private String oldcusCfgCode = ""; /** * */ private String tabName = ""; /** * ļ */ private String fileType = ""; /** * ʽ */ private String formatType=""; public String getMoneyField() { return this.moneyField; } public void setMoneyField(String moneyField) { this.moneyField = moneyField; } public String getMoneyUnit() { return this.moneyUnit; } public void setMoneyUnit(String moneyUnit) { this.moneyUnit = moneyUnit; } public String getFileType() { return this.fileType; } public void setFileType(String fileType) { this.fileType = fileType; } public String getTabName(){ return tabName; } public void setTabName(String tabName){ this.tabName = tabName; } /*public String getSplitMark() { return splitMark; } public void setSplitMark(String splitMark) { this.splitMark = splitMark; } public String getSplitType() { return splitType; } public void setSplitType(String splitType) { this.splitType = splitType; }*/ public String getFileInfoDictName(){ return fileInfoDictName; } public void setFileInfoDictName(String fileInfoDictName){ this.fileInfoDictName = fileInfoDictName; } public FileContentBean getFilterType(){ return filterType; } public void setFilterType(FileContentBean filterType){ this.filterType = filterType; } public String getOldcusCfgCode(){ return oldcusCfgCode; } public void setOldcusCfgCode(String oldcusCfgCode){ this.oldcusCfgCode = oldcusCfgCode; } public String getDesc(){ return desc; } public void setDesc(String desc){ this.desc = desc; } public String getFileInfoDict(){ return fileInfoDict; } public void setFileInfoDict(String fileInfoDict){ this.fileInfoDict = fileInfoDict; } public String getFormat(){ return format; } public void setFormat(String format){ this.format = format; } public String getFieldDesc(){ return fieldDesc; } public void setFieldDesc(String fieldDesc){ this.fieldDesc = fieldDesc; } public String getTabField(){ return tabField; } public void setTabField(String tabField){ this.tabField = tabField; } public String getLoadLen(){ return loadLen; } public void setLoadLen(String loadLen){ this.loadLen = loadLen; } /* public String getloadLen() { return loadLen; }*/ public String getLoadIndex(){ return loadIndex; } public void setLoadIndex(String loadIndex){ this.loadIndex = loadIndex; } public String getBeginRow(){ return beginRow; } public void setBeginRow(String beginRow){ this.beginRow = beginRow; } public String getOrderNum(){ return orderNum; } public void setOrderNum(String orderNum){ this.orderNum = orderNum; } public String getCusCfgName(){ return cusCfgName; } public void setCusCfgName(String cusCfgName){ this.cusCfgName = cusCfgName; } public String getCusCfgCode(){ return cusCfgCode; } public void setCusCfgCode(String cusCfgCode){ this.cusCfgCode = cusCfgCode; } public String getListViewData1() throws YssException{ String strSql = "select distinct y.* from " + "(select * from " + pub.yssGetTableName("qsFileContent") + " " + " where FCheckState <> 2) x join" + " (select a.*,d.FFieldDesc as FFieldDesc,f.FVocName as FVocName, g.FCusCfgName as FCusCfgName,h.FDictName as FDictName,k.fusername as fcreatorName,l.fusername as fcheckuserName from " + pub.yssGetTableName("qsFileContent") + " a" + " left join (select FDictCode,FDictName from " + pub.yssGetTableName("qsDict") + " ) h on a.FFileContentDict = h.FDictCode " + " left join (select FCusCfgCode,FCusCfgName from " + pub.yssGetTableName("qsCusConfig") + " ) g on a.FCusCfgCode = g.FCusCfgCode" + " left join(select FFieldName,FFieldDesc from sysDATADICT where FTabName = " + dbl.sqlString(this.tabName) + " ) d on d.FFieldName=a.FTabFeild " + " left join sysVocabulary f on a.FFormat = f.FVocCode and f.FVocTypeCode = " + dbl.sqlString(YssCons.YSS_FORMAT) +" left join (select fuser,fuserName from sysusers group by fuser,fuserName) k on a.Fcreator = k.fuser" +" left join (select fuser,fuserName from sysusers group by fuser,fuserName) l on a.Fcheckuser = l.fuser" + buildFilterSql() + ")y on y.FCusCfgCode=x.FCusCfgCode and y.FOrderNum=x.FOrderNum" + " order by y.FCusCfgCode,y.FOrderNum";//2009-05-02 cyg ˶Աsysusersϲѯ return builderListViewData(strSql); } public String builderListViewData(String strSql) throws YssException{ String sHeader = ""; String sShowDataStr = ""; String sAllDataStr = ""; ResultSet rs = null; String sVocStr = ""; StringBuffer bufShow = new StringBuffer(); StringBuffer bufAll = new StringBuffer(); try{ sHeader = this.getListView1Headers(); rs = dbl.openResultSet(strSql); while(rs.next()){ bufShow.append(super.buildRowShowStr(rs, this.getListView1ShowCols())).append(YssCons. YSS_LINESPLITMARK); setDaoFileContentAttr(rs); bufAll.append(this.buildRowStr()).append(YssCons. YSS_LINESPLITMARK); } if(bufShow.toString().length() > 2){ sShowDataStr = bufShow.toString().substring(0, bufShow.toString().length() - 2); } if(bufAll.toString().length() > 2){ sAllDataStr = bufAll.toString().substring(0, bufAll.toString().length() - 2); } VocabularyBean vocabulary = new VocabularyBean(); vocabulary.setYssPub(pub); sVocStr = vocabulary.getVoc(YssCons.YSS_FORMAT); return sHeader + "\r\f" + sShowDataStr + "\r\f" + sAllDataStr + "\r\f" + this.getListView1ShowCols() + "\r\f" + "voc" + sVocStr; } catch(Exception e){ throw new YssException("ȡļϢ", e,"com.yss.main.dataInterface.FileContentBean"); } finally{ dbl.closeResultSetFinal(rs); } } public void setDaoFileContentAttr(ResultSet rs) throws Exception{ //try //{ this.cusCfgCode = rs.getString("FcusCfgCode"); this.cusCfgName = rs.getString("FCusCfgName"); this.orderNum = String.valueOf(rs.getInt("ForderNum")); this.beginRow = Integer.toString(rs.getInt("FBeginRow")); this.loadIndex = Integer.toString(rs.getInt("FloadIndex")); this.loadLen = Integer.toString(rs.getInt("FloadLen")); this.tabField = rs.getString("FtabFeild"); this.fieldDesc = rs.getString("FFieldDesc"); this.format = rs.getString("Fformat"); //this.splitType=rs.getString("FSplitType"); //this.splitMark = rs.getString("FsplitMark"); this.fileInfoDict = rs.getString("FFileContentDict"); this.fileInfoDictName = rs.getString("FDictName"); this.desc = rs.getString("FDesc"); this.insertLocation=rs.getString("FInsertLocation"); this.insertString=rs.getString("FInsertString"); this.moneyField = rs.getString("FMoneyField"); this.moneyUnit = rs.getString("FMoneyUnit"); this.formatType=rs.getString("Fcelltype")==null?"S":rs.getString("Fcelltype"); // }catch(Exception e) // { // throw new YssException(e.getMessage()); // } } private String buildFilterSql() throws YssException{ String sResult = ""; if(this.filterType != null){ sResult = " where 1=1"; if(this.filterType.oldcusCfgCode.length() != 0){ sResult = sResult + " and a.FCusCfgCode =" + dbl.sqlString(filterType.oldcusCfgCode); }//zupeng 2009-05-19ɸѡoldֵɸѡ } return sResult; } /** * getListViewData2 * * @return String */ public String getListViewData2(){ return ""; } /** * getListViewData3 * * @return String */ public String getListViewData3() throws YssException{ String strSql = "select a.*, k.fusername as fcreatorName,l.fusername as fcheckuserName from " + pub.yssGetTableName("qsFileContent") +" a" +" left join (select fuser,fuserName from sysusers group by fuser,fuserName) k on a.Fcreator = k.fuser" +" left join (select fuser,fuserName from sysusers group by fuser,fuserName) l on a.Fcheckuser = l.fuser" + " where 1=2"; //ֻǻȡͷ;//2009-05-02 cyg ˶Աsysusersϲѯ return builderListViewData(strSql); } /** * getListViewData4 * * @return String */ public String getListViewData4() throws YssException{ /* String strSql= "select y.* from " + "(select FVchTplCode,FEntityCode,FCheckState from " + pub.yssGetTableName("Tb_Vch_EntityResume") + " " + " where FCheckState <> 2 group by FVchTplCode,FEntityCode,FCheckState) x join" + " (select a.*,b.FUserName as FCreatorName, c.FUserName as FCheckUserName ," + " e.FDesc as FResumeFieldValue,d.FDictName as FResumeDictValue, f.FVocName as FValueTypeValue from " + pub.yssGetTableName("Tb_Vch_EntityResume") + " a" + " left join (select FUserCode,FUserName from Tb_Sys_UserList) b on a.FCreator = b.FUserCode" + " left join (select FUserCode,FUserName from Tb_Sys_UserList) c on a.FCheckUser = c.FUserCode" + " left join(select distinct FDictCode,FDictName from "+pub.yssGetTableName("Tb_Vch_Dict")+ " ) d on d.FDictCode=a.FResumeDict"+ " left join(select FAliasName,FDesc from "+pub.yssGetTableName("Tb_Vch_DsTabField")+ " where FVchDsCode="+dbl.sqlString(this.dataSource)+") e on e.FAliasName=a.FResumeField "+ " left join Tb_Fun_Vocabulary f on a.FValueType = f.FVocCode and f.FVocTypeCode = " + dbl.sqlString(YssCons.YSS_VALUETYPE) + buildFilterSql() + ")y on y.FVchTplCode=x.FVchTplCode and y.FEntityCode=x.FEntityCode" + " order by y.FVchTplCode,y.FEntityCode"; return builderListViewData(strSql);*/ return ""; } /** * checkInput * * @param btOper byte */ public void checkInput(byte btOper){ } /** * addSetting * * @return String */ public String addSetting() throws YssException{ Connection con = dbl.loadConnection(); ResultSet rs = null; String strSql = ""; PreparedStatement pstmt = null; int Num = 0; try{ strSql = "select * from " + pub.yssGetTableName("qsFileContent") + " where FCusCfgCode=" + dbl.sqlString(this.oldcusCfgCode); rs = dbl.openResultSet(strSql); //begin 17341A 2014-6-23 jm //Ϻ-[Ԫ]TAʽϵͳV4.0[]20140612001Ԫ𣺵Ͼļݸʽ strSql = "insert into " + pub.yssGetTableName("qsFileContent") + "(FCusCfgCode,FOrderNum," + " FBeginRow,FLoadIndex,FLoadLen,FTabFeild,FFormat,FFileContentDict,FDesc," + " FCheckState,FCreator,FCreateTime,FCheckUser,FCheckTime,FInsertString,FInsertLocation,FMoneyField,FMoneyUnit,Fcelltype)" + " values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"; //end 17341A pstmt = con.prepareStatement(strSql); while(rs.next()){ Num += 1; super.parseRecLog(); pstmt.setString(1, this.cusCfgCode); pstmt.setInt(2, Num); pstmt.setInt(3, rs.getInt("FBeginRow")); pstmt.setInt(4, rs.getInt("FLoadIndex")); pstmt.setInt(5, rs.getInt("FLoadLen")); pstmt.setString(6, rs.getString("FTabFeild")); pstmt.setString(7, rs.getString("FFormat")); //pstmt.setInt(7,YssFun.toInt(this.splitType)); // pstmt.setString(8,this.splitMark); pstmt.setString(8, rs.getString("FFileContentDict")); pstmt.setString(9, rs.getString("FDesc")); pstmt.setInt(10, (pub.getSysCheckState() ? 0 : 1)); pstmt.setString(11, this.creatorCode); pstmt.setString(12, this.creatorTime); pstmt.setString(13, (pub.getSysCheckState() ? " " : this.creatorCode)); pstmt.setString(14,this.checkTime); pstmt.setString(15, this.insertString); pstmt.setString(16,this.insertLocation); pstmt.setString(17, rs.getString("FMoneyField")); pstmt.setString(18, rs.getString("FMoneyUnit")); pstmt.setString(19, rs.getString("Fcelltype")); pstmt.addBatch(); } pstmt.executeBatch(); return ""; } catch(Exception e){ throw new YssException(e.getMessage() + "\r\nļϢ!"); } finally{ dbl.closeResultSetFinal(rs); dbl.closeStatementFinal(pstmt); } } /** * editSetting * * @return String */ public String editSetting() throws YssException{ /*String strSql = ""; boolean bTrans = false; //Ƿʼ Connection conn = dbl.loadConnection(); try { strSql = "update " + pub.yssGetTableName("Tb_Dao_FileInfo") + " set FCusCfgCode = " + dbl.sqlString(this.cusCfgCode) + ", FLoadRow = " + this.loadRow + " , FLoadIndex = " + this.loadIndex + ", FLoadLen = " + this.loadLen + ", FDesc = " + dbl.sqlString(this.desc) + ", FTabFeild =" + dbl.sqlString(this.tabField) + ", FFormat =" + dbl.sqlString(this.format) + ", FFileInfoDict =" + dbl.sqlString(this.fileInfoDict) + ",FCheckState = " + (pub.getSysCheckState() ? "0" : "1") + ", FCreator = " + dbl.sqlString(this.creatorCode) + ", FCreateTime = " + dbl.sqlString(this.creatorTime) + ",FCheckUser = " + (pub.getSysCheckState() ? "' '" : dbl.sqlString(this.creatorCode)) + " where FCusCfgCode = " + dbl.sqlString(this.oldcusCfgCode); conn.setAutoCommit(false); bTrans = true; dbl.executeSql(strSql); conn.commit(); bTrans = false; conn.setAutoCommit(true); } catch (Exception e) { throw new YssException("ļͷϢ", e); } finally { dbl.endTransFinal(conn, bTrans); }*/ return ""; } /** * delSetting */ public void delSetting() throws YssException{ /*String strSql = ""; boolean bTrans = false; //Ƿʼ Connection conn = dbl.loadConnection(); try { strSql = "update " + pub.yssGetTableName("Tb_Dao_FileInfo") + " set FCheckState = " + this.checkStateId + ", FCheckUser = " + dbl.sqlString(pub.getUserCode()) + ", FCheckTime = '" + YssFun.formatDatetime(new java.util.Date()) + "'" + " where FCusCfgCode = " + dbl.sqlString(this.cusCfgCode) + " and FOrderNum = " + this.orderNum ; conn.setAutoCommit(false); bTrans = true; dbl.executeSql(strSql); conn.commit(); bTrans = false; conn.setAutoCommit(true); } catch (Exception e) { throw new YssException("ɾļͷϢ", e); } finally { dbl.endTransFinal(conn, bTrans); }*/ } /** * checkSetting */ public void checkSetting() throws YssException{ /*String strSql = ""; boolean bTrans = false; //Ƿʼ Connection conn = dbl.loadConnection(); try { strSql = "update " + pub.yssGetTableName("Tb_Dao_FileInfo") + " set FCheckState = " + this.checkStateId + ", FCheckUser = " + dbl.sqlString(pub.getUserCode()) + ", FCheckTime = '" + YssFun.formatDatetime(new java.util.Date()) + "'" + " where FCusCfgCode = " + dbl.sqlString(this.cusCfgCode) + " and FOrderNum = " + this.orderNum ; conn.setAutoCommit(false); bTrans = true; dbl.executeSql(strSql); conn.commit(); bTrans = false; conn.setAutoCommit(true); } catch (Exception e) { throw new YssException("ļͷϢ", e); } finally { dbl.endTransFinal(conn, bTrans); } */ } /** * saveMutliSetting * * @param sMutilRowStr String * @return String */ public String saveMutliSetting(String sMutilRowStr) throws YssException{ String[] sMutilRowAry = null; PreparedStatement pstmt = null; Connection con = dbl.loadConnection(); String sql = ""; boolean bTrans = false; try{ /* Num = dbFun.getNextInnerCode(pub.yssGetTableName( "qsFileContent"), dbl.sqlRight("FOrderNum", 1), "1", " where 1=1", 1);*/ sMutilRowAry = sMutilRowStr.split(YssCons.YSS_LINESPLITMARK); sql = "delete from " + pub.yssGetTableName("qsFileContent") + " where FCusCfgCode=" + dbl.sqlString(this.oldcusCfgCode);//zupeng 2009-04-21 ޸whereʹoldcusCfgCode dbl.executeSql(sql); //begin 17341A 2014-6-23 jm //Ϻ-[Ԫ]TAʽϵͳV4.0[]20140612001Ԫ𣺵Ͼļݸʽ sql = "insert into " + pub.yssGetTableName("qsFileContent") + "(FCusCfgCode,FOrderNum," + " FBeginRow,FLoadIndex,FLoadLen,FTabFeild,FFormat,FFILECONTENTDICT,FDesc," + " FCheckState,FCreator,FCreateTime,FCheckUser,FCheckTime,FInsertString,FInsertLocation,FMoneyField,FMoneyUnit,Fcelltype)" + " values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"; //end 17341A pstmt = con.prepareStatement(sql); for(int i = 0; i < sMutilRowAry.length; i++){ // Num = dbFun.getNextInnerCode(pub.yssGetTableName( // "qsFileContent"), // dbl.sqlRight("FOrderNum", 1), "1", // " where 1=1", 1); 20070920һ޸ this.parseRowStr(sMutilRowAry[i]); //zupeng 2009-05-20 ǰ̨ĴΪվͲݿ if(this.cusCfgCode.equalsIgnoreCase("")) { break; } // if (this.cusCfgCode.trim().length() > 0) { pstmt.setString(1, this.cusCfgCode); pstmt.setInt(2, i + 1); pstmt.setInt(3, YssFun.toInt(this.beginRow)); pstmt.setInt(4, YssFun.toInt(this.loadIndex)); pstmt.setInt(5, YssFun.toInt(this.loadLen)); pstmt.setString(6, this.tabField); pstmt.setString(7, this.format); // pstmt.setInt(7,YssFun.toInt(this.splitType)); //pstmt.setString(8,this.splitMark); pstmt.setString(8, this.fileInfoDict); pstmt.setString(9, this.desc); pstmt.setInt(10, (pub.getSysCheckState() ? 0 : 1)); pstmt.setString(11, this.creatorCode); pstmt.setString(12, this.creatorTime); pstmt.setString(13, (pub.getSysCheckState() ? " " : this.creatorCode)); pstmt.setString(14,this.checkTime); pstmt.setString(15, this.insertString); pstmt.setString(16,this.insertLocation); pstmt.setString(17, this.moneyField); pstmt.setString(18, this.moneyUnit); pstmt.setString(19, this.formatType); pstmt.executeUpdate(); // } } } catch(Exception ex){ throw new YssException("ļϢ\r\n" + ex.getMessage()); } finally{ dbl.closeStatementFinal(pstmt); } return ""; } /** * getSetting * * @return IDataSetting */ public IDataSetting getSetting(){ return null; } /** * getAllSetting * * @return String */ public String getAllSetting(){ return ""; } /** * getTreeViewData1 * * @return String */ public String getTreeViewData1(){ return ""; } /** * getTreeViewData2 * * @return String */ public String getTreeViewData2(){ return ""; } /** * getTreeViewData3 * * @return String */ public String getTreeViewData3(){ return ""; } /** * parseRowStr * * @param sRowStr String */ public void parseRowStr(String sRowStr) throws YssException{ String[] reqAry = null; String sTmpStr = ""; try{ if(sRowStr.trim().length() == 0){ return; } if(sRowStr.indexOf("\r\t") >= 0){ sTmpStr = sRowStr.split("\r\t")[0]; } else{ sTmpStr = sRowStr; } reqAry = sTmpStr.split("\t"); this.cusCfgCode = reqAry[0]; //this.orderNum=reqAry[1]; this.beginRow = reqAry[1]; this.loadIndex = reqAry[2]; this.loadLen = reqAry[3]; this.tabField = reqAry[4]; this.format = reqAry[5]; //this.splitType=reqAry[6]; //this.splitMark = reqAry[7]; this.fileInfoDict = reqAry[6]; this.desc = reqAry[7]; this.oldcusCfgCode = reqAry[8];//zupeng 2009-05-19 89λõԭǴģûкǰӦ this.checkStateId = YssFun.toInt(reqAry[9]); this.tabName = reqAry[10]; this.insertString=reqAry[11]; this.insertLocation=reqAry[12]; this.moneyField = reqAry[13]; this.moneyUnit = reqAry[14]; this.formatType= reqAry[15]; super.parseRecLog(); if(sRowStr.indexOf("\r\t") >= 0){ if(this.filterType == null){ this.filterType = new FileContentBean(); this.filterType.setYssPub(pub); } this.filterType.parseRowStr(sRowStr.split("\r\t")[1]); } } catch(Exception e){ throw new YssException("¼ժҪϢ"); } } /** * buildRowStr * * @return String */ public String buildRowStr(){ StringBuffer buf = new StringBuffer(); buf.append(this.cusCfgCode).append("\t"); buf.append(this.cusCfgName).append("\t"); // buf.append(this.beginRow).append("\t"); buf.append(this.loadLen).append("\t"); buf.append(this.loadIndex).append("\t"); //zupeng 2009-04-20 nullĴ buf.append((this.tabField==null || this.tabField.trim().equalsIgnoreCase("null")) ? "" : this.tabField.trim()).append("\t"); buf.append((this.fieldDesc==null || this.fieldDesc.trim().equalsIgnoreCase("null")) ? "" : this.fieldDesc.trim()).append("\t"); buf.append((this.insertString==null || this.insertString.trim().equalsIgnoreCase("null")) ? "" : this.insertString.trim()).append("\t"); buf.append((this.insertLocation==null || this.insertLocation.trim().equalsIgnoreCase("null")) ? "" : this.insertLocation.trim()).append("\t"); buf.append((this.format==null || this.format.trim().equalsIgnoreCase("null")) ? "" : this.format.trim()).append("\t"); //buf.append(this.splitType).append("\t"); // buf.append(this.splitMark).append("\t"); buf.append((this.fileInfoDict==null || this.fileInfoDict.trim().equalsIgnoreCase("null")) ? "" : this.fileInfoDict.trim()).append("\t"); buf.append((this.fileInfoDictName==null || this.fileInfoDictName.trim().equalsIgnoreCase("null")) ? "" : this.fileInfoDictName.trim()).append("\t"); buf.append(this.desc).append("\t"); buf.append(this.orderNum).append("\t"); buf.append((this.moneyField == null || this.moneyField.trim().equalsIgnoreCase("null")) ? "0" : this.moneyField.trim()).append("\t"); buf.append((this.moneyUnit == null || this.moneyUnit.trim().equalsIgnoreCase("null")) ? "" : this.moneyUnit.trim()).append("\t"); buf.append((this.formatType == null || this.formatType.trim().equalsIgnoreCase("null")) ? "S" : this.formatType.trim()).append("\t"); buf.append(super.buildRecLog()); return buf.toString(); } /** * getOperValue *Ӵ˷һӿڴȡʼ add liyu 0920 * sType=""; * ز beginRow+"\t"+Cols */ public String getOperValue(String sType) throws YssException{ Connection conn = dbl.loadConnection(); ResultSet rs = null; boolean bTrans = false; int beginRow = 0, Cols = 0; String strSql = ""; try{ strSql = " select count(FCusCFGCode) as FCusCFGCode,FBeginRow from " + pub.yssGetTableName("qsFileContent") + " where FCusCFGCode=" + dbl.sqlString(this.cusCfgCode) + " group by FBeginRow "; rs = dbl.openResultSet(strSql); while(rs.next()){ beginRow = rs.getInt("FCusCFGCode"); Cols = rs.getInt("FBeginRow"); } rs.close(); } catch(Exception e){ throw new YssException("ȡӿֵϢ", e,"com.yss.main.dataInterface.FileContentBean"); } finally{ try{ dbl.closeResultSetFinal(rs); dbl.endTransFinal(conn, bTrans); }catch(Exception ex){} } return beginRow + "\t" + Cols; } /** * getBeforeEditData * * @return String */ /** * getBeforeEditData * * @return String */ public String getBeforeEditData(){ return ""; } public ArrayList getContents() throws YssException{ String strSql = ""; ResultSet rs = null; ArrayList list = new ArrayList(); FileContentBean fileContentBean = null; try{ strSql = "select a.*,b.ffieldDesc,c.fcuscfgname,d.fdictname from qsfileContent a " + " left join(select FFieldName,FFieldDesc from sysDATADICT where FTabName = " + dbl.sqlString(this.tabName) + " ) b on b.ffieldName = a.Ftabfeild " + " left join (select FCusCfgCode,FCusCfgName from " + pub.yssGetTableName("qsCusConfig") + ") c on a.FCusCfgCode = c.FCusCfgCode" + " left join (select FDictCode,FDictName from " + pub.yssGetTableName("qsDict") + " group by FDictCode,FDictName" + " ) d on a.FFileContentDict = d.FDictCode " + " where a.FCusCFGCode=" + dbl.sqlString(this.cusCfgCode)//WLX 2011-06-30 11gݿбδȷС + " order by fordernum"; // strSql = // "select a.*,b.ffieldDesc,c.fcuscfgname,'' as fdictname from qsfileContent a " // + " left join(select FFieldName,FFieldDesc from sysDATADICT where FTabName = " // + dbl.sqlString(this.tabName) // + " ) b on b.ffieldName = a.Ftabfeild " // + " left join (select FCusCfgCode,FCusCfgName from " // + pub.yssGetTableName("qsCusConfig") // + ") c on a.FCusCfgCode = c.FCusCfgCode" // + " where FCusCFGCode=" + dbl.sqlString(this.cusCfgCode) // + " order by fordernum"; rs = dbl.openResultSet(strSql); while(rs.next()){ fileContentBean = new FileContentBean(); fileContentBean.setYssPub(pub); fileContentBean.setDaoFileContentAttr(rs); list.add(Integer.parseInt(fileContentBean.orderNum) - 1, fileContentBean); } return list; } catch(Exception ex){ throw new YssException(ex); }finally{ try{ if(rs != null) dbl.closeResultSetFinal(rs); }catch(Exception e){System.out.println(e.getMessage());} } } public ArrayList getSplitContents() throws YssException{ String strSql = ""; ResultSet rs = null; ArrayList list = new ArrayList(); FileContentBean fileContentBean = null; try{ strSql = "select a.*,b.ffieldDesc,c.fcuscfgname,d.fdictname from qsfileContent a " + " left join(select FFieldName,FFieldDesc from sysDATADICT where FTabName = " + dbl.sqlString(this.tabName) + " ) b on b.ffieldName = a.Ftabfeild " + " left join (select FCusCfgCode,FCusCfgName from " + pub.yssGetTableName("qsCusConfig") + ") c on a.FCusCfgCode = c.FCusCfgCode" + " left join (select FDictCode,FDictName from " + pub.yssGetTableName("qsDict") + " group by FDictCode,FDictName" + " ) d on a.FFileContentDict = d.FDictCode " + " where a.FCusCFGCode=" + dbl.sqlString(this.cusCfgCode)//2011-10-17 TAV42011101401_B + " order by floadindex"; // strSql = // "select a.*,b.ffieldDesc,c.fcuscfgname,'' as fdictname from qsfileContent a " // + " left join(select FFieldName,FFieldDesc from sysDATADICT where FTabName = " // + dbl.sqlString(this.tabName) // + " ) b on b.ffieldName = a.Ftabfeild " // + " left join (select FCusCfgCode,FCusCfgName from " // + pub.yssGetTableName("qsCusConfig") // + ") c on a.FCusCfgCode = c.FCusCfgCode" // + " where FCusCFGCode=" + dbl.sqlString(this.cusCfgCode) // + " order by fordernum"; rs = dbl.openResultSet(strSql); while(rs.next()){ fileContentBean = new FileContentBean(); fileContentBean.setYssPub(pub); fileContentBean.setDaoFileContentAttr(rs); //#158256 ݳsqllordؼļ start ygs //if(this.fileType.equalsIgnoreCase("3") || this.fileType.equalsIgnoreCase("1") || this.fileType.equalsIgnoreCase("7")) { //ļΪxls,xlsxȡд0пʼ,txt,ȡд1пʼ if(this.fileType.equalsIgnoreCase("3") || this.fileType.equalsIgnoreCase("1")) { //#158256 ݳsqllordؼļ end ygs list.add(Integer.parseInt(fileContentBean.getLoadIndex()), fileContentBean); } else { list.add(Integer.parseInt(fileContentBean.getLoadIndex()) - 1, fileContentBean); } // list.add(Integer.parseInt(fileContentBean.loadIndex) - 1, // fileContentBean); } return list; } catch(Exception ex){ throw new YssException(ex); }finally{ try{ if(rs != null) dbl.closeResultSetFinal(rs); }catch(Exception e){System.out.println(e.getMessage());} } } /** * getListViewData5 * * @return String */ public String getListViewData5(){ return ""; } /** * cleanSetting */ public void cleanSetting(){ } /** * builderListViewDataEx * * @param strSql0 String * @param strSql1 String * @param strSql2 String * @return String */ public String builderListViewDataEx(String strSql0, String strSql1, String strSql2){ return ""; } /** * setEntityAttr * * @param rs ResultSet */ public void setEntityAttr(ResultSet rs){ } /** * batchOperation * * @param allData String * @return String */ public String batchOperation(String allData){ return ""; } public String getInsertString() { return insertString; } public void setInsertString(String insertString) { this.insertString = insertString; } public String getInsertLocation() { return insertLocation; } public void setInsertLocation(String insertLocation) { this.insertLocation = insertLocation; } public String getFieldpre() { return fieldpre; } public void setFieldpre(String fieldpre) { this.fieldpre = fieldpre; } public String getFormatType() { return formatType; } public void setFormatType(String formatType) { this.formatType = formatType; } }
true
6c384117006011d2e7c996cb6ae1fd49fe213a1c
Java
wuyuf/Algorithm_IntroDuction
/Documents/wokepace F Eclipse/STUDY_JAVA/src/java_eleven/RegexFinal.java
UTF-8
526
3.265625
3
[]
no_license
package java_eleven; import java.util.*; public class RegexFinal { public static void main(String args[]){ String str1 = "A1B22C333D4444E55555F".replaceAll("\\d+", "_"); boolean temp = "1983-07-27".matches("\\d{4}-\\d{2}-\\d{2}"); String s[] = "A1B22C333D4444E55555F".split("\\d+"); System.out.println("字符串替换操作:" + str1) ; System.out.println("字符串验证:" + temp) ; System.out.print("字符串的拆分:") ; for(int x=0;x<s.length;x++){ System.out.println(s[x] + "\t"); } } }
true
19c13732031505ba000f2c21afffd07d3acc2900
Java
alsansone/Intro_To_Java_Programming_Exercises
/CHAPTER 9 - Objects & Classes/Account/src/Exercise_9_07.java
UTF-8
699
3.703125
4
[]
no_license
public class Exercise_9_07 { public static void main(String[] args) { // new Account object Account account = new Account(1122, 20000); // sets annual interest rate for all objects of Account class Account.setAnnualInterestRate(4.5); // invoke withdraw and deposit methods account.withdraw(2500); account.deposit(3000); // display account object details System.out.println("Balance is " + account.getBalance()); System.out.println("Monthly interest is " + account.getMonthlyInterest()); System.out.println("This account was created at " + account.getDateCreated()); } }
true
58e3b85fc4d94b7b52b8e8c888118e9fad270700
Java
marcomarcolinozup/bootcamp-template-proposta
/src/main/java/br/com/zup/bootcamp/proposta/config/AnaliseConfig.java
UTF-8
316
1.820313
2
[]
no_license
package br.com.zup.bootcamp.proposta.config; import feign.Logger; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class AnaliseConfig { @Bean Logger.Level feignLoggerLevel() { return Logger.Level.NONE; } }
true
ca1ee34e32c54e234fb6239720749a74cbee2dfc
Java
cyferlawyn/regain-control
/src/main/java/de/cydev/controller/TaskController.java
UTF-8
880
2.328125
2
[]
no_license
package de.cydev.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import de.cydev.model.tasks.Task; import de.cydev.repositories.TaskRepository; @Controller public class TaskController { @Autowired TaskRepository taskRepository; public Task createTask(Task task) { return taskRepository.save(task); } public Task getTaskById(Long id) { return taskRepository.findOne(id); } public Task updateTask(Long id, Task updatedTask) { Task task = taskRepository.findOne(id); if (task != null) { task.setTitle(updatedTask.getTitle()); task.setPriority(updatedTask.getPriority()); taskRepository.save(task); return task; } return null; } public void deleteTask(Long id) { taskRepository.delete(id); } }
true
88dad7238514b17e329b15146b1d0a631c05bd9b
Java
HelintonAlves/SistemaFinanceiro
/IDE/eclipse/configuration/org.eclipse.osgi/1340/0/.cp/src/com/jaspersoft/studio/toolbars/alignment/JoinRightAlignmentContributionItem.java
UTF-8
1,736
2.203125
2
[]
no_license
/******************************************************************************* * Copyright (C) 2010 - 2016. TIBCO Software Inc. * All Rights Reserved. Confidential & Proprietary. ******************************************************************************/ package com.jaspersoft.studio.toolbars.alignment; import org.eclipse.swt.SWT; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.ToolBar; import org.eclipse.swt.widgets.ToolItem; import com.jaspersoft.studio.JaspersoftStudioPlugin; import com.jaspersoft.studio.messages.Messages; /** * Toolitem to join vertically the selected elements * * @author Orlandin Marco * */ public class JoinRightAlignmentContributionItem extends AbstractAlignmentContributionItem{ @Override protected Control createControl(Composite parent) { ToolBar buttons = new ToolBar(parent, SWT.FLAT | SWT.WRAP); ToolItem button = new ToolItem(buttons, SWT.PUSH); button.setToolTipText(Messages.JoinRightAction_actionDescription); button.setImage(JaspersoftStudioPlugin.getInstance().getImage("icons/resources/joinright.png")); button.setData(WIDGET_DATA_KEY, JOIN_DIRECTION.RIGHT); button.addSelectionListener(joinButtonPressed); return buttons; } @Override protected boolean fillWithToolItems(ToolBar parent) { ToolItem joinRight = new ToolItem(parent, SWT.PUSH); joinRight.setToolTipText(Messages.JoinRightAction_actionDescription); joinRight.setImage(JaspersoftStudioPlugin.getInstance().getImage("icons/resources/joinright.png")); joinRight.setData(WIDGET_DATA_KEY, JOIN_DIRECTION.RIGHT); joinRight.addSelectionListener(joinButtonPressed); getToolItems().add(joinRight); return true; } }
true
bd574c5e04715607722890a9c84761f64502ba6d
Java
reason1241/INHAMAP
/app/src/main/java/com/example/inhamap/Adapter/BuildingData.java
UTF-8
860
2.734375
3
[]
no_license
package com.example.inhamap.Adapter; import java.util.ArrayList; public class BuildingData { /* 이걸 비롯해서 빌딩이름 이라는 파라미터(하나만 넘어옴)를 이용해서 객체지향적으로 활용할수 있도록 작성. 일단, static한 정보들 어디 저장해야함. 건물이름, 건물주소, 건물 설명, 문1, 문2, ... , 문3, 문 개수를 갖고 있어야함. */ public String buildingName; public String buildingAddress; public String buildingExplain; public int numberOfDoors; public BuildingData(String BuildingName, String buildingAddress, String buildingExplain, int numberOfDoors){ this.buildingName = BuildingName; this.buildingAddress = buildingAddress; this.buildingExplain = buildingExplain; this.numberOfDoors = numberOfDoors; } }
true
34cfe7234a3bd5c187ff5b1cfdfa0a618e8270e6
Java
ComradeBaz/Covid19Boot
/src/main/java/com/domrade/entity/implementation/UsLocations.java
UTF-8
467
1.851563
2
[]
no_license
package com.domrade.entity.implementation; import javax.persistence.Basic; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name = "us_locations") public class UsLocations { @Id @Basic private long id; @Basic @Column(name = "state_id") private long stateId; @Basic private String county; public UsLocations() { // TODO Auto-generated constructor stub } }
true
2c838b2d8a35c07de3a8592c6697f0e2a142698b
Java
cws3299/timeline
/timeSNS/src/main/java/com/timeSNS/dto/MemberModifySignDto.java
UTF-8
583
1.71875
2
[]
no_license
package com.timeSNS.dto; import java.time.LocalDate; import java.time.LocalDateTime; import org.springframework.web.multipart.MultipartFile; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; @Getter @Setter @Builder @AllArgsConstructor @NoArgsConstructor public class MemberModifySignDto { private String mid; private String mpwd; private LocalDateTime mregdate; private MultipartFile mphoto; private String mnickname; private String mproduce; private String mbirthday; }
true
ce2a6f4bc10eff348a740a23797bc90be40b318c
Java
mayavend/TestRepo
/Test/NestedIfPractice.java
UTF-8
422
3.515625
4
[]
no_license
package Test; public class NestedIfPractice { public static void main(String[] args) { //if x>5 and y>5 then print x and y are greater than 5 int x = 6; int y = 4; if (x > 5) { if (y > 5) System.out.println("Both x and y are greater than 5"); } else System.out.println("x is less than or equal to 5"); } }
true
2ca5d15effea97078323a6e0acd4cd7eed55b230
Java
StanislavShelest/School
/List/src/shelest/list/singlyLinkedList/ListElement.java
UTF-8
580
3.359375
3
[]
no_license
package shelest.list.singlyLinkedList; public class ListElement<T> { private T data; private ListElement<T> next; public ListElement(T data) { this.data = data; } public ListElement(T data, ListElement<T> next) { this.data = data; this.next = next; } public T getData() { return this.data; } public void setData(T data) { this.data = data; } public ListElement<T> getNext() { return this.next; } public void setNext(ListElement<T> next) { this.next = next; } }
true
80344dd01571ff6122c3c17a7521dc8024d9e4dc
Java
RONGYijing/BDPA_Assign2_YRONG
/code/similarityjoin_B.java
UTF-8
6,396
2.484375
2
[]
no_license
package yijing.assignment2; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.io.OutputStreamWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.TreeSet; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.conf.Configured; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.lib.input.FileInputFormat; import org.apache.hadoop.mapreduce.lib.input.KeyValueTextInputFormat; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.Mapper; import org.apache.hadoop.mapreduce.Reducer; import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat; import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat; import org.apache.hadoop.util.Tool; import org.apache.hadoop.util.ToolRunner; public class similarityjoin_B extends Configured implements Tool { // define a customer counter to count the number of comparisons public static enum MYCOUNTER { totcompare_b, }; public static void main(String[] args) throws Exception { System.out.println(Arrays.toString(args)); int res = ToolRunner.run(new Configuration(), new similarityjoin_B(), args); System.exit(res); } @Override public int run(String[] args) throws Exception { System.out.println(Arrays.toString(args)); Job myjob = Job.getInstance(getConf(), "similarityjoin_B"); myjob.setJarByClass(similarityjoin_B.class); FileInputFormat.addInputPath(myjob, new Path(args[0])); FileOutputFormat.setOutputPath(myjob, new Path(args[1])); myjob.setMapperClass(Map.class); myjob.setReducerClass(Reduce.class); myjob.setMapOutputKeyClass(Text.class); myjob.setMapOutputValueClass(Text.class); myjob.setOutputKeyClass(Text.class); myjob.setOutputValueClass(Text.class); myjob.setInputFormatClass(KeyValueTextInputFormat.class); myjob.setOutputFormatClass(TextOutputFormat.class); myjob.getConfiguration().set( "mapreduce.input.keyvaluelinerecordreader.key.value.separator", ","); myjob.getConfiguration().set( "mapreduce.output.textoutputformat.separator", ", "); myjob.setNumReduceTasks(1); FileSystem fs = FileSystem.newInstance(getConf()); if (fs.exists(new Path(args[1]))) { fs.delete(new Path(args[1]), true); } // save the counter value in HDFS as a text file myjob.waitForCompletion(true); long mycounter = myjob.getCounters() .findCounter(MYCOUNTER.totcompare_b).getValue(); Path outFile = new Path("totcompare_b.txt"); BufferedWriter br = new BufferedWriter(new OutputStreamWriter( fs.create(outFile, true))); br.write(String.valueOf(mycounter)); br.close(); return 0; } public static class Map extends Mapper<Text, Text, Text, Text> { private Text word = new Text(); // define the number |d| - [0.8|d] + 1 @Override public void map(Text key, Text value, Context context) throws IOException, InterruptedException { String[] wordlength = value.toString().split(" "); long nb_keep = Math.round(wordlength.length - (wordlength.length * 0.8) + 1); String[] keeplength = Arrays.copyOfRange(wordlength, 0, (int) nb_keep); // output an inverted index for each selected words for (String keep : keeplength) { word.set(keep); context.write(word, key); } } } public static class Reduce extends Reducer<Text, Text, Text, Text> { private BufferedReader reader; // compute the jaccard similarity (intersection/union) public double similarity(TreeSet<String> str1, TreeSet<String> str2) { if (str1.size() < str2.size()) { TreeSet<String> s1bis = str1; s1bis.retainAll(str2); int intersection = s1bis.size(); str1.addAll(str2); int union = str1.size(); return (double) intersection / union; } else { TreeSet<String> s1bis = str2; s1bis.retainAll(str1); int intersection = s1bis.size(); str2.addAll(str1); int union = str2.size(); return (double) intersection / union; } } // load the word list (without frequency) into a HashMap @Override public void reduce(Text key, Iterable<Text> values, Context context) throws IOException, InterruptedException { HashMap<String, String> lineshashmap = new HashMap<String, String>(); reader = new BufferedReader( new FileReader( new File( "/home/cloudera/workspace/assignment2/output/wordlist_asc.txt"))); String pattern; while ((pattern = reader.readLine()) != null) { String[] line = pattern.split(","); lineshashmap.put(line[0], line[1]); } ArrayList<String> wordlength = new ArrayList<String>(); for (Text word : values) { wordlength.add(word.toString()); } //If a word is not present in only one document, we get all possible pairs if (wordlength.size() > 1) { ArrayList<String> pairs = new ArrayList<String>(); for (int i = 0; i < wordlength.size(); ++i) { for (int j = i + 1; j < wordlength.size(); ++j) { String pair = new String(wordlength.get(i) + " " + wordlength.get(j)); pairs.add(pair); } } // create 2 sets to compute the similiarity for (String pair : pairs) { TreeSet<String> words_1_treeset = new TreeSet<String>(); String words_1_string = lineshashmap .get(pair.split(" ")[0].toString()); for (String word : words_1_string.split(" ")) { words_1_treeset.add(word); } TreeSet<String> words_2_treeset = new TreeSet<String>(); String words_2_string = lineshashmap .get(pair.split(" ")[1].toString()); for (String word : words_2_string.split(" ")) { words_2_treeset.add(word); } // compute the jaccard similarity between 2 sets double sim = similarity(words_1_treeset, words_2_treeset); // increment the counter by 1 context.getCounter(MYCOUNTER.totcompare_b).increment(1); // Assuming threshold t = 0.8 if (sim >= 0.8) { context.write(new Text("(" + pair.split(" ")[0] + ", " + pair.split(" ")[1] + ")"), new Text(String.valueOf(sim))); } } } } } }
true
80ac3639bf62401b94929ac47bda8cdaf0ef6009
Java
mxh13920/api-sleeve
/src/main/java/com/meng/sleeve/service/AuthenticationService.java
UTF-8
341
1.53125
2
[]
no_license
package com.meng.sleeve.service; import com.meng.sleeve.dto.TokenGetDTO; import org.springframework.stereotype.Service; @Service public class AuthenticationService { public void getEmailByToken(TokenGetDTO tokenGetDTO){} public void getWxByToken(TokenGetDTO tokenGetDTO){} public void register(TokenGetDTO tokenGetDTO){} }
true
ebbe2a778ceeaab62d1b80eba4c52cdd806af326
Java
atreceno/diaulos
/src/main/java/com/atreceno/it/diaulos/domain/Lap.java
UTF-8
1,107
2.109375
2
[]
no_license
package com.atreceno.it.diaulos.domain; import java.math.BigDecimal; import java.util.HashSet; import java.util.Set; import javax.persistence.CascadeType; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; import org.springframework.roo.addon.equals.RooEquals; import org.springframework.roo.addon.javabean.RooJavaBean; import org.springframework.roo.addon.jpa.entity.RooJpaEntity; import org.springframework.roo.addon.json.RooJson; import org.springframework.roo.addon.tostring.RooToString; @RooJavaBean @RooToString(excludeFields = { "participants" }) @RooJpaEntity @RooEquals @RooJson public class Lap { @NotNull private String code; @Size(max = 20) private String name; private BigDecimal cumulativeDistance; private BigDecimal partialDistance; @NotNull @ManyToOne @JoinColumn(name = "race_id") private Race race; @OneToMany(cascade = CascadeType.ALL, mappedBy = "lap") private Set<ParticLap> participants = new HashSet<ParticLap>(); }
true
8c02194dd80de8ae2c65ce7c3cd20eb6e657292a
Java
hyena811004/dxa-web-application-java
/dxa-framework/dxa-common-api/src/main/java/com/sdl/webapp/common/markup/Markup.java
UTF-8
3,328
2.171875
2
[ "Apache-2.0" ]
permissive
package com.sdl.webapp.common.markup; import com.sdl.webapp.common.api.WebRequestContext; import com.sdl.webapp.common.api.model.EntityModel; import com.sdl.webapp.common.api.model.RegionModel; import com.sdl.webapp.common.api.model.entity.SitemapItem; import org.joda.time.DateTime; /** * <p>Markup interface.</p> */ public interface Markup { /** * <p>url.</p> * * @param path a {@link java.lang.String} object. * @return a {@link java.lang.String} object. */ String url(String path); /** * <p>versionedContent.</p> * * @param path a {@link java.lang.String} object. * @return a {@link java.lang.String} object. */ String versionedContent(String path); /** * <p>region.</p> * * @param region a {@link com.sdl.webapp.common.api.model.RegionModel} object. * @return a {@link java.lang.String} object. */ String region(RegionModel region); /** * <p>entity.</p> * * @param entity a {@link com.sdl.webapp.common.api.model.EntityModel} object. * @return a {@link java.lang.String} object. */ String entity(EntityModel entity); /** * <p>property.</p> * * @param entity a {@link com.sdl.webapp.common.api.model.EntityModel} object. * @param fieldName a {@link java.lang.String} object. * @return a {@link java.lang.String} object. */ String property(EntityModel entity, String fieldName); /** * <p>property.</p> * * @param entity a {@link com.sdl.webapp.common.api.model.EntityModel} object. * @param fieldName a {@link java.lang.String} object. * @param index a int. * @return a {@link java.lang.String} object. */ String property(EntityModel entity, String fieldName, int index); /** * <p>resource.</p> * * @param key a {@link java.lang.String} object. * @return a {@link java.lang.String} object. */ String resource(String key); /** * <p>formatDate.</p> * * @param dateTime a {@link org.joda.time.DateTime} object. * @return a {@link java.lang.String} object. */ String formatDate(DateTime dateTime); /** * <p>formatDateDiff.</p> * * @param dateTime a {@link org.joda.time.DateTime} object. * @return a {@link java.lang.String} object. */ String formatDateDiff(DateTime dateTime); /** * <p>formatMessage.</p> * * @param pattern a {@link java.lang.String} object. * @param args a {@link java.lang.Object} object. * @return a {@link java.lang.String} object. */ String formatMessage(String pattern, Object... args); /** * <p>replaceLineEndsWithHtmlBreaks.</p> * * @param text a {@link java.lang.String} object. * @return a {@link java.lang.String} object. */ String replaceLineEndsWithHtmlBreaks(String text); /** * <p>siteMapList.</p> * * @param item a {@link com.sdl.webapp.common.api.model.entity.SitemapItem} object. * @return a {@link java.lang.String} object. */ String siteMapList(SitemapItem item); /** * <p>getWebRequestContext.</p> * * @return a {@link com.sdl.webapp.common.api.WebRequestContext} object. */ WebRequestContext getWebRequestContext(); }
true
265041e7194f255d8b039f2132c2e4f573b47733
Java
ASparton/Towa
/test/towa/JoueurTowaTest.java
UTF-8
52,942
2.703125
3
[]
no_license
package towa; import org.junit.Assert; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import org.junit.Test; /** * Tests sur la classe JoueurTowa. */ public class JoueurTowaTest { /** * Test de la fonction actionsPossibles. Commentez les appels aux tests des * niveaux inférieurs, n'activez que le test du niveau à valider. */ @Test public void testActionsPossibles() { //testActionsPossibles_niveau1(); //testActionsPossibles_niveau2(); //testActionPossibles_niveau3(); //testActionsPossibles_niveau4(); //testActionsPossibles_niveau5(); //testActionsPossibles_niveau6(); //testActionPossibles_niveau7(); testActionPossibles_niveau8(); } /** * Test de la fonction actionsPossibles, au niveau 1. */ public void testActionsPossibles_niveau1() { JoueurTowa joueur = new JoueurTowa(); // un plateau sur lequel on veut tester actionsPossibles() Case[][] plateau = Utils.plateauDepuisTexte(PLATEAU_NIVEAU1); // on choisit la couleur du joueur boolean estNoir = true; // on choisit le niveau int niveau = 1; // on lance actionsPossibles String[] actionsPossibles = joueur.actionsPossibles(plateau, estNoir, niveau); // on peut afficher toutes les actions possibles calculées : Utils.afficherActionsPossibles(actionsPossibles); // on peut aussi tester si une action est dans les actions possibles : assertTrue(Utils.actionsPossiblesContient(actionsPossibles, "PaB,1,0")); // on peut aussi tester si une action n'est pas dans les actions // possibles : assertFalse(Utils.actionsPossiblesContient(actionsPossibles, "PaQ,1,0")); assertFalse(Utils.actionsPossiblesContient(actionsPossibles, "PaA,0,0")); // testons les 4 coins : assertTrue(Utils.actionsPossiblesContient(actionsPossibles, "PaA,1,0")); assertTrue(Utils.actionsPossiblesContient(actionsPossibles, "PpA,1,0")); assertTrue(Utils.actionsPossiblesContient(actionsPossibles, "PaP,1,0")); assertTrue(Utils.actionsPossiblesContient(actionsPossibles, "PpP,1,0")); // vérifions s'il y a le bon nombre d'actions possibles : assertEquals(Coordonnees.NB_LIGNES * Coordonnees.NB_COLONNES, actionsPossibles.length); } /** * Test de la fonction actionsPossibles, au niveau 2. */ public void testActionsPossibles_niveau2() { JoueurTowa joueur = new JoueurTowa(); Case[][] plateau = Utils.plateauDepuisTexte(PLATEAU_NIVEAU2); boolean estNoir = true; int niveau = 2; int nbPionsNoir = JoueurTowa.nbPions(plateau, true); int nbPionsBlancs = JoueurTowa.nbPions(plateau, false); // on lance actionsPossibles pour un joueur noir String[] actionsPossibles = joueur.actionsPossibles(plateau, estNoir, niveau); Coordonnees coord; // pose sur case vide : possible coord = Coordonnees.depuisCars('a', 'B'); assertTrue(Utils.actionsPossiblesContient(actionsPossibles, JoueurTowa.chaineActionPose(coord, nbPionsNoir + 1, nbPionsBlancs))); // pose sur case de même couleur : possible coord = Coordonnees.depuisCars('b', 'A'); assertTrue(Utils.actionsPossiblesContient(actionsPossibles, JoueurTowa.chaineActionPose(coord, nbPionsNoir + 1, nbPionsBlancs))); // pose sur case de couleur opposée : impossible coord = Coordonnees.depuisCars('a', 'G'); assertFalse(Utils.actionsPossiblesContient(actionsPossibles, JoueurTowa.chaineActionPose(coord, nbPionsNoir + 1, nbPionsBlancs))); // pose sur case de même couleur et hauteur > 1 : possible coord = Coordonnees.depuisCars('k', 'J'); assertTrue(Utils.actionsPossiblesContient(actionsPossibles, JoueurTowa.chaineActionPose(coord, nbPionsNoir + 1, nbPionsBlancs))); // on lance actionsPossibles pour un joueur blanc actionsPossibles = joueur.actionsPossibles(plateau, !estNoir, niveau); // pose sur case vide : possible coord = Coordonnees.depuisCars('a', 'B'); assertTrue(Utils.actionsPossiblesContient(actionsPossibles, JoueurTowa.chaineActionPose(coord, nbPionsNoir, nbPionsBlancs + 2))); // pose sur case de même couleur : possible coord = Coordonnees.depuisCars('a', 'G'); assertTrue(Utils.actionsPossiblesContient(actionsPossibles, JoueurTowa.chaineActionPose(coord, nbPionsNoir, nbPionsBlancs + 1))); // pose sur case de couleur opposée : impossible coord = Coordonnees.depuisCars('b', 'A'); assertFalse(Utils.actionsPossiblesContient(actionsPossibles, JoueurTowa.chaineActionPose(coord, nbPionsNoir, nbPionsBlancs + 1))); // pose sur case de même couleur et hauteur > 1 : possible coord = Coordonnees.depuisCars('m', 'F'); assertTrue(Utils.actionsPossiblesContient(actionsPossibles, JoueurTowa.chaineActionPose(coord, nbPionsNoir, nbPionsBlancs + 1))); } /** * Test de la fonction actionsPossibles, au niveau 3. */ public void testActionsPossibles_niveau3() { //Passe car modifiée et permet d'économiser des lignes de codes testActionsPossibles_niveau2(); JoueurTowa joueur = new JoueurTowa(); Case[][] plateau = Utils.plateauDepuisTexte(PLATEAU_NIVEAU3_4_5_6_7_8); boolean estNoir = true; int niveau = 3; int nbPionsNoir = JoueurTowa.nbPions(plateau, true); int nbPionsBlancs = JoueurTowa.nbPions(plateau, false); // on lance actionsPossibles pour un joueur noir String[] actionsPossibles = joueur.actionsPossibles(plateau, estNoir, niveau); Coordonnees coord; // pose sur case de même couleur et hauteur supérieur ou égale à 4 : impossible coord = Coordonnees.depuisCars('i', 'B'); assertFalse(Utils.actionsPossiblesContient(actionsPossibles, JoueurTowa.chaineActionPose(coord, nbPionsNoir + 1, nbPionsBlancs))); // pose sur une case de même couleur et hauteur inférieur à 4 : possible coord = Coordonnees.depuisCars('l', 'E'); assertTrue(Utils.actionsPossiblesContient(actionsPossibles, JoueurTowa.chaineActionPose(coord, nbPionsNoir + 1, nbPionsBlancs))); // on lance actionsPossibles pour un joueur blanc actionsPossibles = joueur.actionsPossibles(plateau, !estNoir, niveau); // pose sur case de même couleur et hauteur supérieur ou égale à 4 : impossible coord = Coordonnees.depuisCars('l', 'F'); assertFalse(Utils.actionsPossiblesContient(actionsPossibles, JoueurTowa.chaineActionPose(coord, nbPionsNoir, nbPionsBlancs + 1))); /// pose sur une case de même couleur et hauteur inférieur à 4 : possible coord = Coordonnees.depuisCars('m', 'F'); assertTrue(Utils.actionsPossiblesContient(actionsPossibles, JoueurTowa.chaineActionPose(coord, nbPionsNoir, nbPionsBlancs + 1))); } /** * Test de la fonction actionsPossibles, au niveau 4. */ public void testActionsPossibles_niveau4() { JoueurTowa joueur = new JoueurTowa(); Case[][] plateau = Utils.plateauDepuisTexte(PLATEAU_NIVEAU3_4_5_6_7_8); boolean estNoir = true; int niveau = 4; int nbPionsNoir = JoueurTowa.nbPions(plateau, true); int nbPionsBlancs = JoueurTowa.nbPions(plateau, false); // on lance actionsPossibles pour un joueur noir String[] actionsPossibles = joueur.actionsPossibles(plateau, estNoir, niveau); Coordonnees coord; //activation sur une case vide : impossible coord = Coordonnees.depuisCars('a', 'A'); assertFalse(Utils.actionsPossiblesContient(actionsPossibles, JoueurTowa.chaineActionActiver(coord, nbPionsNoir, nbPionsBlancs - 3))); /*activation sur une case de même couleur sans autre(s) tour(s) adverse(s) adjacente(s): possible*/ coord = Coordonnees.depuisCars('b', 'A'); assertTrue(Utils.actionsPossiblesContient(actionsPossibles, JoueurTowa.chaineActionActiver(coord, nbPionsNoir, nbPionsBlancs))); /*activation sur une case de même couleur avec autre(s) tour(s) adverse(s) adjacente(s) moins haute: possible*/ coord = Coordonnees.depuisCars('l', 'E'); assertTrue(Utils.actionsPossiblesContient(actionsPossibles, JoueurTowa.chaineActionActiver(coord, nbPionsNoir, nbPionsBlancs - 3))); /*activation sur une case de même couleur avec autre(s) tour(s) adverse(s) adjacente(s) plus haute: possible*/ coord = Coordonnees.depuisCars('n', 'F'); assertTrue(Utils.actionsPossiblesContient(actionsPossibles, JoueurTowa.chaineActionActiver(coord, nbPionsNoir, nbPionsBlancs))); //activation sur une case de couleur opposée: impossible coord = Coordonnees.depuisCars('n', 'F'); assertFalse(Utils.actionsPossiblesContient(actionsPossibles, JoueurTowa.chaineActionActiver(coord, nbPionsNoir - 3, nbPionsBlancs))); // on lance actionsPossibles pour un joueur blanc actionsPossibles = joueur.actionsPossibles(plateau, !estNoir, niveau); //activation sur case vide: impossoble coord = Coordonnees.depuisCars('a', 'A'); assertFalse(Utils.actionsPossiblesContient(actionsPossibles, JoueurTowa.chaineActionActiver(coord, nbPionsNoir - 3, nbPionsBlancs))); /*activation sur une case de même couleur sans autre(s) tour(s) adverse(s) adjacente(s): possible*/ coord = Coordonnees.depuisCars('d', 'I'); assertTrue(Utils.actionsPossiblesContient(actionsPossibles, JoueurTowa.chaineActionActiver(coord, nbPionsNoir, nbPionsBlancs))); /*activation sur une case de même couleur avec autre(s) tour(s) adverse(s) adjacente(s) moins haute: possible*/ coord = Coordonnees.depuisCars('l', 'F'); assertTrue(Utils.actionsPossiblesContient(actionsPossibles, JoueurTowa.chaineActionActiver(coord, nbPionsNoir - 5, nbPionsBlancs))); /*activation sur une case de même couleur avec autre(s) tour(s) adverse(s) adjacente(s) plus haute: possible*/ coord = Coordonnees.depuisCars('c', 'L'); assertTrue(Utils.actionsPossiblesContient(actionsPossibles, JoueurTowa.chaineActionActiver(coord, nbPionsNoir, nbPionsBlancs))); //activation sur une case de couleur opposée: impossible coord = Coordonnees.depuisCars('c', 'K'); assertFalse(Utils.actionsPossiblesContient(actionsPossibles, JoueurTowa.chaineActionActiver(coord, nbPionsNoir, nbPionsBlancs - 15))); } /** * Test de la fonction actionsPossibles, au niveau 5. */ void testActionsPossibles_niveau5() { //Testes de l'action activer, et de l'action pose basique //testActionsPossibles_niveau4(); JoueurTowa joueur = new JoueurTowa(); Case[][] plateau = Utils.plateauDepuisTexte(PLATEAU_NIVEAU3_4_5_6_7_8); Coordonnees coord; boolean joueurNoir; int niveau = 5; int nbPionsNoir = JoueurTowa.nbPions(plateau, true); int nbPionsBlancs = JoueurTowa.nbPions(plateau, false); // on lance actionsPossibles pour un joueur noir joueurNoir = true; String[] actionsPossibles = joueur.actionsPossibles(plateau, joueurNoir, niveau); //on teste pour une case vide qui n'a pas de tours adverses adjacentes coord = Coordonnees.depuisCars('n', 'B'); assertTrue(Utils.actionsPossiblesContient(actionsPossibles, JoueurTowa.chaineActionPose(coord, nbPionsNoir + 1, nbPionsBlancs))); //on teste pour une case vide qui a des tours adverses adjacentes coord = Coordonnees.depuisCars('c', 'M'); assertTrue(Utils.actionsPossiblesContient(actionsPossibles, JoueurTowa.chaineActionPose(coord, nbPionsNoir + 2, nbPionsBlancs))); // on lance actionsPossibles pour un joueur blanc joueurNoir = false; actionsPossibles = joueur.actionsPossibles(plateau, joueurNoir, niveau); //on teste pour une case vide qui n'a pas de tours adverses adjacentes coord = Coordonnees.depuisCars('p', 'P'); assertTrue(Utils.actionsPossiblesContient(actionsPossibles, JoueurTowa.chaineActionPose(coord, nbPionsNoir, nbPionsBlancs + 1))); //on teste pour une case vide qui a des tours adverses adjacentes coord = Coordonnees.depuisCars('i', 'K'); assertTrue(Utils.actionsPossiblesContient(actionsPossibles, JoueurTowa.chaineActionPose(coord, nbPionsNoir, nbPionsBlancs + 2))); } /** * Test de la fonction actionsPossibles, au niveau 6. */ void testActionsPossibles_niveau6() { JoueurTowa joueur = new JoueurTowa(); Case[][] plateau = Utils.plateauDepuisTexte(PLATEAU_NIVEAU3_4_5_6_7_8); Coordonnees coord; boolean joueurNoir; int niveau = 6; int nbPionsNoir = JoueurTowa.nbPions(plateau, true); int nbPionsBlancs = JoueurTowa.nbPions(plateau, false); //on lance actionsPossibles pour un joueur noir joueurNoir = true; String[] actionsPossibles = joueur.actionsPossibles(plateau, joueurNoir, niveau); //on teste une activation sans tours ennemies adjacentes/lignes/colonnes coord = Coordonnees.depuisCars('i', 'M'); assertTrue(Utils.actionsPossiblesContient(actionsPossibles, JoueurTowa.chaineActionActiver(coord, nbPionsNoir, nbPionsBlancs))); //on teste une activation avec tours ennemies adjacentes/lignes/colonnes coord = Coordonnees.depuisCars('c', 'K'); assertTrue(Utils.actionsPossiblesContient(actionsPossibles, JoueurTowa.chaineActionActiver(coord, nbPionsNoir, nbPionsBlancs - 5))); //on lance actionsPossibles pour un joueur blanc joueurNoir = false; actionsPossibles = joueur.actionsPossibles(plateau, joueurNoir, niveau); //on teste une activation sans tours ennemies adjacentes/lignes/colonnes coord = Coordonnees.depuisCars('k', 'O'); assertTrue(Utils.actionsPossiblesContient(actionsPossibles, JoueurTowa.chaineActionActiver(coord, nbPionsNoir, nbPionsBlancs))); //on teste une activation avec tours ennemies adjacentes/lignes/colonnes coord = Coordonnees.depuisCars('o', 'C'); assertTrue(Utils.actionsPossiblesContient(actionsPossibles, JoueurTowa.chaineActionActiver(coord, nbPionsNoir - 3, nbPionsBlancs))); } void testActionPossibles_niveau7() { JoueurTowa joueur = new JoueurTowa(); Case[][] plateau = Utils.plateauDepuisTexte(PLATEAU_NIVEAU3_4_5_6_7_8); Coordonnees coord; boolean joueurNoir; int niveau = 7; int nbPionsNoir = JoueurTowa.nbPions(plateau, true); int nbPionsBlancs = JoueurTowa.nbPions(plateau, false); //on lance actionsPossibles pour un joueur noir joueurNoir = true; String[] actionsPossibles = joueur.actionsPossibles(plateau, joueurNoir, niveau); //on teste une activation sans tours ennemies adjacentes + lignes + colonnes coord = Coordonnees.depuisCars('i', 'N'); assertTrue(Utils.actionsPossiblesContient(actionsPossibles, JoueurTowa.chaineActionActiver(coord, nbPionsNoir, nbPionsBlancs))); //on teste une activation avec tours ennemies adjacentes + lignes + colonnes coord = Coordonnees.depuisCars('c', 'K'); assertTrue(Utils.actionsPossiblesContient(actionsPossibles, JoueurTowa.chaineActionActiver(coord, nbPionsNoir, nbPionsBlancs - 4))); //on teste une activation avec tours ennemies que sur les cases adjacentes coord = Coordonnees.depuisCars('l', 'E'); assertTrue(Utils.actionsPossiblesContient(actionsPossibles, JoueurTowa.chaineActionActiver(coord, nbPionsNoir, nbPionsBlancs - 3))); //on lance actionsPossibles pour un joueur blanc joueurNoir = false; actionsPossibles = joueur.actionsPossibles(plateau, joueurNoir, niveau); //on teste une activation sans tours ennemies adjacentes + lignes + colonnes coord = Coordonnees.depuisCars('c', 'C'); assertTrue(Utils.actionsPossiblesContient(actionsPossibles, JoueurTowa.chaineActionActiver(coord, nbPionsNoir, nbPionsBlancs))); //on teste une activation avec tours ennemies adjacentes + lignes + colonnes coord = Coordonnees.depuisCars('o', 'C'); assertTrue(Utils.actionsPossiblesContient(actionsPossibles, JoueurTowa.chaineActionActiver(coord, nbPionsNoir - 3, nbPionsBlancs))); //on teste une activation avec tours ennemies que sur les cases adjacentes coord = Coordonnees.depuisCars('m', 'F'); assertTrue(Utils.actionsPossiblesContient(actionsPossibles, JoueurTowa.chaineActionActiver(coord, nbPionsNoir - 3, nbPionsBlancs))); } void testActionPossibles_niveau8() { JoueurTowa joueur = new JoueurTowa(); Case[][] plateau = Utils.plateauDepuisTexte(PLATEAU_NIVEAU3_4_5_6_7_8); Coordonnees coord; boolean joueurNoir; int niveau = 8; int nbPionsNoir = JoueurTowa.nbPions(plateau, true); int nbPionsBlancs = JoueurTowa.nbPions(plateau, false); //on lance actionsPossibles pour un joueur noir joueurNoir = true; String[] actionsPossibles = joueur.actionsPossibles(plateau, joueurNoir, niveau); //on teste une fusion sans avec tours alliées adjacentes + colonne + ligne coord = Coordonnees.depuisCars('m', 'J'); assertTrue(Utils.actionsPossiblesContient(actionsPossibles, JoueurTowa.chaineActionFusion(coord, nbPionsNoir - 1, nbPionsBlancs))); //on teste une fusion avec uniquement des tours alliées adjacentes coord = Coordonnees.depuisCars('n', 'E'); assertTrue(Utils.actionsPossiblesContient(actionsPossibles, JoueurTowa.chaineActionFusion(coord, nbPionsNoir, nbPionsBlancs))); //on teste une fusion avec uniquement des tours alliées sur la ligne et/ou la colonne coord = Coordonnees.depuisCars('p', 'B'); assertTrue(Utils.actionsPossiblesContient(actionsPossibles, JoueurTowa.chaineActionFusion(coord, nbPionsNoir - 1, nbPionsBlancs))); //on teste une fusion avec aucune tour alliée à portée coord = Coordonnees.depuisCars('c', 'K'); assertTrue(Utils.actionsPossiblesContient(actionsPossibles, JoueurTowa.chaineActionFusion(coord, nbPionsNoir, nbPionsBlancs))); //on lance actionsPossibles pour un joueur blanc joueurNoir = false; actionsPossibles = joueur.actionsPossibles(plateau, joueurNoir, niveau); //on teste une fusion sans avec tours alliées adjacentes + colonne + ligne coord = Coordonnees.depuisCars('b', 'L'); assertTrue(Utils.actionsPossiblesContient(actionsPossibles, JoueurTowa.chaineActionFusion(coord, nbPionsNoir, nbPionsBlancs))); //on teste une fusion avec uniquement des tours alliées adjacentes coord = Coordonnees.depuisCars('m', 'F'); assertTrue(Utils.actionsPossiblesContient(actionsPossibles, JoueurTowa.chaineActionFusion(coord, nbPionsNoir, nbPionsBlancs - 4))); //on teste une fusion avec uniquement des tours alliées sur la ligne et/ou la colonne coord = Coordonnees.depuisCars('c', 'C'); assertTrue(Utils.actionsPossiblesContient(actionsPossibles, JoueurTowa.chaineActionFusion(coord, nbPionsNoir, nbPionsBlancs))); //on teste une fusion avec aucune tour alliée à portée coord = Coordonnees.depuisCars('p', 'G'); assertTrue(Utils.actionsPossiblesContient(actionsPossibles, JoueurTowa.chaineActionFusion(coord, nbPionsNoir, nbPionsBlancs))); } @Test public void testsMethodesBooleennes() { testPosePossible(); testEstMemeCouleurJoueur(); testCoordonneeEstDansPlateau(); testHauteurPlusPetite(); testExisteTourAdverseAdjacente(); testSuppressionPossible(); testFusionPossible(); } void testPosePossible() { JoueurTowa joueur = new JoueurTowa(); Case[][] plateau = Utils.plateauDepuisTexte(PLATEAU_NIVEAU3_4_5_6_7_8); boolean estNoir = true; //on teste pour un joueur noir Coordonnees coord; // pose sur case vide : possible coord = Coordonnees.depuisCars('a', 'B'); assertTrue(joueur.posePossible(plateau, coord, estNoir)); // pose sur case de même couleur : possible coord = Coordonnees.depuisCars('b', 'A'); assertTrue(joueur.posePossible(plateau, coord, estNoir)); // pose sur case de couleur opposée : impossible coord = Coordonnees.depuisCars('a', 'G'); assertFalse(joueur.posePossible(plateau, coord, estNoir)); // pose sur case de même couleur et hauteur > 1 : possible coord = Coordonnees.depuisCars('k', 'J'); assertTrue(joueur.posePossible(plateau, coord, estNoir)); // on lance actionsPossibles pour un joueur blanc estNoir = false; // pose sur case vide : possible coord = Coordonnees.depuisCars('a', 'B'); assertTrue(joueur.posePossible(plateau, coord, estNoir)); // pose sur case de même couleur : possible coord = Coordonnees.depuisCars('a', 'G'); assertTrue(joueur.posePossible(plateau, coord, estNoir)); // pose sur case de couleur opposée : impossible coord = Coordonnees.depuisCars('b', 'A'); assertFalse(joueur.posePossible(plateau, coord, estNoir)); // pose sur case de même couleur et hauteur > 1 : possible coord = Coordonnees.depuisCars('m', 'F'); assertTrue(joueur.posePossible(plateau, coord, estNoir)); } void testSuppressionPossible() { Case[][] plateau = Utils.plateauDepuisTexte(PLATEAU_NIVEAU3_4_5_6_7_8); boolean joueurNoir; Coordonnees coordActivation, coordATester; //Test pour le joueur noir joueurNoir = true; //Suppression possible pour une tour blanche de plus petite hauteur coordActivation = Coordonnees.depuisCars('c', 'K'); coordATester = Coordonnees.depuisCars('c', 'L'); assertTrue(JoueurTowa.suppressionPossible(plateau, coordATester, coordActivation, joueurNoir)); //Suppression impossible pour une tour blanche de même hauteur coordActivation = Coordonnees.depuisCars('c', 'K'); coordATester = Coordonnees.depuisCars('l', 'F'); assertFalse(JoueurTowa.suppressionPossible(plateau, coordATester, coordActivation, joueurNoir)); //Suppression impossible pour une tour noir coordActivation = Coordonnees.depuisCars('c', 'K'); coordATester = Coordonnees.depuisCars('b', 'A'); assertFalse(JoueurTowa.suppressionPossible(plateau, coordATester, coordActivation, joueurNoir)); //Suppression impossible pour une case vide coordActivation = Coordonnees.depuisCars('c', 'K'); coordATester = Coordonnees.depuisCars('a', 'B'); assertFalse(JoueurTowa.suppressionPossible(plateau, coordATester, coordActivation, joueurNoir)); //Test pour le joueur blanc joueurNoir = false; //Suppression possible pour une tour noire de plus petite hauteur coordActivation = Coordonnees.depuisCars('f', 'F'); coordATester = Coordonnees.depuisCars('g', 'J'); assertTrue(JoueurTowa.suppressionPossible(plateau, coordATester, coordActivation, joueurNoir)); //Suppression impossible pour une tour noire de même hauteur coordActivation = Coordonnees.depuisCars('f', 'F'); coordATester = Coordonnees.depuisCars('l', 'E'); assertFalse(JoueurTowa.suppressionPossible(plateau, coordATester, coordActivation, joueurNoir)); //Suppression impossible pour une tour blanche coordActivation = Coordonnees.depuisCars('f', 'F'); coordATester = Coordonnees.depuisCars('a', 'G'); assertFalse(JoueurTowa.suppressionPossible(plateau, coordATester, coordActivation, joueurNoir)); //Suppression impossible pour une case vide coordActivation = Coordonnees.depuisCars('f', 'F'); coordATester = Coordonnees.depuisCars('a', 'B'); assertFalse(JoueurTowa.suppressionPossible(plateau, coordATester, coordActivation, joueurNoir)); } void testFusionPossible() { Case[][] plateau = Utils.plateauDepuisTexte(PLATEAU_NIVEAU3_4_5_6_7_8); Coordonnees coord; boolean joueurNoir; //Test pour un joueur noir joueurNoir = true; //Test pour une tour de même couleur : possible coord = Coordonnees.depuisCars('i', 'C'); assertTrue(JoueurTowa.fusionPossible(plateau, coord, joueurNoir)); //Test pour une tour de couleur opposée : impossible coord = Coordonnees.depuisCars('a', 'G'); assertFalse(JoueurTowa.fusionPossible(plateau, coord, joueurNoir)); //Test pour une case vide: impossible coord = Coordonnees.depuisCars('a', 'A'); assertFalse(JoueurTowa.fusionPossible(plateau, coord, joueurNoir)); //Test pour un joueur blanc joueurNoir = false; //Test pour une tour de même couleur : possible coord = Coordonnees.depuisCars('a', 'G'); assertTrue(JoueurTowa.fusionPossible(plateau, coord, joueurNoir)); //Test pour une tour de couleur opposée : impossible coord = Coordonnees.depuisCars('i', 'C'); assertFalse(JoueurTowa.fusionPossible(plateau, coord, joueurNoir)); //Test pour une case vide: impossible coord = Coordonnees.depuisCars('a', 'A'); assertFalse(JoueurTowa.fusionPossible(plateau, coord, joueurNoir)); } void testEstMemeCouleurJoueur() { Case[][] plateau = Utils.plateauDepuisTexte(PLATEAU_NIVEAU3_4_5_6_7_8); Case caseATest; Coordonnees coord; boolean estNoir = true; //on teste pour le joueur noir //la case est de la même couleur : possible coord = Coordonnees.depuisCars('b', 'A'); caseATest = plateau[coord.ligne][coord.colonne]; assertTrue(JoueurTowa.caseEstMemeCouleurJoueur(caseATest, estNoir)); //la case n'est pas de la même couleur : impossible coord = Coordonnees.depuisCars('a', 'G'); caseATest = plateau[coord.ligne][coord.colonne]; assertFalse(JoueurTowa.caseEstMemeCouleurJoueur(caseATest, estNoir)); estNoir = false; //on teste pour le joueur blanc //la case est de la même couleur : possible coord = Coordonnees.depuisCars('a', 'G'); caseATest = plateau[coord.ligne][coord.colonne]; assertTrue(JoueurTowa.caseEstMemeCouleurJoueur(caseATest, estNoir)); //la case n'est pas de la même couleur : impossible coord = Coordonnees.depuisCars('b', 'A'); caseATest = plateau[coord.ligne][coord.colonne]; assertFalse(JoueurTowa.caseEstMemeCouleurJoueur(caseATest, estNoir)); } void testCoordonneeEstDansPlateau() { //x et y de la coordonnée dans le plateau : possible assertTrue(JoueurTowa.coordonneeEstDansPlateau(new Coordonnees(2, 7))); //uniquement x de la coordonnée dans le plateau : impossible assertFalse(JoueurTowa.coordonneeEstDansPlateau(new Coordonnees(10, 20))); //uniquement y de la coordonnée dans le plateau : impossible assertFalse(JoueurTowa.coordonneeEstDansPlateau(new Coordonnees(18, 4))); //x et y de la coordonnée pas dans le plateau : impossible assertFalse(JoueurTowa.coordonneeEstDansPlateau(new Coordonnees(16, 17))); } void testHauteurPlusPetite() { Case[][] plateau = Utils.plateauDepuisTexte(PLATEAU_NIVEAU3_4_5_6_7_8); Case caseTour1; Case caseTour2; Coordonnees coord1; Coordonnees coord2; //on teste pour le joueur noir //la tour est plus petite : possible coord1 = Coordonnees.depuisCars('b', 'A'); coord2 = Coordonnees.depuisCars('l', 'F'); caseTour1 = plateau[coord1.ligne][coord1.colonne]; caseTour2 = plateau[coord2.ligne][coord2.colonne]; assertTrue(JoueurTowa.hauteurPlusPetite(caseTour1, caseTour2)); //la tour est plus grande : impossible coord1 = Coordonnees.depuisCars('l', 'E'); coord2 = Coordonnees.depuisCars('m', 'E'); caseTour1 = plateau[coord1.ligne][coord1.colonne]; caseTour2 = plateau[coord2.ligne][coord2.colonne]; assertFalse(JoueurTowa.hauteurPlusPetite(caseTour1, caseTour2)); //on teste pour le joueur blanc //la tour est plus petite : possible coord1 = Coordonnees.depuisCars('m', 'E'); coord2 = Coordonnees.depuisCars('l', 'E'); caseTour1 = plateau[coord1.ligne][coord1.colonne]; caseTour2 = plateau[coord2.ligne][coord2.colonne]; assertTrue(JoueurTowa.hauteurPlusPetite(caseTour1, caseTour2)); //la tour est plus grande : impossible coord1 = Coordonnees.depuisCars('l', 'F'); coord2 = Coordonnees.depuisCars('b', 'A'); caseTour1 = plateau[coord1.ligne][coord1.colonne]; caseTour2 = plateau[coord2.ligne][coord2.colonne]; assertFalse(JoueurTowa.hauteurPlusPetite(caseTour1, caseTour2)); } void testExisteTourAdverseAdjacente() { Case[][] plateau = Utils.plateauDepuisTexte(PLATEAU_NIVEAU3_4_5_6_7_8); Coordonnees coord; boolean existeTourAdverseAdjacente, joueurNoir; //testes pour un joueur noir joueurNoir = true; //on teste pour une case où il y a au moins une tour adverse adjacente coord = Coordonnees.depuisCars('o', 'H'); existeTourAdverseAdjacente = true; assertEquals( JoueurTowa.existeTourAdverseAdjacente(plateau, coord, joueurNoir), existeTourAdverseAdjacente); //on teste pour une case où il n'y a que des tours alliées adjacentes coord = Coordonnees.depuisCars('i', 'B'); existeTourAdverseAdjacente = false; assertEquals( JoueurTowa.existeTourAdverseAdjacente(plateau, coord, joueurNoir), existeTourAdverseAdjacente); //on teste pour une case où il n'y a que des cases vides adjacentes coord = Coordonnees.depuisCars('j', 'H'); existeTourAdverseAdjacente = false; assertEquals( JoueurTowa.existeTourAdverseAdjacente(plateau, coord, joueurNoir), existeTourAdverseAdjacente); //testes pour un joueur blanc joueurNoir = false; //on teste pour une case où il y a au moins une tour adverse adjacente coord = Coordonnees.depuisCars('i', 'L'); existeTourAdverseAdjacente = true; assertEquals( JoueurTowa.existeTourAdverseAdjacente(plateau, coord, joueurNoir), existeTourAdverseAdjacente); //on teste pour une case où il n'y a que des tours alliées adjacentes coord = Coordonnees.depuisCars('b', 'H'); existeTourAdverseAdjacente = false; assertEquals( JoueurTowa.existeTourAdverseAdjacente(plateau, coord, joueurNoir), existeTourAdverseAdjacente); //on teste pour une case où il n'y a que des cases vides adjacentes coord = Coordonnees.depuisCars('d', 'I'); existeTourAdverseAdjacente = false; assertEquals( JoueurTowa.existeTourAdverseAdjacente(plateau, coord, joueurNoir), existeTourAdverseAdjacente); } @Test public void testsMethodesNbPions() { testCalculerNbPionsSiPose(); testCalculerNbPionsSiActiver(); testCalculerNbPionsSiFusion(); testCalculerPionsSiAjoutHauteur(); testNbPions(); } void testCalculerNbPionsSiPose() { Case[][] plateau = Utils.plateauDepuisTexte(PLATEAU_NIVEAU3_4_5_6_7_8); Coordonnees coord; int nbPions[] = new int[2]; nbPions[0] = JoueurTowa.nbPions(plateau, true); nbPions[1] = JoueurTowa.nbPions(plateau, false); //on teste pour le joueur noir //ajoute un pion sur une case de même couleur coord = Coordonnees.depuisCars('m', 'J'); nbPions[0]++; Assert.assertArrayEquals( JoueurTowa.calculerNbPionsSiPose(plateau, coord, nbPions[0] - 1, nbPions[1], true), nbPions); //ajoute un pion sur une case vide avec tour adverse adjacente coord = Coordonnees.depuisCars('i', 'L'); nbPions[0] += 2; Assert.assertArrayEquals( JoueurTowa.calculerNbPionsSiPose(plateau, coord, nbPions[0] - 2, nbPions[1], true), nbPions); //on teste pour une pose du joueur blanc //ajoute un pion sur une case de même couleur coord = Coordonnees.depuisCars('m', 'F'); nbPions[1]++; Assert.assertArrayEquals( JoueurTowa.calculerNbPionsSiPose(plateau, coord, nbPions[0], nbPions[1] - 1, false), nbPions); //ajoute un pion sur une case vide avec tour adverse adjacente coord = Coordonnees.depuisCars('i', 'L'); nbPions[1] += 2; Assert.assertArrayEquals( JoueurTowa.calculerNbPionsSiPose(plateau, coord, nbPions[0], nbPions[1] - 2, false), nbPions); } void testCalculerNbPionsSiActiver() { Case[][] plateau = Utils.plateauDepuisTexte(PLATEAU_NIVEAU3_4_5_6_7_8); Coordonnees coordActiver; int nbTourAdverseASuppr; int nbPions[] = new int[2]; nbPions[0] = JoueurTowa.nbPions(plateau, true); nbPions[1] = JoueurTowa.nbPions(plateau, false); //on teste pour un joueur noir //Il y a des tours adjacentes/lignes/colonnes blanches moins hautes coordActiver = Coordonnees.depuisCars('c', 'K'); nbTourAdverseASuppr = 4; nbPions[1] -= nbTourAdverseASuppr; Assert.assertArrayEquals( nbPions, JoueurTowa.calculerNbPionsSiActiver(plateau, coordActiver, nbPions[0], nbPions[1]+nbTourAdverseASuppr, true)); //Il n'y a aucune tour adjacente blanche moins haute coordActiver = Coordonnees.depuisCars('o', 'H'); nbTourAdverseASuppr = 0; nbPions[1] -= nbTourAdverseASuppr; Assert.assertArrayEquals( nbPions, JoueurTowa.calculerNbPionsSiActiver(plateau, coordActiver, nbPions[0], nbPions[1]+nbTourAdverseASuppr, true)); //on teste pour un joueur blanc //Il y a des tours adjacentes noires moins hautes coordActiver = Coordonnees.depuisCars('m', 'F'); nbTourAdverseASuppr = 3; nbPions[0] -= nbTourAdverseASuppr; Assert.assertArrayEquals( nbPions, JoueurTowa.calculerNbPionsSiActiver(plateau, coordActiver, nbPions[0]+nbTourAdverseASuppr, nbPions[1], false)); //Il n'y a aucune tour adjacente noire moins haute coordActiver = Coordonnees.depuisCars('p', 'G'); nbTourAdverseASuppr = 0; nbPions[0] -= nbTourAdverseASuppr; Assert.assertArrayEquals( nbPions, JoueurTowa.calculerNbPionsSiActiver(plateau, coordActiver, nbPions[0]+nbTourAdverseASuppr, nbPions[1], false)); } void testCalculerNbPionsSiFusion() { Case[][] plateau = Utils.plateauDepuisTexte(PLATEAU_NIVEAU3_4_5_6_7_8); Coordonnees coordFusion; int nbTourAdverseASuppr; int nbPions[] = new int[2]; nbPions[0] = JoueurTowa.nbPions(plateau, true); nbPions[1] = JoueurTowa.nbPions(plateau, false); boolean joueurNoir; //on teste pour un joueur noir joueurNoir = true; //Il y a des tours adjacentes/lignes/colonnes alliées, et le tout n'excède pas 4 coordFusion = Coordonnees.depuisCars('g', 'J'); nbTourAdverseASuppr = 0; nbPions[0] -= nbTourAdverseASuppr; Assert.assertArrayEquals( nbPions, JoueurTowa.calculerNbPionsSiFusion(plateau, coordFusion, nbPions[0]-nbTourAdverseASuppr, nbPions[1], joueurNoir)); //Il n'y aucune tour alliée coordFusion = Coordonnees.depuisCars('c', 'K'); nbTourAdverseASuppr = 0; nbPions[0] -= nbTourAdverseASuppr; Assert.assertArrayEquals( nbPions, JoueurTowa.calculerNbPionsSiFusion(plateau, coordFusion, nbPions[0]-nbTourAdverseASuppr, nbPions[1], joueurNoir)); //La tour de fusion est égale à 4 de hauteur coordFusion = Coordonnees.depuisCars('i', 'B'); nbTourAdverseASuppr = 2; nbPions[0] -= nbTourAdverseASuppr; Assert.assertArrayEquals( nbPions, JoueurTowa.calculerNbPionsSiFusion(plateau, coordFusion, nbPions[0]+nbTourAdverseASuppr, nbPions[1], joueurNoir)); //on teste pour un joueur blanche joueurNoir = false; //Il y a des tours adjacentes/lignes/colonnes alliées, et le tout n'excède pas 4 coordFusion = Coordonnees.depuisCars('a', 'G'); nbTourAdverseASuppr = 0; nbPions[1] -= nbTourAdverseASuppr; Assert.assertArrayEquals( nbPions, JoueurTowa.calculerNbPionsSiFusion(plateau, coordFusion, nbPions[0], nbPions[1]+nbTourAdverseASuppr, joueurNoir)); //Il n'y aucune tour alliée coordFusion = Coordonnees.depuisCars('d', 'I'); nbTourAdverseASuppr = 0; nbPions[1] -= nbTourAdverseASuppr; Assert.assertArrayEquals( nbPions, JoueurTowa.calculerNbPionsSiFusion(plateau, coordFusion, nbPions[0], nbPions[1]+nbTourAdverseASuppr, joueurNoir)); //La tour de fusion est égale à 4 de hauteur coordFusion = Coordonnees.depuisCars('l', 'F'); nbTourAdverseASuppr = 7; nbPions[1] -= nbTourAdverseASuppr; Assert.assertArrayEquals( nbPions, JoueurTowa.calculerNbPionsSiFusion(plateau, coordFusion, nbPions[0], nbPions[1]+nbTourAdverseASuppr, joueurNoir)); } void testCalculerPionsSiAjoutHauteur() { Case[][] plateau = Utils.plateauDepuisTexte(PLATEAU_NIVEAU3_4_5_6_7_8); Coordonnees coordAjout; int hauteurAAjouter; int nbPionsAjoutes; //Test pour un ajout de 1 pions sur une hauteur strictement inférieur à 4 coordAjout = Coordonnees.depuisCars('f', 'F'); hauteurAAjouter = 1; nbPionsAjoutes = 1; assertEquals(nbPionsAjoutes, JoueurTowa.calculerPionsSiAjoutHauteur(plateau, coordAjout, hauteurAAjouter)); //Test pour un ajout de pions sur une hauteur égale 4 coordAjout = Coordonnees.depuisCars('c', 'K'); hauteurAAjouter = 2; nbPionsAjoutes = 0; assertEquals(nbPionsAjoutes, JoueurTowa.calculerPionsSiAjoutHauteur(plateau, coordAjout, hauteurAAjouter)); //Test pour un ajout de pions supérieur à la hauteur d'une tour de hauteur strictement inférieur à 4 coordAjout = Coordonnees.depuisCars('n', 'G'); hauteurAAjouter = 3; nbPionsAjoutes = 2; assertEquals(nbPionsAjoutes, JoueurTowa.calculerPionsSiAjoutHauteur(plateau, coordAjout, hauteurAAjouter)); } void testNbPions() { // plateau1 : 0 noir, 0 blanc Case[][] plateau1 = Utils.plateauDepuisTexte(PLATEAU_NIVEAU1); assertEquals(0, JoueurTowa.nbPions(plateau1, true)); assertEquals(0, JoueurTowa.nbPions(plateau1, false)); // plateau2 : 27 noirs, 20 blancs Case[][] plateau2 = Utils.plateauDepuisTexte(PLATEAU_NIVEAU2); assertEquals(27, JoueurTowa.nbPions(plateau2, true)); assertEquals(20, JoueurTowa.nbPions(plateau2, false)); } @Test public void testChaineAction() { testChaineActionPose(); testChaineActionActiver(); testChaineActionFusion(); testVerifierNomAction(); } void testVerifierNomAction() { assertTrue(JoueurTowa.verifierNomAction('P')); assertTrue(JoueurTowa.verifierNomAction('A')); assertTrue(JoueurTowa.verifierNomAction('F')); assertFalse(JoueurTowa.verifierNomAction('3')); } void testChaineActionPose() { assertEquals("PfK,3,8", JoueurTowa.chaineActionPose(Coordonnees.depuisCars('f', 'K'), 3, 8)); assertEquals("PaA,0,0", JoueurTowa.chaineActionPose(Coordonnees.depuisCars('a', 'A'), 0, 0)); assertEquals("PpP,10,10", JoueurTowa.chaineActionPose(Coordonnees.depuisCars('p', 'P'), 10, 10)); assertFalse("PdC,14,4".equals(JoueurTowa.chaineActionPose(Coordonnees.depuisCars('p', 'P'), -6, 4))); assertFalse("PdC,14,4".equals(JoueurTowa.chaineActionPose(Coordonnees.depuisCars('e', 'P'), 14, 4))); } void testChaineActionActiver() { assertEquals("AjP,11,5", JoueurTowa.chaineActionActiver(Coordonnees.depuisCars('j', 'P'), 11, 5)); assertEquals("AaA,1,7", JoueurTowa.chaineActionActiver(Coordonnees.depuisCars('a', 'A'), 1, 7)); assertEquals("ApP,10,10", JoueurTowa.chaineActionActiver(Coordonnees.depuisCars('p', 'P'), 10, 10)); assertFalse("AdC,14,4".equals(JoueurTowa.chaineActionActiver(Coordonnees.depuisCars('p', 'P'), -6, 4))); assertFalse("PdC,14,4".equals(JoueurTowa.chaineActionActiver(Coordonnees.depuisCars('n', 'P'), 14, 4))); } void testChaineActionFusion() { assertEquals("FjP,11,5", JoueurTowa.chaineActionFusion(Coordonnees.depuisCars('j', 'P'), 11, 5)); assertEquals("FaA,1,7", JoueurTowa.chaineActionFusion(Coordonnees.depuisCars('a', 'A'), 1, 7)); assertEquals("FpP,10,10", JoueurTowa.chaineActionFusion(Coordonnees.depuisCars('p', 'P'), 10, 10)); assertFalse("FdC,14,4".equals(JoueurTowa.chaineActionFusion(Coordonnees.depuisCars('p', 'P'), -6, 4))); assertFalse("FdC,14,4".equals(JoueurTowa.chaineActionFusion(Coordonnees.depuisCars('n', 'P'), 14, 4))); } /** * Un plateau de base, sous forme de chaîne. Pour construire une telle * chaîne depuis votre sortie.log, déclarez simplement : final String * MON_PLATEAU = ""; puis copiez le plateau depuis votre sortie.log, et * collez-le entre les guillemets. Puis Alt+Shift+f pour mettre en forme. */ static final String PLATEAU_NIVEAU1 = " A B C D E F G H I J K L M N O P \n" + " +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+\n" + "a| | | | | | | | | | | | | | | | |\n" + " +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+\n" + "b| | | | | | | | | | | | | | | | |\n" + " +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+\n" + "c| | | | | | | | | | | | | | | | |\n" + " +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+\n" + "d| | | | | | | | | | | | | | | | |\n" + " +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+\n" + "e| | | | | | | | | | | | | | | | |\n" + " +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+\n" + "f| | | | | | | | | | | | | | | | |\n" + " +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+\n" + "g| | | | | | | | | | | | | | | | |\n" + " +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+\n" + "h| | | | | | | | | | | | | | | | |\n" + " +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+\n" + "i| | | | | | | | | | | | | | | | |\n" + " +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+\n" + "j| | | | | | | | | | | | | | | | |\n" + " +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+\n" + "k| | | | | | | | | | | | | | | | |\n" + " +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+\n" + "l| | | | | | | | | | | | | | | | |\n" + " +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+\n" + "m| | | | | | | | | | | | | | | | |\n" + " +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+\n" + "n| | | | | | | | | | | | | | | | |\n" + " +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+\n" + "o| | | | | | | | | | | | | | | | |\n" + " +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+\n" + "p| | | | | | | | | | | | | | | | |\n" + " +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+"; static final String PLATEAU_NIVEAU2 = " A B C D E F G H I J K L M N O P \n" + " +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+\n" + "a| | | | | | |B1 | | | | | | | | | |\n" + " +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+\n" + "b|N1 | | | | | | |B1 | | | |B1 | | | | |\n" + " +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+\n" + "c| | |B1 | |B1 | | | | | |N5 |B1 | | | | |\n" + " +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+\n" + "d| | | | | | | | |B1 | | | | | | | |\n" + " +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+\n" + "e|B1 | | | | | | | | | | | | | | | |\n" + " +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+\n" + "f| | | | | | | | | | | | | | | | |\n" + " +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+\n" + "g| | |B1 | | | | | | |N1 | | | | | | |\n" + " +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+\n" + "h| | | | | | | | | | |N1 | | | | | |\n" + " +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+\n" + "i| |N1 |N1 | | | | | | | | | |N1 | | | |\n" + " +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+\n" + "j| | | | | | | |N1 | | | |B1 | | | | |\n" + " +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+\n" + "k| | | | |N1 | | | | |N2 | | | | |B1 | |\n" + " +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+\n" + "l| | | | |N3 |B4 |B1 | | | | | | | | | |\n" + " +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+\n" + "m| | | | |B1 |B2 |N1 | | |N1 | | | | | | |\n" + " +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+\n" + "n| | | | |N1 |N1 |N2 | | |N1 | | | | | | |\n" + " +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+\n" + "o| |N1 | | | | | |N1 | | | | | | | | |\n" + " +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+\n" + "p| | | | | | |B1 | | | | | | | | | |\n" + " +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+\n"; static final String PLATEAU_NIVEAU3_4_5_6_7_8 = " A B C D E F G H I J K L M N O P \n" + " +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+\n" + "a| | | | | | |B1 | | | | | | | | |N1 |\n" + " +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+\n" + "b|N1 | | | | | | |B1 | | | |B1 | | | | |\n" + " +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+\n" + "c| | |B1 | |B1 | | | | | |N4 |B1 | | | | |\n" + " +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+\n" + "d| | | | | | | | |B1 | | | | | | | |\n" + " +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+\n" + "e|B1 | | | | | | | | | |B1 | | | | | |\n" + " +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+\n" + "f| | | | | |B3 | | | | | | | | | | |\n" + " +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+\n" + "g| | |B1 | | | | | | |N1 | | | | | | |\n" + " +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+\n" + "h| | | | | | | | | | |N1 | | | | | |\n" + " +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+\n" + "i| |N4 |N1 | | | | | | | | | | |N1 | | |\n" + " +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+\n" + "j| | | | | | | |N1 | | | |B1 | | | | |\n" + " +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+\n" + "k| | | | |N1 | | | | |N2 | | | | |B1 | |\n" + " +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+\n" + "l| | | | |N3 |B4 |B1 | | | | | | | | | |\n" + " +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+\n" + "m| | | | |B1 |B2 |N1 | | |N1 | | | | | | |\n" + " +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+\n" + "n| | | | |N1 |N1 |N2 | | |N1 | | | | | | |\n" + " +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+\n" + "o| | |B2 | | | | |N1 | | | | | | | | |\n" + " +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+\n" + "p| |N1 | | | | |B1 | | | | | | | | | |\n" + " +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+\n"; }
true
ee89ac092199225ae65d67306fef98655b2a22d1
Java
l424533553/SamrtWeight
/app/src/main/java/com/luofx/entity/Errorinfo.java
UTF-8
736
2.0625
2
[]
no_license
package com.luofx.entity; /** * 作者:罗发新 * 时间:2018/12/6 0006 9:51 * 邮件:424533553@qq.com * 说明: */ public class Errorinfo { String classpath = ""; String errormessage = ""; String errortime = " "; public String getClasspath() { return classpath; } public void setClasspath(String classpath) { this.classpath = classpath; } public String getErrormessage() { return errormessage; } public void setErrormessage(String errormessage) { this.errormessage = errormessage; } public String getErrortime() { return errortime; } public void setErrortime(String errortime) { this.errortime = errortime; } }
true
8e5c262ce49e7dc1bffa7b01b9b5dc8aa56cddbd
Java
wizardcode-bot/Proyecto-LearnTraveling
/src/LearnTraveling/main.java
UTF-8
3,225
3.390625
3
[]
no_license
/* learn traveling. -se crea una clase para estudiantes y una clase para docentes. -->DONE -se crea menu para ingresar como docente o estudiante. -->DONE -los docentes se crean una cuenta, ingresan sus datos y se guardan en un archivo si crea el curso. -->DONE -los estudiantes se crean una cuenta por cada uno y se guarda en un archivo diferente --> DONE y escojen uno de los cursos disponibles, en una opcion de cursos disponibles. --> DONE -cuando un estudiante se quiere matricular a un curso pueda ver quienes ya estan o si no hay ninguno. -->DONE -a el docente se le pone un maximo de estudiantes por curso y se muestra si ya se completo o cuantos hay (estado) --> DONE -a el estudiante se le muestra si esta cursando o no algun curso (estado) --> DONE -crear una clase que herede a docente y a estudiante, se crea un archivo en el que se agreguen los datos del docente y los estudiantes que se anoten al curso. --> DONE ->el (DOCENTE) ingresa sus datos y al final se le dice con cuales requisitos cumplio y con cuales no. */ package LearnTraveling; import java.awt.Desktop; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import javax.swing.JOptionPane; public class main { public static void main(String[] args) throws IOException { Estudiante student = new Estudiante(); Docente teacher = new Docente(); int op; do{ op = Integer.parseInt(JOptionPane.showInputDialog("Hi there! Welcome to Learn-Traveling" +"\n MAIN MENU\n\n1. Access as a Teacher\n2. Access as a Student" +"\n3. About\n4. Why traveling?\n0. Exit")); switch(op){ case 1: teacher.menu(); break; case 2: student.menu(); break; case 3: JOptionPane.showMessageDialog(null, "Learn-Traveling is an educational company intended for people"+ " who wants to learn \na language in another country. Where is taught by a professional native teacher."+ "\nThese teachers have been previously registered in the platform with their respective personal information"+ "\nand the student will decide which one to have classes with, depending on the country they've chosen."+ "\nLearn-Traveling will provide basic services, being these hotel accommodation, food and transport"+ "\nduring the stipulated time."+ "\nThe student will graduate with an international certification taking the IELTS exam at the end of the course." + "\nEach course has a maximum quota of five students."); break; case 4: enlace("https://www.trafalgar.com/real-word/learning-through-travel/"); break; } }while(op!=0); } public static void enlace (String enlaceAAceder) throws IOException{ Desktop enlace=Desktop.getDesktop(); try { enlace.browse(new URI(enlaceAAceder)); } catch (URISyntaxException e) { e.getMessage(); } } }
true
e16bf52cb8a0c271e9588c836b3a0f9fb87e2d9e
Java
Tian-Zhen-Yin/Homomorphic_Encryption
/Java_PHE/src/main/java/security/DGK/DGKPublicKey.java
UTF-8
2,917
2.8125
3
[ "MIT" ]
permissive
package security.DGK; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.math.BigInteger; import java.security.PublicKey; import java.util.HashMap; import security.misc.CipherConstants; public final class DGKPublicKey implements Serializable, DGK_Key, PublicKey, Runnable, CipherConstants { /** * The type fingerprint that is set to indicate serialization compatibility with a previous version of the type. */ private static final long serialVersionUID = -1613333167285302035L; protected final BigInteger n; protected final BigInteger g; protected final BigInteger h; protected final long u; protected final BigInteger bigU; protected final HashMap <Long, BigInteger> gLUT = new HashMap<Long, BigInteger>(); protected final HashMap <Long, BigInteger> hLUT = new HashMap<Long, BigInteger>(); // Key Parameters protected final int l; protected final int t; protected final int k; //DGK Constructor with ALL parameters public DGKPublicKey(BigInteger n, BigInteger g, BigInteger h, BigInteger u, int l, int t, int k) { this.n = n; this.g = g; this.h = h; this.u = u.longValue(); this.bigU = u; this.l = l; this.t = t; this.k = k; } private void readObject(ObjectInputStream aInputStream) throws ClassNotFoundException,IOException { aInputStream.defaultReadObject(); } private void writeObject(ObjectOutputStream aOutputStream) throws IOException { aOutputStream.defaultWriteObject(); } public BigInteger ZERO() { return DGKOperations.encrypt(0, this); } public BigInteger ONE() { return DGKOperations.encrypt(1, this); } /** * @return DGK */ public String getAlgorithm() { return "DGK"; } /** * @return String representation of DGK Public Key */ public String toString() { String answer = ""; answer += "n: " + n + ", " + '\n'; answer += "g: " + g + ", " + '\n'; answer += "h: " + h + ", " + '\n'; answer += "u: " + bigU + ", " + '\n'; answer += "l: " + l + ", " + '\n'; answer += "t: " + t + ", " + '\n'; answer += "k: " + k + ", " + '\n'; return answer; } public String getFormat() { return "X.509"; } public byte[] getEncoded() { return null; } public void run() { this.generatehLUT(); this.generategLUT(); } private void generatehLUT() { for (long i = 0; i < 2 * t; ++i) { // e = 2^i (mod n) // h^{2^i (mod n)} (mod n) // f(i) = h^{2^i}(mod n) BigInteger e = TWO.pow((int) i).mod(this.n); this.hLUT.put(i, this.h.modPow(e, this.n)); } } private void generategLUT() { for (long i = 0; i < this.u; ++i) { BigInteger out = this.g.modPow(BigInteger.valueOf(i), this.n); this.gLUT.put(i, out); } } public BigInteger getU() { return this.bigU; } public BigInteger getN() { return this.n; } public int getL() { return this.l; } }
true
924e75f4ca30042fd14338e81eaf2002d67552a9
Java
Oaks907/bookspace
/LeetCode/src/S201_300/S239_SlidingWindowMaximum.java
UTF-8
2,682
3.640625
4
[]
no_license
package S201_300; import utils.PrintUtils; import java.util.ArrayDeque; import java.util.Queue; /** * Create by haifei on 13/1/2019 2:58 PM. * <p> * https://leetcode.com/problems/sliding-window-maximum/ * <p> * Sliding Window Maximum * Input: nums = [1,3,-1,-3,5,3,6,7], and k = 3 * Output: [3,3,5,5,6,7] * Explanation: * <p> * Window position Max * --------------- ----- * [1 3 -1] -3 5 3 6 7 3 * 1 [3 -1 -3] 5 3 6 7 3 * 1 3 [-1 -3 5] 3 6 7 5 * 1 3 -1 [-3 5 3] 6 7 5 * 1 3 -1 -3 [5 3 6] 7 6 * 1 3 -1 -3 5 [3 6 7] 7 */ public class S239_SlidingWindowMaximum { /** * 使用双端队列 * * @param nums * @param k * @return */ public int[] maxSlidingWindow(int[] nums, int k) { if (nums == null || nums.length == 0) { return new int[0]; } int[] result = new int[nums.length - k + 1]; //声明双端队列 ArrayDeque<Integer> dequeue = new ArrayDeque<>(); for (int i = 0; i < nums.length; i++) { int item = nums[i]; //处理前 k - 1 个元素 if (i < k - 1) { dequeue.addLast(item); continue; } //由第 k 个元素开始计算 dequeue.addLast(item); //维护双端队列长度不大于 k while (dequeue.size() > k) { dequeue.removeFirst(); } //最后的数是最大数,会使后面的失效 while (dequeue.peekLast() > dequeue.peekFirst() && dequeue.size() != 1) { dequeue.removeFirst(); } int maxItem = Integer.MIN_VALUE; //找出双端队列的最大值 for (int temp : dequeue) { if (temp > maxItem) { maxItem = temp; } } result[i - k + 1] = maxItem; } return result; } public int[] maxSlidingWindow_Array(int[] nums, int k){ if (nums == null || nums.length == 0) { return new int[0]; } int[] result = new int[nums.length - k + 1]; for (int i = 0; i < nums.length - k + 1; i++) { int maxValue = Integer.MIN_VALUE; for (int j = i; j < i + k; j++) { if (nums[j] > maxValue) { maxValue = nums[j]; } } result[i] = maxValue; } return result; } public static void main(String[] args) { int[] arrays = {1, 3, -1, -3, 5, 3, 6, 7}; final S239_SlidingWindowMaximum slidingWindowMaximum = new S239_SlidingWindowMaximum(); int[] ints = slidingWindowMaximum.maxSlidingWindow(arrays, 3); PrintUtils.printArray(ints); ints = slidingWindowMaximum.maxSlidingWindow_Array(arrays, 3); PrintUtils.printArray(ints); } }
true
714bf133066329bd70c00748e9b1ac8407c7d379
Java
srosenberg/datakernel
/eventloop/src/main/java/io/datakernel/async/AssertingCompletionCallback.java
UTF-8
268
2.03125
2
[ "Apache-2.0" ]
permissive
package io.datakernel.async; public abstract class AssertingCompletionCallback extends CompletionCallback { @Override protected final void onException(Exception e) { throw new AssertionError("Fatal error in callback " + this.getClass().getSimpleName(), e); } }
true
245d14e1ececef4eab05dad0fefbab2539b3bbf2
Java
GWphua/tp
/src/main/java/seedu/address/model/task/Task.java
UTF-8
2,631
3.3125
3
[ "MIT" ]
permissive
package seedu.address.model.task; import static java.util.Objects.requireNonNull; import static seedu.address.commons.util.AppUtil.checkArgument; import java.util.Objects; /** * Represents a task in the Ail. * Guarantees: immutable; is valid as declared in {@link #isValidTaskName(String)} */ public class Task { public static final String MESSAGE_CONSTRAINTS = "Task name can take any values, and it should not be blank"; /* * The first character of the task name must not be a whitespace, * otherwise " " (a blank string) becomes a valid input. */ public static final String VALIDATION_REGEX = "[^\\s].*"; private final String taskName; private final boolean isDone; /** * Constructs a {@code Task}. * * @param taskName A valid task name. */ public Task(String taskName) { requireNonNull(taskName); checkArgument(isValidTaskName(taskName), MESSAGE_CONSTRAINTS); this.taskName = taskName; this.isDone = false; } /** * Constructs a {@code Task}. * * @param taskName A valid task name. * @param isDone A boolean value. */ public Task(String taskName, boolean isDone) { requireNonNull(taskName); checkArgument(isValidTaskName(taskName), MESSAGE_CONSTRAINTS); this.taskName = taskName; this.isDone = isDone; } public String getTaskName() { return taskName; } public boolean isDone() { return isDone; } /** * Returns true if a given string is a valid task name. */ public static boolean isValidTaskName(String test) { return test.matches(VALIDATION_REGEX); } /** * Returns true if both tasks are the same as defined * This defines a weaker notion of equality between two tasks. */ /*public boolean isSameTask(Task otherTask) { return this.taskName.equals(otherTask.taskName); }*/ @Override public boolean equals(Object other) { if (this == other) { return true; } if (other == null || getClass() != other.getClass()) { return false; } Task task = (Task) other; boolean result = isDone == task.isDone && taskName.equals(task.taskName); return result; } @Override public int hashCode() { return Objects.hash(taskName, isDone); } private String getStatusIcon() { return (isDone ? "X" : " "); // mark done task with X } @Override public String toString() { return "(" + getStatusIcon() + ")" + taskName; } }
true
20fb5af2bceaeb3af78eaf57626e6be66a2c72e6
Java
avereon/aveon
/source/main/java/com/avereon/geometry/Shape.java
UTF-8
104
1.890625
2
[ "MIT" ]
permissive
package com.avereon.geometry; public abstract class Shape { public abstract Bounds2D getBounds(); }
true
9b4572c3cbc1edddbc6f011b38bf1ab82e32f865
Java
aitonjiaotong/BaMinGongWuCar
/src/cn/com/easytaxi/common/Window.java
UTF-8
45,165
1.554688
2
[]
no_license
package cn.com.easytaxi.common; import java.lang.reflect.Field; import java.util.Calendar; import java.util.List; import org.apache.commons.lang3.StringUtils; import org.json.JSONException; import org.json.JSONObject; import android.app.AlertDialog; import android.app.Dialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.pm.PackageManager.NameNotFoundException; import android.content.res.Resources; import android.net.Uri; import android.view.Display; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup.LayoutParams; import android.view.WindowManager; import android.widget.Button; import android.widget.EditText; import android.widget.ExpandableListView; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.PopupWindow; import android.widget.SeekBar; import android.widget.TextView; import android.widget.Toast; import cn.com.easytaxi.NewNetworkRequest; import cn.com.easytaxi.airport.AirportBookPublishFragement; import cn.com.easytaxi.book.view.Datetime; import cn.com.easytaxi.book.view.scrollwheel.ArrayWheelAdapter; import cn.com.easytaxi.book.view.scrollwheel.WheelView; import cn.com.easytaxi.expandable.Child; import cn.com.easytaxi.expandable.ExpAdapter; import cn.com.easytaxi.expandable.Group; import cn.com.easytaxi.onetaxi.NewMainActivityNew; import cn.com.easytaxi.util.ToastUtil; import com.aiton.yc.client.R; public final class Window { public static <T> void alert(Context context, String title, String content, final Callback<Object> callback) { try { AlertDialog.Builder alert = new AlertDialog.Builder(context); alert.setMessage(content); alert.setTitle(title); alert.setPositiveButton("确定", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { if (callback != null) callback.handle(which); } }); alert.create().show(); } catch (Throwable e) { e.printStackTrace(); } } public static <T> void alert(Context context, String title, String content) { alert(context, title, content, null); } public static <T> void info(Context context, String content) { alert(context, "信息提示", content, null); } public static <T> void info(Context context, String content, Callback<Object> callback) { alert(context, "信息提示", content, callback); } public static <T> void error(Context context, String content) { alert(context, "错误", content, null); } public static <T> void error(Context context, String title, String content) { alert(context, title, content, null); } public static <T> void error(Context context, String title, String content, Callback<Object> callback) { alert(context, title, content, callback); } public static <T> void error(Context context, String content, Callback<Object> callback) { alert(context, "错误", content, callback); } public static <T> void alert(Context context, String content) { alert(context, "警告", content, null); } public static <T> AlertDialog confirm(Context context, String title, String content, final Callback<Object> callback1, final Callback<Object> callback2, String btn1Name, String btn2Name) { try { AlertDialog.Builder alert = new AlertDialog.Builder(context); alert.setCancelable(false); alert.setMessage(content); alert.setTitle(title); alert.setPositiveButton(btn1Name, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { if (callback1 != null) { dialog.dismiss(); callback1.handle(which); } } }); alert.setNegativeButton(btn2Name, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { if (callback2 != null) { callback2.handle(which); dialog.dismiss(); } } }); AlertDialog dialog = alert.create(); dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT); dialog.show(); return dialog; } catch (Throwable e) { e.printStackTrace(); } return null; } public static <T> AlertDialog confirm(boolean force, Context context, String title, String content, final Callback<Object> callback1, final Callback<Object> callback2, String btn1Name, String btn2Name) { try { AlertDialog.Builder alert = new AlertDialog.Builder(context); alert.setCancelable(false); alert.setMessage(content); alert.setTitle(title); alert.setPositiveButton(btn1Name, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { if (callback1 != null) { dialog.dismiss(); callback1.handle(which); } } }); if (!force) alert.setNegativeButton(btn2Name, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { if (callback2 != null) { callback2.handle(which); dialog.dismiss(); } } }); AlertDialog dialog = alert.create(); dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT); dialog.show(); return dialog; } catch (Throwable e) { e.printStackTrace(); } return null; } public static <T> void confirm(Context context, String title, String content, final Callback<Object> callback1, final Callback<Object> callback2) { confirm(context, title, content, callback1, callback2, "确定", "取消"); } public static <T> void confirm(Context context, String title, String content, final Callback<Object> callback1) { confirm(context, title, content, callback1, null); } public static <T> void confirm(Context context, String content, final Callback<Object> callback1) { confirm(context, "请确认", content, callback1, null); } public static <T> void confirmOK(Context context, String content, final Callback<Object> callback1) { AlertDialog.Builder alert = new AlertDialog.Builder(context); alert.setCancelable(false); alert.setMessage(content); alert.setTitle("提示"); alert.setPositiveButton("确认", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { if (callback1 != null) callback1.handle(which); } }); AlertDialog dialog = alert.create(); dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT); dialog.show(); } public static <T> AlertDialog input(Context context, String title, final Callback<Object> callback1, final Callback<Object> callback2, String btn1Name, String btn2Name) { final EditText editText = new EditText(context); editText.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT)); AlertDialog.Builder alert = new AlertDialog.Builder(context); alert.setView(editText); alert.setTitle(title); alert.setPositiveButton(btn1Name, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { if (callback1 != null) callback1.handle(editText.getText().toString()); } }); alert.setNegativeButton(btn2Name, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { if (callback2 != null) callback2.handle(which); } }); AlertDialog dialog = alert.create(); dialog.show(); return dialog; } public static void selectHistory(final Context context, final List<String> rows, final Callback<String> callback) { LinearLayout l = new LinearLayout(context); l.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT)); l.setOrientation(LinearLayout.VERTICAL); AlertDialog.Builder alert = new AlertDialog.Builder(context); alert.setView(l); alert.setTitle("从历史记录中选择 "); final AlertDialog dialog = alert.create(); for (final String row : rows) { Button button = new Button(context); button.setText(row); button.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { if (callback != null) { callback.handle(row); dialog.dismiss(); } } }); l.addView(button, new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT)); } dialog.show(); } // 司机违约提示框 public static AlertDialog breachTipWindow(final Context applicationContext, String title, String msg, final Callback<Object> callBack1, final Callback<Object> callBack2, final Callback<Object> callBack3) { AlertDialog.Builder builder = new AlertDialog.Builder(applicationContext); // builder.setIcon(android.R.drawable.btn_star); builder.setTitle(title); builder.setMessage(msg); builder.setCancelable(false); builder.setNegativeButton("取消", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { // TODO Auto-generated method stub dialog.dismiss(); if (callBack1 != null) { callBack1.handle(null); } } }); // builder.setNeutralButton("重新打车", new // DialogInterface.OnClickListener() { // // public void onClick(DialogInterface dialog, int which) { // // TODO Auto-generated method stub // dialog.dismiss(); // if (callBack2 != null) { // callBack2.handle(null); // } // } // }); builder.setPositiveButton("投诉", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { // TODO Auto-generated method stub dialog.dismiss(); if (callBack3 != null) { callBack3.handle(null); } } }); builder.create(); return builder.show(); } // 结束服务提示框 public static Dialog stopServeWindow(final Context context, String title, final Callback<Object> comfirmCallback, final Callback<Object> cancelCallback) { LayoutInflater factory = LayoutInflater.from(context); Dialog dlg = new Dialog(context, R.style.Customdialog); final View dialogView = factory.inflate(R.layout.onetaxi_stopserve_window_new, null); dlg.setContentView(dialogView); Button pop_good = (Button) dialogView.findViewById(R.id.pop_good); pop_good.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { // TODO Auto-generated method stub } }); Button pop_bad = (Button) dialogView.findViewById(R.id.pop_bad); pop_bad.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub } }); Button pop_cancel = (Button) dialogView.findViewById(R.id.pop_cancel); pop_cancel.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { } }); return dlg; } // about窗口 public static <T> void about(final Context context) { View view = LayoutInflater.from(context).inflate(R.layout.about, null); PackageManager pm = context.getPackageManager(); PackageInfo pi = null; try { pi = pm.getPackageInfo(context.getPackageName(), 0); } catch (NameNotFoundException e) { e.printStackTrace(); return; } String versionName = pi.versionName + " Ver."; TextView tv = (TextView) view.findViewById(R.id.about_version); tv.setText(versionName); view.findViewById(R.id.companysite).setOnClickListener(new View.OnClickListener() { public void onClick(View v) { Uri uri = Uri.parse("http://www.easytaxi.com.cn"); context.startActivity(new Intent(Intent.ACTION_VIEW, uri)); } }); AlertDialog.Builder alert = new AlertDialog.Builder(context); alert.setView(view); alert.setOnCancelListener(new DialogInterface.OnCancelListener() { public void onCancel(DialogInterface dialog) { } }); alert.create().show(); } public static void dateTime(Context context, String time, final Callback<String> callback) { final Datetime datetime = new Datetime(context, time); AlertDialog.Builder builder = new AlertDialog.Builder(context); builder.setTitle("选择时间"); builder.setView(datetime); builder.setNeutralButton("确定", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { if (callback != null) { callback.handle(datetime.getDatetimeStr()); } } }); builder.setNegativeButton("取消", null); builder.create().show(); } private static String getContent(int time) { // TODO Auto-generated method stub StringBuilder content = new StringBuilder("等待倒计时:"); if (time < 60) { content.append(time); content.append("秒"); } else { content.append(time / 60); content.append("分"); content.append(time % 60); content.append("秒"); } return content.toString(); } public static Dialog Tip(Context ctx, String tip) { AlertDialog.Builder builder = new AlertDialog.Builder(ctx); builder.setTitle("信息提示"); builder.setMessage(tip); builder.setCancelable(true); builder.setNegativeButton("知道了", null); Dialog d = builder.create(); d.show(); return d; } public static Dialog tipSystem(Context ctx, String tip) { AlertDialog.Builder builder = new AlertDialog.Builder(ctx); builder.setTitle("信息提示"); builder.setMessage(tip); builder.setCancelable(true); builder.setNegativeButton("知道了", null); Dialog d = builder.create(); d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT); d.show(); return d; } public static void callTaxi(final Context ctx, String phone) throws Exception { if (phone == null || phone.equals("")) { throw new Exception("电话号码未知"); } final String[] phoneList = phone.split(","); if (phoneList.length == 1) { Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + phoneList[0])); ctx.startActivity(intent); return; } AlertDialog.Builder builder = new AlertDialog.Builder(ctx); DialogInterface.OnClickListener clickLis = new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); String number = phoneList[which]; Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + number)); ctx.startActivity(intent); } }; builder.setTitle("选择电话"); builder.setSingleChoiceItems(phoneList, -1, clickLis); builder.setCancelable(true); final Dialog d = builder.create(); d.show(); } /** * 新的选择用车时间的弹出框 * * @param context * @param callback * @param timeLine * 从服务器获取的时间上下线 * @param defaultMinUseCarTime * 本地默认的最小用车时间 * @param defaultMaxUseCarTime * 本地默认的最大用车时间 */ public static void selectDate(final Context context, final Callback<String[]> callback, final NewNetworkRequest.TimeLine timeLine, final int defaultMinUseCarTime, final int defaultMaxUseCarTime) { View view = LayoutInflater.from(context).inflate(R.layout.wheel_scroll_layout, null); final Dialog dialog = new Dialog(context, R.style.Customdialog); dialog.setContentView(view); Button btnok = (Button) view.findViewById(R.id.button_ok); Button btnCancel = (Button) view.findViewById(R.id.button_cancel); final WheelView wheelDay = (WheelView) view.findViewById(R.id.am_pm); final WheelView wheelHour = (WheelView) view.findViewById(R.id.clockadd_hour); final WheelView wheelMinutes = (WheelView) view.findViewById(R.id.clockadd_minutes); final Resources res = context.getResources(); final String[] days = AirportBookPublishFragement.getTimeValues(0, 0, -1, 0, timeLine, defaultMinUseCarTime, defaultMaxUseCarTime); final String[] hours = AirportBookPublishFragement.getTimeValues(1, 0, -1, 0, timeLine, defaultMinUseCarTime, defaultMaxUseCarTime); final String[] mins = AirportBookPublishFragement.getTimeValues(2, 0, -1, 0, timeLine, defaultMinUseCarTime, defaultMaxUseCarTime); wheelMinutes.setAdapter(new ArrayWheelAdapter<String>(mins)); wheelMinutes.setVisibleItems(5); wheelMinutes.setCyclic(false); wheelMinutes.setCurrentItem(0); wheelHour.setAdapter(new ArrayWheelAdapter<String>(hours)); wheelHour.setVisibleItems(5); wheelHour.setCyclic(false); wheelHour.setCurrentItem(0); wheelDay.setAdapter(new ArrayWheelAdapter<String>(days)); wheelDay.setVisibleItems(5); wheelDay.setCyclic(false); wheelDay.setCurrentItem(0); wheelDay.addChangingListener(new WheelView.OnWheelChangedListener() { @Override public void onChanged(WheelView wheel, int oldValue, int newValue) { try { wheelHour.setAdapter(new ArrayWheelAdapter<String>(AirportBookPublishFragement.getTimeValues(1, 0, -1, newValue, timeLine, defaultMinUseCarTime, defaultMaxUseCarTime))); wheelHour.setCurrentItem(0); wheelMinutes.setAdapter(new ArrayWheelAdapter<String>(AirportBookPublishFragement.getTimeValues(2, 0, -1, newValue, timeLine, defaultMinUseCarTime, defaultMaxUseCarTime))); wheelMinutes.setCurrentItem(0); } catch (Exception e) { e.printStackTrace(); wheelMinutes.setAdapter(new ArrayWheelAdapter<String>(AirportBookPublishFragement.getTimeValues(2, 0, -1, newValue, timeLine, defaultMinUseCarTime, defaultMaxUseCarTime))); wheelMinutes.setCurrentItem(0); } } }); wheelHour.addChangingListener(new WheelView.OnWheelChangedListener() { @Override public void onChanged(WheelView wheel, int oldValue, int newValue) { int day = wheelDay.getCurrentItem(); int hourIndex = wheel.getCurrentItem(); int hour = Integer.parseInt(wheel.getAdapter().getItem(newValue)); wheelMinutes.setAdapter(new ArrayWheelAdapter<String>(AirportBookPublishFragement.getTimeValues(2, hourIndex, hour, day, timeLine, defaultMinUseCarTime, defaultMaxUseCarTime))); wheelMinutes.setCurrentItem(0); } }); wheelMinutes.addChangingListener(new WheelView.OnWheelChangedListener() { @Override public void onChanged(WheelView wheel, int oldValue, int newValue) { } }); btnok.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { String dayChoosedIndex = "" + wheelDay.getCurrentItem(); String day = wheelDay.getAdapter().getItem(wheelDay.getCurrentItem()); String hour = wheelHour.getAdapter().getItem(wheelHour.getCurrentItem()); String min = wheelMinutes.getAdapter().getItem(wheelMinutes.getCurrentItem()); boolean isChooseCorrect = checkChooseTime(); if (isChooseCorrect) { if (day == null || hour == null || min == null) { ToastUtil.show(context, res.getString(R.string.tip_book_time)); } else { if (callback != null) { callback.handle(new String[] { dayChoosedIndex, day, hour, min }); } dialog.dismiss(); } } else { ToastUtil.show(context, res.getString(R.string.tip_book_time)); } } /** * 检查选择时间是否比当前时间大 */ private boolean checkChooseTime() { String day = wheelDay.getAdapter().getItem(wheelDay.getCurrentItem()); int chooseHour = Integer.parseInt(wheelHour.getAdapter().getItem(wheelHour.getCurrentItem())); int chooseMin = Integer.parseInt(wheelMinutes.getAdapter().getItem(wheelMinutes.getCurrentItem())); Calendar now = Calendar.getInstance(); int hourNow = now.get(Calendar.HOUR_OF_DAY); int minNow = now.get(Calendar.MINUTE); if (day.equals("今天")) { if (chooseHour > hourNow) { return true; } else if (chooseHour == hourNow && chooseMin > minNow) { return true; } else { return false; } } else { return true; } } }); btnCancel.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { dialog.dismiss(); } }); dialog.show(); } /** * 旧的选择用车时间的弹出框 * * @param context * @param callback */ public static void selectDate(final Context context, final Callback<String[]> callback) { View view = LayoutInflater.from(context).inflate(R.layout.wheel_scroll_layout, null); final Dialog dialog = new Dialog(context, R.style.Customdialog); dialog.setContentView(view); Button btnok = (Button) view.findViewById(R.id.button_ok); Button btnCancel = (Button) view.findViewById(R.id.button_cancel); final WheelView wheelDay = (WheelView) view.findViewById(R.id.am_pm); final WheelView wheelHour = (WheelView) view.findViewById(R.id.clockadd_hour); final WheelView wheelMinutes = (WheelView) view.findViewById(R.id.clockadd_minutes); final Resources res = context.getResources(); final String[] days = AirportBookPublishFragement.getTimeValues(0, -1, 0); final String[] hours = AirportBookPublishFragement.getTimeValues(1, -1, 0); final String[] mins = AirportBookPublishFragement.getTimeValues(2, -1, 0); wheelMinutes.setAdapter(new ArrayWheelAdapter<String>(mins)); wheelMinutes.setVisibleItems(5); wheelMinutes.setCyclic(false); wheelMinutes.setCurrentItem(0); wheelHour.setAdapter(new ArrayWheelAdapter<String>(hours)); wheelHour.setVisibleItems(5); wheelHour.setCyclic(false); wheelHour.setCurrentItem(0); wheelDay.setAdapter(new ArrayWheelAdapter<String>(days)); wheelDay.setVisibleItems(5); wheelDay.setCyclic(false); wheelDay.setCurrentItem(0); wheelDay.addChangingListener(new WheelView.OnWheelChangedListener() { @Override public void onChanged(WheelView wheel, int oldValue, int newValue) { try { wheelHour.setAdapter(new ArrayWheelAdapter<String>(AirportBookPublishFragement.getTimeValues(1, -1, newValue))); wheelHour.setCurrentItem(0); wheelMinutes.setAdapter(new ArrayWheelAdapter<String>(AirportBookPublishFragement.getTimeValues(2, -1, newValue))); wheelMinutes.setCurrentItem(0); } catch (Exception e) { e.printStackTrace(); wheelMinutes.setAdapter(new ArrayWheelAdapter<String>(AirportBookPublishFragement.getTimeValues(2, -1, newValue))); wheelMinutes.setCurrentItem(0); } } }); wheelHour.addChangingListener(new WheelView.OnWheelChangedListener() { @Override public void onChanged(WheelView wheel, int oldValue, int newValue) { int day = wheelDay.getCurrentItem(); int hour = Integer.parseInt(wheel.getAdapter().getItem(newValue)); wheelMinutes.setAdapter(new ArrayWheelAdapter<String>(AirportBookPublishFragement.getTimeValues(2, hour, day))); wheelMinutes.setCurrentItem(0); } }); wheelMinutes.addChangingListener(new WheelView.OnWheelChangedListener() { @Override public void onChanged(WheelView wheel, int oldValue, int newValue) { } }); btnok.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { String day = wheelDay.getAdapter().getItem(wheelDay.getCurrentItem()); String hour = wheelHour.getAdapter().getItem(wheelHour.getCurrentItem()); String min = wheelMinutes.getAdapter().getItem(wheelMinutes.getCurrentItem()); boolean isChooseCorrect = checkChooseTime(); if (isChooseCorrect) { if (day == null || hour == null || min == null) { ToastUtil.show(context, res.getString(R.string.tip_book_time)); } else { if (callback != null) { callback.handle(new String[] { day, hour, min }); } dialog.dismiss(); } } else { ToastUtil.show(context, res.getString(R.string.tip_book_time)); } } /** * 检查选择时间是否比当前时间大 */ private boolean checkChooseTime() { String day = wheelDay.getAdapter().getItem(wheelDay.getCurrentItem()); int chooseHour = Integer.parseInt(wheelHour.getAdapter().getItem(wheelHour.getCurrentItem())); int chooseMin = Integer.parseInt(wheelMinutes.getAdapter().getItem(wheelMinutes.getCurrentItem())); Calendar now = Calendar.getInstance(); int hourNow = now.get(Calendar.HOUR_OF_DAY); int minNow = now.get(Calendar.MINUTE); if (day.equals("今天")) { if (chooseHour > hourNow) { return true; } else if (chooseHour == hourNow && chooseMin > minNow) { return true; } else { return false; } } else { return true; } } }); btnCancel.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { dialog.dismiss(); } }); dialog.show(); } public static void stopServiceWindow(final Context context, final int type, final Callback<JSONObject> callback) { final int commentGood = 150;// 非常满意 final int commentNomal = 100;// 一般满意 final int commentBad = 10;// 差评 final int commentCancelBook = 500; // 结束服务 LayoutInflater factory = LayoutInflater.from(context); final Dialog dlg = new Dialog(context, R.style.Customdialog); final View dialogView = factory.inflate(R.layout.stopserve_window, null); dlg.setContentView(dialogView); final TextView tvTitle = (TextView) dialogView.findViewById(R.id.stopservice_title); final ExpandableListView epdList = (ExpandableListView) dialogView.findViewById(R.id.stopwindow_expandableListView); final EditText tvComment = (EditText) dialogView.findViewById(R.id.stopservice_comment); Button btnComfirm = (Button) dialogView.findViewById(R.id.stopservice_comfirm); Button btnBack = (Button) dialogView.findViewById(R.id.stopservice_cancel); if (type == 3) { tvTitle.setText("评价"); } else { tvTitle.setText("结束"); } final ExpAdapter exAdapter = new ExpAdapter(context, NewMainActivityNew.getGroupData(type)); epdList.setAdapter(exAdapter); epdList.setGroupIndicator(null); epdList.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() { @Override public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id) { // TODO Auto-generated method stub epdList.expandGroup(groupPosition); exAdapter.setSelectGroupIndex(((Group) exAdapter.getGroup(groupPosition)).getIndex()); switch (groupPosition) { case 2: exAdapter.setSelectChildIndex(1); break; case 3: exAdapter.setSelectChildIndex(5); break; default: break; } return true; } }); // 始终只展开一个组 epdList.setOnGroupExpandListener(new ExpandableListView.OnGroupExpandListener() { @Override public void onGroupExpand(int groupPosition) { // TODO Auto-generated method stub int goupIndex = ((Group) exAdapter.getGroup(groupPosition)).getIndex(); exAdapter.setSelectGroupIndex(goupIndex); switch (goupIndex) { case 3: exAdapter.setSelectChildIndex(1); break; case 4: exAdapter.setSelectChildIndex(5); break; default: break; } for (int i = 0; i < exAdapter.getGroupCount(); i++) { if (i != groupPosition && epdList.isGroupExpanded(i)) { epdList.collapseGroup(i); } } } }); epdList.setOnChildClickListener(new ExpandableListView.OnChildClickListener() { @Override public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) { // TODO Auto-generated method stub Child child = (Child) ((Group) parent.getAdapter().getItem(groupPosition)).getChildrenList().get(childPosition); exAdapter.setSelectChildIndex(child.getIndex()); exAdapter.notifyDataSetChanged(); return true; } }); btnComfirm.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { exAdapter.getSelectGroupIndex(); int groupIndex = exAdapter.getSelectGroupIndex(); int childIndex = exAdapter.getSelectChildIndex(); String commentTxt = ""; int commentValue = 100; switch (groupIndex) { // "非常满意" case 1: commentValue = commentGood; commentTxt = ""; break; // "一般满意" case 2: commentValue = commentNomal; commentTxt = ""; break; // "不太满意" case 3: commentValue = commentBad; commentTxt = NewMainActivityNew.childName[childIndex - 1]; break; // "取消订单" case 4: commentValue = commentCancelBook; commentTxt = NewMainActivityNew.childName[childIndex - 1]; break; default: break; } String inputComment = tvComment.getText().toString().trim(); if (!StringUtils.isEmpty(inputComment)) { commentTxt = inputComment; } JSONObject object = new JSONObject(); try { object.put("value", commentValue); object.put("comment", commentTxt); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } // Toast.makeText(context, object.toString(), // Toast.LENGTH_SHORT).show(); callback.handle(object); dlg.dismiss(); } }); btnBack.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { dlg.dismiss(); } }); // 默认选中第一项 epdList.expandGroup(0); dlg.show(); } private static void keepDialog(DialogInterface dialog) { try { Field field = dialog.getClass().getSuperclass().getDeclaredField("mShowing"); field.setAccessible(true); field.set(dialog, false); } catch (Exception e) { e.printStackTrace(); } } private static void distoryDialog(DialogInterface dialog) { try { Field field = dialog.getClass().getSuperclass().getDeclaredField("mShowing"); field.setAccessible(true); field.set(dialog, true); } catch (Exception e) { e.printStackTrace(); } } public static void showMessageDialog(final Context context, String title, String msg, String comfirmBtn, String cancelBtn, final Callback<Object> comfirmCallback, final Callback<Object> cancelCallback) { LayoutInflater factory = LayoutInflater.from(context); final Dialog dlg = new Dialog(context, R.style.Customdialog); final View dialogView = factory.inflate(R.layout.showmsg_window, null); final TextView tvTitle = (TextView) dialogView.findViewById(R.id.show_message_title); final TextView tvTxt = (TextView) dialogView.findViewById(R.id.show_message_txt); final TextView tvComfirm = (TextView) dialogView.findViewById(R.id.show_msg_comfirm_txt); final TextView tvCancel = (TextView) dialogView.findViewById(R.id.show_msg_cancel_txt); final View btnComfirm = dialogView.findViewById(R.id.show_msg_comfirm); final View btnBack = dialogView.findViewById(R.id.show_msg_cancel); dlg.setContentView(dialogView); if (StringUtils.isEmpty(title)) { tvTitle.setText("信息提示"); } else { tvTitle.setText(title); } if (StringUtils.isEmpty(msg)) { tvTxt.setText(""); } else { tvTxt.setText(msg); } if (StringUtils.isEmpty(comfirmBtn)) { tvComfirm.setText("确定"); } else { tvComfirm.setText(comfirmBtn); } btnComfirm.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub dlg.dismiss(); if (comfirmCallback != null) { comfirmCallback.handle(null); } } }); if (!StringUtils.isEmpty(cancelBtn)) { tvCancel.setText(cancelBtn); btnBack.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub dlg.dismiss(); if (cancelCallback != null) { cancelCallback.handle(null); } } }); } else { btnBack.setVisibility(View.GONE); } dlg.show(); } public static void showDlgList(final Context context, final String title, final String[] items, final Callback<String> callback) { try { // 自定义title,居中显示 TextView tvTitle = new TextView(context); tvTitle.setGravity(Gravity.CENTER); tvTitle.setTextSize(24); tvTitle.setPadding(0, 10, 0, 10); tvTitle.setText(title); new AlertDialog.Builder(context).setCustomTitle(tvTitle).setItems(items, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { callback.handle(items[which]); } }).show(); } catch (Exception e) { e.printStackTrace(); } } /** * 新的选择用车时间的弹出框 * * @param context * @param callback * @param timeLine * 从服务器获取的时间上下线 * @param defaultMinUseCarTime * 本地默认的最小用车时间 * @param defaultMaxUseCarTime * 本地默认的最大用车时间 */ public static void selectCarInfos(final Context context, final Callback<int[]> callback) { View view = LayoutInflater.from(context).inflate(R.layout.wheel_carinfo_layout, null); final Dialog dialog = new Dialog(context, R.style.Customdialog); dialog.setContentView(view); android.view.Window dlgWindow = dialog.getWindow(); WindowManager.LayoutParams lp = dlgWindow.getAttributes(); dlgWindow.setGravity(Gravity.BOTTOM); WindowManager m = dlgWindow.getWindowManager(); Display d = m.getDefaultDisplay(); // 获取屏幕宽、高用 WindowManager.LayoutParams p = dlgWindow.getAttributes(); // // 获取对话框当前的参数值 // p.height = (int) (d.getHeight() * 1); // 高度设置为屏幕的1 p.width = (int) (d.getWidth() * 1); // 宽度设置为屏幕的1 dlgWindow.setAttributes(p); Button btnok = (Button) view.findViewById(R.id.bj_button_ok); Button btnCancel = (Button) view.findViewById(R.id.bj_button_cancel); final WheelView wheelFirst = (WheelView) view.findViewById(R.id.bj_am_pm); final WheelView wheelTwo = (WheelView) view.findViewById(R.id.bj_clockadd_hour); final WheelView wheelThree = (WheelView) view.findViewById(R.id.bj_clockadd_minutes); final String[] persons = context.getResources().getStringArray(R.array.bj_persons); final String[] banches = context.getResources().getStringArray(R.array.bj_banche); final String[] floors = context.getResources().getStringArray(R.array.bj_floors); wheelThree.setAdapter(new ArrayWheelAdapter<String>(floors, 18)); wheelThree.setVisibleItems(5); wheelThree.setCyclic(false); wheelThree.setCurrentItem(0); wheelTwo.setAdapter(new ArrayWheelAdapter<String>(banches, 4)); wheelTwo.setVisibleItems(5); wheelTwo.setCyclic(false); wheelTwo.setCurrentItem(0); wheelFirst.setAdapter(new ArrayWheelAdapter<String>(persons, 4)); wheelFirst.setVisibleItems(5); wheelFirst.setCyclic(false); wheelFirst.setCurrentItem(0); wheelFirst.addChangingListener(new WheelView.OnWheelChangedListener() { @Override public void onChanged(WheelView wheel, int oldValue, int newValue) { } }); wheelTwo.addChangingListener(new WheelView.OnWheelChangedListener() { @Override public void onChanged(WheelView wheel, int oldValue, int newValue) { } }); wheelThree.addChangingListener(new WheelView.OnWheelChangedListener() { @Override public void onChanged(WheelView wheel, int oldValue, int newValue) { } }); btnok.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if (callback != null) { callback.handle(new int[] { wheelFirst.getCurrentItem(), wheelTwo.getCurrentItem(), wheelThree.getCurrentItem() }); } dialog.dismiss(); } /** * 检查选择时间是否比当前时间大 */ private boolean checkChooseTime() { String day = wheelFirst.getAdapter().getItem(wheelFirst.getCurrentItem()); int chooseHour = Integer.parseInt(wheelTwo.getAdapter().getItem(wheelTwo.getCurrentItem())); int chooseMin = Integer.parseInt(wheelThree.getAdapter().getItem(wheelThree.getCurrentItem())); Calendar now = Calendar.getInstance(); int hourNow = now.get(Calendar.HOUR_OF_DAY); int minNow = now.get(Calendar.MINUTE); if (day.equals("今天")) { if (chooseHour > hourNow) { return true; } else if (chooseHour == hourNow && chooseMin > minNow) { return true; } else { return false; } } else { return true; } } }); btnCancel.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { dialog.dismiss(); } }); dialog.show(); } /** * 旧的选择用车时间的弹出框 * * @param context * @param callback */ public static void selectInfos(final Context context, final Callback<String[]> callback) { View view = LayoutInflater.from(context).inflate(R.layout.wheel_scroll_layout, null); final Dialog dialog = new Dialog(context, R.style.Customdialog); dialog.setContentView(view); Button btnok = (Button) view.findViewById(R.id.button_ok); Button btnCancel = (Button) view.findViewById(R.id.button_cancel); final WheelView wheelDay = (WheelView) view.findViewById(R.id.am_pm); final WheelView wheelHour = (WheelView) view.findViewById(R.id.clockadd_hour); final WheelView wheelMinutes = (WheelView) view.findViewById(R.id.clockadd_minutes); final Resources res = context.getResources(); final String[] days = AirportBookPublishFragement.getTimeValues(0, -1, 0); final String[] hours = AirportBookPublishFragement.getTimeValues(1, -1, 0); final String[] mins = AirportBookPublishFragement.getTimeValues(2, -1, 0); wheelMinutes.setAdapter(new ArrayWheelAdapter<String>(mins)); wheelMinutes.setVisibleItems(5); wheelMinutes.setCyclic(false); wheelMinutes.setCurrentItem(0); wheelHour.setAdapter(new ArrayWheelAdapter<String>(hours)); wheelHour.setVisibleItems(5); wheelHour.setCyclic(false); wheelHour.setCurrentItem(0); wheelDay.setAdapter(new ArrayWheelAdapter<String>(days)); wheelDay.setVisibleItems(5); wheelDay.setCyclic(false); wheelDay.setCurrentItem(0); wheelDay.addChangingListener(new WheelView.OnWheelChangedListener() { @Override public void onChanged(WheelView wheel, int oldValue, int newValue) { try { wheelHour.setAdapter(new ArrayWheelAdapter<String>(AirportBookPublishFragement.getTimeValues(1, -1, newValue))); wheelHour.setCurrentItem(0); wheelMinutes.setAdapter(new ArrayWheelAdapter<String>(AirportBookPublishFragement.getTimeValues(2, -1, newValue))); wheelMinutes.setCurrentItem(0); } catch (Exception e) { e.printStackTrace(); wheelMinutes.setAdapter(new ArrayWheelAdapter<String>(AirportBookPublishFragement.getTimeValues(2, -1, newValue))); wheelMinutes.setCurrentItem(0); } } }); wheelHour.addChangingListener(new WheelView.OnWheelChangedListener() { @Override public void onChanged(WheelView wheel, int oldValue, int newValue) { int day = wheelDay.getCurrentItem(); int hour = Integer.parseInt(wheel.getAdapter().getItem(newValue)); wheelMinutes.setAdapter(new ArrayWheelAdapter<String>(AirportBookPublishFragement.getTimeValues(2, hour, day))); wheelMinutes.setCurrentItem(0); } }); wheelMinutes.addChangingListener(new WheelView.OnWheelChangedListener() { @Override public void onChanged(WheelView wheel, int oldValue, int newValue) { } }); btnok.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { String day = wheelDay.getAdapter().getItem(wheelDay.getCurrentItem()); String hour = wheelHour.getAdapter().getItem(wheelHour.getCurrentItem()); String min = wheelMinutes.getAdapter().getItem(wheelMinutes.getCurrentItem()); boolean isChooseCorrect = checkChooseTime(); if (isChooseCorrect) { if (day == null || hour == null || min == null) { ToastUtil.show(context, res.getString(R.string.tip_book_time)); } else { if (callback != null) { callback.handle(new String[] { day, hour, min }); } dialog.dismiss(); } } else { ToastUtil.show(context, res.getString(R.string.tip_book_time)); } } /** * 检查选择时间是否比当前时间大 */ private boolean checkChooseTime() { String day = wheelDay.getAdapter().getItem(wheelDay.getCurrentItem()); int chooseHour = Integer.parseInt(wheelHour.getAdapter().getItem(wheelHour.getCurrentItem())); int chooseMin = Integer.parseInt(wheelMinutes.getAdapter().getItem(wheelMinutes.getCurrentItem())); Calendar now = Calendar.getInstance(); int hourNow = now.get(Calendar.HOUR_OF_DAY); int minNow = now.get(Calendar.MINUTE); if (day.equals("今天")) { if (chooseHour > hourNow) { return true; } else if (chooseHour == hourNow && chooseMin > minNow) { return true; } else { return false; } } else { return true; } } }); btnCancel.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { dialog.dismiss(); } }); dialog.show(); } public static void selectBanyungong(final Context context, int yOffset, int defaultPserson, final Callback<Integer> callback) { View view = LayoutInflater.from(context).inflate(R.layout.dlg_banyungong, null); final Dialog dialog = new Dialog(context, R.style.Customdialog); dialog.setContentView(view); android.view.Window dlgWindow = dialog.getWindow(); dlgWindow.setGravity(Gravity.BOTTOM); dialog.setCancelable(false); dialog.setCanceledOnTouchOutside(false); WindowManager m = dlgWindow.getWindowManager(); Display d = m.getDefaultDisplay(); // 获取屏幕宽、高用 WindowManager.LayoutParams lp = dlgWindow.getAttributes(); // // 获取对话框当前的参数值 // p.height = (int) (d.getHeight() * 1); // 高度设置为屏幕的1 lp.width = (int) (d.getWidth() * 1); // 宽度设置为屏幕的1 lp.y = yOffset; dlgWindow.setAttributes(lp); final TextView ivPcount0 = (TextView) view.findViewById(R.id.dlg_tv_pcount_0); final TextView ivPcount1 = (TextView) view.findViewById(R.id.dlg_tv_pcount_1); final TextView ivPcount2 = (TextView) view.findViewById(R.id.dlg_tv_pcount_2); final TextView ivPcount3 = (TextView) view.findViewById(R.id.dlg_tv_pcount_3); final TextView ivPcount4 = (TextView) view.findViewById(R.id.dlg_tv_pcount_4); final TextView ivPcount5 = (TextView) view.findViewById(R.id.dlg_tv_pcount_5); ImageView btnCancel = (ImageView) view.findViewById(R.id.dlg_iv_cancel); ImageView btnOk = (ImageView) view.findViewById(R.id.dlg_iv_ok); final SeekBar seekBar = (SeekBar) view.findViewById(R.id.dlg_sb_person); seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onStopTrackingTouch(SeekBar seekBar) { // TODO Auto-generated method stub } @Override public void onStartTrackingTouch(SeekBar seekBar) { // TODO Auto-generated method stub } @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { // TODO Auto-generated method stub ivPcount0.setVisibility(View.INVISIBLE); ivPcount1.setVisibility(View.INVISIBLE); ivPcount2.setVisibility(View.INVISIBLE); ivPcount3.setVisibility(View.INVISIBLE); ivPcount4.setVisibility(View.INVISIBLE); ivPcount5.setVisibility(View.INVISIBLE); switch (progress) { case 0: ivPcount0.setVisibility(View.VISIBLE); break; case 1: ivPcount1.setVisibility(View.VISIBLE); break; case 2: ivPcount2.setVisibility(View.VISIBLE); break; case 3: ivPcount3.setVisibility(View.VISIBLE); break; case 4: ivPcount4.setVisibility(View.VISIBLE); break; case 5: ivPcount5.setVisibility(View.VISIBLE); break; default: break; } } }); seekBar.setProgress(defaultPserson); btnOk.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub dialog.dismiss(); callback.handle(seekBar.getProgress()); } }); btnCancel.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { dialog.dismiss(); } }); dialog.show(); } }
true
1bd7a75bfd388684001212646eb700f973a6d42c
Java
freeuni-sdp/snake-15
/src/ge/edu/freeuni/sdp/snake/model/Caretaker.java
UTF-8
2,924
3
3
[ "MIT" ]
permissive
package ge.edu.freeuni.sdp.snake.model; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; public class Caretaker { private Memento savedState; private boolean fileExists; File mementoFile = new File("memento.txt"); public Caretaker() { if (mementoFile.exists()) { restoreMementoFromFile(); } } private void restoreMementoFromFile() { int length = 0; String direction = null; Point head = null; int levelIndex = 0; try { FileReader fileReader = new FileReader(mementoFile); BufferedReader bufferedReader = new BufferedReader(fileReader); length = Integer.parseInt(bufferedReader.readLine()); direction = bufferedReader.readLine(); head = new Point(Integer.parseInt(bufferedReader.readLine()),Integer.parseInt(bufferedReader.readLine())); levelIndex = Integer.parseInt(bufferedReader.readLine()); bufferedReader.close(); } catch(FileNotFoundException ex) { } catch(IOException e) { e.printStackTrace(); } savedState = new Memento(length, direction, head, levelIndex); } public Memento getMemento() { return savedState; } public void addMemento(Memento savedState) { this.savedState = savedState; try { mementoFile.createNewFile(); } catch (IOException e) { e.printStackTrace(); } saveInFile(); } private void saveInFile() { try { // Assume default encoding. FileWriter fileWriter = new FileWriter(mementoFile); BufferedWriter bufferedWriter = new BufferedWriter(fileWriter); bufferedWriter.write(""+savedState.getLength()); bufferedWriter.newLine(); bufferedWriter.write(savedState.getDirectionString()); bufferedWriter.newLine(); bufferedWriter.write(""+savedState.getHead().X); bufferedWriter.newLine(); bufferedWriter.write(""+savedState.getHead().Y); bufferedWriter.newLine(); bufferedWriter.write(""+savedState.getLevelIndex()); bufferedWriter.close(); } catch(IOException e) { e.printStackTrace(); } // BufferedWriter writer = null; // try { // writer = new BufferedWriter(new FileWriter(mementoFile)); // writer.write(savedState.getLength()); // writer.newLine(); // writer.write(savedState.getDirectionString()); // writer.newLine(); // writer.write(); // writer.newLine(); // writer.write(savedState.getHead().Y); // writer.newLine(); // writer.write(savedState.getLevelIndex()); // // writer.close(); // // } catch (IOException e) { // e.printStackTrace(); // } } public boolean hasSavedState() { return fileExists; } }
true
258400be7424f4537aaf217a17c8d2000cab0f50
Java
khandura/Basic
/src/com/test/entity/Person.java
UTF-8
1,074
2.8125
3
[]
no_license
package com.test.entity; public class Person { private String name; private String profile; private Integer age; public Person() { } /** * * @param name * @param profile * @param age */ public Person(String name, String profile, Integer age) { super(); this.name = name; this.profile = profile; this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getProfile() { return profile; } public void setProfile(String profile) { this.profile = profile; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("Person [name="); builder.append(name); builder.append(", profile="); builder.append(profile); builder.append(", age="); builder.append(age); builder.append("]"); return builder.toString(); } }
true
153328a097037e41afa7b28c6b98f4dbe15ac18c
Java
AndreasRam/blogWeb
/AppBlogEJB/src/java/cl/senpai/appBlog/dao/UsuariosDAO.java
UTF-8
1,845
2.34375
2
[]
no_license
/* * 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 cl.senpai.appBlog.dao; import cl.senpai.appBlog.dto.Usuario; import javax.ejb.Stateless; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; /** * * @author Senpai */ @Stateless public class UsuariosDAO implements UsuariosDAOLocal { private EntityManagerFactory emf = Persistence.createEntityManagerFactory("AppBlogEJBPU"); @Override public void add(Usuario u) { EntityManager em = emf.createEntityManager(); try{ em.persist(u); }catch(Exception e){ }finally{ em.close(); } } @Override public Usuario findUsuarioByCorreoAndPassword(String correo, String contrasena) { EntityManager em = emf.createEntityManager(); try{ return em.createNamedQuery("Usuario.findByCorreoAndContrasena", Usuario.class) .setParameter("correo", correo) .setParameter("contrasena", contrasena) .getSingleResult(); }catch(Exception e){ return null; }finally{ em.close(); } } @Override public Usuario findUsuarioByCorreo(String correo) { EntityManager em = emf.createEntityManager(); try{ return em.createNamedQuery("Usuario.findByCorreo", Usuario.class) .setParameter("correo", correo) .getSingleResult(); }catch(Exception e){ return null; }finally{ em.close(); } } }
true
21f980954fde64243c977aff3b09237357532ba3
Java
elsand/vefa-srest
/api/src/main/java/no/sr/ringo/common/SoftwareVersionNumber.java
UTF-8
2,429
2.8125
3
[]
no_license
/* Created by steinar on 15.05.12 at 23:00 */ package no.sr.ringo.common; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * @author Steinar Overbeck Cook steinar@sendregning.no */ public class SoftwareVersionNumber { Integer majorRevision; Integer minorRevision; Integer incrementalRevision; String qualifier; /** * Regex pattern which will always of 4 groups, numbered from 1 through 4. Group 0 is the entire pattern. * Group number 3 and 4 are optional (incremental version number and qualifier) */ Pattern versionNumberPattern = Pattern.compile( "(\\d+)" // Major revision number + "(?:\\.(\\d+))" // Minor revision number + "(?:(?:\\.(\\d+))?" // Incremental revision number (optional) + "(?:\\-(\\w*))?)?"); // Qualifier (optional) public SoftwareVersionNumber(String versionNumber) { Matcher m = versionNumberPattern.matcher(versionNumber); if (m.matches()) { majorRevision = Integer.parseInt(m.group(1)); minorRevision = Integer.parseInt(m.group(2)); if (m.group(3) != null) incrementalRevision = Integer.parseInt(m.group(3)); if (m.group(4) != null) { qualifier = m.group(4); } } else throw new IllegalArgumentException("Invalid version number: " + versionNumber); } public Integer getMajorRevision() { return majorRevision; } public Integer getMinorRevision() { return minorRevision; } /** * Optional incremental revision number, i.e. this could possibly return null * * @return incremental revision number */ public Integer getIncrementalRevision() { return incrementalRevision; } public String getQualifier() { return qualifier; } /** * Checks if version is up to date comparing minor and major revisions only. * <p> * Example usage boolean outOfDate = serverVersion.isOutOfDate(clientVersion); * </p> * @param another the other version number to check against * @return true if the "another" version number is out of date. */ public boolean isOutOfDate(SoftwareVersionNumber another) { return another.majorRevision != majorRevision || minorRevision != another.minorRevision; } }
true
5bb8fb413087ab7aa205a9fbed91ec712a7ceca3
Java
Nona9961/DesignPattern
/code/state/NormalState.java
UTF-8
288
2.65625
3
[]
no_license
package state; public class NormalState extends AbstractState { public NormalState(Context ctx) { super(ctx); } @Override public void handle() { System.out.println("正常人真好"); ctx.setAge(-1); stateCheck(); } }
true
c9917e3527882044008100f394a3f6fc65ec1744
Java
leowongkh/Cointiplay-Simulator
/src/Simulator.java
UTF-8
7,190
2.796875
3
[]
no_license
import javafx.application.Application; import javafx.geometry.Pos; import javafx.scene.Scene; import javafx.scene.layout.BorderPane; import javafx.scene.layout.GridPane; import javafx.scene.text.FontWeight; import javafx.scene.text.Text; import javafx.scene.text.TextAlignment; import javafx.scene.text.*; import javafx.scene.control.*; import javafx.scene.paint.*; import javafx.stage.Stage; import javafx.scene.input.*; import javafx.event.*; import javafx.scene.layout.*; import javafx.scene.control.SpinnerValueFactory.DoubleSpinnerValueFactory; import javafx.scene.control.SpinnerValueFactory.IntegerSpinnerValueFactory; public class Simulator extends Application{ private static final int INITIAL_BET = 10; private static final double START_BET_MULTIPLIER = 1.0; private static final int INIT_NUM_OF_PLAYS = 10000; private static final double INTERVAL_BETWEEN_PLAYS_IN_SECONDS = 0.1; private static int numberOfPlays = 10000; private static double betMultiplier = 1.0; private static int initialBet = 0; private static int totalProfit = 0; private static SimulatorController simulatorControl = new SimulatorController(0, 0, 0); @Override public void start(Stage primaryStage){ var title = new Text("Cointiplay Simulator"); title.setTextAlignment(TextAlignment.CENTER); title.setFont(Font.font("Times New Roman", FontWeight.EXTRA_BOLD,40.0)); title.setFill(Color.RED); var grid = new GridPane(); grid.setAlignment(Pos.CENTER); grid.add(new Label("Initial Bet in coins:"), 0,0 ); var initBet = new Spinner<Integer>(10,Integer.MAX_VALUE, INITIAL_BET, 1); initBet.setEditable(true); initBet.getEditor().textProperty().addListener((observable, oldValue, newValue)->{ try { Integer.parseInt(newValue); if (Integer.parseInt(newValue) < ((IntegerSpinnerValueFactory) initBet.getValueFactory()).getMin()){ throw new NumberFormatException(); } if (newValue.endsWith("f") || newValue.endsWith("d")) { initBet.getEditor().setText(newValue.substring(0, newValue.length()-1)); } } catch (NumberFormatException e) { initBet.getEditor().setText(oldValue); } }); grid.add(initBet, 1,0); grid.add(new Label("Bet multiplier: "), 0,1); var betMult = new Spinner<Double>(0.0001, Double.MAX_VALUE, START_BET_MULTIPLIER, 0.1); betMult.setEditable(true); betMult.getEditor().textProperty().addListener((observable, oldValue, newValue)->{ try { Double.parseDouble(newValue); if (Double.parseDouble(newValue) < ((DoubleSpinnerValueFactory) betMult.getValueFactory()).getMin()){ throw new NumberFormatException(); } if (newValue.endsWith("f") || newValue.endsWith("d")) { betMult.getEditor().setText(newValue.substring(0, newValue.length()-1)); } } catch (NumberFormatException e) { betMult.getEditor().setText(oldValue); } }); grid.add(betMult, 1,1); grid.add(new Label("Number of Plays:"), 0,2); var numSim = new Spinner<Integer>(1, Integer.MAX_VALUE, INIT_NUM_OF_PLAYS, 1); numSim.setEditable(true); numSim.getEditor().textProperty().addListener((observable, oldValue, newValue)->{ try { Integer.parseInt(newValue); if (Integer.parseInt(newValue) < ((IntegerSpinnerValueFactory) numSim.getValueFactory()).getMin()){ throw new NumberFormatException(); } if (newValue.endsWith("f") || newValue.endsWith("d")) { numSim.getEditor().setText(newValue.substring(0, newValue.length()-1)); } } catch (NumberFormatException e) { numSim.getEditor().setText(oldValue); } }); grid.add(numSim, 1,2); var button = new Button("Start Simulation"); var root = new BorderPane(); root.setTop(title); root.setCenter(grid); root.setBottom(button); BorderPane.setAlignment(title, Pos.BOTTOM_CENTER); BorderPane.setAlignment(grid,Pos.CENTER); BorderPane.setAlignment(button, Pos.TOP_CENTER); button.setOnAction(e->{ betMultiplier = betMult.getValue().doubleValue(); numberOfPlays = numSim.getValue().intValue(); initialBet = initBet.getValue().intValue(); simulatorControl.setWager(initialBet); changeScene(primaryStage); }); var startScene = new Scene(root, 400, 300); primaryStage.setScene(startScene); primaryStage.show(); } public void changeScene(Stage currentStage){ var title = new Text("Cointiplay Simulator"); title.setTextAlignment(TextAlignment.CENTER); title.setFont(Font.font("Times New Roman", FontWeight.EXTRA_BOLD,40.0)); title.setFill(Color.RED); var nextGrid = new GridPane(); nextGrid.setAlignment(Pos.CENTER); nextGrid.setVgap(15.0); nextGrid.setHgap(10.0); nextGrid.add(new Text("Roll Result:"), 0, 0, 4, 1); var resultDisplay = new Text(); resultDisplay.setTextAlignment(TextAlignment.CENTER); resultDisplay.setFont(new Font(30.0)); var betDisplay = new Text(); var playDisplay = new Text(); var messageDisplay = new Text(); messageDisplay.setTextAlignment(TextAlignment.CENTER); var profitDisplay = new Text(); profitDisplay.setTextAlignment(TextAlignment.CENTER); nextGrid.add(resultDisplay, 0, 1, 4, 2); nextGrid.add(new Label("Current Bet: "), 0, 2, 1,1); nextGrid.add(betDisplay, 1,2,1,1); nextGrid.add(new Label("Current Play #: "), 2,2,1,1); nextGrid.add(playDisplay, 3, 2, 1, 1); nextGrid.add(messageDisplay, 0,3,4,1); nextGrid.add(profitDisplay, 0,4,4,1); var nextBottom = new HBox(); nextBottom.setSpacing(20); nextBottom.setAlignment(Pos.CENTER); var list = nextBottom.getChildren(); list.addAll(new Label("Initial Bet: "+ initialBet), new Label("Bet Multiply when lose: " + betMultiplier), new Label("Number of Plays: " + numberOfPlays)); var root = new BorderPane(); root.setTop(title); root.setCenter(nextGrid); root.setBottom(nextBottom); BorderPane.setAlignment(title, Pos.BOTTOM_CENTER); BorderPane.setAlignment(nextGrid,Pos.CENTER); BorderPane.setAlignment(nextBottom, Pos.TOP_CENTER); var nextScene = new Scene(root,600, 600); currentStage.setScene(nextScene); currentStage.show(); boolean result; for (int i = 0; i < numberOfPlays; i++){ betDisplay.setText(Integer.toString(simulatorControl.getWager())); result = simulatorControl.rollAndReturnResult(); resultDisplay.setText(Integer.toString(simulatorControl.getRollResult())); playDisplay.setText(Integer.toString(i+1)); totalProfit += simulatorControl.getProfit(); if (result){ messageDisplay.setText("You win and earned " +Integer.toString(simulatorControl.getProfit()) + " coins."); simulatorControl.setWager(initialBet); } else{ messageDisplay.setText("You lose and "+ Integer.toString(-1 * simulatorControl.getProfit()) + " coins was deducted from your account."); simulatorControl.setWager(Double.valueOf(simulatorControl.getWager() * betMultiplier).intValue()); } profitDisplay.setText("Total Profit: " + Integer.toString(totalProfit)); /*try { Thread.sleep(Double.valueOf(INTERVAL_BETWEEN_PLAYS_IN_SECONDS*1000).longValue()); }catch (InterruptedException e){ e.printStackTrace(); }*/ } } public static void main(String[] args){ launch(args); } }
true
3278dac34cbb32c037dc4260451fcb0977567d10
Java
percussion/percussioncms
/system/webservices/src/com/percussion/webservices/uidesign/UiDesignSOAPImpl.java
UTF-8
37,822
1.507813
2
[ "LicenseRef-scancode-dco-1.1", "Apache-2.0", "OFL-1.1", "LGPL-2.0-or-later" ]
permissive
/* * Copyright 1999-2023 Percussion Software, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * limitations under the License. */ package com.percussion.webservices.uidesign; import com.percussion.cms.objectstore.PSAction; import com.percussion.cms.objectstore.PSSearch; import com.percussion.error.PSExceptionUtils; import com.percussion.services.catalog.IPSCatalogSummary; import com.percussion.services.catalog.PSTypeEnum; import com.percussion.services.guidmgr.PSGuidUtils; import com.percussion.services.guidmgr.data.PSDesignGuid; import com.percussion.services.ui.PSUiException; import com.percussion.utils.guid.IPSGuid; import com.percussion.webservices.PSBaseSOAPImpl; import com.percussion.webservices.PSErrorException; import com.percussion.webservices.PSErrorResultsException; import com.percussion.webservices.PSErrorsException; import com.percussion.webservices.PSLockErrorException; import com.percussion.webservices.common.PSObjectSummary; import com.percussion.webservices.faults.PSContractViolationFault; import com.percussion.webservices.faults.PSErrorResultsFault; import com.percussion.webservices.faults.PSErrorsFault; import com.percussion.webservices.faults.PSInvalidSessionFault; import com.percussion.webservices.faults.PSNotAuthorizedFault; import com.percussion.webservices.ui.IPSUiDesignWs; import com.percussion.webservices.ui.PSUiWsLocator; import com.percussion.webservices.ui.data.ActionType; import com.percussion.webservices.ui.data.PSDisplayFormat; import com.percussion.webservices.ui.data.PSHierarchyNode; import com.percussion.webservices.ui.data.PSSearchDef; import com.percussion.webservices.ui.data.PSViewDef; import java.rmi.RemoteException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * Server side implementations for web services defined in * <code>rhythmyxDesign.wsdl</code> for operations defined in the * <code>uiDesignSOAP</code> bindings. */ public class UiDesignSOAPImpl extends PSBaseSOAPImpl implements UiDesign { /* * (non-Javadoc) * * @see UiDesign#createActions(CreateActionsRequest) */ public com.percussion.webservices.ui.data.PSAction[] createActions( CreateActionsRequest req) throws RemoteException, PSInvalidSessionFault, PSContractViolationFault, PSNotAuthorizedFault { final String serviceName = "createActions"; String session = authenticate(); String user = getRemoteUser(); // get list of names ane types from the request List<String> names = Arrays.asList( req.getName()); List<ActionType> types = new ArrayList<ActionType>(); for (com.percussion.webservices.uidesign.CreateActionsRequestType type : req.getType()) { if (type.getValue().equals( com.percussion.webservices.uidesign.CreateActionsRequestType._item)) { types.add(ActionType.item); } else if (type.getValue().equals( com.percussion.webservices.uidesign.CreateActionsRequestType._cascading)) { types.add(ActionType.cascading); } else { types.add(ActionType.dynamic); } } // create the actions IPSUiDesignWs uiws = PSUiWsLocator.getUiDesignWebservice(); com.percussion.webservices.ui.data.PSAction[] result = null; try { List<PSAction> actions = uiws.createActions(names, types, session, user); // convert the actions result = (com.percussion.webservices.ui.data.PSAction[]) convert( com.percussion.webservices.ui.data.PSAction[].class, actions); } catch (IllegalArgumentException e) { handleInvalidContract(e, serviceName); } catch (PSLockErrorException e) { handleLockError(e); } catch (PSErrorException e) { throw new RemoteException(PSExceptionUtils.getMessageForLog(e)); } catch (RuntimeException e) { handleRuntimeException(e, serviceName); } return result; } /* * (non-Javadoc) * * @see UiDesign#createDisplayFormats(String[]) */ public PSDisplayFormat[] createDisplayFormats(String[] names) throws RemoteException, PSInvalidSessionFault, PSContractViolationFault, PSNotAuthorizedFault { final String serviceName = "createDisplayFormats"; String session = authenticate(); String user = getRemoteUser(); IPSUiDesignWs uiws = PSUiWsLocator.getUiDesignWebservice(); PSDisplayFormat[] result = null; try { List<com.percussion.cms.objectstore.PSDisplayFormat> dspFormats = uiws.createDisplayFormats(Arrays.asList(names), session, user); result = (PSDisplayFormat[]) convert(PSDisplayFormat[].class, dspFormats); } catch (IllegalArgumentException e) { handleInvalidContract(e, serviceName); } catch (PSLockErrorException e) { handleLockError(e); } catch (PSErrorException e) { throw new RemoteException(PSExceptionUtils.getMessageForLog(e)); } catch (RuntimeException e) { handleRuntimeException(e, serviceName); } return result; } /* * (non-Javadoc) * * @see UiDesign#createSearches(CreateSearchesRequest) */ public PSSearchDef[] createSearches( CreateSearchesRequest req) throws RemoteException, PSInvalidSessionFault, PSContractViolationFault, PSNotAuthorizedFault { final String serviceName = "createSearches"; String session = authenticate(); String user = getRemoteUser(); // get list of names ane types from the request List<String> names = Arrays.asList( req.getName()); List<String> types = new ArrayList<String>(); for (CreateSearchesRequestType type :req.getType()) { if (type.getValue().equals(CreateSearchesRequestType._custom)) types.add(PSSearch.TYPE_CUSTOMSEARCH); else if (type.getValue().equals(CreateSearchesRequestType._standard)) types.add(PSSearch.TYPE_STANDARDSEARCH); else types.add(PSSearch.TYPE_USERSEARCH); } // create the searches IPSUiDesignWs uiws = PSUiWsLocator.getUiDesignWebservice(); PSSearchDef[] result = null; try { List<PSSearch> searches = uiws.createSearches(names, types, session, user); result = (PSSearchDef[]) convert(PSSearchDef[].class, searches); } catch (IllegalArgumentException e) { handleInvalidContract(e, serviceName); } catch (PSLockErrorException e) { handleLockError(e); } catch (PSErrorException e) { throw new RemoteException(PSExceptionUtils.getMessageForLog(e)); } catch (RuntimeException e) { handleRuntimeException(e, serviceName); } return result; } /* * (non-Javadoc) * * @see UiDesign#createViews(String[]) */ public PSViewDef[] createViews(String[] names) throws RemoteException, PSInvalidSessionFault, PSContractViolationFault, PSNotAuthorizedFault { final String serviceName = "createViews"; String session = authenticate(); String user = getRemoteUser(); // get list of names ane types from the request List<String> nameList = Arrays.asList( names); // create the searches IPSUiDesignWs uiws = PSUiWsLocator.getUiDesignWebservice(); PSViewDef[] result = null; try { List<PSSearch> searches = uiws.createViews(nameList, session, user); result = (PSViewDef[]) convert(PSViewDef[].class, searches); } catch (IllegalArgumentException e) { handleInvalidContract(e, serviceName); } catch (PSLockErrorException e) { handleLockError(e); } catch (PSErrorException e) { throw new RemoteException(PSExceptionUtils.getMessageForLog(e)); } catch (RuntimeException e) { handleRuntimeException(e, serviceName); } return result; } /* * (non-Javadoc) * * @see UiDesign#deleteActions(DeleteActionsRequest) */ public void deleteActions(DeleteActionsRequest req) throws RemoteException, PSInvalidSessionFault, PSErrorsFault, PSContractViolationFault, PSNotAuthorizedFault { final String service = "deleteActions"; String session = authenticate(); String user = getRemoteUser(); // convert ids to a list of GUIDs List<IPSGuid> ids = new ArrayList<IPSGuid>(); for (long id : req.getId()) ids.add(new PSDesignGuid(id)); boolean ignoreDep = extractBooleanValue(req.getIgnoreDependencies(), false); IPSUiDesignWs uiws = PSUiWsLocator.getUiDesignWebservice(); try { uiws.deleteActions(ids, ignoreDep, session, user); } catch (PSErrorsException e) { handleErrorsException(e, service); } catch (IllegalArgumentException e) { handleInvalidContract(e, service); } catch (RuntimeException e) { handleRuntimeException(e, service); } } /* * (non-Javadoc) * * @see UiDesign#deleteDisplayFormats(DeleteDisplayFormatsRequest) */ public void deleteDisplayFormats( DeleteDisplayFormatsRequest req) throws RemoteException, PSInvalidSessionFault, PSErrorsFault, PSContractViolationFault, PSNotAuthorizedFault { final String service = "deleteDisplayFormats"; String session = authenticate(); String user = getRemoteUser(); // convert ids to a list of GUIDs List<IPSGuid> ids = new ArrayList<IPSGuid>(); for (long id : req.getId()) ids.add(new PSDesignGuid(id)); boolean ignoreDep = extractBooleanValue(req.getIgnoreDependencies(), false); IPSUiDesignWs uiws = PSUiWsLocator.getUiDesignWebservice(); try { uiws.deleteDisplayFormats(ids, ignoreDep, session, user); } catch (PSErrorsException e) { handleErrorsException(e, service); } catch (IllegalArgumentException e) { handleInvalidContract(e, service); } catch (RuntimeException e) { handleRuntimeException(e, service); } } /* * (non-Javadoc) * * @see UiDesign#deleteSearches(DeleteSearchesRequest) */ public void deleteSearches(DeleteSearchesRequest req) throws RemoteException, PSInvalidSessionFault, PSErrorsFault, PSContractViolationFault, PSNotAuthorizedFault { final String service = "deleteSearches"; String session = authenticate(); String user = getRemoteUser(); // convert ids to a list of GUIDs List<IPSGuid> ids = new ArrayList<IPSGuid>(); for (long id : req.getId()) ids.add(new PSDesignGuid(id)); boolean ignoreDep = extractBooleanValue(req.getIgnoreDependencies(), false); IPSUiDesignWs uiws = PSUiWsLocator.getUiDesignWebservice(); try { uiws.deleteSearches(ids, ignoreDep, session, user); } catch (PSErrorsException e) { handleErrorsException(e, service); } catch (IllegalArgumentException e) { handleInvalidContract(e, service); } catch (RuntimeException e) { handleRuntimeException(e, service); } } /* * (non-Javadoc) * * @see UiDesign#deleteViews(DeleteViewsRequest) */ public void deleteViews(DeleteViewsRequest req) throws RemoteException, PSInvalidSessionFault, PSErrorsFault, PSContractViolationFault, PSNotAuthorizedFault { final String service = "deleteViews"; String session = authenticate(); String user = getRemoteUser(); // convert ids to a list of GUIDs List<IPSGuid> ids = new ArrayList<IPSGuid>(); for (long id : req.getId()) ids.add(new PSDesignGuid(id)); boolean ignoreDep = extractBooleanValue(req.getIgnoreDependencies(), false); IPSUiDesignWs uiws = PSUiWsLocator.getUiDesignWebservice(); try { uiws.deleteViews(ids, ignoreDep, session, user); } catch (PSErrorsException e) { handleErrorsException(e, service); } catch (IllegalArgumentException e) { handleInvalidContract(e, service); } catch (RuntimeException e) { handleRuntimeException(e, service); } } /* * (non-Javadoc) * * @see UiDesign#findActions(FindActionsRequest) */ public PSObjectSummary[] findActions(FindActionsRequest request) throws RemoteException, PSInvalidSessionFault, PSContractViolationFault { authenticate(); IPSUiDesignWs uiws = PSUiWsLocator.getUiDesignWebservice(); try { List<ActionType> types = request.getType() == null ? null : Arrays .asList(request.getType()); List<IPSCatalogSummary> objects = uiws.findActions(request.getName(), request.getLabel(), types); return (PSObjectSummary[]) convert(PSObjectSummary[].class, objects); } catch (PSErrorException e) { // unknown error throw new RemoteException(PSExceptionUtils.getMessageForLog(e)); } } /* * (non-Javadoc) * * @see UiDesign#findDisplayFormats(FindDisplayFormatsRequest) */ public PSObjectSummary[] findDisplayFormats( FindDisplayFormatsRequest request) throws RemoteException, PSInvalidSessionFault, PSContractViolationFault { authenticate(); IPSUiDesignWs uiws = PSUiWsLocator.getUiDesignWebservice(); try { List<IPSCatalogSummary> objects = uiws.findDisplayFormats(request .getName(), request.getLabel()); return (PSObjectSummary[]) convert(PSObjectSummary[].class, objects); } catch (PSErrorException e) { // unknown error throw new RemoteException(PSExceptionUtils.getMessageForLog(e)); } } /* * (non-Javadoc) * * @see UiDesign#findSearches(FindSearchesRequest) */ public PSObjectSummary[] findSearches(FindSearchesRequest request) throws RemoteException, PSInvalidSessionFault, PSContractViolationFault { authenticate(); IPSUiDesignWs uiws = PSUiWsLocator.getUiDesignWebservice(); try { List<IPSCatalogSummary> objects = uiws.findSearches(request.getName(), request.getLabel()); return (PSObjectSummary[]) convert(PSObjectSummary[].class, objects); } catch (PSErrorException e) { // unknown error throw new RemoteException(PSExceptionUtils.getMessageForLog(e)); } } /* * (non-Javadoc) * * @see UiDesign#findViews(FindViewsRequest) */ public PSObjectSummary[] findViews(FindViewsRequest request) throws RemoteException, PSInvalidSessionFault, PSContractViolationFault { authenticate(); IPSUiDesignWs uiws = PSUiWsLocator.getUiDesignWebservice(); try { List<IPSCatalogSummary> objects = uiws.findViews(request.getName(), request.getLabel()); return (PSObjectSummary[]) convert(PSObjectSummary[].class, objects); } catch (PSErrorException e) { // unknown error throw new RemoteException(PSExceptionUtils.getMessageForLog(e)); } } /* * (non-Javadoc) * * @see UiDesign#loadActions(LoadActionsRequest) */ public com.percussion.webservices.ui.data.PSAction[] loadActions( LoadActionsRequest loadActionsRequest) throws RemoteException, PSErrorResultsFault, PSInvalidSessionFault, PSContractViolationFault, PSNotAuthorizedFault { final String service = "loadActions"; String session = authenticate(); String user = getRemoteUser(); // convert ids to a list of GUIDs List<IPSGuid> ids = new ArrayList<IPSGuid>(); for (long id : loadActionsRequest.getId()) ids.add(new PSDesignGuid(id)); IPSUiDesignWs uiws = PSUiWsLocator.getUiDesignWebservice(); com.percussion.webservices.ui.data.PSAction[] result = null; try { List<PSAction> actions = uiws.loadActions(ids, loadActionsRequest .getLock(), loadActionsRequest.getOverrideLock(), session, user); result = (com.percussion.webservices.ui.data.PSAction[]) convert( com.percussion.webservices.ui.data.PSAction[].class, actions); } catch (IllegalArgumentException e) { handleInvalidContract(e, service); } catch (RuntimeException e) { handleRuntimeException(e, service); } catch (PSErrorResultsException e) { handleErrorResultsException(e, service); } return result; } /* * (non-Javadoc) * * @see UiDesign#loadDisplayFormats(LoadDisplayFormatsRequest) */ public PSDisplayFormat[] loadDisplayFormats( LoadDisplayFormatsRequest request) throws RemoteException, PSErrorResultsFault, PSInvalidSessionFault, PSContractViolationFault, PSNotAuthorizedFault { final String service = "loadDisplayFormats"; String session = authenticate(); String user = getRemoteUser(); // convert ids to a list of GUIDs List<IPSGuid> ids = new ArrayList<IPSGuid>(); for (long id : request.getId()) ids.add(new PSDesignGuid(id)); IPSUiDesignWs uiws = PSUiWsLocator.getUiDesignWebservice(); PSDisplayFormat[] result = null; try { List<com.percussion.cms.objectstore.PSDisplayFormat> dspFormats = uiws .loadDisplayFormats(ids, request.getLock(), request .getOverrideLock(), session, user); result = (PSDisplayFormat[]) convert(PSDisplayFormat[].class, dspFormats); } catch (IllegalArgumentException e) { handleInvalidContract(e, service); } catch (RuntimeException e) { handleRuntimeException(e, service); } catch (PSErrorResultsException e) { handleErrorResultsException(e, service); } return result; } /* * (non-Javadoc) * * @see UiDesign#loadSearches(LoadSearchesRequest) */ public PSSearchDef[] loadSearches(LoadSearchesRequest request) throws RemoteException, PSErrorResultsFault, PSInvalidSessionFault, PSContractViolationFault, PSNotAuthorizedFault { final String service = "loadSearches"; String session = authenticate(); String user = getRemoteUser(); // convert ids to a list of GUIDs List<IPSGuid> ids = new ArrayList<IPSGuid>(); for (long id : request.getId()) ids.add(new PSDesignGuid(id)); IPSUiDesignWs uiws = PSUiWsLocator.getUiDesignWebservice(); PSSearchDef[] result = null; try { List<com.percussion.cms.objectstore.PSSearch> searches = uiws .loadSearches(ids, request.getLock(), request .getOverrideLock(), session, user); result = (PSSearchDef[]) convert(PSSearchDef[].class, searches); } catch (IllegalArgumentException e) { handleInvalidContract(e, service); } catch (RuntimeException e) { handleRuntimeException(e, service); } catch (PSErrorResultsException e) { handleErrorResultsException(e, service); } return result; } /* * (non-Javadoc) * * @see UiDesign#loadViews(LoadViewsRequest) */ public PSViewDef[] loadViews(LoadViewsRequest request) throws RemoteException, PSErrorResultsFault, PSInvalidSessionFault, PSContractViolationFault, PSNotAuthorizedFault { final String service = "loadViews"; String session = authenticate(); String user = getRemoteUser(); // convert ids to a list of GUIDs List<IPSGuid> ids = new ArrayList<IPSGuid>(); for (long id : request.getId()) ids.add(new PSDesignGuid(id)); IPSUiDesignWs uiws = PSUiWsLocator.getUiDesignWebservice(); PSViewDef[] result = null; try { List<com.percussion.cms.objectstore.PSSearch> views = uiws .loadViews(ids, request.getLock(), request .getOverrideLock(), session, user); result = (PSViewDef[]) convert(PSViewDef[].class, views); } catch (IllegalArgumentException e) { handleInvalidContract(e, service); } catch (RuntimeException e) { handleRuntimeException(e, service); } catch (PSErrorResultsException e) { handleErrorResultsException(e, service); } return result; } /* * (non-Javadoc) * * @see UiDesign#saveActions(SaveActionsRequest) */ @SuppressWarnings("unchecked") public void saveActions(SaveActionsRequest saveActionsRequest) throws RemoteException, PSErrorsFault, PSInvalidSessionFault, PSContractViolationFault, PSNotAuthorizedFault { final String serviceName = "saveActions"; String session = authenticate(); String user = getRemoteUser(); try { List<PSAction> actions = (List<PSAction>) convert(List.class, saveActionsRequest.getPSAction()); IPSUiDesignWs uiws = PSUiWsLocator.getUiDesignWebservice(); uiws.saveActions(actions, saveActionsRequest.getRelease() .booleanValue(), session, user); } catch (PSErrorsException e) { handleErrorsException(e, serviceName); } catch (RuntimeException e) { handleRuntimeException(e, serviceName); } } /* * (non-Javadoc) * * @see UiDesign#saveDisplayFormats(SaveDisplayFormatsRequest) */ @SuppressWarnings("unchecked") public void saveDisplayFormats(SaveDisplayFormatsRequest request) throws RemoteException, PSErrorsFault, PSInvalidSessionFault, PSContractViolationFault, PSNotAuthorizedFault { final String serviceName = "saveDisplayFormats"; String session = authenticate(); String user = getRemoteUser(); try { List<com.percussion.cms.objectstore.PSDisplayFormat> dspFormats = (List<com.percussion.cms.objectstore.PSDisplayFormat>) convert( List.class, request.getPSDisplayFormat()); IPSUiDesignWs uiws = PSUiWsLocator.getUiDesignWebservice(); uiws.saveDisplayFormats(dspFormats, request.getRelease().booleanValue(), session, user); } catch (PSErrorsException e) { handleErrorsException(e, serviceName); } catch (RuntimeException e) { handleRuntimeException(e, serviceName); } } /* * (non-Javadoc) * * @see UiDesign#saveSearches(SaveSearchesRequest) */ @SuppressWarnings("unchecked") public void saveSearches(SaveSearchesRequest saveSearchesRequest) throws RemoteException, PSErrorsFault, PSInvalidSessionFault, PSContractViolationFault, PSNotAuthorizedFault { final String serviceName = "saveSearches"; String session = authenticate(); String user = getRemoteUser(); try { List<PSSearch> searches = (List<PSSearch>) convert(List.class, saveSearchesRequest.getPSSearchDef()); IPSUiDesignWs uiws = PSUiWsLocator.getUiDesignWebservice(); uiws.saveSearches(searches, saveSearchesRequest.getRelease() .booleanValue(), session, user); } catch (PSErrorsException e) { handleErrorsException(e, serviceName); } catch (RuntimeException e) { handleRuntimeException(e, serviceName); } } /* * (non-Javadoc) * * @see UiDesign#saveViews(SaveViewsRequest) */ @SuppressWarnings("unchecked") public void saveViews(SaveViewsRequest saveViewsRequest) throws RemoteException, PSErrorsFault, PSInvalidSessionFault, PSContractViolationFault, PSNotAuthorizedFault { final String serviceName = "saveViews"; String session = authenticate(); String user = getRemoteUser(); try { List<PSSearch> searches = (List<PSSearch>) convert(List.class, saveViewsRequest.getPSViewDef()); IPSUiDesignWs uiws = PSUiWsLocator.getUiDesignWebservice(); uiws.saveViews(searches, saveViewsRequest.getRelease() .booleanValue(), session, user); } catch (PSErrorsException e) { handleErrorsException(e, serviceName); } catch (RuntimeException e) { handleRuntimeException(e, serviceName); } } /* * (non-Javadoc) * * @see UiDesign#createHierarchyNodes(CreateHierarchyNodesRequest) */ @SuppressWarnings("unchecked") public PSHierarchyNode[] createHierarchyNodes( CreateHierarchyNodesRequest createHierarchyNodesRequest) throws RemoteException, PSInvalidSessionFault, PSContractViolationFault, PSNotAuthorizedFault { final String serviceName = "createHierarchyNodes"; try { String session = authenticate(); String user = getRemoteUser(); IPSUiDesignWs service = PSUiWsLocator.getUiDesignWebservice(); String[] names = createHierarchyNodesRequest.getName(); List<IPSGuid> parents = new ArrayList<IPSGuid>(); for (long parent : createHierarchyNodesRequest.getParentId()) parents.add(parent == 0 ? null : new PSDesignGuid(parent)); List<com.percussion.services.ui.data.PSHierarchyNode.NodeType> types = new ArrayList<com.percussion.services.ui.data.PSHierarchyNode.NodeType>(); for (CreateHierarchyNodesRequestType type : createHierarchyNodesRequest.getType()) types.add( (com.percussion.services.ui.data.PSHierarchyNode.NodeType) convert( com.percussion.services.ui.data.PSHierarchyNode.NodeType.class, type)); return (PSHierarchyNode[]) convert(PSHierarchyNode[].class, service.createHierarchyNodes(Arrays.asList(names), parents, types, session, user)); } catch (IllegalArgumentException e) { handleInvalidContract(e, serviceName); } catch (RuntimeException e) { handleRuntimeException(e, serviceName); } catch (PSUiException e) { // this should never happen throw new RemoteException(PSExceptionUtils.getMessageForLog(e)); } // will never get here return null; } /* * (non-Javadoc) * * @see UiDesign#deleteHierarchyNodes(DeleteHierarchyNodesRequest) */ public void deleteHierarchyNodes( DeleteHierarchyNodesRequest deleteHierarchyNodesRequest) throws RemoteException, PSInvalidSessionFault, PSErrorsFault, PSContractViolationFault, PSNotAuthorizedFault { final String serviceName = "deleteHierarchyNodes"; try { String session = authenticate(); String user = getRemoteUser(); IPSUiDesignWs service = PSUiWsLocator.getUiDesignWebservice(); List<IPSGuid> ids = PSGuidUtils.toGuidList( deleteHierarchyNodesRequest.getId(), PSTypeEnum.HIERARCHY_NODE); boolean ignoreDependencies = extractBooleanValue( deleteHierarchyNodesRequest.getIgnoreDependencies(), false); service.deleteHierarchyNodes(ids, ignoreDependencies, session, user); } catch (IllegalArgumentException e) { handleInvalidContract(e, serviceName); } catch (PSErrorsException e) { handleErrorsException(e, serviceName); } catch (RuntimeException e) { handleRuntimeException(e, serviceName); } } /* * (non-Javadoc) * * @see UiDesign#findHierarchyNodes(FindHierarchyNodesRequest) */ public PSObjectSummary[] findHierarchyNodes( FindHierarchyNodesRequest findHierarchyNodesRequest) throws RemoteException, PSInvalidSessionFault, PSContractViolationFault { final String serviceName = "findHierarchyNodes"; try { authenticate(); IPSUiDesignWs service = PSUiWsLocator.getUiDesignWebservice(); com.percussion.services.ui.data.PSHierarchyNode.NodeType type = null; if (findHierarchyNodesRequest.getType() != null) { type = (com.percussion.services.ui.data.PSHierarchyNode.NodeType) convert( com.percussion.services.ui.data.PSHierarchyNode.NodeType.class, findHierarchyNodesRequest.getType()); } List summaries = service.findHierarchyNodes( findHierarchyNodesRequest.getPath(), type); return (PSObjectSummary[]) convert(PSObjectSummary[].class, summaries); } catch (IllegalArgumentException e) { handleInvalidContract(e, serviceName); return null; // never here, used to turn off compiling error } } /* * (non-Javadoc) * * @see UiDesign#getChildren(GetChildrenRequest) */ public long[] getChildren(GetChildrenRequest getChildrenRequest) throws RemoteException, PSInvalidSessionFault, PSContractViolationFault { final String serviceName = "getChildren"; try { authenticate(); IPSUiDesignWs service = PSUiWsLocator.getUiDesignWebservice(); IPSGuid parentId = null; if (getChildrenRequest.getId() != 0) parentId = new PSDesignGuid(getChildrenRequest.getId()); List<IPSGuid> children = service.getChildren(parentId); return PSGuidUtils.toLongArray(children); } catch (IllegalArgumentException e) { handleInvalidContract(e, serviceName); return null; // never here, used to turn off compiling error } } /* * (non-Javadoc) * * @see UiDesign#idsToPaths(long[]) */ public String[] idsToPaths(long[] idsToPathsRequest) throws RemoteException, PSInvalidSessionFault, PSContractViolationFault, PSErrorResultsFault { final String serviceName = "idsToPaths"; try { authenticate(); IPSUiDesignWs service = PSUiWsLocator.getUiDesignWebservice(); if (idsToPathsRequest == null) throw new IllegalArgumentException("ids cannot be null"); List<String> paths = service.idsToPaths( PSGuidUtils.toGuidList(idsToPathsRequest)); return paths.toArray(new String[paths.size()]); } catch (IllegalArgumentException e) { handleInvalidContract(e, serviceName); } catch (PSErrorResultsException e) { handleErrorResultsException(e, serviceName); } return null; // never here, used to turn off compiling error } /* * (non-Javadoc) * * @see UiDesign#loadHierarchyNodes(LoadHierarchyNodesRequest) */ public PSHierarchyNode[] loadHierarchyNodes( LoadHierarchyNodesRequest loadHierarchyNodesRequest) throws RemoteException, PSErrorResultsFault, PSInvalidSessionFault, PSContractViolationFault, PSNotAuthorizedFault { final String serviceName = "loadHierarchyNodes"; try { String session = authenticate(); String user = getRemoteUser(); IPSUiDesignWs service = PSUiWsLocator.getUiDesignWebservice(); List<IPSGuid> ids = PSGuidUtils.toGuidList( loadHierarchyNodesRequest.getId(), PSTypeEnum.HIERARCHY_NODE); boolean lock = extractBooleanValue( loadHierarchyNodesRequest.getLock(), false); boolean overrideLock = extractBooleanValue( loadHierarchyNodesRequest.getOverrideLock(), false); List nodes = service.loadHierachyNodes(ids, lock, overrideLock, session, user); return (PSHierarchyNode[]) convert(PSHierarchyNode[].class, nodes); } catch (IllegalArgumentException e) { handleInvalidContract(e, serviceName); } catch (RuntimeException e) { handleRuntimeException(e, serviceName); } catch (PSErrorResultsException e) { handleErrorResultsException(e, serviceName); } return null; // never here, used to turn off compiling error } /* * (non-Javadoc) * * @see UiDesign#moveChildren(MoveChildrenRequest) */ public void moveChildren(MoveChildrenRequest moveChildrenRequest) throws RemoteException, PSInvalidSessionFault, PSContractViolationFault { final String serviceName = "moveChildren"; try { authenticate(); IPSUiDesignWs service = PSUiWsLocator.getUiDesignWebservice(); IPSGuid sourceId = new PSDesignGuid( moveChildrenRequest.getSourceId()); IPSGuid targetId = new PSDesignGuid( moveChildrenRequest.getTargetId()); List<IPSGuid> children = PSGuidUtils.toGuidList( moveChildrenRequest.getId()); service.moveChildren(sourceId, targetId, children); } catch (IllegalArgumentException e) { handleInvalidContract(e, serviceName); } } /* * (non-Javadoc) * * @see UiDesign#pathsToIds(String[]) */ public long[][] pathsToIds(String[] pathsToIdsRequest) throws RemoteException, PSInvalidSessionFault, PSContractViolationFault, PSErrorResultsFault { final String serviceName = "pathsToIds"; try { authenticate(); IPSUiDesignWs service = PSUiWsLocator.getUiDesignWebservice(); if (pathsToIdsRequest == null) throw new IllegalArgumentException("paths cannot be null"); List<List<IPSGuid>> idsList = service.pathsToIds( Arrays.asList(pathsToIdsRequest)); long[][] idsArray = new long[idsList.size()][0]; int index = 0; for (List<IPSGuid> ids : idsList) idsArray[index++] = PSGuidUtils.toLongArray(ids); return idsArray; } catch (IllegalArgumentException e) { handleInvalidContract(e, serviceName); } catch (PSErrorException e) { throw new RemoteException(PSExceptionUtils.getMessageForLog(e)); } return null; // never here, used to turn off compiling error } /* * (non-Javadoc) * * @see UiDesign#removeChildren(RemoveChildrenRequest) */ public void removeChildren(RemoveChildrenRequest removeChildrenRequest) throws RemoteException, PSInvalidSessionFault, PSContractViolationFault { final String serviceName = "removeChildren"; try { authenticate(); IPSUiDesignWs service = PSUiWsLocator.getUiDesignWebservice(); IPSGuid parentId = null; if (removeChildrenRequest.getParentId() != 0) parentId = new PSDesignGuid(removeChildrenRequest.getParentId()); List<IPSGuid> children = PSGuidUtils.toGuidList( removeChildrenRequest.getId()); service.removeChildren(parentId, children); } catch (IllegalArgumentException e) { handleInvalidContract(e, serviceName); } } /* * (non-Javadoc) * * @see UiDesign#saveHierarchyNodes(SaveHierarchyNodesRequest) */ @SuppressWarnings("unchecked") public void saveHierarchyNodes( SaveHierarchyNodesRequest saveHierarchyNodesRequest) throws RemoteException, PSErrorsFault, PSInvalidSessionFault, PSContractViolationFault, PSNotAuthorizedFault { final String serviceName = "saveHierarchyNodes"; try { String session = authenticate(); String user = getRemoteUser(); IPSUiDesignWs service = PSUiWsLocator.getUiDesignWebservice(); List nodes = (List) convert(List.class, saveHierarchyNodesRequest.getPSHierarchyNode()); boolean release = extractBooleanValue( saveHierarchyNodesRequest.getRelease(), true); service.saveHierarchyNodes(nodes, release, session, user); } catch (IllegalArgumentException e) { handleInvalidContract(e, serviceName); } catch (PSErrorsException e) { handleErrorsException(e, serviceName); } catch (RuntimeException e) { handleRuntimeException(e, serviceName); } } }
true
92a94d3b788f285bff44146bc241cc9fa7ef518e
Java
xiaoronggh/smileblog
/src/main/java/com/shxzhlxrr/code/article/service/impl/CommentService.java
UTF-8
4,132
2.359375
2
[]
no_license
package com.shxzhlxrr.code.article.service.impl; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.shxzhlxrr.code.article.dao.ArticleDao; import com.shxzhlxrr.code.article.dao.CommentDao; import com.shxzhlxrr.code.article.model.CommentModel; import com.shxzhlxrr.code.article.model.CommentUserModel; import com.shxzhlxrr.code.article.service.ICommentService; import com.shxzhlxrr.code.user.model.ReturnModel; import com.shxzhlxrr.spring.config.BaseService; import com.shxzhlxrr.util.md5.Md5Util; import com.shxzhlxrr.util.reg.RegUtil; import com.shxzhlxrr.util.string.StringUtil; /** * * @author zxr <br/> * 2017年5月3日 下午2:20:18 <br/> * @description */ @Service @Transactional public class CommentService extends BaseService implements ICommentService { @Autowired private CommentDao commentDao; @Autowired private ArticleDao articleDao; @Override public ReturnModel comment(Map<String, Object> param) { // TODO 判断用户是否已经存在,根据用户名进行判断 // 用户名是唯一的,如果用户名相同邮件不同时进行覆盖操作 String msg = validateInfo(param); if (msg != null) {// 校验没通过,直接返回 return new ReturnModel(false, msg); } msg = isSaveUser(param); if (msg == null) { // 保存用户信息 CommentUserModel user = saveCommentUser(param); // 保存用户的评论信息 param.put("user_id", user.getId()); } else if ("same".equals(msg)) { // 什么都不做 } else { return new ReturnModel(false, msg); } saveComment(param); // 更新评论次数 updateCommentNum(param); return new ReturnModel(true, "评论发表成功,请刷新查看。"); } private void updateCommentNum(Map<String, Object> param) { String article_id = StringUtil.getVal(param, "article_id"); param.put("id", article_id); Map<String, Object> articleMap = articleDao.queryArticle(param); int comment_num = Integer.valueOf(StringUtil.getVal(articleMap, "comment_num")); comment_num++; articleDao.updateCommentNum(comment_num, article_id); } private String validateInfo(Map<String, Object> param) { if (StringUtil.isNull(param.get("user_name"))) { return "用户名不能为空!"; } if (StringUtil.isNull(param.get("email"))) { return "邮箱不能为空!"; } if (StringUtil.isNull(param.get("comment_content"))) { return "评论内容不能为空!"; } if (!RegUtil.isEmail(StringUtil.getVal(param, "email"))) { return "请输入正确的邮箱!"; } return null; } private CommentModel saveComment(Map<String, Object> param) { CommentModel comment = new CommentModel(); comment.setArticle_id(StringUtil.getVal(param, "article_id")); comment.setUser_id(StringUtil.getVal(param, "user_id")); comment.setComment_content(StringUtil.getVal(param, "comment_content")); commentDao.saveComment(comment); return comment; } private CommentUserModel saveCommentUser(Map<String, Object> param) { CommentUserModel user = new CommentUserModel(); user.setUser_name(StringUtil.getVal(param, "user_name")); user.setEmail(StringUtil.getVal(param, "email")); String pwd = StringUtil.getVal(param, "password"); pwd = Md5Util.getPwdMd5(pwd); user.setPassword(pwd); commentDao.saveCommentUser(user); return user; } /** * 判断是否保存用户 * * @param param * @return null ,未查询到用户,尽心保存;same 用户已经存在,不保存;否则,用户已经使用 */ private String isSaveUser(Map<String, Object> param) { Map<String, Object> userMap = commentDao.queryCommentUserByName(StringUtil.getVal(param, "user_name")); if (!userMap.isEmpty()) { String user_pwd = StringUtil.getVal(param, "password"); user_pwd = Md5Util.getPwdMd5(user_pwd); if (!user_pwd.equals(userMap.get("password"))) { return "该用户名已经被使用,请重新输入!"; } else { param.put("user_id", userMap.get("id")); return "same"; } } return null; } }
true
9c8d69ccf98a732b10a7330812328bd0efc535e3
Java
PolinaDurdeva/testFrameworkExample
/src/test/java/com/qandoo/DriverHolder.java
UTF-8
676
2.59375
3
[]
no_license
package com.qandoo; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; /** * Contains the web driver singleton used in all tests. */ public class DriverHolder { private static WebDriver driver; /** * Gets the current driver * @return current driver instance */ public static WebDriver getDriver() { return driver; } /** * Replaces current driver with new driver instance */ public static void initializeDriver() { driver = new ChromeDriver(); } /** * Closes the current driver */ public static void closeDriver(){ driver.close(); } }
true
9c66fc0752d9c78480f5e2689233f67e1ec61380
Java
dnyaneshrt/textextract
/app/src/main/java/com/example/textread/DbHelper.java
UTF-8
2,262
2.46875
2
[]
no_license
package com.example.textread; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.util.Log; import android.widget.Toast; import androidx.annotation.Nullable; public class DbHelper extends SQLiteOpenHelper { public static final String DATABASE_NAME = "myapp.db"; public static final int DB_VERSION = 1; public static final String TABLE_NAME = "Registration"; public static final String Name = "name"; public static final String Email = "email"; public static final String Password = "password"; public static final String CREATE_TABLE_USERS = "CREATE TABLE " + TABLE_NAME + "(" // + Name + " TEXT PRIMARY KEY AUTOINCREMENT," + Email + " TEXT," + Password + " TEXT);"; private static final String TAG = "login"; public DbHelper(Context context) { super(context, DATABASE_NAME, null, DB_VERSION); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL(CREATE_TABLE_USERS); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { db.execSQL("DROP TABLE IF EXISTS " +TABLE_NAME); onCreate(db); } public void addUser(String name, String email, String password) { SQLiteDatabase db = this.getWritableDatabase(); ContentValues values = new ContentValues(); values.put(Name,name); values.put(Email, email); values.put(Password, password); long id = db.insert(TABLE_NAME, null, values); db.close(); Log.d(TAG, "user inserted" + id); } public boolean getUser(String email, String pass){ //HashMap<String, String> user = new HashMap<String, String>(); String selectQuery = "select * from " + TABLE_NAME+ " where " + Email + " = " + "'"+email+"'" + " and " + Password + " = " + "'"+pass+"'"; SQLiteDatabase db = this.getReadableDatabase(); Cursor cursor = db.rawQuery(selectQuery, null); // Move to first row cursor.moveToFirst(); if (cursor.getCount() > 0) { return true; } cursor.close(); db.close(); return false; } }
true
97f4056eeaaa54319efea81391dbc348e4cfac55
Java
DragonHeir/Level_4
/src/HospitalExercise/Zombie.java
UTF-8
220
2.203125
2
[]
no_license
package HospitalExercise; public class Zombie { public Zombie(String string) { // TODO Auto-generated constructor stub } public String getTimeOfDeath() { // TODO Auto-generated method stub return null; } }
true
5ab45ae0a6c69b2cf99735aeec94990ba38b0080
Java
Aguayo91/PruebasVersion
/Aventones/src/main/java/com/sociomas/aventones/UI/Activities/Carros/CarPresenter.java
UTF-8
418
1.617188
2
[]
no_license
package com.sociomas.aventones.UI.Activities.Carros; import android.content.Intent; import com.sociomas.core.MVP.BasePresenter; import com.sociomas.core.WebService.Model.Request.Alta.Vehiculo; /** * Created by oemy9 on 05/10/2017. */ public interface CarPresenter extends BasePresenter { void agregarEditarAuto(Vehiculo selectedVehiculo,boolean navegarPreferencias); void obtenerAutosListadoAsync(); }
true
7a00000206523f8f2666b6882fefa38aa7083873
Java
hadyehab34/AI
/EightPuzzle.java
UTF-8
12,136
3.765625
4
[]
no_license
import java.util.*; import java.util.LinkedList; import java.util.Stack; import java.util.ArrayList; import java.util.PriorityQueue; public class EightPuzzle { static class node { List<node> children = new ArrayList<>(); int []puzzle = new int [9]; node parent; int x = 0 ; //index of zero tile (movable tile) int heuristicCost; int finalCost; // f(n) = h(n) + g(n) public node (int []p) { SetPuzzle(p); heuristicCost = Search.heuristic(p); finalCost = heuristicCost; } // method finds g(n) the number of moves that have been made from the root to the given node to get the cost // to calculate f(n) by counting the number of parents of the given node. public static int FinalCost (node n){ node temp = n; int cost = 0; while (temp.parent != null){ cost = cost + 1; temp = temp.parent; } return cost; } public void SetPuzzle (int[]puzzle) { System.arraycopy(puzzle, 0, this.puzzle, 0, 9); } public void expandNodeDFS() { //loop to find index of zero tile (movable tile) for (int i = 0; i < 9; i++) { if (puzzle[i] == 0) x = i;// x is index of zero tile } MoveToRight(puzzle,x); MoveToDown(puzzle,x); MoveToLeft(puzzle,x); MoveToUp(puzzle,x); } public void expandNode() { for (int i = 0; i < 9; i++ ) { if (puzzle[i] == 0) x = i; } MoveToUp(puzzle,x); MoveToLeft(puzzle,x); MoveToDown(puzzle,x); MoveToRight(puzzle,x); } public void MoveToUp(int []puzzle,int i) { if (i - 3 >=0) { // initializing new array to represent next move int[] upPuzzle = new int[9]; CopyPuzzle(upPuzzle,puzzle); // swapping zero tile into new position int temp = upPuzzle[i-3]; upPuzzle[i-3] = upPuzzle[i]; upPuzzle[i] = temp; // initializing new node for next move node child = new node(upPuzzle); children.add(child); } } public void MoveToDown(int []p,int i) { if (i + 3 < 9) { int[] downPuzzle = new int[9]; CopyPuzzle(downPuzzle,p); int temp = downPuzzle[i+3]; downPuzzle[i+3] = downPuzzle[i]; downPuzzle[i] = temp; node child = new node(downPuzzle); children.add(child); } } public void MoveToLeft(int []p,int i) { if ((i % 3) > 0) { int[] leftPuzzle = new int[9]; CopyPuzzle(leftPuzzle,p); int temp = leftPuzzle[i-1]; leftPuzzle[i-1] = leftPuzzle[i]; leftPuzzle[i] = temp; node child = new node(leftPuzzle); children.add(child); } } public void MoveToRight(int []p,int i) { if ((i % 3) < (3 - 1)) { int[] rightPuzzle = new int[9]; CopyPuzzle(rightPuzzle,p); int temp = rightPuzzle[i+1]; rightPuzzle[i+1] = rightPuzzle[i]; rightPuzzle[i] = temp; node child = new node(rightPuzzle); children.add(child); } } // method to copy an array into another public void CopyPuzzle(int[]a,int[]b) { System.arraycopy(b, 0, a, 0, 9); } // method to print puzzle array in 3x3 board look public void printPuzzle () { System.out.println(); int m = 0; for (int i = 0; i < 3; i++ ) { for (int j = 0; j < 3; j++ ) { System.out.print(puzzle[m]+" "); m++; } System.out.println(); } } public boolean isSamePuzzle(int[]p) { boolean samePuzzle = true; for (int i = 0; i < 9; i++ ) { if (puzzle[i] != p[i]) { samePuzzle = false; break; } } return samePuzzle; } public boolean GoalTest() { boolean isGoal = true; int m = puzzle[0]; for (int i = 1;i<9;i++) { if(m>puzzle[i]) isGoal = false; m = puzzle[i]; } return isGoal; } } // Comparator to use in the priority queue to make the order based on the final cost f(n) = h(n) + g(n) . static class boardComparator implements Comparator<EightPuzzle.node> { public int compare (EightPuzzle.node n1 ,EightPuzzle.node n2) { if (n1.finalCost > n2.finalCost) return 1; else if (n1.finalCost < n2.finalCost) return -1; return 0; } } static class Search { public static void AStar(EightPuzzle.node root) { PriorityQueue<EightPuzzle.node> frontier = new PriorityQueue<>(100, new boardComparator()); Queue<EightPuzzle.node> explored = new LinkedList<>(); int c = 0; frontier.add(root); while (!frontier.isEmpty()) { EightPuzzle.node current = frontier.poll(); explored.add(current); current.printPuzzle(); c++; if (current.GoalTest()){ System.out.println("number of moves : "+c); return;} current.expandNode(); for (int i = 0; i < current.children.size(); i++) { EightPuzzle.node currentChild = current.children.get(i); currentChild.parent = current; currentChild.finalCost += node.FinalCost(currentChild); if (!containsPQueue(frontier, currentChild) && !containsQueue(explored, currentChild)) { frontier.add(currentChild); } else if (frontier.contains(currentChild)){ node t = getSameNode(frontier , currentChild); if (currentChild.finalCost < t.finalCost){ frontier.remove(t); frontier.add(currentChild); } } } } } public static int heuristic (int[] n) { int[] goal = {0, 1, 2, 3, 4, 5, 6, 7, 8}; int h = 0; for (int i = 0; i < 9; i++) { int j = getArrayIndex(n,i); if (j != goal[i]) { h += Math.abs((j / 3) - (i / 3)) + Math.abs(((j % 3) - (i % 3))); } } return h; } public static int getArrayIndex(int[] arr, int value) { int k = 0; for (int i = 0; i < arr.length; i++) { if (arr[i] == value) { k = i; break; } } return k; } public static EightPuzzle.node getSameNode (PriorityQueue<node> front , node n) { PriorityQueue <EightPuzzle.node> temp = new PriorityQueue<>(front); // loop that compares each element in Queue to the given node for (int i = 0; i < front.size(); i++) { if (Objects.requireNonNull(temp.peek()).isSamePuzzle(n.puzzle)) return temp.poll(); else temp.poll(); } return n; } public static void BFS (node root) { Queue<node> frontier = new LinkedList<>(); Queue<node> explored = new LinkedList<>(); frontier.add(root); while (!frontier.isEmpty()) { node current = frontier.poll(); explored.add(current); current.printPuzzle(); if (current.GoalTest()) return; current.expandNode(); for (int i = 0; i < current.children.size(); i++) { node currentChild = current.children.get(i); if( !containsQueue(frontier,currentChild) && !containsQueue(explored,currentChild) ) frontier.add(currentChild); } } } public static void DFS (node root) { Stack<node> frontier = new Stack<>(); Queue<node> explored = new LinkedList<>(); frontier.push(root); while (!frontier.isEmpty()) { node current = frontier.pop(); explored.add(current); current.printPuzzle(); if (current.GoalTest()) return; current.expandNodeDFS(); for (int i = 0; i < current.children.size(); i++) { node currentChild = current.children.get(i); if(!containsStack(frontier,currentChild) && !containsQueue(explored,currentChild)) frontier.push(currentChild); } } } // method checks if a given node's array puzzle is in a given Priority Queue of nodes public static boolean containsPQueue(PriorityQueue<EightPuzzle.node> front, EightPuzzle.node c) { boolean contain = false; PriorityQueue <EightPuzzle.node> temp = new PriorityQueue<>(front); // loop that compares each element in Queue to the given node for (int i = 0; i < front.size(); i++) { if (Objects.requireNonNull(temp.poll()).isSamePuzzle(c.puzzle)) contain = true; } return contain; } // method checks if a given node's array puzzle is in a given Stack of nodes public static boolean containsStack (Stack<node> front,node c) { boolean contain = false; // loop that compares each element in Stack to the given node for (int i = 0 ; i < front.size() ; i++) { if (front.get(i).isSamePuzzle(c.puzzle)) contain = true; } return contain; } // method checks if a given node's array puzzle is in a given Queue of nodes public static boolean containsQueue (Queue<node> front,node c) { boolean contain = false; List<node> Queue = (List) front; // casting given queue to a list to traverse it by index // loop that compares each element in Queue to the given node for (int i = 0 ; i < front.size() ; i++) { if (Queue.get(i).isSamePuzzle(c.puzzle)) contain = true; } return contain; } public static void main (String[]args) { int [] puzzle3 = {1,2,3,0,4,5,6,7,8}; node initialNode3 = new node(puzzle3); System.out.println("A star :"+"\n"); double start3 = System.currentTimeMillis(); BFS(initialNode3); double end3 = System.currentTimeMillis(); System.out.println("\n"+"Runtime : " +(end3 - start3)+" ms"+"\n"); } } }
true
3426a5d54a3498afbb1f8578a92af62fe6ea845d
Java
ldabul/TGDBClient
/src/main/java/net/tgdb/config/TGDBConfig.java
UTF-8
2,779
2.046875
2
[ "MIT" ]
permissive
package net.tgdb.config; import java.util.ArrayList; import java.util.List; import javax.annotation.Resource; import net.tgdb.client.TGDBClient; import net.tgdb.client.TGDBClientImpl; import org.apache.http.client.config.RequestConfig; import org.apache.http.impl.client.HttpClientBuilder; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; import org.springframework.core.env.Environment; import org.springframework.http.client.ClientHttpRequestFactory; import org.springframework.http.client.HttpComponentsClientHttpRequestFactory; import org.springframework.http.converter.HttpMessageConverter; import org.springframework.http.converter.xml.Jaxb2RootElementHttpMessageConverter; import org.springframework.web.client.RestTemplate; /** * @author Ldabul * @version 0.1 - 06.03.2015 */ @Configuration @ComponentScan("net.tgdb") @PropertySource(value = "classpath:tgdb.properties", ignoreResourceNotFound = true) public class TGDBConfig { private static final int DEFAULT_TIMEOUT = 30 * 1000; @Resource private Environment env; @Bean public TGDBClient tgdbClient() { TGDBClientImpl tgdbClient = new TGDBClientImpl(); tgdbClient.setRestTemplate(getRestTemplate()); return tgdbClient; } /** * Creates rest template for TGDB client * * @return */ private RestTemplate getRestTemplate() { RestTemplate restTemplate = new RestTemplate(); restTemplate.setRequestFactory(getRequestFactory()); restTemplate.setMessageConverters(getMessageConverters()); return restTemplate; } /** * Creates request factory for rest template * * @return */ private ClientHttpRequestFactory getRequestFactory() { RequestConfig.Builder builder = RequestConfig.custom(); builder.setConnectTimeout(env.getProperty("tgdb.connectTimeout", Integer.class, DEFAULT_TIMEOUT)); builder.setSocketTimeout(env.getProperty("tgdb.connectTimeout", Integer.class, DEFAULT_TIMEOUT)); builder.setConnectionRequestTimeout(env.getProperty("tgdb.readTimeout", Integer.class, DEFAULT_TIMEOUT)); HttpClientBuilder httpClientBuilder = HttpClientBuilder.create(); httpClientBuilder.setDefaultRequestConfig(builder.build()); return new HttpComponentsClientHttpRequestFactory(httpClientBuilder.build()); } /** * Creates message converters for rest template * * @return */ private List<HttpMessageConverter<?>> getMessageConverters() { List<HttpMessageConverter<?>> messageConverter = new ArrayList<>(); messageConverter.add(new Jaxb2RootElementHttpMessageConverter()); return messageConverter; } }
true
3744ec245633a91a9a8edb08999c073d3680dbd8
Java
MmahdiM79/Pentago
/Rules.java
UTF-8
7,576
3.484375
3
[]
no_license
import java.util.Scanner; /** * This class is Monitoring on the enforcement of game rules * * @author Mohammad Mahdi Malmasi * @version 0.1.0 */ public class Rules { // this variable hold the winner of the game private static Player winner = null; /* Mehtods */ /** * Set the winner of the game * @param winner : the winner to set */ public static void setWinner(Player winner) { Rules.winner = winner; } /** * @return the winner */ public static Player getWinner() { return winner; } /** * This method check the player choosen block * * @param gameBoard : the board of the game * @param y : the y of the choosen block * @param x : the x of the choosen block * * @return {@code true} if and only if the choosen block is empty. * otherwise {@code false}. */ public static boolean isPlayerSelectValid(Board gameBoard, int y, int x) { if (gameBoard.getMainBoardBlockKind(y, x) == 0) return true; // else return false; } /** * This method check that the game is ended or not * * @return {@code ture} if the game was ended */ public static boolean isGameEnded() { if (winner == null) return false; // else return true; } /** * This method put the player color to his/her choosen block * * @param gameBoard : the board of the game * @param y : the y of the choosen block * @param x : the x of the choosen block * @param player : the player */ public static void applyPlayerSelect(Board gameBoard, int y, int x, Player player) { gameBoard.setBoard(y, x, player.getPlayerID()); } /** * This method search for a sequence of lenght 5 * * * @param gameBoard : the board of the game * @param player : the player to check * * @return : {@code true} if the given player has built a sequence of lenght 5 */ public static boolean isWinner(Board gameBoard, Player player) { Player holdLastWinner = winner; winner = player; if (checkSequenceHorizontal(gameBoard, 0, player.getPlayerID())) return true; if (checkSequenceHorizontal(gameBoard, 1, player.getPlayerID())) return true; if (checkSequenceVertical(gameBoard, 0, player.getPlayerID())) return true; if (checkSequenceVertical(gameBoard, 1, player.getPlayerID())) return true; if (checkSequenceDiagonal(gameBoard, true, player.getPlayerID())) return true; if (checkSequenceDiagonal(gameBoard, false, player.getPlayerID())) return true; winner = holdLastWinner; return false; } /** * This method find the winner of the game * * @param gameBoard : the board of the game * @param player1 : player one * @param player2 : player two * @param finish : inputs source */ public static void WINNER(Board gameBoard, Player player1, Player player2, Scanner finish) { if (isWinner(gameBoard, player1) && isWinner(gameBoard, player2)) Printer.printDraw(finish); else Printer.printWinner(winner, finish); } /** * This method reset the winner player for new game */ public static void reset() { winner = null; } // this method search for a sequence lenght of 5 in lines private static boolean checkSequenceHorizontal(Board gameBoard, int first, int kind) { int len = 0; for (int j = 0; j < gameBoard.getMainBoardY(); j++) { for (int i = 0+first; i < gameBoard.getMainBoardX()-1+first; i++) { if (gameBoard.getMainBoardBlockKind(j, i) == kind) len++; else break; } if (len == 5) return true; len = 0; } return false; } // this method search for a sequence lenght of 5 in columns private static boolean checkSequenceVertical(Board gameBoard, int first, int kind) { int len = 0; for (int i = 0; i < gameBoard.getMainBoardX(); i++) { for (int j = 0+first; j < gameBoard.getMainBoardY()-1+first; j++) { if (gameBoard.getMainBoardBlockKind(j, i) == kind) len++; else break; } if (len == 5) return true; len = 0; } return false; } // this method search for a sequence lenght of 5 in diameters private static boolean checkSequenceDiagonal(Board gameBoard, boolean whichDiameter, int kind) { int len = 0; if (whichDiameter) { for (int j = 4, i = 0; i < 5 && j >= 0; j--, i++) { if (gameBoard.getMainBoardBlockKind(j, i) == kind) len++; else break; } if (len == 5) return true; len = 0; for (int j = 5, i = 0; i < 5 && j > 0; j--, i++) { if (gameBoard.getMainBoardBlockKind(j, i) == kind) len++; else break; } if (len == 5) return true; len = 0; for (int j = 4, i = 1; i < 6 && j >= 0; j--, i++) { if (gameBoard.getMainBoardBlockKind(j, i) == kind) len++; else break; } if (len == 5) return true; len = 0; for (int j = 5, i = 1; i < 6 && j > 0; j--, i++) { if (gameBoard.getMainBoardBlockKind(j, i) == kind) len++; else break; } if (len == 5) return true; } else { len = 0; for (int j = 0, i = 1; i < 6 && j < 6; j++, i++) { if (gameBoard.getMainBoardBlockKind(j, i) == kind) len++; else break; } if (len == 5) return true; len = 0; for (int j = 0, i = 0; i < 5 && j < 5; j++, i++) { if (gameBoard.getMainBoardBlockKind(j, i) == kind) len++; else break; } if (len == 5) return true; len = 0; for (int j = 1, i = 1; i < 6 && j < 6; j++, i++) { if (gameBoard.getMainBoardBlockKind(j, i) == kind) len++; else break; } if (len == 5) return true; len = 0; for (int j = 1, i = 0; i < 5 && j < 6; j++, i++) { if (gameBoard.getMainBoardBlockKind(j, i) == kind) len++; else break; } if (len == 5) return true; } return false; } }
true
d79e00d5febae0baa7f552fc234ccfc7d37d7583
Java
rand0x0m/printer
/src/T.java
UTF-8
2,302
3.046875
3
[]
no_license
import java.util.Arrays; import java.util.List; public class T { public static void main(String[] args) { List<String> list = Arrays.asList("a", "b", "c", "D", "E", "F"); list.stream().peek(System.out::println); // try { // PDDocument document = PDDocument.load(new File("/home/ff/Downloads/VI_EDITOR.pdf")); // PDFRenderer pdfRenderer = new PDFRenderer(document); // pdfRenderer // for (int i=0; i<document.getNumberOfPages(); i++) { // BufferedImage bi = null; // Graphics2D g2d = bi.createGraphics(); // } // // } catch (IOException e) { // e.printStackTrace(); // } // // // // System.exit(0); // PrinterJob job = PrinterJob.getPrinterJob(); // PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet(); // // PageFormat pf = job.pageDialog(aset); // if (pf != null) { // job.setPrintable(new HelloWorldPrinter(), pf); // // if (job.printDialog(aset)) { // try { // job.print(aset); // } catch (PrinterException e) { // e.printStackTrace(); // } // } // } else { // System.out.println("Dialog closed. Exiting"); // } } // // public static class HelloWorldPrinter // implements Printable { // // public int print(Graphics g, PageFormat pf, int page) // throws PrinterException { // // // // // We have only one page, and 'page' // // is zero-based // if (page > 0) { // return NO_SUCH_PAGE; // } // // // User (0,0) is typically outside the // // imageable area, so we must translate // // by the X and Y values in the PageFormat // // to avoid clipping. // Graphics2D g2d = (Graphics2D) g; // g2d.translate(pf.getImageableX(), pf.getImageableY()); // // // Now we perform our rendering // g.drawString("Hello world!", 100, 100); // // // tell the caller that this page is part // // of the printed document // return PAGE_EXISTS; // } // } }
true
37d3d27794cabc533c0fef842009b991616d9b0f
Java
fujaba/mdbda
/org.hahnpro.mdbda.diagrameditor/src/org/mdbda/diagrameditor/diagram/MDBDAPlugableImageProvider.java
UTF-8
3,481
1.929688
2
[ "Apache-2.0" ]
permissive
package org.mdbda.diagrameditor.diagram; import java.util.HashMap; import java.util.HashSet; import org.eclipse.core.runtime.IConfigurationElement; import org.eclipse.core.runtime.IExtensionRegistry; import org.eclipse.core.runtime.Platform; import org.eclipse.graphiti.platform.AbstractExtension; import org.eclipse.graphiti.ui.platform.AbstractImageProvider; import org.eclipse.graphiti.ui.platform.IImageProvider; import org.osgi.framework.Bundle; public class MDBDAPlugableImageProvider extends AbstractExtension implements IImageProvider { HashSet<IImageProvider> plugedImageProvider = new HashSet<IImageProvider>(); HashMap<String, String> imageIdToUrl = new HashMap<String, String>(); static final String PNG16 = "_16.png"; static final String PNG32 = "_32.png"; static final String PNG64 = "_64.png"; static final String ASTRONAUT_URL = "platform:/plugin/org.mdbda.diagrameditor/icon/astronaut"; static final String DATA_URL = "platform:/plugin/org.mdbda.diagrameditor/icon/data29"; static final String FILTER_URL = "platform:/plugin/org.mdbda.diagrameditor/icon/filter13"; static final String GEN_URL = "platform:/plugin/org.mdbda.diagrameditor/icon/gen"; static final String HIERACHICAL_URL = "platform:/plugin/org.mdbda.diagrameditor/icon/hierarchical9"; static final String JOIN_URL = "platform:/plugin/org.mdbda.diagrameditor/icon/join"; static final String SUM_URL = "platform:/plugin/org.mdbda.diagrameditor/icon/spreadsheet1_sum"; public static final String MAIN_ICON = "MDBDA MAIN_ICON"; public static final String FILTER_ICON = "MDBDA FILTER_ICON"; public static final String JOIN_ICON = "MDBDA JOIN_ICON"; public static final String SUMMARIZATION_ICON = "MDBDA SUMMARIZATION_ICON"; public static final String RESSOURCE_ICON = "MDBDA RESSOURCE_ICON"; public static final String STRUCTURE_ICON = "MDBDA STRUCTURE_ICON"; public MDBDAPlugableImageProvider() { super(); IExtensionRegistry reg = Platform.getExtensionRegistry(); IConfigurationElement[] elements = reg.getConfigurationElementsFor("org.mdbda.diagrameditor.imageprovider"); for(IConfigurationElement el : elements){ String imageProviderClass = el.getAttribute("ImageProviderClass"); Bundle bundle = Platform.getBundle(el.getContributor().getName()); try { Class<IImageProvider> ipClazz = (Class<IImageProvider>) bundle.loadClass(imageProviderClass); IImageProvider ip = ipClazz.newInstance(); plugedImageProvider.add(ip); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } } imageIdToUrl.put(MAIN_ICON, ASTRONAUT_URL + PNG16); imageIdToUrl.put(FILTER_ICON, FILTER_URL + PNG16); imageIdToUrl.put(JOIN_ICON, JOIN_URL + PNG16); imageIdToUrl.put(SUMMARIZATION_ICON, SUM_URL + PNG16); imageIdToUrl.put(RESSOURCE_ICON, DATA_URL + PNG16); imageIdToUrl.put(STRUCTURE_ICON, HIERACHICAL_URL + PNG16); } private String pluginId; @Override final public void setPluginId(String pluginId) { this.pluginId = pluginId; } @Override final public String getPluginId() { return this.pluginId; } @Override final public String getImageFilePath(String imageId) { for(IImageProvider ip : plugedImageProvider){ String imageFilePath = ip.getImageFilePath(imageId); if(imageFilePath != null){ return imageFilePath; } } return imageIdToUrl.get(imageId); } }
true
26d9c5a2036a757bc5f5771192438c24a2371385
Java
fpmi-hci2020/pchmi-gr13-r3-emelianovarudkopavliv
/src/main/java/org/phci/core/model/order/OrderDao.java
UTF-8
193
1.742188
2
[]
no_license
package org.phci.core.model.order; import java.util.List; public interface OrderDao { List<Order> get(String email); Order placeOrder(Order order); void cancel(Integer bookId); }
true
b0c1c7efe898d8f6ed2d29c7cb552fe2d724db50
Java
superzoeyian/tongyimall-admin
/高仿小米商城管理后台/src/main/java/com/zty/xiaomiadmin/server/Service/User/UserService.java
UTF-8
258
1.570313
2
[]
no_license
package com.zty.xiaomiadmin.server.Service.User; import com.zty.xiaomiadmin.server.Vo.User.UserResult; import org.apache.ibatis.session.SqlSession; import java.io.IOException; public interface UserService { UserResult getUsers() throws IOException; }
true
6363c3776eed2d66c4f09194066fa3c9d21bbede
Java
bxh7425014/BookCode
/Google.Android.SDK开发范例大全-第1版/CH07/EX07_14/src/irdc/ex07_14/EX07_14.java
BIG5
6,639
2.375
2
[]
no_license
package irdc.ex07_14; import android.app.Activity; import android.graphics.PixelFormat; import android.media.AudioManager; import android.media.MediaPlayer; import android.os.Bundle; import android.util.Log; import android.view.SurfaceHolder; import android.view.SurfaceView; import android.view.View; import android.widget.ImageButton; import android.widget.TextView; import android.widget.Toast; /* Activity@SurfaceHolder.Callback */ public class EX07_14 extends Activity implements SurfaceHolder.Callback { private TextView mTextView01; private static final String TAG = "HIPPO_MediaPlayer"; /* إMediaPlayer */ private MediaPlayer mMediaPlayer01; /* SurfaceView@LayoutWX */ private SurfaceView mSurfaceView01; /* HSurfaceHolderӱSurfaceView */ private SurfaceHolder mSurfaceHolder01; /* |ImageButtonMediaPlayerƥ */ private ImageButton mPlay; private ImageButton mPause; private ImageButton mReset; private ImageButton mStop; /* MediaPlayerȰflag */ private boolean bIsPaused = false; /* MediaPlayerQflag */ private boolean bIsReleased = false; /* N.3gpvɦsbSDdڥؿ */ private String strVideoPath = ""; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); if(!checkSDCard()) { /* UserwSDOХd */ mMakeTextToast ( getResources().getText(R.string.str_err_nosd).toString(), true ); } mTextView01 = (TextView)findViewById(R.id.myTextView1); /* ]wtPixelFormaeUNKNOW */ getWindow().setFormat(PixelFormat.UNKNOWN); /* ôLayoutWSurfaceView */ mSurfaceView01 = (SurfaceView) findViewById(R.id.mSurfaceView1); /* ]wSurfaceHolderLayout SurfaceViewù */ mSurfaceHolder01 = mSurfaceView01.getHolder(); mSurfaceHolder01.addCallback(this); /* vSize176x144 */ mSurfaceHolder01.setFixedSize(176,144); mSurfaceHolder01.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); /* 4ImageButton */ mPlay = (ImageButton) findViewById(R.id.play); mPause = (ImageButton) findViewById(R.id.pause); mReset = (ImageButton) findViewById(R.id.reset); mStop = (ImageButton) findViewById(R.id.stop); /* ]wեμvm */ strVideoPath = "/sdcard/test.3gp"; /* s */ mPlay.setOnClickListener(new ImageButton.OnClickListener() { public void onClick(View view) { /* IsvFunction */ if(checkSDCard()) { playVideo(strVideoPath); } } }); /* Ȱs */ mPause.setOnClickListener(new ImageButton.OnClickListener() { public void onClick(View view) { if(checkSDCard()) { if (mMediaPlayer01 != null) { if(bIsReleased == false) { if(bIsPaused==false) { mMediaPlayer01.pause(); bIsPaused = true; mTextView01.setText(R.string.str_pause); } else if(bIsPaused==true) { mMediaPlayer01.start(); bIsPaused = false; mTextView01.setText(R.string.str_play); } } } } } }); /* ss */ mReset.setOnClickListener(new ImageButton.OnClickListener() { public void onClick(View view) { if(checkSDCard()) { if(bIsReleased == false) { if (mMediaPlayer01 != null) { mMediaPlayer01.seekTo(0); } } } } }); /* פs */ mStop.setOnClickListener(new ImageButton.OnClickListener() { public void onClick(View view) { if(checkSDCard()) { if (mMediaPlayer01 != null) { if(bIsReleased==false) { mMediaPlayer01.stop(); mMediaPlayer01.release(); bIsReleased = true; mTextView01.setText(R.string.str_stop); } } } } }); } /* ۭqv */ private void playVideo(String strPath) { mMediaPlayer01 = new MediaPlayer(); mMediaPlayer01.setAudioStreamType(AudioManager.STREAM_MUSIC); /* ]wVideovHSurfaceHolder */ mMediaPlayer01.setDisplay(mSurfaceHolder01); try { mMediaPlayer01.setDataSource(strPath); } catch (Exception e) { // TODO Auto-generated catch block mTextView01.setText("setDataSource Exceeption:"+e.toString()); e.printStackTrace(); } try { mMediaPlayer01.prepare(); } catch (Exception e) { // TODO Auto-generated catch block mTextView01.setText("prepare Exceeption:"+e.toString()); e.printStackTrace(); } mMediaPlayer01.start(); bIsReleased = false; mTextView01.setText(R.string.str_play); mMediaPlayer01.setOnCompletionListener(new MediaPlayer.OnCompletionListener() { @Override public void onCompletion(MediaPlayer arg0) { // TODO Auto-generated method stub mTextView01.setText(R.string.str_stop); } }); } private boolean checkSDCard() { /* P_OХdO_sb */ if(android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED)) { return true; } else { return false; } } public void mMakeTextToast(String str, boolean isLong) { if(isLong==true) { Toast.makeText(EX07_14.this, str, Toast.LENGTH_LONG).show(); } else { Toast.makeText(EX07_14.this, str, Toast.LENGTH_SHORT).show(); } } @Override public void surfaceChanged(SurfaceHolder surfaceholder, int format, int w, int h) { // TODO Auto-generated method stub Log.i(TAG, "Surface Changed"); } @Override public void surfaceCreated(SurfaceHolder surfaceholder) { // TODO Auto-generated method stub Log.i(TAG, "Surface Changed"); } @Override public void surfaceDestroyed(SurfaceHolder surfaceholder) { // TODO Auto-generated method stub Log.i(TAG, "Surface Destroyed"); } }
true
49aea50dbaea7498d075ad7769f98d4332df2f86
Java
zemenuyar/giftSampl
/src/com/company/gift2.java
UTF-8
587
2.546875
3
[]
no_license
package com.company; import java.util.ArrayList; public class gift2 { public static void main(String[] args) { // write your code here ArrayList<giftApp> mygift = new ArrayList<giftApp>(); mygift.add(new giftApp("Jewlery", "Female", "High")); mygift.add(new giftApp("Jewlery", "Female", "High")); mygift.add(new giftApp("Jewlery", "Female", "High")); mygift.add(new giftApp("Jewlery", "Female", "High")); mygift.add(new giftApp("Jewlery", "Female", "High")); mygift.add(new giftApp("Jewlery", "Female", "High")); } }
true
7e75fc3a4cbf74f0408a048b38247535865cf6e5
Java
arx-deidentifier/arx
/src/main/org/deidentifier/arx/risk/RiskModelCostBenefit.java
UTF-8
2,962
2.4375
2
[ "Apache-2.0" ]
permissive
/* * ARX Data Anonymization Tool * Copyright 2012 - 2023 Fabian Prasser and contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.deidentifier.arx.risk; import java.io.Serializable; import org.deidentifier.arx.ARXCostBenefitConfiguration; /** * This class implements a cost/benefit analysis following the game-theoretic approach proposed in: <br> * * A Game Theoretic Framework for Analyzing Re-Identification Risk. * Zhiyu Wan, Yevgeniy Vorobeychik, Weiyi Xia, Ellen Wright Clayton, * Murat Kantarcioglu, Ranjit Ganta, Raymond Heatherly, Bradley A. Malin * PLOS|ONE. 2015. * * @author Fabian Prasser */ public class RiskModelCostBenefit implements Serializable { /** SVUID */ private static final long serialVersionUID = -6124431335607475931L; /** The underlying configuration */ private final ARXCostBenefitConfiguration config; /** * Creates a new instance * @param configuration */ public RiskModelCostBenefit(ARXCostBenefitConfiguration configuration) { this.config = configuration; } /** * Returns the expected adversary payout * @param successProbability * @return */ public double getExpectedAdversaryPayout(double successProbability) { checkArgument(successProbability); return config.getAdversaryGain() * successProbability - config.getAdversaryCost(); } /** * Returns the expected information loss * @param informationLoss * @return */ public double getExpectedPublisherBenefit(double informationLoss) { checkArgument(informationLoss); return config.getPublisherBenefit() * (1d - informationLoss); } /** * Returns the expected publisher payout * @param informationLoss * @param adversarySuccessProbability * @return */ public double getExpectedPublisherPayout(double informationLoss, double adversarySuccessProbability ) { // Arguments will be checked in subsequent method calls return getExpectedPublisherBenefit(informationLoss) - (getExpectedAdversaryPayout(adversarySuccessProbability) > 0 ? config.getPublisherLoss() * adversarySuccessProbability : 0); } /** * Checks the provided argument * @param argument */ private void checkArgument(double argument) { if (argument < 0d || argument > 1d) { throw new IllegalArgumentException("Argument out of range [0,1]: " + argument); } } }
true
e33dc0a875ba3856207f5b3152e8b07c03a07238
Java
Tornaco/DataMigration
/app/src/main/java/org/newstand/datamigration/service/DataCompressService.java
UTF-8
7,765
1.953125
2
[]
no_license
package org.newstand.datamigration.service; import android.app.Notification; import android.app.NotificationManager; import android.app.Service; import android.content.Context; import android.content.Intent; import android.os.Binder; import android.os.Build; import android.os.Handler; import android.os.HandlerThread; import android.os.IBinder; import androidx.annotation.Nullable; import org.newstand.datamigration.R; import org.newstand.datamigration.common.ActionListener; import org.newstand.datamigration.utils.MediaScannerClient; import org.newstand.datamigration.utils.SevenZipper; import org.newstand.datamigration.utils.ZipUtils; import org.newstand.logger.Logger; import java.io.File; import java.util.HashSet; import java.util.Set; import java.util.concurrent.atomic.AtomicInteger; /** * Created by Nick on 2017/6/27 21:49 */ public class DataCompressService extends Service implements DataCompresser { private static final int NOTIFICATION_ID = 6888; private static final AtomicInteger sNotificationId = new AtomicInteger(NOTIFICATION_ID); private Handler mHandler; private final Set<Integer> sTasks = new HashSet<>(); @Override public void onCreate() { super.onCreate(); HandlerThread hr = new HandlerThread(getClass().getSimpleName()); hr.start(); mHandler = new Handler(hr.getLooper()); } @Nullable @Override public IBinder onBind(Intent intent) { return new ServiceStub(); } @Override public void compressAsync(final String src, final String dest, final ActionListener<Boolean> listener) { // Show notification. final int id = setupCompressingNotification(getApplicationContext()); sTasks.add(id); Logger.d("Add compress task:%s", id); mHandler.post(new Runnable() { @Override public void run() { boolean res = false;//SevenZipper.compressTar(src, dest); File destFile = new File(dest); try { ZipUtils.zip(src, destFile.getParent(), destFile.getName()); } catch (Exception e) { e.printStackTrace(); } if (destFile.exists() && destFile.length() > 0) { res = true; } Logger.d("Compress complete"); if (res) { try { MediaScannerClient.scanSync(getApplicationContext(), dest); MediaScannerClient.scanSync(getApplicationContext(), new File(dest).getParent()); } catch (InterruptedException ignored) { } } clearCompressingNotification(getApplicationContext(), id); setupCompressedNotification(dest, res, getApplicationContext()); sTasks.remove(id); try { listener.onAction(res); } catch (Throwable e) { Logger.w("Error call listener:" + e.getLocalizedMessage()); } if (sTasks.isEmpty()) { stopSelf(); } } }); } private synchronized int setupCompressingNotification(Context context) { Logger.d("Setting up the notification"); // Get NotificationManager reference NotificationManager nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); // Instantiate a Notification int icon = R.drawable.ic_compressing; long when = System.currentTimeMillis(); // Define Notification's message and Intent CharSequence contentTitle = context.getString(R.string.action_compress); CharSequence contentText = getString(R.string.action_compressing); Notification.Builder nb = new Notification.Builder(context) .setContentTitle(contentTitle) .setContentText(contentText) // .setContentIntent(contentIntent) .setSmallIcon(icon) .setTicker(getString(R.string.action_compressing)) .setWhen(when) .setOngoing(true); Notification notification; // go delegate high to low android version adding extra options if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { nb.setVisibility(Notification.VISIBILITY_PUBLIC); nb.setCategory(Notification.CATEGORY_SERVICE); nb.setPriority(Notification.PRIORITY_MAX); } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) { nb.setShowWhen(false); notification = nb.build(); } else { notification = nb.getNotification(); } // Pass Notification to NotificationManager int id = sNotificationId.incrementAndGet(); nm.notify(id, notification); Logger.d("Notification setup done"); return id; } private void clearCompressingNotification(Context context, int id) { Logger.d("Clearing the notifications"); NotificationManager nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); nm.cancel(id); Logger.d("Cleared notification"); } private void setupCompressedNotification(String dest, boolean res, Context context) { Logger.d("Setting up the notification"); // Get NotificationManager reference NotificationManager nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); // Instantiate a Notification int icon = R.drawable.ic_compressing; long when = System.currentTimeMillis(); // Define Notification's message and Intent CharSequence contentTitle = context.getString(R.string.action_compressed); CharSequence contentText = res ? getString(R.string.action_compressed_to, dest) : getString(R.string.action_compress_fail); Notification.Builder nb = new Notification.Builder(context) .setContentTitle(contentTitle) .setContentText(contentText) .setSmallIcon(icon) .setTicker(getString(R.string.action_compressing)) .setWhen(when) .setOngoing(false); Notification notification; // go delegate high to low android version adding extra options if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { nb.setVisibility(Notification.VISIBILITY_PUBLIC); nb.setCategory(Notification.CATEGORY_SERVICE); nb.setPriority(Notification.PRIORITY_MAX); } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) { nb.setShowWhen(false); notification = nb.build(); } else { notification = nb.getNotification(); } // Pass Notification to NotificationManager nm.notify(sNotificationId.incrementAndGet(), notification); Logger.d("Notification setup done"); } @Override public void onDestroy() { super.onDestroy(); } private class ServiceStub extends Binder implements DataCompresser { @Override public void compressAsync(String src, String dest, ActionListener<Boolean> listener) { DataCompressService.this.compressAsync(src, dest, listener); } } }
true
341235253dfcc87a7933d25aacc2d67c285711ae
Java
omarradwan/DB-Engine
/SIsPair.java
UTF-8
276
2.359375
2
[]
no_license
package B3gr; import java.io.Serializable; import java.util.ArrayList; public class SIsPair implements Serializable{ String colName ; SecondaryIndex SI ; public SIsPair(String colName , SecondaryIndex SI) { this.colName = colName; this.SI = SI; } }
true
bc74dbbb020d28ed319a4cabff0d3ee0dfe29719
Java
linkedpipes/etl
/plugins/t-rdfToJsonTemplate/src/main/java/cz/skodape/hdt/rdf/rdf4j/Rdf4jGraphProducer.java
UTF-8
3,825
2.4375
2
[ "MIT" ]
permissive
package cz.skodape.hdt.rdf.rdf4j; import cz.skodape.hdt.core.OperationFailed; import org.eclipse.rdf4j.model.Resource; import org.eclipse.rdf4j.model.Statement; import org.eclipse.rdf4j.rio.RDFFormat; import org.eclipse.rdf4j.rio.RDFHandler; import org.eclipse.rdf4j.rio.RDFParser; import org.eclipse.rdf4j.rio.Rio; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import java.util.Optional; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingDeque; class Rdf4jGraphProducer implements RDFHandler, Runnable { public static class Container { public final List<Statement> statements; public final Resource graph; private Container(List<Statement> statements, Resource graph) { this.statements = statements; this.graph = graph; } public static Container copyAndWrap( List<Statement> statements, Resource graph) { return new Container(new ArrayList<>(statements), graph); } public static Container deadPill() { return new Container(null, null); } } private static final Logger LOG = LoggerFactory.getLogger(Rdf4jGraphProducer.class); private final File file; private final RDFFormat format; private Resource currentGraph = null; private final List<Statement> statements = new ArrayList<>(); private final BlockingQueue<Container> queue = new LinkedBlockingDeque<>(4); public Rdf4jGraphProducer(File file) throws OperationFailed { this.file = file; this.format = getInputFileFormat(); } protected RDFFormat getInputFileFormat() throws OperationFailed { Optional<RDFFormat> format = Rio.getParserFormatForFileName(file.getName()); if (format.isEmpty()) { throw new OperationFailed("Can't determine file format."); } return format.get(); } @Override public void run() { RDFParser parser = Rio.createParser(format); parser.setRDFHandler(this); try (InputStream inputStream = new FileInputStream(file)) { parser.parse(inputStream, "http://localhost/"); } catch (IOException exception) { LOG.info("Can't parse input file.", exception); } try { LOG.info("Queue put pill ..."); queue.put(Container.deadPill()); } catch (InterruptedException exception) { LOG.info("Interrupted."); } } @Override public void startRDF() { // Do nothing. } @Override public void endRDF() { onNextGraphReady(); } /** * Called when the content is ready. */ private void onNextGraphReady() { if (statements.size() == 0) { return; } try { queue.put(Container.copyAndWrap(statements, currentGraph)); statements.clear(); } catch (InterruptedException exception) { LOG.info("Interrupted."); } } @Override public void handleNamespace(String prefix, String uri) { // Do nothing. } @Override public void handleStatement(Statement statement) { if (statement.getContext() == currentGraph) { statements.add(statement); } else { onNextGraphReady(); currentGraph = statement.getContext(); statements.add(statement); } } @Override public void handleComment(String comment) { // Do nothing. } public BlockingQueue<Container> getQueue() { return queue; } }
true
da0ed22433bf2bafb204bb02b8e700401768315d
Java
B112SME/TeamShubhamLD
/BankLoanProject-EurekaServer/src/main/java/com/csrt/app/sme/main/BankLoanProjectEurekaServerApplication.java
UTF-8
451
1.648438
2
[]
no_license
package com.csrt.app.sme.main; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer; @EnableEurekaServer @SpringBootApplication public class BankLoanProjectEurekaServerApplication { public static void main(String[] args) { SpringApplication.run(BankLoanProjectEurekaServerApplication.class, args); } }
true
2c3ecf7624a71ee7a42c76955f40b568a8ca328a
Java
codetriage-readme-bot/hydra-android
/app/src/main/java/be/ugent/zeus/hydra/ui/library/HoursViewModel.java
UTF-8
1,184
2.3125
2
[ "MIT", "Apache-2.0" ]
permissive
package be.ugent.zeus.hydra.ui.library; import android.app.Application; import be.ugent.zeus.hydra.data.models.library.Library; import be.ugent.zeus.hydra.data.models.library.OpeningHours; import be.ugent.zeus.hydra.repository.requests.Request; import be.ugent.zeus.hydra.repository.requests.Requests; import be.ugent.zeus.hydra.data.network.requests.library.OpeningHoursRequest; import be.ugent.zeus.hydra.ui.common.RequestViewModel; import java.util.Arrays; import java.util.List; /** * @author Niko Strijbol */ public class HoursViewModel extends RequestViewModel<List<OpeningHours>> { private Library library; public HoursViewModel(Application application) { super(application); } public void setLibrary(Library library) { this.library = library; } @Override protected Request<List<OpeningHours>> getRequest() { if (library == null) { //TODO: should this be a LiveData instead? throw new IllegalStateException("You must set the library before using it."); } // TODO: this is currently not cached. return Requests.map(new OpeningHoursRequest(library), Arrays::asList); } }
true
c71d75e6f30d92ac2a405f7fe02eef3239943fe3
Java
Mryangtaofang/sample
/sample-case/src/main/java/com/yang/thread/pool/ThreadPoolCase.java
UTF-8
283
2.109375
2
[]
no_license
package com.yang.thread.pool; import com.yang.utils.ThreadPoolUtils; public class ThreadPoolCase { public static void main(String[] args){ ThreadPoolUtils.execute(new Runnable() { @Override public void run() { System.out.println("线程池!"); } }); } }
true
d4bd88df9b9c5ad8e0331b477cb42b61898fa5b7
Java
wangyuesong/WYSBuilder-Backend
/src/main/java/wys/servlets/GcsLogFetcherServlet.java
UTF-8
7,432
1.789063
2
[]
no_license
package wys.servlets; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.nio.channels.Channels; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.ws.rs.client.Client; import javax.ws.rs.client.ClientBuilder; import javax.ws.rs.client.WebTarget; import javax.ws.rs.core.Response; import wys.utils.CloudStorageUtils; import wys.utils.Constants; import wys.utils.CloudStorageUtils.GCSObjectPath; import com.google.appengine.api.datastore.DatastoreService; import com.google.appengine.api.datastore.DatastoreServiceFactory; import com.google.appengine.api.datastore.Entity; import com.google.appengine.api.datastore.EntityNotFoundException; import com.google.appengine.api.datastore.Key; import com.google.appengine.api.datastore.KeyFactory; import com.google.appengine.api.taskqueue.Queue; import com.google.appengine.api.taskqueue.QueueFactory; import com.google.appengine.api.taskqueue.TaskOptions; import com.google.appengine.api.taskqueue.TaskOptions.Method; import com.google.appengine.tools.cloudstorage.GcsFileOptions; import com.google.appengine.tools.cloudstorage.GcsFilename; import com.google.appengine.tools.cloudstorage.GcsInputChannel; import com.google.appengine.tools.cloudstorage.GcsOutputChannel; import com.google.appengine.tools.cloudstorage.GcsService; import com.google.appengine.tools.cloudstorage.GcsServiceFactory; import com.google.appengine.tools.cloudstorage.RetryParams; import com.google.apphosting.utils.remoteapi.RemoteApiPb.Request; import com.offbytwo.jenkins.JenkinsServer; import com.offbytwo.jenkins.model.BuildResult; import com.offbytwo.jenkins.model.Job; import com.sun.istack.logging.Logger; /** * @Project: wysbuilder * @Title: GcsExampleServlet.java * @Package wys.servlets * @Description: TODO * @author YuesongWang * @date Mar 11, 2016 11:57:17 PM * @version V1.0 */ public class GcsLogFetcherServlet extends HttpServlet { /** * */ private String jenkinsLogUrl; private String jenkinsEndpointUrl; private int interval; private String currentOffset; private WebTarget target; private Client client; private Queue queueService = QueueFactory.getDefaultQueue();; private static Logger logger = Logger.getLogger(GcsLogFetcherServlet.class); private DatastoreService datastore = DatastoreServiceFactory.getDatastoreService(); private static final long serialVersionUID = 1L; @Override public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { GCSObjectPath objectPath = getObjectPath(req); String objectPathString = objectPath.toString(); jenkinsLogUrl = req.getParameter("jenkinsLogUrl"); jenkinsEndpointUrl = req.getParameter("jenkinsEndpointUrl"); interval = Integer.parseInt(req.getParameter("interval")); currentOffset = req.getParameter("currentOffset"); client = ClientBuilder.newClient(); target = client.target(jenkinsLogUrl + "?start=" + currentOffset); String result = null; Response response = target.request().get(); String xTextSize = response.getHeaderString("X-Text-Size"); // Server not started that job yet, retry if (xTextSize == null || xTextSize == "") { try { Thread.sleep(interval); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } queueService.add(TaskOptions.Builder .withUrl( Constants.getLogFecthWorkerUrl(objectPath.getUserLogin(), objectPath.getRepoName(), objectPath.getBuildName())). param("jenkinsLogUrl", jenkinsLogUrl). param("jenkinsEndpointUrl", jenkinsEndpointUrl). param("interval", "5000"). param("currentOffset", "0"). method(Method.POST)); return; } // Server started that job, append log to Cloud storage, update build status in datastore JenkinsServer jenkins; try { // Update build status in jenkins jenkins = new JenkinsServer(new URI(jenkinsEndpointUrl), "", ""); Job job = jenkins.getJob(objectPath.getBuildName()); Key parentKey = KeyFactory.createKey("User", objectPath.getUserLogin()); Key childKey = KeyFactory.createKey(parentKey, "Repository", objectPath.getRepoName()); Key grandChildKey = KeyFactory.createKey(childKey, "Build", objectPath.getBuildName()); Entity buildEntity = datastore.get(grandChildKey); if (buildEntity != null) { if (job != null) { BuildResult buildResult = job.details().getLastBuild().details().getResult(); if (buildResult != null) { buildEntity.setProperty("status", buildResult.toString()); datastore.put(buildEntity); } } } logger.info("Jenkins server already have log. Fetch now"); result = response.readEntity(String.class); // Wait for a while Thread.sleep(interval); // Append the log to the cloud storage ByteArrayOutputStream outputStream = null; if (CloudStorageUtils.isObjectExist(objectPath)) { outputStream = CloudStorageUtils.getObject(objectPath); } else { outputStream = new ByteArrayOutputStream(); } outputStream.write(result.getBytes()); CloudStorageUtils.uploadStream(objectPath, "text/plain", new ByteArrayInputStream(outputStream.toByteArray())); } catch (Exception e) { e.printStackTrace(); } // Still more log, Invoke another request if (response.getHeaderString("X-More-Data") != null) { queueService.add(TaskOptions.Builder .withUrl(Constants.getLogFecthWorkerUrl(objectPath.getUserLogin(), objectPath.getRepoName(), objectPath.getBuildName())). param("jenkinsLogUrl", jenkinsLogUrl). param("jenkinsEndpointUrl", jenkinsEndpointUrl). param("interval", "5000"). param("currentOffset", xTextSize). method(Method.POST)); } // No more log else { logger.info("Fetching job final result: " + objectPathString); logger.info("Finished retriving log"); } } private GCSObjectPath getObjectPath(HttpServletRequest req) { String[] splits = req.getRequestURI().split("/", 5); for (int i = 0; i < splits.length; i++) { System.out.println(splits[i]); } if (!splits[0].equals("") || !splits[1].equals("gcs")) { throw new IllegalArgumentException("The URL is not formed as expected. " + "Expecting /gcs/<bucket>/<object>"); } return new GCSObjectPath(splits[2], splits[3], splits[4]); } }
true
39c0243424c9d49a90a5546455747d3d7c626c6c
Java
kelvinpang90/DaFi
/src/com/pwk/service/impl/CommentServiceImpl.java
UTF-8
2,098
2.328125
2
[]
no_license
package com.pwk.service.impl; import com.pwk.entity.Comment; import com.pwk.service.CommentService; import org.hibernate.Hibernate; import org.hibernate.Query; import org.hibernate.SessionFactory; import org.springframework.transaction.annotation.Transactional; import javax.annotation.Resource; import java.util.List; /** * Created by wenkai.peng on 2014/6/22. */ @Transactional public class CommentServiceImpl implements CommentService { @Resource private SessionFactory sessionFactory; @Override public void add(Comment comment) { sessionFactory.getCurrentSession().save(comment); } @Override public void update(Comment comment) { sessionFactory.getCurrentSession().update(comment); } @Override public void delete(int id) { sessionFactory.getCurrentSession().delete(this.getById(id)); } @Override public Comment getById(int id) { return (Comment)sessionFactory.getCurrentSession().get(Comment.class,id); } @Override public List<Comment> getByList(int page, int size) { if(page==0||size==0){ page = 1; size = 10; } Query query = sessionFactory.getCurrentSession().createQuery("from Comment c order by c.createDate desc"); if (page != 0 && size != 0) { query.setFirstResult(size * (page - 1)); query.setMaxResults(size); } return query.list(); } @Override public List<Comment> getByMicroId(int id) { Query query = sessionFactory.getCurrentSession().createQuery("from Comment c where c.microId=:id order by c.createDate desc"); query.setParameter("id",id, Hibernate.INTEGER); return query.list(); } @Override public int getTotal() { return sessionFactory.getCurrentSession().createQuery("from Comment c where c.status=1").list().size(); } @Override public int getTotalByMicroId(int id) { return sessionFactory.getCurrentSession().createQuery("from Comment c where c.status=1 and c.microId="+id).list().size(); } }
true
00bbdc112ef8d4f1f5bc72c261ddab5b75794b02
Java
rajveer92192/Collage-Admission-Management-System
/src/database/ADMIN.java
UTF-8
14,985
2.28125
2
[]
no_license
package database; public class ADMIN extends javax.swing.JFrame { String p1,p2; public ADMIN() { initComponents(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPanel2 = new javax.swing.JPanel(); jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); jLabel10 = new javax.swing.JLabel(); jButton1 = new javax.swing.JButton(); jLabel4 = new javax.swing.JLabel(); jLabel6 = new javax.swing.JLabel(); jPanel4 = new javax.swing.JPanel(); jLabel7 = new javax.swing.JLabel(); jLabel8 = new javax.swing.JLabel(); jTextField1 = new javax.swing.JTextField(); jButton2 = new javax.swing.JButton(); jLabel9 = new javax.swing.JLabel(); jPasswordField1 = new javax.swing.JPasswordField(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setLocation(new java.awt.Point(520, 200)); jPanel2.setBackground(new java.awt.Color(204, 255, 255)); jPanel2.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED)); jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/database/photo-gallery-18.jpg"))); // NOI18N jLabel2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/database/UIET.jpg"))); // NOI18N jLabel10.setIcon(new javax.swing.ImageIcon(getClass().getResource("/database/18299477_203542573496350_5533787278943453184_n.jpg"))); // NOI18N jButton1.setBackground(new java.awt.Color(204, 255, 255)); jButton1.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N jButton1.setText("BACK"); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); jLabel4.setIcon(new javax.swing.ImageIcon(getClass().getResource("/database/mANIN!.jpg"))); // NOI18N jLabel6.setBackground(new java.awt.Color(153, 255, 255)); jLabel6.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N jLabel6.setText("* THIS LOGIN PORTAL IS FOR HOD AND TEACHER'S ONLY !!"); jPanel4.setBackground(new java.awt.Color(204, 255, 255)); jLabel7.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N jLabel7.setText("USER NAME"); jLabel8.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N jLabel8.setText("PASSWORD"); jTextField1.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N jButton2.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N jButton2.setText("LOGIN"); jButton2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton2ActionPerformed(evt); } }); jLabel9.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N jLabel9.setText("DEPARTMENT LOGIN"); jPasswordField1.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4); jPanel4.setLayout(jPanel4Layout); jPanel4Layout.setHorizontalGroup( jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel4Layout.createSequentialGroup() .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel4Layout.createSequentialGroup() .addGap(96, 96, 96) .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel7) .addComponent(jLabel8)) .addGap(83, 83, 83) .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jButton2) .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 198, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jPasswordField1, javax.swing.GroupLayout.PREFERRED_SIZE, 198, javax.swing.GroupLayout.PREFERRED_SIZE)))) .addGroup(jPanel4Layout.createSequentialGroup() .addGap(204, 204, 204) .addComponent(jLabel9))) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); jPanel4Layout.setVerticalGroup( jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel4Layout.createSequentialGroup() .addGap(53, 53, 53) .addComponent(jLabel9) .addGap(55, 55, 55) .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel7)) .addGap(35, 35, 35) .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jPasswordField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel8)) .addGap(54, 54, 54) .addComponent(jButton2) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2); jPanel2.setLayout(jPanel2Layout); jPanel2Layout.setHorizontalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup() .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 99, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)) .addGroup(jPanel2Layout.createSequentialGroup() .addContainerGap() .addComponent(jLabel6)) .addGroup(jPanel2Layout.createSequentialGroup() .addGap(21, 21, 21) .addComponent(jLabel4))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 19, Short.MAX_VALUE) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(jPanel2Layout.createSequentialGroup() .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 297, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(jLabel10, javax.swing.GroupLayout.PREFERRED_SIZE, 294, javax.swing.GroupLayout.PREFERRED_SIZE))) .addContainerGap()) ); jPanel2Layout.setVerticalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel10, javax.swing.GroupLayout.PREFERRED_SIZE, 202, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 203, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 203, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 59, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 265, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 70, Short.MAX_VALUE) .addComponent(jLabel6, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(jPanel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 0, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); pack(); }// </editor-fold>//GEN-END:initComponents private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed // TODO add your handling code here: if(evt.getSource() == jButton2) { p1 = jTextField1.getText(); p2 = new String(jPasswordField1.getPassword()); if(p1.equals("admin_dcet")) { if(p2.equals("qwerty")) { JTABLE ob = new JTABLE(); ob.setVisible(true); this.setVisible(false); } } else if(p1.equals("aman_dcet")) { if(p2.equals("qwerty")) { if(evt.getSource() == jButton2) { JTABLE1 ob = new JTABLE1(); ob.setVisible(true); this.setVisible(false); } } } else if(p1.equals("priya_dcet")) { if(p2.equals("qwerty")) { if(evt.getSource() == jButton2) { JTABLE2 ob = new JTABLE2(); ob.setVisible(true); this.setVisible(false); } } } else { ERROR ob = new ERROR(); ob.setVisible(true); } } }//GEN-LAST:event_jButton2ActionPerformed private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed // TODO add your handling code here: if(evt.getSource() == jButton1) { LOGIN ob = new LOGIN(); ob.setVisible(true); this.setVisible(false); } }//GEN-LAST:event_jButton1ActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(ADMIN.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(ADMIN.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(ADMIN.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(ADMIN.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new ADMIN().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton jButton1; private javax.swing.JButton jButton2; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel10; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel6; private javax.swing.JLabel jLabel7; private javax.swing.JLabel jLabel8; private javax.swing.JLabel jLabel9; private javax.swing.JPanel jPanel2; private javax.swing.JPanel jPanel4; private javax.swing.JPasswordField jPasswordField1; private javax.swing.JTextField jTextField1; // End of variables declaration//GEN-END:variables }
true
77c3aa4b5cc961ac77ef5828ea3d4e29d7c03520
Java
jianglei260/AILab
/miquan/src/main/java/com/example/miquan/ui/activitiy/ImageActivity.java
UTF-8
2,503
1.984375
2
[]
no_license
package com.sharevar.miquan.ui.activitiy; import android.databinding.DataBindingUtil; import android.graphics.Color; import android.os.Handler; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.TypedValue; import android.view.View; import android.widget.TextView; import android.widget.ViewSwitcher; import com.sharevar.miquan.R; import com.sharevar.miquan.databinding.ActivityImageBinding; import com.sharevar.miquan.ui.adapter.SimpleDraweeAdapteer; import com.sharevar.miquan.ui.detail.ImageViewModel; import com.kelin.mvvmlight.bindingadapter.viewpager.ViewBindingAdapter; import me.tatarka.bindingcollectionadapter.BindingCollectionAdapters; import me.tatarka.bindingcollectionadapter.ItemViewArg; public class ImageActivity extends AppCompatActivity { public static final String RESOURCE_ID = "resource_id"; public static final String IMG_INDEX = "image_index"; ActivityImageBinding binding; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); binding = DataBindingUtil.setContentView(this, R.layout.activity_image); int id = getIntent().getIntExtra(RESOURCE_ID, 147); final int index = getIntent().getIntExtra(IMG_INDEX, 0); binding.switcher.setFactory(new ViewSwitcher.ViewFactory() { @Override public View makeView() { TextView textView = new TextView(ImageActivity.this); textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 32); textView.setTextColor(getResources().getColor(R.color.white)); return textView; } }); binding.setImageViewModel(new ImageViewModel(this, id, index)); BindingCollectionAdapters.setAdapter(binding.viewpager, ItemViewArg.of(binding.getImageViewModel().itemView), binding.getImageViewModel().viewModels, null, null); ViewBindingAdapter.onScrollChangeCommand(binding.viewpager, null, binding.getImageViewModel().itemSelected, null); Handler handler = new Handler(); handler.postDelayed(new Runnable() { @Override public void run() { binding.viewpager.setCurrentItem(index, false); } }, 100); } public void switchToolbar(){ binding.getImageViewModel().visibleClick.execute(); } public void showSelected(final int index) { binding.switcher.setText("" + (index + 1)); } }
true
ef1d4c706f02dd19b30d37aa7ab9698ef533adc7
Java
imjarp/OpenClothes
/app/src/main/java/com/mx/kanjo/openclothes/model/OutcomeTypeSale.java
UTF-8
401
2.109375
2
[]
no_license
package com.mx.kanjo.openclothes.model; /** * Created by JARP on 20/01/2015. */ public class OutcomeTypeSale { public final static int idOutcomeSale = 0 ; public final static String descriptionSaleOutcome = "Sale" ; private OutcomeTypeSale(){} public static OutcomeType OutcomeTypeSale() { return new OutcomeType(idOutcomeSale,descriptionSaleOutcome); } }
true
8425dc7b9d9c586193fc7ca9d668ed75e7310510
Java
li-gaochao/base_test
/Base_Test/src/Lagrange.java
GB18030
3,008
3.28125
3
[]
no_license
import java.math.BigDecimal; /** * @Description: * @date: 201943 */ public class Lagrange { private static double[] Lag(double x[], double y[], double x0[]) { int m = x.length; int n = x0.length; double y0[] = new double[n]; for (int ia = 0; ia < n; ia++) { double j = 0; for (int ib = 0; ib < m; ib++) { double k = 1; for (int ic = 0; ic < m; ic++) { if (ib != ic) { k = k * (x0[ia] - x[ic]) / (x[ib] - x[ic]); } } k = k * y[ib]; j = j + k; } if (j < 0) { y0[ia] = 0; } else { y0[ia] = j; } } return y0; } public static void main(String[] args) { // System.out.println("IJֵ"); // Scanner input=new Scanner(System.in); // int m=input.nextInt(); // System.out.println("IJֵ"); // int n=input.nextInt(); // double x[]=new double[m]; // double y[]=new double[m]; // double x0[]=new double[n]; // // for(int i=0;i<m;i++){ // x[i]=input.nextDouble(); // } // System.out.println("IJֵӦĺֵ:"); // for(int i=0;i<m;i++){ // y[i]=input.nextDouble(); // } // System.out.println("IJֵ"); // for(int i=0;i<n;i++){ // x0[i]=input.nextDouble(); // } // double y0[]=Lag(x, y, x0); // System.out.println("ղֵ:"); // for(int i=0;i<n;i++){ // System.out.println(y0[i]+" "); // } double x[] = new double[] { 5, 10, 20, 50, 60, 100 }; double y[] = new double[] { 0, 20 }; double value[] = new double[] { 33, 78, 12, 34, 54, 99 }; double x0[] = new double[300]; double ynew[] = new double[100]; for (int i = 0; i < 300; i++) { x0[i] = i; } double y0[] = Lag(x, value, x0); // System.out.println("ղֵ:"); // for(int i=0;i<300;i++){ // System.out.println(x0[i] + "," +y0[i]); // } // õ100valueٰyֳ100 for (int i = 0; i < 100; i++) { if (i == 0) { ynew[i] = 0; } else { ynew[i] = ynew[i - 1] + (new BigDecimal("20").divide(new BigDecimal("100"))).doubleValue(); } // System.out.println("ynew[i]" + i +":"+ ynew[i]); } System.out.println("y0[]:" + y0.length); double value0[] = Lag(y, y0, ynew); double resultx[] = new double[300]; double resulty[] = new double[100]; double resultvalue[] = new double[300]; System.out.println("ղֵ:"); // for(int i=0;i<100;i++){ // resulty[i] = ynew[i]; // } // for(int i=0;i<300;i++){ // resultx[i] = x0[i]; // resultvalue[i] = value0[i]; // // System.out.println(x0[i] + "," + ynew[i] + "," +value0[i]); // } System.out.println("x0[]:" + x0.length); System.out.println("ynew[]:" + ynew.length); System.out.println("value0[]:" + value0.length); for (int i = 0; i < 300; i++) { for (int j = 0; j < 100; j++) { System.out.println(x0[i] + "," + ynew[j] + "," + value0[i]); } } } }
true
e3ffe9ebde4c48e017773a11407e4b97cc7847ae
Java
jhordanSnow/ArukamiAndroid
/app/src/main/java/hiker/arukami/arukamiapp/Controllers/Fragments/MainHikeFragment.java
UTF-8
7,366
1.976563
2
[]
no_license
package hiker.arukami.arukamiapp.Controllers.Fragments; import android.content.Intent; import android.os.AsyncTask; import android.os.Bundle; import android.support.design.widget.TabLayout; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentStatePagerAdapter; import android.support.v4.view.ViewPager; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.google.android.gms.maps.model.LatLng; import java.io.IOException; import java.util.ArrayList; import java.util.concurrent.ExecutionException; import hiker.arukami.arukamiapp.API.APIClient; import hiker.arukami.arukamiapp.API.AruKamiAPI; import hiker.arukami.arukamiapp.Controllers.Activities.MainActivity; import hiker.arukami.arukamiapp.Models.HikePointRequest; import hiker.arukami.arukamiapp.Models.HikePointRespond; import hiker.arukami.arukamiapp.Models.HikeRequest; import hiker.arukami.arukamiapp.Models.PointModel; import hiker.arukami.arukamiapp.R; import retrofit2.Call; import retrofit2.Retrofit; /** * A simple {@link Fragment} subclass. */ public class MainHikeFragment extends Fragment { private static MainHikeFragment instance; private ViewPager mViewPager; private static TabLayout tabLayout; private HikeFragment hikeGeneral; private HikeMapFragment hikeMap; private HikeRequest hike; private ArrayList<PointModel> hikePoints; public static MainHikeFragment getInstance() { if (instance == null) { instance = new MainHikeFragment(); } return instance; } public void reload(){ getActivity().recreate(); Intent intent = getActivity().getIntent(); getActivity().finish(); startActivity(intent); } public ArrayList<PointModel> getHikeSelectedPoints(){ return hikePoints; } public void addPoint(PointModel model){ hikePoints.add(model); } public LatLng getLastPoint(){ ArrayList<LatLng> hikePoints = hikeMap.getPoints(); return hikePoints.get(hikePoints.size() - 1); } public void resetHike() { instance = null; } public MainHikeFragment() { hikeGeneral = new HikeFragment(); hikeMap = new HikeMapFragment(); } public HikeRequest getHike(){ hike = hikeGeneral.getHike(); return hike; } public HikeRequest getHikePoints() { InsertPointCall pointTask = new InsertPointCall(); try { pointTask.execute().get(); } catch (InterruptedException | ExecutionException e) { e.printStackTrace(); } hike.setRoute(hikeMap.encodePath()); return hike; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { hikeGeneral = new HikeFragment(); hikeMap = new HikeMapFragment(); hikePoints = new ArrayList<>(); View inflatedView = inflater.inflate(R.layout.fragment_likes, container, false); mViewPager = (ViewPager) inflatedView.findViewById(R.id.viewpager); mViewPager.addOnPageChangeListener( new ViewPager.SimpleOnPageChangeListener() { @Override public void onPageSelected(int position) { TabLayout.Tab tab = tabLayout.getTabAt(position); tab.select(); } }); tabLayout = (TabLayout) inflatedView.findViewById(R.id.tabLayout); tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() { @Override public void onTabSelected(TabLayout.Tab tab) { int position = tab.getPosition(); showLayout(); mViewPager.setCurrentItem(position); } @Override public void onTabUnselected(TabLayout.Tab tab) { } @Override public void onTabReselected(TabLayout.Tab tab) { } }); tabLayout.addTab(tabLayout.newTab().setText("General")); tabLayout.addTab(tabLayout.newTab().setText("Map")); mViewPager.setAdapter(new PagerAdapter (getFragmentManager(), tabLayout.getTabCount())); mViewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout)); return inflatedView; } public void changeTab(int position){ mViewPager.setCurrentItem(position); } public void showLayout() { tabLayout.setVisibility(View.VISIBLE); ((MainActivity) getActivity()).showButton(); ((MainActivity) getActivity()).showNavBar(); } public void hideLayout() { tabLayout.setVisibility(View.GONE); ((MainActivity) getActivity()).hideButtons(); ((MainActivity) getActivity()).hideNavBar(); } public class PagerAdapter extends FragmentStatePagerAdapter { int mNumOfTabs; public PagerAdapter(FragmentManager fm, int NumOfTabs) { super(fm); this.mNumOfTabs = NumOfTabs; } @Override public Fragment getItem(int position) { switch (position) { case 0: return hikeGeneral; case 1: return hikeMap; default: return null; } } @Override public int getCount() { return mNumOfTabs; } } private class InsertPointCall extends AsyncTask<Call, Void, HikeRequest> { private HikePointRequest startPoint; private HikePointRequest endPoint; @Override protected void onPreExecute() { ArrayList<LatLng> points = hikeMap.getPoints(); if (points.size() > 1) { hike = hikeGeneral.getHike(); startPoint = new HikePointRequest(String.valueOf(points.get(0).latitude), String.valueOf(points.get(0).longitude)); endPoint = new HikePointRequest(String.valueOf(points.get(points.size()-1).latitude), String.valueOf(points.get(points.size()-1).longitude)); } } @Override protected HikeRequest doInBackground(Call... params) { Retrofit retrofit = APIClient.getClient(); AruKamiAPI apiService = retrofit.create(AruKamiAPI.class); HikePointRespond startPointResponse = new HikePointRespond(); HikePointRespond endPointResponse = new HikePointRespond(); Call<HikePointRespond> startPointResult = apiService.addGeoPoint(startPoint); Call<HikePointRespond> endPointResult = apiService.addGeoPoint(endPoint); try { startPointResponse = startPointResult.execute().body(); endPointResponse = endPointResult.execute().body(); } catch (IOException e) { e.printStackTrace(); } hike.setStartPoint(startPointResponse.getIdPoint()); hike.setEndPoint(endPointResponse.getIdPoint()); return hike; } @Override protected void onPostExecute(HikeRequest result) { } } }
true
3caf052156c93b2737c1a20c11fc1c75dc90d348
Java
enayetullah/spring-5-rest-app-2
/src/test/java/throne/springreacto/spring5restapp2/controllers/v1/JsonObjectConverter.java
UTF-8
496
2.265625
2
[]
no_license
package throne.springreacto.spring5restapp2.controllers.v1; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; public abstract class JsonObjectConverter { public static String objectToJsonStirng(Object object){ try { return new ObjectMapper().writeValueAsString(object); }catch (JsonProcessingException e){ throw new IllegalArgumentException("Error in parsing object"); } } }
true
364a2d6987359c18aa434e29cb1640db72e474a9
Java
lzh06550107/online-video-website
/TCKMS_jetty/src/main/java/com/and9/tckms/factory/VideoTypeDaoFactory.java
UTF-8
923
2.359375
2
[]
no_license
package com.and9.tckms.factory; import java.io.InputStream; import java.util.Properties; import com.and9.tckms.dao.VideoTypeDao; import sun.security.jca.GetInstance; public class VideoTypeDaoFactory { VideoTypeDao vtDao = null; private static VideoTypeDaoFactory instance = new VideoTypeDaoFactory(); private VideoTypeDaoFactory(){ try{ Properties prop = new Properties(); InputStream inStream = VideoTypeDaoFactory.class.getClassLoader() .getResourceAsStream("DaoConfig.properties"); prop.load(inStream); String vtDaoClass = prop.getProperty("VideoTypeDaoClass"); System.out.println(vtDaoClass); vtDao = (VideoTypeDao) Class.forName(vtDaoClass).newInstance(); } catch (Exception e) { throw new ExceptionInInitializerError(); } } public static VideoTypeDaoFactory getInstance(){ return instance; } public VideoTypeDao getVideoTypeDao(){ return vtDao; } }
true
18a757a59f8d046eb2fcd67279fce58c07aa4498
Java
sistemasUPeU/ppp
/ppp/src/main/java/pe/edu/upeu/ppp/service/EvaluacionesService.java
UTF-8
253
1.539063
2
[]
no_license
package pe.edu.upeu.ppp.service; public interface EvaluacionesService { public int ActualizarEvaluacion(int p_idevaluacion, int p_estado); public int CrearDimensiones(int p_idevaluacion, String[] nombre, String[] p_activo); }
true
5a29fc46c2cba2fcb802066fc1221927fcbcf04b
Java
igorarouca/jeecourse
/huge-integer-calc-interfaces/src/main/java/br/com/objective/training/calc/Calculator.java
UTF-8
254
2.484375
2
[]
no_license
package br.com.objective.training.calc; public interface Calculator<T> extends CalculatorX<T, RuntimeException> { @Override T compare(T left, T right); @Override T add(T left, T right); @Override T subtract(T left, T right); }
true
74f6b0d5b45aa0fc4eaf6c9189ca725b88ef7ec5
Java
xdlv-sys/Xd
/src/main/java/xd/fw/job/EventJob.java
UTF-8
2,195
2.34375
2
[]
no_license
package xd.fw.job; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Service; import xd.fw.bean.Event; import xd.fw.service.FwService; import xd.fw.service.IConst; import java.util.Arrays; import java.util.List; /** * Created by xd lv on 10/26/2016. */ @Service public abstract class EventJob implements IConst{ Logger logger = LoggerFactory.getLogger(Event.class); @Autowired protected FwService fwService; @Scheduled(cron="0/10 * * * * ?") public void execute() throws Exception { List<Event> events = getEvent(); if (events == null || events.size() < 1){ return; } byte[] processType = processType(); logger.info("start to process event:count: {}", Arrays.toString(processType), processType.length); byte eventStatus; for (Event event : events){ try{ eventStatus = process(event); } catch (Throwable e){ logger.error("",e); eventStatus = STATUS_FAIL; } if (eventStatus == STATUS_FAIL){ processFailure(event); } else { //finish the event processSuccess(event); } } logger.info("end to process event"); } protected void processFailure(Event event){ updateEvent(event, STATUS_FAIL); } protected void processSuccess(Event event){ updateEvent(event, STATUS_DONE); } private void updateEvent(Event event, byte status){ event.setEventStatus(status); event.setTryCount((byte)(event.getTryCount() + 1)); fwService.update(event); } protected abstract byte process(Event event) throws Exception; protected abstract byte[] processType(); protected List<Event> getEvent() { return fwService.getTriggeringEvent(processType(), maxTry(), maxLimit()); } protected int maxTry(){ return 1; } protected int maxLimit(){ return 100; } }
true
bb108889a8885c95aa5d7b10d08259d1a6a7f628
Java
dariakrupenko/FinalTask
/AdmissionWeb/src/test/by/epam/admissionweb/service/EnrollmentServiceTest.java
UTF-8
3,094
2.515625
3
[]
no_license
package test.by.epam.admissionweb.service; import static org.junit.Assert.assertNull; import java.util.Calendar; import java.util.Date; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import main.by.epam.admissionweb.dao.pool.ConnectionPool; import main.by.epam.admissionweb.dao.pool.exception.ConnectionPoolException; import main.by.epam.admissionweb.dao.pool.impl.ConnectionPoolImpl; import main.by.epam.admissionweb.entity.Enroll; import main.by.epam.admissionweb.service.EnrollmentService; import main.by.epam.admissionweb.service.ServiceFactory; import main.by.epam.admissionweb.service.exception.ServiceException; /** * Класс <code>EnrollmentServiceTest</code> представляет собой JUnit Test Case и * предназначен для тестирования сервис-объекта {@link EnrollmentService}. * * @author Daria Krupenko * @see EnrollmentService * */ public class EnrollmentServiceTest { /** * Пул соединений с базой данных */ private static ConnectionPool pool; /** * Фабрика для получения сервис-объектов */ private static ServiceFactory serviceFactory; /** * Инициализация пула соединений с базой данных и фабрики получения * сервис-объектов * * @throws ConnectionPoolException * если при инициализации пула соединений произошла ошибка * @see ConnectionPool * @see ServiceFactory */ @BeforeClass public static void initTestContext() throws ConnectionPoolException { pool = ConnectionPoolImpl.getInstance(); pool.initConnectionPool(); serviceFactory = ServiceFactory.getInstance(); } /** * JUnit Test, который заключается в попытке открыть новый набор с * невалидными данными: дата начала набора по своему значению наступает * позднее даты окончания набора. * * @throws ServiceException * если при анализе данных произошла ошибка */ @Test public void testEnroll() throws ServiceException { EnrollmentService service = serviceFactory.getEnrollmentService(); Enroll e = new Enroll(); Calendar c = Calendar.getInstance(); Date bDate = c.getTime(); c.roll(Calendar.MONTH, -1); Date eDate = c.getTime(); e.setBeginDate(bDate); e.setEndDate(eDate); e.setStatus(true); Enroll eS = service.startEnroll(e); assertNull(eS); } /** * Уничтожение пула соединений * * @throws ConnectionPoolException * если при уничтожении пула соединений произошла ошибка */ @AfterClass public static void destroyTestContext() throws ConnectionPoolException { pool.destroyConnectionPool(); } }
true
391572502e0064330391670451fe2375db55499b
Java
superproyectos/UpSideDown
/core/src/com/upsidedown/juego/Creators/Preview.java
UTF-8
450
2.484375
2
[]
no_license
package com.upsidedown.juego.Creators; import com.framework.Camara; import com.framework.Figuras.Poligonos.Polygon; public class Preview extends Creation { public void vistaPrevia(Polygon p) { p.cambiarRelleno(getRelleno()); Polygon ax=p.copy(); ax.resize(1.5f); ax.setPosicion(Camara.W/6,Camara.W/2); addElemento(ax); } public void resultadoFinal() { for(Polygon p:getElementos()) p.setPosicion(Camara.W/600,Camara.W/200); } }
true
cb99d87fbbe8d0c5cb54161f456cd7488c09b0c0
Java
wrightdw/biolayout-1
/src/main/java/org/BioLayoutExpress3D/CPUParallelism/Executors/LoggerThreadPoolExecutor.java
UTF-8
4,474
2.9375
3
[]
no_license
package org.BioLayoutExpress3D.CPUParallelism.Executors; import java.util.concurrent.*; import java.util.concurrent.atomic.*; import static org.BioLayoutExpress3D.Environment.GlobalEnvironment.*; import static org.BioLayoutExpress3D.DebugConsole.ConsoleOutput.*; /** * * The LoggerThreadPoolExecutor class is used to create a custom Thread Pool Executor with logging capabilities. * * @see org.BioLayoutExpress3D.CPUParallelism.Executors.LoggerThread * @see org.BioLayoutExpress3D.CPUParallelism.Executors.LoggerThreadFactory * @author Thanos Theo, 2008-2009-2010 * @version 3.0.0.0 */ public class LoggerThreadPoolExecutor extends ThreadPoolExecutor { /** * Variable to be used from the LoggerThreadPoolExecutor. */ private final ThreadLocal<Long> startTime = (DEBUG_BUILD) ? new ThreadLocal<Long>() : null; /** * Variable to be used from the LoggerThreadPoolExecutor. */ private final AtomicLong numberOfTasks = (DEBUG_BUILD) ? new AtomicLong() : null; /** * Variable to be used from the LoggerThreadPoolExecutor. */ private final AtomicLong totalTime = (DEBUG_BUILD) ? new AtomicLong() : null; /** * The first constructor of the LoggerThreadPoolExecutor class. */ public LoggerThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue) { super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue); } /** * The second constructor of the LoggerThreadPoolExecutor class. */ public LoggerThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory) { super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory); } /** * The third constructor of the LoggerThreadPoolExecutor class. */ public LoggerThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, RejectedExecutionHandler handler) { super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, handler); } /** * The fourth constructor of the LoggerThreadPoolExecutor class. */ public LoggerThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory, RejectedExecutionHandler handler) { super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory, handler); } /** * Overrides the beforeExecute() method of the parent ThreadPoolExecutor class. */ @Override protected void beforeExecute(Thread thread, Runnable runnable) { super.beforeExecute(thread, runnable); if (DEBUG_BUILD) { printf("%s: start %s\n", thread, runnable); startTime.set( System.nanoTime() ); } } /** * Overrides the afterExecute() method of the parent ThreadPoolExecutor class. */ @Override protected void afterExecute(Runnable runnable, Throwable t) { try { if (DEBUG_BUILD) { long taskTime = System.nanoTime() - startTime.get(); numberOfTasks.incrementAndGet(); totalTime.addAndGet(taskTime); printf("Throwable %s: ended Runnable %s, with time taken: %d nsecs\n", t, runnable, taskTime); } } finally { super.afterExecute(runnable, t); } } /** * Overrides the terminated() method of the parent ThreadPoolExecutor class. */ @Override protected void terminated() { try { // warning, have to run in another thread to avoid InterruptedException problems with multicore ConsoleOutput thread interruption & Executor.shutdown()! if (DEBUG_BUILD) { new Thread( new Runnable() { @Override public void run() { printf( "Terminated Logger Thread Pool: avg time=%d nsecs\n", totalTime.get() / ( (numberOfTasks.get() == 0) ? 1 : numberOfTasks.get() ) ); } } ).start(); } } finally { super.terminated(); } } }
true
c12ae87332c183c996c9a32ca61c501c565acb1c
Java
sameerveda/RssScrapper
/garbaged/DownloadTasks.java
UTF-8
6,855
2.5
2
[ "Apache-2.0" ]
permissive
package scrapper.scrapper; import static java.nio.file.StandardOpenOption.CREATE; import static java.nio.file.StandardOpenOption.READ; import static java.nio.file.StandardOpenOption.TRUNCATE_EXISTING; import static java.nio.file.StandardOpenOption.WRITE; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Objects; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ExecutorService; import java.util.function.Consumer; import java.util.stream.Stream; import sam.console.ANSI; import scrapper.Utils; public class DownloadTasks { private static final ConcurrentHashMap<String, DownloadTasks> DATA = new ConcurrentHashMap<>(); private static final ConcurrentHashMap<String, Boolean> EXISTING = new ConcurrentHashMap<>(); public static DownloadTasks get(String url) { return DATA.get(url); } public static DownloadTasks create(String pageUrl, List<String> list, Path folder) { list.removeIf(t -> t == null || t.trim().isEmpty() || EXISTING.putIfAbsent(t, true) != null); DownloadTasks sr = new DownloadTasks(pageUrl, list, folder); DATA.put(pageUrl, sr); return sr; } public static Collection<DownloadTasks> keys() { return Collections.unmodifiableCollection(DATA.values()); } static { read(); addShutdownHook(); System.out.println(ANSI.yellow("ScrappingResult initilized")); } private static void read() { Path p = Paths.get("app_data/ScrappingResult.dat"); if(Files.exists(p)) { try(InputStream is = Files.newInputStream(p, READ); DataInputStream dis = new DataInputStream(is)) { int size = dis.readInt(); for (int i = 0; i < size; i++) { DownloadTasks sr = new DownloadTasks(dis); DATA.put(sr.pageUrl, sr); } } catch (IOException e) { throw new RuntimeException(e); } } } private static void addShutdownHook() { Utils.addShutDownTask(() -> { Path p = Paths.get("app_data/ScrappingResult.dat"); try { if(DATA.isEmpty()) Files.deleteIfExists(p); else { Files.createDirectories(p.getParent()); try(OutputStream os = Files.newOutputStream(p, CREATE, WRITE, TRUNCATE_EXISTING); DataOutputStream dos = new DataOutputStream(os)) { dos.writeInt(DATA.size()); for (DownloadTasks sr : DATA.values()) sr.write(dos); Utils.logger(DownloadTasks.class) .info(ANSI.green("created: ")+p); } } } catch (IOException e) { Utils.logger(DownloadTasks.class) .error("failed to save:"+p, e); } }); } private void write(DataOutputStream dos) throws IOException { synchronized (tasks) { dos.writeUTF(pageUrl); dos.writeUTF(folder.toString()); dos.writeBoolean(toParent); int count = 0; for (DownloadTask d : tasks) { if(d != null) count++; } dos.writeInt(count); if(count == 0) return; for (DownloadTask d : tasks) { if(d != null) { dos.writeUTF(d.urlString); dos.writeUTF(d.name == null ? "" : d.name); } } } } private DownloadTasks(DataInputStream dis) throws IOException { this.pageUrl = dis.readUTF(); this.folder = Paths.get(dis.readUTF()); this.toParent = dis.readBoolean(); int size = dis.readInt(); this.tasks = new DownloadTask[size]; if( size != 0) { for (int n = 0; n < size; n++) { String url = dis.readUTF(); String name = dis.readUTF(); tasks[n] = new DownloadTask(url, name.isEmpty() ? null : name, n, this); } } } static String failedTaskLog() { StringBuilder sb = new StringBuilder(); DATA.values().forEach(sr -> sr.appendFailedLog(sb)); return sb.length() == 0 ? null : sb.toString(); } public static boolean hasFailed() { return DATA.values().stream().anyMatch(DownloadTasks::_hasFailed); } private void appendFailedLog(StringBuilder sb) { int length = sb.length(); sb.append(folder).append('\n'); int length2 = sb.length(); forEach(d -> sb.append(" ").append(d.urlString).append('\n')); if(sb.length() == length2) sb.setLength(length); } private final String pageUrl; final boolean toParent; private final DownloadTask[] tasks; final Path folder; private DownloadTasks(String pageUrl, List<String> childrenUrls, Path folder) { Objects.requireNonNull(pageUrl, "url cannot be null"); Objects.requireNonNull(childrenUrls, "childrenUrls cannot be null"); Objects.requireNonNull(folder, "folder cannot be null"); if(childrenUrls.isEmpty()) throw new IllegalArgumentException("childrenUrls cannot be empty"); this.pageUrl = pageUrl; this.folder = folder; this.toParent = childrenUrls.size() == 1; this.tasks = createTasks(childrenUrls); } private boolean _hasFailed() { return Stream.of(tasks).anyMatch(Objects::nonNull); } private DownloadTask[] createTasks(List<String> urls) { DownloadTask[] ts = new DownloadTask[urls.size()]; for (int i = 0; i < ts.length; i++) ts[i] = new DownloadTask(urls.get(i), i, this); return ts; } public DownloadTasks(String pageUrl, boolean toParent, DownloadTask[] tasks, Path folder) { this.pageUrl = pageUrl; this.toParent = toParent; this.tasks = tasks; this.folder = folder; } public String getUrl() { return pageUrl; } public int size() { return tasks.length; } public int startDownload(ExecutorService ex) { int count[] = {0}; forEach(d -> { ex.execute(d); count[0]++; }); return count[0]; } public List<DownloadTask> failedTasks() { synchronized(tasks) { ArrayList<DownloadTask> list = new ArrayList<>(); forEach(list::add); return list; } } private void forEach(Consumer<DownloadTask> consumer) { synchronized (tasks) { for (DownloadTask d : tasks) { if(d != null) consumer.accept(d); } } } public static final DownloadTasks EMPTY = constant("EMPTY"); public static final DownloadTasks COMPLETED = constant("COMPLETED"); private DownloadTasks() { this.pageUrl = null; this.folder = null; this.toParent = false; tasks = null; } private static DownloadTasks constant(String name) { String s = "ScrappingResult"+name; return new DownloadTasks() { @Override public String getUrl() { throw new IllegalAccessError(); } @Override public int size() { throw new IllegalAccessError(); } @Override public int startDownload(ExecutorService ex) { throw new IllegalAccessError(); } @Override public List<DownloadTask> failedTasks() { throw new IllegalAccessError(); } @Override public String toString() { return s; } }; } void remove(int index) { synchronized(tasks) { tasks[index] = null; } } }
true
d4ab2f0e5d15730025659b218f5552947e7e1f64
Java
JOSEPHVIJAYS/Day2_Assignment
/MissingElementArray.java
UTF-8
387
3.265625
3
[]
no_license
package day2assignment; import java.util.Arrays; public class MissingElementArray { public static void main(String[] args) { int arr[] = {0,1,2,3,4,7,6,8}; Arrays.sort(arr); System.out.println("sorted it"); for ( int i=0; i<arr.length;i++) { System.out.println(arr[i]); if(arr[i]!=i) { System.out.println("Missing" + i); break; } } } }
true
a4de6650b215d430e0f77e4e2d98c1842af1050a
Java
IITDBGroup/VagabondGUI
/src/org/vagabond/rcp/controller/TargetDBViewActionGroup.java
UTF-8
6,595
1.742188
2
[]
no_license
package org.vagabond.rcp.controller; import java.sql.Connection; import java.sql.ResultSet; import java.util.Iterator; import org.apache.log4j.Logger; import org.eclipse.jface.action.Action; import org.eclipse.jface.action.IMenuManager; import org.eclipse.jface.action.Separator; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.wizard.WizardDialog; import org.vagabond.explanation.generation.prov.SourceProvParser; import org.vagabond.rcp.Activator; import org.vagabond.rcp.controller.TableNavHandler.SCHEMA_TYPE; import org.vagabond.rcp.gui.views.ProvenanceView; import org.vagabond.rcp.gui.views.SourceDBView; import org.vagabond.rcp.util.PluginLogProvider; import org.vagabond.rcp.DetailSelection.DetailSelectionPage; import org.vagabond.rcp.DetailSelection.DetailSelectionWizard; import org.vagabond.rcp.wizards.ExplGenPage; import org.vagabond.rcp.wizards.ExplGenWizard; import org.vagabond.util.ConnectionManager; import org.vagabond.util.LoggerUtil; import com.quantum.Messages; import com.quantum.model.Bookmark; import com.quantum.model.BookmarkCollection; import com.quantum.sql.MultiSQLServer; import com.quantum.sql.SQLResultSetResults; import com.quantum.sql.SQLResults; import com.quantum.view.tableview.TableView; public class TargetDBViewActionGroup extends DBViewActionGroup { static Logger log = PluginLogProvider.getInstance().getLogger( TargetDBViewActionGroup.class); private final TableView tableView; class ShowProvenanceAction extends Action { final Logger pLog = PluginLogProvider.getInstance().getLogger( ShowProvenanceAction.class); public ShowProvenanceAction() { setText(Messages.getString("tableview.provenance")); } @SuppressWarnings("unchecked") public void run() { SQLResultSetResults resultSet = getSelectedSQLResults(); IStructuredSelection selection = getTableRowSelection(); String relations = ""; String tids = ""; if (resultSet == null || resultSet.isMetaData() || selection.size() < 1) { MessageDialog.openInformation( tableView.getSite().getShell(),"Operation not allowed","Please select at least 1 row to view provenance."); return; } SourceDBView.getInstance().resetSelections(); for (Iterator<SQLResultSetResults.Row> i = (Iterator<SQLResultSetResults.Row>) selection.iterator(); i.hasNext();) { SQLResultSetResults.Row r = i.next(); if (relations != "" && tids != "") { if (!relations.contains(resultSet.getName())) relations = relations + ", target." + resultSet.getName(); tids = tids + ", '" + r.get(1).toString() + "'"; } else { relations = "target." + resultSet.getName(); tids = "'" + r.get(1).toString() + "'"; } } try { String query = provQuery(relations, tids); SourceProvParser parser = selectProvenance(query); SourceDBView.getInstance().highlightProvenance(parser); SQLResultSetResults results = provResultSet(query); ProvenanceView.getInstance().showProvenance(results); } catch (Exception e) { LoggerUtil.logException(e, pLog); } } }; class ExplGenAction extends Action { public ExplGenAction() { setText(Messages.getString("tableview.expl")); } public void run() { SQLResultSetResults resultSet = getSelectedSQLResults(); IStructuredSelection selection = getTableRowSelection(); if (resultSet == null || resultSet.isMetaData() || selection.size() < 1) { MessageDialog.openInformation( tableView.getSite().getShell(),"Operation not allowed","Please select at least 1 row to view explanations."); return; } ExplGenPage page = new ExplGenPage(""); //$NON-NLS-1$ ExplGenWizard wizard = new ExplGenWizard(); wizard.init(Messages.getString("TableView.ExplGen"), page, resultSet, selection); //$NON-NLS-1$ WizardDialog dialog = new WizardDialog( tableView.getSite().getShell(), wizard); dialog.open(); if (dialog.getReturnCode() == 0) { } } }; //detailed selection class DetailSelection extends Action{ public DetailSelection() { setText(Messages.getString("User-defined selection")); } public void run(){ SQLResultSetResults rs = getSelectedSQLResults(); String relname=rs.getName(); TableNavHandler.getInstance(); SQLResultSetResults resultSet = TableNavHandler.getResultSet(SCHEMA_TYPE.TARGET,relname); DetailSelectionPage dsp=new DetailSelectionPage("",resultSet,relname); DetailSelectionWizard wizard=new DetailSelectionWizard(dsp); WizardDialog dialog = new WizardDialog( tableView.getSite().getShell(), wizard); dialog.open(); } }; private ShowProvenanceAction showProvenanceAction; private ExplGenAction explGenAction; private DetailSelection detailSelection; public TargetDBViewActionGroup(TableView tableView) { super(tableView); this.tableView = tableView; this.showProvenanceAction = new ShowProvenanceAction(); this.explGenAction = new ExplGenAction(); this.detailSelection=new DetailSelection(); } private SQLResultSetResults getSelectedSQLResults() { return this.tableView.getSelectedResultSet(); } // private SQLResultSetResults.Row getSelection() { // return this.tableView.getSelectedFirstRow(); // } private IStructuredSelection getTableRowSelection() { return this.tableView.getTableRowSelection(); } public void fillContextMenu(IMenuManager menuManager) { menuManager.add(this.showProvenanceAction); menuManager.add(this.explGenAction); menuManager.add(this.detailSelection); menuManager.add(new Separator()); super.fillContextMenu(menuManager); } private String provQuery(String tableNames, String tids) { String query = "SELECT PROVENANCE * FROM "+ tableNames +" WHERE tid IN ("+ tids +")"; return query; } private SourceProvParser selectProvenance(String query) throws Exception { ResultSet rs = ConnectionManager.getInstance().execQuery(query); SourceProvParser parser = new SourceProvParser(rs); return parser; } private SQLResultSetResults provResultSet(String query) throws Exception { String databaseString = Activator.getDefault().getPreferenceStore().getString("DATABASE"); Bookmark bookmark = BookmarkCollection.getInstance().find(databaseString); Connection c = ConnectionManager.getInstance().getConnection(); SQLResults results = MultiSQLServer.getInstance().execute(bookmark, c, query); ((SQLResultSetResults)results).setName("Provenance"); return (SQLResultSetResults)results; } }
true
24a9820dfcacec2dbe92e57daa91e89497e56f8c
Java
let-sgo/Notes_node
/studytime/src/project/com/bo/Notes.java
UTF-8
961
2.375
2
[]
no_license
package project.com.bo; public class Notes { long sno; long id; int sem_id; String subcode; String subject; String file_name; public long getSno() { return sno; } public void setSno(long sno) { this.sno = sno; } public long getId() { return id; } public void setId(long id) { this.id = id; } public int getSem_id() { return sem_id; } public void setSem_id(int sem_id) { this.sem_id = sem_id; } public String getSubcode() { return subcode; } public void setSubcode(String subcode) { this.subcode = subcode; } public String getSubject() { return subject; } public void setSubject(String subject) { this.subject = subject; } public String getFile_name() { return file_name; } public void setFile_name(String file_name) { this.file_name = file_name; } @Override public String toString() { return "Notes [sno=" + sno + ", id=" + id + ", sem_id=" + sem_id + ", subcode=" + subcode + ", subject=" + subject + ", file_name=" + file_name + "]"; } }
true
9a909f6e494ec895e1fd565afb7708bc82ade9f3
Java
Baishu/megamek
/megamek/src/megamek/common/logging/LogLevel.java
UTF-8
2,468
2.4375
2
[]
no_license
/* * MegaMek - Copyright (C) 2000-2011 Ben Mazur (bmazur@sev.org) * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 2 of the License, or (at your option) * any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * for more details. */ package megamek.common.logging; import megamek.common.annotations.Nullable; import org.apache.log4j.Level; import java.util.ArrayList; import java.util.List; /** * Created with IntelliJ IDEA. * * @version $Id$ * @author: Deric "Netzilla" Page (deric dot page at usa dot net) * @since: 9/7/13 9:31 AM */ public enum LogLevel { OFF(Level.OFF), FATAL(Level.FATAL), ERROR(Level.ERROR), WARNING(Level.WARN), INFO(Level.INFO), DEBUG(Level.DEBUG), TRACE(Level.TRACE); private final Level level; LogLevel(Level level) { this.level = level; } public Level getLevel() { return level; } public int toInt() { return level.toInt(); } public static String[] getLogLevelNames() { List<String> out = new ArrayList<>(); for (LogLevel l : values()) { out.add(l.toString()); } return out.toArray(new String[out.size()]); } public static LogLevel getLogLevel(final String levelName) { for (LogLevel l : values()) { if (l.toString().equalsIgnoreCase(levelName)) { return l; } } return null; } @Nullable public static LogLevel getFromLog4jLevel(final int level) { if (Level.FATAL_INT == level) { return FATAL; } else if (Level.ERROR_INT == level) { return ERROR; } else if (Level.WARN_INT == level) { return WARNING; } else if (Level.INFO_INT == level) { return INFO; } else if (Level.DEBUG_INT == level) { return DEBUG; } else if (Level.TRACE_INT == level) { return TRACE; } else if (Level.OFF_INT == level) { return OFF; } return null; } }
true
aecc274544378a1654a6e754a5ea8b106bb5991e
Java
skill-lang/skilled
/de.unistuttgart.iste.ps.skilled.ui/src/de/unistuttgart/iste/ps/skilled/ui/views/ToolViewButtonInitializer.java
UTF-8
6,264
2.5625
3
[]
no_license
package de.unistuttgart.iste.ps.skilled.ui.views; import java.util.NoSuchElementException; import org.eclipse.jface.action.Action; import org.eclipse.jface.action.IToolBarManager; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.window.Window; import org.eclipse.jface.wizard.WizardDialog; import org.eclipse.ui.IActionBars; import de.unistuttgart.iste.ps.skilled.sir.Tool; import de.unistuttgart.iste.ps.skilled.tools.SIRHelper; import de.unistuttgart.iste.ps.skilled.ui.tools.ToolUtil; import de.unistuttgart.iste.ps.skilled.ui.wizards.toolWizard.SKilLToolWizard; import de.unistuttgart.iste.ps.skilled.ui.wizards.toolWizard.WizardOption; /** * this class is used to initialize the buttons displayed in the {@link ToolView * toolview} * * @author Ken Singer * @author Marco Link * @category GUI */ public class ToolViewButtonInitializer { private Action createToolAction; private Action cloneToolAction; private Action removeHintAction; private ToolView toolView; public ToolViewButtonInitializer(ToolView toolview) { this.toolView = toolview; } /** * make the Actions for the buttons in the {@link ToolView toolview}. * * @category GUI */ private void makeActions() { // Action for create tool button createToolAction = new Action() { @Override public void run() { runCreateToolDialog(); } }; createToolAction.setText("Create Tool"); createToolAction.setToolTipText("opens a wizard to create a new tool"); // Action for clone tool button cloneToolAction = new Action() { @Override public void run() { cloneToolDialog(); } }; cloneToolAction.setText("Clone Tool"); cloneToolAction.setToolTipText("opens a wizard to clone an existing tool."); // Action for remove hints in tools button removeHintAction = new Action() { @Override public void run() { removeHintsFromTools(); } }; removeHintAction.setText("Remove Hints"); removeHintAction.setToolTipText("opens a wizard to remove hint from tools."); } /** * Creates a new {@link Tool tool}. * * @category Dialog */ private void runCreateToolDialog() { final SKilLToolWizard sKilLToolWizard = new SKilLToolWizard(WizardOption.CREATE, SIRHelper.getTools(toolView.getActiveProject())); WizardDialog wizardDialog = new WizardDialog(toolView.getShell(), sKilLToolWizard); if (wizardDialog.open() == Window.OK) { String newToolName = sKilLToolWizard.getToolNewName(); if (newToolName == null) return; Tool t = ToolUtil.createNewTool(toolView.getActiveProject(), newToolName, sKilLToolWizard.getAddAllCheckboxState()); toolView.refresh(); toolView.setActiveTool(t); } } /** * opens the dialog to clone a existing {@link Tool tool} * * @category Dialog */ private void cloneToolDialog() { final SKilLToolWizard skillToolWizard = new SKilLToolWizard(WizardOption.CLONE, toolView.getSkillFile().Tools()); WizardDialog wizardDialog = new WizardDialog(toolView.getShell(), skillToolWizard); if (wizardDialog.open() == Window.OK) { String newToolName = skillToolWizard.getToolNewName(); Tool cloneTool; try { cloneTool = toolView.getSkillFile().Tools().stream() .filter(t -> t.getName().equals(skillToolWizard.getCloneToolName())).findFirst().get(); } catch (NoSuchElementException e) { showMessage("Could not create tool."); return; } if (newToolName == null) return; if (!ToolUtil.cloneTool(toolView.getActiveProject(), cloneTool, newToolName, toolView.getSkillFile())) { showMessage("Could not create tool."); return; } toolView.refresh(); } } /** * Show a message window with the passed string. * * @param message * - {@link String Message} which should be displayed. * @category Dialog */ private static void showMessage(String message) { MessageDialog.openInformation(null, "Tool View", message); } /** * Open a wizard to select tools where hints should be deleted. * * @category GUI */ private void removeHintsFromTools() { throw new NoSuchMethodError(); // final SKilLToolWizard skillToolWizard = new // SKilLToolWizard(WizardOption.REMOVEHINTS, // toolview.getSkillFile().Tools()); // WizardDialog wizardDialog = new WizardDialog(toolview.getShell(), // skillToolWizard); // if (wizardDialog.open() == Window.OK) { // ArrayList<Tool> removeHints = // skillToolWizard.getRemoveHintsFromTools(); // for (Tool tempTool : removeHints) { // for (Type tempType : tempTool.getTypes()) { // for (Field tempField : tempType.getFields()) { // if (tempField.getHints().size() > 0) // ToolUtil.removeAllFieldHints(this.toolview.getActiveProject(), // tempTool, tempType, // tempField); // } // if (tempType.getHints().size() > 0) // ToolUtil.removeAllTypeHints(this.toolview.getActiveProject(), // tempTool, tempType); // } // } // toolview.refresh(); // } } /** * Add the buttons to the {@link ToolView}. * * @category GUI */ private void fillLocalToolBar() { IActionBars bars = toolView.getViewSite().getActionBars(); IToolBarManager manager = bars.getToolBarManager(); manager.add(createToolAction); manager.add(cloneToolAction); manager.add(removeHintAction); } /** * initializes the buttons */ public void initialize() { makeActions(); fillLocalToolBar(); } }
true
09301cfe12fcc42018f2d0ce957b50b30a95edc9
Java
Augustocastilho/TrabalhoOC
/src/Instrucoes/Instrucoes.java
UTF-8
2,511
3.3125
3
[]
no_license
package Instrucoes; /** * Constroi uma operacao de qualquer tipo */ public class Instrucoes { private String valor; private long valorDecimal; private long op; //6 bits private long rs; //5 bits private long rt; //5 bits private long rd; //5 bits private long shamt; //5 bits private long funct; //6 bits private long address; //16 bits public Instrucoes() { this.valor = null; valorDecimal = 0; } public String getValor() { return valor; } public void setValor(String valor) { this.valor = valor; } /** * Converte a representacao binaria em um valor inteiro * * @param val String com o valor a ser convertido */ public long converteValor(String val) { long novoVal = 0; for (int i = 0; i < val.length(); i++) { char x = val.charAt(val.length() - 1 - i); if (x == '1') { long y = (long) Math.pow(2, i); novoVal = novoVal + y; } } return novoVal; } public long getValorDecimal() { return this.valorDecimal; } public void setValorDecimal(long valor) { this.valorDecimal = valor; } public void atribuiValores() { this.op = converteValor(getValor().substring(0, 6)); this.rs = converteValor(getValor().substring(6, 11)); this.rt = converteValor(getValor().substring(11, 16)); if (getOp() != 0) { //intrucoes tipo I e J this.address = converteValor(getValor().substring(16, 32)); } else { //instrucoes tipo R this.rd = converteValor(getValor().substring(16, 21)); this.shamt = converteValor(getValor().substring(21, 26)); this.funct = converteValor(getValor().substring(26, 32)); } } public long getOp() { return op; } public long getRs() { return rs; } public long getRt() { return rt; } public long getRd() { return rd; } public long getShamt() { return shamt; } public long getFunct() { return funct; } public long getAddress() { return address; } public void setRS(long valor) { this.rs = valor; } public void clear() { valor = null; valorDecimal = 0; op = 0; rs = 0; rt = 0; rd = 0; shamt = 0; funct = 0; address = 0; } }
true
4c9df2d4bd241abe26c362932982d146d56141f7
Java
GUMILLANF/RegisterUserBackend
/src/main/java/com/gustavofernandes/registeruserbackend/service/UserService.java
UTF-8
677
1.851563
2
[]
no_license
package com.gustavofernandes.registeruserbackend.service; import com.gustavofernandes.registeruserbackend.model.User; import com.gustavofernandes.registeruserbackend.service.exception.InvalidEmailException; import com.gustavofernandes.registeruserbackend.service.exception.InvalidTokenException; import com.gustavofernandes.registeruserbackend.service.exception.LoginUnavailableException; public interface UserService { User save(User user) throws LoginUnavailableException, InvalidEmailException; User edit(Long id, User user) throws InvalidEmailException; void updateUnsetEmail(User user); User validate(String login); void triggerEmail(User user); }
true
568353176f37d8b46e07d2dd3c1e0d03e9bfaa19
Java
Akirus/octave-web-app
/src/main/java/me/alextur/matlab/rest/config/CorsFilter.java
UTF-8
1,376
2.03125
2
[]
no_license
package me.alextur.matlab.rest.config; import org.apache.catalina.connector.RequestFacade; import org.apache.log4j.Logger; import org.springframework.core.Ordered; import org.springframework.core.annotation.Order; import org.springframework.stereotype.Component; import javax.servlet.*; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; /** * @author Alex Turchynovich */ @Component @Order(Ordered.HIGHEST_PRECEDENCE) class CorsFilter implements Filter { private static final Logger logger = Logger.getLogger(CorsFilter.class); public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) { HttpServletResponse response = (HttpServletResponse) res; response.setHeader("Access-Control-Allow-Origin", "*"); response.setHeader("Access-Control-Allow-Methods", "POST, PUT, GET, OPTIONS, DELETE"); response.setHeader("Access-Control-Allow-Headers", "Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With, X-ACCESS-TOKEN"); response.setHeader("Access-Control-Max-Age", "3600"); try { chain.doFilter(req, res); } catch (IOException | ServletException pE) { logger.error("Erorr", pE); } } public void init(FilterConfig filterConfig) {} public void destroy() {} }
true
e6ad3896187b2535e8e9e861526a63a273209d3f
Java
RainbowCookiz/2012-Rumblebee
/src/io/IOConstants.java
UTF-8
2,254
2.28125
2
[]
no_license
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package io; /** * This class will provide access to the channels of each * device on connected to the cRIO and the slots of cRIO modules. * @author 708 */ public class IOConstants{ public class crioModules{ public static final int kModule1 = 1; public static final int kModule2 = 2; } public class Driverstation{ public static final int driver_Gamepad = 1; public static final int operator_Gamepad = 2; } public class PWMChannels{ public static final int kLeftMotor = 1; public static final int kRightMotor = 2; public static final int kFlyWheelMotor = 3; public static final int kRotationMotor = 4; public static final int kArmMotor = 5; } public class RelayChannels{ public static final int kLowerMotor = 1; public static final int kUpperMotor = 5; public static final int kBrushSpike = 3; public static final int kArmSpike = 4; } public class DigitalIOChannels{ public static final int kLeftEncoderA = 1; public static final int kLeftEncoderB = 2; public static final int kRightEncoderA = 3; public static final int kRightEncoderB = 4; public static final int kShooterEncoderA = 5; public static final int kShooterEncoderB = 6; public static final int kLeftLimit = 7; public static final int kRightLimit = 8; public static final int kArmUp = 9; public static final int kArmDown = 10; public static final int kBrushVertical = 11; } public class AnalogInputChannels{ public static final int kGyro = 1; public static final int kTopBallSensor = 2; public static final int kEntranceSensor = 3; public static final int kMiddleBallSensor = 4; public static final int kBottomBallSensor = 5; public static final int kShooterPot = 6; public static final int kArmPot = 7; } public class SolenoidChannels{ public static final int kGatePiston = 1; } public class Network{ public static final String cameraIP = "10.7.8.11"; } }
true
e07c05481e4a722ded456de13cee16f29c794271
Java
aquenneville/coin-taxinomy-db
/coin-taxinomy-db-server/src/main/java/com/example/demo/web/controller/AssetPartnershipController.java
UTF-8
349
1.554688
2
[ "MIT" ]
permissive
package com.example.demo.web.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import com.example.demo.service.AssetPartnershipService; @Controller public class AssetPartnershipController { @Autowired AssetPartnershipService assetPartnershipService; }
true
1d7144bf2c0daead838c733d82d56b152192c145
Java
charles-wangkai/codeforces
/1846/C/Main.java
UTF-8
1,718
3.125
3
[]
no_license
import java.util.Arrays; import java.util.Comparator; import java.util.Scanner; import java.util.stream.IntStream; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int t = sc.nextInt(); for (int tc = 0; tc < t; ++tc) { int n = sc.nextInt(); int m = sc.nextInt(); int h = sc.nextInt(); int[][] times = new int[n][m]; for (int i = 0; i < times.length; ++i) { for (int j = 0; j < times[i].length; ++j) { times[i][j] = sc.nextInt(); } } System.out.println(solve(times, h)); } sc.close(); } static int solve(int[][] times, int h) { Outcome firstOutcome = computeBestOutcome(h, times[0]); return (int) IntStream.range(1, times.length) .mapToObj(i -> computeBestOutcome(h, times[i])) .filter( outcome -> Comparator.comparing(Outcome::point) .reversed() .thenComparing(Outcome::penalty) .compare(outcome, firstOutcome) < 0) .count() + 1; } static Outcome computeBestOutcome(int h, int[] time) { Arrays.sort(time); long[] prefixSums = new long[time.length]; for (int i = 0; i < prefixSums.length; ++i) { prefixSums[i] = ((i == 0) ? 0 : prefixSums[i - 1]) + time[i]; } return new Outcome( (int) Arrays.stream(prefixSums).filter(prefixSum -> prefixSum <= h).count(), Arrays.stream(prefixSums).filter(prefixSum -> prefixSum <= h).sum()); } } record Outcome(int point, long penalty) {}
true
cc9b1ca451f0c559977f008b83be1e45aa6c6185
Java
mapkon/toy-robot-challenge
/src/main/java/com/rea/interviews/command/impl/UnknownCommand.java
UTF-8
672
2.625
3
[]
no_license
package com.rea.interviews.command.impl; import com.rea.interviews.Constants; import com.rea.interviews.command.Command; import com.rea.interviews.command.CommandFactory; import com.rea.interviews.command.InvocationContext; import com.rea.interviews.robot.Robot; /** * Modes an unknown command that is passed in as part of the invocation context. * * @see Command * @see CommandFactory * @see InvocationContext * * @author Night King * */ public class UnknownCommand implements Command<Robot> { @Override public Robot execute(Robot robot, InvocationContext context) { System.err.println(Constants.WRONG_COMMAND.concat(context.getArgs())); return robot; } }
true
5c9c3ff8154630f4987d8aca5ef2dc3de6f811cd
Java
zaproxy/zaproxy
/zap/src/main/java/org/zaproxy/zap/view/messagelocation/AbstractMessageLocationsPanel.java
UTF-8
15,392
1.695313
2
[ "Apache-2.0" ]
permissive
/* * Zed Attack Proxy (ZAP) and its related class files. * * ZAP is an HTTP/HTTPS proxy for assessing web application security. * * Copyright 2015 The ZAP Development Team * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.zaproxy.zap.view.messagelocation; import java.awt.Component; import javax.swing.JCheckBox; import javax.swing.JOptionPane; import javax.swing.ListSelectionModel; import javax.swing.SortOrder; import javax.swing.table.DefaultTableCellRenderer; import javax.swing.table.TableCellEditor; import javax.swing.table.TableCellRenderer; import org.jdesktop.swingx.JXTable; import org.parosproxy.paros.Constant; import org.parosproxy.paros.view.View; import org.zaproxy.zap.extension.httppanel.ComponentChangedEvent; import org.zaproxy.zap.extension.httppanel.MessagePanelEventListener; import org.zaproxy.zap.extension.httppanel.MessageViewSelectedEvent; import org.zaproxy.zap.extension.httppanel.view.HttpPanelView; import org.zaproxy.zap.model.MessageLocation; import org.zaproxy.zap.view.AbstractMultipleOptionsBaseTablePanel; /** * An {@code AbstractMultipleOptionsBaseTablePanel} that allows to manage highlights and message * locations. * * @param <T> the type that contains the details of the highlight and message location * @param <S> the type of the table model that contains the elements with the details * @since 2.4.0 * @see MessageLocationTableEntry * @see MessageLocationsTableModel */ @SuppressWarnings("serial") public abstract class AbstractMessageLocationsPanel< T extends MessageLocationTableEntry, S extends MessageLocationsTableModel<T>> extends AbstractMultipleOptionsBaseTablePanel<T> { private static final long serialVersionUID = -8990789229815588716L; private static final String REMOVE_DIALOG_TITLE = Constant.messages.getString("messagelocationspanel.dialog.remove.location.title"); private static final String REMOVE_DIALOG_TEXT = Constant.messages.getString("messagelocationspanel.dialog.remove.location.text"); private static final String REMOVE_DIALOG_CONFIRM_BUTTON_LABEL = Constant.messages.getString( "messagelocationspanel.dialog.remove.location.button.confirm"); private static final String REMOVE_DIALOG_CANCEL_BUTTON_LABEL = Constant.messages.getString( "messagelocationspanel.dialog.remove.location.button.cancel"); private static final String REMOVE_DIALOG_CHECKBOX_LABEL = Constant.messages.getString( "messagelocationspanel.dialog.remove.location.checkbox.label"); private MessageLocationProducerFocusListener addButtonFocusListenerEnabler; private SelectMessageLocationsPanel selectMessageLocationsPanel; private final Component parent; public AbstractMessageLocationsPanel( Component parent, SelectMessageLocationsPanel selectMessageLocationsPanel, S model) { this(parent, selectMessageLocationsPanel, model, false); } public AbstractMessageLocationsPanel( Component parent, SelectMessageLocationsPanel selectMessageLocationsPanel, S model, boolean allowModifications) { super(model, allowModifications); this.parent = parent; this.selectMessageLocationsPanel = selectMessageLocationsPanel; this.selectMessageLocationsPanel.addMessagePanelEventListener( createMessagePanelEventListener()); getModel().addMessageLocationHighlightChangedListener(createHighlightChangedListener()); addButton.setEnabled(false); addButton.setToolTipText( Constant.messages.getString("messagelocationspanel.add.location.tooltip")); addButtonFocusListenerEnabler = createFocusListener(); getTable().setSortOrder(1, SortOrder.ASCENDING); getTable() .setDefaultRenderer( MessageLocationHighlight.class, new DefaultMessageLocationHighlightRenderer()); getRemoveWithoutConfirmationCheckBox().setSelected(true); } protected MessagePanelEventListener createMessagePanelEventListener() { return new MessagePanelEventListener() { @Override public void componentChanged(ComponentChangedEvent event) { for (T entry : getModel().getElements()) { MessageLocationHighlight highlight = entry.getHighlight(); if (highlight != null) { MessageLocationHighlight highlightReference = selectMessageLocationsPanel.highlight( entry.getLocation(), highlight); entry.setHighlightReference(highlightReference); } } } @Override public void viewSelected(MessageViewSelectedEvent event) { HttpPanelView view = event.getCurrentView(); if (view instanceof MessageLocationHighlighter) { MessageLocationHighlighter highlighter = (MessageLocationHighlighter) view; for (T entry : getModel().getElements()) { MessageLocationHighlight highlight = entry.getHighlight(); if (highlight != null) { MessageLocationHighlight highlightReference = highlighter.highlight(entry.getLocation(), highlight); entry.setHighlightReference(highlightReference); } } } else { for (T entry : getModel().getElements()) { entry.setHighlightReference(null); } } } }; } protected HighlightChangedListener<T> createHighlightChangedListener() { return new MessageLocationsHighlightChangedListener(); } @Override protected JXTable createTable() { MessageLocationsTable table = new MessageLocationsTable(); table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); table.setColumnControlVisible(true); return table; } public MessageLocationProducerFocusListener getFocusListenerAddButtonEnabler() { return addButtonFocusListenerEnabler; } protected MessageLocationProducerFocusListener createFocusListener() { return new MessageLocationsFocusListener(); } @Override public T showAddDialogue() { addButton.setEnabled(false); return addMessageLocationImpl(true, selectMessageLocationsPanel.getSelection()); } public boolean addMessageLocation(MessageLocation messageLocation) { if (messageLocation == null) { throw new IllegalArgumentException("Parameter messageLocation must not be null."); } return addMessageLocationImpl(false, messageLocation) != null; } private T addMessageLocationImpl(boolean buttonAddedLocation, MessageLocation messageLocation) { for (T locationUI : getModel().getElements()) { if (locationUI.getLocation().overlaps(messageLocation)) { View.getSingleton() .showWarningDialog( Constant.messages.getString( "messagelocationspanel.add.location.warning.locations.overlap")); return null; } } MessageLocationHighlight highlight = null; MessageLocationHighlight highlightReference = null; MessageLocationHighlightsManager highlightsManager = selectMessageLocationsPanel.create(); if (highlightsManager != null) { highlight = highlightsManager.getHighlight(messageLocation); highlightReference = selectMessageLocationsPanel.highlight(messageLocation, highlight); } T entry = createMessageLocationTableEntry( buttonAddedLocation, messageLocation, highlight, highlightReference); if (entry == null) { if (highlightsManager != null) { selectMessageLocationsPanel.removeHighlight(messageLocation, highlightReference); } return null; } getModel().addElement(entry); int row = getTable().convertRowIndexToView(getModel().getRow(entry)); getTable().setRowSelectionInterval(row, row); return null; } protected abstract T createMessageLocationTableEntry( boolean buttonAddedLocation, MessageLocation messageLocation, MessageLocationHighlight highlight, MessageLocationHighlight highlightReference); @Override public T showModifyDialogue(T e) { return null; } @Override public boolean showRemoveDialogue(T e) { if (!getRemoveWithoutConfirmationCheckBox().isSelected()) { if (!showRemoveDialogueImpl(e)) { return false; } } MessageLocationHighlight highlightReference = e.getHighlightReference(); if (highlightReference != null) { selectMessageLocationsPanel.removeHighlight(e.getLocation(), highlightReference); } return true; } protected Component getParentOwner() { return parent; } protected boolean showRemoveDialogueImpl(T e) { JCheckBox removeWithoutConfirmationCheckBox = new JCheckBox(REMOVE_DIALOG_CHECKBOX_LABEL); Object[] messages = {REMOVE_DIALOG_TEXT, " ", removeWithoutConfirmationCheckBox}; int option = JOptionPane.showOptionDialog( View.getSingleton().getMainFrame(), messages, REMOVE_DIALOG_TITLE, JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, new String[] { REMOVE_DIALOG_CONFIRM_BUTTON_LABEL, REMOVE_DIALOG_CANCEL_BUTTON_LABEL }, null); if (option == JOptionPane.OK_OPTION) { getRemoveWithoutConfirmationCheckBox() .setSelected(removeWithoutConfirmationCheckBox.isSelected()); return true; } return false; } @Override public boolean isRemoveWithoutConfirmation() { // Force base class to call the method showRemoveDialogue(T1) so the // state of the panels can be changed before deleting the entries return false; } public void reset() { for (T entry : getMultipleOptionsModel().getElements()) { MessageLocationHighlight highlightReference = entry.getHighlightReference(); if (highlightReference != null) { selectMessageLocationsPanel.removeHighlight( entry.getLocation(), highlightReference); } } getMultipleOptionsModel().clear(); } @Override protected S getModel() { @SuppressWarnings("unchecked") // Safe cast it's the model that's set in the constructor (which can't be changed) S model = (S) super.getMultipleOptionsModel(); return model; } private static class DefaultMessageLocationHighlightRenderer extends DefaultTableCellRenderer { private static final long serialVersionUID = 427590735065539815L; @Override protected void setValue(Object value) {} } protected class MessageLocationsTable extends JXTable { private static final long serialVersionUID = -3277532157790764376L; @Override public TableCellEditor getCellEditor(int row, int column) { Class<?> columnClass = AbstractMessageLocationsPanel.this.getModel().getColumnClass(row, column); if (columnClass != null && MessageLocationHighlight.class.isAssignableFrom(columnClass)) { @SuppressWarnings("unchecked") TableCellEditor editor = MessageLocationHighlightRenderersEditors.getInstance() .getEditor((Class<? extends MessageLocationHighlight>) columnClass); if (editor != null) { return editor; } } return super.getCellEditor(row, column); } @Override public TableCellRenderer getCellRenderer(int row, int column) { Class<?> columnClass = AbstractMessageLocationsPanel.this.getModel().getColumnClass(row, column); if (columnClass != null && MessageLocationHighlight.class.isAssignableFrom(columnClass)) { @SuppressWarnings("unchecked") TableCellRenderer renderer = MessageLocationHighlightRenderersEditors.getInstance() .getRenderer( (Class<? extends MessageLocationHighlight>) columnClass); if (renderer != null) { return renderer; } } return super.getCellRenderer(row, column); } } protected class MessageLocationsHighlightChangedListener implements HighlightChangedListener<T> { @Override public void highlightChanged(HighlightChangedEvent<T> event) { T tableEntry = event.getEntry(); MessageLocationHighlight highlightReference = event.getHighlightReference(); if (highlightReference != null) { selectMessageLocationsPanel.removeHighlight( tableEntry.getLocation(), event.getHighlightReference()); } MessageLocationHighlight highlight = tableEntry.getHighlight(); if (highlight != null) { highlightReference = selectMessageLocationsPanel.highlight( tableEntry.getLocation(), tableEntry.getHighlight()); tableEntry.setHighlightReference(highlightReference); } } } protected class MessageLocationsFocusListener implements MessageLocationProducerFocusListener { @Override public void focusLost(MessageLocationProducerFocusEvent e) { if (e.getFocusEvent().getOppositeComponent() != addButton) { addButton.setEnabled(false); } } @Override public void focusGained(MessageLocationProducerFocusEvent e) { addButton.setEnabled(true); } } }
true
508c521a5d23aeb3e4db0c129cb27cf290c939c9
Java
KengoTODA/findbugs-slf4j
/bug-pattern/src/test/java/jp/skypencil/findbugs/slf4j/CodepointIteratorTest.java
UTF-8
814
2.5
2
[ "Apache-2.0" ]
permissive
package jp.skypencil.findbugs.slf4j; import static com.google.common.truth.Truth.assertThat; import org.junit.jupiter.api.Test; public class CodepointIteratorTest { @Test public void testAbc() { CodepointIterator iter = new CodepointIterator("abc"); assertThat(iter.next()).isEqualTo(Integer.valueOf('a')); assertThat(iter.next()).isEqualTo(Integer.valueOf('b')); assertThat(iter.next()).isEqualTo(Integer.valueOf('c')); } @Test public void testSurrogatePair() { CodepointIterator iter = new CodepointIterator("a𠮟c"); int expected = ("𠮟".charAt(0) << 16) + "𠮟".charAt(1); assertThat(iter.next()).isEqualTo(Integer.valueOf('a')); assertThat(iter.next()).isEqualTo(Integer.valueOf(expected)); assertThat(iter.next()).isEqualTo(Integer.valueOf('c')); } }
true
696ae4d6b7916ebdf68cbee563082adc3fb2b017
Java
ilyashpakovski/JD2019-12-03
/src/by/it/popkov/jd01_10/PrintMath.java
UTF-8
1,347
3.421875
3
[]
no_license
package by.it.popkov.jd01_10; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Modifier; class PrintMath { static void getContract(Class<?> aClass) { Method[] methods = aClass.getDeclaredMethods(); StringBuilder sb = new StringBuilder(); for (Method method : methods) { if (Modifier.isPublic(method.getModifiers())) { sb.append("public "); if (Modifier.isStatic(method.getModifiers())) { sb.append("static "); } sb.append(method.getReturnType().getName()).append(" ").append(method.getName()).append("("); Class<?>[] parameterTypes = method.getParameterTypes(); for (int i = 0; i < parameterTypes.length; i++) { sb.append(parameterTypes[i].getName()); if (i != parameterTypes.length - 1) sb.append(","); } sb.append(")").append("\n"); } } Field[] fields = aClass.getFields(); for (Field field : fields) { sb.append(field.getType().getName()).append(" ").append(field.getName()).append("\n"); } System.out.println(sb); } public static void main(String[] args) { getContract(Math.class); } }
true