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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
6debeadbde6185b0e9a7d34eeb8b182253a34c07 | Java | BlockJJam/streamstudy | /src/com/company/stream/intermediate_operation/Converting.java | UTF-8 | 894 | 3.40625 | 3 | [] | no_license | package com.company.stream.intermediate_operation;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class Converting {
public static void main(String[] args) {
Stream<String> stream = Stream.of("HTML","CSS","JAVA");
stream.map(s -> s.length()).forEach(System.out::println);
List<List<String>> listStream = Arrays.asList(Arrays.asList("12","123","1234"), Arrays.asList("12","123","1234"), Arrays.asList("12","123","1234"));
List<Integer> result = listStream.stream()
.flatMap(Collection::stream)
.filter(str -> str.length()>3)
.map(filtered-> Integer.parseInt(filtered))
.collect(Collectors.toList());
System.out.println("result = " + result);
}
}
| true |
bc0a0bc06546f722b470ee75077d42eef1dba1cd | Java | moutainhigh/wencai-dev | /src/main/java/com/sftc/web/model/vo/swaggerRequest/CommonQuestionVO.java | UTF-8 | 873 | 2.109375 | 2 | [] | no_license | package com.sftc.web.model.vo.swaggerRequest;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Getter;
import lombok.Setter;
@ApiModel(value = "问题说明查询 list并分页 新增id为0,修改时传id")
public class CommonQuestionVO{
@ApiModelProperty(name="主键")
@Setter @Getter
private int id;
@ApiModelProperty(name="当前页",example="1",required = true)
@Setter @Getter
private int pageNumKey;
@ApiModelProperty(name="每页显示个数",example="5",required = true)
@Setter @Getter
private int pageSizeKey;
@ApiModelProperty(name="标题",example = "问题标题,模糊查询")
@Setter @Getter
private String title;
@ApiModelProperty(name="内容",example = "问题答案,模糊查询")
@Setter @Getter
private String content;
}
| true |
df4392a84caf08586a04c4e1bcf07b6c1ff77e42 | Java | Kirudiha/Eventapp | /src/main/java/com/kgisl/Eventapp/Repository/EventRepository.java | UTF-8 | 290 | 1.867188 | 2 | [] | no_license | package com.kgisl.Eventapp.Repository;
import com.kgisl.Eventapp.model.Agenda;
import com.kgisl.Eventapp.model.Event;
import org.springframework.data.jpa.repository.JpaRepository;
public interface EventRepository extends JpaRepository<Event, Long> {
void save(Agenda agenda);
} | true |
3fe313182df4f7f6a719e85bcc2a340c2c1bf8a2 | Java | lefloh/dropwizard-viewtest | /src/main/java/de/utkast/dropwizard/viewtest/ViewResource.java | UTF-8 | 518 | 2.015625 | 2 | [] | no_license | package de.utkast.dropwizard.viewtest;
import io.dropwizard.views.View;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
/**
* @author Florian Hirsch
*/
@Path("views")
public class ViewResource {
@GET
@Path("mustache")
@Produces(MediaType.TEXT_HTML)
public View mustache() {
return new SimpleView("test.mustache");
}
@GET
@Path("freemarker")
@Produces(MediaType.TEXT_HTML)
public View freemarker() {
return new SimpleView("test.ftl");
}
}
| true |
fa76723715835111a1c6fb6ddd2ee38a0286adb6 | Java | teamtargareyns/DataStructureAndAlgo | /src/com/test/gyan/ds/array/orderstatics/MinimumProductOfKInteger.java | UTF-8 | 1,263 | 4.21875 | 4 | [] | no_license | package com.test.gyan.ds.array.orderstatics;
import com.test.gyan.ds.array.MinHeap;
/**
* Given an array of n positive integers. We are required to write a program to print
* the minimum product of k integers of the given array.
*
* Examples:
*
* Input : 198 76 544 123 154 675
* k = 2
* Output : 9348
* We get minimum product after multiplying
* 76 and 123.
*/
public class MinimumProductOfKInteger {
static void printArray(int arr[]) {
for (int i = 0; i < arr.length; i++)
System.out.print(arr[i] + " ");
}
/* Driver program to test above functions */
public static void main(String[] args) {
int arr[] = {198, 76, 544, 123, 154, 675};
int k = 2;
minimumProductOfKInteger(arr,k);
}
/**
* Approach is to find smallest K elements in an Array.
*/
private static void minimumProductOfKInteger(int[] arr,int k) {
MinHeap heap = new MinHeap(arr.length);
for(int i = 0;i<arr.length;i++){
heap.insertNode(arr[i]);
}
int product = 1;
for(int i = 0;i<k;i++){
int min = heap.extractMinNode();
product = product*min;
}
System.out.print("Minimum Product: "+product);
}
}
| true |
b7bc70d308a6a0e15b4dec5e02fe0dc65c90aaeb | Java | sankaranarayanan/cache-sync | /src/main/java/com/cache/impl/controllers/CacheSynchController.java | UTF-8 | 1,119 | 2.046875 | 2 | [] | no_license | package com.cache.impl.controllers;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
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.RestController;
import com.cache.impl.model.User;
import com.cache.impl.service.UserService;
@RestController
@RequestMapping("cache-synch")
public class CacheSynchController {
@Autowired UserService userService;
@GetMapping
public ResponseEntity<List<User>> getUsers() {
List<User> users = userService.findAllUser();
return new ResponseEntity<>(users, HttpStatus.OK);
}
@PostMapping
public ResponseEntity<Long> createUser(@RequestBody User user) {
User savedUsers = userService.save(user);
return new ResponseEntity<>(savedUsers.getId(), HttpStatus.OK);
}
}
| true |
569ef39f2e5cce75a00a39e0032521217ca72809 | Java | JNCdeve00per/diogenes | /src/main/java/cl/compad/service/TestService.java | UTF-8 | 241 | 1.632813 | 2 | [] | no_license | package cl.compad.service;
import java.util.List;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import cl.service.dto.TestDTO;
public interface TestService {
List<TestDTO> list ();
}
| true |
afa2fea99317a4d1c936c52c1672d6a669f6305a | Java | ShreyanshG22/CeramicsManagementDBMS | /Ceramics2/app/src/main/java/com/example/sg_22/ceramics2/SupplierListActivity.java | UTF-8 | 2,517 | 2.484375 | 2 | [] | no_license | package com.example.sg_22.ceramics2;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import java.util.ArrayList;
import java.util.List;
public class SupplierListActivity extends AppCompatActivity {
private RecyclerView recyclerViewSuppliers;
private List<Suppliers> listSuppliers;
private SupplierRecyclerAdapter supplierRecyclerAdapter;
private DatabaseHandler databaseHelper;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_supplier_list);
getSupportActionBar().setTitle("Suppliers");
initViews();
initObjects();
}
/**
* This method is to initialize views
*/
private void initViews() {
recyclerViewSuppliers = (RecyclerView) findViewById(R.id.recyclerViewSuppliers);
}
/**
* This method is to initialize objects to be used
*/
private void initObjects() {
listSuppliers = new ArrayList<>();
supplierRecyclerAdapter = new SupplierRecyclerAdapter(listSuppliers);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
recyclerViewSuppliers.setLayoutManager(mLayoutManager);
recyclerViewSuppliers.setItemAnimator(new DefaultItemAnimator());
recyclerViewSuppliers.setHasFixedSize(true);
recyclerViewSuppliers.setAdapter(supplierRecyclerAdapter);
databaseHelper = new DatabaseHandler(this, null, null, 1);
getDataFromSQLite();
}
/**
* This method is to fetch all user records from SQLite
*/
private void getDataFromSQLite() {
// AsyncTask is used that SQLite operation not blocks the UI Thread.
new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... params) {
listSuppliers.clear();
listSuppliers.addAll(databaseHelper.getAllSuppliers());
return null;
}
@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
supplierRecyclerAdapter.notifyDataSetChanged();
}
}.execute();
}
}
| true |
eabbe6feb42407459d5bb7ac565b14a0a7cd2dab | Java | Dennishe92/cs5200-summer2018-dennishe | /src/main/java/model/Phone.java | UTF-8 | 453 | 3.125 | 3 | [] | no_license | package model;
public class Phone {
private String phone;
private int primary;
public Phone(String phone, int primary) {
super();
this.phone = phone;
this.primary = primary;
}
public Phone() {
super();
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public int isPrimary() {
return primary;
}
public void setPrimary(int primary) {
this.primary = primary;
}
}
| true |
e8118475fec42a36d296918ddd55b9704261e208 | Java | kaka-develop/bulk-sms | /bulk-sms-jpa/src/main/java/com/minhthanh/bulk/jpa/entities/BlacklistGeneral.java | UTF-8 | 1,035 | 2.15625 | 2 | [] | no_license | package com.minhthanh.bulk.jpa.entities;
import java.io.Serializable;
import javax.persistence.*;
import java.util.Date;
/**
* The persistent class for the blacklist_general database table.
*
*/
@Entity
@Table(name="blacklist_general")
@NamedQuery(name="BlacklistGeneral.findAll", query="SELECT b FROM BlacklistGeneral b")
public class BlacklistGeneral implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private int id;
@Temporal(TemporalType.TIMESTAMP)
@Column(name="created_date")
private Date createdDate;
private String keyword;
public BlacklistGeneral() {
}
public int getId() {
return this.id;
}
public void setId(int id) {
this.id = id;
}
public Date getCreatedDate() {
return this.createdDate;
}
public void setCreatedDate(Date createdDate) {
this.createdDate = createdDate;
}
public String getKeyword() {
return this.keyword;
}
public void setKeyword(String keyword) {
this.keyword = keyword;
}
} | true |
010d27be34bd411d08469fab62662b9fe4e82536 | Java | hyeon-kyeong/SSD_2021_1-1 | /src/main/java/com/ssd/delivery/dao/mybatis/mapper/AuctionLineItemMapper.java | UTF-8 | 433 | 1.828125 | 2 | [] | no_license | package com.ssd.delivery.dao.mybatis.mapper;
import java.util.List;
import org.apache.ibatis.annotations.Mapper;
import com.ssd.delivery.domain.AuctionLineItemDTO;
@Mapper
public interface AuctionLineItemMapper {
List<AuctionLineItemDTO> getACLineItemsByACId(int acId);
void insertACLineItem(AuctionLineItemDTO ACLineId);
void deleteACLineItem(int auctionId);
void deleteACLineItemByUsername(String username);
}
| true |
5d8be05461712a6f77f45965b0e8f8a3bf796aec | Java | charlieDef/Test | /CoolPasCher/src/main/java/com/materials/client/widgets/search/SearchPanel.java | UTF-8 | 4,337 | 1.953125 | 2 | [] | no_license | package com.materials.client.widgets.search;
import com.google.gwt.core.client.GWT;
import com.google.gwt.dom.client.Style.Unit;
import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.ui.Composite;
import com.materials.client.utils.ConstantsUtils;
import com.materials.client.widgets.icon.MDWidgetMorph;
import gwt.material.design.addins.client.combobox.MaterialComboBox;
import gwt.material.design.client.constants.IconPosition;
import gwt.material.design.client.constants.IconType;
import gwt.material.design.client.ui.MaterialButton;
import gwt.material.design.client.ui.MaterialCard;
import gwt.material.design.client.ui.MaterialCardAction;
import gwt.material.design.client.ui.MaterialTextBox;
import gwt.material.design.client.ui.animate.MaterialAnimation;
import gwt.material.design.client.ui.animate.Transition;
public class SearchPanel extends Composite {
private static SearchPanelUiBinder uiBinder = GWT.create(SearchPanelUiBinder.class);
interface SearchPanelUiBinder extends UiBinder<MaterialCard, SearchPanel> {
}
@UiField
MaterialCard cardUi;
@UiField
MaterialCardAction cardActionUi;
@UiField
MaterialComboBox<String> rubriqueUi, type2BienUi, provinceUi, villeUi;
@UiField
MaterialTextBox autresVilleUi;
private MDWidgetMorph buttonMorph;
public SearchPanel() {
initWidget(uiBinder.createAndBindUi(this));
MaterialButton buttonSearch = new MaterialButton("Chercher", IconType.SEARCH);
buttonSearch.setIconPosition(IconPosition.RIGHT);
buttonSearch.getElement().getStyle().setProperty("backgroundColor", " #960018");
buttonSearch.getElement().getStyle().setProperty("color", " #ffb74d");
MaterialButton buttonCreation = new MaterialButton("Creer", IconType.ADD_BOX);
buttonCreation.setIconPosition(IconPosition.RIGHT);
buttonCreation.getElement().getStyle().setProperty("backgroundColor", " #960018");
buttonCreation.getElement().getStyle().setProperty("color", " #ffb74d");
buttonMorph = new MDWidgetMorph(buttonSearch, buttonCreation);
buttonMorph.getElement().getStyle().setMarginTop(-8, Unit.PX);
cardActionUi.add(buttonMorph);
rubriqueUi.getLabel().getElement().getStyle().setColor("#ffb74d");
rubriqueUi.setAcceptableValues(ConstantsUtils.RUBRIQUES);
type2BienUi.getLabel().getElement().getStyle().setColor("#ffb74d");
provinceUi.getLabel().getElement().getStyle().setColor("#ffb74d");
villeUi.getLabel().getElement().getStyle().setColor("#ffb74d");
type2BienUi.setAcceptableValues(ConstantsUtils.RUBRIQUES_KEYS.get(ConstantsUtils.LOCATIONS));
provinceUi.setAcceptableValues(ConstantsUtils.PROVINCES);
villeUi.setAcceptableValues(ConstantsUtils.VILLES_EXTREME_NORD);
rubriqueUi.addValueChangeHandler(x -> {
String value = rubriqueUi.getSingleValue();
type2BienUi.setAcceptableValues(ConstantsUtils.RUBRIQUES_KEYS.get(value));
});
provinceUi.addValueChangeHandler(x -> {
String value = provinceUi.getSingleValue();
villeUi.setAcceptableValues(ConstantsUtils.PROVINCES_KEYS.get(value));
});
villeUi.addValueChangeHandler(x -> {
String value = villeUi.getSingleValue();
autresVilleUi.setVisible(value.equals("Autres Villes"));
autresVilleUi.setValue("");
});
}
@UiHandler("rechercheCheckUi")
public void onRecherche(ValueChangeEvent<Boolean> changeEvent) {
if (buttonMorph != null && changeEvent.getValue()) {
buttonMorph.showWidgetSource();
}
}
@UiHandler("creationCheckUi")
public void onCreation(ValueChangeEvent<Boolean> changeEvent) {
if (buttonMorph != null && changeEvent.getValue()) {
buttonMorph.showWidgetTarget();
}
}
@Override
protected void onLoad() {
super.onLoad();
// Menu animation
MaterialAnimation animationMenu = new MaterialAnimation();
animationMenu.setTransition(Transition.FADEIN);
animationMenu.setDelay(2000);
animationMenu.setDuration(6000);
animationMenu.animate(cardUi);
new Timer() {
@Override
public void run() {
cardUi.setOpacity(1);
}
}.schedule(2000);
}
}
| true |
9efadda8502c733da42ebc2861d53abcf29fc0e9 | Java | fsfish/electron-backend | /customerManager/src/main/java/com/electron/mfs/pg/customer/service/CustomerManagerKafkaConsumer.java | UTF-8 | 661 | 2.140625 | 2 | [] | no_license | package com.electron.mfs.pg.customer.service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Service;
import java.io.IOException;
@Service
public class CustomerManagerKafkaConsumer {
private final Logger log = LoggerFactory.getLogger(CustomerManagerKafkaConsumer.class);
private static final String TOPIC = "topic_customermanager";
@KafkaListener(topics = "topic_customermanager", groupId = "group_id")
public void consume(String message) throws IOException {
log.info("Consumed message in {} : {}", TOPIC, message);
}
}
| true |
acb12ec5316df521767a80a45cd56c8a50444211 | Java | MVK-USA/JavaProgramming2020_B21 | /src/day17_Strings/HW_KidsAge.java | UTF-8 | 1,201 | 3.984375 | 4 | [] | no_license | package day17_Strings;
public class HW_KidsAge {
public static void main(String[] args) {
int age =15;
if(age<2){
System.out.println("ineligible");
}else if(age==2){
System.out.println("toddler");
}else if(age>=3 && age<=5){
System.out.println("early childhood");
}else if(age>=6 && age<=7){
System.out.println("young reader");
}else if(age>=8 && age<=10){
System.out.println("elementary");
}else if(age>=11 && age<=12){
System.out.println("middle");
}else if(age==13){
System.out.println("impossible");
}else if(age>=14 && age<=16){
System.out.println("high school");
}else if(age>=17 && age<=18){
System.out.println("scholar");
}else{
System.out.println("ineligible");
}
}
}
/*
In the Happy Valley School System, children
are classified by age as follows:
less than 2, ineligible
2, toddler
3-5, early childhood
6-7, young reader
8-10, elementary
11 and 12, middle
13, impossible
14-16, high school
17-18, scholar
greater than 18, ineligible
*/
| true |
538a33d9244f7d593cdcbef62ccdfa7440bcec62 | Java | Muzna-alkhen/hiveql-compiler | /final/src/codeGeneration/FileScanner.java | UTF-8 | 1,018 | 3.1875 | 3 | [] | no_license | package codeGeneration;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
public class FileScanner {
public static String readFileAsString(String fileName) {
String text = "";
try {
text = new String(Files.readAllBytes(Paths.get(fileName)));
} catch (IOException e) {
e.printStackTrace();
}
return text;
}
public static void writeFileAsString(String s, String path) {
try (PrintStream out = new PrintStream(new FileOutputStream(path))) {
out.print(s);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public static ArrayList<File> getFiles(String path) {
File folder = new File(path);
File[] listOfFiles = folder.listFiles();
ArrayList<File> list = new ArrayList<>();
for (File element:
listOfFiles) {
list.add(element);
}
return list;
}
}
| true |
4149e103e2187d4725c5b2fbe40be35fee52133c | Java | youngindia05/jobby | /app/src/main/java/com/youngindia/jobportal/ui/fragment_companybase.java | UTF-8 | 3,647 | 2.265625 | 2 | [] | no_license | package com.youngindia.jobportal.ui;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;
import com.youngindia.jobportal.R;
import com.youngindia.jobportal.adapter.ImageAdapter;
/**
* A simple {@link Fragment} subclass.
* Activities that contain this fragment must implement the
* {@link fragment_companybase.OnFragmentInteractionListener} interface
* to handle interaction events.
* Use the factory method to
* create an instance of this fragment.
*/
public class fragment_companybase extends Fragment {
Company_Base employeer_homeActivity;
public Integer[] mThumbIds = {
R.drawable.post_job, R.drawable.search_candidate,
R.drawable.shotlist, R.drawable.recive_aplicnt,
};
public String[]jobtype={"Post a Job","Candidate Search","Shortlisted Candidate","Received Candidatelist"};
private OnFragmentInteractionListener mListener;
public fragment_companybase() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.fragment_fragment_companybase, container, false);
final GridView gridview = (GridView)rootView.findViewById(R.id.gridview);
gridview.setAdapter(new ImageAdapter(employeer_homeActivity,jobtype,mThumbIds));
gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
if(position==0)
{
Intent intent=new Intent(getActivity(),CompanyDetail.class);
startActivity(intent);
}
if(position==1)
{
Intent intent=new Intent(getActivity(),Search_Activity.class);
startActivity(intent);
}
if(position==2|| position==3)
{
Intent intent=new Intent(getActivity(),Company_candidatelist.class);
startActivity(intent);
}
}
});
return rootView;
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
employeer_homeActivity=(Company_Base) activity;
}
@Override
public void onDetach() {
super.onDetach();
mListener = null;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
}
| true |
b2e23d47439664509d44a17c3f820bad8c4449b3 | Java | Barryrowe/sneakynessie | /texture-packer/src/AnimationTexturePacker.java | UTF-8 | 913 | 2.6875 | 3 | [] | no_license | import com.badlogic.gdx.tools.texturepacker.TexturePacker.Settings;
import com.badlogic.gdx.tools.texturepacker.TexturePacker;
public class AnimationTexturePacker {
private static final String INPUT_DIR = "assets/";
private static final String OUTPUT_DIR = "../android/assets/animations/";
private static final String PACK_FILE = "animations";
public static void main(String[] args){
// create the packing's settings
Settings settings = new Settings();
// adjust the padding settings
settings.paddingX = 2;
settings.paddingY = 2;
settings.edgePadding = false;
// set the maximum dimension of each image atlas
settings.maxWidth = 4096;
settings.maxHeight = 4096;
settings.combineSubdirectories = true;
// pack the images
TexturePacker.process(settings, INPUT_DIR, OUTPUT_DIR, PACK_FILE);
}
}
| true |
a0f6a11d75e5ae46248d68c41e0b174842b7c070 | Java | jgtadeo/Project--MOBAPPL | /SalesandProductReport/app/src/main/java/ph/edu/apc/renzo/salesandproductreport/Activities/SalesActivity.java | UTF-8 | 8,939 | 2.171875 | 2 | [] | no_license | package ph.edu.apc.renzo.salesandproductreport.Activities;
import android.app.DatePickerDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import java.text.DateFormat;
import java.util.Calendar;
import java.util.Date;
import ph.edu.apc.renzo.salesandproductreport.R;
/**
* Created by Renzo on 29/10/2016.
*/
public class SalesActivity extends AppCompatActivity implements View.OnClickListener{
private EditText editGross, editBread, editGrocery, editEload, editSmart, editGlobe, editSun;
private TextView back, textDate;
private Button addDate, compute;
private FirebaseAuth mAuth;
private FirebaseUser mUser;
private DatabaseReference database;
private String mUid;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sales);
textDate = (TextView)findViewById(R.id.textView_SaleDate);
back = (TextView)findViewById(R.id.textView_BackElous);
back.setOnClickListener(this);
editGross = (EditText)findViewById(R.id.editText_SaleGross);
editBread = (EditText)findViewById(R.id.editText_SaleBread);
editGrocery = (EditText)findViewById(R.id.editText_SaleGrocery);
editEload = (EditText)findViewById(R.id.editText_SaleEload);
editSmart = (EditText)findViewById(R.id.editText_SaleSmart);
editGlobe = (EditText)findViewById(R.id.editText_SaleGlobe);
editSun = (EditText)findViewById(R.id.editText_SaleSun);
addDate = (Button)findViewById(R.id.button_SalesAddDate);
addDate.setOnClickListener(this);
compute = (Button)findViewById(R.id.button_SalesCompute);
compute.setOnClickListener(this);
mAuth = FirebaseAuth.getInstance();
mUser = mAuth.getCurrentUser();
mUid = mUser.getUid();
database = FirebaseDatabase.getInstance().getReference().child("users").child("sales");
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.textView_BackElous:
Intent back = new Intent(SalesActivity.this, MainActivity.class);
startActivity(back);
finish();
break;
case R.id.button_SalesAddDate:
Calendar c = Calendar.getInstance();
int year_x = c.get(Calendar.YEAR);
int month_x = c.get(Calendar.MONTH);
int day_x = c.get(Calendar.DAY_OF_MONTH);
DatePickerDialog date = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
textDate.setText(dayOfMonth + "/" + (monthOfYear + 1) + "/" + year);
}
}, year_x, month_x, day_x);
date.show();
break;
case R.id.button_SalesCompute:
if (textDate.length() == 0) {
AlertDialog.Builder builder = new AlertDialog.Builder(SalesActivity.this);
builder.setMessage("Please choose a date")
.setTitle("Unknown Date Error!")
.setPositiveButton(android.R.string.ok, null);
AlertDialog dialog = builder.create();
dialog.show();
return;
} else if (editGross.getText().toString().isEmpty()) {
editGross.setError("Input gross");
return;
} else if (editBread.getText().toString().isEmpty()) {
editBread.setError("Input bread");
return;
} else if (editGrocery.getText().toString().isEmpty()) {
editGrocery.setError("Input grocery");
return;
} else if (editEload.getText().toString().isEmpty()) {
editEload.setError("Input eload");
return;
} else if (editSmart.getText().toString().isEmpty()) {
editSmart.setError("Input smart");
return;
} else if (editGlobe.getText().toString().isEmpty()) {
editGlobe.setError("Input globe");
return;
} else if (editSun.getText().toString().isEmpty()) {
editSun.setError("Input sun");
return;
} else {
String Date = textDate.getText().toString();
Double Gross = Double.parseDouble(editGross.getText().toString());
Double Bread = Double.parseDouble(editBread.getText().toString());
Double Grocery = Double.parseDouble(editGrocery.getText().toString());
Double Eload = Double.parseDouble(editEload.getText().toString());
Double Smart = Double.parseDouble(editSmart.getText().toString());
Double Globe = Double.parseDouble(editGlobe.getText().toString());
Double Sun = Double.parseDouble(editSun.getText().toString());
addSales(Date, Gross, Bread, Grocery, Eload, Smart, Globe, Sun);
}
break;
}
}
private void addSales(String Date, Double Gross, Double Bread, Double Grocery,
Double Eload, Double Smart, Double Globe, Double Sun) {
double computeGross, computeEload;
Log.d("debug", "Date:" + Date);
Log.d("debug", "Gross:" + Gross);
Log.d("debug", "Bread:" + Bread);
Log.d("debug", "Grocery:" + Grocery);
Log.d("debug", "Eload:" + Eload);
Log.d("debug", "Smart:" + Smart);
Log.d("debug", "Globe:" + Globe);
Log.d("debug", "Sun:" + Sun);
computeGross = Bread + Grocery;
Log.d("debug", "Computed Gross:" + computeGross);
computeEload = Smart + Globe + Sun;
Log.d("debug", "Computed Eload:" + computeEload);
DatabaseReference mData = database.push();
mData.child("date").setValue(Date);
mData.child("gross").setValue(Gross);
mData.child("computed_gross").setValue(computeGross);
mData.child("grocery").setValue(Grocery);
mData.child("bread").setValue(Bread);
mData.child("eload").setValue(Eload);
mData.child("computed_eload").setValue(computeEload);
mData.child("smart").setValue(Smart);
mData.child("globe").setValue(Globe);
mData.child("sun").setValue(Sun);
/* database.child("users").child(mUid).child(dateStamp).child("sales").push().setValue("date: " + Date );
database.child("users").child(mUid).child(dateStamp).child("sales").push().setValue("gross: " + Gross);
database.child("users").child(mUid).child(dateStamp).child("sales").push().setValue("computed_gross: " + computeGross);
database.child("users").child(mUid).child(dateStamp).child("sales").push().setValue("grocery: " + Grocery);
database.child("users").child(mUid).child(dateStamp).child("sales").push().setValue("bread: " + Bread);
database.child("users").child(mUid).child(dateStamp).child("sales").push().setValue("eload: " + Eload);
database.child("users").child(mUid).child(dateStamp).child("sales").push().setValue("computed_eload: " + computeEload);
database.child("users").child(mUid).child(dateStamp).child("sales").push().setValue("smart: " + Smart);
database.child("users").child(mUid).child(dateStamp).child("sales").push().setValue("globe: " + Globe);
database.child("users").child(mUid).child(dateStamp).child("sales").push().setValue("sun: " + Sun);*/
Toast.makeText(this, "All information has been saved!", Toast.LENGTH_LONG).show();
textDate.setText("");
editGross.setText("");
editBread.setText("");
editGrocery.setText("");
editEload.setText("");
editSmart.setText("");
editGlobe.setText("");
editSun.setText("");
}
@Override
public void onBackPressed() {
Intent back = new Intent(SalesActivity.this, MainActivity.class);
startActivity(back);
finish();
}
}
| true |
5ebee2792dd4a1bfaec929066454a1dae3d097d5 | Java | liangminxiong/PlatFormCompanyProject | /app/src/main/java/com/yuefeng/home/contract/MsgListInfosContract.java | UTF-8 | 393 | 1.609375 | 2 | [] | no_license | package com.yuefeng.home.contract;
import com.common.base.codereview.BaseView;
/*消息列表*/
public interface MsgListInfosContract {
interface View extends BaseView<Object> {
}
interface Presenter {
void getAnMentDataList(String function, String pid,String timestart, String timeend,
int page, int limit, boolean isShowLoad);
}
}
| true |
33c875b9af0c850c977ba5fb7801e96f7e092f52 | Java | maryamkarimi/functional-programming | /q9/CustomerManager.java | UTF-8 | 1,146 | 3.359375 | 3 | [] | no_license | import java.util.ArrayList;
import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Collectors;
public class CustomerManager extends ArrayList<Customer> {
// Return a new list containing only the customers that match the given predicate
public List<Customer> getCustomersBy(Predicate<Customer> predicate){
return this.stream().filter(predicate).collect(Collectors.<Customer>toList());
}
// Return a new list containing only customers 65 or older
public List<Customer> getSeniors(){
return getCustomersBy(p -> p.getAge() > 64);
}
// Return a new list containing only customers under 18
public List<Customer> getChildren(){
return getCustomersBy(p -> p.getAge() < 18 );
}
// Return a new list containing only customers in the given country
public List<Customer> getCustomersFrom(String country){
return getCustomersBy(p -> p.getCountry() == country);
}
// Return a new list containing only customers having a last name starting with the given prefix
public List<Customer> getCustomersByLastNamePrefix(String prefix){
return getCustomersBy(p -> p.getLastName().startsWith(prefix));
}
} | true |
10dc43394e9b389a95e4e2b2f92ab6acc1325a7b | Java | ibisTime/xn-gchf | /src/main/java/com/cdkj/gchf/enums/EPoliticsType.java | UTF-8 | 2,649 | 2.671875 | 3 | [] | no_license | package com.cdkj.gchf.enums;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import com.cdkj.gchf.exception.BizException;
/**
* 政治面貌类型
* @author: silver
* @since: Mar 29, 2019 2:11:09 PM
* @history:
*/
public enum EPoliticsType {
ZHONGGONGDANGYUAN("01", "中共党员"),
YUBEIDANGYUAN("02", "中共预备党员"),
GONGQINGTUANYUAN("03", "共青团员"),
MINGEDANGYUAN("04", "民革党员"),
MINMENGMENGYUAN("05", "民盟盟员"),
MINJIANHUIYUAN("06", "民建会员"),
MINJINHUIYUAN("07", "民进会员"),
MINGONGDANGDANGYUAN("08", "农工党党员"),
ZHIGONGDANGDANGYUAN("09", "致公党党员"),
JIUSANXUESHESHEYUAN("10", "九三学社社员"),
TAIMENGMENGYUAN("11", "台盟盟员"),
WUDANGPAIRENYUAN("12", "无党派人士"),
QUNZHONG("13", "群众");
public static Map<String, EPoliticsType> getPoliticsTypeMap() {
Map<String, EPoliticsType> map = new HashMap<String, EPoliticsType>();
for (EPoliticsType type : EPoliticsType.values()) {
map.put(type.getCode(), type);
}
return map;
}
public static EPoliticsType getPoliticsType(String code) {
Map<String, EPoliticsType> map = getPoliticsTypeMap();
EPoliticsType projectCorpType = map.get(code);
if (null == projectCorpType) {
throw new BizException("xn0000", code + "对应政治面貌类型不存在");
}
return projectCorpType;
}
public static String getPoliticsTypeCode(String dictVaule) {
Map<String, EPoliticsType> politicsTypeMap = getPoliticsTypeMap();
Set<Entry<String, EPoliticsType>> entrySet = politicsTypeMap.entrySet();
for (Entry<String, EPoliticsType> entry : entrySet) {
if (entry.getValue().getStatus().equals(dictVaule)) {
return entry.getKey();
}
}
throw new BizException("XN0000", dictVaule + "对应政治面貌类型不存在");
}
public static void checkExists(String code) {
Map<String, EPoliticsType> map = getPoliticsTypeMap();
EPoliticsType projectCorpType = map.get(code);
if (null == projectCorpType) {
throw new BizException("xn0000", code + "对应政治面貌类型不存在");
}
}
EPoliticsType(String code, String status) {
this.code = code;
this.status = status;
}
private String code;
private String status;
public String getCode() {
return code;
}
public String getStatus() {
return status;
}
}
| true |
867f8fe1c7bf63e1e4c94cb8d9b12aac61213330 | Java | xiezz/medical | /src/main/java/com/xie/work/service/impl/TeamUserServiceImpl.java | UTF-8 | 2,874 | 2.125 | 2 | [] | no_license | package com.xie.work.service.impl;
import com.xie.work.dao.ITeamUserDao;
import com.xie.work.domain.TeamUserEntity;
import com.xie.work.service.ITeamUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Created by xiezhongzheng on 2017/8/9.
*/
@Component
public class TeamUserServiceImpl implements ITeamUserService {
@Autowired
private ITeamUserDao teamUserDao;
public Map<String,Object> createTeamUser( Long teamId,Long userId,Integer leader,String role,String teamName) throws Exception{
Map<String,Object> returnMap = new HashMap<String,Object>();
TeamUserEntity teamUserEntity= new TeamUserEntity();
teamUserEntity.setTeamId(teamId);
teamUserEntity.setRole(role);
teamUserEntity.setTeamName(teamName);
teamUserEntity.setUserId(userId);
teamUserEntity.setLeader(leader);
teamUserDao.save(teamUserEntity);
returnMap.put("value", teamUserEntity);
returnMap.put("message", "创建团队成功");
returnMap.put("success", true);
return returnMap;
}
public Map<String, Object> findTeamUser(Long userId) throws Exception {
Map<String,Object> returnMap = new HashMap<String,Object>();
String hql = "from TeamUserEntity where userId ="+userId+"";
List<TeamUserEntity> teamUserList = new ArrayList();
teamUserList = teamUserDao.findList(hql);
if(teamUserList.size()>0) {
returnMap.put("value", teamUserList);
returnMap.put("message", "获取列表成功");
returnMap.put("success", true);
}else{
returnMap.put("message", "获取列表失败!");
returnMap.put("success", false);
}
return returnMap;
}
public Map<String, Object> findUserTeam(Long teamId)throws Exception {
Map<String,Object> returnMap = new HashMap<String,Object>();
String hql = "from TeamUserEntity where teamId ="+teamId+"";
List<TeamUserEntity> teamUserList = new ArrayList();
teamUserList = teamUserDao.findList(hql);
if(teamUserList.size()>0) {
returnMap.put("value", teamUserList);
returnMap.put("message", "获取列表成功");
returnMap.put("success", true);
}else{
returnMap.put("message", "获取列表失败!");
returnMap.put("success", false);
}
return returnMap;
}
public Map<String,Object> update(String title, String content, Timestamp create_time ,Long user_id,Integer type) throws Exception{
Map<String,Object> returnMap = new HashMap<String,Object>();
return returnMap;
}
} | true |
7d015acbf43f7be4193be84508e0ac339bf444c3 | Java | 1026957152/supervision | /src/main/java/org/ylgjj/loan/rates/SY_1_ljjzzdws_建制总单位数_RateServiceImpl.java | UTF-8 | 5,714 | 1.859375 | 2 | [] | no_license | package org.ylgjj.loan.rates;
import org.apache.commons.lang3.time.StopWatch;
import org.javatuples.Pair;
import org.javatuples.Triplet;
import org.springframework.stereotype.Service;
import org.ylgjj.loan.domain.DP005_单位分户账;
import org.ylgjj.loan.enumT.E_DP005_单位分户账_单位账户状态;
import org.ylgjj.loan.enumT.E_DP005_单位分户账_单位账户类型;
import org.ylgjj.loan.domain_flow.RateAnalysisStream;
import org.ylgjj.loan.domain_flow.RateAnalysisTable;
import org.ylgjj.loan.domain_flow.ProRateHistory;
import org.ylgjj.loan.output.H1_2监管主要指标查询_公积金中心主要运行情况查询;
import org.ylgjj.loan.outputenum.E_指标_RATE_SY;
import org.ylgjj.loan.outputenum.统计周期编码;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.*;
import java.util.stream.Collectors;
/**
* Created by silence yuan on 2015/7/25.
*/
@Service
public class SY_1_ljjzzdws_建制总单位数_RateServiceImpl extends RateServiceBaseImpl{
E_指标_RATE_SY e_指标_rate_sy = E_指标_RATE_SY.SY_1_ljjzzdws_建制总单位数;
public void realTime() {
Long count = dp005_单位分户账_repository.countByUnitacctype单位账户类型(E_DP005_单位分户账_单位账户类型.普通.getText());
saveAccLongRealtime(count,LocalDate.now(),e_指标_rate_sy);
}
public void groupProcess(){
process(LocalDate.parse("2015-10-01",df),LocalDate.now());
transfer累计ToPro(LocalDate.parse("2015-10-01",df),e_指标_rate_sy,Long.class.getName());
}
public void process(LocalDate beginDate,LocalDate endDate) {
RateAnalysisTable rateAnalysisTable = rateAnalysisTableRepository.findByIndexNo(e_指标_rate_sy.get编码());
if(rateAnalysisTable == null){
return;
}
StopWatch timer = new StopWatch();
timer.start();
if(true || rateAnalysisTable.getAanalysedEndDate()== null){
deleteAll(e_指标_rate_sy);
deleteReduction_流水还原(e_指标_rate_sy);
deleteReduction_流水还原_Pro(e_指标_rate_sy);
RateAnalysisStream rateAnalysisStream = history(beginDate,endDate,false);
rateAnalysisStream.setDuration(timer.getTime());
rateAnalysisTable.setAanalysedBeginDate(rateAnalysisStream.getBeginDate());
rateAnalysisTable.setAanalysedEndDate(rateAnalysisStream.getEndDate());
updateRateTable(rateAnalysisTable,rateAnalysisStream);
}else{
// if(rateAnalysisTable.getAanalysedEndDate().is)
RateAnalysisStream rateAnalysisStream = history(rateAnalysisTable.getAanalysedEndDate(),LocalDate.now(),false);
rateAnalysisStream.setDuration(timer.getTime());
rateAnalysisTable.setAanalysedBeginDate(rateAnalysisStream.getBeginDate());
rateAnalysisTable.setAanalysedEndDate(rateAnalysisStream.getEndDate());
updateRateTable(rateAnalysisTable,rateAnalysisStream);
}
}
public RateAnalysisStream history(LocalDate beginDate,LocalDate endDate,Boolean acc) {
List<DP005_单位分户账> ln003_合同信息s = dp005_单位分户账_repository
.findByOpnaccdate开户日期BetweenOrderByOpnaccdate开户日期Desc(beginDate.minusDays(1),endDate.plusDays(1));
System.out.println("-----------------------------"+ ln003_合同信息s.size());
List<Pair<LocalDate,Long>> sourceList =ln003_合同信息s
.stream()
.filter(e->e.getUnitacctype单位账户类型().equals(E_DP005_单位分户账_单位账户类型.普通.getText()))
.filter(e->!e.getUnitaccstate单位账户状态().equals(E_DP005_单位分户账_单位账户状态.销户.getText()))
.collect(Collectors.groupingBy(e->e.getOpnaccdate开户日期()))
.entrySet()
.stream()
.sorted(Comparator.comparingLong(e->e.getKey().toEpochDay()))
.map(e->{
System.out.println("stream---------"+e.getKey());
return Pair.with(e.getKey(),e.getValue().stream().count());
}).collect(Collectors.toList());
Long num = 0L;
List<Pair<LocalDate,Long>> triplets = new ArrayList<>();
for(Pair<LocalDate,Long> triplet: sourceList){
num += triplet.getValue1();
triplets.add(Pair.with(triplet.getValue0(),num));
}
if(acc){
saveAccLong(triplets,e_指标_rate_sy);
}else{
saveDeltaLong(sourceList,e_指标_rate_sy);
}
return new RateAnalysisStream(beginDate,endDate);
}
public void query(H1_2监管主要指标查询_公积金中心主要运行情况查询 h1, List<ProRateHistory> rateHistories, List<ProRateHistory> rateHistories_环比, List<ProRateHistory> rateHistories_同比) {
Triplet<Long,Long,Long> triplet = queryLong期末(e_指标_rate_sy,rateHistories,rateHistories_环比,rateHistories_同比);
Long rateHistory_环比 =triplet.getValue1();
Long rateHistory_同比 = triplet.getValue2();
Long rateHistory = triplet.getValue0();
h1.setLjjzzdws_建制总单位数_NUMBER_18_2(rateHistory.intValue());
BigDecimal bigDecimal = BigDecimal.valueOf(rateHistory_环比);
h1.setLjhbjzzdws_环比建制总单位数_NUMBER_18_0(bigDecimal.setScale(4, BigDecimal.ROUND_HALF_UP).doubleValue());
bigDecimal = BigDecimal.valueOf(rateHistory_同比);
h1.setLjsnjzzdws_同比建制总单位数_NUMBER_18_0(bigDecimal.setScale(4, BigDecimal.ROUND_HALF_UP).doubleValue());
}
}
| true |
daad35a24eb662c5f0f9c57819f7246e69dbde16 | Java | atulverma1212/superduperdrive | /src/main/java/com/udacity/jwdnd/course1/cloudstorage/config/WebSecurity.java | UTF-8 | 3,848 | 1.992188 | 2 | [] | no_license | package com.udacity.jwdnd.course1.cloudstorage.config;
import com.udacity.jwdnd.course1.cloudstorage.services.UserService;
import org.apache.catalina.filters.CorsFilter;
import org.apache.juli.logging.Log;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
@Configuration
@EnableWebSecurity
//@EnableRedisHttpSession
@EnableGlobalMethodSecurity(securedEnabled = true)
public class WebSecurity extends WebSecurityConfigurerAdapter {
@Qualifier("userDetailsServiceImpl")
@Autowired
private UserDetailsService userDetailsService;
@Autowired
private LogoutHandler logoutHandler;
@Value("${jwt.token.secret}")
private String secret;
@Value("${jwt.token.expiry.ms}")
private long expiry;
@Autowired
private BCryptPasswordEncoder bCryptPasswordEncoder;
@Override
protected void configure(HttpSecurity http) throws Exception {
http.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.ALWAYS).and()
.csrf().disable().authorizeRequests()
.antMatchers(HttpMethod.POST, "/api/user/signup").permitAll()
.antMatchers(HttpMethod.GET, "/api/user/signup").permitAll()
.antMatchers(HttpMethod.GET, "/api/user/login").permitAll()
.antMatchers(HttpMethod.GET, "/api/user/logout").permitAll()
.antMatchers(HttpMethod.GET, "/api/user/invalidCredentials").permitAll()
.antMatchers(HttpMethod.GET,
"/",
"/*.html",
"/css/*",
"/js/*",
"/favicon.ico",
"/**/*.html",
"/**/*.css",
"/**/*.js").permitAll()
.anyRequest().authenticated()
.and()
.exceptionHandling()
.accessDeniedPage("/error.html")
.and()
.logout().addLogoutHandler(logoutHandler)
.and()
.addFilter(new JWTAuthenticationFilter(authenticationManager(), secret, expiry))
.addFilter(new JWTAuthorizationFilter(authenticationManager(), secret));
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().and().userDetailsService(userDetailsService).passwordEncoder(bCryptPasswordEncoder);
}
@Bean
public BCryptPasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Override
public void configure(org.springframework.security.config.annotation.web.builders.WebSecurity web) throws Exception {
web.ignoring().antMatchers(HttpMethod.GET, "/api/user/invalidCredentials")
.antMatchers(HttpMethod.GET, "/api/user/logout");
}
}
| true |
4ed957db6b2c18f3637171d368d2316b65e646b1 | Java | vishakvinod/FoodOrderApplication | /src/com/food/item/Beverage.java | UTF-8 | 782 | 2.671875 | 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 com.food.item;
import com.food.FoodItems;
import com.food.packing.FoodPacking;
import com.food.packing.items.BottelPacking;
/**
*
* @author Vishak
*/
public abstract class Beverage extends FoodItems {
public static final int XLSIZE = 1;
public static final int LSIZE = 1;
public static final int MSIZE = 1;
public static final int SSIZE = 1;
public Beverage(String name) {
super(name);
this.size = MSIZE;
}
@Override
public FoodPacking getPackingType() {
return new BottelPacking();
}
}
| true |
aff3b3d8e122fa8f55ac6802211fcf1399af1be0 | Java | hwangsiyuan/high-frequency-question | /spring-question/src/main/java/com/hussein/module/SpringModule.java | UTF-8 | 2,168 | 3 | 3 | [] | no_license | package com.hussein.module;
/**
* <p>Title: SpringModule</p>
* <p>Description: </p>
* <p>Company: www.hussein.com</p>
*
* @author hwangsy
* @date 2019/10/22 3:13 PM
*/
public class SpringModule {
public static void main(String[] args) {
/**
* Jdbc ORM WebSocket Servlet
* OXM JMS Web Portlet
* Transaction
*
* Aop Aspects Instrumentation Messaging
*
* Core Bean Context SpEL
* Test
*
* 1、Spring的Core模块 是Spring的核心类库,Spring的所有功能都依赖于该类库,Core主要实现IOC功能,Spring的所有功能都是借助IOC实现的。
* 2、Spring的AOP模块 是Spring的AOP库,提供了AOP(拦截器)机制,并提供常用的拦截器,供用户自定义和配置。
* 3、Spring的ORM模块 提供对常用的ORM框架的管理和辅助支持,Spring支持常用的Hibernate,ibtas,jdao等框架的支持,Spring本身并不对ORM进行实现,仅对常见的ORM框架进行封装,并对其进行管理
* 4、Spring的DAO模块 提供对JDBC的支持,对JDBC进行封装,允许JDBC使用Spring资源,并能统一管理JDBC事物,并不对JDBC进行实现。(执行sql语句)
* 5、Spring的Web模块 WEB模块提供对常见框架如Struts1,WEBWORK(Struts 2),JSF的支持,Spring能够管理这些框架,将Spring的资源注入给框架,也能在这些框架的前后插入拦截器。
* 6、Spring的Context模块 提供框架式的Bean访问方式,其他程序可以通过Context访问Spring的Bean资源,相当于资源注入。
* 7、Spring的MVC模块 为Spring提供了一套轻量级的MVC实现,在Spring的开发中,我们既可以用Struts也可以用Spring自己的MVC框架,相对于Struts,Spring自己的MVC框架更加简洁和方便。
*/
System.out.println("Spring module.");
}
}
| true |
a5bfac2f0c071db251110e884e2518ccf2fc009a | Java | Crazyalltnt/DataStructureAndAlgorithm | /DataStructure/src/recursion/Queens8.java | UTF-8 | 2,535 | 4.21875 | 4 | [] | no_license | package recursion;
/**
* 递归-八皇后问题
*
* @author Neil
* @version v1.0
* @date 2021/2/6 17:25
*/
public class Queens8 {
/**
* 定义一个max表示共有多少个皇后
*/
int max = 8;
/**
* 定义数组,保存皇后放置位置的结果,
* locationOfQueensArray[i]=val表示第i+1个皇后放在第i+1行的第val+1列
*/
int [] locationOfQueensArray= new int[max];
static int count = 0;
static int judgeCount = 0;
public static void main(String[] args) {
// 测试
Queens8 queens8 = new Queens8();
queens8.check(0);
System.out.printf("一共有%d种解法\n", count);
System.out.printf("一共判断冲突%d次", judgeCount);
}
/**
* 放置第n个皇后
*
* @param n 第n个皇后
*/
private void check(int n) {
if (n == max) {
print();
return;
}
// 依次放入皇后,并判断是否冲突
for (int i = 0; i < max; i++) {
// 先把当前皇后n放到该行第一列
locationOfQueensArray[n] = i;
// 判断当放置第n个皇后到i列时,是否冲突
if (judge(n)) {
// 不冲突时接着放n+1个皇后,开始递归
check(n + 1);
}
// 如果冲突,就继续执行locationOfQueensArray[n]=i,即将第n个皇后放置在本行的后一个位置
}
}
/**
* 检测摆放当前第n个皇后时是否和之前的冲突,不冲突可以放
*
* @param n 第n个皇后
* @return 是否和前面摆放的皇后冲突,冲突false不冲突true
*/
private boolean judge(int n) {
judgeCount++;
for (int i = 0; i < n; i++) {
/*
* 说明
* 1.第一个等式判断第n个皇后是否和前面的n-1个皇后在同一列
* 2.第二个等式判断判断第n个皇后是否和第i个皇后在同一斜线
* */
if (locationOfQueensArray[i] == locationOfQueensArray[n] || Math.abs(n - i) == Math
.abs(locationOfQueensArray[n] - locationOfQueensArray[i])) {
return false;
}
}
return true;
}
/**
* 打印皇后摆放的位置
*/
private void print() {
count++;
for (int location : locationOfQueensArray) {
System.out.print(location + " ");
}
System.out.println();
}
}
| true |
cc3d7ab911b346fef28e4dc8a1fcc51a624dbb8f | Java | PrecociouslyDigital/p2pMessager | /Webp2p/src/webp2p/p2p/Peer.java | UTF-8 | 647 | 2.09375 | 2 | [] | no_license | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package webp2p.p2p;
import webp2p.connection.Connection;
/**
*
* @author s-yinb
*/
public class Peer extends Thread{
private Connection server;
public void sendToPeer(WireMessage mess){
server.send(mess);
}
public void sendToPeer(Message mess){
WireMessage sending = new WireMessage(mess, server.ip, new String[]{server.ip});
}
public void handleMessage(WireMessage mess){
}
}
| true |
5c03aaf127febf89b63915c02b06cf60d6b9bae0 | Java | chenrong108/Institution-oriented-Educational-Administration-System | /面向机构的教务系统兼备课系统 后端代码/XiaoJiaoYu/src/main/java/com/scnu/teach/pojo/ProductlineinfoExample.java | UTF-8 | 10,063 | 2.234375 | 2 | [] | no_license | package com.scnu.teach.pojo;
import java.util.ArrayList;
import java.util.List;
public class ProductlineinfoExample {
protected String orderByClause;
protected boolean distinct;
protected List<Criteria> oredCriteria;
public ProductlineinfoExample() {
oredCriteria = new ArrayList<Criteria>();
}
public void setOrderByClause(String orderByClause) {
this.orderByClause = orderByClause;
}
public String getOrderByClause() {
return orderByClause;
}
public void setDistinct(boolean distinct) {
this.distinct = distinct;
}
public boolean isDistinct() {
return distinct;
}
public List<Criteria> getOredCriteria() {
return oredCriteria;
}
public void or(Criteria criteria) {
oredCriteria.add(criteria);
}
public Criteria or() {
Criteria criteria = createCriteriaInternal();
oredCriteria.add(criteria);
return criteria;
}
public Criteria createCriteria() {
Criteria criteria = createCriteriaInternal();
if (oredCriteria.size() == 0) {
oredCriteria.add(criteria);
}
return criteria;
}
protected Criteria createCriteriaInternal() {
Criteria criteria = new Criteria();
return criteria;
}
public void clear() {
oredCriteria.clear();
orderByClause = null;
distinct = false;
}
protected abstract static class GeneratedCriteria {
protected List<Criterion> criteria;
protected GeneratedCriteria() {
super();
criteria = new ArrayList<Criterion>();
}
public boolean isValid() {
return criteria.size() > 0;
}
public List<Criterion> getAllCriteria() {
return criteria;
}
public List<Criterion> getCriteria() {
return criteria;
}
protected void addCriterion(String condition) {
if (condition == null) {
throw new RuntimeException("Value for condition cannot be null");
}
criteria.add(new Criterion(condition));
}
protected void addCriterion(String condition, Object value, String property) {
if (value == null) {
throw new RuntimeException("Value for " + property + " cannot be null");
}
criteria.add(new Criterion(condition, value));
}
protected void addCriterion(String condition, Object value1, Object value2, String property) {
if (value1 == null || value2 == null) {
throw new RuntimeException("Between values for " + property + " cannot be null");
}
criteria.add(new Criterion(condition, value1, value2));
}
public Criteria andProductLineIdIsNull() {
addCriterion("product_Line_Id is null");
return (Criteria) this;
}
public Criteria andProductLineIdIsNotNull() {
addCriterion("product_Line_Id is not null");
return (Criteria) this;
}
public Criteria andProductLineIdEqualTo(Integer value) {
addCriterion("product_Line_Id =", value, "productLineId");
return (Criteria) this;
}
public Criteria andProductLineIdNotEqualTo(Integer value) {
addCriterion("product_Line_Id <>", value, "productLineId");
return (Criteria) this;
}
public Criteria andProductLineIdGreaterThan(Integer value) {
addCriterion("product_Line_Id >", value, "productLineId");
return (Criteria) this;
}
public Criteria andProductLineIdGreaterThanOrEqualTo(Integer value) {
addCriterion("product_Line_Id >=", value, "productLineId");
return (Criteria) this;
}
public Criteria andProductLineIdLessThan(Integer value) {
addCriterion("product_Line_Id <", value, "productLineId");
return (Criteria) this;
}
public Criteria andProductLineIdLessThanOrEqualTo(Integer value) {
addCriterion("product_Line_Id <=", value, "productLineId");
return (Criteria) this;
}
public Criteria andProductLineIdIn(List<Integer> values) {
addCriterion("product_Line_Id in", values, "productLineId");
return (Criteria) this;
}
public Criteria andProductLineIdNotIn(List<Integer> values) {
addCriterion("product_Line_Id not in", values, "productLineId");
return (Criteria) this;
}
public Criteria andProductLineIdBetween(Integer value1, Integer value2) {
addCriterion("product_Line_Id between", value1, value2, "productLineId");
return (Criteria) this;
}
public Criteria andProductLineIdNotBetween(Integer value1, Integer value2) {
addCriterion("product_Line_Id not between", value1, value2, "productLineId");
return (Criteria) this;
}
public Criteria andProductLineNameIsNull() {
addCriterion("product_Line_Name is null");
return (Criteria) this;
}
public Criteria andProductLineNameIsNotNull() {
addCriterion("product_Line_Name is not null");
return (Criteria) this;
}
public Criteria andProductLineNameEqualTo(String value) {
addCriterion("product_Line_Name =", value, "productLineName");
return (Criteria) this;
}
public Criteria andProductLineNameNotEqualTo(String value) {
addCriterion("product_Line_Name <>", value, "productLineName");
return (Criteria) this;
}
public Criteria andProductLineNameGreaterThan(String value) {
addCriterion("product_Line_Name >", value, "productLineName");
return (Criteria) this;
}
public Criteria andProductLineNameGreaterThanOrEqualTo(String value) {
addCriterion("product_Line_Name >=", value, "productLineName");
return (Criteria) this;
}
public Criteria andProductLineNameLessThan(String value) {
addCriterion("product_Line_Name <", value, "productLineName");
return (Criteria) this;
}
public Criteria andProductLineNameLessThanOrEqualTo(String value) {
addCriterion("product_Line_Name <=", value, "productLineName");
return (Criteria) this;
}
public Criteria andProductLineNameLike(String value) {
addCriterion("product_Line_Name like", value, "productLineName");
return (Criteria) this;
}
public Criteria andProductLineNameNotLike(String value) {
addCriterion("product_Line_Name not like", value, "productLineName");
return (Criteria) this;
}
public Criteria andProductLineNameIn(List<String> values) {
addCriterion("product_Line_Name in", values, "productLineName");
return (Criteria) this;
}
public Criteria andProductLineNameNotIn(List<String> values) {
addCriterion("product_Line_Name not in", values, "productLineName");
return (Criteria) this;
}
public Criteria andProductLineNameBetween(String value1, String value2) {
addCriterion("product_Line_Name between", value1, value2, "productLineName");
return (Criteria) this;
}
public Criteria andProductLineNameNotBetween(String value1, String value2) {
addCriterion("product_Line_Name not between", value1, value2, "productLineName");
return (Criteria) this;
}
}
public static class Criteria extends GeneratedCriteria {
protected Criteria() {
super();
}
}
public static class Criterion {
private String condition;
private Object value;
private Object secondValue;
private boolean noValue;
private boolean singleValue;
private boolean betweenValue;
private boolean listValue;
private String typeHandler;
public String getCondition() {
return condition;
}
public Object getValue() {
return value;
}
public Object getSecondValue() {
return secondValue;
}
public boolean isNoValue() {
return noValue;
}
public boolean isSingleValue() {
return singleValue;
}
public boolean isBetweenValue() {
return betweenValue;
}
public boolean isListValue() {
return listValue;
}
public String getTypeHandler() {
return typeHandler;
}
protected Criterion(String condition) {
super();
this.condition = condition;
this.typeHandler = null;
this.noValue = true;
}
protected Criterion(String condition, Object value, String typeHandler) {
super();
this.condition = condition;
this.value = value;
this.typeHandler = typeHandler;
if (value instanceof List<?>) {
this.listValue = true;
} else {
this.singleValue = true;
}
}
protected Criterion(String condition, Object value) {
this(condition, value, null);
}
protected Criterion(String condition, Object value, Object secondValue, String typeHandler) {
super();
this.condition = condition;
this.value = value;
this.secondValue = secondValue;
this.typeHandler = typeHandler;
this.betweenValue = true;
}
protected Criterion(String condition, Object value, Object secondValue) {
this(condition, value, secondValue, null);
}
}
} | true |
bc49b39ef742f19c47556818939c49fd80c314bc | Java | patilpradnya28894/JavaData | /Day 7/Day_7.1/src/test/Program.java | UTF-8 | 627 | 3.5 | 4 | [] | no_license | package test;
public class Program
{
public static void showRecord( )
{
try
{
for( int count = 1; count <= 10; ++ count )
{
System.out.println("Count : "+count);
Thread.sleep(250);
}
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
public static void printRecord( ) throws InterruptedException
{
for( int count = 1; count <= 10; ++ count )
{
System.out.println("Count : "+count);
Thread.sleep(250);
}
}
public static void main(String[] args)
{
try
{
Program.printRecord();
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
| true |
685bda1c84fe6ddc94d34274c3007f7b1922db3a | Java | MayerTh/RVRPSimulator | /vrpsim-core/src/main/java/vrpsim/core/model/util/uncertainty/UncertainParameterContainer.java | UTF-8 | 9,823 | 2.140625 | 2 | [
"Apache-2.0"
] | permissive | /**
* Copyright © 2016 Thomas Mayer (thomas.mayer@unibw.de)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package vrpsim.core.model.util.uncertainty;
import java.util.ArrayList;
import java.util.List;
import vrpsim.core.model.structure.storage.impl.StorableParameters;
public class UncertainParameterContainer {
private final StorableParameters storableParameters;
private final IDistributionFunction startDistributionFunction;
private Double startInstance;
private List<Double> startInstances = new ArrayList<>();
private final IDistributionFunction numberDistributionFunction;
private Double numberInstance;
private List<Double> numberInstances = new ArrayList<>();
private final IDistributionFunction cycleDistributionFunction;
private Double cycleInstance;
private List<Double> cycleInstances = new ArrayList<>();
private final IDistributionFunction earliestDueDateDistributionFunction;
private Double earliestDueDateInstance;
private List<Double> earliestDueDateInstances = new ArrayList<>();
private final IDistributionFunction latestDueDateDistributionFunction;
private Double latestDueDateInstance;
private List<Double> latestDueDateInstances = new ArrayList<>();
private final boolean adaptDueDatesToSimulationTime;
/**
* @param storableParameters
* - defining the storable which are consumed/ordered/...
* @param number
* - amount of storables which are consumed/ordered/...
* @param start
* - the start when the defined amount the first time are
* consumed/ordered/...
*/
public UncertainParameterContainer(final StorableParameters storableParameters, final IDistributionFunction number, final IDistributionFunction start) {
this(storableParameters, number, start, null, null, null, false);
}
/**
* @param storableParameters
* - defining the storable which are consumed/ordered/...
* @param number
* - amount of storables which are consumed/ordered/...
* @param start
* - the start when the defined amount the first time are
* consumed/ordered/...
* @param cycle
* - cycle where defined amount of defined storables are
* consumed/ordered/...
*/
public UncertainParameterContainer(final StorableParameters storableParameters, final IDistributionFunction number, final IDistributionFunction start,
final IDistributionFunction cycle) {
this(storableParameters, number, start, cycle, null, null, false);
}
/**
*
* @param storableParameters
* - defining the storable which are consumed/ordered/...
* @param number
* - amount of storables which are consumed/ordered/...
* @param earliestDueDate
* - earliest delivery of the order, after order is created,
* see {@link UncertainParameterContainer#getNewRealizationOfCycleDistributionFunction()}
* @param latestDueDate
* - latest delivery of the order, after order is created,
* see {@link UncertainParameterContainer#getNewRealizationOfCycleDistributionFunction()}
* @param adaptDueDatesToSimulationTime
* - define if the due dates have to be adapted to simulation
* time.
*/
public UncertainParameterContainer(final StorableParameters storableParameters, final IDistributionFunction number, final IDistributionFunction earliestDueDate,
final IDistributionFunction latestDueDate, final boolean adaptDueDatesToSimulationTime) {
this(storableParameters, number, null, null, earliestDueDate, latestDueDate, adaptDueDatesToSimulationTime);
}
/**
*
* @param storableParameters
* - defining the storable which are consumed/ordered/...
* @param number
* - amount of storables which are consumed/ordered/...
* @param start
* - the start when the defined amount the first time are
* consumed/ordered/...
* @param cycle
* - cycle where defined amount of defined storables are
* consumed/ordered/...
* @param earliestDueDate
* - earliest delivery of the order, after order is created,
* see {@link UncertainParameterContainer#getNewRealizationOfCycleDistributionFunction()}
* @param latestDueDate
* - latest delivery of the order, after order is created,
* see {@link UncertainParameterContainer#getNewRealizationOfCycleDistributionFunction()}
* @param adaptDueDatesToSimulationTime
* - define if the due dates have to be adapted to simulation
* time.
*/
public UncertainParameterContainer(final StorableParameters storableParameters, final IDistributionFunction number, final IDistributionFunction start,
final IDistributionFunction cycle, final IDistributionFunction earliestDueDate, final IDistributionFunction latestDueDate,
final boolean adaptDueDatesToSimulationTime) {
this.startDistributionFunction = start;
this.numberDistributionFunction = number;
this.cycleDistributionFunction = cycle;
this.storableParameters = storableParameters;
this.earliestDueDateDistributionFunction = earliestDueDate;
this.latestDueDateDistributionFunction = latestDueDate;
this.adaptDueDatesToSimulationTime = adaptDueDatesToSimulationTime;
}
/**
* Returns {@link StorableParameters}, which defines the storables
* consumed/ordered/..
*
* @return
*/
public StorableParameters getStorableParameters() {
return storableParameters;
}
/**
* Returns true if the container is cyclic, means if a value for
* {@link UncertainParameterContainer#getNewRealizationOfCycleDistributionFunction()} is defined.
*
* @return
*/
public boolean isCyclic() {
return this.cycleDistributionFunction != null;
}
/**
* Returns true, if you have to adapt the due dates to the current
* simulation time (the current simulation time is the time where you
* would like to create something dependent on this container).
*
* @return
*/
public boolean isAdaptDueDatesToSimulationTime() {
return adaptDueDatesToSimulationTime;
}
/**
* Returns earliest delivery of the order, after order is created, see
* {@link UncertainParameterContainer#getNewRealizationOfCycleDistributionFunction()}. Theoretical
* background are time windows in the context of VRP.
*
* @return
*/
public Double getNewRealizationFromEarliestDueDateDistributionFunction() {
if (this.earliestDueDateDistributionFunction != null) {
this.earliestDueDateInstance = this.earliestDueDateDistributionFunction.getNumber();
this.earliestDueDateInstances.add(this.earliestDueDateInstance);
return this.earliestDueDateInstance;
} else {
return null;
}
}
/**
* Returns latest delivery of the order, after order is created, see
* {@link UncertainParameterContainer#getNewRealizationOfCycleDistributionFunction()}. Theoretical
* background are time windows in the context of VRP.
*
* @return
*/
public Double getNewRealizationFromLatestDueDateDistributionFunction() {
if (this.latestDueDateDistributionFunction != null) {
this.latestDueDateInstance = this.latestDueDateDistributionFunction.getNumber();
this.latestDueDateInstances.add(this.latestDueDateInstance);
return this.latestDueDateInstance;
} else {
return null;
}
}
/**
* Returns the number of storables which are consumed/ordered/...
*
* @return
*/
public Double getNewRealizationFromNumberDistributionFunction() {
if (this.numberDistributionFunction != null) {
this.numberInstance = this.numberDistributionFunction.getNumber();
this.numberInstances.add(this.numberInstance);
return this.numberInstance;
} else {
return null;
}
}
/**
* Returns the cycle when defined amount of defined storables are
* consumed/ordered/...
*
* Can return null.
*
* @return
*/
public Double getNewRealizationOfCycleDistributionFunction() {
if (this.cycleDistributionFunction != null) {
this.cycleInstance = this.cycleDistributionFunction.getNumber();
this.cycleInstances.add(this.cycleInstance);
return this.cycleInstance;
} else {
return null;
}
}
/**
* Returns the start when the defined amount the first time are
* consumed/ordered/...
*
* @return
*/
public Double getNewRealizationFromStartDistributionFunction() {
if (this.startDistributionFunction != null) {
this.startInstance = this.startDistributionFunction.getNumber();
this.startInstances.add(this.startInstance);
return this.startInstance;
} else {
return null;
}
}
public Double getStartInstance() {
return startInstance;
}
public List<Double> getStartInstances() {
return startInstances;
}
public Double getNumberInstance() {
return numberInstance;
}
public List<Double> getNumberInstances() {
return numberInstances;
}
public Double getCycleInstance() {
return cycleInstance;
}
public List<Double> getCycleInstances() {
return cycleInstances;
}
public Double getEarliestDueDateInstance() {
return earliestDueDateInstance;
}
public List<Double> getEarliestDueDateInstances() {
return earliestDueDateInstances;
}
public Double getLatestDueDateInstance() {
return latestDueDateInstance;
}
public List<Double> getLatestDueDateInstances() {
return latestDueDateInstances;
}
}
| true |
0d3cee1dd336e50b551a606f057b89328e6fe729 | Java | thomasboel/ClientServerChatSimplified | /src/main/java/com/thom/cc/account/Account.java | UTF-8 | 446 | 2.03125 | 2 | [] | no_license | package com.thom.cc.account;
import lombok.AccessLevel;
import lombok.Data;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import java.beans.ConstructorProperties;
import java.util.ArrayList;
@Data
@RequiredArgsConstructor(access = AccessLevel.PUBLIC)
public class Account {
@NonNull private String username;
@NonNull private String password;
private final ArrayList<Account> friendList = new ArrayList<Account>();
} | true |
e973986bd563748d72cc5cb0f4caf81748283bda | Java | LADOSSIFPB/quality-manager | /quality-manager-web/src/main/java/convert/CommaSeparatedFieldConverter.java | UTF-8 | 916 | 2.515625 | 3 | [] | no_license | package convert;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
@FacesConverter("commaSeparatedFieldConverter")
public class CommaSeparatedFieldConverter implements Converter {
@Override
public String getAsString(FacesContext context, UIComponent component,
Object value) {
if (value == null) {
return null;
}
String[] strings = (String[]) value;
StringBuilder builder = new StringBuilder();
for (String string : strings) {
if (builder.length() > 0) {
builder.append(",");
}
builder.append(string);
}
return builder.toString();
}
@Override
public Object getAsObject(FacesContext context, UIComponent component,
String value) {
if (value == null) {
return null;
}
return value.split(",");
}
} | true |
b50cfcd9e2adf3c4704d70fb84da6a8df11de3c2 | Java | gsiu-criobe/commander | /commander/src/main/java/com/ted/commander/client/events/OAuthFailEvent.java | UTF-8 | 784 | 2.09375 | 2 | [
"Apache-2.0"
] | permissive | /*
* Copyright 2015 The Energy Detective. All Rights Reserved.
*/
package com.ted.commander.client.events;
import com.google.gwt.event.shared.GwtEvent;
public class OAuthFailEvent extends GwtEvent<OAuthHandler> {
public static Type<OAuthHandler> TYPE = new Type<OAuthHandler>();
final String errorMessage;
public OAuthFailEvent(String errorMessage) {
this.errorMessage = errorMessage;
}
@Override
public Type<OAuthHandler> getAssociatedType() {
return TYPE;
}
@Override
protected void dispatch(OAuthHandler handler) {
handler.onFail(this);
}
@Override
public String toString() {
return "OAuthFailEvent{" +
"errorMessage='" + errorMessage + '\'' +
'}';
}
}
| true |
311b01566c92d400429f3e476d2bc2eef3dc58e0 | Java | jtransc/jtransc-examples | /stress/src/main/java/com/stress/sub0/sub1/Class332.java | UTF-8 | 381 | 2.203125 | 2 | [] | no_license | package com.stress.sub0.sub1;
import com.jtransc.annotation.JTranscKeep;
@JTranscKeep
public class Class332 {
public static final String static_const_332_0 = "Hi, my num is 332 0";
static int static_field_332_0;
int member_332_0;
public void method332()
{
System.out.println(static_const_332_0);
}
public void method332_1(int p0, String p1)
{
System.out.println(p1);
}
}
| true |
9baef61be5d54b2bd6731c11141524ea441e00ea | Java | kundan2/Java | /crud1/src/UpdateRecord.java | UTF-8 | 2,149 | 2.421875 | 2 | [] | no_license |
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class UpdateRecobrd
*/
@WebServlet("/UpdateRecord")
public class UpdateRecord extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public UpdateRecord() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out=response.getWriter();
String name=request.getParameter("name");
int mark=Integer.parseInt(request.getParameter("mark"));
int rollno=Integer.parseInt(request.getParameter("rollno"));
String city=request.getParameter("city");
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb","root","root");
PreparedStatement ps=con.prepareStatement("update student set name=?,mark=?,city=? where rollno=?");
ps.setString(1, name);
ps.setInt(2, mark);
ps.setString(3, city);
ps.setInt(4, rollno);
int row = ps.executeUpdate();
if(row>0)
{
out.print("<script>alert('Data Updated Successfully');window.location='InsertData';</script>");
}
else
{
out.print("<script>alert('Data Not Updated Successfully');window.location='InsertData';</script>");
}
}
catch(Exception e)
{
System.out.println(e);
}
}
}
| true |
87a9467a3b9347066614b7470f635221095c7d48 | Java | satyamjava/cgweb | /src/com/corporate/gazetteer/object/EmpCompClientStak.java | UTF-8 | 2,047 | 2.09375 | 2 | [] | no_license | package com.corporate.gazetteer.object;
public class EmpCompClientStak {
public String roll; //OR Action----Employee, Company, Client, StackHolder
public String mobileNo;
public String phoneNo;
public String faxNo;
public String addressLineOne;
public String addressLineTwo;
public String city;
public String state;
public String zip;
public String countryName;
public EmpCompClientStak(String l_roll, String l_mobile, String l_phone, String l_fax, String l_add_1, String l_add_2, String l_city, String l_state, String l_zip, String l_country) {
roll = l_roll;
mobileNo = l_mobile;
phoneNo = l_phone;
faxNo = l_fax;
addressLineOne = l_add_1;
addressLineTwo = l_add_2;
city = l_city;
state = l_state;
zip = l_zip;
countryName = l_country;
}
public String getRoll() {
return roll;
}
public void setRoll(String l_roll) {
roll = l_roll;
}
public String getMobileNo() {
return mobileNo;
}
public void setMobileNo(String l_mobileNo) {
mobileNo = l_mobileNo;
}
public String getPhoneNo() {
return phoneNo;
}
public void setPhoneNo(String l_phoneNo) {
phoneNo = l_phoneNo;
}
public String getFaxNo() {
return faxNo;
}
public void setFaxNo(String l_faxNo) {
faxNo = l_faxNo;
}
public String getAddressLineOne() {
return addressLineOne;
}
public void setAddressLineOne(String l_addressLineOne) {
addressLineOne = l_addressLineOne;
}
public String getAddressLineTwo() {
return addressLineTwo;
}
public void setAddressLineTwo(String l_addressLineTwo) {
addressLineTwo = l_addressLineTwo;
}
public String getCity() {
return city;
}
public void setCity(String l_city) {
city = l_city;
}
public String getState() {
return state;
}
public void setState(String l_state) {
state = l_state;
}
public String getZip() {
return zip;
}
public void setZip(String l_zip) {
zip = l_zip;
}
public String getCountryName() {
return countryName;
}
public void setCountryName(String l_countryName) {
countryName = l_countryName;
}
}
| true |
d282ccf8b92f9e6a2428fbb024e2a62406af3579 | Java | jihyun-um/design-patterns | /src/com/jihyunum/patterns/behavioral/observer/publisher/CovidCasePublisher.java | UTF-8 | 413 | 2.765625 | 3 | [] | no_license | package com.jihyunum.patterns.behavioral.observer.publisher;
public class CovidCasePublisher {
public CovidCaseManager covidCaseManager;
public CovidCasePublisher() {
covidCaseManager = new CovidCaseManager(new String[] {"South Korea", "UK", "US"});
}
public void updateNumberOfCases(String country, int numberOfCases) {
covidCaseManager.notify(country, numberOfCases);
}
}
| true |
7b3524a47599199cf641477c019f2a15d17511d0 | Java | hyleene/ThatsLife | /src/gui/ChoosePlayer.java | UTF-8 | 4,296 | 3.78125 | 4 | [] | no_license | package gui;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.*;
import java.awt.event.ActionListener;
import java.util.ArrayList;
/**
* Class implementing a <b>ChoosePlayer window</b> as part of the GUI for
* choosing another player
*/
public class ChoosePlayer extends JFrame {
/**
* List of buttons for choosing the players in the game
*/
private ArrayList<JButton> btnChoices;
/**
* Prompt indicating instructions for the player
*/
private JLabel lblMessage;
/**
* Creates a ChoosePlayer object
*
* <p>As part of the larger interface of the game, this window cannot be closed without proper player input;
* it remains visible until the player presses one of the buttons.</p>
*
* @param title title of the window
* @param message message containing player instructions
* @param names list of names of the players
*/
public ChoosePlayer (String title, String message, ArrayList<String> names) {
/* The passed parameter title is passed as the label for the title bar */
super(title);
/* Additional formatting methods for the window are executed */
setLayout(new BorderLayout());
/* init() is called to initialize the elements of the window */
init(message, names);
/* Additional formatting methods for the window are executed */
setUndecorated(true);
getRootPane().setBorder(BorderFactory.createLineBorder(new Color(139, 0, 139), 8));
setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
setSize(300, 200);
setLocationRelativeTo(null);
setResizable(false);
setVisible(true);
}
/**
* Initializes the elements of the ChoosePlayer object
*
* <p>The object contains buttons for each of the players in the game.</p>
*
* @param message prompt indicating instructions for the player
* @param names list of names of the players in the game
*/
private void init(String message, ArrayList<String> names) {
/* JPanels used to arrange the window elements */
JPanel pMain;
JPanel pBox;
/* A new array list is created for the JButtons */
btnChoices = new ArrayList<>();
/* The pMain panel is formatted */
pMain = new JPanel();
pMain.setLayout(new BorderLayout());
pMain.setBackground(new Color(142, 229, 238));
/* The pBox panel is formatted; it can hold at most three elements (corresponding to
the maximum number of players in the game)
*/
pBox = new JPanel();
pBox.setLayout(new GridLayout(3, 1));
pBox.setBackground(new Color(142, 229, 238));
pBox.setBorder(new EmptyBorder(10, 40, 10, 40));
/* The player prompt is formatted and added to the window */
lblMessage = new JLabel("<html><center>" + message + "</center></html>");
lblMessage.setBorder(new EmptyBorder(10, 10, 10, 10));
pMain.add(lblMessage);
add (pMain, BorderLayout.NORTH);
/* The names of each of the players in the game are used to create the
window buttons
*/
for (int i = 0; i < names.size(); i++) {
btnChoices.add(new JButton("Choose " + names.get(i)));
pBox.add(btnChoices.get(i));
}
/* The panel containing the window buttons is added to the window */
add(pBox, BorderLayout.CENTER);
}
/**
* Enables a button at a particular index
*
* <p>One of the window buttons is made clickable.</p>
*
* @param isEnabled boolean value enabling or disabling the button
* @param index index of the button to be made clickable
*/
public void setChooseEnabled(boolean isEnabled, int index) {
btnChoices.get(index).setEnabled(isEnabled);
}
/**
* Sets action listeners for the window
*
* <p>Action listeners are added for each of the buttons in the window.</p>
*
* @param listener action listener for the window buttons
*/
public void setActionListener(ActionListener listener) {
for (int i = 0; i < btnChoices.size(); i++)
btnChoices.get(i).addActionListener(listener);
}
}
| true |
0c84cd71938a8ae521afa838741c353e94d39281 | Java | yinzhidong/tmpp-admin | /src/main/java/top/itning/tmpp/tmppadmin/pojo/AdminUserRoleResource.java | UTF-8 | 810 | 1.929688 | 2 | [] | no_license | package top.itning.tmpp.tmppadmin.pojo;
import java.util.Date;
public class AdminUserRoleResource extends AdminUserRoleResourceKey {
private Date gmtCreate;
private Date gmtModified;
public AdminUserRoleResource(Integer userRoleId, String resourceId, Date gmtCreate, Date gmtModified) {
super(userRoleId, resourceId);
this.gmtCreate = gmtCreate;
this.gmtModified = gmtModified;
}
public AdminUserRoleResource() {
super();
}
public Date getGmtCreate() {
return gmtCreate;
}
public void setGmtCreate(Date gmtCreate) {
this.gmtCreate = gmtCreate;
}
public Date getGmtModified() {
return gmtModified;
}
public void setGmtModified(Date gmtModified) {
this.gmtModified = gmtModified;
}
} | true |
fe150c8dcdee852d1e2da03d644eaac6afa65061 | Java | OneLemonyBoi/Satisforestry | /Render/ResourceNodeRenderer.java | UTF-8 | 10,075 | 1.796875 | 2 | [] | no_license | /*******************************************************************************
* @author Reika Kalseki
*
* Copyright 2017
*
* All rights reserved.
* Distribution of the software in any form is only allowed with
* explicit, prior permission from the owner.
******************************************************************************/
package Reika.Satisforestry.Render;
import net.minecraft.block.Block;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.RenderBlocks;
import net.minecraft.client.renderer.Tessellator;
import net.minecraft.util.IIcon;
import net.minecraft.world.EnumSkyBlock;
import net.minecraft.world.IBlockAccess;
import net.minecraft.world.World;
import Reika.DragonAPI.Base.ISBRH;
import Reika.DragonAPI.Instantiable.Math.Noise.SimplexNoiseGenerator;
import Reika.DragonAPI.Libraries.Java.ReikaRandomHelper;
import Reika.DragonAPI.Libraries.MathSci.ReikaMathLibrary;
import Reika.DragonAPI.Libraries.Rendering.ReikaColorAPI;
import Reika.Satisforestry.Blocks.BlockResourceNode;
import Reika.Satisforestry.Blocks.BlockResourceNode.TileResourceNode;
import Reika.Satisforestry.Config.ResourceItem;
public class ResourceNodeRenderer extends ISBRH {
public ResourceNodeRenderer(int id) {
super(id);
}
@Override
public void renderInventoryBlock(Block block, int metadata, int modelId, RenderBlocks renderer) {
}
@Override
public boolean renderWorldBlock(IBlockAccess world, int x, int y, int z, Block block, int modelId, RenderBlocks renderer) {
Tessellator v5 = Tessellator.instance;
TileResourceNode te = (TileResourceNode)world.getTileEntity(x, y, z);
ResourceItem ri = te.getResource();
int c = ri == null ? 0xffffff : ri.color;
if (renderPass == 0) {
v5.setColorOpaque_I(0xffffff);
renderer.renderStandardBlockWithAmbientOcclusion(block, x, y, z, 1, 1, 1);
}
else {
v5.setBrightness(240);
World w = Minecraft.getMinecraft().theWorld;
float l = Math.max(w.getSavedLightValue(EnumSkyBlock.Block, x, y+1, z), w.getSavedLightValue(EnumSkyBlock.Sky, x, y+1, z)*w.getSunBrightnessFactor(0));
float a = 1-l/24F;
if (a < 1) {
c = ReikaColorAPI.mixColors(c, 0xffffff, a*0.5F+0.5F);
}
v5.setColorRGBA_I(c, (int)(a*255));
}
rand.setSeed(this.calcSeed(x, y, z));
rand.nextBoolean();
IIcon ico = renderPass == 1 ? BlockResourceNode.getOverlay() : block.blockIcon;
int n = ReikaRandomHelper.getRandomBetween(5, 9, rand);
double minr = 1.75;
double maxr = 2.25;
double da = 360D/n;
for (int i = 0; i < n; i++) {
double ox = ReikaRandomHelper.getRandomPlusMinus(0, 0.09375, rand);
double oz = ReikaRandomHelper.getRandomPlusMinus(0, 0.09375, rand);
double h = ReikaRandomHelper.getRandomBetween(0.0625, 0.1875, rand);
double dy = y+1+h;
boolean split = rand.nextInt(3) > 0;
double r1 = ReikaRandomHelper.getRandomBetween(0.25, 0.625, rand);
double r2 = Math.max(r1+0.5, ReikaRandomHelper.getRandomBetween(minr, maxr, rand));
double f = ReikaRandomHelper.getRandomBetween(0.625, 0.875, rand);
double aw = da*f/2D;
double oa = (1-f)*da/2D;
double a0 = da*i+oa;
double a1 = Math.toRadians(a0-aw);
double a2 = Math.toRadians(a0+aw);
double oo = 0.09375;
double x1 = r1*Math.cos(a1)+ox+ReikaRandomHelper.getRandomPlusMinus(0, oo, rand);
double x2 = r1*Math.cos(a2)+ox+ReikaRandomHelper.getRandomPlusMinus(0, oo, rand);
double x3 = r2*Math.cos(a2)+ox+ReikaRandomHelper.getRandomPlusMinus(0, oo, rand);
double x4 = r2*Math.cos(a1)+ox+ReikaRandomHelper.getRandomPlusMinus(0, oo, rand);
double z1 = r1*Math.sin(a1)+oz+ReikaRandomHelper.getRandomPlusMinus(0, oo, rand);
double z2 = r1*Math.sin(a2)+oz+ReikaRandomHelper.getRandomPlusMinus(0, oo, rand);
double z3 = r2*Math.sin(a2)+oz+ReikaRandomHelper.getRandomPlusMinus(0, oo, rand);
double z4 = r2*Math.sin(a1)+oz+ReikaRandomHelper.getRandomPlusMinus(0, oo, rand);
if (split) {
double xm = Math.cos(Math.toRadians(a0));
double zm = Math.sin(Math.toRadians(a0));
double xa = xm*r1+ox+ReikaRandomHelper.getRandomPlusMinus(0, oo, rand);
double xb = xm*r2+ox+ReikaRandomHelper.getRandomPlusMinus(0, oo, rand);
double za = zm*r1+oz+ReikaRandomHelper.getRandomPlusMinus(0, oo, rand);
double zb = zm*r2+oz+ReikaRandomHelper.getRandomPlusMinus(0, oo, rand);
this.addVertexAt(v5, x, dy, z, maxr, ico, x1, z1);
this.addVertexAt(v5, x, dy, z, maxr, ico, xa, za);
this.addVertexAt(v5, x, dy, z, maxr, ico, xb, zb);
this.addVertexAt(v5, x, dy, z, maxr, ico, x4, z4);
this.addVertexAt(v5, x, dy, z, maxr, ico, xa, za);
this.addVertexAt(v5, x, dy, z, maxr, ico, x2, z2);
this.addVertexAt(v5, x, dy, z, maxr, ico, x3, z3);
this.addVertexAt(v5, x, dy, z, maxr, ico, xb, zb);
this.addVertexAt(v5, x, y+1, z, maxr, ico, x1, z1);
this.addVertexAt(v5, x, y+1, z, maxr, ico, xa, za);
this.addVertexAt(v5, x, dy, z, maxr, ico, xa, za);
this.addVertexAt(v5, x, dy, z, maxr, ico, x1, z1);
this.addVertexAt(v5, x, y+1, z, maxr, ico, xa, za);
this.addVertexAt(v5, x, y+1, z, maxr, ico, x2, z2);
this.addVertexAt(v5, x, dy, z, maxr, ico, x2, z2);
this.addVertexAt(v5, x, dy, z, maxr, ico, xa, za);
this.addVertexAt(v5, x, dy, z, maxr, ico, x4, z4);
this.addVertexAt(v5, x, dy, z, maxr, ico, xb, zb);
this.addVertexAt(v5, x, y+1, z, maxr, ico, xb, zb);
this.addVertexAt(v5, x, y+1, z, maxr, ico, x4, z4);
this.addVertexAt(v5, x, dy, z, maxr, ico, xb, zb);
this.addVertexAt(v5, x, dy, z, maxr, ico, x3, z3);
this.addVertexAt(v5, x, y+1, z, maxr, ico, x3, z3);
this.addVertexAt(v5, x, y+1, z, maxr, ico, xb, zb);
this.addVertexAt(v5, x, y+1, z, maxr, ico, x1, z1);
this.addVertexAt(v5, x, dy, z, maxr, ico, x1, z1);
this.addVertexAt(v5, x, dy, z, maxr, ico, x4, z4);
this.addVertexAt(v5, x, y+1, z, maxr, ico, x4, z4);
this.addVertexAt(v5, x, y+1, z, maxr, ico, x3, z3);
this.addVertexAt(v5, x, dy, z, maxr, ico, x3, z3);
this.addVertexAt(v5, x, dy, z, maxr, ico, x2, z2);
this.addVertexAt(v5, x, y+1, z, maxr, ico, x2, z2);
}
else {
this.addVertexAt(v5, x, dy, z, maxr, ico, x1, z1);
this.addVertexAt(v5, x, dy, z, maxr, ico, x2, z2);
this.addVertexAt(v5, x, dy, z, maxr, ico, x3, z3);
this.addVertexAt(v5, x, dy, z, maxr, ico, x4, z4);
this.addVertexAt(v5, x, y+1, z, maxr, ico, x1, z1);
this.addVertexAt(v5, x, y+1, z, maxr, ico, x2, z2);
this.addVertexAt(v5, x, dy, z, maxr, ico, x2, z2);
this.addVertexAt(v5, x, dy, z, maxr, ico, x1, z1);
this.addVertexAt(v5, x, dy, z, maxr, ico, x4, z4);
this.addVertexAt(v5, x, dy, z, maxr, ico, x3, z3);
this.addVertexAt(v5, x, y+1, z, maxr, ico, x3, z3);
this.addVertexAt(v5, x, y+1, z, maxr, ico, x4, z4);
this.addVertexAt(v5, x, y+1, z, maxr, ico, x1, z1);
this.addVertexAt(v5, x, dy, z, maxr, ico, x1, z1);
this.addVertexAt(v5, x, dy, z, maxr, ico, x4, z4);
this.addVertexAt(v5, x, y+1, z, maxr, ico, x4, z4);
this.addVertexAt(v5, x, y+1, z, maxr, ico, x3, z3);
this.addVertexAt(v5, x, dy, z, maxr, ico, x3, z3);
this.addVertexAt(v5, x, dy, z, maxr, ico, x2, z2);
this.addVertexAt(v5, x, y+1, z, maxr, ico, x2, z2);
}
}
if (renderPass == 1) {
v5.setColorOpaque_I(c);
ico = BlockResourceNode.getCrystal();
SimplexNoiseGenerator gen = (SimplexNoiseGenerator)new SimplexNoiseGenerator(rand.nextLong()).setFrequency(12);
n = 8;
double dd = 1D/n;
double r = ReikaMathLibrary.roundToNearestFraction(ReikaRandomHelper.getRandomBetween(minr-0.5, minr-0.25, rand), dd);
double h = 0.4;
double dhl = 0.15;
double oy = 0.995;
for (double i = -r; i <= r; i += dd) {
for (double k = -r; k <= r; k += dd) {
double dh11 = Math.max(-0.5, -dhl*ReikaMathLibrary.py3d(i, 0, k));
double dh12 = Math.max(-0.5, -dhl*ReikaMathLibrary.py3d(i, 0, k+dd));
double dh21 = Math.max(-0.5, -dhl*ReikaMathLibrary.py3d(i+dd, 0, k));
double dh22 = Math.max(-0.5, -dhl*ReikaMathLibrary.py3d(i+dd, 0, k+dd));
/*
double y11 = rand.nextDouble()*h*dh11;
double y12 = rand.nextDouble()*h*dh12;
double y21 = rand.nextDouble()*h*dh21;
double y22 = rand.nextDouble()*h*dh22;
*/
double x1 = x+0.5+i;
double x2 = x+0.5+i+dd;
double z1 = z+0.5+k;
double z2 = z+0.5+k+dd;
double y11 = ReikaMathLibrary.normalizeToBounds(gen.getValue(x1, z1), 0, 1)*h+dh11;
double y12 = ReikaMathLibrary.normalizeToBounds(gen.getValue(x1, z2), 0, 1)*h+dh12;
double y21 = ReikaMathLibrary.normalizeToBounds(gen.getValue(x2, z1), 0, 1)*h+dh21;
double y22 = ReikaMathLibrary.normalizeToBounds(gen.getValue(x2, z2), 0, 1)*h+dh22;
double u1 = ico.getInterpolatedU((i+r)*16D/(r*2));
double u2 = Math.min(ico.getMaxU(), ico.getInterpolatedU((i+dd+r)*16D/(r*2)));
double v1 = ico.getInterpolatedV((k+r)*16D/(r*2));
double v2 = Math.min(ico.getMaxV(), ico.getInterpolatedV((k+dd+r)*16D/(r*2)));
if (rand.nextBoolean()) {
double s = u2;
u2 = u1;
u1 = s;
}
if (rand.nextBoolean()) {
double s = v2;
v2 = v1;
v1 = s;
}
v5.addVertexWithUV(x1, y+oy+y12, z2, u1, v2);
v5.addVertexWithUV(x2, y+oy+y22, z2, u2, v2);
v5.addVertexWithUV(x2, y+oy+y21, z1, u2, v1);
v5.addVertexWithUV(x1, y+oy+y11, z1, u1, v1);
}
}
}
return true;
}
private void addVertexAt(Tessellator v5, int x, double y, int z, double maxr, IIcon ico, double dx, double dz) {
double x2 = x+0.5+dx;
double z2 = z+0.5+dz;
double x0 = x+0.5-maxr;
double z0 = z+0.5-maxr;
double fx = (x2-x0)/(maxr*2);//ReikaMathLibrary.getDecimalPart(x2);
double fz = (z2-z0)/(maxr*2);//ReikaMathLibrary.getDecimalPart(z2);
double u = ico.getInterpolatedU(fx*16+0.01);
double v = ico.getInterpolatedV(fz*16+0.01); //tiny offset is to avoid the selection lying right at the boundary between two px and giving flicker
v5.addVertexWithUV(x2, y, z2, u, v);
}
@Override
public boolean shouldRender3DInInventory(int modelId) {
return false;
}
}
| true |
f21cb1cb1993f0b75da403b3449ec0d5522d9412 | Java | wilau2/GLO-4003 | /HouseMatch/src/main/java/ca/ulaval/glo4003/b6/housematch/dto/assembler/DescriptionAssembler.java | UTF-8 | 2,719 | 2.484375 | 2 | [] | no_license | package ca.ulaval.glo4003.b6.housematch.dto.assembler;
import ca.ulaval.glo4003.b6.housematch.domain.estate.Description;
import ca.ulaval.glo4003.b6.housematch.domain.estate.builder.DescriptionBuilder;
import ca.ulaval.glo4003.b6.housematch.dto.DescriptionDto;
public class DescriptionAssembler {
public Description assembleDescription(DescriptionDto descriptionDto) {
if (descriptionDto == null) {
return new Description();
}
DescriptionBuilder descriptionBuilder = new DescriptionBuilder();
Integer numberOfBedRooms = descriptionDto.getNumberOfBedRooms();
Integer numberOfBathrooms = descriptionDto.getNumberOfBathrooms();
Integer numberOfRooms = descriptionDto.getNumberOfRooms();
Integer numberOfLevel = descriptionDto.getNumberOfLevel();
Integer yearsOfConstruction = descriptionDto.getYearOfConstruction();
String dimensionsBuilding = descriptionDto.getBuildingDimension();
Integer livingSpaceAreaSquareMeter = descriptionDto.getLivingSpaceAreaSquareMeter();
Integer municipalValuation = descriptionDto.getMunicipalAssessment();
String backyardOrientation = descriptionDto.getBackyardOrientation();
return descriptionBuilder.setNewBackyardOrientation(backyardOrientation)
.setNewDimensionsBuilding(dimensionsBuilding).setNewLivingSpaceAreaSquareMeter(livingSpaceAreaSquareMeter)
.setNewMunicipalValuation(municipalValuation).setNewNumberOfBathrooms(numberOfBathrooms)
.setNewNumberOfBedRooms(numberOfBedRooms).setNewNumberOfLevel(numberOfLevel)
.setNewNumberOfRooms(numberOfRooms).setNewYearsOfConstruction(yearsOfConstruction).buildDescription();
}
public DescriptionDto assembleDescriptionDto(Description description) {
Integer numberOfBedRooms = description.getNumberOfBedRooms();
Integer numberOfBathrooms = description.getNumberOfBathrooms();
Integer numberOfRooms = description.getNumberOfRooms();
Integer numberOfLevel = description.getNumberOfLevel();
Integer yearsOfConstruction = description.getYearOfConstruction();
String dimensionsBuilding = description.getBuildingDimensions();
Integer livingSpaceAreaSquareMeter = description.getLivingSpaceAreaSquareMeter();
Integer municipalValuation = description.getMunicipalAssessment();
String backyardOrientation = description.getBackyardOrientation();
DescriptionDto descriptionDto = new DescriptionDto(numberOfBedRooms, numberOfBathrooms, numberOfRooms,
numberOfLevel, yearsOfConstruction, dimensionsBuilding, livingSpaceAreaSquareMeter, municipalValuation,
backyardOrientation);
return descriptionDto;
}
}
| true |
ce3c66906c4269bfb692819622b8043308a4aec5 | Java | GyanTech877/Google | /BinarySearch/MedianOfTwoSortedArray.java | UTF-8 | 1,850 | 3.75 | 4 | [] | no_license | /*
There are two sorted arrays A and B of size m and n respectively.
Find the median of the two sorted arrays ( The median of the array formed by merging both the arrays ).
The overall run time complexity should be O(log (m+n)).
Sample Input
A : [1 4 5]
B : [2 3]
Sample Output
3
NOTE: IF the number of elements in the merged array is even, then the median is the average of n / 2 th and n/2 + 1th element.
For example, if the array is [1 2 3 4], the median is (2 + 3) / 2.0 = 2.5
*/
public class Solution {
public double findMedianSortedArrays(final List<Integer> a, final List<Integer> b) {
if(a==null || b==null || (a.size()==0 && b.size()==0)) return -1.00;
if(a.size()>b.size()) return findMedianSortedArrays(b,a);
if(a.size()==0){
int size = b.size();
if(size%2==0){
return (b.get(size/2-1)+b.get(size/2))/2.00;
}
else{
return b.get(size/2);
}
}
int start = 0;
int end = a.size();
int length = (a.size()+b.size()+1)/2;
while(start<=end){
int midA = (start+end)/2;
int midB = length - midA;
int leftMidA=(midA==0)?Integer.MIN_VALUE:a.get(midA-1);
int leftMidB=(midB==0)?Integer.MIN_VALUE:b.get(midB-1);
int rightMidA=(midA==a.size())?Integer.MAX_VALUE:a.get(midA);
int rightMidB=(midB==b.size())?Integer.MAX_VALUE:b.get(midB);
if(leftMidA<=rightMidB && leftMidB<=rightMidA){
if((a.size()+b.size())%2==0){
return (Math.max(leftMidB,leftMidA) + Math.min(rightMidA,rightMidB))/2.00;
}
else{
return Math.max(leftMidB,leftMidA)*1.00;
}
}
else if(leftMidA>rightMidB){
end = midA-1;
}
else start = midA+1;
}
return -1.00;
}
}
| true |
8db7c9522200ef18fb7ac10f129a5ee1b7c39b8a | Java | benben198805/booking-example-gradle | /src/main/java/rental/presentation/exception/InvalidParamException.java | UTF-8 | 201 | 2.171875 | 2 | [] | no_license | package rental.presentation.exception;
public class InvalidParamException extends AppException {
public InvalidParamException(String code, String message) {
super(code, message);
}
}
| true |
d212f120533196a46ebd6466ac19677bf4b7a8d6 | Java | povrtar/My-practice-project | /01-my-library-practice/src/main/java/com/myperssonal/demo/service/BookService.java | UTF-8 | 470 | 2.09375 | 2 | [] | no_license | package com.myperssonal.demo.service;
import java.util.List;
import com.myperssonal.demo.entity.Book;
public interface BookService {
public void saveBook(Book theBook);
public Book getBook(int theId);
public void deleteBook(int theId);
public List<Book> getBooksByTitle(String title);
public List<Book> getBooksByAutor(String lastName);
public boolean isComplete(Book theBook);
public List<Book> getBooks();
}
| true |
71d4a0f2a683e785ca15050107b72219199ad38b | Java | frederic-orlando/android-hoonian-agent | /app/src/main/java/com/example/hoonianAgent/view/viewholder/contacts/VHContact.java | UTF-8 | 1,700 | 2.203125 | 2 | [] | no_license | package com.example.hoonianAgent.view.viewholder.contacts;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.example.hoonianAgent.R;
import com.example.hoonianAgent.model.content.contacts.Contacts;
import com.example.hoonianAgent.presenter.callback.RecyclerListener;
import com.example.hoonianAgent.view.viewholder.base.BaseViewHolder;
public class VHContact extends BaseViewHolder<Contacts> {
private TextView avatar;
private TextView nameLbl;
private TextView recommendLbl;
private TextView purchaseLbl;
private LinearLayout recommendLayout;
private LinearLayout purchaseLayout;
public VHContact(View itemView, RecyclerListener recyclerListener) {
super(itemView, recyclerListener);
avatar = findView(R.id.avatar);
nameLbl = findView(R.id.nameLbl);
recommendLbl = findView(R.id.recommendLbl);
purchaseLbl = findView(R.id.purchaseLbl);
recommendLayout = findView(R.id.recommendLayout);
purchaseLayout = findView(R.id.purchaseLayout);
}
@Override
public void setData(Contacts data) {
super.setData(data);
avatar.setText(data.getName().substring(0,1));
nameLbl.setText(data.getName());
int referred = data.getReferred();
if (referred > 0) {
recommendLbl.setText("" + referred);
}
else {
recommendLayout.setVisibility(View.INVISIBLE);
}
int purchase = data.getPurchase();
if (purchase > 0) {
purchaseLbl.setText("" + purchase);
}
else {
purchaseLayout.setVisibility(View.INVISIBLE);
}
}
}
| true |
b9b7768a0d5066f2d08d5a4497b40044c1445f99 | Java | 777shengjunjie/java | /arithmetic/Depth_first_Search_arithmetic/src/GetImportance_690/GetImportance.java | UTF-8 | 2,854 | 3.546875 | 4 | [] | no_license | package GetImportance_690;
import UtilClass.Employee;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* 给定一个保存员工信息的数据结构,它包含了员工唯一的id,重要度和直系下属的id。
* 比如,员工1是员工2的领导,员工2是员工3的领导。他们相应的重要度为15, 10, 5。
* 那么员工1的数据结构是[1, 15, [2]],员工2的数据结构是[2, 10, [3]],
* 员工3的数据结构是[3, 5, []]。注意虽然员工3也是员工1的一个下属,但是由于并不是直系下属,
* 因此没有体现在员工1的数据结构中。
* 现在输入一个公司的所有员工信息,以及单个员工id,返回这个员工和他所有下属的重要度之和。
*/
public class GetImportance {
public int importance=0;
public static void main(String[] args) {
Employee el1=new Employee();
el1.id=1;
el1.importance=5;
el1.subordinates=new ArrayList<>(){
{
add(2);
add(3);
}
};
Employee el2=new Employee();
el2.id=2;
el2.importance=3;
el2.subordinates=new ArrayList<>();
Employee el3=new Employee();
el3.id=3;
el3.importance=3;
el3.subordinates=new ArrayList<>();
List<Employee> employees=new ArrayList<>(){
{
add(el1);
add(el2);
add(el3);
}
};
int id =1;
int result =new GetImportance().getImportance(employees,id);
System.out.println(result);
}
public int getImportance(List<Employee> employees,int id){
return helper(employees,id);
}
private int helper(List<Employee> employees, int id) {
for (Employee employee : employees) {
if (employee.id==id){
if (employee.subordinates.isEmpty()) {
importance=importance+employee.importance;
return importance;
}
while (!employee.subordinates.isEmpty()){
int sid=employee.subordinates.remove(0);
helper(employees,sid);
}
importance+=employee.importance;
}
}
return importance;
}
Map<Integer, Employee> emap;
public int getImportance2(List<Employee> employees, int queryid) {
emap = new HashMap();
for (Employee e: employees) emap.put(e.id, e);
return dfs(queryid);
}
public int dfs(int eid) {
Employee employee = emap.get(eid);
int ans = employee.importance;
for (Integer subid: employee.subordinates)
ans += dfs(subid);
return ans;
}
}
| true |
6f7300b113b45f485b677f21d0fe3f735d6fb2ae | Java | sheikhu/Treasure-Map | /src/main/java/com/carbonit/map/InputParser.java | UTF-8 | 94 | 1.710938 | 2 | [] | no_license | package com.carbonit.map;
public interface InputParser {
Map parse() throws Exception;
}
| true |
3cc10809adb50cc54d77ef49bdd54d99bd1c5a5c | Java | h2hyun37/algostudy | /study-algorithm/src/xenomity/examination/tree/BST.java | UTF-8 | 3,783 | 3.421875 | 3 | [] | no_license | package xenomity.examination.tree;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import xenomity.examination.tree.structure.BinaryTree;
import xenomity.examination.tree.structure.TreeNode;
/**
* Binary Search Tree Test
*
* @author Xenomity a.k.a P-slinc' (이승한)
*
*/
public class BST {
private static final int[] SOURCE = new int[] { 30, 20, 40, 10, 25, 35, 45 };
private BinaryTree rootNode;
@Before
public void setUp() throws IllegalAccessException {
rootNode = new BinaryTree(SOURCE[0]);
BinaryTree depth1_1 = new BinaryTree(SOURCE[1]);
BinaryTree depth1_2 = new BinaryTree(SOURCE[2]);
rootNode.setChild(depth1_1, BinaryTree.LEFT_NODE);
rootNode.setChild(depth1_2, BinaryTree.RIGHT_NODE);
depth1_1.setChild(new BinaryTree(SOURCE[3]), BinaryTree.LEFT_NODE);
depth1_1.setChild(new BinaryTree(SOURCE[4]), BinaryTree.RIGHT_NODE);
depth1_2.setChild(new BinaryTree(SOURCE[5]), BinaryTree.LEFT_NODE);
depth1_2.setChild(new BinaryTree(SOURCE[6]), BinaryTree.RIGHT_NODE);
// debug
System.out.println("Initialized: " + BinaryTree.toString(rootNode));
}
@Test
public TreeNode<Integer> add(TreeNode<Integer> treeNode, int value) {
if (treeNode.getNodeValue() == null) {
treeNode.setNodeValue(value);
return treeNode;
}
if (value < treeNode.getNodeValue()) {
return add(treeNode.getChild(BinaryTree.LEFT_NODE), value);
} else {
return add(treeNode.getChild(BinaryTree.RIGHT_NODE), value);
}
}
@Test
public void remove(BinaryTree treeNode, int value) throws IllegalAccessException {
BinaryTree parentTree = (BinaryTree) treeNode.getParent();
if (treeNode.isLeaf()) {
parentTree.removeChild(treeNode);
} else if (treeNode.getChild(BinaryTree.LEFT_NODE).getNodeValue() != null
|| treeNode.getChild(BinaryTree.RIGHT_NODE).getNodeValue() != null) {
BinaryTree childNode = treeNode.getChild(BinaryTree.LEFT_NODE).getNodeValue() != null
? (BinaryTree) treeNode.getChild(BinaryTree.LEFT_NODE)
: (BinaryTree) treeNode.getChild(BinaryTree.RIGHT_NODE);
int childIndex = parentTree.contain(childNode);
parentTree.setChild(childNode, childIndex);
} else {
BinaryTree leftChildNode = (BinaryTree) treeNode.getChild(BinaryTree.LEFT_NODE);
BinaryTree rightChildNode = (BinaryTree) treeNode.getChild(BinaryTree.RIGHT_NODE);
BinaryTree parentNode = (BinaryTree) treeNode.getParent();
int targetNodeIndex = parentNode.contain(treeNode);
// TODO: 직후 원소 찾기.
BinaryTree replaceNode = parentTree;
BinaryTree replaceChildNode = (BinaryTree) replaceNode.getChild(BinaryTree.RIGHT_NODE);
BinaryTree replaceParentNode = (BinaryTree) replaceNode.getParent();
// replace
parentNode.setChild(replaceNode, targetNodeIndex);
replaceNode.setChild(leftChildNode, BinaryTree.LEFT_NODE);
replaceNode.setChild(rightChildNode, BinaryTree.RIGHT_NODE);
replaceParentNode.setChild(replaceChildNode, BinaryTree.RIGHT_NODE);
}
}
@Test
public void search() {
int searchValue = 35;
System.out.print("Search ");
Assert.assertTrue(search(rootNode, searchValue));
}
private boolean search(TreeNode<Integer> treeNode, int value) {
System.out.printf("=> %d ", treeNode.getNodeValue());
if (treeNode.getNodeValue() == value) {
return true;
} else if (!treeNode.isLeaf()) {
TreeNode<Integer> leftChildNode = treeNode.getChild(BinaryTree.LEFT_NODE);
TreeNode<Integer> rightChildNode = treeNode.getChild(BinaryTree.RIGHT_NODE);
if (leftChildNode != null && treeNode.getNodeValue() > value) {
return search(leftChildNode, value);
} else if (rightChildNode != null && treeNode.getNodeValue() < value) {
return search(rightChildNode, value);
}
}
return false;
}
}
| true |
8999f3cb2161c88d8f61ffa7c6ca25d1cd9a8a69 | Java | Iglu-OU/skeleton | /tools/apigen/src/main/java/ee/iglu/skeleton/tools/apigen/ApiMethodTSTypeNamingStrategy.java | UTF-8 | 1,752 | 2.25 | 2 | [] | no_license | package ee.iglu.skeleton.tools.apigen;
import ee.iglu.skeleton.rpc.RpcMethod;
import java2typescript.jackson.module.conf.typename.WithEnclosingClassTSTypeNamingStrategy;
import org.apache.commons.lang3.StringUtils;
import java.util.Arrays;
class ApiMethodTSTypeNamingStrategy extends WithEnclosingClassTSTypeNamingStrategy {
@Override
public String getName(Class<?> rawClass) {
String classNameWithEnclosingClasses = super.getName(rawClass);
if (isEnclosingClassApiMethod(rawClass)) {
return getClassNamePrefixFromPackage(rawClass) + "_" + classNameWithEnclosingClasses;
}
return classNameWithEnclosingClasses;
}
private String getClassNamePrefixFromPackage(Class<?> rawClass) {
String classNamePrefixFromPackage = getPackageNameForPrefix(rawClass);
return StringUtils.capitalize(classNamePrefixFromPackage);
}
String getPackageNameForPrefix(Class<?> rawClass) {
Package aPackage = rawClass.getPackage();
return getPackageNameForPrefix(aPackage);
}
String getPackageNameForPrefix(Package aPackage) {
String packageName = aPackage.getName();
String packageNameWithoutApiSufix = packageName;
if (packageName.endsWith(".api")) {
packageNameWithoutApiSufix = getParentPackage(packageName);
}
return StringUtils.substringAfterLast(packageNameWithoutApiSufix, ".");
}
private String getParentPackage(String packageName) {
return StringUtils.substringBeforeLast(packageName, ".");
}
boolean isEnclosingClassApiMethod(Class<?> klass) {
Class<?> enclosingClass = klass.getEnclosingClass();
if (enclosingClass == null) {
return false;
}
return Arrays.stream(enclosingClass.getInterfaces())
.filter((Class<?> interf) -> interf.equals(RpcMethod.class))
.findFirst()
.isPresent();
}
}
| true |
5b4212d4e494b1730c95dd8b98e13a22d2f0cf1a | Java | ATai2/atshop | /at-web/at-goods/src/main/java/com/atshop/goods/service/SkuService.java | UTF-8 | 341 | 1.5625 | 2 | [] | no_license | package com.atshop.goods.service;
import com.at.common.bean.PmsSkuInfo;
import java.util.List;
public interface SkuService {
void saveSkuInfo(PmsSkuInfo pmsSkuInfo);
PmsSkuInfo getSkuById(String skuId);
List<PmsSkuInfo> getSkuSaleAttrValueListBySpu(String productId);
List<PmsSkuInfo> getAllSku(String catalog3Id);
}
| true |
6e07c219c922061796d4f00107f41f5ef6eecdd2 | Java | Zhou004692/FirstJob | /src/com/jdd/powermanager/basic/MyViewPagerAdapter.java | UTF-8 | 1,124 | 2.46875 | 2 | [] | no_license | package com.jdd.powermanager.basic;
import java.util.ArrayList;
import java.util.List;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.ViewGroup;
public class MyViewPagerAdapter extends PagerAdapter
{
private List<View> mViews;
private ViewPager mPager;
public MyViewPagerAdapter(ViewPager v)
{
mPager = v;
}
public void addView(View v)
{
if( null == mViews )
{
mViews = new ArrayList<View>();
}
mViews.add(v);
}
public void removeView(int i)
{
// TODO
}
@Override
public int getCount()
{
return null == mViews ? 0 : mViews.size();
}
@Override
public boolean isViewFromObject(View arg0, Object arg1)
{
return arg0 == arg1;
}
@Override
public Object instantiateItem(ViewGroup container, int position)
{
View v = null == mViews ? null : mViews.get(position);
if( null != v )
{
mPager.addView(v);
}
return v;
}
@Override
public void destroyItem(ViewGroup container, int position, Object object)
{
// super.destroyItem(container, position, object);
}
}
| true |
0dd4ad4ac529a8602ceba01f57e489a8a45cb745 | Java | gritsoftwares/YuzuBrowser | /app/src/main/java/jp/hazuki/yuzubrowser/search/SearchActivity.java | UTF-8 | 13,136 | 1.5625 | 2 | [
"Apache-2.0"
] | permissive | package jp.hazuki.yuzubrowser.search;
import android.app.SearchManager;
import android.content.ActivityNotFoundException;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.speech.RecognizerIntent;
import android.support.v4.app.LoaderManager.LoaderCallbacks;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v4.widget.CursorAdapter;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.ActionMode;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import jp.hazuki.yuzubrowser.R;
import jp.hazuki.yuzubrowser.settings.data.AppData;
import jp.hazuki.yuzubrowser.theme.ThemeData;
import jp.hazuki.yuzubrowser.utils.ClipboardUtils;
import jp.hazuki.yuzubrowser.utils.ErrorReport;
import jp.hazuki.yuzubrowser.utils.Logger;
import jp.hazuki.yuzubrowser.utils.UrlUtils;
import jp.hazuki.yuzubrowser.utils.WebUtils;
public class SearchActivity extends AppCompatActivity implements TextWatcher, LoaderCallbacks<Cursor>, SearchButton.Callback {
private static final String TAG = "SearchActivity";
public static final String EXTRA_URI = "jp.hazuki.yuzubrowser.search.SearchActivity.extra.uri";
public static final String EXTRA_QUERY = "jp.hazuki.yuzubrowser.search.SearchActivity.extra.query";
public static final String EXTRA_SELECT_INITIAL_QUERY = "jp.hazuki.yuzubrowser.search.SearchActivity.extra.selectinitquery";
public static final String EXTRA_APP_DATA = "jp.hazuki.yuzubrowser.search.SearchActivity.extra.appdata";
public static final String EXTRA_SEARCH_MODE = "jp.hazuki.yuzubrowser.search.SearchActivity.extra.searchmode";
public static final String EXTRA_OPEN_NEW_TAB = "jp.hazuki.yuzubrowser.search.SearchActivity.extra.openNewTab";
public static final int SEARCH_MODE_AUTO = 0;
public static final int SEARCH_MODE_URL = 1;
public static final int SEARCH_MODE_WORD = 2;
private static final int RESULT_REQUEST_SPEECH = 0;
private Uri mContentUri;
private Bundle mAppData;
private EditText editText;
private ListView listView;
private String initQuery;
private String initDecodedQuery = "";
private boolean openNewTab;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.search_activity);
editText = (EditText) findViewById(R.id.editText);
SearchButton searchButton = (SearchButton) findViewById(R.id.searchButton);
listView = (ListView) findViewById(R.id.listView);
if (ThemeData.isEnabled()) {
if (ThemeData.getInstance().toolbarBackgroundColor != 0)
findViewById(R.id.search_bar_container).setBackgroundColor(ThemeData.getInstance().toolbarBackgroundColor);
int textColor = ThemeData.getInstance().toolbarTextColor;
if (textColor != 0) {
editText.setTextColor(textColor);
editText.setHintTextColor(textColor & 0xffffff | 0x55000000);
}
if (ThemeData.getInstance().toolbarImageColor != 0)
searchButton.setColorFilter(ThemeData.getInstance().toolbarImageColor);
if (ThemeData.getInstance().statusBarColor != 0) {
Window window = getWindow();
window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
window.setStatusBarColor(ThemeData.getInstance().statusBarColor);
}
}
editText.addTextChangedListener(this);
editText.setOnEditorActionListener(new OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (event != null && event.getKeyCode() == KeyEvent.KEYCODE_ENTER) {
finishWithResult(editText.getText().toString(), SEARCH_MODE_AUTO);
return true;
}
return false;
}
});
editText.setCustomSelectionActionModeCallback(new ActionMode.Callback() {
@Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
return true;
}
@Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return true;
}
@Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
CharSequence text = editText.getText();
int min = 0;
int max = text.length();
if (editText.isFocused()) {
final int selStart = editText.getSelectionStart();
final int selEnd = editText.getSelectionEnd();
min = Math.max(0, Math.min(selStart, selEnd));
max = Math.max(0, Math.max(selStart, selEnd));
}
switch (item.getItemId()) {
case android.R.id.copy:
if (min == 0 && max == text.length() && initDecodedQuery.equals(text.toString())) {
ClipboardUtils.setClipboardText(SearchActivity.this, initQuery, false);
mode.finish();
return true;
}
break;
case android.R.id.cut:
if (min == 0 && max == text.length() && initDecodedQuery.equals(text.toString())) {
ClipboardUtils.setClipboardText(SearchActivity.this, initQuery, false);
editText.setText("");
mode.finish();
return true;
}
break;
}
return false;
}
@Override
public void onDestroyActionMode(ActionMode mode) {
}
});
searchButton.setActionCallback(this);
searchButton.setSense(AppData.swipebtn_sensitivity.get());
Intent intent = getIntent();
if (intent != null) {
Uri uri = intent.getParcelableExtra(EXTRA_URI);
if (uri != null) {
mContentUri = uri;
} else {
switch (AppData.search_suggest.get()) {
case 0:
default:
mContentUri = SuggestProvider.URI_NORMAL;
break;
case 1:
mContentUri = SuggestProvider.URI_NET;
break;
case 2:
mContentUri = SuggestProvider.URI_LOCAL;
break;
}
}
initQuery = intent.getStringExtra(EXTRA_QUERY);
if (initQuery != null) {
initDecodedQuery = UrlUtils.decodeUrl(initQuery);
editText.setText(initDecodedQuery);
}
if (intent.getBooleanExtra(EXTRA_SELECT_INITIAL_QUERY, true)) {
editText.selectAll();
}
mAppData = intent.getBundleExtra(EXTRA_APP_DATA);
openNewTab = intent.getBooleanExtra(EXTRA_OPEN_NEW_TAB, false);
} else {
throw new IllegalStateException("Intent is null");
}
}
@Override
public void afterTextChanged(final Editable s) {
final String query = s.toString();
Bundle bundle = new Bundle();
bundle.putString("QUERY", query);
getSupportLoaderManager().restartLoader(0, bundle, this);
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public Loader<Cursor> onCreateLoader(int arg0, Bundle bundle) {
String query;
try {
query = URLEncoder.encode(bundle.getString("QUERY"), "UTF-8");
} catch (UnsupportedEncodingException e) {
ErrorReport.printAndWriteLog(e);
query = bundle.getString("QUERY");
}
return new CursorLoader(getApplicationContext(), Uri.withAppendedPath(mContentUri, query), null, null, null, null);
}
@Override
public void onLoadFinished(Loader<Cursor> arg0, Cursor c) {
if (c == null) {
Logger.d(TAG, "Cursor is null");
listView.setAdapter(null);
return;
}
final int COL_QUERY = c.getColumnIndex(SearchManager.SUGGEST_COLUMN_QUERY);
CursorAdapter adapter = new CursorAdapter(getApplicationContext(), c, 0) {
@Override
public void bindView(View view, Context context, Cursor cursor) {
final String query = cursor.getString(COL_QUERY);
((TextView) view.findViewById(R.id.textView)).setText(query);
view.findViewById(R.id.textView).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finishWithResult(query, SEARCH_MODE_AUTO);
}
});
view.findViewById(R.id.imageButton).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
editText.setText(query);
editText.setSelection(query.length());
}
});
}
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
return LayoutInflater.from(context).inflate(R.layout.search_activity_list_item, null);
}
};
listView.setAdapter(adapter);
}
@Override
public void onLoaderReset(Loader<Cursor> arg0) {
listView.setAdapter(null);
}
private void finishWithResult(String query, int mode) {
if (!AppData.private_mode.get() && !TextUtils.isEmpty(query) && mode != SEARCH_MODE_URL && !WebUtils.isUrl(query)) {
ContentValues values = new ContentValues();
values.put(SearchManager.SUGGEST_COLUMN_QUERY, query);
getContentResolver().insert(mContentUri, values);
}
Intent data = new Intent();
data.putExtra(EXTRA_QUERY, query);
data.putExtra(EXTRA_SEARCH_MODE, mode);
data.putExtra(EXTRA_OPEN_NEW_TAB, openNewTab);
if (mAppData != null)
data.putExtra(EXTRA_APP_DATA, mAppData);
setResult(RESULT_OK, data);
finish();
}
@Override
public void forceOpenUrl() {
finishWithResult(editText.getText().toString(), SEARCH_MODE_URL);
}
@Override
public void forceSearchWord() {
finishWithResult(editText.getText().toString(), SEARCH_MODE_WORD);
}
@Override
public void autoSearch() {
finishWithResult(editText.getText().toString(), SEARCH_MODE_AUTO);
}
@Override
public void recognizeSpeech() {
try {
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
startActivityForResult(intent, RESULT_REQUEST_SPEECH);
} catch (ActivityNotFoundException e) {
e.printStackTrace();
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case RESULT_REQUEST_SPEECH:
if (resultCode != RESULT_OK || data == null) break;
ArrayList<String> results = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
if (!results.isEmpty()) {
String query = results.get(0);
editText.setText(query);
editText.setSelection(query.length());
}
break;
}
}
@Override
public boolean onTouchEvent(MotionEvent event) {
if (event.getActionMasked() == MotionEvent.ACTION_UP) {
finish();
}
return super.onTouchEvent(event);
}
}
| true |
d3be83b29eb672b6a324151e74b6c4e696b9b781 | Java | Fabricioultrasoft/salutem | /src/salutem/Telas/TelaAgendaConsulta.java | UTF-8 | 17,402 | 1.84375 | 2 | [] | no_license | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/*
* TelaAgendaConsulta.java
*
* Created on 17/05/2012, 15:24:42
*/
package salutem.Telas;
import java.awt.Component;
import java.sql.SQLException;
import java.util.Date;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.table.DefaultTableModel;
import javax.xml.crypto.Data;
import salutem.Beans.AgendaConsultaBean;
import salutem.Beans.PacienteBean;
import salutem.DAO.AgendaConsultaDAO;
import salutem.DAO.PacientePesquisaDAO;
import salutem.DAO.pacienteDAO;
import salutem.Utils.Msg;
import salutem.Utils.Params;
import salutem.Utils.Utils;
/**
*
* @author Tironi
*/
public class TelaAgendaConsulta extends javax.swing.JDialog {
private int idPac;
private pacienteDAO pacientedao;
private Integer idPaciente;
private String nomePaciente;
private TelaPacientePesquisa telaBusca;
private AgendaConsultaDAO agendaDao;
private boolean inserir;
/** Creates new form TelaAgendaConsulta */
public TelaAgendaConsulta(java.awt.Frame parent, boolean modal) {
super(parent, modal);
initComponents();
atualizarTabela();
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
lbNome = new javax.swing.JLabel();
btnPesquisar = new javax.swing.JButton();
jPanel3 = new javax.swing.JPanel();
lbNome2 = new javax.swing.JLabel();
lbNome3 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
dtAgenda = new org.jdesktop.swingx.JXDatePicker();
jPanel2 = new javax.swing.JPanel();
jScrollPane1 = new javax.swing.JScrollPane();
tabela = new javax.swing.JTable();
jButton1 = new javax.swing.JButton();
jButton2 = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Dados do Paciente"));
jLabel1.setText("Nome:");
btnPesquisar.setText("Localizar Paciente");
btnPesquisar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnPesquisarActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
jPanel3.setLayout(jPanel3Layout);
jPanel3Layout.setHorizontalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(lbNome2)
.addGroup(jPanel3Layout.createSequentialGroup()
.addContainerGap()
.addComponent(lbNome3)))
.addContainerGap(232, Short.MAX_VALUE))
);
jPanel3Layout.setVerticalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addComponent(lbNome2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 23, Short.MAX_VALUE)
.addComponent(lbNome3))
);
jLabel2.setText("Data");
dtAgenda.setFormats("dd/MM/yyyy");
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jLabel1)
.addGap(10, 10, 10)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(lbNome))
.addContainerGap(269, Short.MAX_VALUE))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel2)
.addComponent(dtAgenda, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 264, Short.MAX_VALUE)
.addComponent(btnPesquisar)
.addGap(67, 67, 67))))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jLabel1)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(lbNome)
.addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2)
.addComponent(btnPesquisar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGap(1, 1, 1)
.addComponent(dtAgenda, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
);
jPanel2.setBorder(javax.swing.BorderFactory.createEtchedBorder());
tabela.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
},
new String [] {
"Data", "Nome"
}
));
jScrollPane1.setViewportView(tabela);
javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 516, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(44, Short.MAX_VALUE))
);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 118, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(28, Short.MAX_VALUE))
);
jButton1.setText("Salvar");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jButton2.setText("Finalizar");
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(jPanel1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jPanel2, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addContainerGap(32, Short.MAX_VALUE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap(374, Short.MAX_VALUE)
.addComponent(jButton2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jButton1)
.addGap(112, 112, 112))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButton1)
.addComponent(jButton2))
.addContainerGap(31, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void btnPesquisarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnPesquisarActionPerformed
this.telaBusca = new TelaPacientePesquisa(this, true);
this.telaBusca.setVisible(true);
}//GEN-LAST:event_btnPesquisarActionPerformed
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
setInserir(true);
salvar();
}//GEN-LAST:event_jButton1ActionPerformed
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
try {
this.agendaDao.excluir();
atualizarTabela();
} catch (SQLException ex) {
Logger.getLogger(TelaAgendaConsulta.class.getName()).log(Level.SEVERE, null, ex);
}
}//GEN-LAST:event_jButton2ActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(TelaAgendaConsulta.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(TelaAgendaConsulta.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(TelaAgendaConsulta.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(TelaAgendaConsulta.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the dialog */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
TelaAgendaConsulta dialog = new TelaAgendaConsulta(new javax.swing.JFrame(), true);
dialog.addWindowListener(new java.awt.event.WindowAdapter() {
@Override
public void windowClosing(java.awt.event.WindowEvent e) {
System.exit(0);
}
});
dialog.setVisible(true);
}
});
}
protected void preencherCampos(int id) {
try {
this.idPac = id;
this.pacientedao = new pacienteDAO();
PacienteBean paciente = pacientedao.getPaciente(id);
this.nomePaciente = paciente.getNome().trim().toUpperCase();
this.idPaciente = paciente.getIdPaciente();
this.lbNome3.setText(this.nomePaciente);
atualizarTabela();
} catch (SQLException ex) {
Msg.erro(this, "Erro ao preencher campos. \n" + ex.getMessage());
}
}
protected void atualizarTabela() {
try {
DefaultTableModel modelo = (DefaultTableModel) this.tabela.getModel();
modelo.setNumRows(0);
this.agendaDao = new AgendaConsultaDAO();
String data = this.dtAgenda.getEditor().getText();
List<AgendaConsultaBean> lista = this.agendaDao.getLista();
for (int i = 0; i < lista.size(); i++) {
modelo.addRow(new Object[]{
lista.get(i).getDate(),
lista.get(i).getNomePaciente(),
});
}
} catch (SQLException ex) {
Msg.erro(this, "Erro ao atualizar tabela. \n" + ex.getMessage());
}
}
protected void setInserir(boolean inserir) {
this.inserir = inserir;
this.idPaciente = null;
}
protected boolean isInserir() {
return inserir;
}
private void destacarCampo(Component c, boolean b) {
if (b) {
c.setBackground(Params.COR_CAMPO_VAZIO);
} else {
c.setBackground(Params.COR_CAMPO_NORMAL);
}
}
private boolean verificarCampos() {
boolean aux = false;
String msg = "Preencha corretamente os campos. \n";
if (aux) {
Msg.alerta(this, msg);
}
return aux;
}
private void cancelar() {
this.setVisible(false);
this.dispose();
}
private void salvar() {
if (this.verificarCampos()) {
return;
}
try {
if (this.isInserir()) {
AgendaConsultaBean agenda = new AgendaConsultaBean();
agenda.setNomePaciente(this.nomePaciente);
agenda.setDate(dtAgenda.getDate());
this.agendaDao = new AgendaConsultaDAO();
this.agendaDao.inserir(agenda);
Msg.informacao(this, "Salvo com sucesso.");
atualizarTabela();
}
} catch (SQLException ex) {
ex.printStackTrace();
Msg.erro(this, "Erro ao salvar. \n" + ex.getMessage());
}
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton btnPesquisar;
private org.jdesktop.swingx.JXDatePicker dtAgenda;
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
private javax.swing.JPanel jPanel3;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JLabel lbNome;
private javax.swing.JLabel lbNome2;
private javax.swing.JLabel lbNome3;
private javax.swing.JTable tabela;
// End of variables declaration//GEN-END:variables
}
| true |
0ca1a3b4f84fce66192f1a0021a8c0461fa0bda1 | Java | tony056/Api10to19 | /src/com/example/scaletest/MyScaleGestureDetector.java | UTF-8 | 15,395 | 2.09375 | 2 | [] | no_license | package com.example.scaletest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Handler;
import android.util.FloatMath;
import android.util.Log;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.ScaleGestureDetector;
import android.view.ViewConfiguration;
import android.view.ScaleGestureDetector.OnScaleGestureListener;
public class MyScaleGestureDetector extends ScaleGestureDetector{
private final Context mContext;
private final OnScaleGestureListener mListener;
private float mFocusX;
private float mFocusY;
private boolean mQuickScaleEnabled;
private float mCurrSpan;
private float mPrevSpan;
private float mInitialSpan;
private float mCurrSpanX;
private float mCurrSpanY;
private float mPrevSpanX;
private float mPrevSpanY;
private long mCurrTime;
private long mPrevTime;
private boolean mInProgress;
private int mSpanSlop;
private int mMinSpan;
// Bounds for recently seen values
private float mTouchUpper;
private float mTouchLower;
private float mTouchHistoryLastAccepted;
private int mTouchHistoryDirection;
private long mTouchHistoryLastAcceptedTime;
private int mTouchMinMajor;
private MotionEvent mDoubleTapEvent;
private int mDoubleTapMode = DOUBLE_TAP_MODE_NONE;
private final Handler mHandler;
private static final long TOUCH_STABILIZE_TIME = 128; // ms
private static final int DOUBLE_TAP_MODE_NONE = 0;
private static final int DOUBLE_TAP_MODE_IN_PROGRESS = 1;
private static final float SCALE_FACTOR = .5f;
private boolean mModeSwitch = false;
private int mFlag = 0;
private float downX;
private float downY;
/**
* Consistency verifier for debugging purposes.
*/
/*private final InputEventConsistencyVerifier mInputEventConsistencyVerifier =
InputEventConsistencyVerifier.isInstrumentationEnabled() ?
new InputEventConsistencyVerifier(this, 0) : null;*/
private GestureDetector mGestureDetector;
private boolean mEventBeforeOrAboveStartingGestureEvent;
public MyScaleGestureDetector(Context context, OnScaleGestureListener listener, Handler handler) {
super(context, listener);
mContext = context;
mListener = listener;
mHandler = handler;
mSpanSlop = ViewConfiguration.get(context).getScaledTouchSlop() * 2;
setQuickScaleEnabled(true);
//Log.e("create", "My Scale");
}
@Override
public boolean onTouchEvent(MotionEvent event){
//Log.e("PROGRESS", "1"+isInProgress());
final int action = event.getActionMasked();
if(mQuickScaleEnabled){
//Log.e("ENABLE", "quick scale enabled");
mGestureDetector.onTouchEvent(event);
}
final boolean streamComplete = action == MotionEvent.ACTION_UP ||
action == MotionEvent.ACTION_CANCEL;
if (action == MotionEvent.ACTION_DOWN || streamComplete) {
// Reset any scale in progress with the listener.
// If it's an ACTION_DOWN we're beginning a new event stream.
// This means the app probably didn't give us all the events. Shame on it.
if(mFlag == 1 && mModeSwitch == true){
Log.e("DDDDD", ""+downX+",,"+downY);
downX = event.getX();
downY = event.getY();
}
if (mInProgress) {
mListener.onScaleEnd(this);
mInProgress = false;
mInitialSpan = 0;
mDoubleTapMode = DOUBLE_TAP_MODE_NONE;
}
if(mModeSwitch == true){
mDoubleTapMode = DOUBLE_TAP_MODE_IN_PROGRESS;
mInProgress = true;
mFlag = 1;
Log.e("MODE SWITCH", "switch"+mModeSwitch);
}
if (streamComplete) {
//clearTouchHistory();
return true;
}
}
final boolean configChanged = action == MotionEvent.ACTION_DOWN ||
action == MotionEvent.ACTION_POINTER_UP ||
action == MotionEvent.ACTION_POINTER_DOWN;
final boolean pointerUp = action == MotionEvent.ACTION_POINTER_UP;
final int skipIndex = pointerUp ? event.getActionIndex() : -1;
// Determine focal point
float sumX = 0, sumY = 0;
final int count = event.getPointerCount();
final int div = pointerUp ? count - 1 : count;
final float focusX;
final float focusY;
if (mDoubleTapMode == DOUBLE_TAP_MODE_IN_PROGRESS) {
// In double tap mode, the focal pt is always where the double tap
// gesture started
//Log.e("MODE", "Double TapQQQQQQQ");
if(mDoubleTapEvent != null){
if((mFlag == 1 && mModeSwitch == true) || (mFlag == 0 && mModeSwitch == false)){
Log.e("MODE", "Double Tap");
focusX = mDoubleTapEvent.getX();
focusY = mDoubleTapEvent.getY();
if (event.getY() < focusY) {
mEventBeforeOrAboveStartingGestureEvent = true;
} else {
mEventBeforeOrAboveStartingGestureEvent = false;
}
}
else{
Log.e("NULL", "null, "+mFlag);
focusX = downX;
focusY = downY;
if (event.getY() < focusY) {
mEventBeforeOrAboveStartingGestureEvent = true;
} else {
mEventBeforeOrAboveStartingGestureEvent = false;
}
//mFlag = 1;
}
}else{
Log.e("NULL", "null, "+mFlag);
focusX = downX;
focusY = downY;
if (event.getY() < focusY) {
mEventBeforeOrAboveStartingGestureEvent = true;
} else {
mEventBeforeOrAboveStartingGestureEvent = false;
}
//mFlag = 1;
}
} else {
for (int i = 0; i < count; i++) {
if (skipIndex == i) continue;
sumX += event.getX(i);
sumY += event.getY(i);
}
focusX = sumX / div;
focusY = sumY / div;
}
// Determine average deviation from focal point
float devSumX = 0, devSumY = 0;
for (int i = 0; i < count; i++) {
if (skipIndex == i) continue;
// Convert the resulting diameter into a radius.
final float touchSize = mTouchHistoryLastAccepted / 2;
devSumX += Math.abs(event.getX(i) - focusX) + touchSize;
devSumY += Math.abs(event.getY(i) - focusY) + touchSize;
}
final float devX = devSumX / div;
final float devY = devSumY / div;
// Span is the average distance between touch points through the focal point;
// i.e. the diameter of the circle with a radius of the average deviation from
// the focal point.
final float spanX = devX * 2;
final float spanY = devY * 2;
final float span;
if (inDoubleTapMode()) {
span = spanY;
} else {
span = FloatMath.sqrt(spanX * spanX + spanY * spanY);
}
// Dispatch begin/end events as needed.
// If the configuration changes, notify the app to reset its current state by beginning
// a fresh scale event stream.
final boolean wasInProgress = mInProgress;
mFocusX = focusX;
mFocusY = focusY;
if (!inDoubleTapMode() && mInProgress && (span < mMinSpan || configChanged)) {
mListener.onScaleEnd(this);
mInProgress = false;
mInitialSpan = span;
mDoubleTapMode = DOUBLE_TAP_MODE_NONE;
}
if (configChanged) {
mPrevSpanX = mCurrSpanX = spanX;
mPrevSpanY = mCurrSpanY = spanY;
mInitialSpan = mPrevSpan = mCurrSpan = span;
}
if(mModeSwitch == true && mFlag % 2 == 1){
mInProgress = false;
mFlag = 1;
}
final int minSpan = inDoubleTapMode() ? mSpanSlop : mMinSpan;
if (!mInProgress && span >= minSpan &&
(wasInProgress || Math.abs(span - mInitialSpan) > mSpanSlop)) {
mPrevSpanX = mCurrSpanX = spanX;
mPrevSpanY = mCurrSpanY = spanY;
mPrevSpan = mCurrSpan = span;
mPrevTime = mCurrTime;
mInProgress = mListener.onScaleBegin(this);
}
//if(mModeSwitch == true)mInProgress = true;
// Handle motion; focal point and span/scale factor are changing.
if (action == MotionEvent.ACTION_MOVE) {
mCurrSpanX = spanX;
mCurrSpanY = spanY;
mCurrSpan = span;
boolean updatePrev = true;
if (mInProgress) {
updatePrev = mListener.onScale(this);
//Log.e("UPDATE", ""+updatePrev);
}
if (updatePrev) {
//Log.e("UPDATE", "dddddddddd");
mPrevSpanX = mCurrSpanX;
mPrevSpanY = mCurrSpanY;
mPrevSpan = mCurrSpan;
mPrevTime = mCurrTime;
}
if(mFlag == 1) mFlag = 0;
}
Log.e("BUG", ""+mInProgress+", "+mInitialSpan+", "+mDoubleTapMode+",, "+mCurrSpan+"!! "+mPrevSpan);
//textView.setText(String.valueOf(this.getScaleFactor()));
return true;
}
private boolean inDoubleTapMode() {
return mDoubleTapMode == DOUBLE_TAP_MODE_IN_PROGRESS;
}
@SuppressLint("Override") public void setQuickScaleEnabled(boolean scales) {
mQuickScaleEnabled = scales;
if (mQuickScaleEnabled && mGestureDetector == null) {
GestureDetector.SimpleOnGestureListener gestureListener =
new GestureDetector.SimpleOnGestureListener() {
@Override
public boolean onDoubleTap(MotionEvent e) {
// Double tap: start watching for a swipe
mDoubleTapEvent = e;
mDoubleTapMode = DOUBLE_TAP_MODE_IN_PROGRESS;
return true;
}
@Override
public boolean onDown(MotionEvent e){
if(mFlag == 0 && mModeSwitch == true){
Log.e("TOUCHHHHHHH", ""+mFlag);
mDoubleTapEvent = e;
mDoubleTapMode = DOUBLE_TAP_MODE_IN_PROGRESS;
mFlag = 1;
}
return true;
}
};
mGestureDetector = new GestureDetector(mContext, gestureListener, mHandler);
//Log.e("Create", "gestureListener");
}
}
@SuppressLint("Override") public boolean isQuickScaleEnabled() {
return mQuickScaleEnabled;
}
/**
* Returns {@code true} if a scale gesture is in progress.
*/
public boolean isInProgress() {
return mInProgress;
}
/**
* Get the X coordinate of the current gesture's focal point.
* If a gesture is in progress, the focal point is between
* each of the pointers forming the gesture.
*
* If {@link #isInProgress()} would return false, the result of this
* function is undefined.
*
* @return X coordinate of the focal point in pixels.
*/
public float getFocusX() {
return mFocusX;
}
/**
* Get the Y coordinate of the current gesture's focal point.
* If a gesture is in progress, the focal point is between
* each of the pointers forming the gesture.
*
* If {@link #isInProgress()} would return false, the result of this
* function is undefined.
*
* @return Y coordinate of the focal point in pixels.
*/
public float getFocusY() {
return mFocusY;
}
/**
* Return the average distance between each of the pointers forming the
* gesture in progress through the focal point.
*
* @return Distance between pointers in pixels.
*/
public float getCurrentSpan() {
return mCurrSpan;
}
/**
* Return the average X distance between each of the pointers forming the
* gesture in progress through the focal point.
*
* @return Distance between pointers in pixels.
*/
@SuppressLint("Override") public float getCurrentSpanX() {
return mCurrSpanX;
}
/**
* Return the average Y distance between each of the pointers forming the
* gesture in progress through the focal point.
*
* @return Distance between pointers in pixels.
*/
@SuppressLint("Override") public float getCurrentSpanY() {
return mCurrSpanY;
}
/**
* Return the previous average distance between each of the pointers forming the
* gesture in progress through the focal point.
*
* @return Previous distance between pointers in pixels.
*/
public float getPreviousSpan() {
return mPrevSpan;
}
/**
* Return the previous average X distance between each of the pointers forming the
* gesture in progress through the focal point.
*
* @return Previous distance between pointers in pixels.
*/
@SuppressLint("Override") public float getPreviousSpanX() {
return mPrevSpanX;
}
/**
* Return the previous average Y distance between each of the pointers forming the
* gesture in progress through the focal point.
*
* @return Previous distance between pointers in pixels.
*/
@SuppressLint("Override") public float getPreviousSpanY() {
return mPrevSpanY;
}
/**
* Return the scaling factor from the previous scale event to the current
* event. This value is defined as
* ({@link #getCurrentSpan()} / {@link #getPreviousSpan()}).
*
* @return The current scaling factor.
*/
public float getScaleFactor() {
if (inDoubleTapMode()) {
// Drag is moving up; the further away from the gesture
// start, the smaller the span should be, the closer,
// the larger the span, and therefore the larger the scale
final boolean scaleUp =
(mEventBeforeOrAboveStartingGestureEvent && (mCurrSpan < mPrevSpan)) ||
(!mEventBeforeOrAboveStartingGestureEvent && (mCurrSpan > mPrevSpan));
final float spanDiff = (Math.abs(1 - (mCurrSpan / mPrevSpan)) * SCALE_FACTOR);
return mPrevSpan <= 0 ? 1 : scaleUp ? (1 + spanDiff) : (1 - spanDiff);
}
return mPrevSpan > 0 ? mCurrSpan / mPrevSpan : 1;
}
/**
* Return the time difference in milliseconds between the previous
* accepted scaling event and the current scaling event.
*
* @return Time difference since the last scaling event in milliseconds.
*/
public long getTimeDelta() {
return mCurrTime - mPrevTime;
}
/**
* Return the event time of the current event being processed.
*
* @return Current event time in milliseconds.
*/
public long getEventTime() {
return mCurrTime;
}
public void setDoubleTapMode(boolean set){
mModeSwitch = set;
}
public boolean getDoubleTapMode(){
return mModeSwitch;
}
}
| true |
259c1eceda587a540bbffdcd55e39a07e3df8772 | Java | HighlandProger/Zoo | /src/actions/Voice.java | UTF-8 | 86 | 2.28125 | 2 | [] | no_license | package actions;
public interface Voice {
int effort = 15;
String voice();
}
| true |
221870ad887133afbf2330c09e65837ab406bc3d | Java | cckmit/cfx | /cfx-api-shop/src/main/java/cn/cf/service/B2bWareService.java | UTF-8 | 841 | 1.835938 | 2 | [] | no_license | package cn.cf.service;
import java.util.Map;
import cn.cf.PageModel;
import cn.cf.dto.B2bWareDto;
import cn.cf.dto.B2bWareDtoEx;
import cn.cf.dto.B2bWarehouseNumberDto;
import cn.cf.model.B2bWare;
import cn.cf.model.B2bWarehouseNumber;
public interface B2bWareService {
Integer update(B2bWare model);
/**
* 仓库是否重复
* @param map
* @return
*/
B2bWareDto isWareRepeated(Map<String, Object> map);
int insert(B2bWare model);
PageModel<B2bWareDtoEx> searchWareList(Map<String, Object> map);
B2bWareDto getByPk(String pk);
int addWareNumber(B2bWarehouseNumber model);
int updateWareNumber(B2bWarehouseNumber model);
PageModel<B2bWarehouseNumberDto> searchWareNumberList(Map<String, Object> map);
B2bWarehouseNumberDto searchWareNumberByPk(String pk);
int selectEntity(B2bWarehouseNumberDto dto);
}
| true |
bf08ecff355fd55c80fd7a17291e8bb2b76458eb | Java | nitinmundhe/Java8 | /src/main/java/com/java8/day1/defualtstaticinterface/MyDocument.java | UTF-8 | 767 | 3.28125 | 3 | [] | no_license | package com.java8.day1.defualtstaticinterface;
public class MyDocument implements Openable, Closable {
public static void main(String[] args) {
// TODO Auto-generated method stub
MyDocument obj = new MyDocument();
obj.open("Hi");
obj.close("Bye");
obj.log("My Logs");
obj.log2("My Logs");
}
@Override
public void close(String str) {
System.out.println(str);
}
@Override
public void open(String str) {
System.out.println(str);
}
@Override
public void open2(String str) {
System.out.println(str);
}
@Override
public void log(String str) {
System.out.println("MyDocument logging..." + str);
Openable.print("abc");
}
}
| true |
7a04ac5eda1dd2abe921727d71aba4f2418afc6e | Java | apache/phoenix | /phoenix-core/src/main/java/org/apache/phoenix/schema/stats/StatisticsCollectorFactory.java | UTF-8 | 3,816 | 1.867188 | 2 | [
"MIT",
"OFL-1.1",
"BSD-3-Clause",
"ISC",
"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.phoenix.schema.stats;
import static org.apache.phoenix.query.QueryServices.STATS_COLLECTION_ENABLED;
import static org.apache.phoenix.query.QueryServicesOptions.DEFAULT_STATS_COLLECTION_ENABLED;
import java.io.IOException;
import org.apache.hadoop.hbase.client.Table;
import org.apache.hadoop.hbase.coprocessor.RegionCoprocessorEnvironment;
import org.apache.phoenix.jdbc.PhoenixDatabaseMetaData;
import org.apache.phoenix.util.SchemaUtil;
import org.apache.phoenix.util.ServerUtil.ConnectionFactory;
import org.apache.phoenix.util.ServerUtil.ConnectionType;
/**
* Provides new {@link StatisticsCollector} instances based on configuration settings for a
* table (or system-wide configuration of statistics).
*/
public class StatisticsCollectorFactory {
public static StatisticsCollector createStatisticsCollector(RegionCoprocessorEnvironment env,
String tableName, long clientTimeStamp, byte[] guidepostWidthBytes,
byte[] guidepostsPerRegionBytes) throws IOException {
return createStatisticsCollector(env, tableName, clientTimeStamp, null, guidepostWidthBytes, guidepostsPerRegionBytes);
}
public static StatisticsCollector createStatisticsCollector(
RegionCoprocessorEnvironment env, String tableName, long clientTimeStamp,
byte[] storeName) throws IOException {
return createStatisticsCollector(env, tableName, clientTimeStamp, storeName, null, null);
}
public static StatisticsCollector createStatisticsCollector(
RegionCoprocessorEnvironment env, String tableName, long clientTimeStamp,
byte[] storeName, byte[] guidepostWidthBytes,
byte[] guidepostsPerRegionBytes) throws IOException {
if (statisticsEnabled(env)) {
StatisticsWriter statsWriter = StatisticsWriter.newWriter(env, tableName, clientTimeStamp);
Table table = ConnectionFactory.getConnection(ConnectionType.DEFAULT_SERVER_CONNECTION, env).getTable(
SchemaUtil.getPhysicalTableName(PhoenixDatabaseMetaData.SYSTEM_CATALOG_NAME_BYTES, env.getConfiguration()));
return new DefaultStatisticsCollector(env.getConfiguration(), env.getRegion(), tableName,
storeName,guidepostWidthBytes, guidepostsPerRegionBytes, statsWriter, table);
} else {
return new NoOpStatisticsCollector();
}
}
/**
* Determines if statistics are enabled (which is the default). This is done on the
* RegionCoprocessorEnvironment for now to allow setting this on a per-table basis, although
* it could be moved to the general table metadata in the future if there is a realistic
* use case for that.
*/
private static boolean statisticsEnabled(RegionCoprocessorEnvironment env) {
return (env.getConfiguration().getBoolean(STATS_COLLECTION_ENABLED, DEFAULT_STATS_COLLECTION_ENABLED))
&& StatisticsUtil.isStatsEnabled(env.getRegionInfo().getTable());
}
}
| true |
59b6251524b50105f6f6aeb93885905efa1fbfad | Java | EduCCor/ms-transferencias-yanki | /src/main/java/com/bootcamp/transaction/msyanki/MsMsyankiTransactionBankApplication.java | UTF-8 | 449 | 1.59375 | 2 | [] | no_license | package com.bootcamp.transaction.msyanki;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
@EnableEurekaClient
@SpringBootApplication
public class MsMsyankiTransactionBankApplication {
public static void main(String[] args) {
SpringApplication.run(MsMsyankiTransactionBankApplication.class, args);
}
}
| true |
6caf32e909504c2f929c20eaf1ecf9575856979b | Java | mozammel2246/midtermbatch1901 | /src/main/java/inheritance/PreNokia1100.java | UTF-8 | 800 | 3.1875 | 3 | [] | no_license | package inheritance;
public abstract class PreNokia1100 implements SymbianPhone {
/**
*
* Implement interface SymbianPhone
* Make necessary changes to make this class abstract
*
* Think Nokia company is planning to add a colorful display in future
* but they cant implement that feature now. This implementation can be done by display()
* Declare and assign value to a String instance variable called nameOfTheClass
*
*
* */
String nameOfTheClass = "PreNokia1100";
public void sendText(){
System.out.println("This will send my text");
}
public abstract void makeCall();
public void contactList(){
System.out.println("This will show contact list");
}
public abstract void addColorFullDisplay();
}
| true |
659dd1c115467126f99ac47cfaa0f3e32c1213f7 | Java | shiweijie122/demo | /小例程/03-SE/day02-all/day02-all/day02/DoubleDemo01.java | UTF-8 | 271 | 3.234375 | 3 | [] | no_license | package day02;
/**
* 包装类中声明了每种类型的最大值和最小值
*/
public class DoubleDemo01 {
public static void main(String[] args) {
double max = Double.MAX_VALUE;
System.out.println(max);
max = max + 200000;
System.out.println(max);
}
}
| true |
fad2944151c3af59be7b166e58623ebaa4f93395 | Java | xtayicy/spring-boot | /spring-boot-data-jpa/src/main/java/harry/spring/boot/data/jpa/repository/ReviewRepository.java | UTF-8 | 563 | 2.1875 | 2 | [] | no_license | package harry.spring.boot.data.jpa.repository;
import harry.spring.boot.data.jpa.entity.Hotel;
import harry.spring.boot.data.jpa.entity.Review;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.repository.Repository;
/**
*
* @author harry
*
*/
public interface ReviewRepository extends Repository<Review, Long> {
Page<Review> findByHotel(Hotel hotel, Pageable pageable);
Review findByHotelAndIndex(Hotel hotel, int index);
Review save(Review review);
}
| true |
fc09d35bdeef1e58f4cb72b7e9c3db8f65ffeaad | Java | cmFodWx5YWRhdjEyMTA5/Kfarmers_vit | /app/src/main/java/com/leadplatform/kfarmers/model/parcel/RowsData.java | UTF-8 | 123 | 1.570313 | 2 | [] | no_license | package com.leadplatform.kfarmers.model.parcel;
public class RowsData
{
public String Type;
public String Value;
} | true |
d4321a6ba9d48192b0fdd460f1173703b9fe90b2 | Java | QuangNV98/Car-Garage | /Backend/src/main/java/com/quangnv/service/GuaranteeService.java | UTF-8 | 1,479 | 1.679688 | 2 | [] | no_license | package com.quangnv.service;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.quangnv.dao.GuaranteeDao;
@Service
public class GuaranteeService {
@Autowired
GuaranteeDao dao;
public List getAllTransCompleted() throws Exception {
return dao.getAllTransCompleted();
}
@Transactional(rollbackFor = Exception.class)
public int insertGuarantee(Map<Object, Object> map) throws Exception {
int returnId = 0;
returnId = dao.insertGuarantee(map);
return returnId;
}
public List getAllGuarantee() throws Exception {
return dao.getAllGuarantee();
}
public Map getGuarantedById(Map map) throws Exception {
return dao.getGuarantedById(map);
}
public List getGuarantedByCusId(Map map) throws Exception {
return dao.getGuarantedByCusId(map);
}
@Transactional(rollbackFor = Exception.class)
public int updateGuaranted(Map<Object, Object> map) throws Exception {
int returnId = 0;
returnId = dao.updateGuaranted(map);
return returnId;
}
@Transactional(rollbackFor = Exception.class)
public int deleteGuarantedById(Map<Object, Object> map) throws Exception {
int returnId = 0;
returnId = dao.deleteGuarantedById(map);
return returnId;
}
public List getListIsGuaranted(Map map) throws Exception {
return dao.getListIsGuaranted(map);
}
}
| true |
a639d4db0788ca93c862630340131905a579006f | Java | Leputa/Leetcode | /java/_594_Longest_Harmonious_Subsequence.java | UTF-8 | 815 | 3.078125 | 3 | [] | no_license | import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;
public class _594_Longest_Harmonious_Subsequence {
public int findLHS(int[] nums) {
int max=0;
if(nums.length==0)
return max;
HashMap<Integer, Integer>map=new HashMap<>();
for(int i=0;i<nums.length;i++) {
map.put(nums[i], map.getOrDefault(nums[i], 0)+1);
}
int cnt=0;
Set<Integer>keys=map.keySet();
Iterator<Integer>it=keys.iterator();
while(it.hasNext()) {
int tmp=it.next();
if(map.getOrDefault(tmp+1, 0)!=0){
cnt=map.get(tmp)+map.getOrDefault(tmp+1, 0);
if(cnt>max)
max=cnt;
}
if(map.getOrDefault(tmp-1, 0)!=0) {
cnt=map.get(tmp)+map.getOrDefault(tmp-1, 0);
if(cnt>max)
max=cnt;
}
cnt=0;
}
return max;
}
}
| true |
a027e743c0e82292874178160d652bb7331baf2e | Java | erik1o6/Java | /Project6/src/Cube.java | UTF-8 | 1,318 | 3.5625 | 4 | [] | no_license | /**
* Name: Erik Arfvidson Section: 001 Program: Cube.java definition
* Date:9/24/2012 Lab6
*/
public class Cube extends ThreeDimensionalShape {
private double leng;// the length of one side of the cube
// @Override
// initializer constructor for cube
/**
*
* @param x
* coordinate
* @param y
* coordinate
* @param z
* coordinate
* @param leng
* = the length of the sides of the cube The cube constructor
* initializer take 4 arguments defining it's position(center of
* mass) and also the length of one of the sides of the cube
*/
public Cube(double x, double y, double z, double leng)
// PRE: takes x>0.0, y>0.0, z>0.0, leng >0.0
// POST:
// shape cube
{
super(x, y, z);
this.setLeng(leng);
super.SetName("Cube");
}
// get length method
public double getLeng()
// POST: returns the length of the cube
{
return leng;
}
// setLength method
public void setLeng(double leng)
// PRE: length>0.0
// POST:Sets the length of the cube.
{
this.leng = leng;
}
// returns all information of cube
@Override
public String toString()
// POST: FCTVAL == String representation of CUBE object
{
return super.toString() + " length=" + leng;
}
}
| true |
233f58a5f127f9addfa6d24772da3d068f9e5ed5 | Java | kyunghoj/pigout | /src/main/java/edu/buffalo/cse/pigout/partitioner/DataTransferCostEstimator.java | UTF-8 | 9,120 | 1.96875 | 2 | [
"Apache-2.0"
] | permissive | package edu.buffalo.cse.pigout.partitioner;
import edu.buffalo.cse.pigout.tools.PigOutUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.pig.impl.PigContext;
import org.apache.pig.impl.io.FileSpec;
import org.apache.pig.impl.logicalLayer.FrontendException;
import org.apache.pig.newplan.DependencyOrderWalker;
import org.apache.pig.newplan.Operator;
import org.apache.pig.newplan.OperatorPlan;
import org.apache.pig.newplan.PlanWalker;
import org.apache.pig.newplan.logical.expression.LogicalExpression;
import org.apache.pig.newplan.logical.expression.LogicalExpressionPlan;
import org.apache.pig.newplan.logical.expression.UserFuncExpression;
import org.apache.pig.newplan.logical.relational.*;
import org.apache.pig.newplan.logical.relational.LogicalSchema.LogicalFieldSchema;
import java.util.List;
public class DataTransferCostEstimator extends LogicalPlanCostEstimator {
protected final Log LOG = LogFactory.getLog(getClass());
private PigContext context;
private static final float OP_SCALER_FILTER = (float)0.5;
private static final float OP_SCALER_DISTINCT = (float)0.25;
private static final float OP_SCALER_LOAD = (float)0.000001;
private static final float OP_SCALER_USERFUNC = (float) 0.10;
private static final float NUMBER_OF_GROUPS = (float) 4.00;
// For inner plan
private float initCost = (float) 0.0;
private boolean isInner = false;
private OperatorPlan outerPlan = null;
private LOForEach outerForEach = null;
// when you get into inner plan
protected DataTransferCostEstimator(OperatorPlan plan, PlanWalker walker, LOForEach op, float initCost)
throws FrontendException {
this(plan, walker);
this.initCost = initCost;
this.isInner = true;
this.outerForEach = op;
this.outerPlan = op.getPlan();
}
public DataTransferCostEstimator(PigContext context, OperatorPlan plan)
throws FrontendException
{
this(plan, new DependencyOrderWalker(plan));
this.context = context;
}
private DataTransferCostEstimator(OperatorPlan plan, PlanWalker walker)
throws FrontendException {
super(plan, walker);
}
private void updateAlias(LogicalRelationalOperator logRelOp) {
String newAlias;
List<Operator> preds = logRelOp.getPlan().getPredecessors(logRelOp);
if (preds == null) {
/* If the predecessor is null, set a unique alias */
newAlias = logRelOp.hashCode() + "null_pigout";
} else {
newAlias = ((LogicalRelationalOperator)preds.get(0)).getAlias() + "_pigout";
}
logRelOp.setAlias(newAlias);
}
private boolean updateCostTable(Operator op, Float cost) {
this.costTable.put(op, cost);
LogicalRelationalOperator logRelOp = (LogicalRelationalOperator)op;
if (logRelOp.getAlias() == null) {
updateAlias(logRelOp);
}
LOG.debug(logRelOp.getAlias() + " = " + logRelOp.getName() + " => " + cost);
return false;
}
public void visit(LOStore store) throws FrontendException {
Float costEstimate = getPredCost(store);
this.updateCostTable(store, costEstimate);
}
public void visit(LOLoad load) throws FrontendException {
FileSpec fs = load.getFileSpec();
String namenode = getNameNode(fs);
long size;
size = PigOutUtils.getHDFSFileSize(fs.getFileName(), namenode);
float costEstimate = OP_SCALER_LOAD * size;
this.updateCostTable(load, costEstimate);
}
public void visit(LOFilter op) throws FrontendException {
float costEstimate = OP_SCALER_FILTER * getPredCost(op);
this.updateCostTable(op, costEstimate);
}
public void visit(LOJoin op) throws FrontendException {
float costEstimate = getPredCost(op);
this.updateCostTable(op, costEstimate);
}
public void visit(LOForEach op) throws FrontendException {
float costEstimate;
LogicalPlan innerPlan = op.getInnerPlan();
DataTransferCostEstimator estimator;
estimator = new DataTransferCostEstimator(innerPlan, new DependencyOrderWalker(innerPlan), op, getPredCost(op));
estimator.visit();
costEstimate = estimator.getCostTable().get(innerPlan.getSinks().get(0));
this.updateCostTable(op, costEstimate);
}
public void visit(LOGenerate op) throws FrontendException {
float total_pred_cost = 0;
int total_pred_fields;
boolean isUserFunc = false;
LogicalPlan lp = (LogicalPlan) op.getPlan();
List<Operator> preds = lp.getPredecessors(op);
List<LogicalExpressionPlan> outExprPlans = op.getOutputPlans();
for (LogicalExpressionPlan exprPlan : outExprPlans) {
List<Operator> exprPlanSources = exprPlan.getSources();
for (Operator exprSrc : exprPlanSources) {
if (exprSrc instanceof UserFuncExpression) {
isUserFunc = true;
}
}
}
if (!preds.isEmpty()) {
for (Operator pred : preds) {
if (pred instanceof LogicalRelationalOperator) {
LogicalRelationalOperator predLO = (LogicalRelationalOperator) pred;
total_pred_cost += costTable.get(predLO);
}
}
} else {
LOG.error("Invalid logical plan: no predecessors for LOGenerate.");
throw new FrontendException();
}
List<LogicalFieldSchema> result_fields = op.getSchema().getFields();
float generate_weight = 1;
/*
* If generate has 'group' in output, we estimate that the number of rows
* reduce by a factor of the number of groups, which is arbitrarily defined as 4
*/
for (LogicalFieldSchema field : result_fields) {
if (field.toString().startsWith("group")) {
generate_weight = (float) 1.0 / NUMBER_OF_GROUPS;
break;
}
}
Operator outerPred = this.outerPlan.getPredecessors(this.outerForEach).get(0);
try {
total_pred_fields = ((LogicalRelationalOperator)outerPred).getSchema().size();
} catch (NullPointerException npe) {
if (((LogicalRelationalOperator) outerPred) instanceof LOLoad) {
LOLoad loadOp = (LOLoad) outerPred;
if (loadOp.getFileSpec().getFileName().endsWith("widerow"))
total_pred_fields = 500;
else
throw npe;
} else
throw npe;
}
float cost = total_pred_cost * generate_weight * ( (float) 1 / total_pred_fields);
if (isUserFunc)
cost = cost * OP_SCALER_USERFUNC;
this.updateCostTable(op, cost);
}
public void visit(LOInnerLoad op) throws FrontendException {
float costEstimate;
if (this.initCost != 0.0)
costEstimate = this.initCost;
else
costEstimate = getPredCost(op);
this.updateCostTable(op, costEstimate);
}
public void visit(LOCube op) throws FrontendException {
float costEstimate = getPredCost(op);
this.updateCostTable(op, costEstimate);
}
public void visit(LOCogroup op) throws FrontendException {
float costEstimate = getPredCost(op);
this.updateCostTable(op, costEstimate);
}
public void visit(LOSplit op) throws FrontendException {
float costEstimate = getPredCost(op);
this.updateCostTable(op, costEstimate);
}
public void visit(LOSplitOutput op) throws FrontendException {
int no_of_splits = op.getSchema().getFields().size();
float costEstimate = getPredCost(op) / no_of_splits;
this.updateCostTable(op, costEstimate);
}
public void visit(LOSort op) throws FrontendException {
float costEstimate = getPredCost(op);
this.updateCostTable(op, costEstimate);
}
public void visit(LORank op) throws FrontendException {
float costEstimate = getPredCost(op);
this.updateCostTable(op, costEstimate);
}
public void visit(LODistinct op) throws FrontendException {
float costEstimate = OP_SCALER_DISTINCT * getPredCost(op);
this.updateCostTable(op, costEstimate);
}
public void visit(LOLimit op) throws FrontendException {
float costEstimate = getPredCost(op);
this.updateCostTable(op, costEstimate);
}
public void visit(LOCross op) throws FrontendException {
LogicalPlan lp = (LogicalPlan) op.getPlan();
float pred_cost_product = 1;
List<Operator> preds = lp.getPredecessors(op);
if (!preds.isEmpty()) {
for (Operator pred : preds) {
pred_cost_product *= costTable.get(pred);
}
}
this.updateCostTable(op, pred_cost_product);
}
public void visit(LOUnion op) throws FrontendException {
LogicalPlan lp = (LogicalPlan) op.getPlan();
float pred_cost_union = 0;
List<Operator> preds = lp.getPredecessors(op);
/*
List<Operator> succs = lp.getSuccessors(op);
if (!succs.isEmpty()) {
for (Operator succ : succs) {
System.out.println("succ = " + succ);
}
}
*/
if ( !preds.isEmpty() ) {
for (Operator pred : preds) {
LOG.debug("LOUnion's Pred = " + pred);
float pred_val = costTable.get(pred);
pred_cost_union += pred_val;
}
}
this.updateCostTable(op, pred_cost_union);
}
}
| true |
5620cff33560eb6ddf71f7057804d65bdd9bd1b4 | Java | ijoywan/okex-java-sdk-api-v5 | /src/main/java/com/haoshuashua/okex/bean/funding/param/Withdrawal.java | UTF-8 | 609 | 1.9375 | 2 | [] | no_license | package com.haoshuashua.okex.bean.funding.param;
import lombok.Data;
@Data
public class Withdrawal {
private String ccy;
private String amt;
private String dest;
private String toAddr;
private String pwd;
private String fee;
@Override
public String toString() {
return "Withdrawal{" +
"ccy='" + ccy + '\'' +
", amt='" + amt + '\'' +
", dest='" + dest + '\'' +
", toAddr='" + toAddr + '\'' +
", pwd='" + pwd + '\'' +
", fee='" + fee + '\'' +
'}';
}
}
| true |
b89db0dcd5e3b168de34fb2bbc820694b85006c1 | Java | FranklinZhang1992/SpringOES | /src/com/augmentum/oes/modle/UserExam.java | UTF-8 | 1,235 | 1.992188 | 2 | [] | no_license | package com.augmentum.oes.modle;
import java.io.Serializable;
public class UserExam implements Serializable {
private static final long serialVersionUID = -8065398798000496997L;
private int userId;
private int examId;
private int examScore;
private String startTime;
private String finishTime;
private String result;
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public int getExamId() {
return examId;
}
public void setExamId(int examId) {
this.examId = examId;
}
public int getExamScore() {
return examScore;
}
public void setExamScore(int examScore) {
this.examScore = examScore;
}
public String getStartTime() {
return startTime;
}
public void setStartTime(String startTime) {
this.startTime = startTime;
}
public String getFinishTime() {
return finishTime;
}
public void setFinishTime(String finishTime) {
this.finishTime = finishTime;
}
public String getResult() {
return result;
}
public void setResult(String result) {
this.result = result;
}
}
| true |
fa1695007260821e4596dd1117b49810291c22ee | Java | arsenioSoto/sistema_De_Gestao_E_Controlo_Farmaceutico | /src/main/java/mz/com/soto/junior/bean/ProdutoBean3.java | UTF-8 | 2,486 | 2.140625 | 2 | [] | no_license | package mz.com.soto.junior.bean;
import java.io.Serializable;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.event.ActionEvent;
import org.omnifaces.util.Messages;
import mz.com.soto.junior.dao.FabricanteDAO;
import mz.com.soto.junior.dao.ProdutoDAO;
import mz.com.soto.junior.domain.Fabricante;
import mz.com.soto.junior.domain.Produto;
@SuppressWarnings("serial")
@ManagedBean
@ViewScoped
public class ProdutoBean3 implements Serializable {
private Produto produto;
private Long codigoProduto;
private List<Fabricante> fabricantes;
private List<Produto> produtos;
private FabricanteDAO fabricanteDAO;
private ProdutoDAO produtoDAO;
public Produto getProduto() {
return produto;
}
public void setProduto(Produto produto) {
this.produto = produto;
}
public Long getCodigoProduto() {
return codigoProduto;
}
public void setCodigoProduto(Long codigoProduto) {
this.codigoProduto = codigoProduto;
}
public void setFabricantes(List<Fabricante> fabricantes) {
this.fabricantes = fabricantes;
}
public List<Fabricante> getFabricantes() {
return fabricantes;
}
public List<Produto> getProdutos() {
return produtos;
}
public void setProdutos(List<Produto> produtos) {
this.produtos = produtos;
}
@PostConstruct
public void iniciar(){
fabricanteDAO = new FabricanteDAO();
produtoDAO = new ProdutoDAO();
}
public void listar() {
try {
produtos = produtoDAO.listar("descricao");
} catch (RuntimeException erro) {
Messages.addGlobalError("Ocorreu um erro ao tentar listar os produtos");
erro.printStackTrace();
}
}
public void carregarEdicao(){
try {
produto = produtoDAO.buscar(codigoProduto);
fabricantes = fabricanteDAO.listar("descricao");
} catch (RuntimeException erro) {
Messages.addGlobalError("Ocorreu um erro ao tentar carregar os dados para edição");
erro.printStackTrace();
}
}
public void editar(ActionEvent evento) {
try {
produto = (Produto) evento.getComponent().getAttributes().get("produtoSelecionado");
FabricanteDAO fabricanteDAO = new FabricanteDAO();
fabricantes = fabricanteDAO.listar("descricao");
Messages.addGlobalInfo("Produto actualizado com sucesso!");
} catch (RuntimeException erro) {
Messages.addFlashGlobalError("Ocorreu um erro ao tentar selecionar um produto");
erro.printStackTrace();
}
}
}
| true |
7411b2a1432e270e7ef32880d002a95af598457f | Java | djw1149/cougaar-core | /core/src/org/cougaar/core/blackboard/AckSet.java | UTF-8 | 7,875 | 2.421875 | 2 | [] | no_license | /*
* <copyright>
*
* Copyright 1997-2004 BBNT Solutions, LLC
* under sponsorship of the Defense Advanced Research Projects
* Agency (DARPA).
*
* You can redistribute this software and/or modify it under the
* terms of the Cougaar Open Source License as published on the
* Cougaar Open Source Website (www.cougaar.org).
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* </copyright>
*/
package org.cougaar.core.blackboard;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
/**
* A bit set for keeping track of sequence numbers, used by
* the {@link MessageManager}.
* <p>
* This is similar to a BitSet, but has a shifting base index. The
* position of the first zero bit in the set can be queried and the
* representation shifted so that the one bits prior to that first
* zero don't require storage.
*/
class AckSet implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
/** The sequence number of the first zero bit. */
private int minSequence = 0;
/** The sequence number corresponding to bit 0 of the bits array */
private int baseSequence = 0;
/** The index of the last word with bits */
private transient int maxIndex = 0;
/** The values of the bits */
private transient long[] bits = new long[4];
/** Computed index in bits of a given sequence number */
private transient int index;
/** Computed bit of a given sequence number */
private transient long bit;
/**
* Construct with sequence numbers starting at zero.
*/
public AckSet() {
}
/**
* Construct with sequence numbers starting at a specified position.
* @param initialSequenceNumber the position of the first zero in
* the bit set.
*/
public AckSet(int initialSequenceNumber) {
computeIndexInfo(initialSequenceNumber);
baseSequence = index * 64;
minSequence = initialSequenceNumber;
bits[0] = bit - 1L;
}
/**
* Compute the index into the bits array and the bit corresponding
* to a given sequence number.
* @param sequenceNumber
*/
private void computeIndexInfo(int sequenceNumber) {
sequenceNumber -= baseSequence;
index = (sequenceNumber / 64);
int bitIndex = (sequenceNumber % 64);
bit = 1L << bitIndex;
}
/**
* Find the first zero in the bitset, advance minSequence to that
* position, and return that sequence number.
* @return the position of the first bit that has not be set.
*/
public synchronized int advance() {
try {
computeIndexInfo(minSequence);
if (index >= bits.length) { // Beyond the end
return minSequence;
}
if ((bits[index] & bit) == 0L) return minSequence;
while (index <= maxIndex) { // Check all the words in the array
long word = bits[index];
if (word == 0xffffffffffffffffL) {
bit = 1L; // All ones, advance to first bit
++index; // of the next word
minSequence = baseSequence + index * 64;
} else { // Some zeros here
while (bit != 0x8000000000000000L && (word & bit) != 0L) {
++minSequence;
bit <<= 1;
}
return minSequence; // That's the answer
}
}
// All ones everywhere we looked
return minSequence;
}
catch (Exception e) {
e.printStackTrace();
System.exit(13);
return 0;
}
}
/**
* Get the current minSequence value. This is always the same as the
* last value returned from advance.
* @return the position of first zero in the set as of the last call
* to advance.
*/
public int getMinSequence() {
return minSequence;
}
/**
* Set the bit corresponding to a particular sequence number. If the
* word containing the bit falls beyond the end of the array, first
* discard the words before the word containing minSequence. Then
* expand the array if necessary.
*/
public synchronized void set(int sequenceNumber) {
computeIndexInfo(sequenceNumber);
if (index < 0) return; // These bits are already set.
if (index >= bits.length) { // Beyond the end
computeIndexInfo(minSequence); // Find out where the min is
if (index > 0) { // There is room to shift down
int nw = maxIndex - index + 1; // The number of words to retain
System.arraycopy(bits, index, bits, 0, nw);
while (nw < bits.length) {
bits[nw++] = 0L; // Zero vacated words
}
baseSequence += index * 64; // Advance by bits shifted
maxIndex -= index; // Decrease by words shifted
}
computeIndexInfo(sequenceNumber); // Re-evaluate
}
if (index >= bits.length) { // Still beyond the end?
long[] oldBits = bits; // Need to expand
bits = new long[index + 4]; // Make it a little bigger
// than necessary
System.arraycopy(oldBits, 0, bits, 0, maxIndex + 1);
}
bits[index] |= bit;
if (index > maxIndex) {
maxIndex = index;
}
}
/**
* Test if a particular bit is set.
* @param sequenceNumber the bit to test.
* @return true if the specified bit has been set.
*/
public boolean isSet(int sequenceNumber) {
if (sequenceNumber < minSequence) {
return true; // No need to test these
}
computeIndexInfo(sequenceNumber);
if (index > maxIndex) {
return false; // These are always zero
}
return ((bits[index] & bit) != 0L);
}
/**
* Write this object. We only write the active portion of the bits
* array
*/
private synchronized void writeObject(ObjectOutputStream os) throws IOException {
os.defaultWriteObject();
os.writeInt(maxIndex);
for (int i = 0; i <= maxIndex; i++) {
os.writeLong(bits[i]);
}
}
/**
* Read this object. The bits array is restored.
*/
private void readObject(ObjectInputStream is) throws IOException, ClassNotFoundException {
is.defaultReadObject();
maxIndex = is.readInt();
bits = new long[maxIndex + 1];
for (int i = 0; i <= maxIndex; i++) {
bits[i] = is.readLong();
}
}
@Override
public String toString() {
StringBuffer buf = new StringBuffer();
buf.append(0);
boolean inRange = false;
int prevSeq = minSequence-1;
for (int seq = minSequence; ; seq++) {
if (isSet(seq)) {
if (seq != prevSeq + 1) {
if (inRange) {
buf.append(prevSeq);
inRange = false;
}
buf.append(",");
buf.append(seq);
prevSeq = seq;
} else {
if (!inRange) {
buf.append("..");
inRange = true;
}
prevSeq = seq;
}
} else if (index > maxIndex) {
break;
}
}
if (inRange) {
buf.append(prevSeq);
}
return buf.substring(0);
}
}
| true |
be19f5761e062b34ecef5d7b3cedcf7a19cee134 | Java | hamed-dvrm/DesignPattern_Java | /src/CourierStrategy.java | UTF-8 | 261 | 2.828125 | 3 | [] | no_license | public class CourierStrategy implements SendStrategy {
@Override
public void send(int index) {
System.out.println("Courier : Character " + index + " got the notification");
}
public String toString(){
return "courier";
}
}
| true |
6c9df58fe9b0392cf3fdcd2dfd7f6be847de7909 | Java | ZeynelAkin/Java-SE-Calismalarim | /006_ControlStatements_Kontrolifadeleri/src/com/_25_ForSwitch.java | UTF-8 | 564 | 3.3125 | 3 | [] | no_license | package com;
public class _25_ForSwitch {
public static void main(String[] args) {
for (int i = 0; i < 3; i++) {
switch (i)
{ case 0:
System.out.println("sıfır");
break;
case 1:
System.out.println("Bir");
break;
case 2:
System.out.println("İki");
break;
default:
System.out.println("farklı bir sayı girildi");
}
}
}
}
| true |
0420caf48f0f9860285a41851523873d5440b448 | Java | robbaker292/SportParser | /src/rob/strataparser/chance/AssistType.java | UTF-8 | 728 | 2.4375 | 2 | [] | no_license | package rob.strataparser.chance;
public enum AssistType {
CORNER("corner"),
CORNER_WON("corner won"),
CROSS_HIGH("cross high"),
CROSS_LOW("cross low"),
FREEKICK("freekick"),
FREEKICK_WON("freekick won"),
DANGEROUS_MOMENT("danger moment"),
OPEN_PLAY_PASS("pass"),
PENALTY_EARNED("pen earned"),
SHOT_DEFLECTION("shot deflection"),
SHOT_OPPOSITION_REBOUND("shot oppo rebound"),
SHOT_WOODWORK_REBOUND("shot woodwork rebound"),
THROW_IN("throw in"),
TURNOVER("turnover");
private String description;
private AssistType(String description) {
this.description = description;
}
public String getDescription() {
return description;
}
@Override
public String toString() {
return getDescription();
}
}
| true |
1f71db10cca6d20601301e35063ce53254eac777 | Java | BKampers/LookAndFeel | /src/bka/swing/validators/AbstractValidator.java | UTF-8 | 3,873 | 2.375 | 2 | [] | no_license |
package bka.swing.validators;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.text.*;
public abstract class AbstractValidator extends JFormattedTextField.AbstractFormatterFactory {
@SuppressWarnings("LeakingThisInConstructor")
public AbstractValidator(JFormattedTextField field, Number min, Number max) {
this.field = field;
this.min = min;
this.max = max;
formatter = new Formatter();
field.setFormatterFactory(this);
field.addFocusListener(FOCUS_ADAPTER);
field.addKeyListener(KEY_ADAPTER);
field.addPropertyChangeListener(PROPERTY_CHANGE_LISTENER);
verify();
}
public void setListener(ValidatorListener listener) {
this.listener = listener;
}
final public void verify() {
Number value = value();
if (value != null) {
valid = inRange(value);
}
else {
valid = false;
}
formatter.changeEditValid();
if (listener != null) {
listener.verified(valid);
}
}
public JFormattedTextField.AbstractFormatter getFormatter(JFormattedTextField tf) {
return formatter;
}
public void setSilent(boolean silent) {
this.silent = silent;
}
public boolean isSilent() {
return silent;
}
public abstract Number value();
protected abstract boolean inRange(Number number);
protected abstract String filter(String text, int offset);
protected boolean filterError(String text, String filtered) {
return ! text.equals(filtered);
}
private void setBackground() {
if (valid || ! field.isEnabled()) {
field.setBackground(UIManager.getColor("FormattedTextField.background"));
}
else {
field.setBackground(UIManager.getColor("errorBackground"));
}
field.invalidate();
}
private class Formatter extends DefaultFormatter {
void changeEditValid() {
setEditValid(valid);
setBackground();
}
protected void setEditValid(boolean valid) {
JFormattedTextField ftf = getFormattedTextField();
if (ftf != null) {
super.setEditValid(valid);
}
}
protected javax.swing.text.DocumentFilter getDocumentFilter() {
return FILTER;
}
private final DocumentFilter FILTER = new DocumentFilter() {
public void replace(DocumentFilter.FilterBypass fb, int offset, int length, String text, AttributeSet attrs) throws BadLocationException {
String filtered = filter(text, offset);
if (! silent && filterError(text, filtered)) {
invalidEdit();
}
super.replace(fb, offset, length, filtered, attrs);
}
};
}
private final FocusAdapter FOCUS_ADAPTER = new FocusAdapter() {
public void focusLost(java.awt.event.FocusEvent evt) {
formatter.changeEditValid();
}
};
private final KeyAdapter KEY_ADAPTER = new KeyAdapter() {
public void keyReleased(KeyEvent evt) {
verify();
}
};
private final java.beans.PropertyChangeListener PROPERTY_CHANGE_LISTENER = new java.beans.PropertyChangeListener() {
public void propertyChange(java.beans.PropertyChangeEvent evt) {
String name = evt.getPropertyName();
if ("enabled".equals(name)) {
setBackground();
}
}
};
protected JFormattedTextField field;
protected Number min;
protected Number max;
private Formatter formatter;
private boolean valid = false;
private boolean silent = true;
private ValidatorListener listener = null;
}
| true |
80a18acb9a701fa57d836ae8053ba5094567fe8f | Java | amelio-sysproga/PizzaDelivery-master | /src/main/java/edu/up/pizzadelivery/view/EscolherTamanhoActivity.java | UTF-8 | 2,451 | 2.078125 | 2 | [] | no_license | package edu.up.pizzadelivery.view;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import edu.up.pizzadelivery.DAO.TamanhoDAO;
import edu.up.pizzadelivery.R;
import edu.up.pizzadelivery.model.Tamanho;
public class EscolherTamanhoActivity extends AppCompatActivity {
private ListView lstTamanhos;
private static final String ARQUIVO_PREF = "LogUsuario";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_escolher_tamanho);
// id pedido esta vindo null
Bundle bundle = getIntent().getExtras();
final int idPedido = bundle.getInt("IDPEDIDO");
Log.i("id do pedido",""+idPedido);
lstTamanhos = (ListView) findViewById(R.id.lstTamanhos);
final ArrayList<Tamanho> tamanhosArrayList = TamanhoDAO.retornarTamanhos(this);
String[] tamanhos = new String[tamanhosArrayList.size()];
for (int i = 0; i < tamanhosArrayList.size(); i++) {
tamanhos[i] = tamanhosArrayList.get(i).getNome();
}
// TamanhosAdapter tamanhosAdapter = new TamanhosAdapter(tamanhosArrayList,this);
//O adapter é componente que prepara os dados para o ListView
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_single_choice, tamanhos);
//setAdapter é método que vai popular os dados dentro do ListView
lstTamanhos.setAdapter(adapter);
//Criar o clique de cada do ListView
lstTamanhos.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
lstTamanhos.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(EscolherTamanhoActivity.this, BordaActivity.class);
intent.putExtra("TAMANHO", tamanhosArrayList.get(position));
intent.putExtra("IDPEDIDO", idPedido);
startActivity(intent);
}
});
}
}
| true |
1682e87cdd22ff7c38d5e836fac6a61b9cde3b42 | Java | nirkrieger/oop-ex5 | /filesprocessing/filters/filters/WritableFilter.java | UTF-8 | 554 | 2.875 | 3 | [] | no_license | package filesprocessing.filters.filters;
import filesprocessing.filters.filters.BooleanFilter;
import java.io.File;
public class WritableFilter extends BooleanFilter {
/**
* represents if true or false.
*/
public WritableFilter(boolean flag) {
super(flag);
}
/**This doeas the actual filtering
* @param pathname the file
* @return true if the file passes the filter, false otherwise
*/
@Override
public boolean accept(File pathname) {
return logicalNotXor(super.accept(pathname),pathname.canWrite());
}
}
| true |
e99202122fd4d7cbeacbcb99ad2e5a6757c53254 | Java | Mitaxing/Hotelen | /app/src/main/java/com/kupa/hotel/adapter/FifthSecondServerRVAdapter.java | UTF-8 | 3,544 | 2.109375 | 2 | [] | no_license | package com.kupa.hotel.adapter;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.kupa.hotel.R;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;
/**
* Created by admin on 2017/6/7.
*/
public class FifthSecondServerRVAdapter extends RecyclerView.Adapter<FifthSecondServerRVAdapter.FifthSecondViewHolder> {
private Context context;
private static SecondServerClickListener secondClickListener;
private String[] names = {"Movies", "Online Store", "Travel", "Delicious", "Service"};
private int[] bgs = {R.drawable.item_server_movie, R.drawable.item_server_shopping, R.drawable.item_server_view,
R.drawable.item_server_food, R.drawable.item_second_server};
private int[] enterFocusIcons = {R.mipmap.focus_icon_movie, R.mipmap.focus_icon_buy, R.mipmap.focus_icon_trip,
R.mipmap.focus_icon_eat, R.mipmap.focus_icon_hotel};
public FifthSecondServerRVAdapter(Context context) {
this.context = context;
}
@Override
public FifthSecondViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.item_fifth_second, parent, false);
FifthSecondViewHolder holder = new FifthSecondViewHolder(view);
x.view().inject(holder, view);
return holder;
}
@Override
public void onBindViewHolder(final FifthSecondViewHolder holder, int position) {
holder.mTvName.setText(names[position]);
holder.mLlBg.setBackgroundResource(bgs[position]);
holder.mIvIcon.setBackgroundResource(enterFocusIcons[position]);
holder.itemView.setFocusable(true);
holder.itemView.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View view, boolean hasFocus) {
if (hasFocus) {
holder.mIvFocus.setVisibility(View.VISIBLE);
holder.mBorder.setVisibility(View.VISIBLE);
} else {
holder.mIvFocus.setVisibility(View.GONE);
holder.mBorder.setVisibility(View.GONE);
}
}
});
}
@Override
public int getItemCount() {
return names.length;
}
public static class FifthSecondViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public FifthSecondViewHolder(View itemView) {
super(itemView);
itemView.setOnClickListener(this);
}
@ViewInject(R.id.item_second_name)
TextView mTvName;
@ViewInject(R.id.item_second_icon)
ImageView mIvIcon;
@ViewInject(R.id.item_second_focus)
ImageView mIvFocus;
@ViewInject(R.id.item_second_layout)
LinearLayout mLlBg;
@ViewInject(R.id.item_second_focus_border)
ImageView mBorder;
@Override
public void onClick(View view) {
if (secondClickListener != null) {
secondClickListener.onClick(view);
}
}
}
public void setSecondClickListener(SecondServerClickListener secondClickListener) {
this.secondClickListener = secondClickListener;
}
public interface SecondServerClickListener {
void onClick(View v);
}
}
| true |
63fee3dc9dc29b398ef6a8c9bee3ef61d29bed58 | Java | igorfalko/payservice | /src/main/java/gpb/web/dto/OfficeReport.java | UTF-8 | 2,061 | 2.40625 | 2 | [] | no_license | package gpb.web.dto;
import gpb.report.IReport;
import java.math.BigDecimal;
import java.util.Objects;
public class OfficeReport implements IReport {
// * точка продаж
// * количество платежей
// * сумма платежей
// * сумма комиссии
private final String office;
private final Long paymentCount;
private final BigDecimal paymentSum;
private final BigDecimal paymentCommissionSum;
public OfficeReport(String office, Long paymentCount, BigDecimal paymentSum, BigDecimal paymentCommissionSum) {
this.office = office;
this.paymentCount = paymentCount;
this.paymentSum = paymentSum;
this.paymentCommissionSum = paymentCommissionSum;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
OfficeReport that = (OfficeReport) o;
return Objects.equals(office, that.office) &&
Objects.equals(paymentCount, that.paymentCount) &&
Objects.equals(paymentSum, that.paymentSum) &&
Objects.equals(paymentCommissionSum, that.paymentCommissionSum);
}
@Override
public int hashCode() {
return Objects.hash(office, paymentCount, paymentSum, paymentCommissionSum);
}
public String getOffice() {
return office;
}
public Long getPaymentCount() {
return paymentCount;
}
public BigDecimal getPaymentSum() {
return paymentSum;
}
public BigDecimal getPaymentCommissionSum() {
return paymentCommissionSum;
}
@Override
public String toJson() {
return
"{" +
"\"office\":\"" + office + "\"," +
"\"paymentCount\":\""+ paymentCount +"\"," +
"\"paymentSum\":" + paymentSum + "," +
"\"paymentCommissionSum\":\"" + paymentCommissionSum + "\"" +
"}";
}
}
| true |
9b168e4c86467fea222bfe488b773cc9cedf9e59 | Java | santhosh1980/bradyrochfordmavenpro | /src/test/java/Tuto/myStaticReturn.java | UTF-8 | 414 | 3.1875 | 3 | [] | no_license | package Tuto;
public class myStaticReturn {
static int addmethod(int dig1, int dig2) {
return(dig1+dig2);
}
static int diffmethod(int dig1, int dig2) {
return(dig1-dig2);
}
static int mulmethod(int dig1, int dig2) {
return(dig1*dig2);
}
public static void main(String[] args) {
System.out.println(addmethod(4,2));
System.out.println(diffmethod(4,2));
System.out.println(mulmethod(4,2));
}
}
| true |
69653acafac987fe6894fec87e71667c509364f9 | Java | brianbc4/CrazyMikeNative | /app/src/main/java/com/crazymike/alert/DailyNotification.java | UTF-8 | 2,536 | 2.15625 | 2 | [] | no_license | package com.crazymike.alert;
import android.content.Context;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import com.crazymike.R;
import com.crazymike.api.NetworkService;
import com.crazymike.api.response.DailyNoticeResponse;
import com.crazymike.models.DailyNotice;
import com.crazymike.util.RxUtil;
import com.crazymike.web.WebViewActivity;
import java.util.ArrayList;
import java.util.List;
/**
* Created by user1 on 2017/3/16.
*/
public class DailyNotification extends AlertDialog implements View.OnClickListener{
private Context mContext;
private View view;
private Button conferm;
private ImageView close;
private TextView title,content;
private DailyNotice dailyNotice;
public DailyNotification(Context context) {
super(context);
mContext = context;
initView();
}
private void initView(){
view = LayoutInflater.from(mContext).inflate(R.layout.dialog_daily_notice, null);
close = (ImageView) view.findViewById(R.id.close);
title = (TextView) view.findViewById(R.id.title);
content = (TextView) view.findViewById(R.id.content);
conferm = (Button) view.findViewById(R.id.conferm);
NetworkService.getInstance().getDailyNoticeApi().callDailyNotice("notice","-1","android","indextAlert")
.map(dailyNoticeResponse -> {
dailyNotice= dailyNoticeResponse.getDailyNoticeList().get(0);
title.setText(dailyNotice.getTitle());
content.setText(dailyNotice.getContent());
conferm.setText(dailyNotice.getIs_url().equals("t")?"立即前往":"好的");
return this;
}).compose(RxUtil.mainAsync())
.subscribe();
setView(view);
close.setOnClickListener(this);
conferm.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch(v.getId()) {
case R.id.close:
dismiss();
break;
case R.id.conferm:
if(dailyNotice.getIs_url().equals("t")){
WebViewActivity.startActivity(mContext,dailyNotice.getUrl());
dismiss();
}else{
dismiss();
}
break;
}
}
} | true |
73e2aedcca7ec34478077db6611f11a346f364c6 | Java | Keos99/BugTracker | /src/main/java/Search.java | UTF-8 | 1,567 | 2.59375 | 3 | [] | no_license | import java.util.ArrayList;
public class Search {
private Users users;
private Projects projects;
private Issues issues;
private Data bugdata;
private ArrayList<Integer> tempdata;
private int[][] data;
private int usernumber;
private int projectnumber;
public Search(Users users, Projects projects, Data data,Issues issues){
usernumber = 0;
projectnumber = 0;
this.users = users;
this.projects = projects;
this.issues = issues;
this.bugdata = data;
tempdata = new ArrayList<>();
}
public void findIssuesByUserAndProject(){
if (issues.getIssues().size() != 0){
this.data = bugdata.getData();
usernumber = users.getUserNumber(users.chooseUser());
projectnumber = projects.getProjectNumber(projects.chooseProject());
if (data != null){
for (int i = 0; i < data[1].length; i++) {
if (data[0][i] == usernumber && data[1][i] == projectnumber && data[3][i] == 1) {
tempdata.add(i);
}
}
}
if (tempdata.size() != 0){
bugdata.showData(tempdata);
tempdata.clear();
} else {
System.out.println("Записей не найдено!");
}
} else {
System.out.println("Вопросы еще никто не добавлял.");
System.out.println("Поиск прерван!\n");
}
}
}
| true |
470acc3fd6bdbf68a38dc2bacaf9806b686e1270 | Java | hybrezz54/Android | /DubstepLionsRadar/app/src/main/java/technowolves/org/otpradar/fragment/TeamFragment.java | UTF-8 | 14,260 | 2.109375 | 2 | [] | no_license | package technowolves.org.otpradar.fragment;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.RatingBar;
import android.widget.Spinner;
import technowolves.org.otpradar.R;
import technowolves.org.otpradar.framework.Team;
public class TeamFragment extends Fragment {
public static final String PREFS_KEY = "technowolves.org.otpradar.PREFERENCE_FILE_KEY";
public static final String NUMBER_KEY = "TEAM_NUMBER";
public static final String NAME_KEY = "TEAM_NAME";
public static final String SITE_KEY = "WEB_SITE";
public static final String LOCATION_KEY = "LOCATION";
public static final String TOTAL_KEY = "TOTAL_YEARS";
public static final String OTHER_KEY = "PARTICIPATION";
public static final String AWARD1_KEY = "AWARD_ONE_KEY";
public static final String AWARD2_KEY = "AWARD_TWO_KEY";
public static final String AWARD3_KEY = "AWARD_THREE_KEY";
public static final String YEAR1_KEY = "YEAR_ONE_KEY";
public static final String YEAR2_KEY = "YEAR_TWO_KEY";
public static final String YEAR3_KEY = "YEAR_THREE_KEY";
public static final String NOTES_KEY = "NOTES_KEY";
public static final String DRIVER1_KEY = "DRIVER_NAME_ONE";
public static final String DRIVER2_KEY = "DRIVER_NAME_TWO";
public static final String COACH_KEY = "COACH_NAME";
public static final String CM_KEY = "COACH_MENTOR";
public static final String DRIVER_KEY = "DRIVER_RATE";
public static final String HP_KEY = "HP_RATE";
public static final String HPTOTE_KEY = "HP_TOTE";
public static final String HPLITTER_KEY = "HP_LITTER";
public static final String HPTHROW_KEY = "HP_THROW";
public static final String[] HEADER = new String[] {"Number", "Name", "Website", "Location", "Total Yrs.", "Another competition this year?", "Award 1",
"Year 1", "Award 2", "Year 2", "Award 3", "Year 3", "Notes", "Driver #1 Name", "Driver #2 Name", "Drive Coach Name", "Is drive coach mentor?",
"Driver Rating", "Human Player Rating", "HP: Can load totes?", "HP: Can load litter?", "HP: Can throw litter?"};
public static final String[] AWARDS = new String[] {"------", "Rookie All Star Award", "Chairman's Award", "Creativity Award", "Dean's List Award",
"Engineering Excellence Award", "Engineering Inspiration Award", "Entrepreneurship Award", "Gracious Professionalism", "Imagery Award",
"Industrial Design Award", "Industrial Safety Award", "Innovation in Control Award", "Media & Tech. Innovation Award",
"Judges' Award", "Quality Award", "Team Spirit Award", "Woodie Flowers Finalist Award", "Rookie Inspiration Award",
"Highest Rookie Seed", "Regional Finalist", "Regional Winner"};
public static final String[] YEARS = new String[] {"------", "2015", "2014", "2013", "2012", "2011", "2010", "2009", "2008", "2007", "2006", "2005",
"2004", "2003", "2002", "2001", "2000"};
public static final String[] COMPETITION = new String[] {"No - 1st competition this year", "Yes - 2nd competition this year"};
public static final String[] SIMPLE = new String[] {"------", "No", "Yes"};
private static boolean isEditing;
private static int mPosition;
private static boolean isExisting;
private EditText mNumber;
private EditText mTeam;
private EditText mSite;
private EditText mLocation;
private EditText mTotal;
private Spinner mParticipation;
private Spinner mAwardOne;
private Spinner mYearOne;
private Spinner mAwardTwo;
private Spinner mYearTwo;
private Spinner mAwardThree;
private Spinner mYearThree;
private EditText mNotes;
private EditText mDriver1;
private EditText mDriver2;
private EditText mCoach;
private Spinner mCoachMentor;
private RatingBar mDriverRate;
private RatingBar mHpRate;
private Spinner mHpTote;
private Spinner mHpLitter;
private Spinner mHpThrow;
public static TeamFragment newInstance(int position, boolean editing, boolean existing) {
TeamFragment fragment = new TeamFragment();
/*Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);*/
mPosition = position;
isEditing = editing;
isExisting = existing;
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
setRetainInstance(true);
ActionBar bar = ((ActionBarActivity) getActivity()).getSupportActionBar();
bar.setHomeButtonEnabled(true);
bar.setTitle("Team Details");
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
if (isEditing)
getActivity().getMenuInflater().inflate(R.menu.save, menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
FragmentManager fm = getFragmentManager();
switch (id) {
case android.R.id.home:
fm.popBackStack();
break;
case R.id.action_save:
saveValues();
if (!isExisting) {
((PrimaryListFragment) fm.findFragmentByTag("PrimaryListFragment1"))
.add(new Team(mNumber.getText().toString(), mTeam.getText().toString()));
} else {
((PrimaryListFragment) fm.findFragmentByTag("PrimaryListFragment1"))
.update(new Team(mNumber.getText().toString(), mTeam.getText().toString()), mPosition);
}
fm.popBackStack();
break;
}
return super.onOptionsItemSelected(item);
}
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_team_data, container, false);
mNumber = (EditText) rootView.findViewById(R.id.edtNumber);
mTeam = (EditText) rootView.findViewById(R.id.edtName);
mSite = (EditText) rootView.findViewById(R.id.edtWebsite);
mLocation = (EditText) rootView.findViewById(R.id.edtLocation);
mTotal = (EditText) rootView.findViewById(R.id.edtTotal);
mParticipation = (Spinner) rootView.findViewById(R.id.participate);
mAwardOne = (Spinner) rootView.findViewById(R.id.award1);
mYearOne = (Spinner) rootView.findViewById(R.id.year1);
mAwardTwo = (Spinner) rootView.findViewById(R.id.award2);
mYearTwo = (Spinner) rootView.findViewById(R.id.year2);
mAwardThree = (Spinner) rootView.findViewById(R.id.award3);
mYearThree = (Spinner) rootView.findViewById(R.id.year3);
mNotes = (EditText) rootView.findViewById(R.id.notes);
mDriver1 = (EditText) rootView.findViewById(R.id.edtDriver1);
mDriver2 = (EditText) rootView.findViewById(R.id.edtDriver2);
mCoach = (EditText) rootView.findViewById(R.id.edtCoach);
mCoachMentor = (Spinner) rootView.findViewById(R.id.coachMentor);
mDriverRate = (RatingBar) rootView.findViewById(R.id.driverRating);
mHpRate = (RatingBar) rootView.findViewById(R.id.hpRating);
mHpTote = (Spinner) rootView.findViewById(R.id.hpTote);
mHpLitter = (Spinner) rootView.findViewById(R.id.hpLitter);
mHpThrow = (Spinner) rootView.findViewById(R.id.hpThrow);
initSpinner();
loadValues();
if (!isEditing)
disableViews();
return rootView;
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
}
private void initSpinner() {
ArrayAdapter<String> comp = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_dropdown_item, COMPETITION);
ArrayAdapter<String> simple = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_dropdown_item, SIMPLE);
ArrayAdapter<String> year = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_dropdown_item, YEARS);
ArrayAdapter<String> award = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_dropdown_item, AWARDS);
mParticipation.setAdapter(comp);
mAwardOne.setAdapter(award);
mAwardTwo.setAdapter(award);
mAwardThree.setAdapter(award);
mYearOne.setAdapter(year);
mYearTwo.setAdapter(year);
mYearThree.setAdapter(year);
mCoachMentor.setAdapter(simple);
mHpTote.setAdapter(simple);
mHpLitter.setAdapter(simple);
mHpThrow.setAdapter(simple);
}
private void disableViews() {
mNumber.setEnabled(false);
mTeam.setEnabled(false);
mSite.setEnabled(false);
mLocation.setEnabled(false);
mTotal.setEnabled(false);
mParticipation.setEnabled(false);
mAwardOne.setEnabled(false);
mYearOne.setEnabled(false);
mAwardTwo.setEnabled(false);
mYearTwo.setEnabled(false);
mAwardThree.setEnabled(false);
mYearThree.setEnabled(false);
mNotes.setEnabled(false);
mDriver1.setEnabled(false);
mDriver2.setEnabled(false);
mCoach.setEnabled(false);
mCoachMentor.setEnabled(false);
mDriverRate.setEnabled(false);
mHpRate.setEnabled(false);
mHpTote.setEnabled(false);
mHpLitter.setEnabled(false);
mHpThrow.setEnabled(false);
}
private void loadValues() {
SharedPreferences prefs = getActivity().getSharedPreferences(PREFS_KEY + mPosition, Context.MODE_PRIVATE);
String number = prefs.getString(NUMBER_KEY, "");
String name = prefs.getString(NAME_KEY, "");
String site = prefs.getString(SITE_KEY, "");
String location = prefs.getString(LOCATION_KEY, "");
String total = prefs.getString(TOTAL_KEY, "");
int other = prefs.getInt(OTHER_KEY, 0);
int awardOne = prefs.getInt(AWARD1_KEY, 0);
int awardTwo = prefs.getInt(AWARD2_KEY, 0);
int awardThree = prefs.getInt(AWARD3_KEY, 0);
int yearOne = prefs.getInt(YEAR1_KEY, 0);
int yearTwo = prefs.getInt(YEAR2_KEY, 0);
int yearThree = prefs.getInt(YEAR3_KEY, 0);
String notes = prefs.getString(NOTES_KEY, "");
String driver1 = prefs.getString(DRIVER1_KEY, "");
String driver2 = prefs.getString(DRIVER2_KEY, "");
String coach = prefs.getString(COACH_KEY, "");
int coachMentor = prefs.getInt(CM_KEY, 0);
float driver = prefs.getFloat(DRIVER_KEY, 0f);
float hp = prefs.getFloat(HP_KEY, 0f);
int hptote = prefs.getInt(HPTOTE_KEY, 0);
int hplitter = prefs.getInt(HPLITTER_KEY, 0);
int hpthrow = prefs.getInt(HPTHROW_KEY, 0);
mNumber.setText(number);
mTeam.setText(name);
mSite.setText(site);
mLocation.setText(location);
mTotal.setText(total);
mParticipation.setSelection(other);
mAwardOne.setSelection(awardOne);
mAwardTwo.setSelection(awardTwo);
mAwardThree.setSelection(awardThree);
mYearOne.setSelection(yearOne);
mYearTwo.setSelection(yearTwo);
mYearThree.setSelection(yearThree);
mNotes.setText(notes);
mDriver1.setText(driver1);
mDriver2.setText(driver2);
mCoach.setText(coach);
mCoachMentor.setSelection(coachMentor);
mDriverRate.setRating(driver);
mHpRate.setRating(hp);
mHpTote.setSelection(hptote);
mHpLitter.setSelection(hplitter);
mHpThrow.setSelection(hpthrow);
}
private void saveValues() {
SharedPreferences prefs = getActivity().getSharedPreferences(PREFS_KEY + mPosition, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putString(NUMBER_KEY, mNumber.getText().toString());
editor.putString(NAME_KEY, mTeam.getText().toString());
editor.putString(SITE_KEY, mSite.getText().toString());
editor.putString(LOCATION_KEY, mLocation.getText().toString());
editor.putString(TOTAL_KEY, mTotal.getText().toString());
editor.putInt(OTHER_KEY, mParticipation.getSelectedItemPosition());
editor.putInt(AWARD1_KEY, mAwardOne.getSelectedItemPosition());
editor.putInt(AWARD2_KEY, mAwardTwo.getSelectedItemPosition());
editor.putInt(AWARD3_KEY, mAwardThree.getSelectedItemPosition());
editor.putInt(YEAR1_KEY, mYearOne.getSelectedItemPosition());
editor.putInt(YEAR2_KEY, mYearTwo.getSelectedItemPosition());
editor.putInt(YEAR3_KEY, mYearThree.getSelectedItemPosition());
editor.putString(NOTES_KEY, mNotes.getText().toString());
editor.putString(DRIVER1_KEY, mDriver1.getText().toString());
editor.putString(DRIVER2_KEY, mDriver2.getText().toString());
editor.putString(COACH_KEY, mCoach.getText().toString());
editor.putInt(CM_KEY, mCoachMentor.getSelectedItemPosition());
editor.putFloat(DRIVER_KEY, mDriverRate.getRating());
editor.putFloat(HP_KEY, mHpRate.getRating());
editor.putInt(HPTOTE_KEY, mHpTote.getSelectedItemPosition());
editor.putInt(HPLITTER_KEY, mHpLitter.getSelectedItemPosition());
editor.putInt(HPTHROW_KEY, mHpThrow.getSelectedItemPosition());
editor.commit();
}
/*public void removeValues(int index) {
SharedPreferences prefs = getActivity().getSharedPreferences(PREFS_KEY + index, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.clear();
editor.commit();
}*/
}
| true |
5f452d18d08c0819c5df33aabb4919af841f6561 | Java | bcrochez/online-cv | /src/main/java/fr/upem/onlinecv/bean/SearchManagedBean.java | UTF-8 | 421 | 2.28125 | 2 | [
"MIT"
] | permissive | package fr.upem.onlinecv.bean;
/**
*
* @author Bastien
*/
public class SearchManagedBean {
private String query;
/**
* Creates a new instance of SearchManagedBean
*/
public SearchManagedBean() {
}
public String getQuery() {
return query;
}
public void setQuery(String query) {
System.out.println("set query : "+query);
this.query = query;
}
}
| true |
8830e131299ab78212036b7fd08b995694e606de | Java | ppliuzf/sgai-training-property | /src/main/java/com/sgai/property/em/web/EmSecuRecordController.java | UTF-8 | 15,690 | 1.867188 | 2 | [] | no_license | package com.sgai.property.em.web;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.sgai.common.persistence.Page;
import com.sgai.common.utils.StringUtils;
import com.sgai.common.web.BaseController;
import com.sgai.property.ctl.entity.CtlAttachfile;
import com.sgai.property.ctl.entity.CtlCodeDet;
import com.sgai.property.ctl.service.CtlAttachfileService;
import com.sgai.property.ctl.service.CtlCodeDetService;
import com.sgai.property.ctl.service.CtlComRuleService;
import com.sgai.property.ctl.service.DeleteRulesUtils;
import com.sgai.property.em.dto.EmSecuRecordVo;
import com.sgai.property.em.entity.EmSecuRecord;
import com.sgai.property.em.service.EmSecuRecordService;
import com.sgai.modules.login.jwt.bean.LoginUser;
import com.sgai.modules.login.jwt.util.CommonResponse;
import com.sgai.modules.login.jwt.util.ResponseUtil;
import com.sgai.modules.login.support.UserServletContext;
import com.sgai.property.wf.service.WfUserRightService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
/**
* 安保事件维护Controller
* @author guanze
* @version 2017-12-05
*/
@Controller
@RequestMapping(value = "${adminPath}/emSecuRecord")
@Api(description = "安保事件接口")
public class EmSecuRecordController extends BaseController {
@Autowired
private EmSecuRecordService emSecuRecordService;
@Autowired
private DeleteRulesUtils deleteRulesUtils;
@Autowired
private CtlAttachfileService ctlAttachfileService;
@Autowired
private CtlComRuleService ctlComRuleService;
SimpleDateFormat formatParam = new SimpleDateFormat("yyyyMMdd");
@Autowired
private WfUserRightService wfUserRightService;
@Autowired
private CtlCodeDetService ctlCodeDetService;
@ApiOperation(value = "安保事件列表", notes = "安保事件列表")
@RequestMapping(value = {"list", ""},method=RequestMethod.GET )
public String list(EmSecuRecord emSecuRecord,
@RequestHeader(value="token")String token,
@RequestParam(value="pageNo",required = true ,defaultValue = "0" )Integer pageNo,
@RequestParam(value="pageSize",required = true ,defaultValue = "10" )Integer pageSize,
HttpServletRequest request, HttpServletResponse response, Model model) {
if(emSecuRecord==null){
emSecuRecord=new EmSecuRecord();
}
Page<EmSecuRecord> page = emSecuRecordService.findPage(new Page<EmSecuRecord>(pageNo, pageSize), emSecuRecord);
model.addAttribute("page", page);
return "em/emsecurecord/emSecuRecordList";
}
@ApiOperation(value = "安保事件form", notes = "安保事件form")
@RequestMapping(value = "form",method=RequestMethod.GET)
public String form(EmSecuRecord emSecuRecord, Model model) {
model.addAttribute("emSecuRecord", emSecuRecord);
return "em/emsecurecord/emSecuRecordForm";
}
@ApiOperation(value = "安保事件创建页面", notes = "安保事件创建页面")
@RequestMapping(value = "emSecuRecordForm",method=RequestMethod.GET)
public String emSecuRecordForm(EmSecuRecord emSecuRecord, @RequestHeader(value="token")String token,String instanceId, String emCode, String emType, Model model) {
model.addAttribute("emSecuRecord", emSecuRecord);
return "/em/emSecuRecordCreateForm";
}
@ApiOperation(value = "安保事件保存", notes = "安保事件保存")
@RequestMapping(value = "save",method=RequestMethod.POST )
public @ResponseBody Map<String,String> save(
@RequestHeader(value="token")String token,
@RequestBody EmSecuRecord emSecuRecord) {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Map<String,String> data = new HashMap<String,String>();
emSecuRecord.setEnabledFlag("Y");
//emSecuRecord.setComCode(user.getComCode());
LoginUser user = UserServletContext.getUserInfo();
try {
if (StringUtils.isBlank(emSecuRecord.getId())) {
String emCode = ctlComRuleService.getNext("EMCODE-AB");
emSecuRecord.setEmCode(emCode);
emSecuRecord.setReportDatetime(new Date());
emSecuRecord.setEmType("AB");
emSecuRecord.setStates("0");
emSecuRecordService.saveSecuRecord(emSecuRecord,user);
//String path="";//图片服务器地址
if (emSecuRecord.getRepairPhoto()!=null && !"".equals(emSecuRecord.getRepairPhoto())) {
String[] images = emSecuRecord.getRepairPhoto().split("\\|");
for(String str:images) {
CtlAttachfile p = new CtlAttachfile();
p.setMasterFileType("安保事件");//模块名称
p.setKeyDesc("安保图片");//文件描述
p.setMasterFileId(emSecuRecord.getId());//主表id
p.setUploadSession(token);//用户token
String filePath = str.substring(0, 31) + user.getUserId() + "/";
String fileName = str.substring(filePath.length());
p.setFileName(fileName);//文件名称
p.setFileLoc(filePath);//文件存储路径
p.setUploadTime(format.format(new Date()));//上传时间
p.setContentType("multipart/form-data; charset=utf-8");//文件MIME类型
//File file = new File(path + str);
//p.setFileSize(String.valueOf(file.length()));//文件大小,单位byte
ctlAttachfileService.saveAttachfile(p);
}
}
data.put("message", "success");
} else {
//如果是更新数据,直接执行save方法
emSecuRecordService.save(emSecuRecord);
data.put("message", "success");
}
} catch (Exception e) {
data.put("message", "failed");
e.printStackTrace();
}
return data;
}
@ApiOperation(value = "安保事件删除", notes = "安保事件删除")
@ApiImplicitParams({
@ApiImplicitParam(name = "ids", value = "id集合", required = false,paramType = "query", dataType = "String")
})
@RequestMapping(value = "delete",method=RequestMethod.POST )
public @ResponseBody Map<String,String> delete(@RequestHeader(value="token")String token,String ids) {
String[] idArr=ids.split(",");
List<String> idList = new ArrayList<String>();
List<EmSecuRecord> emList = new ArrayList<EmSecuRecord>();
for(String id:idArr){
if(id!=null&&!id.equals("")){
idList.add(id);
EmSecuRecord emSecuRecord = emSecuRecordService.get(id);
emList.add(emSecuRecord);
}
}
// 检查是否满足删除条件
Map<String, String> data = deleteRulesUtils.checkBeforeDelete(EmSecuRecord.class, idList);
if ("true".equals(data.get("value"))) {
List<EmSecuRecord> finalList = emSecuRecordService.batchDelete(emList);
if (finalList.size() > 0) {
data.put("result", "删除成功");
} else {
data.put("result", "删除失败");
}
}
return data;
}
// /**
// *
// * updateSecuRecord:(更新事件状态).
// * @param emSecuRecord
// * @return :Map<String,String>
// * @since JDK 1.8
// * @author guanze
// */
// @RequestMapping(value = "updateSecuRecord")
// public Map<String,String> updateSecuRecord(EmSecuRecord emSecuRecord) {
// Map<String,String> data = new HashMap<String,String>();
//
// try {
// LoginUser userInfo = UserServletContext.getUserInfo();
// EmSecuRecord info = emSecuRecordService.get(emSecuRecord.getId());
// info.setStates(emSecuRecord.getStates());
// //info.setProcPerson(userInfo.getUserName());
// emSecuRecordService.save(info);
// data.put("result", "已终止");
// } catch (Exception e) {
//
// e.printStackTrace();
// data.put("result", "终止失败");
// }
// return data;
// }
//
// /**
// * n
// * findNextNodeUserList:(查询user列表).
// * @return :List<CtlUser>
// * @since JDK 1.8
// * @author guanze
// */
// @RequestMapping(value = "/findNextNodeUserList")
// public List<CtlUser> findNextNodeUserList(){
// Map<String, String> map = new HashMap<String, String>();
// map.put("flowCode", "AB");
// map.put("stepPos", "B");
// List<CtlUser> list = ctlUserService.findNextNodeUserList(map);
// return list;
// }
@ApiOperation(value = "根据用户过滤流程实例", notes = "根据用户过滤流程实例")
@ApiImplicitParams({
@ApiImplicitParam(name = "emCode", value = "事件编号", required = false,paramType = "query", dataType = "String"),
})
@RequestMapping(value = "/getListEmSecuRecord",method=RequestMethod.POST)
public @ResponseBody CommonResponse getListEmSecuRecord(
String emCode,
String reportPerson,
String startDate,
String endDate,
LoginUser userInfo,
@RequestHeader(value="token")String token,
@RequestParam(value="pageNo",required = true ,defaultValue = "0" )Integer pageNo,
@RequestParam(value="pageSize",required = true ,defaultValue = "10" )Integer pageSize,
HttpServletRequest request, HttpServletResponse response) throws IOException {
EmSecuRecord emSecuRecord =new EmSecuRecord();
emSecuRecord.setEmCode(emCode);
//emSecuRecord.setReportPerson(reportPerson);
//emSecuRecord.setComCode(userInfo.getComCode());
Map<String, String> map = new HashMap<String, String>();
map.put("flowCode", "AB");
map.put("userCode", userInfo.getUserId());
map.put("comCode", userInfo.getComCode());
Map<String, String> userMap = wfUserRightService.getListsByUser(map);
if (startDate != null && !"".equals(startDate)) {
String sql = userMap.get("sqlMap") + " and a.REPORT_DATETIME >= " + "TO_DATE ('"+startDate +"','yyyy-mm-dd')";
userMap.put("sqlMap",sql);
}
if (endDate != null && !"".equals(endDate)) {
String sql = userMap.get("sqlMap") + " and a.REPORT_DATETIME < " + "TO_DATE ('"+endDate +"','yyyy-mm-dd')+1";
userMap.put("sqlMap",sql);
}
emSecuRecord.setSqlMap(userMap);
Page<EmSecuRecord> page = emSecuRecordService.findSecuRecordPage(new Page<EmSecuRecord>(pageNo, pageSize), emSecuRecord);
for(EmSecuRecord info:page.getList()) {
CtlCodeDet ctlCodeDet = new CtlCodeDet();
ctlCodeDet.setCodeCode(info.getEmCategory());
ctlCodeDet.setCodeType("AbCategory");
CtlCodeDet codeDet = ctlCodeDetService.getCodeDet(ctlCodeDet);
if(codeDet != null) {
info.setEmCategory(codeDet.getCodeName());
}
}
return ResponseUtil.successResponse(page);
}
@ApiOperation(value = "安保事件查询分页", notes = "安保事件查询分页")
@ApiImplicitParams({
@ApiImplicitParam(name = "emCode", value = "事件编号", required = false,paramType = "query", dataType = "String"),
})
@RequestMapping(value = "/getListEmSecuRecordSkan",method=RequestMethod.POST )
public @ResponseBody CommonResponse getListEmSecuRecordSkan(
String emCode,
String reportPerson,
String startDate,
String endDate,
@RequestHeader(value="token")String token,
@RequestParam(value="pageNo",required = true ,defaultValue = "0" )Integer pageNo,
@RequestParam(value="pageSize",required = true ,defaultValue = "10" )Integer pageSize,
HttpServletRequest request, HttpServletResponse response) throws IOException {
EmSecuRecord emSecuRecord =new EmSecuRecord();
emSecuRecord.setEmCode(emCode);
emSecuRecord.setReportPerson(reportPerson);
Map<String,String> sqlMap = new HashMap<String,String>();
String sql="a.states IN ('3','4')";
if (startDate != null && !"".equals(startDate)) {
sql += " and a.REPORT_DATETIME >= " + "TO_DATE ('"+startDate +"','yyyy-mm-dd')";
}
if (endDate != null && !"".equals(endDate)) {
sql += " and a.REPORT_DATETIME < " + "TO_DATE ('"+endDate +"','yyyy-mm-dd')+1";
}
sqlMap.put("sqlMap", sql);
emSecuRecord.setSqlMap(sqlMap);
Page<EmSecuRecord> page = emSecuRecordService.findPage(new Page<EmSecuRecord>(pageNo, pageSize), emSecuRecord);
for(EmSecuRecord info:page.getList()) {
CtlCodeDet ctlCodeDet = new CtlCodeDet();
ctlCodeDet.setCodeCode(info.getEmCategory());
ctlCodeDet.setCodeType("AbCategory");
CtlCodeDet codeDet = ctlCodeDetService.getCodeDet(ctlCodeDet);
if(codeDet != null) {
info.setEmCategory(codeDet.getCodeName());
}
}
return ResponseUtil.successResponse(page);
}
@ApiOperation(value = "根据id查询安保事件", notes = "根据id查询安保事件")
@RequestMapping(value = "/findByIdEmSecuRecord",method=RequestMethod.POST )
public @ResponseBody EmSecuRecord findByIdEmSecuRecord(EmSecuRecord emSecuRecord,@RequestHeader(value="token")String token,HttpServletRequest request, HttpServletResponse response) {
return emSecuRecordService.get(emSecuRecord.getId());
}
@ApiOperation(value = "安保事件", notes = "安保事件")
@RequestMapping(value = "/findNextCodeEmSecuRecord",method=RequestMethod.POST )
public @ResponseBody EmSecuRecord findNextCodeEmSecuRecord(HttpServletRequest request,@RequestHeader(value="token")String token, HttpServletResponse response) {
return emSecuRecordService.findNextCodeEmSecuRecord();
}
/**
*
* getEmSecuRecord:(查询安保事件).
* @param emSecuRecord
* @param request
* @param response
* @return
* @since JDK 1.8
* @author guanze
*/
@ApiOperation(value = "查询安保事件", notes = "查询安保事件")
@RequestMapping(value = "/getEmSecuRecord",method=RequestMethod.POST )
public @ResponseBody EmSecuRecordVo getEmSecuRecord(
@RequestBody EmSecuRecordVo emSecuRecord,
@RequestHeader(value="token")String token,
HttpServletRequest request,
HttpServletResponse response
) {
EmSecuRecordVo emSecuRecordVo = emSecuRecordService.getEmSecuRecord(emSecuRecord);
if (emSecuRecordVo != null) {
CtlCodeDet ctlCodeDet = new CtlCodeDet();
ctlCodeDet.setCodeCode(emSecuRecordVo.getEmCategory());
ctlCodeDet.setCodeType("AbCategory");
CtlCodeDet codeDet = ctlCodeDetService.getCodeDet(ctlCodeDet);
if(codeDet != null) {
emSecuRecordVo.setEmCategory(codeDet.getCodeName());
}
CtlAttachfile file = new CtlAttachfile();
file.setMasterFileId(emSecuRecordVo.getId());
List<CtlAttachfile> files = ctlAttachfileService.findList(file);
if (files != null && files.size() > 0) {
emSecuRecordVo.setFiles(files);
}
}
return emSecuRecordVo;
}
@ApiOperation(value = "查询安保事件列表", notes = "查询安保事件列表")
@RequestMapping(value = "/getEmSecuRecordList",method=RequestMethod.POST )
public @ResponseBody List<EmSecuRecord> getEmSecuRecordList(
@RequestBody EmSecuRecord emSecuRecord,
@RequestHeader(value="token")String token,
String startDate,
String endDate,
HttpServletRequest request,
HttpServletResponse response
){
Map<String,String> sqlMap = new HashMap<String,String>();
String sql="1=1";
if (startDate != null && !"".equals(startDate)) {
startDate = startDate + " 00:00:00";
sql += " and a.REPORT_DATETIME >= " + "TO_DATE ('"+startDate +"','yyyy-mm-dd hh24:mi:ss')";
}
if (endDate != null && !"".equals(endDate)) {
endDate = endDate + " 23:59:59";
sql += " and a.REPORT_DATETIME <= " + "TO_DATE ('"+endDate +"','yyyy-mm-dd hh24:mi:ss')";
}
sqlMap.put("sqlMap", sql);
emSecuRecord.setSqlMap(sqlMap);
List<EmSecuRecord> list = emSecuRecordService.findList(emSecuRecord);
return list;
}
} | true |
3c7e2b919c8d729219ed62efd61acbb51b8b6671 | Java | sdgdsffdsfff/wagon | /wagon-console/src/main/java/com/youzan/wagon/console/bean/DepartmentDetail.java | UTF-8 | 2,582 | 2.21875 | 2 | [
"Apache-2.0"
] | permissive | package com.youzan.wagon.console.bean;
import java.util.List;
/**
* @author wangguofeng since 2016年6月27日 上午10:32:03
*/
public class DepartmentDetail {
private String id;
private String leader_id;
private String level;
private String name;
private String user_count;
private String is_leaf;
private String hrbp_id;
private String parent_id;
private UserSimple leader_detail;
private UserSimple hrbp_detail;
private List<UserSimple> users;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public List<UserSimple> getUsers() {
return users;
}
public void setUsers(List<UserSimple> users) {
this.users = users;
}
public String getLeader_id() {
return leader_id;
}
public void setLeader_id(String leader_id) {
this.leader_id = leader_id;
}
public String getLevel() {
return level;
}
public void setLevel(String level) {
this.level = level;
}
public UserSimple getLeader_detail() {
return leader_detail;
}
public void setLeader_detail(UserSimple leader_detail) {
this.leader_detail = leader_detail;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getUser_count() {
return user_count;
}
public void setUser_count(String user_count) {
this.user_count = user_count;
}
public String getIs_leaf() {
return is_leaf;
}
public void setIs_leaf(String is_leaf) {
this.is_leaf = is_leaf;
}
public UserSimple getHrbp_detail() {
return hrbp_detail;
}
public void setHrbp_detail(UserSimple hrbp_detail) {
this.hrbp_detail = hrbp_detail;
}
public String getHrbp_id() {
return hrbp_id;
}
public void setHrbp_id(String hrbp_id) {
this.hrbp_id = hrbp_id;
}
public String getParent_id() {
return parent_id;
}
public void setParent_id(String parent_id) {
this.parent_id = parent_id;
}
@Override
public String toString() {
return "ClassPojo [id = " + id + ", users = " + users + ", leader_id = " + leader_id + ", level = " + level + ", leader_detail = " + leader_detail + ", name = " + name + ", user_count = " + user_count + ", is_leaf = " + is_leaf + ", hrbp_detail = " + hrbp_detail + ", hrbp_id = " + hrbp_id + ", parent_id = " + parent_id + "]";
}
}
| true |
9e620e7601e08948b9b05e76abeba742f121283d | Java | bmeridet/Java | /MavenTest/src/main/java/maventest/student.java | UTF-8 | 923 | 3.328125 | 3 | [] | no_license | package maventest;
public class student {
private int studentID;
private String studentName;
private String studentMajor;
public student(int id, String name, String major)
{
studentID = id;
studentName = name;
studentMajor = major;
}
// od getters and setters
public void SetID(int id)
{
studentID = id;
}
public int GetID()
{
return studentID;
}
public void SetName(String name)
{
studentName = name;
}
public String GetName()
{
return studentName;
}
public void SetMajor(String major)
{
studentMajor = major;
}
public String GetMajor()
{
return studentMajor;
}
public void Display()
{
System.out.println(studentID + ": " + studentName + " " + studentMajor);
}
}
| true |
79388611f98a5730c6bd79fe70cbc8a1ce2e1452 | Java | Kum4r4n/Java-for-beginners | /studentMarks/src/studentMarks/calculation.java | UTF-8 | 805 | 2.6875 | 3 | [] | no_license | package studentMarks;
import java.util.Scanner;
//import java.util.Scanner;
public class calculation {
static int total=0;
public static int[][] getmarks() {
int[][] amarks=new int[3][6];
for (int r = 0; r < 3; r++) {
for (int c = 0; c < 6; c++) {
Scanner getmark = new Scanner(System.in);
System.out.println("Enter subject "+(c + 1)+" mark :- ");
int a = getmark.nextInt();
amarks[r][c] = a;
}
}
return amarks;
}
public static int totalmarkks(int[][] amarks) {
for(int x=0; x<3; x++) {
for(int y=0; y<6; y++) {
total=total+amarks[x][y];
}
System.out.println((x+1)+" student total is "+total);
total=0;
}
return total;
}
/*public void summary() {
total=0;
}*/
}
| true |
dbac2799b564849935e9dee646ae505949408887 | Java | guzhigang001/YotuComponent | /app/src/main/java/com/example/ggxiaozhi/yotucomponent/module/course/CourseCommentValue.java | UTF-8 | 515 | 1.710938 | 2 | [
"Apache-2.0"
] | permissive | package com.example.ggxiaozhi.yotucomponent.module.course;
import com.example.ggxiaozhi.yotucomponent.user.BaseModel;
/**
* 工程名 : YotuComponent
* 包名 : com.example.ggxiaozhi.yotucomponent.module.course
* 作者名 : 志先生_
* 日期 : 2017/10/21
* 功能 :详情页列表数据
*/
public class CourseCommentValue extends BaseModel {
public String text;
public String name;
public String logo;
public int type;
public String userId; //评论所属用户ID
}
| true |
8ba3ff14b5fd2d647183f0572fa83621531b6448 | Java | niks36/hands-on | /src/stringmanipulation/RemoveConsecutiveChar.java | UTF-8 | 1,541 | 4.09375 | 4 | [] | no_license | package stringmanipulation;
/**
* Remove Consecutive characters from string.
*
* Input: ahfijgwdexyz
* Output: ah
* 1.Remove consecutive char i,j -> ahfgwdexyz
* 2.Remove consecutive char f,g -> ahwdexyz
* 3.Remove consecutive char d,w -> ahwxyz
* 4.Remove consecutive char w,x,y,z -> ah
*
* Input: abcdefgh
* Output: empty
*
* Input: aherks
* Output: aherks
*/
public class RemoveConsecutiveChar {
public static void main(String[] args) {
String s = "aghijwzyz";
char[] charArr = s.toCharArray();
boolean bFound = true;
while (bFound) {
bFound = false;
for (int i = 0; i < charArr.length; i++) {
int currentIndex = i;
while (charArr.length > i + 1 && checkForConsecutive(charArr[i], charArr[i + 1])) {
i = i + 1;
}
if (currentIndex != i) {
bFound = true;
char[] newArr = new char[charArr.length - (i + 1 - currentIndex)];
System.arraycopy(charArr, 0, newArr, 0, currentIndex);
System.arraycopy(charArr, i + 1, newArr, currentIndex, charArr.length - i - 1);
charArr = newArr;
break;
}
}
}
for (int i = 0; i < charArr.length; i++) {
System.out.print(charArr[i]);
}
}
private static boolean checkForConsecutive(int current, int next) {
return next - current == 1;
}
}
| true |
b6b67518472793218a73101575a45e51145f197a | Java | MitchellRodio/Challenges | /InsertionSort.java | UTF-8 | 592 | 3.5625 | 4 | [] | no_license | class insertionSort {
public static void Insertion(int [] sort_array){
for(int i=0; i < sort_array.length; ++i){
int j = i;
while(j > 0 && sort_array[j-1] > sort_array[j]){
int key = sort_arr[j];
sort_array[j] = sort_array[j-1];
sort_array[j-1] = key;
j = j - 1;
}
}
}
public static void main( String args[] ) {
int [] array = {9, 24, 13, 5, 9};
Insertion(array);
for(int i=0; i < array.length; ++i){
System.out.print(array[i] + " ");
}
}
}
| true |
598e810b95d91c964ea40316de9e858f9365d6a4 | Java | aheadlcx/analyzeApk | /budejie/sources/com/baidu/mobads/g/g$b.java | UTF-8 | 234 | 1.664063 | 2 | [] | no_license | package com.baidu.mobads.g;
import com.baidu.mobads.utils.XAdSDKFoundationFacade;
protected final class g$b extends Exception {
public g$b(String str) {
XAdSDKFoundationFacade.getInstance().getAdLogger().e(str);
}
}
| true |
09a4220297a54a77e292e04a23b0eee24cbd1891 | Java | upadhyaysabyasachi/backend-play-activator-java | /app/actors/registrationTokenUpdateActor.java | UTF-8 | 2,419 | 2.40625 | 2 | [
"Apache-2.0"
] | permissive | package actors;
import akka.actor.UntypedActor;
import com.jolbox.bonecp.BoneCP;
import models.DBConnectionPool;
import models.UserWithDevice;
import org.json.simple.JSONObject;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
/**
* Created by sabyasachi.upadhyay on 02/09/16.
*/
public class registrationTokenUpdateActor extends UntypedActor {
public String insertQueryDeviceRegistrationBuilder(UserWithDevice user) {
return "INSERT INTO user_sessions(userid,device_token,login_status) values(" + user.uid + "," + user.device_id + ","+"'yes')";
}
@Override
public void onReceive(Object message) throws Throwable {
//message contains the userid and the registrationToken
if (message instanceof UserWithDevice) {
{
BoneCP pool = DBConnectionPool.getConnectionPool();
Connection conn = pool.getConnection();
try {
UserWithDevice user = (UserWithDevice) message;
if (conn != null) {
System.out.println("Connection successful inside registrationTokenActor!");
Statement stmt = conn.createStatement();
System.out.println("query is " + insertQueryDeviceRegistrationBuilder(user));
//ResultSet rs = stmt.executeQuery(insertQueryRegisterBuilder(user));
//System.out.println("query is " + insertQueryRegisterBuilder(user));
int a = stmt.executeUpdate(insertQueryDeviceRegistrationBuilder(user));
//PreparedStatement ps = conn.prepareStatement(insertQueryRegisterBuilder(user),
// Statement.RETURN_GENERATED_KEYS);
//int a = ps.executeUpdate(); // do something with the connection.
//ResultSet key = ps.getGeneratedKeys();
JSONObject obj = new JSONObject();
obj.put("status", "inserted");
getSender().tell(obj.toJSONString(), self());
}
} catch (SQLException sqe) {
sqe.printStackTrace();
} finally {
if (conn != null) {
conn.close();
}
}
}
}
}
}
| true |
d5548bf59fb3f831d36adb23112369e8297446b3 | Java | iamflorencejay/drongo-lbc | /src/main/java/com/sparrowwallet/drongo/policy/PolicyException.java | UTF-8 | 582 | 2.171875 | 2 | [
"Apache-2.0"
] | permissive | package com.sparrowwallet.drongo.policy;
public class PolicyException extends RuntimeException {
public PolicyException() {
}
public PolicyException(String message) {
super(message);
}
public PolicyException(String message, Throwable cause) {
super(message, cause);
}
public PolicyException(Throwable cause) {
super(cause);
}
public PolicyException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
}
| true |
bfec6d2c4d25e06269dde8da779e4cba55cb4d42 | Java | khoiboo/Central_Server | /simple-service/src/main/java/com/example/getPublicResult.java | UTF-8 | 3,977 | 2.09375 | 2 | [] | no_license | package com.example;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.joda.time.DateTime;
import org.slf4j.LoggerFactory;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.mongodb.BasicDBList;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.MongoClient;
import GeoC_QuestionHierarchy.Answer;
import GeoC_QuestionHierarchy.Answer_Deserializer;
import GeoC_QuestionHierarchy.BaseQuestion_Deserializer;
import GeoC_QuestionHierarchy.Base_Question;
import GeoC_QuestionHierarchy.Branch;
import GeoC_QuestionHierarchy.Branch_Deserializer;
import GeoC_QuestionHierarchy.Campaign;
import GeoC_QuestionHierarchy.Campaign_Deserializer;
import GeoC_QuestionHierarchy.DateTimeConverter;
import GeoC_QuestionHierarchy.Participant;
import GeoC_QuestionHierarchy.Workflow_Element;
import GeoC_QuestionHierarchy.Workflow_Element_Deserializer;
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.LoggerContext;
@Path("getPublicResult")
public class getPublicResult {
static String campaignStorage = "campaignStorage";
static String campaign_List = "campaign_List";
@GET
@Produces(MediaType.TEXT_PLAIN)
public Response getIt(@QueryParam("userID") String userID) throws IOException {
Record_ViewPublicResult update_ViewResult = new Record_ViewPublicResult(userID);
update_ViewResult.start();
//Disable logging from MongoDB
LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();
Logger rootLogger = loggerContext.getLogger("org.mongodb.driver");
rootLogger.setLevel(Level.OFF);
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(Answer.class, new Answer_Deserializer());
gsonBuilder.registerTypeAdapter(Campaign.class, new Campaign_Deserializer());
gsonBuilder.registerTypeAdapter(DateTime.class, new DateTimeConverter());
//gsonBuilder.registerTypeAdapter(PoI.class, new PoI_Deserializer());
final Gson gson = gsonBuilder.create();
ArrayList<Campaign> reply = new ArrayList();
MongoClient mongo = new MongoClient("localhost", 27017);
DB db = mongo.getDB(campaignStorage);
DBCollection table = db.getCollection(campaign_List);
ArrayList<String> arrayAllCampaign = new ArrayList();
BasicDBObject query = new BasicDBObject();
BasicDBObject field = new BasicDBObject();
field.put("campaign_Config", 1);
DBCursor cursor = table.find(query,field);
while (cursor.hasNext()) {
BasicDBObject obj = (BasicDBObject) cursor.next();
arrayAllCampaign.add(obj.getString("campaign_Config"));
}
System.out.println("The size of array containing all campaign is " + arrayAllCampaign.size());
for (int i=0;i< arrayAllCampaign.size();i++)
{
Campaign cam_obj = gson.fromJson(arrayAllCampaign.get(i), Campaign.class);
if (cam_obj.getShowResultBoolean() == true)
reply.add(cam_obj);
}
System.out.println("The number of campaigns with public results is " + reply.size());
return Response.status(200).entity(gson.toJson(reply)).build();
}
}
class Record_ViewPublicResult extends Thread {
String userID;
public Record_ViewPublicResult(String userID) { this.userID = userID; }
@Override
public void run() {
MongoClient mongo = new MongoClient("localhost", 27017);
DB db = mongo.getDB("incomingViewPublicResult");
DBCollection table = db.getCollection("requestDetails");
BasicDBObject document = new BasicDBObject();
document.put("userID", userID);
document.put("time", new Date());
table.insert(document);
mongo.close();
}
}
| true |
155796e0968d8591991267df910d7dca1c8183fa | Java | JulianR01/atms | /tm/RatesM/InsertRate/webui/InsertRateCO.java | ISO-8859-2 | 7,893 | 1.71875 | 2 | [] | no_license | /*===========================================================================+
| Copyright (c) 2001, 2005 Oracle Corporation, Redwood Shores, CA, USA |
| All rights reserved. |
+===========================================================================+
| HISTORY |
+===========================================================================*/
package xxgam.oracle.apps.xbol.tm.RatesM.InsertRate.webui;
import oracle.apps.fnd.common.VersionInfo;
import oracle.apps.fnd.framework.webui.OAControllerImpl;
import oracle.apps.fnd.framework.webui.OAPageContext;
import oracle.apps.fnd.framework.webui.beans.OAWebBean;
/*Added libraries*/
import oracle.apps.fnd.framework.OAApplicationModule;
import oracle.jbo.domain.Number;
import oracle.apps.fnd.common.MessageToken;
import oracle.apps.fnd.framework.OAException;
import oracle.apps.fnd.framework.OAViewObject;
import oracle.apps.fnd.framework.webui.OAWebBeanConstants;
import oracle.apps.fnd.framework.webui.beans.layout.OAQueryBean;
import oracle.jbo.domain.Number;
import xxgam.oracle.apps.xbol.tm.RatesM.InsertRate.server.InsertRateAMImpl;
/**
* Controller for ...
*/
public class InsertRateCO extends OAControllerImpl {
public static final String RCS_ID = "$Header$";
public static final boolean RCS_ID_RECORDED =
VersionInfo.recordClassVersion(RCS_ID, "%packagename%");
/**
* Layout and page setup logic for a region.
* @param pageContext the current OA page context
* @param webBean the web bean corresponding to the region
*/
public void processRequest(OAPageContext pageContext, OAWebBean webBean) {
super.processRequest(pageContext, webBean);
System.out.println("*****************************************************Entro a PR");
if (!pageContext.isFormSubmission()) {
OAApplicationModule am = pageContext.getApplicationModule(webBean);
am.invokeMethod("createRecord", null);
System.out.println("Debug 1");
} else
System.out.println("Debug 2");
}
/**
* Procedure to handle form submissions for form elements in
* a region.
* @param pageContext the current OA page context
* @param webBean the web bean corresponding to the region
*/
public void processFormRequest(OAPageContext pageContext,
OAWebBean webBean) {
super.processFormRequest(pageContext, webBean);
// OAApplicationModule am = pageContext.getApplicationModule(webBean);
InsertRateAMImpl am =
(InsertRateAMImpl)pageContext.getApplicationModule(webBean);
OAApplicationModule am1 = pageContext.getApplicationModule(webBean);
// OAQueryBean queryBean = (OAQueryBean)webBean.findChildRecursive("PageLayoutRN");
// queryBean.clearSearchPersistenceCache(pageContext);
if (pageContext.getParameter("Ok") != null) {
// am1.invokeMethod("createRecord", null);
OAViewObject vo = (OAViewObject)am.findViewObject("InsertRateVO1");
// oracle.jbo.domain.Number IdTarifaNum = (oracle.jbo.domain.Number)am.invokeMethod("sequenceapply");
// System.out.println("Id tarifa: " + IdTarifaNum);
// vo.getCurrentRow().setAttribute("IdTarifa",IdTarifaNum);
String StrOrigin =
(String)vo.getCurrentRow().getAttribute("Origin");
System.out.println("Origin " + StrOrigin);
String StrZones = (String)vo.getCurrentRow().getAttribute("RZone");
System.out.println("RZone " + StrZones);
String StrDestination =
(String)vo.getCurrentRow().getAttribute("Destination");
System.out.println("Destination " + StrDestination);
String StrProviderNumber =
(String)vo.getCurrentRow().getAttribute("ProviderNumber");
System.out.println("ProviderNumber " + StrProviderNumber);
String StrProvider =
(String)vo.getCurrentRow().getAttribute("ProviderName");
System.out.println("ProviderName " + StrProvider);
String StrTransportMode =
(String)vo.getCurrentRow().getAttribute("RMode");
System.out.println("TransportMode " + StrTransportMode);
String StrCurrency =
(String)vo.getCurrentRow().getAttribute("Currency");
System.out.println("Currency " + StrCurrency);
oracle.jbo.domain.Number StrRate =
(oracle.jbo.domain.Number)vo.getCurrentRow().getAttribute("Rate");
System.out.println("Rate " + StrRate);
oracle.jbo.domain.Number StrManeuvers =
(oracle.jbo.domain.Number)vo.getCurrentRow().getAttribute("Maneuvers");
System.out.println("Maneuvers " + StrManeuvers);
oracle.jbo.domain.Number StrReparts =
(oracle.jbo.domain.Number)vo.getCurrentRow().getAttribute("Reparts");
System.out.println("Reparts " + StrReparts);
String StrCruce =
(String)vo.getCurrentRow().getAttribute("Intersection");
System.out.println("Cruce " + StrCruce);
oracle.jbo.domain.Date StrDateFrom =
(oracle.jbo.domain.Date)vo.getCurrentRow().getAttribute("DateFrom");
System.out.println("DateFrom " + StrDateFrom);
oracle.jbo.domain.Date StrDateTo =
(oracle.jbo.domain.Date)vo.getCurrentRow().getAttribute("DateTo");
System.out.println("DateTo " + StrDateTo);
String StrDistribution =
(String)vo.getCurrentRow().getAttribute("DistributionType");
System.out.println("Distribution " + StrDistribution);
String StrHyreType =
(String)vo.getCurrentRow().getAttribute("Classification");
System.out.println("Hyretype " + StrHyreType);
String StrType = (String)vo.getCurrentRow().getAttribute("TypeD");
System.out.println("Type " + StrType);
String TypeV = am.RateTypeD(StrType);
System.out.println("TypeV: " + TypeV);
vo.getCurrentRow().setAttribute("TypeV", TypeV);
String strSalida = "";
int check =
am.validateRecord(StrOrigin, StrZones, StrDestination, StrProviderNumber,
StrProvider, StrTransportMode, StrCurrency,
StrRate, StrManeuvers, StrReparts, StrCruce,
StrDateFrom, StrDateTo, StrDistribution,
StrHyreType, StrType, TypeV);
System.out.println("ckeck: " + check);
String WMessage = "Registro duplicado, verifique su informacin.";
if (check > 0) {
throw new OAException(WMessage, OAException.WARNING);
}
System.out.println("StrDateFrom.compareTo(StrDateTo): " +
StrDateTo.compareTo(StrDateFrom));
int x = StrDateTo.compareTo(StrDateFrom);
if (x < 0) {
String WMessage2 = "Verificar el intervalo de fechas dado.";
throw new OAException(WMessage2, OAException.WARNING);
}
am.invokeMethod("apply");
System.out.println("Guardado");
String message = "Registro creado satisfactoriamente.";
throw new OAException(message, OAException.CONFIRMATION);
}
if (pageContext.getParameter("New") != null) {
System.out.println("New pressed");
am1.invokeMethod("createRecord", null);
System.out.println("nuevo registro creado");
}
}
}
| true |
3ef8740670965e412d73a095d31d59515032cdba | Java | AKhafagi/CS-537 | /src/MyMap.java | UTF-8 | 14,235 | 3.109375 | 3 | [] | no_license | //// Just adds a simple AcetateLayer to place a line & points on the
//// map. Mercifully this works if the drawing is done in Java terms,
//// using frame coordinates (pixels). Using an AcetateLayer has the
//// advantage that an AcetateLayer is transparent, and this solves
//// a problem that transparent layers in Java are somewhat tricky
//// to do, e.g. a canvas can not be made transparent. In addition,
//// the line is drawn in stages by using a thread. The thread is
//// wise and necessary. In this version, the acetate layers
//// are removed, within the loop, so they do not accumulate
//// and slow things down. The loop should work with two arbitrary
//// points! Those points are parameters to the thread code.
//
//import com.esri.mo2.cs.geom.Point;
//import com.esri.mo2.ui.bean.*;
//import com.esri.mo2.ui.tb.*;
//
//import javax.swing.*;
//import java.awt.*;
//import java.awt.event.*;
//import java.awt.geom.*;
//
//public class MyMap extends JFrame {
// private java.awt.Point start;
// private java.awt.Point end;
// private java.awt.Point mid;
// private boolean drawTriangle = false;
// static Map map = new Map();
// private Layer layer = new Layer();
// private Layer layer2 = new Layer();
// private Toc toc = new Toc();
// private String s1 = "./esri/MOJ20/Samples/Data/World/country.shp";
// private String s2 = "./esri/MOJ20/Samples/Data/World/cities.shp";
// private ZoomPanToolBar zptb = new ZoomPanToolBar();
// private SelectionToolBar stb = new SelectionToolBar();
// private JPanel jpanel = new JPanel();
// private JButton getCoordinates = new JButton("Input Coordinates");
// private JButton draw = new JButton("Draw");
// private JButton help = new JButton("Help");
// private ActionListener getCoordinatesListener;
// private ActionListener drawListener;
// private ActionListener helpPopup;
//
//
// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// /*
// * Helper method to convert a World Point to a pixel on the screen
// * input: worldPoint: a Point that holds the world point to convert to a pixel on the screen.
// * returns: a Java.awt.Point that has the x, and y pixel on the screen.
// * */
// private java.awt.Point transformWorldPointToPixel(Point worldPoint) {
// return map.transformWorldToPixel(worldPoint.x, worldPoint.y);
// }
//
// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// private MyMap() {
// super("World Map");
// this.setBounds(80, 80, 1024, 1024);
// zptb.setMap(map);
// stb.setMap(map);
// // listens to changes on the get coordinates button.
// getCoordinatesListener = ae -> {
// Point startPoint, endPoint, midPoint;
// double x1, x2, x3, y1, y2, y3;
// x1 = x2 = x3 = y1 = y2 = y3 = 0.0;
// String prompt = "Please enter a set of coordinates separated by a comma for example \"37 N,65 W, 21 N,42 W\"\n"
// + "will be 2 sets of coordinates \'37 N\' is one part of the set and \'65 W\' is the second part\n" +
// "you can also enter 3 sets of coordinates to draw a triangle";
// String input;
// String[] inputs;
// do {
// input = JOptionPane.showInputDialog(this, prompt, "Please Enter Coordinates", JOptionPane.QUESTION_MESSAGE);
// if (input == null) {
// JOptionPane.showMessageDialog(this, "Input is required, please try again");
// continue;
// }
// inputs = input.trim().split(",");
// if(inputs.length ==1 && inputs[0].isEmpty()){
// JOptionPane.showMessageDialog(this, "No coordinates have been entered the program will now exit!");
// try {
// Thread.sleep(500);
// } catch (InterruptedException e) {
// e.printStackTrace();
// } finally {
// System.exit(0);
// }
// }
// else if (inputs.length < 4) {
// JOptionPane.showMessageDialog(this, "Incorrect number of coordinates please try again");
// continue;
// }
// boolean error = false;
// // converts S,and W to negative for all inputs.
// for (int i = 0; i < inputs.length; i++) {
// String[] coordinate = inputs[i].trim().split(" ", -1);
// if (coordinate.length != 2) {
// JOptionPane.showMessageDialog(this, "Coordinates entered in wrong format please try again");
// error = true;
// break;
// }
// switch (i) {
//
// case 0:
// x1 = Double.parseDouble(coordinate[0]);
// if (coordinate[1].toUpperCase().equals("S")) {
// x1 *= -1;
// }
// break;
//
// case 1:
// y1 = Double.parseDouble(coordinate[0]);
// if (coordinate[1].toUpperCase().equals("W")) {
// y1 *= -1;
// }
// break;
// case 2:
// x2 = Double.parseDouble(coordinate[0]);
// if (coordinate[1].toUpperCase().equals("S")) {
// x2 *= -1;
// }
// break;
// case 3:
// y2 = Double.parseDouble(coordinate[0]);
// if (coordinate[1].toUpperCase().equals("W")) {
// y2 *= -1;
// }
// break;
// case 4:
// x3 = Double.parseDouble(coordinate[0]);
// if (coordinate[1].toUpperCase().equals("S")) {
// x3 *= -1;
// }
// break;
// case 5:
// y3 = Double.parseDouble(coordinate[0]);
// if (coordinate[1].toUpperCase().equals("W")) {
// y3 *= -1;
// }
// break;
//
// }
// }
// if (!error)
// break;
// } while (true);
// if (inputs.length > 4) {
// startPoint = new Point(y1, x1);
// midPoint = new Point(y2, x2);
// endPoint = new Point(y3, x3);
// start = transformWorldPointToPixel(startPoint);
// end = transformWorldPointToPixel(endPoint);
// mid = transformWorldPointToPixel(midPoint);
// drawTriangle = true;
// draw.setText("Draw Triangle");
// JOptionPane.showMessageDialog(this, "Three Coordinates entered successfully you can now draw a triangle");
// } else {
// startPoint = new Point(y1, x1);
// endPoint = new Point(y2, x2);
// start = transformWorldPointToPixel(startPoint);
// end = transformWorldPointToPixel(endPoint);
// drawTriangle = false;
// draw.setText("Draw Line");
// JOptionPane.showMessageDialog(this, "Two Coordinates entered successfully");
// }
//
// getCoordinates.setEnabled(false);
// draw.setEnabled(true);
// };
// drawListener = ae -> {
// Flash flash;
// if (drawTriangle) {
// flash = new Flash(start.x, start.y, mid.x, mid.y, end.x, end.y, this);
// } else
// flash = new Flash(start.x, start.y, end.x, end.y, this);
// flash.start();
// };
//
//
// toc.setMap(map);
// helpPopup = ae -> {
// String message = "To use this program first click the button \"Enter Coordinates\" \n then click the button \"Draw\"\n" +
// "1) You can draw a line by inputting two coordinates.\n"+
// "The form of the coordinates should be latitude degree with direction separated by a space and \n"+
// "and the longitude degree with direction sperated by a space. Every coordinate should be delimted by a comma\n"+
// "2) You can draw a triangle by inputting three world coordinates";
// JOptionPane.showMessageDialog(this.getComponent(0), message);
// };
// draw.addActionListener(drawListener);
// draw.setEnabled(false);
// getCoordinates.addActionListener(getCoordinatesListener);
// help.addActionListener(helpPopup);
// jpanel.add(zptb);
// jpanel.add(stb);
// jpanel.add(getCoordinates);
// jpanel.add(draw);
// jpanel.add(help);
// getContentPane().add(map, BorderLayout.CENTER);
// getContentPane().add(jpanel, BorderLayout.NORTH);
// addShapefileToMap(layer, s1);
// addShapefileToMap(layer2, s2);
// getContentPane().add(toc, BorderLayout.WEST);
// }
//
// private void addShapefileToMap(Layer layer, String s) {
// layer.setDataset("0;" + s);
// map.add(layer);
//
// }
//
// public static void main(String[] args) {
// MyMap qstart = new MyMap();
// qstart.addWindowListener(new WindowAdapter() {
// public void windowClosing(WindowEvent e) {
// JOptionPane.showMessageDialog(qstart, "Thanks for using this program Good Bye!");
// System.exit(0);
// }
// });
// qstart.setVisible(true);
// }
//}
//
//class Flash extends Thread {
// private AcetateLayer acetLayer = new AcetateLayer();
// private double x1;
// private double y1;
// private double x2;
// private double y2;
// private double x3;
// private double y3;
// private boolean drawTriangle;
// private JFrame frame;
//
//
// Flash(double x11, double y11, double x22, double y22, JFrame f) {
// x1 = x11;
// y1 = y11;
// x2 = x22;
// y2 = y22;
// this.drawTriangle = false;
// this.frame = f;
// }
//
// Flash(double x11, double y11, double x22, double y22, double x33, double y33, JFrame f) {
// x1 = x11;
// y1 = y11;
// x2 = x22;
// y2 = y22;
// x3 = x33;
// y3 = y33;
// this.drawTriangle = true;
// this.frame = f;
// }
//
//
// public void run() {
// if (drawTriangle) {
// for (int i = 0; i < 21; i++) {
// try {
// Thread.sleep(300);
// final int j = i;
// if (acetLayer != null) MyMap.map.remove(acetLayer);
// acetLayer = new AcetateLayer() {
// public void paintComponent(java.awt.Graphics g) {
// java.awt.Graphics2D g2d = (java.awt.Graphics2D) g;
// // Line2D.Double line = new Line2D.Double(x1,y1,x2,y2);
// Line2D.Double line = new Line2D.Double(x1, y1, x1 + j * (x2 - x1) / 20.0, y1 + j * (y2 - y1) / 20.0);
// Line2D.Double line2 = new Line2D.Double(x2, y2, x2 + j * (x3 - x2) / 20.0, y2 + j * (y3 - y2) / 20.0);
// Line2D.Double line3 = new Line2D.Double(x3, y3, x3 + j * (x1 - x3) / 20.0, y3 + j * (y1 - y3) / 20.0);
// g2d.setColor(new Color(250, 23, 0));
// g2d.draw(line);
// g2d.draw(line2);
// g2d.draw(line3);
// g2d.setColor(new Color(0, 42, 250));
// g2d.fillOval((int) x1, (int) y1, 5, 5);
// g2d.fillOval((int) x2, (int) y2, 5, 5);
// g2d.fillOval((int) x3, (int) y3, 5, 5);
// }
// };
// acetLayer.setMap(MyMap.map);
// MyMap.map.add(acetLayer);
// } catch (Exception ignored) {
//
// }
// }
// JOptionPane.showMessageDialog(frame, "The Triangle has been drawn");
// System.exit(0);
// } else {
// for (int i = 0; i < 21; i++) {
// try {
// Thread.sleep(300);
// final int j = i;
// if (acetLayer != null) MyMap.map.remove(acetLayer);
// acetLayer = new AcetateLayer() {
// public void paintComponent(java.awt.Graphics g) {
// java.awt.Graphics2D g2d = (java.awt.Graphics2D) g;
// // Line2D.Double line = new Line2D.Double(x1,y1,x2,y2);
// Line2D.Double line = new Line2D.Double(x1, y1, x1 + j * (x2 - x1) / 20.0, y1 + j * (y2 - y1) / 20.0);
// g2d.setColor(new Color(250, 23, 0));
// g2d.draw(line);
// g2d.setColor(new Color(41, 0, 250));
// g2d.fillOval((int) x1, (int) y1, 5, 5);
// g2d.fillOval((int) x2, (int) y2, 5, 5);
// }
// };
// acetLayer.setMap(MyMap.map);
// MyMap.map.add(acetLayer);
// } catch (Exception ignored) {
// }
// }
// JOptionPane.showMessageDialog(frame, "The Line has been drawn");
// System.exit(0);
// }
// }
//}
//
| true |
22eb2298083ff732047f1b37297a3af8b1939fef | Java | dmc-uilabs/dmcrest | /src/main/java/org/dmc/services/projects/ProjectCreateRequest.java | UTF-8 | 2,296 | 2.25 | 2 | [
"MIT"
] | permissive | package org.dmc.services.projects;
//import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
// JSON sent by frontend as of 10-Mar-2016
// {
// description: "adfa"
// dueDate: "1457413200000"
// featureImage: {thumbnail: "/images/project_relay_controller.png", large: "/images/project_relay_controller.png"}
// projectManager: "DMC member"
// title: "cathy3"
// type: "private"
// }
public class ProjectCreateRequest {
private String title = null;
private String description = null;
private String projectType = null;
private long dueDate = 0;
private int createdOn = 0;
private String approvalOption = null;
// @JsonCreator
// public ProjectCreateRequest(@JsonProperty("name") String name, @JsonProperty("description") String description)
// {
// this.name = name;
// this.description = description;
// }
public ProjectCreateRequest() {
}
@JsonProperty("title")
public String getTitle(){
return title;
}
@JsonProperty("title")
public void setTitle(String value){
title = value;
}
@JsonProperty("description")
public String getDescription(){
return description;
}
@JsonProperty("description")
public void setDescription(String value){
description = value;
}
@JsonProperty("dueDate")
public long getDueDate(){
return dueDate;
}
@JsonProperty("dueDate")
public void setDueDate(long value){
dueDate = value;
}
@JsonProperty("createdOn")
public int getCreatedOn() { return createdOn; }
@JsonProperty("createdOn")
public void setCreatedOn(int createdOn) { this.createdOn = createdOn; }
@JsonProperty("type")
public String getProjectType(){
return projectType;
}
@JsonProperty("type")
public void setProjectType(String value){
projectType = value;
}
@JsonProperty("approvalOption")
public String getApprovalOption() {
return approvalOption;
}
@JsonProperty("approvalOption")
public void setApprovalOption(String value) {
approvalOption = value;
}
@Override
public String toString() {
ObjectMapper mapper = new ObjectMapper();
try {
return mapper.writeValueAsString(this);
} catch (JsonProcessingException e) {}
return null;
}
}
| true |
ce1fba3a7baea6bcddae7034f9657b5e65fc9d3f | Java | liziGaoLi/MenCarsTrajectory | /app/src/main/java/com/zhhl/analysis/di/module/PersonTrajectoryAnalysisModule.java | UTF-8 | 2,165 | 2.171875 | 2 | [] | no_license | package com.zhhl.analysis.di.module;
import com.google.gson.Gson;
import com.zhhl.analysis.common.OriginApp;
import com.zhhl.analysis.di.ActivityScope;
import com.zhhl.analysis.mvp.contacts.PersonTrajectoryAnalysisContract;
import com.zhhl.analysis.mvp.model.PersonTrajectoryAnalysisModel;
import com.zhhl.analysis.net.IModel;
import com.zhhl.analysis.net.ITrajectoryAnalysis;
import com.zhhl.analysis.net.proxy.ITrajectoryStaticProxy;
import dagger.Module;
import dagger.Provides;
/**
* 通过Template生成对应页面的MVP和Dagger代码,请注意输入框中输入的名字必须相同
* 由于每个项目包结构都不一定相同,所以每生成一个文件需要自己导入import包名,可以在设置中设置自动导入包名
* 请在对应包下按以下顺序生成对应代码,Contract->Model->Presenter->Activity->Module->Component
* 因为生成Activity时,Module和Component还没生成,但是Activity中有它们的引用,所以会报错,但是不用理会
* 继续将Module和Component生成完后,编译一下项目再回到Activity,按提示修改一个方法名即可
* 如果想生成Fragment的相关文件,则将上面构建顺序中的Activity换为Fragment,并将Component中inject方法的参数改为此Fragment
*/
/**
* Created by miao on 2019/1/17.
*/
@Module
public class PersonTrajectoryAnalysisModule {
private final PersonTrajectoryAnalysisContract.View view;
/**
* 构建PersonTrajectoryAnalysisModule时,将View的实现类传进来,这样就可以提供View的实现类给presenter
*
* @param view contract
*/
public PersonTrajectoryAnalysisModule(PersonTrajectoryAnalysisContract.View view) {
this.view = view;
}
@ActivityScope
@Provides
PersonTrajectoryAnalysisContract.View providePersonTrajectoryAnalysisView() {
return this.view;
}
@ActivityScope
@Provides
PersonTrajectoryAnalysisContract.Model providePersonTrajectoryAnalysisModel(Gson gson, OriginApp application, ITrajectoryAnalysis iWx, IModel iMd) {
return new PersonTrajectoryAnalysisModel(application, gson, (iWx), new ITrajectoryStaticProxy(iMd));
}
} | true |