text
stringlengths
10
2.72M
package jsportsreg.entity; import static org.junit.Assert.*; import java.util.ArrayList; import org.junit.Test; public class SportTest { @Test public void test() { Sport instance0 = new Sport(); assertEquals("Sport Test 1: Sport ID", -1, instance0.getSportID() ); assertEquals("Sport Test 1: Sport Name", "", instance0.getSportName() ); assertEquals("Sport Test 1: Sport Description", "", instance0.getSportDescription() ); assertEquals("Sport Test 1: Divisions", true, instance0.getDivisions().isEmpty() ); ArrayList<Division> dList = new ArrayList<Division>(); Division division0 = new Division(); Division division1 = new Division(); dList.add(division0); dList.add(division1); Sport instance1 = new Sport( 1111111, "Mixed Martial Arts", "MMA", dList ); assertEquals("Sport Test 2: Sport ID", 1111111, instance1.getSportID() ); assertEquals("Sport Test 2: Sport Name", "MMA", instance1.getSportName() ); assertEquals("Sport Test 2: Sport Description", "Mixed Martial Arts", instance1.getSportDescription() ); assertEquals("Sport Test 2: Divisions", 2, instance1.getDivisions().size() ); Division division2 = new Division(); Division division3 = new Division(); instance1.addDivision(division2); instance1.addDivision(division3); assertEquals("Sport Test 3: Divisions", 4, instance1.getDivisions().size() ); instance1.removeDivision(division2); assertEquals("Sport Test 4: Divisions", 3, instance1.getDivisions().size() ); instance0.setSportID(21212121); instance0.setSportName("Futball"); instance0.setSportDescription("Soccer"); instance0.addDivision(division3); assertEquals("Sport Test 5: Sport ID", 21212121, instance0.getSportID() ); assertEquals("Sport Test 5: Sport Name", "Futball", instance0.getSportName() ); assertEquals("Sport Test 5: Sport Description", "Soccer", instance0.getSportDescription() ); assertEquals("Sport Test 5: Divisions", 1, instance0.getDivisions().size() ); Sport instance2 = new Sport( 1111111, "Mixed Martial Arts", "MMA", dList ); assertEquals("Sport Test 6: Sport Equals", true, instance1.equals(instance2) ); } }
package com.rc.portal.service; import java.sql.SQLException; import java.util.List; import com.rc.portal.vo.TMemberHobby; import com.rc.portal.vo.TMemberHobbyExample; public interface TMemberHobbyManager { int countByExample(TMemberHobbyExample example) throws SQLException; int deleteByExample(TMemberHobbyExample example) throws SQLException; int deleteByPrimaryKey(Long memberId) throws SQLException; Long insert(TMemberHobby record) throws SQLException; Long insertSelective(TMemberHobby record) throws SQLException; List selectByExample(TMemberHobbyExample example) throws SQLException; TMemberHobby selectByPrimaryKey(Long memberId) throws SQLException; int updateByExampleSelective(TMemberHobby record, TMemberHobbyExample example) throws SQLException; int updateByExample(TMemberHobby record, TMemberHobbyExample example) throws SQLException; int updateByPrimaryKeySelective(TMemberHobby record) throws SQLException; int updateByPrimaryKey(TMemberHobby record) throws SQLException; }
package com.example.media; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ListView; import com.aqi00.lib.dialog.FileSelectFragment; import com.aqi00.lib.dialog.FileSelectFragment.FileSelectCallbacks; import com.example.media.adapter.MediaListAdapter; import com.example.media.bean.MediaInfo; import com.example.media.loader.MovieLoader; import java.util.Map; public class MoviePlayerActivity extends AppCompatActivity implements OnClickListener, OnItemClickListener, FileSelectCallbacks { private static final String TAG = "MoviePlayerActivity"; private MovieLoader loader; // 声明一个影视加载器对象 @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_movie_player); findViewById(R.id.btn_open).setOnClickListener(this); initMovieList(); // 初始化影视列表 } // 初始化影视列表 private void initMovieList() { // 从布局文件中获取名叫lv_movie的列表视图 ListView lv_movie = findViewById(R.id.lv_movie); // 获得影视加载器的唯一实例 loader = MovieLoader.getInstance(getContentResolver()); // 构建一个影视信息的列表适配器 MediaListAdapter adapter = new MediaListAdapter(this, loader.getMovieList()); // 给lv_movie设置影视列表适配器 lv_movie.setAdapter(adapter); // 给lv_movie设置单项点击监听器 lv_movie.setOnItemClickListener(this); } @Override public void onClick(View v) { if (v.getId() == R.id.btn_open) { String[] videoExs = new String[]{"mp4", "3gp", "mkv", "mov", "avi"}; // 打开文件选择对话框 FileSelectFragment.show(this, videoExs, null); } } // 点击文件选择对话框的确定按钮后触发 public void onConfirmSelect(String absolutePath, String fileName, Map<String, Object> map_param) { Log.d(TAG, "onConfirmSelect absolutePath=" + absolutePath + ". fileName=" + fileName); // 拼接文件的完整路径 String file_path = absolutePath + "/" + fileName; // 创建一个媒体信息实例 MediaInfo movie = new MediaInfo(fileName, "未知", file_path); gotoPlay(movie); // 跳转到电影播放页面 } // 检查文件是否合法时触发 public boolean isFileValid(String absolutePath, String fileName, Map<String, Object> map_param) { return true; } @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { gotoPlay(loader.getMovieList().get(position)); // 跳转到电影播放页面 } // 跳转到电影播放页面 private void gotoPlay(MediaInfo media) { // 以下携带媒体信息跳转到影视播放详情页面 Intent intent = new Intent(this, MovieDetailActivity.class); intent.putExtra("movie", media); startActivity(intent); } }
package controlFlow; /** * @author malf * @description 水仙花数 * 水仙花数定义: * 1. 一定是3位数 * 2. 每一位的立方,加起来恰好是这个数本身,比如153=1*1*1+5*5*5+3*3*3 * 寻找所有的水仙花数 * @project how2jStudy * @since 2020/9/14 */ public class narcissisticNumber { public static void main(String[] args) { for (int i = 100; i < 1000; i++) { int baiwei = i / 100; int shiwei = i / 10 % 10; int gewei = i % 10; int cube = baiwei * baiwei * baiwei + shiwei * shiwei * shiwei + gewei * gewei * gewei; if (cube == i) { System.out.println("找到水仙花数:" + i); } } } }
package com.tencent.mm.plugin.emoji.ui; import android.content.DialogInterface; import android.content.DialogInterface.OnCancelListener; import com.tencent.mm.R; import com.tencent.mm.model.au; class EmojiStoreDetailUI$5 implements OnCancelListener { final /* synthetic */ EmojiStoreDetailUI inz; EmojiStoreDetailUI$5(EmojiStoreDetailUI emojiStoreDetailUI) { this.inz = emojiStoreDetailUI; } public final void onCancel(DialogInterface dialogInterface) { au.DF().c(EmojiStoreDetailUI.r(this.inz)); EmojiStoreDetailUI.s(this.inz).setText(R.l.emoji_store_load_failed_network); EmojiStoreDetailUI.t(this.inz); } }
package com.tencent.mm.model.d; import com.tencent.mm.ar.k; import com.tencent.mm.model.au; import com.tencent.mm.sdk.platformtools.x; class c$1 implements Runnable { final /* synthetic */ c dFv; public c$1(c cVar) { this.dFv = cVar; } public final void run() { if (c.a(this.dFv)) { x.i("MicroMsg.TraceConfigUpdater", "summer update isUpdating and ret"); return; } long j = c.b(this.dFv).getLong("trace_config_last_update_time", 0); long currentTimeMillis = System.currentTimeMillis(); if (currentTimeMillis - j > 86400000 || j > currentTimeMillis) { c.c(this.dFv); c.d(this.dFv); au.DF().a(159, this.dFv); au.DF().a(160, this.dFv); au.DF().a(new k(21), 0); return; } x.i("MicroMsg.TraceConfigUpdater", "summer last update time: " + j + " current time: " + currentTimeMillis + " in same day"); } }
/* * 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 services; import java.rmi.Remote; import java.rmi.RemoteException; import java.util.List; import jpaModel.Administrateur; import jpaModel.Medecin; /** * * @author Fallou */ public interface IMedecin extends Remote{ public void InsererMedecin(Medecin m) throws RemoteException; public void ModifierMedecin(Medecin m) throws RemoteException; public List listeMedecin() throws RemoteException; public Medecin find(String matricule) throws RemoteException; }
package com.qa.callhub.Pages; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; import org.openqa.selenium.support.PageFactory; import com.qa.callhub.BaseClass.TestBase; public class LoginPage extends TestBase { @FindBy(xpath = "//a[contains(text(), 'Login & Signup')]") WebElement clickOnLoginSignUp; @FindBy(xpath = "//input[@class='_2zrpKA _1dBPDZ']") WebElement userName; @FindBy(xpath = "//input[@class='_2zrpKA _3v41xv _1dBPDZ']") WebElement password; @FindBy(xpath = "//button[@class='_2AkmmA _1LctnI _7UHT_c']") WebElement clickOnLogin; public LoginPage() { PageFactory.initElements(driver, this); } public String verifyLoginPageTitle() { return driver.getTitle(); } public void login(String uname, String pword) { JavascriptExecutor js1 = (JavascriptExecutor)driver; js1.executeScript("arguments[0].click();", clickOnLoginSignUp); userName.sendKeys(uname); password.sendKeys(pword); JavascriptExecutor js2 = (JavascriptExecutor)driver; js2.executeScript("arguments[0].click();", clickOnLogin); } }
package com.example.structural.adapter; /** * Copyright (C), 2020 * FileName: AdapterPatternDemo * * @author: xieyufeng * @date: 2020/11/16 11:29 * @description: */ public class AdapterPatternDemo { public static void main(String[] args) { Adapter adapter = new Adapter(); adapter.handler(); } }
package SwordOffer; /** * @author renyujie518 * @version 1.0.0 * @ClassName intPower_16.java * @Description 数值的整数次方 * 给定一个 double 类型的浮点数 base 和 int 类型的整数 exponent,求 base 的 exponent 次方。 base^exp *比如要求x^11 正常的乘积需要循环乘11次,时间复杂度为O(n) * 将指数11 可以转成二进制数1011,则原来的式子可以转化成 * x^11 = x^(2^3+2^1+2^0) = x^(2^3) * x(2^1) * x(2^0) * 此时只运算了3次乘积,时间复杂度降至O(logn) * @createTime 2021年08月18日 16:34:00 */ public class intPower_16 { public static double myPow(double x, int n) { if (x == 0) { return 0; } long b = n; double res = 1.0; if (b < 0) { x = 1 / x; b = -b; } while (b > 0) { // 最后一位为1,需要乘上该位上的权重 if ((b & 1) == 1) { res *= x; } //累乘 x *= x; b = b >> 1; } return res; } }
/* * Copyright 2011-2012 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 * * 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.springframework.integration.splunk.inbound; import static org.mockito.Mockito.*; import java.util.ArrayList; import java.util.List; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.springframework.integration.splunk.event.SplunkEvent; import org.springframework.integration.splunk.support.SplunkExecutor; /** * @author Jarred Li * @since 1.0 * */ public class SplunkPollingChannelAdapterTests { private SplunkPollingChannelAdapter inboundAdapter; private SplunkExecutor executor; @Before public void init() { executor = mock(SplunkExecutor.class); inboundAdapter = new SplunkPollingChannelAdapter(executor); } /** * Test method for {@link org.springframework.integration.splunk.inbound.SplunkPollingChannelAdapter#receive()}. */ @Test public void testReceive() { List<SplunkEvent> data = new ArrayList<SplunkEvent>(); SplunkEvent sd = new SplunkEvent("spring", "spring:example"); sd.setCommonDesc("description"); data.add(sd); when(executor.poll()).thenReturn(data); List<SplunkEvent> received = inboundAdapter.receive().getPayload(); Assert.assertEquals(1, received.size()); } /** * Test method for {@link org.springframework.integration.splunk.inbound.SplunkPollingChannelAdapter#getComponentType()}. */ @Test public void testGetComponentType() { Assert.assertEquals("splunk:inbound-channel-adapter", inboundAdapter.getComponentType()); } }
package com.lolRiver.river.models; import java.sql.Timestamp; import java.util.ArrayList; import java.util.List; /** * @author mxia (mxia@lolRiver.com) * 10/2/13 */ public class Clip { public static final String ID_STRING = "id"; public static final String GAME_ID_STRING = "game_id"; public static final String VIDEO_ID_STRING = "video_id"; public static final String GAME_TYPE_STRING = "game_type"; public static final String URL_STRING = "url"; public static final String STREAMER_NAME_STRING = "streamer_name"; public static final String START_TIME_STRING = "start_time"; public static final String END_TIME_STRING = "end_time"; public static final String LENGTH_STRING = "length"; public static final String VIEWS_STRING = "views"; public static final String CHAMPION_PLAYED_STRING = "champion_played"; public static final String ROLE_PLAYED_STRING = "role_played"; public static final String CHAMPION_FACED_STRING = "champion_faced"; public static final String LANE_PARTNER_CHAMPION_STRING = "lane_partner_champion"; public static final String ENEMY_LANE_PARTNER_CHAMPION_STRING = "enemy_lane_partner_champion"; public static final String ELO_STRING = "elo"; private int id; private int gameId; private int videoId; private Game.Type gameType; private String url; private String streamerName; private Timestamp startTime; private Timestamp endTime; private int length; // video length in seconds private int views; private Champion championPlayed; private Role rolePlayed; private Champion championFaced; private Champion lanePartnerChampion; private Champion enemyLanePartnerChampion; private Elo elo; /* START - Non DB variables */ private String timeSinceNowMessage; // used for index.jsp private boolean isViewable; // set by video converter to know if clip is viewable // front-end related for searching clips private String generalElo; private String championPlayedString; private String championFacedString; private List<String> eloCriteria; private List<String> roleCriteria; private String minLength; private String maxLength; /* END - Non DB variables */ public int getId() { return id; } public int getGameId() { return gameId; } public int getVideoId() { return videoId; } public Game.Type getGameType() { return gameType; } public Clip setGameType(Game.Type gameType) { this.gameType = gameType; return this; } public String getUrl() { return url; } public String getStreamerName() { return streamerName; } public Timestamp getStartTime() { return startTime; } public Timestamp getEndTime() { return endTime; } public int getLength() { return length; } public int getViews() { return views; } public Champion getChampionPlayed() { return championPlayed; } public Role getRolePlayed() { return rolePlayed; } public Champion getChampionFaced() { return championFaced; } public Champion getLanePartnerChampion() { return lanePartnerChampion; } public Champion getEnemyLanePartnerChampion() { return enemyLanePartnerChampion; } public Elo getElo() { return elo; } public Clip setId(int id) { this.id = id; return this; } public Clip setGameId(int gameId) { this.gameId = gameId; return this; } public Clip setVideoId(int videoId) { this.videoId = videoId; return this; } public Clip setUrl(String url) { this.url = url; return this; } public Clip setStreamerName(String streamerName) { this.streamerName = streamerName; return this; } public Clip setStartTime(Timestamp startTime) { this.startTime = startTime; return this; } public Clip setEndTime(Timestamp endTime) { this.endTime = endTime; return this; } public Clip setLength(int length) { this.length = length; return this; } public Clip setViews(int views) { this.views = views; return this; } public Clip setChampionPlayed(Champion championPlayed) { this.championPlayed = championPlayed; return this; } public Clip setRolePlayed(Role rolePlayed) { this.rolePlayed = rolePlayed; return this; } public Clip setChampionFaced(Champion championFaced) { this.championFaced = championFaced; return this; } public Clip setLanePartnerChampion(Champion lanePartnerChampion) { this.lanePartnerChampion = lanePartnerChampion; return this; } public Clip setEnemyLanePartnerChampion(Champion enemyLanePartnerChampion) { this.enemyLanePartnerChampion = enemyLanePartnerChampion; return this; } public Clip setElo(Elo elo) { this.elo = elo; return this; } public String getTimeSinceNowMessage() { return timeSinceNowMessage; } public Clip setTimeSinceNowMessage(String timeSinceNowMessage) { this.timeSinceNowMessage = timeSinceNowMessage; return this; } public boolean isViewable() { return isViewable; } public void setViewable(boolean viewable) { isViewable = viewable; } public String getGeneralElo() { return generalElo; } public Clip setGeneralElo(String generalElo) { this.generalElo = generalElo; return this; } public String getChampionPlayedString() { return championPlayedString; } public Clip setChampionPlayedString(String championPlayedString) { this.championPlayedString = championPlayedString; return this; } public String getChampionFacedString() { return championFacedString; } public Clip setChampionFacedString(String championFacedString) { this.championFacedString = championFacedString; return this; } public List<String> getRoleCriteria() { return roleCriteria; } public Clip setRoleCriteria(List<String> roleCriteria) { this.roleCriteria = new ArrayList<String>(roleCriteria); return this; } public List<String> getEloCriteria() { return eloCriteria; } public Clip setEloCriteria(List<String> eloCriteria) { this.eloCriteria = new ArrayList<String>(eloCriteria); return this; } public String getMinLength() { return minLength; } public Clip setMinLength(String minLength) { this.minLength = minLength; return this; } public String getMaxLength() { return maxLength; } public Clip setMaxLength(String maxLength) { this.maxLength = maxLength; return this; } @Override public String toString() { return "Clip{" + "id=" + id + ", gameId=" + gameId + ", videoId=" + videoId + ", gameType=" + gameType + ", url='" + url + '\'' + ", streamerName='" + streamerName + '\'' + ", startTime=" + startTime + ", endTime=" + endTime + ", length=" + length + ", views=" + views + ", championPlayed=" + championPlayed + ", rolePlayed=" + rolePlayed + ", championFaced=" + championFaced + ", lanePartnerChampion=" + lanePartnerChampion + ", enemyLanePartnerChampion=" + enemyLanePartnerChampion + ", elo=" + elo + ", timeSinceNowMessage='" + timeSinceNowMessage + '\'' + ", generalElo='" + generalElo + '\'' + ", championPlayedString='" + championPlayedString + '\'' + ", championFacedString='" + championFacedString + '\'' + ", eloCriteria=" + eloCriteria + ", roleCriteria=" + roleCriteria + ", minLength='" + minLength + '\'' + ", maxLength='" + maxLength + '\'' + '}'; } }
package br.ita.sem4dia2.TarefaAvaliadaCarrinhoDecompras; import static org.junit.Assert.*; import org.junit.Test; public class TesteProduto { @Test public void testeProdutosIguais() { Produto p0 = new Produto(1,"batata",20); Produto p1 = new Produto(2,"tomate",30); Produto p2 = new Produto(1,"batata roxa",20); //Teste hashCode() assertEquals(p0.hashCode(), p2.hashCode()); //Teste equals() assertEquals(true,p0.equals(p2)); assertEquals(false,p0.equals(p1)); assertEquals(false,p1.equals(p0)); assertEquals(false,p1.equals(p2)); } }
package enums; public enum MountainBikeSuspension { /** * suspensão simples */ SIMPLE, /** * suspensão dupla */ DOUBLE, /** * sem suspensão */ SEM; /** * Enumeração para escolher suspension de BikeStore.MountainBike * * @param tipo de suspension * @return tipo de suspension */ public static String MountainBikeSuspensionToString(MountainBikeSuspension tipo) { switch (tipo) { case SIMPLE: return "Suspensao simples"; case DOUBLE: return "Suspensao dupla"; default: return "Sem suspensão"; } } }
package 문제풀이; import java.util.Random; import javax.swing.JOptionPane; public class 랜덤2개 { public static void main(String[] args) { //int x; //Random r; Random r = new Random(); // 램에 랜덤을 복사 / random 부품 클레스 int n1 = r.nextInt(100); // 0~99까지 정수 중 하나를 n1에 대입 int n2 = r.nextInt(100); // 0~99까지 정수 중 하나를 n2에 대입 System.out.println(n1); // 0~99까지 정수 중 n1에 대입된걸 출력 System.out.println(n2); // 0~99까지 정수 중 n2에 대입된걸 출력 if (n1 > n2) { // n1은 n2보다 큰가? JOptionPane.showMessageDialog(null, "n1이 더 큼"); // n1이 n2보다 큼 } if (n1 < n2) { // n2은 n1보다 작은가? JOptionPane.showMessageDialog(null, "n2이 더 큼"); // n2이 n1보다 큼 } } }
package io.sensesecure.hadoop.xz; import java.io.IOException; import org.apache.hadoop.io.compress.Decompressor; /** * * @author yongtang */ public class XZDecompressor implements Decompressor { @Override public void setInput(byte[] b, int off, int len) { throw new UnsupportedOperationException("Not supported yet."); } @Override public boolean needsInput() { throw new UnsupportedOperationException("Not supported yet."); } @Override public void setDictionary(byte[] b, int off, int len) { throw new UnsupportedOperationException("Not supported yet."); } @Override public boolean needsDictionary() { throw new UnsupportedOperationException("Not supported yet."); } @Override public boolean finished() { throw new UnsupportedOperationException("Not supported yet."); } @Override public int decompress(byte[] b, int off, int len) throws IOException { throw new UnsupportedOperationException("Not supported yet."); } @Override public int getRemaining() { throw new UnsupportedOperationException("Not supported yet."); } @Override public void reset() { // do nothing } @Override public void end() { throw new UnsupportedOperationException("Not supported yet."); } }
package drawing; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class Scribble { final Logger logger = LoggerFactory.getLogger(Scribble.class); public Scribble() { logger.trace("Entering drawing mode"); logger.debug("Starting a new drawing"); logger.info("Connected to database"); logger.warn("Empty input"); logger.error("Permission denied (error code {})", 2); } }
package Controllers; import java.io.IOException; import java.time.LocalDate; /** this is the person class * * still need to implement the dateofBirth but unsure what datatype to make int string? * * **/ public class Person { public static final int NEW_PERSON = 0; String firstName; String lastName; LocalDate dateOfBirth; int id; int age; /** * person constructor **/ Person(String firstName, String lastName, int id, int age, LocalDate dateOfBirth){ this.firstName = firstName; this.lastName = lastName; this.id = id; this.age = age; this.dateOfBirth = dateOfBirth; } /** * allows you to retrieve persons lastname **/ public String getLastName() { return lastName; } /** * allows you to set dob **/ public void setDateOfBirth(LocalDate dateOfBirth) { this.dateOfBirth = dateOfBirth; } /** * allows you to retrieve DOB **/ public LocalDate getDateOfBirth() { return dateOfBirth; } /** * allows you to setLastName **/ public void setLastName(String lastName) { this.lastName = lastName; } /** * allows you to retrieve age **/ public int getAge() { return age; } /** * allows you to set Age **/ public void setAge(int age) { this.age = age; } /** * allows you to retrieve persons id **/ public int getId() { return id; } public void setId(int id) { this.id = id; } /** * allows you to retrieve firstname **/ public String getFirstName() { return firstName; } /** * allows you to set FirstName **/ public void setFirstName(String firstName) { this.firstName = firstName; } public String toString() { return firstName + " " + lastName + " id:" + id + " age:" +age+ " dob:"+dateOfBirth; } }
package things.entity.strategy.movement; import things.entity.GameComponent; public class StandardMovement implements Movement { private GameComponent gameComponent; private boolean left; private boolean right; private int deltaX; private int horizontalSpeed; public StandardMovement(GameComponent gameComponent) { this.gameComponent = gameComponent; } @Override public void moveSprite() { // If the left attribute has the value of true if(left){ // The next position of deltaX is the value of the horizontal speed ie. 5 pixels to the left deltaX = horizontalSpeed; // The original value of topLeftXPos is now the original value minus the next positions value deltaX gameComponent.setTopLeftXPos(gameComponent.getTopLeftXPos() - deltaX); } // If the right attribute has the value of true if(right){ // The next position of x is the value of the horizontal speed ie. 5 pixels to the right deltaX = horizontalSpeed; // The original value of x is now the original value plus the next positions value gameComponent.setTopLeftXPos(gameComponent.getTopLeftXPos() + deltaX); } deltaX = 0; } @Override public void setLeft(boolean left) { this.left = left; } @Override public void setRight(boolean right) { this.right = right; } @Override public void setUp(boolean up) {// not applicable } @Override public void setDown(boolean down) { // not applicable } @Override public int getSpeed() { return horizontalSpeed; } @Override public void setSpeed(int horizontalSpeed) { this.horizontalSpeed = horizontalSpeed; } }
package com.zero.qa.testcases; import org.testng.Assert; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import com.zero.qa.base.TestBase; import com.zero.qa.pages.ShowTransaction; import com.zero.qa.pages.LoginPage; import com.zero.qa.pages.AccountSummaryPage; import com.zero.qa.pages.Home; import com.zero.qa.util.TestUtil; public class ShowTransactionTest extends TestBase { Home home; LoginPage loginPage; TestUtil testUtil; ShowTransaction ShowTransaction; //AccountSummary AccountSummaryPage; public ShowTransactionTest() { super(); } @BeforeMethod public void setUp() { initialization(); testUtil = new TestUtil(); //AccountSummary = new AccountSummaryPage(); ShowTransaction = new ShowTransaction(); home = new Home(); loginPage = new LoginPage(); home.clickOnSignin(); loginPage.login(prop.getProperty("username"), prop.getProperty("password")); } @Test(priority=1) public void verifySavingsTest(){ ShowTransaction.clickOnSavings(); Assert.assertEquals(driver.getTitle(), "Zero - Account Activity"); } @AfterMethod public void tearDown() { driver.close(); driver.quit(); } }
package com.domain; /** * Created by Michał on 2016-11-14. */ public enum Role { USER("user"), ADMIN("admin"); private String value; Role(String value) { this.value = value; } }
package com.example.doubnut.data.repository; import android.arch.lifecycle.LiveData; import android.util.Log; import com.example.doubnut.data.db.NewsListDao; import com.example.doubnut.data.db.entity.Article; import com.example.doubnut.data.network.NewsListDataSource; import java.util.List; import io.reactivex.Completable; import io.reactivex.CompletableObserver; import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.disposables.Disposable; import io.reactivex.functions.Action; import io.reactivex.schedulers.Schedulers; public class NewsRepositoryImpl implements NewsRepository { private NewsListDao newsListDao; private NewsListDataSource newsListDataSource; public NewsRepositoryImpl(NewsListDao newsListDao, NewsListDataSource newsListDataSource) { this.newsListDao = newsListDao; this.newsListDataSource = newsListDataSource; syncRemoteWithLocalDB(); } @Override public void persistNewsToDB(String country) { newsListDataSource.getCurrentNews(country); } public void syncRemoteWithLocalDB() { newsListDataSource.getCurrentNewsLive().observeForever(this::saveNewsToDB); } private void saveNewsToDB(List<Article> articles) { Completable.fromAction(new Action() { @Override public void run() throws Exception { persistNewsToDB(articles); } }).observeOn(AndroidSchedulers.mainThread()) .subscribeOn(Schedulers.io()).subscribe(new CompletableObserver() { @Override public void onSubscribe(Disposable d) { Log.d("dispose", "dispose"); } @Override public void onComplete() { Log.d("onComplete", "onComplerte"); } @Override public void onError(Throwable e) { Log.d("error", "error"); } }); } private void persistNewsToDB(List<Article> articleList) { newsListDao.deleteAllUsers(); newsListDao.insertAll(articleList); } public LiveData<List<Article>> getNewsFromLocalDB() { return newsListDao.getAll(); } @Override public LiveData<Boolean> getNewsLoadError() { return newsListDataSource.getNewsLoadError(); } @Override public LiveData<Boolean> getLoading() { return newsListDataSource.getLoading(); } }
/* * created 07.05.2005 * * $Id: PostgreSQL.java 501 2006-08-25 19:33:49Z hannesn $ */ package com.byterefinery.rmbench.database.pgsql; import com.byterefinery.rmbench.external.database.DatabaseInfo; import com.byterefinery.rmbench.external.database.sql99.SQL99; import com.byterefinery.rmbench.external.model.IDataType; /** * @author cse */ public class PostgreSQL extends DatabaseInfo { public static final String RESERVED_SCHEMA_NAME = "reserved_schema_name"; public static final Object PUBLIC_SCHEMA_NAME = "public"; public final IDataType time; public final IDataType timetz; public final IDataType timestamp; public final IDataType timestamptz; public final IDataType interval; public final IDataType serial; public final IDataType bigserial; public PostgreSQL() { registerDataType(new String[]{"SMALLINT", "INT2"}, SQL99.SMALLINT.getPrimaryName(), 1); registerDataType(new String[]{"INTEGER", "INT", "INT4"}, SQL99.INTEGER.getPrimaryName(), 1); registerDataType(new String[]{"BIGINT", "INT8"}, SQL99.INTEGER.getPrimaryName(), 2); registerDataType(new String[]{"DOUBLE PRECISION", "FLOAT8"}, SQL99.DOUBLE_PRECISION.getPrimaryName(), 1); registerDataType(new String[]{"REAL", "FLOAT4"}, SQL99.FLOAT.getPrimaryName(), 1); registerDataType("MONEY", SQL99.DECIMAL.getPrimaryName(), 2); registerDataType( new String[] {"NUMERIC", "DECIMAL"}, IDataType.UNLIMITED_SIZE, false, 10, IDataType.UNLIMITED_SCALE, false, 2, SQL99.DECIMAL.getPrimaryName(), 1); registerDataType( new String[] {"VARCHAR", "CHARACTER VARYING"}, IDataType.UNLIMITED_SIZE, false, 100, SQL99.VARCHAR.getPrimaryName(), 1); registerDataType( new String[] {"CHAR", "CHARACTER", "BPCHAR"}, IDataType.UNLIMITED_SIZE, false, 10, SQL99.CHAR.getPrimaryName(), 1); registerDataType("TEXT", SQL99.CLOB.getPrimaryName(), 2); serial = registerDataType(new String[]{"SERIAL", "SERIAL4"}, SQL99.INTEGER.getPrimaryName(), 2); bigserial = registerDataType(new String[]{"BIGSERIAL", "SERIAL8"}, SQL99.INTEGER.getPrimaryName(), 2); registerDataType( new String[]{"BIT"}, IDataType.UNLIMITED_SIZE, false, 10, SQL99.BIT.getPrimaryName(), 1); registerDataType( new String[]{"BIT VARYING", "VARBIT"}, IDataType.UNLIMITED_SIZE, false, 100, SQL99.BIT_VARYING.getPrimaryName(), 1); registerDataType(new String[]{"BOOL", "BOOLEAN"}, SQL99.BOOLEAN.getPrimaryName(), 1); registerDataType("BYTEA", SQL99.BLOB.getPrimaryName(), 2); registerDataType("DATE", SQL99.DATE.getPrimaryName(), 1); time = registerDataType( "TIME", 6, false, IDataType.UNSPECIFIED_SIZE, SQL99.TIME.getPrimaryName(), 1); timetz = registerDataType( new String[]{"TIMETZ", "TIME WITH TIME ZONE"}, 6, false, IDataType.UNSPECIFIED_SIZE, SQL99.TIME.getPrimaryName(), 1); timestamp = registerDataType( "TIMESTAMP", 6, false, IDataType.UNSPECIFIED_SIZE, SQL99.TIMESTAMP.getPrimaryName(), 1); timestamptz = registerDataType( new String[]{"TIMESTAMPTZ", "TIMESTAMP WITH TIME ZONE"}, 6, false, IDataType.UNSPECIFIED_SIZE, SQL99.TIMESTAMP.getPrimaryName(), 2); interval = registerDataType( "INTERVAL", 6, false, IDataType.UNSPECIFIED_SIZE, null, 1); registerDataType("BOX", null, 1); registerDataType("CIRCLE", null, 1); registerDataType("LINE", null, 1); registerDataType("LSEG", null, 1); registerDataType("PATH", null, 1); registerDataType("POINT", null, 1); registerDataType("POLYGON", null, 1); registerDataType("INET", null, 1); registerDataType("CIDR", null, 1); registerDataType("MACADDR", null, 1); } public IDataType getDataType(int jdbcType, String typeName, long size, int scale) { IDataType dataType = getDataType(typeName); if(dataType == null) return null; if(!dataType.equals(time) && !dataType.equals(timetz) && !dataType.equals(timestamp) && !dataType.equals(timestamptz) && !dataType.equals(interval)) { if(dataType.acceptsSize()) dataType.setSize(size); if(dataType.acceptsScale()) dataType.setScale(scale); } return dataType; } public String validateSchemaName(String name) { if(PUBLIC_SCHEMA_NAME.equals(name)) return RESERVED_SCHEMA_NAME; return validateIdentifier(name); } public boolean isPublicSchema(String catalogname, String name) { return PUBLIC_SCHEMA_NAME.equals(name); } public boolean impliesDefault(IDataType dataType) { return dataType == serial || dataType == bigserial; } }
package com.tencent.mm.ui.chatting.b; import android.os.Looper; import com.tencent.mm.ab.l; import com.tencent.mm.ak.d.a; import com.tencent.mm.sdk.platformtools.ag; import com.tencent.mm.sdk.platformtools.x; import com.tencent.mm.storage.bd; class y$6 implements a { final /* synthetic */ bd dAs; final /* synthetic */ y tQV; y$6(y yVar, bd bdVar) { this.tQV = yVar; this.dAs = bdVar; } public final void a(long j, long j2, int i, int i2, Object obj, int i3, int i4, l lVar) { } public final void a(long j, long j2, int i, int i2, Object obj, int i3, int i4, String str, l lVar) { boolean z = i3 == 0 && i4 == 0; x.i("MicroMsg.ChattingUI.MessBoxComponent", "oreh downloadImgAndFav taskEnd image succed: %s, msgID:%d, errType: %s, errCode:%s", new Object[]{Boolean.valueOf(z), Long.valueOf(this.dAs.field_msgId), Integer.valueOf(i3), Integer.valueOf(i4)}); new ag(Looper.getMainLooper()).post(new 1(this)); } public final void a(long j, long j2, int i, int i2, Object obj) { x.i("MicroMsg.ChattingUI.MessBoxComponent", "oreh downloadImgAndFav download image taskcancel: msgID:%d", new Object[]{Long.valueOf(this.dAs.field_msgId)}); } }
package mypackage; import java.io.IOException; import java.io.InputStream; import javax.microedition.io.Connector; import javax.microedition.io.HttpConnection; import net.rim.device.api.system.Bitmap; import net.rim.device.api.ui.component.BitmapField; public class BitmapRetriever extends BitmapField { public static final String pictureNotAvailable = "not_available.jpg"; public static Bitmap connectServerForImage(String url) { byte[] bitmap = null;//Utilities.getImage(url); HttpConnection httpConnection = null; InputStream inputStream = null; try { httpConnection = (HttpConnection) Connector.open(url, Connector.READ_WRITE); httpConnection.setRequestMethod(HttpConnection.GET); StringBuffer b = new StringBuffer(); int lon = 0; int ch = 0; int responseCode = httpConnection.getResponseCode(); if (responseCode == HttpConnection.HTTP_OK) { inputStream = httpConnection.openInputStream(); lon = (int) httpConnection.getLength(); if (lon != -1) { for(int i = 0 ; i < lon ; i++ ) { if((ch = inputStream.read()) != -1) { b.append((char) ch); } } } else { //Read until the connection is closed. while ((ch = inputStream.read()) != -1) { lon = inputStream.available() ; b.append((char)ch); } } bitmap = b.toString().getBytes(); } } catch (Throwable e){ e.printStackTrace(); } finally { try { if (inputStream != null) { inputStream.close(); } if (httpConnection != null) { httpConnection.close(); } } catch (IOException e) { System.out.println("IOException: Closing conexion" + e.getMessage()); } } Bitmap resultBitmap=null; if (bitmap==null){ resultBitmap= Bitmap.getBitmapResource(BitmapRetriever.pictureNotAvailable); }else{ resultBitmap= Bitmap.createBitmapFromBytes(bitmap, 0, bitmap.length, 1); } return resultBitmap; } }
package pss_server; import java.io.*; import java.net.*; import java.util.*; public class WebServer { public static void main(String args[])throws Exception { //Defining 2 string objects String requestMessageLine;//It will contain the first line in the HTTP message String fileName;//It will contain the file name of the requested file //These are two socket like objects ServerSocket listenSocket=new ServerSocket(9190);//It is created by the server program before receiving a request Socket connectionSocket= listenSocket.accept(); //when the request arrives the accept method listen the socket and create a new object BufferedReader inFromClient=new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));//The http request comes from network through connectionsocket and into infromclient DataOutputStream outToClient=new DataOutputStream(connectionSocket.getOutputStream());// response message goes into outtoclient through socketconnection and into the network requestMessageLine=inFromClient.readLine();//IT reads the first line of the http request it takes input in the form of GET file_name HTTP/1.0 //NOw our server will parse the line to extract the filename StringTokenizer tokenizedLine=new StringTokenizer(requestMessageLine);//The first line of request message to obtain the requested filename if(tokenizedLine.nextToken().equals("GET")) { fileName=tokenizedLine.nextToken(); if(fileName.startsWith("/")==true) fileName=fileName.substring(1); File file=new File(fileName); int numOfBytes=(int)file.length(); FileInputStream inFile=new FileInputStream(fileName);//it attaches a stream infile byte[] fileInBytes=new byte[numOfBytes];//it determine the size of the string inFile.read(fileInBytes); outToClient.writeBytes("HTTP/1.0 200 Document Follows"); if(fileName.endsWith(".jpg")) outToClient.writeBytes("Content-Type: image/jpg\r\n"); if(fileName.endsWith(".gif")) outToClient.writeBytes("Content-Type: image/gif\r\n"); outToClient.writeBytes("Content-Length"+numOfBytes+ "\r\n"); outToClient.writeBytes("\r\n"); outToClient.write(fileInBytes,0,numOfBytes); connectionSocket.close(); } else { System.out.println("Bad request Message"); } listenSocket.close(); } }
/* * Copyright (c) 2013 Google 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 com.google.appengine.demos.websocketchat.message; import com.google.gson.Gson; /** * An interface that is supposed to be passed to {@code ChatSocketServer#sendToClients()} method. */ public interface OutgoingMessage { /** * A type of the message. */ public enum MessageType { /** A normal chat message. */ MESSAGE, /** A message for notifying the participant list. */ PARTICIPANTS, /** A system message. */ SYSTEM, /** A message indicating someone entered the room. */ ENTER, /** A message indicating someone left the room. */ LEAVE, /** A special message for propagating various message between multiple server nodes. */ PROPAGATE } /** * Returns the type of this message. * * @return the type of this message. */ public MessageType getType(); /** * Returns a JSON object that will be sent to the clients. * * @param gson a Gson object for serializing this message. * @return a JSON object that will be sent to the clients. */ public String toJson(Gson gson); /** * Returns whether or not we should send this message to the given chat room. * * @param room a name of the chat room. * @return whether or not we should send this message to the given chat room. */ public boolean shouldSendTo(String room); /** * Returns the name of the chat room that this message belongs to. * * @return the name of the chat room that this message belongs to. */ public String getRoom(); }
package com.fleet.seg.util; import org.apdplat.word.WordSegmenter; import org.apdplat.word.segmentation.Word; import java.util.ArrayList; import java.util.List; /** * Word 分词器 * * @author April Han */ public class WordUtil { public static List<String> seg(String text) { List<String> list = new ArrayList<>(); List<Word> segList = WordSegmenter.seg(text); for (Word word : segList) { list.add(word.getText()); } return list; } public static List<String> segWithStopWords(String text) { List<String> list = new ArrayList<>(); List<Word> segList = WordSegmenter.segWithStopWords(text); for (Word word : segList) { list.add(word.getText()); } return list; } }
package com.niubimq.service; import java.util.List; import org.springframework.stereotype.Service; import com.niubimq.pojo.Consumer; @Service public interface ConsumerManageService { /** * 新增消费者信息 * */ public void addConsumer(Consumer consumer); /** * 删除消费者信息 * */ public void deleteConsumer(Consumer c); /** * 修改消费者信息 * */ public void updateConsumer(Consumer consumer); /** * 查询新增消费者信息 * */ public List<Consumer> showConsumer(); /** * 校验消费者内置参数 * @return */ String validateConsumerParams(Consumer consumer); }
package system.utils; import lombok.extern.slf4j.Slf4j; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import sun.applet.Main; import system.common.JsonData; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.util.*; /** * @Author: mol * @Description: * @Date: create in 13:15 2018/3/15 */ @Slf4j public class ExcelUtil { /** * 文件导入工具类 * @param fileName 文件名 * @param sheetIndex 表索引 从0开始 * @param startRowIndex 开始行的索引号 * @return */ public static JsonData export(String fileName,Integer sheetIndex,Integer startRowIndex)throws Exception{ FileInputStream fileInputStream = null; try { Map<String,List<String>> map = new HashMap<>(); if(fileName.endsWith(".xls") || fileName.endsWith(".xlsx")){ boolean is03Excel = fileName.endsWith(".xls"); Workbook workbook = null; try { fileInputStream = new FileInputStream(fileName); } catch (FileNotFoundException e) { log.error("【导入数据】未找到上传的文件,fileName={}",fileName); return JsonData.createError("未找到文件上传的文件"); } try { workbook = is03Excel?new HSSFWorkbook(fileInputStream):new XSSFWorkbook(fileInputStream); } catch (IOException e) { deleteFile(fileName); log.error("【导入数据】创建工作簿失败,fileName={}",fileName); return JsonData.createError("创建工作簿失败"); } //获取索引为sheetIndex的工作表 Sheet sheet = workbook.getSheetAt(sheetIndex); //循环获取每一行 for(int rowNum = startRowIndex;rowNum <= sheet.getLastRowNum(); rowNum++){ //存放本行每个单元格值得容器 List<String> list = new ArrayList<>(); //获取第rowNum+1行 Row row = sheet.getRow(rowNum); //获取最后一列的索引号 short lastCellNum = row.getLastCellNum(); //遍历本行的每个单元格,获取其值 for(int i = 0; i <= lastCellNum-1; i++){ //获取当前单元格的值 row.getCell(i).setCellType(Cell.CELL_TYPE_STRING); String value = row.getCell(i).getStringCellValue(); //将本单元格的值放入容器 list.add(value); } //将存放本行数据的list放入map中,以当前行为key map.put(rowNum+"",list); } //deleteFile(fileName); //将结果返回给调用者,用于取值并封装对象 return JsonData.createSuccess(map); } deleteFile(fileName); return JsonData.createError("表格格式有误"); } catch (Exception e) { return JsonData.createError("未知异常"); } finally { if(fileInputStream != null){ fileInputStream.close(); } } } private static boolean deleteFile(String fileName){ File file = new File(fileName); if(!file.exists()){ return false; }else{ return file.delete(); } } /*public static void main(String[] args) throws Exception{ String fileName = "E:\\123.xlsx"; JsonData export = export(fileName, 0, 1); Map map = export.toMap(); System.out.println(map.get("status")); //System.out.println(map.get("msg")); Map<String,List<String>> m = (Map<String, List<String>>) map.get("data"); Iterator<Map.Entry<String, List<String>>> iterator = m.entrySet().iterator(); while (iterator.hasNext()){ Map.Entry<String, List<String>> entry = iterator.next(); System.out.println(entry.getValue()); } } */ }
package com.dao; import com.entity.OrdersEntity; import org.hibernate.internal.CriteriaImpl; import java.math.BigDecimal; import java.util.Vector; /** * Created by 滩涂上的芦苇 on 2016/6/8. */ public interface OrderDao { // insert cart into database to become an order public void pay(OrdersEntity order) throws Exception; // query order by username public Vector<OrdersEntity> queryByUsername(String username) throws Exception; public Vector<Integer> queryUserBooks() throws Exception; public Vector<BigDecimal> queryUserPrice() throws Exception; public Vector<Integer> queryUserTimes() throws Exception; // query all orders public Vector<OrdersEntity> queryAll() throws Exception; public Vector<Integer> queryCategoryBooks() throws Exception; public Vector<Integer> queryCategoryTimes() throws Exception; public Vector<Integer> queryBookBooks() throws Exception; public Vector<Integer> queryBookTimes() throws Exception; }
package org.browsexml.timesheetjob.web; import java.beans.PropertyEditorSupport; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; public class FulltimeEditor extends PropertyEditorSupport { private static Log log = LogFactory.getLog(FulltimeEditor.class); public void setAsText(String text) { log.debug("set value: " + text); new Exception("HERE").printStackTrace(); if (text == null) { log.debug("setting to false"); setValue(false); } boolean value = text.equals("F"); log.debug("setting to " + value); setValue(value); } public String getAsText() { Boolean value = (Boolean) getValue(); log.debug("get value: " + value); if (value == null) { return ""; } return value?"F":"S"; } }
/** * Created by Tom Remeeus on 3-5-2016. */ package nl.computerinfor.groamchat.clients; import java.io.*; import java.net.*; import java.util.*; public class ChatClient extends Protocol { private Socket connection; private DataInputStream input; private DataOutputStream output; private List<String> messages; private List<String> unrelatedMessages; final private String clientName; final private String otherClientName; public ChatClient(String thisUserName, String otherUserName) { this.clientName = thisUserName; this.otherClientName = otherUserName; messages = new ArrayList<>(); unrelatedMessages = new ArrayList<>(); connect(); sendUserData(); receiveData(); } //connect client to server private void connect() { try { connection = new Socket(ipAddress(), portAddress()); output = new DataOutputStream(connection.getOutputStream()); } catch(IOException IOe) { System.out.println(clientName + ": " + IOe); } } //send userdata to server private void sendUserData() { String data = startProtocol() + "|" + clientName + "|" + null + "|" + sendClientDataProtocol() + "|" + null + "|" + endProtocol(); try { output.writeUTF(data); output.flush(); } catch(Exception e) { System.out.println(clientName + ": " + e); } } public void sendMessage(String message, String receiver) { String data = startProtocol() + "|" + clientName + "|" + receiver + "|" + messageProtocol() + "|" + message + "|" + endProtocol(); try { output.writeUTF(data); output.flush(); messages.add(clientName + " (You): " + message); } catch(Exception e) { System.out.println(clientName + ": " + e); } } private void receiveData() { new Thread() { @Override public void run() { while(true) { try { input = new DataInputStream(connection.getInputStream()); String dataString = input.readUTF(); String[] dataSegments = dataString.split("\\|", -1); //check if command is currupt if(dataSegments.length == 6) { if(dataSegments[0].equals(startProtocol()) && dataSegments[5].equals(endProtocol())) { int command = Integer.parseInt(dataSegments[3]); switch (command) { case 1: receiveMessage(dataSegments[1], dataSegments[2], dataSegments[4]); break; } } } } catch (Exception e) { System.out.println(clientName + ": " + e); } } } }.start(); } private void receiveMessage(String sender, String receiver, String message) { if(sender.equals(otherClientName)) { messages.add(sender + ": " + message); } if(!sender.equals(otherClientName)) { unrelatedMessages.add(sender + ": " + message); } } public List getMessages() { return messages; } public List getUnrelatedMessages() { return unrelatedMessages; } public void setMessages(String inputMessages) { String messagesString = inputMessages; messagesString = messagesString.replace("[", ""); messagesString = messagesString.replace("]", ""); String[] messageArray = messagesString.split(", "); for(int i = 0; i < messageArray.length; i ++) { messages.add(messageArray[i]); } } public void closeConnection() { String data = startProtocol() + "|" + clientName + "|" + null + "|" + removeClientFromServerProtocol() + "|" + null + "|" + endProtocol(); try { output.writeUTF(data); output.flush(); } catch(Exception e) { System.out.println(clientName + ": " + e); } } }
/*Create loops to print out a series of numbers, then print out a series of symbols*/ public class GettingLoopy{ public static void main(String []args){ //Step 1 int counter = 1; while (counter<8){ System.out.print(counter); counter++; } while (counter<8){ System.out.print("7"); counter++; } } }
package util; import com.google.common.util.concurrent.ThreadFactoryBuilder; import java.util.ArrayList; import java.util.List; import java.util.concurrent.*; /** * 线程池工具类 * * @author yinyiyun * @date 2018/5/3 9:18 */ public class WorkThreadPool { /** * 线程池 */ private ExecutorService pool; /** * 任务返回值集合 */ private List<Future> listTask = new ArrayList<>(); /** * 创建默认线程池 * * @param threadName 线程名称 * @param size 循环的size * @param maximumSize 最大线程数 */ public WorkThreadPool(String threadName, Integer size, Integer maximumSize) { int coorPoolSize = Math.min(size, maximumSize); this.pool = getPool(threadName, coorPoolSize, maximumSize, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>()); } /** * 根据参数创建线程池 * * @param threadName 线程名称 * @param size 循环的size * @param maximumSize 最大线程数 * @param keepAliveTime 当前线程池线程总数达到核心线程数时,终止多余的空闲线程的时间 * @param timeUnit keepAliveTime参数的时间单位 * @param deque 任务队列 如果当前线程池达到核心线程数量corePoolSize后,且当前所有线程都处于活动状态时,则将新加入的任务放到此队列中 */ public WorkThreadPool(String threadName, Integer size, Integer maximumSize, Long keepAliveTime, TimeUnit timeUnit, BlockingQueue<Runnable> deque) { int coorPoolSize = Math.min(size, maximumSize); this.pool = getPool(threadName, coorPoolSize, maximumSize, keepAliveTime, timeUnit, deque); } /** * 创建线程池 * * @param threadName 线程名称 * @param coorPoolSize 线程数 * @param maximumSize 最大线程数 * @param keepAliveTime 当前线程池线程总数达到核心线程数时,终止多余的空闲线程的时间 * @param timeUnit keepAliveTime参数的时间单位 * @param deque 任务队列 如果当前线程池达到核心线程数量corePoolSize后,且当前所有线程都处于活动状态时,则将新加入的任务放到此队列中 * @return */ private ExecutorService getPool(String threadName, Integer coorPoolSize, Integer maximumSize, Long keepAliveTime, TimeUnit timeUnit, BlockingQueue<Runnable> deque) { // 线程工厂 - 定义线程名称 ThreadFactory namedThreadFactory = new ThreadFactoryBuilder().setNameFormat("pool-%d-" + threadName).build(); return new ThreadPoolExecutor(coorPoolSize, maximumSize, keepAliveTime, timeUnit, deque, namedThreadFactory); } /** * 执行任务 * * @param worker */ public void submit(Callable worker) { // 执行任务并获取Future对象 Future f1 = pool.submit(worker); // 将任务结果加入集合 listTask.add(f1); } /** * 线程池终止(在终止前允许执行以前提交的任务) */ public void shutdown() { pool.shutdown(); } /** * 获取线程执行结果并终止线程 */ public void getAndShutdown() { // 获取所有并发任务的运行结果 for (Future f : listTask) { try { f.get(); } catch (Exception e) { e.printStackTrace(); } } this.shutdown(); } public static void main(String[] args) { WorkThreadPool pool = new WorkThreadPool("test", 4, 8); int[] arr = new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; for (int i : arr) { pool.submit(() -> { System.out.println(i); return null; }); } pool.getAndShutdown(); } }
/** * */ package com.goodhealth.algorithm.LintCode_Tree; /** * @author 24663 * @date 2018年9月4日 * @Description 927. 翻转字符串II 给定输入的字符数组,逐词翻转数组。单词被定义为不包含空格的字符串. 输入字符数组不包含前导或尾部空格,单词总是用单个空格分隔。 样例 给定 s = "the sky is blue", 翻转之后 : "blue is sky the" 挑战 你能在不分配额外空间的情况下原地解决这个问题吗? */ public class TI_924 { private void reverse(char[] str, int start, int end) { for (int i = start, j = end; i < j; i++, j--) { char temp = str[i]; str[i]=str[j]; str[j]=temp; } } public char[] reverseWords(char[] str) { int pre=0; int next=0; for (int i = 0; i < str.length; i++) { if (str[i]==' '&&pre==0&&next==0) { pre=i; reverse(str, 0, pre-1); } if (str[i]==' '&&pre!=0&&next==0) { next=i; reverse(str, pre+1,next-1); } if (str[i]==' '&&pre!=0&&next!=0) { pre=next; next=i; reverse(str, pre+1,next-1); } } reverse(str, next+1, str.length-1); reverse(str,0,str.length-1); return str; } }
package Exams.June16_2019.healthyHeaven; import java.util.ArrayList; import java.util.List; public class Restaurant { private String name; private List<Salad> data; public Restaurant(String name) { this.name = name; this.data = new ArrayList<>(); } public void add(Salad salad) { this.data.add(salad); } public boolean buy(String name) { for (int i = 0; i < this.data.size(); i++) { if (this.data.get(i).getName().equals(name)) { this.data.remove(i); return true; } } return false; } public Salad getHealthiestSalad() { int less = Integer.MAX_VALUE; String healthySalad = ""; int index = 0; for (Salad datum : this.data) { if (datum.getTotalCalories() < less) { less = datum.getTotalCalories(); healthySalad = datum.getName(); index = this.data.indexOf(datum); } } return this.data.get(index); } public String generateMenu() { StringBuilder sb1 = new StringBuilder(); sb1.append(String.format("%s have %d salads:", this.name, this.data.size())).append(System.lineSeparator()); sb1.trimToSize(); if (this.data.size()>0) { for (Salad datum : this.data) { sb1.append(datum.toString()); } } return sb1.toString().trim(); } }
package com.tencent.mm.plugin.card.sharecard.model; import com.tencent.mm.plugin.card.model.n.a; /* synthetic */ class k$1 { public static final /* synthetic */ int[] hwe = new int[a.axf().length]; static { try { hwe[a.hwN - 1] = 1; } catch (NoSuchFieldError e) { } try { hwe[a.hwO - 1] = 2; } catch (NoSuchFieldError e2) { } try { hwe[a.hwP - 1] = 3; } catch (NoSuchFieldError e3) { } } }
package com.rsm.yuri.projecttaxilivredriver.avaliation; /** * Created by yuri_ on 07/03/2018. */ public class AvaliationInteractorImpl implements AvaliationInteractor { private AvaliationRepository avaliationRepository; public AvaliationInteractorImpl(AvaliationRepository avaliationRepository) { this.avaliationRepository = avaliationRepository; } @Override public void execute(String email) { avaliationRepository.retrieveRatings(email); } }
/* * 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 anikolic_zadaca_1; import java.time.LocalTime; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * * @author Ana */ public class Program { private int id; private String naziv; private List<Emisija> emisijePrograma; //private Map<Integer, List<PrikazEmisije>> prikaz; private Map<Integer, PrikazEmisije> prikaz; private LocalTime pocetakPrograma; private LocalTime krajPrograma; public Program() { emisijePrograma = new ArrayList<>(); prikaz = new HashMap<>(); } public Program(int id, String naziv, List<Emisija> emisijePrograma, Map<Integer, PrikazEmisije> prikaz, LocalTime pocetakPrograma, LocalTime krajPrograma) { this.id = id; this.naziv = naziv; this.emisijePrograma = emisijePrograma; this.prikaz = prikaz; this.pocetakPrograma = pocetakPrograma; this.krajPrograma = krajPrograma; } public int getId() { return id; } public void setId(int id) { this.id = id; } public List<Emisija> getEmisijePrograma() { return emisijePrograma; } public void setEmisijePrograma(List<Emisija> emisijePrograma) { this.emisijePrograma = emisijePrograma; } public LocalTime getPocetakPrograma() { return pocetakPrograma; } public void setPocetakPrograma(LocalTime pocetakPrograma) { this.pocetakPrograma = pocetakPrograma; } public String getNaziv() { return naziv; } public void setNaziv(String naziv) { this.naziv = naziv; } public LocalTime getKrajPrograma() { return krajPrograma; } public void setKrajPrograma(LocalTime krajPrograma) { this.krajPrograma = krajPrograma; } public Map<Integer, PrikazEmisije> getPrikaz() { return prikaz; } public void setPrikaz(Map<Integer, PrikazEmisije> prikaz) { this.prikaz = prikaz; } }
package tachyon.worker.eviction; import java.util.Collection; import java.util.Map.Entry; import java.util.Set; import tachyon.Pair; import tachyon.master.BlockInfo; import tachyon.worker.hierarchy.StorageDir; /** * Base class for evicting blocks by LRU strategy. */ public abstract class EvictLRUBase implements EvictStrategy { private final boolean mLastTier; EvictLRUBase(boolean lastTier) { mLastTier = lastTier; } /** * Check if current block can be evicted * * @param blockId Id of the block * @param pinList list of pinned files * @return true if the block can be evicted, false otherwise */ boolean blockEvictable(long blockId, Set<Integer> pinList) { if (mLastTier && pinList.contains(BlockInfo.computeInodeId(blockId))) { return false; } return true; } /** * Get the oldest access information of certain StorageDir * * @param curDir current StorageDir * @param toEvictBlockIds Ids of blocks that have been selected to be evicted * @param pinList list of pinned files * @return the oldest access information of current StorageDir */ Pair<Long, Long> getLRUBlock(StorageDir curDir, Collection<Long> toEvictBlockIds, Set<Integer> pinList) { long blockId = -1; long oldestTime = Long.MAX_VALUE; Set<Entry<Long, Long>> accessTimes = curDir.getLastBlockAccessTimeMs(); for (Entry<Long, Long> accessTime : accessTimes) { if (toEvictBlockIds.contains(accessTime.getKey())) { continue; } if (accessTime.getValue() < oldestTime && !curDir.isBlockLocked(accessTime.getKey())) { if (blockEvictable(accessTime.getKey(), pinList)) { oldestTime = accessTime.getValue(); blockId = accessTime.getKey(); } } } return new Pair<Long, Long>(blockId, oldestTime); } }
package sapronov.pavel.managementrestapi.repositories; import org.springframework.data.repository.PagingAndSortingRepository; import org.springframework.stereotype.Repository; import sapronov.pavel.managementrestapi.entities.Communication; @Repository public interface CommunicationRepository extends PagingAndSortingRepository<Communication, Long> { }
package camel.serial; import java.io.OutputStream; import org.apache.camel.Exchange; import org.apache.camel.Suspendable; import org.apache.camel.impl.DefaultProducer; import org.apache.camel.util.URISupport; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class SerialProducer extends DefaultProducer implements Suspendable { private static final Logger LOG = LoggerFactory.getLogger(SerialProducer.class); private static final boolean DO_TIMESLOT_REQUEST = true; private static final byte[] TIMESLOT_REQUEST = {0x1}; private OutputStream out; private SerialEndpoint endpoint; public SerialProducer(SerialEndpoint endpoint, OutputStream out) { super(endpoint); this.endpoint = endpoint; this.out = out; } @Override public void process(Exchange exchange) throws Exception { if (out == null) { LOG.error("Can not send serial data, no OutputStream!"); return; } String dataMessage; if (exchange.hasOut()) { dataMessage = exchange.getOut().getBody(String.class); } else { dataMessage = exchange.getIn().getBody(String.class); } if (!dataMessage.endsWith("\n")) { dataMessage += "\n"; } if (DO_TIMESLOT_REQUEST) { out.write(TIMESLOT_REQUEST); out.flush(); delayMillis(15); } out.write(dataMessage.getBytes()); LOG.debug("Serial data sent: [{}]", dataMessage.toString()); } private void delayMillis(long millis) { try { Thread.sleep(millis); } catch (InterruptedException e) { LOG.warn("Sleep failure", e); } } // @Override // protected void doStop() throws Exception { // super.doStop(); // // if (out != null) { // try { // LOG.debug("Close outputstream for {}", URISupport.sanitizeUri(endpoint.getEndpointUri())); // out.close(); // } catch (IOException e) { // LOG.warn("Error closing input stream", e); // } finally { // out = null; // } // } // // try { // endpoint.stop(); // } catch (Exception e) { // LOG.error("Error stopping endpoint", e); // } // } @Override protected void doSuspend() { LOG.debug("Suspend SerialProducer..."); try { endpoint.serialSuspend(); super.doSuspend(); } catch (Exception e) { LOG.error("Error suspending SerialProducer", e); } } @Override protected void doResume() { LOG.debug("Resume SerialProducer..."); try { endpoint.serialResume(); super.doResume(); } catch (Exception e) { LOG.error("Error resuming SerialProducer", e); } } protected void setOut(OutputStream out) { this.out = out; } @Override public String toString() { return "SerialProducer[" + URISupport.sanitizeUri(getEndpoint().getEndpointUri()) + "]"; } }
package com.koreait.db; import java.sql.Connection; import java.sql.PreparedStatement; public class Ex05_insert { public static void main(String[] args) { Connection conn = null; PreparedStatement ps = null; String[] sqls = { "insert into bbs_t (b_idx, writer, title, content, pw, hit, reg_date) values (bbs_seq.nextval, '작성자1', '공지1', '공지입니다.', '1111', 0, sysdate)", "insert into bbs_t (b_idx, writer, title, content, pw, hit, reg_date) values (bbs_seq.nextval, '작성자2', '공지2', '공지입니다.', '1111', 0, sysdate)", "insert into bbs_t (b_idx, writer, title, content, pw, hit, reg_date) values (bbs_seq.nextval, '작성자3', '공지3', '공지입니다.', '1111', 0, sysdate)", "insert into bbs_t (b_idx, writer, title, content, pw, hit, reg_date) values (bbs_seq.nextval, '작성자4', '공지4', '공지입니다.', '1111', 0, sysdate)", "insert into bbs_t (b_idx, writer, title, content, pw, hit, reg_date) values (bbs_seq.nextval, '작성자5', '공지5', '공지입니다.', '1111', 0, sysdate)", "insert into bbs_t (b_idx, writer, title, content, pw, hit, reg_date) values (bbs_seq.nextval, '작성자6', '공지6', '공지입니다.', '1111', 0, sysdate)", "insert into bbs_t (b_idx, writer, title, content, pw, hit, reg_date) values (bbs_seq.nextval, '작성자7', '공지7', '공지입니다.', '1111', 0, sysdate)", "insert into bbs_t (b_idx, writer, title, content, pw, hit, reg_date) values (bbs_seq.nextval, '작성자8', '공지8', '공지입니다.', '1111', 0, sysdate)", "insert into bbs_t (b_idx, writer, title, content, pw, hit, reg_date) values (bbs_seq.nextval, '작성자9', '공지9', '공지입니다.', '1111', 0, sysdate)", "insert into bbs_t (b_idx, writer, title, content, pw, hit, reg_date) values (bbs_seq.nextval, '작성자10', '공지10', '공지입니다.', '1111', 0, sysdate)", "insert into bbs_t (b_idx, writer, title, content, pw, hit, reg_date) values (bbs_seq.nextval, '작성자11', '공지11', '공지입니다.', '1111', 0, sysdate)", "insert into bbs_t (b_idx, writer, title, content, pw, hit, reg_date) values (bbs_seq.nextval, '작성자12', '공지12', '공지입니다.', '1111', 0, sysdate)", "insert into bbs_t (b_idx, writer, title, content, pw, hit, reg_date) values (bbs_seq.nextval, '작성자13', '공지13', '공지입니다.', '1111', 0, sysdate)", "insert into bbs_t (b_idx, writer, title, content, pw, hit, reg_date) values (bbs_seq.nextval, '작성자14', '공지14', '공지입니다.', '1111', 0, sysdate)", "insert into bbs_t (b_idx, writer, title, content, pw, hit, reg_date) values (bbs_seq.nextval, '작성자15', '공지15', '공지입니다.', '1111', 0, sysdate)", "insert into bbs_t (b_idx, writer, title, content, pw, hit, reg_date) values (bbs_seq.nextval, '작성자16', '공지16', '공지입니다.', '1111', 0, sysdate)", "insert into bbs_t (b_idx, writer, title, content, pw, hit, reg_date) values (bbs_seq.nextval, '작성자17', '공지17', '공지입니다.', '1111', 0, sysdate)", "insert into bbs_t (b_idx, writer, title, content, pw, hit, reg_date) values (bbs_seq.nextval, '작성자18', '공지18', '공지입니다.', '1111', 0, sysdate)", "insert into bbs_t (b_idx, writer, title, content, pw, hit, reg_date) values (bbs_seq.nextval, '작성자19', '공지19', '공지입니다.', '1111', 0, sysdate)", "insert into bbs_t (b_idx, writer, title, content, pw, hit, reg_date) values (bbs_seq.nextval, '작성자20', '공지20', '공지입니다.', '1111', 0, sysdate)", "insert into bbs_t (b_idx, writer, title, content, pw, hit, reg_date) values (bbs_seq.nextval, '작성자21', '공지21', '공지입니다.', '1111', 0, sysdate)" }; int result = 0; int count = 0; try { conn = DBConnect.getConnection(); for ( String sql : sqls ) { ps = conn.prepareStatement(sql); result = ps.executeUpdate(); if ( result > 0 ) { System.out.println("추가가 성공하였습니다. 현재 " + (++count) + "게시글 등록"); } } } catch (Exception e) { e.printStackTrace(); } finally { try { if (ps != null) ps.close(); if (conn != null) conn.close(); } catch (Exception e) { e.printStackTrace(); } } } }
package com.elvarg; import com.elvarg.world.model.Position; /** * A class containing different attributes * which affect the game in different ways. * @author Professor Oak */ public class GameConstants { /** * The directory of the definition files. */ public static final String DEFINITIONS_DIRECTORY = "./data/definitions/"; /** * The directory of the clipping files. */ public static final String CLIPPING_DIRECTORY = "./data/clipping/"; /** * Is JAGGRAB enabled? */ public static final boolean JAGGRAB_ENABLED = false; /** * The game engine cycle rate in milliseconds. */ public static final int GAME_ENGINE_PROCESSING_CYCLE_RATE = 600; /** * The maximum amount of iterations that should occur per queue each cycle. */ public static final int QUEUED_LOOP_THRESHOLD = 50; /** * The current game/client version. */ public static final int GAME_VERSION = 3; /** * The secure game UID /Unique Identifier/ */ public static final int GAME_UID = 4 >> 1; /** * The default position in game. */ public static final Position DEFAULT_POSITION = new Position(3093, 3509); /** * Blood money. * Current currency ingame. */ public static final int BLOOD_MONEY = 13307; /** * Should the inventory be refreshed immediately * on switching items or should it be delayed * until next game cycle? */ public static final boolean QUEUE_SWITCHING_REFRESH = false; /** * Multiplies the experience gained. */ public static final double EXP_MULTIPLIER = 6; /** * The tab interfaces in game. * {Gameframe} * [0] = tab Id, [1] = tab interface Id */ public static final int TAB_INTERFACES[][] = { {0, 2423}, {1, 24000}, {2, 31000}, {3, 3213}, {4, 1644}, {5, 5608}, {6, -1}, //Row 1 {7, 37128}, {8, 5065}, {9, 5715}, {10, 2449}, {11, 42500}, {12, 147}, {13, 32000} //ROw 2 }; /** * Spawnable Items */ public static final int[] ALLOWED_SPAWNS = { 3144,391,397,385,7946,2436,2440,2442,9739,3040,2444,2452,2448,6685,2450,3024,2434, //potions and food 1149,3140,4087,4585,1187,11840, //dragon 1163,1127,1079,1093,1201,4131, //rune 1161,1123,1073,1091,1199,4129, //addy 1159,1121,1071,1091,1197,4127, //mithril 1165,1125,1077,1089,1195,4125, //black 1157,1119,1069,1083,1193,4123, //steel 1153,1115,1067,1081,1191,4121, //iron 1155,1117,1075,1087,1189,4119, // bronze 4587,1333,1331,1329,1327,1325,1323,1321, // scimitars 21009,1289,1287,1285,1283,1281,1279,1277, // swords 1305,1303,1301,1299,1297,1295,1293,1291, // longswords 7158,1319,1317,1315,1313,1311,1309,1307, // 2hs 1347,1345,1343,1341,1339,1335,1337, // warhammers 5698,1215,1213,1211,1209,1217,1207,1203,1205, // daggers 1434,1432,1430,1428,1426,1424,1420,1422, // maces 7462,7461,7460,7459,7458,7457,7456,7455,7454, // gloves 11126, 2550, 4151,4153,10887, // special weapons 6528,6527,6526,6525,6524,6523,6522, // obby items 9747,9748,9750,9751,9753,9754,9756,9757,9759,9760,9762,9763,6568,2412,2413,2414, // capes 8850,8849,8848,8847,8846,8845,8844,10828,3755,3753,3751,3749,3748,12831,12829, 3040, 3842, 3844, 12608, 12610, 12612, 11235,859,855,851,847,845,841, 861,857,853,849,843,841, 9185,9183,9181,9179,9177,9174, 11212,892,890,888,886,884,882, 9245,9244,9243,9242,9241,9240,9239,9238,9237,9236,9305,9144,9143,9142,9141,9140,877, 5667,868,867,866,869,865,863,864, 19484, 5653,830,829,828,827,826,825, 11230,811,810,809,808,807,806, 10368,10370,10372,10374,10376,10378,10380,10382,10384,10386,10388,10390,12490,12492,12494,12496,12498,12500,12502,12504,12506,12508,12510,12512, 2503,2497,2491,2501,2495,2489,2499,2493,2487,1135,1099,1065, 6322,6324,6326,6328,6330,10954,10956,10958,6131,6133,6135,1169,1133,1097,1131,1167,1129,1095, 10499, 4675,1381,1383,1385,1387,1379, 4089,4091,4093,4095,4097,4099,4101,4103,4105,4107,4109,4111,4113,4115,4117, 7400,7399,7398, 6918,6916,6924,6922,6920,6109,6107,6108,6110,6106,6111,544,542,1035,1033,579,577,1011, 554, 555, 556, 557, 558, 559, 561, 563, 562, 560, 565, 566, 9075, 1704, 1731, 1725, 1727, 1729, }; }
package com.mighty.springcloud.feign.service; import com.mighty.springcloud.feign.helloserviceapi.service.HelloService; import org.springframework.cloud.openfeign.FeignClient; /** * RefactorHelloService * * @author mighty * @create 2018-12-24 9:59 */ @FeignClient("hello-service") public interface RefactorHelloService extends HelloService { }
package com.city.beijing.task; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; /** * Created by liuyang on 16-7-4. */ @Component public class taskService { // @Autowired // private UserTaskService userTaskService; @Scheduled(cron = "0 */1 * * * ? ") public void userTask(){ System.out.println("execute"); // userTaskService.insertData(); } }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.mapred; import static org.junit.Assert.*; import java.io.File; import java.io.IOException; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileStatus; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.FileUtil; import org.apache.hadoop.fs.Path; import org.apache.hadoop.fs.RawLocalFileSystem; import org.apache.hadoop.mapreduce.MRConfig; import org.junit.Test; import org.junit.Before; /** * Tests for the correct behavior of the TaskTracker starting up with * respect to its local-disk directories. */ public class TestTaskTrackerDirectories { private final String TEST_DIR = new File("build/test/testmapredlocaldir") .getAbsolutePath(); @Before public void deleteTestDir() throws IOException { FileUtil.fullyDelete(new File(TEST_DIR)); assertFalse("Could not delete " + TEST_DIR, new File(TEST_DIR).exists()); } @Test public void testCreatesLocalDirs() throws Exception { Configuration conf = new Configuration(); String[] dirs = new String[] { TEST_DIR + "/local1", TEST_DIR + "/local2" }; conf.setStrings(MRConfig.LOCAL_DIR, dirs); setupTaskController(conf); for (String dir : dirs) { checkDir(dir); } } @Test public void testFixesLocalDirPermissions() throws Exception { Configuration conf = new Configuration(); String[] dirs = new String[] { TEST_DIR + "/badperms" }; new File(dirs[0]).mkdirs(); FileUtil.chmod(dirs[0], "000"); conf.setStrings(MRConfig.LOCAL_DIR, dirs); setupTaskController(conf); for (String dir : dirs) { checkDir(dir); } } @Test public void testCreatesLogDir() throws Exception { File dir = TaskLog.getUserLogDir(); FileUtil.fullyDelete(dir); setupTaskController(new Configuration()); checkDir(dir.getAbsolutePath()); } /** * If the log dir can't be created, the TT should fail to start since * it will be unable to localize or run tasks. */ @Test public void testCantCreateLogDir() throws Exception { File dir = TaskLog.getUserLogDir(); FileUtil.fullyDelete(dir); assertTrue("Making file in place of log dir", dir.createNewFile()); try { setupTaskController(new Configuration()); fail("Didn't throw!"); } catch (IOException ioe) { System.err.println("Got expected exception"); ioe.printStackTrace(System.out); } } @Test public void testFixesLogDirPermissions() throws Exception { File dir = TaskLog.getUserLogDir(); FileUtil.fullyDelete(dir); dir.mkdirs(); FileUtil.chmod(dir.getAbsolutePath(), "000"); setupTaskController(new Configuration()); checkDir(dir.getAbsolutePath()); } private void setupTaskController(Configuration conf) throws IOException { TaskController tc = new DefaultTaskController(); tc.setConf(conf); tc.setup(); } private void checkDir(String dir) throws IOException { FileSystem fs = RawLocalFileSystem.get(new Configuration()); File f = new File(dir); assertTrue(dir + "should exist", f.exists()); FileStatus stat = fs.getFileStatus(new Path(dir)); assertEquals(dir + " has correct permissions", 0755, stat.getPermission().toShort()); } }
package com.mapping.oneTomany.Demo; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; import com.mapping.entity.Course; import com.mapping.entity.Instructor; import com.mapping.entity.InstructorDetail; public class CreateCouseDemo { public static void main(String[] args) { SessionFactory factory=new Configuration().configure().addAnnotatedClass(Instructor.class) .addAnnotatedClass(InstructorDetail.class) .addAnnotatedClass(Course.class) .buildSessionFactory(); Session session =factory.getCurrentSession(); try { session.beginTransaction(); // get Instructor from DB Instructor instructor=session.get(Instructor.class, 5); // create some cources Course course1=new Course("Guiter Trianer"); Course course2=new Course("Pinball Trianer"); // add cources to instructor instructor.add(course1); instructor.add(course2); // bi -directioanl // save the courrse session.save(course1); session.save(course2); session.getTransaction().commit(); } catch (Exception e) { } finally { // add clean up code session.close(); factory.close(); } } }
package c04; public class a3 { public static void main(String[] args) { // 변수 생성 double x = 7.0 / 2.0; // 3.5 double y = 7 / 2; // 3 => (자동 변환) => 3.0 // 결과 출력 System.out.printf("x = %f, y = %f", x, y); } }
/*---------------------------------------------------------------- * Author: Junjiajia Long * Written: 1/25/2015 * Last updated: 1/30/2015 * * Compilation: javac PercolationStats.java * Execution: java PercolationStats 200 100 *----------------------------------------------------------------*/ public class PercolationStats { private int T; private double m; // calculate mean private double std; // calculate stddev public PercolationStats(int N, int T) {// perform T independent experiments on an N-by-N grid if (N <= 0) throw new IllegalArgumentException("Grid size N must be positive"); if (T <= 0) throw new IllegalArgumentException ("Number of independent computations T must be positive"); this.T = T; Percolation[] experiments = new Percolation[T]; double[] x = new double[T]; for (int t = 0; t < T; t++) // perform each experiment { experiments[t] = new Percolation(N); x[t] = 0; while (!experiments[t].percolates()) // open site until percolation { // choose a site randomly and open int i = StdRandom.uniform(1,N+1); int j = StdRandom.uniform(1,N+1); //StdOut.print(i); //StdOut.print(" "); //StdOut.println(j); // be careful not to double count if (!experiments[t].isOpen(i,j)) { experiments[t].open(i,j); x[t]++; // add to total number of open sites } } x[t] /= (N*N); } m = StdStats.mean(x); std = StdStats.stddev(x); } public double mean() // sample mean of percolation threshold { return m; } public double stddev() // sample standard deviation of percolation threshold { return std; } public double confidenceLo() // low endpoint of 95% confidence interval { return m - 1.96*std/Math.sqrt(T); } public double confidenceHi() // high endpoint of 95% confidence interval { return m + 1.96*std/Math.sqrt(T); } public static void main(String[] args) // test client (described below) { int T; int N; if (args.length < 2) T = 100; // set default T else T = Integer.parseInt(args[1]); if (args.length < 1) N = 200; // set default N else N = Integer.parseInt(args[0]); // perform computational experiments PercolationStats pStats = new PercolationStats(N, T); // output stats StdOut.print("mean = "); StdOut.println(pStats.mean()); StdOut.print("stddev = "); StdOut.println(pStats.stddev()); StdOut.print("95% confidence interval = "); StdOut.print(pStats.confidenceLo()); StdOut.print(", "); StdOut.println(pStats.confidenceHi()); } }
package net.julisapp.riesenkrabbe.views.supportViews; import android.app.Activity; import android.app.Dialog; import android.content.Context; import android.content.DialogInterface; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.v4.app.DialogFragment; import android.support.v4.app.Fragment; import android.support.v7.app.AlertDialog; import android.widget.ArrayAdapter; import net.julisapp.riesenkrabbe.R; import net.julisapp.riesenkrabbe.background.utilities.GeneralUtilities; import java.util.ArrayList; /** * Dialog used by the user to select the eventtype. */ public class PickerDialogFragment extends DialogFragment { public static final String KEY_PICKER_TYPE = "type-of-pickers"; public static final int PICKER_TYPE = 0; public static final int PICKER_FORMATION_USER = 1; public static final int PICKER_FORMATION_EVENT = 2; public interface listPickerCallback { void onPicked(String text, int type); } @NonNull @Override public Dialog onCreateDialog(Bundle savedInstanceState) { int type = getArguments().getInt(KEY_PICKER_TYPE); return buildDialog(type).create(); } private AlertDialog.Builder buildDialog(final int typeOfPicker) { // Type indicates if we're called by a fragment or activity final Fragment callerFormation = getTargetFragment(); final Activity callerActivity = getActivity(); Context context = getContext(); AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); switch (typeOfPicker) { case PICKER_TYPE: final ArrayAdapter<String> choicesTypeAdapter = new ArrayAdapter<>(context, android.R.layout.select_dialog_item); ArrayList<String> eventTypes = GeneralUtilities.getEventTypes(context); choicesTypeAdapter.addAll(eventTypes); String titleType = getString(R.string.creator_picker_eventtype); builder.setTitle(titleType); builder.setAdapter(choicesTypeAdapter, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { listPickerCallback callback = (listPickerCallback) callerFormation; String type = choicesTypeAdapter.getItem(which); callback.onPicked(type, typeOfPicker); } }); break; case PICKER_FORMATION_USER: final ArrayAdapter<String> choicesFormationUserAdapter = new ArrayAdapter<>(context, android.R.layout.select_dialog_item); ArrayList<String> formationsUser = GeneralUtilities.getFormationsDistrict(context); choicesFormationUserAdapter.addAll(formationsUser); String titleFormationUser = getString(R.string.user_edit_formation_title); builder.setTitle(titleFormationUser); builder.setAdapter(choicesFormationUserAdapter, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { listPickerCallback callback = (listPickerCallback) callerActivity; String type = choicesFormationUserAdapter.getItem(which); callback.onPicked(type, typeOfPicker); } }); break; case PICKER_FORMATION_EVENT: final ArrayAdapter<String> choicesAdapter = new ArrayAdapter<>(context, android.R.layout.select_dialog_item); ArrayList<String> formationsEvent = GeneralUtilities.getFormationsEditRights(context); choicesAdapter.addAll(formationsEvent); String title = getString(R.string.creator_title_organiser_selector); builder.setTitle(title); builder.setAdapter(choicesAdapter, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { listPickerCallback callback = (listPickerCallback) callerFormation; String type = choicesAdapter.getItem(which); callback.onPicked(type, typeOfPicker); } }); break; } return builder; } }
package com.playtika.secure.service; import com.playtika.secure.entity.User; public interface UserService { User getUser(String login); }
package com.phone1000.martialstudyself.interfaces; /** * Created by 马金利 on 2016/12/2. */ public interface GridViewItemClick { void itemClickListener(int tag); }
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2015.09.03 at 09:19:50 PM EDT // package org.oasisopen.xliff; import javax.xml.bind.annotation.XmlEnum; import javax.xml.bind.annotation.XmlEnumValue; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for state-qualifierValueList. * * <p>The following schema fragment specifies the expected content contained within this class. * <p> * <pre> * &lt;simpleType name="state-qualifierValueList"> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}NMTOKEN"> * &lt;enumeration value="exact-match"/> * &lt;enumeration value="fuzzy-match"/> * &lt;enumeration value="id-match"/> * &lt;enumeration value="leveraged-glossary"/> * &lt;enumeration value="leveraged-inherited"/> * &lt;enumeration value="leveraged-mt"/> * &lt;enumeration value="leveraged-repository"/> * &lt;enumeration value="leveraged-tm"/> * &lt;enumeration value="mt-suggestion"/> * &lt;enumeration value="rejected-grammar"/> * &lt;enumeration value="rejected-inaccurate"/> * &lt;enumeration value="rejected-length"/> * &lt;enumeration value="rejected-spelling"/> * &lt;enumeration value="tm-suggestion"/> * &lt;/restriction> * &lt;/simpleType> * </pre> * */ @XmlType(name = "state-qualifierValueList") @XmlEnum public enum StateQualifierValueList { /** * Indicates an exact match. An exact match occurs when a source text of a segment is exactly the same as the source text of a segment that was translated previously. * */ @XmlEnumValue("exact-match") EXACT_MATCH("exact-match"), /** * Indicates a fuzzy match. A fuzzy match occurs when a source text of a segment is very similar to the source text of a segment that was translated previously (e.g. when the difference is casing, a few changed words, white-space discripancy, etc.). * */ @XmlEnumValue("fuzzy-match") FUZZY_MATCH("fuzzy-match"), /** * Indicates a match based on matching IDs (in addition to matching text). * */ @XmlEnumValue("id-match") ID_MATCH("id-match"), /** * Indicates a translation derived from a glossary. * */ @XmlEnumValue("leveraged-glossary") LEVERAGED_GLOSSARY("leveraged-glossary"), /** * Indicates a translation derived from existing translation. * */ @XmlEnumValue("leveraged-inherited") LEVERAGED_INHERITED("leveraged-inherited"), /** * Indicates a translation derived from machine translation. * */ @XmlEnumValue("leveraged-mt") LEVERAGED_MT("leveraged-mt"), /** * Indicates a translation derived from a translation repository. * */ @XmlEnumValue("leveraged-repository") LEVERAGED_REPOSITORY("leveraged-repository"), /** * Indicates a translation derived from a translation memory. * */ @XmlEnumValue("leveraged-tm") LEVERAGED_TM("leveraged-tm"), /** * Indicates the translation is suggested by machine translation. * */ @XmlEnumValue("mt-suggestion") MT_SUGGESTION("mt-suggestion"), /** * Indicates that the item has been rejected because of incorrect grammar. * */ @XmlEnumValue("rejected-grammar") REJECTED_GRAMMAR("rejected-grammar"), /** * Indicates that the item has been rejected because it is incorrect. * */ @XmlEnumValue("rejected-inaccurate") REJECTED_INACCURATE("rejected-inaccurate"), /** * Indicates that the item has been rejected because it is too long or too short. * */ @XmlEnumValue("rejected-length") REJECTED_LENGTH("rejected-length"), /** * Indicates that the item has been rejected because of incorrect spelling. * */ @XmlEnumValue("rejected-spelling") REJECTED_SPELLING("rejected-spelling"), /** * Indicates the translation is suggested by translation memory. * */ @XmlEnumValue("tm-suggestion") TM_SUGGESTION("tm-suggestion"); private final String value; StateQualifierValueList(String v) { value = v; } public String value() { return value; } public static StateQualifierValueList fromValue(String v) { for (StateQualifierValueList c: StateQualifierValueList.values()) { if (c.value.equals(v)) { return c; } } throw new IllegalArgumentException(v); } }
package com.andhikapanjiprasetyo.caltyfarm; import androidx.appcompat.app.AppCompatActivity; import androidx.cardview.widget.CardView; import android.content.Intent; import android.os.Bundle; import android.view.View; public class BerandaActivity extends AppCompatActivity { CardView cardVInput, cardVDaftar; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_beranda); } public void viewLayout(View v){ Intent intent; switch (v.getId()){ case R.id.cardVInput : intent = new Intent(BerandaActivity.this, InputDataSapiActivity.class); startActivity(intent); break; case R.id.cardVDaftar : intent = new Intent(BerandaActivity.this, DaftarStatusSapiActivity.class); startActivity(intent); break; case R.id.cardVAlarm: intent = new Intent(BerandaActivity.this, DaftarStatusSapiActivity.class); startActivity(intent); break; case R.id.cardVTidakan: intent = new Intent(BerandaActivity.this, DaftarStatusSapiActivity.class); startActivity(intent); break; case R.id.cardVHubDokter: intent = new Intent(BerandaActivity.this, DaftarStatusSapiActivity.class); startActivity(intent); break; } } }
package com.getronics.quarkus.util.decorator; public interface TelemetryDecorator { String decorate(String stationId, String measurement) throws Exception; }
/** * */ package com.goodhealth.algorithm.Date; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; /** * @author 24663 * @date 2018年7月25日 * @Description */ public class DateApi implements Comparable<DateApi>{ public static void main(String[] args) { //显示当前日期 Date utilDate=new Date(); System.out.println(utilDate); //java.util.date 与java.sql.date <数据库类型DATE> 的转换 java.sql.Date date_sql=new java.sql.Date(utilDate.getTime()); System.out.println(date_sql); //java.util.date 与java.sql.date <数据库类型TIME> 的转换 java.sql.Time sTime=new java.sql.Time(utilDate.getTime()); System.out.println(sTime); //java.util.date 与java.sql.Timestamp <数据库类型DATETIME> 的转换 java.sql.Timestamp stp=new java.sql.Timestamp(utilDate.getTime()); System.out.println(stp); System.out.println("-----------------------------------"); // 按指定格式显示当前日期 /* 要指定时间格式,使用时间模式字符串。在这个模式中,所有的ASCII字母被保留为模式字母,其定义如下: 字符 描述 例子 G 时代指示器 AD y 四位数年份 2001 M 年中的月份 July or 07 d 月份中日期 10 h 时间 A.M./P.M.(1~12) 12 H 天中的小时 (0~23) 22 m 小时中的分钟 30 s 分钟中的秒钟 55 S 毫秒 234 E 星期中的天 Tuesday D 年中的天 360 F 月中星期中的天 2 (second Wed. in July) w 年中的星期 40 W 月中的星期 1 a A.M./P.M. 标记 PM k 天中的小时(1~24) 24 K 小时A.M./P.M. (0~11) 10 z 时区 东部标准时间 ' 脱离文本 分隔符 " 单引号 ` */ Date d=new Date(); SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); System.out.println(sdf.format(stp)); //根据字符串确定一个时间 SimpleDateFormat sdf2=new SimpleDateFormat("yyyy.MM.dd HH:mm:ss"); String string="2018.12.12 24:56:52"; try { System.out.println(sdf2.parse(string)); } catch (ParseException e) { e.printStackTrace(); } //测量执行时间 try { long start = System.currentTimeMillis( ); System.out.println(start); //休眠十秒 Thread.sleep(1000); long end = System.currentTimeMillis( ); System.out.println(end); long diff = end - start; System.out.println("Difference is : " + diff); } catch (Exception e) { System.out.println("Got an exception!"); } } /* (non-Javadoc) * @see java.lang.Comparable#compareTo(java.lang.Object) */ @Override public int compareTo(DateApi o) { // TODO Auto-generated method stub return 0; } }
package com.example.appBack.Tablas.Student.infrastructure.controller.dto.Output; import com.example.appBack.Tablas.Student.domain.StudentJpa; import com.example.appBack.noDatabase.BranchEnum; import com.fasterxml.jackson.annotation.JsonFormat; import com.sun.istack.NotNull; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import java.util.ArrayList; import java.util.Date; import java.util.List; @Data @NoArgsConstructor @AllArgsConstructor public class StudentOutputDTO { private String id; @NotNull private String nombre; @NotNull private String apellido; @NotNull private String correo; @JsonFormat(pattern = "dd/MM/yyyy") private Date fecha_entrada; @NotNull private String ciudad; @NotNull private int horas_semanales; @NotNull private String especialidad; @NotNull private Boolean estado; //--------------------NUEVOS----------------------- @NotNull private String correo_trabajo; private String comentarios; @JsonFormat(pattern = "dd/MM/yyyy") private Date fecha_finalizacion; @NotNull BranchEnum branch; String Profesor; public static StudentOutputDTO getStudentOutputDTO(StudentJpa student){ return new StudentOutputDTO(student.getId_Student(), student.getNombre(), student.getApellido(), student.getCorreo(), student.getFecha_entrada(), student.getCiudad(), student.getHoras_semanales(), student.getEspecialidad(), student.getEstado(), student.getCorreo_trabajo(), student.getComentarios(), student.getFecha_finalizacion(), student.getBranch(), student.getProfesor()); } public static List<StudentOutputDTO> getAllDTO(List<StudentJpa> listStudent){ List<StudentOutputDTO> devolver = new ArrayList<>(); listStudent.forEach(student -> devolver.add(getStudentOutputDTO(student))); return devolver; } }
package com.thomaster.ourcloud.json; import com.thomaster.ourcloud.model.filesystem.UploadedFolder; import java.util.Set; import java.util.stream.Collectors; public class UploadedFolderJSON extends FileSystemElementJSON { private Set<ContainedFSEInfoJSON> containedFiles; UploadedFolderJSON(UploadedFolder source) { super(source); this.containedFiles = extractContainedFiles(source); } public Set<ContainedFSEInfoJSON> getContainedFiles() { return containedFiles; } public void setContainedFiles(Set<ContainedFSEInfoJSON> containedFiles) { this.containedFiles = containedFiles; } private Set<ContainedFSEInfoJSON> extractContainedFiles(UploadedFolder source) { return source.getContainedFileInfos() .stream() .map(ContainedFSEInfoJSON::new) .collect(Collectors.toSet()); } }
package com.liufeng.domian.dto.base; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import lombok.Data; import javax.validation.constraints.NotBlank; @Data @ApiModel(description = "共用分页类") public class BaseSort { @ApiModelProperty(value = "排序规则(asc-升序,desc-降序)",required = true) @NotBlank(message = "排序规则属性不能为空") private String sort; @ApiModelProperty(value = "排序字段",required = true) @NotBlank(message = "排序字段属性不能为空") private String filed; }
/* * 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.github.somi92.seecsk.gui; import com.github.somi92.seecsk.data.Sesija; import com.github.somi92.seecsk.gui.panels.MembersPanel; import com.github.somi92.seecsk.model.tables.trening.PrisustvaClanTableModel; import com.github.somi92.seecsk.model.tables.trening.PrisustvaTableRenderer; import com.github.somi92.seecsk.model.tables.uplata.UplateTableClanarinaEditor; import com.github.somi92.seecsk.model.tables.uplata.UplateTableModel; import com.github.somi92.seecsk.model.tables.uplata.UplateTableModelDatumEditor; import com.github.somi92.seecsk.server.ServerInstance; import com.github.somi92.seecskcommon.domain.Clan; import com.github.somi92.seecskcommon.domain.Clanarina; import com.github.somi92.seecskcommon.domain.Grupa; import com.github.somi92.seecskcommon.domain.Uplata; import com.github.somi92.seecskcommon.transfer.OdgovorObjekat; import com.github.somi92.seecskcommon.transfer.ZahtevObjekat; import com.github.somi92.seecskcommon.util.Constants; import com.github.somi92.seecskcommon.util.Ref; import com.github.somi92.seecskcommon.util.SistemskeOperacije; import java.awt.Color; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.io.File; import java.util.ArrayList; import java.util.Calendar; import java.util.List; import javax.swing.JFrame; import javax.swing.JOptionPane; import javax.swing.border.Border; import javax.swing.plaf.basic.BasicBorders; import javax.swing.table.DefaultTableCellRenderer; import javax.swing.table.TableColumn; import javax.swing.table.TableColumnModel; /** * * @author milos */ public class FNewMember extends javax.swing.JDialog { // private FMembers parent; private MembersPanel caller; private Clan clan; private List<Clanarina> clanarine; private List<Uplata> uplateBrisanje; /** * Creates new form FNewMember */ public FNewMember(JFrame parent, MembersPanel caller, boolean modal) { super(parent, modal); this.caller = caller; // this.operacije = (ApstraktnaSistemskaOperacija) Sesija.vratiInstancu().vratiMapuSesije().get(Sesija.CLAN_OPERACIJA); initComponents(); clan = (Clan) Sesija.vratiInstancu().vratiMapuSesije().get(Sesija.CLAN); uplateBrisanje = new ArrayList<>(); initForm(clan); Sesija.vratiInstancu().vratiMapuSesije().put(Sesija.CLAN, null); Sesija.vratiInstancu().vratiMapuSesije().put(Sesija.CLAN_OPERACIJA, null); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPanel1 = new javax.swing.JPanel(); jlblFirstLastName = new javax.swing.JLabel(); jlblPol = new javax.swing.JLabel(); jlblEmail = new javax.swing.JLabel(); jlblPhoneNum = new javax.swing.JLabel(); jlblDateOfBirth = new javax.swing.JLabel(); jlblMembershipDate = new javax.swing.JLabel(); jlblGroup = new javax.swing.JLabel(); jlblRemark = new javax.swing.JLabel(); jtxtFirstLastName = new javax.swing.JTextField(); jtxtEmail = new javax.swing.JTextField(); jtxtPhoneNum = new javax.swing.JTextField(); jcmbGender = new javax.swing.JComboBox(); jScrollPane1 = new javax.swing.JScrollPane(); jtxtaRemark = new javax.swing.JTextArea(); jcmbGroup = new javax.swing.JComboBox(); jdccDateOfBirth = new datechooser.beans.DateChooserCombo(); jdccMembershipDate = new datechooser.beans.DateChooserCombo(); jlblNameError = new javax.swing.JLabel(); jlblEmailError = new javax.swing.JLabel(); jlblPhoneError = new javax.swing.JLabel(); jlblIdCardError = new javax.swing.JLabel(); jtxtIdCard = new javax.swing.JTextField(); jlblidCard = new javax.swing.JLabel(); jlblEmail1 = new javax.swing.JLabel(); jtxtAdresa = new javax.swing.JTextField(); jlblAdresaError = new javax.swing.JLabel(); jbtnSave = new javax.swing.JButton(); jbtnEmpty = new javax.swing.JButton(); jbtnExit = new javax.swing.JButton(); jpnlClanarine = new javax.swing.JPanel(); jScrollPane2 = new javax.swing.JScrollPane(); jtblUplate = new javax.swing.JTable(); jbtnObrisiUplatu = new javax.swing.JButton(); jbtnNovaUplata = new javax.swing.JButton(); jbtnUplatnica = new javax.swing.JButton(); jpnlPrisustva = new javax.swing.JPanel(); jScrollPane3 = new javax.swing.JScrollPane(); jtblPrisustva = new javax.swing.JTable(); jbtnTreninzi = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); setTitle("SEECSK - Unos novog člana"); setResizable(false); jPanel1.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED)); jlblFirstLastName.setText("Ime i prezime:"); jlblPol.setText("Pol:"); jlblEmail.setText("E-mail:"); jlblPhoneNum.setText("Broj telefona:"); jlblDateOfBirth.setText("Datum rođenja:"); jlblMembershipDate.setText("Datum učlanjenja:"); jlblGroup.setText("Grupa:"); jlblRemark.setText("Napomena:"); jtxtFirstLastName.setText(" "); jtxtFirstLastName.addFocusListener(new java.awt.event.FocusAdapter() { public void focusGained(java.awt.event.FocusEvent evt) { jtxtFirstLastNameFocusGained(evt); } }); jtxtEmail.setText(" "); jtxtEmail.addFocusListener(new java.awt.event.FocusAdapter() { public void focusGained(java.awt.event.FocusEvent evt) { jtxtEmailFocusGained(evt); } }); jtxtEmail.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jtxtEmailActionPerformed(evt); } }); jtxtPhoneNum.setText(" "); jtxtPhoneNum.addFocusListener(new java.awt.event.FocusAdapter() { public void focusGained(java.awt.event.FocusEvent evt) { jtxtPhoneNumFocusGained(evt); } }); jcmbGender.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Muški", "Ženski" })); jtxtaRemark.setColumns(20); jtxtaRemark.setLineWrap(true); jtxtaRemark.setRows(5); jScrollPane1.setViewportView(jtxtaRemark); jdccDateOfBirth.setCalendarPreferredSize(new java.awt.Dimension(340, 240)); jdccDateOfBirth.setFormat(2); jdccDateOfBirth.setLocale(new java.util.Locale("sr", "BA", "")); jdccMembershipDate.setCalendarPreferredSize(new java.awt.Dimension(340, 240)); jdccMembershipDate.setLocale(new java.util.Locale("sr", "BA", "")); jlblNameError.setFont(new java.awt.Font("DejaVu Sans", 0, 10)); // NOI18N jlblNameError.setForeground(new java.awt.Color(255, 0, 0)); jlblEmailError.setFont(new java.awt.Font("DejaVu Sans", 0, 10)); // NOI18N jlblEmailError.setForeground(new java.awt.Color(255, 0, 0)); jlblEmailError.setText(" "); jlblPhoneError.setFont(new java.awt.Font("DejaVu Sans", 0, 10)); // NOI18N jlblPhoneError.setForeground(new java.awt.Color(255, 0, 0)); jlblPhoneError.setText(" "); jlblIdCardError.setFont(new java.awt.Font("DejaVu Sans", 0, 10)); // NOI18N jlblIdCardError.setForeground(new java.awt.Color(255, 0, 0)); jtxtIdCard.setText(" "); jtxtIdCard.addFocusListener(new java.awt.event.FocusAdapter() { public void focusGained(java.awt.event.FocusEvent evt) { jtxtIdCardFocusGained(evt); } }); jlblidCard.setText("Broj lične karte:"); jlblEmail1.setText("Adresa:"); jtxtAdresa.setText(" "); jtxtAdresa.addFocusListener(new java.awt.event.FocusAdapter() { public void focusGained(java.awt.event.FocusEvent evt) { jtxtAdresaFocusGained(evt); } }); jlblAdresaError.setFont(new java.awt.Font("DejaVu Sans", 0, 10)); // NOI18N jlblAdresaError.setForeground(new java.awt.Color(255, 0, 0)); jlblAdresaError.setText(" "); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jlblPol, javax.swing.GroupLayout.PREFERRED_SIZE, 113, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jlblEmail, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jlblPhoneNum, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jlblDateOfBirth, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jlblMembershipDate, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jlblRemark, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jlblEmail1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addComponent(jlblFirstLastName, javax.swing.GroupLayout.PREFERRED_SIZE, 110, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jlblGroup, javax.swing.GroupLayout.PREFERRED_SIZE, 113, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jlblidCard, javax.swing.GroupLayout.PREFERRED_SIZE, 123, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jtxtIdCard, javax.swing.GroupLayout.PREFERRED_SIZE, 260, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jlblNameError, javax.swing.GroupLayout.PREFERRED_SIZE, 260, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jtxtFirstLastName, javax.swing.GroupLayout.PREFERRED_SIZE, 260, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jlblIdCardError, javax.swing.GroupLayout.PREFERRED_SIZE, 260, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(3, 3, 3) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jcmbGender, javax.swing.GroupLayout.PREFERRED_SIZE, 260, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 260, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jdccDateOfBirth, javax.swing.GroupLayout.PREFERRED_SIZE, 260, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jdccMembershipDate, javax.swing.GroupLayout.PREFERRED_SIZE, 260, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jlblPhoneError, javax.swing.GroupLayout.PREFERRED_SIZE, 260, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jtxtPhoneNum, javax.swing.GroupLayout.PREFERRED_SIZE, 260, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jlblEmailError, javax.swing.GroupLayout.PREFERRED_SIZE, 260, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jtxtEmail, javax.swing.GroupLayout.PREFERRED_SIZE, 260, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jcmbGroup, javax.swing.GroupLayout.PREFERRED_SIZE, 260, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jtxtAdresa, javax.swing.GroupLayout.PREFERRED_SIZE, 260, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jlblAdresaError, javax.swing.GroupLayout.PREFERRED_SIZE, 260, javax.swing.GroupLayout.PREFERRED_SIZE)))) .addContainerGap(15, Short.MAX_VALUE)) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup() .addContainerGap(8, Short.MAX_VALUE) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jtxtIdCard, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jlblidCard)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jlblIdCardError, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jlblFirstLastName) .addComponent(jtxtFirstLastName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(1, 1, 1) .addComponent(jlblNameError, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jlblPol) .addComponent(jcmbGender, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jlblEmail) .addComponent(jtxtEmail, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jlblEmailError, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jlblEmail1) .addComponent(jtxtAdresa, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jlblAdresaError, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jlblPhoneNum, javax.swing.GroupLayout.PREFERRED_SIZE, 15, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jtxtPhoneNum, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(1, 1, 1) .addComponent(jlblPhoneError, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jlblDateOfBirth) .addComponent(jdccDateOfBirth, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jdccMembershipDate, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jlblMembershipDate, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jlblGroup) .addComponent(jcmbGroup, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jlblRemark) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 150, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(15, 15, 15)) ); jbtnSave.setText(" Sačuvaj"); jbtnSave.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jbtnSaveActionPerformed(evt); } }); jbtnEmpty.setText(" Poništi sve"); jbtnEmpty.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jbtnEmptyActionPerformed(evt); } }); jbtnExit.setText("Izađi"); jbtnExit.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jbtnExitActionPerformed(evt); } }); jpnlClanarine.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED), "Uplate članarine izabranog člana")); jtblUplate.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null} }, new String [] { "Title 1", "Title 2", "Title 3", "Title 4" } )); jScrollPane2.setViewportView(jtblUplate); jbtnObrisiUplatu.setText("Obriši uplatu"); jbtnObrisiUplatu.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jbtnObrisiUplatuActionPerformed(evt); } }); jbtnNovaUplata.setText("Dodaj uplatu"); jbtnNovaUplata.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jbtnNovaUplataActionPerformed(evt); } }); jbtnUplatnica.setText("Uplatnica..."); jbtnUplatnica.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jbtnUplatnicaActionPerformed(evt); } }); javax.swing.GroupLayout jpnlClanarineLayout = new javax.swing.GroupLayout(jpnlClanarine); jpnlClanarine.setLayout(jpnlClanarineLayout); jpnlClanarineLayout.setHorizontalGroup( jpnlClanarineLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jpnlClanarineLayout.createSequentialGroup() .addContainerGap() .addGroup(jpnlClanarineLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jpnlClanarineLayout.createSequentialGroup() .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 728, Short.MAX_VALUE) .addContainerGap()) .addGroup(jpnlClanarineLayout.createSequentialGroup() .addComponent(jbtnUplatnica, javax.swing.GroupLayout.PREFERRED_SIZE, 170, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jbtnNovaUplata) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jbtnObrisiUplatu) .addGap(17, 17, 17)))) ); jpnlClanarineLayout.setVerticalGroup( jpnlClanarineLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jpnlClanarineLayout.createSequentialGroup() .addContainerGap() .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE) .addGap(18, 18, 18) .addGroup(jpnlClanarineLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jbtnUplatnica) .addComponent(jbtnNovaUplata) .addComponent(jbtnObrisiUplatu)) .addContainerGap()) ); jpnlPrisustva.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED), "Prisustva izabranog člana")); jtblPrisustva.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null} }, new String [] { "Title 1", "Title 2", "Title 3", "Title 4" } )); jScrollPane3.setViewportView(jtblPrisustva); jbtnTreninzi.setText("Treninzi..."); jbtnTreninzi.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jbtnTreninziActionPerformed(evt); } }); javax.swing.GroupLayout jpnlPrisustvaLayout = new javax.swing.GroupLayout(jpnlPrisustva); jpnlPrisustva.setLayout(jpnlPrisustvaLayout); jpnlPrisustvaLayout.setHorizontalGroup( jpnlPrisustvaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jpnlPrisustvaLayout.createSequentialGroup() .addContainerGap() .addGroup(jpnlPrisustvaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 728, Short.MAX_VALUE) .addGroup(jpnlPrisustvaLayout.createSequentialGroup() .addComponent(jbtnTreninzi, javax.swing.GroupLayout.PREFERRED_SIZE, 161, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 0, Short.MAX_VALUE))) .addContainerGap()) ); jpnlPrisustvaLayout.setVerticalGroup( jpnlPrisustvaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jpnlPrisustvaLayout.createSequentialGroup() .addContainerGap() .addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 229, Short.MAX_VALUE) .addGap(18, 18, 18) .addComponent(jbtnTreninzi) .addContainerGap()) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(layout.createSequentialGroup() .addGap(20, 20, 20) .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(27, 27, 27) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jpnlClanarine, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jpnlPrisustva, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))) .addGroup(layout.createSequentialGroup() .addGap(28, 28, 28) .addComponent(jbtnSave, javax.swing.GroupLayout.PREFERRED_SIZE, 103, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jbtnEmpty, javax.swing.GroupLayout.PREFERRED_SIZE, 103, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 898, Short.MAX_VALUE) .addComponent(jbtnExit, javax.swing.GroupLayout.PREFERRED_SIZE, 102, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGap(28, 28, 28)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(39, 39, 39) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(layout.createSequentialGroup() .addComponent(jpnlClanarine, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jpnlPrisustva, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 18, Short.MAX_VALUE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jbtnEmpty, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jbtnExit, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(jbtnSave, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap()) ); pack(); }// </editor-fold>//GEN-END:initComponents private void jtxtEmailActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jtxtEmailActionPerformed // TODO add your handling code here: }//GEN-LAST:event_jtxtEmailActionPerformed private void jtxtFirstLastNameFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jtxtFirstLastNameFocusGained jtxtFirstLastName.setBorder(defaultBorder); jlblNameError.setText(""); }//GEN-LAST:event_jtxtFirstLastNameFocusGained private void jtxtEmailFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jtxtEmailFocusGained jtxtEmail.setBorder(defaultBorder); jlblEmailError.setText(""); }//GEN-LAST:event_jtxtEmailFocusGained private void jtxtPhoneNumFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jtxtPhoneNumFocusGained jtxtPhoneNum.setBorder(defaultBorder); jlblPhoneError.setText(""); }//GEN-LAST:event_jtxtPhoneNumFocusGained private void jbtnSaveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtnSaveActionPerformed String idClana = jtxtIdCard.getText().trim(); String imePrezime = jtxtFirstLastName.getText().trim(); char pol = (jcmbGender.getSelectedItem().toString().equals("Muški") ? 'M' : 'Ž'); String email = jtxtEmail.getText().trim(); String adresa = jtxtAdresa.getText().trim(); String brojTel = jtxtPhoneNum.getText().trim(); Calendar datumRodjenja = jdccDateOfBirth.getSelectedDate(); Calendar datumUclanjenja = jdccMembershipDate.getSelectedDate(); Grupa grupa = (Grupa) jcmbGroup.getSelectedItem(); String napomena = jtxtaRemark.getText().trim(); boolean isValidated = validateInput(idClana, imePrezime, email, adresa, brojTel); if(isValidated) { if(clan == null ) { Ref<Clan> c = new Ref(new Clan()); // KontrolerPL.kreirajClana(c); ZahtevObjekat zo = new ZahtevObjekat(); zo.setSistemskaOperacija(SistemskeOperacije.SO_KREIRAJ_CLANA); zo.setParametar(c); ServerInstance.vratiInstancu().posaljiZahtev(zo); OdgovorObjekat oo = ServerInstance.vratiInstancu().vratiOdgovor(); c = oo.getPodaci(); clan = c.get(); } // Clan clan = new Clan(idClana, imePrezime, pol, email, brojTel, datumRodjenja.getTime(), datumUclanjenja.getTime(), napomena); clan.setBrojLK(idClana); clan.setImePrezime(imePrezime); clan.setPol(pol); clan.setEmail(email); clan.setAdresa(adresa); clan.setBrojTel(brojTel); clan.setDatumRodjenja(datumRodjenja.getTime()); clan.setDatumUclanjenja(datumUclanjenja.getTime()); clan.setNapomena(napomena); clan.setGrupa(grupa); List<Uplata> uplataTabele = utm.vratiUplateTabele(); for(Uplata u : uplataTabele) { if(u.getClanarina() == null) { JOptionPane.showMessageDialog(this, "Niste izabrali članarinu (period) za neku od uplata."); return; } else { u.setClan(clan); // clan.getUplate().add(u); } } clan.setUplate(uplataTabele); ZahtevObjekat zo = new ZahtevObjekat(); zo.setSistemskaOperacija(SistemskeOperacije.SO_ZAPAMTI_CLANA); zo.setParametar(clan); zo.setUplateZaBrisanje(uplateBrisanje); ServerInstance.vratiInstancu().posaljiZahtev(zo); OdgovorObjekat oo = ServerInstance.vratiInstancu().vratiOdgovor(); int status = oo.getStatusOperacije(); boolean res = (status==0); // boolean res = KontrolerPL.sacuvajIliAzurirajClana(clan, uplateBrisanje); if(res) { JOptionPane.showMessageDialog(this, "Član je uspešno zapamćen."); caller.azurirajTabelu(); dispose(); } else { JOptionPane.showMessageDialog(this, "Sistem ne može da sačuva člana.", "Greška", JOptionPane.ERROR_MESSAGE); } } else { // JOptionPane.showMessageDialog(this, "Podaci nisu validni, pokušajte ponovo."); } }//GEN-LAST:event_jbtnSaveActionPerformed private void jtxtIdCardFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jtxtIdCardFocusGained jtxtIdCard.setBorder(defaultBorder); jlblIdCardError.setText(""); }//GEN-LAST:event_jtxtIdCardFocusGained private void jbtnEmptyActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtnEmptyActionPerformed resetFields(); }//GEN-LAST:event_jbtnEmptyActionPerformed private void jbtnExitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtnExitActionPerformed dispose(); }//GEN-LAST:event_jbtnExitActionPerformed private void jbtnNovaUplataActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtnNovaUplataActionPerformed utm.dodajRed(); }//GEN-LAST:event_jbtnNovaUplataActionPerformed private void jtxtAdresaFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jtxtAdresaFocusGained jtxtAdresa.setBorder(defaultBorder); jlblAdresaError.setText(""); }//GEN-LAST:event_jtxtAdresaFocusGained private void jbtnObrisiUplatuActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtnObrisiUplatuActionPerformed int row = jtblUplate.getSelectedRow(); if(row == -1) { JOptionPane.showMessageDialog(this, "Niste izabrali uplatu."); } else { int response = JOptionPane.showConfirmDialog(this, "Jeste li sigurni da želite izbrisati izabranu uplatu?", "Potvrdite izbor", JOptionPane.OK_CANCEL_OPTION); if(response == JOptionPane.OK_OPTION) { Uplata u = utm.vratiUplateTabele().get(row); u.setClan(clan); if(u.getClanarina() != null) { uplateBrisanje.add(utm.obrisiRed(row)); } else { utm.obrisiRed(row); } } } }//GEN-LAST:event_jbtnObrisiUplatuActionPerformed private void jbtnUplatnicaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtnUplatnicaActionPerformed // try { Sesija.vratiInstancu().vratiMapuSesije().put(Sesija.LISTA, clanarine); Sesija.vratiInstancu().vratiMapuSesije().put(Sesija.CLAN, clan); new FInvoice(null, true).setVisible(true); /* File pdfFile = new File( Constants.LocationConfigKeys.TEMP_INVOICE_LOCATION+"uplatnica_"+clan.getIdClan()+".pdf"); PDDocument doc = PDDocument.load(pdfFile); List<PDPage> pages = doc.getDocumentCatalog().getAllPages(); PDPage page = (PDPage) pages.get(0); PDFPagePanel pdfPanel = new PDFPagePanel(); pdfPanel.setPage(page); JInternalFrame iFrame = new JInternalFrame(); iFrame.setBounds(0, 0, jpnlUplatnica.getWidth(), jpnlUplatnica.getHeight()); jpnlUplatnica.add(iFrame); iFrame.add(pdfPanel); iFrame.setVisible(true); iFrame.setResizable(false); iFrame.setSelected(false); pdfPanel.setVisible(true); */ // } catch (IOException ex) { // ex.printStackTrace(); // } catch (PropertyVetoException ex) { // ex.printStackTrace(); // } }//GEN-LAST:event_jbtnUplatnicaActionPerformed private void jbtnTreninziActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtnTreninziActionPerformed Sesija.vratiInstancu().vratiMapuSesije().put(Sesija.GRUPA, clan.getGrupa()); new FTraining(null, true).setVisible(true); }//GEN-LAST:event_jbtnTreninziActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JPanel jPanel1; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JScrollPane jScrollPane2; private javax.swing.JScrollPane jScrollPane3; private javax.swing.JButton jbtnEmpty; private javax.swing.JButton jbtnExit; private javax.swing.JButton jbtnNovaUplata; private javax.swing.JButton jbtnObrisiUplatu; private javax.swing.JButton jbtnSave; private javax.swing.JButton jbtnTreninzi; private javax.swing.JButton jbtnUplatnica; private javax.swing.JComboBox jcmbGender; private javax.swing.JComboBox jcmbGroup; private datechooser.beans.DateChooserCombo jdccDateOfBirth; private datechooser.beans.DateChooserCombo jdccMembershipDate; private javax.swing.JLabel jlblAdresaError; private javax.swing.JLabel jlblDateOfBirth; private javax.swing.JLabel jlblEmail; private javax.swing.JLabel jlblEmail1; private javax.swing.JLabel jlblEmailError; private javax.swing.JLabel jlblFirstLastName; private javax.swing.JLabel jlblGroup; private javax.swing.JLabel jlblIdCardError; private javax.swing.JLabel jlblMembershipDate; private javax.swing.JLabel jlblNameError; private javax.swing.JLabel jlblPhoneError; private javax.swing.JLabel jlblPhoneNum; private javax.swing.JLabel jlblPol; private javax.swing.JLabel jlblRemark; private javax.swing.JLabel jlblidCard; private javax.swing.JPanel jpnlClanarine; private javax.swing.JPanel jpnlPrisustva; private javax.swing.JTable jtblPrisustva; private javax.swing.JTable jtblUplate; private javax.swing.JTextField jtxtAdresa; private javax.swing.JTextField jtxtEmail; private javax.swing.JTextField jtxtFirstLastName; private javax.swing.JTextField jtxtIdCard; private javax.swing.JTextField jtxtPhoneNum; private javax.swing.JTextArea jtxtaRemark; // End of variables declaration//GEN-END:variables private Border errorBorder; private Border defaultBorder; private UplateTableModel utm; private PrisustvaClanTableModel pctm; // private JWebBrowser browser; private void initBorders() { defaultBorder = jtxtFirstLastName.getBorder(); errorBorder = new BasicBorders.ButtonBorder(Color.red, Color.red, Color.red, Color.red); } private boolean validateInput(String idCard, String firstLastName, String email, String adresa, String phoneNumber) { boolean isValid = true; if(idCard == null || idCard.isEmpty() || !idCard.matches("[A-Za-z0-9]{9}")) { jlblIdCardError.setText("Morate uneti broj lične karte (9 znakova)."); jtxtIdCard.setBorder(errorBorder); isValid = false; } if(firstLastName == null || firstLastName.isEmpty()) { jlblNameError.setText("Morate uneti ime i prezime."); jtxtFirstLastName.setBorder(errorBorder); isValid = false; } if(email != null && !email.isEmpty() && !email.matches("[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}")) { jlblEmailError.setText("E-mail foramt je nepravilan."); jtxtEmail.setBorder(errorBorder); isValid = false; } if(adresa == null || adresa.isEmpty()) { jlblAdresaError.setText("Adresa nije uneta."); jtxtAdresa.setBorder(errorBorder); isValid = false; } if(phoneNumber == null || phoneNumber.isEmpty()) { jlblPhoneError.setText("Broj telefona nije unet."); jtxtPhoneNum.setBorder(errorBorder); isValid = false; } return isValid; } private void initGroupsCombo() { Ref<List<Grupa>> ref = new Ref(new ArrayList<>()); // KontrolerPL.vratiListuGrupa(ref, false); ZahtevObjekat zo = new ZahtevObjekat(); zo.setSistemskaOperacija(SistemskeOperacije.SO_VRATI_LISTU_GRUPA); zo.setUcitajListe(false); zo.setParametar(ref); ServerInstance.vratiInstancu().posaljiZahtev(zo); OdgovorObjekat oo = ServerInstance.vratiInstancu().vratiOdgovor(); ref = oo.getPodaci(); List<Grupa> groups = ref.get(); for(Grupa g : groups) { jcmbGroup.addItem(g); } } private void resetFields() { jtxtFirstLastName.setText(""); jtxtIdCard.setText(""); jtxtEmail.setText(""); jtxtPhoneNum.setText(""); jtxtaRemark.setText(""); } private void initForm(Clan clan) { addWindowListener(new WindowAdapter() { @Override public void windowClosed(WindowEvent e) { File tempFolder = new File(Constants.LocationConfigKeys.TEMP_INVOICE_LOCATION); File[] files = tempFolder.listFiles(); if(files != null) { for(File file : files) { file.delete(); } } } }); resetFields(); initBorders(); initGroupsCombo(); utm = new UplateTableModel(); jtblUplate.setModel(utm); pctm = new PrisustvaClanTableModel(); jtblPrisustva.setModel(pctm); List<Clanarina> sample = new ArrayList<>(); sample.add(new Clanarina()); Ref<List<Clanarina>> clanarineRef = new Ref(sample); ZahtevObjekat zo = new ZahtevObjekat(); zo.setSistemskaOperacija(SistemskeOperacije.SO_PRONADJI_CLANARINE); zo.setUcitajListe(false); zo.setParametar(clanarineRef); ServerInstance.vratiInstancu().posaljiZahtev(zo); OdgovorObjekat oo = ServerInstance.vratiInstancu().vratiOdgovor(); clanarineRef = oo.getPodaci(); // KontrolerPL.vratiClanarine(clanarineRef, null, false); TableColumnModel tcmUplate = jtblUplate.getColumnModel(); TableColumn tcUplate = tcmUplate.getColumn(0); TableColumnModel tcmPrisustva = jtblPrisustva.getColumnModel(); TableColumn tcPrisustvo = tcmPrisustva.getColumn(1); clanarine = new ArrayList<>(); for(int i=0; i<clanarineRef.get().size(); i++) { boolean contains = false; if(clan == null) { clanarine = clanarineRef.get(); break; } for(Uplata u : clan.getUplate()) { if(u.getClanarina().equals(clanarineRef.get().get(i))) { contains = true; break; } } if(!contains && clan.getDatumUclanjenja().before(clanarineRef.get().get(i).getDatumDo())) { clanarine.add(clanarineRef.get().get(i)); } } if(clanarine.isEmpty()) { jbtnUplatnica.setEnabled(false); } UplateTableClanarinaEditor ute = new UplateTableClanarinaEditor(clanarine.toArray()); tcUplate.setCellEditor(ute); tcUplate = tcmUplate.getColumn(2); tcUplate.setCellEditor(new UplateTableModelDatumEditor()); TableColumn tcKasnjenje = tcmPrisustva.getColumn(2); DefaultTableCellRenderer rnd = new DefaultTableCellRenderer(); rnd.setHorizontalAlignment(DefaultTableCellRenderer.CENTER); tcKasnjenje.setCellRenderer(rnd); tcPrisustvo.setCellRenderer(new PrisustvaTableRenderer()); if(clan != null) { // memberId = clan.getIdClan(); jtxtIdCard.setText(clan.getBrojLK()); jtxtFirstLastName.setText(clan.getImePrezime()); jcmbGender.setSelectedItem(clan.getPol()); jtxtEmail.setText(clan.getEmail()); jtxtAdresa.setText(clan.getAdresa()); jtxtPhoneNum.setText(clan.getBrojTel()); jcmbGender.setSelectedItem(clan.getPol() == 'M' ? "Muški" : "Ženski"); Calendar dob = Calendar.getInstance(); dob.setTime(clan.getDatumRodjenja()); jdccDateOfBirth.setSelectedDate(dob); Calendar dom = Calendar.getInstance(); dom.setTime(clan.getDatumUclanjenja()); jdccMembershipDate.setSelectedDate(dom); jcmbGroup.setSelectedItem(clan.getGrupa()); jtxtaRemark.setText(clan.getNapomena()); setTitle("SEECSK - Detalji i izmena člana"); jbtnSave.setText("Izmeni"); // Uplata u = new Uplata(); // u.setClan(clan); // List<Uplata> ul = new ArrayList<>(); // ul.add(u); // Ref<List<Uplata>> uplateRef = new Ref(ul); // List<String> pretraga = new ArrayList<>(); // pretraga.add("clan"); // KontrolerPL.vratiClanarine(uplateRef, pretraga); // ul = uplateRef.get(); utm.postaviUplateTabele(new ArrayList<>(clan.getUplate())); utm.postaviClana(clan); pctm.postaviPrisustvaTabele(clan.getPrisustva()); } else { // jtblUplate.setEnabled(false); // jbtnNovaUplata.setEnabled(false); // jbtnObrisiUplatu.setEnabled(false); // memberId = KontrolerPL.vratiBrojacEntiteta(Clan.class)+1; setTitle("SEECSK - Unos novog člana"); jbtnSave.setText("Sačuvaj"); jbtnUplatnica.setEnabled(false); } } }
package com.team.mapper; import java.util.Date; import java.util.HashMap; import java.util.List; import org.apache.ibatis.annotations.Mapper; import com.team.vo.Comments; import com.team.vo.Feedback; import com.team.vo.FeedbackReceiver; @Mapper public interface FeedbackMapper { public int insertFeedback(Feedback feedback); public void insertFeedbackReceivers(List<FeedbackReceiver> receivers); public void insertComment(Comments comment); public List<Feedback> selectFeedback(HashMap<String, Object> params); public List<Comments> selectComments(int feedbackNo); public int countFeedback(HashMap<String, Object> params); public Date selectLatestWritedate(HashMap<String, Object> params); public int receivedFeedbackCount(String email); public void deleteFeedback(HashMap<String, Object> params); public void checkFeedback(HashMap<String, Object> params); }
package com.example.nata.hallimane; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.widget.TextView; import java.util.HashMap; public class SplashScreen extends Activity { // Splash screen timer private static int SPLASH_TIME_OUT = 1000; SessionManager session ; String email,password; TextView lallle; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_splash_screen); new Handler().postDelayed(new Runnable() { @Override public void run() { // This method will be executed once the timer is over // Start your app main activity SplashScreen.this.finish(); Intent i = new Intent(SplashScreen.this, Temp.class); startActivity(i); // close this activity finish(); } }, SPLASH_TIME_OUT); } }
package cn.leancloud.plugin; import cn.leancloud.LCException; public class Exception { public static final int ErrorCode_Invalid_Parameter = LCException.INVALID_PARAMETER; public static final String ErrorMsg_Invalid_ClientId = "Client id is null or invalid."; public static final String ErrorMsg_Invalid_ConversationId = "Conversation id is null or invalid."; }
package com.tencent.mm.plugin.sns.ui; import android.view.MenuItem; import android.view.MenuItem.OnMenuItemClickListener; import com.tencent.mm.plugin.sns.i.j; import com.tencent.mm.sdk.platformtools.bi; import com.tencent.mm.ui.base.h; class SnsTagDetailUI$5 implements OnMenuItemClickListener { final /* synthetic */ SnsTagDetailUI obJ; SnsTagDetailUI$5(SnsTagDetailUI snsTagDetailUI) { this.obJ = snsTagDetailUI; } public final boolean onMenuItemClick(MenuItem menuItem) { if (!(this.obJ.obG + " " + bi.c(this.obJ.jzp, ",")).equals(this.obJ.bKg) || this.obJ.noJ == 0) { h.a(this.obJ, j.sns_tag_cancel, j.app_tip, new 1(this), null); } else { this.obJ.finish(); } return true; } }
package gob.igm.ec; import java.math.BigDecimal; import javax.annotation.Generated; import javax.persistence.metamodel.SingularAttribute; import javax.persistence.metamodel.StaticMetamodel; @Generated(value="EclipseLink-2.5.2.v20140319-rNA", date="2018-10-03T11:38:06") @StaticMetamodel(Ttipocarta.class) public class Ttipocarta_ { public static volatile SingularAttribute<Ttipocarta, BigDecimal> tamanio; public static volatile SingularAttribute<Ttipocarta, String> control; public static volatile SingularAttribute<Ttipocarta, String> descCarta; public static volatile SingularAttribute<Ttipocarta, Short> idTipoCarta; public static volatile SingularAttribute<Ttipocarta, String> tipoTamanio; }
package pt.ua.nextweather; import android.content.Context; import android.content.Intent; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.TreeSet; import pt.ua.nextweather.datamodel.City; import pt.ua.nextweather.ui.CityForecast; public class CityItemAdapter extends RecyclerView.Adapter<CityItemAdapter.ForecastViewHolder> { private final HashMap<String, City> cities; private LayoutInflater mInflater; public CityItemAdapter(Context context, HashMap<String,City> cities) { mInflater = LayoutInflater.from(context); this.cities = cities; } class ForecastViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener { public final TextView cityItemView; final CityItemAdapter mAdapter; public ForecastViewHolder(View itemView, CityItemAdapter adapter) { super(itemView); cityItemView= itemView.findViewById(R.id.city_name); cityItemView.setOnClickListener(this); this.mAdapter = adapter; } @Override public void onClick(View view) { TextView cityview = (TextView) view; Context context=view.getContext(); City city = cities.get(cityview.getText()); // Use that to access the affected item in mWordList. Intent intent = new Intent(context, CityForecast.class); intent.putExtra("cityname", city.getLocal()); intent.putExtra("citycode",city.getGlobalIdLocal()); context.startActivity(intent); } } @NonNull @Override public CityItemAdapter.ForecastViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View mItemView = mInflater.inflate(R.layout.city_item, parent, false); return new ForecastViewHolder(mItemView, this); } @Override public void onBindViewHolder(@NonNull CityItemAdapter.ForecastViewHolder holder, int position) { TreeSet<String> keys = new TreeSet<>(cities.keySet()); String mCurrent = keys.toArray()[position].toString(); holder.cityItemView.setText(mCurrent); } @Override public int getItemCount() { return cities.size(); } }
package com.thomaster.ourcloud.services.request.save.folder; import com.thomaster.ourcloud.model.filesystem.UploadedFile; import com.thomaster.ourcloud.model.filesystem.UploadedFolder; import com.thomaster.ourcloud.model.user.OCUser; import com.thomaster.ourcloud.services.FileService; import com.thomaster.ourcloud.services.OCUserService; import com.thomaster.ourcloud.services.request.RequestValidationException; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.ArgumentCaptor; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.mockito.junit.jupiter.MockitoExtension; import java.util.Optional; import static org.assertj.core.api.Assertions.*; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.*; @ExtendWith(MockitoExtension.class) class SaveFolderRequestFactoryTest { @Mock private OCUserService userService; @Mock private FileService fileService; @InjectMocks private SaveFolderRequestFactory requestFactory = new SaveFolderRequestFactory(userService, fileService); @BeforeEach public void init() { MockitoAnnotations.initMocks(this); } @Test void test_createSaveFolderRequest_happyPath() { OCUser ocUser = new OCUser(); ocUser.setId(1L); ocUser.setUsername("Thomaster"); ocUser.setUsedBytes(100L); UploadedFolder folder = new UploadedFolder(); folder.setParentFolderPath(""); folder.setFileSize(100L); folder.setOriginalName("Thomaster"); folder.setRelativePath("Thomaster"); folder.setOwner(ocUser); when(userService.getCurrentlyLoggedInUser()).thenReturn(Optional.of(ocUser)); when(fileService.findFSElementWithContainedFilesByPath_noChecks(any())).thenReturn(folder); SaveFolderRequest saveFolderRequest = requestFactory.createSaveFolderRequest("Thomaster", "New Folder", true); ArgumentCaptor<String> argumentCaptor = ArgumentCaptor.forClass(String.class); verify(fileService, times(1)).findFSElementWithContainedFilesByPath_noChecks(argumentCaptor.capture()); verify(userService, times(1)).getCurrentlyLoggedInUser(); assertThat(argumentCaptor.getValue()).isEqualTo("Thomaster"); assertThat(saveFolderRequest.getOriginalName()).isEqualTo("New Folder"); assertThat(saveFolderRequest.isShouldOverrideExistingFile()).isEqualTo(true); assertThat(saveFolderRequest.getParentFolder()).isEqualTo(folder); assertThat(saveFolderRequest.getParentFolderOwner()).isEqualTo(ocUser); assertThat(saveFolderRequest.getInitiatingUser().get()).isEqualTo(ocUser); } @Test void test_createSaveFolderRequest_userNotLoggedIn() { OCUser ocUser = new OCUser(); ocUser.setId(1L); ocUser.setUsername("Thomaster"); ocUser.setUsedBytes(100L); UploadedFolder folder = new UploadedFolder(); folder.setParentFolderPath(""); folder.setFileSize(100L); folder.setOriginalName("Thomaster"); folder.setRelativePath("Thomaster"); folder.setOwner(ocUser); when(userService.getCurrentlyLoggedInUser()).thenReturn(Optional.empty()); when(fileService.findFSElementWithContainedFilesByPath_noChecks(any())).thenReturn(folder); SaveFolderRequest saveFolderRequest = requestFactory.createSaveFolderRequest("Thomaster", "New Folder", true); ArgumentCaptor<String> argumentCaptor = ArgumentCaptor.forClass(String.class); verify(fileService, times(1)).findFSElementWithContainedFilesByPath_noChecks(argumentCaptor.capture()); verify(userService, times(1)).getCurrentlyLoggedInUser(); assertThat(argumentCaptor.getValue()).isEqualTo("Thomaster"); assertThat(saveFolderRequest.getOriginalName()).isEqualTo("New Folder"); assertThat(saveFolderRequest.isShouldOverrideExistingFile()).isEqualTo(true); assertThat(saveFolderRequest.getParentFolder()).isEqualTo(folder); assertThat(saveFolderRequest.getParentFolderOwner()).isEqualTo(ocUser); assertThat(saveFolderRequest.getInitiatingUser()).isEmpty(); } @Test void test_createSaveFolderRequest_parentFolderNotExists() { OCUser ocUser = new OCUser(); ocUser.setId(1L); ocUser.setUsername("Thomaster"); ocUser.setUsedBytes(100L); when(userService.getCurrentlyLoggedInUser()).thenReturn(Optional.of(ocUser)); when(fileService.findFSElementWithContainedFilesByPath_noChecks(any())).thenReturn(null); RequestValidationException requestValidationException = catchThrowableOfType(() -> requestFactory.createSaveFolderRequest("Thomaster", "New Folder", true), RequestValidationException.class); assertThat(requestValidationException.getErrorCode()).isEqualTo(RequestValidationException.NO_FSE_FOUND_CODE); ArgumentCaptor<String> argumentCaptor = ArgumentCaptor.forClass(String.class); verify(fileService, times(1)).findFSElementWithContainedFilesByPath_noChecks(argumentCaptor.capture()); verify(userService, times(1)).getCurrentlyLoggedInUser(); } @Test void test_createSaveFolderRequest_parentFolderNotFolder() { OCUser ocUser = new OCUser(); ocUser.setId(1L); ocUser.setUsername("Thomaster"); ocUser.setUsedBytes(100L); UploadedFile uploadedFile = new UploadedFile(); uploadedFile.setParentFolderPath("Thomaster"); uploadedFile.setFileSize(100L); uploadedFile.setOriginalName("file_that_is_not_folder.txt"); uploadedFile.setRelativePath("Thomaster.file_that_is_not_folder_txt"); uploadedFile.setOwner(ocUser); when(userService.getCurrentlyLoggedInUser()).thenReturn(Optional.of(ocUser)); when(fileService.findFSElementWithContainedFilesByPath_noChecks(any())).thenReturn(uploadedFile); RequestValidationException requestValidationException = catchThrowableOfType(() -> requestFactory.createSaveFolderRequest("Thomaster.file_that_is_not_folder_txt", "New Folder", true), RequestValidationException.class); assertThat(requestValidationException.getErrorCode()).isEqualTo(RequestValidationException.NO_FSE_FOUND_CODE); ArgumentCaptor<String> argumentCaptor = ArgumentCaptor.forClass(String.class); verify(fileService, times(1)).findFSElementWithContainedFilesByPath_noChecks(argumentCaptor.capture()); verify(userService, times(1)).getCurrentlyLoggedInUser(); } }
import java.util.*; import java.text.*; public class CashRegister { public static void main(String[] args) { Scanner input = new Scanner(System.in); DecimalFormat fmt = new DecimalFormat("0.00"); final double TAX = 0.08; Items item1 = new Items(1.25); Items item2 = new Items(2.50); Items item3 = new Items(0.80); System.out.println("There are 3 items. \nEnter an amount for each:"); int amount1 = input.nextInt(); int amount2 = input.nextInt(); int amount3 = input.nextInt(); double price1 = item1.getPrice(); double price2 = item2.getPrice(); double price3 = item3.getPrice(); double subtotal = price1 + price2 + price3; double total = subtotal * (1 + TAX); System.out.println("--------------------------"); System.out.println("Apples: " + amount1); System.out.println("Price: " + fmt.format(price1)); System.out.println("--------------------------"); System.out.println("Carrots: " + amount2); System.out.println("Price: " + fmt.format(price2)); System.out.println("--------------------------"); System.out.println("Chocolate Chip Cookies: " + amount3); System.out.println("Price: " + fmt.format(price3)); double tax = TAX * 100; System.out.println("--------------------------"); System.out.println("Subtotal: " + fmt.format(subtotal)); System.out.println("Tax: " + fmt.format(tax) + "%"); System.out.println("Total: " + fmt.format(total)); } }
package com.hevi.dao; import com.hevi.dataobject.ProductCategory; import org.springframework.data.jpa.repository.JpaRepository; import java.util.List; /** * Created by Hevi on 2017/9/26. */ public interface ProductCategoryDao extends JpaRepository<ProductCategory,Integer> { /** * 查询在Category List数组以内的所有分类 * @return */ List<ProductCategory> findByCategoryTypeIn(List list); }
package martin.s4a.shift4all2; public class WidgetListItem { public String heading,content, custom, background; boolean notes, holiday; //eg }
package _MemoCalculatorAccountbook; import java.awt.Rectangle; import java.awt.event.*; import javax.swing.*; import javax.swing.table.*; class MemoPanel extends JPanel{ private static final long serialVersionUID = 1L; private JButton jBtnAddRow = null; private JButton jBtnDelRow = null; private JTable table; private JScrollPane scrollPane; private JTabbedPane tabbedPane; public MemoPanel() { setLayout(null); String colNames[] = {"날짜","내용"}; DefaultTableModel model = new DefaultTableModel(colNames, 0); table = new JTable(model); table.addMouseListener(new JTableMouseListener()); scrollPane = new JScrollPane(table); // 테이블에 스크롤 생기게 하기 scrollPane.setSize(400, 300); add(scrollPane); initialize(); } private class JTableMouseListener implements MouseListener{ @Override public void mouseClicked(java.awt.event.MouseEvent e) { JTable jtable = (JTable)e.getSource(); int row = jtable.getSelectedRow(); int col = jtable.getSelectedColumn(); DefaultTableModel model = (DefaultTableModel)table.getModel(); System.out.println(model.getValueAt(row, 0)); // 눌려진 행의 부분에서 0번째 값을 출력 System.out.println(model.getValueAt(row, col)); // 눌려진 행과 열에 해당하는 선택된 데이터 하나 출력 } @Override public void mouseEntered(java.awt.event.MouseEvent e) { } @Override public void mouseExited(java.awt.event.MouseEvent e) { } @Override public void mousePressed(java.awt.event.MouseEvent e) { } @Override public void mouseReleased(java.awt.event.MouseEvent e) { } } private void initialize() { // 테이블 새로 한줄 추가하는 부분 jBtnAddRow = new JButton(); jBtnAddRow.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { jBtnAddRow(); } }); jBtnAddRow.setBounds(50,300,120, 25); jBtnAddRow.setText("추가"); add(jBtnAddRow); // 선택된 테이블 한줄 삭제하는 부분 jBtnDelRow = new JButton(); jBtnDelRow.addActionListener(new ActionListener() { public void actionPerformed(java.awt.event.ActionEvent e) { jBtnDelRow(); } }); jBtnDelRow.setBounds(new Rectangle(220, 300, 120, 25)); jBtnDelRow.setText("삭제"); add(jBtnDelRow); } void jBtnAddRow(){ DefaultTableModel model = (DefaultTableModel)table.getModel(); model.addRow(new String[]{"",""}); // 새테이블의 초기값 } void jBtnDelRow(){ int row = table.getSelectedRow(); if(row<0) return; // 선택이 안된 상태면 -1리턴 DefaultTableModel model = (DefaultTableModel)table.getModel(); //System.out.println(model.getValueAt(row, 0)); model.removeRow(row); } }
package cc.protea.foundation.template.services; import java.util.List; import javax.annotation.security.RolesAllowed; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response.Status; import org.apache.commons.lang3.StringUtils; import com.wordnik.swagger.annotations.Api; import com.wordnik.swagger.annotations.ApiOperation; import com.wordnik.swagger.annotations.ApiParam; import cc.protea.foundation.integrations.DatabaseUtil; import cc.protea.foundation.integrations.SpreedlyUtil; import cc.protea.foundation.model.ProteaException; import cc.protea.foundation.template.model.TemplateUser; import cc.protea.foundation.util.KeyUtil; import cc.protea.platform.MerchantAccountUtil; import cc.protea.platform.services.ProteaService; import cc.protea.platform.services.creditcardtransaction.MerchantAccount; import cc.protea.spreedly.model.SpreedlyGatewayAccount; /** * { "initial": "boolean", -- Read only, if true no spreedly token is associated with this account "name": "string", -- Friendly name for the merchant account "thirdPartyVault": "boolean", -- If true retained payment methods will be vaulted with the provider as well as spreedly "hidden": "boolean", -- If true account will not be included in /merchantAccounts/list "provider": "string", -- The key for the gateway provider. Gateway provider definitions can be retrieved through /spreedly/providers/list -- Use this value to look up the definition, including the human readable provider name, and the list of possible credentials "credentials": "Map[string,string]", -- Provider specific credentials. -- Privileged credentials, like passwords are never retrieved from the server, -- but may be including in PUT /merchantAccounts/{merchantAccountKey} to be saved in Spreedly "redacted": "boolean", -- Readonly. A redacted gateway has been 'deleted' in Spreedly } * */ @Path("/merchantAccounts") @Api(value = "/merchantAccounts", description = "Merchant Account Services") @Produces(MediaType.APPLICATION_JSON) public class MerchantAccountService extends ProteaService<TemplateUser>{ @GET @Path("/list") @ApiOperation(value = "List all merchant accounts", response = MerchantAccount.class, responseContainer = "List") @RolesAllowed("loggedIn") public List<MerchantAccount> listMerchantAccounts() { return DatabaseUtil.get(h -> { return h.createQuery("SELECT * FROM merchant_account WHERE hidden != true") .map(MerchantAccount.mapper) .list(); }); } @GET @Path("/{merchantAccountKey}") @ApiOperation(value = "Fetch merchant account details") @RolesAllowed("loggedIn") public MerchantAccount fetchMerchantAccount(@PathParam("merchantAccountKey") String merchantAccountKey) { MerchantAccount merchantAccount = MerchantAccount.select(merchantAccountKey); if(StringUtils.isBlank(merchantAccount.token)) { // Account is still initialized, return with no details return merchantAccount; } SpreedlyGatewayAccount sga = SpreedlyUtil.getSpreedly().getGatewayAccount(merchantAccount.token); return merchantAccount = MerchantAccountUtil.fillMerchantAccount(sga, merchantAccount); } @POST @Path("/create") @ApiOperation(value = "Create a new merchant account, no push to spreedly") @RolesAllowed("loggedIn") public MerchantAccount create(@ApiParam(required = true) MerchantAccount merchantAccount) { merchantAccount.id = null; merchantAccount.name = StringUtils.trimToNull(merchantAccount.name); if (merchantAccount.name == null) { throw new ProteaException(Status.NOT_ACCEPTABLE, "Name should not be blank"); } merchantAccount.insert(); return merchantAccount; } @PUT @Path("/{merchantAccountKey}") @ApiOperation(value = "Update a gateway, pushes changes to spreedly as well") @RolesAllowed("loggedIn") public MerchantAccount update(@PathParam("merchantAccountKey") String merchantAccountKey, @ApiParam(required = true) MerchantAccount merchantAccount) { final MerchantAccount current = MerchantAccount.select(merchantAccountKey); if (current == null) { throw new ProteaException(Status.NOT_FOUND, "Payment credentials " + merchantAccountKey + " does not exist"); } merchantAccount.id = KeyUtil.toKey(merchantAccountKey); // Never edit some other gateway merchantAccount.token = current.token; // Don't overwrite the token SpreedlyGatewayAccount sga = MerchantAccountUtil.convert(merchantAccount); // Update Spreedly if (merchantAccount.token == null) { // if we don't already have a token it's a new gateway and we need to create it with spreedly sga = SpreedlyUtil.getSpreedly().create(sga); } else { // otherwise it's an existing gateway and we will update it, but only if the new credentials aren't empty if ( merchantAccount.credentials != null && ! merchantAccount.credentials.isEmpty() ) { sga = SpreedlyUtil.getSpreedly().update(sga); } } // Also update the database MerchantAccountUtil.fillMerchantAccount(sga, merchantAccount); merchantAccount.update(); return merchantAccount; } // Add by token @POST @Path("/import/{token}") @ApiOperation(value = "Import a merchant account from spreedly") @RolesAllowed("loggedIn") public MerchantAccount create(@PathParam("token") String token, @ApiParam(required = true) String name) { SpreedlyGatewayAccount sga = SpreedlyUtil.getSpreedly().getGatewayAccount(token); MerchantAccount merchantAccount = MerchantAccountUtil.convert(sga); merchantAccount.name = StringUtils.trimToNull(name); merchantAccount.insert(); return merchantAccount; } // TODO: Sync spreedly account list }
package pretask.test; public class PositionFinder { public static void findPosition(String[] list, String term){ if (list==null || list.length==0) System.out.print("Empty array"); else{ int position=-1; for (String name: list){ if(name.compareTo(term)==0) break; position++; } System.out.print(position > 0 ? position: 0); } } public static void main(String[] args){ String[] myArray = {"Hola","Kumusta", "Hello", "Ciao"}; findPosition(myArray, "Ciao"); } }
public class Sphere extends Shape implements Spatial{ private double radius; public double getRadius() { return this.radius; } public void setRadius(double radius) { this.radius=radius; } public double volume() { return 4*Math.PI*this.radius*this.radius*this.radius/3; } public double area() { return 4*Math.PI*this.radius*this.radius; } }
package fundamentos; import java.util.ArrayList; import java.util.Scanner; public class Class28NumerosArrayList { public static void main(String[] args) { Scanner teclado = new Scanner(System.in); //NECESITAMOS UNA COLECCION PARA GUARDAR TODOS LOS NUMEROS ArrayList<Integer> numeros = new ArrayList<>(); System.out.println("Introduzca números hasta escribir -1"); //QUEREMOS PEDIR AL USUARIO NUMEROS HASTA QUE PONGA -1 int numero = 0; // do { // System.out.println("Introduzca un número"); // String datonumero = teclado.nextLine(); // numero = Integer.parseInt(datonumero); // numeros.add(numero); // } while (numero != -1); System.out.println("Introduzca un número"); String datonumero = teclado.nextLine(); numero = Integer.parseInt(datonumero); while (numero != -1) { numeros.add(numero); System.out.println("Introduzca un número"); datonumero = teclado.nextLine(); numero = Integer.parseInt(datonumero); } System.out.println("Números almacenados: " + numeros.size()); double suma = 0; double media; //RECORREMOS TODOS LOS ELEMENTOS DE LA COLECCION for (int num : numeros) { suma += num; System.out.println(num); } media = suma / numeros.size(); System.out.println("La suma es " + suma); System.out.println("La media es " + media); System.out.println("Fin del programa"); } }
package components; import javafx.scene.media.Media; import javafx.scene.media.MediaPlayer; import javafx.scene.media.MediaView; import java.io.File; public class Movie { private MediaPlayer mediaPlayer; private MediaView mediaView; public Movie(String path) { Media media = new Media(new File(path).toURI().toString()); mediaPlayer = new MediaPlayer(media); mediaView = new MediaView(mediaPlayer); setSize(960, 840); } private void setSize(int width, int height) { mediaView.setFitHeight(width); mediaView.setFitWidth(height); } public void play() { mediaPlayer.play(); } public void stop() { mediaPlayer.stop(); } public MediaView getMediaView() { return mediaView; } }
package figures; abstract public class Figures {} class Pentagon extends Figures{} class Hexagon extends Figures{} class Oval extends Figures{} class Circle extends Oval{}
package ucll.drijkel.soa.services; import com.fasterxml.jackson.databind.util.JSONPObject; import org.json.JSONObject; import org.springframework.http.*; import org.springframework.stereotype.Service; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; import org.springframework.web.client.HttpClientErrorException; import org.springframework.web.client.HttpServerErrorException; import org.springframework.web.client.RestTemplate; import ucll.drijkel.soa.model.Meteorite; import ucll.drijkel.soa.model.RestException; import java.util.Collection; import java.util.Collections; @Service public class MeteoriteLandingsService { private final String url = "https://stark-beyond-06002.herokuapp.com/"; public MeteoriteLandingsService() {} public Meteorite getMeteorite(int id) { RestTemplate restTemplate = new RestTemplate(); try { //JSONObject result = restTemplate.getForObject(url+"api/getmeteorite/"+id, JSONObject.class); ResponseEntity<String> response = restTemplate.getForEntity(url+"api/getmeteorite/"+id, String.class); JSONObject result = new JSONObject(response.getBody()); JSONObject meteorite = result.getJSONObject("meteorite"); String name = meteorite.getString("name"); int id_model = meteorite.getInt("id_model"); String nametype = meteorite.getString("nametype"); String recclass = meteorite.getString("recclass"); double mass = meteorite.getDouble("mass"); String fall = meteorite.getString("fall"); int year = meteorite.getInt("year"); double reclat = meteorite.getDouble("reclat"); double reclong = meteorite.getDouble("reclong"); String geoLocation = meteorite.getString("geoLocation"); Meteorite meteorite1 = new Meteorite(id, name, id_model, nametype, recclass, mass, fall, year, reclat, reclong, geoLocation); assert result != null; return meteorite1; } catch (HttpClientErrorException e) { throw new RestException("Didn't find that specific meteorite landing."); } } public JSONObject getAllMeteorites() { RestTemplate restTemplate = new RestTemplate(); ResponseEntity<String> response = restTemplate.getForEntity(url+"api/getmeteorites", String.class); String meteorites = response.getBody(); JSONObject wrapper = new JSONObject(response.getBody()); //assert meteorites != null; /*for(String meteorite : meteorites) { wrapper.put(Integer.toString(meteorite.getId()), new JSONObject(meteorite)); }*/ return wrapper; } public JSONObject addMeteorite(Meteorite meteorite, String apiKey){ RestTemplate restTemplate = new RestTemplate(); HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON)); headers.set("Authorization","Token " + apiKey); HttpEntity<Meteorite> request = new HttpEntity<>(meteorite, headers); try { ResponseEntity<String> result = restTemplate.exchange(url+"api/"+"addmeteorite", HttpMethod.POST,request, String.class); if(result.getStatusCode() == HttpStatus.CREATED){ return new JSONObject(result.getBody()); } else{ return null; } } catch (HttpClientErrorException.Unauthorized ex) { throw new RestException("Unauthorized"); } } public void deleteMeteorite(int id, String apiKey){ RestTemplate restTemplate = new RestTemplate(); HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); headers.set("Authorization", "Token " + apiKey); Meteorite meteorite = getMeteorite(id); if (meteorite == null){ throw new RestException("Meteorite landing not found"); } HttpEntity<Meteorite> request = new HttpEntity<>(meteorite,headers); try { ResponseEntity<String> result = restTemplate.exchange(url + "api/"+"deletemeteorite/" + id, HttpMethod.DELETE,request, String.class); } catch ( HttpClientErrorException.NotFound e) { throw new RestException("Meteorite landing not found"); } catch (HttpClientErrorException.Unauthorized ex) { throw new RestException("Unauthorized"); } catch (HttpServerErrorException.InternalServerError e) { } } public JSONObject updateMeteorite(Meteorite updatedMeteorite, String apiKey){ RestTemplate restTemplate = new RestTemplate(); HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON)); headers.set("Authorization", "Token " + apiKey); HttpEntity<Meteorite> request = new HttpEntity<>(updatedMeteorite, headers); try { ResponseEntity<String> response = restTemplate.exchange(url + "api/"+"updatemeteorite/" + updatedMeteorite.getId(),HttpMethod.PUT, request, String.class); //JSONObject result = new JSONObject(response.getBody()); //ResponseEntity<String> result = restTemplate.exchange(url + "api/"+"updatemeteorite/" + updatedMeteorite.getId(),HttpMethod.PUT, request, String.class); if (response.getStatusCode() == HttpStatus.OK){ return new JSONObject(response.getBody()); } return null; } catch (HttpClientErrorException.Unauthorized ex) { throw new RestException("Unauthorized"); } catch (HttpClientErrorException.NotFound ex) { throw new NotFoundException("Didn't find that meteorite landing"); } } public void register(String username, String password1, String password2){ RestTemplate restTemplate = new RestTemplate(); HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED); MultiValueMap<String, String> map= new LinkedMultiValueMap<String, String>(); map.add("username", username); map.add("password1", password1); map.add("password2", password2); HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<MultiValueMap<String, String>>(map, headers); ResponseEntity<String> response = restTemplate.postForEntity( url+"registration/", request , String.class ); } public JSONObject getKey(String username, String password) { RestTemplate restTemplate = new RestTemplate(); HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED); MultiValueMap<String, String> map= new LinkedMultiValueMap<String, String>(); map.add("username", username); map.add("password", password); HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<MultiValueMap<String, String>>(map, headers); ResponseEntity<String> response = restTemplate.postForEntity( url+"login/", request , String.class ); return new JSONObject(response.getBody()); } }
package frc.robot; import edu.wpi.first.wpilibj.geometry.Pose2d; import edu.wpi.first.wpilibj.geometry.Rotation2d; import edu.wpi.first.wpilibj.geometry.Translation2d; import frc.robot.utility.MathUtils; import frc.robot.utility.TrajectoryMaker; import java.util.ArrayList; @SuppressWarnings("unused") public class TrajectoryHelper { public static double[][] test4Meters= { {0,0}, {157.48,0}, // roughly equal to 4 meters }; public static double[][] test3Meters= { {0,0}, {117.7721,0}, // roughly equal to 3 meters }; public static double[][] test2Meters= { {0,0}, {78.7402,0}, // roughly equal to 2 meters }; public static double[][] test1Meter= { {0,0}, {39.3701,0}, // roughly equal to 2 meters }; public static double[][] testStep= { // Slalom 2021.02.15 001 {30,150}, {60,160}, {90,120}, {120,85}, {150,80}, {180,80}, {225,80}, {255,90}, {270,120}, {285,155}, {310,160}, {330,150}, {340,120}, {330,85}, {300,75}, {280,95}, {270,120}, {265,140}, {240,155}, {210,160}, {180,160}, {150,160}, {120,155}, {105,145}, {90,120}, {80,95}, {60,80}, {30,90}, }; public static double[][] test2MetersAndBack = { {0,0}, {78.7402,0}, // roughly equal to 2 meters {78.7402,78.7402}, {0,78.7402}, {0,0} }; public static double[][] test2MetersTriangle= { {0,0}, {78.7402,0}, // roughly equal to 2 meters {78.7402,78.7402}, // roughly equal to 2 meters {0,0} }; public static double[][] slalom = { // {30,150}, //1 // {80,145}, // {95,90}, // {235,90}, // {240,155}, //5 old: {250, 145} // {305,155}, //old: {300, 145} // {305,90}, // {255,90}, // {230,155}, //old: {230, 145} // {95,155}, //10 old: {90, 145} // {60,90}, // {25,90}, {30,150}, //1 {90,153}, {105,85}, {235,85}, {250,155}, //5 old: {250, 145} {315,155}, //old: {300, 145} {315,85}, {245,80}, {220,155}, //old: {230, 145} {80,150}, //10 old: {90, 145} {65,75}, {20,75}, }; public static double[][] leg1 = { {0,0}, {60,0}, }; public static double[][] leg2 = { {60,0}, {60,60}, }; public static double[][] leg3 = { {60,60}, {0,60}, }; public static double[][] leg4 = { {0,60}, {0,0}, }; public static double[][] bounce1Relative = { {0, 0}, {30, 0} }; public static double[][] test = { {95, 30}, {110, 30} }; public static double[][] bounce00 = { {30, 90}, {37, 90}, }; public static double[][] bounce01 = { {37, 90}, //1 {90, 77}, {95,30}, //3 }; public static double[][] bounce10 = { {95, 30}, {95, 37}, }; public static double[][] bounce11 = { {95, 37},//3 {100, 85}, {125,100}, // 100, 90 {135,145},//5 {175,135}, //6 {190,25}, // {190,130},//8 // {255,130}, // {275,30}, // {270,85}, //11 // {330,85}, }; public static double[][] bounce20 = { {185, 25}, {185, 32}, }; public static double[][] bounce21 = { {185, 32}, {185,135},//8 {265,135}, {275,25}, }; public static double[][] bounce30 = { {277,25}, {277, 32}, }; public static double[][] bounce31 = { {277, 32}, {285,102}, //11 {330,102} }; public static double[][] barrel0 = { {30, 90}, {37, 90} }; public static double[][] barrel = { {37,90}, //1 {60,90}, {120,90}, {150,90}, {180,110}, //5 {180,140}, {150,150}, {110,140}, {110,80}, {205,110}, //10 {260,90}, //{270,60}, {270,30}, //12 {190,30}, {190,80},//14 {230,120}, {250,135}, {300,140}, {310,80}, {80,70}, {45,65}, //19 }; private static double[][] driveForward = { {12,60}, {15,60}, }; public static double[][] Forward2M = { {0,0}, {0,78.74}, }; public static double GLOBAL_SCALE = 0.827; /** * translateAndScale takes an array of integer coordinates in 2-d space, and scales them to meters, and applies a scale in additinoos * Omits the first and last points * @param pointsArray arrray of more than two X,Y coordinates * @param scale resize the entire grid * @return */ public static ArrayList<Translation2d> translateAndScale(double[][] pointsArray, double scale) { ArrayList<Translation2d> points = new ArrayList<>(pointsArray.length-1); // translate all the points to the initial coordinate double initialX = pointsArray[0][0]; double initialY = pointsArray[0][1]; for ( int i = 1; i < pointsArray.length; i++) { // also; convert from inches to meters // translate to 0,0 double x = pointsArray[i][0]; double y = pointsArray[i][1]; x = x - initialX; // translate points to be relative to starting point y = y - initialY; x = MathUtils.inchesToMeters(x); // convert to metric y = MathUtils.inchesToMeters(y); x = x * scale; // apply extra scale y = y * scale; points.add(new Translation2d(x, y)); } return points; } public static TrajectoryMaker createTrajectory(double [][] inputPoints, double scale, double startOrientation, double endOrientation, boolean isReversed) // for bounce { ArrayList<Translation2d> points = translateAndScale(inputPoints, scale); // make .2 for Hajel's garage. Turns the 30 foot field to 6 feet Pose2d initialPose = new Pose2d(0, 0, new Rotation2d(startOrientation)); Translation2d lastPoint = points.remove(points.size()-1); // remove last point in array Pose2d endPose = new Pose2d(lastPoint.getX(), lastPoint.getY(), new Rotation2d(endOrientation)); return new TrajectoryMaker(initialPose, endPose, points, isReversed); } public static TrajectoryMaker createTrajectory(double [][] inputPoints, double scale) // for slalom and barrel { ArrayList<Translation2d> points = translateAndScale(inputPoints, scale); // make .2 for Hajel's garage. Turns the 30 foot field to 6 feet Pose2d initialPose = new Pose2d(0, 0, new Rotation2d(0)); Translation2d lastPoint = points.remove(points.size()-1); // remove last point in array Pose2d endPose = new Pose2d(lastPoint.getX(), lastPoint.getY(), new Rotation2d(180)); return new TrajectoryMaker(initialPose, endPose, points, false); } public static TrajectoryMaker createTrajectory(double [][] inputPoints) { return createTrajectory(inputPoints, GLOBAL_SCALE); } public static TrajectoryMaker createDriveForward() // test path going only 4 meters forward { return createTrajectory(driveForward, GLOBAL_SCALE, 0, 0, false); } public static TrajectoryMaker createTest() // test path going only 4 meters forward { return createTrajectory(test, GLOBAL_SCALE, 0, 0, true); } public static TrajectoryMaker createTest4Meters() // test path going only 4 meters forward { return createTrajectory(test4Meters, GLOBAL_SCALE); } public static TrajectoryMaker createTest3Meters() // test path going 2 meters forward { return createTrajectory(test3Meters, GLOBAL_SCALE); } public static TrajectoryMaker createTest2MetersAndBack() // test path going 2 meters forward { return createTrajectory(test2MetersAndBack, GLOBAL_SCALE, 0, 0, false); } public static TrajectoryMaker createTestStep() // test path going forward { return createTrajectory(testStep, GLOBAL_SCALE); } public static TrajectoryMaker createSlalom() { return createTrajectory(slalom, GLOBAL_SCALE, 0, Math.PI, false); } public static TrajectoryMaker createBounce00() { return createTrajectory(bounce00, GLOBAL_SCALE, 0, 0, false); //Math.toRadians(-42.3) } public static TrajectoryMaker createBounce01() { return createTrajectory(bounce01, GLOBAL_SCALE, 0, 3 * Math.PI / 2, false); } public static TrajectoryMaker createBounce10() { return createTrajectory(bounce10, GLOBAL_SCALE, 3 * Math.PI / 2, 3 * Math.PI / 2, true); //Math.toRadians(60.85) } public static TrajectoryMaker createBounce11() { return createTrajectory(bounce11, GLOBAL_SCALE, 3 * Math.PI / 2, Math.PI / 2, true); } public static TrajectoryMaker createBounce20() { return createTrajectory(bounce20, GLOBAL_SCALE, Math.PI / 2, Math.PI / 2, false); //Math.toRadians(45) } public static TrajectoryMaker createBounce21() { return createTrajectory(bounce21, GLOBAL_SCALE, Math.PI / 2, 3 * Math.PI / 2, false); } public static TrajectoryMaker createBounce30() { return createTrajectory(bounce30, GLOBAL_SCALE, 3 * Math.PI / 2, 3 * Math.PI / 2, true); } public static TrajectoryMaker createBounce31() { return createTrajectory(bounce31, GLOBAL_SCALE, 3 * Math.PI / 2, Math.PI, true); } //go forward, turn 90 degrees right public static TrajectoryMaker createLeg1() { return createTrajectory(leg1, GLOBAL_SCALE, 0, Math.PI / 2, false); } //go forward, turn 90 degrees right public static TrajectoryMaker createLeg2() { return createTrajectory(leg2, GLOBAL_SCALE, Math.PI / 2, Math.PI, false); } public static TrajectoryMaker createLeg3() { return createTrajectory(leg3, GLOBAL_SCALE, Math.PI, 3*Math.PI / 2, false); } public static TrajectoryMaker createLeg4() { return createTrajectory(leg4, GLOBAL_SCALE, 3*Math.PI / 2, 0, false); } public static TrajectoryMaker createBarrel0() { return createTrajectory(barrel0, GLOBAL_SCALE, 0, 0, false); } public static TrajectoryMaker createBarrel() { return createTrajectory(barrel, GLOBAL_SCALE, 0, 3 * Math.PI / 2, false); } // Need better documentation here. What are these doing? Are the units in meters? public static TrajectoryMaker createfrontScorePath() { return new TrajectoryMaker(new Pose2d(0, 0, new Rotation2d(0)), new Pose2d(3, 0, new Rotation2d(0)), true); } public static TrajectoryMaker createTrenchToTargetDiagonal() { return new TrajectoryMaker(new Pose2d(0, 0, new Rotation2d(0)), new Pose2d(0.25, -0.25, new Rotation2d(0)), true);//8,-1.6 } public static TrajectoryMaker createTargetToFrontOfTrench() { return new TrajectoryMaker(new Pose2d(0, 0, new Rotation2d(0)), new Pose2d(-0.25, 0.25, new Rotation2d(0)), true);// -4.2,1.6 } public static TrajectoryMaker createTrenchForward() //Assuming facing forward { return new TrajectoryMaker(new Pose2d(0, 0, new Rotation2d(0)), new Pose2d(0.25, 0, new Rotation2d(0)), true);//2 } public static TrajectoryMaker createForwardPath() //For Testing Purposes { return new TrajectoryMaker(new Pose2d(0, 0, new Rotation2d(0)), new Pose2d(.75, 0, new Rotation2d(0)), true); } public static TrajectoryMaker createZagPath() //For Testing Purposes { return new TrajectoryMaker(new Pose2d(0, 0, new Rotation2d(0)), new Pose2d(1, 0.5, new Rotation2d(0)), true); } public static TrajectoryMaker createForwardPath2() //For Testing Purposes { return new TrajectoryMaker(new Pose2d(0, 0, new Rotation2d(0)), new Pose2d(2, 0, new Rotation2d(0)), true); } public static TrajectoryMaker createToPortPath() //For Testing Purposes { return new TrajectoryMaker(new Pose2d(0, 0, new Rotation2d(0)), new Pose2d(0.25, 0, new Rotation2d(0)), true);//3 } public static TrajectoryMaker createPortToFrontofTrench() { ArrayList<Translation2d> points = new ArrayList<Translation2d>(); points.add(new Translation2d(-1.5, 2.3)); points.add(new Translation2d(-3, 2.3)); return new TrajectoryMaker(new Pose2d(0, 0, new Rotation2d(0)), new Pose2d(-5.3, 2.3, new Rotation2d(180)), points ); } public static TrajectoryMaker createTestMultiPath() { ArrayList<Translation2d> points = new ArrayList<Translation2d>(); points.add(new Translation2d(1,-0.5)); points.add(new Translation2d(1,0.5)); return new TrajectoryMaker(new Pose2d(0, 0, new Rotation2d(0)), new Pose2d(2, 0, new Rotation2d(Math.PI)), points ); } public static TrajectoryMaker createMoveDownTrench() { return new TrajectoryMaker(new Pose2d(0,0,new Rotation2d(0)), new Pose2d(3, 0, new Rotation2d(0)), true); } public static TrajectoryMaker createMoveToPort() { ArrayList<Translation2d> points = new ArrayList<Translation2d>(); points.add(new Translation2d(1.524, 2.286)); return new TrajectoryMaker(new Pose2d(0, 0, new Rotation2d(0)), new Pose2d(3.048, 4.572, new Rotation2d(0)), points ); } public static TrajectoryMaker createAutonomousPath1() // Init Line (Start on Left) to Port Test { return new TrajectoryMaker(new Pose2d(0, 0, new Rotation2d(0)), new Pose2d(2, 0, new Rotation2d(0)), true); } public static TrajectoryMaker createAutonomousPath2() //Test 2 Electric Bugaloo { return new TrajectoryMaker(new Pose2d(0, 0, new Rotation2d(0)), new Pose2d(0, -1, new Rotation2d(0)), true); } public static TrajectoryMaker createSidePath() //Test Path { //return new TrajectoryMaker(new Pose2d(0, 0, new Rotation2d(0)), new Pose2d(2.77, 0.2, new Rotation2d(0)), true); return new TrajectoryMaker(new Pose2d(0, 0, new Rotation2d(0)), new Pose2d(0, -2, new Rotation2d(0)), true); } public static TrajectoryMaker createDiagonalPath() //Test Path { return new TrajectoryMaker(new Pose2d(0, 0, new Rotation2d(0)), new Pose2d(1, 1, new Rotation2d(0)), true); } public static TrajectoryMaker createBackwardPath() //Test Path { return new TrajectoryMaker(new Pose2d(0, 0, new Rotation2d(0)), new Pose2d(2.77, 0, new Rotation2d(0)), true); } public static TrajectoryMaker createForwardPath3() //Test Path { return new TrajectoryMaker(new Pose2d(0, 0, new Rotation2d(0)), new Pose2d(2, 0, new Rotation2d(0)), true); } public static TrajectoryMaker createForwardPath4() //Test Path { return new TrajectoryMaker(new Pose2d(0, 0, new Rotation2d(0)), new Pose2d(-4.75, 0, new Rotation2d(0)), true); } public static TrajectoryMaker test2MetersAndBack() { return null; } public static TrajectoryMaker createForward2M() // test path going only 4 meters forward { return createTrajectory(Forward2M, GLOBAL_SCALE, 0, 0, false); } }
package com.statistic.app.view; import java.io.File; import com.statistic.app.Main; import com.statistic.app.model.Data; import com.statistic.app.util.WindowUtil; import javafx.collections.ObservableList; import javafx.fxml.FXML; import javafx.scene.control.Alert.AlertType; import javafx.stage.FileChooser; public class WindowRootController { private Main main; /** * Ustawienie referencji do maina * * @param main */ public void setMain(Main main) { this.main = main; } @FXML private void handleNew() { main.getData().clear(); main.getSample().clear(); main.setDataFilePath(null, "data"); main.setDataFilePath(null, "sample"); } /** * Szablon otwarcia pliku * @param data lista do ktorej zostana wczyatane dane */ private void handleOpen(ObservableList<Data> data, String value) { FileChooser fileChooser = new FileChooser(); FileChooser.ExtensionFilter extFilter = new FileChooser.ExtensionFilter("XML files (*.xml)", "*.xml"); fileChooser.getExtensionFilters().add(extFilter); // okno wyboru File file = fileChooser.showOpenDialog(main.getStage()); if (file != null) { main.loadDataFromFile(file, data); main.setDataFilePath(file, value); } } @FXML private void handleOpenGroup() { handleOpen(main.getData(), "data"); } @FXML private void handleOpenSample() { handleOpen(main.getSample(), "sample"); } @FXML private void handleSaveAsGroup() { handleSaveAs(main.getData()); } @FXML private void handleSaveAsSample() { handleSaveAs(main.getSample()); } /** * Zapis plików * @param data lista ktora zostanie zapisana */ @FXML private void handleSave() { File file = main.getDataFilePath("data"); if (file != null) { System.out.println("zapis"); main.saveDataToFile(file, main.getData()); } else { handleSaveAs(main.getData()); } file = main.getDataFilePath("sample"); if (file != null) { System.out.println("zapisa"); main.saveDataToFile(file, main.getSample()); } else { handleSaveAs(main.getSample()); } } /** * Szablon zapisu pliku * @param data lista ktora ma byc zapisana */ private void handleSaveAs(ObservableList<Data> data) { FileChooser fileChooser = new FileChooser(); FileChooser.ExtensionFilter extFilter = new FileChooser.ExtensionFilter("XML files (*.xml)", "*.xml"); fileChooser.getExtensionFilters().add(extFilter); File file = fileChooser.showSaveDialog(main.getStage()); if (file != null) { if (!file.getPath().endsWith(".xml")) { file = new File(file.getPath() + ".xml"); } main.saveDataToFile(file, data); } } /** * O apliakcji */ @FXML private void handleAbout() { WindowUtil.showAlert(AlertType.INFORMATION , main.getStage(), "Analiza i wizualizacja danych", "Szacowanie cenny za metr kwadratowy (m2) mieszkania w miescie\n na "+ "podstawie liczby mieszkanców miasta." ,"Wykonali\n"+ "Mateusz Majcher\n"+ "Ariel Trybek\n"+ "Bartłomiej Loranty"); } /** * Zamkniecie aplikacji */ @FXML private void handleExit() { System.exit(0); } }
package com.example.healthmanage.ui.activity.consultation; import android.util.Log; import androidx.lifecycle.MutableLiveData; import com.example.healthmanage.base.BaseApplication; import com.example.healthmanage.base.BaseViewModel; import com.example.healthmanage.bean.UsersInterface; import com.example.healthmanage.bean.UsersRemoteSource; import com.example.healthmanage.data.network.exception.ExceptionHandle; import com.example.healthmanage.ui.activity.consultation.response.AddConsultationPlanResponse; import com.example.healthmanage.ui.activity.consultation.response.AddPatientInfoResponse; import com.example.healthmanage.ui.activity.consultation.response.ConsultationListResponse; import com.example.healthmanage.ui.activity.consultation.response.DoctorTeamListResponse; import com.example.healthmanage.ui.activity.consultation.response.PatientInfoBean; import com.example.healthmanage.ui.activity.qualification.response.CertificateResponse; import java.io.File; import java.util.List; public class ConsultationViewModel extends BaseViewModel { private UsersRemoteSource usersRemoteSource; public MutableLiveData<List<DoctorTeamListResponse.DataBean>> hospitalDepartMutableData = new MutableLiveData<>(); public MutableLiveData<List<String>> patientPhotos = new MutableLiveData<>(); //患者病史 public MutableLiveData<String> patientHistory = new MutableLiveData<>(); //初步诊断 public MutableLiveData<String> primaryDiagnosis = new MutableLiveData<>(); //会诊要求与目的 public MutableLiveData<String> consultationPurpose = new MutableLiveData<>(); public MutableLiveData<Boolean> isAddSuccess = new MutableLiveData<>(); public MutableLiveData<Boolean> isUpdateSuccess = new MutableLiveData<>(); public MutableLiveData<List<ConsultationListResponse.DataBean>> consultationListLiveData = new MutableLiveData<>(); public ConsultationViewModel() { usersRemoteSource = new UsersRemoteSource(); } public void getHospitalDepartmentList(){ usersRemoteSource.getHospitalDepartmentList(BaseApplication.getToken(), new UsersInterface.GetHospitalDepartmentListCallback() { @Override public void getSucceed(DoctorTeamListResponse doctorTeamListResponse) { if (doctorTeamListResponse.getData()!=null && doctorTeamListResponse.getData().size()>0){ hospitalDepartMutableData.setValue(doctorTeamListResponse.getData()); }else { hospitalDepartMutableData.setValue(null); } } @Override public void getFailed(String msg) { hospitalDepartMutableData.setValue(null); } @Override public void error(ExceptionHandle.ResponseException e) { hospitalDepartMutableData.setValue(null); } }); } public void uploadPhotoForPatient(List<File> files) { usersRemoteSource.getUploadCertificate(files, new UsersInterface.UpCertificateCallback() { @Override public void sendSucceed(CertificateResponse certificateResponse) { if (certificateResponse.getData() != null && certificateResponse.getData().size()>0){ patientPhotos.postValue(certificateResponse.getData()); }else { patientPhotos.postValue(null); } } @Override public void sendFailed(String msg) { patientPhotos.postValue(null); } @Override public void error(ExceptionHandle.ResponseException e) { patientPhotos.postValue(null); } }); } public void insertPatientExamine(PatientInfoBean patientInfoBean){ usersRemoteSource.insertPatientExamine(patientInfoBean, new UsersInterface.InsertPatientExamineCallback() { @Override public void insertSucceed(AddPatientInfoResponse addPatientInfoResponse) { Log.i("成功",addPatientInfoResponse.getMessage()); isAddSuccess.setValue(true); } @Override public void insertFailed(String msg) { Log.e("失败",msg); isAddSuccess.setValue(false); } @Override public void error(ExceptionHandle.ResponseException e) { isAddSuccess.setValue(false); } }); } public void getPatientExamine(int status){ usersRemoteSource.getPatientExamine(BaseApplication.getUserInfoBean().getAppDoctorInfo().getSystemUserId(), status, BaseApplication.getToken(), new UsersInterface.GetPatientExamineCallback() { @Override public void getSucceed(ConsultationListResponse consultationListResponse) { if (consultationListResponse.getData()!=null && consultationListResponse.getData().size()>0){ consultationListLiveData.setValue(consultationListResponse.getData()); }else { consultationListLiveData.setValue(null); } } @Override public void getFailed(String msg) { consultationListLiveData.setValue(null); } @Override public void error(ExceptionHandle.ResponseException e) { consultationListLiveData.setValue(null); } }); } public void updatePatientExamine(int id,String examinePlan){ usersRemoteSource.updatePatientExamine(id, examinePlan, BaseApplication.getToken(), new UsersInterface.UpdatePatientExamineCallback() { @Override public void updateSucceed(AddConsultationPlanResponse addConsultationPlanResponse) { isUpdateSuccess.setValue(true); } @Override public void updateFailed(String msg) { isUpdateSuccess.setValue(false); } @Override public void error(ExceptionHandle.ResponseException e) { isUpdateSuccess.setValue(false); } }); } }
package br.com.tinyconn.layout.nota.inclusao.retorno; import java.util.List; import br.com.tinyconn.bean.Resposta; import com.thoughtworks.xstream.annotations.XStreamAlias; @XStreamAlias("retorno") public class RetornoEnvioNota implements Resposta{ /** * Conforme tabela "Status de Processamento" */ @XStreamAlias("status_processamento") private Integer statusProcessamento; /** * Contém o status do retorno "OK" ou "Erro". Para o caso de conter erros * estes serão descritos abaixo */ private String status; /** * Conforme tabela "Códigos de erro" */ @XStreamAlias("codigo_erro") private Integer codigoErro; /** * Condicional [0..n] - Contém a lista dos erros encontrados. */ private List<Erro> erros; /** * Lista de resultados da inclusão */ private List<Registro> registros; public RetornoEnvioNota() { super(); } public RetornoEnvioNota(Integer statusProcessamento, String status, Integer codigoErro, List<Erro> erros, List<Registro> registros) { super(); this.statusProcessamento = statusProcessamento; this.status = status; this.codigoErro = codigoErro; this.erros = erros; this.registros = registros; } public Integer getStatusProcessamento() { return statusProcessamento; } public void setStatusProcessamento(Integer statusProcessamento) { this.statusProcessamento = statusProcessamento; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public Integer getCodigoErro() { return codigoErro; } public void setCodigoErro(Integer codigoErro) { this.codigoErro = codigoErro; } public List<Erro> getErros() { return erros; } public void setErros(List<Erro> erros) { this.erros = erros; } public List<Registro> getRegistros() { return registros; } public void setRegistros(List<Registro> registros) { this.registros = registros; } }
//Exercícios no link: https://www.slideshare.net/loianeg/curso-java-basico-exercicios-aulas-14-15 package exerciciosAulas14e15; import java.util.Scanner; public class Exercicio_10_Turno { public static void main(String[] args) { // TODO Auto-generated method stub Scanner scan = new Scanner(System.in); System.out.println("Qual turno vc estuda? (M, V ou N)"); String turno = scan.next().toLowerCase(); System.out.println(turno); if(turno.equals("m") || turno.equals("v") || turno.equals("n")) { switch(turno) { case "m": System.out.println("Bom dia!"); break; case "v": System.out.println("Boa tarde!"); break; case "n": System.out.println("Boa noite!"); break; } } else { System.out.println("Valor inválido!"); } scan.close(); } }
package org.fuserleer.serialization.mapper; import java.io.IOException; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.databind.SerializerProvider; import com.fasterxml.jackson.databind.ser.std.StdSerializer; /** * Serializer for conversion from {@code String} data * to the appropriate JSON encoding. */ class JacksonJsonStringSerializer extends StdSerializer<String> { private static final long serialVersionUID = -2472482347700365657L; JacksonJsonStringSerializer() { this(null); } JacksonJsonStringSerializer(Class<String> t) { super(t); } @Override public void serialize(String value, JsonGenerator jgen, SerializerProvider provider) throws IOException { jgen.writeString(/*JacksonCodecConstants.STR_STR_VALUE + */value); } }
package com.cryfish.myalomatika; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import org.apache.log4j.Logger; @CrossOrigin(origins = "*") @RestController public class ServerController { private static final Logger log = Logger.getLogger(ServerController.class); @RequestMapping("/") String home() { return "Server is available"; } @RequestMapping("/getNumbers") String[] getNumbers(@RequestParam("level") int level, @RequestParam("digit") int digit, @RequestParam("count") int count, @RequestParam("combo") boolean combo) { log.info("Level: " + level); log.info("Digit: " + digit); log.info("Count: " + count); log.info("Combo: " + combo); return NumbersGenerator.generateJson(level, digit, count, combo); } }
package www.limo.com.mymovies.entities; import java.util.*; import java.io.IOException; public enum OriginalLanguage { EN, RU; public String toValue() { switch (this) { case EN: return "en"; case RU: return "ru"; } return null; } public static OriginalLanguage forValue(String value) throws IOException { if (value.equals("en")) return EN; if (value.equals("ru")) return RU; throw new IOException("Cannot deserialize OriginalLanguage"); } }
package com.example.pedidos.model; import java.util.Date; public class Pedido { private int codigo; private int valor; private String descricao; private String cliente; private Date datadopedido; public int getCodigo() { return codigo; } public void setCodigo(int codigo) { this.codigo = codigo; } public int getValor() { return valor; } public void setValor(int valor) { this.valor = valor; } public String getDescricao() { return descricao; } public void setDescricao(String descricao) { this.descricao = descricao; } public String getCliente() { return cliente; } public void setCliente(String nome) { this.cliente = nome; } public Date getDatadopedido() { return datadopedido; } public void setDatadopedido(Date datadopedido) { this.datadopedido = datadopedido; } @Override public String toString() { return "Pedido [codigo=" + codigo + ", datadopedido=" + datadopedido + ", descricao=" + descricao + ", nome=" + cliente + ", valor=" + valor + "]"; } /* 1. Criar um repositório privado no GitHub para esse projeto. 2. Compartilhar o repositório com o professor( glauco.todesco@gmail.com) 3. Esse projeto tem somente um modelo: Pedido.java Um pedido possui os seguintes atributos: codigo, valor, descricao, cliente e data do pedido. 4. Desenvolver uma aplicação SpringBoot (rest) do zero que: Permita cadastrar um novo pedido. O código do pedido deve ser único. Permita listar todos os pedidos. Permita pesquisar um pedido pelo código. Permita remover um pedido Permita alterar um pedido. */ }
/* * 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.printcalculator.bean; import com.printcalculator.enums.PrintJobName; import com.printcalculator.enums.PrintJobType; import java.util.logging.Level; import java.util.logging.Logger; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author LiH */ public class A4DoubleSidedPrintJobTest extends PrintJobTest { private static final Logger logger = Logger.getLogger(A4DoubleSidedPrintJobTest.class.getName()); public A4DoubleSidedPrintJobTest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { } @After public void tearDown() { } @Override protected void setInstance(int totalPages, int colourPages, PrintJobType jobType, PrintJobName jobName) { instance = new A4DoubleSidedPrintJob(totalPages, colourPages, jobName); } @Test @Override public void testConstructor() { super.testConstructor(); PrintJobType type = instance.getJobType(); assertEquals(PrintJobType.A4DoubleSide, type); } @Test public void testConstructA4DoubleSidedPrintJobWithoutArguments() { logger.log(Level.FINE, "testConstructA4DoubleSidedPrintJobWithoutArguments..."); A4DoubleSidedPrintJob job = new A4DoubleSidedPrintJob(); PrintJobType type = job.getJobType(); PrintJobName name = job.getJobName(); int totalPageNumber = job.getNumberOfTotalPages(); int colourPageNumber = job.getNumberOfColourPages(); assertEquals(PrintJobType.A4DoubleSide, type); assertEquals(PrintJobName.A4DoubleSide, name); assertEquals(0, totalPageNumber); assertEquals(0, colourPageNumber); } @Test public void testConstructA4DoubleSidedPrintJobWithTwoArguments() { logger.log(Level.FINE, "testConstructA4DoubleSidedPrintJobWithTwoArguments..."); A4DoubleSidedPrintJob job = new A4DoubleSidedPrintJob(100, 30); PrintJobType type = job.getJobType(); PrintJobName name = job.getJobName(); int totalPageNumber = job.getNumberOfTotalPages(); int colourPageNumber = job.getNumberOfColourPages(); assertEquals(PrintJobType.A4DoubleSide, type); assertEquals(PrintJobName.A4DoubleSide, name); assertEquals(100, totalPageNumber); assertEquals(30, colourPageNumber); } @Test public void testConstructA4DoubleSidedPrintJobWithThreeArguments() { logger.log(Level.FINE, "testConstructA4DoubleSidedPrintJobWithThreeArguments..."); A4DoubleSidedPrintJob job = new A4DoubleSidedPrintJob(100, 30, PrintJobName.A4DoubleSide); PrintJobType type = job.getJobType(); PrintJobName name = job.getJobName(); int totalPageNumber = job.getNumberOfTotalPages(); int colourPageNumber = job.getNumberOfColourPages(); assertEquals(PrintJobType.A4DoubleSide, type); assertEquals(PrintJobName.A4DoubleSide, name); assertEquals(100, totalPageNumber); assertEquals(30, colourPageNumber); } @Test public void testGetDetails() { logger.log(Level.FINE, "testGetDetails..."); A4DoubleSidedPrintJob job = new A4DoubleSidedPrintJob(100, 30, PrintJobName.A4DoubleSide); String result = job.getDetails(); StringBuilder builder = new StringBuilder(); String line = System.getProperty("line.separator"); builder.append("Job Name:").append(PrintJobName.A4DoubleSide.getName()).append(line) .append("Total pages number:").append(100).append(line) .append("Colour pages number:").append(30); assertEquals(builder.toString(), result); } @Test public void testToString() { logger.log(Level.FINE, "testToString..."); A4DoubleSidedPrintJob job = new A4DoubleSidedPrintJob(100, 30, PrintJobName.A4DoubleSide); String result = job.toString(); assertTrue(result.startsWith("com.printcalculator.bean.A4DoubleSidedPrintJob[id=")); } @Test public void testEqualsAndHashCode() { logger.log(Level.FINE, "testEqualsAndHashCode..."); A4DoubleSidedPrintJob job1 = new A4DoubleSidedPrintJob(100, 30, PrintJobName.A4DoubleSide); A4DoubleSidedPrintJob job2 = new A4DoubleSidedPrintJob(100, 30, PrintJobName.A4DoubleSide); assertFalse(job1.equals(job2)); assertFalse(job1.hashCode() == job2.hashCode()); } }
/* * Copyright 2005-2010 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 * * 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 sdloader.javaee.impl; import java.util.Map; import javax.servlet.http.HttpSession; import sdloader.javaee.InternalWebApplication; import sdloader.javaee.SessionManager; import sdloader.util.CollectionsUtil; /** * セッション管理の実装クラス. * * <pre> * セッションID単位でセッションを管理します。 通常のJ2EEのセッション管理方式です。 * </pre> * * @author c9katayama */ public class SessionManagerImpl extends SessionManager { protected Map<String, HttpSessionImpl> sessionMap = CollectionsUtil .newConcurrentHashMap(); @Override public synchronized HttpSession getSession(String sessionId, boolean createNew, InternalWebApplication webApplication) { if (sessionId == null) { if(createNew){ return createNewSession(webApplication); }else{ return null; } } HttpSessionImpl session = (HttpSessionImpl) sessionMap.get(sessionId); if (session != null) { if (!session.isInvalidate()) { return session; } else { session.invalidate(); sessionMap.remove(sessionId); if (createNew) { return createNewSession(webApplication); } else { return null; } } } else { if (createNew) { return createNewSession(webApplication); } else { return null; } } } protected HttpSession createNewSession(InternalWebApplication webApplication) { String sessionId = createNewSessionId(); HttpSessionImpl ses = new HttpSessionImpl(webApplication, sessionId); sessionMap.put(sessionId, ses); return ses; } @Override public void close() { for (HttpSessionImpl session : sessionMap.values()) { session.invalidate(); } sessionMap.clear(); } }
package gogo7_09; import java.util.Scanner; public class insooday { //made by insoo public static void main(String[] args) throws Exception { // TODO Auto-generated method stub Scanner sc = new Scanner(System.in); System.out.println("\t***INSOO BANK EXCHANGE SERVICE***"); memu menu = new memu(6); menu.selectmenu(); // ********구현 간략 설명 ********* //패키지 간의 클래스 사용 //jsoup libary를 사용한 네이버 환율정보 스크래이핑 //DecimalFormat API사용해서 숫자 형식 표시 //while문을 활용해서 반복 진행 구현 } }
package Networking; import java.rmi.Naming; public class PiClient { public static void doIt(String host, String port, int digits) { String message = ""; try { Pi_MyServer obj = (Pi_MyServer) Naming.lookup("//" + host + ":" + port + "/PiServer"); System.out.println(obj.computePi(digits)); } catch (Exception e) { System.out.println("Something went wrong: " + e.getMessage()); e.printStackTrace(); } } public static void main(String args[] ) { int digits = 10; String host = "yps"; String port = ""; if ( args.length >= 1 ) { try { digits = Integer.parseInt(args[0]); } catch ( NumberFormatException e ) { System.out.println("Hm , digits = " + args[0]); System.exit(1); } } if ( args.length >= 2 ) { host = args[1]; } if ( args.length == 3 ) { try { port = args[2]; Integer.parseInt(port); } catch ( NumberFormatException e ) { System.out.println("Port = " + port + " is not valid."); System.exit(1); } } if ( args.length > 3 ) { System.out.println("Usage: java Client [digits [host [port]]]"); System.exit(1); } doIt(host, port, digits); } }
package com.yksoul.demo.controller; import com.yksoul.demo.utils.R; import com.yksoul.demo.utils.RequestUtils; import com.yksoul.pay.domain.enums.AliPaymentEnum; import com.yksoul.pay.domain.model.PayModel; import com.yksoul.pay.payment.PaymentHandler; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import javax.servlet.http.HttpServletRequest; import java.util.Map; /** * @author yk * @version 1.0 * @date 2018-07-11 */ @RestController @RequestMapping("/pay") @Slf4j public class PayController { private final PaymentHandler paymentManager; @Autowired public PayController(PaymentHandler paymentManager) { this.paymentManager = paymentManager; } /*@GetMapping(value = "/{prefix}/{type}/{orderSn}", produces="text/html;charset=UTF-8") public String onPay(@PathVariable("prefix") String prefix, @PathVariable("type") Integer type, @PathVariable("orderSn") String orderSn) { String s = paymentManager.onPay(prefix, type, orderSn); return s; }*/ @GetMapping(value = "/{prefix}/{type}/{orderSn}") public R<String> onPay(@PathVariable("prefix") String prefix, @PathVariable("type") Integer type, @PathVariable("orderSn") String orderSn, String authCode, String storeId) { PayModel payModel = PayModel.builder().prefix(prefix).payCode(type).body("测试商品").orderSn(orderSn).subject("支付").payment(AliPaymentEnum.ALIPAY_TRADE_PAGE).totalAmount("0.01").authCode(authCode).storeId(storeId).build(); String s = paymentManager.onPay(payModel); return new R<>(s); } @GetMapping("/return") public Map<String, Object> onReturn(HttpServletRequest request) throws Exception { Map<String, Object> allParams = RequestUtils.getAllParams(request); return allParams; } @PostMapping("/notify") public void onNotify(HttpServletRequest request) throws Exception { Map<String, Object> allParams = RequestUtils.getAllParams(request); StringBuilder sb = new StringBuilder(); allParams.keySet().forEach(k -> { sb.append(k).append("=").append(allParams.get(k).toString()).append("&"); }); System.out.println(sb.toString()); paymentManager.onNotify(allParams); } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright * ownership. The ASF licenses this file to you under the Apache * License, Version 2.0 (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied. See the License for the specific * language governing permissions and limitations under the License. */ package org.apache.clerezza.dataset; /** * This interface is implemented by providers to which {@link TcManager} * delegates. * * @author reto */ public interface WeightedTcProvider extends TcProvider { /** * Get the weight of this provider. {@link TcManager} will prioritize * <code>TcProvider</code>s with greater weight. * * @return a positive number indicating the weight of the provider */ int getWeight(); }
package com.mx.profuturo.bolsa.model.service.vacancies.dto; import java.io.Serializable; public class GetJobBoardResponse implements Serializable { }
import java.io.*; import java.util.*; public class SalamanderTraceActivity { /* ***** Topher's Code For Trace Activity *******/ public static void main(String[] args) { ArrayList salamander = new ArrayList(); //explicitly fill arraylist with intent to search for // present and nonpresent values... // generate an arraylist with an odd num of elems... salamander.add(4); salamander.add(8); salamander.add(15); salamander.add(16); salamander.add(23); System.out.println(salamander); System.out.println("BoogleCount.binSearch(salamander, 8) (1)"); System.out.println(BoogleCount.binSearch(salamander, 8)); // 1 System.out.println("BoogleCount.binSearch(salamander, 15) (2)"); System.out.println(BoogleCount.binSearch(salamander, 15)); // 2 System.out.println("BoogleCount.binSearch(salamander, 16) (3)"); System.out.println(BoogleCount.binSearch(salamander, 16)); // 3 //search for target not in the list System.out.println("BoogleCount.binSearch(salamander, 3) (-1)"); System.out.println(BoogleCount.binSearch(salamander, 3)); // -1 System.out.println("BoogleCount.binSearch(salamander, 9) (-1)"); System.out.println(BoogleCount.binSearch(salamander, 9)); // -1 //add another element, for an even num of elems salamander.add(42); System.out.println(salamander); //search for target in the list System.out.println("BoogleCount.binSearch(salamander, 8) (1)"); System.out.println(BoogleCount.binSearch(salamander, 8)); // 1 System.out.println("BoogleCount.binSearch(salamander, 15) (2)"); System.out.println(BoogleCount.binSearch(salamander, 15)); // 2 System.out.println("BoogleCount.binSearch(salamander, 16) (3)"); System.out.println(BoogleCount.binSearch(salamander, 16)); // 3 //search for target not in the list System.out.println("BoogleCount.binSearch(salamander, 3) (-1)"); System.out.println(BoogleCount.binSearch(salamander, 3)); // -1 System.out.println("BoogleCount.binSearch(salamander, 9) (-1)"); System.out.println(BoogleCount.binSearch(salamander, 9)); // -1 }//end main /***** End Trace Activity Code *******/ }//end class
package com.yixin.kepler.enity; import java.util.ArrayList; import java.util.List; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Table; import org.apache.commons.collections.CollectionUtils; import org.assertj.core.util.Lists; import com.yixin.common.system.domain.BZBaseEntiy; import com.yixin.common.system.util.Label; import com.yixin.kepler.common.enums.BankPhaseEnum; import com.yixin.kepler.core.constant.CommonConstant; @Entity @Table(name = "k_asset_payment_task") public class AssetPaymentTask extends BZBaseEntiy{ private static final long serialVersionUID = 1L; @Label(name = "申请编号") @Column(name = "apply_no", length = 32) private String applyNo; @Label(name = "是否成功") @Column(name = "is_success", length = 1) private Boolean isSuccess; @Label(name = "是否结束") @Column(name = "is_end", length = 1) private Boolean isEnd; @Label(name = "资方code") @Column(name = "asset_code", length = 32) private String assetCode; @Label(name = "执行状态") @Column(name = "exec_state", length = 2) private Integer execState; @Label(name = "执行次数") @Column(name = "exec_times", length = 12) private Integer execTimes; @Label(name = "文件是否上传成功") @Column(name = "file_status",length = 1) private Integer fileStatus; public Integer getFileStatus() { return fileStatus; } public void setFileStatus(Integer fileStatus) { this.fileStatus = fileStatus; } public String getApplyNo() { return applyNo; } public void setApplyNo(String applyNo) { this.applyNo = applyNo; } public Boolean getIsSuccess() { return isSuccess; } public void setIsSuccess(Boolean isSuccess) { this.isSuccess = isSuccess; } public String getAssetCode() { return assetCode; } public void setAssetCode(String assetCode) { this.assetCode = assetCode; } public Boolean getIsEnd() { return isEnd; } public void setIsEnd(Boolean isEnd) { this.isEnd = isEnd; } public Integer getExecState() { return execState; } public void setExecState(Integer execState) { this.execState = execState; } public Integer getExecTimes() { return execTimes; } public void setExecTimes(Integer execTimes) { this.execTimes = execTimes; } public static AssetPaymentTask getByApplyNo(String applyNo) { String jpql = "SELECT apt FROM AssetPaymentTask AS apt WHERE" + " apt.deleted = 0 AND apt.applyNo = ?1"; List<Object> params = new ArrayList<Object>(1) {{ add(applyNo); }}; return getRepository().createJpqlQuery(jpql.toString()) .setParameters(params).singleResult(); } public static List<AssetPaymentTask> getCurrentTask() { // add by wanghonglin 修改查询条数,一次最多执行50条数据。2018-09-26 /*String jpql = "SELECT apt FROM AssetPaymentTask AS apt WHERE" + " apt.deleted = 0 AND apt.isEnd = 0 LIMIT 50";*/ String sql = " SELECT id FROM k_asset_payment_task " + " WHERE is_deleted = FALSE AND is_end = FALSE " + " AND file_status = ?1 " + " ORDER BY create_time ASC " + " LIMIT 50 "; List<Object> params = Lists.newArrayList(CommonConstant.ONE); List<Object> resultList = getRepository().createSqlQuery(sql).setParameters(params).list(); if(CollectionUtils.isEmpty(resultList)){ return Lists.newArrayList(); } List<AssetPaymentTask> taskList = Lists.newArrayList(); for(Object result:resultList){ String id = (String)result; //主键 if(id == null){ continue; } taskList.add(AssetPaymentTask.get(AssetPaymentTask.class, id)); } return taskList; } /** * 更新任务记录结束状态 * @param id 任务主键 * @param isSuccess 是否成功 * @author YixinCapital -- wangwenlong * 2018年10月9日 下午4:21:04 */ public void updateTaskEnd(boolean isSuccess,String errorCode,String errorMessage){ this.setIsSuccess(isSuccess); this.setIsEnd(true); this.update(); if(!isSuccess){ //失败,则记录错误日志 /** * 情况异常记录表 */ AssetPaymentFail failLog = new AssetPaymentFail(); failLog.setApplyNo(this.getApplyNo()); failLog.setAssetCode(this.getAssetCode()); failLog.setBankCode(errorCode); failLog.setBankMessage(errorMessage); failLog.setIsSuccess(false); failLog.setPhase(BankPhaseEnum.PAYMENT.getPhase()); failLog.create(); } } /** * * @author YixinCapital -- wangwenlong * 2018年10月12日 下午2:14:55 */ public void addOneTimes(){ this.setExecTimes((this.getExecTimes() == null?1:this.getExecTimes())+1); this.update(); } }
package util; import com.google.gson.Gson; import java.io.InputStream; import java.io.InputStreamReader; public class JobFileParser { public Jobs readConfigFile() { Gson gson = new Gson(); InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream("job.json"); InputStreamReader reader = new InputStreamReader(resourceAsStream); return gson.fromJson(reader, Jobs.class); } }
package com.hevi; import lombok.Data; import org.junit.Test; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; public class LambdaTest { @Data private class Person { private String name; private List<Car> cars; public Person(String name, List<Car> cars) { this.name = name; this.cars = cars; } } @Data private class Car { private String type; private Integer maxSpeed; public Car(String type, Integer maxSpeed) { this.type = type; this.maxSpeed = maxSpeed; } } @Test public void lambdaTest() throws Exception { Car c1 = new Car("奥迪", 200); Car c2 = new Car("奔驰", 221); Car c3 = new Car("五菱", 120); Car c4 = new Car("GTR", 320); Car c5 = new Car("雪佛兰", 123); List<Car> cars1 = Arrays.asList(c2, c4, c5); List<Car> cars2 = Arrays.asList(c1, c5); List<Car> cars3 = Arrays.asList(c1, c2, c3, c4, c5); Person peter = new Person("Peter",cars1); Person anna = new Person("Anna",cars2); Person tom = new Person("Tom",cars3); List<Person> personList = Arrays.asList(peter, anna, tom); List nameList = personList.stream().map(p->p.getName()).collect(Collectors.toList()); System.out.println(nameList); List pList = personList.stream().filter(p->p.getCars().size()>=3).collect(Collectors.toList()); System.out.println(pList); } }