text
stringlengths 10
2.72M
|
|---|
package com.itheima.controller;
/**
* @Auther: wyan
* @Date: 2019/1/6 12:03
* @Description:
*/
public class LeftController {
}
|
package org.gaoshin.openflier.model;
import net.edzard.kinetic.Colour;
import net.edzard.kinetic.Shadow;
import net.edzard.kinetic.Shape.LineJoin;
public class Fshape extends Fnode {
private Colour stroke;
private double strokeWidth;
private LineJoin lineJoin;
private Shadow shadow;
public Colour getStroke() {
return stroke;
}
public void setStroke(Colour stroke) {
this.stroke = stroke;
}
public double getStrokeWidth() {
return strokeWidth;
}
public void setStrokeWidth(double strokeWidth) {
this.strokeWidth = strokeWidth;
}
public LineJoin getLineJoin() {
return lineJoin;
}
public void setLineJoin(LineJoin lineJoin) {
this.lineJoin = lineJoin;
}
public Shadow getShadow() {
return shadow;
}
public void setShadow(Shadow shadow) {
this.shadow = shadow;
}
}
|
package com.capgemini.service;
import java.util.List;
import com.capgemini.entity.Donation;
import com.capgemini.entity.Donor;
import com.capgemini.exception.NoDonationFoundException;
import com.capgemini.exception.UniqueConstraintViolationException;
public interface DonorService {
public boolean addDonor(Donor donor) throws UniqueConstraintViolationException;
public boolean addDonation(Donation donation);
public List<Donation> findDonation() throws NoDonationFoundException;
}
|
package domain;
import java.util.Collection;
import java.util.Date;
import javax.persistence.Access;
import javax.persistence.AccessType;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.Index;
import javax.persistence.ManyToMany;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.validation.Valid;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Past;
import org.hibernate.validator.constraints.NotBlank;
import org.hibernate.validator.constraints.URL;
import org.springframework.format.annotation.DateTimeFormat;
@Entity
@Access(AccessType.PROPERTY)
@Table(indexes = {
@Index(columnList = "relationshipEngage"), @Index(columnList = "banned")
})
public class Chorbi extends Actor {
// Constructors -----------------------------------------------------------
public Chorbi() {
super();
}
// Attributes -------------------------------------------------------------
private String picture;
private String description;
private Genre genre;
private Boolean banned;
private Date birthDate;
private RelationshipType relationshipEngage;
private Coordinates coordinates;
private Date lastFeeDate;
private Double fee;
@NotBlank
@URL
public String getPicture() {
return this.picture;
}
public void setPicture(final String picture) {
this.picture = picture;
}
@NotBlank
public String getDescription() {
return this.description;
}
public void setDescription(final String description) {
this.description = description;
}
@NotNull
@Valid
@Enumerated(EnumType.STRING)
public Genre getGenre() {
return this.genre;
}
public void setGenre(final Genre genre) {
this.genre = genre;
}
@NotNull
public Boolean getBanned() {
return this.banned;
}
public void setBanned(final Boolean banned) {
this.banned = banned;
}
@NotNull
@Past
@Temporal(TemporalType.DATE)
@DateTimeFormat(pattern = "dd/MM/yyyy")
public Date getBirthDate() {
return this.birthDate;
}
public void setBirthDate(final Date birthDate) {
this.birthDate = birthDate;
}
@NotNull
@Valid
@Enumerated(EnumType.STRING)
public RelationshipType getRelationshipEngage() {
return this.relationshipEngage;
}
public void setRelationshipEngage(final RelationshipType relationshipEngage) {
this.relationshipEngage = relationshipEngage;
}
@NotNull
@Valid
public Coordinates getCoordinates() {
return this.coordinates;
}
public void setCoordinates(final Coordinates coordinates) {
this.coordinates = coordinates;
}
@NotNull
@Past
@Temporal(TemporalType.DATE)
@DateTimeFormat(pattern = "dd/MM/yyyy HH:mm:ss")
public Date getLastFeeDate() {
return this.lastFeeDate;
}
public void setLastFeeDate(final Date lastFeeDate) {
this.lastFeeDate = lastFeeDate;
}
@NotNull
@Min(0)
public Double getFee() {
return this.fee;
}
public void setFee(final Double fee) {
this.fee = fee;
}
// Relationships ----------------------------------------------------------
private Collection<Like> givenLikes;
private Collection<Like> receivedLikes;
private Collection<Event> events;
@Valid
@NotNull
@OneToMany(mappedBy = "givenBy")
public Collection<Like> getGivenLikes() {
return this.givenLikes;
}
public void setGivenLikes(final Collection<Like> givenLikes) {
this.givenLikes = givenLikes;
}
@Valid
@NotNull
@OneToMany(mappedBy = "givenTo")
public Collection<Like> getReceivedLikes() {
return this.receivedLikes;
}
public void setReceivedLikes(final Collection<Like> receivedLikes) {
this.receivedLikes = receivedLikes;
}
@Valid
@NotNull
@ManyToMany(mappedBy = "chorbies")
public Collection<Event> getEvents() {
return this.events;
}
public void setEvents(final Collection<Event> events) {
this.events = events;
}
}
|
public class SimilarRatingGraph {
public double maxLength(int[] date, int[] rating) {
double max = 0.0;
for(int i = 0; i < date.length; ++i) {
for(int j = i + 1; j < date.length - 1; ++j) {
double scaleD = (double)(date[i] - date[i + 1])/(date[j] - date[j + 1]);
long d1 = date[i] - date[i + 1];
long d2 = date[j] - date[j + 1];
long r1 = rating[i] - rating[i + 1];
long r2 = rating[j] - rating[j + 1];
if(d1 * r2 == r1 * d2) {
double lengthI = 0.0;
double lengthJ = 0.0;
boolean simmilar = true;
for(int k = 1; j + k < date.length && simmilar; ++k) {
long id1 = date[i + k - 1] - date[i + k];
long id2 = date[j + k - 1] - date[j + k];
long ir1 = rating[i + k - 1] - rating[i + k];
long ir2 = rating[j + k - 1] - rating[j + k];
if(id2 * d1 == id1 * d2 && ir2 * d1 == ir1 * d2) {
lengthI += Math.sqrt(id1 * id1 + ir1 * ir1);
lengthJ += Math.sqrt(id2 * id2 + ir2 * ir2);
} else {
simmilar = false;
}
}
if(max < lengthI) {
max = lengthI;
}
if(max < lengthJ) {
max = lengthJ;
}
}
}
}
return max;
}
}
|
package com.library.web.controllers;
import com.library.web.models.Activity;
import com.library.web.models.Ticket;
import com.library.web.models.User;
import com.library.web.repo.ActivityRepository;
import com.library.web.repo.TicketRepo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import java.sql.Date;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
@Controller
public class ActivityController {
@Autowired
private ActivityRepository activityRepository;
@Autowired
private TicketRepo ticketRepo;
@GetMapping("/activity")
public String getActivity(Model model) {
Iterable<Activity> activity = activityRepository.findAll();
model.addAttribute("activity", activity);
return "activity";
}
@PostMapping("/activity")
public String activityFilter(@RequestParam String filter, Model model) {
List<Activity> activity = activityRepository.findByTitleIgnoreCaseContaining(filter);
model.addAttribute("activity", activity);
return "/activity";
}
@GetMapping("/activity/add")
public String activityAdd(Model model) {
return "activityAdd";
}
@PostMapping("/activity/add")
public String activityPostAdd(@RequestParam String title, @RequestParam Date date, @RequestParam int seats, @AuthenticationPrincipal User user, Model model) {
Activity activity = new Activity(title, date, seats, user);
activityRepository.save(activity);
return "redirect:/activity";
}
@GetMapping("/activity/{id}")
public String getActivityDetails(@PathVariable(value = "id") long id, Model model) {
if(!activityRepository.existsById(id)){
return "redirect:/books";
}
Optional<Activity> activity = activityRepository.findById(id);
ArrayList<Activity> res = new ArrayList<>();
activity.ifPresent(res::add);
model.addAttribute("activity", res);
return "activityDetails";
}
@PostMapping("/activity/{id}")
public String activityRegistration(@PathVariable(value = "id") long id, @AuthenticationPrincipal User user){
if(!activityRepository.existsById(id)){
return "redirect:/books";
}
Activity activity = activityRepository.findById(id).orElseThrow(IllegalStateException::new);
int seats = activity.getSeats();
activity.setSeats(seats-1);
activityRepository.save(activity);
Ticket ticket = new Ticket(activity, user);
ticketRepo.save(ticket);
return "redirect:/activity";
}
}
|
package com.synclab.Challenginator.microservice.challenge.insertChallenge;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.synclab.Challenginator.microservice.challenge.challenge.*;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.web.client.HttpStatusCodeException;
import org.springframework.web.client.RestTemplate;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
@Service
@AllArgsConstructor
public class InsertService {
private final ChallengeService challengeService;
@Autowired
private RestTemplate restTemplate;
private ObjectMapper objectMapper;
//dall'id dello sfidato determino il giudice
public Long getEvaluator(Long challenged,String jwt) throws JsonProcessingException {
HttpHeaders headers = new HttpHeaders();
headers.add("Authorization", jwt);
HttpEntity<String> entity = new HttpEntity<String>(headers);
BossList response = null;
response = restTemplate.exchange("http://localhost:8080/user/valutator/"+ challenged,
HttpMethod.GET, entity, new ParameterizedTypeReference<BossList>() {
}).getBody();
return response.getBossOfUser();
}
public HttpStatus insert(InsertRequest request, Long userid, String jwt) throws JsonProcessingException {
Long evaluator = this.getEvaluator(request.getIdChallenged(),jwt);
return challengeService.insertNewChallenge(
new Challenge(
LocalDateTime.now(),
userid,
request.getIdChallenged(),
request.getTitle(),
request.getDescription(),
request.getDeadline(),
ChallengeStatus.PENDING,
evaluator
)
);
}
}
|
package RegExpressions;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class regExpClass {
private static final String phones =
"Phone number: +74991922610\n" +
"как говорится читайте между строк\n" +
"Phone number: +74991922611\n" +
"как говорится читайте между строк\n" +
"Phone number: +74991922612\n" +
"как говорится читайте между строк\n" +
"Phone number: +74991922613\n" +
"как говорится читайте между строк\n" +
"Phone number: +74991922614\n" +
"просто спам\n" +
"Phone number: 84991922615\n" +
"Phone number: 84991922616\n" +
"Phone number: 84991922617\n" +
"просто спам\n" +
"Phone number: 84991922618\n" +
"Phone number: 84991922619";
public void phoneExper(){
Pattern regExp = Pattern.compile("\\+([7]|[8])[4][9][9]"); // reg exp for phone number
Matcher matcher = regExp.matcher(phones);
String newPhones = matcher.replaceAll("8495");
System.out.println(newPhones);
}
private void exampleRegExp(){
// IP адрес
String regexp = "(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)";
// для сравнения работы find() и matches()
String goodIp = "192.168.0.3";
String badIp = "192.168.0.3g";
Pattern patternIP = Pattern.compile(regexp);
Matcher matcherIP = patternIP.matcher(goodIp);
// matches() - true, find() - true
matcherIP = patternIP.matcher(badIp);
// matches() - false, find() - true
// а теперь получим дополнительную информацию
System.out.println(matcherIP.find() ?
"I found '" + matcherIP.group() + "' starting at index " + matcherIP.start() + " and ending at index " + matcherIP.end() + "." :
"I found nothing!");
// I found the text '192.168.0.3' starting at index 0 and ending at index 11.
}
}
|
import java.util.*;
public class LeetCode_Question1 {
//finds median of one sorted array, takes O(1) time complexity
private static double arrayMedian(List<Integer> array) {
if (array.size() == 0) {
return 0;
}
int middle = array.size() / 2;
if (array.size() % 2 != 0) {
return (double) array.get(middle);
} else {
return (double) (array.get(middle) + array.get(middle - 1)) / 2;
}
}
// finds index of an array where a given value can be placed using binary search, takes O(log(m)) time
// complexity -- if smaller than arrays smallest value returns -1, if greater returns arrays length, and
// if inside array returns one index above index of closest element less than or equal to it
private static int findIndex(List<Integer> array, double value) {
int LB = 0;
int UB = array.size() - 1;
// edge cases
if (value < array.get(LB)) {
return -1;
} else if (value > array.get(UB)) {
return array.size();
}
// other cases
while (UB - LB > 1) {
//iterative cases
int median = (UB + LB) / 2;
if (array.get(median) == value ) {
return median + 1;
} else if (array.get(median) > value) {
UB = median;
} else {
LB = median;
}
}
//base case
if (UB - LB == 1) {
return LB + 1;
}
return -1;
}
//finds the median of two sorted array in log(m + n) time complexity, where m is size of array 1 and
// n is size of array 2
public static double findMedian(List<Integer> array1, List<Integer> array2) {
}
public static void main (String []args) {
List<Integer> array0 = Arrays.asList(1);
System.out.println(arrayMedian(array0));
List<Integer> array1 = Arrays.asList(3, 5, 90, 100);
List<Integer> array2 = Arrays.asList(0, 2, 4, 10, 20, 30, 50, 200);
//System.out.println(findMedian(array1, array2));
}
}
|
package com.github.xuchengen;
import java.security.KeyPair;
/**
* 银联证书信息
* 作者:徐承恩
* 邮箱:xuchengen@gmail.com
* 日期:2019/8/28
*/
public class UnionPayCertInfo {
/**
* 密钥对
*/
private KeyPair keyPair;
/**
* 证书序列号
*/
private String serialNo;
/**
* 公钥字符串
*/
private String publicKeyStr;
/**
* 私钥字符串
*/
private String privateKeyStr;
public KeyPair getKeyPair() {
return keyPair;
}
public UnionPayCertInfo setKeyPair(KeyPair keyPair) {
this.keyPair = keyPair;
return this;
}
public String getSerialNo() {
return serialNo;
}
public UnionPayCertInfo setSerialNo(String serialNo) {
this.serialNo = serialNo;
return this;
}
public String getPublicKeyStr() {
return publicKeyStr;
}
public UnionPayCertInfo setPublicKeyStr(String publicKeyStr) {
this.publicKeyStr = publicKeyStr;
return this;
}
public String getPrivateKeyStr() {
return privateKeyStr;
}
public UnionPayCertInfo setPrivateKeyStr(String privateKeyStr) {
this.privateKeyStr = privateKeyStr;
return this;
}
@Override
public String toString() {
return "UnionpayCertInfo{" +
"keyPair=" + keyPair +
", serialNo='" + serialNo + '\'' +
", publicKeyStr='" + publicKeyStr + '\'' +
", privateKeyStr='" + privateKeyStr + '\'' +
'}';
}
}
|
package org.emphie.fod;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.List;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.os.Build;
import android.os.Bundle;
import android.preference.CheckBoxPreference;
import android.preference.EditTextPreference;
import android.preference.Preference;
import android.preference.Preference.OnPreferenceChangeListener;
import android.preference.PreferenceActivity;
import android.preference.PreferenceFragment;
import android.preference.SwitchPreference;
import android.view.View;
// Uses reflection to work on older devices
// Code from: http://www.blackmoonit.com/2012/07/all_api_prefsactivity/
public class preferences extends PreferenceActivity {
protected Method mLoadHeaders = null;
protected Method mHasHeaders = null;
public static AlertDialog.Builder builder;
public static Boolean isdebug;
/**
* Checks to see if using new v11+ way of handling PrefsFragments.
*
* @return Returns false pre-v11, else checks to see if using headers.
*/
public boolean isNewV11Prefs() {
if (mHasHeaders != null && mLoadHeaders != null) {
try {
return (Boolean) mHasHeaders.invoke(this);
} catch (IllegalArgumentException e) {
} catch (IllegalAccessException e) {
} catch (InvocationTargetException e) {
}
}
return false;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
// onBuildHeaders() will be called during super.onCreate()
try {
mLoadHeaders = getClass().getMethod("loadHeadersFromResource", int.class, List.class);
mHasHeaders = getClass().getMethod("hasHeaders");
} catch (NoSuchMethodException e) {
}
super.onCreate(savedInstanceState);
builder = new AlertDialog.Builder(this);
isdebug = FoDActivity.isdebug((Activity) preferences.this);
if (!isNewV11Prefs()) {
final EditTextPreference SMS_number;
final CheckBoxPreference just_dawson;
// deprecated methods OK here...
addPreferencesFromResource(R.xml.preferences);
// addPreferencesFromResource(R.preferences2);
// addPreferencesFromResource(R.xml.preferencesN);
// Link to just dawson_checkbox to update SMS_number summary
just_dawson = (CheckBoxPreference) getPreferenceScreen().findPreference("just_dawson");
// Link to sms number for validation
SMS_number = (EditTextPreference) getPreferenceScreen().findPreference("SMS_number");
if (just_dawson.isChecked()) {
SMS_number.setSummary((CharSequence) getString(R.string.dawsons_number));
} else {
SMS_number.setSummary((CharSequence) SMS_number.getText());
}
SMS_number.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
private Boolean rtnval = false;
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
rtnval = check_number(builder, newValue);
if (rtnval) {
SMS_number.setSummary((CharSequence) newValue);
}
return rtnval;
}
});
just_dawson.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
if ((Boolean) newValue) {
SMS_number.setSummary((CharSequence) getString(R.string.dawsons_number));
} else {
SMS_number.setSummary((CharSequence) SMS_number.getText());
}
return true;
}
});
}
}
/*
* Populate the activity with the top-level headers.
*/
@Override
public void onBuildHeaders(List<Header> target) {
try {
mLoadHeaders.invoke(this, new Object[] { R.xml.pref_headers, target });
// loadHeadersFromResource(R.xml.pref_headers, target);
} catch (IllegalArgumentException e) {
} catch (IllegalAccessException e) {
} catch (InvocationTargetException e) {
}
}
/*
* The menus for version 11 and onwards
*/
@TargetApi(11)
public static class basics extends PreferenceFragment implements OnSharedPreferenceChangeListener {
int os_version = Build.VERSION.SDK_INT;
int SWITCH_MIN = 14;
private EditTextPreference SMS_number;
private View SMS_layout;
private CheckBoxPreference just_dawson_check;
private SwitchPreference just_dawson_switch;
private boolean just_dawson_checked;
@TargetApi(14)
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Build the fragment
addPreferencesFromResource(R.xml.preferences);
// Link to just dawson_checkbox/switch to update SMS_number summary
if (Build.VERSION.SDK_INT < SWITCH_MIN) {
just_dawson_check = (CheckBoxPreference) getPreferenceScreen().findPreference("just_dawson");
} else {
just_dawson_switch = (SwitchPreference) getPreferenceScreen().findPreference("just_dawson");
}
// Link to sms number for validation
SMS_number = (EditTextPreference) getPreferenceScreen().findPreference("SMS_number");
// int int_SMS_layout =
// getPreferenceScreen().findPreference("SMS_number").getLayoutResource();
// handle different OS versions
// versions less than 14 don't have testable switch preferences, so use check boxes.
if (Build.VERSION.SDK_INT < SWITCH_MIN) {
just_dawson_checked = just_dawson_check.isChecked();
}else{
just_dawson_checked = just_dawson_switch.isChecked();
}
if (just_dawson_checked) {
SMS_number.setSummary((CharSequence) getString(R.string.dawsons_number));
} else {
SMS_number.setSummary((CharSequence) SMS_number.getText());
}
//TODO
/*
* final int CONTACT_PICKER_RESULT = 1001;
* Intent contactPickerIntent = new Intent(Intent.ACTION_PICK,
* Contacts.CONTENT_URI);
* startActivityForResult(contactPickerIntent,
* CONTACT_PICKER_RESULT);
*
*
* Bundle extras = data.getExtras();
* Set keys = extras.keySet();
* Iterator iterate = keys.iterator();
* while (iterate.hasNext()) {
* String key = iterate.next();
* Log.v(DEBUG_TAG, key + "[" + extras.get(key) + "]");
* }
* Uri result = data.getData();
* Log.v(DEBUG_TAG, "Got a result: "
* + result.toString());
*
* // query for everything email
* cursor = getContentResolver().query(
* Email.CONTENT_URI, null,
* Email.CONTACT_ID + "=?",
* new String[]{id}, null);
* cursor.moveToFirst();
* String columns[] = cursor.getColumnNames();
* for (String column : columns) {
* int index = cursor.getColumnIndex(column);
* Log.v(DEBUG_TAG, "Column: " + column + " == ["
* + cursor.getString(index) + "]");
* onActivityResult(int requestCode, int resultCode, Intent data) {
* if (resultCode == RESULT_OK) {
* switch (requestCode) {
* case CONTACT_PICKER_RESULT:
* // handle contact results
* break;
* }
*
* } else {
* // gracefully handle failure
* Log.w(DEBUG_TAG, "Warning: activity result not ok");
* }
* }
*/
//TODO
SMS_number.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
return check_number(builder, newValue);
}
});
if (Build.VERSION.SDK_INT < SWITCH_MIN) {
just_dawson_check.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
if ((Boolean) newValue) {
SMS_number.setSummary((CharSequence) getString(R.string.dawsons_number));
} else {
SMS_number.setSummary((CharSequence) SMS_number.getText());
}
return true;
}
});
}else{
just_dawson_switch.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
if ((Boolean) newValue) {
SMS_number.setSummary((CharSequence) getString(R.string.dawsons_number));
} else {
SMS_number.setSummary((CharSequence) SMS_number.getText());
}
return true;
}
});
}
}
@TargetApi(14)
@Override
public void onResume() {
super.onResume();
// Setup the initial values
if (Build.VERSION.SDK_INT < SWITCH_MIN) {
just_dawson_checked = just_dawson_check.isChecked();
}else{
just_dawson_checked = just_dawson_switch.isChecked();
}
if (just_dawson_checked) {
SMS_number.setSummary((CharSequence) getString(R.string.dawsons_number));
} else {
SMS_number.setSummary((CharSequence) SMS_number.getText());
}
// Set up a listener whenever a key changes
getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
}
@TargetApi(11)
@Override
public void onPause() {
super.onPause();
// Unregister the listener whenever a key changes
getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this);
}
@TargetApi(14)
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
// Update the item summary to reflect the change
if (key.equals("just_dawson")) {
if (Build.VERSION.SDK_INT < SWITCH_MIN) {
just_dawson_checked = just_dawson_check.isChecked();
}else{
just_dawson_checked = just_dawson_switch.isChecked();
}
if (just_dawson_checked) {
SMS_number.setSummary((CharSequence) getString(R.string.dawsons_number));
} else {
SMS_number.setSummary((CharSequence) SMS_number.getText());
}
} else if (key.equals("SMS_number")) {
SMS_number.setSummary(SMS_number.getText());
}
}
}
/*
* Common code for phone number validation
*/
public static boolean check_number(AlertDialog.Builder builder, Object newValue) {
boolean rtnval = false;
// builder = new AlertDialog.Builder((Context) builder);
if (FoDActivity.valid_victim((String) newValue)) {
if (newValue.toString().length() > 0) {
// valid number, well, close enough
rtnval = true;
} else {
builder.setTitle(R.string.bad_number_title);
builder.setMessage(R.string.bad_number_message);
builder.setPositiveButton(android.R.string.ok, null);
builder.show();
rtnval = false;
}
} else {
// invalid number (probably ours)
if (isdebug) {
// but it's ok because we're debugging
builder.setTitle("Debug build");
builder.setMessage("Allowed for debug... But don't be a cunt!");
rtnval = true;
} else {
// invalid number message
builder.setTitle(R.string.banned_number_title);
builder.setMessage(R.string.banned_number_message);
rtnval = false;
}
builder.setPositiveButton(android.R.string.ok, null);
builder.show();
}
return rtnval;
}
}
|
/*
* Created by Antonio Cappiello on 1/13/16 9:31 PM
* Copyright (c) 2016. All rights reserved.
*
* Last modified 1/11/16 11:26 PM
*/
package com.antoniocappiello.curriculumvitae.presenter.webapi;
import com.antoniocappiello.curriculumvitae.model.AboutMe;
import rx.Observable;
public class WebApiService {
private final WebApi mWebApi;
public WebApiService(WebApi webApi){
mWebApi = webApi;
}
public Observable<AboutMe> readAboutMe(){
return mWebApi.readAssetWithObservable(
"about_me.json");
}
public void readEducation(){
mWebApi.readAssetWithCallback(
"education.json",
WebApiCallbackFactory.getEducationCallback());
}
public void readWorkExperience(){
mWebApi.readAssetWithCallback(
"work_experience.json",
WebApiCallbackFactory.getWorkExperienceCallback());
}
}
|
package com.gmail.raynlegends.adventofcode.puzzles;
import java.util.HashMap;
import com.gmail.raynlegends.adventofcode.Puzzle;
public class _07_2_Puzzle implements Puzzle {
private static interface Source {
int getValue();
String toString();
}
private static class Wire implements Source {
private static HashMap<String, Integer> calculateds = new HashMap<>();
private final String id;
private Source firstSource;
private Source secondSource;
private String operation;
private Wire(String id, Source firstSource, Source secondSource, String operation) {
this.id = id;
this.firstSource = firstSource;
this.secondSource = secondSource;
this.operation = operation;
}
@Override
public int getValue() {
Integer calculated = calculateds.get(id);
if (calculated != null) {
return calculated; // Otherwise it would fall into an infinite loop
}
int result = 0;
if (secondSource != null) {
result = calculate(firstSource.getValue(), secondSource.getValue(), operation);
} else if (operation != null) {
result = ~firstSource.getValue(); // Operation equals "BWC" at this point
} else {
result = firstSource.getValue();
}
calculateds.put(id, result);
return result;
}
@Override
public String toString() {
return id;
}
}
private static class Value implements Source {
private int value;
private Value(int value) {
this.value = value;
}
@Override
public int getValue() {
return value;
}
@Override
public String toString() {
return value + "";
}
}
@Override
public String calculate(String input) {
HashMap<String, Wire> wires = new HashMap<>();
int part = 0;
int last = 100;
String[] parts = new String[5];
for (String section : input.split(" ")) {
if (part == last + 1) {
part = 0;
last = 100;
parts = new String[5];
}
parts[part] = section;
if (section.equals("->")) {
last = part + 1;
}
if (part == last) {
String wireId = parts[last];
Wire wire = wires.get(wireId);
if (wire == null) {
wire = new Wire(wireId, null, null, null);
wires.put(wireId, wire);
}
if (last == 2) {
wire.firstSource = getProvider(wires, parts[0]);
} else if (last == 3) {
wire.firstSource = getProvider(wires, parts[1]);
wire.operation = "BWC";
} else if (last == 4) {
wire.firstSource = getProvider(wires, parts[0]);
wire.operation = parts[1];
wire.secondSource = getProvider(wires, parts[2]);
}
}
part++;
}
Wire aWire = wires.get("a");
Wire bWire = wires.get("b");
bWire.firstSource = new Value(aWire.getValue());
bWire.operation = null;
aWire.secondSource = null;
Wire.calculateds.clear();
return aWire.getValue() + "";
}
private static int calculate(int first, int second, String operation) {
switch (operation) {
case "AND": return first & second;
case "OR": return first | second;
case "LSHIFT": return first << second;
case "RSHIFT": return first >> second;
}
return 0;
}
private static Source getProvider(HashMap<String, Wire> wires, String id) {
Source provider = null;
try {
provider = new Value(Integer.parseInt(id));
} catch (Exception e) {
Wire otherWire = wires.get(id);
if (otherWire == null) {
otherWire = new Wire(id, null, null, null);
wires.put(id, otherWire);
}
provider = otherWire;
}
return provider;
}
@Override
public String toString() {
return "Day 7, Part 2";
}
}
|
package nowcoder;
import nowcoder.domain.ListNode;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.TreeSet;
/**
*********************************************************************
*
* @author poles
* @date 2020/8/28 8:35 下午
*
*********************************************************************
*/
public class 多个有序链表合并 {
public static void main(String[] args) {
ArrayList<ListNode> list = new ArrayList<>();
ListNode node = new ListNode(1); node.next = new ListNode(2); node.next.next = new ListNode(2);
ListNode node2 = new ListNode(1); node2.next = new ListNode(1); node2.next.next = new ListNode(2);
list.add(node);
list.add(node2);
System.out.println(mergeKLists(list));
}
public static ListNode mergeKLists(ArrayList<ListNode> lists) {
//思路一,直接使用树形结构,然后再使用前序遍历,试一下
TreeSet<ListNode> tree = new TreeSet<>((o1, o2) -> o1.val > o2.val ? 1 : -1);
for(ListNode head : lists){
while(head != null){
ListNode node = head;
head = head.next; //走下一个
node.next = null;
tree.add(node); //节点加入tree中
}
}
//前序遍历即可
ListNode head = null;
ListNode current = null;
for(ListNode node : tree){
if(head == null){
head = node;
current = head;
}else{
current.next = node;
current = current.next;
}
}
return head;
}
}
|
package br.imd.modelo;
public class Histograma {
private String data;
private int dia;
private int mes;
private int ano;
private String horaCompleta;
private int hora;
private int minuto;
}
|
package cc.smh.common.dao;
import java.io.Serializable;
import java.util.Collection;
import java.util.List;
import org.hibernate.criterion.DetachedCriteria;
import cc.smh.common.bean.BaseTO;
import cc.smh.common.exception.DaoException;
/**
* dao基类接口
* @date 2011/04/07
*/
public interface IBaseDao {
/**
* 保存实例
*
* @param oTO
* @throws DaoException
*/
public void editSave(BaseTO oTO) throws DaoException;
/**
* 修改实例
*
* @param oTO
* @throws DaoException
*/
public void editUpdate(BaseTO oTO) throws DaoException;
/**
* 保存或修改实例
*
* @param oTO
* @throws DaoException
*/
public void edit(BaseTO oTO) throws DaoException;
/**
* 删除实例
*
* @param oTO
* @throws DaoException
*/
public void delete(BaseTO oTO) throws DaoException;
public List<BaseTO> queryAll(String hql) throws DaoException;
}
|
package com.apssouza.mytrade.trading.forex.session;
import com.apssouza.mytrade.trading.forex.order.OrderDto;
import com.apssouza.mytrade.trading.forex.portfolio.FilledOrderDto;
import com.apssouza.mytrade.trading.forex.portfolio.Position;
import com.apssouza.mytrade.trading.forex.statistics.TransactionState;
import java.time.LocalDateTime;
public class TransactionDto {
private final LocalDateTime time;
private final String identifier;
private OrderDto order;
private Position position;
private FilledOrderDto filledOrder;
private TransactionState state;
public TransactionDto(LocalDateTime time, String identifier) {
this.time = time;
this.identifier = identifier;
}
public LocalDateTime getTime() {
return this.time;
}
public String getIdentifier() {
return this.identifier;
}
public OrderDto getOrder() {
return this.order;
}
public Position getPosition() {
return this.position;
}
public FilledOrderDto getFilledOrder() {
return this.filledOrder;
}
public TransactionState getState() {
return this.state;
}
public void setOrder(OrderDto order) {
this.order = order;
}
public void setPosition(Position position) {
this.position = position;
}
public void setFilledOrder(FilledOrderDto filledOrder) {
this.filledOrder = filledOrder;
}
public void setState(TransactionState state) {
this.state = state;
}
public boolean equals(final Object o) {
if (o == this) {
return true;
}
if (!(o instanceof TransactionDto)) {
return false;
}
final TransactionDto other =
(TransactionDto) o;
if (!other.canEqual((Object) this)) {
return false;
}
final Object this$time = this.getTime();
final Object other$time = other.getTime();
if (this$time == null ? other$time != null : !this$time.equals(other$time)) {
return false;
}
final Object this$identifier = this.getIdentifier();
final Object other$identifier = other.getIdentifier();
if (this$identifier == null ? other$identifier != null : !this$identifier.equals(other$identifier)) {
return false;
}
final Object this$order = this.getOrder();
final Object other$order = other.getOrder();
if (this$order == null ? other$order != null : !this$order.equals(other$order)) {
return false;
}
final Object this$position = this.getPosition();
final Object other$position = other.getPosition();
if (this$position == null ? other$position != null : !this$position.equals(other$position)) {
return false;
}
final Object this$filledOrder = this.getFilledOrder();
final Object other$filledOrder = other.getFilledOrder();
if (this$filledOrder == null ? other$filledOrder != null : !this$filledOrder.equals(other$filledOrder)) {
return false;
}
final Object this$state = this.getState();
final Object other$state = other.getState();
if (this$state == null ? other$state != null : !this$state.equals(other$state)) {
return false;
}
return true;
}
protected boolean canEqual(final Object other) {
return other instanceof TransactionDto;
}
public int hashCode() {
final int PRIME = 59;
int result = 1;
final Object $time = this.getTime();
result = result * PRIME + ($time == null ? 43 : $time.hashCode());
final Object $identifier = this.getIdentifier();
result = result * PRIME + ($identifier == null ? 43 : $identifier.hashCode());
final Object $order = this.getOrder();
result = result * PRIME + ($order == null ? 43 : $order.hashCode());
final Object $position = this.getPosition();
result = result * PRIME + ($position == null ? 43 : $position.hashCode());
final Object $filledOrder = this.getFilledOrder();
result = result * PRIME + ($filledOrder == null ? 43 : $filledOrder.hashCode());
final Object $state = this.getState();
result = result * PRIME + ($state == null ? 43 : $state.hashCode());
return result;
}
public String toString() {
return "TransactionDto(time=" + this.getTime() + ", identifier=" + this.getIdentifier() + ", order=" +
this.getOrder() + ", position=" + this.getPosition() + ", filledOrder=" + this.getFilledOrder() +
", state=" + this.getState() + ")";
}
}
|
package ru.job4j.ui;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.GregorianCalendar;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.LogManager;
/**
* Класс UserService.
*
* @author Gureyev Ilya (mailto:ill-jah@yandex.ru)
* @version 1
* @since 2017-11-26
*/
class UserService {
/**
* Драйвер бд.
*/
private UserStore db;
/**
* Логгер.
*/
private Logger logger;
/**
* Таблица в бд.
*/
private String tbl;
/**
* Конструктор.
*/
UserService() {
this.logger = LogManager.getLogger("UserService");
this.db = UserStore.getInstance();
this.tbl = this.db.getTblName();
}
/**
* Добавляет пользователя.
* @param user новый пользователь.
* @return true если пользователь добавлен в бд. Иначе false.
* @throws SQLException ошибка SQL.
* @throws ParseException ошибка парсинга.
*/
public boolean addUser(User user) throws SQLException, ParseException {
boolean result = false;
String query = String.format("insert into %s (name, login, email, createDate) values ('%s', '%s', '%s', '%5$tY-%5$tm-%5$td')", this.tbl, user.getName(), user.getLogin(), user.getEmail(), user.getDate());
HashMap<String, String> entry = this.db.insert(query);
if (!entry.isEmpty()) {
user.setId(Integer.parseInt(entry.get("id")));
result = true;
}
return result;
}
/**
* Удаляет пользователя.
* @param id идентификатор.
* @return true если пользователь удалён из бд. Иначе false.
* @throws SQLException ошибка SQL.
*/
public boolean deleteUser(int id) throws SQLException {
boolean result = false;
String query = String.format("delete from %s where id = %d", this.tbl, id);
int affected = this.db.delete(query);
if (affected > 0) {
result = true;
}
return result;
}
/**
* Получает пользователя по идентификатору.
* @param id идентификатор пользователя.
* @return пользователь.
* @throws SQLException ошибка SQL.
* @throws ParseException ошибка парсинга.
*/
public User getUser(int id) throws SQLException, ParseException {
User user = null;
String query = String.format("select * from %s where id = %d", this.tbl, id);
HashMap<String, String> entry = this.db.select(query).getFirst();
if (!entry.isEmpty()) {
GregorianCalendar cal = new GregorianCalendar();
SimpleDateFormat sdf = new SimpleDateFormat("YYYY-MM-dd");
String strDate = entry.get("createdate");
Date date = sdf.parse(strDate);
cal.setTime(date);
user = new User(Integer.parseInt(entry.get("id")), entry.get("name"), entry.get("login"), entry.get("email"), cal);
}
return user;
}
/**
* Получает всех пользователей.
* @param order имя столбца сортировки (по умолчанию id).
* @param desc направление сортировки (asc, desc. По умолчанию asc).
* @return Коллекция пользователей.
* @throws SQLException ошибка SQL.
* @throws ParseException ошибка парсинга.
*/
public LinkedList<User> getUsers(final String order, final boolean desc) throws SQLException, ParseException {
LinkedList<User> users = new LinkedList<>();
String query = String.format("select * from %s order by %s %s", this.tbl, order.equals("") ? "id" : order, desc ? "desc" : "asc");
LinkedList<HashMap<String, String>> rl = this.db.select(query);
if (!rl.isEmpty()) {
for (HashMap<String, String> entry : rl) {
GregorianCalendar cal = new GregorianCalendar();
SimpleDateFormat sdf = new SimpleDateFormat("YYYY-MM-dd");
String strDate = entry.get("createdate");
Date date = sdf.parse(strDate);
cal.setTime(date);
users.add(new User(Integer.parseInt(entry.get("id")), entry.get("name"), entry.get("login"), entry.get("email"), cal));
}
}
return users;
}
/**
* Редактирует пользователя.
* @param user новый пользователь.
* @return true если пользователь обновлён в бд. Иначе false.
* @throws SQLException ошибка SQL.
*/
public boolean editUser(User user) throws SQLException {
boolean result = false;
String query = String.format("update %s set name='%s', login='%s', email='%s' where id=%d", this.tbl, user.getName(), user.getLogin(), user.getEmail(), user.getId());
int affected = this.db.update(query);
if (affected > 0) {
result = true;
}
return result;
}
}
|
package io.snice.buffer;
import io.snice.buffer.impl.DefaultReadWriteBuffer;
import static io.snice.preconditions.PreConditions.assertArray;
public interface ReadWriteBuffer extends ReadableBuffer, WritableBuffer {
static ReadWriteBuffer of(final byte... buffer) {
assertArray(buffer);
return DefaultReadWriteBuffer.of(buffer);
}
static ReadWriteBuffer of(final int capacity) {
return DefaultReadWriteBuffer.of(capacity);
}
static ReadWriteBuffer of(final byte[] buffer, final int offset, final int length) {
return DefaultReadWriteBuffer.of(buffer, offset, length);
}
}
|
import java.util.*;
public class Arraystuff {
/*--------------------- Instance Variables --------------------*/
private int[] a;
Random rnd;
// By making x final, we can set it once but then never change it
// private final int x = 123;
/*--------------------- Constructors --------------------*/
public Arraystuff(int n){
rnd = new Random();
a = new int[n];
for (int i=0; i<a.length;i++){
a[i] = 75+rnd.nextInt(76);
}
}
public Arraystuff(){
this(100);
}
/*--------------------- Methods --------------------*/
public String toString(){
String s = "";
for (int i = 0; i < a.length; i++) {
s = s + a[i]+", ";
}
return s;}
/*--------------------- Main --------------------*/
public static void main(String[] args) {
Arraystuff as = new Arraystuff();
System.out.println(as);
}
public int find(int n){
int x;
for (x = 0; x < a.length; x++){
if (a[x] == n){
return x;
}
else {
return -1;
}
}
}
public int maxVal(){
int x = a[0];
int i;
for (i = 0; i < a.length; i++){
if (a[i] > x){
x = a[i];
}
}
return x;
}
public int freq(int i){
int y = 0;
for (int x = 0; i < a.length; x++){
if (a[x]==i){
y++;
}
}
return y;
}
}
|
package cpup.poke4j;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class BufferPos {
protected final int column;
protected final int line;
public BufferPos(int _column, int _line) {
column = _column;
line = _line;
}
@Override
public String toString() {
return column + ", " + line;
}
public boolean equals(BufferPos other) {
return getColumn() == other.getColumn() && getLine() == other.getLine();
}
public boolean greater(BufferPos other) {
if(getLine() == other.getLine()) {
return getColumn() > other.getColumn();
} else {
return getLine() > other.getLine();
}
}
public BufferPos find(Buffer buffer) {
return buffer.find(this);
}
public BufferPos move(Buffer buffer, int dist) {
int column = getColumn();
int line = getLine();
final int amt = Math.abs(dist); // pull off the sign so i only have to loop one way
if(amt == 0) {
return this;
}
final int dir = dist / amt; // the direction to move in (-1 for back, 1 for forwards)
for(int i = 0; i < amt; i++) {
// if this is at the end of the line (and we're going forwards)
if(dir == 1 && column == buffer.getLine(line).length()) {
// try to go down a line
if(line < buffer.getLineCount() - 1) {
line += 1;
column = 0;
} else {
// otherwise we're done
break;
}
// if this is at the start of the line (and we're going backwards)
} else if(dir == -1 && column == 0) {
// try to go up a line
if(line > 0) {
line -= 1;
column = buffer.getLine(line).length();
} else {
// otherwise we're done
break;
}
} else {
column += dir;
}
}
return new BufferPos(column, line);
}
protected final Pattern rightWordRE = Pattern.compile("(?:[a-zA-Z]+\\s*|[^a-zA-Z])$");
protected final Pattern leftWordRE = Pattern.compile("^(?:\\s*[a-zA-Z]+|[^a-zA-Z])");
public int getRightWordLength(Buffer buffer) {
final Matcher textMatch = rightWordRE.matcher(buffer.getLine(line).substring(0, column));
if(textMatch.find()) {
return textMatch.end() - textMatch.start();
} else {
return 0;
}
}
public int getLeftWordLength(Buffer buffer) {
final Matcher textMatch = leftWordRE.matcher(buffer.getLine(line).substring(column));
if(textMatch.find()) {
return textMatch.end();
} else {
return 0;
}
}
public BufferPos moveWord(Buffer buffer, int dist) {
BufferPos pos = this;
final int amt = Math.abs(dist); // how much needs to be moved (without a direction)
if(amt == 0) {
return this;
}
final int dir = dist / amt; // the direction to move in (-1 for back, 1 for forwards)
for(int i = 0; i < amt; i++) {
int moveAmt = 0;
final String sline = buffer.getLine(line);
if(dir == -1) {
if(column == 0) {
// if this is the first column then try to move up a line (one character)
moveAmt = 1;
} else {
final Matcher textMatch = rightWordRE.matcher(sline.substring(0, column));
if(textMatch.find()) {
// move back however much the pattern matched (end - start should be positive)
moveAmt += textMatch.end() - textMatch.start();
}
}
} else if(dir == 1) {
if(column == sline.length()) {
// move down a line (one character)
moveAmt = 1;
} else {
final Matcher textMatch = leftWordRE.matcher(sline.substring(column));
if(textMatch.find()) {
// move forward however much the pattern matched
moveAmt += textMatch.end();
}
}
}
// do the move (multiple the amt by the direction (makes stuff simpler while calculating this))
pos = move(buffer, moveAmt * dir);
}
return pos;
}
public BufferPos moveUD(Buffer buffer, int dist) {
int column = getColumn();
int line = getLine();
line += dist;
return new BufferPos(column, line).find(buffer);
}
// Getters and Setters
public int getColumn() {
return column;
}
public int getLine() {
return line;
}
}
|
package com.auro.scholr.home.presentation.view.viewholder;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.auro.scholr.R;
import com.auro.scholr.databinding.FriendsInviteItemLayoutBinding;
import com.auro.scholr.home.data.model.FriendsLeaderBoardModel;
import com.bumptech.glide.Glide;
import com.bumptech.glide.Priority;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.request.RequestOptions;
import java.util.List;
public class InviteItemViewHolder extends RecyclerView.ViewHolder {
FriendsInviteItemLayoutBinding binding;
public InviteItemViewHolder(@NonNull FriendsInviteItemLayoutBinding binding) {
super(binding.getRoot());
this.binding = binding;
}
public void bindUser(FriendsLeaderBoardModel model,int position) {
int reminder = position % 2;
if (reminder == 0) {
binding.parentLayout.setBackgroundColor(binding.parentLayout.getContext().getResources().getColor(R.color.white));
binding.checkbox.setChecked(true);
} else {
binding.checkbox.setChecked(false);
binding.parentLayout.setBackgroundColor(binding.parentLayout.getContext().getResources().getColor(R.color.item_bg_color));
}
binding.nameText.setText(model.getStudentName());
Glide.with(binding.profileImage.getContext())
.load((String) model.getImagePath())
.apply(RequestOptions.bitmapTransform(new RoundedCorners(20))
.dontAnimate()
.priority(Priority.IMMEDIATE)
.diskCacheStrategy(DiskCacheStrategy.ALL)
)
.into(binding.profileImage);
}
}
|
package com.contentstack.sdk;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import com.contentstack.sdk.utilities.CSAppConstants;
import com.contentstack.sdk.utilities.CSAppUtils;
import org.json.JSONObject;
import java.io.File;
import java.util.HashMap;
/**
* Connection Status.
*
* @author contentstack.com, Inc
*
*/
public class ConnectionStatus extends BroadcastReceiver {
public ConnectionStatus() {
}
@Override
public void onReceive(Context context, Intent intent) {
Contentstack.isNetworkAvailable(context);
if(!CSAppConstants.isNetworkAvailable){
//no net connection
CSAppConstants.isNetworkAvailable = false;
}else{
try{
JSONObject jsonObj = null;
JSONObject headerObject = null;
HashMap<String, Object> headerGroup = new HashMap();
CSAppConstants.isNetworkAvailable = true;
File offlineCallsFolder = new File(context.getDir("OfflineCalls", 0).getPath());
if(offlineCallsFolder.isDirectory()){
File[] childFiles = offlineCallsFolder.listFiles();
for(File child :childFiles){
File file = new File(offlineCallsFolder, child.getName());
if(file.exists()){
jsonObj = CSAppUtils.getJsonFromCacheFile(file);
if(jsonObj != null) {
headerObject = jsonObj.optJSONObject("headers");
int count = headerObject.names().length();
for (int i = 0; i < count; i++) {
String key = headerObject.names().getString(i);
headerGroup.put(key, headerObject.optString(key));
}
CSConnectionRequest connectionRequest = new CSConnectionRequest();
connectionRequest.setParams(
jsonObj.opt("url").toString(),
CSAppConstants.RequestMethod.POST,
jsonObj.opt("controller").toString(),
jsonObj.optJSONObject("params"),
headerGroup,
jsonObj.opt("cacheFileName"),
jsonObj.opt("requestInfo"),
null
);
}
child.delete();
}else{
CSAppUtils.showLog("ConnectionStatus", "--------------------no offline network calls");
}
}
}
}catch (Exception e) {
CSAppUtils.showLog("ConnectionStatus", "-----content stack----------send saved network calls-------catch|" + e);
}
}
CSAppUtils.showLog("ConnectionStatus", "---------------------BuiltAppConstants.isNetworkAvailable|" + CSAppConstants.isNetworkAvailable);
}
}
|
package baseline;
import java.util.*;
/*
* UCF COP3330 Fall 2021 Assignment 3 Solutions
* Copyright 2021 Federico Abreu Seymour
*/
public class Solution40 {
//Implment most of 39 here except print table
static TreeMap<Integer, Solution40> employees = new TreeMap<>();
//Make Private String variables for firstName lastName Position and separationDate
private String firstName;
private String lastName;
private String position;
private String separationDate;
public Solution40(String firstName, String lastName, String position, String separationDate) {
this.firstName = firstName;
this.lastName = lastName;
this.position = position;
this.separationDate = separationDate;
}
//Make get and set methods for last name
public String getLastName() {
return lastName;
}
//Compare Last Name
public static class LastNameSort implements Comparator<Solution40> {
public int compare(Solution40 o1, Solution40 o2) {
return o1.getLastName().compareTo(o2.getLastName());
}
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
//Create an Array to make a new Employee
List<Solution40> employeeList = new ArrayList<>();
//add new Employee to list
employeeList.add(new Solution40("John", "Johnson ", "Manager ", "2016-12-31"));
employeeList.add(new Solution40("Tou", "Xiong ", "Software Engineer ", "2016-10-05"));
employeeList.add(new Solution40("Michaela", "Michaelson ", "District Manager ", "2015-12-19"));
employeeList.add(new Solution40("Jake", "Jacobson ", "Programmer ", ""));
employeeList.add(new Solution40("Jacquelyn", "Jackson ", "DBA ", ""));
employeeList.add(new Solution40("Sally", "Weber ", "Web Developer ", "2015-12-18"));
//Sort by last name
employeeList.sort(new LastNameSort());
//Display Enter a search string: and Scan as String
System.out.print("Enter a search String: ");
String search = input.nextLine();
//if the Scaned String contains employee Then Display employees
System.out.println("Name" + " | " + "Position |" + " Separation Date");
System.out.println("---------------------|----------------------|----------------");
for(Solution40 solution40 : employeeList){
if(solution40.firstName.contains(search) || solution40.lastName.contains(search)) {
System.out.print(solution40.firstName + " " + solution40.lastName + " | "+solution40.position + " | "+solution40.separationDate + "\n");
}
}
}
}
|
package Utilites;
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import practice.practice.Base;
public class Testutils extends Base {
public void screenShot() throws IOException
{
File src=((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(src,new File(prop.getProperty("location")+"\\"+"1.png"));
}
}
|
package com.sandbox;
import org.antlr.v4.runtime.ANTLRInputStream;
import org.antlr.v4.runtime.CommonTokenStream;
import org.antlr.v4.runtime.TokenSource;
import org.antlr.v4.runtime.tree.ParseTreeWalker;
public class Main {
public static void main(String[] args) {
// Get our lexer
TokenSource lexer = new DrinkLexer(new ANTLRInputStream("a pint of beer"));
// Get a list of matched tokens
CommonTokenStream tokens = new CommonTokenStream(lexer);
// Pass the tokens to the parser
DrinkParser parser = new DrinkParser(tokens);
// Specify our entry point
DrinkParser.DrinkSentenceContext drinkSentenceContext = parser.drinkSentence();
// Walk it and attach our listener
ParseTreeWalker walker = new ParseTreeWalker();
DrinkListener listener = new MyDrinkListener();
walker.walk(listener, drinkSentenceContext);
}
}
|
/*
* 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 servlet;
import bbdd.Actor;
import bbdd.ConstructorPelicula;
import bbdd.Pelicula;
import bbdd.Pelicula0Builder;
import bbdd.Pelicula13Builder;
import bbdd.Pelicula18Builder;
import bbdd.Pelicula7Builder;
import bbdd.Proxy;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Iterator;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
*
* @author JD
*/
@WebServlet(name = "nuevaPeliServlet", urlPatterns = {"/nuevaPeliServlet"})
public class nuevaPeliServlet extends HttpServlet {
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
HttpSession sesion = request.getSession();
//Utilizaremos el patron builder para construir la pelicula
try {
ConstructorPelicula cons = new ConstructorPelicula();
Pelicula0Builder b0 = new Pelicula0Builder();
Pelicula18Builder b1 = new Pelicula18Builder();
Pelicula13Builder b2 = new Pelicula13Builder();
Pelicula7Builder b3 = new Pelicula7Builder();
Pelicula peli;
//elegimos el Builder adecuado
int clasi = Integer.parseInt(request.getParameter("clasificacion"));
switch (clasi) {
case 0:
cons.setPeliculaBuilder(b0);
break;
case 7:
cons.setPeliculaBuilder(b3);
break;
case 13:
cons.setPeliculaBuilder(b2);
break;
case 18:
cons.setPeliculaBuilder(b1);
break;
}
String nombre = request.getParameter("nombre");
String sinopsis = request.getParameter("sinopsis");
String pagina = request.getParameter("pagina");
String titulo = request.getParameter("titulo");
String genero = request.getParameter("genero");
String nacionalidad = request.getParameter("nacionalidad");
int duracion = Integer.parseInt(request.getParameter("duracion"));
int ano = Integer.parseInt(request.getParameter("ano"));
String distribibuidora = request.getParameter("distribuidora");
String director = request.getParameter("director");
String otros = request.getParameter("otros");
String listaActores = request.getParameter("listaActores");
//sacamos los actores del String
Actor miActor;
ArrayList<Actor> arrayLActores = new ArrayList<>();
String nombreA = "", apellidoA = "";
String[] actores, actor;
if (!listaActores.equals("")) {
actores = listaActores.split(";");
for (String a : actores) {
actor = a.split(",");
nombreA = actor[0];
apellidoA = actor[1];
miActor = new Actor(nombreA, apellidoA);
//System.out.println(miActor.toString());
arrayLActores.add(miActor);
}
}
System.out.println("ArrayActores: " + arrayLActores);
//Creamos la pelicula
cons.crearPelicula(nombre, sinopsis, pagina, titulo, genero, nacionalidad, duracion, ano, distribibuidora, director, arrayLActores, otros);
peli = cons.getPelicula();
//Guardamos la Pelicula en bbdd
Proxy bd = Proxy.getInstancia();
//Si ya existe esa pelicula, se le indica al usuario
if (bd.estaPelicula(nombre)) {
try (PrintWriter out = response.getWriter()) {
/* TODO output your page here. You may use following sample code. */
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>Ya existe la película</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1> Ya hay una pelicula en el sistema con el nombre: " + nombre + "</h1>");
out.println("Intenta insertar otra o modificar la existente");
out.println("</body>");
out.println("</html>");
}
}
bd.guardarPelicula(peli);
//Se añaden los actores
Iterator it = arrayLActores.iterator();
Actor a;
while (it.hasNext()) {
a = (Actor) it.next();
if (!bd.estaActor(a.getNombre(), a.getApellidos())) {
bd.guardarActor(a, nombre);
}
if (!bd.estaRelacionActor(peli, a)) {
bd.relacionActorPelicula(peli, a);
}
}
sesion.setAttribute("peliculaId", nombre);
response.sendRedirect(response.encodeRedirectURL("/PracticaFinalWeb/pelicula.jsp"));
} catch (Exception e) {
System.out.println("ERROR: " + e.toString());
e.printStackTrace();
}
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
|
package test;
import static org.junit.Assert.*;
import java.util.Arrays;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
import picoplaca.*;
@RunWith(value = Parameterized.class)
public class TimeConvertTest {
private String _input;
private String _expected;
@Parameters
public static Iterable<Object[]> getInput(){
return Arrays.asList(new Object[][]{
{"20:50","20.84"},{"07:20","7.34"},{"14:54","14.90"}});
}
public TimeConvertTest(String input, String expected){
this._input = input;
this._expected = expected;
}
@Test
public void test() {
TimeValidator objTimeValidator = new TimeValidator(_input);
String result = objTimeValidator.convert();
assertEquals("Test Time Convert Error",_expected , result);
}
}
|
package com.fehead.community.mapper;
import com.fehead.community.entities.Club;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
/**
* <p>
* Mapper 接口
* </p>
*
* @author ktoking
* @since 2020-04-03
*/
public interface ClubMapper extends BaseMapper<Club> {
}
|
package com.trump.auction.cust.api.impl;
import com.alibaba.dubbo.config.annotation.Service;
import com.cf.common.utils.ServiceResult;
import com.trump.auction.cust.api.UserRelationStubService;
import com.trump.auction.cust.model.UserRelationModel;
import com.trump.auction.cust.service.UserRelationService;
import org.springframework.beans.factory.annotation.Autowired;
/**
* @description: 用户关系
* @author: zhangqingqiang
* @date: 2018-03-31 14:38
**/
@Service(version = "1.0.0")
public class UserRelationStubServiceImpl implements UserRelationStubService {
@Autowired
private UserRelationService userRelationService;
@Override
public ServiceResult saveRelation(UserRelationModel userRelationModel) {
return userRelationService.saveRelation(userRelationModel);
}
@Override
public UserRelationModel selectPid(Integer userId) {
return userRelationService. selectPid(userId);
}
}
|
/**
* MIT License
* <p>
* Copyright (c) 2019-2022 nerve.network
* <p>
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* <p>
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
* <p>
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package network.nerve.converter.heterogeneouschain.eth.storage.impl;
import io.nuls.core.core.annotation.Component;
import io.nuls.core.exception.NulsException;
import io.nuls.core.model.ByteUtils;
import io.nuls.core.model.StringUtils;
import io.nuls.core.rockdb.service.RocksDBService;
import network.nerve.converter.constant.ConverterErrorCode;
import network.nerve.converter.heterogeneouschain.eth.constant.EthConstant;
import network.nerve.converter.heterogeneouschain.eth.constant.EthDBConstant;
import network.nerve.converter.heterogeneouschain.eth.context.EthContext;
import network.nerve.converter.heterogeneouschain.eth.model.EthERC20Po;
import network.nerve.converter.heterogeneouschain.eth.storage.EthERC20StorageService;
import network.nerve.converter.model.po.StringSetPo;
import network.nerve.converter.utils.ConverterDBUtil;
import java.util.*;
/**
* @author: Mimi
* @date: 2020-02-20
*/
@Component
public class EthERC20StorageServiceImpl implements EthERC20StorageService {
private final String baseArea = EthDBConstant.DB_ETH;
private final String KEY_PREFIX = "ERC20-";
private final String KEY_ASSETID_PREFIX = "ERC20_ASSETID-";
private final String KEY_SYMBOL_PREFIX = "ERC20_SYMBOL-";
private final byte[] MAX_INITIALIZED_ASSETID_KEY = ConverterDBUtil.stringToBytes("ERC20-MAX_INITIALIZED_ASSETID");
private final byte[] MAX_ASSETID_KEY = ConverterDBUtil.stringToBytes("ERC20-MAX_ASSETID");
private final byte[] HAD_INIT_DB_KEY = ConverterDBUtil.stringToBytes("ERC20-HAD_INIT_DB");
@Override
public int save(EthERC20Po po) throws Exception {
if (po == null) {
return 0;
}
if (isExistsByAssetId(po.getAssetId())) {
EthContext.logger().error("资产ID已存在[{}], 存在的资产详情: {}", po.getAssetId(), this.findByAssetId(po.getAssetId()));
throw new NulsException(ConverterErrorCode.ASSET_ID_EXIST);
}
Map<byte[], byte[]> values = new HashMap<>(8);
String address = po.getAddress();
byte[] addressBytes = ConverterDBUtil.stringToBytes(address);
values.put(ConverterDBUtil.stringToBytes(KEY_PREFIX + address), ConverterDBUtil.getModelSerialize(po));
values.put(ConverterDBUtil.stringToBytes(KEY_ASSETID_PREFIX + po.getAssetId()), addressBytes);
StringSetPo setPo = ConverterDBUtil.getModel(baseArea, ConverterDBUtil.stringToBytes(KEY_SYMBOL_PREFIX + po.getSymbol()), StringSetPo.class);
if (setPo == null) {
setPo = new StringSetPo();
Set<String> set = new HashSet<>();
set.add(address);
setPo.setCollection(set);
values.put(ConverterDBUtil.stringToBytes(KEY_SYMBOL_PREFIX + po.getSymbol()), ConverterDBUtil.getModelSerialize(setPo));
} else {
Set<String> set = setPo.getCollection();
if (set.add(address)) {
values.put(ConverterDBUtil.stringToBytes(KEY_SYMBOL_PREFIX + po.getSymbol()), ConverterDBUtil.getModelSerialize(setPo));
}
}
RocksDBService.batchPut(baseArea, values);
//ConverterDBUtil.putModel(baseArea, stringToBytes(KEY_PREFIX + po.getAddress()), po);
//RocksDBService.put(baseArea, stringToBytes(KEY_ASSETID_PREFIX + po.getAssetId()), stringToBytes(po.getAddress()));
//RocksDBService.put(baseArea, stringToBytes(KEY_SYMBOL_PREFIX + po.getSymbol()), stringToBytes(po.getAddress()));
return 1;
}
@Override
public EthERC20Po findByAddress(String address) {
EthERC20Po po = ConverterDBUtil.getModel(baseArea, ConverterDBUtil.stringToBytes(KEY_PREFIX + address), EthERC20Po.class);
if (po == null) {
return null;
}
po.setAddress(address);
return po;
}
@Override
public void deleteByAddress(String address) throws Exception {
EthERC20Po po = this.findByAddress(address);
if (po == null) {
return;
}
this.deleteAddressByAssetId(po.getAssetId());
this.deleteAddressBySymbol(po.getSymbol(), address);
RocksDBService.delete(baseArea, ConverterDBUtil.stringToBytes(KEY_PREFIX + address));
}
@Override
public boolean isExistsByAddress(String address) {
byte[] bytes = RocksDBService.get(baseArea, ConverterDBUtil.stringToBytes(KEY_PREFIX + address));
if (bytes == null) {
return false;
}
return true;
}
@Override
public EthERC20Po findByAssetId(int assetId) {
String address = this.findAddressByAssetId(assetId);
if (StringUtils.isBlank(address)) {
return null;
}
return this.findByAddress(address);
}
@Override
public void deleteByAssetId(int assetId) throws Exception {
String address = this.findAddressByAssetId(assetId);
if (StringUtils.isBlank(address)) {
return;
}
this.deleteByAddress(address);
}
@Override
public String findAddressByAssetId(int assetId) {
byte[] bytes = RocksDBService.get(baseArea, ConverterDBUtil.stringToBytes(KEY_ASSETID_PREFIX + assetId));
if (bytes == null) {
return null;
}
return ConverterDBUtil.bytesToString(bytes);
}
private void deleteAddressByAssetId(int assetId) throws Exception {
RocksDBService.delete(baseArea, ConverterDBUtil.stringToBytes(KEY_ASSETID_PREFIX + assetId));
}
@Override
public boolean isExistsByAssetId(int assetId) {
byte[] bytes = RocksDBService.get(baseArea, ConverterDBUtil.stringToBytes(KEY_ASSETID_PREFIX + assetId));
if (bytes == null) {
return false;
}
return true;
}
@Override
public List<EthERC20Po> findBySymbol(String symbol) {
Set<String> addressSet = this.findAddressBySymbol(symbol);
if (addressSet == null || addressSet.isEmpty()) {
return null;
}
List<EthERC20Po> erc20PoList = new ArrayList<>(addressSet.size());
for (String address : addressSet) {
erc20PoList.add(this.findByAddress(address));
}
return erc20PoList;
}
private void deleteAddressBySymbol(String symbol, String address) throws Exception {
StringSetPo setPo = ConverterDBUtil.getModel(baseArea, ConverterDBUtil.stringToBytes(KEY_SYMBOL_PREFIX + symbol), StringSetPo.class);
if (setPo != null) {
setPo.getCollection().remove(address);
ConverterDBUtil.putModel(baseArea, ConverterDBUtil.stringToBytes(KEY_SYMBOL_PREFIX + symbol), setPo);
}
}
@Override
public Set<String> findAddressBySymbol(String symbol) {
StringSetPo setPo = ConverterDBUtil.getModel(baseArea, ConverterDBUtil.stringToBytes(KEY_SYMBOL_PREFIX + symbol), StringSetPo.class);
if (setPo == null) {
return null;
}
return setPo.getCollection();
}
@Override
public boolean isExistsBySymbol(String symbol) {
byte[] bytes = RocksDBService.get(baseArea, ConverterDBUtil.stringToBytes(KEY_SYMBOL_PREFIX + symbol));
if (bytes == null) {
return false;
}
return true;
}
@Override
public boolean hadInitDB() {
byte[] bytes = RocksDBService.get(baseArea, HAD_INIT_DB_KEY);
if (bytes == null) {
return false;
}
return true;
}
@Override
public void initDBCompleted(int maxAssetId) throws Exception {
RocksDBService.put(baseArea, HAD_INIT_DB_KEY, EthConstant.EMPTY_BYTE);
RocksDBService.put(baseArea, MAX_INITIALIZED_ASSETID_KEY, ByteUtils.intToBytes(maxAssetId));
}
@Override
public void saveMaxAssetId(int maxAssetId) throws Exception {
RocksDBService.put(baseArea, MAX_ASSETID_KEY, ByteUtils.intToBytes(maxAssetId));
}
@Override
public int getMaxAssetId() throws Exception {
byte[] bytes = RocksDBService.get(baseArea, MAX_ASSETID_KEY);
if(bytes == null) {
int maxAssetId = 1;
saveMaxAssetId(maxAssetId);
return maxAssetId;
}
return ByteUtils.bytesToInt(bytes);
}
@Override
public int getMaxInitializedAssetId() throws Exception {
byte[] bytes = RocksDBService.get(baseArea, MAX_INITIALIZED_ASSETID_KEY);
if(bytes == null) {
int maxAssetId = 1;
saveMaxInitializedAssetId(maxAssetId);
return maxAssetId;
}
return ByteUtils.bytesToInt(bytes);
}
private void saveMaxInitializedAssetId(int maxAssetId) throws Exception {
RocksDBService.put(baseArea, MAX_INITIALIZED_ASSETID_KEY, ByteUtils.intToBytes(maxAssetId));
}
@Override
public List<EthERC20Po> getAllInitializedERC20() throws Exception {
int maxInitializedAssetId = this.getMaxInitializedAssetId();
if (maxInitializedAssetId < 2) {
return Collections.emptyList();
}
List<EthERC20Po> list = new ArrayList<>(maxInitializedAssetId - 1);
for (int i = 2; i <= maxInitializedAssetId; i++) {
EthERC20Po erc20Po = this.findByAssetId(i);
if (erc20Po != null) {
list.add(erc20Po);
}
}
return list;
}
@Override
public void increaseAssetId() throws Exception {
int maxAssetId = this.getMaxAssetId();
maxAssetId++;
this.saveMaxAssetId(maxAssetId);
}
}
|
package net.aphotix.spring.entities;
import net.aphotix.packages.PackageDefinitionDelta;
import javax.persistence.ElementCollection;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import java.util.List;
/**
* The object representation of a package stored in the underlying JPA repository
*
* @author Veil (nathan@aphotix.net).
*/
@Entity
public class StoredPackage implements PackageDefinitionDelta {
@Id
@GeneratedValue
private Long id;
@NotNull
private String name;
@NotNull
private String description;
@NotNull
@Size(min = 1)
@ElementCollection
private List<String> productIds;
@Override
public Long getId() {
return id;
}
@Override
public String getName() {
return name;
}
@Override
public String getDescription() {
return description;
}
@Override
public List<String> getProductIds() {
return productIds;
}
@Override
public void setProductIds(List<String> ids) {
productIds = ids;
}
@Override
public void setName(String name) {
this.name = name;
}
@Override
public void setDescription(String description) {
this.description = description;
}
/**
* Allows the direct setting of an id, should only be called when this object has not originated from the JPA
* layer and is intended as an updated package
*
* @param id The id to set for this package
*/
public void setId(long id) {
this.id = id;
}
}
|
import processing.core.*;
import processing.data.*;
import processing.event.*;
import processing.opengl.*;
import processing.net.*;
import processing.sound.*;
import processing.net.*;
import java.util.HashMap;
import java.util.ArrayList;
import java.io.File;
import java.io.BufferedReader;
import java.io.PrintWriter;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.IOException;
public class GameThing extends PApplet {
/**
* Panels are done, either press on a panel to open it, or use the number keys to toggle them
* scene transition animations work now but need polishing
CHANGELOG:
2.2.2020
- added tree and mountain sprites
2.3.2020
- cleaned up code
- added exit prompt
- made house sprite
*/
PImage backgroundImage;
PFont germanica;
PFont simple;
String scene = "load";
boolean mousePressed = false;
boolean exitGame = false;
/**
used for development only, sends the user into the game on game start
*/
boolean goneToGameOnStart = false;
boolean developerMode = false;
OpenSimplexNoise noise;
float gameZoom = 1;
public void setup () {
germanica = createFont("fonts/Plain Germanica.ttf", 32);
simple = loadFont("fonts/simpleFont.vlw");
// fullScreen(P2D, 1);
background(0);
textFont(germanica);
textAlign(CENTER, CENTER);
splashScreen();
noise = new OpenSimplexNoise();
backgroundImage = loadImage("worldMap.png");
}
public void draw () {
switch (scene) {
case "load":
loadAssets();
splashScreen();
break;
case "menu":
menu();
// if (!goneToGameOnStart) {
// scene = "game"; // FOR DEV
// goneToGameOnStart = true;
// }
break;
case "credits":
creditsScreen();
break;
case "options":
optionsScreen();
break;
case "game":
background(0, 0, 0);
image(terrainImg, 0, 0, width, height); // Draw an image of the terrain, instead of using for loops
tileGrid(); // Update the mouse/tile grid
game();
break;
case "multiplayer":
background(0, 0, 0);
image(terrainImg, 0, 0, width, height); // Draw an image of the terrain, instead of using for loops
tileGrid(); // Update the mouse/tile grid
game();
connectToServer();
break;
}
guiManager(); // Calls all GUI elements
resetInputVariables();
}
/**
Contains all Graphical user interface classes and methods like buttons, modals, the minimap, etc.
*/
class Panel {
int xPosition;
int yPosition;
int panelWidth;
int panelHeight;
boolean active;
boolean goUp = false;
boolean goDown = false;
int animationSpeed = 50;
Panel (int xPosition_, int panelWidth_, int panelHeight_) {
xPosition = xPosition_;
yPosition = height - 30;
panelWidth = panelWidth_;
panelHeight = panelHeight_;
}
public void draw () {
if (!active) {
fill(20);
rect(xPosition, yPosition, panelWidth, panelHeight, 5);
fill(200);
if (mouseX > xPosition && mouseX < xPosition + panelWidth && mouseY > yPosition && mouseY < yPosition + 30) {
strokeWeight(4);
stroke(200);
line(xPosition + panelWidth / 2 - 40, yPosition + 15, xPosition + panelWidth / 2, yPosition + 10); // up arrow
line(xPosition + panelWidth / 2, yPosition + 10, xPosition + panelWidth / 2 + 40, yPosition + 15);
cursor(HAND);
if (mousePressed) {
goUp = true;
buttonClickSound.play();
}
} else {
noStroke();
rect(xPosition + panelWidth / 2 - 40, yPosition + 15, 80, 4);
cursor(ARROW);
}
if (goUp) {
yPosition -= animationSpeed;
if (yPosition + panelHeight < height) {
yPosition = height - panelHeight;
goUp = false;
active = true;
}
}
} else {
fill(20);
rect(xPosition, yPosition, panelWidth, panelHeight, 5);
fill(200);
if (mouseX > xPosition && mouseX < xPosition + panelWidth && mouseY > yPosition && mouseY < yPosition + 30) {
strokeWeight(4);
stroke(200);
line(xPosition + panelWidth / 2 - 40, yPosition + 15, xPosition + panelWidth / 2, yPosition + 20); // down arrow
line(xPosition + panelWidth / 2, yPosition + 20, xPosition + panelWidth / 2 + 40, yPosition + 15);
cursor(HAND);
if (mousePressed) {
goDown = true;
buttonClickSound.play();
}
} else {
noStroke();
rect(xPosition + panelWidth / 2 - 40, yPosition + 15, 80, 4);
cursor(ARROW);
}
if (goDown) {
yPosition += animationSpeed;
if (yPosition + 30 > height) {
yPosition = height - 30;
goDown = false;
active = false;
}
}
}
noStroke();
}
}
class Button {
float xPosition = 0;
float yPosition = 0;
boolean pressed = false;
int buttonWidth;
int buttonHeight;
String buttonTitle;
float buttonHoverY = 0;
Button (float xPos, float yPos, int btnWidth, int btnHeight, String btnTitle){
xPosition = xPos;
yPosition = yPos;
buttonTitle = btnTitle;
buttonWidth = btnWidth;
buttonHeight = btnHeight;
};
public void draw (){
if (mouseX > xPosition && mouseX < xPosition + buttonWidth && mouseY > yPosition && mouseY < yPosition + buttonHeight) {
fill(50);
if(mousePressed) {
buttonClickSound.play();
pressed = true;
transitionStage = 1;
}
} else {
fill(38);
pressed = false;
}
noStroke();
rect(xPosition, yPosition, buttonWidth, buttonHeight, 5);
textAlign(CENTER, CENTER);
fill(200);
textSize(25);
text(buttonTitle, xPosition + buttonWidth/2, yPosition + buttonHeight/2);
}
}
int switchBtnColor = color(255);
class SwitchBtn {
int x, y;
// int bx, by;
Boolean active;
int slider;
int sliderColor;
boolean done;
String title;
SwitchBtn(int X, int Y, String _title) {
x = X;
y = Y;
// bx = X;
// by = Y;
active = false;
slider = 0;
sliderColor = switchBtnColor;
done = false;
title = _title;
}
public void draw () {
// fill(33);
noFill();
stroke(switchBtnColor);
strokeWeight(5);
if (mouseX > x - 2 && mouseX < x + 42 && mouseY > y - 2 && mouseY < y + 21) {
cursor(HAND);
if (mousePressed && !active && !done) {
active = true; //turn it on
done = true;
} else if (mousePressed && done && active) {
done = false;
active = false;//turn it off
}
} else {
cursor(ARROW);
}
if (active && done) {
active = true;
sliderColor = color(50);
slider += 2;
if (slider > 20) {
slider = 20;
done = true;
}
fill(switchBtnColor);
} else {
sliderColor = switchBtnColor;
slider -= 2;
if (slider < 0) {
slider = 0;
done = false;
}
} //off
rect(x, y, 40, 19, 10);
pushMatrix();
translate(x + 10, y + 10);
noStroke();
fill(sliderColor);
ellipse(slider, 0, 10, 10);
popMatrix();
textFont(simple);
textAlign(LEFT, CENTER);
textSize(18);
fill(255);
text("" + title, x + 50, y + 19/2);
//return active;
}
}
class Slider {
int value;
int max;
int x, y;
Slider(int X, int Y, int Max){
value = 150;
max = Max;
x = X;
y = Y;
}
public int round10(final int n) {
return (n + 5) / 10 * 10;
}
public void draw () {
fill(255);
rect(x, y, max, 7, 20);
fill(150);
rect(value, y, max - value + 22, 7, 20);
fill(255);
ellipse(value, y + 7/2, 15, 15);
int current = round10(value - 22);
textAlign(TOP, LEFT);
text(round(current * 0.666666667f) + "%", 178, 68);
if (mouseX > x && mouseX < x + max) {
if (mouseY > y - 15 && mouseY < y + 15) {
if (mousePressed) {
value = mouseX;
// VLCInstance.setVolume(round(value));
}
}
}
}
}
float closeGameOpacity = 2.1f;
public void closeGame () {
fill(0, 0, 0, closeGameOpacity);
rect(0, 0, width, height);
closeGameOpacity *= 1.073f;
if (closeGameOpacity < 100) {
closeGameOpacity += 2;
} else if (closeGameOpacity > 355) {
logEvent("User closed game", 'i');
exit();
}
}
public void closeGamePrompt () {
fill(0, 0, 0, closeGameOpacity);
rectMode(CENTER);
rect(width/2, height/2, width/3 - 50, height/3 - 50, 10);
rectMode(CORNER);
fill(255, 255, 255, closeGameOpacity + 55);
textAlign(CENTER, CENTER);
textSize(width/70);
textFont(germanica);
text("Do you want to close the game?", width/2, height/2 - 40);
closeGameOpacity *= 1.073f;
if (closeGameOpacity < 100) {
closeGameOpacity += 2;
} else if (closeGameOpacity > 200) {
closeGameOpacity = 200;
exitPromptYes.draw();
exitPromptNo.draw();
if (exitPromptYes.pressed) {
exit();
} else if (exitPromptNo.pressed){
exitPromptNo.pressed = false;
exitGamePrompt = false;
closeGameOpacity = 0;
}
}
textFont(simple);
}
float screenOverlayOpacity = 0;
int transitionStage = 1;
float transitionSpeed = 15;
public void gotoScene (String nextScene) {
fill(0, 0, 0, screenOverlayOpacity);
rect(0, 0, width, height);
switch (transitionStage) {
case 1:
screenOverlayOpacity += 3;
if (screenOverlayOpacity >= 40) {
transitionStage = 2;
}
break;
case 2:
screenOverlayOpacity += transitionSpeed;
if (screenOverlayOpacity >= 255) {
transitionStage = 3;
logEvent("transitioning from: " + scene + " to: " + nextScene, 'i');
scene = nextScene;
screenOverlayOpacity = 255;
}
break;
default:
logEvent("Unable to transition to scene: " + nextScene + ". Defaulting to menu scene.", 'e');
scene = "menu";
break;
}
} // smoothly transition from scene to scene with fade
public void finishTransition () {
fill(0, 0, 0, screenOverlayOpacity);
rect(0, 0, width, height);
switch (transitionStage) {
case 3:
screenOverlayOpacity -= transitionSpeed - 5.2f;
if (screenOverlayOpacity <= 7) {
transitionStage = 4;
}
break;
case 4:
screenOverlayOpacity --;
if (screenOverlayOpacity <= 0) {
screenOverlayOpacity = 0;
transitionStage = 1;
}
break;
}
}
Panel economics;
Panel military;
Panel networkStats;
Button dock;
Button mill;
Button farm;
Button toggleDevMode;
Button exitGameButton;
Button menu; // in game button to return to menu
Button menuFromCredits; // button to return to menu from credits screen
boolean exitGamePrompt = false;
Button exitPromptYes;
Button exitPromptNo;
boolean GUI_OBJECTS_INITIALIZED = false;
boolean OPTIONS_GUI_OBJECTS_INITIALIZED = false;
public void guiManager () {
if (!GUI_OBJECTS_INITIALIZED) {
dock = new Button(270, 5, 90, 35, "Dock");
mill = new Button(370, 5, 190, 35, "Lumber Mill");
farm = new Button(570, 5, 90, 35, "Farm");
exitGameButton = new Button(width - 100, 5, 90, 35, "Exit");
toggleDevMode = new Button(width - 320, 5, 210, 35, "Developer Mode");
menu = new Button(width - 420, 5, 90, 35, "Menu");
networkStats = new Panel(50, width / 2 - 100, 500);
economics = new Panel(50, width / 2 - 100, 500);
military = new Panel(width / 2 + 50, width / 2 - 100, 500);
menuFromCredits = new Button(width / 2 - 60, height - 100, 120, 40, "Back");
exitPromptYes = new Button(width/2 + 10, height/2, 120, 40, "Yes");
exitPromptNo = new Button(width/2 - 130, height/2, 120, 40, "No");
logEvent("GUI objects initialized", 's');
GUI_OBJECTS_INITIALIZED = true;
}
if (scene == "game") {
if (exitGameButton.pressed) {
exitGame = true;
}
if (toggleDevMode.pressed) {
}
if (menu.pressed) {
gotoMainMenu = true;
goneToGameOnStart = true;
}
economics.draw(); // Panels
military.draw();
fill(20); // Top bar
rect(0, 0, width, 45);
dock.draw(); // Buttons
mill.draw();
farm.draw();
exitGameButton.draw();
toggleDevMode.draw();
menu.draw();
textFont(simple);
textSize(15);
textAlign(CORNER);
text("Gold: " + gold.amountCollected + " | Food: " + food.amountCollected + " | Wood: " + wood.amountCollected, 10, 30);
// HoveredTile tooltip
fill(20, 20, 20, 100);
rect(mouseX + 13, mouseY - 10, 100, 30);
fill(255);
textAlign(LEFT, CENTER);
String hoveredTileType = null;
switch (hoveredTile) {
case 't':
hoveredTileType = "Forest";
break;
case 'g':
hoveredTileType = "Grass";
break;
case 's':
hoveredTileType = "Sand";
break;
case 'w':
hoveredTileType = "Water";
break;
case 'm':
hoveredTileType = "Mountain";
break;
}
text(hoveredTileType + " tile", mouseX + 15, mouseY + 4);
}
if (scene == "credits") {
menuFromCredits.draw();
if (menuFromCredits.pressed) {
gotoMainMenu = true;
}
}
if (scene == "multiplayer") {
networkStats.draw();
if (networkStats.active) {
if (localClient.available() > 0) {
text(localClient.readString(), 100, height - 300);
}
}
}
sceneTransitions();
if (exitGamePrompt) {
closeGamePrompt();
}
if (exitGame) {
closeGame();
}
}
public void sceneTransitions () {
if (gotoGame) {
gotoScene("game");
if (scene == "game") {
gotoGame = false;
}
} if (gotoMultiplayerScene) {
gotoScene("multiplayer");
if (scene == "multiplayer") {
gotoMultiplayerScene = false;
}
} if (gotoCreditsScene) {
gotoScene("credits");
if (scene == "credits") {
gotoCreditsScene = false;
}
} if (gotoOptionsScene) {
gotoScene("options");
if (scene == "options") {
gotoOptionsScene = false;
}
} if (gotoMainMenu) {
gotoScene("menu");
if (scene == "menu") {
gotoMainMenu = false;
}
}
finishTransition();
}
SwitchBtn soundEffects;
Button menuFromOptions; // button to return to menu from credits screen
public void optionsScreenGuiManager () {
if (!OPTIONS_GUI_OBJECTS_INITIALIZED) {
soundEffects = new SwitchBtn(130, 130, "Sound effects");
menuFromOptions = new Button(width - 200, height - 150, 90, 40, "Back");
OPTIONS_GUI_OBJECTS_INITIALIZED = true;
}
soundEffects.draw();
menuFromOptions.draw();
if (menuFromOptions.pressed) {
gotoMainMenu = true;
}
}
int startingResources = 200;
boolean givenStartingResources = false;
public void game () {
gold.computeAmounts();
food.computeAmounts();
wood.computeAmounts();
// Starting resources
if (!givenStartingResources) {
gold.addResource(100);
food.addResource(100);
wood.addResource(100);
givenStartingResources = true;
}
}
float mouseScroll = 0;
public void mouseWheel(MouseEvent event) {
mouseScroll = event.getCount();
if (scene == "game") {
if (mouseScroll >= 1) {
gameZoom -= 0.1f;
}
if (mouseScroll <= -1) {
gameZoom += 0.1f;
}
}
}
public void mousePressed () {
mousePressed = true;
}
public void resetInputVariables () {
/**
called once at the end of the draw.
use to reset input variables only
*/
mouseScroll = 0;
mousePressed = false;
}
public void keyPressed() {
if (scene == "game") {
if (keyCode == '1') {
if (economics.active) {
economics.goDown = true;
} else {
economics.goUp = true;
}
}
if (keyCode == '2') {
if (military.active) {
military.goDown = true;
} else {
military.goUp = true;
}
}
}
if (key == ESC) {
key = 0;
exitGamePrompt = true;
}
}
String backgroundMusicPath = "backgroundMusic.mp3";
SoundFile backgroundMusic;
SoundFile buttonClickSound;
boolean initialized = false;
float splashScreenAlpha = 255;
PImage mountainSprite;
PImage tree1Sprite;
PImage tree2Sprite;
PImage houseSprite;
boolean heightmapCreated = false;
PImage terrainImg;
public void splashScreen () {
if (!initialized) {
background(0);
fill(255);
text("Game Studio", width/2, height/2);
} else {
image(terrainImg, 0, 0, width, height); // change to the menu background later
fill(0, 0, 0, splashScreenAlpha);
rect(0, 0, width, height);
fill(255, 255, 255, splashScreenAlpha);
text("Game Studio", width/2, height/2);
splashScreenAlpha /= 1.02f;
if (splashScreenAlpha < 160) {
splashScreenAlpha -= 2;
}
if (splashScreenAlpha <= 3 || developerMode) {
scene = "menu";
}
}
}
public void loadAssets () {
if (!initialized) {
// load music
// backgroundMusic = new SoundFile(this, "sounds/music/backgroundMusic.mp3");
// backgroundMusic.play();
// backgroundMusic.loop();
buttonClickSound = new SoundFile(this, "sounds/effects/ButtonClick.mp3");
mountainSprite = loadImage("images/sprites/world/mtn.png");
tree1Sprite = loadImage("images/sprites/world/tree.png");
tree2Sprite = loadImage("images/sprites/world/twoTrees.png");
houseSprite = loadImage("images/sprites/buildings/house.png");
// create heightmap
if (!heightmapCreated) {
createHeightMapValues(); // Generate noise values for heightmap
drawHeightMap(); // Draw using for loops once
terrainImg = get(0, 0, width, height); // Create an image of the terrain
heightmapCreated = true; // Never call this again
logEvent("Heightmap created", 's');
}
logEvent("Finished loading assets", 's');
initialized = true;
}
}
float menuButtonBackgroundOpacity = 1.1f;
String menuButtonTitles[] = {"Campaign", "Multiplayer", "options", "credits", "Exit to Desktop"};
Button menuButtons[] = new Button[7];
int buttonCount = 0;
boolean gotoCreditsScene = false;
boolean gotoGame = false;
boolean gotoMainMenu = false;
boolean gotoOptionsScene = false;
boolean gotoMultiplayerScene = false;
boolean buttonObjectsInitialized = false;
public void createMenuButton (int x, int y, int btnWidth, int btnHeight, String title) {
menuButtons[buttonCount] = new Button(x, y, btnWidth, btnHeight, title);
if (buttonCount < menuButtons.length - 1) {
buttonCount += 1;
}
}
public void menu () {
// create the button objects
if (!buttonObjectsInitialized) {
for (int i = 0; i < menuButtonTitles.length; i ++) {
createMenuButton(200, i * 100 - 600, 230, 60, menuButtonTitles[i]);
}
if (buttonCount >= 6) {
buttonObjectsInitialized = true;
}
}
// Animate the elements
menuButtonBackgroundOpacity *= 1.08f;
menuButtonBackgroundOpacity ++;
if (menuButtonBackgroundOpacity > 100) {
menuButtonBackgroundOpacity = 100;
}
if (menuButtons[0].yPosition <= 200) {
for (int i = 0; i < buttonCount - 1; i ++) {
menuButtons[i].yPosition += 15;
}
}
// Draw the stuff
image(terrainImg, 0, 0, width, height);
fill(0, 0, 0, menuButtonBackgroundOpacity);
rect(170, 0, 290, height);
textFont(germanica);
fill(255);
text("GameThing", 315, menuButtons[0].yPosition - 50);
for (int i = 0; i < buttonCount - 1; i ++) {
menuButtons[i].draw();
}
// register clicks
if (menuButtons[0].pressed) {
gotoGame = true;
} if (menuButtons[1].pressed) {
gotoMultiplayerScene = true;
} if (menuButtons[2].pressed) {
gotoOptionsScene = true;
} if (menuButtons[3].pressed) {
gotoCreditsScene = true;
} if (menuButtons[4].pressed) {
exitGame = true;
}
}
String ANSI_RESET = "\u001B[0m";
String ANSI_RED = "\u001B[31m";
String ANSI_GREEN = "\u001B[32m";
String ANSI_YELLOW = "\u001B[33m";
String ANSI_BLUE = "\u001B[34m";
String ANSI_WHITE = "\u001B[37m";
public void logEvent (String log, char type) {
String ANSI_COLOR = ANSI_WHITE;
String logType = "[INFO]";
switch (type) {
case 's':
ANSI_COLOR = ANSI_GREEN;
logType = "[SUCCESS]";
break;
case 'i':
ANSI_COLOR = ANSI_BLUE;
logType = "[INFO]";
break;
case 'w':
ANSI_COLOR = ANSI_YELLOW;
logType = "[WARNING]";
break;
case 'e':
ANSI_COLOR = ANSI_RED;
logType = "[ERROR]";
break;
case 'f':
ANSI_COLOR = ANSI_RED;
logType = "[FATAL]";
break;
}
println(ANSI_COLOR + logType + " " + log + ANSI_RESET);
}
/**
This code can sucessfully receive messages from chatApp
requires port 8080 to be open so that you can connect over the WWW.
figure out if LAN reuires a port.
*/
Client localClient;
String serverAddress = "68.185.198.252";
int defaultPort = 8080;
boolean connectedToServer = false;
public void connectToServer () {
if (!connectedToServer) {
try {
logEvent("Attempting to connet to server " + serverAddress + " on port " + defaultPort, 'i');
localClient = new Client(this, serverAddress, defaultPort); // EDIT - SEE TODO
connectedToServer = true;
} catch (Exception e) {
logEvent("Couldn't connect to server " + serverAddress + " on port " + defaultPort + "\n" + e, 'w'); // EDIT THIS PLEASE!!!!!
}
}
if (localClient.available() > 0) {
println(localClient.readString());
}
}
Gold gold = new Gold();
Wood wood = new Wood();
Food food = new Food();
class Resource {
int amountCollected;
int increase; // Per second
Resource () {
}
public void computeAmounts () {
amountCollected += increase;
}
public void addResource (int amount) {
amountCollected += amount;
}
public void removeResource (int amount) {
amountCollected -= amount;
}
}
class Gold extends Resource {
}
class Wood extends Resource {
}
class Food extends Resource {
}
float creditTextOpacity = 0;
public void creditsScreen () {
textFont(simple);
background(0);
textSize(width/70);
fill(255, 255, 255, creditTextOpacity);
text("Programming:\nEthan Grandin \nAsher Haun\n\nMusic:\nNightrain - Airtone\n\nLibraries:\nOpen Simplex Noise\nProcessing 3", width / 2, height / 2);
creditTextOpacity += 3;
}
public void optionsScreen () {
image(terrainImg, 0, 0, width, height);
fill(0, 0, 0, 100);
rect(100, 100, width - 200, height - 200);
optionsScreenGuiManager();
}
/** Create Heightmap and save to a PImage */
int chunkWidth = 900; // chunkSize * blockSize should fill the entire screen
int chunkHeight = 600;
int blockSize = width/27;
// int blockSize = 10;
float increment = 0.013f; // the fineness of the noise map
float[][] terrain = new float[chunkWidth][chunkHeight]; // create an empty 2D array with the dimensions of chunkSize
public void createHeightMapValues () {
float yoff = 0;
// these loops fill the terrain array with a perlin noise map, that creates integer height values between 0 and 100
for (int x = 0; x < chunkWidth; x ++) {
float xoff = 0;
for (int y = 0; y < chunkHeight; y ++) {
terrain[x][y] = map(noise(xoff, yoff), 0, 1, 0, 50);
terrain[x][y] += map((float) noise.eval(xoff, yoff), -1, 1, 0, 50);
xoff += increment;
}
yoff += increment;
}
};
// these are the height levels that change the color of individual tiles according to the terrain array
float deepWater = 67;
float shallowWater = 60;
float sand = 57;
float grass = 40;
float treeline = 0;
public void drawHeightMap () {
for (int x = 0; x < chunkWidth; x ++) {
for (int y = 0; y < chunkHeight; y ++) {
// changes the rect fill based on the height given by each index in terrain at x, y
if (terrain[x][y] >= deepWater) {
fill(35, 81, 128); // deep water
} else if (terrain[x][y] >= shallowWater) {
fill(37, 91, 148); // shallow water
} else if (terrain[x][y] >= sand) {
fill(199, 174, 46); // sand
} else if (terrain[x][y] >= grass) {
fill(31, 97, 9); // light green grass
} else if (terrain[x][y] >= treeline) {
fill(34, 77, 19); // dark green grass
}
noStroke();
rect(x * blockSize, y * blockSize, 40, 40);
// fill(0, 0, 0, random(0, 30));
// rect(x * blockSize, y * blockSize, 40, 40);
}
}
};
/** Draw the grid the player interacts with and draw sprites */
String currentMouseTile;
//char[][] tileMap = new char[chunkWidth][chunkHeight];
int tileSize = 10;
char[][] tileMap = new char[chunkWidth][chunkHeight]; // create an empty 2D array with the dimensions of chunkSize
char hoveredTile = 'x';
boolean createdSpriteLocations = false;
int[] displayMountainSprite = {30};
int[][] treeType = new int[chunkWidth][chunkHeight]; // create an empty 2D array with the dimensions of chunkSize
public void tileGrid () {
int increment = tileSize;
for (int x = 0; x < chunkWidth; x += increment) {
for (int y = 0; y < chunkHeight; y += increment) {
// Check the index in terrain every ten (or whatever value is within increment)
noFill();
if (tileMap[x][y] != 'm') {
if (terrain[x][y] >= treeline) {
tileMap[x][y] = 't';
} if (terrain[x][y] >= grass - 1) {
tileMap[x][y] = 'g';
} if (terrain[x][y] >= sand - 3) {
tileMap[x][y] = 's';
} if (terrain[x][y] >= deepWater - 2) {
tileMap[x][y] = 'w';
}
}
if (!createdSpriteLocations) {
if (random(0, 10) < 0.3f && terrain[x][y] < deepWater - 10) {
tileMap[x][y] = 'm';
}
if (terrain[x][y] >= treeline) {
if (random(0, 10) < 5) {
treeType[x][y] = 1;
} else {
treeType[x][y] = 2;
}
}
if (x > chunkWidth - increment*3 && y > chunkHeight/2) {
createdSpriteLocations = true;
}
}
strokeWeight(1);
noStroke();
int tileX = x * tileSize / increment * blockSize - tileSize;
int tileY = y * tileSize / increment * blockSize - tileSize;
int ts = tileSize * blockSize;
if (mouseX > tileX && mouseY > tileY && mouseX < tileX + ts && mouseY < tileY + ts) {
fill(0, 0, 0, 100);
hoveredTile = tileMap[x][y];
} else {
noFill();
}
rect(tileX, tileY, ts, ts);
fill(20, 20, 20, 200);
textAlign(CENTER, CENTER);
// text(tileMap[x][y], tileX + ts / 2, tileY + ts / 2);
if (tileMap[x][y] == 'm') {
// println("called: X: " + x + ", Y: " + y);
image(mountainSprite, tileX, tileY);
}
if (tileMap[x][y] == 't') {
if (treeType[x][y] == 1) {
image(tree1Sprite, tileX, tileY);
} else {
image(tree2Sprite, tileX, tileY);
}
}
}
}
}
public void settings() { size(1600, 900, P2D); }
static public void main(String[] passedArgs) {
String[] appletArgs = new String[] { "GameThing" };
if (passedArgs != null) {
PApplet.main(concat(appletArgs, passedArgs));
} else {
PApplet.main(appletArgs);
}
}
}
|
package br.com.kessel.test;
import br.com.kessel.controller.SetupController;
public class TestClassSetup {
public static void main(String[] args) {
SetupController sc = new SetupController();
sc.read();
}
}
|
/*
* 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 view;
import controller.ItemvendaJpaController;
import controller.ProdutoJpaController;
import controller.VendasJpaController;
import java.awt.event.KeyEvent;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import model.domain.Itemvenda;
import model.domain.Produto;
import model.domain.Vendas;
/**
*
* @author Danie
*/
public class VendasView extends javax.swing.JInternalFrame {
/**
* Creates new form Teste
*/
private ProdutoJpaController produtoJpaController;
private VendasJpaController vendasJpaController;
private ItemvendaJpaController itemvendaJpaController;
public VendasView() {
produtoJpaController = new ProdutoJpaController();
vendasJpaController = new VendasJpaController();
itemvendaJpaController = new ItemvendaJpaController();
initComponents();
}
public ProdutoJpaController getProdutoscontroller() {
return produtoJpaController;
}
public VendasJpaController getVendasJpaController() {
return vendasJpaController;
}
public ItemvendaJpaController getItemvendaJpaController() {
return itemvendaJpaController;
}
/**
* 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() {
bindingGroup = new org.jdesktop.beansbinding.BindingGroup();
textDescricao = new javax.swing.JTextField();
textUnidade = new javax.swing.JTextField();
textCodigoBarra = new javax.swing.JTextField();
textValorTotalCompra = new javax.swing.JTextField();
textQuantidade = new javax.swing.JTextField();
textValorUniario = new javax.swing.JTextField();
jScrollPane1 = new javax.swing.JScrollPane();
jTable1 = new javax.swing.JTable();
textValorTotalItem = new javax.swing.JTextField();
jButton1 = new javax.swing.JButton();
jButton2 = new javax.swing.JButton();
jButton3 = new javax.swing.JButton();
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
jLabel5 = new javax.swing.JLabel();
jLabel6 = new javax.swing.JLabel();
jLabel7 = new javax.swing.JLabel();
jLabel8 = new javax.swing.JLabel();
jButton4 = new javax.swing.JButton();
jButton5 = new javax.swing.JButton();
setClosable(true);
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
setTitle("FRENTE DE CAIXA");
textDescricao.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N
textDescricao.setHorizontalAlignment(javax.swing.JTextField.LEFT);
textUnidade.setFont(new java.awt.Font("Tahoma", 0, 15)); // NOI18N
textUnidade.setHorizontalAlignment(javax.swing.JTextField.LEFT);
textUnidade.setText("UN");
textCodigoBarra.setHorizontalAlignment(javax.swing.JTextField.RIGHT);
textCodigoBarra.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
textCodigoBarraActionPerformed(evt);
}
});
textCodigoBarra.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(java.awt.event.KeyEvent evt) {
textCodigoBarraKeyPressed(evt);
}
});
textValorTotalCompra.setFont(new java.awt.Font("Tahoma", 0, 36)); // NOI18N
textValorTotalCompra.setForeground(new java.awt.Color(255, 0, 51));
textValorTotalCompra.setHorizontalAlignment(javax.swing.JTextField.RIGHT);
textValorTotalCompra.setText("0.00");
textQuantidade.setFont(new java.awt.Font("Tahoma", 0, 15)); // NOI18N
textQuantidade.setHorizontalAlignment(javax.swing.JTextField.RIGHT);
textQuantidade.setText("1");
textQuantidade.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(java.awt.event.KeyEvent evt) {
textQuantidadeKeyPressed(evt);
}
});
textValorUniario.setFont(new java.awt.Font("Tahoma", 0, 15)); // NOI18N
textValorUniario.setHorizontalAlignment(javax.swing.JTextField.RIGHT);
textValorUniario.setText("0");
jTable1.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null, null, null},
{null, null, null, null},
{null, null, null, null},
{null, null, null, null}
},
new String [] {
"Title 1", "Title 2", "Title 3", "Title 4"
}
));
org.jdesktop.beansbinding.ELProperty eLProperty = org.jdesktop.beansbinding.ELProperty.create("${itemvendaJpaController.itemVendas}");
org.jdesktop.swingbinding.JTableBinding jTableBinding = org.jdesktop.swingbinding.SwingBindings.createJTableBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, eLProperty, jTable1);
org.jdesktop.swingbinding.JTableBinding.ColumnBinding columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${nomeProduto}"));
columnBinding.setColumnName("Nome Produto");
columnBinding.setColumnClass(String.class);
columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${unidadeProduto}"));
columnBinding.setColumnName("Unidade Produto");
columnBinding.setColumnClass(String.class);
columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${quantidadeProduto}"));
columnBinding.setColumnName("Quantidade Produto");
columnBinding.setColumnClass(Double.class);
columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${valorUnitario}"));
columnBinding.setColumnName("Valor Unitario");
columnBinding.setColumnClass(Double.class);
columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${valorTotal}"));
columnBinding.setColumnName("Valor Total");
columnBinding.setColumnClass(Double.class);
bindingGroup.addBinding(jTableBinding);
jTableBinding.bind();
jScrollPane1.setViewportView(jTable1);
textValorTotalItem.setFont(new java.awt.Font("Tahoma", 0, 36)); // NOI18N
textValorTotalItem.setHorizontalAlignment(javax.swing.JTextField.RIGHT);
textValorTotalItem.setText("0.00");
textValorTotalItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
textValorTotalItemActionPerformed(evt);
}
});
textValorTotalItem.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(java.awt.event.KeyEvent evt) {
textValorTotalItemKeyPressed(evt);
}
});
jButton1.setText("Nova venda");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jButton2.setText("Receber a vista");
jButton2.setEnabled(false);
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(evt);
}
});
jButton3.setText("Receber com cartão");
jButton3.setEnabled(false);
jButton3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton3ActionPerformed(evt);
}
});
jLabel1.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
jLabel1.setText("Codigo do produto");
jLabel2.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
jLabel2.setText("Descrição do produto");
jLabel3.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
jLabel3.setText("Quantidade");
jLabel4.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
jLabel4.setText("Unidade");
jLabel5.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
jLabel5.setText("Valor Unitário");
jLabel6.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
jLabel6.setText("Valor Total Item");
jLabel7.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
jLabel7.setText("Valor total da venda");
jLabel8.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
jLabel8.setText("Lista de produtos");
jButton4.setText("Calcular Balança");
jButton4.setEnabled(false);
jButton4.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton4ActionPerformed(evt);
}
});
jButton5.setText("Adicionar");
jButton5.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton5ActionPerformed(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()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(20, 20, 20)
.addComponent(jButton1)
.addGap(18, 18, 18)
.addComponent(jButton2)
.addGap(43, 43, 43)
.addComponent(jButton3)
.addGap(33, 33, 33)
.addComponent(jButton4)
.addGap(0, 0, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(textCodigoBarra, javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(textValorUniario, javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(textDescricao, javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(textQuantidade, javax.swing.GroupLayout.PREFERRED_SIZE, 171, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel1)
.addComponent(jLabel2)
.addComponent(jLabel3))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel4)
.addComponent(textUnidade, javax.swing.GroupLayout.PREFERRED_SIZE, 156, javax.swing.GroupLayout.PREFERRED_SIZE))))
.addGap(24, 24, 24))
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel5)
.addGroup(layout.createSequentialGroup()
.addComponent(textValorTotalItem, javax.swing.GroupLayout.PREFERRED_SIZE, 283, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jButton5)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel6)
.addGap(286, 286, 286)))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(textValorTotalCompra)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel7)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel8))
.addGap(0, 0, Short.MAX_VALUE)))))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel8)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(textCodigoBarra, javax.swing.GroupLayout.PREFERRED_SIZE, 44, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel2)
.addGap(5, 5, 5)
.addComponent(textDescricao, javax.swing.GroupLayout.PREFERRED_SIZE, 44, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(3, 3, 3)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel3)
.addComponent(jLabel4))
.addGap(1, 1, 1)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(textQuantidade, javax.swing.GroupLayout.PREFERRED_SIZE, 44, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(textUnidade, javax.swing.GroupLayout.PREFERRED_SIZE, 44, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jLabel5)
.addGap(1, 1, 1)
.addComponent(textValorUniario, javax.swing.GroupLayout.PREFERRED_SIZE, 44, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel6)
.addComponent(jLabel7))
.addGap(3, 3, 3)
.addComponent(textValorTotalItem, javax.swing.GroupLayout.PREFERRED_SIZE, 87, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 393, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(textValorTotalCompra, javax.swing.GroupLayout.PREFERRED_SIZE, 87, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton5))))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 19, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButton1)
.addComponent(jButton2)
.addComponent(jButton3)
.addComponent(jButton4))
.addGap(25, 25, 25))
);
bindingGroup.bind();
pack();
}// </editor-fold>//GEN-END:initComponents
private void textValorTotalItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_textValorTotalItemActionPerformed
}//GEN-LAST:event_textValorTotalItemActionPerformed
private void textCodigoBarraKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_textCodigoBarraKeyPressed
if(evt.getKeyCode() == KeyEvent.VK_ENTER) {
Produto prod = this.produtoJpaController.findProduto(Integer.valueOf(this.textCodigoBarra.getText()));
this.textCodigoBarra.setText(String.valueOf(prod.getIdProduto()));
this.textDescricao.setText(prod.getNomeProduto());
this.textUnidade.setText(prod.getUnidadeProduto());
this.textValorUniario.setText(String.valueOf(prod.getValorPoduto()));
this.textValorTotalItem.setText(String.valueOf(Double.valueOf(this.textQuantidade.getText()) * prod.getValorPoduto()));
if(prod.getUnidadeProduto().equals("KG")){
System.out.print(prod.getUnidadeProduto());
this.jButton4.setEnabled(true);
} else {
this.jButton4.setEnabled(false);
}
}
}//GEN-LAST:event_textCodigoBarraKeyPressed
private void textQuantidadeKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_textQuantidadeKeyPressed
if(!this.textQuantidade.getText().isEmpty()) {
this.textValorTotalItem.setText(String.valueOf(Double.valueOf(this.textQuantidade.getText()) * Double.valueOf(this.textValorUniario.getText())));
}
}//GEN-LAST:event_textQuantidadeKeyPressed
private void textValorTotalItemKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_textValorTotalItemKeyPressed
if(evt.getKeyCode() == KeyEvent.VK_ENTER) {
Produto prod = this.produtoJpaController.findProduto(Integer.valueOf(this.textCodigoBarra.getText()));
try {
this.itemvendaJpaController.create(new Itemvenda(Integer.valueOf(this.textCodigoBarra.getText()), this.vendasJpaController.getVendasCount(), Double.valueOf(this.textQuantidade.getText()), Double.valueOf(this.textValorTotalItem.getText()), prod.getNomeProduto(), prod.getValorPoduto(), prod.getUnidadeProduto()));
this.textCodigoBarra.setText(null);
this.textDescricao.setText(null);
this.textUnidade.setText(null);
this.textValorUniario.setText(null);
this.textValorTotalItem.setText(null);
this.itemvendaJpaController.limparLista();
this.jButton2.setEnabled(true);
this.jButton3.setEnabled(true);
this.textValorTotalCompra.setText(String.valueOf(this.itemvendaJpaController.getValorItems()));
} catch (Exception ex) {
Logger.getLogger(VendasView.class.getName()).log(Level.SEVERE, null, ex);
}
}
}//GEN-LAST:event_textValorTotalItemKeyPressed
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
double valorTroco;
double valorPago = Double.valueOf(JOptionPane.showInputDialog(null, "Qual o valor que deseja receber? O valor a ser pago é R$"+this.textValorTotalCompra.getText()));
valorTroco = Double.valueOf(this.textValorTotalCompra.getText()) - valorPago;
JOptionPane.showMessageDialog(null, "Valor do troco: R$"+ valorTroco);
try {
this.vendasJpaController.create(new Vendas(1, Double.valueOf(this.textValorTotalCompra.getText()), Double.valueOf(valorPago), Double.valueOf(valorTroco), "Dinheiro", new Date()));
this.textCodigoBarra.setText(null);
this.textDescricao.setText(null);
this.textUnidade.setText(null);
this.textValorUniario.setText(null);
this.textValorTotalItem.setText(null);
this.itemvendaJpaController.limparLista();
this.textValorTotalCompra.setText(null);
this.jButton2.setEnabled(false);
this.jButton3.setEnabled(false);
} catch (Exception ex) {
Logger.getLogger(VendasView.class.getName()).log(Level.SEVERE, null, ex);
}
}//GEN-LAST:event_jButton2ActionPerformed
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
try {
this.vendasJpaController.create(new Vendas(1, Double.valueOf(this.textValorTotalCompra.getText()), Double.valueOf(this.textValorTotalCompra.getText()), Double.valueOf(0), "Cartão", new Date()));
JOptionPane.showMessageDialog(null, "Venda com cartão realizada com sucesso");
this.textCodigoBarra.setText(null);
this.textDescricao.setText(null);
this.textUnidade.setText(null);
this.textValorUniario.setText(null);
this.textValorTotalItem.setText(null);
this.itemvendaJpaController.limparLista();
this.textValorTotalCompra.setText(null);
this.jButton2.setEnabled(false);
this.jButton3.setEnabled(false);
} catch (Exception ex) {
Logger.getLogger(VendasView.class.getName()).log(Level.SEVERE, null, ex);
}
}//GEN-LAST:event_jButton3ActionPerformed
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
try {
this.vendasJpaController.create(new Vendas(1, Double.valueOf(0), Double.valueOf(0), Double.valueOf(0), "Cartão", new Date()));
} catch (Exception ex) {
Logger.getLogger(VendasView.class.getName()).log(Level.SEVERE, null, ex);
}
}//GEN-LAST:event_jButton1ActionPerformed
private void textCodigoBarraActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_textCodigoBarraActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_textCodigoBarraActionPerformed
private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed
double valorBalanca = Math.round(Math.random() * 10);
this.textQuantidade.setText(String.valueOf(valorBalanca));
JOptionPane.showMessageDialog(null, "Kilos pesados na balança: " + valorBalanca);
this.textValorTotalItem.setText(String.valueOf(Double.valueOf(this.textQuantidade.getText()) * Double.valueOf(this.textValorUniario.getText())));
this.jButton4.setEnabled(false);
}//GEN-LAST:event_jButton4ActionPerformed
private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton5ActionPerformed
Produto prod = this.produtoJpaController.findProduto(Integer.valueOf(this.textCodigoBarra.getText()));
try {
this.itemvendaJpaController.edit(new Itemvenda(Integer.valueOf(this.textCodigoBarra.getText()), this.vendasJpaController.getVendasLastId(), Double.valueOf(this.textQuantidade.getText()), Double.valueOf(this.textValorTotalItem.getText()), prod.getNomeProduto(), prod.getValorPoduto(), prod.getUnidadeProduto()));
this.textCodigoBarra.setText(null);
this.textDescricao.setText(null);
this.textUnidade.setText(null);
this.textValorUniario.setText(null);
this.textValorTotalItem.setText(null);
this.itemvendaJpaController.limparLista();
this.jButton2.setEnabled(true);
this.jButton3.setEnabled(true);
this.textValorTotalCompra.setText(String.valueOf(this.itemvendaJpaController.getValorItems()));
} catch (Exception ex) {
Logger.getLogger(VendasView.class.getName()).log(Level.SEVERE, null, ex);
}
}//GEN-LAST:event_jButton5ActionPerformed
/**
* @param args the command line arguments
*/
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JButton jButton3;
private javax.swing.JButton jButton4;
private javax.swing.JButton jButton5;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel7;
private javax.swing.JLabel jLabel8;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTable jTable1;
private javax.swing.JTextField textCodigoBarra;
private javax.swing.JTextField textDescricao;
private javax.swing.JTextField textQuantidade;
private javax.swing.JTextField textUnidade;
private javax.swing.JTextField textValorTotalCompra;
private javax.swing.JTextField textValorTotalItem;
private javax.swing.JTextField textValorUniario;
private org.jdesktop.beansbinding.BindingGroup bindingGroup;
// End of variables declaration//GEN-END:variables
}
|
package com.shensu.controller;
import java.io.File;
/**
* 首页轮播图
*/
import java.io.IOException;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
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 org.springframework.web.multipart.MultipartFile;
import com.alibaba.fastjson.JSONArray;
import com.shensu.pojo.Shop;
import com.shensu.pojo.ShopType;
import com.shensu.pojo.Swiper;
import com.shensu.service.ShopService;
import com.shensu.service.SwiperService;
import com.shensu.tool.DateTime;
import com.shensu.tool.DeleteLocationImgHelper;
import com.shensu.tool.UploadHelper;
/**
*
* @author YUKI 轮播图的上传时间
*/
@Controller
@RequestMapping("admin/swiper")
public class SwiperController {
@Autowired
SwiperService swiperService;
@Autowired
ShopService shopService;
// 增加轮播图
@RequestMapping(value = "/inserSwiper",method=RequestMethod.POST)
public String inserSwiper(Swiper swiper, HttpServletRequest request, @RequestParam("File") MultipartFile File[]) throws IOException {
for (MultipartFile f : File) {
String img = UploadHelper.upload(f, request);
Swiper s1 = new Swiper();
s1.setSwiperimg(img);
s1.setSwipercreattime(new DateTime().getDate());
swiperService.inserSwiper(s1);
}
return "selectAll";
}
// 刪除一张轮播图
@RequestMapping("/deleteSwiper")
public String deleteSwiper(int swiperid) throws IOException {
swiperService.deleteSwiper(swiperid);
return "selectAll";
}
// 展示轮播图
@RequestMapping("/findAllSwiper")
public List<Swiper> findAllSwiper() throws IOException {
System.out.println("*************************************");
System.out.println("进来了");
return swiperService.findAllSwiper();
}
//预跳转首页展示图banner
@RequestMapping("/indexBanner")
public String indexBanner(HttpServletRequest request){
List<Shop> shopList=shopService.getAll();
request.setAttribute("shopList", shopList);
List<Swiper> sList=swiperService.findAllSwiper();
request.setAttribute("swiperList", JSONArray.toJSONString(sList));
return "indexBanner/indexBanner";
}
//以下为渲染时新建控制器
// 在添加商品类目的同时给类目绑定上用户添加的图片
@RequestMapping(value = "indexSwiperUpload")
@ResponseBody
public String addTypeAndPhoto(@RequestParam(value = "file", required = false) MultipartFile files,
HttpServletRequest request, ShopType shopType) throws IOException {
String imgUrl = UploadHelper.upload(files, request);
return imgUrl;
}
@RequestMapping("insert")
public String insert(HttpServletRequest request,Swiper swiper,int []selectShopId) throws IOException{
System.out.println(swiper.getShopId());
Swiper s=swiperService.findByLocation(swiper.getLocation());
swiper.setShopId(selectShopId[swiper.getLocation()-1]);
if(s==null){
swiperService.inserSwiper(swiper);
}else{
DeleteLocationImgHelper.deleteLocationImg(s.getSwiperimg(), request);
int a=swiperService.update(swiper);
System.out.println(a);
//修改轮播图
}
return "redirect:indexBanner";
}
}
|
package Pages;
import org.openqa.selenium.WebDriver;
public class LoginPage extends Pages {
static WebDriver driver = null;
public LoginPage(WebDriver driver) {
// TODO Auto-generated constructor stub
this.driver = driver;
}
//封装业务方法:Busness,考虑业务步骤的先后顺序
public static void login(String buttonName) {
// TODO Auto-generated method stub
click(buttonName,driver);
}
}
|
package com.metoo.manage.admin.action;
import java.math.BigDecimal;
import java.text.ParseException;
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.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import com.metoo.core.annotation.SecurityMapping;
import com.metoo.core.domain.virtual.SysMap;
import com.metoo.core.mv.JModelAndView;
import com.metoo.core.query.support.IPageList;
import com.metoo.core.security.support.SecurityUserHolder;
import com.metoo.core.tools.CommUtil;
import com.metoo.core.tools.WebForm;
import com.metoo.foundation.domain.PredepositCash;
import com.metoo.foundation.domain.User;
import com.metoo.foundation.domain.query.PredepositCashQueryObject;
import com.metoo.foundation.service.IPredepositCashService;
import com.metoo.foundation.service.ISysConfigService;
import com.metoo.foundation.service.IUserConfigService;
import com.metoo.foundation.service.IUserService;
/**
*
* <p>
* Title: PredepositCashManageAction.java
* </p>
*
* <p>
* Description:商城用户提现管理控制器,用来显示用户提现列表、处理用户提现申请、查询提现详情
* </p>
*
* <p>
* Copyright: Copyright (c) 2015
* </p>
*
* <p>
* Company: 沈阳网之商科技有限公司 www.koala.com
* </p>
*
* @author erikzhang
*
* @date 2014-5-30
*
* @version koala_b2b2c v2.0 2015版
*/
@Controller
public class PredepositCashManageAction {
@Autowired
private ISysConfigService configService;
@Autowired
private IUserConfigService userConfigService;
@Autowired
private IPredepositCashService predepositcashService;
@Autowired
private IUserService userService;
/**
* PredepositCash列表页
*
* @param currentPage
* @param orderBy
* @param orderType
* @param request
* @return
*/
@SecurityMapping(title = "提现申请列表", value = "/admin/predeposit_cash.htm*", rtype = "admin", rname = "预存款管理", rcode = "predeposit", rgroup = "会员")
@RequestMapping("/admin/predeposit_cash.htm")
public ModelAndView predeposit_cash(HttpServletRequest request,
HttpServletResponse response, String currentPage, String orderBy,
String orderType, String q_pd_userName, String q_beginTime,
String q_endTime,String q_cash_payment,String q_cash_pay_status,
String q_cash_status,String q_cash_userName,String q_cash_remittance_user,
String q_cash_remittance_bank) {
ModelAndView mv = new JModelAndView("admin/blue/predeposit_cash.html",
configService.getSysConfig(),
this.userConfigService.getUserConfig(), 0, request, response);
if (this.configService.getSysConfig().isDeposit()) {
String url = this.configService.getSysConfig().getAddress();
if (url == null || url.equals("")) {
url = CommUtil.getURL(request);
}
PredepositCashQueryObject qo = new PredepositCashQueryObject(
currentPage, mv, orderBy, orderType);
WebForm wf = new WebForm();
wf.toQueryPo(request, qo, PredepositCash.class, mv);
if (!CommUtil.null2String(q_cash_payment).equals("")) {
qo.addQuery("obj.cash_payment", new SysMap(
"cash_payment", q_cash_payment), "=");
}
if (!CommUtil.null2String(q_cash_userName).equals("")) {
qo.addQuery("obj.cash_userName", new SysMap(
"cash_userName", q_cash_userName), "=");
}
if (!CommUtil.null2String(q_cash_status).equals("")) {
qo.addQuery("obj.cash_status", new SysMap(
"cash_status", CommUtil.null2Int(q_cash_status)), "=");
}
if (!CommUtil.null2String(q_cash_remittance_user).equals("")) {
qo.addQuery("obj.cash_user.userName", new SysMap(
"cash_remittance_user", q_cash_remittance_user), "=");
}
if (!CommUtil.null2String(q_cash_remittance_bank).equals("")) {
qo.addQuery("obj.cash_bank", new SysMap(
"cash_remittance_bank", q_cash_remittance_bank), "=");
}
if (!CommUtil.null2String(q_cash_pay_status).equals("")) {
qo.addQuery("obj.cash_bank", new SysMap(
"cash_pay_status", CommUtil.null2Int(q_cash_pay_status)), "=");
}
if (!CommUtil.null2String(q_beginTime).equals("")) {
qo.addQuery(
"obj.addTime",
new SysMap("beginTime", CommUtil
.formatDate(q_beginTime)), ">=");
}
if (!CommUtil.null2String(q_endTime).equals("")) {
qo.addQuery("obj.addTime",
new SysMap("endTime", CommUtil.formatDate(q_endTime)),
"<=");
}
IPageList pList = this.predepositcashService.list(qo);
CommUtil.saveIPageList2ModelAndView("", "", "", pList, mv);
mv.addObject("q_cash_payment", q_cash_payment);
mv.addObject("q_cash_pay_status", q_cash_pay_status);
mv.addObject("q_cash_userName", q_cash_userName);
mv.addObject("q_cash_status", q_cash_status);
mv.addObject("q_cash_remittance_user", q_cash_remittance_user);
mv.addObject("q_cash_remittance_bank", q_cash_remittance_bank);
mv.addObject("q_beginTime", q_beginTime);
mv.addObject("q_endTime", q_endTime);
} else {
mv = new JModelAndView("admin/blue/error.html",
configService.getSysConfig(),
this.userConfigService.getUserConfig(), 0, request,
response);
mv.addObject("op_title", "系统未开启预存款");
mv.addObject("list_url", CommUtil.getURL(request)
+ "/admin/operation_base_set.htm");
}
return mv;
}
/**
* predepositcash编辑管理
*
* @param id
* @param request
* @return
* @throws ParseException
*/
@SecurityMapping(title = "提现申请编辑", value = "/admin/predeposit_cash_edit.htm*", rtype = "admin", rname = "预存款管理", rcode = "predeposit", rgroup = "会员")
@RequestMapping("/admin/predeposit_cash_edit.htm")
public ModelAndView predeposit_cash_edit(HttpServletRequest request,
HttpServletResponse response, String id, String currentPage) {
ModelAndView mv = new JModelAndView(
"admin/blue/predeposit_cash_edit.html",
configService.getSysConfig(),
this.userConfigService.getUserConfig(), 0, request, response);
if (this.configService.getSysConfig().isDeposit()) {
if (id != null && !id.equals("")) {
PredepositCash predepositcash = this.predepositcashService
.getObjById(Long.parseLong(id));
mv.addObject("obj", predepositcash);
mv.addObject("currentPage", currentPage);
}
} else {
mv = new JModelAndView("admin/blue/error.html",
configService.getSysConfig(),
this.userConfigService.getUserConfig(), 0, request,
response);
mv.addObject("op_title", "系统未开启预存款");
mv.addObject("list_url", CommUtil.getURL(request)
+ "/admin/operation_base_set.htm");
}
return mv;
}
/**
* predepositcash保存管理
*
* @param id
* @return
*/
@SecurityMapping(title = "提现申请编辑保存", value = "/admin/predeposit_cash_save.htm*", rtype = "admin", rname = "预存款管理", rcode = "predeposit", rgroup = "会员")
@RequestMapping("/admin/predeposit_cash_save.htm")
public ModelAndView predeposit_cash_save(HttpServletRequest request,
HttpServletResponse response, String id, String currentPage,
String cmd, String list_url) {
ModelAndView mv = new JModelAndView("admin/blue/success.html",
configService.getSysConfig(),
this.userConfigService.getUserConfig(), 0, request, response);
if (this.configService.getSysConfig().isDeposit()) {
WebForm wf = new WebForm();
PredepositCash obj = this.predepositcashService.getObjById(Long
.parseLong(id));
PredepositCash predepositcash = (PredepositCash) wf.toPo(request,
obj);
if(obj.getCash_pay_status()==1){
obj.setCash_status(1);
}
obj.setCash_admin(SecurityUserHolder.getCurrentUser());
this.predepositcashService.update(predepositcash);
User user = obj.getCash_user();
user.setAvailableBalance(BigDecimal.valueOf(CommUtil.subtract(
user.getAvailableBalance(), predepositcash.getCash_amount())));
this.userService.update(user);
mv.addObject("list_url", list_url);
mv.addObject("op_title", "审核提现申请成功");
} else {
mv = new JModelAndView("admin/blue/error.html",
configService.getSysConfig(),
this.userConfigService.getUserConfig(), 0, request,
response);
mv.addObject("op_title", "系统未开启预存款");
mv.addObject("list_url", CommUtil.getURL(request)
+ "/admin/operation_base_set.htm");
}
return mv;
}
@SecurityMapping(title = "提现申请详情", value = "/admin/predeposit_cash_view.htm*", rtype = "admin", rname = "预存款管理", rcode = "predeposit", rgroup = "会员")
@RequestMapping("/admin/predeposit_cash_view.htm")
public ModelAndView predeposit_cash_view(HttpServletRequest request,
HttpServletResponse response, String id) {
ModelAndView mv = new JModelAndView(
"admin/blue/predeposit_cash_view.html",
configService.getSysConfig(),
this.userConfigService.getUserConfig(), 0, request, response);
if (this.configService.getSysConfig().isDeposit()) {
if (id != null && !id.equals("")) {
PredepositCash predepositcash = this.predepositcashService
.getObjById(Long.parseLong(id));
mv.addObject("obj", predepositcash);
}
} else {
mv = new JModelAndView("admin/blue/error.html",
configService.getSysConfig(),
this.userConfigService.getUserConfig(), 0, request,
response);
mv.addObject("op_title", "系统未开启预存款");
mv.addObject("list_url", CommUtil.getURL(request)
+ "/admin/operation_base_set.htm");
}
return mv;
}
}
|
package com.sionicmobile.ion.adapters;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.sionicmobile.ion.R;
import java.util.ArrayList;
/**
* Created by TChwang on 4/3/2015.
*/
public class IonDrawerListAdapter extends BaseAdapter {
private Context _context;
private String[] _ionMenuList;
public IonDrawerListAdapter(Context context, String[] list) {
_context = context;
_ionMenuList = list;
}
@Override
public int getCount() {
return _ionMenuList.length;
}
@Override
public Object getItem(int position) {
return _ionMenuList[position];
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView == null) {
LayoutInflater inflater = (LayoutInflater) _context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.drawer_menu_list_layout, null);
}
TextView txtTitle = (TextView) convertView.findViewById(R.id.ion_drawer_item_id);
txtTitle.setText(_ionMenuList[position]);
return convertView;
}
}
|
package com.myvodafone.android.model.service.handlers;
import com.myvodafone.android.model.service.RegistrationOption;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import java.util.ArrayList;
public class RegistrationScreenHandler extends DefaultHandler {
private RegistrationOption item = new RegistrationOption();
private ArrayList<RegistrationOption> registrationOptions = new ArrayList<RegistrationOption>();
private boolean in_registration = false;
private boolean in_order_number = false;
private boolean in_registration_id = false;
private boolean in_registration_label_en = false;
private boolean in_registration_label_gr = false;
private boolean in_registration_type = false;
private boolean in_registration_action_url = false;
private boolean in_registration_action_url_en = false;
private boolean in_registration_action_url_gr = false;
private boolean in_registration_icon = false;
public ArrayList<RegistrationOption> getRegistrationOptionsListItem() {
return registrationOptions;
}
@Override
public void characters(char ch[], int start, int length) {
String s1 = new String(ch, start, length);
if (this.in_order_number) {
item.setOrder_number(s1);
} else if (this.in_registration_id) {
item.setId(s1);
} else if (this.in_registration_label_en) {
item.setLabel_en(s1);
} else if (this.in_registration_label_gr) {
item.setLabel_gr(s1);
} else if (this.in_registration_type) {
item.setType(s1);
} else if (this.in_registration_action_url) {
item.setAction_url(s1);
} else if (this.in_registration_action_url_gr) {
item.setAction_url_gr(s1);
} else if (this.in_registration_action_url_en) {
item.setAction_url_en(s1);
} else if (this.in_registration_icon) {
item.setIcon(s1);
}
}
/** Gets be called on opening tags like: <tag> **/
@Override
public void startElement(String namespaceURI, String localName, String qName, Attributes atts) throws SAXException {
if (localName.equals("registration")) {
item = new RegistrationOption();
this.in_registration = true;
} else if (localName.equals("order_number")) {
this.in_order_number = true;
} else if (localName.equals("registration_id")) {
this.in_registration_id = true;
} else if (localName.equals("registration_label_en")) {
this.in_registration_label_en = true;
} else if (localName.equals("registration_label_gr")) {
this.in_registration_label_gr = true;
} else if (localName.equals("registration_type")) {
this.in_registration_type = true;
} else if (localName.equals("registration_action_url")) {
this.in_registration_action_url = true;
} else if (localName.equals("registration_action_url_gr")) {
this.in_registration_action_url_gr = true;
} else if (localName.equals("registration_action_url_en")) {
this.in_registration_action_url_en = true;
} else if (localName.equals("registration_icon")) {
this.in_registration_icon = true;
}
}
/**
* Gets be called on closing tags like: </tag>
*/
@Override
public void endElement(String namespaceURI, String localName, String qName) throws SAXException {
if (localName.equals("registration")) {
registrationOptions.add(item);
this.in_registration = false;
} else if (localName.equals("order_number")) {
this.in_order_number = false;
} else if (localName.equals("registration_id")) {
this.in_registration_id = false;
} else if (localName.equals("registration_label_en")) {
this.in_registration_label_en = false;
} else if (localName.equals("registration_label_gr")) {
this.in_registration_label_gr = false;
} else if (localName.equals("registration_type")) {
this.in_registration_type = false;
} else if (localName.equals("registration_action_url")) {
this.in_registration_action_url = false;
} else if (localName.equals("registration_action_url_gr")) {
this.in_registration_action_url_gr = false;
} else if (localName.equals("registration_action_url_en")) {
this.in_registration_action_url_en = false;
} else if (localName.equals("registration_icon")) {
this.in_registration_icon = false;
}
}
@Override
public void startDocument() throws SAXException {
item = new RegistrationOption();
}
@Override
public void endDocument() throws SAXException {
// Nothing to do
}
}
|
package com.zhicai.byteera.widget;
import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.zhicai.byteera.R;
/**
* Created by Administrator on 2015/7/2 0002.
*/
public class OrganizationLinearLayout extends LinearLayout {
public OrganizationLinearLayout(Context context) {
this(context, null);
}
public OrganizationLinearLayout(Context context, AttributeSet attrs) {
super(context, attrs);
initView();
}
private void initView() {
this.setOrientation(VERTICAL);
}
public void addItem(String name, String content) {
View item = LayoutInflater.from(getContext()).inflate(R.layout.linear_item, null);
TextView tvName = (TextView) item.findViewById(R.id.tv_name);
TextView tvContent = (TextView) item.findViewById(R.id.tv_content);
tvName.setText(name);
tvContent.setText(content);
this.addView(item);
}
}
|
package lab_12;
public class CountChars {
public static void main(String[] args) {
System.out.println(CharacterCount("four", 0));
}
public static int CharacterCount(String s, int index){
if (s.length() == index)
return 0;
else
return 1 + CharacterCount(s, index + 1);
}
}
|
package com.proyectogrado.alternativahorario.entidades;
import java.io.Serializable;
import java.math.BigDecimal;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
import lombok.Getter;
import lombok.Setter;
/**
*
* @author Steven
*/
@Entity
@Table(name = "horarios")
@SequenceGenerator(name = "SecuenciaHorario", sequenceName = "SEC_IDHORARIOS")
@NamedQueries({
@NamedQuery(name = "Horario.findByClase", query = "SELECT h FROM Horario h WHERE h.clases = :clase")})
public class Horario implements Serializable {
private static final long serialVersionUID = 1L;
@Getter
@Setter
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "SecuenciaHorario")
@Basic(optional = false)
@Column(name = "id")
private BigDecimal id;
@Getter
@Setter
@Column(name = "dia")
private String dia;
@Getter
@Setter
@Column(name = "horainicio")
private BigDecimal horainicio;
@Getter
@Setter
@Column(name = "horafin")
private BigDecimal horafin;
@Getter
@Setter
@JoinColumn(name = "clases", referencedColumnName = "id")
@ManyToOne(fetch = FetchType.LAZY)
private Clase clases;
public Horario() {
}
public Horario(BigDecimal id) {
this.id = id;
}
}
|
package com.adanac.demo.leecode.base.math;
import java.util.HashMap;
import java.util.Map;
public class Solution {
// Iterative
public int getSum(int a, int b) {
if (a == 0)
return b;
if (b == 0)
return a;
while (b != 0) {
int carry = a & b;
a = a ^ b;
b = carry << 1;
}
return a;
}
// Iterative
public int getSubtract(int a, int b) {
while (b != 0) {
int borrow = (~a) & b;
a = a ^ b;
b = borrow << 1;
}
return a;
}
// Recursive 回归的方式得到两个数的和
public int getSum2(int a, int b) {
return (b == 0) ? a : getSum2(a ^ b, (a & b) << 1);
}
// Recursive
public int getSubtract2(int a, int b) {
return (b == 0) ? a : getSubtract2(a ^ b, (~a & b) << 1);
}
// Get negative numbe 得到一个数的相反数
public int negate(int x) {
return ~x + 1;
}
/**
* 在number整形数组中找到两个数的和为target的两个数的坐标
* @param numbers
* @param target
* @return
*/
public int[] twoSum(int[] numbers, int target) {
int[] result = new int[2];
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for (int i = 0; i < numbers.length; i++) {
if (map.containsKey(target - numbers[i])) {
result[1] = i + 1;
result[0] = map.get(target - numbers[i]);
return result;
}
map.put(numbers[i], i + 1);
}
return result;
}
}
|
package com.wrathOfLoD.Views;
/**
* Created by zach on 4/16/16.
*/
public interface Selectable {
public void selectNextItem();
public void selectPrevItem();
public void selectUpItem();
public void selectDownItem();
public Object useSelectedItem();
}
|
package com.hhdb.csadmin.plugin.user_create.ui;
import java.awt.Color;
import java.awt.Component;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.Point;
import java.awt.Rectangle;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import com.hhdb.csadmin.plugin.tree.util.ThreadUtils;
public class UIUtils {
private static boolean checkedMac;
private static boolean isMac;
public static Point getPointToCenter(Component component, Dimension dimension) {
Dimension screenSize = getDefaultDeviceScreenSize();
if (component == null) {
if (dimension.height > screenSize.height) {
dimension.height = screenSize.height;
}
if (dimension.width > screenSize.width) {
dimension.width = screenSize.width;
}
return new Point((screenSize.width - dimension.width) / 2, (screenSize.height - dimension.height) / 2);
}
Dimension frameDim = component.getSize();
Rectangle dRec = new Rectangle(component.getX(), component.getY(), (int) frameDim.getWidth(), (int) frameDim.getHeight());
int dialogX = dRec.x + ((dRec.width - dimension.width) / 2);
int dialogY = dRec.y + ((dRec.height - dimension.height) / 2);
if (dialogX <= 0 || dialogY <= 0) {
if (dimension.height > screenSize.height) {
dimension.height = screenSize.height;
}
if (dimension.width > screenSize.width) {
dimension.width = screenSize.width;
}
dialogX = (screenSize.width - dimension.width) / 2;
dialogY = (screenSize.height - dimension.height) / 2;
}
return new Point(dialogX, dialogY);
}
public static Dimension getDefaultDeviceScreenSize() {
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice gs = ge.getScreenDevices()[0];
Dimension screenSize = gs.getDefaultConfiguration().getBounds().getSize();
return screenSize;
}
public static Color getBrighter(Color color, double factor) {
int r = color.getRed();
int g = color.getGreen();
int b = color.getBlue();
int i = (int) (1.0 / (1.0 - factor));
if (r == 0 && g == 0 && b == 0) {
return new Color(i, i, i);
}
if (r > 0 && r < i)
r = i;
if (g > 0 && g < i)
g = i;
if (b > 0 && b < i)
b = i;
return new Color(Math.min((int) (r / factor), 255), Math.min((int) (g / factor), 255), Math.min((int) (b / factor), 255));
}
public static boolean isGtkLookAndFeel() {
return isLookAndFeel("com.sun.java.swing.plaf.gtk.GTKLookAndFeel");
}
public static void showWarningBox(String message) {
JOptionPane.showMessageDialog( null,message, "提示", JOptionPane.WARNING_MESSAGE, null);
}
public static void showErrorBox(String message) {
if(message!=null&&!"".equals(message.trim())){
JOptionPane.showMessageDialog(null, message, "提示",JOptionPane.ERROR_MESSAGE);
}
}
private static boolean isLookAndFeel(String name) {
return UIManager.getLookAndFeel().getClass().getName().equals(name);
}
public static boolean isMac() {
if (!checkedMac) {
String osName = System.getProperty ("os.name");
if (osName != null && osName.indexOf("Mac") != -1) {
isMac = true;
}
checkedMac = true;
}
return isMac;
}
public static void showWaitCursor() {
ThreadUtils.invokeAndWait(new Runnable() {
public void run() {
showWaitCursor(null);
}
});
}
public static void showWaitCursor(Component component) {
setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR), component);
}
private static void setCursor(Cursor cursor, Component component) {
if (component != null) {
component.setCursor(cursor);
}
}
public static void scheduleGC() {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
System.gc();
}
});
}
public static void showNormalCursor(Component component) {
setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR), component);
}
public static void showNormalCursor() {
ThreadUtils.invokeAndWait(new Runnable() {
public void run() {
showNormalCursor(null);
}
});
}
}
|
package com.cs.game;
import com.cs.player.Player;
import com.google.common.base.Objects;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Enumerated;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.io.Serializable;
import java.util.Date;
import static javax.persistence.EnumType.STRING;
import static javax.persistence.GenerationType.IDENTITY;
import static javax.persistence.TemporalType.TIMESTAMP;
/**
* @author Hadi Movaghar
*/
@Entity
@Table(name = "game_sessions")
public class GameSession implements Serializable {
private static final long serialVersionUID = 3L;
@Id
@GeneratedValue(strategy = IDENTITY)
@Column(name = "id", nullable = false, unique = true)
@Nonnull
private Long id;
@OneToOne
@JoinColumn(name = "player_id", nullable = false)
@Nonnull
@Valid
private Player player;
@Column(name = "session_id")
@Nullable
private String sessionId;
@Column(name = "start_date", nullable = false)
@Temporal(TIMESTAMP)
@Nonnull
@NotNull(message = "gameSession.startDate.notNull")
private Date startDate;
@Column(name = "end_date")
@Temporal(TIMESTAMP)
@Nullable
private Date endDate;
@Column(name = "session_length")
@Nonnull
private Integer sessionLength;
@Column(name = "channel", nullable = false)
@Enumerated(STRING)
@Nullable
private Channel channel;
public GameSession() {
sessionLength = 0;
}
public GameSession(@Nonnull final Player player, @Nonnull final Date startDate) {
this();
this.player = player;
this.startDate = startDate;
}
@Nonnull
public Long getId() {
return id;
}
public void setId(@Nonnull final Long id) {
this.id = id;
}
@Nonnull
public Player getPlayer() {
return player;
}
public void setPlayer(@Nonnull final Player player) {
this.player = player;
}
@Nullable
public String getSessionId() {
return sessionId;
}
public void setSessionId(@Nullable final String sessionId) {
this.sessionId = sessionId;
}
@Nonnull
public Date getStartDate() {
return startDate;
}
public void setStartDate(@Nonnull final Date startDate) {
this.startDate = startDate;
}
@Nullable
public Date getEndDate() {
return endDate;
}
public void setEndDate(@Nullable final Date endDate) {
this.endDate = endDate;
}
@Nonnull
public Integer getSessionLength() {
return sessionLength;
}
public void setSessionLength(@Nonnull final Integer sessionLength) {
this.sessionLength = sessionLength;
}
@Nullable
public Channel getChannel() {
return channel;
}
public void setChannel(@Nullable final Channel channel) {
this.channel = channel;
}
@Override
public boolean equals(final Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
final GameSession that = (GameSession) o;
return Objects.equal(id, that.id);
}
@Override
public int hashCode() {
return Objects.hashCode(id);
}
@SuppressWarnings("ConstantConditions")
@Override
public String toString() {
return Objects.toStringHelper(this)
.addValue(id)
.addValue(player != null ? player.getId() : null)
.addValue(sessionId)
.addValue(startDate)
.addValue(endDate)
.addValue(sessionLength)
.addValue(channel)
.toString();
}
}
|
/*
* Copyright 2002-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.http.converter.json;
import java.util.Map;
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonInclude;
import org.springframework.http.ProblemDetail;
import org.springframework.lang.Nullable;
import static com.fasterxml.jackson.annotation.JsonInclude.Include.NON_EMPTY;
/**
* An interface to associate Jackson annotations with
* {@link org.springframework.http.ProblemDetail} to avoid a hard dependency on
* the Jackson library.
*
* <p>The annotations ensure the {@link ProblemDetail#getProperties() properties}
* map is unwrapped and rendered as top-level JSON properties, and likewise that
* the {@code properties} map contains unknown properties from the JSON.
*
* <p>{@link Jackson2ObjectMapperBuilder} automatically registers this as a
* "mix-in" for {@link ProblemDetail}, which means it always applies, unless
* an {@code ObjectMapper} is instantiated directly and configured for use.
*
* @author Rossen Stoyanchev
* @since 6.0
*/
@JsonInclude(NON_EMPTY)
public interface ProblemDetailJacksonMixin {
@JsonAnySetter
void setProperty(String name, @Nullable Object value);
@JsonAnyGetter
Map<String, Object> getProperties();
}
|
package arrays;
import java.util.Arrays;
public class Exercicio2 {
public static void main(String[] args) {
double notasAlunoA[] = new double[3];
System.out.println(Arrays.toString(notasAlunoA));
notasAlunoA[0] = 7.0;
notasAlunoA[1] = 8;
notasAlunoA[2] = 7.4;
System.out.println(Arrays.toString(notasAlunoA));
System.out.println(notasAlunoA[0]);
System.out.println(notasAlunoA[notasAlunoA.length - 1]);
double totalAlunoA = 0;
for(double i:notasAlunoA) {
totalAlunoA += i;
}
System.out.println(totalAlunoA / notasAlunoA.length);
double reforco = 8;
double[] notasAlunoB = {6.9, 5.7, 8.6, reforco};
double totalAlunoB = 0;
for (double i: notasAlunoB) {
totalAlunoB += i;
}
System.out.println(totalAlunoB / notasAlunoB.length);
}
}
|
/**
* Copyright (C),2015-2018
* FileNmae: RegisterDao
* Author: Administrator
* Date: 2018/8/2816:35
* History:
* <author> <Time> <version> <desc>
* 陈泽群 时间 版本号 描述
*/
package com.youma.his.dao;
import com.youma.his.vo.Register;
import java.util.List;
/**
* 挂号信息表数据库操作接口
* @author Administrator
*/
public interface RegisterDao {
/**
* 挂号信息添加操作
* @param register 挂号信息
* @return int 影响行数
*/
public int registerAdd(Register register);
/**
* 挂号信息修改操作
* @param register 挂号信息
* @return int 影响行数
*/
public int updateRegister(Register register);
/**
* 挂号信息删除操作
* @param id 病历号
* @return int 影响的行数
*/
public int delRegister(int id);
/**
* 查询所有挂号信息操作
* @return List<Register> 挂号信息集合
*/
public List<Register> findAllRegister();
/**
* 查询指定病历号的挂号信息
* @param id 病历号
* @return 指定病历号的挂号信息
*/
public Register findRegister(int id);
}
|
package org.turtledream;
import com.hazelcast.core.*;
import io.vertx.core.AbstractVerticle;
import io.vertx.core.Vertx;
import io.vertx.ext.web.FileUpload;
import io.vertx.ext.web.Router;
import io.vertx.ext.web.handler.BodyHandler;
import java.io.File;
class MainMsgListener implements MessageListener<String> {
IAtomicLong counter;
MainMsgListener (IAtomicLong counter){
this.counter = counter;
}
public void onMessage(Message<String> message) {
String msg = message.getMessageObject();
if(msg.equals("Delivered!")) {
counter.addAndGet(1);
}
System.out.println("Message received = " + msg);
}
}
public class Main extends AbstractVerticle{
public static HazelcastInstance hz;
public static ITopic<File> topic_send;
public static ITopic<String> topic_get;
public static ITopic<String> topic_backup;
public static IAtomicLong counter;
@Override
public void start(){
Router router = Router.router(vertx);
router.route().handler(BodyHandler.create().setUploadsDirectory("upls"));
router.route("/").handler(routingContext -> {
routingContext.response().putHeader("content-type", "text/html").end(
"<form action=\"/form\" method=\"post\" enctype=\"multipart/form-data\">\n" +
" <div>\n" +
" <label for=\"name\">Select a file:</label>\n" +
" <input type=\"file\" name=\"file\">\n" +
" </div>\n" +
" <div class=\"button\">\n" +
" <button type=\"submit\">Send</button>\n" +
" </div>" +
"</form>"
);
});
router.route("/form").handler(ctx -> {
for (FileUpload fileUpload : ctx.fileUploads()) {
File file = new File(fileUpload.uploadedFileName());
topic_send.publish(file);
long lastTime = System.currentTimeMillis();
long curTime = lastTime;
while((counter.get() != hz.getCluster().getMembers().size() - 1) && (lastTime - curTime < 5000)){
lastTime = System.currentTimeMillis();
}
if(counter.get() == hz.getCluster().getMembers().size() - 1){
topic_backup.publish("Success");
file.delete();
counter.set(0);
ctx.response().putHeader("Content-Type", "text/html").end("Success");
}
else{
topic_backup.publish("Backup");
file.delete();
counter.set(0);
ctx.response().putHeader("Content-Type", "text/html").end("Fail");
}
}
});
vertx.createHttpServer().requestHandler(router).listen(8080);
}
public static void main(String[] args) {
Vertx vertx = Vertx.vertx();
vertx.deployVerticle(new Main());
hz = Hazelcast.newHazelcastInstance();
counter = hz.getAtomicLong("counter");
topic_send = hz.getTopic("topic_send");
topic_get = hz.getTopic("topic_get");
topic_backup = hz.getTopic("topic_backup");
topic_get.addMessageListener(new MainMsgListener(counter));
}
}
|
package com.example.demo22222222;
import com.alibaba.fastjson.JSONObject;
import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.*;
import com.dingtalk.api.response.*;
import java.util.List;
/**
* author: ljian
* describe: 通讯录相关demo
* createDate:
**/
public class MailListController {
public static void main(String[] args)throws Exception{
getMailListPremesion("ebda0bd29c123af48ba44c66ffa5dcf0");
getDeptUserList("71c39f1144913864a7c869c1749ab36b","82731762");
getUserDetail("ebda0bd29c123af48ba44c66ffa5dcf0","14035045511222783");
getChildDeptId("ebda0bd29c123af48ba44c66ffa5dcf0","1");
//71c39f1144913864a7c869c1749ab36b
getDeptList("71c39f1144913864a7c869c1749ab36b",null);
getDeptDetail("71c39f1144913864a7c869c1749ab36b","1");
}
/**
* 获取通讯录权限范围
* @param accessToken
*/
public static void getMailListPremesion(String accessToken)throws Exception{
DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/auth/scopes");
OapiAuthScopesRequest request = new OapiAuthScopesRequest();
//request.setHttpMethod("GET");
OapiAuthScopesResponse response = client.execute(request, accessToken);
System.out.println("code:"+response.getErrcode());
System.out.println("msg:"+response.getErrmsg());
List<Long> authedDept = response.getAuthOrgScopes().getAuthedDept();
for (Long aLong : authedDept) {
System.out.println("dept:"+aLong);
}
List<String> userList = response.getAuthOrgScopes().getAuthedUser();
System.out.println("userSize:"+userList.size());
for(String str:userList){
System.out.println(str);
}
System.out.println("---------------------------------");
List<String> list = response.getAuthUserField();
for (String str :list){
System.out.println(str);
}
}
/**
* 获取部门用户userid列表
* @param accessToken
* @param deptId
* @throws Exception
*/
public static void getDeptUserList(String accessToken,String deptId)throws Exception{
DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/user/getDeptMember");
OapiUserGetDeptMemberRequest req = new OapiUserGetDeptMemberRequest();
req.setDeptId(deptId);
req.setTopHttpMethod("GET");
OapiUserGetDeptMemberResponse rsp = client.execute(req, accessToken);
System.out.println("获取部门所有用户列表开始>>>>>>");
System.out.println(rsp.getBody());
System.out.println("获取部门所有用户列表结束<<<<<<");
}
/**
* 获取用户详细信息
* @param accessToken
* @param userId
* @return
* @throws Exception
*/
public static String getUserDetail(String accessToken,String userId)throws Exception{
DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/user/get");
OapiUserGetRequest request = new OapiUserGetRequest();
request.setUserid(userId);
request.setTopHttpMethod("GET");
OapiUserGetResponse response = client.execute(request, accessToken);
System.out.println("获取用户详细信息开始>>>>>>");
System.out.println(response.getBody());
System.out.println("获取用户详细信息结束<<<<<<");
return null;
}
/**
* 获取子部门id
* @param accessToken
* @param parentDeptId
* @throws Exception
*/
public static void getChildDeptId(String accessToken,String parentDeptId)throws Exception{
DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/department/list_ids");
OapiDepartmentListIdsRequest request = new OapiDepartmentListIdsRequest();
request.setId(parentDeptId);
request.setTopHttpMethod("GET");
OapiDepartmentListIdsResponse response = client.execute(request, accessToken);
List<Long> subDeptIdList = response.getSubDeptIdList();
for (Long aLong : subDeptIdList) {
System.out.println("childId:"+aLong);
}
}
/**
* 获取部门列表
* @param accessToken
* @param parentDeptId
* @throws Exception
*/
public static void getDeptList(String accessToken,String parentDeptId)throws Exception{
DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/department/list");
OapiDepartmentListRequest request = new OapiDepartmentListRequest();
request.setId(parentDeptId);
request.setTopHttpMethod("GET");
OapiDepartmentListResponse response = client.execute(request, accessToken);
List<OapiDepartmentListResponse.Department> department = response.getDepartment();
for (OapiDepartmentListResponse.Department department1 : department) {
String string = JSONObject.toJSONString(department1);
System.out.println(string);
}
}
/**
* 获取部门详情
* @param accessToken
* @param deptId
* @throws Exception
*/
public static void getDeptDetail(String accessToken,String deptId)throws Exception{
DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/department/get");
OapiDepartmentGetRequest request = new OapiDepartmentGetRequest();
request.setId(deptId);
request.setTopHttpMethod("GET");
OapiDepartmentGetResponse response = client.execute(request, accessToken);
System.out.println("部门详情开始>>>>>>");
String string = JSONObject.toJSONString(response);
System.out.println(string);
System.out.println("部门详情结束<<<<<<");
}
}
|
package com.jvm.debugger.util;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import com.ujd.sharedutils.model.Filter;
import com.ujd.sharedutils.model.FunctionParameters;
public class DatabaseConnection {
private static final String TABLE_NAME = "functionparameters";
private static final String ID = "id";
private static final String PROGRAM_NAME = "programname";
private static final String THREAD_ID = "threadid";
private static final String CLASS_NAME = "classname";
private static final String METHOD_NAME = "methodname";
private static final String PARAMETER_VALUES = "parametervalues";
private static final String EXECUTE_TIME = "executetime";
private static final String INSERT_STATEMENT_TEMPLATE = "INSERT INTO \""+TABLE_NAME+"\" "
+ "("+PROGRAM_NAME+","+THREAD_ID+","+CLASS_NAME+","+METHOD_NAME+","+PARAMETER_VALUES+","+EXECUTE_TIME+") "
+ "VALUES(?,?,?,?,?,?);";
protected Connection connection = null;
private String url;
private String username;
private String password;
public DatabaseConnection(String url, String username, String password){
this.url = url;
this.username = username;
this.password = password;
}
public void insertFunctionParameters(Logging functionParameters){
if (initConnection()){
insert(functionParameters);
}
closeConnection();
}
public List<Logging> getFunctionParameters(Filter filter){
if (initConnection()){
return select(filter);
}
closeConnection();
return new ArrayList<Logging>();
}
public void clearFunctionParameters(){
if (initConnection()){
clear();
}
closeConnection();
}
protected void clear(){
PreparedStatement ps = null;
try {
ps = this.connection.prepareStatement("DELETE FROM \""+TABLE_NAME+"\";");
ps.executeUpdate();
} catch (SQLException e){
e.printStackTrace();
}
}
protected boolean insert(Logging functionParameters){
PreparedStatement ps = null;
try {
ps = this.connection.prepareStatement(INSERT_STATEMENT_TEMPLATE);
ps.setString(1, functionParameters.getProgramName());
ps.setLong(2, functionParameters.getThreadId());
ps.setString(3, functionParameters.getClassName());
ps.setString(4, functionParameters.getMethodName());
ps.setString(5, functionParameters.getParameterValues());
ps.setLong(6, functionParameters.getTimestamp());
ps.executeUpdate();
return true;
} catch (SQLException e) {
e.printStackTrace();
}
close(ps);
return false;
}
protected List<Logging> select(Filter filter){
List<Logging> functionParameters = new ArrayList<Logging>();
PreparedStatement ps = null;
ResultSet rs = null;
try {
ps = this.connection.prepareStatement(convertFilterToSql(filter));
int index = 1;
if (filter.getId() != null){
ps.setInt(index++, filter.getId());
}
if (filter.getProgramName() != null){
ps.setString(index++, filter.getProgramName());
}
if (filter.getThreadId() != null){
ps.setLong(index++, filter.getThreadId());
}
if (filter.getClassName() != null){
ps.setString(index++, filter.getClassName());
}
if (filter.getMethodName() != null){
ps.setString(index++, filter.getMethodName());
}
if (filter.getFromTimestamp() != null){
ps.setLong(index++, filter.getFromTimestamp());
}
if (filter.getToTimestamp() != null){
ps.setLong(index++, filter.getToTimestamp());
}
rs = ps.executeQuery();
while (rs.next()){
Logging fp = new Logging();
fp.setId(rs.getInt(1));
fp.setProgramName(rs.getString(2));
fp.setThreadId(rs.getLong(3));
fp.setClassName(rs.getString(4));
fp.setMethodName(rs.getString(5));
fp.setParameterValues(rs.getString(6));
fp.setTimestamp(rs.getLong(7));
functionParameters.add(fp);
}
return functionParameters;
} catch (SQLException e) {
e.printStackTrace();
}
close(rs);
close(ps);
return functionParameters;
}
private String convertFilterToSql(Filter filter){
String sql = "SELECT * FROM \""+TABLE_NAME+"\"";
String condition = "";
boolean hasCondition = false;
if (filter.getId() != null){
condition += ID + "=? ";
hasCondition = true;
}
if (filter.getProgramName() != null){
condition += ((hasCondition) ? " AND " : "") + PROGRAM_NAME + "=? ";
hasCondition = true;
}
if (filter.getThreadId() != null){
condition += ((hasCondition) ? " AND " : "") + THREAD_ID + "=? ";
hasCondition = true;
}
if (filter.getClassName() != null){
condition += ((hasCondition) ? " AND " : "") + CLASS_NAME + "=? ";
hasCondition = true;
}
if (filter.getMethodName() != null){
condition += ((hasCondition) ? " AND " : "") + METHOD_NAME + "=? ";
hasCondition = true;
}
if (filter.getFromTimestamp() != null){
condition += ((hasCondition) ? " AND " : "") + EXECUTE_TIME + " > ? ";
hasCondition = true;
}
if (filter.getToTimestamp() != null){
condition += ((hasCondition) ? " AND " : "") + EXECUTE_TIME + " < ? ";
}
return sql + ((condition.length() > 0) ? " WHERE " : "") + condition + " ORDER BY "+ID+";";
}
protected boolean initConnection(){
if (loadDriver()){
try {
this.connection = DriverManager.getConnection(this.url, this.username, this.password);
return true;
} catch (SQLException e) {
e.printStackTrace();
}
}
closeConnection();
return false;
}
private void close(AutoCloseable closable){
if (closable != null){
try {
closable.close();
} catch (Exception e) {}
}
}
protected void closeConnection(){
if (this.connection != null){
try {
this.connection.close();
} catch (SQLException e) {}
}
this.connection = null;
}
private boolean loadDriver(){
try {
Class.forName("org.postgresql.Driver");
return true;
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return false;
}
}
|
package com.google.track;
import android.os.Bundle;
import android.view.MenuItem;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.cardview.widget.CardView;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;
import com.google.android.material.bottomnavigation.BottomNavigationView;
public class MainActivity extends AppCompatActivity {
BottomNavigationView bottomNavigation;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bottomNavigation = findViewById(R.id.bottom_navigation);
bottomNavigation.setOnNavigationItemSelectedListener(navigationItemSelectedListener);
openFragment(CardFragment.newInstance());
}
public void openFragment(Fragment fragment) {
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.container, fragment);
transaction.addToBackStack(null);
transaction.commit();
}
BottomNavigationView.OnNavigationItemSelectedListener navigationItemSelectedListener =
item -> {
switch (item.getItemId()) {
case R.id.navigation_profile:
MainActivity.this.openFragment(ProfileFragment.newInstance());
return true;
case R.id.navigation_calendar:
MainActivity.this.openFragment(CalendarFragment.newInstance());
return true;
case R.id.navigation_history:
MainActivity.this.openFragment(HistoryFragment.newInstance());
return true;
case R.id.navigation_card:
MainActivity.this.openFragment(CardFragment.newInstance());
return true;
}
return false;
};
@Override
public void onBackPressed() {
super.onBackPressed();
finish();
}
}
|
package com.anderson.pontointeligente.api.services;
import java.util.List;
import java.util.Optional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import com.anderson.pontointeligente.api.entities.Lancamento;
public interface LancamentoService {
/**
* Retorna uma lista de lançamentos de determinado funcionário
*
* @param funcionarioId
* @return List<Lancamento>
*/
List<Lancamento> findByFuncionarioId(Long funcionarioId);
/**
* Retorna uma lista de lançamentos páginada de determinado funcionário
*
* @param funcionarioId
* @param pageRequest
* @return List<Lancamento>
*/
Page<Lancamento> findByFuncionarioId(Long funcionarioId, PageRequest pageRequest);
/**
* Retorna um lançamento por id
*
* @param id
* @return Lancamento
*/
Optional<Lancamento> findById(Long id);
/**
* Salva um lançamento na base de dados
*
* @param lancamento
* @return Lancamento
*/
Lancamento save(Lancamento lancamento);
/**
* Remove um lançamento da base de dados a partir de um id
*
* @param id
*/
void delete(Long id);
}
|
package com.android.cartloading.activities;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import com.android.cartloading.R;
/**
* Created by Toader on 6/6/2015.
*/
public class ToolbarActivity extends AppCompatActivity {
private Toolbar mToolbar;
private boolean mToolbarInitialized;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
protected void initializeToolbar() {
mToolbar = (Toolbar) findViewById(R.id.toolbar);
if (mToolbar == null) {
throw new IllegalStateException("Layout is required to include a Toolbar with id " +
"'toolbar'");
}
setSupportActionBar(mToolbar);
mToolbarInitialized = true;
}
}
|
package com.finalyearproject.spring.web.dao;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import com.finalyearproject.spring.web.entity.Comment;
import com.finalyearproject.spring.web.entity.Forum;
@Repository
@Transactional
@Component("CommentDao")
public class CommentDao {
@Autowired
private SessionFactory sessionFactory;
public Session session() {
return sessionFactory.getCurrentSession();
}
public Comment getComment(int id) {
Criteria crit = session().createCriteria(Comment.class);
crit.add(Restrictions.idEq(id));
return (Comment) crit.uniqueResult();
}
public void update(Comment commentObj) {
session().update(commentObj);
}
public void merge(Comment commentObj) {
session().merge(commentObj);
}
public void delete(Comment commentObj) {
// TODO Auto-generated method stub
session().delete(commentObj);
}
}
|
package com.jit.stream02;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
public class Test {
public static void main(String[] args) {
List<Integer> l1 = new ArrayList<Integer>();
for(int i=0;i<10;i++) {
l1.add(i);
}
List<Integer> l2 = l1.stream().map(I -> I*2).collect(Collectors.toList());
System.out.println(l2);
}
}
|
package person.zhao.threadExecutor.queue;
import java.util.concurrent.LinkedBlockingQueue;
import person.zhao.Utils;
/**
* 队列,线程安全
* 队列容量可以指定
* 队列容量满后,生产者进入堵塞状态
*
* 在本例中
* 生产者不停的生产
* 消费者每隔2秒消费
* 生产者会快速占满整个队列,然后进入堵塞状态
* 等待消费者消费后,继续生产
*
* @author zhao_hongsheng
*
*/
public class LinkedBlockingQueueDemo {
public void p() {
LinkedBlockingQueue<String> queue = new LinkedBlockingQueue<String>(5);
new Thread(new Producer2(queue)).start();
new Thread(new Consumer2(queue)).start();
}
public static void main(String[] args){
new LinkedBlockingQueueDemo().p();
}
}
/**
* 生产者,向queue中产生数据
* @author zhao_hongsheng
*
*/
class Producer2 implements Runnable {
private LinkedBlockingQueue<String> queue = null;
public Producer2(LinkedBlockingQueue<String> queue) {
this.queue = queue;
}
@Override
public void run() {
try {
while (true) {
String randomValue = (int)(Math.random() * 100) + 1 + "";
queue.put(randomValue);
System.out.println("生产:" + randomValue);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
/**
* 消费者,每隔2秒消费一个商品
* @author zhao_hongsheng
*
*/
class Consumer2 implements Runnable {
private LinkedBlockingQueue<String> queue = null;
public Consumer2(LinkedBlockingQueue<String> queue) {
this.queue = queue;
}
@Override
public void run() {
while (true) {
String p = queue.poll();
System.out.println("消费:" + p);
Utils.sleep(2);
}
}
}
|
/**
* This is a generated file. DO NOT EDIT ANY CODE HERE, YOUR CHANGES WILL BE LOST.
*/
package br.com.senior.furb.basico;
import br.com.senior.messaging.model.*;
@CommandDescription(name="generoEhFamoso", kind=CommandKind.Action, requestPrimitive="generoEhFamoso", responsePrimitive="generoEhFamosoResponse")
public interface GeneroEhFamoso extends MessageHandler {
public GeneroEhFamosoOutput generoEhFamoso(GeneroEhFamosoInput request);
}
|
package com.ginkgo.fms.util;
import org.junit.Test;
import com.ginkgo.bing.wallpaper.util.Keygen;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class KeygenTest {
@Test
public void test() {
//fail("Not yet implemented");
String gen = Keygen.keyGen("admin", "123456");
log.info("gen->" +gen);
String decodedGen = Keygen.unpack(gen);
log.info("decodedGen->" +decodedGen);
}
}
|
import java.io.*;
import java.lang.*;
import java.util.*;
// #!/usr/bin/python -O
// #include <stdio.h>
// #include <stdlib.h>
// #include <string.h>
// #include<stdbool.h>
// #include<limits.h>
// #include<iostream>
// #include<algorithm>
// #include<string>
// #include<vector>
// using namespace std;
/*
# Author : @RAJ009F
# Topic or Type : GFG/Amazon
# Problem Statement : FlipBits: 1. find max zeros with one flip operation ,2. max ones with one flip opertion
# Description :
# Complexity :
=======================
#sample output
----------------------
=======================
*/
class FlipBitsWithMaxOnesZeros
{
public int max(int a, int b)
{
return a>b?a:b;
}
public int max_ones(int arr[], int n)
{
int total_ones = 0;
int cur_max = 0;
int max_diff = 0;
for(int i=0; i<n; i++)
{
if(arr[i]==1)
total_ones++;
int val = (arr[i]==1)?-1:1;
cur_max = max(val, cur_max+val);
max_diff = max(cur_max, max_diff);
}
max_diff = max(0, max_diff);
return max_diff+total_ones;
}
public int max_zeors(int arr[], int n)
{
int total_zeroes = 0;
int cur_max = 0;
int max_diff = 0;
for(int i=0; i<n; i++)
{
if(arr[i]==0)
total_zeroes++;
int val = (arr[i]==0)?-1:1;
cur_max = max(val, cur_max+val);
max_diff = max(cur_max, max_diff);
}
max_diff = max(0, max_diff);
return max_diff+total_zeroes;
}
public static void main(String args[])
{
FlipBitsWithMaxOnesZeros fp = new FlipBitsWithMaxOnesZeros();
int arr[] = {0, 1, 0, 0, 1, 1, 0};
System.out.println("max noof ones: "+fp.max_ones(arr, arr.length));
System.out.println("max noof zeors: "+fp.max_zeors(arr, arr.length));
}
}
|
package com.zdp.ddshop.service;
import com.zdp.ddshop.common.dto.Page;
import com.zdp.ddshop.common.dto.Result;
import com.zdp.ddshop.pojo.po.TbItemParam;
import com.zdp.ddshop.pojo.vo.TbItemParamCustom;
public interface ItemParamService {
Result<TbItemParamCustom> listItemByPage(Page page);
int itemParamSave(Long cid, String paramData);
TbItemParam getParamById(Long cid);
}
|
package com.mmall.util;
import java.util.Properties;
import javax.mail.Address;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import com.mmall.common.Const;
/**
*
* 项目名称:mmall
* 类名称:EmailUtils
* 类描述:忘记密码邮件发送
* 创建人:xuzijia
* 创建时间:2017年10月15日 下午7:37:26
* 修改人:xuzijia
* 修改时间:2017年10月15日 下午7:37:26
* 修改备注:
* @version 1.0
*
*/
public class EmailUtils {
private static Session session;
static{
Properties props = new Properties();
// 开启debug调试
props.setProperty("mail.debug", "true");
// 发送服务器需要身份验证
props.setProperty("mail.smtp.auth", "true");
// 设置邮件服务器主机名
props.setProperty("mail.host", "smtp.163.com");
// 发送邮件协议名称
props.setProperty("mail.transport.protocol", "smtp");
// 设置环境信息
session = Session.getInstance(props);
}
public static void send(String accepter,String path) throws MessagingException {
// 创建邮件对象
Message msg = new MimeMessage(session);
msg.setSubject("[MMALL] Please reset your password");
// 设置邮件内容
msg.setText("重置密码请请点击该连接进行重置 ========--------------------=========token:"+path);
// 设置发件人
msg.setFrom(new InternetAddress(Const.EMAIL_SEND_USER));
Transport transport = session.getTransport();
// 连接邮件服务器
transport.connect(Const.EMAIL_HOST,Const.EMAIL_USERNAME,Const.EMAIL_PASSWORD);
// 发送邮件
transport.sendMessage(msg, new Address[] {new InternetAddress(accepter)});
// 关闭连接
transport.close();
}
}
|
package com.metoo.foundation.domain;
import javax.persistence.Entity;
import javax.persistence.Table;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
import com.metoo.core.constant.Globals;
import com.metoo.core.domain.IdEntity;
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
@Entity
@Table(name = Globals.DEFAULT_TABLE_SUFFIX + "botany")
public class Botany extends IdEntity{
}
|
package org.testing.testscript;
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class Youtube {
public static void main(String []args) throws InterruptedException
{
System.setProperty("webdriver.chrome.driver", "C:\\Users\\Awanish\\Downloads\\chromedriver_win32 (2)\\chromedriver.exe");
// a=45;
WebDriver driver= new ChromeDriver();
driver.get("https://www.youtube.com/");
Thread.sleep(3000);
driver.manage().window().maximize();
//WebElement sign=driver.findElement(By.cssSelector('yt-formatted-string:contains("Sign in")'));
driver.manage().timeouts().implicitlyWait(3, TimeUnit.SECONDS);
WebElement sign=driver.findElement(By.xpath("//yt-formatted-string[text()='Sign in']"));
sign.click();
WebElement Email= driver.findElement(By.xpath("//input[@id='identifierId']"));
Email.sendKeys("awanish.tiwari@abbieit.com");
WebElement next=driver.findElement(By.xpath("//span[text()='Next']"));
next.click();
WebElement pass= driver.findElement(By.xpath("//input[@autocomplete='current-password']"));
pass.sendKeys("Gmail@1234");
WebElement next2=driver.findElement(By.xpath("//span[text()='Next']"));
next2.click();
WebElement Trend=driver.findElement(By.xpath("//yt-formatted-string[text()='Trending']"));
Trend.click();
WebElement Game= driver.findElement(By.xpath("//div[text()='Gaming']"));
Game.click();
WebElement home=driver.findElement(By.xpath("//yt-formatted-string[text()='Home']"));
home.click();
WebElement play=driver.findElement(By.id("img"));
play.click();
}
}
|
/*
* Copyright (c) 2013 ICM Uniwersytet Warszawski All rights reserved.
* See LICENCE.txt file for licensing information.
*/
package pl.edu.icm.unity.ws.authn.ext;
import pl.edu.icm.unity.rest.authn.ext.TLSRetrievalBase;
import pl.edu.icm.unity.ws.authn.WebServiceAuthentication;
/**
* Retrieves certificate from the TLS
* @author K. Benedyczak
*/
public class TLSRetrieval extends TLSRetrievalBase implements WebServiceAuthentication
{
public TLSRetrieval()
{
super(WebServiceAuthentication.NAME);
}
}
|
/*
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.beans.factory.aot;
import java.lang.reflect.Executable;
import java.util.List;
import java.util.function.Predicate;
import org.springframework.aot.generate.GenerationContext;
import org.springframework.aot.generate.MethodReference;
import org.springframework.beans.factory.support.InstanceSupplier;
import org.springframework.beans.factory.support.RegisteredBean;
import org.springframework.beans.factory.support.RootBeanDefinition;
import org.springframework.core.ResolvableType;
import org.springframework.javapoet.ClassName;
import org.springframework.javapoet.CodeBlock;
/**
* Generate the various fragments of code needed to register a bean.
*
* @author Phillip Webb
* @since 6.0
*/
public interface BeanRegistrationCodeFragments {
/**
* The variable name to used when creating the bean definition.
*/
String BEAN_DEFINITION_VARIABLE = "beanDefinition";
/**
* The variable name to used when creating the bean definition.
*/
String INSTANCE_SUPPLIER_VARIABLE = "instanceSupplier";
/**
* Return the target for the registration. Used to determine where to write
* the code.
* @param registeredBean the registered bean
* @param constructorOrFactoryMethod the constructor or factory method
* @return the target {@link ClassName}
*/
ClassName getTarget(RegisteredBean registeredBean,
Executable constructorOrFactoryMethod);
/**
* Generate the code that defines the new bean definition instance.
* @param generationContext the generation context
* @param beanType the bean type
* @param beanRegistrationCode the bean registration code
* @return the generated code
*/
CodeBlock generateNewBeanDefinitionCode(GenerationContext generationContext,
ResolvableType beanType, BeanRegistrationCode beanRegistrationCode);
/**
* Generate the code that sets the properties of the bean definition.
* @param generationContext the generation context
* @param beanRegistrationCode the bean registration code
* @param attributeFilter any attribute filtering that should be applied
* @return the generated code
*/
CodeBlock generateSetBeanDefinitionPropertiesCode(
GenerationContext generationContext, BeanRegistrationCode beanRegistrationCode,
RootBeanDefinition beanDefinition, Predicate<String> attributeFilter);
/**
* Generate the code that sets the instance supplier on the bean definition.
* @param generationContext the generation context
* @param beanRegistrationCode the bean registration code
* @param instanceSupplierCode the instance supplier code supplier code
* @param postProcessors any instance post processors that should be applied
* @return the generated code
* @see #generateInstanceSupplierCode
*/
CodeBlock generateSetBeanInstanceSupplierCode(
GenerationContext generationContext, BeanRegistrationCode beanRegistrationCode,
CodeBlock instanceSupplierCode, List<MethodReference> postProcessors);
/**
* Generate the instance supplier code.
* @param generationContext the generation context
* @param beanRegistrationCode the bean registration code
* @param constructorOrFactoryMethod the constructor or factory method for
* the bean
* @param allowDirectSupplierShortcut if direct suppliers may be used rather
* than always needing an {@link InstanceSupplier}
* @return the generated code
*/
CodeBlock generateInstanceSupplierCode(
GenerationContext generationContext, BeanRegistrationCode beanRegistrationCode,
Executable constructorOrFactoryMethod, boolean allowDirectSupplierShortcut);
/**
* Generate the return statement.
* @param generationContext the generation context
* @param beanRegistrationCode the bean registration code
* @return the generated code
*/
CodeBlock generateReturnCode(
GenerationContext generationContext, BeanRegistrationCode beanRegistrationCode);
}
|
import java.util.*;
public class MyComparator implements Comparator<Node>
{
@Override
public int compare(Node x, Node y)
{
/**if(x.freq<y.freq)
return -1;
else
if(x.freq>y.freq)
return 1;
return 0;*/
return x.frequency - y.frequency;
}
}
//return ((Integer)d.age).compareTo(d1.age);
|
package com.UsingPojoClasses;
import com.Pojo.Delete_Pojo;
public class DeleteUsing_DeletePojo {
public Delete_Pojo deleteMethod() {
Delete_Pojo delete = new Delete_Pojo();
delete.setId(32);
return delete;
}
}
|
package KataProblems.week2.FindFibonacciLastDigit;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class FindFibonacciLastDigitTest {
@Test
public void example1(){
assertEquals(5, FindFibonacciLastDigit.getFibNumb(193150));
}
@Test
public void example2(){
assertEquals(0, FindFibonacciLastDigit.getFibNumb(300));
}
@Test
public void example3(){
assertEquals(6, FindFibonacciLastDigit.getFibNumb(20001));
}
}
|
package com.springlearnig.moviecatalogservice;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.context.annotation.Bean;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;
//import org.springframework.web.reactive.function.client.WebClient;
@SpringBootApplication
@EnableEurekaClient
public class MovieCatalogServiceApplication {
public static void main(String[] args) {
SpringApplication.run(MovieCatalogServiceApplication.class, args);
}
@LoadBalanced
@Bean
public RestTemplate getReatTemplate() {
HttpComponentsClientHttpRequestFactory clientHttpRequestFactory = new HttpComponentsClientHttpRequestFactory(); //it allows to create timeout property
clientHttpRequestFactory.setConnectTimeout(3000);
return new RestTemplate(clientHttpRequestFactory);
}
}
// @Bean
// public WebClient.Builder getWebClientBuilder(){
// return WebClient.builder();
// }
/*why annotation is loadbalanced taht not only is doing service discovery but it is also doing
load balancing client side load balancing
java -Dserver.port=8221 -jar movie-info-service-0.0.1-SNAPSHOT.jar
java -jar movie-info-service-0.0.1-SNAPSHOT.jar ///basically run class with main method inside it
Apache Maven is a popular build tool, that takes your project’s Java source code, compiles it,
tests it and converts it into an executable Java program: either a .jar or a .war file.
mvn clean install :->
mvn clean install is the command to do just that.
You are calling the mvn executable, which means you need Maven installed on your machine.
You are using the clean command, which will delete all previously compiled Java sources and
resources (like .properties) in your project. Your build will start from a clean slate.
Install will then compile, test & package your Java project and even install/copy your built .jar/.war file
into your local Maven repository.
------------------------------------------------------------------------------------
Now what exactly does a build tool do? Maven does three things rather well:
Dependency Management: Maven lets you easily include 3rd party dependencies (think libraries/frameworks
such as Spring) in your project. An equivalent in other languages would be Javascript’s npm, Ruby’s gems or
PHP’s composer.
Compilation through convention: In theory you could compile big Java projects with a ton of classes, by hand with
the javac command line compiler (or automate that with a bash script). This does however only work for toy projects.
Maven expects a certain directory structure for your Java source code to live in and when you later do a mvn clean
install , the whole compilation and packaging work will be done for you.
Everything Java: Maven can also run code quality checks, execute test cases and even deploy applications to remote
servers, through plugins. Pretty much every possible task you can think of.
------------------A pom.xml file contains everything needed to describe your Java project.
+ myproject
+ -- src
+ -- main
+ -- java
MyApp.java
+ -- target
+ -- classes (upon mvn compile)
MyApp.class
myproject.jar (upon mvn package or mvn install)
pom.xml
install JAR to local maven repository :->
mvn install:install-file \
-Dfile=<path-to-file> \
-DgroupId=<group-id> \
-DartifactId=<artifact-id> \
-Dversion=<version> \
-Dpackaging=<packaging> \
-DgeneratePom=true
*/
|
/*
Given a word and a dictionary, return the number of sentences the word can form,
by adding spaces between characters.
Input:
s = "catsanddog"
wordDict = ["cat", "cats", "and", "sand", "dog"]
Output: 2
because there are:
[
"cats and dog",
"cat sand dog"
]
Example 2:
Input:
s = "pineapplepenapple"
wordDict = ["apple", "pen", "applepen", "pine", "pineapple"]
Output: 3
because there are:
[
"pine apple pen apple",
"pineapple pen apple",
"pine applepen apple"
]
Explanation: Note that you are allowed to reuse a dictionary word.
*/
public class Solution {
public int wordBreak3(String s, Set<String> dict) {
int n = s.length();
String lowerS = s.toLowerCase();
Set<String> lowerDict = new HashSet<String>();
for(String str : dict) {
lowerDict.add(str.toLowerCase());
}
int[][] dp = new int[n][n];
for(int i = 0; i < n; i++){
for(int j = i; j < n;j++){
String sub = lowerS.substring(i, j + 1);
if(lowerDict.contains(sub)){
dp[i][j] = 1;
}
}
}
for(int i = 0; i < n; i++){
for(int j = i; j < n; j++){
for(int k = i; k < j; k++){
dp[i][j] += (dp[i][k] * dp[k + 1][j]);
}
}
}
return dp[0][n - 1];
}
}
|
package com.gezhiwei.projectstart.common;
/**
* @ClassName: DirConfig
* @Author: 葛志伟(赛事)
* @Description:
* @Date: 2019/1/9 12:14
* @modified By:
*/
public class DirConfig {
private String projectName;
private String packageName;
public DirConfig(String projectName, String packageName) {
this.packageName = packageName;
this.projectName = projectName;
}
public String getProjectName() {
return projectName;
}
public DirConfig setProjectName(String projectName) {
this.projectName = projectName;
return this;
}
public String getPackageName() {
return packageName;
}
public DirConfig setPackageName(String packageName) {
this.packageName = packageName;
return this;
}
}
|
package com.javarush.task.task08.task0812;
/**
* Created by varba on 19.03.2017.
*/
public class grym {
public static void main(String[] args) {
int b = 0;
for (int i = 0; i < 100; i++) {
b = b + i;
}
System.out.println(b);
}
}
|
package com.proxiad.games.extranet.utils;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
public class NetworkUtils {
public static String getIpString(String port) {
String ip;
try {
ip = NetworkUtils.getIpString();
} catch (SocketException e) {
e.printStackTrace();
return null;
}
if (ip.length() <= 16) {
String fullIp = ip;
fullIp += (port == null) ? "" : ":" + port;
return fullIp;
}
return ip;
}
private static String getIpString() throws SocketException {
StringBuilder ip = new StringBuilder();
Enumeration<NetworkInterface> e = NetworkInterface.getNetworkInterfaces();
while (e.hasMoreElements()) {
Enumeration<InetAddress> i = e.nextElement().getInetAddresses();
while (i.hasMoreElements()) {
InetAddress a = i.nextElement();
if (!a.isLoopbackAddress() && a.isSiteLocalAddress()) {
return a.getHostAddress();
}
ip.append(a.getHostName())
.append(" -> ")
.append(a.getHostAddress())
.append("\n\t isloopback? ")
.append(a.isLoopbackAddress())
.append("\n\t isSiteLocalAddress? ")
.append(a.isSiteLocalAddress())
.append("\n\t isIPV6? ")
.append((a instanceof Inet6Address))
.append("\n\n");
}
}
return ip.toString();
}
}
|
package swing;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JLabel;
import javax.swing.JComboBox;
import java.awt.Color;
import java.awt.Font;
import javax.swing.DefaultComboBoxModel;
public class scientific_cal {
private JFrame frame;
private JTextField textField;
private JTextField textField_1;
double num1;
double num2;
double result;
double result1;
String op;
String ans;
double united=302.96;
double india=100.96;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
scientific_cal window = new scientific_cal();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public scientific_cal() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame("Scientific Calculator");
frame.setBounds(100, 100, 848, 435);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JMenuBar menuBar = new JMenuBar();
frame.setJMenuBar(menuBar);
JMenu mnFile = new JMenu("File");
menuBar.add(mnFile);
JMenuItem mntmStandard_1 = new JMenuItem("Standard");
mntmStandard_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
frame.setBounds(100, 100, 357, 435);
textField.setBounds(30, 21, 500, 40);
}
});
mnFile.add(mntmStandard_1);
JMenuItem mntmNewMenuItem = new JMenuItem("Unit Conversion");
mntmNewMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
frame.setBounds(100, 100, 848, 435);
}
});
mnFile.add(mntmNewMenuItem);
JMenuItem mntmScientific = new JMenuItem("Scientific");
mntmScientific.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
frame.setBounds(100, 100, 623, 435);
}
});
mnFile.add(mntmScientific);
JMenuItem mntmStandard = new JMenuItem("Exit");
mntmStandard.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String Container frame = mntmStandard.getParent();
do
frame = frame.getParent();
while (!(frame instanceof JFrame));
((JFrame) frame).dispose();
}
});
mnFile.add(mntmStandard);
frame.getContentPane().setLayout(null);
textField = new JTextField();
textField.setBounds(10, 21, 314, 30);
frame.getContentPane().add(textField);
textField.setColumns(10);
JButton btnNewButton = new JButton("<-");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String b=null;
if(textField.getText().length()>0)
{
StringBuilder strB=new StringBuilder(textField.getText());
strB.deleteCharAt(textField.getText().length()-1);
b=strB.toString();
textField.setText(b);
}
}
});
btnNewButton.setBounds(10, 76, 64, 40);
frame.getContentPane().add(btnNewButton);
JButton btnCe = new JButton("CE");
btnCe.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String b=null;
if(textField.getText().length()>0)
{
StringBuilder strB=new StringBuilder(textField.getText());
strB.deleteCharAt(textField.getText().length()-1);
b=strB.toString();
textField.setText(b);
}
}
});
btnCe.setBounds(77, 76, 64, 40);
frame.getContentPane().add(btnCe);
JButton btnC = new JButton("C");
btnC.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
textField.setText("");
}
});
btnC.setBounds(144, 76, 64, 40);
frame.getContentPane().add(btnC);
JButton button = new JButton("+/-");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
num1=Double.parseDouble(textField.getText());
textField.setText("-"+num1);
//op="+/-";
}
});
button.setBounds(210, 76, 64, 40);
frame.getContentPane().add(button);
JButton btnSqrt = new JButton("sqrt");
btnSqrt.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
num1=Double.parseDouble(textField.getText());
num1=Math.sqrt(num1);
textField.setText(String.valueOf(num1));
}
});
btnSqrt.setBounds(276, 76, 64, 40);
frame.getContentPane().add(btnSqrt);
JButton btnL = new JButton("L..");
btnL.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
num1=Double.parseDouble(textField.getText());
num1=Math.sqrt(num1);
textField.setText(String.valueOf(num1));
}
});
btnL.setBounds(342, 76, 64, 40);
frame.getContentPane().add(btnL);
JButton btnSin = new JButton("Sin");
btnSin.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
num1=Double.parseDouble(textField.getText());
num1=Math.sin(num1);
textField.setText(String.valueOf(num1));
}
});
btnSin.setBounds(407, 76, 64, 40);
frame.getContentPane().add(btnSin);
JButton btnSinh = new JButton("Sinh");
btnSinh.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
num1=Double.parseDouble(textField.getText());
num1=Math.sinh(num1);
textField.setText(String.valueOf(num1));
}
});
btnSinh.setBounds(473, 76, 64, 40);
frame.getContentPane().add(btnSinh);
JButton btnMod = new JButton("Mod");
btnMod.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
num1=Double.parseDouble(textField.getText());
textField.setText("");
op="Mod";
}
});
btnMod.setBounds(538, 76, 64, 40);
frame.getContentPane().add(btnMod);
JButton button_1 = new JButton("7");
button_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String Number=textField.getText()+button_1.getText();
textField.setText(Number);
}
});
button_1.setBounds(10, 127, 64, 40);
frame.getContentPane().add(button_1);
JButton button_2 = new JButton("8");
button_2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String Number=textField.getText()+button_2.getText();
textField.setText(Number);
}
});
button_2.setBounds(77, 127, 64, 40);
frame.getContentPane().add(button_2);
JButton button_3 = new JButton("9");
button_3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String Number=textField.getText()+button_3.getText();
textField.setText(Number);
}
});
button_3.setBounds(144, 127, 64, 40);
frame.getContentPane().add(button_3);
JButton button_4 = new JButton("/");
button_4.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
num1=Double.parseDouble(textField.getText());
textField.setText("");
op="/";
}
});
button_4.setBounds(210, 127, 64, 40);
frame.getContentPane().add(button_4);
JButton button_5 = new JButton("%");
button_5.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
num1=Double.parseDouble(textField.getText());
textField.setText("");
op="%";
}
});
button_5.setBounds(276, 127, 64, 40);
frame.getContentPane().add(button_5);
JButton btnPie = new JButton("pie");
btnPie.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
num1=Double.parseDouble(textField.getText());
num1=num1*3.14;;
textField.setText(String.valueOf(num1));
}
});
btnPie.setBounds(342, 127, 64, 40);
frame.getContentPane().add(btnPie);
JButton btnCos = new JButton("cos");
btnCos.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
num1=Double.parseDouble(textField.getText());
num1=Math.cos(num1);
textField.setText(String.valueOf(num1));
}
});
btnCos.setBounds(407, 127, 64, 40);
frame.getContentPane().add(btnCos);
JButton btnCosh = new JButton("cosh");
btnCosh.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
num1=Double.parseDouble(textField.getText());
num1=Math.cosh(num1);
textField.setText(String.valueOf(num1));
}
});
btnCosh.setBounds(473, 127, 64, 40);
frame.getContentPane().add(btnCosh);
JButton btnLnx = new JButton("lnx");
btnLnx.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
num1=Double.parseDouble(textField.getText());
num1=Math.log(num1);
textField.setText(String.valueOf(num1));
}
});
btnLnx.setBounds(538, 127, 64, 40);
frame.getContentPane().add(btnLnx);
JButton button_10 = new JButton("4");
button_10.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String Number=textField.getText()+button_10.getText();
textField.setText(Number);
}
});
button_10.setBounds(10, 174, 64, 38);
frame.getContentPane().add(button_10);
JButton button_11 = new JButton("5");
button_11.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String Number=textField.getText()+button_11.getText();
textField.setText(Number);
}
});
button_11.setBounds(77, 174, 64, 38);
frame.getContentPane().add(button_11);
JButton button_12 = new JButton("6");
button_12.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String Number=textField.getText()+button_12.getText();
textField.setText(Number);
}
});
button_12.setBounds(144, 174, 64, 38);
frame.getContentPane().add(button_12);
JButton button_13 = new JButton("*");
button_13.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
num1=Double.parseDouble(textField.getText());
textField.setText("");
op="*";
}
});
button_13.setBounds(210, 174, 64, 38);
frame.getContentPane().add(button_13);
JButton btnx = new JButton("1/x");
btnx.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
num1=Double.parseDouble(textField.getText());
num1=(1/num1);
textField.setText(String.valueOf(num1));
}
});
btnx.setBounds(276, 174, 64, 38);
frame.getContentPane().add(btnx);
JButton btnXy = new JButton("x^y");
btnXy.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
num1=Double.parseDouble(textField.getText());
textField.setText("");
op="x^y";
}
});
btnXy.setBounds(342, 174, 64, 38);
frame.getContentPane().add(btnXy);
JButton btnTan = new JButton("tan");
btnTan.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
num1=Double.parseDouble(textField.getText());
num1=Math.tan(num1);
textField.setText(String.valueOf(num1));
}
});
btnTan.setBounds(407, 174, 64, 38);
frame.getContentPane().add(btnTan);
JButton btnTanh = new JButton("tanh");
btnTanh.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
num1=Double.parseDouble(textField.getText());
num1=Math.tanh(num1);
textField.setText(String.valueOf(num1));
}
});
btnTanh.setBounds(473, 174, 64, 38);
frame.getContentPane().add(btnTanh);
JButton btnC_1 = new JButton("c");
btnC_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
textField.setText("");
}
});
btnC_1.setBounds(538, 174, 64, 38);
frame.getContentPane().add(btnC_1);
JButton button_19 = new JButton("1");
button_19.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String Number=textField.getText()+button_19.getText();
textField.setText(Number);
}
});
button_19.setBounds(10, 223, 64, 39);
frame.getContentPane().add(button_19);
JButton button_20 = new JButton("2");
button_20.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String Number=textField.getText()+button_20.getText();
textField.setText(Number);
}
});
button_20.setBounds(77, 223, 64, 39);
frame.getContentPane().add(button_20);
JButton button_21 = new JButton("3");
button_21.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String Number=textField.getText()+button_21.getText();
textField.setText(Number);
}
});
button_21.setBounds(144, 223, 64, 39);
frame.getContentPane().add(button_21);
JButton button_22 = new JButton("-");
button_22.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
num1=Double.parseDouble(textField.getText());
textField.setText("");
op="-";
}
});
button_22.setBounds(210, 223, 64, 39);
frame.getContentPane().add(button_22);
JButton button_23 = new JButton("=");
button_23.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String ans;
num2=Double.parseDouble(textField.getText());
if(op=="+")
{
result=num1+num2;
ans=String.format("%.2f", result);
textField.setText(ans);
}
if(op=="-")
{
result=num1-num2;
ans=String.format("%.2f", result);
textField.setText(ans);
}
if(op=="*")
{
result=num1*num2;
ans=String.format("%.2f", result);
textField.setText(ans);
}
if(op=="/")
{
result=num1/num2;
ans=String.format("%.2f", result);
textField.setText(ans);
}
if(op=="%")
{
result=num1%num2;
ans=String.format("%.2f", result);
textField.setText(ans);
}
if(op=="x^y")
{
result=Math.pow(num1,num2);
//result1=Math.acos(result);
ans=String.format("%.2f", result);
textField.setText(ans);
}
if(op=="Mod")
{
result=num1%num2;
ans=String.format("%.2f", result);
textField.setText(ans);
}
if(op=="Cbr")
{
result=(num1*num2)/100;
ans=String.format("%.2f", result);
textField.setText(ans);
}
}
});
button_23.setBounds(276, 223, 64, 90);
frame.getContentPane().add(button_23);
JButton btnX = new JButton("x^2");
btnX.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
num1=Double.parseDouble(textField.getText());
num1=num1*num1;
textField.setText(String.valueOf(num1));
}
});
btnX.setBounds(342, 223, 64, 39);
frame.getContentPane().add(btnX);
JButton btnCbr = new JButton("Cbr");
btnCbr.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
num1=Double.parseDouble(textField.getText());
textField.setText("");
op="Cbr";
}
});
btnCbr.setBounds(407, 223, 64, 39);
frame.getContentPane().add(btnCbr);
JButton btnRund = new JButton("Rund");
btnRund.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
num1=Double.parseDouble(textField.getText());
num1=Math.round(num1);
textField.setText(String.valueOf(num1));
}
});
btnRund.setBounds(473, 223, 64, 39);
frame.getContentPane().add(btnRund);
JButton btnpie = new JButton("2*pie");
btnpie.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
num1=Double.parseDouble(textField.getText());
num1=2*3.14*num1;
textField.setText(String.valueOf(num1));
}
});
btnpie.setBounds(538, 223, 64, 39);
frame.getContentPane().add(btnpie);
JButton button_28 = new JButton("0");
button_28.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String Number=textField.getText()+button_28.getText();
textField.setText(Number);
}
});
button_28.setBounds(10, 273, 131, 40);
frame.getContentPane().add(button_28);
JButton button_30 = new JButton(".");
button_30.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String Number=textField.getText()+button_30.getText();
textField.setText(Number);
}
});
button_30.setBounds(144, 273, 64, 40);
frame.getContentPane().add(button_30);
JButton button_31 = new JButton("+");
button_31.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
num1=Double.parseDouble(textField.getText());
textField.setText("");
op="+";
}
});
button_31.setBounds(210, 273, 64, 40);
frame.getContentPane().add(button_31);
JButton btnX_1 = new JButton("x^3");
btnX_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
num1=Double.parseDouble(textField.getText());
num1=num1*num1*num1;
textField.setText(String.valueOf(num1));
}
});
btnX_1.setBounds(342, 273, 64, 40);
frame.getContentPane().add(btnX_1);
JButton btnBin = new JButton("Bin");
btnBin.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int a=Integer.parseInt(textField.getText());
textField.setText(Integer.toBinaryString(a));
}
});
btnBin.setBounds(407, 273, 64, 40);
frame.getContentPane().add(btnBin);
JButton btnHex = new JButton("Hex");
btnHex.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int a=Integer.parseInt(textField.getText());
textField.setText(Integer.toHexString(a));
}
});
btnHex.setBounds(473, 273, 64, 40);
frame.getContentPane().add(btnHex);
JButton btnOc = new JButton("Oc..");
btnOc.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int a=Integer.parseInt(textField.getText());
textField.setText(Integer.toOctalString(a));
}
});
btnOc.setBounds(538, 273, 64, 40);
frame.getContentPane().add(btnOc);
JPanel panel = new JPanel();
panel.setBackground(Color.GRAY);
panel.setBounds(604, 21, 223, 289);
frame.getContentPane().add(panel);
panel.setLayout(null);
JLabel lblNewLabel = new JLabel("Currency Converter");
lblNewLabel.setFont(new Font("Tahoma", Font.BOLD, 14));
lblNewLabel.setBounds(48, 11, 143, 14);
panel.add(lblNewLabel);
JComboBox comboBox = new JComboBox();
comboBox.setModel(new DefaultComboBoxModel(new String[] {"selected one..", "india", "united"}));
comboBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
comboBox.setBounds(66, 51, 104, 20);
panel.add(comboBox);
textField_1 = new JTextField();
textField_1.setBounds(78, 101, 86, 20);
panel.add(textField_1);
textField_1.setColumns(10);
JLabel label = new JLabel("");
label.setBounds(94, 161, 46, 14);
panel.add(label);
JButton btnNewButton_1 = new JButton("Convert");
btnNewButton_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
double bp=Double.parseDouble(textField_1.getText());
if(comboBox.getSelectedItem().equals("india"));
{
String c=String.format("Rs%.2f",bp*india);
label.setText(c);
}
if(comboBox.getSelectedItem().equals("united"));
{
String c=String.format("Rs%.2f",bp*united);
label.setText(c);
}
}
});
btnNewButton_1.setBounds(25, 211, 89, 23);
panel.add(btnNewButton_1);
JButton btnNewButton_2 = new JButton("Clear");
btnNewButton_2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
textField_1.setText("");
label.setText("");
}
});
btnNewButton_2.setBounds(124, 211, 89, 23);
panel.add(btnNewButton_2);
}
}
|
package com.dicoding.associate.latihan3;
import android.app.SearchManager;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import butterknife.BindView;
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
@BindView(R.id.picikan_peta) Button picikanPeta;
@Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
picikanPeta.setOnClickListener(this);
}
@Override
public void onClick(View gangan){
switch (gangan.getId()){
case R.id.picikan_peta:
String query = "https://www.bing.com/maps?osid=86eb845b-450f-4939-995e-f1aa4f79d9c9&cp=31.710201~35.071011&lvl=9&v=2&sV=2&form=S00027";
Intent intenttujuanAdin = new Intent(Intent.ACTION_WEB_SEARCH);
intenttujuanAdin.putExtra(SearchManager.QUERY,query );
startActivity(intenttujuanAdin);
break;
}
}
}
|
package at.fhooe.mc.calendar;
public class KategorieItem {
String title;
KategorieItem(String name){
title=name;
}
public String getTitle() {
return title;
}
}
|
package com.xinhua.xdcb;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlType;
/**
* <p>SrvResBizBody complex type�� Java �ࡣ
*
* <p>����ģʽƬ��ָ�������ڴ����е�Ԥ�����ݡ�
*
* <pre>
* <complexType name="SrvResBizBody">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="freshPolicySignRspData" type="{http://ws.freshpolicysign.exports.bankpolicy.interfaces.nb.tunan.nci.com/}freshPolicySignRspData" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "SrvResBizBody", propOrder = {
"freshPolicySignRspData"
})
public class SrvResBizBody {
protected FreshPolicySignRspData freshPolicySignRspData;
/**
* ��ȡfreshPolicySignRspData���Ե�ֵ��
*
* @return
* possible object is
* {@link FreshPolicySignRspData }
*
*/
public FreshPolicySignRspData getFreshPolicySignRspData() {
return freshPolicySignRspData;
}
/**
* ����freshPolicySignRspData���Ե�ֵ��
*
* @param value
* allowed object is
* {@link FreshPolicySignRspData }
*
*/
public void setFreshPolicySignRspData(FreshPolicySignRspData value) {
this.freshPolicySignRspData = value;
}
}
|
package xdroid.example.settings;
import android.app.Activity;
import android.os.Bundle;
import android.preference.CheckBoxPreference;
import android.preference.EditTextPreference;
import android.preference.Preference;
import android.preference.PreferenceFragment;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import xdroid.example.R;
public class SettingsActivity extends Activity {
@Override
public void onCreate(Bundle state) {
super.onCreate(state);
ViewGroup container = new FrameLayout(this);
container.setId(R.id.container);
setContentView(container);
}
public static class SettingsFragment extends PreferenceFragment {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.settings);
CheckBoxPreference myFlag = (CheckBoxPreference) findPreference("my.flag");
myFlag.setChecked(Settings.MY_FLAG.get.asBoolean());
myFlag.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
if (newValue instanceof Boolean) {
Settings.MY_FLAG.set.asBoolean((Boolean) newValue);
return true;
}
return false;
}
});
EditTextPreference myNumber = (EditTextPreference) findPreference("my.number");
myNumber.setText(String.valueOf(Settings.MY_NUMBER.get.asInt()));
myNumber.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
if (newValue instanceof String) {
Settings.MY_NUMBER.set.asInt(Integer.parseInt((String) newValue));
return true;
}
return false;
}
});
}
}
}
|
package Inheritance_Hierarchy;
public class Square extends Rectangle{
public int MainLength;
public Square(int x1,int y1,int x2,int y2){
super(x1, y1, x2, y2,0,0);
MainLength=LengthA();
}
@Override
public int getArea(){
return (int) Math.pow(MainLength, 2);
}
}
|
package me.ewriter.daynightsample;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ObjectAnimator;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.util.TypedValue;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import me.ewriter.nightmodedemo.R;
public class ZhihuActivity extends AppCompatActivity {
Bitmap bp = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
initTheme();
setContentView(R.layout.activity_zhihu);
}
// setTheme 必须在 setContentView 之前才能生效
private void initTheme() {
SharedPreferences sharedPreferences = this.getPreferences(Context.MODE_PRIVATE);
boolean isNight = sharedPreferences.getBoolean("isNight", false);
if (isNight) {
setTheme(R.style.Night);
} else {
setTheme(R.style.Day);
}
}
public void onZhihuClick(View view) {
// 切换主题设置
SharedPreferences sharedPreferences = this.getPreferences(Context.MODE_PRIVATE);
boolean isNight = sharedPreferences.getBoolean("isNight", false);
if (isNight) {
setTheme(R.style.Day);
sharedPreferences.edit().putBoolean("isNight", false).commit();
} else {
setTheme(R.style.Night);
sharedPreferences.edit().putBoolean("isNight", true).commit();
}
showAnim();
refresh();
// 或者这里直接 recreate ,但是这个会闪一下,体验不是很好
// recreate();
}
private void showAnim() {
final View decorView = getWindow().getDecorView();
// 设置false 清除缓存
decorView.setDrawingCacheEnabled(false);
// 设置为 true 获取 bitmap
decorView.setDrawingCacheEnabled(true);
decorView.buildDrawingCache(true);
Bitmap cacheBitmap = null;
if (decorView.getDrawingCache() != null) {
cacheBitmap = Bitmap.createBitmap(decorView.getDrawingCache());
decorView.setDrawingCacheEnabled(false);
}
if (decorView instanceof ViewGroup && cacheBitmap != null) {
final View view = new View(this);
view.setBackgroundDrawable(new BitmapDrawable(getResources(), cacheBitmap));
ViewGroup.LayoutParams layoutParam = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT);
((ViewGroup) decorView).addView(view, layoutParam);
ObjectAnimator objectAnimator = ObjectAnimator.ofFloat(view, "alpha", 1f, 0f);
objectAnimator.setDuration(500);
objectAnimator.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
super.onAnimationEnd(animation);
((ViewGroup) decorView).removeView(view);
}
});
objectAnimator.start();
}
}
/**
* 更新layout的 view,可以更新部分或者全部来避免通过 recreate 造成的闪烁问题
* 使用这种方法需要处理好各种 view 来进行设置
* */
private void refresh() {
TypedValue background = new TypedValue();
TypedValue textColor = new TypedValue();
Resources.Theme theme = getTheme();
theme.resolveAttribute(R.attr.colorBackground, background, true);
theme.resolveAttribute(R.attr.colorTextView, textColor, true);
findViewById(R.id.background).setBackgroundColor(background.data);
TextView text = (TextView) findViewById(R.id.text);
text.setTextColor(textColor.data);
// statusBar and actionbar
if (Build.VERSION.SDK_INT >= 21) {
TypedValue typedValue = new TypedValue();
TypedValue typedValue1 = new TypedValue();
Resources.Theme theme1 = getTheme();
theme1.resolveAttribute(R.attr.colorPrimaryDark, typedValue, true);
theme1.resolveAttribute(R.attr.colorPrimary, typedValue1, true);
getWindow().setStatusBarColor(getResources().getColor(typedValue.resourceId));
getSupportActionBar().setBackgroundDrawable(new ColorDrawable(typedValue1.data));
}
}
public void onTransferActivityClick(View view) {
// 获取屏幕当前截图
final View decorView = getWindow().getDecorView().getRootView();
// 设置false 清除缓存
decorView.setDrawingCacheEnabled(false);
// 设置为 true 获取 bitmap
decorView.setDrawingCacheEnabled(true);
decorView.buildDrawingCache(true);
if (decorView.getDrawingCache() != null) {
bp = Bitmap.createBitmap(decorView.getDrawingCache());
decorView.setDrawingCacheEnabled(false);
}
// bitmap 数据太大,直接传 intent 会报错
FileOutputStream fos = null;
try {
fos = new FileOutputStream(new File(this.getCacheDir().getAbsolutePath() + "/intent.png"));
bp.compress(Bitmap.CompressFormat.PNG, 100, fos);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
Intent intent = new Intent(this, TansferActivity.class);
// intent.putExtra("bitmap", bp);
startActivity(intent);
this.overridePendingTransition(R.anim.none, R.anim.none);
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
SharedPreferences sharedPreferences = getPreferences(Context.MODE_PRIVATE);
boolean isNight = sharedPreferences.getBoolean("isNight", false);
if (isNight) {
setTheme(R.style.Day);
sharedPreferences.edit().putBoolean("isNight", false).commit();
} else {
setTheme(R.style.Night);
sharedPreferences.edit().putBoolean("isNight", true).commit();
}
recreate();
}
},50);
}
}
|
package urstory.ganada;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
/**
* Created by urstory on 2016. 6. 30..
*/
@Getter
@Setter
@NoArgsConstructor
@ToString
public class GanadaPage {
private String title;
private String url;
private String question;
private String answer;
private String questionHtml;
private String answerHtml;
}
|
package webapp;
import org.apache.wicket.Page;
import org.apache.wicket.cdi.CdiConfiguration;
import org.apache.wicket.protocol.http.WebApplication;
import org.jboss.weld.environment.servlet.Listener;
import javax.enterprise.inject.spi.BeanManager;
/**
* @author simetrias
*/
public class DevWebApplication extends WebApplication {
@Override
public Class<? extends Page> getHomePage() {
return CanvasPage.class;
}
@Override
protected void init() {
super.init();
BeanManager manager = (BeanManager) getServletContext().getAttribute(Listener.BEAN_MANAGER_ATTRIBUTE_NAME);
new CdiConfiguration(manager).configure(this);
}
}
|
package com.pdd.pop.sdk.http;
import com.pdd.pop.sdk.common.exception.PopClientException;
import com.pdd.pop.sdk.common.util.PreconditionUtil;
import com.pdd.pop.sdk.http.client.AbstractPopClient;
import com.pdd.pop.sdk.http.client.HttpClientFactory;
import com.pdd.pop.ext.apache.http.impl.client.CloseableHttpClient;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
public class PopHttpClient extends AbstractPopClient {
private ExecutorService executorService;
public PopHttpClient(String clientId, String clientSecret) {
this(clientId, clientSecret, HttpClientConfig.getDefault());
}
public PopHttpClient(String apiServerUrl, String clientId, String clientSecret) {
this(clientId, clientSecret, HttpClientConfig.getDefault());
this.apiServerUrl = apiServerUrl;
}
public PopHttpClient(String clientId, String clientSecret, CloseableHttpClient closeableHttpClient) {
PreconditionUtil.checkNotNull(closeableHttpClient);
PreconditionUtil.checkNotNull(clientId);
PreconditionUtil.checkNotNull(clientSecret);
this.clientId = clientId;
this.clientSecret = clientSecret;
httpClient = closeableHttpClient;
executorService = getDefaultExecutorService();
}
public PopHttpClient(String clientId, String clientSecret, HttpClientConfig config) {
PreconditionUtil.checkNotNull(clientId);
PreconditionUtil.checkNotNull(clientSecret);
this.clientId = clientId;
this.clientSecret = clientSecret;
httpClient = HttpClientFactory.getHttpClient(config);
if (config.getExecutorService() == null) {
executorService = getDefaultExecutorService();
} else {
executorService = config.getExecutorService();
}
}
public <T extends PopBaseHttpResponse> T syncInvoke(PopBaseHttpRequest<T> request) throws Exception {
return syncInvoke(request,null);
}
/**
* 同步执行请求
*
* @param request : 请求参数
* @param accessToken : 鉴权token
* @return 继承于 PopBaseHttpResponse的响应
* @throws Exception
*/
public <T extends PopBaseHttpResponse> T syncInvoke(PopBaseHttpRequest<T> request, String accessToken) throws Exception {
switch (request.getHttpMethod()) {
case GET:
return syncGet(request,accessToken);
case POST:
return syncPost(request,accessToken);
default:
throw new PopClientException(ClientErrorCode.ILLEGAL_HTTP_METHOD);
}
}
/**
* 异步执行请求
* @param request : 请求参数
* @param <T>
* @return Future<PopBaseHttpResponse>的响应
* @throws Exception
*/
public <T extends PopBaseHttpResponse> Future<T> asyncInvoke(final PopBaseHttpRequest<T> request) throws Exception {
return asyncInvoke(request,null);
}
/**
* 异步执行请求
*
* @param request : 请求参数
* @param accessToken : 鉴权token
* @return Future<PopBaseHttpResponse>的响应
* @throws Exception
*/
public <T extends PopBaseHttpResponse> Future<T> asyncInvoke(final PopBaseHttpRequest<T> request, final String accessToken) throws Exception {
PreconditionUtil.checkNotNull(executorService);
return executorService.submit(new Callable<T>() {
public T call() throws Exception {
return syncInvoke(request,accessToken);
}
});
}
}
|
package netUtils;
import concurrentUtils.Channel;
import concurrentUtils.Stoppable;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.util.ArrayList;
/**
* Created by 14Malgavka on 10.02.2017.
*/
public class Host implements Stoppable {
private Integer port;
private Channel channel;
private ServerSocket serverSocket;
private MessageHandlerFactory messageHandlerFactory;
private volatile boolean isActive;
private ArrayList<Socket> allClients = new ArrayList<Socket>();
public Host(Integer port, Channel channel, MessageHandlerFactory messageHandlerFactory) {
this.port = port;
this.channel = channel;
this.messageHandlerFactory = messageHandlerFactory;
isActive = true;
try {
serverSocket = new ServerSocket(this.port);
} catch (IOException e) {
System.out.printf("Port problems\n%s%n", e.getMessage());
}
}
@Override
public void run() {
try {
while (isActive) {
Socket socket = serverSocket.accept();
channel.put(new Session(socket, messageHandlerFactory.createMessageHandler(this)));
allClients.add(socket);
}
} catch (SocketException e) {
System.out.println("Some problems: " + e.getMessage());
} catch (IOException e) {
System.out.printf("Port problems\n%s%n", e.getMessage());
}
}
@Override
public void stop() {
if (isActive)
isActive = false;
try {
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public ArrayList<Socket> getAllClients()
{
return allClients;
}
}
|
package com.smartsampa.shapefileapi;
import org.junit.Ignore;
import org.junit.Test;
/**
* Created by ruan0408 on 22/03/2016.
*/
public class ShapefileAPITest {
private ShapefileAPI shapefileApi;
@Ignore
@Test
public void testPrintBusLanesProperties() throws Exception {
shapefileApi = new ShapefileAPI("faixa_onibus/sirgas_faixa_onibus.shp");
shapefileApi.printProperties();
}
@Ignore
@Test
public void testPrintPropertiesToFile() throws Exception {
shapefileApi.printPropertiesToFile();
}
}
|
package sistematcc;
import DAO.AlunoDAO;
import java.util.ArrayList;
import javax.swing.JButton;
import javax.swing.JOptionPane;
import models.Aluno;
import models.Serializar;
import models.tableModelCrudAluno;
/**
*
* @author rob
*/
public class CrudAluno extends javax.swing.JPanel {
tableModelCrudAluno modelo;
AlunoDAO lista;
public CrudAluno(AlunoDAO listaAlunos) {
this.lista = listaAlunos;
modelo = new tableModelCrudAluno();
initComponents();
jTable1.setModel(modelo);
popularTabela();
}
public void popularTabela() {
ArrayList<Aluno> lista = Serializar.load("alunos.ser");
for(Aluno i : lista){
modelo.addRow(i);
}
}
/**
* 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() {
jScrollPane1 = new javax.swing.JScrollPane();
jTable1 = new javax.swing.JTable();
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
matricula = new javax.swing.JTextField();
nome = new javax.swing.JTextField();
telefone = new javax.swing.JTextField();
email = new javax.swing.JTextField();
jButton1 = new javax.swing.JButton();
jButton2 = new javax.swing.JButton();
jButton3 = new javax.swing.JButton();
confirmar = new javax.swing.JButton();
jTable1.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null, null, null},
{null, null, null, null},
{null, null, null, null},
{null, null, null, null}
},
new String [] {
"Title 1", "Title 2", "Title 3", "Title 4"
}
));
jScrollPane1.setViewportView(jTable1);
jLabel1.setText("Nome:");
jLabel2.setText("Matricula:");
jLabel3.setText("Email:");
jLabel4.setText("Telefone:");
jButton1.setText("Adicionar");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jButton2.setText("Excluir");
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(evt);
}
});
jButton3.setText("Alterar");
jButton3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton3ActionPerformed(evt);
}
});
confirmar.setText("VOLTAR PARA PAGINA DE LOGIN");
confirmar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
confirmarActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(12, 12, 12)
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 730, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel1)
.addGap(38, 38, 38)
.addComponent(nome, javax.swing.GroupLayout.PREFERRED_SIZE, 130, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(matricula, javax.swing.GroupLayout.PREFERRED_SIZE, 131, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel4)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(telefone))
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel3)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(email, javax.swing.GroupLayout.PREFERRED_SIZE, 182, javax.swing.GroupLayout.PREFERRED_SIZE))))
.addGroup(layout.createSequentialGroup()
.addComponent(jButton1)
.addGap(18, 18, 18)
.addComponent(jButton2)
.addGap(18, 18, 18)
.addComponent(jButton3)))
.addGap(255, 255, 255)))
.addContainerGap())
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(confirmar)
.addGap(252, 252, 252))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGap(21, 21, 21)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(jLabel3)
.addComponent(nome, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(email, javax.swing.GroupLayout.PREFERRED_SIZE, 19, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2)
.addComponent(jLabel4)
.addComponent(matricula, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(telefone, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(31, 31, 31)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButton1)
.addComponent(jButton2)
.addComponent(jButton3))
.addGap(18, 18, 18)
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 301, Short.MAX_VALUE)
.addGap(18, 18, 18)
.addComponent(confirmar)
.addGap(21, 21, 21))
);
}// </editor-fold>//GEN-END:initComponents
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
if(!(nome.getText().isEmpty()) && !(matricula.getText().isEmpty())
&& !(email.getText().isEmpty()) && !(telefone.getText().isEmpty())) {
Aluno novoAluno = new Aluno(nome.getText(), matricula.getText(),
email.getText(), telefone.getText());
if(lista.add(novoAluno)) {
modelo.addRow(novoAluno);
}
}
else
JOptionPane.showMessageDialog(null, "Preencha todos os campos");
}//GEN-LAST:event_jButton1ActionPerformed
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
int linha = jTable1.getSelectedRow();
if(linha != -1) {
Object nomeAluno = modelo.getValueAt(linha, 0);
Aluno alunoExcluido = lista.search((String)nomeAluno);
if(lista.remove(alunoExcluido))
modelo.removeRow(linha);
}
}//GEN-LAST:event_jButton2ActionPerformed
public JButton getConfirmar() {
return confirmar;
}
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
if(!(nome.getText().isEmpty()) && !(matricula.getText().isEmpty())
&& !(email.getText().isEmpty()) && !(telefone.getText().isEmpty())) {
Aluno novoAluno = new Aluno(nome.getText(), matricula.getText(),
email.getText(), telefone.getText());
Aluno alunoAntigo;
if(jTable1.getSelectedRow() != -1) {
Object nomeAluno = modelo.getValueAt(jTable1.getSelectedRow(), 0);
alunoAntigo = lista.search((String)nomeAluno);
if(lista.update(alunoAntigo, novoAluno)){
int linha = jTable1.getSelectedRow();
modelo.setValueAt(novoAluno.getNome(), linha, 0);
modelo.setValueAt(novoAluno.getEmail(),linha,1);
modelo.setValueAt(novoAluno.getMatricula(), linha, 2);
modelo.setValueAt(novoAluno.getTelefone(), linha, 3);
modelo.fireTableDataChanged();
}
}
else {
JOptionPane.showMessageDialog(null, "Selecione um Aluno");
}
}
else {
JOptionPane.showMessageDialog(null,"Preencha todos os campos");
}
}//GEN-LAST:event_jButton3ActionPerformed
private void confirmarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_confirmarActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_confirmarActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton confirmar;
private javax.swing.JTextField email;
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JButton jButton3;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTable jTable1;
private javax.swing.JTextField matricula;
private javax.swing.JTextField nome;
private javax.swing.JTextField telefone;
// End of variables declaration//GEN-END:variables
}
|
package model;
import java.util.ArrayList;
public class StableUser extends User {
/**
*
*/
private static final long serialVersionUID = -9051743265634088553L;
private double annual;
private double bonus;
public StableUser()
{
annual = 15000;
bonus = 0;
}
public void addAnnual(double amount){
annual = amount;
}
public void addBonus(double bonusAmount){
annual += bonusAmount;
}
public double getAnnual(){
return annual;
}
/*
public double getTimeForGoals(){
double income = annual;
double goals = getTotalGoalCost();
return (goals-getWallet())/income;
}
*/
}
|
package sop.web.management;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import dwz.framework.config.Constants;
import dwz.framework.user.User;
import dwz.framework.user.UserServiceMgr;
import dwz.web.BaseController;
import sop.persistence.beans.SysUser;
import sop.reports.vo.ReportResult;
import sop.services.OfferSheetServiceMgr;
import sop.services.ReportServiceMgr;
import sop.vo.ItemMasterConditionVo;
import sop.vo.OfferSheetCombos;
import sop.vo.OfferSheetConditionVo;
import sop.vo.PoSearchItemConditionVo;
import sop.vo.PoSoSearchItemReportConditionVo;
import sop.vo.SearchItemReportConditionVo;
import sop.vo.SoPoConditionVo;
/**
* @Author: LCF
* @Date: 2020/1/9 12:58
* @Package: sop.web.management
*/
@Controller("management.reportController")
@RequestMapping(value = "/management/reports")
public class ReportController extends BaseController {
@Autowired
private ReportServiceMgr reportMgr;
@Autowired
private OfferSheetServiceMgr offerSheetMgr;
@Autowired
private UserServiceMgr userMgr;
@RequestMapping("/offabcostprice")
public String offAbCostPrice(ModelMap model) {
OfferSheetCombos offerSheetCombos = offerSheetMgr.getOfferSheetCombos();
model.addAttribute("offerSheetCombos", offerSheetCombos);
return "/management/reports/offabcostprice";
}
@RequestMapping(value = "/offabcostpricereports", method = RequestMethod.POST)
@ResponseBody
public Map<String, Object> offAbCostPriceReports(OfferSheetConditionVo vo, HttpServletRequest request) {
User currentUser = (User) request.getSession().getAttribute(Constants.AUTHENTICATION_KEY);
String coCode = "";
if (currentUser != null) {
coCode = currentUser.getCoCode();
} else {
coCode = "RRR";
}
ReportResult offAbCostPriceResult = reportMgr.getOffAbCostPriceReport(vo, coCode);
Map<String, Object> result = new HashMap<String, Object>();
result.put("result", offAbCostPriceResult);
return result;
}
//itemmaster list page
@RequestMapping("/itemmaster")
public String itemMaster() {
return "/management/reports/itemmaster";
}
//itemmaster list report
@RequestMapping(value = "/itemmasterreports", method = RequestMethod.POST)
@ResponseBody
public Map<String, Object> itemMasterReports(ItemMasterConditionVo vo, HttpServletRequest request) {
User currentUser = (User) request.getSession().getAttribute(Constants.AUTHENTICATION_KEY);
String coCode = "";
if (currentUser != null) {
coCode = currentUser.getCoCode();
} else {
coCode = "RRR";
}
ReportResult itemMasterResult = reportMgr.getItemMasterReport(vo, coCode);
Map<String, Object> result = new HashMap<String, Object>();
result.put("result", itemMasterResult);
return result;
}
//OFFERSHEET page
@RequestMapping("/offersheet")
public String offerSheet(ModelMap model) {
OfferSheetCombos offerSheetCombos = offerSheetMgr.getOfferSheetCombos();
model.addAttribute("offerSheetCombos", offerSheetCombos);
return "/management/reports/simplifiedoffersheet";
}
//OFFERSHEET report
@RequestMapping(value = "/offersheetreports", method = RequestMethod.POST)
@ResponseBody
public Map<String, Object> offerSheetReports(ItemMasterConditionVo vo, HttpServletRequest request) {
User currentUser = (User) request.getSession().getAttribute(Constants.AUTHENTICATION_KEY);
String coCode = "";
if (currentUser != null) {
coCode = currentUser.getCoCode();
} else {
coCode = "RRR";
}
ReportResult itemMasterResult = reportMgr.getItemMasterReport(vo, coCode);
Map<String, Object> result = new HashMap<String, Object>();
result.put("result", itemMasterResult);
return result;
}
//A&B price list page
@RequestMapping("/abpricelist")
public String abPrice(ModelMap model) {
OfferSheetCombos offerSheetCombos = offerSheetMgr.getOfferSheetCombos();
model.addAttribute("offerSheetCombos", offerSheetCombos);
return "/management/reports/abpricelist";
}
//A&B price list report
@RequestMapping(value = "/abpricelistreports", method = RequestMethod.POST)
@ResponseBody
public Map<String, Object> abPriceListReports(OfferSheetConditionVo vo, HttpServletRequest request) {
User currentUser = (User) request.getSession().getAttribute(Constants.AUTHENTICATION_KEY);
String coCode = "";
if (currentUser != null) {
coCode = currentUser.getCoCode();
} else {
coCode = "RRR";
}
ReportResult abPriceListResult = reportMgr.getABPriceListReport(vo, coCode);
Map<String, Object> result = new HashMap<String, Object>();
result.put("result", abPriceListResult);
return result;
}
//COST PRICE LIST page
@RequestMapping("/costpricelist")
public String costPriceList(ModelMap model) {
OfferSheetCombos offerSheetCombos = offerSheetMgr.getOfferSheetCombos();
model.addAttribute("offerSheetCombos", offerSheetCombos);
return "/management/reports/costpricelist";
}
//COST PRICE LIST report
@RequestMapping(value = "/costpricelistreports", method = RequestMethod.POST)
@ResponseBody
public Map<String, Object> costPriceListReports(OfferSheetConditionVo vo, HttpServletRequest request) {
User currentUser = (User) request.getSession().getAttribute(Constants.AUTHENTICATION_KEY);
String coCode = "";
if (currentUser != null) {
coCode = currentUser.getCoCode();
} else {
coCode = "RRR";
}
ReportResult costPriceListResult = reportMgr.getCostPriceListReport(vo, coCode);
Map<String, Object> result = new HashMap<String, Object>();
result.put("result", costPriceListResult);
return result;
}
//offersheet list item page
@RequestMapping("/offlistitem")
public String offListItem() {
return "/management/reports/offlistitem";
}
//offersheet list item report
@RequestMapping(value = "/offlistitemreports", method = RequestMethod.POST)
@ResponseBody
public Map<String, Object> offListItemReports(ItemMasterConditionVo vo, HttpServletRequest request) {
User currentUser = (User) request.getSession().getAttribute(Constants.AUTHENTICATION_KEY);
String coCode = "";
if (currentUser != null) {
coCode = currentUser.getCoCode();
} else {
coCode = "RRR";
}
ReportResult offListItemResult = reportMgr.getOffListItemReport(vo, coCode);
Map<String, Object> result = new HashMap<String, Object>();
result.put("result", offListItemResult);
return result;
}
//P/I page
@RequestMapping("/proformainvoice")
public String proformaInvoice() {
return "/management/reports/proformainvoice";
}
//P/I report
@RequestMapping(value = "/proformainvoicereports", method = RequestMethod.POST)
@ResponseBody
public Map<String, Object> proformaInvoiceReports(SoPoConditionVo vo, HttpServletRequest request) {
User currentUser = (User) request.getSession().getAttribute(Constants.AUTHENTICATION_KEY);
String coCode = "";
if (currentUser != null) {
coCode = currentUser.getCoCode();
} else {
coCode = "RRR";
}
ReportResult itemMasterResult = reportMgr.getProformaInvoiceReport(vo);
Map<String, Object> result = new HashMap<String, Object>();
result.put("result", itemMasterResult);
return result;
}
//P/O page
@RequestMapping("/purchaseorder")
public String purchaseorder() {
return "/management/reports/purchaseorder";
}
//P/O report
@RequestMapping(value = "/purchaseorderreports", method = RequestMethod.POST)
@ResponseBody
public Map<String, Object> purchaseOrderReports(PoSearchItemConditionVo vo, HttpServletRequest request) {
User currentUser = (User) request.getSession().getAttribute(Constants.AUTHENTICATION_KEY);
String coCode = "";
if (currentUser != null) {
coCode = currentUser.getCoCode();
} else {
coCode = "RRR";
}
ReportResult purchaseOrderResult = reportMgr.getPurchaseOrderReport(vo, coCode);
Map<String, Object> result = new HashMap<String, Object>();
result.put("result", purchaseOrderResult);
return result;
}
//Simpliefied offersheet (2 photo) page
@RequestMapping("/simplifiedoffersheet")
public String simplifiedOfferSheet() {
return "/management/reports/simplifiedoffersheet";
}
//Simpliefied offersheet (2 photo) report
@RequestMapping(value = "/simplifiedoffersheetreports", method = RequestMethod.POST)
@ResponseBody
public Map<String, Object> simplifiedOfferSheetReports(OfferSheetConditionVo vo, HttpServletRequest request) {
User currentUser = (User) request.getSession().getAttribute(Constants.AUTHENTICATION_KEY);
String coCode = "";
if (currentUser != null) {
coCode = currentUser.getCoCode();
} else {
coCode = "RRR";
}
ReportResult simplfiedOffResult = reportMgr.getSimplfiedOffReport(vo, coCode);
Map<String, Object> result = new HashMap<String, Object>();
result.put("result", simplfiedOffResult);
return result;
}
//PROFORMA- CO.HEADER 3 page
@RequestMapping("/proformacoheader3")
public String proformaCoHeader3() {
return "/management/reports/proformacoheader3";
}
//PROFORMA- CO.HEADER 3 report
@RequestMapping(value = "/proformacoheader3reports", method = RequestMethod.POST)
@ResponseBody
public Map<String, Object> proformaCoHeader3Reports(SoPoConditionVo vo, HttpServletRequest request) {
User currentUser = (User) request.getSession().getAttribute(Constants.AUTHENTICATION_KEY);
String coCode = "";
if (currentUser != null) {
coCode = currentUser.getCoCode();
} else {
coCode = "RRR";
}
ReportResult itemMasterResult = reportMgr.getProformaCoHeaderReport(vo);
Map<String, Object> result = new HashMap<String, Object>();
result.put("result", itemMasterResult);
return result;
}
//SALES ITEM OVERVIEW page
@RequestMapping("/salesitemoverview")
public String salesItemOverview() {
return "/management/reports/salesitemoverview";
}
//SALES ITEM OVERVIEW report
@RequestMapping(value = "/salesitemoverviewreports", method = RequestMethod.POST)
@ResponseBody
public Map<String, Object> salesItemOverviewReports(HttpServletRequest request) {
User currentUser = (User) request.getSession().getAttribute(Constants.AUTHENTICATION_KEY);
String coCode = "";
if (currentUser != null) {
coCode = currentUser.getCoCode();
} else {
coCode = "RRR";
}
String p_year = request.getParameter("year");
String p_handle = request.getParameter("handle");
String p_cu_code = request.getParameter("cu_code");
ReportResult itemMasterResult = reportMgr.getSalesItemOverviewReport(p_year, p_handle, p_cu_code);
Map<String, Object> result = new HashMap<String, Object>();
result.put("result", itemMasterResult);
return result;
}
//Order follow shipment schedule ( P/O NO.) page
@RequestMapping("/orderfollowshipmentschedulepo")
public String orderFollowShipmentSchedulePo(Model model) {
List<SysUser> allHandlers = userMgr.getAllUsers();
model.addAttribute("allHandlers", allHandlers);
return "/management/reports/orderfollowshipmentschedulepo";
}
//Order follow shipment schedule ( P/O NO.) report
@RequestMapping(value = "/orderfollowshipmentscheduleporeports", method = RequestMethod.POST)
@ResponseBody
public Map<String, Object> orderFollowShipmentSchedulePoReports(PoSoSearchItemReportConditionVo vo, HttpServletRequest request) {
User currentUser = (User) request.getSession().getAttribute(Constants.AUTHENTICATION_KEY);
String coCode = "";
if (currentUser != null) {
coCode = currentUser.getCoCode();
} else {
coCode = "RRR";
}
ReportResult orderFollowShipmentSchedulePoResult = reportMgr.getOrderFollowShipmentSchedulePoReports(vo, coCode);
Map<String, Object> result = new HashMap<String, Object>();
result.put("result", orderFollowShipmentSchedulePoResult);
return result;
}
//Order follow shipment schedule ( S/O NO.) page
@RequestMapping("/orderfollowshipmentscheduleso")
public String orderFollowShipmentScheduleSo(Model model) {
List<SysUser> allHandlers = userMgr.getAllUsers();
model.addAttribute("allHandlers", allHandlers);
return "/management/reports/orderfollowshipmentscheduleso";
}
//Order follow shipment schedule ( S/O NO.) report
@RequestMapping(value = "/orderfollowshipmentschedulesoreports", method = RequestMethod.POST)
@ResponseBody
public Map<String, Object> orderFollowShipmentScheduleSoReports(PoSoSearchItemReportConditionVo vo, HttpServletRequest request) {
User currentUser = (User) request.getSession().getAttribute(Constants.AUTHENTICATION_KEY);
String coCode = "";
if (currentUser != null) {
coCode = currentUser.getCoCode();
} else {
coCode = "RRR";
}
ReportResult itemMasterResult = reportMgr.getOrderFollowShipmentScheduleSoReports(vo, coCode);
Map<String, Object> result = new HashMap<String, Object>();
result.put("result", itemMasterResult);
return result;
}
//P/O shipmnet schedule (purchase order NO.) page
@RequestMapping("/poshipmentschedule")
public String poShipmentSchedule() {
return "/management/reports/poshipmentschedule";
}
//P/O shipmnet schedule (purchase order NO.) report
@RequestMapping(value = "/poshipmentschedulereports", method = RequestMethod.POST)
@ResponseBody
public Map<String, Object> poShipmentScheduleReports(PoSoSearchItemReportConditionVo vo, HttpServletRequest request) {
User currentUser = (User) request.getSession().getAttribute(Constants.AUTHENTICATION_KEY);
String coCode = "";
if (currentUser != null) {
coCode = currentUser.getCoCode();
} else {
coCode = "RRR";
}
ReportResult reportResult = reportMgr.getPoShipmentScheduleReport(vo, coCode);
Map<String, Object> result = new HashMap<String, Object>();
result.put("result", reportResult);
return result;
}
//shipment schedule (customer NO.) page
@RequestMapping("/shipmentschedulecustomer")
public String shipmentScheduleCustomer() {
return "/management/reports/shipmentschedulecustomer";
}
//shipment schedule (customer NO.) report
@RequestMapping(value = "/shipmentschedulecustomerreports", method = RequestMethod.POST)
@ResponseBody
public Map<String, Object> shipmentScheduleCustomerReports(PoSoSearchItemReportConditionVo vo, HttpServletRequest request) {
User currentUser = (User) request.getSession().getAttribute(Constants.AUTHENTICATION_KEY);
String coCode = "";
if (currentUser != null) {
coCode = currentUser.getCoCode();
} else {
coCode = "RRR";
}
ReportResult reportResult = reportMgr.getShipmentScheduleCustomerReports(vo, coCode);
Map<String, Object> result = new HashMap<String, Object>();
result.put("result", reportResult);
return result;
}
// //Shipment schedule - Confirmed ( customer NO.) page
// @RequestMapping("/shipmentscheduleconfirmed")
// public String shipmentScheduleConfirmed(){
// return "/management/reports/shipmentscheduleconfirmed";
// }
// //Shipment schedule - Confirmed ( customer NO.) report
// @RequestMapping(value = "/shipmentscheduleconfirmedreports", method = RequestMethod.POST)
// @ResponseBody
// public Map<String, Object> shipmentScheduleConfirmedReports(ItemMasterConditionVo vo,HttpServletRequest request){
// User currentUser = (User) request.getSession().getAttribute(Constants.AUTHENTICATION_KEY);
// String coCode = "";
// if(currentUser != null){
// coCode = currentUser.getCoCode();
// }else{
// coCode = "RRR";
// }
// ReportResult reportResult = reportMgr.getItemMasterReport(vo, coCode);
// Map<String, Object> result = new HashMap<String, Object>();
// result.put("result", reportResult);
// return result;
// }
//Shipment schedule - factory ( factory NO.) page
@RequestMapping("/shipmentschedulefactory")
public String shipmentScheduleFactory() {
return "/management/reports/shipmentschedulefactory";
}
//Shipment schedule - factory ( factory NO.) report
@RequestMapping(value = "/shipmentschedulefactoryreports", method = RequestMethod.POST)
@ResponseBody
public Map<String, Object> shipmentScheduleFactoryReports(PoSoSearchItemReportConditionVo vo, HttpServletRequest request) {
User currentUser = (User) request.getSession().getAttribute(Constants.AUTHENTICATION_KEY);
String coCode = "";
if (currentUser != null) {
coCode = currentUser.getCoCode();
} else {
coCode = "RRR";
}
ReportResult reportResult = reportMgr.getShipmentScheduleFactoryReports(vo, coCode);
Map<String, Object> result = new HashMap<String, Object>();
result.put("result", reportResult);
return result;
}
// //Shipment schedule - Finished ( customer NO.) page
// @RequestMapping("/shipmentschedulefinished")
// public String shipmentScheduleFinished(){
// return "/management/reports/shipmentschedulefinished";
// }
// //Shipment schedule - Finished ( customer NO.) report
// @RequestMapping(value = "/shipmentschedulefinishedreports", method = RequestMethod.POST)
// @ResponseBody
// public Map<String, Object> shipmentScheduleFinishedReports(ItemMasterConditionVo vo,HttpServletRequest request){
// User currentUser = (User) request.getSession().getAttribute(Constants.AUTHENTICATION_KEY);
// String coCode = "";
// if(currentUser != null){
// coCode = currentUser.getCoCode();
// }else{
// coCode = "RRR";
// }
// ReportResult reportResult = reportMgr.getItemMasterReport(vo, coCode);
// Map<String, Object> result = new HashMap<String, Object>();
// result.put("result", reportResult);
// return result;
// }
// //Shipment schedule - Outstanding ( customer NO.) page
// @RequestMapping("/shipmentscheduleoutstanding")
// public String shipmentScheduleOutstanding(){
// return "/management/reports/shipmentscheduleoutstanding";
// }
// //Shipment schedule - Outstanding ( customer NO.) report
// @RequestMapping(value = "/shipmentscheduleoutstandingreports", method = RequestMethod.POST)
// @ResponseBody
// public Map<String, Object> shipmentScheduleOutstandingReports(ItemMasterConditionVo vo,HttpServletRequest request){
// User currentUser = (User) request.getSession().getAttribute(Constants.AUTHENTICATION_KEY);
// String coCode = "";
// if(currentUser != null){
// coCode = currentUser.getCoCode();
// }else{
// coCode = "RRR";
// }
// ReportResult reportResult = reportMgr.getItemMasterReport(vo, coCode);
// Map<String, Object> result = new HashMap<String, Object>();
// result.put("result", reportResult);
// return result;
// }
//Shipment schedule - w / ETD,ETA,Vessel etc. page
@RequestMapping("/shipmentschedulewetdetavessel")
public String shipmentScheduleWEtdEtaVessel() {
return "/management/reports/shipmentschedulewetdetavessel";
}
//Shipment schedule - w / ETD,ETA,Vessel etc. report
@RequestMapping(value = "/shipmentschedulewetdetavesselreports", method = RequestMethod.POST)
@ResponseBody
public Map<String, Object> shipmentScheduleWEtdEtaVesselReports(PoSoSearchItemReportConditionVo vo, HttpServletRequest request) {
User currentUser = (User) request.getSession().getAttribute(Constants.AUTHENTICATION_KEY);
String coCode = "";
if (currentUser != null) {
coCode = currentUser.getCoCode();
} else {
coCode = "RRR";
}
ReportResult reportResult = reportMgr.getShipmentScheduleWEtdEtaVesselReports(vo, coCode);
Map<String, Object> result = new HashMap<String, Object>();
result.put("result", reportResult);
return result;
}
//Sold item summary by S/O - W/photo page
@RequestMapping("/solditemsummarybysowphoto")
public String soldItemSummaryBySoWPhoto() {
return "/management/reports/solditemsummarybysowphoto";
}
//Sold item summary by S/O - W/photo report
@RequestMapping(value = "/solditemsummarybysowphotoreports", method = RequestMethod.POST)
@ResponseBody
public Map<String, Object> soldItemSummaryBySoWPhotoReports(SearchItemReportConditionVo vo, HttpServletRequest request) {
User currentUser = (User) request.getSession().getAttribute(Constants.AUTHENTICATION_KEY);
String coCode = "";
if (currentUser != null) {
coCode = currentUser.getCoCode();
} else {
coCode = "RRR";
}
ReportResult reportResult = reportMgr.getSoldItemSummaryBySoWPhotoReports(vo, coCode);
Map<String, Object> result = new HashMap<String, Object>();
result.put("result", reportResult);
return result;
}
//Sold item summary by S/O- W/photo (W/O. C.Art #) page
@RequestMapping("/solditemsummarybysowphotowocart")
public String soldItemSummaryBySoWPhotoWoCArt() {
return "/management/reports/solditemsummarybysowphotowocart";
}
//Sold item summary by S/O- W/photo (W/O. C.Art #) report
@RequestMapping(value = "/solditemsummarybysowphotowocartreports", method = RequestMethod.POST)
@ResponseBody
public Map<String, Object> soldItemSummaryBySoWPhotoWoCArtReports(ItemMasterConditionVo vo, HttpServletRequest request) {
User currentUser = (User) request.getSession().getAttribute(Constants.AUTHENTICATION_KEY);
String coCode = "";
if (currentUser != null) {
coCode = currentUser.getCoCode();
} else {
coCode = "RRR";
}
ReportResult reportResult = reportMgr.getItemMasterReport(vo, coCode);
Map<String, Object> result = new HashMap<String, Object>();
result.put("result", reportResult);
return result;
}
//PRICE HISTORY FOR MANY ITEMS page
@RequestMapping("/pricehistoryformanyitems")
public String priceHistoryForManyItems() {
return "/management/reports/pricehistoryformanyitems";
}
//PRICE HISTORY FOR MANY ITEMS report
@RequestMapping(value = "/pricehistoryformanyitemsreports", method = RequestMethod.POST)
@ResponseBody
public Map<String, Object> priceHistoryForManyItemsReports(ItemMasterConditionVo vo, HttpServletRequest request) {
User currentUser = (User) request.getSession().getAttribute(Constants.AUTHENTICATION_KEY);
String coCode = "";
if (currentUser != null) {
coCode = currentUser.getCoCode();
} else {
coCode = "RRR";
}
ReportResult reportResult = reportMgr.getItemMasterReport(vo, coCode);
Map<String, Object> result = new HashMap<String, Object>();
result.put("result", reportResult);
return result;
}
}
|
/*
* *
* *
* * @version 1.0.0
* *
* * Copyright (C) 2012-2016 REDNOVO Corporation.
*
*/
package com.rednovo.ace.widget.live;
import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.annotation.TargetApi;
import android.content.Context;
import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.AttributeSet;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.LinearInterpolator;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import com.rednovo.ace.R;
/**
* @author Zhen.Li
* @fileNmae EnterRoomAnimView
* @since 2016-03-08
*/
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
public class EnterRoomAnimView extends RelativeLayout {
private int count = 0;
private ImageView tvRoomAnim;
private Animation animation;
private AnimatorSet animatorSet;
private ObjectAnimator aplphaIn;
private ObjectAnimator scaleX;
private ObjectAnimator scaleY;
private ObjectAnimator aplphaOut;
private Handler mHandler = new Handler(Looper.myLooper()) {
@Override
public void handleMessage(Message msg) {
if (msg.what == 0) {
int count = getCount();
int resourceId = 0;
if (count == 2) {
resourceId = R.drawable.enter_room_ready;
} else {
resourceId = R.drawable.enter_room_go;
}
tvRoomAnim.setImageResource(resourceId);
if (count == 2) {
startAnim(tvRoomAnim, null);
mHandler.sendEmptyMessageDelayed(0, 1000);
} else {
startAnim(tvRoomAnim, animatorListenerAdapter);
}
}
}
};
public EnterRoomAnimView(Context context) {
super(context);
initView(context);
}
public EnterRoomAnimView(Context context, AttributeSet attrs) {
super(context, attrs);
initView(context);
}
public EnterRoomAnimView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
initView(context);
}
protected void initView(Context context) {
setClickable(true);
setFocusable(true);
setBackgroundResource(R.color.clolor_88000000);
tvRoomAnim = new ImageView(context);
tvRoomAnim.setScaleType(ImageView.ScaleType.FIT_CENTER);
tvRoomAnim.setClickable(false);
tvRoomAnim.setFocusable(false);
LayoutParams layoutParams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); // ShowUtils.dip2px(context, 102), ShowUtils.dip2px(context, 39)
layoutParams.addRule(CENTER_IN_PARENT);
addView(tvRoomAnim, layoutParams);
animation = AnimationUtils.loadAnimation(getContext(), R.anim.anim_room_in);
}
public void startAnimView() {
mHandler.sendEmptyMessageDelayed(0, 1000);
}
private void startAnim(final ImageView view, AnimatorListenerAdapter animatorListenerAdapter) {
animatorSet = new AnimatorSet();
aplphaIn = ObjectAnimator.ofFloat(view, View.ALPHA, 0f, 1.0f);
scaleX = ObjectAnimator.ofFloat(view, View.SCALE_X, 1.0f, 1.5f);
scaleY = ObjectAnimator.ofFloat(view, View.SCALE_Y, 1.0f, 1.5f);
aplphaOut = ObjectAnimator.ofFloat(view, View.ALPHA, 1.0f, 0.0f);
animatorSet.setDuration(1000);
animatorSet.setInterpolator(new LinearInterpolator());
if (animatorListenerAdapter != null) {
animatorSet.addListener(animatorListenerAdapter);
}
animatorSet.playTogether(aplphaIn, scaleX, scaleY);
animatorSet.start();
}
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
}
@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
mHandler.removeCallbacksAndMessages(null);
}
private int getCount() {
count--;
if (count <= 0 || count >= 2) {
count = 2;
}
return count;
}
private AnimatorListenerAdapter animatorListenerAdapter = new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(android.animation.Animator animation) {
super.onAnimationEnd(animation);
EnterRoomAnimView.this.setVisibility(View.GONE);
}
};
}
|
package com.snxy.pay.config.ali;
public enum AliRefundCodeEnum {
ACQ_SYSTEM_ERROR("ACQ_SYSTEM_ERROR","系统错误,请使用相同的参数再次调用"),
ACQ_XML_ERROR("ACQ_XML_ERROR","XML 格式错误"),
ACQ_INVALID_SIGN("ACQ_INVALID_SIGN","无效签名"),
ACQ_REFUND_ACCEPT("ACQ_REFUND_ACCEPT","退款请求已处理"),
ACQ_INVALID_PARAMETER("ACQ_INVALID_PARAMETER","参数无效,请求参数有错,重新检查请求后,再调用退款"),
ACQ_SELLER_BALANCE_NOT_ENOUGH("ACQ_SELLER_BALANCE_NOT_ENOUGH","卖家余额不足"),
ACQ_REFUND_AMT_NOT_EQUAL_TOTAL("ACQ_REFUND_AMT_NOT_EQUAL_TOTAL","退款金额超限"),
ACQ_REASON_TRADE_BEEN_FREEZEN("ACQ_REASON_TRADE_BEEN_FREEZEN","请求退款的交易被冻结"),
ACQ_TRADE_NOT_EXIST("ACQ_TRADE_NOT_EXIST","交易不存在,检查请求中的交易号和商户订单号是否正确,"),
ACQ_TRADE_HAS_FINISHED("ACQ_TRADE_HAS_FINISHED","交易已完结,该交易已完结,不允许进行退款"),
ACQ_TRADE_STATUS_ERROR("ACQ_TRADE_STATUS_ERROR","交易状态非法,查询交易,确认交易是否已经付款"),
ACQ_DISCORDANT_REPEAT_REQUEST("ACQ_DISCORDANT_REPEAT_REQUEST","不一致的请求,检查该退款号是否已退过款或更换退款号重新发起请求"),
ACQ_REASON_TRADE_REFUND_FEE_ERR("ACQ_REASON_TRADE_REFUND_FEE_ERR","退款金额无效"),
ACQ_TRADE_NOT_ALLOW_REFUND("ACQ_TRADE_NOT_ALLOW_RE","当前交易不允许退款");
private String code ;
private String msg ;
private String returnMsg;
AliRefundCodeEnum(String code, String msg, String returnMsg) {
this.code = code;
this.msg = msg;
this.returnMsg = returnMsg;
}
AliRefundCodeEnum(String code, String msg) {
this.code = code;
this.msg = msg;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public String getReturnMsg() {
return returnMsg;
}
public void setReturnMsg(String returnMsg) {
this.returnMsg = returnMsg;
}
}
|
package com.example.receivebroadcast;
import androidx.appcompat.app.AppCompatActivity;
import android.content.IntentFilter;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MyReceiver receiver = new MyReceiver();
IntentFilter filter = new IntentFilter();
filter.addAction("com.example.sendbroadcast");
this.registerReceiver(receiver,filter);
}
}
|
package com.ctse.automatedbirthdaywisher.background_task;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.job.JobParameters;
import android.app.job.JobService;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.NotificationCompat;
import com.ctse.automatedbirthdaywisher.R;
import com.ctse.automatedbirthdaywisher.SplashActivity;
/**
* Created by Kasun on 3/30/2018.
*/
public class MsgJobSheduler extends JobService {
private MsgJobExecuter jobExecuter;
@Override
public boolean onStartJob(final JobParameters params) {
jobExecuter = new MsgJobExecuter(getApplicationContext()) {
@Override
protected void onPostExecute(String s) {
if (!s.equals("")) {
showNotification(s);
}
jobFinished(params, false);
}
};
jobExecuter.execute();
return true;
}
@Override
public boolean onStopJob(JobParameters params) {
jobExecuter.cancel(true);
return true;
}
public void showNotification(String names) {
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)//, "CHANNEL"
.setSmallIcon(R.drawable.ic_blue_cake)
.setContentTitle("Birthday Wisher")
.setContentText("Your wish sent to " + names)
.setAutoCancel(true);
Intent resultIntent = new Intent(this, SplashActivity.class);
PendingIntent resultPendingIntent = PendingIntent.getActivity(
this,
0,
resultIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(resultPendingIntent);
Notification notification = mBuilder.build();
notification.flags |= Notification.FLAG_AUTO_CANCEL;
NotificationManager mNotifyMgr = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
mNotifyMgr.notify(1, notification);
}
public void disapperIcon() {
((NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE)).cancel(1);
}
}
|
package controller;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.URL;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Optional;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.control.Button;
import javafx.scene.control.ButtonBar;
import javafx.scene.control.ButtonBar.ButtonData;
import javafx.scene.control.ButtonType;
import javafx.scene.control.CheckBox;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
import javafx.scene.control.RadioButton;
import javafx.scene.control.TextField;
import javafx.scene.input.KeyEvent;
import javafx.stage.Stage;
import model.Goal;
import model.User;
public class createGoalsController {
private static final long serialVersionUID = 5838486165102144861L;
private File path = new File("users.ser");
private User user;
private User stableuser;
//private UnstableUser unstableuser;
private static final String[] tensNames = {
"",
" ten",
" twenty",
" thirty",
" forty",
" fifty",
" sixty",
" seventy",
" eighty",
" ninety"
};
private static final String[] numNames = {
"",
" one",
" two",
" three",
" four",
" five",
" six",
" seven",
" eight",
" nine",
" ten",
" eleven",
" twelve",
" thirteen",
" fourteen",
" fifteen",
" sixteen",
" seventeen",
" eighteen",
" nineteen"
};
ObservableList<String> options =
FXCollections.observableArrayList(
"High",
"Low"
);
@FXML
private Button btnCreateGoal;
@FXML
private TextField fieldCostOfGoal, fieldTitleOfGoal;
@FXML
private CheckBox cBoxHighPriority, cBoxLowPriority;
@FXML
private Label lblWarningMessage, lblCurrencyAnswer1, lblCurrencyAnswer, lblConvertNumber;
@FXML
private ComboBox<String> cBoxPriorityLevel, cBoxCurrencyChoice, cBoxCurrencyChoice2;
@FXML
private RadioButton radioNo, radioYes;
@FXML
private TextField tfAmountOfEuro, tfAmountOfCurrency;
private boolean radioSelected;
private byte asap;
private ArrayList<String> curName = new ArrayList<String>();
private ArrayList<String> curValue = new ArrayList<String>();
@FXML
public void initialize(){
getEuroCurrencyValues(); // current xml file is not working with the code
radioSelected = false;
asap = 0;
user = deserialize();
disableTextFieldToEuro();
disableTextFieldToCurrency();
cBoxPriorityLevel.getItems().addAll(options);
cBoxCurrencyChoice.getItems().addAll(curName);
cBoxCurrencyChoice2.getItems().addAll(curName);
tfAmountOfCurrency.setOnKeyReleased((KeyEvent keyEvent) -> {
handleCurrencyToEuro();
});
tfAmountOfEuro.setOnKeyReleased((KeyEvent keyEvent) -> {
handleCurrencyFromEuro();
});
//IDEAAAAAAAAAAAAAAAAAAAAAA//
//green area can contain current currency exchange rates
//Or Random Facts about cars or trips and prices depending on how much user earns
//or saves we can calculate how much it would take for a random goal
}
private void disableTextFieldToEuro(){
tfAmountOfEuro.setEditable(false);
tfAmountOfEuro.setMouseTransparent(true);
tfAmountOfEuro.setFocusTraversable(false);
tfAmountOfEuro.setStyle("-fx-background-color: grey;");
}
private void disableTextFieldToCurrency(){
tfAmountOfCurrency.setEditable(false);
tfAmountOfCurrency.setMouseTransparent(true);
tfAmountOfCurrency.setFocusTraversable(false);
tfAmountOfCurrency.setStyle("-fx-background-color: grey;");
}
@FXML
protected void enableTextFieldToEuro(ActionEvent event) throws IOException{
lblCurrencyAnswer.setText("0");
tfAmountOfEuro.setText("0");
tfAmountOfEuro.setEditable(true);
tfAmountOfEuro.setMouseTransparent(false);
tfAmountOfEuro.setFocusTraversable(true);
tfAmountOfEuro.setStyle("-fx-background-color: white;");
}
@FXML
protected void enableTextFieldToCurrency() throws IOException{
lblCurrencyAnswer1.setText("€ 0");
tfAmountOfCurrency.setText("0");
tfAmountOfCurrency.setEditable(true);
tfAmountOfCurrency.setMouseTransparent(false);
tfAmountOfCurrency.setFocusTraversable(true);
tfAmountOfCurrency.setStyle("-fx-background-color: white;");
}
private void handleCurrencyToEuro(){
System.out.println(cBoxCurrencyChoice.getSelectionModel().getSelectedItem());
int val = Integer.parseInt(tfAmountOfCurrency.getText());
DecimalFormat f = new DecimalFormat("##.00");
for(int i=0; i<curName.size(); i++){
if(cBoxCurrencyChoice2.getSelectionModel().getSelectedItem().equals(curName.get(i))){
double num = Double.parseDouble(curValue.get(i));
lblCurrencyAnswer1.setText("= €" + f.format(val/num));
}
}
}
private void handleCurrencyFromEuro (){
System.out.println(cBoxCurrencyChoice.getSelectionModel().getSelectedItem());
int val = Integer.parseInt(tfAmountOfEuro.getText());
DecimalFormat f = new DecimalFormat("##.00");
for(int i=0; i<curName.size(); i++){
if(cBoxCurrencyChoice.getSelectionModel().getSelectedItem().equals(curName.get(i))){
double num = Double.parseDouble(curValue.get(i));
lblCurrencyAnswer.setText("= " + f.format(num*val));
}
}
}
private void promptInformationAlert(String info){
Alert confirmAlert = new Alert(AlertType.INFORMATION);
confirmAlert.setTitle("Information");
confirmAlert.setHeaderText(info);
ButtonType buttonTypeExit = new ButtonType("Ok", ButtonData.CANCEL_CLOSE);
confirmAlert.getButtonTypes().setAll(buttonTypeExit);
confirmAlert.showAndWait();
}
private void promptErrorAlert(String info){
Alert errorAlert = new Alert(AlertType.ERROR);
errorAlert.setTitle("error");
errorAlert.setHeaderText(info);
errorAlert.setContentText("Ooops, there was an error!");
ButtonType buttonTypeExit = new ButtonType("Ok", ButtonData.CANCEL_CLOSE);
errorAlert.getButtonTypes().setAll(buttonTypeExit);
errorAlert.showAndWait();
}
private Optional<ButtonType> promptConfirmationAlert(String title, double cost){
Alert alert = new Alert(AlertType.CONFIRMATION);
alert.setTitle("Confirmation");
alert.setHeaderText("Please Confirm " + "Title: " + title + " , Cost: " + cost);
alert.setContentText("Choose your option");
ButtonType buttonTypeOne = new ButtonType("Yes", ButtonData.YES);
ButtonType buttonTypeTwo = new ButtonType("No", ButtonData.CANCEL_CLOSE);
ButtonType buttonTypeClear = new ButtonType("Clear", ButtonData.CANCEL_CLOSE);
alert.getButtonTypes().setAll(buttonTypeOne, buttonTypeTwo, buttonTypeClear);
return alert.showAndWait();
}
public void getEuroCurrencyValues()
{
try
{
URL url = new URL("https://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml?3f4b98854580782b979f6792a114486b");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
InputStream stream = url.openStream();
Document doc = dBuilder.parse(stream);
NodeList nList = doc.getElementsByTagName("Cube");
for (int i = 0; i < nList.getLength(); i++) {
Node nNode = nList.item(i);
Element eElement = (Element) nNode;
System.out.println("\nCurrent Element :" + eElement.getNodeName());
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
if (eElement.hasChildNodes()) {
System.out.println("has child");
}else{
if (eElement.hasAttributes()) {
NamedNodeMap nodeMap = eElement.getAttributes();
for (int j = 0; j < nodeMap.getLength(); j++) {
Node node = nodeMap.item(j);
if(j==0){
curName.add(node.getNodeValue());
}else if(j==1){
curValue.add(node.getNodeValue());
}
}
}
}
}
}
}catch (Exception e) {
e.printStackTrace();
}
}
@FXML
protected void handleSelectRadioButton (ActionEvent event) throws IOException{ // BUGGY
if(event.getSource().equals(this.radioYes)){
asap = 1;
radioNo.setSelected(false);
}
if(event.getSource().equals(this.radioNo)){
asap = 0;
radioYes.setSelected(false);
}
radioSelected = true;
}
@FXML
protected void createGoalAction (ActionEvent event) throws IOException{ // can be reduced using AND/OR operators or maybe other
String title = "";
String priority = "";
double cost = 0;
boolean exists = false;
if(fieldTitleOfGoal.getText().length() > 0){
title = fieldTitleOfGoal.getText();
for(int j=0; j<user.getGoals().size() ; j++){
if(title.equals(user.getGoals().get(j).getTitle())){
exists = true;
}
}
if(cBoxPriorityLevel.getValue() != null){
if(cBoxPriorityLevel.getSelectionModel().getSelectedItem().equals("High")){
priority = "highest";
}else{
priority = "Low";
}
}else{
promptErrorAlert("Please select a priority");
return;
}if(radioSelected){
try {
String amount = fieldCostOfGoal.getText();
Double val = Double.parseDouble(amount);
if(amount.length() > 0){
cost = val;
}else{
System.out.println("Please enter cost of the goal");
}
}catch(NumberFormatException ex){
promptInformationAlert("Please enter a number");
return;
}
}else{
promptErrorAlert("Please chose radio button");
return;
}
if(!exists){
ButtonType result = promptConfirmationAlert(title, cost).get();
if (result.getButtonData() == ButtonData.YES) {
Goal obj = new Goal();
obj.setTitle(title);
obj.setFocus(asap);
obj.setPriority(priority);
obj.setGoalCost(cost);
user.addGoal(obj);
serialize(user);
}else {
promptErrorAlert("Something went wrong");
}
}else{
promptErrorAlert("This goal already exists");
}
}else{
promptErrorAlert("please enter the title");
}
}
private static String convertLessThanOneThousand(int number) {
String soFar;
if (number % 100 < 20){
soFar = numNames[number % 100];
number /= 100;
}
else {
soFar = numNames[number % 10];
number /= 10;
soFar = tensNames[number % 10] + soFar;
number /= 10;
}
if (number == 0) return soFar;
return numNames[number] + " hundred" + soFar;
}
public static String convert(long number) {
// 0 to 999 999 999 999
if (number == 0) { return "zero"; }
String snumber = Long.toString(number);
// pad with "0"
String mask = "000000000000";
DecimalFormat df = new DecimalFormat(mask);
snumber = df.format(number);
// XXXnnnnnnnnn
int billions = Integer.parseInt(snumber.substring(0,3));
// nnnXXXnnnnnn
int millions = Integer.parseInt(snumber.substring(3,6));
// nnnnnnXXXnnn
int hundredThousands = Integer.parseInt(snumber.substring(6,9));
// nnnnnnnnnXXX
int thousands = Integer.parseInt(snumber.substring(9,12));
String tradBillions;
switch (billions) {
case 0:
tradBillions = "";
break;
case 1 :
tradBillions = convertLessThanOneThousand(billions)
+ " billion ";
break;
default :
tradBillions = convertLessThanOneThousand(billions)
+ " billion ";
}
String result = tradBillions;
String tradMillions;
switch (millions) {
case 0:
tradMillions = "";
break;
case 1 :
tradMillions = convertLessThanOneThousand(millions)
+ " million ";
break;
default :
tradMillions = convertLessThanOneThousand(millions)
+ " million ";
}
result = result + tradMillions;
String tradHundredThousands;
switch (hundredThousands) {
case 0:
tradHundredThousands = "";
break;
case 1 :
tradHundredThousands = "one thousand ";
break;
default :
tradHundredThousands = convertLessThanOneThousand(hundredThousands)
+ " thousand ";
}
result = result + tradHundredThousands;
String tradThousand;
tradThousand = convertLessThanOneThousand(thousands);
result = result + tradThousand;
// remove extra spaces!
return result.replaceAll("^\\s+", "").replaceAll("\\b\\s{2,}\\b", " ");
}
@FXML
protected void handleCostEntered(KeyEvent event) throws IOException{
try{
if(Double.parseDouble(fieldCostOfGoal.getText()) > 0){
lblConvertNumber.setText(convert(Long.parseLong(fieldCostOfGoal.getText())));
}
}catch(NumberFormatException e){
Alert errorAlert = new Alert(AlertType.ERROR);
errorAlert.setTitle("error");
errorAlert.setHeaderText("Re enter the information");
errorAlert.setContentText("Ooops, there was an error!");
ButtonType buttonTypeExit = new ButtonType("Ok", ButtonData.CANCEL_CLOSE);
errorAlert.getButtonTypes().setAll(buttonTypeExit);
}
}
@FXML
protected void handleDeleteUser(ActionEvent event) throws IOException{
File file = new File("C:\\Users\\Oskar\\BudgetApplicationv2.git\\trunk\\src\\users.ser");
if(file.delete())
{
System.out.println("File deleted successfully");
newScreen("/view/userScreenScreen.fxml", event);
}
else
{
System.out.println("Failed to delete the file");
}
}
public User deserialize(){
User e = null;
try {
ObjectInputStream in = new ObjectInputStream(
new FileInputStream (path));
e = (User) in.readObject();
in.close();
} catch (IOException i) {
i.printStackTrace();
return e;
} catch (ClassNotFoundException c) {
System.out.println("User not found");
c.printStackTrace();
return e;
}
return e;
}
public void serialize(User user){
System.out.println(path);
try {
FileOutputStream fileOut = new FileOutputStream(path);
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(user);
out.close();
fileOut.close();
System.out.println("Serialized data is saved");
} catch (IOException i) {
i.printStackTrace();
}
}
public void newScreen(String address, ActionEvent event) throws IOException{
Parent blah = FXMLLoader.load(getClass().getResource(address)); // "/view/mainScreen.fxml"
Scene scene = new Scene(blah);
Stage appStage = (Stage) ((javafx.scene.Node)event.getSource()).getScene().getWindow();
appStage.setScene(scene);
appStage.setTitle("BudgetApp");
appStage.setWidth(1280);
appStage.setHeight(800);
appStage.show();
}
@FXML
protected void handleScreenNavigation(ActionEvent event) throws IOException{
String name = "/view/";
Button address = (Button) event.getSource();
name += address.getText().replaceAll(" ", "") + "Screen.fxml";
System.out.println(name);
Parent blah = FXMLLoader.load(getClass().getResource(name)); // "/view/mainScreen.fxml"
Scene scene = new Scene(blah);
Stage appStage = (Stage) ((javafx.scene.Node)event.getSource()).getScene().getWindow();
appStage.setScene(scene);
appStage.setTitle("BudgetApp");
appStage.setWidth(1280);
appStage.setHeight(800);
appStage.show();
}
}
|
package com.news.demo.mapper;
import com.news.demo.model.Enews;
import com.baomidou.mybatisplus.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
/**
* <p>
* Mapper 接口
* </p>
*
* @author GEBILAOHU
* @since 2019-06-09
*/
@Mapper
public interface EnewsMapper extends BaseMapper<Enews> {
}
|
package com.zzping.fix.controller;
import com.zzping.fix.entity.FixRecord;
import com.zzping.fix.entity.FixUser;
import com.zzping.fix.mapper.FixRecordMapper;
import com.zzping.fix.model.BaseModel;
import com.zzping.fix.model.LayUIGrid;
import com.zzping.fix.service.FixMainService;
import com.zzping.fix.service.FixSelfService;
import com.zzping.fix.util.Constant;
import com.zzping.fix.util.FixStatusConstant;
import com.zzping.fix.util.ServerResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import java.sql.SQLException;
import java.text.ParseException;
import java.util.List;
@RequestMapping("self")
@Controller
public class FixSelfController extends BaseController {
@Autowired
private FixSelfService fixSelfService;
@Autowired
private FixMainService fixMainService;
@Autowired
private FixRecordMapper fixRecordMapper;
@RequestMapping("myFixGrid")
@ResponseBody
public LayUIGrid myFixGrid(BaseModel baseModel) {
LayUIGrid layUIGrid = fixSelfService.getSelfFixList(getUserId(), baseModel);
return layUIGrid;
}
@RequestMapping("delete")
@ResponseBody
public ServerResponse deleteSelfFix(String fixId) {
FixRecord fixRecord = fixMainService.getOneByFixId(fixId);
if(getUser().getIsAdmin().equals( Constant.STR_SUCCESS)){
fixRecord.setFixStatus(FixStatusConstant.USER_DELETE);
fixSelfService.updateFixRecord(fixRecord);
return ServerResponse.buildSuccessMsg("删除成功");
}
if (!fixRecord.getUserId().equals(getUserId())) {
return ServerResponse.buildErrorMsg("您不是提单人,不能删除,请结单");
}
//用户删除
fixRecord.setFixStatus(FixStatusConstant.USER_DELETE);
fixSelfService.updateFixRecord(fixRecord);
return ServerResponse.buildSuccessMsg("删除成功");
}
@RequestMapping("/finish")
@ResponseBody
public ServerResponse finish(String fixId, int success, String detail) {
return fixSelfService.finishRecord(fixId, success, detail, getUser());
}
@RequestMapping("/historyGrid")
@ResponseBody
public LayUIGrid historyGrid(BaseModel model) {
return fixSelfService.getHistoryRecordList(model, getUser());
}
@RequestMapping("/orderGrid")
@ResponseBody
public LayUIGrid layUIGrid(BaseModel model) {
return fixSelfService.getAppointRecordList(model, getUser());
}
@RequestMapping("/appoint")
@ResponseBody
public ServerResponse oppoint(String fixId) {
try {
ServerResponse response = fixSelfService.appoint(fixId, getUser());
return response;
} catch (Exception e) {
e.printStackTrace();
return ServerResponse.buildErrorMsg("接受预约失败");
}
}
@RequestMapping("/reject")
@ResponseBody
public ServerResponse reject(String fixId) {
FixRecord fixRecord = fixMainService.getOneByFixId(fixId);
if (fixRecord.getUserId().equals(getUserId())) {
return ServerResponse.buildErrorMsg("您是提单人,不能拒绝");
}
try {
return fixSelfService.rejectRecord(fixRecord, getUser());
} catch (Exception e) {
e.printStackTrace();
return ServerResponse.buildErrorMsg("拒绝失败");
}
}
@RequestMapping("/showLabel")
@ResponseBody
public FixUser showLabel() {
String userId = getUserId();
FixUser user = fixSelfService.getUserByUserId(userId);
return user;
}
@RequestMapping("/labelApply")
@ResponseBody
public ServerResponse labelApply(String label, String detail) throws SQLException {
ServerResponse response = fixSelfService.labelApply(getUser(), label, detail);
return response;
}
@RequestMapping("/setBusyTime")
@ResponseBody
public ServerResponse setBusyTime(String busyTime1,String busyTime2,String busyTime3) throws ParseException {
return fixSelfService.setBusyTime(getUser(),busyTime1,busyTime2,busyTime3);
}
@RequestMapping("/comment")
@ResponseBody
public ServerResponse comment(String fixId,String score,String comment){
return fixSelfService.comment(fixId,score,comment,getUser());
}
@RequestMapping("/showMyOrderNum")
@ResponseBody
public ServerResponse showMyOrderNum(){
FixUser fixUser = getUser();
return fixSelfService.showMyOrderNum(fixUser);
}
@RequestMapping("/showMyFixNum")
@ResponseBody
public ServerResponse showMyFixNum(){
FixUser fixUser = getUser();
return fixSelfService.showMyFixNum(fixUser);
}
/**
*维修人员结单后,提单人进行确认
* @return
*/
@RequestMapping("/finishSure")
@ResponseBody
public ServerResponse finishSure(String fixId){
String userId = getUserId();
return fixSelfService.finishSure(fixId,userId);
}
}
|
package com.greyfinch.tdd.exercise_06;
import com.greyfinch.tdd.exercise_06.domain.Transaction;
import com.greyfinch.tdd.exercise_06.repository.AccountInMemoryRepository;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.runners.MockitoJUnitRunner;
import java.time.LocalDate;
@RunWith(MockitoJUnitRunner.class)
public class AccountServiceShould {
@Mock
AccountInMemoryRepository accountRepository;
@InjectMocks
AccountService accountService;
@Test
public void record_deposit_transaction() {
Transaction expected = new Transaction(LocalDate.now(), 100, Transaction.Type.DEPOSIT);
accountService.deposit(100);
Mockito.verify(accountRepository).save(expected);
}
@Test
public void record_withdraw_transaction() {
Transaction expected = new Transaction(LocalDate.now(), 100, Transaction.Type.WITHDRAWAL);
accountService.withdraw(100);
Mockito.verify(accountRepository).save(expected);
}
@Test
public void read_all_transactions_before_printing() {
Transaction expected = new Transaction(LocalDate.now(), 100, Transaction.Type.WITHDRAWAL);
Transaction expected2 = new Transaction(LocalDate.now(), 100, Transaction.Type.DEPOSIT);
accountService.withdraw(100);
accountService.deposit(100);
accountService.printStatement();
Mockito.verify(accountRepository).save(expected);
Mockito.verify(accountRepository).save(expected2);
Mockito.verify(accountRepository).findAll();
}
}
|
package model;
import java.util.List;
public class Menu_DTO {
private int m_no;
private String m_type;
private String m_name;
private String m_recipe;
private int m_cost;
private List<Menu_DTO> mdto;
public int getM_no() {
return m_no;
}
public List<Menu_DTO> getMdto() {
return mdto;
}
public void setMdto(List<Menu_DTO> mdto) {
this.mdto = mdto;
}
public void setM_no(int m_no) {
this.m_no = m_no;
}
public String getM_type() {
return m_type;
}
public void setM_type(String m_type) {
this.m_type = m_type;
}
public String getM_name() {
return m_name;
}
public void setM_name(String m_name) {
this.m_name = m_name;
}
public String getM_recipe() {
return m_recipe;
}
public void setM_recipe(String m_recipe) {
this.m_recipe = m_recipe;
}
public int getM_cost() {
return m_cost;
}
public void setM_cost(int m_cost) {
this.m_cost = m_cost;
}
public Menu_DTO() {
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.