blob_id
stringlengths
40
40
language
stringclasses
1 value
repo_name
stringlengths
5
132
path
stringlengths
2
382
src_encoding
stringclasses
34 values
length_bytes
int64
9
3.8M
score
float64
1.5
4.94
int_score
int64
2
5
detected_licenses
listlengths
0
142
license_type
stringclasses
2 values
text
stringlengths
9
3.8M
download_success
bool
1 class
6772705cc89bade93d10158052fe86ed556e0e5c
Java
JasleenDhillon/Java-Bootcamp
/BinaryTreeClient.java
UTF-8
1,191
2.65625
3
[]
no_license
package lecture22ndApril; public class BinaryTreeClient { public static void main(String[] args) { // 50 true 25 true 12 false false true 37 true 30 false false true 40 false false true 75 true 62 true 60 false false true 70 false false true 87 false false BinaryTree bt = new BinaryTree(); bt.display(); System.out.println(bt.max()); System.out.println(bt.height()); System.out.println(bt.find(62)); System.out.println(bt.size2()); /* bt.preorder(); bt.postorder(); bt.inorder(); bt.preorderIterative(); bt.levelorder(); */ /* int[] pre = { 50, 25, 12, 37, 30, 40, 75, 62, 60, 70, 87 }; int[] in = { 12, 25, 30, 37, 40, 50, 60, 62, 70, 75, 87 }; int[] post = { 12, 30, 40, 37, 25, 60, 70, 62, 87, 75, 50 }; BinaryTree b = new BinaryTree(pre, post); b.display(); */ System.out.println(bt.diameter()); System.out.println(bt.diameter2()); System.out.println(bt.Isbalanced()); System.out.println(bt.IsBST()); System.out.println(bt.IsBST2()); System.out.println("------------------"); // bt.levelOrderline(); // bt.levelorederZigzag(); bt.multiSolver(65); } }
true
31bbbe5086e86c7fc8ea18a6d2a87556afa4c65e
Java
Danemora23/Producto-Clase9
/productos-api/src/main/java/com/example/demo/controllers/ProductController.java
UTF-8
2,486
2.359375
2
[]
no_license
package com.example.demo.controllers; import java.util.Collection; import java.util.Optional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; import com.example.demo.entitys.Producto; import com.example.demo.repository.ProductRepository; @RestController @RequestMapping(value = "/productos") public class ProductController { @Autowired ProductRepository repository; @GetMapping @ResponseStatus(code = HttpStatus.OK) public Collection<Producto> getListaProductos(){ Iterable<Producto> listaProductos = repository.findAll(); return (Collection<Producto>) listaProductos; } @GetMapping(value = "/{id}") @ResponseStatus(code = HttpStatus.OK) public Producto getProducto(@PathVariable(name = "id") Long id) { Optional<Producto> producto = repository.findById(id); Producto result = null; if(producto.isPresent()) { result = producto.get(); } return result; } @PostMapping @ResponseStatus(code = HttpStatus.CREATED) public Producto createProducto(@RequestBody Producto producto) { Producto nuevoProducto = repository.save(producto); return nuevoProducto; } @DeleteMapping(value = "/{id}") @ResponseStatus(code = HttpStatus.ACCEPTED) public void deleteProducto(@PathVariable(name = "id") Long id) { repository.deleteById(id); } @PutMapping(value = "/{id}") @ResponseStatus(code = HttpStatus.ACCEPTED) public Producto updateProduct(@PathVariable(name="id") Long id, @RequestBody Producto producto) { Optional<Producto> oProducto = repository.findById(id); if(oProducto.isPresent()) { Producto actual = oProducto.get(); actual.setId(id); actual.setName(producto.getName()); actual.setPreci(producto.getPreci()); Producto updatedProduct = repository.save(actual); return updatedProduct; } return null; } }
true
780fb81f0f183af47d979c72f9a9bffd2ab947ad
Java
wasd003/OS_Course_Project
/电梯调度/Elevator/src/elevator/Controller.java
UTF-8
7,905
2.53125
3
[ "MIT" ]
permissive
package elevator; import com.jfoenix.controls.JFXButton; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.fxml.FXML; import javafx.scene.control.*; import javafx.scene.layout.StackPane; import javafx.scene.media.AudioClip; import elevator.Const.Command; import elevator.Const.FXColor; import java.nio.file.Paths; import java.util.*; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class Controller { @FXML private StackPane root; @FXML private ToggleGroup toggleGroup; private List<JFXButton> innerButton = new ArrayList<>(); private List<Slider> sliderList = new ArrayList<>(); private List<JFXButton> outerDisplayButton = new ArrayList<>(); private List<JFXButton> outerFloorUpButton = new ArrayList<>(); private List<JFXButton> outerFloorDownButton = new ArrayList<>(); private JFXButton innerFloorDisplayButton; private JFXButton innerUpDisplayButton; private JFXButton innerDownDisplayButton; private JFXButton openDoorButton; private JFXButton closeDoorButton; private JFXButton alarmButton; private List<Elevator> elevatorList = new ArrayList<>(); private Queue<FloorButton> outerTaskQueue = new LinkedList<FloorButton>(); public int currentElevatorId; private ExecutorService service = Executors.newCachedThreadPool(); public void init(){ initChooseElevator(); initInnerElevator(); initOuterElevator(); initDisplayElevator(); //创建五部电梯并开始运行 for(int i = 1;i<=5;i++){ Elevator elevator = new Elevator(i, sliderList.get(i-1), outerDisplayButton.get(i-1),innerFloorDisplayButton, innerUpDisplayButton, innerDownDisplayButton,this); elevatorList.add(elevator); service.execute(elevator); } //创建外部调度算法的线程并开始运行 Schedule schedule = new Schedule(outerTaskQueue,this); service.execute(schedule); currentElevatorId = 1; } private void initChooseElevator() { toggleGroup.selectedToggleProperty().addListener(new ChangeListener<Toggle>(){ @Override public void changed(ObservableValue<? extends Toggle> changed, Toggle oldVal, Toggle newVal) { RadioButton temp_rb=(RadioButton)newVal; currentElevatorId = Integer.valueOf(temp_rb.getText().split(" ")[1]); System.out.println("当前运行的电梯id是:" + currentElevatorId); resetInnerButton(); } }); } public List<Elevator> getElevatorList() { return elevatorList; } private void initInnerElevator() { //初始化功能键 openDoorButton = (JFXButton) root.lookup("#open-door"); openDoorButton.setOnAction(action->{ elevatorList.get(currentElevatorId - 1).openDoor(); }); closeDoorButton = (JFXButton) root.lookup("#close-door"); closeDoorButton.setOnAction(action->{ elevatorList.get(currentElevatorId - 1).closeDoor(); }); alarmButton = (JFXButton) root.lookup("#alarm"); alarmButton.setOnAction(action->{ AudioClip audioClip = new AudioClip(Paths.get("src/resource/alarm.wav").toUri().toString()); audioClip.play(); }); //初始化电梯状态展示的三个按钮 innerFloorDisplayButton = (JFXButton) root.lookup("#floor_display"); innerFloorDisplayButton.setText("1"); innerUpDisplayButton = (JFXButton) root.lookup("#up-display"); innerDownDisplayButton = (JFXButton) root.lookup("#down-display"); //初始化电梯内部20个按键 for(int i =1;i <= 20;i++){ JFXButton button = (JFXButton) root.lookup("#e"+ i); button.setOnAction(action->{ button.setDisable(true); int floor = Integer.valueOf(button.getText()); button.setStyle(FXColor.YELLOW); elevatorList.get(currentElevatorId -1).addInnerTask(floor); }); innerButton.add(button); } } private void initOuterElevator() { //上行按钮(从1楼到19楼) for(int i = 1;i<20;i++){ JFXButton button = (JFXButton) root.lookup(String.format("#L%d-up",i)); button.setOnAction(action->{ //外部上行按钮的监听事件,改变颜色并设置为不可用,避免多次添加同一任务,将该外部任务添加到调度队列中 button.setStyle(FXColor.YELLOW); button.setDisable(true); int floor = getFloorFromId(button.getId()); outerTaskQueue.offer(new FloorButton(floor, Command.UP)); }); outerFloorUpButton.add(button); } //下行按钮(从2楼到20楼) for(int i = 2;i<=20;i++){ JFXButton button = (JFXButton) root.lookup(String.format("#L%d-down",i)); button.setOnAction(action->{ //外部下行按钮的监听事件,改变颜色并设置为不可用,避免多次添加同一任务,将该外部任务添加到调度队列中 button.setStyle(FXColor.YELLOW); button.setDisable(true); int floor = getFloorFromId(button.getId()); outerTaskQueue.offer(new FloorButton(floor, Command.DOWN)); }); outerFloorDownButton.add(button); } } private void initDisplayElevator() { for (int i = 1; i <=5; i++){ Slider slider = (Slider) root.lookup(String.format("#e%d-slider",i)); slider.setValue(1); sliderList.add(slider); JFXButton button = (JFXButton) root.lookup(String.format("#e%d-display",i)); button.setText("1-"); outerDisplayButton.add(button); } } private int getFloorFromId(String id){ return Integer.valueOf(id.split("L")[1].split("-")[0]); } //当切换电梯时重置电梯内部的按钮状态 private void resetInnerButton() { Elevator elevator = elevatorList.get(currentElevatorId - 1); //按钮恢复默认状态 for (Button button : innerButton) { button.setStyle(FXColor.GREY); button.setDisable(false); } innerUpDisplayButton.setStyle(FXColor.GREY); innerDownDisplayButton.setStyle(FXColor.GREY); //访问当前电梯的按钮状态map及状态,设置按钮 Iterator iter = elevator.getInnerButtonState().entrySet().iterator(); while (iter.hasNext()) { Map.Entry entry = (Map.Entry) iter.next(); int key = (int) entry.getKey(); innerButton.get(key-1).setDisable(true); innerButton.get(key-1).setStyle(FXColor.YELLOW); } innerFloorDisplayButton.setText(String.valueOf(elevator.getCurrentFloor())); int status = elevator.getStatus(); if(status == 1){ innerUpDisplayButton.setStyle(FXColor.YELLOW); }else if(status == 2){ innerDownDisplayButton.setStyle(FXColor.YELLOW); } } public void setInnerButtonStyle(int id, int floor, String style){ if(currentElevatorId == id){ JFXButton button = innerButton.get(floor-1); button.setStyle(style); button.setDisable(false); } } public void removeOuterButton(int current_floor, int status) { JFXButton button; if(status == Command.UP){ button = outerFloorUpButton.get(current_floor - 1); }else{ button = outerFloorDownButton.get(current_floor - 2); } button.setStyle(FXColor.GREY); button.setDisable(false); } }
true
d624349ae2fdc883d7cd49f0cae6e05ef7712d83
Java
connierearden/spring-mvc1609
/2.2.2. spring_mvc/src/main/java/web/dao/CarDao.java
UTF-8
149
1.90625
2
[]
no_license
package web.dao; import web.model.Car; import java.util.List; public interface CarDao { void add (Car car); List listCarsByCriteria (); }
true
d0d8d8dd4cdc7e9b74117bdc3ad93a9c9f1078bb
Java
Chee285/CodeReview
/homework/stroe/vo/User.java
UTF-8
106
1.507813
2
[]
no_license
package vo; public class User { private String id; private String pwd; private int balance; }
true
d3a27da5cefea2247e1eff80a52a3969388866ca
Java
tr00per/javaintro
/src/main/java/sda/code/intermediate/part1/exercises/patterns/ItemBuilder.java
UTF-8
532
2.703125
3
[]
no_license
package sda.code.intermediate.part1.exercises.patterns; import sda.code.intermediate.part1.exercises.data.Item; /** * @see ProductBuilder */ public class ItemBuilder extends ProductBuilder<ItemBuilder, Item> { private Double weight; public ItemBuilder withWeight(Double weight) { throw new UnsupportedOperationException("Not implemented yet"); } @Override public Item build() { prepare(); validate(); throw new UnsupportedOperationException("Not implemented yet"); } }
true
6e98ecc989d5548d0cf2ffd60ac4589a48d713cb
Java
mahaiyi2/mhyUtils
/src/main/java/excelWord/excel/transformer/FormatTest.java
UTF-8
3,053
2.390625
2
[]
no_license
package excelWord.excel.transformer; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import com.sun.media.sound.InvalidFormatException; //import net.sf.jxls.transformer.XLSTransformer; public class FormatTest { public static void applicationExport() throws Exception { String templateFileName = "C:\\Users\\Administrator\\Desktop\\jx2.xlsx"; String destFileName = "C:\\Users\\Administrator\\Desktop\\jx2OO.xlsx"; Map<String, Object> beanParams = new HashMap<String, Object>(); beanParams.put("pd", ""); beanParams.put("ccpd", "ddd"); beanParams.put("fgpd", new ArrayList<>()); beanParams.put("fgpdsize", null); beanParams.put("gtpd", new ArrayList<>()); beanParams.put("gtpdsize", ""); beanParams.put("name", "0000"); InputStream in = null; OutputStream out = null; // 设置响应 // response.setHeader("Content-Disposition", "attachment;filename=" // + URLEncoder.encode(destFileName, "UTF-8")); // response.setContentType("application/vnd.ms-excel"); try { InputStream is = new FileInputStream(templateFileName); // XLSTransformer transformer = new XLSTransformer(); // XSSFWorkbook workBook = (XSSFWorkbook) transformer.transformXLS(is, // beanParams); /*HSSFWorkbook workBook = (HSSFWorkbook) transformer.transformXLS(is, beanParams);*/ // 将图片以字节流的方式输入输出 // XSSFSheet sheet = workBook.getSheetAt(0); // String picture = "C:/Users/Administrator/Desktop/appewm2.png"; // ByteArrayOutputStream bos = new ByteArrayOutputStream(); // BufferedImage BufferImg = ImageIO.read(new File(picture)); // ImageIO.write(BufferImg, "png", bos); // public HSSFClientAnchor(int dx1,int dy1,int dx2,int dy2,short // col1,int row1,short col2,int row2) // XSSFClientAnchor anchor = new // XSSFClientAnchor(0,0,0,0,(short)10,10,(short)20,50); // XSSFDrawing patriarch = sheet.createDrawingPatriarch(); // patriarch.createPicture(anchor, // workBook.addPicture(bos.toByteArray(), // workBook.PICTURE_TYPE_JPEG)); // OutputStream os = new FileOutputStream(destPath); // in=new BufferedInputStream(new // FileInputStream(templateFileName)); // Workbook workbook=transformer.transformXLS(in, beans); // out = response.getOutputStream(); out = new FileOutputStream(destFileName); // 将内容写入输出流并把缓存的内容全部发出去 // workBook.write(out); out.flush(); } catch (InvalidFormatException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (in != null) { try { in.close(); } catch (IOException e) { } } if (out != null) { try { out.close(); } catch (IOException e) { } } } } public static void main(String[] args) throws Exception { applicationExport(); } }
true
5108d260bff7947f35ffb8791b7a9219b6aee94e
Java
mobpshyco98/online-ayurveda
/OnlineAyurveda/src/test/java/com/cg/TestCart/TestEditCartItems.java
UTF-8
1,331
2.1875
2
[]
no_license
package com.cg.TestCart; import static org.junit.jupiter.api.Assertions.*; import static org.mockito.Mockito.*; import java.util.Optional; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.mockito.InjectMocks; import org.mockito.Mock; import org.springframework.boot.test.context.SpringBootTest; import com.cg.oam.dao.ICartDao; import com.cg.oam.entities.Cart; import com.cg.oam.exceptions.CartIdInvalidException; import com.cg.oam.service.CartServiceImpl; import com.cg.oam.service.ICartService; @SpringBootTest public class TestEditCartItems { @Mock private ICartDao cartdao; @InjectMocks private ICartService service = new CartServiceImpl(); @BeforeEach public void beforeEach() { Optional<Cart> optcart1 = Optional.of(new Cart()); Optional<Cart> optcart2 = Optional.empty(); when(cartdao.findById(1020)).thenReturn(optcart1); when(cartdao.findById(6873)).thenReturn(optcart2); } @Test @DisplayName(value = "testing edit method for id 1020") public void edittest1() throws CartIdInvalidException { assertNotNull(service.qtyEdit(1020, 51)); } @Test @DisplayName(value = "testing edit method for id 6873") public void edittest2() { assertThrows(CartIdInvalidException.class, () -> service.qtyEdit(6873, 75)); } }
true
080b66fde7263aeb51590bf63a54a2f1555af654
Java
tanghaijian/itmp
/common/src/main/java/cn/pioneeruniverse/common/utils/PageWithBootStrap.java
UTF-8
842
2.609375
3
[]
no_license
package cn.pioneeruniverse.common.utils; import java.util.Map; /** * Description: bootstrap table 分页公共写法 * Author:liushan * Date: 2019/1/2 上午 10:10 */ public class PageWithBootStrap { /** *@author liushan *@Description bootstrap分页规则 *@Date 2020/7/29 *@Param [map, pageNumber, pageSize] *@return java.util.Map<java.lang.String,java.lang.Object> **/ public static Map<String,Object> setPageNumberSize(Map<String, Object> map, Integer pageNumber, Integer pageSize){ if (pageNumber != null && pageSize != null){ int start = (pageNumber - 1) * pageSize; map.put("start", start); map.put("pageSize", pageSize); } else { map.put("start", null); map.put("pageSize", null); } return map; } }
true
4a7ce32606100c7a8bdaf3b7f04e6d453b5919dc
Java
sebastienvial/DPF
/Decorateur.java
UTF-8
91
1.75
2
[]
no_license
public abstract class Decorateur extends Contenu { protected Contenu contenu; }
true
faad4e070ecbc49b000b3383953cd64952ed59b8
Java
aagnone3/CDC_Obesity_Management_CC
/app/src/main/java/edu/gatech/johndoe/carecoordinator/care_plan/UI/CarePlanDetailFragment.java
UTF-8
21,608
1.921875
2
[]
no_license
package edu.gatech.johndoe.carecoordinator.care_plan.UI; import android.app.Dialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.res.Resources; import android.location.Address; import android.location.Geocoder; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentActivity; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.support.v7.app.AlertDialog; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.RadioButton; import android.widget.RadioGroup; import android.widget.TextView; import android.widget.Toast; import com.firebase.client.Firebase; import com.google.gson.Gson; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import edu.gatech.johndoe.carecoordinator.ContentListFragment; import edu.gatech.johndoe.carecoordinator.MainActivity; import edu.gatech.johndoe.carecoordinator.OnFragmentInteractionListener; import edu.gatech.johndoe.carecoordinator.R; import edu.gatech.johndoe.carecoordinator.care_plan.CarePlan; import edu.gatech.johndoe.carecoordinator.community.Community; import edu.gatech.johndoe.carecoordinator.patient.*; import edu.gatech.johndoe.carecoordinator.patient.UI.InnerCarePlanAdapter; import edu.gatech.johndoe.carecoordinator.patient.UI.PatientDetailFragment; import edu.gatech.johndoe.carecoordinator.patient.email.FinalReferralEmail; import edu.gatech.johndoe.carecoordinator.patient.email.PatientEmail; import edu.gatech.johndoe.carecoordinator.patient.email.PatientEmailFactory; import edu.gatech.johndoe.carecoordinator.util.OnLatLongUpdateListener; import edu.gatech.johndoe.carecoordinator.util.Utility; public class CarePlanDetailFragment extends Fragment { // private static final String ARG_REFERRAL = "carePlan"; private CarePlan carePlan; private OnFragmentInteractionListener mListener; private String patientConditionText; private Patient patient; private Map<String, ArrayList<String>> suggestedCommunitiesMap = new HashMap<>(); private ArrayList<String> suggestedCommunities = new ArrayList<>(); private RadioButton firstR, secondR, thirdR, forthR, fifthR; private ArrayList<String> communityList = new ArrayList<String>(); private ArrayList<String> communityListIDs = new ArrayList<String>(); /** * * @param carePlan carePlan. * @return A new instance of fragment CommunityDetailFragment. */ public static CarePlanDetailFragment newInstance(CarePlan carePlan) { CarePlanDetailFragment fragment = new CarePlanDetailFragment(); Bundle args = new Bundle(); args.putString(ARG_REFERRAL, new Gson().toJson(carePlan)); fragment.setArguments(args); return fragment; } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); if (savedInstanceState != null) { if (carePlan == null) { carePlan = new Gson().fromJson(savedInstanceState.getString("carePlan"), CarePlan.class); } } } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (getArguments() != null) { carePlan = new Gson().fromJson(getArguments().getString(ARG_REFERRAL), CarePlan.class); } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_care_plan_detail, container, false); // Attach an listener to read the data at our posts reference Utility.getAllPatients(); for (Patient pat: Utility.patient_list) { if (pat.getId().equals(carePlan.getPatientID())) { patient = pat; } } View.OnClickListener patientClickListener = new View.OnClickListener() { public void onClick(View v) { Fragment detailFragment = PatientDetailFragment.newInstance(patient, Utility.getAllRelatedReferrals(patient.getReferralList())); FragmentManager fragmentManager = ((FragmentActivity) v.getContext()).getSupportFragmentManager(); FragmentTransaction transaction = fragmentManager.beginTransaction(); if (MainActivity.isInExpandedMode) { //noinspection ResourceType transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE); transaction.replace(R.id.detailFragmentContainer, detailFragment, "detail").addToBackStack(null); } else { transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN); transaction.add(R.id.contentContainer, detailFragment, "detail").addToBackStack(null); } transaction.commit(); } }; Integer resourceCount = 0; Integer loopCount = 0; Set<Double> keys = patient.getDistanceSortedCommunities().keySet(); String carePlanType = "NONE"; String workingCarePlan = "NONE"; Geocoder coder = new Geocoder(getActivity()); List<Address> address; try { address = coder.getFromLocationName(patient.getFullAddress(),1); if (address==null) { return null; } Address location=address.get(0); location.getLatitude(); location.getLongitude(); patient.setLatitude(location.getLatitude()); patient.setLongitude(location.getLongitude()); Utility.sortCommunitiesByDistance(patient); } catch (Exception e) { } // if (patient.getReferralList() != null) { for (String carePlanID : patient.getReferralList()) { if (!carePlanType.equals("NONE")) break; for (CarePlan carePlan : Utility.carePlan_list) { if (carePlan.getId().equals(carePlanID)) { if (carePlan.getStatus().equals("OPENED")) { carePlanType = carePlan.getType(); workingCarePlan = carePlan.getId(); } } } } } if (!carePlanType.equals("NONE")) { for (Object key : keys) { Log.e("key", key.toString()); if (loopCount >= patient.getDistanceSortedCommunities().size() || resourceCount >= 5) break; Object o = patient.getDistanceSortedCommunities().get(key); for (Community community : Utility.community_list) { if (community.getId().equals(o.toString())) { if (carePlanType.equals("Diet Plan") && community.getCommunityType().equals("nutritionist")) { suggestedCommunities.add(community.getId()); resourceCount++; loopCount++; } else if (carePlanType.equals("Exercise Plan") && community.getCommunityType().equals("physical")) { suggestedCommunities.add(community.getId()); resourceCount++; loopCount++; } else { loopCount++; } break; } } } if (!patient.getSuggestedCommunities().containsKey(workingCarePlan)) { patient.addSuggestedCommunities(workingCarePlan, suggestedCommunities); } } suggestedCommunitiesMap = patient.getSuggestedCommunities(); communityList = new ArrayList<String>(); if (!suggestedCommunitiesMap.keySet().isEmpty()) { // System.out.println("keyset " + suggestedCommunitiesMap.keySet()); String b = ""; for (String a : suggestedCommunitiesMap.keySet()) { b = a; } ArrayList<String> c = suggestedCommunitiesMap.get(b); for (String a : c) { for (Community com : Utility.community_list) { if (a.equals(com.getId())) { communityList.add(com.getName()); communityListIDs.add(com.getId()); // System.out.println("Suggested name " + com.getName()); } } } } TextView physician_name_short = (TextView) view.findViewById(R.id.care_plan_physician_name); TextView patient_name_short = (TextView) view.findViewById(R.id.care_plan_patient_name); TextView patient_name = (TextView) view.findViewById(R.id.patient_name2); TextView patient_condition = (TextView) view.findViewById(R.id.care_plan_condition); TextView physician_name = (TextView) view.findViewById(R.id.physician_name); TextView type = (TextView) view.findViewById(R.id.care_plan_type); TextView details = (TextView) view.findViewById(R.id.care_plan_detail); TextView care_plan_goal = (TextView) view.findViewById(R.id.care_plan_goal); TextView period = (TextView) view.findViewById(R.id.care_plan_period); // Set images int imageId = getResources().getIdentifier(patient.getImageName(), "drawable", getActivity().getPackageName()); ImageView image = (ImageView) view.findViewById(R.id.image_patient); image.setImageResource(imageId); image.setOnClickListener(patientClickListener); imageId = getResources().getIdentifier(carePlan.getPhysicianImageName(), "drawable", getActivity().getPackageName()); image = (ImageView) view.findViewById(R.id.image_physician); image.setImageResource(imageId); RecyclerView list = (RecyclerView) view.findViewById(R.id.community_suggestion_list); // type.setText(carePlan.getType()); details.setText(carePlan.getDetail()); patient_name.setOnClickListener(patientClickListener); if (carePlan.getStatus().equals("UNOPENED")) { System.out.println(carePlan.getStatus() + " and " + carePlan.getId() + " is updated"); for (CarePlan cp : Utility.carePlan_list) { if (cp.getId().equals(carePlan.getId())) { Firebase ref = new Firebase("https://cdccoordinator2.firebaseio.com/care_plans"); Firebase alanRef = ref.child(carePlan.getId()); cp.setStatus("OPENED"); Map<String, Object> cp2 = new HashMap<String, Object>(); alanRef.updateChildren(cp2); cp2.put("status", "OPENED"); alanRef.updateChildren(cp2); } } } else if (carePlan.getStatus().equals("OPENED")){ System.out.println(carePlan.getStatus()+ " and " + carePlan.getId()); } else if (carePlan.getStatus().equals("ACTIVE")) { System.out.println(carePlan.getStatus()+ " and " + carePlan.getId()); } else { System.out.println(carePlan.getStatus()+ " and " + carePlan.getId()); } if (patient == null) { patient_name.setText("Dummy"); patient_condition.setText("N/A"); physician_name.setText("N/A"); care_plan_goal.setText("N/A"); physician_name_short.setText("Dr. Who"); physician_name_short.setText("Patient Who"); period.setText("N/A"); } else { Resources res = getResources(); // Condition that the care plan addresses patient_condition.setText(formPatientConditionText()); // Physician name String physicianName = carePlan.getPhysicianName(); String physicianNameShort = physicianName.substring(physicianName.indexOf(',') + 2); physician_name.setText(physicianName); physician_name_short.setText(String.format(res.getString(R.string.care_plan_physician_name), physicianNameShort)); // Patient name String patientName = carePlan.getPatientName(); patient_name.setText(patientName); patient_name_short.setText(patientName.substring(patientName.indexOf(',') + 2)); // Goal of the care plan String care_plan_goal_text = String.format(res.getString(R.string.care_plan_goal_text), carePlan.getGoalType(), carePlan.getGoalValue()); care_plan_goal.setText(care_plan_goal_text); period.setText(carePlan.getPeriod()); } Button completedButton = (Button) view.findViewById(R.id.button_completed); Button erefButton = (Button) view.findViewById(R.id.buttonereferral); completedButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (patient != null && carePlan.getStatus().equals("ACTIVE")) { if (carePlan.getStatus().equals("COMPLETED")){ Toast.makeText(getActivity().getApplicationContext(), "The care plan is already completed.", Toast.LENGTH_SHORT).show(); } else { System.out.println("CarePlan ID " + carePlan.getId()); for (CarePlan cp : Utility.carePlan_list) { if (cp.getId().equals(carePlan.getId())) { Firebase ref = new Firebase("https://cdccoordinator2.firebaseio.com/care_plans"); Firebase alanRef = ref.child(carePlan.getId()); cp.setStatus("COMPLETED"); Map<String, Object> cp2 = new HashMap<String, Object>(); alanRef.updateChildren(cp2); cp2.put("status", "COMPLETED"); alanRef.updateChildren(cp2); //Utility.closeCarePlan(cp); // System.out.println("Updated"); } } ContentListFragment contentListFragment = (ContentListFragment) getActivity().getSupportFragmentManager().findFragmentById(R.id.contentListFragment); contentListFragment.getAdapter().notifyDataSetChanged(); } } else { Toast.makeText(getActivity().getApplicationContext(), "Email the Patient First", Toast.LENGTH_SHORT).show(); } } }); erefButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { showPopUp(); } }); if (communityList.size() < 1) { communityList.add("No Suggested Community"); } list.setLayoutManager(new LinearLayoutManager(getContext())); list.setAdapter(new InnerCommunityAdapter(communityList, getActivity().getSupportFragmentManager())); list.setHasFixedSize(true); list.setVisibility(View.VISIBLE); ContentListFragment contentListFragment = (ContentListFragment) getActivity().getSupportFragmentManager().findFragmentById(R.id.contentListFragment); contentListFragment.getAdapter().notifyDataSetChanged(); return view; } @Override public void onAttach(Context context) { super.onAttach(context); if (context instanceof OnFragmentInteractionListener) { mListener = (OnFragmentInteractionListener) context; } else { throw new RuntimeException(context.toString() + " must implement OnFragmentInteractionListener"); } } @Override public void onDetach() { super.onDetach(); mListener = null; } private String formPatientConditionText() { StringBuilder text = new StringBuilder(); text.append(carePlan.getConditionSystem()) .append(" - ") .append(carePlan.getConditionCode()); return text.toString(); } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putString("carePlan", new Gson().toJson(carePlan)); } private final void showPopUp() { final Dialog dialog = new Dialog(getActivity()); dialog.setTitle("Woo"); dialog.setContentView(R.layout.pop_up); List<String> stringList=new ArrayList<>(); // here is list for(int i=0;i<communityList.size();i++) { stringList.add(communityList.get(i)); } if (!communityList.get(0).equals("No Suggested Community")) { RadioGroup rg = (RadioGroup) dialog.findViewById(R.id.radio_group); for(int i=0;i<stringList.size();i++){ RadioButton rb=new RadioButton(getActivity()); // dynamically creating RadioButton and adding to RadioGroup. rb.setText(stringList.get(i)); rg.addView(rb); } dialog.show(); rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup group, int checkedId) { // int childCount = group.getChildCount(); int childCount = communityList.size(); for (int x = 0; x < childCount; x++) { RadioButton btn = (RadioButton) group.getChildAt(x); if (btn.getId() == checkedId) { Log.e("selected RadioButton->",btn.getText().toString()); try { // activate the final referral email for (Community community : Utility.community_list){ if (community.getId().equals(communityListIDs.get(btn.getId()-1))){ patient.setWorkingCommunity(community); try { for (CarePlan cp : Utility.carePlan_list) { if (cp.getId().equals(carePlan.getId())) { Utility.activateCarePlan(cp); Firebase ref = new Firebase("https://cdccoordinator2.firebaseio.com/care_plans"); Firebase alanRef = ref.child(carePlan.getId()); cp.setStatus("ACTIVE"); Map<String, Object> cp2 = new HashMap<String, Object>(); alanRef.updateChildren(cp2); cp2.put("status", "ACTIVE"); alanRef.updateChildren(cp2); } } ContentListFragment contentListFragment = (ContentListFragment) getActivity().getSupportFragmentManager().findFragmentById(R.id.contentListFragment); contentListFragment.getAdapter().notifyDataSetChanged(); PatientEmail email = new FinalReferralEmail(patient, community, carePlan); startActivity(Intent.createChooser(email.getEmailIntent(), "Send mail...")); Log.i("Finished email...", ""); } catch (android.content.ActivityNotFoundException ex) { Toast.makeText(getActivity().getApplicationContext(), "There is no email client installed.", Toast.LENGTH_SHORT).show(); } } } // Toast.makeText(getActivity().getApplicationContext(), "final referral" + btn.getText(), Toast.LENGTH_LONG); } catch (android.content.ActivityNotFoundException ex) { Toast.makeText(getActivity().getApplicationContext(), "There is no email client installed.", Toast.LENGTH_SHORT).show(); } } } } }); } else { Toast.makeText(getActivity().getApplicationContext(), "No Suggested Community", Toast.LENGTH_SHORT).show(); } } }
true
160e0b1283493d8fc681fbedf0bd52734e4ded89
Java
DmitriyLy/multithreading
/src/main/java/org/dmly/concurrent_utils/countdownlatch/CountDownLatchApp.java
UTF-8
620
3.21875
3
[]
no_license
package org.dmly.concurrent_utils.countdownlatch; import java.util.concurrent.CountDownLatch; public class CountDownLatchApp { public static void main(String[] args) { CountDownLatch latch = new CountDownLatch(5); System.out.println("Starting"); new Thread(() -> { for (int i = 0; i < 5; i++) { System.out.println(i); latch.countDown(); } }).start(); try { latch.await(); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("Done"); } }
true
02e698898e1dd19ce67b2b3076260b1b2896557f
Java
IssacYoung2013/daily
/02_spring_primary/src/main/java/com/issac/spring/postprocessor/util/BeanPostProcessor.java
UTF-8
394
1.898438
2
[]
no_license
package com.issac.spring.postprocessor.util; /** * @author: ywy * @date: 2019-10-26 * @desc: */ public interface BeanPostProcessor { default Object postProcessBeforeInitialization(Object bean, String beanName) throws Exception { return bean; } default Object postProcessAfterInitialization(Object bean, String beanName) throws Exception { return bean; } }
true
0b2145e118c332294b06fba7bac06edee5005bd4
Java
cavz11397/Spring-boot-udemy
/SpringBoot/demo/src/main/java/com/example/demo/controllers/ControllerSubstraction.java
UTF-8
600
2.59375
3
[]
no_license
package com.example.demo.controllers; import com.example.demo.services.CalculatorService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; public class ControllerSubstraction { @Autowired private CalculatorService calculatorService; public ControllerSubstraction(){ System.out.println("creando ControllerSubstraction"); } @GetMapping("/restar") public String restar(){ int numA = 5; int numB = 6; return ("la resta es: "+calculatorService.resta(numA,numB)); } }
true
d58e87505521d21551f47e7fad6b5351db5c97be
Java
CPPAlien/Shuyou
/src/com/shuyou/ConfigActivity.java
UTF-8
2,808
2.09375
2
[]
no_license
package com.shuyou; import com.umeng.analytics.MobclickAgent; import com.umeng.fb.FeedbackAgent; import com.umeng.update.UmengUpdateAgent; import com.umeng.update.UmengUpdateListener; import com.umeng.update.UpdateResponse; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Toast; public class ConfigActivity extends Activity implements OnClickListener { private FeedbackAgent agent; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_config); findViewById(R.id.config_feedback).setOnClickListener(this); findViewById(R.id.config_checkUpdate).setOnClickListener(this); findViewById(R.id.config_about).setOnClickListener(this); findViewById(R.id.config_back).setOnClickListener(this); agent = new FeedbackAgent(this); agent.sync();// 服务器反馈获取 UmengUpdateAgent.setUpdateAutoPopup(false); UmengUpdateAgent.setUpdateOnlyWifi(false); UmengUpdateAgent.setUpdateListener(new UmengUpdateListener() { @Override public void onUpdateReturned(int updateStatus, UpdateResponse updateInfo) { // TODO Auto-generated method stub switch (updateStatus) { case 0: // has update UmengUpdateAgent.showUpdateDialog(ConfigActivity.this, updateInfo); break; case 1: // has no update Toast.makeText(ConfigActivity.this, "没有更新", Toast.LENGTH_SHORT).show(); break; case 2: // none wifi Toast.makeText(ConfigActivity.this, "没有wifi连接, 只在wifi下更新", Toast.LENGTH_SHORT) .show(); break; case 3: // time out Toast.makeText(ConfigActivity.this, "检查更新超时,请检查网络", Toast.LENGTH_SHORT).show(); break; } } }); } @Override protected void onPause() { super.onPause(); MobclickAgent.onPause(this); } @Override protected void onResume() { super.onResume(); MobclickAgent.onResume(this); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.config_feedback: agent.startFeedbackActivity();// 友盟反馈界面 break; case R.id.config_checkUpdate: UmengUpdateAgent.forceUpdate(this); break; case R.id.config_about: startActivity(new Intent(ConfigActivity.this, AboutActivity.class)); break; case R.id.config_back: finish(); break; default: break; } } }
true
c8294ebc069a6d804980330317e66febe17663e8
Java
justomiguel/testMobile
/Ingeniero 2.0 (mail)/Ingeniero 2.0/src/com/jmv/frre/moduloestudiante/activities/sysacad/LinkActivity.java
UTF-8
6,313
1.875
2
[ "Apache-2.0", "BSD-3-Clause" ]
permissive
package com.jmv.frre.moduloestudiante.activities.sysacad; import android.animation.Animator; import android.animation.AnimatorListenerAdapter; import android.annotation.TargetApi; import android.app.Activity; import android.app.Dialog; import android.content.Context; import android.os.Build; import android.os.Bundle; import android.view.View; import android.widget.TextView; import com.google.common.base.Function; import com.jmv.frre.moduloestudiante.AdsActivity; import com.jmv.frre.moduloestudiante.R; import com.jmv.frre.moduloestudiante.dialogs.ConfirmationDialog; import com.jmv.frre.moduloestudiante.net.HTMLParser; import com.jmv.frre.moduloestudiante.net.HTTPScraper; import com.swacorp.oncallpager.MainActivity; /** * Created by Cleo on 12/10/13. */ public class LinkActivity extends AdsActivity{ public static final String CONTEXT = "context"; public static final String LINK_EXTRA = "link_extra"; protected static final int DIALOG_SHOW_ERROR = 0; protected static final int DIALOG_SHOW_ERROR_SYSACAD_NO_ANDA = 8; protected static final int DIALOG_SHOW_INFO = 1; protected static final int DIALOG_SHOW_ABOUT = 5; protected static final int DIALOG_SHOW_DETAILS_EXAM = 2; protected static final int DIALOG_SHOW_INSCRIBIRSE_EXAM = 3; protected static final int DIALOG_SHOW_INSCRIBIRSE_CONFIRM = 4; protected static final int DIALOG_SHOW_DELETE_CONFIRM = 7; protected static final int DIALOG_SHOW_DELETE_EXAM = 6; protected static final int DIALOG_SHOW_DELETE_EXAM_EMPTY = 9; protected View mHomeFormView; protected View mLoginStatusView; protected TextView mHomeStatusMessageView; protected HTTPScraper scraper; protected String currentError; protected Function<Activity,String> getRequest; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); scraper = new HTTPScraper(); } /** * Shows the progress UI and hides the login form. */ @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2) protected void showProgress(final boolean show) { // On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow // for very easy animations. If available, use these APIs to fade-in // the progress spinner. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) { int shortAnimTime = getResources().getInteger(android.R.integer.config_shortAnimTime); mLoginStatusView.setVisibility(View.VISIBLE); mHomeFormView.setVisibility(View.GONE); mLoginStatusView.animate() .setDuration(shortAnimTime) .alpha(show ? 1 : 0) .setListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { mLoginStatusView.setVisibility(show ? View.VISIBLE : View.GONE); mHomeFormView.setVisibility(show ? View.GONE : View.VISIBLE); } }); } else { // The ViewPropertyAnimator APIs are not available, so simply show // and hide the relevant UI components. mLoginStatusView.setVisibility(show ? View.VISIBLE : View.GONE); mHomeFormView.setVisibility(show ? View.GONE : View.VISIBLE); } } @Override public Dialog onCreateDialog(int id) { switch (id) { case DIALOG_SHOW_ERROR_SYSACAD_NO_ANDA: return ConfirmationDialog.create(this, id, R.string.dialog_tittle_label, currentError, R.string.dialog_confirm_response_has_errors_button, new Runnable() { @Override public void run() { MainActivity.showHome(LinkActivity.this); } }); case DIALOG_SHOW_ERROR: return ConfirmationDialog.create(this, id, R.string.dialog_tittle_label, currentError, R.string.dialog_confirm_response_has_errors_button, new Runnable() { @Override public void run() { //MainActivity.showHome(LinkActivity.this); } }); case DIALOG_SHOW_INFO: return ConfirmationDialog.create(this, id, R.string.dialog_tittle_label, getString(R.string.dialog_confirm_nothing_to_show), R.string.dialog_confirm_response_info_button, new Runnable() { @Override public void run() { } }); case DIALOG_SHOW_ABOUT: return ConfirmationDialog.create(this, id, R.string.dialog_tittle_label_about, getString(R.string.dialog_about_details), R.string.dialog_confirm_response_info_button, new Runnable() { @Override public void run() { } }); } return super.onCreateDialog(id); } protected Function<Activity, String> makeGetRequest(final String link) { return new Function<Activity, String>() { @Override public String apply(Activity context) { String response = scraper.fecthHtmlGet(link); return response; } }; } protected boolean checkForErrors(HTMLParser parser, String response, Context parent) { if (response == null || response.length() == 0|| parser.containsError()) { currentError = response == null || response.length() == 0 ? "Empty Response" : parser.getError(); showDialog(DIALOG_SHOW_ERROR); return true; } else if (response.equalsIgnoreCase(HTTPScraper.MAINTENANCE_MODE_ON)){ MaintenanceMode.showHome(parent); return true; } return false; } }
true
f48ca5740fb01780c592c4f55fb71f54887ae729
Java
Mustang-ssc/ANXMiuiCamera10
/src/ANXCamera/sources/com/bumptech/glide/load/resource/gif/b.java
UTF-8
7,075
1.78125
2
[]
no_license
package com.bumptech.glide.load.resource.gif; import android.content.Context; import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.ColorFilter; import android.graphics.Paint; import android.graphics.Rect; import android.graphics.drawable.Animatable; import android.graphics.drawable.Drawable; import android.graphics.drawable.Drawable.Callback; import android.graphics.drawable.Drawable.ConstantState; import android.support.annotation.NonNull; import android.support.annotation.VisibleForTesting; import android.view.Gravity; import com.bumptech.glide.c; import com.bumptech.glide.load.engine.bitmap_recycle.d; import com.bumptech.glide.load.i; import java.nio.ByteBuffer; /* compiled from: GifDrawable */ public class b extends Drawable implements Animatable, com.bumptech.glide.load.resource.gif.GifFrameLoader.a { public static final int lA = -1; public static final int lB = 0; private static final int lC = 119; private boolean fZ; private boolean isRunning; private final a lD; private boolean lE; private boolean lF; private int lG; private boolean lH; private Rect lI; private int loopCount; private Paint paint; /* compiled from: GifDrawable */ static final class a extends ConstantState { @VisibleForTesting final GifFrameLoader frameLoader; a(GifFrameLoader gifFrameLoader) { this.frameLoader = gifFrameLoader; } @NonNull public Drawable newDrawable(Resources resources) { return newDrawable(); } @NonNull public Drawable newDrawable() { return new b(this); } public int getChangingConfigurations() { return 0; } } @Deprecated public b(Context context, com.bumptech.glide.b.a aVar, d dVar, i<Bitmap> iVar, int i, int i2, Bitmap bitmap) { this(context, aVar, iVar, i, i2, bitmap); } public b(Context context, com.bumptech.glide.b.a aVar, i<Bitmap> iVar, int i, int i2, Bitmap bitmap) { this(new a(new GifFrameLoader(c.b(context), aVar, i, i2, iVar, bitmap))); } b(a aVar) { this.lF = true; this.lG = -1; this.lD = (a) com.bumptech.glide.util.i.checkNotNull(aVar); } @VisibleForTesting b(GifFrameLoader gifFrameLoader, Paint paint) { this(new a(gifFrameLoader)); this.paint = paint; } public int getSize() { return this.lD.frameLoader.getSize(); } public Bitmap cA() { return this.lD.frameLoader.cA(); } public void a(i<Bitmap> iVar, Bitmap bitmap) { this.lD.frameLoader.a(iVar, bitmap); } public i<Bitmap> cB() { return this.lD.frameLoader.cB(); } public ByteBuffer getBuffer() { return this.lD.frameLoader.getBuffer(); } public int getFrameCount() { return this.lD.frameLoader.getFrameCount(); } public int cC() { return this.lD.frameLoader.getCurrentIndex(); } private void cD() { this.loopCount = 0; } public void cE() { com.bumptech.glide.util.i.a(this.isRunning ^ 1, "You cannot restart a currently running animation."); this.lD.frameLoader.cM(); start(); } public void start() { this.lE = true; cD(); if (this.lF) { cF(); } } public void stop() { this.lE = false; stopRunning(); } private void cF() { com.bumptech.glide.util.i.a(this.fZ ^ true, "You cannot start a recycled Drawable. Ensure thatyou clear any references to the Drawable when clearing the corresponding request."); if (this.lD.frameLoader.getFrameCount() == 1) { invalidateSelf(); } else if (!this.isRunning) { this.isRunning = true; this.lD.frameLoader.a(this); invalidateSelf(); } } private void stopRunning() { this.isRunning = false; this.lD.frameLoader.b(this); } public boolean setVisible(boolean z, boolean z2) { com.bumptech.glide.util.i.a(this.fZ ^ 1, "Cannot change the visibility of a recycled resource. Ensure that you unset the Drawable from your View before changing the View's visibility."); this.lF = z; if (!z) { stopRunning(); } else if (this.lE) { cF(); } return super.setVisible(z, z2); } public int getIntrinsicWidth() { return this.lD.frameLoader.getWidth(); } public int getIntrinsicHeight() { return this.lD.frameLoader.getHeight(); } public boolean isRunning() { return this.isRunning; } void f(boolean z) { this.isRunning = z; } protected void onBoundsChange(Rect rect) { super.onBoundsChange(rect); this.lH = true; } public void draw(@NonNull Canvas canvas) { if (!this.fZ) { if (this.lH) { Gravity.apply(119, getIntrinsicWidth(), getIntrinsicHeight(), getBounds(), cG()); this.lH = false; } canvas.drawBitmap(this.lD.frameLoader.cJ(), null, cG(), getPaint()); } } public void setAlpha(int i) { getPaint().setAlpha(i); } public void setColorFilter(ColorFilter colorFilter) { getPaint().setColorFilter(colorFilter); } private Rect cG() { if (this.lI == null) { this.lI = new Rect(); } return this.lI; } private Paint getPaint() { if (this.paint == null) { this.paint = new Paint(2); } return this.paint; } public int getOpacity() { return -2; } private Callback cH() { Callback callback = getCallback(); while (callback instanceof Drawable) { callback = ((Drawable) callback).getCallback(); } return callback; } public void cI() { if (cH() == null) { stop(); invalidateSelf(); return; } invalidateSelf(); if (cC() == getFrameCount() - 1) { this.loopCount++; } if (this.lG != -1 && this.loopCount >= this.lG) { stop(); } } public ConstantState getConstantState() { return this.lD; } public void recycle() { this.fZ = true; this.lD.frameLoader.clear(); } boolean isRecycled() { return this.fZ; } public void setLoopCount(int i) { if (i <= 0 && i != -1 && i != 0) { throw new IllegalArgumentException("Loop count must be greater than 0, or equal to GlideDrawable.LOOP_FOREVER, or equal to GlideDrawable.LOOP_INTRINSIC"); } else if (i == 0) { i = this.lD.frameLoader.getLoopCount(); if (i == 0) { i = -1; } this.lG = i; } else { this.lG = i; } } }
true
7dd7bebbf03762a0384ff1b71002ede1f665c7d0
Java
penghuiping/common
/ws/src/main/java/com/php25/common/ws/core/RetryMsgManager.java
UTF-8
2,721
2.265625
2
[]
no_license
package com.php25.common.ws.core; import com.php25.common.core.mess.SpringContextHolder; import com.php25.common.core.util.JsonUtil; import com.php25.common.ws.protocal.BaseMsg; import com.php25.common.ws.retry.DefaultRetryQueue; import com.php25.common.ws.retry.RejectAction; import com.php25.common.ws.retry.RetryQueue; import lombok.extern.log4j.Log4j2; import org.jetbrains.annotations.NotNull; import org.springframework.beans.factory.InitializingBean; import org.springframework.context.ApplicationListener; import org.springframework.context.event.ContextClosedEvent; /** * 消息重发器,此类用于实现延时消息重发 * 对于服务端push消息,客户端需要回ack,如果服务端没有收到客户端回的ack的消息,则服务端需要重发 * 服务端默认5秒没收到ack消息,进行原消息重发 * 最大重发次数为5次 * * @author penghuiping * @date 2021/8/26 15:56 */ @Log4j2 public class RetryMsgManager implements InitializingBean, ApplicationListener<ContextClosedEvent> { private final RetryQueue<BaseMsg> retryQueue; private SessionContext globalSession; public RetryMsgManager() { this.retryQueue = new DefaultRetryQueue<>(5, 5000L, retryMsg -> { //重试逻辑 ExpirationSocketSession expirationSocketSession = this.getGlobalSession().getExpirationSocketSession(retryMsg.getSessionId()); if (null != expirationSocketSession) { expirationSocketSession.put(retryMsg); } }, retryMsg -> { //重试超过5次拒绝逻辑 log.warn("此消息重试超过五次依旧失败:{}", JsonUtil.toJson(retryMsg)); }); } public SessionContext getGlobalSession() { if (this.globalSession == null) { this.globalSession = SpringContextHolder.getBean0(SessionContext.class); } return globalSession; } @Override public void onApplicationEvent(@NotNull ContextClosedEvent contextClosedEvent) { } @Override public void afterPropertiesSet() throws Exception { } public void put(BaseMsg baseMsg) { this.put(baseMsg, null); } public void put(BaseMsg baseMsg, RejectAction<BaseMsg> rejectAction) { //需要重试 retryQueue.offer(baseMsg.getMsgId(), baseMsg, rejectAction); } public void remove(String msgId) { retryQueue.remove(msgId); } public BaseMsg get(String msgId) { return retryQueue.get(msgId); } public void stats() { log.info("InnerMsgRetryQueue msgs:{}", retryQueue.size()); } }
true
2b4a7a9652a0ef7f3f63c4b0d5b84889f4fa10f6
Java
ReganIu/Bullet-Freedom
/SuperBar.java
UTF-8
852
3.125
3
[]
no_license
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) import java.awt.Color; /** * This actor constantly updates to * show the charging of the special ability. * * Jonah Reeves, Cody Chiu, Regan Iu * January 18/ 2018 */ public class SuperBar extends Actor { /** * Shows the charging process for the special ability * used by the Player class. Flashes green when the * special ability is ready to be used, and cyan otherwise. */ public void act() { MyWorld w = (MyWorld) getWorld(); GreenfootImage image = new GreenfootImage(10, ((w.getSuperCharge()) * 10) + 1); if (w.getSuperCharge() > 19) image.setColor(Color.GREEN); else image.setColor(Color.CYAN); image.fill(); setImage(image); } }
true
1ec77d0366f895a29c92ec2b4e2419a8c5475ae3
Java
timboudreau/netbeans-contrib
/fileopenserver/src/main/java/org/netbeans/modules/fileopenserver/FileOpenServerSettings.java
UTF-8
5,585
1.617188
2
[ "Apache-2.0" ]
permissive
/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): * * The Original Software is NetBeans. The Initial Developer of the Original * Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun * Microsystems, Inc. All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. */ package org.netbeans.modules.fileopenserver; import java.util.prefs.Preferences; import org.openide.util.NbPreferences; /** * * @author Sandip Chitale (Sandip.Chitale@Sun.Com) */ public class FileOpenServerSettings { private static Preferences preferences; private static FileOpenServerSettings fileOpenServerSettings; /** Creates a new instance of FileOpenServerOptions */ private FileOpenServerSettings() { } // Default instance of this system option, for the convenience of associated classes. public static FileOpenServerSettings getInstance() { if (fileOpenServerSettings == null) { fileOpenServerSettings = new FileOpenServerSettings(); } return fileOpenServerSettings; } private static Preferences getPreferences() { if (preferences == null) { preferences = NbPreferences.forModule(FileOpenServerSettings.class); } return preferences; } public int getPortNumber() { return getPreferences().getInt(FileOpenServerConstants.PROPERTY_PORT_NUMBER, FileOpenServerConstants.PROPERTY_PORT_NUMBER_DEFAULT_VALUE); } public void setPortNumber(int portNumber) { getPreferences().putInt(FileOpenServerConstants.PROPERTY_PORT_NUMBER, portNumber); } public boolean isStartAtStartup() { return getPreferences().getBoolean(FileOpenServerConstants.PROPERTY_START_AT_STARTUP, FileOpenServerConstants.PROPERTY_START_AT_STARTUP_DEFAULT_VALUE); } public void setStartAtStartup(boolean startAtStartup) { getPreferences().putBoolean(FileOpenServerConstants.PROPERTY_START_AT_STARTUP, startAtStartup); } public boolean isLogRequests() { return getPreferences().getBoolean(FileOpenServerConstants.PROPERTY_LOG_REQUESTS, FileOpenServerConstants.PROPERTY_LOG_REQUESTS_DEFAULT_VALUE); } public void setLogRequests(boolean logRequests) { getPreferences().putBoolean(FileOpenServerConstants.PROPERTY_LOG_REQUESTS, logRequests); } public String getExternalEditorCommand() { return getPreferences().get(FileOpenServerConstants.PROPERTY_EXTERNAL_EDITOR_COMMAND, FileOpenServerConstants.PROPERTY_EXTERNAL_EDITOR_COMMAND_DEFAULT_VALUE); } public void setExternalEditorCommand(String externalEditorCommand) { getPreferences().put(FileOpenServerConstants.PROPERTY_EXTERNAL_EDITOR_COMMAND, externalEditorCommand); } public boolean isLineNumberStartsWith0() { return getPreferences().getBoolean(FileOpenServerConstants.PROPERTY_LINE_NUMBER_STARTS_WITH_0, FileOpenServerConstants.PROPERTY_LINE_NUMBER_STARTS_WITH_0_DEFAULT_VALUE); } public void setLineNumberStartsWith0(boolean lineNumberStartsWith1) { getPreferences().putBoolean(FileOpenServerConstants.PROPERTY_LINE_NUMBER_STARTS_WITH_0, lineNumberStartsWith1); } public boolean isColumnNumberStartsWith0() { return getPreferences().getBoolean(FileOpenServerConstants.PROPERTY_COLUMN_NUMBER_STARTS_WITH_0, FileOpenServerConstants.PROPERTY_COLUMN_NUMBER_STARTS_WITH_0_DEFAULT_VALUE); } public void setColumnNumberStartsWith0(boolean columnNumberStartsWith1) { getPreferences().putBoolean(FileOpenServerConstants.PROPERTY_COLUMN_NUMBER_STARTS_WITH_0, columnNumberStartsWith1); } }
true
1f04c820a57ac582a93bda1de27b738d358cb5f0
Java
maslke/spring-cloud-in-action
/chapter4/organization-service/src/main/java/com/maslke/spring/demos/organizationservice/services/OrganizationService.java
UTF-8
1,597
2.390625
2
[]
no_license
package com.maslke.spring.demos.organizationservice.services; import com.maslke.spring.demos.organizationservice.event.source.SimpleSourceBean; import com.maslke.spring.demos.organizationservice.model.Organization; import com.maslke.spring.demos.organizationservice.repository.OrganizationRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.UUID; @Service public class OrganizationService { private OrganizationRepository organizationRepository; private SimpleSourceBean simpleSourceBean; @Autowired public OrganizationService(OrganizationRepository organizationRepository, SimpleSourceBean simpleSourceBean) { this.organizationRepository = organizationRepository; this.simpleSourceBean = simpleSourceBean; } public Organization getOrg(String organizationId) { return organizationRepository.findByOrganizationId(organizationId); } public void saveOrg(Organization org) { org.setOrganizationId(UUID.randomUUID().toString()); organizationRepository.save(org); this.simpleSourceBean.publishOrgChange("SAVE", org.getOrganizationId()); } public void updateOrg(Organization org) { organizationRepository.save(org); this.simpleSourceBean.publishOrgChange("UPDATE", org.getOrganizationId()); } public void deleteOrg(Organization org) { organizationRepository.deleteById(org.getOrganizationId()); this.simpleSourceBean.publishOrgChange("DELETE", org.getOrganizationId()); } }
true
da3c63ef1f96c0b934f8d7cf030a43acdbf11351
Java
SziFeng/library
/library/chuanshuke/csk-framework-parent/csk-service-ucenter/src/main/java/com/chuanshuke/ucenter/controller/UserController.java
UTF-8
1,226
2
2
[]
no_license
package com.chuanshuke.ucenter.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import com.chuanshuke.api.ucenter.UserControllerApi; import com.chuanshuke.framework.domain.ucenter.TbUser; import com.chuanshuke.framework.domain.ucenter.response.UcenterResult; import com.chuanshuke.framework.model.response.ResponseResult; import com.chuanshuke.ucenter.service.TbUserService; @RestController @RequestMapping("/ucenter") public class UserController implements UserControllerApi { @Autowired private TbUserService tbUserService; @GetMapping("/getuser") @Override public UcenterResult getUser(@RequestParam("username")String username) { return tbUserService.findByUsername(username); } @PostMapping("/register") public ResponseResult insertUser(@RequestBody TbUser user) { return tbUserService.insert(user); } }
true
f5d0adeac23ab88d0328d5cb1b9f240a8bed9eae
Java
mijail79/CampusMapperGamified
/src/de/ifgi/sitcom/campusmappergamified/player/Player.java
UTF-8
2,917
2.3125
2
[]
no_license
package de.ifgi.sitcom.campusmappergamified.player; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; import android.accounts.Account; import android.accounts.AccountManager; import android.util.Log; import de.ifgi.sitcom.campusmappergamified.activities.MyCampusMapperGame; import de.ifgi.sitcom.campusmappergamified.exceptions.UploadException; import de.ifgi.sitcom.campusmappergamified.io.RDFUpload; public class Player { public String name; public String email; public String username; public String registrationDate; public String badge = "beginner"; public Player(String playerUsername) { this.setName("playername"); this.setEmail("playeremail"); this.setUsername(playerUsername); this.setBadge("beginner"); this.setRegistrationDate(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ", Locale.ENGLISH).format(new Date())); } public String registerUser() { String RDFRegisterInsert; RDFUpload upload = new RDFUpload(); final AccountManager manager = AccountManager.get(MyCampusMapperGame .getContext()); final Account[] accounts = manager.getAccountsByType("com.google"); if (accounts[0].name != null) { registrationDate = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ", Locale.ENGLISH).format(new Date()); setEmail(accounts[0].name); Log.v(" Got contacts", "Username: " + username + " Email : " + email + "date:" + registrationDate + "badge: " + badge); RDFRegisterInsert = "<indoor:"+this.getEmail()+"> rdf:type prv:Player . "+ "<indoor:"+this.getEmail()+"> foaf:nick '" + this.getUsername() + "' . "+ "<indoor:"+this.getEmail()+"> foaf:mbox '" + this.getEmail() + "' . "+ "<indoor:"+this.getEmail()+"> indoor:hasRegistrationDate '" + this.getRegistrationDate() + "'^^xsd:dateTime . " + "<indoor:"+this.getEmail()+"> indoor:hasTotalPlayerScore '" + MyCampusMapperGame.getInstance().getMyScore().toString() +"'^^xsd:integer . "+ "<indoor:"+this.getEmail()+"> indoor:hasPersonBadge '"+this.getBadge()+ "' . "; try { upload.uploadRDF(RDFRegisterInsert); } catch (UploadException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return email; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getBadge() { return badge; } public void setBadge(String badge) { this.badge = badge; } public String getRegistrationDate() { return registrationDate; } public void setRegistrationDate(String registrationDate) { this.registrationDate = registrationDate; } }
true
d48a32a19ec19b5fb3002c1ad8f5c0600bbc16f4
Java
svn2github/RefactorIT
/refactorit-core/src/test/misc/jacks/jls/blocks-and-statements/try-statement/T1419s8.java
UTF-8
277
1.648438
2
[]
no_license
public class T1419s8 { public static void main(String[] args) { try { throw new Exception(); } catch (NullPointerException e) { } catch (RuntimeException e) { } catch (Throwable e) { } } }
true
525741941f10370f3ce5cebbe98801f69415c84a
Java
iXxXlink/db
/dbkeshe/src/main/java/com/dbtest/dbkeshe/repository/UserRepository.java
UTF-8
241
2.078125
2
[]
no_license
package com.dbtest.dbkeshe.repository; import com.dbtest.dbkeshe.entity.User; public interface UserRepository { public void register(User user); public User findByName(String username); public User check(User user); }
true
2dc30eb3f8d8eba866f70ef0de336670966fac35
Java
mooreford95/portfolio
/Data Structures/Project_3/src/CommandHandler.java
UTF-8
2,170
3.671875
4
[]
no_license
import java.util.HashMap; /** * Wrapper class that handles the command input by calling Graph.java methods. * * @author Thomas Ortiz * @author Michael Mackrell * @author Jacob Stone * @author Curtis Moore */ public class CommandHandler { /** graph that holds all vertices */ private Graph graph; /** hashGraph to quickly link a name with a vertex object */ private HashMap<String, Vertex> hashGraph; /** * Constructor for the command handler class. * @param graph that holds all vertices * @param hashGraph to quickly link a name with a vertex object */ public CommandHandler(Graph graph, HashMap<String, Vertex> hashGraph) { this.graph = graph; this.hashGraph = hashGraph; } /** * This method handles isfriend input by calling Graph.java's isFriend method. * * @param name1 the name of the first person * @param name2 the name of the second person */ public void isFriend(String name1, String name2){ if( graph.isFriend(hashGraph.get(name1), hashGraph.get(name2)) ){ System.out.println("yes"); } else { System.out.println("no"); } } /** * This method handles mutual input by calling Graph.java's mutual method. * * @param name1 the name of the first person * @param name2 the name of the second person */ public void mutual(String name1, String name2){ System.out.print( graph.mutual(hashGraph.get(name1), hashGraph.get(name2)) ); } /** * This method handles relation input by calling Graph.java's relation method. * * @param name1 the name of the first person * @param name2 the name of the second person */ public void relation(String name1, String name2){ System.out.print( graph.relation(hashGraph.get(name1), hashGraph.get(name2)) ); graph.unmark(); } /** * This method handles notconnected input by calling Graph.java's notConnected method. */ public void notConnected(){ System.out.println( graph.getNotConnected() ); graph.unmark(); } /** * This method handles popular input by calling Graph.java's popular method. */ public void popular(){ System.out.print( graph.getPopular() ); } }
true
40afcd28aa42a76184f2bb583e54176720757f7a
Java
hmirandadeveloper/hsm-dental-system-java-ee
/sodonto-system-back-end/ejbModule/persistencia/dao/PacienteDAO.java
ISO-8859-1
3,197
2.71875
3
[]
no_license
package persistencia.dao; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.ejb.Stateless; import persistencia.generics.GenericDAO; import entidade.Paciente; @Stateless public class PacienteDAO extends GenericDAO<Paciente>{ public PacienteDAO() { super(Paciente.class); } public void remover(Paciente entidade) { System.out.println("[SODONTO SYSTEM][2.0.00][DAO] Instanciando paciente DAO..."); super.remover(entidade.getIdPaciente(), Paciente.class); System.out.println("[SODONTO SYSTEM][2.0.00][DAO] Instancia Concluda!"); } public List<Paciente> buscarPorDentista(Long idDentista) { Map<String, Object> parametros = new HashMap<String, Object>(); parametros.put("idDentista", idDentista); return buscarResultadosFiltrados(Paciente.NQ_BUSCAR_POR_DENTISTA, parametros); } public long buscarUltimoID() { return (long)buscarContagemResultado(Paciente.NQ_BUSCAR_ULTIMO_ID, null); } public List<Paciente> buscarPorNome(String nome, int limite) { Map<String, Object> parametros = new HashMap<String, Object>(); parametros.put("nome", nome); return buscarResultadosFiltrados(Paciente.NQ_BUSCAR_POR_NOME, parametros, limite); } public List<Paciente> buscarTitularPorNome(String nome, int limite) { Map<String, Object> parametros = new HashMap<String, Object>(); parametros.put("nome", nome); return buscarResultadosFiltrados(Paciente.NQ_BUSCAR_TITULAR_POR_NOME, parametros, limite); } public Paciente buscarTitularPorId(Long idPaciente) { Map<String, Object> parametros = new HashMap<String, Object>(); parametros.put("idPaciente", idPaciente); return buscarUmResultado(Paciente.NQ_BUSCAR_TITULAR_POR_ID, parametros); } public List<Paciente> buscarPorCpfOuRg(String cpf, String rg, int limite) { Map<String, Object> parametros = new HashMap<String, Object>(); parametros.put("cpf", cpf); parametros.put("rg", rg); return buscarResultadosFiltrados(Paciente.NQ_BUSCAR_POR_CPF_OU_RG, parametros, limite); } public List<Paciente> buscarTitularPorCpfOuRg(String cpf, String rg, int limite) { Map<String, Object> parametros = new HashMap<String, Object>(); parametros.put("cpf", cpf); parametros.put("rg", rg); return buscarResultadosFiltrados(Paciente.NQ_BUSCAR_TITULAR_POR_CPF_OU_RG, parametros, limite); } public List<Paciente> buscarPorPR(Long idPaciente) { Map<String, Object> parametros = new HashMap<String, Object>(); parametros.put("idPaciente", idPaciente); return buscarResultadosFiltrados(Paciente.NQ_BUSCAR_POR_PR, parametros); } public List<Paciente> buscarPorCondicao(boolean condicao, int limite) { Map<String, Object> parametros = new HashMap<String, Object>(); parametros.put("condicao", condicao); return buscarResultadosFiltrados(Paciente.NQ_BUSCAR_POR_CONDICAO, parametros, limite); } public List<Paciente> buscarTitularPorCondicao(boolean condicao, int limite) { Map<String, Object> parametros = new HashMap<String, Object>(); parametros.put("condicao", condicao); return buscarResultadosFiltrados(Paciente.NQ_BUSCAR_TITULAR_POR_CONDICAO, parametros, limite); } }
true
da79f3f974dd31881cdd6ee064ec24cac34dffe4
Java
ikucuze/gedcom
/src/main/java/fr/ikucuze/gedcom/structure/subrecord/EventDetail.java
UTF-8
839
1.796875
2
[]
no_license
package fr.ikucuze.gedcom.structure.subrecord; import java.util.List; import fr.ikucuze.gedcom.structure.GedcomObject; import fr.ikucuze.gedcom.structure.annotation.GedcomField; import fr.ikucuze.gedcom.structure.primitive.DateValue; public class EventDetail extends GedcomObject { @GedcomField(name="TYPE") public String type; @GedcomField(name="DATE") public DateValue date; @GedcomField public PlaceStructure place; @GedcomField public AddressStructure address; @GedcomField(name="AGNC") public String responsibleAgency; @GedcomField(name="RELI") public String religiousAffiliation; @GedcomField(name="CAUS") public String cause; @GedcomField public List<NoteStructure> notes; @GedcomField public List<SourceCitation> sources; @GedcomField public List<MultimediaLink> multimedias; }
true
819606ec2321eeb43eef846db5d45422a12c0b63
Java
chenleicpp/FragmentBase
/app/src/main/java/com/sanshisoft/fragmentbase/Utils/CommenUtils.java
UTF-8
1,698
2.390625
2
[]
no_license
package com.sanshisoft.fragmentbase.Utils; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; /** * Created by chenleicpp on 2015/5/5. */ public class CommenUtils { public static String TAG = "FragmentBase"; public static String ACTION_REPORT = "action_report"; public static String ACTION_DISPLAY = "action_display"; public static void exit(final Context context) { AlertDialog.Builder builder = new AlertDialog.Builder(context) .setTitle("warning!") .setMessage("make sure to exit") .setNegativeButton("cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }) .setPositiveButton("ok", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { AppManager.getAppManager().AppExit(context); } }); builder.create().show(); } public static boolean isBlank(CharSequence cs) { int strLen; if (cs == null || (strLen = cs.length()) == 0 || cs.equals("null")) { return true; } for (int i = 0; i < strLen; i++) { if (Character.isWhitespace(cs.charAt(i)) == false) { return false; } } return true; } public static boolean isNotBlank(CharSequence cs) { return !CommenUtils.isBlank(cs); } }
true
8bc826a06f4b6f7b1b60e7dec194791b244ee1a9
Java
Kapiton42/nuts-and-bolts
/nuts-and-bolts/src/main/java/ru/hh/nab/hibernate/Transactional.java
UTF-8
1,489
2.328125
2
[]
no_license
package ru.hh.nab.hibernate; import java.lang.annotation.Annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Retention(RetentionPolicy.RUNTIME) @Target({ ElementType.METHOD, ElementType.TYPE, ElementType.CONSTRUCTOR }) public @interface Transactional { // readonly attribute is not enforced at the moment because doing that would // require closing of readonly transaction and creating a new readwrite // transaction. However, it is better to specify it anyway for documentation // purposes and because we may start enforcing it. boolean readOnly() default false; // If optional flag is set to true, then current method does not start // transaction, but has access to EntityManager via providers. // // If another method is called and it has transactional annotation with // optional() flag set to false, then that method starts its own // transaction with its own post commit hooks which are run on return. // // So, the following code starts 1000 transactions in method2: // ..... // @Transactional // void method1() { do something } // ..... // @Transactional(optional = true) // void method2() { // for (int 1 = 0; i < 1000; i++) { // method1(); // } // } // .... // boolean optional() default false; boolean rollback() default false; Class<? extends Annotation> value() default Default.class; }
true
b636a12d96190d437c226b33b48b45be25980f1f
Java
adaqwerty15/schedule
/src/main/java/ru/isu/tashkenova/appSch/Workload.java
UTF-8
1,089
2.328125
2
[]
no_license
package ru.isu.tashkenova.appSch; public class Workload { public int id; public int studentClassId; public int subjectId; public int userId; public int errorCode; public Workload(int id, int studentClassId, int subjectId, int userId, int errorCode) { this.id = id; this.studentClassId = studentClassId; this.subjectId = subjectId; this.userId = userId; this.errorCode = errorCode; } public Workload(int studentClassId, int subjectId, int userId) { this.studentClassId = studentClassId; this.subjectId = subjectId; this.userId = userId; } public Workload(){ this.errorCode = 1; } public Workload(int errorCode) { this.errorCode = 0; } public int getId() { return id; } public int getStudentClassId() { return studentClassId; } public int getSubjectId() { return subjectId; } public int getUserId() { return userId; } public int getErrorCode() { return errorCode; } }
true
7cc508c964ed56d5d5586299c3be9b7a1cbab314
Java
minhee0327/Algorithm
/JAVA/Programmers/weekly/Day04.java
UTF-8
1,438
3.390625
3
[]
no_license
package programmers.monthly; import java.util.*; public class Day04 { } class Solution4{ public String solution(String[] table, String[] languages, int[] preference) { String answer = ""; Map<String, Integer> companyScoreMap = new HashMap<>(); for(String t: table){ String[] tables = t.split(" "); String company = tables[0]; int tableSize = tables.length; int languagePreference = languages.length; int sum = 0; Map<String, Integer> scoreMap = new HashMap<>(); for(int i = 1; i < tableSize; i++){ scoreMap.put(tables[i], tableSize -i); } for(int i = 0; i < languagePreference; i++){ sum += scoreMap.getOrDefault(languages[i], 0) * preference[i]; } companyScoreMap.put(company, sum); } List<Integer> scoreValues = new ArrayList<>(companyScoreMap.values()); scoreValues.sort(Comparator.reverseOrder()); int maxValue = scoreValues.get(0); List<String> candidates = new ArrayList<>(); for(Map.Entry<String , Integer> entry: companyScoreMap.entrySet()){ if(entry.getValue() == maxValue){ candidates.add(entry.getKey()); } } Collections.sort(candidates); System.out.println(candidates); return candidates.get(0); } }
true
1471806c7b5b8effb90f2dbc020858d11857375b
Java
ZYHGOD-1/Aosp11
/packages/apps/KeyChain/src/com/android/keychain/KeyChainStateStorage.java
UTF-8
3,965
1.945313
2
[]
no_license
/* * Copyright (C) 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.keychain; import android.annotation.Nullable; import android.security.CredentialManagementApp; import android.util.AtomicFile; import android.util.Log; import android.util.Xml; import com.android.internal.util.FastXmlSerializer; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import org.xmlpull.v1.XmlSerializer; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.nio.charset.StandardCharsets; public class KeyChainStateStorage { private static final String TAG = "KeyChain"; private static final String TAG_CREDENTIAL_MANAGEMENT_APP = "credential-management-app"; private final File mDirectory; public KeyChainStateStorage(File directory) { mDirectory = directory; } @Nullable public CredentialManagementApp loadCredentialManagementApp() { CredentialManagementApp credentialManagementApp = null; AtomicFile file = getCredentialManagementFile(); FileInputStream stream = null; try { stream = file.openRead(); XmlPullParser parser = Xml.newPullParser(); parser.setInput(stream, StandardCharsets.UTF_8.name()); int type; while ((type = parser.next()) != XmlPullParser.START_TAG && type != XmlPullParser.END_DOCUMENT) { } String tag = parser.getName(); if (TAG_CREDENTIAL_MANAGEMENT_APP.equals(tag)) { credentialManagementApp = CredentialManagementApp.readFromXml(parser); } } catch (XmlPullParserException | IOException e) { Log.e(TAG, "Failed to load state", e); } finally { try { if (stream != null) { stream.close(); } } catch (IOException e) { } } return credentialManagementApp; } public void saveCredentialManagementApp( @Nullable CredentialManagementApp credentialManagementApp) { AtomicFile file = getCredentialManagementFile(); FileOutputStream stream; try { stream = file.startWrite(); } catch (IOException e) { Log.e(TAG, "Failed to write state " + e); return; } try { XmlSerializer out = new FastXmlSerializer(); out.setOutput(stream, StandardCharsets.UTF_8.name()); out.startDocument(null, true); if (credentialManagementApp != null) { out.startTag(null, TAG_CREDENTIAL_MANAGEMENT_APP); credentialManagementApp.writeToXml(out); out.endTag(null, TAG_CREDENTIAL_MANAGEMENT_APP); } out.endDocument(); file.finishWrite(stream); stream.close(); } catch (IOException e) { Log.e(TAG, "Failed to store state"); file.failWrite(stream); } } private AtomicFile getCredentialManagementFile() { File file = new File(mDirectory, "credential-management-app.xml"); if (!file.exists()) { try { file.createNewFile(); } catch (IOException e) { } } return new AtomicFile(file); } }
true
8573455baba2a00adee4c3c5e44f06e735e5087f
Java
rollingcupcake/Examples-of-java
/ExampleAndOr.java
UTF-8
493
3.71875
4
[]
no_license
package day1.examples; /** * Created by Rullendemuffins on 11-Jan-17. */ public class ExampleAndOr { public static void main(String[] args){ int x, y; x = 10; y = -10; if(x > 0 && y > 0){ System.out.println("Both numbers are positive"); }else if(x > 0 || y > 0){ System.out.println("One of the numbers are positive"); }else{ System.out.println("Both of the numbers are negative"); } } }
true
e316efb85cf3957e3246811568dcc453b9aa17d4
Java
Sid-26/Chuu
/src/main/java/core/commands/billboard/BillboardCommand.java
UTF-8
12,981
1.78125
2
[ "MIT" ]
permissive
package core.commands.billboard; import core.apis.last.entities.chartentities.*; import core.commands.Context; import core.commands.abstracts.ConcurrentCommand; import core.commands.utils.ChuuEmbedBuilder; import core.commands.utils.CommandCategory; import core.commands.utils.CommandUtil; import core.imagerenderer.ChartQuality; import core.imagerenderer.CollageMaker; import core.imagerenderer.GraphicUtils; import core.imagerenderer.HotMaker; import core.otherlisteners.util.PaginatorBuilder; import core.parsers.NoOpParser; import core.parsers.NumberParser; import core.parsers.Parser; import core.parsers.params.CommandParameters; import core.parsers.params.NumberParameters; import core.parsers.utils.OptionalEntity; import core.parsers.utils.Optionals; import core.services.BillboardHoarder; import dao.ServiceView; import dao.entities.*; import dao.exceptions.InstanceNotFoundException; import dao.utils.LinkUtils; import net.dv8tion.jda.api.EmbedBuilder; import javax.annotation.Nonnull; import java.awt.image.BufferedImage; import java.sql.Date; import java.time.*; import java.time.format.DateTimeFormatter; import java.time.temporal.ChronoUnit; import java.util.*; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.ConcurrentSkipListSet; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import static core.parsers.ExtraParser.LIMIT_ERROR; public class BillboardCommand extends ConcurrentCommand<NumberParameters<CommandParameters>> { private final static ConcurrentSkipListSet<Long> inProcessSets = new ConcurrentSkipListSet<>(); public BillboardCommand(ServiceView dao) { super(dao); respondInPrivate = false; } @Override protected CommandCategory initCategory() { return CommandCategory.TRENDS; } @Override public Parser<NumberParameters<CommandParameters>> initParser() { Map<Integer, String> map = new HashMap<>(2); map.put(LIMIT_ERROR, "The number introduced must be between 1 and 100"); String s = "You can also introduce a number to vary the number of tracks shown in the image" + "defaults to 5"; NumberParser<CommandParameters, NoOpParser> extraParser = new NumberParser<>(NoOpParser.INSTANCE, 5L, 100L, map, s, false, true, false, "count"); extraParser.addOptional(new OptionalEntity("scrobbles", "sort the top by scrobble count, not listeners"), new OptionalEntity("full", "in case of doing the image show first 100 songs in the image"), Optionals.LIST.opt, Optionals.IMAGE.opt, Optionals.NOTITLES.opt, Optionals.ASIDE.opt, Optionals.PLAYS_REPLACE.opt); extraParser.replaceOptional("plays", Optionals.NOPLAYS.opt); return extraParser; } @Override public String getDescription() { return "The most popular tracks last week on this server"; } @Override public List<String> getAliases() { return List.of("billboard", "trend"); } @Override public String getName() { return "Server's Billboard Top 100"; } // You have to call the insert_weeks procedure first that is declared in MariadBnew. on the mysql client it would be something like `call inert_weeks()` public List<BillboardEntity> getEntities(int weekId, long guildId, boolean doListeners, Context event) { return db.getBillboard(weekId, guildId, doListeners); } public String getTitle() { return ""; } @Override public void onCommand(Context e, @Nonnull NumberParameters<CommandParameters> params) { long guildId = e.getGuild().getIdLong(); List<UsersWrapper> all = db.getAllNonPrivate(guildId); if (all.isEmpty()) { sendMessageQueue(e, "There is not a single person registered in this server"); return; } Week week = db.getCurrentWeekId(); Date weekStart = week.getWeekStart(); Optional<UsersWrapper> min = all.stream().min(Comparator.comparingInt(x -> x.getTimeZone().getOffset(Instant.now().getEpochSecond()))); if (min.isPresent()) { UsersWrapper usersWrapper = min.get(); TimeZone timeZone = usersWrapper.getTimeZone(); if (LocalDate.now().getDayOfWeek().equals(DayOfWeek.MONDAY)) { int offset = timeZone.getOffset(LocalDate.now().atStartOfDay().toInstant( ZoneOffset.UTC).getEpochSecond() * 1000); if (offset > 0) { ZonedDateTime plus = LocalDate.now().atStartOfDay().atZone(ZoneId.of("UTC")).plus(offset, ChronoUnit.MILLIS); if (plus.isAfter(ZonedDateTime.now())) { long remaining = offset - LocalTime.now().toNanoOfDay() / 1_000_000; if (remaining > 0) { String format = String.format("%02d:%02d:%02d", TimeUnit.MILLISECONDS.toHours(remaining), TimeUnit.MILLISECONDS.toMinutes(remaining) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(remaining)), TimeUnit.MILLISECONDS.toSeconds(remaining) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(remaining))); sendMessageQueue(e, "The week hasn't ended for a user because they have set a different timezone!" + "\nYou will have to wait " + format); return; } } } } } int weekId = week.getId(); boolean doListeners = !params.hasOptional("scrobbles"); List<BillboardEntity> entities = getEntities(weekId, guildId, doListeners, e); LocalDateTime weekBeggining = weekStart.toLocalDate().minus(1, ChronoUnit.WEEKS).atStartOfDay(); if (entities.isEmpty() && weekId == 1 && this instanceof BillboardAlbumCommand && !db.getBillboard(weekId, guildId, doListeners).isEmpty()) { sendMessageQueue(e, "The album trend couldn't be computed this week because it was the first one."); return; } if (entities.isEmpty()) { if (inProcessSets.contains(guildId)) { sendMessageQueue(e, "This weekly chart is still being calculated, wait a few seconds/minutes more pls."); return; } try { inProcessSets.add(guildId); sendMessageQueue(e, "Didn't have the top from this week, will start to make it now."); BillboardHoarder billboardHoarder = new BillboardHoarder(all, db, week, lastFM); billboardHoarder.hoardUsers(); db.insertBillboardData(weekId, guildId); } finally { inProcessSets.remove(guildId); } entities = getEntities(weekId, guildId, doListeners, e); if (entities.isEmpty()) { sendMessageQueue(e, "Didn't find any scrobbles in this server users"); return; } sendMessageQueue(e, "Successfully generated this week's charts"); } String name = e.getGuild().getName(); doBillboard(e, params, doListeners, entities, weekStart.toLocalDate().atStartOfDay(), weekBeggining, name, true); } protected void doBillboard(Context e, NumberParameters<CommandParameters> params, boolean doListeners, List<BillboardEntity> entities, LocalDateTime weekStart, LocalDateTime weekBeggining, String name, boolean isFromGuild) { DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMMM"); String one = formatter.format(weekBeggining.toLocalDate()); String dayOne = weekBeggining.getDayOfMonth() + CommandUtil.getDayNumberSuffix(weekBeggining.getDayOfMonth()); String second = formatter.format(weekStart.toLocalDate()); String daySecond = weekStart.toLocalDate().getDayOfMonth() + CommandUtil.getDayNumberSuffix(weekStart.toLocalDate().getDayOfMonth()); String subtitle = dayOne + " " + one + " - " + daySecond + " " + second; String url = isFromGuild ? e.getGuild().getIconUrl() : e.getJDA().getSelfUser().getAvatarUrl(); if (params.hasOptional("list")) { EmbedBuilder embedBuilder = new ChuuEmbedBuilder(e); List<String> artistAliases = entities .stream().map(x -> String.format(". **[%s](%s):**\n Rank: %d | Previous Week: %s | Peak: %s | Weeks on top: %s | %s: %d%n%n", x.getArtist() == null ? CommandUtil.escapeMarkdown(x.getName()) : CommandUtil.escapeMarkdown(x.getName() + " - " + x.getArtist()), x.getArtist() == null ? LinkUtils.getLastFmArtistUrl(x.getName()) : LinkUtils.getLastFMArtistTrack(x.getArtist(), x.getName()), x.getPosition(), x.getPreviousWeek() == 0 ? "--" : x.getPreviousWeek(), x.getPeak() == 0 ? "--" : x.getPeak(), x.getStreak() == 0 ? "--" : x.getStreak(), doListeners ? "Listeners" : "Scrobbles", x.getListeners() )).toList(); embedBuilder.setAuthor("Top 100 " + getTitle() + "from " + name + " in " + subtitle, null, url); new PaginatorBuilder<>(e, embedBuilder, artistAliases).build().queue(); } else if (params.hasOptional("image")) { AtomicInteger ranker = new AtomicInteger(0); int size = entities.size(); int x = Math.max((int) Math.ceil(Math.sqrt(size)), 1); int y = (int) Math.ceil((double) size / x); if (y == 1) { x = size; } boolean drawTitles = !params.hasOptional("notitles"); boolean drawPlays = !params.hasOptional("noplays"); boolean isAside = params.hasOptional("aside"); try { LastFMData data = e.isFromGuild() ? db.computeLastFmData(e.getAuthor().getIdLong(), e.getGuild().getIdLong()) : db.findLastFMData(e.getAuthor().getIdLong()); isAside = isAside || EnumSet.of(ChartMode.IMAGE_ASIDE, ChartMode.IMAGE_ASIDE_INFO).contains(data.getChartMode()); } catch (InstanceNotFoundException ex) { // Shallowed } boolean finalIsAside = isAside; List<UrlCapsule> urlEntities = entities.stream() .limit(size) .map(w -> { if (w.getName() == null) { if (doListeners) { return new ArtistListenersChart(w.getUrl(), ranker.getAndIncrement(), w.getArtist(), null, Math.toIntExact(w.getListeners()), drawTitles, drawPlays, finalIsAside); } else { return new ArtistChart(w.getUrl(), ranker.getAndIncrement(), w.getArtist(), null, Math.toIntExact(w.getListeners()), drawTitles, drawPlays, finalIsAside); } } else { if (doListeners) { return new AlbumListenersChart(w.getUrl(), ranker.getAndIncrement(), w.getName(), w.getArtist(), null, Math.toIntExact(w.getListeners()), drawTitles, drawPlays, finalIsAside); } else { return new AlbumChart(w.getUrl(), ranker.getAndIncrement(), w.getName(), w.getArtist(), null, Math.toIntExact(w.getListeners()), drawTitles, drawPlays, finalIsAside); } } }) .toList(); ChartQuality quality = GraphicUtils.getQuality(urlEntities.size(), e); BufferedImage image = CollageMaker.generateCollageThreaded(x, y, new ArrayBlockingQueue<>(urlEntities.size(), false, urlEntities), quality, isAside); sendImage(image, e, quality, new ChuuEmbedBuilder(e).setAuthor("Top 100 " + getTitle() + "from " + name + " in " + subtitle, null, url)); } else { BufferedImage logo = CommandUtil.getLogo(db, e); int size = params.hasOptional("full") ? 100 : Math.toIntExact(params.getExtraParam()); sendImage(HotMaker.doHotMaker(name + "'s " + getTitle() + "chart", subtitle, entities, doListeners, size, logo), e); } } @Override public String getUsageInstructions() { return super.getUsageInstructions() + "The chart gets filled with the top 1k tracks of each user from the previous week's Monday to this week's Monday. Once the chart is built if new users come to the server they wont affect the chart. Come back next Monday to generate the next chart"; } }
true
ab51423db86a6e0091ea37d6b5ab75db8ed03a02
Java
snooze6/Entroido-Verin
/app/src/main/java/es/develover/joker/entroido/Activities/HistoriaActivity.java
UTF-8
1,491
1.96875
2
[]
no_license
package es.develover.joker.entroido.Activities; import android.content.pm.ActivityInfo; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.MenuItem; import android.widget.ListView; import es.develover.joker.entroido.Adapters.HistoryAdapter; import es.develover.joker.entroido.Model.ContentProvider; import es.develover.joker.entroido.R; public class HistoriaActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_historia); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); this.setTitle("Carteles"); if (getSupportActionBar()!=null) getSupportActionBar().setDisplayHomeAsUpEnabled(true); ListView listView = (ListView)findViewById(R.id.listview_events); listView.setAdapter(new HistoryAdapter(ContentProvider.history, this)); if(getResources().getBoolean(R.bool.portrait_only)){ setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); } } @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == android.R.id.home) { //Log.v(LOG_TAG, "HOOOME"); finish(); return true; } return super.onOptionsItemSelected(item); } }
true
c6222ffce3a4f99aa070237e4830d645d5f438da
Java
lyq0604/spring-cloud-demo
/spring-cloud-system/src/main/java/com/blade/system/base/controller/UserController.java
UTF-8
1,083
2.203125
2
[]
no_license
package com.blade.system.base.controller; import com.blade.common.base.BaseController; import com.blade.system.base.domain.User; import com.blade.system.base.service.UserService; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.springframework.web.bind.annotation.*; import com.blade.system.common.vo.UserInfoVO; /** * @author lyq * @create 6/21/19 */ @Api(tags = {"用户相关接口"}) @RestController @RequestMapping("/users") public class UserController extends BaseController<UserService,User> { @ApiOperation(value = "用户登录") @PostMapping("/login") public String login(@RequestBody User user){ String token = service.login(user); return "bearer " + token; } /** * 获取当前用户信息,包含用户角色、权限、菜单等 * @return */ @ApiOperation(value = "获取用户信息(角色、权限、菜单)") @GetMapping("/info") public UserInfoVO getInfo(){ UserInfoVO userInfoVO = service.getUserInfo(); return userInfoVO; } }
true
928c5c3a9b96db2fcee721bcc77a80bf180fff24
Java
StormPhoenix/OGit
/httpknife/src/main/java/com/stormphoenix/httpknife/github/payload/GitMemberPayload.java
UTF-8
761
2.21875
2
[ "Apache-2.0" ]
permissive
package com.stormphoenix.httpknife.github.payload; import com.stormphoenix.httpknife.github.GitUser; import java.io.Serializable; /** * Created by Quinn on 15/10/2. */ public class GitMemberPayload extends GitPayload { private GitUser member; private String action; public String getAction() { return action; } public void setAction(String action) { this.action = action; } public GitUser getMember() { return member; } public void setMember(GitUser member) { this.member = member; } @Override public String toString() { return "GitMemberPayload{" + "action='" + action + '\'' + ", member=" + member + '}'; } }
true
f1fdffec6bff861d00ad28415e1eaa27d5a94aa1
Java
musket-ml/ds-ide
/com.onpositive.yamledit/src/com/onpositive/yamledit/ast/CallbackValidator.java
UTF-8
1,038
2.3125
2
[]
no_license
package com.onpositive.yamledit.ast; import java.util.HashSet; import org.aml.typesystem.Status; import org.aml.typesystem.values.IArray; import com.onpositive.yamledit.model.IValidator; public class CallbackValidator implements IValidator{ @Override public Status validate(ASTElement element) { Object property = element.getRoot().getProperty("metrics"); Status res=new Status(0, 0, ""); HashSet<String>metrics=new HashSet<>(); if (property instanceof IArray) { IArray arr=(IArray) property; for (int i=0;i<arr.length();i++) { metrics.add(arr.item(i).toString()); metrics.add("val_"+arr.item(i).toString()); } } metrics.add("loss"); metrics.add("val_loss"); Object property2 = element.getProperty("monitor"); if (property2!=null) { if (!metrics.contains(property2.toString())) { Status status = new Status(Status.ERROR,1,"monitor should be one of:"+metrics); status.setKey("monitor"); res.addSubStatus(status); } } return res; } }
true
761e2d51c8313d326a8663b376e15b92061c07ee
Java
VinodKandula/vinod
/src/main/java/com/poi/ExcelExample.java
UTF-8
6,842
2.640625
3
[]
no_license
/** * */ package com.poi; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import org.apache.poi.hssf.usermodel.HSSFFont; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.CellStyle; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.util.CellRangeAddress; /** * @author vinod * */ public class ExcelExample { /** * @param args */ public static void main(String[] args) { createExcelFile(); } public static void createExcelFile() { HSSFWorkbook workbook = new HSSFWorkbook(); HSSFSheet sheet = workbook.createSheet("COMMERCIAL INVOICE"); HSSFFont font = workbook.createFont(); font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); CellStyle style = workbook.createCellStyle(); style.setFont(font); int rownum = 2; sheet.addMergedRegion(new CellRangeAddress(2, 2, 1, 2)); Row row = sheet.createRow(rownum); Cell cell = row.createCell(1); cell.setCellValue("Emmett London"); CellStyle headerStyle = workbook.createCellStyle(); HSSFFont headerFont = workbook.createFont(); headerFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); headerFont.setFontHeightInPoints((short) 40); headerStyle.setFont(headerFont); headerStyle.setAlignment(CellStyle.ALIGN_CENTER); cell.setCellStyle(headerStyle); rownum = rownum+2; row = sheet.createRow(rownum); cell = row.createCell(0); cell.setCellValue("COMMERCIAL INVOICE"); cell.setCellStyle(style); row = sheet.createRow(++rownum); row = sheet.createRow(++rownum); cell = row.createCell(0); cell.setCellValue("DATE"); cell.setCellStyle(style); cell = row.createCell(1); cell.setCellValue("28/6/16"); row = sheet.createRow(++rownum); cell = row.createCell(0); cell.setCellValue("SENDERS VAT No."); cell.setCellStyle(style); cell = row.createCell(1); cell.setCellValue("563180253"); row = sheet.createRow(++rownum); cell = row.createCell(0); cell.setCellValue("SENDER REFERENCE"); cell.setCellStyle(style); cell = row.createCell(1); cell.setCellValue("100004303"); row = sheet.createRow(++rownum); cell = row.createCell(0); cell.setCellValue("SHIPPER INFORMATION"); cell.setCellStyle(style); cell = row.createCell(1); cell.setCellValue("CONSIGNEE INFORMATION"); cell.setCellStyle(style); row = sheet.createRow(++rownum); cell = row.createCell(0); CellStyle cs = workbook.createCellStyle(); cs.setWrapText(true); //cell.setCellStyle(cs); cell.setCellValue("Emmett Shirts Ltd. \n380 King's Road \nLondon \nSW3 5UZ"); cell = row.createCell(1); //cell.setCellStyle(cs); cell.setCellValue("Clive Parry \nSAGE (Marketing) \n2455 TELLER ROAD \nThousand Oaks, California, 91320 \nUnited States"); row = sheet.createRow(++rownum); cell = row.createCell(0); cell.setCellStyle(style); cell.setCellValue("CONSIGNEE CONTACT DETAILS"); cell = row.createCell(1); cell.setCellValue("T: 347 571 9899"); row = sheet.createRow(++rownum); cell = row.createCell(0); cell.setCellStyle(style); cell.setCellValue("AGENTS WAYBILL No."); cell = row.createCell(1); cell.setCellValue(""); row = sheet.createRow(++rownum); cell = row.createCell(0); cell.setCellStyle(style); cell.setCellValue("PIECES"); cell = row.createCell(1); cell.setCellValue("100"); row = sheet.createRow(++rownum); cell = row.createCell(0); cell.setCellStyle(style); cell.setCellValue("WEIGHT"); cell = row.createCell(1); cell.setCellValue("200"); row = sheet.createRow(++rownum); cell = row.createCell(0); row = sheet.createRow(++rownum); cell = row.createCell(0); cell.setCellStyle(style); cell.setCellValue("WECONSIGNMENT DETAILSIGHT"); cell = row.createCell(1); cell.setCellValue(""); row = sheet.createRow(++rownum); cell = row.createCell(0); cell.setCellStyle(style); cell.setCellValue("GOODS DESCRIPTION"); cell = row.createCell(1); cell.setCellStyle(style); cell.setCellValue("QUANTITY"); cell = row.createCell(2); cell.setCellStyle(style); cell.setCellValue("UNIT VALUE"); cell = row.createCell(3); cell.setCellStyle(style); cell.setCellValue("TOTAL CUSTOMS VALUE"); //TODO for loop with order lines row = sheet.createRow(++rownum); cell = row.createCell(0); cell.setCellValue("Blue Cotton Twill"); cell = row.createCell(1); cell.setCellValue("2"); cell = row.createCell(2); cell.setCellValue("£ 125.00"); cell = row.createCell(3); cell.setCellValue("£ 250.00"); row = sheet.createRow(++rownum); cell = row.createCell(0); cell.setCellValue("Blue Jean Linen"); cell = row.createCell(1); cell.setCellValue("1"); cell = row.createCell(2); cell.setCellValue("£ 145.00"); cell = row.createCell(3); cell.setCellValue("£ 145.00"); row = sheet.createRow(++rownum); cell = row.createCell(0); cell.setCellValue("Blue Jean Linen"); cell = row.createCell(1); cell.setCellValue("1"); cell = row.createCell(2); cell.setCellValue("£ 125.00"); cell = row.createCell(3); cell.setCellValue("£ 125.00"); row = sheet.createRow(++rownum); row = sheet.createRow(++rownum); row = sheet.createRow(++rownum); row = sheet.createRow(++rownum); row = sheet.createRow(++rownum); row = sheet.createRow(++rownum); cell = row.createCell(0); cell.setCellStyle(style); cell.setCellValue("TOTAL"); cell = row.createCell(1); cell.setCellStyle(style); cell.setCellValue("4"); cell = row.createCell(1); cell.setCellStyle(style); cell.setCellValue("£ 520.00"); row = sheet.createRow(++rownum); cell = row.createCell(0); cell.setCellStyle(style); cell.setCellValue("I CONFIRM THESE GOODS ARE NOT HAZARDOUS"); row = sheet.createRow(++rownum); cell = row.createCell(0); cell.setCellStyle(style); cell.setCellValue("I CONFIRM THESE GOODS DO NOT REQUIRE A LICENCE"); row = sheet.createRow(++rownum); row = sheet.createRow(++rownum); cell = row.createCell(0); cell.setCellStyle(style); cell.setCellValue("SIGNATURE: _________________"); row = sheet.createRow(++rownum); cell = row.createCell(0); cell.setCellStyle(style); cell.setCellValue("PRINT NAME: _________________"); // Auto size the column widths for(int columnIndex = 0; columnIndex < 4; columnIndex++) { sheet.autoSizeColumn(columnIndex); } try { FileOutputStream out = new FileOutputStream(new File("//Users//vinod/Desktop//test.xls")); workbook.write(out); out.close(); System.out.println("Excel written successfully.."); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
true
6d652898325dfef331153d7155e89f085b9fbd57
Java
SurbhiAggarwal04/HATEOAS-Restful-Assignment
/HATEOAS-Appeals-saggarw9-Eclipse-Server/src/main/java/edu/asu/surbhi/assignment/services/UpdateAppealActivity.java
UTF-8
3,110
2.625
3
[]
no_license
package edu.asu.surbhi.assignment.services; import edu.asu.surbhi.assignment.exceptions.NoSuchAppealException; import edu.asu.surbhi.assignment.exceptions.UpdateException; import edu.asu.surbhi.assignment.model.AppealStatus; import edu.asu.surbhi.assignment.model.Identifier; import edu.asu.surbhi.assignment.model.Items; import edu.asu.surbhi.assignment.repositories.AppealRepository; import edu.asu.surbhi.assignment.representations.AppealRepresentation; import edu.asu.surbhi.assignment.representations.RestbucksUri; public class UpdateAppealActivity { public AppealRepresentation update(Items items, RestbucksUri appealUri) { Identifier appealIdentifier = appealUri.getId(); AppealRepository repository = AppealRepository.current(); if (!AppealRepository.current().appealPlaced(appealIdentifier)) { throw new NoSuchAppealException(); } if (!appealCanBeChanged(appealIdentifier)) { throw new UpdateException(); } repository.remove(appealIdentifier); repository.store(appealIdentifier,items); return AppealRepresentation.createAppealRepresentation(items, appealUri); } public AppealRepresentation updateReady(RestbucksUri appealUri) { Identifier appealIdentifier = appealUri.getId(); AppealRepository repository = AppealRepository.current(); if (!AppealRepository.current().appealPlaced(appealIdentifier)) { throw new NoSuchAppealException(); } if (!appealCanBeChanged(appealIdentifier)) { throw new UpdateException(); } Items storedOrder = repository.get(appealIdentifier); storedOrder.setStatus(AppealStatus.READY); repository.remove(appealIdentifier); repository.store(appealIdentifier,storedOrder); return AppealRepresentation.createAppealRepresentation(storedOrder, appealUri); } public AppealRepresentation updateFollowUp(RestbucksUri appealUri) { Identifier appealIdentifier = appealUri.getId(); AppealRepository repository = AppealRepository.current(); if (!AppealRepository.current().appealPlaced(appealIdentifier)) { throw new NoSuchAppealException(); } if (!followUpAppealCanBeChanged(appealIdentifier)) { throw new UpdateException(); } Items storedOrder = repository.get(appealIdentifier); storedOrder.setStatus(AppealStatus.FOLLOWUP); repository.remove(appealIdentifier); repository.store(appealIdentifier,storedOrder); return AppealRepresentation.createAppealRepresentation(storedOrder, appealUri); } private boolean followUpAppealCanBeChanged(Identifier identifier) { return AppealRepository.current().get(identifier).getStatus() == AppealStatus.PREPARING || AppealRepository.current().get(identifier).getStatus() == AppealStatus.READY; } private boolean appealCanBeChanged(Identifier identifier) { return AppealRepository.current().get(identifier).getStatus() == AppealStatus.PREPARING; } }
true
18de5a9d3d41aedfabf8dd4a9a37a44cc0f98e17
Java
fernandamsouza/UDESC
/Trabalho de LFA/Brzozowski.java
ISO-8859-1
1,644
3.3125
3
[]
no_license
//Feito por: Fernanda Maria de Souza e Matias Gutierrez package main; import java.util.TreeMap; public class Brzozowski { private AutomatoFinitoDeterministico afd; private TreeMap<Integer, Linguagem> linguagens; // rvore que contm um inteiro e a linguagem de cada autmato inicializado pelo mtodo. private int qtd; public Brzozowski(AutomatoFinitoDeterministico afd) { this.afd = afd; linguagens = new TreeMap<Integer, Linguagem>(); int i = 1; //inicializa o mapa colocando nele os estados com suas respectivas linguagens for (Estado e: this.afd.getEstados()) { if (e.compareTo(afd.getEstadoInicial()) == 0) { // caso a comparao seja verdadeira e seja o estado inicial. linguagens.put(1,new Linguagem(e.getLinguagem(), e.getEstado())); // para o estado inicial. } else { // demais estados. ++i; linguagens.put(i, new Linguagem(e.getLinguagem(), e.getEstado())); } } qtd = i; } public String brzozowski() { //mtodo de brzozowski for (int i = qtd; i > 0; i--) { if (i == qtd) { if (!linguagens.get(i).verifica()) { linguagens.get(i).setLinguagem(linguagens.get(i).simplifica(linguagens.get(i).getLinguagem())); linguagens.get(i).arden(); // chamada do lema de arden. } } else { for (int j = qtd; j > i; j--) { linguagens.get(i).substitui(linguagens.get(j).getEstado(),linguagens.get(j).getLinguagem()); } if (!linguagens.get(i).verifica()) { linguagens.get(i).setLinguagem(linguagens.get(i).simplifica(linguagens.get(i).getLinguagem())); linguagens.get(i).arden(); // chamada do lema de arden } } } return linguagens.get(1).getLinguagem(); } }
true
f4ecc6b19c3b83973cfb808bd43356677ffa8c20
Java
reverseengineeringer/me.lyft.android
/src/me/lyft/android/ui/passenger/v2/inride/ContactDriverDialogController.java
UTF-8
3,033
1.953125
2
[]
no_license
package me.lyft.android.ui.passenger.v2.inride; import android.content.res.Resources; import com.makeramen.roundedimageview.RoundedImageView; import com.squareup.picasso.RequestCreator; import javax.inject.Inject; import me.lyft.android.analytics.studies.PassengerAnalytics; import me.lyft.android.application.passenger.IPassengerRideProvider; import me.lyft.android.common.DialogFlow; import me.lyft.android.domain.passenger.ride.Driver; import me.lyft.android.domain.passenger.ride.PassengerRide; import me.lyft.android.domain.passenger.ride.RideFeature; import me.lyft.android.infrastructure.share.IShareService; import me.lyft.android.managers.ImageLoader; import me.lyft.android.ui.dialogs.StandardDialogController; import me.lyft.android.utils.Telephony; public class ContactDriverDialogController extends StandardDialogController { private final ImageLoader imageLoader; private final IPassengerRideProvider passengerRideProvider; private final IShareService smsService; private final Telephony telephony; @Inject public ContactDriverDialogController(DialogFlow paramDialogFlow, IShareService paramIShareService, IPassengerRideProvider paramIPassengerRideProvider, Telephony paramTelephony, ImageLoader paramImageLoader) { super(paramDialogFlow); smsService = paramIShareService; passengerRideProvider = paramIPassengerRideProvider; telephony = paramTelephony; imageLoader = paramImageLoader; } private void callDriver() { dismissDialog(); String str = passengerRideProvider.getPassengerRide().getDriver().getPhoneNumber(); telephony.callPhone(str); } private void sendMessageToDriver() { dismissDialog(); PassengerAnalytics.trackTextDriverTap(); smsService.openSmsComposer(passengerRideProvider.getPassengerRide().getDriver().getPhoneNumber()); } public void onAttach() { super.onAttach(); PassengerRide localPassengerRide = passengerRideProvider.getPassengerRide(); Driver localDriver = localPassengerRide.getDriver(); setContentTitle(getResources().getString(2131165949, new Object[] { localDriver.getName() })); RoundedImageView localRoundedImageView = (RoundedImageView)addHeaderLayout(2130903128); imageLoader.load(localDriver.getPhoto()).fit().centerCrop().into(localRoundedImageView); if (localPassengerRide.isFeatureEnabled(RideFeature.CALL_DRIVER)) { addPositiveButton(2130903157, getResources().getString(2131165948), new ContactDriverDialogController.1(this)); } if (localPassengerRide.isFeatureEnabled(RideFeature.SMS_DRIVER)) { addNeutralButton(2130903157, getResources().getString(2131165950), new ContactDriverDialogController.2(this)); } addNegativeButton(2130903152, getResources().getString(2131165358), getDismissListener()); } public int viewId() { return 2131558419; } } /* Location: * Qualified Name: me.lyft.android.ui.passenger.v2.inride.ContactDriverDialogController * Java Class Version: 6 (50.0) * JD-Core Version: 0.7.1 */
true
220f1a8badc9e0932d0ed20b76411192d64211f3
Java
LHJ-123/everydat
/20210102/src/Demo3.java
UTF-8
7,147
3.296875
3
[]
no_license
import java.util.Scanner; public class Demo3{ public static void main(String[] args) { System.out.println("请输入 S、K、L以表示该动物是属于水、空、陆中的其中一种"); Scanner sc = new Scanner(System.in); String s = judge1(sc.nextLine()); inferenceMachine(sc, s); // 推理机 } private static void inferenceMachine(Scanner sc, String s) { if(s.equals("S")) { System.out.println("请您摁下 GO 或者 END"); String s12 = judge2(sc.nextLine()); if (s12.equals("END")) { System.out.println("您要找的是:水生动物"); } else { System.out.println("您所要查询的水生动物是否用肺呼吸(Y or N)"); String s13 = judge0(sc.nextLine()); if (s13.equals("Y")) { System.out.println("请您摁下 GO 或者 END"); String s13_ = judge2(sc.nextLine()); if (s13_.equals("END")) { System.out.println("您要找的是:鲸鱼"); } else { System.out.println("您所要查询的用肺呼吸的水生动物是否有牙齿(Y or N)"); String s14 = judge0(sc.nextLine()); if (s14.equals("Y")) { System.out.println("您要找的动物是:虎鲸"); } else { System.out.println("您要找的动物是:须鲸"); } } } else if (s13.equals("N")) { System.out.println("您要找的是用腮呼吸的是:普通鱼"); } } }else if(s.equals("K")) { System.out.println("请您摁下 GO or END"); String s21 = judge2(sc.nextLine()); if (s21.equals("GO")) { System.out.println("请问该空中动物是节肢动物吗?(Y or N)"); String s21_ = judge0(sc.nextLine()); if (s21_.equals("Y")) { System.out.println("请您摁下 GO or END"); String s22 = judge2(sc.nextLine()); if (s22.equals("GO")) { System.out.println("请问该空中飞行的节肢动物是害虫还是益虫:害虫为N,益虫为Y?"); String s22_ = judge0(sc.nextLine()); if (s22_.equals("Y")) { System.out.println("您所查询的为:蜜蜂"); } else { System.out.println("您所查询的为:蝗虫"); } } else { System.out.println("您输入的是:空中飞行的节肢动物"); } } else { System.out.println("请您摁下 GO or END"); String s23 = judge2(sc.nextLine()); if (s23.equals("GO")) { System.out.println("请问该空中飞行的非节肢动物能否模仿人类说话(Y or N)"); String s23_ = judge0(sc.nextLine()); if (s23_.equals("Y")) { System.out.println("您所查询的是:鹦鹉"); } else { System.out.println("您所查询的是:麻雀"); } } else { System.out.println("您输入的是:空中飞行的非节肢动物"); } } } else { System.out.println("您输入的是:空中动物"); } }else if(s.equals("L")) { System.out.println("请您摁下 GO or END"); String s21 = judge2(sc.nextLine()); if (s21.equals("GO")) { System.out.println("请问该陆地动物是食肉动物还是食草动物 食肉用Y,食草用N?"); String s21_ = judge0(sc.nextLine()); if (s21_.equals("Y")) { System.out.println("请您摁下 GO or END"); String s22 = judge2(sc.nextLine()); if (s22.equals("GO")) { System.out.println("请问该动物是否为猫科动物?(Y or N)"); String s22_ = judge0(sc.nextLine()); if (s22_.equals("Y")) { System.out.println("您所查询的为:老虎"); } else { System.out.println("您所查询的为:狼"); } } else { System.out.println("您输入的是:陆地上的食肉动物"); } } else { System.out.println("请您摁下 GO or END"); String s23 = judge2(sc.nextLine()); if (s23.equals("GO")) { System.out.println("请问该动物是否有角(Y or N)"); String s23_ = judge0(sc.nextLine()); if (s23_.equals("Y")) { System.out.println("您所查询的是:山羊"); } else { System.out.println("您所查询的是:熊猫"); } } else { System.out.println("您输入的是:食草动物"); } } } else { System.out.println("您输入的是:陆地动物"); } }else { System.out.println("程序运行出错了,请重新运行!!!"); } } /*判断输入是否为 Y or N,若不是则循环采集正确格式*/ public static String judge0(String s) { Scanner sc = new Scanner(System.in); while (!(s.equals("Y") || s.equals("N"))) { System.out.println("您输入的字母有误,请重新输入:Y, N"); String ss = sc.nextLine(); s = ss; } return s; } /*判断输入是否为 L、K or S,若不是则循环采集正确格式*/ public static String judge1(String s) { Scanner sc = new Scanner(System.in); while (!(s.equals("L") || s.equals("K") || s.equals("S"))) { System.out.println("您输入的字母有误,请重新输入:L, K, S"); String ss = sc.nextLine(); s = ss; } return s; } /*判断输入是否为 END or GO,若不是则循环采集正确格式*/ public static String judge2(String s) { Scanner sc = new Scanner(System.in); while (!(s.equals("END") || s.equals("GO"))) { System.out.println("您输入的指令有误,请重新输入:END or GO"); String ss = sc.nextLine(); s = ss; } return s; } }
true
8cb305275fd1df95616fb7419f39d38192187034
Java
MrSolmi/labJava
/lab7/t1/src/com/company/MyMethod.java
UTF-8
325
3.140625
3
[]
no_license
package com.company; import java.util.Scanner; public class MyMethod { public static double powMethod (double _value) throws Exception { if (_value > 0) { return Math.pow(_value,2); } else { throw new Exception("Число должно быть > 0"); } } }
true
dee7c380b92685a19580b0cfa59a111022142a72
Java
DenisVini/Turma12Java
/G12/Java/Lista1/src/L1Ex1.java
MacCentralEurope
558
3.375
3
[]
no_license
import java.util.*; public class L1Ex1 { public static void main(String[]args) { Scanner leia = new Scanner(System.in); int idade ; int meses ; int dias ; int dia ; System.out.print("Voc tem quantos anos: "); idade = leia.nextInt(); System.out.print("Voc tem "+idade+" anos e quantos meses: "); meses = leia.nextInt(); System.out.print("Voc tem "+idade+" anos, "+meses+" meses e quantos dias: "); dia = leia.nextInt(); dias = ((idade * 365)+(meses*30)+dia); System.out.println("Voc viveu: "+dias+" dias"); } }
true
7b71492b22ee27a3cd3793d922fd85483f217654
Java
joserljdev/catalogo-de-musicas
/src/main/java/br/com/joserlj/catalogo/controller/UsuarioController.java
UTF-8
1,493
2.140625
2
[]
no_license
package br.com.joserlj.catalogo.controller; import javax.validation.Valid; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Controller; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import br.com.joserlj.catalogo.domain.Usuario; import br.com.joserlj.catalogo.service.UsuarioService; @Controller @RequestMapping("/catalogoDeMusicas/usuarios") public class UsuarioController { @Autowired private UsuarioService usuarioService; @Autowired private PasswordEncoder passwordEncoder; @GetMapping("/cadastro") public String preSalvar(@ModelAttribute("usuario") Usuario usuario) { return "/usuario/add"; } @PostMapping("/salvar") public String salvar(@Valid @ModelAttribute("usuario") Usuario usuario, BindingResult result, RedirectAttributes attr) { if (result.hasErrors()) { return "/usuario/add"; } usuario.setSenha(passwordEncoder.encode(usuario.getSenha())); usuarioService.salvar(usuario); attr.addFlashAttribute("mensagem", "Usuário cadastrado com sucesso!"); return "redirect:/catalogoDeMusicas/entrar"; } }
true
c3bc6b43bdc004643b671d3be51e247f3268e47a
Java
SOTASHE/springboot-graphql-reactjsapollo
/springboot-graphql/src/main/java/com/motaharinia/presentation/loguploadedfile/LogUploadedFileController.java
UTF-8
8,955
2.0625
2
[]
no_license
package com.motaharinia.presentation.loguploadedfile; import com.fasterxml.jackson.databind.ObjectMapper; import com.motaharinia.business.service.loguploadedfile.LogUploadedFileService; import com.motaharinia.msutility.json.CustomObjectMapper; import com.motaharinia.msutility.json.PrimitiveResponse; import com.motaharinia.presentation.loguploadedfile.backuploader.FileUploadChunkModel; import com.motaharinia.presentation.loguploadedfile.frontuploader.FineUploaderChunkModel; import com.motaharinia.presentation.loguploadedfile.frontuploader.FineUploaderResponseModel; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import javax.servlet.http.HttpServletRequest; import java.util.Locale; @RestController @RequestMapping({"/fso"}) public class LogUploadedFileController { private final LogUploadedFileService logUploadedFileService; @Autowired public LogUploadedFileController(LogUploadedFileService logUploadedFileService) { this.logUploadedFileService = logUploadedFileService; } @RequestMapping(value = "/upload/{subSystem}/{entity}", method = RequestMethod.POST, produces = "application/json") public @ResponseBody PrimitiveResponse uploadBackPanel(HttpServletRequest request, Locale locale, @RequestBody MultipartFile file, @RequestParam String params, @PathVariable("subSystem") SubSystemEnum subSystem, @PathVariable("entity") String entity) throws Exception { ObjectMapper mapper = new CustomObjectMapper(); System.out.println("params:"+params); FileUploadChunkModel fileUploadChunkModel = mapper.readValue(params, FileUploadChunkModel.class); fileUploadChunkModel.setSubSystem(subSystem); fileUploadChunkModel.setEntity(entity); //ارسال اطلاعات قسمتی از اپلود برای سرویس آپلود فایل logUploadedFileService.uploadToFileModel(file, fileUploadChunkModel); //ایجاد خروجی برای آپلودر بک پنل return new PrimitiveResponse(true); } @RequestMapping(value = "/upload/{subSystem}/{entity}/fine", method = RequestMethod.POST, produces = "application/json") public @ResponseBody FineUploaderResponseModel uploadFrontPanel(HttpServletRequest request, Locale locale, @RequestParam(required = true) String qquuid, @RequestParam(required = true) String qqfilename, @RequestParam(required = true) Long qqtotalfilesize, @RequestBody MultipartFile qqfile, @RequestParam(required = false, defaultValue = "0") Integer qqpartindex, @RequestParam(required = false, defaultValue = "0") Integer qqpartbyteoffset, @RequestParam(required = false, defaultValue = "0") Long qqchunksize, @RequestParam(required = false, defaultValue = "1") Integer qqtotalparts, @PathVariable("subSystem") SubSystemEnum subSystem, @PathVariable("entity") String entity) throws Exception { FineUploaderChunkModel fineUploaderChunkModel = new FineUploaderChunkModel(); fineUploaderChunkModel.setQquuid(qquuid); fineUploaderChunkModel.setQqfilename(qqfilename); fineUploaderChunkModel.setQqtotalfilesize(qqtotalfilesize); fineUploaderChunkModel.setQqfile(qqfile); fineUploaderChunkModel.setQqpartindex(qqpartindex); fineUploaderChunkModel.setQqpartbyteoffset(qqpartbyteoffset); fineUploaderChunkModel.setQqchunksize(qqchunksize); fineUploaderChunkModel.setQqtotalparts(qqtotalparts); fineUploaderChunkModel.setSubSystem(subSystem); fineUploaderChunkModel.setEntity(entity); //ارسال اطلاعات قسمتی از اپلود برای سرویس آپلود فایل logUploadedFileService.uploadToFileModel(qqfile, fineUploaderChunkModel); //ایجاد خروجی جهت آپلود فایل در فرانت پنل FineUploaderResponseModel fineUploaderResponseModel = new FineUploaderResponseModel(); fineUploaderResponseModel.setSuccess(Boolean.TRUE); return fineUploaderResponseModel; } // @RequestMapping(value = "/upload/{subSystem}/{entity}", method = RequestMethod.POST, produces = "application/json") // public @ResponseBody //// PrimitiveResponse upload(HttpServletRequest request, Locale locale, @RequestBody MultipartFile file, @RequestParam String params, // PrimitiveResponse upload(@RequestBody MultipartFile file, @RequestParam String params, // @PathVariable("subSystem") SubSystemEnum subSystem, @PathVariable("entity") String entity) throws Exception { // ObjectMapper mapper = new CustomObjectMapper(); // FileUploadChunkModel fileUploadChunkModel = mapper.readValue(params, FileUploadChunkModel.class); // fileUploadChunkModel.setSubSystem(subSystem); // fileUploadChunkModel.setEntity(entity); // logUploadedFileService.uploadToFileModel(file, fileUploadChunkModel); // // return new PrimitiveResponse(true); // } // @GraphQLMutation(name = "uploadFile") // public Boolean uploadFile(FileUpload fileUpload) { // // String fileContentType = fileUpload.getContentType(); // byte[] fileContent = fileUpload.getContent(); // // // Do something in order to persist the file :) // // // return true; // } // @CrossOrigin // @RequestMapping(method = RequestMethod.POST, consumes = MediaType.MULTIPART_FORM_DATA_VALUE) // @ResponseBody // public Map<String, Object> post(final MultipartHttpServletRequest httpServletRequest, @RequestParam String operations, @RequestParam String map) throws IOException { // // final Map<String, Object> operationsMap = GraphQLUploadExtension.process(operations, map, httpServletRequest::getFile); // // //noinspection unchecked // return execute( // request, // (String) operationsMap.getOrDefault("query", ""), // (Map<String, Object>) operationsMap.get("variables") // ); // } // public FSOController(GraphQL graphQL, GraphQLExecutor<NativeWebRequest> executor) { // super(graphQL, executor); // } /** * For Requests that follow the GraphQL Multipart Request Spec from: https://github.com/jaydenseric/graphql-multipart-request-spec * * The Request contains the following parts: * operations: JSON String with the GQL Query * map: Maps the multipart files to the variables of the GQL Query */ // @PostMapping( // value = "${graphql.spqr.http.endpoint:/graphql}", // consumes = {MediaType.MULTIPART_FORM_DATA_VALUE}, // produces = MediaType.APPLICATION_JSON_UTF8_VALUE // ) // @ResponseBody // public Object executeMultipartPost(@RequestPart("operations") String operations, // @RequestPart("map") String map, // MultipartHttpServletRequest multiPartRequest, // NativeWebRequest webRequest) throws IOException, ServletException { // GraphQLRequest graphQLRequest = new ObjectMapper().readerFor(GraphQLRequest.class).readValue(operations); // Map<String, ArrayList<String>> fileMap = new ObjectMapper().readerFor(Map.class).readValue(map); // // mapRequestFilesToVariables(multiPartRequest, graphQLRequest, fileMap); // return this.executeJsonPost(graphQLRequest, new GraphQLRequest(null, null, null), webRequest); // } // // /** // * Maps the files that were sent in a Multipart Request to the corresponding variables of a {@link GraphQLRequest}. // * This makes it possible to use a file input like a normal parameter in a GraphQLApi Method. // */ // private void mapRequestFilesToVariables(MultipartHttpServletRequest multiPartRequest, GraphQLRequest graphQLRequest, // Map<String, ArrayList<String>> fileMap) throws IOException, ServletException { // for (var pair : fileMap.entrySet()) { // String targetVariable = pair.getValue().get(0).replace("variables.", ""); // if(graphQLRequest.getVariables().containsKey(targetVariable)) { // Part correspondingFile = multiPartRequest.getPart(pair.getKey()); // graphQLRequest.getVariables().put(targetVariable, correspondingFile); // } // } // } // @GraphQLMutation // public void uploadTemplate(@GraphQLNonNull @GraphQLArgument(name = "itemTemplate") byte[] uploadFile) throws IOException { // Xcelite uploadTemplate = new Xcelite(Files.write(Files.createTempFile("temp", ".xlsx"), uploadFile).toFile()); // //CustomBeanSheetReader<TemplateItem> reader = new CustomBeanSheetReader<>(uploadTemplate.getSheet(0), TemplateItem.class); // //reader.skipHeaderRow(true); // // //return reader.read(); // } }
true
07989dc4be26076ab7d0bd9ca1b9ab3ab0f12760
Java
apache/asterixdb
/asterixdb/asterix-runtime/src/main/java/org/apache/asterix/runtime/evaluators/functions/ToNumberDescriptor.java
UTF-8
7,761
1.5625
2
[ "MIT", "BSD-3-Clause", "PostgreSQL", "Apache-2.0" ]
permissive
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.asterix.runtime.evaluators.functions; import java.io.DataOutput; import org.apache.asterix.common.annotations.MissingNullInOutFunction; import org.apache.asterix.dataflow.data.nontagged.serde.ABooleanSerializerDeserializer; import org.apache.asterix.formats.nontagged.SerializerDeserializerProvider; import org.apache.asterix.om.base.ADouble; import org.apache.asterix.om.base.AInt64; import org.apache.asterix.om.base.AMutableDouble; import org.apache.asterix.om.base.AMutableInt64; import org.apache.asterix.om.functions.BuiltinFunctions; import org.apache.asterix.om.functions.IFunctionDescriptorFactory; import org.apache.asterix.om.types.ATypeTag; import org.apache.asterix.om.types.BuiltinType; import org.apache.asterix.runtime.evaluators.base.AbstractScalarFunctionDynamicDescriptor; import org.apache.asterix.runtime.evaluators.common.NumberUtils; import org.apache.asterix.runtime.exceptions.TypeMismatchException; import org.apache.commons.lang3.mutable.MutableBoolean; import org.apache.hyracks.algebricks.core.algebra.functions.FunctionIdentifier; import org.apache.hyracks.algebricks.runtime.base.IEvaluatorContext; import org.apache.hyracks.algebricks.runtime.base.IScalarEvaluator; import org.apache.hyracks.algebricks.runtime.base.IScalarEvaluatorFactory; import org.apache.hyracks.api.dataflow.value.ISerializerDeserializer; import org.apache.hyracks.api.exceptions.HyracksDataException; import org.apache.hyracks.data.std.api.IPointable; import org.apache.hyracks.data.std.primitive.UTF8StringPointable; import org.apache.hyracks.data.std.primitive.VoidPointable; import org.apache.hyracks.data.std.util.ArrayBackedValueStorage; import org.apache.hyracks.dataflow.common.data.accessors.IFrameTupleReference; @MissingNullInOutFunction public class ToNumberDescriptor extends AbstractScalarFunctionDynamicDescriptor { private static final long serialVersionUID = 1L; public static final IFunctionDescriptorFactory FACTORY = ToNumberDescriptor::new; @Override public IScalarEvaluatorFactory createEvaluatorFactory(final IScalarEvaluatorFactory[] args) { return new IScalarEvaluatorFactory() { private static final long serialVersionUID = 1L; @Override public IScalarEvaluator createScalarEvaluator(final IEvaluatorContext ctx) throws HyracksDataException { final IScalarEvaluator inputEval = args[0].createScalarEvaluator(ctx); final IPointable inputArg = new VoidPointable(); final ArrayBackedValueStorage resultStorage = new ArrayBackedValueStorage(); final DataOutput out = resultStorage.getDataOutput(); final AMutableInt64 aInt64 = new AMutableInt64(0); final AMutableDouble aDouble = new AMutableDouble(0); final UTF8StringPointable utf8Ptr = new UTF8StringPointable(); final MutableBoolean maybeNumeric = new MutableBoolean(); @SuppressWarnings("unchecked") final ISerializerDeserializer<AInt64> INT64_SERDE = SerializerDeserializerProvider.INSTANCE.getSerializerDeserializer(BuiltinType.AINT64); @SuppressWarnings("unchecked") final ISerializerDeserializer<ADouble> DOUBLE_SERDE = SerializerDeserializerProvider.INSTANCE.getSerializerDeserializer(BuiltinType.ADOUBLE); return new IScalarEvaluator() { @Override public void evaluate(IFrameTupleReference tuple, IPointable result) throws HyracksDataException { inputEval.evaluate(tuple, inputArg); resultStorage.reset(); if (PointableHelper.checkAndSetMissingOrNull(result, inputArg)) { return; } byte[] bytes = inputArg.getByteArray(); int startOffset = inputArg.getStartOffset(); ATypeTag tt = ATypeTag.VALUE_TYPE_MAPPING[bytes[startOffset]]; switch (tt) { case TINYINT: case SMALLINT: case INTEGER: case BIGINT: case FLOAT: case DOUBLE: result.set(inputArg); break; case BOOLEAN: boolean b = ABooleanSerializerDeserializer.getBoolean(bytes, startOffset + 1); aInt64.setValue(b ? 1 : 0); INT64_SERDE.serialize(aInt64, out); result.set(resultStorage); break; case STRING: utf8Ptr.set(bytes, startOffset + 1, inputArg.getLength() - 1); if (NumberUtils.parseInt64(utf8Ptr, aInt64, maybeNumeric)) { INT64_SERDE.serialize(aInt64, out); result.set(resultStorage); } else if (maybeNumeric.booleanValue() && NumberUtils.parseDouble(utf8Ptr, aDouble)) { DOUBLE_SERDE.serialize(aDouble, out); result.set(resultStorage); } else { PointableHelper.setNull(result); } break; case ARRAY: case MULTISET: case OBJECT: PointableHelper.setNull(result); break; default: throw new TypeMismatchException(sourceLoc, getIdentifier(), 0, bytes[startOffset], ATypeTag.SERIALIZED_INT8_TYPE_TAG, ATypeTag.SERIALIZED_INT16_TYPE_TAG, ATypeTag.SERIALIZED_INT32_TYPE_TAG, ATypeTag.SERIALIZED_INT64_TYPE_TAG, ATypeTag.SERIALIZED_FLOAT_TYPE_TAG, ATypeTag.SERIALIZED_DOUBLE_TYPE_TAG, ATypeTag.SERIALIZED_BOOLEAN_TYPE_TAG, ATypeTag.SERIALIZED_STRING_TYPE_TAG, ATypeTag.SERIALIZED_ORDEREDLIST_TYPE_TAG, ATypeTag.SERIALIZED_UNORDEREDLIST_TYPE_TAG, ATypeTag.SERIALIZED_RECORD_TYPE_TAG); } } }; } }; } @Override public FunctionIdentifier getIdentifier() { return BuiltinFunctions.TO_NUMBER; } }
true
ad07d65da118208af45e7a17d891b05ef7e5703f
Java
huoyuanping/ShopCar
/src/com/et/shop/QueryGoodServlet.java
GB18030
3,424
2.40625
2
[]
no_license
package com.et.shop; import java.io.IOException; import java.io.PrintWriter; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.et.tools.DbUtils; import com.sun.java.swing.plaf.windows.resources.windows; public class QueryGoodServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //ַ response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); //ȡ String goodName=request.getParameter("goodName"); //صǰѯҳ out.print("<center>"); out.print("<form action=\"QueryGoodServlet\" method=get>"); out.print("<input type=\"text\" name=\"goodName\" value=\"\"+goodName+\"\"/>"); out.print("<input type=\"submit\" value=\"\"/>"); out.println("</form>"); out.print("</center>"); out.print("<div style=\"margin:0 auto; width:1100px;\">"); out.println("<table border=\"1\" >"); out.print("<tr>"); out.print("<th>ƷͼƬ</th>"); out.print("<th>Ʒ</th>"); out.print("<th width:500px>Ʒ</th>"); out.print("<th>Ʒ</th>"); out.print("<th>Ʒλ</th>"); //out.print("<th>Ʒ</th>"); out.print("<th></th>"); out.println("</tr>"); if(goodName==null){//goodName=nullʱ滻"" goodName=""; } //ѯ߼ String sql="select * from goods where name like '%"+goodName+"%'"; try { PreparedStatement pst=con.prepareStatement(sql); ResultSet rt=pst.executeQuery(); while(rt.next()){ //ͨץȡ String id=rt.getString("ID"); String imagePath=rt.getString("IMAGEPATH");//ƷͼƬ String name=rt.getString("NAME");//Ʒ String model=rt.getString("MODEL");//Ʒ double price=rt.getDouble("PRICE");//Ʒ String stock=rt.getString("STOCK");//Ʒλ //String descp=rt.getString("DESCP");//Ʒ out.print("<tr>"); out.println("<td>"); out.println("<img src=\""+request.getContextPath()+imagePath+"\">"); out.println("</td>"); out.println("<td>"+name+"</td>"); out.println("<td>"+model+"</td>"); out.println("<td>"+price+"</td>"); out.println("<td>"+stock+"</td>"); //out.println("<td>"+descp+"</td>"); out.println("<td><input type='button' value='빺ﳵ' onclick=\"window.location='CarServlet?id="+id+"';\"></td>"); out.println("</tr>"); } } catch (SQLException e) { e.printStackTrace(); } out.println("</table>"); out.print("</div>"); out.flush(); out.close(); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doGet(request, response); } /** * ȡ */ public static Connection con=null; @Override public void init() throws ServletException { con=DbUtils.getConnect(); } @Override public void destroy() { try { con.close(); } catch (SQLException e) { e.printStackTrace(); } } }
true
75ffc0af192fd2443e608efedc788973e1ab165c
Java
zavalacl/WhatsForDinner
/src/main/java/com/zavala/whatsfordinner/Text.java
UTF-8
324
2.65625
3
[]
no_license
package com.zavala.whatsfordinner; public class Text { private Text text; private double weight; public Text getText() { return text; } public double getWeight() { return weight; } public void setText(Text text) { this.text = text; } public void setWeight(double weight) { this.weight = weight; } }
true
d9661bd9a9d7aa64e101aa1dbd201bb15624142f
Java
zhoujunexercise/AnalysisProjectDependencies
/AnalysisProjectDependencies/src/main/java/com/ibm/vmi/lsdep/LsjarUtil.java
UTF-8
3,403
2.65625
3
[]
no_license
package com.ibm.vmi.lsdep; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.BufferedReader; import java.io.IOException; import java.util.List; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; public class LsjarUtil { public static String getSuffix(File file){ if(file==null) return ""; if(!file.isFile()) return ""; String name=file.getName(); int index = name.lastIndexOf("."); if (index < 0) return ""; return name.substring(index + 1); } public static String getClassName(File file) throws IOException{ String suffix=getSuffix(file); if(!suffix.equals("java")) return ""; FileReader reader = new FileReader("D://lbhdev//feisanWeb//src//265_url.txt"); BufferedReader br = new BufferedReader(reader); String line = null; while((line = br.readLine()) != null) { if(line.startsWith("package ")){ String className = line.substring(8); className = className.replaceAll(" ", ""); className = className.replaceAll(";", ""); className = className.replaceAll("\t", ""); br.close(); return ""; } } br.close(); reader.close(); return ""; } public static String cleanSpaces(String st){ int start=0; int i=0; for(i=0; i<st.length(); i++){ char ch=st.charAt(i); if(ch==' ' || ch=='\t'){ start++; } else break; } int end = st.length(); for(i=end-1; i>start; i--){ char ch=st.charAt(i); if(ch==' ' || ch=='\t'){ end=i; } else break; } if(start >= end) return ""; if(start>0 || end<st.length()){ st = st.substring(start, end); } return st; } public static String getLastTag(String st){ String tag = cleanSpaces(st); for(int i=tag.length()-1; i>=0; i--){ char ch=st.charAt(i); if(ch==' ' || ch=='\t'){ if(i==tag.length()-1) return ""; return tag.substring(i+1); } } return tag; } public static void sort(List <String> list){ class StringComparator implements Comparator<String>{ @Override public int compare(String s1, String s2){ return s1.compareTo(s2); } } StringComparator comparator = new StringComparator(); Collections.sort(list,comparator); } public static boolean append(List<String> list, String value){ if(list==null) return false; for(String v:list){ if(v.compareTo(value)==0) return false; } list.add(value); return true; } public static List<String> copyList(List<String> list){ if(list==null) return null; List<String> newList = new ArrayList<String>(); for(String s:list){ newList.add(s); } return newList; } public static List<String> append(List<String> dst, List<String> src){ if(src==null) return dst; if(dst==null) return copyList(src); for(String s:src){ append(dst,s); } return dst; } public static String getShortPath(String packageName){ for(int i=packageName.length()-1; i>=0; i--){ char ch = packageName.charAt(i); if(ch == '/' || ch == '\\'){ if(i==packageName.length()-1) return ""; return packageName.substring(i+1, packageName.length()); } } return packageName; } }
true
80d3bc73e8d34b4d5e78c53055fe289fc6e547f2
Java
JAYASELVAN/Prp
/Athelete&MedalCount.java
UTF-8
290
2.859375
3
[]
no_license
import java.util.*; public class Hello { public static void main(String[] args) { //Your Code Here String s; int n; Scanner sc=new Scanner(System.in); s=sc.nextLine(); n=sc.nextInt(); System.out.print(s+" won "+n+" medals"); } }
true
dbb649874be43738de607ae96027d3125cb19f17
Java
Magueye717/Cohort-management
/cohort-web/src/main/java/sn/edacy/web/cohort/CreateCohortBean.java
UTF-8
680
2.578125
3
[]
no_license
package sn.edacy.web.cohort; import javax.enterprise.inject.Model; import javax.inject.Inject; import sn.edacy.business.CohortService; import sn.edacy.model.Cohort; @Model public class CreateCohortBean { private Cohort cohort = new Cohort(); @Inject private CohortService cohortService; /** * Called when user save the object */ public void create() { cohortService.saveCohort(cohort); System.out.println("Nom de la cohorte " + cohort.getName() + " id: "+ cohort.getId()); } public String navigateToHome() { return "/index"; } public Cohort getCohort() { return cohort; } public void setCohort(Cohort cohort) { this.cohort = cohort; } }
true
1e9a1a521f75b8e6b222a248af01bae650382e26
Java
commercetools/commercetools-sdk-java-v2
/commercetools/commercetools-sdk-java-api/src/main/java-predicates-generated/com/commercetools/api/predicates/query/quote/QuoteSetCustomFieldActionQueryBuilderDsl.java
UTF-8
1,380
1.960938
2
[ "Apache-2.0", "GPL-2.0-only", "EPL-2.0", "CDDL-1.0", "MIT", "BSD-3-Clause", "Classpath-exception-2.0" ]
permissive
package com.commercetools.api.predicates.query.quote; import com.commercetools.api.predicates.query.*; public class QuoteSetCustomFieldActionQueryBuilderDsl { public QuoteSetCustomFieldActionQueryBuilderDsl() { } public static QuoteSetCustomFieldActionQueryBuilderDsl of() { return new QuoteSetCustomFieldActionQueryBuilderDsl(); } public StringComparisonPredicateBuilder<QuoteSetCustomFieldActionQueryBuilderDsl> action() { return new StringComparisonPredicateBuilder<>( BinaryQueryPredicate.of().left(new ConstantQueryPredicate("action")), p -> new CombinationQueryPredicate<>(p, QuoteSetCustomFieldActionQueryBuilderDsl::of)); } public StringComparisonPredicateBuilder<QuoteSetCustomFieldActionQueryBuilderDsl> name() { return new StringComparisonPredicateBuilder<>( BinaryQueryPredicate.of().left(new ConstantQueryPredicate("name")), p -> new CombinationQueryPredicate<>(p, QuoteSetCustomFieldActionQueryBuilderDsl::of)); } public StringComparisonPredicateBuilder<QuoteSetCustomFieldActionQueryBuilderDsl> value() { return new StringComparisonPredicateBuilder<>( BinaryQueryPredicate.of().left(new ConstantQueryPredicate("value")), p -> new CombinationQueryPredicate<>(p, QuoteSetCustomFieldActionQueryBuilderDsl::of)); } }
true
6c0c4a1cf604fd49307128abee3a775b6af07cb5
Java
reverseengineeringer/com.facebook.orca
/src/com/facebook/common/stringformat/StringFormatUtil.java
UTF-8
6,862
2.296875
2
[]
no_license
package com.facebook.common.stringformat; import com.facebook.proguard.annotations.DoNotStrip; import java.util.Formattable; import java.util.Formatter; import javax.annotation.Nullable; @DoNotStrip public class StringFormatUtil { private static int a(@Nullable StringBuilder paramStringBuilder, String paramString, Object[] paramArrayOfObject) { int i1 = 0; int j = 0; int i3 = paramString.length(); int n; int i; int k; label28: char c; int i2; if (paramStringBuilder == null) { n = 1; i = 0; k = 0; m = 0; if (i1 >= i3) { break label632; } if (m != 0) { break label157; } c = paramString.charAt(i1); if (c != '%') { break label106; } m = 1; i2 = 1; k = j; j = i; i = i2; } for (;;) { i2 = i1 + 1; i1 = i; i = j; j = k; k = i1; i1 = i2; break label28; n = 0; break; label106: if (n != 0) { i2 = j; j = i + 1; i = k; k = i2; } else { paramStringBuilder.append(c); i2 = j; j = i; i = k; k = i2; } } label157: int m = paramString.charAt(i1); if (m == 37) { if (n != 0) { i += 1; } for (;;) { i2 = i; i = k; k = j; m = 0; j = i2; break; paramStringBuilder.append('%'); } } if ((paramArrayOfObject == null) || (j >= paramArrayOfObject.length)) { if (n != 0) { i = -1; } } label609: label624: label632: do { return i; throw new AssertionError(); Object localObject1 = paramArrayOfObject[j]; switch (m) { default: if (n == 0) { break label624; } return -1; case 115: if ((localObject1 instanceof Formattable)) { if (n != 0) { return -1; } throw new AssertionError(); } if ((localObject1 instanceof String)) { if (n != 0) { i = ((String)localObject1).length() + i; } } break; } for (;;) { j += 1; break; paramStringBuilder.append(localObject1); continue; if (n != 0) { if (localObject1 == null) {} for (localObject1 = "null";; localObject1 = localObject1.toString()) { Object localObject2 = localObject1; if (localObject1 == null) { localObject2 = "null"; } m = ((String)localObject2).length(); paramArrayOfObject[j] = localObject2; i += m; break; } } paramStringBuilder.append(localObject1); continue; if (localObject1 == null) { if (n != 0) { i += 4; } else { paramStringBuilder.append("null"); } } else if ((localObject1 instanceof Integer)) { if (n != 0) { i += 11; } else { paramStringBuilder.append(((Number)localObject1).intValue()); } } else if ((localObject1 instanceof Short)) { if (n != 0) { i += 6; } else { paramStringBuilder.append(((Number)localObject1).intValue()); } } else if ((localObject1 instanceof Byte)) { if (n != 0) { i += 4; } else { paramStringBuilder.append(((Number)localObject1).intValue()); } } else { if (!(localObject1 instanceof Long)) { break label609; } if (n != 0) { i += 20; } else { paramStringBuilder.append(((Long)localObject1).longValue()); } } } if (n != 0) { return -1; } throw new AssertionError(); throw new AssertionError(); if (m != 0) { if (n != 0) { return -1; } throw new AssertionError(); } } while (k != 0); return -2; } public static String a(String paramString, Object... paramVarArgs) { int i = b(paramString, paramVarArgs); if (i == -1) { localObject = String.format(null, paramString, paramVarArgs); } do { return (String)localObject; localObject = paramString; } while (i == -2); Object localObject = new StringBuilder(i); a((StringBuilder)localObject, paramString, paramVarArgs); return ((StringBuilder)localObject).toString(); } @DoNotStrip public static void appendFormatStrLocaleSafe(StringBuilder paramStringBuilder, String paramString, Object... paramVarArgs) { int i = b(paramString, paramVarArgs); if (i == -1) { new Formatter(paramStringBuilder).format(null, paramString, paramVarArgs); return; } if (i == -2) { paramStringBuilder.append(paramString); return; } paramStringBuilder.ensureCapacity(i); a(paramStringBuilder, paramString, paramVarArgs); } private static int b(String paramString, Object[] paramArrayOfObject) { return a(null, paramString, paramArrayOfObject); } @DoNotStrip public static String formatStrLocaleSafe(String paramString) { return a(paramString, new Object[0]); } @DoNotStrip public static String formatStrLocaleSafe(String paramString, @Nullable Object paramObject) { return a(paramString, new Object[] { paramObject }); } @DoNotStrip public static String formatStrLocaleSafe(String paramString, @Nullable Object paramObject1, @Nullable Object paramObject2) { return a(paramString, new Object[] { paramObject1, paramObject2 }); } @DoNotStrip public static String formatStrLocaleSafe(String paramString, @Nullable Object paramObject1, @Nullable Object paramObject2, @Nullable Object paramObject3) { return a(paramString, new Object[] { paramObject1, paramObject2, paramObject3 }); } @DoNotStrip public static String formatStrLocaleSafe(String paramString, @Nullable Object paramObject1, @Nullable Object paramObject2, @Nullable Object paramObject3, @Nullable Object paramObject4) { return a(paramString, new Object[] { paramObject1, paramObject2, paramObject3, paramObject4 }); } @DoNotStrip public static String formatStrLocaleSafe(String paramString, Object... paramVarArgs) { return a(paramString, paramVarArgs); } } /* Location: * Qualified Name: com.facebook.common.stringformat.StringFormatUtil * Java Class Version: 6 (50.0) * JD-Core Version: 0.7.1 */
true
c7e58a2cc7a99e6fd3db49087b5b8da7f894928e
Java
NikitON/ce
/src/main/java/com/belkatechnologies/configeditor/checkers/app/DefaultRTChecker.java
UTF-8
1,077
2.484375
2
[]
no_license
package com.belkatechnologies.configeditor.checkers.app; import com.belkatechnologies.configeditor.checkers.InputChecker; import com.belkatechnologies.configeditor.gui.panels.workbench.mainPanel.InputPanel; import com.belkatechnologies.configeditor.model.RewardWord; import java.util.List; /** * Author: Nikita Khvorov * Date: 12.04.13 */ public class DefaultRTChecker extends InputChecker { @Override public void check(InputPanel inputPanel, StringBuilder sb) { String defaultRewardType = inputPanel.getParam("defaultRewardType"); if (!checkEmpty(defaultRewardType, "Reward Type", sb)) { checkExists(sb, defaultRewardType, inputPanel.getList("words")); } } private void checkExists(StringBuilder sb, String defaultRewardType, List words) { if (words != null) { for (Object word : words) { if (((RewardWord) word).getId().equals(defaultRewardType)) { return; } } } sb.append("Reward Type: Should be one of Words.\n"); } }
true
d12dc5f579e69e0c30fab4d0b62a0587280a5141
Java
Rahulgithub-code/JavaPractice
/src/com/practice/throw_and_throws.java
UTF-8
1,163
4.09375
4
[]
no_license
package com.practice; class NegativeRadiusException extends Exception{ @Override public String toString() { return "Radius can't be negative."; } @Override public String getMessage() { return "Radius can't be negative."; } } public class throw_and_throws { public static int divide(int a, int b) throws ArithmeticException{ return a/b; } public static double area(int r) throws NegativeRadiusException{ if (r<0){ throw new NegativeRadiusException(); } return Math.PI*r*r; } public static void main(String[] args) { /* throw => explicitly throw exception. throws => Gives information to the programmer for exception. */ try { int res=divide(4,1); System.out.println(res); } catch (Exception e){ System.out.println("Exception"); } //Example 2 try { double ar = area(-1); System.out.println(ar); } catch (NegativeRadiusException e){ System.out.println(e.getMessage()); } } }
true
531108de92e5d0cd8a14f3c58a0e31bf2c36ee6b
Java
xuxiaowei007/wt-console
/src/main/java/com/wt/uum2/web/wicket/panel/index/FooterPanel.java
UTF-8
963
1.9375
2
[]
no_license
package com.wt.uum2.web.wicket.panel.index; import org.apache.wicket.ajax.AjaxSelfUpdatingTimerBehavior; import org.apache.wicket.markup.html.basic.Label; import org.apache.wicket.model.Model; import org.apache.wicket.util.time.Duration; import com.wt.uum2.web.wicket.panel.BaseUUMPanel; /** * <pre> * 业务名: * 功能说明: * 编写日期: 2011-12-16 * 作者: Administrator * * 历史记录 * 1、修改日期: * 修改人: * 修改内容: * </pre> */ public class FooterPanel extends BaseUUMPanel { /** * */ private static final long serialVersionUID = 1L; /** * @param id * id */ public FooterPanel(String id) { super(id); AjaxSelfUpdatingTimerBehavior ajaxSelfUpdatingTimerBehavior = new AjaxSelfUpdatingTimerBehavior( Duration.seconds(30)); add(new Label("copyright", Model.of(getSetting().getCopyRight())).setEscapeModelStrings( false).add(ajaxSelfUpdatingTimerBehavior)); } }
true
9a2220722f8472d589e6b21d670c7a2077778171
Java
Gova988/Assignments
/lab9/src/com/lab9/Autenticate.java
UTF-8
593
2.921875
3
[]
no_license
package com.lab9; import java.util.Scanner; public class Autenticate { public static void main(String[] args) { Scanner scn= new Scanner(System.in); UsernameAndPassword up= (username, password) -> username.equals("Ajay") && password.equals("Asdfghjkl1234@#"); System.out.println("Enter User Name: "); String username= scn.next(); System.out.println(); System.out.println("Enter Password: "); String password= scn.next(); System.out.println(); System.out.println("Status: "+ up.validation(username, password)); scn.close(); } }
true
18938bc66f0996dd29bddf66ff25be803c1b1c9b
Java
p-nikolaichik/ebay-jbehave
/src/main/java/by/iba/nikolaichik/StoriesConfig.java
UTF-8
3,179
2.0625
2
[]
no_license
package by.iba.nikolaichik; import by.iba.nikolaichik.pages.LoginPage; import by.iba.nikolaichik.pages.PageFactory; import by.iba.nikolaichik.steps.HomePageSteps; import by.iba.nikolaichik.steps.LifeCycleSteps; import by.iba.nikolaichik.steps.LoginPageSteps; import by.iba.nikolaichik.steps.UserCabinetSteps; import com.github.valfirst.jbehave.junit.monitoring.JUnitReportingRunner; import org.jbehave.core.Embeddable; import org.jbehave.core.configuration.Configuration; import org.jbehave.core.configuration.Keywords; import org.jbehave.core.configuration.MostUsefulConfiguration; import org.jbehave.core.i18n.LocalizedKeywords; import org.jbehave.core.io.CodeLocations; import org.jbehave.core.io.LoadFromClasspath; import org.jbehave.core.io.StoryFinder; import org.jbehave.core.junit.JUnitStories; import org.jbehave.core.reporters.StoryReporterBuilder; import org.jbehave.core.steps.InjectableStepsFactory; import org.jbehave.core.steps.InstanceStepsFactory; import org.jbehave.core.steps.ParameterConverters; import org.junit.runner.RunWith; import java.util.List; import java.util.Locale; import java.util.Properties; import static org.jbehave.core.io.CodeLocations.codeLocationFromClass; import static org.jbehave.core.reporters.Format.*; /** * <p> * {@link Embeddable} class to run multiple textual stories via JUnit. * </p> * <p> * Stories are specified in classpath and correspondingly the {@link LoadFromClasspath} story loader is configured. * </p> */ @RunWith(JUnitReportingRunner.class) public class StoriesConfig extends JUnitStories { public StoriesConfig() { configuredEmbedder().embedderControls().doGenerateViewAfterStories(true).doIgnoreFailureInStories(true) .doIgnoreFailureInView(true).useThreads(2); } @Override public Configuration configuration() { Class<? extends Embeddable> embeddableClass = this.getClass(); ParameterConverters parameterConverters = new ParameterConverters(); Keywords keywords = new LocalizedKeywords(new Locale("en")); Properties properties = new Properties(); properties.setProperty("encoding", "UTF-8"); return new MostUsefulConfiguration() .useStoryLoader(new LoadFromClasspath(embeddableClass)) .useStoryReporterBuilder(new StoryReporterBuilder() .withCodeLocation(CodeLocations.codeLocationFromClass(embeddableClass)) .withDefaultFormats() .withKeywords(keywords) .withViewResources(properties) .withFormats(CONSOLE, TXT, HTML, XML)) .useParameterConverters(parameterConverters); } @Override public InjectableStepsFactory stepsFactory() { PageFactory pageFactory = new PageFactory(); return new InstanceStepsFactory(configuration(), new LifeCycleSteps(), new HomePageSteps(pageFactory), new LoginPageSteps(pageFactory), new UserCabinetSteps(pageFactory)); } @Override protected List<String> storyPaths() { return new StoryFinder().findPaths(codeLocationFromClass(this.getClass()), "**/*.story", "**/excluded*.story"); } }
true
eb5a3708b83d6937f5b49baa7b179c4930895260
Java
SchoenbeckZipCode/DiceyLab
/src/main/java/Simulation.java
UTF-8
1,118
3.390625
3
[]
no_license
import java.util.TreeMap; public class Simulation { public String simulation(Bins bins, Integer numberOfRolls){ String printSimulationResults="***\nSimulation of "+bins.getNumOfDice()+" dice tossed for "+numberOfRolls+" times.\n***\n"; for (int i = 2; i<= bins.getNumOfKeys(); i++){ String keyValue=String.format("%2d", i); String numberOfEachValue= String.format("%10d", bins.countTotals.get(i)); String percentOfTotal=String.format("%.2f", (bins.countTotals.get(i).floatValue()/numberOfRolls.floatValue())); int numberofStars= (int)Math.floor((bins.countTotals.get(i).floatValue()/numberOfRolls.floatValue() *100)); String starString= printStars(numberofStars); printSimulationResults+=keyValue+" :"+numberOfEachValue+": "+percentOfTotal+" "+starString +"\n"; } return printSimulationResults.trim(); } public String printStars(int numberOfStars){ String starString=""; for(int i=0;i<numberOfStars;i++){ starString+="*"; } return starString; } }
true
bf16b6594f64f1e2be5a6f4a4363b5c39819c9be
Java
mounika123-vallapuri/GreenAvenueBackend
/src/test/java/com/spring/test/SupplierTest.java
UTF-8
2,484
2.6875
3
[]
no_license
/*package com.spring.test; import static org.junit.Assert.*; import java.util.List; import org.junit.BeforeClass; import org.junit.Ignore; import org.junit.Test; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import com.spring.config.DataBaseConfig; import com.spring.dao.SupplierDAO; import com.spring.model.Supplier; @Ignore public class SupplierTest { static SupplierDAO supplierDAO; @BeforeClass public static void initialize() { @SuppressWarnings("resource") AnnotationConfigApplicationContext configApplnContext=new AnnotationConfigApplicationContext(); configApplnContext.scan("com.spring"); configApplnContext.register(DataBaseConfig.class); configApplnContext.refresh(); //SessionFactory sessionFactory=(SessionFactory)configApplnContext.getBean("DBConfig.class"); supplierDAO=(SupplierDAO)configApplnContext.getBean("supplierDAO"); } @Test public void addSupplierTest() { Supplier supplier=new Supplier(); supplier.setSupId(102); supplier.setSupName("Desktop"); supplier.setSupDesc("all kinds of desktops "); assertTrue(supplierDAO.addSupplier(supplier)); } @Test public void updateSupplierTest() { Supplier Supplier=new Supplier(); Supplier.setSupId(1002); Supplier.setSupName("JMShirt"); Supplier.setSupDesc("John Miller Shirt with Best Price"); int supId = 0; assertTrue(supplierDAO.updateSupplier(supId)); } @Ignore @Test public void deleteSupplierTest() { Supplier Supplier=new Supplier(); Supplier.setSupId(1002); int supId = 0; assertTrue(supplierDAO.deleteSupplier(supId)); } @Ignore @Test public void retrieveSupplierTest() { List<Supplier> listSupplier=supplierDAO.retrieveSupplier(); assertNotNull("Problem in Retriving ",listSupplier); this.show(listSupplier); } public void show(List<Supplier> listSupplier) { for(Supplier Supplier:listSupplier) { System.out.println("Supplier ID:"+Supplier.getSupId()); System.out.println("Supplier Name:"+Supplier.getSupName()); } } @Ignore @Test public void getSupplierTest() { Supplier Supplier=supplierDAO.getSupplier(1001); assertNotNull("Problem in Getting:",Supplier); System.out.println("Supplier ID:"+Supplier.getSupId()); System.out.println("Supplier Name:"+Supplier.getSupName()); System.out.println("Supplier Description = "+Supplier.getSupDesc()); } } */
true
d89e4030020cefe9594b270710785eac85071d03
Java
mariomartinezjr/FabricaProgramador
/Listas/src/Lista16/ErroLeitura.java
UTF-8
128
2.03125
2
[]
no_license
package Lista16; public class ErroLeitura extends Exception{ public ErroLeitura(Throwable causa) { super(causa); } }
true
1cf8d1779f35ae2e664e3b1f93da36ccdc0bf64e
Java
113-GittiGidiyor-Java-Spring-Bootcamp/fourth-homework-ahmetgltkn
/mappers/StudentMapper.java
UTF-8
339
2.3125
2
[ "MIT" ]
permissive
package dev.patika.hw04.mappers; import dev.patika.hw04.dto.CourseDTO; import dev.patika.hw04.dto.StudentDTO; import dev.patika.hw04.model.Course; import dev.patika.hw04.model.Student; public interface StudentMapper { Student mapFromStudentDTOtoStudent(StudentDTO dto); StudentDTO mapFromStudenttoStudentrDTO(Student student); }
true
2c1e1efe695b352b36006f6dbfea4ff7f9c7c460
Java
cyrilelijahaurino/DCIT50
/src/HasARelationship/Address.java
UTF-8
784
2.578125
3
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package HasARelationship; /** * * @author Cyril */ public class Address { protected String street; protected String barangay; protected String city; protected String province; public Address(String street, String barangay, String city, String province) { this.street = street; this.barangay = barangay; this.city = city; this.province = province; } @Override public String toString() { return "" + street + ", " + barangay + ", " + city + ", " + province; } }
true
6b96f408be12517d28dcb56dd94ac3418aa48aba
Java
dbenamara/excilyscdb
/src/main/java/dao/ComputerDao.java
UTF-8
4,979
2.515625
3
[]
no_license
package dao; import java.util.List; import java.util.Optional; import javax.sql.DataSource; import org.springframework.jdbc.core.namedparam.MapSqlParameterSource; import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate; import org.springframework.jdbc.core.namedparam.SqlParameterSource; import org.springframework.stereotype.Repository; import mapper.ComputerMapper; import model.Computer; /** * @author Djamel * */ @Repository public class ComputerDao { private NamedParameterJdbcTemplate namedParameterJdbcTemplate; private ComputerMapper computerMapper = new ComputerMapper(); private static final String CREATE_COMPUTER = "INSERT INTO computer (name, introduced, discontinued, company_id)" + " VALUES (:computerName, :introduced, :discontinued, :companyId);"; private static final String DELETE_COMPUTER = "DELETE FROM computer WHERE id = :id ;"; private static final String DELETE_COMPUTER_SELECTED = "DELETE FROM computer WHERE id IN (:id);"; private static final String UPDATE_COMPUTER = "UPDATE computer SET name= :name, introduced= :introduced, discontinued= :discontinued, company_id= :company_id WHERE id= :id;"; private static final String GET_ALL_COMPUTER = "SELECT computer.id , computer.name, introduced, discontinued, company_id, company.name FROM computer LEFT JOIN company ON company_id=company.id;"; private static final String GET_PAGE_COMPUTER = "SELECT computer.id, computer.name, computer.introduced , computer.discontinued , company_id, company.name FROM computer LEFT JOIN company ON company_id = company.id ORDER BY :order LIMIT :offset, :number;"; private static final String GET_COMPUTER_BY_NAME = "SELECT computer.id, computer.name, computer.introduced , computer.discontinued , company_id, company.name FROM computer LEFT JOIN company ON company_id = company.id WHERE computer.name LIKE :like ORDER BY :order LIMIT :offset, :number;"; private static final String GET_COMPUTER_BY_ID = "SELECT * FROM computer LEFT JOIN company ON company_id = company.id WHERE computer.id = :computer.id;"; protected static final String DELETE_COMPUTER_FROM_COMPANY = "DELETE FROM computer WHERE company_id= :id;"; public ComputerDao(DataSource dataSource) { this.namedParameterJdbcTemplate = new NamedParameterJdbcTemplate(dataSource); } public void create(Computer computer) { SqlParameterSource namedParameters = new MapSqlParameterSource() .addValue("computerName", computer.getName()) .addValue("introduced", computer.getIntroduced()) .addValue("discontinued", computer.getDiscontinued()) .addValue("companyId", computer.getCompany().getId()); this.namedParameterJdbcTemplate.update(CREATE_COMPUTER, namedParameters); } public List<Computer> readAll() { return this.namedParameterJdbcTemplate.query(GET_ALL_COMPUTER, this.computerMapper); } public void delete(int id) { SqlParameterSource namedParameters = new MapSqlParameterSource().addValue("id", id); this.namedParameterJdbcTemplate.update(DELETE_COMPUTER, namedParameters); } public void deleteAllComputerSelected(List<Integer> idList) { SqlParameterSource namedParameters = new MapSqlParameterSource().addValue("id", idList); this.namedParameterJdbcTemplate.update(DELETE_COMPUTER_SELECTED, namedParameters); } public Optional<Computer> find(int id) { SqlParameterSource namedParameters = new MapSqlParameterSource().addValue("computer.id", id); return Optional.of(this.namedParameterJdbcTemplate.queryForObject(GET_COMPUTER_BY_ID, namedParameters,this.computerMapper)); } public void update(Computer computer) { SqlParameterSource namedParameters = new MapSqlParameterSource() .addValue("id", computer.getId()) .addValue("name", computer.getName()) .addValue("introduced", computer.getIntroduced()) .addValue("discontinued", computer.getDiscontinued()) .addValue("company_id", computer.getCompany().getId()); this.namedParameterJdbcTemplate.update(UPDATE_COMPUTER, namedParameters); } public List<Computer> getPageComputer(int offset, int number, String orderBy) { SqlParameterSource namedParameters = new MapSqlParameterSource().addValue("order", orderBy).addValue("offset", offset) .addValue("number", number); return this.namedParameterJdbcTemplate.query(GET_PAGE_COMPUTER, namedParameters, this.computerMapper); } public List<Computer> findName(String like,int offset,int number, String orderBy) { SqlParameterSource namedParameters = new MapSqlParameterSource().addValue("like", '%'+like+'%') .addValue("offset", offset).addValue("number", number).addValue("order", orderBy); return this.namedParameterJdbcTemplate.query(GET_COMPUTER_BY_NAME, namedParameters, this.computerMapper); } public void deleteComputerFromCompany(int id) { SqlParameterSource namedParameters = new MapSqlParameterSource().addValue("id", id); this.namedParameterJdbcTemplate.update(DELETE_COMPUTER_FROM_COMPANY, namedParameters); } }
true
214eb21751520f94937180e9ef029fffe846f531
Java
ncats/gsrs-play
/app/ix/core/util/pojopointer/IDFilterPath.java
UTF-8
346
2.515625
3
[ "Apache-2.0" ]
permissive
package ix.core.util.pojopointer; import java.util.Objects; public class IDFilterPath extends LambdaPath{ private final String id; public IDFilterPath(final String id){ Objects.requireNonNull(id); this.id=id; } public String getId(){ return this.id; } @Override protected String thisURIPath() { return "(" + this.id + ")"; } }
true
961769412238ae9c04f201686f6c9e011f21d5fa
Java
orached/Duke_Java_Programing_Specialization
/Course4/Week1/TP1/SearchingEarthquakeDataStarterProgram/LargestQuakes.java
UTF-8
1,584
3.515625
4
[]
no_license
/** * Write a description of LargestQuakes here. * * @Orached * @24/12/2015 */ import java.util.*; public class LargestQuakes { public void findLargestQuakes(){ EarthQuakeParser parser = new EarthQuakeParser(); String source = "data/nov20quakedata.atom"; ArrayList<QuakeEntry> list = parser.read(source); int i = 1; for(QuakeEntry quake : list){ System.out.println(quake); i++; } System.out.println("There are "+(i-1)+" quakes in this file"); System.out.println("The quake with the largest magnitude is "+indexOfLargest(list)); System.out.println("And the 50 top largest are "); for(QuakeEntry quake : getLargest(list, 50)){ System.out.println(quake); } } public int indexOfLargest(ArrayList<QuakeEntry> data){ double max = 0; int maxIndex = 0; for(int i=0; i<data.size(); i++){ double magnitude = data.get(i).getMagnitude(); if(magnitude>max){ max = magnitude; maxIndex = i; } } return maxIndex; } public ArrayList<QuakeEntry> getLargest(ArrayList<QuakeEntry> quakeData, int howMany){ ArrayList<QuakeEntry> ret = new ArrayList<QuakeEntry>(); ArrayList<QuakeEntry> copy = new ArrayList<QuakeEntry>(quakeData); for(int i=0; i<howMany; i++){ QuakeEntry q = copy.get(indexOfLargest(copy)); ret.add(q); copy.remove(q); } return ret; } }
true
7ded7e7335e4334331ceda00c5ddb88793cf0b3c
Java
liuhegong/livemq
/src/main/java/cc/livemq/server/core/NioServer.java
UTF-8
1,197
2.375
2
[]
no_license
package cc.livemq.server.core; import cc.livemq.constant.Constant; import cc.livemq.core.Context; import lombok.extern.slf4j.Slf4j; import java.io.IOException; import java.net.InetSocketAddress; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.nio.channels.ServerSocketChannel; /** * */ @Slf4j public final class NioServer { private Selector selector; private ServerSocketChannel server; private ClientListener listener; public void start() throws IOException { Context.start(); selector = Selector.open(); server = ServerSocketChannel.open(); server.configureBlocking(false); server.bind(new InetSocketAddress(Constant.SERVER_PORT)); server.register(selector, SelectionKey.OP_ACCEPT); log.info("服务端信息:{}", server.getLocalAddress().toString()); // 启动客户端连接监听线程 listener = new ClientListener(selector); listener.start(); } public void stop() throws IOException { Context.stop(); if(listener != null) { listener.exit(); } server.close(); selector.close(); } }
true
fe554310eec98f90a2cb4d15e3529aa8ef472591
Java
NVSateesh/macgit1
/com.weather.SmokeTest/src/test/java/com/weather/driver/Driver.java
UTF-8
905
2.109375
2
[]
no_license
package com.weather.driver; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.util.NoSuchElementException; import java.util.Properties; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import io.appium.java_client.AppiumDriver; public abstract class Driver { protected static AppiumDriver Ad; //File file = new File("/Users/monocept/Documents/workspace_luna/com.weather.SmokeTest/Config/DataFile.Properties"); protected Properties properties = new Properties(); // public void Dr() // { // //driver=null; // Ad=null; // // } // // public boolean isElemenetPresent(By by) throws Exception // { // // try{ // //driver.findElement(by); // Ad.findElement(by); // return true; // }catch (NoSuchElementException e){ // return false; // } // } }
true
979bbf321073997ab5b029d50835c042eab9681e
Java
stackify/stackify-log-log4j12
/src/main/java/com/stackify/log/log4j12/NonReentrantAppender.java
UTF-8
1,780
2.609375
3
[ "Apache-2.0" ]
permissive
/* * Copyright 2013 Stackify * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.stackify.log.log4j12; import org.apache.log4j.AppenderSkeleton; import org.apache.log4j.spi.LoggingEvent; /** * Log4j appender that guards against reentering the same instance of the log4j appender * * @author Eric Martin */ public abstract class NonReentrantAppender extends AppenderSkeleton { /** * Guard against re-entering an appender from the same appender */ private final ThreadLocal<Boolean> guard = new ThreadLocal<Boolean>() { @Override protected Boolean initialValue() { return Boolean.FALSE; } }; /** * @see org.apache.log4j.AppenderSkeleton#append(org.apache.log4j.spi.LoggingEvent) */ @Override protected synchronized void append(final LoggingEvent event) { if (guard == null) { return; } if (guard.get() == null) { return; } if (guard.get().equals(Boolean.TRUE)) { return; } try { guard.set(Boolean.TRUE); subAppend(event); } finally { guard.remove(); } } /** * Performs the logging of the event after the reentrant guard has been verified * @param event The logging event */ protected abstract void subAppend(final LoggingEvent event); }
true
55468db6771e1fc92b928c4aefec99f362608c6e
Java
adelaid/Caretakers
/InfCareCaretakersWeb/build/generated/jax-wsCache/NeedWS/ws/ObjectFactory.java
UTF-8
3,266
2.109375
2
[]
no_license
package ws; import javax.xml.bind.JAXBElement; import javax.xml.bind.annotation.XmlElementDecl; import javax.xml.bind.annotation.XmlRegistry; import javax.xml.namespace.QName; /** * This object contains factory methods for each * Java content interface and Java element interface * generated in the ws package. * <p>An ObjectFactory allows you to programatically * construct new instances of the Java representation * for XML content. The Java representation of XML * content can consist of schema derived interfaces * and classes representing the binding of schema * type definitions, element declarations and model * groups. Factory methods for each of these are * provided in this class. * */ @XmlRegistry public class ObjectFactory { private final static QName _AddGeneralNeed_QNAME = new QName("http://ws/", "addGeneralNeed"); private final static QName _GetAllPatientNeed_QNAME = new QName("http://ws/", "getAllPatientNeed"); private final static QName _GetAllPatientNeedResponse_QNAME = new QName("http://ws/", "getAllPatientNeedResponse"); /** * Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: ws * */ public ObjectFactory() { } /** * Create an instance of {@link AddGeneralNeed } * */ public AddGeneralNeed createAddGeneralNeed() { return new AddGeneralNeed(); } /** * Create an instance of {@link GetAllPatientNeed } * */ public GetAllPatientNeed createGetAllPatientNeed() { return new GetAllPatientNeed(); } /** * Create an instance of {@link GetAllPatientNeedResponse } * */ public GetAllPatientNeedResponse createGetAllPatientNeedResponse() { return new GetAllPatientNeedResponse(); } /** * Create an instance of {@link PatientNeed } * */ public PatientNeed createPatientNeed() { return new PatientNeed(); } /** * Create an instance of {@link JAXBElement }{@code <}{@link AddGeneralNeed }{@code >}} * */ @XmlElementDecl(namespace = "http://ws/", name = "addGeneralNeed") public JAXBElement<AddGeneralNeed> createAddGeneralNeed(AddGeneralNeed value) { return new JAXBElement<AddGeneralNeed>(_AddGeneralNeed_QNAME, AddGeneralNeed.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link GetAllPatientNeed }{@code >}} * */ @XmlElementDecl(namespace = "http://ws/", name = "getAllPatientNeed") public JAXBElement<GetAllPatientNeed> createGetAllPatientNeed(GetAllPatientNeed value) { return new JAXBElement<GetAllPatientNeed>(_GetAllPatientNeed_QNAME, GetAllPatientNeed.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link GetAllPatientNeedResponse }{@code >}} * */ @XmlElementDecl(namespace = "http://ws/", name = "getAllPatientNeedResponse") public JAXBElement<GetAllPatientNeedResponse> createGetAllPatientNeedResponse(GetAllPatientNeedResponse value) { return new JAXBElement<GetAllPatientNeedResponse>(_GetAllPatientNeedResponse_QNAME, GetAllPatientNeedResponse.class, null, value); } }
true
d1dcd2a01e9451f863463f63a7c53baa69f0377c
Java
minuku/minuku-android
/minuku2-extended/src/main/java/labelingStudy/nctu/minuku/dao/ConnectivityDataRecordDAO.java
UTF-8
714
2.046875
2
[]
no_license
package labelingStudy.nctu.minuku.dao; import android.arch.persistence.room.Dao; import android.arch.persistence.room.Insert; import android.arch.persistence.room.Query; import java.util.List; import labelingStudy.nctu.minuku.model.DataRecord.ConnectivityDataRecord; /** * Created by tingwei on 2018/9/10. */ @Dao public interface ConnectivityDataRecordDAO { @Query("SELECT * FROM ConnectivityDataRecord") List<ConnectivityDataRecord> getAll(); @Query("SELECT * FROM ConnectivityDataRecord WHERE creationTime BETWEEN :start AND :end") List<ConnectivityDataRecord> getRecordBetweenTimes(long start, long end); @Insert void insertAll(ConnectivityDataRecord connectivityDataRecord); }
true
a405985112ef7f978c57d22c1a36bf1e5d89316d
Java
w1992wishes/daily-summary
/azkaban/azkaban-java-api/src/main/java/me/w1992wishes/azkaban/response/FetchAllProjectsResponse.java
UTF-8
409
1.820313
2
[]
no_license
package me.w1992wishes.azkaban.response; import java.util.List; /** * 查询所有项目的响应 * * @author Administrator */ public class FetchAllProjectsResponse extends AzkabanBaseResponse { private List<Project> projects; public List<Project> getProjects() { return projects; } public void setProjects(List<Project> projects) { this.projects = projects; } }
true
08d8f37b5d2187d16e95f1f74d4b7aa2f5a3db90
Java
jhwsx/KotlinInAction
/lib/src/main/java/com/kotlin/inaction/chapter_4/JavaInterfaceTest.java
UTF-8
1,387
3.59375
4
[ "MIT" ]
permissive
package com.kotlin.inaction.chapter_4; /** * @author wangzhichao * @since 2020/6/23 */ public class JavaInterfaceTest { interface ClickableJava { double PI = 3.14159126; // 可以声明常量 void click(); default void showOff() { System.out.println("I'm clickable!"); } } interface FocusableJava { default void setFocus(boolean b) { System.out.println("I " +(b ? "got" : "lost") + " focus"); } default void showOff() { System.out.println("I'm focusable!"); } } static class ButtonJava implements ClickableJava, FocusableJava { @Override public void click() { System.out.println("I was clicked"); } @Override public void showOff() { ClickableJava.super.showOff(); FocusableJava.super.showOff(); } } static class ButtonImplementsKotlin implements Clickable2, Focusable { @Override public void click() { } @Override public void showOff() { } @Override public void setFocus(boolean b) { } } public static void main(String[] args) { ButtonJava buttonJava = new ButtonJava(); buttonJava.showOff(); buttonJava.setFocus(true); buttonJava.click(); } }
true
1197b5491360d34d2c06884cb15298efbbfcdc4b
Java
cmFodWx5YWRhdjEyMTA5/smell-and-machine-learning
/ast_results/osmandapp_Osmand/OsmAnd/src/net/osmand/plus/resources/GeometryTilesCache.java
UTF-8
1,372
1.726563
2
[]
no_license
// isComment package net.osmand.plus.resources; import net.osmand.binary.BinaryVectorTileReader; import net.osmand.data.GeometryTile; import net.osmand.map.ITileSource; import net.osmand.plus.resources.AsyncLoadingThread.TileLoadDownloadRequest; import java.io.File; import java.io.IOException; public class isClassOrIsInterface extends TilesCache<GeometryTile> { public isConstructor(AsyncLoadingThread isParameter) { super(isNameExpr); isNameExpr = isIntegerConstant; } @Override public boolean isMethod(ITileSource isParameter) { return "isStringConstant".isMethod(isNameExpr.isMethod()); } @Override protected GeometryTile isMethod(TileLoadDownloadRequest isParameter) { GeometryTile isVariable = null; File isVariable = new File(isNameExpr.isFieldAccessExpr, isNameExpr.isFieldAccessExpr); if (isNameExpr.isMethod()) { try { isNameExpr = isNameExpr.isMethod(isNameExpr); isMethod(isNameExpr, isNameExpr.isMethod()); } catch (IOException isParameter) { isNameExpr.isMethod("isStringConstant", isNameExpr); } catch (OutOfMemoryError isParameter) { isNameExpr.isMethod("isStringConstant", isNameExpr); isMethod(); } } return isNameExpr; } }
true
ca1396884e3620cfb643661ec975895c2107c16d
Java
hkruni/sell
/src/main/java/com/imooc/util/CSVReportUtils.java
UTF-8
2,261
2.984375
3
[]
no_license
package com.imooc.util; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.util.List; /** * @author hukai * */ public class CSVReportUtils { public static String CSV_QUOTE = "\""; public static String CSV_QUOTE_ESCAPE = "\"\""; public static String CSV_DELIMITER = ","; public static char CSV_DELIMITER_CHAR = ','; public static String CSV_NEWLINE = "\r\n"; /** * 生成CSV格式的报表字符串 * * @param titles List<String> 报表标题 * @param data List<String[]> 报表数据 * @return CSV格式的报表字符串 */ public static String genCSVReport(List<String> titles, List<List<String>> data){ StringBuffer sb = new StringBuffer(); if(titles!=null){ for(String title: titles) { if(title==null){ title = ""; }else{ title = title.replaceAll(CSV_QUOTE, CSV_QUOTE_ESCAPE); } sb.append(CSV_QUOTE).append(title).append(CSV_QUOTE).append(CSV_DELIMITER); } if (sb.charAt(sb.length() - 1) == CSV_DELIMITER_CHAR){ sb.deleteCharAt(sb.length() - 1); } sb.append(CSV_NEWLINE); } if(data!=null){ for(List<String> items: data) { for(String item: items) { if(item==null){ item = ""; }else{ item = item.replaceAll(CSV_QUOTE, CSV_QUOTE_ESCAPE); } sb.append(CSV_QUOTE).append(item).append(CSV_QUOTE).append(CSV_DELIMITER); } if (sb.charAt(sb.length() - 1) == CSV_DELIMITER_CHAR){ sb.deleteCharAt(sb.length() - 1); } sb.append(CSV_NEWLINE); } } return sb.toString(); } public static void writeCsvData(String content,File file) throws IOException{ OutputStreamWriter fw = new OutputStreamWriter(new FileOutputStream(file.getAbsolutePath()), "gbk"); fw.write(content); fw.flush(); fw.close(); } }
true
26331314ab130e419c06a34a4339d4c2890aece3
Java
spring-projects/spring-data-examples
/jpa/deferred/src/main/java/example/repo/Customer202Repository.java
UTF-8
280
1.929688
2
[ "Apache-2.0" ]
permissive
package example.repo; import example.model.Customer202; import java.util.List; import org.springframework.data.repository.CrudRepository; public interface Customer202Repository extends CrudRepository<Customer202, Long> { List<Customer202> findByLastName(String lastName); }
true
9feab85d1ebe113cd238a9f471633392d5bb2525
Java
JadeByfield89/MatchLayoutMVVM
/app/src/main/java/com/permoveo/matchlayoutmvvm/data/MatchService.java
UTF-8
285
1.804688
2
[]
no_license
package com.permoveo.matchlayoutmvvm.data; import io.reactivex.Observable; import retrofit2.http.GET; import retrofit2.http.Url; /** * Created by byfieldj on 8/4/17. */ public interface MatchService { @GET("matchSample.json") Observable<MatchResponse> fetchMatches(); }
true
381f5dafbb7be2d2c540c1d5b93909191b681ddb
Java
platon777/OS-Process-Management
/Project-Code/src/Queue.java
UTF-8
1,184
3.421875
3
[]
no_license
class NodeQ<T> { public T data; public NodeQ<T> next; public NodeQ() { data = null; next = null; } public NodeQ(T val) { data = val; next = null; } } //to be used for the implementation of the waiting queue and the job queue. //----- Queue --------- public class Queue<T>{ private NodeQ<T> head, tail; private int size; /** Creates a new instance of LinkedQueue */ public Queue() { head = tail = null; size = 0; } public T peak() { return head.data; } public int length (){ return size; } public void deleteSpec(T e) { // delete a specific element in the Queue by its reference of data if (e == head.data) { head = head.next; } else { NodeQ<T> temp = head; while (temp.next.data != e) { temp = temp.next; } temp.next = temp.next.next; if(tail.data == e) tail = temp; } size--; if(size == 0) tail = null; } public void enqueue(T e) { if(tail == null){ head = tail = new NodeQ<T>(e); } else { tail.next = new NodeQ<T>(e); tail = tail.next; } size++; } public T serve() { T x = head.data; head = head.next; size--; if(size == 0) tail = null; return x; } }
true
53f295cb4c1dc371a70412dd2be6c51a0cc934e5
Java
superanni/Educational_Manager_System
/src/main/java/com/twoGroup/educational/mapper/TemplateInfoMapper.java
UTF-8
308
1.507813
2
[]
no_license
package com.twoGroup.educational.mapper; import com.twoGroup.educational.entities.TemplateInfo; import com.baomidou.mybatisplus.mapper.BaseMapper; /** * <p> * Mapper 接口 * </p> * * @author GroupTwo * @since 2019-05-26 */ public interface TemplateInfoMapper extends BaseMapper<TemplateInfo> { }
true
0c653482dd101aebf877a284b2f14ea2df3ba099
Java
Erikomoreira/java-poo
/src/br/com/devmedia/aula05/ClassB.java
UTF-8
281
2.15625
2
[]
no_license
package br.com.devmedia.aula05; public class ClassB { private String privado; protected String protegido; public String publico; String pacote; public static void main(String[] args) { //ClassD d = new ClassD(); //d.metodoD(); } }
true
e4d26fc98eb696d819c8d545979ddf8bf9aba7f4
Java
Beyondzhangxin/emergency_plan
/src/main/java/com/aiidc/sps/ep/parameter/EntEmPlanParameter.java
UTF-8
483
1.84375
2
[]
no_license
package com.aiidc.sps.ep.parameter; import org.hibernate.annotations.Subselect; @SuppressWarnings("serial") @Subselect("select a.*,b.name company_name,c.plan_type_name,d.usage_name " + "from em_response_plan a ,em_enterprise_info b ,em_response_plan_type c,em_response_plan_usage_type d " + "where a.company_id=b.id(+) and a.plan_type=c.plan_type_id and a.usage_scope=d.usage_id and a.company_id is not null") public class EntEmPlanParameter extends EmPlanParameter{ }
true
1f12eadd5f87d26404f3de1250f50a1f2ebc4922
Java
MohamedEldahma/SofraNewApp
/app/src/main/java/com/example/sofranewapp/adapter/ShowRestaurantClientRecyclerAdapter.java
UTF-8
5,793
1.867188
2
[]
no_license
package com.example.sofranewapp.adapter; import android.app.Activity; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.RatingBar; import android.widget.TextView; import com.example.sofranewapp.R; import com.example.sofranewapp.data.api.APiSofraResturant; import com.example.sofranewapp.data.api.RetrofitSofra; import com.example.sofranewapp.data.model.Generated.GeneratedDataUser; import com.example.sofranewapp.ui.fragment.user.ContentRestaurantComponentClientFragment; import java.util.List; import androidx.annotation.NonNull; import androidx.cardview.widget.CardView; import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentActivity; import androidx.recyclerview.widget.RecyclerView; import butterknife.BindView; import butterknife.ButterKnife; import static com.example.sofranewapp.helper.HelperMathod.LodeImageCircle; import static com.example.sofranewapp.helper.HelperMathod.getStartFragments; public class ShowRestaurantClientRecyclerAdapter extends RecyclerView.Adapter<ShowRestaurantClientRecyclerAdapter.ViewHolder> { List<GeneratedDataUser> ordersArrayList; Activity context; private APiSofraResturant apiServerRestaurant; private View itemLayoutView; private ViewHolder viewHolder; public static Integer idRestaurant; public static String PhotoUrl; public static String Name; public ShowRestaurantClientRecyclerAdapter(List<GeneratedDataUser> ordersArrayList, Activity context) { this.ordersArrayList = ordersArrayList; this.context = context; } @NonNull @Override public ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) { // create a new view layout pending itemLayoutView = LayoutInflater.from(viewGroup.getContext()) .inflate(R.layout.set_adapter_show_restaurant_client_recycler_sofra, null); // create ViewHolder viewHolder = new ViewHolder(itemLayoutView); /// get date MyItemRestaurantFragment apiServerRestaurant = RetrofitSofra.getRestaurant().create(APiSofraResturant.class); return viewHolder; } @Override public void onBindViewHolder(@NonNull final ViewHolder viewHolder, final int i) { // set title viewHolder.setAdapterShowRestaurantClientTVNameRestaurant.setText(ordersArrayList.get(i).getName()); viewHolder.setAdapterShowRestaurantClientTvMinimumRequest.setText(ordersArrayList.get(i).getMinimumCharger()); viewHolder.setAdapterShowRestaurantClientTvDeliveryCost.setText(ordersArrayList.get(i).getDeliveryCost()); viewHolder.setAdapterShowRestaurantClientRatingBarRestaurant.setRating(ordersArrayList.get(i).getRate()); if (ordersArrayList.get(i).getAvailability().equals("open")) { viewHolder.setAdapterShowRestaurantClientImgPhotoOnline.setImageResource(R.drawable.icons_online); viewHolder.setAdapterShowRestaurantClientTvOnline.setText("Open"); } else { viewHolder.setAdapterShowRestaurantClientImgPhotoOnline.setImageResource(R.drawable.icons_offline); viewHolder.setAdapterShowRestaurantClientTvOnline.setText("Close"); } LodeImageCircle(context, ordersArrayList.get(i).getPhotoUrl(), viewHolder.setAdapterShowRestaurantClientImgPhotoRestaurant); viewHolder.setAdapterItemsCardView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { idRestaurant = ordersArrayList.get(i).getId(); PhotoUrl = ordersArrayList.get(i).getPhotoUrl(); Name = ordersArrayList.get(i).getName(); Bundle bundle = new Bundle(); bundle.putInt("IdRestaurantFromCartOrShowAdapter", ordersArrayList.get(i).getId()); Fragment fragment = new ContentRestaurantComponentClientFragment(); Log.d("idRestaurantAdap", String.valueOf(ordersArrayList.get(i).getId())); fragment.setArguments(bundle); getStartFragments(((FragmentActivity) context).getSupportFragmentManager(), R.id.mainClientReplaceFragment, fragment); } }); } @Override public int getItemCount() { return ordersArrayList.size(); } // inner class to hold a reference to each item of RecyclerView class ViewHolder extends RecyclerView.ViewHolder { View view; @BindView(R.id.setAdapterShowRestaurantClientTVNameRestaurant) TextView setAdapterShowRestaurantClientTVNameRestaurant; @BindView(R.id.setAdapterShowRestaurantClientRatingBarRestaurant) RatingBar setAdapterShowRestaurantClientRatingBarRestaurant; @BindView(R.id.setAdapterShowRestaurantClientTvMinimumRequest) TextView setAdapterShowRestaurantClientTvMinimumRequest; @BindView(R.id.setAdapterShowRestaurantClientTvDeliveryCost) TextView setAdapterShowRestaurantClientTvDeliveryCost; @BindView(R.id.setAdapterShowRestaurantClientImgPhotoRestaurant) ImageView setAdapterShowRestaurantClientImgPhotoRestaurant; @BindView(R.id.setAdapterShowRestaurantClientImgPhotoOnline) ImageView setAdapterShowRestaurantClientImgPhotoOnline; @BindView(R.id.setAdapterShowRestaurantClientTvOnline) TextView setAdapterShowRestaurantClientTvOnline; @BindView(R.id.setAdapterItemsCardView) CardView setAdapterItemsCardView; ViewHolder(View itemLayoutView) { super(itemLayoutView); view = itemLayoutView; ButterKnife.bind(this, view); } } }
true
b91fd470abad4dbc7a4641df32fb39d01d3458a2
Java
RogerLwr/Foundation
/src/main/java/com/tianpingpai/model/Model.java
UTF-8
6,979
2.515625
3
[]
no_license
package com.tianpingpai.model; import android.os.Parcel; import android.os.Parcelable; import android.text.TextUtils; import android.util.Log; import com.tianpingpai.parser.JSONModelMapper; import org.json.JSONException; import org.json.JSONObject; import java.util.HashMap; import java.util.List; import java.util.Map; public class Model implements Parcelable { private HashMap<String, Object> itemMap = new HashMap<>(); private HashMap<String, List<?>> arrayMap = new HashMap<>(); public static final Creator<Model> CREATOR = new Creator<Model>() { @Override public Model createFromParcel(Parcel in) { Model m = new Model(); try { JSONObject json = new JSONObject(in.readString()); JSONModelMapper.mapObject( json,m); } catch (JSONException e) { e.printStackTrace(); } return m; } @Override public Model[] newArray(int size) { return new Model[size]; } }; public String getString(String key) { return get(key, String.class); } public Number getNumber(String key) { Object value = get(key); if (value != null && value instanceof Number) { return (Number) value; } return null; } public int getInt(String key) { Integer value = get(key, Integer.class); return value == null ? 0 : value; } public double getDouble(String key) { Double value = get(key, Double.class); if (value == null) { Integer intValue = get(key, Integer.class); if (intValue != null) { return intValue; } String stringValue = get(key, String.class); if (stringValue != null && !TextUtils.isEmpty(stringValue)) { try { return Double.parseDouble(stringValue); } catch (Exception e) { e.printStackTrace(); } } } return value == null ? 0 : value; } public Object get(String key) { return itemMap.get(key); } public boolean getBoolean(String key) { Boolean value = get(key, Boolean.class); Log.e("xx", value + ""); if (value != null) { return value; } return false; } public Model getModel(String key) { return get(key, Model.class); } public <T> T getKeyPath(String key, Class<T> clz) { String[] keys = key.split("."); T result; Model m = this; for (int i = 0; i < keys.length - 1; i++) { m = m.getModel(keys[i]); if (m == null) { return null; } } result = m.get(keys[keys.length - 1], clz); return result; } @SuppressWarnings("unchecked") public <T> T get(String key, Class<T> clz) { Object value = itemMap.get(key); if(value != null && value.getClass() == clz){ return (T) value; } return null; } public <T> void set(String key, T value) { if (value == null) { return;//TODO } itemMap.put(key, value); } public void setList(String key, List<?> models) { arrayMap.put(key, models); } public <T> List<T> getList(String key, Class<T> clz) { return (List<T>) arrayMap.get(key); } @Override public String toString() { StringBuilder sb = new StringBuilder(); for (String k : itemMap.keySet()) { sb.append(k); Object value = this.itemMap.get(k); sb.append(value); } for (String key : arrayMap.keySet()) { List<?> array = arrayMap.get(key); if (array != null) { sb.append(key); sb.append(":"); sb.append(array); } } return sb.toString(); } public long getLong(String key) { long result = 0; Long l = get(key, Long.class); if (l == null) { Integer intValue = get(key, Integer.class); if (intValue == null) { String stringValue = getString(key); if (stringValue != null) { try { result = Integer.parseInt(stringValue); } catch (Exception e) { e.printStackTrace(); } } } else { result = intValue.longValue(); } } else { result = l; } return result; } public String toJsonString() { StringBuilder sb = new StringBuilder(); sb.append("{"); // for (String k : itemMap.keySet()) { // HashMap<String, Object> itemMap = this.itemMap.get(k); for (String key : itemMap.keySet()) { sb.append("\""); sb.append(key); sb.append("\":"); sb.append(valueString(itemMap.get(key))); sb.append(","); } //TODO remove last? // } for (String k : arrayMap.keySet()) { List<?> array = arrayMap.get(k); sb.append("\""); sb.append(k); sb.append("\":"); sb.append(valueString(array)); sb.append(","); } if (sb.charAt(sb.length() - 1) == ',') { sb.deleteCharAt(sb.length() - 1); } sb.append("}"); return sb.toString(); } public static String valueString(List<?> array) { if(array == null || array.isEmpty()){ return "[]"; } StringBuilder sb = new StringBuilder(); sb.append("["); for (Object o : array) { sb.append(valueString(o)); sb.append(","); } if (sb.charAt(sb.length() - 1) == ',') { sb.deleteCharAt(sb.length() - 1); } sb.append("]"); return sb.toString(); } private static String valueString(Object obj) { if (obj == null) { return "null"; } if (obj instanceof Model) { Model m = (Model) obj; return m.toJsonString(); } if (obj instanceof String) { String s = (String) obj; return JSONObject.quote(s); } return obj.toString(); } public Map<String, Object> getAll() { return itemMap; } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(toJsonString()); } public static void copy(Model src,Model dest,String... names){ for(String name:names){ dest.set(name,src.get(name)); } } }
true
3ec889b0f521d4e06287807cdeb68555c01ee4a9
Java
JonasPhilbert/PRO1
/Lektion16_JavaFX02/src/opgave010203/MainApp.java
UTF-8
1,779
2.890625
3
[]
no_license
package opgave010203; import java.util.ArrayList; import java.util.Optional; import javafx.application.Application; import javafx.geometry.*; import javafx.scene.Scene; import javafx.scene.control.*; import javafx.scene.layout.GridPane; import javafx.stage.Stage; public class MainApp extends Application { public static void main(String[] args) { Application.launch(args); } @Override public void start(Stage stage) { stage.setTitle("Person List App"); GridPane pane = new GridPane(); initContent(pane); personWindow = new PersonInputWindow("Person Information", stage); Scene scene = new Scene(pane); stage.setScene(scene); stage.show(); } private ArrayList<Person> people = new ArrayList<>(); private ListView<String> peopleLView; private final Controller controller = new Controller(); private PersonInputWindow personWindow; private void initContent(GridPane pane) { pane.setGridLinesVisible(false); pane.setPadding(new Insets(20)); pane.setHgap(10); pane.setVgap(10); Label peopleLbl = new Label("People:"); pane.add(peopleLbl, 0, 0); peopleLView = new ListView<>(); pane.add(peopleLView, 0, 1); Button addBtn = new Button("Add Person"); pane.add(addBtn, 2, 2); addBtn.setOnAction(event -> controller.addBtnAction()); } private class Controller { public void addBtnAction() { personWindow.showAndWait(); if (personWindow.getPerson() != null) { Person pers = personWindow.getPerson(); people.add(pers); peopleLView.getItems().add(pers.toString()); } } } }
true
c594b4abc6c7f3df20d5a7903be4526801bb55e3
Java
jakubDoka/TWS-pluginV2
/src/main/java/theWorst/discord/DiscordCommands.java
UTF-8
3,693
2.609375
3
[]
no_license
package theWorst.discord; import mindustry.gen.Call; import org.javacord.api.entity.channel.Channel; import org.javacord.api.entity.channel.ServerChannel; import org.javacord.api.entity.message.Message; import org.javacord.api.entity.message.MessageAttachment; import org.javacord.api.entity.message.embed.EmbedBuilder; import org.javacord.api.event.message.MessageCreateEvent; import org.javacord.api.listener.message.MessageCreateListener; import java.awt.*; import java.util.HashMap; import java.util.List; import java.util.Optional; import static theWorst.Bot.*; public class DiscordCommands implements MessageCreateListener { public HashMap<String, Command> commands = new HashMap<>(); public void registerCommand(Command c){ commands.put(c.name,c); } public boolean hasCommand(String command){ return commands.containsKey(command); } @Override public void onMessageCreate(MessageCreateEvent event) { String message = event.getMessageContent(); if(event.getMessageAuthor().isBotUser()) { if(event.isPrivateMessage()) { Call.sendMessage(event.getMessageContent()); } return; } if(!message.startsWith(config.prefix)) return; Channel chan = config.channels.get("commands"); if(chan != null && chan.getId() != event.getChannel().getId()){ String msg = "This is not channel for commands."; Optional<ServerChannel> optionalServerChannel = chan.asServerChannel(); if(optionalServerChannel.isPresent()) msg+= " Go to "+optionalServerChannel.get().getName()+"."; event.getChannel().sendMessage(msg); return; } int nameLength = message.indexOf(" "); if(nameLength<0){ runCommand(message.replace(config.prefix,""),new CommandContext(event,new String[0],null)); return; } String theMessage = message.substring(nameLength+1); String[] args = theMessage.split(" "); String name = message.substring(config.prefix.length(),nameLength); runCommand(name,new CommandContext(event,args,theMessage)); } /**Validates command**/ private void runCommand(String name, CommandContext ctx) { Command command=commands.get(name); if(command==null){ ctx.reply("Sorry i don t know this command. Try "+config.prefix+"help."); return; } if(!command.hasPerm(ctx)){ EmbedBuilder msg= new EmbedBuilder() .setColor(Color.red) .setTitle("ACCESS DENIED!") .setDescription("You don't have high enough permission to use this command."); ctx.channel.sendMessage(msg); return; } Message message=ctx.event.getMessage(); List<MessageAttachment> mas = message.getAttachments(); boolean tooFew = ctx.args.length<command.minArgs,tooMatch=ctx.args.length>command.maxArgs; boolean correctFiles = command.attachment==null || (mas.size() == 1 && mas.get(0).getFileName().endsWith(command.attachment)); if(tooFew || tooMatch || !correctFiles){ EmbedBuilder eb= new EmbedBuilder() .setColor(Color.red) .setDescription("Valid format : " + config.prefix + name + " " + command.argStruct ); if(tooFew) eb.setTitle("TOO FEW ARGUMENTS!" ); else if(tooMatch) eb.setTitle( "TOO MATCH ARGUMENTS!"); else eb.setTitle("INCORRECT ATTACHMENT!"); ctx.channel.sendMessage(eb); return; } command.run(ctx); } }
true
319fc5aad5d20370df1c77f6562b5a01012e17ad
Java
cha63506/CompSecurity
/wellfargo/src/com/kofax/kmc/kut/utilities/appstats/AppStatsWritetoFileEvent.java
UTF-8
1,171
1.796875
2
[]
no_license
// Decompiled by Jad v1.5.8e. Copyright 2001 Pavel Kouznetsov. // Jad home page: http://www.geocities.com/kpdus/jad.html // Decompiler options: braces fieldsfirst space lnc package com.kofax.kmc.kut.utilities.appstats; import com.kofax.kmc.kut.utilities.error.ErrorInfo; import java.util.EventObject; public class AppStatsWritetoFileEvent extends EventObject { private static final long serialVersionUID = 0x6b5e08628f559c45L; private AppStatsWriteFileListener.WriteFileStatus a; private float b; private ErrorInfo c; public AppStatsWritetoFileEvent(Object obj, AppStatsWriteFileListener.WriteFileStatus writefilestatus, float f, ErrorInfo errorinfo) { super(obj); a = writefilestatus; b = f; c = errorinfo; } void a(float f) { b = f; } void a(AppStatsWriteFileListener.WriteFileStatus writefilestatus) { a = writefilestatus; } public ErrorInfo getErrorInfo() { return c; } public float getPercentComplete() { return b; } public AppStatsWriteFileListener.WriteFileStatus getWritetoFileStatus() { return a; } }
true
4e9dc73242bebf4fe9f73ccc12daf5b55059fca0
Java
satyamleo77-7/RestMicro
/src/main/java/com/test/myproject/restwebservice/dao/PersonRepository.java
UTF-8
1,271
2.484375
2
[]
no_license
package com.test.myproject.restwebservice.dao; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.persistence.Query; import javax.persistence.TypedQuery; import org.springframework.stereotype.Repository; import com.test.myproject.restwebservice.model.Person; @Repository public class PersonRepository { @PersistenceContext EntityManager entityManager; public Person findPersonById(int id) { Person personFromDb = entityManager.find(Person.class, id); return personFromDb; } public List<Person> findAllPerson() { List<Person> personList = entityManager.createNamedQuery("get_all_person", Person.class).getResultList(); return personList; } /** * using named query with sql result set mapping, but using jpql only */ public Person findAllIdAndAddress(int id) { TypedQuery<Person> query = entityManager.createNamedQuery("get_only_id_address", Person.class); query.setParameter("personId", id); Person person = query.getSingleResult(); return person; } public List<Person> findAllByNativeSqlQuery() { Query query = entityManager.createNativeQuery("Select * from Person", Person.class); List<Person> personList = query.getResultList(); return personList; } }
true
536ba936153ecc3d22444d22dd738453d2319f0d
Java
OG-Kloud/Ore-Redistribution
/src/main/java/kloud/ore/handler/CreativeTabHandler.java
UTF-8
1,050
2.53125
3
[]
no_license
package kloud.ore.handler; import net.kloudspace.util.IKHandler; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.init.Items; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; public class CreativeTabHandler implements IKHandler{ public static CreativeTabs ORES; public static CreativeTabs TOOLS; public static CreativeTabs ITEMS; public void init() { ORES = tabCreater("Ores & Ingots", Items.IRON_INGOT); TOOLS = tabCreater("Tools", ToolHandler.flint_pickaxe); ITEMS = tabCreater("Misc.", ItemHandler.copperIngot); } /** Creates a CreativeTab * * @param name of the new creative tab to create * @param display - Item to display on the tab * @return the newly created {@link CreativeTab} */ public CreativeTabs tabCreater(String name, final Item display) { return new CreativeTabs(name){ @Override public ItemStack getTabIconItem() { return new ItemStack(display); } }; } @Override public void register() { } }
true
7a5e4a2e4c06ca76d3d957313d841ddd3db864a9
Java
wiglenet/wigle-wifi-wardriving
/wiglewifiwardriving/src/main/java/net/wigle/wigleandroid/listener/LeScanUpdater.java
UTF-8
250
1.640625
2
[ "BSD-2-Clause" ]
permissive
package net.wigle.wigleandroid.listener; import android.bluetooth.le.ScanResult; import android.location.Location; public interface LeScanUpdater { void handleLeScanResult(final ScanResult scanResult, Location location, final boolean batch); }
true
030a5a5ac9ed5ae3125f2398a94a312e2d61eabb
Java
MonaRazbani/online-shop
/src/dataAccess/ProductDaos/ReadableItemProductsDao.java
UTF-8
2,675
2.609375
3
[]
no_license
package dataAccess.ProductDaos; import dataAccess.DataBaseAccess; import models.enums.ElectronicType; import models.enums.ProductStatus; import models.enums.PurchaseStatus; import models.enums.ReadableItemsType; import models.products.Electronic; import models.products.Product; import models.products.ReadableItems; import models.products.Shoes; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.Collections; import java.util.List; public class ReadableItemProductsDao extends DataBaseAccess { public ReadableItemProductsDao() throws ClassNotFoundException, SQLException { super(); } public List<ReadableItems> displayReadableProduct() throws SQLException { if (getConnection() != null) { List<ReadableItems> readableItemPurchase = new ArrayList<>(); Statement statement = getConnection().createStatement(); String sql = "SELECT product.id, product.name,product.cost,product.company,product.status,readable_item_product.readable_item_Type,readable_item_product.subject,product.wiki FROM (product INNER JOIN readable_item_product ON product.id = id_readable_item);" ; ResultSet resultSet = statement.executeQuery(sql); while (resultSet.next()) { //product_id, name, cost, company, status, electronic_type ReadableItems readableItem = new ReadableItems(); readableItem.setName(resultSet.getString(2)); readableItem.setCost(resultSet.getDouble(3)); readableItem.setCompanyName(resultSet.getString(4)); readableItem.setStatus(ProductStatus.valueOf(resultSet.getString(5))); readableItem.setType(ReadableItemsType.valueOf(resultSet.getString(6))); readableItem.setSubject(resultSet.getString(7)); readableItem.setWiki(resultSet.getInt(8)); readableItemPurchase.add(readableItem); } return readableItemPurchase; } else return Collections.emptyList(); } public int save(ReadableItems readableItems, int readableItemId ) throws SQLException { if (getConnection() != null) { Statement statement = getConnection().createStatement(); String sql = String.format("insert into `readable_item_product` (`id_readable_item`,`readable_item_Type`,`subject`) VALUES ('%d','%s','%s')" , readableItemId, readableItems.getType(), readableItems.getSubject(), readableItems.getStatus()); return statement.executeUpdate(sql); } else return -1; } }
true
366968693f6af06efd65a9f7d1f2cfb4a382997d
Java
amikhalev/Sprinklers
/src/main/java/org/amikhalev/sprinklers/repositories/ProgramSectionRepository.java
UTF-8
295
1.609375
2
[]
no_license
package org.amikhalev.sprinklers.repositories; import org.amikhalev.sprinklers.model.ProgramSection; import org.springframework.data.repository.CrudRepository; /** * Created by alex on 4/30/15. */ public interface ProgramSectionRepository extends CrudRepository<ProgramSection, Integer> { }
true
37c7fe07b61230a30a6e94c0d7a0e6494d3e7d10
Java
lily-elephant/api-yinao
/src/main/java/yinao/qualityLife/model/domain/Feedback.java
UTF-8
1,741
2.0625
2
[]
no_license
package yinao.qualityLife.model.domain; public class Feedback { private String cid ; private String clienttype ; private String comment ; private String userid ; private String create_time ; private String replyer ; private String reply ; private String state ; private String isanswer ; private String name ; private String username ; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getIsanswer() { return isanswer; } public void setIsanswer(String isanswer) { this.isanswer = isanswer; } public Feedback() {} public String getCid() { return cid; } public void setCid(String cid) { this.cid = cid; } public String getClienttype() { return clienttype; } public void setClienttype(String clienttype) { this.clienttype = clienttype; } public String getComment() { return comment; } public void setComment(String comment) { this.comment = comment; } public String getUserid() { return userid; } public void setUserid(String userid) { this.userid = userid; } public String getCreate_time() { return create_time; } public void setCreate_time(String create_time) { this.create_time = create_time; } public String getReplyer() { return replyer; } public void setReplyer(String replyer) { this.replyer = replyer; } public String getReply() { return reply; } public void setReply(String reply) { this.reply = reply; } public String getState() { return state; } public void setState(String state) { this.state = state; } }
true
5942aff49de3bea421b789a1f647cadc87c58305
Java
daixuzhong/WebUIAutoTest_Future_BM
/src/test/java/cn/dxz/pages/AllBudgetPage.java
UTF-8
1,047
1.9375
2
[]
no_license
package cn.dxz.pages; import cn.dxz.base.BasePage; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; /** * @author daixuzhong * @title: AllBudgetPage * @description: 全面预算页面 * @date 2019/5/10 */ public class AllBudgetPage extends BasePage { //预算执行 @FindBy(xpath = "/html/body/div/aside/div[1]/div/div/div/ul/li[4]/a") private WebElement budgetExecute; //新建流程 @FindBy(xpath = "/html/body/div/aside/div[1]/div/div/div/ul/li[4]/ul/li/a") private WebElement newProcess; //费用报销 @FindBy(xpath = "/html/body/div/div/ng-view/ng-include/div/div[2]/div/div[2]/div/a[1]") private WebElement expenseBX; public AllBudgetPage(WebDriver driver) { super(driver); } public WebElement getExpenseBX() { return expenseBX; } public WebElement getNewProcess() { return newProcess; } public WebElement getBudgetExecute() { return budgetExecute; } }
true
0615bd52465882837e82cf9bf2c07ee45d5ed4df
Java
Micromoving/bcp
/代码bcp1.0/010_source/src/main/java/cn/micromoving/bcp/modules/hr/service/TeacherQualificationService.java
UTF-8
1,138
1.992188
2
[ "Apache-2.0" ]
permissive
package cn.micromoving.bcp.modules.hr.service; import java.util.List; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import cn.micromoving.bcp.common.service.CrudService; import cn.micromoving.bcp.modules.hr.dao.TeacherQualificationDao; import cn.micromoving.bcp.modules.hr.entity.Employee; import cn.micromoving.bcp.modules.hr.entity.TeacherQualification; @Service @Transactional(readOnly = true) public class TeacherQualificationService extends CrudService<TeacherQualificationDao, TeacherQualification>{ public TeacherQualification getId(String id){ TeacherQualification teacherQualification = new TeacherQualification(); teacherQualification = dao.getId(id); return teacherQualification; } public List<TeacherQualification> findAllList(TeacherQualification teacherQualification) { teacherQualification.getSqlMap().put("dsf", dataScopeFilter(teacherQualification.getCurrentUser(), "o", "a")); List<TeacherQualification> teacherQualificationList = dao.findAllList(teacherQualification); return teacherQualificationList; } }
true
14f29e03842d3a4ffa7b3804863a0d0d8ca19d2b
Java
bellmit/zycami-ded
/src/main/java/com/google/common/reflect/TypeToken$3.java
UTF-8
1,729
2.0625
2
[]
no_license
/* * Decompiled with CFR 0.151. */ package com.google.common.reflect; import com.google.common.reflect.TypeToken; import com.google.common.reflect.TypeVisitor; import java.lang.reflect.GenericArrayType; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.lang.reflect.TypeVariable; import java.lang.reflect.WildcardType; public class TypeToken$3 extends TypeVisitor { public final /* synthetic */ TypeToken this$0; public TypeToken$3(TypeToken typeToken) { this.this$0 = typeToken; } public void visitGenericArrayType(GenericArrayType type) { Type[] typeArray = new Type[1]; type = type.getGenericComponentType(); typeArray[0] = type; this.visit(typeArray); } public void visitParameterizedType(ParameterizedType type) { Type[] typeArray = type.getActualTypeArguments(); this.visit(typeArray); typeArray = new Type[1]; type = type.getOwnerType(); typeArray[0] = type; this.visit(typeArray); } public void visitTypeVariable(TypeVariable object) { CharSequence charSequence = new StringBuilder(); Type type = TypeToken.access$500(this.this$0); charSequence.append(type); charSequence.append("contains a type variable and is not safe for the operation"); charSequence = charSequence.toString(); object = new IllegalArgumentException((String)charSequence); throw object; } public void visitWildcardType(WildcardType typeArray) { Type[] typeArray2 = typeArray.getLowerBounds(); this.visit(typeArray2); typeArray = typeArray.getUpperBounds(); this.visit(typeArray); } }
true
2bed21739bb68d8806ccee3f1d0a99d6b7b0aa50
Java
AESPROJECT/track_task
/app/src/main/java/com/example/autoemergencyapp/ServicesActivity.java
UTF-8
9,929
2.015625
2
[]
no_license
package com.example.autoemergencyapp; import android.Manifest; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.pm.PackageManager; import android.location.Location; import android.location.LocationManager; import android.net.Uri; import android.provider.Settings; import android.support.v4.app.ActivityCompat; import android.support.v4.content.ContextCompat; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.telephony.SmsManager; import android.telephony.TelephonyManager; import android.view.View; import android.widget.Button; import android.widget.RadioButton; import android.widget.Toast; public class ServicesActivity extends AppCompatActivity implements View.OnClickListener { private LocationManager locationManager; private TelephonyManager Tell; private static final int REQUEST_CALL=1; private static final int REQUEST_LOCATION = 2; private static final int REQUEST_SEND_SMS=3; private static final int REQUEST_PHONE_NUM=4; private RadioButton illnessEmergency, AccidenttEmergency, FireEmergency; private Button call, track; private static final String PhoneNumber = "0788097599"; String link, Msg = "My Location is : "; String lattitude,longitude; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_services); call = findViewById(R.id.callbtn); track=findViewById(R.id.trackbtn); illnessEmergency = findViewById(R.id.illness); AccidenttEmergency = findViewById(R.id.accident); FireEmergency = findViewById(R.id.fire); Tell = (TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE); call.setOnClickListener(this); track.setOnClickListener(this); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.trackbtn: Toast.makeText(this, "Track", Toast.LENGTH_LONG).show(); break; case R.id.callbtn: makeCall(); break; } } private void makeCall() { if(ContextCompat.checkSelfPermission(ServicesActivity.this, Manifest.permission.CALL_PHONE)!= PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(ServicesActivity.this, new String[]{Manifest.permission.CALL_PHONE},REQUEST_CALL); } else { String dial="tel:"+PhoneNumber; startActivity(new Intent(Intent.ACTION_CALL, Uri.parse(dial))); } GetLocation(); sendMsg(); } private void GetLocation() { locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE); if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) { buildAlertMessageNoGps(); } else if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) { getCurrentLocation(); } locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE); if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) { buildAlertMessageNoGps(); } else if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) { getCurrentLocation(); } } private void sendMsg() { if(ContextCompat.checkSelfPermission(this, Manifest.permission.SEND_SMS)!= PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(ServicesActivity.this, new String[]{Manifest.permission.SEND_SMS},REQUEST_SEND_SMS); } else { try { SmsManager smsmanage = SmsManager.getDefault(); Msg += link + "\n"; getType(); smsmanage.sendTextMessage( PhoneNumber, null, Msg, null, null ); Toast.makeText(this, "SMS SENT!", Toast.LENGTH_LONG ).show(); } catch (Exception c) { Toast.makeText(this, "SMS NOT SENT!", Toast.LENGTH_LONG ).show(); } } } private void buildAlertMessageNoGps() { final AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage("Please Turn ON your GPS Connection").setCancelable(false) .setPositiveButton("Yes", new DialogInterface.OnClickListener() { public void onClick(final DialogInterface dialog, final int id) { startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS)); } }).setNegativeButton("No", new DialogInterface.OnClickListener() { public void onClick(final DialogInterface dialog, final int id) { dialog.cancel(); } }); final AlertDialog alert = builder.create(); alert.show(); } private void getCurrentLocation() { if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(ServicesActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_LOCATION); } else { Location location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER); Location location1 = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); Location location2 = locationManager.getLastKnownLocation(LocationManager. PASSIVE_PROVIDER); if (location != null) { double lat = location.getLatitude(); double lng = location.getLongitude(); Uri.Builder builder = new Uri.Builder(); builder.scheme("https").authority("www.google.com").appendPath("maps").appendPath("dir").appendPath("") .appendQueryParameter("api", "1").appendQueryParameter("destination", lat + "," + lng); String url = builder.build().toString(); link = "Directions" + url; Intent i = new Intent(Intent.ACTION_VIEW); i.setData(Uri.parse(url)); startActivity(i); } else if (location1 != null) { double latti = location1.getLatitude(); double longi = location1.getLongitude(); lattitude = String.valueOf(latti); longitude = String.valueOf(longi); Msg += "Caller current location is: " + lattitude + ", " + longitude; } else if (location2 != null) { double latti = location2.getLatitude(); double longi = location2.getLongitude(); lattitude = String.valueOf(latti); longitude = String.valueOf(longi); Msg += "Caller current location is: " + lattitude + ", " + longitude; } else Toast.makeText(this,"Unble to Trace your location",Toast.LENGTH_SHORT).show(); } } private void makephoneCall(){ if(ContextCompat.checkSelfPermission(this,Manifest.permission.READ_PHONE_NUMBERS)!= PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(ServicesActivity.this, new String[]{Manifest.permission.READ_PHONE_NUMBERS},REQUEST_CALL); } else { makeCall(); } } private void getPhoneNumber() { if(ContextCompat.checkSelfPermission(ServicesActivity.this, Manifest.permission.READ_PHONE_STATE)!= PackageManager.PERMISSION_GRANTED) { if(ActivityCompat.shouldShowRequestPermissionRationale(ServicesActivity.this, Manifest.permission.READ_PHONE_STATE)) ActivityCompat.requestPermissions(ServicesActivity.this, new String[]{Manifest.permission.READ_PHONE_STATE}, 1); else ActivityCompat.requestPermissions(ServicesActivity.this, new String[]{Manifest.permission.READ_PHONE_STATE}, 1); } else { //do nothing } } private void getType() { if (illnessEmergency.isChecked()) { Msg += "I Need Illness Emergency"; } else if(FireEmergency.isChecked()) { Msg += "I Need Fire Emergency"; } else if(AccidenttEmergency.isChecked()) { Msg += "I Need Accident Emergency"; } } @Override public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) { if(requestCode==REQUEST_CALL) { if(grantResults.length >0 && grantResults[0] ==PackageManager.PERMISSION_GRANTED) { makeCall(); }else Toast.makeText(this,"Permission Denited :(",Toast.LENGTH_SHORT).show(); } if(requestCode==REQUEST_LOCATION){ if(grantResults.length >0 && grantResults[1] ==PackageManager.PERMISSION_GRANTED) { GetLocation(); }else Toast.makeText(this,"Permission Denited :(",Toast.LENGTH_SHORT).show(); } if(requestCode==REQUEST_SEND_SMS){ if(grantResults.length >0 && grantResults[2] ==PackageManager.PERMISSION_GRANTED) { sendMsg(); }else Toast.makeText(this,"Permission Denited :(",Toast.LENGTH_SHORT).show(); } if(requestCode==REQUEST_PHONE_NUM){ if(grantResults.length >0 && grantResults[3] ==PackageManager.PERMISSION_GRANTED) { getPhoneNumber(); }else Toast.makeText(this,"Permission Denited :(",Toast.LENGTH_SHORT).show(); } } }
true
eef2045437de8c191da3196145d64e51b55c923e
Java
BigWang1109/StellaConference
/src/main/java/com/wxx/conference/interceptor/BaseInterceptor.java
UTF-8
1,674
2.03125
2
[]
no_license
package com.wxx.conference.interceptor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Created by wxx on 16-11-26. */ public class BaseInterceptor implements HandlerInterceptor { private static final Logger logger = LoggerFactory.getLogger(BaseInterceptor.class); public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3) throws Exception { //System.out.println("BaseInterceptor.afterCompletion 当前用户:"+ SessionUtil.getInstance().getUsername()); // TODO Auto-generated method stub } public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3) throws Exception { // if (arg3 != null) { // String uri = arg0.getRequestURI(); // Map<String, Object> model = arg3.getModel(); // //header.jsp 页面使用 // model.put("RequestURI", uri); // } // TODO Auto-generated method stub } public boolean preHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2) throws Exception { // TODO Auto-generated method stub //System.out.println("BaseInterceptor.preHandle 当前用户:"+ SessionUtil.getInstance().getUsername()); //SessionUtil.getInstance().initSession(arg0.getSession()); // String uri = arg0.getRequestURI(); // logger.info(uri); return true; } }
true