text
stringlengths 10
2.72M
|
|---|
package com.google.engedu.puzzle8;
import android.app.Application;
import android.graphics.Bitmap;
import android.support.test.runner.AndroidJUnit4;
import android.test.ApplicationTestCase;
import android.util.Log;
import org.junit.runner.RunWith;
import org.junit.Before;
import org.junit.Test;
@RunWith(AndroidJUnit4.class)
public class ApplicationTest extends ApplicationTestCase<Application> {
public ApplicationTest() {
super(Application.class);
}
// @Test
// public void runTestIsSameBoard() {
// Bitmap.Config conf = Bitmap.Config.ARGB_8888; // see other conf types
// Bitmap bmp = Bitmap.createBitmap(10, 10, conf);
// PuzzleBoard pb1 = new PuzzleBoard(bmp, 10);
// PuzzleBoard pb2 = new PuzzleBoard(bmp, 30);
//
// assertTrue(pb1.isSameBoard(pb2));
// pb1.swapTiles(0, 5);
// assertFalse(pb1.isSameBoard(pb2));
//
//
//
// }
@Test
public void checkSolved() {
// Bitmap.Config conf = Bitmap.Config.ARGB_8888; // see other conf types
// Bitmap bmp = Bitmap.createBitmap(10, 10, conf);
// PuzzleBoard pb1 = new PuzzleBoard(bmp, 10, 10);
// pb1.swapTiles(7, 8);
// pb1.swapTiles(4,7);
// pb1.swapTiles(3,4);
// int dist = pb1.totalManhattanDistance();
// assertTrue(dist == 6);
}
//[0,1,2,3,4,5,6,7,null]
// 0,1,2
// 3,null,5
// 6,4,7
// md = 0
//
// [1,2,3,5,7,null,4,6,0]
// 1,2,3
// 5,7,null
// 4,6,0
//md = 1+1+3+2+1+1+1+2+4
}
|
package com.tencent.mm.plugin.backup.bakoldlogic.bakoldpcmodel;
import com.tencent.mm.plugin.backup.bakoldlogic.bakoldpcmodel.e.2;
import com.tencent.mm.plugin.backup.bakoldlogic.d.b.a;
import com.tencent.mm.plugin.backup.f.b;
import com.tencent.mm.plugin.backup.h.s;
import com.tencent.mm.sdk.platformtools.x;
class e$1 extends a {
final /* synthetic */ e gZX;
e$1(e eVar) {
this.gZX = eVar;
}
public final void run() {
s sVar = new s();
if (this.hbk) {
sVar.hbZ = this.dbSize;
sVar.hcx = this.hbm - this.dbSize;
sVar.hcw = this.hbl;
e eVar = this.gZX;
e.a(6, 0, sVar);
b.a(3, new 2(eVar));
x.i("MicroMsg.BakPcProcessMgr", "send restore info cmd");
new com.tencent.mm.plugin.backup.bakoldlogic.c.b(2).ass();
return;
}
if (this.dbSize > this.hbm && this.hbm > 0) {
sVar.hbZ = this.dbSize;
sVar.hcx = this.hbm - this.dbSize;
}
e.a(6, 14, sVar);
x.e("MicroMsg.BakPcProcessMgr", "init TempDB error");
}
}
|
package com.example.places.model;
import lombok.AllArgsConstructor;
import lombok.Data;
import java.time.LocalTime;
@AllArgsConstructor
@Data
public class Interval {
private LocalTime from;
private LocalTime to;
}
|
package com.github.jrubygradle.jem;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
/**
* Plain Old Java Object for an enumeration of metadata provided by a gem
*/
public class Gem {
@JsonProperty
public String name;
@JsonProperty
public Version version;
@JsonProperty
public String description;
@JsonProperty
public String platform;
@JsonProperty
public Object email;
@JsonProperty
public String homepage;
@JsonProperty
public List<String> authors;
@JsonProperty
public List<String> files;
@JsonProperty(value="test_files")
public List<String> testFiles;
@JsonProperty
public List<String> executables;
@JsonProperty
public String bindir;
@JsonProperty(value="require_paths")
public List<String> requirePaths;
@JsonProperty
public List<String> licenses;
@JsonProperty(value="specification_version")
public Integer specificationVersion;
@JsonProperty(value="rubygems_version")
public String rubygemsVersion;
/**
* Take the given argument and produce a {@code Gem} instance
*
* @param metadata a {@code java.lang.String}, a {@code java.io.File} or a {@code java.util.zip.GZIPInputStream}
* @return constructed instance of Gem or null if we couldn't process arguments
* @throws JsonProcessingException when the String provided is not JSON
* @throws IOException when the File provided can not be properly read
*/
public static Gem fromFile(Object metadata) throws JsonProcessingException, IOException {
if (metadata instanceof String) {
return createGemFromFile(new File((String)metadata));
}
if (metadata instanceof File) {
return createGemFromFile((File)(metadata));
}
if (metadata instanceof InputStream) {
return createGemFromInputStream((InputStream)(metadata));
}
return null;
}
/**
* Output the gemspec stub for this file
*
* See: https://github.com/rubygems/rubygems/blob/165030689defe16680b7f336232db62024f49de4/lib/rubygems/specification.rb#L2422-L2512
*
* @return String representation of the computed .gemspec file
* @throws JsonProcessingException if some attributes could not be properly serialized out to JSON
*/
public String toRuby() throws JsonProcessingException {
String[] specification = {
"# -*- encoding: utf-8 -*-",
"#",
String.format("# stub: %s %s %s %s",
name, version.version, platform, join(requirePaths.toArray(new String[0]), "\0")),
"#",
"# NOTE: This specification was generated by `jem`",
"# <https://github.com/jruby-gradle/jem>",
"",
"Gem::Specification.new do |s|",
" s.name = " + sanitize(name),
" s.version = " + sanitize(version.version),
" s.description = " + sanitize(description),
" s.homepage = " + sanitize(homepage),
" s.authors = " + sanitize(authors),
" s.email = " + sanitize(email),
" s.licenses = " + sanitize(licenses),
"",
" s.platform = " + sanitize(platform),
" s.require_paths = " + sanitize(requirePaths),
" s.executables = " + sanitize(executables),
" s.rubygems_version = " + sanitize(rubygemsVersion),
"end",
};
return join(specification);
}
private String join(String[] segments) {
return this.join(segments, System.getProperty("line.separator"));
}
private String join(String[] segments, String split) {
StringBuilder builder = new StringBuilder();
for (String segment : segments) {
builder.append(String.format("%s%s", segment, split));
}
return builder.toString();
}
/**
* Convert whatever object we're given into a safe (see: JSON) reprepsentation
*
* @param value Object to pass to Jackson to create a string representation of
* @return String representation of the value parameter
* @throws JsonProcessingException Exception when the value cannot be JSON serialized
*/
protected String sanitize(Object value) throws JsonProcessingException {
ObjectMapper mapper = new ObjectMapper();
return mapper.writeValueAsString(value);
}
private static Gem createGemFromFile(File gemMetadataFile) throws
JsonProcessingException, IOException {
if (!gemMetadataFile.exists()) {
return null;
}
return getYamlMapper().readValue(gemMetadataFile, Gem.class);
}
private static Gem createGemFromInputStream(InputStream gemMetadataStream) throws
JsonProcessingException, IOException {
return getYamlMapper().readValue(gemMetadataStream, Gem.class);
}
private static ObjectMapper getYamlMapper() {
ObjectMapper mapper = new ObjectMapper(new YAMLFactory());
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
return mapper;
}
}
|
/*
* The MIT License (MIT)
*
* Copyright (c) 2020 Marcelo Guimarães <ataxexe@backpackcloud.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package io.backpackcloud.fakeomatic.spi;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
public class Statistics {
private final int totalResponses;
private final int informationalResponses;
private final int successResponses;
private final int redirectionResponses;
private final int clientErrorResponses;
private final int serverErrorResponses;
private final long processingTime;
private final LocalDateTime startTime;
private final LocalDateTime endTime;
public Statistics(int informationalResponses,
int successResponses,
int redirectionResponses,
int clientErrorResponses,
int serverErrorResponses,
LocalDateTime startTime,
LocalDateTime endTime) {
this.informationalResponses = informationalResponses;
this.successResponses = successResponses;
this.redirectionResponses = redirectionResponses;
this.clientErrorResponses = clientErrorResponses;
this.serverErrorResponses = serverErrorResponses;
this.startTime = startTime;
this.endTime = endTime;
this.totalResponses =
informationalResponses + successResponses + redirectionResponses + clientErrorResponses + serverErrorResponses;
this.processingTime =
endTime.toInstant(ZoneOffset.UTC).toEpochMilli() - startTime.toInstant(ZoneOffset.UTC).toEpochMilli();
}
public int totalResponses() {
return this.totalResponses;
}
public int informationalResponses() {
return this.informationalResponses;
}
public int successResponses() {
return this.successResponses;
}
public int redirectionResponses() {
return this.redirectionResponses;
}
public int clientErrorResponses() {
return this.clientErrorResponses;
}
public int serverErrorResponses() {
return this.serverErrorResponses;
}
public long processingTime() {
return this.processingTime;
}
public LocalDateTime startTime() {
return this.startTime;
}
public LocalDateTime endTime() {
return this.endTime;
}
}
|
package api.io.reader_writer;
import java.io.FileReader;
import java.io.IOException;
public class FileReaderEx {
public static void main(String[] args) {
/*
* 문자기반으로 읽어들이는 클래스는 FileReader클래스 입니다
* 2바이트 단위로 읽고쓰기 때문에 문자를 쓰기에 적합합니다.
*/
FileReader fr = null;
try {
fr = new FileReader("D:\\course\\file\\test.txt");
while(true) {
int i = fr.read();//문자를 하나씩 읽어들임
if(i ==-1)break;//읽어들일 문자가 없다면 -1을 반환
System.out.print( (char)i );//문자형 변환
}
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
fr.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
|
package com.dzh.foodrs;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
@SpringBootApplication
//@ComponentScan(basePackages={"com.dzh.foodrs.po"})
public class FOODRSApplication {
public static void main(String[] args) {
SpringApplication.run(FOODRSApplication.class, args);
}
}
|
package com.skilldistillery.blackjack;
import java.util.List;
import com.skilldistillery.cards.Card;
import com.skilldistillery.gameabstractions.Hand;
public class BlackjackHand extends Hand {
public BlackjackHand() {
super();
}
public void displayCards(String title , boolean withFaceDownCard) {
if(withFaceDownCard) {
System.out.println("\n"+ title +": > " + getVisibleHandValue());
}
else {
System.out.println("\n"+ title +": " + getHandValue());
}
int i;
for(i = 1 ; i < cardsOfHand.size(); i++) {
System.out.println("\t"+ i + ". "+ cardsOfHand.get(i));
}
if(withFaceDownCard) {
System.out.println("\t" + i + ". (facedown card)");
}
else {
System.out.println("\t"+ i + ". "+ cardsOfHand.get(0));
}
}
@Override
public int getHandValue() {
int totalValue = 0;
for(Card c : cardsOfHand) {
totalValue += c.getValue();
}
return totalValue;
}
private int getVisibleHandValue() {
int totalValue = 0;
for(int i = 1 ; i < cardsOfHand.size(); i++) {
totalValue += cardsOfHand.get(i).getValue();
}
return totalValue;
}
@Override
public void displayCards() {
for(int i = 0 ; i < cardsOfHand.size(); i++) {
System.out.println("\t"+ (i+1) + ". "+ cardsOfHand.get(i));
}
}
}
|
// Sun Certified Java Programmer
// Chapter 1, P45
// Declarations and Access Control
public class PrimitiveRanges {
public static void main(String[] args) {
System.out.println("Character.BITS == " + Character.SIZE);
System.out.println("Character.BYTES == " + Character.BYTES);
System.out.println("Character.MIN_VALUE == " + Character.MIN_VALUE);
System.out.println("Character.MAX_VALUE == " + Character.MAX_VALUE);
System.out.println();
System.out.println("Byte.BITS == " + Byte.SIZE);
System.out.println("Byte.BYTES == " + Byte.BYTES);
System.out.println("Byte.MIN_VALUE == " + Byte.MIN_VALUE);
System.out.println("Byte.MAX_VALUE == " + Byte.MAX_VALUE);
System.out.println();
System.out.println("Short.BITS == " + Short.SIZE);
System.out.println("Short.BYTES == " + Short.BYTES);
System.out.println("Short.MIN_VALUE == " + Short.MIN_VALUE);
System.out.println("Short.MAX_VALUE == " + Short.MAX_VALUE);
System.out.println();
System.out.println("Integer.BITS == " + Integer.SIZE);
System.out.println("Integer.BYTES == " + Integer.BYTES);
System.out.println("Integer.MIN_VALUE == " + Integer.MIN_VALUE);
System.out.println("Integer.MAX_VALUE == " + Integer.MAX_VALUE);
System.out.println();
System.out.println("Long.BITS == " + Long.SIZE);
System.out.println("Long.BYTES == " + Long.BYTES);
System.out.println("Long.MIN_VALUE == " + Long.MIN_VALUE);
System.out.println("Long.MAX_VALUE == " + Long.MAX_VALUE);
System.out.println();
System.out.println("Float.BITS == " + Float.SIZE);
System.out.println("Float.BYTES == " + Float.BYTES);
System.out.println("Float.MIN_VALUE == " + Float.MIN_VALUE);
System.out.println("Float.MAX_VALUE == " + Float.MAX_VALUE);
System.out.println();
System.out.println("Double.BITS == " + Double.SIZE);
System.out.println("Double.BYTES == " + Double.BYTES);
System.out.println("Double.MIN_VALUE == " + Double.MIN_VALUE);
System.out.println("Double.MAX_VALUE == " + Double.MAX_VALUE);
}
}
|
package seveida.firetvforreddit.domain.objects;
import java.util.ArrayList;
import java.util.List;
import androidx.annotation.NonNull;
import seveida.firetvforreddit.response.objects.Child;
import seveida.firetvforreddit.response.objects.SubredditResponse;
public class SubredditDetails {
@NonNull public final SubredditMetadata subredditMetadata;
@NonNull public final List<ThreadMetadata> threadMetadataList;
public SubredditDetails(@NonNull SubredditMetadata subredditMetadata,
@NonNull List<ThreadMetadata> threadMetadataList) {
this.subredditMetadata = subredditMetadata;
this.threadMetadataList = threadMetadataList;
}
public static SubredditDetails fromResponse(SubredditResponse response) {
SubredditMetadata metadata = SubredditMetadata.fromResponse(response);
List<ThreadMetadata> threads = new ArrayList<>(25);
for (Child child : response.data.children) {
threads.add(ThreadMetadata.fromResponse(child));
}
return new SubredditDetails(metadata, threads);
}
}
|
package com.example.rnztx.donors.feeds.chat;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import com.example.rnztx.donors.R;
import com.example.rnztx.donors.models.ChatMessage;
import com.example.rnztx.donors.models.utils.Constants;
import com.example.rnztx.donors.models.utils.Utilities;
import com.firebase.client.ChildEventListener;
import com.firebase.client.DataSnapshot;
import com.firebase.client.Firebase;
import com.firebase.client.FirebaseError;
import java.util.ArrayList;
import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
/**
* A simple {@link Fragment} subclass.
*/
public class ChatFragment extends Fragment {
ArrayAdapter mArrayAdapter;
private static final String LOG_TAG = ChatFragment.class.getSimpleName();
@Bind(R.id.img_send_chat_message) ImageButton imgSendChatMessage;
@Bind(R.id.edtx_new_message) EditText edtxNewMesssage;
@Bind(R.id.list_view_chats) ListView listViewChats;
ArrayList<String> mList ;
String mTargetUserId = "879322342";
Firebase mFirebaseNewMessage;
public ChatFragment() {
// Required empty public constructor
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mList = new ArrayList<>();
mArrayAdapter = new ArrayAdapter(getActivity(),R.layout.item_chat_messages,mList);
Bundle arguments = getActivity().getIntent().getExtras();
if (arguments.containsKey(Constants.EXTRA_TARGET_USERID)){
mTargetUserId = arguments.getString(Constants.EXTRA_TARGET_USERID);
}
// set target userName to Actionbar Title
getActivity().setTitle(
Utilities.userInfoMap
.get(mTargetUserId) // get UserInfo Obj
.getUserDisplayName() // get his name
);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.chat_fragment, container, false);
ButterKnife.bind(this,rootView);
listViewChats.setAdapter(mArrayAdapter);
Firebase firebase = new Firebase(Constants.FIREBASE_URL)
.child(Constants.FIREBASE_LOCATION_CHATMESSAGES);
mFirebaseNewMessage = firebase.child(Utilities.getChatId(mTargetUserId));
mFirebaseNewMessage.addChildEventListener(new ChildEventListener() {
@Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
ChatMessage incomingMessage = dataSnapshot.getValue(ChatMessage.class);
String userName = Utilities.userInfoMap.get(incomingMessage.getUserId()).getUserDisplayName();
String message = userName.split(" ")[0] + ": " +incomingMessage.getMessage();
mArrayAdapter.add(message);
}
@Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
@Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
@Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
@Override
public void onCancelled(FirebaseError firebaseError) {
}
});
return rootView;
}
@OnClick(R.id.img_send_chat_message)
public void onMessageSend(){
String newMessage = edtxNewMesssage.getText().toString();
if (!newMessage.isEmpty()){
ChatMessage newMessageObj = new ChatMessage(Utilities.getUserId(),newMessage);
String uniqueKey = mFirebaseNewMessage.push().getKey();
mFirebaseNewMessage.child(uniqueKey).setValue(newMessageObj, new Firebase.CompletionListener() {
@Override
public void onComplete(FirebaseError firebaseError, Firebase firebase) {
if (firebaseError==null){
edtxNewMesssage.setText("");
}
}
});
}
}
}
|
package com.jvmless.threecardgame.domain.game;
import java.time.LocalDateTime;
import java.util.HashSet;
import java.util.Set;
public class Results {
private Set<Result> results = new HashSet<>();
public void win(HostId hostId, GamerId gamerId) {
this.results.add(new Result(gamerId, hostId, ResultState.PLAYER_WIN_HOST_LOST, LocalDateTime.now()));
}
public void lost(HostId hostId, GamerId gamerId) {
this.results.add(new Result(gamerId, hostId, ResultState.PLAYER_LOST_HOST_WIN, LocalDateTime.now()));
}
public void draft(HostId hostId, GamerId gamerId) {
this.results.add(new Result(gamerId, hostId, ResultState.DRAFT, LocalDateTime.now()));
}
public boolean hasAny(GamerId gamerId) {
return this.results.stream().anyMatch(x -> x.getGamerId().equals(gamerId));
}
}
|
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;
import java.util.TreeMap;
class InReader {
static BufferedReader reader;
static StringTokenizer tokenizer;
/** call this method to initialize reader for InputStream */
static void init(InputStream input) {
reader = new BufferedReader(
new InputStreamReader(input) );
tokenizer = new StringTokenizer("");
}
/** get next word */
static String next() throws IOException {
while ( ! tokenizer.hasMoreTokens() ) {
//TODO add check for eof if necessary
tokenizer = new StringTokenizer(
reader.readLine() );
}
return tokenizer.nextToken();
}
static String nextLine() throws IOException
{
return reader.readLine();
}
static int nextInt() throws IOException {
return Integer.parseInt( next() );
}
static double nextDouble() throws IOException {
return Double.parseDouble( next() );
}
static float nextFloat() throws IOException {
return Float.parseFloat( next() );
}
}
public class NaiveBayes {
static int no_of_features, no_of_points;
static float accuracy = 0;
static double[][][] classifier;
static TreeMap<String, ArrayList<Integer>> classLabels;
static String[] classes;
public static void trainNB(double[][] featureMatrix, String[] labels)
{
classLabels = new TreeMap<>();
for (int i = 0; i < labels.length; i++)
{
if (!classLabels.containsKey(labels[i]))
{
ArrayList<Integer> index = new ArrayList<Integer>();
index.add(i);
classLabels.put(labels[i], index);
}
else {
classLabels.get(labels[i]).add(i);
}
}
classes = new String[classLabels.keySet().size()];
classLabels.keySet().toArray(classes);
classifier = new double[no_of_features][classLabels.size()][2]; // mean & variance
for (int i = 0; i < no_of_features; i++)
{
int k = 0;
for (Map.Entry<String, ArrayList<Integer>> entry : classLabels.entrySet())
{
ArrayList<Integer> index = entry.getValue();
double mean = 0, variance = 0;
for (int j = 0; j < index.size(); j++)
{
mean += featureMatrix[index.get(j)][i];
}
mean = mean / index.size();
for (int j = 0; j < index.size(); j++)
{
variance += Math.pow((featureMatrix[index.get(j)][i] - mean), 2);
}
variance = variance / index.size();
classifier[i][k][0] = mean;
if (Double.compare(variance, 0) == 0)
{
classifier[i][k][1] = 1;
}
else
classifier[i][k][1] = variance;
k++;
}
}
}
public static String classifyNB(double[] testPoint)
{
double[] posterior = new double[classLabels.size()];
int maxIndex = 0;
double max = 0;
for (int i = 0; i < posterior.length; i++)
{
double numerator = (double) 1 / classLabels.size();
for (int j = 0; j < testPoint.length; j++)
{
numerator *= Math.exp((-1) * Math.pow((testPoint[j] - classifier[j][i][0]), 2)) / Math.sqrt(2 * Math.PI * classifier[j][i][1]);
}
posterior[i] = numerator;
max = Math.max(posterior[i], max);
if (Double.compare(max, posterior[i]) == 0)
maxIndex = i;
}
return classes[maxIndex];
}
public static void Partition(List<String> dataset, int t)
{
String[] parts;
double[][] feature = new double[dataset.size()][no_of_features];
String[] label = new String[dataset.size()];
for (int i = 0; i < dataset.size(); i++)
{
parts = dataset.get(i).split(",");
int j;
for (j = 0; j < parts.length - 1; j++)
{
feature[i][j] = Double.parseDouble(parts[j]);
}
label[i] = parts[j];
}
if (t == 0)
trainNB(feature, label);
else
{
int correct = 0;
for (int i = 0; i < feature.length; i++)
{
if (classifyNB(feature[i]).equals(label[i]))
{
correct += 1;
}
}
accuracy += (float) correct / label.length;
System.out.println(((float) correct / label.length) * 100 + "%");
if (t == 1)
{
accuracy /= 10;
System.out.println("Overall Accuracy: " + accuracy * 100 + "%");
}
}
}
public static void Predict(List<String> dataset) throws IOException
{
String[] parts;
double[][] feature = new double[dataset.size()][no_of_features];
for (int i = 0; i < dataset.size(); i++)
{
parts = dataset.get(i).split(",");
int j;
for (j = 0; j < parts.length; j++)
{
feature[i][j] = Double.parseDouble(parts[j]);
}
}
File outFile = new File("/home/ritu/Downloads/Assignment_3/labels.txt");
FileWriter fr = new FileWriter(outFile);
String result;
int i, d = 0, r = 0;
for (i = 0; i < feature.length - 1; i++)
{
result = classifyNB(feature[i]);
if (result.equals("D"))
d++;
else if (result.equals("R"))
r++;
result += "\n";
fr.write(result);
}
result = classifyNB(feature[i]);
if (result.equals("D"))
d++;
else if (result.equals("R"))
r++;
fr.write(result);
fr.close();
System.out.println("D's = " + d + ", R's = " + r);
}
public static void main(String[] args) throws IOException
{
InReader.init(System.in);
System.out.println(".....Naive Bayes Classification.....");
System.out.print("Enter the filename (training data): ");
String filename = InReader.next();
File file = new File(filename);
BufferedReader br = new BufferedReader(new FileReader(file));
String line = br.readLine();
String[] parts = line.split(",");
no_of_features = parts.length - 1;
br.close();
br = new BufferedReader(new FileReader(file));
no_of_points = (int) br.lines().count();
br.close();
br = new BufferedReader(new FileReader(file));
List<String> dataset = new ArrayList<String>();
while ((line = br.readLine()) != null)
{
dataset.add(line);
}
int ctr = 9, L = 0;
ArrayList<ArrayList<String>> folds = new ArrayList<>();
for (int i = 0; i < 10; i++)
{
folds.add(new ArrayList<String>());
for (int j = 0; j < dataset.size()/10; j++)
{
folds.get(i).add(dataset.get(j + L));
}
L = dataset.size()/10;
}
while (ctr >= 0)
{
List<String> training = new ArrayList<String>();
List<String> test = new ArrayList<String>();
for (int i = 0; i < 10; i++)
{
if (i != ctr)
training.addAll(folds.get(i));
}
test.addAll(folds.get(ctr));
System.out.print("Model " + (10-ctr) + " - ");
Partition(training, 0);
Partition(test, ctr+1);
ctr--;
}
br.close();
System.out.print("Enter the filename (testing data): ");
filename = InReader.next();
file = new File(filename);
br = new BufferedReader(new FileReader(file));
line = br.readLine();
parts = line.split(",");
no_of_features = parts.length;
br.close();
br = new BufferedReader(new FileReader(file));
no_of_points = (int) br.lines().count();
br.close();
br = new BufferedReader(new FileReader(file));
List<String> dataset2 = new ArrayList<String>();
while ((line = br.readLine()) != null)
{
dataset2.add(line);
}
Predict(dataset2);
}
}
|
package com.techalb.composite.test;
import java.util.ArrayList;
import java.util.List;
public class Folder implements IStorageItem {
private String name;
private List<IStorageItem> children;
public Folder(String name) {
this.name = name;
this.children = new ArrayList<IStorageItem>();
}
public void addStorageItem(IStorageItem item) {
this.children.add(item);
}
@Override
public void display(String leadingSpace) {
if (leadingSpace == null)
leadingSpace = "";
System.out.printf("%s%s\n", leadingSpace, this.name);
leadingSpace += "--";
for (IStorageItem item : children)
item.display(leadingSpace);
}
}
|
/*
* Copyright (C) 2022-2023 Hedera Hashgraph, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hedera.mirror.web3.viewmodel;
import org.apache.commons.lang3.StringUtils;
public record BlockType(String name, long number) {
public static final BlockType EARLIEST = new BlockType("earliest", 0L);
public static final BlockType LATEST = new BlockType("latest", Long.MAX_VALUE);
public static final BlockType PENDING = new BlockType("pending", Long.MAX_VALUE);
private static final String HEX_PREFIX = "0x";
public static BlockType of(final String value) {
if (StringUtils.isEmpty(value) || BlockType.LATEST.name().equalsIgnoreCase(value)) {
return BlockType.LATEST;
} else if (BlockType.EARLIEST.name().equalsIgnoreCase(value)) {
return BlockType.EARLIEST;
} else if (BlockType.PENDING.name().equalsIgnoreCase(value)) {
return BlockType.PENDING;
}
int radix = 10;
var cleanedValue = value;
if (value.startsWith(HEX_PREFIX)) {
radix = 16;
cleanedValue = StringUtils.removeStart(value, HEX_PREFIX);
}
try {
long blockNumber = Long.parseLong(cleanedValue, radix);
return new BlockType(value, blockNumber);
} catch (Exception e) {
throw new IllegalArgumentException("Invalid block value: " + value, e);
}
}
}
|
/*
* 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 Memoria;
import javax.swing.JLabel;
/**
*
* @author JP
*/
public class Lista {
private LNodo Inicio;
private LNodo Fin;
public Lista()
{
Inicio = null;
Fin = null;
}
public void IngresarInicio(String nom, JLabel ima)
{
LNodo nuevo = new LNodo();
nuevo.setNombre(nom);
nuevo.setImagen(ima);
if(ListaVacia())
{
setInicio(nuevo);
setFin(nuevo);
}else{
nuevo.setSiguiente(getInicio());
getInicio().setAtras(nuevo);
setInicio(nuevo);
}
}
public void IngresarFin(String nom, JLabel ima)
{
LNodo nuevo = new LNodo();
nuevo.setNombre(nom);
nuevo.setImagen(ima);
if(ListaVacia())
{
setInicio(nuevo);
setFin(nuevo);
}else{
nuevo.setAtras(getFin());
getFin().setSiguiente(nuevo);
setFin(nuevo);
}
}
public LNodo ExtraerInicio()
{
if(ListaVacia())
{
return null;
}else{
LNodo aux = getInicio();
if(getInicio() == getFin())
{
setInicio(null);
setFin(null);
return aux;
}else{
setInicio(getInicio().getSiguiente());
getInicio().setAtras(null);
return aux;
}
}
}
public LNodo ExtraerFin()
{
if(ListaVacia())
{
return null;
}else{
LNodo aux = getFin();
if(getInicio() == getFin())
{
setInicio(null);
setFin(null);
return aux;
}else{
setFin(getFin().getAtras());
getFin().setSiguiente(null);
return aux;
}
}
}
public void Eliminar(String Nombre,int j)
{
//System.out.println("********************************************");
//System.out.println("Eliminar: ["+Nombre+","+j+"]");
LNodo aux = Inicio;
while(aux != null)
{
//System.out.println("Eliminar11: ["+aux.getNombre()+","+aux.getId()+"]");
if(aux.getNombre().equals(Nombre) && aux.getId() == j)
{
if(aux.getAtras() == null)
{
if(aux.getSiguiente() == null)
{
Inicio = Fin = aux = null;
}else{
Inicio = aux.getSiguiente();
Inicio.setAtras(null);
aux = null;
}
}else{
if(aux.getSiguiente() == null)
{
aux.getAtras().setSiguiente(null);
aux = null;
}else{
aux.getAtras().setSiguiente(aux.getSiguiente());
aux.getSiguiente().setAtras(aux.getAtras());
aux = null;
}
}
}else{
aux = aux.getSiguiente();
}
}
}
public LNodo Buscar(String Nombre,int j)
{
LNodo aux = Inicio;
LNodo tmp = null;
while(aux != null)
{
if(aux.getNombre().equals(Nombre) && aux.getId() == j)
{
tmp = aux;
}else{
aux = aux.getSiguiente();
}
}
return tmp;
}
public boolean ListaVacia()
{
return getInicio() == null;
}
public LNodo getInicio() {
return Inicio;
}
public void setInicio(LNodo Inicio) {
this.Inicio = Inicio;
}
public LNodo getFin() {
return Fin;
}
public void setFin(LNodo Fin) {
this.Fin = Fin;
}
}
|
package com.thatredhead.jmath.obj.impl.ops;
/**
* Created by JGallicchio on 3/16/2017.
*/
public class Divide {
}
|
package main.java.heap;
import main.java.objects.CachedObject;
public class HeapObject {
private long priority;
private CachedObject object;
private int index;
public HeapObject(long priority, CachedObject object, int index){
this.priority = priority;
this.object = object;
this.index = index;
}
public long getPriority() {
return priority;
}
public void setPriority(long priority) {
this.priority = priority;
}
public CachedObject getObject() {
return object;
}
public int getIndex() {
return index;
}
public void setIndex(int index) {
this.index = index;
}
}
|
package com.flutterwave.raveandroid.rave_presentation.di.ugmomo;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import javax.inject.Scope;
@Scope
@Retention(RetentionPolicy.RUNTIME)
public @interface UgScope {
}
|
/*
* 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 Clases;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
/**
*
* @author luis-d
*/
public class Cl_Compra {
Cl_Conectar con = new Cl_Conectar();
Cl_Varios ven = new Cl_Varios();
private int id;
private String fec_com;
private String fec_pag;
private String serie;
private int nro;
private int est = 1;
private int nro_filas = 0;
public Cl_Compra() {
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFec_com() {
return fec_com;
}
public void setFec_com(String fec_com) {
this.fec_com = fec_com;
}
public String getFec_pag() {
return fec_pag;
}
public void setFec_pag(String fec_pag) {
this.fec_pag = fec_pag;
}
public String getSerie() {
return serie;
}
public void setSerie(String serie) {
this.serie = serie;
}
public int getNro() {
return nro;
}
public void setNro(int nro) {
this.nro = nro;
}
public int getEst() {
return est;
}
public void setEst(int est) {
this.est = est;
}
public List le_compras(String periodo) {
List filas_compras = new ArrayList();
try {
Statement st = con.conexion();
String ver_compra = "select c.idcompra, c.periodo, c.fec_com, c.ruc_pro, p.raz_soc_pro, c.idmoneda, c.tc, c.idtido, c.serie, c.numero, "
+ "c.base, month(c.fec_com) as mes_per from compra as c inner join proveedor as p on p.ruc_pro = c.ruc_pro where c.periodo = '" + periodo + "' order by"
+ " c.idcompra asc";
ResultSet rs = con.consulta(st, ver_compra);
Object datos[] = new Object[41];
String mes_periodo, anio_periodo;
String per = periodo;
mes_periodo = per.charAt(0) + "" + per.charAt(1);
int mes = Integer.parseInt(mes_periodo);
anio_periodo = per.charAt(3) + "" + per.charAt(4) + "" + per.charAt(5) + "" + per.charAt(6);
while (rs.next()) {
Double tc = rs.getDouble("tc");
datos[0] = anio_periodo + mes_periodo + "00";
datos[1] = rs.getString("idcompra");
datos[2] = "M" + ven.ceros_izquierda(3, rs.getString("idcompra"));
datos[3] = ven.fechaformateada(rs.getString("fec_com"));
int idtido = rs.getInt("idtido");
if (idtido == 7) {
datos[4] = ven.fechaformateada(rs.getString("fec_pago"));
} else {
datos[4] = "";
}
switch (idtido) {
case 3:
datos[5] = "01";
break;
case 5:
datos[5] = "09";
break;
case 6:
datos[5] = "12";
break;
case 7:
datos[5] = "14";
break;
case 8:
datos[5] = "07";
break;
case 9:
datos[5] = "08";
break;
}
String ser_doc = rs.getString("serie");
datos[6] = ven.ceros_izquierda(4, ser_doc);
datos[7] = "0";
datos[8] = rs.getInt("numero");
datos[9] = "";
datos[10] = "6";
datos[11] = rs.getString("ruc_pro");
datos[12] = rs.getString("raz_soc_pro");
int mon = rs.getInt("idmoneda");
if (mon == 2) {
datos[13] = ven.formato_numero(rs.getDouble("base") * tc);
datos[14] = ven.formato_numero(rs.getDouble("base") * 0.18 * tc);
} else {
datos[13] = ven.formato_numero(rs.getDouble("base"));
datos[14] = ven.formato_numero(rs.getDouble("base") * 0.18);
}
datos[15] = "0.00";
datos[16] = "0.00";
datos[17] = "0.00";
datos[18] = "0.00";
datos[19] = "0.00";
datos[20] = "0.00";
datos[21] = "0.00";
if (mon == 2) {
datos[22] = ven.formato_numero(rs.getDouble("base") * 1.18 * tc);
datos[23] = "USD";
datos[24] = ven.formato_tc(tc);
} else {
datos[22] = ven.formato_numero(rs.getDouble("base") * 1.18);
datos[23] = "PEN";
datos[24] = "1.000";
}
datos[25] = "";
datos[26] = "";
datos[27] = "";
datos[28] = "";
datos[29] = "";
datos[30] = "";
datos[31] = "";
datos[32] = "";
datos[33] = "";
datos[34] = "";
datos[35] = "";
datos[36] = "";
datos[37] = "";
datos[38] = "";
datos[39] = "";
int ms_fecha = rs.getInt("mes_per");
if (ms_fecha == mes) {
datos[40] = "1";
} else {
datos[40] = "6";
}
//concatenar valores de objeto en una sola linea incluyendo los palotes
String linea;
String concat = "";
for (Object dato : datos) {
linea = dato.toString();
concat = concat.concat(linea + "|");
}
//agregar linea a arraylist;
filas_compras.add(concat);
//System.out.println(concat);
}
con.cerrar(rs);
con.cerrar(st);
} catch (SQLException | NumberFormatException e) {
System.out.println(e.getLocalizedMessage());
}
return filas_compras;
}
public void crear_lecompras(List filas, String ruc, String anio_periodo, String mes_periodo) {
int informacion = 0;
if (filas.size() > 0) {
informacion = 1;
}
String ruta = "D:\\LE" + ruc + anio_periodo + mes_periodo + "00080100001" + informacion + "11.txt";
try {
File archivo = new File(ruta);
BufferedWriter bw;
if (archivo.exists()) {
bw = new BufferedWriter(new FileWriter(archivo));
for (Object fila : filas) {
bw.write(fila.toString());
bw.newLine();
}
} else {
bw = new BufferedWriter(new FileWriter(archivo));
for (Object fila : filas) {
bw.write(fila.toString());
bw.newLine();
}
}
bw.close();
} catch (Exception e) {
System.out.println(e.getLocalizedMessage());
}
}
public void crear_lecompras_0802(String ruc, String anio_periodo, String mes_periodo) {
int informacion = 0;
String ruta = "D:\\LE" + ruc + anio_periodo + mes_periodo + "00080200001" + informacion + "11.txt";
try {
File archivo = new File(ruta);
BufferedWriter bw;
if (archivo.exists()) {
bw = new BufferedWriter(new FileWriter(archivo));
} else {
bw = new BufferedWriter(new FileWriter(archivo));
}
bw.close();
} catch (Exception e) {
System.out.println(e.getLocalizedMessage());
}
}
}
|
package com.mysql.cj.protocol.a;
import com.mysql.cj.exceptions.ExceptionFactory;
import com.mysql.cj.exceptions.WrongArgumentException;
import com.mysql.cj.protocol.ProtocolEntity;
import com.mysql.cj.protocol.ProtocolEntityFactory;
import com.mysql.cj.protocol.Resultset;
import com.mysql.cj.protocol.ResultsetRows;
import com.mysql.cj.protocol.a.result.NativeResultset;
import com.mysql.cj.protocol.a.result.OkPacket;
public class ResultsetFactory implements ProtocolEntityFactory<Resultset, NativePacketPayload> {
private Resultset.Type type = Resultset.Type.FORWARD_ONLY;
private Resultset.Concurrency concurrency = Resultset.Concurrency.READ_ONLY;
public ResultsetFactory(Resultset.Type type, Resultset.Concurrency concurrency) {
this.type = type;
this.concurrency = concurrency;
}
public Resultset.Type getResultSetType() {
return this.type;
}
public Resultset.Concurrency getResultSetConcurrency() {
return this.concurrency;
}
public Resultset createFromProtocolEntity(ProtocolEntity protocolEntity) {
if (protocolEntity instanceof OkPacket)
return (Resultset)new NativeResultset((OkPacket)protocolEntity);
if (protocolEntity instanceof ResultsetRows)
return (Resultset)new NativeResultset((ResultsetRows)protocolEntity);
throw (WrongArgumentException)ExceptionFactory.createException(WrongArgumentException.class, "Unknown ProtocolEntity class " + protocolEntity);
}
}
/* Location: C:\Users\BSV\AppData\Local\Temp\Rar$DRa6216.20396\Preview\Preview.jar!\com\mysql\cj\protocol\a\ResultsetFactory.class
* Java compiler version: 8 (52.0)
* JD-Core Version: 1.1.3
*/
|
package test;
import game.Jugador;
import game.Tablero;
public class JugadorTest {
Tablero mapa = null;
Jugador jugador = null;
Jugador segundoJugador = null;
// @Before
// public void init() {
// mapa = new Tablero(2, 2);
// mapa.crearTablero(2, 2);
// jugador = new Jugador(0, mapa, "Mario");
// segundoJugador = new Jugador(0, mapa, "Luigi");
// }
//
// @Test
// public void crearJugador() {
// assertEquals(mapa.getCasillaInicial(), jugador.getPosicionActual());
// }
//
// @Test
// public void moverJugador() {
// jugador.setNroPasos(new DadoTrucado().generar());
// assertEquals(1, jugador.getNroPasos());
// jugador.avanzar();
// assertEquals(mapa.getCasillaFinal(), jugador.getPosicionActual());
// }
//
// @Test
// public void JugadorPerdioTurno() {
// assertEquals(mapa.getCasillaInicial(), segundoJugador.getPosicionActual());
// segundoJugador.setNroPasos(1);
// segundoJugador.setFinTurno(true);
// segundoJugador.avanzar(); // Como perdio el turno se queda en el lugar
// assertEquals(mapa.getCasillaInicial(), segundoJugador.getPosicionActual());
// }
//
// @Test
// public void tirarDadoTest() {
// DadoTrucado dadoTrucado = new DadoTrucado();
// assertEquals(1, jugador.tirarDado(dadoTrucado));
// }
//
// @Test
// public void elegirCaminoTest() {
// assertTrue(true);
//// Casillero elegirCamino = jugador.elegirCamino(new Casillero(0, null, null, null, null, new Objeto(0), new Poder(0)));
//// assertEquals(new Casillero(0, null, null, null, null, new Objeto(0), new Poder(0)), elegirCamino);
// }
//
// @Test
// public void usarObjetoTest() {
// Objeto objeto = new Objeto(1);
// jugador.setObjeto(objeto);
// assertEquals(objeto, jugador.usarObjeto());
// }
//
// @Test
// public void usarPoderTest() {
// jugador.setPoder(new Poder(1));
//// assertEquals(new Poder(1).efecto(jugador), jugador.usarPoder());
// assertTrue(true);
// }
//
// @Test
// public void activarPoderTest() {
// Poder poder = new Poder(1);
// jugador.setPoder(poder);
// assertEquals(poder, jugador.activarPoder());
// }
//
// @Test
// public void accionTest() {
// assertTrue(jugador.accion());
// }
//
// @Test
// public void avanzarTest() {
// jugador.setPosicionActual(new Casillero(0, null, null, null, null, new Objeto(0), new Poder(0)));
// assertTrue(jugador.avanzar());
// }
//
// @Test
// public void activarCasillaTest() {
// //no se que tiene que hacer!
// assertTrue(true);
// }
}
|
package cn.chinaSoft.pandaMall.common.entity;
import java.sql.Timestamp;
import cn.chinaSoft.pandaMall.common.constant.Currency;
/*商品实体类*/
public class Good {
private String id;
//商品名称
private String name;
//商品图片URL
private String imgNames;
//价格
private double price;
//商品计价货币
private String currency=Currency.CNY.getName();
//产地
private String productionPlace;
//销售量
private int salesCount;
//销售额
private double salesAmount;
//产品介绍
private String introduce;
//上架时间
private Timestamp crtDate;
//最近修改时间
private Timestamp modifyDate;
//下架时间
private Timestamp unShelveDate;
//状态,0代表已下架,1代表在售
private int state;
//商品所属用户的id
private int userId;
public Good() {
super();
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getImgNames() {
return imgNames;
}
public void setImgNames(String imgNames) {
this.imgNames = imgNames;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public String getCurrency() {
return currency;
}
public void setCurrency(String currency) {
this.currency = currency;
}
public String getProductionPlace() {
return productionPlace;
}
public void setProductionPlace(String productionPlace) {
this.productionPlace = productionPlace;
}
public int getSalesCount() {
return salesCount;
}
public void setSalesCount(int salesCount) {
this.salesCount = salesCount;
}
public double getSalesAmount() {
return salesAmount;
}
public void setSalesAmount(double salesAmount) {
this.salesAmount = salesAmount;
}
public String getIntroduce() {
return introduce;
}
public void setIntroduce(String introduce) {
this.introduce = introduce;
}
public Timestamp getCrtDate() {
return crtDate;
}
public void setCrtDate(Timestamp crtDate) {
this.crtDate = crtDate;
}
public Timestamp getModifyDate() {
return modifyDate;
}
public void setModifyDate(Timestamp modifyDate) {
this.modifyDate = modifyDate;
}
public Timestamp getUnShelveDate() {
return unShelveDate;
}
public void setUnShelveDate(Timestamp unShelveDate) {
this.unShelveDate = unShelveDate;
}
public int getState() {
return state;
}
public void setState(int state) {
this.state = state;
}
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
}
|
package com.infy.surveyExpert.model;
import java.time.LocalDate;
public class Survey {
private Organizer organizer;
private Integer id;
private LocalDate startDate;
private LocalDate endDate;
private Integer status;
public Organizer getOrganizer() {
return organizer;
}
public void setOrganizer(Organizer organizer) {
this.organizer = organizer;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public LocalDate getStartDate() {
return startDate;
}
public void setStartDate(LocalDate startDate) {
this.startDate = startDate;
}
public LocalDate getEndDate() {
return endDate;
}
public void setEndDate(LocalDate endDate) {
this.endDate = endDate;
}
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
}
|
package com.rockwellcollins.atc.limp.reasoning;
import java.util.Map;
import com.rockwellcollins.atc.limp.ConstantDeclaration;
import com.rockwellcollins.atc.limp.Expr;
import com.rockwellcollins.atc.limp.IdExpr;
import com.rockwellcollins.atc.limp.VariableRef;
import com.rockwellcollins.atc.limp.reasoning.visitor.LimpMapVisitor;
public class SubForIds extends LimpMapVisitor {
private Map<VariableRef,Expr> programEnvironment;
public SubForIds(Map<VariableRef,Expr> pvsMap) {
programEnvironment = pvsMap;
}
//Note that the substitution for IdExprs will take place even if they have different types
// (e.g., InputArg versus GlobalDelcaration). I think this is fine for GatherProcedureEnvironments
// since I only put the left-hand side of assignment statements in the programEnvironment and so the
// type is unique for a given VariableRef. I should verify that this is safe though. If not, I may need
// to store the type info in the programEnvironment as well.
@Override
public Expr caseIdExpr(IdExpr id) {
if (programEnvironment.containsKey(id.getId())) {
return (Expr) programEnvironment.get(id.getId());
} else if (id.getId() instanceof ConstantDeclaration) {
ConstantDeclaration cd = (ConstantDeclaration) id.getId();
return (Expr) cd.getExpr();
}
return id;
}
}
|
package mop.main.java.backend.caching;
import java.util.HashMap;
public abstract class Cache<K, V> {
private final HashMap<K, V> map = new HashMap<>();
public void set(K key, V value) {
map.put(key, value);
}
public V get(K key) {
return map.get(key);
}
}
|
package mouse.shared;
import java.awt.*;
import java.io.Serializable;
/**
* Created by Florian on 2014-04-13. Adapted by Kevin on 20014-07-18
*/
public class Mouse implements Serializable {
//A mouse always has a position, either for simulation or for visualization
protected Point position;
//A mouse always has a orientation either for simulation or visualization
protected Orientation orientation;
//On both server and client a mouse needs an identifier to share. Mice
//can be exchanged as subset of all mice on an update and a mapping back to the
//original mouse is needed.
protected int playerIndex;
public Mouse(Point position, Orientation orientation, int playerIndex) {
this.position = position;
this.orientation = orientation;
this.playerIndex = playerIndex;
}
public Point getPosition() {
return position;
}
public Orientation getOrientation() {
return orientation;
}
public int getPlayerIndex() {
return playerIndex;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Mouse that = (Mouse) o;
if (orientation != that.orientation) {
return false;
}
if (!position.equals(that.position)) {
return false;
}
return true;
}
@Override
public int hashCode() {
int result = position.hashCode();
result = 31 * result + orientation.hashCode();
return result;
}
@Override
public String toString() {
return "MouseState{"
+ "position=" + position
+ ", orientation=" + orientation
+ '}';
}
}
|
package com.cos.services;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.cos.entities.Image;
import com.cos.entities.Product;
import com.cos.repositories.ImageRepository;
import com.cos.repositories.ProductRepository;
import com.cos.services.interfaces.ImageServiceInterface;
@Service
@Transactional
public class ImageService implements ImageServiceInterface {
@Autowired
private ImageRepository imageRepository;
@Autowired
private ProductRepository productRepository;
@Override
public Image addImage(String link, int productId, boolean main) {
// TODO Auto-generated method stub
Image image = new Image();
Product product = productRepository.findByProductId(productId);
image.setLink(link);
image.setProduct(product);
image.setMain(main);
imageRepository.save(image);
return image;
}
@Override
public List<Image> getAllImage() {
// TODO Auto-generated method stub
List<Image> listOfImage = imageRepository.findAll();
return listOfImage;
}
//ko co loi
@Override
public void changeMainImage(Image image, String newImage) {
// TODO Auto-generated method stub
List<Image> listOfImageByProductId = getImageByProductId(image.getProduct().getProductId());
imageRepository.setMainImage(newImage, true, image.getImageId());
image.setMain(true);
image.setLink(newImage);
listOfImageByProductId.remove(image);
for (Image i : listOfImageByProductId) {
imageRepository.setFixedMainFor(false, i.getImageId());
}
}
@Override
public Image getImageById(int imageId) {
// TODO Auto-generated method stub
return imageRepository.findByImageId(imageId);
}
@Override
public List<Image> getImageByProductId(Integer productId) {
// TODO Auto-generated method stub
List<Image> listOfImageByProductId = imageRepository.findByProduct(productId);
return listOfImageByProductId;
}
@Override
public void deleteImageByProduct(int productId) {
// TODO Auto-generated method stub
List<Image> listImages = imageRepository.findByProduct(productId);
for (int index = 0; index < listImages.size(); index++) {
imageRepository.delete(listImages.get(index));
}
}
}
|
/*
* This class is auto generated by https://github.com/hauner/openapi-processor-spring.
* DO NOT EDIT.
*/
package generated.api;
import generated.model.Book;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
public interface Api {
@GetMapping(
path = "/books",
produces = {"application/json"})
Flux<Book> getBooks();
@PostMapping(
path = "/books",
consumes = {"application/json"})
Mono<Void> postBooks(@RequestBody Flux<Book> body);
@GetMapping(
path = "/books/{isbn}",
produces = {"application/json"})
Mono<Book> getBooksIsbn(@PathVariable(name = "isbn") String isbn);
@PutMapping(
path = "/books/{isbn}",
consumes = {"application/json"})
Mono<Void> putBooksIsbn(@PathVariable(name = "isbn") String isbn, @RequestBody Mono<Book> body);
}
|
package com.rc.portal.webapp.model;
public class NotEnoughException extends Exception {
}
|
// assignment 9
// pair p134
// Singh, Bhavneet
// singhb
// Wang, Shiyu
// shiyu
import java.util.Comparator;
// This class represents a comparator for integers
class IntegerComparator implements Comparator<Integer> {
/* Template:
*
* Fields:
* None
*
* Methods:
* ...this.compare(Integer, Integer)... -- int
*
* Methods for Fields:
* No fields
*
*/
// compares two integers by their magnitude
public int compare(Integer first, Integer second) {
return first - second;
}
}
|
import java.util.Scanner;
public class CountAllWords {
//Write a program to count the number of words in given sentence.
///Use any non-letter character as word separator.
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
String input = reader.nextLine();
//Split the text using any non- letter characters as separator
String[] splitted = input.split("[^a-zA-Z]+");
//Get the length of the array string which is the count of words
int countOfWords = splitted.length;
System.out.println(countOfWords);
}
}
|
public class DayOne {
public static void main (String[] args) {
// #1
// Accept an isbn, name, author, price, and print the values.
printBookStuff(25, "Mary Had a Little Lamb", 250);
// #2
// Compute the quotient and remainder for a provided number
// #3
// Swap two numbers using a temporary variable;
int x = 10;
int y = 20;
int temp = x;
x = y;
y = temp;
System.out.println(y);
// #4
// Swap two numbers without using a temporary variable;
int a = 10;
int b = 20;
a = a + b; // a is 10 + 20
b = a - b; // b is 30 - 20
a = a - b; // a is 30 - 10
// #5
// Check whether an alphabet is vowel or consonant using if..else statement
char ch = 'b';
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {
System.out.println("Cha che chi cho chu");
}
else
System.out.println("It's a continent.");
// #6
// The same as #5, using a switch statement.
// *Complete on ClassLabs project
// #7
// Java Program to Check a Leap Year
int year = 1992;
boolean leap = false;
// If the year is divisible by 4
if (year % 4 == 0) {
if (year % 100 == 0) { // If the year is a century
if (year % 400 == 0) { // If the year is divisible by 400, it is a leap year
leap = true;
}
else
leap = false;
}
else
leap = true;
}
else
leap = false;
if (leap)
System.out.println(year + " is a leap year.");
else
System.out.println(year + " is NOT leap year.");
// #8
// Check if a Number is Positive or Negative using if..else
int num = 2;
if (num > 0) {
System.out.println("It is positive.");
}
else
System.out.println("It is not positive.");
// #9
// Print prime numbers between two integers
}
public static void printBookStuff(int isbn, String title, int price) {
System.out.println("The isbn is: " + isbn);
System.out.println("The title of the book is: " + title);
System.out.println("The price of the book is: " + price);
}
}
|
package dependency_inversion;
public class Main {
public static void test() {
MySQLConnection mySQLConnection = new MySQLConnection();
PasswordReminder passwordReminder = new PasswordReminder(mySQLConnection);
passwordReminder.dbConnectionInterface.connect();
}
public static void main(String[] args) {
test();
}
}
|
package com.tencent.mm.plugin.appbrand.jsapi.a;
import android.app.Activity;
import com.tencent.mm.plugin.appbrand.jsapi.a.c.17;
import com.tencent.mm.plugin.appbrand.jsapi.a.c.9;
import com.tencent.mm.plugin.appbrand.jsapi.a.c.a;
import com.tencent.mm.plugin.appbrand.s.b;
import com.tencent.mm.plugin.appbrand.s.j;
import com.tencent.mm.plugin.report.service.h;
import com.tencent.mm.protocal.c.blb;
import com.tencent.mm.sdk.platformtools.x;
class c$17$1 implements Runnable {
final /* synthetic */ blb fKr;
final /* synthetic */ 17 fKs;
c$17$1(17 17, blb blb) {
this.fKs = 17;
this.fKr = blb;
}
public final void run() {
c cVar = this.fKs.fKg;
int i = this.fKr.status;
x.i("MicroMsg.JsApiGetPhoneNumber", "handleSendVerifyCodeStatus:%d", new Object[]{Integer.valueOf(i)});
if (i == 0) {
x.i("MicroMsg.JsApiGetPhoneNumber", "startSmsListener");
if (cVar.fJZ != null) {
cVar.fJZ.cancel();
} else {
cVar.fJZ = new a(cVar);
}
cVar.fJZ.start();
if (cVar.fKa == null) {
cVar.fKa = new com.tencent.mm.plugin.ai.a(cVar.fJQ.mContext);
}
cVar.fKa.eNC = cVar.fJQ.getContentView().getResources().getStringArray(b.appbrand_sms_content);
cVar.fKa.ngW = cVar.fKf;
com.tencent.mm.plugin.appbrand.a.a(cVar.fJQ.mAppId, new 9(cVar));
boolean a = com.tencent.mm.pluginsdk.permission.a.a((Activity) cVar.fJQ.mContext, "android.permission.READ_SMS", 128, "", "");
if (a) {
com.tencent.mm.plugin.appbrand.a.pZ(cVar.fJQ.mAppId);
}
if (a) {
x.i("MicroMsg.JsApiGetPhoneNumber", "request sms permission success");
} else {
x.e("MicroMsg.JsApiGetPhoneNumber", "request sms permission fail");
}
cVar.fKa.start();
} else if (i == 1 || i != 2) {
cVar.tn(cVar.fJQ.getContentView().getResources().getString(j.app_brand_get_phone_number_send_verify_code_fail));
h.mEJ.h(14249, new Object[]{cVar.fJQ.mAppId, Integer.valueOf(1), Integer.valueOf(1), Integer.valueOf(1), Integer.valueOf(1), Integer.valueOf(cVar.fKd), Integer.valueOf(cVar.fKe), Integer.valueOf(cVar.fKc)});
} else {
cVar.tn(cVar.fJQ.getContentView().getResources().getString(j.app_brand_get_phone_number_send_verify_code_frequent));
h.mEJ.h(14249, new Object[]{cVar.fJQ.mAppId, Integer.valueOf(1), Integer.valueOf(1), Integer.valueOf(1), Integer.valueOf(1), Integer.valueOf(cVar.fKd), Integer.valueOf(cVar.fKe), Integer.valueOf(cVar.fKc)});
}
}
}
|
package com.nationsky.vote.tasks.vote.dao;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.commons.lang3.StringUtils;
import com.ds.framework.db.DataBaseUtil;
import com.ds.framework.db.TableRow;
import com.ds.framework.exception.DsFrameworkException;
import com.nationsky.vote.tasks.vote.resp.VoteItemVo;
import com.nationsky.vote.tasks.vote.util.VoteEnum;
import com.nationsky.vote.tasks.vote.vo.VtVoteInfo;
import com.nationsky.vote.tasks.vote.vo.VtVoteResult;
import com.nationsky.vote.tasks.vote.vo.VtVoteScope;
public class VoteDao {
public List<VtVoteInfo> queryUnExpiredVote(Date time) throws DsFrameworkException {
String sql
= "select id,ecid,title from mbl_vote_info where expired_state =0 and del_state =0 and expire_time <= ? ";
List<TableRow> rows = DataBaseUtil.query(sql, new Object[] {time});
List<VtVoteInfo> voteInfos = new ArrayList<VtVoteInfo>();
if (rows != null && !rows.isEmpty()) {
for (TableRow row : rows) {
String ecid = row.getField("ecid", "");
String id = row.getField("id", "");
String title = row.getField("title", "");
VtVoteInfo voteInfo = new VtVoteInfo();
voteInfo.setId(id);
voteInfo.setEcid(ecid);
voteInfo.setTitle(title);
voteInfos.add(voteInfo);
}
}
return voteInfos;
}
/**
* 获取投票信息,根据投票id
*
* @param voteid
* @throws DsFrameworkException
*/
public VtVoteInfo queryVote(String ecid, String voteid) throws DsFrameworkException {
String sql = "select * from mbl_vote_info where id=? and ecid=? and del_state=0 ";
TableRow row = DataBaseUtil.queryRow(sql, new Object[] {voteid, ecid});
if (row != null) {
String dbEcid = row.getField("ecid", "");
String id = row.getField("id", "");
String title = row.getField("title", "");
String content = row.getField("content", "");
String coverid = row.getField("coverid", "");
String creator = row.getField("creator", "");
String creatorName = row.getField("creator_name", "");
long startTime = row.getDateField("start_time", 0);
long expireTime = row.getDateField("expire_time", 0);
int voteMulti = row.getField("vote_multi", 0);
int voteMultiMin = row.getField("vote_multi_min", 1);
int voteMultiMax = row.getField("vote_multi_max", 1);
int voteAnon = row.getField("vote_anon", 0);
int voteResultPrivacy = row.getField("vote_result_privacy", 0);
int expiredState = row.getField("expired_state", 0);
int delState = row.getField("del_state", 0);
VtVoteInfo vote = new VtVoteInfo();
vote.setId(id);
vote.setEcid(dbEcid);
vote.setTitle(title);
vote.setContent(content);
vote.setCoverid(coverid);
vote.setCreator(creator);
vote.setCreatorname(creatorName);
vote.setStarttime(startTime);
vote.setExpiretime(expireTime);
vote.setVotemulti(voteMulti);
vote.setVotemultimin(voteMultiMin);
vote.setVotemultimax(voteMultiMax);
vote.setVoteanon(voteAnon);
vote.setVoteresultprivacy(voteResultPrivacy);
vote.setExpiredstate(expiredState);
if (new Date().getTime() > expireTime) {
vote.setExpiredstate(VoteEnum.Expired.getIdx());
}
vote.setDelstate(delState);
return vote;
}
return null;
}
/**
* 获取投票列表数据总数
*
* @throws DsFrameworkException
*/
public int queryVotesTotal(String ecid, long starttime, String loginId, String title) throws DsFrameworkException {
int total = 0;
TableRow row;
String cntSql = "select count(*) as cnt from mbl_vote_info v left join "
+ "( select * from mbl_vote_scope where ecid=? and userid= ? ) s on v.id = s.vote_id "
+ " where s.vote_id is not null and v.del_state=0 ";
List<Object> params = new ArrayList<Object>();
params.add(ecid);
params.add(loginId);
if (starttime > 0) {
cntSql = cntSql + " and v.start_time < ? ";
params.add(new Date(starttime));
}
if (StringUtils.isNotBlank(title)) {
cntSql = cntSql + " and v.title like ? ";
params.add("%" + title + "%");
}
row = DataBaseUtil.queryRow(cntSql, params.toArray(new Object[0]));
if (row != null) {
total = row.getField("cnt", 0);
}
return total;
}
/**
* 获取投票列表数据总数
*
* @throws DsFrameworkException
*/
public int queryVotesTotal(String ecid, long starttime, String loginId, String title, boolean my)
throws DsFrameworkException {
int total = 0;
TableRow row;
String cntSql = "select count(*) as cnt from mbl_vote_info v left join "
+ "( select * from mbl_vote_scope where ecid=? and userid= ? ) s on v.id = s.vote_id "
+ " where v.del_state=0 ";
List<Object> params = new ArrayList<Object>();
params.add(ecid);
params.add(loginId);
if (starttime > 0) {
cntSql = cntSql + " and v.start_time < ? ";
params.add(new Date(starttime));
}
if (StringUtils.isNotBlank(title)) {
cntSql = cntSql + " and v.title like ? ";
params.add("%" + title + "%");
}
if (my) {
cntSql = cntSql + " and v.creator = ? ";
params.add(loginId);
}
row = DataBaseUtil.queryRow(cntSql, params.toArray(new Object[0]));
if (row != null) {
total = row.getField("cnt", 0);
}
return total;
}
/**
* 获取投票列表数据
*
* @throws DsFrameworkException
*/
public List<VtVoteInfo> queryVotes(String ecid, long starttime, String ptitle, String loginId, int startpage,
int limit) throws DsFrameworkException {
List<TableRow> rows;
String sql = "select * from mbl_vote_info v left join "
+ "( select * from mbl_vote_scope where ecid=? and userid= ? ) s on v.id = s.vote_id "
+ " where s.vote_id is not null and v.del_state=0 ";
if (starttime > 0) {
if (StringUtils.isNotBlank(ptitle)) {
sql = sql + " and v.start_time < ?";
sql = sql + " and v.title like ? ";
sql = sql + "order by start_time desc ";
rows = DataBaseUtil.queryForLimit(sql,
new Object[] {ecid, loginId, new Date(starttime), "%" + ptitle + "%"}, startpage, limit);
} else {
sql = sql + " and v.start_time < ?";
sql = sql + "order by start_time desc ";
rows = DataBaseUtil.queryForLimit(sql, new Object[] {ecid, loginId, new Date(starttime)}, startpage,
limit);
}
} else {
if (StringUtils.isNotBlank(ptitle)) {
sql = sql + " and v.title like ? ";
sql = sql + "order by start_time desc ";
rows = DataBaseUtil.queryForLimit(sql, new Object[] {ecid, loginId, "%" + ptitle + "%"}, startpage,
limit);
} else {
sql = sql + "order by start_time desc ";
rows = DataBaseUtil.queryForLimit(sql, new Object[] {ecid, loginId}, startpage, limit);
}
}
if (rows != null) {
List<VtVoteInfo> voteInfos = new ArrayList<VtVoteInfo>();
for (TableRow row : rows) {
String dbEcid = row.getField("ecid", "");
String id = row.getField("id", "");
String title = row.getField("title", "");
String content = row.getField("content", "");
String coverid = row.getField("coverid", "");
String creator = row.getField("creator", "");
String creatorName = row.getField("creator_name", "");
long startTime = row.getDateField("start_time", 0);
long expireTime = row.getDateField("expire_time", 0);
int voteMulti = row.getField("vote_multi", 0);
int voteMultiMin = row.getField("vote_multi_min", 1);
int voteMultiMax = row.getField("vote_multi_max", 1);
int voteAnon = row.getField("vote_anon", 0);
int voteResultPrivacy = row.getField("vote_result_privacy", 0);
int expiredState = row.getField("expired_state", 0);
int delState = row.getField("del_state", 0);
int voted = row.getField("voted", 0);
VtVoteInfo vote = new VtVoteInfo();
vote.setId(id);
vote.setEcid(dbEcid);
vote.setTitle(title);
vote.setContent(content);
vote.setCoverid(coverid);
vote.setCreator(creator);
vote.setCreatorname(creatorName);
vote.setStarttime(startTime);
vote.setExpiretime(expireTime);
vote.setVotemulti(voteMulti);
vote.setVotemultimin(voteMultiMin);
vote.setVotemultimax(voteMultiMax);
vote.setVoteanon(voteAnon);
vote.setVoteresultprivacy(voteResultPrivacy);
vote.setExpiredstate(expiredState);
if (new Date().getTime() > expireTime) {
vote.setExpiredstate(VoteEnum.Expired.getIdx());
}
vote.setDelstate(delState);
vote.setVoted(voted);
voteInfos.add(vote);
}
return voteInfos;
}
return null;
}
/**
* 获取投票列表数据
*
* @throws DsFrameworkException
*/
public List<VtVoteInfo> queryVotes(String ecid, long starttime, String ptitle, String loginId, int startpage,
int limit, boolean my) throws DsFrameworkException {
List<TableRow> rows;
String sql = "select * from mbl_vote_info v left join "
+ "( select * from mbl_vote_scope where ecid=? and userid= ? ) s on v.id = s.vote_id "
+ " where v.del_state=0 ";
List<Object> params = new ArrayList<Object>();
params.add(ecid);
params.add(loginId);
if (starttime > 0) {
sql = sql + " and v.start_time < ?";
params.add(new Date(starttime));
}
if (StringUtils.isNotBlank(ptitle)) {
sql = sql + " and v.title like ? ";
params.add("%" + ptitle + "%");
}
if (my) {
sql = sql + " and v.creator = ? ";
params.add(loginId);
}
sql = sql + "order by v.start_time desc ";
rows = DataBaseUtil.queryForLimit(sql, params.toArray(new Object[0]), startpage, limit);
if (rows != null) {
List<VtVoteInfo> voteInfos = new ArrayList<VtVoteInfo>();
for (TableRow row : rows) {
String dbEcid = row.getField("ecid", "");
String id = row.getField("id", "");
String title = row.getField("title", "");
String content = row.getField("content", "");
String coverid = row.getField("coverid", "");
String creator = row.getField("creator", "");
String creatorName = row.getField("creator_name", "");
long startTime = row.getDateField("start_time", 0);
long expireTime = row.getDateField("expire_time", 0);
int voteMulti = row.getField("vote_multi", 0);
int voteMultiMin = row.getField("vote_multi_min", 1);
int voteMultiMax = row.getField("vote_multi_max", 1);
int voteAnon = row.getField("vote_anon", 0);
int voteResultPrivacy = row.getField("vote_result_privacy", 0);
int expiredState = row.getField("expired_state", 0);
int delState = row.getField("del_state", 0);
int voted = row.getField("voted", 1);
VtVoteInfo vote = new VtVoteInfo();
vote.setId(id);
vote.setEcid(dbEcid);
vote.setTitle(title);
vote.setContent(content);
vote.setCoverid(coverid);
vote.setCreator(creator);
vote.setCreatorname(creatorName);
vote.setStarttime(startTime);
vote.setExpiretime(expireTime);
vote.setVotemulti(voteMulti);
vote.setVotemultimin(voteMultiMin);
vote.setVotemultimax(voteMultiMax);
vote.setVoteanon(voteAnon);
vote.setVoteresultprivacy(voteResultPrivacy);
vote.setExpiredstate(expiredState);
if (new Date().getTime() > expireTime) {
vote.setExpiredstate(VoteEnum.Expired.getIdx());
}
vote.setDelstate(delState);
vote.setVoted(voted);
voteInfos.add(vote);
}
return voteInfos;
}
return null;
}
/**
* 获取投票选项人员信息
*
* @param voteid
* @param loginId
* @throws DsFrameworkException
*/
public List<VoteItemVo> queryNoInvolvedItems(String voteid, int startpage, int limit) throws DsFrameworkException {
StringBuffer buf
= new StringBuffer("select m.*,s.cnt,s.voter,s.vote_type,s.vote_time from mbl_vote_item m left join ( ");
buf.append(
"select r.item_id ,count(r.item_id) as cnt,r.voter,r.vote_type,r.vote_time from mbl_vote_result r where r.vote_id = ?");
buf.append(" group by r.item_id,r.voter,r.vote_type,r.vote_time order by r.vote_time desc limit 0,? ");
buf.append(") s on m.id = s.item_id where m.vote_id = ? order by m.item_seq asc ");
List<TableRow> rows = DataBaseUtil.query(buf.toString(), new Object[] {voteid, limit, voteid});
if (rows != null) {
List<VoteItemVo> itemVos = new ArrayList<VoteItemVo>();
for (TableRow row : rows) {
VoteItemVo itemVo = new VoteItemVo();
String id = row.getField("id", "");
String vote_id = row.getField("vote_id", "");
String content = row.getField("content", "");
String coverid = row.getField("coverid", "");
int itemseq = row.getField("item_seq", 0);
int cnt = row.getField("cnt", 0);
String voter = row.getField("voter", "");
int vote_type = row.getField("vote_type", 0);
long vote_time = row.getDateField("vote_time", 0);
itemVo.setId(id);
itemVo.setVoteid(vote_id);
itemVo.setContent(content);
itemVo.setCoverid(coverid);
itemVo.setItemseq(itemseq);
itemVo.setItemtotal(cnt);
itemVo.setVoter(voter);
itemVo.setVotetype(vote_type);
itemVo.setVotetime(vote_time);
itemVos.add(itemVo);
}
return itemVos;
}
return null;
}
/**
* 获取投票选项信息
*
* @param voteid
* @param loginId
* @throws DsFrameworkException
*/
public List<VoteItemVo> queryVoteItems(String voteid, String loginId) throws DsFrameworkException {
StringBuffer buf = new StringBuffer("select m.* from mbl_vote_item m,mbl_vote_info v ");
buf.append(" where m.vote_id = ? and m.vote_id=v.id and v.del_state=0 order by m.item_seq asc ");
List<TableRow> rows = DataBaseUtil.query(buf.toString(), new Object[] {voteid});
if (rows != null) {
List<VoteItemVo> itemVos = new ArrayList<VoteItemVo>();
for (TableRow row : rows) {
VoteItemVo itemVo = new VoteItemVo();
String id = row.getField("id", "");
String vote_id = row.getField("vote_id", "");
String content = row.getField("content", "");
String coverid = row.getField("coverid", "");
int itemseq = row.getField("item_seq", 0);
itemVo.setId(id);
itemVo.setVoteid(vote_id);
itemVo.setContent(content);
itemVo.setCoverid(coverid);
itemVo.setItemseq(itemseq);
itemVos.add(itemVo);
}
return itemVos;
}
return null;
}
/**
* 获取选票结果
*
* @param voteid
* @return
* @throws DsFrameworkException
*/
public int queryVoteResultTotal(String itemid, int anon) throws DsFrameworkException {
StringBuffer buf = new StringBuffer("select count(*) as cnt from mbl_vote_result r where r.item_id = ? ");
TableRow row;
List<Object> params = new ArrayList<Object>();
params.add(itemid);
if (anon == 1 || anon == 0) {
buf.append(" and r.vote_type=? ");
params.add(anon);
row = DataBaseUtil.queryRow(buf.toString(), params.toArray(new Object[0]));
} else {
row = DataBaseUtil.queryRow(buf.toString(), params.toArray(new Object[0]));
}
if (row != null) {
int cnt = row.getField("cnt", 0);
return cnt;
}
return 0;
}
/**
* 获取未投票总数
*
* @param voteid
* @return
* @throws DsFrameworkException
*/
public int queryNotVoteUserTotal(String voteid) throws DsFrameworkException {
StringBuffer buf
= new StringBuffer("select count(*) as cnt from mbl_vote_scope r where r.voted = 0 and r.vote_id = ? ");
TableRow row;
List<Object> params = new ArrayList<Object>();
params.add(voteid);
row = DataBaseUtil.queryRow(buf.toString(), params.toArray(new Object[0]));
if (row != null) {
int cnt = row.getField("cnt", 0);
return cnt;
}
return 0;
}
/**
* 获取未投票总数
*
* @param voteid
* @param limit
* @param startpage
* @return
* @throws DsFrameworkException
*/
public List<String> queryNotVoteUser(String voteid, int startpage, int limit) throws DsFrameworkException {
StringBuffer buf = new StringBuffer(
"select r.userid from mbl_vote_scope r where r.voted = 0 and r.vote_id = ? order by r.userid asc");
List<TableRow> rows = DataBaseUtil.queryForLimit(buf.toString(), new Object[] {voteid}, startpage, limit);
List<String> loginIds = new ArrayList<String>();
if (rows != null && !rows.isEmpty()) {
for (TableRow row : rows) {
loginIds.add(row.getField("userid", ""));
}
}
return loginIds;
}
/**
* 获取选票结果
*
* @param voteid
* @return
* @throws DsFrameworkException
*/
public Map<String, List<VtVoteResult>> queryVoteResult(String itemid, long timestamp, int startpage, int limit)
throws DsFrameworkException {
StringBuffer buf = new StringBuffer(
"select r.vote_id,r.item_id ,r.vote_time,r.voter,r.vote_type from mbl_vote_result r where r.item_id = ? and r.vote_type = 1 ");
List<TableRow> rows;
List<Object> params = new ArrayList<Object>();
params.add(itemid);
if (timestamp != 0) {
buf.append(" and r.vote_time < ? ");
params.add(new Date(timestamp));
}
if (startpage == 0) {
buf.append(" order by r.vote_time desc ");
buf.append(" limit 0,? ");
params.add(limit);
rows = DataBaseUtil.query(buf.toString(), params.toArray(new Object[0]));
} else {
buf.append(" order by r.vote_time desc ");
rows = DataBaseUtil.queryForLimit(buf.toString(), params.toArray(new Object[0]), startpage, limit);
}
if (rows != null) {
Map<String, List<VtVoteResult>> itemVoMaps = new HashMap<String, List<VtVoteResult>>();
for (TableRow row : rows) {
VtVoteResult itemVo = new VtVoteResult();
String voteid = row.getField("vote_id", "");
String voter = row.getField("voter", "");
long votetime = row.getDateField("vote_time", 0);
int votetype = row.getField("vote_type", 0);
itemVo.setVoteid(voteid);
itemVo.setItemid(itemid);
itemVo.setVoter(voter);
itemVo.setVotetime(votetime);
itemVo.setVotetype(votetype);
if (itemVoMaps.containsKey(itemid)) {
itemVoMaps.get(itemid).add(itemVo);
} else {
List<VtVoteResult> itemVos = new ArrayList<VtVoteResult>();
itemVos.add(itemVo);
itemVoMaps.put(itemid, itemVos);
}
}
return itemVoMaps;
}
return null;
}
/**
* 获取选票结果
*
* @param voteid
* @return
* @throws DsFrameworkException
*/
public Map<String, List<VtVoteResult>> queryVoteResult(String voteid) throws DsFrameworkException {
StringBuffer buf = new StringBuffer(
"select r.item_id ,r.vote_time,r.voter,r.vote_type from mbl_vote_result r where r.vote_id = ?");
List<TableRow> rows = DataBaseUtil.query(buf.toString(), new Object[] {voteid});
if (rows != null) {
Map<String, List<VtVoteResult>> itemVoMaps = new HashMap<String, List<VtVoteResult>>();
for (TableRow row : rows) {
VtVoteResult itemVo = new VtVoteResult();
String itemid = row.getField("item_id", "");
String voter = row.getField("voter", "");
long votetime = row.getDateField("vote_time", 0);
int votetype = row.getField("vote_type", 0);
itemVo.setVoteid(voteid);
itemVo.setItemid(itemid);
itemVo.setVoter(voter);
itemVo.setVotetime(votetime);
itemVo.setVotetype(votetype);
if (itemVoMaps.containsKey(itemid)) {
itemVoMaps.get(itemid).add(itemVo);
} else {
List<VtVoteResult> itemVos = new ArrayList<VtVoteResult>();
itemVos.add(itemVo);
itemVoMaps.put(itemid, itemVos);
}
}
return itemVoMaps;
}
return null;
}
/**
* 获取投票范围状态
*
* @param voteid
* @param loginId
* @throws DsFrameworkException
*/
public VtVoteScope queryVoteScope(String voteid, String loginId) throws DsFrameworkException {
String sql = "select * from mbl_vote_scope where vote_id=? and userid=? ";
TableRow row = DataBaseUtil.queryRow(sql, new Object[] {voteid, loginId});
if (row != null) {
String ecid = row.getField("ecid", "");
String voteId = row.getField("vote_id", "");
String userid = row.getField("userid", "");
int voted = row.getField("voted", 0);
VtVoteScope scp = new VtVoteScope();
scp.setEcid(ecid);
scp.setUserid(userid);
scp.setVoteid(voteId);
scp.setVoted(voted);
return scp;
}
return null;
}
/**
* 检验投票id和选项id是否匹配
*
* @param voteid
* @throws DsFrameworkException
*/
public boolean checkVoteItemExist(String voteid, String[] itemids) throws DsFrameworkException {
String sql = "select m.id as id from mbl_vote_info v left join mbl_vote_item m on v.id=m.vote_id where v.id=? ";
List<TableRow> rows = DataBaseUtil.query(sql, new Object[] {voteid});
if (rows != null) {
Set<String> items = new HashSet<String>();
for (TableRow row : rows) {
items.add(row.getField("id", ""));
}
for (String item : itemids) {
if (!items.contains(item)) {
return false;
}
}
return true;
}
return false;
}
/**
* 检验选项id是否存在
*
* @param voteid
* @throws DsFrameworkException
*/
public boolean checkVoteItemExist(String itemid) throws DsFrameworkException {
String sql
= "select m.id as id from mbl_vote_info v left join mbl_vote_item m on v.id=m.vote_id where m.id=? and v.del_state = 0";
List<TableRow> rows = DataBaseUtil.query(sql, new Object[] {itemid});
if (rows != null && !rows.isEmpty()) {
return true;
}
return false;
}
/**
* 删除投票
*
* @param voteid
* @throws DsFrameworkException
*/
public void deleteVote(String voteid) throws DsFrameworkException {
String sql = "update mbl_vote_info set expired_state = 1, del_state = 1, expire_time =? where id = ?";
DataBaseUtil.update(sql, new Object[] {new Date(), voteid});
}
/**
* 关闭投票
*
* @param voteid
* @throws DsFrameworkException
*/
public void closeVote(String voteid) throws DsFrameworkException {
String sql = "update mbl_vote_info set expired_state = 1, expire_time =? where id = ?";
DataBaseUtil.update(sql, new Object[] {new Date(), voteid});
}
/**
* 更新投票状态
*
* @throws DsFrameworkException
*/
public void updateVoteStatus(Date time) throws DsFrameworkException {
String sql
= "update mbl_vote_info set expired = 1, expire_time =? where expired_state =0 and del_state =0 and expire_time <= ?";
DataBaseUtil.update(sql, new Object[] {time, time});
}
}
|
package com.backend.SecondProject;
import static org.junit.Assert.assertTrue;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import com.TokChatBackend.config.DBconfg;
/**
* Unit test for simple App.
*/
public class AppTest
{
@BeforeClass
public static void init(){
AnnotationConfigApplicationContext context=new AnnotationConfigApplicationContext();
context.register(DBconfg.class);
context.refresh();
}
@Test
@Ignore
public void test(){
}
}
|
package edu.uci.ics.sdcl.firefly.report.predictive;
import java.util.Date;
import java.util.HashMap;
import java.util.TreeMap;
import edu.uci.ics.sdcl.firefly.report.descriptive.Filter;
/**
* Class responsible to keep the multiple filter combinations and the respective outcome of
* computing predictors with the data produced by a concrete filter combination.
*
* @author adrianoc
*
*/
public class FilterCombination {
public static final String ANSWER_DURATION = "ANSWER DURATION RANGE";
public static final String SESSION_DURATION = "SESSION DURATION RANGE";
public static final String CONFIDENCE_LEVEL = "CONFIDENCE LEVEL RANGE";
public static final String DIFFICULTY_LEVEL = "DIFFICULTY LEVEL RANGE";
public static final String WORKER_SCORE = "WORKER SCORE RANGE";
public static final String WORKER_SCORE_EXCLUSION = "WORKER SCORES EXCLUDED"; //List of professions to be considered
public static final String EXPLANATION_SIZE = "EXPLANATION SIZE RANGE";
public static final String WORKER_IDK = "WORKER %IDK RANGE";
public static final String WORKER_PROFESSION = "WORKER PROFESSION"; //List of professions to be considered.
public static final String WORKER_YEARS_OF_EXEPERIENCE = "WORKER YEARS OF EXPERIENCE"; //List of professions to be considered.
public static final String FIRST_ANSWER_DURATION = "FIRST_ANSWER_DURATION";
public static final String SECOND_THIRD_ANSWER_DURATION = "SECOND_THIRD_ANSWER_DURATION";
public static final String CONFIDENCE_DIFFICULTY_PAIRS = "CONFIDENCE_DIFFICULTY_PAIRS";
public static final String EXCLUDED_QUESTIONS = "EXCLUDED_QUESTIONS";
public static final String FIRST_HOURS = "FIRST_HOURS";
public static final String MAX_ANSWERS = "MAX_ANSWERS";
public HashMap<String,Range> combinationMap = new HashMap<String,Range>();
//-----------------------------------------------------------------------------------------------------
//FOR REPORT GENERATION
public static String[] headerList = {
FIRST_ANSWER_DURATION,
SECOND_THIRD_ANSWER_DURATION,
CONFIDENCE_LEVEL,
DIFFICULTY_LEVEL,
EXPLANATION_SIZE,
WORKER_SCORE_EXCLUSION,
WORKER_SCORE,
WORKER_IDK,
WORKER_PROFESSION,
WORKER_YEARS_OF_EXEPERIENCE,
CONFIDENCE_DIFFICULTY_PAIRS,
EXCLUDED_QUESTIONS,
FIRST_HOURS,
MAX_ANSWERS
};
public static String getFilterHeaders(){
String result="";
for(String name:headerList){
if(result.length()==0)
result = name+",";
else
result = result + name+",";
}
return result;
}
public String toString(String[] headerList){
String result="";
for(String name : headerList){
Range range = combinationMap.get(name);
//System.out.println(name);
if(result.length()==0)
result = range.toString();
else
result = result+","+range.toString();
}
return result;
}
public void addFilterParam(String filterName, int max, int min){
if(combinationMap==null)
combinationMap = new HashMap<String, Range>();
combinationMap.put(filterName, new Range(min,max));
}
public Range getFilterParam(String filterName){
return this.combinationMap.get(filterName);
}
/** Instantiates a filter with the combined configurations */
public Filter getFilter(){
Filter filter = new Filter();
for(String filterName: this.combinationMap.keySet()){
int min=-1;
int max=-1;
if(this.combinationMap.get(filterName).min!=null){
min = this.combinationMap.get(filterName).min.intValue();
max = this.combinationMap.get(filterName).max.intValue();
}
if(filterName.compareTo(FilterCombination.FIRST_ANSWER_DURATION)==0){
Range range = this.combinationMap.get(filterName);
filter.setFirstAnswerDurationCriteria(range.minD.doubleValue(), range.maxD.doubleValue());
}
else
if(filterName.compareTo(FilterCombination.SECOND_THIRD_ANSWER_DURATION)==0){
Range range = this.combinationMap.get(filterName);
filter.setSecondThirdAnswerDurationCriteria(range.minD.doubleValue(), range.maxD.doubleValue());
}
else
if(filterName.compareTo(FilterCombination.SESSION_DURATION)==0){
filter.setSessionDurationCriteria(new Double(min), new Double(max));
}
else
if(filterName.compareTo(FilterCombination.CONFIDENCE_LEVEL)==0){
filter.setConfidenceCriteria(min, max);
}
else
if(filterName.compareTo(FilterCombination.DIFFICULTY_LEVEL)==0){
filter.setDifficultyCriteria(min, max);
}
else
if(filterName.compareTo(FilterCombination.EXPLANATION_SIZE)==0){
filter.setExplanationSizeCriteria(min, max);
}
else
if(filterName.compareTo(FilterCombination.WORKER_SCORE)==0){
filter.setWorkerScoreCriteria(min, max);
}
else
if(filterName.compareTo(FilterCombination.WORKER_SCORE_EXCLUSION)==0){
filter.setWorkerScoreExclusionList(this.combinationMap.get(filterName).list);
}
else
if(filterName.compareTo(FilterCombination.WORKER_IDK)==0){
filter.setIDKPercentageCriteria(new Double(min), new Double(max));
}
else
if(filterName.compareTo(FilterCombination.WORKER_PROFESSION)==0){
filter.setWorkerProfessionMap(this.combinationMap.get(filterName).professionExclusionList);
}
else
if(filterName.compareTo(FilterCombination.WORKER_YEARS_OF_EXEPERIENCE)==0){
Range range = this.combinationMap.get(filterName);
filter.setYearsOfExperience(range.minD, range.maxD);
}
else
if(filterName.compareTo(FilterCombination.CONFIDENCE_DIFFICULTY_PAIRS)==0){
Range range = this.combinationMap.get(filterName);
filter.setConfidenceDifficultyPairList(range.confidenceDifficultyPairMap);
}
else
if(filterName.compareTo(FilterCombination.EXCLUDED_QUESTIONS)==0){
Range range = this.combinationMap.get(filterName);
filter.setQuestionToExcludeMap(range.questionsToExcludeMap);
}
else
if(filterName.compareTo(FilterCombination.FIRST_HOURS)==0){
Range range = this.combinationMap.get(filterName);
filter.setStartEndDates(range.startEndDates);
}
else
if(filterName.compareTo(FilterCombination.MAX_ANSWERS)==0){
Range range = this.combinationMap.get(filterName);
filter.setMaxAnswers(range.max.intValue());
}
}
return filter;
}
public void addFilterParam(String workerScoreExclusion,
int[] workerScoreExclusionList) {
if(combinationMap==null)
combinationMap = new HashMap<String, Range>();
combinationMap.put(workerScoreExclusion, new Range(workerScoreExclusionList));
}
public void addFilterParam(String workerProfession, String[] workerProfessionList) {
if(combinationMap==null)
combinationMap = new HashMap<String, Range>();
combinationMap.put(workerProfession, new Range(workerProfessionList));
}
public void addFilterParam(String workerYearsOfExeperienceProfession,
double maxYearsOfExperience, double minYearsOfExperience) {
if(combinationMap==null)
combinationMap = new HashMap<String, Range>();
combinationMap.put(workerYearsOfExeperienceProfession, new Range(minYearsOfExperience,maxYearsOfExperience));
}
public void addFilterParam(String confidenceDifficultyPairs,
HashMap<String,Tuple> confidenceDifficultyPairMap) {
if(combinationMap==null)
combinationMap = new HashMap<String, Range>();
combinationMap.put(confidenceDifficultyPairs, new Range(confidenceDifficultyPairMap));
}
public void addFilterParam(String questionExclusion,
TreeMap<String,String> questionToExcludeMap) {
if(combinationMap==null)
combinationMap = new HashMap<String, Range>();
combinationMap.put(questionExclusion, new Range(questionToExcludeMap));
}
public void addFilterParam(String firstHours, Date maxDate, Date minDate) {
if(combinationMap==null)
combinationMap = new HashMap<String, Range>();
combinationMap.put(firstHours, new Range(maxDate, minDate));
}
}
|
package com.ccxia.cbcraft.item;
import com.ccxia.cbcraft.CbCraft;
import com.ccxia.cbcraft.creativetab.CreativeTabsCbCraft;
import net.minecraft.item.Item;
public class ItemEggMilkDough extends Item {
public ItemEggMilkDough() {
this.setUnlocalizedName(CbCraft.MODID + ".eggMilkDough");
this.setRegistryName("egg_milk_dough");
this.setCreativeTab(CreativeTabsCbCraft.tabCbCraft);
}
}
|
package edu.gatech.cs2340.spacetraders.views;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
import edu.gatech.cs2340.spacetraders.R;
import edu.gatech.cs2340.spacetraders.entity.City;
import edu.gatech.cs2340.spacetraders.entity.Planet;
import edu.gatech.cs2340.spacetraders.entity.Player;
import edu.gatech.cs2340.spacetraders.entity.SpaceShip;
/**
* planet adapter to display all planets in home screen
*/
public class PlanetAdapter extends RecyclerView.Adapter<PlanetAdapter.CityViewHolder> {
private List<City> cityList = new ArrayList<>();
private Player player;
private OnTravelClickListener listener;
private Planet planet;
private SpaceShip ship;
@NonNull
@Override
public CityViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int i) {
//Tell the adapter what layout to use for each course in the list
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.city_item, parent, false);
return new CityViewHolder(itemView);
}
@Override
public void onBindViewHolder(@NonNull CityViewHolder holder, int position) {
/* When the list needs to display a city it will call this method and pass the
position in the list it needs and a view holder for that position
*/
//get the city located at this position
City city = cityList.get(position);
//now use the view holder to set the appropriate information
holder.name.setText(new StringBuilder("City: ").append(city.getName()));
holder.location.setText(new StringBuilder("Location On Planet: " )
.append(city.getLocation().toString()));
if ((player.getCoordinates().get(0) < 0) || (player.getCoordinates().get(1) < 0)){
holder.travel.setText(new StringBuilder("Travel To This Planet And City"));
} else if (player.getCurrentPlanet().equals(planet.getName()) &&
player.getLocation().equals(city.getLocation())) {
holder.travel.setText(new StringBuilder("Visit Marketplace"));
} else if (player.getCurrentPlanet().equals(planet.getName())){
holder.travel.setText(new StringBuilder("Travel To This City"));
} else if (ship.getFuel() < 5) {
holder.travel.setText(new StringBuilder("You Do Not Have Enough Fuel"));
} else {
holder.travel.setText(new StringBuilder("Travel To This Planet And City"));
}
}
@Override
public int getItemCount() {
if (cityList == null) {
return 0;
}
return cityList.size();
}
void setCityList(List<City> cities) {
cityList = cities;
notifyDataSetChanged();
}
/**
* setter for player
* @param player player info
*/
public void setPlayer(Player player) {
this.player = player;
notifyDataSetChanged();
}
/**
* setter for planet
* @param planet planet info
*/
public void setPlanet(Planet planet) {
this.planet = planet;
notifyDataSetChanged();
}
/**
* setter for ship
* @param ship spaceship info
*/
public void setShip (SpaceShip ship) {
this.ship = ship;
}
class CityViewHolder extends RecyclerView.ViewHolder {
//View holder needs reference to each widget in the individual item in the list
private final TextView name;
private final TextView location;
private final Button travel;
/**
* Construct a new view holder, grab all the widget references and setup the
* listener to detect a click on this item.
*
* @param itemView the current view
*/
CityViewHolder(@NonNull View itemView) {
super(itemView);
name = itemView.findViewById(R.id.name);
location = itemView.findViewById(R.id.location);
travel = itemView.findViewById(R.id.travelButton);
travel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
int position = getAdapterPosition();
if ((listener != null) && (position != RecyclerView.NO_POSITION)) {
listener.onTravelClicked(cityList.get(position));
}
}
});
}
}
/**
* class to allow planet to be clicked on to set action
*/
public interface OnTravelClickListener {
/**
* travel to a city button
* @param city city to travel to
*/
void onTravelClicked(City city);
}
void setOnTravelClickListener(OnTravelClickListener listener) {
this.listener = listener;
}
}
|
package com.netease.course.aspect;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
/**
* @author menglanyingfei
* @date 2017-8-26
*/
@Aspect
public class LoggingAspect {
/**
* 正常返回时调用
*
* @param jp调用点信息
*/
@AfterReturning("execution(* com.netease.course.service.*.*(..))")
public void loggindAfterReturning(JoinPoint jp) {
String className = jp.getSignature().getDeclaringTypeName();
String methodName = jp.getSignature().getName();
System.out.print("正常返回Logging:调用" + className + "的" + methodName
+ "方法, 参数为:");
for (Object obj : jp.getArgs()) {
System.out.print(obj.toString());
}
System.out.println("");
}
/**
* 抛出异常返回时调用
*
* @param jp
* 调用点信息
* @param ex
* 异常信息
*/
@AfterThrowing(pointcut = "execution(* com.netease.course.service.*.*(..))", throwing = "ex")
public void loggingAfterThrowing(JoinPoint jp, Exception ex) {
String className = jp.getSignature().getDeclaringTypeName();
String methodName = jp.getSignature().getName();
System.out.print("异常Logging:调用" + className + "的" + methodName + "方法, 参数为:");
for (Object obj : jp.getArgs()) {
System.out.print(obj.toString());
}
System.out.println("。抛出异常:" + ex.getMessage() + "!");
}
}
|
package br.ufs.livraria.dao;
import javax.ejb.Stateless;
import br.ufs.livraria.modelo.Funcionario;
@Stateless
public class FuncionarioDAO extends DAO<Funcionario> {
private static final long serialVersionUID = 1L;
public FuncionarioDAO() {
super(Funcionario.class);
}
}
|
/*
package com.jpa.dao.impl;
import com.jpa.dao.BaseJpaDao;
import com.jpa.filter.FilterConverter;
import com.jpa.filter.FilterItem;
import com.jpa.filter.Order;
import com.jpa.operator.FilterOperator;
import com.jpa.operator.OrderOperator;
import com.jpa.query.Filters;
import com.jpa.query.Query;
import com.jpa.utils.StringUtil;
import org.apache.log4j.Logger;
import org.hibernate.Criteria;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.criterion.Example;
import org.hibernate.criterion.MatchMode;
import org.hibernate.transform.Transformers;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Tuple;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import javax.persistence.criteria.Selection;
import java.util.*;
public class BaseJpaDaoImpl implements BaseJpaDao {
public static final Logger logger = Logger.getLogger(BaseJpaDaoImpl.class);
@PersistenceContext(
unitName = "entityManagerFactory"
)
private EntityManager em;
public BaseJpaDaoImpl() {
}
public <T> T find(Class<T> clazz, Object id) {
return this.getEm().find(clazz, id);
}
public <T> List<T> findAllByExample(T pojo, FilterOperator filterOperator) {
return this.findAllByExample(pojo, (List)(new ArrayList()), filterOperator);
}
public <T> List<T> findAllByExample(T pojo, Order order, FilterOperator filterOperator) {
ArrayList<Order> orders = new ArrayList();
if (order != null) {
orders.add(order);
}
return this.findAllByExample(pojo, (List)orders, filterOperator);
}
public <T> List<T> findAllByExample(T pojo, List<Order> orders, FilterOperator filterOperator) {
Session session = (Session)this.getEm().getDelegate();
Example example = Example.create(pojo).excludeZeroes();
if (FilterOperator.LIKE.equals(filterOperator)) {
example.enableLike();
} else if (FilterOperator.LEFTLIKE.equals(filterOperator)) {
example.enableLike(MatchMode.START);
}
if (FilterOperator.RIGHTLIKE.equals(filterOperator)) {
example.enableLike(MatchMode.END);
}
Criteria criteria = session.createCriteria(pojo.getClass()).add(example);
if (orders != null) {
Iterator iterator = orders.iterator();
while(iterator.hasNext()) {
Order tmp = (Order)iterator.next();
if (tmp.getOrderOperator().equals(OrderOperator.ASC)) {
criteria.addOrder(org.hibernate.criterion.Order.asc(tmp.getField()));
} else if (tmp.getOrderOperator().equals(OrderOperator.DESC)) {
criteria.addOrder(org.hibernate.criterion.Order.desc(tmp.getField()));
}
}
}
return criteria.list();
}
public <T> List<T> find(Class<T> clazz, FilterOperator op, String field, Object value) {
Query query = Query.from(clazz);
query.filter(op, field, value);
return this.findAll(query);
}
public void flush() {
this.getEm().flush();
}
public <T> T save(T t) {
if (t instanceof ICreateEntity && ((ICreateEntity)t).getCreatedTime() == null) {
((ICreateEntity)t).setCreatedTime(new Date());
}
if (t instanceof IRemovable && (((IRemovable)t).getIsRemoved() == null || "".equals(((IRemovable)t).getIsRemoved()))) {
((IRemovable)t).setIsRemoved("0");
}
if (t instanceof IUpdateEntity) {
((IUpdateEntity)t).setLastModifiedTime(new Date());
}
return this.getEm().merge(t);
}
public void save(Iterable<?> iterable) {
Iterator it = iterable.iterator();
while(it.hasNext()) {
this.save(it.next());
}
}
public void delete(Query query) {
this.deleteByQuery(query);
}
public void deleteByQuery(Query query) {
HashMap<String, List<FilterItem>> filterItemMap = new HashMap();
filterItemMap.put("obj", query.getFilterItems());
HashMap<String, Object> paramMap = new HashMap();
String hql;
if (IRemovable.class.isAssignableFrom(query.getEntityClass())) {
hql = "update " + query.getEntityClass().getName() + " as obj set obj.isRemoved='" + "1" + "'";
} else {
hql = "delete " + query.getEntityClass().getName() + " as obj";
}
hql = this.parseFilterItemMap(filterItemMap, paramMap, hql, (Map)null, (Order[])null);
this.executeUpdate(hql, paramMap);
}
public void delete(Object obj) {
if (obj != null) {
if (obj instanceof Query) {
this.deleteByQuery((Query)obj);
} else {
if (obj instanceof IRemovable) {
((IRemovable)obj).setIsRemoved("1");
this.getEm().merge(obj);
} else {
this.getEm().remove(obj);
}
}
}
}
public void delete(Class<?> clazz, Object id) {
Object t = this.find(clazz, id);
if (t == null) {
logger.warn("未找到" + clazz.getName() + "数据" + id.toString());
}
if (t instanceof IRemovable) {
((IRemovable)t).setIsRemoved("1");
this.getEm().merge(t);
} else {
this.getEm().remove(t);
}
}
public void delete(Class<?> clazz, Iterable<?> iterable) {
Iterator it = iterable.iterator();
while(it.hasNext()) {
this.delete(clazz, it.next());
}
}
public int removedPhysiclly(Class<?> clazz, Object id) {
int total = 0;
Object t = this.find(clazz, id);
if (t == null) {
logger.warn("未找到" + clazz.getName() + "数据" + id.toString());
} else {
this.getEm().remove(t);
++total;
}
return total;
}
public int removedPhysiclly(Class<?> clazz, Iterable<?> ids) {
int total = 0;
for(Iterator it = ids.iterator(); it.hasNext(); total += this.removedPhysiclly(clazz, it.next())) {
}
return total;
}
public void removedPhysiclly(Query query) {
HashMap<String, List<FilterItem>> filterItemMap = new HashMap();
filterItemMap.put("obj", query.getFilterItems());
HashMap<String, Object> paramMap = new HashMap();
String hql = "delete " + query.getEntityClass().getName() + " as obj";
hql = this.parseFilterItemMap(filterItemMap, paramMap, hql, (Map)null, (Order[])null);
this.executeUpdate(hql, paramMap);
}
public <T> List<T> findAll(Class<T> clazz) {
return this.findAll(Query.from(clazz));
}
public <T> List<T> findAll(Query<T> query) {
if (query == null) {
return null;
} else {
if (IRemovable.class.isAssignableFrom(query.getEntityClass())) {
query.filter(Filters.equal("isRemoved", "0"));
}
return this.findAllWithRemoved(query);
}
}
public <T> Page<T> findAll(Query<T> query, Pageable pageable) {
if (query == null) {
return null;
} else {
if (IRemovable.class.isAssignableFrom(query.getEntityClass())) {
query.filter(Filters.equal("isRemoved", "0"));
}
return this.findAllWithRemoved(query, pageable);
}
}
public long count(Query query) {
if (IRemovable.class.isAssignableFrom(query.getEntityClass())) {
query.filter(Filters.equal("isRemoved", "0"));
}
CriteriaBuilder cb = this.getEm().getCriteriaBuilder();
CriteriaQuery<?> cq = cb.createQuery(query.getEntityClass());
Root<?> root = cq.from(query.getEntityClass());
query.getQuery(root, cq, cb);
TypedQuery<?> tq = this.getEm().createQuery(cq);
CriteriaQuery<Tuple> cqTuple = cb.createQuery(Tuple.class);
cqTuple.select(cb.tuple(new Selection[]{cb.count(root).alias("_resultTotal")}));
query.clearOrders();
Root<?> rootTuple = cqTuple.from(query.getEntityClass());
query.getQuery(rootTuple, cqTuple, cb);
TypedQuery<Tuple> tqTuple = this.getEm().createQuery(cqTuple);
List<Tuple> tupleResult = tqTuple.getResultList();
long total = (Long)((Long)((Tuple)tupleResult.get(0)).get(0));
return total;
}
public <T> List<T> findAllWithRemoved(Query<T> query) {
CriteriaBuilder cb = this.getEm().getCriteriaBuilder();
CriteriaQuery<?> cq = cb.createQuery(query.getEntityClass());
Root<?> root = cq.from(query.getEntityClass());
query.getQuery(root, cq, cb);
TypedQuery<?> tq = this.getEm().createQuery(cq);
List<?> rows = tq.getResultList();
return rows;
}
public <T> Page<T> findAllWithRemoved(Query<T> query, Pageable pageable) {
CriteriaBuilder cb = this.getEm().getCriteriaBuilder();
CriteriaQuery<?> cq = cb.createQuery(query.getEntityClass());
Root<?> root = cq.from(query.getEntityClass());
query.getQuery(root, cq, cb);
TypedQuery<?> tq = this.getEm().createQuery(cq);
CriteriaQuery<Tuple> cqTuple = cb.createQuery(Tuple.class);
cqTuple.select(cb.tuple(new Selection[]{cb.count(root).alias("_resultTotal")}));
query.clearOrders();
Root<?> rootTuple = cqTuple.from(query.getEntityClass());
query.getQuery(rootTuple, cqTuple, cb);
TypedQuery<Tuple> tqTuple = this.getEm().createQuery(cqTuple);
List<Tuple> tupleResult = tqTuple.getResultList();
long total = (Long)((Long)((Tuple)tupleResult.get(0)).get(0));
if (pageable != null) {
tq.setFirstResult(pageable.getPageNumber() * pageable.getPageSize());
tq.setMaxResults(pageable.getPageSize());
}
List<?> rows = tq.getResultList();
Page<T> page = new PageImpl(rows, pageable, total);
return page;
}
public List<?> executeQuery(String hql, Map<String, ?> parameters) {
javax.persistence.Query query = this.getEm().createQuery(hql);
if (parameters != null) {
Iterator it = parameters.keySet().iterator();
while(it.hasNext()) {
String key = (String)it.next();
query.setParameter(key, parameters.get(key));
}
}
return query.getResultList();
}
public Page executeQuery(String hql, Map<String, ?> parameters, Pageable pageable) {
javax.persistence.Query query = this.getEm().createQuery(hql);
if (parameters != null) {
Iterator it = parameters.keySet().iterator();
while(it.hasNext()) {
String key = (String)it.next();
query.setParameter(key, parameters.get(key));
}
}
query.setFirstResult(pageable.getPageNumber() * pageable.getPageSize());
query.setMaxResults(pageable.getPageSize());
List<?> rows = query.getResultList();
int firstIndex = hql.indexOf("from");
if (firstIndex != -1) {
hql = hql.substring(firstIndex);
}
hql = this.filterOrderBy(hql);
query = this.getEm().createQuery("select count(*) as count " + hql + "");
if (parameters != null) {
Iterator it = parameters.keySet().iterator();
while(it.hasNext()) {
String key = (String)it.next();
query.setParameter(key, parameters.get(key));
}
}
Number total = (Number)query.getSingleResult();
Page page = new PageImpl(rows, pageable, total.longValue());
return page;
}
public Page getQueryList(Map filterItemMap, String hql, Map clazzMap, Map parameters, Pageable pageable) {
return this.getQueryList(filterItemMap, hql, clazzMap, parameters, pageable, (Order[])null);
}
public Page getQueryList(Map<String, ?> filterItemMap, String hql, Map<Class, String> clazzMap, Map<String, Object> parameters, Pageable pageable, Order[] orders) {
if (!StringUtil.isValidStr(hql)) {
return null;
} else {
Map<String, Object> paramMap = new HashMap();
hql = this.parseFilterItemMap(filterItemMap, paramMap, hql, clazzMap, orders);
javax.persistence.Query query = this.getEm().createQuery(hql);
this.parseParameterMap(paramMap, parameters, query);
if (pageable != null) {
query.setFirstResult(pageable.getPageNumber() * pageable.getPageSize());
query.setMaxResults(pageable.getPageSize());
}
List<?> rows = query.getResultList();
int firstIndex = hql.indexOf("from");
if (firstIndex != -1) {
hql = hql.substring(firstIndex);
}
hql = this.filterOrderBy(hql);
query = this.getEm().createQuery("select count(*) as count " + hql + "");
this.parseParameterMap(paramMap, parameters, query);
Number total = (Number)query.getSingleResult();
Page page = new PageImpl(rows, pageable, total.longValue());
return page;
}
}
public List<?> executeSqlQuery(String sql, Map<String, ?> parameters) {
javax.persistence.Query query = this.getEm().createNativeQuery(sql);
if (parameters != null) {
Iterator it = parameters.keySet().iterator();
while(it.hasNext()) {
String key = (String)it.next();
query.setParameter(key, parameters.get(key));
}
}
((SQLQuery)query.unwrap(SQLQuery.class)).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
return query.getResultList();
}
public int executeUpdate(String hql, Map<String, ?> parameters) {
javax.persistence.Query query = this.getEm().createQuery(hql);
if (parameters != null) {
Iterator it = parameters.keySet().iterator();
while(it.hasNext()) {
String key = (String)it.next();
query.setParameter(key, parameters.get(key));
}
}
return query.executeUpdate();
}
public int executeSqlUpdate(String sql, Map<String, ?> parameters) {
javax.persistence.Query query = this.getEm().createNativeQuery(sql);
if (parameters != null) {
Iterator it = parameters.keySet().iterator();
while(it.hasNext()) {
String key = (String)it.next();
query.setParameter(key, parameters.get(key));
}
}
return query.executeUpdate();
}
private String filterOrderBy(String hql) {
String word = "([\\w\\.]+\\s*\\([\\s\\S]*?\\)|[\\w\\.]+)(\\s+(desc|asc))?";
String pattern = "(?i)order[\\s]+by\\s+" + word + "(\\s*,\\s*" + word + ")*";
return hql.replaceAll(pattern, "");
}
public static void main(String[] args) {
BaseJpaDaoImpl bjdi = new BaseJpaDaoImpl();
String hql = "select * from (select * from table order by a.aaa , b.bbb ) order by c.ccc(mm , nn) , dd.dd asc";
String result = bjdi.filterOrderBy(hql);
System.out.println(result);
}
private String parseFilterItemMap(Map<String, ?> filterItemMap, Map<String, Object> paramMap, String hql, Map<Class, String> clazzMap, Order[] orders) {
if (hql.indexOf("where") == -1) {
hql = hql + " where";
}
hql = hql + " ";
if (filterItemMap != null) {
Iterator iterator = filterItemMap.keySet().iterator();
label47:
while(true) {
String key;
FilterItem[] filterValueArray;
do {
if (!iterator.hasNext()) {
break label47;
}
key = (String)iterator.next();
filterValueArray = new FilterItem[0];
if (filterItemMap.get(key) instanceof Collection) {
filterValueArray = (FilterItem[])((FilterItem[])((Collection)filterItemMap.get(key)).toArray(new FilterItem[0]));
} else if (filterItemMap.get(key) instanceof FilterItem[]) {
filterValueArray = (FilterItem[])((FilterItem[])filterItemMap.get(key));
}
} while(filterValueArray.length == 0);
FilterItem[] var9 = filterValueArray;
int var10 = filterValueArray.length;
for(int var11 = 0; var11 < var10; ++var11) {
FilterItem filterValue = var9[var11];
if (!hql.trim().endsWith("where")) {
hql = hql + " and ";
}
hql = hql + FilterConverter.toHqlCondition(key, paramMap, filterValue);
}
}
}
if (orders != null) {
String order = FilterConverter.toHqlOrder(clazzMap, orders);
if (order != null && !"".equals(order.trim())) {
hql = hql + " order by " + order;
}
}
return hql;
}
private void parseParameterMap(Map<String, Object> paramMap, Map<String, Object> parameters, javax.persistence.Query query) {
if (query != null) {
Iterator it;
String key;
if (paramMap != null) {
it = paramMap.keySet().iterator();
while(it.hasNext()) {
key = (String)it.next();
query.setParameter(key, paramMap.get(key));
}
}
if (parameters != null) {
it = parameters.keySet().iterator();
while(it.hasNext()) {
key = (String)it.next();
query.setParameter(key, parameters.get(key));
}
}
}
}
public EntityManager getEm() {
return this.em;
}
}
*/
|
package me.hsgamer.bettergui.npcopener;
import java.util.HashMap;
import java.util.Map;
public class InteractiveNPC {
private final int id;
private String[] args = new String[0];
public InteractiveNPC(int id) {
this.id = id;
}
public static InteractiveNPC deserialize(Map<String, Object> map) {
InteractiveNPC npc = new InteractiveNPC((Integer) map.get("id"));
if (map.containsKey("args")) {
npc.setArgs(((String) map.get("args")).split(" "));
}
return npc;
}
public int getId() {
return id;
}
public String[] getArgs() {
return args;
}
public void setArgs(String[] args) {
this.args = args;
}
public Map<String, Object> serialize() {
Map<String, Object> map = new HashMap<>();
map.put("id", id);
if (args.length > 0) {
map.put("args", String.join(" ", args));
}
return map;
}
}
|
package exam_module5.demo.model;
import javax.persistence.*;
@Entity
public class Car {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String code;
@ManyToOne(targetEntity = Type.class)
@JoinColumn(name = "type_id", referencedColumnName = "id")
private Type type;
private String name;
@ManyToOne(targetEntity = Start.class)
@JoinColumn(name = "start_id", referencedColumnName = "id")
private Start start;
@ManyToOne(targetEntity = End.class)
@JoinColumn(name = "end_id", referencedColumnName = "id")
private End end;
private String phone;
private String timeStart;
private String timeEnd;
private String email;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public Type getType() {
return type;
}
public void setType(Type type) {
this.type = type;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Start getStart() {
return start;
}
public void setStart(Start start) {
this.start = start;
}
public End getEnd() {
return end;
}
public void setEnd(End end) {
this.end = end;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getTimeStart() {
return timeStart;
}
public void setTimeStart(String timeStart) {
this.timeStart = timeStart;
}
public String getTimeEnd() {
return timeEnd;
}
public void setTimeEnd(String timeEnd) {
this.timeEnd = timeEnd;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
|
package dk.sdu.mmmi.cbse.common.data;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
*
* @author jcs
*/
public class World {
private int TILESIZE;
private final Map<String, Entity> entityMap = new ConcurrentHashMap<>();
private float[] playerSpawn = {4, 56};
public int getTILESIZE() {
return TILESIZE;
}
public void setTILESIZE(int TILESIZE) {
this.TILESIZE = TILESIZE;
}
private int[][] blockedMap;
public int[][] getBlockedMap() {
return blockedMap;
}
public void setBlockedMap(int[][] blockedMap) {
this.blockedMap = blockedMap;
}
public float[] getPlayerSpawn() {
return playerSpawn;
}
public void setPlayerSpawn(float[] playerSpawn) {
this.playerSpawn = playerSpawn;
}
public String addEntity(Entity entity) {
entityMap.put(entity.getID(), entity);
return entity.getID();
}
public void removeEntity(String entityID) {
entityMap.remove(entityID);
}
public void removeEntity(Entity entity) {
entityMap.remove(entity.getID());
}
public Collection<Entity> getEntities() {
return entityMap.values();
}
public <E extends Entity> List<Entity> getEntities(Class<E>... entityTypes) {
List<Entity> r = new ArrayList<>();
for (Entity e : getEntities()) {
for (Class<E> entityType : entityTypes) {
if (entityType.equals(e.getClass())) {
r.add(e);
}
}
}
return r;
}
public Entity getEntity(String ID) {
return entityMap.get(ID);
}
}
|
/*
* Copyright 2008 University of California at Berkeley
*
* 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.rebioma.client.maps;
import org.rebioma.client.bean.AscData;
import com.google.gwt.core.client.GWT;
import com.google.gwt.maps.client.base.Point;
import com.google.gwt.maps.client.base.Size;
import com.google.gwt.maps.client.maptypes.TileUrlCallBack;
/**
* Represents an environmental layer that backed by an {@link AscData} that can
* be overlaid on a Google map.
*/
public class EnvLayer extends AscTileLayer {
/**
* Returns a layer info that allows this environmental layer to be lazy
* loaded.
*
* @param data
* the asc data
* @return the loayer info
*/
public static LayerInfo init(final AscData data) {
return new LayerInfo() {
@Override
public String getName() {
return dataSummary(data);
}
@Override
protected AscTileLayer get() {
return EnvLayer.newInstance(data);
}
};
}
private static String dataSummary(AscData data) {
return data.getEnvDataType() + " - " + data.getEnvDataSubtype() + " "
+ data.getYear();
}
private AscData data;
private TileLayerLegend legend;
protected EnvLayer() {
super();
}
public static EnvLayer newInstance(AscData data){
final EnvLayer envLayer = new EnvLayer();
envLayer.data = data;
envLayer.imageMapTypeOptions.setTileSize(Size.newInstance(256, 256));
envLayer.imageMapTypeOptions.setOpacity(0.5);
//envLayer.setOpacity(opacity);
envLayer.baseUrl = GWT.getModuleBaseURL() + "ascOverlay?f=" + data.getFileName();
envLayer.imageMapTypeOptions.setTileUrl(new TileUrlCallBack() {
@Override
public String getTileUrl(Point point, int zoomLevel) {
String tileUrl = envLayer.baseUrl;
tileUrl += "&x=" + new Double(Math.rint(point.getX())).intValue();
tileUrl += "&y=" + new Double(Math.rint(point.getY())).intValue();
tileUrl += "&z=" + zoomLevel;
return tileUrl;
}
});
return envLayer;
}
@Override
public TileLayerLegend getLegend() {
if (legend == null) {
legend = new EnvLayerLegend(data);
}
return legend;
}
}
|
import java.util.Random;
import java.util.Scanner;
public class Random_num{
public static void main(String[] args) {
Random rand=new Random();
for(int i=1;i<3;i++) {
System.out.println(rand.nextInt());
System.out.println(rand.nextDouble());
System.out.println(rand.nextLong());
}
}
}
|
import java.util.Scanner;
public class Main {
static Scanner scan = new Scanner(System.in);
public static void main(String[] args) {
double[][] x = new double[3][3];
double[][] y = new double[3][3];
System.out.print("Enter matrix1: ");
readM(x);
System.out.print("Enter matrix2: ");
readM(y);
multiplyM(x, y);
showM(x, y, multiplyM(x, y));
}
private static void showM(double[][] x, double[][] y, double[][] mul) {
for (int i = 0; i < 3; i++) {
if (i != 1) {
System.out.printf("%.1f %.1f %.1f %.1f %.1f %.1f %.1f %.1f %.1f%n",
x[i][0],x[i][1], x[i][2],y[i][0],y[i][1], y[i][2],mul[i][0],mul[i][1], mul[i][2]);
}
if (i == 1) {
System.out.printf("%.1f %.1f %.1f * %.1f %.1f %.1f = %.1f %.1f %.1f%n",
x[i][0],x[i][1], x[i][2],y[i][0],y[i][1], y[i][2],mul[i][0],mul[i][1], mul[i][2]);
}
}
}
private static double[][] multiplyM(double[][] x, double[][] y) {
double[][] mul = new double[3][3];
for (int i = 0; i < 3; i++){
for (int j = 0; j < 3; j++){
mul[i][j] = x[i][0] * y[0][j] + x[i][1] * y[1][j] + x[i][2] * y[2][j];
}
}
return mul;
}
private static double[][] readM(double[][] m) {
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
m[i][j] = scan.nextDouble();
}
}
return m;
}
}
|
package testHIbernate;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.ManyToOne;
@Entity
public class SuperHero extends AbstractEntity {
// @NotEmpty
@Column(unique = true)
public String name;
@ManyToOne
// @NotNull
public SuperPower power;
// @NotEmpty
public String weakness;
// @NotEmpty
public String secretIdentity;
}
|
package edu.up.cs301.quoridor;
import edu.up.cs301.game.GamePlayer;
import edu.up.cs301.game.actionMsg.GameAction;
/**
* Created by lieu18 on 3/25/2018.
*/
public class QuoridorUndoTurn extends GameAction {
private static final long serialVersionUID = 420696942069L;
/**
* constructor for GameAction
*
* @param player the player who created the action
*/
public QuoridorUndoTurn(GamePlayer player) {
super(player);
}
/**
* @return
* whether this action is an Undo turn
*/
public boolean isUndo() {
return true;
}
}
|
package com.wlc.ds.tree;
/**
* 检查一颗二叉树是否是二叉查找树 二叉查找树的定义为对于每一个结点, 它的左边的结点必须小于等于它,右边的结点必须大于它
* 自上而下传递一个区间,如果某个值不在区间里,则说明不是
* @author lanchun
*
*/
public class IsBST {
private static boolean checkBST(TreeNode root, int min, int max) {
if (root == null)
return true;
if (root.data >= max || root.data < min) {
return false;
}
if (!checkBST(root.leftChild, min, root.data) || !checkBST(root.rightChild, root.data, max)) {
return false;
}
return true;
}
public static boolean checkBST(TreeNode root) {
return checkBST(root, Integer.MIN_VALUE, Integer.MAX_VALUE);
}
}
|
package org.kernelab.basis.test;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.kernelab.basis.HashedEquality;
import org.kernelab.basis.Tools;
import org.kernelab.basis.WrappedHashMap;
import org.kernelab.basis.WrappedHashSet;
public class TestWrappedContainer
{
public static class DemoObject
{
public final int id;
public final String name;
public DemoObject(int id, String name)
{
this.id = id;
this.name = name;
}
@Override
public String toString()
{
return id + " " + name;
}
}
public static void main(String[] args)
{
DemoObject a = new DemoObject(1, "a");
DemoObject b = new DemoObject(1, "a");
DemoObject c = new DemoObject(2, "c");
HashedEquality<DemoObject> eql = new HashedEquality<TestWrappedContainer.DemoObject>()
{
@Override
public boolean equals(DemoObject a, DemoObject b)
{
return a.id == b.id && Tools.equals(a.name, b.name);
}
@Override
public int hashCode(DemoObject obj)
{
return obj.id * 31 + obj.name.hashCode();
}
};
Set<DemoObject> set1 = new HashSet<DemoObject>();
set1.add(a);
set1.add(b);
set1.add(c);
for (DemoObject o : set1)
{
Tools.debug(o);
}
Tools.debug("==================");
Set<DemoObject> set2 = new WrappedHashSet<DemoObject>(eql);
set2.add(a);
set2.add(b);
set2.add(c);
for (DemoObject o : set2)
{
Tools.debug(o);
}
Tools.debug("==================");
Map<DemoObject, Object> map1 = new HashMap<DemoObject, Object>();
map1.put(a, 1);
map1.put(b, 2);
map1.put(c, 3);
for (Entry<DemoObject, Object> e : map1.entrySet())
{
Tools.debug(e.getKey() + " -> " + e.getValue());
}
Tools.debug("==================");
Map<DemoObject, Object> map2 = new WrappedHashMap<DemoObject, Object>(eql);
map2.put(a, 1);
map2.put(b, 2);
map2.put(c, 3);
for (Entry<DemoObject, Object> e : map2.entrySet())
{
Tools.debug(e.getKey() + " -> " + e.getValue());
}
}
}
|
package elements;
import primitives.Color;
import primitives.Point3D;
import primitives.Vector;
/**
* class PointLight to apply point lighting
*
* @author Rina and Tamar
*
*/
public class PointLight extends Light implements LightSource
{
/**
* PointLight values
*/
protected Point3D _position;
protected double _kC, _kL, _kQ;
/**
* PointLight constructor
*
* @param intensity
* @param position
* @param kC
* @param kL
* @param kQ
*/
public PointLight(Color intensity, Point3D position, double kC, double kL, double kQ) {
super(intensity);
_position = new Point3D(position);
_kC = kC;
_kL = kL;
_kQ = kQ;
}
/**
* The get function to get color
*
* @param Point - p
* @return color
*/
@Override
public Color getIntensity()
{
return super.getIntensity();
}
@Override
public Color getIntensity(Point3D p)
{
//double dsquared = p.distanceSquared(_position);
//double d = p.distance(_position);
double d = getDistance(p);
double dsquared = d*d;
return (_intensity.reduce(_kC + _kL * d + _kQ * dsquared));
}
/**
* The get function to get the direction of the lighting
*
* @param Point - p
* @return vector - direction
*/
@Override
public Vector getL(Point3D p) {
if (p.equals(_position)) {
return null;
}
return p.subtract(_position).normalize();
}
/**
*
*/
@Override
public double getDistance(Point3D point)
{
return _position.distance(point);
}
}
|
package com.jamesball.learn.tictactoe;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class PlayTest {
private final BoardEvaluator evaluator = new BoardEvaluator();
private final PlayerSwapper swapper = new PlayerSwapper();
private List<TerminalBoardPosition> terminalBoardPositions;
private static class TerminalBoardPosition {
private final Board boardPosition;
private final PlayerMark playerMark;
private final GameState gameState;
public TerminalBoardPosition(Board boardPosition, PlayerMark playerMark, GameState gameState) {
this.boardPosition = boardPosition;
this.playerMark = playerMark;
this.gameState = gameState;
}
public Board getBoardPosition() {
return boardPosition;
}
public PlayerMark getPlayerMark() {
return playerMark;
}
public GameState getGameState() {
return gameState;
}
}
@BeforeEach
public void beforeEach() {
terminalBoardPositions = findAllTerminalBoardPositions();
}
@Test
public void whenAllPossibleMoveSequencesPlayed_then138DistinctTerminalBoardPositionsAreReached() {
assertEquals(138, terminalBoardPositions.size());
}
@Test
public void whenAllPossibleMoveSequencesPlayed_then91TerminalBoardPositionsAreWonByX() {
assertEquals(91, terminalBoardPositions.stream()
.filter(terminalBoardPosition -> terminalBoardPosition.getPlayerMark() == PlayerMark.X && terminalBoardPosition.getGameState() == GameState.WIN)
.count()
);
}
@Test
public void whenAllPossibleMoveSequencesPlayed_then44TerminalBoardPositionsAreWonByO() {
assertEquals(44, terminalBoardPositions.stream()
.filter(terminalBoardPosition -> terminalBoardPosition.getPlayerMark() == PlayerMark.O && terminalBoardPosition.getGameState() == GameState.WIN)
.count()
);
}
@Test
public void whenAllPossibleMoveSequencesPlayed_then3TerminalBoardPositionsAreDrawn() {
assertEquals(3, terminalBoardPositions.stream()
.filter(terminalBoardPosition -> terminalBoardPosition.getGameState() == GameState.DRAW)
.count()
);
}
private List<TerminalBoardPosition> findAllTerminalBoardPositions() {
final List<TerminalBoardPosition> terminalBoardPositions = new ArrayList<>();
Board startingBoardPosition = new Board();
PlayerMark startingPlayerMark = PlayerMark.X;
playAllPossibleMoveSequences(terminalBoardPositions, startingBoardPosition, startingPlayerMark);
return terminalBoardPositions;
}
private void playAllPossibleMoveSequences(List<TerminalBoardPosition> terminalBoardPositions, Board currentBoardPosition, PlayerMark currentPlayerMark) {
GameState currentGameState = evaluator.evaluate(currentBoardPosition);
if (isTerminalBoardPositionReached(currentGameState)) {
addTerminalBoardPosition(terminalBoardPositions, currentBoardPosition, currentPlayerMark, currentGameState);
}
else {
for (Move move : availableMoves(currentBoardPosition, currentPlayerMark)) {
final Board boardPosition = nextBoardPosition(currentBoardPosition, move);
final PlayerMark playerMark = swapper.swap(currentPlayerMark);
playAllPossibleMoveSequences(terminalBoardPositions, boardPosition, playerMark);
}
}
}
private boolean isTerminalBoardPositionReached(GameState state) {
return state != GameState.IN_PLAY;
}
private void addTerminalBoardPosition(List<TerminalBoardPosition> terminalBoardPositions, Board boardPosition, PlayerMark playerMark, GameState gameState) {
List<Board> boardPositions = terminalBoardPositions.stream()
.map(TerminalBoardPosition::getBoardPosition)
.collect(Collectors.toCollection(ArrayList::new));
if (boardPositions.stream().anyMatch(board -> board.isSymmetrical(boardPosition))) {
return;
}
TerminalBoardPosition terminalBoardPosition = new TerminalBoardPosition(boardPosition, swapper.swap(playerMark), gameState);
terminalBoardPositions.add(terminalBoardPosition);
}
private Board nextBoardPosition(Board boardPosition, Move move) {
Board boardPositionCopy = boardPosition.clone();
boardPositionCopy.addMove(move);
return boardPositionCopy;
}
private List<Move> availableMoves(Board boardPosition, PlayerMark playerMark) {
return IntStream.range(0, boardPosition.getSize())
.filter(square -> !boardPosition.isMarked(square))
.mapToObj(square -> new Move(playerMark, square))
.collect(Collectors.toList());
}
}
|
package co.th.aten.network;
public class Constants {
public static int GROUP_STAFF=1;
}
|
package com.mobica.rnd.parking.parkingbetests;
import com.mobica.rnd.parking.parkingbetests.support.*;
import com.mobica.rnd.parking.parkingbetests.support.extractors.DatesExtractor;
import com.mobica.rnd.parking.parkingbetests.support.extractors.IDataExtractor;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.junit.Ignore;
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.TestPropertySource;
import org.springframework.test.context.junit4.SpringRunner;
import javax.annotation.PostConstruct;
/**
* Created by int_eaja on 2017-08-07.
*/
@RunWith(SpringRunner.class)
@SpringBootTest
@TestPropertySource("classpath:application-test.properties")
public class Issue_16_ParkingSlotsAvailableForBookingTest {
private static final String ISSUE_NAME = "16-ParkingSlotsAvailableForBooking";
@Autowired
private RestAssuredProcessor processor;
private TestSuiteData suiteData;
private DatesExtractor datesExtractor;
private IDataExtractor fakeIdsExtractor, emptyDatesExtractor;
@PostConstruct
public void setUp() {
suiteData = new TestSuiteData(processor.getBaseURL(), ISSUE_NAME);
initExtractors();
}
@Test
public void mark_parking_slots_available_for_booking_success_test() {
suiteData
.createTestCaseExecutor("mark_parking_slots_available_for_booking_success")
.extractItemConfigurationJSONResponses(datesExtractor, "dates")
.extractItemConfigurationJSONResponses("parking")
.extendConfigurationItemRequestBody(DataAssociationType.ONE_TO_ALL, SourceDataType.ITEM, "parking_places", new String[]{"parking", "id", "parking.id"}, new int[]{-1, -1})
.extractItemConfigurationJSONResponses("parking_places")
.extendTestCaseRequestQueryParam(SourceDataType.ITEM, "start", new String[]{"dates", "start"})
.extendTestCaseRequestQueryParam(SourceDataType.ITEM, "end", new String[]{"dates", "end"})
.extendTestCaseRequestBody(DataAssociationType.ALL_TO_ALL, SourceDataType.ITEM, new String[]{"parking_places", "parkingPlaceId", "parkingPlaceId"}, new int[]{-1, -1})
.performTests(processor, suiteData);
}
@Test
public void mark_parking_slots_available_for_booking_using_dates_boundary_values_success_test() {
suiteData
.createTestCaseExecutor("mark_parking_slots_available_for_booking_using_dates_boundary_values_success")
.extractItemConfigurationJSONResponses(datesExtractor, "dates")
.extractItemConfigurationJSONResponses("parking")
.extendConfigurationItemRequestBody(DataAssociationType.ONE_TO_ALL, SourceDataType.ITEM, "parking_places", new String[]{"parking", "id", "parking.id"}, new int[]{-1, -1})
.extractItemConfigurationJSONResponses("parking_places")
.extendTestCaseRequestQueryParam(SourceDataType.ITEM, "start", new String[]{"dates", "start"})
.extendTestCaseRequestQueryParam(SourceDataType.ITEM, "end", new String[]{"dates", "end"})
.extendTestCaseRequestBody(DataAssociationType.ALL_TO_ALL, SourceDataType.ITEM, new String[]{"parking_places", "parkingPlaceId", "parkingPlaceId"}, new int[]{-1, -1})
.performTests(processor, suiteData);
}
@Test
public void mark_parking_slots_available_for_booking_using_parking_places_boundary_values_success_test() {
suiteData
.createTestCaseExecutor("mark_parking_slots_available_for_booking_using_parking_places_boundary_values_success")
.extractItemConfigurationJSONResponses(datesExtractor, "dates")
.extractItemConfigurationJSONResponses(datesExtractor, "primary_dates")
.extractItemConfigurationJSONResponses("parking")
.extendConfigurationItemRequestBody(DataAssociationType.ONE_TO_ALL, SourceDataType.ITEM, "parking_places", new String[]{"parking", "id", "parking.id"}, new int[]{-1, -1})
.extractItemConfigurationJSONResponses("parking_places")
.extendConfigurationItemRequestQueryParam(SourceDataType.ITEM, "start", new String[]{"primary_dates", "start", "primary_parking_slots"}, 0)
.extendConfigurationItemRequestQueryParam(SourceDataType.ITEM, "end", new String[]{"primary_dates", "end", "primary_parking_slots"}, 0)
.extendConfigurationItemRequestBody(DataAssociationType.ALL_TO_ALL, SourceDataType.ITEM, "primary_parking_slots", new String[]{"parking_places", "parkingPlaceId", "parkingPlaceId"}, new int[]{-1, -1})
.extractItemConfigurationJSONResponses("primary_parking_slots")
.extendTestCaseRequestQueryParam(SourceDataType.ITEM, "start", new String[]{"dates", "start"})
.extendTestCaseRequestQueryParam(SourceDataType.ITEM, "end", new String[]{"dates", "end"})
.extendTestCaseRequestBody(DataAssociationType.ALL_TO_ALL, SourceDataType.ITEM, new String[]{"parking_places", "parkingPlaceId", "parkingPlaceId"}, new int[]{-1, -1})
.performTests(processor, suiteData);
}
@Test
public void mark_parking_slots_available_for_booking_using_different_parking_places_values_success_test() {
suiteData
.createTestCaseExecutor("mark_parking_slots_available_for_booking_using_different_parking_places_values_success")
.extractItemConfigurationJSONResponses(datesExtractor, "dates")
.extractItemConfigurationJSONResponses(datesExtractor, "primary_dates")
.extractItemConfigurationJSONResponses("parking")
.extendConfigurationItemRequestBody(DataAssociationType.ONE_TO_ALL, SourceDataType.ITEM, "parking_places", new String[]{"parking", "id", "parking.id"}, new int[]{-1, -1})
.extractItemConfigurationJSONResponses("parking_places")
.extendConfigurationItemRequestQueryParam(SourceDataType.ITEM, "start", new String[]{"primary_dates", "start", "primary_parking_slots"}, 0)
.extendConfigurationItemRequestQueryParam(SourceDataType.ITEM, "end", new String[]{"primary_dates", "end", "primary_parking_slots"}, 0)
.extendConfigurationItemRequestBody(DataAssociationType.ONE_TO_ONE, SourceDataType.ITEM, "primary_parking_slots", new String[]{"parking_places", "parkingPlaceId", "parkingPlaceId"}, new int[]{0, 0})
.extractItemConfigurationJSONResponses("primary_parking_slots")
.extendTestCaseRequestQueryParam(SourceDataType.ITEM, "start", new String[]{"dates", "start"})
.extendTestCaseRequestQueryParam(SourceDataType.ITEM, "end", new String[]{"dates", "end"})
.extendTestCaseRequestBody(DataAssociationType.ONE_TO_ONE, SourceDataType.ITEM, new String[]{"parking_places", "parkingPlaceId", "parkingPlaceId"}, new int[]{1, 0})
.performTests(processor, suiteData);
}
@Test
public void mark_parking_slots_available_for_booking_for_past_dates_failure_test() {
suiteData
.createTestCaseExecutor("mark_parking_slots_available_for_booking_for_past_dates_failure")
.extractItemConfigurationJSONResponses(datesExtractor, "dates")
.extractItemConfigurationJSONResponses("parking")
.extendConfigurationItemRequestBody(DataAssociationType.ONE_TO_ALL, SourceDataType.ITEM, "parking_places", new String[]{"parking", "id", "parking.id"}, new int[]{-1, -1})
.extractItemConfigurationJSONResponses("parking_places")
.extendTestCaseRequestQueryParam(SourceDataType.ITEM, "start", new String[]{"dates", "start"})
.extendTestCaseRequestQueryParam(SourceDataType.ITEM, "end", new String[]{"dates", "end"})
.extendTestCaseRequestBody(DataAssociationType.ALL_TO_ALL, SourceDataType.ITEM, new String[]{"parking_places", "parkingPlaceId", "parkingPlaceId"}, new int[]{-1, -1})
.performTests(processor, suiteData);
}
@Test
@Ignore
public void mark_parking_slots_available_for_booking_for_dates_after_selected_limit_failure_test() {
suiteData
.createTestCaseExecutor("mark_parking_slots_available_for_booking_for_dates_after_selected_limit_failure")
.extractItemConfigurationJSONResponses(datesExtractor, "dates")
.extractItemConfigurationJSONResponses("parking")
.extendConfigurationItemRequestBody(DataAssociationType.ONE_TO_ALL, SourceDataType.ITEM, "parking_places", new String[]{"parking", "id", "parking.id"}, new int[]{-1, -1})
.extractItemConfigurationJSONResponses("parking_places")
.extendTestCaseRequestQueryParam(SourceDataType.ITEM, "start", new String[]{"dates", "start"})
.extendTestCaseRequestQueryParam(SourceDataType.ITEM, "end", new String[]{"dates", "end"})
.extendTestCaseRequestBody(DataAssociationType.ALL_TO_ALL, SourceDataType.ITEM, new String[]{"parking_places", "parkingPlaceId", "parkingPlaceId"}, new int[]{-1, -1})
.performTests(processor, suiteData);
}
@Test
public void mark_parking_slots_available_for_booking_with_end_date_before_start_date_failure_test() {
suiteData
.createTestCaseExecutor("mark_parking_slots_available_for_booking_with_end_date_before_start_date_failure")
.extractItemConfigurationJSONResponses(datesExtractor, "dates")
.extractItemConfigurationJSONResponses("parking")
.extendConfigurationItemRequestBody(DataAssociationType.ONE_TO_ALL, SourceDataType.ITEM, "parking_places", new String[]{"parking", "id", "parking.id"}, new int[]{-1, -1})
.extractItemConfigurationJSONResponses("parking_places")
.extendTestCaseRequestQueryParam(SourceDataType.ITEM, "start", new String[]{"dates", "start"})
.extendTestCaseRequestQueryParam(SourceDataType.ITEM, "end", new String[]{"dates", "end"})
.extendTestCaseRequestBody(DataAssociationType.ALL_TO_ALL, SourceDataType.ITEM, new String[]{"parking_places", "parkingPlaceId", "parkingPlaceId"}, new int[]{-1, -1})
.performTests(processor, suiteData);
}
@Test
public void mark_parking_slots_available_for_booking_when_some_of_them_already_marked_failure_test() {
suiteData
.createTestCaseExecutor("mark_parking_slots_available_for_booking_when_some_of_them_already_marked_failure")
.extractItemConfigurationJSONResponses(datesExtractor, "dates")
.extractItemConfigurationJSONResponses("parking")
.extendConfigurationItemRequestBody(DataAssociationType.ONE_TO_ALL, SourceDataType.ITEM, "parking_places", new String[]{"parking", "id", "parking.id"}, new int[]{-1, -1})
.extractItemConfigurationJSONResponses("parking_places")
.extendConfigurationItemRequestQueryParam(SourceDataType.ITEM, "start", new String[]{"dates", "start", "primary_parking_slots"}, 0)
.extendConfigurationItemRequestQueryParam(SourceDataType.ITEM, "end", new String[]{"dates", "end", "primary_parking_slots"}, 0)
.extendConfigurationItemRequestBody(DataAssociationType.ALL_TO_ALL, SourceDataType.ITEM, "primary_parking_slots", new String[]{"parking_places", "parkingPlaceId", "parkingPlaceId"}, new int[]{-1, -1})
.extractItemConfigurationJSONResponses("primary_parking_slots")
.extendTestCaseRequestQueryParam(SourceDataType.ITEM, "start", new String[]{"dates", "start"})
.extendTestCaseRequestQueryParam(SourceDataType.ITEM, "end", new String[]{"dates", "end"})
.extendTestCaseRequestBody(DataAssociationType.ALL_TO_ALL, SourceDataType.ITEM, new String[]{"parking_places", "parkingPlaceId", "parkingPlaceId"}, new int[]{-1, -1})
.performTests(processor, suiteData);
}
@Test
public void mark_parking_slots_available_for_booking_when_some_of_them_do_not_exist_failure_test() {
suiteData
.createTestCaseExecutor("mark_parking_slots_available_for_booking_when_some_of_them_do_not_exist_failure")
.extractItemConfigurationJSONResponses(datesExtractor, "dates")
.extractItemConfigurationJSONResponses("parking")
.extendConfigurationItemRequestBody(DataAssociationType.ONE_TO_ALL, SourceDataType.ITEM, "parking_places", new String[]{"parking", "id", "parking.id"}, new int[]{-1, -1})
.extractItemConfigurationJSONResponses("parking_places")
.extractItemConfigurationJSONResponses(fakeIdsExtractor, "fake_parking_places")
.extendTestCaseRequestQueryParam(SourceDataType.ITEM, "start", new String[]{"dates", "start"})
.extendTestCaseRequestQueryParam(SourceDataType.ITEM, "end", new String[]{"dates", "end"})
.extendTestCaseRequestBody(DataAssociationType.ALL_TO_ALL, SourceDataType.ITEM, new String[]{"parking_places", "parkingPlaceId", "parkingPlaceId"}, new int[]{-1, -1})
.extendTestCaseRequestBody(DataAssociationType.ONE_TO_ONE, SourceDataType.ITEM, new String[]{"fake_parking_places", "parkingPlaceId", "parkingPlaceId"}, new int[]{0, 0})
.performTests(processor, suiteData);
}
@Test
public void mark_parking_slots_available_for_booking_using_dates_boundary_values_failure_test() {
suiteData
.createTestCaseExecutor("mark_parking_slots_available_for_booking_using_dates_boundary_values_failure")
.extractItemConfigurationJSONResponses(datesExtractor, "dates")
.extractItemConfigurationJSONResponses("parking")
.extendConfigurationItemRequestBody(DataAssociationType.ONE_TO_ALL, SourceDataType.ITEM, "parking_places", new String[]{"parking", "id", "parking.id"}, new int[]{-1, -1})
.extractItemConfigurationJSONResponses("parking_places")
.extendTestCaseRequestQueryParam(SourceDataType.ITEM, "start", new String[]{"dates", "start"})
.extendTestCaseRequestQueryParam(SourceDataType.ITEM, "end", new String[]{"dates", "end"})
.extendTestCaseRequestBody(DataAssociationType.ALL_TO_ALL, SourceDataType.ITEM, new String[]{"parking_places", "parkingPlaceId", "parkingPlaceId"}, new int[]{-1, -1})
.performTests(processor, suiteData);
}
@Test
public void mark_parking_slots_available_for_booking_using_parking_places_boundary_values_failure_test() {
suiteData
.createTestCaseExecutor("mark_parking_slots_available_for_booking_using_parking_places_boundary_values_failure")
.extractItemConfigurationJSONResponses(datesExtractor, "dates")
.extractItemConfigurationJSONResponses(datesExtractor, "primary_dates")
.extractItemConfigurationJSONResponses("parking")
.extendConfigurationItemRequestBody(DataAssociationType.ONE_TO_ALL, SourceDataType.ITEM, "parking_places", new String[]{"parking", "id", "parking.id"}, new int[]{-1, -1})
.extractItemConfigurationJSONResponses("parking_places")
.extendConfigurationItemRequestQueryParam(SourceDataType.ITEM, "start", new String[]{"primary_dates", "start", "primary_parking_slots"}, 0)
.extendConfigurationItemRequestQueryParam(SourceDataType.ITEM, "end", new String[]{"primary_dates", "end", "primary_parking_slots"}, 0)
.extendConfigurationItemRequestBody(DataAssociationType.ALL_TO_ALL, SourceDataType.ITEM, "primary_parking_slots", new String[]{"parking_places", "parkingPlaceId", "parkingPlaceId"}, new int[]{-1, -1})
.extractItemConfigurationJSONResponses("primary_parking_slots")
.extendTestCaseRequestQueryParam(SourceDataType.ITEM, "start", new String[]{"dates", "start"})
.extendTestCaseRequestQueryParam(SourceDataType.ITEM, "end", new String[]{"dates", "end"})
.extendTestCaseRequestBody(DataAssociationType.ALL_TO_ALL, SourceDataType.ITEM, new String[]{"parking_places", "parkingPlaceId", "parkingPlaceId"}, new int[]{-1, -1})
.performTests(processor, suiteData);
}
@Test
@Ignore
public void mark_parking_slots_available_for_booking_without_passing_dates_failure_test() {
suiteData
.createTestCaseExecutor("mark_parking_slots_available_for_booking_without_passing_dates_failure")
.extractItemConfigurationJSONResponses("parking")
.extendConfigurationItemRequestBody(DataAssociationType.ONE_TO_ALL, SourceDataType.ITEM, "parking_places", new String[]{"parking", "id", "parking.id"}, new int[]{-1, -1})
.extractItemConfigurationJSONResponses("parking_places")
.extendTestCaseRequestBody(DataAssociationType.ALL_TO_ALL, SourceDataType.ITEM, new String[]{"parking_places", "parkingPlaceId", "parkingPlaceId"}, new int[]{-1, -1})
.performTests(processor, suiteData);
}
@Test
@Ignore
public void mark_parking_slots_available_for_booking_with_passing_empty_dates_failure_test() {
suiteData
.createTestCaseExecutor("mark_parking_slots_available_for_booking_with_passing_empty_dates_failure")
.extractItemConfigurationJSONResponses(emptyDatesExtractor, "dates")
.extractItemConfigurationJSONResponses("parking")
.extendConfigurationItemRequestBody(DataAssociationType.ONE_TO_ALL, SourceDataType.ITEM, "parking_places", new String[]{"parking", "id", "parking.id"}, new int[]{-1, -1})
.extractItemConfigurationJSONResponses("parking_places")
.extendTestCaseRequestQueryParam(SourceDataType.ITEM, "start", new String[]{"dates", "start"})
.extendTestCaseRequestQueryParam(SourceDataType.ITEM, "end", new String[]{"dates", "end"})
.extendTestCaseRequestBody(DataAssociationType.ALL_TO_ALL, SourceDataType.ITEM, new String[]{"parking_places", "parkingPlaceId", "parkingPlaceId"}, new int[]{-1, -1})
.performTests(processor, suiteData);
}
private void initExtractors() {
datesExtractor = new DatesExtractor();
emptyDatesExtractor = new IDataExtractor() {
@Override
public JSONObject[] extractData(JSONObject obj, String key) {
JSONArray data = (JSONArray) obj.get("data");
JSONObject datesObj = (JSONObject) data.get(0);
String start = (String) datesObj.get("start");
String end = (String) datesObj.get("end");
return new JSONObject[]{getDates(start, end)};
}
private JSONObject getDates(String start, String end) {
JSONObject o = new JSONObject();
o.put("start", start);
o.put("end", end);
return o;
}
};
fakeIdsExtractor = new IDataExtractor() {
@Override
public JSONObject[] extractData(JSONObject obj, String key) {
JSONArray data = (JSONArray) obj.get("data");
JSONObject idsObj = (JSONObject) data.get(0);
String fakeId = (String) idsObj.get("parkingPlaceId");
JSONObject o = new JSONObject();
o.put("parkingPlaceId", fakeId);
return new JSONObject[]{o};
}
};
}
}
|
package com.bcgbcg.br.dto;
public class BCDto {
private int MON,TUE,WEN,TUR,FRI,SAT,SUN;
public BCDto() {
super();
// TODO Auto-generated constructor stub
}
public BCDto(int mON, int tUE, int wEN, int tUR, int fRI, int sAT, int sUN) {
super();
MON = mON;
TUE = tUE;
WEN = wEN;
TUR = tUR;
FRI = fRI;
SAT = sAT;
SUN = sUN;
}
public int getMON() {
return MON;
}
public void setMON(int mON) {
MON = mON;
}
public int getTUE() {
return TUE;
}
public void setTUE(int tUE) {
TUE = tUE;
}
public int getWEN() {
return WEN;
}
public void setWEN(int wEN) {
WEN = wEN;
}
public int getTUR() {
return TUR;
}
public void setTUR(int tUR) {
TUR = tUR;
}
public int getFRI() {
return FRI;
}
public void setFRI(int fRI) {
FRI = fRI;
}
public int getSAT() {
return SAT;
}
public void setSAT(int sAT) {
SAT = sAT;
}
public int getSUN() {
return SUN;
}
public void setSUN(int sUN) {
SUN = sUN;
}
}
|
package package1;
import javax.swing.*;
import javax.swing.border.Border;
import javax.swing.border.LineBorder;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
/**********************************************************************
* Creates the Panel for the TicTacToe GUI
*
* @author Jarod Collier and Ben Burger
* @version 6/12/2018
*********************************************************************/
public class SuperTicTacToePanel extends JPanel {
/** Declares the JButton for the 2D Array board */
private JButton[][] board;
/** Declares the JButton for the quit button */
private JButton quitButton;
/** Declares the JButton for the undo button */
private JButton undoButton;
/** Declares the JButton for the reset button */
private JButton resetButton;
/** Declares the JLabel for the label of X wins */
private JLabel xWon;
/** Declares the JLabel for the label of O wins */
private JLabel oWon;
/** Declares the JLabel for the label that stores X win total */
private JLabel labxWins;
/** Declares the JLabel for the label that stores O win total */
private JLabel laboWins;
/** Declares a sub-panel named bottom */
private JPanel bottom;
/** Declares a sub-panel named bottom */
private JPanel center;
/** Declares the ImageIcon for the empty space in the board */
private ImageIcon emptyIcon;
/** Declares the ImageIcon for the X space in the board */
private ImageIcon xIcon;
/** Declares the ImageIcon for the O space in the board */
private ImageIcon oIcon;
/** Declares a button listener */
private ButtonListener listener;
/** Checks the status of each cell */
private CellStatus iCell;
/** Declares a new TicTactoe game */
private SuperTicTacToeGame game;
/** Integer for the desired board size */
private int size;
/** Integer for the desired connections needed to win */
private int connectionsToWin;
/** Integer to keep track of who's turn it is */
private int turn;
/** 2D Array to keep track of all the moves on the board */
private int [][] turnSelection;
/** Integer that keeps track of who moves first */
private int moveFirst;
/** Integer that is set to 1 or 2 depending who goes first */
private int firstTurn;
/** Boolean to check if the game has started */
private boolean gameStart = true;
/** Boolean to check if the cancel button was pressed */
private boolean cancel = false;
public SuperTicTacToePanel() {
// create bottom panel
// (contains undo, quit, reset buttons and win totals)
bottom = new JPanel();
// set images for the icons
emptyIcon = new ImageIcon("blank.png");
xIcon = new ImageIcon("x.png");
oIcon = new ImageIcon("o.png");
// create action listener
listener = new ButtonListener();
// create and add undo, quit, reset buttons
quitButton = new JButton("Quit");
quitButton.addActionListener(listener);
undoButton = new JButton("Undo");
undoButton.addActionListener(listener);
resetButton = new JButton("Reset");
resetButton.addActionListener(listener);
// method call to create board
createBoard();
// method call to display board
displayBoard();
// set layout for bottom panel
bottom.setLayout (new GridLayout(4,2,0,0));
// setting text for labels
labxWins = new JLabel ("X Wins: ");
laboWins = new JLabel ("O Wins: ");
xWon = new JLabel ("0");
oWon = new JLabel ("0");
// adding labels and buttons to bottom panel
bottom.add(labxWins);
bottom.add(xWon);
bottom.add(laboWins);
bottom.add(oWon);
bottom.add(quitButton);
bottom.add(undoButton);
bottom.add(resetButton);
// adding bottom and center panels
add (bottom);
add (center);
}
/******************************************************************
* Displays the TicTacToe board by setting the image in each cell.
* @param none
* @return none
* @throws none
*****************************************************************/
private void displayBoard() {
// nested for loop, sets image in each cell of the board
for (int row = 0; row < game.getBoard().length; row++)
for (int col = 0; col < game.getBoard().length; col++) {
board[row][col].setIcon(emptyIcon);
iCell = game.getCell(row, col);
if (iCell == CellStatus.O)
board[row][col].setIcon(oIcon);
else if (iCell == CellStatus.X)
board[row][col].setIcon(xIcon);
else if (iCell == CellStatus.EMPTY)
board[row][col].setIcon(emptyIcon);
}
}
/******************************************************************
* Creates a TicTacToe board.
* @param none
* @return none
* @throws none
*****************************************************************/
public void createBoard () {
// asks user for the desired board size
boolean goodNum = false;
goodNum = getValidBoardSize(goodNum);
getValidConnections();
getValidTurn();
// if the user didn't cancel
if (!cancel) {
// try to create a new game
try {
game = new SuperTicTacToeGame(size, connectionsToWin);
turn = 0;
turnSelection = new int [size*size][2];
gameStart = false;
}
catch (Exception e) {
JOptionPane.showMessageDialog(null, "Enter" +
" valid parameters.");
}
if (moveFirst == 1) {
firstTurn = 1;
game.setTurnX();
}
else if (moveFirst == 2) {
firstTurn = 2;
game.setTurnO();
}
// create new panel for the board, set layout
center = new JPanel();
center.setLayout(new GridLayout(size,size,3,2));
// create new button board
board = new JButton[size][size];
// nested for loops: adds buttons, sets board to blank,
// adds listeners
for (int row = 0; row < game.getBoard().length; row++)
for (int col = 0; col < game.getBoard().length; col++){
Border thickBorder = new LineBorder(Color.blue, 2);
board[row][col] = new JButton ("", emptyIcon);
board[row][col].setBorder(thickBorder);
board[row][col].addActionListener(listener);
center.add(board[row][col]);
}
}
// set cancel to false
cancel = false;
game.commandAI();
}
private void getValidTurn() {
// asks user who should start
boolean goodFirstTurn = false;
// stays in loop until valid first turn
// is entered or user hits cancel
while (!goodFirstTurn && !cancel) {
// prompt user if they want to go first or second
try {
String firstMove = JOptionPane.showInputDialog(null,
"Enter '1' to go first or '2' to got second:");
moveFirst = Integer.parseInt(firstMove);
}
catch (Exception e) {
// if the game just started
if (gameStart)
System.exit(0); // exit the program
else {
cancel = true; // set cancel to true
}
}
if (moveFirst == 1) {
goodFirstTurn = true;
}
else if (moveFirst == 2) {
goodFirstTurn = true;
}
else {
JOptionPane.showMessageDialog(null,
"Enter valid number");
}
}
}
private void getValidConnections() {
// asks user for the desired number of connections
boolean goodConnection = false;
// stays in loop until valid number of connections
// is entered or user hits cancel
while (!goodConnection && !cancel) {
try {
String connections = JOptionPane.showInputDialog(null,
"Enter number of connections needed to win: "
+ "\n (Must be >2 and less than the "
+ "size of the board)");
connectionsToWin = Integer.parseInt(connections);
}
catch (Exception e) {
// if the game just started
if (gameStart)
System.exit(0); // exit the program
else
cancel = true; // set cancel to true
}
if (connectionsToWin > 2 && connectionsToWin <= size)
goodConnection = true;
else
JOptionPane.showMessageDialog(null, "Enter" +
" valid amount of connections.");
}
}
private boolean getValidBoardSize(boolean goodNum) {
// stays in loop until valid size is entered or
// user hits cancel
while (!goodNum && !cancel) {
try {
String boardSize = JOptionPane.showInputDialog(null,
"Enter in the size of the board: \n "
+ "(Must be 2 < n < 10)");
size = Integer.parseInt(boardSize);
}
catch(Exception e) {
// if the game just started
if (gameStart)
System.exit(0); // exit the program
else
cancel = true; // set cancel to true
}
if (size > 2 && size < 10)
goodNum = true;
else
JOptionPane.showMessageDialog(null, "Enter" +
" valid board size.");
}
return goodNum;
}
private class ButtonListener implements ActionListener {
/**************************************************************
* Determines what happens when the User clicks something
* @param ActionEvent e used to tell computer the User clicked
* @return none
* @throws none
*************************************************************/
public void actionPerformed(ActionEvent e) {
// if quit button is clicked, exit program
if (quitButton == e.getSource())
System.exit(0);
// if reset button is clicked
if (resetButton == e.getSource()) {
JOptionPane.showMessageDialog(null,
"The game will reset");
// reset game, create new board, add new center panel
game.reset();
if (firstTurn == 1) {
game.setTurnX();
}
if (firstTurn == 2) {
game.setTurnO();
}
remove(center);
createBoard();
add (center);
// display new board
displayBoard();
revalidate();
repaint();
game.commandAI();
displayBoard();
}
// nested for loops, determines which cell was selected
for (int row = 0; row < game.getBoard().length; row++) {
for (int col = 0;
col < game.getBoard().length; col++) {
if (board[row][col] == e.getSource()
&& game.isEmpty(row,col)) {
// select method
game.select (row,col);
// storing coordinates of the selected cell
turnSelection [turn][0] = row;
turnSelection [turn][1] = col;
// increment turn
turn++;
displayBoard();
checkForEndGame();
int selection [];
selection = game.commandAI();
// store coordinates of AI selected cell
turnSelection [turn][0] = selection[0];
turnSelection [turn][1] = selection[1];
// increment turn
turn++;
displayBoard();
checkForEndGame();
}
}
}
displayBoard();
// undo button is clicked
if (undoButton == e.getSource()) {
if (turn >= 2) {
// undo the last user move and AI move
game.undo(turnSelection[turn-1][0],
turnSelection[turn-1][1]);
game.undo(turnSelection[turn-2][0],
turnSelection[turn-2][1]);
turn = turn - 2;
}
else {
JOptionPane.showMessageDialog(null,
"Cannot undo");
}
displayBoard();
}
}
}
/******************************************************************
* Checks whether the game has ended by X or O winning or a tie
* @param none
* @return none
* @throws none
*****************************************************************/
public void checkForEndGame () {
// checking if O (AI) won
if (game.getGameStatus() == GameStatus.O_WON) {
JOptionPane.showMessageDialog(null, "O won and "
+ "X lost!\n The game will reset");
game.reset();
if (firstTurn == 1) {
game.setTurnX();
}
if (firstTurn == 2) {
game.setTurnO();
}
turn = 0;
turnSelection = new int [size*size][2];
game.commandAI();
displayBoard();
oWon.setText("" +
(Integer.parseInt(oWon.getText()) + 1));
}
// checking if X (user) won
if (game.getGameStatus() == GameStatus.X_WON) {
JOptionPane.showMessageDialog(null, "X won and "
+ "O lost!\n The game will reset");
game.reset();
if (firstTurn == 1) {
game.setTurnX();
}
if (firstTurn == 2) {
game.setTurnO();
}
turn = 0;
turnSelection = new int [size*size][2];
game.commandAI();
displayBoard();
xWon.setText("" +
(Integer.parseInt(xWon.getText()) + 1));
}
// checking if game is a tie
if (game.getGameStatus() == GameStatus.CATS) {
JOptionPane.showMessageDialog(null, "Tie game!" +
"\n The game will reset");
game.reset();
if (firstTurn == 1) {
game.setTurnX();
}
if (firstTurn == 2) {
game.setTurnO();
}
turn = 0;
turnSelection = new int [size*size][2];
game.commandAI();
displayBoard();
}
}
}
|
package com.dudg.demo.web;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication(scanBasePackages = "com.dudg.demo")
@MapperScan("com.dudg.demo.dao.mapper")
public class DemoWebApplication {
public static void main(String[] args) {
SpringApplication.run(DemoWebApplication.class,args);
}
}
|
package com.tt.miniapp.feedback.entrance;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.v4.app.Fragment;
import android.support.v4.app.k;
import android.text.TextUtils;
import com.storage.async.Action;
import com.storage.async.Function;
import com.storage.async.Observable;
import com.storage.async.Schedulers;
import com.storage.async.Subscriber;
import com.tt.miniapp.AppbrandConstant;
import com.tt.miniapp.base.activity.IActivityResultHandler;
import com.tt.miniapp.feedback.entrance.vo.FAQItemVO;
import com.tt.miniapp.feedback.entrance.vo.FeedbackParam;
import com.tt.miniapp.feedback.report.ReportHelper;
import com.tt.miniapp.feedback.report.ReportNetHelper;
import com.tt.miniapp.manager.NetManager;
import com.tt.miniapp.manager.UserInfoManager;
import com.tt.miniapp.thread.ThreadPools;
import com.tt.miniapp.thread.ThreadUtil;
import com.tt.miniapphost.AppBrandLogger;
import com.tt.miniapphost.entity.AppInfoEntity;
import com.tt.miniapphost.host.HostDependManager;
import com.tt.miniapphost.language.LocaleManager;
import com.tt.miniapphost.util.CharacterUtils;
import com.tt.miniapphost.util.UIUtils;
import com.tt.miniapphost.view.BaseActivity;
import com.tt.option.q.i;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.atomic.AtomicBoolean;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class FAQActivity extends BaseActivity implements BaseFAQFragment.FAQPresenter {
private AppInfoEntity mAppInfoEntity;
public FeedbackParam mFeedbackParam;
private k mFragmentManager;
private IActivityResultHandler mHandler = null;
public List<FAQItemVO> mItemList;
public JSONArray mListJsonArray;
public final Object mLock = new Object();
public volatile String mOpenId;
public AtomicBoolean mOpenIdPreloading;
public long mSelectItemId = -1L;
public static Intent genIntent(Context paramContext, FeedbackParam paramFeedbackParam, AppInfoEntity paramAppInfoEntity) {
return genIntent(paramContext, paramFeedbackParam, paramAppInfoEntity, -1L);
}
public static Intent genIntent(Context paramContext, FeedbackParam paramFeedbackParam, AppInfoEntity paramAppInfoEntity, long paramLong) {
Intent intent = new Intent(paramContext, FAQActivity.class);
intent.putExtra("key_request_param", (Parcelable)paramFeedbackParam);
intent.putExtra("key_appinfo_entity", (Parcelable)paramAppInfoEntity);
intent.putExtra("key_selected_item_id", paramLong);
return intent;
}
public static List<FAQItemVO> getFAQListFromJSONArray(JSONArray paramJSONArray) throws JSONException {
ArrayList<FAQItemVO> arrayList = new ArrayList();
for (int i = 0; i < paramJSONArray.length(); i++)
arrayList.add(FAQItemVO.from(paramJSONArray.getJSONObject(i)));
return arrayList;
}
private void initIntent() {
if (getIntent() == null)
return;
this.mFeedbackParam = (FeedbackParam)getIntent().getParcelableExtra("key_request_param");
this.mAppInfoEntity = (AppInfoEntity)getIntent().getParcelableExtra("key_appinfo_entity");
this.mSelectItemId = getIntent().getLongExtra("key_selected_item_id", this.mSelectItemId);
}
private void preloadOpenId() {
if (this.mFeedbackParam == null)
return;
this.mOpenIdPreloading = new AtomicBoolean(true);
Observable.create(new Action() {
public void act() {
FAQActivity fAQActivity = FAQActivity.this;
fAQActivity.mOpenId = UserInfoManager.requestOpenId(fAQActivity.mFeedbackParam.getHostAid(), FAQActivity.this.mFeedbackParam.getAid());
}
}).schudleOn(ThreadPools.longIO()).subscribe(new Subscriber() {
public void onError(Throwable param1Throwable) {
if (FAQActivity.this.mOpenIdPreloading != null)
FAQActivity.this.mOpenIdPreloading.set(false);
synchronized (FAQActivity.this.mLock) {
FAQActivity.this.mLock.notify();
return;
}
}
public void onSuccess() {
if (FAQActivity.this.mOpenIdPreloading != null)
FAQActivity.this.mOpenIdPreloading.set(false);
synchronized (FAQActivity.this.mLock) {
FAQActivity.this.mLock.notify();
return;
}
}
public void onSuccess(Object param1Object) {
if (FAQActivity.this.mOpenIdPreloading != null)
FAQActivity.this.mOpenIdPreloading.set(false);
synchronized (FAQActivity.this.mLock) {
FAQActivity.this.mLock.notify();
return;
}
}
});
}
public void addListFragment2Root(JSONArray paramJSONArray) {
FAQListFragment fAQListFragment;
if (paramJSONArray == null) {
fAQListFragment = FAQListFragment.newInstance(false, null);
} else {
fAQListFragment = FAQListFragment.newInstance((JSONArray)fAQListFragment, false, null);
}
this.mFragmentManager.a().a(2097545295, fAQListFragment).a(fAQListFragment.getClass().getSimpleName()).c();
}
public void addTargetFragment2Root(FAQItemVO paramFAQItemVO) {
FAQListFragment fAQListFragment;
JSONArray jSONArray = paramFAQItemVO.getChildren();
if (jSONArray == null || jSONArray.length() <= 0) {
FAQCommitFragment fAQCommitFragment;
if (TextUtils.isEmpty(paramFAQItemVO.getValue()) || paramFAQItemVO.getValue().equals("null")) {
fAQCommitFragment = FAQCommitFragment.newInstance(paramFAQItemVO);
} else {
FAQDetailFragment fAQDetailFragment = FAQDetailFragment.newInstance((FAQItemVO)fAQCommitFragment);
}
} else {
fAQListFragment = FAQListFragment.newInstance(jSONArray, false, null);
}
this.mFragmentManager.a().a(2097545295, fAQListFragment).a(fAQListFragment.getClass().getSimpleName()).c();
}
public void finish() {
super.finish();
overridePendingTransition(2131034235, UIUtils.getSlideOutAnimation());
}
public k getActivitySupportFragmentManager() {
return this.mFragmentManager;
}
public AppInfoEntity getAppInfoEntity() {
return this.mAppInfoEntity;
}
public FeedbackParam getFeedbackParam() {
return this.mFeedbackParam;
}
public String getOpenIdSync() {
if (TextUtils.isEmpty(this.mOpenId)) {
AtomicBoolean atomicBoolean = this.mOpenIdPreloading;
if (atomicBoolean != null && atomicBoolean.get())
synchronized (this.mLock) {
boolean bool = TextUtils.isEmpty(this.mOpenId);
if (bool)
try {
this.mLock.wait(1500L);
return this.mOpenId;
} catch (InterruptedException interruptedException) {
AppBrandLogger.e("tma_FAQActivity", new Object[] { "", interruptedException });
return CharacterUtils.empty();
}
}
}
return this.mOpenId;
}
public void onActivityResult(int paramInt1, int paramInt2, Intent paramIntent) {
super.onActivityResult(paramInt1, paramInt2, paramIntent);
IActivityResultHandler iActivityResultHandler = this.mHandler;
if (iActivityResultHandler != null)
iActivityResultHandler.handleActivityResult(paramInt1, paramInt2, paramIntent);
}
public void onAddFragment(Fragment paramFragment1, Fragment paramFragment2) {
this.mFragmentManager.a().a(2097545295, paramFragment2).b(paramFragment1).a(UIUtils.getSlideInAnimation(), 2131034242).a(paramFragment2.getClass().getSimpleName()).c();
}
public void onBackPressed() {
if (getSupportFragmentManager().e() == 1) {
finish();
return;
}
super.onBackPressed();
}
public void onCreate(Bundle paramBundle) {
super.onCreate(paramBundle);
setContentView(2097676292);
ReportHelper.init();
initIntent();
this.mFragmentManager = getSupportFragmentManager();
if (-1L == this.mSelectItemId) {
addListFragment2Root((JSONArray)null);
} else {
requestItemList(new BaseFAQFragment.OnRequestDataCallback() {
public void callbackItemList(List<FAQItemVO> param1List) {
FAQItemVO fAQItemVO;
FAQActivity fAQActivity;
List list = null;
if (param1List == null || param1List.isEmpty()) {
FAQActivity.this.addListFragment2Root((JSONArray)null);
return;
}
Iterator<FAQItemVO> iterator = param1List.iterator();
while (true) {
param1List = list;
if (iterator.hasNext()) {
fAQItemVO = iterator.next();
if (FAQActivity.this.mSelectItemId == fAQItemVO.getId())
break;
continue;
}
break;
}
if (fAQItemVO == null) {
fAQActivity = FAQActivity.this;
fAQActivity.addListFragment2Root(fAQActivity.mListJsonArray);
return;
}
FAQActivity.this.addTargetFragment2Root((FAQItemVO)fAQActivity);
}
});
}
preloadOpenId();
}
public void onPause() {
super.onPause();
if (ReportHelper.isReportOpen() && isFinishing())
ReportNetHelper.clearOptionCache();
}
public void requestItemList(final BaseFAQFragment.OnRequestDataCallback callback) {
List<FAQItemVO> list = this.mItemList;
if (list != null && !list.isEmpty()) {
callback.callbackItemList(this.mItemList);
return;
}
HostDependManager.getInst().showToast((Context)this, null, getString(2097741915), 10000L, "loading");
Observable.create(new Function<String>() {
public String fun() {
StringBuilder stringBuilder = new StringBuilder();
FeedbackParam feedbackParam = new FeedbackParam();
feedbackParam.setFeedbackAppkey(FAQActivity.this.mFeedbackParam.getFeedbackAppkey());
feedbackParam.setFeedbackAid(FAQActivity.this.mFeedbackParam.getFeedbackAid());
feedbackParam.setFeedbackAppName(FAQActivity.this.mFeedbackParam.getFeedbackAppName());
feedbackParam.setIid(FAQActivity.this.mFeedbackParam.getIid());
feedbackParam.setChannel(FAQActivity.this.mFeedbackParam.getChannel());
feedbackParam.setDeviceId(FAQActivity.this.mFeedbackParam.getDeviceId());
stringBuilder.append(AppbrandConstant.SnssdkAPI.getInst().getFeedbackQuestionList());
stringBuilder.append(feedbackParam.toParamString(FAQActivity.this.mFeedbackParam.getFeedbackAppkey(), FAQActivity.this.mFeedbackParam.getFeedbackAid(), FAQActivity.this.mFeedbackParam.getFeedbackAppName()));
Locale locale = LocaleManager.getInst().getCurrentLocale();
if (locale != null) {
String str1 = locale.getLanguage();
stringBuilder.append("&lang=");
stringBuilder.append(str1);
}
String str = stringBuilder.toString();
return NetManager.getInst().request(new i(str, "GET", false)).a();
}
}).schudleOn(Schedulers.longIO()).subscribe((Subscriber)new Subscriber.ResultableSubscriber<String>() {
public void onError(Throwable param1Throwable) {
ThreadUtil.runOnUIThread(new Runnable() {
public void run() {
HostDependManager.getInst().hideToast();
}
});
AppBrandLogger.e("tma_FAQActivity", new Object[] { "requestData", param1Throwable });
}
public void onSuccess(String param1String) {
try {
JSONObject jSONObject = new JSONObject(param1String);
FAQActivity.this.mListJsonArray = jSONObject.optJSONArray("list");
ReportHelper.tryInsertReportItem(FAQActivity.this.mListJsonArray);
FAQActivity.this.mItemList = FAQActivity.getFAQListFromJSONArray(FAQActivity.this.mListJsonArray);
ThreadUtil.runOnUIThread(new Runnable() {
public void run() {
HostDependManager.getInst().hideToast();
callback.callbackItemList(FAQActivity.this.mItemList);
}
});
return;
} catch (JSONException jSONException) {
AppBrandLogger.e("tma_FAQActivity", new Object[] { jSONException });
return;
}
}
});
}
public void setActivityResultHandler(IActivityResultHandler paramIActivityResultHandler) {
this.mHandler = paramIActivityResultHandler;
}
}
/* Location: C:\Users\august\Desktop\tik\df_miniapp\classes.jar!\com\tt\miniapp\feedback\entrance\FAQActivity.class
* Java compiler version: 6 (50.0)
* JD-Core Version: 1.1.3
*/
|
package org.apache.commons.net.io;
import java.util.EventListener;
import org.apache.commons.net.util.ListenerList;
public class CopyStreamAdapter implements CopyStreamListener {
private final ListenerList internalListeners = new ListenerList();
public void bytesTransferred(CopyStreamEvent event) {
for (EventListener listener : this.internalListeners)
((CopyStreamListener)listener).bytesTransferred(event);
}
public void bytesTransferred(long totalBytesTransferred, int bytesTransferred, long streamSize) {
for (EventListener listener : this.internalListeners)
((CopyStreamListener)listener).bytesTransferred(
totalBytesTransferred, bytesTransferred, streamSize);
}
public void addCopyStreamListener(CopyStreamListener listener) {
this.internalListeners.addListener(listener);
}
public void removeCopyStreamListener(CopyStreamListener listener) {
this.internalListeners.removeListener(listener);
}
}
/* Location: C:\Users\BSV\AppData\Local\Temp\Rar$DRa6216.20396\Preview\Preview.jar!\org\apache\commons\net\io\CopyStreamAdapter.class
* Java compiler version: 8 (52.0)
* JD-Core Version: 1.1.3
*/
|
package org.xtext.example.mydsl.tests.kmmv.compilateur;
import java.util.List;
import java.util.stream.Collectors;
import org.xtext.example.mydsl.mml.CrossValidation;
import org.xtext.example.mydsl.mml.DT;
import org.xtext.example.mydsl.mml.FrameworkLang;
import org.xtext.example.mydsl.mml.GTB;
import org.xtext.example.mydsl.mml.MLAlgorithm;
import org.xtext.example.mydsl.mml.RandomForest;
import org.xtext.example.mydsl.mml.SGD;
import org.xtext.example.mydsl.mml.SVR;
import org.xtext.example.mydsl.mml.StratificationMethod;
import org.xtext.example.mydsl.mml.TrainingTest;
public class Utils {
public static String algorithmName(MLAlgorithm algorithm) {
if(algorithm instanceof DT)
return "DT";
if(algorithm instanceof GTB)
return "GTB";
if(algorithm instanceof RandomForest)
return "RF";
if(algorithm instanceof SVR)
return "SVR";
if(algorithm instanceof SGD)
return "SGD";
return "";
}
public static String tab() {
return " ";
}
private static List<String> insertTab(List<String> data) {
return data.stream().map(el -> tab() + el).collect(Collectors.toList());
}
public static List<String> insertTab(List<String> data, int iteration) {
List<String> result = data;
for(int i=0; i < iteration; ++i) {
result = insertTab(result);
}
return result;
}
public static String stratificationToString(StratificationMethod stratification) {
if(stratification instanceof CrossValidation) {
int fold = 5;
if(stratification.getNumber() != 0)
fold = stratification.getNumber();
return String.format("CrossValidation_%d", fold);
}
if(stratification instanceof TrainingTest) {
double train = 0.7;
if(stratification.getNumber() > 0 && stratification.getNumber() < 100)
train = stratification.getNumber()/100.0;
return String.format("TrainingTest_%s", Double.toString(train)).replace('.', '_');
}
return "";
}
}
|
package org.samp;
public class First {
private void firstpgm() {
System.out.println("Welcome to Java Selinium course");
System.out.println("Week end batch");
System.out.println("Project class 2nd day class");
}
public static void main(String[] args) {
First f = new First();
f.firstpgm();
}
}
|
package com.tencent.mm.plugin.aa.a;
import com.tencent.mm.kernel.g;
import com.tencent.mm.plugin.aa.a.a.h;
import com.tencent.mm.vending.h.e;
public class e$a implements e<Void, Void> {
final /* synthetic */ e eAp;
public e$a(e eVar) {
this.eAp = eVar;
}
public final /* synthetic */ Object call(Object obj) {
d dVar = this.eAp.eAn;
h hVar = new h();
g.Ek();
g.Eh().dpP.a(hVar, 0);
dVar.eAc = com.tencent.mm.vending.g.g.cBL();
return uQG;
}
public final String xr() {
return "Vending.LOGIC";
}
}
|
package com.chocolate.chocoland;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class ChocolandApplication {
public static void main(String[] args) {
SpringApplication.run(ChocolandApplication.class, args);
}
}
|
package com.example.ideskdemo.object;
public class AdvertisementRating {
String ratingId;
String advertisementId;
public String getRatingId() {
return ratingId;
}
public void setRatingId(String ratingId) {
this.ratingId = ratingId;
}
String userId;
float rating;
String comment;
public String getAdvertisementId() {
return advertisementId;
}
public void setAdvertisementId(String advertisementId) {
this.advertisementId = advertisementId;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public float getRating() {
return rating;
}
public void setRating(float rating) {
this.rating = rating;
}
public String getComment() {
return comment;
}
public void setComment(String comment) {
this.comment = comment;
}
}
|
package org.automator.data.parser;
public interface IDataParser {
}
|
package com.team.zhihu.bean;
public class Good {
private Integer id;
private Integer userid;
private Integer eassayid;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getUserid() {
return userid;
}
public void setUserid(Integer userid) {
this.userid = userid;
}
public Integer getEassayid() {
return eassayid;
}
public void setEassayid(Integer eassayid) {
this.eassayid = eassayid;
}
}
|
/*
* Copyright © 2014 YAOCHEN Corporation, All Rights Reserved.
*/
package com.yaochen.address.data.domain.address;
import java.util.Date;
public class AdCollections {
/** 用户ID */
private String userid;
/** 收藏的地址的ID */
private Integer addrId;
/** */
private Date createTime;
public String getUserid() {
return userid;
}
public void setUserid(String userid) {
this.userid = userid == null ? null : userid.trim();
}
public Integer getAddrId() {
return addrId;
}
public void setAddrId(Integer addrId) {
this.addrId = addrId;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
}
|
package com.fundwit.sys.shikra.user.service;
import com.fundwit.sys.shikra.authentication.LoginUser;
import com.fundwit.sys.shikra.exception.ResourceNotFoundException;
import com.fundwit.sys.shikra.user.persistence.po.Identity;
import com.fundwit.sys.shikra.user.persistence.po.User;
import com.fundwit.sys.shikra.user.persistence.repository.IdentityRepository;
import com.fundwit.sys.shikra.user.persistence.repository.UserRepository;
import com.fundwit.sys.shikra.user.pojo.RegisterRequest;
import com.fundwit.sys.shikra.user.pojo.UserAccountInfo;
import com.fundwit.sys.shikra.util.IdWorker;
import org.h2.util.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import javax.transaction.Transactional;
import java.util.Date;
import java.util.UUID;
@Service
public class UserServiceImpl implements UserService{
private static final Logger LOG = LoggerFactory.getLogger(UserServiceImpl.class);
public static final String LOCAL_CREDENTIAL = "LOCAL_CREDENTIAL";
private IdWorker idWorker;
private UserRepository userRepository;
private IdentityRepository identityRepository;
private PasswordEncoder passwordEncoder;
private PasswordObfuscator passwordObfuscator;
public UserServiceImpl(
UserRepository userRepository,
IdentityRepository identityRepository,
IdWorker idWorker,
PasswordEncoder passwordEncoder,
PasswordObfuscator passwordObfuscator){
this.userRepository = userRepository;
this.identityRepository = identityRepository;
this.idWorker = idWorker;
this.passwordEncoder = passwordEncoder;
this.passwordObfuscator = passwordObfuscator;
}
@Override
public boolean existsByUsername(String username) {
return this.userRepository.existsByUsername(username);
}
@Override
public boolean existsByEmail(String email) {
return this.userRepository.existsByEmail(email);
}
@Override
public Mono<LoginUser> authenticate(String principal, String password) throws AuthenticationException {
User user = this.userRepository.findByUsernameOrEmail(principal, principal).orElseThrow(()-> new AuthenticationServiceException("user not found"));
Identity identity = identityRepository.findByUserIdAndType(user.getId(), LOCAL_CREDENTIAL);
String obfuscatedPassword = this.passwordObfuscator.obfuscate(password, user.getSalt());
if(identity==null || !passwordEncoder.matches(obfuscatedPassword, identity.getCredential())) {
throw new AuthenticationServiceException("authentication failed");
}
LoginUser loginUser = new LoginUser();
loginUser.setId(user.getId());
loginUser.setUsername(user.getUsername());
loginUser.setNickname(user.getNickname());
// TODO update token
return Mono.just(loginUser);
}
@Override
@Transactional
public Mono<User> createUser(RegisterRequest registerRequest) {
User user = new User();
user.setUsername(registerRequest.getUsername());
user.setNickname(StringUtils.isNullOrEmpty(registerRequest.getNickname()) ?
registerRequest.getUsername() : registerRequest.getNickname());
user.setEmail(registerRequest.getEmail());
user.setId(idWorker.nextId());
user.setSalt(UUID.randomUUID().toString().replace("-",""));
user.setActive(true);
user.setCreateAt(new Date());
user.setLastUpdateAt(user.getCreateAt());
User savedUser = userRepository.saveAndFlush(user);
Identity identity = new Identity();
identity.setId(idWorker.nextId());
identity.setUserId(savedUser.getId());
identity.setType(LOCAL_CREDENTIAL);
String obfuscatedPassword = this.passwordObfuscator.obfuscate(registerRequest.getPassword(), user.getSalt());
identity.setCredential(this.passwordEncoder.encode(obfuscatedPassword));
identity.setCreateAt(new Date());
identity.setLastUpdateAt(identity.getCreateAt());
identity.setExternalId(null);
Identity savedIdentity = identityRepository.saveAndFlush(identity);
Assert.notNull(savedIdentity);
return Mono.just(savedUser);
}
@Override
public Mono<User> findUser(Long userId) {
Assert.notNull(userId, "parameter 'userId' must not null");
// getOne() EntityNotFoundException
User user = userRepository.findById(userId).orElseThrow(()-> new ResourceNotFoundException("User", "id", userId+""));
return Mono.just(user);
}
@Override
public Flux<User> listUser(){
return Flux.fromIterable(userRepository.findAll());
}
@Override
public Mono<User> updateUser(Long userId, UserAccountInfo userInfo){
User user = userRepository.findById(userId)
.orElseThrow(()-> new ResourceNotFoundException(User.class.getSimpleName(), "id", String.valueOf(userId)));
user.setUsername(userInfo.getUsername());
user.setNickname(userInfo.getNickname());
user.setEmail(userInfo.getEmail());
user.setPhone(userInfo.getPhone());
user.setLastUpdateAt(new Date());
userRepository.saveAndFlush(user);
return Mono.just(user);
}
@Override
public Mono<Void> deleteUser(Long userId) {
// EmptyResultDataAccessException
userRepository.deleteById(userId);
return Mono.empty();
}
}
|
/*
Punit Shah and Jack Ingalls
2007 New Mexico Supercomputing Challenge
School: Albuquerque Academy
Team: 7
Project Name: Deriving Ramsey Numbers
*/
//------------------------------------------------------------------------------------------
// These methods help to debug aspects of the program by printing information to the console
// window or modifying variables to test cases
//------------------------------------------------------------------------------------------
class Debugging
{
//private debugging debugger = new debugging();;
public Debugging()
{
}
public void printInt1DArray (int array[])
{
for (int i = 0; i < array.length; i++)
{
System.out.print(array[i] + " ");
}
System.out.println();
}
public void printInt2DArray (int array[][])
{
for (int i = 0; i < array.length; i++)
{
printInt1DArray(array[i]);
}
}
public void printBool1DArray (boolean array[])
{
for (int i = 0; i < array.length; i++)
{
System.out.print(array[i] + " ");
}
System.out.println();
}
public void printBool2DArray (boolean array[][])
{
for (int i = 0; i < array.length; i++)
{
printBool1DArray(array[i]);
}
}
public void setWholeArrayToTrue (boolean theMap[][])
{
// this method sets all of the values of the array to true
for (int i = 0; i < theMap.length; i++)
{
for (int k = 0; k < theMap[i].length; k++)
{
theMap[i][k] = true;
}
}
}
public void set5NodeMapToNonmonochromaticConfig(boolean theMap[][])
{
//all outside painted true; all inside painted false (this is a 5 node map with no monochromatic 3 node submaps
theMap[1][0] = true;
theMap[2][0] = false;
theMap[2][1] = true;
theMap[3][0] = false;
theMap[3][2] = true;
theMap[3][1] = false;
theMap[3][0] = false;
theMap[4][0] = true;
theMap[4][1] = false;
theMap[4][2] = false;
theMap[4][3] = true;
}
}
|
package org.springframework.sync.diffsync;
import java.io.Serializable;
public interface IPersistenceCallbackRegistry {
void addPersistenceCallback(PersistenceCallback<? extends Serializable> persistenceCallback);
PersistenceCallback<? extends Serializable> findPersistenceCallback(String key);
}
|
package edu.uis.mastermind.view;
import java.awt.Color;
import java.awt.Font;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.UIManager;
public class GreetingScreen {
public JFrame frmWelcome;
private JButton player1Button;
private JButton player2Button;
// Create the application.
public GreetingScreen() {
initialize();
}
// Initialize the contents of the frame.
private void initialize() {
frmWelcome = new JFrame();
frmWelcome.getContentPane().setBackground(new Color(176, 196, 222));
frmWelcome.setTitle("Welcome ");
frmWelcome.setBounds(100, 100, 445, 365);
frmWelcome.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frmWelcome.getContentPane().setLayout(null);
player1Button = new JButton("1 player");
player1Button.setFont(new Font("Segoe UI", Font.PLAIN, 14));
player1Button.setBackground(UIManager.getColor("Button.light"));
player1Button.setBounds(91, 200, 239, 41);
player1Button.setActionCommand("PLAYER_1");
frmWelcome.getContentPane().add(player1Button);
player2Button = new JButton("2 player");
player2Button.setFont(new Font("Segoe UI", Font.PLAIN, 14));
player2Button.setBackground(UIManager.getColor("Button.light"));
player2Button.setBounds(91, 261, 239, 41);
player2Button.setActionCommand("PLAYER_2");
frmWelcome.getContentPane().add(player2Button);
/*
* player2Button.addActionListener(new ActionListener() {
*
* public void actionPerformed(ActionEvent e) { NameEntryForm window =
* new NameEntryForm(); window.frmPlayers.setVisible(true);
* frmWelcome.setVisible(false); } });
*/
JLabel lblMastermind = new JLabel("Mastermind");
lblMastermind.setFont(new Font("Vivaldi", Font.PLAIN, 70));
lblMastermind.setBounds(54, 11, 313, 87);
frmWelcome.getContentPane().add(lblMastermind);
CodePegButton peg1 = new CodePegButton();
peg1.setBounds(65, 115, 40, 10);
frmWelcome.getContentPane().add(peg1);
CodePegButton peg2 = new CodePegButton();
peg2.setBounds(115, 115, 40, 10);
frmWelcome.getContentPane().add(peg2);
CodePegButton peg3 = new CodePegButton();
peg3.setBounds(165, 115, 40, 10);
frmWelcome.getContentPane().add(peg3);
CodePegButton peg4 = new CodePegButton();
peg4.setBounds(215, 115, 40, 10);
frmWelcome.getContentPane().add(peg4);
CodePegButton peg5 = new CodePegButton();
peg5.setBounds(267, 115, 40, 10);
frmWelcome.getContentPane().add(peg5);
CodePegButton peg6 = new CodePegButton();
peg6.setBounds(317, 115, 40, 10);
frmWelcome.getContentPane().add(peg6);
peg1.setBackground(Color.RED);
peg2.setBackground(Color.BLUE);
peg3.setBackground(Color.GREEN);
peg4.setBackground(Color.YELLOW);
peg5.setBackground(Color.BLACK);
peg6.setBackground(Color.WHITE);
peg1.setEnabled(false);
peg2.setEnabled(false);
peg3.setEnabled(false);
peg4.setEnabled(false);
peg5.setEnabled(false);
peg6.setEnabled(false);
// plasyer selects game modes
JLabel lblPleaseSelectGame = new JLabel("Please select game mode ");
lblPleaseSelectGame.setFont(new Font("Segoe UI", Font.PLAIN, 20));
lblPleaseSelectGame.setBounds(95, 149, 313, 29);
frmWelcome.getContentPane().add(lblPleaseSelectGame);
}
public JButton getPlayer1Button() {
return player1Button;
}
public JButton getPlayer2Button() {
return player2Button;
}
}
|
package com.ts.timesTable.vo;
public class TimesTableVo {
private int firstTimes;
private int lastTimes;
private int firstMultiplier;
private int lastMultiplier;
public int getFirstTimes() {
return firstTimes;
}
public void setFirstTimes(int firstTimes) {
this.firstTimes = firstTimes;
}
public int getLastTimes() {
return lastTimes;
}
public void setLastTimes(int lastTimes) {
this.lastTimes = lastTimes;
}
public int getFirstMultiplier() {
return firstMultiplier;
}
public void setFirstMultiplier(int firstMultiplier) {
this.firstMultiplier = firstMultiplier;
}
public int getLastMultiplier() {
return lastMultiplier;
}
public void setLastMultiplier(int lastMultiplier) {
this.lastMultiplier = lastMultiplier;
}
}
|
package main.java;
import java.lang.*;
import java.lang.System;
import java.util.concurrent.ThreadFactory;
/**
* Created by alexiaborchgrevink on 11/17/17.
*/
public class CustomThreadFactory {
private String name;
private int counter;
private int maxThreads;
public CustomThreadFactory(String name, int maxThreads){
this.name = name;
this.maxThreads=maxThreads;
}
public Thread newThread(Job r) {
this.counter++;
return new Thread(r, name+"-"+counter);
}
public int getCounter(){
return this.counter;
}
}
|
package com.tencent.mm.plugin.emoji.ui.v2;
import android.graphics.Bitmap;
import com.tencent.mm.ak.a.c.i;
class EmojiStoreV2DesignerUI$15 implements i {
final /* synthetic */ EmojiStoreV2DesignerUI ipH;
EmojiStoreV2DesignerUI$15(EmojiStoreV2DesignerUI emojiStoreV2DesignerUI) {
this.ipH = emojiStoreV2DesignerUI;
}
public final void a(String str, Bitmap bitmap, Object... objArr) {
if (EmojiStoreV2DesignerUI.j(this.ipH) != null) {
EmojiStoreV2DesignerUI.j(this.ipH).sendEmptyMessage(10001);
}
}
}
|
package LeetCode.Problems.medium;
import java.util.*;
public class LongestContinuousSubarrayWithAbsolute {
public static void main(String[] arg0){
System.out.println(getSubstringSize(new int[]{10,1,2,4,7,2},5)); //4
System.out.println(getSubstringSize(new int[]{4,2,2,2,4,4,2,2},0)); //3
System.out.println(getSubstringSize(new int[]{8,2,4,7},4)); //2
}
public static int getSubstringSize(int[] nums, int limit){
if(nums.length==1) return 1;
Deque<Integer> ar= new LinkedList<>();
int i=0,j=0,max=0;
while (i< nums.length && j< nums.length){
if (ar.equals(null) || ar.size() ==0){
ar.add(nums[j]);
j++;
}else if(Math.abs(Collections.max(ar)-Collections.min(ar))>limit){
ar.pop();
i++;
}else {
max= Math.max(ar.size(),max);
ar.add(nums[j]);
j++;
}
}
if(Math.abs(Collections.max(ar)-Collections.min(ar))<=limit){
max= Math.max(ar.size(),max);
}
return max;
}
}
|
/*
* 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 dao;
import dto.EmployeeDTO;
import dto.UserDTO;
import dto.UserProfileInfoDTO;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
/**
*
* @author ASUS
*/
public class UserDAO {
private String sql;
public int addUser(UserDTO user,Connection connection) throws SQLException{
Statement statement = connection.createStatement();
return statement.executeUpdate("insert into users values('"+user.getEmp_Id()+"','"+user.getUserID()+"','"+user.getUser_Level()+"','"+user.getPassword()+"')");
}
public ArrayList<UserDTO> getAllUsers(Connection connection) throws SQLException{
Statement statement = connection.createStatement();
ResultSet result = statement.executeQuery("select * from users order by 1");
result.beforeFirst();
ArrayList<UserDTO> list = new ArrayList<>();
while (result.next()) {
UserDTO userDTO = new UserDTO();
userDTO.setEmp_Id(result.getString(1));
userDTO.setUserID(result.getString(2));
userDTO.setUser_Level(result.getString(3));
list.add(userDTO);
}
return list;
}
public ArrayList<EmployeeDTO> getAllEmployee(Connection connection) throws SQLException {
Statement statement = connection.createStatement();
ResultSet result = statement.executeQuery("select * from work_force order by 1");
result.beforeFirst();
ArrayList<EmployeeDTO> list = new ArrayList<>();
while (result.next()) {
EmployeeDTO empDTO = new EmployeeDTO();
empDTO.setEmpId(result.getString(1));
empDTO.setFname(result.getString(2));
empDTO.setLname(result.getString(3));
empDTO.setGender(result.getString(4));
empDTO.setNIC(result.getString(5));
empDTO.setDOB(result.getString(6));
empDTO.setAddress(result.getString(7));
empDTO.setEPFNo(result.getString(8));
empDTO.setPhoto(result.getString(9));
empDTO.setPassportNo(result.getString(10));
empDTO.setEmail(result.getString(13));
list.add(empDTO);
}
return list;
}
public UserDTO getUser(String userId,Connection connection) throws SQLException{
Statement statement = connection.createStatement();
ResultSet userResult = statement.executeQuery("select * from users where userId = '"+userId+"'");
UserDTO userDTO = new UserDTO();
userResult.beforeFirst();
if(userResult.next()){
userDTO.setUserID(userResult.getString(2));
userDTO.setPassword(userResult.getString(4));
userDTO.setEmp_Id(userResult.getString(1));
userDTO.setUser_Level(userResult.getString(3));
}
return userDTO;
}
public UserProfileInfoDTO getUserProfileInfo(String empId,Connection connection) throws SQLException{
Statement statement = connection.createStatement();
String sql = "select e.Emp_Id,e.FName,e.LName,e.Photo,e.Email,c.Name from work_force e,cardre c where e.Cardre_Id = c.Cardre_Id AND e.Emp_Id = '"+empId+"'";
ResultSet resultSet = statement.executeQuery(sql);
UserProfileInfoDTO userProfileInfoDTO = new UserProfileInfoDTO();
resultSet.beforeFirst();
if(resultSet.next()){
userProfileInfoDTO.setEmpId(resultSet.getString(1));
userProfileInfoDTO.setName(resultSet.getString(2)+" "+resultSet.getString(3));
userProfileInfoDTO.setPhoto(resultSet.getBlob(4));
userProfileInfoDTO.setEmail(resultSet.getString(5));
}
return userProfileInfoDTO;
}
public int updateUser(UserDTO user,Connection connection) throws SQLException{
Statement statement = connection.createStatement();
return statement.executeUpdate("update users set userId = '"+user.getUserID()+"',user_level = '"+user.getUser_Level()+"' where Emp_id = '"+user.getEmp_Id()+"'");
}
public int deleteUser(String empNo, Connection connection) throws SQLException {
Statement statement = connection.createStatement();
return statement.executeUpdate("delete from users where Emp_Id='" +empNo+"'");
}
public int changePassword(String username, String password, Connection connection) throws SQLException {
Statement statement = connection.createStatement();
return statement.executeUpdate("update users set password = '"+password+"' where userId = '"+username+"'");
}
}
|
package br.usp.memoriavirtual.modelo.fachadas.remoto;
import java.util.Map;
import javax.ejb.Remote;
import br.usp.memoriavirtual.modelo.fachadas.ModeloException;
@Remote
public interface ValidacaoRemote {
public boolean validacaoUnico(String query, Object o,
Map<String, Object> parametros) throws ModeloException;
public boolean validacaoNaoExiste(String query, Object o,
Map<String, Object> parametros) throws ModeloException;
}
|
package com.tencent.mm.plugin.mmsight.ui;
public interface MMSightRecordButton$d {
void bfj();
}
|
package com.tencent.mm.plugin.bottle.ui;
import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.FrameLayout;
import android.widget.ImageView;
import com.tencent.mm.R;
import com.tencent.mm.model.au;
import com.tencent.mm.model.c;
import com.tencent.mm.model.k;
import com.tencent.mm.plugin.bottle.a.h.b;
import com.tencent.mm.plugin.game.gamewebview.jsapi.biz.aq;
import com.tencent.mm.sdk.platformtools.ag;
import com.tencent.mm.sdk.platformtools.bi;
import com.tencent.mm.storage.ai;
public class PickBottleUI extends FrameLayout implements OnClickListener, OnTouchListener {
private float density;
float fto;
float ftp;
ag handler = new ag();
private boolean hasInit = false;
BottleBeachUI hlO;
SprayLayout hmj;
PickedBottleImageView hmk;
ImageView hml;
private b hmm;
Runnable hmn = new 1(this);
Runnable hmo = new Runnable() {
public final void run() {
if (PickBottleUI.this.hmk != null && PickBottleUI.this.hmk.isShown()) {
PickBottleUI.this.hlO.nm(0);
}
}
};
public PickBottleUI(Context context, AttributeSet attributeSet) {
super(context, attributeSet);
this.hlO = (BottleBeachUI) context;
}
public PickBottleUI(Context context, AttributeSet attributeSet, int i) {
super(context, attributeSet, i);
this.hlO = (BottleBeachUI) context;
}
public void onFinishInflate() {
super.onFinishInflate();
initView();
}
public final void initView() {
if (!this.hasInit) {
this.hmk = (PickedBottleImageView) findViewById(R.h.bottle_picked_result_img);
this.hmj = (SprayLayout) this.hlO.findViewById(R.h.bottle_spray_fl);
this.hml = (ImageView) this.hlO.findViewById(R.h.bottle_close_frame_btn);
this.hmk.setOnClickListener(this);
if (!bi.ciW()) {
setBackgroundResource(R.g.bottle_pick_bg_spotlight_night);
}
setOnClickListener(this);
setOnTouchListener(this);
this.hasInit = true;
}
}
public void setVisibility(int i) {
this.hmj.setVisibility(i);
this.hmk.setVisibility(8);
super.setVisibility(i);
}
public void setDensity(float f) {
this.density = f;
}
public void onClick(View view) {
if (R.h.bottle_picked_result_img == view.getId()) {
if (this.hmk.getBottleTalker() != null) {
au.HU();
c.FW().Ys(this.hmk.getBottleTalker());
au.HU();
ai Yq = c.FW().Yq("floatbottle");
if (!(Yq == null || bi.oW(Yq.field_username))) {
Yq.eV(k.GB());
au.HU();
c.FW().a(Yq, Yq.field_username);
}
}
this.hlO.onClick(view);
}
}
public boolean onTouch(View view, MotionEvent motionEvent) {
int action = motionEvent.getAction();
if (action == 0) {
this.fto = motionEvent.getX();
this.ftp = motionEvent.getY();
} else if (action == 1) {
boolean z;
float x = motionEvent.getX();
float y = motionEvent.getY();
action = getHeight();
int width = getWidth();
action = (action * 550) / 800;
int i = (width - ((width * 120) / 480)) / 2;
width -= i;
if (y > ((float) action)) {
z = true;
} else if (x < ((float) i) - ((((float) i) * y) / ((float) action))) {
z = true;
} else {
z = x > ((((float) i) * y) / ((float) action)) + ((float) width);
}
if (z) {
if (!this.hmk.isShown()) {
if (this.hmm != null) {
b bVar = this.hmm;
au.DF().b(155, bVar);
au.DF().b(156, bVar);
au.DF().c(bVar.hkc);
this.hmm = null;
}
this.handler.removeCallbacks(this.hmn);
this.handler.removeCallbacks(this.hmo);
this.hlO.nm(0);
} else if (this.hmk.getBottleTalker() == null) {
this.hlO.nm(0);
}
} else if (F(x, y) && F(this.fto, this.ftp)) {
if (this.hmk.getBottleTalker() != null) {
au.HU();
c.FW().Ys(this.hmk.getBottleTalker());
au.HU();
ai Yq = c.FW().Yq("floatbottle");
if (!(Yq == null || bi.oW(Yq.field_username))) {
Yq.eV(k.GB());
au.HU();
c.FW().a(Yq, Yq.field_username);
}
}
this.hlO.onClick(this.hmk);
}
}
return true;
}
private boolean F(float f, float f2) {
int height = getHeight();
int width = getWidth();
int i = (width * 180) / 480;
int i2 = (height * 75) / 800;
float f3 = f - ((float) ((width * aq.CTRL_BYTE) / 480));
float f4 = f2 - ((float) ((height * 495) / 800));
if (((f4 * f4) / ((float) (i2 * i2))) + ((f3 * f3) / ((float) (i * i))) <= 1.0f) {
return true;
}
return false;
}
}
|
package com.yirmio.lockawayadmin.UI;
import android.app.Activity;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import com.yirmio.lockawayadmin.R;
public class UsersActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_users);
}
}
|
package pages;
import org.openqa.selenium.By;
import other.DriverStart;
import static com.codeborne.selenide.Selenide.$;
import static com.codeborne.selenide.Selenide.open;
public class JobsTutByStartingPage extends DriverStart {
private static final String URL = "https://jobs.tut.by/";
public void openStartingPage(){
open(URL);
}
public void writeSomeVacancy(String vacancyName){
$(By.xpath("//*[@class = 'supernova-search-group__input']//input")).sendKeys(vacancyName);
}
public void clickSearchButton(){
$(By.className("supernova-search-submit-text")).click();
}
}
|
package question2;
/**
* This class uses recursion to find length of a string.
* @author WahabEhsan
*/
public class Question2 {
/**
* Prints the length of string.
* @param args the command line arguments
*/
public static void main(String[] args) {
System.out.println(length("QuestionOneIsDone"));
}
/**
* This Method recursively finds length of a String
* @param word the string given
* @return the value zero if word is empty string or returns the recursive
* method length with new parameter plus one.
*/
public static int length(String word){
if("".equals(word)){//checks if the word is empty
return 0;
}
String newWord = word.substring(1);//cuts the first letter of the word and sets it to different variable
return 1 + length(newWord); //returns the recursice of the newWord plus one for length
}
}
|
package com.e6soft.form.service;
import com.e6soft.core.service.BaseService;
import com.e6soft.form.model.BaseFormType;
public interface BaseFormTypeService extends BaseService<BaseFormType,String> {
}
|
package chapter06;
public class Exercise06_25 {
public static void main(String[] args) {
System.out.println(convertMillis(555550000));
}
public static String convertMillis(long millis) {
String str="";
long second=millis/1_000;
int currentSecond=(int)(second%60);
int minute=(int)(second/60);
int currentMinute=minute%60;
int hour=minute/60;
str=hour+":"+currentMinute+":"+currentSecond;
return str;
}
}
|
package edu.weber;
import javax.swing.*;
import java.awt.*;
public class DepositWindow extends JFrame {
public DepositWindow(AccountHolder accountHolder)
{
super("Deposit for: " + accountHolder.getAccountNumber());
DepositPanel depositPanel = new DepositPanel(accountHolder);
add(depositPanel, BorderLayout.CENTER);
setSize(600, 500);
setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
setVisible(true);
}
}
|
package foo;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
public class Engine {
public static void main(String[] args) {
System.out.println("Java Persistence Api 2.2");
System.out.println("EclipseLink 2.5.2");
System.out.println("MySQL Connector/J 8.0.19");
}
EntityManager init() {
EntityManagerFactory entityFactory = Persistence
.createEntityManagerFactory("JavaPersistenceApi");
EntityManager entityManager = entityFactory.createEntityManager();
return entityManager;
}
void create(Model model) {
EntityManager em = init();
em.getTransaction().begin();
em.persist(model);
em.getTransaction().commit();
em.close();
System.out.println("Model successfully created.");
}
void read(int id) {
EntityManager em = init();
Model model = em.find(Model.class, id);
int i0 = model.getId();
String s0 = model.getFirstName();
String s1 = model.getLastName();
String s2 = model.getCountry();
System.out.printf("%d %s %s %s\n", i0, s0, s1, s2);
}
void update(int id0, String firstName, String lastName, String country) {
EntityManager em = init();
em.getTransaction().begin();
Model model = em.find(Model.class, id0);
model.setFirstName(firstName);
model.setLastName(lastName);
model.setCountry(country);
em.getTransaction().commit();
em.close();
System.out.println("Record successfully updated.");
}
void delete(int id) {
EntityManager em = init();
em.getTransaction().begin();
em.remove(id);
em.getTransaction().commit();
em.close();
System.out.println("Record successfully deleted.");
}
}
|
/*
* 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 problema1;
import java.util.*;
/**
*
* @author Eduardo
*/
public class Problema1 {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
int a; //declaramos variable
a=getAnio(); //variable asignada al metodo que pide dato
calculaBis(a); //metodo para determinar si es bisiesto o no
}
public static int getAnio(){ //Pedimos el año por teclado
int anio;
Scanner teclado=new Scanner(System.in);
System.out.println("Introduzca el año a verificar");
anio=teclado.nextInt();
return anio;
}
public static void calculaBis(int anio){ //determinaremos si es bisiesto o no
int anioCero=0;
if (anio%100==0){ //para ver si termina en 00
anioCero=anio;
if (anioCero%400==0){ //de ser asi tiene que ser divisible /400
System.out.println("El año es bisiesto");
}else System.out.println("El año no es bisiesto");
}else if (anio%100!=0){ //si no termina en 00
if (anio%4==0){ //solo debe ser divisible entre 4
System.out.println("El año es bisiesto");
}else System.out.println("El año no es bisiesto");
}
}
}
|
package edu.nju.logic.vo;
import edu.nju.data.entity.Question;
import edu.nju.logic.service.TimeService;
import org.springframework.beans.factory.annotation.Autowired;
/**
* Created by cuihao on 2016/7/25.
*/
public class QuestionApiVO {
private long questionId;
private long userId;
private String userName;
private String avaUrl;
private String title;
private String content;
private String questionUrl;
private String createAt;
private String updateAt;
public QuestionApiVO(Question question) {
this.questionId = question.getId();
this.userId = question.getAuthorId();
this.userName = question.getAuthor().getUserName();
this.avaUrl = question.getAuthor().getPhotoUri();
this.title = question.getTitle();
this.content = question.getContent();
}
public long getQuestionId() {
return questionId;
}
public void setQuestionId(long questionId) {
this.questionId = questionId;
}
public long getUserId() {
return userId;
}
public void setUserId(long userId) {
this.userId = userId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getAvaUrl() {
return avaUrl;
}
public void setAvaUrl(String avaUrl) {
this.avaUrl = avaUrl;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getQuestionUrl() {
return questionUrl;
}
public void setQuestionUrl(String questionUrl) {
this.questionUrl = questionUrl;
}
public String getCreateAt() {
return createAt;
}
public void setCreateAt(String createAt) {
this.createAt = createAt;
}
public String getUpdateAt() {
return updateAt;
}
public void setUpdateAt(String updateAt) {
this.updateAt = updateAt;
}
}
|
package mod.coda.ambients.client.renderer;
import javax.annotation.Nullable;
import mod.coda.ambients.client.model.ModelBird;
import mod.coda.ambients.common.entity.EntityBird;
import net.minecraft.client.model.ModelBase;
import net.minecraft.client.renderer.entity.RenderLiving;
import net.minecraft.client.renderer.entity.RenderManager;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
@SideOnly(value=Side.CLIENT)
public class RenderBird extends RenderLiving<EntityBird> {
public static ModelBase model;
private static final ResourceLocation[] BIRD_TEXTURE = new ResourceLocation[6];
public RenderBird(RenderManager render) {
super(render, (ModelBase)new ModelBird(), 0.1f);
}
@Nullable
protected ResourceLocation getEntityTexture(EntityBird entity) {
return BIRD_TEXTURE[entity.getVariant()];
}
static {
for (int i = 0; i < BIRD_TEXTURE.length; ++i) {
RenderBird.BIRD_TEXTURE[i] = new ResourceLocation("ambients", "textures/entity/texture_" + (i + 1) + ".png");
}
}
}
|
package org.adn.ceiba.ceibarest.bussines.impl;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Optional;
import org.adn.ceiba.ceibarest.adapter.TipoVehiculoAdapter;
import org.adn.ceiba.ceibarest.bussines.ITipoVehiculoBussines;
import org.adn.ceiba.ceibarest.dto.TipoVehiculoDTO;
import org.adn.ceiba.ceibarest.entity.TipoVehiculo;
import org.adn.ceiba.ceibarest.service.TipoVehiculoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
* clase manejadora del negocio de tipovehiculo
* @author jose.lozano
*
*/
@Service
public class TipoVehiculoBussines implements ITipoVehiculoBussines {
@Autowired
private TipoVehiculoService tipoVehiculoService;
@Override
public Collection<TipoVehiculoDTO> obtenerTipoVehiculos() {
Collection<TipoVehiculo> listaEntities = tipoVehiculoService.obtenerTipoVehiculos();
Optional<Collection<TipoVehiculoDTO>> listaOptional = TipoVehiculoAdapter
.getInstance().getListaVehiculoDTO(listaEntities);
return listaOptional.orElse(new ArrayList<>());
}
}
|
package com.tencent.mm.plugin.scanner.util;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import com.tencent.mm.model.au;
import com.tencent.mm.plugin.scanner.a.f;
class a$1 implements OnCancelListener {
final /* synthetic */ f mLs;
final /* synthetic */ a mMD;
public a$1(a aVar, f fVar) {
this.mMD = aVar;
this.mLs = fVar;
}
public final void onCancel(DialogInterface dialogInterface) {
this.mMD.bsT();
au.DF().c(this.mLs);
}
}
|
package ru.otus.adapters.json;
/*
* Created by VSkurikhin at autumn 2018.
*/
import ru.otus.adapters.DataSetAdapter;
import ru.otus.models.DeptEntity;
import javax.json.bind.adapter.JsonbAdapter;
public class DeptEntityJsonAdapter
implements JsonbAdapter<DeptEntity, String>, DataSetAdapter<DeptEntity>
{
@Override
public String adaptToJson(DeptEntity dept) throws Exception
{
return marshalAdapter(dept);
}
@Override
public DeptEntity adaptFromJson(String s) throws Exception
{
return unmarshalAdapter(s, DeptEntity.class);
}
}
/* vim: syntax=java:fileencoding=utf-8:fileformat=unix:tw=78:ts=4:sw=4:sts=4:et
*/
//EOF
|
package org.study.xml;
import javax.xml.bind.annotation.*;
import java.util.LinkedList;
import java.util.List;
/**
* Created by yur on 28.10.2015.
*/
@XmlRootElement(name = "CellSet")
@XmlAccessorType(XmlAccessType.NONE)
public class HBaseTable {
private List<HBaseRow> rows = new LinkedList<>();
public List<HBaseRow> getRows() {
return rows;
}
@XmlElement(name = "Row")
public void setRow(HBaseRow row) {
rows.add(row);
}
@Override
public String toString() {
return "HBaseTable{" +
"rows=" + rows +
'}';
}
}
|
package demo.dao;
import org.hibernate.annotations.GenericGenerator;
import javax.persistence.*;
import java.io.Serializable;
@Entity
@Table(name = "sys_user")
public class User implements Serializable {
private static final long serialVersionUID = 4543785261816598686L;
@Id
@GenericGenerator(name = "idGenerator", strategy = "uuid")
@GeneratedValue(generator = "idGenerator")
private String id;
private String username;
@Column(name = "pass_word")
private String password;
}
|
package com.tencent.mm.plugin.music.ui;
import com.tencent.mm.plugin.music.b.a.c.a;
class MusicMainUI$7 implements a {
final /* synthetic */ MusicMainUI lBe;
MusicMainUI$7(MusicMainUI musicMainUI) {
this.lBe = musicMainUI;
}
public final void co(int i, int i2) {
if (MusicMainUI.l(this.lBe) == 1 && !MusicMainUI.m(this.lBe)) {
float floatExtra = this.lBe.getIntent().getFloatExtra("key_offset", 0.0f);
floatExtra *= 1000.0f;
long currentTimeMillis = (long) (floatExtra + ((float) (System.currentTimeMillis() - this.lBe.getIntent().getLongExtra("music_player_beg_time", 0))));
if (currentTimeMillis >= 0) {
MusicMainUI.h(this.lBe).D(MusicMainUI.i(this.lBe).getCurrentItem(), currentTimeMillis + 200);
}
} else if (i >= 0 && i2 > 0) {
MusicMainUI.h(this.lBe).D(MusicMainUI.i(this.lBe).getCurrentItem(), (long) i);
}
}
}
|
// Sun Certified Java Programmer
// Chapter 6, P469
// Strings, I/O, Formatting, and Parsing
class Animal {
}
|
package gd26.asteroids;
import java.awt.*;
/**
* Shaped object class
*
* Created by gdorwin26 on 3/30/2017.
*/
public class ShapedObject extends GameObject
{
private Vec2D[] vertices;
private double radiusSquared;
public ShapedObject(Vec2D[] vertices)
{
this.vertices = vertices;
}
public ShapedObject()
{
}
public void render(Graphics g)
{
Graphics2D g2d = (Graphics2D) g.create();
g2d.translate((int) getPos().getX(), (int) getPos().getY());
g2d.setColor(new Color(32, 128, 255));
g2d.setStroke(new BasicStroke(2F));
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.drawLine((int) vertices[0].getX(), (int) vertices[0].getY(),
(int)vertices[vertices.length - 1].getX(), (int) vertices[vertices.length - 1].getY());
for(int i = 0; i < vertices.length - 1; i++)
{
g2d.drawLine((int) vertices[i].getX(), (int) vertices[i].getY(),
(int) vertices[i + 1].getX(), (int) vertices[i + 1].getY());
}
g2d.dispose();
}
public void setVertices(Vec2D[] vertices)
{
this.vertices = vertices;
}
public void rotate(double theta)
{
for(Vec2D vertex : vertices)
{
vertex.rot(theta);
}
}
public void setRadius(double radius)
{
radiusSquared = radius * radius;
}
public boolean checkCollision(ShapedObject so)
{
return MathUtil.squareDistance(getPos().getX(), getPos().getY(), so.getPos().getX(), so.getPos().getY()) <=
radiusSquared + so.radiusSquared;
}
public boolean checkCollision(Vec2D point)
{
return MathUtil.squareDistance(getPos().getX(), getPos().getY(), point.getX(), point.getY()) <= radiusSquared;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.