text
stringlengths 10
2.72M
|
|---|
/*
* Lesson 13 Coding Activity 5
* Create a program to let the user practice their multiplication tables.
* Print two random integers between 1 and 12 each on a new line.
* Then, ask the user to input the multiplication of the two numbers.
* If they enter the correct product print "Correct!" otherwise print "Wrong".
*/
import java.util.Scanner;
class Lesson_13_Activity_Five {
public static int numgen(int max)
{
return (int) (Math.random() * max);
}
public static int numgen(int max, int offset)
{
return (int) (Math.random() * max) + offset;
}
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
Integer firstNum = numgen(12, 1), SecondNum = numgen(12, 1);
System.out.println(input.nextInt() == (firstNum * SecondNum) ? "Correct!" : "Wrong");
input.close();
}
}
|
//INPUT 2
import java.io.*;
class input1
{
public static void main(String args[]) throws IOException
{
BufferedReader v=new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter first String:-");
String str1=v.readLine();
System.out.print("Enter second String:-");
String str2=v.readLine();
String str=str1+str2;
System.out.print("Concatnition String is:-"+str);
}
}
|
package com.shiyifan.service;
//@Service
public class UserService {
// //想拿到provider提供的票,去注册中心拿到服务
// @Reference//引用,Pom坐标或者定义路径相同的接口名
// SendMailService sendMailService;//定义路径相同的接口名
// public void sendmailbyzookeeper() {
// String staus = sendMailService.sendmail("zookeeper测试", "zookeeper测试", "814986678@qq.com", "814986678@qq.com");
// System.out.println(staus);
// }
}
|
package patterns.behavioral.iterator;
public class ConcreteIterator<T> implements Iterator
{
private Object[] items;
private int position = 0;
public ConcreteIterator(T[] items)
{
this.items = items;
}
@Override
public T next()
{
return (T) items[position++];
}
@Override
public boolean hasNext()
{
return position < items.length;
}
}
|
package th.co.gosoft;
import org.junit.Test;
public class PeriodSelectorTest {
@Test
public void itShouldBeAfterMidnight() {
}
@Test
public void itShouldBeAfterMidday() {
}
}
|
package Problem_15657;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.StringTokenizer;
public class Main {
static int N, M;
static int[] arr;
static int[] arr_;
static StringBuilder sb;
public static void ans(int idx) {
if (idx == M) {
for(int i = 0; i<M; i++) {
sb.append(arr[arr_[i]]).append(" ");
}
sb.append("\n");
} else if(idx >= 1){
for(int i = arr_[idx-1]; i < N;i++) {
arr_[idx] = i;
ans(idx+1);
}
}
else {
for(int i = 0; i < N;i++) {
arr_[idx] = i;
ans(idx+1);
}
}
}
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String buffer = br.readLine();
StringTokenizer st;
sb = new StringBuilder();
N = Integer.parseInt(buffer.split(" ")[0]);
M = Integer.parseInt(buffer.split(" ")[1]);
arr = new int[N];
arr_ = new int[M];
buffer = br.readLine();
st = new StringTokenizer(buffer, " ");
for (int i = 0; i < N; i++)
arr[i] = Integer.parseInt(st.nextToken());
Arrays.sort(arr);
ans(0);
System.out.print(sb.toString());
}
}
|
package com.kevin.cloud.service;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
/**
* @ProjectName: vue-blog-backend
* @Package: com.kevin.cloud.service
* @ClassName: ServiceJobApplication
* @Author: kevin
* @Description:
* @Date: 2020/2/12 0:39
* @Version: 1.0
*/
@SpringBootApplication(exclude= {DataSourceAutoConfiguration.class},
scanBasePackageClasses = {ServiceJobApplication.class})
@EnableDiscoveryClient
@EnableFeignClients
public class ServiceJobApplication {
public static void main(String[] args) {
System.out.println("123");
SpringApplication.run(ServiceJobApplication.class, args);
}
}
|
package swea_d3;
import java.io.FileInputStream;
import java.util.Scanner;
public class Solution_4751_다솔이의다이아몬드장식 {
public static void main(String[] args) throws Exception {
System.setIn(new FileInputStream("input.txt"));
Scanner sc = new Scanner(System.in);
int T = sc.nextInt();
for (int tc = 1; tc <= T; tc++) {
String s = sc.next();
for (int i = 0; i < s.length(); i++) {
if (i == 0) {
System.out.print("..#..");
} else {
System.out.print(".#..");
}
}
System.out.println();
for (int i = 0; i < s.length(); i++) {
if (i == 0) {
System.out.print(".#.#.");
} else {
System.out.print("#.#.");
}
}
System.out.println();
for (int i = 0; i < s.length(); i++) {
if (i == 0) {
System.out.print("#." + s.charAt(i) + ".#");
} else {
System.out.print("." + s.charAt(i) + ".#");
}
}
System.out.println();
for (int i = 0; i < s.length(); i++) {
if (i == 0) {
System.out.print(".#.#.");
} else {
System.out.print("#.#.");
}
}
System.out.println();
for (int i = 0; i < s.length(); i++) {
if (i == 0) {
System.out.print("..#..");
} else {
System.out.print(".#..");
}
}
System.out.println();
}
}
}
|
package gina.nikol.qnr.demo.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import gina.nikol.qnr.demo.dao.DepartmentDAO;
import gina.nikol.qnr.demo.entity.Department;
import gina.nikol.qnr.demo.entity.Employee;
@Controller
@RequestMapping("/department")
public class DepartmentController {
// inject the department dao
@Autowired
private DepartmentDAO departmentDAO;
@GetMapping("/list")
public String listDepartments(Model theModel) {
List<Department> theDepartments = departmentDAO.getDepartments();
theModel.addAttribute("departments", theDepartments);
return "list-departments";
}
@Autowired
private DepartmentDAO departmentDAO2;
@GetMapping("/processForm")
public String listEmployees(@RequestParam(name = "depId") String depId, Model theModel) {
int departmentId = Integer.parseInt(depId);
Department department = departmentDAO2.getDepartment(departmentId);
String depName = department.getDepartmentName();
List<Employee> theEmployeesInDep = department.getEmployees();
theModel.addAttribute("theEmployeesInDep", theEmployeesInDep);
theModel.addAttribute("depName", depName);
return "employees-at-department";
}
}
|
package com.fmi.decorator;
public interface IShape {
/**
* Draw a shape.
*/
void draw();
}
|
package com.pointinside.android.piwebservices.net;
import android.content.Context;
import android.net.Uri;
import android.net.Uri.Builder;
import com.pointinside.android.api.net.JSONWebRequester;
import com.pointinside.android.api.net.JSONWebRequester.RestResponseException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;
import org.apache.http.client.methods.HttpGet;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class DealsClient
{
public static final String FIELD_BRAND = "brand";
public static final String FIELD_CATEGORY = "category";
public static final String FIELD_DESCRIPTION = "description";
public static final String FIELD_DESTINATION_UUID = "destination_uuid";
public static final String FIELD_DISPLAY_END_DATE = "display_end_date";
public static final String FIELD_DISPLAY_IMAGE = "display_image";
public static final String FIELD_DISPLAY_START_DATE = "display_start_date";
public static final String FIELD_DISTANCE = "distance";
public static final String FIELD_END_DATE = "end_date";
public static final String FIELD_LATITUDE = "latitude";
public static final String FIELD_LONGITUDE = "longitude";
public static final String FIELD_PLACE_NAME = "organization";
public static final String FIELD_PLACE_UUID = "place_uuid";
public static final String FIELD_START_DATE = "start_date";
public static final String FIELD_THUMBNAIL_IMAGE = "thumbnail_image";
public static final String FIELD_TITLE = "title";
public static final String FIELD_TYPE = "type";
public static final String FIELD_UPC = "upc";
private static final String PARAM_API_KEY = "api_key";
private static final String PARAM_LATITUDE = "lat";
private static final String PARAM_LONGITUDE = "long";
private static final String PARAM_MAX_RESULTS = "max_results";
private static final String PARAM_OUTPUT_FIELDS = "output_fields";
private static final String PARAM_RADIUS = "radius";
private static final String PARAM_START_INDEX = "start_index";
private static final String REQUEST_TYPE_DESTINATION = "destination";
private static final String REQUEST_TYPE_NEARBY = "nearby";
private static final String REQUEST_TYPE_OFFERS = "offers";
private static final String RESULT_ID = "id";
private static final String RESULT_OFFERS = "offers";
private static final String RESULT_STATUS = "status_code";
private static final Uri URL = Uri.parse("http://interact.pointinside.com/adws/v1");
private static WebServiceDescriptor sDescriptor;
private static DealsClient sInstance;
private final JSONWebRequester mRequester;
private DealsClient(JSONWebRequester paramJSONWebRequester)
{
this.mRequester = paramJSONWebRequester;
}
private static DealsResult executeAndGetResult(JSONWebRequester paramJSONWebRequester, String paramString)
throws JSONWebRequester.RestResponseException
{
HttpGet localHttpGet = new HttpGet(paramString);
try
{
DealsResult localDealsResult = DealsResult.fromJSON(paramJSONWebRequester.execute(localHttpGet));
return localDealsResult;
}
catch (JSONException localJSONException)
{
throw new JSONWebRequester.RestResponseException(localJSONException);
}
catch (ParseException localParseException)
{
throw new JSONWebRequester.RestResponseException(localParseException);
}
}
public static DealsClient getInstance(Context paramContext)
{
try
{
if (sInstance == null) {
sInstance = new DealsClient(PIWebServices.getWebRequester(paramContext));
}
if (sDescriptor == null) {
throw new IllegalStateException("Must call DealsClient.init first");
}
} catch(Exception ex) {
ex.printStackTrace();
}
DealsClient localDealsClient = sInstance;
return localDealsClient;
}
public static void init(String paramString)
{
try
{
if (sInstance != null) {
throw new IllegalStateException();
}
}
finally {}
sDescriptor = new WebServiceDescriptor(URL, paramString);
}
public DealsResult getDestinationDeals(DestinationDealsRequest paramDestinationDealsRequest)
throws JSONWebRequester.RestResponseException
{
Uri.Builder localBuilder = sDescriptor.getMethodUriBuilder("destination");
localBuilder.appendPath(paramDestinationDealsRequest.venue);
localBuilder.appendPath("offers");
paramDestinationDealsRequest.apply(localBuilder, sDescriptor.apiKey);
return executeAndGetResult(this.mRequester, localBuilder.build().toString());
}
public DealsResult getNearbyDeals(NearbyDealsRequest paramNearbyDealsRequest)
throws JSONWebRequester.RestResponseException
{
Uri.Builder localBuilder = sDescriptor.getMethodUriBuilder("nearby");
localBuilder.appendPath("offers");
paramNearbyDealsRequest.apply(localBuilder, sDescriptor.apiKey);
return executeAndGetResult(this.mRequester, localBuilder.build().toString());
}
public static class Deal
{
private static final SimpleDateFormat DATE_FORMATTER = new SimpleDateFormat("yyyyMMdd");
private static final SimpleDateFormat DATE_PARSER = new SimpleDateFormat("yyyy-MM-dd");
private String brand;
private String category;
private String description;
private String displayEndDate;
private String displayImage;
private String displayStartDate;
private String distance;
private String endDate;
private boolean hasBrand;
private boolean hasCategory;
private boolean hasDescription;
private boolean hasDisplayEndDate;
private boolean hasDisplayImage;
private boolean hasDisplayStartDate;
private boolean hasDistance;
private boolean hasEndDate;
private boolean hasLatitude;
private boolean hasLongitude;
private boolean hasPlaceName;
private boolean hasPlaceUUID;
private boolean hasStartDate;
private boolean hasThumbnailImage;
private boolean hasTitle;
private boolean hasType;
private boolean hasUpc;
private boolean hasVenueUUID;
private final HashMap<String, String> ids = new HashMap();
private double latitude;
private double longitude;
private String placeName;
private String placeUUID;
private String startDate;
private String thumbnailImage;
private String title;
private String type;
private String upc;
private String venueUUID;
private Deal(JSONObject paramJSONObject)
throws JSONException, ParseException
{
JSONObject localJSONObject = paramJSONObject.getJSONObject("id");
Iterator localIterator = localJSONObject.keys();
for (;;)
{
if (!localIterator.hasNext())
{
boolean bool1 = paramJSONObject.has("title");
this.hasTitle = bool1;
if (bool1) {
this.title = paramJSONObject.getString("title");
}
boolean bool2 = paramJSONObject.has("brand");
this.hasBrand = bool2;
if (bool2) {
this.brand = paramJSONObject.getString("brand");
}
boolean bool3 = paramJSONObject.has("type");
this.hasType = bool3;
if (bool3) {
this.type = paramJSONObject.getString("type");
}
boolean bool4 = paramJSONObject.has("category");
this.hasCategory = bool4;
if (bool4) {
this.category = paramJSONObject.getString("category");
}
boolean bool5 = paramJSONObject.has("distance");
this.hasDistance = bool5;
if (bool5) {
this.distance = paramJSONObject.getString("distance");
}
boolean bool6 = paramJSONObject.has("description");
this.hasDescription = bool6;
if (bool6) {
this.description = paramJSONObject.getString("description");
}
boolean bool7 = paramJSONObject.has("display_image");
this.hasDisplayImage = bool7;
if (bool7) {
this.displayImage = paramJSONObject.getString("display_image");
}
boolean bool8 = paramJSONObject.has("thumbnail_image");
this.hasThumbnailImage = bool8;
if (bool8) {
this.thumbnailImage = paramJSONObject.getString("thumbnail_image");
}
boolean bool9 = paramJSONObject.has("start_date");
this.hasStartDate = bool9;
if (bool9) {
this.startDate = parseDate(paramJSONObject.getString("start_date"));
}
boolean bool10 = paramJSONObject.has("display_start_date");
this.hasDisplayStartDate = bool10;
if (bool10) {
this.displayStartDate = paramJSONObject.getString("display_start_date");
}
boolean bool11 = paramJSONObject.has("end_date");
this.hasEndDate = bool11;
if (bool11) {
this.endDate = parseDate(paramJSONObject.getString("end_date"));
}
boolean bool12 = paramJSONObject.has("display_end_date");
this.hasDisplayEndDate = bool12;
if (bool12) {
this.displayEndDate = paramJSONObject.getString("display_end_date");
}
boolean bool13 = paramJSONObject.has("upc");
this.hasUpc = bool13;
if (bool13) {
this.upc = paramJSONObject.getString("upc");
}
boolean bool14 = paramJSONObject.has("latitude");
this.hasLatitude = bool14;
if (bool14) {
this.latitude = paramJSONObject.getDouble("latitude");
}
boolean bool15 = paramJSONObject.has("longitude");
this.hasLongitude = bool15;
if (bool15) {
this.longitude = paramJSONObject.getDouble("longitude");
}
boolean bool16 = paramJSONObject.has("organization");
this.hasPlaceName = bool16;
if (bool16) {
this.placeName = paramJSONObject.getString("organization");
}
boolean bool17 = paramJSONObject.has("place_uuid");
this.hasPlaceUUID = bool17;
if (bool17) {
this.placeUUID = paramJSONObject.getString("place_uuid");
}
boolean bool18 = paramJSONObject.has("destination_uuid");
this.hasVenueUUID = bool18;
if (bool18) {
this.venueUUID = paramJSONObject.getString("destination_uuid");
}
return;
}
String str = (String)localIterator.next();
this.ids.put(str, localJSONObject.getString(str));
}
}
private static String parseDate(String paramString)
throws ParseException
{
Date localDate = DATE_PARSER.parse(paramString);
return DATE_FORMATTER.format(localDate);
}
private static void throwUnless(String paramString, boolean paramBoolean)
{
if (!paramBoolean) {
throw new IllegalArgumentException("'" + paramString + "' does not exist in offers result");
}
}
public String getBrand()
{
throwUnless("brand", this.hasBrand);
return this.brand;
}
public String getCategory()
{
throwUnless("category", this.hasCategory);
return this.category;
}
public Set<String> getDataSources()
{
return this.ids.keySet();
}
public String getDescription()
{
throwUnless("description", this.hasDescription);
return this.description;
}
public String getDisplayEndDate()
{
throwUnless("display_end_date", this.hasDisplayEndDate);
return this.displayEndDate;
}
public String getDisplayImage()
{
throwUnless("display_image", this.hasDisplayImage);
return this.displayImage;
}
public String getDisplayStartDate()
{
throwUnless("display_start_date", this.hasDisplayStartDate);
return this.displayStartDate;
}
public String getDistance()
{
throwUnless("type", this.hasDistance);
return this.distance;
}
public String getEndDate()
{
throwUnless("end_date", this.hasEndDate);
return this.endDate;
}
public String getId(String paramString)
{
return (String)this.ids.get(paramString);
}
public double getLatitude()
{
throwUnless("latitude", this.hasLatitude);
return this.latitude;
}
public double getLongitude()
{
throwUnless("longitude", this.hasLongitude);
return this.longitude;
}
public String getPlaceName()
{
throwUnless("organization", this.hasPlaceName);
return this.placeName;
}
public String getPlaceUUID()
{
throwUnless("place_uuid", this.hasPlaceUUID);
return this.placeUUID;
}
public String getStartDate()
{
throwUnless("start_date", this.hasStartDate);
return this.startDate;
}
public String getThumbnailImage()
{
throwUnless("thumbnail_image", this.hasThumbnailImage);
return this.thumbnailImage;
}
public String getTitle()
{
throwUnless("title", this.hasTitle);
return this.title;
}
public String getType()
{
throwUnless("type", this.hasType);
return this.type;
}
public String getUpc()
{
throwUnless("upc", this.hasUpc);
return this.upc;
}
public String getVenueUUID()
{
throwUnless("destination_uuid", this.hasVenueUUID);
return this.venueUUID;
}
public boolean hasBrand()
{
return this.hasBrand;
}
public boolean hasCategory()
{
return this.hasCategory;
}
public boolean hasDescription()
{
return this.hasDescription;
}
public boolean hasDisplayEndDate()
{
return this.hasDisplayEndDate;
}
public boolean hasDisplayStartDate()
{
return this.hasDisplayStartDate;
}
public boolean hasDistance()
{
return this.hasDistance;
}
public boolean hasEndDate()
{
return this.hasEndDate;
}
public boolean hasLatLong()
{
return (this.hasLatitude) && (this.hasLongitude);
}
public boolean hasPlaceUUID()
{
return this.hasPlaceUUID;
}
public boolean hasStartDate()
{
return this.hasStartDate;
}
public boolean hasThumbnailImage()
{
return this.hasThumbnailImage;
}
public boolean hasType()
{
return this.hasType;
}
public boolean hasUPC()
{
return this.hasUpc;
}
public boolean hasVenueUUID()
{
return this.hasVenueUUID;
}
}
public static class DealsResult
{
public final ArrayList<DealsClient.Deal> deals = new ArrayList();
public final int status;
private DealsResult(JSONObject paramJSONObject)
throws JSONException, ParseException
{
this.status = paramJSONObject.getInt("status_code");
JSONArray localJSONArray = paramJSONObject.getJSONArray("offers");
int i = localJSONArray.length();
for (int j = 0;j<i; j++)
{
this.deals.add(new DealsClient.Deal(localJSONArray.getJSONObject(j)));
}
}
public static DealsResult fromJSON(JSONObject paramJSONObject)
throws JSONException, ParseException
{
return new DealsResult(paramJSONObject);
}
}
public static class DestinationDealsRequest
extends PIWebServices.CommonRequestObject
{
public String venue;
protected void onApply(Uri.Builder paramBuilder) {}
}
public static class NearbyDealsRequest
extends PIWebServices.CommonRequestObject
{
public double latitude;
public double longitude;
public int radius = 0;
protected void onApply(Uri.Builder paramBuilder)
{
paramBuilder.appendQueryParameter("lat", String.valueOf(this.latitude)).appendQueryParameter("long", String.valueOf(this.longitude));
if (this.radius > 0) {
paramBuilder.appendQueryParameter("radius", String.valueOf(this.radius));
}
if (this.maxResults > 0) {
paramBuilder.appendQueryParameter("max_results", String.valueOf(this.maxResults));
}
}
}
}
/* Location: D:\xinghai\dex2jar\classes-dex2jar.jar
* Qualified Name: com.pointinside.android.piwebservices.net.DealsClient
* JD-Core Version: 0.7.0.1
*/
|
package org.virgil.jdk.tcp;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
/**
* Created by Virgil on 2017/8/22.
*/
public class SelectorProtocal implements TCPProtocal {
private int buffsize;
public SelectorProtocal(int buffsize) {
this.buffsize = buffsize;
}
@Override
public void handleAccept(SelectionKey key) throws IOException {
SocketChannel socketChannel = ((ServerSocketChannel) key.channel()).accept();
socketChannel.configureBlocking(false);
socketChannel.register(key.selector(), SelectionKey.OP_READ, ByteBuffer.allocate(buffsize));
}
@Override
public void handleRead(SelectionKey key) throws IOException {
SocketChannel channel = (SocketChannel) key.channel();
//获取信道关联的附件
ByteBuffer byteBuffer = (ByteBuffer) key.attachment();
int read = channel.read(byteBuffer);
if (read != -1) {
//缓存区读入了数据 信道感兴趣设置为可读可写
key.interestOps(SelectionKey.OP_READ | SelectionKey.OP_WRITE);
} else {
channel.close();
}
}
@Override
public void handleWrite(SelectionKey key) throws IOException {
ByteBuffer buf = (ByteBuffer) key.attachment();
buf.flip();
SocketChannel channel = (SocketChannel) key.channel();
channel.write(buf);
if (!buf.hasRemaining()) {
key.interestOps(SelectionKey.OP_READ);
}
buf.compact();
}
}
|
package Topic10;
public class Aplication {
public static void main(String[] args) {
Point point = new Point(10, 20);
PointController pointController = new PointController();
System.out.println("Punkty " + point.getX() + " : " + point.getY());
pointController.addX(point);
System.out.println("Punkty " + point.getX() + " : " + point.getY());
pointController.minusX(point);
System.out.println("Punkty " + point.getX() + " : " + point.getY());
pointController.addY(point);
System.out.println("Punkty " + point.getX() + " : " + point.getY());
pointController.minusY(point);
System.out.println("Punkty " + point.getX() + " : " + point.getY());
}
}
|
/*
* Copyright 2008, Myron Marston <myron DOT marston AT gmail DOT com>
*
* This file is part of Fractal Composer.
*
* Fractal Composer is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* at your option any later version.
*
* Fractal Composer is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Fractal Composer. If not, see <http://www.gnu.org/licenses/>.
*/
package com.myronmarston.music.settings;
import com.myronmarston.music.GermIsEmptyException;
import com.myronmarston.music.NoteList;
import com.myronmarston.music.NoteStringParseException;
import com.myronmarston.music.OutputManager;
import com.myronmarston.music.Tempo;
import com.myronmarston.music.scales.Scale;
import com.myronmarston.util.Fraction;
import org.simpleframework.xml.*;
import org.simpleframework.xml.core.Persister;
import org.simpleframework.xml.strategy.CycleStrategy;
import java.io.StringWriter;
import java.lang.reflect.UndeclaredThrowableException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
/**
* The GrandDaddy of them all. This class controls the entire piece of music.
* Before generating the piece, you will need to provide values for each
* of the appropriate settings: the voices (via getVoices()), the sections
* (via getSections()), the germ, the scale, etc.
*
* @author Myron
*/
@Root
public class FractalPiece {
private static interface InsertIndexProvider { int getInsertIndex(List l); }
@Element
private NoteList germ = new NoteList().getReadOnlyCopy();
@Attribute
private String germString = "";
@Attribute
private int tempo = Tempo.DEFAULT;
@Element
private Scale scale = Scale.DEFAULT;
@Element
private TimeSignature timeSignature = TimeSignature.DEFAULT;
@Element
private VoiceOrSectionList<Voice, Section> voices = new VoiceOrSectionList<Voice, Section>(this);
@Element
private VoiceOrSectionList<Section, Voice> sections = new VoiceOrSectionList<Section, Voice>(this);
@Element
private Map<VoiceSectionHashMapKey, VoiceSection> voiceSections = new VoiceSectionHashMap();
@Attribute
private boolean generateLayeredIntro = true;
@Attribute
private boolean generateLayeredOutro = true;
private List<Section> tempIntroOutroSections = new ArrayList<Section>();
/**
* Returns the germ NoteList. Guarenteed to never be null. Is read-only.
* The germ is the short melody from which the entire piece is generated.
*
* @return the germ NoteList
*/
public NoteList getGerm() {
assert germ != null : germ; // germ should never be null!
// the germ should be read-only because we only support changing it
// through the setGermString() method. Our section cached germs
// must be updated when the germ changes, and it's easiest to only
// do that the germ string changes
assert germ.isReadOnly();
return germ;
}
/**
* Gets the germ string.
*
* @return the germ string
*/
public String getGermString() {
assert germString != null : germString; // germString should never be null!
return germString;
}
/**
* Sets the notes for the germ.
*
* @param germString string containing a list of notes
* @throws com.myronmarston.music.NoteStringParseException if the note list
* string cannot be parsed
*/
public void setGermString(String germString) throws NoteStringParseException {
this.germ = NoteList.parseNoteListString(germString, this.getScale()).getReadOnlyCopy();
this.germString = germString;
// the germ string effects each section's germ for section, so clear them...
for (Section section : this.getSections()) {
section.clearCachedGermForSection();
}
}
/**
* Gets the tempo of the piece, in beats per minute.
*
* @return the tempo of the piece
*/
public int getTempo() {
return tempo;
}
/**
* Sets the tempo of the piece, in beats per minute.
*
* @param tempo the tempo of the piece
* @throws IllegalArgumentException if the tempo is outside of the
* acceptable range
*/
public void setTempo(int tempo) throws IllegalArgumentException {
Tempo.checkTempoValidity(tempo);
this.tempo = tempo;
}
/**
* Returns the Scale. The Scale is used to determine the tonality of the
* piece, and will also be used to set the key signature of the Midi
* sequence.
*
* @return the Scale used by this FractalPiece
*/
public Scale getScale() {
assert scale != null : scale; // scale should never be null!
return scale;
}
/**
* Sets the Scale used by this FractalPiece. The Scale is used to
* determine the tonality of the piece, and will also be used to set the
* key signature of the Midi sequence.
*
* @param scale the Scale to be used by this FractalPiece
* @throws IllegalArgumentException if the passed scale is null
*/
public void setScale(Scale scale) throws IllegalArgumentException {
if (scale == null) throw new IllegalArgumentException("Scale cannot be set to null.");
if (this.getGermString() != null && !this.getGermString().isEmpty()) {
try {
this.germ = NoteList.parseNoteListString(this.getGermString(), scale).getReadOnlyCopy();
} catch (NoteStringParseException ex) {
// All scales should be able to handle a valid note list string.
// if we have a germString, it was valid with the existing scale,
// so it should also be valid with this scale. We should only
// get a NoteStringParseException in the case of a programming
// error.
throw new UndeclaredThrowableException(ex, "An error occured while parsing the note list string '" + this.getGermString() + "' using the scale " + scale.toString() + ". This indicates a programming error.");
}
}
this.scale = scale;
// the scale effects each section's germ for section, so clear them...
for (Section section : this.getSections()) {
section.clearCachedGermForSection();
}
}
/**
* Gets whether or not a layered intro should be included in the generated
* fractal piece.
*
* @return whether or not to generate the layered intro
*/
public boolean getGenerateLayeredIntro() {
return generateLayeredIntro;
}
/**
* Sets whether or not a layered intro should be included in the generated
* fractal piece.
*
* @param generateLayeredIntro whether or not to generate the layered intro
*/
public void setGenerateLayeredIntro(boolean generateLayeredIntro) {
this.generateLayeredIntro = generateLayeredIntro;
}
/**
* Gets whether or not a layered outro should be included in the generated
* fractal piece.
*
* @return whether or not to generate the layered outro
*/
public boolean getGenerateLayeredOutro() {
return generateLayeredOutro;
}
/**
* Sets whether or not a layered outro should be included in the generated
* fractal piece.
*
* @param generateLayeredOutro whether or not to generate the layered outro
*/
public void setGenerateLayeredOutro(boolean generateLayeredOutro) {
this.generateLayeredOutro = generateLayeredOutro;
}
/**
* Gets the time signature for this piece. If none has been set, a default
* signature of 4/4 will be created.
*
* @return the time signature
*/
public TimeSignature getTimeSignature() {
assert timeSignature != null : timeSignature; // timeSignature should never be null...
return timeSignature;
}
/**
* Sets the time signature for this piece.
*
* @param timeSignature the time signature
*/
public void setTimeSignature(TimeSignature timeSignature) {
if (timeSignature == null) throw new IllegalArgumentException("TimeSignature cannot be set to null.");
this.timeSignature = timeSignature;
}
/**
* Gets the hash table containing all the VoiceSections for the entire
* piece.
*
* @return the hash table containing all VoiceSections
*/
protected Map<VoiceSectionHashMapKey, VoiceSection> getVoiceSections() {
return voiceSections;
}
/**
* Gets a list of Voices for the FractalPiece. To add a Voice, use the
* provided createVoice() method, rather than attempting to add it to the
* list on your own.
*
* @return the list of Voices
*/
public VoiceOrSectionList<Voice, Section> getVoices() {
assert voices != null : voices; // voices should never be null!
return voices;
}
/**
* Gets an unmodifiable list of voices, in order from the fastest to the
* slowest.
*
* @return an unmodifiable list
*/
private List<Voice> getVoices_FastToSlow() {
List<Voice> sortableVoiceList = new ArrayList<Voice>(this.getVoices());
// sort the list using a fast-to-slow comparator...
Collections.sort(sortableVoiceList, new Comparator<Voice>() {
public int compare(Voice v1, Voice v2) {
return v2.getSettings().getSpeedScaleFactor().compareTo(v1.getSettings().getSpeedScaleFactor());
}
});
return Collections.unmodifiableList(sortableVoiceList);
}
/**
* Gets a list of Sections for the FractalPiece. To add a Section, use the
* provided createSection() method, rather than attempting to add it to the
* list on your own.
*
* @return the list of Sections
*/
public VoiceOrSectionList<Section, Voice> getSections() {
assert sections != null : sections; // sections should never be null!
return sections;
}
/**
* Normalizes the unique indices so as to label the items in natural order.
*/
public void normalizeUniqueIndices() {
this.voices.normalizeUniqueIndices();
this.sections.normalizeUniqueIndices();
}
/**
* Creates a Voice for the FractalPiece, and adds it to the Voice list.
*
* @return the created Voice
*/
public Voice createVoice() {
return this.createVoice(this.getVoices().size());
}
/**
* Creates a Voice for the FractalPiece, and adds it to a particular point
* in the voice list.
*
* @param index the point to insert the voice
* @return the created voice
* @throws UnsupportedOperationException if there are more than 15 voices
*/
public Voice createVoice(int index) throws UnsupportedOperationException {
if (this.voices.size() > 15) throw new UnsupportedOperationException("You cannot create more than 16 voices, since Midi only supports 16 channels.");
Voice v = new Voice(this, this.voices.getNextUniqueIndex());
this.voices.add(index, v);
return v;
}
/**
* Creates a Section for the FractalPiece, and adds it to the Section list.
*
* @return the created Section
*/
public Section createSection() {
return this.createSection(this.getSections().size());
}
/**
* Creates a Section for the FractalPiece, and inserts it at a particular
* point in the Section list.
*
* @param index the point in the list to insert the section
* @return the created Section
*/
public Section createSection(int index) {
Section s = new Section(this, this.sections.getNextUniqueIndex());
this.sections.add(index, s);
return s;
}
/**
* Sets up the default settings. If there are already voices, they will be
* left alone and no new voices will be created. Any section settings will
* be overriden with new ones.
*/
public void createDefaultSettings() {
createDefaultVoices();
createDefaultSections();
}
/**
* Creates the default voice settings. This generates three voices. The
* highest and fastest voice will have self-similarity applied to the
* pitch and volume.
*/
public void createDefaultVoices() {
this.voices.clear();
createDefaultVoice(1, new Fraction(2, 1), true, false, true, 1);
createDefaultVoice(0, new Fraction(1, 1), false, false, false, 1);
createDefaultVoice(-1, new Fraction(1, 2), false, false, false, 1);
}
private void createDefaultVoice(int octaveAdjustment, Fraction speedScaleFactor, boolean applySelfSimilarityToPitch, boolean applySelfSimilarityToRhythm, boolean applySelfSimilarityToVolume, int selfSimilarityIterations) {
Voice v = this.createVoice();
v.getSettings().setOctaveAdjustment(octaveAdjustment);
v.getSettings().setSpeedScaleFactor(speedScaleFactor);
SelfSimilaritySettings sss = v.getSettings().getSelfSimilaritySettings();
sss.setApplyToPitch(applySelfSimilarityToPitch);
sss.setApplyToRhythm(applySelfSimilarityToRhythm);
sss.setApplyToVolume(applySelfSimilarityToVolume);
sss.setSelfSimilarityIterations(selfSimilarityIterations);
}
/**
* Sets up default section settings. Any existing sections will be
* overriden. This generates one normal section, one inversion section,
* one retrograde inversion section, and one retrograde section. For each
* section, the self-similarity is applied to only the fastest voice.
*/
public void createDefaultSections() {
this.sections.clear();
createDefaultSection(false, false); // normal
createDefaultSection(true, false); // inversion
createDefaultSection(true, true); // retrograde inversion
createDefaultSection(false, true); // retrograde
}
/**
* Creates a default section.
*
* @param applyInversion whether or not to apply inversion to this section
* @param applyRetrograde whether or not to apply retrograde to this section
*/
private void createDefaultSection(boolean applyInversion, boolean applyRetrograde) {
Section section = this.createSection();
// apply inversion and retrograde based on the passed settings...
section.getSettings().setApplyInversion(applyInversion);
section.getSettings().setApplyRetrograde(applyRetrograde);
}
/**
* Creates the layered intro sections.
*/
protected void createIntroSections() {
if (!this.getGenerateLayeredIntro()) return;
createLayeredSections(
new InsertIndexProvider() {
public int getInsertIndex(List l) { return 0; }
}
);
}
/**
* Creates the layered outro sections.
*/
protected void createOutroSections() {
if (!this.getGenerateLayeredOutro()) return;
createLayeredSections(
new InsertIndexProvider() {
public int getInsertIndex(List l) { return l.size(); }
}
);
}
/**
* Creates the necessary layered intro or outro sections.
*
* @param insertIndexProvider object that provides index into the start of
* the list (for the intro) or the end of the list (for the outro)
*/
private void createLayeredSections(InsertIndexProvider insertIndexProvider) {
List<Voice> fastToSlowVoices = this.getVoices_FastToSlow();
for (int sectionIndex = 0; sectionIndex < fastToSlowVoices.size(); sectionIndex++) {
// create the section at the appropriate index...
Section s = this.createSection(insertIndexProvider.getInsertIndex(this.getSections()));
// add our section to our temp list, since the layered sections are
// only created during fractal piece generation and should never be
// available for editing
this.tempIntroOutroSections.add(s);
// set defaults...
s.getSettings().setApplyInversion(false);
s.getSettings().setApplyRetrograde(false);
s.setSelfSimilaritySettingsOnAllVoiceSections(false, false, false, 1);
s.setRestOnAllVoiceSections(false);
// set some of the voice sections to rests, to create our layered effect...
for (int voiceIndex = 0; voiceIndex < sectionIndex; voiceIndex++) {
VoiceSection vs = this.getVoiceSections().get(new VoiceSectionHashMapKey(fastToSlowVoices.get(voiceIndex), s));
vs.setRest(true);
}
}
}
/**
* Clears out any temporary intro or outro sections. These are created
* during fractal piece generation and should not be available the rest of
* the time.
*
* @param sectionLastUniqueIndex the lastUniqueIndex to set on the sections
*/
protected void clearTempIntroOutroSections(int sectionLastUniqueIndex) {
// clear out any sections that were temporarily created...
for (Section s : this.tempIntroOutroSections) {
this.getSections().remove(s);
}
this.tempIntroOutroSections.clear();
this.getSections().setLastUniqueIndex(sectionLastUniqueIndex);
}
/**
* Creates the output manager for the whole piece.
*
* @return the output manager
* @throws com.myronmarston.music.GermIsEmptyException if the germ is empty
* @throws UnsupportedOperationException if there are no voices or sections
*/
public OutputManager createPieceResultOutputManager() throws GermIsEmptyException, UnsupportedOperationException {
if (this.voices.isEmpty() || this.sections.isEmpty()) throw new UnsupportedOperationException("You must have at least one voice and one section to generate a fractal piece.");
int originalSectionUniqueIndex = this.sections.getLastUniqueIndex();
try {
// create our intro and outro...
this.createIntroSections();
this.createOutroSections();
ArrayList<NoteList> voiceResults = new ArrayList<NoteList>();
for (Voice v : this.getVoices()) voiceResults.add(v.getEntireVoice());
return new OutputManager(this, voiceResults);
} finally {
this.clearTempIntroOutroSections(originalSectionUniqueIndex);
}
}
/**
* Creates the output manager for the germ.
*
* @return the output manager
* @throws com.myronmarston.music.GermIsEmptyException if the germ is empty
*/
public OutputManager createGermOutputManager() throws GermIsEmptyException {
return new OutputManager(this, Arrays.asList(this.getGerm()), false, false, false);
}
/**
* Creates and loads a fractal piece from a serialized xml string.
*
* @param xml string containing an xml representation of the fractal piece
* @return the new fractal piece
* @throws Exception if there is a deserialization error
*/
public static FractalPiece loadFromXml(String xml) throws Exception {
Serializer serializer = new Persister(new CycleStrategy());
return serializer.read(FractalPiece.class, xml);
}
/**
* Serializes the fractal piece to xml.
*
* @return the xml representation of the fractal piece
*/
public String getXmlRepresentation() {
Serializer serializer = new Persister(new CycleStrategy());
StringWriter xml = new StringWriter();
try {
serializer.write(this, xml);
} catch (Exception ex) {
// Our serialization annotations and accompanying code should prevent
// this from ever occuring; if it does it is a programming error.
// We do this so that we don't have to declare it as a checked exception.
throw new UndeclaredThrowableException(ex, "An error occurred while serializing the fractal piece to xml.");
}
return xml.toString();
}
}
|
package csmen.group.project.dao;
import csmen.group.project.entity.UserInfo;
import java.util.List;
public interface UserDao {
List<UserInfo> findAll();
int addUser(UserInfo user);
UserInfo login(UserInfo user);
UserInfo findByid(Integer id);
List<UserInfo> findByname(String name);
int updateUser(UserInfo user);
UserInfo findBynameAndIDnumber(UserInfo user);
int changePasswd(UserInfo user);
int delUser(Integer id);
}
|
package com.Xpath;
public class XpathAmazon {
}
|
/*
* 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 chessPackage.pieces;
import chessPackage.Alliance;
import chessPackage.board.Board;
import chessPackage.board.BoardUtilities;
import chessPackage.board.Moves;
import chessPackage.board.Moves.AttackMove;
import chessPackage.board.Moves.MajorMove;
import chessPackage.board.Tile;
import java.util.ArrayList;
import java.util.List;
/**
*
* @author tonip
*/
public class Knight extends Piece{
private final static int[] POSSIBLE_MOVE_COORDINATES = {-17, -15, -10, -6, 6, 10, 15, 17};
public Knight(final Alliance pieceAlliance, final int piecePosition){
super(pieceAlliance, piecePosition);
}
/**
*
* @param board
* @return
*/
@Override
public List<Moves> calculateAllowedMoves(final Board board) {
final List<Moves> legalMoves = new ArrayList<>();
for(final int currentPossibleMove : POSSIBLE_MOVE_COORDINATES){
final int possibleDestinationCoordinate = this.piecePosition + currentPossibleMove;
if(BoardUtilities.isValidTileCoordinate(possibleDestinationCoordinate)){
if(isFirstColumnExclusion(this.piecePosition, currentPossibleMove) ||
isSecondColumnExclusion(this.piecePosition, currentPossibleMove) ||
isSeventhColumnExclusion(this.piecePosition, currentPossibleMove) ||
isEighthColumnExclusion(this.piecePosition, currentPossibleMove)) {
continue;
}
final Tile possibleDestinationTile = board.getTile(possibleDestinationCoordinate);
if(possibleDestinationTile.isTileOccupied()){
legalMoves.add(new MajorMove(board, this, possibleDestinationCoordinate));
} else{
final Piece pieceAtDestination = possibleDestinationTile.getPiece();
final Alliance pieceAlliance = pieceAtDestination.getPieceAlliance();
if(this.pieceAlliance != pieceAlliance){
legalMoves.add(new AttackMove(board, this, possibleDestinationCoordinate, pieceAtDestination));
}
}
}
}
return legalMoves;
}
private static boolean isFirstColumnExclusion(final int currentPosition, final int possiblePosition){
return BoardUtilities.FIRST_COLUMN[currentPosition] && (possiblePosition == -17 || possiblePosition == -10 ||
possiblePosition == 6 || possiblePosition == 15);
}
private static boolean isSecondColumnExclusion(final int currentPosition, final int possiblePosition) {
return BoardUtilities.SECOND_COLUMN[currentPosition] && (possiblePosition == -10 || possiblePosition == 6);
}
private static boolean isSeventhColumnExclusion(final int currentPosition, final int possiblePosition) {
return BoardUtilities.SEVENTH_COLUMN[currentPosition] && (possiblePosition == -6 || possiblePosition == 10);
}
private static boolean isEighthColumnExclusion(final int currentPosition, final int possiblePosition){
return BoardUtilities.EIGHTH_COLUMN[currentPosition] && (possiblePosition == -15 || possiblePosition == -6 ||
possiblePosition == 10 || possiblePosition == 17);
}
}
|
package run100;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map.Entry;
import java.util.Set;
public class test14 {
public static void main(String[] args) throws Exception {
HashMap<String,ArrayList<String>> map = new HashMap<String,ArrayList<String>>();
ArrayList<String> bj = new ArrayList<String>();
bj.add("北京市");
map.put("北京市", bj);
ArrayList<String> hn = new ArrayList<String>();
hn.add("海口市");
hn.add("三亚市");
map.put("海南省", hn);
ArrayList<String> zj = new ArrayList<String>();
zj.add("绍兴市");
zj.add("温州市");
zj.add("湖州市");
zj.add("嘉兴市");
zj.add("台州市");
zj.add("金华市");
zj.add("舟山市");
zj.add("衢州市");
zj.add("丽水市");
map.put("浙江省", zj);
Set<Entry<String, ArrayList<String>>> entrySet = map.entrySet();
for (Entry<String, ArrayList<String>> entry : entrySet) {
System.out.println(entry.getKey());
ArrayList<String> value = entry.getValue();
for (String string : value) {
System.out.println("\t" + string);
}
}
}
}
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jclouds.openstack.poppy.v1.mapbinders;
import java.io.IOException;
import java.util.Map;
import org.jclouds.http.HttpRequest;
import org.jclouds.json.Json;
import org.jclouds.openstack.poppy.v1.domain.Service;
import org.jclouds.rest.MapBinder;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.fge.jsonpatch.diff.JsonDiff;
import com.google.inject.Inject;
/**
* This will create a JSONPatch out of a Service and an UpdateService.
*
* User side:
* Get a Service with api.get(service_id)
* Get a UpdateService builder by using Service.toUpdatableService()
* This step will provide an interface that exposes the updatable JSON values to the user.
* Use the UpdateService.Builder instance to modify and build() a new UpdateService.
* Send the original Service and the new UpdateService to the api.update method.
*
* jclouds side:
* Convert the Service to UpdateService, but don't change it (this is the source).
* Serialize both source and target to String
* Diff to create JSONPatch using dependency.
* Send the JSONPatch in the request.
*
* JSONPatch RFC:
* https://tools.ietf.org/html/rfc6902
*/
public class JSONPatchUpdate implements MapBinder {
@Inject
Json json;
@Override
public <R extends HttpRequest> R bindToRequest(R request, Map<String, Object> postParams) {
String jsonPatch = null;
Service service = (Service) postParams.get("service");
//Json json = Guice.createInjector(new GsonModule()).getInstance(Json.class);
String targetService = json.toJson(postParams.get("updateService"));
String sourceService = json.toJson(service.toUpdatableService().build());
ObjectMapper mapper = new ObjectMapper();
try {
jsonPatch = JsonDiff.asJson(mapper.readTree(sourceService), mapper.readTree(targetService)).toString();
} catch (IOException e) {
throw new RuntimeException("Could not create a JSONPatch", e);
}
return bindToRequest(request, (Object) jsonPatch);
}
@Override
public <R extends HttpRequest> R bindToRequest(R request, Object input) {
request.setPayload((String) input);
request.getPayload().getContentMetadata().setContentType("application/json");
return request;
}
}
|
package br.com.wasys.library.utils;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import org.apache.commons.lang3.StringUtils;
/**
* Created by pascke on 19/04/16.
*/
public class FragmentUtils {
private FragmentUtils() {
}
public static void replace(FragmentActivity activity, int id, Fragment fragment) {
replace(activity, id, fragment, null);
}
public static void replace(FragmentActivity activity, int id, Fragment fragment, String backStackName) {
FragmentTransaction transaction = beginTransaction(activity);
transaction.replace(id, fragment);
if (StringUtils.isNotBlank(backStackName)) {
transaction.addToBackStack(backStackName);
}
transaction.commit();
}
public static void popAllBackStackImmediate(FragmentActivity activity) {
FragmentManager fragmentManager = activity.getSupportFragmentManager();
fragmentManager.popBackStackImmediate(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
}
public static boolean popBackStackImmediate(FragmentActivity activity, String backStackName) {
FragmentManager manager = activity.getSupportFragmentManager();
return manager.popBackStackImmediate(backStackName, FragmentManager.POP_BACK_STACK_INCLUSIVE);
}
/*private void removeByTag(FragmentActivity activity, String tag) {
FragmentManager manager = activity.getSupportFragmentManager();
Fragment fragment = manager.findFragmentByTag(tag);
manager.popBackStack();
if (fragment != null) {
FragmentTransaction transaction = manager.beginTransaction();
transaction.remove(fragment);
manager.popBackStack();
}
}*/
private static FragmentTransaction beginTransaction(FragmentActivity activity) {
FragmentManager manager = activity.getSupportFragmentManager();
return manager.beginTransaction();
}
}
|
package com.wangzhu.spring.test.ioc.interfaces;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.BlockJUnit4ClassRunner;
import com.wangzhu.spring.ioc.interfaces.OneInterface;
import com.wangzhu.spring.test.base.UnitTestBase;
/**
*
* @author wangzhu
* @date 2015-3-7ÏÂÎç2:24:57
*
*/
@RunWith(BlockJUnit4ClassRunner.class)
public class TestOneInterface extends UnitTestBase {
public TestOneInterface() {
super("classpath*:spring-ioc.xml");
}
@Test
public void testsay() {
OneInterface oneInterface = super.getBean("oneInterface");
oneInterface.say("This is a test.");
}
}
|
package br.com.ufrn.imd.lpii.classes.gui;
import br.com.ufrn.imd.lpii.classes.main.Bot;
import javafx.application.Platform;
import javafx.concurrent.Task;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextArea;
import javafx.scene.layout.StackPane;
public class MainScreenController {
@FXML
private StackPane stackPane;
@FXML
private TextArea textArea;
@FXML
private Label botStatus;
@FXML
private Button startButton;
@FXML
private Button finishButton;
@FXML
private Button quitButton;
public void startButtonPressed(){
Task<Void> botTask = new Task<Void>() {
@Override
protected Void call() throws Exception {
Bot.inicializacaoBot("1048746356:AAEDDgr7PPTnQ0hQuxSaZdDp3AVVYErsTDc", textArea, botStatus);
return null;
}
};
Thread botThread = new Thread(botTask);
botThread.start();
}
public void finishButtonPressed(){
Bot.desativarBot(botStatus);
}
public void quitButtonPressed(){
closeProgram();
}
private void closeProgram(){
Bot.desativarBot(botStatus);
Platform.exit();
}
}
|
package tjava.base;
public class EitherUtils {
}
|
package com.arthur.leetcode;
/**
* @title: No152
* @Author ArthurJi
* @Date: 2021/3/9 10:34
* @Version 1.0
*/
public class No152 {
public static void main(String[] args) {
}
public int maxProduct(int[] nums) {
int len = nums.length;
int[][] dp = new int[len][2]; //0是小 1是大
dp[0][0] = nums[0];
dp[0][1] = nums[0];
for (int i = 1; i < len; i++) {
if (nums[i] < 0) {
dp[i][0] = Math.min(nums[i], nums[i] * dp[i - 1][1]);
dp[i][1] = Math.max(nums[i], nums[i] * dp[i - 1][0]);
} else {
dp[i][0] = Math.min(nums[i], nums[i] * dp[i - 1][0]);
dp[i][1] = Math.max(nums[i], nums[i] * dp[i - 1][1]);
}
}
int max = Integer.MIN_VALUE;
for (int i = 0; i < len; i++) {
max = Math.max(dp[i][1], max);
}
return max;
}
}
/*
152. 乘积最大子数组
给你一个整数数组 nums ,请你找出数组中乘积最大的连续子数组(该子数组中至少包含一个数字),并返回该子数组所对应的乘积。
示例 1:
输入: [2,3,-2,4]
输出: 6
解释: 子数组 [2,3] 有最大乘积 6。
示例 2:
输入: [-2,0,-1]
输出: 0
解释: 结果不能为 2, 因为 [-2,-1] 不是子数组。
*/
/*
解题思路
标签:动态规划
遍历数组时计算当前最大值,不断更新
令imax为当前最大值,则当前最大值为 imax = max(imax * nums[i], nums[i])
由于存在负数,那么会导致最大的变最小的,最小的变最大的。因此还需要维护当前最小值imin,imin = min(imin * nums[i], nums[i])
当负数出现时则imax与imin进行交换再进行下一步计算
时间复杂度:O(n)O(n)
代码
class Solution {
public int maxProduct(int[] nums) {
int max = Integer.MIN_VALUE, imax = 1, imin = 1;
for(int i=0; i<nums.length; i++){
if(nums[i] < 0){
int tmp = imax;
imax = imin;
imin = tmp;
}
imax = Math.max(imax*nums[i], nums[i]);
imin = Math.min(imin*nums[i], nums[i]);
max = Math.max(max, imax);
}
return max;
}
}
作者:guanpengchn
链接:https://leetcode-cn.com/problems/maximum-product-subarray/solution/hua-jie-suan-fa-152-cheng-ji-zui-da-zi-xu-lie-by-g/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。*/
/*
思路
这个问题很像「力扣」第 53 题:最大子序和,只不过当前这个问题求的是乘积的最大值;
「连续」这个概念很重要,可以参考第 53 题的状态设计,将状态设计为:以 nums[i]结尾的连续子数组的最大值;
类似状态设计的问题还有「力扣」第 300 题:最长上升子序列,「子数组」、「子序列」问题的状态设计的特点是:以 nums[i] 结尾,这是一个经验,可以简化讨论。
提示:以 nums[i] 结尾这件事情很重要,贯穿整个解题过程始终,请大家留意。
分析与第 53 题的差异
求乘积的最大值,示例中负数的出现,告诉我们这题和 53 题不一样了,一个正数乘以负数就变成负数,即:最大值乘以负数就变成了最小值;
因此:最大值和最小值是相互转换的,这一点提示我们可以把这种转换关系设计到「状态转移方程」里去;
如何解决这个问题呢?这里常见的技巧是在「状态设计」的时候,在原始的状态设计后面多加一个维度,减少分类讨论,降低解决问题的难度。
这里是百度百科的「无后效性」词条的解释:
无后效性是指如果在某个阶段上过程的状态已知,则从此阶段以后过程的发展变化仅与此阶段的状态有关,而与过程在此阶段以前的阶段所经历过的状态无关。利用动态规划方法求解多阶段决策过程问题,过程的状态必须具备无后效性。
再翻译一下就是:「动态规划」通常不关心过程,只关心「阶段结果」,这个「阶段结果」就是我们设计的「状态」。什么算法关心过程呢?「回溯算法」,「回溯算法」需要记录过程,复杂度通常较高。
而将状态定义得更具体,通常来说对于一个问题的解决是满足「无后效性」的。这一点的叙述很理论化,不熟悉朋友可以通过多做相关的问题来理解「无后效性」这个概念。
第 1 步:状态设计(特别重要)
dp[i][j]:以 nums[i] 结尾的连续子数组的最值,计算最大值还是最小值由 j 来表示,j 就两个值;
当 j = 0 的时候,表示计算的是最小值;
当 j = 1 的时候,表示计算的是最大值。
这样一来,状态转移方程就容易写出。
第 2 步:推导状态转移方程(特别重要)
由于状态的设计 nums[i] 必须被选取(请大家体会这一点,这一点恰恰好也是使得子数组、子序列问题更加简单的原因:当情况复杂、分类讨论比较多的时候,需要固定一些量,以简化计算);
nums[i] 的正负和之前的状态值(正负)就产生了联系,由此关系写出状态转移方程:
当 nums[i] > 0 时,由于是乘积关系:
最大值乘以正数依然是最大值;
最小值乘以同一个正数依然是最小值;
当 nums[i] < 0 时,依然是由于乘积关系:
最大值乘以负数变成了最小值;
最小值乘以同一个负数变成最大值;
当 nums[i] = 0 的时候,由于 nums[i] 必须被选取,最大值和最小值都变成 00 ,合并到上面任意一种情况均成立。
但是,还要注意一点,之前状态值的正负也要考虑:例如,在考虑最大值的时候,当 nums[i] > 0 是,如果 dp[i - 1][1] < 0 (之前的状态最大值) ,此时 nums[i] 可以另起炉灶(这里依然是第 53 题的思想),此时 dp[i][1] = nums[i] ,合起来写就是:
dp[i][1] = max(nums[i], nums[i] * dp[i - 1][1]) if nums[i] >= 0
其它三种情况可以类似写出,状态转移方程如下:
dp[i][0] = min(nums[i], nums[i] * dp[i - 1][0]) if nums[i] >= 0
dp[i][1] = max(nums[i], nums[i] * dp[i - 1][1]) if nums[i] >= 0
dp[i][0] = min(nums[i], nums[i] * dp[i - 1][1]) if nums[i] < 0
dp[i][1] = max(nums[i], nums[i] * dp[i - 1][0]) if nums[i] < 0
第 3 步:考虑初始化
由于 nums[i] 必须被选取,那么 dp[i][0] = nums[0],dp[i][1] = nums[0]。
第 4 步:考虑输出
题目问连续子数组的乘积最大值,这些值需要遍历 dp[i][1] 获得。
参考代码 1:
Java
public class Solution {
public int maxProduct(int[] nums) {
int len = nums.length;
if (len == 0) {
return 0;
}
// dp[i][0]:以 nums[i] 结尾的连续子数组的最小值
// dp[i][1]:以 nums[i] 结尾的连续子数组的最大值
int[][] dp = new int[len][2];
dp[0][0] = nums[0];
dp[0][1] = nums[0];
for (int i = 1; i < len; i++) {
if (nums[i] >= 0) {
dp[i][0] = Math.min(nums[i], nums[i] * dp[i - 1][0]);
dp[i][1] = Math.max(nums[i], nums[i] * dp[i - 1][1]);
} else {
dp[i][0] = Math.min(nums[i], nums[i] * dp[i - 1][1]);
dp[i][1] = Math.max(nums[i], nums[i] * dp[i - 1][0]);
}
}
// 只关心最大值,需要遍历
int res = dp[0][1];
for (int i = 1; i < len; i++) {
res = Math.max(res, dp[i][1]);
}
return res;
}
}
复杂度分析:
时间复杂度:O(N)O(N),这里 NN 是数组的长度,遍历 2 次数组;
空间复杂度:O(N)O(N),状态数组的长度为 2N2N。
问题做到这个地方,其实就可以了。下面介绍一些非必要但进阶的知识。
第 5 步:考虑表格复用
动态规划问题,基于「自底向上」、「空间换时间」的思想,通常是「填表格」,本题也不例外;
由于通常只关心最后一个状态值,或者在状态转移的时候,当前值只参考了上一行的值,因此在填表的过程中,表格可以复用,常用的技巧有:
1、滚动数组(当前行只参考了上一行的时候,可以只用 2 行表格完成全部的计算);
2、滚动变量(斐波拉契数列问题)。
掌握非常重要的「表格复用」技巧,来自「0-1 背包问题」(弄清楚为什么要倒序填表)和「完全背包问题」(弄清楚为什么可以正向填表);
「表格复用」的合理性,只由「状态转移方程」决定,即当前状态值只参考了哪些部分的值。
参考代码 2:
Java
public class Solution {
public int maxProduct(int[] nums) {
int len = nums.length;
if (len == 0) {
return 0;
}
int preMax = nums[0];
int preMin = nums[0];
// 滚动变量
int curMax;
int curMin;
int res = nums[0];
for (int i = 1; i < len; i++) {
if (nums[i] >= 0) {
curMax = Math.max(preMax * nums[i], nums[i]);
curMin = Math.min(preMin * nums[i], nums[i]);
} else {
curMax = Math.max(preMin * nums[i], nums[i]);
curMin = Math.min(preMax * nums[i], nums[i]);
}
res = Math.max(res, curMax);
// 赋值滚动变量
preMax = curMax;
preMin = curMin;
}
return res;
}
}
复杂度分析:
时间复杂度:O(N)O(N),这里 NN 是数组的长度,最值也在一次遍历的过程中计算了出来;
空间复杂度:O(1)O(1),只使用了常数变量。
这里说一点题外话:除了基础的「0-1」背包问题和「完全背包」问题,需要掌握「表格复用」的技巧以外。在绝大多数情况下,在「力扣」上做的「动态规划」问题都可以不考虑「表格复用」。
做题通常可以不先考虑优化空间(个人观点,仅供参考),理由如下:
空间通常来说是用户不敏感的,并且在绝大多数情况下,空间成本低,我们写程序通常需要优先考虑时间复杂度最优;
时间复杂度和空间复杂度通常来说不可能同时最优,所以我们经常看到的是优化解法思路都是「空间换时间」,这一点几乎贯穿了基础算法领域的绝大多数的算法设计思想;
限制空间的思路,通常来说比较难,一般是在优化的过程中才考虑优化空间,在一些限制答题时间的场景下(例如面试),先写出一版正确的代码是更重要的,并且不优化空间的代码一般来说,可读性和可解释性更强。
以上个人建议,仅供参考。
总结
动态规划问题通常用于计算多阶段决策问题的最优解。
多阶段,是指解决一个问题有多个步骤;
最优解,是指「最优子结构」。
动态规划有三个概念很重要:
重复子问题:因为重复计算,所以需要「空间换时间」,记录子问题的最优解;
最优子结构:规模较大的问题的最优解,由各个子问题的最优解得到;
无后效性(上面已经解释)。
动态规划有两个特别关键的步骤:
设计状态:
有些题目问啥,就设计成什么;
如果不行,只要有利于状态转移,很多时候,就可以设计成状态;
根据过往经验;
还有一部分问题是需要在思考的过程中调整的,例如本题。
推导状态转移方程:通常是由问题本身决定的。
动态规划问题思考的两个方向:
自顶向下:即「递归 + 记忆化」,入门的时候优先考虑这样做;
自底向上:即「递推」,从一个最小的问题开始,逐步得到最终规模问题的解。后面问题见得多了,优先考虑这样做,绝大部分动态规划问题可以「自底向上」通过递推得到。
相关练习
「力扣」第 376 题:摆动序列(中等);
股票系列 6 道问题:区别仅在于题目加了不同的约束。一般来说有一个约束,就在「状态设计」的时候在后面多加一维,消除后效性,这个系列里最难的问题,也只有 2 个约束,因此状态设计最多 3 维。增加维度使得状态设计满足无后效性,是常见的解决问题的技巧。
「力扣」第 121 题:买卖股票的最佳时机(简单);
「力扣」第 122 题:买卖股票的最佳时机 II(简单) ;
「力扣」第 123 题:买卖股票的最佳时机 III(困难);
「力扣」第 188 题:买卖股票的最佳时机 IV(困难);
「力扣」第 309 题:最佳买卖股票时机含冷冻期(中等);
「力扣」第 714 题:买卖股票的最佳时机含手续费(中等)。
打家劫舍系列的两道问题都很典型:
「力扣」第 198 题:打家劫舍(简单),第 213 题:打家劫舍 II(中等) 基于这个问题分治(分类讨论)做;
「力扣」第 337 题:打家劫舍 III(中等),树形 dp 的入门问题,依然是加一个维度,使得求解过程具有无后效性,使用后序遍历,完成计算。
作者:liweiwei1419
链接:https://leetcode-cn.com/problems/maximum-product-subarray/solution/dong-tai-gui-hua-li-jie-wu-hou-xiao-xing-by-liweiw/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。*/
|
package com.git.cloud.request.dao.impl;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.stereotype.Repository;
import com.git.cloud.appmgt.model.po.AppStatPo;
import com.git.cloud.appmgt.model.vo.AppStatVo;
import com.git.cloud.appmgt.model.vo.AppSysKpiVo;
import com.git.cloud.common.dao.CommonDAOImpl;
import com.git.cloud.common.exception.RollbackableBizException;
import com.git.cloud.foundation.util.DateUtil;
import com.git.cloud.request.dao.IBmSrDao;
import com.git.cloud.request.model.SrStatusCodeEnum;
import com.git.cloud.request.model.vo.BmSrVo;
import com.git.cloud.request.model.vo.BmToDoVo;
import com.git.cloud.request.tools.SrDateUtil;
import com.git.cloud.resmgt.common.model.DeviceStatusEnum;
import com.git.cloud.resmgt.common.model.po.CmDevicePo;
/**
* 服务申请数据层实现类
* @ClassName:BmSrDaoImpl
* @Description:TODO
* @author sunhailong
* @date 2014-9-30 上午10:02:47
*/
@Repository
public class BmSrDaoImpl extends CommonDAOImpl implements IBmSrDao {
public void insertBmSr(BmSrVo bmSrVo) throws RollbackableBizException {
this.save("insertBmSr", bmSrVo);
}
public void updateBmSr(BmSrVo bmSrVo) throws RollbackableBizException {
this.update("updateBmSr", bmSrVo);
}
public void updateBmSrStatus(String srId, String srStatusCode) throws RollbackableBizException {
BmSrVo bmSrVo = new BmSrVo();
bmSrVo.setSrId(srId);
if(srStatusCode.equals(SrStatusCodeEnum.REQUEST_CLOSED.getValue())) {
bmSrVo.setCloseTime(SrDateUtil.getSrFortime(new Date()));
}
bmSrVo.setSrStatusCode(srStatusCode);
this.update("updatetBmSrStatus", bmSrVo);
}
public void updateAssignResult(String srId, String assignResult) throws RollbackableBizException {
BmSrVo bmSrVo = new BmSrVo();
bmSrVo.setSrId(srId);
bmSrVo.setAssignResult(assignResult);
this.update("updateAssignResult", bmSrVo);
}
public BmSrVo findBmSrVoById(String srId) throws RollbackableBizException {
return this.findObjectByID("findRrByIdBmSr",srId);
}
public BmSrVo findBmSrVoBySrCode(String srCode) throws RollbackableBizException {
return this.findObjectByID("findBmSrVoBySrCode",srCode);
}
public List<BmSrVo> findNewestCompleteRequest(int num) throws RollbackableBizException {
Map<String, Object> paramMap = new HashMap<String, Object> ();
paramMap.put("srStatusClose", SrStatusCodeEnum.REQUEST_CLOSED.getValue());
paramMap.put("num", num);
return this.findListByParam("findNewestCompleteRequest", paramMap);
}
public List<BmSrVo> findNewestCreateRequest(int num, String creatorId) throws RollbackableBizException {
Map<String, Object> paramMap = new HashMap<String, Object> ();
paramMap.put("num", num);
paramMap.put("userId", creatorId);
return this.findListByParam("findNewestCreateRequest", paramMap);
}
public List<BmToDoVo> findNewestWaitDealRequest(int num, String creatorId, String roleIds) throws RollbackableBizException {
Map<String, Object> paramMap = new HashMap<String, Object> ();
paramMap.put("num", num);
paramMap.put("userId", creatorId);
paramMap.put("roleIds", roleIds);
return this.findListByParam("findNewestWaitDealRequest", paramMap);
}
public List<AppSysKpiVo> findAppSysVirtualServer() throws RollbackableBizException {
Map<String, Object> paramMap = new HashMap<String, Object> ();
paramMap.put("deviceStatus", DeviceStatusEnum.DEVICE_STATUS_ONLINE.getValue());
return this.findListByParam("findAppSysVirtualServer", paramMap);
}
public List<AppSysKpiVo> findAppSysCompleteRequest() throws RollbackableBizException {
Map<String, Object> paramMap = new HashMap<String, Object> ();
paramMap.put("srStatusClose", SrStatusCodeEnum.REQUEST_CLOSED.getValue());
String year = DateUtil.getCurrentDataString("yyyy");
String month = DateUtil.getCurrentDataString("MM");
paramMap.put("closeStartTime", year + "-" + month + "-" + "01");
paramMap.put("closeEndTime", year + "-" + (Integer.valueOf(month) + 1) + "-" + "01");
return this.findListByParam("findAppSysCompleteRequest", paramMap);
}
@SuppressWarnings({ "unchecked"})
@Override
public void updateDeviceState(String srId) throws RollbackableBizException {
List<String> devIds = this.getSqlMapClientTemplate().queryForList("findDeviceIdsBySrId", srId);
CmDevicePo dev = null;
if(devIds != null && devIds.size() != 0){
dev = new CmDevicePo();
for(String devId : devIds){
dev.setId(devId);
dev.setRunningState("poweron");
this.getSqlMapClientTemplate().update("updateCmdeviceRunningState", dev);
}
}
}
@SuppressWarnings({ "unchecked"})
@Override
public List<AppStatVo> findAppStatBySrId(String srId)
throws RollbackableBizException {
List<AppStatVo> list = this.getSqlMapClientTemplate().queryForList("findAppStatBySrId", srId);
return list;
}
@Override
public String findTenatIdByUserId(String userId) throws RollbackableBizException{
return (String) this.getSqlMapClientTemplate().queryForObject("selectTenantByUserId", userId);
}
@Override
public BmToDoVo getCloudRequestWaitDealBySrId(String srId) {
return (BmToDoVo) this.getSqlMapClientTemplate().queryForObject("getCloudRequestWaitDealBySrId", srId);
}
}
|
package ast;
import eval.State;
public class VarDef extends AST {
public String name;
public Exp expression;
public VarDef(String name, Exp exp) {
this.name = name;
this.expression = exp;
}
@Override
public String toString() {
return "VarDef("+ name + "," + expression + ")";
}
@Override
public String gen(int depth) {
return null;
}
public void eval(State<Integer> varState, State<FunDef> stFun){
varState.bind(this.name, this.expression.eval(varState, stFun));
}
}
|
package ModeoDAO;
import Conexion.Conexion;
import ModeoDAO.ConvertirFecha;
import Modelo.Prestamo;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.ArrayList;
import java.util.List;
/**
*
* @author Bolaines
*/
public class PrestamoSQL extends Conexion {
public List mostrar() {
PreparedStatement ps = null;
ResultSet rs = null;
Connection con = getConexion();
ArrayList<Prestamo> list = new ArrayList<>();
String sql = "SELECT* FROM prestamo";
try {
ps = con.prepareStatement(sql);
rs = ps.executeQuery();
while (rs.next()) {
Prestamo prestamo = new Prestamo();
prestamo.setCodPrestamo(rs.getInt(1));
prestamo.setFecha_entrega(rs.getString(2));
prestamo.setFecha_devolucion(rs.getString(3));
prestamo.setEjemplar_codEjemplar(rs.getString(4));
prestamo.setUsuario(rs.getInt(5));
prestamo.setMora(rs.getString(6));
list.add(prestamo);
}
} catch (SQLException e) {
System.err.println(e);
} finally {
try {
con.close();
} catch (SQLException e) {
System.err.println(e);
}
}
return list;
}
public Prestamo buscar(String ID) {
PreparedStatement ps = null;
ResultSet rs = null;
Connection con = getConexion();
Prestamo obj = new Prestamo();
String sql = "SELECT* FROM Prestamo where codPrestamo=" + ID;
try {
ps = con.prepareStatement(sql);
rs = ps.executeQuery();
while (rs.next()) {
obj.setCodPrestamo(rs.getInt(1));
obj.setFecha_entrega(rs.getString(2));
obj.setFecha_devolucion(rs.getString(3));
obj.setEjemplar_codEjemplar(rs.getString(4));
obj.setUsuario(rs.getInt(5));
obj.setMora(rs.getString(6));
}
} catch (SQLException e) {
System.err.println(e);
} finally {
try {
con.close();
} catch (SQLException e) {
System.err.println(e);
}
}
return obj;
}
public boolean agregar(boolean pass, Prestamo prest) throws ParseException {
if (pass) {
PreparedStatement ps = null;
Connection con = getConexion();
ConvertirFecha convert = new ConvertirFecha();
String sql = "INSERT INTO prestamo (codPrestamo, fecha_entrega, fecha_devolucion, ejemplar_codEjemplar, usuario, mora ) VALUES(?,?,?,?,?,?)";
String sDate1 = prest.getFecha_entrega();
String sDate2 = prest.getFecha_devolucion();
Date date1 = new SimpleDateFormat("yyyy-MM-dd").parse(sDate1);
Date date2 = new SimpleDateFormat("yyyy-MM-dd").parse(sDate2);
try {
int z = 1;
ps = con.prepareStatement(sql);
ps.setInt(z++, generarCod());
ps.setDate(z++, convert.convertUtilToSql(date1));
ps.setDate(z++, null);
ps.setString(z++, prest.getEjemplar_codEjemplar());
ps.setInt(z++, prest.getUsuario());
ps.setInt(z++, Integer.parseInt(prest.getMora()));
ps.execute();
} catch (SQLException e) {
System.err.println(e);
System.out.println("Error en Agregar de la clase PrestamoSQL");
return false;
} finally {
try {
con.close();
} catch (SQLException e) {
System.err.println(e);
}
}
}
EjemplarSQL ejemsql = new EjemplarSQL();
ejemsql.ActualizarEstado(false, prest.getEjemplar_codEjemplar());
return true;
}
public void actualizar(boolean pass, Prestamo prest) {
if (pass) {
PreparedStatement ps = null;
Connection con = getConexion();
String sql = "UPDATE prestamo SET codPrestamo=?, fecha_entrega=?, fecha_devolucion=?, ejemplar_codEjemplar=?, usuario=?, mora=? WHERE codPrestamo=? ";
try {
ps = con.prepareStatement(sql);
int z = 1;
ps.setString(z++, prest.getFecha_entrega());
ps.setString(z++, prest.getFecha_devolucion());
ps.setString(z++, prest.getEjemplar_codEjemplar());
ps.setInt(z++, prest.getUsuario());
ps.setString(z++, prest.getMora());
ps.setInt(z++, prest.getCodPrestamo());
ps.execute();
} catch (SQLException e) {
System.err.println(e);
System.out.println("Error en Actualizar de la clase PrestamoSQL");
} finally {
try {
con.close();
} catch (SQLException e) {
System.err.println(e);
}
}
}
}
public void eliminar(boolean pass, String id) {
if (pass) {
PreparedStatement ps = null;
Connection con = getConexion();
String sql = "DELETE FROM prestamo WHERE codPrestamo=" + id;
try {
ps = con.prepareStatement(sql);
ps.setString(1, sql);
ps.execute();
} catch (SQLException e) {
System.err.println(e);
System.out.println("Error en Eliminar de la clase PrestamoSQL");
} finally {
try {
con.close();
} catch (SQLException e) {
System.err.println(e);
}
}
}
}
///Genarador de codigo
public int generarCod() {
PreparedStatement ps = null;
ResultSet rs = null;
Connection con = getConexion();
String sql = "SELECT MAX(codPrestamo) as cantidad FROM prestamo";
try {
ps = con.prepareStatement(sql);
rs = ps.executeQuery();
if (rs.next()) {
return Integer.parseInt(rs.getString("cantidad")) + 1;
}
return 0;
} catch (SQLException e) {
System.err.println(e);
return 0;
} finally {
try {
con.close();
} catch (SQLException e) {
System.err.println(e);
}
}
}
public List seleccionarEjemplar(String ID) {
PreparedStatement ps = null;
ResultSet rs = null;
Connection con = getConexion();
List<String> objeto = new ArrayList<String>();
String sql = "SELECT max(codEjemplar),cod_Libro,Titulo,Ubicacion "
+ "FROM ejemplar "
+ "inner join libro on cod_Libro=codLibro "
+ "where Estado='DISPONIBLE' AND cod_Libro=?";
try {
ps = con.prepareStatement(sql);
ps.setString(1, ID);
rs = ps.executeQuery();
while (rs.next()) {
int z=1;
objeto.add(rs.getString(z++)+"");
objeto.add(rs.getString(z++));
objeto.add(rs.getString(z++));
objeto.add(rs.getString(z++));
}
} catch (SQLException e) {
System.err.println(e);
} finally {
try {
con.close();
} catch (SQLException e) {
System.err.println(e);
}
}
return objeto;
}
public List InfoPrestamosUsuario(String user, boolean nivel) {
PreparedStatement ps = null;
ResultSet rs = null;
Connection con = getConexion();
List<List> list = new ArrayList<List>();
String sql = "";
if (nivel) {
//estudiante
sql = "SELECT codPrestamo,Fecha_entrega,ejemplar_codEjemplar,Titulo,Usuario \n"
+ "FROM biblioteca.prestamo\n"
+ "inner join ejemplar as e on e.codEjemplar=ejemplar_codEjemplar\n"
+ "inner join libro as l on e.cod_Libro=l.codLibro\n"
+ "inner join usuario as u on u.codUsuario=Usuario\n"
+ "where Fecha_devolucion is null and correo='" + user + "'";
} else {
sql = "SELECT codPrestamo,Fecha_entrega,ejemplar_codEjemplar,Titulo,Estado \n"
+ "FROM biblioteca.prestamo\n"
+ "inner join ejemplar as e on e.codEjemplar=ejemplar_codEjemplar\n"
+ "inner join libro as l on e.cod_Libro=l.codLibro\n"
+ "inner join usuario as u on u.codUsuario=Usuario\n"
+ "where correo='" + user + "'";
}
try {
ps = con.prepareStatement(sql);
rs = ps.executeQuery();
while (rs.next()) {
int z = 1;
List<String> objeto = new ArrayList<String>();
objeto.add(rs.getString(z++));
objeto.add(rs.getString(z++));
objeto.add(rs.getString(z++));
objeto.add(rs.getString(z++));
objeto.add(rs.getString(z++));
list.add(objeto);
}
} catch (SQLException e) {
System.err.println(e);
} finally {
try {
con.close();
} catch (SQLException e) {
System.err.println(e);
}
}
return list;
}
}// cierre
|
package cn.jaychang.scstudy.scfeignms.controller;
import cn.jaychang.scstudy.scfeignms.feign.HelloFeignClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
/**
* @author zhangjie
* @package cn.jaychang.scstudy.scfeignms.controller
* @description TODO
* @create 2018-09-20 10:16
*/
@RestController
public class HelloController {
@Autowired
private HelloFeignClient helloFeignClient;
@GetMapping("/hello")
public String hello(@RequestParam(value = "name",required = false,defaultValue = "springcloud") String name){
return helloFeignClient.sayHello(name);
}
}
|
package by.realovka.diploma.controller;
import by.realovka.diploma.dto.CommentAddDTO;
import by.realovka.diploma.dto.PostOnPageDTO;
import by.realovka.diploma.entity.User;
import by.realovka.diploma.service.FriendshipService;
import by.realovka.diploma.service.PostService;
import by.realovka.diploma.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import java.util.List;
@Controller
@RequestMapping(path = "/friend")
public class FriendController {
@Autowired
private FriendshipService friendshipService;
@Autowired
private UserService userService;
@Autowired
private PostService postService;
@GetMapping(path = "/friend/{personId}")
public ModelAndView additionToFriend(@PathVariable long personId, @AuthenticationPrincipal User user, ModelAndView modelAndView){
User person = userService.getUserById(personId);
friendshipService.saveFriendship(user,person);
List<User> friends = friendshipService.getAllFriendsPerson(person.getId(), user.getId());
if (friendshipService.getAnswerAreUserAndPersonFriends(user.getId(),person.getId())) {
modelAndView.addObject("messageAboutFriend", "It's your friend");
}
List<PostOnPageDTO> posts = postService.getPosts(personId);
modelAndView.addObject("comment", new CommentAddDTO());
modelAndView.addObject("person", person);
modelAndView.addObject("authUser", user);
modelAndView.addObject("posts", posts);
modelAndView.addObject("friends", friends);
modelAndView.setViewName(String.format("redirect:/person/person/%s",person.getId()));
return modelAndView;
}
}
|
package edu.ycp.cs320.groupProject.ui;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
import edu.ycp.cs320.groupProject.webapp.shared.controller.*;
import edu.ycp.cs320.groupProject.webapp.shared.model.Ball;
import edu.ycp.cs320.groupProject.webapp.shared.model.Paddle;
import edu.ycp.cs320.groupProject.webapp.shared.model.Stage;
public class StageView extends JPanel {
private static final long serialVersionUID = -5918784966455771417L;
private Stage model;
private StageController controller;
private Timer timer;
public StageView(Stage model) {
this.model = model;
setPreferredSize(new Dimension( Stage.WIDTH, Stage.HEIGHT));
this.timer = new Timer(1000 / 30, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
handleTimerTick();
}
});
}
public void setController(StageController controller) {
this.controller = controller;
}
public void startAnimation() {
timer.start();
}
protected void handleTimerTick() {
controller.timerTick(model);
repaint();
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g); // paint background
Ball ball = model.getBall();
for(Paddle temp: model.getPaddles()){
g.setColor(Color.DARK_GRAY);
if (temp.isVertical()){
g.fillRect(temp.getTopLeft().getX(), temp.getTopLeft().getY(),
temp.getHeight() , temp.getWidth());
}else{
g.fillRect(temp.getTopLeft().getX(), temp.getTopLeft().getY(),
temp.getWidth(),temp.getHeight() );
}
g.setColor(Color.BLUE);
g.fillOval(temp.findNearest(ball).getX(),temp.findNearest(ball).getY(),6,6);
}
g.fillOval(ball.getX()-ball.getRadius(), ball.getY()-ball.getRadius(), ball.getRadius()*2, ball.getRadius()*2);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
Stage model = new Stage();
StageController controller = new StageController();
StageView view = new StageView(model);
view.setController(controller);
controller.initModel(model);
JFrame frame = new JFrame("p4ng");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(view);
frame.pack();
frame.setVisible(true);
view.startAnimation();
}
});
}
}
|
package reading;
public class NewCarClass{
public String manufacturename;
private String modelname;
private String passkey;
int enginecc;
private float fuelamount;
final private float amountoffuelconsumepersecond=0.02f;
protected int manufactureyear;
public NewCarClass(){
manufacturename=new String();
modelname=new String();
enginecc=1000;
fuelamount=0;
manufactureyear=0;
}
public NewCarClass(String carname){
manufacturename=new String(carname);
modelname=new String();
enginecc=0;
fuelamount=0;
manufactureyear=0;
}
public NewCarClass(String manu,String model,String key,int enginecc,float fuel){
manufacturename=manu;
modelname=model;
passkey=key;
this.enginecc=enginecc;
fuelamount=fuel;
manufactureyear=0;
}
public NewCarClass(String manu,String model,String key,int enginecc,float fuel,int year){
this(manu,model,key,enginecc,fuel);
manufactureyear=year;
}
public float presentamountoffuel(){
return fuelamount;
}
public String getmanufacturename(){
return manufacturename;
}
public String getmodelname(){
return modelname;
}
public void addfuel(float fuelamount){
this.fuelamount+=fuelamount;
}
public void runforsecond(int timeinsecond){
float usedfuel=timeinsecond*amountoffuelconsumepersecond;
fuelamount-=usedfuel;
}
public boolean matchpass(String userinput){
return userinput.equals(passkey);
}
public void printAllinfo(){
pl("Manufacturer : "+manufacturename);
pl("Model Name : "+getmodelname());
pl("Password Match : "+matchpass("rtyfgH"));
pl("2nd car name : "+enginecc);
pl("Amount of Fuel : "+presentamountoffuel()+"L");
addfuel(2);
pl("After adding 2L : "+presentamountoffuel()+"L");
runforsecond(60);
pl("Amount of Fuel after driving fro 60s : "+presentamountoffuel()+"L");
}
static void pl(Object an){
System.out.println(an);
}
static void p(Object an){
System.out.print(an);
}
}
|
package com.egame.app.uis;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnKeyListener;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Window;
import android.view.WindowManager;
import com.egame.R;
import com.egame.app.EgameApplication;
import com.egame.utils.common.CommonUtil;
import com.egame.utils.sys.DialogStyle;
import com.eshore.network.stat.NetStat;
/**
*
* service中弹出对话框的activity
*
* @author yaopp@gzylxx.com
*/
public class AlertActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.egame_alert_layout);
DialogInterface.OnClickListener comfirmL = new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
CommonUtil.installGames(AlertActivity.this.getIntent()
.getStringExtra("gameid"), AlertActivity.this);
AlertActivity.this.finish();
}
};
DialogInterface.OnClickListener cancelL = new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
AlertActivity.this.finish();
}
};
DialogStyle ds = new DialogStyle();
AlertDialog.Builder builder = ds.getBuilder(AlertActivity.this, "确定",
"取消", comfirmL, cancelL);
builder.setOnKeyListener(new OnKeyListener() {
@Override
public boolean onKey(DialogInterface dialog, int keyCode,
KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_UP
&& keyCode == KeyEvent.KEYCODE_BACK) {
AlertActivity.this.finish();
return true;
}
return false;
}
});
AlertDialog d = builder.setIcon(android.R.drawable.ic_dialog_map).setTitle("下载完成!")
.setMessage("是否立即安装已下载的游戏?").create();
d.setCanceledOnTouchOutside(false);
d.show();
EgameApplication.Instance().addActivity(this);
}
/**
*
*/
@Override
protected void onResume() {
super.onResume();
NetStat.onResumePage();
}
/**
*
*/
@Override
protected void onPause() {
super.onPause();
NetStat.onPausePage("AlertActivity");
}
}
|
package fh.ooe.mcm.accelerometerdatagatherer;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.AsyncTask;
import android.os.PowerManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.CompoundButton;
import android.widget.Toast;
import android.widget.ToggleButton;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity implements CompoundButton.OnCheckedChangeListener {
DecimalFormat format = new DecimalFormat("00.00");
boolean activityOn = false;
String activity;
String label;
String filename = "data.txt";
FileOutputStream outputStream;
File file;
ToggleButton sittingToggle;
ToggleButton standingToggle;
ToggleButton walkingToggle;
ToggleButton joggingToggle;
ToggleButton downstairsToggle;
ToggleButton upstairsToggle;
ToggleButton currentlyToggled;
ArrayList<String> gatheredData;
LockScreenReceiver lockScreenReceiver;
SensorService sensorService;
long previousTime = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
file = new File(getExternalFilesDir(null) + "/" + filename);
if(!file.exists()) {
try {
if(!file.createNewFile()) {
Toast.makeText(getApplicationContext(), "File not created.", Toast.LENGTH_SHORT);
finish();
}
} catch (IOException e) {
e.printStackTrace();
}
}
gatheredData = new ArrayList<>();
sittingToggle = findViewById(R.id.sittingToggle);
standingToggle = findViewById(R.id.standingToggle);
walkingToggle = findViewById(R.id.walkingToggle);
joggingToggle = findViewById(R.id.joggingToggle);
downstairsToggle = findViewById(R.id.downstairsToggle);
upstairsToggle = findViewById(R.id.upstairsToggle);
sittingToggle.setOnCheckedChangeListener(this);
standingToggle.setOnCheckedChangeListener(this);
walkingToggle.setOnCheckedChangeListener(this);
joggingToggle.setOnCheckedChangeListener(this);
downstairsToggle.setOnCheckedChangeListener(this);
upstairsToggle.setOnCheckedChangeListener(this);
lockScreenReceiver = new LockScreenReceiver(this);
IntentFilter lockFilter = new IntentFilter();
lockFilter.addAction(Intent.ACTION_SCREEN_ON);
lockFilter.addAction(Intent.ACTION_SCREEN_OFF);
registerReceiver(lockScreenReceiver, lockFilter);
sensorService = new SensorService(this);
}
@Override
protected void onDestroy() {
super.onDestroy();
}
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
if(currentlyToggled != null) {
currentlyToggled.setChecked(false);
}
currentlyToggled = (ToggleButton) buttonView;
lockScreenReceiver.setCurrentlyToggled(currentlyToggled);
activityOn = true;
activity = buttonView.getText().toString();
sensorService.sleep(3000);
gatheredData.clear();
String startLine = " " + "," + "START" + "," + 0 + "," + 0 + "," + 0 + "\n";
gatheredData.add(startLine);
} else {
activityOn = false;
currentlyToggled = null;
gatheredData.clear();
}
}
private class DataWriter extends AsyncTask<ArrayList<String>, Integer, Void> {
protected Void doInBackground(ArrayList<String>... arrayLists) {
ArrayList<String> lines = arrayLists[0];
try {
outputStream = new FileOutputStream(file, true);
for (String line : lines) {
outputStream.write(line.getBytes());
// Escape early if cancel() is called
if (isCancelled()) break;
}
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
public void addData(double x, double y, double z) {
Long time = System.currentTimeMillis();
Long timediff = time - previousTime;
if(timediff > 45 && previousTime != 0) {
gatheredData.add(time + "," + activity + "," + format.format(x) + "," + format.format(y) + "," + format.format(z) + "\n");
if (gatheredData.size() >= 201) {
new MainActivity.DataWriter().execute((ArrayList<String>) gatheredData.clone());
gatheredData.clear();
}
}
previousTime = time;
}
public boolean isActivityOn() {
return activityOn;
}
}
|
/*
* Board.java
* Author: Alex LaFroscia
* Date: Jan 28, 2015
*/
import java.util.*;
public class Board {
private static final int NUM_ROWS = 4;
private static final int NUM_COLS = 4;
private BoardSpace[][] board;
private String name;
public DictionaryInterface foundWords;
private DictionaryInterface dictionary;
private Set<String> foundWordsList = new HashSet<String>();
public Board(String fileName, String dbType, char[] characterArray) {
// Get name of board
fileName = fileName.substring(5, 6);
name = "Board " + fileName;
// Set up dictionary
if (dbType.equals("simple")) {
foundWords = new SimpleDictionary();
} else if (dbType.equals("dlb")) {
foundWords = new DlbDictionary();
}
// Set up board
board = new BoardSpace[NUM_ROWS][NUM_COLS];
int k = 0;
for (int i = 0; i < NUM_ROWS; i++) {
for (int j = 0; j < NUM_COLS; j++) {
board[i][j] = new BoardSpace(characterArray[k++]);
}
}
}
/**
* Scans the board for words found in the given dictionary
*
* @param dictionary An instance of a DictionaryInterface that represents all
* of the possible valid words
*/
public Thread scan(DictionaryInterface dictionary) {
this.dictionary = dictionary;
Thread t = new Thread(new DictionarySearch(dictionary));
t.start();
return t;
}
/**
* Start a new thread to search the board against the dictionary.
*
* This is a process that can take a long time, and I noticed that the way the
* game is set up, we have a chance to do some keyboard IO during the same
* time to get the guesses from the user of the program. Instead of having an
* awkward pause here, we can parallelize it and have the board searched while
* the user guesses
*/
private class DictionarySearch implements Runnable {
private DictionaryInterface dictionary;
public DictionarySearch(DictionaryInterface dictionary) {
this.dictionary = dictionary;
}
/**
* Kick off the search of the board.
*
* To make this a separate thread, we needed a new class with a run() method
*/
public void run() {
StringBuilder sb = new StringBuilder();
// Run a search tree starting at each of the board's squares
for (int i = 0; i < NUM_ROWS; i++) {
for (int j = 0; j < NUM_COLS; j++) {
search(i, j, sb);
}
}
}
/**
* Check if a square is part of a string.
*
* Searches one square of the board for the given StringBuilder, then possibly
* goes on to search further squares.
*
* Note: This is a recursive call
*
* @param x The x value of the coordinates of the board square to check
* @param y The y value of the coordinates of the board square to check
* @param sb The string builder that represents the current String being built
* and checked against the master dictionary.
*/
private void search(int x, int y, StringBuilder sb) {
BoardSpace square = board[x][y];
// If the square has been used in this word already, skip it here
if (square.checked) {
return;
} else {
square.checked = true;
}
char c = square.value;
c = Character.toLowerCase(c); // Normalize everything to lower case
if (c == '*') {
int ALPHABET_LENGTH = 26;
char[] alphabet = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k',
'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
'w', 'x', 'y', 'z'};
for (int i = 0; i < ALPHABET_LENGTH; i++) {
StringBuilder sbNew = new StringBuilder(sb);
sbNew.append(alphabet[i]);
searchForString(x, y, square, sbNew);
}
} else {
sb.append(c);
searchForString(x, y, square, sb);
}
}
private void searchForString(int x, int y, BoardSpace square, StringBuilder sb) {
// Note: This could be refactored into less lines of code by making
// extensive use of fallthrough, but in reality it makes the code a lot
// harder to read. Like they always say, write code for humans!
switch(this.dictionary.search(sb)) {
case 0:
// sb not in dictionary, remove new character and return
sb.deleteCharAt(sb.length() - 1);
square.checked = false;
return;
case 1:
// sb is a prefix; break to search
break;
case 2:
// sb is in the dictionary but is _not_ a prefix. Add it to the
// dictionary, shorten sb and return
foundWords.add(sb.toString());
foundWordsList.add(sb.toString());
sb.deleteCharAt(sb.length() - 1);
square.checked = false;
return;
case 3:
// sb is both in the dictionary _and_ is a prefix. Add it to the
// dictionary and break to search
foundWords.add(sb.toString());
foundWordsList.add(sb.toString());
break;
default:
// If by some strange miracle you end up with a return value from
// dictionary.search that isn't one of those values, just shorten sb and
// return
sb.deleteCharAt(sb.length() - 1);
square.checked = false;
return;
}
// Format the if statements to that the `x` and `y` statements line up
// Check X Value Check Y Value Search that square
// North West
if ((x - 1) >= 0 & (y - 1) >= 0 ) { search(x - 1, y - 1, sb); }
// North
if ( (y - 1) >= 0 ) { search(x , y - 1, sb); }
// North East
if ((x + 1) < NUM_ROWS & (y - 1) >= 0 ) { search(x + 1, y - 1, sb); }
// West
if ((x - 1) >= 0 ) { search(x - 1, y , sb); }
// East
if ((x + 1) < NUM_ROWS ) { search(x + 1, y , sb); }
// South West
if ((x - 1) >= 0 & (y + 1) < NUM_COLS) { search(x - 1, y + 1, sb); }
// South
if ( (y + 1) < NUM_COLS) { search(x , y + 1, sb); }
// South East
if ((x + 1) < NUM_ROWS & (y + 1) < NUM_COLS) { search(x + 1, y + 1, sb); }
// After checking each neighboring square, remove the last character from
// sb, mark this square as not yet checked, and return
sb.deleteCharAt(sb.length() - 1);
square.checked = false;
return;
}
}
/**
* Prints the dictionary of words found on this board.
*
* Takes the HashSet of words that were found on the board, converts it into
* an ArrayList, sorts it, and prints it out.
*
*/
public void printDictionary() {
ArrayList<String> sortedList = new ArrayList<String>(this.foundWordsList);
Collections.sort(sortedList);
for(String word: sortedList) {
System.out.println(word);
}
}
public int getDictionaryCount() {
return foundWordsList.size();
}
@Override public String toString() {
StringBuilder result = new StringBuilder();
result.append(name + '\n');
for (int i = 0; i < NUM_ROWS; i++) {
StringBuilder row = new StringBuilder();
for (int j = 0; j < NUM_COLS; j++) {
row.append(board[i][j].value + " ");
}
row.append('\n');
result.append(row);
}
return result.toString();
}
/*
* BoardSpace
* Author: Alex LaFroscia
* Date: Jan 28, 2015
*
* Represents a single space on a Boggle board
*/
private class BoardSpace {
public boolean checked = false;
public char value;
public BoardSpace(char boardValue) {
value = boardValue;
}
}
}
|
package com.gsccs.sme.api.domain;
import java.io.Serializable;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import com.gsccs.sme.api.domain.base.Domain;
/**
* 订单购物项
* @author x.d zhang
*
*/
public class PorderItem extends Domain{
private String id;
private String orderid;
private Long productid;
private Long skuid;
private Integer num;
private Double price;
private Double accout;
private String buyer;
private String seller;
private Date addtime;
private String state;
private String title;
private String specstr;
private String ptitle;
private String purl;
private String adddatestr;
//是否已评价
private String iseval;
public String getAdddatestr() {
DateFormat df = new SimpleDateFormat("yyyy-mm-dd");
if(null != getAddtime()){
adddatestr = df.format(getAddtime());
}
return adddatestr;
}
public void setAdddatestr(String adddatestr) {
this.adddatestr = adddatestr;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getOrderid() {
return orderid;
}
public void setOrderid(String orderid) {
this.orderid = orderid;
}
public Long getProductid() {
return productid;
}
public void setProductid(Long productid) {
this.productid = productid;
}
public Long getSkuid() {
return skuid;
}
public void setSkuid(Long skuid) {
this.skuid = skuid;
}
public Integer getNum() {
return num;
}
public void setNum(Integer num) {
this.num = num;
}
public Double getPrice() {
return price;
}
public void setPrice(Double price) {
this.price = price;
}
public Double getAccout() {
return accout;
}
public void setAccout(Double accout) {
this.accout = accout;
}
public String getBuyer() {
return buyer;
}
public void setBuyer(String buyer) {
this.buyer = buyer == null ? null : buyer.trim();
}
public String getSeller() {
return seller;
}
public void setSeller(String seller) {
this.seller = seller == null ? null : seller.trim();
}
public Date getAddtime() {
return addtime;
}
public void setAddtime(Date addtime) {
this.addtime = addtime;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state == null ? null : state.trim();
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getSpecstr() {
return specstr;
}
public void setSpecstr(String specstr) {
this.specstr = specstr;
}
public String getPtitle() {
return ptitle;
}
public void setPtitle(String ptitle) {
this.ptitle = ptitle;
}
public String getPurl() {
return purl;
}
public void setPurl(String purl) {
this.purl = purl;
}
public String getIseval() {
return iseval;
}
public void setIseval(String iseval) {
this.iseval = iseval;
}
}
|
package com.uchain.core.consensus.sorted;
import com.google.common.collect.Lists;
import com.uchain.core.consensus.MapKeyComparator;
import com.uchain.core.consensus.TwoTuple;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
public class SortedMultiMap1<K, V> {
private Map<K, List<V>> container;
public SortedMultiMap1(String sortType) {
this.container = new TreeMap(new MapKeyComparator<K>(sortType));
}
public int size() {
int sizeBig = 0;
for (Map.Entry<K, List<V>> entry : container.entrySet()) {
sizeBig += entry.getValue().size();
}
return sizeBig;
}
public boolean contains(K k) {
return container.containsKey(k);
}
public List<V> get(K k) {
return container.get(k);
}
public void put(K k, V v) {
if (!container.containsKey(k)) {
container.put(k, Lists.newArrayList());
}
container.get(k).add(v);
}
public List<V> remove(K k) {
return container.remove(k);
}
public TwoTuple<K, V> head() {
return iterator().next();
}
public SortedMultiMap1Iterator<K, V> iterator() {
return new SortedMultiMap1Iterator(container);
}
}
|
package com.codigo.smartstore.xbase.codepage;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CharsetEncoder;
import java.nio.charset.CoderResult;
/**
* Klasa implementuje mechanizm kodowania/dekodowania znaków w standardzie
* ROT13. Przykładowe użycie:
*
* ROT13 – prosty szyfr przesuwający, którego działanie polega na zamianie
* każdego znaku alfabetu łacińskiego na znak występujący 13 pozycji po nim,
* przy czym wielkość liter nie ma przy przekształcaniu znaczenia. ROT13 jest
* przykładem szyfru Cezara, opracowanego w Starożytnym Rzymie.
*
* <code>Charset.forName("ROT13")</code>
*
* @author andrzej.radziszewski
* @version 1.0.0.0
* @since 2017
* @category charset
*/
public final class Rot13Charset
extends
Charset {
/**
* Domyślna nazwa standardu kodowania/dekodowania znaków
*/
private static final String BASE_CHARSET_NAME = "UTF-8";
/**
* Atrybut reprezentuje podstawowy rodzaj kodowania/dekodowania znaków
*/
private final Charset baseCharset;
/**
* Podstawowy konstruktor obiektu klasy <code>Rot13Charset</code>
*
* @param canonical Potoczna nazwa standardu kodowania/dekodowania znaków
* @param aliases Aliasy nazw dla standaru kodowania/dekodowania znaków
*/
public Rot13Charset(final String canonical, final String[] aliases) {
super(canonical, aliases);
this.baseCharset = Charset.forName(Rot13Charset.BASE_CHARSET_NAME);
}
/*
* (non-Javadoc)
* @see java.nio.charset.Charset#contains(java.nio.charset.Charset)
*/
@Override
public boolean contains(final Charset cs) {
return cs.equals(this);
}
/*
* (non-Javadoc)
* @see java.nio.charset.Charset#newDecoder()
*/
@Override
public CharsetDecoder newDecoder() {
return new Rot13CharsetDecoder(
this, this.baseCharset.newDecoder());
}
/*
* (non-Javadoc)
* @see java.nio.charset.Charset#newEncoder()
*/
@Override
public CharsetEncoder newEncoder() {
return new Rot13CharsetEncoder(
this, this.baseCharset.newEncoder());
}
/**
* Metoda implementuje mechanizm kodowanie/dekodowania znaków dla standardu
* ROT13
*
* @param cb Bufor wejściowy prztetwarznych znaków
*/
private void rot13(final CharBuffer cb) {
for (int pos = cb.position(); pos < cb.limit(); pos++) {
char basechar = cb.get(pos);
char cezarchar = '\u0000';
// Is it lower case alpha?
if ((basechar >= 'a') && (basechar <= 'z'))
cezarchar = 'a';
// Is it upper case alpha?
if ((basechar >= 'A') && (basechar <= 'Z'))
cezarchar = 'A';
// If either, roll it by 13
if (cezarchar != '\u0000') {
basechar = (char) ((((basechar - cezarchar) + 13) % 26) + cezarchar);
cb.put(pos, basechar);
}
}
}
/**
* Klasa implementuje mechanizm dekodowania znaków standardu ROT13
*
* @author andrzej.radziszewski
* @version 1.0.0.0
* @since 2017
* @category charset
*/
private final class Rot13CharsetDecoder
extends
CharsetDecoder {
/**
* Atrybut reprezentuje podstawowy dekoder standardu R0T13
*/
private final CharsetDecoder baseDecoder;
/**
* Podstawowy konstruktor obiektu klasy <code>Rot13CharsetDecoder</code>
*
* @param cs Rodzaj kodowania/dekodowania znaków
* @param baseDecoder Dekoder znaków standardu ROT13
*/
public Rot13CharsetDecoder(final Charset cs, final CharsetDecoder baseDecoder) {
super(cs, baseDecoder.averageCharsPerByte(), baseDecoder.maxCharsPerByte());
this.baseDecoder = baseDecoder;
}
/*
* (non-Javadoc)
* @see java.nio.charset.CharsetDecoder#decodeLoop(java.nio.ByteBuffer,
* java.nio.CharBuffer)
*/
@Override
protected CoderResult decodeLoop(final ByteBuffer in, final CharBuffer out) {
this.baseDecoder.reset();
final CoderResult result = this.baseDecoder.decode(in, out, true);
Rot13Charset.this.rot13(out);
return result;
}
}
/**
* Klasa implementuje mechanizm kodowania standardu ROT13
*
* @author andrzej.radziszewski
* @version 1.0.0.0
* @since 2017
* @category charset
*/
private final class Rot13CharsetEncoder
extends
CharsetEncoder {
/**
* Atrybut reprezentuje podstawowy koder standardu R0T13
*/
private final CharsetEncoder baseEncoder;
/**
* Podstawowy konstruktor obiektu klasy <code>Rot13CharsetEncoder</code>
*
* @param cs Rodzaj kodowania/dekodowania znaków
* @param baseEncoder Podstawowy koder standardu ROT13
*/
public Rot13CharsetEncoder(final Charset cs, final CharsetEncoder baseEncoder) {
super(cs, baseEncoder.averageBytesPerChar(), baseEncoder.maxBytesPerChar());
this.baseEncoder = baseEncoder;
}
/*
* (non-Javadoc)
* @see java.nio.charset.CharsetEncoder#encodeLoop(java.nio.CharBuffer,
* java.nio.ByteBuffer)
*/
@Override
protected CoderResult encodeLoop(final CharBuffer in, final ByteBuffer out) {
final CharBuffer buffer = CharBuffer.allocate(in.remaining());
while (in.hasRemaining())
buffer.put(in.get());
buffer.rewind();
Rot13Charset.this.rot13(buffer);
this.baseEncoder.reset();
final CoderResult result = this.baseEncoder.encode(buffer, out, true);
in.position(in.position() - buffer.remaining());
return result;
}
}
}
|
package arr;
import java.util.Arrays;
import java.util.Stack;
public class PrintAllDistinctSubset {
public static void main(String arg[]){
int[] a = {1,3,1};
Arrays.sort(a);
powerSubset(a,new Stack(),a.length-1);
}
public static void powerSubset(int[] s, Stack res, int l){
if(l<0){
System.out.println(res.toString());
return;
}
res.push(s[l]);
powerSubset(s,res,l-1);
res.pop();
while(l>0 && s[l]==s[l-1]){
l--;
}
powerSubset(s,res,l-1);
}
}
|
package com.netcracker.app.domain.info.entities.resumes;
import java.util.Calendar;
public interface Resume {
String getFirstName();
void setFirstName(String firstName) throws Exception;
String getLastName();
void setLastName(String lastName) throws Exception;
String getPhone();
void setPhone(String phone) throws Exception;
String getEmail();
void setEmail(String email) throws Exception;
String getText();
void setText(String text) throws Exception;
Calendar getBirthday();
void setBirthday(String birthday) throws Exception;
}
|
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter Number:");
int input = scanner.nextInt();
if (input < 0) {
throw new IllegalArgumentException(input + "");
}
int output = 1;
for (int i = input; i > 0; i--) {
output = output * i;
}
System.out.println(input + "! = " + output);
}
}
|
package za.co.bonginkosilukhele.servicebiz.fragments;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import za.co.bonginkosilukhele.servicebiz.R;
/**
* Created by Admin on 2017-02-01.
*/
public class NotificationsFragment extends Fragment{
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.view_things,container,false);
TextView textView= (TextView) rootView.findViewById(R.id.textview_frag);
textView.setText("This is my Notifications page");
return rootView;
}
}
|
package action.com.team;
import action.com.Base.BaseAction;
import pojo.DAO.ProjectDAO;
import pojo.DAO.TeamDAO;
import pojo.valueObject.DTO.TeamDTO;
import pojo.valueObject.domain.ProjectVO;
import pojo.valueObject.domain.TeacherVO;
import pojo.valueObject.domain.TeamVO;
import tool.BeanFactory;
import tool.JSONHandler;
import java.util.ArrayList;
/**
* Created by GR on 2017/4/19.
*/
public class GetTeamsByTeacherAction extends BaseAction{
@Override
public String execute() throws Exception {
try {
TeacherVO teacherVO = (TeacherVO) session.get("teacherVO");
ProjectDAO projectDAO = BeanFactory.getBean("projectDAO", ProjectDAO.class);
TeamDAO teamDAO = BeanFactory.getBean("teamDAO", TeamDAO.class);
ArrayList<ProjectVO> projectVOS = projectDAO.getTeacherProjectVOList(teacherVO);
ArrayList<TeamDTO> teamDTOS = BeanFactory.getBean("arrayList", ArrayList.class);
if (projectVOS != null) {
for (ProjectVO projectVO : projectVOS) {
ArrayList<TeamVO> teamVOS = (ArrayList<TeamVO>) teamDAO.getTeamVOByProjectVO(projectVO);
if (teamVOS != null) {
for (TeamVO teamVO : teamVOS) {
boolean isHave = false;
for(TeamDTO teamDTO:teamDTOS){
if(teamDTO.getId() == teamVO.getId()) {
isHave = true;
}
}
if(isHave == false) {
TeamDTO teamDTO = BeanFactory.getBean("teamDTO", TeamDTO.class);
teamDTO.clone(teamVO);
teamDTOS.add(teamDTO);
}
}
}
}
}
jsonObject.put("result", "success");
jsonObject.put("teamBeans", teamDTOS);
JSONHandler.sendJSON(jsonObject, response);
return "success";
}catch(Exception e){
e.printStackTrace();
jsonObject.put("result","SQLException");
JSONHandler.sendJSON(jsonObject,response);
return "fail";
}
}
}
|
package io.github.stepheniskander.equationsolver;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* A polynomial in Q[x]
*/
public class Polynomial {
private RationalNumber[] coefficients;
private RationalNumber[] powers;
public Polynomial(RationalNumber[] coefficients, RationalNumber[] powers) throws IllegalArgumentException {
this.coefficients = coefficients;
this.powers = powers;
}
public Polynomial(String input) {
List<String> splitA = Arrays.asList(input.split("\\+"));
ArrayList<String> split = new ArrayList<>();
split.addAll(splitA);
Pattern negCheck = Pattern.compile("(.+) ?- ?(.+)");
Pattern termSplitter = Pattern.compile(" *([\\-0-9\\/]*)\\*?([xX]\\^(.+)|[xX]|) *");
for (int i = 0; i < split.size(); i++) {
String s = split.get(i);
Matcher negMatch = negCheck.matcher(s);
if (negMatch.matches()) {
if (!s.matches("^\\-?([0-9/])*[xX]\\^\\-([0-9/])+$")) {
split.set(split.indexOf(s), s.split("-", 2)[0]);
String temp = "-" + s.split("-", 2)[1];
split.add(temp);
}
}
}
RationalNumber[] coefficients = new RationalNumber[split.size()];
RationalNumber[] powers = new RationalNumber[split.size()];
for (int i = 0; i < split.size(); i++) {
String s = split.get(i);
Matcher termMatcher = termSplitter.matcher(s);
termMatcher.matches();
if (termMatcher.matches()) {
if (!s.contains("x")) {
powers[i] = RationalNumber.ZERO;
coefficients[i] = fractionConstructor(termMatcher.group(1));
} else if (s.equals("x")) {
coefficients[i] = RationalNumber.ONE;
powers[i] = RationalNumber.ONE;
} else if (s.equals("-x")) {
coefficients[i] = new RationalNumber("-1");
powers[i] = RationalNumber.ONE;
} else if (termMatcher.group(2) == null && termMatcher.group(3) == null) {
coefficients[i] = fractionConstructor(termMatcher.group(1));
powers[i] = RationalNumber.ZERO;
} else if (termMatcher.group(3) == null) {
coefficients[i] = fractionConstructor(termMatcher.group(1));
powers[i] = RationalNumber.ONE;
} else if (termMatcher.group(1) == null || termMatcher.group(1).length() == 0) {
coefficients[i] = RationalNumber.ONE;
powers[i] = fractionConstructor(termMatcher.group(3));
} else if (termMatcher.group(1).equals("-")) {
coefficients[i] = new RationalNumber("-1");
powers[i] = fractionConstructor(termMatcher.group(3));
} else {
coefficients[i] = fractionConstructor(termMatcher.group(1));
powers[i] = fractionConstructor(termMatcher.group(3));
}
}
}
this.coefficients = coefficients;
this.powers = powers;
}
private RationalNumber fractionConstructor(String s) {
Pattern check = Pattern.compile("(\\-?[0-9]+)/([0-9]+)");
Matcher match = check.matcher(s);
if (match.matches()) {
return new RationalNumber(match.group(1), match.group(2));
} else {
return new RationalNumber(s);
}
}
public RationalNumber[] getCoefficients() {
return this.coefficients;
}
public RationalNumber[] getPowers() {
return this.powers;
}
@Override
public String toString() {
StringBuilder result = new StringBuilder();
for (int i = 0; i < coefficients.length - 1; i++) {
if (!coefficients[i].equals(RationalNumber.ZERO)) {
if (!coefficients[i].equals(RationalNumber.ONE)) {
result.append(coefficients[i]);
}
if (!powers[i].equals(RationalNumber.ZERO)) {
result.append("x");
if (!powers[i].equals(RationalNumber.ONE)) {
result.append("^").append(powers[i]);
}
result.append("+");
}
}
}
if (!coefficients[coefficients.length - 1].equals(RationalNumber.ZERO)) {
result.append(coefficients[coefficients.length - 1]);
if (!powers[coefficients.length - 1].equals(RationalNumber.ZERO)) {
result.append("x");
if (!powers[coefficients.length - 1].equals(RationalNumber.ONE)) {
result.append("^").append(powers[coefficients.length - 1]);
}
}
}
if(result.length()==0){
return "0";
}
if (result.charAt(result.length() - 1) == '+') {
return result.substring(0, result.length() - 2);
}
return result.toString();
}
}
|
/*
* Copyright (c) 2013-2014, Neuro4j.org
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.neuro4j.studio.properties.descriptor;
import java.util.Arrays;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.emf.common.ui.celleditor.ExtendedDialogCellEditor;
import org.eclipse.jface.viewers.CellEditor;
import org.eclipse.jface.window.Window;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.views.properties.PropertyDescriptor;
import org.neuro4j.studio.core.views.dialogs.FlowResourcesSelectionDialog;
public class CallNodeFlowNamePropertyDescriptor extends PropertyDescriptor {
public CallNodeFlowNamePropertyDescriptor(Object id, String displayName) {
super(id, displayName);
}
@Override
public CellEditor createPropertyEditor(Composite parent) {
return new ExtendedDialogCellEditor(parent, getLabelProvider()) {
@Override
protected Object openDialogBox(Control cellEditorWindow) {
FlowResourcesSelectionDialog dialog = new FlowResourcesSelectionDialog(
PlatformUI.getWorkbench().getDisplay().getActiveShell(), false,
ResourcesPlugin.getWorkspace().getRoot(), IResource.FILE);
dialog.setTitle("Available flows");
dialog.setResourceFilter("n4j");
dialog.setPathFilter("/");
int result = dialog.open();
labelProvider.dispose();
return result == Window.OK ? Arrays.asList(dialog.getResult())
: null;
}
};
}
}
|
package com.needii.dashboard.model;
import javax.persistence.*;
/**
* The persistent class for the product_attributes database table.
*
*/
@Entity
@Table(name="product_city_maps")
@NamedQuery(name="ProductCityMap.findAll", query="SELECT p FROM ProductCityMap p")
public class ProductCityMap extends BaseModel {
private static final long serialVersionUID = 1L;
@Id
@Column(name="id")
@GeneratedValue(strategy=GenerationType.IDENTITY)
private long id;
@ManyToOne
@JoinColumn(name="product_id")
private Product product;
@OneToOne
@JoinColumn(name="city_id")
private City city;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public Product getProduct() {
return product;
}
public void setProduct(Product product) {
this.product = product;
}
public City getCity() {
return city;
}
public int getCityId() {
return city.getId();
}
public void setCity(City city) {
this.city = city;
}
}
|
package org.crazyit.app;
import android.app.Activity;
import android.app.LauncherActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
public class MainActivity extends LauncherActivity
{
//定义两个Activity的名称
String[] names = {"设置程序参数" , "查看星际兵种"};
//定义两个Activity对应的实现类
Class<?>[] clazzs = {PreferenceActivityTest.class
, ExpandableListActivityTest.class};
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1 , names);
// 设置该窗口显示的列表所需的Adapter
setListAdapter(adapter);
}
//根据列表项返回指定Activity对应的Intent
@Override
public Intent intentForPosition(int position)
{
return new Intent(MainActivity.this , clazzs[position]);
}
}
|
package org.webtop.module.polarization;
import org.webtop.component.WApplication;
import org.webtop.module.polarization.ControlPanel;
import javax.swing.JTabbedPane;
import javax.swing.event.*;
import javax.swing.*;
import java.util.HashMap;
import java.awt.Component;
import org.sdl.gui.numberbox.*;
import org.webtop.wsl.script.WSLNode;
import org.webtop.x3d.widget.*;
import org.webtop.x3d.*;
import org.web3d.x3d.sai.*;
import org.webtop.util.*;
import org.webtop.component.*;
import org.webtop.module.wavefront.Engine;
public class Polarization extends WApplication {
private Engine engine;
private Animation anim;
private SourcePanel sourcePanel;
private ControlPanel controlPanel;
private FilterPanel filterPanel;
static private Polarization polarization;
protected void setDefaults() {
}
protected void setupMenubar() {
}
protected Component getFirstFocus() {
return controlPanel;
}
protected String getAuthor() {
return "test";
}
protected String getDate() {
return "date";
}
protected int getMajorVersion() {return 6;}
protected int getMinorVersion() {return 1;}
protected int getRevision() {return 1;}
protected String getModuleName() { return "Polarization";}
//Initiate the X3D variables
protected void initX3D(String world, HashMap params) {
}
//Called by module to connect X3DFields, Widgets, etc.
protected void setupX3D() {
}
//Called by module to layout the user interface for the module.
protected void setupGUI() {
controlPanel = new ControlPanel(polarization);
filterPanel = new FilterPanel(polarization);
sourcePanel = new SourcePanel(polarization);
addToConsole(controlPanel);
addToConsole(filterPanel);
addToConsole(sourcePanel);
}
public static void main(String[] args)
{
polarization = new Polarization("Polarization", "Polarization.x3dv");
}
public Polarization(String title, String world)
{
super(title, world, true);
}
public void invalidEvent(String p1, String p2) {
}
public SourcePanel getSourcePanel() {return sourcePanel;}
public ControlPanel getControlPanel() {return controlPanel;}
public FilterPanel getFilterPanel() {return filterPanel;}
@Override
protected void toWSLNode(WSLNode node) {
// TODO Auto-generated method stub
}
public String getWSLModuleName() {
// TODO Auto-generated method stub
return null;
}
}
|
package cardGames;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Scanner;
public class SimpleBlackJack {
private static PlayerDatabase allPlayers = new PlayerDatabase();
private static PlayerDatabase currPlayers = new PlayerDatabase();
private static Player currPlayer = null;
private static BlackjackStack bj = null;
public static Scanner in = null;
private static int numDecks;
private static int minBet;
private static int maxBet;
private static char hitOn17;
public static void main(String[] args) {
loadDatabase();
loadSettings();
mainMenu();
updateData();
updateSettings();
in.close();
}
private static void loadSettings() {
String fileName = "Settings.txt";
File f = new File(fileName);
Scanner fileReader = null;
try {
fileReader = new Scanner(f);
numDecks = fileReader.nextInt();
minBet = fileReader.nextInt();
maxBet = fileReader.nextInt();
hitOn17 = fileReader.next().charAt(0);
} catch (FileNotFoundException e) {
e.printStackTrace();
System.exit(-1);
} finally {
fileReader.close();
}
}
private static void loadDatabase() {
String fileName = "BlackjackPlayerDB.txt";
File f = new File(fileName);
Scanner fileReader = null;
try {
fileReader = new Scanner(f);
while (fileReader.hasNext()) {
String name = fileReader.next();
char type = fileReader.next().charAt(0);
int funds = fileReader.nextInt();
int wins = fileReader.nextInt();
int losses = fileReader.nextInt();
int draws = fileReader.nextInt();
int moneyGained = fileReader.nextInt();
int moneyLost = fileReader.nextInt();
Player newPlayer = new Player(name, type, funds,
wins, losses, draws, moneyGained, moneyLost);
allPlayers.addPlayer(newPlayer);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
System.exit(-1);
} finally {
fileReader.close();
}
}
private static void mainMenu() {
boolean exit = false;
in = new Scanner(System.in);
while (!exit) {
System.out.println("\nb = begin game\nc = view current settings\ns = alter settings\nm = modify database\nd = display stats\nq = quit");
char command = in.next().charAt(0);
in.nextLine();
switch (command) {
case 'b': setUp(); break;
case 'c': viewCurrSettings();;break;
case 's': changeSettings(); break;
case 'm': Menues.changeDatabase(allPlayers); break;
case 'd': Menues.displayStats(allPlayers); break;
case 'q': exit = true; break;
}
}
}
private static void viewCurrSettings() {
System.out.println("\nNum. Decks = "+numDecks+"\nCurr Min. bet = "+minBet
+"\nCurr Max. bet = "+maxBet+"\nSoft/hard 17 = "+hitOn17+"\n");
}
private static void changeSettings() {
boolean exit = false;
while (!exit){
System.out.println("\n1 = alter number of decks\n2 = change min/max bet\n3 = change soft/hard 17"
+ "\n4 = view current settings\n5 = exit");
int response = in.nextInt();
switch (response) {
case 1:
int decks;
decks = Menues.setNumDecks();
numDecks = decks;
break;
case 2:
int [] minMax = new int[2];
minMax = Menues.setMinMaxBet();
minBet = minMax[0];
maxBet = minMax[1];
break;
case 3:
char type;
do {
System.out.print("Press s to make the dealer hit on a soft 17, press h to implement a hard 17: ");
type = in.next().charAt(0);
System.out.println("\n");
} while (type != 's' && type != 'h');
break;
case 4: viewCurrSettings(); break;
case 5: exit = true; break;
}
}
}
private static void setUp() {
currPlayers = Menues.setCurrPlayers(allPlayers);
createDeck();
startGame();
}
private static void createDeck() {
DeckADT <Card> deck = new DeckStack <Card> ();
for (int i = 0; i < numDecks; i++) {
deck.insert52();
}
try {
bj = new BlackjackStack(deck, currPlayers.getPlayers());
currPlayer = bj.startGame();
} catch (IllegalArgumentException e) {
System.out.println("\nWhen choosing a list of players, one and only one of them must be of type house\n");
currPlayers.getPlayers().clear();
setUp();
}
}
private static void startGame() {
simulateGame();
System.out.print("Want to play again? (Press y): ");
char command = in.next().charAt(0);
System.out.println();
if (command == 'y') {
createDeck();
startGame();
}
}
private static void makeBets() {
while (currPlayer.getType() != 'h') {
int bet = 0;
while (bet < minBet || bet > maxBet) {
System.out.print(currPlayer.getName()+", select an amount to bet. Min= "+minBet+", Max= "
+maxBet+": ");
bet = in.nextInt();
currPlayer.setCurrBet(bet);
System.out.println();
}
currPlayer = bj.changeTurn();
}
currPlayer = bj.changeTurn();
// returns current player as first player
}
private static void simulateGame() {
boolean exit = false;
boolean bust = false;
boolean hasHit = false;
currPlayer = currPlayers.getPlayers().get(0);
makeBets();
//Print all player hands and see first of house's cards
System.out.println("\n");
while (!exit) {
printGameInfo();
if (currPlayer.getType() == 'p') {
if (!currPlayer.hasDoubleDowned()) {
System.out.println("\nIt is "+currPlayer.getName()+"'s turn!\n");
System.out.println("\nCommands\nc = check hand\nh = hit\ns = stay\nd = "
+ "double down\nv = get hand value\nf = surrender (only on first turn)");
char command = in.next().charAt(0);
in.nextLine();
switch (command) {
// TODO: might add back when double down/splitting is implemented
case 'c': System.out.println(currPlayer.getHand()); break;
case 'h':
if (!hasHit) {
currPlayer.setFirstTurn(false); // if on first turn
hasHit = true;
bj.hit(currPlayer);
bust = bj.isBust();
if (bust) {
System.out.println(currPlayer.getName()+" busted!\n"+currPlayer.getHand()+"\n");
hasHit = false;
}
}
else {
System.out.println("You can only hit once per turn. Type 's' to end turn.\n");
}
break;
case 's':
hasHit = false;
int value = bj.countHandForValue(currPlayer.getHand());
currPlayer.setCardValue(value);
currPlayer.setFirstTurn(false);
currPlayer = bj.changeTurn();
break;
case 'd':
if (!hasHit && !currPlayer.hasDoubleDowned()) {
currPlayer.setFirstTurn(false); // if on first turn
currPlayer.makeDoubleDowned(true);
bj.hit(currPlayer);
int bet = currPlayer.getCurrBet();
// double original bets
currPlayer.setCurrBet(bet * 2);
bust = bj.isBust();
if (bust) {
System.out.println(currPlayer.getName()+" busted!\n"+currPlayer.getHand()+"\n");
hasHit = false;
currPlayer = bj.changeTurn();
}
else {
System.out.println(currPlayer.getHand());
}
int value1 = bj.countHandForValue(currPlayer.getHand());
currPlayer.setCardValue(value1);
currPlayer = bj.changeTurn();
}
else {
System.out.println("\nMove not valid.\n");
}
break;
case 'v': System.out.println(bj.countHandForValue(currPlayer.getHand())); break;
case 'f':
if (currPlayer.getFirstTurn()) {
hasHit = false;
currPlayer.makeBust(true);
int value2 = bj.countHandForValue(currPlayer.getHand());
currPlayer.setCardValue(value2);
int bet = currPlayer.getCurrBet();
// half original bet
currPlayer.setCurrBet(bet /2);
currPlayer = bj.changeTurn();
}
else {
System.out.println("\nMove not valid.\n");
}
break; //remove player from active game
}
}
else {
System.out.println("\n"+currPlayer.getName()+"'s turn is skipped because they double downed.");
currPlayer = bj.changeTurn();
}
}
else { // Determine if the game is over or not
System.out.println("\nIt is "+currPlayer.getName()+"'s turn!\n");
exit = endTurn();
}
}
for (Player p: currPlayers.getPlayers()) {
p.getHand().clear(); // remove cards from player
p.setCurrBet(0);
p.setCardValue(0);
p.setFirstTurn(true);
p.makeBust(false);
p.makeDoubleDowned(false);
p.makeWin(false);
}
}
private static void printGameInfo() {
for (int i = 0; i < currPlayers.getPlayers().size() - 1; i++) {
System.out.println(currPlayers.getPlayers().get(i));
}
System.out.println(currPlayers.getPlayers().get(currPlayers.getPlayers().size() - 1).getName()
+ ": ["+currPlayers.getPlayers().get(currPlayers.getPlayers().size() - 1).getHand().get(0)+", ??]\n");
}
private static boolean endTurn() {
boolean bustedPlayers = true;
for (Player p: currPlayers.getPlayers()) {
if (!p.hasBust() && p.getType() == 'p') {
bustedPlayers = false;
}
}
// if all players have busted
if (bustedPlayers){
//int value = bj.countHandForValue(curr.getHand());
//curr.setCardValue(value);
currPlayer.setCardValue(0);
bj.endGame();
return true;
}
else {
int value = bj.countHandForValue(currPlayer.getHand());
currPlayer.setCardValue(value);
//TODO: Implement soft 17 feature
boolean hit = false;
if (value == 17) {
if (hitOn17 == 's') {
for (Card e: currPlayer.getHand()){
if (e.getRank() == 1) {
hit = true;
break;
}
}
}
}
if (value >= 17 && !hit) {
System.out.println(currPlayer.getName()+" has hit to the appropriate amount.\n");
//TODO: would use isBust() but takes more lines
if (value > 21) {
System.out.println(currPlayer.getName()+" has bust!\n");
currPlayer.setCardValue(0);
currPlayer.makeBust(true);
}
// check all active player hands and end game
bj.endGame();
return true;
}
else {
bj.hit(currPlayer);
System.out.println(currPlayer.getName()+" hit!\n");
currPlayer = bj.changeTurn();
return false;
}
}
}
private static void updateData() {
String writeTo = "BlackjackPlayerDB.txt";
File f = new File(writeTo);
PrintWriter pw = null;
try {
pw = new PrintWriter(f);
for (Player p: allPlayers.getPlayers()) {
pw.println(p.getName()+" "+p.getType()+" "+p.getFunds()+" "+p.getWins()+" "
+p.getLosses()+" "+p.getDraws()+" "+p.getMoneyEarned()+" "+p.getMoneyLost());
}
} catch (FileNotFoundException g) {
g.printStackTrace();
System.exit(-1);
} finally {
pw.close();
}
}
private static void updateSettings() {
String writeTo = "Settings.txt";
File f = new File(writeTo);
PrintWriter pw = null;
try {
pw = new PrintWriter(f);
pw.println(numDecks);
pw.println(minBet);
pw.println(maxBet);
pw.println(hitOn17);
} catch (FileNotFoundException g) {
g.printStackTrace();
System.exit(-1);
} finally {
pw.close();
}
}
}
|
package cucumber.Options;
import org.junit.runner.RunWith;
import io.cucumber.junit.Cucumber;
import io.cucumber.junit.CucumberOptions;
@RunWith(Cucumber.class)
@CucumberOptions(features = {"src/test/java/features/validateAddPlaceAPI.feature"},
glue = {"stepDefinitions"},
plugin = "json:target/jsonReports/cucumber-reports.json")
public class TestRunner {
//,tags = "@deletePlaceAPI", tags = "@addPlaceAPI" , tags = "@RegressionTest"
}
|
package com.volvobuses.client.bean;
public class GenTbParametrica {
private String paraId;
private String categoria;
private String valor;
private String activo;
public String getParaId() {
return paraId;
}
public void setParaId(String paraId) {
this.paraId = paraId;
}
public String getCategoria() {
return categoria;
}
public void setCategoria(String categoria) {
this.categoria = categoria;
}
public String getValor() {
return valor;
}
public void setValor(String valor) {
this.valor = valor;
}
public String getActivo() {
return activo;
}
public void setActivo(String activo) {
this.activo = activo;
}
}
|
package menu;
import java.awt.Color;
import java.awt.Cursor;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
public class Button {
Menu menu;
int x;
int y;
int width;
int height;
Color color;
Color activeColor;
BufferedImage image = null;
int id;
String text;
Font font;
boolean active = false;
public Button(int id, int x, int y, int width, int height, Color color, String text, Menu menu) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
this.color = color;
int r = color.getRed() + 15;
int g = color.getGreen() + 15;
int b = color.getBlue() + 15;
if (r > 255) {
r = 255;
}
if (g > 255) {
g = 255;
}
if (b > 255) {
b = 255;
}
this.activeColor = new Color(r, g, b);
this.menu = menu;
this.id = id;
this.text = text;
this.font = new Font("Impact", Font.PLAIN, 28);
}
public Button(int id, int x, int y, BufferedImage image, Menu menu) {
this.x = x;
this.y = y;
this.width = image.getWidth();
this.height = image.getHeight();
this.image = image;
this.menu = menu;
this.id = id;
}
public void mouseClicked(Point p) {
if (p.getX() > x && p.getY() > y && p.getX() < x + width && p.getY() < y + height) {
menu.handler.getPanel().setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
menu.execute(id);
}
}
public boolean mouseMoved(Point p) {
if (p.getX() > x && p.getY() > y && p.getX() < x + width && p.getY() < y + height) {
active = true;
menu.handler.getPanel().setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
return true;
}
else {
active = false;
return false;
}
}
public void draw(Graphics g) {
if (image != null) {
g.drawImage(image, x, y, null);
} else {
if (active) {
g.setColor(activeColor);
} else {
g.setColor(color);
}
g.fillRoundRect(x, y, width, height, 10, 10);
g.setColor(Color.BLACK);
g.drawRoundRect(x, y, width, height, 10, 10);
g.setFont(font);
FontMetrics fm = g.getFontMetrics();
g.setColor(Color.WHITE);
Graphics2D g2d = (Graphics2D) g;
g2d.setRenderingHint(
RenderingHints.KEY_TEXT_ANTIALIASING,
RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
g2d.drawString(this.text, (int)(this.x + this.width / 2 - fm.stringWidth(text) / 2), (int)(this.y + this.height / 2 + (fm.getAscent() / 2.7)));
}
}
public void setFont(Font font) {
this.font = font;
}
}
|
/**
* This class is generated by jOOQ
*/
package schema.tables.records;
import java.sql.Timestamp;
import javax.annotation.Generated;
import org.jooq.Field;
import org.jooq.Record1;
import org.jooq.Record11;
import org.jooq.Row11;
import org.jooq.impl.UpdatableRecordImpl;
import schema.tables.ApiAdminApiaccessrequest;
/**
* This class is generated by jOOQ.
*/
@Generated(
value = {
"http://www.jooq.org",
"jOOQ version:3.8.4"
},
comments = "This class is generated by jOOQ"
)
@SuppressWarnings({ "all", "unchecked", "rawtypes" })
public class ApiAdminApiaccessrequestRecord extends UpdatableRecordImpl<ApiAdminApiaccessrequestRecord> implements Record11<Integer, Timestamp, Timestamp, String, String, String, Integer, String, String, Byte, Integer> {
private static final long serialVersionUID = 93257204;
/**
* Setter for <code>bitnami_edx.api_admin_apiaccessrequest.id</code>.
*/
public void setId(Integer value) {
set(0, value);
}
/**
* Getter for <code>bitnami_edx.api_admin_apiaccessrequest.id</code>.
*/
public Integer getId() {
return (Integer) get(0);
}
/**
* Setter for <code>bitnami_edx.api_admin_apiaccessrequest.created</code>.
*/
public void setCreated(Timestamp value) {
set(1, value);
}
/**
* Getter for <code>bitnami_edx.api_admin_apiaccessrequest.created</code>.
*/
public Timestamp getCreated() {
return (Timestamp) get(1);
}
/**
* Setter for <code>bitnami_edx.api_admin_apiaccessrequest.modified</code>.
*/
public void setModified(Timestamp value) {
set(2, value);
}
/**
* Getter for <code>bitnami_edx.api_admin_apiaccessrequest.modified</code>.
*/
public Timestamp getModified() {
return (Timestamp) get(2);
}
/**
* Setter for <code>bitnami_edx.api_admin_apiaccessrequest.status</code>.
*/
public void setStatus(String value) {
set(3, value);
}
/**
* Getter for <code>bitnami_edx.api_admin_apiaccessrequest.status</code>.
*/
public String getStatus() {
return (String) get(3);
}
/**
* Setter for <code>bitnami_edx.api_admin_apiaccessrequest.website</code>.
*/
public void setWebsite(String value) {
set(4, value);
}
/**
* Getter for <code>bitnami_edx.api_admin_apiaccessrequest.website</code>.
*/
public String getWebsite() {
return (String) get(4);
}
/**
* Setter for <code>bitnami_edx.api_admin_apiaccessrequest.reason</code>.
*/
public void setReason(String value) {
set(5, value);
}
/**
* Getter for <code>bitnami_edx.api_admin_apiaccessrequest.reason</code>.
*/
public String getReason() {
return (String) get(5);
}
/**
* Setter for <code>bitnami_edx.api_admin_apiaccessrequest.user_id</code>.
*/
public void setUserId(Integer value) {
set(6, value);
}
/**
* Getter for <code>bitnami_edx.api_admin_apiaccessrequest.user_id</code>.
*/
public Integer getUserId() {
return (Integer) get(6);
}
/**
* Setter for <code>bitnami_edx.api_admin_apiaccessrequest.company_address</code>.
*/
public void setCompanyAddress(String value) {
set(7, value);
}
/**
* Getter for <code>bitnami_edx.api_admin_apiaccessrequest.company_address</code>.
*/
public String getCompanyAddress() {
return (String) get(7);
}
/**
* Setter for <code>bitnami_edx.api_admin_apiaccessrequest.company_name</code>.
*/
public void setCompanyName(String value) {
set(8, value);
}
/**
* Getter for <code>bitnami_edx.api_admin_apiaccessrequest.company_name</code>.
*/
public String getCompanyName() {
return (String) get(8);
}
/**
* Setter for <code>bitnami_edx.api_admin_apiaccessrequest.contacted</code>.
*/
public void setContacted(Byte value) {
set(9, value);
}
/**
* Getter for <code>bitnami_edx.api_admin_apiaccessrequest.contacted</code>.
*/
public Byte getContacted() {
return (Byte) get(9);
}
/**
* Setter for <code>bitnami_edx.api_admin_apiaccessrequest.site_id</code>.
*/
public void setSiteId(Integer value) {
set(10, value);
}
/**
* Getter for <code>bitnami_edx.api_admin_apiaccessrequest.site_id</code>.
*/
public Integer getSiteId() {
return (Integer) get(10);
}
// -------------------------------------------------------------------------
// Primary key information
// -------------------------------------------------------------------------
/**
* {@inheritDoc}
*/
@Override
public Record1<Integer> key() {
return (Record1) super.key();
}
// -------------------------------------------------------------------------
// Record11 type implementation
// -------------------------------------------------------------------------
/**
* {@inheritDoc}
*/
@Override
public Row11<Integer, Timestamp, Timestamp, String, String, String, Integer, String, String, Byte, Integer> fieldsRow() {
return (Row11) super.fieldsRow();
}
/**
* {@inheritDoc}
*/
@Override
public Row11<Integer, Timestamp, Timestamp, String, String, String, Integer, String, String, Byte, Integer> valuesRow() {
return (Row11) super.valuesRow();
}
/**
* {@inheritDoc}
*/
@Override
public Field<Integer> field1() {
return ApiAdminApiaccessrequest.API_ADMIN_APIACCESSREQUEST.ID;
}
/**
* {@inheritDoc}
*/
@Override
public Field<Timestamp> field2() {
return ApiAdminApiaccessrequest.API_ADMIN_APIACCESSREQUEST.CREATED;
}
/**
* {@inheritDoc}
*/
@Override
public Field<Timestamp> field3() {
return ApiAdminApiaccessrequest.API_ADMIN_APIACCESSREQUEST.MODIFIED;
}
/**
* {@inheritDoc}
*/
@Override
public Field<String> field4() {
return ApiAdminApiaccessrequest.API_ADMIN_APIACCESSREQUEST.STATUS;
}
/**
* {@inheritDoc}
*/
@Override
public Field<String> field5() {
return ApiAdminApiaccessrequest.API_ADMIN_APIACCESSREQUEST.WEBSITE;
}
/**
* {@inheritDoc}
*/
@Override
public Field<String> field6() {
return ApiAdminApiaccessrequest.API_ADMIN_APIACCESSREQUEST.REASON;
}
/**
* {@inheritDoc}
*/
@Override
public Field<Integer> field7() {
return ApiAdminApiaccessrequest.API_ADMIN_APIACCESSREQUEST.USER_ID;
}
/**
* {@inheritDoc}
*/
@Override
public Field<String> field8() {
return ApiAdminApiaccessrequest.API_ADMIN_APIACCESSREQUEST.COMPANY_ADDRESS;
}
/**
* {@inheritDoc}
*/
@Override
public Field<String> field9() {
return ApiAdminApiaccessrequest.API_ADMIN_APIACCESSREQUEST.COMPANY_NAME;
}
/**
* {@inheritDoc}
*/
@Override
public Field<Byte> field10() {
return ApiAdminApiaccessrequest.API_ADMIN_APIACCESSREQUEST.CONTACTED;
}
/**
* {@inheritDoc}
*/
@Override
public Field<Integer> field11() {
return ApiAdminApiaccessrequest.API_ADMIN_APIACCESSREQUEST.SITE_ID;
}
/**
* {@inheritDoc}
*/
@Override
public Integer value1() {
return getId();
}
/**
* {@inheritDoc}
*/
@Override
public Timestamp value2() {
return getCreated();
}
/**
* {@inheritDoc}
*/
@Override
public Timestamp value3() {
return getModified();
}
/**
* {@inheritDoc}
*/
@Override
public String value4() {
return getStatus();
}
/**
* {@inheritDoc}
*/
@Override
public String value5() {
return getWebsite();
}
/**
* {@inheritDoc}
*/
@Override
public String value6() {
return getReason();
}
/**
* {@inheritDoc}
*/
@Override
public Integer value7() {
return getUserId();
}
/**
* {@inheritDoc}
*/
@Override
public String value8() {
return getCompanyAddress();
}
/**
* {@inheritDoc}
*/
@Override
public String value9() {
return getCompanyName();
}
/**
* {@inheritDoc}
*/
@Override
public Byte value10() {
return getContacted();
}
/**
* {@inheritDoc}
*/
@Override
public Integer value11() {
return getSiteId();
}
/**
* {@inheritDoc}
*/
@Override
public ApiAdminApiaccessrequestRecord value1(Integer value) {
setId(value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public ApiAdminApiaccessrequestRecord value2(Timestamp value) {
setCreated(value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public ApiAdminApiaccessrequestRecord value3(Timestamp value) {
setModified(value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public ApiAdminApiaccessrequestRecord value4(String value) {
setStatus(value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public ApiAdminApiaccessrequestRecord value5(String value) {
setWebsite(value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public ApiAdminApiaccessrequestRecord value6(String value) {
setReason(value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public ApiAdminApiaccessrequestRecord value7(Integer value) {
setUserId(value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public ApiAdminApiaccessrequestRecord value8(String value) {
setCompanyAddress(value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public ApiAdminApiaccessrequestRecord value9(String value) {
setCompanyName(value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public ApiAdminApiaccessrequestRecord value10(Byte value) {
setContacted(value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public ApiAdminApiaccessrequestRecord value11(Integer value) {
setSiteId(value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public ApiAdminApiaccessrequestRecord values(Integer value1, Timestamp value2, Timestamp value3, String value4, String value5, String value6, Integer value7, String value8, String value9, Byte value10, Integer value11) {
value1(value1);
value2(value2);
value3(value3);
value4(value4);
value5(value5);
value6(value6);
value7(value7);
value8(value8);
value9(value9);
value10(value10);
value11(value11);
return this;
}
// -------------------------------------------------------------------------
// Constructors
// -------------------------------------------------------------------------
/**
* Create a detached ApiAdminApiaccessrequestRecord
*/
public ApiAdminApiaccessrequestRecord() {
super(ApiAdminApiaccessrequest.API_ADMIN_APIACCESSREQUEST);
}
/**
* Create a detached, initialised ApiAdminApiaccessrequestRecord
*/
public ApiAdminApiaccessrequestRecord(Integer id, Timestamp created, Timestamp modified, String status, String website, String reason, Integer userId, String companyAddress, String companyName, Byte contacted, Integer siteId) {
super(ApiAdminApiaccessrequest.API_ADMIN_APIACCESSREQUEST);
set(0, id);
set(1, created);
set(2, modified);
set(3, status);
set(4, website);
set(5, reason);
set(6, userId);
set(7, companyAddress);
set(8, companyName);
set(9, contacted);
set(10, siteId);
}
}
|
package com.youngtech.fabartists.ui.adapter;
import android.content.Context;
import android.content.DialogInterface;
import android.databinding.DataBindingUtil;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.youngtech.fabartists.DTO.ArtistBooking;
import com.youngtech.fabartists.DTO.UserDTO;
import com.youngtech.fabartists.R;
import com.youngtech.fabartists.databinding.AdapterAllBookingsBinding;
import com.youngtech.fabartists.https.HttpsRequest;
import com.youngtech.fabartists.interfacess.Consts;
import com.youngtech.fabartists.interfacess.Helper;
import com.youngtech.fabartists.network.NetworkManager;
import com.youngtech.fabartists.ui.fragment.NewBookings;
import com.youngtech.fabartists.utils.CustomTextView;
import com.youngtech.fabartists.utils.ProjectUtils;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
public class AdapterAllBookings extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private String TAG = AdapterAllBookings.class.getSimpleName();
private NewBookings newBookings;
private ArrayList<ArtistBooking> artistBookingsList;
private UserDTO userDTO;
private LayoutInflater myInflater;
private Context context;
private HashMap<String, String> paramsBookingOp;
private HashMap<String, String> paramsDecline;
private final int VIEW_ITEM = 1;
private final int VIEW_SECTION = 0;
public AdapterAllBookings(NewBookings newBookings, ArrayList<ArtistBooking> artistBookingsList, UserDTO userDTO, LayoutInflater myInflater) {
this.newBookings = newBookings;
this.artistBookingsList = artistBookingsList;
this.userDTO = userDTO;
this.myInflater = myInflater;
context = newBookings.getActivity();
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup viewGroup, final int viewType) {
RecyclerView.ViewHolder vh;
if (myInflater == null) {
myInflater = LayoutInflater.from(viewGroup.getContext());
}
if (viewType == VIEW_ITEM) {
AdapterAllBookingsBinding binding =
DataBindingUtil.inflate(myInflater, R.layout.adapter_all_bookings, viewGroup, false);
vh = new MyViewHolder(binding);
} else {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item_section, viewGroup, false);
vh = new MyViewHolderSection(v);
}
return vh;
}
@Override
public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holderMain, final int position) {
if (holderMain instanceof MyViewHolder) {
MyViewHolder holder = (MyViewHolder) holderMain;
holder.binding.tvName.setText(artistBookingsList.get(position).getUserName());
holder.binding.tvLocation.setText(artistBookingsList.get(position).getAddress());
holder.binding.tvDate.setText(ProjectUtils.changeDateFormate1(artistBookingsList.get(position).getBooking_date())+" "+artistBookingsList.get(position).getBooking_time());
Glide.with(context).
load(artistBookingsList.get(position).getUserImage())
.placeholder(R.drawable.dummyuser_image)
.dontAnimate()
.diskCacheStrategy(DiskCacheStrategy.ALL)
.into(holder.binding.ivArtist);
holder.binding.tvDescription.setText(artistBookingsList.get(position).getDescription());
if (artistBookingsList.get(position).getBooking_type().equalsIgnoreCase("0") || artistBookingsList.get(position).getBooking_type().equalsIgnoreCase("3")) {
if (artistBookingsList.get(position).getBooking_flag().equalsIgnoreCase("0")) {
holder.binding.llACDE.setVisibility(View.VISIBLE);
holder.binding.llSt.setVisibility(View.GONE);
holder.binding.tvCompleted.setVisibility(View.GONE);
holder.binding.tvRejected.setVisibility(View.GONE);
} else if (artistBookingsList.get(position).getBooking_flag().equalsIgnoreCase("1")) {
holder.binding.llSt.setVisibility(View.VISIBLE);
holder.binding.llACDE.setVisibility(View.GONE);
holder.binding.tvCompleted.setVisibility(View.GONE);
holder.binding.tvRejected.setVisibility(View.GONE);
} else if (artistBookingsList.get(position).getBooking_flag().equalsIgnoreCase("2")) {
holder.binding.llSt.setVisibility(View.GONE);
holder.binding.llACDE.setVisibility(View.GONE);
holder.binding.tvCompleted.setVisibility(View.GONE);
holder.binding.tvRejected.setVisibility(View.VISIBLE);
} else if (artistBookingsList.get(position).getBooking_flag().equalsIgnoreCase("4")) {
holder.binding.llSt.setVisibility(View.GONE);
holder.binding.llACDE.setVisibility(View.GONE);
holder.binding.tvCompleted.setVisibility(View.VISIBLE);
holder.binding.tvRejected.setVisibility(View.GONE);
}
} else if (artistBookingsList.get(position).getBooking_type().equalsIgnoreCase("2")) {
if (artistBookingsList.get(position).getBooking_flag().equalsIgnoreCase("0")) {
holder.binding.llACDE.setVisibility(View.VISIBLE);
holder.binding.llSt.setVisibility(View.GONE);
holder.binding.tvCompleted.setVisibility(View.GONE);
holder.binding.tvRejected.setVisibility(View.GONE);
} else if (artistBookingsList.get(position).getBooking_flag().equalsIgnoreCase("1")) {
holder.binding.llSt.setVisibility(View.VISIBLE);
holder.binding.llACDE.setVisibility(View.GONE);
holder.binding.tvCompleted.setVisibility(View.GONE);
holder.binding.tvRejected.setVisibility(View.GONE);
} else if (artistBookingsList.get(position).getBooking_flag().equalsIgnoreCase("2")) {
holder.binding.llSt.setVisibility(View.GONE);
holder.binding.llACDE.setVisibility(View.GONE);
holder.binding.tvCompleted.setVisibility(View.GONE);
holder.binding.tvRejected.setVisibility(View.VISIBLE);
} else if (artistBookingsList.get(position).getBooking_flag().equalsIgnoreCase("4")) {
holder.binding.llSt.setVisibility(View.GONE);
holder.binding.llACDE.setVisibility(View.GONE);
holder.binding.tvCompleted.setVisibility(View.VISIBLE);
holder.binding.tvRejected.setVisibility(View.GONE);
}
}
holder.binding.llAccept.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (NetworkManager.isConnectToInternet(context)) {
booking("1", position);
} else {
ProjectUtils.showToast(context, context.getResources().getString(R.string.internet_concation));
}
}
});
holder.binding.llDecline.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
ProjectUtils.showDialog(context, context.getResources().getString(R.string.dec_cpas), context.getResources().getString(R.string.decline_msg), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
decline(position);
}
}, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
}, false);
}
});
holder.binding.llStart.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (NetworkManager.isConnectToInternet(context)) {
booking("2", position);
} else {
ProjectUtils.showToast(context, context.getResources().getString(R.string.internet_concation));
}
}
});
holder.binding.llCancel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
ProjectUtils.showDialog(context, context.getResources().getString(R.string.dec_cpas), context.getResources().getString(R.string.decline_msg), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
decline(position);
}
}, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
}, false);
}
});
} else {
MyViewHolderSection view = (MyViewHolderSection) holderMain;
view.tvSection.setText(artistBookingsList.get(position).getSection_name());
}
}
@Override
public int getItemViewType(int position) {
return this.artistBookingsList.get(position).isSection() ? VIEW_SECTION : VIEW_ITEM;
}
@Override
public int getItemCount() {
return artistBookingsList.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
AdapterAllBookingsBinding binding;
public MyViewHolder(AdapterAllBookingsBinding binding) {
super(binding.getRoot());
this.binding = binding;
}
}
public void booking(String req, int pos) {
paramsBookingOp = new HashMap<>();
paramsBookingOp.put(Consts.BOOKING_ID, artistBookingsList.get(pos).getId());
paramsBookingOp.put(Consts.REQUEST, req);
paramsBookingOp.put(Consts.USER_ID, artistBookingsList.get(pos).getUser_id());
ProjectUtils.showProgressDialog(context, true, context.getResources().getString(R.string.please_wait));
new HttpsRequest(Consts.BOOKING_OPERATION_API, paramsBookingOp, context).stringPost(TAG, new Helper() {
@Override
public void backResponse(boolean flag, String msg, JSONObject response) {
ProjectUtils.pauseProgressDialog();
if (flag) {
ProjectUtils.showToast(context, msg);
newBookings.getBookings();
} else {
ProjectUtils.showToast(context, msg);
}
}
});
}
public void decline(int pos) {
paramsDecline = new HashMap<>();
paramsDecline.put(Consts.USER_ID, userDTO.getUser_id());
paramsDecline.put(Consts.BOOKING_ID, artistBookingsList.get(pos).getId());
paramsDecline.put(Consts.DECLINE_BY, "1");
paramsDecline.put(Consts.DECLINE_REASON, "Busy");
ProjectUtils.showProgressDialog(context, true, context.getResources().getString(R.string.please_wait));
new HttpsRequest(Consts.DECLINE_BOOKING_API, paramsDecline, context).stringPost(TAG, new Helper() {
@Override
public void backResponse(boolean flag, String msg, JSONObject response) {
ProjectUtils.pauseProgressDialog();
if (flag) {
ProjectUtils.showToast(context, msg);
newBookings.getBookings();
} else {
ProjectUtils.showToast(context, msg);
}
}
});
}
public static class MyViewHolderSection extends RecyclerView.ViewHolder {
public CustomTextView tvSection;
public MyViewHolderSection(View view) {
super(view);
tvSection = view.findViewById(R.id.tvSection);
}
}
}
|
package application.controller;
import application.apiInt.Equip;
import application.domain.Equipment;
import application.repository.Repository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.RestController;
import javax.jws.WebService;
import java.util.Date;
import java.util.List;
@RestController
@RequestMapping(path="/equip")
public class EquipImpl implements Equip {
@Autowired
private Repository repository;
@Override
@PostMapping("/add")
public Equipment addEquip(@RequestParam String name, @RequestParam String producer, @RequestParam Date date_produce) {
Equipment equipment = new Equipment(name, producer, date_produce);
repository.equipmentRepository.save(equipment);
return equipment;
}
@Override
@GetMapping("/select/{eqpId}")
public Equipment selectEquip(@RequestParam Long eqpId) {
Equipment equipment = repository.equipmentRepository.findById(eqpId).get();
return equipment;
}
@Override
@PostMapping("/update")
public Equipment updateEquip(@RequestParam Long eqpId, @RequestParam String name, @RequestParam String producer,@RequestParam Date date_produce) {
Equipment equipment = repository.equipmentRepository.findById(eqpId).get();
equipment.setName(name);
equipment.setProducer(producer);
equipment.setDate_produce(date_produce);
repository.equipmentRepository.save(equipment);
return equipment;
}
@Override
@GetMapping("/list")
public List<Equipment> selectListEquip() {
List<Equipment> equipmentList = (List) repository.equipmentRepository.findAll();
return equipmentList;
}
@Override
@GetMapping("/delete/{eqpId}")
public String deleteEquip(Long eqpId) {
repository.equipmentRepository.delete(repository.equipmentRepository.findById(eqpId).get());
return "Equipment is delete!";
}
@Override
@GetMapping("/equipStatus")
public List<Equipment> selectListStatusEquip(String status) {
List<Equipment> equipmentList = repository.equipmentRepository.findByStatus(status);
return equipmentList;
}
@Override
@GetMapping("/workequip")
public String workEquip(Long eqpId) {
Equipment equipment = repository.equipmentRepository.findById(eqpId).get();
equipment.setStatus("Work!");
return "Status is work!";
}
}
|
package cl.bwukkit.utils;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.entity.Player;
public class ChatUtils {
public static void sm(Player p, String msg){
p.sendMessage(prefix()+msg);
}
@SuppressWarnings("deprecation")
public static void bc(String msg){
for(Player p: Bukkit.getOnlinePlayers()){
p.sendMessage(prefix()+msg);
}
}
public static String prefix(){
return ChatColor.GRAY+"["+ChatColor.DARK_GREEN+"Random"+ChatColor.YELLOW+"Location"+ChatColor.GRAY+"] " + ChatColor.BLUE+"";
}
}
|
import java.util.Scanner;
import java.lang.Math;
public class Lesson_17_Activity_Two {
public static void main (String[]args){
Scanner scan = new Scanner (System.in);
System.out.println("Enter two numbers: ");
int a = scan.nextInt();
int b = scan.nextInt();
while (b >= a) {
if ((a % 2) == 0) {
System.out.print (" " + a);
}
a++;
}
}
}
|
package com.example.weizixun.common;
public interface Constants {
//全局日志拦截器开关,只有debug模式才开启,上线以后关闭日志拦截器,为false
boolean IS_DEBUG=true;
String CACHE_NAME="cache";
}
|
package com.example.gerenciamentodesalas.ui.activity;
import android.app.DatePickerDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.CalendarView;
import android.widget.DatePicker;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import com.example.gerenciamentodesalas.R;
import com.example.gerenciamentodesalas.TinyDB;
import com.example.gerenciamentodesalas.model.Sala;
import com.example.gerenciamentodesalas.model.Usuario;
import com.google.android.material.navigation.NavigationView;
import org.joda.time.LocalDateTime;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class CalendarioAgendamentoActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
private DrawerLayout drawer;
private DatePicker calendario;
private DatePickerDialog.OnDateSetListener pegarData;
int ano, mes, dia;
private static final String TAG = "CalendarioActivity";
private String dataEscolhidaRaw;
TinyDB tinyDB;
AlertDialog.Builder builder;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_calendario_agendamento);
tinyDB = new TinyDB(getApplicationContext());
final SimpleDateFormat formatoData = new SimpleDateFormat("yyyy-MM-dd");
final SimpleDateFormat formatoLocalData = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
final SimpleDateFormat formatoBrData = new SimpleDateFormat("dd/MM/yyyy");
final TextView textViewData= findViewById(R.id.textViewData);
LocalDateTime dataAgoraRaw = LocalDateTime.now();
try {
Date dataAgora = formatoLocalData.parse(dataAgoraRaw.toString());
dataEscolhidaRaw = formatoData.format(dataAgora);
textViewData.setText(formatoBrData.format(dataAgora));
} catch (ParseException e) {
e.printStackTrace();
}
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
drawer = findViewById(R.id.drawer_layout);
NavigationView navigationView = findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
navigationView.setNavigationItemSelectedListener(this);
View headerView = navigationView.getHeaderView(0);
TextView navNome = headerView.findViewById(R.id.nav_usuario);
TextView navOrg = headerView.findViewById(R.id.nav_org);
TextView navEmail = headerView.findViewById(R.id.nav_email);
navNome.setText(tinyDB.getObject("usuario", Usuario.class).getNome());
navOrg.setText(tinyDB.getObject("usuario", Usuario.class).getIdOrganizacao().getNome());
navEmail.setText(tinyDB.getObject("usuario", Usuario.class).getEmail());
Button btn = findViewById(R.id.btn);
calendario = findViewById(R.id.calendario);
final TextView textViewSala = findViewById(R.id.textViewSala);
Intent intent = getIntent();
textViewSala.setText(tinyDB.getObject("salaEscolhida", Sala.class).getNome());
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (! textViewData.getText().equals("DD/MM/AAAA")) {
int dayOfMonth = calendario.getDayOfMonth();
int month = calendario.getMonth();
int year = calendario.getYear();
String dataRaw;
String dataString;
dataRaw = dayOfMonth + "/" + month + "/" + year;
String parts[] = dataRaw.split("/");
month++;
int dia = Integer.parseInt(parts[0]);
int mes = Integer.parseInt(parts[1]);
int ano = Integer.parseInt(parts[2]);
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.YEAR, ano);
calendar.set(Calendar.MONTH, mes);
calendar.set(Calendar.DAY_OF_MONTH, dia);
String dataEscolhida;
dataEscolhida = formatoBrData.format(calendar.getTime());
Intent intent = new Intent(CalendarioAgendamentoActivity.this, AgendamentoActivity.class);
tinyDB.putString("dataEscolhida", dataEscolhida);
CalendarioAgendamentoActivity.this.startActivity(intent);
}
else {
builder = new AlertDialog.Builder(CalendarioAgendamentoActivity.this);
builder.setMessage("Por favor selecione uma data.").setTitle("Data não específicada.");
builder.setNeutralButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
}
});
AlertDialog dialog = builder.create();
dialog.show();
}
}
});
}
@Override
public boolean onNavigationItemSelected (@NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.nav_logout:
tinyDB.clear();
Intent intent = new Intent(CalendarioAgendamentoActivity.this, LoginActivity.class);
CalendarioAgendamentoActivity.this.startActivity(intent);
}
return true;
}
@Override
public void onBackPressed() {
if(drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
}
else
super.onBackPressed();
}
}
|
package Ex1;
public class Trapezio extends Poligono {
private double area;
private double perimetro;
public Trapezio (String nome, double base, double altura, double basemenor) {
super(nome,base,altura);
this.area = ((base + basemenor) * altura) / 2;
this.perimetro = base + basemenor + (2 * altura);
}
@Override
public double perimetro() {
return perimetro;
}
@Override
public double area() {
// TODO Auto-generated method stub
return area;
}
}
|
package hu.logout.example.divinity.phone.fragments;
import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import hu.logout.example.divinity.phone.R;
import hu.logout.example.divinity.phone.recycleview.ContactsAdapter;
/**
* Fragment that holds the RecyclerView
*/
public class Contacts2Fragment extends Fragment {
private static final int PERMISSIONS_REQUEST_READ_CONTACTS = 1;
private RecyclerView mContactListView;
public Contacts2Fragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the fragment layout
View root = inflater.inflate(R.layout.contacts_list, container, false);
mContactListView = root.findViewById(R.id.contact_list);
requestContacts();
return root;
}
private void requestContacts() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && getActivity().checkSelfPermission(Manifest.permission.READ_CONTACTS) == PackageManager.PERMISSION_GRANTED) {
mContactListView.setAdapter(new ContactsAdapter(getActivity()));
mContactListView.setLayoutManager(new LinearLayoutManager(getActivity()));
mContactListView.setItemAnimator(new DefaultItemAnimator());
} else {
requestPermissions(new String[]{Manifest.permission.READ_CONTACTS}, PERMISSIONS_REQUEST_READ_CONTACTS);
}
}
}
|
public class ContaPoupanca extends Conta{
protected void atualiza(double taxa) {
this.saldo -= (taxa*3);
}
}
|
package codingexercises;
public class SpeedConverter {
/* Write a method toMilesPerHour that has parameter
* double kilometersPerHour. Return rounded value of calculation
* as type long. If kph is less than 0, return -1. If positive,
* calculate mph and round it and return it.
* 1 mph = 1.609 kph
*/
public static void main(String[] args) {
toMilesPerHour(85.00);
System.out.println(toMilesPerHour(70.00));
printConversion(70.00);
}
public static long toMilesPerHour(double kilometersPerHour) {
if (kilometersPerHour < 0) {
return -1;
} else {
// double conversion = (1/1.609) * kilometersPerHour;
// long rounded = Math.round(conversion);
// return rounded;
long milesPerHour = Math.round(kilometersPerHour/1.609);
return milesPerHour;
}
}
public static void printConversion(double kilometersPerHour) {
if (kilometersPerHour < 0) {
System.out.println("Invalid Value");
} else {
System.out.println(kilometersPerHour + " km/h = " +
toMilesPerHour(kilometersPerHour) + " mi/h");
}
}
}
|
package src.principal;
import java.util.Scanner;
import src.tablero.*;
public class Damas {
private static Scanner scanner = new Scanner(System.in);
private static String readString(String mensaje){
String res = "";
boolean lecturaCorrecta = false;
while(!lecturaCorrecta){
System.out.print(mensaje + " ");
res = scanner.nextLine();
res = res.trim();
if (res.length()>0){
lecturaCorrecta = true;
}
else{
System.out.println("Debe ingresar al menos un caracter para continuar.");
}
}
return res;
}
private static int readInt(String mensaje, boolean soloPositivo){
int res = 0 ;
String lectura = "";
boolean lecturaCorrecta = false;
while(!lecturaCorrecta){
System.out.print(mensaje+" ");
lectura = scanner.nextLine();
try {
res = Integer.valueOf(lectura);
lecturaCorrecta = true;
if (soloPositivo && res<0){
lecturaCorrecta = false;
System.out.println("Debe ingresar un número positivo. ");
}
} catch (Exception e) {
lecturaCorrecta = false;
}
}
return res;
}
Tablero tablero ;
public Damas(){
tablero = new Tablero(8, 8,true);
}
public void jugar(){
turno(true);
turno(false);
turno(true);
turno(false);
turno(true);
turno(false);
turno(true);
turno(false);
}
private void turno(boolean esBlanca){
Ficha fichaAMover = null;
Coordenada[] coordenadasPosibles = null;
String advertencia = "";
while (fichaAMover== null) {
tablero.pintarTablero();
System.out.println(advertencia);
advertencia = "";
System.out.println("TURNO DE LAS "+((esBlanca)?"BLANCAS":"NEGRAS"));
fichaAMover = tablero.getFicha(Damas.readString("Seleccione la ficha que desea mover "), esBlanca);
if (fichaAMover == null){
advertencia +="Debe seleccionar una ficha valida";
}
else{
coordenadasPosibles = fichaAMover.getMovimientosPosibles();
if (coordenadasPosibles!=null){
String mensaje = "\nCoordenadas posibles para la ficha seleccionada: \n";
int cantidadPosibilidades = 0;
int i = 0;
while (coordenadasPosibles[i]!=null) {
if (coordenadasPosibles[i] != null) {
mensaje+= i+") "+coordenadasPosibles[i].toString()+"\n";
cantidadPosibilidades++;
}
i++;
}
mensaje += "\nSeleccione la coordenada a la que desea moverse: ";
int seleccion = -1;
while ((seleccion < 0)||(seleccion >= cantidadPosibilidades)){
seleccion = Damas.readInt(mensaje, true);
}
tablero.moverFicha(fichaAMover, coordenadasPosibles[seleccion]);
}
else{
advertencia += "La ficha "+fichaAMover.getId()+" que selecciono no tiene movimientos posibles";
fichaAMover = null;
}
}
}
}
}
|
package TST_teamproject.main.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import TST_teamproject.main.dao.MainMapper;
import TST_teamproject.main.model.MainVo;
@Service
public class MainServiceImp implements MainService {
@Autowired
private MainMapper mapper;
@Override
public List<MainVo> test() {
return mapper.test();
}
}
|
package com.zensar.controllers;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.zensar.entites.Product;
import com.zensar.services.ProductService;
@RestController
public class ProductController {
@Autowired
ProductService impl;
@RequestMapping(value = "/products", produces = { MediaType.APPLICATION_XML_VALUE,
MediaType.APPLICATION_JSON_VALUE }, method = RequestMethod.GET)
public Iterable<Product> getAllProducts() {
return impl.getAllProducts();
}
@RequestMapping("/products/{productId}")
public Product getProduct(@PathVariable(value = "productId", required = false) int productId) {
return impl.getProduct(productId);
}
@RequestMapping(value = "/products", method = RequestMethod.POST)
public void insertProduct(@RequestBody Product product) {
impl.insertProduct(product);
}
}
|
package com.atguigu.test;
import static org.junit.Assert.*;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.atguigu.entity.User;
import com.atguigu.mvc.UserController;
public class diTest {
/*
* 容器中的对象是创建容器时创建;
*
*/
@Test
public void test2() throws Exception {
ApplicationContext Context = new ClassPathXmlApplicationContext("di.xml");
UserController controller = Context.getBean(UserController.class);
System.out.println(controller.getUserById());
}
}
|
package com.zhiyou.controller;
import java.io.IOException;
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.multipart.MultipartFile;
import com.zhiyou.model.Video;
import com.zhiyou.service.CourseService;
import com.zhiyou.service.SpeakerService;
import com.zhiyou.service.VideoService;
import com.zhiyou.util.FTPUtil;
@Controller
public class VideoController {
@Autowired
VideoService service;
@Autowired
SpeakerService services;
@Autowired
CourseService servicec;
@RequestMapping("video_manage")
public String show(HttpServletRequest req, HttpServletResponse resp) throws IOException {
int count = service.selectCount();
int page = req.getParameter("page") == "" || req.getParameter("page") == null ? 1
: Integer.valueOf(req.getParameter("page"));
req.setAttribute("count", count);
req.setAttribute("page", page);
req.setAttribute("list", service.selectAll((page - 1) * 5, 5));
req.setAttribute("speakerList", services.selectAll());
req.setAttribute("courseList", servicec.selectAll());
return "videomanage";
}
@RequestMapping("video_manageLike")
public String showLike(String title, Integer speaker_id, Integer course_id, HttpServletRequest req,
HttpServletResponse resp) throws IOException {
System.out.println("title :" + title + "; speaker_id:" + speaker_id + "; course_id:" + course_id);
int count = service.selectCountLike(title, speaker_id, course_id);
int page = req.getParameter("page") == "" || req.getParameter("page") == null ? 1
: Integer.valueOf(req.getParameter("page"));
req.setAttribute("count", count);
req.setAttribute("page", page);
req.setAttribute("speaker_id", speaker_id);
req.setAttribute("course_id", course_id);
req.setAttribute("title", title);
req.setAttribute("list", service.selectLike(title, speaker_id, course_id, (page - 1) * 5, 5));
return "videomanagelike";
}
@RequestMapping("video_delete")
public String delete(Integer video_id, HttpServletRequest req, HttpServletResponse resp) throws IOException {
Integer[] ids = { video_id };
service.delete(ids);
return "forward:video_manage";
}
@RequestMapping("video_deleteAll")
public void deleteAll(Integer[] video_ids, HttpServletRequest req, HttpServletResponse resp) throws IOException {
service.delete(video_ids);
resp.getWriter().write("success");
}
@RequestMapping("video_add")
public String add(HttpServletRequest req, HttpServletResponse resp) throws IOException {
req.setAttribute("speakerList", services.selectAll());
req.setAttribute("courseList", servicec.selectAll());
return "videoadd";
}
@RequestMapping("video_update")
public String update(Integer video_id, HttpServletRequest req, HttpServletResponse resp) throws IOException {
Video video = service.selectById(video_id);
req.setAttribute("video", video);
req.setAttribute("speakerList", services.selectAll());
req.setAttribute("courseList", servicec.selectAll());
return "videoupdate";
}
@RequestMapping("video_alter.do")
public String alter(Video obj, MultipartFile image, MultipartFile video, HttpServletRequest req,
HttpServletResponse resp) throws IOException {
if (image.getSize() != 0) {
String image_url = FTPUtil.upload(image.getInputStream(), image.getOriginalFilename());
obj.setImage_url(image_url);
}
if (video.getSize() != 0) {
String video_url = FTPUtil.upload(video.getInputStream(), video.getOriginalFilename());
obj.setVideo_url(video_url);
}
if (obj.getVideo_id() == null) {
service.add(obj);
} else {
service.update(obj);
}
return "forward:video_manage";
}
}
|
package com.wang.search.controller;
import com.wang.search.controller.entity.Response;
import com.wang.search.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DataAccessException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice;
/**
* controller父类
*
* @author wangjunhao
* @version 1.0
* @date 2020/6/6 9:48
* @since JDK 1.8
*/
@RestController
@Slf4j
public class BaseContruller {
@ExceptionHandler(value = Throwable.class)
public Response handException(Throwable throwable) {
if (throwable instanceof DataAccessException) {
log.error("DATABASE_ERROR:{}", throwable.getStackTrace().toString());
return new Response().setReturnCode(1002).setDescription("数据库错误").setData(null);
}
if (throwable instanceof BusinessException) {
log.warn("BUSSINESS_ERROR:{}", throwable.getStackTrace().toString());
return new Response().setReturnCode(((BusinessException) throwable).getCode()).setDescription(((BusinessException) throwable).getDescription());
}
return new Response().setReturnCode(1001).setDescription("系统未知错误");
}
}
|
package net.redis.dao.user;
import net.redis.dto.user.User;
import org.apache.ibatis.annotations.Param;
public interface UserMapper {
User selectUserByMobile(@Param("mobile") String mobile);
}
|
package eecs.ai.p1.commands;
import eecs.ai.p1.Board;
public class EnableRecorder extends Command {
private EnableRecorder(){
}
/**
* Build method for the command to enable recorder
* @return The command of EnableRecorder
*/
public static EnableRecorder of(){
return new EnableRecorder();
}
/**
* Executes the command and sets the board to a recording state.
*/
@Override
public void execute(Board board) {
board.record();
}
}
|
package com.intricatech.topwatch;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import static com.intricatech.topwatch.DBContract.*;
/**
* Created by Bolgbolg on 06/11/2017.
*/
public class DBHelper extends SQLiteOpenHelper {
public DBHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
//OnDestroyDirector director = (OnDestroyDirector) context;
//director.register(this);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(RouteList.SQL_CREATE_ROUTE_LIST_TABLE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
public void onMainActivityDestroyed() {
close();
}
}
|
package spring0316;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import Conf.mainConf;
import DTO.Person;
import Service.Doing;
public class SampleTest2 {
public static void main(String[] args) {
// AnnotationConfigApplicationContext app = new AnnotationConfigApplicationContext(Conf1.class,Conf2.class);//class name 을 써준다
AnnotationConfigApplicationContext app = new AnnotationConfigApplicationContext(mainConf.class);
Person p1=app.getBean("p1",Person.class);
Person p2=app.getBean("p2",Person.class);
Doing d1=app.getBean("d1",Doing.class);
p1.getAge();
p2.getAge();
d1.prt();
d1.show();
d1.view();
app.close();
}
}
|
package filamentengine.io.xml;
import nu.xom.Attribute;
import nu.xom.Element;
import org.lwjgl.util.vector.Vector3f;
/**
* Serialization helper for writing/reading various classes.
*
* @author toriscope
*
*/
public class XMLIOHelper {
private XMLIOHelper() {
}
public static Element vector3fWrite(final Vector3f v, final String title) {
Element posEle = new Element(title);
posEle.addAttribute(new Attribute("x", "" + v.x));
posEle.addAttribute(new Attribute("y", "" + v.y));
posEle.addAttribute(new Attribute("z", "" + v.z));
return posEle;
}
public static Vector3f vector3fRead(final Element e) {
Vector3f pos = new Vector3f();
pos.x = Float.parseFloat(e.getAttributeValue("x").trim());
pos.y = Float.parseFloat(e.getAttributeValue("y").trim());
pos.z = Float.parseFloat(e.getAttributeValue("z").trim());
return pos;
}
}
|
package com.pan.al.heap;
/**
* 堆就是完全二叉树
* 分类:①大根堆
* 任何一颗子树的最大值都是子树的头部
* ②小根堆
*
*/
public class heap {
/**
* 互换元素
* @param arr
* @param index1
* @param index2
*/
public static void swap(int[] arr, int index1, int index2) {
int tmp = arr[index1];
arr[index1] = arr[index2];
arr[index2] = tmp;
}
/**
* 大根堆的建立,关键一步,
* for(i)循环调用这个函数,就能建立大根堆
* 建立大根堆的时间复杂度为O(N)
* @param arr
* @param index
*/
public static void headInsert(int[] arr,int index){
while(arr[index]>arr[(index-1)/2]){ //一旦子大于父就往上换
swap(arr,index,(index-1)/2);
index=(index-1)/2;
}
}
/**
* 当大根堆中的数突然变小了,从这个变小的位置开始向下沉;
* 0~heapSize上已经形成堆
* @param arr
* @param index
* @param heapSize
*/
public static void heapify(int[] arr, int index, int heapSize) {
int left=index*2+1;
while (left<heapSize)
{ //获取左右最大值
int largest=left+1<heapSize&&arr[left+1]>arr[left]
?left+1
:left;
//与父节点比较
largest=arr[largest]>arr[index]?largest:index;
if(largest==index) break;
swap(arr,largest,index);
index=largest;
left=index*2+1;
}
}
/*减堆操作,将大根堆的堆顶弹出,在将原来的变成大根堆
/ 先将堆顶与数组的最后一个数交换,在进行headify操作
*/
/**
* 堆排序
*
* @param arr
*/
public static void headSort(int[] arr){
if(arr==null||arr.length>2)
{
return;
}
for(int i=0;i<arr.length;i++)
{
headInsert(arr,i); //创建大根堆
}
int heapSize=arr.length;
swap(arr,0,--heapSize);// 交换堆顶和数组最后一个元素
while (heapSize>0)
{
heapify(arr,0,--heapSize);
swap(arr,0,--heapSize);
}
}
}
|
package com.ut.database.dao;
import android.arch.lifecycle.LiveData;
import android.arch.persistence.room.Dao;
import android.arch.persistence.room.Insert;
import android.arch.persistence.room.OnConflictStrategy;
import android.arch.persistence.room.Query;
import com.ut.database.entity.LockKey;
import com.ut.database.entity.SearchRecord;
import java.util.List;
/**
* author : zhouyubin
* time : 2018/12/24
* desc :
* version: 1.0
*/
@Dao
public interface SearchRecordDao {
@Query("SELECT * FROM search_record ORDER BY id DESC LIMIT 10")
LiveData<List<SearchRecord>> getAll();
@Insert(onConflict = OnConflictStrategy.REPLACE)
void insert(SearchRecord searchRecord);
}
|
package com.nepshop.dao;
import com.nepshop.model.Customer;
import com.nepshop.model.User;
import org.apache.commons.codec.binary.Base64;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
public class AuthDAO {
static Connection conn = DBConnectionUtil.getConnection();
public static User loginUser(String email, String password) {
User user = null;
String query = "select * from users where email = ? and password = ?";
try (PreparedStatement ps = conn.prepareStatement(query)) {
ps.setString(1, email);
ps.setString(2, password);
ResultSet rs = ps.executeQuery();
while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
String gender = rs.getString("gender");
Blob blob = rs.getBlob("photo");
if (blob != null) {
InputStream inputStream = blob.getBinaryStream();
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
byte[] buffer = new byte[4096];
int bytesRead = -1;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
byte[] imageBytes = outputStream.toByteArray();
String base64String = new String(Base64.encodeBase64(imageBytes));
String photo = "data:image/jpg;base64," + base64String;
user = new User(id, name, email, password, gender, photo);
} else {
user = new User(id, name, email, password, gender, null);
}
return user;
}
} catch (SQLException | IOException ex) {
ex.printStackTrace();
}
return user;
}
public static boolean createUser(String name, String email, String password, String gender) {
String query = "insert into users(name, email, password, gender) values(?, ? ,?, ?)";
try (PreparedStatement ps = conn.prepareStatement(query)) {
ps.setString(1, name);
ps.setString(2, email);
ps.setString(3, password);
ps.setString(4, gender);
int rs = ps.executeUpdate();
if (rs > 0)
return true;
else
return false;
} catch (SQLException ex) {
ex.printStackTrace();
}
return false;
}
public static Customer loginCustomer(String email, String password) {
Customer customer = null;
String query = "select * from customer where email = ? and password = ?";
try (PreparedStatement ps = conn.prepareStatement(query)) {
ps.setString(1, email);
ps.setString(2, password);
ResultSet rs = ps.executeQuery();
while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
String address = rs.getString("address");
String phone = rs.getString("phone");
Blob blob = rs.getBlob("photo");
if (blob != null) {
InputStream inputStream = blob.getBinaryStream();
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
byte[] buffer = new byte[4096];
int bytesRead = -1;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
byte[] imageBytes = outputStream.toByteArray();
String base64String = new String(Base64.encodeBase64(imageBytes));
String photo = "data:image/jpg;base64," + base64String;
customer = new Customer(id, name, email, password, address, phone, photo);
} else {
customer = new Customer(id, name, email, password, address, phone, null);
}
return customer;
}
} catch (SQLException | IOException ex) {
ex.printStackTrace();
}
return customer;
}
public static boolean createCustomer(String name, String email, String password, String address, String phone) {
String query = "insert into customer(name, email, password, address, phone) values(?, ? ,?, ?, ?)";
try (PreparedStatement ps = conn.prepareStatement(query)) {
ps.setString(1, name);
ps.setString(2, email);
ps.setString(3, password);
ps.setString(4, address);
ps.setString(5, phone);
int rs = ps.executeUpdate();
if (rs > 0)
return true;
else
return false;
} catch (SQLException ex) {
ex.printStackTrace();
}
return false;
}
}
|
package app;
import config.ThymeleafConfig;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import java.util.List;
/**
* Created by pic on 29/04/2017.
*/
@Configuration
@EnableWebMvc
@ComponentScan({"config", "controller"})
@Import({ThymeleafConfig.class})
public class ApplicationContext extends WebMvcConfigurerAdapter{
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry)
{
registry.addResourceHandler("/css/**").addResourceLocations("/static/css");
registry.addResourceHandler("/fonts/**").addResourceLocations("/static/fonts");
registry.addResourceHandler("/img/**").addResourceLocations("/static/img");
registry.addResourceHandler("/js/**").addResourceLocations("/static/js");
}
@Bean
public static PropertySourcesPlaceholderConfigurer properties()
{
PropertySourcesPlaceholderConfigurer propertySources = new PropertySourcesPlaceholderConfigurer();
return propertySources;
}
@Bean
public ResourceBundleMessageSource messageSource()
{
ResourceBundleMessageSource source = new ResourceBundleMessageSource();
source.setBasename("locale/locale");
source.setDefaultEncoding("UTF-8");
return source;
}
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder();
builder.indentOutput(true);
converters.add(new MappingJackson2HttpMessageConverter(builder.build()));
}
}
|
package intToStringUsingFunctionPKG; // Pakage declared
import java.util.Scanner; // importing scanner utility
// This class will convert a Int type variable value to String type using String inbuilt function
public class IntToStringUsingFunction { // class declared and defined
public static void main(String[] args) { // main method
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in); // creating a scanner object
System.out.println("Enter a Integer Value : "); // Printing info
int intVar = input.nextInt(); // taking input value and assigning it to int type variable
String strVar = String.valueOf(intVar);; // converting an int variable value to string type using valueof()
System.out.println(); // printing a blank line
System.out.println("String Representation of Integer Value "+intVar+" is : "+strVar);
}
}
|
package com.djtracksholder.djtracksholder.provider;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
/**
* Created by Вадим on 06.12.13.
*/
public class DBHelper extends SQLiteOpenHelper {
Context context;
private static DBHelper instance;
private static final int DATABASE_VERSION = 1;
public static final String TRACK_TABLE_NAME = "track";
public static final String AUTHOR_TABLE_NAME = "author";
public static final String HOLDER_TABLE_NAME = "holder";
public static final String TRACK_TRACKID = "_id";
public static final String TRACK_TITLE = "name";
public static final String TRACK_AUTHORID = "authorid";
public static final String AUTHOR_AUTHORID = "_id";
public static final String AUTHOR_NAME = "name";
public static final String HOLDER_ID = "_id";
public static final String HOLDER_TRACKID = "trackid";
public static final String HOLDER_CDNUMBER = "cdnumber";
public static final String HOLDER_TRACKNUMBER = "tracknumber";
public static final String WAITLIST_TABLE_NAME = "waitlist";
public static final String WAITLIST_ID = "_id";
public static final String WAITLIST_TRACKID = "trackid";
private static final String TRACK_TABLE_CREATE = "create table " + TRACK_TABLE_NAME + " (" +
"_id integer primary key autoincrement, " +
"title text, " +
"authorid integer);";
private static final String AUTHOR_TABLE_CREATE = "create table " + AUTHOR_TABLE_NAME + " (" +
"_id integer primary key autoincrement, " +
"name text" + ");";
private static final String HOLDER_TABLE_CREATE = "create table " + HOLDER_TABLE_NAME + " (" +
"_id integer primary key autoincrement, " +
"trackid integer, " +
"cdnumber integer, " +
"tracknumber integer" + ");";
private static final String WAITLIST_TABLE_CREATE = "create table " + WAITLIST_TABLE_NAME + " (" +
"_id integer primary key autoincrement, " +
"trackid integer);";
private DBHelper(Context context) {
super(context, "DJHolder", null, 1);
this.context = context;
}
public static DBHelper getInstance(Context context) {
if (instance != null) {
return instance;
}
else {
return new DBHelper(context);
}
}
@Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
sqLiteDatabase.execSQL(TRACK_TABLE_CREATE);
sqLiteDatabase.execSQL(AUTHOR_TABLE_CREATE);
sqLiteDatabase.execSQL(HOLDER_TABLE_CREATE);
sqLiteDatabase.execSQL(WAITLIST_TABLE_CREATE);
}
@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i2) {
}
}
|
package com.example.zhkh_workerapp.tasks;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.fragment.app.FragmentManager;
import com.example.zhkh_workerapp.ApiInteractions.Pojoes.TaskStory;
import com.example.zhkh_workerapp.R;
import java.util.ArrayList;
public class ListTaskAdapter extends ArrayAdapter<TaskStory> {
private LayoutInflater inflater;
private int layout;
private ArrayList<TaskStory> itemList;
private FragmentManager fm;
public ListTaskAdapter(@NonNull Context context, int resource, ArrayList<TaskStory> items,
FragmentManager fm) {
super(context, resource, items);
this.itemList = items;
this.layout = resource;
this.inflater = LayoutInflater.from(context);
this.fm = fm;
}
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder viewHolder;
if(convertView==null){
convertView = inflater.inflate(this.layout, parent, false);
viewHolder = new ViewHolder(convertView);
convertView.setTag(viewHolder);
}
else{
viewHolder = (ViewHolder) convertView.getTag();
}
final TaskStory item = itemList.get(position);
int last = item.getTask().getChangeLogs().size()-1;
viewHolder.status.setText(item.getTask().getChangeLogs().get(last).getActionResult().getState().getName());
String[] dates = item.calculateDate();
viewHolder.date.setText(dates[0]);
viewHolder.name.setText(item.getTask().getName());
viewHolder.days.setText(dates[2]+'/'+item.getTask().getChangeLogs().get(last).getActionResult().getDaysCount());
return convertView;
}
private class ViewHolder {
final TextView status, date, name, days;
ViewHolder(View view){
status = (TextView) view.findViewById(R.id.taskStatus);
date = (TextView) view.findViewById(R.id.taskDate);
name = (TextView) view.findViewById(R.id.taskEventName);
days = (TextView) view.findViewById(R.id.taskDays);
}
}
}
|
package architecture.exception;
public class ClubMemberNotFoundException extends RuntimeException{
//
private static final long serialVersionUID = 853884285421555823L;
public ClubMemberNotFoundException(String message){
//
super(message);
}
}
|
/**
*
*/
package com.ucas.algorithms.utils;
import java.util.Arrays;
import java.util.Random;
/**
* @author wjg
* @version 0.0.1
*
*/
public class IntegerArrayGenerator {
private static int[] A = new int[] {4, 8, 1, 2, 0, 6, 5, 1, 9, 3};
/**
* 返回内置的长度为10的元素大小不超过10的数组。
* @return 数组
*/
public static int[] fixedArray() {
return A.clone();
}
/**
* 返回随机生成的长度为10的元素大小不超过10的数组。
* @return 数组
*/
public static int[] randomArray() {
return randomArray(10);
}
/**
* 返回随机生成的长度为10的指定元素大小上限的数组。
* @param upperLimit 元素大小上限
* @return 数组
*/
public static int[] randomArray(int upperLimit) {
return randomArray(upperLimit, 10);
}
/**
* 返回随机生成的指定长度的指定元素大小上限的数组。
* @param upperLimit 元素大小上限
* @param size 数组长度
* @return 数组
*/
public static int[] randomArray(int upperLimit, int size) {
Random random = new Random(Seed.next());
int[] randomArray = new int[size];
for (int i=0; i<randomArray.length; i++) {
randomArray[i] = random.nextInt(upperLimit);
}
return randomArray;
}
/**
* 返回随机生成的指定长度的指定元素大小上下限的数组。
* @param lowerLimit 元素大小下限
* @param upperLimit 元素大小上限
* @param size 数组长度
* @return 数组
*/
public static int[] randomArray(int lowerLimit, int upperLimit, int size) {
int[] arr = randomArray(upperLimit - lowerLimit, size);
for (int i=0; i<arr.length; i++) {
arr[i] += lowerLimit;
}
return arr;
}
/**
* 返回随机生成的长度为10的分布在[0,1)区间上的数组。
* @return 数组
*/
public static double[] randomArrayDouble() {
int[] arr = randomArray();
double[] arrDouble = new double[arr.length];
for (int i=0; i<arr.length; i++) {
arrDouble[i] = arr[i] / 10.0;
}
return arrDouble;
}
}
|
/**
*
*/
package com.cassandra.TrialWithIText;
import javafx.event.EventHandler;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.input.KeyEvent;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import java.util.ArrayList;
import java.util.List;
/**
* @author Cassandra Mae
*
*/
public class MainCanvas extends Pane {
/**
* The canvas.
*/
protected Canvas canvas;
/**
* Holds a list of shapes to render on the canvas.
*/
private List<Shapes> shapes;
/**
* A handler corresponding to the current selected tool.
*/
private HandleingEvents eventHandler;
/**
* Constructs the canvas pane.
*/
public MainCanvas() {
canvas = new Canvas(Main.WINDOW_WIDTH, Main.WINDOW_HEIGHT);
shapes = new ArrayList<>();
getChildren().add(canvas);
EventHandler<MouseEvent> handler = new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent e) {
eventHandler.Event(e);
}
};
canvas.addEventHandler(MouseEvent.MOUSE_PRESSED, handler);
canvas.addEventHandler(MouseEvent.MOUSE_DRAGGED, handler);
canvas.addEventHandler(MouseEvent.MOUSE_RELEASED, handler);
canvas.addEventHandler(MouseEvent.MOUSE_CLICKED, handler);
}
/**
* Getter for shapes.
* @return list of shapes
*/
public List<Shapes> getShapes() {
return shapes;
}
/**
* Getter for event handler.
* @return the current event handler
*/
public HandleingEvents getEventHandler() {
return eventHandler;
}
/**
* Setter for event handler.
* @param eventHandler new event handler
*/
public void setEventHandler(HandleingEvents eventHandler) {
this.eventHandler = eventHandler;
}
/**
* Clears the canvas.
* @param color the background color of the canvas after clearing
*/
public void clear(Color color) {
GraphicsContext gc = canvas.getGraphicsContext2D();
gc.setFill(color);
gc.fillRect(0, 0, canvas.getWidth(), canvas.getHeight());
}
/**
* Clears the canvas with a white background.
*/
public void clear() {
clear(Color.WHITE);
}
/**
* Draw all the shapes onto the canvas.
*/
private void render() {
GraphicsContext gc = canvas.getGraphicsContext2D();
for (Shapes myShape : shapes)
myShape.draw(gc);
shapes.get(0).HghlightShape(gc);
// if(shapes.size()!=0) {
// for(int i =0; i<shapes.size();i++) {
// Shapes myShape = shapes.get(i);
// if(myShape.selected) {
// myShape.HghlightShape(gc);
// }
// }
// }
}
/**
* Update the canvas by clearing and redrawing the shapes.
*/
public void update() {
clear();
render();
}
/**
* Deselects any selected shape.
*/
private void deselectShapes() {
for (Shapes shape : shapes)
shape.setElementSelected(false);
update();
}
// public GraphicsContext getGraphicsContextMainCanvas() {
// GraphicsContext gc = canvas.getGraphicsContext2D();
// return gc;
// }
//
// public void setHighlight() {
// GraphicsContext gc = canvas.getGraphicsContext2D();
// }
}
//if(myShape.isShapeSelected==true) {
// myShape.setHighlight(gc);
//}
//}
//if(shapes.size()!=0) {
//for(int i =0; i<=shapes.size();i++) {
// Shapes myShape = shapes.get(i);
// if(myShape.isShapeSelected) {
// myShape.setHighlight(gc);
// }
//}
//}
|
package com.example.testproject.first_setting;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import androidx.fragment.app.Fragment;
import com.example.testproject.R;
public class SecondNameFragment extends Fragment {
private LinearLayout skipLayout;
private EditText inputName;
private Button btnNext;
public SecondNameFragment() {
// Required empty public constructor
}
public static SecondNameFragment newInstance() {
return new SecondNameFragment();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_set_second_name, container, false);
skipLayout = view.findViewById(R.id.skip_layout);
inputName = view.findViewById(R.id.edit_text);
btnNext = view.findViewById(R.id.btn_next);
if (getActivity() != null) {
skipLayout.setOnClickListener(v -> ((FirstSettingActivity) getActivity()).addFragment(ThirdGreetingFragment.newInstance()));
btnNext.setOnClickListener(v -> ((FirstSettingActivity) getActivity()).addFragment(ThirdGreetingFragment.newInstance()));
}
inputName.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
checkValidation();
}
});
checkValidation();
return view;
}
private void checkValidation() {
boolean isValid = false;
if (inputName.length() > 0) {
isValid = true;
}
btnNext.setBackgroundResource(isValid ? R.drawable.button_enabled : R.drawable.button_disabled);
btnNext.setTextColor(isValid ? Color.parseColor("#404040") : Color.parseColor("#696969"));
btnNext.setEnabled(isValid);
}
}
|
package com.zheng.pool;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
/**
* 线程池
* Created by zhenglian on 2016/10/1.
*/
public class ThreadPool {
public static void main(String[] args) {
// new ThreadPool().createThreadPool();
new ThreadPool().scheduleThreadPool();
}
private static void createThreadPool() {
// ExecutorService service = Executors.newFixedThreadPool(3);
// ExecutorService service = Executors.newCachedThreadPool();
ExecutorService service = Executors.newSingleThreadExecutor();
for(int i = 0; i < 10; i++) {
final int task = i;
service.execute(new Runnable() {
public void run() {
for(int j = 0; j < 10; j++) {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + " loop of " + j + " task " + task);
}
}
});
}
service.shutdown();
}
public void scheduleThreadPool() {
ScheduledExecutorService service = Executors.newScheduledThreadPool(3);
service.schedule(new Runnable() {
public void run() {
System.out.println("bloming!");
}
}, 2, TimeUnit.SECONDS);
service.scheduleAtFixedRate(new Runnable() {
public void run() {
System.out.println("bloming!");
}
}, 6, 2, TimeUnit.SECONDS);
}
}
|
package cn.ztuo.bitrade;
import cn.ztuo.bitrade.entity.ExchangeTrade;
import cn.ztuo.bitrade.service.ReleaseService;
import com.alibaba.fastjson.JSON;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import cn.ztuo.bitrade.MarketApplication;
import cn.ztuo.bitrade.service.ExchangeOrderService;
import cn.ztuo.bitrade.service.MarketService;
import org.springframework.web.client.RestTemplate;
import java.util.List;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = MarketApplication.class)
public class MarketAppTest {
@Autowired
private MarketService marketService;
@Autowired
private ExchangeOrderService exchangeOrderService;
@Autowired
private RestTemplate restTemplate;
@Autowired
ReleaseService releaseService;
@Test
public void contextLoads() throws Exception {
releaseService.release();
}
}
|
package com.learning.arrays;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
public class Task12270Test {
Task12270 task12270;
char[][] randomArray;
char[][] concreteArray;
@Before
public void init() {
task12270 = new Task12270();
randomArray = ArrayHelper.getTwoDimensionalArray();
concreteArray = new char[2][2];
concreteArray[0][0] = 'a';
concreteArray[0][1] = 'b';
concreteArray[1][0] = 'c';
concreteArray[1][1] = 'd';
}
@Test(expected = IllegalArgumentException.class)
public void testGetCornersNullIn() {
task12270.getCorners(null);
}
@Test(expected = IllegalArgumentException.class)
public void testGetCornersToSmallArray() {
task12270.getCorners(new char[1][1]);
}
@Test
public void testGetCornersOut() {
assertNotNull(task12270.getCorners(randomArray));
assertEquals("Symbols from corners: abcd", task12270.getCorners(concreteArray).toString());
}
}
|
/*
* Created on Mar 17, 2007
*
*
* Window - Preferences - Java - Code Style - Code Templates
*/
package com.citibank.ods.modules.product.prodqlfyprvt.functionality.valueobject;
import com.citibank.ods.common.functionality.valueobject.BaseODSFncVO;
import com.citibank.ods.entity.pl.BaseTplProdQlfyPrvtEntity;
/**
* @author fernando.salgado
*
*
* Preferences - Java - Code Style - Code Templates
*/
public class BaseProdQlfyPrvtDetailFncVO extends BaseODSFncVO
{
/**
* Constante de descrição do nome do campo da Qualificação do Produto
*/
public static final String C_PROD_QLFY_CODE_DESCRIPTION = "Código da Qualificação";
/**
* Constante de descrição do nome do campo de Descrição da Qualificação do
* Produto
*/
public static final String C_PROD_QLFY_TEXT_DESCRIPTION = "Descrição da Qualificação";
protected BaseTplProdQlfyPrvtEntity m_baseTplProdQlfyPrvtEntity;
/**
* @return Returns the m_baseTplProdQlfyPrvtEntity.
*/
public BaseTplProdQlfyPrvtEntity getBaseTplProdQlfyPrvtEntity()
{
return m_baseTplProdQlfyPrvtEntity;
}
/**
* @param tplProdQlfyPrvtEntity The m_baseTplProdQlfyPrvtEntity to set.
*/
public void setBaseTplProdQlfyPrvtEntity(
BaseTplProdQlfyPrvtEntity tplProdQlfyPrvtEntity_ )
{
m_baseTplProdQlfyPrvtEntity = tplProdQlfyPrvtEntity_;
}
}
|
package org.apache.cassandra.db.transaction;
import org.apache.cassandra.utils.SimpleCondition;
import java.util.Date;
import java.util.concurrent.TimeUnit;
public class ROT_Timestamp {
long[] tv;
SimpleCondition cv;
ROT_Timestamp() {
cv = new SimpleCondition();
}
}
|
package com.zhongyp.advanced.proxy.cglib;
import org.springframework.cglib.proxy.Enhancer;
/**
* @author zhongyp.
* @date 2019/9/17
*/
public class Test {
public static void main(String[] args) {
LogInterceptor logInterceptor = new LogInterceptor();
Enhancer enhancer = new Enhancer();
// 设置超类,cglib是通过继承来实现的
enhancer.setSuperclass(UserDao.class);
enhancer.setCallback(logInterceptor);
// 创建代理类
Dao dao = (Dao)enhancer.create();
dao.update();
dao.select();
}
}
|
package com.example.algamaney.api.enums;
public enum TipoLancamentoEnum {
RECEITA,DESPESA;
}
|
import com.amazonaws.services.kinesis.AmazonKinesis;
import com.amazonaws.services.kinesis.model.*;
import java.util.Date;
public class KinesisStreamComsumer {
private AmazonKinesis client;
public KinesisStreamComsumer(AmazonKinesis client) {
this.client = client;
}
public Record getRecord(String streamName, Date timestamp){
ShardFilter filter = new ShardFilter();
filter.setType("FROM_TIMESTAMP");
filter.setTimestamp(timestamp);
ListShardsRequest listShardsRequest = new ListShardsRequest().withStreamName(streamName).withShardFilter(filter);
ListShardsResult response = client.listShards(listShardsRequest);
Shard shard = response.getShards().get(0);
GetShardIteratorRequest getShardIteratorRequest = new GetShardIteratorRequest();
getShardIteratorRequest.setStreamName(streamName);
getShardIteratorRequest.setShardId(shard.getShardId());
getShardIteratorRequest.setShardIteratorType("TRIM_HORIZON");
GetShardIteratorResult getShardIteratorResult = client.getShardIterator(getShardIteratorRequest);
String shardIterator = getShardIteratorResult.getShardIterator();
GetRecordsRequest getRecordsRequest = new GetRecordsRequest();
getRecordsRequest.setShardIterator(shardIterator);
getRecordsRequest.setLimit(25);
GetRecordsResult getRecordsResult = client.getRecords(getRecordsRequest);
int recordsSize = getRecordsResult.getRecords().size();
return getRecordsResult.getRecords().get(recordsSize - 1);
}
}
|
/*
* 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 loja.produtos;
/**
*
* @author Xcution
*/
public class LojaProdutos {
public LojaProdutos(){}
public boolean CadastraProdutos(){
return true;
}
public boolean ExcluirProdutos(){
return true;
}
public boolean AtualizarProdutos(){
return true;
}
public boolean AddEstoque(){
return true;
}
public boolean RmEstoque(){
return true;
}
public boolean ConsultaEstoque(){
return true;
}
}
|
package pl.rafaltruszewski.stringcalculator;
import java.util.List;
import java.util.stream.Collectors;
class StringCalculator {
private final NumbersParser numbersParser;
StringCalculator(NumbersParser numbersParser) {
this.numbersParser = numbersParser;
}
public int add(String numbers) throws NegativesNotAllowed {
if(numbers.isEmpty()) return 0;
List<Integer> numbersAsInt = numbersParser.parse(numbers);
checkNegatives(numbersAsInt);
return sum(numbersAsInt);
}
private int sum(List<Integer> numbersAsInt) {
return numbersAsInt.stream()
.filter(e -> e <= 1000)
.mapToInt(Integer::valueOf)
.sum();
}
private void checkNegatives(List<Integer> numbersAsInt) {
List<Integer> negatives = numbersAsInt.stream()
.filter(e -> e < 0)
.collect(Collectors.toList());
if(negatives.isEmpty()){
return;
}
StringBuilder message = new StringBuilder();
message.append(negatives.get(0));
for (int i = 1; i < negatives.size(); i++){
message.append(",")
.append(negatives.get(i));
}
throw new NegativesNotAllowed(message.toString());
}
}
|
package com.pbadun.fragment;
import com.pbadun.fragment.interfaces.IConstFragment;
import com.pbadun.rssreaderv2.R;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.webkit.WebViewClient;
/**
* Фрагмен отвечает за вывад контента...
*
* @author jb
*
*/
public class ContentFragment extends Fragment implements IConstFragment{
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.content, container, false);
String url = getArguments().getString(URL_NEWS_SITE);
WebView wv = (WebView) v.findViewById(R.id.webViewSite);
wv.setWebViewClient(new myWebViewClient());
wv.getSettings().setJavaScriptEnabled(false);
wv.loadUrl(url);
return v;
}
class myWebViewClient extends WebViewClient{
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url)
{
view.loadUrl(url);
return true;
}
}
}
|
package com.nilbardou.drivingangel.adapter;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;
import androidx.recyclerview.widget.RecyclerView;
import android.app.Dialog;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.Transformation;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.android.material.transition.Hold;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.nilbardou.drivingangel.HistorialFragment;
import com.nilbardou.drivingangel.MainActivity;
import com.nilbardou.drivingangel.PulsoFragment;
import com.nilbardou.drivingangel.R;
import com.nilbardou.drivingangel.models.Trayecto;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class MyItemRecyclerViewAdapter extends RecyclerView.Adapter<MyItemRecyclerViewAdapter.ViewHolder> {
Context mContext;
List<Trayecto> trayecto_list;
private List<Boolean> lista_borrado = new ArrayList<>();
int duration = Toast.LENGTH_SHORT;
Dialog mDialog;
HistorialFragment historialFragment;
int position, primero = 0;
private FirebaseAuth mAuth;
private DatabaseReference mDatabase;
private String id_trayecto, titulo;
private TextView dialog_trayecto, dialog_pulsoMed, dialog_pulsoMax, dialog_pulsoMin, dialog_cronoTray, dialog_cronoDesc,
dialog_fecha;
private EditText edit_trayecto;
private Button borrar_btn, modificar_btn;
Map<String, Integer> map = new HashMap<String, Integer>();
public MyItemRecyclerViewAdapter(Context mContext, List<Trayecto> trayecto_list, HistorialFragment historialFragment) {
this.mContext = mContext;
this.trayecto_list = trayecto_list;
this.historialFragment = historialFragment;
}
public class ViewHolder extends RecyclerView.ViewHolder {
private TextView tray, fecha;
private LinearLayout tray_item;
private CheckBox checkBox;
private View view;
public ViewHolder(View itemView, HistorialFragment historialFragment) {
super(itemView);
tray = (TextView) itemView.findViewById(R.id.trayecto_txt);
tray_item = (LinearLayout) itemView.findViewById(R.id.trayecto_item);
checkBox = (CheckBox) itemView.findViewById(R.id.checkBox_delete);
fecha = (TextView) itemView.findViewById(R.id.fecha_trayecto);
lista_borrado.add(0,false);
}
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
final View view = LayoutInflater.from(mContext).inflate(R.layout.fragment_historial, parent, false);
final ViewHolder vHolder = new ViewHolder(view, historialFragment);
mDialog = new Dialog(mContext);
mDialog.setContentView(R.layout.trayecto);
vHolder.tray_item.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dialog_trayecto = (TextView) mDialog.findViewById(R.id.tray_text);
edit_trayecto = (EditText) mDialog.findViewById(R.id.tray_edit);
dialog_pulsoMed = (TextView) mDialog.findViewById(R.id.pulso_medio);
dialog_pulsoMax = (TextView) mDialog.findViewById(R.id.pulso_max);
dialog_pulsoMin = (TextView) mDialog.findViewById(R.id.pulso_min);
dialog_cronoTray = (TextView) mDialog.findViewById(R.id.crono_tray);
dialog_cronoDesc = (TextView) mDialog.findViewById(R.id.crono_desc);
dialog_fecha = (TextView) mDialog.findViewById(R.id.data_try);
borrar_btn = (Button) mDialog.findViewById(R.id.borrar_try);
modificar_btn = (Button) mDialog.findViewById(R.id.modificar_try);
dialog_trayecto.setVisibility(view.VISIBLE);
edit_trayecto.setVisibility(view.GONE);
modificar_btn.setText("Modificar");
primero = 0;
id_trayecto = trayecto_list.get(vHolder.getAdapterPosition()).getId_trayecto();
dialog_trayecto.setText(trayecto_list.get(vHolder.getAdapterPosition()).getTrayecto());
edit_trayecto.setText(trayecto_list.get(vHolder.getAdapterPosition()).getTrayecto());
dialog_pulsoMed.setText(String.valueOf(trayecto_list.get(vHolder.getAdapterPosition()).getPulsoMedio()));
dialog_pulsoMax.setText(String.valueOf(trayecto_list.get(vHolder.getAdapterPosition()).getPulsoMax()));
dialog_pulsoMin.setText(String.valueOf(trayecto_list.get(vHolder.getAdapterPosition()).getPulsoMin()));
dialog_cronoTray.setText(trayecto_list.get(vHolder.getAdapterPosition()).getCronoTrayecto());
dialog_cronoDesc.setText(trayecto_list.get(vHolder.getAdapterPosition()).getCronoDescanso());
dialog_fecha.setText(trayecto_list.get(vHolder.getAdapterPosition()).getFecha());
mDialog.show();
mDatabase = FirebaseDatabase.getInstance().getReference();
mAuth = FirebaseAuth.getInstance();
borrar_btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
final String id = mAuth.getCurrentUser().getUid();
mDatabase.child("Usuarios").child(id).child("Trayectos").child(id_trayecto).removeValue().addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if (task.isSuccessful()){
Toast.makeText(mContext, "Borrado de la BD", duration).show();
}else {
Toast.makeText(mContext, "No se ha podido borrar de la BD", duration).show();
}
}
});
trayecto_list.clear();
mDialog.dismiss();
}
});
modificar_btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (primero == 0){
modificar_btn.setText("Guardar");
dialog_trayecto.setVisibility(view.GONE);
edit_trayecto.setVisibility(view.VISIBLE);
primero = 1;
}else{
final String id = mAuth.getCurrentUser().getUid();
titulo = edit_trayecto.getText().toString();
mDatabase.child("Usuarios").child(id).child("Trayectos").child(id_trayecto).child("título").setValue(titulo).addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if (task.isSuccessful()){
Toast.makeText(mContext, "Modificado", duration).show();
}else {
Toast.makeText(mContext, "No se ha podido modificar", duration).show();
}
}
});
modificar_btn.setText("Modificar");
trayecto_list.clear();
mDialog.dismiss();
}
}
});
}
});
return vHolder;
}
@Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
holder.tray.setText(trayecto_list.get(position).getTrayecto());
holder.fecha.setText(trayecto_list.get(position).getFecha());
holder.checkBox.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Boolean borrado = lista_borrado.get(position);
if (borrado == true){
lista_borrado.set(position, false);
}else{
lista_borrado.set(position, true);
}
}
});
}
@Override
public int getItemCount() {
return trayecto_list.size();
}
public void setFilter(ArrayList<Trayecto> lista_trayecto){
this.trayecto_list = new ArrayList<>();
this.trayecto_list.addAll(lista_trayecto);
notifyDataSetChanged();
}
public List getListaBorrado(){
return lista_borrado;
}
public void setTrayecto_list(List<Trayecto> trayecto_list) {
this.trayecto_list = trayecto_list;
}
public List getLista(){
return trayecto_list;
}
}
|
package com.proyectogrado.alternativahorario.persistencia;
import com.proyectogrado.alternativahorario.entidades.Sede;
import java.util.List;
import javax.ejb.Local;
/**
*
* @author Steven
*/
@Local
public interface FachadaPersistenciaSedeLocal {
void create(Sede sede);
void edit(Sede sede);
void remove(Sede sede);
Sede find(Object id);
List<Sede> findAll();
List<Sede> findRange(int[] range);
int count();
Sede findByNombre(String nombre);
}
|
package com.git.cloud.handler.automation.fw.impl;
import java.util.HashMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.alibaba.fastjson.JSONObject;
import com.git.cloud.handler.automation.fw.FirewallCommonHandler;
import com.git.cloud.handler.automation.fw.model.ExecuteTypeEnum;
import com.git.cloud.handler.automation.fw.model.RmNwFirewallRequestPo;
import com.git.cloud.request.model.SrTypeMarkEnum;
import com.git.cloud.request.model.po.BmSrRrinfoPo;
public class ExecutePolicyHandler extends FirewallCommonHandler{
private static Logger logger = LoggerFactory.getLogger(ExecutePolicyHandler.class);
public void executeOperate(HashMap<String, Object> contextParams) throws Exception {
String srId = (String) contextParams.get("srvReqId");
BmSrRrinfoPo rrinfo = super.getFirewallAutomationService().findBmSrRrinfoBySrId(srId);
String parametersJson = rrinfo.getParametersJson();
logger.info("[ExecutePolicyHandler] parametersJson : " + parametersJson);
JSONObject json = JSONObject.parseObject(parametersJson);
String firewallRequestId = json.getString("firewallRequestId");
String srTypeMark = json.getString("srTypeMark");
RmNwFirewallRequestPo rmNwFirewallRequestPo = super.getFirewallAutomationService()
.findRmNwFirewallRequestById(firewallRequestId);
if (srTypeMark.equals(SrTypeMarkEnum.FIREWALL.getValue())) {
String openExecuteType = rmNwFirewallRequestPo.getOpenExecuteType();
if (openExecuteType.equals(ExecuteTypeEnum.IMMEDIATE.getValue())) {
} else {
throw new Exception("当前开通申请为定时执行,定时执行时间为:"+rmNwFirewallRequestPo.getOpenExecuteTime());
}
} else {
String closeExecuteType = rmNwFirewallRequestPo.getCloseExecuteType();
if (closeExecuteType.equals(ExecuteTypeEnum.IMMEDIATE.getValue())) {
} else {
throw new Exception("当前回收申请为定时执行,定时执行时间为:"+rmNwFirewallRequestPo.getCloseExecuteTime());
}
}
}
}
|
package com.xiv.gearplanner.models.inventory;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonManagedReference;
import javax.persistence.*;
@Entity
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public abstract class Item {
@Id
@GeneratedValue(strategy = GenerationType.TABLE)
private Long id;
@Column /* Imported Id */
private Integer originalId;
@Column
private String name;
@Column
@JsonIgnore
private Integer icon;
@Column
private Integer iLvl;
@Column
private Long xivdbID;
@Column(columnDefinition = "text")
private String description;
@Column
@JsonIgnore
private String lodestoneId;
@ManyToOne
@JsonManagedReference
ItemCategory category;
@Column
private boolean craftable = false;
public Item() { }
public Item(String name, String description, Integer iLvl, Integer icon, Integer originalId, ItemCategory category) {
this.name = name;
this.description = description;
this.icon = icon;
this.iLvl = iLvl;
this.originalId = originalId;
this.category = category;
}
public Item(String name, Integer icon, Integer iLvl, Integer equipLevel, String lodestoneId) {
this.name = name;
this.icon = icon;
this.iLvl = iLvl;
this.lodestoneId = lodestoneId;
}
public Item(String name, Integer iLvl) {
this.name = name;
this.iLvl = iLvl;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getiLvl() {
return iLvl;
}
public void setiLvl(Integer iLvl) {
this.iLvl = iLvl;
}
public Long getXivdbID() {
return xivdbID;
}
public void setXivdbID(Long xivdbID) {
this.xivdbID = xivdbID;
}
public String getLodestoneId() {
return lodestoneId;
}
public void setLodestoneId(String lodestoneId) {
this.lodestoneId = lodestoneId;
}
public Integer getIcon() {
return icon;
}
public void setIcon(Integer icon) {
this.icon = icon;
}
public Integer getOriginalId() {
return originalId;
}
public void setOriginalId(Integer originalId) {
this.originalId = originalId;
}
public String getXivDBLink() {
return "http://xivdb.com/item/" + this.originalId;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public ItemCategory getCategory() {
return category;
}
public void setCategory(ItemCategory category) {
this.category = category;
}
public boolean isCraftable() {
return craftable;
}
public void setCraftable(boolean craftable) {
this.craftable = craftable;
}
}
|
package com.zc.pivas.statistics.repository;
import com.zc.base.orm.mybatis.annotation.MyBatisRepository;
import com.zc.pivas.statistics.bean.configFee.ConfigFeeBatchPieBean;
import com.zc.pivas.statistics.bean.configFee.ConfigFeeDeptPieBean;
import com.zc.pivas.statistics.bean.configFee.ConfigFeeSearchBean;
import com.zc.pivas.statistics.bean.configFee.ConfigFeeStatusBean;
import org.apache.ibatis.annotations.Param;
import java.util.List;
/**
* 配置费报表DAO
*
* @author jagger
* @version 1.0
*/
@MyBatisRepository("configFeeDao")
public interface STConfigFeeDao {
/**
* 查询
*
* @param medicSingle
* @return
*/
List<ConfigFeeStatusBean> queryBatchStatusList(@Param("configFee") ConfigFeeSearchBean medicSingle);
/**
* 查询批次统计信息
*
* @param configFee
* @return
*/
List<ConfigFeeBatchPieBean> queryBatchPieList(@Param("configFee") ConfigFeeSearchBean configFee);
/**
* 根据批次ID 查询批次的药单状态统计
*
* @param configFee
* @return
*/
List<ConfigFeeStatusBean> queryBatchStatusListByID(@Param("configFee") ConfigFeeSearchBean configFee);
/**
* 查询病区 药单状态统计信息
*
* @param configFee
* @return
*/
List<ConfigFeeStatusBean> queryDeptStatusList(@Param("configFee") ConfigFeeSearchBean configFee);
/**
* 查询病区统计信息
*
* @return
*/
List<ConfigFeeDeptPieBean> queryDeptPieList(@Param("configFee") ConfigFeeSearchBean configFee);
/**
* 根据病区名称,查询病区 药单状态统计信息
*
* @param configFee
* @return
*/
List<ConfigFeeStatusBean> queryDeptStatusListByName(@Param("configFee") ConfigFeeSearchBean configFee);
/**
* 获取用到的配置费类型列表
*
* @param compareResult
* @return
*/
List<Integer> getConfigFeeTypeList(@Param("compareResult") String compareResult);
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.