text
stringlengths 10
2.72M
|
|---|
/*
* Author: RINEARN (Fumihiro Matsui), 2020
* License: CC0
*/
package org.vcssl.nano.plugin.system.xfci1;
import org.vcssl.connect.ConnectorException;
import org.vcssl.connect.ConnectorPermissionName;
import org.vcssl.connect.EngineConnectorInterface1;
import org.vcssl.connect.ExternalFunctionConnectorInterface1;
// Interface Specification: https://www.vcssl.org/en-us/dev/code/main-jimpl/api/org/vcssl/connect/ExternalFunctionConnectorInterface1.html
// インターフェース仕様書: https://www.vcssl.org/ja-jp/dev/code/main-jimpl/api/org/vcssl/connect/ExternalFunctionConnectorInterface1.html
public class ExitIntXfci1Plugin implements ExternalFunctionConnectorInterface1 {
// パーミッション要求用にエンジンコネクタを控える
EngineConnectorInterface1 engineConnector = null;
// 初期化/終了時処理の引数に渡される、スクリプトエンジンと情報をやり取りするインターフェースの指定
@Override
public Class<?> getEngineConnectorClass() {
return EngineConnectorInterface1.class;
}
// 接続時の初期化
@Override
public void initializeForConnection(Object engineConnector) throws ConnectorException { }
// スクリプト実行前の初期化
@Override
public void initializeForExecution(Object engineConnector) throws ConnectorException {
// 処理系の情報を取得するコネクタ(処理系依存)の互換性を検査し、適合すればフィールドに控える
if (!(engineConnector instanceof EngineConnectorInterface1)) {
throw new ConnectorException(
"The type of the engine connector \"" +
engineConnector.getClass().getCanonicalName() +
"\" is not supported by this plug-in."
);
}
this.engineConnector = (EngineConnectorInterface1)engineConnector;
}
// スクリプト実行後の終了時処理
@Override
public void finalizeForDisconnection(Object engineConnector) throws ConnectorException { }
// 接続解除時の終了時処理
@Override
public void finalizeForTermination(Object engineConnector) throws ConnectorException { }
// 関数名を返す
@Override
public String getFunctionName() {
return "exit";
}
// int 型の引数を取るので、その内部表現の long 型を返す
@Override
public Class<?>[] getParameterClasses() {
return new Class<?>[] { long.class };
}
// データの自動変換を有効化しているので参照されない
@Override
public Class<?>[] getParameterUnconvertedClasses() {
return null;
}
// 引数名が定義されているので true を返す
@Override
public boolean hasParameterNames() {
return true;
}
// 引数名を返す
@Override
public String[] getParameterNames() {
return new String[] { "exitStatusCode" };
}
// 任意型の引数は取らないので false を返す
@Override
public boolean[] getParameterDataTypeArbitrarinesses() {
return new boolean[]{ false };
}
// 任意次元の引数は取らないので false を返す
@Override
public boolean[] getParameterArrayRankArbitrarinesses() {
return new boolean[]{ false };
}
// 参照渡しする必要はないので false を返す
@Override
public boolean[] getParameterReferencenesses() {
return new boolean[]{ false };
}
// 引数の中身を書き変えないので true を返す(そう宣言しておくと最適化で少し有利になる可能性がある)
@Override
public boolean[] getParameterConstantnesses() {
return new boolean[]{ true };
}
// 任意個の引数は取らないので false を返す
@Override
public boolean isParameterCountArbitrary() {
return false;
}
// 可変長引数は取らないので false を返す
@Override
public boolean hasVariadicParameters() {
return false;
}
// 戻り値は無いので、void 型を返す
@Override
public Class<?> getReturnClass(Class<?>[] parameterClasses) {
return void.class;
}
// データの自動変換を有効化しているので参照されない
@Override
public Class<?> getReturnUnconvertedClass(Class<?>[] parameterClasses) {
return null;
}
// 戻り値のデータ型は固定なので false
@Override
public boolean isReturnDataTypeArbitrary() {
return false;
}
// 戻り値の配列次元数は固定なので false
@Override
public boolean isReturnArrayRankArbitrary() {
return false;
}
// データ型の自動変換機能を利用するので true を返す
@Override
public boolean isDataConversionNecessary() {
return true;
}
// スクリプトから呼ばれた際に実行する処理
@Override
public Object invoke(Object[] arguments) throws ConnectorException {
// プログラムの終了を許可/拒否設定できるパーミッション項目が存在するため、終了前に要求しておく
// (却下されてもどのみち permission denied で終了するが、エラー扱いになるかどうかが異なる)
// (許可されればこの行では何も起こらず、拒否されればここで ConnectorException が発生する)
this.engineConnector.requestPermission(ConnectorPermissionName.PROGRAM_EXIT, this, new String[0]);
// 許可された場合、exit 関数による正常終了はエラー扱いにしたくないため、
// 特別に "__EXIT:終了ステータスコード" のメッセージを持たせた ConnectorException を投げる
// (そうするとスクリプトエンジン側がそう判断してくれる)
throw new ConnectorException("___EXIT:" + Long.toString((long)arguments[0]) );
}
}
|
package com.suntf.pkm.util;
import java.io.IOException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpResponseException;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.entity.BufferedHttpEntity;
import android.os.AsyncTask;
public class AsyncHttpSender extends AsyncTask<InputHolder, Void, OutputHolder> {
@Override
protected OutputHolder doInBackground(InputHolder... params) {
HttpEntity entity = null;
InputHolder input = params[0];
try {
HttpResponse response = AsyncHttpClient.getClient().execute((HttpUriRequest) input.getRequest());
StatusLine status = response.getStatusLine();
if(status.getStatusCode() >= 300) {
return new OutputHolder(
new HttpResponseException(status.getStatusCode(), status.getReasonPhrase()),
input.getResponseListener());
}
entity = response.getEntity();
// Log.i(TAG, "isChunked:" + entity.isChunked());
if(entity != null) {
try{
entity = new BufferedHttpEntity(entity);
}catch(Exception e){
// Log.e(<span style="background-color: #ffffff;">TAG</span>, e.getMessage(), e);
//ignore?
}
}
} catch (ClientProtocolException e) {
// Log.e(<span style="background-color: #ffffff;">TAG</span>, e.getMessage(), e);
return new OutputHolder(e, input.getResponseListener());
} catch (IOException e) {
// Log.e(<span style="background-color: #ffffff;">TAG</span>, e.getMessage(), e);
return new OutputHolder(e, input.getResponseListener());
}
return new OutputHolder(entity, input.getResponseListener());
}
@Override
protected void onPreExecute(){
// Log.i(<span style="background-color: #ffffff;">TAG</span>, "AsyncHttpSender.onPreExecute()");
super.onPreExecute();
}
@Override
protected void onPostExecute(OutputHolder result) {
// Log.i(<span style="background-color: #ffffff;">TAG</span>, "AsyncHttpSender.onPostExecute()");
super.onPostExecute(result);
if(isCancelled()){
// Log.i(<span style="background-color: #ffffff;">TAG</span>, "AsyncHttpSender.onPostExecute(): isCancelled() is true");
return; //Canceled, do nothing
}
AsyncResponseListener listener = result.getResponseListener();
HttpEntity response = result.getResponse();
Throwable exception = result.getException();
if(response!=null){
// Log.i(<span style="background-color: #ffffff;">TAG</span>, "AsyncHttpSender.onResponseReceived(response)");
listener.onResponseReceived(response);
}else{
// Log.i(<span style="background-color: #ffffff;">TAG</span>, "AsyncHttpSender.onResponseReceived(exception)");
listener.onResponseReceived(exception);
}
}
@Override
protected void onCancelled(){
// Log.i(<span style="background-color: #ffffff;">TAG</span>, "AsyncHttpSender.onCancelled()");
super.onCancelled();
//this.isCancelled = true;
}
}
|
package org.example.common.exception.request;
import org.example.common.exception.ExceptionEnumInterface;
import org.springframework.http.HttpStatus;
public interface ExceptionEnumInterface403 extends ExceptionEnumInterface {
@Override
default HttpStatus getType() {
return HttpStatus.FORBIDDEN;
}
}
|
import javax.swing.*;
import java.awt.*;
import java.awt.geom.Path2D;
public class Marker extends JComponent {
private final Path2D path2D;
private final Feature owner;
private final int side = 50;
private boolean isSelected;
Marker(Feature owner) {
isSelected = false;
this.owner = owner;
path2D = new Path2D.Double();
setPreferredSize(new Dimension(side, side));
setBounds(getPositionOffset().getX(), getPositionOffset().getY(), side, side);
drawPath();
}
public boolean isSelected() {
return isSelected;
}
void setSelected(boolean selected) {
isSelected = selected;
repaint();
}
private void drawPath() {
double yOffset = (side * 0.5);
double startX = (side / 2.0) * (1 - 1 / Math.sqrt(3));
double startY = (3.0 * side / 4.0);
path2D.moveTo(startX, startY - yOffset);
path2D.lineTo((side - startX), startY - yOffset);
path2D.lineTo((side / 2.0), (side * 1.25) - yOffset);
path2D.closePath();
}
@Override
public void paint(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
if (isSelected) {
g2.setPaint(Color.RED);
g2.setStroke(new BasicStroke(10));
g2.draw(path2D);
}
g2.setPaint(owner.getCategory().getColor());
g2.fill(path2D);
}
private Position getPositionOffset() {
return new Position(owner.getPosition().getX() - side / 2, (int) (owner.getPosition().getY() - side / 1.25));
}
}
|
package ua.training.controller.commands.action.admin;
import ua.training.constant.Attributes;
import ua.training.constant.Pages;
import ua.training.controller.commands.Command;
import ua.training.model.dao.utility.PasswordEncoder;
import ua.training.model.entity.User;
import ua.training.model.entity.enums.Roles;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Optional;
import static com.mysql.jdbc.StringUtils.isNullOrEmpty;
/**
* Description: This class update users parameters by 'ADMIN'
*
* @author Zakusylo Pavlo
*/
public class UpdateUsersByAdmin implements Command {
@Override
public String execute(HttpServletRequest request) {
User user = (User) request.getSession().getAttribute(Attributes.REQUEST_USER);
String emailUsers = request.getParameter(Attributes.REQUEST_EMAIL_USERS);
String password = request.getParameter(Attributes.REQUEST_PASSWORD);
String role = request.getParameter(Attributes.REQUEST_USER_ROLE);
boolean flag = false;
Optional<User> userSQL = USER_SERVICE_IMP.getOrCheckUserByEmail(emailUsers);
if (userSQL.isPresent()) {
if (!isNullOrEmpty(password)) {
flag = true;
userSQL.get()
.setPassword(PasswordEncoder.encodePassword(password));
}
if (!Roles.valueOf(role).equals(userSQL.get().getRole())) {
flag = true;
userSQL.get()
.setRole(Roles.valueOf(role));
}
}
if (flag) {
List<User> listUsers = (List<User>) request.getSession().getAttribute(Attributes.REQUEST_LIST_USERS);
listUsers.removeIf(u -> u.getEmail().equalsIgnoreCase(emailUsers));
USER_SERVICE_IMP.updateUserParameters(userSQL.get());
listUsers.add(userSQL.get());
request.getSession().setAttribute(Attributes.REQUEST_LIST_USERS, listUsers);
}
Integer forPage = USER_SERVICE_IMP.countUsers(user.getId());
request.getSession().setAttribute(Attributes.REQUEST_NUMBER_USERS, forPage);
return Pages.SHOW_USERS_AFTER_UPDATE_OR_SEARCH_REDIRECT;
}
}
|
/*
* Copyright 2002-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.aop.support;
import java.lang.reflect.Method;
import org.junit.jupiter.api.Test;
import org.springframework.aop.ClassFilter;
import org.springframework.aop.MethodMatcher;
import org.springframework.aop.Pointcut;
import org.springframework.beans.testfixture.beans.TestBean;
import org.springframework.core.NestedRuntimeException;
import org.springframework.lang.Nullable;
import static org.assertj.core.api.Assertions.assertThat;
/**
* @author Rod Johnson
* @author Chris Beams
*/
public class ComposablePointcutTests {
public static MethodMatcher GETTER_METHOD_MATCHER = new StaticMethodMatcher() {
@Override
public boolean matches(Method m, @Nullable Class<?> targetClass) {
return m.getName().startsWith("get");
}
};
public static MethodMatcher GET_AGE_METHOD_MATCHER = new StaticMethodMatcher() {
@Override
public boolean matches(Method m, @Nullable Class<?> targetClass) {
return m.getName().equals("getAge");
}
};
public static MethodMatcher ABSQUATULATE_METHOD_MATCHER = new StaticMethodMatcher() {
@Override
public boolean matches(Method m, @Nullable Class<?> targetClass) {
return m.getName().equals("absquatulate");
}
};
public static MethodMatcher SETTER_METHOD_MATCHER = new StaticMethodMatcher() {
@Override
public boolean matches(Method m, @Nullable Class<?> targetClass) {
return m.getName().startsWith("set");
}
};
@Test
public void testMatchAll() throws NoSuchMethodException {
Pointcut pc = new ComposablePointcut();
assertThat(pc.getClassFilter().matches(Object.class)).isTrue();
assertThat(pc.getMethodMatcher().matches(Object.class.getMethod("hashCode"), Exception.class)).isTrue();
}
@Test
public void testFilterByClass() throws NoSuchMethodException {
ComposablePointcut pc = new ComposablePointcut();
assertThat(pc.getClassFilter().matches(Object.class)).isTrue();
ClassFilter cf = new RootClassFilter(Exception.class);
pc.intersection(cf);
assertThat(pc.getClassFilter().matches(Object.class)).isFalse();
assertThat(pc.getClassFilter().matches(Exception.class)).isTrue();
pc.intersection(new RootClassFilter(NestedRuntimeException.class));
assertThat(pc.getClassFilter().matches(Exception.class)).isFalse();
assertThat(pc.getClassFilter().matches(NestedRuntimeException.class)).isTrue();
assertThat(pc.getClassFilter().matches(String.class)).isFalse();
pc.union(new RootClassFilter(String.class));
assertThat(pc.getClassFilter().matches(Exception.class)).isFalse();
assertThat(pc.getClassFilter().matches(String.class)).isTrue();
assertThat(pc.getClassFilter().matches(NestedRuntimeException.class)).isTrue();
}
@Test
public void testUnionMethodMatcher() {
// Matches the getAge() method in any class
ComposablePointcut pc = new ComposablePointcut(ClassFilter.TRUE, GET_AGE_METHOD_MATCHER);
assertThat(Pointcuts.matches(pc, PointcutsTests.TEST_BEAN_ABSQUATULATE, TestBean.class)).isFalse();
assertThat(Pointcuts.matches(pc, PointcutsTests.TEST_BEAN_GET_AGE, TestBean.class)).isTrue();
assertThat(Pointcuts.matches(pc, PointcutsTests.TEST_BEAN_GET_NAME, TestBean.class)).isFalse();
pc.union(GETTER_METHOD_MATCHER);
// Should now match all getter methods
assertThat(Pointcuts.matches(pc, PointcutsTests.TEST_BEAN_ABSQUATULATE, TestBean.class)).isFalse();
assertThat(Pointcuts.matches(pc, PointcutsTests.TEST_BEAN_GET_AGE, TestBean.class)).isTrue();
assertThat(Pointcuts.matches(pc, PointcutsTests.TEST_BEAN_GET_NAME, TestBean.class)).isTrue();
pc.union(ABSQUATULATE_METHOD_MATCHER);
// Should now match absquatulate() as well
assertThat(Pointcuts.matches(pc, PointcutsTests.TEST_BEAN_ABSQUATULATE, TestBean.class)).isTrue();
assertThat(Pointcuts.matches(pc, PointcutsTests.TEST_BEAN_GET_AGE, TestBean.class)).isTrue();
assertThat(Pointcuts.matches(pc, PointcutsTests.TEST_BEAN_GET_NAME, TestBean.class)).isTrue();
// But it doesn't match everything
assertThat(Pointcuts.matches(pc, PointcutsTests.TEST_BEAN_SET_AGE, TestBean.class)).isFalse();
}
@Test
public void testIntersectionMethodMatcher() {
ComposablePointcut pc = new ComposablePointcut();
assertThat(pc.getMethodMatcher().matches(PointcutsTests.TEST_BEAN_ABSQUATULATE, TestBean.class)).isTrue();
assertThat(pc.getMethodMatcher().matches(PointcutsTests.TEST_BEAN_GET_AGE, TestBean.class)).isTrue();
assertThat(pc.getMethodMatcher().matches(PointcutsTests.TEST_BEAN_GET_NAME, TestBean.class)).isTrue();
pc.intersection(GETTER_METHOD_MATCHER);
assertThat(pc.getMethodMatcher().matches(PointcutsTests.TEST_BEAN_ABSQUATULATE, TestBean.class)).isFalse();
assertThat(pc.getMethodMatcher().matches(PointcutsTests.TEST_BEAN_GET_AGE, TestBean.class)).isTrue();
assertThat(pc.getMethodMatcher().matches(PointcutsTests.TEST_BEAN_GET_NAME, TestBean.class)).isTrue();
pc.intersection(GET_AGE_METHOD_MATCHER);
// Use the Pointcuts matches method
assertThat(Pointcuts.matches(pc, PointcutsTests.TEST_BEAN_ABSQUATULATE, TestBean.class)).isFalse();
assertThat(Pointcuts.matches(pc, PointcutsTests.TEST_BEAN_GET_AGE, TestBean.class)).isTrue();
assertThat(Pointcuts.matches(pc, PointcutsTests.TEST_BEAN_GET_NAME, TestBean.class)).isFalse();
}
@Test
public void testEqualsAndHashCode() throws Exception {
ComposablePointcut pc1 = new ComposablePointcut();
ComposablePointcut pc2 = new ComposablePointcut();
assertThat(pc2).isEqualTo(pc1);
assertThat(pc2.hashCode()).isEqualTo(pc1.hashCode());
pc1.intersection(GETTER_METHOD_MATCHER);
assertThat(pc1.equals(pc2)).isFalse();
assertThat(pc1.hashCode()).isNotEqualTo(pc2.hashCode());
pc2.intersection(GETTER_METHOD_MATCHER);
assertThat(pc2).isEqualTo(pc1);
assertThat(pc2.hashCode()).isEqualTo(pc1.hashCode());
pc1.union(GET_AGE_METHOD_MATCHER);
pc2.union(GET_AGE_METHOD_MATCHER);
assertThat(pc2).isEqualTo(pc1);
assertThat(pc2.hashCode()).isEqualTo(pc1.hashCode());
}
}
|
package com.mvc4.service;
import com.mvc4.entity.DemoInfo;
/**
* Created with IntelliJ IDEA.
* User: uc203808
* Date: 6/17/16
* Time: 5:46 PM
* To change this template use File | Settings | File Templates.
*/
public interface DemoInfoService {
public DemoInfo findById(long id);
public void deleteFromCache(long id);
public DemoInfo getDemoInfoById(long id);
void test();
}
|
package com.hubpan.IslandBooking.resources;
import com.hubpan.IslandBooking.api.CampsiteAvailabilityDTO;
import com.hubpan.IslandBooking.api.CampsiteDTO;
import com.hubpan.IslandBooking.core.ReservationService;
import com.hubpan.IslandBooking.core.model.Campsite;
import com.hubpan.IslandBooking.core.CampsiteService;
import com.hubpan.IslandBooking.core.model.ModelMapper;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.time.ZonedDateTime;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;
@RestController
@RequestMapping("/api/campsites")
public class CampsiteController {
@Autowired
private ModelMapper modelMapper;
@Autowired
private CampsiteService campSiteService;
@Autowired
private ReservationService reservationService;
@ApiOperation(value = "list all campsites")
@GetMapping()
public List<CampsiteDTO> findAll() {
Collection<Campsite> campsites = campSiteService.findAll();
return campsites.stream().map(modelMapper::map).collect(Collectors.toList());
}
@ApiOperation(value = "retrieve availability of an existing campsite")
@GetMapping("/{id}/availability")
public Collection<CampsiteAvailabilityDTO> getAvailabilityById(
@ApiParam(
name = "id",
value = "the id of an existing campsite",
required = true)
@PathVariable Long id,
@ApiParam(
name = "from",
value = "search for availability since this time",
required = false)
@RequestParam(required = false) ZonedDateTime from,
@ApiParam(
name = "to",
value = "search for availability until this time",
required = false)
@RequestParam(required = false) ZonedDateTime to) {
if (from == null && to == null) {
from = ZonedDateTime.now();
}
if (from == null) {
from = to.minusDays(30);
}
if (to == null) {
to = from.plusDays(30);
}
return reservationService.findAvailabilityByCampsite(id, from.toLocalDateTime(), to.toLocalDateTime())
.stream().map(modelMapper::map).collect(Collectors.toList());
}
}
|
/**
* This class is generated by jOOQ
*/
package schema.tables;
import java.util.Arrays;
import java.util.List;
import javax.annotation.Generated;
import org.jooq.Field;
import org.jooq.Identity;
import org.jooq.Schema;
import org.jooq.Table;
import org.jooq.TableField;
import org.jooq.UniqueKey;
import org.jooq.impl.TableImpl;
import schema.BitnamiEdx;
import schema.Keys;
import schema.tables.records.BulkEmailCourseauthorizationRecord;
/**
* This class is generated by jOOQ.
*/
@Generated(
value = {
"http://www.jooq.org",
"jOOQ version:3.8.4"
},
comments = "This class is generated by jOOQ"
)
@SuppressWarnings({ "all", "unchecked", "rawtypes" })
public class BulkEmailCourseauthorization extends TableImpl<BulkEmailCourseauthorizationRecord> {
private static final long serialVersionUID = 1079954600;
/**
* The reference instance of <code>bitnami_edx.bulk_email_courseauthorization</code>
*/
public static final BulkEmailCourseauthorization BULK_EMAIL_COURSEAUTHORIZATION = new BulkEmailCourseauthorization();
/**
* The class holding records for this type
*/
@Override
public Class<BulkEmailCourseauthorizationRecord> getRecordType() {
return BulkEmailCourseauthorizationRecord.class;
}
/**
* The column <code>bitnami_edx.bulk_email_courseauthorization.id</code>.
*/
public final TableField<BulkEmailCourseauthorizationRecord, Integer> ID = createField("id", org.jooq.impl.SQLDataType.INTEGER.nullable(false), this, "");
/**
* The column <code>bitnami_edx.bulk_email_courseauthorization.course_id</code>.
*/
public final TableField<BulkEmailCourseauthorizationRecord, String> COURSE_ID = createField("course_id", org.jooq.impl.SQLDataType.VARCHAR.length(255).nullable(false), this, "");
/**
* The column <code>bitnami_edx.bulk_email_courseauthorization.email_enabled</code>.
*/
public final TableField<BulkEmailCourseauthorizationRecord, Byte> EMAIL_ENABLED = createField("email_enabled", org.jooq.impl.SQLDataType.TINYINT.nullable(false), this, "");
/**
* Create a <code>bitnami_edx.bulk_email_courseauthorization</code> table reference
*/
public BulkEmailCourseauthorization() {
this("bulk_email_courseauthorization", null);
}
/**
* Create an aliased <code>bitnami_edx.bulk_email_courseauthorization</code> table reference
*/
public BulkEmailCourseauthorization(String alias) {
this(alias, BULK_EMAIL_COURSEAUTHORIZATION);
}
private BulkEmailCourseauthorization(String alias, Table<BulkEmailCourseauthorizationRecord> aliased) {
this(alias, aliased, null);
}
private BulkEmailCourseauthorization(String alias, Table<BulkEmailCourseauthorizationRecord> aliased, Field<?>[] parameters) {
super(alias, null, aliased, parameters, "");
}
/**
* {@inheritDoc}
*/
@Override
public Schema getSchema() {
return BitnamiEdx.BITNAMI_EDX;
}
/**
* {@inheritDoc}
*/
@Override
public Identity<BulkEmailCourseauthorizationRecord, Integer> getIdentity() {
return Keys.IDENTITY_BULK_EMAIL_COURSEAUTHORIZATION;
}
/**
* {@inheritDoc}
*/
@Override
public UniqueKey<BulkEmailCourseauthorizationRecord> getPrimaryKey() {
return Keys.KEY_BULK_EMAIL_COURSEAUTHORIZATION_PRIMARY;
}
/**
* {@inheritDoc}
*/
@Override
public List<UniqueKey<BulkEmailCourseauthorizationRecord>> getKeys() {
return Arrays.<UniqueKey<BulkEmailCourseauthorizationRecord>>asList(Keys.KEY_BULK_EMAIL_COURSEAUTHORIZATION_PRIMARY, Keys.KEY_BULK_EMAIL_COURSEAUTHORIZATION_COURSE_ID);
}
/**
* {@inheritDoc}
*/
@Override
public BulkEmailCourseauthorization as(String alias) {
return new BulkEmailCourseauthorization(alias, this);
}
/**
* Rename this table
*/
public BulkEmailCourseauthorization rename(String name) {
return new BulkEmailCourseauthorization(name, null);
}
}
|
package com.example.actividaddeaprendizaje.characters.filterCharacters.contract;
import com.example.actividaddeaprendizaje.beans.Character;
import java.util.ArrayList;
public interface FilterCharactersContract {
interface View{
void success(ArrayList<Character> character);
void error(String mensaje);
}
interface Presenter{
void getCharacter(String fecha);
}
interface Model{
void getCharacterWS(OnCharacterListener onCharacterListener, String fecha);
interface OnCharacterListener{
void resolve(ArrayList<Character> character);
void reject(String error);
}
}
}
|
package controller;
import java.sql.ResultSet;
import java.sql.SQLException;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import model.Main;
import outils.ConversionEuro;
import vue.Vue;
public class DetailCompteController {
@FXML private Button button_virement;
@FXML private Button button_quitter;
@FXML private TextField text_virement_n_compte;
@FXML private TextField text_virement_somme;
@FXML private Label text_balance;
@FXML private Label solde_dollar;
@FXML private Label solde_livre;
@FXML private Label text_decouvert;
@FXML private Label Label_Titre;
private double solde;
private ResultSet details_compte;
@FXML
public void initialize()
{
Label_Titre.setText("Compte n° " + Vue.NumCompte);
rafraichir_solde();
rafraichir_solde_dollar();
rafraichir_solde_livre();
rafraichir_decouvert();
}
@FXML
public void rafraichir_solde()
{
try
{
details_compte = Main.Req.details_compte(String.valueOf(Main.IDClient));
details_compte.next();
String solde = String.valueOf(details_compte.getDouble("balanceCompte"));
text_balance.setText(solde + " €");
this.solde = details_compte.getDouble("balanceCompte");
} catch (SQLException e)
{
Main.message_erreur("Erreur : Impossible d'afficher le solde" + e.toString());
}
}
private void rafraichir_solde_dollar()
{
Double solde_dollars = ConversionEuro.euroToDollar(this.solde);
solde_dollar.setText(String.valueOf(solde_dollars + " $"));
}
private void rafraichir_solde_livre()
{
Double solde_livres = ConversionEuro.euroToLivre(this.solde);
solde_livre.setText(String.valueOf(solde_livres + " £"));
}
private void rafraichir_decouvert()
{
try
{
Double decouvert = details_compte.getDouble("decouvertCompte");
text_decouvert.setText(String.valueOf(decouvert) + " €");
} catch (SQLException e)
{
Main.message_erreur("Impossible de charger le découvert. Cause : " + e.toString());
}
}
@FXML
private void virement()
{
String somme = text_virement_somme.getText();
String compte = text_virement_n_compte.getText();
if(somme.isEmpty() || compte.isEmpty())
Main.message_erreur("Entrez une somme à virer ainsi que le n° de compte du destinataire.");
else
{
try
{
if(somme.contains("-"))
{
Main.message_erreur("La somme ne doit pas être négative !");
return;
}
if(Main.Req.virement(Double.parseDouble(somme), Vue.NumCompte, compte))
{
rafraichir_solde();
Main.message_info("Virement réussi");
}
else
Main.message_erreur("Le virement a échoué. Peut-être que le compte destinataire n'existe pas ou que votre solde est insuffisant.");
} catch (NumberFormatException e)
{
Main.message_erreur("Veuillez entrer une somme correcte. Erreur : " + e.toString());
} catch (SQLException e)
{
Main.message_erreur("Erreur lors du virement. Erreur : " + e.toString());
}
}
}
@FXML
public void Btn_Retour_Click()
{
try
{
new Vue("Compte",null,null);
} catch (Exception e)
{
Main.message_erreur("Impossible de revenir à la fenètre précédente. Erreur : " + e.toString());
}
}
@FXML
public void btn_quitter()
{
Main.parentWindow.close();
}
}
|
package com.tongchuang.huangshan.model.domain.admin;
import lombok.ToString;
/**
* 用户和岗位关联 sys_user_post
*
* @author fangwenzao
*/
@ToString
public class SysUserPost
{
/** 用户ID */
private Long userId;
/** 岗位ID */
private String postId;
public Long getUserId()
{
return userId;
}
public void setUserId(Long userId)
{
this.userId = userId;
}
public String getPostId() {
return postId;
}
public void setPostId(String postId) {
this.postId = postId;
}
}
|
package interfaces;
public interface LogAnalysis {
//APP MUST IMPLEMENT
//...
}
|
package com.crutchclothing.cart.dao;
import java.util.List;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import com.crutchclothing.cart.model.Cart;
import com.crutchclothing.cart.model.CartProduct;
import com.crutchclothing.cart.model.CartProductDetail;
import com.crutchclothing.cart.model.CartProductRef;
import com.crutchclothing.cart.model.CartProductRef.Id;
import com.crutchclothing.products.model.Product;
import com.crutchclothing.products.model.ProductDetail;
@Repository
public class CartDaoImpl implements CartDao {
//@Autowired
private SessionFactory sessionFactory;
public CartDaoImpl() {
}
@Override
public Cart createCart() {
Cart cart = new Cart();
save(cart);
return cart;
}
@Override
@Transactional
public Cart findCart(Integer cart_id) {
return (Cart) sessionFactory.getCurrentSession().get(Cart.class, cart_id);
}
@Override
@Transactional
public void save(Cart cart) {
sessionFactory.getCurrentSession().save(cart);
}
@Override
@Transactional
public void update(Cart cart) {
Cart foundCart = findCart(cart.getCartId());
sessionFactory.getCurrentSession().merge(foundCart);
}
@Override
@Transactional
public void addProductToCart(Integer cartId, Product product) {
Cart foundCart = findCart(cartId);
//System.out.println("productid = " + product.getId());
//foundCart.getProducts().add(product);
//sessionFactory.getCurrentSession().saveOrUpdate(product);
sessionFactory.getCurrentSession().merge(foundCart);
//sessionFactory.getCurrentSession().saveOrUpdate(foundCart);
}
@Override
@Transactional
public void increaseCartProductQuantity(Integer productDetailId, Integer cartProductId, int quantity) {
//String query = "select * from cart_products where cart_id = " + cartId + " and product_id = " + productId + ";";
String hql = "from CartProductRef where product_details_id = ? and cart_product_id = ?";
//List<CartProduct> cartProducts = sessionFactory.getCurrentSession().createSQLQuery(query).list();
List<CartProductRef> cprs = sessionFactory.getCurrentSession().createQuery(hql).setParameter(0, productDetailId)
.setParameter(1, cartProductId)
.list();
if(cprs.size() > 0) {
CartProductRef cpr = (CartProductRef) cprs.get(0);
cpr.setProductQuantity(cpr.getProductQuantity() + quantity);
sessionFactory.getCurrentSession().saveOrUpdate(cpr);
}
}
@Override
@Transactional
public void changeCartProductQuantity(Integer cartProductId, Integer productDetailId,
int newQuantity) {
//String query = "select * from cart_products where cart_id = " + cartId + " and product_id = " + productId + ";";
String hql = "from CartProductRef where cart_product_id = ? and product_details_id = ?";
String cartSizeHql = "from CartProductRef where cart_product_id = ?";
//List<CartProduct> cartProducts = sessionFactory.getCurrentSession().createSQLQuery(query).list();
List<CartProductRef> cprs = sessionFactory.getCurrentSession().createQuery(hql)
.setParameter(0, cartProductId)
.setParameter(1, productDetailId)
.list();
if(cprs.size() > 0) {
CartProductRef cpr = (CartProductRef) cprs.get(0);
if(newQuantity == 0) {
cpr.getCartProduct().getCartProductRefs().remove(cpr);
cpr.getProductDetail().getCartProductRefs().remove(cpr);
//boolean val = cp.getProductDetails().remove(productDetail);
sessionFactory.getCurrentSession().delete(cpr);
List<CartProductRef> cartProducts = sessionFactory.getCurrentSession().createQuery(cartSizeHql)
.setParameter(0, cartProductId)
.list();
if(cartProducts.size() == 0) {
String delHql = "delete from CartProduct where cart_product_id = ?";
sessionFactory.getCurrentSession().createQuery(delHql)
.setParameter(0, cartProductId)
.executeUpdate();
//sessionFactory.getCurrentSession().(cp);
}
}
else {
cpr.setProductQuantity(newQuantity);
sessionFactory.getCurrentSession().merge(cpr);
}
}
}
@Override
@Transactional
public void saveCartProduct(CartProduct cartProduct) {
sessionFactory.getCurrentSession().persist(cartProduct);
}
@Override
@Transactional
public void saveProductDetail(CartProduct cartProduct, ProductDetail productDetail) {
CartProduct cp = findCartProduct(cartProduct.getCartProductId());
CartProductRef cpr = new CartProductRef(productDetail, cp, productDetail.getQuantity());
sessionFactory.getCurrentSession().persist(cpr);
cp.getCartProductRefs().add(cpr);
sessionFactory.getCurrentSession().merge(cp);
productDetail.getCartProductRefs().add(cpr);
sessionFactory.getCurrentSession().merge(productDetail);
}
@Override
@Transactional
public void saveDetailToCartProduct(Integer cartProductId, ProductDetail productDetail) {
String hql = "from CartProduct where cart_product_id = ?";
List<CartProduct> cps = sessionFactory.getCurrentSession().createQuery(hql)
.setParameter(0, cartProductId).list();
if(cps.size() > 0) {
CartProduct cp = (CartProduct) cps.get(0);
Id cprId = new Id(productDetail.getId(), cartProductId);
CartProductRef cpr = new CartProductRef(productDetail, cp, productDetail.getQuantity());
cpr.setId(cprId);
//productDetail.getCartProductRefs().add(cpr);
//cp.getCartProductRefs().add(cpr);
//sessionFactory.getCurrentSession().merge(productDetail);
//sessionFactory.getCurrentSession().merge(cp);
sessionFactory.getCurrentSession().save(cpr);
//productDetail.setCartProduct(cp);
//productDetail.getCartProductRefs().add(cpr);
//cp.getCartProductRef().add(cpr);
//sessionFactory.getCurrentSession().merge(cp);
}
//sessionFactory.getCurrentSession().persist(cpd);
}
@Override
@Transactional
public CartProduct findCartProduct(Integer id) {
return (CartProduct) sessionFactory.getCurrentSession().get(CartProduct.class, id);
}
@Override
@SuppressWarnings("unchecked")
@Transactional
public List<CartProduct> getCartProducts() {
System.out.println();
return sessionFactory.getCurrentSession().createQuery("from CartProduct").list();
}
@Override
@SuppressWarnings("unchecked")
@Transactional
public List<ProductDetail> getProductDetails() {
return sessionFactory.getCurrentSession().createQuery("from ProductDetail").list();
}
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
@Override
@Transactional
public CartProductRef findCartProductRef(Integer cartProductId,
Integer productDetailsId) {
CartProductRef cpr = null;
String hql = "from CartProductRef where cart_product_id = ? and product_details_id = ?";
List<CartProductRef> cprs = this.sessionFactory.getCurrentSession().createQuery(hql)
.setParameter(0, cartProductId)
.setParameter(1, productDetailsId)
.list();
if(cprs.size() > 0) {
cpr = cprs.get(0);
}
return cpr;
}
}
|
package cn.ztuo.bitrade;
import cn.ztuo.bitrade.constant.ActivityRewardType;
import cn.ztuo.bitrade.dao.*;
import cn.ztuo.bitrade.entity.*;
import cn.ztuo.bitrade.service.*;
import cn.ztuo.bitrade.util.DateUtil;
import cn.ztuo.bitrade.util.MessageResult;
import com.querydsl.core.types.Predicate;
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.kafka.core.KafkaTemplate;
import org.springframework.test.context.junit4.SpringRunner;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;
import static org.springframework.util.Assert.notNull;
/**
* @author GS
* @date 2018年03月22日
*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes=WebApplication.class)
public class DividendControllerTest {
@Autowired
private OrderDetailAggregationService orderDetailAggregationService;
@Autowired
SellRobotOrderDao sellRobotOrderDao;
@Test
public void queryStatistics(){
RobotOrder robotOrder =new RobotOrder();
robotOrder.setSellRobotOrderId(13237L);
SellRobotOrder sellRobotOrder=sellRobotOrderDao.getOrderById(robotOrder.getSellRobotOrderId());
System.err.println(sellRobotOrder);
}
@Autowired
private ExchangeReleaseTokenService exchangeReleaseTokenService;
@Test
public void queryStatistics2(){
List<ExchangeReleaseToken> exchangeReleaseTokens= exchangeReleaseTokenService.findByReleaseTimeBetweenAndMemberIdIs(DateUtil.getNowStartTime().getTime(),
DateUtil.getNowEndTime().getTime(),11);
System.out.println(exchangeReleaseTokens);
ExchangeReleaseToken exchangeReleaseToken = new ExchangeReleaseToken();
exchangeReleaseToken.setMemberId(11);
exchangeReleaseToken.setOrderId(11111+"");
exchangeReleaseToken.setReleaseAmount(new BigDecimal("123124"));
exchangeReleaseToken.setReleaseTime(System.currentTimeMillis());
exchangeReleaseTokenService.save(exchangeReleaseToken);
//System.out.println(exchangeOrderRepository.selectBuyOrderCountByCompleteTime(DateUtil.getNowStartTime().getTime(),DateUtil.getNowEndTime().getTime(),11));
}
@Autowired
private MemberDao memberDao;
@Autowired
private MemberBorrowingReturningDao memberBorrowingReturningDao;
@Autowired
private RewardPromotionSettingDao rewardPromotionSettingDao;
@Autowired
private MemberWalletService memberWalletService;
@Autowired
private MemberWalletDao memberWalletDao;
@Autowired
private MemberTransactionDao memberTransactionDao;
@Autowired
private BorrowingAndReturningService borrowingAndReturningService;
@Autowired
private MemberTransactionService memberTransactionService;
@Autowired
private MemberTransactionDao transactionDao;
@Autowired
private KafkaTemplate<String, String> kafkaTemplate;
@Autowired
RewardActivitySettingService rewardActivitySettingService;
@Autowired
private MemberApplicationService memberApplicationService;
@Test
public void test(){
borrowingAndReturningService.borrowingAndReturning(540,0,"3000","123456");
}
@Autowired
private PatternConfDao patternConfDao;
@Test
public void contextLoads1(){
patternConfDao.getPatternConf();
System.out.println("wqeqwe");
//releaseService.release();
}
}
|
package com.gen.serve;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.Statement;
import java.io.PrintWriter;
/**
* Servlet implementation class dbconnection
*/
//@SuppressWarnings("unused")
@WebServlet("/Dispatch_to_modifyshipment")
public class Dispatch_to_modifyshipment extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public Dispatch_to_modifyshipment() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.getWriter().append("Served at: ").append(request.getContextPath());
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
//doGet(request, response);
response.setContentType("text/number/html");
PrintWriter pw = response.getWriter();
pw.println("connecting");
Connection Conn=null;
String url = "jdbc:mysql://localhost:3306/";
String dbName = "world";
String driver = "com.mysql.jdbc.Driver";
try {
Class.forName(driver).newInstance();
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String nextJSP="/ModifyShipment.jsp";
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(nextJSP);
dispatcher.forward(request, response);
}
}
|
package estudo1.main;
//import estudo1.model.dao.Banco;
public class Principal {
public static void main(String[] args) {
// TODO Auto-generated method stub
// teste de conex„o com o banco
//Banco banco = new Banco();
//banco.getConnection();
}
}
|
package kr.or.ddit.reportboard.service;
import java.util.List;
import java.util.Map;
import kr.or.ddit.reportboard.dao.IReportBoardDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
@Service
public class ReportBoardServiceImpl implements IReportBoardService {
@Autowired
private IReportBoardDao dao;
@Transactional(propagation=Propagation.REQUIRED, readOnly=true)
@Override
public List<Map<String, String>> reportboardList(Map<String, String> params) throws Exception {
return dao.reportboardList(params);
}
@Transactional(propagation=Propagation.REQUIRED, readOnly=true)
@Override
public Map<String, String> selectReportboard(Map<String, String> params)
throws Exception {
return dao.selectReportboard(params);
}
@Transactional(propagation=Propagation.REQUIRED, rollbackFor={Exception.class})
@Override
public String insertReportboard(Map<String, String> params)
throws Exception {
return dao.insertReportboard(params);
}
@Transactional(propagation=Propagation.REQUIRED, rollbackFor={Exception.class})
@Override
public int updateReportboard(Map<String, String> params) throws Exception {
return dao.updateReportboard(params);
}
@Transactional(propagation=Propagation.REQUIRED, rollbackFor={Exception.class})
@Override
public int deleteReportboard(Map<String, String> params) throws Exception {
return dao.deleteReportboard(params);
}
@Transactional(propagation=Propagation.REQUIRED, rollbackFor={Exception.class})
@Override
public int updateReportStatus(Map<String, String> params) throws Exception {
return dao.updateReportStatus(params);
}
//comment
@Transactional(propagation=Propagation.REQUIRED, readOnly=true)
@Override
public List<Map<String, String>> reportCommentList(
Map<String, String> params) throws Exception {
return dao.reportCommentList(params);
}
@Transactional(propagation=Propagation.REQUIRED, rollbackFor={Exception.class})
@Override
public int insertReportComment(Map<String, String> params) throws Exception {
return dao.insertReportComment(params);
}
@Transactional(propagation=Propagation.REQUIRED, rollbackFor={Exception.class})
@Override
public int deleteReportComment(Map<String, String> params) throws Exception {
return dao.deleteReportComment(params);
}
@Transactional(propagation=Propagation.REQUIRED, rollbackFor={Exception.class})
@Override
public int updateReportComment(Map<String, String> params) throws Exception {
return dao.updateReportComment(params);
}
}
|
package com.cinema.biz.dao;
import java.util.List;
import java.util.Map;
import com.cinema.biz.model.SimFault;
import com.cinema.biz.model.base.TSimFault;
import tk.mybatis.mapper.common.Mapper;
import tk.mybatis.mapper.common.MySqlMapper;
public interface SimFaultMapper extends Mapper<TSimFault>,MySqlMapper<TSimFault>{
/**列表*/
List<SimFault> getList(Map<String, Object> paraMap);
}
|
package com.example.penandlim.pebble;
/**
* Created by penandlim on 1/17/15.
*/
public class FavoriteLocation {
String name, address, phoneNumber, buisinessName, notes;
FavoriteLocation(){}
FavoriteLocation(String _name, String _address, String _phoneNumber, String _buisinessName, String _notes) {
name = _name;
address = _address;
phoneNumber = _phoneNumber;
buisinessName = _buisinessName;
notes = _notes;
}
public String getName() {
return name;
}
public String getAddress() {
return address;
}
}
|
/*
* Copyright (c) 2020. The Kathra Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.
*
* Contributors:
* IRT SystemX (https://www.kathra.org/)
*
*/
package org.kathra.resourcemanager.resource.dao;
import org.kathra.core.model.Resource.StatusEnum;
import org.kathra.core.model.Resource;
import java.util.Map;
public interface IResourceDb<ID,X extends Resource> {
public ID getId();
public void setId(ID identifier);
public String getName();
public String getCreatedBy();
public String getUpdatedBy();
public StatusEnum getStatus();
public long getUpdatedAt();
public long getCreatedAt();
public void setCreatedBy(String author);
public void setUpdatedBy(String author);
public void setStatus(StatusEnum state);
public void setUpdatedAt(long timestamp);
public void setCreatedAt(long timestamp);
public Map<String, Object> getMetadata();
}
|
package com.ytdsuda.management.service;
import com.ytdsuda.management.entity.TotalInfo;
import java.util.List;
public interface TotalInfoService {
List<TotalInfo> findAll();
TotalInfo updateTotalInfo(String type, Integer count);
}
|
/*
* Copyright (c) 2008-2021, Hazelcast, Inc. All Rights Reserved.
*
* 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 example.serialization;
import com.hazelcast.internal.serialization.impl.compact.Compactable;
import com.hazelcast.nio.serialization.compact.CompactReader;
import com.hazelcast.nio.serialization.compact.CompactSerializer;
import com.hazelcast.nio.serialization.compact.CompactWriter;
import javax.annotation.Nonnull;
import java.io.IOException;
/**
* An example class which is planned to be generated via code generator
*/
public class EmployeeWithSerializerDTO implements Compactable<EmployeeWithSerializerDTO> {
private static final CompactSerializer<EmployeeWithSerializerDTO> SERIALIZER =
new CompactSerializer<EmployeeWithSerializerDTO>() {
@Nonnull
@Override
public EmployeeWithSerializerDTO read(@Nonnull CompactReader in) throws IOException {
EmployeeWithSerializerDTO employee = new EmployeeWithSerializerDTO();
employee.age = in.readInt("a");
employee.id = in.readLong("i");
return employee;
}
@Override
public void write(@Nonnull CompactWriter out, @Nonnull EmployeeWithSerializerDTO object) throws IOException {
out.writeInt("a", object.age);
out.writeLong("i", object.id);
}
};
private int age;
private long id;
public EmployeeWithSerializerDTO() {
}
public EmployeeWithSerializerDTO(int age, long id) {
this.age = age;
this.id = id;
}
@Override
public String toString() {
return "EmployeeDTO{"
+ "age=" + age
+ ", id=" + id
+ '}';
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
EmployeeWithSerializerDTO that = (EmployeeWithSerializerDTO) o;
if (age != that.age) {
return false;
}
return id == that.id;
}
public void setAge(int age) {
this.age = age;
}
public int getAge() {
return age;
}
public long getId() {
return id;
}
@Override
public int hashCode() {
int result = age;
result = 31 * result + (int) (id ^ (id >>> 32));
return result;
}
@Override
public CompactSerializer<EmployeeWithSerializerDTO> getCompactSerializer() {
return SERIALIZER;
}
}
|
package com.msingiapp;
import java.util.List;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;
public class Exam extends Activity implements OnClickListener {
public DatabaseHelper db = new DatabaseHelper(this);
public static List<ExamSession> quest;
public static ExamSession ex;
WebView webQuest;
TextView questionNo;
TextView examTitle;
public RadioGroup rgroup;
public RadioButton radioA, radioB, radioC, radioD;
ScrollView sv;
Button next, prev, quit;
int number = 0;
int questNo = number + 1;
String pickedAnswer = "";
public static int totalAnswered = 0, incorectAnswers = 0, totalUnaswered;
public static int totalCorrectAns = 0;
public static String ans;
final Context context = this;
public static String selected = "", correct = "";
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.exam);
View title = getWindow().findViewById(android.R.id.title);
View titleBar = (View) title.getParent();
titleBar.setBackgroundColor(getResources().getColor(
R.color.dark_green_color));
initialize();
displayFirstQuestion();
}
@SuppressLint({ "NewApi" })
public void initialize() {
examTitle = (TextView) findViewById(R.id.subTit);
questionNo = (TextView) findViewById(R.id.tvquestionNumber1);
webQuest = (WebView) findViewById(R.id.quest_web_view1);
webQuest.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
webQuest.getSettings().setBuiltInZoomControls(true);
// declare radiogroup
rgroup = (RadioGroup) findViewById(R.id.radioGroup);
// declare radiobuttons
radioA = (RadioButton) findViewById(R.id.radio_AA);
radioB = (RadioButton) findViewById(R.id.radio_BB);
radioC = (RadioButton) findViewById(R.id.radio_CC);
radioD = (RadioButton) findViewById(R.id.radio_DD);
// add action to the radiogroup on chhagelistner
rgroup.setOnCheckedChangeListener(new OnCheckedChangeListener() {
public void onCheckedChanged(RadioGroup group, int checkedId) {
// checkedId is the RadioButton selected
switch (rgroup.getCheckedRadioButtonId()) {
case R.id.radio_AA:
pickedAnswer = "A";
break;
case R.id.radio_BB:
pickedAnswer = "B";
break;
case R.id.radio_CC:
pickedAnswer = "C";
break;
case R.id.radio_DD:
pickedAnswer = "D";
break;
default:
pickedAnswer = "";
break;
}
}
});
next = (Button) findViewById(R.id.Button_Next);
next.setOnClickListener(this);
prev = (Button) findViewById(R.id.Button_Prev);
prev.setOnClickListener(this);
quit = (Button) findViewById(R.id.Button_Quit);
quit.setOnClickListener(this);
}
public void displayFirstQuestion() {
// getting the elements at index 0 from database table
quest = db.getAllQusetions();
if (quest.isEmpty()) {
Toast.makeText(getApplicationContext(),
"Ther are no contents to display", Toast.LENGTH_SHORT)
.show();
} else {
ex = (ExamSession) quest.get(0);
examTitle.setText("KCPE " + Year.subTitle.toUpperCase() + " "
+ Year.question_year);
if (Year.subTitle.equals("Kiswahili")) {
questionNo.setText(" Swali la " + questNo + " kati ya "
+ quest.size());
next.setText("mbele");
prev.setText("nyuma");
quit.setText("maliza mtihani");
} else {
questionNo.setText(" Question " + questNo + " out of "
+ quest.size());
}
/*
* String quiz =
* "<link rel=\"stylesheet\" type=\"text/css\" href=\"msingipack.css\" />"
* + ex.getQuestion();
*
* String choiA =
* "<link rel=\"stylesheet\" type=\"text/css\" href=\"msingipack.css\" />"
* + ex.getChoice1();
*
* String choiB =
* "<link rel=\"stylesheet\" type=\"text/css\" href=\"msingipack.css\" />"
* + ex.getChoice2();
*
* String choiC =
* "<link rel=\"stylesheet\" type=\"text/css\" href=\"msingipack.css\" />"
* + ex.getChoice3();
*
* String choiD =
* "<link rel=\"stylesheet\" type=\"text/css\" href=\"msingipack.css\" />"
* + ex.getChoice4();
*/
webQuest.loadDataWithBaseURL(
"file:///android_asset/",
" </p> <p id=\"question\">" + ex.getQuestion() + "</p> "
+ "<p></p>" + "<strong> A  </strong>"
+ ex.getChoice1() + "<p></p>"
+ "<strong> B  </strong>"
+ ex.getChoice2() + "<p></p>"
+ "<strong> C  </strong>"
+ ex.getChoice3() + "<p></p>"
+ "<strong> D  </strong>"
+ ex.getChoice4(), "text/html", "utf-8", null);
}
}
@SuppressLint("DefaultLocale")
public void nextRecord() {
number++;
if (number == quest.size()) {
/* if user has reached the end of results, disable forward button */
// dec by one to counter last inc
number--;
} else {
prev.setEnabled(true);
ex = (ExamSession) quest.get(number);
int questNo = number + 1;
// displaying questions to the user
ans = ex.getSelectedAnswer();
examTitle.setText("KCPE " + Year.subTitle.toUpperCase() + " "
+ Year.question_year);
if (Year.subTitle.equals("Kiswahili")) {
questionNo.setText(" Swali la " + questNo + " kati ya "
+ quest.size());
next.setText("mbele");
prev.setText("nyuma");
quit.setText("maliza mtihani");
} else {
questionNo.setText(" Question " + questNo + " out of "
+ quest.size());
}
/*
* String quiz =
* "<link rel=\"stylesheet\" type=\"text/css\" href=\"msingipack.css\" />"
* + ex.getQuestion();
*
* String choiA =
* "<link rel=\"stylesheet\" type=\"text/css\" href=\"msingipack.css\" />"
* + ex.getChoice1();
*
* String choiB =
* "<link rel=\"stylesheet\" type=\"text/css\" href=\"msingipack.css\" />"
* + ex.getChoice2();
*
* String choiC =
* "<link rel=\"stylesheet\" type=\"text/css\" href=\"msingipack.css\" />"
* + ex.getChoice3();
*
* String choiD =
* "<link rel=\"stylesheet\" type=\"text/css\" href=\"msingipack.css\" />"
* + ex.getChoice4();
*/
try {
webQuest.loadDataWithBaseURL(
"file:///android_asset/",
" </p> <p id=\"question\">" + ex.getQuestion()
+ "</p> " + "<p></p>"
+ "<strong> A  </strong>"
+ ex.getChoice1() + "<p></p>"
+ "<strong> B  </strong>"
+ ex.getChoice2() + "<p></p>"
+ "<strong> C  </strong>"
+ ex.getChoice3() + "<p></p>"
+ "<strong> D  </strong>"
+ ex.getChoice4(), "text/html", "utf-8", null);
} catch (Exception e) {
e.printStackTrace();
}
}
if (number == quest.size() - 1) {
/*
* if user has reached the end of results, disable forward button
*/
next.setEnabled(false);
prev.setEnabled(true);
// dec by one to counter last inc
}
// set the selected answer -1 because we are setting when nxt btn
// is clicked
ex = (ExamSession) quest.get(number - 1);
ex.setSelectedAnswer(pickedAnswer);
// get the picked answer at that index
clearRadioButtons();
selectedAnswer();
}
public void previousRecord() {
number--;
if (number < 0) {
/* if user has reached the begining of results, disable back button */
next.setEnabled(true);
prev.setEnabled(false);
// inc by one to counter last dec
number++;
} else {
next.setEnabled(true);
ex = (ExamSession) quest.get(number);
int questNo = number + 1;
// displaying search record in text fields
ans = ex.getSelectedAnswer();
examTitle.setText("KCPE " + Year.subTitle.toUpperCase() + " "
+ Year.question_year);
if (Year.subTitle.equals("Kiswahili")) {
questionNo.setText(" Swali la " + questNo + " kati ya "
+ quest.size());
next.setText("mbele");
prev.setText("nyuma");
quit.setText("maliza mtihani");
} else {
questionNo.setText(" Question " + questNo + " out of "
+ quest.size());
}
/*
* String quiz =
* "<link rel=\"stylesheet\" type=\"text/css\" href=\"msingipack.css\" />"
* + ex.getQuestion();
*
* String choiA =
* "<link rel=\"stylesheet\" type=\"text/css\" href=\"msingipack.css\" />"
* + ex.getChoice1();
*
* String choiB =
* "<link rel=\"stylesheet\" type=\"text/css\" href=\"msingipack.css\" />"
* + ex.getChoice2();
*
* String choiC =
* "<link rel=\"stylesheet\" type=\"text/css\" href=\"msingipack.css\" />"
* + ex.getChoice3();
*
* String choiD =
* "<link rel=\"stylesheet\" type=\"text/css\" href=\"msingipack.css\" />"
* + ex.getChoice4();
*/
try {
webQuest.loadDataWithBaseURL(
"file:///android_asset/",
" </p> <p id=\"question\">" + ex.getQuestion()
+ "</p> " + "<p></p>"
+ "<strong> A  </strong>"
+ ex.getChoice1() + "<p></p>"
+ "<strong> B  </strong>"
+ ex.getChoice2() + "<p></p>"
+ "<strong> C  </strong>"
+ ex.getChoice3() + "<p></p>"
+ "<strong> D  </strong>"
+ ex.getChoice4(), "text/html", "utf-8", null);
} catch (Exception e) {
e.printStackTrace();
}
// set the selected answer -1 because we are setting when nxt btn
// is clicked
ex = (ExamSession) quest.get(number + 1);
ex.setSelectedAnswer(pickedAnswer);
// get the picked answer at that index
clearRadioButtons();
selectedAnswer();
}
}
public void markExam() {
totalUnaswered = quest.size();
incorectAnswers = quest.size();
// if (!ex.selectedAnswer.equals("")) {
for (int i = 0; i < quest.size(); i++) {
ex = (ExamSession) quest.get(i);
// comparing the supplied answer to the correct ans hence
// incrementing
try {
if (ex.selectedAnswer.equals(ex.answer)) {
totalCorrectAns++;
int inc = quest.size() - totalCorrectAns;
incorectAnswers = inc;
// increment the value of totalUnAnswered if the question
// remains unanswered
}
if (!ex.getSelectedAnswer().equals("")) {
totalAnswered++;
int un = quest.size() - totalAnswered;
totalUnaswered = un;
// else increment the value of incorrect answers
}
} catch (Exception e) {
e.printStackTrace();
}
}
if (totalAnswered < quest.size()) {
confirmMarking();
} else {
Grade.Grading(quest.size(), totalCorrectAns);
Intent finish = new Intent(Exam.this, Score.class);
startActivity(finish);
finish();
}
}
public void confirmMarking() {
final Dialog dialog = new Dialog(context);
if (Year.subTitle.equals("Kiswahili")) {
dialog.setContentView(R.layout.examfinish_dialog_swa);
dialog.setTitle("Mda wa mthihani");
} else if (!Year.subTitle.equals("Kiswahili")) {
dialog.setContentView(R.layout.examfinish_dialog);
dialog.setTitle("Exam Session");
}
dialog.setCanceledOnTouchOutside(false);
Button dialogButtonOk = (Button) dialog
.findViewById(R.id.dialogButtonOK);
// if button is clicked, close the custom dialog
dialogButtonOk.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
dialog.dismiss();
Grade.Grading(quest.size(), totalCorrectAns);
Intent finish = new Intent(Exam.this, Score.class);
startActivity(finish);
finish();
}
});
Button dialogCancel = (Button) dialog
.findViewById(R.id.dialogButtonCancel);
dialogCancel.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
dialog.dismiss();
}
});
dialog.show();
}
// get the last selection from exam choices
public void lastSelectedAns() {
ex = (ExamSession) quest.get(number);
ex.setSelectedAnswer(pickedAnswer);
// get the picked answer at that index
ans = ex.getSelectedAnswer();
clearRadioButtons();
}
public void clearRadioButtons() {
rgroup.clearCheck();
pickedAnswer = "";
}
// To check the previously selected answer, show it by selecting the
// radio btn in question and the re-assing it if answer is changed
public void selectedAnswer() {
try {
if (ans.equals("")) {
pickedAnswer = "";
}
if (ans.equals("A")) {
rgroup.check(R.id.radio_AA);
pickedAnswer = "A";
}
if (ans.equals("B")) {
rgroup.check(R.id.radio_BB);
pickedAnswer = "B";
}
if (ans.equals("C")) {
rgroup.check(R.id.radio_CC);
pickedAnswer = "C";
}
if (ans.equals("D")) {
rgroup.check(R.id.radio_DD);
pickedAnswer = "D";
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static void reviewAnswers(int index) {
String ansSelected, correctAns;
ex = (ExamSession) quest.get(index);
ansSelected = ex.getSelectedAnswer();
correctAns = ex.getAnswer();
// handling for questions not answered
if (ansSelected.equals("")) {
selected = "<p >You did not answer the question</p>";
correct = "<p> The correct answer is " + "  "
+ correctAns;
} else if (!ansSelected.equals("")) {
selected = "<p> You selected: " + "  " + ansSelected;
correct = " <p > The correct answer is " + "  "
+ correctAns;
}
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.Button_Quit:
lastSelectedAns();
markExam();
break;
case R.id.Button_Next:
nextRecord();
break;
case R.id.Button_Prev:
previousRecord();
break;
}
}
@Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
}
@Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
}
@Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
finish();
}
}
|
package com.hznu.fa2login.modules.sys.dao;
import com.baomidou.mybatisplus.mapper.BaseMapper;
import com.hznu.fa2login.modules.sys.entity.Ccode;
/**
* @Author: TateBrown
* @date: 2018/11/28 19:27
* @param:
* @return:
*/
public interface CcodeDao extends BaseMapper<Ccode> {
}
|
package com.gamzat;
public class Main {
public static void main(String[] args) {
int Bender = 5; // Какой то Робот.
int Beer = 4; // Пиво 4 стакана.
// Условия if
if (Bender == 1) {
System.out.println("Это всего-лишь 1");
}
if (Bender == 2) {
System.out.println("Это всего-лишь 2");
}
if (Bender == 3) {
System.out.println("Это всего-лишь 3");
}
if (Bender == 4) {
System.out.println("Это всего-лишь 4");
}
if (Bender == 5) {
System.out.println("Это всего-лишь 5");
}
switch (Beer) {
case 1:
System.out.println("После 1 кружки пива я в польном порядке!");
break;
case 2:
System.out.println("После 2 кружки пива я ищу приключения!");
break;
case 3:
System.out.println("После 3 кружки пива приключения ищут меня!");
break;
case 4:
System.out.println("После 4 кружки пива я начинаю разбираться в политике!");
break;
default:
System.out.println("В этом мире слишком мало пива!");
break;
}
}
}
|
// AbstractClient.java
package org.google.code.servant.net;
import java.io.IOException;
import java.util.List;
import java.util.ArrayList;
import org.google.code.servant.util.Logger;
/**
* Implementation of the "pipe" algorithm.
*
* @version 1.1 08/09/2001
* @author Alexander Shvets
*/
public abstract class AbstractClient implements Client {
/** The logger object */
protected Logger logger = new Logger() {
public void logMessage(String message) {
System.out.println(message);
}
};
/**
* Performs the "pipe" operation (writeRequest/readresponse as atomic action)
*
* @param request the request from the client
* @return the responses array from the server
*/
public Object[] pipe(Object request) throws IOException {
writeRequest(request);
List responses = new ArrayList();
while(true) {
try {
Object response = readResponse();
if(response == null) {
break;
}
responses.add(response);
}
catch(IOException e) {
break;
}
}
return responses.toArray();
}
/**
* Gets the logger object
*
* @return the logger object
*/
public Logger getLogger() {
return logger;
}
/**
* Sets the logger object
*
* @param logger the logger object
*/
public void setLogger(Logger logger) {
this.logger = logger;
}
}
|
package org.isc.certanalysis.repository;
import org.isc.certanalysis.domain.NotificationGroup;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
/**
* @author p.dzeviarylin
*/
@Repository
public interface NotificationGroupRepository extends JpaRepository<NotificationGroup, Long> {
}
|
package com.mykarsol.appconnectivity;
/*
* 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.
*/
import DataObjects.Candidate_Profile_Object;
import DataOperations.Candidate_Profile_Operation;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.json.JsonArray;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
*
* @author Shivam Patel
*/
public class Login_Server extends HttpServlet {
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
/* TODO output your page here. You may use following sample code. */
}
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
PrintWriter out = response.getWriter();
String Username,Password;
String message="";
Username = request.getParameter("username");
Password = request.getParameter("password");
Candidate_Profile_Object cpo = new Candidate_Profile_Object();
// Candidate_Profile_Operation cpop = new Candidate_Profile_Operation();
// out.println(cpop.getError());
cpo.setCandidate_ID(Username);
cpo.setPassword(Password);
//out.println(Username);
//out.println(Password);
//Candidate_Profile_Operation cpop = new Candidate_Profile_Operation();
//cpop.RetriveCandidateDetails(cpo);
// out.println(cpop);
String usn,usp,name,uimg;
ArrayList<Candidate_Profile_Object> userlist=(new Candidate_Profile_Operation()).allids();
for( int x = 0 ; x < userlist.size() ; x++ ) {
Candidate_Profile_Object cpb=(Candidate_Profile_Object)userlist.get(x);
usn=cpb.getCandidate_ID();
usp=cpb.getPassword();
uimg=cpb.getImage();
if(usn.equals(Username) && usp.equals(Password))
{
name=cpb.getFirstname();
System.err.println(name);
if(name.equals("admin"))
{
out.println("admatch");
}
else
{
out.println("UPMatched"+"-"+name+"-"+uimg);
break;
}
}
else
{
// out.println("NotMatched"+usn+usp);
}
}
} catch (SQLException ex) {
System.out.println(ex.getMessage());
}
}
/**
* Handles the HTTP <code>POST</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
|
package com.qfedu.jinggong.dao;
import com.qfedu.jinggong.entity.DesignInstitute;
public interface DesignInstituteDao {
DesignInstitute queryInfo();
}
|
/*
* 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 PPI.Controladores;
import PPI.Modelos.ModeloSesion;
import PPI.Utils.Archivo;
import PPI.Vista.VistaPrincipal;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.io.File;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
/**
*
* @author Personal
*/
public class ControladorPrincipal {
public File archivo;
Archivo utilArchivo = new Archivo();
Gson gson;
public ControladorPrincipal(VistaPrincipal aThis) {
archivo = new File("iniciosesion.txt");
gson = new Gson();
}
public boolean VerificarSesion(ModeloSesion sesion) {
String informacionDelArchivo = utilArchivo.obtenerInformacionArchivo(archivo);
ModeloSesion sesionJson = new ModeloSesion();
if (informacionDelArchivo != null && !informacionDelArchivo.isEmpty()) {
Type sesionActiva = new TypeToken<ModeloSesion>() {
}.getType();
sesionJson = gson.fromJson(informacionDelArchivo, sesionActiva);
return sesionJson.isSesionActiva();
}
return false;
}
public int RetornarTipoUsuario(ModeloSesion sesion) {
String informacionDelArchivo = utilArchivo.obtenerInformacionArchivo(archivo);
ModeloSesion sesionJson = new ModeloSesion();
if (informacionDelArchivo != null && !informacionDelArchivo.isEmpty()) {
Type tipoUsuario = new TypeToken<ModeloSesion>() {
}.getType();
sesionJson = gson.fromJson(informacionDelArchivo, tipoUsuario);
return sesionJson.gettipoUsuario();
}
return 0;
}
}
|
package datenewtypes;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.time.temporal.ChronoUnit;
public class Rendezvous {
private LocalTime rendezvousTime;
public Rendezvous(int hour, int minute) {
rendezvousTime = LocalTime.of(hour, minute);
}
public Rendezvous(String timeStr, String formatStr) {
validateFormatString(formatStr);
try {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(formatStr);
try {
rendezvousTime = LocalTime.parse(timeStr, formatter);
} catch (DateTimeParseException ex) {
throw new IllegalArgumentException("Illegal time string: " + timeStr);
}
} catch (IllegalStateException ex) {
throw new IllegalArgumentException("Illegal format string: " + formatStr);
}
}
public void pushLater(int hour, int minute) {
rendezvousTime = rendezvousTime.plusHours(hour).plusMinutes(minute);
}
public void pullEarlier(int hour, int minute) {
rendezvousTime = rendezvousTime.minusHours(hour).minusMinutes(minute);
}
public int countMinutesLeft(LocalTime base) {
int timeToGo = (int) ChronoUnit.MINUTES.between(base, rendezvousTime);
if (timeToGo <= 0) {
throw new MissedOpportunityException("Too late!");
}
return timeToGo;
}
public void validateFormatString(String formatStr) {
if (formatStr == null || formatStr.isBlank()) {
throw new IllegalArgumentException("Empty pattern string!");
}
}
public String toString(String formatStr) {
validateFormatString(formatStr);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(formatStr);
return formatter.format(rendezvousTime);
}
}
|
package ma.ensa.todo.beans;
import java.util.ArrayList;
import java.util.List;
public class Utilisateur {
private int id;
private String login;
private String motpasse;
private String email;
private List<Tache> taches;
public Utilisateur() {
// TODO Auto-generated constructor stub
taches = new ArrayList<Tache>();
}
/**
* @return the id
*/
public int getId() {
return id;
}
/**
* @param id
* the id to set
*/
public void setId(int id) {
this.id = id;
}
/**
* @return the login
*/
public String getLogin() {
return login;
}
/**
* @param login
* the login to set
*/
public void setLogin(String login) {
this.login = login;
}
/**
* @return the motpasse
*/
public String getMotpasse() {
return motpasse;
}
/**
* @param motpasse
* the motpasse to set
*/
public void setMotpasse(String motpasse) {
this.motpasse = motpasse;
}
/**
* @return the email
*/
public String getEmail() {
return email;
}
/**
* @param email
* the email to set
*/
public void setEmail(String email) {
this.email = email;
}
/**
* @return the taches
*/
public List<Tache> getTaches() {
return taches;
}
/**
* @param taches
* the taches to set
*/
public void setTaches(List<Tache> taches) {
this.taches = taches;
}
public void ajouterTache(Tache tache) {
this.taches.add(tache);
}
public void supprimerTache(Tache tache) {
this.taches.remove(tache);
}
}
|
package com.tu.springsession;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* @Auther: tuyongjian
* @Date: 2020/4/16 15:56
* @Description:
*/
@SpringBootApplication
public class MycatApplication {
public static void main(String[] args) {
SpringApplication.run(MycatApplication.class,args);
}
}
|
package com.company;
//import java.util.Scanner;
public class Random {
public static void main(String[] args) {
// Person p1=new Person();//calss obj=new construc()
// Person p2=new Person(21,"Rabin");
// p1.name="Rahul";
// p1.age=19;
// p2.name="Raj";
// p2.age=20;
// System.out.println(p1.name+" "+p1.age);
// System.out.println(p2.name+" "+p2.age);
// p1.walk();
// p2.walk(10);
// p1.eat();
// p2.eat();
// System.out.println(Person.count);
Engineer e=new Engineer(19,"Rahul");
System.out.println(e.age);
System.out.println(e.name);
e.eat();
e.walk();
e.walk(10);
}
}
class Person{
String name;
int age;
static int count;
public Person(){
System.out.println("Rahul is eating rice");
count++;
}
public Person(int age,String name){
this();
this. name=name;
this. age=age;
}
void walk(){
System.out.println(name+" "+"is walking");
}
void eat(){
System.out.println(name+" "+"has eaten fish");
}
void walk(int steps){
System.out.println(name+" "+"walked"+" "+steps+"steps");
}
}
class Engineer extends Person{
public Engineer(int age,String name){
super(age, name);
}
void walk(){
System.out.println(name+" "+"is not walking");
}
}
|
package Customer;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import javax.swing.*;
import oracleDBA.CustomerOra;
import Templates.JDateTimePicker;
public class DataSelectPanel extends JPanel {
/**
*
*/
private static final long serialVersionUID = -3958070591089437721L;
private JDateTimePicker checkInBox;
private JDateTimePicker checkOutBox;
private JComboBox roomTypeCombo;
private JComboBox guestNumCombo;
private JComboBox parkingCombo;
private GridBagConstraints gbc;
public DataSelectPanel() {
super();
this.setLayout(new GridBagLayout());
gbc = new GridBagConstraints();
gbc.insets = new Insets(5, 5, 5, 5);
setUpDataSelectPanel();
}
public void setResData(Reservation res) {
res.setCheckInDate(checkInBox.getDate());
res.setCheckOutDate(checkOutBox.getDate());
res.setRoomType(roomTypeCombo.getSelectedItem().toString());
}
private void populateComboBoxes() {
CustomerOra ora = new CustomerOra();
String roomTypes = ora.getRoomTypesFromDB();
List<String> types = Arrays.asList(roomTypes.split("\\s*,\\s*"));
for (int i = 0; i < types.size(); i++) {
roomTypeCombo.addItem(types.get(i));
}
parkingCombo.addItem("Yes");
parkingCombo.addItem("No");
for (int i = 1; i < 10; i++) {
guestNumCombo.addItem(i);
}
}
private void setUpDataSelectPanel() {
roomTypeCombo = new JComboBox();
guestNumCombo = new JComboBox();
setUpDatePickers();
parkingCombo = new JComboBox();
JLabel checkInLabel = new JLabel("Check-in:");
JLabel checkOutLabel = new JLabel("Check-out:");
JLabel RoomTypeLabel = new JLabel("Room Type:");
JLabel GuestNumLabel = new JLabel("Guest Number:");
JLabel ParkingLabel = new JLabel("Parking:");
this.setMaximumSize(new Dimension(300, 150));
this.addInGrid(checkInLabel, 1, 1);
this.addInGrid(checkInBox, 2, 1, GridBagConstraints.EAST);
this.addInGrid(checkOutLabel, 1, 2);
this.addInGrid(checkOutBox, 2, 2, GridBagConstraints.EAST);
this.addInGrid(RoomTypeLabel, 1, 3);
roomTypeCombo.setPreferredSize(new Dimension(170, 40));
this.addInGrid(roomTypeCombo, 2, 3, GridBagConstraints.EAST);
this.addInGrid(GuestNumLabel, 1, 4);
guestNumCombo.setPreferredSize(new Dimension(170, 40));
this.addInGrid(guestNumCombo, 2, 4, GridBagConstraints.EAST);
this.addInGrid(ParkingLabel, 1, 5);
parkingCombo.setPreferredSize(new Dimension(170, 40));
this.addInGrid(parkingCombo, 2, 5, GridBagConstraints.EAST);
populateComboBoxes();
}
private void addInGrid(JComponent toBeAdded, int x, int y) {
gbc.gridx = x;
gbc.gridy = y;
this.add(toBeAdded, gbc);
}
private void addInGrid(JComponent toBeAdded, int x, int y, int align) {
gbc.gridx = x;
gbc.gridy = y;
gbc.anchor = align;
this.add(toBeAdded, gbc);
}
private void setUpDatePickers() {
checkInBox = new JDateTimePicker();
checkOutBox = new JDateTimePicker();
checkOutBox.addDay(1);
}
public void setData(Reservation res) {
// TODO Auto-generated method stub
checkInBox.setDate(res.getCheckInDate());
checkOutBox.setDate(res.getCheckOutDate());
roomTypeCombo.setSelectedItem(res.getRoomType());
}
public void clear() {
checkInBox.setDate(new Date());
checkOutBox.setDate(new Date());
checkOutBox.addDay(1);
roomTypeCombo.setSelectedIndex(0);
guestNumCombo.setSelectedIndex(0);
parkingCombo.setSelectedIndex(0);
}
}
|
package lib.hyxen.ui;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import java.util.ArrayList;
import java.util.Arrays;
/**
* Will notice through listen when needs to load next page data.
*
* Created by redjack on 15/7/13.
*/
public class ListPager<E> extends SimpleItemAdapter {
static final public int INITIAL_PAGE = 1;
int initialPage = INITIAL_PAGE;
int page = 0;
int reloadCount = 20;
int nextReloadIndex = 0;
public boolean isReloadWhenShowTwoThird = false;
boolean isLoadedFirst = false;
boolean isLoadAll = false;
boolean hasSentLoadNotice = false;
ListPagerListener pageListener;
public ListPager(Context context, Class itemClass, ListPagerListener pageListener) {
super(context, itemClass, new ArrayList<E>());
this.pageListener = pageListener;
this.initialPage = INITIAL_PAGE;
this.page = this.initialPage;
}
public ListPager(Context context, Class itemClass, int reloadCount, ListPagerListener pageListener) {
super(context, itemClass, new ArrayList<E>());
this.initialPage = INITIAL_PAGE;
this.page = this.initialPage;
this.reloadCount = reloadCount;
this.pageListener = pageListener;
}
public ListPager(Context context, Class itemClass, int initialPage, int reloadCount, ListPagerListener pageListener) {
super(context, itemClass, new ArrayList<E>());
this.initialPage = initialPage;
this.page = this.initialPage;
this.reloadCount = reloadCount;
this.pageListener = pageListener;
}
/**
* Call this method when view is ready, if view is not finished onCreateView, list view won't load.
*/
public void loadFirstPage()
{
if (isLoadedFirst || pageListener == null) return;
isLoadedFirst = false;
pageListener.needToLoadNextPage(new ListPagerTask(true, page, reloadCount));
}
public void updateList(ArrayList items, boolean needToReload) {
updateList(items);
page = initialPage;
setCheckPoint(items != null ? items.size() : 0, isReloadWhenShowTwoThird);
if (needToReload) loadFirstPage();
}
public void updateList(Object[] items, boolean needToReload) {
updateList(items);
page = initialPage;
setCheckPoint(items != null ? items.length : 0, isReloadWhenShowTwoThird);
if (needToReload) loadFirstPage();
}
private void setCheckPoint(int totalCount, boolean isReloadWhenShowTwoThird)
{
if (totalCount <= 0)
{
nextReloadIndex = 0;
return;
}
nextReloadIndex = isReloadWhenShowTwoThird ? (int) (totalCount * 0.6) : totalCount - 1;
if (nextReloadIndex <= 0) nextReloadIndex = 0;
}
public boolean isLoadAll(E[] data)
{
return isLoadAll(new ArrayList<E>(Arrays.asList(data)));
}
public boolean isLoadAll(ArrayList<E> data)
{
isLoadAll = data.size() < reloadCount;
return isLoadAll;
}
public boolean isNeedToLoadAtPosition(int position)
{
return !isLoadAll && !hasSentLoadNotice && position >= nextReloadIndex;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View item = super.getView(position, convertView, parent);
if (pageListener != null && isNeedToLoadAtPosition(position))
{
pageListener.needToLoadNextPage(new ListPagerTask(false, page + 1, reloadCount));
hasSentLoadNotice = true;
}
return item;
}
@Override
public E getItem(int position) {
return (E) super.getItem(position);
}
public void appendNewData(E[] newItems)
{
appendNewData(new ArrayList<E>(Arrays.asList(newItems)));
}
public void appendNewData(final ArrayList<E> newItems)
{
updateHandler.post(new Runnable() {
@Override
public void run() {
items.addAll(newItems);
isLoadAll(newItems);
setCheckPoint(items.size(), isReloadWhenShowTwoThird);
updateList(items);
}
});
}
/**
* Default is 20;
*/
public void setReloadCount(int reloadCount) {
this.reloadCount = reloadCount;
}
public void setPagerListener(ListPagerListener pagerListener) {
this.pageListener = pagerListener;
}
public void setPagerListener(int reloadCount, ListPagerListener pagerListener) {
setReloadCount(reloadCount);
setPagerListener(pagerListener);
}
public void clearAll()
{
isLoadedFirst = false;
items.clear();
updateList(items, false);
}
public void clearAllAndReload()
{
isLoadedFirst = false;
items.clear();
updateList(items, true);
}
public ArrayList<E> getAll(){
return items;
}
/**
* Execute appendNewData if receive new data.
*/
public class ListPagerTask
{
boolean isAskFirstLoad = false;
int needLoadAtPage;
int reloadCount;
public ListPagerTask(boolean isAskFirstLoad, int needLoadAtPage, int reloadCount)
{
this.isAskFirstLoad = isAskFirstLoad;
this.needLoadAtPage = needLoadAtPage;
this.reloadCount = reloadCount;
}
public void newDataArrive(ArrayList<E> data)
{
appendNewData(data);
page = this.needLoadAtPage;
hasSentLoadNotice = false;
if (isAskFirstLoad) isLoadedFirst = true;
}
public void newDataArrive(E[] data)
{
appendNewData(data);
page = this.needLoadAtPage;
hasSentLoadNotice = false;
}
public void loadNextPage()
{
page = this.needLoadAtPage;
this.needLoadAtPage ++;
pageListener.needToLoadNextPage(this);
}
public ArrayList<E> getAll(){
return ListPager.this.getAll();
}
public void clearAndUpdateNewData(ArrayList<E> data)
{
updateList(data, true);
}
public void clearAndUpdateNewData(E[] data)
{
updateList(data, true);
}
public int getPage() {
return needLoadAtPage;
}
public int getReloadCount() {
return reloadCount;
}
}
public interface ListPagerListener {
public void needToLoadNextPage(ListPager.ListPagerTask task);
}
}
|
package com.blog.Idao;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import com.blog.bean.Adminuser;
import com.blog.util.DBUtil;
public interface IAdminuserDao {
/**
* 判断该管理员是否存在
* @param a_name
* @param a_pass
* @return boolean
*/
public boolean Login(String a_name);
/**
* 获取该管理员信息
* @param a_name
* @param a_pass
* @return Adminuser
*/
public Adminuser adminUserByname(String a_name);
/**
* 插入数据添加管理员
*/
public boolean RegAdminUser(Adminuser adminuser);
/**
* 判断该管理员账户是否存在
*/
public boolean isAdminuserByname(Adminuser adminuser);
/**
* 根据账户查询管理员信息
*/
public Adminuser AdminUserReg(Adminuser adminuser);
/**
* 修改密码字段
* @param adminuser
* @param a_id
*/
public boolean Change_a_pass(Adminuser adminuser,int a_id);
public List<Adminuser> adminuserlist();
public int getTotalCountadminuser();
public List<Adminuser> adminuserlistBypage(int currentPage, int pageSize);
}
|
package com.leibro.service;
import com.leibro.dto.Exposer;
import com.leibro.dto.SeckillExecution;
import com.leibro.entity.SecKill;
import com.leibro.exception.RepeatKillException;
import com.leibro.exception.SeckillCloseException;
import com.leibro.exception.SeckillException;
import java.util.List;
/**
* 业务接口:站在"使用者"角度设计接口
* 三个方面:方法定义粒度,参数,返回类型(return 类型/异常)
* Created by leibro on 2017/4/9.
*/
public interface SeckillSerivce {
/**
* 查询所有秒杀记录
* @return
*/
List<SecKill> getSeckillList();
SecKill getById(long seckillId);
Exposer exportSeckillUrl(long seckillId);
SeckillExecution executeSeckill(long seckillId, long userPhone, String md5) throws SeckillException,RepeatKillException,SeckillCloseException;
}
|
package com.model;
public class poto {
private String xh;
private String lj;
private String filename;
private String intime;
private String bz;
private String busi;
private String typename;
private String sid;
private String zt;
private String inperson;
private String wjfl;
private String jlj;
private String ljbz;
private String mlbm;
private String mlmc;
private String sjmlbm;
private String mllj;
private String begindate;
private String enddate;
private String qsjd;
private String zzjd;
private String jswd;
private String zzwd;
private String kcmc;
public String getBegindate() {
return begindate;
}
public void setBegindate(String begindate) {
this.begindate = begindate;
}
public String getEnddate() {
return enddate;
}
public void setEnddate(String enddate) {
this.enddate = enddate;
}
public String getQsjd() {
return qsjd;
}
public void setQsjd(String qsjd) {
this.qsjd = qsjd;
}
public String getZzjd() {
return zzjd;
}
public void setZzjd(String zzjd) {
this.zzjd = zzjd;
}
public String getJswd() {
return jswd;
}
public void setJswd(String jswd) {
this.jswd = jswd;
}
public String getZzwd() {
return zzwd;
}
public void setZzwd(String zzwd) {
this.zzwd = zzwd;
}
public String getKcmc() {
return kcmc;
}
public void setKcmc(String kcmc) {
this.kcmc = kcmc;
}
public String getMllj() {
return mllj;
}
public void setMllj(String mllj) {
this.mllj = mllj;
}
public String getMlbm() {
return mlbm;
}
public void setMlbm(String mlbm) {
this.mlbm = mlbm;
}
public String getMlmc() {
return mlmc;
}
public void setMlmc(String mlmc) {
this.mlmc = mlmc;
}
public String getSjmlbm() {
return sjmlbm;
}
public void setSjmlbm(String sjmlbm) {
this.sjmlbm = sjmlbm;
}
public String getLjbz() {
return ljbz;
}
public void setLjbz(String ljbz) {
this.ljbz = ljbz;
}
public String getJlj() {
return jlj;
}
public void setJlj(String jlj) {
this.jlj = jlj;
}
public String getWjfl() {
return wjfl;
}
public void setWjfl(String wjfl) {
this.wjfl = wjfl;
}
public String getInperson() {
return inperson;
}
public void setInperson(String inperson) {
this.inperson = inperson;
}
public String getZt() {
return zt;
}
public void setZt(String zt) {
this.zt = zt;
}
public String getSid() {
return sid;
}
public void setSid(String sid) {
this.sid = sid;
}
public String getTypename() {
return typename;
}
public void setTypename(String typename) {
this.typename = typename;
}
public String getBusi() {
return busi;
}
public void setBusi(String busi) {
this.busi = busi;
}
public String getBz() {
return bz;
}
public void setBz(String bz) {
this.bz = bz;
}
public String getIntime() {
return intime;
}
public void setIntime(String intime) {
this.intime = intime;
}
public String getFilename() {
return filename;
}
public void setFilename(String filename) {
this.filename = filename;
}
public String getXh() {
return xh;
}
public void setXh(String xh) {
this.xh = xh;
}
public String getLj() {
return lj;
}
public void setLj(String lj) {
this.lj = lj;
}
}
|
// ScriptExecutor.java
package org.google.code.servant.util;
import java.io.IOException;
import java.io.InputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.List;
import java.util.ArrayList;
/**
* This class wraps all work related to script execution.
* It is implemented as Singleton pattern.
*
* @version 1.0 05/18/2001
* @author Alexander Shvets
*/
public class ScriptExecutor {
private StringBuffer stdOutput = new StringBuffer();
private StringBuffer errOutput = new StringBuffer();
/** The name of the user */
private String userName;
/**
* Creates an instance of this class.
*/
public ScriptExecutor() {}
/**
* Gets the user name.
*
* @return the name of the user
*/
public String getUserName() {
return userName;
}
/**
* Sets the user name.
*
* @param userName the name of the user
*/
public void setUserName(String userName) {
this.userName = userName;
}
/**
* Executes the script with one parameter.
*
* @param scriptName the name of the script
* @param param the single parameter-string
* @return the status of execution
* @exception InterruptedException if an interruption occurs.
* @throws IOException I/O exception
*/
public int execute(String scriptName, String param)
throws IOException, InterruptedException {
List params = new ArrayList();
params.add(scriptName);
params.add(param);
return execute(params);
}
/**
* Executes the command outlined in params list.
*
* @param params the list of parameters
* @return the exit value
* @exception IOException if an I/O error occurs.
* @exception InterruptedException if an interruption occurs.
*/
public int execute(List params) throws IOException, InterruptedException {
stdOutput.delete(0, stdOutput.length());
errOutput.delete(0, errOutput.length());
String osName = System.getProperties().getProperty("os.name");
String[] args;
int offset = 0;
if(osName.startsWith("Windows")) {
args = new String[params.size()+2];
args[offset++] = "command.com";
args[offset++] = "/C";
}
else {
args = new String[params.size()];
}
for(int i=0; i < params.size(); i++) {
args[i+offset] = (String)params.get(i);
}
Process process = Runtime.getRuntime().exec(args);
process.waitFor();
redirectStream(process.getInputStream(), stdOutput);
redirectStream(process.getErrorStream(), errOutput);
return process.exitValue();
}
/**
* Redirects the stream to a console.
*
* @param is the input stream
* @param sb the string buffer
* @throws IOException I/O exception
*/
private void redirectStream(InputStream is, StringBuffer sb)
throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
while(true) {
String line = reader.readLine();
if(line == null) {
break;
}
sb.append(line).append("\r\n");
}
reader.close();
}
public String getStandardOutput() {
return stdOutput.toString();
}
public String getErrorOutput() {
return errOutput.toString();
}
}
|
package com.oa.asset.dao;
import java.util.List;
import org.springframework.stereotype.Repository;
import com.oa.asset.form.ProductListItem;
import com.oa.base.dao.BaseDaoImpl;
import com.oa.page.form.Page;
@Repository
public class ProductListItemDaoImpl extends BaseDaoImpl<ProductListItem> implements ProductListItemDao {
@Override
public void addProductListItem(ProductListItem productListItem) {
this.add(productListItem);
}
@Override
public List<ProductListItem> selectAllProductListItem() {
return this.findAll();
}
@Override
public List<ProductListItem> selectProductListItemsByPage(Page page) {
return null;
}
@Override
public ProductListItem selectProductListItemById(int productListItemId) {
return this.load(productListItemId);
}
@Override
public void updateProductListItem(ProductListItem productListItem) {
this.update(productListItem);
}
@Override
public void deleteProductListItem(Integer productListItemId) {
this.delete(productListItemId);
}
}
|
package com.citibank.ods.common.valueobject;
import java.io.Serializable;
import com.citibank.ods.common.BaseObject;
/**
*
* Classe base para as classes do tipo VO. As classes deste tipo devem ser
* serializáveis poir tem o objeto de somente trafegar informação. Portanto,
* poderão ser agregadas ao FncVO que será disponibilizado em session.
*
* @version: 1.00
* @author Luciano Marubayashi, Dec 21, 2006
*/
public class BaseVO extends BaseObject implements Serializable
{
}
|
package main;
import org.junit.Test;
public class HelloWold {
public static void main(String[] args) {
System.out.println("helloworld");
}
@Test
public void sayHelloWorld() {
System.out.println("helloworld");
}
}
|
package TestCases;
import org.openqa.selenium.support.PageFactory;
import org.testng.annotations.Test;
import Utility.BaseClass;
import pages.HomePage;
import pages.Login;
public class LoginToStore extends BaseClass {
@Test
public void testInvalidLogin()
{
BaseClass.logger = reports.createTest("testInvalidLogin");
HomePage home1 = PageFactory.initElements(driver, HomePage.class);
home1.verifyPageTitle();
home1.clickonAccountLink();
Login loginpage = PageFactory.initElements(driver, Login.class);
loginpage.logintoApplication("Selenium", "Password");
}
}
|
package Laboratorio0;
import java.util.Scanner;
public class Ejercicio3_2 {
public static void main(String[] args) {
// Ingresar el número cifrado
// Intercambiar el primero con el tercero
// Intercambiar el segundo con el cuarto
// Realizar la operación inversa
Scanner s = new Scanner(System.in);
System.out.print("Ingrese el numero: ");
String numero;
numero = s.nextLine();
int[] cadena = new int[numero.length()];
int[] cadenaNueva = new int[numero.length()];
for(int i = 0; i < cadena.length; i++){
cadena[i] = Integer.parseInt(String.valueOf(numero.charAt(i)));
}
// Intercambiando el primero con el tercero
int aux = cadena[0];
int aux2 = cadena[2];
cadena[0] = aux2;
cadena[2] = aux;
// Intercambiando el segundo con el cuarto
int aux1 = cadena[1];
int aux3 = cadena[3];
cadena[1] = aux3;
cadena[3] = aux1;
for(int i = 0; i < cadena.length; i++){
// Sumando 10 y restando 7 al número
int al = 0, sum = 0, res = 0;
al = cadena[i]; // 1
sum = al+10; // 11
res = sum-7; // 4
cadenaNueva[i] = res;
}
for (int i = 0; i < cadenaNueva.length; i++){
System.out.println(cadenaNueva[i]);
}
}
}
|
/*
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.context.annotation;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.role.ComponentWithRole;
import org.springframework.context.annotation.role.ComponentWithoutRole;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Tests the use of the @Role and @Description annotation on @Bean methods and @Component classes.
*
* @author Chris Beams
* @author Juergen Hoeller
* @since 3.1
*/
class RoleAndDescriptionAnnotationTests {
@Test
void onBeanMethod() {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
ctx.register(Config.class);
ctx.refresh();
assertThat(ctx.getBeanDefinition("foo").getRole()).isEqualTo(BeanDefinition.ROLE_APPLICATION);
assertThat(ctx.getBeanDefinition("foo").getDescription()).isNull();
assertThat(ctx.getBeanDefinition("bar").getRole()).isEqualTo(BeanDefinition.ROLE_INFRASTRUCTURE);
assertThat(ctx.getBeanDefinition("bar").getDescription()).isEqualTo("A Bean method with a role");
ctx.close();
}
@Test
void onComponentClass() {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
ctx.register(ComponentWithoutRole.class, ComponentWithRole.class);
ctx.refresh();
assertThat(ctx.getBeanDefinition("componentWithoutRole").getRole()).isEqualTo(BeanDefinition.ROLE_APPLICATION);
assertThat(ctx.getBeanDefinition("componentWithoutRole").getDescription()).isNull();
assertThat(ctx.getBeanDefinition("componentWithRole").getRole()).isEqualTo(BeanDefinition.ROLE_INFRASTRUCTURE);
assertThat(ctx.getBeanDefinition("componentWithRole").getDescription()).isEqualTo("A Component with a role");
ctx.close();
}
@Test
void viaComponentScanning() {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
ctx.scan("org.springframework.context.annotation.role");
ctx.refresh();
assertThat(ctx.getBeanDefinition("componentWithoutRole").getRole()).isEqualTo(BeanDefinition.ROLE_APPLICATION);
assertThat(ctx.getBeanDefinition("componentWithoutRole").getDescription()).isNull();
assertThat(ctx.getBeanDefinition("componentWithRole").getRole()).isEqualTo(BeanDefinition.ROLE_INFRASTRUCTURE);
assertThat(ctx.getBeanDefinition("componentWithRole").getDescription()).isEqualTo("A Component with a role");
ctx.close();
}
@Configuration
static class Config {
@Bean
String foo() {
return "foo";
}
@Bean
@Role(BeanDefinition.ROLE_INFRASTRUCTURE)
@Description("A Bean method with a role")
String bar() {
return "bar";
}
}
}
|
package com.fuchangyao.controller;
import com.alibaba.dubbo.config.annotation.Reference;
import com.fuchangyao.pojo.Goods;
import com.fuchangyao.service.GoodsService;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Map;
/**
* Created by fcy on 2019/11/18.
*/
@CrossOrigin
@RestController
@RequestMapping("goods")
public class GoodsController {
@Reference
private GoodsService goodsService;
@RequestMapping(value = "/findAll",method = RequestMethod.POST)
public List findAll(@RequestBody Map<String,String> map){
System.out.println("输入的价格:"+map.get("gprice"));
System.out.println("下拉框code:"+map.get("code"));
return goodsService.findAll(map);
}
@RequestMapping(value = "/delShops",method = RequestMethod.POST)
public String findAll(String ids){
System.out.println(ids);
try {
goodsService.delShops(ids);
return "删除成功";
} catch (Exception e) {
e.printStackTrace();
return "删除失败";
}
}
@RequestMapping(value = "/saveGood",method = RequestMethod.POST)
public String saveGood(@RequestBody Goods goods){
try {
goodsService.saveGood(goods);
return "添加成功";
} catch (Exception e) {
e.printStackTrace();
return "添加失败";
}
}
@RequestMapping(value = "/findOne",method = RequestMethod.GET)
public Goods findAll(int id){
return goodsService.findOne(id);
}
@RequestMapping(value = "/updateGood",method = RequestMethod.POST)
public String updateGood(@RequestBody Goods goods){
try {
goodsService.updateGood(goods);
return "修改成功";
} catch (Exception e) {
e.printStackTrace();
return "修改失败";
}
}
}
|
package com.wangzhu.guava;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.base.Function;
import com.google.common.base.Predicate;
import com.google.common.base.Predicates;
import com.google.common.collect.Collections2;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
public class TestFilterTransform {
private static final Logger logger = LoggerFactory
.getLogger(TestFilterTransform.class);
public static void main(String[] args) {
// filter
List<String> strList = Lists.newArrayList("apple", "orange", "pear",
"banana");
TestFilterTransform.logger.info("iterables filter:{}",
Iterables.filter(strList, Predicates.containsPattern("p")));
TestFilterTransform.logger.info("collections2 filter:{}",
Collections2.filter(strList, Predicates.containsPattern("p")));
Predicate<String> predicate = new Predicate<String>() {
public boolean apply(String input) {
return input.contains("p") && input.startsWith("a");
}
};
TestFilterTransform.logger.info("iterables filter:{}",
Iterables.filter(strList, predicate));
TestFilterTransform.logger.info("collections2 filter:{}",
Collections2.filter(strList, predicate));
Function<String, Integer> function = new Function<String, Integer>() {
public Integer apply(String input) {
return input.length();
}
};
TestFilterTransform.logger.info("transform:{}",
Collections2.transform(strList, function));
}
}
|
package com.bsoft;
import java.util.List;
/**
* @ClassName: TestMyList
* @Description: TODO
* @Author: zhuangy
* @Date: 2019-05-20 09:40
**/
public class TestMyList {
public static void main(String[] args) {
List myList = new MyList();
myList.add(2);
myList.add(1);
traversingList(myList);
System.out.println("------分隔符--------");
((MyList) myList).sort(new ObjectComparator());
traversingList(myList);
}
private static void traversingList(List list) {
for (Object obj : list) {
System.out.println(obj);
}
}
}
|
package com.jude.file.mail;
import com.jude.file.bean.ResponseBean;
import com.jude.file.common.MailUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.*;
import java.util.List;
import java.util.Properties;
/**
* @author :wupeng
* @date :Created in 9:51 2018/8/6
* @description:
*/
@Component
public class KindlePush {
@Value("mail.connect.senderAddress")
private String senderAddress;
@Value("mail.connect.recipientsAddress")
private String recipientsAddress;
@Value("mail.connect.senderAccount")
private String senderAccount;
@Value("mail.connect.senderToken")
private String senderToken;
@Value("mail.connect.authMail")
private String authMail;
@Value("mail.connect.protocolMail")
private String protocolMail;
@Value("mail.connect.hostMail")
private String hostMail;
private static final Logger logger = LoggerFactory.getLogger(KindlePush.class);
public ResponseBean push(String title, String message, List<String> filePath){
/*邮件参数*/
Properties arguments = new Properties();
arguments.put(Constants.AUTH_MAIL,authMail);
arguments.put(Constants.PROTOCOL_MAIL,protocolMail);
arguments.put(Constants.HOST_MAIL,hostMail);
Session session = Session.getInstance(arguments);
/*控制台打印调试信息*/
session.setDebug(true);
try {
MimeMessage mail = MailUtils.getMimeMessage(senderAddress, recipientsAddress, title, message, filePath, session);
Transport transport = session.getTransport();
transport.connect(senderAccount, senderToken);
transport.sendMessage(mail,mail.getAllRecipients());
} catch (MessagingException e) {
return ResponseBean.error("推送异常");
}
return ResponseBean.success("推送成功");
}
}
|
package com.mingrisoft.generic;
import java.util.Arrays;
public class BinSearch {
public static <T extends Comparable<? super T>> int search(T[] array, T key) {
int low = 0;
int mid = 0;
int high = array.length;
System.out.println("查找的中间值:");
while (low <= high) {
mid = (low + high) / 2;
System.out.print(mid+" ");
if (key.compareTo(array[mid]) > 0) {
low = mid + 1;
} else if (key.compareTo(array[mid]) < 0) {
high = mid - 1;
} else {
System.out.println();
return mid;
}
}
return -1;
}
public static void main(String[] args) {
Integer[] ints = {1,2,3,4,5,6,7,8,9,10};
System.out.println("数据集合:");
System.out.println(Arrays.toString(ints));
System.out.println("元素3所对于的索引序号:"+search(ints, 3));
}
}
|
/*
* 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 util.curves;
import graphicalsystem.IntPoint;
import static util.MoreGenericity.checkNullArg;
import util.MoreMath;
import util.Reflection;
/**
* @author Raphaël
**/
public final class IntFrame
{
private int xMin, xMax, yMin, yMax;
public IntFrame()
{
xMin = 0;
xMax = 0;
yMin = 0;
yMax = 0;
}
public IntFrame(int x1, int y1, int x2, int y2)
{
xMin = Math.min(x1, x2);
xMax = Math.max(x1, x2);
yMin = Math.min(y1, y2);
yMax = Math.max(y1, y2);
}
public int getxMin()
{
return xMin;
}
public void setxMin(int xMin)
{
if(xMin > xMax)
{
throw new IllegalArgumentException("xMin can't be superior to xMax.");
}
else
{
this.xMin = xMin;
}
}
public int getxMax()
{
return xMax;
}
public void setxMax(int xMax)
{
if(xMax < xMin)
{
throw new IllegalArgumentException("xMax can't be inferior to xMin.");
}
else
{
this.xMax = xMax;
}
}
public int getyMin()
{
return yMin;
}
public void setyMin(int yMin)
{
if(yMin > yMax)
{
throw new IllegalArgumentException("yMin can't be superior to yMax.");
}
else
{
this.yMin = yMin;
}
}
public int getyMax()
{
return yMax;
}
public void setyMax(int yMax)
{
if(yMax < yMin)
{
throw new IllegalArgumentException("yMax can't be inferior to yMin.");
}
else
{
this.yMax = yMax;
}
}
public IntFrame getIntersection(IntFrame frame)
{
if(frame == null)
{
return null;
}
int interXMin = Math.max(xMin, frame.xMin),
interXMax = Math.min(xMax, frame.xMax),
interYMin = Math.max(yMin, frame.yMin),
interYMax = Math.min(yMax, frame.yMax);
if(interXMin <= interXMax && interYMin <= interYMax)
{
return new IntFrame(interXMin, interYMin, interXMax, interYMax);
}
else
{
return null;
}
}
public IntPoint getNearestInsidePoint(int X, int Y)
{
return new IntPoint(MoreMath.limit(X, xMin, xMax),
MoreMath.limit(Y, yMin, yMax));
}
public IntPoint getNearestInsidePoint(IntPoint point)
{
checkNullArg(point, "point");
return getNearestInsidePoint(point.getAbs(), point.getOrd());
}
@Override
public String toString()
{
return Reflection.describeAttributes(this, false);
}
}
|
package util;
import java.util.List;
import java.util.Collection;
import java.util.LinkedList;
import java.util.ArrayList;
public class Queue {
private static final boolean DEBUG = false;
private String name;
private boolean pause = false;
private boolean stop = false;
private boolean drain = false;
private LinkedList list;
public Queue() {
this("Queue");
}
public Queue(String name) {
list = new LinkedList();
this.name = name;
}
public synchronized void drain() {
drain = true;
notifyAll();
}
public synchronized void pause() {
pause = true;
}
public synchronized void resume() {
pause = false;
notifyAll();
}
public synchronized List<?> contents() {
return new ArrayList(list);
}
public synchronized void stop() {
stop = true;
notifyAll();
}
public synchronized List<?> clear() {
List l = new ArrayList(list);
list.clear();
return l;
}
public synchronized int size() {
return list.size();
}
public synchronized boolean isEmpty() {
return list.isEmpty();
}
public synchronized void put(Object[] objects) {
for (int i = 0; i < objects.length; i++) list.add(objects[i]);
notifyAll();
}
public synchronized void put(Collection<?> collection) {
list.addAll(collection);
notifyAll();
}
public synchronized void put(Object object) {
list.add(object);
notifyAll();
}
public synchronized boolean putFirst(Object object) {
boolean c = list.remove(object);
list.addFirst(object);
notifyAll();
return c;
}
public synchronized Object remove(Object obj) {
int ind = list.indexOf(obj);
if (ind < 0) return null;
Object o = list.get(ind);
notifyAll();
return o;
}
public synchronized Object get() {
while (!stop && (list.isEmpty() || pause)) {
if (drain && list.isEmpty()) return null;
printDebug("Waiting");
try {
wait(60000);
} catch (InterruptedException e) { }
}
return stop ? null : list.removeFirst();
}
private void printDebug(String message) {
if (DEBUG) System.out.println(name+": "+message);
}
}
|
package com.junzhao.shanfen.model;
import android.os.Parcel;
import org.json.JSONException;
import org.json.JSONObject;
/**
* Created by Administrator on 2018/4/25 0025.
*/
public class PHFriend implements android.os.Parcelable{
public String userId;
public String userName;
public PHFriend(String userId, String userName) {
this.userId = userId;
this.userName = userName;
}
protected PHFriend(Parcel in) {
userId = in.readString();
userName = in.readString();
}
public static final Creator<PHFriend> CREATOR = new Creator<PHFriend>() {
@Override
public PHFriend createFromParcel(Parcel in) {
return new PHFriend(in);
}
@Override
public PHFriend[] newArray(int size) {
return new PHFriend[size];
}
};
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(userId);
dest.writeString(userName);
}
@Override
public String toString() {
JSONObject json = new JSONObject();
try {
json.put("userId",userId);
json.put("userName",userName);
return json.toString();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
}
|
package homework_5;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.File;
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
ArrayList <Student> listOfStudents = new ArrayList <>();
listOfStudents.add(new Student("Whilson", 3, 18));
listOfStudents.add(new Student("Jackson", 4, 20));
listOfStudents.add(new Student("Thompson", 5, 21));
listOfStudents.add(new Student("Jackson", 1, 16));
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder;
File dir = new File("C:\\test");
dir.mkdir();
try {
builder = factory.newDocumentBuilder();
Document doc = builder.newDocument();
Element rootElement =
doc.createElementNS(null, "Students");
doc.appendChild(rootElement);
for(int i = 0; i < listOfStudents.size(); i++ ){
rootElement.appendChild(XmlFile.getStudent(doc, listOfStudents.get(i).getSurname(), String.valueOf(listOfStudents.get(i).getCourse()), String.valueOf(listOfStudents.get(i).getStudentAge())));
}
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
DOMSource source = new DOMSource(doc);
StreamResult file = new StreamResult(new File("C:\\test\\Students.xml"));
transformer.transform(source, file);
System.out.println("XML file creation is finished \n ");
} catch (ParserConfigurationException e){
System.out.println(e.getStackTrace());
}
catch (TransformerConfigurationException e){
System.out.println(e.getStackTrace());
}
catch (TransformerException e){
System.out.println(e.getStackTrace());
}
Student.getStudentsSorted(listOfStudents);
}
}
|
package ua.com.hibernate.repository.impl;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import ua.com.hibernate.model.User;
import ua.com.hibernate.repository.UserRepository;
import java.util.List;
@Repository
public class UserRepositoryImpl implements UserRepository {
@Autowired
SessionFactory SessionFactory;
@Override
public void addUser(User user) {
getCurrentSession().save(user);
}
@Override
public void updateUser(User user) {
getCurrentSession().update(user);
}
@Override
public void deleteUser(User user) {
getCurrentSession().delete(user);
}
@Override
public User findById(int id) {
return getCurrentSession().get(User.class, id);
}
@Override
public List<User> findAll() {
return getCurrentSession().createQuery("SELECT u from User u", User.class).getResultList();
}
private Session getCurrentSession() {
return SessionFactory.getCurrentSession();
}
}
|
package p06;
import java.util.Scanner;
public class Exam01 {
static int[] numarr = new int[5];
public static void main(String[] args) {
inputNums();
run();
}
static void run() {
for (int i = numarr[0]; i >= numarr[1]; i--) {
String str = "";
for (int j = numarr[2]; j >= numarr[3]; j--) {
if ((i * j) % numarr[4] == 0) {
str += "[" + numarr[4] + "의배수], ";
}
else {
str += "[" + i + "*" + j + "=" + (i * j) + "]" + ", ";
}
}
System.out.println(str.substring(0, str.length() - 2));
}
}
static void inputNums() {
Scanner s = new Scanner(System.in);
for (int i = 0; i < 5; i++) {
System.out.println((i + 1) + "번째 숫자를 입력하세요");
numarr[i] = s.nextInt();
}
}
}
|
/*
* Copyright (C) 2008-2010 Martin Riesz <riesz.martin at gmail.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.petrinator.editor.commands;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import org.petrinator.petrinet.Arc;
import org.petrinator.petrinet.ArcEdge;
import org.petrinator.petrinet.Element;
import org.petrinator.petrinet.ElementCloner;
import org.petrinator.petrinet.PetriNet;
import org.petrinator.petrinet.Place;
import org.petrinator.petrinet.PlaceNode;
import org.petrinator.petrinet.ReferencePlace;
import org.petrinator.petrinet.Subnet;
import org.petrinator.petrinet.Transition;
import org.petrinator.util.CollectionTools;
import org.petrinator.util.Command;
/**
*
* @author Martin Riesz <riesz.martin at gmail.com>
*/
public class ReplaceSubnetCommand implements Command {
private Subnet subnet;
private Subnet storedSubnet;
private List<Element> previousElements;
private List<Element> newElements = new LinkedList<Element>();
private Set<Command> deleteReferenceArcCommands = new HashSet<Command>();
private PetriNet petriNet;
public ReplaceSubnetCommand(Subnet subnet, Subnet storedSubnet, PetriNet petriNet) {
this.petriNet = petriNet;
this.subnet = subnet;
Subnet clonedSubnet = ElementCloner.getClone(storedSubnet, petriNet);
petriNet.getNodeLabelGenerator().setLabelsToReplacedSubnet(clonedSubnet);
this.storedSubnet = clonedSubnet;
}
private Set<ReferencePlace> getReferencePlaces(Subnet subnet) {
Set<ReferencePlace> referencePlaces = new HashSet<ReferencePlace>();
for (Element element : subnet.getElements()) {
if (element instanceof ReferencePlace) {
ReferencePlace referencePlace = (ReferencePlace) element;
referencePlaces.add(referencePlace);
}
}
return referencePlaces;
}
private Set<ReferencePlace> getWeakEquivalents(ReferencePlace referencePlace, Set<ReferencePlace> referencePlaces) {
Set<ReferencePlace> weakEquivalents = new HashSet<ReferencePlace>();
for (ReferencePlace anotherReferencePlace : referencePlaces) {
if (referencePlace != anotherReferencePlace) {
if (weakEquivalentReferencePlaces(referencePlace, anotherReferencePlace)) {
weakEquivalents.add(anotherReferencePlace);
}
}
}
return weakEquivalents;
}
private boolean isWeakEquivalentWithAnotherFrom(ReferencePlace referencePlace, Set<ReferencePlace> referencePlaces) {
return !getWeakEquivalents(referencePlace, referencePlaces).isEmpty();
}
private boolean isStrongEquivalentWithAllWeakEquivalents(ReferencePlace referencePlace, Set<ReferencePlace> referencePlaces) {
Set<ReferencePlace> weakEquivalents = getWeakEquivalents(referencePlace, referencePlaces);
for (ReferencePlace weakEquivalent : weakEquivalents) {
if (!strongEquivalentReferencePlaces(referencePlace, weakEquivalent)) {
return false;
}
}
return true;
}
private boolean areAllStrongEquivalent(Set<ReferencePlace> referencePlaces) {
ReferencePlace someEquivalent = CollectionTools.getFirstElement(referencePlaces);
for (ReferencePlace referencePlace : referencePlaces) {
if (!strongEquivalentReferencePlaces(referencePlace, someEquivalent)) {
return false;
}
}
return true;
}
private void connect(ReferencePlace storedReferencePlace, ReferencePlace previousReferencePlace, Set<ReferencePlace> resolved) {
storedReferencePlace.setConnectedPlace(previousReferencePlace.getConnectedPlaceNode());
resolved.add(storedReferencePlace);
resolved.add(previousReferencePlace);
}
private ReferencePlace getNewReferencePlace(PlaceNode referencedPlaceNode, ReferencePlace model) {
ReferencePlace newReferencePlace = new ReferencePlace(referencedPlaceNode);
petriNet.getNodeSimpleIdGenerator().setUniqueId(newReferencePlace);
newReferencePlace.setCenter(referencedPlaceNode.getCenter().x - subnet.getCenter().x,
referencedPlaceNode.getCenter().y - subnet.getCenter().y);
for (Arc arc : model.getConnectedArcs()) { //TODO: !!! what if there are ReferenceArcs?
Arc newArc = new Arc(newReferencePlace, arc.getTransition(), arc.isPlaceToTransition());
newElements.add(newArc);
}
newElements.add(newReferencePlace);
return newReferencePlace;
}
public void execute() {
Set<ReferencePlace> previousReferencePlaces = getReferencePlaces(subnet);
Set<ReferencePlace> storedReferencePlaces = getReferencePlaces(storedSubnet);
Set<ReferencePlace> resolved = new HashSet<ReferencePlace>();
for (ReferencePlace storedReferencePlace : storedReferencePlaces) {
if (!isWeakEquivalentWithAnotherFrom(storedReferencePlace, storedReferencePlaces)) {
Set<ReferencePlace> weakEquivalentsFromPrevious = getWeakEquivalents(storedReferencePlace, previousReferencePlaces);
if (weakEquivalentsFromPrevious.size() == 1) {
ReferencePlace previousWeakEquivalent = CollectionTools.getFirstElement(getWeakEquivalents(storedReferencePlace, previousReferencePlaces));
connect(storedReferencePlace, previousWeakEquivalent, resolved);
}
}
}
for (ReferencePlace storedReferencePlace : storedReferencePlaces) {
if (!resolved.contains(storedReferencePlace)) {
Set<ReferencePlace> storedEquivalents = getWeakEquivalents(storedReferencePlace, storedReferencePlaces);
storedEquivalents.add(storedReferencePlace);
Set<ReferencePlace> previousEquivalents = getWeakEquivalents(storedReferencePlace, previousReferencePlaces);
if (areAllStrongEquivalent(storedEquivalents) && areAllStrongEquivalent(previousEquivalents)) {
for (ReferencePlace previousEquivalent : previousEquivalents) {
if (!resolved.contains(previousEquivalent)) {
ReferencePlace storedEquivalent = CollectionTools.getFirstElementNotIn(storedEquivalents, resolved);
if (storedEquivalent == null) {
ReferencePlace someStoredEquivalent = CollectionTools.getFirstElement(storedEquivalents);
storedEquivalent = getNewReferencePlace(previousEquivalent.getConnectedPlaceNode(), someStoredEquivalent);
}
connect(storedEquivalent, previousEquivalent, resolved);
}
}
}
}
}
Set<ReferencePlace> unresolvedStored = CollectionTools.getElementsNotIn(storedReferencePlaces, resolved);
Set<ReferencePlace> unresolvedPrevious = CollectionTools.getElementsNotIn(previousReferencePlaces, resolved);
if (areAllStrongEquivalent(unresolvedStored) && areAllStrongEquivalent(unresolvedPrevious)
&& unresolvedStored.size() >= 1 && unresolvedPrevious.size() >= 1) {
for (ReferencePlace unresolvedOnePrevious : unresolvedPrevious) {
ReferencePlace unresolvedOneStored = CollectionTools.getFirstElementNotIn(unresolvedStored, resolved);
if (unresolvedOneStored == null) {
ReferencePlace someUnresolvedStored = CollectionTools.getFirstElement(unresolvedStored);
unresolvedOneStored = getNewReferencePlace(unresolvedOnePrevious.getConnectedPlaceNode(), someUnresolvedStored);
}
connect(unresolvedOneStored, unresolvedOnePrevious, resolved);
}
}
for (ReferencePlace previousReferencePlace : previousReferencePlaces) {
if (!resolved.contains(previousReferencePlace)) {
deleteReferenceArcCommands.add(new DeleteReferenceArcCommand(previousReferencePlace.getReferenceArc()));
}
}
for (Element element : storedSubnet.getElements()) {
if (element instanceof ReferencePlace) {
ReferencePlace referencePlace = (ReferencePlace) element;
if (resolved.contains(referencePlace)) {
newElements.add(referencePlace);
}
} else {
newElements.add(element);
}
}
for (ReferencePlace storedReferencePlace : storedReferencePlaces) {
if (!resolved.contains(storedReferencePlace)) {
Place place = new Place();
petriNet.getNodeSimpleIdGenerator().setUniqueId(place);
place.setCenter(storedReferencePlace.getCenter().x, storedReferencePlace.getCenter().y);
for (ArcEdge arc : storedReferencePlace.getConnectedArcEdges()) {
arc.setPlaceNode(place);
}
place.setLabel("?!");
newElements.add(place);
}
}
for (Element element : storedSubnet.getElements()) { //TODO: clone
element.setParentSubnet(subnet);
}
previousElements = subnet.getElementsCopy();
subnet.setElements(newElements);
for (Command deleteReferenceArcCommand : deleteReferenceArcCommands) {
deleteReferenceArcCommand.execute();
}
}
public void undo() {
subnet.setElements(previousElements);
for (Command deleteReferenceArcCommand : deleteReferenceArcCommands) {
deleteReferenceArcCommand.undo();
}
}
public void redo() {
subnet.setElements(newElements);
for (Command deleteReferenceArcCommand : deleteReferenceArcCommands) {
deleteReferenceArcCommand.redo();
}
}
private boolean weakEquivalentReferencePlaces(ReferencePlace referencePlace1, ReferencePlace referencePlace2) {
Set<Transition> resolved = new HashSet<Transition>();
for (Transition transition1 : referencePlace1.getConnectedTransitionsRecursively()) {
for (Transition transition2 : referencePlace2.getConnectedTransitionsRecursively()) {
if (!resolved.contains(transition1) && !resolved.contains(transition2)) {
if (equivalentPlaceTransitionRelation(referencePlace1, transition1, referencePlace2, transition2)) {
resolved.add(transition1);
resolved.add(transition2);
}
}
}
}
if (resolved.containsAll(referencePlace1.getConnectedTransitionsRecursively()) && resolved.containsAll(referencePlace2.getConnectedTransitionsRecursively())) {
return true;
}
return false;
}
private boolean strongEquivalentReferencePlaces(ReferencePlace referencePlace1, ReferencePlace referencePlace2) {
return weakEquivalentReferencePlaces(referencePlace1, referencePlace2)
&& referencePlace1.getConnectedTransitionNodes().containsAll(referencePlace2.getConnectedTransitionNodes());
}
private boolean equivalentPlaceTransitionRelation(PlaceNode placeNode1, Transition transition1, PlaceNode placeNode2, Transition transition2) {
Arc arc1pTt = placeNode1.getConnectedArc(transition1, true);
Arc arc1tTp = placeNode1.getConnectedArc(transition1, false);
Arc arc2pTt = placeNode2.getConnectedArc(transition2, true);
Arc arc2tTp = placeNode2.getConnectedArc(transition2, false);
return equivalentArcs(arc1pTt, arc2pTt) && equivalentArcs(arc1tTp, arc2tTp);
}
private boolean equivalentArcs(Arc arc1, Arc arc2) {
if (arc1 == null && arc2 == null) {
return true;
} else if (arc1 == null || arc2 == null) {
return false;
} else if (arc1.getMultiplicity() == arc2.getMultiplicity()) {
return true;
}
return false;
}
@Override
public String toString() {
return "Replace subnet";
}
}
|
package unae.lp3.notas.controller;
import java.sql.Date;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import unae.lp3.notas.model.Categoria;
import unae.lp3.notas.model.Noticia;
import unae.lp3.notas.service.CategoriasServiceImpl;
import unae.lp3.notas.service.NoticiasServicesImpl;
@Controller
@RequestMapping(value="noticias")
public class NotciasController {
@Autowired
private NoticiasServicesImpl servNoti;
@Autowired
private CategoriasServiceImpl caterepo;
@GetMapping(value="/")
public String index(Model datos)
{
String titulo="Todas las Noticias";
String contenido="soy el contenido de DOS";
datos.addAttribute("titulo",titulo);
datos.addAttribute("contenido",contenido);
List <Noticia> noticias= servNoti.getNoticias();
datos.addAttribute("datos", noticias);
return "noticias/index";
}
@PostMapping(value="guardar")
public String save(Noticia noticia)
{
servNoti.saveNoticia(noticia);
return "redirect:/noticias/";
}
@GetMapping(value="nuevo")
public String add(Model datos)
{
Noticia nuevaNoticia = new Noticia();
nuevaNoticia.setFecha(new Date(System.currentTimeMillis()));
List<Categoria> categorias= (List<Categoria>) caterepo.getCategorias();
datos.addAttribute("noticia", nuevaNoticia);
datos.addAttribute("categorias",categorias);
datos.addAttribute("titulo", "Crear");
return "noticias/f_new";
}
@GetMapping(value="editar/{id}")
public String edit(Model datos, @PathVariable("id") int id)
{
List<Categoria> categorias= (List<Categoria>) caterepo.getCategorias();
Noticia noti=servNoti.getNoticia(id);
datos.addAttribute("noticia",noti);
datos.addAttribute("categorias",categorias);
datos.addAttribute("titulo", "Modificar");
return "noticias/f_new";
}
@GetMapping(value="borrar/{id}")
public String destroy(Model datos, @PathVariable("id") int id)
{
servNoti.deleteNoticia(id);
return "redirect:/noticias/";
}
}
|
package JavaPackage;
public class LoopsConcept {
public static void main(String[] args) {
//1 to 100
//1) While loop:
int i = 1; //Initialize
while(i<=10){ //Condition
System.out.println(i);
i++; //Incremental or Decremental
}
int p=1;
while(p<=20){
if(p % 5 == 0){
System.out.println("Hey");
}
p++;
}
//2) for loop:
for(int k=1; k<=10; k++){
System.out.println(k);
}
//Even Numbers
//Print only Even numbers: 2,4,...10
for(int even=2; even<=10; even=even+2){ //Here we start from 2 an even number and not 0
System.out.println(even);
}
//Odd Numbers
//Print only ODD numbers: 1,3,5,7,9
for(int odd=1; odd<10; odd=odd+2){
System.out.println(odd);
}
//3) do-while loop
int t = 1;
do{
System.out.println(t);
t++;
}
while (t<=10);
}
}
|
/*
* Created on 09/12/2008
*
*/
package com.citibank.ods.entity.pl;
import java.util.Date;
import com.citibank.ods.entity.pl.valueobject.TplErEntityVO;
import com.citibank.ods.entity.pl.valueobject.TplErMovEntityVO;
/**
* @author lfabiano
* @since 09/12/2008
*/
public class TplErEntity extends BaseTplErEntity
{
public TplErEntity()
{
m_data = new TplErEntityVO();
}
public TplErEntity( TplErMovEntity tplErMovEntity,
String lastAuthUserId_, Date lastAuthDate_,
String recStatCode_ )
{
m_data = new TplErEntityVO();
TplErEntityVO tplErEntityVO = ( TplErEntityVO ) m_data;
TplErMovEntityVO tplErMovEntityVO = ( TplErMovEntityVO ) tplErMovEntity.getData();
tplErEntityVO.setErNbr( tplErMovEntityVO.getErNbr() );
tplErEntityVO.setErReltnTrfInd( tplErMovEntityVO.getErReltnTrfInd() );
tplErEntityVO.setReltnEndReasCode( tplErMovEntityVO.getReltnEndReasCode() );
tplErEntityVO.setReltnEndReasText( tplErMovEntityVO.getReltnEndReasText() );
tplErEntityVO.setEquityClassCode( tplErMovEntityVO.getEquityClassCode() );
tplErEntityVO.setLastUpdDate( tplErMovEntityVO.getLastUpdDate() );
tplErEntityVO.setLastUpdUserId( tplErMovEntityVO.getLastUpdUserId() );
tplErEntityVO.setLastAuthDate( lastAuthDate_ );
tplErEntityVO.setLastAuthUserId( lastAuthUserId_ );
tplErEntityVO.setRecStatCode( recStatCode_ );
}
}
|
package com.utils.tianyi;
import java.io.IOException;
import java.io.Serializable;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.httpclient.NameValuePair;
import org.json.JSONException;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.memory.platform.common.util.HttpInvoker;
import com.memory.platform.common.util.HttpTool;
public class SMSUtils {
private static final String ACCESS_TOKEN_URL = "https://oauth.api.189.cn/emp/oauth2/v3/access_token";
private static final String SEND_SMS_URL = "http://api.189.cn/v2/emp/templateSms/sendSms";
private static final String APP_ID = "316392550000250363";
private static final String APP_SECRET = "84bb61402e3a6142c31cbe4cb37bb534";
private static final String GRANT_TYPE = "client_credentials";
private static final String TEMPLATE_ID = "91550513";
private static String getAccessToken() throws IOException, JSONException {
NameValuePair grantTypePair = new NameValuePair("grant_type",
GRANT_TYPE);
NameValuePair appIdPair = new NameValuePair("app_id", APP_ID);
NameValuePair appSecretPair = new NameValuePair("app_secret",
APP_SECRET);
String body = HttpTool.doPosts(ACCESS_TOKEN_URL, new NameValuePair[] {
grantTypePair, appIdPair, appSecretPair });
if (body != null) {
GetTokenResult result = new Gson().fromJson(body,
GetTokenResult.class);
if (result.resCode == 0) {
return result.accessToken;
}
}
return null;
}
public static boolean sendSms(String phone, String code) throws Exception {
String accessToken = getAccessToken();
if (accessToken != null) {
/*
* SimpleDateFormat dateFormat = new
* SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String timestamp =
* dateFormat.format(new Date());
*
* String templateParam = "{\"param1\":\"" + code + "\"}";
*
* NameValuePair appIdPair = new NameValuePair("app_id", APP_ID);
* NameValuePair tokenPair = new NameValuePair("access_token",
* accessToken); NameValuePair telPair = new
* NameValuePair("acceptor_tel", phone); NameValuePair
* templateIdPair = new NameValuePair("template_id", TEMPLATE_ID);
* NameValuePair templateParamPair = new
* NameValuePair("template_param", templateParam); NameValuePair
* timestampPair = new NameValuePair("timestamp", timestamp); String
* body = HttpTool .doPost(SEND_SMS_URL, new NameValuePair[] {
* appIdPair, tokenPair, telPair, templateIdPair, templateParamPair,
* timestampPair }); if (body != null) { SendSMSResult result = new
* Gson().fromJson(body, SendSMSResult.class); if (result.res_code
* == 0) { return true; } }
*/
Date date = new Date();
SimpleDateFormat dateFormat = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss");
String timestamp = dateFormat.format(date);
Gson gson = new Gson();
Map<String, String> map = new HashMap<String, String>();
// 这里存放模板参数,如果模板没有参数直接用template_param={}
map.put("param1", phone);
map.put("param2", code);
map.put("param3", "20");
String template_param = gson.toJson(map);
// String postEntity = "app_id=" + APP_ID + "&access_token="
// + accessToken + "&acceptor_tel=" + "13735571198" + "&template_id="
// + TEMPLATE_ID + "&template_param=" + template_param
// + "×tamp=" + URLEncoder.encode(timestamp, "utf-8");
String postEntity = "acceptor_tel=" + phone + "&template_id="
+ TEMPLATE_ID + "&template_param=" + template_param + "&app_id="
+ APP_ID + "&access_token=" + accessToken
+ "×tamp=" + URLEncoder.encode(timestamp, "utf-8");
String resJson = "";
String idertifier = null;
Map<String, String> map2 = null;
try {
resJson = HttpInvoker.httpPost1(SEND_SMS_URL, null, postEntity);
map2 = gson.fromJson(resJson,
new TypeToken<Map<String, String>>() {
}.getType());
idertifier = map2.get("idertifier").toString();
SendSMSResult result = new Gson().fromJson(resJson, SendSMSResult.class);
if(result.resCode == 0) {
return true;
}
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
return false;
}
public static void main(String[] args) throws Exception {
String code = String.valueOf(Math.round(Math.random() * 899999 + 100000)); // 随机生成短信验证码
boolean isSuccess = SMSUtils.sendSms("18680893391", code);
}
class GetTokenResult implements Serializable {
private static final long serialVersionUID = -6003955917559793675L;
public int resCode;
public String resMessage;
public String accessToken;
public int expiresIn;
public int getResCode() {
return resCode;
}
public void setResCode(int resCode) {
this.resCode = resCode;
}
public String getResMessage() {
return resMessage;
}
public void setResMessage(String resMessage) {
this.resMessage = resMessage;
}
public String getAccessToken() {
return accessToken;
}
public void setAccessToken(String accessToken) {
this.accessToken = accessToken;
}
public int getExpiresIn() {
return expiresIn;
}
public void setExpiresIn(int expiresIn) {
this.expiresIn = expiresIn;
}
}
class SendSMSResult implements Serializable {
private static final long serialVersionUID = 4953741204165689933L;
public int resCode;
public String resMessage;
public String idertifier;
public int getResCode() {
return resCode;
}
public void setResCode(int resCode) {
this.resCode = resCode;
}
public String getResMessage() {
return resMessage;
}
public void setResMessage(String resMessage) {
this.resMessage = resMessage;
}
public String getIdertifier() {
return idertifier;
}
public void setIdertifier(String idertifier) {
this.idertifier = idertifier;
}
}
}
|
package cn.com.finn.base.exception;
/**
*
* @author Finn Zhao
* @version 2017年5月31日
*/
public class Err {
public Err() {
}
public Err(String exceptionCode, String messageCode) {
this.exceptionCode = exceptionCode;
this.messageCode = messageCode;
}
/**
* 异常区分
*/
private String exceptionCode;
/**
* 消息Code
*/
private String messageCode;
public String getExceptionCode() {
return exceptionCode;
}
public void setExceptionCode(String exceptionCode) {
this.exceptionCode = exceptionCode;
}
public String getMessageCode() {
return messageCode;
}
public void setMessageCode(String messageCode) {
this.messageCode = messageCode;
}
/**
* static method:create instance.
*
* @param exceptionCode
* @param messageCode
* @return
*/
public static Err create(String exceptionCode, String messageCode) {
return new Err(exceptionCode, messageCode);
}
}
|
package Model;
import Client.*;
import IO.MyDecompressorInputStream;
import Server.*;
import algorithms.mazeGenerators.Maze;
import algorithms.search.*;
import javafx.scene.control.Alert;
import javafx.scene.input.KeyCode;
import java.io.*;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Observable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class MyModel extends Observable implements IModel {
//TODO - DONE
// Add Scroll with the mouse - 5 points
//TODO - DONE
// Drag the character with the mouse - 10 points
private MazeCharacter mainCharacter = new MazeCharacter("Main_",0,0);;
private MazeCharacter secondCharacter = new MazeCharacter("Second_",0,0);
private Maze maze;
private Solution mazeSolution;
private boolean isAtTheEnd;
private int[][] mazeSolutionArr;
private boolean multiPlayerMode = false;
//private String mainCharacterName = "Crash_";
//private String secondCharacterName = "Mask_";
private Server serverMazeGenerator;
private Server serverSolveMaze;
private ExecutorService threadPool = Executors.newCachedThreadPool();;
public int[][] getMazeSolutionArr() {
return mazeSolutionArr;
}
public MyModel(){
Configurations.run();
isAtTheEnd = false;
startServers();
}
private void startServers(){
serverMazeGenerator = new Server(5400, 1000, new ServerStrategyGenerateMaze());
serverSolveMaze = new Server(5401, 1000, new ServerStrategySolveSearchProblem());
serverMazeGenerator.start();
serverSolveMaze.start();
}
private void closeServers(){
serverMazeGenerator.stop();
serverSolveMaze.stop();
}
@Override
public void generateMaze(int row, int col) {
try {
Client clientMazeGenerator = new Client(InetAddress.getLocalHost(), 5400, new IClientStrategy() {
@Override
public void clientStrategy(InputStream inFromServer, OutputStream outToServer) {
try {
ObjectOutputStream toServer = new ObjectOutputStream(outToServer);
ObjectInputStream fromServer = new ObjectInputStream(inFromServer);
toServer.flush();
int[] mazeDimensions = new int[]{row, col};
toServer.writeObject(mazeDimensions); //send maze dimensions to server
toServer.flush();
byte[] compressedMaze = (byte[]) fromServer.readObject(); //read generated maze (compressed with MyCompressor) from server
InputStream is = new MyDecompressorInputStream(new ByteArrayInputStream(compressedMaze));
byte[] decompressedMaze = new byte[mazeDimensions[0] * mazeDimensions[1] + 12 /*CHANGE SIZE ACCORDING TO YOU MAZE SIZE*/]; //allocating byte[] for the decompressed maze -
is.read(decompressedMaze); //Fill decompressedMaze with bytes
maze = new Maze(decompressedMaze);
toServer.close();
fromServer.close();
} catch (Exception e) {
e.printStackTrace();
}
}
});
//threadPool.execute(() ->{
Thread t = new Thread(()->{
clientMazeGenerator.communicateWithServer();
int mazeRow = maze.getStartPosition().getRowIndex();
int mazeCol = maze.getStartPosition().getColumnIndex();
mainCharacter = new MazeCharacter("Main_",mazeRow,mazeCol);
secondCharacter = new MazeCharacter("Second_", mazeRow,mazeCol);
isAtTheEnd = false;
mazeSolutionArr = null;
setChanged();
notifyObservers("Maze");
});
t.start();
//});
//clientMazeGenerator.communicateWithServer();
} catch (UnknownHostException e) {
e.printStackTrace();
}
}
@Override
public void moveCharacter(KeyCode movement) {
mazeSolutionArr = null;
boolean legitKey = false;
int mainCharacterPositionRow = mainCharacter.getCharacterRow();
int mainCharacterPositionCol = mainCharacter.getCharacterCol();
int secondCharacterPositionRow = secondCharacter.getCharacterRow();
int secondCharacterPositionCol = secondCharacter.getCharacterCol();
switch(movement){
case UP:
case W:
case NUMPAD8:
legitKey = true;
mainCharacter.setCharacterDirection("back");
if(!multiPlayerMode)
secondCharacter.setCharacterDirection(mainCharacter.getCharacterDirection());
if(isNotWall(mainCharacterPositionRow - 1, mainCharacterPositionCol )){
if(!multiPlayerMode){
secondCharacter.setCharacterRow(mainCharacterPositionRow);
secondCharacter.setCharacterCol(mainCharacterPositionCol);
}
mainCharacter.setCharacterRow(mainCharacterPositionRow - 1);
}
break;
case DOWN:
case X:
case NUMPAD2:
legitKey = true;
mainCharacter.setCharacterDirection("front");
if(!multiPlayerMode)
secondCharacter.setCharacterDirection(mainCharacter.getCharacterDirection());
if(isNotWall(mainCharacterPositionRow + 1, mainCharacterPositionCol)) {
if(!multiPlayerMode){
secondCharacter.setCharacterRow(mainCharacterPositionRow);
secondCharacter.setCharacterCol(mainCharacterPositionCol);
}
mainCharacter.setCharacterRow(mainCharacterPositionRow + 1);
}
break;
case LEFT:
case A:
case NUMPAD4:
legitKey = true;
mainCharacter.setCharacterDirection("left");
if(!multiPlayerMode)
secondCharacter.setCharacterDirection(mainCharacter.getCharacterDirection());
if(isNotWall(mainCharacterPositionRow, mainCharacterPositionCol - 1)) {
if(!multiPlayerMode){
secondCharacter.setCharacterRow(mainCharacterPositionRow);
secondCharacter.setCharacterCol(mainCharacterPositionCol);
}
mainCharacter.setCharacterCol(mainCharacterPositionCol - 1);
}
break;
case RIGHT:
case D:
case NUMPAD6:
legitKey = true;
mainCharacter.setCharacterDirection("right");
if(!multiPlayerMode)
secondCharacter.setCharacterDirection(mainCharacter.getCharacterDirection());
if(isNotWall(mainCharacterPositionRow, mainCharacterPositionCol + 1)) {
if(!multiPlayerMode){
secondCharacter.setCharacterRow(mainCharacterPositionRow);
secondCharacter.setCharacterCol(mainCharacterPositionCol);
}
mainCharacter.setCharacterCol(mainCharacterPositionCol + 1);
}
break;
case Q:
case NUMPAD7:
legitKey = true;
mainCharacter.setCharacterDirection("left");
if(!multiPlayerMode)
secondCharacter.setCharacterDirection(mainCharacter.getCharacterDirection());
if(isNotWall(mainCharacterPositionRow - 1, mainCharacterPositionCol - 1) && (isNotWall(mainCharacterPositionRow, mainCharacterPositionCol - 1) || isNotWall(mainCharacterPositionRow - 1, mainCharacterPositionCol) )){
if(!multiPlayerMode){
secondCharacter.setCharacterRow(mainCharacterPositionRow);
secondCharacter.setCharacterCol(mainCharacterPositionCol);
}
mainCharacter.setCharacterRow(mainCharacterPositionRow - 1);
mainCharacter.setCharacterCol(mainCharacterPositionCol - 1);
}
break;
case E:
case NUMPAD9:
legitKey = true;
mainCharacter.setCharacterDirection("right");
if(!multiPlayerMode)
secondCharacter.setCharacterDirection(mainCharacter.getCharacterDirection());
if(isNotWall(mainCharacterPositionRow - 1, mainCharacterPositionCol + 1) && (isNotWall(mainCharacterPositionRow, mainCharacterPositionCol + 1) || isNotWall(mainCharacterPositionRow - 1, mainCharacterPositionCol) )){
if(!multiPlayerMode){
secondCharacter.setCharacterRow(mainCharacterPositionRow);
secondCharacter.setCharacterCol(mainCharacterPositionCol);
}
mainCharacter.setCharacterRow(mainCharacterPositionRow - 1);
mainCharacter.setCharacterCol(mainCharacterPositionCol + 1);
}
break;
case Z:
case NUMPAD1:
legitKey = true;
mainCharacter.setCharacterDirection("left");
if(!multiPlayerMode)
secondCharacter.setCharacterDirection(mainCharacter.getCharacterDirection());
if(isNotWall(mainCharacterPositionRow + 1, mainCharacterPositionCol - 1) && (isNotWall(mainCharacterPositionRow, mainCharacterPositionCol - 1) || isNotWall(mainCharacterPositionRow + 1, mainCharacterPositionCol) )){
if(!multiPlayerMode){
secondCharacter.setCharacterRow(mainCharacterPositionRow);
secondCharacter.setCharacterCol(mainCharacterPositionCol);
}
mainCharacter.setCharacterRow(mainCharacterPositionRow + 1);
mainCharacter.setCharacterCol(mainCharacterPositionCol - 1);
}
break;
case C:
case NUMPAD3:
legitKey = true;
mainCharacter.setCharacterDirection("right");
if(!multiPlayerMode)
secondCharacter.setCharacterDirection(mainCharacter.getCharacterDirection());
if(isNotWall(mainCharacterPositionRow + 1, mainCharacterPositionCol + 1) && (isNotWall(mainCharacterPositionRow, mainCharacterPositionCol + 1) || isNotWall(mainCharacterPositionRow + 1, mainCharacterPositionCol) )){
if(!multiPlayerMode){
secondCharacter.setCharacterRow(mainCharacterPositionRow);
secondCharacter.setCharacterCol(mainCharacterPositionCol);
}
mainCharacter.setCharacterRow(mainCharacterPositionRow + 1);
mainCharacter.setCharacterCol(mainCharacterPositionCol + 1);
}
break;
case H:
if(multiPlayerMode){
legitKey = true;
secondCharacter.setCharacterDirection("left");
if(isNotWall(secondCharacterPositionRow, secondCharacterPositionCol - 1)){
secondCharacter.setCharacterRow(secondCharacterPositionRow);
secondCharacter.setCharacterCol(secondCharacterPositionCol - 1);
}
}
break;
case J:
if(multiPlayerMode){
legitKey = true;
secondCharacter.setCharacterDirection("front");
if(isNotWall(secondCharacterPositionRow + 1, secondCharacterPositionCol)){
secondCharacter.setCharacterRow(secondCharacterPositionRow + 1);
secondCharacter.setCharacterCol(secondCharacterPositionCol);
}
}
break;
case U:
if(multiPlayerMode){
legitKey = true;
secondCharacter.setCharacterDirection("back");
if(isNotWall(secondCharacterPositionRow - 1, secondCharacterPositionCol)){
secondCharacter.setCharacterRow(secondCharacterPositionRow - 1);
secondCharacter.setCharacterCol(secondCharacterPositionCol);
}
}
break;
case K:
if(multiPlayerMode){
legitKey = true;
secondCharacter.setCharacterDirection("right");
if(isNotWall(secondCharacterPositionRow , secondCharacterPositionCol + 1)){
secondCharacter.setCharacterRow(secondCharacterPositionRow );
secondCharacter.setCharacterCol(secondCharacterPositionCol + 1);
}
}
break;
default:
break;
}
if(maze.getCharAt(mainCharacter.getCharacterRow(), mainCharacter.getCharacterCol()) == 'E')
isAtTheEnd = true;
if(maze.getCharAt(secondCharacter.getCharacterRow(), secondCharacter.getCharacterCol()) == 'E')
isAtTheEnd = true;
if(legitKey) {
setChanged();
notifyObservers("Character");
}
}
@Override
public void generateSolution() {
try {
Client clientSolveMaze = new Client(InetAddress.getLocalHost(), 5401, new IClientStrategy() {
@Override
public void clientStrategy(InputStream inFromServer, OutputStream outToServer) {
try {
ObjectOutputStream toServer = new ObjectOutputStream(outToServer);
ObjectInputStream fromServer = new ObjectInputStream(inFromServer);
toServer.flush();
toServer.writeObject(new Maze(maze, mainCharacter.getCharacterRow(), mainCharacter.getCharacterCol())); //send maze to server
toServer.flush();
mazeSolution = (Solution) fromServer.readObject(); //read generated maze (compressed with MyCompressor) from server
toServer.close();
fromServer.close();
} catch (Exception e) {
e.printStackTrace();
}
}
});
//threadPool.execute(()->{
Thread t = new Thread(() -> {
clientSolveMaze.communicateWithServer();
mazeSolutionArr = mazeSolution.getSolution();
setChanged();
notifyObservers("Solution");
});
t.start();
//});
//clientSolveMaze.communicateWithServer();
}catch (Exception e){
e.printStackTrace();
}
}
private boolean isNotWall(int row, int col){
char c = maze.getCharAt(row, col);
return (c == 'S' || c == '0' || c == 'E');
}
@Override
public char[][] getMaze() {
return maze.getMaze();
}
@Override
public int getMainCharacterPositionRow() {
return mainCharacter.getCharacterRow();
}
@Override
public int getMainCharacterPositionColumn() {
return mainCharacter.getCharacterCol();
}
@Override
public String getMainCharacterDirection() {
return mainCharacter.getCharacterDirection();
}
public int getSecondCharacterPositionRow() {
return secondCharacter.getCharacterRow();
}
public int getSecondCharacterPositionColumn() {
return secondCharacter.getCharacterCol();
}
public String getSecondCharacterDirection() {
return secondCharacter.getCharacterDirection();
}
@Override
public int[][] getSolution() {
return mazeSolution.getSolution();
}
@Override
public boolean isAtTheEnd() {
return isAtTheEnd;
}
@Override
public void closeModel() {
System.out.println("Close Model");
closeServers();
threadPool.shutdown();
}
@Override
public void saveOriginalMaze(File file, String name){
try {
FileOutputStream fileWriter = null;
fileWriter = new FileOutputStream(file);
ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileWriter);
MazeCharacter mazeCharacter = new MazeCharacter(name, maze.getStartPosition().getRowIndex(), maze.getStartPosition().getColumnIndex());
MazeDisplayState mazeDisplayState = new MazeDisplayState(maze, mazeCharacter);
objectOutputStream.writeObject(mazeDisplayState);
objectOutputStream.flush();
objectOutputStream.close();
fileWriter.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
@Override
public void saveCurrentMaze(File file,String name){
try {
FileOutputStream fileWriter = null;
fileWriter = new FileOutputStream(file);
ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileWriter);
Maze currentMaze = getCurrentMaze();
MazeCharacter mazeCharacter = new MazeCharacter(name, mainCharacter.getCharacterRow(), mainCharacter.getCharacterCol());
MazeDisplayState mazeDisplayState = new MazeDisplayState(currentMaze, mazeCharacter);
objectOutputStream.writeObject(mazeDisplayState);
objectOutputStream.flush();
objectOutputStream.close();
fileWriter.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
private Maze getCurrentMaze() {
try{
Maze currentMaze = new Maze(maze,mainCharacter.getCharacterRow(),mainCharacter.getCharacterCol());
return currentMaze;
}catch (Exception e){
e.printStackTrace();
}
return null;
}
public MazeCharacter getLoadedCharacter() {
return mainCharacter;
}
public void loadMaze(File file){
try{
FileInputStream fin = new FileInputStream(file);
ObjectInputStream oin = new ObjectInputStream(fin);
MazeDisplayState loadedMazeDisplayState = (MazeDisplayState) oin.readObject();
if(loadedMazeDisplayState != null) {
maze = loadedMazeDisplayState.getMaze();
mainCharacter = loadedMazeDisplayState.getMazeCharacter();
//secondCharacter = loadedMazeDisplayState.getMazeCharacter();
//secondCharacter.setCharacterName(secondCharacter.getCharacterName() + "Second_");
isAtTheEnd = false;
setChanged();
notifyObservers("Maze Load");
}
fin.close();
oin.close();
}catch (IOException | ClassNotFoundException e) {
Alert alert = new Alert(Alert.AlertType.INFORMATION);
alert.setTitle("Loaded Maze ERROR");
alert.setHeaderText("Exception caught trying to load:\n" + file.getName());
alert.setGraphic(null);
alert.setContentText("Loaded file was not a saved maze!\nPlease load the right type of file");
alert.show();
}
}
public void setMultiPlayerMode(boolean setMode){
multiPlayerMode = setMode;
}
}
|
package com.google.ar.sceneform.samples.hellosceneform.services.image_export;
import android.util.Log;
import com.google.ar.core.Anchor;
import com.google.ar.core.Plane;
import java.util.ArrayList;
import java.util.Collection;
public class PlaneAnchorsToPointsMapper {
public static Collection<Point> Map(Collection<Anchor> anchors) {
Collection<Point> points = new ArrayList<Point>();
for(Anchor anchor : anchors) {
points.add(new Point(anchor.getPose().tx(), anchor.getPose().tz(), 0.2f, 0));
}
return points;
}
}
|
/**
* Appcelerator Titanium Mobile
* Copyright (c) 2009-2011 by Appcelerator, Inc. All Rights Reserved.
* Licensed under the terms of the Apache Public License
* Please see the LICENSE included with this distribution for details.
*/
package ti.modules.titanium.ui;
import org.appcelerator.kroll.KrollDict;
import org.appcelerator.kroll.annotations.Kroll;
import org.appcelerator.titanium.TiC;
import org.appcelerator.titanium.TiContext;
import org.appcelerator.titanium.proxy.TiViewProxy;
import org.appcelerator.titanium.view.TiUIView;
import ti.modules.titanium.ui.widget.TiUIButton;
import android.app.Activity;
@Kroll.proxy(creatableInModule=UIModule.class)
@Kroll.dynamicApis(properties = {
TiC.PROPERTY_TITLE,
TiC.PROPERTY_TITLEID,
TiC.PROPERTY_COLOR,
TiC.PROPERTY_ENABLED,
TiC.PROPERTY_FONT,
TiC.PROPERTY_IMAGE,
TiC.PROPERTY_TEXT_ALIGN,
TiC.PROPERTY_VERTICAL_ALIGN
})
public class ButtonProxy extends TiViewProxy
{
public ButtonProxy(TiContext tiContext)
{
super(tiContext);
setProperty(TiC.PROPERTY_TITLE, "");
}
@Override
protected KrollDict getLangConversionTable() {
KrollDict table = new KrollDict();
table.put(TiC.PROPERTY_TITLE, TiC.PROPERTY_TITLEID);
return table;
}
@Override
public TiUIView createView(Activity activity)
{
return new TiUIButton(this);
}
}
|
package leetcode.solution;
import leetcode.struct.ListNode;
/**
* 160. 相交链表
* <p>
* https://leetcode-cn.com/problems/intersection-of-two-linked-lists/
* <p>
* 编写一个程序,找到两个单链表相交的起始节点。
* <p>
* 输入:intersectVal = 8, listA = [4,1,8,4,5], listB = [5,0,1,8,4,5], skipA = 2, skipB = 3
* 输出:Reference of the node with value = 8
* 输入解释:相交节点的值为 8 (注意,如果两个链表相交则不能为 0)。从各自的表头开始算起,链表 A 为 [4,1,8,4,5],链表 B 为 [5,0,1,8,4,5]。在 A 中,相交节点前有 2 个节点;在 B 中,相交节点前有 3 个节点。
* <p>
* 注意:
* <p>
* 如果两个链表没有交点,返回 null.
* 在返回结果后,两个链表仍须保持原有的结构。
* 可假定整个链表结构中没有循环。
* 程序尽量满足 O(n) 时间复杂度,且仅用 O(1) 内存。
* <p>
* Solution: 一开始想到用哈希表,遍历A中每一个放入哈希表,如果B中有相同地址元素就是交点,但是空间复杂度为O(n)
* 参考题解,使用双指针法,相当于将两个链表拼起来分别遍历,两个指针相遇就是交点,比如:
* 两个链表 1-2-3-4-5 和 8-9-4-5
* 1-2-3-4-5-null-8-9-4-5-null
* 8-9-4-5-null-1-2-3-4-5-null
*/
public class Solution160 {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
if (headA == null || headB == null) {
return null;
}
ListNode a = headA;
ListNode b = headB;
while (a != b) {
a = a == null ? headB : a.next;
b = b == null ? headA : b.next;
}
return a;
}
public static void main(String[] args) {
ListNode a = ListNode.create(2);
ListNode ah = a;
ListNode b = ListNode.create(7, 6);
ListNode bh = b;
ListNode c = ListNode.create(1, 2);
while (a.next != null) {
a = a.next;
}
while (b.next != null) {
b = b.next;
}
a.next = c;
b.next = c;
Solution160 solution160 = new Solution160();
solution160.getIntersectionNode(ah, bh).print();
}
}
|
package walmartHomepage;
public class ItemPricelimit {
}
|
package pro.likada.dao;
import pro.likada.model.AddressBuildingType;
import java.util.List;
/**
* Created by bumur on 05.01.2017.
*/
public interface AddressBuildingTypeDAO {
List<AddressBuildingType> getAllAddressBuildingTypes();
}
|
package p0010;
public class Chien extends Animal
{
public Chien(String nom)
{
super(nom);
}
public void faireLeBeau()
{
System.out.printf("%s se met sur les pattes arrières et fait le beau, arf\n", getNom());
}
}
|
package com.lesports.albatross.fragment;
import android.os.Bundle;
import android.text.format.DateUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ListView;
import android.widget.TextView;
import com.google.gson.reflect.TypeToken;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.lesports.albatross.Constants;
import com.lesports.albatross.R;
import com.lesports.albatross.adapter.learn.LearningMainAdapter;
import com.lesports.albatross.adapter.learn.LearningMainAlbumAdapter;
import com.lesports.albatross.entity.CommonEntity;
import com.lesports.albatross.entity.HttpRespNorlistEntity;
import com.lesports.albatross.entity.HttpRespObjectEntity;
import com.lesports.albatross.entity.learn.BannerEntity;
import com.lesports.albatross.entity.learn.ParamsTitleEntity;
import com.lesports.albatross.entity.learn.TeachingAlbumEntity;
import com.lesports.albatross.entity.learn.TeachingEntity;
import com.lesports.albatross.json.GsonHelper;
import com.lesports.albatross.utils.LogUtil;
import com.lesports.albatross.utils.NetworkUtil;
import com.lesports.albatross.utils.SpFileUtil;
import com.lesports.albatross.utils.StringUtils;
import com.lesports.albatross.utils.UIUtils;
import com.lesports.albatross.utils.Utils;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;
import java.util.List;
import it.sephiroth.android.library.widget.AdapterView;
import it.sephiroth.android.library.widget.HListView;
/**
* 乐学
* Created by Andye on 16/6/13.
*/
public class LearningFragment extends BannerViewPageFragment implements AdapterView.OnItemClickListener {
PullToRefreshListView pullToRefreshListView;
private int Page = 0, Size = 10;
private boolean isMore = false;
LearningMainAdapter mainAdapter;
LearningMainAlbumAdapter albumAdapter;
TextView tv_type_1;
TextView tv_type_2;
@Override
public View viewBindLayout(LayoutInflater inflater) {
return inflater.inflate(R.layout.fragment_learning, null);
}
@Override
public void viewBindId(View view) {
InitView(view);
}
@Override
public void resourcesInit(Bundle data) {
}
@Override
public void viewInit(LayoutInflater inflater) {
}
@Override
public void viewBindListener() {
}
private void InitView(View view) {
pullToRefreshListView = (PullToRefreshListView) view.findViewById(R.id.layout_main_listview);
//-----------header----------------
View main_headerview = LayoutInflater.from(getActivity()).inflate(R.layout.learn_main_headerview, null);
initBanner(main_headerview);
HListView layout_hlistview = (HListView) main_headerview.findViewById(R.id.layout_hlistview);
tv_type_1 = (TextView) main_headerview.findViewById(R.id.tv_type_1);
tv_type_2 = (TextView) main_headerview.findViewById(R.id.tv_type_2);
albumAdapter = new LearningMainAlbumAdapter(getActivity());
layout_hlistview.setAdapter(albumAdapter);
layout_hlistview.setOnItemClickListener(this);
//---------------------------
mainAdapter = new LearningMainAdapter(getActivity());
pullToRefreshListView.setAdapter(mainAdapter);
pullToRefreshListView.setShowIndicator(false);
pullToRefreshListView.setPullToRefreshOverScrollEnabled(false);
pullToRefreshListView.setMode(PullToRefreshBase.Mode.BOTH);
Utils.setPullToRefreshIndicator(pullToRefreshListView);
pullToRefreshListView.requestFocus();
pullToRefreshListView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
@Override
public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
String label = DateUtils.formatDateTime(getActivity(), System.currentTimeMillis(),
DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_ABBREV_ALL);
try {
getLearningAlbumData();
} catch (Exception e) {
e.printStackTrace();
}
label = "上次更新于" + label;
refreshView.getLoadingLayoutProxy().setLastUpdatedLabel(label);
Page = 0;
isMore = false;
try {
getParamsTitleData();
getFocusImageData();
getLearningData();
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
isMore = true;
Page++;
try {
getLearningData();
} catch (Exception e) {
e.printStackTrace();
}
}
});
pullToRefreshListView.setRefreshing(true);
pullToRefreshListView.getRefreshableView().addHeaderView(main_headerview);
}
/**
* 获取焦点图的数据
*/
public void getFocusImageData() {
RequestParams params = new RequestParams(Constants.LEARNING_FOCUS_IMAGE_URL);
params.setAsJsonContent(true);
x.http().get(params, new Callback.CacheCallback<String>() {
private boolean hasError = false;
private String result = null;
@Override
public void onSuccess(String result) {
Page++;
if (result != null) {
this.result = result;
}
}
@Override
public void onError(Throwable ex, boolean isOnCallback) {
if (!NetworkUtil.isNetworkConnected(getActivity())) {
UIUtils.showToast(getActivity(), getResources().getString(R.string.network_unreachable_title));
}
}
@Override
public void onCancelled(CancelledException cex) {
if (null != pullToRefreshListView) {
pullToRefreshListView.onRefreshComplete();
}
}
@Override
public void onFinished() {
if (!hasError && result != null) {
try {
showBannerData(result);
} catch (Exception e) {
e.printStackTrace();
}
}
if (null != pullToRefreshListView) {
pullToRefreshListView.postDelayed(new Runnable() {
@Override
public void run() {
if (null != pullToRefreshListView) {
pullToRefreshListView.onRefreshComplete();
}
}
}, 200);
}
}
@Override
public boolean onCache(String result) {
this.result = result;
return true;
}
});
}
/**
* 获取标题配置的数据
*/
public void getParamsTitleData() {
RequestParams params = new RequestParams(Constants.BASE_PARAMS_TITLE_URL);
params.setAsJsonContent(true);
x.http().get(params, new Callback.CacheCallback<String>() {
@Override
public void onSuccess(String result) {
try {
if (StringUtils.isNotEmpty(result)) {
SpFileUtil.saveString(getActivity(), SpFileUtil.FILE_PARAMS_DATA, SpFileUtil.KEY_PARAMS_TITLE, result);
showTitleData(result);
// if (null != mainAdapter) {
// mainAdapter.showTitleData(result);
// showTitleData(result);
// }
}
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void onError(Throwable ex, boolean isOnCallback) {
// if (null != mainAdapter) {
// mainAdapter.showTitleData(null);
// }
String titleDatas = SpFileUtil.getString(getActivity(), SpFileUtil.FILE_PARAMS_DATA, SpFileUtil.KEY_PARAMS_TITLE, "");
showTitleData(titleDatas);
}
@Override
public void onCancelled(CancelledException cex) {
if (null != pullToRefreshListView) {
pullToRefreshListView.onRefreshComplete();
}
}
@Override
public void onFinished() {
if (null != pullToRefreshListView) {
pullToRefreshListView.postDelayed(new Runnable() {
@Override
public void run() {
if (null != pullToRefreshListView) {
pullToRefreshListView.onRefreshComplete();
}
}
}, 200);
}
}
@Override
public boolean onCache(String result) {
return false;
}
});
}
/**
* 获取learn的数据
*/
public void getLearningData() {
RequestParams params = new RequestParams(Constants.LEARNING_TEACH_LIST);
params.setAsJsonContent(true);
params.setCacheMaxAge(1000 * 300);
params.addParameter("page", Page);
params.addParameter("size", Size);
x.http().get(params, new Callback.CacheCallback<String>() {
private boolean hasError = false;
private String result = null;
@Override
public void onSuccess(String result) {
if (result != null) {
LogUtil.i("on online data");
this.result = result;
}
}
@Override
public void onError(Throwable ex, boolean isOnCallback) {
}
@Override
public void onCancelled(CancelledException cex) {
if (null != pullToRefreshListView) {
pullToRefreshListView.onRefreshComplete();
}
}
@Override
public void onFinished() {
try {
if (StringUtils.isNotEmpty(result)) {
showLearningData(result);
}
} catch (Exception e) {
e.printStackTrace();
}
if (null != pullToRefreshListView) {
pullToRefreshListView.postDelayed(new Runnable() {
@Override
public void run() {
if (null != pullToRefreshListView) {
pullToRefreshListView.onRefreshComplete();
}
}
}, 200);
}
}
@Override
public boolean onCache(String result) {
this.result = result;
return true;
}
});
}
/**
* 获取Album的数据
*/
public void getLearningAlbumData() {
RequestParams params = new RequestParams(Constants.LEARNING_TEACH_ALBUM_LIST);
params.setAsJsonContent(true);
params.setCacheMaxAge(1000 * 300);
params.addParameter("page", "0");
params.addParameter("size", "15");
x.http().get(params, new Callback.CacheCallback<String>() {
private boolean hasError = false;
private String result = null;
@Override
public void onSuccess(String result) {
if (result != null) {
LogUtil.i("on online data");
this.result = result;
}
}
@Override
public void onError(Throwable ex, boolean isOnCallback) {
}
@Override
public void onCancelled(CancelledException cex) {
if (null != pullToRefreshListView) {
pullToRefreshListView.onRefreshComplete();
}
}
@Override
public void onFinished() {
if (!hasError && result != null) {
try {
if (StringUtils.isNotEmpty(result)) {
showLearningAlbumData(result);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
@Override
public boolean onCache(String result) {
this.result = result;
return true;
}
});
}
/**
* banner数据
*
* @param datas
*/
public void showBannerData(String datas) {
try {
if (StringUtils.isNotEmpty(datas)) {
HttpRespNorlistEntity<BannerEntity> bannerEntity = GsonHelper.fromJson(datas, new TypeToken<HttpRespNorlistEntity<BannerEntity>>() {
}.getType());
if (bannerEntity != null) {
updateViewPager(bannerEntity.getData());
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
pullToRefreshListView.postDelayed(new Runnable() {
@Override
public void run() {
if (null != pullToRefreshListView) {
pullToRefreshListView.onRefreshComplete();
}
}
}, 200);
}
}
/**
* title数据
*
* @param datas
*/
public void showTitleData(String datas) {
try {
if (StringUtils.isNotEmpty(datas)) {
HttpRespNorlistEntity<ParamsTitleEntity> paramsTitleEntity = GsonHelper.fromJson(datas, new TypeToken<HttpRespNorlistEntity<ParamsTitleEntity>>() {
}.getType());
for (ParamsTitleEntity titleEntity : paramsTitleEntity.getData()) {
if (titleEntity.getParamName().equals("ALBUM")) {
// learning_title_album = new InnerHeader(titleEntity.getId(), titleEntity.getParamValue());
tv_type_1.setText(titleEntity.getParamValue());
} else if (titleEntity.getParamName().equals("TEACHING_LIST")) {
tv_type_2.setText(titleEntity.getParamValue());
// learning_title_teaching_list = new InnerHeader(titleEntity.getId(), titleEntity.getParamValue());
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 乐学数据
*
* @param datas
*/
public void showLearningData(String datas) {
try {
if (StringUtils.isNotEmpty(datas)) {
HttpRespObjectEntity<CommonEntity<TeachingEntity>> teachEntity = GsonHelper.fromJson(datas, new TypeToken<HttpRespObjectEntity<CommonEntity<TeachingEntity>>>() {
}.getType());
List<TeachingEntity> teachingEntities = teachEntity.getData().getContent();
if (null != teachingEntities && teachingEntities.size() > 0) {
if (isMore)
mainAdapter.addData(teachEntity.getData().getContent());
else
mainAdapter.updateData(teachEntity.getData().getContent());
} else {
UIUtils.showToast(getActivity(), R.string.no_more_data);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 乐学推荐数据
*
* @param datas
*/
public void showLearningAlbumData(String datas) {
try {
if (StringUtils.isNotEmpty(datas)) {
HttpRespObjectEntity<CommonEntity<TeachingAlbumEntity>> teachEntity = GsonHelper.fromJson(datas, new TypeToken<HttpRespObjectEntity<CommonEntity<TeachingAlbumEntity>>>() {
}.getType());
if (null != teachEntity) {
albumAdapter.updateData(teachEntity.getData().getContent());
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
pullToRefreshListView.postDelayed(new Runnable() {
@Override
public void run() {
pullToRefreshListView.onRefreshComplete();
}
}, 200);
}
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
UIUtils.showToast(getActivity(), "当前位置:" + position);
}
}
|
/******************************************************************************
* __ *
* <-----/@@\-----> *
* <-< < \\// > >-> *
* <-<-\ __ /->-> *
* Data / \ Crow *
* ^ ^ *
* info@datacrow.net *
* *
* This file is part of Data Crow. *
* Data Crow is free software; you can redistribute it and/or *
* modify it under the terms of the GNU General Public *
* License as published by the Free Software Foundation; either *
* version 3 of the License, or any later version. *
* *
* Data Crow is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public *
* License along with this program. If not, see http://www.gnu.org/licenses *
* *
******************************************************************************/
package net.datacrow.core.db;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Types;
import net.datacrow.core.DataCrow;
import net.datacrow.core.DcRepository;
import net.datacrow.core.Version;
import net.datacrow.core.modules.DcModule;
import net.datacrow.core.modules.DcModules;
import net.datacrow.core.objects.DcField;
import net.datacrow.core.objects.DcObject;
import net.datacrow.core.resources.DcResources;
import net.datacrow.core.security.SecurityCentre;
import net.datacrow.core.upgrade.SystemUpgradeAfterInitialization;
import net.datacrow.core.upgrade.SystemUpgradeBeforeInitialization;
import net.datacrow.settings.DcSettings;
import org.apache.log4j.Logger;
/**
* Manages the Data Crow database. Is responsible for executing queries and
* database maintenance (upgrading).
*
* @author Robert Jan van der Waals
*/
public class DcDatabase {
private static Logger logger = Logger.getLogger(DcDatabase.class.getName());
private QueryQueue queue;
private Version originalVersion;
private Conversions conversions = new Conversions();
public DcDatabase() {}
protected Conversions getConversions() {
return conversions;
}
/**
* The version from before the upgrade.
*/
protected Version getOriginalVersion() {
return originalVersion;
}
/**
* Retrieves the current version of the database. In case the database does not have
* a version number asigned an undetermined version number is returned.
* @param connection
*/
protected Version getVersion(Connection connection) {
int major = 0;
int minor = 0;
int build = 0;
int patch = 0;
try {
if (connection != null) {
Statement stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM VERSION");
while (rs.next()) {
major = rs.getInt("major");
minor = rs.getInt("minor");
build = rs.getInt("build");
patch = rs.getInt("patch");
}
rs.close();
stmt.close();
}
} catch (SQLException se) {}
return new Version(major, minor, build, patch);
}
public boolean isNew() {
return getVersion(DatabaseManager.getConnection()).equals(new Version(0, 0, 0, 0));
}
private void updateVersion(Connection connection) throws SQLException {
Version v = DataCrow.getVersion();
Statement stmt = connection.createStatement();
stmt.execute("DELETE FROM VERSION");
stmt.execute("INSERT INTO VERSION(MAJOR, MINOR, BUILD, PATCH) VALUES (" +
v.getMajor() + "," + v.getMinor() + "," + v.getBuild() + "," + v.getPatch() + ")");
stmt.close();
}
/**
* Initializes the database. Upgrades are performed automatically; missing columns are added
* and missing tables are created.
*
* @param connection
* @throws Exception
*/
@SuppressWarnings("resource")
protected void initiliaze() throws Exception {
Connection connection = DatabaseManager.getAdminConnection();
if (!isNew())
new SystemUpgradeBeforeInitialization().start();
startQueryQueue();
initialize(connection);
setDbProperies(connection);
if (!isNew())
new SystemUpgradeAfterInitialization().start();
originalVersion = getVersion(connection);
updateVersion(connection);
// Set the database privileges for the current user. This avoids errors for upgraded modules and such.
DatabaseManager.setPriviliges(SecurityCentre.getInstance().getUser().getUser());
DatabaseManager.setPriviliges("DC_ADMIN", true);
}
/**
* Removes unused columns.
*/
protected void cleanup() {
// As we might still need the info during the upgrade.....
// we'll clean this all up after the database has been upgraded!
if (DataCrow.getVersion().isNewer(DatabaseManager.getOriginalVersion()))
return;
String sql;
ResultSet rs = null;
ResultSetMetaData md;
String columnName;
boolean remove;
for (DcModule module : DcModules.getAllModules()) {
if (module.isAbstract()) continue;
try {
sql = "select top 1 * from " + module.getTableName();
rs = DatabaseManager.executeSQL(sql);
md = rs.getMetaData();
for (int i = 1; i < md.getColumnCount() + 1; i++) {
columnName = md.getColumnName(i);
remove = false;
if (!columnName.startsWith("KEEP_ME_")) {
for (DcField field : module.getFields()) {
if (columnName.equalsIgnoreCase(field.getDatabaseFieldName()))
remove = field.getValueType() == DcRepository.ValueTypes._DCOBJECTCOLLECTION ? true : false;
}
// the column is not used.. remove!
if (remove) {
logger.info("Removing column " + columnName + " for module " + module.getName() + " as it is no longer in use");
DatabaseManager.execute("alter table " + module.getTableName() + " drop column " + columnName);
}
}
}
} catch (Exception e) {
logger.error("Error while trying to cleanup unused columns", e);
} finally {
try {
if (rs != null) rs.close();
} catch (Exception e) {
logger.debug("Error while closing database resources", e);
}
}
}
}
/**
* Returns the current count of queries waiting in the queue.
*/
protected int getQueueSize() {
return queue.getQueueSize();
}
private void startQueryQueue() {
queue = new QueryQueue();
Thread queryQueue = new Thread(queue, "queryQueue");
queryQueue.setPriority(Thread.NORM_PRIORITY);
queryQueue.setDaemon(true);
queryQueue.start();
}
/**
* Returns the name of the database.
*/
protected String getName() {
return DcSettings.getString(DcRepository.Settings.stConnectionString);
}
/**
* Adds a query to the query queue of this database.
* @param query
*/
protected void queue(Query query) {
queue.addQuery(query);
}
/**
* Applies the default settings on the database.
* @param connection
*/
protected void setDbProperies(Connection connection) {
try {
Statement stmt = connection.createStatement();
//stmt.execute("SET SCRIPTFORMAT COMPRESSED");
//int cacheScale = DcSettings.getInt(DcRepository.Settings.stHsqlCacheScale);
//int cacheSizeScale = DcSettings.getInt(DcRepository.Settings.stHsqlCacheSizeScale);
//stmt.execute("SET PROPERTY \"hsqldb.cache_scale\" " + cacheScale);
//stmt.execute("SET PROPERTY \"hsqldb.cache_size_scale\" " + cacheSizeScale);
stmt.execute("SET FILES SCRIPT FORMAT COMPRESSED");
stmt.close();
} catch (Exception e) {
logger.error(DcResources.getText("msgUnableToChangeDbSettings"), e);
}
}
private void initialize(Connection connection) throws Exception {
Statement stmt = connection.createStatement();
initializeSystemTable(stmt);
String testQuery;
ResultSet rs = null;
for (DcModule module : DcModules.getAllModules()) {
if (!module.isAbstract()) {
testQuery = "select * from " + module.getTableName();
try {
stmt.setMaxRows(1);
rs = stmt.executeQuery(testQuery);
initializeColumns(connection, rs.getMetaData(), module);
logger.debug(DcResources.getText("msgTableFound", module.getTableName()));
} catch (SQLException e) {
logger.info((DcResources.getText("msgTableNotFound", module.getTableName())));
createTable(module);
} finally {
try {
if (rs != null) rs.close();
} catch (Exception e) {
logger.debug("Failed to close ResultSet", e);
}
}
}
}
stmt.close();
}
private void initializeSystemTable(Statement stmt) {
try {
stmt.execute("SELECT * FROM VERSION");
} catch (Exception e) {
try {
stmt.execute("CREATE TABLE VERSION (Major " + DcRepository.Database._FIELDBIGINT + "," +
"Minor " + DcRepository.Database._FIELDBIGINT + "," +
"Build " + DcRepository.Database._FIELDBIGINT + "," +
"Patch " + DcRepository.Database._FIELDBIGINT + ")");
} catch (SQLException se) {
logger.error("Could not create the version table!", se);
}
}
}
private void initializeColumns(Connection connection, ResultSetMetaData metaData, DcModule module) throws SQLException {
String tablename = module.getTableName();
String column;
String type;
boolean found;
boolean convert;
int dbSize;
int dbType;
for (DcField field : module.getFields()) {
column = field.getDatabaseFieldName();
type = field.getDataBaseFieldType();
found = false;
convert = false;
if (!field.isUiOnly()) {
for (int i = 1; i < metaData.getColumnCount() + 1; i++) {
if (metaData.getColumnName(i).equalsIgnoreCase(column)) {
found = true;
dbSize = metaData.getColumnDisplaySize(i);
dbType = metaData.getColumnType(i);
convert = false;
if ( dbType == Types.BIGINT &&
(field.getValueType() == DcRepository.ValueTypes._DCPARENTREFERENCE ||
field.getValueType() == DcRepository.ValueTypes._DCOBJECTREFERENCE ||
field.getIndex() == DcObject._ID))
convert = true;
else if (dbSize < field.getMaximumLength() &&
(field.getValueType() == DcRepository.ValueTypes._STRING))
convert = true;
if (convert) {
logger.info(DcResources.getText("msgTableUpgradeIncorrectColumn", new String[] {tablename, field.getLabel()}));
executeQuery(connection, "alter table " + tablename + " alter column " + column + " " + type);
}
}
}
}
if (!field.isUiOnly() && !found) {
logger.info(DcResources.getText("msgTableUpgradeMissingColumn", new String[] {tablename, field.getLabel()}));
executeQuery(DatabaseManager.getAdminConnection(), "alter table " + tablename + " add column " + column + " " + type);
}
}
}
private void executeQuery(Connection connection, String sql) {
try {
executeQuery(connection.prepareStatement(sql));
} catch (Exception e) {
logger.error("Error while executing query " + sql, e);
}
}
private void executeQuery(PreparedStatement ps) {
try {
ps.execute();
logger.info(ps);
ps.close();
} catch (Exception e) {
logger.error("Error while executing query " + ps, e);
}
}
private void createTable(DcModule module) {
try {
Query query = new CreateQuery(module.getIndex());
query.run();
module.setNew(true);
} catch (Exception e) {
logger.error("An error occurred while inserting demo data", e);
}
}
}
|
import java.sql.SQLException;
import javafx.scene.Scene;
import javafx.scene.control.Menu;
import javafx.scene.control.MenuBar;
import javafx.scene.control.MenuItem;
import javafx.scene.control.Tab;
import javafx.scene.control.TabPane;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class GUI {
// Database
private Database db;
// Scene
private Scene scene;
// "Root"
private VBox vBox;
// Tab objects
public TabCreatePallet tabCreatePallet;
private TabRegisterPallet tabRegisterPallet;
private TabSearchPallet tabSearchPallet;
private TabBlockPallet tabBlockPallet;
// Layout properties
private final int GAP = 10;
private final int PADDING = 15;
// Menu bar
private MenuBar menuBar;
public GUI(Stage primaryStage, Database db) throws SQLException {
this.db = db;
startDB();
// "Root"
vBox = new VBox();
// Initialize menu bar and tabs
initializeMenuBar(primaryStage);
initializeTabs(primaryStage);
// Scene
scene = new Scene(vBox, 900, 600); // Arbitrary integers
}
private void initializeMenuBar(Stage primaryStage) {
// MenuBar
menuBar = new MenuBar();
vBox.getChildren().add(menuBar);
// Menu 1
Menu menu1 = new Menu("File");
MenuItem menu1Item1 = new MenuItem("Exit");
menu1Item1.setOnAction(e -> exit());
menu1.getItems().add(menu1Item1);
// Add menus to the menu bar
menuBar.getMenus().add(menu1);
}
private void exit() {
db.closeConnection();
System.exit(0);
}
private void initializeTabs(Stage primaryStage) {
// TabPane
TabPane tabPane = new TabPane();
vBox.getChildren().add(tabPane);
// Tabs
Tab tab1 = new Tab("Produce pallet");
Tab tab2 = new Tab("Search pallet");
Tab tab3 = new Tab("Block pallets");
tabPane.getTabs().add(tab1);
tabPane.getTabs().add(tab2);
tabPane.getTabs().add(tab3);
// Tab configurations
tab1.setClosable(false);
tab2.setClosable(false);
tab3.setClosable(false);
// Tab objects and tab content
tabCreatePallet = new TabCreatePallet(GAP, PADDING, db, primaryStage);
tab1.setContent(tabCreatePallet.hBox);
tab1.setOnSelectionChanged(e -> tabCreatePallet.restoreInvalidInputs());
tabSearchPallet = new TabSearchPallet(GAP, PADDING, db);
tab2.setContent(tabSearchPallet.hBox);
tab2.setOnSelectionChanged(e -> {
tabSearchPallet.restoreInvalidInputs();
tabSearchPallet.clearTextFields();
});
tabBlockPallet = new TabBlockPallet(GAP, PADDING, db);
tab3.setContent(tabBlockPallet.hBox);
tab3.setOnSelectionChanged(e -> {
if (tab3.isSelected()) {
tabBlockPallet.addAllBlockedPalletsToTable();
}
tabBlockPallet.restoreInvalidInputs();
tabBlockPallet.clearTextFields();
});
}
private void startDB() throws SQLException {
if (db.openConnection("cookies.db")) {
System.out.println("Database connected");
db.foreignKey();
} else {
System.out.println("Database not connected");
System.exit(0);
}
}
public Scene getScene() {
return scene;
}
}
|
package com.example.bigdata.service;
import com.example.bigdata.jdbc.TestJDBC;
import org.springframework.stereotype.Service;
@Service
public class CreateScreenService {
public void createScreen() {
TestJDBC jdbc = new TestJDBC();
jdbc.createScreen();
}
}
|
/*
* 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 domain;
import java.sql.PreparedStatement;
import java.util.Objects;
/**
*
* @author Mihailo
*/
public class MovieGenre implements GenericEntity{
private Genre genre;
private Movie movie;
public MovieGenre() {
}
public MovieGenre(Genre genre, Movie movie) {
this.genre = genre;
this.movie = movie;
}
public Genre getGenre() {
return genre;
}
public void setGenre(Genre genre) {
this.genre = genre;
}
public Movie getMovie() {
return movie;
}
public void setMovie(Movie movie) {
this.movie = movie;
}
@Override
public int hashCode() {
int hash = 5;
hash = 97 * hash + Objects.hashCode(this.genre);
hash = 97 * hash + Objects.hashCode(this.movie);
return hash;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final MovieGenre other = (MovieGenre) obj;
if (!Objects.equals(this.genre, other.genre)) {
return false;
}
if (!Objects.equals(this.movie, other.movie)) {
return false;
}
return true;
}
@Override
public String toString() {
return "MovieGenre{" + "genre=" + genre + ", movie=" + movie + '}';
}
@Override
public String getTableName() {
return "movie_genre";
}
@Override
public String getColumnNamesForInsert() {
return "genreID, movieID";
}
@Override
public void getInsertValues(PreparedStatement statement) throws Exception{
statement.setLong(1, genre.getGenreID());
statement.setLong(2, movie.getMovieID());
}
@Override
public void setId(Long id) {
}
@Override
public int getColumnCount() {
return 2;
}
@Override
public String getColumnNamesForUpdate() {
return "";
}
@Override
public String getConditionForUpdate() {
return "";
}
@Override
public String getConditionForDelete() {
return "movieID = " + movie.getMovieID();
}
@Override
public String getColumnNamesForSelect() {
return "g.name as gname, g.genreID as ggenreID ";
}
@Override
public String getTableForSelect() {
return "movie m JOIN movie_genre mg ON (m.movieID = mg.movieID) "
+ "JOIN genre g ON (mg.genreID = g.genreID)";
}
@Override
public String getConditionForSelect() {
return "mg.movieID = " + movie.getMovieID();
}
@Override
public String getConditionForSelectSpecific() {
return "";
}
@Override
public String getAdditionalQueries() {
return "";
}
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.xag.util;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class SendMailTLS {
private static final String username = "yolojeya@gmail.com";
private static final String password = "pzpoaarxutxasluw";
private static final Logger log = LoggerFactory.getLogger(MailObject.class);
public static boolean sendMail(MailObject mo) {
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", "587");
Session session = Session.getInstance(props,
new javax.mail.Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(username));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(mo.getTo()));
message.setSubject(mo.getMessageSubject());
message.setText(mo.getMessageBody());
Transport.send(message);
log.info("Mail sent!");
return true;
} catch (MessagingException e) {
log.error("Mail sending failed: " + e.getMessage());
return false;
}
}
}
|
import java.util.Scanner;
public class Problem4 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
//adds users number to array
System.out.print("Enter list: ");
int length = input.nextInt();
int[] list = new int[length];
for(int i = 1; i < list.length; i++){
list[i] = input.nextInt();
}
//if true, print is sorted, if false, print is not sorted
if (isSorted(list) == true){
System.out.print("The list is sorted");
} else {
System.out.print("The list is not sorted");
}
}
public static boolean isSorted(int[] list){
boolean sort = false;
for(int i = 0; i <= list.length; i++){
for(int j = 1; j + i < list.length; j++){
//if the list doesn't need to be rearranged, sort is true
if(list[i] < list[i + j]){ // JA: This should be <= to account for repeated numbers
sort = true;
//if it does, sort is false
} else {
sort = false;
return false;
}
}
}
if(sort == true){
return true;
} else {
return false;
}
}
}
|
package com.example.demo.service;
import com.example.demo.dto.integration.IntegrationDto;
/**
* @author songjuxing
*/
public interface IntegrationManager {
/**
* 服务编排
* @param dto 服务请求对象
* @param <T> 所有服务请求与返回继承于IntegrationDto一个基类
* @return 服务返回对象
* @throws Exception 服务异常
*/
<T extends IntegrationDto> T execute(T dto) throws Exception;
}
|
package view;
import java.awt.EventQueue;
import javax.swing.JInternalFrame;
import javax.swing.JPanel;
import javax.swing.border.TitledBorder;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import java.awt.Font;
import java.beans.PropertyVetoException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Vector;
import javax.swing.JTextField;
import javax.swing.JComboBox;
import javax.swing.JButton;
import javax.swing.JScrollPane;
import java.awt.Color;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import Dao.CostumeDao;
import bean.Costume;
import util.DbUtil;
import util.FormatUtil;
import javax.swing.border.EtchedBorder;
import javax.swing.JTextArea;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.DefaultComboBoxModel;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public class maintainCostumeInterFrame extends JInternalFrame {
private JTextField s_costumeNameTxt;
private JTextField s_brandTxt;
private JTextField s_sourceTxt;
private JTextField s_costumeTypeTxt;
private JTextField s_minPriceTxt;
private JTextField s_maxPriceTxt;
private JTable costumeTable;
private JTable costumeInfoTable;
private JTextField costumeIdTxt;
private JTextField costumeNameTxt;
private JTextField brandTxt;
private JTextField sourceTxt;
private JTextField costumeTypeTxt;
private JTextField priceTxt;
private CostumeDao costumeDao = new CostumeDao();
private JLabel countLabel;
private JComboBox orderJcb;
private JTextArea describeTxt;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
maintainCostumeInterFrame frame = new maintainCostumeInterFrame();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public maintainCostumeInterFrame() {
setTitle("服装信息维护");
setIconifiable(true);
setClosable(true);
setBounds(100, 100, 1004, 637);
getContentPane().setLayout(null);
JPanel panel = new JPanel();
panel.setLayout(null);
panel.setBorder(new TitledBorder(new EtchedBorder(EtchedBorder.LOWERED, new Color(255, 255, 255), new Color(160, 160, 160)), "服装信息查询", TitledBorder.LEADING, TitledBorder.TOP, null, new Color(0, 0, 0)));
panel.setBounds(10, 10, 718, 353);
getContentPane().add(panel);
JLabel l1 = new JLabel("名称:");
l1.setFont(new Font("黑体", Font.PLAIN, 16));
l1.setBounds(21, 62, 48, 15);
panel.add(l1);
s_costumeNameTxt = new JTextField();
s_costumeNameTxt.setFont(new Font("黑体", Font.PLAIN, 16));
s_costumeNameTxt.setColumns(10);
s_costumeNameTxt.setBounds(66, 57, 107, 27);
panel.add(s_costumeNameTxt);
JLabel l2 = new JLabel("品牌:");
l2.setFont(new Font("黑体", Font.PLAIN, 16));
l2.setBounds(183, 64, 48, 15);
panel.add(l2);
s_brandTxt = new JTextField();
s_brandTxt.setFont(new Font("黑体", Font.PLAIN, 16));
s_brandTxt.setColumns(10);
s_brandTxt.setBounds(227, 57, 96, 27);
panel.add(s_brandTxt);
JLabel l3 = new JLabel("产地:");
l3.setFont(new Font("黑体", Font.PLAIN, 16));
l3.setBounds(333, 64, 48, 15);
panel.add(l3);
s_sourceTxt = new JTextField();
s_sourceTxt.setFont(new Font("黑体", Font.PLAIN, 16));
s_sourceTxt.setColumns(10);
s_sourceTxt.setBounds(377, 57, 96, 27);
panel.add(s_sourceTxt);
JLabel l4 = new JLabel("服装类型:");
l4.setFont(new Font("黑体", Font.PLAIN, 16));
l4.setBounds(483, 58, 80, 22);
panel.add(l4);
s_costumeTypeTxt = new JTextField();
s_costumeTypeTxt.setFont(new Font("黑体", Font.PLAIN, 16));
s_costumeTypeTxt.setColumns(10);
s_costumeTypeTxt.setBounds(558, 56, 96, 27);
panel.add(s_costumeTypeTxt);
JButton searchBtn = new JButton("查询");
searchBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
searchActionPerformed(e);
}
});
searchBtn.setFont(new Font("黑体", Font.PLAIN, 15));
searchBtn.setBounds(584, 93, 70, 27);
panel.add(searchBtn);
JLabel l6 = new JLabel("最小单价:");
l6.setFont(new Font("黑体", Font.PLAIN, 16));
l6.setBounds(183, 99, 80, 15);
panel.add(l6);
s_minPriceTxt = new JTextField();
s_minPriceTxt.setFont(new Font("苹方 特粗", Font.PLAIN, 16));
s_minPriceTxt.setColumns(10);
s_minPriceTxt.setBounds(273, 94, 96, 27);
panel.add(s_minPriceTxt);
JLabel l7 = new JLabel("最大单价:");
l7.setFont(new Font("黑体", Font.PLAIN, 16));
l7.setBounds(387, 98, 86, 15);
panel.add(l7);
s_maxPriceTxt = new JTextField();
s_maxPriceTxt.setFont(new Font("苹方 特粗", Font.PLAIN, 16));
s_maxPriceTxt.setColumns(10);
s_maxPriceTxt.setBounds(467, 92, 96, 27);
panel.add(s_maxPriceTxt);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(21, 135, 676, 208);
panel.add(scrollPane);
costumeTable = new JTable();
costumeTable.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
int row = costumeTable.getSelectedRow(); //获得选中的行号
int costumeId = (int)costumeTable.getValueAt(row, 0); // 获取服装id,查询尺码等信息
DefaultTableModel dtm = (DefaultTableModel) costumeInfoTable.getModel();
dtm.setRowCount(0);
Connection conn = null;
try {
conn = DbUtil.getConnection();
/**
* 第一件
*/
ResultSet rs = costumeDao.quetyInfos(conn, costumeId);
while (rs.next()) {
Vector v = new Vector();
v.add(rs.getInt("costumeId"));
v.add(FormatUtil.rtrim(rs.getString("costumeName")));
v.add(FormatUtil.rtrim(rs.getString("color")));
v.add(FormatUtil.rtrim(rs.getString("size")));
v.add(rs.getInt("storage"));
dtm.addRow(v);
}
/**
* 第二件
*/
Costume costume = costumeDao.query(conn, costumeId);
costumeIdTxt.setText(costume.getCostumeId()+"");
costumeNameTxt.setText(costume.getCostumeName());
brandTxt.setText(costume.getBrand());
sourceTxt.setText(costume.getSource());
costumeTypeTxt.setText(costume.getCostumeType());
priceTxt.setText(costume.getPrice()+"");
describeTxt.setText(costume.getDescribe());
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}finally {
DbUtil.close(conn);
}
}
});
costumeTable.setModel(new DefaultTableModel(
new Object[][] {
},
new String[] {
"服装编号", "服装名称", "品牌", "产地", "服装类型", "单价", "服装描述"
}
) {
boolean[] columnEditables = new boolean[] {
false, false, false, false, false, false, false
};
public boolean isCellEditable(int row, int column) {
return columnEditables[column];
}
});
costumeTable.getColumnModel().getColumn(5).setPreferredWidth(59);
costumeTable.getColumnModel().getColumn(6).setPreferredWidth(188);
costumeTable.setFont(new Font("苹方 特粗", Font.PLAIN, 14));
scrollPane.setViewportView(costumeTable);
countLabel = new JLabel("");
countLabel.setForeground(Color.BLACK);
countLabel.setFont(new Font("苹方 特粗", Font.PLAIN, 14));
countLabel.setBounds(21, 97, 152, 35);
panel.add(countLabel);
JLabel l5 = new JLabel("排序方式:");
l5.setFont(new Font("黑体", Font.PLAIN, 16));
l5.setBounds(333, 24, 80, 15);
panel.add(l5);
orderJcb = new JComboBox();
orderJcb.setModel(new DefaultComboBoxModel(new String[] {"默认", "单价递增", "单价递减"}));
orderJcb.setFont(new Font("黑体", Font.PLAIN, 14));
orderJcb.setBounds(423, 15, 116, 35);
panel.add(orderJcb);
JPanel panel_1 = new JPanel();
panel_1.setBorder(new TitledBorder(null, "服装具体数据查询", TitledBorder.LEADING, TitledBorder.TOP, null, null));
panel_1.setBounds(10, 373, 718, 219);
getContentPane().add(panel_1);
panel_1.setLayout(null);
JScrollPane scrollPane_1 = new JScrollPane();
scrollPane_1.setBounds(22, 23, 674, 173);
panel_1.add(scrollPane_1);
costumeInfoTable = new JTable();
costumeInfoTable.setFont(new Font("苹方 特粗", Font.PLAIN, 14));
costumeInfoTable.setModel(new DefaultTableModel(
new Object[][] {
},
new String[] {
"服装编号", "服装名称", "颜色", "尺码", "库存量"
}
) {
boolean[] columnEditables = new boolean[] {
false, false, false, false, false
};
public boolean isCellEditable(int row, int column) {
return columnEditables[column];
}
});
scrollPane_1.setViewportView(costumeInfoTable);
JPanel panel_3 = new JPanel();
panel_3.setBorder(new TitledBorder(null, "数据更新", TitledBorder.LEADING, TitledBorder.TOP, null, null));
panel_3.setBounds(738, 10, 244, 582);
getContentPane().add(panel_3);
panel_3.setLayout(null);
JLabel l8 = new JLabel("服装编号:");
l8.setFont(new Font("黑体", Font.PLAIN, 16));
l8.setBounds(23, 32, 80, 15);
panel_3.add(l8);
costumeIdTxt = new JTextField();
costumeIdTxt.setEditable(false);
costumeIdTxt.setFont(new Font("苹方 特粗", Font.PLAIN, 16));
costumeIdTxt.setColumns(10);
costumeIdTxt.setBounds(103, 25, 107, 27);
panel_3.add(costumeIdTxt);
JLabel l9 = new JLabel("服装名称:");
l9.setFont(new Font("黑体", Font.PLAIN, 16));
l9.setBounds(23, 83, 80, 15);
panel_3.add(l9);
costumeNameTxt = new JTextField();
costumeNameTxt.setFont(new Font("苹方 特粗", Font.PLAIN, 16));
costumeNameTxt.setColumns(10);
costumeNameTxt.setBounds(103, 77, 107, 27);
panel_3.add(costumeNameTxt);
JLabel l10 = new JLabel("品牌:");
l10.setFont(new Font("黑体", Font.PLAIN, 16));
l10.setBounds(47, 136, 56, 15);
panel_3.add(l10);
brandTxt = new JTextField();
brandTxt.setFont(new Font("苹方 特粗", Font.PLAIN, 16));
brandTxt.setColumns(10);
brandTxt.setBounds(103, 130, 107, 27);
panel_3.add(brandTxt);
JLabel l11 = new JLabel("产地:");
l11.setFont(new Font("黑体", Font.PLAIN, 16));
l11.setBounds(47, 183, 48, 15);
panel_3.add(l11);
sourceTxt = new JTextField();
sourceTxt.setFont(new Font("苹方 特粗", Font.PLAIN, 16));
sourceTxt.setColumns(10);
sourceTxt.setBounds(103, 177, 107, 27);
panel_3.add(sourceTxt);
JLabel l12 = new JLabel("服装类型:");
l12.setFont(new Font("黑体", Font.PLAIN, 16));
l12.setBounds(23, 236, 80, 15);
panel_3.add(l12);
costumeTypeTxt = new JTextField();
costumeTypeTxt.setFont(new Font("苹方 特粗", Font.PLAIN, 16));
costumeTypeTxt.setColumns(10);
costumeTypeTxt.setBounds(103, 230, 107, 27);
panel_3.add(costumeTypeTxt);
JLabel l13 = new JLabel("单价:");
l13.setFont(new Font("黑体", Font.PLAIN, 16));
l13.setBounds(47, 292, 56, 15);
panel_3.add(l13);
priceTxt = new JTextField();
priceTxt.setFont(new Font("苹方 特粗", Font.PLAIN, 16));
priceTxt.setColumns(10);
priceTxt.setBounds(103, 286, 107, 27);
panel_3.add(priceTxt);
JLabel l14 = new JLabel("服装描述:");
l14.setFont(new Font("黑体", Font.PLAIN, 16));
l14.setBounds(23, 334, 80, 15);
panel_3.add(l14);
JButton modifyBtn = new JButton("修改");
modifyBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
modifyActionPerformed(e);
}
});
modifyBtn.setFont(new Font("黑体", Font.PLAIN, 15));
modifyBtn.setBounds(23, 519, 80, 33);
panel_3.add(modifyBtn);
JButton deleteBtn = new JButton("删除");
deleteBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
deleteActionPerformed(e);
}
});
deleteBtn.setFont(new Font("黑体", Font.PLAIN, 15));
deleteBtn.setBounds(130, 519, 80, 33);
panel_3.add(deleteBtn);
JScrollPane scrollPane_2 = new JScrollPane();
scrollPane_2.setBounds(23, 359, 187, 132);
panel_3.add(scrollPane_2);
describeTxt = new JTextArea();
describeTxt.setLineWrap(true);
describeTxt.setFont(new Font("苹方 特粗", Font.PLAIN, 16));
scrollPane_2.setViewportView(describeTxt);
this.fillCostumeTable(new Costume(),null,null); // 初始化显示所有信息
}
private void deleteActionPerformed(ActionEvent evt) {
// TODO Auto-generated method stub
int select = JOptionPane.showConfirmDialog(null, "确认要删除吗?");
if (select != 0) {
return;
}
int costumeId = Integer.parseInt(costumeIdTxt.getText());
Connection conn = null;
try {
conn = DbUtil.getConnection();
int amout = costumeDao.delete(conn,costumeId);
if (amout > 0) {
JOptionPane.showMessageDialog(null, "删除成功!");
this.fillCostumeTable(new Costume(),null,null); // 初始化显示所有信息
}else {
JOptionPane.showMessageDialog(null, "删除失败,该服装包含多种尺码和颜色!");
}
} catch (Exception e) {
// TODO Auto-generated catch block
JOptionPane.showMessageDialog(null, "删除失败,该服装包含多种尺码和颜色!");
e.printStackTrace();
}
}
private void modifyActionPerformed(ActionEvent evt) {
// TODO Auto-generated method stub
int costumeId = Integer.parseInt(costumeIdTxt.getText());
String costumeName = costumeNameTxt.getText();
String brand = brandTxt.getText();
String source = sourceTxt.getText();
String costumeType = costumeTypeTxt.getText();
String describe = describeTxt.getText(); // 无需判空
if (costumeName.isEmpty()) {
JOptionPane.showMessageDialog(null, "服装名称不能为空!");
return;
}
if (brand.isEmpty()) {
JOptionPane.showMessageDialog(null, "品牌不能为空!");
return;
}
if (source.isEmpty()) {
JOptionPane.showMessageDialog(null, "产地不能为空!");
return;
}
if (costumeType.isEmpty()) {
JOptionPane.showMessageDialog(null, "服装类型不能为空!");
return;
}
if (priceTxt.getText().isEmpty()) {
JOptionPane.showMessageDialog(null, "服装单价不能为空!");
return;
}
double price = Double.parseDouble(priceTxt.getText()); //不为空才能转换
Costume costume = new Costume(costumeId, costumeName, brand, source, costumeType, price, describe);
Connection conn = null;
try {
conn = DbUtil.getConnection();
int amount = costumeDao.update(conn, costume);
if (amount > 0) {
JOptionPane.showMessageDialog(null, "修改成功!");
this.fillCostumeTable(new Costume(),null,null); // 初始化显示所有信息
}else {
JOptionPane.showMessageDialog(null, "修改失败!");
}
} catch (Exception e) {
// TODO Auto-generated catch block
JOptionPane.showMessageDialog(null, "修改失败!");
e.printStackTrace();
}finally {
DbUtil.close(conn);
}
}
private void searchActionPerformed(ActionEvent evt) {
// TODO Auto-generated method stub
String costumeName = s_costumeNameTxt.getText();
String brand = s_brandTxt.getText();
String source = s_sourceTxt.getText();
String costumeType = s_costumeTypeTxt.getText();
String order = null; // 都不选择以下两种排序,order为null
if ("单价递增".equals((String)orderJcb.getSelectedItem())){
order = "ASC";
}
if ("单价递减".equals((String)orderJcb.getSelectedItem())) {
order = "DESC";
}
String minPrice = null;
String maxPrice = null;
double[] prices = new double[2];
if (!s_minPriceTxt.getText().isEmpty()) {
minPrice = s_minPriceTxt.getText();
}
if (!s_maxPriceTxt.getText().isEmpty()) {
maxPrice = s_maxPriceTxt.getText();
}
if (minPrice==null) {
prices[0]=0;
}else {
prices[0]=Double.parseDouble(minPrice);
}
if (maxPrice==null) {
prices[1]=Double.MAX_VALUE;
}else {
prices[1]=Double.parseDouble(maxPrice);
}
if (minPrice!=null && maxPrice!=null && prices[1]<prices[0]) {
JOptionPane.showMessageDialog(null, "最大价格不能小于最小价格,请重新输入!");
return;
}
Costume costume = new Costume(costumeName, brand, source,costumeType);
this.fillCostumeTable(costume, prices,order);
}
private void fillCostumeTable(Costume costume,double[] prices,String order) {
DefaultTableModel dtm = (DefaultTableModel) costumeTable.getModel();
dtm.setRowCount(0);
Connection conn = null;
int count = 0;
try {
conn = DbUtil.getConnection();
ResultSet rs = costumeDao.query(conn, costume, prices,order); // prices在处理查询事件时给出
while (rs.next()) {
Vector v = new Vector();
v.add(rs.getInt("costumeId"));
v.add(FormatUtil.rtrim(rs.getString("costumeName")));
v.add(FormatUtil.rtrim(rs.getString("brand")));
v.add(FormatUtil.rtrim(rs.getString("source")));
v.add(FormatUtil.rtrim(rs.getString("costumeType")));
v.add(rs.getDouble("price"));
v.add(FormatUtil.rtrim(rs.getString("describe")));
dtm.addRow(v);
count++;
// 以下是查询条数
countLabel.setText("共查询到"+count+"条记录");
}
if (count==0) {
countLabel.setText("没有找到任何记录");
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
DbUtil.close(conn);
}
}
}
|
package ch09;
public class Manager extends SalariedEmployee
{
private double weeklyBonus;
private String department;
/**
Constructs a manager with a given name, annual salary and weekly bonus.
@param name the name of this employee
@param salary the annual salary
@param bonus the weekly bonus
*/
public Manager(String name, double salary, double bonus, String department)
{
super(name, salary);
weeklyBonus = bonus;
this.department = department;
}
public double weeklyPay(int hours)
{
return super.weeklyPay(hours) + weeklyBonus;
}
public String toString()
{
String returnValue = "This is " + getName() + " working at " + department + " earning " + weeklyPay(20);
return returnValue;
}
}
|
package com.trump.auction.goods.domain;
import lombok.Data;
import lombok.ToString;
import java.util.Date;
/**
* 商品图片
* @author zhangqingqiang
* @since 2017-12-21
*/
@Data
@ToString
public class ProductPic {
private Integer id;
private String picUrl;
private Integer skuId;
private Integer colorId;
private Integer productId;
private Date createTime;
private Date updateTime;
private String picType;
private String userId;
private String userIp;
}
|
package com.wangzhu.thread;
/**
* Created by wang.zhu on 2020-09-23 11:04.
**/
public class PSGCDemo {
public static void main(String[] args)throws Exception {
byte[] bytes1 = new byte[1024 * 1024 * 2];
byte[] bytes2 = new byte[1024 * 1024 * 2];
byte[] bytes3 = new byte[1024 * 1024 * 2];
System.out.println("step 1");
Thread.sleep(3000);
byte[] bytes4 = new byte[1024 * 1024 * 2];
System.out.println("step 2");
Thread.sleep(3000);
System.out.println("step 3");
}
}
|
package walnoot.dodgegame.states;
import walnoot.dodgegame.Util;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.scenes.scene2d.ui.Table;
public abstract class State{
protected final OrthographicCamera camera;
public Stage stage;
public State(OrthographicCamera camera){
this.camera = camera;
Vector2 dimensions = Util.getStageDimensions();
stage = new Stage(dimensions.x, dimensions.y, false);
}
public abstract void update();
public abstract void render(SpriteBatch batch);
public void renderUI(SpriteBatch stateBatch){
stage.act();
stage.draw();
Table.drawDebug(stage);
}
public abstract void dispose();
/**
* Called when the window is resized or the state is instantiated.
*/
public void resize(){
Vector2 dims = Util.getStageDimensions();
stage.setViewport(dims.x, dims.y, false);
}
public OrthographicCamera getCamera(){
return camera;
}
public void pause(){
}
public boolean playsGameMusic(){
return false;
}
}
|
class Solution {
public int[] shuffle(int[] nums, int n) {
int[] result=new int[2*n];
for(int k=0,i=0,j=n;j<nums.length;i++,j++,k++){
result[k]=nums[i];
k++;
result[k]=nums[j];
}
return result;
}
}
|
package com.gaoshin.cloud.web.xen.service;
import com.gaoshin.cloud.web.xen.bean.CloneRequest;
import com.gaoshin.cloud.web.xen.bean.ConsoleSession;
import com.gaoshin.cloud.web.xen.bean.Host;
import com.gaoshin.cloud.web.xen.bean.HostDetails;
import com.gaoshin.cloud.web.xen.bean.HostList;
import com.gaoshin.cloud.web.xen.bean.HostNetworkList;
import com.gaoshin.cloud.web.xen.bean.StorageRepoDetails;
import com.gaoshin.cloud.web.xen.bean.StorageRepoList;
import com.gaoshin.cloud.web.xen.bean.VirtualDiskImageList;
import com.gaoshin.cloud.web.xen.bean.VmDetails;
import com.gaoshin.cloud.web.xen.bean.VmList;
public interface XenService {
Host createHost(Host host);
HostList listHosts();
HostDetails getHostDetails(Long hostId);
void updateHost(Host host);
void removeHost(Long hostId);
VmList listHostVms(Long hostId) throws Exception;
String cloneVm(CloneRequest cloneRequest);
void startVm(Long hostId, String vmId);
void shutdownVm(Long hostId, String vmId);
void suspendVm(Long hostId, String vmId);
VmDetails getVmDetails(Long hostId, String vmId);
void resumeVm(Long hostId, String vmId);
void destroyVm(Long hostId, String vmId);
ConsoleSession getConsole(Long hostId, String vmId, String consoleId) throws Exception;
void sessionHeartBeat(String sessionId);
Host getHost(Long hostId);
void refreshHostStorageRepository(Long hostId) throws Exception;
void refreshHostVirtualDiskImages(Long hostId) throws Exception;
StorageRepoDetails getStorageRepoDetails(Long hostId, String srUuid) throws Exception;
VirtualDiskImageList listHostVdis(Long hostId) throws Exception;
StorageRepoList listHostStorage(Long hostId) throws Exception;
HostNetworkList listNetwork(Long hostId) throws Exception;
}
|
package com.belhomme.alexandre.sudokuandroid;
import android.os.Bundle;
import android.widget.TextView;
import com.belhomme.alexandre.sudokuandroid.composants.BaseAppCompatActivity;
import com.belhomme.alexandre.sudokuandroid.composants.GrilleDraw;
import com.belhomme.alexandre.sudokuandroid.objects.Cellule;
import com.belhomme.alexandre.sudokuandroid.objects.Grille;
public class GrilleActivity extends BaseAppCompatActivity {
private GrilleDraw grille_draw;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_grille);
this.grille_draw = (GrilleDraw) findViewById(R.id.grille_draw);
Bundle objetbunble = this.getIntent().getExtras();
String niveau = objetbunble.getString("niveau");
Grille g = new Grille();
int position = 0;
for (int y = 0; y < 9; y++) {
for (int x = 0; x < 9; x++) {
int valeur;
try {
valeur = Integer.parseInt("" + niveau.charAt(position));
} catch (Exception e) {
valeur = 0;
}
g.add(new Cellule(x, y, valeur, valeur != 0));
position++;
}
}
this.grille_draw.setGrille(g);
}
}
|
package de.amr.games.pacman.ui;
import java.util.Arrays;
import java.util.List;
/**
* Constants for the sounds used in the Pac-Man and Ms. Pac-Man games.
*
* @author Armin Reichert
*/
public enum PacManGameSound {
//@formatter:off
BONUS_EATEN,
CREDIT,
EXTRA_LIFE,
GAME_READY,
GHOST_EATEN,
GHOST_RETURNING_HOME,
GHOST_SIREN_1,
GHOST_SIREN_2,
GHOST_SIREN_3,
GHOST_SIREN_4,
INTERMISSION_1,
INTERMISSION_2,
INTERMISSION_3,
PACMAN_DEATH,
PACMAN_MUNCH,
PACMAN_POWER;
//@formatter:on
public static final List<PacManGameSound> SIRENS = Arrays.asList(GHOST_SIREN_1, GHOST_SIREN_2, GHOST_SIREN_3,
GHOST_SIREN_4);
}
|
package com.codigo.smartstore.webapi.services;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import javax.inject.Inject;
import org.springframework.stereotype.Service;
import com.codigo.smartstore.webapi.domain.Customer;
@Service
public class CustomerService
implements ICustomerService {
// @Inject
// CustomerRepository repository;
private final ICustomerIdGenerator customerIdGenerator;
private final List<Customer> customers = new ArrayList<>();
@Inject
public CustomerService(final ICustomerIdGenerator customerIdGenerator) {
this.customerIdGenerator = customerIdGenerator;
}
@Override
public Customer createCustomer(final Customer customer) {
customer.setId(this.customerIdGenerator.generateNextId());
this.customers.add(customer);
return customer;
}
@Override
public Optional<Customer> findCustomer(final Long id) {
return this.customers.stream()
.filter(
customer -> customer.getId()
.equals(id))
.findFirst();
}
@Override
public void updateCustomer(final Customer customer) {
this.customers.set(this.customers.indexOf(customer), customer);
}
}
|
/*
This class explains the main concepts of Inheritance in Java
EXTENDS and IMPLEMENTS
We basically use these 2 keywords to do inheritance in java
IS-A RELATIONSHIP:
public class Animal{
}
public class Mammal extends Animal{
}
public class Reptile extends Animal{
}
public class Dog extends Mammal{
}
In terms of OOP, we can say:
1) Animal is a superclass of Mammal
2) Animal is a superclass of Reptile
3) Mammal and Reptile are subclasses of Animal
4) Dog is a subclass of both Animal and Mammal
In terms of IS-A, we can say:
1) Mammal IS-A Animal
2) Reptile IS-A Animal
3) Dog IS-A Mammal
4) Hence Dog IS-A Animal as well
EXTENDS
With use of the extends keyword the subclasses will be able to inherit all the properties of the superclass
except for the private properties of the superclass.
INSTANCE OPERATOR
We can assure that Mammal is actually an Animal with the use of the instance operator.
public class Dog extends Mammal{
public static void main(String[] args){
// can access Animal class too (Dog <- Mammal <- Animal)
Animal a = new Animal();
// can access Mammal class obviously (Dog <- Mammal)
Mammal m = new Mammal();
// Make a Dog object
Dog d = new Dog()
System.out.println(m instanceof Animal); //prints true
System.out.println(d instanceof Mammal); //prints true
System.out.println(d instanceof Animal); //prints true
}
}
IMPLEMENTS
The implements keyword is used by classes by inherit from interfaces. Interfaces can never be extended by the classes.
EXAMPLE:
public interface Animal{}
// Can't use extends cos Animal is an interface now
public class Mammal implements Animal{
}
// Can use extends here cos Mammal is a class
public class Dog extends Mammal{
}
INSTANCEOF:
interface Animal{}
class Mammal implements Animal{}
public class Dog extends Mammal{
public static void main(String[] args){
Mammal m = new Mammal();
Dog d = new Dog();
System.out.println(m instanceof Animal); //true
System.out.println(d instanceof Mammal); //true
System.out.println(d instanceof Animal); //true
}
}
HAS-A RELATIONSHIP
This determines whether a certain class HAS-A certain thing.
This relationship helps to reduce duplication of code as well as bugs.
EXAMPLE:
public class Vehicle{}
public class Speed{}
public class Van extends Vehicle{
private Speed sp;
}
This shows that class Van HAS-A Speed.
By having a separate class for Speed,
we do not have to put the entire code that belongs to speed inside the Van class.,
which makes it possible to reuse the Speed class in multiple applications.
SINGLE INHERITANCE
A very important fact to remember is that Java only supports only single inheritance.
This means that a class cannot extend more than one class. Therefore following is illegal:
public class extends Animal, Mammal{}
MULTIPLE INTERFACES
However, a class can implement one or more interfaces.
This has made Java get rid of the impossibility of multiple inheritance.
*/
|
package com.javarush.task.task15.task1525;
import java.io.*;
import java.nio.Buffer;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
/*
Файл в статическом блоке
*/
public class Solution {
public static List<String> lines = new ArrayList<String>();
static {
try {
Solution.lines = Files.readAllLines(Paths.get(Statics.FILE_NAME));
} catch (IOException e) {
e.printStackTrace();
}
// try {
// Files.lines(Paths.get(Statics.FILE_NAME), StandardCharsets.UTF_8).forEach(l -> Solution.lines.add(l));
// } catch (IOException e) {
// e.printStackTrace();
// }
// try {
try {
BufferedReader reader = new BufferedReader(new FileReader(Statics.FILE_NAME));
while(reader.ready()){
String l = reader.readLine();
System.out.println(l);
}
} catch (IOException e) {
e.printStackTrace();
}
// StringBuilder sb = new StringBuilder();
// BufferedInputStream reader = new BufferedInputStream (new FileInputStream(FILE_NAME));
// while(reader.available()>0 ) {
// char ch = (char)reader.read();
// if(ch == '\r'){
// Solution.lines.add(sb.toString());
// sb.delete(0, sb.length());
// continue;
// }
// sb.append(ch);
// }
// Solution.lines.add(sb.toString());
// } catch (IOException e) {
// e.printStackTrace();
// }
}
public static void main(String[] args) {
Statics st = new Statics();
System.out.println(lines);
}
}
|
package Laboratorio1.Ejercicio1;
import java.util.Scanner;
public class Principal {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
double[] num1 = new double[4];
double[] num2 = new double[4];
double n1, n2;
for (int i = 0; i < num1.length; i++){
n1 = 0; n2 = 0;
System.out.print("Ingrese x" + (i + 1) + ": ");
n1 = s.nextDouble();
num1[i] = n1;
System.out.print("Ingrese y" + (i + 1) + ": ");
n2 = s.nextDouble();
num2[i] = n2;
}
Coordenada p1 = new Coordenada(num1[0],num2[0]);
Coordenada p2 = new Coordenada(num1[1],num2[1]);
Coordenada q1 = new Coordenada(num1[2],num2[2]);
Coordenada q2 = new Coordenada(num1[3],num2[3]);
Rectangulo A = new Rectangulo(p1,p2);
Rectangulo B = new Rectangulo(q1,q2);
System.out.println("\n¿Se sobreponen?: " + Verificador.esSobrePos(A,B));
// System.out.println("¿Son juntos?: " + Verificador.esJunto(A,B));
// System.out.println("¿son disjuntos?: " + Verificador.esDisjunto(A,B));
}
}
|
package am.bizis.cds.dpfdp4;
/**
* <p>DAP<br />
* Typ daňového přiznání.<br />
* B - řádné<br />
* O - řádné-opravné<br />
* D - dodatečné<br />
* E - dodatečné-opravné</p>
* @author alex
*
*/
public enum DAPTyp {
B("B","radne"),O("O","radne-opravne"),D("D","dodatecne"),E("E","dodatecne-opravne");
String dap_typ, desc;
private DAPTyp(String dap_typ, String desc){
this.dap_typ=dap_typ;
this.desc=desc;
}
}
|
package com.example.submissionempat.model;
import android.content.Intent;
import android.os.Parcel;
import android.os.Parcelable;
import android.util.Log;
import org.json.JSONObject;
public class MovieData implements Parcelable {
private int id;
private String title;
private int popularity;
private String overview;
private String poster_path;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public int getPopularity() {
return popularity;
}
public void setPopularity(int popularity) {
this.popularity = popularity;
}
public String getOverview() {
return overview;
}
public void setOverview(String overview) {
this.overview = overview;
}
public String getPoster_path() {
return poster_path;
}
public void setPoster_path(String poster_path) {
this.poster_path = poster_path;
}
public MovieData(JSONObject object){
try {
String title = object.getString("title");
int id = object.getInt("id");
String overview = object.getString("overview");
String poster_path = object.getString("poster_path");
String finalPosterPath = "https://image.tmdb.org/t/p/w500"+poster_path;
Log.d("cetakTitle",title);
this.id = id;
this.title = title;
this.popularity = popularity;
this.poster_path = finalPosterPath;
this.overview = overview;
} catch (Exception e) {
e.printStackTrace();
}
}
public MovieData(){
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(this.id);
dest.writeString(this.title);
dest.writeString(this.poster_path);
dest.writeString(this.overview);
}
protected MovieData(Parcel in){
this.id = in.readInt();
this.title =in.readString();
this.poster_path = in.readString();
this.overview = in.readString();
}
public static final Parcelable.Creator<MovieData> CREATOR = new Parcelable.Creator<MovieData>() {
@Override
public MovieData createFromParcel(Parcel source) {
return new MovieData(source);
}
@Override
public MovieData[] newArray(int size) {
return new MovieData[size];
}
};
}
|
package uk.co.mtford.jalp.abduction.logic.instance.term;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import choco.kernel.model.variables.Variable;
import uk.co.mtford.jalp.abduction.AbductiveFramework;
import uk.co.mtford.jalp.abduction.logic.instance.IFirstOrderLogicInstance;
import uk.co.mtford.jalp.abduction.logic.instance.IInferableInstance;
import uk.co.mtford.jalp.abduction.logic.instance.IUnifiableInstance;
import uk.co.mtford.jalp.abduction.rules.RuleNode;
/**
* Interface for terms i.e. variables, constants and functions.
*/
public interface ITermInstance extends IFirstOrderLogicInstance {
/** Returns the choco representation of this term.
*
* @param possSubst
* @param termToVarMap
* @return
*/
boolean reduceToChoco(List<Map<VariableInstance,IUnifiableInstance>> possSubst, HashMap<ITermInstance,Variable> termToVarMap);
/** Returns true if this term is in the specified list.
*
* @param constantList
* @param possSubst
* @return
*/
boolean inList(CharConstantListInstance constantList, List<Map<VariableInstance,IUnifiableInstance>> possSubst);
/**
* Returns the ruleNode for which this term is at the head of the current denial goal.
* @param abductiveFramework
* @param query
* @param goals
* @return
*/
public RuleNode getNegativeRootRuleNode(AbductiveFramework abductiveFramework, List<IInferableInstance> query, List<IInferableInstance> goals);
}
|
/**
* Copyright (C) 2016 - 2030 youtongluan.
*
* 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.yx.redis;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.function.Function;
import org.yx.common.Host;
import org.yx.conf.AppInfo;
import org.yx.exception.SimpleSumkException;
import org.yx.exception.SumkException;
import org.yx.log.Log;
import redis.clients.jedis.BinaryJedisCommands;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisCommands;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.JedisSentinelPool;
import redis.clients.jedis.MultiKeyCommands;
import redis.clients.jedis.ScriptingCommands;
import redis.clients.jedis.exceptions.JedisConnectionException;
import redis.clients.util.Pool;
public abstract class Redis implements BinaryJedisCommands, JedisCommands, MultiKeyCommands, ScriptingCommands {
private static final SumkException DIS_CONNECTION_EXCEPTION = new SimpleSumkException(400, "redis is disConnected");
static final String LOG_NAME = "sumk.redis";
protected final List<Host> hosts;
protected final int db;
protected final int tryCount;
protected final Pool<Jedis> pool;
public static final Charset UTF8 = StandardCharsets.UTF_8;
boolean disConnected;
protected JedisPoolConfig defaultPoolConfig() {
JedisPoolConfig config = new JedisPoolConfig();
config.setMinIdle(AppInfo.getInt("sumk.redis.minidle", 1));
config.setMaxIdle(AppInfo.getInt("sumk.redis.maxidle", 20));
config.setMaxTotal(AppInfo.getInt("sumk.redis.maxtotal", 100));
config.setTestWhileIdle(AppInfo.getBoolean("sumk.redis.testWhileIdle", false));
return config;
}
public Redis(JedisPoolConfig config, RedisParamter p) {
this.tryCount = p.getTryCount();
this.hosts = p.hosts();
this.db = p.getDb();
if (config == null) {
config = defaultPoolConfig();
}
String masterName = p.masterName();
if (masterName == null) {
Host host = p.hosts().get(0);
this.pool = new JedisPool(config, host.ip(), host.port(), p.getTimeout(), p.getPassword(), p.getDb(),
AppInfo.appId("sumk"));
RedisChecker.get().addRedis(this);
return;
}
List<Host> hosts = p.hosts();
Set<String> sentinels = new HashSet<>();
for (Host h : hosts) {
sentinels.add(h.toString());
}
Log.get(LOG_NAME).info("create sentinel redis pool,sentinels={},db={}", sentinels, p.getDb());
this.pool = new JedisSentinelPool(masterName, sentinels, config, p.getTimeout(), p.getTimeout(),
p.getPassword(), p.getDb(), AppInfo.appId("sumk"));
RedisChecker.get().addRedis(this);
}
/**
* @return redis的主机地址,如果存在多个,就用逗号分隔
*/
public List<Host> getHosts() {
return hosts;
}
public int getDb() {
return db;
}
protected Jedis jedis() {
return pool.getResource();
}
public int getTryCount() {
return tryCount;
}
protected final void checkConnection() {
if (this.disConnected) {
throw DIS_CONNECTION_EXCEPTION;
}
}
public <T> T exec(Function<Jedis, T> callback) {
checkConnection();
Jedis jedis = null;
try {
jedis = this.jedis();
return callback.apply(jedis);
} catch (Exception e) {
throw new SumkException(12342410, e.getMessage(), e);
} finally {
if (jedis != null) {
jedis.close();
}
}
}
public <T> T executeAndRetry(Function<Jedis, T> callback) {
Jedis jedis = null;
Exception e1 = null;
for (int i = 0; i < this.getTryCount(); i++) {
checkConnection();
try {
e1 = null;
jedis = this.jedis();
return callback.apply(jedis);
} catch (Exception e) {
if (isConnectException(e)) {
Log.get(Redis.LOG_NAME).warn("redis连接错误!({})" + e.getMessage(), hosts);
if (jedis != null) {
jedis.close();
jedis = null;
}
e1 = e;
continue;
}
Log.get(Redis.LOG_NAME).error("redis执行错误!({})" + e.getMessage(), hosts);
if (jedis != null) {
jedis.close();
jedis = null;
}
SumkException.throwException(12342411, e.getMessage(), e);
} finally {
if (jedis != null) {
jedis.close();
}
}
}
if (e1 != null) {
throw new SumkException(12342422, e1.getMessage(), e1);
}
throw new SumkException(12342423, "未知redis异常");
}
protected static boolean isConnectException(Exception e) {
return JedisConnectionException.class.isInstance(e)
|| (e.getCause() != null && JedisConnectionException.class.isInstance(e.getCause()));
}
@Override
public String toString() {
return "[hosts=" + hosts + ", db=" + db + ", tryCount=" + tryCount + "]";
}
public void shutdown() {
this.pool.close();
}
}
|
package Bai2;
public class MainNhanVien {
public static void main(String[] args) {
QuanLyNhanVien nv = new QuanLyNhanVien();
while (true) {
nv.menu();
}
}
}
|
package nl.capaxit.mybatisexamples.demos.dynamic;
/**
* Created by jamiecraane on 01/07/16.
*/
public class SearchSpec {
private String firstName;
private String lastName;
public SearchSpec(final Builder builder) {
this.firstName = builder.firstName;
this.lastName = builder.lastName;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public static class Builder {
private String firstName;
private String lastName;
public Builder firstName(final String firstName) {
this.firstName = firstName;
return this;
}
public Builder lastName(final String lastName) {
this.lastName = lastName;
return this;
}
public SearchSpec build() {
return new SearchSpec(this);
}
}
}
|
package commands;
import org.newdawn.slick.SlickException;
import org.newdawn.slick.command.BasicCommand;
import actionEngines.ActionEngine;
import actionEngines.ActorActionEngine;
public class FaceDirectionCommand extends BasicCommand implements GenericCommand{
private float[] newDirection;
public FaceDirectionCommand(float[] newDirection) {
super("Face Direction" + newDirection);
this.newDirection = newDirection;
}
@Override
public void execute(ActionEngine engine) throws SlickException{
if (engine instanceof ActorActionEngine){
((ActorActionEngine) engine).setFacingDirection(newDirection);
}
}
}
|
package com.movieapp.anti.movieapp.Models;
import java.io.Serializable;
import java.security.PublicKey;
import java.util.ArrayList;
/**
* Created by Anti on 2/18/2018.
*/
public class Details implements Serializable {
public String overview;
// public ArrayList<Details> credits = new ArrayList<>();
// public ArrayList<Credits> credits = new ArrayList<>();
public Details(String overview) {
this.overview = overview;
}
public String getOverview() {
return overview;
}
public void setOverview(String overview) {
this.overview = overview;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.