text
stringlengths
10
2.72M
package com.proky.booking.presentation.controller; import com.proky.booking.util.constans.Attributes; import lombok.extern.log4j.Log4j2; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.*; @Log4j2 @Controller @SessionAttributes(Attributes.LANGUAGE) public class LanguageController { @GetMapping("/changeLanguage") public String changeLanguage(@RequestParam(defaultValue = "en") String language, @RequestHeader(value = "referer", required = false) final String referer, Model model) { model.addAttribute(Attributes.LANGUAGE, language); return "redirect:" + referer; } }
package com.example.androidquizapp; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.Toolbar; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import android.os.Bundle; import android.widget.LinearLayout; import com.example.androidquizapp.model.Adapter; import java.util.ArrayList; import java.util.List; public class profCategoryActivity extends AppCompatActivity { RecyclerView profCategoryRecyclerView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_prof_category); Toolbar toolbar = findViewById(R.id.toolbar); setSupportActionBar(toolbar); getSupportActionBar().setTitle("Subject"); profCategoryRecyclerView = findViewById(R.id.profCategoryRecyclerView); List<String> cat_list = new ArrayList<>(); cat_list.add("SEPA"); cat_list.add("UNP"); cat_list.add("DM"); Adapter adapter = new Adapter(cat_list); profCategoryRecyclerView.setAdapter(adapter); LinearLayoutManager layoutManager = new LinearLayoutManager(this); layoutManager.setOrientation(LinearLayoutManager.VERTICAL); profCategoryRecyclerView.setLayoutManager(layoutManager); } }
package com.misa.pool; import android.app.Application; public class BaseApplication extends Application { public void onCreate() { } }
package tradingmaster.db.entity; import javax.persistence.*; import java.util.Date; @Entity @Table(uniqueConstraints={ @UniqueConstraint(columnNames = {"exchange", "market"}) }) public class MarketWatcher { @Id @GeneratedValue(strategy = GenerationType.AUTO) Integer id; @Column(nullable = false) String exchange; @Column(nullable = false) String market; @Column(nullable = false) boolean active = false; @Column(nullable = false) Long intervalMillis = new Long(10000); @Column(nullable = false) Date startDate = new Date(); @Column String integrationFlowId; public MarketWatcher() { } public MarketWatcher(String exchange, String market) { this.exchange = exchange; this.market = market; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getExchange() { return exchange; } public void setExchange(String exchange) { this.exchange = exchange; } public String getMarket() { return market; } public void setMarket(String market) { this.market = market; } public boolean isActive() { return active; } public void setActive(boolean active) { this.active = active; } public Date getStartDate() { return startDate; } public String getIntegrationFlowId() { return integrationFlowId; } public void setStartDate(Date startDate) { this.startDate = startDate; } public void setIntegrationFlowId(String integrationFlowId) { this.integrationFlowId = integrationFlowId; } public Long getIntervalMillis() { return intervalMillis; } public void setIntervalMillis(Long intervalMillis) { this.intervalMillis = intervalMillis; } }
package com.alex; import com.alex.eat.Lapa; import com.alex.exceptions.PetIsDeadException; import com.alex.pets.Bear; import com.alex.pets.Dragon; import org.junit.Assert; import org.junit.Test; import com.alex.eat.Wet; public class BearTest { public Object object; @Test public void testBearCanSosoatLapy() { Bear bear = new Bear("Kopatych", "Grizli", "brown"); Lapa lapa = new Lapa("lapa", "43"); bear.grblzt(lapa); Assert.assertTrue("Can bear sosat lapy", lapa.isWet()); } @Test public void testCanBearSushitLapy() { Bear bear = new Bear("Kopatych", "Grizli", "brown"); Lapa lapa = new Lapa("lapa", "43"); if (bear.isAlive()) { lapa.dry(); } else { lapa.namochit(); } Assert.assertFalse("Can bear sushit lapy", lapa.isWet()); } @Test(expected = PetIsDeadException.class) public void testBearsDeath() { Bear bear = new Bear("Misha", "beliy", "white"); Dragon dragon = new Dragon("Hvostoroga", "Fire"); dragon.kill(bear); bear.grblzt(new Lapa("lapa", "43")); } }
package com.aisino.invoice.pygl.po; import java.util.Date; /** * @ClassName: FwkpUserXfsh * @Description: * @author: ZZc * @date: 2016年10月10日 下午8:07:25 * @Copyright: 2016 航天信息股份有限公司-版权所有 * */ public class FwkpUserXfsh { public String getUser_id() { return user_id; } public void setUser_id(String user_id) { this.user_id = user_id; } public String getXfsh() { return xfsh; } public void setXfsh(String xfsh) { this.xfsh = xfsh; } public int getKpjh() { return kpjh; } public void setKpjh(int kpjh) { this.kpjh = kpjh; } private String qysb; private String cjrid; private Date cjrq; private String des; private String reserve; private String user_id; private String xfsh; private int kpjh; public String getCjrid() { return cjrid; } public void setCjrid(String cjrid) { this.cjrid = cjrid == null ? null : cjrid.trim(); } public Date getCjrq() { return cjrq; } public void setCjrq(Date cjrq) { this.cjrq = cjrq; } public String getDes() { return des; } public void setDes(String des) { this.des = des == null ? null : des.trim(); } public String getReserve() { return reserve; } public void setReserve(String reserve) { this.reserve = reserve == null ? null : reserve.trim(); } public String getQysb() { return qysb; } public void setQysb(String qysb) { this.qysb = qysb; } @Override public String toString() { return "<fwkp_user_xfsh " + "user_id='" + user_id + "',xfsh='" + xfsh + "',kpjh='" + kpjh + "',cjrid='" + cjrid + "', cjrq='" + cjrq + "'/>"; } }
package adcar.com.algorithms; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Random; import adcar.com.database.dao.AdDAO; import adcar.com.database.dao.CampaignInfoDAO; import adcar.com.factory.Factory; import adcar.com.model.Ad; import adcar.com.model.CampaignInfo; /** * Created by adinema on 17/05/16. */ public class AdAlgorithms { private static CampaignInfoDAO campaignInfoDAO = (CampaignInfoDAO)Factory.getInstance().get(Factory.DAO_CAMPAIGN_INFO); public static Random random = new Random(); public static CampaignInfo getAdIdToDisplay(Integer areaId, String time){ List<CampaignInfo> campaignInfoList = campaignInfoDAO.getAdsForArea(areaId, time); if(campaignInfoList.size()==0){ return null; } Collections.sort(campaignInfoList); int size = campaignInfoList.size(); int no = getRandomNoBetween(0, size-1); return campaignInfoList.get(no); } public static Integer getRandomNoBetween(Integer a, Integer b){ return random.nextInt(b-a+1) + a; } }
package Spark.SparkBasicOperations.anuj; import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.apache.commons.lang3.StringUtils; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.LocatedFileStatus; import org.apache.hadoop.fs.Path; import org.apache.hadoop.fs.RemoteIterator; import org.apache.spark.api.java.JavaRDD; import org.apache.spark.sql.Dataset; import org.apache.spark.sql.Row; import org.apache.spark.sql.SparkSession; import org.apache.spark.sql.catalyst.expressions.GenericRowWithSchema; import org.apache.spark.sql.types.DataTypes; import org.apache.spark.sql.types.StructField; import org.apache.spark.sql.types.StructType; /** * * @author anujmehra * */ public class CreateMultipleParquetsForImpala { public static void main(final String args[]) throws IOException{ final SparkSession sparkSession = SparkSession .builder() .master("local[*]") .appName("Java Spark SQL basic example") .getOrCreate(); //Read all parquet files preset at a location in HDFS final String inputPath = args[0]; final String outputPath = args[1]; /* String inputPath = "/am/staging_data/8001/sf_data_extension_cleaning/"; String outputPath = "/am/qarelease/1801/impala/salesforce/cleaning/"; */ final List<String> fileNames = getFileNames(inputPath); for(final String fileName : fileNames){ final Dataset<Row> input = sparkSession.read().parquet(inputPath + fileName); final JavaRDD<Row> inputRowJavaRDD = input.javaRDD(); final StructType inputSchema = input.schema(); final StructField[] schemaFields = inputSchema.fields(); final StructField[] schemaFieldsWithStringDataType = new StructField[schemaFields.length]; int counter = 0; for(final StructField field : schemaFields){ schemaFieldsWithStringDataType[counter]= DataTypes.createStructField(field.name(), DataTypes.StringType, true); counter++; } final StructType newSchema = DataTypes.createStructType(schemaFieldsWithStringDataType); System.out.println(inputSchema); System.out.println("*********************************"); System.out.println(newSchema); final JavaRDD<Row> finalRDD = inputRowJavaRDD.map((row) ->{ final Object[] newValues = new Object[newSchema.fieldNames().length]; int i=0; for(final String fieldName : newSchema.fieldNames()){ newValues[i] = row.getAs(fieldName) == null ? null : row.getAs(fieldName).toString(); i++; } return new GenericRowWithSchema(newValues, newSchema); }); final Dataset<Row> outputDataset = sparkSession.createDataFrame(finalRDD, newSchema); outputDataset.write().parquet(outputPath + fileName); } } public static final int HADOOP_FILE_READ_BUFFER_SIZE = 262144 * 2; public static transient Configuration conf = null; public static org.apache.hadoop.conf.Configuration newHadoopConf() { final org.apache.hadoop.conf.Configuration hadoopConf = new org.apache.hadoop.conf.Configuration(); hadoopConf.set("fs.maprfs.impl", "com.mapr.fs.MapRFileSystem"); hadoopConf.setInt("io.file.buffer.size", HADOOP_FILE_READ_BUFFER_SIZE); return hadoopConf; } private static void init() { if (conf == null) { conf = newHadoopConf(); } } public static List<String> getFileNames(final String directoryPath) throws IOException { init(); List<String> fileNames = null; if (!StringUtils.isEmpty(directoryPath)) { final Path dstPath = new Path(directoryPath); fileNames = new ArrayList<>(); final FileSystem fileSystem = dstPath.getFileSystem(conf); final RemoteIterator<LocatedFileStatus> filesIterator = fileSystem.listLocatedStatus(dstPath); if (filesIterator != null) { while (filesIterator.hasNext()) { fileNames.add(filesIterator.next().getPath().getName()); } } } return fileNames; } }
package com.hoanganhtuan95ptit.awesomekeyboard; import android.content.Context; import android.util.AttributeSet; import android.widget.RelativeLayout; import com.hoanganhtuan95ptit.awesomekeyboard.callback.OnDeleteClickListener; import com.hoanganhtuan95ptit.awesomekeyboard.callback.OnItemColorClickListener; import com.hoanganhtuan95ptit.awesomekeyboard.callback.OnItemEmoticonClickListener; import com.hoanganhtuan95ptit.awesomekeyboard.callback.OnItemPhotoClickListener; import com.hoanganhtuan95ptit.awesomekeyboard.callback.OnItemStickerClickListener; import com.hoanganhtuan95ptit.awesomekeyboard.callback.OnShopClickListener; import com.hoanganhtuan95ptit.awesomekeyboard.view.ColorLayout; import com.hoanganhtuan95ptit.awesomekeyboard.view.PhotoLayout; import com.hoanganhtuan95ptit.awesomekeyboard.view.StickerLayout; /** * Created by HOANG ANH TUAN on 7/5/2017. */ public class KeyboardLayout extends RelativeLayout { private StickerLayout stickerLayout; private PhotoLayout photoLayout; private ColorLayout colorLayout; public KeyboardLayout(Context context) { super(context); addKeyboard(); } public KeyboardLayout(Context context, AttributeSet attrs) { super(context, attrs); addKeyboard(); } public KeyboardLayout(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); addKeyboard(); } private void addKeyboard() { stickerLayout = new StickerLayout(getContext()); photoLayout = new PhotoLayout(getContext()); colorLayout = new ColorLayout(getContext()); addView(colorLayout, LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT); addView(photoLayout, LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT); addView(stickerLayout, LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT); stickerLayout.setVisibility(GONE); photoLayout.setVisibility(GONE); colorLayout.setVisibility(GONE); } public void showSticker() { stickerLayout.executeSticker(); photoLayout.setVisibility(GONE); colorLayout.setVisibility(GONE); } public void showPhoto() { photoLayout.executePhoto(); stickerLayout.setVisibility(GONE); colorLayout.setVisibility(GONE); } public void showColor() { colorLayout.executeColor(); photoLayout.setVisibility(GONE); stickerLayout.setVisibility(GONE); } public void updateStiker(){ stickerLayout.updateSticker(); } public void setOnDeleteClickListener(OnDeleteClickListener onDeleteClickListener) { stickerLayout.setOnDeleteClickListener(onDeleteClickListener); } public void setOnShopClickListener(OnShopClickListener onShopClickListener) { stickerLayout.setOnShopClickListener(onShopClickListener); } public void setOnItemEmoticonClickListener(OnItemEmoticonClickListener onItemEmoticonClickListener) { stickerLayout.setOnItemEmoticonClickListener(onItemEmoticonClickListener); } public void setOnItemStickerClickListener(OnItemStickerClickListener onItemStickerClickListener) { stickerLayout.setOnItemStickerClickListener(onItemStickerClickListener); } public void setOnItemPhotoClickListener(OnItemPhotoClickListener onItemPhotoClickListener) { photoLayout.setOnItemPhotoClickListener(onItemPhotoClickListener); } public void setOnItemColorClickListener(OnItemColorClickListener onItemColorClickListener) { colorLayout.setOnItemColorClickListener(onItemColorClickListener); } }
package com.day07code; /* 测试类 */ public class StudentDemo07 { public static void main(String[] args) { //创建对象 Student07 s = new Student07(); s.show(); } }
import java.awt.Color; import java.awt.Point; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseEvent; import java.awt.event.MouseMotionListener; import java.util.ArrayList; import java.util.Random; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.Timer; public class BallBounce implements Runnable, MouseMotionListener { JFrame frame; JPanel pane; Ball ball; BallShape b1; BallShape b2; BallShape b3; BallShape b4; BallShape b5; BallShape b6; BallShape b7; Timer t; boolean directX = false; boolean directY = false; int x, y = Integer.MAX_VALUE; ArrayList<BallShape> balls; Random rand; @Override public void run() { balls = new ArrayList<BallShape>(); ActionListener taskPerformer = new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if(intersects(x, y)){ System.exit(0); } for(int i = 0; i < balls.size(); i++){ for(int ii = i+1; ii < balls.size(); ii++){ if(balls.get(i).intersects(balls.get(ii))){ balls.get(ii).changeX(); balls.get(ii).changeY(); balls.get(i).changeX(); balls.get(i).changeY(); } } if(balls.get(i).returnX() >= 180 || balls.get(i).returnX() < 0){ balls.get(i).changeX(); } if(balls.get(i).returnY()>= 460 || balls.get(i).returnY() < 0){ balls.get(i).changeY(); } balls.get(i).update(); } ball.repaint(); } }; frame = new JFrame("Ball Bounce"); frame.setBounds(0, 0, 200, 500); pane = new JPanel(null); pane.setBounds(0, 0, 200, 500); ball = new Ball(); ball.setBounds(0, 0, 200, 500); rand = new Random(System.currentTimeMillis()); b1 = new BallShape(rand.nextInt(160), rand.nextInt(460), Color.BLACK); b2 = new BallShape(rand.nextInt(160), rand.nextInt(460), Color.RED); b3 = new BallShape(rand.nextInt(160), rand.nextInt(460), Color.PINK); b4 = new BallShape(rand.nextInt(160), rand.nextInt(460), Color.ORANGE); b5 = new BallShape(rand.nextInt(160), rand.nextInt(460), Color.GREEN); b6 = new BallShape(rand.nextInt(160), rand.nextInt(460), Color.YELLOW); b7 = new BallShape(rand.nextInt(160), rand.nextInt(460), Color.MAGENTA); ball.addBall(b1); ball.addBall(b2); ball.addBall(b3); ball.addBall(b4); ball.addBall(b5); ball.addBall(b6); ball.addBall(b7); balls.add(b1); balls.add(b2); balls.add(b3); balls.add(b4); balls.add(b5); balls.add(b6); balls.add(b7); frame.add(pane); pane.add(ball); ball.setBackground(Color.CYAN); pane.addMouseMotionListener(this); frame.setVisible(true); t = new Timer(10, taskPerformer); t.start(); } @Override public void mouseDragged(MouseEvent e) { System.out.println(e.getX() + "\t" + e.getY()); if(e.getX()>= ball.x && e.getX() <= ball.x+40){ System.exit(0); } if(e.getY()>= ball.y && e.getY() <= ball.y+40){ System.exit(0); } } @Override public void mouseMoved(MouseEvent e) { x = e.getX(); y = e.getY(); } private boolean intersects(int w, int h){ for(int i = 0; i < balls.size(); i++){ if(balls.get(i).intersects(x, y, 1, 1)){ return true; } } return false; } }
package mobi.app.test; import mobi.app.redis.RedisClient; import mobi.app.redis.netty.SyncRedisClient; import java.util.concurrent.TimeUnit; /** * User: thor * Date: 13-1-6 * Time: 下午3:53 */ public class TestReconnect { public static void main(String[] args){ RedisClient client = new SyncRedisClient("172.16.3.214:6379", 1, null, 1, TimeUnit.SECONDS, 1); } }
package com.wms.db; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Timestamp; import java.util.ArrayList; import java.util.List; import java.util.Properties; /** * 数据库管理类 * @author win7 * */ public class DBManager { public static final String DEFAULT_DRIVER_NAME = "net.sourceforge.jtds.jdbc.Driver"; public static final String DEFAULT_DB_URL = "jdbc:jtds:sqlserver://localhost:1433;DatabaseName=wms"; public static String DB_URL = null; public static Properties prop = null; public Connection getConnection() { Connection coon = null; try { Class.forName(DEFAULT_DRIVER_NAME); coon = DriverManager.getConnection(DEFAULT_DB_URL,"sa","8888"); } catch (Exception e) { e.printStackTrace(); } return coon; } public static void main(String[] args) { DBManager manager = new DBManager(); manager.getConnection(); } public boolean login(String username, String pwd) { Connection coon = getConnection(); ResultSet rs = null; PreparedStatement pstmt = null; try { pstmt = coon .prepareStatement("select * from admin where name='" + username + "' and pwd='" + pwd + "'"); rs = pstmt.executeQuery(); while (rs.next()) { return true; } } catch (SQLException e) { e.printStackTrace(); } finally { try { if (pstmt != null) pstmt.close(); if (coon != null) coon.close(); } catch (Exception e) { e.printStackTrace(); } } return false; } }
package com.zjy.dao; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.zjy.entity.Admin; public class AdminDao extends BaseDao { private static Log log = LogFactory.getLog(AdminDao.class); /** * 验证登陆 * @param user * @return */ public boolean hasAdmin(Admin user){ Admin a = (Admin) super.get(Admin.class, user.getUserName()); log.debug(a); return user.equals(a); } }
package com.appdirect.Pages; import java.io.IOException; import java.util.Properties; import java.util.concurrent.TimeUnit; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import com.appdirect.Utils.ReadFile; public class SignUpPage { WebDriver driver; String xpath; public SignUpPage(WebDriver driver) { this.driver = driver; } public void SignUpPageFuntionalities() throws IOException { driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS); ReadFile read = new ReadFile(); Properties pr = read.propertyFile("SignUp.properties"); System.out.println("ewdedbwh"); xpath = pr.getProperty("xpath"); signUp(); } public void signUp() { driver.findElement(By.xpath(xpath)).click(); } }
package com.example.app.intentservicetest; import android.content.Intent; import android.content.IntentFilter; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.ProgressBar; import android.widget.TextView; public class MainActivity extends AppCompatActivity { TextView tv; ProgressBar pb; MyReceiver receiver; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); tv = (TextView) findViewById(R.id.tv); pb = (ProgressBar) findViewById(R.id.pb); pb.setMax(100); pb.setProgress(0); receiver = new MyReceiver(callBack); IntentFilter filter = new IntentFilter(); filter.addAction("pro"); registerReceiver(receiver,filter); Intent intent = new Intent(this, MyService.class); startService(intent); } public MyReceiver.CallBack callBack = new MyReceiver.CallBack() { @Override public void updateUi(int progress) { tv.setText(progress + "%"); pb.setProgress(progress); } }; @Override protected void onDestroy() { super.onDestroy(); unregisterReceiver(receiver); } }
package com.core.util; import java.util.Objects; public class Position { public float x; public float y; public Position() { } public Position(float x, float y) { this.x = x; this.y = y; } public float getX() { return x; } public void setX(float x) { this.x = x; } public float getY() { return y; } public void setY(float y) { this.y = y; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Position position = (Position) o; return Float.compare(position.x, x) == 0 && Float.compare(position.y, y) == 0; } @Override public int hashCode() { return Objects.hash(x, y); } @Override public String toString() { final StringBuilder sb = new StringBuilder(); sb.append("Position "); sb.append('(').append(x); sb.append(", "); sb.append(y).append(')'); return sb.toString(); } }
import java.util.ArrayList; import java.util.Date; import java.time.temporal.ChronoUnit; import java.time.*; public class Reservation { public Date date; public Double identifiant; public String etat; public ArrayList<Passager> passagers; public Reservation(Date date,Double identifiant, String etat){ this.date =date; this.identifiant = identifiant; this.etat = etat; passagers = new ArrayList<>(); } public void annuler(){ this.etat="annulation"; } public void confirmer(){ this.etat="confirmation"; } public void payer(){ this.etat="payement"; } }
package gr.javapemp.vertxonspring.model.pagination; import io.vertx.codegen.annotations.DataObject; import io.vertx.core.json.JsonArray; import io.vertx.core.json.JsonObject; import org.springframework.data.domain.Page; import java.util.List; import java.util.stream.Collectors; @DataObject(generateConverter = true) public class PageList { private int totalPages; private long totalElements; private int number; private int size; private int numberOfElements; private JsonArray content; private boolean hasContent; private boolean isFirst; private boolean isLast; private boolean hasNext; private boolean hasPrevious; public PageList(Page data) { this.totalPages = data.getTotalPages(); this.totalElements = data.getTotalElements(); this.number = data.getNumber(); this.size = data.getSize(); this.numberOfElements = data.getNumberOfElements(); this.content = new JsonArray( (List<JsonObject>) data.toList().stream().map(JsonObject::mapFrom).collect(Collectors.toList()) ); this.hasContent = data.hasContent(); this.isFirst = data.isFirst(); this.isLast = data.isLast(); this.hasNext = data.hasNext(); this.hasPrevious = data.hasPrevious(); } public PageList(JsonObject jsonObject) { PageListConverter.fromJson(jsonObject, this); } public JsonObject toJson() { JsonObject json = new JsonObject(); PageListConverter.toJson(this, json); return json; } public int getTotalPages() { return totalPages; } public void setTotalPages(int totalPages) { this.totalPages = totalPages; } public long getTotalElements() { return totalElements; } public void setTotalElements(long totalElements) { this.totalElements = totalElements; } public int getNumber() { return number; } public void setNumber(int number) { this.number = number; } public int getSize() { return size; } public void setSize(int size) { this.size = size; } public int getNumberOfElements() { return numberOfElements; } public void setNumberOfElements(int numberOfElements) { this.numberOfElements = numberOfElements; } public JsonArray getContent() { return content; } public void setContent(JsonArray content) { this.content = content; } public boolean isHasContent() { return hasContent; } public void setHasContent(boolean hasContent) { this.hasContent = hasContent; } public boolean isFirst() { return isFirst; } public void setFirst(boolean first) { isFirst = first; } public boolean isLast() { return isLast; } public void setLast(boolean last) { isLast = last; } public boolean isHasNext() { return hasNext; } public void setHasNext(boolean hasNext) { this.hasNext = hasNext; } public boolean isHasPrevious() { return hasPrevious; } public void setHasPrevious(boolean hasPrevious) { this.hasPrevious = hasPrevious; } }
public class HorseFactory { public static HorseBase create(HorseType type){ HorseBase.HorseBuilder builder = new HorseBase.HorseBuilder(); switch (type) { case My: builder.setHorseName("My Horse") .setRun(new MyHorse()); break; case Jeju: builder.setHorseName("Jeju Horse") .setRun(new JejuHorse()); break; case Black: builder.setHorseName("Black horse") .setRun(new BlackHorse()); break; } return builder.build(); } }
package routines; import java.util.Date; import java.util.regex.Matcher; import java.util.regex.Pattern; /* * user specification: the function's comment should contain keys as follows: 1. write about the function's comment.but * it must be before the "{talendTypes}" key. * * 2. {talendTypes} 's value must be talend Type, it is required . its value should be one of: String, char | Character, * long | Long, int | Integer, boolean | Boolean, byte | Byte, Date, double | Double, float | Float, Object, short | * Short * * 3. {Category} define a category for the Function. it is required. its value is user-defined . * * 4. {param} 's format is: {param} <type>[(<default value or closed list values>)] <name>[ : <comment>] * * <type> 's value should be one of: string, int, list, double, object, boolean, long, char, date. <name>'s value is the * Function's parameter name. the {param} is optional. so if you the Function without the parameters. the {param} don't * added. you can have many parameters for the Function. * * 5. {example} gives a example for the Function. it is optional. */ public class Hao { /** * helloExample: not return value, only print "hello" + message. * * * {talendTypes} String * * {Category} User Defined * * {param} string("world") input: The string need to be printed. * * {example} helloExemple("world") # hello world !. */ public static void helloExample(String message) { if (message == null) { message = "World"; //$NON-NLS-1$ } System.out.println("Hello " + message + " !"); //$NON-NLS-1$ //$NON-NLS-2$ } /** * 从字符串中取出url * @param ligne * @return */ public static String get_url(String ligne) { if(ligne==null) { return null; } else { Pattern p = Pattern.compile("<!-- saved from url=\\([0-9]+\\)(https:[^\t^ ^\r^\n]+) -->"); Matcher m = p.matcher(ligne); if(m.find()) { return m.group(1); } else { return null; } } } /** * 从链接中取出ID * @param ligne_url * @return */ public static String get_id_from_url(String ligne_url) { if(ligne_url==null) { return null; } else { Pattern p = Pattern.compile("<!-- saved from url=\\([0-9]+\\)https://www.meetic.fr/d/profile-display/([0-9]+)\\?[^ ]+ -->"); Matcher m = p.matcher(ligne_url); if(m.find()) { return m.group(1); } else { return null; } } } /** * Get the informations of the user from the content * @param ligne_contenu * @param type * @return */ public static String get_infos_from_contenu(String ligne_contenu, String type) { if(ligne_contenu==null) { return null; } else { Pattern p = Pattern.compile(" "); Matcher m = p.matcher(ligne_contenu); String resultat = null; switch (type){ case "name": p = Pattern.compile("<title>([^<]+) - Meetic</title>"); m = p.matcher(ligne_contenu); if(m.find()) resultat = m.group(1); break; case "age": p = Pattern.compile("ctrl\\.age}\">([0-9]+) ans</span>"); m = p.matcher(ligne_contenu); if(m.find()) resultat = m.group(1); break; case "photo": p = Pattern.compile("class=\"pictures-main-area__picture\" style=\"background-image: url\\(&quot;([^&]+)&quot;\\);\"></a>"); m = p.matcher(ligne_contenu); if(m.find()) resultat = m.group(1); else { p = Pattern.compile("class=\"pictures-main-area__picture.+\" style=\"background-image: url\\(&quot;([^&]+)&quot;\\);\"></a>"); m = p.matcher(ligne_contenu); if(m.find()) resultat = m.group(1); } break; default: break; } return resultat; } } /** * reflist + div * Récupérer les informations de la partie "Ma personnalité" * @param ligne_contenu * @param type * @return */ public static String get_personnalite_from_contenu(String ligne_contenu, String type) { if(ligne_contenu==null || type==null) { return null; } else { String resultat = null; String string_compile = "reflist\\."+type+"\">[^<]+</div>(<!---->)+<[^>]+>([^<]+)</div>"; Pattern p = Pattern.compile(string_compile); Matcher m = p.matcher(ligne_contenu); if(m.find()) resultat = m.group(2); return resultat; } } /** * reflist + span * @param ligne_contenu * @param type * @return */ public static String get_mode_from_contenu(String ligne_contenu, String type) { if(ligne_contenu==null || type==null) { return null; } else { String resultat = null; String string_compile = "reflist\\."+type+"\">[^<]+</div>(<!---->)+<[^>]+>([^<]+)</span>"; Pattern p = Pattern.compile(string_compile); Matcher m = p.matcher(ligne_contenu); if(m.find()) resultat = m.group(2); return resultat; } } /** * ctrl + span * @param ligne_contenu * @param type * @return */ public static String get_title_from_contenu(String ligne_contenu, String type) { if(ligne_contenu==null || type==null) { return null; } else { String resultat = null; String string_compile = "ctrl\\."+type+"\">([^<]+)</span>"; Pattern p = Pattern.compile(string_compile); Matcher m = p.matcher(ligne_contenu); if(m.find()) resultat = m.group(1); return resultat; } } /** * ctrl + div * @param ligne_contenu * @param type * @return */ public static String get_physique_from_contenu(String ligne_contenu, String type) { if(ligne_contenu==null || type==null) { return null; } else { String resultat = null; String string_compile = "ctrl\\."+type+"\">([^<]+)</div>"; Pattern p = Pattern.compile(string_compile); Matcher m = p.matcher(ligne_contenu); if(m.find()) resultat = m.group(1); return resultat; } } /** * * @param ligne_contenu * @return */ public static Integer get_number_from_string(String ligne_contenu) { if(ligne_contenu==null) return null; else { Pattern p = Pattern.compile("[0-9]+"); Matcher m = p.matcher(ligne_contenu); if(m.find()) return Integer.valueOf(m.group()); else return null; } } /** * * @param ligne_contenu * @return */ public static Boolean get_boolean_from_string(String ligne_contenu) { if(ligne_contenu==null) return null; else { String tmp_string = ligne_contenu.trim().toLowerCase(); if(tmp_string.equals("yes") || tmp_string.equals("oui") || tmp_string.equals("y") || tmp_string.equals("o")) return true; else return false; } } /** * * @param ligne_contenu * @param type * @return */ public static String get_search_card_span(String ligne_contenu, String type) { if(ligne_contenu==null || type==null) { return null; } else { String resultat = null; String string_compile = "search_card\\."+type+"\">[^<]+</span>( <!---->)+<[^>]+>([^<]+)</span>"; Pattern p = Pattern.compile(string_compile); Matcher m = p.matcher(ligne_contenu); if(m.find()) resultat = m.group(2); return resultat; } } /** * get search age * @param ligne_contenu * @param choix 1-FROM 2-TO * @return */ public static Integer get_search_age(String ligne_contenu, int choix) { if(ligne_contenu==null) return null; else { Pattern p = Pattern.compile("de ([0-9]+) ([a-zA-Z]+ )?à ([0-9]+) "); Matcher m = p.matcher(ligne_contenu); if(m.find()) { if(choix == 1) return Integer.valueOf(m.group(choix)); else return Integer.valueOf(m.group(3)); } else return null; } } public static Integer get_birthday(Integer age) { if(age==null) return null; else { Date tmp_date = TalendDate.getCurrentDate(); String tmp_string = TalendDate.formatDate("yyyy", tmp_date); int tmp_int = Integer.valueOf(tmp_string); return (tmp_int-age); } } public static String get_interest(String ligne_contenu, String type) { if(ligne_contenu==null || type==null) { return null; } else { String resultat = null; String string_compile = "interests\\."+type+"\">[^<]+</h2>(.+)<!----><!----><!----></div></div>"; Pattern p = Pattern.compile(string_compile); Matcher m = p.matcher(ligne_contenu); if(m.find()) { resultat = ""; String resultat_tmp = m.group(1); p = Pattern.compile("value\">([^<]+)</div>"); m = p.matcher(resultat_tmp); while(m.find()) { resultat += m.group(1)+","; } } return resultat; } } }
package me.hotjoyit.user.sqlservice; /** * Created by hotjoyit on 2016-07-30 */ public class SqlNotFoundException extends RuntimeException { SqlNotFoundException(String message) { super(message); } }
package chapter1; public class oneAway { public static boolean solution(String one, String two){ int len1 = one.length(); int len2 = two.length(); int[][] mem = new int[len1 + 1][len2 + 1]; for (int i = 0; i <= len1; i++) { mem[i][0] = i; } for (int j = 0; j <= len2; j++) { mem[0][j] = j; } for (int i = 0; i < len1; i++) { char c1 = one.charAt(i); for (int j = 0; j < len2; j++) { char c2 = two.charAt(j); if (c1 == c2) { mem[i + 1][j + 1] = mem[i][j]; } else { int replace = mem[i][j] + 1; int insert = mem[i][j + 1] + 1; int delete = mem[i + 1][j] + 1; int min = replace > insert ? insert : replace; min = delete > min ? min : delete; mem[i + 1][j + 1] = min; } } } return mem[len1][len2] < 2; } public static void main (String [] args){ System.out.println(solution("pale", "ple")); System.out.println(solution("pale", "bake")); } }
package com.biblio.api.model; import java.net.URI; import java.util.Optional; import org.springframework.beans.factory.annotation.*; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import org.springframework.web.servlet.support.ServletUriComponentsBuilder; import com.biblio.api.core.Emprunt; import com.biblio.api.dao.EmpruntRepository; @RestController public class EmpruntController { @Autowired private EmpruntRepository empruntDao; //Récupérer la liste des Emprunts @RequestMapping(value = "/Emprunts", method = RequestMethod.GET) @ResponseBody public Iterable<Emprunt> listeEmprunts() { return empruntDao.findAll(); } //Récupérer un Emprunt donnée @RequestMapping(value = "/Emprunts/{id}", method = RequestMethod.GET) @ResponseBody public Optional<Emprunt> getEmprunt(@PathVariable long id) { return empruntDao.findById(id); } //Récupérer la liste sous catégorie d'une Categorie donnée @RequestMapping(value = "/Emprunts/Utilisateur/{id}", method = RequestMethod.GET) @ResponseBody public Iterable<Emprunt> listeEmpruntUtilisateurId(@PathVariable long id) { return empruntDao.findByUtilisateur_Id(id); } //Supprimer un emprunt donné @RequestMapping(value = "/emprunts/{id}", method = RequestMethod.DELETE) @ResponseBody public void deleteEmpruntId(@PathVariable long id) { empruntDao.deleteById(id); } @PostMapping(value = "/Emprunts") public ResponseEntity<Void> ajouterEmprunt(@RequestBody Emprunt emprunt) { Emprunt empruntAdded = empruntDao.save(emprunt); if (empruntAdded == null) return ResponseEntity.noContent().build(); URI location = ServletUriComponentsBuilder .fromCurrentRequest() .path("/{id}") .buildAndExpand(empruntAdded.getId()) .toUri(); return ResponseEntity.created(location).build(); } }
/* * Copyright (c) 2013 ICM Uniwersytet Warszawski All rights reserved. * See LICENCE.txt file for licensing information. */ package pl.edu.icm.unity.db.model; /** * In DB attribute representation. It contains also syntax id and name which are stored in the * table with attribute types. * @author K. Benedyczak */ public class AttributeBean { private Long id; private Long typeId; private Long groupId; private Long entityId; private byte[] values; private String name; private String valueSyntaxId; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Long getGroupId() { return groupId; } public void setGroupId(Long groupId) { this.groupId = groupId; } public Long getEntityId() { return entityId; } public void setEntityId(Long entityId) { this.entityId = entityId; } public byte[] getValues() { return values; } public void setValues(byte[] values) { this.values = values; } public Long getTypeId() { return typeId; } public void setTypeId(Long typeId) { this.typeId = typeId; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getValueSyntaxId() { return valueSyntaxId; } public void setValueSyntaxId(String valueSyntaxId) { this.valueSyntaxId = valueSyntaxId; } }
package dwz.persistence.mapper; import java.util.List; import org.apache.ibatis.session.RowBounds; import org.springframework.stereotype.Repository; import dwz.dal.BaseMapper; import sop.persistence.beans.OfferSheet; import sop.persistence.beans.OfferSheetItem; import sop.reports.vo.OffAbCostPriceHead; import sop.vo.ItemMasterConditionVo; import sop.vo.OfferSheetConditionVo; import sop.vo.OfferSheetVo; import sop.vo.TxnVo; /** * @Author: LCF * @Date: 2020/1/8 17:24 * @Package: dwz.persistence.mapper */ @Repository public interface OfferSheetMapper extends BaseMapper<OfferSheet, Integer> { // 查询 List<OfferSheetVo> findPageBreakByCondition(OfferSheetConditionVo vo, RowBounds rb); Integer findNumberByCondition(OfferSheetConditionVo vo); List<TxnVo> getAllTxns(); Integer getCountByOfferSheet(OfferSheet currentOfferSheet); Integer insertOfferSheet(OfferSheet currentOfferSheet); void insertOfferSheetItem(OfferSheetItem offerSheetItem); OfferSheet getOfferSheetByOfferSheetVo(OfferSheetVo offerSheetVo); List<OfferSheetItem> getOfferSheetItemListByOfferSheetVo(OfferSheetVo offerSheetVo); Integer updateOfferSheet(OfferSheet currentOfferSheet); void deleteOfferItem(OfferSheet currentOfferSheet); Integer deleteOfferSheet(OfferSheetVo offerSheetVo); OfferSheet getOfferSheetByOffShNoPfixNo(String offShNoPfixNo); List<OfferSheetItem> getOfferSheetItemListByOffShNoPfixNo(String offShNoPfixNo); void deleteOfferItemByOffShNoPfixNo(String offShNoPfixNo); Integer deleteOfferSheetByOffShNoPfixNo(String offShNoPfixNo); OffAbCostPriceHead getAbCostPriceReport(OfferSheetConditionVo vo); List<Object> getOffAbCostPrice(OfferSheetConditionVo vo); List<Object> getOffListItem(ItemMasterConditionVo vo); List<Object> getCostPriceList(OfferSheetConditionVo vo); List<Object> getABPriceList(OfferSheetConditionVo vo); List<Object> getSimplifiedOff(OfferSheetConditionVo vo); }
package gate; import com.google.protobuf.Message; import gate.handler.GateAuthConnectionHandler; import gate.handler.GateLogicConnectionHandler; import gate.utils.ClientConnection; import gate.utils.ClientConnectionMap; import io.netty.buffer.ByteBuf; import protobuf.Utils; import protobuf.analysis.ParseMap; import protobuf.generate.device.Auth; import protobuf.generate.device.Device; import protobuf.generate.internal.Internal; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; /** * @Author:lzq * @Discription * @Date: Created on 2017/5/11. * @Modified By: */ public class TransferHandlerMap { private static final Logger logger = LoggerFactory.getLogger(ClientMessage.class); public static void initRegistry() throws IOException { //传递消息到Auth Transfer t2Auth = (Message msg, ClientConnection conn) -> { ByteBuf byteBuf = null; if (msg instanceof Auth.CLogin) { String userId = ((Auth.CLogin) msg).getUserid(); byteBuf = Utils.pack2Server(msg, ParseMap.getPtoNum(msg), conn.getNetId(), Internal.Dest.Auth, userId); ClientConnectionMap.registerUserid(userId, conn.getNetId()); } else if (msg instanceof Auth.CRegister) { byteBuf = Utils.pack2Server(msg, ParseMap.getPtoNum(msg), conn.getNetId(), Internal.Dest.Auth, ((Auth.CRegister) msg).getUserid()); } GateAuthConnectionHandler.getGateAuthConnection().writeAndFlush(byteBuf); }; //传递消息到Logic Transfer t2Logic = (Message msg, ClientConnection conn) -> { ByteBuf byteBuf = null; if (conn.getUserId() == null) { logger.error("User not login."); return; } if (msg instanceof Device.DeviceMessage) { byteBuf = Utils.pack2Server(msg, ParseMap.getPtoNum(msg), conn.getNetId(), Internal.Dest.Logic, conn.getUserId()); } GateLogicConnectionHandler.getGatelogicConnection().writeAndFlush(byteBuf); }; ClientMessage.registerTranferHandler(1000, t2Auth, Auth.CLogin.class); ClientMessage.registerTranferHandler(1001, t2Auth, Auth.CRegister.class); ClientMessage.registerTranferHandler(1003, t2Logic, Device.DeviceMessage.class); // ClientMessage.registerTranferHandler(1000, ClientMessage::transfer2Auth, Auth.CLogin.class); // ClientMessage.registerTranferHandler(1001, ClientMessage::transfer2Auth, Auth.CRegister.class); // ClientMessage.registerTranferHandler(1003, ClientMessage::transfer2Logic, Chat.CPrivateChat.class); } }
/** * Diese Datei gehört zum Android/Java Framework zur Veranstaltung "Computergrafik für * Augmented Reality" von Prof. Dr. Philipp Jenke an der Hochschule für Angewandte * Wissenschaften (HAW) Hamburg. Weder Teile der Software noch das Framework als Ganzes dürfen * ohne die Einwilligung von Philipp Jenke außerhalb von Forschungs- und Lehrprojekten an der HAW * Hamburg verwendet werden. * <p> * This file is part of the Android/Java framework for the course "Computer graphics for augmented * reality" by Prof. Dr. Philipp Jenke at the University of Applied (UAS) Sciences Hamburg. Neither * parts of the framework nor the complete framework may be used outside of research or student * projects at the UAS Hamburg. */ package edu.hawhamburg.shared.misc; import java.util.ArrayList; import java.util.List; import android.util.Log; import edu.hawhamburg.shared.datastructures.mesh.ITriangleMesh; import edu.hawhamburg.shared.datastructures.mesh.ObjReader; import edu.hawhamburg.shared.datastructures.mesh.TriangleMesh; import edu.hawhamburg.shared.datastructures.mesh.TriangleMeshTools; import edu.hawhamburg.shared.datastructures.mesh.halfedge.HalfEdgeTriangleMeshFactory; import edu.hawhamburg.shared.datastructures.spline.HermiteSpline; import edu.hawhamburg.shared.math.Matrix; import edu.hawhamburg.shared.math.Vector; import edu.hawhamburg.shared.scenegraph.*; import platform.vuforia.VuforiaMarkerNode; import static edu.hawhamburg.shared.scenegraph.TriangleMeshNode.RenderNormals.PER_VERTEX_NORMAL; /** * Dummy scene with rather simple content. * * @author Philipp Jenke */ public class SplineDefaultScene extends Scene { private static final double TICK_MOVE = 1. / 200; private TransformationNode transformationNode; private HermiteSpline hermiteSpline; private double t; public SplineDefaultScene() { super(100, INode.RenderMode.REGULAR); } @Override public void onSetup(InnerNode rootNode) { try { // marker VuforiaMarkerNode markerNode = new VuforiaMarkerNode("elphi"); rootNode.addChild(markerNode); // Cow ScaleNode cowNode = new ScaleNode(1); ObjReader reader = new ObjReader(); List<ITriangleMesh> triangleMeshes = reader.read("meshes/cow.obj"); // transform to half triangle meshes List<ITriangleMesh> meshes = new ArrayList<>(triangleMeshes.size()); for (ITriangleMesh mesh : triangleMeshes) { if (mesh instanceof TriangleMesh) { meshes.add(HalfEdgeTriangleMeshFactory.create((TriangleMesh) mesh)); } else { throw new RuntimeException("Mesh not instance of " + TriangleMesh.class.getCanonicalName()); } } TriangleMeshTools.fitToUnitBox(meshes); TriangleMeshTools.placeOnXZPlane(meshes); for (ITriangleMesh mesh : meshes) { TriangleMeshNode TMN = new TriangleMeshNode(mesh); TMN.setRenderNormals(PER_VERTEX_NORMAL); cowNode.addChild(TMN); } // create spline hermiteSpline = new HermiteSpline( new Vector(-.25, 0, -.25), new Vector(0, .5, -.25), new Vector(0, .5, .25), new Vector(.25, .25, .25) ); // draw spline double step = 1. / 100; for (double t = 0; t < 1; t += step) { markerNode.addChild(new LineStripNode( hermiteSpline.evaluateCurve(t), hermiteSpline.evaluateCurve(t + step) )); } // add cow transformationNode = new TransformationNode(); markerNode.addChild(transformationNode); transformationNode.addChild(cowNode); // initially set t t = 0; } catch (Throwable t) { Log.e("DEBUG", "" + t.getMessage(), t); } } @Override public void onTimerTick(int counter) { // update t if (t >= 1) { t = 0; } t += TICK_MOVE; // update matrix transformationNode.setTransformation(getTransformationMatrix(t)); } @Override public void onSceneRedraw() { // Redraw event } private Matrix getTransformationMatrix(double t) { Vector x = hermiteSpline.evaluateTangent(t).getNormalized(); Vector z = x.cross(new Vector(0, 1, 0)).getNormalized(); Vector y = z.cross(x).getNormalized(); Vector p = hermiteSpline.evaluateCurve(t); return Matrix.createTransformationMatrix( Vector.addDimension(x, 0), Vector.addDimension(y, 0), Vector.addDimension(z, 0), Vector.addDimension(p, 1) ); } }
/** * Description: The order class is responsible for processing * an order and sending the user its information * @author Killian O'Dálaigh * @version 10 October 2018 */ import java.util.UUID; import java.util.ArrayList; public class Order { private Customer customer; private ShoppingCart shoppingCart; private ArrayList<Item> orderItems; private String orderNumber; private Payment payment; private Email email; private double total; private Address deliveryAddress; private Address billingAddress; private boolean status; // True == Confirmed // False == Not Confirmed /* * Class Constructor */ public Order(Customer customer, ShoppingCart shoppingCart) { this.customer = customer; this.shoppingCart = shoppingCart; this.orderItems = new ArrayList<Item>(shoppingCart.getItems()); this.orderNumber = makeOrderNumber(); this.payment = null; this.email = null; this.status = false; this.total = getTotalItems(); this.setDeliveryAddress(customer.getDeliveryAddress()); }// End constructor /* * Methods */ // Processes the Order public void processOrder() { // If there is no Delivery address prompt error message if (!(this.deliveryAddress.isEmpty())) { System.out.println("Error - You have no delivery address"); } // If there is no Billing Address set it equal to the Delivery Address if (this.billingAddress == null) { this.billingAddress = this.deliveryAddress; } // Removes all the items in the shopping cart items array (Cleans the Cart) this.shoppingCart.getItems().clear(); // Close the cart for editing this.shoppingCart.closeCart(); } // Confirms the Order and send out an email with the order details public void confirmOrder(boolean payment) { this.email = new Email(this.customer, this, payment); // Sends Email this.email.sendEmail(email.generateEmail(payment)); this.status = true; } // Updates the users order public void update(Customer customer, ShoppingCart shoppingCart) { this.customer = customer; this.shoppingCart = shoppingCart; this.orderItems = shoppingCart.getItems(); this.orderNumber = makeOrderNumber(); this.payment = null; this.email = null; this.status = false; } // Makes a Unique Order number private String makeOrderNumber() { return (UUID.randomUUID().toString()); } // Lists all the items ordered public String listOrderItems() { String string1 = ""; for (int i=0; i<this.orderItems.size(); i++) { string1 += ("\n" + this.orderItems.get(i).toString()); } return string1; } /* * Getters and Setters */ public Customer getCustomer() { return customer; } public void setCustomer(Customer customer) { this.customer = customer; } public ArrayList<Item> getOrderItems() { return orderItems; } public void setOrderItems(ArrayList<Item> orderItems) { this.orderItems = orderItems; } public String getOrderNumber() { return orderNumber; } public void setOrderNumber(String orderNumber) { this.orderNumber = orderNumber; } public Payment getPayment() { return payment; } public void setPayment(Payment payment) { this.payment = payment; } public Email getEmail() { return email; } public void setEmail(Email email) { this.email = email; } public Address getDeliveryAddress() { return deliveryAddress; } public void setDeliveryAddress(Address deliveryAddress) { this.deliveryAddress = deliveryAddress; } private double getTotalItems() { double total = 0; for(int i=0; i<this.orderItems.size(); i++) { total += this.orderItems.get(i).getPrice(); } return total; } public ShoppingCart getShoppingCart() { return shoppingCart; } public void setShoppingCart(ShoppingCart shoppingCart) { this.shoppingCart = shoppingCart; } public double getTotal() { return total; } public void setTotal(double total) { this.total = total; } public boolean isStatus() { return status; } public void setStatus(boolean status) { this.status = status; } public Address getBillingAddress() { return billingAddress; } public void setBillingAddress(Address billingAddress) { this.billingAddress = billingAddress; } }// End Class Order
package structural.bridge; /** * @author Renat Kaitmazov */ public final class SmallShapesDrawer implements Drawer { @Override public final String draw(String shapeName) { return String.format("Drawing small %s", shapeName); } }
import ControladorConversor.ConversorControlador; import ModeloConversor.ConversorMonedas; import VistaConversor.Ventana; /* * 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. */ /** * * @author Jose Angel Garcia Garcia */ public class PyMVControlador { public static void main(String[] args) { // Propiedades ConversorMonedas modelo = new ConversorMonedas(); Ventana vista = new Ventana(); ConversorControlador controlador = new ConversorControlador(vista,modelo); // Metodos vista.conectarControaldor(controlador); vista.arrancar(); } }
package sn.simplon.entities; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.JoinTable; import javax.persistence.ManyToMany; @Entity public class User implements Serializable { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) private int id; @Column private String nom; @Column private String prenom; @Column private String password; @Column private String email; @Column private int etat; @ManyToMany(fetch=FetchType.LAZY , cascade=CascadeType.ALL) @JoinTable(name="user_roles" , joinColumns = {@JoinColumn(name="idU",nullable=false,updatable =false)}, inverseJoinColumns = {@JoinColumn(name="idR",nullable= false , updatable =false)}) private List<Roles> roles = new ArrayList<Roles>(); public User() { super(); } public User(int id, String nom, String prenom, String password, String email, int etat, List<Roles> roles) { super(); this.id = id; this.nom = nom; this.prenom = prenom; this.password = password; this.email = email; this.etat = etat; this.roles = roles; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getNom() { return nom; } public void setNom(String nom) { this.nom = nom; } public String getPrenom() { return prenom; } public void setPrenom(String prenom) { this.prenom = prenom; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public int getEtat() { return etat; } public void setEtat(int etat) { this.etat = etat; } public List<Roles> getRoles() { return roles; } public void setRoles(List<Roles> roles) { this.roles = roles; } }
package mx.com.otss.barbershopapp.activities.servicios; import android.content.Intent; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.design.widget.BottomNavigationView; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.DefaultItemAnimator; import android.support.v7.widget.DividerItemDecoration; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.Toast; import com.android.volley.RequestQueue; import com.android.volley.Response; import com.android.volley.toolbox.Volley; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import mx.com.otss.barbershopapp.R; import mx.com.otss.barbershopapp.activities.comisiones.MenuComisionesActivity; import mx.com.otss.barbershopapp.activities.menu_inferior.ListadosActivity; import mx.com.otss.barbershopapp.activities.menu_inferior.PrincipalEmpleadosActivity; import mx.com.otss.barbershopapp.activities.menu_inferior.PrincipalFranquiciasActivity; import mx.com.otss.barbershopapp.activities.menu_inferior.PrincipalServiciosActivity; import mx.com.otss.barbershopapp.activities.menu_inferior.ReportesActivity; import mx.com.otss.barbershopapp.adapters.servicios.ConsultaServiciosAdapter; import mx.com.otss.barbershopapp.request.servicios.ConsultaIdServiceRequest; import mx.com.otss.barbershopapp.utils.BarberShop; import mx.com.otss.barbershopapp.utils.Comunicador; import mx.com.otss.barbershopapp.utils.RecyclerTouchListener; import static mx.com.otss.barbershopapp.utils.Red.verificaConexion; public class ConsultarServiciosActivity extends AppCompatActivity { private ArrayList<BarberShop> listA ; private RecyclerView recyclerView; private ConsultaServiciosAdapter mAdapter; private ArrayList<String> lista; private BarberShop al; private Button btnObtenerReporte; private View v; private ArrayList<String> listas; private Menu menu; private MenuItem menuItem; private BottomNavigationView navigation; private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener = new BottomNavigationView.OnNavigationItemSelectedListener() { /** * * @param item * @return */ @Override public boolean onNavigationItemSelected(@NonNull MenuItem item) { switch (item.getItemId()) { case R.id.menu_inferior_empleados: Intent intentPrincipalEmpleados=new Intent(getApplication(),PrincipalEmpleadosActivity.class); finish(); startActivity(intentPrincipalEmpleados); return true; case R.id.menu_inferior_servicios: Intent intentPrincipalServicios=new Intent(getApplication(),PrincipalServiciosActivity.class); finish(); startActivity(intentPrincipalServicios); return true; case R.id.menu_inferior_franquicias: Intent intentPrincipalFranquicias = new Intent(getApplicationContext(), PrincipalFranquiciasActivity.class); finish(); startActivity(intentPrincipalFranquicias); return true; case R.id.menu_inferior_listados: Intent intentPrincipalClientes = new Intent(getApplicationContext(), ListadosActivity.class); finish(); startActivity(intentPrincipalClientes); return true; case R.id.menu_inferior_reportes: Intent intentReportes = new Intent(getApplicationContext(), ReportesActivity.class); finish(); startActivity(intentReportes); return true; } return false; } }; /** * * @param savedInstanceState */ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_consultar_servicios); Intent intent_receptor = getIntent(); navigation = (BottomNavigationView) findViewById(R.id.navigation); navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener); menu = navigation.getMenu(); menuItem = menu.getItem(1); menuItem.setChecked(true); recyclerView = (RecyclerView) findViewById(R.id.recycler_view_consulta_servicios); listA = new ArrayList<>(); lista = getIntent().getStringArrayListExtra("dat"); ArrayList<BarberShop> objpersonas = new ArrayList<BarberShop>(); for (int i = 0; i< Comunicador.getOBJ().size(); i++){ BarberShop obj=(BarberShop) Comunicador.getOBJ().get(i); objpersonas.add(obj); } for(BarberShop i: Comunicador.getOBJ()){ al = new BarberShop(); al.setIdServicios(i.getIdServicios()); al.setNombreServicio(i.getNombreServicio()); al.setPrecio(i.getPrecio()); al.setImagen(i.getImagen()); al.setTiempoRequerido(i.getTiempoRequerido()); al.setIdFranquisia(i.getIdFranquisia()); listA.add(al); } Log.i("info", "mensaje"+ objpersonas.toString()); mAdapter = new ConsultaServiciosAdapter(listA); recyclerView.setHasFixedSize(true); RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext()); recyclerView.setLayoutManager(mLayoutManager); recyclerView.addItemDecoration(new DividerItemDecoration(this, LinearLayoutManager.VERTICAL)); recyclerView.setItemAnimator(new DefaultItemAnimator()); recyclerView.setAdapter(mAdapter); // row click listener recyclerView.addOnItemTouchListener(new RecyclerTouchListener(getApplicationContext(), recyclerView, new RecyclerTouchListener.ClickListener() { @Override public void onClick(View view, int position) { BarberShop movie = listA.get(position); Comunicador.limpiar(); Toast.makeText(getApplicationContext(), movie.getIdServicios() + " is selected!", Toast.LENGTH_SHORT).show(); if (!verificaConexion(getApplication())) { Toast.makeText(getBaseContext(), "Comprueba tu conexión a Internet.... ", Toast.LENGTH_SHORT) .show(); } else { final ArrayList<BarberShop> arrayList = new ArrayList<BarberShop>(); String idServicio = movie.getIdServicios(); final BarberShop obj = new BarberShop(); Response.Listener<String> responseListener = new Response.Listener<String>() { /** * * @param response */ @Override public void onResponse(String response) { try { JSONArray jsonResponse = new JSONArray(response); Log.i("Info", "" + jsonResponse.length()); ArrayList<String> list = new ArrayList<String>(); String[] q = new String[jsonResponse.length()]; for (int x = 0; x < q.length; x++) { String v = q[x] = jsonResponse.optString(x); Log.i("info", "Mi lista" + v); } for (String s : q) { JSONObject jsonObject = new JSONObject(s); for (int z = 0; z < jsonObject.length(); z++) { JSONArray array = jsonObject.getJSONArray("servicios"); String cadena = null; Comunicador obj = new Comunicador(); BarberShop o = new BarberShop(); for (int i = 0; i < array.length(); i++) { o.setIdServicios(array.getJSONObject(i).getString("idServicio")); o.setNombreServicio(array.getJSONObject(i).getString("nombreServicio")); o.setPrecio(array.getJSONObject(i).getString("precio")); o.setImagen(array.getJSONObject(i).getString("imagen")); o.setTiempoRequerido(array.getJSONObject(i).getString("tiempoRequerido")); o.setIdFranquisia(array.getJSONObject(i).getString("idFranquisia")); obj.setOBJ(o); } } } Intent intentConsultar = new Intent(getApplicationContext(), ActualizarServiciosActivity.class); finish(); startActivity(intentConsultar); } catch (JSONException e) { Log.e("Error", "Error" + e.getMessage()); e.printStackTrace(); Toast.makeText(getApplicationContext(), "No hay registros", Toast.LENGTH_SHORT).show(); } catch (Exception e){ if(e!=null && e.getMessage() !=null){ Toast.makeText(getApplicationContext(),"error VOLLEY "+e.getMessage(),Toast.LENGTH_LONG).show(); } else{ Toast.makeText(getApplicationContext(),"Something went wrong",Toast.LENGTH_LONG).show(); } } } }; ConsultaIdServiceRequest consultaIdServicioRequest = new ConsultaIdServiceRequest(idServicio, responseListener); RequestQueue queue = Volley.newRequestQueue(getApplicationContext()); queue.add(consultaIdServicioRequest); } } /** * * @param view * @param position */ @Override public void onLongClick(View view, int position) { } })); } /** * * @param menu * @return */ //menu @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_superior, menu); return true; } /** * * @param item * @return */ @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); if(id == R.id.menu_superior_otros){ Intent intentMenuComisiones = new Intent(getApplicationContext(), MenuComisionesActivity.class); startActivity(intentMenuComisiones); } if (id == R.id.menu_superior_salir) { finish(); } return super.onOptionsItemSelected(item); } }
package Problem_1891; import java.util.Scanner; public class Main { static int d; static String No; static long x, y; static class Data { long x, y; public Data(long x, long y) { this.x = x; this.y = y; } } public static void main(String[] args) { Scanner sc = new Scanner(System.in); d = sc.nextInt(); No = sc.next(); x = sc.nextLong(); y = sc.nextLong(); char[] Nums = String.valueOf(No).toCharArray(); long size = 1L << d; Data data = func(Nums, 0, 0, 0, size); data.x -= y; data.y += x; if(0 <= data.x && size > data.x && 0 <= data.y && size > data.y) { String str = dfunc(0, 0, size, data.x, data.y); System.out.println(str); } else { System.out.println("-1"); } } public static Data func(char[] num, int idx, long x, long y, long size) { if(size == 1) return new Data(x, y); else { switch(num[idx]) { case '1': return func(num, idx+1, x, y+size/2, size/2); case '2': return func(num, idx+1, x, y, size/2); case '3': return func(num, idx+1, x+size/2, y, size/2); case '4': return func(num, idx+1, x+size/2, y+size/2, size/2); } } return new Data(0l, 0l); } public static String dfunc(long r, long c, long size, long x, long y) { if(size == 1) return ""; // 끝 if(x < r+size/2 && y < c+size/2) // 2사분면 return "2" + dfunc(r, c, size/2, x, y); else if(x < r+size/2 && y >= c+size/2) // 1사분면 return "1" + dfunc(r, c+size/2, size/2, x, y); else if(x >= r+size/2 && y < c + size/2) // 3사분면 return "3" + dfunc(r+size/2, c, size/2, x,y); else // 4사분면 return "4" +dfunc(r+size/2, c+size/2, size/2, x,y); } }
package nxpense.controller; import nxpense.service.api.UserService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import javax.servlet.http.HttpServletRequest; @Controller @RequestMapping("/account") public class AccountController { private static final Logger LOGGER = LoggerFactory.getLogger(AccountController.class); @Autowired private UserService userService; @RequestMapping(value = "/new", method = RequestMethod.POST) @ResponseBody public String createNewAccount(HttpServletRequest request, @RequestParam String email, @RequestParam char[] password, @RequestParam char[] passwordRepeat) { userService.createUser(email, password, passwordRepeat); StringBuilder redirection = new StringBuilder() .append(request.getContextPath()) .append("/view/home.html"); LOGGER.info("User [{}] has been created and is automatically logged in", email); return redirection.toString(); } }
package com.asciiwarehouse.configuraton; import lombok.extern.log4j.Log4j2; import org.springframework.cache.CacheManager; import org.springframework.cache.annotation.CachingConfigurerSupport; import org.springframework.cache.annotation.EnableCaching; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.cache.RedisCacheManager; import org.springframework.data.redis.connection.RedisConnectionFactory; import org.springframework.data.redis.connection.jedis.JedisConnectionFactory; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.web.servlet.config.annotation.EnableWebMvc; @Configuration @EnableCaching @ComponentScan(basePackages = "com.asciiwarehouse") @EnableWebMvc @Log4j2 public class CacheConfigurator extends CachingConfigurerSupport{ private static final String REDIS_HOST = "127.0.0.1"; private static final int REDIS_PORT = 6379; private static final int DEFAULT_CACHE_EXPIRATION_TIME = 300; @Bean public JedisConnectionFactory redisConnectionFactory() { JedisConnectionFactory redisConnectionFactory = new JedisConnectionFactory(); // Defaults redisConnectionFactory.setHostName(REDIS_HOST); redisConnectionFactory.setPort(REDIS_PORT); return redisConnectionFactory; } @Bean public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory cf) { RedisTemplate<String, String> redisTemplate = new RedisTemplate<>(); redisTemplate.setConnectionFactory(cf); return redisTemplate; } @Bean public CacheManager cacheManager(RedisTemplate redisTemplate) { RedisCacheManager cacheManager = new RedisCacheManager(redisTemplate); // Number of seconds before expiration. Defaults to unlimited (0) cacheManager.setDefaultExpiration(DEFAULT_CACHE_EXPIRATION_TIME); return cacheManager; } }
package kr.co.magiclms.shop.controller; import java.io.IOException; import java.util.List; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import kr.co.magiclms.common.db.MyAppSqlConfig; import kr.co.magiclms.domain.Cart; import kr.co.magiclms.domain.CartItem; import kr.co.magiclms.domain.Login; import kr.co.magiclms.domain.Order; import kr.co.magiclms.domain.OrderItem; import kr.co.magiclms.mapper.CartItemMapper; import kr.co.magiclms.mapper.CartMapper; import kr.co.magiclms.mapper.GoodsMapper; import kr.co.magiclms.mapper.OrderItemMapper; import kr.co.magiclms.mapper.OrderMapper; @WebServlet("/shop/orderlist") public class OrderListController extends HttpServlet { @Override public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{ request.setCharacterEncoding("utf-8"); CartMapper mapper = MyAppSqlConfig.getSqlSession().getMapper(CartMapper.class); CartItemMapper cmapper = MyAppSqlConfig.getSqlSession().getMapper(CartItemMapper.class); GoodsMapper gmapper = MyAppSqlConfig.getSqlSession().getMapper(GoodsMapper.class); OrderMapper omapper = MyAppSqlConfig.getSqlSession().getMapper(OrderMapper.class); OrderItemMapper oimapper = MyAppSqlConfig.getSqlSession().getMapper(OrderItemMapper.class); HttpSession session = request.getSession(); Login login = (Login)session.getAttribute("user"); String memberId = login.getMemberID(); // dell dell request.setAttribute("memberId", memberId); System.out.println("[OrderListController]** memberID = "+ memberId); int orderId = 1; //dell // to get orderId, You can use also MemberId orderId = Integer.parseInt(request.getParameter("orderId")); System.out.println("[OrderListController]** orderId = "+orderId); Order order = omapper.selectOrderByNo(orderId); memberId = order.getMemberId(); request.setAttribute("memberId", memberId); System.out.println("[OrderListController]** memberId= "+ memberId); if(order == null){ System.out.println("**order is null ** ?????"); response.sendRedirect("cartlist"); } // to get orderId request.setAttribute("orderId", order.getOrderId()); int totalPrice = 0, dicountPrice = 0, lastPrice = 0; int totalShippingCost = 0; // to get content of Order Table, OrderItemTable List<OrderItem> orderItemList = oimapper.selectOrderItemByNo(orderId); request.setAttribute("orderItemList", orderItemList); System.out.println("*order*** orderItemList= "+orderItemList+ ", *** orderItemList size= " + orderItemList.size()); RequestDispatcher rd = request.getRequestDispatcher("/jsp/shop/orderlist.jsp"); rd.forward(request, response); // response.sendRedirect("orderlist?'orderId'=orderId&'memberId'=memberId"); System.out.println("** End of OrderListController, After order "); // response.sendRedirect("list"); } }
package delfi.com.vn.newsample.model; /** * Created by PC on 8/3/2017. */ public class CUsers { }
package domain; import domain.Role; import repository.RoleRepository; public class Waiters extends Employee implements RoleRepository { public String getJobDescription() { return "Serve designated tables, ensure customers are well taken care of"; } }
package com.param.unboundservicedemo; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; public class MainActivity extends AppCompatActivity implements View.OnClickListener { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button btnPlay = (Button) findViewById(R.id.btnPlay); Button btnStop = (Button) findViewById(R.id.btnStop); btnPlay.setOnClickListener(this); btnStop.setOnClickListener(this); } @Override public void onClick(View view) { Intent myIntent; switch (view.getId()) { case R.id.btnPlay: myIntent = new Intent(MainActivity.this, MyService.class); startService(myIntent); break; case R.id.btnStop: myIntent = new Intent(MainActivity.this, MyService.class); stopService(myIntent); break; } } }
package com.example.administrator.myapplication; import android.os.Handler; import android.os.Message; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.TextView; public class MainActivity1 extends AppCompatActivity { private TextView tv_textview; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_mains); Log.i("onCreate()","onCreate()"); tv_textview = (TextView) findViewById(R.id.tv_textview); tv_textview.setText("未更新"); final Handler handler = new Handler(){ @Override public void handleMessage(Message msg) { super.handleMessage(msg); if(msg.what==1){ tv_textview.setText("已更新"); } } }; tv_textview.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { new Thread(new Runnable() { @Override public void run() { Message message = Message.obtain(); message.what=1; handler.sendMessage(message); } }).start(); } }); } @Override protected void onStart() { super.onStart(); Log.i("onStart()","onStart()"); } @Override protected void onRestart() { super.onRestart(); Log.i("onRestart()","onRestart()"); } @Override protected void onResume() { super.onResume(); Log.i("onResume()","onResume()"); } @Override protected void onPause() { super.onPause(); Log.i("onPause()","onPause()"); } @Override protected void onStop() { super.onStop(); Log.i("onStop()","onStop()"); } @Override protected void onDestroy() { super.onDestroy(); Log.i("onDestroy()","onDestroy()"); } }
package team21.pylonconstructor; import android.util.Log; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.LinkedList; import java.util.Objects; import java.util.concurrent.ExecutionException; /** * Created by joshuarobertson on 2017-03-17. */ public class Controller { //https://gist.github.com/Akayh/5566992 //This is what I found for making singletons //March 17th 2017 Joshua did this. private static Controller mInstance = null; private ElasticSearch elasticSearch; private ArrayList<Mood> moodList; private ArrayList<Mood> moodFeed; private LinkedList<Command> commands; private boolean internetStatus = false; String filterTerm; int filterOption; private Profile profile; Date filterDate; public void setProfile(Profile profile) { Log.d("setProfile: Input =", profile.getUserName()); this.profile = profile; Log.d("SetProfile: Output =", this.profile.getUserName()); } public Profile getProfile() { Log.d("Controller: Username:", this.profile.getUserName()); return this.profile; } private Controller() { profile = new Profile(); profile.setUserName(""); elasticSearch = new ElasticSearch(); elasticSearch = new ElasticSearch(); moodList = new ArrayList<>(); moodFeed = new ArrayList<>(); commands = new LinkedList<>(); filterTerm = null; filterOption = 0; filterDate = null; } public static Controller getInstance(){ if(mInstance == null) { mInstance = new Controller(); } return mInstance; } void update() { Command c; for (int i = 0; i < commands.size(); i++) { c = commands.getFirst(); if (!c.execute()) { commands.addLast(c); } commands.removeFirst(); Log.i("CommUpp", "Executing..."); } } Boolean addMood(Mood mood) { Command c = new NewMoodCommand(mood); smartInsert(mood); if (c.execute()) { this.update(); Log.i("AddMood: ", "Added mood!"); return true; } else if (!this.commands.contains(c)) { this.commands.addLast(c); //Manually sort. or smart insert. Log.i("AddMood: ", "Saved mood!"); } return false; } Boolean editMood(Mood mood) { Command c = new EditMoodCommand(mood); this.moodList.remove(mood); smartInsert(mood); if (c.execute()) { this.update(); Log.i("EditMood: ", "Edited mood!"); return true; } else if (!this.commands.contains(c)) { this.commands.addLast(c); //If equals() override works, this should update. } return false; } Boolean deleteMood(Mood mood) { Command c = new DeleteMoodCommand(mood); this.moodList.remove(mood); //TODO: Local Sort if (c.execute()) { this.update(); Log.i("DeleteMood: ", "Deleted mood!"); return true; } else if (!this.commands.contains(c)) { this.commands.addLast(c); } return false; } ArrayList<Mood> getAllMoods() { this.update(); try { ArrayList<Mood> received = new ArrayList<>(); if (filterOption == 0) { received = this.elasticSearch.getmymoods(this.profile); } if (filterOption == 1) { received = this.elasticSearch.emotionalstatefilteredmoods(this.profile, filterTerm); } if (filterOption == 2) { received = this.elasticSearch.triggerfilteredmoods(this.profile, filterTerm); } if (filterOption == 3) { received = this.elasticSearch.getrecentweekmoods(this.profile); } if (received != null) { //Got a mood list this.moodList = received; } else { Log.i("Get MoodList", "Error getting."); } //TODO: Handle exceptions. } catch (Exception e) { Log.i("Get MoodList", "Error connecting."); e.printStackTrace(); } Log.i("MoodList", "Returning MoodList"); return this.moodList; } ArrayList<Mood> getAllMoodsFeed() { update(); try { ArrayList<Mood> received = new ArrayList<>(); if (filterOption == 0) { received = this.elasticSearch.getfollowingmoods(this.profile); } if (filterOption == 1) { received = this.elasticSearch.emotionalstatefilteredmoodsfeed(this.profile, filterTerm); } if (filterOption == 2) { received = this.elasticSearch.triggerfilteredmoodsfeed(this.profile, filterTerm); } if (filterOption == 3) { received = this.elasticSearch.getrecentweekmoodsfeed(this.profile); } if (received != null) { //Got a mood list this.moodFeed = received; } else { Log.i("Get MoodList", "Error getting."); } //TODO: Handle exceptions. } catch (Exception e) { Log.i("Get MoodList", "Error connecting."); e.printStackTrace(); } Log.i("MoodList", "Returning MoodList"); return this.moodFeed; } void addFilters(String filterTerm, int filterOption) { this.filterTerm = filterTerm; this.filterOption = filterOption; } void addDateFilter(Date filterDate, int filterOption) { this.filterDate = filterDate; this.filterOption = filterOption; } int getFilterOption() { return this.filterOption; } String getFilterTerm() { return this.filterTerm; } Date getFilterDate() { return this.getFilterDate(); } public void reset() { } void smartInsert(Mood mood) { int i; for (i = 0; i < this.moodList.size(); i++) { // if the element you are looking at is smaller than x, // go to the next element if (this.moodList.get(i).getDate().after(mood.getDate())) { continue; } else { break; } } this.moodList.add(i, mood); Log.i("Controller", "Added mood at: " + i ); return; } }
package test; interface Transport { public void inform( byte[] data ); } class TextTransport implements Transport { @Override public void inform(byte[] data) { System.out.println("Informing bank using "+this.getClass().getName()); } } class HttpTransport implements Transport { @Override public void inform(byte[] data) { System.out.println("Informing bank using "+this.getClass().getName()); } } class SoapTransport implements Transport { @Override public void inform(byte[] data) { System.out.println("Informing bank using "+this.getClass().getName()); } } interface Atm { void withdraw( float amount ); void deposit( float amount ); } class AtmImplementation implements Atm { private Transport transport; public AtmImplementation( Transport transport ) { this.transport = transport; System.out.println("Inside Constructor "+this.getClass().getName()); } public void setTransport(Transport transport) { this.transport = transport; } @Override public void withdraw(float amount) { StringBuilder sb = new StringBuilder("Depositing "+amount); transport.inform(sb.toString().getBytes()); } @Override public void deposit(float amount) { StringBuilder sb = new StringBuilder("Depositing "+amount); transport.inform(sb.toString().getBytes()); } } public class Program { /*public static void main(String[] args) { AtmImplementation atm = new AtmImplementation(); //Transport transport = new HttpTransport(); //Transport transport = new SoapTransport(); Transport transport = new TextTransport(); atm.setTransport(transport); atm.deposit(5000); }*/ public static void main(String[] args) { Transport transport = null; //transport = new TextTransport(); //transport = new HttpTransport(); transport = new SoapTransport(); AtmImplementation atm = new AtmImplementation( transport ); atm.deposit(5000); } }
package com.qfc.yft.entity.offline; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; public class OfflineData extends JsonOffline { JSONArray seriesArray; JSONArray productArray; OffShopInfo shopInfo; OffDownloadStatus downloadStatus; public OfflineData(){ this(0); } public OfflineData(int shopId){ seriesArray= new JSONArray(); productArray= new JSONArray(); shopInfo = new OffShopInfo(shopId); downloadStatus = new OffDownloadStatus(); } public OfflineData(JSONObject job){ super(job); } @Override public JSONObject toJsonObj() { JSONObject job = new JSONObject(); try { job.put(OFF_SERIESARRAY, seriesArray); job.put(OFF_PRODUCTARRAY, productArray); job.put(OFF_SHOPINFO, shopInfo.toJsonObj()); job.put(OFF_DOWNLOADSTATUS, downloadStatus.toJsonObj()); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } return job; } @Override public void initJackJson(JSONObject job) { seriesArray=job.optJSONArray(OFF_SERIESARRAY ); productArray=job.optJSONArray(OFF_PRODUCTARRAY ); try { shopInfo=new OffShopInfo(job.getJSONObject(OFF_SHOPINFO )); downloadStatus=new OffDownloadStatus(job.getJSONObject(OFF_DOWNLOADSTATUS )); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public int getSize(){ int size=0; size+=getArraySize(seriesArray); size+=getArraySize2(productArray); size+=shopInfo.getSize(); return size; } private int getArraySize2(JSONArray array) { if(array==null) return 0; int size=0; for(int i=0;i<array.length();i++){ try { JSONObject job =array.getJSONObject(i); if(countMe(job.optInt(OFF_STATUS, 0))){ if(job.has(OFF_PRODUCTIMAGE)){ if( countMe(job)) size++; } if(job.has(OFF_PRODUCTPICSARRAY)){ size+= getArraySize(job.getJSONArray(OFF_PRODUCTPICSARRAY)); } } } catch (JSONException e) { e.printStackTrace(); } } return size; } public JSONArray getSeriesArray() { return seriesArray; } public void setSeriesArray(JSONArray seriesArray) { this.seriesArray = seriesArray; } public JSONArray getProductArray() { return productArray; } public void setProductArray(JSONArray productArray) { this.productArray = productArray; } public OffShopInfo getShopInfo() { return shopInfo; } public void setShopInfo(OffShopInfo shopInfo) { this.shopInfo = shopInfo; } public OffDownloadStatus getDownloadStatus() { return downloadStatus; } public void setDownloadStatus(OffDownloadStatus downloadStatus) { this.downloadStatus = downloadStatus; } }
package org.springframework.roo.addon.jpa.addon.entity; import java.util.Set; import org.apache.felix.scr.annotations.Component; import org.apache.felix.scr.annotations.Reference; import org.apache.felix.scr.annotations.Service; import org.springframework.roo.classpath.TypeLocationService; import org.springframework.roo.classpath.details.ClassOrInterfaceTypeDetails; import org.springframework.roo.model.JavaType; import org.springframework.roo.model.JpaJavaType; import org.springframework.roo.model.RooJavaType; import org.springframework.roo.project.ProjectOperations; import org.springframework.roo.settings.project.ProjectSettingsService; import org.springframework.roo.shell.ShellContext; import org.springframework.roo.addon.field.addon.FieldCreatorProvider; /** * Provides field creation operations support for JPA entities by implementing * FieldCreatorProvider. * * @author Sergio Clares * @since 2.0 */ @Component @Service public class JpaFieldCreatorProvider implements FieldCreatorProvider { @Reference private TypeLocationService typeLocationService; @Reference private ProjectOperations projectOperations; @Reference private ProjectSettingsService projectSettings; private static final String SPRING_ROO_JPA_REQUIRE_SCHEMA_OBJECT_NAME = "spring.roo.jpa.require.schema-object-name"; public static final String ROO_DEFAULT_JOIN_TABLE_NAME = "_ROO_JOIN_TABLE_"; @Override public boolean isValid(JavaType javaType) { ClassOrInterfaceTypeDetails cid = typeLocationService.getTypeDetails(javaType); if (cid.getAnnotation(RooJavaType.ROO_JPA_ENTITY) != null || cid.getAnnotation(JpaJavaType.ENTITY) != null) { return true; } return false; } @Override public boolean isFieldManagementAvailable() { Set<ClassOrInterfaceTypeDetails> entities = typeLocationService.findClassesOrInterfaceDetailsWithAnnotation(JpaJavaType.ENTITY, RooJavaType.ROO_JPA_ENTITY); if (!entities.isEmpty()) { return true; } return false; } /** * ROO-3710: Indicator that checks if exists some project setting that makes * table column parameter mandatory. * * @param shellContext * @return true if exists property * {@link #SPRING_ROO_JPA_REQUIRE_SCHEMA_OBJECT_NAME} on project settings * and its value is "true". If not, return false. */ @Override public boolean isColumnMandatoryForFieldBoolean(ShellContext shellContext) { // Check if property 'spring.roo.jpa.require.schema-object-name' is defined on // project settings String requiredSchemaObjectName = projectSettings.getProperty(SPRING_ROO_JPA_REQUIRE_SCHEMA_OBJECT_NAME); if (requiredSchemaObjectName != null && requiredSchemaObjectName.equals("true")) { return true; } return false; } @Override public boolean isColumnVisibleForFieldBoolean(ShellContext shellContext) { return true; } @Override public boolean isTransientVisibleForFieldBoolean(ShellContext shellContext) { return true; } /** * ROO-3710: Indicator that checks if exists some project setting that makes * table column parameter mandatory. * * @param shellContext * @return true if exists property * {@link #SPRING_ROO_JPA_REQUIRE_SCHEMA_OBJECT_NAME} on project settings * and its value is "true". If not, return false. */ @Override public boolean isColumnMandatoryForFieldDate(ShellContext shellContext) { // Check if property 'spring.roo.jpa.require.schema-object-name' is defined on // project settings String requiredSchemaObjectName = projectSettings.getProperty(SPRING_ROO_JPA_REQUIRE_SCHEMA_OBJECT_NAME); if (requiredSchemaObjectName != null && requiredSchemaObjectName.equals("true")) { return true; } return false; } @Override public boolean isColumnVisibleForFieldDate(ShellContext shellContext) { return true; } @Override public boolean isPersistenceTypeVisibleForFieldDate(ShellContext shellContext) { return true; } @Override public boolean isTransientVisibleForFieldDate(ShellContext shellContext) { return true; } /** * ROO-3710: Indicator that checks if exists some project setting that makes * table column parameter mandatory. * * @param shellContext * @return true if exists property * {@link #SPRING_ROO_JPA_REQUIRE_SCHEMA_OBJECT_NAME} on project settings * and its value is "true". If not, return false. */ @Override public boolean isColumnMandatoryForFieldEnum(ShellContext shellContext) { // Check if property 'spring.roo.jpa.require.schema-object-name' is defined on // project settings String requiredSchemaObjectName = projectSettings.getProperty(SPRING_ROO_JPA_REQUIRE_SCHEMA_OBJECT_NAME); if (requiredSchemaObjectName != null && requiredSchemaObjectName.equals("true")) { return true; } return false; } @Override public boolean isColumnVisibleForFieldEnum(ShellContext shellContext) { return true; } @Override public boolean isEnumTypeVisibleForFieldEnum(ShellContext shellContext) { return true; } @Override public boolean isTransientVisibleForFieldEnum(ShellContext shellContext) { return true; } /** * ROO-3710: Indicator that checks if exists some project setting that makes * table column parameter mandatory. * * @param shellContext * @return true if exists property * {@link #SPRING_ROO_JPA_REQUIRE_SCHEMA_OBJECT_NAME} on project settings * and its value is "true". If not, return false. */ @Override public boolean isColumnMandatoryForFieldNumber(ShellContext shellContext) { // Check if property 'spring.roo.jpa.require.schema-object-name' is defined on // project settings String requiredSchemaObjectName = projectSettings.getProperty(SPRING_ROO_JPA_REQUIRE_SCHEMA_OBJECT_NAME); if (requiredSchemaObjectName != null && requiredSchemaObjectName.equals("true")) { return true; } return false; } @Override public boolean isColumnVisibleForFieldNumber(ShellContext shellContext) { return true; } @Override public boolean isUniqueVisibleForFieldNumber(ShellContext shellContext) { return true; } @Override public boolean isTransientVisibleForFieldNumber(ShellContext shellContext) { return true; } /** * ROO-3710: Indicator that checks if exists some project setting that makes * table column parameter mandatory. * * @param shellContext * @return true if exists property * {@link #SPRING_ROO_JPA_REQUIRE_SCHEMA_OBJECT_NAME} on project settings * and its value is "true". If not, return false. */ @Override public boolean isColumnMandatoryForFieldReference(ShellContext shellContext) { // Check if property 'spring.roo.jpa.require.schema-object-name' is defined on // project settings String requiredSchemaObjectName = projectSettings.getProperty(SPRING_ROO_JPA_REQUIRE_SCHEMA_OBJECT_NAME); if (requiredSchemaObjectName != null && requiredSchemaObjectName.equals("true")) { return true; } return false; } @Override public boolean isJoinColumnNameVisibleForFieldReference(ShellContext shellContext) { return true; } @Override public boolean isReferencedColumnNameVisibleForFieldReference(ShellContext shellContext) { return true; } @Override public boolean isCardinalityVisibleForFieldReference(ShellContext shellContext) { return true; } @Override public boolean isFetchVisibleForFieldReference(ShellContext shellContext) { return true; } @Override public boolean isTransientVisibleForFieldReference(ShellContext shellContext) { return true; } @Override public boolean isCascadeTypeVisibleForFieldReference(ShellContext shellContext) { return true; } /** * ROO-3710: Indicator that checks if exists some project setting that makes * table column parameter mandatory. * * @param shellContext * @return true if exists property * {@link #SPRING_ROO_JPA_REQUIRE_SCHEMA_OBJECT_NAME} on project settings * and its value is "true". If not, return false. */ @Override public boolean areJoinTableParamsMandatoryForFieldSet(ShellContext shellContext) { // Check if property 'spring.roo.jpa.require.schema-object-name' is defined on project settings String requiredSchemaObjectName = projectSettings.getProperty(SPRING_ROO_JPA_REQUIRE_SCHEMA_OBJECT_NAME); // See if joinTable param has been specified String joinTableParam = shellContext.getParameters().get("joinTable"); if (joinTableParam != null && requiredSchemaObjectName != null && requiredSchemaObjectName.equals("true")) { return true; } return false; } /** * ROO-3710: Indicator that checks if exists some project setting that makes * table column parameter mandatory. * * @param shellContext * @return true if exists property * {@link #SPRING_ROO_JPA_REQUIRE_SCHEMA_OBJECT_NAME} on project settings * and its value is "true". If not, return false. */ @Override public boolean isJoinTableMandatoryForFieldSet(ShellContext shellContext) { String cardinality = shellContext.getParameters().get("cardinality"); // Check if property 'spring.roo.jpa.require.schema-object-name' is defined on project settings String requiredSchemaObjectName = projectSettings.getProperty(SPRING_ROO_JPA_REQUIRE_SCHEMA_OBJECT_NAME); if (cardinality != null && cardinality.equals("MANY_TO_MANY") && requiredSchemaObjectName != null && requiredSchemaObjectName.equals("true")) { return true; } return false; } @Override public boolean areJoinTableParamsVisibleForFieldSet(ShellContext shellContext) { String joinTableParam = shellContext.getParameters().get("joinTable"); if (joinTableParam != null) { return true; } return false; } @Override public boolean isMappedByVisibleForFieldSet(ShellContext shellContext) { return true; } @Override public boolean isCardinalityVisibleForFieldSet(ShellContext shellContext) { return true; } @Override public boolean isFetchVisibleForFieldSet(ShellContext shellContext) { return true; } @Override public boolean isTransientVisibleForFieldSet(ShellContext shellContext) { return true; } @Override public boolean isJoinTableVisibleForFieldSet(ShellContext shellContext) { return true; } @Override public boolean areJoinTableParamsVisibleForFieldList(ShellContext shellContext) { String joinTableParam = shellContext.getParameters().get("joinTable"); if (joinTableParam != null) { return true; } return false; } @Override public boolean isJoinTableMandatoryForFieldList(ShellContext shellContext) { String cardinality = shellContext.getParameters().get("cardinality"); if (cardinality != null && cardinality.equals("MANY_TO_MANY")) { return true; } return false; } /** * ROO-3710: Indicator that checks if exists some project setting that makes * table column parameter mandatory. * * @param shellContext * @return true if exists property * {@link #SPRING_ROO_JPA_REQUIRE_SCHEMA_OBJECT_NAME} on project settings * and its value is "true". If not, return false. */ @Override public boolean areJoinTableParamsMandatoryForFieldList(ShellContext shellContext) { // Check if property 'spring.roo.jpa.require.schema-object-name' is defined on project settings String requiredSchemaObjectName = projectSettings.getProperty(SPRING_ROO_JPA_REQUIRE_SCHEMA_OBJECT_NAME); // See if joinTable param has been specified String joinTableParam = shellContext.getParameters().get("joinTable"); if (joinTableParam != null && requiredSchemaObjectName != null && requiredSchemaObjectName.equals("true")) { return true; } return false; } @Override public boolean isMappedByVisibleForFieldList(ShellContext shellContext) { return true; } @Override public boolean isCardinalityVisibleForFieldList(ShellContext shellContext) { return true; } @Override public boolean isFetchVisibleForFieldList(ShellContext shellContext) { return true; } @Override public boolean isTransientVisibleForFieldList(ShellContext shellContext) { return true; } @Override public boolean isJoinTableVisibleForFieldList(ShellContext shellContext) { return true; } /** * ROO-3710: Indicator that checks if exists some project setting that makes * table column parameter mandatory. * * @param shellContext * @return true if exists property * {@link #SPRING_ROO_JPA_REQUIRE_SCHEMA_OBJECT_NAME} on project settings * and its value is "true". If not, return false. */ @Override public boolean isColumnMandatoryForFieldString(ShellContext shellContext) { // Check if property 'spring.roo.jpa.require.schema-object-name' is defined on // project settings String requiredSchemaObjectName = projectSettings.getProperty(SPRING_ROO_JPA_REQUIRE_SCHEMA_OBJECT_NAME); if (requiredSchemaObjectName != null && requiredSchemaObjectName.equals("true")) { return true; } return false; } @Override public boolean isColumnVisibleForFieldString(ShellContext shellContext) { return true; } @Override public boolean isUniqueVisibleForFieldString(ShellContext shellContext) { return true; } @Override public boolean isTransientVisibleForFieldString(ShellContext shellContext) { return true; } @Override public boolean isLobVisibleForFieldString(ShellContext shellContext) { return true; } /** * ROO-3710: Indicator that checks if exists some project setting that makes * table column parameter mandatory. * * @param shellContext * @return true if exists property * {@link #SPRING_ROO_JPA_REQUIRE_SCHEMA_OBJECT_NAME} on project settings * and its value is "true". If not, return false. */ @Override public boolean isColumnMandatoryForFieldFile(ShellContext shellContext) { // Check if property 'spring.roo.jpa.require.schema-object-name' is defined on // project settings String requiredSchemaObjectName = projectSettings.getProperty(SPRING_ROO_JPA_REQUIRE_SCHEMA_OBJECT_NAME); if (requiredSchemaObjectName != null && requiredSchemaObjectName.equals("true")) { return true; } return false; } @Override public boolean isColumnVisibleForFieldFile(ShellContext shellContext) { return true; } /** * ROO-3710: Indicator that checks if exists some project setting that makes * table column parameter mandatory. * * @param shellContext * @return true if exists property * {@link #SPRING_ROO_JPA_REQUIRE_SCHEMA_OBJECT_NAME} on project settings * and its value is "true". If not, return false. */ public boolean isColumnMandatoryForFieldOther(ShellContext shellContext) { // Check if property 'spring.roo.jpa.require.schema-object-name' is defined on // project settings String requiredSchemaObjectName = projectSettings.getProperty(SPRING_ROO_JPA_REQUIRE_SCHEMA_OBJECT_NAME); if (requiredSchemaObjectName != null && requiredSchemaObjectName.equals("true")) { return true; } return false; } public boolean isColumnVisibleForFieldOther(ShellContext shellContext) { return true; } public boolean isTransientVisibleForFieldOther(ShellContext shellContext) { return true; } }
package com.datasoucre; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; public class MySqlConnector { static final String JDBC_DRIVER = "com.mysql.jdbc.Driver"; static final String DB_URL = "jdbc:mysql://localhost:3306/tbluser"; // Database credentials static final String USER = "root"; static final String PASS = "123456"; public static Connection getConnection() throws ClassNotFoundException { Connection conn = null; try { // Register JDBC driver Class.forName(JDBC_DRIVER); conn = DriverManager.getConnection(DB_URL, USER, PASS); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return conn; } }
package Practicas; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.geom.Rectangle2D; import java.util.Date; public class MarcoDialogos extends JFrame { public MarcoDialogos(){ setTitle("Prueba de diálogos"); setBounds(350,150,650,450); //=========parametros iniciales========================// JPanel LaminaCuadricula=new JPanel(); LaminaCuadricula.setLayout(new GridLayout(2,3)); String primero[]={"Mensaje","Confirmar","Opcion","Entrada"}; LaminaTipo=new LaminaBotones("Tipo", primero); LaminaConfirmar=new LaminaBotones("Confirmar",new String[]{ "DEFAULT_OPTION","YES_NO_OPTION","YES_NO_CANCEL_OPTION","OK_CANCEL_OPTION" }); LaminaTipoMensaje=new LaminaBotones("Tipo de Mensaje",new String[]{//instancia del array de String dentro del parametro "ERROR_MESSAGE","INFORMATION_MESSAGE","WARNING_MESSAGE","QUESTION_MESSAGE","PLAIN_MESSAGE" }); LaminaOpcion=new LaminaBotones("Opcion",new String[]{ "String[]","Icon[]","Object[]" }); LaminaMensaje=new LaminaBotones("Mensaje",new String[]{ "Cadena","Icono","Componente","Otros","Object[]" }); LaminaEntrada=new LaminaBotones("Entrada",new String[]{ "Campo de texto","Combo" }); LaminaCuadricula.add(LaminaTipo); LaminaCuadricula.add(LaminaTipoMensaje); LaminaCuadricula.add(LaminaMensaje); LaminaCuadricula.add(LaminaConfirmar); LaminaCuadricula.add(LaminaOpcion); LaminaCuadricula.add(LaminaEntrada); setLayout(new BorderLayout()); add(LaminaCuadricula, BorderLayout.CENTER); //construimosla laminainferrio JPanel LaminaMostrar=new JPanel(); JButton BotonMostrar=new JButton("Mostrar"); BotonMostrar.addActionListener(new AccionMostrar()); LaminaMostrar.add(BotonMostrar); add(LaminaMostrar,BorderLayout.SOUTH); } //======================proporciona el mensaje============================// public Object dameMensaje(){ String s=LaminaMensaje.dameSeleccion();//devuelve el string de la opcion selecionada if(s.equals("Cadena")){ return cadenaMensaje; }else if(s.equals("Icono")){ return iconoMensaje; }else if(s.equals("Componente")){ return componenteMensaje; }else if(s.equals("Otros")){ return objetoMensaje; }else if(s.equals("Object[]")){ return new Object[]{cadenaMensaje,iconoMensaje,componenteMensaje,objetoMensaje}; }else{ return null; } } //======================devuleve tipo icono y tambien numero de botones en confirmar===================================================// public int dameTipo(LaminaBotones lamina){ String s=lamina.dameSeleccion();//almacena en s la opcion selecionada por ele usuario if(s.equals("ERROR_MESSAGE") || s.equals("YES_NO_OPTION")){ return 0; }else if(s.equals("INFORMATION_MESSAGE") || s.equals("YES_NO_CANCEL_OPTION")){ return 1; }else if(s.equals("WARNING_MESSAGE") || s.equals("OK_CANCEL_OPTION")){ return 2; }else if(s.equals("QUESTION_MESSAGE")){ return 3; }else if(s.equals("PLAIN_MESSAGE") || s.equals("DEFAULT_OPTION")){ return -1; }else{ return 0; } } //===================DA OPCIONES A LA LAMINA OPCIONES===========// public Object[] dameOpciones(LaminaBotones lamina){ String s=lamina.dameSeleccion(); if (s.equals("String[]")){ return new String[]{"Amarillo","Azul","Rojo"}; }else if(s.equals("Icon[]")){ return new Object[]{new ImageIcon("src/imagenes/bolaAmarillo.gif"),new ImageIcon("src/imagenes/bolaAzul.gif"),new ImageIcon("src/imagenes/bolaRoja.gif")}; } else if(s.equals("Object[]")){ return new Object[]{cadenaMensaje,iconoMensaje,componenteMensaje,objetoMensaje}; } else{ return null; } } //clas interna quegestiona el metodo private class AccionMostrar implements ActionListener{ @Override public void actionPerformed(ActionEvent e) { //System.out.println(LaminaTipo.dameSeleccion()); if(LaminaTipo.dameSeleccion().equals("Mensaje")){ JOptionPane.showMessageDialog(MarcoDialogos.this, dameMensaje(), "Titulo", dameTipo(LaminaTipoMensaje)); } else if(LaminaTipo.dameSeleccion().equals("Confirmar")){ JOptionPane.showConfirmDialog(MarcoDialogos.this, dameMensaje(), "Titulo", dameTipo(LaminaConfirmar),dameTipo(LaminaTipoMensaje)); } else if(LaminaTipo.dameSeleccion().equals("Entrada")){ if(LaminaEntrada.dameSeleccion().equals("Campo de texto")){ JOptionPane.showInputDialog(MarcoDialogos.this, dameMensaje(), "Titulo",dameTipo(LaminaTipoMensaje)); }else{ JOptionPane.showInputDialog(MarcoDialogos.this, dameMensaje(),"Titulo", dameTipo(LaminaTipo), null, new String[]{"Amarillo","Azul","Rojo"}, "Azul"); } } else if(LaminaTipo.dameSeleccion().equals("Opcion")){ JOptionPane.showOptionDialog(MarcoDialogos.this, dameMensaje(), "Titulo", 1, dameTipo(LaminaTipoMensaje), null, dameOpciones(LaminaOpcion), null); } } } //===============================================================================// private LaminaBotones LaminaTipo, LaminaConfirmar, LaminaTipoMensaje, LaminaOpcion, LaminaMensaje, LaminaEntrada; private String cadenaMensaje="Cadena String"; private Icon iconoMensaje=new ImageIcon("src/imagenes/bolaAmarillo.GIF"); private Object objetoMensaje=new Date();//almacena la fecahas de hoy private Component componenteMensaje=new LaminaEjemplo(); } class LaminaEjemplo extends JPanel{ public void paintComponent(Graphics g){ super.paintComponents(g); Graphics2D g2=(Graphics2D) g; Rectangle2D rectangulo=new Rectangle2D.Double(0,0,getWidth(),getHeight()); g2.setPaint(Color.blue); g2.fill(rectangulo);//rellenar figuras geometricas } }
package com.mike.blog.controller; import com.mike.blog.modal.Blog; import com.mike.blog.service.BlogService; import com.mike.blog.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import javax.validation.Valid; import java.util.List; /** * This is the controller for the crud operation of blog * * @author Michael Ng * */ @RequestMapping("blog") @RestController public class BlogController { private BlogService blogService; private UserService userService; @Autowired public BlogController(BlogService blogService, UserService userService) { this.blogService = blogService; this.userService = userService; } /** * @return the list of blog from the system */ @GetMapping() public List<Blog> getBlog() { return blogService.getBlog(); } @GetMapping(path = "{id}") public Blog getBlogById(@PathVariable("id") long id) { return blogService.getBlog(id).orElse(null); } /** * @param token the user identifier * @param blog the blog in a json format */ @PostMapping() public void addBlog(@RequestParam String token, @RequestBody Blog blog) { blog.setCreator(userService.getUserByToken(token).getUsername()); blogService.addBlog(blog); } @DeleteMapping() public void deleteBlog(@RequestParam String token, @RequestBody long id) { if (userService.getUserByToken(token).getUsername().equals(blogService.getBlog(id).get().getCreator())) blogService.removeBlog(id); } @PutMapping() public void UpdateBlog(@RequestParam String token, @Valid @RequestBody Blog blog) { if (userService.getUserByToken(token).getUsername().equals(blog.getCreator())) blogService.updateBlog(blog); } }
package kosta.student.service; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Scanner; import kosta.student.manage.StudentManager; import kosta.student.vo.Student; public class StudentService3 implements StudentService{ @Override public void start(Scanner scan) { // TODO Auto-generated method stub StudentManager sm = new StudentManager(); List<Student> list = sm.service3(); System.out.println("1.이름순 출력, 2.성적순 출력, 3.반별 출력"); switch (scan.nextInt()) { case 1: Collections.sort(list, new Comparator<Student>() { @Override public int compare(Student o1, Student o2) { return o1.getName().compareTo(o2.getName()); } }); for (Student student : list) { System.out.println(student.toString()); } break; case 2: list.stream() .sorted((a, b)->a.getScore()-b.getScore()) .forEach((t)->System.out.println(t)); break; case 3: list.stream() .sorted((a, b) -> a.getBan().compareTo(b.getBan())) .forEach(t->System.out.println(t)); default: break; } } }
package com.lytlogic.simulate; public interface Event { public void act(); public Point getLocation(); public int getTime(); }
package dev.nowalk.util; import java.util.HashMap; import java.util.Map; import dev.nowalk.models.Movie; public class FakeDB { /* * This class will eventually be replaced, this will serve as a way for us to store our data, but the data will be lost when we * close out the application */ public static Map<Integer, Movie> movies = new HashMap<Integer, Movie>(); public static int idCount = 1; //static block, this is an initializer //the first time there is a reference to FakeDB this static block will be executed //this block will pre-populate our movies. For testing purposes static { Movie m1 = new Movie(1, "Iron Man", 5.0, true, 0); Movie m2 = new Movie(2, "Thor", 6.0, true, 0); Movie m3 = new Movie(3, "Captain America", 10.0, true, 0); //.put is the way you add things to a map with the key and value as parameters movies.put(idCount++, m1); movies.put(idCount++, m2); movies.put(idCount++, m3); } }
/* * null string is not an Object, for it is referred to any object. * */ package String; /** * * @author YNZ */ public class NullIsObject { static private String str; /** * @param args the command line arguments */ public static void main(String[] args) { System.out.println("" + str); System.out.println("null string is an object " + Boolean.toString(str instanceof Object)); } }
package org.ordogene.file; import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Base64; import java.util.List; import java.util.Objects; import org.ordogene.file.utils.Calculation; import org.ordogene.file.utils.Const; import com.fasterxml.jackson.databind.ObjectMapper; import gui.ava.html.image.generator.HtmlImageGenerator; /** * Handle files for all the project : create, write in, check, remove, get path * * @author darwinners team * */ public class FileUtils { private final static UserManager uh = new UserManager(); private final static CalculationManager ch = new CalculationManager(); private FileUtils() { } /** * call the method to add an user on the server * * @param username * : name of the user to add * @return true if the user has been added, false otherwise. */ public static boolean addUser(String username) { return uh.createUser(username); } /** * * @param directory * to create * @return true if directory is created, false otherwise */ public static boolean createCalculationDirectory(Path directory) { try { Files.createDirectories(directory); return true; } catch (IOException e) { return false; } } /** * * @param path * : file to encode in base 64 * @return : file encoded in base 64 */ public static String encodeFile(Path path) throws IOException { Objects.requireNonNull(path); byte[] imageData = Files.readAllBytes(path); return Base64.getEncoder().encodeToString(imageData); } /** * * @param userId * : owner of the calculation * @param cid * : id of the calculation * @param cName * : name of the calculation * @return : path of the calculation */ public static String getCalculationDirectoryPath(String userId, int cid, String cName) { return Const.getConst().get("ApplicationPath") + File.separatorChar + userId + File.separatorChar + "" + cid + "_" + cName; } /** * * @param userId * : owner of the calculation * @param cid * : id of the calculation * @param calName * : name of the calculation * @return : path of the state.json file for this calculation */ public static String getCalculationStatePath(String userId, int cid, String calName) { return getCalculationDirectoryPath(userId, cid, calName) + File.separator + "state.json"; } /** * call the method to get user's calculations * * @param username * @return the calculations of the specified user in argument */ public static List<Calculation> getUserCalculations(String username) { return ch.getCalculations(username); } /** * * @param model * : file to Read * @return : file read as a String * @throws IOException * : if it's impossible to read the model * @throws IllegalArgumentException * : if model is a folder or does not exists */ public static String readFile(File model) throws IOException { Path jsonPath = model.toPath(); if (!jsonPath.toFile().exists()) { throw new IllegalArgumentException("The path does not exist. Try again."); } if (jsonPath.toFile().isDirectory()) { throw new IllegalArgumentException(jsonPath + " is a directory. Try again."); } return new String(Files.readAllBytes(jsonPath)); } /** * call the method to remove an user on the server * * @param username * : name of the user to remove * @return true if the user has been deleted, false otherwise. */ public static boolean removeUser(String username) { return uh.removeUser(username); } /** * call the method to remove user's calculations * * @param username * : owner of the calculation to deleter * @param cid * : id of the calculation to delete * @param calName * : name of the calculation to delete * @return true if success, false otherwise */ public static boolean removeUserCalculation(String username, int cid, String calName) { return ch.removeCalculation(username, cid, calName); } /** * * @param base64Html * : html code in base 64 * @param pathDstHtml * : path to save the base 64 html decoded * @throws IOException * : if it's not possible to write (rights, incorrect path,...) */ public static void saveHtmlFromBase64(String base64Html, String pathDstHtml) throws IOException { Objects.requireNonNull(base64Html); Objects.requireNonNull(pathDstHtml); Path path = Paths.get(pathDstHtml); try (BufferedWriter writer = Files.newBufferedWriter(path, Charset.forName("UTF-8"))) { byte[] decodedBytes = Base64.getDecoder().decode(base64Html); String decodedStr = new String(decodedBytes); writer.write(decodedStr); } catch (FileNotFoundException e) { throw new FileNotFoundException("Destination path is not a file : " + e); } catch (IOException e) { throw new IOException("cannot write to the path : " + e); } } /** * * @param base64Img * : image in base 64 * @param pathDstImg * : destination path (relative or absolute, in String) to write the * image on the disk * @throws IOException * : if it is not possible to write on the folder * @throws FileNotFoundException * : if the destination Path doesn't exists */ public static void saveImageFromBase64(String base64Img, String pathDstImg) throws IOException, FileNotFoundException { Objects.requireNonNull(base64Img); Objects.requireNonNull(pathDstImg); byte[] imageData = Base64.getDecoder().decode(base64Img); try (FileOutputStream imageFile = new FileOutputStream(pathDstImg)) { imageFile.write(imageData); } catch (FileNotFoundException e) { throw new FileNotFoundException("Destination path is not a file or cannot be created/opened : " + e); } catch (IOException e) { throw new IOException("Cannot write to the path : " + e); } } /** * Save a result in .html and .png format * * @param html * : html content to write * @param calculationDirectory * : destination Path for the .png and .html file * @return true if the files has been writed successfully, false otherwise. */ public static boolean saveResult(String html, Path calculationDirectory) { Path pngPath = calculationDirectory.resolve("result.png"); Path htmlPath = calculationDirectory.resolve("result.html"); try { Files.createDirectories(calculationDirectory); if (htmlPath != null) { Files.write(htmlPath, html.getBytes(StandardCharsets.UTF_8)); } HtmlImageGenerator imageGenerator = new HtmlImageGenerator(); imageGenerator.loadHtml(html); imageGenerator.saveAsImage(pngPath.toString()); return true; } catch (Exception e) { e.printStackTrace(); return false; } } /** * call the method to check if the given user exist on the server * * @param username * : name of the user to check * @return true if the user exists, false otherwise. */ public static boolean userExist(String username) { return uh.checkUserExists(username); } /** * * @param content * : object to write in json * @param username * : id of the calculation owner * @param cid * : id of the calculation to write in * @param calName * : name of the calculation to write in * * @throws IOException */ public static void writeJsonInFile(Object content, String username, int cid, String calName) throws IOException { Path dest = Paths.get(getCalculationStatePath(username, cid, calName)); if (dest.toFile().exists()) { Files.delete(dest); } Files.createDirectories(dest.getParent()); Files.createFile(dest); ObjectMapper mapper = new ObjectMapper(); // Object to JSON in file mapper.writeValue(dest.toFile(), content); } }
package featureEngineering; public class PriceRecord { }
/* * Demoiselle Framework * * License: GNU Lesser General Public License (LGPL), version 3 or later. * See the lgpl.txt file in the root directory or <https://www.gnu.org/licenses/lgpl.html>. */ package org.demoiselle.jee.security.token.impl; import static java.lang.System.out; import java.util.logging.Logger; import javax.inject.Inject; import org.apache.deltaspike.testcontrol.api.junit.CdiTestRunner; import org.demoiselle.jee.core.api.security.DemoiselleUser; import org.demoiselle.jee.core.api.security.Token; import org.demoiselle.jee.core.api.security.TokenManager; import org.junit.After; import org.junit.AfterClass; import static org.junit.Assert.*; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; /** * * @author gladson */ @RunWith(CdiTestRunner.class) public class TokenManagerImplTest { private static String localtoken; private static final Logger LOG = Logger.getLogger(TokenManagerImplTest.class.getName()); /** * */ @BeforeClass public static void setUpClass() { } /** * */ @AfterClass public static void tearDownClass() { } @Inject private DemoiselleUser dml; @Inject private Token token; @Inject private TokenManager instance; /** * */ public TokenManagerImplTest() { } /** * */ @Before public void setUp() { } /** * */ @After public void tearDown() { } /** * Test of setUser method, of class TokenManagerImpl. */ @Test public void test20() { out.println("setUser"); assertEquals("", ""); } }
package com.xixiwan.platform.sys.service; import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.extension.service.IService; import com.xixiwan.platform.module.common.rest.RestResponse; import com.xixiwan.platform.sys.entity.SysUser; import com.xixiwan.platform.sys.form.SysUserForm; /** * <p> * 管理员表 服务类 * </p> * * @author Sente * @since 2018-09-18 */ public interface ISysUserService extends IService<SysUser> { IPage<SysUser> selectPage(SysUserForm userForm); SysUser selectUserByUsername(String username); RestResponse<String> register(SysUser user); RestResponse<String> editUser(SysUser user); RestResponse<String> editAvatar(String avatar, String fileName, SysUser user); RestResponse<String> unlockScreen(SysUser user, String password); RestResponse<String> expire(SysUserForm userForm); RestResponse<String> changePassword(SysUser user, SysUserForm userForm); }
package com.zc.pivas.configfee.bean; import java.util.Date; /** * * 收费详情实体bean * * @author cacabin * @version 1.0 */ public class ChargeDetailsBean { private int yDPZFID;// 药单配置费表主键,自增长 NUMBER private int yDID;// 药单表的主键 NUMBER private int pZFZT;// 药单配置费收取、退费状态,0,配置费收取失败 1,配置费收费成功 2,配置费退费失败 3、配置费退费成功 // NUMBER private String pZFSBYY; // 药单配置费收取、退费失败原因 VARCHAR2 private String pZFSQRQ; // 药单配置费收取、退费时间 YYYY-MM-DD HH:MM:SS DATE private int cONFIGFEERULEID;// 对应配置费规则表的主键 NUMBER private String cZYMC; // 收费、退费操作员名称 VARCHAR2 private int gID; // 对应核对步骤表的主键;// NUMBER private String cASE_ID; // 病人唯一住院号[新增] VARCHAR2 private String costcode; private String pidrqzxbc; private String doctor; private String doctorName; // 20PIVAS_YD药单表 // private int YD_ID;// 主键标识,自增长 NUMBER private int aCTORDER_NO;// 医嘱编码,此字段须与HIS医嘱信息中编码一致 NUMBER private int pARENT_NO;// 父医嘱编码或组编码 NUMBER private int dYBZ;// 药单打印标志,0已打印 1未打印 NUMBER Date yYRQ; // 用药日期 YYYY-MM-DD HH:MM:SS DATE Date dATESCRQ;// 药单生成日期 YYYY-MM-DD HH:MM:SS DATE private int zXBC;// 执行批次,对应批次表的主键 NUMBER private int yDZXZT;// 药单执行状态 0,执行 1,停止 2,撤销 NUMBER private int yDZT;// 药单状态步骤 0,执行 1,停止 2,撤销 3,未打印 4,已打印 5,入仓扫描核对完成 // 6,出仓扫描核对完成[移到公共表] NUMBER private String yDPQ;// 药单瓶签的唯一编号,审核通过后自动生成,打印时写入二维码并显示在瓶签上[移到公共表] NUMBER private String mEDICAMENTS_CODE;// 药品编码 VARCHAR2 private String cHARGE_CODE;// 医嘱的药品编码。 VARCHAR2 private String dRUGNAME;// 医嘱的药品名称。 VARCHAR2 private String sPECIFICATIONS;// 医嘱的药品规格。 VARCHAR2 private String dOSE;// 医嘱的药品单次剂量。 VARCHAR2 private String dOSE_UNIT;// 医嘱的药品单次剂量单位。 VARCHAR2 private String qUANTITY;// 药品数量 VARCHAR2 private String rESERVE1;// 备用字段1 VARCHAR2 private String rESERVE2;// 备用字段2 VARCHAR2 private String rESERVE3;// 备用字段3 VARCHAR2 private String nAME_; private Long pqRefFeeID; public String getnAME_() { return nAME_; } public void setnAME_(String nAME_) { this.nAME_ = nAME_; } public String getwARDNAME() { return wARDNAME; } public void setwARDNAME(String wARDNAME) { this.wARDNAME = wARDNAME; } private String mEDICAMENTS_PACKING_UNIT;// 包装单位 VARCHAR2 private String wARDNAME; // SRVS_LABEL药单瓶签表 private String dEPTNAME;// 病区名称 VARCHAR2 private String cATEGORY_CODE_LIST;// 分类瓶签编码列表 VARCHAR2 public int getpZFZT() { return pZFZT; } public void setpZFZT(int pZFZT) { this.pZFZT = pZFZT; } public String getpZFSBYY() { return pZFSBYY; } public void setpZFSBYY(String pZFSBYY) { this.pZFSBYY = pZFSBYY; } public int getcONFIGFEERULEID() { return cONFIGFEERULEID; } public void setcONFIGFEERULEID(int cONFIGFEERULEID) { this.cONFIGFEERULEID = cONFIGFEERULEID; } public String getcZYMC() { return cZYMC; } public void setcZYMC(String cZYMC) { this.cZYMC = cZYMC; } public String getpZFSQRQ() { return pZFSQRQ; } public void setpZFSQRQ(String pZFSQRQ) { this.pZFSQRQ = pZFSQRQ; } public int getgID() { return gID; } public void setgID(int gID) { this.gID = gID; } public String getcASE_ID() { return cASE_ID; } public void setcASE_ID(String cASE_ID) { this.cASE_ID = cASE_ID; } public int getyDPZFID() { return yDPZFID; } public void setyDPZFID(int yDPZFID) { this.yDPZFID = yDPZFID; } public int getyDID() { return yDID; } public void setyDID(int yDID) { this.yDID = yDID; } public int getaCTORDER_NO() { return aCTORDER_NO; } public void setaCTORDER_NO(int aCTORDER_NO) { this.aCTORDER_NO = aCTORDER_NO; } public int getpARENT_NO() { return pARENT_NO; } public void setpARENT_NO(int pARENT_NO) { this.pARENT_NO = pARENT_NO; } public int getdYBZ() { return dYBZ; } public void setdYBZ(int dYBZ) { this.dYBZ = dYBZ; } public Date getyYRQ() { Date date = new Date(yYRQ.getTime()); return date; } public void setyYRQ(Date yYRQ) { Date date = new Date(yYRQ.getTime()); this.yYRQ = date; } public Date getdATESCRQ() { Date date = new Date(dATESCRQ.getTime()); return date; } public void setdATESCRQ(Date dATESCRQ) { Date date = new Date(dATESCRQ.getTime()); this.dATESCRQ = date; } public int getzXBC() { return zXBC; } public void setzXBC(int zXBC) { this.zXBC = zXBC; } public int getyDZXZT() { return yDZXZT; } public void setyDZXZT(int yDZXZT) { this.yDZXZT = yDZXZT; } public int getyDZT() { return yDZT; } public void setyDZT(int yDZT) { this.yDZT = yDZT; } public String getyDPQ() { return yDPQ; } public void setyDPQ(String yDPQ) { this.yDPQ = yDPQ; } public String getmEDICAMENTS_CODE() { return mEDICAMENTS_CODE; } public void setmEDICAMENTS_CODE(String mEDICAMENTS_CODE) { this.mEDICAMENTS_CODE = mEDICAMENTS_CODE; } public String getcHARGE_CODE() { return cHARGE_CODE; } public void setcHARGE_CODE(String cHARGE_CODE) { this.cHARGE_CODE = cHARGE_CODE; } public String getdRUGNAME() { return dRUGNAME; } public void setdRUGNAME(String dRUGNAME) { this.dRUGNAME = dRUGNAME; } public String getsPECIFICATIONS() { return sPECIFICATIONS; } public void setsPECIFICATIONS(String sPECIFICATIONS) { this.sPECIFICATIONS = sPECIFICATIONS; } public String getdOSE() { return dOSE; } public void setdOSE(String dOSE) { this.dOSE = dOSE; } public String getdOSE_UNIT() { return dOSE_UNIT; } public void setdOSE_UNIT(String dOSE_UNIT) { this.dOSE_UNIT = dOSE_UNIT; } public String getqUANTITY() { return qUANTITY; } public void setqUANTITY(String qUANTITY) { this.qUANTITY = qUANTITY; } public String getrESERVE1() { return rESERVE1; } public void setrESERVE1(String rESERVE1) { this.rESERVE1 = rESERVE1; } public String getrESERVE2() { return rESERVE2; } public void setrESERVE2(String rESERVE2) { this.rESERVE2 = rESERVE2; } public String getrESERVE3() { return rESERVE3; } public void setrESERVE3(String rESERVE3) { this.rESERVE3 = rESERVE3; } public String getmEDICAMENTS_PACKING_UNIT() { return mEDICAMENTS_PACKING_UNIT; } public void setmEDICAMENTS_PACKING_UNIT(String mEDICAMENTS_PACKING_UNIT) { this.mEDICAMENTS_PACKING_UNIT = mEDICAMENTS_PACKING_UNIT; } public String getdEPTNAME() { return dEPTNAME; } public void setdEPTNAME(String dEPTNAME) { this.dEPTNAME = dEPTNAME; } public String getcATEGORY_CODE_LIST() { return cATEGORY_CODE_LIST; } public void setcATEGORY_CODE_LIST(String cATEGORY_CODE_LIST) { this.cATEGORY_CODE_LIST = cATEGORY_CODE_LIST; } public String getiNHOSPNO() { return iNHOSPNO; } public void setiNHOSPNO(String iNHOSPNO) { this.iNHOSPNO = iNHOSPNO; } public String getpATNAME() { return pATNAME; } public void setpATNAME(String pATNAME) { this.pATNAME = pATNAME; } public int getsEX() { return sEX; } public void setsEX(int sEX) { this.sEX = sEX; } public Date getbIRTHDAY() { Date date = new Date(bIRTHDAY.getTime()); return date; } public void setbIRTHDAY(Date bIRTHDAY) { Date date = new Date(bIRTHDAY.getTime()); this.bIRTHDAY = date; } public String getaGE() { return aGE; } public void setaGE(String aGE) { this.aGE = aGE; } public int getaGEUNIT() { return aGEUNIT; } public void setaGEUNIT(int aGEUNIT) { this.aGEUNIT = aGEUNIT; } public String getaVDP() { return aVDP; } public void setaVDP(String aVDP) { this.aVDP = aVDP; } public String getsFYSMC() { return sFYSMC; } public void setsFYSMC(String sFYSMC) { this.sFYSMC = sFYSMC; } public String getbEDNO() { return bEDNO; } public void setbEDNO(String bEDNO) { this.bEDNO = bEDNO; } private String iNHOSPNO;// 住院流水号,病人唯一标识 VARCHAR2 private String pATNAME;// 患者姓名 VARCHAR2 private int sEX;// 性别:0女,1男,默认0 NUMBER Date bIRTHDAY; // 病人出生日期 DATE private String aGE; // 病人年龄 //VARCHAR2 private int aGEUNIT; // 年龄单位,0天 1月 2年 NUMBER private String aVDP; // 病人体重 VARCHAR2 private String sFYSMC; // 医嘱审核药师名名称,如[1001,詹姆斯] VARCHAR2 private String bEDNO; // 患者住院期间,所住床位对应的编号 VARCHAR2 public String getCostcode() { return costcode; } public void setCostcode(String costcode) { this.costcode = costcode; } public String getPidrqzxbc() { return pidrqzxbc; } public void setPidrqzxbc(String pidrqzxbc) { this.pidrqzxbc = pidrqzxbc; } public String getDoctor() { return doctor; } public void setDoctor(String doctor) { this.doctor = doctor; } public String getDoctorName() { return doctorName; } public void setDoctorName(String doctorName) { this.doctorName = doctorName; } public Long getPqRefFeeID() { return pqRefFeeID; } public void setPqRefFeeID(Long pqRefFeeID) { this.pqRefFeeID = pqRefFeeID; } }
package EstadosDoJogo; import java.awt.Graphics2D; import java.util.ArrayList; public class GerenciadorDeEstados { private ArrayList<Estado> estadosDoJogo; private int estadoAtual; //Atual estados em que o jogo se encontra //Constantes que identificam os estados do jogo private final int MENU = 0; private final int LEVEL1 = 0; public GerenciadorDeEstados(){ estadosDoJogo = new ArrayList<>(); estadosDoJogo.add(new Level1()); //adicionar os estados estadoAtual = LEVEL1; // Quando o jogo é iniciado, ele começa a executar o menu } //Atualiza o estado atual public void atualizar(){ estadosDoJogo.get(estadoAtual).atualizar(); } //Renderiza o estado atual public void renderizar(Graphics2D g){ estadosDoJogo.get(estadoAtual).renderizar(g); } //Notifica o estado atual de que uma tecla foi pressionada public void keyPressed(int key){ estadosDoJogo.get(estadoAtual).keyPressed(key); } //Notifica o estado atual de que uma tecla foi liberada public void keyReleased(int key){ estadosDoJogo.get(estadoAtual).keyReleased(key); } }
package com.itsoul.lab.ledgerbook.accounting.dependency; import com.itsoul.lab.generalledger.entities.Client; import com.itsoul.lab.generalledger.services.AccountService; import com.itsoul.lab.generalledger.services.TransferService; import com.itsoul.lab.ledgerbook.connector.SourceConnector; import java.sql.SQLException; public interface ContextResolver extends AutoCloseable{ /** * @return an instance of the AccountService providing account management */ AccountService getAccountService(); /** * @return an instance of the TransferService providing account transfers */ TransferService getTransferService(); /** * @param connector */ void configureDataSource(SourceConnector connector) throws SQLException; /** * @param connector */ void configureRepositories(SourceConnector connector, Client ref) throws SQLException; }
package Section_1_Basics; /* pattern *** *** *** */ public class P1 { public static void main(String[] args) { int n = 5; for (int i = 0 ; i <n;i++){ for (int j = 0;j<n;j++){ System.out.print("* "); } System.out.println(); } } }
package com.pdd.pop.sdk.http.api.response; import com.pdd.pop.ext.fasterxml.jackson.annotation.JsonProperty; import com.pdd.pop.sdk.http.PopBaseHttpResponse; public class PddSmsCreateCustomTemplateResponse extends PopBaseHttpResponse{ /** * 创建结果 */ @JsonProperty("sms_create_custom_template_response") private SmsCreateCustomTemplateResponse smsCreateCustomTemplateResponse; public SmsCreateCustomTemplateResponse getSmsCreateCustomTemplateResponse() { return smsCreateCustomTemplateResponse; } public static class SmsCreateCustomTemplateResponse { /** * 请求结果 */ @JsonProperty("result") private String result; public String getResult() { return result; } } }
package com.netcracker.Gleb; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.io.IOException; import java.io.PrintWriter; import java.util.Date; @WebServlet("/sessions") public class SessionTracking extends HttpServlet{ public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { HttpSession session = request.getSession(true); Date createTime = new Date(session.getCreationTime()); Date lastAccessTime = new Date(session.getLastAccessedTime()); String title = "Welcome Back to my website"; Integer visitCount = 0; String visitCountKey = new String("visitCount"); String userIDKey = new String("userID"); String userID = new String("ABCD"); if (session.isNew()) { title = "Welcome to my website"; session.setAttribute(userIDKey, userID); } else { visitCount = (Integer) session.getAttribute(visitCountKey); visitCount = visitCount + 1; userID = (String) session.getAttribute(userIDKey); } session.setAttribute(visitCountKey, visitCount); response.setContentType("text/html"); PrintWriter out = response.getWriter(); StringBuilder sb = new StringBuilder("<html>"); sb.append("<head><title>").append(title).append("</head></title>"); sb.append("<body>"); sb.append("<h1>" + "Visit count: ").append(visitCount).append("</h1><br>"); sb.append("<h1>" + "Visit count key: ").append(visitCountKey).append("</h1><br>"); sb.append("<h1>" + "UserId key: ").append(userIDKey).append("</h1><br>"); sb.append("<h1>" + "UserId: ").append(userID).append("</h1><br>"); sb.append("<h1>" + "Create time: ").append(createTime).append("</h1><br>"); sb.append("<h1>" + "Last access time: ").append(lastAccessTime).append("</h1><br>"); sb.append("<h1>" + "JSESSION_ID: ").append(request.getCookies()[0].getValue()).append("</h1><br>"); sb.append("</body></html>"); out.print(sb); } }
package uz.pdp.appcodingbat.service; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import uz.pdp.appcodingbat.entity.Task; import uz.pdp.appcodingbat.entity.TaskCategory; import uz.pdp.appcodingbat.payload.Result; import uz.pdp.appcodingbat.payload.TaskDto; import uz.pdp.appcodingbat.repository.TaskCategoryRepository; import uz.pdp.appcodingbat.repository.TaskRepository; import java.util.List; import java.util.Optional; @Service public class TaskService { @Autowired TaskRepository taskRepository; @Autowired TaskCategoryRepository taskCategoryRepository; public List<Task> get() { return taskRepository.findAll(); } public Task getById(Integer id) { Optional<Task> optionalTask = taskRepository.findById(id); return optionalTask.orElse(null); } public Result delete(Integer id) { try { taskRepository.deleteById(id); return new Result("Successfully deleted", true); } catch (Exception e) { return new Result("Error", false); } } public Result add(TaskDto taskDto) { boolean existsByName = taskRepository.existsByName(taskDto.getName()); if (existsByName) { return new Result("Task already exist", false); } Optional<TaskCategory> optionalTaskCategory = taskCategoryRepository.findById(taskDto.getTaskCategoryId()); if (!optionalTaskCategory.isPresent()) { return new Result("TaskCategory not found", false); } TaskCategory taskCategory = optionalTaskCategory.get(); Task task = new Task(taskDto.getName(), taskDto.getText(), taskDto.getSolution(), taskDto.getExample(), taskCategory); taskRepository.save(task); return new Result("Successfully added", true); } public Result edit(Integer id, TaskDto taskDto) { boolean existsByNameAndIdNot = taskRepository.existsByNameAndIdNot(taskDto.getName(), id); if (existsByNameAndIdNot) { return new Result("Task already exist", false); } Optional<Task> optionalTask = taskRepository.findById(id); if (!optionalTask.isPresent()) { return new Result("Task not found", false); } Task task = optionalTask.get(); task.setName(taskDto.getName()); task.setText(taskDto.getText()); task.setExample(taskDto.getExample()); task.setSolution(taskDto.getSolution()); taskRepository.save(task); return new Result("Successfully edited", true); } }
/* * Autopsy Forensic Browser * * Copyright 2011 Basis Technology Corp. * Contact: carrier <at> sleuthkit <dot> org * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.sleuthkit.autopsy.keywordsearch; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ExecutionException; import java.util.logging.Level; import java.util.logging.Logger; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; import javax.swing.SwingWorker; import org.apache.solr.client.solrj.SolrQuery; import org.apache.solr.client.solrj.SolrServerException; import org.apache.solr.client.solrj.response.TermsResponse; import org.apache.solr.client.solrj.response.TermsResponse.Term; import org.netbeans.api.progress.ProgressHandle; import org.netbeans.api.progress.ProgressHandleFactory; import org.openide.nodes.AbstractNode; import org.openide.nodes.Children; import org.openide.nodes.Node; import org.openide.windows.TopComponent; import org.sleuthkit.autopsy.corecomponents.DataResultTopComponent; import org.sleuthkit.autopsy.keywordsearch.KeywordSearchQueryManager.Presentation; import org.sleuthkit.datamodel.BlackboardArtifact; import org.sleuthkit.datamodel.BlackboardArtifact.ARTIFACT_TYPE; import org.sleuthkit.datamodel.BlackboardAttribute; import org.sleuthkit.datamodel.BlackboardAttribute.ATTRIBUTE_TYPE; import org.sleuthkit.datamodel.FsContent; import org.sleuthkit.datamodel.TskException; public class TermComponentQuery implements KeywordSearchQuery { private static final int TERMS_UNLIMITED = -1; //corresponds to field in Solr schema, analyzed with white-space tokenizer only private static final String TERMS_SEARCH_FIELD = Server.Schema.CONTENT_WS.toString(); private static final String TERMS_HANDLER = "/terms"; private static final int TERMS_TIMEOUT = 90 * 1000; //in ms private static Logger logger = Logger.getLogger(TermComponentQuery.class.getName()); private String termsQuery; private String queryEscaped; private boolean isEscaped; private List<Term> terms; private Keyword keywordQuery = null; private KeywordQueryFilter filter = null; public TermComponentQuery(Keyword keywordQuery) { this.keywordQuery = keywordQuery; this.termsQuery = keywordQuery.getQuery(); this.queryEscaped = termsQuery; isEscaped = false; terms = null; } @Override public void setFilter(KeywordQueryFilter filter) { this.filter = filter; } @Override public void escape() { queryEscaped = Pattern.quote(termsQuery); isEscaped = true; } @Override public boolean validate() { if (queryEscaped.equals("")) { return false; } boolean valid = true; try { Pattern.compile(queryEscaped); } catch (PatternSyntaxException ex1) { valid = false; } catch (IllegalArgumentException ex2) { valid = false; } return valid; } @Override public boolean isEscaped() { return isEscaped; } @Override public boolean isLiteral() { return false; } /* * helper method to create a Solr terms component query */ protected SolrQuery createQuery() { final SolrQuery q = new SolrQuery(); q.setQueryType(TERMS_HANDLER); q.setTerms(true); q.setTermsLimit(TERMS_UNLIMITED); q.setTermsRegexFlag("case_insensitive"); //q.setTermsLimit(200); //q.setTermsRegexFlag(regexFlag); //q.setTermsRaw(true); q.setTermsRegex(queryEscaped); q.addTermsField(TERMS_SEARCH_FIELD); q.setTimeAllowed(TERMS_TIMEOUT); return q; } /* * execute query and return terms, helper method */ protected List<Term> executeQuery(SolrQuery q) throws NoOpenCoreException { List<Term> termsCol = null; try { Server solrServer = KeywordSearch.getServer(); TermsResponse tr = solrServer.queryTerms(q); termsCol = tr.getTerms(TERMS_SEARCH_FIELD); return termsCol; } catch (SolrServerException ex) { logger.log(Level.WARNING, "Error executing the regex terms query: " + termsQuery, ex); return null; //no need to create result view, just display error dialog } } @Override public String getEscapedQueryString() { return this.queryEscaped; } @Override public String getQueryString() { return this.termsQuery; } @Override public Collection<Term> getTerms() { return terms; } @Override public KeywordWriteResult writeToBlackBoard(String termHit, FsContent newFsHit, String snippet, String listName) { final String MODULE_NAME = KeywordSearchIngestService.MODULE_NAME; if (snippet == null || snippet.equals("")) { return null; } //there is match actually in this file, create artifact only then BlackboardArtifact bba = null; KeywordWriteResult writeResult = null; Collection<BlackboardAttribute> attributes = new ArrayList<BlackboardAttribute>(); try { bba = newFsHit.newArtifact(ARTIFACT_TYPE.TSK_KEYWORD_HIT); writeResult = new KeywordWriteResult(bba); } catch (Exception e) { logger.log(Level.WARNING, "Error adding bb artifact for keyword hit", e); return null; } //regex match attributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_KEYWORD.getTypeID(), MODULE_NAME, "", termHit)); //list if (listName == null) { listName = ""; } attributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_KEYWORD_SET.getTypeID(), MODULE_NAME, "", listName)); //preview attributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_KEYWORD_PREVIEW.getTypeID(), MODULE_NAME, "", snippet)); //regex keyword attributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_KEYWORD_REGEXP.getTypeID(), MODULE_NAME, "", termsQuery)); //selector TODO move to general info artifact /* if (keywordQuery != null) { BlackboardAttribute.ATTRIBUTE_TYPE selType = keywordQuery.getType(); if (selType != null) { BlackboardAttribute selAttr = new BlackboardAttribute(selType.getTypeID(), MODULE_NAME, "", regexMatch); attributes.add(selAttr); } } */ try { bba.addAttributes(attributes); writeResult.add(attributes); return writeResult; } catch (TskException e) { logger.log(Level.WARNING, "Error adding bb attributes for terms search artifact", e); } return null; } @Override public Map<String, List<ContentHit>> performQuery() throws NoOpenCoreException{ Map<String, List<ContentHit>> results = new HashMap<String, List<ContentHit>>(); final SolrQuery q = createQuery(); terms = executeQuery(q); for (Term term : terms) { final String termS = KeywordSearchUtil.escapeLuceneQuery(term.getTerm(), true, false); StringBuilder filesQueryB = new StringBuilder(); filesQueryB.append(TERMS_SEARCH_FIELD).append(":").append(termS); final String queryStr = filesQueryB.toString(); LuceneQuery filesQuery = new LuceneQuery(queryStr); if (filter != null) filesQuery.setFilter(filter); try { Map<String, List<ContentHit>> subResults = filesQuery.performQuery(); Set<ContentHit> filesResults = new HashSet<ContentHit>(); for (String key : subResults.keySet()) { filesResults.addAll(subResults.get(key)); } results.put(term.getTerm(), new ArrayList<ContentHit>(filesResults)); } catch (NoOpenCoreException e) { logger.log(Level.WARNING, "Error executing Solr query,", e); throw e; } catch (RuntimeException e) { logger.log(Level.WARNING, "Error executing Solr query,", e); } } return results; } @Override public void execute() { SolrQuery q = createQuery(); logger.log(Level.INFO, "Executing TermsComponent query: " + q.toString()); final SwingWorker<List<Term>, Void> worker = new TermsQueryWorker(q); worker.execute(); } /** * map Terms to generic Nodes with key/value pairs properties * @param terms */ private void publishNodes(List<Term> terms) { Collection<KeyValueQuery> things = new ArrayList<KeyValueQuery>(); Iterator<Term> it = terms.iterator(); int termID = 0; //long totalMatches = 0; while (it.hasNext()) { Term term = it.next(); Map<String, Object> kvs = new LinkedHashMap<String, Object>(); //long matches = term.getFrequency(); final String match = term.getTerm(); KeywordSearchResultFactory.setCommonProperty(kvs, KeywordSearchResultFactory.CommonPropertyTypes.MATCH, match); //setCommonProperty(kvs, CommonPropertyTypes.MATCH_RANK, Long.toString(matches)); //things.add(new KeyValue(match, kvs, ++termID)); things.add(new KeyValueQuery(match, kvs, ++termID, this)); //totalMatches += matches; } Node rootNode = null; if (things.size() > 0) { Children childThingNodes = Children.create(new KeywordSearchResultFactory(new Keyword(termsQuery, false), things, Presentation.DETAIL), true); rootNode = new AbstractNode(childThingNodes); } else { rootNode = Node.EMPTY; } final String pathText = "Term query"; // String pathText = "RegEx query: " + termsQuery //+ " Files with exact matches: " + Long.toString(totalMatches) + " (also listing approximate matches)"; TopComponent searchResultWin = DataResultTopComponent.createInstance("Keyword search", pathText, rootNode, things.size()); searchResultWin.requestActive(); // make it the active top component } class TermsQueryWorker extends SwingWorker<List<Term>, Void> { private SolrQuery q; private ProgressHandle progress; TermsQueryWorker(SolrQuery q) { this.q = q; } @Override protected List<Term> doInBackground() throws Exception { progress = ProgressHandleFactory.createHandle("Terms query task"); progress.start(); progress.progress("Running Terms query."); terms = executeQuery(q); progress.progress("Terms query completed."); return terms; } @Override protected void done() { if (!this.isCancelled()) { try { List<Term> terms = get(); if (terms.isEmpty()) { KeywordSearchUtil.displayDialog("Keyword Search", "No results for regex search: " + termsQuery, KeywordSearchUtil.DIALOG_MESSAGE_TYPE.INFO); } else { publishNodes(terms); } } catch (InterruptedException e) { logger.log(Level.INFO, "Exception while executing regex query,", e); } catch (ExecutionException e) { logger.log(Level.INFO, "Exception while executing regex query,", e); } finally { progress.finish(); } } } } }
package algorithm.constants; public class SensorContants { /** * CONSTANTS FOR SENSOR READING SIMULATION MODE */ public static final int SIMULATOR_FRONT_CENTER_A_START = 7; public static final int SIMULATOR_FRONT_CENTER_A_END = 10; public static final int SIMULATOR_FRONT_CENTER_B_START = 11; public static final int SIMULATOR_FRONT_CENTER_B_END = 20; public static final int SIMULATOR_FRONT_CENTER_C_START = 21; public static final int SIMULATOR_FRONT_CENTER_C_END = 30; public static final int SIMULATOR_FRONT_LEFT_A_START = 7; public static final int SIMULATOR_FRONT_LEFT_A_END = 15; public static final int SIMULATOR_FRONT_LEFT_B_START = 16; public static final int SIMULATOR_FRONT_LEFT_B_END = 25; public static final int SIMULATOR_FRONT_LEFT_C_START = 26; public static final int SIMULATOR_FRONT_LEFT_C_END = 36; public static final int SIMULATOR_FRONT_RIGHT_A_START = 7; public static final int SIMULATOR_FRONT_RIGHT_A_END = 14; public static final int SIMULATOR_FRONT_RIGHT_B_START = 15; public static final int SIMULATOR_FRONT_RIGHT_B_END = 25; public static final int SIMULATOR_FRONT_RIGHT_C_START = 26; public static final int SIMULATOR_FRONT_RIGHT_C_END = 35; public static final int SIMULATOR_RIGHT_TOP_A_START = 7; public static final int SIMULATOR_RIGHT_TOP_A_END = 13; public static final int SIMULATOR_RIGHT_TOP_B_START = 14; public static final int SIMULATOR_RIGHT_TOP_B_END = 23; public static final int SIMULATOR_RIGHT_TOP_C_START = 24; public static final int SIMULATOR_RIGHT_TOP_C_END = 35; public static final int SIMULATOR_RIGHT_BOTTOM_A_START = 7; public static final int SIMULATOR_RIGHT_BOTTOM_A_END = 14; public static final int SIMULATOR_RIGHT_BOTTOM_B_START = 15; public static final int SIMULATOR_RIGHT_BOTTOM_B_END = 28; public static final int SIMULATOR_RIGHT_BOTTOM_C_START = 29; public static final int SIMULATOR_RIGHT_BOTTOM_C_END = 43; public static final int SIMULATOR_LEFT_MIDDLE_A_START = 0; public static final int SIMULATOR_LEFT_MIDDLE_A_END = 20; public static final int SIMULATOR_LEFT_MIDDLE_B_START = 21; public static final int SIMULATOR_LEFT_MIDDLE_B_END = 27; public static final int SIMULATOR_LEFT_MIDDLE_C_START = 28; public static final int SIMULATOR_LEFT_MIDDLE_C_END = 37; public static final int SIMULATOR_LEFT_MIDDLE_D_START = 38; public static final int SIMULATOR_LEFT_MIDDLE_D_END = 47; public static final int SIMULATOR_LEFT_MIDDLE_E_START = 48; public static final int SIMULATOR_LEFT_MIDDLE_E_END = 58; public static final int SIMULATOR_LEFT_MIDDLE_F_START = 59; public static final int SIMULATOR_LEFT_MIDDLE_F_END = 68; /** * CONSTANTS FOR SENSOR READING ACTUAL RUN MODE */ public static final int FRONT_CENTER_A_START = 6; public static final int FRONT_CENTER_A_END = 11; public static final int FRONT_CENTER_B_START = 11; public static final int FRONT_CENTER_B_END = 20; public static final int FRONT_CENTER_C_START = 21; public static final int FRONT_CENTER_C_END = 29; public static final int FRONT_LEFT_A_START = 7; public static final int FRONT_LEFT_A_END = 12; public static final int FRONT_LEFT_B_START = 13; public static final int FRONT_LEFT_B_END = 22; public static final int FRONT_LEFT_C_START = 23; public static final int FRONT_LEFT_C_END = 30; public static final int FRONT_RIGHT_A_START = 6; public static final int FRONT_RIGHT_A_END = 11; public static final int FRONT_RIGHT_B_START = 12; public static final int FRONT_RIGHT_B_END = 21; public static final int FRONT_RIGHT_C_START = 22; public static final int FRONT_RIGHT_C_END = 30; public static final int RIGHT_TOP_A_START = 6; //6 public static final int RIGHT_TOP_A_END = 13;//12 public static final int RIGHT_TOP_B_START = 13;//14 public static final int RIGHT_TOP_B_END = 22;//21 public static final int RIGHT_TOP_C_START = 23; //dont map public static final int RIGHT_TOP_C_END = 25; //dont map public static final int RIGHT_BOTTOM_A_START = 6;//6 public static final int RIGHT_BOTTOM_A_END = 12;//9 public static final int RIGHT_BOTTOM_B_START = 11;//11 public static final int RIGHT_BOTTOM_B_END = 21;//19 public static final int RIGHT_BOTTOM_C_START = 22;//22 public static final int RIGHT_BOTTOM_C_END = 35;//33 public static final int LEFT_MIDDLE_A_START = 0; //dont map public static final int LEFT_MIDDLE_A_END = 20; public static final int LEFT_MIDDLE_B_START = 18; //18, 18, 18 public static final int LEFT_MIDDLE_B_END = 18; public static final int LEFT_MIDDLE_C_START = 23; //20, 20, 20 public static final int LEFT_MIDDLE_C_END = 29; public static final int LEFT_MIDDLE_D_START = 32; //27, 27, 27 public static final int LEFT_MIDDLE_D_END = 40; public static final int LEFT_MIDDLE_E_START = 43; //37, 37, 37 public static final int LEFT_MIDDLE_E_END = 50; // public static final int LEFT_MIDDLE_F_START = 54; //dont map // public static final int LEFT_MIDDLE_F_END = 62; }
package cn.com.onlinetool.fastpay.util; import lombok.extern.slf4j.Slf4j; import okhttp3.*; import okio.BufferedSink; import org.junit.Test; import javax.annotation.Nullable; import java.io.File; import java.io.IOException; /** * @author choice * @date 2019-06-19 11:09 * */ @Slf4j public class OkHttp3ClientUtilTest { private static final OkHttpClient okHttpClient = new OkHttpClient(); /** * 测试 okHttp3 异步请求 GET * @return */ @Test public void okHttp3AsynGetReqTest(){ String url = "http://wwww.baidu.com"; final Request request = new Request.Builder() .url(url) .get()//默认就是GET请求,可以不写 .build(); Call call = okHttpClient.newCall(request); call.enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { log.error("onFailure:" + e.getMessage()); e.printStackTrace(); } @Override public void onResponse(Call call, Response res) throws IOException { log.info("onResponse: " + res.body().string()); } }); } /** * 测试 okHttp3 同步请求 GET * @return */ @Test public void okHttp3SyncGetReqTest(){ String url = "http://wwww.baidu.com"; final Request request = new Request.Builder() .url(url) .get() .build(); Response res = null; try { res = okHttpClient.newCall(request).execute(); System.out.println("onResponse: " + res.body().string()); } catch (IOException e) { System.out.println("onFailure: " + e.getMessage()); e.printStackTrace(); } } /** * 测试 okHttp3 异步请求 POST String * @return */ @Test public void okHttp3AsynPostStringReqTest(){ MediaType mediaType = MediaType.parse("text/x-markdown; charset=utf-8"); String requestBody = "I am Jdqm."; Request request = new Request.Builder() .url("https://api.github.com/markdown/raw") .post(RequestBody.create(mediaType, requestBody)) .build(); okHttpClient.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { System.out.println("onFailure: " + e.getMessage()); e.printStackTrace(); } @Override public void onResponse(Call call, Response res) throws IOException { System.out.println(res.protocol() + " " +res.code() + " " + res.message()); Headers headers = res.headers(); for (int i = 0; i < headers.size(); i++) { System.out.println(headers.name(i) + ":" + headers.value(i)); } System.out.println("onResponse: " + res.body().string()); } }); } /** * 测试 okHttp3 同步请求 POST String * @return */ @Test public void okHttp3SyncPostStringReqTest(){ MediaType mediaType = MediaType.parse("text/x-markdown; charset=utf-8"); String requestBody = "I am Jdqm."; Request request = new Request.Builder() .url("https://api.github.com/markdown/raw") .post(RequestBody.create(mediaType, requestBody)) .build(); Response res = null; try { res = okHttpClient.newCall(request).execute(); System.out.println(res.protocol() + " " +res.code() + " " + res.message()); Headers headers = res.headers(); for (int i = 0; i < headers.size(); i++) { System.out.println(headers.name(i) + ":" + headers.value(i)); } System.out.println("onResponse: " + res.body().string()); } catch (IOException e) { System.out.println("onFailure: " + e.getMessage()); e.printStackTrace(); } } /** * 测试 okHttp3 异步请求 POST Stream * @return */ @Test public void okHttp3AsynPostStreamReqTest(){ RequestBody requestBody = new RequestBody() { @Nullable @Override public MediaType contentType() { return MediaType.parse("text/x-markdown; charset=utf-8"); } @Override public void writeTo(BufferedSink sink) throws IOException { sink.writeUtf8("I am Jdqm."); } }; Request request = new Request.Builder() .url("https://api.github.com/markdown/raw") .post(requestBody) .build(); okHttpClient.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { System.out.println("onFailure: " + e.getMessage()); e.printStackTrace(); } @Override public void onResponse(Call call, Response res) throws IOException { System.out.println(res.protocol() + " " +res.code() + " " + res.message()); Headers headers = res.headers(); for (int i = 0; i < headers.size(); i++) { System.out.println(headers.name(i) + ":" + headers.value(i)); } System.out.println("onResponse: " + res.body().string()); } }); } /** * 测试 okHttp3 同步请求 POST Stream * @return */ @Test public void okHttp3SyncPostStreamReqTest(){ RequestBody requestBody = new RequestBody() { @Nullable @Override public MediaType contentType() { return MediaType.parse("text/x-markdown; charset=utf-8"); } @Override public void writeTo(BufferedSink sink) throws IOException { sink.writeUtf8("I am Jdqm."); } }; Request request = new Request.Builder() .url("https://api.github.com/markdown/raw") .post(requestBody) .build(); Response res = null; try { res = okHttpClient.newCall(request).execute(); System.out.println(res.protocol() + " " +res.code() + " " + res.message()); Headers headers = res.headers(); for (int i = 0; i < headers.size(); i++) { System.out.println(headers.name(i) + ":" + headers.value(i)); } System.out.println("onResponse: " + res.body().string()); } catch (IOException e) { System.out.println("onFailure: " + e.getMessage()); e.printStackTrace(); } } /** * 测试 okHttp3 异步请求 POST File * @return */ @Test public void okHttp3AsynPostFileReqTest(){ MediaType mediaType = MediaType.parse("text/x-markdown; charset=utf-8"); File file = new File("test.md"); Request request = new Request.Builder() .url("https://api.github.com/markdown/raw") .post(RequestBody.create(mediaType, file)) .build(); okHttpClient.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { System.out.println("onFailure: " + e.getMessage()); e.printStackTrace(); } @Override public void onResponse(Call call, Response res) throws IOException { System.out.println(res.protocol() + " " +res.code() + " " + res.message()); Headers headers = res.headers(); for (int i = 0; i < headers.size(); i++) { System.out.println(headers.name(i) + ":" + headers.value(i)); } System.out.println("onResponse: " + res.body().string()); } }); } /** * 测试 okHttp3 同步请求 POST File * @return */ @Test public void okHttp3SyncPostFileReqTest(){ MediaType mediaType = MediaType.parse("text/x-markdown; charset=utf-8"); File file = new File("test.md"); Request request = new Request.Builder() .url("https://api.github.com/markdown/raw") .post(RequestBody.create(mediaType, file)) .build(); Response res = null; try { res = okHttpClient.newCall(request).execute(); System.out.println(res.protocol() + " " +res.code() + " " + res.message()); Headers headers = res.headers(); for (int i = 0; i < headers.size(); i++) { System.out.println(headers.name(i) + ":" + headers.value(i)); } System.out.println("onResponse: " + res.body().string()); } catch (IOException e) { System.out.println("onFailure: " + e.getMessage()); e.printStackTrace(); } } }
package com.uchain.storage; import com.uchain.core.consensus.TwoTuple; import java.io.IOException; import java.util.List; import java.util.Map; public interface Storage<Key, Value> { boolean containsKey(Key key); Value get(Key key); boolean set(Key key, Value value,Batch batch); boolean delete(Key key, Batch batch); // boolean batchWrite(); void newSession(); void commit(Integer revision); void commit(); void rollBack(); void close(); List<Map.Entry<byte[], byte[]>> find(byte[] prefix); Batch batchWrite(); Map.Entry<byte[], byte[]> last() throws IOException; Integer revision(); List<Integer> uncommitted(); }
package treinamentojava.ordenacao.lambda; import java.util.ArrayList; import java.util.List; public class ExecutaOrdenacaoLambda { public static void main(String[] args) { List<Item> itens = new ArrayList<>(); itens.add(new Item(3)); itens.add(new Item(1)); itens.add(new Item(5)); itens.add(new Item(2)); itens.add(new Item(4)); System.out.println("Lista não ordenada:"); // Expressão lambda itens.forEach(item -> System.out.println(item.getNumero())); // Ordenando com lambda itens.sort((Item item1, Item item2) -> { if (item1.getNumero() < item2.getNumero()) { return -1; } else if (item1.getNumero() > item2.getNumero()) { return 1; } else { return 0; } }); System.out.println("Lista ordenada:"); // Expressão lambda itens.forEach(item -> System.out.println(item.getNumero())); } }
package org.kevoree.registry.repository; import org.kevoree.registry.domain.DeployUnit; import org.kevoree.registry.domain.TypeDefinition; import org.springframework.data.jpa.repository.*; import java.util.Optional; import java.util.Set; /** * Spring Data JPA repository for the DeployUnit entity. */ public interface DeployUnitRepository extends JpaRepository<DeployUnit, Long> { @Query("select d from DeployUnit d where d.typeDefinition in (select t from TypeDefinition t where t.namespace.name = ?1)") Set<DeployUnit> findByNamespace(String name); @Query("select d from DeployUnit d where d.typeDefinition in (select t from TypeDefinition t where t.namespace.name = ?1 and t.name = ?2)") Set<DeployUnit> findByNamespaceAndTypeDefinition(String nsName, String tdefName); @Query("select d from DeployUnit d where d.typeDefinition in (select t from TypeDefinition t where t.namespace.name = ?1 and t.name = ?2 and t.version = ?3)") Set<DeployUnit> findByNamespaceAndTypeDefinitionAndTypeDefinitionVersion( String nsName, String tdefName, Long tdefVersion); @Query("select d from DeployUnit d where d.typeDefinition in (select t from TypeDefinition t where t.namespace.name = ?1 and t.name = ?2 and t.version = ?3) and d.platform = ?4") Set<DeployUnit> findByNamespaceAndTypeDefinitionAndTypeDefinitionVersionAndPlatform( String nsName, String tdefName, Long tdefVersion, String platform); @Query("select d from DeployUnit d where d.typeDefinition in (select t from TypeDefinition t where t.namespace.name = ?1 and t.name = ?2 and t.version = ?3) and d.name = ?4") Set<DeployUnit> findByNamespaceAndTypeDefinitionAndTypeDefinitionVersionAndName( String nsName, String tdefName, Long tdefVersion, String name); @Query("select d from DeployUnit d where d.typeDefinition in (select t from TypeDefinition t where t.namespace.name = ?1 and t.name = ?2 and t.version = ?3) and d.name = ?4 and d.version = ?5") Set<DeployUnit> findByNamespaceAndTypeDefinitionAndTypeDefinitionVersionAndNameAndVersion( String nsName, String tdefName, Long tdefVersion, String name, String version); @Query("select d from DeployUnit d where d.typeDefinition in (select t from TypeDefinition t where t.namespace.name = ?1 and t.name = ?2 and t.version = ?3) and d.name = ?4 and d.version = ?5 and d.platform = ?6") Optional<DeployUnit> findOneByNamespaceAndTypeDefinitionAndTypeDefinitionVersionAndNameAndVersionAndPlatform( String nsName, String tdefName, Long tdefVersion, String name, String version, String platform); @Query("select distinct d.platform from DeployUnit d where d.typeDefinition.id = ?1") Set<String> findDistinctPlatformByTypeDefinitionId(Long id); Set<DeployUnit> findByTypeDefinitionId(Long id); }
package com.solucionfactible.dev; /** * isValid allow 4 or 6 digit PIN codes and PIN codes cannot contain anything but exactly 4 digits or exactly 6 digits. * If the function is passed a valid PIN string, return true, else return false. * * @author developer */ public class ValidatePIN { public static boolean isValid(String pin) { int len = pin.length(); // Validamos que todos los caracteres sean digitos for (int i = 0; i < len; i++) { if (!Character.isDigit(pin.charAt(i))) { return false; } } // Validamos que la longitud sea 4 o 6 y retornamos la respuesta return (len == 4 || len == 6); } }
package pkg8queen; public class Main { static int tempreture; static Board board; public static void main(String[] args) { java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new Board().setVisible(true); } }); } public static State simulatedAnnealing(State initial) { State current = null; if (initial == null) { current = randomGenerateInitialState(); }else{ current = initial ; } int T, randomSuccessorIndex, deltaE; double possibility; State next; System.out.println(current + "\nh : " + current.getH()); for (int t = 1; t < 100000; t++) { // Goal reached if (current.getH() == 0) { return current; } T = schedule(t); if (T == 0) { return current; } current.generateSuccessors(); randomSuccessorIndex = (int) (Math.random() * current.getSuccessors().size()); next = current.getSuccessors().get(randomSuccessorIndex); deltaE = current.getH() - next.getH(); if (deltaE > 0) { current = next; } else { possibility = Math.random(); if (possibility < Math.pow(Math.E, (double) (deltaE / T))) { current = next; } } } return current; } public static State randomGenerateInitialState() { return new State(); } // a mapping from t to T public static int schedule(int t) { return t; } }
package LeetCode; import java.util.Arrays; public class IncreasingTripletSubsequence { public static void main(String[] args) { IncreasingTripletSubsequence solution = new IncreasingTripletSubsequence(); System.out.println(solution.increasingTriplet(new int[] {2,1,5,0,4,6})); } /* * Given an unsorted array return whether an increasing subsequence of length 3 exists or not in the array. Formally the function should: Return true if there exists i, j, k such that arr[i] < arr[j] < arr[k] given 0 ≤ i < j < k ≤ n-1 else return false. Note: Your algorithm should run in O(n) time complexity and O(1) space complexity. * * Example 1: Input: [1,2,3,4,5] Output: true Example 2: Input: [5,4,3,2,1] Output: false * */ public boolean increasingTriplet(int[] nums) { return false; } }
/* * Copyright (c) 2021. <plusmancn@gmail.com> All Rights Reversed. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. */ package cn.plusman.poc.httpclient.agent; import lombok.extern.slf4j.Slf4j; import java.lang.instrument.Instrumentation; /** * @author plusman * @since 2021/3/3 10:56 AM */ @Slf4j public class SimpleHttpClientAgent { public static void premain(String agentArgs, Instrumentation ins) { log.info("In premain method"); ins.addTransformer(new BasicHttpResponseInterceptor(), true); } public static void agentmain(String agentArgs, Instrumentation inst) { log.info("In agentmain method"); } }
package forms; import core.ActionManager; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.collections.FXCollections; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.ListCell; import javafx.scene.control.ListView; import javafx.scene.control.TextField; import javafx.scene.layout.GridPane; import javafx.stage.Stage; import javafx.util.Callback; import storage.DatabaseManager; import users.*; import users.userTypes.Guest; import users.userTypes.Librarian; import users.userTypes.UserType; import java.net.URL; public class AuthorizationForm { private Stage stage; private Scene scene; private DatabaseManager databaseManager; @FXML private Button loginAsStudentBtn; @FXML private Button loginAsGuestBtn; @FXML private ListView<UserCard> usersListView; @FXML private TextField dateField; /** * Initialization and run new scene on the primary stage */ public void startForm(Stage primaryStage) throws Exception{ this.stage = primaryStage; UserType.load(); databaseManager = new DatabaseManager("library"); sceneInitialization(); stage.setScene(scene); stage.show(); } /** * Initialization scene and scene's elements */ private void sceneInitialization() throws Exception { URL url = getClass().getResource("FXMLFiles/AuthorizationForm.fxml"); System.err.println(url); FXMLLoader loader = new FXMLLoader(url); loader.setController(this); GridPane root = loader.load(); this.scene = new Scene(root,700,700); loginAsStudentBtn = (Button) scene.lookup("#loginAsStudentBtn"); loginAsGuestBtn = (Button) scene.lookup("#loginAsGuestBtn"); usersListView = (ListView<UserCard>) scene.lookup("#usersListView"); dateField = (TextField) scene.lookup("#dateField"); dateField.textProperty().addListener(new ChangeListener<String>() { @Override public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) { if(!newValue.matches("(3[0-1]|[12][0-9]|0[1-9])\\/(1[0-2]|0[1-9])")){ loginAsStudentBtn.setDisable(true); loginAsGuestBtn.setDisable(true); }else { loginAsStudentBtn.setDisable(false); loginAsGuestBtn.setDisable(false); } } }); usersListView.setItems(FXCollections.observableArrayList(databaseManager.getAllUsers())); usersListView.setCellFactory(new Callback<ListView<UserCard>, ListCell<UserCard>>() { public ListCell<UserCard> call(ListView<UserCard> userCardListView) { return new ListCell<UserCard>() { @Override protected void updateItem(UserCard user, boolean flag) { super.updateItem(user, flag); if (user != null) { setText(user.userType.getClass().getName().replace("users.userTypes.", "") + " " + user.name + " " + user.surname); } } }; } }); } /** * Click on button "loginAsStudent" event * If textField has right format(will be stronger filter soon) then the student log in(temp: from one account) /* */ @FXML public void loginAsStudent() throws Exception{ int day = 1; int month = 1; if(dateField.getText() != null){ String str = dateField.getText(); if(str.length() == 5 && str.charAt(0) >= '0' && str.charAt(0) <= '9' && str.charAt(1) >= '0' && str.charAt(1) <= '9' && str.charAt(3) >= '0' && str.charAt(3) <= '9' && str.charAt(4) >= '0' && str.charAt(4) <= '9'){ day = Integer.parseInt(str.substring(0,2)); month = Integer.parseInt(str.substring(3,5)); if(month > 12 || month < 1) month = 12; if(day > 31 || day<1) day = 28; } } if(selectedUser != null ){ MainForm mainForm = new MainForm(); Session session = new Session(databaseManager.getUserCard(selectedUser.getId()).userType, day,month); session.userCard = databaseManager.getUserCard(selectedUser.getId()); mainForm.startForm(stage, session, databaseManager, databaseManager.actionManager); } } private UserCard selectedUser; @FXML public void selectUserOnListView() throws Exception{ int i = usersListView.getSelectionModel().getSelectedIndex(); if( i > -1){ selectedUser = databaseManager.getUserCard(databaseManager.getUserCardsID()[i]); } } /** /* Click on button "loginAsGuest" event */ @FXML public void loginAsGuest()throws Exception{ int day = 1; int month = 1; if(dateField.getText() != null){ String str = dateField.getText(); if(str.length() == 5 && str.charAt(0) >= '0' && str.charAt(0) <= '9' && str.charAt(1) >= '0' && str.charAt(1) <= '9' && str.charAt(3) >= '0' && str.charAt(3) <= '9' && str.charAt(4) >= '0' && str.charAt(4) <= '9'){ day = Integer.parseInt(str.substring(0,2)); month = Integer.parseInt(str.substring(3,5)); if(month > 12 || month < 1) month = 1; if(day > 31 || day<1) day = 1; } } MainForm mainForm = new MainForm(); mainForm.startForm(stage,new Session(new Guest(), day,month), databaseManager, databaseManager.actionManager); } }
package com.spring.professional.exam.tutorial.module03.question27.configuration; import javax.persistence.EntityManagerFactory; import javax.sql.DataSource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.jpa.repository.config.EnableJpaRepositories; import org.springframework.orm.jpa.JpaTransactionManager; import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; import org.springframework.transaction.PlatformTransactionManager; @Configuration @EnableJpaRepositories(basePackages = "com.spring.professional.exam.tutorial.module03.question27.dao", entityManagerFactoryRef = "", transactionManagerRef = "") public class JpaConfiguration { @Bean @Autowired public LocalContainerEntityManagerFactoryBean entityManagerFactory(DataSource dataSource) { LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean(); em.setDataSource(dataSource); em.setPackagesToScan("com.spring.professional.exam.tutorial.module03.question27.ds"); em.setJpaVendorAdapter(new HibernateJpaVendorAdapter()); return em; } @Bean public PlatformTransactionManager transactionManager(EntityManagerFactory emf) { return new JpaTransactionManager(emf); } }
package com.asm.view.controller; import com.asm.entities.client.Client; import com.asm.interactors.ClientInteractor; import com.asm.interactors.ClientPersistence; import com.asm.persistance.node.client.ClientNodePersistence; import com.asm.view.controller.properties.AutomobileProperty; import com.asm.view.controller.properties.ClientProperty; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.geometry.HPos; import javafx.geometry.Insets; import javafx.scene.Parent; import javafx.scene.control.*; import javafx.scene.input.MouseEvent; import javafx.scene.layout.*; import javafx.scene.text.Font; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Optional; public class EditClientsController { private ScrollPane mainScrollPane; private ClientProperty clientProperty; private List<GridPane> automobileGridPane; private int carCountState = 0; private List<AutomobileProperty> carsAdded; private ClientInteractor interactor; @FXML private VBox newClientVBox; @FXML private TextField newNameInput; @FXML private TextField newSurnameInput; @FXML private TextField newEmailInput; @FXML private TextField newPhoneInput; @FXML private TextField newAddressInput; public EditClientsController() { this.interactor = new ClientInteractor(); this.automobileGridPane = new ArrayList<>(); } public void updateChangesForClientOnClick(MouseEvent mouseEvent) { saveClient(); goToHomeView(); } public void cancelNewClientFormOnClick(MouseEvent mouseEvent) { Alert alert = new Alert(Alert.AlertType.CONFIRMATION); alert.setTitle("Cancelar Registro de Cliente"); alert.setHeaderText("¿Estás seguro que deseas cancelar el registro del cliente?"); alert.setContentText("Todos los cambios se borraran"); Optional<ButtonType> result = alert.showAndWait(); if (result.get() == ButtonType.OK){ goToHomeView(); } } private void goToHomeView() { FXMLLoader loader = new FXMLLoader(getClass().getResource("/fxml/clients.fxml")); try { Parent root = loader.load(); ClientsController clientsController = loader.getController(); clientsController.init(mainScrollPane); this.mainScrollPane.setContent(root); } catch (IOException e) { e.printStackTrace(); } mainScrollPane.setFitToWidth(true); } public GridPane generateAutomobileGridPanel(int state, AutomobileProperty ap) { String carGridId = "car-grid-"+ Integer.toString(state); GridPane carGridPane = new GridPane(); carGridPane.setGridLinesVisible(false); carGridPane.setPadding(new Insets(20, 0,20,0)); ColumnConstraints column1 = new ColumnConstraints(); ColumnConstraints column2 = new ColumnConstraints(); ColumnConstraints column3 = new ColumnConstraints(); RowConstraints row1 = new RowConstraints(); RowConstraints row2 = new RowConstraints(); RowConstraints row3 = new RowConstraints(); RowConstraints row4 = new RowConstraints(); RowConstraints row5 = new RowConstraints(); RowConstraints row6 = new RowConstraints(); RowConstraints row7 = new RowConstraints(); column1.setHgrow(Priority.ALWAYS); column2.setHgrow(Priority.ALWAYS); column2.setMaxWidth(100); column3.setHgrow(Priority.ALWAYS); column3.setHalignment(HPos.LEFT); carGridPane.getRowConstraints().addAll(row1, row2, row3, row4, row5, row6, row7); carGridPane.getColumnConstraints().addAll(column1, column2, column3); Label labelForTitle = new Label("Registro Automovil "+ carCountState +":"); labelForTitle.setFont(new Font(24)); labelForTitle.setPadding(new Insets(5, 5,5,2)); Label labelForBrnad = new Label("Marca:"); labelForBrnad.setPadding(new Insets(5, 5,5,2)); Label labelForModel = new Label("Modelo:"); labelForModel.setPadding(new Insets(5, 5,5,0)); Label labelForLicencePlate = new Label("Placas:"); labelForLicencePlate.setPadding(new Insets(5, 5,5,2)); Label labelForKilometers = new Label("Kilometraje:"); labelForKilometers.setPadding(new Insets(5, 5,5,0)); Label labelForYears = new Label("Año:"); labelForYears.setPadding(new Insets(5, 5,5,2)); Label labelForSerialNumber = new Label("N. Serie:"); labelForSerialNumber.setPadding(new Insets(5, 5,5,0)); TextField brandInput = new TextField(); TextField modelInput = new TextField(); TextField licencePalteInput = new TextField(); TextField kilometersInput = new TextField(); TextField yearInput = new TextField(); TextField serialNumberInput = new TextField(); brandInput.setText(ap.getBrand()); modelInput.setText(ap.getModel()); licencePalteInput.setText(ap.getLicencePlate()); kilometersInput.setText(ap.getCurrentKm()); yearInput.setText(ap.getYear()); serialNumberInput.setText(ap.getSerialNumber()); Button cancelButton = new Button("Remover Automóvil"); cancelButton.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { System.out.println("Remove cars clicked!" + ""); } }); HBox carFormControls = new HBox(); carFormControls.setPadding(new Insets(10, 0,10,0)); carFormControls.getChildren().addAll(cancelButton); // Column 1 carGridPane.add(labelForTitle, 0, 0); carGridPane.add(labelForBrnad, 0, 1); carGridPane.add(brandInput, 0, 2); carGridPane.add(labelForLicencePlate, 0, 3); carGridPane.add(licencePalteInput, 0, 4); carGridPane.add(labelForYears, 0, 5); carGridPane.add(yearInput, 0, 6); carGridPane.add(carFormControls, 0, 7); //Column 3 carGridPane.add(labelForModel, 2, 1); carGridPane.add(modelInput, 2, 2); carGridPane.add(labelForSerialNumber, 2, 3); carGridPane.add(serialNumberInput, 2, 4); carGridPane.add(labelForKilometers, 2, 5); carGridPane.add(kilometersInput, 2, 6); return carGridPane; } public void saveClient() { Client client = new Client(); client.setName(this.newNameInput.getText()); client.setSurnames(this.newSurnameInput.getText()); client.setPhone(this.newPhoneInput.getText()); client.setEmail(this.newEmailInput.getText()); client.setAddress(this.newAddressInput.getText()); interactor.updateClient(client); } public void init(ScrollPane mainScrollPane, ClientProperty clientProperty) { this.mainScrollPane = mainScrollPane; this.clientProperty = clientProperty; this.newNameInput.setText(clientProperty.getFirstName()); this.newEmailInput.setText(clientProperty.getFirstName()); this.newSurnameInput.setText(clientProperty.getSurnames()); this.newEmailInput.setText(clientProperty.getEmail()); this.newAddressInput.setText(clientProperty.getAddress()); this.newPhoneInput.setText(clientProperty.getPhoneNumber()); List<AutomobileProperty> cars = clientProperty.getCars(); for (int i = 0; i < cars.size(); i++) { AutomobileProperty automobileProperty = cars.get(i); GridPane automobilepane = generateAutomobileGridPanel(i,automobileProperty); newClientVBox.getChildren().add(automobilepane); automobileGridPane.add(automobilepane); } System.out.println(newClientVBox.getChildren()); } public String updfateClient() { String updatedCleint = ""; return updatedCleint; } }
package View; import Model.MazeCharacter; import javafx.scene.canvas.Canvas; import javafx.scene.canvas.GraphicsContext; import javafx.scene.control.Alert; import javafx.scene.image.Image; import java.io.FileInputStream; import java.io.FileNotFoundException; public class MazeDisplayer extends Canvas { private MazeCharacter mainCharacter = new MazeCharacter("Crash_",0,0);; private MazeCharacter secondCharacter = new MazeCharacter("Crash_Second_",0,0);; private char[][] mazeCharArr; private int[][] mazeSolutionArr; private int goalPositionRow; private int goalPositionColumn; private int rowMazeSize; private int colMazeSize; private boolean hint; private int oldSecondCharacterRow; private int oldSecondCharacterCol; private int oldMainCharacterRow; private int oldMainCharacterCol; private Image solutionImage; private Image goalImage; private Image secondCharacterImage; private Image mainCharacterImage; private Image backGroundImage; private Image wallImage; private void setImages(){ String mainCharacterName = mainCharacter.getCharacterName(); try { solutionImage = new Image(new FileInputStream("Resources/Images/" + mainCharacterName + "showSolution.png")); secondCharacterImage = new Image(new FileInputStream("Resources/Characters/" + mainCharacterName + "Second_" + secondCharacter.getCharacterDirection() + ".png")); mainCharacterImage = new Image(new FileInputStream("Resources/Characters/" + mainCharacterName + mainCharacter.getCharacterDirection() + ".png")); goalImage = new Image(new FileInputStream("Resources/Characters/" + mainCharacterName + "goal.png")); wallImage = new Image(new FileInputStream("Resources/Images/" + mainCharacterName + "wall.png")); backGroundImage = new Image(new FileInputStream("Resources/Images/" + mainCharacterName + "backGround.png")); }catch(Exception e){ e.printStackTrace(); } } private void setCharactersImage(){ String mainCharacterName = mainCharacter.getCharacterName(); try { secondCharacterImage = new Image(new FileInputStream("Resources/Characters/" + mainCharacterName + "Second_" + secondCharacter.getCharacterDirection() + ".png")); mainCharacterImage = new Image(new FileInputStream("Resources/Characters/" + mainCharacterName + mainCharacter.getCharacterDirection() + ".png")); }catch(Exception e){ e.printStackTrace(); } } public int getMainCharacterRow() { return mainCharacter.getCharacterRow(); } public int getMainCharacterColumn() { return mainCharacter.getCharacterCol(); } public int getSecondCharacterRow() { return secondCharacter.getCharacterRow(); } public int getSecondCharacterColumn() { return secondCharacter.getCharacterCol(); } public void setMaze(char[][] maze){ mazeCharArr = maze; rowMazeSize = maze.length; colMazeSize = maze[0].length; } public void setGoalPosition(int row, int column){ goalPositionRow = row; goalPositionColumn = column; } public void setSecondCharacterDirection(String direction){ secondCharacter.setCharacterDirection(direction); } public void setSecondCharacterPosition(int row, int column) { oldSecondCharacterRow = secondCharacter.getCharacterRow(); oldSecondCharacterCol = secondCharacter.getCharacterCol(); secondCharacter.setCharacterRow(row); secondCharacter.setCharacterCol(column); } public void setMainCharacterDirection(String direction){ mainCharacter.setCharacterDirection(direction); } public void setMainCharacterPosition(int row, int column) { oldMainCharacterRow = mainCharacter.getCharacterRow(); oldMainCharacterCol = mainCharacter.getCharacterCol(); mainCharacter.setCharacterRow(row); mainCharacter.setCharacterCol(column); } public void setMainCharacterName(String name){ mainCharacter.setCharacterName(name); setImages(); } public void setSecondCharacterName(String name){ secondCharacter.setCharacterName(name); } public void redraw() { if (mazeCharArr != null) { this.setHeight(this.getScene().getHeight() - 80 /*ToolBar*/ - 105 /*LowerBar*/ ); this.setWidth( this.getScene().getWidth() * 19/20); double canvasHeight = getHeight(); double canvasWidth = getWidth(); double maxSize = Math.max(colMazeSize,rowMazeSize); double cellHeight = canvasHeight / maxSize; double cellWidth = canvasWidth / maxSize; double startRow = (canvasHeight/2 - (cellHeight * rowMazeSize / 2)) / cellHeight; double startCol = (canvasWidth/2 - (cellWidth * colMazeSize / 2)) / cellWidth; try { GraphicsContext graphicsContext2D = getGraphicsContext2D(); graphicsContext2D.clearRect(0, 0, getWidth(), getHeight()); //Clears the canvas //Draw Maze drawMazeIteration(); //draw solution drawSolutionGeneric(solutionImage); //Draw Character graphicsContext2D.drawImage(mainCharacterImage, (startCol + getMainCharacterColumn()) * cellWidth, (startRow + getMainCharacterRow()) * cellHeight, cellWidth, cellHeight); if (!(secondCharacter.getCharacterRow() == mainCharacter.getCharacterRow() && secondCharacter.getCharacterCol() == mainCharacter.getCharacterCol())) { //Image secondCharacterImage = new Image(new FileInputStream("Resources/Characters/" + secondCharacterName + secondCharacter.getCharacterDirection() + ".png")); graphicsContext2D.drawImage(secondCharacterImage, (startCol + getSecondCharacterColumn()) * cellWidth, (startRow + getSecondCharacterRow()) * cellHeight, cellWidth, cellHeight); } if (mainCharacter.getCharacterRow() != goalPositionRow || mainCharacter.getCharacterCol() != goalPositionColumn) { graphicsContext2D.drawImage(goalImage, (startCol + goalPositionColumn) * cellWidth, (startRow + goalPositionRow) * cellHeight, cellWidth, cellHeight); } } catch (Exception e) { e.printStackTrace(); } } } private void drawMazeIteration(){ if (mazeCharArr != null) { try { this.setHeight(this.getScene().getHeight() - 80 /*ToolBar*/ - 105 /*LowerBar*/ ); this.setWidth( this.getScene().getWidth() * 19/20); double canvasHeight = getHeight(); double canvasWidth = getWidth(); double maxSize = Math.max(colMazeSize, rowMazeSize); double cellHeight = canvasHeight / maxSize; double cellWidth = canvasWidth / maxSize; double startRow = (canvasHeight / 2 - (cellHeight * rowMazeSize / 2)) / cellHeight; double startCol = (canvasWidth / 2 - (cellWidth * colMazeSize / 2)) / cellWidth; GraphicsContext graphicsContext2D = getGraphicsContext2D(); graphicsContext2D.clearRect(0, 0, getWidth(), getHeight()); //Clears the canvas for (int i = 0; i < rowMazeSize; i++) { for (int j = 0; j < colMazeSize; j++) { graphicsContext2D.drawImage(backGroundImage, (startCol + j) * cellWidth, (startRow + i) * cellHeight, cellWidth, cellHeight); if (mazeCharArr[i][j] == '1') { graphicsContext2D.drawImage(wallImage, (startCol + j) * cellWidth, (startRow + i) * cellHeight, cellWidth, cellHeight); } else if (mazeCharArr[i][j] == 'E') { setGoalPosition(i, j); } } } }catch (Exception e) { e.printStackTrace(); } } } public void redrawMaze(){ if (mazeCharArr != null) { hint = false; mazeSolutionArr = null; drawMazeIteration(); } } public void redrawCharacter(){ try { setCharactersImage(); double canvasHeight = getHeight(); double canvasWidth = getWidth(); double maxSize = Math.max(colMazeSize, rowMazeSize); double cellHeight = canvasHeight / maxSize; double cellWidth = canvasWidth / maxSize; double startRow = (canvasHeight / 2 - (cellHeight * rowMazeSize / 2)) / cellHeight; double startCol = (canvasWidth / 2 - (cellWidth * colMazeSize / 2)) / cellWidth; hint = false; GraphicsContext graphicsContext2D = getGraphicsContext2D(); if(mazeCharArr[oldMainCharacterRow][oldMainCharacterCol] != '1') graphicsContext2D.drawImage(backGroundImage, (startCol + oldMainCharacterCol) * cellWidth, (startRow + oldMainCharacterRow) * cellHeight, cellWidth, cellHeight); if(mazeCharArr[oldSecondCharacterRow][oldSecondCharacterCol] != '1') graphicsContext2D.drawImage(backGroundImage, (startCol + oldSecondCharacterCol) * cellWidth, (startRow + oldSecondCharacterRow) * cellHeight, cellWidth, cellHeight); graphicsContext2D.drawImage(backGroundImage, (startCol + getMainCharacterColumn()) * cellWidth, (startRow + getMainCharacterRow()) * cellHeight, cellWidth, cellHeight); graphicsContext2D.drawImage(mainCharacterImage, (startCol + getMainCharacterColumn()) * cellWidth, (startRow + getMainCharacterRow()) * cellHeight, cellWidth, cellHeight); if (!(secondCharacter.getCharacterRow() == mainCharacter.getCharacterRow() && secondCharacter.getCharacterCol() == mainCharacter.getCharacterCol())) { graphicsContext2D.drawImage(backGroundImage, (startCol + getSecondCharacterColumn()) * cellWidth, (startRow + getSecondCharacterRow()) * cellHeight, cellWidth, cellHeight); graphicsContext2D.drawImage(secondCharacterImage, (startCol + getSecondCharacterColumn()) * cellWidth, (startRow + getSecondCharacterRow()) * cellHeight, cellWidth, cellHeight); } if (mainCharacter.getCharacterRow() != goalPositionRow || mainCharacter.getCharacterCol() != goalPositionColumn) { graphicsContext2D.drawImage(backGroundImage, (startCol + goalPositionColumn) * cellWidth, (startRow + goalPositionRow) * cellHeight, cellWidth, cellHeight); graphicsContext2D.drawImage(goalImage, (startCol + goalPositionColumn) * cellWidth, (startRow + goalPositionRow) * cellHeight, cellWidth, cellHeight); } }catch (Exception e) { e.printStackTrace(); } } private void drawSolutionGeneric(Image image){ double canvasHeight = getHeight(); double canvasWidth = getWidth(); double maxSize = Math.max(colMazeSize, rowMazeSize); double cellHeight = canvasHeight / maxSize; double cellWidth = canvasWidth / maxSize; double startRow = (canvasHeight / 2 - (cellHeight * rowMazeSize / 2)) / cellHeight; double startCol = (canvasWidth / 2 - (cellWidth * colMazeSize / 2)) / cellWidth; GraphicsContext graphicsContext2D = getGraphicsContext2D(); int solLength = 0; if(mazeSolutionArr != null){ solLength = mazeSolutionArr.length - 1; if (hint) { if (solLength != 1 && (int) Math.sqrt(solLength) == 1) solLength = 2; else solLength = (int) Math.sqrt(solLength); } } for(int i = 1; mazeSolutionArr != null && i < solLength ;i++){ if(!(secondCharacter.getCharacterRow() == mazeSolutionArr[i][0] && secondCharacter.getCharacterCol() == mazeSolutionArr[i][1])) graphicsContext2D.drawImage(image, (startCol + mazeSolutionArr[i][1]) * cellWidth, (startRow + mazeSolutionArr[i][0]) * cellHeight, cellWidth, cellHeight); } } public void redrawSolution(){ try{ drawSolutionGeneric(solutionImage); }catch (Exception e) { e.printStackTrace(); } } public void redrawCancelSolution(){ try{ drawSolutionGeneric(backGroundImage); mazeSolutionArr = null; }catch (Exception e) { e.printStackTrace(); } } public void setMazeSolutionArr(int[][] mazeSolutionArr) { this.mazeSolutionArr = mazeSolutionArr; } public void setHint(boolean hint){ this.hint = hint; } }
package some.runtime; import com.fasterxml.jackson.databind.ObjectMapper; import java.util.Arrays; import some.runtime.model.UserTemplate; public class HelloWorld { public static void main(String[] args) throws InterruptedException { ObjectMapper objectMapper = new ObjectMapper(); System.out.println("Hello" + Arrays.toString(args)); System.out.println("args length=" + args.length); UserTemplate nike = UserTemplate.of("nike"); System.out.println(nike); System.out.println(System.getenv("my_env")); Thread.sleep(60 * 10000); } }
/* * Origin of the benchmark: * repo: https://github.com/diffblue/cbmc.git * branch: develop * directory: regression/cbmc-java/fcmpx_dcmpx1 * The benchmark was taken from the repo: 24 January 2018 */ class Main { public static void main(String[] args) { float f = 2.5f; assert f == 2.5f; assert f < 3.0f; assert f > 2.0f; double d = 2.5; assert d == 2.5; assert d < 3.0; assert d > 2.0; } }
package cn.diffpi.resource.asthma.user.model; import cn.dreampie.orm.Model; import cn.dreampie.orm.annotation.Table; @Table(name = "asthma_person", cached = true) public class AsthmaPerson extends Model<AsthmaPerson>{ public final static AsthmaPerson dao = new AsthmaPerson(); }
public class Board { Sign[][] board = new Sign[3][3]; public void showBoard() { for (int i = 0; i < board.length; i++) { System.out.print("\n----------------------\n"); for (int j = 0; j < board[i].length; j++){ if(j == 0) { System.out.print(" "); } if (board[i][j] != Sign.EMPTY) { System.out.print("| "+board[i][j]+" |"); } else { System.out.print("| |"); } } } System.out.print("\n----------------------\n"); } public int getLenght() { return board.length; } public void resetBoard() { for (int i = 0; i < board.length; i++) { for (int j = 0; j < board[i].length; j++) board[i][j] = Sign.EMPTY; } } public void setField(int x, int y, Sign fieldState) { board[y][x] = fieldState; } public void setBoard(Sign[][] board) { this.board = board; } public boolean isFieldEmpty(int x, int y){ if(board[y][x].equals(Sign.EMPTY)) return true; return false; } public Sign[][] getBoard() { return board; } }
package com.appspot.smartshop.mock; import java.sql.Date; import com.appspot.smartshop.dom.ProductInfo; public class MockProductInfo { public static ProductInfo getInstance(){ ProductInfo productInfo = new ProductInfo(); productInfo.name = "Thịt chó"; productInfo.price = 50000; productInfo.is_vat = true; productInfo.quantity = 2; productInfo.date_post = new Date(2010, 12, 12); productInfo.warranty = "Việt Nam"; productInfo.origin = "USA"; productInfo.address = "268 Lý Thường Kiệt P7 Q10 HCM"; return productInfo; } }
package com.hfad.quiz; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.widget.EditText; import android.widget.Toast; public class TelaInicialActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_tela_inicial); } public void jogar(View view){ EditText etNomeJogador = (EditText) findViewById(R.id.et_nome_jogador); if(etNomeJogador.getText().toString().isEmpty()){ Toast toast = Toast. makeText(this, "É necessário inserir um nome",Toast.LENGTH_SHORT); toast.show(); }else{ String nomeJogador = etNomeJogador.getText().toString(); Intent intentPerguntas = new Intent(this, PerguntasActivity.class); intentPerguntas.putExtra("nomeJogador", nomeJogador); startActivity(intentPerguntas); } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu items for use in the action bar MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.menu_main, menu); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle item selection switch (item.getItemId()) { case R.id.sobre: Intent intentSobre = new Intent(this, SobreActivity.class); startActivity(intentSobre); return true; default: return super.onOptionsItemSelected(item); } } }
package portfolio.sda.comunication; import java.io.IOException; import java.net.DatagramPacket; import java.net.InetAddress; import java.net.MulticastSocket; /** * * @author Gilvanei */ public class MulticastReceiver { private static final int PORT = 8888; private final MulticastSocket socket; public MulticastReceiver(InetAddress address) throws IOException { this.socket = new MulticastSocket(PORT); this.socket.joinGroup(address); //this.player = player; } public void run() { byte[] inBuffer = new byte[256]; DatagramPacket packet = new DatagramPacket(inBuffer, inBuffer.length); String message; while (true) { try { this.socket.receive(packet); message = new String(inBuffer, 0, packet.getLength()); System.out.println(message); MulticastCommunication mc = new MulticastCommunication(); mc.checarProtocolo(message); } catch (IOException ex) { } } } }
package com.sepnotican.stargame.screen; import com.badlogic.gdx.graphics.g2d.TextureAtlas; import com.sepnotican.stargame.base.Sprite; import com.sepnotican.stargame.sprites.Star; import java.util.List; public class ScreenUtils { private static final int STARS_COUNT = 256; public static void createStars(List<Sprite> sprites, TextureAtlas commonAtlas) { for (int i = 0; i < STARS_COUNT; i++) { sprites.add(new Star(commonAtlas)); } } }
// https://leetcode.com/problems/reverse-bits/ // #bit-manipulation public class Solution { // you need treat n as an unsigned value public int reverseBits(int n) { int res = 0; for (int i = 0; i < 32; i++) { res <<= 1; int end = n & 1; res = res | end; n >>= 1; } return res; } // // you need treat n as an unsigned value // public int reverseBits(int n) { // int mask = 1 << 31; // int res = 0; // for (int i = 0; i <= 31; i++) { // // System.out.println(Integer.toBinaryString(n)); // if ((n & 1) > 0) { // res |= mask; // } // n >>= 1; // mask >>= 1; // // System.out.println(Integer.toBinaryString(res)); // System.out.println(Integer.toBinaryString(mask)); // // System.out.println("nn"); // } // return res; // } }
package com.s1mple.service; import com.s1mple.entity.Admin; import com.s1mple.entity.PageInfo; import java.util.List; /** * @author s1mple * @create 2020/4/6-16:34 */ public interface AdminService { /** * 通过账号和密码查询用户 * @param admin * @return */ public Admin findAdmin(Admin admin); /** * 找到所有所有数据 * @return */ public List<Admin> getAll(); /** * 分页查询 * @param a_username * @param a_describe * @param a_id * @param pageIndex * @param pageSize * @return */ public PageInfo<Admin> findPageInfo(String a_username, String a_describe, Integer a_id, Integer pageIndex, Integer pageSize); /** * 添加管理员信息 * @param admin * @return */ public int addAdmin(Admin admin); /** * 删除管理员信息 * @param a_id * @return */ public int deleteAdmin(Integer a_id); /** * 修改管理员信息 * @param admin * @return */ public int updateAdmin(Admin admin); public Admin findAdminById(Integer a_id); }
package com.worldchip.bbpawphonechat.task; import java.io.IOException; import java.util.List; import android.content.Context; import com.worldchip.bbpawphonechat.comments.MyComment; import com.worldchip.bbpawphonechat.comments.MyJsonParserUtil; import com.worldchip.bbpawphonechat.db.UserDao; import com.worldchip.bbpawphonechat.entity.User; import com.worldchip.bbpawphonechat.net.HttpUtils; public class MyRunable implements Runnable{ private int i; private List<User> contacts; private Context mContext; private UserDao userDao; private boolean mIsHead; public MyRunable(int index, List<User> contacts, Context context, boolean isHead) { this.i = index; this.contacts = contacts; mContext = context; userDao = new UserDao(mContext); mIsHead = isHead; } @Override public void run() { if(mIsHead){ updataHeadUrl(); }else{ updataNickName(); } } private void updataHeadUrl(){ String headUlr = MyComment.GET_MY_HEAD_URL+ "&username="+contacts.get(i).getUsername(); try { String result = HttpUtils.getRequest(headUlr,mContext); String resultUrl = ""; if(result != null){ resultUrl = MyJsonParserUtil.parserMyheadUrl(result); } User user = contacts.get(i); user.setUsername(contacts.get(i).getUsername()); user.setHeadurl(resultUrl); userDao.updataContactHeadUrl(user, resultUrl); System.out.println(contacts.get(i).getUsername()+"---getheadAddressJson--开始获取好友头像---"+resultUrl); } catch (IOException e) { e.printStackTrace(); } } private void updataNickName(){ String url = MyComment.GET_CONTACT_NICK_NAME+ "&username="+ contacts.get(i).getUsername(); try { String result = HttpUtils.getRequest(url, mContext); User user = contacts.get(i); user.setUsername(contacts.get(i).getUsername()); user.setNick(result); userDao.updataNickName(user, result); System.out.println("---changeContactNickName--开始获取好友昵称---"+result); } catch (IOException e) { e.printStackTrace(); } } }
package com.github.olly.workshop.trafficgen.model; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import java.util.Map; public class Transformation { private final TransformationType type; private final Map<String, String> properties; @JsonCreator public Transformation(@JsonProperty("type") TransformationType type, @JsonProperty("properties") Map<String, String> properties) { this.type = type; this.properties = properties; } public TransformationType getType() { return type; } public Map<String, String> getProperties() { return properties; } }
package com.union.express.web.stowagecore.shipping.model; import org.hibernate.annotations.GenericGenerator; import javax.persistence.*; import java.math.BigDecimal; /** * Created by wq on 2016/8/31. */ @Entity @Table(name = "stowage_shipping") public class Shipping { private String id; private String name; //名称 private String consumingTime; //耗时 private int kilometre; //公里数 private String routeId; //路线id private BigDecimal startPrice; //起步价格 private int sort; //排序 private String remark; //备注 @Id @GeneratedValue(generator = "system-uuid") @GenericGenerator(name = "system-uuid",strategy="uuid") @Column(name = "id",nullable = false,unique = true,length = 32) public String getId() { return id; } public void setId(String id) { this.id = id; } @Column(name = "name",length = 10) public String getName() { return name; } public void setName(String name) { this.name = name; } @Column(name = "consuming_time",length = 30) public String getConsumingTime() { return consumingTime; } public void setConsumingTime(String consumingTime) { this.consumingTime = consumingTime; } @Column(name = "kilometre") public int getKilometre() { return kilometre; } public void setKilometre(int kilometre) { this.kilometre = kilometre; } @Column(name = "route_id",length = 32) public String getRouteId() { return routeId; } public void setRouteId(String routeId) { this.routeId = routeId; } @Column(name = "start_price") public BigDecimal getStartPrice() { return startPrice; } public void setStartPrice(BigDecimal startPrice) { this.startPrice = startPrice; } @Column(name = "sort") public int getSort() { return sort; } public void setSort(int sort) { this.sort = sort; } @Column(name = "remark") public String getRemark() { return remark; } public void setRemark(String remark) { this.remark = remark; } }
package com.nisira.core.entity; import com.nisira.annotation.ClavePrimaria; import com.nisira.annotation.Columna; import com.nisira.annotation.Tabla; import com.google.gson.annotations.SerializedName; import com.thoughtworks.xstream.annotations.XStreamAlias; import java.io.Serializable; import java.util.Date; import java.util.ArrayList; @Tabla(nombre = "CARGOS_PERSONAL") @XStreamAlias("CARGOS_PERSONAL") public class Cargos_personal implements Serializable { @ClavePrimaria @Columna @SerializedName("idempresa") @XStreamAlias("IDEMPRESA") private String idempresa = "" ; @ClavePrimaria @Columna @SerializedName("idcargo") @XStreamAlias("IDCARGO") private String idcargo = "" ; @Columna @SerializedName("descripcion") @XStreamAlias("DESCRIPCION") private String descripcion = "" ; @Columna @SerializedName("idactividad") @XStreamAlias("IDACTIVIDAD") private String idactividad = "" ; @Columna @SerializedName("idlabor") @XStreamAlias("IDLABOR") private String idlabor = "" ; @Columna @SerializedName("sincroniza") @XStreamAlias("SINCRONIZA") private String sincroniza = "" ; @Columna @SerializedName("fechacreacion") @XStreamAlias("FECHACREACION") private Date fechacreacion; @Columna @SerializedName("codalterno") @XStreamAlias("CODALTERNO") private String codalterno = "" ; @Columna @SerializedName("es_guardian") @XStreamAlias("ES_GUARDIAN") private Integer es_guardian; @Columna @SerializedName("es_pers_aereo") @XStreamAlias("ES_PERS_AEREO") private Double es_pers_aereo = 0.00 ; @Columna @SerializedName("cargo_pesquera") @XStreamAlias("CARGO_PESQUERA") private String cargo_pesquera = "" ; @Columna @SerializedName("produccion_pesquera") @XStreamAlias("PRODUCCION_PESQUERA") private Double produccion_pesquera = 0.00 ; @Columna @SerializedName("tipo_trabajo") @XStreamAlias("TIPO_TRABAJO") private String tipo_trabajo = "" ; @Columna @SerializedName("idarea") @XStreamAlias("IDAREA") private String idarea = "" ; @Columna @SerializedName("es_jefedearea") @XStreamAlias("ES_JEFEDEAREA") private Double es_jefedearea = 0.00 ; @Columna @SerializedName("usa_subsector") @XStreamAlias("USA_SUBSECTOR") private Double usa_subsector = 0.00 ; @Columna @SerializedName("tipo_cargo") @XStreamAlias("TIPO_CARGO") private Double tipo_cargo = 0.00 ; @Columna @SerializedName("es_chofer") @XStreamAlias("ES_CHOFER") private Double es_chofer = 0.00 ; /* Sets & Gets */ public void setIdempresa(String idempresa) { this.idempresa = idempresa; } public String getIdempresa() { return this.idempresa; } public void setIdcargo(String idcargo) { this.idcargo = idcargo; } public String getIdcargo() { return this.idcargo; } public void setDescripcion(String descripcion) { this.descripcion = descripcion; } public String getDescripcion() { return this.descripcion; } public void setIdactividad(String idactividad) { this.idactividad = idactividad; } public String getIdactividad() { return this.idactividad; } public void setIdlabor(String idlabor) { this.idlabor = idlabor; } public String getIdlabor() { return this.idlabor; } public void setSincroniza(String sincroniza) { this.sincroniza = sincroniza; } public String getSincroniza() { return this.sincroniza; } public void setFechacreacion(Date fechacreacion) { this.fechacreacion = fechacreacion; } public Date getFechacreacion() { return this.fechacreacion; } public void setCodalterno(String codalterno) { this.codalterno = codalterno; } public String getCodalterno() { return this.codalterno; } public void setEs_guardian(Integer es_guardian) { this.es_guardian = es_guardian; } public Integer getEs_guardian() { return this.es_guardian; } public void setEs_pers_aereo(Double es_pers_aereo) { this.es_pers_aereo = es_pers_aereo; } public Double getEs_pers_aereo() { return this.es_pers_aereo; } public void setCargo_pesquera(String cargo_pesquera) { this.cargo_pesquera = cargo_pesquera; } public String getCargo_pesquera() { return this.cargo_pesquera; } public void setProduccion_pesquera(Double produccion_pesquera) { this.produccion_pesquera = produccion_pesquera; } public Double getProduccion_pesquera() { return this.produccion_pesquera; } public void setTipo_trabajo(String tipo_trabajo) { this.tipo_trabajo = tipo_trabajo; } public String getTipo_trabajo() { return this.tipo_trabajo; } public void setIdarea(String idarea) { this.idarea = idarea; } public String getIdarea() { return this.idarea; } public void setEs_jefedearea(Double es_jefedearea) { this.es_jefedearea = es_jefedearea; } public Double getEs_jefedearea() { return this.es_jefedearea; } public void setUsa_subsector(Double usa_subsector) { this.usa_subsector = usa_subsector; } public Double getUsa_subsector() { return this.usa_subsector; } public void setTipo_cargo(Double tipo_cargo) { this.tipo_cargo = tipo_cargo; } public Double getTipo_cargo() { return this.tipo_cargo; } public Double getEs_chofer() { return es_chofer; } public void setEs_chofer(Double es_chofer) { this.es_chofer = es_chofer; } /* Sets & Gets FK*/ }
package com.khakaton.mafia.implementations; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.io.DataInputStream; import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JSpinner; import javax.swing.SpinnerModel; import javax.swing.SpinnerNumberModel; import javax.swing.SwingUtilities; import javax.swing.UIManager; import org.dyno.visual.swing.layouts.Constraints; import org.dyno.visual.swing.layouts.GroupLayout; import org.dyno.visual.swing.layouts.Leading; //VS4E -- DO NOT REMOVE THIS LINE! public class MafiaServerFrame extends JFrame { private static final long serialVersionUID = 1L; private JButton jButton0; private JSpinner jSpinner0; private JLabel jLabel0; private static final String PREFERRED_LOOK_AND_FEEL = "javax.swing.plaf.metal.MetalLookAndFeel"; public MafiaServerFrame() { initComponents(); } private void initComponents() { setLayout(new GroupLayout()); add(getJButton0(), new Constraints(new Leading(216, 10, 10), new Leading(81, 10, 10))); add(getJLabel0(), new Constraints(new Leading(14, 10, 10), new Leading(86, 12, 12))); add(getJSpinner0(), new Constraints(new Leading(153, 10, 10), new Leading(86, 18, 12, 12))); setSize(320, 240); } private JLabel getJLabel0() { if (jLabel0 == null) { jLabel0 = new JLabel(); jLabel0.setText("Number of players"); } return jLabel0; } private JSpinner getJSpinner0() { if (jSpinner0 == null) { SpinnerModel model = new SpinnerNumberModel(3, 3, 25, 1); jSpinner0 = new JSpinner(model); } return jSpinner0; } private JButton getJButton0() { if (jButton0 == null) { jButton0 = new JButton(); jButton0.setText("Begin"); jButton0.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent event) { try { jButton0MouseMouseClicked(event); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }); } return jButton0; } private static void installLnF() { try { String lnfClassname = PREFERRED_LOOK_AND_FEEL; if (lnfClassname == null) lnfClassname = UIManager.getCrossPlatformLookAndFeelClassName(); UIManager.setLookAndFeel(lnfClassname); } catch (Exception e) { System.err.println("Cannot install " + PREFERRED_LOOK_AND_FEEL + " on this platform:" + e.getMessage()); } } /** * Main entry of the class. * Note: This class is only created so that you can easily preview the result at runtime. * It is not expected to be managed by the designer. * You can modify it as you like. */ public static void main(String[] args) { installLnF(); SwingUtilities.invokeLater(new Runnable() { public void run() { MafiaServerFrame frame = new MafiaServerFrame(); frame.setDefaultCloseOperation(MafiaServerFrame.EXIT_ON_CLOSE); frame.setTitle("MafiaFrame"); frame.getContentPane().setPreferredSize(frame.getSize()); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); } }); } private void jButton0MouseMouseClicked(MouseEvent event) throws IOException { System.out.println("Server started.\n"); ServerSocket ss = new ServerSocket(4444); GroupGameImpl gg = new GroupGameImpl((Integer) jSpinner0.getValue()); while(true) { Socket client = ss.accept(); DataInputStream dis = new DataInputStream(client.getInputStream()); String playername = dis.readUTF(); gg.addPlayer(playername, client); System.out.println("Player added : " + playername); System.out.println(gg.getPlayersCount() + " players connected."); if(gg.getPlayersCount()==gg.getTotalCount()) { gg.start(); System.out.println("Game started."); } } } }
package com.example.apprunner.Organizer.menu1_home.Activity; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import android.app.AlertDialog; import android.app.DatePickerDialog; import android.app.ProgressDialog; import android.content.DialogInterface; import android.content.Intent; import android.graphics.Bitmap; import android.net.Uri; import android.os.Bundle; import android.provider.MediaStore; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.DatePicker; import android.widget.EditText; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.Spinner; import android.widget.TextView; import android.widget.Toast; import com.example.apprunner.Cricketer; import com.example.apprunner.DB.CricketerDB; import com.example.apprunner.DB.EventFormDB; import com.example.apprunner.Login.LoginActivity; import com.example.apprunner.Login.RegisterappActivity; import com.example.apprunner.OrganizerAPI; import com.example.apprunner.R; import com.example.apprunner.ResultQuery; import com.google.android.gms.tasks.OnFailureListener; import com.google.android.gms.tasks.OnSuccessListener; import com.google.android.gms.tasks.Task; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.storage.FirebaseStorage; import com.google.firebase.storage.OnProgressListener; import com.google.firebase.storage.StorageReference; import com.google.firebase.storage.UploadTask; import java.io.IOException; import java.util.ArrayList; import java.util.Calendar; import java.util.List; import java.util.UUID; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; import retrofit2.Retrofit; import retrofit2.converter.gson.GsonConverterFactory; public class MainActivityAddEvent extends AppCompatActivity { TextView date_start,date_end; Button pickDate_start,pickDate_end,buttonsubmit,buttonAdd,addpicture; ImageView imageView; DatePickerDialog.OnDateSetListener setListener; LinearLayout layoutlist; String first_name,last_name,type,ID_E; int id_user; Task<Uri> downloadUri; StorageReference ref; Uri downloadURL; FirebaseAuth mAuth; String photoStringLink; private Uri filePath; private final int PICK_IMAGE_REQUEST = 1; //Firebase FirebaseStorage storage = FirebaseStorage.getInstance(); StorageReference storageReference; List<String> distanceList = new ArrayList<>(); ArrayList<Cricketer> cricketersList = new ArrayList<>(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main_add_event); id_user = getIntent().getExtras().getInt("id_user"); first_name = getIntent().getExtras().getString("first_name"); last_name = getIntent().getExtras().getString("last_name"); type = getIntent().getExtras().getString("type"); id_user = getIntent().getExtras().getInt("id_user"); final MainActivity mainActivity = new MainActivity(); final Retrofit retrofit = new Retrofit.Builder() .baseUrl(mainActivity.url) .addConverterFactory(GsonConverterFactory.create()) .build(); //Firebase Init storage = FirebaseStorage.getInstance(); storageReference = storage.getReference(); date_start = findViewById(R.id.tv_date_start); pickDate_start = findViewById(R.id.btn_pickDate1); Calendar calendar_start = Calendar.getInstance(); final int year1 = calendar_start.get(Calendar.YEAR); final int month1 = calendar_start.get(Calendar.MONTH); final int day1 = calendar_start.get(Calendar.DAY_OF_MONTH); pickDate_start.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { DatePickerDialog datePickerDialog = new DatePickerDialog( MainActivityAddEvent.this, new DatePickerDialog.OnDateSetListener() { @Override public void onDateSet(DatePicker datePicker, int year1, int month1, int day1) { month1 = month1+1; String date = day1 + "/" + month1 + "/" + year1; date_start.setText(date); } },year1,month1,day1); datePickerDialog.show(); } }); date_end = findViewById(R.id.tv_date_end); pickDate_end = findViewById(R.id.btn_pickDate2); Calendar calendar_end = Calendar.getInstance(); final int year2 = calendar_end.get(Calendar.YEAR); final int month2 = calendar_end.get(Calendar.MONTH); final int day2 = calendar_end.get(Calendar.DAY_OF_MONTH); pickDate_end.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { DatePickerDialog datePickerDialog = new DatePickerDialog( MainActivityAddEvent.this, new DatePickerDialog.OnDateSetListener() { @Override public void onDateSet(DatePicker datePicker, int year2, int month2, int day2) { month2 = month2+1; String date = day2 + "/" + month2 + "/" + year2; date_end.setText(date); } },year2,month2,day2); datePickerDialog.show(); } }); //setButtonSubmit buttonsubmit = findViewById(R.id.btnRegEvent); layoutlist = findViewById(R.id.layout_list); buttonAdd = findViewById(R.id.button_add); buttonAdd.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { switch (view.getId()){ case R.id.button_add: addView(); break; case R.id.btnRegEvent: if(checkIfValidAndRead()){ Intent intent = new Intent(MainActivityAddEvent.this, MainActivity.class); Bundle bundle = new Bundle(); bundle.putSerializable("list",cricketersList); intent.putExtras(bundle); startActivity(intent); } } } }); final EditText editorganizer = findViewById(R.id.userEDT); final EditText edittel = findViewById(R.id.telEdt); final EditText editevent = findViewById(R.id.eventEDT); final EditText editproducer = findViewById(R.id.producerEDT); final TextView textdatestart = findViewById(R.id.tv_date_start); final TextView textdateend = findViewById(R.id.tv_date_end); final EditText editobjective = findViewById(R.id.objectiveEDT); final EditText editdetail = findViewById(R.id.detailsEDT); final Spinner spinner_bank = findViewById(R.id.bank_spinner); final EditText editnumbank = findViewById(R.id.numberbank_EDT); buttonsubmit.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { String organizer = editorganizer.getText().toString(); String tel = edittel.getText().toString(); String event = editevent.getText().toString(); String producer = editproducer.getText().toString(); String date_start = textdatestart.getText().toString(); String date_end = textdateend.getText().toString(); String bank = spinner_bank.getSelectedItem().toString(); String num_bank = editnumbank.getText().toString(); String objective = editobjective.getText().toString(); String detail = editdetail.getText().toString(); if (validateAddevent(id_user,organizer ,tel, event, producer, date_start, date_end, bank, num_bank, objective, detail)) { doAddevent(id_user ,editorganizer , edittel ,editevent ,editproducer ,textdatestart ,textdateend, spinner_bank ,editnumbank ,editobjective ,editdetail); } } private boolean validateAddevent(int id_user,String organizer,String tel , String event, String producer, String date_start, String date_end, String bank, String num_bank, String objective, String detail) { if(organizer == null || organizer.trim().length() == 0){ Toast.makeText(MainActivityAddEvent.this,"Organizer is required",Toast.LENGTH_SHORT).show(); return false; } if(event == null || event.trim().length() == 0){ Toast.makeText(MainActivityAddEvent.this, "Event is required", Toast.LENGTH_SHORT).show(); return false; } if(producer == null || producer.trim().length() == 0){ Toast.makeText(MainActivityAddEvent.this,"Producer is required",Toast.LENGTH_SHORT).show(); return false; } if(date_start.equals("dd / mm / yyyy")){ Toast.makeText(MainActivityAddEvent.this, "DateStart is required", Toast.LENGTH_SHORT).show(); return false; } if(date_end.equals("dd / mm / yyyy")){ Toast.makeText(MainActivityAddEvent.this,"DateEnd is required",Toast.LENGTH_SHORT).show(); return false; } if(objective == null || objective.trim().length() == 0){ Toast.makeText(MainActivityAddEvent.this, "Objective is required", Toast.LENGTH_SHORT).show(); return false; } if(detail == null || detail.trim().length() == 0){ Toast.makeText(MainActivityAddEvent.this,"Detail is required",Toast.LENGTH_SHORT).show(); return false; } return true; } private void doAddevent(int id_user, EditText editorganizer, EditText edittel, final EditText editevent, final EditText editproducer, TextView textdatestart, TextView textdateend, Spinner spinner_bank , EditText editnumbank , EditText editobjective, EditText editdetail) { uploadImage(id_user, editorganizer, edittel, editevent, editproducer, textdatestart, textdateend, spinner_bank, editnumbank, editobjective, editdetail); } }); //Int view addpicture = findViewById(R.id.btn_addPicture); imageView = findViewById(R.id.imgView); addpicture.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { chooseImage(); } }); } private void getIDEvent(EditText editevent, EditText editproducer) { final String name_event = editevent.getText().toString(); final String producer = editproducer.getText().toString(); MainActivity mainActivity = new MainActivity(); Retrofit retrofit = new Retrofit.Builder() .baseUrl(mainActivity.url) .addConverterFactory(GsonConverterFactory.create()) .build(); OrganizerAPI services = retrofit.create(OrganizerAPI.class); Call call = services.get_idEvent(name_event,producer); call.enqueue(new Callback() { @Override public void onResponse(Call call, Response response) { ResultQuery resultQuery = (ResultQuery) response.body(); if(response.isSuccessful()){ ID_E = Integer.toString(resultQuery.get_eventID()); //ID_Event = resultQuery.get_eventID(); //Toast.makeText(MainActivityAddEvent.this,ID_E,Toast.LENGTH_LONG).show(); checkIfValidAndRead(); //Toast.makeText(MainActivityAddEvent.this,"Response",Toast.LENGTH_LONG).show(); } } @Override public void onFailure(Call call, Throwable t) { Toast.makeText(MainActivityAddEvent.this,"Fail",Toast.LENGTH_LONG).show(); } }); } private void uploadImage(final int id_user, final EditText editorganizer, final EditText edittel, final EditText editevent, final EditText editproducer, final TextView textdatestart, final TextView textdateend, final Spinner spinner_bank, final EditText editnumbank, final EditText editobjective, final EditText editdetail) { if(filePath == null){ Toast.makeText(MainActivityAddEvent.this, "Empty image", Toast.LENGTH_SHORT).show(); } if(filePath != null) { final ProgressDialog progressDialog = new ProgressDialog(this); progressDialog.setTitle("Uploading...."); progressDialog.show(); //** ชื่อ path ที่ส่งไป firebase ref = storageReference.child("images/" + UUID.randomUUID().toString()); ref.putFile(filePath) .addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() { @Override public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) { downloadUri = taskSnapshot.getStorage().getDownloadUrl(); progressDialog.dismiss(); downloadUri.addOnSuccessListener(new OnSuccessListener<Uri>() { @Override public void onSuccess(Uri uri) { photoStringLink = uri.toString(); Log.i("urlimage", photoStringLink); //Toast.makeText(MainActivityAddEvent.this, photoStringLink, Toast.LENGTH_SHORT).show(); add_event(id_user, photoStringLink, editorganizer, edittel, editevent, editproducer, textdatestart, textdateend, spinner_bank, editnumbank, editobjective, editdetail); } }); } }) .addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { progressDialog.dismiss(); //Toast.makeText(MainActivityAddEvent.this, "Failed " +e.getMessage() ,Toast.LENGTH_SHORT).show(); } }) .addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() { @Override public void onProgress(UploadTask.TaskSnapshot taskSnapshot) { double progress = (100.0*taskSnapshot.getBytesTransferred()/taskSnapshot.getTotalByteCount()); progressDialog.setMessage("Uploaded" +(int)progress+"%"); //Toast.makeText(MainActivityAddEvent.this, Double.toString(progress), Toast.LENGTH_SHORT).show(); } }); } } private void chooseImage() { Intent intent = new Intent(); intent.setType("image/*"); intent.setAction(Intent.ACTION_GET_CONTENT); startActivityForResult(Intent.createChooser(intent,"Select Picture"), PICK_IMAGE_REQUEST); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) { filePath = data.getData(); //Toast.makeText(MainActivityAddEvent.this, filePath.toString(), Toast.LENGTH_SHORT).show(); try{ Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath); imageView.setImageBitmap(bitmap); //Toast.makeText(MainActivityAddEvent.this,bitmap.toString(), Toast.LENGTH_SHORT).show(); } catch (IOException e) { e.printStackTrace(); } } } private boolean checkIfValidAndRead() { cricketersList.clear(); boolean result = true; MainActivity mainActivity = new MainActivity(); Retrofit retrofit = new Retrofit.Builder() .baseUrl(mainActivity.url) .addConverterFactory(GsonConverterFactory.create()) .build(); OrganizerAPI services = retrofit.create(OrganizerAPI.class); for(int i=0;i<layoutlist.getChildCount();i++){ View cricketerView = layoutlist.getChildAt(i); EditText editTextNameDistance = (EditText)cricketerView.findViewById(R.id.edt_namedistance); EditText editTextPrice = (EditText)cricketerView.findViewById(R.id.edt_price); EditText editTextDistance = (EditText)cricketerView.findViewById(R.id.edt_distance); EditText editTextNumRegister = (EditText)cricketerView.findViewById(R.id.edt_num_register); String name_distance = editTextNameDistance.getText().toString(); String edt_price = editTextPrice.getText().toString(); String edt_distance = editTextDistance.getText().toString(); String edt_num_register = editTextNumRegister.getText().toString(); int price = Integer.parseInt(edt_price); int distance = Integer.parseInt(edt_distance); int num_register = Integer.parseInt(edt_num_register); final EditText editevent = findViewById(R.id.eventEDT); Cricketer cricketer = new Cricketer(Integer.parseInt(ID_E), name_distance, distance, price, num_register); if(!editTextNameDistance.getText().toString().equals("")){ cricketer.setNameDistance(editTextNameDistance.getText().toString()); cricketer.setDistance(distance); cricketer.setPrice(price); cricketer.setNum_registere(num_register); }else { result = false; break; } cricketersList.add(cricketer); Call<Cricketer> call = services.insertDistance(new CricketerDB(Integer.parseInt(ID_E),editevent.getText().toString(),cricketersList.get(i).getNameDistance(),cricketersList.get(i).getDistance(),cricketersList.get(i).getPrice(),cricketersList.get(i).getNum_register())); //Toast.makeText(MainActivityAddEvent.this,ID_E + " " +cricketersList.get(i).getPrice() + " "+cricketersList.get(i).getDistance(),Toast.LENGTH_LONG).show(); //Toast.makeText(MainActivityAddEvent.this,cricketersList.get(i).getDistance(),Toast.LENGTH_LONG).show(); call.enqueue(new Callback<Cricketer>() { @Override public void onResponse(Call<Cricketer> call, Response<Cricketer> response) { //Toast.makeText(MainActivityAddEvent.this,"distance success",Toast.LENGTH_LONG).show(); } @Override public void onFailure(Call<Cricketer> call, Throwable t) { } }); } if(cricketersList.size()==0){ result = false; Toast.makeText(this, "Add Cricketers First!", Toast.LENGTH_SHORT).show(); }else if(!result){ Toast.makeText(this, "Enter All Details Correctly!", Toast.LENGTH_SHORT).show(); } return result; } private void addView() { final View cricketerView = getLayoutInflater().inflate(R.layout.row_add_event,null,false); EditText editTextNameDistance = (EditText)cricketerView.findViewById(R.id.edt_namedistance); EditText editTextPrice = (EditText)cricketerView.findViewById(R.id.edt_price); EditText editTextDistance = (EditText)cricketerView.findViewById(R.id.edt_distance); ImageView imageClose = (ImageView)cricketerView.findViewById(R.id.image_remove); imageClose.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { removeView(cricketerView); } }); layoutlist.addView(cricketerView); } private void removeView(View view){ layoutlist.removeView(view); } public void add_event(int id_user, String photoStringLink, EditText editorganizer, EditText edittel, final EditText editevent, final EditText editproducer, TextView textdatestart, TextView textdateend, Spinner spinner_bank, EditText editnumbank, EditText editobjective, EditText editdetail){ MainActivity mainActivity = new MainActivity(); Retrofit retrofit = new Retrofit.Builder() .baseUrl(mainActivity.url) .addConverterFactory(GsonConverterFactory.create()) .build(); OrganizerAPI service = retrofit.create(OrganizerAPI.class); Call<ResultQuery> call = service.insertEvent(new EventFormDB( id_user, photoStringLink, editorganizer.getText().toString(), edittel.getText().toString(), editevent.getText().toString(), editproducer.getText().toString(), textdatestart.getText().toString(), textdateend.getText().toString(), spinner_bank.getSelectedItem().toString(), editnumbank.getText().toString(), editobjective.getText().toString(), editdetail.getText().toString())); call.enqueue(new Callback<ResultQuery>() { @Override public void onResponse(Call<ResultQuery> call, Response<ResultQuery> response) { Toast.makeText(MainActivityAddEvent.this,"ลงทะเบียนเสร็จสิ้นโปรดรอแอดมินอนุมัติ",Toast.LENGTH_LONG).show(); getIDEvent(editevent,editproducer); openMainActiviry(); } @Override public void onFailure(Call<ResultQuery> call, Throwable t) { Toast.makeText(MainActivityAddEvent.this,"ข้อมูลของท่านยังกรอกไม่ครบกรุณาลองใหม่อีกครั้ง",Toast.LENGTH_LONG).show(); } }); } //intent public void openMainActiviry(){ Intent intent = new Intent(MainActivityAddEvent.this, MainActivity.class); intent.putExtra("first_name", first_name); intent.putExtra("last_name", last_name); intent.putExtra("type", type); intent.putExtra("id_user", id_user); startActivity(intent); } }
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scan=new Scanner(System.in); int r=0; int n=scan.nextInt(); while(n!=0) { r=n%10; n/=10; if(r%2==0) { System.out.println("This is even:"+r); } if(r%2!=0) { System.out.println("This is odd:"+r); } } } }
/* * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.core.codec; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import org.reactivestreams.Publisher; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import org.springframework.core.ResolvableType; import org.springframework.core.io.buffer.DataBuffer; import org.springframework.core.io.buffer.DataBufferUtils; import org.springframework.core.io.buffer.LimitedDataBufferList; import org.springframework.core.log.LogFormatUtils; import org.springframework.lang.Nullable; import org.springframework.util.Assert; import org.springframework.util.MimeType; import org.springframework.util.MimeTypeUtils; /** * Decode from a data buffer stream to a {@code String} stream, either splitting * or aggregating incoming data chunks to realign along newlines delimiters * and produce a stream of strings. This is useful for streaming but is also * necessary to ensure that multi-byte characters can be decoded correctly, * avoiding split-character issues. The default delimiters used by default are * {@code \n} and {@code \r\n} but that can be customized. * * @author Sebastien Deleuze * @author Brian Clozel * @author Arjen Poutsma * @author Mark Paluch * @since 5.0 * @see CharSequenceEncoder */ public final class StringDecoder extends AbstractDataBufferDecoder<String> { /** The default charset to use, i.e. "UTF-8". */ public static final Charset DEFAULT_CHARSET = StandardCharsets.UTF_8; /** The default delimiter strings to use, i.e. {@code \r\n} and {@code \n}. */ public static final List<String> DEFAULT_DELIMITERS = List.of("\r\n", "\n"); private final List<String> delimiters; private final boolean stripDelimiter; private Charset defaultCharset = DEFAULT_CHARSET; private final ConcurrentMap<Charset, byte[][]> delimitersCache = new ConcurrentHashMap<>(); private StringDecoder(List<String> delimiters, boolean stripDelimiter, MimeType... mimeTypes) { super(mimeTypes); Assert.notEmpty(delimiters, "'delimiters' must not be empty"); this.delimiters = new ArrayList<>(delimiters); this.stripDelimiter = stripDelimiter; } /** * Set the default character set to fall back on if the MimeType does not specify any. * <p>By default this is {@code UTF-8}. * @param defaultCharset the charset to fall back on * @since 5.2.9 */ public void setDefaultCharset(Charset defaultCharset) { this.defaultCharset = defaultCharset; } /** * Return the configured {@link #setDefaultCharset(Charset) defaultCharset}. * @since 5.2.9 */ public Charset getDefaultCharset() { return this.defaultCharset; } @Override public boolean canDecode(ResolvableType elementType, @Nullable MimeType mimeType) { return (elementType.resolve() == String.class && super.canDecode(elementType, mimeType)); } @Override public Flux<String> decode(Publisher<DataBuffer> input, ResolvableType elementType, @Nullable MimeType mimeType, @Nullable Map<String, Object> hints) { byte[][] delimiterBytes = getDelimiterBytes(mimeType); LimitedDataBufferList chunks = new LimitedDataBufferList(getMaxInMemorySize()); DataBufferUtils.Matcher matcher = DataBufferUtils.matcher(delimiterBytes); return Flux.from(input) .concatMapIterable(buffer -> processDataBuffer(buffer, matcher, chunks)) .concatWith(Mono.defer(() -> { if (chunks.isEmpty()) { return Mono.empty(); } DataBuffer lastBuffer = chunks.get(0).factory().join(chunks); chunks.clear(); return Mono.just(lastBuffer); })) .doFinally(signalType -> chunks.releaseAndClear()) .doOnDiscard(DataBuffer.class, DataBufferUtils::release) .map(buffer -> decode(buffer, elementType, mimeType, hints)); } private byte[][] getDelimiterBytes(@Nullable MimeType mimeType) { return this.delimitersCache.computeIfAbsent(getCharset(mimeType), charset -> { byte[][] result = new byte[this.delimiters.size()][]; for (int i = 0; i < this.delimiters.size(); i++) { result[i] = this.delimiters.get(i).getBytes(charset); } return result; }); } private Collection<DataBuffer> processDataBuffer( DataBuffer buffer, DataBufferUtils.Matcher matcher, LimitedDataBufferList chunks) { boolean release = true; try { List<DataBuffer> result = null; do { int endIndex = matcher.match(buffer); if (endIndex == -1) { chunks.add(buffer); release = false; break; } DataBuffer split = buffer.split(endIndex + 1); if (result == null) { result = new ArrayList<>(); } int delimiterLength = matcher.delimiter().length; if (chunks.isEmpty()) { if (this.stripDelimiter) { split.writePosition(split.writePosition() - delimiterLength); } result.add(split); } else { chunks.add(split); DataBuffer joined = buffer.factory().join(chunks); if (this.stripDelimiter) { joined.writePosition(joined.writePosition() - delimiterLength); } result.add(joined); chunks.clear(); } } while (buffer.readableByteCount() > 0); return (result != null ? result : Collections.emptyList()); } finally { if (release) { DataBufferUtils.release(buffer); } } } @Override public String decode(DataBuffer dataBuffer, ResolvableType elementType, @Nullable MimeType mimeType, @Nullable Map<String, Object> hints) { Charset charset = getCharset(mimeType); String value = dataBuffer.toString(charset); DataBufferUtils.release(dataBuffer); LogFormatUtils.traceDebug(logger, traceOn -> { String formatted = LogFormatUtils.formatValue(value, !traceOn); return Hints.getLogPrefix(hints) + "Decoded " + formatted; }); return value; } private Charset getCharset(@Nullable MimeType mimeType) { if (mimeType != null && mimeType.getCharset() != null) { return mimeType.getCharset(); } else { return getDefaultCharset(); } } /** * Create a {@code StringDecoder} for {@code "text/plain"}. */ public static StringDecoder textPlainOnly() { return textPlainOnly(DEFAULT_DELIMITERS, true); } /** * Create a {@code StringDecoder} for {@code "text/plain"}. * @param delimiters delimiter strings to use to split the input stream * @param stripDelimiter whether to remove delimiters from the resulting * input strings */ public static StringDecoder textPlainOnly(List<String> delimiters, boolean stripDelimiter) { return new StringDecoder(delimiters, stripDelimiter, new MimeType("text", "plain", DEFAULT_CHARSET)); } /** * Create a {@code StringDecoder} that supports all MIME types. */ public static StringDecoder allMimeTypes() { return allMimeTypes(DEFAULT_DELIMITERS, true); } /** * Create a {@code StringDecoder} that supports all MIME types. * @param delimiters delimiter strings to use to split the input stream * @param stripDelimiter whether to remove delimiters from the resulting * input strings */ public static StringDecoder allMimeTypes(List<String> delimiters, boolean stripDelimiter) { return new StringDecoder(delimiters, stripDelimiter, new MimeType("text", "plain", DEFAULT_CHARSET), MimeTypeUtils.ALL); } }
package com.company; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Scanner; public class Main { private static int amount; private static int time; private static int sort; private static String[] selection = {"Bubble Sort", "Insertion Sort", "Merge Sort", "Quick Sort", "Selection Sort", "Shell Sort", "Cocktail Sort"}; public static void main(String[] args) { // write your code here Main theMain = new Main(); theMain.go(); } private void go() { Scanner in = new Scanner(System.in); boolean run = true; do { boolean isValidNumber=false; do { System.out.println("Choose how many elements (between 3 and 88) you would like to sort:"); amount = in.nextInt(); if (amount < 3 || amount > 88) { System.out.println("Choose again!"); } else { isValidNumber = true; } } while (!isValidNumber); boolean isValidTime = false; do { System.out.println("How long would you like to delay sorting in milliseconds? Pick '0' for no delay, but no " + "more than 5000:"); time = in.nextInt(); if (time < 0 || time > 5000) { System.out.println("Choose again!"); } else { isValidTime = true; } } while (!isValidTime); boolean isValidSort = false; do { System.out.println("Pick your sorting algorithm. Here are your options:"); int option = 1; for (String entry : selection) { System.out.print(option + ". "); System.out.println(entry); option++; } sort = in.nextInt(); if (sort < 1 || sort > 7) { System.out.println("Choose again!"); } else { isValidSort = true; } } while (!isValidSort); List<Integer> theArray = new ArrayList<>(); for (int i = 0; i < amount; i++) { theArray.add(i + 1); } Collections.shuffle(theArray); System.out.println(theArray); System.out.println("This shuffled array with " + amount + " elements will be sorted with " + selection[sort - 1] + " sorting algorithm every " + time + " milliseconds."); try { Thread.sleep(1000); System.out.println("The sort begins in:\n3..."); Thread.sleep(1000); System.out.println("2..."); Thread.sleep(1000); System.out.println("1..."); Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } switch (sort) { case 1: BubbleSort theBubble = new BubbleSort(); theBubble.go(theArray, time); break; case 2: InsertionSort theInsert = new InsertionSort(); theInsert.go(theArray, time); break; case 3: MergeSort theMerge = new MergeSort(); theMerge.go(theArray, time); break; case 4: QuickSort theQuick = new QuickSort(); theQuick.go(theArray, time); break; case 5: SelectionSort theSelect = new SelectionSort(); theSelect.go(theArray, time); break; case 6: ShellSort theShell = new ShellSort(); theShell.go(theArray, time); break; case 7: CocktailSort theCocktail = new CocktailSort(); theCocktail.go(theArray, time); break; } boolean isValidAnswer; do { System.out.println("Sort complete! Try another sort? (y/n)"); in.nextLine(); String answer = in.nextLine(); if (answer.equals("y")) { System.out.println("Let's goooooo!"); run = true; isValidAnswer = true; } else if (answer.equals("n")) { System.out.println("Goodbye!"); run = false; isValidAnswer = true; } else { System.out.println("Not a valid answer!"); isValidAnswer = false; } } while (!isValidAnswer); } while (run); } }
package com.lagardien.ocpviolation; /** * Ijaaz Lagardien * 214167542 * Group 3A * Dr B. Kabaso * Date: 13 March 2016 */ public class GraphicEditor { public void drawShape(Shape s) { if(s.type == 1) { drawRectangle(); } else if(s.type == 2) { drawCircle(); } } public void drawCircle() { System.out.println("This is supposed to be a circle"); } public void drawRectangle() { System.out.println("This is supposed to be a Rectangle"); } }
package it.univr.domain.tajs.original; import static org.junit.Assert.assertEquals; import org.junit.Test; public class TAJSNumericDiff { @Test public void testTAJSNumericUnsignedInt() throws Exception { assertEquals(new TAJSNumbers(TAJSNumbers.UNSIGNED_INT, true).diff(new TAJSNumbers(2)), new TAJSNumbers(TAJSNumbers.UNSIGNED_INT, true)); assertEquals(new TAJSNumbers(TAJSNumbers.UNSIGNED_INT, true).diff(new TAJSNumbers(1.1)), new TAJSNumbers(TAJSNumbers.NOT_UNSIGNED_INT, true)); assertEquals(new TAJSNumbers(TAJSNumbers.UNSIGNED_INT, true).diff(new TAJSNumbers(-2.2)), new TAJSNumbers(TAJSNumbers.NOT_UNSIGNED_INT, true)); assertEquals(new TAJSNumbers(TAJSNumbers.UNSIGNED_INT, true).diff(new TAJSNumbers(TAJSNumbers.UNSIGNED_INT, true)), new TAJSNumbers(TAJSNumbers.UNSIGNED_INT, true)); assertEquals(new TAJSNumbers(TAJSNumbers.UNSIGNED_INT, true).diff(new TAJSNumbers(TAJSNumbers.NOT_UNSIGNED_INT, true)), new TAJSNumbers(TAJSNumbers.NOT_UNSIGNED_INT, true)); assertEquals(new TAJSNumbers(TAJSNumbers.UNSIGNED_INT, true).diff(new TAJSNumbers(TAJSNumbers.TOP, true)), new TAJSNumbers(TAJSNumbers.TOP, true)); assertEquals(new TAJSNumbers(TAJSNumbers.UNSIGNED_INT, true).diff(new TAJSNumbers(TAJSNumbers.BOT, true)), new TAJSNumbers(TAJSNumbers.BOT, true)); } @Test public void testTAJSNumericNotUnsignedInt() throws Exception { assertEquals(new TAJSNumbers(TAJSNumbers.NOT_UNSIGNED_INT, true).diff(new TAJSNumbers(2)), new TAJSNumbers(TAJSNumbers.NOT_UNSIGNED_INT, true)); assertEquals(new TAJSNumbers(TAJSNumbers.NOT_UNSIGNED_INT, true).diff(new TAJSNumbers(1.1)), new TAJSNumbers(TAJSNumbers.TOP, true)); assertEquals(new TAJSNumbers(TAJSNumbers.NOT_UNSIGNED_INT, true).diff(new TAJSNumbers(-2.2)), new TAJSNumbers(TAJSNumbers.TOP, true)); assertEquals(new TAJSNumbers(TAJSNumbers.NOT_UNSIGNED_INT, true).diff(new TAJSNumbers(TAJSNumbers.UNSIGNED_INT, true)), new TAJSNumbers(TAJSNumbers.NOT_UNSIGNED_INT, true)); assertEquals(new TAJSNumbers(TAJSNumbers.NOT_UNSIGNED_INT, true).diff(new TAJSNumbers(TAJSNumbers.NOT_UNSIGNED_INT, true)), new TAJSNumbers(TAJSNumbers.TOP, true)); assertEquals(new TAJSNumbers(TAJSNumbers.NOT_UNSIGNED_INT, true).diff(new TAJSNumbers(TAJSNumbers.TOP, true)), new TAJSNumbers(TAJSNumbers.TOP, true)); assertEquals(new TAJSNumbers(TAJSNumbers.NOT_UNSIGNED_INT, true).diff(new TAJSNumbers(TAJSNumbers.BOT, true)), new TAJSNumbers(TAJSNumbers.BOT, true)); } @Test public void testTAJSNumericTop() throws Exception { assertEquals(new TAJSNumbers(TAJSNumbers.TOP, true).diff(new TAJSNumbers(2)), new TAJSNumbers(TAJSNumbers.TOP, true)); assertEquals(new TAJSNumbers(TAJSNumbers.TOP, true).diff(new TAJSNumbers(1.1)), new TAJSNumbers(TAJSNumbers.TOP, true)); assertEquals(new TAJSNumbers(TAJSNumbers.TOP, true).diff(new TAJSNumbers(-2.2)), new TAJSNumbers(TAJSNumbers.TOP, true)); assertEquals(new TAJSNumbers(TAJSNumbers.TOP, true).diff(new TAJSNumbers(TAJSNumbers.UNSIGNED_INT, true)), new TAJSNumbers(TAJSNumbers.TOP, true)); assertEquals(new TAJSNumbers(TAJSNumbers.TOP, true).diff(new TAJSNumbers(TAJSNumbers.NOT_UNSIGNED_INT, true)), new TAJSNumbers(TAJSNumbers.TOP, true)); assertEquals(new TAJSNumbers(TAJSNumbers.TOP, true).diff(new TAJSNumbers(TAJSNumbers.TOP, true)), new TAJSNumbers(TAJSNumbers.TOP, true)); assertEquals(new TAJSNumbers(TAJSNumbers.TOP, true).diff(new TAJSNumbers(TAJSNumbers.BOT, true)), new TAJSNumbers(TAJSNumbers.BOT, true)); } }
package Problem_16197; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.LinkedList; import java.util.Queue; public class Main { static int N, M; static char[][] arr; static boolean[][][][] isvisited; static int[][] coins = new int[2][2]; static int[] dx = { 0, 0, -1, 1 }; static int[] dy = { -1, 1, 0, 0 }; public static void bfs() { Queue<int[]> q = new LinkedList<>(); q.add(new int[] { coins[0][0], coins[0][1], coins[1][0], coins[1][1] }); isvisited[coins[0][0]][coins[0][1]][coins[1][0]][coins[1][1]] = true; int cnt = 0; while (!q.isEmpty() && cnt < 10) { cnt++; int size = q.size(); for (int i = 0; i < size; i++) { int[] data = q.poll(); for(int k = 0; k<4;k++) { int da = data[0] + dx[k]; int db = data[1] + dy[k]; int dc = data[2] + dx[k]; int dd = data[3] + dy[k]; int out_coin = 0; if(da < 0 || db < 0 || da >= N || db >= M) out_coin++; if(dc < 0 || dd < 0 || dc >= N || dd >= M) out_coin++; if(out_coin == 2) continue; // 두 코인 다 나간경우, X if(out_coin == 1) { // 코인 1개만 나간 경우, 정답 System.out.println(cnt); return; } // 두코인이 이동한 장소가 벽인 경우, 해당없음 if(arr[da][db] =='#' && arr[dc][dd] =='#') continue; // 코인 하나의 이동한 장소가 벽인 경우, 그 코인의 위치를 다시 바꿈ㄴ if(arr[da][db] =='#') { da -= dx[k]; db -= dy[k]; } else if(arr[dc][dd] =='#') { dc -= dx[k]; dd -= dy[k]; } if(da == dc && db == dd) continue; if(isvisited[da][db][dc][dd]) continue; q.add(new int[] {da,db,dc,dd}); isvisited[da][db][dc][dd] = true; } } } System.out.println("-1"); return; } public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String bf = br.readLine(); N = Integer.parseInt(bf.split(" ")[0]); M = Integer.parseInt(bf.split(" ")[1]); arr = new char[N][M]; isvisited = new boolean[N][M][N][M]; int idx = 0; for (int i = 0; i < N; i++) { bf = br.readLine(); for (int j = 0; j < M; j++) { arr[i][j] = bf.charAt(j); if (bf.charAt(j) == 'o') { coins[idx][0] = i; coins[idx++][1] = j; arr[i][j] = '.'; } } } bfs(); } }
package com.application.swplanetsapi.domain.repository; import com.application.swplanetsapi.domain.model.Planet; import org.springframework.data.mongodb.repository.MongoRepository; import java.util.Optional; public interface PlanetRepository extends MongoRepository<Planet, String> { Optional<Planet> findByName(String planetName); }