blob_id
stringlengths 40
40
| __id__
int64 225
39,780B
| directory_id
stringlengths 40
40
| path
stringlengths 6
313
| content_id
stringlengths 40
40
| detected_licenses
list | license_type
stringclasses 2
values | repo_name
stringlengths 6
132
| repo_url
stringlengths 25
151
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringlengths 4
70
| visit_date
timestamp[ns] | revision_date
timestamp[ns] | committer_date
timestamp[ns] | github_id
int64 7.28k
689M
โ | star_events_count
int64 0
131k
| fork_events_count
int64 0
48k
| gha_license_id
stringclasses 23
values | gha_fork
bool 2
classes | gha_event_created_at
timestamp[ns] | gha_created_at
timestamp[ns] | gha_updated_at
timestamp[ns] | gha_pushed_at
timestamp[ns] | gha_size
int64 0
40.4M
โ | gha_stargazers_count
int32 0
112k
โ | gha_forks_count
int32 0
39.4k
โ | gha_open_issues_count
int32 0
11k
โ | gha_language
stringlengths 1
21
โ | gha_archived
bool 2
classes | gha_disabled
bool 1
class | content
stringlengths 7
4.37M
| src_encoding
stringlengths 3
16
| language
stringclasses 1
value | length_bytes
int64 7
4.37M
| extension
stringclasses 24
values | filename
stringlengths 4
174
| language_id
stringclasses 1
value | entities
list | contaminating_dataset
stringclasses 0
values | malware_signatures
list | redacted_content
stringlengths 7
4.37M
| redacted_length_bytes
int64 7
4.37M
| alphanum_fraction
float32 0.25
0.94
| alpha_fraction
float32 0.25
0.94
| num_lines
int32 1
84k
| avg_line_length
float32 0.76
99.9
| std_line_length
float32 0
220
| max_line_length
int32 5
998
| is_vendor
bool 2
classes | is_generated
bool 1
class | max_hex_length
int32 0
319
| hex_fraction
float32 0
0.38
| max_unicode_length
int32 0
408
| unicode_fraction
float32 0
0.36
| max_base64_length
int32 0
506
| base64_fraction
float32 0
0.5
| avg_csv_sep_count
float32 0
4
| is_autogen_header
bool 1
class | is_empty_html
bool 1
class | shard
stringclasses 16
values |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
5e8f5e0b80a3372c87f1a5a0da079e2a4723a652 | 31,903,017,085,553 | c6c8bed130b399a535738d668083feb434b80e78 | /project-gs/src/main/java/kr/co/controller/BoardController.java | 9e3e8546e7599c680cae7df935e53beafae7a203 | []
| no_license | hgm9157/project-gs | https://github.com/hgm9157/project-gs | 12aa5d8762d73dc6bf25594b139104df77a799b1 | e1a89c5903b1ba1adc523a4fee2011a50a43a1bd | refs/heads/master | 2023-02-10T07:54:50.137000 | 2021-01-08T02:30:25 | 2021-01-08T02:30:25 | 291,223,954 | 3 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package kr.co.controller;
import javax.inject.Inject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import kr.co.service.BoardService;
import kr.co.vo.BoardVO;
@Controller
public class BoardController {
@Inject
BoardService service;
private static final Logger logger = LoggerFactory.getLogger(BoardController.class);
@RequestMapping(value = "/board", method = RequestMethod.GET)
public String home(Model model) throws Exception {
model.addAttribute("list",service.list());
logger.info("board init");
return "/board";
}
// ๊ธ์ฐ๊ธฐ
@RequestMapping(value = "/writeView", method = RequestMethod.POST)
public void writeView() throws Exception{
logger.info("writeView");
}
// ๊ธ์ฐ๊ธฐ - ์์ฑ
@RequestMapping(value = "/write", method = RequestMethod.POST)
public String write(BoardVO boardVO) throws Exception{
logger.info("write");
service.write(boardVO);
return "redirect:/";
}
// ๊ธ ๋ชฉ๋ก ์กฐํ
@RequestMapping(value = "/list", method = RequestMethod.GET)
public String list(Model model) throws Exception{
logger.info("list");
model.addAttribute("list",service.list());
return "redirect:/";
}
//๊ธ ์กฐํ
@RequestMapping(value = "/readView", method = RequestMethod.POST)
public String read(BoardVO boardVO, Model model) throws Exception{
logger.info("read");
model.addAttribute("read",service.read(boardVO.getBno()));
return "viewContent";
}
// ๊ธ ์์ ํ๋ฉด
@RequestMapping(value = "/updateView", method = RequestMethod.GET)
public String updateView(BoardVO boardVO, Model model) throws Exception{
logger.info("updateView");
model.addAttribute("update",service.read(boardVO.getBno()));
return "updateView";
}
// ๊ธ ์์ ํ๋ฉด - ์์
@RequestMapping(value = "/update", method = RequestMethod.POST)
public String update(BoardVO boardVO) throws Exception{
logger.info("update");
service.update(boardVO);
return "redirect:/";
}
// ๊ธ ์์ ํ๋ฉด - ์ญ์
@RequestMapping(value = "/delete", method = RequestMethod.POST)
public String delete(BoardVO boardVO) throws Exception{
logger.info("delete");
service.delete(boardVO.getBno());
return "redirect:/";
}
}
| UTF-8 | Java | 2,457 | java | BoardController.java | Java | []
| null | []
| package kr.co.controller;
import javax.inject.Inject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import kr.co.service.BoardService;
import kr.co.vo.BoardVO;
@Controller
public class BoardController {
@Inject
BoardService service;
private static final Logger logger = LoggerFactory.getLogger(BoardController.class);
@RequestMapping(value = "/board", method = RequestMethod.GET)
public String home(Model model) throws Exception {
model.addAttribute("list",service.list());
logger.info("board init");
return "/board";
}
// ๊ธ์ฐ๊ธฐ
@RequestMapping(value = "/writeView", method = RequestMethod.POST)
public void writeView() throws Exception{
logger.info("writeView");
}
// ๊ธ์ฐ๊ธฐ - ์์ฑ
@RequestMapping(value = "/write", method = RequestMethod.POST)
public String write(BoardVO boardVO) throws Exception{
logger.info("write");
service.write(boardVO);
return "redirect:/";
}
// ๊ธ ๋ชฉ๋ก ์กฐํ
@RequestMapping(value = "/list", method = RequestMethod.GET)
public String list(Model model) throws Exception{
logger.info("list");
model.addAttribute("list",service.list());
return "redirect:/";
}
//๊ธ ์กฐํ
@RequestMapping(value = "/readView", method = RequestMethod.POST)
public String read(BoardVO boardVO, Model model) throws Exception{
logger.info("read");
model.addAttribute("read",service.read(boardVO.getBno()));
return "viewContent";
}
// ๊ธ ์์ ํ๋ฉด
@RequestMapping(value = "/updateView", method = RequestMethod.GET)
public String updateView(BoardVO boardVO, Model model) throws Exception{
logger.info("updateView");
model.addAttribute("update",service.read(boardVO.getBno()));
return "updateView";
}
// ๊ธ ์์ ํ๋ฉด - ์์
@RequestMapping(value = "/update", method = RequestMethod.POST)
public String update(BoardVO boardVO) throws Exception{
logger.info("update");
service.update(boardVO);
return "redirect:/";
}
// ๊ธ ์์ ํ๋ฉด - ์ญ์
@RequestMapping(value = "/delete", method = RequestMethod.POST)
public String delete(BoardVO boardVO) throws Exception{
logger.info("delete");
service.delete(boardVO.getBno());
return "redirect:/";
}
}
| 2,457 | 0.713448 | 0.71261 | 105 | 21.733334 | 23.34514 | 85 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.67619 | false | false | 13 |
8083a077934388c5543ac9d8125487ecd5decc05 | 23,682,449,671,518 | cdd63d0c67014dfeeb5b0f2d8f9e60bf05c4c43e | /common/src/main/java/eu/daiad/common/model/query/UtilityPopulationFilter.java | 9db6b60ebc1e57097653cdaa2df89513bcfc6ad3 | [
"Apache-2.0",
"BSD-2-Clause",
"OFL-1.1",
"MIT",
"BSD-3-Clause"
]
| permissive | DAIAD/home-web | https://github.com/DAIAD/home-web | aef34effa864863f141c6f0ebf26ab6a918ffe56 | be12eb04faea2f4e71bac402e503eec6fbe39c60 | refs/heads/master | 2023-03-20T12:05:04.391000 | 2022-02-22T07:20:33 | 2022-02-22T07:20:33 | 32,319,613 | 4 | 11 | Apache-2.0 | false | 2023-03-06T11:48:13 | 2015-03-16T11:12:54 | 2022-07-19T17:31:12 | 2023-03-06T11:48:08 | 19,992 | 4 | 9 | 33 | Java | false | false | package eu.daiad.common.model.query;
import java.util.UUID;
public class UtilityPopulationFilter extends PopulationFilter {
private UUID utility;
public UtilityPopulationFilter() {
super();
}
public UtilityPopulationFilter(String label) {
super(label);
}
public UtilityPopulationFilter(String label, UUID utility) {
super(label);
this.utility = utility;
}
public UtilityPopulationFilter(String label, UUID utility, Ranking ranking) {
super(label, ranking);
this.utility = utility;
}
public UtilityPopulationFilter(String label, UUID utility, EnumRankingType ranking, EnumMetric metric, int limit) {
super(label, new Ranking(ranking, metric, limit));
this.utility = utility;
}
public UUID getUtility() {
return utility;
}
@Override
public EnumPopulationFilterType getType() {
return EnumPopulationFilterType.UTILITY;
}
}
| UTF-8 | Java | 870 | java | UtilityPopulationFilter.java | Java | []
| null | []
| package eu.daiad.common.model.query;
import java.util.UUID;
public class UtilityPopulationFilter extends PopulationFilter {
private UUID utility;
public UtilityPopulationFilter() {
super();
}
public UtilityPopulationFilter(String label) {
super(label);
}
public UtilityPopulationFilter(String label, UUID utility) {
super(label);
this.utility = utility;
}
public UtilityPopulationFilter(String label, UUID utility, Ranking ranking) {
super(label, ranking);
this.utility = utility;
}
public UtilityPopulationFilter(String label, UUID utility, EnumRankingType ranking, EnumMetric metric, int limit) {
super(label, new Ranking(ranking, metric, limit));
this.utility = utility;
}
public UUID getUtility() {
return utility;
}
@Override
public EnumPopulationFilterType getType() {
return EnumPopulationFilterType.UTILITY;
}
}
| 870 | 0.751724 | 0.751724 | 44 | 18.772728 | 25.214411 | 116 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.363636 | false | false | 13 |
180bd544fd3662fa9c8a37d51cdfbdf9e4d33ab6 | 19,980,187,861,420 | 936701e15aff20ce988ba8ddf84d954fe6d19bf0 | /AP2014/src/SQL Server/src/CompileError/CompileError.java | e568cbec619a5fcd3afb69a113563b2513b142e4 | []
| no_license | sajjadrahnama/AUT_HWs | https://github.com/sajjadrahnama/AUT_HWs | 0c761c08b2a7f94ff2dcaef993c7e4fd5ce1f59e | c0e2e442ed48657a4c77b263cb28384d12b5c29f | refs/heads/master | 2021-06-09T00:41:21.852000 | 2016-12-07T19:59:50 | 2016-12-07T19:59:50 | 75,870,217 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package CompileError;
public class CompileError extends Exception{
/**
*
*/
String massage="Compile Error";
public String massage(){
return this.massage;
}
private static final long serialVersionUID = 1L;
}
| UTF-8 | Java | 236 | java | CompileError.java | Java | []
| null | []
| package CompileError;
public class CompileError extends Exception{
/**
*
*/
String massage="Compile Error";
public String massage(){
return this.massage;
}
private static final long serialVersionUID = 1L;
}
| 236 | 0.673729 | 0.669492 | 14 | 14.857142 | 16.634117 | 49 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.928571 | false | false | 13 |
18563aec7d732e05c594b8464369c57231be54c4 | 29,996,051,663,438 | a443c1ccace17996be7c790f8b74b1dbdd3a2dab | /app/src/main/java/com/univer/labs/books/controller/author/BooksByAuthorActivity.java | e84f52a1bfa5bb2fdaa8e307987f1e0df1a77670 | []
| no_license | TheMichelangelo/BooksAndroidApp | https://github.com/TheMichelangelo/BooksAndroidApp | b9ee5fb4f1956be4f1f28864a5172fed4a5f8394 | 62c489d3383cc79bc34f16a0ba512028feccefb6 | refs/heads/master | 2022-08-13T15:17:32.804000 | 2020-05-12T08:48:40 | 2020-05-12T08:48:40 | 262,430,587 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.univer.labs.books.controller.author;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.database.Cursor;
import android.os.Bundle;
import com.univer.labs.books.R;
import com.univer.labs.books.model.Author;
import com.univer.labs.books.model.GroupedBooks;
import com.univer.labs.books.service.AuthorService;
import com.univer.labs.books.service.BookService;
import java.util.List;
public class BooksByAuthorActivity extends AppCompatActivity {
private AuthorService authorService;
private BookService bookService;
private RecyclerView recyclerView;
private RecyclerView.Adapter mAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_books_by_author);
authorService = new AuthorService(this);
bookService = new BookService(this);
List<GroupedBooks> list = bookService.getAllBooksByAuthors();
recyclerView = findViewById(R.id.booksByAuthorView);
// specify an adapter
mAdapter = new AuthorsListQuerryAdapter2(this,list);
recyclerView.setAdapter(mAdapter);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
}
}
| UTF-8 | Java | 1,352 | java | BooksByAuthorActivity.java | Java | []
| null | []
| package com.univer.labs.books.controller.author;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.database.Cursor;
import android.os.Bundle;
import com.univer.labs.books.R;
import com.univer.labs.books.model.Author;
import com.univer.labs.books.model.GroupedBooks;
import com.univer.labs.books.service.AuthorService;
import com.univer.labs.books.service.BookService;
import java.util.List;
public class BooksByAuthorActivity extends AppCompatActivity {
private AuthorService authorService;
private BookService bookService;
private RecyclerView recyclerView;
private RecyclerView.Adapter mAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_books_by_author);
authorService = new AuthorService(this);
bookService = new BookService(this);
List<GroupedBooks> list = bookService.getAllBooksByAuthors();
recyclerView = findViewById(R.id.booksByAuthorView);
// specify an adapter
mAdapter = new AuthorsListQuerryAdapter2(this,list);
recyclerView.setAdapter(mAdapter);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
}
}
| 1,352 | 0.77071 | 0.76997 | 37 | 35.540539 | 21.790892 | 69 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.702703 | false | false | 13 |
cb71623761734763361c90cf3d90063123462408 | 29,996,051,666,712 | 18c4c3306b381263d6e697cc3d815c81c88d8351 | /app/src/main/java/com/example/bao/fragment/MainFragment.java | 8612c1425b157c7ade02f6cb722349c4b5c252cc | []
| no_license | ShuoRadio/Bao | https://github.com/ShuoRadio/Bao | 5fd29af5df0cf414b040437f7066cda6d8c297e8 | e9cc0be5b2260179e3af9add54273028c1fbc25f | refs/heads/master | 2022-11-06T07:54:49.401000 | 2020-06-19T07:51:41 | 2020-06-19T07:51:41 | 273,425,156 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.bao.fragment;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.ViewPager;
import com.bumptech.glide.Glide;
import com.example.bao.R;
import com.example.bao.activity.BuyMenuActivity;
import com.example.bao.adapter.CagegoryViewPagerAdapter;
import com.example.bao.adapter.EntranceAdapter;
import com.example.bao.adapter.ShopListViewAdapter;
import com.example.bao.model.ModelHomeEntrance;
import com.example.bao.model.Restaurant;
import com.example.bao.utils.MyDBHelper;
import com.example.bao.utils.ScreenUtil;
import com.example.bao.widget.IndicatorView;
import com.example.bao.widget.MyListView;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.Transformer;
import com.youth.banner.loader.ImageLoader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class MainFragment extends Fragment{
MyDBHelper myDBHelper;
private static MainFragment mainfragment;
List<Restaurant> restaurantList;
public static final int HOME_ENTRANCE_PAGE_SIZE = 10;//้ฆ้กต่ๅๅ้กตๆพ็คบๆฐ้
private ViewPager entranceViewPager;
private LinearLayout homeEntranceLayout;
private List<ModelHomeEntrance> homeEntrances;
private IndicatorView entranceIndicatorView;
ShopListViewAdapter shopListViewAdapter;
MyListView myListView;
Button btn_jl;
Button btn_pj;
View mainView;
Banner banner;
//ๅไพๆจกๅผ
public static MainFragment getMainFragment(){
if(mainfragment == null){
mainfragment = new MainFragment();
Log.i("test", "MainFragment่ขซๅๅปบ");
}
return mainfragment;
}
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view= inflater.inflate(R.layout.fragment_main,container,false);
mainView=inflater.inflate(R.layout.fragment_main,container,false);
return view;
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
initData();
initView();
init();
}
public void initView(){
homeEntranceLayout = (LinearLayout)getActivity().findViewById(R.id.main_home_entrance);
entranceViewPager=(ViewPager)getActivity().findViewById(R.id.main_home_entrance_vp);
entranceIndicatorView=(IndicatorView)getActivity().findViewById(R.id.main_home_entrance_indicator);
banner=getActivity().findViewById(R.id.main_banner1);
btn_jl=getActivity().findViewById(R.id.btn_sort_jl);
btn_pj=getActivity().findViewById(R.id.btn_sort_pj);
}
public void initData(){
homeEntrances = new ArrayList<>();
homeEntrances.add(new ModelHomeEntrance("็พ้ฃ", R.mipmap.ic_category_01));
homeEntrances.add(new ModelHomeEntrance("้ฅฑ้ฅฑ่ถ
ๅธ", R.mipmap.ic_category_02));
homeEntrances.add(new ModelHomeEntrance("็้ฒๆ่ฌ", R.mipmap.ic_category_03));
homeEntrances.add(new ModelHomeEntrance("้ฅฑไบไธ้", R.mipmap.ic_category_04));
homeEntrances.add(new ModelHomeEntrance("ๅฟซ้ฃ็ฎ้ค", R.mipmap.ic_category_05));
homeEntrances.add(new ModelHomeEntrance("ไธๅ่ถ", R.mipmap.ic_category_06));
homeEntrances.add(new ModelHomeEntrance("ๆซ่จๆฑๅ ก", R.mipmap.ic_category_07));
homeEntrances.add(new ModelHomeEntrance("ๆซ่จๆฑๅ ก", R.mipmap.ic_category_07));
homeEntrances.add(new ModelHomeEntrance("ๅฎถๅธธ่", R.mipmap.ic_category_08));
homeEntrances.add(new ModelHomeEntrance("ๅฐๅ้ฆ", R.mipmap.ic_category_09));
homeEntrances.add(new ModelHomeEntrance("้ฒ่ฑ่็ณ", R.mipmap.ic_category_010));
// homeEntrances.add(new ModelHomeEntrance("็พ้ฃ", R.mipmap.ic_category_0));
// homeEntrances.add(new ModelHomeEntrance("็ตๅฝฑ", R.mipmap.ic_category_1));
// homeEntrances.add(new ModelHomeEntrance("้
ๅบไฝๅฎฟ", R.mipmap.ic_category_2));
// homeEntrances.add(new ModelHomeEntrance("็ๆดปๆๅก", R.mipmap.ic_category_3));
// homeEntrances.add(new ModelHomeEntrance("KTV", R.mipmap.ic_category_4));
// homeEntrances.add(new ModelHomeEntrance("ๆ
ๆธธ", R.mipmap.ic_category_5));
// homeEntrances.add(new ModelHomeEntrance("ๅญฆไน ๅน่ฎญ", R.mipmap.ic_category_6));
// homeEntrances.add(new ModelHomeEntrance("ๆฑฝ่ฝฆๆๅก", R.mipmap.ic_category_7));
// homeEntrances.add(new ModelHomeEntrance("ๆๅฝฑๅ็", R.mipmap.ic_category_8));
// homeEntrances.add(new ModelHomeEntrance("ไผ้ฒๅจฑไน", R.mipmap.ic_category_10));
homeEntrances.add(new ModelHomeEntrance("ไธฝไบบ", R.mipmap.ic_category_11));
homeEntrances.add(new ModelHomeEntrance("่ฟๅจๅฅ่บซ", R.mipmap.ic_category_12));
homeEntrances.add(new ModelHomeEntrance("ๅคงไฟๅฅ", R.mipmap.ic_category_13));
homeEntrances.add(new ModelHomeEntrance("ๅข่ดญ", R.mipmap.ic_category_14));
homeEntrances.add(new ModelHomeEntrance("ๆฏ็น", R.mipmap.ic_category_16));
homeEntrances.add(new ModelHomeEntrance("ๅ
จ้จๅ็ฑป", R.mipmap.ic_category_15));
}
public void init() {
ScreenUtil.init(getContext());
LinearLayout.LayoutParams layoutParams12 = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, (int)((float)ScreenUtil.getScreenWidth() / 2.0f));
//้ฆ้กต่ๅๅ้กต
LinearLayout.LayoutParams entrancelayoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, (int)((float)ScreenUtil.getScreenWidth() / 2.0f + 70));
homeEntranceLayout.setLayoutParams(entrancelayoutParams);
entranceViewPager.setLayoutParams(layoutParams12);
// LayoutInflater inflater = LayoutInflater.from(getActivity());
//ๅฐRecyclerViewๆพ่ณViewPagerไธญ๏ผ
int pageSize = HOME_ENTRANCE_PAGE_SIZE;
//ไธๅ
ฑ็้กตๆฐ็ญไบ ๆปๆฐ/ๆฏ้กตๆฐ้๏ผๅนถๅๆดใ
int pageCount = (int) Math.ceil(homeEntrances.size() * 1.0 / pageSize);
List<View> viewList = new ArrayList<View>();
for (int index = 0; index < pageCount; index++) {
//ๆฏไธช้กต้ข้ฝๆฏinflateๅบไธไธชๆฐๅฎไพ
RecyclerView recyclerView = (RecyclerView)LayoutInflater.from(getContext()).inflate(R.layout.item_main_home_entrance_vp,null);
recyclerView.setLayoutParams(layoutParams12);
recyclerView.setLayoutManager(new GridLayoutManager(getContext(), 5));
EntranceAdapter entranceAdapter = new EntranceAdapter(getContext(), homeEntrances, index, HOME_ENTRANCE_PAGE_SIZE);
recyclerView.setAdapter(entranceAdapter);
viewList.add(recyclerView);
}
CagegoryViewPagerAdapter adapter = new CagegoryViewPagerAdapter(viewList,entranceViewPager);
entranceViewPager.setAdapter(adapter);
entranceIndicatorView.setIndicatorCount(entranceViewPager.getAdapter().getCount());
entranceIndicatorView.setCurrentIndicator(entranceViewPager.getCurrentItem());
entranceViewPager.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
@Override
public void onPageSelected(int position) {
entranceIndicatorView.setCurrentIndicator(position);
}
});
//่ฎพ็ฝฎๅพ็่ฝฎๆญ
setBanner();
//่ฎพ็ฝฎๅๅฎถๅ่กจ
setShopList();
//่ฎพ็ฝฎๆๅบ
setSort();
}
private void setBanner(){
List<Integer>imags=new ArrayList();
imags.add(R.drawable.main_banner_1);
// imags.add(R.drawable.main_banner_4);
imags.add(R.drawable.main_banner_5);
// imags.add(R.drawable.main_banner_6);
imags.add(R.drawable.main_banner_2);
imags.add(R.drawable.main_banner_3);
banner.setImageLoader(new ImageLoader() {
@Override
public void displayImage(Context context, Object path, ImageView imageView) {
Glide.with(context.getApplicationContext())
.load(path)
.into(imageView);
}
});
banner.setImages(imags);
banner.setBannerAnimation(Transformer.Default);
banner.setDelayTime(3000);
banner.setIndicatorGravity(BannerConfig.CENTER);
banner.start();
}
private void setShopList(){
myDBHelper=new MyDBHelper(getContext(),"Bao.db",null,1);
restaurantList=myDBHelper.selectRestaurant(null);
myListView =getActivity().findViewById(R.id.lv_main_shopListView);
shopListViewAdapter=new ShopListViewAdapter(restaurantList,getActivity().getBaseContext());
myListView.setAdapter(shopListViewAdapter);
//็นๅป่ฟๅ
ฅๅบๅฎถ่ๅ
myListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
TextView tv_shopName=view.findViewById(R.id.tv_item_Menuname);
String menuName= restaurantList.get(i).getbName();
Bundle bundle=new Bundle();
bundle.putSerializable("menuName",menuName);
Intent intent= new Intent(getContext(), BuyMenuActivity.class);
intent.putExtras(bundle);
startActivityForResult(intent,0000);
}
});
}
//่ฎพ็ฝฎๆๅบ
private void setSort(){
//ๆ นๆฎ่ฏไปทๆๅบ
btn_pj.setOnClickListener(new View.OnClickListener() {
@RequiresApi(api = Build.VERSION_CODES.N)
@Override
public void onClick(View view) {
btn_pj.setTextColor(getResources().getColor(R.color.theme));
btn_jl.setTextColor(getResources().getColor(R.color.balck));
Comparator<Restaurant> comparator1= new Comparator<Restaurant>() {
@Override
public int compare(Restaurant restaurant, Restaurant t1) {
if (restaurant.getbStar()> t1.getbStar())
return -1;
else if(restaurant.getbStar()< t1.getbStar())
return 1;
else return 0;
}
};
// restaurantList.sort(comparator1); //็ๆฌ่ฟไฝไธๆฏๆ
Collections.sort(restaurantList,comparator1);
shopListViewAdapter.notifyDataSetChanged();
}
});
//ๆ นๆฎ่ท็ฆปๆๅบ
btn_jl.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
btn_jl.setTextColor(getResources().getColor(R.color.theme));
btn_pj.setTextColor(getResources().getColor(R.color.balck));
Comparator<Restaurant> comparator1= new Comparator<Restaurant>() {
@Override
public int compare(Restaurant restaurant, Restaurant t1) {
if (Double.parseDouble(restaurant.getbAddress())>Double.parseDouble(t1.getbAddress()))
return 1;
else if(Double.parseDouble(restaurant.getbAddress())<Double.parseDouble(t1.getbAddress()))
return -1;
else return 0;
}
};
// restaurantList.sort(comparator1); //็ๆฌ่ฟไฝไธๆฏๆ
Collections.sort(restaurantList,comparator1);
shopListViewAdapter.notifyDataSetChanged();
}
});
}
}
| UTF-8 | Java | 12,434 | java | MainFragment.java | Java | []
| null | []
| package com.example.bao.fragment;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.ViewPager;
import com.bumptech.glide.Glide;
import com.example.bao.R;
import com.example.bao.activity.BuyMenuActivity;
import com.example.bao.adapter.CagegoryViewPagerAdapter;
import com.example.bao.adapter.EntranceAdapter;
import com.example.bao.adapter.ShopListViewAdapter;
import com.example.bao.model.ModelHomeEntrance;
import com.example.bao.model.Restaurant;
import com.example.bao.utils.MyDBHelper;
import com.example.bao.utils.ScreenUtil;
import com.example.bao.widget.IndicatorView;
import com.example.bao.widget.MyListView;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.Transformer;
import com.youth.banner.loader.ImageLoader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class MainFragment extends Fragment{
MyDBHelper myDBHelper;
private static MainFragment mainfragment;
List<Restaurant> restaurantList;
public static final int HOME_ENTRANCE_PAGE_SIZE = 10;//้ฆ้กต่ๅๅ้กตๆพ็คบๆฐ้
private ViewPager entranceViewPager;
private LinearLayout homeEntranceLayout;
private List<ModelHomeEntrance> homeEntrances;
private IndicatorView entranceIndicatorView;
ShopListViewAdapter shopListViewAdapter;
MyListView myListView;
Button btn_jl;
Button btn_pj;
View mainView;
Banner banner;
//ๅไพๆจกๅผ
public static MainFragment getMainFragment(){
if(mainfragment == null){
mainfragment = new MainFragment();
Log.i("test", "MainFragment่ขซๅๅปบ");
}
return mainfragment;
}
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view= inflater.inflate(R.layout.fragment_main,container,false);
mainView=inflater.inflate(R.layout.fragment_main,container,false);
return view;
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
initData();
initView();
init();
}
public void initView(){
homeEntranceLayout = (LinearLayout)getActivity().findViewById(R.id.main_home_entrance);
entranceViewPager=(ViewPager)getActivity().findViewById(R.id.main_home_entrance_vp);
entranceIndicatorView=(IndicatorView)getActivity().findViewById(R.id.main_home_entrance_indicator);
banner=getActivity().findViewById(R.id.main_banner1);
btn_jl=getActivity().findViewById(R.id.btn_sort_jl);
btn_pj=getActivity().findViewById(R.id.btn_sort_pj);
}
public void initData(){
homeEntrances = new ArrayList<>();
homeEntrances.add(new ModelHomeEntrance("็พ้ฃ", R.mipmap.ic_category_01));
homeEntrances.add(new ModelHomeEntrance("้ฅฑ้ฅฑ่ถ
ๅธ", R.mipmap.ic_category_02));
homeEntrances.add(new ModelHomeEntrance("็้ฒๆ่ฌ", R.mipmap.ic_category_03));
homeEntrances.add(new ModelHomeEntrance("้ฅฑไบไธ้", R.mipmap.ic_category_04));
homeEntrances.add(new ModelHomeEntrance("ๅฟซ้ฃ็ฎ้ค", R.mipmap.ic_category_05));
homeEntrances.add(new ModelHomeEntrance("ไธๅ่ถ", R.mipmap.ic_category_06));
homeEntrances.add(new ModelHomeEntrance("ๆซ่จๆฑๅ ก", R.mipmap.ic_category_07));
homeEntrances.add(new ModelHomeEntrance("ๆซ่จๆฑๅ ก", R.mipmap.ic_category_07));
homeEntrances.add(new ModelHomeEntrance("ๅฎถๅธธ่", R.mipmap.ic_category_08));
homeEntrances.add(new ModelHomeEntrance("ๅฐๅ้ฆ", R.mipmap.ic_category_09));
homeEntrances.add(new ModelHomeEntrance("้ฒ่ฑ่็ณ", R.mipmap.ic_category_010));
// homeEntrances.add(new ModelHomeEntrance("็พ้ฃ", R.mipmap.ic_category_0));
// homeEntrances.add(new ModelHomeEntrance("็ตๅฝฑ", R.mipmap.ic_category_1));
// homeEntrances.add(new ModelHomeEntrance("้
ๅบไฝๅฎฟ", R.mipmap.ic_category_2));
// homeEntrances.add(new ModelHomeEntrance("็ๆดปๆๅก", R.mipmap.ic_category_3));
// homeEntrances.add(new ModelHomeEntrance("KTV", R.mipmap.ic_category_4));
// homeEntrances.add(new ModelHomeEntrance("ๆ
ๆธธ", R.mipmap.ic_category_5));
// homeEntrances.add(new ModelHomeEntrance("ๅญฆไน ๅน่ฎญ", R.mipmap.ic_category_6));
// homeEntrances.add(new ModelHomeEntrance("ๆฑฝ่ฝฆๆๅก", R.mipmap.ic_category_7));
// homeEntrances.add(new ModelHomeEntrance("ๆๅฝฑๅ็", R.mipmap.ic_category_8));
// homeEntrances.add(new ModelHomeEntrance("ไผ้ฒๅจฑไน", R.mipmap.ic_category_10));
homeEntrances.add(new ModelHomeEntrance("ไธฝไบบ", R.mipmap.ic_category_11));
homeEntrances.add(new ModelHomeEntrance("่ฟๅจๅฅ่บซ", R.mipmap.ic_category_12));
homeEntrances.add(new ModelHomeEntrance("ๅคงไฟๅฅ", R.mipmap.ic_category_13));
homeEntrances.add(new ModelHomeEntrance("ๅข่ดญ", R.mipmap.ic_category_14));
homeEntrances.add(new ModelHomeEntrance("ๆฏ็น", R.mipmap.ic_category_16));
homeEntrances.add(new ModelHomeEntrance("ๅ
จ้จๅ็ฑป", R.mipmap.ic_category_15));
}
public void init() {
ScreenUtil.init(getContext());
LinearLayout.LayoutParams layoutParams12 = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, (int)((float)ScreenUtil.getScreenWidth() / 2.0f));
//้ฆ้กต่ๅๅ้กต
LinearLayout.LayoutParams entrancelayoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, (int)((float)ScreenUtil.getScreenWidth() / 2.0f + 70));
homeEntranceLayout.setLayoutParams(entrancelayoutParams);
entranceViewPager.setLayoutParams(layoutParams12);
// LayoutInflater inflater = LayoutInflater.from(getActivity());
//ๅฐRecyclerViewๆพ่ณViewPagerไธญ๏ผ
int pageSize = HOME_ENTRANCE_PAGE_SIZE;
//ไธๅ
ฑ็้กตๆฐ็ญไบ ๆปๆฐ/ๆฏ้กตๆฐ้๏ผๅนถๅๆดใ
int pageCount = (int) Math.ceil(homeEntrances.size() * 1.0 / pageSize);
List<View> viewList = new ArrayList<View>();
for (int index = 0; index < pageCount; index++) {
//ๆฏไธช้กต้ข้ฝๆฏinflateๅบไธไธชๆฐๅฎไพ
RecyclerView recyclerView = (RecyclerView)LayoutInflater.from(getContext()).inflate(R.layout.item_main_home_entrance_vp,null);
recyclerView.setLayoutParams(layoutParams12);
recyclerView.setLayoutManager(new GridLayoutManager(getContext(), 5));
EntranceAdapter entranceAdapter = new EntranceAdapter(getContext(), homeEntrances, index, HOME_ENTRANCE_PAGE_SIZE);
recyclerView.setAdapter(entranceAdapter);
viewList.add(recyclerView);
}
CagegoryViewPagerAdapter adapter = new CagegoryViewPagerAdapter(viewList,entranceViewPager);
entranceViewPager.setAdapter(adapter);
entranceIndicatorView.setIndicatorCount(entranceViewPager.getAdapter().getCount());
entranceIndicatorView.setCurrentIndicator(entranceViewPager.getCurrentItem());
entranceViewPager.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
@Override
public void onPageSelected(int position) {
entranceIndicatorView.setCurrentIndicator(position);
}
});
//่ฎพ็ฝฎๅพ็่ฝฎๆญ
setBanner();
//่ฎพ็ฝฎๅๅฎถๅ่กจ
setShopList();
//่ฎพ็ฝฎๆๅบ
setSort();
}
private void setBanner(){
List<Integer>imags=new ArrayList();
imags.add(R.drawable.main_banner_1);
// imags.add(R.drawable.main_banner_4);
imags.add(R.drawable.main_banner_5);
// imags.add(R.drawable.main_banner_6);
imags.add(R.drawable.main_banner_2);
imags.add(R.drawable.main_banner_3);
banner.setImageLoader(new ImageLoader() {
@Override
public void displayImage(Context context, Object path, ImageView imageView) {
Glide.with(context.getApplicationContext())
.load(path)
.into(imageView);
}
});
banner.setImages(imags);
banner.setBannerAnimation(Transformer.Default);
banner.setDelayTime(3000);
banner.setIndicatorGravity(BannerConfig.CENTER);
banner.start();
}
private void setShopList(){
myDBHelper=new MyDBHelper(getContext(),"Bao.db",null,1);
restaurantList=myDBHelper.selectRestaurant(null);
myListView =getActivity().findViewById(R.id.lv_main_shopListView);
shopListViewAdapter=new ShopListViewAdapter(restaurantList,getActivity().getBaseContext());
myListView.setAdapter(shopListViewAdapter);
//็นๅป่ฟๅ
ฅๅบๅฎถ่ๅ
myListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
TextView tv_shopName=view.findViewById(R.id.tv_item_Menuname);
String menuName= restaurantList.get(i).getbName();
Bundle bundle=new Bundle();
bundle.putSerializable("menuName",menuName);
Intent intent= new Intent(getContext(), BuyMenuActivity.class);
intent.putExtras(bundle);
startActivityForResult(intent,0000);
}
});
}
//่ฎพ็ฝฎๆๅบ
private void setSort(){
//ๆ นๆฎ่ฏไปทๆๅบ
btn_pj.setOnClickListener(new View.OnClickListener() {
@RequiresApi(api = Build.VERSION_CODES.N)
@Override
public void onClick(View view) {
btn_pj.setTextColor(getResources().getColor(R.color.theme));
btn_jl.setTextColor(getResources().getColor(R.color.balck));
Comparator<Restaurant> comparator1= new Comparator<Restaurant>() {
@Override
public int compare(Restaurant restaurant, Restaurant t1) {
if (restaurant.getbStar()> t1.getbStar())
return -1;
else if(restaurant.getbStar()< t1.getbStar())
return 1;
else return 0;
}
};
// restaurantList.sort(comparator1); //็ๆฌ่ฟไฝไธๆฏๆ
Collections.sort(restaurantList,comparator1);
shopListViewAdapter.notifyDataSetChanged();
}
});
//ๆ นๆฎ่ท็ฆปๆๅบ
btn_jl.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
btn_jl.setTextColor(getResources().getColor(R.color.theme));
btn_pj.setTextColor(getResources().getColor(R.color.balck));
Comparator<Restaurant> comparator1= new Comparator<Restaurant>() {
@Override
public int compare(Restaurant restaurant, Restaurant t1) {
if (Double.parseDouble(restaurant.getbAddress())>Double.parseDouble(t1.getbAddress()))
return 1;
else if(Double.parseDouble(restaurant.getbAddress())<Double.parseDouble(t1.getbAddress()))
return -1;
else return 0;
}
};
// restaurantList.sort(comparator1); //็ๆฌ่ฟไฝไธๆฏๆ
Collections.sort(restaurantList,comparator1);
shopListViewAdapter.notifyDataSetChanged();
}
});
}
}
| 12,434 | 0.665891 | 0.65775 | 276 | 42.615944 | 32.06353 | 182 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.833333 | false | false | 13 |
612acd06c22fbd8f3e5ea6f5d3c902bc2bc9e94e | 6,554,120,148,775 | e146b5aded26c259b4fd6c3cce2038ffd50521bc | /src/com/seezoon/framework/modules/zhfw/web/WtZhfwptGuestbookController.java | 00ac8a2b71e3a8b594e2f5b881d9bcf66ce757a0 | []
| no_license | CielTerre/zhglxt | https://github.com/CielTerre/zhglxt | 0904816d2f013f09fd3d784f0ada6f5f2cda9845 | cbcdd864e92123a5a90449cb418c2f6ce4046153 | refs/heads/master | 2022-12-26T11:06:35.922000 | 2019-10-19T01:48:59 | 2019-10-19T01:51:25 | 216,131,517 | 0 | 0 | null | false | 2022-12-16T11:54:26 | 2019-10-19T01:17:20 | 2019-10-19T02:01:46 | 2022-12-16T11:54:23 | 66,481 | 0 | 0 | 15 | JavaScript | false | false | package com.seezoon.framework.modules.zhfw.web;
import java.io.Serializable;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.github.pagehelper.PageInfo;
import com.seezoon.framework.common.context.beans.ResponeModel;
import com.seezoon.framework.common.web.BaseController;
import com.seezoon.framework.modules.zhfw.entity.WtZhfwptGuestbook;
import com.seezoon.framework.modules.zhfw.service.WtZhfwptGuestbookService;
/**
* ็ปผๅๆๅกๅนณๅฐ็่จ็ฎก็controller
*/
@RestController
@RequestMapping("${admin.path}/zhfw/zhfwptguestbook")
public class WtZhfwptGuestbookController extends BaseController {
@Autowired
private WtZhfwptGuestbookService wtZhfwptGuestbookService;
@RequiresPermissions("zhfw:zhfwptguestbook:qry")
@PostMapping("/qryPage.do")
public ResponeModel qryPage(WtZhfwptGuestbook wtZhfwptGuestbook) {
PageInfo<WtZhfwptGuestbook> page = wtZhfwptGuestbookService.findByPage(wtZhfwptGuestbook, wtZhfwptGuestbook.getPage(), wtZhfwptGuestbook.getPageSize());
return ResponeModel.ok(page);
}
@RequiresPermissions("zhfw:zhfwptguestbook:qry")
@RequestMapping("/get.do")
public ResponeModel get(@RequestParam Serializable id) {
WtZhfwptGuestbook wtZhfwptGuestbook = wtZhfwptGuestbookService.findById(id);
//ๅฏๆๆฌๅค็
return ResponeModel.ok(wtZhfwptGuestbook);
}
@RequiresPermissions("zhfw:zhfwptguestbook:save")
@PostMapping("/save.do")
public ResponeModel save(@Validated WtZhfwptGuestbook wtZhfwptGuestbook, BindingResult bindingResult) {
int cnt = wtZhfwptGuestbookService.save(wtZhfwptGuestbook);
return ResponeModel.ok(cnt);
}
@RequiresPermissions("zhfw:zhfwptguestbook:update")
@PostMapping("/update.do")
public ResponeModel update(@Validated WtZhfwptGuestbook wtZhfwptGuestbook, BindingResult bindingResult) {
int cnt = wtZhfwptGuestbookService.updateSelective(wtZhfwptGuestbook);
return ResponeModel.ok(cnt);
}
@RequiresPermissions("zhfw:zhfwptguestbook:delete")
@PostMapping("/delete.do")
public ResponeModel delete(@RequestParam Serializable id) {
int cnt = wtZhfwptGuestbookService.deleteById(id);
return ResponeModel.ok(cnt);
}
}
| UTF-8 | Java | 2,553 | java | WtZhfwptGuestbookController.java | Java | []
| null | []
| package com.seezoon.framework.modules.zhfw.web;
import java.io.Serializable;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.github.pagehelper.PageInfo;
import com.seezoon.framework.common.context.beans.ResponeModel;
import com.seezoon.framework.common.web.BaseController;
import com.seezoon.framework.modules.zhfw.entity.WtZhfwptGuestbook;
import com.seezoon.framework.modules.zhfw.service.WtZhfwptGuestbookService;
/**
* ็ปผๅๆๅกๅนณๅฐ็่จ็ฎก็controller
*/
@RestController
@RequestMapping("${admin.path}/zhfw/zhfwptguestbook")
public class WtZhfwptGuestbookController extends BaseController {
@Autowired
private WtZhfwptGuestbookService wtZhfwptGuestbookService;
@RequiresPermissions("zhfw:zhfwptguestbook:qry")
@PostMapping("/qryPage.do")
public ResponeModel qryPage(WtZhfwptGuestbook wtZhfwptGuestbook) {
PageInfo<WtZhfwptGuestbook> page = wtZhfwptGuestbookService.findByPage(wtZhfwptGuestbook, wtZhfwptGuestbook.getPage(), wtZhfwptGuestbook.getPageSize());
return ResponeModel.ok(page);
}
@RequiresPermissions("zhfw:zhfwptguestbook:qry")
@RequestMapping("/get.do")
public ResponeModel get(@RequestParam Serializable id) {
WtZhfwptGuestbook wtZhfwptGuestbook = wtZhfwptGuestbookService.findById(id);
//ๅฏๆๆฌๅค็
return ResponeModel.ok(wtZhfwptGuestbook);
}
@RequiresPermissions("zhfw:zhfwptguestbook:save")
@PostMapping("/save.do")
public ResponeModel save(@Validated WtZhfwptGuestbook wtZhfwptGuestbook, BindingResult bindingResult) {
int cnt = wtZhfwptGuestbookService.save(wtZhfwptGuestbook);
return ResponeModel.ok(cnt);
}
@RequiresPermissions("zhfw:zhfwptguestbook:update")
@PostMapping("/update.do")
public ResponeModel update(@Validated WtZhfwptGuestbook wtZhfwptGuestbook, BindingResult bindingResult) {
int cnt = wtZhfwptGuestbookService.updateSelective(wtZhfwptGuestbook);
return ResponeModel.ok(cnt);
}
@RequiresPermissions("zhfw:zhfwptguestbook:delete")
@PostMapping("/delete.do")
public ResponeModel delete(@RequestParam Serializable id) {
int cnt = wtZhfwptGuestbookService.deleteById(id);
return ResponeModel.ok(cnt);
}
}
| 2,553 | 0.826397 | 0.826397 | 59 | 41.762711 | 30.635273 | 154 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.254237 | false | false | 13 |
c03dd6069824453f6738de9bc93d9d41cdeb0632 | 6,554,120,150,560 | 2052d407ceaf51fba89dc64807aecba0f20c2ad2 | /desktop/src/com/badogic/drop/desktop/DesktopLauncher.java | 750eafffc8b4154452721baaf05e855ad8840cff | []
| no_license | Danduriel/gjws17 | https://github.com/Danduriel/gjws17 | 9e3f5502894b6a57b6de260a53c9a45b3f807d90 | 8ec6f714e83269da0b4d8232f3e6ba29ee119fc7 | refs/heads/master | 2021-08-16T02:52:52.214000 | 2017-11-18T22:48:56 | 2017-11-18T22:48:56 | 111,091,727 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.badogic.drop.desktop;
import com.badlogic.gdx.backends.lwjgl.LwjglApplication;
import com.badlogic.gdx.backends.lwjgl.LwjglApplicationConfiguration;
import com.badogic.drop.Drop;
public class DesktopLauncher {
public static void main (String[] arg) {
LwjglApplicationConfiguration config = new LwjglApplicationConfiguration();
config.title = "Monkeys Building some temple [MBST]";
config.width = 1280;
config.height = 800;
config.foregroundFPS = 60; // #PC-Masterrace
config.samples = 8; // Antialiasing
new LwjglApplication(new Drop(), config);
}
}
| UTF-8 | Java | 618 | java | DesktopLauncher.java | Java | []
| null | []
| package com.badogic.drop.desktop;
import com.badlogic.gdx.backends.lwjgl.LwjglApplication;
import com.badlogic.gdx.backends.lwjgl.LwjglApplicationConfiguration;
import com.badogic.drop.Drop;
public class DesktopLauncher {
public static void main (String[] arg) {
LwjglApplicationConfiguration config = new LwjglApplicationConfiguration();
config.title = "Monkeys Building some temple [MBST]";
config.width = 1280;
config.height = 800;
config.foregroundFPS = 60; // #PC-Masterrace
config.samples = 8; // Antialiasing
new LwjglApplication(new Drop(), config);
}
}
| 618 | 0.721683 | 0.705502 | 17 | 35.35294 | 23.810381 | 82 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.235294 | false | false | 13 |
9a98965a119e22b300ebb2140b2251996d3e4fc0 | 10,058,813,461,997 | 80b2b07d2e392dc6417df0ade0dfbf2033b484d6 | /Task5/src/task5/epam/task04/treasure/TreasureDragon.java | 1f12b537cc90b36dbddee566c6c4fd9f5d42edad | []
| no_license | faciorys/training | https://github.com/faciorys/training | 30e7920aa98423513f5a76ae80c445491b22d153 | f1d1c8717f68124730f2898cdccc5008dd7470c7 | refs/heads/master | 2023-06-09T11:09:44.990000 | 2021-06-30T12:29:00 | 2021-06-30T12:29:00 | 381,389,922 | 0 | 0 | null | false | 2021-06-29T16:00:44 | 2021-06-29T14:16:24 | 2021-06-29T15:56:24 | 2021-06-29T16:00:44 | 17 | 0 | 0 | 0 | Java | false | false | package task5.epam.task04.treasure;
/**
* ะะปะฐัั ะดะปั ะดัะฐะณะพัะตะฝะฝะพััะตะน.
*
* @author faciorys
*/
public class TreasureDragon implements Treasure {
private TreasureType treasureType;
private MetalType metalType;
private String name;
private int cost;
public TreasureDragon(TreasureType treasureType, MetalType metalType, String name, int cost) {
this.treasureType = treasureType;
this.metalType = metalType;
this.name = name;
this.cost = cost;
}
@Override
public TreasureType getTreasureType() {
return treasureType;
}
@Override
public String getName() {
return name;
}
@Override
public int getCost() {
return cost;
}
@Override
public String toString() {
return "ะัะฐะณะพัะตะฝะฝะพััั - " + treasureType +
", ัะธะฟ ะผะตัะฐะปะปะฐ - " + metalType +
", ััะพะธะผะพััั - " + cost;
}
}
| UTF-8 | Java | 986 | java | TreasureDragon.java | Java | [
{
"context": "e;\n\n/**\n * ะะปะฐัั ะดะปั ะดัะฐะณะพัะตะฝะฝะพััะตะน.\n *\n * @author faciorys\n */\npublic class TreasureDragon implements Treasur",
"end": 92,
"score": 0.9099194407463074,
"start": 84,
"tag": "USERNAME",
"value": "faciorys"
}
]
| null | []
| package task5.epam.task04.treasure;
/**
* ะะปะฐัั ะดะปั ะดัะฐะณะพัะตะฝะฝะพััะตะน.
*
* @author faciorys
*/
public class TreasureDragon implements Treasure {
private TreasureType treasureType;
private MetalType metalType;
private String name;
private int cost;
public TreasureDragon(TreasureType treasureType, MetalType metalType, String name, int cost) {
this.treasureType = treasureType;
this.metalType = metalType;
this.name = name;
this.cost = cost;
}
@Override
public TreasureType getTreasureType() {
return treasureType;
}
@Override
public String getName() {
return name;
}
@Override
public int getCost() {
return cost;
}
@Override
public String toString() {
return "ะัะฐะณะพัะตะฝะฝะพััั - " + treasureType +
", ัะธะฟ ะผะตัะฐะปะปะฐ - " + metalType +
", ััะพะธะผะพััั - " + cost;
}
}
| 986 | 0.611588 | 0.608369 | 42 | 21.190475 | 19.660498 | 98 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.428571 | false | false | 13 |
eeb65873778f91e45bb4c48e0f067d84879eebc9 | 7,181,185,379,982 | 31f0c7bf08ce888500ab437115db95e677c43544 | /src/main/java/operations/Div.java | 47455e0c925f58410ef165adf65b88a5c77779f6 | []
| no_license | artem-temoff/ConsoleCalc | https://github.com/artem-temoff/ConsoleCalc | d9169bd808ea66811689618f57368a6842d08eb1 | 7d2e9da27dcdc31355ebaffb5b11bef3e8171191 | refs/heads/master | 2020-05-18T12:12:42.747000 | 2015-04-07T16:16:31 | 2015-04-07T16:16:31 | 33,245,477 | 0 | 2 | null | false | 2015-05-10T08:58:03 | 2015-04-01T12:11:04 | 2015-04-07T16:17:51 | 2015-05-10T08:58:03 | 125 | 0 | 1 | 1 | Java | null | null | package operations;
/**
* Created by Artem Eremenko on 01.04.2015.
*/
public class Div extends Operator {
public double calculate(double a, double b) {
if(b==0) throw new DivisionByZero("error in division operator");
return a / b;
}
}
| UTF-8 | Java | 263 | java | Div.java | Java | [
{
"context": "package operations;\n\n/**\n * Created by Artem Eremenko on 01.04.2015.\n */\npublic class Div extends Opera",
"end": 53,
"score": 0.9997904896736145,
"start": 39,
"tag": "NAME",
"value": "Artem Eremenko"
}
]
| null | []
| package operations;
/**
* Created by <NAME> on 01.04.2015.
*/
public class Div extends Operator {
public double calculate(double a, double b) {
if(b==0) throw new DivisionByZero("error in division operator");
return a / b;
}
}
| 255 | 0.646388 | 0.612167 | 11 | 22.90909 | 23.023523 | 72 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.363636 | false | false | 13 |
8055b71941806416c4836f456447249a73245f6a | 8,787,503,110,244 | 08144fdf5218c8cdd4729818ab76ed7ebc1779f8 | /src/Calendar/Week.java | 0e0865a3c04a033acfb1d18c4bf6217cfebfe523 | [
"MIT"
]
| permissive | derekstephen/LionPlanner | https://github.com/derekstephen/LionPlanner | 4ee58fd4ce7894652629ca6192b5ca22bf6be164 | 98a08ce976860b3eed1640a59b378d59f6b07f6e | refs/heads/master | 2020-04-15T13:10:07.576000 | 2019-04-29T04:03:31 | 2019-04-29T04:03:31 | 164,705,314 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package Calendar;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.util.ArrayList;
public class Week {
private ArrayList<LocalDate> days;
// Gets week variables from any date (can be within week)
public Week(LocalDate date) {
days = new ArrayList<>();
LocalDate monday = getStartOfWeek(date);
days.add(monday);
for (int i = 1; i < 7; i++) {
days.add(monday.plusDays(i));
}
}
public static LocalDate getStartOfWeek(LocalDate date) {
LocalDate day = date;
while (day.getDayOfWeek() != DayOfWeek.MONDAY) {
day = day.minusDays(1);
}
return day;
}
public LocalDate getDay(DayOfWeek dayOfWeek) {
// DayOfWeek enum starts with monday == 1
return days.get(dayOfWeek.getValue() - 1);
}
public Week nextWeek() {
final LocalDate friday = getDay(DayOfWeek.SUNDAY);
return new Week(friday.plusDays(3));
}
public Week prevWeek() {
final LocalDate monday = getDay(DayOfWeek.MONDAY);
return new Week(monday.minusDays(3));
}
public String toString() {
return "Week of the " + getDay(DayOfWeek.MONDAY);
}
public static void main(String[] args) {
LocalDate now = LocalDate.now();
Week currentWeek = new Week(now);
System.out.println(currentWeek);
System.out.println(currentWeek.prevWeek());
System.out.println(currentWeek.nextWeek());
}
}
| UTF-8 | Java | 1,506 | java | Week.java | Java | []
| null | []
| package Calendar;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.util.ArrayList;
public class Week {
private ArrayList<LocalDate> days;
// Gets week variables from any date (can be within week)
public Week(LocalDate date) {
days = new ArrayList<>();
LocalDate monday = getStartOfWeek(date);
days.add(monday);
for (int i = 1; i < 7; i++) {
days.add(monday.plusDays(i));
}
}
public static LocalDate getStartOfWeek(LocalDate date) {
LocalDate day = date;
while (day.getDayOfWeek() != DayOfWeek.MONDAY) {
day = day.minusDays(1);
}
return day;
}
public LocalDate getDay(DayOfWeek dayOfWeek) {
// DayOfWeek enum starts with monday == 1
return days.get(dayOfWeek.getValue() - 1);
}
public Week nextWeek() {
final LocalDate friday = getDay(DayOfWeek.SUNDAY);
return new Week(friday.plusDays(3));
}
public Week prevWeek() {
final LocalDate monday = getDay(DayOfWeek.MONDAY);
return new Week(monday.minusDays(3));
}
public String toString() {
return "Week of the " + getDay(DayOfWeek.MONDAY);
}
public static void main(String[] args) {
LocalDate now = LocalDate.now();
Week currentWeek = new Week(now);
System.out.println(currentWeek);
System.out.println(currentWeek.prevWeek());
System.out.println(currentWeek.nextWeek());
}
}
| 1,506 | 0.61089 | 0.606242 | 56 | 25.892857 | 20.676659 | 61 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.446429 | false | false | 13 |
19f84842744b32852a282d16c2d77d86111cf9be | 12,859,132,154,991 | c0a8a0637996428692ba088fe296bd8e47c89422 | /src/com/wanted/ws/remote/GetPost.java | a6da54a6dc08165229658d295edd30eae13ae2ac | []
| no_license | zw630507/Wanted_Server | https://github.com/zw630507/Wanted_Server | 5fed485128c7ef5e80c50de234352a8238f4df72 | 6c00afbcfc9a22a998acf57dbe84a2b7f8ca931a | refs/heads/master | 2021-01-18T15:06:13.130000 | 2016-02-18T02:45:12 | 2016-02-18T02:45:12 | 51,972,845 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | // The servlet that deals with returning more job posts asked by a user
package com.wanted.ws.remote;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.wanted.database.Database;
import com.wanted.entities.Information;
import com.wanted.entities.Pack;
import com.wanted.entities.Post;
import com.wanted.util.ServletUtil;
/**
* Servlet implementation class GetPost
*/
public class GetPost extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public GetPost() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doPost(request, response);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Database database = new ServletUtil().getDatabase(getServletContext());
try (ObjectInputStream ois = new ObjectInputStream(request.getInputStream());
ObjectOutputStream oos = new ObjectOutputStream(response.getOutputStream())) {
Class.forName("com.mysql.jdbc.Driver");
Pack pack = (Pack) ois.readObject();
String s = (String)(pack.getContent());
int postNum = 4;
int splitIndex = s.indexOf(":");
String major = s.substring(0, splitIndex);
int cursor = Integer.parseInt(s.substring(splitIndex+1, s.length()));
List<Post> p = new ArrayList<Post>();
if (cursor == -1)
p = database.getNewPost(postNum, major);
else
p = database.getMorePost(cursor, postNum, major);
pack = new Pack(Information.SUCCESS, p);
oos.writeObject(pack);
oos.flush();
} catch (Exception e) {
e.printStackTrace();
}
}
}
| UTF-8 | Java | 2,322 | java | GetPost.java | Java | []
| null | []
| // The servlet that deals with returning more job posts asked by a user
package com.wanted.ws.remote;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.wanted.database.Database;
import com.wanted.entities.Information;
import com.wanted.entities.Pack;
import com.wanted.entities.Post;
import com.wanted.util.ServletUtil;
/**
* Servlet implementation class GetPost
*/
public class GetPost extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public GetPost() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doPost(request, response);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Database database = new ServletUtil().getDatabase(getServletContext());
try (ObjectInputStream ois = new ObjectInputStream(request.getInputStream());
ObjectOutputStream oos = new ObjectOutputStream(response.getOutputStream())) {
Class.forName("com.mysql.jdbc.Driver");
Pack pack = (Pack) ois.readObject();
String s = (String)(pack.getContent());
int postNum = 4;
int splitIndex = s.indexOf(":");
String major = s.substring(0, splitIndex);
int cursor = Integer.parseInt(s.substring(splitIndex+1, s.length()));
List<Post> p = new ArrayList<Post>();
if (cursor == -1)
p = database.getNewPost(postNum, major);
else
p = database.getMorePost(cursor, postNum, major);
pack = new Pack(Information.SUCCESS, p);
oos.writeObject(pack);
oos.flush();
} catch (Exception e) {
e.printStackTrace();
}
}
}
| 2,322 | 0.715332 | 0.713178 | 70 | 31.242857 | 27.413988 | 119 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.757143 | false | false | 13 |
f70ca6a39b8b8744708b49d64c668b5693625e19 | 33,148,557,660,588 | a6f143db7d46dfb143af8f87e7bae84db0f11e01 | /Q2.java | 31acb698532d9e48a56148c32e4ae8513a2cd035 | []
| no_license | Sanchit170054/Assesments | https://github.com/Sanchit170054/Assesments | 52efa405e32c40efff30773941f07223a13b5605 | c439a6dfd2c8c56ceb9d469b55b1ceb08ddc86d6 | refs/heads/master | 2022-12-13T05:38:44.334000 | 2020-09-10T05:24:06 | 2020-09-10T05:24:06 | 294,309,638 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import java.util.Arrays;
import java.util.Scanner;
public class Q2 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int ar[] = new int[n];
for(int i = 0 ; i < n; i++)
{
ar[i] = sc.nextInt();
}
if(ar.length <= 3 || AreAllSame(ar))
{
System.out.println("Invalid");
}
else
{
Arrays.sort(ar);
System.out.println(ar[ar.length-3]);
}
}
public static boolean AreAllSame(int[] array)
{
boolean isFirstElementNull = String.valueOf(array[0]) == null;
for(int i = 1; i < array.length; i++)
{
if(isFirstElementNull)
{
if(String.valueOf(array[i]) != null) return false;
}
else
{
if(!String.valueOf(array[0]).equals(String.valueOf(array[i]))) return false;
}
}
return true;
}
}
| UTF-8 | Java | 879 | java | Q2.java | Java | []
| null | []
| import java.util.Arrays;
import java.util.Scanner;
public class Q2 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int ar[] = new int[n];
for(int i = 0 ; i < n; i++)
{
ar[i] = sc.nextInt();
}
if(ar.length <= 3 || AreAllSame(ar))
{
System.out.println("Invalid");
}
else
{
Arrays.sort(ar);
System.out.println(ar[ar.length-3]);
}
}
public static boolean AreAllSame(int[] array)
{
boolean isFirstElementNull = String.valueOf(array[0]) == null;
for(int i = 1; i < array.length; i++)
{
if(isFirstElementNull)
{
if(String.valueOf(array[i]) != null) return false;
}
else
{
if(!String.valueOf(array[0]).equals(String.valueOf(array[i]))) return false;
}
}
return true;
}
}
| 879 | 0.547213 | 0.539249 | 45 | 17.533333 | 20.244724 | 83 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.888889 | false | false | 13 |
20a382b315c96b4bd0faaa4c1c33b1e58508a044 | 18,614,388,313,360 | e0c32fe080f6dd5946dd1a65fbc4d1e38eecb15c | /app/src/main/java/com/equipa18/geoquest/ui/account/AccountFragment.java | 37c7054759c484663f8428bd818edaf3b3b0f5e5 | []
| no_license | neurodraft/GeoQuest | https://github.com/neurodraft/GeoQuest | b5f98bbdd5b1054563f77c5a158f5ad688821e71 | 21a54b3601aaa960f282233c998883c33cdad067 | refs/heads/main | 2023-05-03T14:54:00.651000 | 2021-05-16T23:24:10 | 2021-05-16T23:24:10 | 366,437,029 | 0 | 0 | null | false | 2021-05-16T23:24:11 | 2021-05-11T15:49:35 | 2021-05-16T22:44:23 | 2021-05-16T23:24:10 | 3,920 | 0 | 0 | 0 | Java | false | false | package com.equipa18.geoquest.ui.account;
import android.content.ContextWrapper;
import android.content.Intent;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import com.equipa18.geoquest.ChangePasswordActivity;
import com.equipa18.geoquest.PicassoManager;
import com.equipa18.geoquest.R;
import com.equipa18.geoquest.RegisterActivity;
import com.equipa18.geoquest.StatisticsActivity;
import com.equipa18.geoquest.player.PlayerManager;
import org.jetbrains.annotations.NotNull;
public class AccountFragment extends Fragment {
private ImageView picture;
private TextView username;
private Button changePic;
private Button changePass;
private Button stats;
@Override
public View onCreateView(@NonNull @NotNull LayoutInflater inflater, @Nullable @org.jetbrains.annotations.Nullable ViewGroup container, @Nullable @org.jetbrains.annotations.Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_account, container, false);
//standard stuff, getting the ids
picture = view.findViewById(R.id.profilePictureImage);
username = view.findViewById(R.id.userNameText);
changePic = view.findViewById(R.id.changeProfilePictureButton);
changePass = view.findViewById(R.id.changePasswordButton);
stats = view.findViewById(R.id.statisticsButton);
//here we start populating data, the fun stuff
username.setText(PlayerManager.getCurrentPlayer().getUsername());
ContextWrapper cw = new ContextWrapper(getActivity());
PicassoManager.loadPaths(cw);
PicassoManager.applyRoundPicture(picture);
changePic.setOnClickListener(v -> {
Intent cam = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cam, 0);
});
changePass.setOnClickListener(v -> {
goToChange();
});
stats.setOnClickListener(v -> {
goToStats();
});
return view;
}
@Override
public void onActivityResult(int requestCode, int resultCode, @Nullable @org.jetbrains.annotations.Nullable Intent data) {
if(PicassoManager.savePic(data)) {
super.onActivityResult(requestCode, resultCode, data);
PicassoManager.applyRoundPicture(picture);
}
}
private void goToChange() {
Intent changeScreen = new Intent(getActivity(), ChangePasswordActivity.class);
startActivity(changeScreen);
}
private void goToStats() {
Intent changeScreen = new Intent(getActivity(), StatisticsActivity.class);
startActivity(changeScreen);
}
}
| UTF-8 | Java | 3,052 | java | AccountFragment.java | Java | []
| null | []
| package com.equipa18.geoquest.ui.account;
import android.content.ContextWrapper;
import android.content.Intent;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import com.equipa18.geoquest.ChangePasswordActivity;
import com.equipa18.geoquest.PicassoManager;
import com.equipa18.geoquest.R;
import com.equipa18.geoquest.RegisterActivity;
import com.equipa18.geoquest.StatisticsActivity;
import com.equipa18.geoquest.player.PlayerManager;
import org.jetbrains.annotations.NotNull;
public class AccountFragment extends Fragment {
private ImageView picture;
private TextView username;
private Button changePic;
private Button changePass;
private Button stats;
@Override
public View onCreateView(@NonNull @NotNull LayoutInflater inflater, @Nullable @org.jetbrains.annotations.Nullable ViewGroup container, @Nullable @org.jetbrains.annotations.Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_account, container, false);
//standard stuff, getting the ids
picture = view.findViewById(R.id.profilePictureImage);
username = view.findViewById(R.id.userNameText);
changePic = view.findViewById(R.id.changeProfilePictureButton);
changePass = view.findViewById(R.id.changePasswordButton);
stats = view.findViewById(R.id.statisticsButton);
//here we start populating data, the fun stuff
username.setText(PlayerManager.getCurrentPlayer().getUsername());
ContextWrapper cw = new ContextWrapper(getActivity());
PicassoManager.loadPaths(cw);
PicassoManager.applyRoundPicture(picture);
changePic.setOnClickListener(v -> {
Intent cam = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cam, 0);
});
changePass.setOnClickListener(v -> {
goToChange();
});
stats.setOnClickListener(v -> {
goToStats();
});
return view;
}
@Override
public void onActivityResult(int requestCode, int resultCode, @Nullable @org.jetbrains.annotations.Nullable Intent data) {
if(PicassoManager.savePic(data)) {
super.onActivityResult(requestCode, resultCode, data);
PicassoManager.applyRoundPicture(picture);
}
}
private void goToChange() {
Intent changeScreen = new Intent(getActivity(), ChangePasswordActivity.class);
startActivity(changeScreen);
}
private void goToStats() {
Intent changeScreen = new Intent(getActivity(), StatisticsActivity.class);
startActivity(changeScreen);
}
}
| 3,052 | 0.729685 | 0.724771 | 86 | 34.488373 | 31.506641 | 213 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.755814 | false | false | 13 |
559afcd700f8e186a924ff1ac4e10ee594409673 | 1,743,756,753,047 | 07e99185a517ae50981c94bec153da70c16aa490 | /SpringBootJwtOAuth2ResourceServerTutorial/src/main/java/com/warumono/resource/repositories/AcceptanceRepository.java | fd8d6bb3797fb3a40f5d3c7479c99e83dc8d489e | [
"Apache-2.0"
]
| permissive | warumono-for-develop/spring-boot-jwt-oauth2-resource-server-tutorial | https://github.com/warumono-for-develop/spring-boot-jwt-oauth2-resource-server-tutorial | d3ef9691f676e5e1b666c98c40c955ba848b2f96 | aede2aeb13fedb9a2892c9a94e1f462f7af3aeee | refs/heads/master | 2021-04-03T11:44:12.027000 | 2018-03-12T16:13:36 | 2018-03-12T16:13:36 | 124,916,351 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.warumono.resource.repositories;
import com.warumono.resource.entities.Acceptance;
public interface AcceptanceRepository extends AbstractRepository<Acceptance>
{
}
| UTF-8 | Java | 178 | java | AcceptanceRepository.java | Java | []
| null | []
| package com.warumono.resource.repositories;
import com.warumono.resource.entities.Acceptance;
public interface AcceptanceRepository extends AbstractRepository<Acceptance>
{
}
| 178 | 0.848315 | 0.848315 | 8 | 21.25 | 28.318501 | 76 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.25 | false | false | 13 |
83e1561780458f2da5623f8cb956f7f911877366 | 19,567,871,008,972 | bc50ebfdba1358340eb16a4ec16133a254d1c0a0 | /src/main/java/com/movie/bean/CityBase.java | c4775761ff2d520f2c1b227361d595ef6ee69e1d | []
| no_license | northofbei/MovieTicketStudy | https://github.com/northofbei/MovieTicketStudy | 298d566034e43b49b8b763918e439e4ad755ae7c | 43f4b1e542bc751b82aaa1f2c2da46e73daa22b6 | refs/heads/master | 2016-09-25T01:51:19.150000 | 2015-08-27T10:16:55 | 2015-08-27T10:16:55 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.movie.bean;
/**
* @ClassName: City
* @Description: ๅๅธ่กจ
* @author haolong
* @date 2015ๅนด8ๆ19ๆฅ ไธๅ7:57:49
*
*/
public class CityBase implements java.io.Serializable {
private static final long serialVersionUID = 2654334646351058302L;
private Long id;// ไธป้ฎ
private String cityCode;// ๅๅธ็ผ็
private String cityName;// ๅๅธๅ
private Integer isOnline;// ๅ ้คๆ ่ฎฐ
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getCityCode() {
return cityCode;
}
public void setCityCode(String cityCode) {
this.cityCode = cityCode;
}
public String getCityName() {
return cityName;
}
public void setCityName(String cityName) {
this.cityName = cityName;
}
public Integer getIsOnline() {
return isOnline;
}
public void setIsOnline(Integer isOnline) {
this.isOnline = isOnline;
}
} | UTF-8 | Java | 962 | java | CityBase.java | Java | [
{
"context": "@ClassName: City\r\n * @Description: ๅๅธ่กจ\r\n * @author haolong\r\n * @date 2015ๅนด8ๆ19ๆฅ ไธๅ7:57:49\r\n * \r\n */\r\npublic ",
"end": 95,
"score": 0.9665525555610657,
"start": 88,
"tag": "USERNAME",
"value": "haolong"
}
]
| null | []
| package com.movie.bean;
/**
* @ClassName: City
* @Description: ๅๅธ่กจ
* @author haolong
* @date 2015ๅนด8ๆ19ๆฅ ไธๅ7:57:49
*
*/
public class CityBase implements java.io.Serializable {
private static final long serialVersionUID = 2654334646351058302L;
private Long id;// ไธป้ฎ
private String cityCode;// ๅๅธ็ผ็
private String cityName;// ๅๅธๅ
private Integer isOnline;// ๅ ้คๆ ่ฎฐ
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getCityCode() {
return cityCode;
}
public void setCityCode(String cityCode) {
this.cityCode = cityCode;
}
public String getCityName() {
return cityName;
}
public void setCityName(String cityName) {
this.cityName = cityName;
}
public Integer getIsOnline() {
return isOnline;
}
public void setIsOnline(Integer isOnline) {
this.isOnline = isOnline;
}
} | 962 | 0.657609 | 0.623913 | 56 | 14.464286 | 16.431639 | 67 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.928571 | false | false | 13 |
dc7a5f55ef2d93ccb25473ec7fa3794870edacca | 21,904,333,223,655 | 75fe8a934012ce8b37e3d6a5c09febc3260fc7ed | /majiang/javaCode/game/view/scene/gamescene/elements/ChiPreviewUI.java | 1eecb1d541f62e4fb06719c3453ce0db43a4293c | []
| no_license | thinkido/exampleAs3 | https://github.com/thinkido/exampleAs3 | 36ad39ad24696bb81ba8985f2c5ac8a67e2b84dd | 55a127b1a1f8e48f04f973a4df8596df4478c154 | refs/heads/master | 2016-09-11T00:48:14.220000 | 2016-02-20T07:14:25 | 2016-02-20T07:14:25 | 14,101,421 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package game.view.scene.gamescene.elements;
import jing.consts.CardPlace;
import jing.consts.GameDir;
import jing.consts.MahjongState;
import jing.consts.PlayerAction;
import jing.game.view.Mahjong;
import framework.views.Sprite;
public class ChiPreviewUI extends Sprite
{
private Mahjong[] mjs = new Mahjong[3];
public ChiPreviewUI(int card, int type)
{
int card1 = 0;
int card2 = 0;
int card3 = 0;
int eatedIndex = -1;
if(type == PlayerAction.CHI_LEFT)
{
eatedIndex = 0;
card1 = card;
card2 = card + 1;
card3 = card + 2;
}
else if(type == PlayerAction.CHI_MIDDLE)
{
eatedIndex = 1;
card1 = card;
card2 = card + 1;
card3 = card + 2;
}
else if(type == PlayerAction.CHI_RIGHT)
{
eatedIndex = 2;
card1 = card;
card2 = card + 1;
card3 = card + 2;
}
mjs[0] = new Mahjong(card1, GameDir.DOWN, CardPlace.ON_TABLE);
mjs[1] = new Mahjong(card2, GameDir.DOWN, CardPlace.ON_TABLE);
mjs[2] = new Mahjong(card3, GameDir.DOWN, CardPlace.ON_TABLE);
int w = mjs[0].getWidth();
mjs[1].setPosition(w, 0);
mjs[2].setPosition(w * 2, 0);
mjs[eatedIndex].setState(MahjongState.GLOW);
for(int i = 0; i < mjs.length; i++)
{
this.addChild(mjs[i]);
}
}
}
| UTF-8 | Java | 1,283 | java | ChiPreviewUI.java | Java | []
| null | []
|
package game.view.scene.gamescene.elements;
import jing.consts.CardPlace;
import jing.consts.GameDir;
import jing.consts.MahjongState;
import jing.consts.PlayerAction;
import jing.game.view.Mahjong;
import framework.views.Sprite;
public class ChiPreviewUI extends Sprite
{
private Mahjong[] mjs = new Mahjong[3];
public ChiPreviewUI(int card, int type)
{
int card1 = 0;
int card2 = 0;
int card3 = 0;
int eatedIndex = -1;
if(type == PlayerAction.CHI_LEFT)
{
eatedIndex = 0;
card1 = card;
card2 = card + 1;
card3 = card + 2;
}
else if(type == PlayerAction.CHI_MIDDLE)
{
eatedIndex = 1;
card1 = card;
card2 = card + 1;
card3 = card + 2;
}
else if(type == PlayerAction.CHI_RIGHT)
{
eatedIndex = 2;
card1 = card;
card2 = card + 1;
card3 = card + 2;
}
mjs[0] = new Mahjong(card1, GameDir.DOWN, CardPlace.ON_TABLE);
mjs[1] = new Mahjong(card2, GameDir.DOWN, CardPlace.ON_TABLE);
mjs[2] = new Mahjong(card3, GameDir.DOWN, CardPlace.ON_TABLE);
int w = mjs[0].getWidth();
mjs[1].setPosition(w, 0);
mjs[2].setPosition(w * 2, 0);
mjs[eatedIndex].setState(MahjongState.GLOW);
for(int i = 0; i < mjs.length; i++)
{
this.addChild(mjs[i]);
}
}
}
| 1,283 | 0.620421 | 0.590023 | 56 | 20.875 | 17.258602 | 64 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.357143 | false | false | 13 |
e2d9f7069533d43722e8b55b41d86bdd623e17e8 | 618,475,323,368 | 46691d084449c4a040b45990e74501cea20cfa16 | /ClientSide Maven Webapp/src/main/java/client/MyClientWriter.java | 90a673c6c1d4cc494999eae0c85eb7ba62c05d66 | []
| no_license | minijiang/socket | https://github.com/minijiang/socket | 63c93014a54131e531635c7d0987eea50310af87 | 5522568e858bb3a6af06995d4b636e9bad28ae53 | refs/heads/master | 2021-08-19T07:54:17.750000 | 2017-11-25T09:32:05 | 2017-11-25T09:32:05 | 111,980,541 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package client;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.util.Scanner;
//ๅๅปบไธไธช่ฟ็จ็จๆฅๅๅ
ฅๅนถๅ้ๆฐๆฎ
public class MyClientWriter extends Thread {
private DataOutputStream dos;
public MyClientWriter(DataOutputStream dos) {
this.dos = dos;
}
@Override
public void run() {
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
String msg;
try {
while (true) {
msg = br.readLine();
dos.writeUTF(msg);
dos.flush();
if (msg.equals("bye")) {
System.out.println("ๅฎขๆท็ซฏไธ็บฟ,็จๅบ้ๅบ");
System.exit(0);
}
}
} catch (IOException e) {
System.out.println(e);
}
}
} | GB18030 | Java | 908 | java | MyClientWriter.java | Java | []
| null | []
| package client;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.util.Scanner;
//ๅๅปบไธไธช่ฟ็จ็จๆฅๅๅ
ฅๅนถๅ้ๆฐๆฎ
public class MyClientWriter extends Thread {
private DataOutputStream dos;
public MyClientWriter(DataOutputStream dos) {
this.dos = dos;
}
@Override
public void run() {
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
String msg;
try {
while (true) {
msg = br.readLine();
dos.writeUTF(msg);
dos.flush();
if (msg.equals("bye")) {
System.out.println("ๅฎขๆท็ซฏไธ็บฟ,็จๅบ้ๅบ");
System.exit(0);
}
}
} catch (IOException e) {
System.out.println(e);
}
}
} | 908 | 0.711628 | 0.710465 | 38 | 21.605263 | 14.25065 | 59 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.157895 | false | false | 13 |
bd0982ad090f985a1dc7856ed69ce2fb35760781 | 21,354,577,422,442 | 54dfab1b3cb55f34bbd477c26e371f59f7cb65d7 | /Ex14_1a/src/Ex14_1a.java | 8758d183cde813fa64ee28b3988f667fa6d48f6b | []
| no_license | bigleeuk/Java | https://github.com/bigleeuk/Java | be766682b2c2d10c6d8871d7b6f4945d54dd85ea | 7df5bbce8514300f7646fa980486ffd6489d8b88 | refs/heads/master | 2020-03-09T01:27:34.611000 | 2018-04-07T09:45:12 | 2018-04-07T09:45:12 | 128,515,005 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import java.util.ArrayList;
import java.util.Scanner;
public class Ex14_1a {
public static ArrayList<String> arrayToArrayList(String[]s){
int i = 0;
ArrayList<String> myArrayList = new ArrayList<String>();
System.out.println("copy String_Array to arrayList");
while(i < s.length)
{
String t = new String(s[i]);
myArrayList.add(t);
i++;
}
for( i = 0 ; i < myArrayList.size(); i++)
{
System.out.println(myArrayList.get(i));
}
return myArrayList;
}
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
ArrayList<String> newArrayList = new ArrayList<String>();
String[] s = new String[4];
System.out.println("puts String");
for(int i = 0 ; i < 4 ; i++)
{
s[i] = keyboard.nextLine();
}
newArrayList = Ex14_1a.arrayToArrayList(s);
System.out.println(" what remove ?");
String remove;
remove = keyboard.nextLine();
Ex14_1a a = new Ex14_1a();
a.removeFromArrayList(newArrayList, remove);
int i = 0;
while( i < newArrayList.size())
{
System.out.println(newArrayList.get(i));
i ++;
}
}
public static void removeFromArrayList(ArrayList<String>list,String s){
list.remove(s);
}
}
| UTF-8 | Java | 1,195 | java | Ex14_1a.java | Java | []
| null | []
| import java.util.ArrayList;
import java.util.Scanner;
public class Ex14_1a {
public static ArrayList<String> arrayToArrayList(String[]s){
int i = 0;
ArrayList<String> myArrayList = new ArrayList<String>();
System.out.println("copy String_Array to arrayList");
while(i < s.length)
{
String t = new String(s[i]);
myArrayList.add(t);
i++;
}
for( i = 0 ; i < myArrayList.size(); i++)
{
System.out.println(myArrayList.get(i));
}
return myArrayList;
}
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
ArrayList<String> newArrayList = new ArrayList<String>();
String[] s = new String[4];
System.out.println("puts String");
for(int i = 0 ; i < 4 ; i++)
{
s[i] = keyboard.nextLine();
}
newArrayList = Ex14_1a.arrayToArrayList(s);
System.out.println(" what remove ?");
String remove;
remove = keyboard.nextLine();
Ex14_1a a = new Ex14_1a();
a.removeFromArrayList(newArrayList, remove);
int i = 0;
while( i < newArrayList.size())
{
System.out.println(newArrayList.get(i));
i ++;
}
}
public static void removeFromArrayList(ArrayList<String>list,String s){
list.remove(s);
}
}
| 1,195 | 0.65272 | 0.637657 | 48 | 23.895834 | 19.497051 | 72 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.458333 | false | false | 13 |
ca86dc92e166eee522fe5dfb875654e957e62d77 | 26,766,236,227,352 | fd1e74c00ca9b44d88f8ce37e728d64a0806a523 | /src/test/java/utils/SeleniumBaseFile.java | 3e7d5bc15ba1dced7dfb6253bc4a580000793fb9 | []
| no_license | bhavanisubsbabu/DaaS_1 | https://github.com/bhavanisubsbabu/DaaS_1 | 4feae88577d15d10a3008eff8e8428073afe58d5 | eed7e6a42dea1f61100e30c645e2f0f6f844ed9c | refs/heads/master | 2020-03-07T00:31:13.423000 | 2018-04-04T14:50:00 | 2018-04-04T14:50:00 | 127,159,482 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package utils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.openqa.selenium.WebDriver;
import java.io.FileInputStream;
import java.util.Properties;
public class SeleniumBaseFile {
static SeleniumBaseFile sel;
public Properties object_Repository;
public Properties configurations_File;
private BrowserFactory browserFactory;
static Log log = LogFactory.getLog(SeleniumBaseFile.class);
private SeleniumBaseFile() {
loadPropertiesFiles_();
}
public static SeleniumBaseFile getInstance() {
try {
if (sel == null)
sel = new SeleniumBaseFile();
} catch (Exception e) {
e.printStackTrace();
}
return sel;
}
public synchronized WebDriver sharedDriver() {
browserFactory = new BrowserFactory();
return browserFactory.getRemoteDriver();
}
private void loadPropertiesFiles_() {
if (object_Repository == null) {
try {
object_Repository = new Properties();
object_Repository.load(this.getClass().getClassLoader()
.getResourceAsStream("ObjectRepository.properties"));
log.info("load Object Repository");
} catch (Exception e) {
log.error("Error on intializing ObjectRepository files:"
+ e.getCause());
e.printStackTrace();
}
if (configurations_File == null) {
try {
configurations_File = new Properties();
configurations_File.load(new FileInputStream(
"OsMapMaker.properties"));
log.info("Load Config Repository");
} catch (Exception e) {
log.error("Error on intializing OsMapMaker properties Files"
+ e.getCause());
e.printStackTrace();
}
}
}
}
} | UTF-8 | Java | 1,640 | java | SeleniumBaseFile.java | Java | []
| null | []
| package utils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.openqa.selenium.WebDriver;
import java.io.FileInputStream;
import java.util.Properties;
public class SeleniumBaseFile {
static SeleniumBaseFile sel;
public Properties object_Repository;
public Properties configurations_File;
private BrowserFactory browserFactory;
static Log log = LogFactory.getLog(SeleniumBaseFile.class);
private SeleniumBaseFile() {
loadPropertiesFiles_();
}
public static SeleniumBaseFile getInstance() {
try {
if (sel == null)
sel = new SeleniumBaseFile();
} catch (Exception e) {
e.printStackTrace();
}
return sel;
}
public synchronized WebDriver sharedDriver() {
browserFactory = new BrowserFactory();
return browserFactory.getRemoteDriver();
}
private void loadPropertiesFiles_() {
if (object_Repository == null) {
try {
object_Repository = new Properties();
object_Repository.load(this.getClass().getClassLoader()
.getResourceAsStream("ObjectRepository.properties"));
log.info("load Object Repository");
} catch (Exception e) {
log.error("Error on intializing ObjectRepository files:"
+ e.getCause());
e.printStackTrace();
}
if (configurations_File == null) {
try {
configurations_File = new Properties();
configurations_File.load(new FileInputStream(
"OsMapMaker.properties"));
log.info("Load Config Repository");
} catch (Exception e) {
log.error("Error on intializing OsMapMaker properties Files"
+ e.getCause());
e.printStackTrace();
}
}
}
}
} | 1,640 | 0.703049 | 0.703049 | 72 | 21.791666 | 19.511349 | 65 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.305556 | false | false | 13 |
d35323d67598ea3cd8670694c406592b1833d23d | 17,136,919,529,168 | 0649ab19811f0d8c6ba0c921507717230372562b | /src/main/java/com/fieryinferno/aggregator/gateway/GroupGateway.java | 0fefd6d45202ee47fce254e21126d2e7392e67ab | []
| no_license | amiralit/aggregator | https://github.com/amiralit/aggregator | 3489d07b96fd3990e40a7e7bba776d0b940f6f06 | 3f89c2f46dd62baf4e75763b89ab7b5e070f8fdf | refs/heads/master | 2021-01-17T16:08:24.124000 | 2016-06-08T02:15:41 | 2016-06-08T02:15:41 | 57,847,880 | 0 | 0 | null | false | 2016-06-02T18:46:17 | 2016-05-01T21:37:11 | 2016-05-01T21:41:35 | 2016-06-02T18:46:17 | 29 | 0 | 0 | 0 | Java | null | null | package com.fieryinferno.aggregator.gateway;
import com.fasterxml.jackson.databind.JsonNode;
import java.util.Optional;
/**
* Created by atahmasebi on 4/23/16.
*/
public interface GroupGateway {
Optional<JsonNode> getGroupStandings(final String groupId);
}
| UTF-8 | Java | 266 | java | GroupGateway.java | Java | [
{
"context": "de;\n\nimport java.util.Optional;\n\n/**\n * Created by atahmasebi on 4/23/16.\n */\npublic interface GroupGateway {\n ",
"end": 151,
"score": 0.9996639490127563,
"start": 141,
"tag": "USERNAME",
"value": "atahmasebi"
}
]
| null | []
| package com.fieryinferno.aggregator.gateway;
import com.fasterxml.jackson.databind.JsonNode;
import java.util.Optional;
/**
* Created by atahmasebi on 4/23/16.
*/
public interface GroupGateway {
Optional<JsonNode> getGroupStandings(final String groupId);
}
| 266 | 0.774436 | 0.755639 | 12 | 21.166666 | 21.774731 | 63 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.333333 | false | false | 13 |
b54518e4c1785334eba54264cadcc43173977a26 | 18,348,100,292,508 | 17cd40f5e90fdab9df6ea898485f167e41a3f853 | /src/main/java/com/obidea/semantika/cli2/command/ShowPrefixesCommand.java | 05024471a63a27d7d261c59a344dd5c2ba285373 | [
"Apache-2.0"
]
| permissive | obidea/semantika-cli2 | https://github.com/obidea/semantika-cli2 | 4f7b4f1d585d3ab31faa3b3a8a420d256ff31fc9 | 81f296f6fc373c361d8a8a571dc22a907c01a65d | refs/heads/master | 2016-09-15T19:42:56.664000 | 2015-10-26T00:20:06 | 2015-10-26T00:20:06 | 22,249,342 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.obidea.semantika.cli2.command;
import java.io.PrintStream;
import java.util.Map;
import com.obidea.semantika.cli2.runtime.ConsoleSession;
import com.obidea.semantika.util.StringUtils;
public class ShowPrefixesCommand extends Command
{
private ConsoleSession mSession;
public ShowPrefixesCommand(String command, ConsoleSession session)
{
mSession = session;
}
@Override
public Object execute() throws Exception
{
return mSession.getPrefixes();
}
@Override
public void printOutput(PrintStream out, Object output)
{
if (output instanceof Map<?, ?>) {
@SuppressWarnings("unchecked")
Map<String, String> map = (Map<String, String>) output;
for (String key : map.keySet()) {
String prefix = key;
if (StringUtils.isEmpty(prefix)) {
prefix = "(default)"; //
}
out.println(prefix + " = " + map.get(key));
}
}
out.println();
}
}
| UTF-8 | Java | 1,002 | java | ShowPrefixesCommand.java | Java | []
| null | []
| package com.obidea.semantika.cli2.command;
import java.io.PrintStream;
import java.util.Map;
import com.obidea.semantika.cli2.runtime.ConsoleSession;
import com.obidea.semantika.util.StringUtils;
public class ShowPrefixesCommand extends Command
{
private ConsoleSession mSession;
public ShowPrefixesCommand(String command, ConsoleSession session)
{
mSession = session;
}
@Override
public Object execute() throws Exception
{
return mSession.getPrefixes();
}
@Override
public void printOutput(PrintStream out, Object output)
{
if (output instanceof Map<?, ?>) {
@SuppressWarnings("unchecked")
Map<String, String> map = (Map<String, String>) output;
for (String key : map.keySet()) {
String prefix = key;
if (StringUtils.isEmpty(prefix)) {
prefix = "(default)"; //
}
out.println(prefix + " = " + map.get(key));
}
}
out.println();
}
}
| 1,002 | 0.626747 | 0.62475 | 40 | 24.049999 | 21.303698 | 69 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.45 | false | false | 13 |
00797d6c86b81a23d0e3de3f7914dfc929f32712 | 32,555,852,141,878 | f19388bb3bc864585412b52c830de3b5122fbfab | /app/src/main/java/com/kumaj/githubapp_mvvm/businessmodel/service/AccountDataSource.java | 03dac0520a8c715f5f82d80e7aaa74bf667c6e22 | []
| no_license | kKumaJ/GitHubApp-mvvm | https://github.com/kKumaJ/GitHubApp-mvvm | 4a7ad7924b65c2aefcc53fd2eac4f8a0fdfe8ccc | 99b7081dfecd75924f000e2d55c62cc80f347b87 | refs/heads/master | 2018-04-14T17:59:03.171000 | 2016-10-24T00:15:10 | 2016-10-24T00:15:10 | 68,531,372 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.kumaj.githubapp_mvvm.businessmodel.service;
import android.accounts.Account;
import android.app.Application;
import android.util.Log;
import com.kumaj.githubapp_mvvm.api.GithubAuthRetrofit;
import com.kumaj.githubapp_mvvm.api.request.CreateAuthorization;
import com.kumaj.githubapp_mvvm.api.request.GithubConfig;
import com.kumaj.githubapp_mvvm.api.response.AuthorizationResp;
import com.kumaj.githubapp_mvvm.api.response.SearchResultResp;
import com.kumaj.githubapp_mvvm.api.response.apimodel.Repo;
import com.kumaj.githubapp_mvvm.api.response.apimodel.User;
import com.kumaj.githubapp_mvvm.api.service.AccountService;
import com.kumaj.githubapp_mvvm.businessmodel.RepoModel;
import com.kumaj.githubapp_mvvm.businessmodel.UserModel;
import com.kumaj.githubapp_mvvm.utils.AccountPref;
import dagger.Lazy;
import java.util.ArrayList;
import javax.inject.Inject;
import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action0;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.Schedulers;
public class AccountDataSource extends BaseDataSource<AuthorizationResp> implements AccountApi {
@Inject //the make multi retrofit
GithubAuthRetrofit mGithubAuthRetrofit;
@Inject
Application mContext;
@Inject
Lazy<AccountService> mLazyService; //cause we need to set the AuthInfo first
@Inject
public AccountDataSource() {
}
@Override public Observable<UserModel> login(String username, String password) {
CreateAuthorization createAuthorization = new CreateAuthorization();
createAuthorization.note = GithubConfig.NOTE;
createAuthorization.client_id = GithubConfig.CLIENT_ID;
createAuthorization.client_secret = GithubConfig.CLIENT_SECRET;
createAuthorization.scopes = GithubConfig.SCOPES;
mGithubAuthRetrofit.setAuthInfo(username, password);
return mLazyService.get()
.createAuthorization(createAuthorization)
.compose(errorTransformer)
.flatMap(new Func1<AuthorizationResp, Observable<UserModel>>() {
@Override public Observable<UserModel> call(AuthorizationResp authorizationResp) {
String token = authorizationResp.token;
Log.e("TAG", "token = " + token);
// save token
AccountPref.saveLoginToken(mContext, token);
return getUserInfo(token);
}
});
}
@Override public Observable<UserModel> searchUserInfo(String username) {
return mLazyService.get()
.searchUserInfo(username)
.map(new Func1<User, UserModel>() {
@Override public UserModel call(User user) {
return user.getUserModel();
}
});
}
@Override public Observable<UserModel> getUserInfo(String token) {
return mLazyService.get()
.getUserInfo(token)
.map(new Func1<User, UserModel>() {
@Override public UserModel call(User user) {
return user.getUserModel();
}
});
}
}
| UTF-8 | Java | 3,195 | java | AccountDataSource.java | Java | []
| null | []
| package com.kumaj.githubapp_mvvm.businessmodel.service;
import android.accounts.Account;
import android.app.Application;
import android.util.Log;
import com.kumaj.githubapp_mvvm.api.GithubAuthRetrofit;
import com.kumaj.githubapp_mvvm.api.request.CreateAuthorization;
import com.kumaj.githubapp_mvvm.api.request.GithubConfig;
import com.kumaj.githubapp_mvvm.api.response.AuthorizationResp;
import com.kumaj.githubapp_mvvm.api.response.SearchResultResp;
import com.kumaj.githubapp_mvvm.api.response.apimodel.Repo;
import com.kumaj.githubapp_mvvm.api.response.apimodel.User;
import com.kumaj.githubapp_mvvm.api.service.AccountService;
import com.kumaj.githubapp_mvvm.businessmodel.RepoModel;
import com.kumaj.githubapp_mvvm.businessmodel.UserModel;
import com.kumaj.githubapp_mvvm.utils.AccountPref;
import dagger.Lazy;
import java.util.ArrayList;
import javax.inject.Inject;
import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action0;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.Schedulers;
public class AccountDataSource extends BaseDataSource<AuthorizationResp> implements AccountApi {
@Inject //the make multi retrofit
GithubAuthRetrofit mGithubAuthRetrofit;
@Inject
Application mContext;
@Inject
Lazy<AccountService> mLazyService; //cause we need to set the AuthInfo first
@Inject
public AccountDataSource() {
}
@Override public Observable<UserModel> login(String username, String password) {
CreateAuthorization createAuthorization = new CreateAuthorization();
createAuthorization.note = GithubConfig.NOTE;
createAuthorization.client_id = GithubConfig.CLIENT_ID;
createAuthorization.client_secret = GithubConfig.CLIENT_SECRET;
createAuthorization.scopes = GithubConfig.SCOPES;
mGithubAuthRetrofit.setAuthInfo(username, password);
return mLazyService.get()
.createAuthorization(createAuthorization)
.compose(errorTransformer)
.flatMap(new Func1<AuthorizationResp, Observable<UserModel>>() {
@Override public Observable<UserModel> call(AuthorizationResp authorizationResp) {
String token = authorizationResp.token;
Log.e("TAG", "token = " + token);
// save token
AccountPref.saveLoginToken(mContext, token);
return getUserInfo(token);
}
});
}
@Override public Observable<UserModel> searchUserInfo(String username) {
return mLazyService.get()
.searchUserInfo(username)
.map(new Func1<User, UserModel>() {
@Override public UserModel call(User user) {
return user.getUserModel();
}
});
}
@Override public Observable<UserModel> getUserInfo(String token) {
return mLazyService.get()
.getUserInfo(token)
.map(new Func1<User, UserModel>() {
@Override public UserModel call(User user) {
return user.getUserModel();
}
});
}
}
| 3,195 | 0.690141 | 0.688263 | 90 | 34.5 | 26.482803 | 98 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.544444 | false | false | 13 |
30a58dfcdc49e579ce2bcd9e0f7c73f3c63e5e02 | 17,025,250,405,101 | e609020831394c76189a35ad91d3c1b169e9552d | /src/patinete/Patinete.java | e5b7e98d7145926e56de426a356e235141f7939e | []
| no_license | luanacarolina/POO-Java-Generation | https://github.com/luanacarolina/POO-Java-Generation | 35881ba12d1e4664d266d8cb307978ebfea7d5c5 | 14621002ffc0d7d542c767634423a373233debbb | refs/heads/master | 2022-11-12T18:15:34.029000 | 2020-07-16T22:48:15 | 2020-07-16T22:48:15 | 279,422,729 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package patinete;
public class Patinete {
private String marca;
private String modelo;
private String cor;
private int quantidadeRodas;
public Patinete (String marca,String modelo,String cor,int quantidadeRodas){
this.marca=marca;
this.modelo=modelo;
this.cor=cor;
this.quantidadeRodas=quantidadeRodas;
}
public void mostrarDados(){
System.out.println("Dados Patinete********");
System.out.println("Marca: "+marca);
System.out.println("Modelo: "+modelo);
System.out.println("Cor: "+cor);
System.out.println("Quantidade De Rodas: "+quantidadeRodas);
}
}
| UTF-8 | Java | 661 | java | Patinete.java | Java | []
| null | []
| package patinete;
public class Patinete {
private String marca;
private String modelo;
private String cor;
private int quantidadeRodas;
public Patinete (String marca,String modelo,String cor,int quantidadeRodas){
this.marca=marca;
this.modelo=modelo;
this.cor=cor;
this.quantidadeRodas=quantidadeRodas;
}
public void mostrarDados(){
System.out.println("Dados Patinete********");
System.out.println("Marca: "+marca);
System.out.println("Modelo: "+modelo);
System.out.println("Cor: "+cor);
System.out.println("Quantidade De Rodas: "+quantidadeRodas);
}
}
| 661 | 0.642965 | 0.642965 | 24 | 26.541666 | 21.488329 | 80 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.708333 | false | false | 13 |
cc14ce98641f6a27a81bd13a92dca38415bcfd60 | 9,723,805,961,402 | 7de8e513166e9996bd32096f7ec2effdca246991 | /tls-client-android/app/src/main/java/de/tum/in/net/client/TlsService.java | 8d6694cc8288937f15c3e25f480a162bfe914094 | [
"Apache-2.0"
]
| permissive | tumi8/interceptls | https://github.com/tumi8/interceptls | b469cd665c45231606406c0c1e88713f8b74a576 | fe7bb9a0ca75a470438dab2f2bfc8441770c8ef0 | refs/heads/master | 2021-06-02T02:25:34.960000 | 2018-09-06T06:54:26 | 2018-09-06T06:54:26 | 147,201,046 | 1 | 1 | Apache-2.0 | false | 2020-12-13T05:21:28 | 2018-09-03T12:20:30 | 2018-09-06T07:07:00 | 2020-12-13T05:21:27 | 5,915 | 2 | 0 | 13 | Java | false | false | /**
* Copyright ยฉ 2018 Johannes Schleger (johannes.schleger@tum.de)
*
* 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 de.tum.in.net.client;
import android.app.IntentService;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.ResultReceiver;
import android.preference.PreferenceManager;
import android.support.annotation.Nullable;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.NotificationManagerCompat;
import android.support.v4.content.ContextCompat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
import de.tum.in.net.model.TlsTestResult;
/**
* Created by johannes on 21.03.18.
*/
public class TlsService extends IntentService {
private static final Logger log = LoggerFactory.getLogger(TlsService.class);
public TlsService() {
super("TlsService");
}
public static void start(Context ctx){
final Intent i = new Intent(ctx, TlsService.class);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
//from oreo on startService throws an IllegalStateException, see https://developer.android.com/about/versions/oreo/android-8.0-changes
ctx.startForegroundService(i);
} else {
ctx.startService(i);
}
}
@Override
public void onCreate() {
super.onCreate();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
final String CHANNEL_ID = "tls_service_channel";
final NotificationChannel channel = new NotificationChannel(CHANNEL_ID,
"intercepTLS service",
NotificationManager.IMPORTANCE_DEFAULT);
((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE)).createNotificationChannel(channel);
final Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
.setSmallIcon(R.drawable.ic_interception)
.setContentTitle(getString(R.string.app_name))
.setContentText(getString(R.string.notification_conduct_test)).build();
startForeground(1, notification);
}
}
@Override
protected void onHandleIntent(@Nullable final Intent intent) {
log.debug("onHandleIntent TlsService");
if (ContextCompat.checkSelfPermission(this, MainActivity.LOCATION_PERMISSION)
!= PackageManager.PERMISSION_GRANTED) {
log.error("We do not have the permission to access the location. Cannot execute test.");
return;
}
TlsTestResult result = null;
//ignore how much time since last scan passed
final boolean force = intent.getBooleanExtra("force", false);
final TlsDB db = new TlsDB(this);
if (force || db.enoughTimeSinceLastScan()) {
try {
final List<HostAndPort> targets = ConfigurationReader.getTargets(this);
final ClientWorkflowCallable c = new ClientWorkflowCallable(targets, new AndroidNetworkIdentifier(this));
result = c.call();
} catch (final Exception e) {
log.error("Could not finish TLS test", e);
}
} else {
log.info("Not enough time has passed since last scan, skip this round.");
}
if (result != null && result.anySuccessfulConnection()) {
//save result
db.saveResultTemp(result);
//upload result
final Intent i = new Intent(this, UploadResultService.class);
this.startService(i);
//inform user
if (result.anyInterception()) {
final NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this, "")
.setSmallIcon(R.drawable.ic_interception)
.setContentTitle(this.getString(R.string.interception_title))
.setContentText("Your connection is intercepted!")
.setPriority(NotificationCompat.PRIORITY_HIGH);
final NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
// notificationId is a unique int for each notification that you must define
notificationManager.notify(0, mBuilder.build());
}
}
//publish result
final ResultReceiver rec = intent.getParcelableExtra("resultReceiver");
if (rec != null) {
if (result != null && result.anySuccessfulConnection()) {
final Bundle b = new Bundle();
b.putString("timestamp", result.getTimestamp());
rec.send(0, b);
} else {
rec.send(-1, null);
}
}
}
}
| UTF-8 | Java | 5,583 | java | TlsService.java | Java | [
{
"context": "/**\n * Copyright ยฉ 2018 Johannes Schleger (johannes.schleger@tum.de)\n *\n * Licensed under t",
"end": 41,
"score": 0.999875545501709,
"start": 24,
"tag": "NAME",
"value": "Johannes Schleger"
},
{
"context": "/**\n * Copyright ยฉ 2018 Johannes Schleger (johannes.schleger@tum.de)\n *\n * Licensed under the Apache License, Version",
"end": 67,
"score": 0.9999303221702576,
"start": 43,
"tag": "EMAIL",
"value": "johannes.schleger@tum.de"
},
{
"context": "tum.in.net.model.TlsTestResult;\n\n/**\n * Created by johannes on 21.03.18.\n */\n\npublic class TlsService extends",
"end": 1438,
"score": 0.9977257251739502,
"start": 1430,
"tag": "USERNAME",
"value": "johannes"
}
]
| null | []
| /**
* Copyright ยฉ 2018 <NAME> (<EMAIL>)
*
* 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 de.tum.in.net.client;
import android.app.IntentService;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.ResultReceiver;
import android.preference.PreferenceManager;
import android.support.annotation.Nullable;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.NotificationManagerCompat;
import android.support.v4.content.ContextCompat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
import de.tum.in.net.model.TlsTestResult;
/**
* Created by johannes on 21.03.18.
*/
public class TlsService extends IntentService {
private static final Logger log = LoggerFactory.getLogger(TlsService.class);
public TlsService() {
super("TlsService");
}
public static void start(Context ctx){
final Intent i = new Intent(ctx, TlsService.class);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
//from oreo on startService throws an IllegalStateException, see https://developer.android.com/about/versions/oreo/android-8.0-changes
ctx.startForegroundService(i);
} else {
ctx.startService(i);
}
}
@Override
public void onCreate() {
super.onCreate();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
final String CHANNEL_ID = "tls_service_channel";
final NotificationChannel channel = new NotificationChannel(CHANNEL_ID,
"intercepTLS service",
NotificationManager.IMPORTANCE_DEFAULT);
((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE)).createNotificationChannel(channel);
final Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
.setSmallIcon(R.drawable.ic_interception)
.setContentTitle(getString(R.string.app_name))
.setContentText(getString(R.string.notification_conduct_test)).build();
startForeground(1, notification);
}
}
@Override
protected void onHandleIntent(@Nullable final Intent intent) {
log.debug("onHandleIntent TlsService");
if (ContextCompat.checkSelfPermission(this, MainActivity.LOCATION_PERMISSION)
!= PackageManager.PERMISSION_GRANTED) {
log.error("We do not have the permission to access the location. Cannot execute test.");
return;
}
TlsTestResult result = null;
//ignore how much time since last scan passed
final boolean force = intent.getBooleanExtra("force", false);
final TlsDB db = new TlsDB(this);
if (force || db.enoughTimeSinceLastScan()) {
try {
final List<HostAndPort> targets = ConfigurationReader.getTargets(this);
final ClientWorkflowCallable c = new ClientWorkflowCallable(targets, new AndroidNetworkIdentifier(this));
result = c.call();
} catch (final Exception e) {
log.error("Could not finish TLS test", e);
}
} else {
log.info("Not enough time has passed since last scan, skip this round.");
}
if (result != null && result.anySuccessfulConnection()) {
//save result
db.saveResultTemp(result);
//upload result
final Intent i = new Intent(this, UploadResultService.class);
this.startService(i);
//inform user
if (result.anyInterception()) {
final NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this, "")
.setSmallIcon(R.drawable.ic_interception)
.setContentTitle(this.getString(R.string.interception_title))
.setContentText("Your connection is intercepted!")
.setPriority(NotificationCompat.PRIORITY_HIGH);
final NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
// notificationId is a unique int for each notification that you must define
notificationManager.notify(0, mBuilder.build());
}
}
//publish result
final ResultReceiver rec = intent.getParcelableExtra("resultReceiver");
if (rec != null) {
if (result != null && result.anySuccessfulConnection()) {
final Bundle b = new Bundle();
b.putString("timestamp", result.getTimestamp());
rec.send(0, b);
} else {
rec.send(-1, null);
}
}
}
}
| 5,555 | 0.647797 | 0.643318 | 155 | 35.012905 | 31.601549 | 146 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.503226 | false | false | 13 |
f8b81a14286244e8d79ec21870c62535f1eefd48 | 9,053,791,074,093 | 8ed3ae6e00901e10945e945506a5add6c392086d | /src/test/java/com/zzgs/post_bar/ShiroMD5Test.java | ea651638932a79c794c2606fd770821b1d072208 | []
| no_license | li334578/post_bar | https://github.com/li334578/post_bar | 1ba334f67aa77f4abe3d12e26f261e1d50c93a2d | e59556edac93d307aeac6740f9a022aa0252b09f | refs/heads/master | 2023-03-06T12:50:35.206000 | 2021-11-27T13:34:49 | 2021-11-27T13:34:49 | 231,584,493 | 4 | 0 | null | false | 2023-02-22T07:39:53 | 2020-01-03T12:32:10 | 2021-11-27T13:44:11 | 2023-02-22T07:39:52 | 11,523 | 2 | 0 | 5 | HTML | false | false | package com.zzgs.post_bar;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.util.ByteSource;
/**
* Author: Tang
* Date: 2019/12/30 14:04
* Description:
*/
public class ShiroMD5Test {
public static void main(String[] args) {
String password = "qianyi";//ๆ็
String algorithmName = "MD5";//ๅ ๅฏ็ฎๆณ
Object source = password;//่ฆๅ ๅฏ็ๅฏ็
Object salt = "qianyi";//็ๅผ๏ผไธ่ฌ้ฝๆฏ็จๆทๅๆ่
userid๏ผ่ฆไฟ่ฏๅฏไธ
int hashIterations = 10;//ๅ ๅฏๆฌกๆฐ
ByteSource credentialsSalt = ByteSource.Util.bytes(salt);
SimpleHash simpleHash = new SimpleHash(algorithmName,source,credentialsSalt,hashIterations);
System.out.println(simpleHash);//ๆๅฐๅบ็ป่ฟ็ๅผใๅ ๅฏๆฌกๆฐใmd5ๅ็ๅฏ็
}
}
| UTF-8 | Java | 827 | java | ShiroMD5Test.java | Java | [
{
"context": "rg.apache.shiro.util.ByteSource;\n\n/**\n * Author: Tang\n * Date: 2019/12/30 14:04\n * Description:\n */",
"end": 139,
"score": 0.9556950330734253,
"start": 135,
"tag": "NAME",
"value": "Tang"
},
{
"context": " main(String[] args) {\n String password = \"qianyi\";//ๆ็ \n String algorithmName = \"MD5\";//ๅ ๅฏ็ฎๆณ",
"end": 296,
"score": 0.9994769096374512,
"start": 290,
"tag": "PASSWORD",
"value": "qianyi"
},
{
"context": "rce = password;//่ฆๅ ๅฏ็ๅฏ็ \n\n Object salt = \"qianyi\";//็ๅผ๏ผไธ่ฌ้ฝๆฏ็จๆทๅๆ่
userid๏ผ่ฆไฟ่ฏๅฏไธ\n int hashItera",
"end": 419,
"score": 0.5280452966690063,
"start": 415,
"tag": "PASSWORD",
"value": "anyi"
}
]
| null | []
| package com.zzgs.post_bar;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.util.ByteSource;
/**
* Author: Tang
* Date: 2019/12/30 14:04
* Description:
*/
public class ShiroMD5Test {
public static void main(String[] args) {
String password = "<PASSWORD>";//ๆ็
String algorithmName = "MD5";//ๅ ๅฏ็ฎๆณ
Object source = password;//่ฆๅ ๅฏ็ๅฏ็
Object salt = "qi<PASSWORD>";//็ๅผ๏ผไธ่ฌ้ฝๆฏ็จๆทๅๆ่
userid๏ผ่ฆไฟ่ฏๅฏไธ
int hashIterations = 10;//ๅ ๅฏๆฌกๆฐ
ByteSource credentialsSalt = ByteSource.Util.bytes(salt);
SimpleHash simpleHash = new SimpleHash(algorithmName,source,credentialsSalt,hashIterations);
System.out.println(simpleHash);//ๆๅฐๅบ็ป่ฟ็ๅผใๅ ๅฏๆฌกๆฐใmd5ๅ็ๅฏ็
}
}
| 837 | 0.68 | 0.656552 | 24 | 29.208334 | 25.628727 | 100 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.583333 | false | false | 13 |
fb4fa4c2af6df6017e90ff16b0c2df84e59d9090 | 15,762,529,985,793 | 445b2d5e7e486510cf602f9dca675ab9d06722eb | /app/src/main/java/com/example/facebooklogin/ChatAdapter.java | a632bc60df5bf9a368da99b6bc9cdbad165a2b64 | []
| no_license | 1083606/facebookLogin | https://github.com/1083606/facebookLogin | 490572f72a5331e3d2ac59077c1661c667ffd396 | b488e4a0244295d134c57c61adcb5345c9dfec59 | refs/heads/master | 2023-01-21T11:47:41.446000 | 2020-12-03T17:59:36 | 2020-12-03T17:59:36 | 264,361,554 | 0 | 1 | null | false | 2020-06-04T21:14:20 | 2020-05-16T04:51:27 | 2020-06-03T13:00:55 | 2020-06-04T21:14:19 | 914 | 0 | 1 | 0 | Java | false | false | package com.example.facebooklogin;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
public class ChatAdapter extends RecyclerView.Adapter<com.example.facebooklogin.ChatAdapter.CustomViewHolder> {
List<Response> responseMessages;
Context context;
class CustomViewHolder extends RecyclerView.ViewHolder{
TextView textView;
public CustomViewHolder(View itemView) {
super(itemView);
textView = itemView.findViewById(R.id.textMessage);
}
}
public ChatAdapter(List<Response> responseMessages, Context context) {
this.responseMessages = responseMessages;
this.context = context;
}
@Override
public int getItemViewType(int position) {
if(responseMessages.get(position).isMe()){
return R.layout.me_bubble;
}if(responseMessages.get(position).isBot()){
return R.layout.botremind;
}
return R.layout.bot_bubble;
}
@Override
public int getItemCount() {
return responseMessages.size();
}
@Override
public CustomViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return new CustomViewHolder(LayoutInflater.from(parent.getContext())
.inflate(viewType, parent, false));
}
@Override
public void onBindViewHolder(@NonNull CustomViewHolder holder, int position) {
holder.textView.setText(responseMessages.get(position).getText());
}
}
| UTF-8 | Java | 1,856 | java | ChatAdapter.java | Java | []
| null | []
| package com.example.facebooklogin;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
public class ChatAdapter extends RecyclerView.Adapter<com.example.facebooklogin.ChatAdapter.CustomViewHolder> {
List<Response> responseMessages;
Context context;
class CustomViewHolder extends RecyclerView.ViewHolder{
TextView textView;
public CustomViewHolder(View itemView) {
super(itemView);
textView = itemView.findViewById(R.id.textMessage);
}
}
public ChatAdapter(List<Response> responseMessages, Context context) {
this.responseMessages = responseMessages;
this.context = context;
}
@Override
public int getItemViewType(int position) {
if(responseMessages.get(position).isMe()){
return R.layout.me_bubble;
}if(responseMessages.get(position).isBot()){
return R.layout.botremind;
}
return R.layout.bot_bubble;
}
@Override
public int getItemCount() {
return responseMessages.size();
}
@Override
public CustomViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return new CustomViewHolder(LayoutInflater.from(parent.getContext())
.inflate(viewType, parent, false));
}
@Override
public void onBindViewHolder(@NonNull CustomViewHolder holder, int position) {
holder.textView.setText(responseMessages.get(position).getText());
}
}
| 1,856 | 0.711207 | 0.711207 | 62 | 28.935484 | 24.946957 | 111 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.532258 | false | false | 13 |
58bc5e61401841649cb1829d3b11de431842e3c9 | 4,870,492,947,845 | 03a71fc1ec832dacadfaca8eeba5eb027f8deda2 | /src/main/java/module/ten/CarComponent.java | ddbf91111113ff3c3a758cc1f30843c74ec3f7ab | []
| no_license | cvgaviao/dagger-experiments | https://github.com/cvgaviao/dagger-experiments | 65c807797e382dda0e05cad443db7c4fe7056759 | 3bf52a1fc602014ec55bec31e5fe7563f3c90eb3 | refs/heads/master | 2020-08-06T13:27:59.821000 | 2019-10-08T22:29:43 | 2019-10-08T22:31:36 | 212,991,627 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package module.ten;
import javax.inject.Named;
import javax.inject.Singleton;
import dagger.BindsInstance;
import dagger.Component;
@Singleton
@Component(modules = { WheelsModule.class, PetroilEngineModule.class })
public interface CarComponent {
Car createCar();
@Component.Builder
interface Builder {
@BindsInstance
Builder horsePower(@Named("horse power") int horsePower);
@BindsInstance
Builder engineCapacity(@Named("engine capacity") int engineCapacity);
CarComponent build();
}
}
| UTF-8 | Java | 552 | java | CarComponent.java | Java | []
| null | []
| package module.ten;
import javax.inject.Named;
import javax.inject.Singleton;
import dagger.BindsInstance;
import dagger.Component;
@Singleton
@Component(modules = { WheelsModule.class, PetroilEngineModule.class })
public interface CarComponent {
Car createCar();
@Component.Builder
interface Builder {
@BindsInstance
Builder horsePower(@Named("horse power") int horsePower);
@BindsInstance
Builder engineCapacity(@Named("engine capacity") int engineCapacity);
CarComponent build();
}
}
| 552 | 0.710145 | 0.710145 | 25 | 21.08 | 21.627611 | 77 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.4 | false | false | 13 |
a57c2af2a01d6c09ae71fa3824481f9f8b493e54 | 23,682,449,691,031 | 66d98b47c12aba99ee509e9d0e9562eeca750d03 | /src/main/java/com/example/awebapp/AWebAppApplication.java | a34292c9d5b247c1563ca2701c3ce5823ec9da64 | []
| no_license | BerendF/AWebApp | https://github.com/BerendF/AWebApp | e75fd79add44af0b7521d6fb43f7014e9b5479af | 4901d9088627d8d6289c9ab4eb809aadf2dcde26 | refs/heads/main | 2023-08-12T07:50:21.816000 | 2021-09-29T08:51:16 | 2021-09-29T08:51:16 | 410,770,466 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.awebapp;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.Locale;
@SpringBootApplication
public class AWebAppApplication {
public static void main(String[] args) {
SpringApplication.run(AWebAppApplication.class, args);
}
@Bean
CommandLineRunner init(TutorialRepository tutorialRepository, WikiRepository wikiRepository) {
return args -> {
String date = new Date().toString();
DateFormat formatterFull = new SimpleDateFormat("E MMM dd HH:mm:ss Z yyyy", Locale.US);
DateFormat formatterSimple = new SimpleDateFormat("dd.MM.yyyy");
date = formatterSimple.format(formatterFull.parse(date));
Tutorial[] t = new Tutorial[11];
t[0] = new Tutorial("Baeldung-WebApp with Spring and Angular", "https://www.baeldung.com/spring-boot-angular-web", 4.0, "base for this page", date);
t[1] = new Tutorial("Tutorialspoint-SAP Hybris", "https://www.tutorialspoint.com/sap_hybris/index.htm", 2.0, "largely outdated", date);
t[2] = new Tutorial("Tutorialspoint Spring XML-based beans", "https://www.tutorialspoint.com/spring/index.htm", 5.0, "- instructive - easy to follow", date);
t[3] = new Tutorial("Angular.io Tutorial", "https://angular.io/tutorial", 5.0, "well structured, instructive content", date);
t[4] = new Tutorial("Spring.io Database", "https://spring.io/guides/gs/relational-data-access/", 1.0, "deprecated, too elementary", date);
t[5] = new Tutorial("Angular.de Tutorial", "https://angular.de/artikel/angular-tutorial-deutsch/", 3.0, "solid, but lacking", date);
t[6] = new Tutorial("Spartacus Visualization", "https://microlearning.opensap.com/playlist/dedicated/178318381/1_sokuy66v/1_8mmwx8ck", 2.0, "not for developers, otherwise fine tutorial", date);
t[7] = new Tutorial("SAP Commerce Visualization", "https://microlearning.opensap.com/playlist/dedicated/178317751/1_4ugj2pn9/1_zsyss1nz", 2.0, "not for developers, otherwise fine tutorial", date);
t[8] = new Tutorial("CronJobs", "http://javainsimpleway.com/cron-jobs-overview/", 3.0, "basic, still instructive", date);
t[9] = new Tutorial("Spring Angular Security", "https://spring.io/guides/tutorials/spring-security-and-angular-js/", 1.0, "mostly deprecated dependencies", date);
t[10] = new Tutorial("Spring Bean Configuration", "https://www.codingame.com/playgrounds/2096/playing-around-with-spring-bean-configuration", 3.0, "fine as a quick reference", date);
Wiki w = new Wiki("SAP Commerce Wiki", "https://help.sap.com/viewer/product/SAP_COMMERCE_CLOUD/SHIP/en-US?task=discover_task");
tutorialRepository.saveAll(Arrays.asList(t));
wikiRepository.save(w);
};
}
}
| UTF-8 | Java | 3,128 | java | AWebAppApplication.java | Java | []
| null | []
| package com.example.awebapp;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.Locale;
@SpringBootApplication
public class AWebAppApplication {
public static void main(String[] args) {
SpringApplication.run(AWebAppApplication.class, args);
}
@Bean
CommandLineRunner init(TutorialRepository tutorialRepository, WikiRepository wikiRepository) {
return args -> {
String date = new Date().toString();
DateFormat formatterFull = new SimpleDateFormat("E MMM dd HH:mm:ss Z yyyy", Locale.US);
DateFormat formatterSimple = new SimpleDateFormat("dd.MM.yyyy");
date = formatterSimple.format(formatterFull.parse(date));
Tutorial[] t = new Tutorial[11];
t[0] = new Tutorial("Baeldung-WebApp with Spring and Angular", "https://www.baeldung.com/spring-boot-angular-web", 4.0, "base for this page", date);
t[1] = new Tutorial("Tutorialspoint-SAP Hybris", "https://www.tutorialspoint.com/sap_hybris/index.htm", 2.0, "largely outdated", date);
t[2] = new Tutorial("Tutorialspoint Spring XML-based beans", "https://www.tutorialspoint.com/spring/index.htm", 5.0, "- instructive - easy to follow", date);
t[3] = new Tutorial("Angular.io Tutorial", "https://angular.io/tutorial", 5.0, "well structured, instructive content", date);
t[4] = new Tutorial("Spring.io Database", "https://spring.io/guides/gs/relational-data-access/", 1.0, "deprecated, too elementary", date);
t[5] = new Tutorial("Angular.de Tutorial", "https://angular.de/artikel/angular-tutorial-deutsch/", 3.0, "solid, but lacking", date);
t[6] = new Tutorial("Spartacus Visualization", "https://microlearning.opensap.com/playlist/dedicated/178318381/1_sokuy66v/1_8mmwx8ck", 2.0, "not for developers, otherwise fine tutorial", date);
t[7] = new Tutorial("SAP Commerce Visualization", "https://microlearning.opensap.com/playlist/dedicated/178317751/1_4ugj2pn9/1_zsyss1nz", 2.0, "not for developers, otherwise fine tutorial", date);
t[8] = new Tutorial("CronJobs", "http://javainsimpleway.com/cron-jobs-overview/", 3.0, "basic, still instructive", date);
t[9] = new Tutorial("Spring Angular Security", "https://spring.io/guides/tutorials/spring-security-and-angular-js/", 1.0, "mostly deprecated dependencies", date);
t[10] = new Tutorial("Spring Bean Configuration", "https://www.codingame.com/playgrounds/2096/playing-around-with-spring-bean-configuration", 3.0, "fine as a quick reference", date);
Wiki w = new Wiki("SAP Commerce Wiki", "https://help.sap.com/viewer/product/SAP_COMMERCE_CLOUD/SHIP/en-US?task=discover_task");
tutorialRepository.saveAll(Arrays.asList(t));
wikiRepository.save(w);
};
}
}
| 3,128 | 0.695652 | 0.673274 | 48 | 64.166664 | 63.533894 | 208 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.770833 | false | false | 13 |
4aab33961beb0eae7d9ea582d0af948e3d21f84c | 18,322,330,492,555 | a263c3d9bdd2be9a4d37cb37e4173647d447adac | /src/main/java/com/manager/base/BaseMapper.java | c6a1849c132e51e0c8dc0973b3f1a71ed74573ca | []
| no_license | BenOniShi/crm | https://github.com/BenOniShi/crm | b5a54c16696e6a5408f2dc39c0356010cca34916 | d8b6cfbfad38908ee9aaca25bc9dede10a062f43 | refs/heads/master | 2020-08-06T21:39:10.925000 | 2019-12-03T15:52:54 | 2019-12-03T15:52:54 | 210,774,515 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.manager.base;
import com.github.pagehelper.PageInfo;
import java.util.List;
import java.util.Map;
/**
* BaseMapper ๆฅๅฃๆนๆณๅฎไน
* ๅบๆฌCRUD ๆนๆณๅฎไน
*
* ๆทปๅ
* ๆทปๅ ่ฎฐๅฝ ่ฟๅๅฝฑๅ่กๆฐ
* ๆทปๅ ่ฎฐๅฝ่ฟๅไธป้ฎ
* ๆน้ๆทปๅ
* ๆฅ่ฏข
* ่ฏฆๆ
ๆฅ่ฏข
* ๅ่กจๆฅ่ฏข๏ผๅ้กต ไธๅ้กต๏ผ
* ๆดๆฐ
* ๅๆก่ฎฐๅฝๆดๆฐ
* ๆน้ๆดๆฐ
* ๅ ้ค
* ๅๆก่ฎฐๅฝๅ ้ค
* ๆน้ๅ ้ค
*/
public interface BaseMapper<T,ID> {
/**
* ๆทปๅ ่ฎฐๅฝ ่ฟๅๅฝฑๅ่กๆฐ
* @param entity
* @return
*/
public int save(T entity);
/**
* ๆทปๅ ่ฎฐๅฝ ่ฟๅไธป้ฎ
* @param entity
* @return
*/
public ID saveHasKey(T entity);
/**
* ๆน้ๆทปๅ
* @param entities
* @return
*/
public int saveBatch(List<T> entities);
/**
* ่ฎฐๅฝ่ฏฆๆ
ๆฅ่ฏข
* @param id
* @return
*/
public T queryById(ID id);
/**
* ๅคๆกไปถๅ่กจๆฅ่ฏข
* @param baseQuery
* @return
*/
public List<T> queryByParams(BaseQuery baseQuery);
/**
* ๅ้กตๆฅ่ฏข
* @param baseQuery
* @return
*/
public PageInfo<T> queryByParamsForPage(BaseQuery baseQuery);
/**
* ๆดๆฐๅๆก่ฎฐๅฝ
* @param entity
* @return
*/
public int update(T entity);
/**
* ๆน้ๆดๆฐ
* @param map
* @return
*/
public int updateBatch(Map<String, Object> map);
/**
* ๅ ้คๅๆก่ฎฐๅฝ
* @param id
* @return
*/
public int delete(ID id);
/**
* ๆน้ๅ ้ค
* @param ids
* @return
*/
public int deleteBatch(ID[] ids);
}
| UTF-8 | Java | 1,728 | java | BaseMapper.java | Java | []
| null | []
| package com.manager.base;
import com.github.pagehelper.PageInfo;
import java.util.List;
import java.util.Map;
/**
* BaseMapper ๆฅๅฃๆนๆณๅฎไน
* ๅบๆฌCRUD ๆนๆณๅฎไน
*
* ๆทปๅ
* ๆทปๅ ่ฎฐๅฝ ่ฟๅๅฝฑๅ่กๆฐ
* ๆทปๅ ่ฎฐๅฝ่ฟๅไธป้ฎ
* ๆน้ๆทปๅ
* ๆฅ่ฏข
* ่ฏฆๆ
ๆฅ่ฏข
* ๅ่กจๆฅ่ฏข๏ผๅ้กต ไธๅ้กต๏ผ
* ๆดๆฐ
* ๅๆก่ฎฐๅฝๆดๆฐ
* ๆน้ๆดๆฐ
* ๅ ้ค
* ๅๆก่ฎฐๅฝๅ ้ค
* ๆน้ๅ ้ค
*/
public interface BaseMapper<T,ID> {
/**
* ๆทปๅ ่ฎฐๅฝ ่ฟๅๅฝฑๅ่กๆฐ
* @param entity
* @return
*/
public int save(T entity);
/**
* ๆทปๅ ่ฎฐๅฝ ่ฟๅไธป้ฎ
* @param entity
* @return
*/
public ID saveHasKey(T entity);
/**
* ๆน้ๆทปๅ
* @param entities
* @return
*/
public int saveBatch(List<T> entities);
/**
* ่ฎฐๅฝ่ฏฆๆ
ๆฅ่ฏข
* @param id
* @return
*/
public T queryById(ID id);
/**
* ๅคๆกไปถๅ่กจๆฅ่ฏข
* @param baseQuery
* @return
*/
public List<T> queryByParams(BaseQuery baseQuery);
/**
* ๅ้กตๆฅ่ฏข
* @param baseQuery
* @return
*/
public PageInfo<T> queryByParamsForPage(BaseQuery baseQuery);
/**
* ๆดๆฐๅๆก่ฎฐๅฝ
* @param entity
* @return
*/
public int update(T entity);
/**
* ๆน้ๆดๆฐ
* @param map
* @return
*/
public int updateBatch(Map<String, Object> map);
/**
* ๅ ้คๅๆก่ฎฐๅฝ
* @param id
* @return
*/
public int delete(ID id);
/**
* ๆน้ๅ ้ค
* @param ids
* @return
*/
public int deleteBatch(ID[] ids);
}
| 1,728 | 0.497253 | 0.497253 | 105 | 12.866667 | 12.375911 | 65 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.152381 | false | false | 13 |
7593894c4c7eb0bb5138f60c98d2f52bc6012b92 | 17,179,869,201,501 | d6e21947043cce2bfd7e1b3aeffcb83172bc474f | /workspace-sts4/chap11/src/chap11/IteratorDemo.java | 47def81d83a26f54dd44342295c9352235ba1276 | []
| no_license | lys0614/java_study | https://github.com/lys0614/java_study | 15e51b3b91dda40dc96a5500e0dc54c6938fe579 | 4aca517cbe6e5c2c5cb5201eb450eff03bde6461 | refs/heads/master | 2021-01-06T09:41:43.524000 | 2020-03-12T08:24:18 | 2020-03-12T08:24:18 | 241,283,870 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package chap11;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.*;
public class IteratorDemo {
public static void main (String[] args) {
List<String> list = new ArrayList<>();
list.add("๋ค๋์ฅ");
list.add("๊ฐ๊ตฌ๋ฆฌ");
list.add("๋๋น");
Iterator<String> iterator = list.iterator();
while(iterator.hasNext()){
System.out.print(iterator.next() + " ");
}
System.out.println();
Collections.sort(list);
while(iterator.hasNext()) {//์ด๋ฏธ ๋ฐ๋ณต์ ์ํํ ๋ฐ๋ณต์์ด๋ฏ๋ก ์ปฌ๋ ์
์ ์์๋ฅผ ์ํํ ์ ์๋ค.
//๋ฐ๋ผ์ ์๋ฌด๋ฐ ๋ด์ฉ๋ ์ถ๋ ฅํ์ง ์๋๋ค.(์ฝ์์ 2๋ฒ์งธ ์ค์ด ๊ณต๋ฐฑ์ธ ์ด์ )
System.out.print(iterator.next() + " ");
}
System.out.println();
iterator = list.iterator();
while(iterator.hasNext()){
System.out.print(iterator.next() + " ");
}
}
}
| UHC | Java | 930 | java | IteratorDemo.java | Java | [
{
"context": "ist<String> list = new ArrayList<>();\n\t\tlist.add(\"๋ค๋์ฅ\");\n\t\tlist.add(\"๊ฐ๊ตฌ๋ฆฌ\");\n\t\tlist.add(\"๋๋น\");\n\t\t\n\t\tIter",
"end": 272,
"score": 0.9997801184654236,
"start": 269,
"tag": "NAME",
"value": "๋ค๋์ฅ"
},
{
"context": "new ArrayList<>();\n\t\tlist.add(\"๋ค๋์ฅ\");\n\t\tlist.add(\"๊ฐ๊ตฌ๋ฆฌ\");\n\t\tlist.add(\"๋๋น\");\n\t\t\n\t\tIterator<String> iterat",
"end": 291,
"score": 0.9996750950813293,
"start": 288,
"tag": "NAME",
"value": "๊ฐ๊ตฌ๋ฆฌ"
},
{
"context": "\t\tlist.add(\"๋ค๋์ฅ\");\n\t\tlist.add(\"๊ฐ๊ตฌ๋ฆฌ\");\n\t\tlist.add(\"๋๋น\");\n\t\t\n\t\tIterator<String> iterator = list.iterator",
"end": 309,
"score": 0.999466061592102,
"start": 307,
"tag": "NAME",
"value": "๋๋น"
}
]
| null | []
| package chap11;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.*;
public class IteratorDemo {
public static void main (String[] args) {
List<String> list = new ArrayList<>();
list.add("๋ค๋์ฅ");
list.add("๊ฐ๊ตฌ๋ฆฌ");
list.add("๋๋น");
Iterator<String> iterator = list.iterator();
while(iterator.hasNext()){
System.out.print(iterator.next() + " ");
}
System.out.println();
Collections.sort(list);
while(iterator.hasNext()) {//์ด๋ฏธ ๋ฐ๋ณต์ ์ํํ ๋ฐ๋ณต์์ด๋ฏ๋ก ์ปฌ๋ ์
์ ์์๋ฅผ ์ํํ ์ ์๋ค.
//๋ฐ๋ผ์ ์๋ฌด๋ฐ ๋ด์ฉ๋ ์ถ๋ ฅํ์ง ์๋๋ค.(์ฝ์์ 2๋ฒ์งธ ์ค์ด ๊ณต๋ฐฑ์ธ ์ด์ )
System.out.print(iterator.next() + " ");
}
System.out.println();
iterator = list.iterator();
while(iterator.hasNext()){
System.out.print(iterator.next() + " ");
}
}
}
| 930 | 0.649254 | 0.645522 | 36 | 21.333334 | 16.975473 | 67 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.055556 | false | false | 13 |
28b0fe8a275e60c60393c9e710bb74d626b12d26 | 22,840,636,107,011 | 7e4f6dc14b775b6afa1d547468997df0317fd4eb | /src/QuestionTwo.java | 1d3153e09a215ec6b6447191e1e8d06b2568d76a | []
| no_license | umang4846/Aubergine-Practical | https://github.com/umang4846/Aubergine-Practical | 4566ce13bf5acd8a6f1a6303a55524839f51ce2b | 7ea445dd4eda8fcd668bbde8c321383d3ea68707 | refs/heads/master | 2020-07-17T19:09:28.706000 | 2019-09-04T17:24:18 | 2019-09-04T17:24:18 | 206,079,659 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import java.util.Scanner;
/**
* need to pass total no of rows and columns --> String [][] arr = new String[row][column];
* then, need to pass all the X and S in 2D Array (X = field , S = Sheep)
* Program will return Max no. of Sheep close to each others
*/
public class QuestionTwo {
// Static class variable
private static int maxCount = 0, count = 0, iLen = 0, jLen = 0;
private static int maxCount(String S[][], int i, int j)
{
if(i<0 || i>=iLen || j<0 || j>=jLen ){
return 0;
}
if("S".equals(S[i][j])){
S[i][j] = "O";
//Incrementing Counter
count++;
//Recursion
maxCount(S, i-1,j-1);
maxCount(S, i,j-1);
maxCount(S, i+1,j-1);
maxCount(S, i+1,j);
maxCount(S, i+1,j+1);
maxCount(S, i,j+1);
maxCount(S, i-1,j+1);
maxCount(S, i-1,j);
}
return 1;
}
public static void main(String[] args)
{
//Creating Scanner class object
Scanner s = new Scanner(System.in);
System.out.println("Enter total no. of rows");
int k = s.nextInt(); //Total Rows
System.out.println("Enter total no. of columns");
int l = s.nextInt(); // Total Columns
//Defining Array based on User Entered Rows & Columns
String arr[][] = new String[k][l];
//Iterating Loop to get value from the user by Row & Column Index
for(int i=0;i<k;i++){
for(int j=0;j<l;j++){
System.out.println("Enter ["+ i+"] ["+j+"] element");
arr[i][j] = s.next();
}
}
// {{"X", "X", "S","S", "X", "X"},
// {"X", "X", "S","S", "X", "S"},
// {"S", "X", "X","X", "X", "S"},
// {"X", "X", "X","X", "S", "S"},
// {"X", "X", "S","X", "S", "X"}
// };
iLen = arr.length;
jLen = arr[iLen-1].length;
for(int i=0;i<iLen;i++){
for(int j=0;j<jLen;j++){
maxCount(arr, i, j);
if(maxCount<count){
maxCount = count;
}
count=0;
}
}
System.out.println(maxCount);
}
}
| UTF-8 | Java | 2,325 | java | QuestionTwo.java | Java | []
| null | []
| import java.util.Scanner;
/**
* need to pass total no of rows and columns --> String [][] arr = new String[row][column];
* then, need to pass all the X and S in 2D Array (X = field , S = Sheep)
* Program will return Max no. of Sheep close to each others
*/
public class QuestionTwo {
// Static class variable
private static int maxCount = 0, count = 0, iLen = 0, jLen = 0;
private static int maxCount(String S[][], int i, int j)
{
if(i<0 || i>=iLen || j<0 || j>=jLen ){
return 0;
}
if("S".equals(S[i][j])){
S[i][j] = "O";
//Incrementing Counter
count++;
//Recursion
maxCount(S, i-1,j-1);
maxCount(S, i,j-1);
maxCount(S, i+1,j-1);
maxCount(S, i+1,j);
maxCount(S, i+1,j+1);
maxCount(S, i,j+1);
maxCount(S, i-1,j+1);
maxCount(S, i-1,j);
}
return 1;
}
public static void main(String[] args)
{
//Creating Scanner class object
Scanner s = new Scanner(System.in);
System.out.println("Enter total no. of rows");
int k = s.nextInt(); //Total Rows
System.out.println("Enter total no. of columns");
int l = s.nextInt(); // Total Columns
//Defining Array based on User Entered Rows & Columns
String arr[][] = new String[k][l];
//Iterating Loop to get value from the user by Row & Column Index
for(int i=0;i<k;i++){
for(int j=0;j<l;j++){
System.out.println("Enter ["+ i+"] ["+j+"] element");
arr[i][j] = s.next();
}
}
// {{"X", "X", "S","S", "X", "X"},
// {"X", "X", "S","S", "X", "S"},
// {"S", "X", "X","X", "X", "S"},
// {"X", "X", "X","X", "S", "S"},
// {"X", "X", "S","X", "S", "X"}
// };
iLen = arr.length;
jLen = arr[iLen-1].length;
for(int i=0;i<iLen;i++){
for(int j=0;j<jLen;j++){
maxCount(arr, i, j);
if(maxCount<count){
maxCount = count;
}
count=0;
}
}
System.out.println(maxCount);
}
}
| 2,325 | 0.432258 | 0.420645 | 77 | 29.194805 | 21.502062 | 92 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.272727 | false | false | 13 |
5d05b8555206015927875e6af82be58a91eb115c | 10,642,928,974,818 | 74458e99e0ece6e49ade7d9ef101d14f6bdc137d | /Competition.java | 55df10b94ee1dd46fe39cbb7ad7b2d6b95e44662 | []
| no_license | NorthFred/Java-Skijump-Competition-Collections-Lists | https://github.com/NorthFred/Java-Skijump-Competition-Collections-Lists | dd57d3afd089bd104d02ce3dc0f87ffe462e3c80 | f1b9943505952c5d5a88eacdea1f38d654d61e9e | refs/heads/master | 2021-01-20T03:47:25.368000 | 2017-04-27T10:43:56 | 2017-04-27T10:43:56 | 89,586,941 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
/*
* This class "Competition" will be used as the interfacing class
* for the SkiJumping program.
*/
package SkiJumping;
import java.util.Scanner;
import java.util.List;
import java.util.ArrayList;
import java.util.Collections;
public class Competition {
// Attributes
Scanner reader;
List<Jumper> competitors;
String competitionName;
// Constructor
public Competition(String competitionName) {
// User input initialization
this.competitionName = competitionName;
this.reader = new Scanner(System.in);
this.competitors = new ArrayList<Jumper>();
}
// Methods
public void checkCompetitors() {
// Since the Jumper object implements the Comparable interface,
// the List with Jumper objects (which also belongs to Comparable interface
// can now be easily sorted. The method "compareTo" in Jumper class defines the criteria for sorting.
Collections.sort(competitors);
// Sort the competitor list, so the jumper with the lowesst amount of points will start in each round
int pos = 1;
for (Jumper jumper : this.competitors) {
System.out.println(" " + pos + ". " + jumper.getName() + " (" + jumper.getPoints() + " points)");
pos++;
}
}
public void competeInRound() {
// Defines what happens in one competion round.
for (Jumper jumper : this.competitors) {
System.out.println(jumper.getName());
// Make a jump
int jumpscore = Action.jump();
jumper.addLength(jumpscore);
System.out.println(" length: " + jumpscore);
// Get a jury score
List<Integer> juryscore = Action.juryVotes();
// Show the jury votes
System.out.print(" judge votes: [ ");
for (int s : juryscore) {
System.out.print(s + " ");
}
System.out.println("]");
// From the jury score, only the middle 3 values are accepted
// On a sorted list, exclude the values in position 0 and 5.
Collections.sort(juryscore);
int votescore = juryscore.get(1) + juryscore.get(2) + juryscore.get(3);
// Calculate the points and add to the jumper
int roundscore = jumpscore + votescore;
jumper.addPoints(roundscore);
}
}
public void endTournament() {
// Sort the list of Jumper objects (sorting is possible because of the override method CompareTo)
Collections.sort(this.competitors, Collections.reverseOrder());
int pos = 1;
for (Jumper jumper : this.competitors) {
System.out.println(pos + "\t\t" + jumper.getName() + " (" + jumper.getPoints() + ")");
System.out.println("" + "\t\t" + jumper.getResults());
pos++;
}
}
// Main program
public void run() {
System.out.println(this.competitionName + "\n");
System.out.println("Enter the name of the participants one by one.");
System.out.println("An empty input will start the competition!");
String name = "";
do {
System.out.print(" Participant name: ");
name = this.reader.nextLine();
if (name.length() > 0) {
// Create a player object out of the competitor
Jumper competitor = new Jumper(name);
// Add the competitor to the set of competitor objects.
this.competitors.add(competitor);
}
}
while (name.length() > 0);
System.out.println("\nThe competition begins!\n");
int round = 1;
String command = "";
do {
System.out.println("Round " + round + "\n");
System.out.println("Jumping order:");
// This method gives the list of competitors and sorts them
// The jumper with lowest points will start the round.
checkCompetitors();
System.out.println("");
competeInRound();
System.out.println("");
round += 1;
System.out.println("Write 'jump' to jump; everything else will stop the competition.");
command = this.reader.nextLine();
System.out.println("");
}
while (command.equals("jump"));
System.out.println("<END OF TOURNAMENT> \n");
System.out.println("TOURNAMENT RESULTS");
endTournament();
}
}
| UTF-8 | Java | 5,040 | java | Competition.java | Java | []
| null | []
|
/*
* This class "Competition" will be used as the interfacing class
* for the SkiJumping program.
*/
package SkiJumping;
import java.util.Scanner;
import java.util.List;
import java.util.ArrayList;
import java.util.Collections;
public class Competition {
// Attributes
Scanner reader;
List<Jumper> competitors;
String competitionName;
// Constructor
public Competition(String competitionName) {
// User input initialization
this.competitionName = competitionName;
this.reader = new Scanner(System.in);
this.competitors = new ArrayList<Jumper>();
}
// Methods
public void checkCompetitors() {
// Since the Jumper object implements the Comparable interface,
// the List with Jumper objects (which also belongs to Comparable interface
// can now be easily sorted. The method "compareTo" in Jumper class defines the criteria for sorting.
Collections.sort(competitors);
// Sort the competitor list, so the jumper with the lowesst amount of points will start in each round
int pos = 1;
for (Jumper jumper : this.competitors) {
System.out.println(" " + pos + ". " + jumper.getName() + " (" + jumper.getPoints() + " points)");
pos++;
}
}
public void competeInRound() {
// Defines what happens in one competion round.
for (Jumper jumper : this.competitors) {
System.out.println(jumper.getName());
// Make a jump
int jumpscore = Action.jump();
jumper.addLength(jumpscore);
System.out.println(" length: " + jumpscore);
// Get a jury score
List<Integer> juryscore = Action.juryVotes();
// Show the jury votes
System.out.print(" judge votes: [ ");
for (int s : juryscore) {
System.out.print(s + " ");
}
System.out.println("]");
// From the jury score, only the middle 3 values are accepted
// On a sorted list, exclude the values in position 0 and 5.
Collections.sort(juryscore);
int votescore = juryscore.get(1) + juryscore.get(2) + juryscore.get(3);
// Calculate the points and add to the jumper
int roundscore = jumpscore + votescore;
jumper.addPoints(roundscore);
}
}
public void endTournament() {
// Sort the list of Jumper objects (sorting is possible because of the override method CompareTo)
Collections.sort(this.competitors, Collections.reverseOrder());
int pos = 1;
for (Jumper jumper : this.competitors) {
System.out.println(pos + "\t\t" + jumper.getName() + " (" + jumper.getPoints() + ")");
System.out.println("" + "\t\t" + jumper.getResults());
pos++;
}
}
// Main program
public void run() {
System.out.println(this.competitionName + "\n");
System.out.println("Enter the name of the participants one by one.");
System.out.println("An empty input will start the competition!");
String name = "";
do {
System.out.print(" Participant name: ");
name = this.reader.nextLine();
if (name.length() > 0) {
// Create a player object out of the competitor
Jumper competitor = new Jumper(name);
// Add the competitor to the set of competitor objects.
this.competitors.add(competitor);
}
}
while (name.length() > 0);
System.out.println("\nThe competition begins!\n");
int round = 1;
String command = "";
do {
System.out.println("Round " + round + "\n");
System.out.println("Jumping order:");
// This method gives the list of competitors and sorts them
// The jumper with lowest points will start the round.
checkCompetitors();
System.out.println("");
competeInRound();
System.out.println("");
round += 1;
System.out.println("Write 'jump' to jump; everything else will stop the competition.");
command = this.reader.nextLine();
System.out.println("");
}
while (command.equals("jump"));
System.out.println("<END OF TOURNAMENT> \n");
System.out.println("TOURNAMENT RESULTS");
endTournament();
}
}
| 5,040 | 0.517063 | 0.514683 | 147 | 32.27211 | 27.03451 | 124 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.435374 | false | false | 13 |
410da15eb42e3cdf078ff0a7cbcecf9f21870c23 | 15,547,781,648,936 | b31ae69273dca4b371c084c06e3fcbd661a5d064 | /persistence/src/main/java/pt/uc/dei/aor/project/persistence/entity/ScriptEntity.java | 7588624754abd2b2d16e28520159f6af36769ebd | []
| no_license | kwakiutlCS/jobapplication | https://github.com/kwakiutlCS/jobapplication | d7b9fc557427fee889c32546856df00826d0af2c | 53a0b2c9976d89abd8d0eaefaea600840f4a7dc5 | refs/heads/master | 2020-05-18T16:43:57.655000 | 2015-10-03T21:37:00 | 2015-10-03T21:37:00 | 40,110,712 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package pt.uc.dei.aor.project.persistence.entity;
import java.io.Serializable;
import java.util.SortedSet;
import java.util.TreeSet;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.OrderBy;
import javax.persistence.Table;
@Entity
@Table(name="script")
@NamedQueries({
@NamedQuery(name = "Script.findAllScripts",
query="from ScriptEntity u where u.entries is not empty and u.deleted = false"),
})
public class ScriptEntity implements Serializable {
private static final long serialVersionUID = -5877196134761879608L;
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private long id;
@Column(nullable=false, unique=true)
private String title;
@Column
private boolean deleted = false;
@OrderBy("position ASC")
@OneToMany(cascade={CascadeType.ALL}, fetch=FetchType.EAGER)
private SortedSet<ScriptEntryEntity> entries;
public ScriptEntity() {
this.entries = new TreeSet<>();
}
public ScriptEntity(String title) {
this.entries = new TreeSet<>();
this.title = title;
}
public long getId() {
return id;
}
public SortedSet<ScriptEntryEntity> getEntries() {
return entries;
}
public void setEntries(SortedSet<ScriptEntryEntity> entries) {
this.entries = entries;
}
public int getNextPosition() {
if (entries.size() == 0) return 0;
return entries.last().getPosition()+1;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((title == null) ? 0 : title.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
ScriptEntity other = (ScriptEntity) obj;
if (title == null) {
if (other.title != null)
return false;
} else if (!title.equals(other.title))
return false;
return true;
}
@Override
public String toString() {
return "ScriptEntity [title=" + title + "]";
}
public void setDeleted(boolean b) {
deleted = b;
title += "_inactive";
}
}
| UTF-8 | Java | 2,492 | java | ScriptEntity.java | Java | []
| null | []
| package pt.uc.dei.aor.project.persistence.entity;
import java.io.Serializable;
import java.util.SortedSet;
import java.util.TreeSet;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.OrderBy;
import javax.persistence.Table;
@Entity
@Table(name="script")
@NamedQueries({
@NamedQuery(name = "Script.findAllScripts",
query="from ScriptEntity u where u.entries is not empty and u.deleted = false"),
})
public class ScriptEntity implements Serializable {
private static final long serialVersionUID = -5877196134761879608L;
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private long id;
@Column(nullable=false, unique=true)
private String title;
@Column
private boolean deleted = false;
@OrderBy("position ASC")
@OneToMany(cascade={CascadeType.ALL}, fetch=FetchType.EAGER)
private SortedSet<ScriptEntryEntity> entries;
public ScriptEntity() {
this.entries = new TreeSet<>();
}
public ScriptEntity(String title) {
this.entries = new TreeSet<>();
this.title = title;
}
public long getId() {
return id;
}
public SortedSet<ScriptEntryEntity> getEntries() {
return entries;
}
public void setEntries(SortedSet<ScriptEntryEntity> entries) {
this.entries = entries;
}
public int getNextPosition() {
if (entries.size() == 0) return 0;
return entries.last().getPosition()+1;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((title == null) ? 0 : title.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
ScriptEntity other = (ScriptEntity) obj;
if (title == null) {
if (other.title != null)
return false;
} else if (!title.equals(other.title))
return false;
return true;
}
@Override
public String toString() {
return "ScriptEntity [title=" + title + "]";
}
public void setDeleted(boolean b) {
deleted = b;
title += "_inactive";
}
}
| 2,492 | 0.716693 | 0.70626 | 115 | 20.669565 | 18.532566 | 83 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.434783 | false | false | 13 |
123d4e8de52d4fc5bc35c5597f6ed1900330cb6f | 17,025,250,413,792 | d60aa63a88af5e0a7745f272d71c4873b40899e2 | /ballvideo-java/ballvideo/src/main/java/com/miguan/ballvideo/service/impl/VideoCacheServiceImpl.java | 994fcb836ccc4c0e44089c142e9cad993373dcd4 | []
| no_license | cckmit/project-6 | https://github.com/cckmit/project-6 | c3b20e9f25c28aafd8a0bcddebd37e71dccf912f | 79fe6cbe3d4c4799518c91b92b51e458892276c8 | refs/heads/master | 2023-04-03T02:28:06.358000 | 2021-03-26T09:04:32 | 2021-03-26T09:04:49 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.miguan.ballvideo.service.impl;
import com.alibaba.fastjson.JSONObject;
import com.miguan.ballvideo.common.constants.Constant;
import com.miguan.ballvideo.common.constants.VideoContant;
import com.miguan.ballvideo.common.util.adv.AdvUtils;
import com.miguan.ballvideo.common.util.video.VideoUtils;
import com.miguan.ballvideo.mapper.*;
import com.miguan.ballvideo.redis.util.RedisKeyConstant;
import com.miguan.ballvideo.service.*;
import com.miguan.ballvideo.vo.AdvertVo;
import com.miguan.ballvideo.vo.FirstVideos;
import com.miguan.ballvideo.vo.SmallVideosVo;
import com.miguan.ballvideo.vo.VideosCatVo;
import com.miguan.ballvideo.vo.video.HotListVo;
import com.miguan.ballvideo.vo.video.Videos161Vo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;
/**
* @author xujinbang
* @date 2019/11/9.
*/
@Slf4j
@Service
public class VideoCacheServiceImpl implements VideoCacheService {
@Resource(name="redisDB8Service")
private RedisDB8Service redisDB8Service;
@Resource
private FirstVideosMapper firstVideosMapper;
@Resource
private SmallVideosMapper smallVideosMapper;
@Resource
private AdvertMapper advertMapper;
@Resource
private VideosCatMapper videosCatMapper;
@Resource
private AdvertOldService advertOldService;
@Resource
private MarketAuditService marketAuditService;
@Resource
private VideosCatService videosCatService;
@Resource
private ClUserVideosMapper clUserVideosMapper;
@Resource
private ClUserService clUserService;
@Override
public Map<Long, VideosCatVo> getVideosCatMap(String type) {
List<VideosCatVo> videosCatVos = videosCatMapper.firstVideosCatList(type);
if (CollectionUtils.isEmpty(videosCatVos)){
return new HashMap<>();
}
return videosCatVos.stream().collect(Collectors.toMap(VideosCatVo::getId,v -> v));
}
@Override
public void fillParams(List<Videos161Vo> firstVideos) {
//VideoUtils.setLoveAndWatchNum(firstVideos);
//่ตๅผๅ็ฑปๅ็งฐ๏ผ็ฅ็ญๅ็น้่ฆ
VideoUtils.setCatName(firstVideos, null, getVideosCatMap(VideoContant.FIRST_VIDEO_CODE));
}
@Override
public void getVideosCollection(List<Videos161Vo> firstVideos,String userId) {
if (CollectionUtils.isEmpty(firstVideos)){
return;
}
//่ง้ขไฝ่
ๅคดๅๅๅๅญๅ็จๆท่กจ๏ผ่ๆ็จๆทๆ่
็ๆฏ็จๆท๏ผ
clUserService.packagingUserAndVideos(firstVideos);
//ๆ นๆฎ็จๆท่ง้ขๅ
ณ่่กจๅคๆญๆฏๅฆๆถ่
if (userId != null && !userId.equals("0")) {
List<Long> videoIds = firstVideos.stream().map(e -> e.getId()).collect(Collectors.toList());
List<Long> list = clUserVideosMapper.queryCollection(userId, videoIds);
for (int i = 0; i < list.size(); i++) {
Long aLong = list.get(i);
for (Videos161Vo esVideo : firstVideos) {
Long videoId = esVideo.getId();
if (videoId.equals(aLong)){
esVideo.setCollection("1");
break;
}
}
}
}
}
@Override
public void getVideosCollection2(List<HotListVo> hotList, String userId) {
if (CollectionUtils.isEmpty(hotList)){
return;
}
//่ง้ขไฝ่
ๅคดๅๅๅๅญๅ็จๆท่กจ๏ผ่ๆ็จๆทๆ่
็ๆฏ็จๆท๏ผ
clUserService.packagingUserAndVideos2(hotList);
//ๆ นๆฎ็จๆท่ง้ขๅ
ณ่่กจๅคๆญๆฏๅฆๆถ่
if (userId != null && !userId.equals("0")) {
List<Long> videoIds = hotList.stream().map(e -> e.getId()).collect(Collectors.toList());
List<Long> list = clUserVideosMapper.queryCollection(userId, videoIds);
for (int i = 0; i < list.size(); i++) {
Long aLong = list.get(i);
for (HotListVo esVideo : hotList) {
Long videoId = esVideo.getId();
if (videoId.equals(aLong)){
esVideo.setCollection("1");
break;
}
}
}
}
}
/**
* ่่ๅฐๅคง้จๅไบบๆฒก็ปๅฝ๏ผ้ๅฏนๆฒก็ปๅฝๆ
ๅตๅ4ๅฐๆถ็ผๅญ
* @param params
* @return
*/
@Override
public List<Videos161Vo> getFirstVideos161(Map<String, Object> params,int count) {
final List<Videos161Vo> firstVideosList = new ArrayList<>();
Object excludeId = params.get("excludeId");
Object videoType = params.get("videoType");
Object catId = params.get("catId");
Object otherCatIds = params.get("otherCatIds");
Object id = params.get("id");
Object state = params.get("state");
Object gatherIds = params.get("gatherIds");
Object appPackage = params.get("appPackage");
if(catId==null){
//catIdไธบ็ฉบ๏ผ้ๆบ่ทๅไธไธช add shixh0430
List<String> catIds = videosCatService.getCatIdsByStateAndType(Constant.open,VideoContant.FIRST_VIDEO_CODE);
Collections.shuffle(catIds);
catId = catIds.get(0);
params.put("catId",catId);
}
final StringBuilder stringBuilder = new StringBuilder(RedisKeyConstant.NEWFIRSTVIDEO161_KEY);
stringBuilder.append(excludeId != null ? excludeId.toString() : "@");
stringBuilder.append(videoType != null ? videoType.toString() : "@");
stringBuilder.append(catId != null ? catId.toString() : "@");
stringBuilder.append(otherCatIds != null ? otherCatIds.toString() : "@");
stringBuilder.append(id != null ? id.toString() : "@");
stringBuilder.append(state != null ? state.toString() : "@");
stringBuilder.append(gatherIds != null ? gatherIds.toString() : "@");
stringBuilder.append(appPackage != null ? appPackage.toString() : "@");
String key = stringBuilder.toString();
if(!redisDB8Service.exits(key)) {
List<Videos161Vo> list = firstVideosMapper.findFirstVideosList161(params);
if(list.isEmpty()) {
return firstVideosList;
}
String[] value = list.stream().collect(Collectors.toMap(Videos161Vo::getId,e -> JSONObject.toJSONString(e))).values().toArray(new String[list.size()]);
redisDB8Service.sadd(key,RedisKeyConstant.NEWFIRSTVIDEO161_SECONDS,value);
}
redisDB8Service.randomValue(key,count).forEach(e -> firstVideosList.add(JSONObject.parseObject(e,Videos161Vo.class)));
return firstVideosList;
}
/**
* ่่ๅฐๅคง้จๅไบบๆฒก็ปๅฝ๏ผ้ๅฏนๆฒก็ปๅฝๆ
ๅตๅ4ๅฐๆถ็ผๅญ
* @param params
* @return
*/
@Override
public List<FirstVideos> getFirstVideos(Map<String, Object> params,int count) {
List<FirstVideos> firstVideosList = new ArrayList<>();
Object excludeId = params.get("excludeId");
Object videoType = params.get("videoType");
String catId = MapUtils.getString(params, "catId");
Object otherCatIds = params.get("otherCatIds");
Object id = params.get("id");
Object state = params.get("state");
Object appPackage = params.get("appPackage");
if(StringUtils.isEmpty(catId)){
//catIdไธบ็ฉบ๏ผ้ๆบ่ทๅไธไธช add shixh0430
List<String> catIds = videosCatService.getCatIdsByStateAndType(Constant.open,VideoContant.FIRST_VIDEO_CODE);
if(otherCatIds!=null && StringUtils.isNotEmpty(otherCatIds+"")){
for(Long id_cat:(List<Long>)otherCatIds){
catIds.remove(String.valueOf(id_cat));
}
}
if(CollectionUtils.isEmpty(catIds)){
catId = "251";
}else{
Collections.shuffle(catIds);
catId = catIds.get(0);
}
params.put("catId",catId);
}
final StringBuilder stringBuilder = new StringBuilder(RedisKeyConstant.NEWFIRSTVIDEO_KEY);
stringBuilder.append(excludeId != null ? excludeId.toString() : "@");
stringBuilder.append(videoType != null ? videoType.toString() : "@");
stringBuilder.append(StringUtils.isNotEmpty(catId) ? catId : "@");
stringBuilder.append(otherCatIds != null ? otherCatIds.toString() : "@");
stringBuilder.append(id != null ? id.toString() : "@");
stringBuilder.append(state != null ? state.toString() : "@");
stringBuilder.append(appPackage != null ? appPackage.toString() : "@");
String key = stringBuilder.toString();
if(!redisDB8Service.exits(key)) {
List<FirstVideos> list = firstVideosMapper.findFirstVideosList(params);
if(list.isEmpty()) {
return firstVideosList;
}
String[] value = list.stream().collect(Collectors.toMap(FirstVideos::getId,e -> JSONObject.toJSONString(e))).values().toArray(new String[list.size()]);
redisDB8Service.sadd(key,RedisKeyConstant.NEWFIRSTVIDEO_SECONDS,value);
}
redisDB8Service.randomValue(key,count).forEach(e -> firstVideosList.add(JSONObject.parseObject(e,FirstVideos.class)));
return firstVideosList;
}
/**
* ็ผๅญๅนฟๅไฟกๆฏ๏ผ2ๅ้ๅ
็ดๆฅไป็ผๅญ่ทๅ
* @param param
* @return
*/
@Override
public List<AdvertVo> getAdvertList(Map<String, Object> param,int count) {
//็ๆฌ2.2.0ไปฅไธ๏ผๅธๅบๅฎกๆ ธๅผๅ
ณๅผๅฏ๏ผๅฑ่ฝๆๆๅนฟๅ
boolean isShield = marketAuditService.isShield(param);
if (isShield) {
return null;
}
List<AdvertVo> advers = advertMapper.queryAdertList(param);
advers = advertOldService.getAdvertsByChannel(advers, param);
return AdvUtils.computer(advers,count);
}
/**
* ่ทๅๅบ็กๅนฟๅไฟกๆฏ
*
* @param param
* @return
*/
@Override
public List<AdvertVo> getBaseAdvertList(Map<String, Object> param) {
//็ๆฌ2.2.0ไปฅไธ๏ผๅธๅบๅฎกๆ ธๅผๅ
ณๅผๅฏ๏ผๅฑ่ฝๆๆๅนฟๅ
boolean isShield = marketAuditService.isShield(param);
if (isShield) {
return null;
}
List<AdvertVo> advers = advertMapper.queryAdertList(param);
advers = advertOldService.getAdvertsByChannel(advers, param);
return advers;
}
/**
* ่่ๅฐๅคง้จๅไบบๆฒก็ปๅฝ๏ผ้ๅฏนๆฒก็ปๅฝๆ
ๅตๅ1ๅฐๆถ็ผๅญ
* @param params
* @return
*/
@Override
public List<SmallVideosVo> getSmallVideos(Map<String, Object> params,int count) {
return smallVideosMapper.findSmallVideosList(params);
}
}
| UTF-8 | Java | 10,999 | java | VideoCacheServiceImpl.java | Java | [
{
"context": "mport java.util.stream.Collectors;\n\n/**\n * @author xujinbang\n * @date 2019/11/9.\n */\n@Slf4j\n@Service\npublic cl",
"end": 1062,
"score": 0.9995602369308472,
"start": 1053,
"tag": "USERNAME",
"value": "xujinbang"
}
]
| null | []
| package com.miguan.ballvideo.service.impl;
import com.alibaba.fastjson.JSONObject;
import com.miguan.ballvideo.common.constants.Constant;
import com.miguan.ballvideo.common.constants.VideoContant;
import com.miguan.ballvideo.common.util.adv.AdvUtils;
import com.miguan.ballvideo.common.util.video.VideoUtils;
import com.miguan.ballvideo.mapper.*;
import com.miguan.ballvideo.redis.util.RedisKeyConstant;
import com.miguan.ballvideo.service.*;
import com.miguan.ballvideo.vo.AdvertVo;
import com.miguan.ballvideo.vo.FirstVideos;
import com.miguan.ballvideo.vo.SmallVideosVo;
import com.miguan.ballvideo.vo.VideosCatVo;
import com.miguan.ballvideo.vo.video.HotListVo;
import com.miguan.ballvideo.vo.video.Videos161Vo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;
/**
* @author xujinbang
* @date 2019/11/9.
*/
@Slf4j
@Service
public class VideoCacheServiceImpl implements VideoCacheService {
@Resource(name="redisDB8Service")
private RedisDB8Service redisDB8Service;
@Resource
private FirstVideosMapper firstVideosMapper;
@Resource
private SmallVideosMapper smallVideosMapper;
@Resource
private AdvertMapper advertMapper;
@Resource
private VideosCatMapper videosCatMapper;
@Resource
private AdvertOldService advertOldService;
@Resource
private MarketAuditService marketAuditService;
@Resource
private VideosCatService videosCatService;
@Resource
private ClUserVideosMapper clUserVideosMapper;
@Resource
private ClUserService clUserService;
@Override
public Map<Long, VideosCatVo> getVideosCatMap(String type) {
List<VideosCatVo> videosCatVos = videosCatMapper.firstVideosCatList(type);
if (CollectionUtils.isEmpty(videosCatVos)){
return new HashMap<>();
}
return videosCatVos.stream().collect(Collectors.toMap(VideosCatVo::getId,v -> v));
}
@Override
public void fillParams(List<Videos161Vo> firstVideos) {
//VideoUtils.setLoveAndWatchNum(firstVideos);
//่ตๅผๅ็ฑปๅ็งฐ๏ผ็ฅ็ญๅ็น้่ฆ
VideoUtils.setCatName(firstVideos, null, getVideosCatMap(VideoContant.FIRST_VIDEO_CODE));
}
@Override
public void getVideosCollection(List<Videos161Vo> firstVideos,String userId) {
if (CollectionUtils.isEmpty(firstVideos)){
return;
}
//่ง้ขไฝ่
ๅคดๅๅๅๅญๅ็จๆท่กจ๏ผ่ๆ็จๆทๆ่
็ๆฏ็จๆท๏ผ
clUserService.packagingUserAndVideos(firstVideos);
//ๆ นๆฎ็จๆท่ง้ขๅ
ณ่่กจๅคๆญๆฏๅฆๆถ่
if (userId != null && !userId.equals("0")) {
List<Long> videoIds = firstVideos.stream().map(e -> e.getId()).collect(Collectors.toList());
List<Long> list = clUserVideosMapper.queryCollection(userId, videoIds);
for (int i = 0; i < list.size(); i++) {
Long aLong = list.get(i);
for (Videos161Vo esVideo : firstVideos) {
Long videoId = esVideo.getId();
if (videoId.equals(aLong)){
esVideo.setCollection("1");
break;
}
}
}
}
}
@Override
public void getVideosCollection2(List<HotListVo> hotList, String userId) {
if (CollectionUtils.isEmpty(hotList)){
return;
}
//่ง้ขไฝ่
ๅคดๅๅๅๅญๅ็จๆท่กจ๏ผ่ๆ็จๆทๆ่
็ๆฏ็จๆท๏ผ
clUserService.packagingUserAndVideos2(hotList);
//ๆ นๆฎ็จๆท่ง้ขๅ
ณ่่กจๅคๆญๆฏๅฆๆถ่
if (userId != null && !userId.equals("0")) {
List<Long> videoIds = hotList.stream().map(e -> e.getId()).collect(Collectors.toList());
List<Long> list = clUserVideosMapper.queryCollection(userId, videoIds);
for (int i = 0; i < list.size(); i++) {
Long aLong = list.get(i);
for (HotListVo esVideo : hotList) {
Long videoId = esVideo.getId();
if (videoId.equals(aLong)){
esVideo.setCollection("1");
break;
}
}
}
}
}
/**
* ่่ๅฐๅคง้จๅไบบๆฒก็ปๅฝ๏ผ้ๅฏนๆฒก็ปๅฝๆ
ๅตๅ4ๅฐๆถ็ผๅญ
* @param params
* @return
*/
@Override
public List<Videos161Vo> getFirstVideos161(Map<String, Object> params,int count) {
final List<Videos161Vo> firstVideosList = new ArrayList<>();
Object excludeId = params.get("excludeId");
Object videoType = params.get("videoType");
Object catId = params.get("catId");
Object otherCatIds = params.get("otherCatIds");
Object id = params.get("id");
Object state = params.get("state");
Object gatherIds = params.get("gatherIds");
Object appPackage = params.get("appPackage");
if(catId==null){
//catIdไธบ็ฉบ๏ผ้ๆบ่ทๅไธไธช add shixh0430
List<String> catIds = videosCatService.getCatIdsByStateAndType(Constant.open,VideoContant.FIRST_VIDEO_CODE);
Collections.shuffle(catIds);
catId = catIds.get(0);
params.put("catId",catId);
}
final StringBuilder stringBuilder = new StringBuilder(RedisKeyConstant.NEWFIRSTVIDEO161_KEY);
stringBuilder.append(excludeId != null ? excludeId.toString() : "@");
stringBuilder.append(videoType != null ? videoType.toString() : "@");
stringBuilder.append(catId != null ? catId.toString() : "@");
stringBuilder.append(otherCatIds != null ? otherCatIds.toString() : "@");
stringBuilder.append(id != null ? id.toString() : "@");
stringBuilder.append(state != null ? state.toString() : "@");
stringBuilder.append(gatherIds != null ? gatherIds.toString() : "@");
stringBuilder.append(appPackage != null ? appPackage.toString() : "@");
String key = stringBuilder.toString();
if(!redisDB8Service.exits(key)) {
List<Videos161Vo> list = firstVideosMapper.findFirstVideosList161(params);
if(list.isEmpty()) {
return firstVideosList;
}
String[] value = list.stream().collect(Collectors.toMap(Videos161Vo::getId,e -> JSONObject.toJSONString(e))).values().toArray(new String[list.size()]);
redisDB8Service.sadd(key,RedisKeyConstant.NEWFIRSTVIDEO161_SECONDS,value);
}
redisDB8Service.randomValue(key,count).forEach(e -> firstVideosList.add(JSONObject.parseObject(e,Videos161Vo.class)));
return firstVideosList;
}
/**
* ่่ๅฐๅคง้จๅไบบๆฒก็ปๅฝ๏ผ้ๅฏนๆฒก็ปๅฝๆ
ๅตๅ4ๅฐๆถ็ผๅญ
* @param params
* @return
*/
@Override
public List<FirstVideos> getFirstVideos(Map<String, Object> params,int count) {
List<FirstVideos> firstVideosList = new ArrayList<>();
Object excludeId = params.get("excludeId");
Object videoType = params.get("videoType");
String catId = MapUtils.getString(params, "catId");
Object otherCatIds = params.get("otherCatIds");
Object id = params.get("id");
Object state = params.get("state");
Object appPackage = params.get("appPackage");
if(StringUtils.isEmpty(catId)){
//catIdไธบ็ฉบ๏ผ้ๆบ่ทๅไธไธช add shixh0430
List<String> catIds = videosCatService.getCatIdsByStateAndType(Constant.open,VideoContant.FIRST_VIDEO_CODE);
if(otherCatIds!=null && StringUtils.isNotEmpty(otherCatIds+"")){
for(Long id_cat:(List<Long>)otherCatIds){
catIds.remove(String.valueOf(id_cat));
}
}
if(CollectionUtils.isEmpty(catIds)){
catId = "251";
}else{
Collections.shuffle(catIds);
catId = catIds.get(0);
}
params.put("catId",catId);
}
final StringBuilder stringBuilder = new StringBuilder(RedisKeyConstant.NEWFIRSTVIDEO_KEY);
stringBuilder.append(excludeId != null ? excludeId.toString() : "@");
stringBuilder.append(videoType != null ? videoType.toString() : "@");
stringBuilder.append(StringUtils.isNotEmpty(catId) ? catId : "@");
stringBuilder.append(otherCatIds != null ? otherCatIds.toString() : "@");
stringBuilder.append(id != null ? id.toString() : "@");
stringBuilder.append(state != null ? state.toString() : "@");
stringBuilder.append(appPackage != null ? appPackage.toString() : "@");
String key = stringBuilder.toString();
if(!redisDB8Service.exits(key)) {
List<FirstVideos> list = firstVideosMapper.findFirstVideosList(params);
if(list.isEmpty()) {
return firstVideosList;
}
String[] value = list.stream().collect(Collectors.toMap(FirstVideos::getId,e -> JSONObject.toJSONString(e))).values().toArray(new String[list.size()]);
redisDB8Service.sadd(key,RedisKeyConstant.NEWFIRSTVIDEO_SECONDS,value);
}
redisDB8Service.randomValue(key,count).forEach(e -> firstVideosList.add(JSONObject.parseObject(e,FirstVideos.class)));
return firstVideosList;
}
/**
* ็ผๅญๅนฟๅไฟกๆฏ๏ผ2ๅ้ๅ
็ดๆฅไป็ผๅญ่ทๅ
* @param param
* @return
*/
@Override
public List<AdvertVo> getAdvertList(Map<String, Object> param,int count) {
//็ๆฌ2.2.0ไปฅไธ๏ผๅธๅบๅฎกๆ ธๅผๅ
ณๅผๅฏ๏ผๅฑ่ฝๆๆๅนฟๅ
boolean isShield = marketAuditService.isShield(param);
if (isShield) {
return null;
}
List<AdvertVo> advers = advertMapper.queryAdertList(param);
advers = advertOldService.getAdvertsByChannel(advers, param);
return AdvUtils.computer(advers,count);
}
/**
* ่ทๅๅบ็กๅนฟๅไฟกๆฏ
*
* @param param
* @return
*/
@Override
public List<AdvertVo> getBaseAdvertList(Map<String, Object> param) {
//็ๆฌ2.2.0ไปฅไธ๏ผๅธๅบๅฎกๆ ธๅผๅ
ณๅผๅฏ๏ผๅฑ่ฝๆๆๅนฟๅ
boolean isShield = marketAuditService.isShield(param);
if (isShield) {
return null;
}
List<AdvertVo> advers = advertMapper.queryAdertList(param);
advers = advertOldService.getAdvertsByChannel(advers, param);
return advers;
}
/**
* ่่ๅฐๅคง้จๅไบบๆฒก็ปๅฝ๏ผ้ๅฏนๆฒก็ปๅฝๆ
ๅตๅ1ๅฐๆถ็ผๅญ
* @param params
* @return
*/
@Override
public List<SmallVideosVo> getSmallVideos(Map<String, Object> params,int count) {
return smallVideosMapper.findSmallVideosList(params);
}
}
| 10,999 | 0.633552 | 0.624988 | 278 | 36.794964 | 30.281967 | 163 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.582734 | false | false | 13 |
47918031abba460e5f3714c4a026a3f2e0146841 | 26,259,430,078,380 | fa32b68d8e90a3e5ad348d7c97d2f2373a4a9730 | /Javaplace/SpringBoot/boot-ch5-web-01/src/main/java/com/nguyenxb/boot/config/WebConfigTest1.java | a9c48793357a3120af309e545ad9c49a22f7812e | []
| no_license | nguyenxb/learn-java | https://github.com/nguyenxb/learn-java | 6d89e364941f0deb84a835e7e722aa66ccb72f17 | a9b1bc74f911947d1f2ee03910a687cd3bd6b692 | refs/heads/master | 2023-07-30T08:25:38.520000 | 2021-09-16T05:09:11 | 2021-09-16T05:09:11 | 407,021,143 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.nguyenxb.boot.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.PathMatchConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.util.UrlPathHelper;
@Configuration(proxyBeanMethods = false)
public class WebConfigTest1 implements WebMvcConfigurer {
@Override
public void configurePathMatch(PathMatchConfigurer configurer) {
// ่ทๅ่ทฏๅพๅธฎๅฉๅจ
UrlPathHelper pathHelper = new UrlPathHelper();
// ่ฎพ็ฝฎไธ็งป้ค ๅๅทๅ้ข็ๅ
ๅฎน, ่ฟๆ ทๆ่ฝ่ฎฉ็ฉ้ตๅ้ๅ่ฝ็ๆ
pathHelper.setRemoveSemicolonContent(false);
configurer.setUrlPathHelper(pathHelper);
}
}
| UTF-8 | Java | 825 | java | WebConfigTest1.java | Java | []
| null | []
| package com.nguyenxb.boot.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.PathMatchConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.util.UrlPathHelper;
@Configuration(proxyBeanMethods = false)
public class WebConfigTest1 implements WebMvcConfigurer {
@Override
public void configurePathMatch(PathMatchConfigurer configurer) {
// ่ทๅ่ทฏๅพๅธฎๅฉๅจ
UrlPathHelper pathHelper = new UrlPathHelper();
// ่ฎพ็ฝฎไธ็งป้ค ๅๅทๅ้ข็ๅ
ๅฎน, ่ฟๆ ทๆ่ฝ่ฎฉ็ฉ้ตๅ้ๅ่ฝ็ๆ
pathHelper.setRemoveSemicolonContent(false);
configurer.setUrlPathHelper(pathHelper);
}
}
| 825 | 0.792378 | 0.791064 | 20 | 37.049999 | 25.774939 | 77 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false | 13 |
1c2a4655c9189e4a7ae7def3fe1cbd05e01e87eb | 23,957,327,578,715 | d140075b4d9fad72f2227c651b930e38b3bdb084 | /week-8-pair-exercises-java-team-7/java/src/main/java/com/techelevator/ssg/model/store/CartItems.java | bd641b894794daedc6545c93ad80de90fb3c1f42 | []
| no_license | ASaylor1986/techElevatorWork | https://github.com/ASaylor1986/techElevatorWork | cbc4690262a3de42dbd3f8195e895d8f3267aef2 | 6bbc447191f074aed9f2f925c7cc128a4112084e | refs/heads/master | 2023-01-10T07:38:44.465000 | 2019-10-16T20:04:26 | 2019-10-16T20:04:26 | 215,363,665 | 0 | 0 | null | false | 2019-10-16T19:40:22 | 2019-10-15T18:00:08 | 2019-10-16T19:38:56 | 2019-10-16T19:40:21 | 0 | 0 | 0 | 2 | TSQL | false | false | package com.techelevator.ssg.model.store;
import java.math.BigDecimal;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
public class CartItems {
private int quantity;
private Product p;
private BigDecimal totalPerItem;
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public Product getProduct() {
return p;
}
public void setProduct(Product product) {
this.p = product;
}
public BigDecimal getTotalPricePerItem() {
totalPerItem = p.getPrice().multiply(new BigDecimal (quantity));
return totalPerItem;
}
}
| UTF-8 | Java | 651 | java | CartItems.java | Java | []
| null | []
| package com.techelevator.ssg.model.store;
import java.math.BigDecimal;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
public class CartItems {
private int quantity;
private Product p;
private BigDecimal totalPerItem;
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public Product getProduct() {
return p;
}
public void setProduct(Product product) {
this.p = product;
}
public BigDecimal getTotalPricePerItem() {
totalPerItem = p.getPrice().multiply(new BigDecimal (quantity));
return totalPerItem;
}
}
| 651 | 0.737327 | 0.737327 | 36 | 17.083334 | 18.389875 | 67 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.277778 | false | false | 13 |
790b57587e1958212a163fd791078a69e740cd6e | 24,945,170,087,856 | 76fcf591e1b8efd2578a45fbba64c404cffd9713 | /hll_inventory_new/HLL_Inventory/src/main/java/com/hllinventory/demo/service/ChargesMasterService.java | 6ef3ae94f86894db2d5352552faca4bf6bda41c7 | []
| no_license | surekha061993/hll_inventory_new | https://github.com/surekha061993/hll_inventory_new | 26804438833dd632ec3dc62f988b23eb11a0468f | 512c69d28ffcdae16587b70d8cd746ca1ab72774 | refs/heads/master | 2023-03-11T12:33:42.135000 | 2021-02-23T10:26:44 | 2021-02-23T10:26:44 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.hllinventory.demo.service;
import java.util.List;
import com.hllinventory.demo.model.ChargesMaster;
/**
* @author Surekha Londhe
* @Date 20-12-2020
*/
public interface ChargesMasterService {
public void saveCharges(ChargesMaster charges);
public ChargesMaster getCharges(int inv_charges_Id);
public List<ChargesMaster> getAllCharges();
public void updateCharges(ChargesMaster charges);
public ChargesMaster deleteCharges(ChargesMaster charges);
}
| UTF-8 | Java | 474 | java | ChargesMasterService.java | Java | [
{
"context": "inventory.demo.model.ChargesMaster;\n/**\n * @author Surekha Londhe\n * @Date 20-12-2020\n */\npublic interface ChargesM",
"end": 143,
"score": 0.9998831748962402,
"start": 129,
"tag": "NAME",
"value": "Surekha Londhe"
}
]
| null | []
| package com.hllinventory.demo.service;
import java.util.List;
import com.hllinventory.demo.model.ChargesMaster;
/**
* @author <NAME>
* @Date 20-12-2020
*/
public interface ChargesMasterService {
public void saveCharges(ChargesMaster charges);
public ChargesMaster getCharges(int inv_charges_Id);
public List<ChargesMaster> getAllCharges();
public void updateCharges(ChargesMaster charges);
public ChargesMaster deleteCharges(ChargesMaster charges);
}
| 466 | 0.793249 | 0.776371 | 21 | 21.571428 | 21.944891 | 59 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.619048 | false | false | 13 |
676fc47c0eff043f3af6a188d6d78560bd9212ee | 17,944,373,432,957 | f0d23794db6b01238ce22feeb83eeef959cda93c | /src/main/java/com/sprapp/dao/TestDao.java | e10adc58c6f8909f478f61293820d35337dec91d | []
| no_license | tosique/webapp | https://github.com/tosique/webapp | 757875680543e91a21afc462cae37d14b0e34cf7 | 3d5a3f14545485fdf287a6679632e269c3c39980 | refs/heads/master | 2016-04-03T22:50:00.713000 | 2014-12-30T02:49:30 | 2014-12-30T02:49:30 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.sprapp.dao;
import com.sprapp.model.Test;
import java.util.List;
public interface TestDao {
void deleteTest(Test test);
void insertTest(Test test);
void updateTest(Test test);
Test getTestById(int idTest);
List<Test> getAll();
}
| UTF-8 | Java | 270 | java | TestDao.java | Java | []
| null | []
| package com.sprapp.dao;
import com.sprapp.model.Test;
import java.util.List;
public interface TestDao {
void deleteTest(Test test);
void insertTest(Test test);
void updateTest(Test test);
Test getTestById(int idTest);
List<Test> getAll();
}
| 270 | 0.692593 | 0.692593 | 19 | 13.210526 | 14.073413 | 33 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.421053 | false | false | 13 |
f41592054d872148a5cb6d8493858711fcea77ec | 32,487,132,682,215 | f71cf9d6b966a7bb46f82fde29934813a53ac805 | /main/java/com/example/rxandroid/common/connectivity/ConnectivityReceiverListener.java | ec03957c4968ba4d9fe33efcbfea5f8c3c49c3da | []
| no_license | mohamedIbrahimAhmed/androidApplicationArchitecture | https://github.com/mohamedIbrahimAhmed/androidApplicationArchitecture | 25d0eb601cd37a7d1b39503440103807a731b5cc | e556ea2429f10af237c6e6d6355fd6461c38c325 | refs/heads/master | 2021-01-17T16:40:15.558000 | 2016-07-18T12:06:26 | 2016-07-18T12:06:26 | 63,584,150 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.rxandroid.common.connectivity;
/**
* Created by mohamed.ibrahim on 7/10/2016.
*/
public interface ConnectivityReceiverListener {
void onNetworkConnectionChanged(boolean isConnected);
}
| UTF-8 | Java | 220 | java | ConnectivityReceiverListener.java | Java | [
{
"context": "android.common.connectivity;\r\n\r\n/**\r\n * Created by mohamed.ibrahim on 7/10/2016.\r\n */\r\npublic interface Connectivity",
"end": 88,
"score": 0.9992412328720093,
"start": 73,
"tag": "NAME",
"value": "mohamed.ibrahim"
}
]
| null | []
| package com.example.rxandroid.common.connectivity;
/**
* Created by mohamed.ibrahim on 7/10/2016.
*/
public interface ConnectivityReceiverListener {
void onNetworkConnectionChanged(boolean isConnected);
}
| 220 | 0.759091 | 0.727273 | 8 | 25.5 | 24.04163 | 57 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.25 | false | false | 13 |
99d52da6d1175d1e62b7727cff5ea4c44e08da21 | 29,119,878,317,056 | 90ef948c02ee2f01752cbaa07287986536d84088 | /android/src/main/java/com/neoon/blesdk/decode/entity/health/HeartRateValue.java | 51547fa1e5474786e7949b1ac074428a4ef4b28b | []
| no_license | sengeiou/neoon-ble-sdk | https://github.com/sengeiou/neoon-ble-sdk | c7304f8f31d604f98b54a4e70e53db38b007aa74 | 6a02b5f6118aaf0caf6bdc371ea1d0672b3b20d9 | refs/heads/master | 2023-01-30T06:52:57.539000 | 2020-12-12T07:00:34 | 2020-12-12T07:00:34 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.neoon.blesdk.decode.entity.health;
/**
* ไฝ่
:ไธ่(2018/7/10).
* ๅ่ฝ:
*/
public class HeartRateValue {
private int heartRate;
public HeartRateValue(int heartRate) {
this.heartRate = heartRate;
}
public int getHeartRate() {
return heartRate;
}
}
| UTF-8 | Java | 329 | java | HeartRateValue.java | Java | [
{
"context": ".neoon.blesdk.decode.entity.health;\r\n\r\n/**\r\n * ไฝ่
:ไธ่(2018/7/10).\r\n * ๅ่ฝ:\r\n */\r\n\r\npublic class HeartRat",
"end": 63,
"score": 0.9945796132087708,
"start": 61,
"tag": "NAME",
"value": "ไธ่"
}
]
| null | []
| package com.neoon.blesdk.decode.entity.health;
/**
* ไฝ่
:ไธ่(2018/7/10).
* ๅ่ฝ:
*/
public class HeartRateValue {
private int heartRate;
public HeartRateValue(int heartRate) {
this.heartRate = heartRate;
}
public int getHeartRate() {
return heartRate;
}
}
| 329 | 0.586751 | 0.564669 | 20 | 13.85 | 15.614977 | 46 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.2 | false | false | 13 |
7504692d1c8cc55b50e05763feeed089cc35c18b | 32,710,470,944,347 | d691e61127d0620680e5a05540b411bee5578010 | /src/java/control/BrandControl.java | 5a20e6e3eea7cb70103280543e2d4eb752f0e446 | []
| no_license | danielsenaisc/senai-testes | https://github.com/danielsenaisc/senai-testes | 48f66fe4f4c3debb3ca4e14a8cb6fd227b0cd0a6 | 6eb6c45ab72dddd1a5be51533c43823ed042e2a1 | refs/heads/master | 2021-01-10T20:31:49.959000 | 2014-11-10T22:43:31 | 2014-11-10T22:44:12 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package control;
import java.util.ArrayList;
import domain.Marca;
import javax.persistence.NoResultException;
public class BrandControl {
/**
* Retorna todos as marcas cadastradas no banco de dados.
*
* @return Lista de Marcas.
*/
public ArrayList<Marca> selectAll() {
return new ArrayList(Conexao.namedQuery("Marca.findAll"));
}
/**
* Adiciona uma marca no banco de dados.
*
* @param marca Marca a ser adicionada no banco.
*/
public void add(Marca marca) throws NullPointerException {
if (hasNullValues(marca)) {
throw new NullPointerException();
}
Conexao.persist(marca);
}
/**
* Remove permanentemente uma marca do banco de dados.
*
* @param marca Marca a ser removida permanentemente no banco.
*/
public void delete(Marca marca) {
Conexao.remove(marca);
}
//TODO
public void update(Marca marca) {
}
public Marca findById(Long id) {
Marca marcaDeRetorno = new Marca();
try {
marcaDeRetorno = (Marca) Conexao.singleResultNamedQuery("Marca.findById", id, "id");
} catch (NoResultException e) {
//TODO tratar
e.printStackTrace();
}
return marcaDeRetorno;
}
private boolean hasNullValues(Marca marca) {
if (marca.getNome().equals("")) {
return true;
}
System.out.println("nome ok");
if (marca.getDataCriacao() == null) {
return true;
}
System.out.println("data ok");
if (marca.getIdadeInicial() == 0l) {
return true;
}
System.out.println("idade inicial ok");
if (marca.getIdadeFinal() == 0l) {
return true;
}
System.out.println("idade final ok");
if (marca.getStatus().equals(' ')) {
return true;
}
System.out.println("status ok");
if (marca.getIndustriaId() == null) {
return true;
}
System.out.println("industriaID ok");
return false;
}
}
| UTF-8 | Java | 2,211 | java | BrandControl.java | Java | []
| null | []
| package control;
import java.util.ArrayList;
import domain.Marca;
import javax.persistence.NoResultException;
public class BrandControl {
/**
* Retorna todos as marcas cadastradas no banco de dados.
*
* @return Lista de Marcas.
*/
public ArrayList<Marca> selectAll() {
return new ArrayList(Conexao.namedQuery("Marca.findAll"));
}
/**
* Adiciona uma marca no banco de dados.
*
* @param marca Marca a ser adicionada no banco.
*/
public void add(Marca marca) throws NullPointerException {
if (hasNullValues(marca)) {
throw new NullPointerException();
}
Conexao.persist(marca);
}
/**
* Remove permanentemente uma marca do banco de dados.
*
* @param marca Marca a ser removida permanentemente no banco.
*/
public void delete(Marca marca) {
Conexao.remove(marca);
}
//TODO
public void update(Marca marca) {
}
public Marca findById(Long id) {
Marca marcaDeRetorno = new Marca();
try {
marcaDeRetorno = (Marca) Conexao.singleResultNamedQuery("Marca.findById", id, "id");
} catch (NoResultException e) {
//TODO tratar
e.printStackTrace();
}
return marcaDeRetorno;
}
private boolean hasNullValues(Marca marca) {
if (marca.getNome().equals("")) {
return true;
}
System.out.println("nome ok");
if (marca.getDataCriacao() == null) {
return true;
}
System.out.println("data ok");
if (marca.getIdadeInicial() == 0l) {
return true;
}
System.out.println("idade inicial ok");
if (marca.getIdadeFinal() == 0l) {
return true;
}
System.out.println("idade final ok");
if (marca.getStatus().equals(' ')) {
return true;
}
System.out.println("status ok");
if (marca.getIndustriaId() == null) {
return true;
}
System.out.println("industriaID ok");
return false;
}
}
| 2,211 | 0.540027 | 0.539123 | 84 | 24.321428 | 20.488766 | 96 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.321429 | false | false | 13 |
13caa7dd51b0b3b47ff0931a0c4ae3171b9e72dd | 11,175,504,930,560 | bdf17383e0cda687c48d1507a1ab89ce55032b97 | /app/src/main/java/com/example/muslimhotel/ui/HotelDetailActivity.java | 6701f34d99050d81b1f0a3922bec1825cdbe19c0 | []
| no_license | fazri09/android_muslim_hotel | https://github.com/fazri09/android_muslim_hotel | 95088030e1b9aee495f6968b5749d2710e791059 | b2adb86d9aef8bb1ae99f72504b84371ede117cc | refs/heads/master | 2021-01-04T12:17:06.686000 | 2020-02-21T07:59:49 | 2020-02-21T07:59:49 | 240,543,067 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.muslimhotel.ui;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.text.Html;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import com.example.muslimhotel.R;
import com.squareup.picasso.Picasso;
public class HotelDetailActivity extends AppCompatActivity {
Button expandbutton;
TextView tvKotaHotel;
TextView tvDeskripsi, tvNamaHotel, tvHarga, tvReviewerHotel, tvScoreHotel, tvTanggalCheck, tvPeopleBedroom;
ImageView othrpicture, iv_gambar_hotel;
private String bulan;
private String i_namahotel, i_kotahotel, i_gambarhotel, i_hargahotel, i_reviewhotel, i_scorehotel, i_deskripsihotel, i_cekin, i_cekout, i_people, i_bedrooms;
int identifier = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_hotel_detail);
othrpicture = (ImageView) findViewById(R.id.otherpctr);
expandbutton = (Button) findViewById(R.id.expandbutton);
tvDeskripsi = (TextView) findViewById(R.id.tvDeskripsi);
iv_gambar_hotel = (ImageView) findViewById(R.id.iv_gambar_hotel);
tvKotaHotel = (TextView) findViewById(R.id.tvKotaHotel);
tvNamaHotel = (TextView) findViewById(R.id.tvNamaHotel);
tvHarga = (TextView) findViewById(R.id.tvHarga);
tvReviewerHotel = (TextView) findViewById(R.id.tvReviewerHotel);
tvScoreHotel = (TextView) findViewById(R.id.tvScoreHotel);
tvTanggalCheck = (TextView) findViewById(R.id.tvTanggalCheck);
tvPeopleBedroom = (TextView) findViewById(R.id.tvPeopleBedroom);
i_namahotel = getIntent().getStringExtra("nmHotel");
i_kotahotel = getIntent().getStringExtra("kotaHotel");
i_gambarhotel = getIntent().getStringExtra("gambarHotel");
i_hargahotel = getIntent().getStringExtra("hgHotel");
i_reviewhotel = getIntent().getStringExtra("review");
i_scorehotel = getIntent().getStringExtra("scoreHotel");
i_deskripsihotel = getIntent().getStringExtra("deskripsi");
i_cekin = getIntent().getStringExtra("cekIn");
i_cekout = getIntent().getStringExtra("cekOut");
i_people = getIntent().getStringExtra("orang");
i_bedrooms = getIntent().getStringExtra("bedroom");
if (i_cekin.equalsIgnoreCase("9") || i_cekout.equalsIgnoreCase("10")) {
tvNamaHotel.setText(i_namahotel);
tvKotaHotel.setText(Html.fromHtml("<u>" + i_kotahotel + "</u>"));
tvHarga.setText("IDR " + i_hargahotel);
tvReviewerHotel.setText("(" + i_reviewhotel + ")" + " Reviews");
Log.d("cekinsad", "onCreate: " + i_reviewhotel);
tvScoreHotel.setText(i_scorehotel);
tvDeskripsi.setText(i_deskripsihotel);
tvPeopleBedroom.setText("-");
tvTanggalCheck.setText("-");
} else {
tvNamaHotel.setText(i_namahotel);
tvKotaHotel.setText(Html.fromHtml("<u>" + i_kotahotel + "</u>"));
tvHarga.setText("IDR " + i_hargahotel);
tvReviewerHotel.setText("(" + i_reviewhotel + ")" + " Reviews");
Log.d("cekinsad", "onCreate: " + i_reviewhotel);
tvScoreHotel.setText(i_scorehotel);
tvDeskripsi.setText(i_deskripsihotel);
tvPeopleBedroom.setText(i_bedrooms + " Bedroom-" + i_people + " People");
String cekin_total = i_cekin;
String[] strCekin = cekin_total.split("-");
String cekinTahun = strCekin[0]; // tahun
String cekinBulan = strCekin[1]; // bulan
String cekinTanggal = strCekin[2]; // tanggal
String cekout_total = i_cekout;
String[] strCekout = cekout_total.split("-");
String cekoutTahun = strCekout[0]; // tahun
String cekoutBulan = strCekout[1]; // bulan
String cekoutTanggal = strCekout[2]; // tanggal
if (cekoutBulan.equalsIgnoreCase("01")) {
bulan = "Jan";
} else if (cekoutBulan.equalsIgnoreCase("02")) {
bulan = "Feb";
} else if (cekoutBulan.equalsIgnoreCase("03")) {
bulan = "Mar";
} else if (cekoutBulan.equalsIgnoreCase("04")) {
bulan = "Apr";
} else if (cekoutBulan.equalsIgnoreCase("05")) {
bulan = "Mei";
} else if (cekoutBulan.equalsIgnoreCase("06")) {
bulan = "Jun";
} else if (cekoutBulan.equalsIgnoreCase("07")) {
bulan = "Jul";
} else if (cekoutBulan.equalsIgnoreCase("08")) {
bulan = "Aug";
} else if (cekoutBulan.equalsIgnoreCase("09")) {
bulan = "Sep";
} else if (cekoutBulan.equalsIgnoreCase("10")) {
bulan = "Oct";
} else if (cekoutBulan.equalsIgnoreCase("11")) {
bulan = "Nov";
} else if (cekoutBulan.equalsIgnoreCase("12")) {
bulan = "Dec";
} else {
bulan = null;
}
Log.d("ohyes", "onCreate: " + cekinTahun + "$" + cekinBulan + "$" + cekinTanggal + bulan);
tvTanggalCheck.setText(cekinTanggal + " - " + cekoutTanggal + " " + bulan + " " + cekoutTahun);
}
Picasso.with(HotelDetailActivity.this).load(i_gambarhotel).into(iv_gambar_hotel);
othrpicture.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intenttopict = new Intent(HotelDetailActivity.this, OtherPicturesActivity.class);
startActivity(intenttopict);
}
});
expandbutton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (identifier == 0) {
tvDeskripsi.setMaxLines(100);
expandbutton.setBackgroundResource(R.drawable.uarrow);
identifier = 1;
} else {
tvDeskripsi.setMaxLines(4);
expandbutton.setBackgroundResource(R.drawable.darrow);
identifier = 0;
}
}
});
}
}
| UTF-8 | Java | 6,466 | java | HotelDetailActivity.java | Java | []
| null | []
| package com.example.muslimhotel.ui;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.text.Html;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import com.example.muslimhotel.R;
import com.squareup.picasso.Picasso;
public class HotelDetailActivity extends AppCompatActivity {
Button expandbutton;
TextView tvKotaHotel;
TextView tvDeskripsi, tvNamaHotel, tvHarga, tvReviewerHotel, tvScoreHotel, tvTanggalCheck, tvPeopleBedroom;
ImageView othrpicture, iv_gambar_hotel;
private String bulan;
private String i_namahotel, i_kotahotel, i_gambarhotel, i_hargahotel, i_reviewhotel, i_scorehotel, i_deskripsihotel, i_cekin, i_cekout, i_people, i_bedrooms;
int identifier = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_hotel_detail);
othrpicture = (ImageView) findViewById(R.id.otherpctr);
expandbutton = (Button) findViewById(R.id.expandbutton);
tvDeskripsi = (TextView) findViewById(R.id.tvDeskripsi);
iv_gambar_hotel = (ImageView) findViewById(R.id.iv_gambar_hotel);
tvKotaHotel = (TextView) findViewById(R.id.tvKotaHotel);
tvNamaHotel = (TextView) findViewById(R.id.tvNamaHotel);
tvHarga = (TextView) findViewById(R.id.tvHarga);
tvReviewerHotel = (TextView) findViewById(R.id.tvReviewerHotel);
tvScoreHotel = (TextView) findViewById(R.id.tvScoreHotel);
tvTanggalCheck = (TextView) findViewById(R.id.tvTanggalCheck);
tvPeopleBedroom = (TextView) findViewById(R.id.tvPeopleBedroom);
i_namahotel = getIntent().getStringExtra("nmHotel");
i_kotahotel = getIntent().getStringExtra("kotaHotel");
i_gambarhotel = getIntent().getStringExtra("gambarHotel");
i_hargahotel = getIntent().getStringExtra("hgHotel");
i_reviewhotel = getIntent().getStringExtra("review");
i_scorehotel = getIntent().getStringExtra("scoreHotel");
i_deskripsihotel = getIntent().getStringExtra("deskripsi");
i_cekin = getIntent().getStringExtra("cekIn");
i_cekout = getIntent().getStringExtra("cekOut");
i_people = getIntent().getStringExtra("orang");
i_bedrooms = getIntent().getStringExtra("bedroom");
if (i_cekin.equalsIgnoreCase("9") || i_cekout.equalsIgnoreCase("10")) {
tvNamaHotel.setText(i_namahotel);
tvKotaHotel.setText(Html.fromHtml("<u>" + i_kotahotel + "</u>"));
tvHarga.setText("IDR " + i_hargahotel);
tvReviewerHotel.setText("(" + i_reviewhotel + ")" + " Reviews");
Log.d("cekinsad", "onCreate: " + i_reviewhotel);
tvScoreHotel.setText(i_scorehotel);
tvDeskripsi.setText(i_deskripsihotel);
tvPeopleBedroom.setText("-");
tvTanggalCheck.setText("-");
} else {
tvNamaHotel.setText(i_namahotel);
tvKotaHotel.setText(Html.fromHtml("<u>" + i_kotahotel + "</u>"));
tvHarga.setText("IDR " + i_hargahotel);
tvReviewerHotel.setText("(" + i_reviewhotel + ")" + " Reviews");
Log.d("cekinsad", "onCreate: " + i_reviewhotel);
tvScoreHotel.setText(i_scorehotel);
tvDeskripsi.setText(i_deskripsihotel);
tvPeopleBedroom.setText(i_bedrooms + " Bedroom-" + i_people + " People");
String cekin_total = i_cekin;
String[] strCekin = cekin_total.split("-");
String cekinTahun = strCekin[0]; // tahun
String cekinBulan = strCekin[1]; // bulan
String cekinTanggal = strCekin[2]; // tanggal
String cekout_total = i_cekout;
String[] strCekout = cekout_total.split("-");
String cekoutTahun = strCekout[0]; // tahun
String cekoutBulan = strCekout[1]; // bulan
String cekoutTanggal = strCekout[2]; // tanggal
if (cekoutBulan.equalsIgnoreCase("01")) {
bulan = "Jan";
} else if (cekoutBulan.equalsIgnoreCase("02")) {
bulan = "Feb";
} else if (cekoutBulan.equalsIgnoreCase("03")) {
bulan = "Mar";
} else if (cekoutBulan.equalsIgnoreCase("04")) {
bulan = "Apr";
} else if (cekoutBulan.equalsIgnoreCase("05")) {
bulan = "Mei";
} else if (cekoutBulan.equalsIgnoreCase("06")) {
bulan = "Jun";
} else if (cekoutBulan.equalsIgnoreCase("07")) {
bulan = "Jul";
} else if (cekoutBulan.equalsIgnoreCase("08")) {
bulan = "Aug";
} else if (cekoutBulan.equalsIgnoreCase("09")) {
bulan = "Sep";
} else if (cekoutBulan.equalsIgnoreCase("10")) {
bulan = "Oct";
} else if (cekoutBulan.equalsIgnoreCase("11")) {
bulan = "Nov";
} else if (cekoutBulan.equalsIgnoreCase("12")) {
bulan = "Dec";
} else {
bulan = null;
}
Log.d("ohyes", "onCreate: " + cekinTahun + "$" + cekinBulan + "$" + cekinTanggal + bulan);
tvTanggalCheck.setText(cekinTanggal + " - " + cekoutTanggal + " " + bulan + " " + cekoutTahun);
}
Picasso.with(HotelDetailActivity.this).load(i_gambarhotel).into(iv_gambar_hotel);
othrpicture.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intenttopict = new Intent(HotelDetailActivity.this, OtherPicturesActivity.class);
startActivity(intenttopict);
}
});
expandbutton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (identifier == 0) {
tvDeskripsi.setMaxLines(100);
expandbutton.setBackgroundResource(R.drawable.uarrow);
identifier = 1;
} else {
tvDeskripsi.setMaxLines(4);
expandbutton.setBackgroundResource(R.drawable.darrow);
identifier = 0;
}
}
});
}
}
| 6,466 | 0.596041 | 0.5897 | 158 | 39.924049 | 28.662935 | 161 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.753165 | false | false | 13 |
ceb70248e43bda6adf678bc75423503b0a0f0c60 | 23,381,801,986,341 | 919402cdf5146cc207b7dd91912ac39bedb4c3b9 | /src/main/java/com/raddle/dlna/ctrl/ActionHelper.java | a0b813400b2a7396eafdf9aebd7e7b4562ed5fa2 | [
"Apache-2.0"
]
| permissive | raddle60/dlna-client | https://github.com/raddle60/dlna-client | 05639aeef9257fa3f1ab9b01869f89d256388b96 | 2b8f89a117d7484df2bf0dd399d17743371494a3 | refs/heads/master | 2020-05-18T08:39:13.015000 | 2015-01-17T16:33:28 | 2015-01-17T16:33:28 | 23,782,656 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /**
*
*/
package com.raddle.dlna.ctrl;
import org.cybergarage.upnp.Action;
import org.cybergarage.upnp.ArgumentList;
import org.cybergarage.upnp.Device;
import org.cybergarage.upnp.Service;
import com.raddle.dlna.renderer.AVTransport;
import com.raddle.dlna.util.DurationUtils;
/**
* @author raddle
*
*/
public class ActionHelper {
private Device device;
public ActionHelper(Device device) {
this.device = device;
}
public void play(String url) {
Service avTransService = device.getService(AVTransport.SERVICE_TYPE);
Action setUriAct = avTransService.getAction(AVTransport.SETAVTRANSPORTURI);
setUriAct.setArgumentValue(AVTransport.INSTANCEID, "0");
setUriAct.setArgumentValue(AVTransport.CURRENTURI, url);
setUriAct.setArgumentValue(AVTransport.CURRENTURIMETADATA, "");
if (!setUriAct.postControlAction()) {
return;
}
Action playAct = avTransService.getAction(AVTransport.PLAY);
playAct.setArgumentValue(AVTransport.INSTANCEID, "0");
playAct.setArgumentValue(AVTransport.SPEED, "1");
if (!playAct.postControlAction()) {
return;
}
}
public boolean isSupportNext() {
Service avTransService = device.getService(AVTransport.SERVICE_TYPE);
Action nextAct = avTransService.getAction(AVTransport.NEXT);
return nextAct != null;
}
public void next(String url) {
Service avTransService = device.getService(AVTransport.SERVICE_TYPE);
Action setNextUriAct = avTransService.getAction(AVTransport.SETNEXTAVTRANSPORTURI);
setNextUriAct.setArgumentValue(AVTransport.INSTANCEID, "0");
setNextUriAct.setArgumentValue(AVTransport.NEXTURI, url);
setNextUriAct.setArgumentValue(AVTransport.NEXTURIMETADATA, "");
if (!setNextUriAct.postControlAction()) {
return;
}
Action nextAct = avTransService.getAction(AVTransport.NEXT);
nextAct.setArgumentValue(AVTransport.INSTANCEID, "0");
if (!nextAct.postControlAction()) {
return;
}
}
public void resume() {
Service avTransService = device.getService(AVTransport.SERVICE_TYPE);
Action playAct = avTransService.getAction(AVTransport.PLAY);
playAct.setArgumentValue(AVTransport.INSTANCEID, "0");
playAct.setArgumentValue(AVTransport.SPEED, "1");
if (!playAct.postControlAction()) {
return;
}
}
public void pause() {
Service avTransService = device.getService(AVTransport.SERVICE_TYPE);
Action pauseAct = avTransService.getAction(AVTransport.PAUSE);
pauseAct.setArgumentValue(AVTransport.INSTANCEID, "0");
if (!pauseAct.postControlAction()) {
return;
}
}
public ArgumentList getPositionInfo() {
Service avTransService = device.getService(AVTransport.SERVICE_TYPE);
Action getPosAct = avTransService.getAction(AVTransport.GETPOSITIONINFO);
getPosAct.setArgumentValue(AVTransport.INSTANCEID, "0");
if (!getPosAct.postControlAction()) {
return null;
}
return getPosAct.getOutputArgumentList();
}
public void seak(int second) {
Service avTransService = device.getService(AVTransport.SERVICE_TYPE);
Action getPosAct = avTransService.getAction(AVTransport.SEEK);
getPosAct.setArgumentValue(AVTransport.INSTANCEID, "0");
getPosAct.setArgumentValue(AVTransport.UNIT, AVTransport.TRACK_NR);
getPosAct.setArgumentValue(AVTransport.TARGET, DurationUtils.getTrackNRFormat(second));
if (!getPosAct.postControlAction()) {
return;
}
}
public void stop() {
Service avTransService = device.getService(AVTransport.SERVICE_TYPE);
Action stopAct = avTransService.getAction(AVTransport.STOP);
stopAct.setArgumentValue(AVTransport.INSTANCEID, "0");
if (!stopAct.postControlAction()) {
return;
}
}
public Device getDevice() {
return device;
}
}
| UTF-8 | Java | 3,741 | java | ActionHelper.java | Java | [
{
"context": "raddle.dlna.util.DurationUtils;\r\n\r\n/**\r\n * @author raddle\r\n *\r\n */\r\npublic class ActionHelper {\r\n\tprivate D",
"end": 319,
"score": 0.9994380474090576,
"start": 313,
"tag": "USERNAME",
"value": "raddle"
}
]
| null | []
| /**
*
*/
package com.raddle.dlna.ctrl;
import org.cybergarage.upnp.Action;
import org.cybergarage.upnp.ArgumentList;
import org.cybergarage.upnp.Device;
import org.cybergarage.upnp.Service;
import com.raddle.dlna.renderer.AVTransport;
import com.raddle.dlna.util.DurationUtils;
/**
* @author raddle
*
*/
public class ActionHelper {
private Device device;
public ActionHelper(Device device) {
this.device = device;
}
public void play(String url) {
Service avTransService = device.getService(AVTransport.SERVICE_TYPE);
Action setUriAct = avTransService.getAction(AVTransport.SETAVTRANSPORTURI);
setUriAct.setArgumentValue(AVTransport.INSTANCEID, "0");
setUriAct.setArgumentValue(AVTransport.CURRENTURI, url);
setUriAct.setArgumentValue(AVTransport.CURRENTURIMETADATA, "");
if (!setUriAct.postControlAction()) {
return;
}
Action playAct = avTransService.getAction(AVTransport.PLAY);
playAct.setArgumentValue(AVTransport.INSTANCEID, "0");
playAct.setArgumentValue(AVTransport.SPEED, "1");
if (!playAct.postControlAction()) {
return;
}
}
public boolean isSupportNext() {
Service avTransService = device.getService(AVTransport.SERVICE_TYPE);
Action nextAct = avTransService.getAction(AVTransport.NEXT);
return nextAct != null;
}
public void next(String url) {
Service avTransService = device.getService(AVTransport.SERVICE_TYPE);
Action setNextUriAct = avTransService.getAction(AVTransport.SETNEXTAVTRANSPORTURI);
setNextUriAct.setArgumentValue(AVTransport.INSTANCEID, "0");
setNextUriAct.setArgumentValue(AVTransport.NEXTURI, url);
setNextUriAct.setArgumentValue(AVTransport.NEXTURIMETADATA, "");
if (!setNextUriAct.postControlAction()) {
return;
}
Action nextAct = avTransService.getAction(AVTransport.NEXT);
nextAct.setArgumentValue(AVTransport.INSTANCEID, "0");
if (!nextAct.postControlAction()) {
return;
}
}
public void resume() {
Service avTransService = device.getService(AVTransport.SERVICE_TYPE);
Action playAct = avTransService.getAction(AVTransport.PLAY);
playAct.setArgumentValue(AVTransport.INSTANCEID, "0");
playAct.setArgumentValue(AVTransport.SPEED, "1");
if (!playAct.postControlAction()) {
return;
}
}
public void pause() {
Service avTransService = device.getService(AVTransport.SERVICE_TYPE);
Action pauseAct = avTransService.getAction(AVTransport.PAUSE);
pauseAct.setArgumentValue(AVTransport.INSTANCEID, "0");
if (!pauseAct.postControlAction()) {
return;
}
}
public ArgumentList getPositionInfo() {
Service avTransService = device.getService(AVTransport.SERVICE_TYPE);
Action getPosAct = avTransService.getAction(AVTransport.GETPOSITIONINFO);
getPosAct.setArgumentValue(AVTransport.INSTANCEID, "0");
if (!getPosAct.postControlAction()) {
return null;
}
return getPosAct.getOutputArgumentList();
}
public void seak(int second) {
Service avTransService = device.getService(AVTransport.SERVICE_TYPE);
Action getPosAct = avTransService.getAction(AVTransport.SEEK);
getPosAct.setArgumentValue(AVTransport.INSTANCEID, "0");
getPosAct.setArgumentValue(AVTransport.UNIT, AVTransport.TRACK_NR);
getPosAct.setArgumentValue(AVTransport.TARGET, DurationUtils.getTrackNRFormat(second));
if (!getPosAct.postControlAction()) {
return;
}
}
public void stop() {
Service avTransService = device.getService(AVTransport.SERVICE_TYPE);
Action stopAct = avTransService.getAction(AVTransport.STOP);
stopAct.setArgumentValue(AVTransport.INSTANCEID, "0");
if (!stopAct.postControlAction()) {
return;
}
}
public Device getDevice() {
return device;
}
}
| 3,741 | 0.739642 | 0.736701 | 117 | 29.97436 | 26.621584 | 89 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.008547 | false | false | 13 |
167f8e7cc3e6ec7ad250ea965118a8ddc37a6cf3 | 8,924,942,059,792 | 07d0a885869b2ec77838d56be3843e1ffe6c4377 | /src/main/java/com/assignment/calculator/client/Solution.java | c6205c93eda137bfd956fff57541c01ab9ef214c | []
| no_license | ragubalan/RagubalanDurairaj_AtomicCalculator | https://github.com/ragubalan/RagubalanDurairaj_AtomicCalculator | 85ef3854d46cea5d97b4332fecb347223b731c85 | 9179e9072694bb45d49338bbcddb931170c7e408 | refs/heads/master | 2021-01-10T04:54:26.949000 | 2016-02-08T21:30:49 | 2016-02-08T21:30:49 | 51,326,548 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* Copyright (C) 2016
*
* Created on Feb 2016.
*/
package com.assignment.calculator.client;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.assignment.calculator.exception.InvalidDataException;
import org.openscience.cdk.exception.InvalidSmilesException;
import org.openscience.cdk.interfaces.IAtomContainer;
import org.openscience.cdk.interfaces.IChemObjectBuilder;
import org.openscience.cdk.silent.SilentChemObjectBuilder;
import org.openscience.cdk.smiles.SmilesParser;
/**
* Main method
*
* @author Ragubalan Durairaj
*
*/
public class Solution {
private static final Logger LOG = Logger.getLogger(Solution.class.getName());
public static void main(String[] args) {
IChemObjectBuilder bldr = SilentChemObjectBuilder.getInstance();
SmilesParser smipar = new SmilesParser(bldr);
Calculate cal = new Calculate();
try {
Solution sol = new Solution();
// Validate the number of test cases.
int T = Integer.valueOf(cal.getINTVal());
boolean validNoOfTestCases = sol.validateNoOfTestCases(T);
while (validNoOfTestCases && T-- > 0) {
int ch = Integer.valueOf(cal.getINTVal());
// Validate Smiles value
String smiles = cal.getStringVal();
boolean validSmilesValue = sol.validateSmilesValue(smiles);
if (validSmilesValue) {
// Parse smiles value
IAtomContainer mol = smipar.parseSmiles(smiles);
int prop = 0;
switch (ch) {
case 1:
case 2:
case 3:
case 4:
prop = Calculate.get_Prop(ch).main(mol);
break;
default:
throw new InvalidDataException("Character input value is not valid. The passed in value of "
+ ch + " is not acceptable as a valid input value.");
}
// Output the result
cal.output.display(prop);
}
}
} catch (NumberFormatException e) {
LOG.severe("The passed in value is not a proper number. " + e.getMessage());
cal.output.displayError("The passed in value is not a proper number. " + e.getMessage());
} catch (InvalidSmilesException e) {
LOG.severe("The smiles value cannot be parsed. The actual exception reads : " + e.getMessage());
cal.output
.displayError("The smiles value cannot be parsed. The actual exception reads : " + e.getMessage());
} catch (InvalidDataException e) {
LOG.severe("One of the input values is not valid. The actual exception reads : " + e.getMessage());
cal.output.displayError("One of the input values is not valid. The actual exception reads : "
+ e.getMessage());
}
cal.output.out.close();
}
/**
* Validates whether the number of test cases is within 1 - 1000.
*
* @param T
* @return
* @throws InvalidDataException
*/
private boolean validateNoOfTestCases(int T) throws InvalidDataException {
if (1 <= T && T <= 1000) {
return true;
} else {
throw new InvalidDataException("The program can handle only 1 - 1000 test cases. The passed in value of "
+ T + " is not acceptable.");
}
}
/**
* Validates the SMILE value
*
* @param smiles
* @return
* @throws InvalidDataException
*/
private boolean validateSmilesValue(String smiles) throws InvalidDataException {
if (smiles == null || smiles.length() < 4 || smiles.length() > 1000) {
throw new InvalidDataException("SMILES input value is not valid. The passed in value of " + smiles
+ " is not acceptable as a SMILE value.");
} else {
return true;
}
}
} | UTF-8 | Java | 4,155 | java | Solution.java | Java | [
{
"context": "s.SmilesParser;\n\n/**\n * Main method\n * \n * @author Ragubalan Durairaj\n * \n */\npublic class Solution {\n private stati",
"end": 595,
"score": 0.9998254179954529,
"start": 577,
"tag": "NAME",
"value": "Ragubalan Durairaj"
}
]
| null | []
| /*
* Copyright (C) 2016
*
* Created on Feb 2016.
*/
package com.assignment.calculator.client;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.assignment.calculator.exception.InvalidDataException;
import org.openscience.cdk.exception.InvalidSmilesException;
import org.openscience.cdk.interfaces.IAtomContainer;
import org.openscience.cdk.interfaces.IChemObjectBuilder;
import org.openscience.cdk.silent.SilentChemObjectBuilder;
import org.openscience.cdk.smiles.SmilesParser;
/**
* Main method
*
* @author <NAME>
*
*/
public class Solution {
private static final Logger LOG = Logger.getLogger(Solution.class.getName());
public static void main(String[] args) {
IChemObjectBuilder bldr = SilentChemObjectBuilder.getInstance();
SmilesParser smipar = new SmilesParser(bldr);
Calculate cal = new Calculate();
try {
Solution sol = new Solution();
// Validate the number of test cases.
int T = Integer.valueOf(cal.getINTVal());
boolean validNoOfTestCases = sol.validateNoOfTestCases(T);
while (validNoOfTestCases && T-- > 0) {
int ch = Integer.valueOf(cal.getINTVal());
// Validate Smiles value
String smiles = cal.getStringVal();
boolean validSmilesValue = sol.validateSmilesValue(smiles);
if (validSmilesValue) {
// Parse smiles value
IAtomContainer mol = smipar.parseSmiles(smiles);
int prop = 0;
switch (ch) {
case 1:
case 2:
case 3:
case 4:
prop = Calculate.get_Prop(ch).main(mol);
break;
default:
throw new InvalidDataException("Character input value is not valid. The passed in value of "
+ ch + " is not acceptable as a valid input value.");
}
// Output the result
cal.output.display(prop);
}
}
} catch (NumberFormatException e) {
LOG.severe("The passed in value is not a proper number. " + e.getMessage());
cal.output.displayError("The passed in value is not a proper number. " + e.getMessage());
} catch (InvalidSmilesException e) {
LOG.severe("The smiles value cannot be parsed. The actual exception reads : " + e.getMessage());
cal.output
.displayError("The smiles value cannot be parsed. The actual exception reads : " + e.getMessage());
} catch (InvalidDataException e) {
LOG.severe("One of the input values is not valid. The actual exception reads : " + e.getMessage());
cal.output.displayError("One of the input values is not valid. The actual exception reads : "
+ e.getMessage());
}
cal.output.out.close();
}
/**
* Validates whether the number of test cases is within 1 - 1000.
*
* @param T
* @return
* @throws InvalidDataException
*/
private boolean validateNoOfTestCases(int T) throws InvalidDataException {
if (1 <= T && T <= 1000) {
return true;
} else {
throw new InvalidDataException("The program can handle only 1 - 1000 test cases. The passed in value of "
+ T + " is not acceptable.");
}
}
/**
* Validates the SMILE value
*
* @param smiles
* @return
* @throws InvalidDataException
*/
private boolean validateSmilesValue(String smiles) throws InvalidDataException {
if (smiles == null || smiles.length() < 4 || smiles.length() > 1000) {
throw new InvalidDataException("SMILES input value is not valid. The passed in value of " + smiles
+ " is not acceptable as a SMILE value.");
} else {
return true;
}
}
} | 4,143 | 0.575211 | 0.567028 | 117 | 34.521366 | 31.546627 | 119 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.350427 | false | false | 13 |
f9e3021d6f73c49c80c8042f6d42c6c915256dc4 | 30,889,404,830,757 | 1516f2d78057fe6e4e21c9fbcc2fd9c8514dce38 | /src/main/java/com/wesimplify/nodabba/domain/restaurant/search/RestaurantSearchDetail.java | 7d2fda9b9d2d6170baadab894fc7ab0a7a5721b4 | []
| no_license | NoDabba/nobox | https://github.com/NoDabba/nobox | 05fb2b643710d51f88e80ea3ec93e59983fd8e19 | 86879b5e680acc33dfe3f8c4365ee45470c96dc1 | refs/heads/master | 2016-09-05T12:15:53.889000 | 2015-06-30T14:50:55 | 2015-06-30T14:50:55 | 38,315,294 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /**
*
*/
package com.wesimplify.nodabba.domain.restaurant.search;
import java.math.BigDecimal;
import com.wesimplify.nodabba.domain.restaurant.RestaurantProfile;
/**
* @author sdoddi
* This will hold the light weight of search results
*/
public class RestaurantSearchDetail {
private RestaurantProfile profile;
private BigDecimal basePrice;
private float offerPercentage;
private BigDecimal offerPrice;
private BigDecimal savePrice;
private float ratings;
/**
* @param profile
* @param basePrice
* @param offerPercentage
* @param offerPrice
* @param savePrice
* @param ratings
*/
public RestaurantSearchDetail(RestaurantProfile profile,
BigDecimal basePrice, float offerPercentage, BigDecimal offerPrice,
BigDecimal savePrice, float ratings) {
super();
this.profile = profile;
this.basePrice = basePrice;
this.offerPercentage = offerPercentage;
this.offerPrice = offerPrice;
this.savePrice = savePrice;
this.ratings = ratings;
}
/**
* @return the profile
*/
public RestaurantProfile getProfile() {
return profile;
}
/**
* @return the basePrice
*/
public BigDecimal getBasePrice() {
return basePrice;
}
/**
* @return the offerPercentage
*/
public float getOfferPercentage() {
return offerPercentage;
}
/**
* @return the offerPrice
*/
public BigDecimal getOfferPrice() {
return offerPrice;
}
/**
* @return the savePrice
*/
public BigDecimal getSavePrice() {
return savePrice;
}
/**
* @return the ratings
*/
public float getRatings() {
return ratings;
}
}
| UTF-8 | Java | 1,560 | java | RestaurantSearchDetail.java | Java | [
{
"context": "main.restaurant.RestaurantProfile;\n\n/**\n * @author sdoddi\n * This will hold the light weight of search resu",
"end": 189,
"score": 0.9996695518493652,
"start": 183,
"tag": "USERNAME",
"value": "sdoddi"
}
]
| null | []
| /**
*
*/
package com.wesimplify.nodabba.domain.restaurant.search;
import java.math.BigDecimal;
import com.wesimplify.nodabba.domain.restaurant.RestaurantProfile;
/**
* @author sdoddi
* This will hold the light weight of search results
*/
public class RestaurantSearchDetail {
private RestaurantProfile profile;
private BigDecimal basePrice;
private float offerPercentage;
private BigDecimal offerPrice;
private BigDecimal savePrice;
private float ratings;
/**
* @param profile
* @param basePrice
* @param offerPercentage
* @param offerPrice
* @param savePrice
* @param ratings
*/
public RestaurantSearchDetail(RestaurantProfile profile,
BigDecimal basePrice, float offerPercentage, BigDecimal offerPrice,
BigDecimal savePrice, float ratings) {
super();
this.profile = profile;
this.basePrice = basePrice;
this.offerPercentage = offerPercentage;
this.offerPrice = offerPrice;
this.savePrice = savePrice;
this.ratings = ratings;
}
/**
* @return the profile
*/
public RestaurantProfile getProfile() {
return profile;
}
/**
* @return the basePrice
*/
public BigDecimal getBasePrice() {
return basePrice;
}
/**
* @return the offerPercentage
*/
public float getOfferPercentage() {
return offerPercentage;
}
/**
* @return the offerPrice
*/
public BigDecimal getOfferPrice() {
return offerPrice;
}
/**
* @return the savePrice
*/
public BigDecimal getSavePrice() {
return savePrice;
}
/**
* @return the ratings
*/
public float getRatings() {
return ratings;
}
}
| 1,560 | 0.716667 | 0.716667 | 77 | 19.259741 | 16.754456 | 70 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.363636 | false | false | 13 |
8d0873ae97058eb821a714b5eb275a158cdc4f47 | 31,181,462,571,661 | b583739c94e40125e5a26d9d78fd5ba933ff5aec | /src/main/java/com/puhj/electricity/api/v1/SearchController.java | 5075ff84e74995462c5c3a84cce575baee4b2c76 | []
| no_license | puhanjie/electricity | https://github.com/puhanjie/electricity | e118e6cd80918337d61b63097bb08e27dd577b5a | 731989c124cacc8f670f4d0aa28bd8fc6770c383 | refs/heads/main | 2023-08-24T17:15:58.182000 | 2021-10-26T15:18:17 | 2021-10-26T15:18:17 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.puhj.electricity.api.v1;
import com.puhj.electricity.bo.PageCounter;
import com.puhj.electricity.model.Spu;
import com.puhj.electricity.service.SearchService;
import com.puhj.electricity.util.CommonUtil;
import com.puhj.electricity.vo.PagingDozer;
import com.puhj.electricity.vo.SpuSimplifyVO;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
@RequestMapping("search")
@RestController
public class SearchController {
@Autowired
private SearchService searchService;
@GetMapping("")
public PagingDozer<Spu, SpuSimplifyVO> search(@RequestParam String q,
@RequestParam(defaultValue = "0") Integer start,
@RequestParam(defaultValue = "10") Integer count) {
PageCounter counter = CommonUtil.convertToPageParameter(start, count);
Page<Spu> page = this.searchService.search(q, counter.getPage(), counter.getCount());
return new PagingDozer<>(page, SpuSimplifyVO.class);
}
} | UTF-8 | Java | 1,132 | java | SearchController.java | Java | []
| null | []
| package com.puhj.electricity.api.v1;
import com.puhj.electricity.bo.PageCounter;
import com.puhj.electricity.model.Spu;
import com.puhj.electricity.service.SearchService;
import com.puhj.electricity.util.CommonUtil;
import com.puhj.electricity.vo.PagingDozer;
import com.puhj.electricity.vo.SpuSimplifyVO;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
@RequestMapping("search")
@RestController
public class SearchController {
@Autowired
private SearchService searchService;
@GetMapping("")
public PagingDozer<Spu, SpuSimplifyVO> search(@RequestParam String q,
@RequestParam(defaultValue = "0") Integer start,
@RequestParam(defaultValue = "10") Integer count) {
PageCounter counter = CommonUtil.convertToPageParameter(start, count);
Page<Spu> page = this.searchService.search(q, counter.getPage(), counter.getCount());
return new PagingDozer<>(page, SpuSimplifyVO.class);
}
} | 1,132 | 0.709364 | 0.70583 | 26 | 42.576923 | 28.694912 | 101 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.807692 | false | false | 13 |
9d613bac41b35beb356fe35b1a9e2ac35105c120 | 12,489,764,922,796 | 4466a6e23b4f827dc68ce93543c94a94817f9cd2 | /app/src/main/java/com/example/chhots/category_view/Contest/Adapter.java | ae1ecd6f7ef043b021ce415d766a21b4509edf9f | []
| no_license | smurfoh/SmurfohApp | https://github.com/smurfoh/SmurfohApp | a2c37dd8db2ff428b16cc5c0597a5275f11aa8e5 | 0a4b8bec3d8f2b986e9f431290f6f707cb856204 | refs/heads/master | 2022-06-03T14:40:52.451000 | 2020-04-30T09:25:30 | 2020-04-30T09:25:30 | 260,945,922 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.chhots.category_view.Contest;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;
import androidx.viewpager.widget.PagerAdapter;
import com.example.chhots.R;
import java.util.List;
public class Adapter extends PagerAdapter {
private List<Model> models;
private LayoutInflater layoutInflater;
private Context context;
public Adapter(List<Model> models, Context context) {
this.models = models;
this.context = context;
}
@Override
public int getCount() {
return models.size();
}
@Override
public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
return view.equals(object);
}
@NonNull
@Override
public Object instantiateItem(@NonNull final ViewGroup container, final int position) {
layoutInflater = LayoutInflater.from(context);
View view = layoutInflater.inflate(R.layout.raw_contest_item,container,false);
ImageView img1 = (ImageView)view.findViewById(R.id.contest_view);
TextView txt1 = (TextView)view.findViewById(R.id.participate);
img1.setImageResource(models.get(position).getImageId());
txt1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
setFragment(new form_contest());
//TODO: also need to send data
}
});
container.addView(view,0);
return view;
}
public void setFragment(Fragment fragment)
{
FragmentTransaction fragmentTransaction = ((AppCompatActivity)context).getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.nav_host_fragment,fragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
@Override
public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
container.removeView((View) object);
}
}
| UTF-8 | Java | 2,319 | java | Adapter.java | Java | []
| null | []
| package com.example.chhots.category_view.Contest;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;
import androidx.viewpager.widget.PagerAdapter;
import com.example.chhots.R;
import java.util.List;
public class Adapter extends PagerAdapter {
private List<Model> models;
private LayoutInflater layoutInflater;
private Context context;
public Adapter(List<Model> models, Context context) {
this.models = models;
this.context = context;
}
@Override
public int getCount() {
return models.size();
}
@Override
public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
return view.equals(object);
}
@NonNull
@Override
public Object instantiateItem(@NonNull final ViewGroup container, final int position) {
layoutInflater = LayoutInflater.from(context);
View view = layoutInflater.inflate(R.layout.raw_contest_item,container,false);
ImageView img1 = (ImageView)view.findViewById(R.id.contest_view);
TextView txt1 = (TextView)view.findViewById(R.id.participate);
img1.setImageResource(models.get(position).getImageId());
txt1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
setFragment(new form_contest());
//TODO: also need to send data
}
});
container.addView(view,0);
return view;
}
public void setFragment(Fragment fragment)
{
FragmentTransaction fragmentTransaction = ((AppCompatActivity)context).getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.nav_host_fragment,fragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
@Override
public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
container.removeView((View) object);
}
}
| 2,319 | 0.699439 | 0.697283 | 83 | 26.939758 | 27.44912 | 126 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.53012 | false | false | 13 |
2c6b939ddbdffecc18171ba653dedac899030c92 | 12,489,764,920,629 | 1634464228d77b5b7aaa29c3429ffc8d34d5e499 | /src/main/java/websocket/view/AppController.java | b53410d54c1acda765bd5da1285669bc3919ec34 | []
| no_license | adam-wojszczyk/quizer | https://github.com/adam-wojszczyk/quizer | 15bf585f2fdd271de0b4699bfe0e064a49e6f95b | 5270a20f07ae0cd37f1337c91094d909cbfd6f3a | refs/heads/master | 2020-03-05T22:10:28.165000 | 2017-04-09T15:27:03 | 2017-04-09T15:27:03 | 86,092,541 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package websocket.view;
import java.security.Principal;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.simp.annotation.SubscribeMapping;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import websocket.application.ApplicationService;
import websocket.application.Question;
@RestController
public class AppController {
private final ApplicationService applicationService;
@Autowired
public AppController(ApplicationService applicationService) {
this.applicationService = applicationService;
}
@GetMapping("/currentUser")
public String currentUser(@AuthenticationPrincipal Principal principal) {
return principal.getName();
}
@MessageMapping("/commands/answer")
public void answer(@AuthenticationPrincipal Principal principal, AnswerDto answerDto) {
applicationService.answer(answerDto.getNumber(), principal.getName());
}
@SubscribeMapping("/topic/state")
public void state() {
applicationService.pushState();
}
@SubscribeMapping("/topic/questions")
public QuestionDto questions() {
return toDto(applicationService.currentQuestion());
}
private QuestionDto toDto(Question question) {
QuestionDto questionDto = new QuestionDto(question.getQuestionText());
questionDto.setAnswer1(question.getOptions().get(0).getText())
.setAnswer2(question.getOptions().get(1).getText())
.setAnswer3(question.getOptions().get(2).getText())
.setAnswer4(question.getOptions().get(3).getText());
return questionDto;
}
}
| UTF-8 | Java | 1,869 | java | AppController.java | Java | []
| null | []
| package websocket.view;
import java.security.Principal;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.simp.annotation.SubscribeMapping;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import websocket.application.ApplicationService;
import websocket.application.Question;
@RestController
public class AppController {
private final ApplicationService applicationService;
@Autowired
public AppController(ApplicationService applicationService) {
this.applicationService = applicationService;
}
@GetMapping("/currentUser")
public String currentUser(@AuthenticationPrincipal Principal principal) {
return principal.getName();
}
@MessageMapping("/commands/answer")
public void answer(@AuthenticationPrincipal Principal principal, AnswerDto answerDto) {
applicationService.answer(answerDto.getNumber(), principal.getName());
}
@SubscribeMapping("/topic/state")
public void state() {
applicationService.pushState();
}
@SubscribeMapping("/topic/questions")
public QuestionDto questions() {
return toDto(applicationService.currentQuestion());
}
private QuestionDto toDto(Question question) {
QuestionDto questionDto = new QuestionDto(question.getQuestionText());
questionDto.setAnswer1(question.getOptions().get(0).getText())
.setAnswer2(question.getOptions().get(1).getText())
.setAnswer3(question.getOptions().get(2).getText())
.setAnswer4(question.getOptions().get(3).getText());
return questionDto;
}
}
| 1,869 | 0.743713 | 0.739433 | 53 | 34.264153 | 28.516232 | 91 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.396226 | false | false | 13 |
ef2c1b61f3ca79a74a55bf977f6e0a14fd50157b | 17,927,193,497,904 | 813f509adfb91c57c0627923aacd8ee8ab6db292 | /gui/swing/src/main/java/org/openecard/gui/swing/SwingUserConsent.java | 225b5151404619cf07094a41a562edc55dd76d6e | [
"GPL-3.0-only",
"GPL-1.0-or-later",
"LGPL-3.0-only",
"MIT",
"JSON",
"Apache-2.0",
"GPL-2.0-only"
]
| permissive | ecsec/open-ecard | https://github.com/ecsec/open-ecard | 7816bf420a718f0ff32c7e6de76082aea9c015f8 | b478089b79b2552af7eceba74d5b4d539563af7d | refs/heads/master | 2023-08-07T03:12:27.833000 | 2023-07-26T17:01:29 | 2023-07-26T17:01:29 | 4,614,129 | 105 | 30 | Apache-2.0 | false | 2023-04-27T23:54:42 | 2012-06-10T10:03:07 | 2023-04-22T23:55:28 | 2023-04-27T23:54:42 | 21,645 | 117 | 36 | 4 | Java | false | false | /****************************************************************************
* Copyright (C) 2012-2018 ecsec GmbH.
* All rights reserved.
* Contact: ecsec GmbH (info@ecsec.de)
*
* This file is part of the Open eCard App.
*
* GNU General Public License Usage
* This file may be used under the terms of the GNU General Public
* License version 3.0 as published by the Free Software Foundation
* and appearing in the file LICENSE.GPL included in the packaging of
* this file. Please review the following information to ensure the
* GNU General Public License version 3.0 requirements will be met:
* http://www.gnu.org/copyleft/gpl.html.
*
* Other Usage
* Alternatively, this file may be used in accordance with the terms
* and conditions contained in a signed written agreement between
* you and ecsec GmbH.
*
***************************************************************************/
package org.openecard.gui.swing;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.List;
import javax.swing.BoxLayout;
import javax.swing.GroupLayout;
import javax.swing.JComponent;
import javax.swing.JPanel;
import org.openecard.gui.FileDialog;
import org.openecard.gui.MessageDialog;
import org.openecard.gui.UserConsent;
import org.openecard.gui.UserConsentNavigator;
import org.openecard.gui.definition.Step;
import org.openecard.gui.definition.UserConsentDescription;
import org.openecard.gui.swing.common.GUIConstants;
/**
* Swing implementation of the UserConsent interface.
* The implementation encapsulates a DialogWrapper which is needed to supply a root pane for all draw operations.
*
* @author Tobias Wich
* @author Florian Feldmann
* @author Moritz Horsch
* @author Hans-Martin Haase
*/
public class SwingUserConsent implements UserConsent {
private final SwingDialogWrapper baseDialogWrapper;
/**
* Instantiate SwingUserConsent.
*
* @param dialogWrapper
*/
public SwingUserConsent(SwingDialogWrapper dialogWrapper) {
this.baseDialogWrapper = dialogWrapper;
}
@Override
public UserConsentNavigator obtainNavigator(UserConsentDescription parameters) {
SwingDialogWrapper dialogWrapper = baseDialogWrapper.derive();
dialogWrapper.setTitle(parameters.getTitle());
Container rootPanel = dialogWrapper.getContentPane();
rootPanel.removeAll();
boolean isPinEntryDialog = parameters.getDialogType().equals("pin_entry_dialog");
boolean isPinChangeDialog = parameters.getDialogType().equals("pin_change_dialog");
boolean isUpdateDialog = parameters.getDialogType().equals("update_dialog");
// set different size when special dialog type is requested
if (isPinEntryDialog) {
dialogWrapper.setSize(350, 284);
} else if (isPinChangeDialog) {
dialogWrapper.setSize(570, 430);
} else if (isUpdateDialog) {
dialogWrapper.setSize(480, 330);
}
String dialogType = parameters.getDialogType();
List<Step> steps = parameters.getSteps();
// Set up panels
JPanel stepPanel = new JPanel(new BorderLayout());
JPanel sideBar = new JPanel();
StepBar stepBar = new StepBar(steps);
final NavigationBar navBar = new NavigationBar(steps.size());
Logo l = new Logo();
initializeSidePanel(sideBar, l, stepBar);
final SwingNavigator navigator = new SwingNavigator(dialogWrapper, dialogType, steps, stepPanel, navBar, stepBar);
navBar.registerEvents(navigator);
navBar.setDefaultButton(dialogWrapper.getRootPane());
dialogWrapper.getDialog().addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent event) {
// The user has closed the window by pressing the x of the window manager handle this event as
// cancelation. This is necessary to unlock the app in case of a running authentication.
ActionEvent e = new ActionEvent(navBar, ActionEvent.ACTION_PERFORMED, GUIConstants.BUTTON_CANCEL);
navigator.actionPerformed(e);
}
});
// Config layout
GroupLayout layout = new GroupLayout(rootPanel);
rootPanel.setLayout(layout);
layout.setAutoCreateGaps(false);
layout.setAutoCreateContainerGaps(true);
if (isPinEntryDialog || isPinChangeDialog || isUpdateDialog) {
layout.setHorizontalGroup(
layout.createSequentialGroup()
.addGroup(layout.createParallelGroup()
.addComponent(stepPanel)
.addComponent(navBar)));
layout.setVerticalGroup(
layout.createParallelGroup(GroupLayout.Alignment.CENTER)
.addGroup(layout.createSequentialGroup()
.addComponent(stepPanel)
.addComponent(navBar)));
} else {
layout.setHorizontalGroup(
layout.createSequentialGroup()
.addComponent(sideBar, 200, 200, 200)
.addGroup(layout.createParallelGroup()
.addComponent(stepPanel)
.addComponent(navBar)));
layout.setVerticalGroup(
layout.createParallelGroup(GroupLayout.Alignment.CENTER)
.addComponent(sideBar)
.addGroup(layout.createSequentialGroup()
.addComponent(stepPanel)
.addComponent(navBar)));
}
rootPanel.validate();
rootPanel.repaint();
return navigator;
}
@Override
public FileDialog obtainFileDialog() {
return new SwingFileDialog();
}
@Override
public MessageDialog obtainMessageDialog() {
return new SwingMessageDialog();
}
private void initializeSidePanel(JPanel panel, JComponent... components) {
panel.setLayout(new BoxLayout(panel, BoxLayout.PAGE_AXIS));
for (JComponent c : components) {
c.setAlignmentX(Component.LEFT_ALIGNMENT);
panel.add(c);
}
}
}
| UTF-8 | Java | 5,655 | java | SwingUserConsent.java | Java | [
{
"context": ".\n * All rights reserved.\n * Contact: ecsec GmbH (info@ecsec.de)\n *\n * This file is part of the Open eCard App.\n ",
"end": 178,
"score": 0.9999100565910339,
"start": 165,
"tag": "EMAIL",
"value": "info@ecsec.de"
},
{
"context": "a root pane for all draw operations.\n *\n * @author Tobias Wich\n * @author Florian Feldmann\n * @author Moritz Hor",
"end": 1789,
"score": 0.9998630285263062,
"start": 1778,
"tag": "NAME",
"value": "Tobias Wich"
},
{
"context": "w operations.\n *\n * @author Tobias Wich\n * @author Florian Feldmann\n * @author Moritz Horsch\n * @author Hans-Martin H",
"end": 1817,
"score": 0.9998635649681091,
"start": 1801,
"tag": "NAME",
"value": "Florian Feldmann"
},
{
"context": "Tobias Wich\n * @author Florian Feldmann\n * @author Moritz Horsch\n * @author Hans-Martin Haase\n */\npublic class Swi",
"end": 1842,
"score": 0.9998413920402527,
"start": 1829,
"tag": "NAME",
"value": "Moritz Horsch"
},
{
"context": "orian Feldmann\n * @author Moritz Horsch\n * @author Hans-Martin Haase\n */\npublic class SwingUserConsent implements User",
"end": 1871,
"score": 0.9998603463172913,
"start": 1854,
"tag": "NAME",
"value": "Hans-Martin Haase"
}
]
| null | []
| /****************************************************************************
* Copyright (C) 2012-2018 ecsec GmbH.
* All rights reserved.
* Contact: ecsec GmbH (<EMAIL>)
*
* This file is part of the Open eCard App.
*
* GNU General Public License Usage
* This file may be used under the terms of the GNU General Public
* License version 3.0 as published by the Free Software Foundation
* and appearing in the file LICENSE.GPL included in the packaging of
* this file. Please review the following information to ensure the
* GNU General Public License version 3.0 requirements will be met:
* http://www.gnu.org/copyleft/gpl.html.
*
* Other Usage
* Alternatively, this file may be used in accordance with the terms
* and conditions contained in a signed written agreement between
* you and ecsec GmbH.
*
***************************************************************************/
package org.openecard.gui.swing;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.List;
import javax.swing.BoxLayout;
import javax.swing.GroupLayout;
import javax.swing.JComponent;
import javax.swing.JPanel;
import org.openecard.gui.FileDialog;
import org.openecard.gui.MessageDialog;
import org.openecard.gui.UserConsent;
import org.openecard.gui.UserConsentNavigator;
import org.openecard.gui.definition.Step;
import org.openecard.gui.definition.UserConsentDescription;
import org.openecard.gui.swing.common.GUIConstants;
/**
* Swing implementation of the UserConsent interface.
* The implementation encapsulates a DialogWrapper which is needed to supply a root pane for all draw operations.
*
* @author <NAME>
* @author <NAME>
* @author <NAME>
* @author <NAME>
*/
public class SwingUserConsent implements UserConsent {
private final SwingDialogWrapper baseDialogWrapper;
/**
* Instantiate SwingUserConsent.
*
* @param dialogWrapper
*/
public SwingUserConsent(SwingDialogWrapper dialogWrapper) {
this.baseDialogWrapper = dialogWrapper;
}
@Override
public UserConsentNavigator obtainNavigator(UserConsentDescription parameters) {
SwingDialogWrapper dialogWrapper = baseDialogWrapper.derive();
dialogWrapper.setTitle(parameters.getTitle());
Container rootPanel = dialogWrapper.getContentPane();
rootPanel.removeAll();
boolean isPinEntryDialog = parameters.getDialogType().equals("pin_entry_dialog");
boolean isPinChangeDialog = parameters.getDialogType().equals("pin_change_dialog");
boolean isUpdateDialog = parameters.getDialogType().equals("update_dialog");
// set different size when special dialog type is requested
if (isPinEntryDialog) {
dialogWrapper.setSize(350, 284);
} else if (isPinChangeDialog) {
dialogWrapper.setSize(570, 430);
} else if (isUpdateDialog) {
dialogWrapper.setSize(480, 330);
}
String dialogType = parameters.getDialogType();
List<Step> steps = parameters.getSteps();
// Set up panels
JPanel stepPanel = new JPanel(new BorderLayout());
JPanel sideBar = new JPanel();
StepBar stepBar = new StepBar(steps);
final NavigationBar navBar = new NavigationBar(steps.size());
Logo l = new Logo();
initializeSidePanel(sideBar, l, stepBar);
final SwingNavigator navigator = new SwingNavigator(dialogWrapper, dialogType, steps, stepPanel, navBar, stepBar);
navBar.registerEvents(navigator);
navBar.setDefaultButton(dialogWrapper.getRootPane());
dialogWrapper.getDialog().addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent event) {
// The user has closed the window by pressing the x of the window manager handle this event as
// cancelation. This is necessary to unlock the app in case of a running authentication.
ActionEvent e = new ActionEvent(navBar, ActionEvent.ACTION_PERFORMED, GUIConstants.BUTTON_CANCEL);
navigator.actionPerformed(e);
}
});
// Config layout
GroupLayout layout = new GroupLayout(rootPanel);
rootPanel.setLayout(layout);
layout.setAutoCreateGaps(false);
layout.setAutoCreateContainerGaps(true);
if (isPinEntryDialog || isPinChangeDialog || isUpdateDialog) {
layout.setHorizontalGroup(
layout.createSequentialGroup()
.addGroup(layout.createParallelGroup()
.addComponent(stepPanel)
.addComponent(navBar)));
layout.setVerticalGroup(
layout.createParallelGroup(GroupLayout.Alignment.CENTER)
.addGroup(layout.createSequentialGroup()
.addComponent(stepPanel)
.addComponent(navBar)));
} else {
layout.setHorizontalGroup(
layout.createSequentialGroup()
.addComponent(sideBar, 200, 200, 200)
.addGroup(layout.createParallelGroup()
.addComponent(stepPanel)
.addComponent(navBar)));
layout.setVerticalGroup(
layout.createParallelGroup(GroupLayout.Alignment.CENTER)
.addComponent(sideBar)
.addGroup(layout.createSequentialGroup()
.addComponent(stepPanel)
.addComponent(navBar)));
}
rootPanel.validate();
rootPanel.repaint();
return navigator;
}
@Override
public FileDialog obtainFileDialog() {
return new SwingFileDialog();
}
@Override
public MessageDialog obtainMessageDialog() {
return new SwingMessageDialog();
}
private void initializeSidePanel(JPanel panel, JComponent... components) {
panel.setLayout(new BoxLayout(panel, BoxLayout.PAGE_AXIS));
for (JComponent c : components) {
c.setAlignmentX(Component.LEFT_ALIGNMENT);
panel.add(c);
}
}
}
| 5,616 | 0.729089 | 0.722193 | 172 | 31.877907 | 25.587564 | 115 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.104651 | false | false | 13 |
c06a72fa3737dbcc52bfba6bdb83a76147d39316 | 33,612,414,111,613 | cb3b4a5a2a2de3c6710cfcbd673d4d3c10b82594 | /app/src/main/java/kc/ac/kpu/gojourney/MapsActivity.java | 96fd9cda9a2600e0745f7cd4c92c34a71ea227aa | []
| no_license | HyunbinKang/Myjourney | https://github.com/HyunbinKang/Myjourney | 97b4d21bde3ad222953a419a89502996df8f44ba | 7ae60bb94aed401e69df66ab60d9609ed74d2e91 | refs/heads/master | 2021-04-20T14:14:05.181000 | 2020-07-13T07:05:00 | 2020-07-13T07:05:00 | 249,690,948 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package kc.ac.kpu.gojourney;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.FragmentActivity;
import androidx.appcompat.app.AlertDialog;
import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.Build;
import android.os.Bundle;
import android.os.Looper;
import android.widget.Button;
import android.widget.Toast;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationCallback;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationResult;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import java.util.List;
public class MapsActivity extends FragmentActivity implements
GoogleMap.OnMarkerClickListener,
OnMapReadyCallback {
private static final LatLng VIETNAM = new LatLng(16.0473223,108.1364922);
private static final LatLng PHILIPPINES = new LatLng(11.576464,113.5272617);
private static final LatLng TAIWAN = new LatLng(23.4309016,115.5711233);
private static final LatLng THAILAND = new LatLng(13.2169073, 91.9971356);
private static final LatLng CHINA = new LatLng(31.2243023,120.9148227);
private static final LatLng JAPAN = new LatLng(34.7628282,135.2077892);
private static final LatLng CANADA = new LatLng(48.7466171,-129.6697819);
private Marker mVietnam;
private Marker mPhilippines;
private Marker mTaiwan;
private Marker mThailand;
private Marker mChina;
private Marker mJapan;
private Marker mCanada;
private GoogleMap mMap;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
//setContentView(R.layout.marker_demo);
SupportMapFragment mapFragment =
(SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
/**
* Called when the map is ready.
*/
@Override
public void onMapReady(GoogleMap map) {
mMap = map;
// Add some markers to the map, and add a data object to each marker.
mVietnam = mMap.addMarker(new MarkerOptions()
.position(VIETNAM)
.title("VIETNAM"));
mVietnam.setTag(0);
mPhilippines = mMap.addMarker(new MarkerOptions()
.position(PHILIPPINES)
.title("PHILIPPINES"));
mPhilippines.setTag(0);
mTaiwan = mMap.addMarker(new MarkerOptions()
.position(TAIWAN)
.title("TAIWAN"));
mTaiwan.setTag(0);
mThailand = mMap.addMarker(new MarkerOptions()
.position(THAILAND)
.title("THAILAND")
.snippet("dddd"));
mThailand.setTag(0);
mChina = mMap.addMarker(new MarkerOptions()
.position(CHINA)
.title("CHINA")
.snippet("dddd"));
mChina.setTag(0);
mJapan = mMap.addMarker(new MarkerOptions()
.position(JAPAN)
.title("JAPAN")
.snippet("dddd"));
mJapan.setTag(0);
mCanada = mMap.addMarker(new MarkerOptions()
.position(CANADA)
.title("CANADA")
.snippet("dddd"));
mCanada.setTag(0);
// Set a listener for marker click.
mMap.setOnMarkerClickListener(this);
}
/**
* Called when the user clicks a marker.
*/
@Override
public boolean onMarkerClick(final Marker marker) {
// Retrieve the data from the marker.
Integer clickCount = (Integer) marker.getTag();
// Check if a click count was set, then display the click count.
if (clickCount != null) {
clickCount = clickCount + 1;
marker.setTag(clickCount);
Toast.makeText(this,
marker.getTitle() +
" โฅ " + clickCount + " times.",
Toast.LENGTH_SHORT).show();
}
// Return false to indicate that we have not consumed the event and that we wish
// for the default behavior to occur (which is for the camera to move such that the
// marker is centered and for the marker's info window to open, if it has one).
return false;
}
}
/*
public class MapsActivity extends AppCompatActivity implements OnMapReadyCallback {
private GoogleMap mMap;
SupportMapFragment mapFrag;
LocationRequest mLocationRequest;
Location mLastLocation;
Marker mCurrLocationMarker;
FusedLocationProviderClient mFusedLocationClient;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
getSupportActionBar().setTitle("MAPPPPP");
mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
mapFrag = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFrag.getMapAsync(this);
//google map์ด ์ค๋น๊ฐ ๋๋ค
}
/**
* Manipulates the map once available.
* This callback is triggered when the map is ready to be used.
* This is where we can add markers or lines, add listeners or move the camera. In this case,
* we just add a marker near Sydney, Australia.
* If Google Play services is not installed on the device, the user will be prompted to install
* it inside the SupportMapFragment. This method will only be triggered once the user has
* installed Google Play services and returned to the app.
*/
/*
@Override
public void onPause() {
super.onPause();
//stop location updates when Activity is no longer active
if (mFusedLocationClient != null) {
mFusedLocationClient.removeLocationUpdates(mLocationCallback);
}
}
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(120000); // two minute interval
mLocationRequest.setFastestInterval(120000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
// Add a marker in Sydney and move the camera
// ์๋ ๊ฒฝ๋ ํํํ๋ ๊ฐ์ฒด
//LatLng murcia = new LatLng(37.9922399, -1.1306544);
//mMap.addMarker(new MarkerOptions().position(murcia).title("๋ฌด๋ฅด์์๋คํํ"));
//mMap.moveCamera(CameraUpdateFactory.newLatLng(murcia));
//mMap.animateCamera(CameraUpdateFactory.zoomTo(17.0f));
//mMap.setOnInfoWindowClickListener(new GoogleMap.OnInfoWindowClickListener() {
// @Override
// public void onInfoWindowClick(Marker marker) {
// Intent intent = new Intent(MapsActivity.this, MurciaActivity.class);
// startActivity(intent);
// finish();}
// }
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
//Location Permission already granted
mFusedLocationClient.requestLocationUpdates(mLocationRequest, mLocationCallback,
Looper.myLooper());
mMap.setMyLocationEnabled(true);
} else {
//Request Location Permission
checkLocationPermission();
}
} else {
mFusedLocationClient.requestLocationUpdates(mLocationRequest, mLocationCallback,
Looper.myLooper());
mMap.setMyLocationEnabled(true);
}
}
LocationCallback mLocationCallback = new LocationCallback() {
@Override
public void onLocationResult(LocationResult locationResult) {
List<Location> locationList = locationResult.getLocations();
if (locationList.size() > 0) {
//The last location in the list is the newest
Location location = locationList.get(locationList.size() - 1);
mLastLocation = location;
if (mCurrLocationMarker != null) {
mCurrLocationMarker.remove();
}
//move map camera
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
CameraPosition cameraPosition = new CameraPosition.Builder().target(new LatLng(latLng.latitude, latLng.longitude)).zoom(16).build();
mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
}
}
};
public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
private void checkLocationPermission() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
// Should we show an explanation?
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.ACCESS_FINE_LOCATION)) {
// Show an explanation to the user *asynchronously* -- don't block
// this thread waiting for the user's response! After the user
// sees the explanation, try again to request the permission.
new AlertDialog.Builder(this)
.setTitle("Location Permission Needed")
.setMessage("This app needs the Location permission, please accept to use location functionality")
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
//Prompt the user once explanation has been shown
ActivityCompat.requestPermissions(MapsActivity.this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION );
}
})
.create()
.show();
} else {
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION );
}
}
}
@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_LOCATION: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission was granted, yay! Do the
// location-related task you need to do.
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
mFusedLocationClient.requestLocationUpdates(mLocationRequest,
mLocationCallback, Looper.myLooper());
mMap.setMyLocationEnabled(true);
}
} else {
// if not allow a permission, the application will exit
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
finish();
System.exit(0);
}
}
}
}
}
*/
| UTF-8 | Java | 13,034 | java | MapsActivity.java | Java | []
| null | []
| package kc.ac.kpu.gojourney;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.FragmentActivity;
import androidx.appcompat.app.AlertDialog;
import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.Build;
import android.os.Bundle;
import android.os.Looper;
import android.widget.Button;
import android.widget.Toast;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationCallback;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationResult;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import java.util.List;
public class MapsActivity extends FragmentActivity implements
GoogleMap.OnMarkerClickListener,
OnMapReadyCallback {
private static final LatLng VIETNAM = new LatLng(16.0473223,108.1364922);
private static final LatLng PHILIPPINES = new LatLng(11.576464,113.5272617);
private static final LatLng TAIWAN = new LatLng(23.4309016,115.5711233);
private static final LatLng THAILAND = new LatLng(13.2169073, 91.9971356);
private static final LatLng CHINA = new LatLng(31.2243023,120.9148227);
private static final LatLng JAPAN = new LatLng(34.7628282,135.2077892);
private static final LatLng CANADA = new LatLng(48.7466171,-129.6697819);
private Marker mVietnam;
private Marker mPhilippines;
private Marker mTaiwan;
private Marker mThailand;
private Marker mChina;
private Marker mJapan;
private Marker mCanada;
private GoogleMap mMap;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
//setContentView(R.layout.marker_demo);
SupportMapFragment mapFragment =
(SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
/**
* Called when the map is ready.
*/
@Override
public void onMapReady(GoogleMap map) {
mMap = map;
// Add some markers to the map, and add a data object to each marker.
mVietnam = mMap.addMarker(new MarkerOptions()
.position(VIETNAM)
.title("VIETNAM"));
mVietnam.setTag(0);
mPhilippines = mMap.addMarker(new MarkerOptions()
.position(PHILIPPINES)
.title("PHILIPPINES"));
mPhilippines.setTag(0);
mTaiwan = mMap.addMarker(new MarkerOptions()
.position(TAIWAN)
.title("TAIWAN"));
mTaiwan.setTag(0);
mThailand = mMap.addMarker(new MarkerOptions()
.position(THAILAND)
.title("THAILAND")
.snippet("dddd"));
mThailand.setTag(0);
mChina = mMap.addMarker(new MarkerOptions()
.position(CHINA)
.title("CHINA")
.snippet("dddd"));
mChina.setTag(0);
mJapan = mMap.addMarker(new MarkerOptions()
.position(JAPAN)
.title("JAPAN")
.snippet("dddd"));
mJapan.setTag(0);
mCanada = mMap.addMarker(new MarkerOptions()
.position(CANADA)
.title("CANADA")
.snippet("dddd"));
mCanada.setTag(0);
// Set a listener for marker click.
mMap.setOnMarkerClickListener(this);
}
/**
* Called when the user clicks a marker.
*/
@Override
public boolean onMarkerClick(final Marker marker) {
// Retrieve the data from the marker.
Integer clickCount = (Integer) marker.getTag();
// Check if a click count was set, then display the click count.
if (clickCount != null) {
clickCount = clickCount + 1;
marker.setTag(clickCount);
Toast.makeText(this,
marker.getTitle() +
" โฅ " + clickCount + " times.",
Toast.LENGTH_SHORT).show();
}
// Return false to indicate that we have not consumed the event and that we wish
// for the default behavior to occur (which is for the camera to move such that the
// marker is centered and for the marker's info window to open, if it has one).
return false;
}
}
/*
public class MapsActivity extends AppCompatActivity implements OnMapReadyCallback {
private GoogleMap mMap;
SupportMapFragment mapFrag;
LocationRequest mLocationRequest;
Location mLastLocation;
Marker mCurrLocationMarker;
FusedLocationProviderClient mFusedLocationClient;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
getSupportActionBar().setTitle("MAPPPPP");
mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
mapFrag = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFrag.getMapAsync(this);
//google map์ด ์ค๋น๊ฐ ๋๋ค
}
/**
* Manipulates the map once available.
* This callback is triggered when the map is ready to be used.
* This is where we can add markers or lines, add listeners or move the camera. In this case,
* we just add a marker near Sydney, Australia.
* If Google Play services is not installed on the device, the user will be prompted to install
* it inside the SupportMapFragment. This method will only be triggered once the user has
* installed Google Play services and returned to the app.
*/
/*
@Override
public void onPause() {
super.onPause();
//stop location updates when Activity is no longer active
if (mFusedLocationClient != null) {
mFusedLocationClient.removeLocationUpdates(mLocationCallback);
}
}
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(120000); // two minute interval
mLocationRequest.setFastestInterval(120000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
// Add a marker in Sydney and move the camera
// ์๋ ๊ฒฝ๋ ํํํ๋ ๊ฐ์ฒด
//LatLng murcia = new LatLng(37.9922399, -1.1306544);
//mMap.addMarker(new MarkerOptions().position(murcia).title("๋ฌด๋ฅด์์๋คํํ"));
//mMap.moveCamera(CameraUpdateFactory.newLatLng(murcia));
//mMap.animateCamera(CameraUpdateFactory.zoomTo(17.0f));
//mMap.setOnInfoWindowClickListener(new GoogleMap.OnInfoWindowClickListener() {
// @Override
// public void onInfoWindowClick(Marker marker) {
// Intent intent = new Intent(MapsActivity.this, MurciaActivity.class);
// startActivity(intent);
// finish();}
// }
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
//Location Permission already granted
mFusedLocationClient.requestLocationUpdates(mLocationRequest, mLocationCallback,
Looper.myLooper());
mMap.setMyLocationEnabled(true);
} else {
//Request Location Permission
checkLocationPermission();
}
} else {
mFusedLocationClient.requestLocationUpdates(mLocationRequest, mLocationCallback,
Looper.myLooper());
mMap.setMyLocationEnabled(true);
}
}
LocationCallback mLocationCallback = new LocationCallback() {
@Override
public void onLocationResult(LocationResult locationResult) {
List<Location> locationList = locationResult.getLocations();
if (locationList.size() > 0) {
//The last location in the list is the newest
Location location = locationList.get(locationList.size() - 1);
mLastLocation = location;
if (mCurrLocationMarker != null) {
mCurrLocationMarker.remove();
}
//move map camera
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
CameraPosition cameraPosition = new CameraPosition.Builder().target(new LatLng(latLng.latitude, latLng.longitude)).zoom(16).build();
mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
}
}
};
public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
private void checkLocationPermission() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
// Should we show an explanation?
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.ACCESS_FINE_LOCATION)) {
// Show an explanation to the user *asynchronously* -- don't block
// this thread waiting for the user's response! After the user
// sees the explanation, try again to request the permission.
new AlertDialog.Builder(this)
.setTitle("Location Permission Needed")
.setMessage("This app needs the Location permission, please accept to use location functionality")
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
//Prompt the user once explanation has been shown
ActivityCompat.requestPermissions(MapsActivity.this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION );
}
})
.create()
.show();
} else {
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION );
}
}
}
@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_LOCATION: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission was granted, yay! Do the
// location-related task you need to do.
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
mFusedLocationClient.requestLocationUpdates(mLocationRequest,
mLocationCallback, Looper.myLooper());
mMap.setMyLocationEnabled(true);
}
} else {
// if not allow a permission, the application will exit
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
finish();
System.exit(0);
}
}
}
}
}
*/
| 13,034 | 0.619898 | 0.606037 | 338 | 37.42012 | 28.962551 | 148 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.497041 | false | false | 13 |
5749e22e494c951d4cdb2fb964b36d962eb95533 | 16,956,530,953,145 | f0840b194279ad7bb89df0c667719d117650ea45 | /ZXAPI/src/com/hengtian/zxjk/MessageInfo.java | 8782082d3b233820811f994ad3a4b025b55f3e9f | []
| no_license | swinepig/JAVA | https://github.com/swinepig/JAVA | 63c81feb13b1e3490b60d23027c31314c7988791 | bfd8b7491016cefca0b3f3fe2faf98ed0aca3334 | refs/heads/master | 2021-01-10T20:57:17.946000 | 2014-07-30T10:13:33 | 2014-07-30T10:13:33 | 10,054,028 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.hengtian.zxjk;
import java.util.List;
public class MessageInfo {
private String messageNameStr;
private String messageHeadStr;
private List<String> messageBodyStr;
public MessageInfo(String name, String head, List<String> body) {
messageNameStr = name;
messageHeadStr = head;
messageBodyStr = body;
}
public String getMessageNameStr() {
return messageNameStr;
}
public void setMessageNameStr(String messageNameStr) {
this.messageNameStr = messageNameStr;
}
public String getMessageHeadStr() {
return messageHeadStr;
}
public void setMessageHeadStr(String messageHeadStr) {
this.messageHeadStr = messageHeadStr;
}
public List<String> getMessageBodyStr() {
return messageBodyStr;
}
public void setMessageBodyStr(List<String> messageBodyStr) {
this.messageBodyStr = messageBodyStr;
}
}
| UTF-8 | Java | 841 | java | MessageInfo.java | Java | []
| null | []
| package com.hengtian.zxjk;
import java.util.List;
public class MessageInfo {
private String messageNameStr;
private String messageHeadStr;
private List<String> messageBodyStr;
public MessageInfo(String name, String head, List<String> body) {
messageNameStr = name;
messageHeadStr = head;
messageBodyStr = body;
}
public String getMessageNameStr() {
return messageNameStr;
}
public void setMessageNameStr(String messageNameStr) {
this.messageNameStr = messageNameStr;
}
public String getMessageHeadStr() {
return messageHeadStr;
}
public void setMessageHeadStr(String messageHeadStr) {
this.messageHeadStr = messageHeadStr;
}
public List<String> getMessageBodyStr() {
return messageBodyStr;
}
public void setMessageBodyStr(List<String> messageBodyStr) {
this.messageBodyStr = messageBodyStr;
}
}
| 841 | 0.765755 | 0.765755 | 41 | 19.512196 | 19.784351 | 66 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.243902 | false | false | 13 |
9d072936b6af01f7f3aff9d044a140e8c6a68a1b | 21,457,656,666,839 | 38d390be1a31728cace9d43c59bc3e45d018e815 | /NMvvm/nmvvm/src/main/java/com/ducdm/nmvvm/agents/INMvxHostablePresenter.java | 8eacfc24cbca610052177b849cfa83cf05123c73 | []
| no_license | ManhDucIT/NMVVM | https://github.com/ManhDucIT/NMVVM | 94dfaa4fbd04146fcdb97954c1c35893c2521b41 | b15cbf7ad2c4d6f21e70c7300efa17a581f14d61 | refs/heads/master | 2020-04-24T10:03:20.739000 | 2019-02-21T13:55:34 | 2019-02-21T13:55:34 | 171,880,621 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.ducdm.nmvvm.agents;
import com.ducdm.nmvvm.viewmodels.NMvxViewModel;
import com.ducdm.nmvvm.views.INMvxHostableView;
import com.ducdm.nmvvm.views.INMvxView;
/**
* Created by DucDM7 on 1/12/2017.
*/
public interface INMvxHostablePresenter {
void registerChild(Class<? extends NMvxViewModel> viewModelType, INMvxHostableView hostableView);
void registerContainer(int containerResId);
}
| UTF-8 | Java | 427 | java | INMvxHostablePresenter.java | Java | [
{
"context": "ducdm.nmvvm.views.INMvxView;\r\n\r\n/**\r\n * Created by DucDM7 on 1/12/2017.\r\n */\r\n\r\npublic interface INMvxHosta",
"end": 202,
"score": 0.9995932579040527,
"start": 196,
"tag": "USERNAME",
"value": "DucDM7"
}
]
| null | []
| package com.ducdm.nmvvm.agents;
import com.ducdm.nmvvm.viewmodels.NMvxViewModel;
import com.ducdm.nmvvm.views.INMvxHostableView;
import com.ducdm.nmvvm.views.INMvxView;
/**
* Created by DucDM7 on 1/12/2017.
*/
public interface INMvxHostablePresenter {
void registerChild(Class<? extends NMvxViewModel> viewModelType, INMvxHostableView hostableView);
void registerContainer(int containerResId);
}
| 427 | 0.761124 | 0.742389 | 16 | 24.6875 | 27.961399 | 101 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.4375 | false | false | 13 |
d0dcdd509ed12c650f53adcbd2cfb77c977ee0ee | 27,444,841,084,163 | 982830b7bd4d8b22a19451bdfdeea68409a673a5 | /03-ThreadCommunicate/src/chapter01/demo3_1_11/_2/PThread.java | f9cc2ec86ec40ccd9a33bdfe0c80728d43873da4 | []
| no_license | obsoletse/Thread | https://github.com/obsoletse/Thread | 0920379947eabe5756614bf94a8074d6e0d6d303 | 9dcaf0b79b3a54d1b4551a8b7fa71fe6d238aae9 | refs/heads/master | 2020-09-15T04:11:12.953000 | 2019-12-23T03:43:25 | 2019-12-23T03:43:25 | 223,334,061 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package chapter01.demo3_1_11._2;
/**
* @ClassName PThread
* @Author LinBin
* @Date 2019/12/5 11:13
* @Description :
*/
public class PThread extends Thread {
private P p;
public PThread(P p){
super();
this.p = p;
}
@Override
public void run() {
while (true){
p.setValue();
}
}
}
| UTF-8 | Java | 353 | java | PThread.java | Java | [
{
"context": "mo3_1_11._2;\n\n/**\n * @ClassName PThread\n * @Author LinBin\n * @Date 2019/12/5 11:13\n * @Description :\n */\npu",
"end": 77,
"score": 0.9979974031448364,
"start": 71,
"tag": "NAME",
"value": "LinBin"
}
]
| null | []
| package chapter01.demo3_1_11._2;
/**
* @ClassName PThread
* @Author LinBin
* @Date 2019/12/5 11:13
* @Description :
*/
public class PThread extends Thread {
private P p;
public PThread(P p){
super();
this.p = p;
}
@Override
public void run() {
while (true){
p.setValue();
}
}
}
| 353 | 0.521246 | 0.470255 | 22 | 15.045455 | 10.381265 | 37 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.227273 | false | false | 13 |
081b39a6eeabb4cdbe85fb4d71394fb914ee39f1 | 24,180,665,876,930 | 631cd92fea2d05b8af911bc1fb68e51918ba81ba | /AuthManage/src/com/vo/UserGroup.java | be4347f95837d132ba71abe8c59baa5a868d5d7e | []
| no_license | ph96/AuthManage | https://github.com/ph96/AuthManage | 4793932cfb5c45eb3877c74f5c8a3c4bb6591527 | cd79f32f66745bc249e33538fbe097b15db21c47 | refs/heads/master | 2020-06-23T10:28:02.452000 | 2019-08-06T07:24:23 | 2019-08-06T07:24:23 | 198,596,784 | 2 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.vo;
//็จๆท็ป่กจ
public class UserGroup {
//็จๆท็ปid
private Integer groupId;
//็จๆท็ปๅ็งฐ
private String groupName;
//็จๆท็ปcode(็ )
private String groupCode;
//็จๆท็ปๆ่ฟฐ
private String groupDesc;
//็จๆท็ปๆ่ฟฐ
private String groupState;
public UserGroup() {}
public UserGroup(Integer groupId, String groupName, String groupCode, String groupDesc, String groupState) {
this.groupId = groupId;
this.groupName = groupName;
this.groupCode = groupCode;
this.groupDesc = groupDesc;
this.groupState = groupState;
}
public Integer getGroupId() {
return groupId;
}
public void setGroupId(Integer groupId) {
this.groupId = groupId;
}
public String getGroupName() {
return groupName;
}
public void setGroupName(String groupName) {
this.groupName = groupName == null ? null : groupName.trim();
}
public String getGroupCode() {
return groupCode;
}
public void setGroupCode(String groupCode) {
this.groupCode = groupCode == null ? null : groupCode.trim();
}
public String getGroupDesc() {
return groupDesc;
}
public void setGroupDesc(String groupDesc) {
this.groupDesc = groupDesc == null ? null : groupDesc.trim();
}
public String getGroupState() {
return groupState;
}
public void setGroupState(String groupState) {
this.groupState = groupState == null ? null : groupState.trim();
}
@Override
public String toString() {
return "UserGroup [groupId=" + groupId + ", groupName=" + groupName + ", groupCode=" + groupCode
+ ", groupDesc=" + groupDesc + ", groupState=" + groupState + "]";
}
} | UTF-8 | Java | 1,751 | java | UserGroup.java | Java | []
| null | []
| package com.vo;
//็จๆท็ป่กจ
public class UserGroup {
//็จๆท็ปid
private Integer groupId;
//็จๆท็ปๅ็งฐ
private String groupName;
//็จๆท็ปcode(็ )
private String groupCode;
//็จๆท็ปๆ่ฟฐ
private String groupDesc;
//็จๆท็ปๆ่ฟฐ
private String groupState;
public UserGroup() {}
public UserGroup(Integer groupId, String groupName, String groupCode, String groupDesc, String groupState) {
this.groupId = groupId;
this.groupName = groupName;
this.groupCode = groupCode;
this.groupDesc = groupDesc;
this.groupState = groupState;
}
public Integer getGroupId() {
return groupId;
}
public void setGroupId(Integer groupId) {
this.groupId = groupId;
}
public String getGroupName() {
return groupName;
}
public void setGroupName(String groupName) {
this.groupName = groupName == null ? null : groupName.trim();
}
public String getGroupCode() {
return groupCode;
}
public void setGroupCode(String groupCode) {
this.groupCode = groupCode == null ? null : groupCode.trim();
}
public String getGroupDesc() {
return groupDesc;
}
public void setGroupDesc(String groupDesc) {
this.groupDesc = groupDesc == null ? null : groupDesc.trim();
}
public String getGroupState() {
return groupState;
}
public void setGroupState(String groupState) {
this.groupState = groupState == null ? null : groupState.trim();
}
@Override
public String toString() {
return "UserGroup [groupId=" + groupId + ", groupName=" + groupName + ", groupCode=" + groupCode
+ ", groupDesc=" + groupDesc + ", groupState=" + groupState + "]";
}
} | 1,751 | 0.640965 | 0.640965 | 72 | 22.611111 | 24.059277 | 109 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.736111 | false | false | 13 |
d475af4bdc0cf893ac1617c96df3fd2e5ffd190f | 27,865,747,852,601 | 992b1744c50b5906ea7beda05367dd76aeea4c0b | /app/src/main/java/com/eddy/androidstudy/volley/VolleyTestActivity.java | 3743cba2342e99e602814928ffeb4f5710a55add | []
| no_license | limingxiao117/AndroidStudy | https://github.com/limingxiao117/AndroidStudy | 79156ec2538c60775b83b2b9f45c46925e4bd6e9 | ff841931c5317ba7678b90a19d0672dcb3e6cd15 | refs/heads/master | 2020-03-10T01:16:20.998000 | 2018-06-01T09:03:43 | 2018-06-01T09:03:43 | 129,105,285 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.eddy.androidstudy.volley;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.eddy.androidstudy.App;
import com.eddy.androidstudy.R;
import com.eddy.base.Logger;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
/**
* ๅๅปบ ๏ผeddyli@zmodo.com
* ๆถ้ด ๏ผ16:25 on 2018/4/23.
* ๆ่ฟฐ ๏ผ//TODO ๆ่ฟฐๆฌๆไปถ็ๅ่ฝ
* ไฟฎๆน ๏ผ//TODO ๆฏๆฌกไฟฎๆน็ๆถๅๆ่ฟฐไฟฎๆน็ๅฐๆนๆๆ่ฆ็น
*/
public class VolleyTestActivity extends AppCompatActivity implements View.OnClickListener {
private static RequestQueue requestQueue = Volley.newRequestQueue(App.getInstance().getApplicationContext());
private TextView mTvContent;
private Button mBtnVolley;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_volley);
mTvContent = findViewById(R.id.txt_content);
mBtnVolley = findViewById(R.id.btn_test_volley);
mBtnVolley.setOnClickListener(this);
}
@Override
public void onClick(View v) {
if (v.getId() == R.id.btn_test_volley) {
request();
}
}
private void request() {
String url = "https://13-appaccess.myzmodo.com/meshare/user/usrlogin";
StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Logger.d(response.toString());
mTvContent.setText(response.toString());
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Logger.d(error.toString());
mTvContent.setText(error.toString());
}
}) {
@Override
protected Map<String, String> getParams() {
Map<String, String> map = new HashMap<>();
map.put("username", "eddyli@zmodo.com");
map.put("password", "e10adc3949ba59abbe56e057f20f883e");
map.put("clienttype", "0");
map.put("language", "en");
map.put("platform", "1");
map.put("offset_second", "0");
map.put("app_version", "3.3");
JSONObject mobileInfo = new JSONObject();
try {
mobileInfo.put("version_code", 342);
mobileInfo.put("version_name", "4.0.1.00117");
mobileInfo.put("MODEL", "PREVIEW - Google Pixel - 8.0 - API 26 - 1080x1920");
mobileInfo.put("SYS_SDK", 26);
mobileInfo.put("SYS_RELEASE", "8.0.0");
} catch (JSONException e) {
e.printStackTrace();
}
map.put("app_info", mobileInfo.toString());
return map;
}
};
requestQueue.add(stringRequest);
}
}
| UTF-8 | Java | 3,418 | java | VolleyTestActivity.java | Java | [
{
"context": "a.util.HashMap;\nimport java.util.Map;\n\n/**\n * ๅๅปบ ๏ผeddyli@zmodo.com\n * ๆถ้ด ๏ผ16:25 on 2018/4/23.\n * ๆ่ฟฐ ๏ผ//TODO ๆ่ฟฐๆฌๆไปถ็ๅ่ฝ",
"end": 676,
"score": 0.9999268651008606,
"start": 660,
"tag": "EMAIL",
"value": "eddyli@zmodo.com"
},
{
"context": "HashMap<>();\n map.put(\"username\", \"eddyli@zmodo.com\");\n map.put(\"password\", \"e10adc394",
"end": 2364,
"score": 0.9945535659790039,
"start": 2348,
"tag": "EMAIL",
"value": "eddyli@zmodo.com"
},
{
"context": "zmodo.com\");\n map.put(\"password\", \"e10adc3949ba59abbe56e057f20f883e\");\n map.put(\"clienttype\", \"0\");\n ",
"end": 2437,
"score": 0.9994518756866455,
"start": 2405,
"tag": "PASSWORD",
"value": "e10adc3949ba59abbe56e057f20f883e"
}
]
| null | []
| package com.eddy.androidstudy.volley;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.eddy.androidstudy.App;
import com.eddy.androidstudy.R;
import com.eddy.base.Logger;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
/**
* ๅๅปบ ๏ผ<EMAIL>
* ๆถ้ด ๏ผ16:25 on 2018/4/23.
* ๆ่ฟฐ ๏ผ//TODO ๆ่ฟฐๆฌๆไปถ็ๅ่ฝ
* ไฟฎๆน ๏ผ//TODO ๆฏๆฌกไฟฎๆน็ๆถๅๆ่ฟฐไฟฎๆน็ๅฐๆนๆๆ่ฆ็น
*/
public class VolleyTestActivity extends AppCompatActivity implements View.OnClickListener {
private static RequestQueue requestQueue = Volley.newRequestQueue(App.getInstance().getApplicationContext());
private TextView mTvContent;
private Button mBtnVolley;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_volley);
mTvContent = findViewById(R.id.txt_content);
mBtnVolley = findViewById(R.id.btn_test_volley);
mBtnVolley.setOnClickListener(this);
}
@Override
public void onClick(View v) {
if (v.getId() == R.id.btn_test_volley) {
request();
}
}
private void request() {
String url = "https://13-appaccess.myzmodo.com/meshare/user/usrlogin";
StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Logger.d(response.toString());
mTvContent.setText(response.toString());
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Logger.d(error.toString());
mTvContent.setText(error.toString());
}
}) {
@Override
protected Map<String, String> getParams() {
Map<String, String> map = new HashMap<>();
map.put("username", "<EMAIL>");
map.put("password", "<PASSWORD>");
map.put("clienttype", "0");
map.put("language", "en");
map.put("platform", "1");
map.put("offset_second", "0");
map.put("app_version", "3.3");
JSONObject mobileInfo = new JSONObject();
try {
mobileInfo.put("version_code", 342);
mobileInfo.put("version_name", "4.0.1.00117");
mobileInfo.put("MODEL", "PREVIEW - Google Pixel - 8.0 - API 26 - 1080x1920");
mobileInfo.put("SYS_SDK", 26);
mobileInfo.put("SYS_RELEASE", "8.0.0");
} catch (JSONException e) {
e.printStackTrace();
}
map.put("app_info", mobileInfo.toString());
return map;
}
};
requestQueue.add(stringRequest);
}
}
| 3,378 | 0.603531 | 0.584081 | 98 | 33.102039 | 24.761511 | 115 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.714286 | false | false | 13 |
9e9bba63399ecfdb41e7649d9a630602e5014852 | 22,600,117,970,329 | 95574936f80e6a8235546556e9d8c90b5dc9d4d1 | /src/game/area/Room.java | e9f64d75b6d171fc47893cd865897fbaff0bb873 | []
| no_license | WaruiAkushi/Video-Game | https://github.com/WaruiAkushi/Video-Game | 826f7ba84b024885414116151a8fc0ac0a3c005a | 513eff1128ca343862a56322d21dfda9f2ef0480 | refs/heads/master | 2017-05-08T10:59:57.471000 | 2017-02-16T21:23:21 | 2017-02-16T21:23:21 | 82,225,350 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package game.area;
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.event.KeyEvent;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.ArrayList;
import java.util.Collections;
import javax.swing.ImageIcon;
import game.engine.GameEngine;
import game.sprite.Player;
import game.sprite.Sprite;
import game.sprite.GameCharacter;
import game.sprite.GameItem;
import game.ui.DialogPanel;
import game.ui.ItemPanel;
public class Room extends Canvas
{
/**
*
*/
private static final long serialVersionUID = -8275379730185985194L;
protected transient Image backGround;
protected ArrayList<GameCharacter> characters;
protected ArrayList<GameItem> items;
protected ArrayList<Sprite> renderQueue;
protected String fileName;
protected Player player;
protected Point center;
protected Point startPoint;
protected int x, y;
protected int cycles = 0;
protected int floorNo;
protected String roomName;
protected String targetRoom;
protected String targetFloor;
protected DialogPanel currentDialog;
protected transient GameEngine engine;
private boolean initialized = false;
private boolean onFirstDraw = true;
public Room(int width, int height, String fileName, GameEngine engine)
{
setSize(width, height);
setBackground(Color.BLACK);
this.fileName = fileName;
loadImage();
center = new Point(getWidth() / 2, getHeight() / 2);
player = engine.getPlayerRef();
setup();
addSprites();
currentDialog = null;
this.engine = engine;
}
//used to restore GameEngine reference after deserialization
public void restoreEngineRef(GameEngine engine)
{
this.engine = engine;
}
public void setTargetFloor(int floorNo)
{
switch(floorNo)
{
case 1: targetFloor = "Floor1_Hall_Right";
break;
case 2: targetFloor = "Floor2_Hall";
break;
case 3: targetFloor = "Floor3_Hall";
break;
case 4: targetFloor = "Floor4_Hall";
break;
default: targetFloor = "Floor1_Hall_Left";
break;
}
}
public void addItem(GameItem item)
{
item.setLocation(items);
items.add(item);
updateDraw();
}
public void addCharacter(GameCharacter ch)
{
ch.xPos = center.x + ch.xPos;
ch.yPos = center.y + ch.yPos;
characters.add(ch);
updateDraw();
}
//Called when window is resized to position content relative to window center
public void recenter()
{
Point originalCenter = center;
center = new Point(getWidth() / 2, getHeight() / 2);
x += center.x - originalCenter.x;
y += center.y - originalCenter.y;
if(startPoint != null)
{
startPoint.x += center.x - originalCenter.x;
startPoint.y += center.y - originalCenter.y;
}
player.xPos = center.x - player.getBounds().width / 2;
player.yPos = center.y - player.getBounds().height / 2;
for(GameCharacter ch : characters)
{
ch.xPos += center.x - originalCenter.x;
ch.yPos += center.y - originalCenter.y;
}
for(GameItem it : items)
{
it.xPos += center.x - originalCenter.x;
it.yPos += center.y - originalCenter.y;
}
}
//loads room background image from file
protected void loadImage()
{
ImageIcon loader = new ImageIcon(getClass().getResource(fileName));
backGround = loader.getImage();
}
protected void setup()
{
player.xPos = center.x - player.getBounds().width / 2;
player.yPos = center.y - player.getBounds().height / 2;
x = center.x - backGround.getWidth(null) / 2;
y = center.y - backGround.getHeight(null) / 2;
items = new ArrayList<>();
characters = new ArrayList<>();
renderQueue = new ArrayList<>();
}
public Rectangle getBackgroundBounds()
{
return new Rectangle(x, y, backGround.getWidth(null), backGround.getHeight(null));
}
public void onLoadRoom()
{
player.c_detect.reset();
player.c_detect.setCurrentArea(this);
for(GameCharacter ch : characters)
player.c_detect.addObjects(ch);
for(GameItem it : items)
player.c_detect.addObjects(it);
}
public void render(Graphics g)
{
if(onFirstDraw)
{
renderQueue.add(player);
for(GameCharacter ch : characters)
renderQueue.add(ch);
for(GameItem it : items)
renderQueue.add(it);
Collections.sort(renderQueue, new SpriteOrdering());
onFirstDraw = false;
}
g.drawImage(backGround, x, y, null);
for(Sprite sp : renderQueue)
sp.render(g);
}
public void updateDraw()
{
onFirstDraw = true;
renderQueue.clear();
}
public void animate()
{
if (cycles < 20)
cycles++;
else
{
player.cycleFrames();
for(GameCharacter ch : characters)
ch.cycleFrames();
for(GameItem it : items)
it.cycleFrames();
cycles = 0;
}
}
protected void addSprites()
{
//override to add specific sprites to a room
}
public void setInitialized()
{
initialized = true;
}
public boolean isInitialized()
{
return initialized;
}
public String getRoomName()
{
return roomName;
}
public GameCharacter getCharacter(String characterName)
{
for(GameCharacter ch : characters)
if(ch.getCharacterName().equals(characterName))
return ch;
return null; //return null if search fails
}
//uses key inputs to move player around room
public void move()
{
int x_prev = x;
int y_prev = y;
if(engine.keyboard.keyDown(KeyEvent.VK_DOWN) && player.c_detect.clearDown())
{
y--;
player.faceDown();
}
else if(engine.keyboard.keyDown(KeyEvent.VK_LEFT) && player.c_detect.clearLeft())
{
x++;
player.faceLeft();
}
else if(engine.keyboard.keyDown(KeyEvent.VK_UP) && player.c_detect.clearUp())
{
y++;
player.faceUp();
}
else if(engine.keyboard.keyDown(KeyEvent.VK_RIGHT) && player.c_detect.clearRight())
{
x--;
player.faceRight();
}
else
player.stop();
for(GameCharacter ch : characters)
{
ch.xPos += x - x_prev;
ch.yPos += y - y_prev;
}
for(GameItem it : items)
{
it.xPos += x - x_prev;
it.yPos += y - y_prev;
}
}
public void loadNextRoom()
{
engine.switchRoom(targetRoom);
}
public void switchRoom(String targetRoom)
{
engine.switchRoom(targetRoom);
}
public void switchRoom(String targetRoom, Point startPoint)
{
engine.switchRoom(targetRoom, startPoint);
}
public void setStartPoint(Point startPoint)
{
int x_prev = x;
int y_prev = y;
x = center.x - backGround.getWidth(null) / 2;
y = center.y - backGround.getHeight(null) / 2;
for(GameCharacter ch : characters)
{
ch.xPos += x - x_prev;
ch.yPos += y - y_prev;
}
for(GameItem it : items)
{
it.xPos += x - x_prev;
it.yPos += y - y_prev;
}
this.startPoint = new Point(x + startPoint.x, y + startPoint.y);
reposition();
}
protected void reposition()
{
int x_prev = x;
int y_prev = y;
x = startPoint.x;
y = startPoint.y;
for(GameCharacter ch : characters)
{
ch.xPos += x - x_prev;
ch.yPos += y - y_prev;
}
for(GameItem it : items)
{
it.xPos += x - x_prev;
it.yPos += y - y_prev;
}
}
protected void loadDialog()
{
int nearestDist = 150;
int tempSum = 0;
GameCharacter nearest = null;
for(GameCharacter ch : characters)
{
tempSum = Math.abs(ch.getCenter().x - player.getCenter().x) + Math.abs(ch.getCenter().y - player.getCenter().y);
if(tempSum < nearestDist)
{
nearestDist = tempSum;
nearest = ch;
}
}
if(nearest != null)
engine.loadDialogMenu(nearest.getDialog());
}
protected void loadDescription()
{
int nearestDist = 175;
int tempSum = 0;
GameItem nearest = null;
for(GameItem it : items)
{
tempSum = Math.abs(it.getCenter().x - player.getCenter().x) + Math.abs(it.getCenter().y - player.getCenter().y);
if(tempSum < nearestDist)
{
nearestDist = tempSum;
nearest = it;
}
}
if(nearest != null && nearest.getInfo() != null)
{
ItemPanel temp = nearest.getInfo();
temp.setCharacterRef(player);
temp.setAreaRef(this);
engine.loadDialogMenu(temp);
}
}
public void monitorInput()
{
if(!engine.lockKeyBoard)
engine.keyboard.poll();
if(engine.keyboard.keyDownOnce(KeyEvent.VK_T))
loadDialog();
else if(engine.keyboard.keyDownOnce(KeyEvent.VK_E))
loadDescription();
else if(engine.keyboard.keyDownOnce(KeyEvent.VK_ESCAPE))
{
if(engine.inMenu())
engine.exitMenu();
else
engine.loadMenu();
}
else if(engine.keyboard.keyDownOnce(KeyEvent.VK_F11))
engine.switchDisplayMode();
else if(engine.keyboard.keyDownOnce(KeyEvent.VK_I))
engine.loadInventoryMenu(player.getInventoryMenu());
}
private void readObject(ObjectInputStream s)
{
try
{
s.defaultReadObject();
loadImage();
initialized = false;
}
catch (ClassNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
| UTF-8 | Java | 9,320 | java | Room.java | Java | []
| null | []
| package game.area;
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.event.KeyEvent;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.ArrayList;
import java.util.Collections;
import javax.swing.ImageIcon;
import game.engine.GameEngine;
import game.sprite.Player;
import game.sprite.Sprite;
import game.sprite.GameCharacter;
import game.sprite.GameItem;
import game.ui.DialogPanel;
import game.ui.ItemPanel;
public class Room extends Canvas
{
/**
*
*/
private static final long serialVersionUID = -8275379730185985194L;
protected transient Image backGround;
protected ArrayList<GameCharacter> characters;
protected ArrayList<GameItem> items;
protected ArrayList<Sprite> renderQueue;
protected String fileName;
protected Player player;
protected Point center;
protected Point startPoint;
protected int x, y;
protected int cycles = 0;
protected int floorNo;
protected String roomName;
protected String targetRoom;
protected String targetFloor;
protected DialogPanel currentDialog;
protected transient GameEngine engine;
private boolean initialized = false;
private boolean onFirstDraw = true;
public Room(int width, int height, String fileName, GameEngine engine)
{
setSize(width, height);
setBackground(Color.BLACK);
this.fileName = fileName;
loadImage();
center = new Point(getWidth() / 2, getHeight() / 2);
player = engine.getPlayerRef();
setup();
addSprites();
currentDialog = null;
this.engine = engine;
}
//used to restore GameEngine reference after deserialization
public void restoreEngineRef(GameEngine engine)
{
this.engine = engine;
}
public void setTargetFloor(int floorNo)
{
switch(floorNo)
{
case 1: targetFloor = "Floor1_Hall_Right";
break;
case 2: targetFloor = "Floor2_Hall";
break;
case 3: targetFloor = "Floor3_Hall";
break;
case 4: targetFloor = "Floor4_Hall";
break;
default: targetFloor = "Floor1_Hall_Left";
break;
}
}
public void addItem(GameItem item)
{
item.setLocation(items);
items.add(item);
updateDraw();
}
public void addCharacter(GameCharacter ch)
{
ch.xPos = center.x + ch.xPos;
ch.yPos = center.y + ch.yPos;
characters.add(ch);
updateDraw();
}
//Called when window is resized to position content relative to window center
public void recenter()
{
Point originalCenter = center;
center = new Point(getWidth() / 2, getHeight() / 2);
x += center.x - originalCenter.x;
y += center.y - originalCenter.y;
if(startPoint != null)
{
startPoint.x += center.x - originalCenter.x;
startPoint.y += center.y - originalCenter.y;
}
player.xPos = center.x - player.getBounds().width / 2;
player.yPos = center.y - player.getBounds().height / 2;
for(GameCharacter ch : characters)
{
ch.xPos += center.x - originalCenter.x;
ch.yPos += center.y - originalCenter.y;
}
for(GameItem it : items)
{
it.xPos += center.x - originalCenter.x;
it.yPos += center.y - originalCenter.y;
}
}
//loads room background image from file
protected void loadImage()
{
ImageIcon loader = new ImageIcon(getClass().getResource(fileName));
backGround = loader.getImage();
}
protected void setup()
{
player.xPos = center.x - player.getBounds().width / 2;
player.yPos = center.y - player.getBounds().height / 2;
x = center.x - backGround.getWidth(null) / 2;
y = center.y - backGround.getHeight(null) / 2;
items = new ArrayList<>();
characters = new ArrayList<>();
renderQueue = new ArrayList<>();
}
public Rectangle getBackgroundBounds()
{
return new Rectangle(x, y, backGround.getWidth(null), backGround.getHeight(null));
}
public void onLoadRoom()
{
player.c_detect.reset();
player.c_detect.setCurrentArea(this);
for(GameCharacter ch : characters)
player.c_detect.addObjects(ch);
for(GameItem it : items)
player.c_detect.addObjects(it);
}
public void render(Graphics g)
{
if(onFirstDraw)
{
renderQueue.add(player);
for(GameCharacter ch : characters)
renderQueue.add(ch);
for(GameItem it : items)
renderQueue.add(it);
Collections.sort(renderQueue, new SpriteOrdering());
onFirstDraw = false;
}
g.drawImage(backGround, x, y, null);
for(Sprite sp : renderQueue)
sp.render(g);
}
public void updateDraw()
{
onFirstDraw = true;
renderQueue.clear();
}
public void animate()
{
if (cycles < 20)
cycles++;
else
{
player.cycleFrames();
for(GameCharacter ch : characters)
ch.cycleFrames();
for(GameItem it : items)
it.cycleFrames();
cycles = 0;
}
}
protected void addSprites()
{
//override to add specific sprites to a room
}
public void setInitialized()
{
initialized = true;
}
public boolean isInitialized()
{
return initialized;
}
public String getRoomName()
{
return roomName;
}
public GameCharacter getCharacter(String characterName)
{
for(GameCharacter ch : characters)
if(ch.getCharacterName().equals(characterName))
return ch;
return null; //return null if search fails
}
//uses key inputs to move player around room
public void move()
{
int x_prev = x;
int y_prev = y;
if(engine.keyboard.keyDown(KeyEvent.VK_DOWN) && player.c_detect.clearDown())
{
y--;
player.faceDown();
}
else if(engine.keyboard.keyDown(KeyEvent.VK_LEFT) && player.c_detect.clearLeft())
{
x++;
player.faceLeft();
}
else if(engine.keyboard.keyDown(KeyEvent.VK_UP) && player.c_detect.clearUp())
{
y++;
player.faceUp();
}
else if(engine.keyboard.keyDown(KeyEvent.VK_RIGHT) && player.c_detect.clearRight())
{
x--;
player.faceRight();
}
else
player.stop();
for(GameCharacter ch : characters)
{
ch.xPos += x - x_prev;
ch.yPos += y - y_prev;
}
for(GameItem it : items)
{
it.xPos += x - x_prev;
it.yPos += y - y_prev;
}
}
public void loadNextRoom()
{
engine.switchRoom(targetRoom);
}
public void switchRoom(String targetRoom)
{
engine.switchRoom(targetRoom);
}
public void switchRoom(String targetRoom, Point startPoint)
{
engine.switchRoom(targetRoom, startPoint);
}
public void setStartPoint(Point startPoint)
{
int x_prev = x;
int y_prev = y;
x = center.x - backGround.getWidth(null) / 2;
y = center.y - backGround.getHeight(null) / 2;
for(GameCharacter ch : characters)
{
ch.xPos += x - x_prev;
ch.yPos += y - y_prev;
}
for(GameItem it : items)
{
it.xPos += x - x_prev;
it.yPos += y - y_prev;
}
this.startPoint = new Point(x + startPoint.x, y + startPoint.y);
reposition();
}
protected void reposition()
{
int x_prev = x;
int y_prev = y;
x = startPoint.x;
y = startPoint.y;
for(GameCharacter ch : characters)
{
ch.xPos += x - x_prev;
ch.yPos += y - y_prev;
}
for(GameItem it : items)
{
it.xPos += x - x_prev;
it.yPos += y - y_prev;
}
}
protected void loadDialog()
{
int nearestDist = 150;
int tempSum = 0;
GameCharacter nearest = null;
for(GameCharacter ch : characters)
{
tempSum = Math.abs(ch.getCenter().x - player.getCenter().x) + Math.abs(ch.getCenter().y - player.getCenter().y);
if(tempSum < nearestDist)
{
nearestDist = tempSum;
nearest = ch;
}
}
if(nearest != null)
engine.loadDialogMenu(nearest.getDialog());
}
protected void loadDescription()
{
int nearestDist = 175;
int tempSum = 0;
GameItem nearest = null;
for(GameItem it : items)
{
tempSum = Math.abs(it.getCenter().x - player.getCenter().x) + Math.abs(it.getCenter().y - player.getCenter().y);
if(tempSum < nearestDist)
{
nearestDist = tempSum;
nearest = it;
}
}
if(nearest != null && nearest.getInfo() != null)
{
ItemPanel temp = nearest.getInfo();
temp.setCharacterRef(player);
temp.setAreaRef(this);
engine.loadDialogMenu(temp);
}
}
public void monitorInput()
{
if(!engine.lockKeyBoard)
engine.keyboard.poll();
if(engine.keyboard.keyDownOnce(KeyEvent.VK_T))
loadDialog();
else if(engine.keyboard.keyDownOnce(KeyEvent.VK_E))
loadDescription();
else if(engine.keyboard.keyDownOnce(KeyEvent.VK_ESCAPE))
{
if(engine.inMenu())
engine.exitMenu();
else
engine.loadMenu();
}
else if(engine.keyboard.keyDownOnce(KeyEvent.VK_F11))
engine.switchDisplayMode();
else if(engine.keyboard.keyDownOnce(KeyEvent.VK_I))
engine.loadInventoryMenu(player.getInventoryMenu());
}
private void readObject(ObjectInputStream s)
{
try
{
s.defaultReadObject();
loadImage();
initialized = false;
}
catch (ClassNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
| 9,320 | 0.636051 | 0.630257 | 436 | 19.376146 | 19.284227 | 115 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.220183 | false | false | 13 |
227d7e9bbd3ef7ef2eafa106d65a75447f13ffca | 32,624,571,595,288 | bd98e681d65645a4ca6c2afa4cdb3135b75f4813 | /src/main/java/TinySearchEngine.java | 585bb02af03d1e599adbac8ae2c7308e4a1aa653 | [
"MIT"
]
| permissive | akamboj99/simple-search-engine | https://github.com/akamboj99/simple-search-engine | f8c95c2b908c46d0287858385a13e40fb30319d2 | 3c245d15d766d79155475a0c12a84341f1423298 | refs/heads/master | 2022-02-28T05:30:57.396000 | 2019-10-03T20:33:26 | 2019-10-03T20:33:26 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /**
* TinySearchEngine.java
*
* Created by S. Stefani on 2016-11-24.
*/
import se.kth.id1020.TinySearchEngineBase;
import se.kth.id1020.util.Attributes;
import se.kth.id1020.util.Document;
import se.kth.id1020.util.Sentence;
import se.kth.id1020.util.Word;
import java.util.*;
public class TinySearchEngine implements TinySearchEngineBase {
private HashMap<String, ArrayList<ResultDocument>> index;
private HashMap<String, Integer> documentsLengths;
private HashMap<String, ArrayList<ResultDocument>> cache;
public TinySearchEngine() {
this.index = new HashMap<String, ArrayList<ResultDocument>>();
this.documentsLengths = new HashMap<String, Integer>();
this.cache = new HashMap<String, ArrayList<ResultDocument>>();
}
public void preInserts() {
System.out.println("Executing pre-insert...");
}
/**
* Insert all the words of a sentence in the index.
*
* @param sentence is the current sentence
* @param attributes contain the parent document of the sentence
*/
public void insert(Sentence sentence, Attributes attributes) {
for (Word word : sentence.getWords()) {
// Add word to index if not in
if (!index.containsKey(word.word)) {
index.put(word.word, new ArrayList<ResultDocument>());
}
// Create new posting
ArrayList<ResultDocument> postingList = index.get(word.word);
ResultDocument newPosting = new ResultDocument(attributes.document, 1);
int ind = Collections.binarySearch(postingList, newPosting);
// Update posting if existent or add
if (ind < 0) {
postingList.add(-ind-1, newPosting);
} else {
postingList.get(ind).updatePosting();
}
}
// Compute and store lengths of documents
Integer sentenceLength = sentence.getWords().size();
if (documentsLengths.containsKey(attributes.document.name)) {
sentenceLength += documentsLengths.get(attributes.document.name);
}
documentsLengths.put(attributes.document.name, sentenceLength);
}
public void postInserts() {
System.out.println("Executing post-insert...");
}
/**
* Parse a user query and search for all the elements that satisfy such query.
* Order the results according to the user input.
*
* @param s is the input query string
* @return the list of docs that satisfy the query
*/
public List<Document> search(String s) {
// Parse query
Query query = new Query(s);
// Compute Array of result
ArrayList<ResultDocument> result = runQuery(query.getParsedQuery());
if (result == null) { return null; }
// If sorting is specified use comparator to sort
if (query.getProperty() != null && query.getProperty().equals("POPULARITY")) {
Collections.sort(result, new ResultDocument.PopularityComparator(query.getDirection()));
} else if (query.getProperty() != null && query.getProperty().equals("RELEVANCE")) {
Collections.sort(result, new ResultDocument.RelevanceComparator(query.getDirection()));
}
// Convert into list of documents
List<Document> documentList = new LinkedList<Document>();
for (ResultDocument rd : result) { documentList.add(rd.getDocument()); }
return documentList;
}
/**
* Recursively analyse the query and compute the results considering the query operators.
*
* @param subQ is the sub-query object (result of the query parsing)
* @return an array list of documents
*/
private ArrayList<ResultDocument> runQuery(Subquery subQ) {
if (subQ.rightTerm == null) {
if (!index.containsKey(subQ.leftTerm)) return new ArrayList<ResultDocument>();
ArrayList<ResultDocument> list = new ArrayList<ResultDocument>();
for (ResultDocument value : index.get(subQ.leftTerm)) {
ResultDocument newRD = new ResultDocument(value.getDocument(), value.getHits());
newRD.computeRelevance(documentsLengths, index.get(subQ.leftTerm).size());
list.add(newRD);
}
return list;
}
// Check if the query is cached
if (cache.containsKey(subQ.orderedQuery)) {
// System.out.println("Cache hit: " + subQ.toString());
return cache.get(subQ.orderedQuery);
}
ArrayList<ResultDocument> leftResult = runQuery(subQ.leftTerm instanceof Subquery ? (Subquery) subQ.leftTerm : new Subquery(subQ.leftTerm));
ArrayList<ResultDocument> rightResult = runQuery(subQ.rightTerm instanceof Subquery ? (Subquery) subQ.rightTerm : new Subquery(subQ.rightTerm));
String operator = subQ.operator;
// Run query operations (union, intersection, difference)
ArrayList<ResultDocument> result;
if (operator.equals("+")) {
result = resultIntersection(leftResult, rightResult);
} else if (operator.equals("|")) {
result = resultUnion(leftResult, rightResult);
} else {
result = resultDifference(leftResult, rightResult);
}
// Cache the result
cache.put(subQ.orderedQuery, result);
// System.out.println("Add to cache: " + subQ.toString());
return result;
}
// Compute intersection of two queries
private ArrayList<ResultDocument> resultIntersection(ArrayList<ResultDocument> l, ArrayList<ResultDocument> r) {
ArrayList<ResultDocument> result = new ArrayList<ResultDocument>();
for (ResultDocument rd : l) {
int ind = Collections.binarySearch(r, rd);
if (ind >= 0) {
result.add(merge(rd, r.get(ind)));
}
}
return result;
}
// Compute union of two queries
private ArrayList<ResultDocument> resultUnion(ArrayList<ResultDocument> l, ArrayList<ResultDocument> r) {
ArrayList<ResultDocument> result = new ArrayList<ResultDocument>();
result.addAll(l);
for (ResultDocument rd : r) {
int ind = Collections.binarySearch(result, rd);
if (ind >= 0) {
result.set(ind, merge(result.get(ind), rd));
} else {
result.add(-ind-1, rd);
}
}
return result;
}
// Compute difference of two queries
private ArrayList<ResultDocument> resultDifference(ArrayList<ResultDocument> l, ArrayList<ResultDocument> r) {
ArrayList<ResultDocument> result = new ArrayList<ResultDocument>();
for (ResultDocument rd : l) {
if (!r.contains(rd)) { result.add(rd); }
}
return result;
}
private ResultDocument merge(ResultDocument u, ResultDocument v) {
return new ResultDocument(u.getDocument(), u.getRelevance() + v.getRelevance());
}
/**
* Output the infix version of the query string (useful to check correctness of parser)
*
* @param s is the user query string
* @return the infix version of query
*/
public String infix(String s) {
Query query = new Query(s);
String dir = query.getDirection() == 1 ? "asc" : "desc";
return query.getParsedQuery().toString() + " orderby " + query.getProperty().toLowerCase() + " " + dir;
}
} | UTF-8 | Java | 7,473 | java | TinySearchEngine.java | Java | [
{
"context": "/**\n * TinySearchEngine.java\n *\n * Created by S. Stefani on 2016-11-24.\n */\n\nimport se.kth.id1020.TinySear",
"end": 56,
"score": 0.9998847842216492,
"start": 46,
"tag": "NAME",
"value": "S. Stefani"
}
]
| null | []
| /**
* TinySearchEngine.java
*
* Created by <NAME> on 2016-11-24.
*/
import se.kth.id1020.TinySearchEngineBase;
import se.kth.id1020.util.Attributes;
import se.kth.id1020.util.Document;
import se.kth.id1020.util.Sentence;
import se.kth.id1020.util.Word;
import java.util.*;
public class TinySearchEngine implements TinySearchEngineBase {
private HashMap<String, ArrayList<ResultDocument>> index;
private HashMap<String, Integer> documentsLengths;
private HashMap<String, ArrayList<ResultDocument>> cache;
public TinySearchEngine() {
this.index = new HashMap<String, ArrayList<ResultDocument>>();
this.documentsLengths = new HashMap<String, Integer>();
this.cache = new HashMap<String, ArrayList<ResultDocument>>();
}
public void preInserts() {
System.out.println("Executing pre-insert...");
}
/**
* Insert all the words of a sentence in the index.
*
* @param sentence is the current sentence
* @param attributes contain the parent document of the sentence
*/
public void insert(Sentence sentence, Attributes attributes) {
for (Word word : sentence.getWords()) {
// Add word to index if not in
if (!index.containsKey(word.word)) {
index.put(word.word, new ArrayList<ResultDocument>());
}
// Create new posting
ArrayList<ResultDocument> postingList = index.get(word.word);
ResultDocument newPosting = new ResultDocument(attributes.document, 1);
int ind = Collections.binarySearch(postingList, newPosting);
// Update posting if existent or add
if (ind < 0) {
postingList.add(-ind-1, newPosting);
} else {
postingList.get(ind).updatePosting();
}
}
// Compute and store lengths of documents
Integer sentenceLength = sentence.getWords().size();
if (documentsLengths.containsKey(attributes.document.name)) {
sentenceLength += documentsLengths.get(attributes.document.name);
}
documentsLengths.put(attributes.document.name, sentenceLength);
}
public void postInserts() {
System.out.println("Executing post-insert...");
}
/**
* Parse a user query and search for all the elements that satisfy such query.
* Order the results according to the user input.
*
* @param s is the input query string
* @return the list of docs that satisfy the query
*/
public List<Document> search(String s) {
// Parse query
Query query = new Query(s);
// Compute Array of result
ArrayList<ResultDocument> result = runQuery(query.getParsedQuery());
if (result == null) { return null; }
// If sorting is specified use comparator to sort
if (query.getProperty() != null && query.getProperty().equals("POPULARITY")) {
Collections.sort(result, new ResultDocument.PopularityComparator(query.getDirection()));
} else if (query.getProperty() != null && query.getProperty().equals("RELEVANCE")) {
Collections.sort(result, new ResultDocument.RelevanceComparator(query.getDirection()));
}
// Convert into list of documents
List<Document> documentList = new LinkedList<Document>();
for (ResultDocument rd : result) { documentList.add(rd.getDocument()); }
return documentList;
}
/**
* Recursively analyse the query and compute the results considering the query operators.
*
* @param subQ is the sub-query object (result of the query parsing)
* @return an array list of documents
*/
private ArrayList<ResultDocument> runQuery(Subquery subQ) {
if (subQ.rightTerm == null) {
if (!index.containsKey(subQ.leftTerm)) return new ArrayList<ResultDocument>();
ArrayList<ResultDocument> list = new ArrayList<ResultDocument>();
for (ResultDocument value : index.get(subQ.leftTerm)) {
ResultDocument newRD = new ResultDocument(value.getDocument(), value.getHits());
newRD.computeRelevance(documentsLengths, index.get(subQ.leftTerm).size());
list.add(newRD);
}
return list;
}
// Check if the query is cached
if (cache.containsKey(subQ.orderedQuery)) {
// System.out.println("Cache hit: " + subQ.toString());
return cache.get(subQ.orderedQuery);
}
ArrayList<ResultDocument> leftResult = runQuery(subQ.leftTerm instanceof Subquery ? (Subquery) subQ.leftTerm : new Subquery(subQ.leftTerm));
ArrayList<ResultDocument> rightResult = runQuery(subQ.rightTerm instanceof Subquery ? (Subquery) subQ.rightTerm : new Subquery(subQ.rightTerm));
String operator = subQ.operator;
// Run query operations (union, intersection, difference)
ArrayList<ResultDocument> result;
if (operator.equals("+")) {
result = resultIntersection(leftResult, rightResult);
} else if (operator.equals("|")) {
result = resultUnion(leftResult, rightResult);
} else {
result = resultDifference(leftResult, rightResult);
}
// Cache the result
cache.put(subQ.orderedQuery, result);
// System.out.println("Add to cache: " + subQ.toString());
return result;
}
// Compute intersection of two queries
private ArrayList<ResultDocument> resultIntersection(ArrayList<ResultDocument> l, ArrayList<ResultDocument> r) {
ArrayList<ResultDocument> result = new ArrayList<ResultDocument>();
for (ResultDocument rd : l) {
int ind = Collections.binarySearch(r, rd);
if (ind >= 0) {
result.add(merge(rd, r.get(ind)));
}
}
return result;
}
// Compute union of two queries
private ArrayList<ResultDocument> resultUnion(ArrayList<ResultDocument> l, ArrayList<ResultDocument> r) {
ArrayList<ResultDocument> result = new ArrayList<ResultDocument>();
result.addAll(l);
for (ResultDocument rd : r) {
int ind = Collections.binarySearch(result, rd);
if (ind >= 0) {
result.set(ind, merge(result.get(ind), rd));
} else {
result.add(-ind-1, rd);
}
}
return result;
}
// Compute difference of two queries
private ArrayList<ResultDocument> resultDifference(ArrayList<ResultDocument> l, ArrayList<ResultDocument> r) {
ArrayList<ResultDocument> result = new ArrayList<ResultDocument>();
for (ResultDocument rd : l) {
if (!r.contains(rd)) { result.add(rd); }
}
return result;
}
private ResultDocument merge(ResultDocument u, ResultDocument v) {
return new ResultDocument(u.getDocument(), u.getRelevance() + v.getRelevance());
}
/**
* Output the infix version of the query string (useful to check correctness of parser)
*
* @param s is the user query string
* @return the infix version of query
*/
public String infix(String s) {
Query query = new Query(s);
String dir = query.getDirection() == 1 ? "asc" : "desc";
return query.getParsedQuery().toString() + " orderby " + query.getProperty().toLowerCase() + " " + dir;
}
} | 7,469 | 0.626656 | 0.621972 | 200 | 36.369999 | 32.289055 | 152 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false | 13 |
2ba0d174d6e0170c86b391bbac60defae7c2267f | 29,970,281,826,330 | be25b2c018dbacd8147a8fbfbc66f257b050ea1f | /core/baseLanguage/baseLanguage/source_gen/jetbrains/mps/baseLanguage/typesystem/check_LocalStaticMethodCall_NonTypesystemRule.java | c84cab3eed122478d41549793900497f90cd3829 | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
]
| permissive | blutkind/MPS | https://github.com/blutkind/MPS | f5bef8c27c3cb65940ba74a5d1942fdab35ee096 | cac72cce91d98dec40bbadf7a049ed9dbbc18231 | refs/heads/master | 2020-04-08T01:22:10.782000 | 2011-12-09T20:58:07 | 2011-12-09T20:58:07 | 2,950,220 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package jetbrains.mps.baseLanguage.typesystem;
/*Generated by MPS */
import jetbrains.mps.lang.typesystem.runtime.AbstractNonTypesystemRule_Runtime;
import jetbrains.mps.lang.typesystem.runtime.NonTypesystemRule_Runtime;
import jetbrains.mps.smodel.SNode;
import jetbrains.mps.typesystem.inference.TypeCheckingContext;
import jetbrains.mps.lang.typesystem.runtime.IsApplicableStatus;
import java.util.List;
import jetbrains.mps.lang.smodel.generator.smodelAdapter.SNodeOperations;
import java.util.Set;
import jetbrains.mps.internal.collections.runtime.SetSequence;
import java.util.HashSet;
import jetbrains.mps.baseLanguage.search.ClassifierAndSuperClassifiersScope;
import jetbrains.mps.lang.smodel.generator.smodelAdapter.SLinkOperations;
import jetbrains.mps.errors.messageTargets.MessageTarget;
import jetbrains.mps.errors.messageTargets.NodeMessageTarget;
import jetbrains.mps.errors.IErrorReporter;
import jetbrains.mps.smodel.SModelUtil_new;
public class check_LocalStaticMethodCall_NonTypesystemRule extends AbstractNonTypesystemRule_Runtime implements NonTypesystemRule_Runtime {
public check_LocalStaticMethodCall_NonTypesystemRule() {
}
public void applyRule(final SNode call, final TypeCheckingContext typeCheckingContext, IsApplicableStatus status) {
List<SNode> containers = SNodeOperations.getAncestors(call, "jetbrains.mps.baseLanguage.structure.ClassConcept", false);
Set<SNode> containersAndParentClasses = SetSequence.fromSet(new HashSet<SNode>());
for (SNode classConcept : containers) {
List<SNode> classifiers = new ClassifierAndSuperClassifiersScope(classConcept).getClassifiers();
for (SNode classifier : classifiers) {
SetSequence.fromSet(containersAndParentClasses).addElement(classifier);
}
}
if (!(SetSequence.fromSet(containersAndParentClasses).contains(SNodeOperations.getParent(SLinkOperations.getTarget(call, "baseMethodDeclaration", false))))) {
{
MessageTarget errorTarget = new NodeMessageTarget();
IErrorReporter _reporter_2309309498 = typeCheckingContext.reportTypeError(call, "This method can't be called from the current context", "r:00000000-0000-4000-0000-011c895902c5(jetbrains.mps.baseLanguage.typesystem)", "1228992682236", null, errorTarget);
}
}
}
public String getApplicableConceptFQName() {
return "jetbrains.mps.baseLanguage.structure.LocalStaticMethodCall";
}
public IsApplicableStatus isApplicableAndPattern(SNode argument) {
{
boolean b = SModelUtil_new.isAssignableConcept(argument.getConceptFqName(), this.getApplicableConceptFQName());
return new IsApplicableStatus(b, null);
}
}
public boolean overrides() {
return false;
}
}
| UTF-8 | Java | 2,717 | java | check_LocalStaticMethodCall_NonTypesystemRule.java | Java | []
| null | []
| package jetbrains.mps.baseLanguage.typesystem;
/*Generated by MPS */
import jetbrains.mps.lang.typesystem.runtime.AbstractNonTypesystemRule_Runtime;
import jetbrains.mps.lang.typesystem.runtime.NonTypesystemRule_Runtime;
import jetbrains.mps.smodel.SNode;
import jetbrains.mps.typesystem.inference.TypeCheckingContext;
import jetbrains.mps.lang.typesystem.runtime.IsApplicableStatus;
import java.util.List;
import jetbrains.mps.lang.smodel.generator.smodelAdapter.SNodeOperations;
import java.util.Set;
import jetbrains.mps.internal.collections.runtime.SetSequence;
import java.util.HashSet;
import jetbrains.mps.baseLanguage.search.ClassifierAndSuperClassifiersScope;
import jetbrains.mps.lang.smodel.generator.smodelAdapter.SLinkOperations;
import jetbrains.mps.errors.messageTargets.MessageTarget;
import jetbrains.mps.errors.messageTargets.NodeMessageTarget;
import jetbrains.mps.errors.IErrorReporter;
import jetbrains.mps.smodel.SModelUtil_new;
public class check_LocalStaticMethodCall_NonTypesystemRule extends AbstractNonTypesystemRule_Runtime implements NonTypesystemRule_Runtime {
public check_LocalStaticMethodCall_NonTypesystemRule() {
}
public void applyRule(final SNode call, final TypeCheckingContext typeCheckingContext, IsApplicableStatus status) {
List<SNode> containers = SNodeOperations.getAncestors(call, "jetbrains.mps.baseLanguage.structure.ClassConcept", false);
Set<SNode> containersAndParentClasses = SetSequence.fromSet(new HashSet<SNode>());
for (SNode classConcept : containers) {
List<SNode> classifiers = new ClassifierAndSuperClassifiersScope(classConcept).getClassifiers();
for (SNode classifier : classifiers) {
SetSequence.fromSet(containersAndParentClasses).addElement(classifier);
}
}
if (!(SetSequence.fromSet(containersAndParentClasses).contains(SNodeOperations.getParent(SLinkOperations.getTarget(call, "baseMethodDeclaration", false))))) {
{
MessageTarget errorTarget = new NodeMessageTarget();
IErrorReporter _reporter_2309309498 = typeCheckingContext.reportTypeError(call, "This method can't be called from the current context", "r:00000000-0000-4000-0000-011c895902c5(jetbrains.mps.baseLanguage.typesystem)", "1228992682236", null, errorTarget);
}
}
}
public String getApplicableConceptFQName() {
return "jetbrains.mps.baseLanguage.structure.LocalStaticMethodCall";
}
public IsApplicableStatus isApplicableAndPattern(SNode argument) {
{
boolean b = SModelUtil_new.isAssignableConcept(argument.getConceptFqName(), this.getApplicableConceptFQName());
return new IsApplicableStatus(b, null);
}
}
public boolean overrides() {
return false;
}
}
| 2,717 | 0.799411 | 0.779904 | 57 | 46.666668 | 49.196823 | 261 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.701754 | false | false | 13 |
2c4181c5ea5bfe9424b902af0d11e87540a0716f | 4,088,808,890,919 | b9129311faac659f7ab799d4d128c01ffe35f570 | /src/main/java/com/tuniu/tmc/sass/css/controller/ResourceUrlController.java | 3e181bb0613abb8ffef5168371c1d7170420c8b6 | []
| no_license | happyangs/CSdemo | https://github.com/happyangs/CSdemo | 32377eeb313e713c9d5f7a152bcb6d18ad64a0ae | ead8cd78b1d69a455a719ce5914b424682ea608c | refs/heads/master | 2017-12-01T10:37:07.041000 | 2017-06-28T10:02:23 | 2017-06-28T10:02:23 | 95,655,175 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.tuniu.tmc.sass.css.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.servlet.resource.ResourceUrlProvider;
/**
* ้ๆ่ตๆบๅฎไฝๆงๅถๅจ
* <p>
* <pre>
* css/img......
* </pre>
*
* @author shishaomeng
*/
@ControllerAdvice
public class ResourceUrlController {
@Autowired
ResourceUrlProvider resourceUrlProvider;
@ModelAttribute("urls")
public ResourceUrlProvider urls() {
return this.resourceUrlProvider;
}
}
| UTF-8 | Java | 629 | java | ResourceUrlController.java | Java | [
{
"context": "\n * <pre>\n * css/img......\n * </pre>\n *\n * @author shishaomeng\n */\n@ControllerAdvice\npublic class ResourceUrlCon",
"end": 391,
"score": 0.9995698928833008,
"start": 380,
"tag": "USERNAME",
"value": "shishaomeng"
}
]
| null | []
| package com.tuniu.tmc.sass.css.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.servlet.resource.ResourceUrlProvider;
/**
* ้ๆ่ตๆบๅฎไฝๆงๅถๅจ
* <p>
* <pre>
* css/img......
* </pre>
*
* @author shishaomeng
*/
@ControllerAdvice
public class ResourceUrlController {
@Autowired
ResourceUrlProvider resourceUrlProvider;
@ModelAttribute("urls")
public ResourceUrlProvider urls() {
return this.resourceUrlProvider;
}
}
| 629 | 0.774141 | 0.774141 | 30 | 19.366667 | 21.929407 | 68 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.466667 | false | false | 13 |
8d6502b68f108addcdde0e4c2aed2565aefdf337 | 23,072,564,317,579 | e0f063683c6311285ee92256c4fd862187124225 | /JDBC_Project_B20/src/test/java/day4/MySQL_Test.java | da38b1105b46927b27c1a540dd8c75ef6918f31d | []
| no_license | numuminov/Git_Practice2 | https://github.com/numuminov/Git_Practice2 | 0204ebde681165680c175bf253d2b133bb61259a | 13e4dc802e9237f11a85d28e484ad2be351eeced | refs/heads/master | 2023-02-07T17:15:58.687000 | 2021-01-04T17:24:17 | 2021-01-04T17:24:17 | 288,570,569 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package day4;
import utility.ConfigurationReader;
import utility.DB_Utility;
public class MySQL_Test {
public static void main(String[] args) {
String connection = ConfigurationReader.getProperty("library1.database.url");
String username=ConfigurationReader.getProperty("library1.database.username");
String password=ConfigurationReader.getProperty("library1.database.password");
DB_Utility.createConnection(connection,username,password);
DB_Utility.runQuery("Select * from books");
DB_Utility.displayAllData();
}
}
| UTF-8 | Java | 581 | java | MySQL_Test.java | Java | []
| null | []
| package day4;
import utility.ConfigurationReader;
import utility.DB_Utility;
public class MySQL_Test {
public static void main(String[] args) {
String connection = ConfigurationReader.getProperty("library1.database.url");
String username=ConfigurationReader.getProperty("library1.database.username");
String password=ConfigurationReader.getProperty("library1.database.password");
DB_Utility.createConnection(connection,username,password);
DB_Utility.runQuery("Select * from books");
DB_Utility.displayAllData();
}
}
| 581 | 0.726334 | 0.719449 | 22 | 25.40909 | 30.691513 | 86 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false | 13 |
bcf98bd7c79f2f57f257aa623fde999d5987f12e | 5,849,745,509,457 | e961daa367a16759f784ee2a761e64566454a9f1 | /src/PracticeMySelfV2/FindFirstCharacter.java | ee2cf8cfaee608065d54df70de1d4fcc1778875c | []
| no_license | ahmetosan/CyberTekClass | https://github.com/ahmetosan/CyberTekClass | 4a630ee073ad4a03c4afaf306d8941731adc54e0 | aac8949477d8456b1b89e0ede767b0bba9afd570 | refs/heads/master | 2020-12-01T04:53:16.111000 | 2019-12-28T05:12:34 | 2019-12-28T05:12:34 | 230,561,872 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package PracticeMySelfV2;
import java.util.Scanner;
public class FindFirstCharacter {
public static void main(String[] args) {
//DO NOT CHANGE
Scanner scan = new Scanner(System.in);
System.out.println("Please enter the text:");
String word = scan.nextLine();
System.out.println(word.charAt(0));
}
} | UTF-8 | Java | 354 | java | FindFirstCharacter.java | Java | []
| null | []
| package PracticeMySelfV2;
import java.util.Scanner;
public class FindFirstCharacter {
public static void main(String[] args) {
//DO NOT CHANGE
Scanner scan = new Scanner(System.in);
System.out.println("Please enter the text:");
String word = scan.nextLine();
System.out.println(word.charAt(0));
}
} | 354 | 0.638418 | 0.632768 | 19 | 17.68421 | 19.339222 | 53 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.315789 | false | false | 13 |
5d7f36dcd0169021336bc2b7bfc60163a81d8fac | 30,374,008,768,657 | 82d34d29d2e15391337fb382d67f565b9305387a | /src/main/java/uk/ac/ebi/age/model/AgeObject.java | 43b4a255b85b3d9996ce96607db52d09d458cdb8 | []
| no_license | mikegostev/AGE-TAB | https://github.com/mikegostev/AGE-TAB | 2e5cfa89a40f06a0cf43c172696b49629bddca76 | e631725303fca80bfcfb553ebf30d2a6afc43565 | refs/heads/master | 2016-09-10T20:05:22.578000 | 2012-11-09T14:36:53 | 2012-11-09T14:36:53 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package uk.ac.ebi.age.model;
import java.util.Collection;
import java.util.List;
import uk.ac.ebi.age.ext.entity.Entity;
/**
@model
*/
public interface AgeObject extends AgeAbstractObject, Entity
{
/** @model */
String getId();
IdScope getIdScope();
// String getOriginalId();
@Override
AgeClass getAgeElClass();
ClassRef getClassReference();
List<? extends AgeRelation> getRelations();
// Collection<String> getRelationClassesIds();
Collection< ? extends AgeRelationClass> getRelationClasses();
// Collection< ? extends AgeRelation> getRelationsByClassId(String cid);
AgeRelation getRelation(AgeRelationClass cls);
List< ? extends AgeRelation> getRelationsByClass(AgeRelationClass cls, boolean wSubCls);
Object getAttributeValue( AgeAttributeClass cls );
int getOrder();
int getRow();
int getCol();
ModuleKey getModuleKey();
DataModule getDataModule();
}
| UTF-8 | Java | 936 | java | AgeObject.java | Java | []
| null | []
| package uk.ac.ebi.age.model;
import java.util.Collection;
import java.util.List;
import uk.ac.ebi.age.ext.entity.Entity;
/**
@model
*/
public interface AgeObject extends AgeAbstractObject, Entity
{
/** @model */
String getId();
IdScope getIdScope();
// String getOriginalId();
@Override
AgeClass getAgeElClass();
ClassRef getClassReference();
List<? extends AgeRelation> getRelations();
// Collection<String> getRelationClassesIds();
Collection< ? extends AgeRelationClass> getRelationClasses();
// Collection< ? extends AgeRelation> getRelationsByClassId(String cid);
AgeRelation getRelation(AgeRelationClass cls);
List< ? extends AgeRelation> getRelationsByClass(AgeRelationClass cls, boolean wSubCls);
Object getAttributeValue( AgeAttributeClass cls );
int getOrder();
int getRow();
int getCol();
ModuleKey getModuleKey();
DataModule getDataModule();
}
| 936 | 0.71688 | 0.71688 | 44 | 19.272728 | 22.413839 | 89 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.522727 | false | false | 13 |
81317c3cfbb6825aaf3f34d42eb44a4fc4decb7d | 33,586,644,277,729 | 3ee87ef515337cc2997526154a466c0df616e619 | /core/Grammar2Model.KDM/src/kdm/source/util/SourceSwitch.java | 4ae0d5eb41f90204d1041139654532a08776816f | []
| no_license | adolfosbh/gra2mol | https://github.com/adolfosbh/gra2mol | e0eb121e0d4b9757b53546e90aa570194a920bf5 | ab03b456446ba906ce796fd996703df243410492 | refs/heads/master | 2020-04-05T23:00:58.753000 | 2016-11-19T13:13:07 | 2016-11-19T13:13:07 | 51,363,734 | 0 | 0 | null | true | 2016-02-09T11:49:49 | 2016-02-09T11:49:49 | 2015-01-07T14:13:48 | 2014-09-12T08:16:11 | 72,484 | 0 | 0 | 0 | null | null | null | /**
* <copyright>
* </copyright>
*
* $Id$
*/
package kdm.source.util;
import java.util.List;
import kdm.core.Element;
import kdm.core.KDMEntity;
import kdm.core.KDMRelationship;
import kdm.core.ModelElement;
import kdm.kdm.KDMFramework;
import kdm.kdm.KDMModel;
import kdm.source.*;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.EObject;
/**
* <!-- begin-user-doc -->
* The <b>Switch</b> for the model's inheritance hierarchy.
* It supports the call {@link #doSwitch(EObject) doSwitch(object)}
* to invoke the <code>caseXXX</code> method for each class of the model,
* starting with the actual class of the object
* and proceeding up the inheritance hierarchy
* until a non-null result is returned,
* which is the result of the switch.
* <!-- end-user-doc -->
* @see kdm.source.SourcePackage
* @generated
*/
public class SourceSwitch<T> {
/**
* The cached model package
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected static SourcePackage modelPackage;
/**
* Creates an instance of the switch.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public SourceSwitch() {
if (modelPackage == null) {
modelPackage = SourcePackage.eINSTANCE;
}
}
/**
* Calls <code>caseXXX</code> for each class of the model until one returns a non null result; it yields that result.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the first non-null result returned by a <code>caseXXX</code> call.
* @generated
*/
public T doSwitch(EObject theEObject) {
return doSwitch(theEObject.eClass(), theEObject);
}
/**
* Calls <code>caseXXX</code> for each class of the model until one returns a non null result; it yields that result.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the first non-null result returned by a <code>caseXXX</code> call.
* @generated
*/
protected T doSwitch(EClass theEClass, EObject theEObject) {
if (theEClass.eContainer() == modelPackage) {
return doSwitch(theEClass.getClassifierID(), theEObject);
}
else {
List<EClass> eSuperTypes = theEClass.getESuperTypes();
return
eSuperTypes.isEmpty() ?
defaultCase(theEObject) :
doSwitch(eSuperTypes.get(0), theEObject);
}
}
/**
* Calls <code>caseXXX</code> for each class of the model until one returns a non null result; it yields that result.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the first non-null result returned by a <code>caseXXX</code> call.
* @generated
*/
protected T doSwitch(int classifierID, EObject theEObject) {
switch (classifierID) {
case SourcePackage.SOURCE_REF: {
SourceRef sourceRef = (SourceRef)theEObject;
T result = caseSourceRef(sourceRef);
if (result == null) result = caseElement(sourceRef);
if (result == null) result = defaultCase(theEObject);
return result;
}
case SourcePackage.SOURCE_REGION: {
SourceRegion sourceRegion = (SourceRegion)theEObject;
T result = caseSourceRegion(sourceRegion);
if (result == null) result = caseElement(sourceRegion);
if (result == null) result = defaultCase(theEObject);
return result;
}
case SourcePackage.INVENTORY_MODEL: {
InventoryModel inventoryModel = (InventoryModel)theEObject;
T result = caseInventoryModel(inventoryModel);
if (result == null) result = caseKDMModel(inventoryModel);
if (result == null) result = caseKDMFramework(inventoryModel);
if (result == null) result = caseModelElement(inventoryModel);
if (result == null) result = caseElement(inventoryModel);
if (result == null) result = defaultCase(theEObject);
return result;
}
case SourcePackage.ABSTRACT_INVENTORY_ELEMENT: {
AbstractInventoryElement abstractInventoryElement = (AbstractInventoryElement)theEObject;
T result = caseAbstractInventoryElement(abstractInventoryElement);
if (result == null) result = caseKDMEntity(abstractInventoryElement);
if (result == null) result = caseModelElement(abstractInventoryElement);
if (result == null) result = caseElement(abstractInventoryElement);
if (result == null) result = defaultCase(theEObject);
return result;
}
case SourcePackage.INVENTORY_ITEM: {
InventoryItem inventoryItem = (InventoryItem)theEObject;
T result = caseInventoryItem(inventoryItem);
if (result == null) result = caseAbstractInventoryElement(inventoryItem);
if (result == null) result = caseKDMEntity(inventoryItem);
if (result == null) result = caseModelElement(inventoryItem);
if (result == null) result = caseElement(inventoryItem);
if (result == null) result = defaultCase(theEObject);
return result;
}
case SourcePackage.SOURCE_FILE: {
SourceFile sourceFile = (SourceFile)theEObject;
T result = caseSourceFile(sourceFile);
if (result == null) result = caseInventoryItem(sourceFile);
if (result == null) result = caseAbstractInventoryElement(sourceFile);
if (result == null) result = caseKDMEntity(sourceFile);
if (result == null) result = caseModelElement(sourceFile);
if (result == null) result = caseElement(sourceFile);
if (result == null) result = defaultCase(theEObject);
return result;
}
case SourcePackage.IMAGE: {
Image image = (Image)theEObject;
T result = caseImage(image);
if (result == null) result = caseInventoryItem(image);
if (result == null) result = caseAbstractInventoryElement(image);
if (result == null) result = caseKDMEntity(image);
if (result == null) result = caseModelElement(image);
if (result == null) result = caseElement(image);
if (result == null) result = defaultCase(theEObject);
return result;
}
case SourcePackage.RESOURCE_DESCRIPTION: {
ResourceDescription resourceDescription = (ResourceDescription)theEObject;
T result = caseResourceDescription(resourceDescription);
if (result == null) result = caseInventoryItem(resourceDescription);
if (result == null) result = caseAbstractInventoryElement(resourceDescription);
if (result == null) result = caseKDMEntity(resourceDescription);
if (result == null) result = caseModelElement(resourceDescription);
if (result == null) result = caseElement(resourceDescription);
if (result == null) result = defaultCase(theEObject);
return result;
}
case SourcePackage.CONFIGURATION: {
Configuration configuration = (Configuration)theEObject;
T result = caseConfiguration(configuration);
if (result == null) result = caseInventoryItem(configuration);
if (result == null) result = caseAbstractInventoryElement(configuration);
if (result == null) result = caseKDMEntity(configuration);
if (result == null) result = caseModelElement(configuration);
if (result == null) result = caseElement(configuration);
if (result == null) result = defaultCase(theEObject);
return result;
}
case SourcePackage.INVENTORY_CONTAINER: {
InventoryContainer inventoryContainer = (InventoryContainer)theEObject;
T result = caseInventoryContainer(inventoryContainer);
if (result == null) result = caseAbstractInventoryElement(inventoryContainer);
if (result == null) result = caseKDMEntity(inventoryContainer);
if (result == null) result = caseModelElement(inventoryContainer);
if (result == null) result = caseElement(inventoryContainer);
if (result == null) result = defaultCase(theEObject);
return result;
}
case SourcePackage.DIRECTORY: {
Directory directory = (Directory)theEObject;
T result = caseDirectory(directory);
if (result == null) result = caseInventoryContainer(directory);
if (result == null) result = caseAbstractInventoryElement(directory);
if (result == null) result = caseKDMEntity(directory);
if (result == null) result = caseModelElement(directory);
if (result == null) result = caseElement(directory);
if (result == null) result = defaultCase(theEObject);
return result;
}
case SourcePackage.PROJECT: {
Project project = (Project)theEObject;
T result = caseProject(project);
if (result == null) result = caseInventoryContainer(project);
if (result == null) result = caseAbstractInventoryElement(project);
if (result == null) result = caseKDMEntity(project);
if (result == null) result = caseModelElement(project);
if (result == null) result = caseElement(project);
if (result == null) result = defaultCase(theEObject);
return result;
}
case SourcePackage.ABSTRACT_INVENTORY_RELATIONSHIP: {
AbstractInventoryRelationship abstractInventoryRelationship = (AbstractInventoryRelationship)theEObject;
T result = caseAbstractInventoryRelationship(abstractInventoryRelationship);
if (result == null) result = caseKDMRelationship(abstractInventoryRelationship);
if (result == null) result = caseModelElement(abstractInventoryRelationship);
if (result == null) result = caseElement(abstractInventoryRelationship);
if (result == null) result = defaultCase(theEObject);
return result;
}
case SourcePackage.BINARY_FILE: {
BinaryFile binaryFile = (BinaryFile)theEObject;
T result = caseBinaryFile(binaryFile);
if (result == null) result = caseInventoryItem(binaryFile);
if (result == null) result = caseAbstractInventoryElement(binaryFile);
if (result == null) result = caseKDMEntity(binaryFile);
if (result == null) result = caseModelElement(binaryFile);
if (result == null) result = caseElement(binaryFile);
if (result == null) result = defaultCase(theEObject);
return result;
}
case SourcePackage.EXECUTABLE_FILE: {
ExecutableFile executableFile = (ExecutableFile)theEObject;
T result = caseExecutableFile(executableFile);
if (result == null) result = caseInventoryItem(executableFile);
if (result == null) result = caseAbstractInventoryElement(executableFile);
if (result == null) result = caseKDMEntity(executableFile);
if (result == null) result = caseModelElement(executableFile);
if (result == null) result = caseElement(executableFile);
if (result == null) result = defaultCase(theEObject);
return result;
}
case SourcePackage.DEPENDS_ON: {
DependsOn dependsOn = (DependsOn)theEObject;
T result = caseDependsOn(dependsOn);
if (result == null) result = caseAbstractInventoryRelationship(dependsOn);
if (result == null) result = caseKDMRelationship(dependsOn);
if (result == null) result = caseModelElement(dependsOn);
if (result == null) result = caseElement(dependsOn);
if (result == null) result = defaultCase(theEObject);
return result;
}
case SourcePackage.INVENTORY_ELEMENT: {
InventoryElement inventoryElement = (InventoryElement)theEObject;
T result = caseInventoryElement(inventoryElement);
if (result == null) result = caseAbstractInventoryElement(inventoryElement);
if (result == null) result = caseKDMEntity(inventoryElement);
if (result == null) result = caseModelElement(inventoryElement);
if (result == null) result = caseElement(inventoryElement);
if (result == null) result = defaultCase(theEObject);
return result;
}
case SourcePackage.INVENTORY_RELATIONSHIP: {
InventoryRelationship inventoryRelationship = (InventoryRelationship)theEObject;
T result = caseInventoryRelationship(inventoryRelationship);
if (result == null) result = caseAbstractInventoryRelationship(inventoryRelationship);
if (result == null) result = caseKDMRelationship(inventoryRelationship);
if (result == null) result = caseModelElement(inventoryRelationship);
if (result == null) result = caseElement(inventoryRelationship);
if (result == null) result = defaultCase(theEObject);
return result;
}
default: return defaultCase(theEObject);
}
}
/**
* Returns the result of interpreting the object as an instance of '<em>Ref</em>'.
* <!-- begin-user-doc -->
* This implementation returns null;
* returning a non-null result will terminate the switch.
* <!-- end-user-doc -->
* @param object the target of the switch.
* @return the result of interpreting the object as an instance of '<em>Ref</em>'.
* @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)
* @generated
*/
public T caseSourceRef(SourceRef object) {
return null;
}
/**
* Returns the result of interpreting the object as an instance of '<em>Region</em>'.
* <!-- begin-user-doc -->
* This implementation returns null;
* returning a non-null result will terminate the switch.
* <!-- end-user-doc -->
* @param object the target of the switch.
* @return the result of interpreting the object as an instance of '<em>Region</em>'.
* @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)
* @generated
*/
public T caseSourceRegion(SourceRegion object) {
return null;
}
/**
* Returns the result of interpreting the object as an instance of '<em>Inventory Model</em>'.
* <!-- begin-user-doc -->
* This implementation returns null;
* returning a non-null result will terminate the switch.
* <!-- end-user-doc -->
* @param object the target of the switch.
* @return the result of interpreting the object as an instance of '<em>Inventory Model</em>'.
* @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)
* @generated
*/
public T caseInventoryModel(InventoryModel object) {
return null;
}
/**
* Returns the result of interpreting the object as an instance of '<em>Abstract Inventory Element</em>'.
* <!-- begin-user-doc -->
* This implementation returns null;
* returning a non-null result will terminate the switch.
* <!-- end-user-doc -->
* @param object the target of the switch.
* @return the result of interpreting the object as an instance of '<em>Abstract Inventory Element</em>'.
* @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)
* @generated
*/
public T caseAbstractInventoryElement(AbstractInventoryElement object) {
return null;
}
/**
* Returns the result of interpreting the object as an instance of '<em>Inventory Item</em>'.
* <!-- begin-user-doc -->
* This implementation returns null;
* returning a non-null result will terminate the switch.
* <!-- end-user-doc -->
* @param object the target of the switch.
* @return the result of interpreting the object as an instance of '<em>Inventory Item</em>'.
* @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)
* @generated
*/
public T caseInventoryItem(InventoryItem object) {
return null;
}
/**
* Returns the result of interpreting the object as an instance of '<em>File</em>'.
* <!-- begin-user-doc -->
* This implementation returns null;
* returning a non-null result will terminate the switch.
* <!-- end-user-doc -->
* @param object the target of the switch.
* @return the result of interpreting the object as an instance of '<em>File</em>'.
* @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)
* @generated
*/
public T caseSourceFile(SourceFile object) {
return null;
}
/**
* Returns the result of interpreting the object as an instance of '<em>Image</em>'.
* <!-- begin-user-doc -->
* This implementation returns null;
* returning a non-null result will terminate the switch.
* <!-- end-user-doc -->
* @param object the target of the switch.
* @return the result of interpreting the object as an instance of '<em>Image</em>'.
* @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)
* @generated
*/
public T caseImage(Image object) {
return null;
}
/**
* Returns the result of interpreting the object as an instance of '<em>Resource Description</em>'.
* <!-- begin-user-doc -->
* This implementation returns null;
* returning a non-null result will terminate the switch.
* <!-- end-user-doc -->
* @param object the target of the switch.
* @return the result of interpreting the object as an instance of '<em>Resource Description</em>'.
* @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)
* @generated
*/
public T caseResourceDescription(ResourceDescription object) {
return null;
}
/**
* Returns the result of interpreting the object as an instance of '<em>Configuration</em>'.
* <!-- begin-user-doc -->
* This implementation returns null;
* returning a non-null result will terminate the switch.
* <!-- end-user-doc -->
* @param object the target of the switch.
* @return the result of interpreting the object as an instance of '<em>Configuration</em>'.
* @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)
* @generated
*/
public T caseConfiguration(Configuration object) {
return null;
}
/**
* Returns the result of interpreting the object as an instance of '<em>Inventory Container</em>'.
* <!-- begin-user-doc -->
* This implementation returns null;
* returning a non-null result will terminate the switch.
* <!-- end-user-doc -->
* @param object the target of the switch.
* @return the result of interpreting the object as an instance of '<em>Inventory Container</em>'.
* @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)
* @generated
*/
public T caseInventoryContainer(InventoryContainer object) {
return null;
}
/**
* Returns the result of interpreting the object as an instance of '<em>Directory</em>'.
* <!-- begin-user-doc -->
* This implementation returns null;
* returning a non-null result will terminate the switch.
* <!-- end-user-doc -->
* @param object the target of the switch.
* @return the result of interpreting the object as an instance of '<em>Directory</em>'.
* @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)
* @generated
*/
public T caseDirectory(Directory object) {
return null;
}
/**
* Returns the result of interpreting the object as an instance of '<em>Project</em>'.
* <!-- begin-user-doc -->
* This implementation returns null;
* returning a non-null result will terminate the switch.
* <!-- end-user-doc -->
* @param object the target of the switch.
* @return the result of interpreting the object as an instance of '<em>Project</em>'.
* @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)
* @generated
*/
public T caseProject(Project object) {
return null;
}
/**
* Returns the result of interpreting the object as an instance of '<em>Abstract Inventory Relationship</em>'.
* <!-- begin-user-doc -->
* This implementation returns null;
* returning a non-null result will terminate the switch.
* <!-- end-user-doc -->
* @param object the target of the switch.
* @return the result of interpreting the object as an instance of '<em>Abstract Inventory Relationship</em>'.
* @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)
* @generated
*/
public T caseAbstractInventoryRelationship(AbstractInventoryRelationship object) {
return null;
}
/**
* Returns the result of interpreting the object as an instance of '<em>Binary File</em>'.
* <!-- begin-user-doc -->
* This implementation returns null;
* returning a non-null result will terminate the switch.
* <!-- end-user-doc -->
* @param object the target of the switch.
* @return the result of interpreting the object as an instance of '<em>Binary File</em>'.
* @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)
* @generated
*/
public T caseBinaryFile(BinaryFile object) {
return null;
}
/**
* Returns the result of interpreting the object as an instance of '<em>Executable File</em>'.
* <!-- begin-user-doc -->
* This implementation returns null;
* returning a non-null result will terminate the switch.
* <!-- end-user-doc -->
* @param object the target of the switch.
* @return the result of interpreting the object as an instance of '<em>Executable File</em>'.
* @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)
* @generated
*/
public T caseExecutableFile(ExecutableFile object) {
return null;
}
/**
* Returns the result of interpreting the object as an instance of '<em>Depends On</em>'.
* <!-- begin-user-doc -->
* This implementation returns null;
* returning a non-null result will terminate the switch.
* <!-- end-user-doc -->
* @param object the target of the switch.
* @return the result of interpreting the object as an instance of '<em>Depends On</em>'.
* @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)
* @generated
*/
public T caseDependsOn(DependsOn object) {
return null;
}
/**
* Returns the result of interpreting the object as an instance of '<em>Inventory Element</em>'.
* <!-- begin-user-doc -->
* This implementation returns null;
* returning a non-null result will terminate the switch.
* <!-- end-user-doc -->
* @param object the target of the switch.
* @return the result of interpreting the object as an instance of '<em>Inventory Element</em>'.
* @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)
* @generated
*/
public T caseInventoryElement(InventoryElement object) {
return null;
}
/**
* Returns the result of interpreting the object as an instance of '<em>Inventory Relationship</em>'.
* <!-- begin-user-doc -->
* This implementation returns null;
* returning a non-null result will terminate the switch.
* <!-- end-user-doc -->
* @param object the target of the switch.
* @return the result of interpreting the object as an instance of '<em>Inventory Relationship</em>'.
* @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)
* @generated
*/
public T caseInventoryRelationship(InventoryRelationship object) {
return null;
}
/**
* Returns the result of interpreting the object as an instance of '<em>Element</em>'.
* <!-- begin-user-doc -->
* This implementation returns null;
* returning a non-null result will terminate the switch.
* <!-- end-user-doc -->
* @param object the target of the switch.
* @return the result of interpreting the object as an instance of '<em>Element</em>'.
* @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)
* @generated
*/
public T caseElement(Element object) {
return null;
}
/**
* Returns the result of interpreting the object as an instance of '<em>Model Element</em>'.
* <!-- begin-user-doc -->
* This implementation returns null;
* returning a non-null result will terminate the switch.
* <!-- end-user-doc -->
* @param object the target of the switch.
* @return the result of interpreting the object as an instance of '<em>Model Element</em>'.
* @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)
* @generated
*/
public T caseModelElement(ModelElement object) {
return null;
}
/**
* Returns the result of interpreting the object as an instance of '<em>KDM Framework</em>'.
* <!-- begin-user-doc -->
* This implementation returns null;
* returning a non-null result will terminate the switch.
* <!-- end-user-doc -->
* @param object the target of the switch.
* @return the result of interpreting the object as an instance of '<em>KDM Framework</em>'.
* @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)
* @generated
*/
public T caseKDMFramework(KDMFramework object) {
return null;
}
/**
* Returns the result of interpreting the object as an instance of '<em>KDM Model</em>'.
* <!-- begin-user-doc -->
* This implementation returns null;
* returning a non-null result will terminate the switch.
* <!-- end-user-doc -->
* @param object the target of the switch.
* @return the result of interpreting the object as an instance of '<em>KDM Model</em>'.
* @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)
* @generated
*/
public T caseKDMModel(KDMModel object) {
return null;
}
/**
* Returns the result of interpreting the object as an instance of '<em>KDM Entity</em>'.
* <!-- begin-user-doc -->
* This implementation returns null;
* returning a non-null result will terminate the switch.
* <!-- end-user-doc -->
* @param object the target of the switch.
* @return the result of interpreting the object as an instance of '<em>KDM Entity</em>'.
* @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)
* @generated
*/
public T caseKDMEntity(KDMEntity object) {
return null;
}
/**
* Returns the result of interpreting the object as an instance of '<em>KDM Relationship</em>'.
* <!-- begin-user-doc -->
* This implementation returns null;
* returning a non-null result will terminate the switch.
* <!-- end-user-doc -->
* @param object the target of the switch.
* @return the result of interpreting the object as an instance of '<em>KDM Relationship</em>'.
* @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)
* @generated
*/
public T caseKDMRelationship(KDMRelationship object) {
return null;
}
/**
* Returns the result of interpreting the object as an instance of '<em>EObject</em>'.
* <!-- begin-user-doc -->
* This implementation returns null;
* returning a non-null result will terminate the switch, but this is the last case anyway.
* <!-- end-user-doc -->
* @param object the target of the switch.
* @return the result of interpreting the object as an instance of '<em>EObject</em>'.
* @see #doSwitch(org.eclipse.emf.ecore.EObject)
* @generated
*/
public T defaultCase(EObject object) {
return null;
}
} //SourceSwitch
| UTF-8 | Java | 25,531 | java | SourceSwitch.java | Java | []
| null | []
| /**
* <copyright>
* </copyright>
*
* $Id$
*/
package kdm.source.util;
import java.util.List;
import kdm.core.Element;
import kdm.core.KDMEntity;
import kdm.core.KDMRelationship;
import kdm.core.ModelElement;
import kdm.kdm.KDMFramework;
import kdm.kdm.KDMModel;
import kdm.source.*;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.EObject;
/**
* <!-- begin-user-doc -->
* The <b>Switch</b> for the model's inheritance hierarchy.
* It supports the call {@link #doSwitch(EObject) doSwitch(object)}
* to invoke the <code>caseXXX</code> method for each class of the model,
* starting with the actual class of the object
* and proceeding up the inheritance hierarchy
* until a non-null result is returned,
* which is the result of the switch.
* <!-- end-user-doc -->
* @see kdm.source.SourcePackage
* @generated
*/
public class SourceSwitch<T> {
/**
* The cached model package
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected static SourcePackage modelPackage;
/**
* Creates an instance of the switch.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public SourceSwitch() {
if (modelPackage == null) {
modelPackage = SourcePackage.eINSTANCE;
}
}
/**
* Calls <code>caseXXX</code> for each class of the model until one returns a non null result; it yields that result.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the first non-null result returned by a <code>caseXXX</code> call.
* @generated
*/
public T doSwitch(EObject theEObject) {
return doSwitch(theEObject.eClass(), theEObject);
}
/**
* Calls <code>caseXXX</code> for each class of the model until one returns a non null result; it yields that result.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the first non-null result returned by a <code>caseXXX</code> call.
* @generated
*/
protected T doSwitch(EClass theEClass, EObject theEObject) {
if (theEClass.eContainer() == modelPackage) {
return doSwitch(theEClass.getClassifierID(), theEObject);
}
else {
List<EClass> eSuperTypes = theEClass.getESuperTypes();
return
eSuperTypes.isEmpty() ?
defaultCase(theEObject) :
doSwitch(eSuperTypes.get(0), theEObject);
}
}
/**
* Calls <code>caseXXX</code> for each class of the model until one returns a non null result; it yields that result.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the first non-null result returned by a <code>caseXXX</code> call.
* @generated
*/
protected T doSwitch(int classifierID, EObject theEObject) {
switch (classifierID) {
case SourcePackage.SOURCE_REF: {
SourceRef sourceRef = (SourceRef)theEObject;
T result = caseSourceRef(sourceRef);
if (result == null) result = caseElement(sourceRef);
if (result == null) result = defaultCase(theEObject);
return result;
}
case SourcePackage.SOURCE_REGION: {
SourceRegion sourceRegion = (SourceRegion)theEObject;
T result = caseSourceRegion(sourceRegion);
if (result == null) result = caseElement(sourceRegion);
if (result == null) result = defaultCase(theEObject);
return result;
}
case SourcePackage.INVENTORY_MODEL: {
InventoryModel inventoryModel = (InventoryModel)theEObject;
T result = caseInventoryModel(inventoryModel);
if (result == null) result = caseKDMModel(inventoryModel);
if (result == null) result = caseKDMFramework(inventoryModel);
if (result == null) result = caseModelElement(inventoryModel);
if (result == null) result = caseElement(inventoryModel);
if (result == null) result = defaultCase(theEObject);
return result;
}
case SourcePackage.ABSTRACT_INVENTORY_ELEMENT: {
AbstractInventoryElement abstractInventoryElement = (AbstractInventoryElement)theEObject;
T result = caseAbstractInventoryElement(abstractInventoryElement);
if (result == null) result = caseKDMEntity(abstractInventoryElement);
if (result == null) result = caseModelElement(abstractInventoryElement);
if (result == null) result = caseElement(abstractInventoryElement);
if (result == null) result = defaultCase(theEObject);
return result;
}
case SourcePackage.INVENTORY_ITEM: {
InventoryItem inventoryItem = (InventoryItem)theEObject;
T result = caseInventoryItem(inventoryItem);
if (result == null) result = caseAbstractInventoryElement(inventoryItem);
if (result == null) result = caseKDMEntity(inventoryItem);
if (result == null) result = caseModelElement(inventoryItem);
if (result == null) result = caseElement(inventoryItem);
if (result == null) result = defaultCase(theEObject);
return result;
}
case SourcePackage.SOURCE_FILE: {
SourceFile sourceFile = (SourceFile)theEObject;
T result = caseSourceFile(sourceFile);
if (result == null) result = caseInventoryItem(sourceFile);
if (result == null) result = caseAbstractInventoryElement(sourceFile);
if (result == null) result = caseKDMEntity(sourceFile);
if (result == null) result = caseModelElement(sourceFile);
if (result == null) result = caseElement(sourceFile);
if (result == null) result = defaultCase(theEObject);
return result;
}
case SourcePackage.IMAGE: {
Image image = (Image)theEObject;
T result = caseImage(image);
if (result == null) result = caseInventoryItem(image);
if (result == null) result = caseAbstractInventoryElement(image);
if (result == null) result = caseKDMEntity(image);
if (result == null) result = caseModelElement(image);
if (result == null) result = caseElement(image);
if (result == null) result = defaultCase(theEObject);
return result;
}
case SourcePackage.RESOURCE_DESCRIPTION: {
ResourceDescription resourceDescription = (ResourceDescription)theEObject;
T result = caseResourceDescription(resourceDescription);
if (result == null) result = caseInventoryItem(resourceDescription);
if (result == null) result = caseAbstractInventoryElement(resourceDescription);
if (result == null) result = caseKDMEntity(resourceDescription);
if (result == null) result = caseModelElement(resourceDescription);
if (result == null) result = caseElement(resourceDescription);
if (result == null) result = defaultCase(theEObject);
return result;
}
case SourcePackage.CONFIGURATION: {
Configuration configuration = (Configuration)theEObject;
T result = caseConfiguration(configuration);
if (result == null) result = caseInventoryItem(configuration);
if (result == null) result = caseAbstractInventoryElement(configuration);
if (result == null) result = caseKDMEntity(configuration);
if (result == null) result = caseModelElement(configuration);
if (result == null) result = caseElement(configuration);
if (result == null) result = defaultCase(theEObject);
return result;
}
case SourcePackage.INVENTORY_CONTAINER: {
InventoryContainer inventoryContainer = (InventoryContainer)theEObject;
T result = caseInventoryContainer(inventoryContainer);
if (result == null) result = caseAbstractInventoryElement(inventoryContainer);
if (result == null) result = caseKDMEntity(inventoryContainer);
if (result == null) result = caseModelElement(inventoryContainer);
if (result == null) result = caseElement(inventoryContainer);
if (result == null) result = defaultCase(theEObject);
return result;
}
case SourcePackage.DIRECTORY: {
Directory directory = (Directory)theEObject;
T result = caseDirectory(directory);
if (result == null) result = caseInventoryContainer(directory);
if (result == null) result = caseAbstractInventoryElement(directory);
if (result == null) result = caseKDMEntity(directory);
if (result == null) result = caseModelElement(directory);
if (result == null) result = caseElement(directory);
if (result == null) result = defaultCase(theEObject);
return result;
}
case SourcePackage.PROJECT: {
Project project = (Project)theEObject;
T result = caseProject(project);
if (result == null) result = caseInventoryContainer(project);
if (result == null) result = caseAbstractInventoryElement(project);
if (result == null) result = caseKDMEntity(project);
if (result == null) result = caseModelElement(project);
if (result == null) result = caseElement(project);
if (result == null) result = defaultCase(theEObject);
return result;
}
case SourcePackage.ABSTRACT_INVENTORY_RELATIONSHIP: {
AbstractInventoryRelationship abstractInventoryRelationship = (AbstractInventoryRelationship)theEObject;
T result = caseAbstractInventoryRelationship(abstractInventoryRelationship);
if (result == null) result = caseKDMRelationship(abstractInventoryRelationship);
if (result == null) result = caseModelElement(abstractInventoryRelationship);
if (result == null) result = caseElement(abstractInventoryRelationship);
if (result == null) result = defaultCase(theEObject);
return result;
}
case SourcePackage.BINARY_FILE: {
BinaryFile binaryFile = (BinaryFile)theEObject;
T result = caseBinaryFile(binaryFile);
if (result == null) result = caseInventoryItem(binaryFile);
if (result == null) result = caseAbstractInventoryElement(binaryFile);
if (result == null) result = caseKDMEntity(binaryFile);
if (result == null) result = caseModelElement(binaryFile);
if (result == null) result = caseElement(binaryFile);
if (result == null) result = defaultCase(theEObject);
return result;
}
case SourcePackage.EXECUTABLE_FILE: {
ExecutableFile executableFile = (ExecutableFile)theEObject;
T result = caseExecutableFile(executableFile);
if (result == null) result = caseInventoryItem(executableFile);
if (result == null) result = caseAbstractInventoryElement(executableFile);
if (result == null) result = caseKDMEntity(executableFile);
if (result == null) result = caseModelElement(executableFile);
if (result == null) result = caseElement(executableFile);
if (result == null) result = defaultCase(theEObject);
return result;
}
case SourcePackage.DEPENDS_ON: {
DependsOn dependsOn = (DependsOn)theEObject;
T result = caseDependsOn(dependsOn);
if (result == null) result = caseAbstractInventoryRelationship(dependsOn);
if (result == null) result = caseKDMRelationship(dependsOn);
if (result == null) result = caseModelElement(dependsOn);
if (result == null) result = caseElement(dependsOn);
if (result == null) result = defaultCase(theEObject);
return result;
}
case SourcePackage.INVENTORY_ELEMENT: {
InventoryElement inventoryElement = (InventoryElement)theEObject;
T result = caseInventoryElement(inventoryElement);
if (result == null) result = caseAbstractInventoryElement(inventoryElement);
if (result == null) result = caseKDMEntity(inventoryElement);
if (result == null) result = caseModelElement(inventoryElement);
if (result == null) result = caseElement(inventoryElement);
if (result == null) result = defaultCase(theEObject);
return result;
}
case SourcePackage.INVENTORY_RELATIONSHIP: {
InventoryRelationship inventoryRelationship = (InventoryRelationship)theEObject;
T result = caseInventoryRelationship(inventoryRelationship);
if (result == null) result = caseAbstractInventoryRelationship(inventoryRelationship);
if (result == null) result = caseKDMRelationship(inventoryRelationship);
if (result == null) result = caseModelElement(inventoryRelationship);
if (result == null) result = caseElement(inventoryRelationship);
if (result == null) result = defaultCase(theEObject);
return result;
}
default: return defaultCase(theEObject);
}
}
/**
* Returns the result of interpreting the object as an instance of '<em>Ref</em>'.
* <!-- begin-user-doc -->
* This implementation returns null;
* returning a non-null result will terminate the switch.
* <!-- end-user-doc -->
* @param object the target of the switch.
* @return the result of interpreting the object as an instance of '<em>Ref</em>'.
* @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)
* @generated
*/
public T caseSourceRef(SourceRef object) {
return null;
}
/**
* Returns the result of interpreting the object as an instance of '<em>Region</em>'.
* <!-- begin-user-doc -->
* This implementation returns null;
* returning a non-null result will terminate the switch.
* <!-- end-user-doc -->
* @param object the target of the switch.
* @return the result of interpreting the object as an instance of '<em>Region</em>'.
* @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)
* @generated
*/
public T caseSourceRegion(SourceRegion object) {
return null;
}
/**
* Returns the result of interpreting the object as an instance of '<em>Inventory Model</em>'.
* <!-- begin-user-doc -->
* This implementation returns null;
* returning a non-null result will terminate the switch.
* <!-- end-user-doc -->
* @param object the target of the switch.
* @return the result of interpreting the object as an instance of '<em>Inventory Model</em>'.
* @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)
* @generated
*/
public T caseInventoryModel(InventoryModel object) {
return null;
}
/**
* Returns the result of interpreting the object as an instance of '<em>Abstract Inventory Element</em>'.
* <!-- begin-user-doc -->
* This implementation returns null;
* returning a non-null result will terminate the switch.
* <!-- end-user-doc -->
* @param object the target of the switch.
* @return the result of interpreting the object as an instance of '<em>Abstract Inventory Element</em>'.
* @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)
* @generated
*/
public T caseAbstractInventoryElement(AbstractInventoryElement object) {
return null;
}
/**
* Returns the result of interpreting the object as an instance of '<em>Inventory Item</em>'.
* <!-- begin-user-doc -->
* This implementation returns null;
* returning a non-null result will terminate the switch.
* <!-- end-user-doc -->
* @param object the target of the switch.
* @return the result of interpreting the object as an instance of '<em>Inventory Item</em>'.
* @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)
* @generated
*/
public T caseInventoryItem(InventoryItem object) {
return null;
}
/**
* Returns the result of interpreting the object as an instance of '<em>File</em>'.
* <!-- begin-user-doc -->
* This implementation returns null;
* returning a non-null result will terminate the switch.
* <!-- end-user-doc -->
* @param object the target of the switch.
* @return the result of interpreting the object as an instance of '<em>File</em>'.
* @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)
* @generated
*/
public T caseSourceFile(SourceFile object) {
return null;
}
/**
* Returns the result of interpreting the object as an instance of '<em>Image</em>'.
* <!-- begin-user-doc -->
* This implementation returns null;
* returning a non-null result will terminate the switch.
* <!-- end-user-doc -->
* @param object the target of the switch.
* @return the result of interpreting the object as an instance of '<em>Image</em>'.
* @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)
* @generated
*/
public T caseImage(Image object) {
return null;
}
/**
* Returns the result of interpreting the object as an instance of '<em>Resource Description</em>'.
* <!-- begin-user-doc -->
* This implementation returns null;
* returning a non-null result will terminate the switch.
* <!-- end-user-doc -->
* @param object the target of the switch.
* @return the result of interpreting the object as an instance of '<em>Resource Description</em>'.
* @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)
* @generated
*/
public T caseResourceDescription(ResourceDescription object) {
return null;
}
/**
* Returns the result of interpreting the object as an instance of '<em>Configuration</em>'.
* <!-- begin-user-doc -->
* This implementation returns null;
* returning a non-null result will terminate the switch.
* <!-- end-user-doc -->
* @param object the target of the switch.
* @return the result of interpreting the object as an instance of '<em>Configuration</em>'.
* @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)
* @generated
*/
public T caseConfiguration(Configuration object) {
return null;
}
/**
* Returns the result of interpreting the object as an instance of '<em>Inventory Container</em>'.
* <!-- begin-user-doc -->
* This implementation returns null;
* returning a non-null result will terminate the switch.
* <!-- end-user-doc -->
* @param object the target of the switch.
* @return the result of interpreting the object as an instance of '<em>Inventory Container</em>'.
* @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)
* @generated
*/
public T caseInventoryContainer(InventoryContainer object) {
return null;
}
/**
* Returns the result of interpreting the object as an instance of '<em>Directory</em>'.
* <!-- begin-user-doc -->
* This implementation returns null;
* returning a non-null result will terminate the switch.
* <!-- end-user-doc -->
* @param object the target of the switch.
* @return the result of interpreting the object as an instance of '<em>Directory</em>'.
* @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)
* @generated
*/
public T caseDirectory(Directory object) {
return null;
}
/**
* Returns the result of interpreting the object as an instance of '<em>Project</em>'.
* <!-- begin-user-doc -->
* This implementation returns null;
* returning a non-null result will terminate the switch.
* <!-- end-user-doc -->
* @param object the target of the switch.
* @return the result of interpreting the object as an instance of '<em>Project</em>'.
* @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)
* @generated
*/
public T caseProject(Project object) {
return null;
}
/**
* Returns the result of interpreting the object as an instance of '<em>Abstract Inventory Relationship</em>'.
* <!-- begin-user-doc -->
* This implementation returns null;
* returning a non-null result will terminate the switch.
* <!-- end-user-doc -->
* @param object the target of the switch.
* @return the result of interpreting the object as an instance of '<em>Abstract Inventory Relationship</em>'.
* @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)
* @generated
*/
public T caseAbstractInventoryRelationship(AbstractInventoryRelationship object) {
return null;
}
/**
* Returns the result of interpreting the object as an instance of '<em>Binary File</em>'.
* <!-- begin-user-doc -->
* This implementation returns null;
* returning a non-null result will terminate the switch.
* <!-- end-user-doc -->
* @param object the target of the switch.
* @return the result of interpreting the object as an instance of '<em>Binary File</em>'.
* @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)
* @generated
*/
public T caseBinaryFile(BinaryFile object) {
return null;
}
/**
* Returns the result of interpreting the object as an instance of '<em>Executable File</em>'.
* <!-- begin-user-doc -->
* This implementation returns null;
* returning a non-null result will terminate the switch.
* <!-- end-user-doc -->
* @param object the target of the switch.
* @return the result of interpreting the object as an instance of '<em>Executable File</em>'.
* @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)
* @generated
*/
public T caseExecutableFile(ExecutableFile object) {
return null;
}
/**
* Returns the result of interpreting the object as an instance of '<em>Depends On</em>'.
* <!-- begin-user-doc -->
* This implementation returns null;
* returning a non-null result will terminate the switch.
* <!-- end-user-doc -->
* @param object the target of the switch.
* @return the result of interpreting the object as an instance of '<em>Depends On</em>'.
* @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)
* @generated
*/
public T caseDependsOn(DependsOn object) {
return null;
}
/**
* Returns the result of interpreting the object as an instance of '<em>Inventory Element</em>'.
* <!-- begin-user-doc -->
* This implementation returns null;
* returning a non-null result will terminate the switch.
* <!-- end-user-doc -->
* @param object the target of the switch.
* @return the result of interpreting the object as an instance of '<em>Inventory Element</em>'.
* @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)
* @generated
*/
public T caseInventoryElement(InventoryElement object) {
return null;
}
/**
* Returns the result of interpreting the object as an instance of '<em>Inventory Relationship</em>'.
* <!-- begin-user-doc -->
* This implementation returns null;
* returning a non-null result will terminate the switch.
* <!-- end-user-doc -->
* @param object the target of the switch.
* @return the result of interpreting the object as an instance of '<em>Inventory Relationship</em>'.
* @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)
* @generated
*/
public T caseInventoryRelationship(InventoryRelationship object) {
return null;
}
/**
* Returns the result of interpreting the object as an instance of '<em>Element</em>'.
* <!-- begin-user-doc -->
* This implementation returns null;
* returning a non-null result will terminate the switch.
* <!-- end-user-doc -->
* @param object the target of the switch.
* @return the result of interpreting the object as an instance of '<em>Element</em>'.
* @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)
* @generated
*/
public T caseElement(Element object) {
return null;
}
/**
* Returns the result of interpreting the object as an instance of '<em>Model Element</em>'.
* <!-- begin-user-doc -->
* This implementation returns null;
* returning a non-null result will terminate the switch.
* <!-- end-user-doc -->
* @param object the target of the switch.
* @return the result of interpreting the object as an instance of '<em>Model Element</em>'.
* @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)
* @generated
*/
public T caseModelElement(ModelElement object) {
return null;
}
/**
* Returns the result of interpreting the object as an instance of '<em>KDM Framework</em>'.
* <!-- begin-user-doc -->
* This implementation returns null;
* returning a non-null result will terminate the switch.
* <!-- end-user-doc -->
* @param object the target of the switch.
* @return the result of interpreting the object as an instance of '<em>KDM Framework</em>'.
* @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)
* @generated
*/
public T caseKDMFramework(KDMFramework object) {
return null;
}
/**
* Returns the result of interpreting the object as an instance of '<em>KDM Model</em>'.
* <!-- begin-user-doc -->
* This implementation returns null;
* returning a non-null result will terminate the switch.
* <!-- end-user-doc -->
* @param object the target of the switch.
* @return the result of interpreting the object as an instance of '<em>KDM Model</em>'.
* @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)
* @generated
*/
public T caseKDMModel(KDMModel object) {
return null;
}
/**
* Returns the result of interpreting the object as an instance of '<em>KDM Entity</em>'.
* <!-- begin-user-doc -->
* This implementation returns null;
* returning a non-null result will terminate the switch.
* <!-- end-user-doc -->
* @param object the target of the switch.
* @return the result of interpreting the object as an instance of '<em>KDM Entity</em>'.
* @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)
* @generated
*/
public T caseKDMEntity(KDMEntity object) {
return null;
}
/**
* Returns the result of interpreting the object as an instance of '<em>KDM Relationship</em>'.
* <!-- begin-user-doc -->
* This implementation returns null;
* returning a non-null result will terminate the switch.
* <!-- end-user-doc -->
* @param object the target of the switch.
* @return the result of interpreting the object as an instance of '<em>KDM Relationship</em>'.
* @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)
* @generated
*/
public T caseKDMRelationship(KDMRelationship object) {
return null;
}
/**
* Returns the result of interpreting the object as an instance of '<em>EObject</em>'.
* <!-- begin-user-doc -->
* This implementation returns null;
* returning a non-null result will terminate the switch, but this is the last case anyway.
* <!-- end-user-doc -->
* @param object the target of the switch.
* @return the result of interpreting the object as an instance of '<em>EObject</em>'.
* @see #doSwitch(org.eclipse.emf.ecore.EObject)
* @generated
*/
public T defaultCase(EObject object) {
return null;
}
} //SourceSwitch
| 25,531 | 0.699855 | 0.699816 | 657 | 37.85997 | 29.23695 | 118 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.086758 | false | false | 13 |
5da573bbad63f29a5511fdcd319c817549d09cc6 | 721,554,561,692 | 914f44d6ced55c018298b9ae85fbff30167f8060 | /src/main/java/authorization/project/service/impl/AccountService.java | 2be55ded28bfc137fae6e1cf97a79fa1e00633e0 | []
| no_license | savelascod/authorizer_standalone | https://github.com/savelascod/authorizer_standalone | 1f784daf54a62743d0ca49ce228b7fbae99e81bc | 1124efde49e62e8ec57028119e7b5eec4502a924 | refs/heads/master | 2023-03-23T10:01:28.186000 | 2021-03-16T21:06:34 | 2021-03-16T21:06:34 | 348,493,698 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package authorization.project.service.impl;
import authorization.project.constant.AccountError;
import authorization.project.dto.domain.AccountDto;
import authorization.project.exception.BusinessException;
import authorization.project.persistence.entity.AccountEntity;
import authorization.project.persistence.repository.IAccountRepository;
import authorization.project.service.contract.IAccountService;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
/**
* Service implementation of {@link IAccountService}
*
* @version 1.0
* @since 1.0
*/
public class AccountService implements IAccountService {
/**
* Repository class to perform operations in ACCOUNT ENTITIES
*/
private final IAccountRepository accountRepository;
/**
* Constructor with autowired dependencies
*/
public AccountService(IAccountRepository accountRepository) {
this.accountRepository = accountRepository;
}
/**
* {@inheritDoc}
*/
@Override
public boolean isAccountInitialized() {
return accountRepository.count() > 0;
}
/**
* {@inheritDoc}
*/
@Override
public List<BusinessException> createAccount(AccountDto accountDto) {
List<BusinessException> businessErrors = new ArrayList<>();
if (isAccountInitialized()) {
businessErrors.add(new BusinessException(AccountError.ERROR_0.getMessage()));
} else {
accountRepository.save(AccountEntity.builder()
.activeCard(accountDto.getActiveCard())
.availableLimit(accountDto.getAvailableLimit()).build());
}
return businessErrors;
}
/**
* {@inheritDoc}
*/
@Override
public Optional<AccountDto> getAccountStatus() {
Optional<AccountEntity> accountEntity = accountRepository.findFirstByIdIsNotNull();
return accountEntity.map(entity ->
AccountDto.builder().activeCard(entity.getActiveCard()).availableLimit(entity.getAvailableLimit()).build());
}
/**
* {@inheritDoc}
*/
@Override
public boolean isCardActive() {
Optional<AccountDto> accountDto = getAccountStatus();
return accountDto.isPresent() && accountDto.get().getActiveCard();
}
/**
* {@inheritDoc}
*/
@Override
public Optional<Integer> getAccountId() {
return accountRepository.findFirstByIdIsNotNull().map(accountEntity ->
Optional.of(accountEntity.getId())).orElse(Optional.empty());
}
}
| UTF-8 | Java | 2,560 | java | AccountService.java | Java | []
| null | []
| package authorization.project.service.impl;
import authorization.project.constant.AccountError;
import authorization.project.dto.domain.AccountDto;
import authorization.project.exception.BusinessException;
import authorization.project.persistence.entity.AccountEntity;
import authorization.project.persistence.repository.IAccountRepository;
import authorization.project.service.contract.IAccountService;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
/**
* Service implementation of {@link IAccountService}
*
* @version 1.0
* @since 1.0
*/
public class AccountService implements IAccountService {
/**
* Repository class to perform operations in ACCOUNT ENTITIES
*/
private final IAccountRepository accountRepository;
/**
* Constructor with autowired dependencies
*/
public AccountService(IAccountRepository accountRepository) {
this.accountRepository = accountRepository;
}
/**
* {@inheritDoc}
*/
@Override
public boolean isAccountInitialized() {
return accountRepository.count() > 0;
}
/**
* {@inheritDoc}
*/
@Override
public List<BusinessException> createAccount(AccountDto accountDto) {
List<BusinessException> businessErrors = new ArrayList<>();
if (isAccountInitialized()) {
businessErrors.add(new BusinessException(AccountError.ERROR_0.getMessage()));
} else {
accountRepository.save(AccountEntity.builder()
.activeCard(accountDto.getActiveCard())
.availableLimit(accountDto.getAvailableLimit()).build());
}
return businessErrors;
}
/**
* {@inheritDoc}
*/
@Override
public Optional<AccountDto> getAccountStatus() {
Optional<AccountEntity> accountEntity = accountRepository.findFirstByIdIsNotNull();
return accountEntity.map(entity ->
AccountDto.builder().activeCard(entity.getActiveCard()).availableLimit(entity.getAvailableLimit()).build());
}
/**
* {@inheritDoc}
*/
@Override
public boolean isCardActive() {
Optional<AccountDto> accountDto = getAccountStatus();
return accountDto.isPresent() && accountDto.get().getActiveCard();
}
/**
* {@inheritDoc}
*/
@Override
public Optional<Integer> getAccountId() {
return accountRepository.findFirstByIdIsNotNull().map(accountEntity ->
Optional.of(accountEntity.getId())).orElse(Optional.empty());
}
}
| 2,560 | 0.678125 | 0.675781 | 86 | 28.767443 | 28.418661 | 124 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.255814 | false | false | 13 |
f07c193f19a3ef6f8e209c6a75ff52b8656d08e2 | 9,277,129,418,899 | 86fcf49fbaf44d5541f97b8d865c1b1f0f441c3c | /src/us/parr/bookish/entity/BookDef.java | 3ba58483f7c6cbe19938754df54a7f916dacd9cf | [
"MIT"
]
| permissive | parrt/bookish | https://github.com/parrt/bookish | 62f06f0390400297ad408320e22f9225d4c8398f | 10420b04a17368ae18682ecd2a41ab60e5b74d43 | refs/heads/master | 2022-07-21T15:53:48.933000 | 2022-06-19T17:26:20 | 2022-06-19T17:26:20 | 118,663,296 | 466 | 35 | MIT | false | 2022-06-06T03:20:18 | 2018-01-23T20:09:41 | 2022-05-30T07:51:27 | 2022-06-05T20:57:10 | 1,721 | 422 | 27 | 1 | Java | false | false | package us.parr.bookish.entity;
import us.parr.bookish.parse.BookishParser;
public class BookDef extends EntityWithScope {
public BookDef(int index,
BookishParser.AttrsContext attrsCtx,
EntityWithScope enclosingScope)
{
super(index, attrsCtx, enclosingScope);
}
}
| UTF-8 | Java | 303 | java | BookDef.java | Java | []
| null | []
| package us.parr.bookish.entity;
import us.parr.bookish.parse.BookishParser;
public class BookDef extends EntityWithScope {
public BookDef(int index,
BookishParser.AttrsContext attrsCtx,
EntityWithScope enclosingScope)
{
super(index, attrsCtx, enclosingScope);
}
}
| 303 | 0.719472 | 0.719472 | 12 | 24.25 | 20.712818 | 52 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.166667 | false | false | 13 |
b34f762ec82287e01e8b8192530b90d6c2b5957a | 6,889,127,602,744 | a1a95944fd4f31d0eab1e72ef8642d0b115a5353 | /bitCamp - workspace/workspace/Week5Exercieses/src/ba/bitcamp/boris/exercises/day3/task1/Main.java | d5bbf535b70ff4adaf2788629525530327cb06ba | []
| no_license | bc-boristomic/JavaProjects | https://github.com/bc-boristomic/JavaProjects | 4d293e08e7c0cbc91df681cb79c01579e31ebb8b | b07353fa7d46639ecbcdab35a4ac2949be27e757 | refs/heads/master | 2021-05-28T21:15:50.648000 | 2015-11-03T12:09:08 | 2015-11-03T12:09:08 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package ba.bitcamp.boris.exercises.day3.task1;
public class Main {
public static void main(String[] args) {
Speakerphone s1 = new Speakerphone("Sony", 7, 213.99);
System.out.println(s1);
s1.enable(); // Turn it ON
System.out.println(s1);
s1.increaseVolume(); // Increase volume by 40
s1.increaseVolume();
s1.increaseVolume();
s1.increaseVolume();
System.out.println(s1);
System.out.println("How much did it cost? " + s1.getPrice());
s1.disable(); // Turn it OFF
s1.lowerVolume();
}
}
| UTF-8 | Java | 544 | java | Main.java | Java | [
{
"context": " args) {\n\t\t\n\t\tSpeakerphone s1 = new Speakerphone(\"Sony\", 7, 213.99);\n\t\n\t\tSystem.out.println(s1);\n\t\t\n\t\ts1",
"end": 157,
"score": 0.9927425384521484,
"start": 153,
"tag": "NAME",
"value": "Sony"
}
]
| null | []
| package ba.bitcamp.boris.exercises.day3.task1;
public class Main {
public static void main(String[] args) {
Speakerphone s1 = new Speakerphone("Sony", 7, 213.99);
System.out.println(s1);
s1.enable(); // Turn it ON
System.out.println(s1);
s1.increaseVolume(); // Increase volume by 40
s1.increaseVolume();
s1.increaseVolume();
s1.increaseVolume();
System.out.println(s1);
System.out.println("How much did it cost? " + s1.getPrice());
s1.disable(); // Turn it OFF
s1.lowerVolume();
}
}
| 544 | 0.639706 | 0.599265 | 30 | 17.133333 | 18.338909 | 63 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.066667 | false | false | 13 |
dc5c3b3e11d9b5723c77c24f306b04cfc8f335dc | 2,508,260,963,513 | 6252c165657baa6aa605337ebc38dd44b3f694e2 | /org.eclipse.epsilon.egl.sync/Scalability-Tests/boiler-To-Generate-1000-Files/boiler-To-Generate-1000-Files/syncregions-1000Files/BoilerActuator2672.java | 37e4c76cbdc86b169b867ce6184ca2ec972a7593 | []
| no_license | soha500/EglSync | https://github.com/soha500/EglSync | 00fc49bcc73f7f7f7fb7641d0561ca2b9a8ea638 | 55101bc781349bb14fefc178bf3486e2b778aed6 | refs/heads/master | 2021-06-23T02:55:13.464000 | 2020-12-11T19:10:01 | 2020-12-11T19:10:01 | 139,832,721 | 0 | 1 | null | false | 2019-05-31T11:34:02 | 2018-07-05T10:20:00 | 2019-04-15T09:03:54 | 2019-05-31T11:34:01 | 87 | 0 | 0 | 0 | Java | false | false | package syncregions;
public class BoilerActuator2672 {
public int execute(int temperatureDifference2672, boolean boilerStatus2672) {
//sync _bfpnGUbFEeqXnfGWlV2672, behaviour
Half Change - return temperature - targetTemperature;
//endSync
}
}
| UTF-8 | Java | 267 | java | BoilerActuator2672.java | Java | []
| null | []
| package syncregions;
public class BoilerActuator2672 {
public int execute(int temperatureDifference2672, boolean boilerStatus2672) {
//sync _bfpnGUbFEeqXnfGWlV2672, behaviour
Half Change - return temperature - targetTemperature;
//endSync
}
}
| 267 | 0.749064 | 0.689139 | 13 | 19.538462 | 25.436544 | 79 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.230769 | false | false | 13 |
fe9f321e44165da568ee10656dbb4cfd94c33cfc | 25,529,285,619,174 | 7e3838f086b7074cb415fa93bfce45bd9cd24f81 | /app/src/main/java/com/chn/halo/ui/activity/MainActivity.java | 863f9842cdd84b5e3555cc7f36e9135f7efba709 | []
| no_license | Halo-CHN/HelloGradle | https://github.com/Halo-CHN/HelloGradle | ee323716663e1a3d4b05d74bb362af7fb8790c0f | afcaca161a0b62fdb3d9d7fc767b3dcb1a33a406 | refs/heads/master | 2021-01-17T07:54:30.740000 | 2017-08-07T06:50:27 | 2017-08-07T06:50:27 | 41,188,666 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.chn.halo.ui.activity;
import android.view.View;
import com.chn.halo.R;
import com.chn.halo.core.BaseButterKnifeFragmentActivity;
import com.chn.halo.ui.fragment.AccountFragment;
import com.chn.halo.ui.fragment.HomeFragment;
import com.chn.halo.ui.fragment.MoreFragment;
import com.chn.halo.util.ToastUtils;
import com.chn.halo.view.bottomtabbar.HaloFragmentManager;
import com.chn.halo.view.bottomtabbar.HaloViewPager;
import com.chn.halo.view.bottomtabbar.OnSelectableTextViewClickedListener;
import com.chn.halo.view.bottomtabbar.SelectableBottomTextView;
import com.chn.halo.view.bottomtabbar.SelectableBottomTextViewAttributesEx;
import butterknife.Bind;
/**
* @author Halo-CHN
* @version 1.0
* @description ไธป้กต้ข
* @mail halo-chn@outlook.com
* @date 2015ๅนด7ๆ8ๆฅ
*/
public class MainActivity extends BaseButterKnifeFragmentActivity {
@Override
protected boolean supportBackKey() {
return false;
}
@Override
protected int getLayoutResId() {
return R.layout.activity_main;
}
@Override
protected void initializeAfterOnCreate() {
ToastUtils.show(getThis(), "Welcome To Halo's World.");
bottom_tab_home.setOnTextViewClickedListener(bottomListener);
bottom_tab_account.setOnTextViewClickedListener(bottomListener);
bottom_tab_more.setOnTextViewClickedListener(bottomListener);
if (null == homeFragment)
homeFragment = new HomeFragment();
if (null == accountFragment)
accountFragment = new AccountFragment();
if (null == moreFragment)
moreFragment = new MoreFragment();
/* ๅๅงๅ็ฎก็ๅจ */
haloFragmentManager = new HaloFragmentManager(main_viewpager, this.getFragmentManager());
/* ๆณจๆ ๆญคๅค่ฏทๆๆงไปถๆๅๅ
ๅ้กบๅบๆทปๅ ๏ผ๏ผ */
haloFragmentManager.addFragment(bottom_tab_home, homeFragment);
haloFragmentManager.addFragment(bottom_tab_account, accountFragment);
haloFragmentManager.addFragment(bottom_tab_more, moreFragment);
}
/**
* ๅบ้จๅฏผ่ช็นๅปไบไปถๅ่ฐ
*/
OnSelectableTextViewClickedListener bottomListener = new OnSelectableTextViewClickedListener() {
@Override
public void onTextViewClicked(View v) {
if (!SelectableBottomTextViewAttributesEx.supportClickWhenSelected && v.getId() == SelectableBottomTextViewAttributesEx.onSelectableTextViewID)
return;
switch (v.getId()) {
case R.id.bottom_tab_home:
break;
case R.id.bottom_tab_account:
break;
case R.id.bottom_tab_more:
break;
}
haloFragmentManager.clickToChangeFragment(v.getId());
}
};
HaloFragmentManager haloFragmentManager;
HomeFragment homeFragment;
AccountFragment accountFragment;
MoreFragment moreFragment;
@Bind(R.id.main_viewpager)
HaloViewPager main_viewpager;
@Bind(R.id.bottom_tab_home)
SelectableBottomTextView bottom_tab_home;
@Bind(R.id.bottom_tab_account)
SelectableBottomTextView bottom_tab_account;
@Bind(R.id.bottom_tab_more)
SelectableBottomTextView bottom_tab_more;
} | UTF-8 | Java | 3,273 | java | MainActivity.java | Java | [
{
"context": "butesEx;\n\nimport butterknife.Bind;\n\n/**\n * @author Halo-CHN\n * @version 1.0\n * @description ไธป้กต้ข\n * @mail ",
"end": 694,
"score": 0.6429524421691895,
"start": 690,
"tag": "NAME",
"value": "Halo"
},
{
"context": "Ex;\n\nimport butterknife.Bind;\n\n/**\n * @author Halo-CHN\n * @version 1.0\n * @description ไธป้กต้ข\n * @mail hal",
"end": 697,
"score": 0.6608262062072754,
"start": 695,
"tag": "USERNAME",
"value": "CH"
},
{
"context": "\n\nimport butterknife.Bind;\n\n/**\n * @author Halo-CHN\n * @version 1.0\n * @description ไธป้กต้ข\n * @mail halo",
"end": 698,
"score": 0.650238037109375,
"start": 697,
"tag": "NAME",
"value": "N"
},
{
"context": "o-CHN\n * @version 1.0\n * @description ไธป้กต้ข\n * @mail halo-chn@outlook.com\n * @date 2015ๅนด7ๆ8ๆฅ\n */\npublic class MainActivity ",
"end": 764,
"score": 0.9999262094497681,
"start": 744,
"tag": "EMAIL",
"value": "halo-chn@outlook.com"
}
]
| null | []
| package com.chn.halo.ui.activity;
import android.view.View;
import com.chn.halo.R;
import com.chn.halo.core.BaseButterKnifeFragmentActivity;
import com.chn.halo.ui.fragment.AccountFragment;
import com.chn.halo.ui.fragment.HomeFragment;
import com.chn.halo.ui.fragment.MoreFragment;
import com.chn.halo.util.ToastUtils;
import com.chn.halo.view.bottomtabbar.HaloFragmentManager;
import com.chn.halo.view.bottomtabbar.HaloViewPager;
import com.chn.halo.view.bottomtabbar.OnSelectableTextViewClickedListener;
import com.chn.halo.view.bottomtabbar.SelectableBottomTextView;
import com.chn.halo.view.bottomtabbar.SelectableBottomTextViewAttributesEx;
import butterknife.Bind;
/**
* @author Halo-CHN
* @version 1.0
* @description ไธป้กต้ข
* @mail <EMAIL>
* @date 2015ๅนด7ๆ8ๆฅ
*/
public class MainActivity extends BaseButterKnifeFragmentActivity {
@Override
protected boolean supportBackKey() {
return false;
}
@Override
protected int getLayoutResId() {
return R.layout.activity_main;
}
@Override
protected void initializeAfterOnCreate() {
ToastUtils.show(getThis(), "Welcome To Halo's World.");
bottom_tab_home.setOnTextViewClickedListener(bottomListener);
bottom_tab_account.setOnTextViewClickedListener(bottomListener);
bottom_tab_more.setOnTextViewClickedListener(bottomListener);
if (null == homeFragment)
homeFragment = new HomeFragment();
if (null == accountFragment)
accountFragment = new AccountFragment();
if (null == moreFragment)
moreFragment = new MoreFragment();
/* ๅๅงๅ็ฎก็ๅจ */
haloFragmentManager = new HaloFragmentManager(main_viewpager, this.getFragmentManager());
/* ๆณจๆ ๆญคๅค่ฏทๆๆงไปถๆๅๅ
ๅ้กบๅบๆทปๅ ๏ผ๏ผ */
haloFragmentManager.addFragment(bottom_tab_home, homeFragment);
haloFragmentManager.addFragment(bottom_tab_account, accountFragment);
haloFragmentManager.addFragment(bottom_tab_more, moreFragment);
}
/**
* ๅบ้จๅฏผ่ช็นๅปไบไปถๅ่ฐ
*/
OnSelectableTextViewClickedListener bottomListener = new OnSelectableTextViewClickedListener() {
@Override
public void onTextViewClicked(View v) {
if (!SelectableBottomTextViewAttributesEx.supportClickWhenSelected && v.getId() == SelectableBottomTextViewAttributesEx.onSelectableTextViewID)
return;
switch (v.getId()) {
case R.id.bottom_tab_home:
break;
case R.id.bottom_tab_account:
break;
case R.id.bottom_tab_more:
break;
}
haloFragmentManager.clickToChangeFragment(v.getId());
}
};
HaloFragmentManager haloFragmentManager;
HomeFragment homeFragment;
AccountFragment accountFragment;
MoreFragment moreFragment;
@Bind(R.id.main_viewpager)
HaloViewPager main_viewpager;
@Bind(R.id.bottom_tab_home)
SelectableBottomTextView bottom_tab_home;
@Bind(R.id.bottom_tab_account)
SelectableBottomTextView bottom_tab_account;
@Bind(R.id.bottom_tab_more)
SelectableBottomTextView bottom_tab_more;
} | 3,260 | 0.694958 | 0.692452 | 98 | 31.591837 | 27.498362 | 155 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.469388 | false | false | 13 |
8cf0f46fb59f44c2e4b9df8ab5900737573f35e1 | 32,306,744,064,600 | 2695bacb25e31d0c4238f2227dd7dde7206227e4 | /src/com/sohail/alam/mango_pi/smart/cache/mbeans/DeprecatedSmartCacheManager.java | 9bae8a1e754410143a70e845c9d43e432aa79eed | [
"Apache-2.0"
]
| permissive | sohailalam2/Mango-Pi | https://github.com/sohailalam2/Mango-Pi | dfe4d3e6fab456200359e7b33efe91fab8ef045b | b40e7449971eb4e78e35b1ea2635a3917eb42a4b | refs/heads/master | 2020-12-30T09:57:30.975000 | 2013-07-23T19:39:36 | 2013-07-23T19:39:36 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* Copyright 2013 The Mango Pi Project
*
* The Mango Pi Project licenses this file to you under the Apache License, version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied.
* See the License for the specific language governing permissions and limitations under the License.
*/
package com.sohail.alam.mango_pi.smart.cache.mbeans;
import com.sohail.alam.mango_pi.jmx.wrapper.JMXBean;
import com.sohail.alam.mango_pi.jmx.wrapper.JMXBeanOperation;
import com.sohail.alam.mango_pi.jmx.wrapper.JMXBeanParameter;
import com.sohail.alam.mango_pi.smart.cache.DeprecatedSmartCache;
import com.sohail.alam.mango_pi.smart.cache.SmartCacheException;
import com.sohail.alam.mango_pi.smart.cache.SmartCachePojo;
import java.lang.reflect.Method;
import java.util.concurrent.TimeUnit;
/**
* User: Sohail Alam
* Version: 1.0.0
* Date: 4/7/13
* Time: 8:27 AM
*/
@JMXBean(description = "Smart Cache MBean")
@Deprecated
public class DeprecatedSmartCacheManager<T extends DeprecatedSmartCache, K, V extends SmartCachePojo>
extends AbstractSmartCacheManager<T, K, V>
implements DeprecatedSmartCacheManagerMBean<K, V> {
private DeprecatedSmartCache cache;
/**
* Instantiates a new Smart cache manager.
*
* @param cache the cache
*/
public DeprecatedSmartCacheManager(T cache) {
super(cache);
this.cache = cache;
}
/**
* Start auto cleaner.
*
* @param EXPIRY_DURATION the The TTL Value for the Cache entry, after which it will be auto deleted.
* @param START_TASK_DELAY The time after which the auto cleaner task starts
* @param REPEAT_TASK_DELAY The time after which the auto cleaner task repeats itself
* @param TIME_UNIT The time unit in which the above are defined
*
* @return the boolean
*
* @throws SmartCacheException the smart cache exception
*/
@Override
@Deprecated
@JMXBeanOperation(name = "startAutoCleanerWithTimeUnit", description = "Start the auto cleaner service for the given Smart Cache (With a callback method, using Smart Cache Event Listener API)")
public boolean startAutoCleanerWithTimeUnit(@JMXBeanParameter(name = "Expiry Duration", description = "The TTL Value for the Cache elements") final long EXPIRY_DURATION,
@JMXBeanParameter(name = "Start Task Delay", description = "The delay after which the auto cleaner task starts") final long START_TASK_DELAY,
@JMXBeanParameter(name = "Repeat Task Delay", description = "The delay after which the auto cleaner task repeats itself") final long REPEAT_TASK_DELAY,
@JMXBeanParameter(name = "Time Unit", description = "The Time Unit in which the previous two parameters are defined") final TimeUnit TIME_UNIT) throws SmartCacheException {
return this.cache.startAutoCleaner(EXPIRY_DURATION, START_TASK_DELAY, REPEAT_TASK_DELAY, TIME_UNIT);
}
/**
* Start auto cleaner.
*
* @param EXPIRY_DURATION the The TTL Value for the Cache entry, after which it will be auto deleted.
* @param START_TASK_DELAY The time after which the auto cleaner task starts
* @param REPEAT_TASK_DELAY The time after which the auto cleaner task repeats itself
*
* @return the boolean
*
* @throws com.sohail.alam.mango_pi.smart.cache.SmartCacheException
* the smart cache exception
*/
@Override
@Deprecated
@JMXBeanOperation(name = "restartAutoCleaner", description = "Start the auto cleaner service for the given Smart Cache (With a callback method, using Smart Cache Event Listener API) [All are in seconds]")
public boolean startAutoCleaner(@JMXBeanParameter(name = "Expiry Duration", description = "The TTL Value for the Cache elements (in seconds)") final long EXPIRY_DURATION,
@JMXBeanParameter(name = "Start Task Delay", description = "The delay after which the auto cleaner task starts (in seconds)") final long START_TASK_DELAY,
@JMXBeanParameter(name = "Repeat Task Delay", description = "The delay after which the auto cleaner task repeats itself (in seconds)") final long REPEAT_TASK_DELAY) throws SmartCacheException {
return startAutoCleanerWithTimeUnit(EXPIRY_DURATION, START_TASK_DELAY, REPEAT_TASK_DELAY, TimeUnit.SECONDS);
}
/**
* Start auto cleaner reflection.
*
* @param EXPIRY_DURATION the The TTL Value for the Cache entry, after which it will be auto deleted.
* @param START_TASK_DELAY The time after which the auto cleaner task starts
* @param REPEAT_TASK_DELAY The time after which the auto cleaner task repeats itself
* @param TIME_UNIT The time unit in which the above are defined
* @param CALLBACK_CLASS_OBJECT The Object of the Class in which the Callback method resides
* @param CALLBACK_METHOD The Callback Method
*
* @return the boolean
*
* @throws SmartCacheException the smart cache exception
*/
@Override
@Deprecated
@JMXBeanOperation(name = "startAutoCleanerReflection", description = "Start the auto cleaner service for the given Smart Cache (With a callback method, using Java Reflection API)")
public boolean startAutoCleanerReflection(@JMXBeanParameter(name = "Expiry Duration", description = "The TTL Value for the Cache elements") final long EXPIRY_DURATION,
@JMXBeanParameter(name = "Start Task Delay", description = "The delay after which the auto cleaner task starts") final long START_TASK_DELAY,
@JMXBeanParameter(name = "Repeat Task Delay", description = "The delay after which the auto cleaner task repeats itself") final long REPEAT_TASK_DELAY,
@JMXBeanParameter(name = "Time Unit", description = "The Time Unit in which the previous two parameters are defined") final TimeUnit TIME_UNIT,
@JMXBeanParameter(name = "Callback Class Object", description = "An object of the Callback Class (can be null)") final Object CALLBACK_CLASS_OBJECT,
@JMXBeanParameter(name = "Callback Method", description = "The Callback Method (can be null)") final Method CALLBACK_METHOD) throws SmartCacheException {
return this.cache.startAutoCleaner(EXPIRY_DURATION, START_TASK_DELAY, REPEAT_TASK_DELAY, TIME_UNIT, CALLBACK_CLASS_OBJECT, CALLBACK_METHOD);
}
/**
* Stop auto cleaner.
*/
@Override
@Deprecated
@JMXBeanOperation(name = "stopAutoCleaner", description = "Stop the auto cleaner service for the given Smart Cache")
public void stopAutoCleaner() {
this.cache.stopAutoCleaner();
}
/**
* Restart auto cleaner.
*
* @param EXPIRY_DURATION the The TTL Value for the Cache entry, after which it will be auto deleted.
* @param START_TASK_DELAY The time after which the auto cleaner task starts
* @param REPEAT_TASK_DELAY The time after which the auto cleaner task repeats itself
* @param TIME_UNIT The time unit in which the above are defined
*
* @return the boolean
*
* @throws SmartCacheException the smart cache exception
*/
@Override
@Deprecated
@JMXBeanOperation(name = "rescheduleAutoCleanerWithTimeUnit", description = "Restart the auto cleaner service for the given Smart Cache (With a callback method, using Smart Cache Event Listener API)")
public boolean rescheduleAutoCleanerWithTimeUnit(@JMXBeanParameter(name = "Expiry Duration", description = "The TTL Value for the Cache elements") final long EXPIRY_DURATION,
@JMXBeanParameter(name = "Start Task Delay", description = "The delay after which the auto cleaner task starts") final long START_TASK_DELAY,
@JMXBeanParameter(name = "Repeat Task Delay", description = "The delay after which the auto cleaner task repeats itself") final long REPEAT_TASK_DELAY,
@JMXBeanParameter(name = "Time Unit", description = "The Time Unit in which the previous two parameters are defined") final TimeUnit TIME_UNIT) throws SmartCacheException {
this.cache.stopAutoCleaner();
return this.cache.startAutoCleaner(EXPIRY_DURATION, START_TASK_DELAY, REPEAT_TASK_DELAY, TIME_UNIT);
}
/**
* Restart auto cleaner.
*
* @param EXPIRY_DURATION the The TTL Value for the Cache entry, after which it will be auto deleted.
* @param START_TASK_DELAY The time after which the auto cleaner task starts
* @param REPEAT_TASK_DELAY The time after which the auto cleaner task repeats itself
*
* @return the boolean
*
* @throws com.sohail.alam.mango_pi.smart.cache.SmartCacheException
* the smart cache exception
*/
@Override
@Deprecated
@JMXBeanOperation(name = "rescheduleAutoCleaner", description = "Restart the auto cleaner service for the given Smart Cache (With a callback method, using Smart Cache Event Listener API)")
public boolean rescheduleAutoCleaner(@JMXBeanParameter(name = "Expiry Duration", description = "The TTL Value for the Cache elements") final long EXPIRY_DURATION,
@JMXBeanParameter(name = "Start Task Delay", description = "The delay after which the auto cleaner task starts") final long START_TASK_DELAY,
@JMXBeanParameter(name = "Repeat Task Delay", description = "The delay after which the auto cleaner task repeats itself") final long REPEAT_TASK_DELAY) throws SmartCacheException {
this.cache.stopAutoCleaner();
return this.cache.startAutoCleaner(EXPIRY_DURATION, START_TASK_DELAY, REPEAT_TASK_DELAY, TimeUnit.SECONDS);
}
/**
* Restart auto cleaner reflection.
*
* @param EXPIRY_DURATION the The TTL Value for the Cache entry, after which it will be auto deleted.
* @param START_TASK_DELAY The time after which the auto cleaner task starts
* @param REPEAT_TASK_DELAY The time after which the auto cleaner task repeats itself
* @param TIME_UNIT The time unit in which the above are defined
* @param CALLBACK_CLASS_OBJECT The Object of the Class in which the Callback method resides
* @param CALLBACK_METHOD The Callback Method
*
* @return the boolean
*
* @throws SmartCacheException the smart cache exception
*/
@Override
@Deprecated
@JMXBeanOperation(name = "rescheduleAutoCleanerReflection", description = "Restart the auto cleaner service for the given Smart Cache (With a callback method, using Java Reflection API)")
public boolean rescheduleAutoCleanerReflection(@JMXBeanParameter(name = "Expiry Duration", description = "The TTL Value for the Cache elements") final long EXPIRY_DURATION,
@JMXBeanParameter(name = "Start Task Delay", description = "The delay after which the auto cleaner task starts") final long START_TASK_DELAY,
@JMXBeanParameter(name = "Repeat Task Delay", description = "The delay after which the auto cleaner task repeats itself") final long REPEAT_TASK_DELAY,
@JMXBeanParameter(name = "Time Unit", description = "The Time Unit in which the previous two parameters are defined") final TimeUnit TIME_UNIT,
@JMXBeanParameter(name = "Callback Class Object", description = "An object of the Callback Class (can be null)") final Object CALLBACK_CLASS_OBJECT,
@JMXBeanParameter(name = "Callback Method", description = "The Callback Method (can be null)") final Method CALLBACK_METHOD) throws SmartCacheException {
this.cache.stopAutoCleaner();
return this.cache.startAutoCleaner(EXPIRY_DURATION, START_TASK_DELAY, REPEAT_TASK_DELAY, TIME_UNIT, CALLBACK_CLASS_OBJECT, CALLBACK_METHOD);
}
/**
* Put the Data of type {@link V} into the
* {@link com.sohail.alam.mango_pi.smart.cache.SmartCache},
* corresponding to the Key of type {@link K}
*
* @param key Any Key of type
* @param data Any Data of type
* @param ttl the ttl value - The after which data will be auto deleted from the Cache
* @param timeUnit the time unit for the TTL Value
*/
@Override
public void put(K key, V data, int ttl, TimeUnit timeUnit) {
super.put(key, data, ttl, timeUnit);
}
/**
* Put the Data of type {@link V} into the
* {@link com.sohail.alam.mango_pi.smart.cache.SmartCache},
* corresponding to the Key of type {@link K}
*
* @param key Any Key of type
* @param data Any Data of type
* @param ttl the ttl value - The after which data will be auto deleted from the Cache
*/
@Override
public void put(K key, V data, int ttl) {
super.put(key, data, ttl);
}
/**
* Checks if the Cache entry contains the given KEY
*
* @param key The exact KEY to search for
*
* @return true /false
*/
@Override
public boolean containsValue(V key) {
return super.containsValue(key);
}
}
| UTF-8 | Java | 13,993 | java | DeprecatedSmartCacheManager.java | Java | [
{
"context": "mport java.util.concurrent.TimeUnit;\n\n/**\n * User: Sohail Alam\n * Version: 1.0.0\n * Date: 4/7/13\n * Time: 8:27 A",
"end": 1172,
"score": 0.9998486638069153,
"start": 1161,
"tag": "NAME",
"value": "Sohail Alam"
}
]
| null | []
| /*
* Copyright 2013 The Mango Pi Project
*
* The Mango Pi Project licenses this file to you under the Apache License, version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied.
* See the License for the specific language governing permissions and limitations under the License.
*/
package com.sohail.alam.mango_pi.smart.cache.mbeans;
import com.sohail.alam.mango_pi.jmx.wrapper.JMXBean;
import com.sohail.alam.mango_pi.jmx.wrapper.JMXBeanOperation;
import com.sohail.alam.mango_pi.jmx.wrapper.JMXBeanParameter;
import com.sohail.alam.mango_pi.smart.cache.DeprecatedSmartCache;
import com.sohail.alam.mango_pi.smart.cache.SmartCacheException;
import com.sohail.alam.mango_pi.smart.cache.SmartCachePojo;
import java.lang.reflect.Method;
import java.util.concurrent.TimeUnit;
/**
* User: <NAME>
* Version: 1.0.0
* Date: 4/7/13
* Time: 8:27 AM
*/
@JMXBean(description = "Smart Cache MBean")
@Deprecated
public class DeprecatedSmartCacheManager<T extends DeprecatedSmartCache, K, V extends SmartCachePojo>
extends AbstractSmartCacheManager<T, K, V>
implements DeprecatedSmartCacheManagerMBean<K, V> {
private DeprecatedSmartCache cache;
/**
* Instantiates a new Smart cache manager.
*
* @param cache the cache
*/
public DeprecatedSmartCacheManager(T cache) {
super(cache);
this.cache = cache;
}
/**
* Start auto cleaner.
*
* @param EXPIRY_DURATION the The TTL Value for the Cache entry, after which it will be auto deleted.
* @param START_TASK_DELAY The time after which the auto cleaner task starts
* @param REPEAT_TASK_DELAY The time after which the auto cleaner task repeats itself
* @param TIME_UNIT The time unit in which the above are defined
*
* @return the boolean
*
* @throws SmartCacheException the smart cache exception
*/
@Override
@Deprecated
@JMXBeanOperation(name = "startAutoCleanerWithTimeUnit", description = "Start the auto cleaner service for the given Smart Cache (With a callback method, using Smart Cache Event Listener API)")
public boolean startAutoCleanerWithTimeUnit(@JMXBeanParameter(name = "Expiry Duration", description = "The TTL Value for the Cache elements") final long EXPIRY_DURATION,
@JMXBeanParameter(name = "Start Task Delay", description = "The delay after which the auto cleaner task starts") final long START_TASK_DELAY,
@JMXBeanParameter(name = "Repeat Task Delay", description = "The delay after which the auto cleaner task repeats itself") final long REPEAT_TASK_DELAY,
@JMXBeanParameter(name = "Time Unit", description = "The Time Unit in which the previous two parameters are defined") final TimeUnit TIME_UNIT) throws SmartCacheException {
return this.cache.startAutoCleaner(EXPIRY_DURATION, START_TASK_DELAY, REPEAT_TASK_DELAY, TIME_UNIT);
}
/**
* Start auto cleaner.
*
* @param EXPIRY_DURATION the The TTL Value for the Cache entry, after which it will be auto deleted.
* @param START_TASK_DELAY The time after which the auto cleaner task starts
* @param REPEAT_TASK_DELAY The time after which the auto cleaner task repeats itself
*
* @return the boolean
*
* @throws com.sohail.alam.mango_pi.smart.cache.SmartCacheException
* the smart cache exception
*/
@Override
@Deprecated
@JMXBeanOperation(name = "restartAutoCleaner", description = "Start the auto cleaner service for the given Smart Cache (With a callback method, using Smart Cache Event Listener API) [All are in seconds]")
public boolean startAutoCleaner(@JMXBeanParameter(name = "Expiry Duration", description = "The TTL Value for the Cache elements (in seconds)") final long EXPIRY_DURATION,
@JMXBeanParameter(name = "Start Task Delay", description = "The delay after which the auto cleaner task starts (in seconds)") final long START_TASK_DELAY,
@JMXBeanParameter(name = "Repeat Task Delay", description = "The delay after which the auto cleaner task repeats itself (in seconds)") final long REPEAT_TASK_DELAY) throws SmartCacheException {
return startAutoCleanerWithTimeUnit(EXPIRY_DURATION, START_TASK_DELAY, REPEAT_TASK_DELAY, TimeUnit.SECONDS);
}
/**
* Start auto cleaner reflection.
*
* @param EXPIRY_DURATION the The TTL Value for the Cache entry, after which it will be auto deleted.
* @param START_TASK_DELAY The time after which the auto cleaner task starts
* @param REPEAT_TASK_DELAY The time after which the auto cleaner task repeats itself
* @param TIME_UNIT The time unit in which the above are defined
* @param CALLBACK_CLASS_OBJECT The Object of the Class in which the Callback method resides
* @param CALLBACK_METHOD The Callback Method
*
* @return the boolean
*
* @throws SmartCacheException the smart cache exception
*/
@Override
@Deprecated
@JMXBeanOperation(name = "startAutoCleanerReflection", description = "Start the auto cleaner service for the given Smart Cache (With a callback method, using Java Reflection API)")
public boolean startAutoCleanerReflection(@JMXBeanParameter(name = "Expiry Duration", description = "The TTL Value for the Cache elements") final long EXPIRY_DURATION,
@JMXBeanParameter(name = "Start Task Delay", description = "The delay after which the auto cleaner task starts") final long START_TASK_DELAY,
@JMXBeanParameter(name = "Repeat Task Delay", description = "The delay after which the auto cleaner task repeats itself") final long REPEAT_TASK_DELAY,
@JMXBeanParameter(name = "Time Unit", description = "The Time Unit in which the previous two parameters are defined") final TimeUnit TIME_UNIT,
@JMXBeanParameter(name = "Callback Class Object", description = "An object of the Callback Class (can be null)") final Object CALLBACK_CLASS_OBJECT,
@JMXBeanParameter(name = "Callback Method", description = "The Callback Method (can be null)") final Method CALLBACK_METHOD) throws SmartCacheException {
return this.cache.startAutoCleaner(EXPIRY_DURATION, START_TASK_DELAY, REPEAT_TASK_DELAY, TIME_UNIT, CALLBACK_CLASS_OBJECT, CALLBACK_METHOD);
}
/**
* Stop auto cleaner.
*/
@Override
@Deprecated
@JMXBeanOperation(name = "stopAutoCleaner", description = "Stop the auto cleaner service for the given Smart Cache")
public void stopAutoCleaner() {
this.cache.stopAutoCleaner();
}
/**
* Restart auto cleaner.
*
* @param EXPIRY_DURATION the The TTL Value for the Cache entry, after which it will be auto deleted.
* @param START_TASK_DELAY The time after which the auto cleaner task starts
* @param REPEAT_TASK_DELAY The time after which the auto cleaner task repeats itself
* @param TIME_UNIT The time unit in which the above are defined
*
* @return the boolean
*
* @throws SmartCacheException the smart cache exception
*/
@Override
@Deprecated
@JMXBeanOperation(name = "rescheduleAutoCleanerWithTimeUnit", description = "Restart the auto cleaner service for the given Smart Cache (With a callback method, using Smart Cache Event Listener API)")
public boolean rescheduleAutoCleanerWithTimeUnit(@JMXBeanParameter(name = "Expiry Duration", description = "The TTL Value for the Cache elements") final long EXPIRY_DURATION,
@JMXBeanParameter(name = "Start Task Delay", description = "The delay after which the auto cleaner task starts") final long START_TASK_DELAY,
@JMXBeanParameter(name = "Repeat Task Delay", description = "The delay after which the auto cleaner task repeats itself") final long REPEAT_TASK_DELAY,
@JMXBeanParameter(name = "Time Unit", description = "The Time Unit in which the previous two parameters are defined") final TimeUnit TIME_UNIT) throws SmartCacheException {
this.cache.stopAutoCleaner();
return this.cache.startAutoCleaner(EXPIRY_DURATION, START_TASK_DELAY, REPEAT_TASK_DELAY, TIME_UNIT);
}
/**
* Restart auto cleaner.
*
* @param EXPIRY_DURATION the The TTL Value for the Cache entry, after which it will be auto deleted.
* @param START_TASK_DELAY The time after which the auto cleaner task starts
* @param REPEAT_TASK_DELAY The time after which the auto cleaner task repeats itself
*
* @return the boolean
*
* @throws com.sohail.alam.mango_pi.smart.cache.SmartCacheException
* the smart cache exception
*/
@Override
@Deprecated
@JMXBeanOperation(name = "rescheduleAutoCleaner", description = "Restart the auto cleaner service for the given Smart Cache (With a callback method, using Smart Cache Event Listener API)")
public boolean rescheduleAutoCleaner(@JMXBeanParameter(name = "Expiry Duration", description = "The TTL Value for the Cache elements") final long EXPIRY_DURATION,
@JMXBeanParameter(name = "Start Task Delay", description = "The delay after which the auto cleaner task starts") final long START_TASK_DELAY,
@JMXBeanParameter(name = "Repeat Task Delay", description = "The delay after which the auto cleaner task repeats itself") final long REPEAT_TASK_DELAY) throws SmartCacheException {
this.cache.stopAutoCleaner();
return this.cache.startAutoCleaner(EXPIRY_DURATION, START_TASK_DELAY, REPEAT_TASK_DELAY, TimeUnit.SECONDS);
}
/**
* Restart auto cleaner reflection.
*
* @param EXPIRY_DURATION the The TTL Value for the Cache entry, after which it will be auto deleted.
* @param START_TASK_DELAY The time after which the auto cleaner task starts
* @param REPEAT_TASK_DELAY The time after which the auto cleaner task repeats itself
* @param TIME_UNIT The time unit in which the above are defined
* @param CALLBACK_CLASS_OBJECT The Object of the Class in which the Callback method resides
* @param CALLBACK_METHOD The Callback Method
*
* @return the boolean
*
* @throws SmartCacheException the smart cache exception
*/
@Override
@Deprecated
@JMXBeanOperation(name = "rescheduleAutoCleanerReflection", description = "Restart the auto cleaner service for the given Smart Cache (With a callback method, using Java Reflection API)")
public boolean rescheduleAutoCleanerReflection(@JMXBeanParameter(name = "Expiry Duration", description = "The TTL Value for the Cache elements") final long EXPIRY_DURATION,
@JMXBeanParameter(name = "Start Task Delay", description = "The delay after which the auto cleaner task starts") final long START_TASK_DELAY,
@JMXBeanParameter(name = "Repeat Task Delay", description = "The delay after which the auto cleaner task repeats itself") final long REPEAT_TASK_DELAY,
@JMXBeanParameter(name = "Time Unit", description = "The Time Unit in which the previous two parameters are defined") final TimeUnit TIME_UNIT,
@JMXBeanParameter(name = "Callback Class Object", description = "An object of the Callback Class (can be null)") final Object CALLBACK_CLASS_OBJECT,
@JMXBeanParameter(name = "Callback Method", description = "The Callback Method (can be null)") final Method CALLBACK_METHOD) throws SmartCacheException {
this.cache.stopAutoCleaner();
return this.cache.startAutoCleaner(EXPIRY_DURATION, START_TASK_DELAY, REPEAT_TASK_DELAY, TIME_UNIT, CALLBACK_CLASS_OBJECT, CALLBACK_METHOD);
}
/**
* Put the Data of type {@link V} into the
* {@link com.sohail.alam.mango_pi.smart.cache.SmartCache},
* corresponding to the Key of type {@link K}
*
* @param key Any Key of type
* @param data Any Data of type
* @param ttl the ttl value - The after which data will be auto deleted from the Cache
* @param timeUnit the time unit for the TTL Value
*/
@Override
public void put(K key, V data, int ttl, TimeUnit timeUnit) {
super.put(key, data, ttl, timeUnit);
}
/**
* Put the Data of type {@link V} into the
* {@link com.sohail.alam.mango_pi.smart.cache.SmartCache},
* corresponding to the Key of type {@link K}
*
* @param key Any Key of type
* @param data Any Data of type
* @param ttl the ttl value - The after which data will be auto deleted from the Cache
*/
@Override
public void put(K key, V data, int ttl) {
super.put(key, data, ttl);
}
/**
* Checks if the Cache entry contains the given KEY
*
* @param key The exact KEY to search for
*
* @return true /false
*/
@Override
public boolean containsValue(V key) {
return super.containsValue(key);
}
}
| 13,988 | 0.667262 | 0.665976 | 246 | 55.882114 | 63.023663 | 229 | true | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.544715 | false | false | 13 |
68834b16943d4c59efda34dd881b1f7e9cb97490 | 26,594,437,535,173 | f3d6537b5b080805e37f113ae2990f2163a617f5 | /app/services/impl/EmarketDataServiceFake.java | 7b3939a90ec23cc6b2a25b985aedb86198579177 | [
"Apache-2.0"
]
| permissive | Kuann/emarket | https://github.com/Kuann/emarket | 7bdd91c25c84ff81cc43a7bdebcdefa7810d7099 | 08bbdac4516147ce99f1fb22dfe02f790937218f | refs/heads/master | 2020-05-27T14:13:40.905000 | 2017-03-16T14:54:58 | 2017-03-16T14:54:58 | 82,557,647 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package services.impl;
import models.Product;
import services.EmarketDataService;
import javax.inject.Singleton;
import java.util.LinkedList;
import java.util.List;
/**
* Created by An on 2/20/2017.
*/
@Singleton
public class EmarketDataServiceFake implements EmarketDataService {
private List<Product> products;
/*
public EmarketDataServiceFake() {
products = new LinkedList<>();
Product product = new Product();
product.id = 1;
product.name = "Laptop Asus GL552VX-DM070D i7-6700HQ 15.6 inch (ฤen) - Hรฃng Phรขn phแปi chรญnh thแปฉc";
product.category = 1;
product.manufacturer = 1;
product.warranty = "24 thรกng";
product.price = 19500000;
product.shortDescription = "Intel Core i7 6700HQ 2.6GHz up to 3.5GHz 6MB\n" +
"8GB DDR4 2133MHz\n" +
"NVIDIA GeForce GTX 950M 4GB GDDR5 Intel HD Graphics 530\n" +
"15.6 inch Full HD (1920 x 1080 pixels)";
product.informationDetail = "SKU\tAS082ELAA1KCXUVNAMZ-2556531\n" +
"Kรญch thฦฐแปc mร n hรฌnh\t13.3\n" +
"Graphics Card\tIntel\n" +
"Graphics Memory\t4GB\n" +
"Hard Drive Capacity\t1TB\n" +
"Input/Output Ports\tUSB 3.0\n" +
"Mแบซu mรฃ\tTablet Plaza (Tp.HCM)-Laptop Asus GL552VX-DM070D 15.6 inch (ฤen)\n" +
"Hแป ฤiแปu hร nh\tDOS\n" +
"Processor Type\tNot Specified\n" +
"Kรญch thฦฐแปc sแบฃn phแบฉm (D x R x C cm)\t37 x 25 x 2\n" +
"Trแปng lฦฐแปฃng (KG)\t2.59\n" +
"Sแบฃn xuแบฅt tแบกi\tTrung Quแปc\n" +
"Thแปi gian bแบฃo hร nh\t2 nฤm\n" +
"Loแบกi hรฌnh bแบฃo hร nh\tBแบฑng Phiแบฟu bแบฃo hร nh vร Hรณa ฤฦกn\n" +
"Wireless Connectivity\tWifi";
product.description = "";
product.pictures = "1-1.jpg\n" +
"1_2.jpg";
for (int i = 0; i<12; i++)
products.add(product);
}
*/
@Override
public List<Product> getProducts() {
return products;
}
@Override
public Product getProduct(Integer id) {
return products.stream().filter(product -> id.equals(product.getId())).findFirst().orElse(null);
}
}
| UTF-8 | Java | 2,304 | java | EmarketDataServiceFake.java | Java | []
| null | []
| package services.impl;
import models.Product;
import services.EmarketDataService;
import javax.inject.Singleton;
import java.util.LinkedList;
import java.util.List;
/**
* Created by An on 2/20/2017.
*/
@Singleton
public class EmarketDataServiceFake implements EmarketDataService {
private List<Product> products;
/*
public EmarketDataServiceFake() {
products = new LinkedList<>();
Product product = new Product();
product.id = 1;
product.name = "Laptop Asus GL552VX-DM070D i7-6700HQ 15.6 inch (ฤen) - Hรฃng Phรขn phแปi chรญnh thแปฉc";
product.category = 1;
product.manufacturer = 1;
product.warranty = "24 thรกng";
product.price = 19500000;
product.shortDescription = "Intel Core i7 6700HQ 2.6GHz up to 3.5GHz 6MB\n" +
"8GB DDR4 2133MHz\n" +
"NVIDIA GeForce GTX 950M 4GB GDDR5 Intel HD Graphics 530\n" +
"15.6 inch Full HD (1920 x 1080 pixels)";
product.informationDetail = "SKU\tAS082ELAA1KCXUVNAMZ-2556531\n" +
"Kรญch thฦฐแปc mร n hรฌnh\t13.3\n" +
"Graphics Card\tIntel\n" +
"Graphics Memory\t4GB\n" +
"Hard Drive Capacity\t1TB\n" +
"Input/Output Ports\tUSB 3.0\n" +
"Mแบซu mรฃ\tTablet Plaza (Tp.HCM)-Laptop Asus GL552VX-DM070D 15.6 inch (ฤen)\n" +
"Hแป ฤiแปu hร nh\tDOS\n" +
"Processor Type\tNot Specified\n" +
"Kรญch thฦฐแปc sแบฃn phแบฉm (D x R x C cm)\t37 x 25 x 2\n" +
"Trแปng lฦฐแปฃng (KG)\t2.59\n" +
"Sแบฃn xuแบฅt tแบกi\tTrung Quแปc\n" +
"Thแปi gian bแบฃo hร nh\t2 nฤm\n" +
"Loแบกi hรฌnh bแบฃo hร nh\tBแบฑng Phiแบฟu bแบฃo hร nh vร Hรณa ฤฦกn\n" +
"Wireless Connectivity\tWifi";
product.description = "";
product.pictures = "1-1.jpg\n" +
"1_2.jpg";
for (int i = 0; i<12; i++)
products.add(product);
}
*/
@Override
public List<Product> getProducts() {
return products;
}
@Override
public Product getProduct(Integer id) {
return products.stream().filter(product -> id.equals(product.getId())).findFirst().orElse(null);
}
}
| 2,304 | 0.575391 | 0.52528 | 62 | 35.048386 | 25.831606 | 106 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.387097 | false | false | 13 |
688523ace52a5e8af55de9aa067d62c0d8f01caa | 27,779,848,523,790 | a3f1bc29c4938165aca2faf44500b551bd1d5e81 | /src/main/java/ua/org/ekit/vitrenko/lab1/OneDimSqrFunction.java | ca06a92a3ca5c04f6a4fae62436aab9c2fa30144 | []
| no_license | Vestail/Operations-research-labs | https://github.com/Vestail/Operations-research-labs | 053f1e07f46fcd5d0ea7ba5b8dd3598d6fa337af | a8714aae34d3f18dd0c5e6e2912540fdacf2fb67 | refs/heads/master | 2016-08-12T10:22:13.524000 | 2016-02-29T21:40:13 | 2016-02-29T21:40:13 | 51,791,791 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* 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 ua.org.ekit.vitrenko.lab1;
public class OneDimSqrFunction implements OneDimFunction {
public final double a, b, c, r;
public OneDimSqrFunction(double na, double nb, double nc, double nr) {
a = na;
b = nb;
c = nc;
r = nr;
}
@Override
public double f(double x) {
return a * Math.pow(x - r, 2) + b * (x - r) + c;
}
@Override
public double df(double x) {
return 2.0 * a * (x - r) + b;
}
public double ddf(double x) {
return 2.0 * a * x;
}
}
| UTF-8 | Java | 786 | java | OneDimSqrFunction.java | Java | []
| null | []
| /*
* 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 ua.org.ekit.vitrenko.lab1;
public class OneDimSqrFunction implements OneDimFunction {
public final double a, b, c, r;
public OneDimSqrFunction(double na, double nb, double nc, double nr) {
a = na;
b = nb;
c = nc;
r = nr;
}
@Override
public double f(double x) {
return a * Math.pow(x - r, 2) + b * (x - r) + c;
}
@Override
public double df(double x) {
return 2.0 * a * (x - r) + b;
}
public double ddf(double x) {
return 2.0 * a * x;
}
}
| 786 | 0.543257 | 0.535623 | 33 | 21.818182 | 22.188524 | 79 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.575758 | false | false | 13 |
607957eee4f941ecd0a9501d12db9d054abf96c3 | 25,366,076,879,161 | efc55d73f1425ac90d227209b70867f4dd487c5c | /Chapter4/Singularity/SingularityService/src/main/java/com/hubspot/singularity/resources/S3LogResource.java | 3a053b0099f38ffdcff9e22a64fe2fb054a05898 | [
"Apache-2.0",
"MIT"
]
| permissive | PacktPublishing/Mastering-Mesos | https://github.com/PacktPublishing/Mastering-Mesos | 9f6171b449ad96222ce18ad3e3f3c6cdfe8fdbf3 | 88dddb51ed9ad070340edb33eef9fd12745b9f8a | refs/heads/master | 2023-02-08T18:51:28.227000 | 2023-01-30T10:09:39 | 2023-01-30T10:09:39 | 58,921,823 | 12 | 6 | MIT | false | 2022-12-14T20:22:53 | 2016-05-16T09:52:00 | 2022-05-26T11:56:02 | 2022-12-14T20:22:50 | 124,577 | 10 | 8 | 12 | Java | false | false | package com.hubspot.singularity.resources;
import static com.hubspot.singularity.WebExceptions.checkNotFound;
import static com.hubspot.singularity.WebExceptions.timeout;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import org.jets3t.service.S3Service;
import org.jets3t.service.model.S3Object;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.base.Optional;
import com.google.common.base.Throwables;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.common.primitives.Longs;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.ListeningExecutorService;
import com.google.common.util.concurrent.MoreExecutors;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import com.google.inject.Inject;
import com.hubspot.mesos.JavaUtils;
import com.hubspot.singularity.SingularityAuthorizationScope;
import com.hubspot.singularity.SingularityDeployHistory;
import com.hubspot.singularity.SingularityRequestHistory;
import com.hubspot.singularity.SingularityRequestHistory.RequestHistoryType;
import com.hubspot.singularity.SingularityRequestWithState;
import com.hubspot.singularity.SingularityS3FormatHelper;
import com.hubspot.singularity.SingularityS3Log;
import com.hubspot.singularity.SingularityService;
import com.hubspot.singularity.SingularityTaskHistory;
import com.hubspot.singularity.SingularityTaskHistoryUpdate;
import com.hubspot.singularity.SingularityTaskHistoryUpdate.SimplifiedTaskState;
import com.hubspot.singularity.SingularityTaskId;
import com.hubspot.singularity.SingularityUser;
import com.hubspot.singularity.auth.SingularityAuthorizationHelper;
import com.hubspot.singularity.config.S3Configuration;
import com.hubspot.singularity.data.DeployManager;
import com.hubspot.singularity.data.RequestManager;
import com.hubspot.singularity.data.TaskManager;
import com.hubspot.singularity.data.history.HistoryManager;
import com.hubspot.singularity.data.history.RequestHistoryHelper;
import com.wordnik.swagger.annotations.Api;
import com.wordnik.swagger.annotations.ApiOperation;
import com.wordnik.swagger.annotations.ApiParam;
@Path(S3LogResource.PATH)
@Produces({ MediaType.APPLICATION_JSON })
@Api(description="Manages Singularity task logs stored in S3.", value=S3LogResource.PATH)
public class S3LogResource extends AbstractHistoryResource {
public static final String PATH = SingularityService.API_BASE_PATH + "/logs";
private static final Logger LOG = LoggerFactory.getLogger(S3LogResource.class);
private final Optional<S3Service> s3ServiceDefault;
private final Map<String, S3Service> s3GroupOverride;
private final Optional<S3Configuration> configuration;
private final RequestHistoryHelper requestHistoryHelper;
private final RequestManager requestManager;
private static final Comparator<SingularityS3Log> LOG_COMPARATOR = new Comparator<SingularityS3Log>() {
@Override
public int compare(SingularityS3Log o1, SingularityS3Log o2) {
return Longs.compare(o2.getLastModified(), o1.getLastModified());
}
};
@Inject
public S3LogResource(RequestManager requestManager, HistoryManager historyManager, RequestHistoryHelper requestHistoryHelper, TaskManager taskManager, DeployManager deployManager, Optional<S3Service> s3ServiceDefault,
Optional<S3Configuration> configuration, SingularityAuthorizationHelper authorizationHelper, Optional<SingularityUser> user, Map<String, S3Service> s3GroupOverride) {
super(historyManager, taskManager, deployManager, authorizationHelper, user);
this.requestManager = requestManager;
this.s3ServiceDefault = s3ServiceDefault;
this.configuration = configuration;
this.requestHistoryHelper = requestHistoryHelper;
this.s3GroupOverride = s3GroupOverride;
}
private Collection<String> getS3PrefixesForTask(S3Configuration s3Configuration, SingularityTaskId taskId, Optional<Long> startArg, Optional<Long> endArg) {
Optional<SingularityTaskHistory> history = getTaskHistory(taskId);
long start = taskId.getStartedAt();
if (startArg.isPresent()) {
start = Math.max(startArg.get(), start);
}
long end = start + s3Configuration.getMissingTaskDefaultS3SearchPeriodMillis();
if (history.isPresent()) {
SimplifiedTaskState taskState = SingularityTaskHistoryUpdate.getCurrentState(history.get().getTaskUpdates());
if (taskState == SimplifiedTaskState.DONE) {
end = Iterables.getLast(history.get().getTaskUpdates()).getTimestamp();
} else {
end = System.currentTimeMillis();
}
}
if (endArg.isPresent()) {
end = Math.min(endArg.get(), end);
}
Optional<String> tag = Optional.absent();
if (history.isPresent() && history.get().getTask().getTaskRequest().getDeploy().getExecutorData().isPresent()) {
tag = history.get().getTask().getTaskRequest().getDeploy().getExecutorData().get().getLoggingTag();
}
Collection<String> prefixes = SingularityS3FormatHelper.getS3KeyPrefixes(s3Configuration.getS3KeyFormat(), taskId, tag, start, end);
LOG.trace("Task {} got S3 prefixes {} for start {}, end {}, tag {}", taskId, prefixes, start, end, tag);
return prefixes;
}
private boolean isCurrentDeploy(String requestId, String deployId) {
return deployId.equals(deployManager.getInUseDeployId(requestId).orNull());
}
private Collection<String> getS3PrefixesForRequest(S3Configuration s3Configuration, String requestId, Optional<Long> startArg, Optional<Long> endArg) {
Optional<SingularityRequestHistory> firstHistory = requestHistoryHelper.getFirstHistory(requestId);
checkNotFound(firstHistory.isPresent(), "No request history found for %s", requestId);
long start = firstHistory.get().getCreatedAt();
if (startArg.isPresent()) {
start = Math.max(startArg.get(), start);
}
Optional<SingularityRequestHistory> lastHistory = requestHistoryHelper.getLastHistory(requestId);
long end = System.currentTimeMillis();
if (lastHistory.isPresent() && (lastHistory.get().getEventType() == RequestHistoryType.DELETED || lastHistory.get().getEventType() == RequestHistoryType.PAUSED)) {
end = lastHistory.get().getCreatedAt() + TimeUnit.DAYS.toMillis(1);
}
if (endArg.isPresent()) {
end = Math.min(endArg.get(), end);
}
Collection<String> prefixes = SingularityS3FormatHelper.getS3KeyPrefixes(s3Configuration.getS3KeyFormat(), requestId, start, end);
LOG.trace("Request {} got S3 prefixes {} for start {}, end {}", requestId, prefixes, start, end);
return prefixes;
}
private Collection<String> getS3PrefixesForDeploy(S3Configuration s3Configuration, String requestId, String deployId, Optional<Long> startArg, Optional<Long> endArg) {
SingularityDeployHistory deployHistory = getDeployHistory(requestId, deployId);
long start = deployHistory.getDeployMarker().getTimestamp();
if (startArg.isPresent()) {
start = Math.max(startArg.get(), start);
}
long end = System.currentTimeMillis();
if (!isCurrentDeploy(requestId, deployId) && deployHistory.getDeployStatistics().isPresent() && deployHistory.getDeployStatistics().get().getLastFinishAt().isPresent()) {
end = deployHistory.getDeployStatistics().get().getLastFinishAt().get() + TimeUnit.DAYS.toMillis(1);
}
if (endArg.isPresent()) {
end = Math.min(endArg.get(), end);
}
Optional<String> tag = Optional.absent();
if (deployHistory.getDeploy().isPresent() && deployHistory.getDeploy().get().getExecutorData().isPresent()) {
tag = deployHistory.getDeploy().get().getExecutorData().get().getLoggingTag();
}
Collection<String> prefixes = SingularityS3FormatHelper.getS3KeyPrefixes(s3Configuration.getS3KeyFormat(), requestId, deployId, tag, start, end);
LOG.trace("Request {}, deploy {} got S3 prefixes {} for start {}, end {}, tag {}", requestId, deployId, prefixes, start, end, tag);
return prefixes;
}
private List<SingularityS3Log> getS3LogsWithExecutorService(S3Configuration s3Configuration, Optional<String> group, ListeningExecutorService executorService, Collection<String> prefixes) throws InterruptedException, ExecutionException, TimeoutException {
List<ListenableFuture<S3Object[]>> futures = Lists.newArrayListWithCapacity(prefixes.size());
final String s3Bucket = (group.isPresent() && s3Configuration.getGroupOverrides().containsKey(group.get())) ? s3Configuration.getGroupOverrides().get(group.get()).getS3Bucket() : s3Configuration.getS3Bucket();
final S3Service s3Service = (group.isPresent() && s3GroupOverride.containsKey(group.get())) ? s3GroupOverride.get(group.get()) : s3ServiceDefault.get();
for (final String s3Prefix : prefixes) {
futures.add(executorService.submit(new Callable<S3Object[]>() {
@Override
public S3Object[] call() throws Exception {
return s3Service.listObjects(s3Bucket, s3Prefix, null);
}
}));
}
final long start = System.currentTimeMillis();
List<S3Object[]> results = Futures.allAsList(futures).get(s3Configuration.getWaitForS3ListSeconds(), TimeUnit.SECONDS);
List<S3Object> objects = Lists.newArrayListWithExpectedSize(results.size() * 2);
for (S3Object[] s3Objects : results) {
for (final S3Object s3Object : s3Objects) {
objects.add(s3Object);
}
}
LOG.trace("Got {} objects from S3 after {}", objects.size(), JavaUtils.duration(start));
List<ListenableFuture<SingularityS3Log>> logFutures = Lists.newArrayListWithCapacity(objects.size());
final Date expireAt = new Date(System.currentTimeMillis() + s3Configuration.getExpireS3LinksAfterMillis());
for (final S3Object s3Object : objects) {
logFutures.add(executorService.submit(new Callable<SingularityS3Log>() {
@Override
public SingularityS3Log call() throws Exception {
String getUrl = s3Service.createSignedGetUrl(s3Bucket, s3Object.getKey(), expireAt);
return new SingularityS3Log(getUrl, s3Object.getKey(), s3Object.getLastModifiedDate().getTime(), s3Object.getContentLength());
}
}));
}
return Futures.allAsList(logFutures).get(s3Configuration.getWaitForS3LinksSeconds(), TimeUnit.SECONDS);
}
private List<SingularityS3Log> getS3Logs(S3Configuration s3Configuration, Optional<String> group, Collection<String> prefixes) throws InterruptedException, ExecutionException, TimeoutException {
if (prefixes.isEmpty()) {
return Collections.emptyList();
}
ListeningExecutorService executorService = MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(Math.min(prefixes.size(), s3Configuration.getMaxS3Threads()),
new ThreadFactoryBuilder().setNameFormat("S3LogFetcher-%d").build()));
try {
List<SingularityS3Log> logs = Lists.newArrayList(getS3LogsWithExecutorService(s3Configuration, group, executorService, prefixes));
Collections.sort(logs, LOG_COMPARATOR);
return logs;
} finally {
executorService.shutdownNow();
}
}
private void checkS3() {
checkNotFound(s3ServiceDefault.isPresent(), "S3 configuration was absent");
checkNotFound(configuration.isPresent(), "S3 configuration was absent");
}
private SingularityRequestWithState getRequest(final String requestId) {
final Optional<SingularityRequestWithState> maybeRequest = requestManager.getRequest(requestId);
checkNotFound(maybeRequest.isPresent(), "RequestId %s does not exist", requestId);
authorizationHelper.checkForAuthorization(maybeRequest.get().getRequest(), user, SingularityAuthorizationScope.READ);
return maybeRequest.get();
}
@GET
@Path("/task/{taskId}")
@ApiOperation("Retrieve the list of logs stored in S3 for a specific task.")
public List<SingularityS3Log> getS3LogsForTask(
@ApiParam("The task ID to search for") @PathParam("taskId") String taskId,
@ApiParam("Start timestamp (millis, 13 digit)") @QueryParam("start") Optional<Long> start,
@ApiParam("End timestamp (mills, 13 digit)") @QueryParam("end") Optional<Long> end) throws Exception {
checkS3();
SingularityTaskId taskIdObject = getTaskIdObject(taskId);
try {
return getS3Logs(configuration.get(), getRequest(taskIdObject.getRequestId()).getRequest().getGroup(), getS3PrefixesForTask(configuration.get(), taskIdObject, start, end));
} catch (TimeoutException te) {
throw timeout("Timed out waiting for response from S3 for %s", taskId);
} catch (Throwable t) {
throw Throwables.propagate(t);
}
}
@GET
@Path("/request/{requestId}")
@ApiOperation("Retrieve the list of logs stored in S3 for a specific request.")
public List<SingularityS3Log> getS3LogsForRequest(
@ApiParam("The request ID to search for") @PathParam("requestId") String requestId,
@ApiParam("Start timestamp (millis, 13 digit)") @QueryParam("start") Optional<Long> start,
@ApiParam("End timestamp (mills, 13 digit)") @QueryParam("end") Optional<Long> end) throws Exception {
checkS3();
try {
return getS3Logs(configuration.get(), getRequest(requestId).getRequest().getGroup(), getS3PrefixesForRequest(configuration.get(), requestId, start, end));
} catch (TimeoutException te) {
throw timeout("Timed out waiting for response from S3 for %s", requestId);
} catch (Throwable t) {
throw Throwables.propagate(t);
}
}
@GET
@Path("/request/{requestId}/deploy/{deployId}")
@ApiOperation("Retrieve the list of logs stored in S3 for a specific deploy.")
public List<SingularityS3Log> getS3LogsForDeploy(
@ApiParam("The request ID to search for") @PathParam("requestId") String requestId,
@ApiParam("The deploy ID to search for") @PathParam("deployId") String deployId,
@ApiParam("Start timestamp (millis, 13 digit)") @QueryParam("start") Optional<Long> start,
@ApiParam("End timestamp (mills, 13 digit)") @QueryParam("end") Optional<Long> end) throws Exception {
checkS3();
try {
return getS3Logs(configuration.get(), getRequest(requestId).getRequest().getGroup(), getS3PrefixesForDeploy(configuration.get(), requestId, deployId, start, end));
} catch (TimeoutException te) {
throw timeout("Timed out waiting for response from S3 for %s-%s", requestId, deployId);
} catch (Throwable t) {
throw Throwables.propagate(t);
}
}
}
| UTF-8 | Java | 15,018 | java | S3LogResource.java | Java | []
| null | []
| package com.hubspot.singularity.resources;
import static com.hubspot.singularity.WebExceptions.checkNotFound;
import static com.hubspot.singularity.WebExceptions.timeout;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import org.jets3t.service.S3Service;
import org.jets3t.service.model.S3Object;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.base.Optional;
import com.google.common.base.Throwables;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.common.primitives.Longs;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.ListeningExecutorService;
import com.google.common.util.concurrent.MoreExecutors;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import com.google.inject.Inject;
import com.hubspot.mesos.JavaUtils;
import com.hubspot.singularity.SingularityAuthorizationScope;
import com.hubspot.singularity.SingularityDeployHistory;
import com.hubspot.singularity.SingularityRequestHistory;
import com.hubspot.singularity.SingularityRequestHistory.RequestHistoryType;
import com.hubspot.singularity.SingularityRequestWithState;
import com.hubspot.singularity.SingularityS3FormatHelper;
import com.hubspot.singularity.SingularityS3Log;
import com.hubspot.singularity.SingularityService;
import com.hubspot.singularity.SingularityTaskHistory;
import com.hubspot.singularity.SingularityTaskHistoryUpdate;
import com.hubspot.singularity.SingularityTaskHistoryUpdate.SimplifiedTaskState;
import com.hubspot.singularity.SingularityTaskId;
import com.hubspot.singularity.SingularityUser;
import com.hubspot.singularity.auth.SingularityAuthorizationHelper;
import com.hubspot.singularity.config.S3Configuration;
import com.hubspot.singularity.data.DeployManager;
import com.hubspot.singularity.data.RequestManager;
import com.hubspot.singularity.data.TaskManager;
import com.hubspot.singularity.data.history.HistoryManager;
import com.hubspot.singularity.data.history.RequestHistoryHelper;
import com.wordnik.swagger.annotations.Api;
import com.wordnik.swagger.annotations.ApiOperation;
import com.wordnik.swagger.annotations.ApiParam;
@Path(S3LogResource.PATH)
@Produces({ MediaType.APPLICATION_JSON })
@Api(description="Manages Singularity task logs stored in S3.", value=S3LogResource.PATH)
public class S3LogResource extends AbstractHistoryResource {
public static final String PATH = SingularityService.API_BASE_PATH + "/logs";
private static final Logger LOG = LoggerFactory.getLogger(S3LogResource.class);
private final Optional<S3Service> s3ServiceDefault;
private final Map<String, S3Service> s3GroupOverride;
private final Optional<S3Configuration> configuration;
private final RequestHistoryHelper requestHistoryHelper;
private final RequestManager requestManager;
private static final Comparator<SingularityS3Log> LOG_COMPARATOR = new Comparator<SingularityS3Log>() {
@Override
public int compare(SingularityS3Log o1, SingularityS3Log o2) {
return Longs.compare(o2.getLastModified(), o1.getLastModified());
}
};
@Inject
public S3LogResource(RequestManager requestManager, HistoryManager historyManager, RequestHistoryHelper requestHistoryHelper, TaskManager taskManager, DeployManager deployManager, Optional<S3Service> s3ServiceDefault,
Optional<S3Configuration> configuration, SingularityAuthorizationHelper authorizationHelper, Optional<SingularityUser> user, Map<String, S3Service> s3GroupOverride) {
super(historyManager, taskManager, deployManager, authorizationHelper, user);
this.requestManager = requestManager;
this.s3ServiceDefault = s3ServiceDefault;
this.configuration = configuration;
this.requestHistoryHelper = requestHistoryHelper;
this.s3GroupOverride = s3GroupOverride;
}
private Collection<String> getS3PrefixesForTask(S3Configuration s3Configuration, SingularityTaskId taskId, Optional<Long> startArg, Optional<Long> endArg) {
Optional<SingularityTaskHistory> history = getTaskHistory(taskId);
long start = taskId.getStartedAt();
if (startArg.isPresent()) {
start = Math.max(startArg.get(), start);
}
long end = start + s3Configuration.getMissingTaskDefaultS3SearchPeriodMillis();
if (history.isPresent()) {
SimplifiedTaskState taskState = SingularityTaskHistoryUpdate.getCurrentState(history.get().getTaskUpdates());
if (taskState == SimplifiedTaskState.DONE) {
end = Iterables.getLast(history.get().getTaskUpdates()).getTimestamp();
} else {
end = System.currentTimeMillis();
}
}
if (endArg.isPresent()) {
end = Math.min(endArg.get(), end);
}
Optional<String> tag = Optional.absent();
if (history.isPresent() && history.get().getTask().getTaskRequest().getDeploy().getExecutorData().isPresent()) {
tag = history.get().getTask().getTaskRequest().getDeploy().getExecutorData().get().getLoggingTag();
}
Collection<String> prefixes = SingularityS3FormatHelper.getS3KeyPrefixes(s3Configuration.getS3KeyFormat(), taskId, tag, start, end);
LOG.trace("Task {} got S3 prefixes {} for start {}, end {}, tag {}", taskId, prefixes, start, end, tag);
return prefixes;
}
private boolean isCurrentDeploy(String requestId, String deployId) {
return deployId.equals(deployManager.getInUseDeployId(requestId).orNull());
}
private Collection<String> getS3PrefixesForRequest(S3Configuration s3Configuration, String requestId, Optional<Long> startArg, Optional<Long> endArg) {
Optional<SingularityRequestHistory> firstHistory = requestHistoryHelper.getFirstHistory(requestId);
checkNotFound(firstHistory.isPresent(), "No request history found for %s", requestId);
long start = firstHistory.get().getCreatedAt();
if (startArg.isPresent()) {
start = Math.max(startArg.get(), start);
}
Optional<SingularityRequestHistory> lastHistory = requestHistoryHelper.getLastHistory(requestId);
long end = System.currentTimeMillis();
if (lastHistory.isPresent() && (lastHistory.get().getEventType() == RequestHistoryType.DELETED || lastHistory.get().getEventType() == RequestHistoryType.PAUSED)) {
end = lastHistory.get().getCreatedAt() + TimeUnit.DAYS.toMillis(1);
}
if (endArg.isPresent()) {
end = Math.min(endArg.get(), end);
}
Collection<String> prefixes = SingularityS3FormatHelper.getS3KeyPrefixes(s3Configuration.getS3KeyFormat(), requestId, start, end);
LOG.trace("Request {} got S3 prefixes {} for start {}, end {}", requestId, prefixes, start, end);
return prefixes;
}
private Collection<String> getS3PrefixesForDeploy(S3Configuration s3Configuration, String requestId, String deployId, Optional<Long> startArg, Optional<Long> endArg) {
SingularityDeployHistory deployHistory = getDeployHistory(requestId, deployId);
long start = deployHistory.getDeployMarker().getTimestamp();
if (startArg.isPresent()) {
start = Math.max(startArg.get(), start);
}
long end = System.currentTimeMillis();
if (!isCurrentDeploy(requestId, deployId) && deployHistory.getDeployStatistics().isPresent() && deployHistory.getDeployStatistics().get().getLastFinishAt().isPresent()) {
end = deployHistory.getDeployStatistics().get().getLastFinishAt().get() + TimeUnit.DAYS.toMillis(1);
}
if (endArg.isPresent()) {
end = Math.min(endArg.get(), end);
}
Optional<String> tag = Optional.absent();
if (deployHistory.getDeploy().isPresent() && deployHistory.getDeploy().get().getExecutorData().isPresent()) {
tag = deployHistory.getDeploy().get().getExecutorData().get().getLoggingTag();
}
Collection<String> prefixes = SingularityS3FormatHelper.getS3KeyPrefixes(s3Configuration.getS3KeyFormat(), requestId, deployId, tag, start, end);
LOG.trace("Request {}, deploy {} got S3 prefixes {} for start {}, end {}, tag {}", requestId, deployId, prefixes, start, end, tag);
return prefixes;
}
private List<SingularityS3Log> getS3LogsWithExecutorService(S3Configuration s3Configuration, Optional<String> group, ListeningExecutorService executorService, Collection<String> prefixes) throws InterruptedException, ExecutionException, TimeoutException {
List<ListenableFuture<S3Object[]>> futures = Lists.newArrayListWithCapacity(prefixes.size());
final String s3Bucket = (group.isPresent() && s3Configuration.getGroupOverrides().containsKey(group.get())) ? s3Configuration.getGroupOverrides().get(group.get()).getS3Bucket() : s3Configuration.getS3Bucket();
final S3Service s3Service = (group.isPresent() && s3GroupOverride.containsKey(group.get())) ? s3GroupOverride.get(group.get()) : s3ServiceDefault.get();
for (final String s3Prefix : prefixes) {
futures.add(executorService.submit(new Callable<S3Object[]>() {
@Override
public S3Object[] call() throws Exception {
return s3Service.listObjects(s3Bucket, s3Prefix, null);
}
}));
}
final long start = System.currentTimeMillis();
List<S3Object[]> results = Futures.allAsList(futures).get(s3Configuration.getWaitForS3ListSeconds(), TimeUnit.SECONDS);
List<S3Object> objects = Lists.newArrayListWithExpectedSize(results.size() * 2);
for (S3Object[] s3Objects : results) {
for (final S3Object s3Object : s3Objects) {
objects.add(s3Object);
}
}
LOG.trace("Got {} objects from S3 after {}", objects.size(), JavaUtils.duration(start));
List<ListenableFuture<SingularityS3Log>> logFutures = Lists.newArrayListWithCapacity(objects.size());
final Date expireAt = new Date(System.currentTimeMillis() + s3Configuration.getExpireS3LinksAfterMillis());
for (final S3Object s3Object : objects) {
logFutures.add(executorService.submit(new Callable<SingularityS3Log>() {
@Override
public SingularityS3Log call() throws Exception {
String getUrl = s3Service.createSignedGetUrl(s3Bucket, s3Object.getKey(), expireAt);
return new SingularityS3Log(getUrl, s3Object.getKey(), s3Object.getLastModifiedDate().getTime(), s3Object.getContentLength());
}
}));
}
return Futures.allAsList(logFutures).get(s3Configuration.getWaitForS3LinksSeconds(), TimeUnit.SECONDS);
}
private List<SingularityS3Log> getS3Logs(S3Configuration s3Configuration, Optional<String> group, Collection<String> prefixes) throws InterruptedException, ExecutionException, TimeoutException {
if (prefixes.isEmpty()) {
return Collections.emptyList();
}
ListeningExecutorService executorService = MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(Math.min(prefixes.size(), s3Configuration.getMaxS3Threads()),
new ThreadFactoryBuilder().setNameFormat("S3LogFetcher-%d").build()));
try {
List<SingularityS3Log> logs = Lists.newArrayList(getS3LogsWithExecutorService(s3Configuration, group, executorService, prefixes));
Collections.sort(logs, LOG_COMPARATOR);
return logs;
} finally {
executorService.shutdownNow();
}
}
private void checkS3() {
checkNotFound(s3ServiceDefault.isPresent(), "S3 configuration was absent");
checkNotFound(configuration.isPresent(), "S3 configuration was absent");
}
private SingularityRequestWithState getRequest(final String requestId) {
final Optional<SingularityRequestWithState> maybeRequest = requestManager.getRequest(requestId);
checkNotFound(maybeRequest.isPresent(), "RequestId %s does not exist", requestId);
authorizationHelper.checkForAuthorization(maybeRequest.get().getRequest(), user, SingularityAuthorizationScope.READ);
return maybeRequest.get();
}
@GET
@Path("/task/{taskId}")
@ApiOperation("Retrieve the list of logs stored in S3 for a specific task.")
public List<SingularityS3Log> getS3LogsForTask(
@ApiParam("The task ID to search for") @PathParam("taskId") String taskId,
@ApiParam("Start timestamp (millis, 13 digit)") @QueryParam("start") Optional<Long> start,
@ApiParam("End timestamp (mills, 13 digit)") @QueryParam("end") Optional<Long> end) throws Exception {
checkS3();
SingularityTaskId taskIdObject = getTaskIdObject(taskId);
try {
return getS3Logs(configuration.get(), getRequest(taskIdObject.getRequestId()).getRequest().getGroup(), getS3PrefixesForTask(configuration.get(), taskIdObject, start, end));
} catch (TimeoutException te) {
throw timeout("Timed out waiting for response from S3 for %s", taskId);
} catch (Throwable t) {
throw Throwables.propagate(t);
}
}
@GET
@Path("/request/{requestId}")
@ApiOperation("Retrieve the list of logs stored in S3 for a specific request.")
public List<SingularityS3Log> getS3LogsForRequest(
@ApiParam("The request ID to search for") @PathParam("requestId") String requestId,
@ApiParam("Start timestamp (millis, 13 digit)") @QueryParam("start") Optional<Long> start,
@ApiParam("End timestamp (mills, 13 digit)") @QueryParam("end") Optional<Long> end) throws Exception {
checkS3();
try {
return getS3Logs(configuration.get(), getRequest(requestId).getRequest().getGroup(), getS3PrefixesForRequest(configuration.get(), requestId, start, end));
} catch (TimeoutException te) {
throw timeout("Timed out waiting for response from S3 for %s", requestId);
} catch (Throwable t) {
throw Throwables.propagate(t);
}
}
@GET
@Path("/request/{requestId}/deploy/{deployId}")
@ApiOperation("Retrieve the list of logs stored in S3 for a specific deploy.")
public List<SingularityS3Log> getS3LogsForDeploy(
@ApiParam("The request ID to search for") @PathParam("requestId") String requestId,
@ApiParam("The deploy ID to search for") @PathParam("deployId") String deployId,
@ApiParam("Start timestamp (millis, 13 digit)") @QueryParam("start") Optional<Long> start,
@ApiParam("End timestamp (mills, 13 digit)") @QueryParam("end") Optional<Long> end) throws Exception {
checkS3();
try {
return getS3Logs(configuration.get(), getRequest(requestId).getRequest().getGroup(), getS3PrefixesForDeploy(configuration.get(), requestId, deployId, start, end));
} catch (TimeoutException te) {
throw timeout("Timed out waiting for response from S3 for %s-%s", requestId, deployId);
} catch (Throwable t) {
throw Throwables.propagate(t);
}
}
}
| 15,018 | 0.751631 | 0.740844 | 335 | 43.829849 | 46.441338 | 257 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.865672 | false | false | 13 |
5780656bf1c832343f19c5923bf511381cd7983d | 6,631,429,521,417 | aba19119da471d6c4de933196de0bf713ed99e20 | /ensembl-pipeline/java/pipeview/src/pathsteps/gui/EventRouter.java | e671580c130ad24875d135cb629589da2870b496 | []
| no_license | imcb-ensembl/ensembl-50-bronwen | https://github.com/imcb-ensembl/ensembl-50-bronwen | b9178793db993bc77c80fe3c40a9d641b8033e8c | b16454be152b309a7aa8bc46dc574791af727fb6 | refs/heads/master | 2020-05-17T10:42:23.685000 | 2009-04-07T07:25:02 | 2009-04-07T07:25:02 | 169,991 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package pathsteps.gui;
import java.awt.event.*;
import pathsteps.common.*;
/**
* Generic class to forward any old events onto central handler.
**/
public abstract class EventRouter
{
String key;
Application handler;
public EventRouter(Application handler, String key){
this.handler = handler;
this.key = key;
}
protected Application getHandler(){
return handler;
}
protected String getKey(){
return key;
}
}
| UTF-8 | Java | 478 | java | EventRouter.java | Java | []
| null | []
| package pathsteps.gui;
import java.awt.event.*;
import pathsteps.common.*;
/**
* Generic class to forward any old events onto central handler.
**/
public abstract class EventRouter
{
String key;
Application handler;
public EventRouter(Application handler, String key){
this.handler = handler;
this.key = key;
}
protected Application getHandler(){
return handler;
}
protected String getKey(){
return key;
}
}
| 478 | 0.650628 | 0.650628 | 26 | 16.384615 | 16.868443 | 64 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.384615 | false | false | 13 |
d4da098724eb7bd1cf7e07abec62d2e5fdd93de7 | 17,789,754,599,748 | 219cbfd2b09c8989afbdcdd4198b77dd93799b1e | /develop/server/project/base/src/main/java/com/home/base/constlist/generate/GPlayerPartDataType.java | 5b17c4cd5943d00fa8d90e5ab42f6767a52e997b | [
"Apache-2.0"
]
| permissive | shineTeam7/tank | https://github.com/shineTeam7/tank | 2c9d6e1f01ebe6803731b520ce84eea52c593d2b | 1d37e93474bc00ca3923be08d0742849c73f1049 | refs/heads/master | 2022-12-02T01:35:12.116000 | 2020-08-17T12:09:01 | 2020-08-17T12:09:01 | 288,139,019 | 2 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.home.base.constlist.generate;
/** (generated by shine) */
public class GPlayerPartDataType
{
/** ่ตทๅง */
public static final int off=12508;
/** ่ฎกๆฐ */
public static final int count=12516;
/** ่ๅ
*/
public static final int GBag=12508;
/** ่ง่ฒๆจกๅ */
public static final int GCharacter=12509;
public static final int GRole=12510;
public static final int GUnion=12511;
public static final int GFriend=12512;
public static final int GFunc=12513;
public static final int GTeam=12514;
public static final int GScene=12515;
}
| UTF-8 | Java | 610 | java | GPlayerPartDataType.java | Java | []
| null | []
| package com.home.base.constlist.generate;
/** (generated by shine) */
public class GPlayerPartDataType
{
/** ่ตทๅง */
public static final int off=12508;
/** ่ฎกๆฐ */
public static final int count=12516;
/** ่ๅ
*/
public static final int GBag=12508;
/** ่ง่ฒๆจกๅ */
public static final int GCharacter=12509;
public static final int GRole=12510;
public static final int GUnion=12511;
public static final int GFriend=12512;
public static final int GFunc=12513;
public static final int GTeam=12514;
public static final int GScene=12515;
}
| 610 | 0.672881 | 0.588136 | 30 | 17.666666 | 17.026123 | 42 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.166667 | false | false | 13 |
9ef5e823e04a0b55d5d37ba42ea8f2a023a73440 | 4,664,334,529,371 | 5432aee1665affbe200a6e8cfcb081fa66139bc9 | /src/main/java/com/robertx22/mine_and_slash/professions/blocks/bases/ProfessionContainer.java | cde2f1cbaa63b61c1b6a723d2415443a02e27c22 | []
| no_license | saki-saki/Mine-and-Slash | https://github.com/saki-saki/Mine-and-Slash | 9cc8587e5c082470847c7159223666cbc099c454 | 9fd77a6c661f821bf36e773cfbfb944b682020d7 | refs/heads/1.14.4 | 2020-08-28T20:26:13.061000 | 2019-10-30T21:41:33 | 2019-10-30T21:41:33 | 217,811,792 | 0 | 1 | null | true | 2019-10-30T21:41:34 | 2019-10-27T05:57:39 | 2019-10-28T05:13:58 | 2019-10-30T21:41:34 | 74,041 | 0 | 1 | 0 | Java | false | false | package com.robertx22.mine_and_slash.professions.blocks.bases;
import com.robertx22.mine_and_slash.blocks.bases.BaseTileContainer;
import com.robertx22.mine_and_slash.blocks.slots.handlerslots.MaterialSlot;
import com.robertx22.mine_and_slash.mmorpg.registers.common.ContainerTypeRegisters;
import com.robertx22.mine_and_slash.professions.blocks.alchemy.AlchemyTile;
import com.robertx22.mine_and_slash.professions.recipe.BaseMaterial;
import com.robertx22.mine_and_slash.professions.recipe.BaseRecipe;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.entity.player.PlayerInventory;
import net.minecraft.inventory.container.Slot;
import net.minecraft.item.ItemStack;
import net.minecraft.network.PacketBuffer;
import net.minecraft.util.NonNullList;
import net.minecraft.util.math.BlockPos;
import net.minecraftforge.items.ItemStackHandler;
import net.minecraftforge.items.SlotItemHandler;
public class ProfessionContainer extends BaseTileContainer {
public static int size = 6 * 9;
public ProfessionTile tile;
Professions profession = Professions.ALCHEMY;
public BlockPos pos;
static int PLAYER_INV_INDEX = 0;
static int PLAYER_INV_END = 36;
PlayerInventory playerInventory;
public ProfessionContainer(int i, PlayerInventory playerInventory,
PacketBuffer packetBuffer) {
this(i, new AlchemyTile(), packetBuffer.readBlockPos(), playerInventory);
}
protected ProfessionContainer(int id, ProfessionTile tile, BlockPos pos,
PlayerInventory invPlayer) {
super(6 * 9, ContainerTypeRegisters.PROFESSION_RECIPE_CONTAINER, id);
this.profession = tile.profession;
this.pos = pos;
this.tile = tile;
this.playerInventory = invPlayer;
addPlayerSlots(invPlayer);
addTileSlots(tile);
}
static int x = 318;
static int y = 232;
public void addTileSlots(ProfessionTile tile) {
int addX = 142 + 44;
int addY = y / 2 + 9;
ItemStackHandler outputhandler = new ItemStackHandler(tile.outputStacks);
for (int i = 0; i < tile.outputStacks.size(); i++) {
this.addSlot(new SlotItemHandler(outputhandler, i, addX, addY));
addX += 18;
}
addX = 142 + 44;
addY -= 52; // for mat slots
ItemStackHandler mathandler = new ItemStackHandler(tile.materialStacks);
for (int i = 0; i < tile.materialStacks.size(); i++) {
this.addSlot(new MaterialSlot(mathandler, i, addX, addY));
addX += 18;
}
}
public void addPlayerSlots(PlayerInventory playerInv) {
int addX = 142;
int addY = y / 2 + 35;
for (int row = 0; row < 3; ++row) {
for (int column = 0; column < 9; ++column) {
int index = column + row * 9 + 9;
int x = 8 + column * 18 + addX;
int y = row * 18 + addY;
this.addSlot(new Slot(playerInv, index, x, y));
}
}
for (int index = 0; index < 9; ++index) {
this.addSlot(new Slot(playerInv, index, 8 + index * 18 + addX, addY + 3 * 18 + 4));
}
}
public void onRecipeChoosen(BaseRecipe recipe) {
clearMaterials();
for (int i = 0; i < recipe.getMaterials().size(); i++) {
this.gatherMaterial(i);
}
}
public void clearMaterials() {
ItemStackHandler handler = new ItemStackHandler(tile.materialStacks);
ItemStackHandler playerHandler = this.getPlayerInventoryHandler();
for (int i = 0; i < tile.materialStacks.size(); i++) {
ItemStack stack = handler.extractItem(i, handler.getStackInSlot(i)
.getCount(), false);
if (!stack.isEmpty()) {
boolean inserted = false;
for (int x = 0; x < playerHandler.getSlots(); x++) {
if (this.playerInventory.addItemStackToInventory(stack)) {
inserted = true;
break;
}
}
if (!inserted) {
handler.insertItem(i, stack, false); // put it back if no place
}
}
}
}
public ItemStackHandler getPlayerInventoryHandler() {
NonNullList<ItemStack> list = NonNullList.withSize(PLAYER_INV_END - PLAYER_INV_INDEX, ItemStack.EMPTY);
int num = 0;
for (int i = PLAYER_INV_INDEX; i < PLAYER_INV_END; i++) {
list.set(num++, this.getInventory().get(i));
}
return new ItemStackHandler(list);
}
public void gatherMaterial(int num) {
for (int i = 0; i < this.playerInventory.mainInventory.size(); ++i) {
ItemStack itemstack = this.playerInventory.mainInventory.get(i).getStack();
if (!itemstack.isEmpty()) {
if (this.tile.currentRecipe.getMaterials().size() > num) {
ItemStackHandler handler = new ItemStackHandler(tile.materialStacks);
BaseMaterial mat = this.tile.currentRecipe.getMaterials().get(num);
if (mat.isStackValidMaterial(itemstack)) {
ItemStack copy = itemstack.copy();
if (handler.insertItem(num, copy, true) == ItemStack.EMPTY) {
handler.insertItem(num, copy, false);
itemstack.shrink(itemstack.getCount());
}
}
}
}
}
}
@Override
public boolean canInteractWith(PlayerEntity playerIn) {
return true;
}
}
| UTF-8 | Java | 5,743 | java | ProfessionContainer.java | Java | [
{
"context": "package com.robertx22.mine_and_slash.professions.blocks.bases;\n\nimport ",
"end": 21,
"score": 0.9537755846977234,
"start": 18,
"tag": "USERNAME",
"value": "x22"
},
{
"context": "slash.professions.blocks.bases;\n\nimport com.robertx22.mine_and_slash.blocks.bases.BaseTileContainer;\nim",
"end": 84,
"score": 0.9606694579124451,
"start": 81,
"tag": "USERNAME",
"value": "x22"
},
{
"context": ".blocks.bases.BaseTileContainer;\nimport com.robertx22.mine_and_slash.blocks.slots.handlerslots.Material",
"end": 152,
"score": 0.838529109954834,
"start": 149,
"tag": "USERNAME",
"value": "x22"
},
{
"context": "slots.handlerslots.MaterialSlot;\nimport com.robertx22.mine_and_slash.mmorpg.registers.common.ContainerT",
"end": 228,
"score": 0.8840923309326172,
"start": 225,
"tag": "USERNAME",
"value": "x22"
},
{
"context": "s.common.ContainerTypeRegisters;\nimport com.robertx22.mine_and_slash.professions.blocks.alchemy.Alchemy",
"end": 312,
"score": 0.9242703914642334,
"start": 309,
"tag": "USERNAME",
"value": "x22"
},
{
"context": "ions.blocks.alchemy.AlchemyTile;\nimport com.robertx22.mine_and_slash.professions.recipe.BaseMaterial;\ni",
"end": 388,
"score": 0.9433774352073669,
"start": 385,
"tag": "USERNAME",
"value": "x22"
},
{
"context": "professions.recipe.BaseMaterial;\nimport com.robertx22.mine_and_slash.professions.recipe.BaseRecipe;\nimp",
"end": 457,
"score": 0.8135030269622803,
"start": 454,
"tag": "USERNAME",
"value": "x22"
}
]
| null | []
| package com.robertx22.mine_and_slash.professions.blocks.bases;
import com.robertx22.mine_and_slash.blocks.bases.BaseTileContainer;
import com.robertx22.mine_and_slash.blocks.slots.handlerslots.MaterialSlot;
import com.robertx22.mine_and_slash.mmorpg.registers.common.ContainerTypeRegisters;
import com.robertx22.mine_and_slash.professions.blocks.alchemy.AlchemyTile;
import com.robertx22.mine_and_slash.professions.recipe.BaseMaterial;
import com.robertx22.mine_and_slash.professions.recipe.BaseRecipe;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.entity.player.PlayerInventory;
import net.minecraft.inventory.container.Slot;
import net.minecraft.item.ItemStack;
import net.minecraft.network.PacketBuffer;
import net.minecraft.util.NonNullList;
import net.minecraft.util.math.BlockPos;
import net.minecraftforge.items.ItemStackHandler;
import net.minecraftforge.items.SlotItemHandler;
public class ProfessionContainer extends BaseTileContainer {
public static int size = 6 * 9;
public ProfessionTile tile;
Professions profession = Professions.ALCHEMY;
public BlockPos pos;
static int PLAYER_INV_INDEX = 0;
static int PLAYER_INV_END = 36;
PlayerInventory playerInventory;
public ProfessionContainer(int i, PlayerInventory playerInventory,
PacketBuffer packetBuffer) {
this(i, new AlchemyTile(), packetBuffer.readBlockPos(), playerInventory);
}
protected ProfessionContainer(int id, ProfessionTile tile, BlockPos pos,
PlayerInventory invPlayer) {
super(6 * 9, ContainerTypeRegisters.PROFESSION_RECIPE_CONTAINER, id);
this.profession = tile.profession;
this.pos = pos;
this.tile = tile;
this.playerInventory = invPlayer;
addPlayerSlots(invPlayer);
addTileSlots(tile);
}
static int x = 318;
static int y = 232;
public void addTileSlots(ProfessionTile tile) {
int addX = 142 + 44;
int addY = y / 2 + 9;
ItemStackHandler outputhandler = new ItemStackHandler(tile.outputStacks);
for (int i = 0; i < tile.outputStacks.size(); i++) {
this.addSlot(new SlotItemHandler(outputhandler, i, addX, addY));
addX += 18;
}
addX = 142 + 44;
addY -= 52; // for mat slots
ItemStackHandler mathandler = new ItemStackHandler(tile.materialStacks);
for (int i = 0; i < tile.materialStacks.size(); i++) {
this.addSlot(new MaterialSlot(mathandler, i, addX, addY));
addX += 18;
}
}
public void addPlayerSlots(PlayerInventory playerInv) {
int addX = 142;
int addY = y / 2 + 35;
for (int row = 0; row < 3; ++row) {
for (int column = 0; column < 9; ++column) {
int index = column + row * 9 + 9;
int x = 8 + column * 18 + addX;
int y = row * 18 + addY;
this.addSlot(new Slot(playerInv, index, x, y));
}
}
for (int index = 0; index < 9; ++index) {
this.addSlot(new Slot(playerInv, index, 8 + index * 18 + addX, addY + 3 * 18 + 4));
}
}
public void onRecipeChoosen(BaseRecipe recipe) {
clearMaterials();
for (int i = 0; i < recipe.getMaterials().size(); i++) {
this.gatherMaterial(i);
}
}
public void clearMaterials() {
ItemStackHandler handler = new ItemStackHandler(tile.materialStacks);
ItemStackHandler playerHandler = this.getPlayerInventoryHandler();
for (int i = 0; i < tile.materialStacks.size(); i++) {
ItemStack stack = handler.extractItem(i, handler.getStackInSlot(i)
.getCount(), false);
if (!stack.isEmpty()) {
boolean inserted = false;
for (int x = 0; x < playerHandler.getSlots(); x++) {
if (this.playerInventory.addItemStackToInventory(stack)) {
inserted = true;
break;
}
}
if (!inserted) {
handler.insertItem(i, stack, false); // put it back if no place
}
}
}
}
public ItemStackHandler getPlayerInventoryHandler() {
NonNullList<ItemStack> list = NonNullList.withSize(PLAYER_INV_END - PLAYER_INV_INDEX, ItemStack.EMPTY);
int num = 0;
for (int i = PLAYER_INV_INDEX; i < PLAYER_INV_END; i++) {
list.set(num++, this.getInventory().get(i));
}
return new ItemStackHandler(list);
}
public void gatherMaterial(int num) {
for (int i = 0; i < this.playerInventory.mainInventory.size(); ++i) {
ItemStack itemstack = this.playerInventory.mainInventory.get(i).getStack();
if (!itemstack.isEmpty()) {
if (this.tile.currentRecipe.getMaterials().size() > num) {
ItemStackHandler handler = new ItemStackHandler(tile.materialStacks);
BaseMaterial mat = this.tile.currentRecipe.getMaterials().get(num);
if (mat.isStackValidMaterial(itemstack)) {
ItemStack copy = itemstack.copy();
if (handler.insertItem(num, copy, true) == ItemStack.EMPTY) {
handler.insertItem(num, copy, false);
itemstack.shrink(itemstack.getCount());
}
}
}
}
}
}
@Override
public boolean canInteractWith(PlayerEntity playerIn) {
return true;
}
}
| 5,743 | 0.592199 | 0.578617 | 186 | 29.876345 | 29.153667 | 111 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.655914 | false | false | 13 |
8de8d03297752d82a6e0c30920afdaaf7ba818a8 | 4,664,334,529,071 | 5050c75dbb42641834c7ca49105ec2e6baa0a0db | /mymuke/src/serviceimpl/ReplyServiceImpl.java | cfbe48f1e9ae0d50865eaed3df0edbe405509b7e | []
| no_license | 986565479/CMuKe | https://github.com/986565479/CMuKe | 752b9146c00be21f8ac5542947b3308dc1759611 | daa8c7cde919a76250dc2072bc6ff1a30fecb390 | refs/heads/master | 2021-07-23T10:06:42.432000 | 2017-11-04T01:51:28 | 2017-11-04T01:51:28 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package serviceimpl;
import dao.IReplyDao;
import daoimpl.ReplyDaoImpl;
import po.Reply;
import service.IReplyService;
public class ReplyServiceImpl implements IReplyService{
private IReplyDao idao = new ReplyDaoImpl();
@Override
public int replyMsg(Reply reply) {
return idao.replyMsg(reply);
}
}
| UTF-8 | Java | 310 | java | ReplyServiceImpl.java | Java | []
| null | []
| package serviceimpl;
import dao.IReplyDao;
import daoimpl.ReplyDaoImpl;
import po.Reply;
import service.IReplyService;
public class ReplyServiceImpl implements IReplyService{
private IReplyDao idao = new ReplyDaoImpl();
@Override
public int replyMsg(Reply reply) {
return idao.replyMsg(reply);
}
}
| 310 | 0.783871 | 0.783871 | 15 | 19.666666 | 17.280689 | 55 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.8 | false | false | 13 |
54cd772cf71f19d4be5a31bd8690424fcca31514 | 23,587,960,391,699 | db468e2b6fdf91597e99c2064a916020c064f000 | /app/src/main/java/com/example/finalproject/utils/JsonUtils.java | b4f47b4090ae71e19afd61d01b22f8e783a6e7a2 | []
| no_license | Sampaio98/finalproject_front | https://github.com/Sampaio98/finalproject_front | 6450a816ed99f89fa196409aceca5a5508229ca6 | c718710d46869e2b6bfc0ba91efa156da567aae7 | refs/heads/master | 2022-01-29T13:47:30.618000 | 2019-06-11T03:20:36 | 2019-06-11T03:20:36 | 189,912,248 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.finalproject.utils;
import com.fasterxml.jackson.annotation.JsonRootName;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
import java.lang.reflect.Type;
import java.util.Objects;
public abstract class JsonUtils {
public static Gson getGson(Type type) {
return new GsonBuilder()
.setDateFormat("yyyy-MM-dd'T'HH:mm:ss")
.registerTypeAdapter(type, new GsonRootSerializer())
.create();
}
static class GsonRootSerializer implements JsonSerializer<Object> {
@Override
public JsonElement serialize(Object src, Type typeOfSrc, JsonSerializationContext context) {
Gson gson = new Gson();
JsonElement je = gson.toJsonTree(src);
JsonObject jo = new JsonObject();
jo.add(Objects.requireNonNull(src.getClass().getAnnotation(JsonRootName.class)).value(), je);
return jo;
}
}
}
| UTF-8 | Java | 1,121 | java | JsonUtils.java | Java | []
| null | []
| package com.example.finalproject.utils;
import com.fasterxml.jackson.annotation.JsonRootName;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
import java.lang.reflect.Type;
import java.util.Objects;
public abstract class JsonUtils {
public static Gson getGson(Type type) {
return new GsonBuilder()
.setDateFormat("yyyy-MM-dd'T'HH:mm:ss")
.registerTypeAdapter(type, new GsonRootSerializer())
.create();
}
static class GsonRootSerializer implements JsonSerializer<Object> {
@Override
public JsonElement serialize(Object src, Type typeOfSrc, JsonSerializationContext context) {
Gson gson = new Gson();
JsonElement je = gson.toJsonTree(src);
JsonObject jo = new JsonObject();
jo.add(Objects.requireNonNull(src.getClass().getAnnotation(JsonRootName.class)).value(), je);
return jo;
}
}
}
| 1,121 | 0.686887 | 0.686887 | 34 | 31.970589 | 26.705898 | 105 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.588235 | false | false | 13 |
9a0ec450011b48e5db4a54131926dbbcbd26a496 | 30,185,030,157,641 | 0ccd244d099b3fcbf4c6c427d0ac66c00dfb678c | /src/main/java/com/twschool/practice/KlassSubject.java | dab6891b9b86b9549c3178f3d7ccf2aa07418a52 | []
| no_license | qicaisheng/OO_Step_by_Step | https://github.com/qicaisheng/OO_Step_by_Step | ef89a7d29ce30dbd7ed13749ccf17f22353fe068 | 298038dafff2d828a65075af88cec79b72b3ea1f | refs/heads/master | 2022-11-16T16:14:21.567000 | 2020-07-10T06:29:06 | 2020-07-10T06:29:06 | 278,557,950 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.twschool.practice;
public interface KlassSubject {
void register(KlassObserver klassObserver);
void notify(String message);
}
| UTF-8 | Java | 148 | java | KlassSubject.java | Java | []
| null | []
| package com.twschool.practice;
public interface KlassSubject {
void register(KlassObserver klassObserver);
void notify(String message);
}
| 148 | 0.77027 | 0.77027 | 7 | 20.142857 | 17.947769 | 47 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.428571 | false | false | 13 |
3099d5654fda678619dcca8c5b945e7ca228049a | 3,118,146,264,280 | 32f38cd53372ba374c6dab6cc27af78f0a1b0190 | /app/src/main/java/defpackage/azz.java | c23ece12d86c6e865049acad500c4f0279075726 | [
"BSD-3-Clause"
]
| permissive | shuixi2013/AmapCode | https://github.com/shuixi2013/AmapCode | 9ea7aefb42e0413f348f238f0721c93245f4eac6 | 1a3a8d4dddfcc5439df8df570000cca12b15186a | refs/heads/master | 2023-06-06T23:08:57.391000 | 2019-08-29T04:36:02 | 2019-08-29T04:36:02 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package defpackage;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import com.amap.bundle.logs.AMapLog;
import com.autonavi.amap.app.AMapAppGlobal;
import com.autonavi.jni.eyrie.amap.redesign.maps.overlay.BaseLayer;
import com.autonavi.jni.eyrie.amap.redesign.maps.overlay.IClickListener;
import com.autonavi.jni.eyrie.amap.redesign.maps.overlay.PointOverlay;
import com.autonavi.jni.eyrie.amap.redesign.maps.texture.OverlayTextureParam;
import com.autonavi.jni.eyrie.amap.redesign.maps.texture.TextureWrapper;
import com.autonavi.jni.eyrie.amap.redesign.maps.vmap.IVPageContext;
import com.autonavi.minimap.R;
/* renamed from: azz reason: default package */
/* compiled from: DriveCommuteTipsSimLayer */
public final class azz extends BaseLayer {
private final String a = "DriveCommuteTipsSimLayer";
private final String b = "redesign://basemap/RouteCommute/sim/";
private PointOverlay<bac> c = new PointOverlay<>(this, "Commute");
private bac d = new bac();
private View e = LayoutInflater.from(AMapAppGlobal.getApplication()).inflate(R.layout.drive_commute_tips_sim_layout, null);
private ImageView f = ((ImageView) this.e.findViewById(R.id.commute_tips_sim_icon));
public azz(IVPageContext iVPageContext) {
super(iVPageContext);
this.c.addItem(this.d);
}
public final TextureWrapper loadTexture(OverlayTextureParam overlayTextureParam) {
AMapLog.d("DriveCommuteTipsSimLayer", "loadTexture param:".concat(String.valueOf(overlayTextureParam)));
if (!overlayTextureParam.uri.startsWith("redesign://basemap/RouteCommute/sim/") || !(overlayTextureParam.data instanceof bac)) {
return null;
}
this.f.setImageResource(((bac) overlayTextureParam.data).a);
if (this.e == null) {
return null;
}
return makeTextureWrapper(this.e);
}
/* JADX WARNING: Removed duplicated region for block: B:17:0x002e */
/* Code decompiled incorrectly, please refer to instructions dump. */
public final void a(int r6, com.autonavi.common.model.GeoPoint r7) {
/*
r5 = this;
java.lang.String r0 = "DriveCommuteTipsSimLayer"
java.lang.String r1 = "updateItem commuteType:"
java.lang.String r2 = java.lang.String.valueOf(r6)
java.lang.String r1 = r1.concat(r2)
com.amap.bundle.logs.AMapLog.d(r0, r1)
if (r7 != 0) goto L_0x0012
return
L_0x0012:
r0 = 0
r1 = 1
if (r6 == r1) goto L_0x002a
r1 = 3
if (r6 == r1) goto L_0x0027
r1 = 5
if (r6 == r1) goto L_0x002a
r1 = 7
if (r6 == r1) goto L_0x0027
r1 = 9
if (r6 == r1) goto L_0x0024
goto L_0x002c
L_0x0024:
int r0 = com.autonavi.minimap.R.drawable.drive_commute_tips_work_home_sim
goto L_0x002c
L_0x0027:
int r0 = com.autonavi.minimap.R.drawable.drive_commute_tips_work_sim
goto L_0x002c
L_0x002a:
int r0 = com.autonavi.minimap.R.drawable.drive_commute_tips_home_sim
L_0x002c:
if (r0 == 0) goto L_0x0062
bac r6 = r5.d
r6.a = r0
bac r6 = r5.d
java.lang.String r1 = "redesign://basemap/RouteCommute/sim/"
java.lang.String r0 = java.lang.String.valueOf(r0)
java.lang.String r0 = r1.concat(r0)
r1 = 1056964608(0x3f000000, float:0.5)
r2 = 1065353216(0x3f800000, float:1.0)
bac r3 = r5.d
com.autonavi.jni.eyrie.amap.redesign.maps.texture.OverlayTextureParam r0 = r5.makeCustomTextureParam(r0, r1, r2, r3)
r6.defaultTexture = r0
bac r6 = r5.d
com.autonavi.jni.eyrie.amap.redesign.maps.typedef.Coord r0 = new com.autonavi.jni.eyrie.amap.redesign.maps.typedef.Coord
double r1 = r7.getLongitude()
double r3 = r7.getLatitude()
r0.<init>(r1, r3)
r6.coord = r0
com.autonavi.jni.eyrie.amap.redesign.maps.overlay.PointOverlay<bac> r6 = r5.c
bac r7 = r5.d
r6.updateItem(r7)
L_0x0062:
return
*/
throw new UnsupportedOperationException("Method not decompiled: defpackage.azz.a(int, com.autonavi.common.model.GeoPoint):void");
}
public final void a(IClickListener iClickListener) {
this.c.setClickListener(iClickListener);
}
}
| UTF-8 | Java | 4,585 | java | azz.java | Java | []
| null | []
| package defpackage;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import com.amap.bundle.logs.AMapLog;
import com.autonavi.amap.app.AMapAppGlobal;
import com.autonavi.jni.eyrie.amap.redesign.maps.overlay.BaseLayer;
import com.autonavi.jni.eyrie.amap.redesign.maps.overlay.IClickListener;
import com.autonavi.jni.eyrie.amap.redesign.maps.overlay.PointOverlay;
import com.autonavi.jni.eyrie.amap.redesign.maps.texture.OverlayTextureParam;
import com.autonavi.jni.eyrie.amap.redesign.maps.texture.TextureWrapper;
import com.autonavi.jni.eyrie.amap.redesign.maps.vmap.IVPageContext;
import com.autonavi.minimap.R;
/* renamed from: azz reason: default package */
/* compiled from: DriveCommuteTipsSimLayer */
public final class azz extends BaseLayer {
private final String a = "DriveCommuteTipsSimLayer";
private final String b = "redesign://basemap/RouteCommute/sim/";
private PointOverlay<bac> c = new PointOverlay<>(this, "Commute");
private bac d = new bac();
private View e = LayoutInflater.from(AMapAppGlobal.getApplication()).inflate(R.layout.drive_commute_tips_sim_layout, null);
private ImageView f = ((ImageView) this.e.findViewById(R.id.commute_tips_sim_icon));
public azz(IVPageContext iVPageContext) {
super(iVPageContext);
this.c.addItem(this.d);
}
public final TextureWrapper loadTexture(OverlayTextureParam overlayTextureParam) {
AMapLog.d("DriveCommuteTipsSimLayer", "loadTexture param:".concat(String.valueOf(overlayTextureParam)));
if (!overlayTextureParam.uri.startsWith("redesign://basemap/RouteCommute/sim/") || !(overlayTextureParam.data instanceof bac)) {
return null;
}
this.f.setImageResource(((bac) overlayTextureParam.data).a);
if (this.e == null) {
return null;
}
return makeTextureWrapper(this.e);
}
/* JADX WARNING: Removed duplicated region for block: B:17:0x002e */
/* Code decompiled incorrectly, please refer to instructions dump. */
public final void a(int r6, com.autonavi.common.model.GeoPoint r7) {
/*
r5 = this;
java.lang.String r0 = "DriveCommuteTipsSimLayer"
java.lang.String r1 = "updateItem commuteType:"
java.lang.String r2 = java.lang.String.valueOf(r6)
java.lang.String r1 = r1.concat(r2)
com.amap.bundle.logs.AMapLog.d(r0, r1)
if (r7 != 0) goto L_0x0012
return
L_0x0012:
r0 = 0
r1 = 1
if (r6 == r1) goto L_0x002a
r1 = 3
if (r6 == r1) goto L_0x0027
r1 = 5
if (r6 == r1) goto L_0x002a
r1 = 7
if (r6 == r1) goto L_0x0027
r1 = 9
if (r6 == r1) goto L_0x0024
goto L_0x002c
L_0x0024:
int r0 = com.autonavi.minimap.R.drawable.drive_commute_tips_work_home_sim
goto L_0x002c
L_0x0027:
int r0 = com.autonavi.minimap.R.drawable.drive_commute_tips_work_sim
goto L_0x002c
L_0x002a:
int r0 = com.autonavi.minimap.R.drawable.drive_commute_tips_home_sim
L_0x002c:
if (r0 == 0) goto L_0x0062
bac r6 = r5.d
r6.a = r0
bac r6 = r5.d
java.lang.String r1 = "redesign://basemap/RouteCommute/sim/"
java.lang.String r0 = java.lang.String.valueOf(r0)
java.lang.String r0 = r1.concat(r0)
r1 = 1056964608(0x3f000000, float:0.5)
r2 = 1065353216(0x3f800000, float:1.0)
bac r3 = r5.d
com.autonavi.jni.eyrie.amap.redesign.maps.texture.OverlayTextureParam r0 = r5.makeCustomTextureParam(r0, r1, r2, r3)
r6.defaultTexture = r0
bac r6 = r5.d
com.autonavi.jni.eyrie.amap.redesign.maps.typedef.Coord r0 = new com.autonavi.jni.eyrie.amap.redesign.maps.typedef.Coord
double r1 = r7.getLongitude()
double r3 = r7.getLatitude()
r0.<init>(r1, r3)
r6.coord = r0
com.autonavi.jni.eyrie.amap.redesign.maps.overlay.PointOverlay<bac> r6 = r5.c
bac r7 = r5.d
r6.updateItem(r7)
L_0x0062:
return
*/
throw new UnsupportedOperationException("Method not decompiled: defpackage.azz.a(int, com.autonavi.common.model.GeoPoint):void");
}
public final void a(IClickListener iClickListener) {
this.c.setClickListener(iClickListener);
}
}
| 4,585 | 0.631625 | 0.587568 | 107 | 41.850468 | 31.560297 | 137 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.411215 | false | false | 13 |
c31d923f18c03399f676f54a69d6848fbee5e6af | 15,917,148,866,437 | 07827474e94c88cf62e08f0c8e56ddd2ed143414 | /src/main/java/org/ow2/mind/BinaryComponent.java | 7069e2ed480185cfba0e85c403d55de021c99daa | []
| no_license | Mind4SE/dependency-tools | https://github.com/Mind4SE/dependency-tools | 50573b633900e0f9c01f3838fe60fbcfd8a6a784 | 131c3b21f1dd760c5160c4742db852ca06a545a9 | refs/heads/master | 2021-01-18T02:10:47.867000 | 2014-12-09T16:58:03 | 2014-12-09T16:58:03 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package org.ow2.mind;
import java.io.File;
import java.util.HashSet;
import java.util.Iterator;
/**
*
* @author Julien TOUS
*
*/
public abstract class BinaryComponent extends BinaryObject {
public enum State { start, addr, type }
/**
* Flag to keep track of the "resolved-ness" of the Set
* and it's accessor.
*/
protected boolean resolved = true;
public boolean isResolved() {
return resolved;
}
/*
* Remove self referenced undefined symbols
*/
protected void clearResolved() {
for (Iterator<Symbol> U = undefined.keySet().iterator(); U.hasNext();) {
if (undefined.get(U.next()) == this) {
U.remove();
}
}
}
public abstract void add(File file);
void resolve() {
clearDuplicate();
/*
* resolveAgainst ourself as the component is made of several files.
* Inter files dependency are not resolved by the compiler so we need
* track them here.
*/
resolveAgainst(this);
/*
* Once we resolved what could be resolved, lets remove unnecessary link.
*/
clearResolved();
resolved=true;
}
/*
* Remove duplicated referenced undefined symbols
*/
protected void clearDuplicate() {
Symbol sym1;
Symbol sym2;
Iterator<Symbol> U1 = undefined.keySet().iterator();
while ( U1.hasNext()) {
sym1 = U1.next();
Iterator<Symbol> U2 = (new HashSet<Symbol>( undefined.keySet()) ).iterator();
while (U2.hasNext()) {
sym2 = U2.next();
if (sym1 != sym2) {
if (sym1.name.equals(sym2.name)) {
sym2.origin = sym2.origin + File.pathSeparator + sym1.origin;
U1.remove();
break;
}
}
}
}
}
}
| UTF-8 | Java | 1,615 | java | BinaryComponent.java | Java | [
{
"context": "et;\nimport java.util.Iterator;\n\n/**\n * \n * @author Julien TOUS\n * \n */\n\npublic abstract class BinaryComponent ex",
"end": 128,
"score": 0.9998204112052917,
"start": 117,
"tag": "NAME",
"value": "Julien TOUS"
}
]
| null | []
| package org.ow2.mind;
import java.io.File;
import java.util.HashSet;
import java.util.Iterator;
/**
*
* @author <NAME>
*
*/
public abstract class BinaryComponent extends BinaryObject {
public enum State { start, addr, type }
/**
* Flag to keep track of the "resolved-ness" of the Set
* and it's accessor.
*/
protected boolean resolved = true;
public boolean isResolved() {
return resolved;
}
/*
* Remove self referenced undefined symbols
*/
protected void clearResolved() {
for (Iterator<Symbol> U = undefined.keySet().iterator(); U.hasNext();) {
if (undefined.get(U.next()) == this) {
U.remove();
}
}
}
public abstract void add(File file);
void resolve() {
clearDuplicate();
/*
* resolveAgainst ourself as the component is made of several files.
* Inter files dependency are not resolved by the compiler so we need
* track them here.
*/
resolveAgainst(this);
/*
* Once we resolved what could be resolved, lets remove unnecessary link.
*/
clearResolved();
resolved=true;
}
/*
* Remove duplicated referenced undefined symbols
*/
protected void clearDuplicate() {
Symbol sym1;
Symbol sym2;
Iterator<Symbol> U1 = undefined.keySet().iterator();
while ( U1.hasNext()) {
sym1 = U1.next();
Iterator<Symbol> U2 = (new HashSet<Symbol>( undefined.keySet()) ).iterator();
while (U2.hasNext()) {
sym2 = U2.next();
if (sym1 != sym2) {
if (sym1.name.equals(sym2.name)) {
sym2.origin = sym2.origin + File.pathSeparator + sym1.origin;
U1.remove();
break;
}
}
}
}
}
}
| 1,610 | 0.641486 | 0.629721 | 75 | 20.533333 | 21.611315 | 80 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.053333 | false | false | 13 |
37caaef32d0309e179d8eef15c70afdf071da4e1 | 5,549,097,786,717 | eebb984d395ba13dcfb9eb1bc565edf0b03e5032 | /ExampleCode/XmlParse/DOM4J/WriteXml.java | 917f698ae1ea296f61d683f651b170d852a1d213 | []
| no_license | bfchengnuo/java-work | https://github.com/bfchengnuo/java-work | 8508c8c66d70bc06c0b4b449d040652cbc422157 | f352b710edc6f2d00f4b5a456cee8690b622d723 | refs/heads/master | 2021-01-10T14:11:52.759000 | 2019-04-07T08:18:17 | 2019-04-07T08:18:17 | 50,408,940 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.etoak.test;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;
/**
*
* @author Kerronex
* @version ๅๅปบๆถ้ด๏ผ2018ๅนด4ๆ26ๆฅ ไธๅ10:58:25
*/
public class WriteXml {
public static void main(String[] args) {
// 1.ๅๅปบไธไธชๆๆกฃๅฏน่ฑกๆจกๅ
Document doc = DocumentHelper.createDocument();
// 2.ๅๅปบๆ นๅ
็ด
Element root = doc.addElement("root");
// 3.ๅๅปบไธ็บงๅญๅ
็ด
Element student = root.addElement("student");
// 4.ๆทปๅ ๅฑๆง
student.addAttribute("id", "et001");
student.addAttribute("name", "Penny");
// 5.ๆทปๅ ไบ็บงๅญๅ
็ด
Element email = student.addElement("email");
email.setText("et001@etoak.com");
Element phone = student.addElement("phone");
phone.setText("1111");
try {
OutputStream ops = new FileOutputStream("etoak2.xml");
// ่ฎพ็ฝฎ่ชๅจๆข่ก็ XML
OutputFormat format = OutputFormat.createPrettyPrint();
// ่ฎพ็ฝฎ็ผ็
format.setEncoding("utf-8");
// ่พๅบๆๆฌ
XMLWriter xw = new XMLWriter(ops,format);
xw.write(doc);
xw.flush();
xw.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
| UTF-8 | Java | 1,433 | java | WriteXml.java | Java | [
{
"context": "\nimport org.dom4j.io.XMLWriter;\n\n/**\n *\n * @author Kerronex\n * @version ๅๅปบๆถ้ด๏ผ2018ๅนด4ๆ26ๆฅ ไธๅ10:58:25\n */\npublic",
"end": 332,
"score": 0.9979333281517029,
"start": 324,
"tag": "USERNAME",
"value": "Kerronex"
},
{
"context": "e(\"id\", \"et001\");\n\t\tstudent.addAttribute(\"name\", \"Penny\");\n\t\t// 5.ๆทปๅ ไบ็บงๅญๅ
็ด \n\t\tElement email = student.addEl",
"end": 716,
"score": 0.9996324777603149,
"start": 711,
"tag": "NAME",
"value": "Penny"
},
{
"context": "l = student.addElement(\"email\");\n\t\temail.setText(\"et001@etoak.com\");\n\t\tElement phone = student.addElement(\"phone\");",
"end": 814,
"score": 0.9999197721481323,
"start": 799,
"tag": "EMAIL",
"value": "et001@etoak.com"
}
]
| null | []
| package com.etoak.test;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;
/**
*
* @author Kerronex
* @version ๅๅปบๆถ้ด๏ผ2018ๅนด4ๆ26ๆฅ ไธๅ10:58:25
*/
public class WriteXml {
public static void main(String[] args) {
// 1.ๅๅปบไธไธชๆๆกฃๅฏน่ฑกๆจกๅ
Document doc = DocumentHelper.createDocument();
// 2.ๅๅปบๆ นๅ
็ด
Element root = doc.addElement("root");
// 3.ๅๅปบไธ็บงๅญๅ
็ด
Element student = root.addElement("student");
// 4.ๆทปๅ ๅฑๆง
student.addAttribute("id", "et001");
student.addAttribute("name", "Penny");
// 5.ๆทปๅ ไบ็บงๅญๅ
็ด
Element email = student.addElement("email");
email.setText("<EMAIL>");
Element phone = student.addElement("phone");
phone.setText("1111");
try {
OutputStream ops = new FileOutputStream("etoak2.xml");
// ่ฎพ็ฝฎ่ชๅจๆข่ก็ XML
OutputFormat format = OutputFormat.createPrettyPrint();
// ่ฎพ็ฝฎ็ผ็
format.setEncoding("utf-8");
// ่พๅบๆๆฌ
XMLWriter xw = new XMLWriter(ops,format);
xw.write(doc);
xw.flush();
xw.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
| 1,425 | 0.690964 | 0.664389 | 58 | 21.706896 | 16.405434 | 58 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.965517 | false | false | 13 |
6b4e65493fedb08513226d355a7c790875143789 | 5,042,291,617,940 | 385d96b194607b77188da525e171e7c7fc69ba90 | /src/test/java/ru/open/currencycontroller/GetCalcAmountTest.java | 7439b0d120f03ffd389c1088cdb09e8705dcc037 | []
| no_license | EvgKolt/apizapi | https://github.com/EvgKolt/apizapi | 41ecea8508fd99f01353b270bcdc20435ef94da6 | c1b5943403241738229129de17ba914a1220de20 | refs/heads/master | 2020-04-19T23:24:19.648000 | 2019-12-09T08:50:14 | 2019-12-09T08:50:14 | 168,494,810 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package ru.open.currencycontroller;
import com.jayway.restassured.RestAssured;
import com.jayway.restassured.response.Response;
import com.jayway.restassured.specification.RequestSpecification;
import io.qameta.allure.Attachment;
import io.qameta.allure.Step;
import io.qameta.allure.junit4.DisplayName;
import org.junit.Assert;
import org.junit.Test;
import ru.open.checkers.EmptyFieldsChecker;
import ru.open.entities.Constants;
import ru.open.helpers.PropertyHelper;
import java.io.IOException;
public class GetCalcAmountTest {
private static String[] requiredFields = {
"/data/fromCode",
"/data/toCode",
"/data/fromAmount",
"/data/toAmount",
"/data/rate"
};
@Test
@Step("ะะฐะฟัะพั ะบัััะฐ ะฒะฐะปัั")
@DisplayName("ะัะพะฒะตัะบะฐ ะบัััะฐ ััะฑะปั ะบ ะตะฒัะพ")
public void test() throws IOException {
EmptyFieldsChecker emptyFieldsChecker = new EmptyFieldsChecker();
emptyFieldsChecker.check(getRespBody(), requiredFields);
}
@Attachment
private String getRespBody() throws IOException {
RequestSpecification request = RestAssured.given();
request.header("Content-Type", "application/json");
request.header("Authorization", PropertyHelper.getFromProperties("auth.header.msb"));
Response response = request.get(Constants.BASE_URL + "/currency/calc-amount?fromAmount=1&fromCode=RUB&toCode=EUR");
Assert.assertEquals(response.getStatusCode(), 200);
return response.getBody().asString();
}
} | UTF-8 | Java | 1,575 | java | GetCalcAmountTest.java | Java | []
| null | []
| package ru.open.currencycontroller;
import com.jayway.restassured.RestAssured;
import com.jayway.restassured.response.Response;
import com.jayway.restassured.specification.RequestSpecification;
import io.qameta.allure.Attachment;
import io.qameta.allure.Step;
import io.qameta.allure.junit4.DisplayName;
import org.junit.Assert;
import org.junit.Test;
import ru.open.checkers.EmptyFieldsChecker;
import ru.open.entities.Constants;
import ru.open.helpers.PropertyHelper;
import java.io.IOException;
public class GetCalcAmountTest {
private static String[] requiredFields = {
"/data/fromCode",
"/data/toCode",
"/data/fromAmount",
"/data/toAmount",
"/data/rate"
};
@Test
@Step("ะะฐะฟัะพั ะบัััะฐ ะฒะฐะปัั")
@DisplayName("ะัะพะฒะตัะบะฐ ะบัััะฐ ััะฑะปั ะบ ะตะฒัะพ")
public void test() throws IOException {
EmptyFieldsChecker emptyFieldsChecker = new EmptyFieldsChecker();
emptyFieldsChecker.check(getRespBody(), requiredFields);
}
@Attachment
private String getRespBody() throws IOException {
RequestSpecification request = RestAssured.given();
request.header("Content-Type", "application/json");
request.header("Authorization", PropertyHelper.getFromProperties("auth.header.msb"));
Response response = request.get(Constants.BASE_URL + "/currency/calc-amount?fromAmount=1&fromCode=RUB&toCode=EUR");
Assert.assertEquals(response.getStatusCode(), 200);
return response.getBody().asString();
}
} | 1,575 | 0.714193 | 0.710938 | 44 | 33.93182 | 26.107643 | 123 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.681818 | false | false | 13 |
568b347922d447d552c2250a401ee4c6275c766b | 4,475,355,958,945 | 5380e2d6ac7d2ca82004c7b28fee4ed458f29aff | /src/main/java/terraform/resources/aws/database/S3Import.java | d85dfc187c5f4433908d8cee94939ea769810f45 | []
| no_license | AbdessalamElhabbash/SLO-ML | https://github.com/AbdessalamElhabbash/SLO-ML | 89664da1a8679b394880b47b508db01fc0c716b0 | eaab06250fdcd5236b927a426864110af72f6a56 | refs/heads/master | 2020-09-21T15:53:45.334000 | 2019-12-02T18:01:42 | 2019-12-02T18:01:42 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package terraform.resources.aws.database;
import exceptions.RequiredArgumentException;
import terraform.TerraformObject;
import terraform.provider.Constants;
public class S3Import extends TerraformObject{
private String bucket_name; //required
private String bucket_prefix;
private String ingestion_role;//required
private String source_engine;//required
private String source_engine_version; //required
/**
* @return the bucket_name
*/
public String getBucket_name() {
return bucket_name;
}
/**
* @param bucket_name the bucket_name to set
*/
public void setBucket_name(String bucket_name) {
this.bucket_name = bucket_name;
}
/**
* @return the bucket_prefix
*/
public String getBucket_prefix() {
return bucket_prefix;
}
/**
* @param bucket_prefix the bucket_prefix to set
*/
public void setBucket_prefix(String bucket_prefix) {
this.bucket_prefix = bucket_prefix;
}
/**
* @return the ingestion_role
*/
public String getIngestion_role() {
return ingestion_role;
}
/**
* @param ingestion_role the ingestion_role to set
*/
public void setIngestion_role(String ingestion_role) {
this.ingestion_role = ingestion_role;
}
/**
* @return the source_engine
*/
public String getSource_engine() {
return source_engine;
}
/**
* @param source_engine the source_engine to set
*/
public void setSource_engine(String source_engine) {
this.source_engine = source_engine;
}
/**
* @return the source_engine_version
*/
public String getSource_engine_version() {
return source_engine_version;
}
/**
* @param source_engine_version the source_engine_version to set
*/
public void setSource_engine_version(String source_engine_version) {
this.source_engine_version = source_engine_version;
}
/**
*
* @return
* @throws RequiredArgumentException
*/
private boolean isValid() throws RequiredArgumentException{
if(bucket_name == null || bucket_name.equals("")){
throw new RequiredArgumentException("bucket_name is required for the S3Import object");
}
if(ingestion_role == null || ingestion_role.equals("")){
throw new RequiredArgumentException("ingestion_role is required for the S3Import object");
}
if(source_engine == null || source_engine.equals("")){
throw new RequiredArgumentException("source_engine is required for the S3Import object");
}
if(source_engine_version == null || source_engine_version.equals("")){
throw new RequiredArgumentException("source_engine_version is required for the S3Import object");
}
return true;
}
/**
*
* @param level
* @return
*/
@Override
public String getBlock(int level) {
try {
isValid();
} catch (RequiredArgumentException e) {
e.printStackTrace();
}
/***for formatting the terraform code**/
String headIndent="";
for(int i=0; i<level; i++){
headIndent += Constants.indent;
}
String elementIndent= headIndent + Constants.indent;
/*******************************************************/
String block = headIndent + "s3_import \"" + "\" { \n";
block += elementIndent + "bucket_name = \"" + bucket_name + "\"\n";
block += elementIndent + "ingestion_role = \"" + ingestion_role + "\"\n";
block += elementIndent + "source_engine = \"" + source_engine + "\"\n";
block += elementIndent + "source_engine_version = \"" + source_engine_version + "\"\n";
if(bucket_prefix != null && !bucket_prefix.equals("")){
block += elementIndent + "bucket_prefix = \"" + bucket_prefix + "\"\n";
}
block += headIndent + "}\n";
return block;
}
}
| UTF-8 | Java | 3,727 | java | S3Import.java | Java | []
| null | []
| package terraform.resources.aws.database;
import exceptions.RequiredArgumentException;
import terraform.TerraformObject;
import terraform.provider.Constants;
public class S3Import extends TerraformObject{
private String bucket_name; //required
private String bucket_prefix;
private String ingestion_role;//required
private String source_engine;//required
private String source_engine_version; //required
/**
* @return the bucket_name
*/
public String getBucket_name() {
return bucket_name;
}
/**
* @param bucket_name the bucket_name to set
*/
public void setBucket_name(String bucket_name) {
this.bucket_name = bucket_name;
}
/**
* @return the bucket_prefix
*/
public String getBucket_prefix() {
return bucket_prefix;
}
/**
* @param bucket_prefix the bucket_prefix to set
*/
public void setBucket_prefix(String bucket_prefix) {
this.bucket_prefix = bucket_prefix;
}
/**
* @return the ingestion_role
*/
public String getIngestion_role() {
return ingestion_role;
}
/**
* @param ingestion_role the ingestion_role to set
*/
public void setIngestion_role(String ingestion_role) {
this.ingestion_role = ingestion_role;
}
/**
* @return the source_engine
*/
public String getSource_engine() {
return source_engine;
}
/**
* @param source_engine the source_engine to set
*/
public void setSource_engine(String source_engine) {
this.source_engine = source_engine;
}
/**
* @return the source_engine_version
*/
public String getSource_engine_version() {
return source_engine_version;
}
/**
* @param source_engine_version the source_engine_version to set
*/
public void setSource_engine_version(String source_engine_version) {
this.source_engine_version = source_engine_version;
}
/**
*
* @return
* @throws RequiredArgumentException
*/
private boolean isValid() throws RequiredArgumentException{
if(bucket_name == null || bucket_name.equals("")){
throw new RequiredArgumentException("bucket_name is required for the S3Import object");
}
if(ingestion_role == null || ingestion_role.equals("")){
throw new RequiredArgumentException("ingestion_role is required for the S3Import object");
}
if(source_engine == null || source_engine.equals("")){
throw new RequiredArgumentException("source_engine is required for the S3Import object");
}
if(source_engine_version == null || source_engine_version.equals("")){
throw new RequiredArgumentException("source_engine_version is required for the S3Import object");
}
return true;
}
/**
*
* @param level
* @return
*/
@Override
public String getBlock(int level) {
try {
isValid();
} catch (RequiredArgumentException e) {
e.printStackTrace();
}
/***for formatting the terraform code**/
String headIndent="";
for(int i=0; i<level; i++){
headIndent += Constants.indent;
}
String elementIndent= headIndent + Constants.indent;
/*******************************************************/
String block = headIndent + "s3_import \"" + "\" { \n";
block += elementIndent + "bucket_name = \"" + bucket_name + "\"\n";
block += elementIndent + "ingestion_role = \"" + ingestion_role + "\"\n";
block += elementIndent + "source_engine = \"" + source_engine + "\"\n";
block += elementIndent + "source_engine_version = \"" + source_engine_version + "\"\n";
if(bucket_prefix != null && !bucket_prefix.equals("")){
block += elementIndent + "bucket_prefix = \"" + bucket_prefix + "\"\n";
}
block += headIndent + "}\n";
return block;
}
}
| 3,727 | 0.640193 | 0.638315 | 151 | 22.682119 | 25.436161 | 100 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.496689 | false | false | 13 |
c87a78f55cb58c8b9911b99c921b56688f6e5186 | 13,151,189,862,503 | d5052ed4d86930dab80958ba3f1511da5e9dbb7a | /app/src/main/java/com/example/graph2/MyDraw.java | 59ba5b853f3093e490e3debfd68104ee1aab306b | []
| no_license | rakdav/Graph2 | https://github.com/rakdav/Graph2 | 4b7b97091cfdf5db5950166109b3097946d20087 | de193086f4abfe7009d341c6c9bde403d17f160e | refs/heads/master | 2021-01-04T20:31:36.105000 | 2020-02-22T16:29:41 | 2020-02-22T16:29:41 | 240,749,340 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.graph2;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Point;
import android.icu.text.CaseMap;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import com.example.graph2.Model.Player;
import com.example.graph2.Model.Star;
import java.util.ArrayList;
public class MyDraw extends SurfaceView implements Runnable
{
volatile boolean playing;
private Thread gameThread=null;
private Player player;
private Paint paint;
private Canvas canvas;
private SurfaceHolder surfaceHolder;
private ArrayList<Star> stars=new ArrayList<>();
public MyDraw(Context context,int screenX,int screenY) {
super(context);
player=new Player(context,screenX,screenY);
surfaceHolder=getHolder();
paint=new Paint();
int starNums=100;
for(int i=0;i<starNums;i++)
{
Star s=new Star(screenX,screenY);
stars.add(s);
}
}
@Override
public void run() {
while (playing)
{
update();
draw();
control();
}
}
public void update()
{
player.Update();
for(Star s:stars)
{
s.Update(player.getSpeed());
}
}
public void draw()
{
if(surfaceHolder.getSurface().isValid())
{
canvas=surfaceHolder.lockCanvas();
canvas.drawColor(Color.BLACK);
paint.setColor(Color.RED);
for(Star s:stars)
{
paint.setStrokeWidth(s.getStarWidth());
canvas.drawPoint(s.getX(),s.getY(),paint);
}
canvas.drawBitmap(player.getBitmap(),
player.getX(),
player.getY(),
paint);
surfaceHolder.unlockCanvasAndPost(canvas);
}
}
public void control()
{
try {
gameThread.sleep(17);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public void pause()
{
playing=false;
try {
gameThread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public void resume()
{
playing=true;
gameThread=new Thread(this);
gameThread.start();
}
@Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()&MotionEvent.ACTION_MASK)
{
case MotionEvent.ACTION_UP:
player.stopBoosting();
break;
case MotionEvent.ACTION_DOWN:
player.setBoosting();
break;
}
return true;
}
}
| UTF-8 | Java | 3,013 | java | MyDraw.java | Java | []
| null | []
| package com.example.graph2;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Point;
import android.icu.text.CaseMap;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import com.example.graph2.Model.Player;
import com.example.graph2.Model.Star;
import java.util.ArrayList;
public class MyDraw extends SurfaceView implements Runnable
{
volatile boolean playing;
private Thread gameThread=null;
private Player player;
private Paint paint;
private Canvas canvas;
private SurfaceHolder surfaceHolder;
private ArrayList<Star> stars=new ArrayList<>();
public MyDraw(Context context,int screenX,int screenY) {
super(context);
player=new Player(context,screenX,screenY);
surfaceHolder=getHolder();
paint=new Paint();
int starNums=100;
for(int i=0;i<starNums;i++)
{
Star s=new Star(screenX,screenY);
stars.add(s);
}
}
@Override
public void run() {
while (playing)
{
update();
draw();
control();
}
}
public void update()
{
player.Update();
for(Star s:stars)
{
s.Update(player.getSpeed());
}
}
public void draw()
{
if(surfaceHolder.getSurface().isValid())
{
canvas=surfaceHolder.lockCanvas();
canvas.drawColor(Color.BLACK);
paint.setColor(Color.RED);
for(Star s:stars)
{
paint.setStrokeWidth(s.getStarWidth());
canvas.drawPoint(s.getX(),s.getY(),paint);
}
canvas.drawBitmap(player.getBitmap(),
player.getX(),
player.getY(),
paint);
surfaceHolder.unlockCanvasAndPost(canvas);
}
}
public void control()
{
try {
gameThread.sleep(17);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public void pause()
{
playing=false;
try {
gameThread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public void resume()
{
playing=true;
gameThread=new Thread(this);
gameThread.start();
}
@Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()&MotionEvent.ACTION_MASK)
{
case MotionEvent.ACTION_UP:
player.stopBoosting();
break;
case MotionEvent.ACTION_DOWN:
player.setBoosting();
break;
}
return true;
}
}
| 3,013 | 0.559243 | 0.556256 | 118 | 24.533897 | 16.177345 | 62 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.567797 | false | false | 13 |
cc40d4b71a879d93922e059a3e5fe14199be348e | 13,245,679,201,438 | 270aec5996b2438bad8504d4ba92345c89f3d5a6 | /todoapp-it/src/test/java/com/damdamdeo/todoapp/it/TodoFeatureIT.java | e207b049052b2ace01ae5f4e7b365e284d7c08fb | []
| no_license | dcdh/todoapp | https://github.com/dcdh/todoapp | cb1ba01b9cffa872a8fe3231138866cfd5d356e9 | 960a5287242e16309972bc45e7bc0dcfbb05224d | refs/heads/master | 2020-03-27T09:45:12.091000 | 2018-11-04T09:44:15 | 2018-11-04T09:44:15 | 146,369,451 | 2 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.damdamdeo.todoapp.it;
import org.junit.runner.RunWith;
import cucumber.runtime.arquillian.CukeSpace;
import cucumber.runtime.arquillian.api.Features;
import cucumber.runtime.arquillian.api.Glues;
@Features("com/damdamdeo/todoapp/it/Todo.feature")
@RunWith(CukeSpace.class)
@Glues(TodoFeatureITSteps.class)
public class TodoFeatureIT {
}
| UTF-8 | Java | 353 | java | TodoFeatureIT.java | Java | []
| null | []
| package com.damdamdeo.todoapp.it;
import org.junit.runner.RunWith;
import cucumber.runtime.arquillian.CukeSpace;
import cucumber.runtime.arquillian.api.Features;
import cucumber.runtime.arquillian.api.Glues;
@Features("com/damdamdeo/todoapp/it/Todo.feature")
@RunWith(CukeSpace.class)
@Glues(TodoFeatureITSteps.class)
public class TodoFeatureIT {
}
| 353 | 0.818697 | 0.818697 | 14 | 24.214285 | 19.258314 | 50 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.357143 | false | false | 13 |
b68912edd2302e6754165ffd69a909b3e6ec2315 | 13,245,679,201,029 | fe4d5485b4eaaf2741542f66db02e9010ed1c214 | /src/main/java/pl/kacper/starzynski/cqrs/configuration/jackson/JacksonConfiguration.java | 2b6b21d17c1427041f4964f6444a556e4264cd51 | [
"MIT"
]
| permissive | Waksuu/CSRS | https://github.com/Waksuu/CSRS | fd7d40ed0e111d72a52c3bfcc05528c039b6744c | 84ee157a86a4eac786433cfade3034f4c3a8ece8 | refs/heads/master | 2022-10-30T04:52:35.982000 | 2020-06-09T21:36:04 | 2020-06-09T21:36:04 | 270,065,899 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package pl.kacper.starzynski.cqrs.configuration.jackson;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
@Configuration
public class JacksonConfiguration implements Jackson2ObjectMapperBuilderCustomizer {
@Override
public void customize(Jackson2ObjectMapperBuilder jacksonObjectMapperBuilder) {
jacksonObjectMapperBuilder.visibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY);
}
} | UTF-8 | Java | 711 | java | JacksonConfiguration.java | Java | []
| null | []
| package pl.kacper.starzynski.cqrs.configuration.jackson;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
@Configuration
public class JacksonConfiguration implements Jackson2ObjectMapperBuilderCustomizer {
@Override
public void customize(Jackson2ObjectMapperBuilder jacksonObjectMapperBuilder) {
jacksonObjectMapperBuilder.visibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY);
}
} | 711 | 0.859353 | 0.853727 | 16 | 43.5 | 36.537651 | 101 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false | 13 |
031a9502c5c1a81e4f5376804cda44cc876b9726 | 12,841,952,259,960 | 26ebda9ba34d33738180fcc89c16921068fb8649 | /Universal/src/main/java/me/fixeddev/ebcm/parametric/annotation/Default.java | 144543c90bd97d5a5bac942d53c99dec77d7a515 | [
"MIT"
]
| permissive | FixedDev/EBCM | https://github.com/FixedDev/EBCM | 44e9911f166e1ace20ff98d8658dceb09012c3d3 | 3a7cb69d68efdb2c7c9cc9873be7547f68d5878b | refs/heads/master | 2020-09-28T10:31:40.013000 | 2020-05-30T00:20:37 | 2020-05-30T00:20:37 | 226,759,852 | 20 | 9 | MIT | false | 2020-08-05T19:19:07 | 2019-12-09T01:30:56 | 2020-08-04T12:18:09 | 2020-08-05T19:19:07 | 350 | 14 | 3 | 0 | Java | false | false | package me.fixeddev.ebcm.parametric.annotation;
import me.fixeddev.ebcm.part.CommandPart;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* The purpose of this annotation is to define the default value of a parameter
* in an {@link ACommand}.
* <p>
* When you set this annotation to any parameter in an {@link ACommand} you set
* the default value of that parameter and also you set that parameter {@link CommandPart#isRequired()}
* value to false
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.PARAMETER)
public @interface Default {
String[] value() default {};
}
| UTF-8 | Java | 708 | java | Default.java | Java | []
| null | []
| package me.fixeddev.ebcm.parametric.annotation;
import me.fixeddev.ebcm.part.CommandPart;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* The purpose of this annotation is to define the default value of a parameter
* in an {@link ACommand}.
* <p>
* When you set this annotation to any parameter in an {@link ACommand} you set
* the default value of that parameter and also you set that parameter {@link CommandPart#isRequired()}
* value to false
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.PARAMETER)
public @interface Default {
String[] value() default {};
}
| 708 | 0.766949 | 0.766949 | 22 | 31.181818 | 27.546055 | 103 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.318182 | false | false | 13 |
5541e53c2f9edc53894ff3979779abfa2cb598ed | 31,825,707,689,510 | 6bcaeb4d0e7e48629404d57e1590c69dd4754498 | /NK-Payment/src/main/java/by/training/nc/dev5/dao/CreditCardMySQLDAO.java | a5709682c3123613d71cf8ab99493ca86b80816b | []
| no_license | ATPod/nc-training | https://github.com/ATPod/nc-training | 56a03fa01f96ebaa075f93134485180a069b0407 | 75dffd524be61f2675c0bda2bfacfbbad66c993b | refs/heads/master | 2020-05-23T08:36:57.766000 | 2017-07-11T07:26:37 | 2017-07-11T07:26:37 | 84,756,625 | 1 | 6 | null | false | 2017-03-17T15:17:22 | 2017-03-12T20:52:38 | 2017-03-12T21:09:28 | 2017-03-17T15:17:22 | 33 | 0 | 0 | 0 | Java | null | null | /**
*
*/
package by.training.nc.dev5.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import by.training.nc.dev5.dao.factory.MySQLDAOFactory;
import by.training.nc.dev5.entities.Account;
import by.training.nc.dev5.entities.CreditCard;
import by.training.nc.dev5.exceptions.NotCorrectIdException;
import by.training.nc.dev5.exceptions.NotCorrectPasswordException;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
/**
* @author nic
*
*/
public class CreditCardMySQLDAO implements CreditCardDAO {
private static final String SQL_SELECT = "SELECT crditcard_id, client_id, money," +
" account_status, pass from creditcard";
private static final String SQL_INSERT = "INSERT INTO creditcard (crditcard_id, client_id," +
" money, account_status, pass values(?,?,?,?,?)";
private static final String SQL_UPDATE = "UPDATE creditcard SET client_id = ?," +
"money = ?,account_status = ?,pass = ?, WHERE creditcard.crditcard_id = ?";
private static final String SQL_DELETE = "DELETE FROM creditcard WHERE creditcard.crditcard_id = ?";
private static final String SQL_FIND = "SELECT * FROM creditcard WHERE crditcard_id = ?";
// logger for the class
static Logger logger = LogManager.getLogger(ClientMySQLDAO.class);
private String convertArrayToString(int [] arr){
StringBuffer str = null;
for(int temp : arr){
str.append(temp-48);
}
return str.toString();
}
private int[] convertStringToArray(String str){
int[] arr = new int[str.length()];
for(int i = 0;i<str.length();i++){
arr[i] = str.charAt(i)-48;
}
return arr;
}
public boolean deleteCreditCard(CreditCard pCreditCard) {
int success = 0;
try (Connection connection = MySQLDAOFactory.getConnection();
PreparedStatement ptmt = connection.prepareStatement(SQL_DELETE)) {
ptmt.setString(1, convertArrayToString(pCreditCard.getId()));
success = ptmt.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
return (success > 0);
}
/* (non-Javadoc)
* @see by.training.nc.dev5.dao.TrainingDAO#findTraining(java.lang.String)
*/
public CreditCard findCreditCard(int[] pCreditCardId) {
try (Connection connection = MySQLDAOFactory.getConnection();
PreparedStatement ptmt = connection.prepareStatement(SQL_FIND)) {
ptmt.setString(1, convertArrayToString(pCreditCardId));
ResultSet rs = ptmt.executeQuery();
if(rs != null){
rs.next();
CreditCard creditCard = new CreditCard();
Account account = new Account();
creditCard.setClientId(rs.getInt("client_id"));
creditCard.setPassword(convertStringToArray(rs.getString("pass")));
account.setMoney(rs.getDouble("money"));
account.setBlocked(rs.getBoolean("account_status"));
creditCard.setAccount(account);
return creditCard;
}
} catch (SQLException e) {
e.printStackTrace();
} catch (NotCorrectPasswordException e){
e.printStackTrace();
}
return null;
}
/* (non-Javadoc)
* @see by.training.nc.dev5.dao.TrainingDAO#insertTraining(by.training.nc.dev5.bean.Training)
*/
public int insertCreditCard(CreditCard pCreditCard) {
int success = 0;
try(Connection connection = MySQLDAOFactory.getConnection();
PreparedStatement ptmt = connection.prepareStatement(SQL_INSERT)){
ptmt.setString(1,convertArrayToString(pCreditCard.getId()));
ptmt.setInt(2,pCreditCard.getClientId());
ptmt.setDouble(3,pCreditCard.getAccount().getMoney());
ptmt.setBoolean(4,pCreditCard.getAccount().isBlocked());
ptmt.setString(5,convertArrayToString(pCreditCard.getPassword()));
success = ptmt.executeUpdate();
}catch (SQLException ex){
logger.error(ex.getMessage());
}
return success;
}
/* (non-Javadoc)
* @see by.training.nc.dev5.dao.TrainingDAO#selectTrainings()
*/
public Collection<CreditCard> selectCreditCards() {
try {
List<CreditCard> creditCards = new ArrayList<CreditCard>();
CreditCard creditCardBean;
Account accountBean;
Connection connection = MySQLDAOFactory.getConnection();
PreparedStatement ptmt = connection.prepareStatement(SQL_SELECT);
ResultSet rs = ptmt.executeQuery();
while (rs.next()) {
creditCardBean = new CreditCard();
accountBean = new Account();
creditCardBean.setId(convertStringToArray(rs.getString(1)));
creditCardBean.setClientId(rs.getInt(2));
creditCardBean.setPassword(convertStringToArray(rs.getString(5)));
accountBean.setMoney(rs.getDouble(3));
accountBean.setBlocked(rs.getBoolean(4));
creditCardBean.setAccount(accountBean);
creditCards.add(creditCardBean);
logger.debug("CreditCard:" + creditCardBean.toString());
}
return creditCards;
} catch (SQLException ex) {
logger.error(ex.getMessage());
return Collections.emptyList();
} catch (NotCorrectIdException ex){
logger.error(ex.getMessage());
return Collections.emptyList();
} catch (NotCorrectPasswordException ex){
logger.error(ex.getMessage());
return Collections.emptyList();
}
}
/* (non-Javadoc)
* @see by.training.nc.dev5.dao.TrainingDAO#updateTraining(java.lang.String)
*/
public boolean updateCreditCard(CreditCard pCreditCard) {
int success = 0;
try (Connection connection = MySQLDAOFactory.getConnection();
PreparedStatement ptmt = connection.prepareStatement(SQL_UPDATE)) {
ptmt.setInt(1, pCreditCard.getClientId());
ptmt.setDouble(2, pCreditCard.getAccount().getMoney());
ptmt.setBoolean(3,pCreditCard.getAccount().isBlocked());
ptmt.setString(4, convertArrayToString(pCreditCard.getPassword()));
ptmt.setString(5, convertArrayToString(pCreditCard.getId()));
success = ptmt.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
return (success > 0);
}
}
| UTF-8 | Java | 6,767 | java | CreditCardMySQLDAO.java | Java | [
{
"context": "t org.apache.logging.log4j.Logger;\n\n/**\n * @author nic\n *\n */\npublic class CreditCardMySQLDAO implements",
"end": 657,
"score": 0.985451877117157,
"start": 654,
"tag": "USERNAME",
"value": "nic"
}
]
| null | []
| /**
*
*/
package by.training.nc.dev5.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import by.training.nc.dev5.dao.factory.MySQLDAOFactory;
import by.training.nc.dev5.entities.Account;
import by.training.nc.dev5.entities.CreditCard;
import by.training.nc.dev5.exceptions.NotCorrectIdException;
import by.training.nc.dev5.exceptions.NotCorrectPasswordException;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
/**
* @author nic
*
*/
public class CreditCardMySQLDAO implements CreditCardDAO {
private static final String SQL_SELECT = "SELECT crditcard_id, client_id, money," +
" account_status, pass from creditcard";
private static final String SQL_INSERT = "INSERT INTO creditcard (crditcard_id, client_id," +
" money, account_status, pass values(?,?,?,?,?)";
private static final String SQL_UPDATE = "UPDATE creditcard SET client_id = ?," +
"money = ?,account_status = ?,pass = ?, WHERE creditcard.crditcard_id = ?";
private static final String SQL_DELETE = "DELETE FROM creditcard WHERE creditcard.crditcard_id = ?";
private static final String SQL_FIND = "SELECT * FROM creditcard WHERE crditcard_id = ?";
// logger for the class
static Logger logger = LogManager.getLogger(ClientMySQLDAO.class);
private String convertArrayToString(int [] arr){
StringBuffer str = null;
for(int temp : arr){
str.append(temp-48);
}
return str.toString();
}
private int[] convertStringToArray(String str){
int[] arr = new int[str.length()];
for(int i = 0;i<str.length();i++){
arr[i] = str.charAt(i)-48;
}
return arr;
}
public boolean deleteCreditCard(CreditCard pCreditCard) {
int success = 0;
try (Connection connection = MySQLDAOFactory.getConnection();
PreparedStatement ptmt = connection.prepareStatement(SQL_DELETE)) {
ptmt.setString(1, convertArrayToString(pCreditCard.getId()));
success = ptmt.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
return (success > 0);
}
/* (non-Javadoc)
* @see by.training.nc.dev5.dao.TrainingDAO#findTraining(java.lang.String)
*/
public CreditCard findCreditCard(int[] pCreditCardId) {
try (Connection connection = MySQLDAOFactory.getConnection();
PreparedStatement ptmt = connection.prepareStatement(SQL_FIND)) {
ptmt.setString(1, convertArrayToString(pCreditCardId));
ResultSet rs = ptmt.executeQuery();
if(rs != null){
rs.next();
CreditCard creditCard = new CreditCard();
Account account = new Account();
creditCard.setClientId(rs.getInt("client_id"));
creditCard.setPassword(convertStringToArray(rs.getString("pass")));
account.setMoney(rs.getDouble("money"));
account.setBlocked(rs.getBoolean("account_status"));
creditCard.setAccount(account);
return creditCard;
}
} catch (SQLException e) {
e.printStackTrace();
} catch (NotCorrectPasswordException e){
e.printStackTrace();
}
return null;
}
/* (non-Javadoc)
* @see by.training.nc.dev5.dao.TrainingDAO#insertTraining(by.training.nc.dev5.bean.Training)
*/
public int insertCreditCard(CreditCard pCreditCard) {
int success = 0;
try(Connection connection = MySQLDAOFactory.getConnection();
PreparedStatement ptmt = connection.prepareStatement(SQL_INSERT)){
ptmt.setString(1,convertArrayToString(pCreditCard.getId()));
ptmt.setInt(2,pCreditCard.getClientId());
ptmt.setDouble(3,pCreditCard.getAccount().getMoney());
ptmt.setBoolean(4,pCreditCard.getAccount().isBlocked());
ptmt.setString(5,convertArrayToString(pCreditCard.getPassword()));
success = ptmt.executeUpdate();
}catch (SQLException ex){
logger.error(ex.getMessage());
}
return success;
}
/* (non-Javadoc)
* @see by.training.nc.dev5.dao.TrainingDAO#selectTrainings()
*/
public Collection<CreditCard> selectCreditCards() {
try {
List<CreditCard> creditCards = new ArrayList<CreditCard>();
CreditCard creditCardBean;
Account accountBean;
Connection connection = MySQLDAOFactory.getConnection();
PreparedStatement ptmt = connection.prepareStatement(SQL_SELECT);
ResultSet rs = ptmt.executeQuery();
while (rs.next()) {
creditCardBean = new CreditCard();
accountBean = new Account();
creditCardBean.setId(convertStringToArray(rs.getString(1)));
creditCardBean.setClientId(rs.getInt(2));
creditCardBean.setPassword(convertStringToArray(rs.getString(5)));
accountBean.setMoney(rs.getDouble(3));
accountBean.setBlocked(rs.getBoolean(4));
creditCardBean.setAccount(accountBean);
creditCards.add(creditCardBean);
logger.debug("CreditCard:" + creditCardBean.toString());
}
return creditCards;
} catch (SQLException ex) {
logger.error(ex.getMessage());
return Collections.emptyList();
} catch (NotCorrectIdException ex){
logger.error(ex.getMessage());
return Collections.emptyList();
} catch (NotCorrectPasswordException ex){
logger.error(ex.getMessage());
return Collections.emptyList();
}
}
/* (non-Javadoc)
* @see by.training.nc.dev5.dao.TrainingDAO#updateTraining(java.lang.String)
*/
public boolean updateCreditCard(CreditCard pCreditCard) {
int success = 0;
try (Connection connection = MySQLDAOFactory.getConnection();
PreparedStatement ptmt = connection.prepareStatement(SQL_UPDATE)) {
ptmt.setInt(1, pCreditCard.getClientId());
ptmt.setDouble(2, pCreditCard.getAccount().getMoney());
ptmt.setBoolean(3,pCreditCard.getAccount().isBlocked());
ptmt.setString(4, convertArrayToString(pCreditCard.getPassword()));
ptmt.setString(5, convertArrayToString(pCreditCard.getId()));
success = ptmt.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
return (success > 0);
}
}
| 6,767 | 0.635732 | 0.629821 | 171 | 38.573101 | 26.645807 | 101 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.871345 | false | false | 13 |
9cb5a0e708a193bb9bf9868d326da815ab1f47fe | 21,363,167,362,359 | bc5869d81c7e2bd23aa3572ba5a6e9f58fb05745 | /scrumpractices/src/main/java/edu/cdu/xeon/sprint1/task5/App.java | 5b5271fed8f6f51bf02bb85786262b4a640712f6 | []
| no_license | XeonPRT453/TEAM-B | https://github.com/XeonPRT453/TEAM-B | 5366f30e8024943e69b3eadf5e1efed783872504 | 0a68082600903bd8420442be4ef20d215dca0c8c | refs/heads/master | 2020-05-07T12:57:55.372000 | 2019-04-10T08:20:51 | 2019-04-10T08:20:51 | 180,527,724 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package edu.cdu.xeon.sprint1.task5;
public class App {
}
| UTF-8 | Java | 58 | java | App.java | Java | []
| null | []
| package edu.cdu.xeon.sprint1.task5;
public class App {
}
| 58 | 0.741379 | 0.706897 | 4 | 13.5 | 14.326549 | 35 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.25 | false | false | 13 |
97b40236594617707e7117fa84f31b5c25babb0f | 32,427,003,126,787 | 83146828b4081e7d3cc23f365723e95a12b444bb | /src/main/java/jbu/zab/event/MsgEvent.java | 04484711c0b465857499fbd7034ce167c960c604 | []
| no_license | jburet/disruptor-test | https://github.com/jburet/disruptor-test | e89df6525db1be8da03e02afa4a54c81cb1901f4 | 5911f4023a92ef0ad0cf15b2654337a2de24460c | refs/heads/master | 2020-06-14T12:55:36.415000 | 2012-02-13T16:25:22 | 2012-02-13T16:25:22 | 3,427,654 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package jbu.zab.event;
import com.lmax.disruptor.EventFactory;
import jbu.zab.msg.*;
public class MsgEvent<T extends ZabMessage> {
private T msg;
public T getMsg() {
return this.msg;
}
public void setMsg(T msg) {
this.msg = msg;
}
public final static EventFactory<MsgEvent<CEpoch>> CEPOCH_EVENT_FACTORY = new EventFactory<MsgEvent<CEpoch>>() {
public MsgEvent<CEpoch> newInstance() {
return new MsgEvent<CEpoch>();
}
};
public final static EventFactory<MsgEvent<AckNewLeader>> ACKNEWLEADER_EVENT_FACTORY = new EventFactory<MsgEvent<AckNewLeader>>() {
public MsgEvent<AckNewLeader> newInstance() {
return new MsgEvent<AckNewLeader>();
}
};
public final static EventFactory<MsgEvent<Ack>> ACK_EVENT_FACTORY = new EventFactory<MsgEvent<Ack>>() {
public MsgEvent<Ack> newInstance() {
return new MsgEvent<Ack>();
}
};
public final static EventFactory<MsgEvent<ApplicationData>> NEWDATA_EVENT_FACTORY = new EventFactory<MsgEvent<ApplicationData>>() {
public MsgEvent<ApplicationData> newInstance() {
return new MsgEvent<ApplicationData>();
}
};
public final static EventFactory<MsgEvent<NewEpoch>> NEWPOCH_EVENT_FACTORY = new EventFactory<MsgEvent<NewEpoch>>() {
public MsgEvent<NewEpoch> newInstance() {
return new MsgEvent<NewEpoch>();
}
};
public final static EventFactory<MsgEvent<NewLeader>> NEWLEADER_EVENT_FACTORY = new EventFactory<MsgEvent<NewLeader>>() {
public MsgEvent<NewLeader> newInstance() {
return new MsgEvent<NewLeader>();
}
};
public final static EventFactory<MsgEvent<CommitLeader>> COMMITLEADER_EVENT_FACTORY = new EventFactory<MsgEvent<CommitLeader>>() {
public MsgEvent<CommitLeader> newInstance() {
return new MsgEvent<CommitLeader>();
}
};
public final static EventFactory<MsgEvent<Propose>> PROPOSE_EVENT_FACTORY = new EventFactory<MsgEvent<Propose>>() {
public MsgEvent<Propose> newInstance() {
return new MsgEvent<Propose>();
}
};
public final static EventFactory<MsgEvent<Commit>> COMMIT_EVENT_FACTORY = new EventFactory<MsgEvent<Commit>>() {
public MsgEvent<Commit> newInstance() {
return new MsgEvent<Commit>();
}
};
}
| UTF-8 | Java | 2,443 | java | MsgEvent.java | Java | []
| null | []
| package jbu.zab.event;
import com.lmax.disruptor.EventFactory;
import jbu.zab.msg.*;
public class MsgEvent<T extends ZabMessage> {
private T msg;
public T getMsg() {
return this.msg;
}
public void setMsg(T msg) {
this.msg = msg;
}
public final static EventFactory<MsgEvent<CEpoch>> CEPOCH_EVENT_FACTORY = new EventFactory<MsgEvent<CEpoch>>() {
public MsgEvent<CEpoch> newInstance() {
return new MsgEvent<CEpoch>();
}
};
public final static EventFactory<MsgEvent<AckNewLeader>> ACKNEWLEADER_EVENT_FACTORY = new EventFactory<MsgEvent<AckNewLeader>>() {
public MsgEvent<AckNewLeader> newInstance() {
return new MsgEvent<AckNewLeader>();
}
};
public final static EventFactory<MsgEvent<Ack>> ACK_EVENT_FACTORY = new EventFactory<MsgEvent<Ack>>() {
public MsgEvent<Ack> newInstance() {
return new MsgEvent<Ack>();
}
};
public final static EventFactory<MsgEvent<ApplicationData>> NEWDATA_EVENT_FACTORY = new EventFactory<MsgEvent<ApplicationData>>() {
public MsgEvent<ApplicationData> newInstance() {
return new MsgEvent<ApplicationData>();
}
};
public final static EventFactory<MsgEvent<NewEpoch>> NEWPOCH_EVENT_FACTORY = new EventFactory<MsgEvent<NewEpoch>>() {
public MsgEvent<NewEpoch> newInstance() {
return new MsgEvent<NewEpoch>();
}
};
public final static EventFactory<MsgEvent<NewLeader>> NEWLEADER_EVENT_FACTORY = new EventFactory<MsgEvent<NewLeader>>() {
public MsgEvent<NewLeader> newInstance() {
return new MsgEvent<NewLeader>();
}
};
public final static EventFactory<MsgEvent<CommitLeader>> COMMITLEADER_EVENT_FACTORY = new EventFactory<MsgEvent<CommitLeader>>() {
public MsgEvent<CommitLeader> newInstance() {
return new MsgEvent<CommitLeader>();
}
};
public final static EventFactory<MsgEvent<Propose>> PROPOSE_EVENT_FACTORY = new EventFactory<MsgEvent<Propose>>() {
public MsgEvent<Propose> newInstance() {
return new MsgEvent<Propose>();
}
};
public final static EventFactory<MsgEvent<Commit>> COMMIT_EVENT_FACTORY = new EventFactory<MsgEvent<Commit>>() {
public MsgEvent<Commit> newInstance() {
return new MsgEvent<Commit>();
}
};
}
| 2,443 | 0.645927 | 0.645927 | 71 | 33.408451 | 39.811378 | 138 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.338028 | false | false | 13 |
c627d7d50ce0c414621b7cb7dae8bedfd7c26bdb | 5,222,680,248,967 | 9a7818c4ac7f69f8c80e7ba9d91582ad15f52f27 | /Graph Concepts/minDegreeOfTrio.java | 5dbf5d1325ea82123d1b1225b1bbeb66fce3b51c | []
| no_license | pradhuman2022/Ds-Algo | https://github.com/pradhuman2022/Ds-Algo | 45f2c793e92667d686917fce18b3b2774a05775b | ae4c8401385fa37362871b9409fd528d9cbad757 | refs/heads/master | 2023-02-05T19:16:03.520000 | 2021-11-12T17:43:08 | 2021-11-12T17:43:08 | 169,271,273 | 6 | 3 | null | false | 2023-01-21T10:43:22 | 2019-02-05T16:18:12 | 2022-06-09T01:23:25 | 2023-01-21T10:43:18 | 1,935 | 2 | 1 | 1 | Java | false | false | class Solution {
public int minTrioDegree(int n, int[][] edges) {
Map<Integer, Set<Integer>> adjList = new HashMap<>();
for(int i = 0; i < edges.length;i++) {
Set<Integer> set1 = adjList.getOrDefault(edges[i][0], new HashSet<>());
Set<Integer> set2 = adjList.getOrDefault(edges[i][1], new HashSet<>());
set1.add(edges[i][1]);
set2.add(edges[i][0]);
adjList.put(edges[i][0], set1);
adjList.put(edges[i][1], set2);
}
int minDegree = Integer.MAX_VALUE;
for (int edge[]: edges) {
int v1 = edge[0];
int v2 = edge[1];
int degreeOfV1 = adjList.get(v1).size() - 2;
int degreeOfV2 = adjList.get(v2).size() - 4;
Set set1 = adjList.get(v1);
Set set2 = adjList.get(v2);
for(Object setValue: set1) {
if(set2.contains(setValue)) {
Set set3 = adjList.get(setValue);
if(set3.contains(v1) && set3.contains(v2)) {
minDegree = Math.min(minDegree, degreeOfV1 + degreeOfV2 + set3.size());
}
}
}
}
return minDegree == Integer.MAX_VALUE ? -1 : minDegree;
}
}
| UTF-8 | Java | 1,398 | java | minDegreeOfTrio.java | Java | []
| null | []
| class Solution {
public int minTrioDegree(int n, int[][] edges) {
Map<Integer, Set<Integer>> adjList = new HashMap<>();
for(int i = 0; i < edges.length;i++) {
Set<Integer> set1 = adjList.getOrDefault(edges[i][0], new HashSet<>());
Set<Integer> set2 = adjList.getOrDefault(edges[i][1], new HashSet<>());
set1.add(edges[i][1]);
set2.add(edges[i][0]);
adjList.put(edges[i][0], set1);
adjList.put(edges[i][1], set2);
}
int minDegree = Integer.MAX_VALUE;
for (int edge[]: edges) {
int v1 = edge[0];
int v2 = edge[1];
int degreeOfV1 = adjList.get(v1).size() - 2;
int degreeOfV2 = adjList.get(v2).size() - 4;
Set set1 = adjList.get(v1);
Set set2 = adjList.get(v2);
for(Object setValue: set1) {
if(set2.contains(setValue)) {
Set set3 = adjList.get(setValue);
if(set3.contains(v1) && set3.contains(v2)) {
minDegree = Math.min(minDegree, degreeOfV1 + degreeOfV2 + set3.size());
}
}
}
}
return minDegree == Integer.MAX_VALUE ? -1 : minDegree;
}
}
| 1,398 | 0.447783 | 0.420601 | 41 | 33.097561 | 23.859144 | 95 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.634146 | false | false | 13 |
8a685f2ca8d75fdfe0c5a1508d3ae54a8c4e8c50 | 4,174,708,257,228 | 046911ef3fc9fb5b80ba57bcfbec749a75c226cf | /src/main/java/com/api/adress/services/AddressService.java | db27b8bed63e033f54888037e41902ddb2bb7260 | []
| no_license | rivaelRodriguesJr/address-api | https://github.com/rivaelRodriguesJr/address-api | ba7bb3272003e89bec11b6255acb8a7fdfc1f8b6 | 8f8652abeb84d40e585e22c02e6cc29b5a61547c | refs/heads/main | 2023-01-04T02:23:54.986000 | 2020-10-31T20:28:57 | 2020-10-31T20:28:57 | 308,160,643 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.api.adress.services;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import javax.persistence.EntityNotFoundException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.api.adress.dto.AddressDTO;
import com.api.adress.entities.Address;
import com.api.adress.repositories.AddressRepository;
import com.api.adress.services.exceptions.ResourceNotFoundException;
@Service
public class AddressService {
@Autowired
private AddressRepository repository;
@Transactional(readOnly = true)
public List<AddressDTO> findAll() {
return repository.findAll().stream().map(entity -> new AddressDTO(entity)).collect(Collectors.toList());
}
@Transactional(readOnly = true)
public AddressDTO findById(Long id) {
Optional<Address> obj = repository.findById(id);
Address entity = obj.orElseThrow(() -> new ResourceNotFoundException("Id not found: " + id));
return new AddressDTO(entity);
}
@Transactional
public AddressDTO insert(AddressDTO dto) {
Address entity = new Address();
copyDtoToEntity(dto, entity);
entity = repository.save(entity);
return new AddressDTO(entity);
}
@Transactional
public AddressDTO update(Long id, AddressDTO dto) {
try {
Address entity = repository.getOne(id);
copyDtoToEntity(dto, entity);
entity = repository.save(entity);
return new AddressDTO(entity);
} catch (EntityNotFoundException e) {
throw new ResourceNotFoundException("Id not found: " + id);
}
}
public void delete(Long id) {
try {
repository.deleteById(id);
} catch (EmptyResultDataAccessException e) {
throw new ResourceNotFoundException("Id not found" + id);
}
}
private void copyDtoToEntity(AddressDTO dto, Address entity) {
entity.setStreetName(dto.getStreetName());
entity.setNumber(dto.getNumber());
entity.setComplement(dto.getComplement());
entity.setNeighbourhood(dto.getNeighbourhood());
entity.setCity(dto.getCity());
entity.setState(dto.getState());
entity.setCountry(dto.getCountry());
entity.setZipcode(dto.getZipcode());
entity.setLatitude(dto.getLatitude());
entity.setLongitude(dto.getLongitude());
}
}
| UTF-8 | Java | 2,338 | java | AddressService.java | Java | []
| null | []
| package com.api.adress.services;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import javax.persistence.EntityNotFoundException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.api.adress.dto.AddressDTO;
import com.api.adress.entities.Address;
import com.api.adress.repositories.AddressRepository;
import com.api.adress.services.exceptions.ResourceNotFoundException;
@Service
public class AddressService {
@Autowired
private AddressRepository repository;
@Transactional(readOnly = true)
public List<AddressDTO> findAll() {
return repository.findAll().stream().map(entity -> new AddressDTO(entity)).collect(Collectors.toList());
}
@Transactional(readOnly = true)
public AddressDTO findById(Long id) {
Optional<Address> obj = repository.findById(id);
Address entity = obj.orElseThrow(() -> new ResourceNotFoundException("Id not found: " + id));
return new AddressDTO(entity);
}
@Transactional
public AddressDTO insert(AddressDTO dto) {
Address entity = new Address();
copyDtoToEntity(dto, entity);
entity = repository.save(entity);
return new AddressDTO(entity);
}
@Transactional
public AddressDTO update(Long id, AddressDTO dto) {
try {
Address entity = repository.getOne(id);
copyDtoToEntity(dto, entity);
entity = repository.save(entity);
return new AddressDTO(entity);
} catch (EntityNotFoundException e) {
throw new ResourceNotFoundException("Id not found: " + id);
}
}
public void delete(Long id) {
try {
repository.deleteById(id);
} catch (EmptyResultDataAccessException e) {
throw new ResourceNotFoundException("Id not found" + id);
}
}
private void copyDtoToEntity(AddressDTO dto, Address entity) {
entity.setStreetName(dto.getStreetName());
entity.setNumber(dto.getNumber());
entity.setComplement(dto.getComplement());
entity.setNeighbourhood(dto.getNeighbourhood());
entity.setCity(dto.getCity());
entity.setState(dto.getState());
entity.setCountry(dto.getCountry());
entity.setZipcode(dto.getZipcode());
entity.setLatitude(dto.getLatitude());
entity.setLongitude(dto.getLongitude());
}
}
| 2,338 | 0.764756 | 0.764756 | 77 | 29.363636 | 23.408239 | 106 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.688312 | false | false | 13 |
b6a8eff3590339b3e1203525b51f3f81e10ee268 | 6,219,112,666,398 | ed5c98dcf3a55cf6cafdc805469f7c5c62a3f881 | /src/slick/basic_shoot.java | cef7e0a0a99aee21e7e05cf8a62cef4042a396ab | []
| no_license | ktorz14/slick | https://github.com/ktorz14/slick | a546edf9e81f11d6c701b1e6684287fbe7eba86d | 527303d1ae630a36a6c8f4274c48e4fa0e12ad34 | refs/heads/master | 2020-06-04T04:39:53.868000 | 2014-12-17T07:23:03 | 2014-12-17T07:23:03 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package slick;
import org.newdawn.slick.Image;
import org.newdawn.slick.SlickException;
import org.lwjgl.util.Rectangle;
import org.lwjgl.util.vector.Vector2f;
public class basic_shoot extends abstract_shoot{
public basic_shoot(int x, int y) throws SlickException, InterruptedException {
super(x, y);
dirx = 0;
diry = -1;
h=20;
w=5;
shoot = new Image("image/shoot0.png");
speed = 2;
hitbox = new Rectangle(x,y,w,h);
dmg = 1;
}
}
| UTF-8 | Java | 453 | java | basic_shoot.java | Java | []
| null | []
| package slick;
import org.newdawn.slick.Image;
import org.newdawn.slick.SlickException;
import org.lwjgl.util.Rectangle;
import org.lwjgl.util.vector.Vector2f;
public class basic_shoot extends abstract_shoot{
public basic_shoot(int x, int y) throws SlickException, InterruptedException {
super(x, y);
dirx = 0;
diry = -1;
h=20;
w=5;
shoot = new Image("image/shoot0.png");
speed = 2;
hitbox = new Rectangle(x,y,w,h);
dmg = 1;
}
}
| 453 | 0.701987 | 0.682119 | 22 | 19.59091 | 20.087669 | 79 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.818182 | false | false | 13 |
fa5a7c7c87920d2c477532b02daff8cca70c18d4 | 26,474,178,457,070 | 24e9e9c6d51dda25b567fbda20858a6559fcb8ea | /src/main/java/Reto_Sofka_Trainning/nivelDos.java | 768a6dcde32d5f7c567ce6e60ad30a29a002c936 | []
| no_license | jorge0716/Reto_Sofka_Automatizacion | https://github.com/jorge0716/Reto_Sofka_Automatizacion | 18ae2bd65439504b042b7c4c91bb558282c1a9e0 | 4fb239f7916c974440bd003cffaa801618d52772 | refs/heads/master | 2023-08-03T07:35:39.235000 | 2021-09-26T01:44:31 | 2021-09-26T01:44:31 | 410,412,977 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package Reto_Sofka_Trainning;
public class nivelDos {
public void Pregunta1()
{
System.out.println("Premio del segundo nivel: 400.000 pesos");
System.out.println("ยฟDemocracia es:?");
System.out.println("1: Una ronda Infantil");
System.out.println("2: Una comida tipica costeรฑa ");
System.out.println("3: Una forma de gobierno");
System.out.println("4: Una sopa de letras");
};
public void Pregunta2()
{
System.out.println("Premio del segundo nivel: 400.000 pesos");
System.out.println("ยฟ Una molecula es una agrupacion de?");
System.out.println("1: Atomos");
System.out.println("2: Numeros ");
System.out.println("3: Ecuaciones ");
System.out.println("4: Letras");
};
public void Pregunta3()
{
System.out.println("Premio del segundo nivel: 400.000 pesos");
System.out.println("ยฟ Cual es la raiz cuadrada de 9?");
System.out.println("1: 9");
System.out.println("2: 8");
System.out.println("3: 2");
System.out.println("4: 3 ");
};
public void Pregunta4()
{
System.out.println("Premio del segundo nivel: 400.000 pesos");
System.out.println("ยฟEl sol es?");
System.out.println("1: Un Asteroide ");
System.out.println("2: Estrella ");
System.out.println("3: Un cometa");
System.out.println("4: Letras ");
};
public void Pregunta5()
{
System.out.println("Premio del segundo nivel: 400.000 pesos");
System.out.println("ยฟQue artefacto se usa para salir a espacio?");
System.out.println("1: Un velero");
System.out.println("2: Un camion");
System.out.println("3: Un cohete");
System.out.println("4: Barco ");
};
}
| ISO-8859-1 | Java | 1,864 | java | nivelDos.java | Java | []
| null | []
| package Reto_Sofka_Trainning;
public class nivelDos {
public void Pregunta1()
{
System.out.println("Premio del segundo nivel: 400.000 pesos");
System.out.println("ยฟDemocracia es:?");
System.out.println("1: Una ronda Infantil");
System.out.println("2: Una comida tipica costeรฑa ");
System.out.println("3: Una forma de gobierno");
System.out.println("4: Una sopa de letras");
};
public void Pregunta2()
{
System.out.println("Premio del segundo nivel: 400.000 pesos");
System.out.println("ยฟ Una molecula es una agrupacion de?");
System.out.println("1: Atomos");
System.out.println("2: Numeros ");
System.out.println("3: Ecuaciones ");
System.out.println("4: Letras");
};
public void Pregunta3()
{
System.out.println("Premio del segundo nivel: 400.000 pesos");
System.out.println("ยฟ Cual es la raiz cuadrada de 9?");
System.out.println("1: 9");
System.out.println("2: 8");
System.out.println("3: 2");
System.out.println("4: 3 ");
};
public void Pregunta4()
{
System.out.println("Premio del segundo nivel: 400.000 pesos");
System.out.println("ยฟEl sol es?");
System.out.println("1: Un Asteroide ");
System.out.println("2: Estrella ");
System.out.println("3: Un cometa");
System.out.println("4: Letras ");
};
public void Pregunta5()
{
System.out.println("Premio del segundo nivel: 400.000 pesos");
System.out.println("ยฟQue artefacto se usa para salir a espacio?");
System.out.println("1: Un velero");
System.out.println("2: Un camion");
System.out.println("3: Un cohete");
System.out.println("4: Barco ");
};
}
| 1,864 | 0.57535 | 0.543057 | 58 | 31.034483 | 24.208124 | 75 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.396552 | false | false | 13 |
202c87c36f0563640276e5a2ab4bb2843da3475c | 5,446,018,546,954 | 440ebc85f61e8bc0c0fe385625923acb163b1815 | /VeryWowChat/app/src/main/java/hi/hugbo/verywowchat/adapters/MyChatroomItemAdapter.java | 461abeaa212b8d49afe0131fc7178a9a60c38e72 | []
| no_license | RomanRumba/Hugbundarverkefni2_Android | https://github.com/RomanRumba/Hugbundarverkefni2_Android | df63892911bcbe02ee5977d751e3338a21b2c1a8 | 39cbcc7bdb6d68ef12af17a7b746e229ca7b1f73 | refs/heads/master | 2020-04-21T03:16:55.234000 | 2019-04-11T12:29:27 | 2019-04-11T12:29:27 | 169,280,326 | 0 | 1 | null | false | 2019-04-11T12:29:28 | 2019-02-05T17:18:08 | 2019-04-11T12:21:09 | 2019-04-11T12:29:27 | 485 | 0 | 0 | 0 | Java | false | false | package hi.hugbo.verywowchat.adapters;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageButton;
import java.util.List;
import hi.hugbo.verywowchat.controllers.AdminManageChatroomActivity;
import hi.hugbo.verywowchat.controllers.ChatRoomMessageActivity;
import hi.hugbo.verywowchat.controllers.MemberManageChatroomActivity;
import hi.hugbo.verywowchat.controllers.OwnerManageChatroomActivity;
import hi.hugbo.verywowchat.controllers.R;
import hi.hugbo.verywowchat.entities.Chatroom;
/**
* @Author Vilhelm
* The ChatMessageAdapter responsibility is to convert an Chatroom object in a List at position X
* into a list row item to be inserted into RecyclerView. The adapter requires the existence of a "ViewHolder" object
* which describes and provides access to all the widgets, in our case we got 2 ChatroomHolder
* defined in the bottom of this class
* ( Reason they are defined here is cuz we can use a different onBindViewHolder function which makes things much simpler
* and also overall these Handlers should be private noone except the adapter who uses them should have access to them )
*
* Every adapter has three primary methods that neeed to be overridden:
* - onCreateViewHolder to inflate the item layout and create the holder
* - onBindViewHolder to set the view attributes based on the data
* - getItemCount to determine the number of items
* (Note u may be overwriting different variants of this methods based on how you extend the Adapter class) */
public class MyChatroomItemAdapter extends RecyclerView.Adapter {
/** Holds over all the chat messages we display on the screen */
private List<Chatroom> mChatrooms;
/** Just reminder for myself : You can pass the Context from the Activity to this constructor
* then u can implement listeners and other things on the inflated view widgets.*/
public MyChatroomItemAdapter(List<Chatroom> chatrooms) {
mChatrooms = chatrooms;
}
/**
* inflate the appropriate viewHolder so we could bind the data correctly to it
* @param parent
* @param viewType
* @return new instance of ChatroomItemHolder
*/
@Override
public ChatroomItemHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.my_chatroom_list_item, parent, false);
return new ChatroomItemHolder(view);
}
/**
* bind the data to the appropriate viewHolder
* @param viewHolder
* @param i the index
*/
@Override
public void onBindViewHolder(RecyclerView.ViewHolder viewHolder, int i) {
Chatroom chatroom = mChatrooms.get(i);
((ChatroomItemHolder) viewHolder).bind(chatroom);
}
@Override
public int getItemCount() {
return mChatrooms.size();
}
/** -------------------------------------------------------------------------------------------
* ------------------------------------- VIEWHOLDERS ------------------------------------------
* --------------------------------------------------------------------------------------------*/
/** we can add or change viewholders later f.x when we need to add images it will be super
* ez we just create a new view that displays the image and create a viewholder for it */
private class ChatroomItemHolder extends RecyclerView.ViewHolder{
private Button btn_open_chatroom;
private ImageButton btn_manage_chatroom;
public ChatroomItemHolder(View itemView) {
super(itemView);
btn_open_chatroom = itemView.findViewById(R.id.btn_open_chatroom);
btn_manage_chatroom = itemView.findViewById(R.id.btn_manage_chatroom);
}
public void bind(final Chatroom chatroom) {
// set the text
btn_open_chatroom.setText(chatroom.getUserRelation()+": "+chatroom.getDisplayName()+"("+chatroom.getChatroomName()+")");
btn_open_chatroom.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Context context = v.getContext();
context.startActivity(ChatRoomMessageActivity.newIntent(
context.getApplicationContext(),
chatroom.getChatroomName()
));
}
});
btn_manage_chatroom.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Context context = v.getContext();
String r = chatroom.getUserRelation();
switch(r){
case "OWNER":
Log.d("relation", "case: "+"OWNER");
context.startActivity(OwnerManageChatroomActivity.newIntent(
context.getApplicationContext(),
chatroom.getChatroomName()
));
break;
case "ADMIN":
Log.d("relation", "case: "+"ADMIN");
context.startActivity(AdminManageChatroomActivity.newIntent(
context.getApplicationContext(),
chatroom.getChatroomName()
));
break;
default: //case "MEMBER":
Log.d("relation", "case: "+"DEFAULT");
context.startActivity(MemberManageChatroomActivity.newIntent(
context.getApplicationContext(),
chatroom.getChatroomName()
));
break;
}
}
});
}
}
}
| UTF-8 | Java | 6,132 | java | MyChatroomItemAdapter.java | Java | [
{
"context": "gbo.verywowchat.entities.Chatroom;\n\n/**\n * @Author Vilhelm\n * The ChatMessageAdapter responsibility is to co",
"end": 713,
"score": 0.999119758605957,
"start": 706,
"tag": "NAME",
"value": "Vilhelm"
}
]
| null | []
| package hi.hugbo.verywowchat.adapters;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageButton;
import java.util.List;
import hi.hugbo.verywowchat.controllers.AdminManageChatroomActivity;
import hi.hugbo.verywowchat.controllers.ChatRoomMessageActivity;
import hi.hugbo.verywowchat.controllers.MemberManageChatroomActivity;
import hi.hugbo.verywowchat.controllers.OwnerManageChatroomActivity;
import hi.hugbo.verywowchat.controllers.R;
import hi.hugbo.verywowchat.entities.Chatroom;
/**
* @Author Vilhelm
* The ChatMessageAdapter responsibility is to convert an Chatroom object in a List at position X
* into a list row item to be inserted into RecyclerView. The adapter requires the existence of a "ViewHolder" object
* which describes and provides access to all the widgets, in our case we got 2 ChatroomHolder
* defined in the bottom of this class
* ( Reason they are defined here is cuz we can use a different onBindViewHolder function which makes things much simpler
* and also overall these Handlers should be private noone except the adapter who uses them should have access to them )
*
* Every adapter has three primary methods that neeed to be overridden:
* - onCreateViewHolder to inflate the item layout and create the holder
* - onBindViewHolder to set the view attributes based on the data
* - getItemCount to determine the number of items
* (Note u may be overwriting different variants of this methods based on how you extend the Adapter class) */
public class MyChatroomItemAdapter extends RecyclerView.Adapter {
/** Holds over all the chat messages we display on the screen */
private List<Chatroom> mChatrooms;
/** Just reminder for myself : You can pass the Context from the Activity to this constructor
* then u can implement listeners and other things on the inflated view widgets.*/
public MyChatroomItemAdapter(List<Chatroom> chatrooms) {
mChatrooms = chatrooms;
}
/**
* inflate the appropriate viewHolder so we could bind the data correctly to it
* @param parent
* @param viewType
* @return new instance of ChatroomItemHolder
*/
@Override
public ChatroomItemHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.my_chatroom_list_item, parent, false);
return new ChatroomItemHolder(view);
}
/**
* bind the data to the appropriate viewHolder
* @param viewHolder
* @param i the index
*/
@Override
public void onBindViewHolder(RecyclerView.ViewHolder viewHolder, int i) {
Chatroom chatroom = mChatrooms.get(i);
((ChatroomItemHolder) viewHolder).bind(chatroom);
}
@Override
public int getItemCount() {
return mChatrooms.size();
}
/** -------------------------------------------------------------------------------------------
* ------------------------------------- VIEWHOLDERS ------------------------------------------
* --------------------------------------------------------------------------------------------*/
/** we can add or change viewholders later f.x when we need to add images it will be super
* ez we just create a new view that displays the image and create a viewholder for it */
private class ChatroomItemHolder extends RecyclerView.ViewHolder{
private Button btn_open_chatroom;
private ImageButton btn_manage_chatroom;
public ChatroomItemHolder(View itemView) {
super(itemView);
btn_open_chatroom = itemView.findViewById(R.id.btn_open_chatroom);
btn_manage_chatroom = itemView.findViewById(R.id.btn_manage_chatroom);
}
public void bind(final Chatroom chatroom) {
// set the text
btn_open_chatroom.setText(chatroom.getUserRelation()+": "+chatroom.getDisplayName()+"("+chatroom.getChatroomName()+")");
btn_open_chatroom.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Context context = v.getContext();
context.startActivity(ChatRoomMessageActivity.newIntent(
context.getApplicationContext(),
chatroom.getChatroomName()
));
}
});
btn_manage_chatroom.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Context context = v.getContext();
String r = chatroom.getUserRelation();
switch(r){
case "OWNER":
Log.d("relation", "case: "+"OWNER");
context.startActivity(OwnerManageChatroomActivity.newIntent(
context.getApplicationContext(),
chatroom.getChatroomName()
));
break;
case "ADMIN":
Log.d("relation", "case: "+"ADMIN");
context.startActivity(AdminManageChatroomActivity.newIntent(
context.getApplicationContext(),
chatroom.getChatroomName()
));
break;
default: //case "MEMBER":
Log.d("relation", "case: "+"DEFAULT");
context.startActivity(MemberManageChatroomActivity.newIntent(
context.getApplicationContext(),
chatroom.getChatroomName()
));
break;
}
}
});
}
}
}
| 6,132 | 0.593281 | 0.592955 | 143 | 41.881119 | 33.79649 | 132 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.391608 | false | false | 13 |
b288c9906e01f889654f19b83a3179315e5f3e9f | 24,275,155,178,798 | 5efde6fb5e1f2359e0b0dc8fdcd6c2fe4d179a52 | /src/main/java/com/billlog/rest/salsapan/model/response/SingleResult.java | b06c40a322f92d58d54e1cab9b397a211bede2ec | []
| no_license | baesee/salsapan_restAPI_spirngboot | https://github.com/baesee/salsapan_restAPI_spirngboot | 0442d7e5d7c5e17fcd9f1c338eb0ad916c5f76d8 | 34e369dbdbd7bf788ec7430801f79970bd81a427 | refs/heads/master | 2023-05-02T04:16:33.053000 | 2019-10-17T09:13:11 | 2019-10-17T09:13:11 | 204,311,402 | 1 | 1 | null | false | 2023-04-14T17:32:41 | 2019-08-25T15:13:32 | 2021-10-01T15:52:32 | 2023-04-14T17:32:41 | 584 | 0 | 1 | 1 | CSS | false | false | package com.billlog.rest.salsapan.model.response;
/*
๊ฒฐ๊ณผ๊ฐ ๋จ์ผ๊ฑด์ธ api๋ฅผ ๋ด๋ ๋ชจ๋ธ
- Generic Interface์ <T>๋ฅผ ์ง์ ํ์ฌ ์ด๋ค ํํ์ ๊ฐ๋ ๋ฃ์ ์ ์๋๋ก ๊ตฌํํ์์ต๋๋ค.
- ๋ํ CommonResult๋ฅผ ์์๋ฐ์ผ๋ฏ๋ก api์์ฒญ ๊ฒฐ๊ณผ๋ ๊ฐ์ด ์ถ๋ ฅ๋ฉ๋๋ค.
*/
public class SingleResult<T> extends CommonResult {
private T data;
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
} | UTF-8 | Java | 502 | java | SingleResult.java | Java | []
| null | []
| package com.billlog.rest.salsapan.model.response;
/*
๊ฒฐ๊ณผ๊ฐ ๋จ์ผ๊ฑด์ธ api๋ฅผ ๋ด๋ ๋ชจ๋ธ
- Generic Interface์ <T>๋ฅผ ์ง์ ํ์ฌ ์ด๋ค ํํ์ ๊ฐ๋ ๋ฃ์ ์ ์๋๋ก ๊ตฌํํ์์ต๋๋ค.
- ๋ํ CommonResult๋ฅผ ์์๋ฐ์ผ๋ฏ๋ก api์์ฒญ ๊ฒฐ๊ณผ๋ ๊ฐ์ด ์ถ๋ ฅ๋ฉ๋๋ค.
*/
public class SingleResult<T> extends CommonResult {
private T data;
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
} | 502 | 0.648438 | 0.648438 | 18 | 20.388889 | 19.861013 | 61 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.222222 | false | false | 13 |
16ade8bef6b3cffa03375831c02658df2a02c60d | 34,892,314,318,916 | e06d89306659a8b853aa9e5da362c9d3d8f311a2 | /travel_background_server/src/main/java/com/bbdservice/sichuan/service/SysUserRoleService.java | fbd7e4383633a7ac397210c01fecde07a29c9e4e | []
| no_license | wllpeter/travel | https://github.com/wllpeter/travel | 3cd4283b10c0344a8957b82d4fa6bbff97d77596 | bcde9c0c7444a166f96fa0d46ffbbb924ed8ab94 | refs/heads/master | 2019-03-20T20:18:17.733000 | 2018-02-24T07:32:10 | 2018-02-24T07:32:10 | 124,027,804 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.bbdservice.sichuan.service;
import com.bbdservice.sichuan.entity.SysUserRole;
import org.apache.ibatis.annotations.Param;
import java.util.List;
/**
* Created by ้ไบๅ
ฐ on 2018/1/19.
*/
public interface SysUserRoleService {
List<SysUserRole> selectByRoleId(String roleId);
SysUserRole selectByUserId(@Param("userId") String userId);
void deleteByUserId(@Param("userId") String userId);
}
| UTF-8 | Java | 420 | java | SysUserRoleService.java | Java | [
{
"context": "Param;\n\nimport java.util.List;\n\n/**\n * Created by ้ไบๅ
ฐ on 2018/1/19.\n */\npublic interface SysUserRoleSer",
"end": 181,
"score": 0.9993548393249512,
"start": 178,
"tag": "NAME",
"value": "้ไบๅ
ฐ"
}
]
| null | []
| package com.bbdservice.sichuan.service;
import com.bbdservice.sichuan.entity.SysUserRole;
import org.apache.ibatis.annotations.Param;
import java.util.List;
/**
* Created by ้ไบๅ
ฐ on 2018/1/19.
*/
public interface SysUserRoleService {
List<SysUserRole> selectByRoleId(String roleId);
SysUserRole selectByUserId(@Param("userId") String userId);
void deleteByUserId(@Param("userId") String userId);
}
| 420 | 0.763285 | 0.746377 | 15 | 26.6 | 22.802923 | 63 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.466667 | false | false | 13 |
5f647a04c6e939da4c5ff8c534e22daf850fcbeb | 33,217,277,129,849 | e62c3b93b38d2d7781d38ba1cdbabfea2c1cf7af | /BocBankMobile/src/main/java/com/boc/bocsoft/mobile/bocmobile/base/widget/dialogview/securityverify/eshield/DriverConnect.java | 03df5e578af0e701c75e44732388aedf3a25c4e5 | []
| no_license | soghao/zgyh | https://github.com/soghao/zgyh | df34779708a8d6088b869d0efc6fe1c84e53b7b1 | 09994dda29f44b6c1f7f5c7c0b12f956fc9a42c1 | refs/heads/master | 2021-06-19T07:36:53.910000 | 2017-06-23T14:23:10 | 2017-06-23T14:23:10 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.boc.bocsoft.mobile.bocmobile.base.widget.dialogview.securityverify.eshield;
import android.app.Activity;
import android.text.TextUtils;
import com.boc.bocsoft.mobile.bocmobile.base.utils.LogUtils;
import com.boc.bocsoft.mobile.bocmobile.base.widget.dialogview.securityverify.EShieldSequenceDialog;
import com.boc.bocsoft.mobile.bocmobile.base.widget.dialogview.securityverify.EShieldVerify;
import com.boc.device.key.KeyConst;
import com.boc.keydriverinterface.MEBBocKeyMerchantType;
import com.boc.keydriverinterface.MEBKeyDriverCommonModel;
import com.boc.keydriverinterface.MEBKeyDriverInterface;
/**
* Created by wangtong on 2016/7/6.
*/
public class DriverConnect implements EShieldVerify.Command {
private final static String LOG_TAG = DriverConnect.class.getSimpleName();
private Activity activity;
//ๅๅๅบๅๅท
private String mSn;
private boolean isCommandSucceed = true;
private EShieldSequenceDialog dialog;
public DriverConnect(Activity activity) {
this.activity = activity;
}
@Override
public boolean execute() {
LogUtils.i(LOG_TAG, "execute: ๅผๅงๆง่ก....");
String defaultSn = EShieldVerify.getInstance(activity).getSequence();
LogUtils.i(LOG_TAG, "defaultSn: ไฟๅญ็SNไธบ:" + defaultSn);
if (TextUtils.isEmpty(defaultSn)) {
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
LogUtils.i(LOG_TAG, "ๅฝๅไฟๅญ็SNไธบ็ฉบ:" + "่ฏท็จๆท่พๅ
ฅ6ไธบ็snๅท");
dialog = new EShieldSequenceDialog(activity);
dialog.show();
}
});
try {
EShieldVerify.waitThread();
} catch (InterruptedException e) {
e.printStackTrace();
isCommandSucceed = false;
}
mSn = dialog.getSequence();
LogUtils.i(LOG_TAG, "็จๆท่พๅ
ฅ็SNๅทไธบ:" + mSn);
} else {
mSn = defaultSn;
}
initDriver();
return isCommandSucceed;
}
@Override
public void stop() {
isCommandSucceed = false;
if (dialog != null && dialog.isShowing()) {
dialog.cancel();
}
}
/**
* ๅฏนdriver ่ฟ่กๅๅงๅ
*/
public void initDriver() {
// ๅฆๆๅบๅๅทไธบ็ฉบ่ชๅจๅน้
ๅๅ๏ผๅฆๅๆ นๆฎๅบๅๅทๆนๅค
MEBKeyDriverInterface driver = EShieldVerify.getInstance(activity).getKeyDriverInterface();
EShieldVerify.getInstance(activity).initCACallBack();
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
EShieldVerify.getInstance(activity).showLoadingDialog();
}
});
if (driver == null) {
LogUtils.i(LOG_TAG, "driver:ไธบ็ฉบ...");
if (TextUtils.isEmpty(mSn)) {
LogUtils.i(LOG_TAG, "mSn:ไธบ็ฉบ...");
driver = new MEBKeyDriverInterface(activity);
EShieldVerify.getInstance(activity).setKeyDriverInterface(driver);
} else {
LogUtils.i(LOG_TAG, "mSn:ไธไธบ็ฉบ...");
if (mSn != null && mSn.length() >= 6) {
String tmp = mSn.substring(5, 6);
if ("4".equals(tmp) || "5".equals(tmp) || "6".equals(tmp)) {
MEBBocKeyMerchantType type = findMerchantType(tmp);
// driver.changeDriverBySn(mSn);
driver = new MEBKeyDriverInterface(activity, type);
} else {
driver = new MEBKeyDriverInterface(activity);
}
} else {
driver = new MEBKeyDriverInterface(activity);
}
EShieldVerify.getInstance(activity).setKeyDriverInterface(driver);
}
}
if (driver != null) {
// ๅคๆญๆฏๅฆ้่ฆไฟฎๆนๅฏ็
final MEBKeyDriverCommonModel model = driver.getKeyDriverInfoBeforeLogin(activity);
// ่ฟๆฅๅคฑ่ดฅ
if (model.mError.getErrorId() != KeyConst.BOC_SUCCESS) {
isCommandSucceed = false;
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
EShieldVerify.getInstance(activity).closeProgressDialog();
EShieldVerify.getInstance(activity).showErrorDialog(model.mError.getErrorMessage());
}
});
} else {
// ๆฏๅฆไฟฎๆนpin็
boolean isPinNeedModify = model.mInfo.getIsPinNeedModify();
String sn = model.mInfo.getKeySN();
LogUtils.i(LOG_TAG, "isPinNeedModify๏ผ" + "ๆฏๅฆ้ฆๆฌกไฝฟ็จ" + isPinNeedModify);
LogUtils.i(LOG_TAG, "sn๏ผ" + "่ฎพๅค็snๅท๏ผ" + sn);
if (null == sn || "".equals(sn.trim())) {
isCommandSucceed = false;
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
EShieldVerify.getInstance(activity).closeProgressDialog();
EShieldVerify.getInstance(activity).showErrorDialog("่ฎพๅค่ฟๆฅๅคฑ่ดฅ๏ผ่ฏท็จๅๅ่ฏ");
}
});
} else {
isCommandSucceed = true;
EShieldVerify.getInstance(activity).setNeedChangePassword(isPinNeedModify);
EShieldVerify.getInstance(activity).setSequence(sn);
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
EShieldVerify.getInstance(activity).closeProgressDialog();
}
});
}
}
} else {
isCommandSucceed = false;
}
}
private MEBBocKeyMerchantType findMerchantType(String snType){
if ("4".equals(snType)) {
return MEBBocKeyMerchantType.BOCKeyMerchantWatchData;
} else if ("5".equals(snType)){
return MEBBocKeyMerchantType.BOCKeyMerchantFeiTian;
} else if ("6".equals(snType)){
return MEBBocKeyMerchantType.BOCKeyMerchantWenDingChuang;
} else {
return MEBBocKeyMerchantType.BOCKeyMerchantUnknown;
}
}
}
| UTF-8 | Java | 6,590 | java | DriverConnect.java | Java | [
{
"context": "nterface.MEBKeyDriverInterface;\n\n/**\n * Created by wangtong on 2016/7/6.\n */\npublic class DriverConnect imple",
"end": 641,
"score": 0.9995748400688171,
"start": 633,
"tag": "USERNAME",
"value": "wangtong"
}
]
| null | []
| package com.boc.bocsoft.mobile.bocmobile.base.widget.dialogview.securityverify.eshield;
import android.app.Activity;
import android.text.TextUtils;
import com.boc.bocsoft.mobile.bocmobile.base.utils.LogUtils;
import com.boc.bocsoft.mobile.bocmobile.base.widget.dialogview.securityverify.EShieldSequenceDialog;
import com.boc.bocsoft.mobile.bocmobile.base.widget.dialogview.securityverify.EShieldVerify;
import com.boc.device.key.KeyConst;
import com.boc.keydriverinterface.MEBBocKeyMerchantType;
import com.boc.keydriverinterface.MEBKeyDriverCommonModel;
import com.boc.keydriverinterface.MEBKeyDriverInterface;
/**
* Created by wangtong on 2016/7/6.
*/
public class DriverConnect implements EShieldVerify.Command {
private final static String LOG_TAG = DriverConnect.class.getSimpleName();
private Activity activity;
//ๅๅๅบๅๅท
private String mSn;
private boolean isCommandSucceed = true;
private EShieldSequenceDialog dialog;
public DriverConnect(Activity activity) {
this.activity = activity;
}
@Override
public boolean execute() {
LogUtils.i(LOG_TAG, "execute: ๅผๅงๆง่ก....");
String defaultSn = EShieldVerify.getInstance(activity).getSequence();
LogUtils.i(LOG_TAG, "defaultSn: ไฟๅญ็SNไธบ:" + defaultSn);
if (TextUtils.isEmpty(defaultSn)) {
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
LogUtils.i(LOG_TAG, "ๅฝๅไฟๅญ็SNไธบ็ฉบ:" + "่ฏท็จๆท่พๅ
ฅ6ไธบ็snๅท");
dialog = new EShieldSequenceDialog(activity);
dialog.show();
}
});
try {
EShieldVerify.waitThread();
} catch (InterruptedException e) {
e.printStackTrace();
isCommandSucceed = false;
}
mSn = dialog.getSequence();
LogUtils.i(LOG_TAG, "็จๆท่พๅ
ฅ็SNๅทไธบ:" + mSn);
} else {
mSn = defaultSn;
}
initDriver();
return isCommandSucceed;
}
@Override
public void stop() {
isCommandSucceed = false;
if (dialog != null && dialog.isShowing()) {
dialog.cancel();
}
}
/**
* ๅฏนdriver ่ฟ่กๅๅงๅ
*/
public void initDriver() {
// ๅฆๆๅบๅๅทไธบ็ฉบ่ชๅจๅน้
ๅๅ๏ผๅฆๅๆ นๆฎๅบๅๅทๆนๅค
MEBKeyDriverInterface driver = EShieldVerify.getInstance(activity).getKeyDriverInterface();
EShieldVerify.getInstance(activity).initCACallBack();
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
EShieldVerify.getInstance(activity).showLoadingDialog();
}
});
if (driver == null) {
LogUtils.i(LOG_TAG, "driver:ไธบ็ฉบ...");
if (TextUtils.isEmpty(mSn)) {
LogUtils.i(LOG_TAG, "mSn:ไธบ็ฉบ...");
driver = new MEBKeyDriverInterface(activity);
EShieldVerify.getInstance(activity).setKeyDriverInterface(driver);
} else {
LogUtils.i(LOG_TAG, "mSn:ไธไธบ็ฉบ...");
if (mSn != null && mSn.length() >= 6) {
String tmp = mSn.substring(5, 6);
if ("4".equals(tmp) || "5".equals(tmp) || "6".equals(tmp)) {
MEBBocKeyMerchantType type = findMerchantType(tmp);
// driver.changeDriverBySn(mSn);
driver = new MEBKeyDriverInterface(activity, type);
} else {
driver = new MEBKeyDriverInterface(activity);
}
} else {
driver = new MEBKeyDriverInterface(activity);
}
EShieldVerify.getInstance(activity).setKeyDriverInterface(driver);
}
}
if (driver != null) {
// ๅคๆญๆฏๅฆ้่ฆไฟฎๆนๅฏ็
final MEBKeyDriverCommonModel model = driver.getKeyDriverInfoBeforeLogin(activity);
// ่ฟๆฅๅคฑ่ดฅ
if (model.mError.getErrorId() != KeyConst.BOC_SUCCESS) {
isCommandSucceed = false;
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
EShieldVerify.getInstance(activity).closeProgressDialog();
EShieldVerify.getInstance(activity).showErrorDialog(model.mError.getErrorMessage());
}
});
} else {
// ๆฏๅฆไฟฎๆนpin็
boolean isPinNeedModify = model.mInfo.getIsPinNeedModify();
String sn = model.mInfo.getKeySN();
LogUtils.i(LOG_TAG, "isPinNeedModify๏ผ" + "ๆฏๅฆ้ฆๆฌกไฝฟ็จ" + isPinNeedModify);
LogUtils.i(LOG_TAG, "sn๏ผ" + "่ฎพๅค็snๅท๏ผ" + sn);
if (null == sn || "".equals(sn.trim())) {
isCommandSucceed = false;
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
EShieldVerify.getInstance(activity).closeProgressDialog();
EShieldVerify.getInstance(activity).showErrorDialog("่ฎพๅค่ฟๆฅๅคฑ่ดฅ๏ผ่ฏท็จๅๅ่ฏ");
}
});
} else {
isCommandSucceed = true;
EShieldVerify.getInstance(activity).setNeedChangePassword(isPinNeedModify);
EShieldVerify.getInstance(activity).setSequence(sn);
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
EShieldVerify.getInstance(activity).closeProgressDialog();
}
});
}
}
} else {
isCommandSucceed = false;
}
}
private MEBBocKeyMerchantType findMerchantType(String snType){
if ("4".equals(snType)) {
return MEBBocKeyMerchantType.BOCKeyMerchantWatchData;
} else if ("5".equals(snType)){
return MEBBocKeyMerchantType.BOCKeyMerchantFeiTian;
} else if ("6".equals(snType)){
return MEBBocKeyMerchantType.BOCKeyMerchantWenDingChuang;
} else {
return MEBBocKeyMerchantType.BOCKeyMerchantUnknown;
}
}
}
| 6,590 | 0.552044 | 0.549528 | 171 | 36.192982 | 26.882963 | 108 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.690058 | false | false | 13 |
e6c6cedd5875ecec59431284007e2225751194ec | 2,130,303,826,979 | ebbcc9d53dd0d55f050ae6c18ea3a3a41cf9a0ae | /app/src/main/java/org/YYY.java | 78370de5937876b17a714fb82c90f68cd45ef7f2 | []
| no_license | manhtuongbkhn/AiSoAi | https://github.com/manhtuongbkhn/AiSoAi | edd063d118ca4fd134d423aa846219c58ae4ed26 | 41f50fbde408744d5727d1686892ef1776cdff4a | refs/heads/master | 2021-01-21T13:43:48.650000 | 2016-06-02T10:04:05 | 2016-06-02T10:04:05 | 49,548,813 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package org;
/**
* Created by manhtuong on 3/8/16.
*/
public class YYY {
}
| UTF-8 | Java | 78 | java | YYY.java | Java | [
{
"context": "package org;\n\n/**\n * Created by manhtuong on 3/8/16.\n */\npublic class YYY {\n}\n",
"end": 41,
"score": 0.9875503778457642,
"start": 32,
"tag": "USERNAME",
"value": "manhtuong"
}
]
| null | []
| package org;
/**
* Created by manhtuong on 3/8/16.
*/
public class YYY {
}
| 78 | 0.615385 | 0.564103 | 7 | 10.142858 | 11.482018 | 34 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.142857 | false | false | 13 |
c8cc3f76eb2cfb1a35dfc506ea2fbee46133091b | 17,033,840,352,794 | 20f68606be58c1c6006ea48aa1a359df123e1daf | /examples/src/it/java/jdocs/cassandra/WordCountDocExample.java | 1df2c0ff459decca83d40a29148f490fd42e5204 | [
"Apache-2.0"
]
| permissive | claudio-scandura/akka-projection | https://github.com/claudio-scandura/akka-projection | a891cdf0ef77cc85703ffe927242d6f8722d44a1 | d416ec2537a4a3717d9c2d48e48a2f77cdbaf77b | refs/heads/master | 2023-03-13T10:23:02.947000 | 2021-02-24T10:04:52 | 2021-02-24T10:04:52 | 292,866,218 | 0 | 0 | NOASSERTION | true | 2020-09-04T14:18:42 | 2020-09-04T14:18:41 | 2020-09-04T13:18:35 | 2020-09-04T13:18:33 | 2,564 | 0 | 0 | 0 | null | false | false | /*
* Copyright (C) 2020-2021 Lightbend Inc. <https://www.lightbend.com>
*/
package jdocs.cassandra;
// #StatefulHandler-imports
import akka.actor.typed.ActorSystem;
import akka.actor.typed.SupervisorStrategy;
import akka.actor.typed.javadsl.AskPattern;
import akka.actor.typed.javadsl.StashBuffer;
import akka.projection.cassandra.CassandraProjectionTest;
import akka.projection.javadsl.ActorHandler;
import akka.projection.javadsl.StatefulHandler;
// #StatefulHandler-imports
// #ActorHandler-imports
import akka.actor.typed.ActorRef;
import akka.actor.typed.Behavior;
import akka.actor.typed.javadsl.AbstractBehavior;
import akka.actor.typed.javadsl.ActorContext;
import akka.actor.typed.javadsl.Behaviors;
import akka.actor.typed.javadsl.Receive;
// #ActorHandler-imports
import java.time.Duration;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import akka.Done;
import akka.NotUsed;
import akka.projection.ProjectionId;
import akka.projection.javadsl.Handler;
import akka.projection.javadsl.SourceProvider;
import akka.stream.alpakka.cassandra.javadsl.CassandraSession;
import akka.stream.javadsl.Source;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public interface WordCountDocExample {
// #todo
// TDOO
// #todo
// #envelope
public class WordEnvelope {
public final Long offset;
public final String word;
public WordEnvelope(Long offset, String word) {
this.offset = offset;
this.word = word;
}
}
// #envelope
// #repository
public interface WordCountRepository {
CompletionStage<Integer> load(String id, String word);
CompletionStage<Map<String, Integer>> loadAll(String id);
CompletionStage<Done> save(String id, String word, int count);
}
// #repository
public class CassandraWordCountRepository implements WordCountRepository {
private final CassandraSession session;
final String keyspace = "test";
final String table = "wordcount";
private final String keyspaceTable = keyspace + "." + table;
public CassandraWordCountRepository(CassandraSession session) {
this.session = session;
}
@Override
public CompletionStage<Integer> load(String id, String word) {
return session
.selectOne("SELECT count FROM " + keyspaceTable + " WHERE id = ? and word = ?", id, word)
.thenApply(
maybeRow -> {
if (maybeRow.isPresent()) return maybeRow.get().getInt("count");
else return 0;
});
}
@Override
public CompletionStage<Map<String, Integer>> loadAll(String id) {
return session
.selectAll("SELECT word, count FROM " + keyspaceTable + " WHERE id = ?", id)
.thenApply(
rows -> {
return rows.stream()
.collect(
Collectors.toMap(row -> row.getString("word"), row -> row.getInt("count")));
});
}
@Override
public CompletionStage<Done> save(String id, String word, int count) {
return session.executeWrite(
"INSERT INTO " + keyspaceTable + " (id, word, count) VALUES (?, ?, ?)", id, word, count);
}
public CompletionStage<Done> createKeyspaceAndTable() {
return session
.executeDDL(
"CREATE KEYSPACE IF NOT EXISTS "
+ keyspace
+ " WITH REPLICATION = { 'class' : 'SimpleStrategy','replication_factor':1 }")
.thenCompose(
done ->
session.executeDDL(
"CREATE TABLE IF NOT EXISTS "
+ keyspaceTable
+ " (\n"
+ " id text, \n"
+ " word text, \n"
+ " count int, \n"
+ " PRIMARY KEY (id, word)) \n"));
}
}
// #sourceProvider
class WordSource extends SourceProvider<Long, WordEnvelope> {
private final Source<WordEnvelope, NotUsed> src =
Source.from(
Arrays.asList(
new WordEnvelope(1L, "abc"),
new WordEnvelope(2L, "def"),
new WordEnvelope(3L, "ghi"),
new WordEnvelope(4L, "abc")));
@Override
public CompletionStage<Source<WordEnvelope, NotUsed>> source(
Supplier<CompletionStage<Optional<Long>>> offset) {
return offset
.get()
.thenApply(
o -> {
if (o.isPresent()) return src.dropWhile(envelope -> envelope.offset <= o.get());
else return src;
});
}
@Override
public Long extractOffset(WordEnvelope envelope) {
return envelope.offset;
}
@Override
public long extractCreationTime(WordEnvelope envelope) {
return 0L;
}
}
// #sourceProvider
interface IllustrateVariables {
// #mutableState
public class WordCountHandler extends Handler<WordEnvelope> {
private final Logger logger = LoggerFactory.getLogger(getClass());
private final Map<String, Integer> state = new HashMap<>();
@Override
public CompletionStage<Done> process(WordEnvelope envelope) {
String word = envelope.word;
int newCount = state.getOrDefault(word, 0) + 1;
logger.info("Word count for {} is {}", word, newCount);
state.put(word, newCount);
return CompletableFuture.completedFuture(Done.getInstance());
}
}
// #mutableState
}
interface IllustrateStatefulHandlerLoadingInitialState {
// #loadingInitialState
public class WordCountHandler extends StatefulHandler<Map<String, Integer>, WordEnvelope> {
private final ProjectionId projectionId;
private final WordCountRepository repository;
public WordCountHandler(ProjectionId projectionId, WordCountRepository repository) {
this.projectionId = projectionId;
this.repository = repository;
}
@Override
public CompletionStage<Map<String, Integer>> initialState() {
return repository.loadAll(projectionId.id());
}
@Override
public CompletionStage<Map<String, Integer>> process(
Map<String, Integer> state, WordEnvelope envelope) {
String word = envelope.word;
int newCount = state.getOrDefault(word, 0) + 1;
CompletionStage<Map<String, Integer>> newState =
repository
.save(projectionId.id(), word, newCount)
.thenApply(
done -> {
state.put(word, newCount);
return state;
});
return newState;
}
}
// #loadingInitialState
}
interface IllustrateStatefulHandlerLoadingStateOnDemand {
// #loadingOnDemand
public class WordCountHandler extends StatefulHandler<Map<String, Integer>, WordEnvelope> {
private final ProjectionId projectionId;
private final WordCountRepository repository;
public WordCountHandler(ProjectionId projectionId, WordCountRepository repository) {
this.projectionId = projectionId;
this.repository = repository;
}
@Override
public CompletionStage<Map<String, Integer>> initialState() {
return CompletableFuture.completedFuture(new HashMap<>());
}
@Override
public CompletionStage<Map<String, Integer>> process(
Map<String, Integer> state, WordEnvelope envelope) {
String word = envelope.word;
CompletionStage<Integer> currentCount;
if (state.containsKey(word))
currentCount = CompletableFuture.completedFuture(state.get(word));
else currentCount = repository.load(projectionId.id(), word);
CompletionStage<Map<String, Integer>> newState =
currentCount.thenCompose(
n -> {
return repository
.save(projectionId.id(), word, n + 1)
.thenApply(
done -> {
state.put(word, n + 1);
return state;
});
});
return newState;
}
}
// #loadingOnDemand
}
interface IllstrateActorLoadingInitialState {
// #actorHandler
class WordCountActorHandler extends ActorHandler<WordEnvelope, WordCountProcessor.Command> {
private final ActorSystem<?> system;
private final Duration askTimeout = Duration.ofSeconds(5);
WordCountActorHandler(Behavior<WordCountProcessor.Command> behavior, ActorSystem<?> system) {
super(behavior);
this.system = system;
}
@Override
public CompletionStage<Done> process(
ActorRef<WordCountProcessor.Command> actor, WordEnvelope envelope) {
CompletionStage<WordCountProcessor.Result> result =
AskPattern.ask(
actor,
(ActorRef<WordCountProcessor.Result> replyTo) ->
new WordCountProcessor.Handle(envelope, replyTo),
askTimeout,
system.scheduler());
return result.thenCompose(
r -> {
if (r.error.isPresent()) {
CompletableFuture<Done> err = new CompletableFuture<>();
err.completeExceptionally(r.error.get());
return err;
} else {
return CompletableFuture.completedFuture(Done.getInstance());
}
});
}
}
// #actorHandler
// #behaviorLoadingInitialState
public class WordCountProcessor {
public interface Command {}
public static class Handle implements Command {
public final WordEnvelope envelope;
public final ActorRef<Result> replyTo;
public Handle(WordEnvelope envelope, ActorRef<Result> replyTo) {
this.envelope = envelope;
this.replyTo = replyTo;
}
}
public static class Result {
public final Optional<Throwable> error;
public Result(Optional<Throwable> error) {
this.error = error;
}
}
private static class InitialState implements Command {
final Map<String, Integer> state;
private InitialState(Map<String, Integer> state) {
this.state = state;
}
}
private static class SaveCompleted implements Command {
final String word;
final Optional<Throwable> error;
final ActorRef<Result> replyTo;
private SaveCompleted(String word, Optional<Throwable> error, ActorRef<Result> replyTo) {
this.word = word;
this.error = error;
this.replyTo = replyTo;
}
}
public static Behavior<Command> create(
ProjectionId projectionId, WordCountRepository repository) {
return Behaviors.supervise(
Behaviors.setup(
(ActorContext<Command> context) ->
new WordCountProcessor(projectionId, repository).init(context)))
.onFailure(
SupervisorStrategy.restartWithBackoff(
Duration.ofSeconds(1), Duration.ofSeconds(10), 0.1));
}
private final ProjectionId projectionId;
private final WordCountRepository repository;
private WordCountProcessor(ProjectionId projectionId, WordCountRepository repository) {
this.projectionId = projectionId;
this.repository = repository;
}
Behavior<Command> init(ActorContext<Command> context) {
return Behaviors.withStash(10, buffer -> new Initializing(context, buffer));
}
private class Initializing extends AbstractBehavior<Command> {
private final StashBuffer<Command> buffer;
private Initializing(ActorContext<Command> context, StashBuffer<Command> buffer) {
super(context);
this.buffer = buffer;
getContext()
.pipeToSelf(
repository.loadAll(projectionId.id()),
(value, exc) -> {
if (value != null) return new InitialState(value);
else throw new RuntimeException("Load failed.", exc);
});
}
@Override
public Receive<Command> createReceive() {
return newReceiveBuilder()
.onMessage(InitialState.class, this::onInitalState)
.onAnyMessage(this::onOther)
.build();
}
private Behavior<Command> onInitalState(InitialState initialState) {
getContext().getLog().debug("Initial state [{}]", initialState.state);
return buffer.unstashAll(new Active(getContext(), initialState.state));
}
private Behavior<Command> onOther(Command command) {
getContext().getLog().debug("Stashed [{}]", command);
buffer.stash(command);
return this;
}
}
private class Active extends AbstractBehavior<Command> {
private final Map<String, Integer> state;
public Active(ActorContext<Command> context, Map<String, Integer> state) {
super(context);
this.state = state;
}
@Override
public Receive<Command> createReceive() {
return newReceiveBuilder()
.onMessage(Handle.class, this::onHandle)
.onMessage(SaveCompleted.class, this::onSaveCompleted)
.build();
}
private Behavior<Command> onHandle(Handle command) {
String word = command.envelope.word;
int newCount = state.getOrDefault(word, 0) + 1;
getContext()
.pipeToSelf(
repository.save(projectionId.id(), word, newCount),
(done, exc) ->
// will reply from SaveCompleted
new SaveCompleted(word, Optional.ofNullable(exc), command.replyTo));
return this;
}
private Behavior<Command> onSaveCompleted(SaveCompleted completed) {
completed.replyTo.tell(new Result(completed.error));
if (completed.error.isPresent()) {
// restart, reload state from db
throw new RuntimeException("Save failed.", completed.error.get());
} else {
String word = completed.word;
int newCount = state.getOrDefault(word, 0) + 1;
state.put(word, newCount);
}
return this;
}
}
}
// #behaviorLoadingInitialState
}
interface IllstrateActorLoadingStateOnDemand {
class WordCountActorHandler extends ActorHandler<WordEnvelope, WordCountProcessor.Command> {
private final ActorSystem<?> system;
private final Duration askTimeout = Duration.ofSeconds(5);
WordCountActorHandler(Behavior<WordCountProcessor.Command> behavior, ActorSystem<?> system) {
super(behavior);
this.system = system;
}
@Override
public CompletionStage<Done> process(
ActorRef<WordCountProcessor.Command> actor, WordEnvelope envelope) {
CompletionStage<WordCountProcessor.Result> result =
AskPattern.ask(
actor,
(ActorRef<WordCountProcessor.Result> replyTo) ->
new WordCountProcessor.Handle(envelope, replyTo),
askTimeout,
system.scheduler());
return result.thenCompose(
r -> {
if (r.error.isPresent()) {
CompletableFuture<Done> err = new CompletableFuture<>();
err.completeExceptionally(r.error.get());
return err;
} else {
return CompletableFuture.completedFuture(Done.getInstance());
}
});
}
}
// #behaviorLoadingOnDemand
public class WordCountProcessor extends AbstractBehavior<WordCountProcessor.Command> {
public interface Command {}
public static class Handle implements Command {
public final WordEnvelope envelope;
public final ActorRef<Result> replyTo;
public Handle(WordEnvelope envelope, ActorRef<Result> replyTo) {
this.envelope = envelope;
this.replyTo = replyTo;
}
}
public static class Result {
public final Optional<Throwable> error;
public Result(Optional<Throwable> error) {
this.error = error;
}
}
private static class LoadCompleted implements Command {
final String word;
final Optional<Throwable> error;
final ActorRef<Result> replyTo;
private LoadCompleted(String word, Optional<Throwable> error, ActorRef<Result> replyTo) {
this.word = word;
this.error = error;
this.replyTo = replyTo;
}
}
private static class SaveCompleted implements Command {
final String word;
final Optional<Throwable> error;
final ActorRef<Result> replyTo;
private SaveCompleted(String word, Optional<Throwable> error, ActorRef<Result> replyTo) {
this.word = word;
this.error = error;
this.replyTo = replyTo;
}
}
public static Behavior<Command> create(
ProjectionId projectionId, WordCountRepository repository) {
return Behaviors.supervise(
Behaviors.setup(
(ActorContext<Command> context) ->
new WordCountProcessor(context, projectionId, repository)))
.onFailure(
SupervisorStrategy.restartWithBackoff(
Duration.ofSeconds(1), Duration.ofSeconds(10), 0.1));
}
private final ProjectionId projectionId;
private final WordCountRepository repository;
private final Map<String, Integer> state = new HashMap<>();
private WordCountProcessor(
ActorContext<Command> context,
ProjectionId projectionId,
WordCountRepository repository) {
super(context);
this.projectionId = projectionId;
this.repository = repository;
}
@Override
public Receive<Command> createReceive() {
return newReceiveBuilder()
.onMessage(Handle.class, this::onHandle)
.onMessage(LoadCompleted.class, this::onLoadCompleted)
.onMessage(SaveCompleted.class, this::onSaveCompleted)
.build();
}
private Behavior<Command> onHandle(Handle command) {
String word = command.envelope.word;
if (state.containsKey(word)) {
int newCount = state.get(word) + 1;
getContext()
.pipeToSelf(
repository.save(projectionId.id(), word, newCount),
(done, exc) ->
// will reply from SaveCompleted
new SaveCompleted(word, Optional.ofNullable(exc), command.replyTo));
} else {
getContext()
.pipeToSelf(
repository.load(projectionId.id(), word),
(loadResult, exc) ->
// will reply from LoadCompleted
new LoadCompleted(word, Optional.ofNullable(exc), command.replyTo));
}
return this;
}
private Behavior<Command> onLoadCompleted(LoadCompleted completed) {
if (completed.error.isPresent()) {
completed.replyTo.tell(new Result(completed.error));
} else {
String word = completed.word;
int newCount = state.getOrDefault(word, 0) + 1;
getContext()
.pipeToSelf(
repository.save(projectionId.id(), word, newCount),
(done, exc) ->
// will reply from SaveCompleted
new SaveCompleted(word, Optional.ofNullable(exc), completed.replyTo));
}
return this;
}
private Behavior<Command> onSaveCompleted(SaveCompleted completed) {
completed.replyTo.tell(new Result(completed.error));
if (completed.error.isPresent()) {
// remove the word from the state if the save failed, because it could have been a timeout
// so that it was actually saved, best to reload
state.remove(completed.word);
} else {
String word = completed.word;
int newCount = state.getOrDefault(word, 0) + 1;
state.put(word, newCount);
}
return this;
}
}
}
// #behaviorLoadingOnDemand
}
| UTF-8 | Java | 20,797 | java | WordCountDocExample.java | Java | []
| null | []
| /*
* Copyright (C) 2020-2021 Lightbend Inc. <https://www.lightbend.com>
*/
package jdocs.cassandra;
// #StatefulHandler-imports
import akka.actor.typed.ActorSystem;
import akka.actor.typed.SupervisorStrategy;
import akka.actor.typed.javadsl.AskPattern;
import akka.actor.typed.javadsl.StashBuffer;
import akka.projection.cassandra.CassandraProjectionTest;
import akka.projection.javadsl.ActorHandler;
import akka.projection.javadsl.StatefulHandler;
// #StatefulHandler-imports
// #ActorHandler-imports
import akka.actor.typed.ActorRef;
import akka.actor.typed.Behavior;
import akka.actor.typed.javadsl.AbstractBehavior;
import akka.actor.typed.javadsl.ActorContext;
import akka.actor.typed.javadsl.Behaviors;
import akka.actor.typed.javadsl.Receive;
// #ActorHandler-imports
import java.time.Duration;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import akka.Done;
import akka.NotUsed;
import akka.projection.ProjectionId;
import akka.projection.javadsl.Handler;
import akka.projection.javadsl.SourceProvider;
import akka.stream.alpakka.cassandra.javadsl.CassandraSession;
import akka.stream.javadsl.Source;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public interface WordCountDocExample {
// #todo
// TDOO
// #todo
// #envelope
public class WordEnvelope {
public final Long offset;
public final String word;
public WordEnvelope(Long offset, String word) {
this.offset = offset;
this.word = word;
}
}
// #envelope
// #repository
public interface WordCountRepository {
CompletionStage<Integer> load(String id, String word);
CompletionStage<Map<String, Integer>> loadAll(String id);
CompletionStage<Done> save(String id, String word, int count);
}
// #repository
public class CassandraWordCountRepository implements WordCountRepository {
private final CassandraSession session;
final String keyspace = "test";
final String table = "wordcount";
private final String keyspaceTable = keyspace + "." + table;
public CassandraWordCountRepository(CassandraSession session) {
this.session = session;
}
@Override
public CompletionStage<Integer> load(String id, String word) {
return session
.selectOne("SELECT count FROM " + keyspaceTable + " WHERE id = ? and word = ?", id, word)
.thenApply(
maybeRow -> {
if (maybeRow.isPresent()) return maybeRow.get().getInt("count");
else return 0;
});
}
@Override
public CompletionStage<Map<String, Integer>> loadAll(String id) {
return session
.selectAll("SELECT word, count FROM " + keyspaceTable + " WHERE id = ?", id)
.thenApply(
rows -> {
return rows.stream()
.collect(
Collectors.toMap(row -> row.getString("word"), row -> row.getInt("count")));
});
}
@Override
public CompletionStage<Done> save(String id, String word, int count) {
return session.executeWrite(
"INSERT INTO " + keyspaceTable + " (id, word, count) VALUES (?, ?, ?)", id, word, count);
}
public CompletionStage<Done> createKeyspaceAndTable() {
return session
.executeDDL(
"CREATE KEYSPACE IF NOT EXISTS "
+ keyspace
+ " WITH REPLICATION = { 'class' : 'SimpleStrategy','replication_factor':1 }")
.thenCompose(
done ->
session.executeDDL(
"CREATE TABLE IF NOT EXISTS "
+ keyspaceTable
+ " (\n"
+ " id text, \n"
+ " word text, \n"
+ " count int, \n"
+ " PRIMARY KEY (id, word)) \n"));
}
}
// #sourceProvider
class WordSource extends SourceProvider<Long, WordEnvelope> {
private final Source<WordEnvelope, NotUsed> src =
Source.from(
Arrays.asList(
new WordEnvelope(1L, "abc"),
new WordEnvelope(2L, "def"),
new WordEnvelope(3L, "ghi"),
new WordEnvelope(4L, "abc")));
@Override
public CompletionStage<Source<WordEnvelope, NotUsed>> source(
Supplier<CompletionStage<Optional<Long>>> offset) {
return offset
.get()
.thenApply(
o -> {
if (o.isPresent()) return src.dropWhile(envelope -> envelope.offset <= o.get());
else return src;
});
}
@Override
public Long extractOffset(WordEnvelope envelope) {
return envelope.offset;
}
@Override
public long extractCreationTime(WordEnvelope envelope) {
return 0L;
}
}
// #sourceProvider
interface IllustrateVariables {
// #mutableState
public class WordCountHandler extends Handler<WordEnvelope> {
private final Logger logger = LoggerFactory.getLogger(getClass());
private final Map<String, Integer> state = new HashMap<>();
@Override
public CompletionStage<Done> process(WordEnvelope envelope) {
String word = envelope.word;
int newCount = state.getOrDefault(word, 0) + 1;
logger.info("Word count for {} is {}", word, newCount);
state.put(word, newCount);
return CompletableFuture.completedFuture(Done.getInstance());
}
}
// #mutableState
}
interface IllustrateStatefulHandlerLoadingInitialState {
// #loadingInitialState
public class WordCountHandler extends StatefulHandler<Map<String, Integer>, WordEnvelope> {
private final ProjectionId projectionId;
private final WordCountRepository repository;
public WordCountHandler(ProjectionId projectionId, WordCountRepository repository) {
this.projectionId = projectionId;
this.repository = repository;
}
@Override
public CompletionStage<Map<String, Integer>> initialState() {
return repository.loadAll(projectionId.id());
}
@Override
public CompletionStage<Map<String, Integer>> process(
Map<String, Integer> state, WordEnvelope envelope) {
String word = envelope.word;
int newCount = state.getOrDefault(word, 0) + 1;
CompletionStage<Map<String, Integer>> newState =
repository
.save(projectionId.id(), word, newCount)
.thenApply(
done -> {
state.put(word, newCount);
return state;
});
return newState;
}
}
// #loadingInitialState
}
interface IllustrateStatefulHandlerLoadingStateOnDemand {
// #loadingOnDemand
public class WordCountHandler extends StatefulHandler<Map<String, Integer>, WordEnvelope> {
private final ProjectionId projectionId;
private final WordCountRepository repository;
public WordCountHandler(ProjectionId projectionId, WordCountRepository repository) {
this.projectionId = projectionId;
this.repository = repository;
}
@Override
public CompletionStage<Map<String, Integer>> initialState() {
return CompletableFuture.completedFuture(new HashMap<>());
}
@Override
public CompletionStage<Map<String, Integer>> process(
Map<String, Integer> state, WordEnvelope envelope) {
String word = envelope.word;
CompletionStage<Integer> currentCount;
if (state.containsKey(word))
currentCount = CompletableFuture.completedFuture(state.get(word));
else currentCount = repository.load(projectionId.id(), word);
CompletionStage<Map<String, Integer>> newState =
currentCount.thenCompose(
n -> {
return repository
.save(projectionId.id(), word, n + 1)
.thenApply(
done -> {
state.put(word, n + 1);
return state;
});
});
return newState;
}
}
// #loadingOnDemand
}
interface IllstrateActorLoadingInitialState {
// #actorHandler
class WordCountActorHandler extends ActorHandler<WordEnvelope, WordCountProcessor.Command> {
private final ActorSystem<?> system;
private final Duration askTimeout = Duration.ofSeconds(5);
WordCountActorHandler(Behavior<WordCountProcessor.Command> behavior, ActorSystem<?> system) {
super(behavior);
this.system = system;
}
@Override
public CompletionStage<Done> process(
ActorRef<WordCountProcessor.Command> actor, WordEnvelope envelope) {
CompletionStage<WordCountProcessor.Result> result =
AskPattern.ask(
actor,
(ActorRef<WordCountProcessor.Result> replyTo) ->
new WordCountProcessor.Handle(envelope, replyTo),
askTimeout,
system.scheduler());
return result.thenCompose(
r -> {
if (r.error.isPresent()) {
CompletableFuture<Done> err = new CompletableFuture<>();
err.completeExceptionally(r.error.get());
return err;
} else {
return CompletableFuture.completedFuture(Done.getInstance());
}
});
}
}
// #actorHandler
// #behaviorLoadingInitialState
public class WordCountProcessor {
public interface Command {}
public static class Handle implements Command {
public final WordEnvelope envelope;
public final ActorRef<Result> replyTo;
public Handle(WordEnvelope envelope, ActorRef<Result> replyTo) {
this.envelope = envelope;
this.replyTo = replyTo;
}
}
public static class Result {
public final Optional<Throwable> error;
public Result(Optional<Throwable> error) {
this.error = error;
}
}
private static class InitialState implements Command {
final Map<String, Integer> state;
private InitialState(Map<String, Integer> state) {
this.state = state;
}
}
private static class SaveCompleted implements Command {
final String word;
final Optional<Throwable> error;
final ActorRef<Result> replyTo;
private SaveCompleted(String word, Optional<Throwable> error, ActorRef<Result> replyTo) {
this.word = word;
this.error = error;
this.replyTo = replyTo;
}
}
public static Behavior<Command> create(
ProjectionId projectionId, WordCountRepository repository) {
return Behaviors.supervise(
Behaviors.setup(
(ActorContext<Command> context) ->
new WordCountProcessor(projectionId, repository).init(context)))
.onFailure(
SupervisorStrategy.restartWithBackoff(
Duration.ofSeconds(1), Duration.ofSeconds(10), 0.1));
}
private final ProjectionId projectionId;
private final WordCountRepository repository;
private WordCountProcessor(ProjectionId projectionId, WordCountRepository repository) {
this.projectionId = projectionId;
this.repository = repository;
}
Behavior<Command> init(ActorContext<Command> context) {
return Behaviors.withStash(10, buffer -> new Initializing(context, buffer));
}
private class Initializing extends AbstractBehavior<Command> {
private final StashBuffer<Command> buffer;
private Initializing(ActorContext<Command> context, StashBuffer<Command> buffer) {
super(context);
this.buffer = buffer;
getContext()
.pipeToSelf(
repository.loadAll(projectionId.id()),
(value, exc) -> {
if (value != null) return new InitialState(value);
else throw new RuntimeException("Load failed.", exc);
});
}
@Override
public Receive<Command> createReceive() {
return newReceiveBuilder()
.onMessage(InitialState.class, this::onInitalState)
.onAnyMessage(this::onOther)
.build();
}
private Behavior<Command> onInitalState(InitialState initialState) {
getContext().getLog().debug("Initial state [{}]", initialState.state);
return buffer.unstashAll(new Active(getContext(), initialState.state));
}
private Behavior<Command> onOther(Command command) {
getContext().getLog().debug("Stashed [{}]", command);
buffer.stash(command);
return this;
}
}
private class Active extends AbstractBehavior<Command> {
private final Map<String, Integer> state;
public Active(ActorContext<Command> context, Map<String, Integer> state) {
super(context);
this.state = state;
}
@Override
public Receive<Command> createReceive() {
return newReceiveBuilder()
.onMessage(Handle.class, this::onHandle)
.onMessage(SaveCompleted.class, this::onSaveCompleted)
.build();
}
private Behavior<Command> onHandle(Handle command) {
String word = command.envelope.word;
int newCount = state.getOrDefault(word, 0) + 1;
getContext()
.pipeToSelf(
repository.save(projectionId.id(), word, newCount),
(done, exc) ->
// will reply from SaveCompleted
new SaveCompleted(word, Optional.ofNullable(exc), command.replyTo));
return this;
}
private Behavior<Command> onSaveCompleted(SaveCompleted completed) {
completed.replyTo.tell(new Result(completed.error));
if (completed.error.isPresent()) {
// restart, reload state from db
throw new RuntimeException("Save failed.", completed.error.get());
} else {
String word = completed.word;
int newCount = state.getOrDefault(word, 0) + 1;
state.put(word, newCount);
}
return this;
}
}
}
// #behaviorLoadingInitialState
}
interface IllstrateActorLoadingStateOnDemand {
class WordCountActorHandler extends ActorHandler<WordEnvelope, WordCountProcessor.Command> {
private final ActorSystem<?> system;
private final Duration askTimeout = Duration.ofSeconds(5);
WordCountActorHandler(Behavior<WordCountProcessor.Command> behavior, ActorSystem<?> system) {
super(behavior);
this.system = system;
}
@Override
public CompletionStage<Done> process(
ActorRef<WordCountProcessor.Command> actor, WordEnvelope envelope) {
CompletionStage<WordCountProcessor.Result> result =
AskPattern.ask(
actor,
(ActorRef<WordCountProcessor.Result> replyTo) ->
new WordCountProcessor.Handle(envelope, replyTo),
askTimeout,
system.scheduler());
return result.thenCompose(
r -> {
if (r.error.isPresent()) {
CompletableFuture<Done> err = new CompletableFuture<>();
err.completeExceptionally(r.error.get());
return err;
} else {
return CompletableFuture.completedFuture(Done.getInstance());
}
});
}
}
// #behaviorLoadingOnDemand
public class WordCountProcessor extends AbstractBehavior<WordCountProcessor.Command> {
public interface Command {}
public static class Handle implements Command {
public final WordEnvelope envelope;
public final ActorRef<Result> replyTo;
public Handle(WordEnvelope envelope, ActorRef<Result> replyTo) {
this.envelope = envelope;
this.replyTo = replyTo;
}
}
public static class Result {
public final Optional<Throwable> error;
public Result(Optional<Throwable> error) {
this.error = error;
}
}
private static class LoadCompleted implements Command {
final String word;
final Optional<Throwable> error;
final ActorRef<Result> replyTo;
private LoadCompleted(String word, Optional<Throwable> error, ActorRef<Result> replyTo) {
this.word = word;
this.error = error;
this.replyTo = replyTo;
}
}
private static class SaveCompleted implements Command {
final String word;
final Optional<Throwable> error;
final ActorRef<Result> replyTo;
private SaveCompleted(String word, Optional<Throwable> error, ActorRef<Result> replyTo) {
this.word = word;
this.error = error;
this.replyTo = replyTo;
}
}
public static Behavior<Command> create(
ProjectionId projectionId, WordCountRepository repository) {
return Behaviors.supervise(
Behaviors.setup(
(ActorContext<Command> context) ->
new WordCountProcessor(context, projectionId, repository)))
.onFailure(
SupervisorStrategy.restartWithBackoff(
Duration.ofSeconds(1), Duration.ofSeconds(10), 0.1));
}
private final ProjectionId projectionId;
private final WordCountRepository repository;
private final Map<String, Integer> state = new HashMap<>();
private WordCountProcessor(
ActorContext<Command> context,
ProjectionId projectionId,
WordCountRepository repository) {
super(context);
this.projectionId = projectionId;
this.repository = repository;
}
@Override
public Receive<Command> createReceive() {
return newReceiveBuilder()
.onMessage(Handle.class, this::onHandle)
.onMessage(LoadCompleted.class, this::onLoadCompleted)
.onMessage(SaveCompleted.class, this::onSaveCompleted)
.build();
}
private Behavior<Command> onHandle(Handle command) {
String word = command.envelope.word;
if (state.containsKey(word)) {
int newCount = state.get(word) + 1;
getContext()
.pipeToSelf(
repository.save(projectionId.id(), word, newCount),
(done, exc) ->
// will reply from SaveCompleted
new SaveCompleted(word, Optional.ofNullable(exc), command.replyTo));
} else {
getContext()
.pipeToSelf(
repository.load(projectionId.id(), word),
(loadResult, exc) ->
// will reply from LoadCompleted
new LoadCompleted(word, Optional.ofNullable(exc), command.replyTo));
}
return this;
}
private Behavior<Command> onLoadCompleted(LoadCompleted completed) {
if (completed.error.isPresent()) {
completed.replyTo.tell(new Result(completed.error));
} else {
String word = completed.word;
int newCount = state.getOrDefault(word, 0) + 1;
getContext()
.pipeToSelf(
repository.save(projectionId.id(), word, newCount),
(done, exc) ->
// will reply from SaveCompleted
new SaveCompleted(word, Optional.ofNullable(exc), completed.replyTo));
}
return this;
}
private Behavior<Command> onSaveCompleted(SaveCompleted completed) {
completed.replyTo.tell(new Result(completed.error));
if (completed.error.isPresent()) {
// remove the word from the state if the save failed, because it could have been a timeout
// so that it was actually saved, best to reload
state.remove(completed.word);
} else {
String word = completed.word;
int newCount = state.getOrDefault(word, 0) + 1;
state.put(word, newCount);
}
return this;
}
}
}
// #behaviorLoadingOnDemand
}
| 20,797 | 0.603933 | 0.601721 | 620 | 32.543549 | 25.839199 | 100 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.564516 | false | false | 13 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.