file_id
stringlengths
5
9
content
stringlengths
24
16.1k
repo
stringlengths
8
84
path
stringlengths
7
167
token_length
int64
18
3.48k
original_comment
stringlengths
5
2.57k
comment_type
stringclasses
2 values
detected_lang
stringclasses
1 value
masked_comment
stringlengths
11
16.1k
excluded
bool
1 class
file-tokens-Qwen/Qwen2-7B
int64
14
3.27k
comment-tokens-Qwen/Qwen2-7B
int64
2
1.74k
file-tokens-bigcode/starcoder2-7b
int64
18
3.48k
comment-tokens-bigcode/starcoder2-7b
int64
2
2.11k
file-tokens-google/codegemma-7b
int64
14
3.57k
comment-tokens-google/codegemma-7b
int64
2
1.75k
file-tokens-ibm-granite/granite-8b-code-base
int64
18
3.48k
comment-tokens-ibm-granite/granite-8b-code-base
int64
2
2.11k
file-tokens-meta-llama/CodeLlama-7b-hf
int64
31
3.93k
comment-tokens-meta-llama/CodeLlama-7b-hf
int64
4
2.71k
excluded-based-on-tokenizer-Qwen/Qwen2-7B
bool
2 classes
excluded-based-on-tokenizer-bigcode/starcoder2-7b
bool
2 classes
excluded-based-on-tokenizer-google/codegemma-7b
bool
2 classes
excluded-based-on-tokenizer-ibm-granite/granite-8b-code-base
bool
2 classes
excluded-based-on-tokenizer-meta-llama/CodeLlama-7b-hf
bool
2 classes
include-for-inference
bool
2 classes
53801_3
package abstractfactory; import abstractfactory.clothesfactory.clothes.Pants; import abstractfactory.clothesfactory.clothes.Shirt; import abstractfactory.clothesfactory.factory.BusinessClothesFactory; import abstractfactory.clothesfactory.factory.ClothesFactory; import abstractfactory.clothesfactory.factory.FashionClothesFactory; /** * 为了参加一些聚会,肯定会有多套衣服。比如说有商务装(成套,一系列具体产品)、时尚装(成套,一系列具体产品), * 甚至对于一个家庭来说,可能有商务女装、商务男装、时尚女装、时尚男装,这些也都是成套的,即一系列具体产品。 * 假设一种情况,在您的家中,某一个衣柜(具体工厂)只能存放某一种这样的衣服(成套,一系列具体产品), * 每次拿这种成套的衣服时也自然要从这个衣柜中取出了。 * 用 OOP 的思想去理解,所有的衣柜(具体工厂)都是衣柜类的(抽象工厂)某一个, * 而每一件成套的衣服又包括具体的上衣(某一具体产品),裤子(某一具体产品), * 这些具体的上衣其实也都是上衣(抽象产品),具体的裤子也都是裤子(另一个抽象产品)。 * * @author Real * Date: 2022/12/5 0:11 */ public class ClothesFactoryPattern { public static void main(String[] args) { // 生成商务装工厂 ClothesFactory businessClothesFactory = new BusinessClothesFactory(); // 从商务装工厂中生成上衣和裤子 Shirt businessShirt = businessClothesFactory.createShirt(); Pants businessPants = businessClothesFactory.createPants(); // 显示商务装 businessShirt.display(); businessPants.display(); // 生成时尚装工厂 ClothesFactory fashionClothesFactory = new FashionClothesFactory(); // 从时尚装工厂中生成上衣和裤子 Shirt fashionShirt = fashionClothesFactory.createShirt(); Pants fashionPants = fashionClothesFactory.createPants(); // 显示时尚装 fashionShirt.display(); fashionPants.display(); } }
RealBeBetter/design-pattern
src/abstractfactory/ClothesFactoryPattern.java
607
// 显示商务装
line_comment
zh-cn
package abstractfactory; import abstractfactory.clothesfactory.clothes.Pants; import abstractfactory.clothesfactory.clothes.Shirt; import abstractfactory.clothesfactory.factory.BusinessClothesFactory; import abstractfactory.clothesfactory.factory.ClothesFactory; import abstractfactory.clothesfactory.factory.FashionClothesFactory; /** * 为了参加一些聚会,肯定会有多套衣服。比如说有商务装(成套,一系列具体产品)、时尚装(成套,一系列具体产品), * 甚至对于一个家庭来说,可能有商务女装、商务男装、时尚女装、时尚男装,这些也都是成套的,即一系列具体产品。 * 假设一种情况,在您的家中,某一个衣柜(具体工厂)只能存放某一种这样的衣服(成套,一系列具体产品), * 每次拿这种成套的衣服时也自然要从这个衣柜中取出了。 * 用 OOP 的思想去理解,所有的衣柜(具体工厂)都是衣柜类的(抽象工厂)某一个, * 而每一件成套的衣服又包括具体的上衣(某一具体产品),裤子(某一具体产品), * 这些具体的上衣其实也都是上衣(抽象产品),具体的裤子也都是裤子(另一个抽象产品)。 * * @author Real * Date: 2022/12/5 0:11 */ public class ClothesFactoryPattern { public static void main(String[] args) { // 生成商务装工厂 ClothesFactory businessClothesFactory = new BusinessClothesFactory(); // 从商务装工厂中生成上衣和裤子 Shirt businessShirt = businessClothesFactory.createShirt(); Pants businessPants = businessClothesFactory.createPants(); // 显示 <SUF> businessShirt.display(); businessPants.display(); // 生成时尚装工厂 ClothesFactory fashionClothesFactory = new FashionClothesFactory(); // 从时尚装工厂中生成上衣和裤子 Shirt fashionShirt = fashionClothesFactory.createShirt(); Pants fashionPants = fashionClothesFactory.createPants(); // 显示时尚装 fashionShirt.display(); fashionPants.display(); } }
false
487
5
607
6
497
4
607
6
859
7
false
false
false
false
false
true
18072_6
import java.awt.*; import java.awt.event.*; //(c) 2020 Little Xian. All rights Reserved. /** * 创建于2018年7月7日 * 初次完成于2018年7月30日 * 最后完成于2020年1月30日 */ public class GreedSnake { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub new Window(); } } @SuppressWarnings("serial") class NewPanel extends Panel implements KeyListener,Runnable { Button Snk[]; boolean op=true; //输出 boolean t=true; //开始和结束 public static int X=0; //分数 int f[]; //食物 int Face=0; //方向 int x=0,y=0; //蛇的位置 static int fx,fy; //食物的位置 public static int v=15; //速度 Thread thread; NewPanel() { setLayout(null); f=new int [100000]; Snk=new Button[100000]; thread=new Thread(this); for(int n=0;n<100000;n++) { f[n]=(int)(Math.random()*100); } fx=(int)(f[0]*0.1)*60; fy=(int)(f[0]%10)*45; for(int m=0;m<100000;m++) { Snk[m]=new Button(); } add(Snk[0]); Snk[0].setBackground(Color.black); Snk[0].setBounds(0,0,15,15); //基本单位 Snk[0].addKeyListener(this); setBackground(Color.gray); //可以改背景颜色 } public void run() { while(t) //控制 { if(Face==0) { try { x+=v; Snk[0].setLocation(x, y); if(x==fx&&y==fy) { X++;fx=(int)(f[X]*0.1)*60;fy=(int)(f[X]%10)*45; Snk[X].setBounds(Snk[X-1].getBounds()); repaint();add(Snk[X]); } Thread.sleep(100); } catch(Exception e){} } else if(Face==1) { try { x-=v; Snk[0].setLocation(x, y); if(x==fx&&y==fy) { X++;fx=(int)(f[X]*0.1)*60;fy=(int)(f[X]%10)*45; Snk[X].setBounds(Snk[X-1].getBounds()); repaint(); add(Snk[X]); } Thread.sleep(100); } catch(Exception e){} } else if(Face==2) { try { y-=v; Snk[0].setLocation(x, y); if(x==fx&&y==fy) { X++;fx=(int)(f[X]*0.1)*60;fy=(int)(f[X]%10)*45; Snk[X].setBounds(Snk[X-1].getBounds()); repaint(); add(Snk[X]); } Thread.sleep(100); } catch(Exception e){} } else if(Face==3) { try { y+=v; Snk[0].setLocation(x, y); if(x==fx&&y==fy) { X++;fx=(int)(f[X]*0.1)*60;fy=(int)(f[X]%10)*45; Snk[X].setBounds(Snk[X-1].getBounds()); repaint(); add(Snk[X]); } Thread.sleep(100); } catch(Exception e){} } int Y=X; while(Y>1) //尾巴 { if(Snk[Y].getBounds().x==Snk[0].getBounds().x&&Snk[Y].getBounds().y==Snk[0].getBounds().y) { t=false; op=false; repaint(); } Y--; } if(x<0||x>=this.getWidth()||y<0||y>=this.getHeight()) //墙 { t=false; op=false; repaint(); } int Z=X; while(Z>0) { Snk[Z].setBounds(Snk[Z-1].getBounds()); Z--; } if(X==100000) //可以改胜利条件 { t=false; op=true; repaint(); } } } public void keyPressed(KeyEvent e) //键盘输入 { if(e.getKeyCode()==KeyEvent.VK_RIGHT) { if(Face!=1) Face=0; } else if(e.getKeyCode()==KeyEvent.VK_LEFT) { if(Face!=0) Face=1; } else if(e.getKeyCode()==KeyEvent.VK_UP) { if(Face!=3) Face=2; } else if(e.getKeyCode()==KeyEvent.VK_DOWN) { if(Face!=2) Face=3; } } public void keyTyped(KeyEvent e) { } public void keyReleased(KeyEvent e) { } public void paint(Graphics g) { int x1=this.getWidth()-1; int y1=this.getHeight()-1; g.setColor(Color.white); //可以改食物颜色 g.drawString("Your Score:"+X, 325, 50); g.drawString("Tips:After starting,please press the Tab key to select the snake,then control the snake by direction keys.", 100, 20); g.drawString("Jul 30,2018.", 1290, 640); g.drawString("Jan 30,2020.", 1287, 650); g.drawString("(c) 2020 Little Xian. All rights Reserved.", 1150, 660); g.setColor(Color.orange); g.fillOval(fx, fy, 15, 15); g.drawRect(0, 0, x1, y1); g.drawString(" +++++++++++++++++ ",1000,240); g.drawString(" +++++++++++++++++++++ ",1000,250); g.drawString(" +++++ +++++++++ +++++ ",1000,260); g.drawString("++++++ +++++++++ ++++++",1000,270); g.drawString("+++++++++++++++++++++++++",1000,280); g.drawString("+++++++++++++++++++++++++",1000,290); g.drawString("+++++ +++++++++++ +++++",1000,300); g.drawString("++++++ +++++++++ ++++++",1000,310); g.drawString("+++++++ +++++++ +++++++",1000,320); g.drawString(" +++++++ +++++++ ",1000,330); g.drawString(" +++++++++++++++++++++ ",1000,340); g.drawString(" +++++++++++++++++ ",1000,350); g.drawString("Thanks for testing me!",1025,400); if(t==false&&op==false) g.drawString("Game Over!Your score:"+X, 300, 200); if(t==false&&op==true) g.drawString("You win!", 300, 200); } } @SuppressWarnings("serial") class Window extends Frame implements ActionListener { NewPanel my; Button btn; Button ys; Panel panel; int count=0; Window() { super("GreedSnake"+" --By Little Xian"); my=new NewPanel(); btn=new Button("Start Game"); panel=new Panel(); btn.addActionListener(this); panel.add(btn); ys=new Button("I'm No Use"); panel.add(ys); add(panel,BorderLayout.NORTH); add(my,BorderLayout.CENTER); setBounds(50,50,750,597); //更改面板大小 setVisible(true); validate(); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); } protected void methodys() { // TODO 自动生成的方法存根 } public void actionPerformed(ActionEvent e) { if(e.getSource()==btn) { try { my.thread.start(); my.validate(); } catch(Exception ee){} } } } //这是我的第一个Java实例,或许也是最后一个了。 //2023.8.15 令人感叹XD
RealLittleXian/CodingasaNoob
Java/GreedSnake.java
2,419
//食物的位置
line_comment
zh-cn
import java.awt.*; import java.awt.event.*; //(c) 2020 Little Xian. All rights Reserved. /** * 创建于2018年7月7日 * 初次完成于2018年7月30日 * 最后完成于2020年1月30日 */ public class GreedSnake { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub new Window(); } } @SuppressWarnings("serial") class NewPanel extends Panel implements KeyListener,Runnable { Button Snk[]; boolean op=true; //输出 boolean t=true; //开始和结束 public static int X=0; //分数 int f[]; //食物 int Face=0; //方向 int x=0,y=0; //蛇的位置 static int fx,fy; //食物 <SUF> public static int v=15; //速度 Thread thread; NewPanel() { setLayout(null); f=new int [100000]; Snk=new Button[100000]; thread=new Thread(this); for(int n=0;n<100000;n++) { f[n]=(int)(Math.random()*100); } fx=(int)(f[0]*0.1)*60; fy=(int)(f[0]%10)*45; for(int m=0;m<100000;m++) { Snk[m]=new Button(); } add(Snk[0]); Snk[0].setBackground(Color.black); Snk[0].setBounds(0,0,15,15); //基本单位 Snk[0].addKeyListener(this); setBackground(Color.gray); //可以改背景颜色 } public void run() { while(t) //控制 { if(Face==0) { try { x+=v; Snk[0].setLocation(x, y); if(x==fx&&y==fy) { X++;fx=(int)(f[X]*0.1)*60;fy=(int)(f[X]%10)*45; Snk[X].setBounds(Snk[X-1].getBounds()); repaint();add(Snk[X]); } Thread.sleep(100); } catch(Exception e){} } else if(Face==1) { try { x-=v; Snk[0].setLocation(x, y); if(x==fx&&y==fy) { X++;fx=(int)(f[X]*0.1)*60;fy=(int)(f[X]%10)*45; Snk[X].setBounds(Snk[X-1].getBounds()); repaint(); add(Snk[X]); } Thread.sleep(100); } catch(Exception e){} } else if(Face==2) { try { y-=v; Snk[0].setLocation(x, y); if(x==fx&&y==fy) { X++;fx=(int)(f[X]*0.1)*60;fy=(int)(f[X]%10)*45; Snk[X].setBounds(Snk[X-1].getBounds()); repaint(); add(Snk[X]); } Thread.sleep(100); } catch(Exception e){} } else if(Face==3) { try { y+=v; Snk[0].setLocation(x, y); if(x==fx&&y==fy) { X++;fx=(int)(f[X]*0.1)*60;fy=(int)(f[X]%10)*45; Snk[X].setBounds(Snk[X-1].getBounds()); repaint(); add(Snk[X]); } Thread.sleep(100); } catch(Exception e){} } int Y=X; while(Y>1) //尾巴 { if(Snk[Y].getBounds().x==Snk[0].getBounds().x&&Snk[Y].getBounds().y==Snk[0].getBounds().y) { t=false; op=false; repaint(); } Y--; } if(x<0||x>=this.getWidth()||y<0||y>=this.getHeight()) //墙 { t=false; op=false; repaint(); } int Z=X; while(Z>0) { Snk[Z].setBounds(Snk[Z-1].getBounds()); Z--; } if(X==100000) //可以改胜利条件 { t=false; op=true; repaint(); } } } public void keyPressed(KeyEvent e) //键盘输入 { if(e.getKeyCode()==KeyEvent.VK_RIGHT) { if(Face!=1) Face=0; } else if(e.getKeyCode()==KeyEvent.VK_LEFT) { if(Face!=0) Face=1; } else if(e.getKeyCode()==KeyEvent.VK_UP) { if(Face!=3) Face=2; } else if(e.getKeyCode()==KeyEvent.VK_DOWN) { if(Face!=2) Face=3; } } public void keyTyped(KeyEvent e) { } public void keyReleased(KeyEvent e) { } public void paint(Graphics g) { int x1=this.getWidth()-1; int y1=this.getHeight()-1; g.setColor(Color.white); //可以改食物颜色 g.drawString("Your Score:"+X, 325, 50); g.drawString("Tips:After starting,please press the Tab key to select the snake,then control the snake by direction keys.", 100, 20); g.drawString("Jul 30,2018.", 1290, 640); g.drawString("Jan 30,2020.", 1287, 650); g.drawString("(c) 2020 Little Xian. All rights Reserved.", 1150, 660); g.setColor(Color.orange); g.fillOval(fx, fy, 15, 15); g.drawRect(0, 0, x1, y1); g.drawString(" +++++++++++++++++ ",1000,240); g.drawString(" +++++++++++++++++++++ ",1000,250); g.drawString(" +++++ +++++++++ +++++ ",1000,260); g.drawString("++++++ +++++++++ ++++++",1000,270); g.drawString("+++++++++++++++++++++++++",1000,280); g.drawString("+++++++++++++++++++++++++",1000,290); g.drawString("+++++ +++++++++++ +++++",1000,300); g.drawString("++++++ +++++++++ ++++++",1000,310); g.drawString("+++++++ +++++++ +++++++",1000,320); g.drawString(" +++++++ +++++++ ",1000,330); g.drawString(" +++++++++++++++++++++ ",1000,340); g.drawString(" +++++++++++++++++ ",1000,350); g.drawString("Thanks for testing me!",1025,400); if(t==false&&op==false) g.drawString("Game Over!Your score:"+X, 300, 200); if(t==false&&op==true) g.drawString("You win!", 300, 200); } } @SuppressWarnings("serial") class Window extends Frame implements ActionListener { NewPanel my; Button btn; Button ys; Panel panel; int count=0; Window() { super("GreedSnake"+" --By Little Xian"); my=new NewPanel(); btn=new Button("Start Game"); panel=new Panel(); btn.addActionListener(this); panel.add(btn); ys=new Button("I'm No Use"); panel.add(ys); add(panel,BorderLayout.NORTH); add(my,BorderLayout.CENTER); setBounds(50,50,750,597); //更改面板大小 setVisible(true); validate(); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); } protected void methodys() { // TODO 自动生成的方法存根 } public void actionPerformed(ActionEvent e) { if(e.getSource()==btn) { try { my.thread.start(); my.validate(); } catch(Exception ee){} } } } //这是我的第一个Java实例,或许也是最后一个了。 //2023.8.15 令人感叹XD
false
1,971
3
2,419
5
2,323
3
2,419
5
2,719
6
false
false
false
false
false
true
58515_7
package com.momo.wifidemo.utils; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.Iterator; import java.util.List; import android.content.Context; import android.net.wifi.ScanResult; import android.net.wifi.WifiConfiguration; import android.net.wifi.WifiInfo; import android.net.wifi.WifiManager; /** * WIFI管理类 * @author Real.Mo * */ public class WifiAdmin { private static WifiAdmin wifiAdmin = null; private List<WifiConfiguration> mWifiConfiguration; //无线网络配置信息类集合(网络连接列表) private List<ScanResult> mWifiList; //检测到接入点信息类 集合 //描述任何Wifi连接状态 private WifiInfo mWifiInfo; WifiManager.WifiLock mWifilock; //能够阻止wifi进入睡眠状态,使wifi一直处于活跃状态 public WifiManager mWifiManager; /** * 获取该类的实例(懒汉) * @param context * @return */ public static WifiAdmin getInstance(Context context) { if(wifiAdmin == null) { wifiAdmin = new WifiAdmin(context); return wifiAdmin; } return null; } private WifiAdmin(Context context) { //获取系统Wifi服务 WIFI_SERVICE this.mWifiManager = (WifiManager) context.getSystemService("wifi"); //获取连接信息 this.mWifiInfo = this.mWifiManager.getConnectionInfo(); } /** * 是否存在网络信息 * @param str 热点名称 * @return */ private WifiConfiguration isExsits(String str) { Iterator localIterator = this.mWifiManager.getConfiguredNetworks().iterator(); WifiConfiguration localWifiConfiguration; do { if(!localIterator.hasNext()) return null; localWifiConfiguration = (WifiConfiguration) localIterator.next(); }while(!localWifiConfiguration.SSID.equals("\"" + str + "\"")); return localWifiConfiguration; } /**锁定WifiLock,当下载大文件时需要锁定 **/ public void AcquireWifiLock() { this.mWifilock.acquire(); } /**创建一个WifiLock**/ public void CreateWifiLock() { this.mWifilock = this.mWifiManager.createWifiLock("Test"); } /**解锁WifiLock**/ public void ReleaseWifilock() { if(mWifilock.isHeld()) { //判断时候锁定 mWifilock.acquire(); } } /**打开Wifi**/ public void OpenWifi() { if(!this.mWifiManager.isWifiEnabled()){ //当前wifi不可用 this.mWifiManager.setWifiEnabled(true); } } /**关闭Wifi**/ public void closeWifi() { if(mWifiManager.isWifiEnabled()) { mWifiManager.setWifiEnabled(false); } } /**端口指定id的wifi**/ public void disconnectWifi(int paramInt) { this.mWifiManager.disableNetwork(paramInt); } /**添加指定网络**/ public void addNetwork(WifiConfiguration paramWifiConfiguration) { int i = mWifiManager.addNetwork(paramWifiConfiguration); mWifiManager.enableNetwork(i, true); } /** * 连接指定配置好的网络 * @param index 配置好网络的ID */ public void connectConfiguration(int index) { // 索引大于配置好的网络索引返回 if (index > mWifiConfiguration.size()) { return; } //连接配置好的指定ID的网络 mWifiManager.enableNetwork(mWifiConfiguration.get(index).networkId, true); } /** * 根据wifi信息创建或关闭一个热点 * @param paramWifiConfiguration * @param paramBoolean 关闭标志 */ public void createWifiAP(WifiConfiguration paramWifiConfiguration,boolean paramBoolean) { try { Class localClass = this.mWifiManager.getClass(); Class[] arrayOfClass = new Class[2]; arrayOfClass[0] = WifiConfiguration.class; arrayOfClass[1] = Boolean.TYPE; Method localMethod = localClass.getMethod("setWifiApEnabled",arrayOfClass); WifiManager localWifiManager = this.mWifiManager; Object[] arrayOfObject = new Object[2]; arrayOfObject[0] = paramWifiConfiguration; arrayOfObject[1] = Boolean.valueOf(paramBoolean); localMethod.invoke(localWifiManager, arrayOfObject); return; } catch (Exception e) { e.printStackTrace(); } } /** * 创建一个wifi信息 * @param ssid 名称 * @param passawrd 密码 * @param paramInt 有3个参数,1是无密码,2是简单密码,3是wap加密 * @param type 是"ap"还是"wifi" * @return */ public WifiConfiguration createWifiInfo(String ssid, String passawrd,int paramInt, String type) { //配置网络信息类 WifiConfiguration localWifiConfiguration1 = new WifiConfiguration(); //设置配置网络属性 localWifiConfiguration1.allowedAuthAlgorithms.clear(); localWifiConfiguration1.allowedGroupCiphers.clear(); localWifiConfiguration1.allowedKeyManagement.clear(); localWifiConfiguration1.allowedPairwiseCiphers.clear(); localWifiConfiguration1.allowedProtocols.clear(); if(type.equals("wt")) { //wifi连接 localWifiConfiguration1.SSID = ("\"" + ssid + "\""); WifiConfiguration localWifiConfiguration2 = isExsits(ssid); if(localWifiConfiguration2 != null) { mWifiManager.removeNetwork(localWifiConfiguration2.networkId); //从列表中删除指定的网络配置网络 } if(paramInt == 1) { //没有密码 localWifiConfiguration1.wepKeys[0] = ""; localWifiConfiguration1.allowedKeyManagement.set(0); localWifiConfiguration1.wepTxKeyIndex = 0; } else if(paramInt == 2) { //简单密码 localWifiConfiguration1.hiddenSSID = true; localWifiConfiguration1.wepKeys[0] = ("\"" + passawrd + "\""); } else { //wap加密 localWifiConfiguration1.preSharedKey = ("\"" + passawrd + "\""); localWifiConfiguration1.hiddenSSID = true; localWifiConfiguration1.allowedAuthAlgorithms.set(0); localWifiConfiguration1.allowedGroupCiphers.set(2); localWifiConfiguration1.allowedKeyManagement.set(1); localWifiConfiguration1.allowedPairwiseCiphers.set(1); localWifiConfiguration1.allowedGroupCiphers.set(3); localWifiConfiguration1.allowedPairwiseCiphers.set(2); } }else {//"ap" wifi热点 localWifiConfiguration1.SSID = ssid; localWifiConfiguration1.allowedAuthAlgorithms.set(1); localWifiConfiguration1.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP); localWifiConfiguration1.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP); localWifiConfiguration1.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40); localWifiConfiguration1.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104); localWifiConfiguration1.allowedKeyManagement.set(0); localWifiConfiguration1.wepTxKeyIndex = 0; if (paramInt == 1) { //没有密码 localWifiConfiguration1.wepKeys[0] = ""; localWifiConfiguration1.allowedKeyManagement.set(0); localWifiConfiguration1.wepTxKeyIndex = 0; } else if (paramInt == 2) { //简单密码 localWifiConfiguration1.hiddenSSID = true;//网络上不广播ssid localWifiConfiguration1.wepKeys[0] = passawrd; } else if (paramInt == 3) {//wap加密 localWifiConfiguration1.preSharedKey = passawrd; localWifiConfiguration1.allowedAuthAlgorithms.set(0); localWifiConfiguration1.allowedProtocols.set(1); localWifiConfiguration1.allowedProtocols.set(0); localWifiConfiguration1.allowedKeyManagement.set(1); localWifiConfiguration1.allowedPairwiseCiphers.set(2); localWifiConfiguration1.allowedPairwiseCiphers.set(1); } } return localWifiConfiguration1; } /**获取热点名**/ public String getApSSID() { try { Method localMethod = this.mWifiManager.getClass().getDeclaredMethod("getWifiApConfiguration", new Class[0]); if (localMethod == null) return null; Object localObject1 = localMethod.invoke(this.mWifiManager,new Object[0]); if (localObject1 == null) return null; WifiConfiguration localWifiConfiguration = (WifiConfiguration) localObject1; if (localWifiConfiguration.SSID != null) return localWifiConfiguration.SSID; Field localField1 = WifiConfiguration.class .getDeclaredField("mWifiApProfile"); if (localField1 == null) return null; localField1.setAccessible(true); Object localObject2 = localField1.get(localWifiConfiguration); localField1.setAccessible(false); if (localObject2 == null) return null; Field localField2 = localObject2.getClass().getDeclaredField("SSID"); localField2.setAccessible(true); Object localObject3 = localField2.get(localObject2); if (localObject3 == null) return null; localField2.setAccessible(false); String str = (String) localObject3; return str; } catch (Exception localException) { } return null; } /**获取wifi名**/ public String getBSSID() { if (this.mWifiInfo == null) return "NULL"; return this.mWifiInfo.getBSSID(); } /**得到配置好的网络 **/ public List<WifiConfiguration> getConfiguration() { return this.mWifiConfiguration; } /**获取ip地址**/ public int getIPAddress() { return (mWifiInfo == null) ? 0 : mWifiInfo.getIpAddress(); } /**获取物理地址(Mac)**/ public String getMacAddress() { return (mWifiInfo == null) ? "NULL" : mWifiInfo.getMacAddress(); } /**获取网络id**/ public int getNetworkId() { return (mWifiInfo == null) ? 0 : mWifiInfo.getNetworkId(); } /**获取热点创建状态**/ public int getWifiApState() { try { int i = ((Integer) this.mWifiManager.getClass() .getMethod("getWifiApState", new Class[0]) .invoke(this.mWifiManager, new Object[0])).intValue(); return i; } catch (Exception localException) { } return 4; //未知wifi网卡状态 } /**获取wifi连接信息**/ public WifiInfo getWifiInfo() { return this.mWifiManager.getConnectionInfo(); } /** 得到网络列表**/ public List<ScanResult> getWifiList() { return this.mWifiList; } /**查看扫描结果**/ public StringBuilder lookUpScan() { StringBuilder localStringBuilder = new StringBuilder(); for (int i = 0; i < mWifiList.size(); i++) { localStringBuilder.append("Index_"+new Integer(i + 1).toString() + ":"); //将ScanResult信息转换成一个字符串包 //其中把包括:BSSID、SSID、capabilities、frequency、level localStringBuilder.append((mWifiList.get(i)).toString()); localStringBuilder.append("\n"); } return localStringBuilder; } /** 设置wifi搜索结果 **/ public void setWifiList() { this.mWifiList = this.mWifiManager.getScanResults(); } /**开始搜索wifi**/ public void startScan() { this.mWifiManager.startScan(); } /**得到接入点的BSSID**/ public String GetBSSID() { return (mWifiInfo == null) ? "NULL" : mWifiInfo.getBSSID(); } }
RealMoMo/Android_Utils
WifiUtils.java
2,888
//获取连接信息
line_comment
zh-cn
package com.momo.wifidemo.utils; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.Iterator; import java.util.List; import android.content.Context; import android.net.wifi.ScanResult; import android.net.wifi.WifiConfiguration; import android.net.wifi.WifiInfo; import android.net.wifi.WifiManager; /** * WIFI管理类 * @author Real.Mo * */ public class WifiAdmin { private static WifiAdmin wifiAdmin = null; private List<WifiConfiguration> mWifiConfiguration; //无线网络配置信息类集合(网络连接列表) private List<ScanResult> mWifiList; //检测到接入点信息类 集合 //描述任何Wifi连接状态 private WifiInfo mWifiInfo; WifiManager.WifiLock mWifilock; //能够阻止wifi进入睡眠状态,使wifi一直处于活跃状态 public WifiManager mWifiManager; /** * 获取该类的实例(懒汉) * @param context * @return */ public static WifiAdmin getInstance(Context context) { if(wifiAdmin == null) { wifiAdmin = new WifiAdmin(context); return wifiAdmin; } return null; } private WifiAdmin(Context context) { //获取系统Wifi服务 WIFI_SERVICE this.mWifiManager = (WifiManager) context.getSystemService("wifi"); //获取 <SUF> this.mWifiInfo = this.mWifiManager.getConnectionInfo(); } /** * 是否存在网络信息 * @param str 热点名称 * @return */ private WifiConfiguration isExsits(String str) { Iterator localIterator = this.mWifiManager.getConfiguredNetworks().iterator(); WifiConfiguration localWifiConfiguration; do { if(!localIterator.hasNext()) return null; localWifiConfiguration = (WifiConfiguration) localIterator.next(); }while(!localWifiConfiguration.SSID.equals("\"" + str + "\"")); return localWifiConfiguration; } /**锁定WifiLock,当下载大文件时需要锁定 **/ public void AcquireWifiLock() { this.mWifilock.acquire(); } /**创建一个WifiLock**/ public void CreateWifiLock() { this.mWifilock = this.mWifiManager.createWifiLock("Test"); } /**解锁WifiLock**/ public void ReleaseWifilock() { if(mWifilock.isHeld()) { //判断时候锁定 mWifilock.acquire(); } } /**打开Wifi**/ public void OpenWifi() { if(!this.mWifiManager.isWifiEnabled()){ //当前wifi不可用 this.mWifiManager.setWifiEnabled(true); } } /**关闭Wifi**/ public void closeWifi() { if(mWifiManager.isWifiEnabled()) { mWifiManager.setWifiEnabled(false); } } /**端口指定id的wifi**/ public void disconnectWifi(int paramInt) { this.mWifiManager.disableNetwork(paramInt); } /**添加指定网络**/ public void addNetwork(WifiConfiguration paramWifiConfiguration) { int i = mWifiManager.addNetwork(paramWifiConfiguration); mWifiManager.enableNetwork(i, true); } /** * 连接指定配置好的网络 * @param index 配置好网络的ID */ public void connectConfiguration(int index) { // 索引大于配置好的网络索引返回 if (index > mWifiConfiguration.size()) { return; } //连接配置好的指定ID的网络 mWifiManager.enableNetwork(mWifiConfiguration.get(index).networkId, true); } /** * 根据wifi信息创建或关闭一个热点 * @param paramWifiConfiguration * @param paramBoolean 关闭标志 */ public void createWifiAP(WifiConfiguration paramWifiConfiguration,boolean paramBoolean) { try { Class localClass = this.mWifiManager.getClass(); Class[] arrayOfClass = new Class[2]; arrayOfClass[0] = WifiConfiguration.class; arrayOfClass[1] = Boolean.TYPE; Method localMethod = localClass.getMethod("setWifiApEnabled",arrayOfClass); WifiManager localWifiManager = this.mWifiManager; Object[] arrayOfObject = new Object[2]; arrayOfObject[0] = paramWifiConfiguration; arrayOfObject[1] = Boolean.valueOf(paramBoolean); localMethod.invoke(localWifiManager, arrayOfObject); return; } catch (Exception e) { e.printStackTrace(); } } /** * 创建一个wifi信息 * @param ssid 名称 * @param passawrd 密码 * @param paramInt 有3个参数,1是无密码,2是简单密码,3是wap加密 * @param type 是"ap"还是"wifi" * @return */ public WifiConfiguration createWifiInfo(String ssid, String passawrd,int paramInt, String type) { //配置网络信息类 WifiConfiguration localWifiConfiguration1 = new WifiConfiguration(); //设置配置网络属性 localWifiConfiguration1.allowedAuthAlgorithms.clear(); localWifiConfiguration1.allowedGroupCiphers.clear(); localWifiConfiguration1.allowedKeyManagement.clear(); localWifiConfiguration1.allowedPairwiseCiphers.clear(); localWifiConfiguration1.allowedProtocols.clear(); if(type.equals("wt")) { //wifi连接 localWifiConfiguration1.SSID = ("\"" + ssid + "\""); WifiConfiguration localWifiConfiguration2 = isExsits(ssid); if(localWifiConfiguration2 != null) { mWifiManager.removeNetwork(localWifiConfiguration2.networkId); //从列表中删除指定的网络配置网络 } if(paramInt == 1) { //没有密码 localWifiConfiguration1.wepKeys[0] = ""; localWifiConfiguration1.allowedKeyManagement.set(0); localWifiConfiguration1.wepTxKeyIndex = 0; } else if(paramInt == 2) { //简单密码 localWifiConfiguration1.hiddenSSID = true; localWifiConfiguration1.wepKeys[0] = ("\"" + passawrd + "\""); } else { //wap加密 localWifiConfiguration1.preSharedKey = ("\"" + passawrd + "\""); localWifiConfiguration1.hiddenSSID = true; localWifiConfiguration1.allowedAuthAlgorithms.set(0); localWifiConfiguration1.allowedGroupCiphers.set(2); localWifiConfiguration1.allowedKeyManagement.set(1); localWifiConfiguration1.allowedPairwiseCiphers.set(1); localWifiConfiguration1.allowedGroupCiphers.set(3); localWifiConfiguration1.allowedPairwiseCiphers.set(2); } }else {//"ap" wifi热点 localWifiConfiguration1.SSID = ssid; localWifiConfiguration1.allowedAuthAlgorithms.set(1); localWifiConfiguration1.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP); localWifiConfiguration1.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP); localWifiConfiguration1.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40); localWifiConfiguration1.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104); localWifiConfiguration1.allowedKeyManagement.set(0); localWifiConfiguration1.wepTxKeyIndex = 0; if (paramInt == 1) { //没有密码 localWifiConfiguration1.wepKeys[0] = ""; localWifiConfiguration1.allowedKeyManagement.set(0); localWifiConfiguration1.wepTxKeyIndex = 0; } else if (paramInt == 2) { //简单密码 localWifiConfiguration1.hiddenSSID = true;//网络上不广播ssid localWifiConfiguration1.wepKeys[0] = passawrd; } else if (paramInt == 3) {//wap加密 localWifiConfiguration1.preSharedKey = passawrd; localWifiConfiguration1.allowedAuthAlgorithms.set(0); localWifiConfiguration1.allowedProtocols.set(1); localWifiConfiguration1.allowedProtocols.set(0); localWifiConfiguration1.allowedKeyManagement.set(1); localWifiConfiguration1.allowedPairwiseCiphers.set(2); localWifiConfiguration1.allowedPairwiseCiphers.set(1); } } return localWifiConfiguration1; } /**获取热点名**/ public String getApSSID() { try { Method localMethod = this.mWifiManager.getClass().getDeclaredMethod("getWifiApConfiguration", new Class[0]); if (localMethod == null) return null; Object localObject1 = localMethod.invoke(this.mWifiManager,new Object[0]); if (localObject1 == null) return null; WifiConfiguration localWifiConfiguration = (WifiConfiguration) localObject1; if (localWifiConfiguration.SSID != null) return localWifiConfiguration.SSID; Field localField1 = WifiConfiguration.class .getDeclaredField("mWifiApProfile"); if (localField1 == null) return null; localField1.setAccessible(true); Object localObject2 = localField1.get(localWifiConfiguration); localField1.setAccessible(false); if (localObject2 == null) return null; Field localField2 = localObject2.getClass().getDeclaredField("SSID"); localField2.setAccessible(true); Object localObject3 = localField2.get(localObject2); if (localObject3 == null) return null; localField2.setAccessible(false); String str = (String) localObject3; return str; } catch (Exception localException) { } return null; } /**获取wifi名**/ public String getBSSID() { if (this.mWifiInfo == null) return "NULL"; return this.mWifiInfo.getBSSID(); } /**得到配置好的网络 **/ public List<WifiConfiguration> getConfiguration() { return this.mWifiConfiguration; } /**获取ip地址**/ public int getIPAddress() { return (mWifiInfo == null) ? 0 : mWifiInfo.getIpAddress(); } /**获取物理地址(Mac)**/ public String getMacAddress() { return (mWifiInfo == null) ? "NULL" : mWifiInfo.getMacAddress(); } /**获取网络id**/ public int getNetworkId() { return (mWifiInfo == null) ? 0 : mWifiInfo.getNetworkId(); } /**获取热点创建状态**/ public int getWifiApState() { try { int i = ((Integer) this.mWifiManager.getClass() .getMethod("getWifiApState", new Class[0]) .invoke(this.mWifiManager, new Object[0])).intValue(); return i; } catch (Exception localException) { } return 4; //未知wifi网卡状态 } /**获取wifi连接信息**/ public WifiInfo getWifiInfo() { return this.mWifiManager.getConnectionInfo(); } /** 得到网络列表**/ public List<ScanResult> getWifiList() { return this.mWifiList; } /**查看扫描结果**/ public StringBuilder lookUpScan() { StringBuilder localStringBuilder = new StringBuilder(); for (int i = 0; i < mWifiList.size(); i++) { localStringBuilder.append("Index_"+new Integer(i + 1).toString() + ":"); //将ScanResult信息转换成一个字符串包 //其中把包括:BSSID、SSID、capabilities、frequency、level localStringBuilder.append((mWifiList.get(i)).toString()); localStringBuilder.append("\n"); } return localStringBuilder; } /** 设置wifi搜索结果 **/ public void setWifiList() { this.mWifiList = this.mWifiManager.getScanResults(); } /**开始搜索wifi**/ public void startScan() { this.mWifiManager.startScan(); } /**得到接入点的BSSID**/ public String GetBSSID() { return (mWifiInfo == null) ? "NULL" : mWifiInfo.getBSSID(); } }
false
2,666
4
2,888
4
3,140
4
2,888
4
3,894
7
false
false
false
false
false
true
58805_0
package _2_Structural_Pattern.Exam2.work_1_AdapterPattern; public class U { public String findZipCode(String zipCode) { if (zipCode.equals("12345")) { // 假设美国洛杉矶邮编为12345 return "洛杉矶"; } return "该邮编不存在!"; } }
RebornQ/DesignPatternExam
src/_2_Structural_Pattern/Exam2/work_1_AdapterPattern/U.java
96
// 假设美国洛杉矶邮编为12345
line_comment
zh-cn
package _2_Structural_Pattern.Exam2.work_1_AdapterPattern; public class U { public String findZipCode(String zipCode) { if (zipCode.equals("12345")) { // 假设 <SUF> return "洛杉矶"; } return "该邮编不存在!"; } }
false
81
15
96
19
92
15
96
19
121
27
false
false
false
false
false
true
34384_2
package com.ant.jobgod.imagetool.imageprovider.net; import android.app.Activity; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.support.v7.app.ActionBarActivity; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.StaggeredGridLayoutManager; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.Gravity; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.AbsListView; import android.widget.AdapterView; import android.widget.BaseAdapter; import android.widget.FrameLayout; import android.widget.GridView; import android.widget.SearchView; import android.widget.TextView; import com.android.http.RequestManager; import com.ant.jobgod.imagetool.R; import com.ant.jobgod.imagetool.imageprovider.ImageProvider; import com.ant.jobgod.imagetool.imageprovider.Utils; import com.ant.jobgod.imagetool.imageprovider.net.searchers.BaiduSearcher; import com.ant.jobgod.imagetool.imageprovider.net.searchers.HuaBanSearcher; import com.ant.jobgod.imagetool.imageprovider.net.searchers.SosoSearcher; import com.facebook.drawee.generic.GenericDraweeHierarchy; import com.facebook.drawee.generic.GenericDraweeHierarchyBuilder; import com.facebook.drawee.view.SimpleDraweeView; import java.io.Serializable; import java.util.ArrayList; import java.util.Arrays; public class NetImageSearchActivity extends ActionBarActivity { public static final String Key_seacher = "seacher"; private RecyclerView recycleview; private ImageListAdapter adapter; private SearchView searchview; private String searchText; private GridView mGridView; private SearcherConstructor seacher; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Utils.initialize(getApplication(), "NetImageSearch"); initSeacher(); setContentView(R.layout.fragment); Toolbar toolbar = (android.support.v7.widget.Toolbar) findViewById(R.id.toolbar); toolbar.setNavigationIcon(R.drawable.ic_return_black); setSupportActionBar(toolbar); recycleview = (RecyclerView) findViewById(R.id.recyclerview); StaggeredGridLayoutManager manager = new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL); recycleview.setLayoutManager(manager); adapter = new ImageListAdapter(); recycleview.setAdapter(adapter); mGridView = (GridView) findViewById(R.id.grid); mGridView.setAdapter(new GridViewAdapter()); mGridView.setFocusableInTouchMode(true); mGridView.setFocusable(true); mGridView.requestFocus(); mGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { searchview.setQuery(((TextView)view).getText().toString(), true); Utils.closeInputMethod(NetImageSearchActivity.this); } }); searchview = (SearchView)findViewById(R.id.searchview); searchview.setIconified(false); searchview.setOnQueryTextListener(new SearchView.OnQueryTextListener() { @Override public boolean onQueryTextSubmit(String query) { searchText = query; getImageList(searchText,0); recycleview.setVisibility(View.VISIBLE); mGridView.setVisibility(View.INVISIBLE); return false; } @Override public boolean onQueryTextChange(String newText) { if(newText.isEmpty()){ recycleview.setVisibility(View.INVISIBLE); mGridView.setVisibility(View.VISIBLE); } return false; } }); } private void initSeacher(){ ImageProvider.Searcher searcherenum = (ImageProvider.Searcher) getIntent().getSerializableExtra(Key_seacher); if (searcherenum == null){ seacher = new BaiduSearcher(); return; } switch (searcherenum){ case SOSO: seacher = new SosoSearcher(); break; case HuaBan: seacher = new HuaBanSearcher(); break; default: seacher = new BaiduSearcher(); break; } } private void getImageList(String word, final int page){ RequestManager.getInstance().get(seacher.getUrl(word,page),seacher.getHeader(), new RequestManager.RequestListener() { @Override public void onSuccess(String response) { NetImage[] imgs = seacher.getImageList(response); if(page==0)adapter.clear(); adapter.addList(imgs); } @Override public void onRequest() { // TODO Auto-generated method stub } @Override public void onError(String errorMsg) { // TODO Auto-generated method stub } },true); } class ImageListAdapter extends RecyclerView.Adapter<ImageViewHolder>{ private int page = 0; private ArrayList<NetImage> arr = new ArrayList<>(); public void addList(NetImage[] imgs){ if (imgs!=null){ arr.addAll(Arrays.asList(imgs)); notifyDataSetChanged(); } page++; } public void clear(){ arr.clear(); notifyDataSetChanged(); page=0; } @Override public int getItemCount() { return arr.size(); } @Override public void onBindViewHolder(final ImageViewHolder arg0, int arg1) { int width = Utils.getScreenWidth()/2; if (arr.get(arg1).getHeight()!=0 && arr.get(arg1).getWidth()!=0){ int height = width*arr.get(arg1).getHeight()/arr.get(arg1).getWidth(); arg0.img.setLayoutParams(new FrameLayout.LayoutParams(width,height)); } String url = arr.get(arg1).getThumbImg(); arg0.img.setImageURI(Uri.parse(url)); Log.d("img",url); //加载下一页 if(arg1==arr.size()-1){ getImageList(searchText,page+1); } arg0.wallimg = arr.get(arg1); } @Override public ImageViewHolder onCreateViewHolder(ViewGroup arg0, int arg1) { SimpleDraweeView img = new SimpleDraweeView(arg0.getContext()); GenericDraweeHierarchyBuilder builder = new GenericDraweeHierarchyBuilder(getResources()); GenericDraweeHierarchy hierarchy = builder .setProgressBarImage(getResources().getDrawable(R.drawable.default_loading)) .setFailureImage(getResources().getDrawable(R.drawable.default_error)) .build(); img.setHierarchy(hierarchy); img.setId(R.id.image); img.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 0)); img.setPadding(Utils.dip2px(4), Utils.dip2px(4), Utils.dip2px(4), Utils.dip2px(4)); FrameLayout layout = new FrameLayout(arg0.getContext()); layout.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)); layout.addView(img); return new ImageViewHolder(layout); } } class ImageViewHolder extends RecyclerView.ViewHolder{ public Serializable wallimg; public SimpleDraweeView img; public ImageViewHolder(View itemView) { super(itemView); img = (SimpleDraweeView) itemView.findViewById(R.id.image); img.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(); setResult(Activity.RESULT_OK, intent); intent.putExtra("data", wallimg); finish(); } }); } } class GridViewAdapter extends BaseAdapter { String[] hint = { "拥抱","梦幻","爱情","唯美","汪星人","美好","风景","孤独","插画" }; @Override public int getCount() { return hint.length; } @Override public Object getItem(int position) { // TODO Auto-generated method stub return null; } @Override public long getItemId(int position) { // TODO Auto-generated method stub return 0; } @Override public View getView(int position, View convertView, ViewGroup parent) { TextView view = new TextView(NetImageSearchActivity.this); view.setBackgroundColor(getResources().getColor(android.R.color.holo_blue_bright)); view.setLayoutParams(new AbsListView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, Utils.dip2px(48))); view.setGravity(Gravity.CENTER); view.setTextColor(getResources().getColor(android.R.color.white)); view.setText(hint[position]); return view; } } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: this.finish(); } return super.onOptionsItemSelected(item); } }
RedrockTeam/Date_Android
imagetool/src/main/java/com/ant/jobgod/imagetool/imageprovider/net/NetImageSearchActivity.java
2,188
//加载下一页
line_comment
zh-cn
package com.ant.jobgod.imagetool.imageprovider.net; import android.app.Activity; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.support.v7.app.ActionBarActivity; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.StaggeredGridLayoutManager; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.Gravity; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.AbsListView; import android.widget.AdapterView; import android.widget.BaseAdapter; import android.widget.FrameLayout; import android.widget.GridView; import android.widget.SearchView; import android.widget.TextView; import com.android.http.RequestManager; import com.ant.jobgod.imagetool.R; import com.ant.jobgod.imagetool.imageprovider.ImageProvider; import com.ant.jobgod.imagetool.imageprovider.Utils; import com.ant.jobgod.imagetool.imageprovider.net.searchers.BaiduSearcher; import com.ant.jobgod.imagetool.imageprovider.net.searchers.HuaBanSearcher; import com.ant.jobgod.imagetool.imageprovider.net.searchers.SosoSearcher; import com.facebook.drawee.generic.GenericDraweeHierarchy; import com.facebook.drawee.generic.GenericDraweeHierarchyBuilder; import com.facebook.drawee.view.SimpleDraweeView; import java.io.Serializable; import java.util.ArrayList; import java.util.Arrays; public class NetImageSearchActivity extends ActionBarActivity { public static final String Key_seacher = "seacher"; private RecyclerView recycleview; private ImageListAdapter adapter; private SearchView searchview; private String searchText; private GridView mGridView; private SearcherConstructor seacher; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Utils.initialize(getApplication(), "NetImageSearch"); initSeacher(); setContentView(R.layout.fragment); Toolbar toolbar = (android.support.v7.widget.Toolbar) findViewById(R.id.toolbar); toolbar.setNavigationIcon(R.drawable.ic_return_black); setSupportActionBar(toolbar); recycleview = (RecyclerView) findViewById(R.id.recyclerview); StaggeredGridLayoutManager manager = new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL); recycleview.setLayoutManager(manager); adapter = new ImageListAdapter(); recycleview.setAdapter(adapter); mGridView = (GridView) findViewById(R.id.grid); mGridView.setAdapter(new GridViewAdapter()); mGridView.setFocusableInTouchMode(true); mGridView.setFocusable(true); mGridView.requestFocus(); mGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { searchview.setQuery(((TextView)view).getText().toString(), true); Utils.closeInputMethod(NetImageSearchActivity.this); } }); searchview = (SearchView)findViewById(R.id.searchview); searchview.setIconified(false); searchview.setOnQueryTextListener(new SearchView.OnQueryTextListener() { @Override public boolean onQueryTextSubmit(String query) { searchText = query; getImageList(searchText,0); recycleview.setVisibility(View.VISIBLE); mGridView.setVisibility(View.INVISIBLE); return false; } @Override public boolean onQueryTextChange(String newText) { if(newText.isEmpty()){ recycleview.setVisibility(View.INVISIBLE); mGridView.setVisibility(View.VISIBLE); } return false; } }); } private void initSeacher(){ ImageProvider.Searcher searcherenum = (ImageProvider.Searcher) getIntent().getSerializableExtra(Key_seacher); if (searcherenum == null){ seacher = new BaiduSearcher(); return; } switch (searcherenum){ case SOSO: seacher = new SosoSearcher(); break; case HuaBan: seacher = new HuaBanSearcher(); break; default: seacher = new BaiduSearcher(); break; } } private void getImageList(String word, final int page){ RequestManager.getInstance().get(seacher.getUrl(word,page),seacher.getHeader(), new RequestManager.RequestListener() { @Override public void onSuccess(String response) { NetImage[] imgs = seacher.getImageList(response); if(page==0)adapter.clear(); adapter.addList(imgs); } @Override public void onRequest() { // TODO Auto-generated method stub } @Override public void onError(String errorMsg) { // TODO Auto-generated method stub } },true); } class ImageListAdapter extends RecyclerView.Adapter<ImageViewHolder>{ private int page = 0; private ArrayList<NetImage> arr = new ArrayList<>(); public void addList(NetImage[] imgs){ if (imgs!=null){ arr.addAll(Arrays.asList(imgs)); notifyDataSetChanged(); } page++; } public void clear(){ arr.clear(); notifyDataSetChanged(); page=0; } @Override public int getItemCount() { return arr.size(); } @Override public void onBindViewHolder(final ImageViewHolder arg0, int arg1) { int width = Utils.getScreenWidth()/2; if (arr.get(arg1).getHeight()!=0 && arr.get(arg1).getWidth()!=0){ int height = width*arr.get(arg1).getHeight()/arr.get(arg1).getWidth(); arg0.img.setLayoutParams(new FrameLayout.LayoutParams(width,height)); } String url = arr.get(arg1).getThumbImg(); arg0.img.setImageURI(Uri.parse(url)); Log.d("img",url); //加载 <SUF> if(arg1==arr.size()-1){ getImageList(searchText,page+1); } arg0.wallimg = arr.get(arg1); } @Override public ImageViewHolder onCreateViewHolder(ViewGroup arg0, int arg1) { SimpleDraweeView img = new SimpleDraweeView(arg0.getContext()); GenericDraweeHierarchyBuilder builder = new GenericDraweeHierarchyBuilder(getResources()); GenericDraweeHierarchy hierarchy = builder .setProgressBarImage(getResources().getDrawable(R.drawable.default_loading)) .setFailureImage(getResources().getDrawable(R.drawable.default_error)) .build(); img.setHierarchy(hierarchy); img.setId(R.id.image); img.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 0)); img.setPadding(Utils.dip2px(4), Utils.dip2px(4), Utils.dip2px(4), Utils.dip2px(4)); FrameLayout layout = new FrameLayout(arg0.getContext()); layout.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)); layout.addView(img); return new ImageViewHolder(layout); } } class ImageViewHolder extends RecyclerView.ViewHolder{ public Serializable wallimg; public SimpleDraweeView img; public ImageViewHolder(View itemView) { super(itemView); img = (SimpleDraweeView) itemView.findViewById(R.id.image); img.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(); setResult(Activity.RESULT_OK, intent); intent.putExtra("data", wallimg); finish(); } }); } } class GridViewAdapter extends BaseAdapter { String[] hint = { "拥抱","梦幻","爱情","唯美","汪星人","美好","风景","孤独","插画" }; @Override public int getCount() { return hint.length; } @Override public Object getItem(int position) { // TODO Auto-generated method stub return null; } @Override public long getItemId(int position) { // TODO Auto-generated method stub return 0; } @Override public View getView(int position, View convertView, ViewGroup parent) { TextView view = new TextView(NetImageSearchActivity.this); view.setBackgroundColor(getResources().getColor(android.R.color.holo_blue_bright)); view.setLayoutParams(new AbsListView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, Utils.dip2px(48))); view.setGravity(Gravity.CENTER); view.setTextColor(getResources().getColor(android.R.color.white)); view.setText(hint[position]); return view; } } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: this.finish(); } return super.onOptionsItemSelected(item); } }
false
1,757
4
2,188
5
2,289
3
2,188
5
2,641
6
false
false
false
false
false
true
16224_13
package com.reine; import javafx.application.Application; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.geometry.Pos; import javafx.scene.Scene; import javafx.scene.chart.BarChart; import javafx.scene.chart.CategoryAxis; import javafx.scene.chart.NumberAxis; import javafx.scene.chart.XYChart; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.layout.AnchorPane; import javafx.scene.layout.HBox; import javafx.stage.Stage; /** * @author reine * 2022/6/13 17:18 */ public class Main extends Application { public static void main(String[] args) { launch(args); } @Override public void start(Stage primaryStage) throws Exception { BarChart<String, Number> chart = getView2(); chart.setTitle("第二种方式"); // chart.setPrefWidth(300); // chart.setPrefHeight(300); // 开启动画效果 // chart.setAnimated(true); // 设置图示的位置 // chart.setLegendSide(Side.RIGHT); // 设置图示是否可见 // chart.setLegendVisible(false); // 设置图题的位置 // chart.setTitleSide(Side.BOTTOM); // 设置方向 // chart.setNodeOrientation(NodeOrientation.RIGHT_TO_LEFT); // 设置每一类数据柱状之间的间距 // chart.setBarGap(0); // 设置每一组数据柱状之间的间距 // chart.setCategoryGap(100); CategoryAxis xAxis = (CategoryAxis) chart.getXAxis(); // 设置x轴开始于原点的距离 // xAxis.setStartMargin(100); // 设置x轴末尾距离坐标轴末尾的距离 // xAxis.setEndMargin(100); // 设置前后留有空间 // xAxis.setGapStartAndEnd(true); // 设置X轴的位置 // xAxis.setSide(Side.TOP); // 设置x轴类别标签颜色 // xAxis.setTickLabelFill(Color.PURPLE); // 设置x轴类别字体大小 // xAxis.setTickLabelFont(new Font(20)); // 设置类别标签与轴刻度的间距 // xAxis.setTickLabelGap(100); // 设置类型标签旋转45° // xAxis.setTickLabelRotation(45); // 是否显示类别名称 // xAxis.setTickLabelsVisible(false); HBox box = new HBox(); box.getChildren().addAll(chart); Button button = new Button("click"); AnchorPane root = new AnchorPane(); root.getChildren().addAll(box, button); AnchorPane.setBottomAnchor(button, 100.0); AnchorPane.setRightAnchor(button, 100.0); Scene scene = new Scene(root); scene.getStylesheets().addAll(this.getClass().getClassLoader().getResource("css/chart.css").toExternalForm()); primaryStage.setScene(scene); primaryStage.setTitle("BarChart柱状图基本设置"); primaryStage.setWidth(800); primaryStage.setHeight(800); primaryStage.setAlwaysOnTop(true); primaryStage.show(); button.setOnAction(event -> { XYChart.Series<String, Number> series = chart.getData().get(0); XYChart.Data<String, Number> data = series.getData().get(0); data.setYValue(20); }); } /** * 第一种方式 * * @return */ private BarChart<String, Number> getView1() { CategoryAxis x = new CategoryAxis(); x.setLabel("国家"); /* 最低,最高,间距*/ NumberAxis y = new NumberAxis(0, 100, 10); y.setLabel("GDP"); // 构造数据 ObservableList<XYChart.Series<String, Number>> listData = FXCollections.observableArrayList(); XYChart.Series<String, Number> xy = new XYChart.Series<>(); xy.setName("生产总值"); ObservableList<XYChart.Data<String, Number>> data = FXCollections.observableArrayList(); XYChart.Data<String, Number> data1 = new XYChart.Data<>("日本", 70); XYChart.Data<String, Number> data2 = new XYChart.Data<>("美国", 90); XYChart.Data<String, Number> data3 = new XYChart.Data<>("英国", 50); data.addAll(data1, data2, data3); xy.setData(data); listData.add(xy); return new BarChart<>(x, y, listData); } /** * 第二种方式 * * @return */ private BarChart<String, Number> getView2() { CategoryAxis x = new CategoryAxis(); x.setLabel("国家"); /* 最低,最高,间距*/ NumberAxis y = new NumberAxis(0, 100, 10); y.setLabel("GDP"); XYChart.Series<String, Number> ChinaXY = new XYChart.Series<>(); ChinaXY.setName("中国"); XYChart.Series<String, Number> JapanXY = new XYChart.Series<>(); JapanXY.setName("日本"); XYChart.Series<String, Number> AmericanXY = new XYChart.Series<>(); AmericanXY.setName("美国"); XYChart.Data<String, Number> data1 = new XYChart.Data<>("GDP", 70); XYChart.Data<String, Number> data2 = new XYChart.Data<>("GDP", 90); XYChart.Data<String, Number> data3 = new XYChart.Data<>("GDP", 50); XYChart.Data<String, Number> data4 = new XYChart.Data<>("GNP", 40); XYChart.Data<String, Number> data5 = new XYChart.Data<>("GNP", 93); XYChart.Data<String, Number> data6 = new XYChart.Data<>("GNP", 63); ChinaXY.getData().addAll(data1, data4); JapanXY.getData().addAll(data2, data5); AmericanXY.getData().addAll(data3, data6); // ChinaXY.getData().forEach(stringNumberData -> { // HBox box = new HBox(); // box.setAlignment(Pos.CENTER); // box.setStyle("-fx-background-color: #ffff55;"); // box.getChildren().addAll(new Label(String.valueOf(stringNumberData.getYValue()))); // stringNumberData.setNode(box); // stringNumberData.getNode().setOnMouseClicked(event -> System.out.println(stringNumberData.getXValue())); // }); BarChart<String, Number> chart = new BarChart<>(x, y); chart.getData().addAll(ChinaXY, JapanXY, AmericanXY); return chart; } /** * 第三种方式 * * @return */ private BarChart<String, Number> getView3() { CategoryAxis x = new CategoryAxis(); x.setLabel("国家"); /* 最低,最高,间距*/ NumberAxis y = new NumberAxis(0, 100, 10); y.setLabel("GDP"); XYChart.Series<String, Number> GDPXY = new XYChart.Series<>(); GDPXY.setName("GDP"); XYChart.Series<String, Number> GNPXY = new XYChart.Series<>(); GNPXY.setName("GNP"); XYChart.Data<String, Number> data1 = new XYChart.Data<>("中国", 70); XYChart.Data<String, Number> data2 = new XYChart.Data<>("美国", 90); XYChart.Data<String, Number> data3 = new XYChart.Data<>("日本", 50); XYChart.Data<String, Number> data4 = new XYChart.Data<>("中国", 40); XYChart.Data<String, Number> data5 = new XYChart.Data<>("美国", 93); XYChart.Data<String, Number> data6 = new XYChart.Data<>("日本", 63); GDPXY.getData().addAll(data1, data2, data3); GNPXY.getData().addAll(data4, data5, data6); BarChart<String, Number> chart = new BarChart<>(x, y); chart.getData().addAll(GDPXY, GNPXY); return chart; } /** * 第四种方式 * * @return */ private BarChart<Number, String> getView4() { CategoryAxis x = new CategoryAxis(); x.setLabel("国家"); /* 最低,最高,间距*/ NumberAxis y = new NumberAxis(0, 100, 10); y.setLabel("GDP"); XYChart.Series<Number, String> GDPXY = new XYChart.Series<>(); GDPXY.setName("GDP"); XYChart.Series<Number, String> GNPXY = new XYChart.Series<>(); GNPXY.setName("GNP"); XYChart.Data<Number, String> data1 = new XYChart.Data<>(70, "中国"); XYChart.Data<Number, String> data2 = new XYChart.Data<>(90, "美国"); XYChart.Data<Number, String> data3 = new XYChart.Data<>(50, "日本"); XYChart.Data<Number, String> data4 = new XYChart.Data<>(40, "中国"); XYChart.Data<Number, String> data5 = new XYChart.Data<>(93, "美国"); XYChart.Data<Number, String> data6 = new XYChart.Data<>(63, "日本"); GDPXY.getData().addAll(data1, data2, data3); GNPXY.getData().addAll(data4, data5, data6); BarChart<Number, String> chart = new BarChart<>(y, x); chart.getData().addAll(GDPXY, GNPXY); return chart; } }
Reiticia/javafx-study
code/lesson129/src/com/reine/Main.java
2,438
// 设置每一类数据柱状之间的间距
line_comment
zh-cn
package com.reine; import javafx.application.Application; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.geometry.Pos; import javafx.scene.Scene; import javafx.scene.chart.BarChart; import javafx.scene.chart.CategoryAxis; import javafx.scene.chart.NumberAxis; import javafx.scene.chart.XYChart; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.layout.AnchorPane; import javafx.scene.layout.HBox; import javafx.stage.Stage; /** * @author reine * 2022/6/13 17:18 */ public class Main extends Application { public static void main(String[] args) { launch(args); } @Override public void start(Stage primaryStage) throws Exception { BarChart<String, Number> chart = getView2(); chart.setTitle("第二种方式"); // chart.setPrefWidth(300); // chart.setPrefHeight(300); // 开启动画效果 // chart.setAnimated(true); // 设置图示的位置 // chart.setLegendSide(Side.RIGHT); // 设置图示是否可见 // chart.setLegendVisible(false); // 设置图题的位置 // chart.setTitleSide(Side.BOTTOM); // 设置方向 // chart.setNodeOrientation(NodeOrientation.RIGHT_TO_LEFT); // 设置 <SUF> // chart.setBarGap(0); // 设置每一组数据柱状之间的间距 // chart.setCategoryGap(100); CategoryAxis xAxis = (CategoryAxis) chart.getXAxis(); // 设置x轴开始于原点的距离 // xAxis.setStartMargin(100); // 设置x轴末尾距离坐标轴末尾的距离 // xAxis.setEndMargin(100); // 设置前后留有空间 // xAxis.setGapStartAndEnd(true); // 设置X轴的位置 // xAxis.setSide(Side.TOP); // 设置x轴类别标签颜色 // xAxis.setTickLabelFill(Color.PURPLE); // 设置x轴类别字体大小 // xAxis.setTickLabelFont(new Font(20)); // 设置类别标签与轴刻度的间距 // xAxis.setTickLabelGap(100); // 设置类型标签旋转45° // xAxis.setTickLabelRotation(45); // 是否显示类别名称 // xAxis.setTickLabelsVisible(false); HBox box = new HBox(); box.getChildren().addAll(chart); Button button = new Button("click"); AnchorPane root = new AnchorPane(); root.getChildren().addAll(box, button); AnchorPane.setBottomAnchor(button, 100.0); AnchorPane.setRightAnchor(button, 100.0); Scene scene = new Scene(root); scene.getStylesheets().addAll(this.getClass().getClassLoader().getResource("css/chart.css").toExternalForm()); primaryStage.setScene(scene); primaryStage.setTitle("BarChart柱状图基本设置"); primaryStage.setWidth(800); primaryStage.setHeight(800); primaryStage.setAlwaysOnTop(true); primaryStage.show(); button.setOnAction(event -> { XYChart.Series<String, Number> series = chart.getData().get(0); XYChart.Data<String, Number> data = series.getData().get(0); data.setYValue(20); }); } /** * 第一种方式 * * @return */ private BarChart<String, Number> getView1() { CategoryAxis x = new CategoryAxis(); x.setLabel("国家"); /* 最低,最高,间距*/ NumberAxis y = new NumberAxis(0, 100, 10); y.setLabel("GDP"); // 构造数据 ObservableList<XYChart.Series<String, Number>> listData = FXCollections.observableArrayList(); XYChart.Series<String, Number> xy = new XYChart.Series<>(); xy.setName("生产总值"); ObservableList<XYChart.Data<String, Number>> data = FXCollections.observableArrayList(); XYChart.Data<String, Number> data1 = new XYChart.Data<>("日本", 70); XYChart.Data<String, Number> data2 = new XYChart.Data<>("美国", 90); XYChart.Data<String, Number> data3 = new XYChart.Data<>("英国", 50); data.addAll(data1, data2, data3); xy.setData(data); listData.add(xy); return new BarChart<>(x, y, listData); } /** * 第二种方式 * * @return */ private BarChart<String, Number> getView2() { CategoryAxis x = new CategoryAxis(); x.setLabel("国家"); /* 最低,最高,间距*/ NumberAxis y = new NumberAxis(0, 100, 10); y.setLabel("GDP"); XYChart.Series<String, Number> ChinaXY = new XYChart.Series<>(); ChinaXY.setName("中国"); XYChart.Series<String, Number> JapanXY = new XYChart.Series<>(); JapanXY.setName("日本"); XYChart.Series<String, Number> AmericanXY = new XYChart.Series<>(); AmericanXY.setName("美国"); XYChart.Data<String, Number> data1 = new XYChart.Data<>("GDP", 70); XYChart.Data<String, Number> data2 = new XYChart.Data<>("GDP", 90); XYChart.Data<String, Number> data3 = new XYChart.Data<>("GDP", 50); XYChart.Data<String, Number> data4 = new XYChart.Data<>("GNP", 40); XYChart.Data<String, Number> data5 = new XYChart.Data<>("GNP", 93); XYChart.Data<String, Number> data6 = new XYChart.Data<>("GNP", 63); ChinaXY.getData().addAll(data1, data4); JapanXY.getData().addAll(data2, data5); AmericanXY.getData().addAll(data3, data6); // ChinaXY.getData().forEach(stringNumberData -> { // HBox box = new HBox(); // box.setAlignment(Pos.CENTER); // box.setStyle("-fx-background-color: #ffff55;"); // box.getChildren().addAll(new Label(String.valueOf(stringNumberData.getYValue()))); // stringNumberData.setNode(box); // stringNumberData.getNode().setOnMouseClicked(event -> System.out.println(stringNumberData.getXValue())); // }); BarChart<String, Number> chart = new BarChart<>(x, y); chart.getData().addAll(ChinaXY, JapanXY, AmericanXY); return chart; } /** * 第三种方式 * * @return */ private BarChart<String, Number> getView3() { CategoryAxis x = new CategoryAxis(); x.setLabel("国家"); /* 最低,最高,间距*/ NumberAxis y = new NumberAxis(0, 100, 10); y.setLabel("GDP"); XYChart.Series<String, Number> GDPXY = new XYChart.Series<>(); GDPXY.setName("GDP"); XYChart.Series<String, Number> GNPXY = new XYChart.Series<>(); GNPXY.setName("GNP"); XYChart.Data<String, Number> data1 = new XYChart.Data<>("中国", 70); XYChart.Data<String, Number> data2 = new XYChart.Data<>("美国", 90); XYChart.Data<String, Number> data3 = new XYChart.Data<>("日本", 50); XYChart.Data<String, Number> data4 = new XYChart.Data<>("中国", 40); XYChart.Data<String, Number> data5 = new XYChart.Data<>("美国", 93); XYChart.Data<String, Number> data6 = new XYChart.Data<>("日本", 63); GDPXY.getData().addAll(data1, data2, data3); GNPXY.getData().addAll(data4, data5, data6); BarChart<String, Number> chart = new BarChart<>(x, y); chart.getData().addAll(GDPXY, GNPXY); return chart; } /** * 第四种方式 * * @return */ private BarChart<Number, String> getView4() { CategoryAxis x = new CategoryAxis(); x.setLabel("国家"); /* 最低,最高,间距*/ NumberAxis y = new NumberAxis(0, 100, 10); y.setLabel("GDP"); XYChart.Series<Number, String> GDPXY = new XYChart.Series<>(); GDPXY.setName("GDP"); XYChart.Series<Number, String> GNPXY = new XYChart.Series<>(); GNPXY.setName("GNP"); XYChart.Data<Number, String> data1 = new XYChart.Data<>(70, "中国"); XYChart.Data<Number, String> data2 = new XYChart.Data<>(90, "美国"); XYChart.Data<Number, String> data3 = new XYChart.Data<>(50, "日本"); XYChart.Data<Number, String> data4 = new XYChart.Data<>(40, "中国"); XYChart.Data<Number, String> data5 = new XYChart.Data<>(93, "美国"); XYChart.Data<Number, String> data6 = new XYChart.Data<>(63, "日本"); GDPXY.getData().addAll(data1, data2, data3); GNPXY.getData().addAll(data4, data5, data6); BarChart<Number, String> chart = new BarChart<>(y, x); chart.getData().addAll(GDPXY, GNPXY); return chart; } }
false
2,104
9
2,438
12
2,505
10
2,438
12
2,985
20
false
false
false
false
false
true
61859_0
package yyl.example.demo.jts; /** * JTS是加拿大的 Vivid Solutions公司做的一套开放源码的 Java API。<br> * 它提供了一套空间数据操作的核心算法。为在兼容OGC标准的空间对象模型中进行基础的几何操作提供2D空间谓词API。<br> * 支持的空间操作包括:<br> * 相等(Equals): 几何形状拓扑上相等。<br> * 脱节(Disjoint): 几何形状没有共有的点。<br> * 相交(Intersects): 几何形状至少有一个共有点(区别于脱节)<br> * 接触(Touches): 几何形状有至少一个公共的边界点,但是没有内部点。<br> * 交叉(Crosses): 几何形状共享一些但不是所有的内部点。<br> * 内含(Within): 几何形状A的线都在几何形状B内部。<br> * 包含(Contains): 几何形状B的线都在几何形状A内部(区别于内含)<br> * 重叠(Overlaps): 几何形状共享一部分但不是所有的公共点,而且相交处有他们自己相同的区域。<br> * <br> * WKT(Well-known text)是一种文本标记语言,用于表示矢量几何对象、空间参照系统及空间参照系统之间的转换。<br> * 它的二进制表示方式,亦即WKB(well-known binary)则胜于在传输和在数据库中存储相同的信息。<br> * 该格式由开放地理空间联盟(OGC)制定。<br> */
Relucent/yyl_example
src/main/java/yyl/example/demo/jts/package-info.java
432
/** * JTS是加拿大的 Vivid Solutions公司做的一套开放源码的 Java API。<br> * 它提供了一套空间数据操作的核心算法。为在兼容OGC标准的空间对象模型中进行基础的几何操作提供2D空间谓词API。<br> * 支持的空间操作包括:<br> * 相等(Equals): 几何形状拓扑上相等。<br> * 脱节(Disjoint): 几何形状没有共有的点。<br> * 相交(Intersects): 几何形状至少有一个共有点(区别于脱节)<br> * 接触(Touches): 几何形状有至少一个公共的边界点,但是没有内部点。<br> * 交叉(Crosses): 几何形状共享一些但不是所有的内部点。<br> * 内含(Within): 几何形状A的线都在几何形状B内部。<br> * 包含(Contains): 几何形状B的线都在几何形状A内部(区别于内含)<br> * 重叠(Overlaps): 几何形状共享一部分但不是所有的公共点,而且相交处有他们自己相同的区域。<br> * <br> * WKT(Well-known text)是一种文本标记语言,用于表示矢量几何对象、空间参照系统及空间参照系统之间的转换。<br> * 它的二进制表示方式,亦即WKB(well-known binary)则胜于在传输和在数据库中存储相同的信息。<br> * 该格式由开放地理空间联盟(OGC)制定。<br> */
block_comment
zh-cn
package yyl.example.demo.jts; /** * JTS <SUF>*/
false
368
360
432
421
348
337
432
421
633
621
true
true
true
true
true
false
27477_8
package dao; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.RowMapper; import util.JDBCUtils; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Set; public abstract class AbstractDao { protected final JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource()); public abstract void add(Object obj); //增 public abstract void delete(int id); //删 public abstract int update(Object obj); //改 /** * 分页模糊查询 * @param sql 基础语句 * @param condition 条件。按key like %value%组织 */ protected <T> List<T> findByPage(String sql, RowMapper<T> rowMapper,int start, int rows, Map<String, String[]> condition) { //查 StringBuilder sb = new StringBuilder(sql); //2.遍历map Set<String> keySet = condition.keySet(); //定义参数的集合 ArrayList<Object> params = new ArrayList<>(condition.size()); for (String key : keySet) { //排除分页条件参数 if("currentPage".equals(key) || "rows".equals(key)){ continue; } //获取value String value = condition.get(key)[0]; //判断value是否有值 if(value != null && !"".equals(value)){ //有值 sb.append(" and ").append(key).append(" like ? "); params.add("%"+value+"%");//?条件的值 } } //添加分页查询 sb.append(" limit ?,? "); //添加分页查询参数值 params.add(start); params.add(rows); return template.query(sb.toString(), rowMapper,params.toArray()); } }
Remaker01/StuGradeManagement
src/main/java/dao/AbstractDao.java
420
//添加分页查询参数值
line_comment
zh-cn
package dao; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.RowMapper; import util.JDBCUtils; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Set; public abstract class AbstractDao { protected final JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource()); public abstract void add(Object obj); //增 public abstract void delete(int id); //删 public abstract int update(Object obj); //改 /** * 分页模糊查询 * @param sql 基础语句 * @param condition 条件。按key like %value%组织 */ protected <T> List<T> findByPage(String sql, RowMapper<T> rowMapper,int start, int rows, Map<String, String[]> condition) { //查 StringBuilder sb = new StringBuilder(sql); //2.遍历map Set<String> keySet = condition.keySet(); //定义参数的集合 ArrayList<Object> params = new ArrayList<>(condition.size()); for (String key : keySet) { //排除分页条件参数 if("currentPage".equals(key) || "rows".equals(key)){ continue; } //获取value String value = condition.get(key)[0]; //判断value是否有值 if(value != null && !"".equals(value)){ //有值 sb.append(" and ").append(key).append(" like ? "); params.add("%"+value+"%");//?条件的值 } } //添加分页查询 sb.append(" limit ?,? "); //添加 <SUF> params.add(start); params.add(rows); return template.query(sb.toString(), rowMapper,params.toArray()); } }
false
378
7
420
6
444
6
420
6
518
12
false
false
false
false
false
true
54359_1
package com.rsh.coviewer.bean; import lombok.Data; import java.io.Serializable; import java.util.ArrayList; import java.util.HashMap; /** * Created by rsh on 2018/7/4. * 豆瓣-单个电影具体信息 * https://developers.douban.com/wiki/?title=movie_v2 */ @Data public class OneSubject implements Serializable { private Rating rating;//评分 private int reviews_count;//影评数量 private int wish_count;//想看人数 private String douban_site;//豆瓣小站 private String year;//年代 private HashMap<String,String> images;//电影海报图 private String alt;//条目页URL private String id;//条目id private String mobile_url;//移动版条目页id private String title;//中文名 private String do_count;//再看人数。如果是电视剧,默认为0,如果是电影值为null private String share_url;// private String seasons_count;//总季数 private String schedule_url;//影讯页URL private String episodes_count;//当前季的集数 private ArrayList<String> countries;//制片国家或地区 private ArrayList<String> genres;//影片类型 private int collect_count;// private ArrayList<Casts> casts;//主演 private String current_season;//当前季数 private String original_title;//原名 private String summary;//简介 private String subtype;//条目分类 private ArrayList<Directors> directors;//导演,数据结构为影人的简化描述 private int comment_count;//短评数量 private int rating_count;//评分人数 private ArrayList<String> aka;//又名 }
RenShuhuai-Andy/Co-viewer
src/main/java/com/rsh/coviewer/bean/OneSubject.java
418
//影评数量
line_comment
zh-cn
package com.rsh.coviewer.bean; import lombok.Data; import java.io.Serializable; import java.util.ArrayList; import java.util.HashMap; /** * Created by rsh on 2018/7/4. * 豆瓣-单个电影具体信息 * https://developers.douban.com/wiki/?title=movie_v2 */ @Data public class OneSubject implements Serializable { private Rating rating;//评分 private int reviews_count;//影评 <SUF> private int wish_count;//想看人数 private String douban_site;//豆瓣小站 private String year;//年代 private HashMap<String,String> images;//电影海报图 private String alt;//条目页URL private String id;//条目id private String mobile_url;//移动版条目页id private String title;//中文名 private String do_count;//再看人数。如果是电视剧,默认为0,如果是电影值为null private String share_url;// private String seasons_count;//总季数 private String schedule_url;//影讯页URL private String episodes_count;//当前季的集数 private ArrayList<String> countries;//制片国家或地区 private ArrayList<String> genres;//影片类型 private int collect_count;// private ArrayList<Casts> casts;//主演 private String current_season;//当前季数 private String original_title;//原名 private String summary;//简介 private String subtype;//条目分类 private ArrayList<Directors> directors;//导演,数据结构为影人的简化描述 private int comment_count;//短评数量 private int rating_count;//评分人数 private ArrayList<String> aka;//又名 }
false
367
4
418
4
401
4
418
4
539
7
false
false
false
false
false
true
60195_15
package com.learn.music.view.home; import android.content.Context; import android.graphics.Color; import android.graphics.Typeface; import android.os.Bundle; import android.support.v4.view.ViewPager; import android.support.v4.widget.DrawerLayout; import android.util.Log; import android.view.Gravity; import android.view.View; import android.widget.ImageView; import com.alibaba.android.arouter.launcher.ARouter; import com.learn.music.R; import com.learn.music.constant.Constant; import com.learn.music.model.CHANNEL; import com.learn.music.model.login.LoginEvent; import com.learn.music.utils.UserManager; import com.learn.music.view.home.adpater.HomePagerAdapter; import com.learn.music.view.login.LoginActivity; import com.lib.audio.core.AudioController; import com.lib.audio.model.AudioBean; import com.lib.audio.utils.AudioHelper; import com.lib.image.loader.app.ImageLoaderManager; import com.lib.ui.base.BaseActivity; import com.lib.ui.pager_indictor.ScaleTransitionPagerTitleView; import com.lib.update.UpdateHelper; import net.lucode.hackware.magicindicator.MagicIndicator; import net.lucode.hackware.magicindicator.ViewPagerHelper; import net.lucode.hackware.magicindicator.buildins.commonnavigator.CommonNavigator; import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.CommonNavigatorAdapter; import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerIndicator; import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerTitleView; import net.lucode.hackware.magicindicator.buildins.commonnavigator.titles.SimplePagerTitleView; import org.greenrobot.eventbus.EventBus; import org.greenrobot.eventbus.Subscribe; import org.greenrobot.eventbus.ThreadMode; import java.util.ArrayList; public class HomeActivity extends BaseActivity implements View.OnClickListener{ private static final CHANNEL[] CHANNELS = new CHANNEL[]{CHANNEL.MY, CHANNEL.DISCORY,CHANNEL.FRIEND}; private DrawerLayout mDrawerLayout; private View mToggleView; private View mSearchView; private ViewPager mViewPager; private HomePagerAdapter mAdapter; private View mDrawerQrcodeView; private View mDrawerShareView; private View unLogginLayout; private ImageView mPhotoView; private ArrayList<AudioBean> mLists = new ArrayList<>(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_home); EventBus.getDefault().register(this); initView(); initData(); } private void initView() { mDrawerLayout = findViewById(R.id.drawer_layout); mToggleView = findViewById(R.id.toggle_view); mToggleView.setOnClickListener(this); mSearchView = findViewById(R.id.search_view); mSearchView.setOnClickListener(this); //初始化adpater mAdapter = new HomePagerAdapter(getSupportFragmentManager(), CHANNELS); mViewPager = findViewById(R.id.view_pager); mViewPager.setAdapter(mAdapter); initMagicIndicator(); unLogginLayout = findViewById(R.id.unloggin_layout); unLogginLayout.setOnClickListener(this); mPhotoView = findViewById(R.id.avatr_view); findViewById(R.id.exit_layout).setOnClickListener(this); findViewById(R.id.check_update_view).setOnClickListener(this); mDrawerShareView = findViewById(R.id.home_music); mDrawerShareView.setOnClickListener(this); findViewById(R.id.online_music_view).setOnClickListener(this); } private void initData() { mLists.add(new AudioBean("100001", "http://sp-sycdn.kuwo.cn/resource/n2/85/58/433900159.mp3", "以你的名字喊我", "周杰伦", "七里香", "电影《不能说的秘密》主题曲,尤其以最美的不是下雨天,是与你一起躲过雨的屋檐最为经典", "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1559698076304&di=e6e99aa943b72ef57b97f0be3e0d2446&imgtype=0&src=http%3A%2F%2Fb-ssl.duitang.com%2Fuploads%2Fblog%2F201401%2F04%2F20140104170315_XdG38.jpeg", "4:30")); mLists.add( new AudioBean("100002", "http://sq-sycdn.kuwo.cn/resource/n1/98/51/3777061809.mp3", "勇气", "梁静茹", "勇气", "电影《不能说的秘密》主题曲,尤其以最美的不是下雨天,是与你一起躲过雨的屋檐最为经典", "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1559698193627&di=711751f16fefddbf4cbf71da7d8e6d66&imgtype=jpg&src=http%3A%2F%2Fimg0.imgtn.bdimg.com%2Fit%2Fu%3D213168965%2C1040740194%26fm%3D214%26gp%3D0.jpg", "4:40")); mLists.add( new AudioBean("100003", "http://sp-sycdn.kuwo.cn/resource/n2/52/80/2933081485.mp3", "灿烂如你", "汪峰", "春天里", "电影《不能说的秘密》主题曲,尤其以最美的不是下雨天,是与你一起躲过雨的屋檐最为经典", "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1559698239736&di=3433a1d95c589e31a36dd7b4c176d13a&imgtype=0&src=http%3A%2F%2Fpic.zdface.com%2Fupload%2F201051814737725.jpg", "3:20")); mLists.add( new AudioBean("100004", "http://sr-sycdn.kuwo.cn/resource/n2/33/25/2629654819.mp3", "小情歌", "五月天", "小幸运", "电影《不能说的秘密》主题曲,尤其以最美的不是下雨天,是与你一起躲过雨的屋檐最为经典", "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1559698289780&di=5146d48002250bf38acfb4c9b4bb6e4e&imgtype=0&src=http%3A%2F%2Fpic.baike.soso.com%2Fp%2F20131220%2Fbki-20131220170401-1254350944.jpg", "2:45")); // AudioHelper.startMusicService(mLists); AudioController.getInstance().setQueue(mLists); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.exit_layout: finish(); System.exit(0); break; case R.id.unloggin_layout: if (!UserManager.getInstance().hasLogined()) { LoginActivity.start(this); } else { mDrawerLayout.closeDrawer(Gravity.LEFT); } break; case R.id.toggle_view: if (mDrawerLayout.isDrawerOpen(Gravity.LEFT)) { mDrawerLayout.closeDrawer(Gravity.LEFT); } else { mDrawerLayout.openDrawer(Gravity.LEFT); } break; case R.id.check_update_view: checkUpdate(); break; case R.id.home_music: //shareFriend(); goToMusic(); break; case R.id.online_music_view: //跳到指定webactivity gotoWebView("https://www.imooc.com"); break; } } // 初始化指示器 private void initMagicIndicator() { MagicIndicator magicIndicator = findViewById(R.id.magic_indicator); magicIndicator.setBackgroundColor(Color.WHITE); CommonNavigator commonNavigator = new CommonNavigator(this); commonNavigator.setAdjustMode(true); commonNavigator.setAdapter(new CommonNavigatorAdapter() { @Override public int getCount() { return CHANNELS == null ? 0 : CHANNELS.length; } @Override public IPagerTitleView getTitleView(Context context, final int index) { SimplePagerTitleView simplePagerTitleView = new ScaleTransitionPagerTitleView(context); simplePagerTitleView.setText(CHANNELS[index].getKey()); simplePagerTitleView.setTextSize(19); simplePagerTitleView.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD)); simplePagerTitleView.setNormalColor(Color.parseColor("#999999")); simplePagerTitleView.setSelectedColor(Color.parseColor("#333333")); simplePagerTitleView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mViewPager.setCurrentItem(index); } }); return simplePagerTitleView; } @Override public IPagerIndicator getIndicator(Context context) { return null; } @Override public float getTitleWeight(Context context, int index) { return 1.0f; } }); magicIndicator.setNavigator(commonNavigator); ViewPagerHelper.bind(magicIndicator, mViewPager); } /** * 处理登陆事件 */ @Subscribe(threadMode = ThreadMode.MAIN) public void onLoginEvent(LoginEvent event) { unLogginLayout.setVisibility(View.GONE); mPhotoView.setVisibility(View.VISIBLE); ImageLoaderManager.getInstance() .displayImageForCircle(mPhotoView, UserManager.getInstance().getUser().data.photoUrl); } @Override protected void onDestroy() { super.onDestroy(); EventBus.getDefault().unregister(this); } //启动检查更新 private void checkUpdate() { UpdateHelper.checkUpdate(this); } private void goToMusic() { ARouter.getInstance().build(Constant.Router.ROUTER_MUSIC_ACTIVIYT).navigation(); } private void gotoWebView(String url) { ARouter.getInstance() .build(Constant.Router.ROUTER_WEB_ACTIVIYT) .withString("url", url) .navigation(); } }
RenZhongrui/android-learn
006_android_music/app_music/src/main/java/com/learn/music/view/home/HomeActivity.java
2,912
//启动检查更新
line_comment
zh-cn
package com.learn.music.view.home; import android.content.Context; import android.graphics.Color; import android.graphics.Typeface; import android.os.Bundle; import android.support.v4.view.ViewPager; import android.support.v4.widget.DrawerLayout; import android.util.Log; import android.view.Gravity; import android.view.View; import android.widget.ImageView; import com.alibaba.android.arouter.launcher.ARouter; import com.learn.music.R; import com.learn.music.constant.Constant; import com.learn.music.model.CHANNEL; import com.learn.music.model.login.LoginEvent; import com.learn.music.utils.UserManager; import com.learn.music.view.home.adpater.HomePagerAdapter; import com.learn.music.view.login.LoginActivity; import com.lib.audio.core.AudioController; import com.lib.audio.model.AudioBean; import com.lib.audio.utils.AudioHelper; import com.lib.image.loader.app.ImageLoaderManager; import com.lib.ui.base.BaseActivity; import com.lib.ui.pager_indictor.ScaleTransitionPagerTitleView; import com.lib.update.UpdateHelper; import net.lucode.hackware.magicindicator.MagicIndicator; import net.lucode.hackware.magicindicator.ViewPagerHelper; import net.lucode.hackware.magicindicator.buildins.commonnavigator.CommonNavigator; import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.CommonNavigatorAdapter; import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerIndicator; import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerTitleView; import net.lucode.hackware.magicindicator.buildins.commonnavigator.titles.SimplePagerTitleView; import org.greenrobot.eventbus.EventBus; import org.greenrobot.eventbus.Subscribe; import org.greenrobot.eventbus.ThreadMode; import java.util.ArrayList; public class HomeActivity extends BaseActivity implements View.OnClickListener{ private static final CHANNEL[] CHANNELS = new CHANNEL[]{CHANNEL.MY, CHANNEL.DISCORY,CHANNEL.FRIEND}; private DrawerLayout mDrawerLayout; private View mToggleView; private View mSearchView; private ViewPager mViewPager; private HomePagerAdapter mAdapter; private View mDrawerQrcodeView; private View mDrawerShareView; private View unLogginLayout; private ImageView mPhotoView; private ArrayList<AudioBean> mLists = new ArrayList<>(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_home); EventBus.getDefault().register(this); initView(); initData(); } private void initView() { mDrawerLayout = findViewById(R.id.drawer_layout); mToggleView = findViewById(R.id.toggle_view); mToggleView.setOnClickListener(this); mSearchView = findViewById(R.id.search_view); mSearchView.setOnClickListener(this); //初始化adpater mAdapter = new HomePagerAdapter(getSupportFragmentManager(), CHANNELS); mViewPager = findViewById(R.id.view_pager); mViewPager.setAdapter(mAdapter); initMagicIndicator(); unLogginLayout = findViewById(R.id.unloggin_layout); unLogginLayout.setOnClickListener(this); mPhotoView = findViewById(R.id.avatr_view); findViewById(R.id.exit_layout).setOnClickListener(this); findViewById(R.id.check_update_view).setOnClickListener(this); mDrawerShareView = findViewById(R.id.home_music); mDrawerShareView.setOnClickListener(this); findViewById(R.id.online_music_view).setOnClickListener(this); } private void initData() { mLists.add(new AudioBean("100001", "http://sp-sycdn.kuwo.cn/resource/n2/85/58/433900159.mp3", "以你的名字喊我", "周杰伦", "七里香", "电影《不能说的秘密》主题曲,尤其以最美的不是下雨天,是与你一起躲过雨的屋檐最为经典", "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1559698076304&di=e6e99aa943b72ef57b97f0be3e0d2446&imgtype=0&src=http%3A%2F%2Fb-ssl.duitang.com%2Fuploads%2Fblog%2F201401%2F04%2F20140104170315_XdG38.jpeg", "4:30")); mLists.add( new AudioBean("100002", "http://sq-sycdn.kuwo.cn/resource/n1/98/51/3777061809.mp3", "勇气", "梁静茹", "勇气", "电影《不能说的秘密》主题曲,尤其以最美的不是下雨天,是与你一起躲过雨的屋檐最为经典", "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1559698193627&di=711751f16fefddbf4cbf71da7d8e6d66&imgtype=jpg&src=http%3A%2F%2Fimg0.imgtn.bdimg.com%2Fit%2Fu%3D213168965%2C1040740194%26fm%3D214%26gp%3D0.jpg", "4:40")); mLists.add( new AudioBean("100003", "http://sp-sycdn.kuwo.cn/resource/n2/52/80/2933081485.mp3", "灿烂如你", "汪峰", "春天里", "电影《不能说的秘密》主题曲,尤其以最美的不是下雨天,是与你一起躲过雨的屋檐最为经典", "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1559698239736&di=3433a1d95c589e31a36dd7b4c176d13a&imgtype=0&src=http%3A%2F%2Fpic.zdface.com%2Fupload%2F201051814737725.jpg", "3:20")); mLists.add( new AudioBean("100004", "http://sr-sycdn.kuwo.cn/resource/n2/33/25/2629654819.mp3", "小情歌", "五月天", "小幸运", "电影《不能说的秘密》主题曲,尤其以最美的不是下雨天,是与你一起躲过雨的屋檐最为经典", "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1559698289780&di=5146d48002250bf38acfb4c9b4bb6e4e&imgtype=0&src=http%3A%2F%2Fpic.baike.soso.com%2Fp%2F20131220%2Fbki-20131220170401-1254350944.jpg", "2:45")); // AudioHelper.startMusicService(mLists); AudioController.getInstance().setQueue(mLists); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.exit_layout: finish(); System.exit(0); break; case R.id.unloggin_layout: if (!UserManager.getInstance().hasLogined()) { LoginActivity.start(this); } else { mDrawerLayout.closeDrawer(Gravity.LEFT); } break; case R.id.toggle_view: if (mDrawerLayout.isDrawerOpen(Gravity.LEFT)) { mDrawerLayout.closeDrawer(Gravity.LEFT); } else { mDrawerLayout.openDrawer(Gravity.LEFT); } break; case R.id.check_update_view: checkUpdate(); break; case R.id.home_music: //shareFriend(); goToMusic(); break; case R.id.online_music_view: //跳到指定webactivity gotoWebView("https://www.imooc.com"); break; } } // 初始化指示器 private void initMagicIndicator() { MagicIndicator magicIndicator = findViewById(R.id.magic_indicator); magicIndicator.setBackgroundColor(Color.WHITE); CommonNavigator commonNavigator = new CommonNavigator(this); commonNavigator.setAdjustMode(true); commonNavigator.setAdapter(new CommonNavigatorAdapter() { @Override public int getCount() { return CHANNELS == null ? 0 : CHANNELS.length; } @Override public IPagerTitleView getTitleView(Context context, final int index) { SimplePagerTitleView simplePagerTitleView = new ScaleTransitionPagerTitleView(context); simplePagerTitleView.setText(CHANNELS[index].getKey()); simplePagerTitleView.setTextSize(19); simplePagerTitleView.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD)); simplePagerTitleView.setNormalColor(Color.parseColor("#999999")); simplePagerTitleView.setSelectedColor(Color.parseColor("#333333")); simplePagerTitleView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mViewPager.setCurrentItem(index); } }); return simplePagerTitleView; } @Override public IPagerIndicator getIndicator(Context context) { return null; } @Override public float getTitleWeight(Context context, int index) { return 1.0f; } }); magicIndicator.setNavigator(commonNavigator); ViewPagerHelper.bind(magicIndicator, mViewPager); } /** * 处理登陆事件 */ @Subscribe(threadMode = ThreadMode.MAIN) public void onLoginEvent(LoginEvent event) { unLogginLayout.setVisibility(View.GONE); mPhotoView.setVisibility(View.VISIBLE); ImageLoaderManager.getInstance() .displayImageForCircle(mPhotoView, UserManager.getInstance().getUser().data.photoUrl); } @Override protected void onDestroy() { super.onDestroy(); EventBus.getDefault().unregister(this); } //启动 <SUF> private void checkUpdate() { UpdateHelper.checkUpdate(this); } private void goToMusic() { ARouter.getInstance().build(Constant.Router.ROUTER_MUSIC_ACTIVIYT).navigation(); } private void gotoWebView(String url) { ARouter.getInstance() .build(Constant.Router.ROUTER_WEB_ACTIVIYT) .withString("url", url) .navigation(); } }
false
2,407
4
2,912
4
2,929
4
2,912
4
3,368
11
false
false
false
false
false
true
35571_5
import java.util.*; import java.io.*; class Main { public static void main(String[] args) throws Exception { PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out)); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int[] in = read(br); int N = in[0], C = in[1]; var op = new int[N][2]; for (int i = 0; i < N; i++) { op[i] = read(br); } var res = new int[N+1]; // f[i][j],当前位初始为j(0/1) 经历 i 次操作后的结果 var f = new int[N+1][2]; f[0][0] = 0; f[0][1] = 1; // 枚举每一位 for (int i = 0; i < 30; i++) { int cur = (C>>>i) & 1; // 枚举每种操作 for (int j = 1; j <= N; j++) { int t = op[j-1][0], a = op[j-1][1]; int x = (a>>>i) & 1; if (t == 1) { f[j] = new int[]{ f[j-1][0] & x, f[j-1][1] & x}; } if (t == 2) { f[j] = new int[]{ f[j-1][0] | x, f[j-1][1] | x}; } if (t == 3) { f[j] = new int[]{ f[j-1][0] ^ x, f[j-1][1] ^ x}; } // 初始为cur,经历j次操作后的值(重放) cur = f[j][cur]; res[j] |= (cur<<i); } } for (int i = 1; i <= N; i++) { out.println(res[i]); } out.flush(); } public static int[] read(BufferedReader br) throws Exception { return Arrays.stream(br.readLine().split(" ")).mapToInt(Integer::parseInt).toArray(); } } // AtCoder/AcWing 提交上面部分即可,CF需要将JavaMain移到上面然后提交 public class E { public static void main(String[] args) throws Exception{ // 输入重定向,通过jvm参数判断环境 if (args.length > 0 && "Resolmi_DEBUG".equals(args[0])) { System.setIn(new FileInputStream("./input.txt")); } new Main().main(args); } }
Reso1mi/competition-algorithm
比赛/AtCoder/abc261/E.java
643
// 输入重定向,通过jvm参数判断环境
line_comment
zh-cn
import java.util.*; import java.io.*; class Main { public static void main(String[] args) throws Exception { PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out)); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int[] in = read(br); int N = in[0], C = in[1]; var op = new int[N][2]; for (int i = 0; i < N; i++) { op[i] = read(br); } var res = new int[N+1]; // f[i][j],当前位初始为j(0/1) 经历 i 次操作后的结果 var f = new int[N+1][2]; f[0][0] = 0; f[0][1] = 1; // 枚举每一位 for (int i = 0; i < 30; i++) { int cur = (C>>>i) & 1; // 枚举每种操作 for (int j = 1; j <= N; j++) { int t = op[j-1][0], a = op[j-1][1]; int x = (a>>>i) & 1; if (t == 1) { f[j] = new int[]{ f[j-1][0] & x, f[j-1][1] & x}; } if (t == 2) { f[j] = new int[]{ f[j-1][0] | x, f[j-1][1] | x}; } if (t == 3) { f[j] = new int[]{ f[j-1][0] ^ x, f[j-1][1] ^ x}; } // 初始为cur,经历j次操作后的值(重放) cur = f[j][cur]; res[j] |= (cur<<i); } } for (int i = 1; i <= N; i++) { out.println(res[i]); } out.flush(); } public static int[] read(BufferedReader br) throws Exception { return Arrays.stream(br.readLine().split(" ")).mapToInt(Integer::parseInt).toArray(); } } // AtCoder/AcWing 提交上面部分即可,CF需要将JavaMain移到上面然后提交 public class E { public static void main(String[] args) throws Exception{ // 输入 <SUF> if (args.length > 0 && "Resolmi_DEBUG".equals(args[0])) { System.setIn(new FileInputStream("./input.txt")); } new Main().main(args); } }
false
591
11
643
12
683
10
643
12
761
22
false
false
false
false
false
true
15829_1
package top.retain.nd.common; public enum StatusCode { //成功 SUCCESS(200, "请求成功"), //客户端 SYNTAX_ERROR(400, "客户端请求语法错误"), UN_AUTHORIZED(401, "用户未认证"), NO_PERMISSION(403, "权限不足"), NOT_FOUND(404, "未找到相关资源"), METHOD_ERROR(405, "请求方法错误"), UNKNOWN_USERNAME(410, "用户名未找到"), WRONG_USERNAME_OR_PASSWORD(411, "用户名或密码错误"), CODE_WRONG(411, "验证码错误"), USER_DISABLED(412, "用户已被禁用"), USER_LOCKED(413, "用户已被锁定"), NO_ACTION_JOIN(414, "用户未参与任何行动"), USER_NOT_BINDING(415, "用户未绑定"), VERIFY_CODE_ERROR(416, "验证码错误"), MISSING_PARAM(417, "参数不足"), UPLOAD_FAIL(445, "上传失败"), FILE_EXSIT(422, "文件夹已存在"), //服务端错误 INTERNAL_SERVER_ERROR(500, "服务器内部错误"); private final int code; private final String msg; private final Class<? extends Exception> exceptionClass; StatusCode(int code, String msg) { this.code = code; this.msg = msg; this.exceptionClass = Exception.class; } StatusCode(int code, String msg, Class<? extends Exception> exceptionClass) { this.code = code; this.msg = msg; this.exceptionClass = exceptionClass; } public int getCode() { return code; } public String getMsg() { return msg; } public Class<? extends Exception> getExceptionClass() { return exceptionClass; } }
Retainv/cloud-disk-based-on-oss
src/main/java/top/retain/nd/common/StatusCode.java
454
//服务端错误
line_comment
zh-cn
package top.retain.nd.common; public enum StatusCode { //成功 SUCCESS(200, "请求成功"), //客户端 SYNTAX_ERROR(400, "客户端请求语法错误"), UN_AUTHORIZED(401, "用户未认证"), NO_PERMISSION(403, "权限不足"), NOT_FOUND(404, "未找到相关资源"), METHOD_ERROR(405, "请求方法错误"), UNKNOWN_USERNAME(410, "用户名未找到"), WRONG_USERNAME_OR_PASSWORD(411, "用户名或密码错误"), CODE_WRONG(411, "验证码错误"), USER_DISABLED(412, "用户已被禁用"), USER_LOCKED(413, "用户已被锁定"), NO_ACTION_JOIN(414, "用户未参与任何行动"), USER_NOT_BINDING(415, "用户未绑定"), VERIFY_CODE_ERROR(416, "验证码错误"), MISSING_PARAM(417, "参数不足"), UPLOAD_FAIL(445, "上传失败"), FILE_EXSIT(422, "文件夹已存在"), //服务 <SUF> INTERNAL_SERVER_ERROR(500, "服务器内部错误"); private final int code; private final String msg; private final Class<? extends Exception> exceptionClass; StatusCode(int code, String msg) { this.code = code; this.msg = msg; this.exceptionClass = Exception.class; } StatusCode(int code, String msg, Class<? extends Exception> exceptionClass) { this.code = code; this.msg = msg; this.exceptionClass = exceptionClass; } public int getCode() { return code; } public String getMsg() { return msg; } public Class<? extends Exception> getExceptionClass() { return exceptionClass; } }
false
408
4
454
4
481
4
454
4
642
10
false
false
false
false
false
true
43365_0
package com.leetcode.problemset; /** * 假设你有一个很长的花坛,一部分地块种植了花,另一部分却没有。可是,花卉不能种植在相邻的地块上,它们会争夺水源,两者都会死去。 * * 给定一个花坛(表示为一个数组包含0和1,其中0表示没种植花,1表示种植了花),和一个数 n 。能否在不打破种植规则的情况下种入 n 朵花?能则返回True,不能则返回False。 * * 来源:力扣(LeetCode) * 链接:https://leetcode-cn.com/problems/can-place-flowers * 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 * 输入: flowerbed = [1,0,0,0,1], n = 1 * 输出: True * * [0,0,1,0,1] * [0,0,0,1] * [1,0,0,1,0,0,0] * [1,0,0,0,1] */ public class Pro_605 { public static void main(String[] args) { int[] arr = new int[]{0,0,1,0,0}; System.out.println(canPlaceFlowers(arr,1)==true); arr = new int[]{1,0,0}; System.out.println(canPlaceFlowers(arr,1)==true); arr = new int[]{0,0,1}; System.out.println(canPlaceFlowers(arr,1)==true); arr = new int[]{1,0,0,1,0,0}; System.out.println(canPlaceFlowers(arr,1)==true); arr = new int[]{1,0,0,0,1}; System.out.println(canPlaceFlowers(arr,1)==true); arr = new int[]{1}; System.out.println(canPlaceFlowers(arr,1)==false); arr = new int[]{0}; System.out.println(canPlaceFlowers(arr,1)==true); } public static boolean canPlaceFlowers(int[] flowerbed, int n) { int i = 0,count=0; int len = flowerbed.length; while (i<len){ if (flowerbed[i]==0 && (i==0||flowerbed[i-1]==0) && (i==len-1 || flowerbed[i+1]==0)){ flowerbed[i]=1; count++; } i++; } return count==n; } }
RevelationCollection/study
study-jdk/src/main/java/com/leetcode/problemset/Pro_605.java
666
/** * 假设你有一个很长的花坛,一部分地块种植了花,另一部分却没有。可是,花卉不能种植在相邻的地块上,它们会争夺水源,两者都会死去。 * * 给定一个花坛(表示为一个数组包含0和1,其中0表示没种植花,1表示种植了花),和一个数 n 。能否在不打破种植规则的情况下种入 n 朵花?能则返回True,不能则返回False。 * * 来源:力扣(LeetCode) * 链接:https://leetcode-cn.com/problems/can-place-flowers * 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 * 输入: flowerbed = [1,0,0,0,1], n = 1 * 输出: True * * [0,0,1,0,1] * [0,0,0,1] * [1,0,0,1,0,0,0] * [1,0,0,0,1] */
block_comment
zh-cn
package com.leetcode.problemset; /** * 假设你 <SUF>*/ public class Pro_605 { public static void main(String[] args) { int[] arr = new int[]{0,0,1,0,0}; System.out.println(canPlaceFlowers(arr,1)==true); arr = new int[]{1,0,0}; System.out.println(canPlaceFlowers(arr,1)==true); arr = new int[]{0,0,1}; System.out.println(canPlaceFlowers(arr,1)==true); arr = new int[]{1,0,0,1,0,0}; System.out.println(canPlaceFlowers(arr,1)==true); arr = new int[]{1,0,0,0,1}; System.out.println(canPlaceFlowers(arr,1)==true); arr = new int[]{1}; System.out.println(canPlaceFlowers(arr,1)==false); arr = new int[]{0}; System.out.println(canPlaceFlowers(arr,1)==true); } public static boolean canPlaceFlowers(int[] flowerbed, int n) { int i = 0,count=0; int len = flowerbed.length; while (i<len){ if (flowerbed[i]==0 && (i==0||flowerbed[i-1]==0) && (i==len-1 || flowerbed[i+1]==0)){ flowerbed[i]=1; count++; } i++; } return count==n; } }
false
563
238
666
295
642
254
666
295
799
385
false
false
false
false
false
true
19104_34
package com.proxgrind.chameleon.xmodem; import android.util.Log; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import com.proxgrind.chameleon.posixio.PosixCom; import com.proxgrind.chameleon.utils.tools.HexUtil; import com.proxgrind.chameleon.utils.system.LogUtils; import com.proxgrind.chameleon.utils.system.SystemUtils; /** * @author DXL * @version 1.1 */ public class XModem128 extends AbstractXModem { // 开始 private byte SOH = 0x01; // 超时 private final int TIMEOUT = 1000; public XModem128(PosixCom com) { super(com); } final byte calcChecksum(byte[] datas, int count) { byte checksum = 0; int pos = 0; while (count-- != 0) { checksum += datas[pos++]; } return checksum; } @Override public boolean send(InputStream sources) throws IOException { // 错误包数 int errorCount; // 包序号 byte blockNumber = 0x01; // 读取到缓冲区的字节数量 int nbytes; // 初始化数据缓冲区 byte[] sector = new byte[mBlockSize]; /*if (read(3000) != mNAK) { LogUtils.d("接收端没有NAK回复发起接收"); return false; }*/ // 读取字节初始化 while ((nbytes = sources.read(sector)) > 0) { // 如果最后一包数据小于128个字节,以0xff补齐 if (nbytes < mBlockSize) { for (int i = nbytes; i < mBlockSize; i++) { sector[i] = (byte) 0x1A; } } // 同一包数据最多发送10次 errorCount = 0; while (errorCount < mErrorMax) { // 不分包且一次性发送! ByteArrayOutputStream buffer = new ByteArrayOutputStream(); buffer.write(SOH); buffer.write(blockNumber); buffer.write((255 - blockNumber)); buffer.write(sector); buffer.write(calcChecksum(sector, sector.length)); mCom.write(buffer.toByteArray(), 0, buffer.size(), TIMEOUT); flush(); //6、刷新缓冲区,发送数据! // 获取应答数据 byte data = read(TIMEOUT); // 如果收到应答数据则跳出循环,发送下一包数据 // 未收到应答,错误包数+1,继续重发 if (data == mNAK) { Log.d(LOG_TAG, "NAK已收到,将会无条件重新传输!"); //重传! ++errorCount; } else if (data == mCAN) { //终止命令! Log.d(LOG_TAG, "CAN已收到,将会无条件结束发送!"); return false; } else if (data == mACK) { Log.d(LOG_TAG, "ACK已收到,可以进行下一轮发送!"); break; } else { Log.d(LOG_TAG, "未知的值: " + HexUtil.toHexString(data)); //重传! ++errorCount; } } // 包序号自增 blockNumber = (byte) ((++blockNumber) % 256); } boolean isAck = false; while (!isAck) { write(mEOT, TIMEOUT); isAck = read(TIMEOUT) == mACK; } // 接收与发送一个字节,告知结束发送! return true; } @Override public boolean recv(OutputStream target) throws IOException { // 错误包数 int errorCount = 0; // 包序号 byte blocknumber = 0x01; // 数据 byte data; // 校验和 int checkSum; // 初始化数据缓冲区 byte[] sector = new byte[mBlockSize]; // 握手,发起传输! write(mNAK, TIMEOUT); while (true) { if (errorCount > mErrorMax) { LogUtils.d("错误重试次数已达上限!"); return false; } // 获取应答数据 data = read(TIMEOUT); if (data == -1) { LogUtils.d("收到 -1,可能无数据或者读取超时了。"); return false; } if (data == SOH) { try { // 获取包序号 data = read(TIMEOUT); // 获取包序号的反码 byte _blocknumber = read(TIMEOUT); //Log.d(LOG_TAG, "包序号: " + data); //Log.d(LOG_TAG, "包序号的反码: " + _blocknumber); // 判断包序号是否正确 if (data != blocknumber) { LogUtils.d("包序号不正常!"); errorCount++; continue; } // 判断包序号的反码是否正确 if (data + _blocknumber != (byte) 255) { LogUtils.d("包序号的反码不正常!"); errorCount++; continue; } // 获取数据 for (int i = 0; i < mBlockSize; i++) { sector[i] = read(TIMEOUT); } //Log.d(LOG_TAG, "获取到的数据: " + HexUtil.toHexString(sector)); // 获取校验和 checkSum = read(TIMEOUT); //Log.d(LOG_TAG, "接收到的校验和: " + checkSum); // 判断校验和是否正确 int crc = SystemUtils.calcChecksum(sector, false); //Log.d(LOG_TAG, "计算到的校验和: " + crc); if (crc != checkSum) { LogUtils.d("包数据的校验不正常!"); errorCount++; continue; } //Log.d(LOG_TAG, "接收一帧完成!"); // 发送应答 write(mACK, TIMEOUT); // 包序号自增 blocknumber++; // 将数据写入本地 target.write(sector); // 错误包数归零 errorCount = 0; } catch (Exception e) { e.printStackTrace(); } finally { // 如果出错发送重传标识 if (errorCount != 0) { Log.d(LOG_TAG, "错误,将发送重传标志!"); write(mNAK, TIMEOUT); } } } else if (data == mEOT) { LogUtils.d("收到0x04 EOT码,结束传输!"); write(mACK, TIMEOUT); return true; } else { LogUtils.d("未知回复: " + HexUtil.toHexString(data)); return false; } } } }
RfidResearchGroup/ChameleonBLEAPI
appmain/xmodem/XModem128.java
1,667
// 获取数据
line_comment
zh-cn
package com.proxgrind.chameleon.xmodem; import android.util.Log; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import com.proxgrind.chameleon.posixio.PosixCom; import com.proxgrind.chameleon.utils.tools.HexUtil; import com.proxgrind.chameleon.utils.system.LogUtils; import com.proxgrind.chameleon.utils.system.SystemUtils; /** * @author DXL * @version 1.1 */ public class XModem128 extends AbstractXModem { // 开始 private byte SOH = 0x01; // 超时 private final int TIMEOUT = 1000; public XModem128(PosixCom com) { super(com); } final byte calcChecksum(byte[] datas, int count) { byte checksum = 0; int pos = 0; while (count-- != 0) { checksum += datas[pos++]; } return checksum; } @Override public boolean send(InputStream sources) throws IOException { // 错误包数 int errorCount; // 包序号 byte blockNumber = 0x01; // 读取到缓冲区的字节数量 int nbytes; // 初始化数据缓冲区 byte[] sector = new byte[mBlockSize]; /*if (read(3000) != mNAK) { LogUtils.d("接收端没有NAK回复发起接收"); return false; }*/ // 读取字节初始化 while ((nbytes = sources.read(sector)) > 0) { // 如果最后一包数据小于128个字节,以0xff补齐 if (nbytes < mBlockSize) { for (int i = nbytes; i < mBlockSize; i++) { sector[i] = (byte) 0x1A; } } // 同一包数据最多发送10次 errorCount = 0; while (errorCount < mErrorMax) { // 不分包且一次性发送! ByteArrayOutputStream buffer = new ByteArrayOutputStream(); buffer.write(SOH); buffer.write(blockNumber); buffer.write((255 - blockNumber)); buffer.write(sector); buffer.write(calcChecksum(sector, sector.length)); mCom.write(buffer.toByteArray(), 0, buffer.size(), TIMEOUT); flush(); //6、刷新缓冲区,发送数据! // 获取应答数据 byte data = read(TIMEOUT); // 如果收到应答数据则跳出循环,发送下一包数据 // 未收到应答,错误包数+1,继续重发 if (data == mNAK) { Log.d(LOG_TAG, "NAK已收到,将会无条件重新传输!"); //重传! ++errorCount; } else if (data == mCAN) { //终止命令! Log.d(LOG_TAG, "CAN已收到,将会无条件结束发送!"); return false; } else if (data == mACK) { Log.d(LOG_TAG, "ACK已收到,可以进行下一轮发送!"); break; } else { Log.d(LOG_TAG, "未知的值: " + HexUtil.toHexString(data)); //重传! ++errorCount; } } // 包序号自增 blockNumber = (byte) ((++blockNumber) % 256); } boolean isAck = false; while (!isAck) { write(mEOT, TIMEOUT); isAck = read(TIMEOUT) == mACK; } // 接收与发送一个字节,告知结束发送! return true; } @Override public boolean recv(OutputStream target) throws IOException { // 错误包数 int errorCount = 0; // 包序号 byte blocknumber = 0x01; // 数据 byte data; // 校验和 int checkSum; // 初始化数据缓冲区 byte[] sector = new byte[mBlockSize]; // 握手,发起传输! write(mNAK, TIMEOUT); while (true) { if (errorCount > mErrorMax) { LogUtils.d("错误重试次数已达上限!"); return false; } // 获取应答数据 data = read(TIMEOUT); if (data == -1) { LogUtils.d("收到 -1,可能无数据或者读取超时了。"); return false; } if (data == SOH) { try { // 获取包序号 data = read(TIMEOUT); // 获取包序号的反码 byte _blocknumber = read(TIMEOUT); //Log.d(LOG_TAG, "包序号: " + data); //Log.d(LOG_TAG, "包序号的反码: " + _blocknumber); // 判断包序号是否正确 if (data != blocknumber) { LogUtils.d("包序号不正常!"); errorCount++; continue; } // 判断包序号的反码是否正确 if (data + _blocknumber != (byte) 255) { LogUtils.d("包序号的反码不正常!"); errorCount++; continue; } // 获取 <SUF> for (int i = 0; i < mBlockSize; i++) { sector[i] = read(TIMEOUT); } //Log.d(LOG_TAG, "获取到的数据: " + HexUtil.toHexString(sector)); // 获取校验和 checkSum = read(TIMEOUT); //Log.d(LOG_TAG, "接收到的校验和: " + checkSum); // 判断校验和是否正确 int crc = SystemUtils.calcChecksum(sector, false); //Log.d(LOG_TAG, "计算到的校验和: " + crc); if (crc != checkSum) { LogUtils.d("包数据的校验不正常!"); errorCount++; continue; } //Log.d(LOG_TAG, "接收一帧完成!"); // 发送应答 write(mACK, TIMEOUT); // 包序号自增 blocknumber++; // 将数据写入本地 target.write(sector); // 错误包数归零 errorCount = 0; } catch (Exception e) { e.printStackTrace(); } finally { // 如果出错发送重传标识 if (errorCount != 0) { Log.d(LOG_TAG, "错误,将发送重传标志!"); write(mNAK, TIMEOUT); } } } else if (data == mEOT) { LogUtils.d("收到0x04 EOT码,结束传输!"); write(mACK, TIMEOUT); return true; } else { LogUtils.d("未知回复: " + HexUtil.toHexString(data)); return false; } } } }
false
1,562
4
1,659
4
1,736
4
1,659
4
2,203
7
false
false
false
false
false
true
7365_2
package play; import org.antlr.v4.runtime.ParserRuleContext; public class Variable extends Symbol { //变量类型 protected Type type = null; //// 作为parameter的变量的属性 //缺省值 protected Object defaultValue = null; //是否允许多次重复,这是一个创新的参数机制 protected Integer multiplicity = 1; protected Variable(String name, Scope enclosingScope, ParserRuleContext ctx) { this.name = name; this.enclosingScope = enclosingScope; this.ctx = ctx; } /** * 是不是类的属性 * @return */ public boolean isClassMember(){ return enclosingScope instanceof Class; } @Override public String toString(){ return "Variable " + name + " -> "+ type; } }
RichardGong/PlayWithCompiler
playscript-java/src/main/play/Variable.java
182
//缺省值
line_comment
zh-cn
package play; import org.antlr.v4.runtime.ParserRuleContext; public class Variable extends Symbol { //变量类型 protected Type type = null; //// 作为parameter的变量的属性 //缺省 <SUF> protected Object defaultValue = null; //是否允许多次重复,这是一个创新的参数机制 protected Integer multiplicity = 1; protected Variable(String name, Scope enclosingScope, ParserRuleContext ctx) { this.name = name; this.enclosingScope = enclosingScope; this.ctx = ctx; } /** * 是不是类的属性 * @return */ public boolean isClassMember(){ return enclosingScope instanceof Class; } @Override public String toString(){ return "Variable " + name + " -> "+ type; } }
false
175
4
182
4
201
4
182
4
247
6
false
false
false
false
false
true
61231_0
diff --git a/sharding-jdbc-core/src/main/java/com/dangdang/ddframe/rdb/sharding/router/SQLRouteEngine.java b/sharding-jdbc-core/src/main/java/com/dangdang/ddframe/rdb/sharding/router/SQLRouteEngine.java index 6aa9ec2..a108151 100644 --- a/sharding-jdbc-core/src/main/java/com/dangdang/ddframe/rdb/sharding/router/SQLRouteEngine.java +++ b/sharding-jdbc-core/src/main/java/com/dangdang/ddframe/rdb/sharding/router/SQLRouteEngine.java @@ -97,7 +97,7 @@ private SQLParsedResult buildHintParsedResult(final String logicSql) { SQLParsedResult result = new SQLParsedResult(SQLUtil.getTypeByStart(logicSql), new ConditionContext()); - log.trace("Get {} SQL Statement", result.getSqlType()); + log.trace("Get {} SQL Statement", result.getType()); SQLBuilder sqlBuilder = new SQLBuilder(); sqlBuilder.append(logicSql); result.setSqlBuilder(sqlBuilder); @@ -120,7 +120,7 @@ private RoutingResult routeSQL(final ConditionContext conditionContext, final SQLParsedResult parsedResult) { if (HintManagerHolder.isDatabaseShardingOnly()) { - return new DatabaseRouter(shardingRule.getDataSourceRule(), shardingRule.getDatabaseShardingStrategy(), parsedResult.getSqlType()).route(); + return new DatabaseRouter(shardingRule.getDataSourceRule(), shardingRule.getDatabaseShardingStrategy(), parsedResult.getType()).route(); } Set<String> logicTables = Sets.newLinkedHashSet(Collections2.transform(parsedResult.getTables(), new Function<TableContext, String>() { @@ -130,13 +130,13 @@ } })); if (1 == logicTables.size()) { - return new SingleTableRouter(shardingRule, logicTables.iterator().next(), conditionContext, parsedResult.getSqlType()).route(); + return new SingleTableRouter(shardingRule, logicTables.iterator().next(), conditionContext, parsedResult.getType()).route(); } if (shardingRule.isAllBindingTables(logicTables)) { - return new BindingTablesRouter(shardingRule, logicTables, conditionContext, parsedResult.getSqlType()).route(); + return new BindingTablesRouter(shardingRule, logicTables, conditionContext, parsedResult.getType()).route(); } // TODO 可配置是否执行笛卡尔积 - return new MixedTablesRouter(shardingRule, logicTables, conditionContext, parsedResult.getSqlType()).route(); + return new MixedTablesRouter(shardingRule, logicTables, conditionContext, parsedResult.getType()).route(); } private void amendSQLAccordingToRouteResult(final SQLParsedResult parsedResult, final List<Object> parameters, final SQLRouteResult sqlRouteResult) {
Ringbo/Cache
patches/Large/correct/Many/dangdangdotcom.sharding-jdbc/SQLRouteEngine/8c329.java
708
// TODO 可配置是否执行笛卡尔积
line_comment
zh-cn
diff --git a/sharding-jdbc-core/src/main/java/com/dangdang/ddframe/rdb/sharding/router/SQLRouteEngine.java b/sharding-jdbc-core/src/main/java/com/dangdang/ddframe/rdb/sharding/router/SQLRouteEngine.java index 6aa9ec2..a108151 100644 --- a/sharding-jdbc-core/src/main/java/com/dangdang/ddframe/rdb/sharding/router/SQLRouteEngine.java +++ b/sharding-jdbc-core/src/main/java/com/dangdang/ddframe/rdb/sharding/router/SQLRouteEngine.java @@ -97,7 +97,7 @@ private SQLParsedResult buildHintParsedResult(final String logicSql) { SQLParsedResult result = new SQLParsedResult(SQLUtil.getTypeByStart(logicSql), new ConditionContext()); - log.trace("Get {} SQL Statement", result.getSqlType()); + log.trace("Get {} SQL Statement", result.getType()); SQLBuilder sqlBuilder = new SQLBuilder(); sqlBuilder.append(logicSql); result.setSqlBuilder(sqlBuilder); @@ -120,7 +120,7 @@ private RoutingResult routeSQL(final ConditionContext conditionContext, final SQLParsedResult parsedResult) { if (HintManagerHolder.isDatabaseShardingOnly()) { - return new DatabaseRouter(shardingRule.getDataSourceRule(), shardingRule.getDatabaseShardingStrategy(), parsedResult.getSqlType()).route(); + return new DatabaseRouter(shardingRule.getDataSourceRule(), shardingRule.getDatabaseShardingStrategy(), parsedResult.getType()).route(); } Set<String> logicTables = Sets.newLinkedHashSet(Collections2.transform(parsedResult.getTables(), new Function<TableContext, String>() { @@ -130,13 +130,13 @@ } })); if (1 == logicTables.size()) { - return new SingleTableRouter(shardingRule, logicTables.iterator().next(), conditionContext, parsedResult.getSqlType()).route(); + return new SingleTableRouter(shardingRule, logicTables.iterator().next(), conditionContext, parsedResult.getType()).route(); } if (shardingRule.isAllBindingTables(logicTables)) { - return new BindingTablesRouter(shardingRule, logicTables, conditionContext, parsedResult.getSqlType()).route(); + return new BindingTablesRouter(shardingRule, logicTables, conditionContext, parsedResult.getType()).route(); } // TO <SUF> - return new MixedTablesRouter(shardingRule, logicTables, conditionContext, parsedResult.getSqlType()).route(); + return new MixedTablesRouter(shardingRule, logicTables, conditionContext, parsedResult.getType()).route(); } private void amendSQLAccordingToRouteResult(final SQLParsedResult parsedResult, final List<Object> parameters, final SQLRouteResult sqlRouteResult) {
false
624
10
708
11
736
10
708
11
798
22
false
false
false
false
false
true
19813_2
import java.util.*; public class BFS { static int[] goal = new int[30];//目标状态数组 static int[] fa = new int[20000000];//”父亲“编号数组 static int[] dist = new int[20000000];//距离数组 static int[][] st = new int[20000000][30];//过程状态数组 // static ArrayList<Integer> static int dx[] = {-1,1,0,0}; static int dy[] = {0,0,-1,1}; static int row = 0; static int line = 0; static Set<Integer> vis = new HashSet<Integer>();//存放没一步结果,防止回到原来已经走过的路。 public static void main(String[] args) { Scanner sc = new Scanner(System.in); row = sc.nextInt(); line = sc.nextInt(); for (int i = 0; i < row*line; i++) { st[1][i] = sc.nextInt(); } for (int i = 0; i < row*line; i++) { if (i == row*line-1){ goal[i] = 0; } else { goal[i] = i+1; } } int v=0; for (int i = 0; i < row*line; i++) {v=v*10+goal[i];} vis.add(v); int ans = bfs(); if(dist[ans]>0) { System.out.println(dist[ans]); } else System.out.println(0); int[][] process = new int[dist[ans]+1][row*line]; //本来dist[ans]为所需的步数, print(process,ans); } /* * 输出 结果 */ private static void print(int[][] process,int ans) { int i=dist[ans]+1; while(true) { process[--i] = st[ans]; if(ans==1) break; ans = fa[ans]; } for (int j = 0; j < process.length; j++) { for (int j2 = 0; j2 < row*line; j2++) { System.out.print(process[j][j2]+"\t"); if(j2%line==line-1) System.out.println(); } System.out.println(); } } /* * 返回 最终结果 fornt 堆首 或 0未找到 */ private static int bfs() { init_lookup_table(); int front=1,rear=2; while(front<rear) { int[] s = st[front]; if(Arrays.equals(s, goal)) { fa[rear] = front; return front;} int z; for ( z = 0; z < row*line; z++) if(s[z]==0) break; int x = z/line,y=z%line; for (int d = 0; d < 4; d++) { int newx = x+dx[d]; int newy = y+dy[d]; int newz = newx*line+newy; if(newx>=0&&newx<row&&newy>=0&&newy<line) { for (int i = 0; i <row*line; i++) st[rear][i] = s[i]; st[rear][newz] =s[z];//每次只有两个位置改变 st[rear][z] = s[newz]; dist[rear] = dist[front]+1;//再栈首的基础上加一 fa[rear] = front;//给任意一个 fornt,都能fornt = fa[fornt],构造过程 if(try_to_insert(rear)==1) rear++; }//end if }// end for front++; }//end while return 0; } /* * 初始化 */ private static void init_lookup_table() { vis.clear(); for (int i = 0; i < 20000000; i++) { dist[i] = 0; } } private static int try_to_insert(int rear) { int v=0; for (int i = 0; i < row*line; i++) v=v*10+st[rear][i]; if(vis.contains(v)) return 0; vis.add(v); return 1; } // private static void judgesolution(int[] array){ // for (int i = 0;i<array.length;i++){ // int count = 0; // for (int j = 0;j<i;j++){ // if () // } // } // } }
Rjx0613/CS203B
BFS.java
1,171
//距离数组
line_comment
zh-cn
import java.util.*; public class BFS { static int[] goal = new int[30];//目标状态数组 static int[] fa = new int[20000000];//”父亲“编号数组 static int[] dist = new int[20000000];//距离 <SUF> static int[][] st = new int[20000000][30];//过程状态数组 // static ArrayList<Integer> static int dx[] = {-1,1,0,0}; static int dy[] = {0,0,-1,1}; static int row = 0; static int line = 0; static Set<Integer> vis = new HashSet<Integer>();//存放没一步结果,防止回到原来已经走过的路。 public static void main(String[] args) { Scanner sc = new Scanner(System.in); row = sc.nextInt(); line = sc.nextInt(); for (int i = 0; i < row*line; i++) { st[1][i] = sc.nextInt(); } for (int i = 0; i < row*line; i++) { if (i == row*line-1){ goal[i] = 0; } else { goal[i] = i+1; } } int v=0; for (int i = 0; i < row*line; i++) {v=v*10+goal[i];} vis.add(v); int ans = bfs(); if(dist[ans]>0) { System.out.println(dist[ans]); } else System.out.println(0); int[][] process = new int[dist[ans]+1][row*line]; //本来dist[ans]为所需的步数, print(process,ans); } /* * 输出 结果 */ private static void print(int[][] process,int ans) { int i=dist[ans]+1; while(true) { process[--i] = st[ans]; if(ans==1) break; ans = fa[ans]; } for (int j = 0; j < process.length; j++) { for (int j2 = 0; j2 < row*line; j2++) { System.out.print(process[j][j2]+"\t"); if(j2%line==line-1) System.out.println(); } System.out.println(); } } /* * 返回 最终结果 fornt 堆首 或 0未找到 */ private static int bfs() { init_lookup_table(); int front=1,rear=2; while(front<rear) { int[] s = st[front]; if(Arrays.equals(s, goal)) { fa[rear] = front; return front;} int z; for ( z = 0; z < row*line; z++) if(s[z]==0) break; int x = z/line,y=z%line; for (int d = 0; d < 4; d++) { int newx = x+dx[d]; int newy = y+dy[d]; int newz = newx*line+newy; if(newx>=0&&newx<row&&newy>=0&&newy<line) { for (int i = 0; i <row*line; i++) st[rear][i] = s[i]; st[rear][newz] =s[z];//每次只有两个位置改变 st[rear][z] = s[newz]; dist[rear] = dist[front]+1;//再栈首的基础上加一 fa[rear] = front;//给任意一个 fornt,都能fornt = fa[fornt],构造过程 if(try_to_insert(rear)==1) rear++; }//end if }// end for front++; }//end while return 0; } /* * 初始化 */ private static void init_lookup_table() { vis.clear(); for (int i = 0; i < 20000000; i++) { dist[i] = 0; } } private static int try_to_insert(int rear) { int v=0; for (int i = 0; i < row*line; i++) v=v*10+st[rear][i]; if(vis.contains(v)) return 0; vis.add(v); return 1; } // private static void judgesolution(int[] array){ // for (int i = 0;i<array.length;i++){ // int count = 0; // for (int j = 0;j<i;j++){ // if () // } // } // } }
false
1,067
4
1,163
4
1,243
4
1,163
4
1,385
10
false
false
false
false
false
true
30703_2
package com.cloudchewie.util.view; import android.content.Context; import android.util.TypedValue; import android.view.MotionEvent; /** * 手势辅助器 */ public class GestureHelper { /** * 无手势,还不能确定手势 */ public static final int GESTURE_NONE = 0; /** * 手势:按住 */ public static final int GESTURE_PRESSED = 1; /** * 手势:点击 */ public static final int GESTURE_CLICK = 2; /** * 手势:长按 */ public static final int GESTURE_LONG_CLICK = 3; /** * 手势:左滑 */ public static final int GESTURE_LEFT = 4; /** * 手势:上滑 */ public static final int GESTURE_UP = 5; /** * 手势:右滑 */ public static final int GESTURE_RIGHT = 6; /** * 手势:下滑 */ public static final int GESTURE_DOWN = 7; /** * 默认的点大小,单位:dip */ public static final float DEFAULT_FONT_SIZE_DP = 5; /** * 默认的长按时间 */ public static final int DEFAULT_LONG_CLICK_TIME = 800; private float pointSize; // 点的大小 private int longClickTime; // 长按判定时间 private float xyScale; private int gesture = GESTURE_NONE; // 手势 private long downTime; private float downX = 0f; private float downY = 0f; private float preX = 0f; private float preY = 0f; /** * 创建一个手势帮助器 * * @param pointSize 点的大小,超出此大小的滑动手势会被判定为非点击手势 * @param longClickTime 长按点击时间,超过或等于此时间的按住手势算长按点击事件 * @param xyScale X轴与Y轴比例,影响方向手势的判定,默认是1; * 越小,手势判定越偏重于水平方向; * 越大,手势判定偏重于垂直方向; * 1,不偏重任何方向; * 如果是专注于水平方向,可以将此值设置小于1的数, * 如果是专注于垂直方向,可以将此值设置大于1的数; * 如果是垂直与水平同等重要,将此值设置成1 */ public GestureHelper(float pointSize, int longClickTime, float xyScale) { if (pointSize <= 0) { throw new IllegalArgumentException("Illegal:pointSize <= 0"); } if (longClickTime <= 0) { throw new IllegalArgumentException("Illegal:longClickTime <= 0"); } if (xyScale == 0) { throw new IllegalArgumentException("Illegal:xyScale equals 0"); } this.pointSize = pointSize; this.longClickTime = longClickTime; this.xyScale = xyScale; } /** * 创建默认的手势辅助器 * * @param context 上下文对象 * @return 手势器 */ public static GestureHelper createDefault(Context context) { float pointSize = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, DEFAULT_FONT_SIZE_DP, context.getResources().getDisplayMetrics()); return new GestureHelper(pointSize, DEFAULT_LONG_CLICK_TIME, 1f); } /** * 触发触摸滑动事件 * * @param event 事件 */ public void onTouchEvent(MotionEvent event) { // System.out.println("onTouchEvent:action=" + event.getAction()); switch (event.getAction()) { case MotionEvent.ACTION_DOWN: // 按下 touchDown(event); break; case MotionEvent.ACTION_MOVE: // 移动 touchMove(event); break; case MotionEvent.ACTION_CANCEL: // 取消 case MotionEvent.ACTION_UP: // 抬起 touchFinish(event); break; } // System.out.println("onTouchEvent:" + gesture); } /** * 获取手势 * * @return 手势 */ public int getGesture() { return gesture; } /** * 判定是否为水平滑动手势 * * @return true,水平滑动手势 */ public boolean isHorizontalGesture() { return gesture == GESTURE_LEFT || gesture == GESTURE_RIGHT; } /** * 判定是否为垂直滑动手势 * * @return true,垂直滑动手势 */ public boolean isVerticalGesture() { return gesture == GESTURE_UP || gesture == GESTURE_DOWN; } private void touchDown(MotionEvent event) { downTime = System.currentTimeMillis(); downX = preX = event.getRawX(); downY = preY = event.getRawY(); gesture = GESTURE_PRESSED; } private void touchMove(MotionEvent event) { float rangeX = event.getRawX() - downX; float rangeY = event.getRawY() - downY; // System.out.println(String.format("touchMove:rangeX=%f,rangeY=%f,pointSize=%f", // rangeX, rangeY, pointSize)); if (gesture == GESTURE_NONE || gesture == GESTURE_PRESSED) { // 未确定手势或正在长按 if (Math.abs(rangeX) > pointSize || Math.abs(rangeY) > pointSize) { // 超出点的范围,不算点击、按住手势,应该是滑动手势 float ox = event.getRawX() - preX; float oy = event.getRawY() - preY; if (Math.abs(ox) > xyScale * Math.abs(oy)) { // 水平方向滑动 if (ox < 0) { gesture = GESTURE_LEFT; } else { gesture = GESTURE_RIGHT; } } else { // 垂直方向滑动 if (oy < 0) { gesture = GESTURE_UP; } else { gesture = GESTURE_DOWN; } } } else { gesture = GESTURE_PRESSED; // 按住手势 } } if (gesture == GESTURE_PRESSED) { // 按住中 if (System.currentTimeMillis() - downTime >= longClickTime) { // 按住超过长按时间,算长按时间 gesture = GESTURE_LONG_CLICK; } } preX = event.getRawX(); preY = event.getRawY(); } private void touchFinish(MotionEvent event) { if (gesture == GESTURE_PRESSED) { // 按住到释放,应该算点击手势 if (System.currentTimeMillis() - downTime >= longClickTime) { // 按住超过长按时间,算长按时间 gesture = GESTURE_LONG_CLICK; } else { gesture = GESTURE_CLICK; } } } }
Robert-Stackflow/CloudOTP
util/src/main/java/com/cloudchewie/util/view/GestureHelper.java
1,745
/** * 手势:按住 */
block_comment
zh-cn
package com.cloudchewie.util.view; import android.content.Context; import android.util.TypedValue; import android.view.MotionEvent; /** * 手势辅助器 */ public class GestureHelper { /** * 无手势,还不能确定手势 */ public static final int GESTURE_NONE = 0; /** * 手势: <SUF>*/ public static final int GESTURE_PRESSED = 1; /** * 手势:点击 */ public static final int GESTURE_CLICK = 2; /** * 手势:长按 */ public static final int GESTURE_LONG_CLICK = 3; /** * 手势:左滑 */ public static final int GESTURE_LEFT = 4; /** * 手势:上滑 */ public static final int GESTURE_UP = 5; /** * 手势:右滑 */ public static final int GESTURE_RIGHT = 6; /** * 手势:下滑 */ public static final int GESTURE_DOWN = 7; /** * 默认的点大小,单位:dip */ public static final float DEFAULT_FONT_SIZE_DP = 5; /** * 默认的长按时间 */ public static final int DEFAULT_LONG_CLICK_TIME = 800; private float pointSize; // 点的大小 private int longClickTime; // 长按判定时间 private float xyScale; private int gesture = GESTURE_NONE; // 手势 private long downTime; private float downX = 0f; private float downY = 0f; private float preX = 0f; private float preY = 0f; /** * 创建一个手势帮助器 * * @param pointSize 点的大小,超出此大小的滑动手势会被判定为非点击手势 * @param longClickTime 长按点击时间,超过或等于此时间的按住手势算长按点击事件 * @param xyScale X轴与Y轴比例,影响方向手势的判定,默认是1; * 越小,手势判定越偏重于水平方向; * 越大,手势判定偏重于垂直方向; * 1,不偏重任何方向; * 如果是专注于水平方向,可以将此值设置小于1的数, * 如果是专注于垂直方向,可以将此值设置大于1的数; * 如果是垂直与水平同等重要,将此值设置成1 */ public GestureHelper(float pointSize, int longClickTime, float xyScale) { if (pointSize <= 0) { throw new IllegalArgumentException("Illegal:pointSize <= 0"); } if (longClickTime <= 0) { throw new IllegalArgumentException("Illegal:longClickTime <= 0"); } if (xyScale == 0) { throw new IllegalArgumentException("Illegal:xyScale equals 0"); } this.pointSize = pointSize; this.longClickTime = longClickTime; this.xyScale = xyScale; } /** * 创建默认的手势辅助器 * * @param context 上下文对象 * @return 手势器 */ public static GestureHelper createDefault(Context context) { float pointSize = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, DEFAULT_FONT_SIZE_DP, context.getResources().getDisplayMetrics()); return new GestureHelper(pointSize, DEFAULT_LONG_CLICK_TIME, 1f); } /** * 触发触摸滑动事件 * * @param event 事件 */ public void onTouchEvent(MotionEvent event) { // System.out.println("onTouchEvent:action=" + event.getAction()); switch (event.getAction()) { case MotionEvent.ACTION_DOWN: // 按下 touchDown(event); break; case MotionEvent.ACTION_MOVE: // 移动 touchMove(event); break; case MotionEvent.ACTION_CANCEL: // 取消 case MotionEvent.ACTION_UP: // 抬起 touchFinish(event); break; } // System.out.println("onTouchEvent:" + gesture); } /** * 获取手势 * * @return 手势 */ public int getGesture() { return gesture; } /** * 判定是否为水平滑动手势 * * @return true,水平滑动手势 */ public boolean isHorizontalGesture() { return gesture == GESTURE_LEFT || gesture == GESTURE_RIGHT; } /** * 判定是否为垂直滑动手势 * * @return true,垂直滑动手势 */ public boolean isVerticalGesture() { return gesture == GESTURE_UP || gesture == GESTURE_DOWN; } private void touchDown(MotionEvent event) { downTime = System.currentTimeMillis(); downX = preX = event.getRawX(); downY = preY = event.getRawY(); gesture = GESTURE_PRESSED; } private void touchMove(MotionEvent event) { float rangeX = event.getRawX() - downX; float rangeY = event.getRawY() - downY; // System.out.println(String.format("touchMove:rangeX=%f,rangeY=%f,pointSize=%f", // rangeX, rangeY, pointSize)); if (gesture == GESTURE_NONE || gesture == GESTURE_PRESSED) { // 未确定手势或正在长按 if (Math.abs(rangeX) > pointSize || Math.abs(rangeY) > pointSize) { // 超出点的范围,不算点击、按住手势,应该是滑动手势 float ox = event.getRawX() - preX; float oy = event.getRawY() - preY; if (Math.abs(ox) > xyScale * Math.abs(oy)) { // 水平方向滑动 if (ox < 0) { gesture = GESTURE_LEFT; } else { gesture = GESTURE_RIGHT; } } else { // 垂直方向滑动 if (oy < 0) { gesture = GESTURE_UP; } else { gesture = GESTURE_DOWN; } } } else { gesture = GESTURE_PRESSED; // 按住手势 } } if (gesture == GESTURE_PRESSED) { // 按住中 if (System.currentTimeMillis() - downTime >= longClickTime) { // 按住超过长按时间,算长按时间 gesture = GESTURE_LONG_CLICK; } } preX = event.getRawX(); preY = event.getRawY(); } private void touchFinish(MotionEvent event) { if (gesture == GESTURE_PRESSED) { // 按住到释放,应该算点击手势 if (System.currentTimeMillis() - downTime >= longClickTime) { // 按住超过长按时间,算长按时间 gesture = GESTURE_LONG_CLICK; } else { gesture = GESTURE_CLICK; } } } }
false
1,615
12
1,745
11
1,787
12
1,745
11
2,302
17
false
false
false
false
false
true
61822_19
package com.rock.pokemon.gdx.common; /** * 文件地址类,所有文件路径都存放在这里 * 文件包括: 图片、音效、音乐、文本 * * @Author ayl * @Date 2022-10-12 */ public class FilePaths { /** * 系统配置 */ //文本-文件地址 public static final String SYSTEM_CONFIG_TEXT_FILE_PATH = "assets/text/%s/Text.txt"; //文本-文字皮肤 public static final String SYSTEM_TEXT_FONT_FNT = "assets/font/black/黑体.fnt"; public static final String SYSTEM_TEXT_FONT_IMAGE = "assets/font/black/黑体.png"; /** * 文件名 */ //资源文件名 public static final String TEXTURES_ATLAS_FILE_NAME = "textures.atlas"; /** * 图片资源 */ //人物资源-通用路径 public static final String TEXTURES_ALTA_PEOPLE = "assets/packed/image/people/"; //地图资源-通用路径 public static final String TEXTURES_ALTA_MAP = "assets/packed/image/map/"; //ui资源-通用路径 public static final String TEXTURES_ALTA_UI = "assets/packed/image/ui/"; /** * 非通用 世界配置 */ //配置文件路径-未白镇地图 public static final String MAP_CONFIG_PATH_OF_LITTLE_ROOT = "assets/config/map/little_root/Main.json"; //配置文件路径-未白镇-路比家 public static final String MAP_CONFIG_PATH_OF_LITTLE_ROOT_HOUSE_RUBY_FIRST = "assets/config/map/little_root/Ruby-First.json"; public static final String MAP_CONFIG_PATH_OF_LITTLE_ROOT_HOUSE_RUBY_SECOND = "assets/config/map/little_root/Ruby-SECOND.json"; /** * 通用 世界配置 */ //配置文件路径-事物 public static final String MAP_CONFIG_PATH_OF_WORLD_OBJECT = "assets/config/map/WorldObject.json"; //配置文件路径-npc public static final String MAP_CONFIG_PATH_OF_NPC = "assets/config/map/Npc.json"; //配置文件路径-盒子 public static final String MAP_CONFIG_PATH_OF_BOX = "assets/config/map/Box.json"; //配置文件路径-事件 public static final String MAP_CONFIG_PATH_OF_EVENT = "assets/config/map/Event.json"; //配置文件路径-音效 public static final String MAP_CONFIG_PATH_OF_SOUND = "assets/config/map/Sound.json"; /** * 战斗渐变配置 */ //顶点着色器 public static final String TRANSITION_GLSL_VERTEX = "assets/config/transition/glsl/vertex.glsl"; //片元着色器 public static final String TRANSITION_GLSL_FRAGMENT = "assets/config/transition/glsl/fragment.glsl"; //渐变动画图片路径 public static final String TRANSITION_ANIMATION_IMAGE_PATH = "assets/config/transition/transition_%s.png"; }
Rock-Ayl/Pokemon
core/src/com/rock/pokemon/gdx/common/FilePaths.java
766
/** * 战斗渐变配置 */
block_comment
zh-cn
package com.rock.pokemon.gdx.common; /** * 文件地址类,所有文件路径都存放在这里 * 文件包括: 图片、音效、音乐、文本 * * @Author ayl * @Date 2022-10-12 */ public class FilePaths { /** * 系统配置 */ //文本-文件地址 public static final String SYSTEM_CONFIG_TEXT_FILE_PATH = "assets/text/%s/Text.txt"; //文本-文字皮肤 public static final String SYSTEM_TEXT_FONT_FNT = "assets/font/black/黑体.fnt"; public static final String SYSTEM_TEXT_FONT_IMAGE = "assets/font/black/黑体.png"; /** * 文件名 */ //资源文件名 public static final String TEXTURES_ATLAS_FILE_NAME = "textures.atlas"; /** * 图片资源 */ //人物资源-通用路径 public static final String TEXTURES_ALTA_PEOPLE = "assets/packed/image/people/"; //地图资源-通用路径 public static final String TEXTURES_ALTA_MAP = "assets/packed/image/map/"; //ui资源-通用路径 public static final String TEXTURES_ALTA_UI = "assets/packed/image/ui/"; /** * 非通用 世界配置 */ //配置文件路径-未白镇地图 public static final String MAP_CONFIG_PATH_OF_LITTLE_ROOT = "assets/config/map/little_root/Main.json"; //配置文件路径-未白镇-路比家 public static final String MAP_CONFIG_PATH_OF_LITTLE_ROOT_HOUSE_RUBY_FIRST = "assets/config/map/little_root/Ruby-First.json"; public static final String MAP_CONFIG_PATH_OF_LITTLE_ROOT_HOUSE_RUBY_SECOND = "assets/config/map/little_root/Ruby-SECOND.json"; /** * 通用 世界配置 */ //配置文件路径-事物 public static final String MAP_CONFIG_PATH_OF_WORLD_OBJECT = "assets/config/map/WorldObject.json"; //配置文件路径-npc public static final String MAP_CONFIG_PATH_OF_NPC = "assets/config/map/Npc.json"; //配置文件路径-盒子 public static final String MAP_CONFIG_PATH_OF_BOX = "assets/config/map/Box.json"; //配置文件路径-事件 public static final String MAP_CONFIG_PATH_OF_EVENT = "assets/config/map/Event.json"; //配置文件路径-音效 public static final String MAP_CONFIG_PATH_OF_SOUND = "assets/config/map/Sound.json"; /** * 战斗渐 <SUF>*/ //顶点着色器 public static final String TRANSITION_GLSL_VERTEX = "assets/config/transition/glsl/vertex.glsl"; //片元着色器 public static final String TRANSITION_GLSL_FRAGMENT = "assets/config/transition/glsl/fragment.glsl"; //渐变动画图片路径 public static final String TRANSITION_ANIMATION_IMAGE_PATH = "assets/config/transition/transition_%s.png"; }
false
653
12
766
13
779
11
766
13
1,038
20
false
false
false
false
false
true
59288_0
package com.ghostj.master; import com.ghostj.master.conn.CheckServerAlive; import com.ghostj.master.conn.HandleConn; import com.ghostj.master.gui.InitGUI; import com.ghostj.master.util.Config; import com.ghostj.master.util.FileRW; import com.ghostj.master.util.TagLog; import com.ghostj.server_old.ServerMain; import java.io.BufferedWriter; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.net.Socket; import java.util.Date; import java.util.Timer; import java.util.TimerTask; public class MasterMain { public static InitGUI initGUI; public static Socket socket=null; public static InputStreamReader inputStreamReader=null; public static BufferedWriter bufferedWriter=null; public static Config config; public static HandleConn handleConn=null; int receivePeriod=0; public static final int bufferedTextLineAmount=100; public static CheckServerAlive checkServerAlive=new CheckServerAlive(); public static TagLog tagLog=new TagLog(); //内建服务器 public static ServerMain internalServer; public static void main(String [] args){ if(!new File("gmaster.ini").exists()){ FileRW.write("gmaster.ini",""); } config=new Config("gmaster.ini"); initGUI=new InitGUI(); new Timer().schedule(checkServerAlive,4000,10*60*1000); // new Timer().schedule(new TimerTask() { // @Override // public void run() { // initGUI.scrollBar.setValue(initGUI.scrollBar.getMaximum()); // } // },new Date(),200); // new Timer().schedule(new TimerTask() { // @Override // public void run() { // try { // String text[] = initGUI.console.getText().split("\n"); // int len = text.length; // if (len > bufferedTextLineAmount) { // System.out.println("清理" + (len - bufferedTextLineAmount) + "行 共"+len); // StringBuffer retext = new StringBuffer(""); // for (int i = len - bufferedTextLineAmount; i < len; i++) { // retext.append("\n" + text[i]); // } // initGUI.console.setText(retext.toString()); // initGUI.console.setCaretPosition(retext.length()); // } // }catch (Exception e){ // e.printStackTrace(); // } // } // },new Date(),1000); new Timer().schedule(new TimerTask(){ @Override public void run() { initGUI.mainwd.setTitle("total:"+Runtime.getRuntime().totalMemory()+" used:"+(Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory())); } },new Date(),2000); } public static void writeToServer(String cmd){ try { MasterMain.bufferedWriter.write(cmd); MasterMain.bufferedWriter.newLine(); MasterMain.bufferedWriter.flush(); } catch (IOException e) { MasterMain.handleConn.kill("连接已断开"); e.printStackTrace(); } } }
RockChinQ/GhostJ
src/com/ghostj/master/MasterMain.java
872
//内建服务器
line_comment
zh-cn
package com.ghostj.master; import com.ghostj.master.conn.CheckServerAlive; import com.ghostj.master.conn.HandleConn; import com.ghostj.master.gui.InitGUI; import com.ghostj.master.util.Config; import com.ghostj.master.util.FileRW; import com.ghostj.master.util.TagLog; import com.ghostj.server_old.ServerMain; import java.io.BufferedWriter; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.net.Socket; import java.util.Date; import java.util.Timer; import java.util.TimerTask; public class MasterMain { public static InitGUI initGUI; public static Socket socket=null; public static InputStreamReader inputStreamReader=null; public static BufferedWriter bufferedWriter=null; public static Config config; public static HandleConn handleConn=null; int receivePeriod=0; public static final int bufferedTextLineAmount=100; public static CheckServerAlive checkServerAlive=new CheckServerAlive(); public static TagLog tagLog=new TagLog(); //内建 <SUF> public static ServerMain internalServer; public static void main(String [] args){ if(!new File("gmaster.ini").exists()){ FileRW.write("gmaster.ini",""); } config=new Config("gmaster.ini"); initGUI=new InitGUI(); new Timer().schedule(checkServerAlive,4000,10*60*1000); // new Timer().schedule(new TimerTask() { // @Override // public void run() { // initGUI.scrollBar.setValue(initGUI.scrollBar.getMaximum()); // } // },new Date(),200); // new Timer().schedule(new TimerTask() { // @Override // public void run() { // try { // String text[] = initGUI.console.getText().split("\n"); // int len = text.length; // if (len > bufferedTextLineAmount) { // System.out.println("清理" + (len - bufferedTextLineAmount) + "行 共"+len); // StringBuffer retext = new StringBuffer(""); // for (int i = len - bufferedTextLineAmount; i < len; i++) { // retext.append("\n" + text[i]); // } // initGUI.console.setText(retext.toString()); // initGUI.console.setCaretPosition(retext.length()); // } // }catch (Exception e){ // e.printStackTrace(); // } // } // },new Date(),1000); new Timer().schedule(new TimerTask(){ @Override public void run() { initGUI.mainwd.setTitle("total:"+Runtime.getRuntime().totalMemory()+" used:"+(Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory())); } },new Date(),2000); } public static void writeToServer(String cmd){ try { MasterMain.bufferedWriter.write(cmd); MasterMain.bufferedWriter.newLine(); MasterMain.bufferedWriter.flush(); } catch (IOException e) { MasterMain.handleConn.kill("连接已断开"); e.printStackTrace(); } } }
false
674
4
872
4
834
4
872
4
1,024
6
false
false
false
false
false
true
59730_1
package linklist; /** * @BelongsProject: exercises * @BelongsPackage: linklist * @CreateTime : 2024/5/8 19:06 * @Description: TODO * @Author: code_hlb */ public class Demo10 { /** * 86. 分隔链表 * 给你一个链表的头节点 head 和一个特定值 x ,请你对链表进行分隔,使得所有 小于 x 的节点都出现在 大于或等于 x 的节点之前。 * 你应当 保留 两个分区中每个节点的初始相对位置。 * 示例 1: * 输入:head = [1,4,3,2,5,2], x = 3 * 输出:[1,2,2,4,3,5] * 示例 2: * 输入:head = [2,1], x = 2 * 输出:[1,2] */ public static ListNode partition(ListNode head, int x) { if (head == null || head.next == null) { return head; } ListNode smaller = new ListNode(-1); ListNode tmpSma = smaller; ListNode larger = new ListNode(-1); ListNode tmpLar = larger; ListNode cur = head; while (cur != null) { if (cur.val < x) { tmpSma.next = new ListNode(cur.val); tmpSma = tmpSma.next; } else { tmpLar.next = new ListNode(cur.val); tmpLar = tmpLar.next; } cur = cur.next; } // 将当前较小链表的尾 接到 较大链表的头,形成完整链表 tmpSma.next = larger.next; return smaller.next; } public static void main(String[] args) { // head = [1,4,3,2,5,2], x = 3 ListNode head = new ListNode(1); head.next = new ListNode(4); head.next.next = new ListNode(3); head.next.next.next = new ListNode(2); head.next.next.next.next = new ListNode(5); head.next.next.next.next.next = new ListNode(2); System.out.println(partition(head, 3)); } }
Rockyhlb/java_data_struct
exercises/src/linklist/Demo10.java
555
/** * 86. 分隔链表 * 给你一个链表的头节点 head 和一个特定值 x ,请你对链表进行分隔,使得所有 小于 x 的节点都出现在 大于或等于 x 的节点之前。 * 你应当 保留 两个分区中每个节点的初始相对位置。 * 示例 1: * 输入:head = [1,4,3,2,5,2], x = 3 * 输出:[1,2,2,4,3,5] * 示例 2: * 输入:head = [2,1], x = 2 * 输出:[1,2] */
block_comment
zh-cn
package linklist; /** * @BelongsProject: exercises * @BelongsPackage: linklist * @CreateTime : 2024/5/8 19:06 * @Description: TODO * @Author: code_hlb */ public class Demo10 { /** * 86. <SUF>*/ public static ListNode partition(ListNode head, int x) { if (head == null || head.next == null) { return head; } ListNode smaller = new ListNode(-1); ListNode tmpSma = smaller; ListNode larger = new ListNode(-1); ListNode tmpLar = larger; ListNode cur = head; while (cur != null) { if (cur.val < x) { tmpSma.next = new ListNode(cur.val); tmpSma = tmpSma.next; } else { tmpLar.next = new ListNode(cur.val); tmpLar = tmpLar.next; } cur = cur.next; } // 将当前较小链表的尾 接到 较大链表的头,形成完整链表 tmpSma.next = larger.next; return smaller.next; } public static void main(String[] args) { // head = [1,4,3,2,5,2], x = 3 ListNode head = new ListNode(1); head.next = new ListNode(4); head.next.next = new ListNode(3); head.next.next.next = new ListNode(2); head.next.next.next.next = new ListNode(5); head.next.next.next.next.next = new ListNode(2); System.out.println(partition(head, 3)); } }
false
516
156
555
158
571
154
555
158
683
215
false
false
false
false
false
true
52650_1
package cn.alone.AbstractQueueSynchronizer; import java.util.concurrent.Semaphore; /** * Created by RojerAlone on 2017-08-28. */ public class SemaphoreTest { private static final int numOfThreads = 5; // 线程数 private static final int sleepTime = 3000; // 睡眠时间 public static void main(String[] args) { Semaphore semaphore = new Semaphore(numOfThreads); System.out.println("停车场一共有 " + numOfThreads + " 个停车位"); for (int i = 0; i < 2 * numOfThreads; i++) { new Thread(new Runnable() { @Override public void run() { try { semaphore.acquire(); System.out.println(Thread.currentThread().getName() + " 停车"); Thread.sleep(sleepTime); System.out.println(Thread.currentThread().getName() + " 开走了"); semaphore.release(); } catch (InterruptedException e) { e.printStackTrace(); } } }).start(); } } }
RojerAlone/Java-in-Action
src/cn/alone/AbstractQueueSynchronizer/SemaphoreTest.java
264
// 线程数
line_comment
zh-cn
package cn.alone.AbstractQueueSynchronizer; import java.util.concurrent.Semaphore; /** * Created by RojerAlone on 2017-08-28. */ public class SemaphoreTest { private static final int numOfThreads = 5; // 线程 <SUF> private static final int sleepTime = 3000; // 睡眠时间 public static void main(String[] args) { Semaphore semaphore = new Semaphore(numOfThreads); System.out.println("停车场一共有 " + numOfThreads + " 个停车位"); for (int i = 0; i < 2 * numOfThreads; i++) { new Thread(new Runnable() { @Override public void run() { try { semaphore.acquire(); System.out.println(Thread.currentThread().getName() + " 停车"); Thread.sleep(sleepTime); System.out.println(Thread.currentThread().getName() + " 开走了"); semaphore.release(); } catch (InterruptedException e) { e.printStackTrace(); } } }).start(); } } }
false
232
6
264
4
272
4
264
4
344
5
false
false
false
false
false
true
27126_10
package cn.cie.services; import cn.cie.entity.User; import cn.cie.utils.Result; /** * Created by RojerAlone on 2017/5/31. */ public interface UserService { /** * 注册 * @param user * @return */ Result register(User user); /** * 给用户注册的邮箱发送验证码 * @param user * @return */ Result sendMail(User user); /** * 邮箱验证 * @param uid * @param code * @return */ Result validate(Integer uid, String code); /** * 登录 * 登陆时如果选择了“记住我”选项,那么token保持7天,否则保存1天 * 登陆成功,将token存在数据库中记录,同时存入缓存,过期时间为1天 * 每次请求时拦截器先从缓存中查找,如果没有再去数据库中查找 * @param username 用户名 * @param password 密码 * @param remember 是否保持登陆(token生存周期为7天) * @return */ Result login(String username, String password, boolean remember, String ip, String device); /** * 登出 * @return */ Result logout(String token); /** * 更新用户信息 * @param user * @return */ Result updateUserInfo(User user); /** * 更新密码 * @param password * @return */ Result updatePassword(String password); /** * 忘记密码 * @param password * @param code * @return */ Result forgetPassword(String password, String email, String code); /** * 忘记密码时需要给邮箱发送验证码 * @param email * @return */ Result sendFetchPwdMail(String email); /** * 删除没有验证的用户 */ void delNotValidateUser(); /** * 删除已经过期的token */ void expireToken(); }
RojerAlone/shop
src/main/java/cn/cie/services/UserService.java
470
/** * 删除没有验证的用户 */
block_comment
zh-cn
package cn.cie.services; import cn.cie.entity.User; import cn.cie.utils.Result; /** * Created by RojerAlone on 2017/5/31. */ public interface UserService { /** * 注册 * @param user * @return */ Result register(User user); /** * 给用户注册的邮箱发送验证码 * @param user * @return */ Result sendMail(User user); /** * 邮箱验证 * @param uid * @param code * @return */ Result validate(Integer uid, String code); /** * 登录 * 登陆时如果选择了“记住我”选项,那么token保持7天,否则保存1天 * 登陆成功,将token存在数据库中记录,同时存入缓存,过期时间为1天 * 每次请求时拦截器先从缓存中查找,如果没有再去数据库中查找 * @param username 用户名 * @param password 密码 * @param remember 是否保持登陆(token生存周期为7天) * @return */ Result login(String username, String password, boolean remember, String ip, String device); /** * 登出 * @return */ Result logout(String token); /** * 更新用户信息 * @param user * @return */ Result updateUserInfo(User user); /** * 更新密码 * @param password * @return */ Result updatePassword(String password); /** * 忘记密码 * @param password * @param code * @return */ Result forgetPassword(String password, String email, String code); /** * 忘记密码时需要给邮箱发送验证码 * @param email * @return */ Result sendFetchPwdMail(String email); /** * 删除没 <SUF>*/ void delNotValidateUser(); /** * 删除已经过期的token */ void expireToken(); }
false
473
11
470
10
511
11
470
10
676
21
false
false
false
false
false
true
58938_5
package com.github.imp1.gui; import com.github.imp1.dbutils.Engine; import com.github.imp1.dbutils.Rule; import com.github.imp1.dbutils.RuleDao; import javax.swing.*; import javax.swing.border.Border; import javax.swing.plaf.FontUIResource; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.IOException; import java.sql.SQLException; import java.util.ArrayList; import java.util.Arrays; import java.util.Enumeration; import java.util.HashSet; public class MainFrame extends JFrame { private final int weight = 1200; private final int height = 800; private JTextPane rulePane; private JTextPane inputPane; private JTextArea logPane; private JPanel opButtonPane; private JButton beginReason; private JButton reverseReason; private JButton viewDB; private JButton reflushRules; private Font font; private StringBuffer logInfo; private final String banner = "\n" + " _ ______ _ \n" + " | | | ____| | | \n" + " | | __ ___ ____ _ | |__ __ ___ __ ___ _ __| |_ \n" + " _ | |/ _` \\ \\ / / _` | | __| \\ \\/ / '_ \\ / _ \\ '__| __|\n" + " | |__| | (_| |\\ V / (_| | | |____ > <| |_) | __/ | | |_ \n" + " \\____/ \\__,_| \\_/ \\__,_| |______/_/\\_\\ .__/ \\___|_| \\__|\n" + " | | \n" + " |_| \n"; private final String verbose = "I think >"; private final ImageIcon reasonIcon = new ImageIcon("resource/reason.png"); private final ImageIcon reverseIcon = new ImageIcon("resource/reverse_reason.png"); private final ImageIcon viewDBIcon = new ImageIcon("resource/view_db.png"); private final ImageIcon reflushIcon = new ImageIcon("resource/reflush.png"); public static void main(String[] args) { SwingUtilities.invokeLater(() -> { MainFrame frame = null; try { frame = new MainFrame(); MainFrame.InitGlobalFont(frame.font); frame.setTitle("动物识别推理系统"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); } catch (IOException | ClassNotFoundException | SQLException e) { e.printStackTrace(); } }); } /** * 统一设置字体,父界面设置之后,所有由父界面进入的子界面都不需要再次设置字体 */ private static void InitGlobalFont(Font font) { FontUIResource fontRes = new FontUIResource(font); for (Enumeration<Object> keys = UIManager.getDefaults().keys(); keys.hasMoreElements(); ) { Object key = keys.nextElement(); Object value = UIManager.get(key); if (value instanceof FontUIResource) { UIManager.put(key, fontRes); } } } public MainFrame() throws HeadlessException, IOException, SQLException, ClassNotFoundException { font = new Font("楷体", Font.PLAIN, 16); setFont(font); setLayout(new GridLayout(2, 2)); setSize(this.weight, this.height); addBasicPanel(); addInputPanel(); addLogPanel(); addButtonPanel(); initRulePanelContent(); } public void addBasicPanel() { //创建一个蚀刻边界 Border etched = BorderFactory.createEtchedBorder(); //边界加标题 Border titled = BorderFactory.createTitledBorder(etched, "规则面板"); rulePane = new JTextPane(); rulePane.setBorder(titled); rulePane.setSize(this.weight / 2, this.height / 2); rulePane.setFont(font); add(rulePane, 0); } public void initRulePanelContent() throws SQLException, IOException, ClassNotFoundException { reflushRules.doClick(); } public void addInputPanel() { //创建一个蚀刻边界 Border etched = BorderFactory.createEtchedBorder(); //边界加标题 Border titled = BorderFactory.createTitledBorder(etched, "输入事实"); inputPane = new JTextPane(); inputPane.setSize(this.weight / 2, this.height / 2); inputPane.setBorder(titled); inputPane.setFont(font); inputPane.setText("暗斑点,黄褐色,长脖子,长腿,有奶,有蹄"); add(inputPane, 1); } public void addLogPanel() { Border etched = BorderFactory.createEtchedBorder(); Border titled = BorderFactory.createTitledBorder(etched, "推理过程"); logPane = new JTextArea(); JScrollPane jScrollPane = new JScrollPane(logPane); logPane.setSize(this.weight / 2, this.height / 2); logPane.setBorder(titled); logPane.setFont(font); logPane.setText(banner + "\n" + verbose); add(jScrollPane, 2); } public void addButtonPanel() { Border etched = BorderFactory.createEtchedBorder(); Border titled = BorderFactory.createTitledBorder(etched, "操作面板"); opButtonPane = new JPanel(); opButtonPane.setSize(this.weight / 2, this.height / 2); opButtonPane.setBorder(titled); opButtonPane.setFont(font); add(opButtonPane, 3); beginReason = new JButton("开始推理"); beginReason.setFont(font); beginReason.setIcon(reasonIcon); reverseReason = new JButton("反向推理"); reverseReason.setFont(font); reverseReason.setIcon(reverseIcon); viewDB = new JButton("总知识库"); viewDB.setFont(font); viewDB.setIcon(viewDBIcon); reflushRules = new JButton("刷新规则"); reflushRules.setFont(font); reflushRules.setIcon(reflushIcon); opButtonPane.add(beginReason); opButtonPane.add(reverseReason); opButtonPane.add(viewDB); opButtonPane.add(reflushRules); beginReason.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { logInfo = new StringBuffer(verbose); String line = inputPane.getText(); HashSet<String> facts = stringToHashSet(line); try { ArrayList<Rule> rules = RuleDao.getAllUsedRule(); for (Rule rule : rules) { Double mathRate = Engine.matchLevle1(rule, facts); if (mathRate == 1) { logInfo.append("该动物为:" + rule.getConclusion()); logInfo.append("\n事实状态为:"); logInfo.append(facts.toString()); logInfo.append('\n'); logInfo.append(verbose); } } logPane.setText(logInfo.toString()); } catch (SQLException | IOException | ClassNotFoundException ex) { ex.printStackTrace(); } } }); reverseReason.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { try { String line = inputPane.getText(); ArrayList<Rule> ruleSet = RuleDao.getAllRuleAllConclusion(line); HashSet<String> factSet = new HashSet<String>(); for (Rule rule : ruleSet) { StringBuffer message = new StringBuffer(); if (rule.isMatch(factSet)) { showSuccess(rule.getConclusion()); return; } else { String[] ruleCondition = rule.getHava().split(" "); for (String condition : ruleCondition) { if (!factSet.contains(condition)) { if (!RuleDao.isConclusion(condition)) { message = new StringBuffer(); int result = showConfirm(message, condition); if (result == JOptionPane.YES_OPTION) { factSet.add(condition); if (rule.isMatch(factSet)) { showSuccess(rule.getConclusion()); return; } } } else { ArrayList<Rule> conditionRuleSet = RuleDao.getAllRuleAllConclusion(condition); for (Rule r : conditionRuleSet) { if (factSet.contains(condition)) { break; } String[] basicCondition = r.getHava().split(" "); for (String s : basicCondition) { if (!factSet.contains(s)) { message = new StringBuffer(); int result = showConfirm(message, s); if (result == JOptionPane.YES_OPTION) { factSet.add(s); if (r.isMatch(factSet)) { factSet.add(condition); break; } } } } } if (rule.isMatch(factSet)) { showSuccess(rule.getConclusion()); return; } } } } } } showFailure(line); } catch (SQLException | IOException | ClassNotFoundException ex) { ex.printStackTrace(); } } }); viewDB.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { try { DBTableFrame frame = new DBTableFrame(); frame.setTitle("动物识别系统知识库"); frame.setVisible(true); } catch (SQLException | IOException | ClassNotFoundException ex) { ex.printStackTrace(); } } }); reflushRules.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { StringBuffer content = new StringBuffer(); content.append("基础规则如下:\n"); try { ArrayList<Rule> rules = RuleDao.getAllUsedRule(); int cnt = 1; for(Rule r: rules){ content.append(cnt); cnt ++; content.append(":"); for (String condition: r.getHava().split(" ")){ content.append(condition); content.append("\t"); } content.append(r.getConclusion()); content.append("\n"); } rulePane.setText(content.toString()); } catch (SQLException | IOException | ClassNotFoundException ex) { ex.printStackTrace(); } } }); } public HashSet<String> stringToHashSet(String line) { HashSet<String> facts = new HashSet<String>(); line = line.trim(); if (line.contains(",")) { facts.addAll(Arrays.asList(line.split(","))); } else if (line.contains(",")) { facts.addAll(Arrays.asList(line.split(","))); } else if (line.contains("\t")){ facts.addAll(Arrays.asList(line.split("\t"))); } else { facts.addAll(Arrays.asList(line.split(" "))); } return facts; } public int showConfirm(StringBuffer message, String condition) { message = new StringBuffer(); message.append("该对象有:"); message.append(condition); message.append("属性吗?"); int result = JOptionPane.showConfirmDialog(null, message.toString(), "逆向推理", JOptionPane.YES_NO_OPTION); return result; } public void showSuccess(String conclusion) { StringBuffer message = new StringBuffer(); message.append("推理成功!"); message.append("该对象为" + conclusion); JOptionPane.showMessageDialog(null, message.toString(), "逆向推理", JOptionPane.PLAIN_MESSAGE); } public void showFailure(String conclusion) { StringBuffer message = new StringBuffer(); message.append("推理失败!"); message.append("根据先有知识不能推出该对象为" + conclusion); JOptionPane.showMessageDialog(null, message.toString(), "逆向推理", JOptionPane.WARNING_MESSAGE); } } /* 暗斑点,黄褐色,长脖子,长腿,有奶,有蹄 */
RonDen/JavaAnimalExpertSystem
src/com/github/imp1/gui/MainFrame.java
2,853
/* 暗斑点,黄褐色,长脖子,长腿,有奶,有蹄 */
block_comment
zh-cn
package com.github.imp1.gui; import com.github.imp1.dbutils.Engine; import com.github.imp1.dbutils.Rule; import com.github.imp1.dbutils.RuleDao; import javax.swing.*; import javax.swing.border.Border; import javax.swing.plaf.FontUIResource; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.IOException; import java.sql.SQLException; import java.util.ArrayList; import java.util.Arrays; import java.util.Enumeration; import java.util.HashSet; public class MainFrame extends JFrame { private final int weight = 1200; private final int height = 800; private JTextPane rulePane; private JTextPane inputPane; private JTextArea logPane; private JPanel opButtonPane; private JButton beginReason; private JButton reverseReason; private JButton viewDB; private JButton reflushRules; private Font font; private StringBuffer logInfo; private final String banner = "\n" + " _ ______ _ \n" + " | | | ____| | | \n" + " | | __ ___ ____ _ | |__ __ ___ __ ___ _ __| |_ \n" + " _ | |/ _` \\ \\ / / _` | | __| \\ \\/ / '_ \\ / _ \\ '__| __|\n" + " | |__| | (_| |\\ V / (_| | | |____ > <| |_) | __/ | | |_ \n" + " \\____/ \\__,_| \\_/ \\__,_| |______/_/\\_\\ .__/ \\___|_| \\__|\n" + " | | \n" + " |_| \n"; private final String verbose = "I think >"; private final ImageIcon reasonIcon = new ImageIcon("resource/reason.png"); private final ImageIcon reverseIcon = new ImageIcon("resource/reverse_reason.png"); private final ImageIcon viewDBIcon = new ImageIcon("resource/view_db.png"); private final ImageIcon reflushIcon = new ImageIcon("resource/reflush.png"); public static void main(String[] args) { SwingUtilities.invokeLater(() -> { MainFrame frame = null; try { frame = new MainFrame(); MainFrame.InitGlobalFont(frame.font); frame.setTitle("动物识别推理系统"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); } catch (IOException | ClassNotFoundException | SQLException e) { e.printStackTrace(); } }); } /** * 统一设置字体,父界面设置之后,所有由父界面进入的子界面都不需要再次设置字体 */ private static void InitGlobalFont(Font font) { FontUIResource fontRes = new FontUIResource(font); for (Enumeration<Object> keys = UIManager.getDefaults().keys(); keys.hasMoreElements(); ) { Object key = keys.nextElement(); Object value = UIManager.get(key); if (value instanceof FontUIResource) { UIManager.put(key, fontRes); } } } public MainFrame() throws HeadlessException, IOException, SQLException, ClassNotFoundException { font = new Font("楷体", Font.PLAIN, 16); setFont(font); setLayout(new GridLayout(2, 2)); setSize(this.weight, this.height); addBasicPanel(); addInputPanel(); addLogPanel(); addButtonPanel(); initRulePanelContent(); } public void addBasicPanel() { //创建一个蚀刻边界 Border etched = BorderFactory.createEtchedBorder(); //边界加标题 Border titled = BorderFactory.createTitledBorder(etched, "规则面板"); rulePane = new JTextPane(); rulePane.setBorder(titled); rulePane.setSize(this.weight / 2, this.height / 2); rulePane.setFont(font); add(rulePane, 0); } public void initRulePanelContent() throws SQLException, IOException, ClassNotFoundException { reflushRules.doClick(); } public void addInputPanel() { //创建一个蚀刻边界 Border etched = BorderFactory.createEtchedBorder(); //边界加标题 Border titled = BorderFactory.createTitledBorder(etched, "输入事实"); inputPane = new JTextPane(); inputPane.setSize(this.weight / 2, this.height / 2); inputPane.setBorder(titled); inputPane.setFont(font); inputPane.setText("暗斑点,黄褐色,长脖子,长腿,有奶,有蹄"); add(inputPane, 1); } public void addLogPanel() { Border etched = BorderFactory.createEtchedBorder(); Border titled = BorderFactory.createTitledBorder(etched, "推理过程"); logPane = new JTextArea(); JScrollPane jScrollPane = new JScrollPane(logPane); logPane.setSize(this.weight / 2, this.height / 2); logPane.setBorder(titled); logPane.setFont(font); logPane.setText(banner + "\n" + verbose); add(jScrollPane, 2); } public void addButtonPanel() { Border etched = BorderFactory.createEtchedBorder(); Border titled = BorderFactory.createTitledBorder(etched, "操作面板"); opButtonPane = new JPanel(); opButtonPane.setSize(this.weight / 2, this.height / 2); opButtonPane.setBorder(titled); opButtonPane.setFont(font); add(opButtonPane, 3); beginReason = new JButton("开始推理"); beginReason.setFont(font); beginReason.setIcon(reasonIcon); reverseReason = new JButton("反向推理"); reverseReason.setFont(font); reverseReason.setIcon(reverseIcon); viewDB = new JButton("总知识库"); viewDB.setFont(font); viewDB.setIcon(viewDBIcon); reflushRules = new JButton("刷新规则"); reflushRules.setFont(font); reflushRules.setIcon(reflushIcon); opButtonPane.add(beginReason); opButtonPane.add(reverseReason); opButtonPane.add(viewDB); opButtonPane.add(reflushRules); beginReason.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { logInfo = new StringBuffer(verbose); String line = inputPane.getText(); HashSet<String> facts = stringToHashSet(line); try { ArrayList<Rule> rules = RuleDao.getAllUsedRule(); for (Rule rule : rules) { Double mathRate = Engine.matchLevle1(rule, facts); if (mathRate == 1) { logInfo.append("该动物为:" + rule.getConclusion()); logInfo.append("\n事实状态为:"); logInfo.append(facts.toString()); logInfo.append('\n'); logInfo.append(verbose); } } logPane.setText(logInfo.toString()); } catch (SQLException | IOException | ClassNotFoundException ex) { ex.printStackTrace(); } } }); reverseReason.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { try { String line = inputPane.getText(); ArrayList<Rule> ruleSet = RuleDao.getAllRuleAllConclusion(line); HashSet<String> factSet = new HashSet<String>(); for (Rule rule : ruleSet) { StringBuffer message = new StringBuffer(); if (rule.isMatch(factSet)) { showSuccess(rule.getConclusion()); return; } else { String[] ruleCondition = rule.getHava().split(" "); for (String condition : ruleCondition) { if (!factSet.contains(condition)) { if (!RuleDao.isConclusion(condition)) { message = new StringBuffer(); int result = showConfirm(message, condition); if (result == JOptionPane.YES_OPTION) { factSet.add(condition); if (rule.isMatch(factSet)) { showSuccess(rule.getConclusion()); return; } } } else { ArrayList<Rule> conditionRuleSet = RuleDao.getAllRuleAllConclusion(condition); for (Rule r : conditionRuleSet) { if (factSet.contains(condition)) { break; } String[] basicCondition = r.getHava().split(" "); for (String s : basicCondition) { if (!factSet.contains(s)) { message = new StringBuffer(); int result = showConfirm(message, s); if (result == JOptionPane.YES_OPTION) { factSet.add(s); if (r.isMatch(factSet)) { factSet.add(condition); break; } } } } } if (rule.isMatch(factSet)) { showSuccess(rule.getConclusion()); return; } } } } } } showFailure(line); } catch (SQLException | IOException | ClassNotFoundException ex) { ex.printStackTrace(); } } }); viewDB.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { try { DBTableFrame frame = new DBTableFrame(); frame.setTitle("动物识别系统知识库"); frame.setVisible(true); } catch (SQLException | IOException | ClassNotFoundException ex) { ex.printStackTrace(); } } }); reflushRules.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { StringBuffer content = new StringBuffer(); content.append("基础规则如下:\n"); try { ArrayList<Rule> rules = RuleDao.getAllUsedRule(); int cnt = 1; for(Rule r: rules){ content.append(cnt); cnt ++; content.append(":"); for (String condition: r.getHava().split(" ")){ content.append(condition); content.append("\t"); } content.append(r.getConclusion()); content.append("\n"); } rulePane.setText(content.toString()); } catch (SQLException | IOException | ClassNotFoundException ex) { ex.printStackTrace(); } } }); } public HashSet<String> stringToHashSet(String line) { HashSet<String> facts = new HashSet<String>(); line = line.trim(); if (line.contains(",")) { facts.addAll(Arrays.asList(line.split(","))); } else if (line.contains(",")) { facts.addAll(Arrays.asList(line.split(","))); } else if (line.contains("\t")){ facts.addAll(Arrays.asList(line.split("\t"))); } else { facts.addAll(Arrays.asList(line.split(" "))); } return facts; } public int showConfirm(StringBuffer message, String condition) { message = new StringBuffer(); message.append("该对象有:"); message.append(condition); message.append("属性吗?"); int result = JOptionPane.showConfirmDialog(null, message.toString(), "逆向推理", JOptionPane.YES_NO_OPTION); return result; } public void showSuccess(String conclusion) { StringBuffer message = new StringBuffer(); message.append("推理成功!"); message.append("该对象为" + conclusion); JOptionPane.showMessageDialog(null, message.toString(), "逆向推理", JOptionPane.PLAIN_MESSAGE); } public void showFailure(String conclusion) { StringBuffer message = new StringBuffer(); message.append("推理失败!"); message.append("根据先有知识不能推出该对象为" + conclusion); JOptionPane.showMessageDialog(null, message.toString(), "逆向推理", JOptionPane.WARNING_MESSAGE); } } /* 暗斑点 <SUF>*/
false
2,433
23
2,853
32
3,071
23
2,853
32
3,656
41
false
false
false
false
false
true
66371_2
package chapter17.node04; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; /** (熟悉) * 获取运行时类的内部结构2: * 父类、接口们、包、带泛型的父类、父类的泛型等 */ public class ReflectionGetParent { public static void main(String[] args) throws ClassNotFoundException{ func1(); } public static void func1() throws ClassNotFoundException{ // 1.获取运行时类的父类 Class<?> clazz = Class.forName("chapter17.node01.Person"); Class<?> superClass = clazz.getSuperclass(); System.out.println(superClass); // 2.获取运行时类的带泛型的父类 Type genericSuperClass = clazz.getGenericSuperclass(); System.out.println(genericSuperClass); // 3.获取运行时类实现的接口 Class<?>[] interfaces = clazz.getInterfaces(); for (Class<?> class1 : interfaces) { System.out.println(class1); } // 4.获取运行时所在的包 Package package1 = clazz.getPackage(); System.out.println(package1); // 5.获取运行时类的父类的泛型(不易) 与 2是有区别的 // 需要通过 2 的带泛型的父类来获取 泛型实参 ParameterizedType parameterizedType = (ParameterizedType) genericSuperClass; Type[] arguments = parameterizedType.getActualTypeArguments(); // 获取父类泛型实参,可能有多个,因此是数组 System.out.println(((Class<?>) arguments[0]).getName());// 得到Creature<String>中的String } }
RonLee33/shangguigu
chapter17/node04/ReflectionGetParent.java
404
// 2.获取运行时类的带泛型的父类
line_comment
zh-cn
package chapter17.node04; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; /** (熟悉) * 获取运行时类的内部结构2: * 父类、接口们、包、带泛型的父类、父类的泛型等 */ public class ReflectionGetParent { public static void main(String[] args) throws ClassNotFoundException{ func1(); } public static void func1() throws ClassNotFoundException{ // 1.获取运行时类的父类 Class<?> clazz = Class.forName("chapter17.node01.Person"); Class<?> superClass = clazz.getSuperclass(); System.out.println(superClass); // 2. <SUF> Type genericSuperClass = clazz.getGenericSuperclass(); System.out.println(genericSuperClass); // 3.获取运行时类实现的接口 Class<?>[] interfaces = clazz.getInterfaces(); for (Class<?> class1 : interfaces) { System.out.println(class1); } // 4.获取运行时所在的包 Package package1 = clazz.getPackage(); System.out.println(package1); // 5.获取运行时类的父类的泛型(不易) 与 2是有区别的 // 需要通过 2 的带泛型的父类来获取 泛型实参 ParameterizedType parameterizedType = (ParameterizedType) genericSuperClass; Type[] arguments = parameterizedType.getActualTypeArguments(); // 获取父类泛型实参,可能有多个,因此是数组 System.out.println(((Class<?>) arguments[0]).getName());// 得到Creature<String>中的String } }
false
375
15
404
14
410
13
404
14
538
23
false
false
false
false
false
true
18668_28
package Game.Hero; import Util.Numeric.Entity; import Util.Numeric.Rect; import Util.Numeric.Rotate; import Util.Numeric.Vector; import java.awt.*; /** * Created by bakanaouji on 2017/07/23. * プレイヤーを表すクラス. */ public class Hero { /** * プレイヤーが選択できる行動 */ public enum Action { None, // 移動しない Right, // 右に移動 Left, // 左に移動 Up, // 上に移動 Down // 下に移動 } /** * コンストラクタ. * * @param aComp コンポーネント * @param aX 初期x座標 * @param aY 初期y座標 * @param aRot 初期回転角 */ public Hero(final Game.Component aComp, final double aX, final double aY, final double aRot) { // コンポーネント mComp = aComp; // 初期座標決定 mPos = new Vector(aX, aY); // 初期速度と加速度は0 mVelocity = new Vector(2); // 初期回転角決定 mRotate = new Rotate(aRot); // 画像読み込み if (mComp.viewer().paintPanel() != null) { mImage = mComp.viewer().paintPanel().getToolkit().getImage("../resource/Image/hero.png"); } else { mImage = null; } // エンティティは円 final Rect rect = new Rect(20.0, -20.0, 20.0, -20.0); mEntity = new Entity(mPos, mRotate, Entity.CollisionType.Circle, 20.0, rect); mIsDead = false; } /** * 更新を行うメソッド. * 行動を入力として受け取り,プレイヤーの座標を更新する. * 死亡判定も行い,死亡しているかどうかを返す. * * @param aAction 行動 * @return 死亡しているか */ public boolean update(final Action aAction) { // 死亡していたら更新しない if (mIsDead) { return true; } // 速度更新 mVelocity.value(0, 0.0); mVelocity.value(1, 0.0); switch (aAction) { case Right: mVelocity.value(0, 3.0); break; case Left: mVelocity.value(0, -3.0); break; case Up: mVelocity.value(1, -3.0); break; case Down: mVelocity.value(1, 3.0); break; } // 座標更新 mPos.value(0, mPos.value(0) + mVelocity.value(0)); mPos.value(1, mPos.value(1) + mVelocity.value(1)); // ヤリとの当たり判定 // 当たっている場合,死亡 final Vector collisionVec = new Vector(2); for (int i = 0; i < mComp.spearManager().count(); ++i) { boolean hit = mEntity.collidesWith(mComp.spearManager().spear(i).entity(), collisionVec); if (hit) { dead(); break; } } // エンティティ更新 mEntity.update(); return false; } /** * 描画を行うメソッド. */ public void draw() { // 死亡している場合,描画しない if (mIsDead) { return; } // 描画 mComp.viewer().paintPanel().graphics().drawImage(mImage, (int) mPos.value(0) - 20, (int) mPos.value(1) - 20, mComp.viewer().paintPanel()); } /** * 死亡させるメソッド. */ public void dead() { mIsDead = true; } /** * 死亡しているかどうかを取得するメソッド. * * @return 死亡しているかどうか */ public boolean isDead() { return mIsDead; } /** * 座標を取得するメソッド. * * @return 座標 */ public Vector pos() { return mPos; } /** * 復活させるメソッド. */ public void arrive() { mIsDead = false; } // コンポーネント private final Game.Component mComp; // 座標 private final Vector mPos; // 速度 private final Vector mVelocity; // 回転角 private final Rotate mRotate; // 画像ハンドル private final Image mImage; // エンティティ private final Entity mEntity; // 死亡状態か private boolean mIsDead; }
RosenblockChainers/MyRL
src/Game/Hero/Hero.java
1,346
// 回転角
line_comment
zh-cn
package Game.Hero; import Util.Numeric.Entity; import Util.Numeric.Rect; import Util.Numeric.Rotate; import Util.Numeric.Vector; import java.awt.*; /** * Created by bakanaouji on 2017/07/23. * プレイヤーを表すクラス. */ public class Hero { /** * プレイヤーが選択できる行動 */ public enum Action { None, // 移動しない Right, // 右に移動 Left, // 左に移動 Up, // 上に移動 Down // 下に移動 } /** * コンストラクタ. * * @param aComp コンポーネント * @param aX 初期x座標 * @param aY 初期y座標 * @param aRot 初期回転角 */ public Hero(final Game.Component aComp, final double aX, final double aY, final double aRot) { // コンポーネント mComp = aComp; // 初期座標決定 mPos = new Vector(aX, aY); // 初期速度と加速度は0 mVelocity = new Vector(2); // 初期回転角決定 mRotate = new Rotate(aRot); // 画像読み込み if (mComp.viewer().paintPanel() != null) { mImage = mComp.viewer().paintPanel().getToolkit().getImage("../resource/Image/hero.png"); } else { mImage = null; } // エンティティは円 final Rect rect = new Rect(20.0, -20.0, 20.0, -20.0); mEntity = new Entity(mPos, mRotate, Entity.CollisionType.Circle, 20.0, rect); mIsDead = false; } /** * 更新を行うメソッド. * 行動を入力として受け取り,プレイヤーの座標を更新する. * 死亡判定も行い,死亡しているかどうかを返す. * * @param aAction 行動 * @return 死亡しているか */ public boolean update(final Action aAction) { // 死亡していたら更新しない if (mIsDead) { return true; } // 速度更新 mVelocity.value(0, 0.0); mVelocity.value(1, 0.0); switch (aAction) { case Right: mVelocity.value(0, 3.0); break; case Left: mVelocity.value(0, -3.0); break; case Up: mVelocity.value(1, -3.0); break; case Down: mVelocity.value(1, 3.0); break; } // 座標更新 mPos.value(0, mPos.value(0) + mVelocity.value(0)); mPos.value(1, mPos.value(1) + mVelocity.value(1)); // ヤリとの当たり判定 // 当たっている場合,死亡 final Vector collisionVec = new Vector(2); for (int i = 0; i < mComp.spearManager().count(); ++i) { boolean hit = mEntity.collidesWith(mComp.spearManager().spear(i).entity(), collisionVec); if (hit) { dead(); break; } } // エンティティ更新 mEntity.update(); return false; } /** * 描画を行うメソッド. */ public void draw() { // 死亡している場合,描画しない if (mIsDead) { return; } // 描画 mComp.viewer().paintPanel().graphics().drawImage(mImage, (int) mPos.value(0) - 20, (int) mPos.value(1) - 20, mComp.viewer().paintPanel()); } /** * 死亡させるメソッド. */ public void dead() { mIsDead = true; } /** * 死亡しているかどうかを取得するメソッド. * * @return 死亡しているかどうか */ public boolean isDead() { return mIsDead; } /** * 座標を取得するメソッド. * * @return 座標 */ public Vector pos() { return mPos; } /** * 復活させるメソッド. */ public void arrive() { mIsDead = false; } // コンポーネント private final Game.Component mComp; // 座標 private final Vector mPos; // 速度 private final Vector mVelocity; // 回転 <SUF> private final Rotate mRotate; // 画像ハンドル private final Image mImage; // エンティティ private final Entity mEntity; // 死亡状態か private boolean mIsDead; }
false
1,204
6
1,346
6
1,242
4
1,346
6
1,702
7
false
false
false
false
false
true
45075_0
package nowCoderClass1.section9; /** * A(A也是他的编号)是一个孤傲的人,在一个n个人(其中编号依次为1到n)的队列中, * 他于其中的标号为b和标号c的人都有矛盾,所以他不会和他们站在相邻的位置。 * 现在问你满足A的要求的对列有多少种? */ public class LonelyA { public int getWays(int n, int A, int b, int c) { // write code here int count=0; if(n==3) return 0; //至少4个人 //先计算A站在开头或结尾的情况 count+=2*(n-3)*muti(n-2);//2是开头和结尾一样,(n-3)是站在A旁边的人有多少种可能性。muti是剩下的人全排列 //再计算A站在中间的情况 if(n>4){ //思路是A选定一个中间位置,再选两个人站在其旁边,其余的全排列 count+=(n-2)*(2*muti(n-3)/(muti(n-3-2)*2))*muti(n-3); } return count; } /** * 需要递归求积 */ public int muti(int num){ if(num==1){ return 1; } return num*muti(num-1); } }
RosinaWang/Algorithm
src/nowCoderClass1/section9/LonelyA.java
365
/** * A(A也是他的编号)是一个孤傲的人,在一个n个人(其中编号依次为1到n)的队列中, * 他于其中的标号为b和标号c的人都有矛盾,所以他不会和他们站在相邻的位置。 * 现在问你满足A的要求的对列有多少种? */
block_comment
zh-cn
package nowCoderClass1.section9; /** * A(A <SUF>*/ public class LonelyA { public int getWays(int n, int A, int b, int c) { // write code here int count=0; if(n==3) return 0; //至少4个人 //先计算A站在开头或结尾的情况 count+=2*(n-3)*muti(n-2);//2是开头和结尾一样,(n-3)是站在A旁边的人有多少种可能性。muti是剩下的人全排列 //再计算A站在中间的情况 if(n>4){ //思路是A选定一个中间位置,再选两个人站在其旁边,其余的全排列 count+=(n-2)*(2*muti(n-3)/(muti(n-3-2)*2))*muti(n-3); } return count; } /** * 需要递归求积 */ public int muti(int num){ if(num==1){ return 1; } return num*muti(num-1); } }
false
314
73
365
91
342
75
365
91
463
122
false
false
false
false
false
true
18856_3
package main.skill; import main.role.Role; import main.skill.attributes.change.AddDiceChangeAttribute; import main.skill.attributes.change.AddValueChangeAttribute; import main.skill.attributes.condition.ConsumeHpConditionAttribute; import main.skill.attributes.condition.LimitedNumConditionAttribute; import main.skill.attributes.condition.ProbabilisticTriggerConditionAttribute; import main.skill.attributes.condition.SpecialNumConditionAttribute; import main.skill.attributes.damage.FixedPlusDamageAttribute; import main.skill.attributes.damage.MultiplierDamageAttribute; import main.skill.attributes.health.PercentageHealthAttribute; /** *这个枚举代表游戏中不同类型的技能卡。 *每个技能卡都有一个类别和一个与之相关的SkillCard对象。 * SkillCard对象是使用Builder模式构建的。 */ public enum SkillCardTemplates { /** * 攻击类 */ DAMAGE_PERFECT_STRIKE("damage", new SkillCard.Builder("完美打击", "造成点数 * 12 伤害", "投入一个奇数骰子") .addDamageAttribute(new MultiplierDamageAttribute(12)) .addConditionAttribute(new SpecialNumConditionAttribute(1)) .addUseableCnt(1) .build()), DAMAGE_ANGRY("damage", new SkillCard.Builder("愤怒", "造成 2 伤害,本场战斗每使用一个骰子,该技能伤害 + 3", "无限制") .addDamageAttribute(new FixedPlusDamageAttribute(2, 3)) .addUseableCnt(3) .build()), DAMAGE_BOOM("damage", new SkillCard.Builder("#跟你爆了!", "造成 点数 * 99 伤害,消耗 99 HP", "投入一个偶数骰子") .addDamageAttribute(new MultiplierDamageAttribute(99)) .addConditionAttribute((value, role) -> { if (new SpecialNumConditionAttribute(2).isValid(value, role)) { new ConsumeHpConditionAttribute(99).isValid(value, role); return true; } return false; }) .addUseableCnt(1) .build()), /** * 变化类 */ CHANGE_THE_ITALIAN_JOB("change", new SkillCard.Builder("骰子·偷天换日", "获得一个 4-5 点的骰子", "最大 2 点") .addDiceChangeAttribute(new AddDiceChangeAttribute(1, 4, 5)) .addConditionAttribute(new LimitedNumConditionAttribute(1, 2)) .addUseableCnt(2) .build()), CHANGE_GIRLISH_PRIVILEGE("change", new SkillCard.Builder("递归", "投入骰子点数 + 1", "最大 5 点") .addDiceChangeAttribute(new AddValueChangeAttribute(1)) .addConditionAttribute(new LimitedNumConditionAttribute(1, 5)) .addUseableCnt(2) .build()), CHANGE_SUPER_LOTTO("change", new SkillCard.Builder("骰子大乐透", "获得随机点数的骰子,小概率失去 9 HP", "无限制") .addDiceChangeAttribute(new AddDiceChangeAttribute(1, 1, 6)) .addConditionAttribute((Integer value, Role role) -> { if (new ProbabilisticTriggerConditionAttribute(33).isValid(value, role)) { new ConsumeHpConditionAttribute(9).isValid(value, role); } return true; } ) .addDamageAttribute((num, enemy) -> System.out.println("【YOU】x 你失去了 9 HP")) .addUseableCnt(3) .build()), /** * 回复类 */ HEALTH_TAKO_WASABI("health", new SkillCard.Builder("回复·芥末章鱼", "回复 点数*1% 生命值,并造成 点数*5 伤害", "无限制") .addHealthAttribute(new PercentageHealthAttribute(1)) .addDamageAttribute(new MultiplierDamageAttribute(5)) .addUseableCnt(2) .build()), HEALTH_BIG_LUEN("health", new SkillCard.Builder("速效就补丸", "回复满HP", "最小 6") .addHealthAttribute(new PercentageHealthAttribute(100)) .addConditionAttribute(new LimitedNumConditionAttribute(6, 6)) .addUseableCnt(1) .build()), ; SkillCard card; String category; SkillCardTemplates(String category, main.skill.SkillCard card) { this.card = card; this.category = category; } public String getCategory() { return category; } public SkillCard getCard() { return card; } }
Ruafafa/Imitative_Dicey_Dungeons
src/main/skill/SkillCardTemplates.java
1,161
/** * 回复类 */
block_comment
zh-cn
package main.skill; import main.role.Role; import main.skill.attributes.change.AddDiceChangeAttribute; import main.skill.attributes.change.AddValueChangeAttribute; import main.skill.attributes.condition.ConsumeHpConditionAttribute; import main.skill.attributes.condition.LimitedNumConditionAttribute; import main.skill.attributes.condition.ProbabilisticTriggerConditionAttribute; import main.skill.attributes.condition.SpecialNumConditionAttribute; import main.skill.attributes.damage.FixedPlusDamageAttribute; import main.skill.attributes.damage.MultiplierDamageAttribute; import main.skill.attributes.health.PercentageHealthAttribute; /** *这个枚举代表游戏中不同类型的技能卡。 *每个技能卡都有一个类别和一个与之相关的SkillCard对象。 * SkillCard对象是使用Builder模式构建的。 */ public enum SkillCardTemplates { /** * 攻击类 */ DAMAGE_PERFECT_STRIKE("damage", new SkillCard.Builder("完美打击", "造成点数 * 12 伤害", "投入一个奇数骰子") .addDamageAttribute(new MultiplierDamageAttribute(12)) .addConditionAttribute(new SpecialNumConditionAttribute(1)) .addUseableCnt(1) .build()), DAMAGE_ANGRY("damage", new SkillCard.Builder("愤怒", "造成 2 伤害,本场战斗每使用一个骰子,该技能伤害 + 3", "无限制") .addDamageAttribute(new FixedPlusDamageAttribute(2, 3)) .addUseableCnt(3) .build()), DAMAGE_BOOM("damage", new SkillCard.Builder("#跟你爆了!", "造成 点数 * 99 伤害,消耗 99 HP", "投入一个偶数骰子") .addDamageAttribute(new MultiplierDamageAttribute(99)) .addConditionAttribute((value, role) -> { if (new SpecialNumConditionAttribute(2).isValid(value, role)) { new ConsumeHpConditionAttribute(99).isValid(value, role); return true; } return false; }) .addUseableCnt(1) .build()), /** * 变化类 */ CHANGE_THE_ITALIAN_JOB("change", new SkillCard.Builder("骰子·偷天换日", "获得一个 4-5 点的骰子", "最大 2 点") .addDiceChangeAttribute(new AddDiceChangeAttribute(1, 4, 5)) .addConditionAttribute(new LimitedNumConditionAttribute(1, 2)) .addUseableCnt(2) .build()), CHANGE_GIRLISH_PRIVILEGE("change", new SkillCard.Builder("递归", "投入骰子点数 + 1", "最大 5 点") .addDiceChangeAttribute(new AddValueChangeAttribute(1)) .addConditionAttribute(new LimitedNumConditionAttribute(1, 5)) .addUseableCnt(2) .build()), CHANGE_SUPER_LOTTO("change", new SkillCard.Builder("骰子大乐透", "获得随机点数的骰子,小概率失去 9 HP", "无限制") .addDiceChangeAttribute(new AddDiceChangeAttribute(1, 1, 6)) .addConditionAttribute((Integer value, Role role) -> { if (new ProbabilisticTriggerConditionAttribute(33).isValid(value, role)) { new ConsumeHpConditionAttribute(9).isValid(value, role); } return true; } ) .addDamageAttribute((num, enemy) -> System.out.println("【YOU】x 你失去了 9 HP")) .addUseableCnt(3) .build()), /** * 回复类 <SUF>*/ HEALTH_TAKO_WASABI("health", new SkillCard.Builder("回复·芥末章鱼", "回复 点数*1% 生命值,并造成 点数*5 伤害", "无限制") .addHealthAttribute(new PercentageHealthAttribute(1)) .addDamageAttribute(new MultiplierDamageAttribute(5)) .addUseableCnt(2) .build()), HEALTH_BIG_LUEN("health", new SkillCard.Builder("速效就补丸", "回复满HP", "最小 6") .addHealthAttribute(new PercentageHealthAttribute(100)) .addConditionAttribute(new LimitedNumConditionAttribute(6, 6)) .addUseableCnt(1) .build()), ; SkillCard card; String category; SkillCardTemplates(String category, main.skill.SkillCard card) { this.card = card; this.category = category; } public String getCategory() { return category; } public SkillCard getCard() { return card; } }
false
1,022
10
1,161
8
1,150
10
1,161
8
1,496
11
false
false
false
false
false
true
22155_2
package utils; import java.util.Scanner; public class CalendarPrinter { public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.print("请输入年份(大于1800年):"); int year = in.nextInt(); System.out.print("请输入月份(1-12月):"); int month = in.nextInt(); in.close(); printDate(year, month); } /** * 打印某年某月的日历 * * @param year 年 * @param month 月 */ public static void printDate(final int year, final int month) { System.out.println("=================================================="); System.out.println("日\t一\t二\t三\t四\t五\t六"); // 计算某年某月1日是星期几 final int startWeekday = calcWeekday(year, month); // 获取某年某月的天数 final int numberOfDaysInMonth = getNumberOfDaysInMonth(year, month); // 打印偏移 for (int i = 0; i < startWeekday; i++) { System.out.print(" \t"); } // 打印日期 for (int i = 1; i <= numberOfDaysInMonth; i++) { System.out.print(i + "\t"); // 一行显示7列,当日期+偏移是7的倍数时换行 if ((i + startWeekday) % 7 == 0) { System.out.println(); } } System.out.println("\n=================================================="); } /** * 计算某年某月1日,是星期几 * * @param year 年,不能小于 1800 年 * @param month 月 * @return 星期几(0-6,周日、周一~周六) */ public static int calcWeekday(int year, int month) { final int START_YEAR = 1800; final int START_DAY_FOR_JAN_1_1800 = 3; // 从 1800年 算起的总天数 long totalNumberOfDays = calcTotalNumberOfDays(START_YEAR, year, month); // (总天数 + 起始星期偏移)% 7 = 总天数的星期偏移 return (int) ((totalNumberOfDays + START_DAY_FOR_JAN_1_1800) % 7); } /** * 传入数值 @calcWeekday(year, month) 方法 * * @param weekday 值 * @return 星期 */ public static String getWeekdayText(int weekday) { return new String[]{"周日", "周一", "周二", "周三", "周四", "周五", "周六"}[weekday]; } /** * 计算从 起始年1月1日 到 某年某月 的天数 * * @param startYear 起始年 * @param year 年 * @param month 月 * @return 天数 */ public static long calcTotalNumberOfDays(int startYear, int year, int month) { long total = 0; // 计算从 起始年的1月1日 - 当前年1月1日 的天数 for (int i = startYear; i < year; i++) { if (isLeapYear(i)) total = total + 366; else total = total + 365; } // 计算从 1月份 - 当前月 的天数 for (int i = 0; i < month; i++) total += getNumberOfDaysInMonth(year, i); return total; } /** * 返回某年某月的天数 * * @param year 年 * @param month 月 * @return 天(28,29,30,31) */ public static int getNumberOfDaysInMonth(int year, int month) { if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) return 31; if (month == 4 || month == 6 || month == 9 || month == 11) return 30; if (month == 2) return isLeapYear(year) ? 29 : 28; return 0; } /** * 判断是否为闰年 * * @param year 年,如 2000 * @return true 表示是闰年 */ public static boolean isLeapYear(int year) { return year % 400 == 0 || (year % 4 == 0 && year % 100 != 0); } }
RuiRay/PhotosProducer
src/java/utils/CalendarPrinter.java
1,160
// 获取某年某月的天数
line_comment
zh-cn
package utils; import java.util.Scanner; public class CalendarPrinter { public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.print("请输入年份(大于1800年):"); int year = in.nextInt(); System.out.print("请输入月份(1-12月):"); int month = in.nextInt(); in.close(); printDate(year, month); } /** * 打印某年某月的日历 * * @param year 年 * @param month 月 */ public static void printDate(final int year, final int month) { System.out.println("=================================================="); System.out.println("日\t一\t二\t三\t四\t五\t六"); // 计算某年某月1日是星期几 final int startWeekday = calcWeekday(year, month); // 获取 <SUF> final int numberOfDaysInMonth = getNumberOfDaysInMonth(year, month); // 打印偏移 for (int i = 0; i < startWeekday; i++) { System.out.print(" \t"); } // 打印日期 for (int i = 1; i <= numberOfDaysInMonth; i++) { System.out.print(i + "\t"); // 一行显示7列,当日期+偏移是7的倍数时换行 if ((i + startWeekday) % 7 == 0) { System.out.println(); } } System.out.println("\n=================================================="); } /** * 计算某年某月1日,是星期几 * * @param year 年,不能小于 1800 年 * @param month 月 * @return 星期几(0-6,周日、周一~周六) */ public static int calcWeekday(int year, int month) { final int START_YEAR = 1800; final int START_DAY_FOR_JAN_1_1800 = 3; // 从 1800年 算起的总天数 long totalNumberOfDays = calcTotalNumberOfDays(START_YEAR, year, month); // (总天数 + 起始星期偏移)% 7 = 总天数的星期偏移 return (int) ((totalNumberOfDays + START_DAY_FOR_JAN_1_1800) % 7); } /** * 传入数值 @calcWeekday(year, month) 方法 * * @param weekday 值 * @return 星期 */ public static String getWeekdayText(int weekday) { return new String[]{"周日", "周一", "周二", "周三", "周四", "周五", "周六"}[weekday]; } /** * 计算从 起始年1月1日 到 某年某月 的天数 * * @param startYear 起始年 * @param year 年 * @param month 月 * @return 天数 */ public static long calcTotalNumberOfDays(int startYear, int year, int month) { long total = 0; // 计算从 起始年的1月1日 - 当前年1月1日 的天数 for (int i = startYear; i < year; i++) { if (isLeapYear(i)) total = total + 366; else total = total + 365; } // 计算从 1月份 - 当前月 的天数 for (int i = 0; i < month; i++) total += getNumberOfDaysInMonth(year, i); return total; } /** * 返回某年某月的天数 * * @param year 年 * @param month 月 * @return 天(28,29,30,31) */ public static int getNumberOfDaysInMonth(int year, int month) { if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) return 31; if (month == 4 || month == 6 || month == 9 || month == 11) return 30; if (month == 2) return isLeapYear(year) ? 29 : 28; return 0; } /** * 判断是否为闰年 * * @param year 年,如 2000 * @return true 表示是闰年 */ public static boolean isLeapYear(int year) { return year % 400 == 0 || (year % 4 == 0 && year % 100 != 0); } }
false
1,133
9
1,160
9
1,206
8
1,160
9
1,411
15
false
false
false
false
false
true
46334_14
/* * Copyright 2020-2022 RukkitDev Team and contributors. * * This project uses GNU Affero General Public License v3.0.You can find this license in the following link. * 本项目使用 GNU Affero General Public License v3.0 许可证,你可以在下方链接查看: * * https://github.com/RukkitDev/Rukkit/blob/master/LICENSE */ package cn.rukkit.game; import cn.rukkit.*; import cn.rukkit.network.*; import cn.rukkit.network.packet.Packet; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.yaml.snakeyaml.DumperOptions; import org.yaml.snakeyaml.Yaml; import org.yaml.snakeyaml.constructor.Constructor; import java.io.*; import java.nio.charset.StandardCharsets; import java.util.Date; import java.util.HashMap; public class NetworkPlayer { NetworkPlayerData data; public String name = "Player - Empty"; public String uuid = "null"; public int verifyCode = 114514; public int credits = 4000; public int team = 0; public int playerIndex; public boolean isEmpty = true; //public index; // Preparing for 1.15 public int startingUnit; private RoomConnection connection = null; public int ping = -1; public boolean isAdmin = false; public boolean isAI = false; public boolean isSharingControl = false; public boolean isSurrounded = false; private NetworkRoom room; public NetworkPlayer(RoomConnection connection) { this.connection = connection; this.room = connection.currectRoom; this.isEmpty = false; } public NetworkPlayer() { this.connection = null; this.isEmpty = true; } public RoomConnection getConnection() { return this.connection; } public NetworkRoom getRoom() { return this.room; } /** * get a extraData as a object, etc.. * @param key * @param defaultValue * @param tClass * @return * @param <T> */ public <T> T getExtraDataAs(String key, T defaultValue, Class<T> tClass) { return (T) data.extraData.getOrDefault(key, defaultValue); } /** * 获取玩家的临时数据 * @param key * @param defaultValue * @return */ public Object getTempData(String key, Object defaultValue) { return data.tempData.getOrDefault(key, defaultValue); } /** * 放入临时数据 * @param key * @param value */ public void putTempData(String key, Object value) { data.tempData.put(key, value); } public void clearTempData() { data.tempData = new HashMap<String, Object>(); } /** * Get extra data. * @param key * @param defaultValue * @return */ public Object getExtraData(String key, Object defaultValue) { return data.extraData.getOrDefault(key, defaultValue); } /** * Put a data to player's ExtraData. * @param key * @param value */ public void putExtraData(String key, Object value) { data.extraData.put(key, value); } /** * Save player data. */ public void savePlayerData() { Yaml yaml = new Yaml(new Constructor(NetworkPlayerData.class)); try { FileWriter writer = new FileWriter(Rukkit.getEnvPath() + "/data/player/" + uuid + ".yaml"); writer.write(yaml.dumpAs(data, null, DumperOptions.FlowStyle.BLOCK)); writer.flush(); writer.close(); } catch (FileNotFoundException e) { //This should NEVER HAPPEN! } catch (IOException e) { } } public void writePlayer(DataOutputStream stream, boolean simpleMode) throws IOException { if (simpleMode) { stream.writeByte(0); stream.writeInt(ping); stream.writeBoolean(true); stream.writeBoolean(true); } else { //玩家位置 stream.writeByte(playerIndex); //玩家资金(毫无作用) stream.writeInt(credits); //玩家队 stream.writeInt(team); stream.writeBoolean(true); if(isAdmin){ stream.writeUTF("[[[" + name + "]]]"); }else{ stream.writeUTF(name); } stream.writeBoolean(true); //enc.stream.writeBoolean(true); stream.writeInt(ping); stream.writeLong(System.currentTimeMillis()); //是否AI stream.writeBoolean(isAI); //AI难度 stream.writeInt(0); //玩家队伍 stream.writeInt(team); stream.writeByte(0); //分享控制 stream.writeBoolean(isSharingControl); //是否掉线 stream.writeBoolean(false); //是否投降 stream.writeBoolean(isSurrounded); stream.writeBoolean(false); stream.writeInt(-9999); stream.writeBoolean(false); //是否房主 stream.writeInt(0); // 1.15新增 stream.writeBoolean(false); stream.writeBoolean(false); stream.writeBoolean(false); stream.writeBoolean(false); //color stream.writeInt(playerIndex); } } public boolean movePlayer(int index){ //If index larger then maxPlayer if (index > Rukkit.getConfig().maxPlayer) return false; PlayerManager playerGroup = room.playerManager; if (!playerGroup.get(index).isEmpty) { return false; } this.playerIndex = index; playerGroup.remove(this); playerGroup.set(index, this); return true; } public boolean moveTeam(int team){ if(team > 9 || team < 0){ return false; } else { this.team = team; } return true; } public boolean giveAdmin(int index){ NetworkPlayer player = room.playerManager.get(index); if(index < Rukkit.getConfig().maxPlayer && index >= 0 && !player.isEmpty && this.isAdmin){ player.isAdmin = true; this.isAdmin = false; return true; } return false; } public void updateServerInfo() { try { connection.handler.ctx.writeAndFlush(Packet.serverInfo(room.config, isAdmin)); } catch (IOException e) {} } @Override public String toString() { return "NetworkPlayer{" + "name='" + name + '\'' + ", uuid='" + uuid + '\'' + ", team=" + team + ", playerIndex=" + playerIndex + ", ping=" + ping + ", isAdmin=" + isAdmin + ", isSharingControl=" + isSharingControl + ", isSurrounded=" + isSurrounded + '}'; } public boolean isNull() { return false; } public static final void initPlayerDataDir() { File dataDir = new File(Rukkit.getEnvPath() + "/data"); if (!dataDir.isDirectory()) { dataDir.delete(); dataDir.mkdir(); } File userDataDir = new File(Rukkit.getEnvPath() + "/data/player"); if (!userDataDir.isDirectory()) { userDataDir.delete(); userDataDir.mkdir(); } } public void loadPlayerData() { Logger log = LoggerFactory.getLogger("PlayerData"); log.info("Load player infomation."); Yaml yaml = new Yaml(new Constructor(NetworkPlayerData.class)); File dataFile = new File(Rukkit.getEnvPath() + "/data/player/" + uuid + ".yaml"); try { if (dataFile.exists()) { log.info("Player exists.Loading..."); data = yaml.load(new FileInputStream(dataFile)); data.lastUsedName = name; data.lastConnectedTime = new Date().toString(); data.lastConnectedAddress = connection.handler.ctx.channel().remoteAddress().toString(); Writer writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(dataFile), StandardCharsets.UTF_8)); writer.write(yaml.dumpAs(data, null, DumperOptions.FlowStyle.BLOCK)); writer.flush(); writer.close(); } else { log.info("New player.Creating file..."); dataFile.createNewFile(); data = new NetworkPlayerData(); data.uuid = uuid; data.lastUsedName = name; data.lastConnectedTime = new Date().toString(); data.lastConnectedAddress = connection.handler.ctx.channel().remoteAddress().toString(); Writer writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(dataFile), StandardCharsets.UTF_8)); writer.write(yaml.dumpAs(data, null, DumperOptions.FlowStyle.BLOCK)); writer.flush(); writer.close(); } } catch (FileNotFoundException ignored) { // Never happen! } catch (IOException e) { } } }
RukkitDev/Rukkit
src/main/java/cn/rukkit/game/NetworkPlayer.java
2,356
//是否AI
line_comment
zh-cn
/* * Copyright 2020-2022 RukkitDev Team and contributors. * * This project uses GNU Affero General Public License v3.0.You can find this license in the following link. * 本项目使用 GNU Affero General Public License v3.0 许可证,你可以在下方链接查看: * * https://github.com/RukkitDev/Rukkit/blob/master/LICENSE */ package cn.rukkit.game; import cn.rukkit.*; import cn.rukkit.network.*; import cn.rukkit.network.packet.Packet; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.yaml.snakeyaml.DumperOptions; import org.yaml.snakeyaml.Yaml; import org.yaml.snakeyaml.constructor.Constructor; import java.io.*; import java.nio.charset.StandardCharsets; import java.util.Date; import java.util.HashMap; public class NetworkPlayer { NetworkPlayerData data; public String name = "Player - Empty"; public String uuid = "null"; public int verifyCode = 114514; public int credits = 4000; public int team = 0; public int playerIndex; public boolean isEmpty = true; //public index; // Preparing for 1.15 public int startingUnit; private RoomConnection connection = null; public int ping = -1; public boolean isAdmin = false; public boolean isAI = false; public boolean isSharingControl = false; public boolean isSurrounded = false; private NetworkRoom room; public NetworkPlayer(RoomConnection connection) { this.connection = connection; this.room = connection.currectRoom; this.isEmpty = false; } public NetworkPlayer() { this.connection = null; this.isEmpty = true; } public RoomConnection getConnection() { return this.connection; } public NetworkRoom getRoom() { return this.room; } /** * get a extraData as a object, etc.. * @param key * @param defaultValue * @param tClass * @return * @param <T> */ public <T> T getExtraDataAs(String key, T defaultValue, Class<T> tClass) { return (T) data.extraData.getOrDefault(key, defaultValue); } /** * 获取玩家的临时数据 * @param key * @param defaultValue * @return */ public Object getTempData(String key, Object defaultValue) { return data.tempData.getOrDefault(key, defaultValue); } /** * 放入临时数据 * @param key * @param value */ public void putTempData(String key, Object value) { data.tempData.put(key, value); } public void clearTempData() { data.tempData = new HashMap<String, Object>(); } /** * Get extra data. * @param key * @param defaultValue * @return */ public Object getExtraData(String key, Object defaultValue) { return data.extraData.getOrDefault(key, defaultValue); } /** * Put a data to player's ExtraData. * @param key * @param value */ public void putExtraData(String key, Object value) { data.extraData.put(key, value); } /** * Save player data. */ public void savePlayerData() { Yaml yaml = new Yaml(new Constructor(NetworkPlayerData.class)); try { FileWriter writer = new FileWriter(Rukkit.getEnvPath() + "/data/player/" + uuid + ".yaml"); writer.write(yaml.dumpAs(data, null, DumperOptions.FlowStyle.BLOCK)); writer.flush(); writer.close(); } catch (FileNotFoundException e) { //This should NEVER HAPPEN! } catch (IOException e) { } } public void writePlayer(DataOutputStream stream, boolean simpleMode) throws IOException { if (simpleMode) { stream.writeByte(0); stream.writeInt(ping); stream.writeBoolean(true); stream.writeBoolean(true); } else { //玩家位置 stream.writeByte(playerIndex); //玩家资金(毫无作用) stream.writeInt(credits); //玩家队 stream.writeInt(team); stream.writeBoolean(true); if(isAdmin){ stream.writeUTF("[[[" + name + "]]]"); }else{ stream.writeUTF(name); } stream.writeBoolean(true); //enc.stream.writeBoolean(true); stream.writeInt(ping); stream.writeLong(System.currentTimeMillis()); //是否 <SUF> stream.writeBoolean(isAI); //AI难度 stream.writeInt(0); //玩家队伍 stream.writeInt(team); stream.writeByte(0); //分享控制 stream.writeBoolean(isSharingControl); //是否掉线 stream.writeBoolean(false); //是否投降 stream.writeBoolean(isSurrounded); stream.writeBoolean(false); stream.writeInt(-9999); stream.writeBoolean(false); //是否房主 stream.writeInt(0); // 1.15新增 stream.writeBoolean(false); stream.writeBoolean(false); stream.writeBoolean(false); stream.writeBoolean(false); //color stream.writeInt(playerIndex); } } public boolean movePlayer(int index){ //If index larger then maxPlayer if (index > Rukkit.getConfig().maxPlayer) return false; PlayerManager playerGroup = room.playerManager; if (!playerGroup.get(index).isEmpty) { return false; } this.playerIndex = index; playerGroup.remove(this); playerGroup.set(index, this); return true; } public boolean moveTeam(int team){ if(team > 9 || team < 0){ return false; } else { this.team = team; } return true; } public boolean giveAdmin(int index){ NetworkPlayer player = room.playerManager.get(index); if(index < Rukkit.getConfig().maxPlayer && index >= 0 && !player.isEmpty && this.isAdmin){ player.isAdmin = true; this.isAdmin = false; return true; } return false; } public void updateServerInfo() { try { connection.handler.ctx.writeAndFlush(Packet.serverInfo(room.config, isAdmin)); } catch (IOException e) {} } @Override public String toString() { return "NetworkPlayer{" + "name='" + name + '\'' + ", uuid='" + uuid + '\'' + ", team=" + team + ", playerIndex=" + playerIndex + ", ping=" + ping + ", isAdmin=" + isAdmin + ", isSharingControl=" + isSharingControl + ", isSurrounded=" + isSurrounded + '}'; } public boolean isNull() { return false; } public static final void initPlayerDataDir() { File dataDir = new File(Rukkit.getEnvPath() + "/data"); if (!dataDir.isDirectory()) { dataDir.delete(); dataDir.mkdir(); } File userDataDir = new File(Rukkit.getEnvPath() + "/data/player"); if (!userDataDir.isDirectory()) { userDataDir.delete(); userDataDir.mkdir(); } } public void loadPlayerData() { Logger log = LoggerFactory.getLogger("PlayerData"); log.info("Load player infomation."); Yaml yaml = new Yaml(new Constructor(NetworkPlayerData.class)); File dataFile = new File(Rukkit.getEnvPath() + "/data/player/" + uuid + ".yaml"); try { if (dataFile.exists()) { log.info("Player exists.Loading..."); data = yaml.load(new FileInputStream(dataFile)); data.lastUsedName = name; data.lastConnectedTime = new Date().toString(); data.lastConnectedAddress = connection.handler.ctx.channel().remoteAddress().toString(); Writer writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(dataFile), StandardCharsets.UTF_8)); writer.write(yaml.dumpAs(data, null, DumperOptions.FlowStyle.BLOCK)); writer.flush(); writer.close(); } else { log.info("New player.Creating file..."); dataFile.createNewFile(); data = new NetworkPlayerData(); data.uuid = uuid; data.lastUsedName = name; data.lastConnectedTime = new Date().toString(); data.lastConnectedAddress = connection.handler.ctx.channel().remoteAddress().toString(); Writer writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(dataFile), StandardCharsets.UTF_8)); writer.write(yaml.dumpAs(data, null, DumperOptions.FlowStyle.BLOCK)); writer.flush(); writer.close(); } } catch (FileNotFoundException ignored) { // Never happen! } catch (IOException e) { } } }
false
1,907
3
2,356
3
2,352
3
2,356
3
2,893
4
false
false
false
false
false
true
18568_24
package email.content; import javax.mail.Address; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import java.util.Date; import java.util.Properties; /** * JavaMail 版本: 1.6.0 * JDK 版本: JDK 1.7 以上(必须) */ public class Main { // 发件人的 邮箱 和 密码(替换为自己的邮箱和密码) // PS: 某些邮箱服务器为了增加邮箱本身密码的安全性,给 SMTP 客户端设置了独立密码(有的邮箱称为“授权码”), // 对于开启了独立密码的邮箱, 这里的邮箱密码必需使用这个独立密码(授权码)。 public String myEmailAccount = "[email protected]"; public String myEmailPassword = "qyeycemagybdijgc"; public String personal= ""; public String subject= ""; public String value=""; // 发件人邮箱的 SMTP 服务器地址, 必须准确, 不同邮件服务器地址不同, 一般(只是一般, 绝非绝对)格式为: smtp.xxx.com // 网易163邮箱的 SMTP 服务器地址为: smtp.163.com public String myEmailSMTPHost = "smtp.163.com"; // 收件人邮箱(替换为自己知道的有效邮箱) public static String[] receiveMailAccount={"[email protected]"}; public void setValue(String myEmailAccount,String myEmailPassword,String myEmailSMTPHost,String[] receiveMailAccount,String subject,String personal,String value){ this.myEmailAccount = myEmailAccount; this.myEmailPassword = myEmailPassword; this.myEmailSMTPHost = myEmailSMTPHost; this.receiveMailAccount = receiveMailAccount; this.personal=personal; this.value=value; this.subject=subject; } public void start(){ Properties props = new Properties(); // 参数配置 props.setProperty("mail.transport.protocol", "smtp"); // 使用的协议(JavaMail规范要求) props.setProperty("mail.smtp.host", myEmailSMTPHost); // 发件人的邮箱的 SMTP 服务器地址 props.setProperty("mail.smtp.auth", "true"); // 需要请求认证 // PS: 某些邮箱服务器要求 SMTP 连接需要使用 SSL 安全认证 (为了提高安全性, 邮箱支持SSL连接, 也可以自己开启), // 如果无法连接邮件服务器, 仔细查看控制台打印的 log, 如果有有类似 “连接失败, 要求 SSL 安全连接” 等错误, // 打开下面 /* ... */ 之间的注释代码, 开启 SSL 安全连接。 /* // SMTP 服务器的端口 (非 SSL 连接的端口一般默认为 25, 可以不添加, 如果开启了 SSL 连接, // 需要改为对应邮箱的 SMTP 服务器的端口, 具体可查看对应邮箱服务的帮助, // QQ邮箱的SMTP(SLL)端口为465或587, 其他邮箱自行去查看) final String smtpPort = "465"; props.setProperty("mail.smtp.port", smtpPort); props.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); props.setProperty("mail.smtp.socketFactory.fallback", "false"); props.setProperty("mail.smtp.socketFactory.port", smtpPort); */ final String smtpPort = "465"; props.setProperty("mail.smtp.port", smtpPort); props.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); props.setProperty("mail.smtp.socketFactory.fallback", "false"); props.setProperty("mail.smtp.socketFactory.port", smtpPort); // 2. 根据配置创建会话对象, 用于和邮件服务器交互 Session session = Session.getInstance(props); session.setDebug(true); // 设置为debug模式, 可以查看详细的发送 log // 3. 创建一封邮件 MimeMessage message = null; try { message = createMimeMessage(session, myEmailAccount, receiveMailAccount); // 4. 根据 Session 获取邮件传输对象 Transport transport = session.getTransport(); // 5. 使用 邮箱账号 和 密码 连接邮件服务器, 这里认证的邮箱必须与 message 中的发件人邮箱一致, 否则报错 // // PS_01: 成败的判断关键在此一句, 如果连接服务器失败, 都会在控制台输出相应失败原因的 log, // 仔细查看失败原因, 有些邮箱服务器会返回错误码或查看错误类型的链接, 根据给出的错误 // 类型到对应邮件服务器的帮助网站上查看具体失败原因。 // // PS_02: 连接失败的原因通常为以下几点, 仔细检查代码: // (1) 邮箱没有开启 SMTP 服务; // (2) 邮箱密码错误, 例如某些邮箱开启了独立密码; // (3) 邮箱服务器要求必须要使用 SSL 安全连接; // (4) 请求过于频繁或其他原因, 被邮件服务器拒绝服务; // (5) 如果以上几点都确定无误, 到邮件服务器网站查找帮助。 // // PS_03: 仔细看log, 认真看log, 看懂log, 错误原因都在log已说明。 transport.connect(myEmailAccount, myEmailPassword); // 6. 发送邮件, 发到所有的收件地址, message.getAllRecipients() 获取到的是在创建邮件对象时添加的所有收件人, 抄送人, 密送人 transport.sendMessage(message, message.getAllRecipients()); // 7. 关闭连接 transport.close(); } catch (Exception e) { e.printStackTrace(); } } public static void main(String[] args) throws Exception { // 1. 创建参数配置, 用于连接邮件服务器的参数配置 } /** * 创建一封只包含文本的简单邮件 * * @param session 和服务器交互的会话 * @param sendMail 发件人邮箱 * @param receiveMail 收件人邮箱 * @return * @throws Exception */ public MimeMessage createMimeMessage(Session session, String sendMail, String[] receiveMail) throws Exception { // 1. 创建一封邮件 MimeMessage message = new MimeMessage(session); // 2. From: 发件人(昵称有广告嫌疑,避免被邮件服务器误认为是滥发广告以至返回失败,请修改昵称) message.setFrom(new InternetAddress(sendMail, personal, "UTF-8")); Address a = null; // 3. To: 收件人(可以增加多个收件人、抄送、密送) // for (String email:receiveMail) { // a = new InternetAddress(email, personal1, "UTF-8"); // } InternetAddress[] address = new InternetAddress[receiveMail.length]; for (int i = 0; i < receiveMail.length; i++) { address[i] = new InternetAddress(receiveMail[i]); } message.setRecipients(MimeMessage.RecipientType.TO, address); // 4. Subject: 邮件主题(标题有广告嫌疑,避免被邮件服务器误认为是滥发广告以至返回失败,请修改标题) message.setSubject(subject, "UTF-8"); // 5. Content: 邮件正文(可以使用html标签)(内容有广告嫌疑,避免被邮件服务器误认为是滥发广告以至返回失败,请修改发送内容) message.setContent(value, "text/html;charset=UTF-8"); // 6. 设置发件时间 message.setSentDate(new Date()); // 7. 保存设置 message.saveChanges(); return message; } }
Run0nceEx/cna_email
Main.java
1,910
// (1) 邮箱没有开启 SMTP 服务;
line_comment
zh-cn
package email.content; import javax.mail.Address; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import java.util.Date; import java.util.Properties; /** * JavaMail 版本: 1.6.0 * JDK 版本: JDK 1.7 以上(必须) */ public class Main { // 发件人的 邮箱 和 密码(替换为自己的邮箱和密码) // PS: 某些邮箱服务器为了增加邮箱本身密码的安全性,给 SMTP 客户端设置了独立密码(有的邮箱称为“授权码”), // 对于开启了独立密码的邮箱, 这里的邮箱密码必需使用这个独立密码(授权码)。 public String myEmailAccount = "[email protected]"; public String myEmailPassword = "qyeycemagybdijgc"; public String personal= ""; public String subject= ""; public String value=""; // 发件人邮箱的 SMTP 服务器地址, 必须准确, 不同邮件服务器地址不同, 一般(只是一般, 绝非绝对)格式为: smtp.xxx.com // 网易163邮箱的 SMTP 服务器地址为: smtp.163.com public String myEmailSMTPHost = "smtp.163.com"; // 收件人邮箱(替换为自己知道的有效邮箱) public static String[] receiveMailAccount={"[email protected]"}; public void setValue(String myEmailAccount,String myEmailPassword,String myEmailSMTPHost,String[] receiveMailAccount,String subject,String personal,String value){ this.myEmailAccount = myEmailAccount; this.myEmailPassword = myEmailPassword; this.myEmailSMTPHost = myEmailSMTPHost; this.receiveMailAccount = receiveMailAccount; this.personal=personal; this.value=value; this.subject=subject; } public void start(){ Properties props = new Properties(); // 参数配置 props.setProperty("mail.transport.protocol", "smtp"); // 使用的协议(JavaMail规范要求) props.setProperty("mail.smtp.host", myEmailSMTPHost); // 发件人的邮箱的 SMTP 服务器地址 props.setProperty("mail.smtp.auth", "true"); // 需要请求认证 // PS: 某些邮箱服务器要求 SMTP 连接需要使用 SSL 安全认证 (为了提高安全性, 邮箱支持SSL连接, 也可以自己开启), // 如果无法连接邮件服务器, 仔细查看控制台打印的 log, 如果有有类似 “连接失败, 要求 SSL 安全连接” 等错误, // 打开下面 /* ... */ 之间的注释代码, 开启 SSL 安全连接。 /* // SMTP 服务器的端口 (非 SSL 连接的端口一般默认为 25, 可以不添加, 如果开启了 SSL 连接, // 需要改为对应邮箱的 SMTP 服务器的端口, 具体可查看对应邮箱服务的帮助, // QQ邮箱的SMTP(SLL)端口为465或587, 其他邮箱自行去查看) final String smtpPort = "465"; props.setProperty("mail.smtp.port", smtpPort); props.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); props.setProperty("mail.smtp.socketFactory.fallback", "false"); props.setProperty("mail.smtp.socketFactory.port", smtpPort); */ final String smtpPort = "465"; props.setProperty("mail.smtp.port", smtpPort); props.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); props.setProperty("mail.smtp.socketFactory.fallback", "false"); props.setProperty("mail.smtp.socketFactory.port", smtpPort); // 2. 根据配置创建会话对象, 用于和邮件服务器交互 Session session = Session.getInstance(props); session.setDebug(true); // 设置为debug模式, 可以查看详细的发送 log // 3. 创建一封邮件 MimeMessage message = null; try { message = createMimeMessage(session, myEmailAccount, receiveMailAccount); // 4. 根据 Session 获取邮件传输对象 Transport transport = session.getTransport(); // 5. 使用 邮箱账号 和 密码 连接邮件服务器, 这里认证的邮箱必须与 message 中的发件人邮箱一致, 否则报错 // // PS_01: 成败的判断关键在此一句, 如果连接服务器失败, 都会在控制台输出相应失败原因的 log, // 仔细查看失败原因, 有些邮箱服务器会返回错误码或查看错误类型的链接, 根据给出的错误 // 类型到对应邮件服务器的帮助网站上查看具体失败原因。 // // PS_02: 连接失败的原因通常为以下几点, 仔细检查代码: // (1 <SUF> // (2) 邮箱密码错误, 例如某些邮箱开启了独立密码; // (3) 邮箱服务器要求必须要使用 SSL 安全连接; // (4) 请求过于频繁或其他原因, 被邮件服务器拒绝服务; // (5) 如果以上几点都确定无误, 到邮件服务器网站查找帮助。 // // PS_03: 仔细看log, 认真看log, 看懂log, 错误原因都在log已说明。 transport.connect(myEmailAccount, myEmailPassword); // 6. 发送邮件, 发到所有的收件地址, message.getAllRecipients() 获取到的是在创建邮件对象时添加的所有收件人, 抄送人, 密送人 transport.sendMessage(message, message.getAllRecipients()); // 7. 关闭连接 transport.close(); } catch (Exception e) { e.printStackTrace(); } } public static void main(String[] args) throws Exception { // 1. 创建参数配置, 用于连接邮件服务器的参数配置 } /** * 创建一封只包含文本的简单邮件 * * @param session 和服务器交互的会话 * @param sendMail 发件人邮箱 * @param receiveMail 收件人邮箱 * @return * @throws Exception */ public MimeMessage createMimeMessage(Session session, String sendMail, String[] receiveMail) throws Exception { // 1. 创建一封邮件 MimeMessage message = new MimeMessage(session); // 2. From: 发件人(昵称有广告嫌疑,避免被邮件服务器误认为是滥发广告以至返回失败,请修改昵称) message.setFrom(new InternetAddress(sendMail, personal, "UTF-8")); Address a = null; // 3. To: 收件人(可以增加多个收件人、抄送、密送) // for (String email:receiveMail) { // a = new InternetAddress(email, personal1, "UTF-8"); // } InternetAddress[] address = new InternetAddress[receiveMail.length]; for (int i = 0; i < receiveMail.length; i++) { address[i] = new InternetAddress(receiveMail[i]); } message.setRecipients(MimeMessage.RecipientType.TO, address); // 4. Subject: 邮件主题(标题有广告嫌疑,避免被邮件服务器误认为是滥发广告以至返回失败,请修改标题) message.setSubject(subject, "UTF-8"); // 5. Content: 邮件正文(可以使用html标签)(内容有广告嫌疑,避免被邮件服务器误认为是滥发广告以至返回失败,请修改发送内容) message.setContent(value, "text/html;charset=UTF-8"); // 6. 设置发件时间 message.setSentDate(new Date()); // 7. 保存设置 message.saveChanges(); return message; } }
false
1,799
15
1,900
13
1,905
13
1,900
13
2,886
25
false
false
false
false
false
true
23751_2
package com.borun.easybill.utils; import android.content.Context; import android.content.SharedPreferences; import com.borun.easybill.model.bean.local.NoteBean; import com.borun.easybill.model.bean.remote.UserBean; import com.google.gson.Gson; /** * Created by Qing on 2018/10/25. */ public class SharedPUtils { public final static String USER_INFOR = "userInfo"; public final static String USER_SETTING = "userSetting"; /** * 获取当前用户 */ public static UserBean getCurrentUser(Context context) { SharedPreferences sp = context.getSharedPreferences(USER_INFOR, Context.MODE_PRIVATE); if (sp != null) { Gson gson = new Gson(); return gson.fromJson(sp.getString("jsonStr", null), UserBean.class); } return null; } /** * 设置当前用户 */ public static void setCurrentUser(Context context, String jsonStr) { Gson gson = new Gson(); UserBean userBean = gson.fromJson(jsonStr, UserBean.class); SharedPreferences sp = context.getSharedPreferences(USER_INFOR, Context.MODE_PRIVATE); SharedPreferences.Editor editor = sp.edit(); editor.putString("username", userBean.getUsername()); editor.putString("email", userBean.getMail()); editor.putString("id", userBean.getId()); editor.putString("jsonStr", jsonStr); editor.commit(); } /** * 设置当前用户 */ public static void setCurrentUser(Context context, UserBean userBean) { Gson gson = new Gson(); String jsonStr = gson.toJson(userBean); SharedPreferences sp = context.getSharedPreferences(USER_INFOR, Context.MODE_PRIVATE); SharedPreferences.Editor editor = sp.edit(); editor.putString("username", userBean.getUsername()); editor.putString("email", userBean.getMail()); editor.putString("id", userBean.getId()); editor.putString("jsonStr", jsonStr); editor.commit(); } /** * 获取当前用户账单分类信息 */ public static NoteBean getUserNoteBean(Context context) { SharedPreferences sp = context.getSharedPreferences(USER_INFOR, Context.MODE_PRIVATE); if (sp != null) { String jsonStr = sp.getString("noteBean", null); if (jsonStr != null) { Gson gson = new Gson(); return gson.fromJson(jsonStr, NoteBean.class); } } return null; } /** * 设置当前用户账单分类信息 */ public static void setUserNoteBean(Context context, String jsonStr) { SharedPreferences sp = context.getSharedPreferences(USER_INFOR, Context.MODE_PRIVATE); SharedPreferences.Editor editor = sp.edit(); editor.putString("noteBean", jsonStr); editor.commit(); } /** * 设置当前用户账单分类信息 */ public static void setUserNoteBean(Context context, NoteBean noteBean) { Gson gson = new Gson(); String jsonStr = gson.toJson(noteBean); SharedPreferences sp = context.getSharedPreferences(USER_INFOR, Context.MODE_PRIVATE); SharedPreferences.Editor editor = sp.edit(); editor.putString("noteBean", jsonStr); editor.commit(); } /** * 获取当前用户主题 */ public static String getCurrentTheme(Context context) { SharedPreferences sp = context.getSharedPreferences(USER_SETTING, Context.MODE_PRIVATE); if (sp != null) return sp.getString("theme", "原谅绿"); return null; } /** * 获取当前用户主题 */ public static void setCurrentTheme(Context context, String theme) { SharedPreferences sp = context.getSharedPreferences(USER_SETTING, Context.MODE_PRIVATE); SharedPreferences.Editor editor = sp.edit(); if (editor != null) { editor.putString("theme", theme); editor.commit(); } } /** * 判断是否第一次进入APP * * @param context * @return */ public static boolean isFirstStart(Context context) { SharedPreferences sp = context.getSharedPreferences(USER_SETTING, Context.MODE_PRIVATE); boolean isFirst = sp.getBoolean("first", true); //第一次则修改记录 if (isFirst) sp.edit().putBoolean("first", false).commit(); return isFirst; } }
Run2948/EasyBill
app/src/main/java/com/borun/easybill/utils/SharedPUtils.java
1,014
/** * 设置当前用户 */
block_comment
zh-cn
package com.borun.easybill.utils; import android.content.Context; import android.content.SharedPreferences; import com.borun.easybill.model.bean.local.NoteBean; import com.borun.easybill.model.bean.remote.UserBean; import com.google.gson.Gson; /** * Created by Qing on 2018/10/25. */ public class SharedPUtils { public final static String USER_INFOR = "userInfo"; public final static String USER_SETTING = "userSetting"; /** * 获取当前用户 */ public static UserBean getCurrentUser(Context context) { SharedPreferences sp = context.getSharedPreferences(USER_INFOR, Context.MODE_PRIVATE); if (sp != null) { Gson gson = new Gson(); return gson.fromJson(sp.getString("jsonStr", null), UserBean.class); } return null; } /** * 设置当 <SUF>*/ public static void setCurrentUser(Context context, String jsonStr) { Gson gson = new Gson(); UserBean userBean = gson.fromJson(jsonStr, UserBean.class); SharedPreferences sp = context.getSharedPreferences(USER_INFOR, Context.MODE_PRIVATE); SharedPreferences.Editor editor = sp.edit(); editor.putString("username", userBean.getUsername()); editor.putString("email", userBean.getMail()); editor.putString("id", userBean.getId()); editor.putString("jsonStr", jsonStr); editor.commit(); } /** * 设置当前用户 */ public static void setCurrentUser(Context context, UserBean userBean) { Gson gson = new Gson(); String jsonStr = gson.toJson(userBean); SharedPreferences sp = context.getSharedPreferences(USER_INFOR, Context.MODE_PRIVATE); SharedPreferences.Editor editor = sp.edit(); editor.putString("username", userBean.getUsername()); editor.putString("email", userBean.getMail()); editor.putString("id", userBean.getId()); editor.putString("jsonStr", jsonStr); editor.commit(); } /** * 获取当前用户账单分类信息 */ public static NoteBean getUserNoteBean(Context context) { SharedPreferences sp = context.getSharedPreferences(USER_INFOR, Context.MODE_PRIVATE); if (sp != null) { String jsonStr = sp.getString("noteBean", null); if (jsonStr != null) { Gson gson = new Gson(); return gson.fromJson(jsonStr, NoteBean.class); } } return null; } /** * 设置当前用户账单分类信息 */ public static void setUserNoteBean(Context context, String jsonStr) { SharedPreferences sp = context.getSharedPreferences(USER_INFOR, Context.MODE_PRIVATE); SharedPreferences.Editor editor = sp.edit(); editor.putString("noteBean", jsonStr); editor.commit(); } /** * 设置当前用户账单分类信息 */ public static void setUserNoteBean(Context context, NoteBean noteBean) { Gson gson = new Gson(); String jsonStr = gson.toJson(noteBean); SharedPreferences sp = context.getSharedPreferences(USER_INFOR, Context.MODE_PRIVATE); SharedPreferences.Editor editor = sp.edit(); editor.putString("noteBean", jsonStr); editor.commit(); } /** * 获取当前用户主题 */ public static String getCurrentTheme(Context context) { SharedPreferences sp = context.getSharedPreferences(USER_SETTING, Context.MODE_PRIVATE); if (sp != null) return sp.getString("theme", "原谅绿"); return null; } /** * 获取当前用户主题 */ public static void setCurrentTheme(Context context, String theme) { SharedPreferences sp = context.getSharedPreferences(USER_SETTING, Context.MODE_PRIVATE); SharedPreferences.Editor editor = sp.edit(); if (editor != null) { editor.putString("theme", theme); editor.commit(); } } /** * 判断是否第一次进入APP * * @param context * @return */ public static boolean isFirstStart(Context context) { SharedPreferences sp = context.getSharedPreferences(USER_SETTING, Context.MODE_PRIVATE); boolean isFirst = sp.getBoolean("first", true); //第一次则修改记录 if (isFirst) sp.edit().putBoolean("first", false).commit(); return isFirst; } }
false
870
9
1,014
8
1,124
10
1,014
8
1,302
14
false
false
false
false
false
true
52191_21
package server.utils; import io.jsonwebtoken.Claims; import io.jsonwebtoken.CompressionCodecs; import io.jsonwebtoken.Jwts; import io.jsonwebtoken.SignatureAlgorithm; import org.springframework.stereotype.Component; import server.bean.dto.UserDTO; import java.util.Date; import java.util.HashMap; import java.util.Map; /** * JwtTokenManager工具类 * @author : 其然乐衣Letitbe * @date : 2022/11/12 */ @Component public class JwtTokenManager { /** * 用于签名的私钥 */ private final String PRIVATE_KEY = "516Letitbe"; /** * 签发者 */ private final String ISSUER = "Letitbe"; /** * 过期时间 1 小时 */ private final long EXPIRATION_ONE_HOUR = 3600L; /** * 过期时间 1 月 */ private final long EXPIRATION_ONE_MONTH = 3600 * 24 * 30; /** * 生成Token * @param user token存储的 实体类 信息 * @param expireTime token的过期时间 * @return */ public String createToken(UserDTO user, long expireTime) { // 过期时间 if ( expireTime == 0 ) { // 如果是0,就设置默认 1天 的过期时间 expireTime = EXPIRATION_ONE_MONTH; } Map<String, Object> claims = new HashMap<>(); // 自定义有效载荷部分, 将User实体类用户名和密码存储 claims.put("userId", user.getUserId()); claims.put("username", user.getUsername()); claims.put("password", user.getPassword()); String token = Jwts.builder() // 发证人 .setIssuer(ISSUER) // 有效载荷 .setClaims(claims) // 设定签发时间 .setIssuedAt(new Date()) // 设置有效时长 .setExpiration(new Date(System.currentTimeMillis() + expireTime)) // 使用HS512算法签名,PRIVATE_KEY为签名密钥 .signWith(SignatureAlgorithm.HS512, PRIVATE_KEY) // compressWith() 压缩方法,当载荷过长时可对其进行压缩 // 可采用jjwt实现的两种压缩方法CompressionCodecs.GZIP和CompressionCodecs.DEFLATE .compressWith(CompressionCodecs.GZIP) // 生成JWT .compact(); return token; } public String createToken(UserDTO user) { // 设置默认 1 月个 的过期时间 long expireTime = EXPIRATION_ONE_MONTH; Map<String, Object> claims = new HashMap<>(); // 自定义有效载荷部分, 将User实体类用户名和密码存储 claims.put("userId", user.getUserId()); claims.put("username", user.getUsername()); claims.put("password", user.getPassword()); String token = Jwts.builder() // 发证人 .setIssuer(ISSUER) // 有效载荷 .setClaims(claims) // 设定签发时间 .setIssuedAt(new Date()) // 设置有效时长 .setExpiration(new Date(System.currentTimeMillis() + expireTime)) // 使用HS512算法签名,PRIVATE_KEY为签名密钥 .signWith(SignatureAlgorithm.HS512, PRIVATE_KEY) // compressWith() 压缩方法,当载荷过长时可对其进行压缩 // 可采用jjwt实现的两种压缩方法CompressionCodecs.GZIP和CompressionCodecs.DEFLATE .compressWith(CompressionCodecs.GZIP) // 生成JWT .compact(); return token; } /** * 获取token中的User实体类 * @param token * @return */ public UserDTO getUserFromToken(String token) { // 获取有效载荷 Claims claims = getClaimsFromToken(token); // 解析token后,从有效载荷取出值 String id = (String) claims.get("id"); String username = (String) claims.get("username"); String password = (String) claims.get("password"); // 封装成User实体类 UserDTO user = new UserDTO(); user.setUserId(Integer.valueOf(id)); user.setUsername( username ); user.setPassword( password ); return user; } /** * 获取有效载荷 * @param token * @return */ public Claims getClaimsFromToken(String token){ Claims claims = null; try { claims = Jwts.parser() //设定解密私钥 .setSigningKey(PRIVATE_KEY) //传入Token .parseClaimsJws(token) //获取载荷类 .getBody(); }catch (Exception e){ return null; } return claims; } }
RunningYu/Elven_Home
server/src/main/java/server/utils/JwtTokenManager.java
1,170
// 设定签发时间
line_comment
zh-cn
package server.utils; import io.jsonwebtoken.Claims; import io.jsonwebtoken.CompressionCodecs; import io.jsonwebtoken.Jwts; import io.jsonwebtoken.SignatureAlgorithm; import org.springframework.stereotype.Component; import server.bean.dto.UserDTO; import java.util.Date; import java.util.HashMap; import java.util.Map; /** * JwtTokenManager工具类 * @author : 其然乐衣Letitbe * @date : 2022/11/12 */ @Component public class JwtTokenManager { /** * 用于签名的私钥 */ private final String PRIVATE_KEY = "516Letitbe"; /** * 签发者 */ private final String ISSUER = "Letitbe"; /** * 过期时间 1 小时 */ private final long EXPIRATION_ONE_HOUR = 3600L; /** * 过期时间 1 月 */ private final long EXPIRATION_ONE_MONTH = 3600 * 24 * 30; /** * 生成Token * @param user token存储的 实体类 信息 * @param expireTime token的过期时间 * @return */ public String createToken(UserDTO user, long expireTime) { // 过期时间 if ( expireTime == 0 ) { // 如果是0,就设置默认 1天 的过期时间 expireTime = EXPIRATION_ONE_MONTH; } Map<String, Object> claims = new HashMap<>(); // 自定义有效载荷部分, 将User实体类用户名和密码存储 claims.put("userId", user.getUserId()); claims.put("username", user.getUsername()); claims.put("password", user.getPassword()); String token = Jwts.builder() // 发证人 .setIssuer(ISSUER) // 有效载荷 .setClaims(claims) // 设定签发时间 .setIssuedAt(new Date()) // 设置有效时长 .setExpiration(new Date(System.currentTimeMillis() + expireTime)) // 使用HS512算法签名,PRIVATE_KEY为签名密钥 .signWith(SignatureAlgorithm.HS512, PRIVATE_KEY) // compressWith() 压缩方法,当载荷过长时可对其进行压缩 // 可采用jjwt实现的两种压缩方法CompressionCodecs.GZIP和CompressionCodecs.DEFLATE .compressWith(CompressionCodecs.GZIP) // 生成JWT .compact(); return token; } public String createToken(UserDTO user) { // 设置默认 1 月个 的过期时间 long expireTime = EXPIRATION_ONE_MONTH; Map<String, Object> claims = new HashMap<>(); // 自定义有效载荷部分, 将User实体类用户名和密码存储 claims.put("userId", user.getUserId()); claims.put("username", user.getUsername()); claims.put("password", user.getPassword()); String token = Jwts.builder() // 发证人 .setIssuer(ISSUER) // 有效载荷 .setClaims(claims) // 设定 <SUF> .setIssuedAt(new Date()) // 设置有效时长 .setExpiration(new Date(System.currentTimeMillis() + expireTime)) // 使用HS512算法签名,PRIVATE_KEY为签名密钥 .signWith(SignatureAlgorithm.HS512, PRIVATE_KEY) // compressWith() 压缩方法,当载荷过长时可对其进行压缩 // 可采用jjwt实现的两种压缩方法CompressionCodecs.GZIP和CompressionCodecs.DEFLATE .compressWith(CompressionCodecs.GZIP) // 生成JWT .compact(); return token; } /** * 获取token中的User实体类 * @param token * @return */ public UserDTO getUserFromToken(String token) { // 获取有效载荷 Claims claims = getClaimsFromToken(token); // 解析token后,从有效载荷取出值 String id = (String) claims.get("id"); String username = (String) claims.get("username"); String password = (String) claims.get("password"); // 封装成User实体类 UserDTO user = new UserDTO(); user.setUserId(Integer.valueOf(id)); user.setUsername( username ); user.setPassword( password ); return user; } /** * 获取有效载荷 * @param token * @return */ public Claims getClaimsFromToken(String token){ Claims claims = null; try { claims = Jwts.parser() //设定解密私钥 .setSigningKey(PRIVATE_KEY) //传入Token .parseClaimsJws(token) //获取载荷类 .getBody(); }catch (Exception e){ return null; } return claims; } }
false
1,108
6
1,170
7
1,222
6
1,170
7
1,611
10
false
false
false
false
false
true
58587_1
package RcRPG.RPG; import RcRPG.Handle; import RcRPG.Main; import cn.nukkit.Player; import cn.nukkit.entity.Entity; import cn.nukkit.event.entity.EntityDamageEvent; import cn.nukkit.item.Item; import cn.nukkit.math.Vector3; import cn.nukkit.network.protocol.AddEntityPacket; import java.util.LinkedHashMap; import java.util.LinkedList; public class Damage { public static LinkedHashMap<Player, LinkedList<Item>> playerMap = new LinkedHashMap<>(); public static void getItem(Player player){ Item item = player.getInventory().getItemInHand(); LinkedList<Item> list = new LinkedList<>(); if(!item.isNull() && Weapon.isWeapon(item)){ list.add(item); } for(Item armour : player.getInventory().getArmorContents()){ if(Armour.isArmour(armour)) list.add(armour); } Damage.playerMap.put(player,list); } /** * 效果处理 * @param damager 攻击者 * @param entity 受害者 */ public static void onDamage(Player damager, Entity entity){ Item item = damager.getInventory().getItemInHand(); if (!item.isNull() && Weapon.isWeapon(item)) { Weapon weapon = Main.loadWeapon.get(item.getNamedTag().getString("name")); if(entity instanceof Player) {// 当受害者是玩家时 if (weapon.getFireRound() != 0) {// 火焰 if (Handle.random(1, 100) <= weapon.getFireRound()) { entity.setOnFire(weapon.getFire()); } } if (weapon.getLightRound() != 0) {// 雷击 if (Handle.random(1, 100) <= weapon.getLightRound()) { Damage.light(entity, weapon.getLighting()); } } } /** if(entity instanceof Player){// 当受害者是玩家时 if(!weapon.getDamagedEffect().isEmpty()){// 受害者药水效果 for(Effect effect : weapon.getDamagedEffect()){ effect.add(entity); } } } if(weapon.getGroupRound() != 0){// 群体回血 if(Handle.random(1,100) <= weapon.getGroupRound()){ for(Player player:Damage.getPlayerAround(damager,5,true)){ if((player.getMaxHealth() - player.getHealth()) < weapon.getGroup()){ player.setHealth(player.getMaxHealth()); }else{ player.setHealth(player.getHealth()+weapon.getGroup()); } } } } if(!weapon.getDamagerEffect().isEmpty()){// 攻击者药水效果 for(Effect effect : weapon.getDamagerEffect()){ effect.add(damager); } } if(!weapon.getGroupEffect().isEmpty()){ // 群体药水效果 for(Player player:Damage.getPlayerAround(damager,5,true)){ for(Effect effect :weapon.getGroupEffect()){ effect.add(player); } } }*/ } } /** * 闪电技能 * @param entity * @param damage */ public static void light(Entity entity, double damage){ AddEntityPacket pk = new AddEntityPacket(); pk.type = 93; pk.x = (float) entity.x; pk.y = (float) entity.y; pk.z = (float) entity.z; for(Player player : entity.level.getPlayers().values()){ player.dataPacket(pk); } EntityDamageEvent ev = new EntityDamageEvent(entity, EntityDamageEvent.DamageCause.LIGHTNING, (float) damage); entity.attack(ev); } public static LinkedList<Player> getPlayerAround(Entity entity,double dis,boolean flag){ LinkedList<Player> list = new LinkedList<>(); for(Player player : entity.level.getPlayers().values()){ if(entity.distance(player) <= dis) list.add(player); } if(flag) list.add((Player) entity); return list; } /** * 用于计算浮空字跳跃的向量 * @param yaw * @param pitch * @param go * @return */ public static Vector3 go(double yaw,double pitch,int go) { yaw = yaw % 360; double x = 0.0; double z = 0.0; if (0.0 <= yaw && yaw <= 90.0) { //第二象限 x = -go * (yaw / 90.0); z = go * ((90.0 - yaw) / 90.0); } else if (90.0 < yaw && yaw <= 180.0) { //第三象限 yaw = yaw % 90.0; x = -go * ((90.0 - yaw) / 90.0); z = -go * (yaw / 90.0); } else if (180.0 < yaw && yaw <= 270.0) { //第四象限 yaw = yaw % 90.0; x = go * (yaw / 90.0); z = -go * ((90.0 - yaw) / 90.0); } else if (270.0 < yaw && yaw <= 360.0) { //第一象限 yaw = yaw % 90.0; x = go * ((90.0 - yaw) / 90.0); z = go * (yaw / 90.0); } double y = 0.0; if (pitch < 0.0) { //向上 pitch = -1.0 * pitch; y = go * (pitch / 90.0); } if (pitch > 0.0) { //向下 pitch = -1.0 * pitch; y = go * (pitch / 90.0); } return new Vector3(x, y, z); } }
RuoChen688/RcRPG-PNX
src/main/java/RcRPG/RPG/Damage.java
1,475
// 当受害者是玩家时
line_comment
zh-cn
package RcRPG.RPG; import RcRPG.Handle; import RcRPG.Main; import cn.nukkit.Player; import cn.nukkit.entity.Entity; import cn.nukkit.event.entity.EntityDamageEvent; import cn.nukkit.item.Item; import cn.nukkit.math.Vector3; import cn.nukkit.network.protocol.AddEntityPacket; import java.util.LinkedHashMap; import java.util.LinkedList; public class Damage { public static LinkedHashMap<Player, LinkedList<Item>> playerMap = new LinkedHashMap<>(); public static void getItem(Player player){ Item item = player.getInventory().getItemInHand(); LinkedList<Item> list = new LinkedList<>(); if(!item.isNull() && Weapon.isWeapon(item)){ list.add(item); } for(Item armour : player.getInventory().getArmorContents()){ if(Armour.isArmour(armour)) list.add(armour); } Damage.playerMap.put(player,list); } /** * 效果处理 * @param damager 攻击者 * @param entity 受害者 */ public static void onDamage(Player damager, Entity entity){ Item item = damager.getInventory().getItemInHand(); if (!item.isNull() && Weapon.isWeapon(item)) { Weapon weapon = Main.loadWeapon.get(item.getNamedTag().getString("name")); if(entity instanceof Player) {// 当受 <SUF> if (weapon.getFireRound() != 0) {// 火焰 if (Handle.random(1, 100) <= weapon.getFireRound()) { entity.setOnFire(weapon.getFire()); } } if (weapon.getLightRound() != 0) {// 雷击 if (Handle.random(1, 100) <= weapon.getLightRound()) { Damage.light(entity, weapon.getLighting()); } } } /** if(entity instanceof Player){// 当受害者是玩家时 if(!weapon.getDamagedEffect().isEmpty()){// 受害者药水效果 for(Effect effect : weapon.getDamagedEffect()){ effect.add(entity); } } } if(weapon.getGroupRound() != 0){// 群体回血 if(Handle.random(1,100) <= weapon.getGroupRound()){ for(Player player:Damage.getPlayerAround(damager,5,true)){ if((player.getMaxHealth() - player.getHealth()) < weapon.getGroup()){ player.setHealth(player.getMaxHealth()); }else{ player.setHealth(player.getHealth()+weapon.getGroup()); } } } } if(!weapon.getDamagerEffect().isEmpty()){// 攻击者药水效果 for(Effect effect : weapon.getDamagerEffect()){ effect.add(damager); } } if(!weapon.getGroupEffect().isEmpty()){ // 群体药水效果 for(Player player:Damage.getPlayerAround(damager,5,true)){ for(Effect effect :weapon.getGroupEffect()){ effect.add(player); } } }*/ } } /** * 闪电技能 * @param entity * @param damage */ public static void light(Entity entity, double damage){ AddEntityPacket pk = new AddEntityPacket(); pk.type = 93; pk.x = (float) entity.x; pk.y = (float) entity.y; pk.z = (float) entity.z; for(Player player : entity.level.getPlayers().values()){ player.dataPacket(pk); } EntityDamageEvent ev = new EntityDamageEvent(entity, EntityDamageEvent.DamageCause.LIGHTNING, (float) damage); entity.attack(ev); } public static LinkedList<Player> getPlayerAround(Entity entity,double dis,boolean flag){ LinkedList<Player> list = new LinkedList<>(); for(Player player : entity.level.getPlayers().values()){ if(entity.distance(player) <= dis) list.add(player); } if(flag) list.add((Player) entity); return list; } /** * 用于计算浮空字跳跃的向量 * @param yaw * @param pitch * @param go * @return */ public static Vector3 go(double yaw,double pitch,int go) { yaw = yaw % 360; double x = 0.0; double z = 0.0; if (0.0 <= yaw && yaw <= 90.0) { //第二象限 x = -go * (yaw / 90.0); z = go * ((90.0 - yaw) / 90.0); } else if (90.0 < yaw && yaw <= 180.0) { //第三象限 yaw = yaw % 90.0; x = -go * ((90.0 - yaw) / 90.0); z = -go * (yaw / 90.0); } else if (180.0 < yaw && yaw <= 270.0) { //第四象限 yaw = yaw % 90.0; x = go * (yaw / 90.0); z = -go * ((90.0 - yaw) / 90.0); } else if (270.0 < yaw && yaw <= 360.0) { //第一象限 yaw = yaw % 90.0; x = go * ((90.0 - yaw) / 90.0); z = go * (yaw / 90.0); } double y = 0.0; if (pitch < 0.0) { //向上 pitch = -1.0 * pitch; y = go * (pitch / 90.0); } if (pitch > 0.0) { //向下 pitch = -1.0 * pitch; y = go * (pitch / 90.0); } return new Vector3(x, y, z); } }
false
1,326
6
1,475
9
1,545
7
1,475
9
1,846
16
false
false
false
false
false
true
46479_4
package cc.ruok.ja_cqhttp.cq; public enum Face { AMAZED(0), //惊讶 POUT(2), //撇嘴 SEX(3), //色 BLANKLY(4), //发呆 PROUD(5), //得意 SHY(6), //害羞 SHUT_UP(7), //闭嘴 SLEEP(8), //睡 CRY(9), //大哭 AWKWARD(10), //尴尬 ANGER(11), //发怒 NAUGHTY(12), //调皮 TEETH(13), //龇牙 SMILE(14), //微笑 HARD(15), //难过 COOL(16), //酷 CRAZY(18), //抓狂 VOMIT(19), //吐 TITTER(20), //偷笑 LOVELY(21), //可爱 EYES(22), //白眼 ARROGANT(23), //傲慢 HUNGER(24), //饥饿 SLEEPY(25), //困 TERRIFIED(26), //惊恐 SWEAT(27), //流汗 SIMPER(28), //憨笑 CAREFREE(29), //悠闲 STRUGGLE(30), //奋斗 CURSE(31), //咒骂 QUERY(32), //疑问 SH(33), //嘘 SWOON(34), //晕 SUFFERING(35), //折磨 LOST(36), //衰 SKELETON(37), //骷髅 BEAT(38), //敲打 BYE(39), //再见 SHIVER(41), //发抖 LOVE(42), //爱情 JUMP(43), //跳跳 PIG(46), //猪头 HUG(49), //拥抱 CAKE(53), //蛋糕 LIGHTNING(54), //闪电 BOMB(55), //炸弹 KNIFE(56), //刀 FOOTBALL(57), //足球 SHIT(59), //便便 COFFEE(60), //咖啡 RICE(61), //米饭 MEDICINE(62), //药 FLOWER(63), //玫瑰 FADE(64), //凋谢 HEART(66), //爱心 BROKEN_HEART(67), //心碎 GIFT(69), //礼物 MAIL(72), //信 SUN(74), //太阳 MOON(75), //月亮 GOOD(76), //赞 STEP(77), //踩 HANDSHAKE(78), //握手 YEAH(79), //胜利 AIR_KISS(85), //飞吻 ANNOYED(86), //怄火 WATERMELON(89), //西瓜 RAIN(90), //雨 CLOUD(91), //云 COLD_SWEAT(96), //冷汗 WIPE(97), //擦汗 NOSE_PICKING(98), //抠鼻 APPLAUD(99), //鼓掌 EMBARRASS(100), //出糗 GRIN(101), //坏笑 LEFT_HUM(102), //左哼哼 RIGHT_HUM(103), //右哼哼 YAWN(104), //哈欠 DESPISE(105), //鄙视 WRONGED(106), //委屈 WILL_CRY(107), //快哭了 CRAFTY(108), //阴险 LEFT_KISS(109), //左亲亲 FRIGHTEN(110), //吓 POOR(111), //可怜 COOK_COPPER(112), //菜刀 BEER(113), //啤酒 BASKETBALL(114),//篮球 PING_PONG(115), //乒乓球 SHOW_LOVE(116), //示爱 LADYBUG(117), //瓢虫 SALUTING(118), //抱拳 LURE(119), //勾引 FIST(120), //拳头 WORST(121), //差劲 LOVE_YOU(122), //爱你 NO(123), //NO OK(124), //OK ROTATE(125), //转圈 KOWTOW(126), //磕头 LATER(127), //回头 SKIPPING(128), //跳绳 WAVE(129), //挥手 EXCITE(130), //激动 DANCE(131), //街舞 OFFER_KISS(132),//献吻 LEFT_TAICHI(133), //左太极 RIGHT_TAICHI(134), //右太极 HAPPINESS(136), //双喜 MAROON(137), //鞭炮 LANTERN(138), //灯笼 WEALTH(139), //发财 KARAOKE(140), //K歌 SHOPPING(141), //购物 _MAIL(142), //邮件 CHESS_KING(143),//帅 CHEER(144), //喝彩 CANDLE(145), //蜡烛 TENDON(146), //爆筋 LOLLIPOP(147), //棒棒糖 FEEDER(148), //奶瓶 NOODLES(149), //面条 BANANA(150), //香蕉 PLANE(151), //飞机 CAR(152), //汽车 LEFT_LOCOMOTIVE(153), //左车头 TRAIN_CAR(154), //车厢 RIGHT_LOCOMOTIVE(154), //右车头 _RAIN(156), //雨 _CLOUD(157), //云 MONEY(158), //钞票 PANDA(159), //熊猫 LIGHT(160), //灯泡 PINWHEEL(161), //风车 ALARM_CLOCK(162), //闹钟 UMBRELLA(163), //伞 BALLOON(164), //气球 RING(165), //戒指 SOFA(166), //沙发 PAPER(167), //卫生纸 _MEDICINE(168), //药 GUN(169), //手枪 FROG(170), //青蛙 TEA(171), //茶 BLINK(172), //眨眼 TEARS(173), //泪奔 WHOEVER(174), //无奈 ACT_CUTE(175), //卖萌 ENTANGLED_WITH(176), //纠结 BLOOD(177), //喷血 FUNNY(178), //斜眼笑 HUAJI(178), //斜眼笑 DOGE_YELLOW(179), //DOGE SURPRISED(180), //惊喜 HARASS(181), //骚扰 TEARS_OF_JOY(182), //笑哭 STINKY_BEAUTY(183), //我最美 ; private int id; Face(int id) { this.id = id; } public static String get(int id) { return "[CQ:face,id=" + id + "]"; } @Override public String toString() { return "[CQ:face,id=" + id + "]"; } }
Ruokwok/ja-cqhttp
src/main/java/cc/ruok/ja_cqhttp/cq/Face.java
2,200
//乒乓球
line_comment
zh-cn
package cc.ruok.ja_cqhttp.cq; public enum Face { AMAZED(0), //惊讶 POUT(2), //撇嘴 SEX(3), //色 BLANKLY(4), //发呆 PROUD(5), //得意 SHY(6), //害羞 SHUT_UP(7), //闭嘴 SLEEP(8), //睡 CRY(9), //大哭 AWKWARD(10), //尴尬 ANGER(11), //发怒 NAUGHTY(12), //调皮 TEETH(13), //龇牙 SMILE(14), //微笑 HARD(15), //难过 COOL(16), //酷 CRAZY(18), //抓狂 VOMIT(19), //吐 TITTER(20), //偷笑 LOVELY(21), //可爱 EYES(22), //白眼 ARROGANT(23), //傲慢 HUNGER(24), //饥饿 SLEEPY(25), //困 TERRIFIED(26), //惊恐 SWEAT(27), //流汗 SIMPER(28), //憨笑 CAREFREE(29), //悠闲 STRUGGLE(30), //奋斗 CURSE(31), //咒骂 QUERY(32), //疑问 SH(33), //嘘 SWOON(34), //晕 SUFFERING(35), //折磨 LOST(36), //衰 SKELETON(37), //骷髅 BEAT(38), //敲打 BYE(39), //再见 SHIVER(41), //发抖 LOVE(42), //爱情 JUMP(43), //跳跳 PIG(46), //猪头 HUG(49), //拥抱 CAKE(53), //蛋糕 LIGHTNING(54), //闪电 BOMB(55), //炸弹 KNIFE(56), //刀 FOOTBALL(57), //足球 SHIT(59), //便便 COFFEE(60), //咖啡 RICE(61), //米饭 MEDICINE(62), //药 FLOWER(63), //玫瑰 FADE(64), //凋谢 HEART(66), //爱心 BROKEN_HEART(67), //心碎 GIFT(69), //礼物 MAIL(72), //信 SUN(74), //太阳 MOON(75), //月亮 GOOD(76), //赞 STEP(77), //踩 HANDSHAKE(78), //握手 YEAH(79), //胜利 AIR_KISS(85), //飞吻 ANNOYED(86), //怄火 WATERMELON(89), //西瓜 RAIN(90), //雨 CLOUD(91), //云 COLD_SWEAT(96), //冷汗 WIPE(97), //擦汗 NOSE_PICKING(98), //抠鼻 APPLAUD(99), //鼓掌 EMBARRASS(100), //出糗 GRIN(101), //坏笑 LEFT_HUM(102), //左哼哼 RIGHT_HUM(103), //右哼哼 YAWN(104), //哈欠 DESPISE(105), //鄙视 WRONGED(106), //委屈 WILL_CRY(107), //快哭了 CRAFTY(108), //阴险 LEFT_KISS(109), //左亲亲 FRIGHTEN(110), //吓 POOR(111), //可怜 COOK_COPPER(112), //菜刀 BEER(113), //啤酒 BASKETBALL(114),//篮球 PING_PONG(115), //乒乓 <SUF> SHOW_LOVE(116), //示爱 LADYBUG(117), //瓢虫 SALUTING(118), //抱拳 LURE(119), //勾引 FIST(120), //拳头 WORST(121), //差劲 LOVE_YOU(122), //爱你 NO(123), //NO OK(124), //OK ROTATE(125), //转圈 KOWTOW(126), //磕头 LATER(127), //回头 SKIPPING(128), //跳绳 WAVE(129), //挥手 EXCITE(130), //激动 DANCE(131), //街舞 OFFER_KISS(132),//献吻 LEFT_TAICHI(133), //左太极 RIGHT_TAICHI(134), //右太极 HAPPINESS(136), //双喜 MAROON(137), //鞭炮 LANTERN(138), //灯笼 WEALTH(139), //发财 KARAOKE(140), //K歌 SHOPPING(141), //购物 _MAIL(142), //邮件 CHESS_KING(143),//帅 CHEER(144), //喝彩 CANDLE(145), //蜡烛 TENDON(146), //爆筋 LOLLIPOP(147), //棒棒糖 FEEDER(148), //奶瓶 NOODLES(149), //面条 BANANA(150), //香蕉 PLANE(151), //飞机 CAR(152), //汽车 LEFT_LOCOMOTIVE(153), //左车头 TRAIN_CAR(154), //车厢 RIGHT_LOCOMOTIVE(154), //右车头 _RAIN(156), //雨 _CLOUD(157), //云 MONEY(158), //钞票 PANDA(159), //熊猫 LIGHT(160), //灯泡 PINWHEEL(161), //风车 ALARM_CLOCK(162), //闹钟 UMBRELLA(163), //伞 BALLOON(164), //气球 RING(165), //戒指 SOFA(166), //沙发 PAPER(167), //卫生纸 _MEDICINE(168), //药 GUN(169), //手枪 FROG(170), //青蛙 TEA(171), //茶 BLINK(172), //眨眼 TEARS(173), //泪奔 WHOEVER(174), //无奈 ACT_CUTE(175), //卖萌 ENTANGLED_WITH(176), //纠结 BLOOD(177), //喷血 FUNNY(178), //斜眼笑 HUAJI(178), //斜眼笑 DOGE_YELLOW(179), //DOGE SURPRISED(180), //惊喜 HARASS(181), //骚扰 TEARS_OF_JOY(182), //笑哭 STINKY_BEAUTY(183), //我最美 ; private int id; Face(int id) { this.id = id; } public static String get(int id) { return "[CQ:face,id=" + id + "]"; } @Override public String toString() { return "[CQ:face,id=" + id + "]"; } }
false
2,050
2
2,200
6
2,040
4
2,200
6
2,720
8
false
false
false
false
false
true
58563_3
/** * Copyright 2018 人人开源 http://www.renren.io * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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 io.renren.common.utils; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import io.renren.common.xss.SQLFilter; import org.apache.commons.lang.StringUtils; import java.util.LinkedHashMap; import java.util.Map; /** * 查询参数 * * @author Mark [email protected] * @since 2.0.0 2017-03-14 */ public class Query<T> extends LinkedHashMap<String, Object> { private static final long serialVersionUID = 1L; /** * mybatis-plus分页参数 */ private Page<T> page; /** * 当前页码 */ private int currPage = 1; /** * 每页条数 */ private int limit = 10; public Query(Map<String, Object> params){ this.putAll(params); //分页参数 if(params.get("page") != null){ currPage = Integer.parseInt((String)params.get("page")); } if(params.get("limit") != null){ limit = Integer.parseInt((String)params.get("limit")); } this.put("offset", (currPage - 1) * limit); this.put("page", currPage); this.put("limit", limit); //防止SQL注入(因为sidx、order是通过拼接SQL实现排序的,会有SQL注入风险) String sidx = SQLFilter.sqlInject((String)params.get("sidx")); String order = SQLFilter.sqlInject((String)params.get("order")); this.put("sidx", sidx); this.put("order", order); //mybatis-plus分页 this.page = new Page<>(currPage, limit); //排序 if(StringUtils.isNotBlank(sidx) && StringUtils.isNotBlank(order)){ //this.page.setOrderByField(sidx); //this.page.setAsc("ASC".equalsIgnoreCase(order)); this.page.setAsc(sidx); } } public Page<T> getPage() { return page; } public int getCurrPage() { return currPage; } public int getLimit() { return limit; } }
Ryan--Yang/CBoard-boot
src/main/java/io/renren/common/utils/Query.java
702
/** * 当前页码 */
block_comment
zh-cn
/** * Copyright 2018 人人开源 http://www.renren.io * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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 io.renren.common.utils; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import io.renren.common.xss.SQLFilter; import org.apache.commons.lang.StringUtils; import java.util.LinkedHashMap; import java.util.Map; /** * 查询参数 * * @author Mark [email protected] * @since 2.0.0 2017-03-14 */ public class Query<T> extends LinkedHashMap<String, Object> { private static final long serialVersionUID = 1L; /** * mybatis-plus分页参数 */ private Page<T> page; /** * 当前页 <SUF>*/ private int currPage = 1; /** * 每页条数 */ private int limit = 10; public Query(Map<String, Object> params){ this.putAll(params); //分页参数 if(params.get("page") != null){ currPage = Integer.parseInt((String)params.get("page")); } if(params.get("limit") != null){ limit = Integer.parseInt((String)params.get("limit")); } this.put("offset", (currPage - 1) * limit); this.put("page", currPage); this.put("limit", limit); //防止SQL注入(因为sidx、order是通过拼接SQL实现排序的,会有SQL注入风险) String sidx = SQLFilter.sqlInject((String)params.get("sidx")); String order = SQLFilter.sqlInject((String)params.get("order")); this.put("sidx", sidx); this.put("order", order); //mybatis-plus分页 this.page = new Page<>(currPage, limit); //排序 if(StringUtils.isNotBlank(sidx) && StringUtils.isNotBlank(order)){ //this.page.setOrderByField(sidx); //this.page.setAsc("ASC".equalsIgnoreCase(order)); this.page.setAsc(sidx); } } public Page<T> getPage() { return page; } public int getCurrPage() { return currPage; } public int getLimit() { return limit; } }
false
615
10
702
8
733
10
702
8
843
12
false
false
false
false
false
true
23207_15
package game.main; import java.sql.*; import net.sf.json.*; public class CraftHandler { protected static CraftHandler instance; protected static Connection conn; public CraftHandler() throws Exception { conn=DatabaseConnectionManager.getConnection("合成处理机",true); instance=this; } // 获取可以合成的列表 public static JSONObject getCanCraftList(String usernameIn) { JSONObject json=new JSONObject(); int amount=0; try { Statement stmt=conn.createStatement(); stmt.executeQuery("select * from data_crafting"); ResultSet rs=stmt.getResultSet(); while(rs.next()) { json.accumulate("id_crafting", rs.getInt("id_crafting")); json.accumulate("lv_need", rs.getInt("lv_need")); json.accumulate("product_id_item", rs.getInt("product_id_item")); json.accumulate("product_amount", rs.getInt("product_amount")); json.accumulate("des", rs.getString("des")); amount++; } } catch(Exception e) { e.printStackTrace(); } json.put("amounts", amount); return json; } // 获取某一个的原材料 public static JSONObject getCraftingRaw(String id_craftingIn) { try { return getCraftingRaw(Integer.valueOf(id_craftingIn)); } catch(Exception e) { e.printStackTrace(); return new JSONObject(); } } public static JSONObject getCraftingRaw(int id_craftingIn) { JSONObject json=new JSONObject(); try { Statement stmt=conn.createStatement(); stmt.executeQuery("select * from data_crafting where id_crafting="+id_craftingIn); ResultSet rs=stmt.getResultSet(); rs.next(); // 获取详细信息 json.put("class_need", rs.getString("class_need")); json.put("lv_need", rs.getInt("lv_need")); json.put("class_sub_need", rs.getString("class_sub_need")); json.put("lv_sub_need", rs.getInt("lv_sub_need")); json.put("gold_need", rs.getInt("gold_need")); json.put("exp_need", rs.getInt("exp_need")); // 获取物品材料 stmt.executeQuery("select * from data_crafting_raw where id_crafting="+id_craftingIn); rs=stmt.getResultSet(); int amount=0; while(rs.next()) { json.accumulate("raw_id_item", rs.getInt("raw_id_item")); json.accumulate("raw_amount", rs.getInt("raw_amount")); amount++; } json.put("amounts", amount); } catch(Exception e) { e.printStackTrace(); } return json; } // 判断某一个能不能合成 public static boolean canCraft(String usernameIn,String id_craftingIn) { try { return canCraft(usernameIn,Integer.parseInt(id_craftingIn)); } catch(Exception e) { e.printStackTrace(); return false; } } public static boolean canCraft(String usernameIn,int id_craftingIn) { try { // 拿到原材料列表 JSONObject raws=getCraftingRaw(id_craftingIn); System.out.println(raws); String class_need,class_sub_need; int lv_need,lv_sub_need; int gold_need,exp_need; class_need=raws.getString("class_need"); class_sub_need=raws.getString("class_sub_need"); lv_need=raws.getInt("lv_need"); lv_sub_need=raws.getInt("lv_sub_need"); gold_need=raws.getInt("gold_need"); exp_need=raws.getInt("exp_need"); // 拿到 // 判断每一种原材料是否足够 int size=raws.getInt("amounts"); if(size==1) { if(DBAPI.Inventory_Amount(usernameIn, raws.getInt("raw_id_item"), -1) >= raws.getInt("raw_amount")) return true; // 材料足够 判断下一个 else return false; // 材料不够 返回否 } else { for(int step=0;step<size;step++) { if(DBAPI.Inventory_Amount(usernameIn, raws.getJSONArray("raw_id_item").getInt(step), -1) >= raws.getJSONArray("raw_amount").getInt(step)) continue; // 材料足够 判断下一个 else return false; // 材料不够 返回否 } } return true; } catch(Exception e) { e.printStackTrace(); } return false; } // 合成 // 这个方法用来从玩家物品栏中移除对应原材料 public static void executeCrafting(String usernameIn,String id_craftingIn) { try { executeCrafting(usernameIn,Integer.valueOf(id_craftingIn)); } catch(Exception e) { e.printStackTrace(); } } public static void executeCrafting(String usernameIn,int id_craftingIn) { if(!canCraft(usernameIn,id_craftingIn)) // 如果不能合成 直接继续 return; try { JSONObject raws=getCraftingRaw(id_craftingIn); // 先不管物品素材之外的东西 // 以后再加 int size=raws.getInt("amounts"); if(size==1) { DBAPI.Inventory_Edit(usernameIn, raws.getInt("raw_id_item"), -1, - raws.getInt("raw_amount")); } else { for(int step=0;step<size;step++) { // 挨个移除物品 DBAPI.Inventory_Edit(usernameIn, raws.getJSONArray("raw_id_item").getInt(step), -1, - raws.getJSONArray("raw_amount").getInt(step)); } } // 现在开始给予玩家合成产物 Statement stmt=conn.createStatement(); stmt.executeQuery("select * from data_crafting where id_crafting="+id_craftingIn); ResultSet rs=stmt.getResultSet(); if(rs.next()) { DBAPI.Inventory_Edit(usernameIn, rs.getInt("product_id_item"), -1, rs.getInt("product_amount")); } } catch(Exception e) { e.printStackTrace(); } } /* * <<笔记>> * 把合成表相关的数据库弄成两个 * 一个记录需要的等级 金币之类的数据 * 一个记录所有的原材料 * * data_crafting_raws * data_crafting * */ }
S2Lab/SMO
src/game/main/CraftHandler.java
1,843
// 挨个移除物品
line_comment
zh-cn
package game.main; import java.sql.*; import net.sf.json.*; public class CraftHandler { protected static CraftHandler instance; protected static Connection conn; public CraftHandler() throws Exception { conn=DatabaseConnectionManager.getConnection("合成处理机",true); instance=this; } // 获取可以合成的列表 public static JSONObject getCanCraftList(String usernameIn) { JSONObject json=new JSONObject(); int amount=0; try { Statement stmt=conn.createStatement(); stmt.executeQuery("select * from data_crafting"); ResultSet rs=stmt.getResultSet(); while(rs.next()) { json.accumulate("id_crafting", rs.getInt("id_crafting")); json.accumulate("lv_need", rs.getInt("lv_need")); json.accumulate("product_id_item", rs.getInt("product_id_item")); json.accumulate("product_amount", rs.getInt("product_amount")); json.accumulate("des", rs.getString("des")); amount++; } } catch(Exception e) { e.printStackTrace(); } json.put("amounts", amount); return json; } // 获取某一个的原材料 public static JSONObject getCraftingRaw(String id_craftingIn) { try { return getCraftingRaw(Integer.valueOf(id_craftingIn)); } catch(Exception e) { e.printStackTrace(); return new JSONObject(); } } public static JSONObject getCraftingRaw(int id_craftingIn) { JSONObject json=new JSONObject(); try { Statement stmt=conn.createStatement(); stmt.executeQuery("select * from data_crafting where id_crafting="+id_craftingIn); ResultSet rs=stmt.getResultSet(); rs.next(); // 获取详细信息 json.put("class_need", rs.getString("class_need")); json.put("lv_need", rs.getInt("lv_need")); json.put("class_sub_need", rs.getString("class_sub_need")); json.put("lv_sub_need", rs.getInt("lv_sub_need")); json.put("gold_need", rs.getInt("gold_need")); json.put("exp_need", rs.getInt("exp_need")); // 获取物品材料 stmt.executeQuery("select * from data_crafting_raw where id_crafting="+id_craftingIn); rs=stmt.getResultSet(); int amount=0; while(rs.next()) { json.accumulate("raw_id_item", rs.getInt("raw_id_item")); json.accumulate("raw_amount", rs.getInt("raw_amount")); amount++; } json.put("amounts", amount); } catch(Exception e) { e.printStackTrace(); } return json; } // 判断某一个能不能合成 public static boolean canCraft(String usernameIn,String id_craftingIn) { try { return canCraft(usernameIn,Integer.parseInt(id_craftingIn)); } catch(Exception e) { e.printStackTrace(); return false; } } public static boolean canCraft(String usernameIn,int id_craftingIn) { try { // 拿到原材料列表 JSONObject raws=getCraftingRaw(id_craftingIn); System.out.println(raws); String class_need,class_sub_need; int lv_need,lv_sub_need; int gold_need,exp_need; class_need=raws.getString("class_need"); class_sub_need=raws.getString("class_sub_need"); lv_need=raws.getInt("lv_need"); lv_sub_need=raws.getInt("lv_sub_need"); gold_need=raws.getInt("gold_need"); exp_need=raws.getInt("exp_need"); // 拿到 // 判断每一种原材料是否足够 int size=raws.getInt("amounts"); if(size==1) { if(DBAPI.Inventory_Amount(usernameIn, raws.getInt("raw_id_item"), -1) >= raws.getInt("raw_amount")) return true; // 材料足够 判断下一个 else return false; // 材料不够 返回否 } else { for(int step=0;step<size;step++) { if(DBAPI.Inventory_Amount(usernameIn, raws.getJSONArray("raw_id_item").getInt(step), -1) >= raws.getJSONArray("raw_amount").getInt(step)) continue; // 材料足够 判断下一个 else return false; // 材料不够 返回否 } } return true; } catch(Exception e) { e.printStackTrace(); } return false; } // 合成 // 这个方法用来从玩家物品栏中移除对应原材料 public static void executeCrafting(String usernameIn,String id_craftingIn) { try { executeCrafting(usernameIn,Integer.valueOf(id_craftingIn)); } catch(Exception e) { e.printStackTrace(); } } public static void executeCrafting(String usernameIn,int id_craftingIn) { if(!canCraft(usernameIn,id_craftingIn)) // 如果不能合成 直接继续 return; try { JSONObject raws=getCraftingRaw(id_craftingIn); // 先不管物品素材之外的东西 // 以后再加 int size=raws.getInt("amounts"); if(size==1) { DBAPI.Inventory_Edit(usernameIn, raws.getInt("raw_id_item"), -1, - raws.getInt("raw_amount")); } else { for(int step=0;step<size;step++) { // 挨个 <SUF> DBAPI.Inventory_Edit(usernameIn, raws.getJSONArray("raw_id_item").getInt(step), -1, - raws.getJSONArray("raw_amount").getInt(step)); } } // 现在开始给予玩家合成产物 Statement stmt=conn.createStatement(); stmt.executeQuery("select * from data_crafting where id_crafting="+id_craftingIn); ResultSet rs=stmt.getResultSet(); if(rs.next()) { DBAPI.Inventory_Edit(usernameIn, rs.getInt("product_id_item"), -1, rs.getInt("product_amount")); } } catch(Exception e) { e.printStackTrace(); } } /* * <<笔记>> * 把合成表相关的数据库弄成两个 * 一个记录需要的等级 金币之类的数据 * 一个记录所有的原材料 * * data_crafting_raws * data_crafting * */ }
false
1,504
7
1,843
8
1,783
6
1,843
8
2,442
10
false
false
false
false
false
true
6685_3
package com.crossoverjie.actual; /** * Function: * * @author crossoverJie * Date: 2018/10/13 20:00 * @since JDK 1.8 */ import org.junit.Assert; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; /** * Function: * 一个“.”代表一个任意字母。 注意事项:可以假设所有的单词只包含小写字母“a-z” 样例: addWord(“bad”); addWord(“dad”); addWord(“mad”); search(“pad”); // return false; search(“bad”); // return true; search(“.ad”); // return true; search(“b..”); // return true; 如果有并发的情况下,addword() 怎么处理? * * @author crossoverJie * @since JDK 1.8 */ public class Search { private static Map<String,String> ALL_MAP = new ConcurrentHashMap<>(50000) ; /** * 换成 ascii码 更省事 */ private static final char[] dictionary = {'a','b','c','d','m','p'} ; public static void main(String[] args) throws InterruptedException { Thread t1 = new Thread(new Runnable() { @Override public void run() { for (int i = 0; i < 10000; i++) { addWord(i + "ad"); } } }); Thread t2 = new Thread(new Runnable() { @Override public void run() { for (int i = 0; i < 10000; i++) { addWord(i + "bd"); } } }); Thread t3 = new Thread(new Runnable() { @Override public void run() { for (int i = 0; i < 10000; i++) { addWord(i + "cd"); } } }); Thread t4 = new Thread(new Runnable() { @Override public void run() { for (int i = 0; i < 10000; i++) { addWord(i + "dd"); } } }); Thread t5 = new Thread(new Runnable() { @Override public void run() { for (int i = 0; i < 10000; i++) { addWord(i + "ed"); } } }); t1.start(); t2.start(); t3.start(); t4.start(); t5.start(); t1.join(); t2.join(); t3.join(); t4.join(); t5.join(); System.out.println(ALL_MAP.size()); Assert.assertEquals(50000,ALL_MAP.size()); addWord("bad"); addWord("dad"); addWord("mad"); boolean pad = search("pad"); System.out.println(pad); Assert.assertFalse(pad); boolean bad = search("bad"); System.out.println(bad); Assert.assertTrue(bad); boolean ad = search(".ad"); System.out.println(ad); Assert.assertTrue(ad); boolean bsearch = search("b.."); System.out.println(bsearch); Assert.assertTrue(bsearch); boolean asearch = search(".a."); System.out.println(asearch); boolean search = search(".af"); System.out.println(search); boolean search1 = search(null); System.out.println(search1); } public static boolean search(String keyWord){ boolean result = false ; if (null == keyWord || keyWord.trim().equals("")){ return result ; } //做一次完整匹配 String whole = ALL_MAP.get(keyWord) ; if (whole != null){ return true ; } char[] wordChars = keyWord.toCharArray() ; for (int i = 0; i < wordChars.length; i++) { char wordChar = wordChars[i] ; if (46 != (int)wordChar){ continue ; } for (char dic : dictionary) { wordChars[i] = dic ; boolean search = search(String.valueOf(wordChars)); if (search){ return search ; } String value = ALL_MAP.get(String.valueOf(wordChars)); if (value != null){ return true ; } } } return result ; } public static void addWord(String word){ ALL_MAP.put(word,word) ; } }
SASTREPO/monorepojava
JCSprout-master/src/main/java/com/crossoverjie/actual/Search.java
1,112
//做一次完整匹配
line_comment
zh-cn
package com.crossoverjie.actual; /** * Function: * * @author crossoverJie * Date: 2018/10/13 20:00 * @since JDK 1.8 */ import org.junit.Assert; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; /** * Function: * 一个“.”代表一个任意字母。 注意事项:可以假设所有的单词只包含小写字母“a-z” 样例: addWord(“bad”); addWord(“dad”); addWord(“mad”); search(“pad”); // return false; search(“bad”); // return true; search(“.ad”); // return true; search(“b..”); // return true; 如果有并发的情况下,addword() 怎么处理? * * @author crossoverJie * @since JDK 1.8 */ public class Search { private static Map<String,String> ALL_MAP = new ConcurrentHashMap<>(50000) ; /** * 换成 ascii码 更省事 */ private static final char[] dictionary = {'a','b','c','d','m','p'} ; public static void main(String[] args) throws InterruptedException { Thread t1 = new Thread(new Runnable() { @Override public void run() { for (int i = 0; i < 10000; i++) { addWord(i + "ad"); } } }); Thread t2 = new Thread(new Runnable() { @Override public void run() { for (int i = 0; i < 10000; i++) { addWord(i + "bd"); } } }); Thread t3 = new Thread(new Runnable() { @Override public void run() { for (int i = 0; i < 10000; i++) { addWord(i + "cd"); } } }); Thread t4 = new Thread(new Runnable() { @Override public void run() { for (int i = 0; i < 10000; i++) { addWord(i + "dd"); } } }); Thread t5 = new Thread(new Runnable() { @Override public void run() { for (int i = 0; i < 10000; i++) { addWord(i + "ed"); } } }); t1.start(); t2.start(); t3.start(); t4.start(); t5.start(); t1.join(); t2.join(); t3.join(); t4.join(); t5.join(); System.out.println(ALL_MAP.size()); Assert.assertEquals(50000,ALL_MAP.size()); addWord("bad"); addWord("dad"); addWord("mad"); boolean pad = search("pad"); System.out.println(pad); Assert.assertFalse(pad); boolean bad = search("bad"); System.out.println(bad); Assert.assertTrue(bad); boolean ad = search(".ad"); System.out.println(ad); Assert.assertTrue(ad); boolean bsearch = search("b.."); System.out.println(bsearch); Assert.assertTrue(bsearch); boolean asearch = search(".a."); System.out.println(asearch); boolean search = search(".af"); System.out.println(search); boolean search1 = search(null); System.out.println(search1); } public static boolean search(String keyWord){ boolean result = false ; if (null == keyWord || keyWord.trim().equals("")){ return result ; } //做一 <SUF> String whole = ALL_MAP.get(keyWord) ; if (whole != null){ return true ; } char[] wordChars = keyWord.toCharArray() ; for (int i = 0; i < wordChars.length; i++) { char wordChar = wordChars[i] ; if (46 != (int)wordChar){ continue ; } for (char dic : dictionary) { wordChars[i] = dic ; boolean search = search(String.valueOf(wordChars)); if (search){ return search ; } String value = ALL_MAP.get(String.valueOf(wordChars)); if (value != null){ return true ; } } } return result ; } public static void addWord(String word){ ALL_MAP.put(word,word) ; } }
false
990
5
1,112
5
1,195
5
1,112
5
1,340
14
false
false
false
false
false
true
48388_0
package net.minegeck.plugins.scutils.minequery.ast; import net.minegeck.plugins.scutils.minequery.ast.ASTBinarySelector.ASTBinarySelectorType; import net.minegeck.plugins.scutils.minequery.ast.ASTLimiter.ASTLimiterType; import net.minegeck.plugins.scutils.minequery.token.Token; import net.minegeck.plugins.scutils.minequery.token.TokenSequence; import net.minegeck.plugins.scutils.minequery.token.TokenType; import net.minegeck.plugins.scutils.minequery.token.Tokenizer; import net.minegeck.plugins.utils.Annotations; import java.text.MessageFormat; import java.util.ArrayList; @Annotations.Info(作者 = "SCLeo", 许可 = "GPLv3") public class ASTParser { private final TokenSequence sq; public ASTParser(TokenSequence sequence) { this.sq = sequence; } public ASTParser(String input) { this.sq = new Tokenizer(input).tokenize(); } private ASTExpression parseExpression() { if (sq.isNext(TokenType.PUNCTUATION, "(")) { sq.next(); ASTExpression expression = parsePossibleExpression(); sq.next(TokenType.PUNCTUATION, ")"); return expression; } if (sq.isNext(TokenType.IDENTIFIER)) { return new ASTIdentifierExpression(sq.next().getContent()); } if (sq.isNext(TokenType.NUMBER)) { return new ASTConstNumberExpression(Double.valueOf(sq.next().getContent())); } if (sq.isNext(TokenType.STRING)) { return new ASTConstStringExpression(sq.next().getContent()); } if (sq.isNext(TokenType.OPERATOR, "-")) { sq.next(); ASTExpression content = parseExpression(); if (content == null) { sq.lastException("取负操作符后必须是一个表达式。"); } return new ASTMonadicNumberExpression(ASTMonadicNumberExpression.ASTMonadicNumberExpressionType.NEGATIVE, content); } if (sq.isNext(TokenType.OPERATOR, "!")) { sq.next(); ASTExpression content = parseExpression(); if (content == null) { sq.lastException("非操作符后必须是一个表达式。"); } return new ASTMonadicBooleanExpression(ASTMonadicBooleanExpression.ASTMonadicBooleanExpressionType.NOT, content); } Token nextToken = sq.peek(); sq.lastException(MessageFormat.format("此处不应有 <{0}>。", nextToken == null ? "EOF" : nextToken.getContent())); return null; } private ASTExpression parsePossibleExpression(ASTExpression left, int precedence) { if (sq.isNext(TokenType.OPERATOR)) { String operationRaw = sq.peek().getContent(); BinaryExpressionType operation; switch (operationRaw) { case "&&": operation = ASTBinaryBooleanExpression.ASTBinaryBooleanExpressionType.AND; break; case "||": operation = ASTBinaryBooleanExpression.ASTBinaryBooleanExpressionType.OR; break; case ">": operation = ASTBinaryBooleanExpression.ASTBinaryBooleanExpressionType.LARGER; break; case ">=": operation = ASTBinaryBooleanExpression.ASTBinaryBooleanExpressionType.LARGER_OR_EQUAL; break; case "==": operation = ASTBinaryBooleanExpression.ASTBinaryBooleanExpressionType.EQUAL; break; case "<": operation = ASTBinaryBooleanExpression.ASTBinaryBooleanExpressionType.LESS; break; case "<=": operation = ASTBinaryBooleanExpression.ASTBinaryBooleanExpressionType.LESS_OR_EQUAL; break; case "!=": operation = ASTBinaryBooleanExpression.ASTBinaryBooleanExpressionType.UNEQUAL; break; case "+": operation = ASTBinaryNumberExpression.ASTBinaryNumberExpressionType.PLUS; break; case "-": operation = ASTBinaryNumberExpression.ASTBinaryNumberExpressionType.MINUS; break; case "*": operation = ASTBinaryNumberExpression.ASTBinaryNumberExpressionType.MULTIPLY; break; case "/": operation = ASTBinaryNumberExpression.ASTBinaryNumberExpressionType.DIVID; break; case "%": operation = ASTBinaryNumberExpression.ASTBinaryNumberExpressionType.MOD; break; case "//": operation = ASTBinaryNumberExpression.ASTBinaryNumberExpressionType.INT_DIVID; break; case "&": operation = ASTBinaryStringExpression.ASTBinaryStringExpressionType.CONCAT; break; default: sq.exception(MessageFormat.format("不知道的操作符: {0}。", operationRaw)); return null; //永远不会运行到这里 } if (operation.getPrecedence() > precedence) { sq.next(); return parsePossibleExpression( operation.createExpression(left, parsePossibleExpression( parseExpression(), operation.getPrecedence() )), precedence ); } } return left; } private ASTExpression parsePossibleExpression() { return parsePossibleExpression(parseExpression(), 0); } private ASTClassSelector parseClassSelector() { Token token = sq.next(TokenType.CLASS_SELECTOR); return new ASTClassSelector(token.getContent().substring(1)); } private ASTIDSelector parseIDSelector() { Token token = sq.next(TokenType.ID_SELECTOR); return new ASTIDSelector(token.getContent().substring(1)); } private ASTQuerySelector parseQuerySelector() { Token token = sq.next(TokenType.QUERY_SELECTOR); return new ASTQuerySelector(token.getContent().substring(1)); } private ASTNameSelector parseNameSelector() { Token token = sq.next(TokenType.IDENTIFIER); return new ASTNameSelector(token.getContent()); } private ASTSelector parseAttributeSelector() { sq.next(TokenType.PUNCTUATION, "["); ASTAttributeSelector selector = new ASTAttributeSelector(parsePossibleExpression()); if (!sq.isNext(TokenType.PUNCTUATION, ",")) { sq.next(TokenType.PUNCTUATION, "]"); return selector; } else { ArrayList<ASTSelector> selectors = new ArrayList<>(); selectors.add(selector); while (sq.isNext(TokenType.PUNCTUATION, ",")) { sq.next(); selectors.add(new ASTAttributeSelector(parsePossibleExpression())); } sq.next(TokenType.PUNCTUATION, "]"); return new ASTSelectorUnit(selectors, new ArrayList<ASTLimiter>()); } } private ASTSelector parsePossibleSelector() { if (sq.eof()) { return null; } if (sq.isNext(TokenType.PUNCTUATION, "[")) { return parseAttributeSelector(); } switch (sq.peek().getType()) { case ANONYMOUS_QUERY_SELECTOR: return parseAnonymousQuerySelector(); case QUERY_SELECTOR: return parseQuerySelector(); case ID_SELECTOR: return parseIDSelector(); case CLASS_SELECTOR: return parseClassSelector(); case IDENTIFIER: return parseNameSelector(); default: return null; } } private ASTLimiter parsePossibleLimiter() { if (sq.eof()) { return null; } if (!sq.isNext(TokenType.LIMITER)) { return null; } String typeName = sq.next(TokenType.LIMITER).getContent().substring(1); ASTLimiterType type = ASTLimiter.getLimiterType(typeName); if (type == null) { sq.lastException(MessageFormat.format("不知道名为 {0} 的限制器。", typeName)); } int num = 1; if (sq.isNext(TokenType.PUNCTUATION, "(")) { sq.next(TokenType.PUNCTUATION, "("); String numberStr = sq.next(TokenType.NUMBER).getContent(); try { num = Integer.valueOf(numberStr); } catch(NumberFormatException ex) { sq.lastException(MessageFormat.format("限制器的参数必须是整数, 而 {0} 无法被转换为整数。", numberStr)); } sq.next(TokenType.PUNCTUATION, ")"); } return new ASTLimiter(type, num); } private ASTSelectorUnit parseSelectorUnit() { ArrayList<ASTSelector> selectors = new ArrayList<>(); ASTSelector selector; while ((selector = parsePossibleSelector()) != null) { selectors.add(selector); } if (selectors.isEmpty()) { sq.lastException("空的查询选择器单元。"); } ArrayList<ASTLimiter> limiters = new ArrayList<>(); ASTLimiter limiter; while ((limiter = parsePossibleLimiter()) != null) { limiters.add(limiter); } return new ASTSelectorUnit(selectors, limiters); } private ASTSelector parsePossibleBinarySelector(ASTSelector left, int precedence) { if (sq.isNext(TokenType.OPERATOR)) { String operationRaw = sq.peek().getContent(); ASTBinarySelectorType operation = ASTBinarySelector.getASTBinarySelectorType(operationRaw); if (operation == null) { sq.exception(MessageFormat.format("不知道的集合操作符: {0}。", operationRaw)); } if (operation.getPrecedence() > precedence) { sq.next(); return parsePossibleBinarySelector( new ASTBinarySelector(operation, left, parsePossibleBinarySelector( parseSelectorUnit(), operation.getPrecedence() )), precedence ); } } return left; } private ASTSelector parsePossibleBinarySelector() { return parsePossibleBinarySelector(parseSelectorUnit(), 0); } private ASTAnonymousQuerySelector parseAnonymousQuerySelector() { sq.next(TokenType.ANONYMOUS_QUERY_SELECTOR); if (!sq.isNext(TokenType.PUNCTUATION, "(")) { return new ASTAnonymousQuerySelector(new ArrayList<ASTSelector>()); } sq.next(TokenType.PUNCTUATION, "("); ArrayList<ASTSelector> units = new ArrayList<>(); if (!sq.isNext(TokenType.PUNCTUATION, ")")) { while(true) { units.add(parsePossibleBinarySelector()); if (!sq.isNext(TokenType.PUNCTUATION, ",")) { break; } sq.next(); } } sq.next(TokenType.PUNCTUATION, ")"); return new ASTAnonymousQuerySelector(units); } public ASTSelector parseToSelector() { ASTSelector result = parsePossibleBinarySelector(); if (!sq.eof()) { sq.exception(MessageFormat.format("期待 <EOF>, 找到 {0}。", sq.peek().toString())); } return result; } public ASTExpression parseToExpression() { ASTExpression result = parsePossibleExpression(); if (!sq.eof()) { sq.exception(MessageFormat.format("期待 <EOF>, 找到 {0}。", sq.peek().toString())); } return result; } }
SCLeoX/SCUtils
src/net/minegeck/plugins/scutils/minequery/ast/ASTParser.java
2,499
//永远不会运行到这里
line_comment
zh-cn
package net.minegeck.plugins.scutils.minequery.ast; import net.minegeck.plugins.scutils.minequery.ast.ASTBinarySelector.ASTBinarySelectorType; import net.minegeck.plugins.scutils.minequery.ast.ASTLimiter.ASTLimiterType; import net.minegeck.plugins.scutils.minequery.token.Token; import net.minegeck.plugins.scutils.minequery.token.TokenSequence; import net.minegeck.plugins.scutils.minequery.token.TokenType; import net.minegeck.plugins.scutils.minequery.token.Tokenizer; import net.minegeck.plugins.utils.Annotations; import java.text.MessageFormat; import java.util.ArrayList; @Annotations.Info(作者 = "SCLeo", 许可 = "GPLv3") public class ASTParser { private final TokenSequence sq; public ASTParser(TokenSequence sequence) { this.sq = sequence; } public ASTParser(String input) { this.sq = new Tokenizer(input).tokenize(); } private ASTExpression parseExpression() { if (sq.isNext(TokenType.PUNCTUATION, "(")) { sq.next(); ASTExpression expression = parsePossibleExpression(); sq.next(TokenType.PUNCTUATION, ")"); return expression; } if (sq.isNext(TokenType.IDENTIFIER)) { return new ASTIdentifierExpression(sq.next().getContent()); } if (sq.isNext(TokenType.NUMBER)) { return new ASTConstNumberExpression(Double.valueOf(sq.next().getContent())); } if (sq.isNext(TokenType.STRING)) { return new ASTConstStringExpression(sq.next().getContent()); } if (sq.isNext(TokenType.OPERATOR, "-")) { sq.next(); ASTExpression content = parseExpression(); if (content == null) { sq.lastException("取负操作符后必须是一个表达式。"); } return new ASTMonadicNumberExpression(ASTMonadicNumberExpression.ASTMonadicNumberExpressionType.NEGATIVE, content); } if (sq.isNext(TokenType.OPERATOR, "!")) { sq.next(); ASTExpression content = parseExpression(); if (content == null) { sq.lastException("非操作符后必须是一个表达式。"); } return new ASTMonadicBooleanExpression(ASTMonadicBooleanExpression.ASTMonadicBooleanExpressionType.NOT, content); } Token nextToken = sq.peek(); sq.lastException(MessageFormat.format("此处不应有 <{0}>。", nextToken == null ? "EOF" : nextToken.getContent())); return null; } private ASTExpression parsePossibleExpression(ASTExpression left, int precedence) { if (sq.isNext(TokenType.OPERATOR)) { String operationRaw = sq.peek().getContent(); BinaryExpressionType operation; switch (operationRaw) { case "&&": operation = ASTBinaryBooleanExpression.ASTBinaryBooleanExpressionType.AND; break; case "||": operation = ASTBinaryBooleanExpression.ASTBinaryBooleanExpressionType.OR; break; case ">": operation = ASTBinaryBooleanExpression.ASTBinaryBooleanExpressionType.LARGER; break; case ">=": operation = ASTBinaryBooleanExpression.ASTBinaryBooleanExpressionType.LARGER_OR_EQUAL; break; case "==": operation = ASTBinaryBooleanExpression.ASTBinaryBooleanExpressionType.EQUAL; break; case "<": operation = ASTBinaryBooleanExpression.ASTBinaryBooleanExpressionType.LESS; break; case "<=": operation = ASTBinaryBooleanExpression.ASTBinaryBooleanExpressionType.LESS_OR_EQUAL; break; case "!=": operation = ASTBinaryBooleanExpression.ASTBinaryBooleanExpressionType.UNEQUAL; break; case "+": operation = ASTBinaryNumberExpression.ASTBinaryNumberExpressionType.PLUS; break; case "-": operation = ASTBinaryNumberExpression.ASTBinaryNumberExpressionType.MINUS; break; case "*": operation = ASTBinaryNumberExpression.ASTBinaryNumberExpressionType.MULTIPLY; break; case "/": operation = ASTBinaryNumberExpression.ASTBinaryNumberExpressionType.DIVID; break; case "%": operation = ASTBinaryNumberExpression.ASTBinaryNumberExpressionType.MOD; break; case "//": operation = ASTBinaryNumberExpression.ASTBinaryNumberExpressionType.INT_DIVID; break; case "&": operation = ASTBinaryStringExpression.ASTBinaryStringExpressionType.CONCAT; break; default: sq.exception(MessageFormat.format("不知道的操作符: {0}。", operationRaw)); return null; //永远 <SUF> } if (operation.getPrecedence() > precedence) { sq.next(); return parsePossibleExpression( operation.createExpression(left, parsePossibleExpression( parseExpression(), operation.getPrecedence() )), precedence ); } } return left; } private ASTExpression parsePossibleExpression() { return parsePossibleExpression(parseExpression(), 0); } private ASTClassSelector parseClassSelector() { Token token = sq.next(TokenType.CLASS_SELECTOR); return new ASTClassSelector(token.getContent().substring(1)); } private ASTIDSelector parseIDSelector() { Token token = sq.next(TokenType.ID_SELECTOR); return new ASTIDSelector(token.getContent().substring(1)); } private ASTQuerySelector parseQuerySelector() { Token token = sq.next(TokenType.QUERY_SELECTOR); return new ASTQuerySelector(token.getContent().substring(1)); } private ASTNameSelector parseNameSelector() { Token token = sq.next(TokenType.IDENTIFIER); return new ASTNameSelector(token.getContent()); } private ASTSelector parseAttributeSelector() { sq.next(TokenType.PUNCTUATION, "["); ASTAttributeSelector selector = new ASTAttributeSelector(parsePossibleExpression()); if (!sq.isNext(TokenType.PUNCTUATION, ",")) { sq.next(TokenType.PUNCTUATION, "]"); return selector; } else { ArrayList<ASTSelector> selectors = new ArrayList<>(); selectors.add(selector); while (sq.isNext(TokenType.PUNCTUATION, ",")) { sq.next(); selectors.add(new ASTAttributeSelector(parsePossibleExpression())); } sq.next(TokenType.PUNCTUATION, "]"); return new ASTSelectorUnit(selectors, new ArrayList<ASTLimiter>()); } } private ASTSelector parsePossibleSelector() { if (sq.eof()) { return null; } if (sq.isNext(TokenType.PUNCTUATION, "[")) { return parseAttributeSelector(); } switch (sq.peek().getType()) { case ANONYMOUS_QUERY_SELECTOR: return parseAnonymousQuerySelector(); case QUERY_SELECTOR: return parseQuerySelector(); case ID_SELECTOR: return parseIDSelector(); case CLASS_SELECTOR: return parseClassSelector(); case IDENTIFIER: return parseNameSelector(); default: return null; } } private ASTLimiter parsePossibleLimiter() { if (sq.eof()) { return null; } if (!sq.isNext(TokenType.LIMITER)) { return null; } String typeName = sq.next(TokenType.LIMITER).getContent().substring(1); ASTLimiterType type = ASTLimiter.getLimiterType(typeName); if (type == null) { sq.lastException(MessageFormat.format("不知道名为 {0} 的限制器。", typeName)); } int num = 1; if (sq.isNext(TokenType.PUNCTUATION, "(")) { sq.next(TokenType.PUNCTUATION, "("); String numberStr = sq.next(TokenType.NUMBER).getContent(); try { num = Integer.valueOf(numberStr); } catch(NumberFormatException ex) { sq.lastException(MessageFormat.format("限制器的参数必须是整数, 而 {0} 无法被转换为整数。", numberStr)); } sq.next(TokenType.PUNCTUATION, ")"); } return new ASTLimiter(type, num); } private ASTSelectorUnit parseSelectorUnit() { ArrayList<ASTSelector> selectors = new ArrayList<>(); ASTSelector selector; while ((selector = parsePossibleSelector()) != null) { selectors.add(selector); } if (selectors.isEmpty()) { sq.lastException("空的查询选择器单元。"); } ArrayList<ASTLimiter> limiters = new ArrayList<>(); ASTLimiter limiter; while ((limiter = parsePossibleLimiter()) != null) { limiters.add(limiter); } return new ASTSelectorUnit(selectors, limiters); } private ASTSelector parsePossibleBinarySelector(ASTSelector left, int precedence) { if (sq.isNext(TokenType.OPERATOR)) { String operationRaw = sq.peek().getContent(); ASTBinarySelectorType operation = ASTBinarySelector.getASTBinarySelectorType(operationRaw); if (operation == null) { sq.exception(MessageFormat.format("不知道的集合操作符: {0}。", operationRaw)); } if (operation.getPrecedence() > precedence) { sq.next(); return parsePossibleBinarySelector( new ASTBinarySelector(operation, left, parsePossibleBinarySelector( parseSelectorUnit(), operation.getPrecedence() )), precedence ); } } return left; } private ASTSelector parsePossibleBinarySelector() { return parsePossibleBinarySelector(parseSelectorUnit(), 0); } private ASTAnonymousQuerySelector parseAnonymousQuerySelector() { sq.next(TokenType.ANONYMOUS_QUERY_SELECTOR); if (!sq.isNext(TokenType.PUNCTUATION, "(")) { return new ASTAnonymousQuerySelector(new ArrayList<ASTSelector>()); } sq.next(TokenType.PUNCTUATION, "("); ArrayList<ASTSelector> units = new ArrayList<>(); if (!sq.isNext(TokenType.PUNCTUATION, ")")) { while(true) { units.add(parsePossibleBinarySelector()); if (!sq.isNext(TokenType.PUNCTUATION, ",")) { break; } sq.next(); } } sq.next(TokenType.PUNCTUATION, ")"); return new ASTAnonymousQuerySelector(units); } public ASTSelector parseToSelector() { ASTSelector result = parsePossibleBinarySelector(); if (!sq.eof()) { sq.exception(MessageFormat.format("期待 <EOF>, 找到 {0}。", sq.peek().toString())); } return result; } public ASTExpression parseToExpression() { ASTExpression result = parsePossibleExpression(); if (!sq.eof()) { sq.exception(MessageFormat.format("期待 <EOF>, 找到 {0}。", sq.peek().toString())); } return result; } }
false
2,282
4
2,499
7
2,746
5
2,499
7
3,127
12
false
false
false
false
false
true
22424_2
package models; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import play.data.validation.Required; import play.db.jpa.GenericModel; /** * 客户 * * @author Craig Lee * */ @Entity public class Client extends GenericModel { @Id @GeneratedValue public Long cid; @Required @Column(unique = true) public String email; public String password; public String companyName;// 公司名 public String province;// 所在省份 public String city;// 城市 public String street;// 街道 public String phone;// 联系电话 public String field;// 业务领域 public Client(String email, String password, String companyName, String province, String city, String street, String phone, String field) { this.email = email; this.password = password; this.companyName = companyName; this.province = province; this.city = city; this.street = street; this.phone = phone; this.field = field; } /** * 判断email是否被注册 * * @param email * @return */ public static boolean isEmailRegistered(String email) { int num = find("byEmail", email).fetch().size(); if (num == 0) return false; return true; } @Override public String toString() { return "Client [cid=" + cid + ", email=" + email + ", password=" + password + ", companyName=" + companyName + ", province=" + province + ", city=" + city + ", street=" + street + ", phone=" + phone + ", field=" + field + "]"; } }
SDU-Android-Lab/eQuestionnaire-web
app/models/Client.java
451
// 所在省份
line_comment
zh-cn
package models; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import play.data.validation.Required; import play.db.jpa.GenericModel; /** * 客户 * * @author Craig Lee * */ @Entity public class Client extends GenericModel { @Id @GeneratedValue public Long cid; @Required @Column(unique = true) public String email; public String password; public String companyName;// 公司名 public String province;// 所在 <SUF> public String city;// 城市 public String street;// 街道 public String phone;// 联系电话 public String field;// 业务领域 public Client(String email, String password, String companyName, String province, String city, String street, String phone, String field) { this.email = email; this.password = password; this.companyName = companyName; this.province = province; this.city = city; this.street = street; this.phone = phone; this.field = field; } /** * 判断email是否被注册 * * @param email * @return */ public static boolean isEmailRegistered(String email) { int num = find("byEmail", email).fetch().size(); if (num == 0) return false; return true; } @Override public String toString() { return "Client [cid=" + cid + ", email=" + email + ", password=" + password + ", companyName=" + companyName + ", province=" + province + ", city=" + city + ", street=" + street + ", phone=" + phone + ", field=" + field + "]"; } }
false
371
5
451
5
444
5
451
5
522
8
false
false
false
false
false
true
36341_1
package com.se.homework; import java.io.FileWriter; import java.io.IOException; import java.util.Random; import java.util.Scanner; public class Homework001 { public static String practice(){ Random random = new Random(); int de1 = random.nextInt(101);//用于决定运算符个数 int de2,de3;//用于决定运算符种类 //决定运算符的个数 if(de1%2 == 0){//一个运算符 int num1 = random.nextInt(101); int num2 = random.nextInt(101); int result; char suan; //判断运算符种类 de2 = random.nextInt(2); switch(de2){ case 0 : suan = '+';result = num1+num2;break; case 1 : suan = '-';result = num1-num2;break; default : suan = '+';result = num1+num2;break; } if(0<=result && result<=100) return "" + num1 + suan + num2 + " = " + result; else return "error"; }else{//两个运算符 int num1 = random.nextInt(101); int num2 = random.nextInt(101); int num3 = random.nextInt(101); int result; int temp; char suan1,suan2; //判断运算符种类 de2 = random.nextInt(2); switch(de2){ case 0 : suan1 = '+';temp = num1+num2;break; case 1 : suan1 = '-';temp = num1-num2;break; default : suan1 = '+';temp = num1+num2;break; } de3 = random.nextInt(4); switch(de3){ case 0 : suan2 = '+';result = temp+num3;break; case 1 : suan2 = '-';result = temp-num3;break; default : suan2 = '+';result = temp+num3;break; } if(0<=result && result<=100) return "" + num1 + suan1 + num2 + suan2 + num3 + " = " + result; else return "error"; } } public static boolean check(String[] s1,String s2){//判断是否重复出题 for (int i = 0 ; i<s1.length ; i++){ if(s2.equals(s1[i])){ return false;//重复了 } } return true;//没有重复 } public static void main(String[] args) { System.out.println("请输入今日要刷的题目数量"); Scanner sc = new Scanner(System.in); int n = sc.nextInt(); String[] test = new String[n]; for (int i = 0; i < n; i++) { String s = practice(); if (s.equals("error") || !check(test, s)) { i--; continue; } else { test[i] = s; System.out.println(s); } } //分别获取题目和答案 String[] question = new String[n]; String[] answer = new String[n]; for (int i = 0; i < n; i++) { String[] temp = test[i].split("="); question[i] = temp[0]; answer[i] = temp[1]; } //开始导出题目 for (int i = 0; i < n; i++) { FileWriter out = null; try{ out = new FileWriter("Exercises.txt",true); out.write("四则运算题目" + (i+1) + " "); out.write("\t"); out.write(question[i]); out.write("\n"); out.flush(); }catch(IOException e){ e.printStackTrace(); }finally { if(out != null){ try{ out.close(); }catch(IOException e){ e.printStackTrace(); } } } } //开始导出答案 for (int i = 0; i < n; i++) { FileWriter out = null; try{ out = new FileWriter("Answers.txt",true); out.write("答案" + (i+1) + " "); out.write("\t"); out.write(answer[i]); out.write("\n"); out.flush(); }catch(IOException e){ e.printStackTrace(); }finally { if(out != null){ try{ out.close(); }catch(IOException e){ e.printStackTrace(); } } } } } }
SE-HHU/individual-project-ikun98
Homework001.java
1,134
//用于决定运算符种类
line_comment
zh-cn
package com.se.homework; import java.io.FileWriter; import java.io.IOException; import java.util.Random; import java.util.Scanner; public class Homework001 { public static String practice(){ Random random = new Random(); int de1 = random.nextInt(101);//用于决定运算符个数 int de2,de3;//用于 <SUF> //决定运算符的个数 if(de1%2 == 0){//一个运算符 int num1 = random.nextInt(101); int num2 = random.nextInt(101); int result; char suan; //判断运算符种类 de2 = random.nextInt(2); switch(de2){ case 0 : suan = '+';result = num1+num2;break; case 1 : suan = '-';result = num1-num2;break; default : suan = '+';result = num1+num2;break; } if(0<=result && result<=100) return "" + num1 + suan + num2 + " = " + result; else return "error"; }else{//两个运算符 int num1 = random.nextInt(101); int num2 = random.nextInt(101); int num3 = random.nextInt(101); int result; int temp; char suan1,suan2; //判断运算符种类 de2 = random.nextInt(2); switch(de2){ case 0 : suan1 = '+';temp = num1+num2;break; case 1 : suan1 = '-';temp = num1-num2;break; default : suan1 = '+';temp = num1+num2;break; } de3 = random.nextInt(4); switch(de3){ case 0 : suan2 = '+';result = temp+num3;break; case 1 : suan2 = '-';result = temp-num3;break; default : suan2 = '+';result = temp+num3;break; } if(0<=result && result<=100) return "" + num1 + suan1 + num2 + suan2 + num3 + " = " + result; else return "error"; } } public static boolean check(String[] s1,String s2){//判断是否重复出题 for (int i = 0 ; i<s1.length ; i++){ if(s2.equals(s1[i])){ return false;//重复了 } } return true;//没有重复 } public static void main(String[] args) { System.out.println("请输入今日要刷的题目数量"); Scanner sc = new Scanner(System.in); int n = sc.nextInt(); String[] test = new String[n]; for (int i = 0; i < n; i++) { String s = practice(); if (s.equals("error") || !check(test, s)) { i--; continue; } else { test[i] = s; System.out.println(s); } } //分别获取题目和答案 String[] question = new String[n]; String[] answer = new String[n]; for (int i = 0; i < n; i++) { String[] temp = test[i].split("="); question[i] = temp[0]; answer[i] = temp[1]; } //开始导出题目 for (int i = 0; i < n; i++) { FileWriter out = null; try{ out = new FileWriter("Exercises.txt",true); out.write("四则运算题目" + (i+1) + " "); out.write("\t"); out.write(question[i]); out.write("\n"); out.flush(); }catch(IOException e){ e.printStackTrace(); }finally { if(out != null){ try{ out.close(); }catch(IOException e){ e.printStackTrace(); } } } } //开始导出答案 for (int i = 0; i < n; i++) { FileWriter out = null; try{ out = new FileWriter("Answers.txt",true); out.write("答案" + (i+1) + " "); out.write("\t"); out.write(answer[i]); out.write("\n"); out.flush(); }catch(IOException e){ e.printStackTrace(); }finally { if(out != null){ try{ out.close(); }catch(IOException e){ e.printStackTrace(); } } } } } }
false
1,030
7
1,130
8
1,226
7
1,130
8
1,359
13
false
false
false
false
false
true
54291_6
import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; import java.net.SocketException; /** * 非LISTEN 状态的Recv-Q 和 send-Q * 查看命令:ss -t -a -p |sed -n -e 1,2p -e /port/p * 场景 : 客户端给服务端发送数据 ,服务端不取数据 * * [root@dev ~]#ss -t -a -p |sed -n -e 1,2p -e /apc-necmp/p State Recv-Q Send-Q Local Address:Port Peer Address:Port LISTEN 0 3 :::apc-necmp :::* users:(("java",11946,5)) ESTAB 0 0 ::ffff:127.0.0.1:apc-necmp ::ffff:127.0.0.1:58269 users:(("java",11946,6)) ESTAB 0 0 ::ffff:127.0.0.1:58269 ::ffff:127.0.0.1:apc-necmp users:(("java",11960,5)) [root@dev ~]#ss -t -a -p |sed -n -e 1,2p -e /apc-necmp/p State Recv-Q Send-Q Local Address:Port Peer Address:Port LISTEN 0 3 :::apc-necmp :::* users:(("java",11946,5)) ESTAB 1800 0 ::ffff:127.0.0.1:apc-necmp ::ffff:127.0.0.1:58269 users:(("java",11946,6)) ESTAB 0 1980 ::ffff:127.0.0.1:58269 ::ffff:127.0.0.1:apc-necmp users:(("java",11960,5)) [root@dev ~]#ss -t -a -p |sed -n -e 1,2p -e /apc-necmp/p State Recv-Q Send-Q Local Address:Port Peer Address:Port LISTEN 0 3 :::apc-necmp :::* users:(("java",11946,5)) ESTAB 1800 0 ::ffff:127.0.0.1:apc-necmp ::ffff:127.0.0.1:58269 users:(("java",11946,6)) ESTAB 0 2070 ::ffff:127.0.0.1:58269 ::ffff:127.0.0.1:apc-necmp users:(("java",11960,5)) * * 服务端与客户端链接的状态为: ESTABLISHED ,此时 该链接Recv-Q 队列中存储着客户端发送的数据 当达到1800的时候,队列填满,不再增加 * 客户端与服务端链接的状态为:ESTABLISTED 中Recv-Q 和send-Q 都为零 ,直到 服务端的recv-Q 队列填满,此时数据堆积在客户端 的send-Q * */ public class Serv1 { public static void main(String args[]) { try { // 创建一个socket对象 ServerSocket s = new ServerSocket(18888,3); // socket对象调用accept方法,等待连接请求 Socket s1 = s.accept(); System.out.println("默认-->发送缓冲区大小:" + s1.getSendBufferSize() + "----接收缓冲区大小:" + s1.getReceiveBufferSize()); // s1.setSendBufferSize(1); // 对socket的缓冲区没有什么影响 // s1.setReceiveBufferSize(1); //接收缓冲区 对socket的缓冲区没什么影响 System.out.println("修改后-->发送缓冲区大小:"+s1.getSendBufferSize() +"----接收缓冲区大小:"+s1.getReceiveBufferSize()); /** * 不取数据,等到 Recv-Q 填满 */ // 一直阻塞 while(true){ sleep(); } } catch (SocketException e) { e.printStackTrace(); System.out.println("网络连接异常,程序退出!"); } catch (IOException e) { e.printStackTrace(); } } public static void sleep() { try { Thread.sleep(1000); } catch (Exception e) { } } }
SERE026/tcp-demo
src/main/java/Serv1.java
1,191
// 一直阻塞
line_comment
zh-cn
import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; import java.net.SocketException; /** * 非LISTEN 状态的Recv-Q 和 send-Q * 查看命令:ss -t -a -p |sed -n -e 1,2p -e /port/p * 场景 : 客户端给服务端发送数据 ,服务端不取数据 * * [root@dev ~]#ss -t -a -p |sed -n -e 1,2p -e /apc-necmp/p State Recv-Q Send-Q Local Address:Port Peer Address:Port LISTEN 0 3 :::apc-necmp :::* users:(("java",11946,5)) ESTAB 0 0 ::ffff:127.0.0.1:apc-necmp ::ffff:127.0.0.1:58269 users:(("java",11946,6)) ESTAB 0 0 ::ffff:127.0.0.1:58269 ::ffff:127.0.0.1:apc-necmp users:(("java",11960,5)) [root@dev ~]#ss -t -a -p |sed -n -e 1,2p -e /apc-necmp/p State Recv-Q Send-Q Local Address:Port Peer Address:Port LISTEN 0 3 :::apc-necmp :::* users:(("java",11946,5)) ESTAB 1800 0 ::ffff:127.0.0.1:apc-necmp ::ffff:127.0.0.1:58269 users:(("java",11946,6)) ESTAB 0 1980 ::ffff:127.0.0.1:58269 ::ffff:127.0.0.1:apc-necmp users:(("java",11960,5)) [root@dev ~]#ss -t -a -p |sed -n -e 1,2p -e /apc-necmp/p State Recv-Q Send-Q Local Address:Port Peer Address:Port LISTEN 0 3 :::apc-necmp :::* users:(("java",11946,5)) ESTAB 1800 0 ::ffff:127.0.0.1:apc-necmp ::ffff:127.0.0.1:58269 users:(("java",11946,6)) ESTAB 0 2070 ::ffff:127.0.0.1:58269 ::ffff:127.0.0.1:apc-necmp users:(("java",11960,5)) * * 服务端与客户端链接的状态为: ESTABLISHED ,此时 该链接Recv-Q 队列中存储着客户端发送的数据 当达到1800的时候,队列填满,不再增加 * 客户端与服务端链接的状态为:ESTABLISTED 中Recv-Q 和send-Q 都为零 ,直到 服务端的recv-Q 队列填满,此时数据堆积在客户端 的send-Q * */ public class Serv1 { public static void main(String args[]) { try { // 创建一个socket对象 ServerSocket s = new ServerSocket(18888,3); // socket对象调用accept方法,等待连接请求 Socket s1 = s.accept(); System.out.println("默认-->发送缓冲区大小:" + s1.getSendBufferSize() + "----接收缓冲区大小:" + s1.getReceiveBufferSize()); // s1.setSendBufferSize(1); // 对socket的缓冲区没有什么影响 // s1.setReceiveBufferSize(1); //接收缓冲区 对socket的缓冲区没什么影响 System.out.println("修改后-->发送缓冲区大小:"+s1.getSendBufferSize() +"----接收缓冲区大小:"+s1.getReceiveBufferSize()); /** * 不取数据,等到 Recv-Q 填满 */ // 一直 <SUF> while(true){ sleep(); } } catch (SocketException e) { e.printStackTrace(); System.out.println("网络连接异常,程序退出!"); } catch (IOException e) { e.printStackTrace(); } } public static void sleep() { try { Thread.sleep(1000); } catch (Exception e) { } } }
false
1,121
6
1,184
6
1,146
6
1,184
6
1,473
12
false
false
false
false
false
true
33524_3
import java.util.*; public class Solution { ////////////////////////////////////////////////////////////// // // // 请在此处添加你的代码(函数) // // // ////////////////////////////////////////////////////////////// //start //end class Test{ public int k; public int[] input; public ArrayList<Integer> result; public Test(int k,int[] input,ArrayList<Integer> result){ this.k = k; this.input=input; this.result = result; } public Test(){ } public void printSelf(){ System.out.println("正确输出为:"+result); System.out.println("当前测试用例为:"); if(input==null){ System.out.println("空数组引用"); return; } if(input.length==0){ System.out.println("空数组"); return; } for(int i : input) { System.out.print(i); } System.out.println(" k="+k); } } public static void main(String args[]){ Solution solution = new Solution(); int total = 8; Test[] tests = new Test[total]; tests[0] = solution.new Test(4,new int[]{4,5,1,6,2,7,3,8},new ArrayList<>(Arrays.asList(new Integer[]{1,2,3,4}))); tests[1] = solution.new Test(0,new int[]{},new ArrayList<>()); tests[2] = solution.new Test(0,null,new ArrayList<>()); tests[3] = solution.new Test(1,new int[]{1},new ArrayList<>(Arrays.asList(new Integer[]{1}))); tests[4] = solution.new Test(0,new int[]{4,5,1,6,2,7,3,8},new ArrayList<>()); tests[5] = solution.new Test(8,new int[]{4,5,1,6,2,7,3,8},new ArrayList<>(Arrays.asList(new Integer[]{4,5,1,6,2,7,3,8}))); tests[6] = solution.new Test(8,new int[]{11,33,4,5,1,6,99,384,27,2,7,3,8,10},new ArrayList<>(Arrays.asList(new Integer[]{4,5,1,6,2,7,3,8}))); tests[7] = solution.new Test(2,new int[]{1,99},new ArrayList<>(Arrays.asList(new Integer[]{1,99}))); int i = 0; long runtimeCount = System.currentTimeMillis();//获取当前系统时间(毫秒) try { for (i = 0; i < total; i++) { if(!solution.compare(tests[i].result,solution.GetLeastNumbers_Solution(tests[i].input,tests[i].k))){ solution.printFail(i*100/total,String.valueOf(solution.GetLeastNumbers_Solution(tests[i].input,tests[i].k))); tests[i].printSelf(); return; } } solution.printSuccess(); int runtime = (int)(System.currentTimeMillis()-runtimeCount); System.out.println("运行时间为:"+runtime+"ms"); }catch (Exception e){ solution.printFail(i*100/total,"异常!"); tests[i].printSelf(); System.out.println("出现异常!"); e.printStackTrace(); } } private void printSuccess(){ System.out.println("恭喜!你通过了所有的测试用例"); } private void printFail(int percent,String str){ System.out.println("你未能通过所有的测试用例!("+percent+"%)"); System.out.println("你的输出为:"+str); } private boolean compare(ArrayList<Integer> test,ArrayList<Integer> standard){ if(test.size()!=standard.size()){ return false; } for(int i = 0;i<standard.size();i++){ if(!test.contains(standard.get(i))){ return false; } } return true; } }
SEU-CodingTogether/Algorithms
实操演练/templates/t003.java
974
//获取当前系统时间(毫秒)
line_comment
zh-cn
import java.util.*; public class Solution { ////////////////////////////////////////////////////////////// // // // 请在此处添加你的代码(函数) // // // ////////////////////////////////////////////////////////////// //start //end class Test{ public int k; public int[] input; public ArrayList<Integer> result; public Test(int k,int[] input,ArrayList<Integer> result){ this.k = k; this.input=input; this.result = result; } public Test(){ } public void printSelf(){ System.out.println("正确输出为:"+result); System.out.println("当前测试用例为:"); if(input==null){ System.out.println("空数组引用"); return; } if(input.length==0){ System.out.println("空数组"); return; } for(int i : input) { System.out.print(i); } System.out.println(" k="+k); } } public static void main(String args[]){ Solution solution = new Solution(); int total = 8; Test[] tests = new Test[total]; tests[0] = solution.new Test(4,new int[]{4,5,1,6,2,7,3,8},new ArrayList<>(Arrays.asList(new Integer[]{1,2,3,4}))); tests[1] = solution.new Test(0,new int[]{},new ArrayList<>()); tests[2] = solution.new Test(0,null,new ArrayList<>()); tests[3] = solution.new Test(1,new int[]{1},new ArrayList<>(Arrays.asList(new Integer[]{1}))); tests[4] = solution.new Test(0,new int[]{4,5,1,6,2,7,3,8},new ArrayList<>()); tests[5] = solution.new Test(8,new int[]{4,5,1,6,2,7,3,8},new ArrayList<>(Arrays.asList(new Integer[]{4,5,1,6,2,7,3,8}))); tests[6] = solution.new Test(8,new int[]{11,33,4,5,1,6,99,384,27,2,7,3,8,10},new ArrayList<>(Arrays.asList(new Integer[]{4,5,1,6,2,7,3,8}))); tests[7] = solution.new Test(2,new int[]{1,99},new ArrayList<>(Arrays.asList(new Integer[]{1,99}))); int i = 0; long runtimeCount = System.currentTimeMillis();//获取 <SUF> try { for (i = 0; i < total; i++) { if(!solution.compare(tests[i].result,solution.GetLeastNumbers_Solution(tests[i].input,tests[i].k))){ solution.printFail(i*100/total,String.valueOf(solution.GetLeastNumbers_Solution(tests[i].input,tests[i].k))); tests[i].printSelf(); return; } } solution.printSuccess(); int runtime = (int)(System.currentTimeMillis()-runtimeCount); System.out.println("运行时间为:"+runtime+"ms"); }catch (Exception e){ solution.printFail(i*100/total,"异常!"); tests[i].printSelf(); System.out.println("出现异常!"); e.printStackTrace(); } } private void printSuccess(){ System.out.println("恭喜!你通过了所有的测试用例"); } private void printFail(int percent,String str){ System.out.println("你未能通过所有的测试用例!("+percent+"%)"); System.out.println("你的输出为:"+str); } private boolean compare(ArrayList<Integer> test,ArrayList<Integer> standard){ if(test.size()!=standard.size()){ return false; } for(int i = 0;i<standard.size();i++){ if(!test.contains(standard.get(i))){ return false; } } return true; } }
false
861
9
974
10
1,046
9
974
10
1,152
17
false
false
false
false
false
true
52803_3
package cn.community.user.service; import java.io.IOException; import java.sql.SQLException; import java.text.MessageFormat; import java.util.Properties; import javax.mail.MessagingException; import javax.mail.Session; import cn.community.mail.Mail; import cn.community.mail.MailUtils; import cn.community.tool.CommonUtils; import cn.community.user.domain.User; import cn.community.user.service.exception.UserException; import cn.community.user.dao.UserDao; public class UserService { private UserDao userDao = new UserDao(); /** * 注册功能 * @param user */ public void regist(User user){ /* * 1.数据的补齐 * uuid 32位随机数字 */ user.setUid(CommonUtils.uuid()); user.setStatus(false); user.setActivationCode(CommonUtils.uuid() + CommonUtils.uuid()); /* * 2.向数据库插入 */ try { userDao.add(user); } catch (SQLException e) { throw new RuntimeException(e); } /* * 3.发邮件 */ /* * email_template.properties 是文件名 * 把配置文件的内容加载到prop中 */ Properties prop = new Properties(); try { prop.load(this.getClass().getClassLoader().getResourceAsStream("email_template.properties")); } catch (IOException e1) { throw new RuntimeException(e1); } /* * 登录邮件服务器,得到session */ String host = prop.getProperty("host");//服务器主机名 String name = prop.getProperty("username");//登录名 String pass = prop.getProperty("password");//登录密码 Session session = MailUtils.createSession(host, name, pass); /* *创建Mail对象 */ String from = prop.getProperty("from"); String to = user.getEmail(); String subject = prop.getProperty("subject"); // MessageForm.format方法会把第一个参数中的{0},使用第二个参数来替换。 // 例如MessageFormat.format("你好{0}, 你{1}!", "张三", "去死吧"); 返回“你好张三,你去死吧!” String content = MessageFormat.format(prop.getProperty("content"), user.getActivationCode()); Mail mail = new Mail(from, to, subject, content); /* * 发送邮件 */ try { MailUtils.send(session, mail); } catch (MessagingException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } /** * 用户名注册校验 * @param loginname * @return */ public boolean ajaxValidateLoginname(String loginname){ try { return userDao.ajaxValidateLoginname(loginname); } catch (SQLException e) { throw new RuntimeException(e); } } /** * 邮箱注册校验 * @param email * @return */ public boolean ajaxValidateEmail(String email){ try { return userDao.ajaxValidateEmail(email); } catch (SQLException e) { throw new RuntimeException(e); } } /** * 激活功能 * @param code * @throws UserException */ public void activation(String code) throws UserException{ /* * 1.通过激活码查询用户 * 2.如果User为null,说明是无效激活码,抛出异常,给出异常信息(无效激活码) * 3.查看用户状态是否为true,如果为true,抛出异常,给出异常信息(请不要二次激活) * 4.修改用户状态 */ try { User user = userDao.findByCode(code); if(user == null) throw new UserException("无效的激活码!"); if(user.isStatus()) throw new UserException("你已经激活过了,不要二次激活!"); userDao.updateStatus(user.getUid(), true);//修改状态 } catch (SQLException e) { throw new RuntimeException(e); } } /** * 登录功能 * @param user * @return */ public User login(User user){ try { return userDao.findByLoginnameAndLoginpass(user.getLoginname(), user.getLoginpass()); } catch (SQLException e) { // TODO Auto-generated catch block throw new RuntimeException(e); } } public void updatePassword(String uid,String newPass, String oldPass) throws UserException{ boolean bool; try { bool = userDao.findByUidAndPassword(uid, oldPass); if(!bool){ /* * 1.校验原密码 */ throw new UserException("原密码错误了哦!"); } /* * 2.修改密码 */ userDao.updatePassword(uid, newPass); } catch (SQLException e) { throw new RuntimeException(e); } } }
SK-Keith/community
src/cn/community/user/service/UserService.java
1,278
/* * 3.发邮件 */
block_comment
zh-cn
package cn.community.user.service; import java.io.IOException; import java.sql.SQLException; import java.text.MessageFormat; import java.util.Properties; import javax.mail.MessagingException; import javax.mail.Session; import cn.community.mail.Mail; import cn.community.mail.MailUtils; import cn.community.tool.CommonUtils; import cn.community.user.domain.User; import cn.community.user.service.exception.UserException; import cn.community.user.dao.UserDao; public class UserService { private UserDao userDao = new UserDao(); /** * 注册功能 * @param user */ public void regist(User user){ /* * 1.数据的补齐 * uuid 32位随机数字 */ user.setUid(CommonUtils.uuid()); user.setStatus(false); user.setActivationCode(CommonUtils.uuid() + CommonUtils.uuid()); /* * 2.向数据库插入 */ try { userDao.add(user); } catch (SQLException e) { throw new RuntimeException(e); } /* * 3.发 <SUF>*/ /* * email_template.properties 是文件名 * 把配置文件的内容加载到prop中 */ Properties prop = new Properties(); try { prop.load(this.getClass().getClassLoader().getResourceAsStream("email_template.properties")); } catch (IOException e1) { throw new RuntimeException(e1); } /* * 登录邮件服务器,得到session */ String host = prop.getProperty("host");//服务器主机名 String name = prop.getProperty("username");//登录名 String pass = prop.getProperty("password");//登录密码 Session session = MailUtils.createSession(host, name, pass); /* *创建Mail对象 */ String from = prop.getProperty("from"); String to = user.getEmail(); String subject = prop.getProperty("subject"); // MessageForm.format方法会把第一个参数中的{0},使用第二个参数来替换。 // 例如MessageFormat.format("你好{0}, 你{1}!", "张三", "去死吧"); 返回“你好张三,你去死吧!” String content = MessageFormat.format(prop.getProperty("content"), user.getActivationCode()); Mail mail = new Mail(from, to, subject, content); /* * 发送邮件 */ try { MailUtils.send(session, mail); } catch (MessagingException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } /** * 用户名注册校验 * @param loginname * @return */ public boolean ajaxValidateLoginname(String loginname){ try { return userDao.ajaxValidateLoginname(loginname); } catch (SQLException e) { throw new RuntimeException(e); } } /** * 邮箱注册校验 * @param email * @return */ public boolean ajaxValidateEmail(String email){ try { return userDao.ajaxValidateEmail(email); } catch (SQLException e) { throw new RuntimeException(e); } } /** * 激活功能 * @param code * @throws UserException */ public void activation(String code) throws UserException{ /* * 1.通过激活码查询用户 * 2.如果User为null,说明是无效激活码,抛出异常,给出异常信息(无效激活码) * 3.查看用户状态是否为true,如果为true,抛出异常,给出异常信息(请不要二次激活) * 4.修改用户状态 */ try { User user = userDao.findByCode(code); if(user == null) throw new UserException("无效的激活码!"); if(user.isStatus()) throw new UserException("你已经激活过了,不要二次激活!"); userDao.updateStatus(user.getUid(), true);//修改状态 } catch (SQLException e) { throw new RuntimeException(e); } } /** * 登录功能 * @param user * @return */ public User login(User user){ try { return userDao.findByLoginnameAndLoginpass(user.getLoginname(), user.getLoginpass()); } catch (SQLException e) { // TODO Auto-generated catch block throw new RuntimeException(e); } } public void updatePassword(String uid,String newPass, String oldPass) throws UserException{ boolean bool; try { bool = userDao.findByUidAndPassword(uid, oldPass); if(!bool){ /* * 1.校验原密码 */ throw new UserException("原密码错误了哦!"); } /* * 2.修改密码 */ userDao.updatePassword(uid, newPass); } catch (SQLException e) { throw new RuntimeException(e); } } }
false
1,096
11
1,278
10
1,291
12
1,278
10
1,705
17
false
false
false
false
false
true
36509_11
package slmt.crawler.dcard.json; import java.util.LinkedList; import java.util.List; public class Post { // 文章基本資料 public long id; // 編號 public String title; // 標題 public String content; // 內文 public String excerpt; // 摘要 public String createdAt; // 發文時間 public String updatedAt; // 最後更新時間(有人留言也算更新) public String deletedAt; // 刪除時間 (真的會看到這個變數的內容嗎?) public int commentCount; // 回覆人數 public int likeCount; // 喜歡的人數 public List<String> tags = new LinkedList<String>(); // 發文者資料 public boolean anonymousSchool; // 是否隱藏學校 public boolean anonymousDepartment; // 是否隱藏系所 public String gender; // 性別 public String school; // 學校 public String department; // 系所 public boolean currentMember; // 登入的人是不是發文者 // 所屬版面資訊 public boolean pinned; // 是否置頂 public String forumId; // 版面編號? (不確定) public String forumName; // 版面名稱 public String forumAlias; // 版面縮寫 // 不確定用途 public String replyId; // 也許是回覆的原文編號 (預設值是 null) }
SLMT/dcard-crawler
src/main/java/slmt/crawler/dcard/json/Post.java
392
// 是否置頂
line_comment
zh-cn
package slmt.crawler.dcard.json; import java.util.LinkedList; import java.util.List; public class Post { // 文章基本資料 public long id; // 編號 public String title; // 標題 public String content; // 內文 public String excerpt; // 摘要 public String createdAt; // 發文時間 public String updatedAt; // 最後更新時間(有人留言也算更新) public String deletedAt; // 刪除時間 (真的會看到這個變數的內容嗎?) public int commentCount; // 回覆人數 public int likeCount; // 喜歡的人數 public List<String> tags = new LinkedList<String>(); // 發文者資料 public boolean anonymousSchool; // 是否隱藏學校 public boolean anonymousDepartment; // 是否隱藏系所 public String gender; // 性別 public String school; // 學校 public String department; // 系所 public boolean currentMember; // 登入的人是不是發文者 // 所屬版面資訊 public boolean pinned; // 是否 <SUF> public String forumId; // 版面編號? (不確定) public String forumName; // 版面名稱 public String forumAlias; // 版面縮寫 // 不確定用途 public String replyId; // 也許是回覆的原文編號 (預設值是 null) }
false
310
4
392
5
331
4
392
5
482
8
false
false
false
false
false
true
8689_66
package juc.concurrent; import java.util.Date; /** * @author: imi * @Date: 2019/6/1 16:47 * @Description: 熟记Thread类的各个方法 */ public class TreadTest { protected static boolean RUN_FLAG = true; protected static int MAX_RUN_TIMES = 6; public static void main(String[] args) throws Exception { //sleep 用法 // Thread t1 = new T1(); // t1.start(); // Thread.sleep(10000); // System.out.println("主线程睡醒了"); // RUN_FLAG=false; //join 用法 // Thread t2 = new T2("子线程"); // t2.start(); // t2.join(); // t2.run(); // for(int i = 0; i< TreadTest.MAX_RUN_TIMES; i++) { // System.out.println( "主线程运行第" + i + "次"); // } //yield用法 // T3 t33 = new T3("IIIIIIII"); // T3 t34 = new T3("OOOOOOOO"); // for(int i = 0; i< TreadTest.MAX_RUN_TIMES; i++) { // System.out.println( "主线程运行第" + i + "次"); // } // t33.start(); // t34.start(); //线程优先级 // Thread t21 = new T4("低优先级线程"); // Thread t22 = new T4("高优先级线程"); // // t21.setPriority(Thread.MIN_PRIORITY); // t22.setPriority(Thread.MAX_PRIORITY); // // t21.start(); // t22.start(); //线程同步 // final Timer timer = new Timer(); // Thread t1 = new Thread(new Runnable() { // public void run() { // timer.doSomething("T1"); // } // }); // Thread t2 = new Thread(new Runnable() { // public void run() { // timer.doSomething("T2"); // } // }); // t1.start();t2.start(); //线程死锁 // final Object obj1 = new Object(); // final Object obj2 = new Object(); // new Thread(new Runnable() { // public void run() { // synchronized (obj1){ // System.out.println("线程1获得了obj1"); // System.out.println("线程1尝试获取获取obj2"); // try { // Thread.sleep(3000); // } catch (InterruptedException e) { // e.printStackTrace(); // } // synchronized (obj2){ // System.out.println("线程1获得了obj2"); // } // // } // } // }).start(); // new Thread(new Runnable() { // public void run() { // synchronized (obj2){ // System.out.println("线程2获得了obj2"); // System.out.println("线程2尝试获取获取obj1"); // try { // Thread.sleep(1900); // } catch (InterruptedException e) { // e.printStackTrace(); // } // synchronized (obj1){ // System.out.println("线程2获得了obj1"); // } // // } // } // }).start(); } } class T1 extends Thread { @Override public void run() { while (true) { if (!TreadTest.RUN_FLAG) { break; } System.out.println(new Date()); } } } class T2 extends Thread { public T2(String s) { super(s); } @Override public void run() { for (int i = 0; i < TreadTest.MAX_RUN_TIMES; i++) { System.out.println(this.getName() + "运行第" + i + "次"); try { Thread.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); } } } } class T3 extends Thread { public T3(String s) { super(s); } @Override public void run() { for (int i = 0; i < 2 * TreadTest.MAX_RUN_TIMES; i++) { System.out.println(this.getName() + " " + i); if (i % 4 == 0) { yield();//他妈的随机的 } } } } class T4 extends Thread { public T4(String s) { super(s); } @Override public void run() { for (int i = 0; i < TreadTest.MAX_RUN_TIMES; i++) { System.out.println(this.getName() + "运行第" + i + "次"); } } } class Timer { private static int num = 0; void doSomething(String name) { synchronized (this) { num++; try { Thread.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(name + ":你是第" + num + "个使用timer的线程"); } } }
SSSDNSY/one-stop-java
java-base/src/main/java/juc/concurrent/TreadTest.java
1,335
//他妈的随机的
line_comment
zh-cn
package juc.concurrent; import java.util.Date; /** * @author: imi * @Date: 2019/6/1 16:47 * @Description: 熟记Thread类的各个方法 */ public class TreadTest { protected static boolean RUN_FLAG = true; protected static int MAX_RUN_TIMES = 6; public static void main(String[] args) throws Exception { //sleep 用法 // Thread t1 = new T1(); // t1.start(); // Thread.sleep(10000); // System.out.println("主线程睡醒了"); // RUN_FLAG=false; //join 用法 // Thread t2 = new T2("子线程"); // t2.start(); // t2.join(); // t2.run(); // for(int i = 0; i< TreadTest.MAX_RUN_TIMES; i++) { // System.out.println( "主线程运行第" + i + "次"); // } //yield用法 // T3 t33 = new T3("IIIIIIII"); // T3 t34 = new T3("OOOOOOOO"); // for(int i = 0; i< TreadTest.MAX_RUN_TIMES; i++) { // System.out.println( "主线程运行第" + i + "次"); // } // t33.start(); // t34.start(); //线程优先级 // Thread t21 = new T4("低优先级线程"); // Thread t22 = new T4("高优先级线程"); // // t21.setPriority(Thread.MIN_PRIORITY); // t22.setPriority(Thread.MAX_PRIORITY); // // t21.start(); // t22.start(); //线程同步 // final Timer timer = new Timer(); // Thread t1 = new Thread(new Runnable() { // public void run() { // timer.doSomething("T1"); // } // }); // Thread t2 = new Thread(new Runnable() { // public void run() { // timer.doSomething("T2"); // } // }); // t1.start();t2.start(); //线程死锁 // final Object obj1 = new Object(); // final Object obj2 = new Object(); // new Thread(new Runnable() { // public void run() { // synchronized (obj1){ // System.out.println("线程1获得了obj1"); // System.out.println("线程1尝试获取获取obj2"); // try { // Thread.sleep(3000); // } catch (InterruptedException e) { // e.printStackTrace(); // } // synchronized (obj2){ // System.out.println("线程1获得了obj2"); // } // // } // } // }).start(); // new Thread(new Runnable() { // public void run() { // synchronized (obj2){ // System.out.println("线程2获得了obj2"); // System.out.println("线程2尝试获取获取obj1"); // try { // Thread.sleep(1900); // } catch (InterruptedException e) { // e.printStackTrace(); // } // synchronized (obj1){ // System.out.println("线程2获得了obj1"); // } // // } // } // }).start(); } } class T1 extends Thread { @Override public void run() { while (true) { if (!TreadTest.RUN_FLAG) { break; } System.out.println(new Date()); } } } class T2 extends Thread { public T2(String s) { super(s); } @Override public void run() { for (int i = 0; i < TreadTest.MAX_RUN_TIMES; i++) { System.out.println(this.getName() + "运行第" + i + "次"); try { Thread.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); } } } } class T3 extends Thread { public T3(String s) { super(s); } @Override public void run() { for (int i = 0; i < 2 * TreadTest.MAX_RUN_TIMES; i++) { System.out.println(this.getName() + " " + i); if (i % 4 == 0) { yield();//他妈 <SUF> } } } } class T4 extends Thread { public T4(String s) { super(s); } @Override public void run() { for (int i = 0; i < TreadTest.MAX_RUN_TIMES; i++) { System.out.println(this.getName() + "运行第" + i + "次"); } } } class Timer { private static int num = 0; void doSomething(String name) { synchronized (this) { num++; try { Thread.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(name + ":你是第" + num + "个使用timer的线程"); } } }
false
1,149
5
1,335
7
1,371
6
1,335
7
1,542
11
false
false
false
false
false
true
62256_9
package com.sshine.huochexing.bean; import java.io.Serializable; //旅行车次类 public class Travel implements Serializable { /** * */ private static final long serialVersionUID = 1L; private boolean isRequested; //是否已向服务器端请求过数据 private int msgType; //信息类型,0为未发车,1为在车上,2为已到目的站,3为列车还没有从起始站发车 private int sourceType; //信息源类型,0为用时间区间推算而得,1为用用户信息反馈而得 private String nativeId; //本地数据库表中的相应记录的id private String serverId; //服务器表中的相应记录的id private int Uid; //用户id,现用于区分模拟数据 private String travelName; //旅行代号 private String trainNum; //车次 private String startStation; //出发站 private String endStation; //目的站 private String r_Date; //总耗时 private String startLongitude; //出发站经度 private String startLatitude; //出发站纬度 private int receiveMsg; // 是否接收消息 private int receivedReminder; //是否已接收过提醒 private int isRepeatReminder; //是否进行重复提醒 private String trainStatus; //列车状态 private String longitude; //经度 private String latitude; //纬度 private int stationSpace; //距离出发站的站距 private long lateTime; //晚点时间,毫秒 private String startTime; //正点发车时间(包括日期) private String endTime; //正点到站时间(包括日期) private String t_StartTime; //车次从起始站的发车时间 private String predictTime; //预计发车时间 private String remainingTime; //剩余时间 private String userStatusRange; //乘车状态可选项范围,用逗号分隔 private int userStatus; //乘车状态 private int userAddTrain; //添加此车次的人数 private int userOnTrain; //当前在此车次上的人数 public static final String[] USER_STATUS = {"未上车","已上车","已下车"}; public String getTravelName() { return travelName; } public void setTravelName(String travelName) { this.travelName = travelName; } public String getTrainNum() { return trainNum; } public void setTrainNum(String trainNum) { this.trainNum = trainNum; } public String getStartStation() { return startStation; } public void setStartStation(String startStation) { this.startStation = startStation; } public String getEndStation() { return endStation; } public void setEndStation(String endStation) { this.endStation = endStation; } public String getR_Date() { return r_Date; } public void setR_Date(String r_Date) { this.r_Date = r_Date; } public String getTrainStatus() { return trainStatus; } public void setTrainStatus(String trainStatus) { this.trainStatus = trainStatus; } public String getLongitude() { return longitude; } public void setLongitude(String longitude) { this.longitude = longitude; } public String getLatitude() { return latitude; } public void setLatitude(String latitude) { this.latitude = latitude; } public String getPredictTime() { return predictTime; } public void setPredictTime(String predictStartTime) { this.predictTime = predictStartTime; } public String getRemainingTime() { return remainingTime; } public void setRemainingTime(String remainingTime) { this.remainingTime = remainingTime; } public String getStartTime() { return startTime; } public void setStartTime(String startTime) { this.startTime = startTime; } public String getUserStatusArray() { return userStatusRange; } public void setUserStatusArray(String userStatusArray) { this.userStatusRange = userStatusArray; } public String getT_startTime() { return t_StartTime; } public void setT_startTime(String t_startTime) { this.t_StartTime = t_startTime; } public boolean isRequested() { return isRequested; } public void setRequested(boolean isRequested) { this.isRequested = isRequested; } public String getNativeId() { return nativeId; } public void setNativeId(String nativeId) { this.nativeId = nativeId; } public String getServerId() { return serverId; } public void setServerId(String serverId) { this.serverId = serverId; } public int getMsgType() { return msgType; } public void setMsgType(int msgType) { this.msgType = msgType; } public int getStationSpace() { return stationSpace; } public void setStationSpace(int stationSpace) { this.stationSpace = stationSpace; } public String getEndTime() { return endTime; } public void setEndTime(String endTime) { this.endTime = endTime; } public int getSourceType() { return sourceType; } public void setSourceType(int sourceType) { this.sourceType = sourceType; } public int getUserStatus() { return userStatus; } public void setUserStatus(int userStatus) { this.userStatus = userStatus; } public String getStartLongitude() { return startLongitude; } public void setStartLongitude(String startLongitude) { this.startLongitude = startLongitude; } public String getStartLatitude() { return startLatitude; } public void setStartLatitude(String startLatitude) { this.startLatitude = startLatitude; } public int getReceiveMsg() { return receiveMsg; } public void setReceiveMsg(int receiveMsg) { this.receiveMsg = receiveMsg; } public int getReceivedReminder() { return receivedReminder; } public void setReceivedReminder(int receivedReminder) { this.receivedReminder = receivedReminder; } public String getUserStatusRange() { return userStatusRange; } public void setUserStatusRange(String userStatusRange) { this.userStatusRange = userStatusRange; } public int getUserAddTrain() { return userAddTrain; } public void setUserAddTrain(int userAddTrain) { this.userAddTrain = userAddTrain; } public int getUserOnTrain() { return userOnTrain; } public void setUserOnTrain(int userOnTrain) { this.userOnTrain = userOnTrain; } public int getUid() { return Uid; } public void setUid(int uid) { Uid = uid; } public int getIsRepeatReminder() { return isRepeatReminder; } public void setIsRepeatReminder(int isRepeatReminder) { this.isRepeatReminder = isRepeatReminder; } public long getLateTime() { return lateTime; } public void setLateTime(long lateTime) { this.lateTime = lateTime; } }
SShineTeam/Huochexing12306
HuoCheXing/src/main/java/com/sshine/huochexing/bean/Travel.java
1,941
//目的站
line_comment
zh-cn
package com.sshine.huochexing.bean; import java.io.Serializable; //旅行车次类 public class Travel implements Serializable { /** * */ private static final long serialVersionUID = 1L; private boolean isRequested; //是否已向服务器端请求过数据 private int msgType; //信息类型,0为未发车,1为在车上,2为已到目的站,3为列车还没有从起始站发车 private int sourceType; //信息源类型,0为用时间区间推算而得,1为用用户信息反馈而得 private String nativeId; //本地数据库表中的相应记录的id private String serverId; //服务器表中的相应记录的id private int Uid; //用户id,现用于区分模拟数据 private String travelName; //旅行代号 private String trainNum; //车次 private String startStation; //出发站 private String endStation; //目的 <SUF> private String r_Date; //总耗时 private String startLongitude; //出发站经度 private String startLatitude; //出发站纬度 private int receiveMsg; // 是否接收消息 private int receivedReminder; //是否已接收过提醒 private int isRepeatReminder; //是否进行重复提醒 private String trainStatus; //列车状态 private String longitude; //经度 private String latitude; //纬度 private int stationSpace; //距离出发站的站距 private long lateTime; //晚点时间,毫秒 private String startTime; //正点发车时间(包括日期) private String endTime; //正点到站时间(包括日期) private String t_StartTime; //车次从起始站的发车时间 private String predictTime; //预计发车时间 private String remainingTime; //剩余时间 private String userStatusRange; //乘车状态可选项范围,用逗号分隔 private int userStatus; //乘车状态 private int userAddTrain; //添加此车次的人数 private int userOnTrain; //当前在此车次上的人数 public static final String[] USER_STATUS = {"未上车","已上车","已下车"}; public String getTravelName() { return travelName; } public void setTravelName(String travelName) { this.travelName = travelName; } public String getTrainNum() { return trainNum; } public void setTrainNum(String trainNum) { this.trainNum = trainNum; } public String getStartStation() { return startStation; } public void setStartStation(String startStation) { this.startStation = startStation; } public String getEndStation() { return endStation; } public void setEndStation(String endStation) { this.endStation = endStation; } public String getR_Date() { return r_Date; } public void setR_Date(String r_Date) { this.r_Date = r_Date; } public String getTrainStatus() { return trainStatus; } public void setTrainStatus(String trainStatus) { this.trainStatus = trainStatus; } public String getLongitude() { return longitude; } public void setLongitude(String longitude) { this.longitude = longitude; } public String getLatitude() { return latitude; } public void setLatitude(String latitude) { this.latitude = latitude; } public String getPredictTime() { return predictTime; } public void setPredictTime(String predictStartTime) { this.predictTime = predictStartTime; } public String getRemainingTime() { return remainingTime; } public void setRemainingTime(String remainingTime) { this.remainingTime = remainingTime; } public String getStartTime() { return startTime; } public void setStartTime(String startTime) { this.startTime = startTime; } public String getUserStatusArray() { return userStatusRange; } public void setUserStatusArray(String userStatusArray) { this.userStatusRange = userStatusArray; } public String getT_startTime() { return t_StartTime; } public void setT_startTime(String t_startTime) { this.t_StartTime = t_startTime; } public boolean isRequested() { return isRequested; } public void setRequested(boolean isRequested) { this.isRequested = isRequested; } public String getNativeId() { return nativeId; } public void setNativeId(String nativeId) { this.nativeId = nativeId; } public String getServerId() { return serverId; } public void setServerId(String serverId) { this.serverId = serverId; } public int getMsgType() { return msgType; } public void setMsgType(int msgType) { this.msgType = msgType; } public int getStationSpace() { return stationSpace; } public void setStationSpace(int stationSpace) { this.stationSpace = stationSpace; } public String getEndTime() { return endTime; } public void setEndTime(String endTime) { this.endTime = endTime; } public int getSourceType() { return sourceType; } public void setSourceType(int sourceType) { this.sourceType = sourceType; } public int getUserStatus() { return userStatus; } public void setUserStatus(int userStatus) { this.userStatus = userStatus; } public String getStartLongitude() { return startLongitude; } public void setStartLongitude(String startLongitude) { this.startLongitude = startLongitude; } public String getStartLatitude() { return startLatitude; } public void setStartLatitude(String startLatitude) { this.startLatitude = startLatitude; } public int getReceiveMsg() { return receiveMsg; } public void setReceiveMsg(int receiveMsg) { this.receiveMsg = receiveMsg; } public int getReceivedReminder() { return receivedReminder; } public void setReceivedReminder(int receivedReminder) { this.receivedReminder = receivedReminder; } public String getUserStatusRange() { return userStatusRange; } public void setUserStatusRange(String userStatusRange) { this.userStatusRange = userStatusRange; } public int getUserAddTrain() { return userAddTrain; } public void setUserAddTrain(int userAddTrain) { this.userAddTrain = userAddTrain; } public int getUserOnTrain() { return userOnTrain; } public void setUserOnTrain(int userOnTrain) { this.userOnTrain = userOnTrain; } public int getUid() { return Uid; } public void setUid(int uid) { Uid = uid; } public int getIsRepeatReminder() { return isRepeatReminder; } public void setIsRepeatReminder(int isRepeatReminder) { this.isRepeatReminder = isRepeatReminder; } public long getLateTime() { return lateTime; } public void setLateTime(long lateTime) { this.lateTime = lateTime; } }
false
1,545
3
1,941
3
1,904
3
1,941
3
2,274
4
false
false
false
false
false
true
46634_6
/* * @lc app=leetcode.cn id=406 lang=java * * [406] 根据身高重建队列 * * https://leetcode.cn/problems/queue-reconstruction-by-height/description/ * * algorithms * Medium (76.35%) * Likes: 1737 * Dislikes: 0 * Total Accepted: 271.2K * Total Submissions: 355.2K * Testcase Example: '[[7,0],[4,4],[7,1],[5,0],[6,1],[5,2]]' * * 假设有打乱顺序的一群人站成一个队列,数组 people 表示队列中一些人的属性(不一定按顺序)。每个 people[i] = [hi, ki] 表示第 * i 个人的身高为 hi ,前面 正好 有 ki 个身高大于或等于 hi 的人。 * * 请你重新构造并返回输入数组 people 所表示的队列。返回的队列应该格式化为数组 queue ,其中 queue[j] = [hj, kj] * 是队列中第 j 个人的属性(queue[0] 是排在队列前面的人)。 * * * * * * * 示例 1: * * * 输入:people = [[7,0],[4,4],[7,1],[5,0],[6,1],[5,2]] * 输出:[[5,0],[7,0],[5,2],[6,1],[4,4],[7,1]] * 解释: * 编号为 0 的人身高为 5 ,没有身高更高或者相同的人排在他前面。 * 编号为 1 的人身高为 7 ,没有身高更高或者相同的人排在他前面。 * 编号为 2 的人身高为 5 ,有 2 个身高更高或者相同的人排在他前面,即编号为 0 和 1 的人。 * 编号为 3 的人身高为 6 ,有 1 个身高更高或者相同的人排在他前面,即编号为 1 的人。 * 编号为 4 的人身高为 4 ,有 4 个身高更高或者相同的人排在他前面,即编号为 0、1、2、3 的人。 * 编号为 5 的人身高为 7 ,有 1 个身高更高或者相同的人排在他前面,即编号为 1 的人。 * 因此 [[5,0],[7,0],[5,2],[6,1],[4,4],[7,1]] 是重新构造后的队列。 * * * 示例 2: * * * 输入:people = [[6,0],[5,0],[4,0],[3,2],[2,2],[1,4]] * 输出:[[4,0],[5,0],[2,2],[3,2],[1,4],[6,0]] * * * * * 提示: * * * 1 * 0 i * 0 i < people.length * 题目数据确保队列可以被重建 * * */ // @lc code=start class Solution { public int[][] reconstructQueue(int[][] people) { // 1. 先按照身高降序,k升序排序 Arrays.sort(people, (o1, o2) -> { if (o1[0] != o2[0]) return o2[0] - o1[0]; // 身高相同,按照k升序 else return o1[1] - o2[1]; }); // 2. 按照k插入到list中 List<int[]> list = new ArrayList<>(); for (int[] p : people) { // 2.1. 插入到k位置 list.add(p[1], p); } // 3. 转换为数组返回 return list.toArray(new int[list.size()][]); } } // @lc code=end
STARK-775178/leet_code
src/406.根据身高重建队列.java
976
// 3. 转换为数组返回
line_comment
zh-cn
/* * @lc app=leetcode.cn id=406 lang=java * * [406] 根据身高重建队列 * * https://leetcode.cn/problems/queue-reconstruction-by-height/description/ * * algorithms * Medium (76.35%) * Likes: 1737 * Dislikes: 0 * Total Accepted: 271.2K * Total Submissions: 355.2K * Testcase Example: '[[7,0],[4,4],[7,1],[5,0],[6,1],[5,2]]' * * 假设有打乱顺序的一群人站成一个队列,数组 people 表示队列中一些人的属性(不一定按顺序)。每个 people[i] = [hi, ki] 表示第 * i 个人的身高为 hi ,前面 正好 有 ki 个身高大于或等于 hi 的人。 * * 请你重新构造并返回输入数组 people 所表示的队列。返回的队列应该格式化为数组 queue ,其中 queue[j] = [hj, kj] * 是队列中第 j 个人的属性(queue[0] 是排在队列前面的人)。 * * * * * * * 示例 1: * * * 输入:people = [[7,0],[4,4],[7,1],[5,0],[6,1],[5,2]] * 输出:[[5,0],[7,0],[5,2],[6,1],[4,4],[7,1]] * 解释: * 编号为 0 的人身高为 5 ,没有身高更高或者相同的人排在他前面。 * 编号为 1 的人身高为 7 ,没有身高更高或者相同的人排在他前面。 * 编号为 2 的人身高为 5 ,有 2 个身高更高或者相同的人排在他前面,即编号为 0 和 1 的人。 * 编号为 3 的人身高为 6 ,有 1 个身高更高或者相同的人排在他前面,即编号为 1 的人。 * 编号为 4 的人身高为 4 ,有 4 个身高更高或者相同的人排在他前面,即编号为 0、1、2、3 的人。 * 编号为 5 的人身高为 7 ,有 1 个身高更高或者相同的人排在他前面,即编号为 1 的人。 * 因此 [[5,0],[7,0],[5,2],[6,1],[4,4],[7,1]] 是重新构造后的队列。 * * * 示例 2: * * * 输入:people = [[6,0],[5,0],[4,0],[3,2],[2,2],[1,4]] * 输出:[[4,0],[5,0],[2,2],[3,2],[1,4],[6,0]] * * * * * 提示: * * * 1 * 0 i * 0 i < people.length * 题目数据确保队列可以被重建 * * */ // @lc code=start class Solution { public int[][] reconstructQueue(int[][] people) { // 1. 先按照身高降序,k升序排序 Arrays.sort(people, (o1, o2) -> { if (o1[0] != o2[0]) return o2[0] - o1[0]; // 身高相同,按照k升序 else return o1[1] - o2[1]; }); // 2. 按照k插入到list中 List<int[]> list = new ArrayList<>(); for (int[] p : people) { // 2.1. 插入到k位置 list.add(p[1], p); } // 3. <SUF> return list.toArray(new int[list.size()][]); } } // @lc code=end
false
920
11
976
9
951
8
976
9
1,233
12
false
false
false
false
false
true
53300_0
package secret; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import org.apache.commons.codec.binary.Hex; import org.apache.commons.codec.digest.DigestUtils; import org.bouncycastle.crypto.Digest; import org.bouncycastle.crypto.digests.MD4Digest; import org.bouncycastle.crypto.digests.MD5Digest; public class MDTest { public static String src = "i am gc MD"; public static void main(String[] args) { System.out.println("=====jdk提供的MD5====="); jdkMD5(); System.out.println("====================="); System.out.println("=====jdk提供的MD2====="); jdkMD2(); System.out.println("====================="); System.out.println("=====BC提供的MD4====="); bcMD4(); System.out.println("====================="); System.out.println("=====BC提供的MD5====="); bcMD5(); System.out.println("====================="); System.out.println("=====CC提供的MD5====="); ccMD5(); System.out.println("====================="); System.out.println("=====CC提供的MD2====="); ccMD2(); System.out.println("====================="); //运行结果 /*=====jdk提供的MD5===== 信息摘要之后的src: 8a63f68d49d7acfa716602e9ab620394 ===================== =====jdk提供的MD2===== 信息摘要之后的src: 2d2df5c04ceeaac31bdffb019ccd03c8 ===================== =====BC提供的MD4===== 信息摘要之后的src: 5ff5d77df559660ed4ff19ac2f5e2e2a ===================== =====BC提供的MD5===== 信息摘要之后的src: 8a63f68d49d7acfa716602e9ab620394 ===================== =====CC提供的MD5===== 信息摘要之后的src: 8a63f68d49d7acfa716602e9ab620394 ===================== =====CC提供的MD2===== 信息摘要之后的src: 2d2df5c04ceeaac31bdffb019ccd03c8 ===================== */ } /* * jdkMD5方法 */ public static void jdkMD5(){ try { //jdk提供的MessageDegest类 创建对象时候需要传入参数,可以是MD5, MD2 MessageDigest md = MessageDigest.getInstance("MD5"); byte[] result = md.digest(src.getBytes()); //因为digest方法返回的使一个byte数组,如果想输出字符串,必须将byte数组转化成16进制等,但是jdk并没有提供这样的方法,所以你可以选择自己写或者使用bc或cc提供的方法 //现在我们借助cc提供的方法 //输出32位16进制数 System.out.println("信息摘要之后的src: "+Hex.encodeHexString(result)); } catch (Exception e) { e.printStackTrace(); } } /* * jdkMD2信息摘要 */ public static void jdkMD2(){ try { //jdk提供的MessageDegest类 创建对象时候需要传入参数,可以是MD5, MD2 MessageDigest md = MessageDigest.getInstance("MD2"); byte[] result = md.digest(src.getBytes()); //因为digest方法返回的使一个byte数组,如果想输出字符串,必须将byte数组转化成16进制等,但是jdk并没有提供这样的方法,所以你可以选择自己写或者使用bc或cc提供的方法 //现在我们借助cc提供的方法 //输出32位16进制数 System.out.println("信息摘要之后的src: "+Hex.encodeHexString(result)); } catch (Exception e) { e.printStackTrace(); } } //bc实现MD4 public static void bcMD4(){ //Digest是一个借口,MD4Degist仅仅是一个实现类 Digest digest = new MD4Digest(); //进行摘要 digest.update(src.getBytes(), 0 , src.getBytes().length); //获取算法摘要出来的长度 byte[] result = new byte[digest.getDigestSize()]; //摘要的输出到变量里 digest.doFinal(result, 0); //进行转换输出 System.out.println("信息摘要之后的src: "+Hex.encodeHexString(result)); } /* * bc实现MD5 * 跟bc实现MD4相似,在此不再加注释 */ public static void bcMD5(){ Digest digest = new MD5Digest(); digest.update(src.getBytes(), 0, src.getBytes().length); byte[] result = new byte[digest.getDigestSize()]; digest.doFinal(result, 0); System.out.println("信息摘要之后的src: "+Hex.encodeHexString(result)); } /* * cc对MD5的实现 */ public static void ccMD5(){ //说实话.CC提供的DegistUtils工具类对信息摘要的实现真的是简单至极 String result = DigestUtils.md5Hex(src.getBytes()); System.out.println("信息摘要之后的src: "+result); } /* * cc对MD2的实现 */ public static void ccMD2(){ //说实话.CC提供的DegistUtils工具类对信息摘要的实现真的是简单至极 //但是CC做了个偷工减料的地方,CC仅仅是对jdk中MessageDegist的简单包装,所以CC中支持md4的实现 String result = DigestUtils.md2Hex(src.getBytes()); System.out.println("信息摘要之后的src: "+result); } }
SUT-GC/java_GC
screte/src/secret/MDTest.java
1,518
//运行结果
line_comment
zh-cn
package secret; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import org.apache.commons.codec.binary.Hex; import org.apache.commons.codec.digest.DigestUtils; import org.bouncycastle.crypto.Digest; import org.bouncycastle.crypto.digests.MD4Digest; import org.bouncycastle.crypto.digests.MD5Digest; public class MDTest { public static String src = "i am gc MD"; public static void main(String[] args) { System.out.println("=====jdk提供的MD5====="); jdkMD5(); System.out.println("====================="); System.out.println("=====jdk提供的MD2====="); jdkMD2(); System.out.println("====================="); System.out.println("=====BC提供的MD4====="); bcMD4(); System.out.println("====================="); System.out.println("=====BC提供的MD5====="); bcMD5(); System.out.println("====================="); System.out.println("=====CC提供的MD5====="); ccMD5(); System.out.println("====================="); System.out.println("=====CC提供的MD2====="); ccMD2(); System.out.println("====================="); //运行 <SUF> /*=====jdk提供的MD5===== 信息摘要之后的src: 8a63f68d49d7acfa716602e9ab620394 ===================== =====jdk提供的MD2===== 信息摘要之后的src: 2d2df5c04ceeaac31bdffb019ccd03c8 ===================== =====BC提供的MD4===== 信息摘要之后的src: 5ff5d77df559660ed4ff19ac2f5e2e2a ===================== =====BC提供的MD5===== 信息摘要之后的src: 8a63f68d49d7acfa716602e9ab620394 ===================== =====CC提供的MD5===== 信息摘要之后的src: 8a63f68d49d7acfa716602e9ab620394 ===================== =====CC提供的MD2===== 信息摘要之后的src: 2d2df5c04ceeaac31bdffb019ccd03c8 ===================== */ } /* * jdkMD5方法 */ public static void jdkMD5(){ try { //jdk提供的MessageDegest类 创建对象时候需要传入参数,可以是MD5, MD2 MessageDigest md = MessageDigest.getInstance("MD5"); byte[] result = md.digest(src.getBytes()); //因为digest方法返回的使一个byte数组,如果想输出字符串,必须将byte数组转化成16进制等,但是jdk并没有提供这样的方法,所以你可以选择自己写或者使用bc或cc提供的方法 //现在我们借助cc提供的方法 //输出32位16进制数 System.out.println("信息摘要之后的src: "+Hex.encodeHexString(result)); } catch (Exception e) { e.printStackTrace(); } } /* * jdkMD2信息摘要 */ public static void jdkMD2(){ try { //jdk提供的MessageDegest类 创建对象时候需要传入参数,可以是MD5, MD2 MessageDigest md = MessageDigest.getInstance("MD2"); byte[] result = md.digest(src.getBytes()); //因为digest方法返回的使一个byte数组,如果想输出字符串,必须将byte数组转化成16进制等,但是jdk并没有提供这样的方法,所以你可以选择自己写或者使用bc或cc提供的方法 //现在我们借助cc提供的方法 //输出32位16进制数 System.out.println("信息摘要之后的src: "+Hex.encodeHexString(result)); } catch (Exception e) { e.printStackTrace(); } } //bc实现MD4 public static void bcMD4(){ //Digest是一个借口,MD4Degist仅仅是一个实现类 Digest digest = new MD4Digest(); //进行摘要 digest.update(src.getBytes(), 0 , src.getBytes().length); //获取算法摘要出来的长度 byte[] result = new byte[digest.getDigestSize()]; //摘要的输出到变量里 digest.doFinal(result, 0); //进行转换输出 System.out.println("信息摘要之后的src: "+Hex.encodeHexString(result)); } /* * bc实现MD5 * 跟bc实现MD4相似,在此不再加注释 */ public static void bcMD5(){ Digest digest = new MD5Digest(); digest.update(src.getBytes(), 0, src.getBytes().length); byte[] result = new byte[digest.getDigestSize()]; digest.doFinal(result, 0); System.out.println("信息摘要之后的src: "+Hex.encodeHexString(result)); } /* * cc对MD5的实现 */ public static void ccMD5(){ //说实话.CC提供的DegistUtils工具类对信息摘要的实现真的是简单至极 String result = DigestUtils.md5Hex(src.getBytes()); System.out.println("信息摘要之后的src: "+result); } /* * cc对MD2的实现 */ public static void ccMD2(){ //说实话.CC提供的DegistUtils工具类对信息摘要的实现真的是简单至极 //但是CC做了个偷工减料的地方,CC仅仅是对jdk中MessageDegist的简单包装,所以CC中支持md4的实现 String result = DigestUtils.md2Hex(src.getBytes()); System.out.println("信息摘要之后的src: "+result); } }
false
1,311
3
1,518
3
1,443
3
1,518
3
2,068
5
false
false
false
false
false
true
18719_0
import java.util.LinkedList; import java.util.Scanner; public class Main { public static void main(String[] args){ Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int m = sc.nextInt(); LinkedList<Integer> linkedList = new LinkedList<>(); // 队列 for(int i = 0;i < n;i++) linkedList.add(i+1); int[] point = new int[n+1]; // 学生所在队列的位置 for(int i = 1;i < n+1;i++) point[i] = i-1; for(int i =0;i < m;i++){ int num = sc.nextInt(); int dis = sc.nextInt(); int temp = linkedList.remove(point[num]); linkedList.add(point[num]+dis, temp); int p = point[num]; if(dis > 0) for(int j = p;j < p+dis;j++) point[linkedList.get(j)]--; else for(int j = p;j > p+dis;j--) point[linkedList.get(j)]++; point[num] = p+dis; } for(int i = 0;i < linkedList.size();i++) System.out.print(linkedList.get(i) + " "); System.out.println(); sc.close(); } }
SZU999/JAVA-
exp1.java
339
// 学生所在队列的位置
line_comment
zh-cn
import java.util.LinkedList; import java.util.Scanner; public class Main { public static void main(String[] args){ Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int m = sc.nextInt(); LinkedList<Integer> linkedList = new LinkedList<>(); // 队列 for(int i = 0;i < n;i++) linkedList.add(i+1); int[] point = new int[n+1]; // 学生 <SUF> for(int i = 1;i < n+1;i++) point[i] = i-1; for(int i =0;i < m;i++){ int num = sc.nextInt(); int dis = sc.nextInt(); int temp = linkedList.remove(point[num]); linkedList.add(point[num]+dis, temp); int p = point[num]; if(dis > 0) for(int j = p;j < p+dis;j++) point[linkedList.get(j)]--; else for(int j = p;j > p+dis;j--) point[linkedList.get(j)]++; point[num] = p+dis; } for(int i = 0;i < linkedList.size();i++) System.out.print(linkedList.get(i) + " "); System.out.println(); sc.close(); } }
false
286
8
339
7
360
5
339
7
397
13
false
false
false
false
false
true
37657_15
import java.util.Arrays; /** * * LeetCode Solution对象 ,提供所有solution 方法 * @author wicloud * @date 2016-4-24 */ public class Solution { /** * 9. Palindrome Number * Determine whether an integer is a palindrome. Do this without extra space. * @param x * @return * * Your runtime beats 94.16% of javasubmissions. * 11506 / 11506 test cases passed. * Runtime: 10 ms */ public boolean isPalindrome(int x) { if (x < 0) { return false; } int a = x / 10; int b = x % 10; if (a == 0) { // 0--9 return true; } if (b == 0) {//0 结尾的 return false; } while (a - b > 0) { // a 越来越小,b越来越大 b = b * 10 + a % 10; a /= 10; } if (b - a > 0) { // 奇数个数 b /= 10; } return a == b; } /** * 8. String to Integer (atoi) * Implement atoi to convert a string to an integer. * @param str * @return * * * * Runtime: 4 ms 1047 / 1047 test cases passed * Your runtime beats 35.97% of javasubmissions */ public int myAtoi(String str) { if (null == str) { return 0; } str = str.trim(); boolean isPosivit = true; if (str.startsWith("-")) { str = str.substring(1); isPosivit = false; } else if (str.startsWith("+")) { str = str.substring(1); } if ("".equals(str)) { return 0; } short i = 0; char c = '0'; long l = 0; while (i < str.length()) { c = str.charAt(i); if (c >= '0' && c <= '9') { if (isPosivit) { l = l * 10 + (c - '0'); //正数 } else { l = l * 10 + (c - '0') * (-1);//负数 } if (l > Integer.MAX_VALUE) { return Integer.MAX_VALUE; } else if (l < Integer.MIN_VALUE) { return Integer.MIN_VALUE; } i++; } else { break; } } return (int) l; } /** * 7. Reverse Integer * @param x * @return * * Your runtime beats 45.49% of javasubmissions * Runtime: 2 ms */ public int reverse(int x) { long res = 0; for (; x != 0; x /= 10) { res = res * 10 + x % 10; } return res > Integer.MAX_VALUE || res < Integer.MIN_VALUE ? 0 : (int) res; } /** * 6. ZigZag Conversion * The string "PAYPALISHIRING" is written in a zigzag pattern on a given * number of rows like this: (you may want to display this pattern in a fixed font for better legibility) * 写 w * @param s * @param numRows * @return * 1158 / 1158 test cases passed. Runtime: 14 ms Your runtime beats 40.21% of javasubmissions */ public String convert(String s, int numRows) { if (1 == numRows) { return s; } int len = s.length(); StringBuffer[] arrsBuffers = new StringBuffer[numRows]; int pos = 0, row = 0; boolean add = true; while (pos < len) { // System.out.println("row= " + row + " pos = " + pos); if (arrsBuffers[row] == null) { arrsBuffers[row] = new StringBuffer(); } arrsBuffers[row].append(s.charAt(pos)); pos++; if (add) { if (row == numRows - 1) { row--; add = false; continue; } row++; } else { if (row == 0) { row++; add = true; continue; } row--; } } StringBuffer rs = new StringBuffer(); for (int i = 0; i < numRows; i++) { if (arrsBuffers[i] == null) { break; } rs.append(arrsBuffers[i]); } return rs.toString(); } /** * * 2. Add Two Numbers Total Accepted: 138344 Total Submissions: 602371 Difficulty: Medium * * You are given two linked lists representing two non-negative numbers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list. * Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) * Output: 7 -> 0 -> 8 * * @param l1 * @param l2 * @return */ public ListNode addTwoNumbers(ListNode l1, ListNode l2) { int up = 0; ListNode res = l1; int val = 0; while (null != l1) { val = (l1.val + l2.val + up) % 10; up = (l1.val + l2.val + up) / 10; l1.val = val; if (null == l1.next) { //指向l2 l1.next = l2.next; if (l1.next == null && up > 0) { l1.next = new ListNode(up); break; } l1 = l1.next; l2.next = null; l2.val = 0; continue; } if (null == l2.next) { l1 = l1.next; l2.val = 0; } else { l1 = l1.next; l2 = l2.next; } } return res; } // Definition for singly-linked list. public class ListNode { int val; ListNode next; ListNode(int x) { val = x; } } /** * * 1. Two Sum O(n*n) O(1) -.>建议使用hashMap * * Given an array of integers, return indices of the two numbers such that they add up to a specific target. * You may assume that each input would have exactly one solution. * @author wicloud * @date 2016-4-24 */ public int[] twoSum(int[] nums, int target) { for (int i = 0; i < nums.length - 1; i++) { for (int j = i + 1; j < nums.length; j++) { if (nums[i] + nums[j] == target) { return new int[] { i, j }; } } } return new int[] { -1, -1 }; } /** * 16. 3Sum Closest * * Closest Given an array S of n integers, find three integers in S such that the sum is closest to a given * number, target. Return the sum of the three integers. You may assume that each input would have exactly one * solution. * * @param nums * @param target * @return * * */ public int threeSumClosest(int[] nums, int target) { //超时 算法有问题 Arrays.sort(nums); int len = nums.length; int sumClosest = nums[0] + nums[1] + nums[2]; int i = 0, j, k; for (; i < len - 2; i++) { // 第一个数 越加越大了。 for (j = i + 1; j < len - 1; j++) {// 第二个数 for (k = j + 1; k < len; k++) {// 第三个数 int sum = nums[i] + nums[j] + nums[k]; if (Math.abs(sumClosest - target) > Math.abs(sum - target)) { sumClosest = sum; } if (sum - target >= 0) { break; } } } } return sumClosest; } /** * 344 Reverse String 59.9% Easy * @param s * @return */ public String reverseString(String s) { return new StringBuffer(s).reverse().toString(); } /** * * 345 Reverse Vowels of a String 37.5% Easy * @param s * @return */ public String reverseVowels(String s) { char[] sArr = s.toCharArray(); int i = 0; int j = sArr.length - 1; for (; i < j; i++) { if (isVowel(sArr[i])) { int pos = decreaseJ(i, sArr, j); if (pos > i) { char temp = sArr[i]; sArr[i] = sArr[pos]; sArr[pos] = temp; j = pos - 1; } } } return new String(sArr); } public int decreaseJ(int i, char[] chars, int j) { for (; j > i; j--) { if (isVowel(chars[j])) { return j; } } return i; } public boolean isVowel(char c) { return c == 'A' || c == 'a' || c == 'E' || c == 'e' || c == 'i' || c == 'I' || c == 'o' || c == 'O' || c == 'u' || c == 'U'; } }
SZUST/AlphaGo
Team/wicloud/LeetCodeSolution.java
2,706
//超时 算法有问题
line_comment
zh-cn
import java.util.Arrays; /** * * LeetCode Solution对象 ,提供所有solution 方法 * @author wicloud * @date 2016-4-24 */ public class Solution { /** * 9. Palindrome Number * Determine whether an integer is a palindrome. Do this without extra space. * @param x * @return * * Your runtime beats 94.16% of javasubmissions. * 11506 / 11506 test cases passed. * Runtime: 10 ms */ public boolean isPalindrome(int x) { if (x < 0) { return false; } int a = x / 10; int b = x % 10; if (a == 0) { // 0--9 return true; } if (b == 0) {//0 结尾的 return false; } while (a - b > 0) { // a 越来越小,b越来越大 b = b * 10 + a % 10; a /= 10; } if (b - a > 0) { // 奇数个数 b /= 10; } return a == b; } /** * 8. String to Integer (atoi) * Implement atoi to convert a string to an integer. * @param str * @return * * * * Runtime: 4 ms 1047 / 1047 test cases passed * Your runtime beats 35.97% of javasubmissions */ public int myAtoi(String str) { if (null == str) { return 0; } str = str.trim(); boolean isPosivit = true; if (str.startsWith("-")) { str = str.substring(1); isPosivit = false; } else if (str.startsWith("+")) { str = str.substring(1); } if ("".equals(str)) { return 0; } short i = 0; char c = '0'; long l = 0; while (i < str.length()) { c = str.charAt(i); if (c >= '0' && c <= '9') { if (isPosivit) { l = l * 10 + (c - '0'); //正数 } else { l = l * 10 + (c - '0') * (-1);//负数 } if (l > Integer.MAX_VALUE) { return Integer.MAX_VALUE; } else if (l < Integer.MIN_VALUE) { return Integer.MIN_VALUE; } i++; } else { break; } } return (int) l; } /** * 7. Reverse Integer * @param x * @return * * Your runtime beats 45.49% of javasubmissions * Runtime: 2 ms */ public int reverse(int x) { long res = 0; for (; x != 0; x /= 10) { res = res * 10 + x % 10; } return res > Integer.MAX_VALUE || res < Integer.MIN_VALUE ? 0 : (int) res; } /** * 6. ZigZag Conversion * The string "PAYPALISHIRING" is written in a zigzag pattern on a given * number of rows like this: (you may want to display this pattern in a fixed font for better legibility) * 写 w * @param s * @param numRows * @return * 1158 / 1158 test cases passed. Runtime: 14 ms Your runtime beats 40.21% of javasubmissions */ public String convert(String s, int numRows) { if (1 == numRows) { return s; } int len = s.length(); StringBuffer[] arrsBuffers = new StringBuffer[numRows]; int pos = 0, row = 0; boolean add = true; while (pos < len) { // System.out.println("row= " + row + " pos = " + pos); if (arrsBuffers[row] == null) { arrsBuffers[row] = new StringBuffer(); } arrsBuffers[row].append(s.charAt(pos)); pos++; if (add) { if (row == numRows - 1) { row--; add = false; continue; } row++; } else { if (row == 0) { row++; add = true; continue; } row--; } } StringBuffer rs = new StringBuffer(); for (int i = 0; i < numRows; i++) { if (arrsBuffers[i] == null) { break; } rs.append(arrsBuffers[i]); } return rs.toString(); } /** * * 2. Add Two Numbers Total Accepted: 138344 Total Submissions: 602371 Difficulty: Medium * * You are given two linked lists representing two non-negative numbers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list. * Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) * Output: 7 -> 0 -> 8 * * @param l1 * @param l2 * @return */ public ListNode addTwoNumbers(ListNode l1, ListNode l2) { int up = 0; ListNode res = l1; int val = 0; while (null != l1) { val = (l1.val + l2.val + up) % 10; up = (l1.val + l2.val + up) / 10; l1.val = val; if (null == l1.next) { //指向l2 l1.next = l2.next; if (l1.next == null && up > 0) { l1.next = new ListNode(up); break; } l1 = l1.next; l2.next = null; l2.val = 0; continue; } if (null == l2.next) { l1 = l1.next; l2.val = 0; } else { l1 = l1.next; l2 = l2.next; } } return res; } // Definition for singly-linked list. public class ListNode { int val; ListNode next; ListNode(int x) { val = x; } } /** * * 1. Two Sum O(n*n) O(1) -.>建议使用hashMap * * Given an array of integers, return indices of the two numbers such that they add up to a specific target. * You may assume that each input would have exactly one solution. * @author wicloud * @date 2016-4-24 */ public int[] twoSum(int[] nums, int target) { for (int i = 0; i < nums.length - 1; i++) { for (int j = i + 1; j < nums.length; j++) { if (nums[i] + nums[j] == target) { return new int[] { i, j }; } } } return new int[] { -1, -1 }; } /** * 16. 3Sum Closest * * Closest Given an array S of n integers, find three integers in S such that the sum is closest to a given * number, target. Return the sum of the three integers. You may assume that each input would have exactly one * solution. * * @param nums * @param target * @return * * */ public int threeSumClosest(int[] nums, int target) { //超时 <SUF> Arrays.sort(nums); int len = nums.length; int sumClosest = nums[0] + nums[1] + nums[2]; int i = 0, j, k; for (; i < len - 2; i++) { // 第一个数 越加越大了。 for (j = i + 1; j < len - 1; j++) {// 第二个数 for (k = j + 1; k < len; k++) {// 第三个数 int sum = nums[i] + nums[j] + nums[k]; if (Math.abs(sumClosest - target) > Math.abs(sum - target)) { sumClosest = sum; } if (sum - target >= 0) { break; } } } } return sumClosest; } /** * 344 Reverse String 59.9% Easy * @param s * @return */ public String reverseString(String s) { return new StringBuffer(s).reverse().toString(); } /** * * 345 Reverse Vowels of a String 37.5% Easy * @param s * @return */ public String reverseVowels(String s) { char[] sArr = s.toCharArray(); int i = 0; int j = sArr.length - 1; for (; i < j; i++) { if (isVowel(sArr[i])) { int pos = decreaseJ(i, sArr, j); if (pos > i) { char temp = sArr[i]; sArr[i] = sArr[pos]; sArr[pos] = temp; j = pos - 1; } } } return new String(sArr); } public int decreaseJ(int i, char[] chars, int j) { for (; j > i; j--) { if (isVowel(chars[j])) { return j; } } return i; } public boolean isVowel(char c) { return c == 'A' || c == 'a' || c == 'E' || c == 'e' || c == 'i' || c == 'I' || c == 'o' || c == 'O' || c == 'u' || c == 'U'; } }
false
2,464
8
2,706
6
2,734
5
2,706
6
3,309
9
false
false
false
false
false
true
33094_0
package com.zl.lqian.buffer; import java.nio.ByteBuffer; /** * 本质上,缓冲区是就是一个数组。所有的缓冲区都具有四个属性来提供关于其所包含的数组的信息 * * 1:容量(Capacity) 缓冲区能够容纳的数据元素的最大数量。容量在缓冲区创建时被设定,并且永远不能被改变。 * * 2: 上界(Limit) 缓冲区里的数据的总数,代表了当前缓冲区中一共有多少数据。 * * 3: 位置(Position) 下一个要被读或写的元素的位置。Position会自动由相应的 get( )和 put( )函数更新。 * * 4: 标记(Mark) 一个备忘位置。用于记录上一次读写的位置。一会儿,我会通过reset方法来说明这个属性的含义。 * */ public class BufferDemo { public static void main(String [] args){ /** * mark = -1, pos = 0, limit = 256, capacity = 256 */ ByteBuffer byteBuffer = ByteBuffer.allocate(256); byteBuffer.putInt(1); } }
SaberSola/LQian
LQian-jdk-read/src/main/java/com/zl/lqian/buffer/BufferDemo.java
297
/** * 本质上,缓冲区是就是一个数组。所有的缓冲区都具有四个属性来提供关于其所包含的数组的信息 * * 1:容量(Capacity) 缓冲区能够容纳的数据元素的最大数量。容量在缓冲区创建时被设定,并且永远不能被改变。 * * 2: 上界(Limit) 缓冲区里的数据的总数,代表了当前缓冲区中一共有多少数据。 * * 3: 位置(Position) 下一个要被读或写的元素的位置。Position会自动由相应的 get( )和 put( )函数更新。 * * 4: 标记(Mark) 一个备忘位置。用于记录上一次读写的位置。一会儿,我会通过reset方法来说明这个属性的含义。 * */
block_comment
zh-cn
package com.zl.lqian.buffer; import java.nio.ByteBuffer; /** * 本质上 <SUF>*/ public class BufferDemo { public static void main(String [] args){ /** * mark = -1, pos = 0, limit = 256, capacity = 256 */ ByteBuffer byteBuffer = ByteBuffer.allocate(256); byteBuffer.putInt(1); } }
false
253
172
297
203
271
174
297
203
423
307
false
false
false
false
false
true
53116_0
package com.mqd; import java.util.*; /** * 字符串括号问题 * ()()算一个字符串,)()(不算 */ public class StringBracket { static Random random = new Random(System.currentTimeMillis()); public static void main(String[] args) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < 100000000; i++) { if (random.nextInt(2) == 0) { sb.append("("); }else { sb.append(")"); } } String s = sb.toString(); long t1 = System.currentTimeMillis(); System.out.println(solution1(s)); //1842 long t2 = System.currentTimeMillis(); System.out.println("solution1: " + (t2-t1)); System.out.println(solution2(s)); //473 long t3 = System.currentTimeMillis(); System.out.println("solution2: " + (t3-t2)); } /** * 思路:栈 * @param str 字符串 * @return 最少需要添加一个括号 */ public static int solution1(String str) { Stack<Integer> stack = new Stack<>(); for (int i = 0; i < str.length(); i++) { if (str.charAt(i) == '(') { //如果是左括号直接入栈 stack.push(i); }else if (str.charAt(i) == ')') { if (stack.empty()) { //如果为空右括号直接入栈 stack.push(i); }else { if (str.charAt(stack.peek()) == '(') { stack.pop(); }else { stack.push(i); } } } } return stack.size(); } /** * 思路:count遇到左括号+1,遇到右括号-1 * @param str 字符串 * @return 最少需要添加一个括号 */ public static int solution2(String str) { int count = 0; int countR = 0; ArrayList<Character> characters = new ArrayList<>(str.length()); for (int i = 0; i < str.length(); i++) { if (str.charAt(i) == '(') { count++; }else if (str.charAt(i) == ')') { if (count == 0) countR++; else count--; } } return count + countR; } }
SaigyoujiNono/AlgorithmForJava
question/src/main/java/com/mqd/StringBracket.java
602
/** * 字符串括号问题 * ()()算一个字符串,)()(不算 */
block_comment
zh-cn
package com.mqd; import java.util.*; /** * 字符串 <SUF>*/ public class StringBracket { static Random random = new Random(System.currentTimeMillis()); public static void main(String[] args) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < 100000000; i++) { if (random.nextInt(2) == 0) { sb.append("("); }else { sb.append(")"); } } String s = sb.toString(); long t1 = System.currentTimeMillis(); System.out.println(solution1(s)); //1842 long t2 = System.currentTimeMillis(); System.out.println("solution1: " + (t2-t1)); System.out.println(solution2(s)); //473 long t3 = System.currentTimeMillis(); System.out.println("solution2: " + (t3-t2)); } /** * 思路:栈 * @param str 字符串 * @return 最少需要添加一个括号 */ public static int solution1(String str) { Stack<Integer> stack = new Stack<>(); for (int i = 0; i < str.length(); i++) { if (str.charAt(i) == '(') { //如果是左括号直接入栈 stack.push(i); }else if (str.charAt(i) == ')') { if (stack.empty()) { //如果为空右括号直接入栈 stack.push(i); }else { if (str.charAt(stack.peek()) == '(') { stack.pop(); }else { stack.push(i); } } } } return stack.size(); } /** * 思路:count遇到左括号+1,遇到右括号-1 * @param str 字符串 * @return 最少需要添加一个括号 */ public static int solution2(String str) { int count = 0; int countR = 0; ArrayList<Character> characters = new ArrayList<>(str.length()); for (int i = 0; i < str.length(); i++) { if (str.charAt(i) == '(') { count++; }else if (str.charAt(i) == ')') { if (count == 0) countR++; else count--; } } return count + countR; } }
false
546
21
602
22
653
21
602
22
744
31
false
false
false
false
false
true
53949_2
package net.saisimon.leetcode; import java.util.HashMap; import java.util.Map; /** * 383. Ransom Note * Given
 an 
arbitrary
 ransom
 note
 string 
and 
another 
string 
containing 
letters from
 all 
the 
magazines,
 * write 
a 
function 
that 
will 
return 
true 
if 
the 
ransom 
 note 
can 
be 
constructed 
from 
the 
magazines ; 
otherwise, 
it 
will 
return 
false. 

 * Each 
letter
 in
 the
 magazine 
string 
can
 only 
be
 used 
once
 in
 your 
ransom
 note. * canConstruct("a", "b") -> false * canConstruct("aa", "ab") -> false * canConstruct("aa", "aab") -> true * * @author Saisimon * */ public class RansomNote { // 使用 HashMap 存储 public boolean canConstructA(String ransomNote, String magazine) { char[] ransomChars = ransomNote.toCharArray(); char[] magazineChars = magazine.toCharArray(); Map<Character, Integer> map = new HashMap<>(); for (int i = 0; i < magazineChars.length; i++) { if (map.containsKey(magazineChars[i])) { map.put(magazineChars[i], map.get(magazineChars[i]) + 1); } else { map.put(magazineChars[i], 1); } } for (int i = 0; i < ransomChars.length; i++) { if (!map.containsKey(ransomChars[i])) { return false; } else { Integer count = map.get(ransomChars[i]); if (count == 0) { return false; } else { map.put(ransomChars[i], count - 1); } } } return true; } // 使用数组存储,更加高效 public boolean canConstructB(String ransomNote, String magazine) { int[] arr = new int[26]; for (int i = 0; i < magazine.length(); i++) { arr[magazine.charAt(i) - 'a']++; } for (int i = 0; i < ransomNote.length(); i++) { if (--arr[ransomNote.charAt(i) - 'a'] < 0) { return false; } } return true; } }
Saisimon/tip
program/java/leetcode/383/RansomNote.java
729
// 使用数组存储,更加高效
line_comment
zh-cn
package net.saisimon.leetcode; import java.util.HashMap; import java.util.Map; /** * 383. Ransom Note * Given
 an 
arbitrary
 ransom
 note
 string 
and 
another 
string 
containing 
letters from
 all 
the 
magazines,
 * write 
a 
function 
that 
will 
return 
true 
if 
the 
ransom 
 note 
can 
be 
constructed 
from 
the 
magazines ; 
otherwise, 
it 
will 
return 
false. 

 * Each 
letter
 in
 the
 magazine 
string 
can
 only 
be
 used 
once
 in
 your 
ransom
 note. * canConstruct("a", "b") -> false * canConstruct("aa", "ab") -> false * canConstruct("aa", "aab") -> true * * @author Saisimon * */ public class RansomNote { // 使用 HashMap 存储 public boolean canConstructA(String ransomNote, String magazine) { char[] ransomChars = ransomNote.toCharArray(); char[] magazineChars = magazine.toCharArray(); Map<Character, Integer> map = new HashMap<>(); for (int i = 0; i < magazineChars.length; i++) { if (map.containsKey(magazineChars[i])) { map.put(magazineChars[i], map.get(magazineChars[i]) + 1); } else { map.put(magazineChars[i], 1); } } for (int i = 0; i < ransomChars.length; i++) { if (!map.containsKey(ransomChars[i])) { return false; } else { Integer count = map.get(ransomChars[i]); if (count == 0) { return false; } else { map.put(ransomChars[i], count - 1); } } } return true; } // 使用 <SUF> public boolean canConstructB(String ransomNote, String magazine) { int[] arr = new int[26]; for (int i = 0; i < magazine.length(); i++) { arr[magazine.charAt(i) - 'a']++; } for (int i = 0; i < ransomNote.length(); i++) { if (--arr[ransomNote.charAt(i) - 'a'] < 0) { return false; } } return true; } }
false
634
7
729
9
656
7
729
9
897
15
false
false
false
false
false
true
65845_16
package com.oop.demo10; /* 类的内部成员之五:内部类 1. Java中允许将一个类A生命在另一个类B中,则类A就是内部类,类B成为外部类 2. 内部类的分类:成员内部类(静态、非静态) vs 局部内部类(方法内、代码块内、构造器内) 3. 成员内部类: 一方面,作为外部类的成员: >调用外部类的结构 >可以被static修饰 >可以被4种不同的权限修饰 另一方面,作为一个类: >类内可以定义属性、方法、构造器等 >可以被final修饰,表示此类不能被继承 >可以被abstract修饰,表示此类不能被实例化 4. 关注如下的3个问题 4.1 如何实例化成员内部类的对象 4.2 如何在成员内部类中区分调用外部类的结构 4.3 开发中局部内部类的使用 */ public class InnerClassTest { public static void main(String[] args) { //创建Brain实例(静态的成员内部类) Person.Brain brain = new Person.Brain(); brain.think(); //创建Stomach实例(非静态的成员内部类) Person p = new Person(); Person.Stomach stomach = p.new Stomach(); stomach.digest(); stomach.display("恰饭"); } //返回一个实现了Comparable接口的类的对象 public Comparable getComparable(){ //创建一个实现了Comparable接口的类:局部内部类 //方式一: // class MyComparable implements Comparable{ // // @Override // public int compareTo(Object o) { // return 0; // } // } // // return new MyComparable(); //方式二: return new Comparable() { @Override public int compareTo(Object o) { return 0; } }; } } class Person{ String name = "小明"; int age; public void eat(){ System.out.println("人吃饭"); } //静态成员内部类 static class Brain{ String name = "大脑"; int nerve; public void think(){ System.out.println("思考"); } } //非静态成员内部类 class Stomach{ String name = "胃"; public Stomach(){ } public void digest(){ Person.this.eat();//调用外部类的非静态结构 System.out.println("消化食物"); } public void display(String name){ System.out.println(name);//方法的形参 System.out.println(this.name);//内部类的属性 System.out.println(Person.this.name);//外部类的属性 } } public void method(){ //在局部内部类的方法中(比如show)如果调用局部内部类所在的方法(比如method)中的局部变量(比如num), //要求此变量声明为final int num = 10; //局部内部类 class AA{ public void show(){ // num = 20; System.out.println(num); } } } { //局部内部类 class BB{} } public Person(){ //局部内部类 class CC{} } }
Sakai1zumi/JavaTestCode
JavaBasic/src/com/oop/demo10/InnerClassTest.java
793
//内部类的属性
line_comment
zh-cn
package com.oop.demo10; /* 类的内部成员之五:内部类 1. Java中允许将一个类A生命在另一个类B中,则类A就是内部类,类B成为外部类 2. 内部类的分类:成员内部类(静态、非静态) vs 局部内部类(方法内、代码块内、构造器内) 3. 成员内部类: 一方面,作为外部类的成员: >调用外部类的结构 >可以被static修饰 >可以被4种不同的权限修饰 另一方面,作为一个类: >类内可以定义属性、方法、构造器等 >可以被final修饰,表示此类不能被继承 >可以被abstract修饰,表示此类不能被实例化 4. 关注如下的3个问题 4.1 如何实例化成员内部类的对象 4.2 如何在成员内部类中区分调用外部类的结构 4.3 开发中局部内部类的使用 */ public class InnerClassTest { public static void main(String[] args) { //创建Brain实例(静态的成员内部类) Person.Brain brain = new Person.Brain(); brain.think(); //创建Stomach实例(非静态的成员内部类) Person p = new Person(); Person.Stomach stomach = p.new Stomach(); stomach.digest(); stomach.display("恰饭"); } //返回一个实现了Comparable接口的类的对象 public Comparable getComparable(){ //创建一个实现了Comparable接口的类:局部内部类 //方式一: // class MyComparable implements Comparable{ // // @Override // public int compareTo(Object o) { // return 0; // } // } // // return new MyComparable(); //方式二: return new Comparable() { @Override public int compareTo(Object o) { return 0; } }; } } class Person{ String name = "小明"; int age; public void eat(){ System.out.println("人吃饭"); } //静态成员内部类 static class Brain{ String name = "大脑"; int nerve; public void think(){ System.out.println("思考"); } } //非静态成员内部类 class Stomach{ String name = "胃"; public Stomach(){ } public void digest(){ Person.this.eat();//调用外部类的非静态结构 System.out.println("消化食物"); } public void display(String name){ System.out.println(name);//方法的形参 System.out.println(this.name);//内部 <SUF> System.out.println(Person.this.name);//外部类的属性 } } public void method(){ //在局部内部类的方法中(比如show)如果调用局部内部类所在的方法(比如method)中的局部变量(比如num), //要求此变量声明为final int num = 10; //局部内部类 class AA{ public void show(){ // num = 20; System.out.println(num); } } } { //局部内部类 class BB{} } public Person(){ //局部内部类 class CC{} } }
false
735
5
793
4
815
4
793
4
1,105
7
false
false
false
false
false
true
63248_4
package com.example.qicheng.suanming.utils; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.util.Log; import com.example.qicheng.suanming.R; import com.example.qicheng.suanming.common.Constants; import com.example.qicheng.suanming.common.OkHttpManager; import com.example.qicheng.suanming.ui.MyApplication; import com.okhttplib.HttpInfo; import com.okhttplib.annotation.RequestType; import com.tencent.mm.opensdk.constants.Build; import com.tencent.mm.opensdk.modelmsg.SendMessageToWX; import com.tencent.mm.opensdk.modelmsg.WXMediaMessage; import com.tencent.mm.opensdk.modelmsg.WXWebpageObject; import com.tencent.mm.opensdk.openapi.IWXAPI; import org.json.JSONException; import org.json.JSONObject; import java.util.HashMap; import java.util.Map; /** * Created by Sakura on 2020-04-22 09:07 */ public class WxShareUtils { private static IWXAPI api; private static String url; private static String[] contentList = {"人生总有不如意,快来“星逸堂”免费算一卦吧!\n", "解读2020年财富,事业,健康,感情,机缘运势,寻找适合你的发展契机。", "一个人太累,想马上脱单。月老姻缘揭秘你的桃花正缘。", "什么是你财富自由上的最大阻碍?你的“八字”已经告诉你了。"}; public static void showWxShare(String shareUrl, int type) { type = (type > 2 || type < 1) ? 1 : type; if (shareUrl == null || shareUrl.equals("")) { ToastUtils.showShortToast("非法url"); return; } url = shareUrl; api = MyApplication.getInstance().getWxApi(); if (!api.isWXAppInstalled()) { ToastUtils.showShortToast("您还没有安装微信"); return; } wxShare(type); } public static void wxShare(int type) { if (api == null) { api = MyApplication.getInstance().getWxApi(); } boolean isSupportPyq = api.getWXAppSupportAPI() >= Build.TIMELINE_SUPPORTED_SDK_INT; if (!isSupportPyq && type == 2) { ToastUtils.showShortToast("请安装新版微信分享"); return; } // 初始化一个WXWebpageObject对象 WXWebpageObject webpageObject = new WXWebpageObject(); // 填写网页的url webpageObject.webpageUrl = url; // 用WXWebpageObject对象初始化一个WXMediaMessage对象 WXMediaMessage msg = new WXMediaMessage(webpageObject); // 填写网页标题、描述、位图 double db = Math.random(); int i; if (db < 0.25) { i = 0; } else if (db > 0.25 && db < 0.5) { i = 1; } else if (db > 0.5 && db < 0.75) { i = 2; } else { i = 3; } msg.title = "周易八卦,测算前世今生"; msg.description = contentList[i]; // 如果没有位图,可以传null,会显示默认的图片 Bitmap bitmap = BitmapFactory.decodeResource(MyApplication.getInstance().getResources(), R.mipmap.logo); msg.setThumbImage(bitmap); // 构造一个Req SendMessageToWX.Req req = new SendMessageToWX.Req(); // transaction用于唯一标识一个请求(可自定义) req.transaction = "webpage"; // 上文的WXMediaMessage对象 req.message = msg; if (type == 1) { //微信 req.scene = SendMessageToWX.Req.WXSceneSession; } else if (type == 2) { //朋友圈 req.scene = SendMessageToWX.Req.WXSceneTimeline; } // 向微信发送请求 api.sendReq(req); //调用成功的方法 setData2Server(); } private static void setData2Server() { Map map = new HashMap(); OkHttpManager.request(Constants.getApi.ADDUSERSHARE, RequestType.POST, map, new OkHttpManager.RequestListener() { @Override public void Success(HttpInfo info) { Log.d("info---->>", info.getRetDetail()); try { JSONObject jsonObject = new JSONObject(info.getRetDetail()); boolean code = jsonObject.getBoolean("code"); String msg = jsonObject.getString("msg"); } catch (JSONException e) { e.printStackTrace(); } } @Override public void Fail(HttpInfo info) { Log.d("info---->>", info.toString()); String result = info.getRetDetail(); ToastUtils.showShortToast(result); } }); } }
SakuraTCuu/zhouyi
app/src/main/java/com/example/qicheng/suanming/utils/WxShareUtils.java
1,257
// 填写网页标题、描述、位图
line_comment
zh-cn
package com.example.qicheng.suanming.utils; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.util.Log; import com.example.qicheng.suanming.R; import com.example.qicheng.suanming.common.Constants; import com.example.qicheng.suanming.common.OkHttpManager; import com.example.qicheng.suanming.ui.MyApplication; import com.okhttplib.HttpInfo; import com.okhttplib.annotation.RequestType; import com.tencent.mm.opensdk.constants.Build; import com.tencent.mm.opensdk.modelmsg.SendMessageToWX; import com.tencent.mm.opensdk.modelmsg.WXMediaMessage; import com.tencent.mm.opensdk.modelmsg.WXWebpageObject; import com.tencent.mm.opensdk.openapi.IWXAPI; import org.json.JSONException; import org.json.JSONObject; import java.util.HashMap; import java.util.Map; /** * Created by Sakura on 2020-04-22 09:07 */ public class WxShareUtils { private static IWXAPI api; private static String url; private static String[] contentList = {"人生总有不如意,快来“星逸堂”免费算一卦吧!\n", "解读2020年财富,事业,健康,感情,机缘运势,寻找适合你的发展契机。", "一个人太累,想马上脱单。月老姻缘揭秘你的桃花正缘。", "什么是你财富自由上的最大阻碍?你的“八字”已经告诉你了。"}; public static void showWxShare(String shareUrl, int type) { type = (type > 2 || type < 1) ? 1 : type; if (shareUrl == null || shareUrl.equals("")) { ToastUtils.showShortToast("非法url"); return; } url = shareUrl; api = MyApplication.getInstance().getWxApi(); if (!api.isWXAppInstalled()) { ToastUtils.showShortToast("您还没有安装微信"); return; } wxShare(type); } public static void wxShare(int type) { if (api == null) { api = MyApplication.getInstance().getWxApi(); } boolean isSupportPyq = api.getWXAppSupportAPI() >= Build.TIMELINE_SUPPORTED_SDK_INT; if (!isSupportPyq && type == 2) { ToastUtils.showShortToast("请安装新版微信分享"); return; } // 初始化一个WXWebpageObject对象 WXWebpageObject webpageObject = new WXWebpageObject(); // 填写网页的url webpageObject.webpageUrl = url; // 用WXWebpageObject对象初始化一个WXMediaMessage对象 WXMediaMessage msg = new WXMediaMessage(webpageObject); // 填写 <SUF> double db = Math.random(); int i; if (db < 0.25) { i = 0; } else if (db > 0.25 && db < 0.5) { i = 1; } else if (db > 0.5 && db < 0.75) { i = 2; } else { i = 3; } msg.title = "周易八卦,测算前世今生"; msg.description = contentList[i]; // 如果没有位图,可以传null,会显示默认的图片 Bitmap bitmap = BitmapFactory.decodeResource(MyApplication.getInstance().getResources(), R.mipmap.logo); msg.setThumbImage(bitmap); // 构造一个Req SendMessageToWX.Req req = new SendMessageToWX.Req(); // transaction用于唯一标识一个请求(可自定义) req.transaction = "webpage"; // 上文的WXMediaMessage对象 req.message = msg; if (type == 1) { //微信 req.scene = SendMessageToWX.Req.WXSceneSession; } else if (type == 2) { //朋友圈 req.scene = SendMessageToWX.Req.WXSceneTimeline; } // 向微信发送请求 api.sendReq(req); //调用成功的方法 setData2Server(); } private static void setData2Server() { Map map = new HashMap(); OkHttpManager.request(Constants.getApi.ADDUSERSHARE, RequestType.POST, map, new OkHttpManager.RequestListener() { @Override public void Success(HttpInfo info) { Log.d("info---->>", info.getRetDetail()); try { JSONObject jsonObject = new JSONObject(info.getRetDetail()); boolean code = jsonObject.getBoolean("code"); String msg = jsonObject.getString("msg"); } catch (JSONException e) { e.printStackTrace(); } } @Override public void Fail(HttpInfo info) { Log.d("info---->>", info.toString()); String result = info.getRetDetail(); ToastUtils.showShortToast(result); } }); } }
false
1,072
12
1,257
11
1,285
10
1,257
11
1,555
20
false
false
false
false
false
true
45902_13
import java.util.HashMap; import java.util.Map; //模板 /* 滑动窗口算法框架 */ void slidingWindow(string s, string t) { Map<Character, Integer> need = new HashMap<>(); Map<Character, Integer> window = new HashMap<>(); for (char c : t.toCharArray()) need.put(c,need.getOrDefault(c,0)+1); int left = 0, right = 0; int valid = 0; while (right < s.size()) { // c 是将移入窗口的字符 char c = s.charAt(right); // 右移窗口 right++; // 进行窗口内数据的一系列更新 ... /*** debug 输出的位置 ***/ System.out.println("window: ["+left+","+ right+")"); /********************/ // 判断左侧窗口是否要收缩 while (window needs shrink) { // d 是将移出窗口的字符 char d = s[left]; // 左移窗口 left++; // 进行窗口内数据的一系列更新 ... } } } //题解 class Solution { public String minWindow(String s, String t) { //1.维护两个map记录窗口中的符合条件的字符以及need的字符 Map<Character,Integer> window = new HashMap<>(); Map<Character,Integer> need = new HashMap<>();//need中存储的是需要的字符以及需要的对应的数量 for(char c : t.toCharArray()) need.put(c,need.getOrDefault(c,0)+1); int left = 0,right = 0;//双指针 int count = 0;//count记录当前窗口中符合need要求的字符的数量,当count == need.size()时即可shrik窗口 int start = 0;//start表示符合最优解的substring的起始位序 int len = Integer.MAX_VALUE;//len用来记录最终窗口的长度,并且以len作比较,淘汰选出最小的substring的len //一次遍历找“可行解” while(right < s.length()){ //更新窗口 char c = s.charAt(right); right++;//窗口扩大 // window.put(c,window.getOrDefault(c,0)+1);其实并不需要将s中所有的都加入windowsmap,只需要将need中的加入即可 if(need.containsKey(c)){ window.put(c,window.getOrDefault(c,0)+1); if(need.get(c).equals(window.get(c))){ count++; } } //System.out.println****Debug位置 //shrink左边界,找符合条件的最优解 while(count == need.size()){ if(right - left < len){//不断“打擂”找满足条件的len最短值,并记录最短的子串的起始位序start len = right - left; start = left; } //更新窗口——这段代码逻辑几乎完全同上面的更新窗口 char d = s.charAt(left); left++;//窗口缩小 if(need.containsKey(d)){ //window.put(d,window.get(d)-1);——bug:若一进去就将window对应的键值缩小,就永远不会满足下面的if,while也会一直执行,知道left越界,因此,尽管和上面对窗口的处理几乎一样,但是这个处理的顺序还是很关键的!要细心! if(need.get(d).equals(window.get(d))){ count--; } window.put(d,window.get(d)-1); } } } return len == Integer.MAX_VALUE ? "" : s.substring(start,start+len); } }
Sakurato-acg/scj
main.java
904
//双指针
line_comment
zh-cn
import java.util.HashMap; import java.util.Map; //模板 /* 滑动窗口算法框架 */ void slidingWindow(string s, string t) { Map<Character, Integer> need = new HashMap<>(); Map<Character, Integer> window = new HashMap<>(); for (char c : t.toCharArray()) need.put(c,need.getOrDefault(c,0)+1); int left = 0, right = 0; int valid = 0; while (right < s.size()) { // c 是将移入窗口的字符 char c = s.charAt(right); // 右移窗口 right++; // 进行窗口内数据的一系列更新 ... /*** debug 输出的位置 ***/ System.out.println("window: ["+left+","+ right+")"); /********************/ // 判断左侧窗口是否要收缩 while (window needs shrink) { // d 是将移出窗口的字符 char d = s[left]; // 左移窗口 left++; // 进行窗口内数据的一系列更新 ... } } } //题解 class Solution { public String minWindow(String s, String t) { //1.维护两个map记录窗口中的符合条件的字符以及need的字符 Map<Character,Integer> window = new HashMap<>(); Map<Character,Integer> need = new HashMap<>();//need中存储的是需要的字符以及需要的对应的数量 for(char c : t.toCharArray()) need.put(c,need.getOrDefault(c,0)+1); int left = 0,right = 0;//双指 <SUF> int count = 0;//count记录当前窗口中符合need要求的字符的数量,当count == need.size()时即可shrik窗口 int start = 0;//start表示符合最优解的substring的起始位序 int len = Integer.MAX_VALUE;//len用来记录最终窗口的长度,并且以len作比较,淘汰选出最小的substring的len //一次遍历找“可行解” while(right < s.length()){ //更新窗口 char c = s.charAt(right); right++;//窗口扩大 // window.put(c,window.getOrDefault(c,0)+1);其实并不需要将s中所有的都加入windowsmap,只需要将need中的加入即可 if(need.containsKey(c)){ window.put(c,window.getOrDefault(c,0)+1); if(need.get(c).equals(window.get(c))){ count++; } } //System.out.println****Debug位置 //shrink左边界,找符合条件的最优解 while(count == need.size()){ if(right - left < len){//不断“打擂”找满足条件的len最短值,并记录最短的子串的起始位序start len = right - left; start = left; } //更新窗口——这段代码逻辑几乎完全同上面的更新窗口 char d = s.charAt(left); left++;//窗口缩小 if(need.containsKey(d)){ //window.put(d,window.get(d)-1);——bug:若一进去就将window对应的键值缩小,就永远不会满足下面的if,while也会一直执行,知道left越界,因此,尽管和上面对窗口的处理几乎一样,但是这个处理的顺序还是很关键的!要细心! if(need.get(d).equals(window.get(d))){ count--; } window.put(d,window.get(d)-1); } } } return len == Integer.MAX_VALUE ? "" : s.substring(start,start+len); } }
false
790
5
896
4
929
4
896
4
1,252
7
false
false
false
false
false
true
45464_1
package com.aionstar.game.model.engine.ai.event; /** * 该类用于声明所有的AI的子状态 * @author: saltman155 * @date: 2019/5/2 12:52 */ public enum AISubState { /**无*/ NONE, /**谈论*/ TALK, CAST, WALK_PATH, WALK_RANDOM, WALK_WAIT_GROUP, FREEZE }
Saltman155/AION-SERVER
server-game/src/main/java/com/aionstar/game/model/engine/ai/event/AISubState.java
122
/**谈论*/
block_comment
zh-cn
package com.aionstar.game.model.engine.ai.event; /** * 该类用于声明所有的AI的子状态 * @author: saltman155 * @date: 2019/5/2 12:52 */ public enum AISubState { /**无*/ NONE, /**谈论* <SUF>*/ TALK, CAST, WALK_PATH, WALK_RANDOM, WALK_WAIT_GROUP, FREEZE }
false
100
3
122
5
119
4
122
5
153
8
false
false
false
false
false
true
27895_3
package samoy.substr.minimumwindowsubstring; /** * @link <a href="https://leetcode.cn/problems/minimum-window-substring/description/?envType=study-plan-v2&envId=top-100-liked">最小覆盖子串</a> */ class Solution { // 主要方法:给定字符串s和t,返回s中包含t所有字符的最小子串,若无则返回"" public String minWindow(String s, String t) { // 将字符串s转为字符数组,便于索引访问 char[] sCharArray = s.toCharArray(); // 获取s的长度 int m = sCharArray.length; // 初始化答案子串的左右边界,初始设置为无效(-1, m) int ansLeft = -1; int ansRight = m; // 初始化左右指针 int left = 0; // 记录还需匹配的字符数量 int less = 0; // 分别创建大小为128的计数数组,用于记录s和t中字符出现的次数 int[] cntS = new int[128]; int[] cntT = new int[128]; // 预处理t中的字符计数,同时计算需匹配的字符种类数(less) for (char c : t.toCharArray()) { if (cntT[c]++ == 0) { less++; } } // 使用滑动窗口遍历s for (int right = 0; right < m; right++) { char c = sCharArray[right]; // 更新s中字符c的计数,并检查是否满足t的条件,是则减小需匹配字符数 if (++cntS[c] == cntT[c]) { less--; } // 当当前窗口满足包含t所有字符的条件时 while (less == 0) { // 检查并更新最小覆盖子串 if (right - left < ansRight - ansLeft) { ansLeft = left; ansRight = right; } // 左指针右移,缩小窗口,并还原左指针指向字符的计数 char x = sCharArray[left++]; if (cntS[x]-- == cntT[x]) { less++; // 如果移除的字符是t中需要的,需匹配字符数加回 } } } // 根据答案子串边界返回结果,若未找到则返回空字符串 return ansLeft < 0 ? "" : s.substring(ansLeft, ansRight + 1); } }
Samoy/top-100-liked
src/main/java/samoy/substr/minimumwindowsubstring/Solution.java
587
// 获取s的长度
line_comment
zh-cn
package samoy.substr.minimumwindowsubstring; /** * @link <a href="https://leetcode.cn/problems/minimum-window-substring/description/?envType=study-plan-v2&envId=top-100-liked">最小覆盖子串</a> */ class Solution { // 主要方法:给定字符串s和t,返回s中包含t所有字符的最小子串,若无则返回"" public String minWindow(String s, String t) { // 将字符串s转为字符数组,便于索引访问 char[] sCharArray = s.toCharArray(); // 获取 <SUF> int m = sCharArray.length; // 初始化答案子串的左右边界,初始设置为无效(-1, m) int ansLeft = -1; int ansRight = m; // 初始化左右指针 int left = 0; // 记录还需匹配的字符数量 int less = 0; // 分别创建大小为128的计数数组,用于记录s和t中字符出现的次数 int[] cntS = new int[128]; int[] cntT = new int[128]; // 预处理t中的字符计数,同时计算需匹配的字符种类数(less) for (char c : t.toCharArray()) { if (cntT[c]++ == 0) { less++; } } // 使用滑动窗口遍历s for (int right = 0; right < m; right++) { char c = sCharArray[right]; // 更新s中字符c的计数,并检查是否满足t的条件,是则减小需匹配字符数 if (++cntS[c] == cntT[c]) { less--; } // 当当前窗口满足包含t所有字符的条件时 while (less == 0) { // 检查并更新最小覆盖子串 if (right - left < ansRight - ansLeft) { ansLeft = left; ansRight = right; } // 左指针右移,缩小窗口,并还原左指针指向字符的计数 char x = sCharArray[left++]; if (cntS[x]-- == cntT[x]) { less++; // 如果移除的字符是t中需要的,需匹配字符数加回 } } } // 根据答案子串边界返回结果,若未找到则返回空字符串 return ansLeft < 0 ? "" : s.substring(ansLeft, ansRight + 1); } }
false
571
5
587
5
609
5
587
5
833
8
false
false
false
false
false
true
17475_16
package exp5; import java.io.*; import java.net.*; import java.util.*; public class Server{ static ServerSocket server = null; static Socket socket = null; static List<Socket> list = new ArrayList<Socket>(); // 存储客户端 public static void main(String[] args) { MultiChat multiChat = new MultiChat(); // 新建聊天系统界面 try { // 在服务器端对客户端开启文件传输的线程 ServerFileThread serverFileThread = new ServerFileThread(); serverFileThread.start(); server = new ServerSocket(8081); // 服务器端套接字(只能建立一次) // 等待连接并开启相应线程 while (true) { socket = server.accept(); // 等待连接 list.add(socket); // 添加当前客户端到列表 // 在服务器端对客户端开启相应的线程 ServerReadAndPrint readAndPrint = new ServerReadAndPrint(socket, multiChat); readAndPrint.start(); } } catch (IOException e1) { e1.printStackTrace(); // 出现异常则打印出异常的位置 } } } /** * 服务器端读写类线程 * 用于服务器端读取客户端的信息,并把信息发送给所有客户端 */ class ServerReadAndPrint extends Thread{ Socket nowSocket = null; MultiChat multiChat = null; BufferedReader in =null; PrintWriter out = null; // 构造函数 public ServerReadAndPrint(Socket s, MultiChat multiChat) { this.multiChat = multiChat; // 获取多人聊天系统界面 this.nowSocket = s; // 获取当前客户端 } public void run() { try { in = new BufferedReader(new InputStreamReader(nowSocket.getInputStream())); // 输入流 // 获取客户端信息并把信息发送给所有客户端 while (true) { String str = in.readLine(); // 发送给所有客户端 for(Socket socket: Server.list) { out = new PrintWriter(socket.getOutputStream()); // 对每个客户端新建相应的socket套接字 if(socket == nowSocket) { // 发送给当前客户端 out.println("(你)" + str); } else { // 发送给其它客户端 out.println(str); } out.flush(); // 清空out中的缓存 } // 调用自定义函数输出到图形界面 multiChat.setTextArea(str); } } catch (Exception e) { Server.list.remove(nowSocket); // 线程关闭,移除相应套接字 } } }
Samven7/multichat-system
src/exp5/Server.java
659
// 对每个客户端新建相应的socket套接字
line_comment
zh-cn
package exp5; import java.io.*; import java.net.*; import java.util.*; public class Server{ static ServerSocket server = null; static Socket socket = null; static List<Socket> list = new ArrayList<Socket>(); // 存储客户端 public static void main(String[] args) { MultiChat multiChat = new MultiChat(); // 新建聊天系统界面 try { // 在服务器端对客户端开启文件传输的线程 ServerFileThread serverFileThread = new ServerFileThread(); serverFileThread.start(); server = new ServerSocket(8081); // 服务器端套接字(只能建立一次) // 等待连接并开启相应线程 while (true) { socket = server.accept(); // 等待连接 list.add(socket); // 添加当前客户端到列表 // 在服务器端对客户端开启相应的线程 ServerReadAndPrint readAndPrint = new ServerReadAndPrint(socket, multiChat); readAndPrint.start(); } } catch (IOException e1) { e1.printStackTrace(); // 出现异常则打印出异常的位置 } } } /** * 服务器端读写类线程 * 用于服务器端读取客户端的信息,并把信息发送给所有客户端 */ class ServerReadAndPrint extends Thread{ Socket nowSocket = null; MultiChat multiChat = null; BufferedReader in =null; PrintWriter out = null; // 构造函数 public ServerReadAndPrint(Socket s, MultiChat multiChat) { this.multiChat = multiChat; // 获取多人聊天系统界面 this.nowSocket = s; // 获取当前客户端 } public void run() { try { in = new BufferedReader(new InputStreamReader(nowSocket.getInputStream())); // 输入流 // 获取客户端信息并把信息发送给所有客户端 while (true) { String str = in.readLine(); // 发送给所有客户端 for(Socket socket: Server.list) { out = new PrintWriter(socket.getOutputStream()); // 对每 <SUF> if(socket == nowSocket) { // 发送给当前客户端 out.println("(你)" + str); } else { // 发送给其它客户端 out.println(str); } out.flush(); // 清空out中的缓存 } // 调用自定义函数输出到图形界面 multiChat.setTextArea(str); } } catch (Exception e) { Server.list.remove(nowSocket); // 线程关闭,移除相应套接字 } } }
false
594
10
659
11
642
10
659
11
974
21
false
false
false
false
false
true
35021_0
import java.util.Random; import java.util.Scanner; /** * Author: Sangs * Date:2021.1.9 * Function:《算法》P134 1.4.34 * Questiion:热还是冷。你的目标是猜出1到N之间的一个秘密的整数。 * 每次猜完一个整数后,你会知道你猜测和这个秘密整数是否相等(若相等则游戏结束) * 不相等你会知道你的猜测相比上一次猜测距离该秘密整数是比较热(接近) * 还是比较冷(远离) */ public class Question1_4_34 { public static void main(String[] args) { System.out.print("输入随机数的最大值:"); Scanner sc = new Scanner(System.in); int N = sc.nextInt(); Random r = new Random(); int num = r.nextInt(N)+1; while(true){ System.out.print("输入你的猜测:"); int fi = sc.nextInt(); int dis = Math.abs(fi - num); if(dis == 0){ System.out.println("猜测正确,随机数为:" + num); break; }else{ System.out.print("再输一次:"); int t = sc.nextInt(); if(Math.abs(t - num) == 0){ System.out.println("猜测正确,随机数为:" + num); break; }else if(dis < Math.abs(t - num)) System.out.println("冷了"); else System.out.println("热了"); } } sc.close(); } }
Sangs3112/Algorithms
Unit1/Sub1.4/Question1_4_34.java
421
/** * Author: Sangs * Date:2021.1.9 * Function:《算法》P134 1.4.34 * Questiion:热还是冷。你的目标是猜出1到N之间的一个秘密的整数。 * 每次猜完一个整数后,你会知道你猜测和这个秘密整数是否相等(若相等则游戏结束) * 不相等你会知道你的猜测相比上一次猜测距离该秘密整数是比较热(接近) * 还是比较冷(远离) */
block_comment
zh-cn
import java.util.Random; import java.util.Scanner; /** * Aut <SUF>*/ public class Question1_4_34 { public static void main(String[] args) { System.out.print("输入随机数的最大值:"); Scanner sc = new Scanner(System.in); int N = sc.nextInt(); Random r = new Random(); int num = r.nextInt(N)+1; while(true){ System.out.print("输入你的猜测:"); int fi = sc.nextInt(); int dis = Math.abs(fi - num); if(dis == 0){ System.out.println("猜测正确,随机数为:" + num); break; }else{ System.out.print("再输一次:"); int t = sc.nextInt(); if(Math.abs(t - num) == 0){ System.out.println("猜测正确,随机数为:" + num); break; }else if(dis < Math.abs(t - num)) System.out.println("冷了"); else System.out.println("热了"); } } sc.close(); } }
false
349
127
421
149
414
124
421
149
543
212
false
false
false
false
false
true
19574_0
import java.util.ArrayList; /** * 小明很喜欢数学,有一天他在做数学作业时,要求计算出9~16的和,他马上就写出了正确答案是100。 * 但是他并不满足于此,他在想究竟有多少种连续的正数序列的和为100(至少包括两个数)。 * 没多久,他就得到另一组连续正数和为100的序列:18,19,20,21,22。 * 现在把问题交给你,你能不能也很快的找出所有和为S的连续正数序列? * <p> * 输出所有和为S的连续正数序列。序列内按照从小至大的顺序,序列间按照开始数字从小到大的顺序 * <p> * 时间限制:1秒 * 空间限制:32768K * * @author sunyue * @version 1.0 2017/5/1 11:31 */ public class Solution41 { /** * 初始化small=1,big=2; * small到big序列和小于sum,big++;大于sum,small++; * 当small增加到(1+sum)/2是停止 * 运行时间:39ms * 占用内存:654k */ public ArrayList<ArrayList<Integer>> FindContinuousSequence(int sum) { ArrayList<ArrayList<Integer>> res = new ArrayList<>(); if (sum <= 1) return res; int small = 1; int big = 2; while (small != (1 + sum) / 2) { int curSum = sumOfList(small, big); if (curSum == sum) { ArrayList<Integer> tmp = new ArrayList<>(); for (int i = small; i <= big; i++) { tmp.add(i); } res.add(tmp); small++; big++; } else if (curSum < sum) big++; else small++; } return res; } private int sumOfList(int lo, int hi) { int sum = 0; for (int i = lo; i <= hi; i++) { sum += i; } return sum; } }
SawyerSun/Algorithms-and-Data-Structures
sword-to-offer/src/main/java/Solution41.java
552
/** * 小明很喜欢数学,有一天他在做数学作业时,要求计算出9~16的和,他马上就写出了正确答案是100。 * 但是他并不满足于此,他在想究竟有多少种连续的正数序列的和为100(至少包括两个数)。 * 没多久,他就得到另一组连续正数和为100的序列:18,19,20,21,22。 * 现在把问题交给你,你能不能也很快的找出所有和为S的连续正数序列? * <p> * 输出所有和为S的连续正数序列。序列内按照从小至大的顺序,序列间按照开始数字从小到大的顺序 * <p> * 时间限制:1秒 * 空间限制:32768K * * @author sunyue * @version 1.0 2017/5/1 11:31 */
block_comment
zh-cn
import java.util.ArrayList; /** * 小明很 <SUF>*/ public class Solution41 { /** * 初始化small=1,big=2; * small到big序列和小于sum,big++;大于sum,small++; * 当small增加到(1+sum)/2是停止 * 运行时间:39ms * 占用内存:654k */ public ArrayList<ArrayList<Integer>> FindContinuousSequence(int sum) { ArrayList<ArrayList<Integer>> res = new ArrayList<>(); if (sum <= 1) return res; int small = 1; int big = 2; while (small != (1 + sum) / 2) { int curSum = sumOfList(small, big); if (curSum == sum) { ArrayList<Integer> tmp = new ArrayList<>(); for (int i = small; i <= big; i++) { tmp.add(i); } res.add(tmp); small++; big++; } else if (curSum < sum) big++; else small++; } return res; } private int sumOfList(int lo, int hi) { int sum = 0; for (int i = lo; i <= hi; i++) { sum += i; } return sum; } }
false
501
220
552
256
546
219
552
256
690
339
false
false
false
false
false
true
11003_1
package com.scienjus.config; /** * 常量 * @author ScienJus * @date 2015/7/31. */ public class Constants { /** * 存储当前登录用户id的字段名 */ public static final String CURRENT_USER_ID = "CURRENT_USER_ID"; /** * token有效期(小时) */ public static final int TOKEN_EXPIRES_HOUR = 72; /** * 存放Authorization的header字段 */ public static final String AUTHORIZATION = "authorization"; }
ScienJus/spring-restful-authorization
src/main/java/com/scienjus/config/Constants.java
139
/** * 存储当前登录用户id的字段名 */
block_comment
zh-cn
package com.scienjus.config; /** * 常量 * @author ScienJus * @date 2015/7/31. */ public class Constants { /** * 存储当 <SUF>*/ public static final String CURRENT_USER_ID = "CURRENT_USER_ID"; /** * token有效期(小时) */ public static final int TOKEN_EXPIRES_HOUR = 72; /** * 存放Authorization的header字段 */ public static final String AUTHORIZATION = "authorization"; }
false
124
16
139
14
143
16
139
14
173
23
false
false
false
false
false
true
64381_2
package com.scoprion.utils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Created on 2017/9/19. */ public class IDWorker { private final static Logger logger = LoggerFactory.getLogger(IDWorker.class); private final long workerId; private final long epoch = 1403854494756L; // 时间起始标记点,作为基准,一般取系统的最近时间 private final long workerIdBits = 10L; // 机器标识位数 private final long maxWorkerId = -1L ^ -1L << this.workerIdBits; // 机器ID最大值: 1023 private long sequence = 0L; // 0,并发控制 private final long sequenceBits = 12L; //毫秒内自增位 private final long workerIdShift = this.sequenceBits; // 12 private final long timestampLeftShift = this.sequenceBits + this.workerIdBits;// 22 private final long sequenceMask = -1L ^ -1L << this.sequenceBits; // 4095,111111111111,12位 private long lastTimestamp = -1L; private IDWorker(long workerId) { if (workerId > this.maxWorkerId || workerId < 0) { throw new IllegalArgumentException( String.format("worker Id can't be greater than %d or less than 0", this.maxWorkerId)); } this.workerId = workerId; } public synchronized long nextId() throws Exception { long timestamp = this.timeGen(); if (this.lastTimestamp == timestamp) { // 如果上一个timestamp与新产生的相等,则sequence加一(0-4095循环); 对新的timestamp,sequence从0开始 this.sequence = this.sequence + 1 & this.sequenceMask; if (this.sequence == 0) { timestamp = this.tilNextMillis(this.lastTimestamp);// 重新生成timestamp } } else { this.sequence = 0; } if (timestamp < this.lastTimestamp) { logger.error(String.format("clock moved backwards.Refusing to generate id for %d milliseconds", (this.lastTimestamp - timestamp))); throw new Exception(String.format("clock moved backwards.Refusing to generate id for %d milliseconds", (this.lastTimestamp - timestamp))); } this.lastTimestamp = timestamp; return timestamp - this.epoch << this.timestampLeftShift | this.workerId << this.workerIdShift | this.sequence; } private static IDWorker flowIdWorker = new IDWorker(1); public static IDWorker getFlowIdWorkerInstance() { return flowIdWorker; } /** * 等待下一个毫秒的到来, 保证返回的毫秒数在参数lastTimestamp之后 */ private long tilNextMillis(long lastTimestamp) { long timestamp = this.timeGen(); while (timestamp <= lastTimestamp) { timestamp = this.timeGen(); } return timestamp; } /** * 获得系统当前毫秒数 */ private static long timeGen() { return System.currentTimeMillis(); } }
ScorpionTeam/mall
src/main/java/com/scoprion/utils/IDWorker.java
765
// 机器标识位数
line_comment
zh-cn
package com.scoprion.utils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Created on 2017/9/19. */ public class IDWorker { private final static Logger logger = LoggerFactory.getLogger(IDWorker.class); private final long workerId; private final long epoch = 1403854494756L; // 时间起始标记点,作为基准,一般取系统的最近时间 private final long workerIdBits = 10L; // 机器 <SUF> private final long maxWorkerId = -1L ^ -1L << this.workerIdBits; // 机器ID最大值: 1023 private long sequence = 0L; // 0,并发控制 private final long sequenceBits = 12L; //毫秒内自增位 private final long workerIdShift = this.sequenceBits; // 12 private final long timestampLeftShift = this.sequenceBits + this.workerIdBits;// 22 private final long sequenceMask = -1L ^ -1L << this.sequenceBits; // 4095,111111111111,12位 private long lastTimestamp = -1L; private IDWorker(long workerId) { if (workerId > this.maxWorkerId || workerId < 0) { throw new IllegalArgumentException( String.format("worker Id can't be greater than %d or less than 0", this.maxWorkerId)); } this.workerId = workerId; } public synchronized long nextId() throws Exception { long timestamp = this.timeGen(); if (this.lastTimestamp == timestamp) { // 如果上一个timestamp与新产生的相等,则sequence加一(0-4095循环); 对新的timestamp,sequence从0开始 this.sequence = this.sequence + 1 & this.sequenceMask; if (this.sequence == 0) { timestamp = this.tilNextMillis(this.lastTimestamp);// 重新生成timestamp } } else { this.sequence = 0; } if (timestamp < this.lastTimestamp) { logger.error(String.format("clock moved backwards.Refusing to generate id for %d milliseconds", (this.lastTimestamp - timestamp))); throw new Exception(String.format("clock moved backwards.Refusing to generate id for %d milliseconds", (this.lastTimestamp - timestamp))); } this.lastTimestamp = timestamp; return timestamp - this.epoch << this.timestampLeftShift | this.workerId << this.workerIdShift | this.sequence; } private static IDWorker flowIdWorker = new IDWorker(1); public static IDWorker getFlowIdWorkerInstance() { return flowIdWorker; } /** * 等待下一个毫秒的到来, 保证返回的毫秒数在参数lastTimestamp之后 */ private long tilNextMillis(long lastTimestamp) { long timestamp = this.timeGen(); while (timestamp <= lastTimestamp) { timestamp = this.timeGen(); } return timestamp; } /** * 获得系统当前毫秒数 */ private static long timeGen() { return System.currentTimeMillis(); } }
false
709
6
765
6
809
5
765
6
931
10
false
false
false
false
false
true
15973_0
package burp; import org.apache.commons.lang3.StringUtils; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; public class Re { // 手机号匹配 public static String Phone(String str){ ArrayList<String> phones = new ArrayList<>(); String is_number = "\\b\\d{11,}"; Matcher matcher = Pattern.compile(is_number).matcher(str); while (matcher.find()) { if (matcher.group().length() == 11) { String is_phone = "^(13[0-9]|14[5|7]|15[^4]|17[6-9]|18[0-9])\\d{8}$"; Matcher matcher2 = Pattern.compile(is_phone).matcher(matcher.group()); while (matcher2.find()) { phones.add(matcher2.group()); } } } // 去重 List<String> phones_rd = Re.removeDuplicate(phones); return StringUtils.strip(phones_rd.toString(),"[]"); } // 匹配地址(*) public static String Address(String str){ String address = new String(); String is_address ="(?:(北京|天津|上海|重庆|台湾|.+(省|自治区|特别行政区))(?:市)?.+(市|自治州).+(区|县|旗)?.+(?:(镇|乡|街道))?.+(?:(.+[村|社区|街道])).*)" + "|(?:(\\u5317\\u4eac|\\u5929\\u6d25|\\u4e0a\\u6d77|\\u91cd\\u5e86|\\u53f0\\u6e7e|.+(\\u7701|\\u81ea\\u6cbb\\u533a|\\u7279\\u522b\\u884c\\u653f\\u533a))(?:\\u5e02)?.+(\\u5e02|\\u81ea\\u6cbb\\u5dde).+(\\u533a|\\u53bf|\\u65d7)?.+(?:(\\u9547|\\u4e61|\\u8857\\u9053))?.+(?:(.+[\\u6751|\\u793e\\u533a|\\u8857\\u9053])).*)"; Matcher matcher = Pattern.compile(is_address).matcher(str); while (matcher.find()){ address+=matcher.group(); } return address; } //身份证匹配 public static String IdCard(String str){ ArrayList<String> id = new ArrayList<>(); String is_id = "\\b[1-9]\\d{5}(?:19|20)\\d\\d(?:0[1-9]|1[012])(?:0[1-9]|[12]\\d|3[01])\\d{3}(?:\\d|X|x)"; Matcher matcher = Pattern.compile(is_id).matcher(str); while (matcher.find()){ id.add(matcher.group()); } // 去重 List<String> id_rd = Re.removeDuplicate(id); return StringUtils.strip(id_rd.toString(),"[]"); } //特殊字段匹配 public static String Password(String str){ ArrayList<String> pwd = new ArrayList<>(); String is_pwd = "(?:\"pwd\"|\"password\":|pwd=|password=|config/api" + "|method: 'get'|method: 'post'|method: \"get\"|method: \"post\"" + "|service\\.httppost|service\\.httpget|\\$\\.ajax|http\\.get\\(\"|http\\.post\\(\"" + "rememberMe=delete|[A|a]ccess[K|k]ey|[A|a]ccess[T|t]oken|api_secret|app_secret|(ey[A-Za-z0-9_\\/+-]{34,}\\.[A-Za-z0-9._\\/+-]*))"; Matcher matcher = Pattern.compile(is_pwd).matcher(str); while (matcher.find()){ pwd.add(matcher.group()); } // 去重 List<String> pwd_rd = Re.removeDuplicate(pwd); return StringUtils.strip(pwd_rd.toString(),"[]"); } // ip地址匹配 public static String IP(String str){ ArrayList<String> ip = new ArrayList<>(); // String is_ip = "\\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\b"; String is_ip = "\\b(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[0]|[1-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\b"; Matcher matcher = Pattern.compile(is_ip).matcher(str); while (matcher.find()){ ip.add(matcher.group()); } // 去重 List<String> ip_rd = Re.removeDuplicate(ip); return StringUtils.strip(ip_rd.toString(),"[]"); } // 内网ip匹配 public static boolean in_ip(String str){ String in_ip = "\\b(?:(10\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}))|(?:172\\.(?:(?:1[6-9])|(?:2\\d)|(?:3[01]))\\.\\d{1,3}\\.\\d{1,3})|(?:192\\.168\\.\\d{1,3}\\.\\d{1,3})"; Matcher matcher = Pattern.compile(in_ip).matcher(str); if (matcher.find()){ return true; } return false; } //邮箱匹配 public static String Email(String str){ ArrayList<String> email = new ArrayList<>(); String is_email = "\\b[\\w-]+(?:\\.[\\w-]+)*@([\\w](?:[\\w-]*[\\w])?\\.)+(?:((?!png))((?!jpg))((?!jpeg))((?!gif))((?!ico))((?!html))((?!js))((?!css)))[A-Za-z]{2,6}"; Matcher matcher = Pattern.compile(is_email).matcher(str); while (matcher.find()){ email.add(matcher.group()); } // 去重 List<String> email_rd = Re.removeDuplicate(email); return StringUtils.strip(email_rd.toString(),"[]"); } // js路径匹配 public static String Path(String str){ ArrayList<String> path = new ArrayList<>(); String path1 = new String(); // String is_path = "[\"|'](?:(\\.)*/|/)[0-9a-zA-Z.]+(?:((/[\\w,\\?,-,_,.]*)+)|[\"|'])"; String is_path = "[\"|'](/[0-9a-zA-Z.]+(?:/[\\w,\\?,-,\\.,_]*?)+)[\"|']"; Matcher matcher = Pattern.compile(is_path).matcher(str); while (matcher.find()){ path.add(matcher.group()); } // 去重代码 List<String> path_rd = Re.removeDuplicate(path); for (String s : path_rd){ path1 += StringUtils.strip(s,"\"'")+'\n'; } // return StringUtils.strip(path1,"[]"); return path1; } public static String Url(String str){ ArrayList<String> url = new ArrayList<>(); String url1 = new String(); String is_url = "([\"|'](http|https):\\/\\/([\\w.]+\\/?)\\S*?[\"|'])"; Matcher matcher = Pattern.compile(is_url).matcher(str); while (matcher.find()){ url.add(matcher.group()); } // 去重代码 List<String> path_rd = Re.removeDuplicate(url); for (String s : path_rd){ url1 += StringUtils.strip(s,"\"'")+'\n'; } return url1; } // 判断javascript文件 public static boolean js (String headers,byte[] content){ if (headers.contains("/javascript")||headers.contains("/x-javascript") ){ if (Re.Path(new String(content)).length() != 0){ return true; } } return false; } // 去重代码 public static List<String> removeDuplicate (ArrayList<String> strings){ List<String> list2 = new ArrayList<String>(strings); list2 = list2.stream().distinct().collect(Collectors.toList()); return list2; } }
ScriptKid-Beta/Unexpected_information
src/main/java/burp/Re.java
2,205
// 手机号匹配
line_comment
zh-cn
package burp; import org.apache.commons.lang3.StringUtils; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; public class Re { // 手机 <SUF> public static String Phone(String str){ ArrayList<String> phones = new ArrayList<>(); String is_number = "\\b\\d{11,}"; Matcher matcher = Pattern.compile(is_number).matcher(str); while (matcher.find()) { if (matcher.group().length() == 11) { String is_phone = "^(13[0-9]|14[5|7]|15[^4]|17[6-9]|18[0-9])\\d{8}$"; Matcher matcher2 = Pattern.compile(is_phone).matcher(matcher.group()); while (matcher2.find()) { phones.add(matcher2.group()); } } } // 去重 List<String> phones_rd = Re.removeDuplicate(phones); return StringUtils.strip(phones_rd.toString(),"[]"); } // 匹配地址(*) public static String Address(String str){ String address = new String(); String is_address ="(?:(北京|天津|上海|重庆|台湾|.+(省|自治区|特别行政区))(?:市)?.+(市|自治州).+(区|县|旗)?.+(?:(镇|乡|街道))?.+(?:(.+[村|社区|街道])).*)" + "|(?:(\\u5317\\u4eac|\\u5929\\u6d25|\\u4e0a\\u6d77|\\u91cd\\u5e86|\\u53f0\\u6e7e|.+(\\u7701|\\u81ea\\u6cbb\\u533a|\\u7279\\u522b\\u884c\\u653f\\u533a))(?:\\u5e02)?.+(\\u5e02|\\u81ea\\u6cbb\\u5dde).+(\\u533a|\\u53bf|\\u65d7)?.+(?:(\\u9547|\\u4e61|\\u8857\\u9053))?.+(?:(.+[\\u6751|\\u793e\\u533a|\\u8857\\u9053])).*)"; Matcher matcher = Pattern.compile(is_address).matcher(str); while (matcher.find()){ address+=matcher.group(); } return address; } //身份证匹配 public static String IdCard(String str){ ArrayList<String> id = new ArrayList<>(); String is_id = "\\b[1-9]\\d{5}(?:19|20)\\d\\d(?:0[1-9]|1[012])(?:0[1-9]|[12]\\d|3[01])\\d{3}(?:\\d|X|x)"; Matcher matcher = Pattern.compile(is_id).matcher(str); while (matcher.find()){ id.add(matcher.group()); } // 去重 List<String> id_rd = Re.removeDuplicate(id); return StringUtils.strip(id_rd.toString(),"[]"); } //特殊字段匹配 public static String Password(String str){ ArrayList<String> pwd = new ArrayList<>(); String is_pwd = "(?:\"pwd\"|\"password\":|pwd=|password=|config/api" + "|method: 'get'|method: 'post'|method: \"get\"|method: \"post\"" + "|service\\.httppost|service\\.httpget|\\$\\.ajax|http\\.get\\(\"|http\\.post\\(\"" + "rememberMe=delete|[A|a]ccess[K|k]ey|[A|a]ccess[T|t]oken|api_secret|app_secret|(ey[A-Za-z0-9_\\/+-]{34,}\\.[A-Za-z0-9._\\/+-]*))"; Matcher matcher = Pattern.compile(is_pwd).matcher(str); while (matcher.find()){ pwd.add(matcher.group()); } // 去重 List<String> pwd_rd = Re.removeDuplicate(pwd); return StringUtils.strip(pwd_rd.toString(),"[]"); } // ip地址匹配 public static String IP(String str){ ArrayList<String> ip = new ArrayList<>(); // String is_ip = "\\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\b"; String is_ip = "\\b(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[0]|[1-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\b"; Matcher matcher = Pattern.compile(is_ip).matcher(str); while (matcher.find()){ ip.add(matcher.group()); } // 去重 List<String> ip_rd = Re.removeDuplicate(ip); return StringUtils.strip(ip_rd.toString(),"[]"); } // 内网ip匹配 public static boolean in_ip(String str){ String in_ip = "\\b(?:(10\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}))|(?:172\\.(?:(?:1[6-9])|(?:2\\d)|(?:3[01]))\\.\\d{1,3}\\.\\d{1,3})|(?:192\\.168\\.\\d{1,3}\\.\\d{1,3})"; Matcher matcher = Pattern.compile(in_ip).matcher(str); if (matcher.find()){ return true; } return false; } //邮箱匹配 public static String Email(String str){ ArrayList<String> email = new ArrayList<>(); String is_email = "\\b[\\w-]+(?:\\.[\\w-]+)*@([\\w](?:[\\w-]*[\\w])?\\.)+(?:((?!png))((?!jpg))((?!jpeg))((?!gif))((?!ico))((?!html))((?!js))((?!css)))[A-Za-z]{2,6}"; Matcher matcher = Pattern.compile(is_email).matcher(str); while (matcher.find()){ email.add(matcher.group()); } // 去重 List<String> email_rd = Re.removeDuplicate(email); return StringUtils.strip(email_rd.toString(),"[]"); } // js路径匹配 public static String Path(String str){ ArrayList<String> path = new ArrayList<>(); String path1 = new String(); // String is_path = "[\"|'](?:(\\.)*/|/)[0-9a-zA-Z.]+(?:((/[\\w,\\?,-,_,.]*)+)|[\"|'])"; String is_path = "[\"|'](/[0-9a-zA-Z.]+(?:/[\\w,\\?,-,\\.,_]*?)+)[\"|']"; Matcher matcher = Pattern.compile(is_path).matcher(str); while (matcher.find()){ path.add(matcher.group()); } // 去重代码 List<String> path_rd = Re.removeDuplicate(path); for (String s : path_rd){ path1 += StringUtils.strip(s,"\"'")+'\n'; } // return StringUtils.strip(path1,"[]"); return path1; } public static String Url(String str){ ArrayList<String> url = new ArrayList<>(); String url1 = new String(); String is_url = "([\"|'](http|https):\\/\\/([\\w.]+\\/?)\\S*?[\"|'])"; Matcher matcher = Pattern.compile(is_url).matcher(str); while (matcher.find()){ url.add(matcher.group()); } // 去重代码 List<String> path_rd = Re.removeDuplicate(url); for (String s : path_rd){ url1 += StringUtils.strip(s,"\"'")+'\n'; } return url1; } // 判断javascript文件 public static boolean js (String headers,byte[] content){ if (headers.contains("/javascript")||headers.contains("/x-javascript") ){ if (Re.Path(new String(content)).length() != 0){ return true; } } return false; } // 去重代码 public static List<String> removeDuplicate (ArrayList<String> strings){ List<String> list2 = new ArrayList<String>(strings); list2 = list2.stream().distinct().collect(Collectors.toList()); return list2; } }
false
1,999
6
2,205
5
2,300
4
2,205
5
2,613
9
false
false
false
false
false
true
11011_9
package pro.tools.constant; /** * 常量相关工具 * 包含 * 数据单位的常量 * 常见的正则表达式 * * @author SeanDragon */ public final class UnitConst { private UnitConst() { throw new UnsupportedOperationException("我是工具类,别初始化我。。。"); } //region 存储相关常量 /** * KB与Byte的倍数 */ public static final int KB = 1024; /** * MB与Byte的倍数 */ public static final int MB = 1048576; /** * GB与Byte的倍数 */ public static final int GB = 1073741824; /** * 秒与毫秒的倍数 */ public static final int SEC = 1000; /** * 分与毫秒的倍数 */ public static final int MIN = 60000; //endregion //region 时间相关常量 /** * 时与毫秒的倍数 */ public static final int HOUR = 3600000; /** * 天与毫秒的倍数 */ public static final int DAY = 86400000; //endregion public enum MemoryUnit { /** * 字节 */ BYTE, /** * KB */ KB, /** * MB = 1024 * KB */ MB, /** * GB = 1024 * MB */ GB } public enum TimeUnit { /** * 毫秒 */ MSEC, /** * 秒 */ SEC, /** * 分钟 */ MIN, /** * 小时 */ HOUR, /** * 天 */ DAY } }
SeanDragon/protools
common/src/main/java/pro/tools/constant/UnitConst.java
443
/** * 时与毫秒的倍数 */
block_comment
zh-cn
package pro.tools.constant; /** * 常量相关工具 * 包含 * 数据单位的常量 * 常见的正则表达式 * * @author SeanDragon */ public final class UnitConst { private UnitConst() { throw new UnsupportedOperationException("我是工具类,别初始化我。。。"); } //region 存储相关常量 /** * KB与Byte的倍数 */ public static final int KB = 1024; /** * MB与Byte的倍数 */ public static final int MB = 1048576; /** * GB与Byte的倍数 */ public static final int GB = 1073741824; /** * 秒与毫秒的倍数 */ public static final int SEC = 1000; /** * 分与毫秒的倍数 */ public static final int MIN = 60000; //endregion //region 时间相关常量 /** * 时与毫 <SUF>*/ public static final int HOUR = 3600000; /** * 天与毫秒的倍数 */ public static final int DAY = 86400000; //endregion public enum MemoryUnit { /** * 字节 */ BYTE, /** * KB */ KB, /** * MB = 1024 * KB */ MB, /** * GB = 1024 * MB */ GB } public enum TimeUnit { /** * 毫秒 */ MSEC, /** * 秒 */ SEC, /** * 分钟 */ MIN, /** * 小时 */ HOUR, /** * 天 */ DAY } }
false
446
14
443
14
492
14
443
14
604
21
false
false
false
false
false
true
56205_1
public class Lexer { private final String input; private int pos = 0; private String curToken; public Lexer(String input) { this.input = input; this.next(); } private String getNumber() { StringBuilder sb = new StringBuilder(); while (pos < input.length() && Character.isDigit(input.charAt(pos))) { sb.append(input.charAt(pos)); ++pos; } return sb.toString(); } public void next() { if (pos == input.length()) { return; } char c = input.charAt(pos); if (Character.isDigit(c)) { //数字 curToken = getNumber(); } else if (c == '(' || c == ')') { //括号 //TODO 考虑合并单字符集合 pos += 1; curToken = String.valueOf(c); } else if (c == '*' && input.charAt(pos + 1) == '*') { //TODO pos+1是否溢出?因为*绝对不是结尾字符,所以不会溢出。 pos += 2; curToken = "**"; } else if (c == '*' && input.charAt(pos + 1) != '*') { //乘号 pos += 1; curToken = "*"; } else if (c == '+' || c == '-') { //加减 pos += 1; curToken = String.valueOf(c); } else if (c == 'x' || c == 'y' || c == 'z') { //变量名 xyz pos += 1; curToken = String.valueOf(c); } } public String peek() { return this.curToken; } }
Seanium/OOP-Projects
src/Lexer.java
399
//TODO pos+1是否溢出?因为*绝对不是结尾字符,所以不会溢出。
line_comment
zh-cn
public class Lexer { private final String input; private int pos = 0; private String curToken; public Lexer(String input) { this.input = input; this.next(); } private String getNumber() { StringBuilder sb = new StringBuilder(); while (pos < input.length() && Character.isDigit(input.charAt(pos))) { sb.append(input.charAt(pos)); ++pos; } return sb.toString(); } public void next() { if (pos == input.length()) { return; } char c = input.charAt(pos); if (Character.isDigit(c)) { //数字 curToken = getNumber(); } else if (c == '(' || c == ')') { //括号 //TODO 考虑合并单字符集合 pos += 1; curToken = String.valueOf(c); } else if (c == '*' && input.charAt(pos + 1) == '*') { //TO <SUF> pos += 2; curToken = "**"; } else if (c == '*' && input.charAt(pos + 1) != '*') { //乘号 pos += 1; curToken = "*"; } else if (c == '+' || c == '-') { //加减 pos += 1; curToken = String.valueOf(c); } else if (c == 'x' || c == 'y' || c == 'z') { //变量名 xyz pos += 1; curToken = String.valueOf(c); } } public String peek() { return this.curToken; } }
false
368
21
399
25
431
21
399
25
493
36
false
false
false
false
false
true
34739_3
package com.wongcu.ezvizapi.common.device; import lombok.Data; import java.io.Serializable; /** * @author wongcu * @version 2018/11/2 14:55 * @since 2018/11/2 */ @Data public class Device implements Serializable { private static final long serialVersionUID = 2915307603618609014L; /** * 设备序列号 */ private String deviceSerial; /** * 设备名称 */ private String deviceName; /** * 设备类型 */ private String deviceType; /** * 在线状态:0-不在线,1-在线 */ private Integer status; /** * 具有防护能力的设备布撤防状态:0-睡眠,8-在家,16-外出,普通IPC布撤防状态:0-撤防,1-布防 */ private Integer defence; /** * 设备版本号 */ private String deviceVersion; }
SeauWong/ezviz-api
src/main/java/com/wongcu/ezvizapi/common/device/Device.java
267
/** * 设备类型 */
block_comment
zh-cn
package com.wongcu.ezvizapi.common.device; import lombok.Data; import java.io.Serializable; /** * @author wongcu * @version 2018/11/2 14:55 * @since 2018/11/2 */ @Data public class Device implements Serializable { private static final long serialVersionUID = 2915307603618609014L; /** * 设备序列号 */ private String deviceSerial; /** * 设备名称 */ private String deviceName; /** * 设备类 <SUF>*/ private String deviceType; /** * 在线状态:0-不在线,1-在线 */ private Integer status; /** * 具有防护能力的设备布撤防状态:0-睡眠,8-在家,16-外出,普通IPC布撤防状态:0-撤防,1-布防 */ private Integer defence; /** * 设备版本号 */ private String deviceVersion; }
false
245
9
267
8
271
9
267
8
352
14
false
false
false
false
false
true
22672_35
package org.sec; import com.beust.jcommander.JCommander; import org.sec.config.Command; import org.sec.config.Logo; import org.sec.core.InheritanceUtil; import org.sec.model.*; import org.sec.util.DataUtil; import org.sec.util.FileUtil; import org.sec.util.OutputUtil; import org.sec.util.RtUtil; import org.apache.log4j.Logger; import org.sec.core.CallGraph; import org.sec.core.InheritanceMap; import org.sec.service.*; import java.util.*; // _ooOoo_ // o8888888o // 88" . "88 // (| -_- |) // O\ = /O // ____/`---'\____ // . ' \\| |// `. // / \\||| : |||// \ // / _||||| -:- |||||- \ // | | \\\ - /// | | // | \_| ''\---/'' | | // \ .-\__ `-` ___/-. / // ___`. .' /--.--\ `. . __ // ."" '< `.___\_<|>_/___.' >'"". // | | : `- \`.;`\ _ /`;.`/ - ` : | | // \ \ `-. \_ __\ /__ _/ .-` / / // ======`-.____`-.___\_____/___.-`____.-'====== // `=---=' // // ............................................. // 佛祖保佑 永无BUG // // 写字楼里写字间,写字间里程序员; // 程序人员写程序,又拿程序换酒钱。 // 酒醒只在网上坐,酒醉还来网下眠; // 酒醉酒醒日复日,网上网下年复年。 // 但愿老死电脑间,不愿鞠躬老板前; // 奔驰宝马贵者趣,公交自行程序员。 // 别人笑我忒疯癫,我笑自己命太贱; // 不见满街漂亮妹,哪个归得程序员? public class Main { private static final Logger logger = Logger.getLogger(Main.class); // 所有类 private static final List<ClassReference> discoveredClasses = new ArrayList<>(); // 所有方法 private static final List<MethodReference> discoveredMethods = new ArrayList<>(); // 所有方法内的方法调用 private static final Map<MethodReference.Handle, Set<MethodReference.Handle>> methodCalls = new HashMap<>(); // 方法返回值与哪些参数有关 private static final Map<MethodReference.Handle, Set<Integer>> dataFlow = new HashMap<>(); // 所有的方法调用关系 private static final Set<CallGraph> discoveredCalls = new HashSet<>(); // 类名->类对象 private static final Map<ClassReference.Handle, ClassReference> classMap = new HashMap<>(); // 方法名->方法对象 private static final Map<MethodReference.Handle, MethodReference> methodMap = new HashMap<>(); // 类名->类资源 private static final Map<String, ClassFile> classFileByName = new HashMap<>(); // 方法名->方法调用关系 private static final Map<MethodReference.Handle, Set<CallGraph>> graphCallMap = new HashMap<>(); // 最终结果 private static final List<ResultInfo> resultInfos = new ArrayList<>(); public static void main(String[] args) { // 打印Logo Logo.PrintLogo(); logger.info("start code inspector"); // 使用JCommander处理命令参数 Command command = new Command(); JCommander jc = JCommander.newBuilder().addObject(command).build(); jc.parse(args); if (command.help) { jc.usage(); } // 暂时只处理输入SpringBoot的Jar包情况 // 其实Tomcat的War包情况类似暂不处理 if (command.boots != null && command.boots.size() != 0) { start(command); } } private static void start(Command command) { List<String> boots = command.boots; String packageName = command.packageName; boolean draw = command.drawCallGraph; // 读取JDK和输入Jar所有class资源 List<ClassFile> classFileList = RtUtil.getAllClassesFromBoot(boots, true); // 获取所有方法和类 DiscoveryService.start(classFileList, discoveredClasses, discoveredMethods); // 根据已有方法和类得到继承关系 InheritanceMap inheritanceMap = InheritanceService.start(discoveredClasses, discoveredMethods, classMap, methodMap); // 包名 String finalPackageName = packageName.replace(".", "/"); // 获取全部controller List<SpringController> controllers = new ArrayList<>(); // 根据SpringMVC的规则得到相关信息 SpringService.start(classFileList, finalPackageName, controllers, classMap, methodMap); // 得到方法中的方法调用 MethodCallService.start(classFileList, methodCalls, classFileByName); // 对方法进行拓扑逆排序 List<MethodReference.Handle> sortedMethods = SortService.start(methodCalls); // 分析方法返回值与哪些参数有关 DataFlowService.start(inheritanceMap, sortedMethods, classFileByName, classMap, dataFlow); // 同步DataFlow信息到接口 DataFlowService.updateInterfaceDataFlow(discoveredMethods, classMap, dataFlow, finalPackageName); DataFlowService.start(inheritanceMap, sortedMethods, classFileByName, classMap, dataFlow); // 保存到本地观察 if (command.debug) { DataUtil.SaveDataFlows(dataFlow, methodMap, finalPackageName); } // 根据已有条件得到方法调用关系 CallGraphService.start(inheritanceMap, discoveredCalls, sortedMethods, classFileByName, classMap, dataFlow, graphCallMap, methodMap); // 保存到本地观察 if (command.debug) { DataUtil.SaveCallGraphs(discoveredCalls, finalPackageName); } // SSRF检测 SSRFService.start(classFileByName, controllers, inheritanceMap, dataFlow, graphCallMap); resultInfos.addAll(SSRFService.getResults()); XSSService.startReflection(classFileByName, controllers, inheritanceMap, dataFlow, graphCallMap); resultInfos.addAll(XSSService.getResults()); XSSService.startStored(classFileByName, controllers, inheritanceMap, dataFlow, graphCallMap); resultInfos.addAll(XSSService.getResults()); OutputUtil.doOutput(resultInfos); if (draw) { DrawService.start(discoveredCalls, finalPackageName, classMap); } } }
Sec-Fork/CodeInspector
src/main/java/org/sec/Main.java
1,625
// 类名->类资源
line_comment
zh-cn
package org.sec; import com.beust.jcommander.JCommander; import org.sec.config.Command; import org.sec.config.Logo; import org.sec.core.InheritanceUtil; import org.sec.model.*; import org.sec.util.DataUtil; import org.sec.util.FileUtil; import org.sec.util.OutputUtil; import org.sec.util.RtUtil; import org.apache.log4j.Logger; import org.sec.core.CallGraph; import org.sec.core.InheritanceMap; import org.sec.service.*; import java.util.*; // _ooOoo_ // o8888888o // 88" . "88 // (| -_- |) // O\ = /O // ____/`---'\____ // . ' \\| |// `. // / \\||| : |||// \ // / _||||| -:- |||||- \ // | | \\\ - /// | | // | \_| ''\---/'' | | // \ .-\__ `-` ___/-. / // ___`. .' /--.--\ `. . __ // ."" '< `.___\_<|>_/___.' >'"". // | | : `- \`.;`\ _ /`;.`/ - ` : | | // \ \ `-. \_ __\ /__ _/ .-` / / // ======`-.____`-.___\_____/___.-`____.-'====== // `=---=' // // ............................................. // 佛祖保佑 永无BUG // // 写字楼里写字间,写字间里程序员; // 程序人员写程序,又拿程序换酒钱。 // 酒醒只在网上坐,酒醉还来网下眠; // 酒醉酒醒日复日,网上网下年复年。 // 但愿老死电脑间,不愿鞠躬老板前; // 奔驰宝马贵者趣,公交自行程序员。 // 别人笑我忒疯癫,我笑自己命太贱; // 不见满街漂亮妹,哪个归得程序员? public class Main { private static final Logger logger = Logger.getLogger(Main.class); // 所有类 private static final List<ClassReference> discoveredClasses = new ArrayList<>(); // 所有方法 private static final List<MethodReference> discoveredMethods = new ArrayList<>(); // 所有方法内的方法调用 private static final Map<MethodReference.Handle, Set<MethodReference.Handle>> methodCalls = new HashMap<>(); // 方法返回值与哪些参数有关 private static final Map<MethodReference.Handle, Set<Integer>> dataFlow = new HashMap<>(); // 所有的方法调用关系 private static final Set<CallGraph> discoveredCalls = new HashSet<>(); // 类名->类对象 private static final Map<ClassReference.Handle, ClassReference> classMap = new HashMap<>(); // 方法名->方法对象 private static final Map<MethodReference.Handle, MethodReference> methodMap = new HashMap<>(); // 类名 <SUF> private static final Map<String, ClassFile> classFileByName = new HashMap<>(); // 方法名->方法调用关系 private static final Map<MethodReference.Handle, Set<CallGraph>> graphCallMap = new HashMap<>(); // 最终结果 private static final List<ResultInfo> resultInfos = new ArrayList<>(); public static void main(String[] args) { // 打印Logo Logo.PrintLogo(); logger.info("start code inspector"); // 使用JCommander处理命令参数 Command command = new Command(); JCommander jc = JCommander.newBuilder().addObject(command).build(); jc.parse(args); if (command.help) { jc.usage(); } // 暂时只处理输入SpringBoot的Jar包情况 // 其实Tomcat的War包情况类似暂不处理 if (command.boots != null && command.boots.size() != 0) { start(command); } } private static void start(Command command) { List<String> boots = command.boots; String packageName = command.packageName; boolean draw = command.drawCallGraph; // 读取JDK和输入Jar所有class资源 List<ClassFile> classFileList = RtUtil.getAllClassesFromBoot(boots, true); // 获取所有方法和类 DiscoveryService.start(classFileList, discoveredClasses, discoveredMethods); // 根据已有方法和类得到继承关系 InheritanceMap inheritanceMap = InheritanceService.start(discoveredClasses, discoveredMethods, classMap, methodMap); // 包名 String finalPackageName = packageName.replace(".", "/"); // 获取全部controller List<SpringController> controllers = new ArrayList<>(); // 根据SpringMVC的规则得到相关信息 SpringService.start(classFileList, finalPackageName, controllers, classMap, methodMap); // 得到方法中的方法调用 MethodCallService.start(classFileList, methodCalls, classFileByName); // 对方法进行拓扑逆排序 List<MethodReference.Handle> sortedMethods = SortService.start(methodCalls); // 分析方法返回值与哪些参数有关 DataFlowService.start(inheritanceMap, sortedMethods, classFileByName, classMap, dataFlow); // 同步DataFlow信息到接口 DataFlowService.updateInterfaceDataFlow(discoveredMethods, classMap, dataFlow, finalPackageName); DataFlowService.start(inheritanceMap, sortedMethods, classFileByName, classMap, dataFlow); // 保存到本地观察 if (command.debug) { DataUtil.SaveDataFlows(dataFlow, methodMap, finalPackageName); } // 根据已有条件得到方法调用关系 CallGraphService.start(inheritanceMap, discoveredCalls, sortedMethods, classFileByName, classMap, dataFlow, graphCallMap, methodMap); // 保存到本地观察 if (command.debug) { DataUtil.SaveCallGraphs(discoveredCalls, finalPackageName); } // SSRF检测 SSRFService.start(classFileByName, controllers, inheritanceMap, dataFlow, graphCallMap); resultInfos.addAll(SSRFService.getResults()); XSSService.startReflection(classFileByName, controllers, inheritanceMap, dataFlow, graphCallMap); resultInfos.addAll(XSSService.getResults()); XSSService.startStored(classFileByName, controllers, inheritanceMap, dataFlow, graphCallMap); resultInfos.addAll(XSSService.getResults()); OutputUtil.doOutput(resultInfos); if (draw) { DrawService.start(discoveredCalls, finalPackageName, classMap); } } }
false
1,470
6
1,625
7
1,601
6
1,625
7
2,020
10
false
false
false
false
false
true
51484_27
package org.sec; import org.apache.log4j.Logger; import org.sec.input.Logo; import org.sec.start.Application; // _ooOoo_ // o8888888o // 88" . "88 // (| -_- |) // O\ = /O // ____/`---'\____ // . ' \\| |// `. // / \\||| : |||// \ // / _||||| -:- |||||- \ // | | \\\ - /// | | // | \_| ''\---/'' | | // \ .-\__ `-` ___/-. / // ___`. .' /--.--\ `. . __ // ."" '< `.___\_<|>_/___.' >'"". // | | : `- \`.;`\ _ /`;.`/ - ` : | | // \ \ `-. \_ __\ /__ _/ .-` / / // ======`-.____`-.___\_____/___.-`____.-'====== // `=---=' // // ............................................. // 佛祖保佑 永无BUG // // 写字楼里写字间,写字间里程序员; // 程序人员写程序,又拿程序换酒钱。 // 酒醒只在网上坐,酒醉还来网下眠; // 酒醉酒醒日复日,网上网下年复年。 // 但愿老死电脑间,不愿鞠躬老板前; // 奔驰宝马贵者趣,公交自行程序员。 // 别人笑我忒疯癫,我笑自己命太贱; // 不见满街漂亮妹,哪个归得程序员? public class Main { private static final Logger logger = Logger.getLogger(Main.class); public static void main(String[] args) { Logo.PrintLogo(); logger.info("start jsp horse application"); logger.info("please wait 30 second..."); Application.start(args); } }
Sec-Fork/JSPHorse
src/main/java/org/sec/Main.java
549
// 不见满街漂亮妹,哪个归得程序员?
line_comment
zh-cn
package org.sec; import org.apache.log4j.Logger; import org.sec.input.Logo; import org.sec.start.Application; // _ooOoo_ // o8888888o // 88" . "88 // (| -_- |) // O\ = /O // ____/`---'\____ // . ' \\| |// `. // / \\||| : |||// \ // / _||||| -:- |||||- \ // | | \\\ - /// | | // | \_| ''\---/'' | | // \ .-\__ `-` ___/-. / // ___`. .' /--.--\ `. . __ // ."" '< `.___\_<|>_/___.' >'"". // | | : `- \`.;`\ _ /`;.`/ - ` : | | // \ \ `-. \_ __\ /__ _/ .-` / / // ======`-.____`-.___\_____/___.-`____.-'====== // `=---=' // // ............................................. // 佛祖保佑 永无BUG // // 写字楼里写字间,写字间里程序员; // 程序人员写程序,又拿程序换酒钱。 // 酒醒只在网上坐,酒醉还来网下眠; // 酒醉酒醒日复日,网上网下年复年。 // 但愿老死电脑间,不愿鞠躬老板前; // 奔驰宝马贵者趣,公交自行程序员。 // 别人笑我忒疯癫,我笑自己命太贱; // 不见 <SUF> public class Main { private static final Logger logger = Logger.getLogger(Main.class); public static void main(String[] args) { Logo.PrintLogo(); logger.info("start jsp horse application"); logger.info("please wait 30 second..."); Application.start(args); } }
false
458
14
549
21
490
14
549
21
642
32
false
false
false
false
false
true
15357_9
import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; public class Conn { // 创建类Conn Connection con; // 声明Connection对象 public static String user; public static String password; public Connection getConnection() { // 建立返回值为Connection的方法 try { // 加载数据库驱动类 Class.forName("com.mysql.cj.jdbc.Driver"); System.out.println("数据库驱动加载成功"); } catch (ClassNotFoundException e) { e.printStackTrace(); } user = "wslroot";//数据库登录名 password = "LYHongiao1295402";//密码 try { // 通过访问数据库的URL获取数据库连接对象 con = DriverManager.getConnection("jdbc:mysql://172.26.0.1:3306/test1?useUnicode=true&characterEncoding=gbk", user, password); System.out.println("数据库连接成功"); } catch (SQLException e) { e.printStackTrace(); } return con; // 按方法要求返回一个Connection对象 } public static void main(String[] args) { // 主方法,测试连接 Conn c = new Conn(); // 创建本类对象 c.getConnection(); // 调用连接数据库的方法 } }
SecretLittleBoy/learnJava
Conn.java
298
// 创建本类对象
line_comment
zh-cn
import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; public class Conn { // 创建类Conn Connection con; // 声明Connection对象 public static String user; public static String password; public Connection getConnection() { // 建立返回值为Connection的方法 try { // 加载数据库驱动类 Class.forName("com.mysql.cj.jdbc.Driver"); System.out.println("数据库驱动加载成功"); } catch (ClassNotFoundException e) { e.printStackTrace(); } user = "wslroot";//数据库登录名 password = "LYHongiao1295402";//密码 try { // 通过访问数据库的URL获取数据库连接对象 con = DriverManager.getConnection("jdbc:mysql://172.26.0.1:3306/test1?useUnicode=true&characterEncoding=gbk", user, password); System.out.println("数据库连接成功"); } catch (SQLException e) { e.printStackTrace(); } return con; // 按方法要求返回一个Connection对象 } public static void main(String[] args) { // 主方法,测试连接 Conn c = new Conn(); // 创建 <SUF> c.getConnection(); // 调用连接数据库的方法 } }
false
282
5
298
5
311
5
298
5
396
8
false
false
false
false
false
true
17117_3
package com.xt.leetcode; import java.util.*; /** * 1001. 网格照明 * 日期:2022.2.8 * 描述 * 在大小为 n x n 的网格 grid 上,每个单元格都有一盏灯,最初灯都处于 关闭 状态。 * <p> * 给你一个由灯的位置组成的二维数组 lamps ,其中 lamps[i] = [rowi, coli] 表示 打开 位于 grid[rowi][coli] 的灯。即便同一盏灯可能在 lamps 中多次列出,不会影响这盏灯处于 打开 状态。 * <p> * 当一盏灯处于打开状态,它将会照亮 自身所在单元格 以及同一 行 、同一 列 和两条 对角线 上的 所有其他单元格 。 * <p> * 另给你一个二维数组 queries ,其中 queries[j] = [rowj, colj] 。对于第 j 个查询,如果单元格 [rowj, colj] 是被照亮的,则查询结果为 1 ,否则为 0 。在第 j 次查询之后 [按照查询的顺序] ,关闭 位于单元格 grid[rowj][colj] 上及相邻 8 个方向上(与单元格 grid[rowi][coli] 共享角或边)的任何灯。 * <p> * 返回一个整数数组 ans 作为答案, ans[j] 应等于第 j 次查询 queries[j] 的结果,1 表示照亮,0 表示未照亮。 * <p> * 示例 1: * 输入:n = 5, lamps = [[0,0],[4,4]], queries = [[1,1],[1,0]] * 输出:[1,0] * 解释:最初所有灯都是关闭的。在执行查询之前,打开位于 [0, 0] 和 [4, 4] 的灯。第 0 次查询检查 grid[1][1] 是否被照亮(蓝色方框)。该单元格被照亮,所以 ans[0] = 1 。然后,关闭红色方框中的所有灯。 * <p> * 示例 2: * <p> * 输入:n = 5, lamps = [[0,0],[4,4]], queries = [[1,1],[1,1]] * 输出:[1,1] * 示例 3: * <p> * 输入:n = 5, lamps = [[0,0],[0,4]], queries = [[0,4],[0,1],[1,4]] * 输出:[1,1,0] * <p> * 提示: * <p> * 1 <= n <= 10^9 * 0 <= lamps.length <= 20000 * 0 <= queries.length <= 20000 * lamps[i].length == 2 * 0 <= rowi, coli < n * queries[j].length == 2 * 0 <= rowj, colj < n * <p> * 来源:力扣(LeetCode) * 链接:https://leetcode-cn.com/problems/grid-illumination * 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 * 解题思路: * 这题看一下数据范围,n<10^9,很大所以不可能用数组来表示。lamps.length<=20000,说明时间复杂度必须是O(N)或者O(N*logN)级别的。 * 所以我的解题方向就是找一个数据结构记录每一个lamp的点,每次查询之后针对这个数据结构进行依次O(1)级别的操作。O(1)级别的操作的数据结构那肯定就是map或者set了。 * 我的解题思路是构建4个Map分别缓存x轴,y轴,右下-左上方向的轴,左下-右上方向的轴,这四条轴上的所有lamp点。 * x和y轴的key值很简单,直接x,y值即可。但是斜向的两个轴,我选择的key值是映射到边界的值。比如右下-左上方向的轴上的一个点为(1,3),那么映射到边界上为(0,2)。则key为0_2。 * value值为set,记录这条轴上所有的lamp点。 * 遍历queries时,取其x,y值,分别查询对应的四条轴上是否被照到,如果照到,则熄灭附近加自身共9盏灯。对应的对四个map也进行相应的处理。 * * <p> * <p> * state:done */ public class Solution1001 { Set<String> pointSet = new HashSet<>(); Map<String, Set<String>> xMap = new HashMap<>(); Map<String, Set<String>> yMap = new HashMap<>(); Map<String, Set<String>> rightUpMap = new HashMap<>(); Map<String, Set<String>> leftUpMap = new HashMap<>(); public int[] gridIllumination(int n, int[][] lamps, int[][] queries) { int[] result = new int[queries.length]; for (int i = 0; i < lamps.length; i++) { int[] lamp = lamps[i]; int x = lamp[0]; int y = lamp[1]; String xs = String.valueOf(x); String ys = String.valueOf(y); String rightUpKey = getRightUpKey(x, y, n); String leftUpKey = getLeftUpKey(x, y, n); Set<String> xSet = create(xMap, xs); Set<String> ySet = create(yMap, ys); Set<String> rightUpSet = create(rightUpMap, rightUpKey); Set<String> leftUpSet = create(leftUpMap, leftUpKey); String key = lamp[0] + "_" + lamp[1]; xSet.add(key); ySet.add(key); rightUpSet.add(key); leftUpSet.add(key); pointSet.add(x + "_" + y); } for (int i = 0; i < queries.length; i++) { int[] query = queries[i]; int x = query[0]; int y = query[1]; String xS = String.valueOf(x); String yS = String.valueOf(y); boolean isBright = false; //查询x轴 Set<String> xSet = xMap.get(xS); if (xSet != null && xSet.size() > 0) { isBright = true; } //查询y轴 Set<String> ySet = yMap.get(yS); if (ySet != null && ySet.size() > 0) { isBright = true; } //查询左上 String leftUpKey = getLeftUpKey(x, y, n); Set<String> leftUpSet = leftUpMap.get(leftUpKey); if (leftUpSet != null && leftUpSet.size() > 0) { isBright = true; } //查询右上 String rightUpKey = getRightUpKey(x, y, n); Set<String> rightUpSet = rightUpMap.get(rightUpKey); if (rightUpSet != null && rightUpSet.size() > 0) { isBright = true; } if (isBright) { //记录 result[i] = 1; //关闭周围的灯,对应的修改map checkRemove(x, y, n); } } return result; } private Set<String> create(Map<String, Set<String>> map, String key) { Set<String> set = map.get(key); if (set == null) { set = new HashSet<>(); map.put(key, set); } return set; } private void checkRemove(int x, int y, int n) { for (int x1 = x - 1; x1 <= x + 1; x1++) { for (int y1 = y - 1; y1 <= y + 1; y1++) { String x1S = String.valueOf(x1); String y1S = String.valueOf(y1); if (x1 < 0 || y1 < 0) { continue; } //查看是否在集合中 String pointKey = x1 + "_" + y1; if (!pointSet.contains(pointKey)) { continue; } remove(xMap, x1S, pointKey); remove(yMap, y1S, pointKey); remove(leftUpMap, getLeftUpKey(x1, y1, n), pointKey); remove(rightUpMap, getRightUpKey(x1, y1, n), pointKey); } } } private void remove(Map<String, Set<String>> map, String setKey, String pointKey) { Set<String> set = map.get(setKey); if (set != null) { set.remove(pointKey); if (set.size() == 0) { rightUpMap.remove(setKey); } } } private String getRightUpKey(int x, int y, int n) { int sum = x + y; if (sum <= n) { return "0_" + (y + x); } return (n - 1) + "_" + (y - (n - 1) + x); } private String getLeftUpKey(int x, int y, int n) { if (y >= x) { return "0_" + (y - x); } return (x - y) + "_0"; } }
September26/java-algorithms
src/com/xt/leetcode/Solution1001.java
2,409
//查询左上
line_comment
zh-cn
package com.xt.leetcode; import java.util.*; /** * 1001. 网格照明 * 日期:2022.2.8 * 描述 * 在大小为 n x n 的网格 grid 上,每个单元格都有一盏灯,最初灯都处于 关闭 状态。 * <p> * 给你一个由灯的位置组成的二维数组 lamps ,其中 lamps[i] = [rowi, coli] 表示 打开 位于 grid[rowi][coli] 的灯。即便同一盏灯可能在 lamps 中多次列出,不会影响这盏灯处于 打开 状态。 * <p> * 当一盏灯处于打开状态,它将会照亮 自身所在单元格 以及同一 行 、同一 列 和两条 对角线 上的 所有其他单元格 。 * <p> * 另给你一个二维数组 queries ,其中 queries[j] = [rowj, colj] 。对于第 j 个查询,如果单元格 [rowj, colj] 是被照亮的,则查询结果为 1 ,否则为 0 。在第 j 次查询之后 [按照查询的顺序] ,关闭 位于单元格 grid[rowj][colj] 上及相邻 8 个方向上(与单元格 grid[rowi][coli] 共享角或边)的任何灯。 * <p> * 返回一个整数数组 ans 作为答案, ans[j] 应等于第 j 次查询 queries[j] 的结果,1 表示照亮,0 表示未照亮。 * <p> * 示例 1: * 输入:n = 5, lamps = [[0,0],[4,4]], queries = [[1,1],[1,0]] * 输出:[1,0] * 解释:最初所有灯都是关闭的。在执行查询之前,打开位于 [0, 0] 和 [4, 4] 的灯。第 0 次查询检查 grid[1][1] 是否被照亮(蓝色方框)。该单元格被照亮,所以 ans[0] = 1 。然后,关闭红色方框中的所有灯。 * <p> * 示例 2: * <p> * 输入:n = 5, lamps = [[0,0],[4,4]], queries = [[1,1],[1,1]] * 输出:[1,1] * 示例 3: * <p> * 输入:n = 5, lamps = [[0,0],[0,4]], queries = [[0,4],[0,1],[1,4]] * 输出:[1,1,0] * <p> * 提示: * <p> * 1 <= n <= 10^9 * 0 <= lamps.length <= 20000 * 0 <= queries.length <= 20000 * lamps[i].length == 2 * 0 <= rowi, coli < n * queries[j].length == 2 * 0 <= rowj, colj < n * <p> * 来源:力扣(LeetCode) * 链接:https://leetcode-cn.com/problems/grid-illumination * 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 * 解题思路: * 这题看一下数据范围,n<10^9,很大所以不可能用数组来表示。lamps.length<=20000,说明时间复杂度必须是O(N)或者O(N*logN)级别的。 * 所以我的解题方向就是找一个数据结构记录每一个lamp的点,每次查询之后针对这个数据结构进行依次O(1)级别的操作。O(1)级别的操作的数据结构那肯定就是map或者set了。 * 我的解题思路是构建4个Map分别缓存x轴,y轴,右下-左上方向的轴,左下-右上方向的轴,这四条轴上的所有lamp点。 * x和y轴的key值很简单,直接x,y值即可。但是斜向的两个轴,我选择的key值是映射到边界的值。比如右下-左上方向的轴上的一个点为(1,3),那么映射到边界上为(0,2)。则key为0_2。 * value值为set,记录这条轴上所有的lamp点。 * 遍历queries时,取其x,y值,分别查询对应的四条轴上是否被照到,如果照到,则熄灭附近加自身共9盏灯。对应的对四个map也进行相应的处理。 * * <p> * <p> * state:done */ public class Solution1001 { Set<String> pointSet = new HashSet<>(); Map<String, Set<String>> xMap = new HashMap<>(); Map<String, Set<String>> yMap = new HashMap<>(); Map<String, Set<String>> rightUpMap = new HashMap<>(); Map<String, Set<String>> leftUpMap = new HashMap<>(); public int[] gridIllumination(int n, int[][] lamps, int[][] queries) { int[] result = new int[queries.length]; for (int i = 0; i < lamps.length; i++) { int[] lamp = lamps[i]; int x = lamp[0]; int y = lamp[1]; String xs = String.valueOf(x); String ys = String.valueOf(y); String rightUpKey = getRightUpKey(x, y, n); String leftUpKey = getLeftUpKey(x, y, n); Set<String> xSet = create(xMap, xs); Set<String> ySet = create(yMap, ys); Set<String> rightUpSet = create(rightUpMap, rightUpKey); Set<String> leftUpSet = create(leftUpMap, leftUpKey); String key = lamp[0] + "_" + lamp[1]; xSet.add(key); ySet.add(key); rightUpSet.add(key); leftUpSet.add(key); pointSet.add(x + "_" + y); } for (int i = 0; i < queries.length; i++) { int[] query = queries[i]; int x = query[0]; int y = query[1]; String xS = String.valueOf(x); String yS = String.valueOf(y); boolean isBright = false; //查询x轴 Set<String> xSet = xMap.get(xS); if (xSet != null && xSet.size() > 0) { isBright = true; } //查询y轴 Set<String> ySet = yMap.get(yS); if (ySet != null && ySet.size() > 0) { isBright = true; } //查询 <SUF> String leftUpKey = getLeftUpKey(x, y, n); Set<String> leftUpSet = leftUpMap.get(leftUpKey); if (leftUpSet != null && leftUpSet.size() > 0) { isBright = true; } //查询右上 String rightUpKey = getRightUpKey(x, y, n); Set<String> rightUpSet = rightUpMap.get(rightUpKey); if (rightUpSet != null && rightUpSet.size() > 0) { isBright = true; } if (isBright) { //记录 result[i] = 1; //关闭周围的灯,对应的修改map checkRemove(x, y, n); } } return result; } private Set<String> create(Map<String, Set<String>> map, String key) { Set<String> set = map.get(key); if (set == null) { set = new HashSet<>(); map.put(key, set); } return set; } private void checkRemove(int x, int y, int n) { for (int x1 = x - 1; x1 <= x + 1; x1++) { for (int y1 = y - 1; y1 <= y + 1; y1++) { String x1S = String.valueOf(x1); String y1S = String.valueOf(y1); if (x1 < 0 || y1 < 0) { continue; } //查看是否在集合中 String pointKey = x1 + "_" + y1; if (!pointSet.contains(pointKey)) { continue; } remove(xMap, x1S, pointKey); remove(yMap, y1S, pointKey); remove(leftUpMap, getLeftUpKey(x1, y1, n), pointKey); remove(rightUpMap, getRightUpKey(x1, y1, n), pointKey); } } } private void remove(Map<String, Set<String>> map, String setKey, String pointKey) { Set<String> set = map.get(setKey); if (set != null) { set.remove(pointKey); if (set.size() == 0) { rightUpMap.remove(setKey); } } } private String getRightUpKey(int x, int y, int n) { int sum = x + y; if (sum <= n) { return "0_" + (y + x); } return (n - 1) + "_" + (y - (n - 1) + x); } private String getLeftUpKey(int x, int y, int n) { if (y >= x) { return "0_" + (y - x); } return (x - y) + "_0"; } }
false
2,138
4
2,409
4
2,365
4
2,409
4
2,984
7
false
false
false
false
false
true
18853_35
package org.sct.core.util; import java.lang.reflect.Method; import org.sct.core.dto.SlotType; import org.bukkit.craftbukkit.v1_11_R1.inventory.CraftItemStack; import org.bukkit.inventory.ItemStack; import net.minecraft.server.v1_11_R1.NBTTagByte; import net.minecraft.server.v1_11_R1.NBTTagCompound; public class NBTUtil { // /** // * 各类属性 // */ // private static String attackDamage = "generic.attackDamage"; // private static String attackSpeed = "generic.attackSpeed"; // private static String maxHealth = "generic.maxHealth"; // private static String moveMentSpeed = "generic.movementSpeed"; // private static String armor = "generic.armor"; // private static String luck = "generic.luck"; // public static Object NBTTagString(String str) { // try { // return NMSUtil.getNMSClass("NBTTagString").getConstructor(String.class).newInstance(str); // } catch (Exception e) { // System.out.println("错误: " + e.getMessage()); // } // return null; // } public static Object NBTTagInt(int num) { try { return NMSUtil.getNMSClass("NBTTagInt").getConstructor(Integer.TYPE).newInstance(num); } catch (Exception e) { System.out.println("错误: " + e.getMessage()); } return null; } public static Object NBTTagDouble(double num) { try { return NMSUtil.getNMSClass("NBTTagDouble").getConstructor(Double.TYPE).newInstance(num); } catch (Exception e) { System.out.println("错误: " + e.getMessage()); } return null; } // // public static Object NBTTagByte(byte num) { // try { // return NMSUtil.getNMSClass("NBTTagByte").getConstructor(Byte.TYPE).newInstance(num); // } catch (Exception e) { // System.out.println("错误: " + e.getMessage()); // } // return null; // } public static Object NBTTagFloat(float num) { try { return NMSUtil.getNMSClass("NBTTagFloat").getConstructor(Float.TYPE).newInstance(num); } catch (Exception e) { System.out.println("错误: " + e.getMessage()); } return null; } public static Object getItemNBT(ItemStack is) { Object nmsItem = NMSUtil.getNMSItem(is); if (nmsItem == null) { return null; } try { return nmsItem.getClass().getMethod("getTag").invoke(nmsItem) != null ? nmsItem.getClass().getMethod("getTag").invoke(nmsItem) : NMSUtil.getNMSClass("NBTTagCompound").newInstance(); } catch (Exception e) { System.out.println("错误: " + e.getMessage()); } return null; } public static void setUnbreakable(ItemStack is, boolean unbreak) { Object nmsItem = NMSUtil.getNMSItem(is); Object itemNbt = getItemNBT(is); Method set; //ItemStack bukItem = null; try { net.minecraft.server.v1_11_R1.ItemStack nms = CraftItemStack.asNMSCopy(is); NBTTagCompound nbt = nms.hasTag() ? nms.getTag() : new NBTTagCompound(); System.out.println(nbt); nbt.set("Unbreakable", new NBTTagByte((byte) 1)); //set = itemNbt.getClass().getMethod("set", new Class[] { String.class, NMSUtil.getNMSClass("NBTBase") }); //set.invoke(itemNbt, new Object[] { "Unbreakable", new net.minecraft.server.v1_10_R1.NBTTagByte((byte) 1)}); //set.invoke(itemNbt, new Object[] { "Unbreakable", NBTTagByte() }); //itemNbt.set("Unbreakable", new NBTTagByte((byte) (unbreak ? 1 : 0))); //nmsItem.getClass().getMethod("setTag", NMSUtil.getNMSClass("NBTTagCompound")).invoke(nmsItem, itemNbt); nms.setTag(nbt); System.out.println(nbt); //nmsItem.setTag(itemNbt); //bukItem = (ItemStack) NMSUtil.getOBCClass("inventory.CraftItemStack").getMethod("asBukkitCopy", NMSUtil.getNMSClass("ItemStack")).invoke(nmsItem, nmsItem); } catch (Exception e) { e.printStackTrace(); } //return bukItem; } /** * 取武器的Attribute数据 * @param is 物品 * @return NBTTagCompound的实例 */ public static Object getAttribute(ItemStack is) { Object nmsItem = NMSUtil.getNMSItem(is); //判断是否有无Tag数据 try { if (nmsItem.getClass().getMethod("getTag").invoke(nmsItem) != null) { return nmsItem.getClass().getMethod("getTag").invoke(nmsItem); }else { //如果没有Tag数据则实例化个NBTTagCompound的实例 return NMSUtil.getNMSClass("NBTTagCompound").newInstance(); } } catch (Exception e) { System.out.println("错误: " + e.getMessage()); } return null; } /** * 设置物品伤害 * @param is 物品 * @param damage 伤害 * @param slot 位置 * @return 物品的ItemStack */ public static ItemStack setItemDamage(ItemStack is, int damage, SlotType slot) { try { //物品的nms对象 Object nmsItem = is.getClass().getMethod("asNMSCopy", ItemStack.class).invoke(is, is); //物品的nbt对象 Object itemNbt = nmsItem.getClass().getMethod("getTag").invoke(nmsItem) != null ? nmsItem.getClass().getMethod("getTag").invoke(nmsItem) : NMSUtil.getNMSClass("NBTTagCompound").newInstance(); //NbtTagList对象 Object modifiers = NMSUtil.getNMSClass("NBTTagList").getConstructor().newInstance(); Object damageTag = NMSUtil.getNMSClass("NBTTagCompound").getConstructor().newInstance(); //模块数据构造 Object attackDamage = NMSUtil.getNMSClass("NBTTagString").getConstructor(String.class).newInstance("generic.attackDamage"); Object name = NMSUtil.getNMSClass("NBTTagString").getConstructor(String.class).newInstance("Damage"); Object amount = NMSUtil.getNMSClass("NBTTagInt").getConstructor(Integer.TYPE).newInstance(damage); Object operation = NMSUtil.getNMSClass("NBTTagInt").getConstructor(Integer.TYPE).newInstance(0); Object uuidLeast = NMSUtil.getNMSClass("NBTTagInt").getConstructor(Integer.TYPE).newInstance(894654); Object uuidMost = NMSUtil.getNMSClass("NBTTagInt").getConstructor(Integer.TYPE).newInstance(2872); Object slotTag = NMSUtil.getNMSClass("NBTTagString").getConstructor(String.class).newInstance(slot.toString()); //模块数据输入 damageTag.getClass().getMethod("set", new Class[] {String.class, NMSUtil.getNMSClass("NBTBase")}).invoke(damageTag, new Object[] { "AttributeName" , attackDamage}); damageTag.getClass().getMethod("set", new Class[] {String.class, NMSUtil.getNMSClass("NBTBase")}).invoke(damageTag, new Object[] { "Name" , name}); damageTag.getClass().getMethod("set", new Class[] {String.class, NMSUtil.getNMSClass("NBTBase")}).invoke(damageTag, new Object[] { "Amount" , amount}); damageTag.getClass().getMethod("set", new Class[] {String.class, NMSUtil.getNMSClass("NBTBase")}).invoke(damageTag, new Object[] { "Operation" , operation}); damageTag.getClass().getMethod("set", new Class[] {String.class, NMSUtil.getNMSClass("NBTBase")}).invoke(damageTag, new Object[] { "UUIDLeast" , uuidLeast}); damageTag.getClass().getMethod("set", new Class[] {String.class, NMSUtil.getNMSClass("NBTBase")}).invoke(damageTag, new Object[] { "UUIDMost" , uuidMost}); damageTag.getClass().getMethod("set", new Class[] {String.class, NMSUtil.getNMSClass("NBTBase")}).invoke(damageTag, new Object[] { "Slot" , slotTag}); //NbtTagList数据导入 modifiers.getClass().getMethod("add", NMSUtil.getNMSClass("NBTBase")).invoke(modifiers, damageTag); //设置该NbtTagList itemNbt.getClass().getMethod("set", new Class[] {String.class, NMSUtil.getNMSClass("NBTBase")}).invoke(itemNbt, new Object[] { "AttributeModifiers", modifiers}); //保存nbt数据 nmsItem.getClass().getMethod("setTag", NMSUtil.getNMSClass("NBTTagCompound")).invoke(nmsItem, itemNbt); ItemStack bukItem = (ItemStack) is.getClass().getMethod("asBukkitCopy", NMSUtil.getNMSClass("ItemStack")).invoke(nmsItem, nmsItem); return bukItem; } catch (Exception e) { System.out.println("错误: " + e.getMessage()); } return is; } }
Server-CT/SCT_Core
src/org/sct/core/util/NBTUtil.java
2,302
//模块数据构造
line_comment
zh-cn
package org.sct.core.util; import java.lang.reflect.Method; import org.sct.core.dto.SlotType; import org.bukkit.craftbukkit.v1_11_R1.inventory.CraftItemStack; import org.bukkit.inventory.ItemStack; import net.minecraft.server.v1_11_R1.NBTTagByte; import net.minecraft.server.v1_11_R1.NBTTagCompound; public class NBTUtil { // /** // * 各类属性 // */ // private static String attackDamage = "generic.attackDamage"; // private static String attackSpeed = "generic.attackSpeed"; // private static String maxHealth = "generic.maxHealth"; // private static String moveMentSpeed = "generic.movementSpeed"; // private static String armor = "generic.armor"; // private static String luck = "generic.luck"; // public static Object NBTTagString(String str) { // try { // return NMSUtil.getNMSClass("NBTTagString").getConstructor(String.class).newInstance(str); // } catch (Exception e) { // System.out.println("错误: " + e.getMessage()); // } // return null; // } public static Object NBTTagInt(int num) { try { return NMSUtil.getNMSClass("NBTTagInt").getConstructor(Integer.TYPE).newInstance(num); } catch (Exception e) { System.out.println("错误: " + e.getMessage()); } return null; } public static Object NBTTagDouble(double num) { try { return NMSUtil.getNMSClass("NBTTagDouble").getConstructor(Double.TYPE).newInstance(num); } catch (Exception e) { System.out.println("错误: " + e.getMessage()); } return null; } // // public static Object NBTTagByte(byte num) { // try { // return NMSUtil.getNMSClass("NBTTagByte").getConstructor(Byte.TYPE).newInstance(num); // } catch (Exception e) { // System.out.println("错误: " + e.getMessage()); // } // return null; // } public static Object NBTTagFloat(float num) { try { return NMSUtil.getNMSClass("NBTTagFloat").getConstructor(Float.TYPE).newInstance(num); } catch (Exception e) { System.out.println("错误: " + e.getMessage()); } return null; } public static Object getItemNBT(ItemStack is) { Object nmsItem = NMSUtil.getNMSItem(is); if (nmsItem == null) { return null; } try { return nmsItem.getClass().getMethod("getTag").invoke(nmsItem) != null ? nmsItem.getClass().getMethod("getTag").invoke(nmsItem) : NMSUtil.getNMSClass("NBTTagCompound").newInstance(); } catch (Exception e) { System.out.println("错误: " + e.getMessage()); } return null; } public static void setUnbreakable(ItemStack is, boolean unbreak) { Object nmsItem = NMSUtil.getNMSItem(is); Object itemNbt = getItemNBT(is); Method set; //ItemStack bukItem = null; try { net.minecraft.server.v1_11_R1.ItemStack nms = CraftItemStack.asNMSCopy(is); NBTTagCompound nbt = nms.hasTag() ? nms.getTag() : new NBTTagCompound(); System.out.println(nbt); nbt.set("Unbreakable", new NBTTagByte((byte) 1)); //set = itemNbt.getClass().getMethod("set", new Class[] { String.class, NMSUtil.getNMSClass("NBTBase") }); //set.invoke(itemNbt, new Object[] { "Unbreakable", new net.minecraft.server.v1_10_R1.NBTTagByte((byte) 1)}); //set.invoke(itemNbt, new Object[] { "Unbreakable", NBTTagByte() }); //itemNbt.set("Unbreakable", new NBTTagByte((byte) (unbreak ? 1 : 0))); //nmsItem.getClass().getMethod("setTag", NMSUtil.getNMSClass("NBTTagCompound")).invoke(nmsItem, itemNbt); nms.setTag(nbt); System.out.println(nbt); //nmsItem.setTag(itemNbt); //bukItem = (ItemStack) NMSUtil.getOBCClass("inventory.CraftItemStack").getMethod("asBukkitCopy", NMSUtil.getNMSClass("ItemStack")).invoke(nmsItem, nmsItem); } catch (Exception e) { e.printStackTrace(); } //return bukItem; } /** * 取武器的Attribute数据 * @param is 物品 * @return NBTTagCompound的实例 */ public static Object getAttribute(ItemStack is) { Object nmsItem = NMSUtil.getNMSItem(is); //判断是否有无Tag数据 try { if (nmsItem.getClass().getMethod("getTag").invoke(nmsItem) != null) { return nmsItem.getClass().getMethod("getTag").invoke(nmsItem); }else { //如果没有Tag数据则实例化个NBTTagCompound的实例 return NMSUtil.getNMSClass("NBTTagCompound").newInstance(); } } catch (Exception e) { System.out.println("错误: " + e.getMessage()); } return null; } /** * 设置物品伤害 * @param is 物品 * @param damage 伤害 * @param slot 位置 * @return 物品的ItemStack */ public static ItemStack setItemDamage(ItemStack is, int damage, SlotType slot) { try { //物品的nms对象 Object nmsItem = is.getClass().getMethod("asNMSCopy", ItemStack.class).invoke(is, is); //物品的nbt对象 Object itemNbt = nmsItem.getClass().getMethod("getTag").invoke(nmsItem) != null ? nmsItem.getClass().getMethod("getTag").invoke(nmsItem) : NMSUtil.getNMSClass("NBTTagCompound").newInstance(); //NbtTagList对象 Object modifiers = NMSUtil.getNMSClass("NBTTagList").getConstructor().newInstance(); Object damageTag = NMSUtil.getNMSClass("NBTTagCompound").getConstructor().newInstance(); //模块 <SUF> Object attackDamage = NMSUtil.getNMSClass("NBTTagString").getConstructor(String.class).newInstance("generic.attackDamage"); Object name = NMSUtil.getNMSClass("NBTTagString").getConstructor(String.class).newInstance("Damage"); Object amount = NMSUtil.getNMSClass("NBTTagInt").getConstructor(Integer.TYPE).newInstance(damage); Object operation = NMSUtil.getNMSClass("NBTTagInt").getConstructor(Integer.TYPE).newInstance(0); Object uuidLeast = NMSUtil.getNMSClass("NBTTagInt").getConstructor(Integer.TYPE).newInstance(894654); Object uuidMost = NMSUtil.getNMSClass("NBTTagInt").getConstructor(Integer.TYPE).newInstance(2872); Object slotTag = NMSUtil.getNMSClass("NBTTagString").getConstructor(String.class).newInstance(slot.toString()); //模块数据输入 damageTag.getClass().getMethod("set", new Class[] {String.class, NMSUtil.getNMSClass("NBTBase")}).invoke(damageTag, new Object[] { "AttributeName" , attackDamage}); damageTag.getClass().getMethod("set", new Class[] {String.class, NMSUtil.getNMSClass("NBTBase")}).invoke(damageTag, new Object[] { "Name" , name}); damageTag.getClass().getMethod("set", new Class[] {String.class, NMSUtil.getNMSClass("NBTBase")}).invoke(damageTag, new Object[] { "Amount" , amount}); damageTag.getClass().getMethod("set", new Class[] {String.class, NMSUtil.getNMSClass("NBTBase")}).invoke(damageTag, new Object[] { "Operation" , operation}); damageTag.getClass().getMethod("set", new Class[] {String.class, NMSUtil.getNMSClass("NBTBase")}).invoke(damageTag, new Object[] { "UUIDLeast" , uuidLeast}); damageTag.getClass().getMethod("set", new Class[] {String.class, NMSUtil.getNMSClass("NBTBase")}).invoke(damageTag, new Object[] { "UUIDMost" , uuidMost}); damageTag.getClass().getMethod("set", new Class[] {String.class, NMSUtil.getNMSClass("NBTBase")}).invoke(damageTag, new Object[] { "Slot" , slotTag}); //NbtTagList数据导入 modifiers.getClass().getMethod("add", NMSUtil.getNMSClass("NBTBase")).invoke(modifiers, damageTag); //设置该NbtTagList itemNbt.getClass().getMethod("set", new Class[] {String.class, NMSUtil.getNMSClass("NBTBase")}).invoke(itemNbt, new Object[] { "AttributeModifiers", modifiers}); //保存nbt数据 nmsItem.getClass().getMethod("setTag", NMSUtil.getNMSClass("NBTTagCompound")).invoke(nmsItem, itemNbt); ItemStack bukItem = (ItemStack) is.getClass().getMethod("asBukkitCopy", NMSUtil.getNMSClass("ItemStack")).invoke(nmsItem, nmsItem); return bukItem; } catch (Exception e) { System.out.println("错误: " + e.getMessage()); } return is; } }
false
2,113
4
2,302
4
2,403
4
2,302
4
2,786
9
false
false
false
false
false
true
9416_3
import java.util.Scanner; public class RepeaterG { public static final String NAME = "复读姬"; public static final String VERSION = "v1.0.0"; public static final String COPYRIGHT = "(C) 2023 SessionHu"; public static void info() { System.out.println(); System.out.println(NAME+" "+VERSION); System.out.println(COPYRIGHT); System.out.println("输入 \"exit\" 退出"); System.out.println("-----------------------"); } public static void run() { String input = ""; // 初始化 try (Scanner scan = new Scanner(System.in)) { while(true) { // 循环 System.out.print(" 你: "); input = scan.nextLine(); switch (input) { case "exit": // 正常退出 System.out.println("复读姬: 再见!"); System.exit(0); break; default: // 正常输出 System.out.format("复读姬: %s%n", input); break; } } } } public static void main(String[] args) { info(); // 输出软件信息 run(); // 运行 } }
SessionHu/RepeaterG
RepeaterG.java
325
// 输出软件信息
line_comment
zh-cn
import java.util.Scanner; public class RepeaterG { public static final String NAME = "复读姬"; public static final String VERSION = "v1.0.0"; public static final String COPYRIGHT = "(C) 2023 SessionHu"; public static void info() { System.out.println(); System.out.println(NAME+" "+VERSION); System.out.println(COPYRIGHT); System.out.println("输入 \"exit\" 退出"); System.out.println("-----------------------"); } public static void run() { String input = ""; // 初始化 try (Scanner scan = new Scanner(System.in)) { while(true) { // 循环 System.out.print(" 你: "); input = scan.nextLine(); switch (input) { case "exit": // 正常退出 System.out.println("复读姬: 再见!"); System.exit(0); break; default: // 正常输出 System.out.format("复读姬: %s%n", input); break; } } } } public static void main(String[] args) { info(); // 输出 <SUF> run(); // 运行 } }
false
270
4
325
5
328
4
325
5
454
10
false
false
false
false
false
true
40413_25
package cn.ztuo.bitrade.entity; import cn.afterturn.easypoi.excel.annotation.Excel; import cn.ztuo.bitrade.constant.BooleanEnum; import cn.ztuo.bitrade.constant.CommonStatus; import cn.ztuo.bitrade.dto.CoinDTO; import com.fasterxml.jackson.annotation.JsonFormat; import com.fasterxml.jackson.annotation.JsonIgnore; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.ToString; import org.hibernate.annotations.CreationTimestamp; import javax.persistence.*; import javax.validation.constraints.NotBlank; import java.math.BigDecimal; import java.util.Date; import java.util.List; /** * @author MrGao * @description * @date 2017/12/29 14:14 */ @Entity @Data @Table(name = "coin") @ToString(exclude = {"coinChainRelationList"}) @EqualsAndHashCode(exclude = {"coinChainRelationList"}) public class Coin { @Id @NotBlank(message = "{Coin.name.blank}") @Excel(name = "货币", orderNum = "1", width = 20) private String name; /** * 中文 */ @Excel(name = "中文名称", orderNum = "1", width = 20) @NotBlank(message = "{Coin.nameCn.blank}") private String nameCn; /** * 缩写 */ @Excel(name = "单位", orderNum = "1", width = 20) @NotBlank(message = "{Coin.unit.blank}") private String unit; /** * 状态 */ @Enumerated(EnumType.ORDINAL) private CommonStatus status = CommonStatus.NORMAL; /** * 最小提币手续费 */ @Excel(name = "最小提币手续费", orderNum = "1", width = 20) private BigDecimal minTxFee; /** * 对人民币汇率 */ @Excel(name = "对人民币汇率", orderNum = "1", width = 20) @Column(columnDefinition = "decimal(20,8) default 0.00 comment '人民币汇率'") private BigDecimal cnyRate; /** * 最大提币手续费 */ /*@Deprecated*/ @Excel(name = "最大提币手续费", orderNum = "1", width = 20) private BigDecimal maxTxFee; /** * 对美元汇率 */ @Excel(name = "对美元汇率", orderNum = "1", width = 20) @Column(columnDefinition = "decimal(20,8) default 0.00 comment '美元汇率'") private BigDecimal usdRate; /** * 对新加坡币汇率 */ @Excel(name = "对新加坡币汇率", orderNum = "1", width = 20) @Column(columnDefinition = "decimal(12,6) default 0.00 comment '对新加坡币汇率'") private BigDecimal sgdRate; /** * 是否支持rpc接口 */ @Enumerated(EnumType.ORDINAL) private BooleanEnum enableRpc = BooleanEnum.IS_TRUE; /** * 排序 */ private int sort=10; /** * 是否能提币 */ @Enumerated(EnumType.ORDINAL) private BooleanEnum canWithdraw=BooleanEnum.IS_TRUE; /** * 是否能充币 */ @Enumerated(EnumType.ORDINAL) private BooleanEnum canRecharge=BooleanEnum.IS_TRUE; /** * 是否能转账 */ @Enumerated(EnumType.ORDINAL) private BooleanEnum canTransfer = BooleanEnum.IS_TRUE; /** * 是否能自动提币 */ @Enumerated(EnumType.ORDINAL) private BooleanEnum canAutoWithdraw=BooleanEnum.IS_FALSE; /** * 提币阈值 */ @Column(columnDefinition = "decimal(20,8) comment '自动提现阈值'") private BigDecimal withdrawThreshold; @Column(columnDefinition = "decimal(20,8) comment '最小提币数量'") private BigDecimal minWithdrawAmount; @Column(columnDefinition = "decimal(20,8) comment '最大提币数量'") private BigDecimal maxWithdrawAmount; /** * 是否是平台币 */ @Enumerated(EnumType.ORDINAL) @Column(columnDefinition = "int default 0 comment '是否为平台币'") private BooleanEnum isPlatformCoin = BooleanEnum.IS_FALSE; /** * 是否是法币 */ @Column(name = "has_legal", columnDefinition = "bit default 0", nullable = false) private Boolean hasLegal = false; @Transient private BigDecimal allBalance ; private String coldWalletAddress ; @Transient private BigDecimal hotAllBalance ; /** * 转账时付给矿工的手续费 */ @Column(columnDefinition = "decimal(20,8) default 0 comment '矿工费'") private BigDecimal minerFee = BigDecimal.ZERO; @Column(columnDefinition = "int default 4 comment '提币精度'") private int withdrawScale; @Column(columnDefinition = "decimal(20,8) default 0 comment '最小充币数量'") private BigDecimal minRechargeAmount = BigDecimal.ZERO; @Column(columnDefinition = "varchar(64) default null comment '主充值地址'") private String masterAddress; @Column(columnDefinition = "decimal(20,8) default 0 comment '单日最大提币量'") private BigDecimal maxDailyWithdrawRate=BigDecimal.ZERO; /** * 图片地址 */ @Excel(name = "图片地址", orderNum = "1", width = 20) @Column(columnDefinition = "varchar(255) default null comment '图片地址'") private String imgUrl; /** * 发型总量 */ @Excel(name = "发型总量", orderNum = "1", width = 20) @Column(columnDefinition = "decimal(20,8) default 0 comment '发型总量'") private BigDecimal releaseAmount; /** * 发行时间 */ @Excel(name = "发行时间", orderNum = "1", width = 20) @CreationTimestamp @JsonFormat(pattern = "yyyy-MM-dd", timezone = "GMT+8") @Column(columnDefinition = "datetime NULL DEFAULT NULL COMMENT '发行时间'") private Date releaseTime; /** * 众筹价格 */ @Excel(name = "众筹价格", orderNum = "1", width = 20) @Column(columnDefinition = "varchar(255) default null comment '众筹价格'") private String fundPrice; /** * 白皮书 */ @Excel(name = "白皮书", orderNum = "1", width = 20) @Column(columnDefinition = "varchar(255) default null comment '白皮书'") private String whitePaper; /** * 官网 */ @Excel(name = "官网", orderNum = "1", width = 20) @Column(columnDefinition = "varchar(255) default null comment '官网'") private String website; /** * 区块查询 */ @Excel(name = "区块查询", orderNum = "1", width = 20) @Column(columnDefinition = "varchar(255) default null comment '区块查询'") private String blockQuery; @Transient private CoinDTO coinInfo; /** * 是否是结算币种 */ @Column(name = "is_settlement", columnDefinition = "bit default 0", nullable = false) private Boolean isSettlement = false; @Column(columnDefinition = "decimal(20,8) default 0 comment '销毁总量'") private BigDecimal burnAmount = BigDecimal.ZERO; @Column(columnDefinition = "decimal(20,8) default 0 comment '流通总量'") private BigDecimal circulateAmount = BigDecimal.ZERO; @OneToMany(fetch = FetchType.EAGER, mappedBy="coin") @JsonIgnore private List<CoinChainRelation> coinChainRelationList; }
SevenEX/bitrade-parent
core/src/main/java/cn/ztuo/bitrade/entity/Coin.java
1,974
/** * 官网 */
block_comment
zh-cn
package cn.ztuo.bitrade.entity; import cn.afterturn.easypoi.excel.annotation.Excel; import cn.ztuo.bitrade.constant.BooleanEnum; import cn.ztuo.bitrade.constant.CommonStatus; import cn.ztuo.bitrade.dto.CoinDTO; import com.fasterxml.jackson.annotation.JsonFormat; import com.fasterxml.jackson.annotation.JsonIgnore; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.ToString; import org.hibernate.annotations.CreationTimestamp; import javax.persistence.*; import javax.validation.constraints.NotBlank; import java.math.BigDecimal; import java.util.Date; import java.util.List; /** * @author MrGao * @description * @date 2017/12/29 14:14 */ @Entity @Data @Table(name = "coin") @ToString(exclude = {"coinChainRelationList"}) @EqualsAndHashCode(exclude = {"coinChainRelationList"}) public class Coin { @Id @NotBlank(message = "{Coin.name.blank}") @Excel(name = "货币", orderNum = "1", width = 20) private String name; /** * 中文 */ @Excel(name = "中文名称", orderNum = "1", width = 20) @NotBlank(message = "{Coin.nameCn.blank}") private String nameCn; /** * 缩写 */ @Excel(name = "单位", orderNum = "1", width = 20) @NotBlank(message = "{Coin.unit.blank}") private String unit; /** * 状态 */ @Enumerated(EnumType.ORDINAL) private CommonStatus status = CommonStatus.NORMAL; /** * 最小提币手续费 */ @Excel(name = "最小提币手续费", orderNum = "1", width = 20) private BigDecimal minTxFee; /** * 对人民币汇率 */ @Excel(name = "对人民币汇率", orderNum = "1", width = 20) @Column(columnDefinition = "decimal(20,8) default 0.00 comment '人民币汇率'") private BigDecimal cnyRate; /** * 最大提币手续费 */ /*@Deprecated*/ @Excel(name = "最大提币手续费", orderNum = "1", width = 20) private BigDecimal maxTxFee; /** * 对美元汇率 */ @Excel(name = "对美元汇率", orderNum = "1", width = 20) @Column(columnDefinition = "decimal(20,8) default 0.00 comment '美元汇率'") private BigDecimal usdRate; /** * 对新加坡币汇率 */ @Excel(name = "对新加坡币汇率", orderNum = "1", width = 20) @Column(columnDefinition = "decimal(12,6) default 0.00 comment '对新加坡币汇率'") private BigDecimal sgdRate; /** * 是否支持rpc接口 */ @Enumerated(EnumType.ORDINAL) private BooleanEnum enableRpc = BooleanEnum.IS_TRUE; /** * 排序 */ private int sort=10; /** * 是否能提币 */ @Enumerated(EnumType.ORDINAL) private BooleanEnum canWithdraw=BooleanEnum.IS_TRUE; /** * 是否能充币 */ @Enumerated(EnumType.ORDINAL) private BooleanEnum canRecharge=BooleanEnum.IS_TRUE; /** * 是否能转账 */ @Enumerated(EnumType.ORDINAL) private BooleanEnum canTransfer = BooleanEnum.IS_TRUE; /** * 是否能自动提币 */ @Enumerated(EnumType.ORDINAL) private BooleanEnum canAutoWithdraw=BooleanEnum.IS_FALSE; /** * 提币阈值 */ @Column(columnDefinition = "decimal(20,8) comment '自动提现阈值'") private BigDecimal withdrawThreshold; @Column(columnDefinition = "decimal(20,8) comment '最小提币数量'") private BigDecimal minWithdrawAmount; @Column(columnDefinition = "decimal(20,8) comment '最大提币数量'") private BigDecimal maxWithdrawAmount; /** * 是否是平台币 */ @Enumerated(EnumType.ORDINAL) @Column(columnDefinition = "int default 0 comment '是否为平台币'") private BooleanEnum isPlatformCoin = BooleanEnum.IS_FALSE; /** * 是否是法币 */ @Column(name = "has_legal", columnDefinition = "bit default 0", nullable = false) private Boolean hasLegal = false; @Transient private BigDecimal allBalance ; private String coldWalletAddress ; @Transient private BigDecimal hotAllBalance ; /** * 转账时付给矿工的手续费 */ @Column(columnDefinition = "decimal(20,8) default 0 comment '矿工费'") private BigDecimal minerFee = BigDecimal.ZERO; @Column(columnDefinition = "int default 4 comment '提币精度'") private int withdrawScale; @Column(columnDefinition = "decimal(20,8) default 0 comment '最小充币数量'") private BigDecimal minRechargeAmount = BigDecimal.ZERO; @Column(columnDefinition = "varchar(64) default null comment '主充值地址'") private String masterAddress; @Column(columnDefinition = "decimal(20,8) default 0 comment '单日最大提币量'") private BigDecimal maxDailyWithdrawRate=BigDecimal.ZERO; /** * 图片地址 */ @Excel(name = "图片地址", orderNum = "1", width = 20) @Column(columnDefinition = "varchar(255) default null comment '图片地址'") private String imgUrl; /** * 发型总量 */ @Excel(name = "发型总量", orderNum = "1", width = 20) @Column(columnDefinition = "decimal(20,8) default 0 comment '发型总量'") private BigDecimal releaseAmount; /** * 发行时间 */ @Excel(name = "发行时间", orderNum = "1", width = 20) @CreationTimestamp @JsonFormat(pattern = "yyyy-MM-dd", timezone = "GMT+8") @Column(columnDefinition = "datetime NULL DEFAULT NULL COMMENT '发行时间'") private Date releaseTime; /** * 众筹价格 */ @Excel(name = "众筹价格", orderNum = "1", width = 20) @Column(columnDefinition = "varchar(255) default null comment '众筹价格'") private String fundPrice; /** * 白皮书 */ @Excel(name = "白皮书", orderNum = "1", width = 20) @Column(columnDefinition = "varchar(255) default null comment '白皮书'") private String whitePaper; /** * 官网 <SUF>*/ @Excel(name = "官网", orderNum = "1", width = 20) @Column(columnDefinition = "varchar(255) default null comment '官网'") private String website; /** * 区块查询 */ @Excel(name = "区块查询", orderNum = "1", width = 20) @Column(columnDefinition = "varchar(255) default null comment '区块查询'") private String blockQuery; @Transient private CoinDTO coinInfo; /** * 是否是结算币种 */ @Column(name = "is_settlement", columnDefinition = "bit default 0", nullable = false) private Boolean isSettlement = false; @Column(columnDefinition = "decimal(20,8) default 0 comment '销毁总量'") private BigDecimal burnAmount = BigDecimal.ZERO; @Column(columnDefinition = "decimal(20,8) default 0 comment '流通总量'") private BigDecimal circulateAmount = BigDecimal.ZERO; @OneToMany(fetch = FetchType.EAGER, mappedBy="coin") @JsonIgnore private List<CoinChainRelation> coinChainRelationList; }
false
1,782
9
1,974
8
2,048
8
1,974
8
2,582
10
false
false
false
false
false
true
65444_2
package next.operator.linebot.talker; import com.linecorp.bot.client.LineMessagingClient; import com.linecorp.bot.model.event.MessageEvent; import com.linecorp.bot.model.event.message.TextMessageContent; import next.operator.currency.enums.CurrencyType; import next.operator.currency.model.CurrencyExrateModel; import next.operator.currency.service.CurrencyService; import next.operator.linebot.executor.impl.ExrateExecutor; import next.operator.linebot.service.RespondentService; import next.operator.linebot.service.RespondentTalkable; import next.operator.utils.NumberUtils; import org.ansj.domain.Term; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.math.BigDecimal; import java.util.List; import java.util.Optional; import java.util.function.Consumer; /** * 當對話中出現錢幣關鍵字時提供匯率資料 */ @Service public class ExrateTalker implements RespondentTalkable { @Autowired private ExrateExecutor exrateExecutor; @Autowired private CurrencyService currencyService; private ThreadLocal<Term> matched = new ThreadLocal<>(); private ThreadLocal<Double> amount = new ThreadLocal<>(); @Override public boolean isReadable(String message) { // 檢查是否有存在符合幣別的單字 final List<Term> terms = RespondentService.currentTern.get(); final Optional<Term> matchedTerm = terms.stream() .filter(t -> { final Optional<CurrencyType> currencyType = CurrencyType.tryParseByName(t.getName()); return currencyType.filter(type -> CurrencyType.TWD != type).isPresent(); }) .findFirst(); final boolean isMatch = matchedTerm.isPresent(); if (isMatch) { // 檢查是否存在數字 final double sum = terms.stream() .filter(t -> "m".equals(t.getNatureStr()) || "nw".equals(t.getNatureStr())) .mapToDouble(t -> Optional.ofNullable(NumberUtils.tryDouble(t.getName())).orElseGet(() -> Optional.ofNullable(NumberUtils.zhNumConvertToInt(t.getName())).orElse(1D))) .sum(); amount.set(sum); matched.set(matchedTerm.get()); } else { matched.remove(); amount.remove(); } return isMatch; } @Override public Consumer<MessageEvent<TextMessageContent>> doFirst(LineMessagingClient client) { return null; } @Override public String talk(String message) { final Term term = matched.get(); final Double amount = Optional.ofNullable(this.amount.get()).filter(n -> n != 0).orElse(1D); matched.remove(); this.amount.remove(); final CurrencyType matchedCurrenctType = CurrencyType.tryParseByName(term.getName()).get(); // isReadable已經檢查過,必定有值 final CurrencyExrateModel exrate = currencyService.getExrate(matchedCurrenctType.name(), CurrencyType.TWD.name()); return "我感覺到了你想知道" + matchedCurrenctType.getFirstLocalName() + "的匯率!\n" + exrateExecutor.decimalFormat.format(BigDecimal.valueOf(amount)) + " " + exrate.getExFrom() + " = " + exrateExecutor.decimalFormat.format(exrate.getExrate().multiply(BigDecimal.valueOf(amount))) + " " + exrate.getExTo() + ", 資料時間:" + exrateExecutor.dateTimeFormatter.format(exrate.getTime()); } }
Sevenflanks/linebot-operator-next
src/main/java/next/operator/linebot/talker/ExrateTalker.java
891
// 檢查是否存在數字
line_comment
zh-cn
package next.operator.linebot.talker; import com.linecorp.bot.client.LineMessagingClient; import com.linecorp.bot.model.event.MessageEvent; import com.linecorp.bot.model.event.message.TextMessageContent; import next.operator.currency.enums.CurrencyType; import next.operator.currency.model.CurrencyExrateModel; import next.operator.currency.service.CurrencyService; import next.operator.linebot.executor.impl.ExrateExecutor; import next.operator.linebot.service.RespondentService; import next.operator.linebot.service.RespondentTalkable; import next.operator.utils.NumberUtils; import org.ansj.domain.Term; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.math.BigDecimal; import java.util.List; import java.util.Optional; import java.util.function.Consumer; /** * 當對話中出現錢幣關鍵字時提供匯率資料 */ @Service public class ExrateTalker implements RespondentTalkable { @Autowired private ExrateExecutor exrateExecutor; @Autowired private CurrencyService currencyService; private ThreadLocal<Term> matched = new ThreadLocal<>(); private ThreadLocal<Double> amount = new ThreadLocal<>(); @Override public boolean isReadable(String message) { // 檢查是否有存在符合幣別的單字 final List<Term> terms = RespondentService.currentTern.get(); final Optional<Term> matchedTerm = terms.stream() .filter(t -> { final Optional<CurrencyType> currencyType = CurrencyType.tryParseByName(t.getName()); return currencyType.filter(type -> CurrencyType.TWD != type).isPresent(); }) .findFirst(); final boolean isMatch = matchedTerm.isPresent(); if (isMatch) { // 檢查 <SUF> final double sum = terms.stream() .filter(t -> "m".equals(t.getNatureStr()) || "nw".equals(t.getNatureStr())) .mapToDouble(t -> Optional.ofNullable(NumberUtils.tryDouble(t.getName())).orElseGet(() -> Optional.ofNullable(NumberUtils.zhNumConvertToInt(t.getName())).orElse(1D))) .sum(); amount.set(sum); matched.set(matchedTerm.get()); } else { matched.remove(); amount.remove(); } return isMatch; } @Override public Consumer<MessageEvent<TextMessageContent>> doFirst(LineMessagingClient client) { return null; } @Override public String talk(String message) { final Term term = matched.get(); final Double amount = Optional.ofNullable(this.amount.get()).filter(n -> n != 0).orElse(1D); matched.remove(); this.amount.remove(); final CurrencyType matchedCurrenctType = CurrencyType.tryParseByName(term.getName()).get(); // isReadable已經檢查過,必定有值 final CurrencyExrateModel exrate = currencyService.getExrate(matchedCurrenctType.name(), CurrencyType.TWD.name()); return "我感覺到了你想知道" + matchedCurrenctType.getFirstLocalName() + "的匯率!\n" + exrateExecutor.decimalFormat.format(BigDecimal.valueOf(amount)) + " " + exrate.getExFrom() + " = " + exrateExecutor.decimalFormat.format(exrate.getExrate().multiply(BigDecimal.valueOf(amount))) + " " + exrate.getExTo() + ", 資料時間:" + exrateExecutor.dateTimeFormatter.format(exrate.getTime()); } }
false
721
8
891
9
898
5
891
9
1,060
14
false
false
false
false
false
true
65443_7
package tw.org.sevenflanks.sa.stock.model; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; /** * 上櫃公司 * ps. 有些欄位感覺用不到而且感覺很難命名,先用other代替 */ @Getter @Setter @NoArgsConstructor public class OtcCompanyModel { /** 出表日期 */ private String dataDate; /** 公司代號 */ private String uid; /** 公司名稱 */ private String fullName; /** 公司簡稱 */ private String shortName; /** 外國企業註冊地國 */ private String country; /** 產業別 */ private String industry; /** 住址 */ private String address; /** 營利事業統一編號 */ private String taxId; /** 董事長 */ private String chairman; /** 總經理 */ private String gm; /** 發言人 */ private String spokesman; /** 發言人職稱 */ private String spokesmanTitie; /** 代理發言人 */ private String spokesmanAssist; /** 總機電話 */ private String phone; /** 成立日期 */ private String establishDate; /** 上市日期 */ private String listedDate; /** 普通股每股面額 */ private String ordinaryValue; /** 實收資本額 */ private String contributedCapital; /** 私募股數 */ private String other1; /** 特別股 */ private String other2; /** 編制財務報表類型 */ private String other3; /** 股票過戶機構 */ private String other4; /** 過戶電話 */ private String other5; /** 過戶地址 */ private String Other6; /** 簽證會計師事務所 */ private String other7; /** 簽證會計師1 */ private String other8; /** 簽證會計師2 */ private String other9; /** 英文簡稱 */ private String shortEngName; /** 英文通訊地址 */ private String engAddress; /** 傳真機號碼 */ private String fax; /** 電子郵件信箱 */ private String email; /** 網址 */ private String homepage; @Override public String toString() { return "TwseCompanyModel{" + "dataDate='" + dataDate + '\'' + ", uid='" + uid + '\'' + ", fullName='" + fullName + '\'' + ", shortName='" + shortName + '\'' + ", country='" + country + '\'' + ", industry='" + industry + '\'' + ", address='" + address + '\'' + ", taxId='" + taxId + '\'' + ", chairman='" + chairman + '\'' + ", gm='" + gm + '\'' + ", spokesman='" + spokesman + '\'' + ", spokesmanTitie='" + spokesmanTitie + '\'' + ", spokesmanAssist='" + spokesmanAssist + '\'' + ", phone='" + phone + '\'' + ", establishDate='" + establishDate + '\'' + ", listedDate='" + listedDate + '\'' + ", ordinaryValue='" + ordinaryValue + '\'' + ", contributedCapital='" + contributedCapital + '\'' + ", shortEngName='" + shortEngName + '\'' + ", engAddress='" + engAddress + '\'' + ", fax='" + fax + '\'' + ", email='" + email + '\'' + ", homepage='" + homepage + '\'' + '}'; } }
Sevenflanks/stock-assistor
src/main/java/tw/org/sevenflanks/sa/stock/model/OtcCompanyModel.java
976
/** 住址 */
block_comment
zh-cn
package tw.org.sevenflanks.sa.stock.model; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; /** * 上櫃公司 * ps. 有些欄位感覺用不到而且感覺很難命名,先用other代替 */ @Getter @Setter @NoArgsConstructor public class OtcCompanyModel { /** 出表日期 */ private String dataDate; /** 公司代號 */ private String uid; /** 公司名稱 */ private String fullName; /** 公司簡稱 */ private String shortName; /** 外國企業註冊地國 */ private String country; /** 產業別 */ private String industry; /** 住址 <SUF>*/ private String address; /** 營利事業統一編號 */ private String taxId; /** 董事長 */ private String chairman; /** 總經理 */ private String gm; /** 發言人 */ private String spokesman; /** 發言人職稱 */ private String spokesmanTitie; /** 代理發言人 */ private String spokesmanAssist; /** 總機電話 */ private String phone; /** 成立日期 */ private String establishDate; /** 上市日期 */ private String listedDate; /** 普通股每股面額 */ private String ordinaryValue; /** 實收資本額 */ private String contributedCapital; /** 私募股數 */ private String other1; /** 特別股 */ private String other2; /** 編制財務報表類型 */ private String other3; /** 股票過戶機構 */ private String other4; /** 過戶電話 */ private String other5; /** 過戶地址 */ private String Other6; /** 簽證會計師事務所 */ private String other7; /** 簽證會計師1 */ private String other8; /** 簽證會計師2 */ private String other9; /** 英文簡稱 */ private String shortEngName; /** 英文通訊地址 */ private String engAddress; /** 傳真機號碼 */ private String fax; /** 電子郵件信箱 */ private String email; /** 網址 */ private String homepage; @Override public String toString() { return "TwseCompanyModel{" + "dataDate='" + dataDate + '\'' + ", uid='" + uid + '\'' + ", fullName='" + fullName + '\'' + ", shortName='" + shortName + '\'' + ", country='" + country + '\'' + ", industry='" + industry + '\'' + ", address='" + address + '\'' + ", taxId='" + taxId + '\'' + ", chairman='" + chairman + '\'' + ", gm='" + gm + '\'' + ", spokesman='" + spokesman + '\'' + ", spokesmanTitie='" + spokesmanTitie + '\'' + ", spokesmanAssist='" + spokesmanAssist + '\'' + ", phone='" + phone + '\'' + ", establishDate='" + establishDate + '\'' + ", listedDate='" + listedDate + '\'' + ", ordinaryValue='" + ordinaryValue + '\'' + ", contributedCapital='" + contributedCapital + '\'' + ", shortEngName='" + shortEngName + '\'' + ", engAddress='" + engAddress + '\'' + ", fax='" + fax + '\'' + ", email='" + email + '\'' + ", homepage='" + homepage + '\'' + '}'; } }
false
772
4
976
5
840
4
976
5
1,249
7
false
false
false
false
false
true
42392_5
import java.io.*; public class Computer {//裸机类 short page_table;//页表基址寄存器,存放页表基址 public Clock clock;//时钟 public CPU cpu;//CPU private BUS bus;//总线 public MMU mmu;//存储管理部件 private Memory memory;//内存 public Disk disk;//硬盘 private Os os; Computer(){//构造函数 clock=new Clock(); cpu=new CPU(); bus=new BUS(); mmu=new MMU(); memory=new Memory(); disk=new Disk(); page_table=0; os=new Os(this); } public void computerstart(){//开机 os.random_buton.setEnabled(false); os.read_buton.setEnabled(false); os.run_buton.setEnabled(false); os.wtite_pcb(); os.setUI_1(); new Thread(){//启动时钟 public void run(){ try { clock.clockstart(os); } catch (InterruptedException e) { e.printStackTrace(); }catch (NullPointerException e){ e.printStackTrace(); } } }.start(); new Thread(){//操作系统等待时钟中断进行调度 public void run(){ try { os.osstart(); } catch (InterruptedException e) { e.printStackTrace(); }catch (NullPointerException e){ e.printStackTrace(); } } }.start(); } class CPU{//CPU类 public short PC;//程序计数器 private short IR;//指令寄存器 private int []PSW=new int [2];//指令状态字寄存器 private int cpu_state;//CPU状态,表示内核态,1表示用户态 /* public void cpu_run(Os os){ for(;;) { if (os.q1.size() != 0) { PC = (short) os.q1.peek().PSW; if(PC==os.q1.peek().instrucnum) System.out.println(clock.gettime()+"时刻"+os.q1.peek().ProID+ "进程执行结束"); os.q1.peek().instruc_list[PC].starttime = clock.gettime(); } } }*/ } public static void main(String []Args){ Computer computer=new Computer(); } } class Clock{//时钟类 private int time;//记录系统时间,以毫秒为单位 Clock(){ time=0;//系统时间初始为0 } public void clockstart(Os os)throws InterruptedException{//每隔10毫秒系统时间加10并进行时钟中断 for(;;) { Thread.sleep(10); synchronized(this){//给Clock对象加锁 if(os.inter_flag){//线程同步,确保每次时钟中断都进行了调度 wait(); } time += 10; interrupt(os); } if(os.end_flag) break; } } public void interrupt(Os os){//时钟中断 os.inter_flag=true; notifyAll(); } public int gettime(){//获取当前时间 return time; } } class BUS{//总线类 private short addbus;//16位地址线 private short databus;//16位数据线 } class MMU{//存储管理部件类 public short add_change(Os os,short vir_add){//将逻辑地址转换为物理地址 short real_add=0; return real_add; } } class Memory{//内存类 public int memory[]=new int[64]; //共32KB,每个物理块大小512B,共64个物理块,-1表示该物理块空闲,非负表示该物理块被相应序号进程占用 Memory(){//内存初始化 for(int i=0;i<64;i++) memory[i]=-1; } } class Disk{//硬盘类 public int disk[][]=new int[32][64]; //1 个磁道中有64个扇区,1个柱面中有32个磁道,1个扇区为1个物理块,每个物理块大小512B,合计1MB //非负表示被相应序号的进程占用,-1表示空闲 Disk(){ for(int i=0;i<32;i++) for(int j=0;j<64;j++) disk[i][j] = -1; File directory=new File("."); String path=null; try{ path=directory.getCanonicalPath(); }catch(IOException e){ e.printStackTrace(); } path+="\\disk"; File file=new File(path); if(!file.exists()) file.mkdir(); String sonpath=null; for(int i=0;i<32;i++){ sonpath=path+"\\track"+String.valueOf(i+1)+".txt"; File sonfile=new File(sonpath); if(!sonfile.exists()){ try { sonfile.createNewFile(); }catch(IOException e){ e.printStackTrace(); } } try{ FileOutputStream out=new FileOutputStream(sonfile); PrintStream p=new PrintStream(out); for(int j=0;j<64;j++) { p.print("扇区" + j + ":" ); if(disk[i][j]==-1) p.println("空闲"); else p.println(disk[i][j]+"号进程"); } out.close(); p.close(); }catch(FileNotFoundException e){ e.printStackTrace(); }catch(IOException e){ e.printStackTrace(); } } } public void write(){ File directory=new File("."); String path=null; try{ path=directory.getCanonicalPath(); }catch(IOException e){ e.printStackTrace(); } path+="\\disk"; String sonpath=null; for(int i=0;i<32;i++){ sonpath=path+"\\track"+String.valueOf(i+1)+".txt"; File sonfile=new File(sonpath); try{ FileOutputStream out=new FileOutputStream(sonfile); PrintStream p=new PrintStream(out); for(int j=0;j<64;j++) { p.print("扇区" + j + ":" ); if(disk[i][j]==-1) p.println("空闲"); else p.println(disk[i][j]+"号进程"); } out.close(); p.close(); }catch(FileNotFoundException e){ e.printStackTrace(); }catch(IOException e){ e.printStackTrace(); } } System.out.println("磁盘占用情况"); for(int i=0;i<32;i++){ for(int j=0;j<64;j++) { if(disk[i][j]!=-1) System.out.print(disk[i][j] + " "); else System.out.print( "空闲 "); } System.out.println(); } } }
Shadow-Java/OS
src/Computer.java
1,702
//启动时钟
line_comment
zh-cn
import java.io.*; public class Computer {//裸机类 short page_table;//页表基址寄存器,存放页表基址 public Clock clock;//时钟 public CPU cpu;//CPU private BUS bus;//总线 public MMU mmu;//存储管理部件 private Memory memory;//内存 public Disk disk;//硬盘 private Os os; Computer(){//构造函数 clock=new Clock(); cpu=new CPU(); bus=new BUS(); mmu=new MMU(); memory=new Memory(); disk=new Disk(); page_table=0; os=new Os(this); } public void computerstart(){//开机 os.random_buton.setEnabled(false); os.read_buton.setEnabled(false); os.run_buton.setEnabled(false); os.wtite_pcb(); os.setUI_1(); new Thread(){//启动 <SUF> public void run(){ try { clock.clockstart(os); } catch (InterruptedException e) { e.printStackTrace(); }catch (NullPointerException e){ e.printStackTrace(); } } }.start(); new Thread(){//操作系统等待时钟中断进行调度 public void run(){ try { os.osstart(); } catch (InterruptedException e) { e.printStackTrace(); }catch (NullPointerException e){ e.printStackTrace(); } } }.start(); } class CPU{//CPU类 public short PC;//程序计数器 private short IR;//指令寄存器 private int []PSW=new int [2];//指令状态字寄存器 private int cpu_state;//CPU状态,表示内核态,1表示用户态 /* public void cpu_run(Os os){ for(;;) { if (os.q1.size() != 0) { PC = (short) os.q1.peek().PSW; if(PC==os.q1.peek().instrucnum) System.out.println(clock.gettime()+"时刻"+os.q1.peek().ProID+ "进程执行结束"); os.q1.peek().instruc_list[PC].starttime = clock.gettime(); } } }*/ } public static void main(String []Args){ Computer computer=new Computer(); } } class Clock{//时钟类 private int time;//记录系统时间,以毫秒为单位 Clock(){ time=0;//系统时间初始为0 } public void clockstart(Os os)throws InterruptedException{//每隔10毫秒系统时间加10并进行时钟中断 for(;;) { Thread.sleep(10); synchronized(this){//给Clock对象加锁 if(os.inter_flag){//线程同步,确保每次时钟中断都进行了调度 wait(); } time += 10; interrupt(os); } if(os.end_flag) break; } } public void interrupt(Os os){//时钟中断 os.inter_flag=true; notifyAll(); } public int gettime(){//获取当前时间 return time; } } class BUS{//总线类 private short addbus;//16位地址线 private short databus;//16位数据线 } class MMU{//存储管理部件类 public short add_change(Os os,short vir_add){//将逻辑地址转换为物理地址 short real_add=0; return real_add; } } class Memory{//内存类 public int memory[]=new int[64]; //共32KB,每个物理块大小512B,共64个物理块,-1表示该物理块空闲,非负表示该物理块被相应序号进程占用 Memory(){//内存初始化 for(int i=0;i<64;i++) memory[i]=-1; } } class Disk{//硬盘类 public int disk[][]=new int[32][64]; //1 个磁道中有64个扇区,1个柱面中有32个磁道,1个扇区为1个物理块,每个物理块大小512B,合计1MB //非负表示被相应序号的进程占用,-1表示空闲 Disk(){ for(int i=0;i<32;i++) for(int j=0;j<64;j++) disk[i][j] = -1; File directory=new File("."); String path=null; try{ path=directory.getCanonicalPath(); }catch(IOException e){ e.printStackTrace(); } path+="\\disk"; File file=new File(path); if(!file.exists()) file.mkdir(); String sonpath=null; for(int i=0;i<32;i++){ sonpath=path+"\\track"+String.valueOf(i+1)+".txt"; File sonfile=new File(sonpath); if(!sonfile.exists()){ try { sonfile.createNewFile(); }catch(IOException e){ e.printStackTrace(); } } try{ FileOutputStream out=new FileOutputStream(sonfile); PrintStream p=new PrintStream(out); for(int j=0;j<64;j++) { p.print("扇区" + j + ":" ); if(disk[i][j]==-1) p.println("空闲"); else p.println(disk[i][j]+"号进程"); } out.close(); p.close(); }catch(FileNotFoundException e){ e.printStackTrace(); }catch(IOException e){ e.printStackTrace(); } } } public void write(){ File directory=new File("."); String path=null; try{ path=directory.getCanonicalPath(); }catch(IOException e){ e.printStackTrace(); } path+="\\disk"; String sonpath=null; for(int i=0;i<32;i++){ sonpath=path+"\\track"+String.valueOf(i+1)+".txt"; File sonfile=new File(sonpath); try{ FileOutputStream out=new FileOutputStream(sonfile); PrintStream p=new PrintStream(out); for(int j=0;j<64;j++) { p.print("扇区" + j + ":" ); if(disk[i][j]==-1) p.println("空闲"); else p.println(disk[i][j]+"号进程"); } out.close(); p.close(); }catch(FileNotFoundException e){ e.printStackTrace(); }catch(IOException e){ e.printStackTrace(); } } System.out.println("磁盘占用情况"); for(int i=0;i<32;i++){ for(int j=0;j<64;j++) { if(disk[i][j]!=-1) System.out.print(disk[i][j] + " "); else System.out.print( "空闲 "); } System.out.println(); } } }
false
1,500
4
1,702
4
1,815
4
1,702
4
2,357
9
false
false
false
false
false
true
32350_1
package com.zyproject.tool; import java.util.Random; public class GetRandomQuote { String[] quotes={" 不是每个人都注定成功,信念就是即使看不到未来,即使看不到希望,也依然相信自己错不了,自己选的人错不了,自己选的人生错不了。梦想,就能看到未来。", " 只有对人生尽早策划,对人生的与通过预测进行科学防范,减少不必要的损失,才能赢得一个成功的人生。世界上没有一帆风顺的人生。没有的人生如同嚼蜡,索然无味。", " 你做得越好,挑你正确的人也就越多。很多无能之人仰视成功的方式,是诋毁。出来混,难免遭遇各种阴招。那些暗地里给你使绊子的人,别理他们。把自己的事情做好,就是最好的反击。", " 成功不是衡量人生价值的最高标准,比成功更重要的,是一个人能否按自己喜欢的方式生活。做自己喜欢做的事,做自己喜欢做的人。世上没有癞蛤蟆,天鹅其实也会寂寞。", " 人的智慧包括:语言、数理逻辑、空间关系、理解能力、音乐、身体动觉、人际交往与自知之明。勤于思敏于行唯有奋斗才能成功这是最好理解又是最难做到的。", " 只要我们总结跌倒的原因,把孕育的勇气树起,告别迷惘的昨天,拥抱美好的今天,微笑面对明天,不管是从辉煌成功中走出,还是在失败中奋起,漫漫远方路,才是我们不懈的追求。", " 如果你具有积极的心态,就会把你的目标定得愈高,你的成就也将愈大。任何事情上想要取得成功,都有必要清楚那些事情的发展规律,并了解如何应用这些规律。", " 德性是具有磁性的,久而久之,有德之人的周围就会聚足人气,而且芳名远播,形成一种无形而又无价的品牌,这是成功的最大助力。", " 成功的人很明白,没有一个人能一步登天,真正使他们出类拔萃的是他们心甘情愿地一步一步往前迈进,不管道路多么崎岖。", " 幸福足什么?在我看来,幸福来源于“简单生活”。文明只是外在的依托,成功、财富只足外在的荣光,真正的卓福来自于发现真实独特的自我,保持心灵的宁静", " 人一生中,一切伟大的行动与思想,都有一个微不足道的一开始。好好扮演自己的角色,做自己该做的事情,只要一开始,就不要停止,只要不停止,就会有成功。", " 人人都有梦想,都渴望成功,都想找到一条成功的捷径。实际上,捷径就在你我的身边,那就是——勤于积累,脚踏实地。有播种辛苦和汗水,才能收获金子和阳光。", " 你只能靠自己,那就是成功的秘诀。甚至我还和孤儿们在一起,在街头流浪,试着找到足够吃的时候,在那时,我就有了自己要成为世界上最了不起的演员的想法。——卓别林", " 多数人在人潮汹涌的世间,白白挤了一生,从来不知道哪里才是他所想要到达的地方,而有目标的人却始终不忘记自己的方向,所以他能打开出路,走向成功。——罗兰", " 任何通向成功的道路都布满了荆棘,充满了数不清的辛酸与煎熬、艰难与困苦。但是只要我们把失败当作进步的台阶,以积极的心态去面对,就不会被困难打倒。其实,失败也是一种美丽。", " 记住成功第一步,赶走旧观念,培养成功的观念。为日后独自做成功的决策,打下坚同的思想基础。这样你才不会被那些闲言碎语绊住了脚步,因为你知道,他们都是错的,只有自己拥有成功的想法,有成为“卓越人”的秘决。", " 我们一路奋战只是为了不被改变。如果,我们的生命真的还只剩下几天,那么就请一定坚信,你还是那个你,不要放弃任何改变的尝试,纵使注定不会成功。我依旧相信希望存在。", " 责任与严谨是成功的保证。有些人事未做之前,就一开始吹,有些应当属于秘密的细节,也会因为好虚荣而轻易透露出去。这种人不是没有责任感就是缺乏严谨态度,往往导致谋事失败。责任与严谨是相辅相成的。", " 如果你在思考时,总是担心别人怎么想,你会被他们的思想左右。最不快乐的人正是那些在乎别人想法的人。要想获得成功,你需要勇敢地去做你想做的事,让其他人有理由去谈论你的成功。", " 只有是心存美好的人,才是会去欣赏别人。懂得去欣赏别人的人,心灵才是会变得更加美好。拿不出结果,被轻视也是活该的,谁会管你过程多难努力了多少呢,世上也只是有成功的人才是有资格去说结果不重要。" }; public String getRandomQuote(){ //获取随机数 Random rand = new Random(); // 从数组中随机选择一句话 int index = rand.nextInt(quotes.length); return quotes[index]; } }
ShallowRecall/JavaSwing-Blog
src/com/zyproject/tool/GetRandomQuote.java
1,605
// 从数组中随机选择一句话
line_comment
zh-cn
package com.zyproject.tool; import java.util.Random; public class GetRandomQuote { String[] quotes={" 不是每个人都注定成功,信念就是即使看不到未来,即使看不到希望,也依然相信自己错不了,自己选的人错不了,自己选的人生错不了。梦想,就能看到未来。", " 只有对人生尽早策划,对人生的与通过预测进行科学防范,减少不必要的损失,才能赢得一个成功的人生。世界上没有一帆风顺的人生。没有的人生如同嚼蜡,索然无味。", " 你做得越好,挑你正确的人也就越多。很多无能之人仰视成功的方式,是诋毁。出来混,难免遭遇各种阴招。那些暗地里给你使绊子的人,别理他们。把自己的事情做好,就是最好的反击。", " 成功不是衡量人生价值的最高标准,比成功更重要的,是一个人能否按自己喜欢的方式生活。做自己喜欢做的事,做自己喜欢做的人。世上没有癞蛤蟆,天鹅其实也会寂寞。", " 人的智慧包括:语言、数理逻辑、空间关系、理解能力、音乐、身体动觉、人际交往与自知之明。勤于思敏于行唯有奋斗才能成功这是最好理解又是最难做到的。", " 只要我们总结跌倒的原因,把孕育的勇气树起,告别迷惘的昨天,拥抱美好的今天,微笑面对明天,不管是从辉煌成功中走出,还是在失败中奋起,漫漫远方路,才是我们不懈的追求。", " 如果你具有积极的心态,就会把你的目标定得愈高,你的成就也将愈大。任何事情上想要取得成功,都有必要清楚那些事情的发展规律,并了解如何应用这些规律。", " 德性是具有磁性的,久而久之,有德之人的周围就会聚足人气,而且芳名远播,形成一种无形而又无价的品牌,这是成功的最大助力。", " 成功的人很明白,没有一个人能一步登天,真正使他们出类拔萃的是他们心甘情愿地一步一步往前迈进,不管道路多么崎岖。", " 幸福足什么?在我看来,幸福来源于“简单生活”。文明只是外在的依托,成功、财富只足外在的荣光,真正的卓福来自于发现真实独特的自我,保持心灵的宁静", " 人一生中,一切伟大的行动与思想,都有一个微不足道的一开始。好好扮演自己的角色,做自己该做的事情,只要一开始,就不要停止,只要不停止,就会有成功。", " 人人都有梦想,都渴望成功,都想找到一条成功的捷径。实际上,捷径就在你我的身边,那就是——勤于积累,脚踏实地。有播种辛苦和汗水,才能收获金子和阳光。", " 你只能靠自己,那就是成功的秘诀。甚至我还和孤儿们在一起,在街头流浪,试着找到足够吃的时候,在那时,我就有了自己要成为世界上最了不起的演员的想法。——卓别林", " 多数人在人潮汹涌的世间,白白挤了一生,从来不知道哪里才是他所想要到达的地方,而有目标的人却始终不忘记自己的方向,所以他能打开出路,走向成功。——罗兰", " 任何通向成功的道路都布满了荆棘,充满了数不清的辛酸与煎熬、艰难与困苦。但是只要我们把失败当作进步的台阶,以积极的心态去面对,就不会被困难打倒。其实,失败也是一种美丽。", " 记住成功第一步,赶走旧观念,培养成功的观念。为日后独自做成功的决策,打下坚同的思想基础。这样你才不会被那些闲言碎语绊住了脚步,因为你知道,他们都是错的,只有自己拥有成功的想法,有成为“卓越人”的秘决。", " 我们一路奋战只是为了不被改变。如果,我们的生命真的还只剩下几天,那么就请一定坚信,你还是那个你,不要放弃任何改变的尝试,纵使注定不会成功。我依旧相信希望存在。", " 责任与严谨是成功的保证。有些人事未做之前,就一开始吹,有些应当属于秘密的细节,也会因为好虚荣而轻易透露出去。这种人不是没有责任感就是缺乏严谨态度,往往导致谋事失败。责任与严谨是相辅相成的。", " 如果你在思考时,总是担心别人怎么想,你会被他们的思想左右。最不快乐的人正是那些在乎别人想法的人。要想获得成功,你需要勇敢地去做你想做的事,让其他人有理由去谈论你的成功。", " 只有是心存美好的人,才是会去欣赏别人。懂得去欣赏别人的人,心灵才是会变得更加美好。拿不出结果,被轻视也是活该的,谁会管你过程多难努力了多少呢,世上也只是有成功的人才是有资格去说结果不重要。" }; public String getRandomQuote(){ //获取随机数 Random rand = new Random(); // 从数 <SUF> int index = rand.nextInt(quotes.length); return quotes[index]; } }
false
1,118
8
1,604
9
1,196
7
1,605
9
2,395
19
false
false
false
false
false
true
34903_0
import java.util.*; public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param n int整型 * @return int整型 */ public int Fibonacci(int n) { // write code here int[] res = new int[n]; if( n==1 || n == 2){ return 1; } res[0] = 1; res[1] = 1; for(int i = 2; i < n; i++){ res[i] = res[i-1] + res[i -2]; } return res[n-1]; } }
Shane-LiuSH/JZOFFER
JZ10.java
173
/** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param n int整型 * @return int整型 */
block_comment
zh-cn
import java.util.*; public class Solution { /** * 代码中 <SUF>*/ public int Fibonacci(int n) { // write code here int[] res = new int[n]; if( n==1 || n == 2){ return 1; } res[0] = 1; res[1] = 1; for(int i = 2; i < n; i++){ res[i] = res[i-1] + res[i -2]; } return res[n-1]; } }
false
162
51
173
50
189
55
173
50
216
78
false
false
false
false
false
true
53759_14
package com.atguigu.gmall.search.vo; import lombok.Data; /** * @Auther: 上白书妖 * @Date: 2019/11/12 17:35 * @Description: */ @Data public class SearchParamVO { // search?catelog3=手机&catelog3=配件&brand=1&props=43:3g-4g-5g&props=45:4.7-5.0 // &order=2:asc/desc&priceFrom=100&priceTo=10000&pageNum=1&pageSize=12&keyword=手机 private String[] catelog3;//三级分类id private String[] brand;//品牌id private String keyword;//检索的关键字 // order=1:asc 排序规则 0:asc private String order;// 0:综合排序 1:销量 2:价格 private Integer pageNum = 1;//分页信息 //props=2:全高清& 如果前端想传入很多值 props=2:青年-老人-女士 //2:win10-android- //3:4g //4:5.5 private String[] props;//页面提交的数组 private Integer pageSize = 12; private Integer priceFrom;//价格区间开始 private Integer priceTo;//价格区间结束 }
ShangBaiShuYao/gmall
gmall-search/src/main/java/com/atguigu/gmall/search/vo/SearchParamVO.java
332
//价格区间开始
line_comment
zh-cn
package com.atguigu.gmall.search.vo; import lombok.Data; /** * @Auther: 上白书妖 * @Date: 2019/11/12 17:35 * @Description: */ @Data public class SearchParamVO { // search?catelog3=手机&catelog3=配件&brand=1&props=43:3g-4g-5g&props=45:4.7-5.0 // &order=2:asc/desc&priceFrom=100&priceTo=10000&pageNum=1&pageSize=12&keyword=手机 private String[] catelog3;//三级分类id private String[] brand;//品牌id private String keyword;//检索的关键字 // order=1:asc 排序规则 0:asc private String order;// 0:综合排序 1:销量 2:价格 private Integer pageNum = 1;//分页信息 //props=2:全高清& 如果前端想传入很多值 props=2:青年-老人-女士 //2:win10-android- //3:4g //4:5.5 private String[] props;//页面提交的数组 private Integer pageSize = 12; private Integer priceFrom;//价格 <SUF> private Integer priceTo;//价格区间结束 }
false
321
4
332
5
328
4
332
5
426
9
false
false
false
false
false
true
62819_1
package top.shanwer; import io.javalin.Javalin; import java.util.Random; public class Main { public static void main(String[] args){ double startTime = System.nanoTime(); //TODO: // 1.判断是不是周末吃大餐 完成 √ // 2.scanner读文件不太好用,下次可以试试 yaml(下次一定) // 3.每天必须吃一顿有蔬菜的,那样子的话得处理 plain text到多维数组了吧( // 4.写个日志?省得吃的东西重复(或者用堆栈,再来个数组,不写日志,那就得直接生成一周),或者消耗他们,抽一个一个就变成 null,抽到null就catch exception然后throw然后继续抽!然后过一周再重新更新数组 // 5.做到网页上,更泛用,比如叫 Shanwer Start,和4.一起做的话感觉会好一点,嗯,那还得学一些东西 (非常好的完成了!! √) // 6.再来点每日金句做鸡汤鼓励可怜的sw( (大概完成了) √ //Scanner menu = new Scanner(Path.of("menu.txt"), StandardCharsets.UTF_8); //不用Path.of(),有Paths.get()了,虽然不知道区别 final int mode = 2; //开控制台还是后端服务器模式 switch (mode) { case 0: String[] Dishes = new String[2]; Dishes[0] = new GetString().getString(); Dishes[1] = new GetString().getString(); System.out.println(new GetString().getSentence()); System.out.println("中饭吃:" + Dishes[0]); System.out.println("晚饭吃:" + Dishes[1]); double cmdEndTime = System.nanoTime(); System.out.println("执行命令行程序所用时间:" + (cmdEndTime - startTime) / 1000000000 + "秒"); break; case 1: Javalin returnHtmlApp = Javalin.create(/*config*/) .before(ctx -> ctx.header("Content-Type", "text/html;charset=utf-8")) .get("/", ctx -> ctx.result(new GetString().getSentence() + "<br/>" + new GetString().getString() + "<br/>" + new GetString().getString())) .start(8080); double htmlEndTime = System.nanoTime(); System.out.println("开启服务端后所用时间:" + (htmlEndTime - startTime) / 1000000000 + "秒"); break; case 2: GetJson obj = new GetJson();//得到一个静态的getJson对象 Javalin returnJsonApp = Javalin.create(/*config*/) .before(ctx -> ctx.header("Access-Control-Allow-Origin", "*"))//后端还需要加上跨域,否则无法调用API .get("/normalRequest", ctx -> ctx.json(obj.getOnce())) .get("/refreshAll/{pathParam}", ctx -> { if(ctx.pathParam("pathParam").equals("default")){ ctx.json(obj.getAll()); }else{ ctx.json(obj.getWeekday()); } }) //.get("/refreshLunch", ctx -> ctx.json(obj.getLunch())) //.get("/refreshDinner", ctx -> ctx.json(obj.getDinner())) .start(8080); double jsonEndTime = System.nanoTime(); System.out.println("开启服务端后所用时间:" + (jsonEndTime - startTime) / 1000000000 + "秒"); break; } } public static int randomIndex(int i) { //Random randomNumber = new Random(); //randomNumber.setSeed(); 如果使用确定的种子会生成一样的结果 return new Random().nextInt(i); } }
Shanwer/DishesProvider
src/main/java/top/shanwer/Main.java
954
// 1.判断是不是周末吃大餐 完成 √
line_comment
zh-cn
package top.shanwer; import io.javalin.Javalin; import java.util.Random; public class Main { public static void main(String[] args){ double startTime = System.nanoTime(); //TODO: // 1. <SUF> // 2.scanner读文件不太好用,下次可以试试 yaml(下次一定) // 3.每天必须吃一顿有蔬菜的,那样子的话得处理 plain text到多维数组了吧( // 4.写个日志?省得吃的东西重复(或者用堆栈,再来个数组,不写日志,那就得直接生成一周),或者消耗他们,抽一个一个就变成 null,抽到null就catch exception然后throw然后继续抽!然后过一周再重新更新数组 // 5.做到网页上,更泛用,比如叫 Shanwer Start,和4.一起做的话感觉会好一点,嗯,那还得学一些东西 (非常好的完成了!! √) // 6.再来点每日金句做鸡汤鼓励可怜的sw( (大概完成了) √ //Scanner menu = new Scanner(Path.of("menu.txt"), StandardCharsets.UTF_8); //不用Path.of(),有Paths.get()了,虽然不知道区别 final int mode = 2; //开控制台还是后端服务器模式 switch (mode) { case 0: String[] Dishes = new String[2]; Dishes[0] = new GetString().getString(); Dishes[1] = new GetString().getString(); System.out.println(new GetString().getSentence()); System.out.println("中饭吃:" + Dishes[0]); System.out.println("晚饭吃:" + Dishes[1]); double cmdEndTime = System.nanoTime(); System.out.println("执行命令行程序所用时间:" + (cmdEndTime - startTime) / 1000000000 + "秒"); break; case 1: Javalin returnHtmlApp = Javalin.create(/*config*/) .before(ctx -> ctx.header("Content-Type", "text/html;charset=utf-8")) .get("/", ctx -> ctx.result(new GetString().getSentence() + "<br/>" + new GetString().getString() + "<br/>" + new GetString().getString())) .start(8080); double htmlEndTime = System.nanoTime(); System.out.println("开启服务端后所用时间:" + (htmlEndTime - startTime) / 1000000000 + "秒"); break; case 2: GetJson obj = new GetJson();//得到一个静态的getJson对象 Javalin returnJsonApp = Javalin.create(/*config*/) .before(ctx -> ctx.header("Access-Control-Allow-Origin", "*"))//后端还需要加上跨域,否则无法调用API .get("/normalRequest", ctx -> ctx.json(obj.getOnce())) .get("/refreshAll/{pathParam}", ctx -> { if(ctx.pathParam("pathParam").equals("default")){ ctx.json(obj.getAll()); }else{ ctx.json(obj.getWeekday()); } }) //.get("/refreshLunch", ctx -> ctx.json(obj.getLunch())) //.get("/refreshDinner", ctx -> ctx.json(obj.getDinner())) .start(8080); double jsonEndTime = System.nanoTime(); System.out.println("开启服务端后所用时间:" + (jsonEndTime - startTime) / 1000000000 + "秒"); break; } } public static int randomIndex(int i) { //Random randomNumber = new Random(); //randomNumber.setSeed(); 如果使用确定的种子会生成一样的结果 return new Random().nextInt(i); } }
false
833
16
954
17
925
12
954
17
1,230
25
false
false
false
false
false
true
44708_0
package com.questions.activity; import android.annotation.SuppressLint; import android.os.Bundle; import com.questions.R; import com.questions.databinding.ActivityResultBinding; import com.questions.activity.base.BaseActivity; public class ResultActivity extends BaseActivity<ActivityResultBinding> { private String time; private int type; private int source; @Override protected int getLayout() { return R.layout.activity_result; } @SuppressLint("SetTextI18n") @Override protected void initData(Bundle savedInstanceState) { Bundle bundle = getIntent().getExtras(); time = bundle.getString("time"); type = bundle.getInt("subjectType"); source = bundle.getInt("source"); setTitle("考试结果"); if (type == 1){ mBinding.tvQuestionTypeResult.setText("科目1"); }else if (type == 2){ mBinding.tvQuestionTypeResult.setText("科目4"); } mBinding.tvTimeResult.setText(time); mBinding.tvResultSource.setText(""+source); if (source < 90){ mBinding.tvResultSource.setTextColor(getResources().getColor(R.color.color_f4011f)); mBinding.lvnResultBack.setImageResource(R.mipmap.result_no_img); mBinding.tvResultText1.setText("马路杀手"); mBinding.tvResultText1.setTextColor(getResources().getColor(R.color.color_f4011f)); mBinding.tvResultText2.setText("不要灰心,下次继续加油啦!"); } } @Override protected void initEvent() { setTopLeftButton(R.mipmap.back_img, v -> finish()); mBinding.tvMyErrorResult.setOnClickListener(v ->{ Bundle bundle = new Bundle(); bundle.putInt("type",type); startActivity(bundle,MyErrorSubjectActivity.class); finish(); }); mBinding.tvToSubject.setOnClickListener(v -> { Bundle bundle = new Bundle(); bundle.putInt("questionType", 1);// 1 模拟考试 2 章节练习 bundle.putInt("type", type); startActivity(bundle, SubjectActivity.class); finish(); }); } }
Shao232/Questions
app/src/main/java/com/questions/activity/ResultActivity.java
540
// 1 模拟考试 2 章节练习
line_comment
zh-cn
package com.questions.activity; import android.annotation.SuppressLint; import android.os.Bundle; import com.questions.R; import com.questions.databinding.ActivityResultBinding; import com.questions.activity.base.BaseActivity; public class ResultActivity extends BaseActivity<ActivityResultBinding> { private String time; private int type; private int source; @Override protected int getLayout() { return R.layout.activity_result; } @SuppressLint("SetTextI18n") @Override protected void initData(Bundle savedInstanceState) { Bundle bundle = getIntent().getExtras(); time = bundle.getString("time"); type = bundle.getInt("subjectType"); source = bundle.getInt("source"); setTitle("考试结果"); if (type == 1){ mBinding.tvQuestionTypeResult.setText("科目1"); }else if (type == 2){ mBinding.tvQuestionTypeResult.setText("科目4"); } mBinding.tvTimeResult.setText(time); mBinding.tvResultSource.setText(""+source); if (source < 90){ mBinding.tvResultSource.setTextColor(getResources().getColor(R.color.color_f4011f)); mBinding.lvnResultBack.setImageResource(R.mipmap.result_no_img); mBinding.tvResultText1.setText("马路杀手"); mBinding.tvResultText1.setTextColor(getResources().getColor(R.color.color_f4011f)); mBinding.tvResultText2.setText("不要灰心,下次继续加油啦!"); } } @Override protected void initEvent() { setTopLeftButton(R.mipmap.back_img, v -> finish()); mBinding.tvMyErrorResult.setOnClickListener(v ->{ Bundle bundle = new Bundle(); bundle.putInt("type",type); startActivity(bundle,MyErrorSubjectActivity.class); finish(); }); mBinding.tvToSubject.setOnClickListener(v -> { Bundle bundle = new Bundle(); bundle.putInt("questionType", 1);// 1 <SUF> bundle.putInt("type", type); startActivity(bundle, SubjectActivity.class); finish(); }); } }
false
436
14
540
14
555
10
540
14
640
23
false
false
false
false
false
true
32506_62
package com.mediamodule.media; import android.os.Bundle; import com.iflytek.cloud.ErrorCode; import com.iflytek.cloud.InitListener; import com.iflytek.cloud.SpeechConstant; import com.iflytek.cloud.SpeechError; import com.iflytek.cloud.SpeechSynthesizer; import com.iflytek.cloud.SpeechUtility; import com.iflytek.cloud.SynthesizerListener; import com.mediamodule.app.MediaConfig; import com.mediamodule.util.MediaLog; import com.mediamodule.util.StringUtil; /** * Title:语音合成帮助类 * Description: * <p> * Created by pei * Date: 2018/4/8 */ public class SpeechHelper { //语音播报appid private static final String APPID="5afcdbda"; private String[] mCloudVoicersEntries={"小燕—女青、中英、普通话","小宇—男青、中英、普通话","凯瑟琳—女青、英", "亨利—男青、英","玛丽—女青、英","小研—女青、中英、普通话", "小琪—女青、中英、普通话","小峰—男青、中英、普通话","小梅—女青、中英、粤语", "小莉—女青、中英、台湾普通话","小蓉—女青、中、四川话","小芸—女青、中、东北话", "小坤—男青、中、河南话","小强—男青、中、湖南话","小莹—女青、中、陕西话", "小新—男童、中、普通话","楠楠—女童、中、普通话","老孙—男老、中、普通话"}; private String[] mCloudVoicersValue={"xiaoyan","xiaoyu","catherine","henry","vimary","vixy", "xiaoqi","vixf","xiaomei","xiaolin","xiaorong","xiaoqian", "xiaokun","xiaoqiang","vixying","xiaoxin","nannan","vils"}; public static int MIN_VALUE=0;//最小阈值 public static int MAX_VALUE=100;//最大阈值 private static String COMPOUND_SPEED="50";//设置合成语速(参数0-100) private static String COMPOUND_TONES="50";//设置合成音调(参数0-100) private static String COMPOUND_VOICE="50";//设置合成音量(参数0-100) private static String VOICE_STREAM_TYPE="3";//音频六类型 //语速(参数0-100,默认50) private int mCompoundSpeed=Integer.valueOf(COMPOUND_SPEED); //音调(参数0-100,默认50) private int mCompoundTones=Integer.valueOf(COMPOUND_TONES); //音量(参数0-100,默认50) private int mCompoundVoice=Integer.valueOf(COMPOUND_VOICE); // 语音合成对象 private SpeechSynthesizer mTts; // 发音人(下标0-17,默认下标5) private String mVoicer = mCloudVoicersValue[5];//"vixy" // 缓冲进度 private int mPercentForBuffering = 0; // 播放进度 private int mPercentForPlaying = 0; // 引擎类型 private String mEngineType = SpeechConstant.TYPE_CLOUD; private boolean mSpeaking;//是否正在朗读 private SpeechHelper() {} private static class Holder { private static SpeechHelper instance = new SpeechHelper(); } public static SpeechHelper getInstance() { return Holder.instance; } /** * 自定义application中调用 * @return */ public SpeechHelper initSpeech(){ SpeechUtility.createUtility(MediaConfig.getInstance().getApplication(), "appid=" + APPID); // //以下语句用于设置日志开关(默认开启),设置成false时关闭语音云SDK日志打印 // Setting.setShowLog(false); return SpeechHelper.this; } /**设置发音人(index范围[0-17],默认index=5)**/ public SpeechHelper setVoicer(int index){ if(0<=index&&index<=mCloudVoicersValue.length-1){ mVoicer=mCloudVoicersValue[index]; } return SpeechHelper.this; } /**设置语速(参数0-100,默认50)**/ public SpeechHelper setCompoundSpeed(int speed){ if(MIN_VALUE<=speed&&speed<=MAX_VALUE){ this.mCompoundSpeed=speed; } return SpeechHelper.this; } /**设置音调(参数0-100,默认50)**/ public SpeechHelper setCompoundTones(int tones){ if(MIN_VALUE<=tones&&tones<=MAX_VALUE){ this.mCompoundTones=tones; } return SpeechHelper.this; } /**设置音量(参数0-100,默认50)**/ public SpeechHelper setCompoundVoice(int voice){ if(MIN_VALUE<=voice&&voice<=MAX_VALUE){ this.mCompoundVoice=voice; } return SpeechHelper.this; } /**开始读**/ public void speak(String message){ //开始播报 if(StringUtil.isNotEmpty(message)){ if(mTts==null){ // 初始化合成对象 mTts = SpeechSynthesizer.createSynthesizer(MediaConfig.getInstance().getApplication(), mTtsInitListener); } if(mTts!=null){ mSpeaking=true; //设置 setParam(); //开始播报 int code=mTts.startSpeaking(message, mTtsListener); // /** // * 只保存音频不进行播放接口,调用此接口请注释startSpeaking接口 // * text:要合成的文本,uri:需要保存的音频全路径,listener:回调接口 // */ // String path = Environment.getExternalStorageDirectory()+"/tts.ico"; // int code = mTts.synthesizeToUri(text, path, mTtsListener); if (code != ErrorCode.SUCCESS) { MediaLog.e("语音合成失败,错误码: " + code); } }else{ MediaLog.i("======初始化失败======"); } }else{ MediaLog.e("=====播报内容不能为空=========="); } } public void destroy(){ if( null != mTts ){ mTts.stopSpeaking(); // 退出时释放连接 mTts.destroy(); MediaLog.i("======语音播报销毁========"); } } /** * 初始化监听。 */ private InitListener mTtsInitListener = new InitListener() { @Override public void onInit(int code) { MediaLog.i("InitListener init() code = " + code); if (code != ErrorCode.SUCCESS) { MediaLog.i("初始化失败,错误码: " + code); } else { // 初始化成功,之后可以调用startSpeaking方法 // 注:有的开发者在onCreate方法中创建完合成对象之后马上就调用startSpeaking进行合成, // 正确的做法是将onCreate中的startSpeaking调用移至这里 } } }; /** * 合成回调监听。 */ private SynthesizerListener mTtsListener = new SynthesizerListener() { @Override public void onSpeakBegin() { // MediaLog.i("开始播放"); } @Override public void onSpeakPaused() { // MediaLog.i("暂停播放"); } @Override public void onSpeakResumed() { // MediaLog.i("继续播放"); } @Override public void onBufferProgress(int percent, int beginPos, int endPos, String info) { // 合成进度 mPercentForBuffering = percent; // MediaLog.i("======合成进度======缓冲进度="+mPercentForBuffering+" 播放进度:"+mPercentForPlaying); } @Override public void onSpeakProgress(int percent, int beginPos, int endPos) { // 播放进度 mPercentForPlaying = percent; // MediaLog.i("======播放进度======缓冲进度="+mPercentForBuffering+" 播放进度:"+mPercentForPlaying); } @Override public void onCompleted(SpeechError error) { if (error == null) { // MediaLog.i("播放完成"); } else if (error != null) { MediaLog.i(error.getPlainDescription(true)); } mSpeaking=false; } @Override public void onEvent(int eventType, int arg1, int arg2, Bundle obj) { // 以下代码用于获取与云端的会话id,当业务出错时将会话id提供给技术支持人员,可用于查询会话日志,定位出错原因 // 若使用本地能力,会话id为null // if (SpeechEvent.EVENT_SESSION_ID == eventType) { // String sid = obj.getString(SpeechEvent.KEY_EVENT_SESSION_ID); // Log.d(TAG, "session id =" + sid); // } } }; /**是否正在播报**/ public boolean isSpeaking(){ return mSpeaking; } /** * 参数设置 * @return */ private void setParam(){ // 清空参数 mTts.setParameter(SpeechConstant.PARAMS, null); // 根据合成引擎设置相应参数 if(mEngineType.equals(SpeechConstant.TYPE_CLOUD)) { mTts.setParameter(SpeechConstant.ENGINE_TYPE, SpeechConstant.TYPE_CLOUD); // 设置在线合成发音人 mTts.setParameter(SpeechConstant.VOICE_NAME, mVoicer); //设置合成语速 mTts.setParameter(SpeechConstant.SPEED, String.valueOf(mCompoundSpeed)); //设置合成音调 mTts.setParameter(SpeechConstant.PITCH, String.valueOf(mCompoundTones)); //设置合成音量 mTts.setParameter(SpeechConstant.VOLUME, String.valueOf(mCompoundVoice)); }else { mTts.setParameter(SpeechConstant.ENGINE_TYPE, SpeechConstant.TYPE_LOCAL); // 设置本地合成发音人 voicer为空,默认通过语记界面指定发音人。 mTts.setParameter(SpeechConstant.VOICE_NAME, ""); /** * TODO 本地合成不设置语速、音调、音量,默认使用语记设置 * 开发者如需自定义参数,请参考在线合成参数设置 */ } //设置播放器音频流类型 mTts.setParameter(SpeechConstant.STREAM_TYPE,VOICE_STREAM_TYPE); // 设置播放合成音频打断音乐播放,默认为true mTts.setParameter(SpeechConstant.KEY_REQUEST_FOCUS, "true"); // // 设置音频保存路径,保存音频格式支持pcm、wav,设置路径为sd卡请注意WRITE_EXTERNAL_STORAGE权限 // // 注:AUDIO_FORMAT参数语记需要更新版本才能生效 // mTts.setParameter(SpeechConstant.AUDIO_FORMAT, "wav"); // mTts.setParameter(SpeechConstant.TTS_AUDIO_PATH, Environment.getExternalStorageDirectory()+"/msc/tts.wav"); } }
ShaoqiangPei/MediaLibrary
MediaPro/mediamodule/src/main/java/com/mediamodule/media/SpeechHelper.java
2,824
/** * TODO 本地合成不设置语速、音调、音量,默认使用语记设置 * 开发者如需自定义参数,请参考在线合成参数设置 */
block_comment
zh-cn
package com.mediamodule.media; import android.os.Bundle; import com.iflytek.cloud.ErrorCode; import com.iflytek.cloud.InitListener; import com.iflytek.cloud.SpeechConstant; import com.iflytek.cloud.SpeechError; import com.iflytek.cloud.SpeechSynthesizer; import com.iflytek.cloud.SpeechUtility; import com.iflytek.cloud.SynthesizerListener; import com.mediamodule.app.MediaConfig; import com.mediamodule.util.MediaLog; import com.mediamodule.util.StringUtil; /** * Title:语音合成帮助类 * Description: * <p> * Created by pei * Date: 2018/4/8 */ public class SpeechHelper { //语音播报appid private static final String APPID="5afcdbda"; private String[] mCloudVoicersEntries={"小燕—女青、中英、普通话","小宇—男青、中英、普通话","凯瑟琳—女青、英", "亨利—男青、英","玛丽—女青、英","小研—女青、中英、普通话", "小琪—女青、中英、普通话","小峰—男青、中英、普通话","小梅—女青、中英、粤语", "小莉—女青、中英、台湾普通话","小蓉—女青、中、四川话","小芸—女青、中、东北话", "小坤—男青、中、河南话","小强—男青、中、湖南话","小莹—女青、中、陕西话", "小新—男童、中、普通话","楠楠—女童、中、普通话","老孙—男老、中、普通话"}; private String[] mCloudVoicersValue={"xiaoyan","xiaoyu","catherine","henry","vimary","vixy", "xiaoqi","vixf","xiaomei","xiaolin","xiaorong","xiaoqian", "xiaokun","xiaoqiang","vixying","xiaoxin","nannan","vils"}; public static int MIN_VALUE=0;//最小阈值 public static int MAX_VALUE=100;//最大阈值 private static String COMPOUND_SPEED="50";//设置合成语速(参数0-100) private static String COMPOUND_TONES="50";//设置合成音调(参数0-100) private static String COMPOUND_VOICE="50";//设置合成音量(参数0-100) private static String VOICE_STREAM_TYPE="3";//音频六类型 //语速(参数0-100,默认50) private int mCompoundSpeed=Integer.valueOf(COMPOUND_SPEED); //音调(参数0-100,默认50) private int mCompoundTones=Integer.valueOf(COMPOUND_TONES); //音量(参数0-100,默认50) private int mCompoundVoice=Integer.valueOf(COMPOUND_VOICE); // 语音合成对象 private SpeechSynthesizer mTts; // 发音人(下标0-17,默认下标5) private String mVoicer = mCloudVoicersValue[5];//"vixy" // 缓冲进度 private int mPercentForBuffering = 0; // 播放进度 private int mPercentForPlaying = 0; // 引擎类型 private String mEngineType = SpeechConstant.TYPE_CLOUD; private boolean mSpeaking;//是否正在朗读 private SpeechHelper() {} private static class Holder { private static SpeechHelper instance = new SpeechHelper(); } public static SpeechHelper getInstance() { return Holder.instance; } /** * 自定义application中调用 * @return */ public SpeechHelper initSpeech(){ SpeechUtility.createUtility(MediaConfig.getInstance().getApplication(), "appid=" + APPID); // //以下语句用于设置日志开关(默认开启),设置成false时关闭语音云SDK日志打印 // Setting.setShowLog(false); return SpeechHelper.this; } /**设置发音人(index范围[0-17],默认index=5)**/ public SpeechHelper setVoicer(int index){ if(0<=index&&index<=mCloudVoicersValue.length-1){ mVoicer=mCloudVoicersValue[index]; } return SpeechHelper.this; } /**设置语速(参数0-100,默认50)**/ public SpeechHelper setCompoundSpeed(int speed){ if(MIN_VALUE<=speed&&speed<=MAX_VALUE){ this.mCompoundSpeed=speed; } return SpeechHelper.this; } /**设置音调(参数0-100,默认50)**/ public SpeechHelper setCompoundTones(int tones){ if(MIN_VALUE<=tones&&tones<=MAX_VALUE){ this.mCompoundTones=tones; } return SpeechHelper.this; } /**设置音量(参数0-100,默认50)**/ public SpeechHelper setCompoundVoice(int voice){ if(MIN_VALUE<=voice&&voice<=MAX_VALUE){ this.mCompoundVoice=voice; } return SpeechHelper.this; } /**开始读**/ public void speak(String message){ //开始播报 if(StringUtil.isNotEmpty(message)){ if(mTts==null){ // 初始化合成对象 mTts = SpeechSynthesizer.createSynthesizer(MediaConfig.getInstance().getApplication(), mTtsInitListener); } if(mTts!=null){ mSpeaking=true; //设置 setParam(); //开始播报 int code=mTts.startSpeaking(message, mTtsListener); // /** // * 只保存音频不进行播放接口,调用此接口请注释startSpeaking接口 // * text:要合成的文本,uri:需要保存的音频全路径,listener:回调接口 // */ // String path = Environment.getExternalStorageDirectory()+"/tts.ico"; // int code = mTts.synthesizeToUri(text, path, mTtsListener); if (code != ErrorCode.SUCCESS) { MediaLog.e("语音合成失败,错误码: " + code); } }else{ MediaLog.i("======初始化失败======"); } }else{ MediaLog.e("=====播报内容不能为空=========="); } } public void destroy(){ if( null != mTts ){ mTts.stopSpeaking(); // 退出时释放连接 mTts.destroy(); MediaLog.i("======语音播报销毁========"); } } /** * 初始化监听。 */ private InitListener mTtsInitListener = new InitListener() { @Override public void onInit(int code) { MediaLog.i("InitListener init() code = " + code); if (code != ErrorCode.SUCCESS) { MediaLog.i("初始化失败,错误码: " + code); } else { // 初始化成功,之后可以调用startSpeaking方法 // 注:有的开发者在onCreate方法中创建完合成对象之后马上就调用startSpeaking进行合成, // 正确的做法是将onCreate中的startSpeaking调用移至这里 } } }; /** * 合成回调监听。 */ private SynthesizerListener mTtsListener = new SynthesizerListener() { @Override public void onSpeakBegin() { // MediaLog.i("开始播放"); } @Override public void onSpeakPaused() { // MediaLog.i("暂停播放"); } @Override public void onSpeakResumed() { // MediaLog.i("继续播放"); } @Override public void onBufferProgress(int percent, int beginPos, int endPos, String info) { // 合成进度 mPercentForBuffering = percent; // MediaLog.i("======合成进度======缓冲进度="+mPercentForBuffering+" 播放进度:"+mPercentForPlaying); } @Override public void onSpeakProgress(int percent, int beginPos, int endPos) { // 播放进度 mPercentForPlaying = percent; // MediaLog.i("======播放进度======缓冲进度="+mPercentForBuffering+" 播放进度:"+mPercentForPlaying); } @Override public void onCompleted(SpeechError error) { if (error == null) { // MediaLog.i("播放完成"); } else if (error != null) { MediaLog.i(error.getPlainDescription(true)); } mSpeaking=false; } @Override public void onEvent(int eventType, int arg1, int arg2, Bundle obj) { // 以下代码用于获取与云端的会话id,当业务出错时将会话id提供给技术支持人员,可用于查询会话日志,定位出错原因 // 若使用本地能力,会话id为null // if (SpeechEvent.EVENT_SESSION_ID == eventType) { // String sid = obj.getString(SpeechEvent.KEY_EVENT_SESSION_ID); // Log.d(TAG, "session id =" + sid); // } } }; /**是否正在播报**/ public boolean isSpeaking(){ return mSpeaking; } /** * 参数设置 * @return */ private void setParam(){ // 清空参数 mTts.setParameter(SpeechConstant.PARAMS, null); // 根据合成引擎设置相应参数 if(mEngineType.equals(SpeechConstant.TYPE_CLOUD)) { mTts.setParameter(SpeechConstant.ENGINE_TYPE, SpeechConstant.TYPE_CLOUD); // 设置在线合成发音人 mTts.setParameter(SpeechConstant.VOICE_NAME, mVoicer); //设置合成语速 mTts.setParameter(SpeechConstant.SPEED, String.valueOf(mCompoundSpeed)); //设置合成音调 mTts.setParameter(SpeechConstant.PITCH, String.valueOf(mCompoundTones)); //设置合成音量 mTts.setParameter(SpeechConstant.VOLUME, String.valueOf(mCompoundVoice)); }else { mTts.setParameter(SpeechConstant.ENGINE_TYPE, SpeechConstant.TYPE_LOCAL); // 设置本地合成发音人 voicer为空,默认通过语记界面指定发音人。 mTts.setParameter(SpeechConstant.VOICE_NAME, ""); /** * TOD <SUF>*/ } //设置播放器音频流类型 mTts.setParameter(SpeechConstant.STREAM_TYPE,VOICE_STREAM_TYPE); // 设置播放合成音频打断音乐播放,默认为true mTts.setParameter(SpeechConstant.KEY_REQUEST_FOCUS, "true"); // // 设置音频保存路径,保存音频格式支持pcm、wav,设置路径为sd卡请注意WRITE_EXTERNAL_STORAGE权限 // // 注:AUDIO_FORMAT参数语记需要更新版本才能生效 // mTts.setParameter(SpeechConstant.AUDIO_FORMAT, "wav"); // mTts.setParameter(SpeechConstant.TTS_AUDIO_PATH, Environment.getExternalStorageDirectory()+"/msc/tts.wav"); } }
false
2,486
42
2,794
44
2,783
42
2,795
44
3,674
61
false
false
false
false
false
true
23808_14
package servlet; import com.itextpdf.io.font.PdfEncodings; import com.itextpdf.kernel.color.Color; import com.itextpdf.kernel.font.PdfFont; import com.itextpdf.kernel.font.PdfFontFactory; import com.itextpdf.kernel.pdf.PdfDocument; import com.itextpdf.kernel.pdf.PdfWriter; import com.itextpdf.layout.Document; import com.itextpdf.layout.border.SolidBorder; import com.itextpdf.layout.element.Cell; import com.itextpdf.layout.element.Paragraph; import com.itextpdf.layout.element.Table; import com.itextpdf.layout.property.TextAlignment; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; @WebServlet("/export") public class ExportFormServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 设置response参数,可以打开下载页面 // response.addHeader("Content-Disposition","attachment;filename="+ new String("output.pdf".getBytes("UTF-8"))); // request.setCharacterEncoding("UTF-8"); // String name = request.getParameter("name"); // int number = Integer.parseInt(request.getParameter("number")); // String organization = request.getParameter("organization"); // String dateofuse = request.getParameter("dateofuse"); // String timeofuse = request.getParameter("timeofuse"); // String building = request.getParameter("building"); // String size = request.getParameter("size"); // String needMedia = request.getParameter("needmedia"); // String available = request.getParameter("available"); // String reason = request.getParameter("reason"); String organization = "HHU"; String dateofuse = "2017-7-18"; String timeofuse = "1th"; String needMedia = "是"; // 创建 PdfWriter 对象 PdfWriter writer = new PdfWriter(this.getServletContext().getRealPath("/output.pdf")); // 实例化文档对象 PdfDocument pdf = new PdfDocument(writer); // 初始化document Document document = new Document(pdf); PdfFont font1 = PdfFontFactory.createFont("C:\\Users\\PatrickYates\\Desktop\\JspDemo\\src\\main\\webapp\\fonts\\Yahei Consolas Hybrid.ttf", PdfEncodings.IDENTITY_H, false); // 添加段落 document.add(new Paragraph("河海大学(学生课余活动)借用教室审批表\n\n").setFont(font1).setFontSize(22).setTextAlignment(TextAlignment.CENTER)); Table table = new Table(1); table.addCell(new Cell().add(new Paragraph("申请学院(部门):" + organization).setFont(font1)).setFontSize(12).setBorder(new SolidBorder(Color.BLACK, 0.5f))); table.addCell(new Cell().add(new Paragraph("活动(报告、讲座)名称:\n" + "报告、讲座人姓名: 所属单位: 职务职称:").setFont(font1)).setFontSize(12).setBorder(new SolidBorder(Color.BLACK, 0.5f))); table.addCell(new Cell().add(new Paragraph("活动需用教室时间:" + dateofuse+" 星期 " + timeofuse).setFont(font1)).setFontSize(12).setBorder(new SolidBorder(Color.BLACK, 0.5f))); if (needMedia.equals("是")) { table.addCell(new Cell().add(new Paragraph("是否借用多媒体:" + " 是(√) 否( )\n" + "贵重物品(多媒体设备)损坏赔偿意见:\n\n\n" + "学院(部门)负责人签字:\n").setFont(font1)).setFontSize(12).setBorder(new SolidBorder(Color.BLACK, 0.5f))); } if (needMedia.equals("否")) { table.addCell(new Cell().add(new Paragraph("是否借用多媒体:" + " 是( ) 否(√)\n" + "贵重物品(多媒体设备)损坏赔偿意见:\n\n\n" + "学院(部门)负责人签字:\n").setFont(font1)).setFontSize(12).setBorder(new SolidBorder(Color.BLACK, 0.5f))); } table.addCell(new Cell().add(new Paragraph("活动组织单位:\n" + "活动负责人: 联系电话(必填): \n").setFont(font1)).setFontSize(12).setBorder(new SolidBorder(Color.BLACK, 0.5f))); table.addCell(new Cell().add(new Paragraph("活动面向对象: 参加活动人数: ").setFont(font1)).setFontSize(12).setBorder(new SolidBorder(Color.BLACK, 0.5f))); table.addCell(new Cell().add(new Paragraph("活动意义和预期效果:\n\n\n").setFont(font1)).setFontSize(12).setBorder(new SolidBorder(Color.BLACK, 0.5f))); table.addCell(new Cell().add(new Paragraph("宣传部意见:\n\n\n").setFont(font1)).setFontSize(12).setBorder(new SolidBorder(Color.BLACK, 0.5f))); table.addCell(new Cell().add(new Paragraph("学院(部门)意见:\n\n\n" + "学院(部门)负责人签字:\n" + "学院(部门)公章\n\n\n" + "年 月 日\n").setFont(font1)).setFontSize(12).setBorder(new SolidBorder(Color.BLACK, 0.5f))); document.add(table); // 关闭document document.close(); //1.获取要下载的文件的绝对路径 String realPath = this.getServletContext().getRealPath("/output.pdf"); System.out.println(realPath); //2.获取要下载的文件名 String fileName = realPath.substring(realPath.lastIndexOf("\\")+1); //3.设置content-disposition响应头控制浏览器以下载的形式打开文件 response.setContentType("application/pdf;charset=utf-8"); response.setHeader("content-disposition", "attachment;filename="+fileName); //4.获取要下载的文件输入流 InputStream in = new FileInputStream(realPath); int len = 0; //5.创建数据缓冲区 byte[] buffer = new byte[1024]; //6.通过response对象获取OutputStream流 OutputStream out = response.getOutputStream(); //7.将FileInputStream流写入到buffer缓冲区 while ((len = in.read(buffer)) > 0) { //8.使用OutputStream将缓冲区的数据输出到客户端浏览器 out.write(buffer,0,len); } in.close(); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } }
ShawyerPeng/JspCurriculumDesign
src/main/java/servlet/ExportFormServlet.java
1,780
// 实例化文档对象
line_comment
zh-cn
package servlet; import com.itextpdf.io.font.PdfEncodings; import com.itextpdf.kernel.color.Color; import com.itextpdf.kernel.font.PdfFont; import com.itextpdf.kernel.font.PdfFontFactory; import com.itextpdf.kernel.pdf.PdfDocument; import com.itextpdf.kernel.pdf.PdfWriter; import com.itextpdf.layout.Document; import com.itextpdf.layout.border.SolidBorder; import com.itextpdf.layout.element.Cell; import com.itextpdf.layout.element.Paragraph; import com.itextpdf.layout.element.Table; import com.itextpdf.layout.property.TextAlignment; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; @WebServlet("/export") public class ExportFormServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 设置response参数,可以打开下载页面 // response.addHeader("Content-Disposition","attachment;filename="+ new String("output.pdf".getBytes("UTF-8"))); // request.setCharacterEncoding("UTF-8"); // String name = request.getParameter("name"); // int number = Integer.parseInt(request.getParameter("number")); // String organization = request.getParameter("organization"); // String dateofuse = request.getParameter("dateofuse"); // String timeofuse = request.getParameter("timeofuse"); // String building = request.getParameter("building"); // String size = request.getParameter("size"); // String needMedia = request.getParameter("needmedia"); // String available = request.getParameter("available"); // String reason = request.getParameter("reason"); String organization = "HHU"; String dateofuse = "2017-7-18"; String timeofuse = "1th"; String needMedia = "是"; // 创建 PdfWriter 对象 PdfWriter writer = new PdfWriter(this.getServletContext().getRealPath("/output.pdf")); // 实例 <SUF> PdfDocument pdf = new PdfDocument(writer); // 初始化document Document document = new Document(pdf); PdfFont font1 = PdfFontFactory.createFont("C:\\Users\\PatrickYates\\Desktop\\JspDemo\\src\\main\\webapp\\fonts\\Yahei Consolas Hybrid.ttf", PdfEncodings.IDENTITY_H, false); // 添加段落 document.add(new Paragraph("河海大学(学生课余活动)借用教室审批表\n\n").setFont(font1).setFontSize(22).setTextAlignment(TextAlignment.CENTER)); Table table = new Table(1); table.addCell(new Cell().add(new Paragraph("申请学院(部门):" + organization).setFont(font1)).setFontSize(12).setBorder(new SolidBorder(Color.BLACK, 0.5f))); table.addCell(new Cell().add(new Paragraph("活动(报告、讲座)名称:\n" + "报告、讲座人姓名: 所属单位: 职务职称:").setFont(font1)).setFontSize(12).setBorder(new SolidBorder(Color.BLACK, 0.5f))); table.addCell(new Cell().add(new Paragraph("活动需用教室时间:" + dateofuse+" 星期 " + timeofuse).setFont(font1)).setFontSize(12).setBorder(new SolidBorder(Color.BLACK, 0.5f))); if (needMedia.equals("是")) { table.addCell(new Cell().add(new Paragraph("是否借用多媒体:" + " 是(√) 否( )\n" + "贵重物品(多媒体设备)损坏赔偿意见:\n\n\n" + "学院(部门)负责人签字:\n").setFont(font1)).setFontSize(12).setBorder(new SolidBorder(Color.BLACK, 0.5f))); } if (needMedia.equals("否")) { table.addCell(new Cell().add(new Paragraph("是否借用多媒体:" + " 是( ) 否(√)\n" + "贵重物品(多媒体设备)损坏赔偿意见:\n\n\n" + "学院(部门)负责人签字:\n").setFont(font1)).setFontSize(12).setBorder(new SolidBorder(Color.BLACK, 0.5f))); } table.addCell(new Cell().add(new Paragraph("活动组织单位:\n" + "活动负责人: 联系电话(必填): \n").setFont(font1)).setFontSize(12).setBorder(new SolidBorder(Color.BLACK, 0.5f))); table.addCell(new Cell().add(new Paragraph("活动面向对象: 参加活动人数: ").setFont(font1)).setFontSize(12).setBorder(new SolidBorder(Color.BLACK, 0.5f))); table.addCell(new Cell().add(new Paragraph("活动意义和预期效果:\n\n\n").setFont(font1)).setFontSize(12).setBorder(new SolidBorder(Color.BLACK, 0.5f))); table.addCell(new Cell().add(new Paragraph("宣传部意见:\n\n\n").setFont(font1)).setFontSize(12).setBorder(new SolidBorder(Color.BLACK, 0.5f))); table.addCell(new Cell().add(new Paragraph("学院(部门)意见:\n\n\n" + "学院(部门)负责人签字:\n" + "学院(部门)公章\n\n\n" + "年 月 日\n").setFont(font1)).setFontSize(12).setBorder(new SolidBorder(Color.BLACK, 0.5f))); document.add(table); // 关闭document document.close(); //1.获取要下载的文件的绝对路径 String realPath = this.getServletContext().getRealPath("/output.pdf"); System.out.println(realPath); //2.获取要下载的文件名 String fileName = realPath.substring(realPath.lastIndexOf("\\")+1); //3.设置content-disposition响应头控制浏览器以下载的形式打开文件 response.setContentType("application/pdf;charset=utf-8"); response.setHeader("content-disposition", "attachment;filename="+fileName); //4.获取要下载的文件输入流 InputStream in = new FileInputStream(realPath); int len = 0; //5.创建数据缓冲区 byte[] buffer = new byte[1024]; //6.通过response对象获取OutputStream流 OutputStream out = response.getOutputStream(); //7.将FileInputStream流写入到buffer缓冲区 while ((len = in.read(buffer)) > 0) { //8.使用OutputStream将缓冲区的数据输出到客户端浏览器 out.write(buffer,0,len); } in.close(); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } }
false
1,475
6
1,780
6
1,746
5
1,780
6
2,218
11
false
false
false
false
false
true
66367_2
package calculate; import com.huaban.analysis.jieba.JiebaSegmenter; import com.huaban.analysis.jieba.WordDictionary; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * @author 肖斌武. * @describe * @datetime 2020/4/17 11:36 */ public class JieBaTest { // 前缀 private static List<String> pre = new ArrayList<>(Arrays.asList("了解", "熟练", "掌握", "熟练掌握", "精通", "熟悉", "了解", "较强的", "良好的", "")); // 前缀尾 private static List<String> pre_end = new ArrayList<>(Arrays.asList("等", ".", "。", ";", ";")); // 后缀 private static List<String> pos = new ArrayList<>(Arrays.asList("经验", "优先", "能力")); // 后缀头 private static List<String> pos_start = new ArrayList<>(Arrays.asList("的", ",", ",", ".", "。", "、", ":", ":", " ")); // 结果 private static List<String> result = new ArrayList<>(); public static void nomal() { JiebaSegmenter segmenter = new JiebaSegmenter(); WordDictionary.getInstance().init(Paths.get("conf")); String sentences = "岗位职责: 1.审视、规划系统整体技术架构评,估外部技术与解决方案; 2.制定开发规范,接口规范,接口规范等。 2.主导系统架构设计和优化,以及性能调优; 3.架构设计保证系统安全,比如客户端安全,认证安全,脚本安全,防sql注入,数据库安全,SSL安全传输等。 4.参与核心模块的编码开发; 5.指导高级软件工程师的工作; 8.提升团队的技术分析,设计和编码能力。 任职要求: 1.五年以上Java开发经验;两年年以上架构设计经验,了解阿里云或者华为云相关技术,了解互联网的技术发展,了解微服务; 2.熟练掌握spring mvc,redis,mq,zookeeper,dubbo,logstash等互联网框架,并具有丰富的性能调优经验; 3.精通各种中间件的设计及应用如JEE,Messaging,Workflow,Cache,及数据层; 4.精通Linux 操作系统和mysql数据库;有较强的分析设计能力和方案整合能力; 5.了解敏捷开发,良好的沟通技能,团队合作能力。 6.有互联网项目设计经验,有大数据量,大并发经验优先。 7、3-7年工作经验; 8、2-3年电商/互联网工作经验。"; List<String> strings = segmenter.sentenceProcess(sentences.toLowerCase()); for (int i = 0; i < strings.size(); i++) { // 包含前缀 if (pre.contains(strings.get(i))) { int j = i + 1; StringBuffer temp = new StringBuffer(); // 包含前缀尾 while (!pre_end.contains(strings.get(j)) && j < strings.size()) { temp.append(strings.get(j++)); } result.add(temp.toString()); i = j + 1; } // 包含后缀 if (pos.contains(strings.get(i))) { int j = i - 1; StringBuffer temp = new StringBuffer(); // 包含后缀头 while (!pos_start.contains(strings.get(j)) && j > 0) { temp.insert(0, strings.get(j--)); } result.add(temp.toString()); } } System.out.println(result); } public static void main(String[] args) { nomal(); } }
ShenDeng75/GraduationProject
BigDataHandler/src/main/java/calculate/JieBaTest.java
969
// 后缀头
line_comment
zh-cn
package calculate; import com.huaban.analysis.jieba.JiebaSegmenter; import com.huaban.analysis.jieba.WordDictionary; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * @author 肖斌武. * @describe * @datetime 2020/4/17 11:36 */ public class JieBaTest { // 前缀 private static List<String> pre = new ArrayList<>(Arrays.asList("了解", "熟练", "掌握", "熟练掌握", "精通", "熟悉", "了解", "较强的", "良好的", "")); // 前缀尾 private static List<String> pre_end = new ArrayList<>(Arrays.asList("等", ".", "。", ";", ";")); // 后缀 private static List<String> pos = new ArrayList<>(Arrays.asList("经验", "优先", "能力")); // 后缀 <SUF> private static List<String> pos_start = new ArrayList<>(Arrays.asList("的", ",", ",", ".", "。", "、", ":", ":", " ")); // 结果 private static List<String> result = new ArrayList<>(); public static void nomal() { JiebaSegmenter segmenter = new JiebaSegmenter(); WordDictionary.getInstance().init(Paths.get("conf")); String sentences = "岗位职责: 1.审视、规划系统整体技术架构评,估外部技术与解决方案; 2.制定开发规范,接口规范,接口规范等。 2.主导系统架构设计和优化,以及性能调优; 3.架构设计保证系统安全,比如客户端安全,认证安全,脚本安全,防sql注入,数据库安全,SSL安全传输等。 4.参与核心模块的编码开发; 5.指导高级软件工程师的工作; 8.提升团队的技术分析,设计和编码能力。 任职要求: 1.五年以上Java开发经验;两年年以上架构设计经验,了解阿里云或者华为云相关技术,了解互联网的技术发展,了解微服务; 2.熟练掌握spring mvc,redis,mq,zookeeper,dubbo,logstash等互联网框架,并具有丰富的性能调优经验; 3.精通各种中间件的设计及应用如JEE,Messaging,Workflow,Cache,及数据层; 4.精通Linux 操作系统和mysql数据库;有较强的分析设计能力和方案整合能力; 5.了解敏捷开发,良好的沟通技能,团队合作能力。 6.有互联网项目设计经验,有大数据量,大并发经验优先。 7、3-7年工作经验; 8、2-3年电商/互联网工作经验。"; List<String> strings = segmenter.sentenceProcess(sentences.toLowerCase()); for (int i = 0; i < strings.size(); i++) { // 包含前缀 if (pre.contains(strings.get(i))) { int j = i + 1; StringBuffer temp = new StringBuffer(); // 包含前缀尾 while (!pre_end.contains(strings.get(j)) && j < strings.size()) { temp.append(strings.get(j++)); } result.add(temp.toString()); i = j + 1; } // 包含后缀 if (pos.contains(strings.get(i))) { int j = i - 1; StringBuffer temp = new StringBuffer(); // 包含后缀头 while (!pos_start.contains(strings.get(j)) && j > 0) { temp.insert(0, strings.get(j--)); } result.add(temp.toString()); } } System.out.println(result); } public static void main(String[] args) { nomal(); } }
false
819
5
969
5
927
4
969
5
1,363
7
false
false
false
false
false
true
27726_2
/** * The MIT License * Copyright (c) 2014-2016 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.shengfq.designpatten.chain.kingdom; import org.springframework.stereotype.Service; /** * * OrcKing makes requests that are handled by the chain. * */ @Service public class OrcKing extends RequestHandler{ @Override public void handleRequest(Request req) { //国王不参与任何执行,下发 super.handleRequest(req); } @Override public String toString() { return "国王"; } }
ShengFQ/threadpool
src/main/java/com/shengfq/designpatten/chain/kingdom/OrcKing.java
379
//国王不参与任何执行,下发
line_comment
zh-cn
/** * The MIT License * Copyright (c) 2014-2016 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.shengfq.designpatten.chain.kingdom; import org.springframework.stereotype.Service; /** * * OrcKing makes requests that are handled by the chain. * */ @Service public class OrcKing extends RequestHandler{ @Override public void handleRequest(Request req) { //国王 <SUF> super.handleRequest(req); } @Override public String toString() { return "国王"; } }
false
344
8
379
11
383
9
379
11
514
15
false
false
false
false
false
true
11969_8
package zhw.container; import zhw.service.Human; import zhw.utils.ClassUtils; import java.util.HashMap; import java.util.List; import java.util.Random; /*** * 工厂模式 */ @SuppressWarnings("all") public class HumanFactory { //定义一个map,初始化的Human对象放入这里 private static HashMap<String, Human> humans = new HashMap<String, Human>(); /*** * 造指定种别的人类 * @param clazz * @return */ public static Human createHuman(Class clazz) { Human human = null; try { //如果map中有,则直接取出,不用初始化了 //延迟始化 if (humans.containsKey(clazz.getSimpleName())) { human = humans.get(clazz.getSimpleName()); } else { //初始化 human = (Human) Class.forName(clazz.getName()).newInstance(); //放到map中 humans.put(clazz.getSimpleName(), human); } } catch (IllegalAccessException e) {//定义的人类有问题 System.out.println("人类定义错误"); } catch (InstantiationException e) { System.out.println("必须指定人类的颜色"); } catch (ClassNotFoundException e) {//定义的人类找不到 System.out.println("混蛋,你定义的人类找不到"); } return human; } /*** * 随机生成人类 * @return */ public static Human createHuman() { Human human = null; Random random = new Random(); List<Class> concreteHumanList = ClassUtils.getAllClassByInterface(Human.class); int rand = random.nextInt(concreteHumanList.size()); human = createHuman(concreteHumanList.get(rand)); return human; } }
ShepherdOutsidethefortres/JavaBase
src/zhw/container/HumanFactory.java
420
//定义的人类找不到
line_comment
zh-cn
package zhw.container; import zhw.service.Human; import zhw.utils.ClassUtils; import java.util.HashMap; import java.util.List; import java.util.Random; /*** * 工厂模式 */ @SuppressWarnings("all") public class HumanFactory { //定义一个map,初始化的Human对象放入这里 private static HashMap<String, Human> humans = new HashMap<String, Human>(); /*** * 造指定种别的人类 * @param clazz * @return */ public static Human createHuman(Class clazz) { Human human = null; try { //如果map中有,则直接取出,不用初始化了 //延迟始化 if (humans.containsKey(clazz.getSimpleName())) { human = humans.get(clazz.getSimpleName()); } else { //初始化 human = (Human) Class.forName(clazz.getName()).newInstance(); //放到map中 humans.put(clazz.getSimpleName(), human); } } catch (IllegalAccessException e) {//定义的人类有问题 System.out.println("人类定义错误"); } catch (InstantiationException e) { System.out.println("必须指定人类的颜色"); } catch (ClassNotFoundException e) {//定义 <SUF> System.out.println("混蛋,你定义的人类找不到"); } return human; } /*** * 随机生成人类 * @return */ public static Human createHuman() { Human human = null; Random random = new Random(); List<Class> concreteHumanList = ClassUtils.getAllClassByInterface(Human.class); int rand = random.nextInt(concreteHumanList.size()); human = createHuman(concreteHumanList.get(rand)); return human; } }
false
364
5
420
6
438
5
420
6
560
11
false
false
false
false
false
true
19316_5
package GC; /** * 对象生存或死亡? * 需要多次标记,判别是否死亡 * 1.可达性分析 * 2.判断是否执行或没有覆盖 finalize(),若是,直接回收;若否,则丢进 F-Queue 执行他们的 finalize() 并标记 * 3. F-Queue 执行完 finalize()后,第二次就将他们加入 即将移出 的集合待移出 * * 这里展示一个对象在被 GC 时的一次自救:how does it save itself ? 覆盖 finalize 方法,实现再次被 GCRoots Chain 引用 */ public class FinalizeEscapeGC { // 抓住 救命稻草! private static FinalizeEscapeGC SAVE_HOOK = null; // 存活信号 public void isAlive(){ System.out.println("i am alive :)"); } // 覆盖 finalize ,实现一次自救 @Override protected void finalize() throws Throwable { super.finalize(); System.out.println("finalize executed !"); // 实现自救的关键步骤 SAVE_HOOK = this; } public static void main(String[] args) throws InterruptedException { SAVE_HOOK = new FinalizeEscapeGC(); //第一次回收时的自救 SAVE_HOOK = null; System.gc(); // Finalizer 线程优先度低,所以主线程休息 0.5 s Thread.sleep(500); if(SAVE_HOOK != null){ SAVE_HOOK.isAlive(); }else { System.out.println("i am dead :("); } // 第二次回收因为先前已经执行了finalize方法,无法自救 SAVE_HOOK = null; System.gc(); // Finalizer 线程优先度低,所以主线程休息 0.5 s Thread.sleep(500); if(SAVE_HOOK != null){ SAVE_HOOK.isAlive(); }else { System.out.println("i am dead :("); } } }
ShgL6/learn-note
JVM/src/GC/FinalizeEscapeGC.java
482
//第一次回收时的自救
line_comment
zh-cn
package GC; /** * 对象生存或死亡? * 需要多次标记,判别是否死亡 * 1.可达性分析 * 2.判断是否执行或没有覆盖 finalize(),若是,直接回收;若否,则丢进 F-Queue 执行他们的 finalize() 并标记 * 3. F-Queue 执行完 finalize()后,第二次就将他们加入 即将移出 的集合待移出 * * 这里展示一个对象在被 GC 时的一次自救:how does it save itself ? 覆盖 finalize 方法,实现再次被 GCRoots Chain 引用 */ public class FinalizeEscapeGC { // 抓住 救命稻草! private static FinalizeEscapeGC SAVE_HOOK = null; // 存活信号 public void isAlive(){ System.out.println("i am alive :)"); } // 覆盖 finalize ,实现一次自救 @Override protected void finalize() throws Throwable { super.finalize(); System.out.println("finalize executed !"); // 实现自救的关键步骤 SAVE_HOOK = this; } public static void main(String[] args) throws InterruptedException { SAVE_HOOK = new FinalizeEscapeGC(); //第一 <SUF> SAVE_HOOK = null; System.gc(); // Finalizer 线程优先度低,所以主线程休息 0.5 s Thread.sleep(500); if(SAVE_HOOK != null){ SAVE_HOOK.isAlive(); }else { System.out.println("i am dead :("); } // 第二次回收因为先前已经执行了finalize方法,无法自救 SAVE_HOOK = null; System.gc(); // Finalizer 线程优先度低,所以主线程休息 0.5 s Thread.sleep(500); if(SAVE_HOOK != null){ SAVE_HOOK.isAlive(); }else { System.out.println("i am dead :("); } } }
false
438
6
482
9
476
6
482
9
694
12
false
false
false
false
false
true
31699_0
package cn.sjdeng.ds; /* 移动公司需要对已经发放的所有139段的号码进行统计排序,已经发放的139号码段的文件 存放在一个文本文件中( 原题是放在两个文件中),一个号码一行,现在需要将文 件里的 所有号码进行排序,并写入到一个新的文件中;号码 可能会有很多,最多可能有一亿个不 同的号码(所有的139段号码), 存入文本文件中大概要占1.2G的空间;jvm最大的内存 在300以内, 程序要考虑程序的可执行性及效率;只能使用Java标准库,不得使用第三方 工具。 这是个典型的大数据量的排序算法问题,首先要考虑空间问题,一下把1.2G的数据 读入内存是不太可能的,就算把1一亿条数据,转都转 换成int类型存储也要占接近400M的 空间。当时做个题目我并没有想太多 的执行效率问题,主要就考虑了空间,而且习惯性的 想到合并排序,基 本思想是原文件分割成若干个小文件并排序,再将排序好的小文件合并 得到最后结果,算法大概如下: 1.顺序读取存放号码文件的中所有号码,并取139之后的八位转换为int类型;每 读取号码数满一百万个,(这个数据可配置)将已经读取的号码排序并存入新建的临时文件。 2.将所有生成的号码有序的临时文件合并存入结果文件。 这个算法虽然解决了空间问题,但是运行效率极低,由于IO读写操作太多,加上步骤1中的 排序的算法(快速排序)本来效率就不高(对于电话排序这种特殊情况来说),导致1亿 条数据排序运行3个小时才有结果。 如果和能够减少排序的时间呢?首当其冲的减少IO操作,另外如果能够有更加好排序算法也 行。:用位向量存储电话号码,一个号码占一个bit, 一亿个电话号码也只需要大概12M的 空间;算法大概如下: 1.初始化bits[capacity]; 2.顺序所有读入电话号码,并转换为int类型,修改位向量值:bits[phoneNum]=1; 3.遍历bits数组,如果bits[index]=1,转换index为电话号码输出。 这个算法很快,不过也有他的局限性: 1.只能用于整数的排序,或者可以准确映射到正整数(对象不同对应的正整数也不相同)的数据的排序。 2.不能处理重复的数据,重复的数据排序后只有一条(如果有这种需求可以在这个算法的基础上修改, 给出现次数大于1的数据添加个计数器,然后存入Map中) 3.对于数据量极其大的数据处理可能还是比较占用空间,这种情况可配合多通道排序算法解决。 */ public class BitArray { private int[] bits = null; private int length; //用于设置或者提取int类型的数据的某一位(bit)的值时使用 private final static int[] bitValue = { 0x80000000, // 10000000 00000000 00000000 00000000 0x40000000, // 01000000 00000000 00000000 00000000 0x20000000, // 00100000 00000000 00000000 00000000 0x10000000, // 00010000 00000000 00000000 00000000 0x08000000, // 00001000 00000000 00000000 00000000 0x04000000, // 00000100 00000000 00000000 00000000 0x02000000, // 00000010 00000000 00000000 00000000 0x01000000, // 00000001 00000000 00000000 00000000 0x00800000, // 00000000 10000000 00000000 00000000 0x00400000, // 00000000 01000000 00000000 00000000 0x00200000, // 00000000 00100000 00000000 00000000 0x00100000, // 00000000 00010000 00000000 00000000 0x00080000, // 00000000 00001000 00000000 00000000 0x00040000, // 00000000 00000100 00000000 00000000 0x00020000, // 00000000 00000010 00000000 00000000 0x00010000, // 00000000 00000001 00000000 00000000 0x00008000, // 00000000 00000000 10000000 00000000 0x00004000, // 00000000 00000000 01000000 00000000 0x00002000, // 00000000 00000000 00100000 00000000 0x00001000, // 00000000 00000000 00010000 00000000 0x00000800, // 00000000 00000000 00001000 00000000 0x00000400, // 00000000 00000000 00000100 00000000 0x00000200, // 00000000 00000000 00000010 00000000 0x00000100, // 00000000 00000000 00000001 00000000 0x00000080, // 00000000 00000000 00000000 10000000 0x00000040, // 00000000 00000000 00000000 01000000 0x00000020, // 00000000 00000000 00000000 00100000 0x00000010, // 00000000 00000000 00000000 00010000 0x00000008, // 00000000 00000000 00000000 00001000 0x00000004, // 00000000 00000000 00000000 00000100 0x00000002, // 00000000 00000000 00000000 00000010 0x00000001 // 00000000 00000000 00000000 00000001 }; public BitArray(int length) { if (length < 0) { throw new IllegalArgumentException("length must be above zero!"); } bits = new int[length / 32 + ((length % 32) > 0 ? 1 : 0)]; this.length = length; } public int getBit(int index) { if (index < 0 || index > length) { throw new IllegalArgumentException("length value illegal!"); } int intData = bits[index / 32]; return ((intData & bitValue[index % 32]) >>> (32 - index % 32 - 1)); } public void setBit(int index, int value) { if (index < 0 || index > length) { throw new IllegalArgumentException("length value illegal!"); } if (value != 1 && value != 0) { throw new IllegalArgumentException("value must be 1 or 0!"); } int intData = bits[index / 32]; if (value == 1) { bits[index / 32] = intData | bitValue[index % 32]; } else { bits[index / 32] = intData & ~bitValue[index % 32]; } } public int getLength() { return length; } public static void main(String[] args) { BitArray bitArray = new BitArray(100000); bitArray.setBit(100, 1); System.out.println(bitArray.getBit(100)); } }
ShijunDeng/OnlineJudge
Other/BigData/BitArray.java
2,775
/* 移动公司需要对已经发放的所有139段的号码进行统计排序,已经发放的139号码段的文件 存放在一个文本文件中( 原题是放在两个文件中),一个号码一行,现在需要将文 件里的 所有号码进行排序,并写入到一个新的文件中;号码 可能会有很多,最多可能有一亿个不 同的号码(所有的139段号码), 存入文本文件中大概要占1.2G的空间;jvm最大的内存 在300以内, 程序要考虑程序的可执行性及效率;只能使用Java标准库,不得使用第三方 工具。 这是个典型的大数据量的排序算法问题,首先要考虑空间问题,一下把1.2G的数据 读入内存是不太可能的,就算把1一亿条数据,转都转 换成int类型存储也要占接近400M的 空间。当时做个题目我并没有想太多 的执行效率问题,主要就考虑了空间,而且习惯性的 想到合并排序,基 本思想是原文件分割成若干个小文件并排序,再将排序好的小文件合并 得到最后结果,算法大概如下: 1.顺序读取存放号码文件的中所有号码,并取139之后的八位转换为int类型;每 读取号码数满一百万个,(这个数据可配置)将已经读取的号码排序并存入新建的临时文件。 2.将所有生成的号码有序的临时文件合并存入结果文件。 这个算法虽然解决了空间问题,但是运行效率极低,由于IO读写操作太多,加上步骤1中的 排序的算法(快速排序)本来效率就不高(对于电话排序这种特殊情况来说),导致1亿 条数据排序运行3个小时才有结果。 如果和能够减少排序的时间呢?首当其冲的减少IO操作,另外如果能够有更加好排序算法也 行。:用位向量存储电话号码,一个号码占一个bit, 一亿个电话号码也只需要大概12M的 空间;算法大概如下: 1.初始化bits[capacity]; 2.顺序所有读入电话号码,并转换为int类型,修改位向量值:bits[phoneNum]=1; 3.遍历bits数组,如果bits[index]=1,转换index为电话号码输出。 这个算法很快,不过也有他的局限性: 1.只能用于整数的排序,或者可以准确映射到正整数(对象不同对应的正整数也不相同)的数据的排序。 2.不能处理重复的数据,重复的数据排序后只有一条(如果有这种需求可以在这个算法的基础上修改, 给出现次数大于1的数据添加个计数器,然后存入Map中) 3.对于数据量极其大的数据处理可能还是比较占用空间,这种情况可配合多通道排序算法解决。 */
block_comment
zh-cn
package cn.sjdeng.ds; /* 移动公 <SUF>*/ public class BitArray { private int[] bits = null; private int length; //用于设置或者提取int类型的数据的某一位(bit)的值时使用 private final static int[] bitValue = { 0x80000000, // 10000000 00000000 00000000 00000000 0x40000000, // 01000000 00000000 00000000 00000000 0x20000000, // 00100000 00000000 00000000 00000000 0x10000000, // 00010000 00000000 00000000 00000000 0x08000000, // 00001000 00000000 00000000 00000000 0x04000000, // 00000100 00000000 00000000 00000000 0x02000000, // 00000010 00000000 00000000 00000000 0x01000000, // 00000001 00000000 00000000 00000000 0x00800000, // 00000000 10000000 00000000 00000000 0x00400000, // 00000000 01000000 00000000 00000000 0x00200000, // 00000000 00100000 00000000 00000000 0x00100000, // 00000000 00010000 00000000 00000000 0x00080000, // 00000000 00001000 00000000 00000000 0x00040000, // 00000000 00000100 00000000 00000000 0x00020000, // 00000000 00000010 00000000 00000000 0x00010000, // 00000000 00000001 00000000 00000000 0x00008000, // 00000000 00000000 10000000 00000000 0x00004000, // 00000000 00000000 01000000 00000000 0x00002000, // 00000000 00000000 00100000 00000000 0x00001000, // 00000000 00000000 00010000 00000000 0x00000800, // 00000000 00000000 00001000 00000000 0x00000400, // 00000000 00000000 00000100 00000000 0x00000200, // 00000000 00000000 00000010 00000000 0x00000100, // 00000000 00000000 00000001 00000000 0x00000080, // 00000000 00000000 00000000 10000000 0x00000040, // 00000000 00000000 00000000 01000000 0x00000020, // 00000000 00000000 00000000 00100000 0x00000010, // 00000000 00000000 00000000 00010000 0x00000008, // 00000000 00000000 00000000 00001000 0x00000004, // 00000000 00000000 00000000 00000100 0x00000002, // 00000000 00000000 00000000 00000010 0x00000001 // 00000000 00000000 00000000 00000001 }; public BitArray(int length) { if (length < 0) { throw new IllegalArgumentException("length must be above zero!"); } bits = new int[length / 32 + ((length % 32) > 0 ? 1 : 0)]; this.length = length; } public int getBit(int index) { if (index < 0 || index > length) { throw new IllegalArgumentException("length value illegal!"); } int intData = bits[index / 32]; return ((intData & bitValue[index % 32]) >>> (32 - index % 32 - 1)); } public void setBit(int index, int value) { if (index < 0 || index > length) { throw new IllegalArgumentException("length value illegal!"); } if (value != 1 && value != 0) { throw new IllegalArgumentException("value must be 1 or 0!"); } int intData = bits[index / 32]; if (value == 1) { bits[index / 32] = intData | bitValue[index % 32]; } else { bits[index / 32] = intData & ~bitValue[index % 32]; } } public int getLength() { return length; } public static void main(String[] args) { BitArray bitArray = new BitArray(100000); bitArray.setBit(100, 1); System.out.println(bitArray.getBit(100)); } }
false
2,723
687
2,773
738
2,714
643
2,775
740
3,384
1,187
true
true
true
true
true
false
46069_7
package me.shouheng.data.model; import android.content.Context; import java.text.DateFormatSymbols; import java.util.Calendar; import me.shouheng.data.R; /* * 使用整数代表重复的周次信息 * 0x00 0 (0000 0000): 不重复 * 0x01 1 (0000 0001): 周一 * 0x02 2 (0000 0010): 周二 * 0x04 4 (0000 0100): 周三 * 0x08 8 (0000 1000): 周四 * 0x10 16 (0001 0000): 周五 * 0x20 32 (0010 0000): 周六 * 0x40 64 (0100 0000): 周日 * * 0x1F 31 (0001 1111): 工作日 * 0x60 96 (0110 0000): 周末 * 0x7F 127 (0111 1111): 每天重复 */ public final class DaysOfWeek { /** * 在java中提供的API中,下面的几个值分别是: * Calendar.SUNDAY == 1 * Calendar.MONDAY == 2 * …… */ private static int[] DAY_MAP = new int[] { Calendar.MONDAY, Calendar.TUESDAY, Calendar.WEDNESDAY, Calendar.THURSDAY, Calendar.FRIDAY, Calendar.SATURDAY, Calendar.SUNDAY, }; private int mDays; /** * 使用传入的布尔数组获取一个DaysOfWeek的实例 * * @param booleanArray 该布尔数组的各个位置的元素代表的依次是:周一,周二,…… * @return DaysOfWeek 的实例 */ public static DaysOfWeek getInstance(boolean[] booleanArray){ DaysOfWeek daysOfWeek = new DaysOfWeek(); int length = booleanArray.length; for (int index = 0;index<length; index++){ daysOfWeek.set(index, booleanArray[index]); } return daysOfWeek; } /** * 通过直接传入值的方式来创建一个DaysOfWeek实例 * * @param days 天的整数值 * @return DaysOfWeek实例 */ public static DaysOfWeek getInstance(int days){ return new DaysOfWeek(days); } private DaysOfWeek(){} private DaysOfWeek(int days) { mDays = days; } /** * 判断指定的日期是否被设置为重复的 * * @param day 其值等于DAY_MAP中的索引的值 * @return 指定的日期是否被设置 */ public boolean isSet(int day) { return (mDays & 1 << day) > 0; } /** * 设置某天的mDays的值 * * @param day 某天的顺序 * @param set 指定的天是否设置为重复的:set为true时,设置为1,否则为0 */ public void set(int day, boolean set) { if (set) { mDays |= 1 << day; } else { mDays &= ~(1 << day); } } public void set(DaysOfWeek dow) { mDays = dow.mDays; } public int getCoded() { return mDays; } public boolean[] getBooleanArray() { boolean[] ret = new boolean[7]; for (int i = 0; i < 7; i++) { ret[i] = isSet(i); } return ret; } public boolean isRepeatSet() { return mDays != 0; } public boolean isEveryDay() { return mDays == 0x7f; } /** * 返回从当前日期到下一个响铃日期需要的天数 * * @param nextTime 传入的日期,如果闹钟的时间小于当前时间,就将闹钟日期加1,然后设置为指定时间; * 如果闹钟时间大于当前时间,就将闹钟设置为指定的时间,日期是当前日期 * @return 获取闹钟需要增加的天数,如果返回的值小于等于0就表示无需在之前的nextTime基础上增加天数 */ public int getNextAlarm(Calendar nextTime) { if (mDays == 0) return -1; // 非重复的闹钟类型,无需增加? int today = (nextTime.get(Calendar.DAY_OF_WEEK) + 5) % 7; // 将nextTime的天转换成的DAY_MAP中的索引 // 使用从今天到下周的今天的循环方式计算距离下一个提醒需要的天数 int day = 0, dayCount = 0; for (; dayCount < 7; dayCount++) { day = (today + dayCount) % 7; if (isSet(day)) { break; } } return dayCount; } @Override public String toString() { if (mDays == 0) return "never"; if (mDays == 0x7f) return "everyday"; StringBuilder ret = new StringBuilder(); String[] dayList = new DateFormatSymbols().getShortWeekdays(); for (int i = 0; i < 7; i++) { if ((mDays & 1 << i) != 0) { ret.append(dayList[DAY_MAP[i]]); } } return ret.toString(); } public String toString(Context context, boolean showNever) { StringBuilder ret = new StringBuilder(); if (mDays == 0) { return showNever ? context.getText(R.string.text_one_shot).toString() : ""; } if (mDays == 0x7f) { return context.getText(R.string.text_every_day).toString(); } int dayCount = 0, days = mDays; while (days > 0) { if ((days & 1) == 1) { dayCount++; } days >>= 1; } DateFormatSymbols dfs = new DateFormatSymbols(); String[] dayList = dayCount > 1 ? dfs.getShortWeekdays() : dfs.getWeekdays(); for (int i = 0; i < 7; i++) { if ((mDays & 1 << i) != 0) { ret.append(dayList[DAY_MAP[i]]); dayCount -= 1; if (dayCount > 0) { ret.append(context.getText(R.string.text_day_concat)); } } } return ret.toString(); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + mDays; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; DaysOfWeek other = (DaysOfWeek) obj; return mDays == other.mDays; } }
Shouheng88/MarkNote
data/src/main/java/me/shouheng/data/model/DaysOfWeek.java
1,733
// 非重复的闹钟类型,无需增加?
line_comment
zh-cn
package me.shouheng.data.model; import android.content.Context; import java.text.DateFormatSymbols; import java.util.Calendar; import me.shouheng.data.R; /* * 使用整数代表重复的周次信息 * 0x00 0 (0000 0000): 不重复 * 0x01 1 (0000 0001): 周一 * 0x02 2 (0000 0010): 周二 * 0x04 4 (0000 0100): 周三 * 0x08 8 (0000 1000): 周四 * 0x10 16 (0001 0000): 周五 * 0x20 32 (0010 0000): 周六 * 0x40 64 (0100 0000): 周日 * * 0x1F 31 (0001 1111): 工作日 * 0x60 96 (0110 0000): 周末 * 0x7F 127 (0111 1111): 每天重复 */ public final class DaysOfWeek { /** * 在java中提供的API中,下面的几个值分别是: * Calendar.SUNDAY == 1 * Calendar.MONDAY == 2 * …… */ private static int[] DAY_MAP = new int[] { Calendar.MONDAY, Calendar.TUESDAY, Calendar.WEDNESDAY, Calendar.THURSDAY, Calendar.FRIDAY, Calendar.SATURDAY, Calendar.SUNDAY, }; private int mDays; /** * 使用传入的布尔数组获取一个DaysOfWeek的实例 * * @param booleanArray 该布尔数组的各个位置的元素代表的依次是:周一,周二,…… * @return DaysOfWeek 的实例 */ public static DaysOfWeek getInstance(boolean[] booleanArray){ DaysOfWeek daysOfWeek = new DaysOfWeek(); int length = booleanArray.length; for (int index = 0;index<length; index++){ daysOfWeek.set(index, booleanArray[index]); } return daysOfWeek; } /** * 通过直接传入值的方式来创建一个DaysOfWeek实例 * * @param days 天的整数值 * @return DaysOfWeek实例 */ public static DaysOfWeek getInstance(int days){ return new DaysOfWeek(days); } private DaysOfWeek(){} private DaysOfWeek(int days) { mDays = days; } /** * 判断指定的日期是否被设置为重复的 * * @param day 其值等于DAY_MAP中的索引的值 * @return 指定的日期是否被设置 */ public boolean isSet(int day) { return (mDays & 1 << day) > 0; } /** * 设置某天的mDays的值 * * @param day 某天的顺序 * @param set 指定的天是否设置为重复的:set为true时,设置为1,否则为0 */ public void set(int day, boolean set) { if (set) { mDays |= 1 << day; } else { mDays &= ~(1 << day); } } public void set(DaysOfWeek dow) { mDays = dow.mDays; } public int getCoded() { return mDays; } public boolean[] getBooleanArray() { boolean[] ret = new boolean[7]; for (int i = 0; i < 7; i++) { ret[i] = isSet(i); } return ret; } public boolean isRepeatSet() { return mDays != 0; } public boolean isEveryDay() { return mDays == 0x7f; } /** * 返回从当前日期到下一个响铃日期需要的天数 * * @param nextTime 传入的日期,如果闹钟的时间小于当前时间,就将闹钟日期加1,然后设置为指定时间; * 如果闹钟时间大于当前时间,就将闹钟设置为指定的时间,日期是当前日期 * @return 获取闹钟需要增加的天数,如果返回的值小于等于0就表示无需在之前的nextTime基础上增加天数 */ public int getNextAlarm(Calendar nextTime) { if (mDays == 0) return -1; // 非重 <SUF> int today = (nextTime.get(Calendar.DAY_OF_WEEK) + 5) % 7; // 将nextTime的天转换成的DAY_MAP中的索引 // 使用从今天到下周的今天的循环方式计算距离下一个提醒需要的天数 int day = 0, dayCount = 0; for (; dayCount < 7; dayCount++) { day = (today + dayCount) % 7; if (isSet(day)) { break; } } return dayCount; } @Override public String toString() { if (mDays == 0) return "never"; if (mDays == 0x7f) return "everyday"; StringBuilder ret = new StringBuilder(); String[] dayList = new DateFormatSymbols().getShortWeekdays(); for (int i = 0; i < 7; i++) { if ((mDays & 1 << i) != 0) { ret.append(dayList[DAY_MAP[i]]); } } return ret.toString(); } public String toString(Context context, boolean showNever) { StringBuilder ret = new StringBuilder(); if (mDays == 0) { return showNever ? context.getText(R.string.text_one_shot).toString() : ""; } if (mDays == 0x7f) { return context.getText(R.string.text_every_day).toString(); } int dayCount = 0, days = mDays; while (days > 0) { if ((days & 1) == 1) { dayCount++; } days >>= 1; } DateFormatSymbols dfs = new DateFormatSymbols(); String[] dayList = dayCount > 1 ? dfs.getShortWeekdays() : dfs.getWeekdays(); for (int i = 0; i < 7; i++) { if ((mDays & 1 << i) != 0) { ret.append(dayList[DAY_MAP[i]]); dayCount -= 1; if (dayCount > 0) { ret.append(context.getText(R.string.text_day_concat)); } } } return ret.toString(); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + mDays; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; DaysOfWeek other = (DaysOfWeek) obj; return mDays == other.mDays; } }
false
1,676
13
1,733
14
1,811
11
1,733
14
2,159
22
false
false
false
false
false
true
34998_2
package com.seed.data.ai.model; import lombok.Data; import lombok.NoArgsConstructor; import java.util.List; /** * @author <a href="mailto:[email protected]">Shouheng.W</a> * @version 1.0 * @date 2020/11/7 0:01 */ @Data @NoArgsConstructor public class RecognizeResult { /** * log_id : 5521953171948657672 * words_result_num : 5 * words_result : [{"location":{"width":592,"top":241,"left":93,"height":78},"words":"每次在大街上闻到像你的味道,"},{"location":{"width":595,"top":334,"left":90,"height":75},"words":"我都会控制不住地找你再找你。"},{"location":{"width":994,"top":529,"left":84,"height":53},"words":"人都是视觉动物,没有人一上来就想操纵别人的大脑。"},{"location":{"width":960,"top":621,"left":82,"height":57},"words":"每场一见钟情,无非都是性冲动在指引着我们前行。"},{"location":{"width":887,"top":710,"left":78,"height":67},"words":"我们不能否认,视觉让我们有了最开始的欲望。"}] */ private long log_id; private int words_result_num; private List<WordsResultBean> words_result; /** * 请求的错误码和错误信息 */ private String error_code; private String error_msg; @Data @NoArgsConstructor public static class WordsResultBean { /** * location : {"width":592,"top":241,"left":93,"height":78} * words : 每次在大街上闻到像你的味道, */ private LocationBean location; private String words; @Data @NoArgsConstructor public static class LocationBean { /** * width : 592 * top : 241 * left : 93 * height : 78 */ private int width; private int top; private int left; private int height; } } }
Shouheng88/Seed
seed/seed-data/src/main/java/com/seed/data/ai/model/RecognizeResult.java
584
/** * 请求的错误码和错误信息 */
block_comment
zh-cn
package com.seed.data.ai.model; import lombok.Data; import lombok.NoArgsConstructor; import java.util.List; /** * @author <a href="mailto:[email protected]">Shouheng.W</a> * @version 1.0 * @date 2020/11/7 0:01 */ @Data @NoArgsConstructor public class RecognizeResult { /** * log_id : 5521953171948657672 * words_result_num : 5 * words_result : [{"location":{"width":592,"top":241,"left":93,"height":78},"words":"每次在大街上闻到像你的味道,"},{"location":{"width":595,"top":334,"left":90,"height":75},"words":"我都会控制不住地找你再找你。"},{"location":{"width":994,"top":529,"left":84,"height":53},"words":"人都是视觉动物,没有人一上来就想操纵别人的大脑。"},{"location":{"width":960,"top":621,"left":82,"height":57},"words":"每场一见钟情,无非都是性冲动在指引着我们前行。"},{"location":{"width":887,"top":710,"left":78,"height":67},"words":"我们不能否认,视觉让我们有了最开始的欲望。"}] */ private long log_id; private int words_result_num; private List<WordsResultBean> words_result; /** * 请求的 <SUF>*/ private String error_code; private String error_msg; @Data @NoArgsConstructor public static class WordsResultBean { /** * location : {"width":592,"top":241,"left":93,"height":78} * words : 每次在大街上闻到像你的味道, */ private LocationBean location; private String words; @Data @NoArgsConstructor public static class LocationBean { /** * width : 592 * top : 241 * left : 93 * height : 78 */ private int width; private int top; private int left; private int height; } } }
false
536
13
584
12
596
14
584
12
707
23
false
false
false
false
false
true
3165_2
package models; /** * Created by shuai * on 2017/3/5. */ public class Light { private int direction; // 灯的方向:东西,南北 private int color; // 灯的颜色:红,绿 private int seconds; // 交通灯持续时间 public Light(int direction, int color, int seconds) { this.direction = direction; this.color = color; this.seconds = seconds; } public int getDirection() { return direction; } public int getColor() { return color; } public void setColor(int color) { this.color = color; } public String toString() { return "交通灯方向:" + direction + "\t" + "状态:" + color + "\t" + "颜色持续时间:" + seconds; } }
Shuai-Xie/os-semaphore-traffic-java
src/models/Light.java
210
// 灯的颜色:红,绿
line_comment
zh-cn
package models; /** * Created by shuai * on 2017/3/5. */ public class Light { private int direction; // 灯的方向:东西,南北 private int color; // 灯的 <SUF> private int seconds; // 交通灯持续时间 public Light(int direction, int color, int seconds) { this.direction = direction; this.color = color; this.seconds = seconds; } public int getDirection() { return direction; } public int getColor() { return color; } public void setColor(int color) { this.color = color; } public String toString() { return "交通灯方向:" + direction + "\t" + "状态:" + color + "\t" + "颜色持续时间:" + seconds; } }
false
187
9
210
11
211
7
210
11
261
16
false
false
false
false
false
true
52049_3
/** * @author Junlan Shuai[[email protected]]. * @date Created on 19:12 2017/1/17. * <p> * 已知二维数组@matrix,行数为@rows,列数为@columns,找出目标数@number, * 存在返回@true,不存在返回@false */ public class $03 { /** * 算法实现在已知数组(满足:每一行从左到右逐渐递增,每一列从上到下逐渐递增)中找出目标数@target: * 先取出数组中最右上角的那个数@res, * 比较res与target的大小, * 若res=target,则直接执行result=true,退出循环 * 若res>target,说明res所在列的所有数都大于target,因此执行--columns, * 若res<target,说明res所在行的所有数都小于target,因此执行++rows, * 退出循环的条件为:row<rows && columns>0 * 最后返回结果 * * @param matrix 二维数组 * @param rows 行数 * @param columns 列数 * @param number 待查找的目标数 * @return 返回结果,存在返回@true,不存在返回@false */ public static boolean find(int[][] matrix, int rows, int columns, int number) { boolean result = false; // 返回结果变量 if (matrix.length != 0 && rows > 0 && columns > 0) // 判断是否是一个二维数组 { --columns; int row = 0; while (row < rows && columns >= 0) { if (matrix[row][columns] == number) { result = true; break; } else if (matrix[row][columns] > number) --columns; else // matrix[row][columns] < number ++row; } } return result; } /** * 测试函数 * * @param args */ public static void main(String[] args) { int[][] a = {{1, 2, 8, 9}, {2, 4, 9, 12}, {4, 7, 10, 13}, {6, 8, 11, 15}}; boolean c = find(a, 4, 4, 0); System.out.println(c); } }
ShuaiJunlan/DataStructure-Algorithm
Java/offer/$03.java
593
// 判断是否是一个二维数组
line_comment
zh-cn
/** * @author Junlan Shuai[[email protected]]. * @date Created on 19:12 2017/1/17. * <p> * 已知二维数组@matrix,行数为@rows,列数为@columns,找出目标数@number, * 存在返回@true,不存在返回@false */ public class $03 { /** * 算法实现在已知数组(满足:每一行从左到右逐渐递增,每一列从上到下逐渐递增)中找出目标数@target: * 先取出数组中最右上角的那个数@res, * 比较res与target的大小, * 若res=target,则直接执行result=true,退出循环 * 若res>target,说明res所在列的所有数都大于target,因此执行--columns, * 若res<target,说明res所在行的所有数都小于target,因此执行++rows, * 退出循环的条件为:row<rows && columns>0 * 最后返回结果 * * @param matrix 二维数组 * @param rows 行数 * @param columns 列数 * @param number 待查找的目标数 * @return 返回结果,存在返回@true,不存在返回@false */ public static boolean find(int[][] matrix, int rows, int columns, int number) { boolean result = false; // 返回结果变量 if (matrix.length != 0 && rows > 0 && columns > 0) // 判断 <SUF> { --columns; int row = 0; while (row < rows && columns >= 0) { if (matrix[row][columns] == number) { result = true; break; } else if (matrix[row][columns] > number) --columns; else // matrix[row][columns] < number ++row; } } return result; } /** * 测试函数 * * @param args */ public static void main(String[] args) { int[][] a = {{1, 2, 8, 9}, {2, 4, 9, 12}, {4, 7, 10, 13}, {6, 8, 11, 15}}; boolean c = find(a, 4, 4, 0); System.out.println(c); } }
false
565
8
593
8
605
7
593
8
753
15
false
false
false
false
false
true
24366_6
package leetcode; /** * @author swzhao * @data 2023/10/2 12:44 * @Discreption <> 买卖股票的最佳时机 * 买卖股票的最佳时机 II */ public class MaxProfit { public static void main(String[] args) { int[] ints = {1,2,3,4,5}; System.out.println(process2(ints)); } /** * 问题一: * @param prices * @return */ public static int process1(int[] prices) { int min = Integer.MAX_VALUE; int res = 0; for (int i = 0; i < prices.length; i++){ // 计算到目前位置的最小值 min = Math.min(min, prices[i]); // 如果今天卖,那么利润最大就是最小值买的那天 res = Math.max(res, prices[i] - min); } return res; } /** * 问题二: * @param prices * @return */ public static int process2(int[] prices) { if (prices == null || prices.length <= 1) { return 0; } // 利润 int res = 0; // 买点 int mai1 = 0; // 卖点 int mai2 = 0; for (int i = 1; i < prices.length; i++) { if (prices[i] <= prices[i-1]) { // 跌,卖点,计算利润,并且重新等待买的时机 res += prices[mai2] - prices[mai1]; mai1 = mai2; mai1++; mai2++; }else { // 涨,买点 mai2++; } } // 最后可能没有跌点,需要收尾 res += prices[mai2] - prices[mai1]; return res; } }
ShuoWen5656/AlgorithmManuscript
src/leetcode/MaxProfit.java
483
// 涨,买点
line_comment
zh-cn
package leetcode; /** * @author swzhao * @data 2023/10/2 12:44 * @Discreption <> 买卖股票的最佳时机 * 买卖股票的最佳时机 II */ public class MaxProfit { public static void main(String[] args) { int[] ints = {1,2,3,4,5}; System.out.println(process2(ints)); } /** * 问题一: * @param prices * @return */ public static int process1(int[] prices) { int min = Integer.MAX_VALUE; int res = 0; for (int i = 0; i < prices.length; i++){ // 计算到目前位置的最小值 min = Math.min(min, prices[i]); // 如果今天卖,那么利润最大就是最小值买的那天 res = Math.max(res, prices[i] - min); } return res; } /** * 问题二: * @param prices * @return */ public static int process2(int[] prices) { if (prices == null || prices.length <= 1) { return 0; } // 利润 int res = 0; // 买点 int mai1 = 0; // 卖点 int mai2 = 0; for (int i = 1; i < prices.length; i++) { if (prices[i] <= prices[i-1]) { // 跌,卖点,计算利润,并且重新等待买的时机 res += prices[mai2] - prices[mai1]; mai1 = mai2; mai1++; mai2++; }else { // 涨, <SUF> mai2++; } } // 最后可能没有跌点,需要收尾 res += prices[mai2] - prices[mai1]; return res; } }
false
444
7
483
7
499
6
483
7
611
10
false
false
false
false
false
true
50340_18
package com.thelionking.campus.fragment; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import android.app.Activity; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.Button; import android.widget.GridView; import android.widget.ImageView; import android.widget.SimpleAdapter; import android.widget.TextView; import android.widget.Toast; import com.thelionking.campus.R; /** * @author the lion king * <b>美食Fragment</b> */ public class DelicacyFragment extends Fragment{ public static final String TAG = "DelicacyFragment"; private View topLayout; private ImageView topMenuButton; private TextView topTitle; private ImageView topRefreshButton; private View rootLayout; //private ListView listViewLeft; //private ListView listViewRight; private GridView mDisplay; //美食显示列表 //private ContentView contentview; private Button schoolfoodButton1; private Button schoolfoodButton2; private int res[] = new int[] {R.drawable.an06, R.drawable.an07,R.drawable.an08, R.drawable.an04,R.drawable.an05}; private Integer[] mThumbIds = { R.drawable.an06, R.drawable.an07,R.drawable.an07,R.drawable.an08, R.drawable.an04,R.drawable.an07,R.drawable.an08, R.drawable.an04,R.drawable.an05 }; private String[] mTextValues = { "甜心葡萄","旋风冰激凌","麦旋风", "水煮鱼","牛肉玉米","Spinner", "","","" }; private String[] mTime = { "很不错!","味道超赞哦","建议大家尝一下", "很美味,32赞","好好吃哦!","我们都喜欢", "","","" }; String[] from = { "imageView", "content","time" }; int[] to = { R.id.schoolfood_item_img, R.id.schoolfood_item_title,R.id.schoolfood_item_description }; private TextView schoolfood_content; private TextView schoolfood_time; private ImageView schoolfood_image; int[] leftViewsHeights; int[] rightViewsHeights; private ActionContext actionContext; public DelicacyFragment() { } public void setActionContext(final ActionContext actionContext){ this.actionContext = actionContext; } @Override public void setArguments(Bundle args) { super.setArguments(args); } @Override public void onAttach(Activity activity) { super.onAttach(activity); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { //rootLayout = inflater.inflate(R.layout.self_study_room_fragment, null); rootLayout = inflater.inflate(R.layout.schoolfood, null); //setContentView(R.layout.schoolfood_list_view_item); topLayout = rootLayout.findViewById(R.id.top_layout); topTitle = (TextView)rootLayout.findViewById(R.id.top_title); topTitle.setText("美食"); topMenuButton = (ImageView)rootLayout.findViewById(R.id.top_menu_button); topRefreshButton = (ImageView)rootLayout.findViewById(R.id.top_refresh_button); topRefreshButton.setVisibility(View.GONE); mDisplay=(GridView)rootLayout.findViewById(R.id.food_display); schoolfoodButton1=(Button)rootLayout.findViewById(R.id.schoolfood_button1); schoolfoodButton2=(Button)rootLayout.findViewById(R.id.schoolfood_button2); schoolfood_content=(TextView)rootLayout.findViewById(R.id.schoolfood_item_img); schoolfood_time=(TextView)rootLayout.findViewById(R.id.schoolfood_item_title); schoolfood_image=(ImageView)rootLayout.findViewById(R.id.schoolfood_item_description); //List<Map<String, Object>> data = new ArrayList<Map<String,Object>>(); // for(int i=0;i<mThumbIds.length;i++){ // // // schoolfood_image.setImageResource(mThumbIds[i]); // schoolfood_content.setText(mTextValues[i]); // schoolfood_time.setText(mTime[i]); // // } List<Map<String, Object>> data = new ArrayList<Map<String,Object>>(); //List<Map<String, Object>> content = new ArrayList<Map<String,Object>>(); //List<Map<String, Object>> time = new ArrayList<Map<String,Object>>(); for(int i=0;i<res.length;i++){ Map<String,Object> map = new HashMap<String, Object>(); //Map<String,Object> map1 = new HashMap<String, Object>(); //Map<String,Object> map2 = new HashMap<String, Object>(); map.put("imageView",mThumbIds[i]); map.put("content", mTextValues[i]); map.put("time",mTime[i]); data.add(map); } SimpleAdapter simpleAdapter = new SimpleAdapter(getActivity(),data,R.layout.schoolfood_item1,from,to ); mDisplay.setAdapter(simpleAdapter); //思考题 在Gridview中 SimpleAdpater 图片添加事件 //mDisplay.setAdapter(new ImageAdapter(getActivity())); mDisplay.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { //可以显示图片大图 Toast.makeText(getActivity().getApplicationContext(), "xxxx"+res[position], Toast.LENGTH_LONG).show(); } }); //setListener(); //init(); //listViewLeft = (ListView) rootLayout.findViewById(R.id.list_view_left); //listViewRight = (ListView) rootLayout.findViewById(R.id.list_view_right); bindListener(); return rootLayout; } private void init() { // TODO Auto-generated method stub } private void setListener() { // TODO Auto-generated method stub } private final void bindListener(){ topMenuButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(topMenuButton == v){ actionContext.openMenu(0); } } }); } @Override public void onStart() { super.onStart(); } @Override public void onResume() { super.onResume(); } @Override public void onPause() { super.onPause(); } @Override public void onStop() { super.onStop(); } @Override public void onDestroy() { super.onDestroy(); } @Override public void onDetach() { super.onDetach(); } }
Simbaorz/easycampus
android/campus/src/com/thelionking/campus/fragment/DelicacyFragment.java
1,842
//可以显示图片大图
line_comment
zh-cn
package com.thelionking.campus.fragment; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import android.app.Activity; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.Button; import android.widget.GridView; import android.widget.ImageView; import android.widget.SimpleAdapter; import android.widget.TextView; import android.widget.Toast; import com.thelionking.campus.R; /** * @author the lion king * <b>美食Fragment</b> */ public class DelicacyFragment extends Fragment{ public static final String TAG = "DelicacyFragment"; private View topLayout; private ImageView topMenuButton; private TextView topTitle; private ImageView topRefreshButton; private View rootLayout; //private ListView listViewLeft; //private ListView listViewRight; private GridView mDisplay; //美食显示列表 //private ContentView contentview; private Button schoolfoodButton1; private Button schoolfoodButton2; private int res[] = new int[] {R.drawable.an06, R.drawable.an07,R.drawable.an08, R.drawable.an04,R.drawable.an05}; private Integer[] mThumbIds = { R.drawable.an06, R.drawable.an07,R.drawable.an07,R.drawable.an08, R.drawable.an04,R.drawable.an07,R.drawable.an08, R.drawable.an04,R.drawable.an05 }; private String[] mTextValues = { "甜心葡萄","旋风冰激凌","麦旋风", "水煮鱼","牛肉玉米","Spinner", "","","" }; private String[] mTime = { "很不错!","味道超赞哦","建议大家尝一下", "很美味,32赞","好好吃哦!","我们都喜欢", "","","" }; String[] from = { "imageView", "content","time" }; int[] to = { R.id.schoolfood_item_img, R.id.schoolfood_item_title,R.id.schoolfood_item_description }; private TextView schoolfood_content; private TextView schoolfood_time; private ImageView schoolfood_image; int[] leftViewsHeights; int[] rightViewsHeights; private ActionContext actionContext; public DelicacyFragment() { } public void setActionContext(final ActionContext actionContext){ this.actionContext = actionContext; } @Override public void setArguments(Bundle args) { super.setArguments(args); } @Override public void onAttach(Activity activity) { super.onAttach(activity); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { //rootLayout = inflater.inflate(R.layout.self_study_room_fragment, null); rootLayout = inflater.inflate(R.layout.schoolfood, null); //setContentView(R.layout.schoolfood_list_view_item); topLayout = rootLayout.findViewById(R.id.top_layout); topTitle = (TextView)rootLayout.findViewById(R.id.top_title); topTitle.setText("美食"); topMenuButton = (ImageView)rootLayout.findViewById(R.id.top_menu_button); topRefreshButton = (ImageView)rootLayout.findViewById(R.id.top_refresh_button); topRefreshButton.setVisibility(View.GONE); mDisplay=(GridView)rootLayout.findViewById(R.id.food_display); schoolfoodButton1=(Button)rootLayout.findViewById(R.id.schoolfood_button1); schoolfoodButton2=(Button)rootLayout.findViewById(R.id.schoolfood_button2); schoolfood_content=(TextView)rootLayout.findViewById(R.id.schoolfood_item_img); schoolfood_time=(TextView)rootLayout.findViewById(R.id.schoolfood_item_title); schoolfood_image=(ImageView)rootLayout.findViewById(R.id.schoolfood_item_description); //List<Map<String, Object>> data = new ArrayList<Map<String,Object>>(); // for(int i=0;i<mThumbIds.length;i++){ // // // schoolfood_image.setImageResource(mThumbIds[i]); // schoolfood_content.setText(mTextValues[i]); // schoolfood_time.setText(mTime[i]); // // } List<Map<String, Object>> data = new ArrayList<Map<String,Object>>(); //List<Map<String, Object>> content = new ArrayList<Map<String,Object>>(); //List<Map<String, Object>> time = new ArrayList<Map<String,Object>>(); for(int i=0;i<res.length;i++){ Map<String,Object> map = new HashMap<String, Object>(); //Map<String,Object> map1 = new HashMap<String, Object>(); //Map<String,Object> map2 = new HashMap<String, Object>(); map.put("imageView",mThumbIds[i]); map.put("content", mTextValues[i]); map.put("time",mTime[i]); data.add(map); } SimpleAdapter simpleAdapter = new SimpleAdapter(getActivity(),data,R.layout.schoolfood_item1,from,to ); mDisplay.setAdapter(simpleAdapter); //思考题 在Gridview中 SimpleAdpater 图片添加事件 //mDisplay.setAdapter(new ImageAdapter(getActivity())); mDisplay.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { //可以 <SUF> Toast.makeText(getActivity().getApplicationContext(), "xxxx"+res[position], Toast.LENGTH_LONG).show(); } }); //setListener(); //init(); //listViewLeft = (ListView) rootLayout.findViewById(R.id.list_view_left); //listViewRight = (ListView) rootLayout.findViewById(R.id.list_view_right); bindListener(); return rootLayout; } private void init() { // TODO Auto-generated method stub } private void setListener() { // TODO Auto-generated method stub } private final void bindListener(){ topMenuButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(topMenuButton == v){ actionContext.openMenu(0); } } }); } @Override public void onStart() { super.onStart(); } @Override public void onResume() { super.onResume(); } @Override public void onPause() { super.onPause(); } @Override public void onStop() { super.onStop(); } @Override public void onDestroy() { super.onDestroy(); } @Override public void onDetach() { super.onDetach(); } }
false
1,459
7
1,808
7
1,922
8
1,808
7
2,180
11
false
false
false
false
false
true
24945_54
package com.entity; import com.baomidou.mybatisplus.annotations.TableId; import com.baomidou.mybatisplus.annotations.TableName; import javax.validation.constraints.NotBlank; import javax.validation.constraints.NotEmpty; import javax.validation.constraints.NotNull; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import java.lang.reflect.InvocationTargetException; import java.io.Serializable; import java.util.Date; import java.util.List; import org.springframework.format.annotation.DateTimeFormat; import com.fasterxml.jackson.annotation.JsonFormat; import org.apache.commons.beanutils.BeanUtils; import com.baomidou.mybatisplus.annotations.TableField; import com.baomidou.mybatisplus.enums.FieldFill; import com.baomidou.mybatisplus.enums.IdType; /** * 取货信息 * 数据库通用操作实体类(普通增删改查) * @author * @email * @date 2020-12-02 20:04:37 */ @TableName("quhuoxinxi") public class QuhuoxinxiEntity<T> implements Serializable { private static final long serialVersionUID = 1L; public QuhuoxinxiEntity() { } public QuhuoxinxiEntity(T t) { try { BeanUtils.copyProperties(this, t); } catch (IllegalAccessException | InvocationTargetException e) { // TODO Auto-generated catch block e.printStackTrace(); } } /** * 主键id */ @TableId private Long id; /** * 快递编号 */ private String kuaidibianhao; /** * 商品名称 */ private String shangpinmingcheng; /** * 图片 */ private String tupian; /** * 数量 */ private Integer shuliang; /** * 运费险 */ private String yunfeixian; /** * 快递状态 */ private String kuaidizhuangtai; /** * 学号 */ private String xuehao; /** * 学生姓名 */ private String xueshengxingming; /** * 手机 */ private String shouji; /** * 大学 */ private String daxue; /** * 班级 */ private String banji; /** * 楼栋 */ private String loudong; /** * 楼层 */ private String louceng; /** * 备注 */ private String beizhu; /** * 快递员工号 */ private String kuaidiyuangonghao; /** * 快递员姓名 */ private String kuaidiyuanxingming; /** * 联系电话 */ private String lianxidianhua; /** * 年龄 */ private String nianling; /** * 用户id */ private Long userid; @JsonFormat(locale="zh", timezone="GMT+8", pattern="yyyy-MM-dd HH:mm:ss") @DateTimeFormat private Date addtime; public Date getAddtime() { return addtime; } public void setAddtime(Date addtime) { this.addtime = addtime; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } /** * 设置:快递编号 */ public void setKuaidibianhao(String kuaidibianhao) { this.kuaidibianhao = kuaidibianhao; } /** * 获取:快递编号 */ public String getKuaidibianhao() { return kuaidibianhao; } /** * 设置:商品名称 */ public void setShangpinmingcheng(String shangpinmingcheng) { this.shangpinmingcheng = shangpinmingcheng; } /** * 获取:商品名称 */ public String getShangpinmingcheng() { return shangpinmingcheng; } /** * 设置:图片 */ public void setTupian(String tupian) { this.tupian = tupian; } /** * 获取:图片 */ public String getTupian() { return tupian; } /** * 设置:数量 */ public void setShuliang(Integer shuliang) { this.shuliang = shuliang; } /** * 获取:数量 */ public Integer getShuliang() { return shuliang; } /** * 设置:运费险 */ public void setYunfeixian(String yunfeixian) { this.yunfeixian = yunfeixian; } /** * 获取:运费险 */ public String getYunfeixian() { return yunfeixian; } /** * 设置:快递状态 */ public void setKuaidizhuangtai(String kuaidizhuangtai) { this.kuaidizhuangtai = kuaidizhuangtai; } /** * 获取:快递状态 */ public String getKuaidizhuangtai() { return kuaidizhuangtai; } /** * 设置:学号 */ public void setXuehao(String xuehao) { this.xuehao = xuehao; } /** * 获取:学号 */ public String getXuehao() { return xuehao; } /** * 设置:学生姓名 */ public void setXueshengxingming(String xueshengxingming) { this.xueshengxingming = xueshengxingming; } /** * 获取:学生姓名 */ public String getXueshengxingming() { return xueshengxingming; } /** * 设置:手机 */ public void setShouji(String shouji) { this.shouji = shouji; } /** * 获取:手机 */ public String getShouji() { return shouji; } /** * 设置:大学 */ public void setDaxue(String daxue) { this.daxue = daxue; } /** * 获取:大学 */ public String getDaxue() { return daxue; } /** * 设置:班级 */ public void setBanji(String banji) { this.banji = banji; } /** * 获取:班级 */ public String getBanji() { return banji; } /** * 设置:楼栋 */ public void setLoudong(String loudong) { this.loudong = loudong; } /** * 获取:楼栋 */ public String getLoudong() { return loudong; } /** * 设置:楼层 */ public void setLouceng(String louceng) { this.louceng = louceng; } /** * 获取:楼层 */ public String getLouceng() { return louceng; } /** * 设置:备注 */ public void setBeizhu(String beizhu) { this.beizhu = beizhu; } /** * 获取:备注 */ public String getBeizhu() { return beizhu; } /** * 设置:快递员工号 */ public void setKuaidiyuangonghao(String kuaidiyuangonghao) { this.kuaidiyuangonghao = kuaidiyuangonghao; } /** * 获取:快递员工号 */ public String getKuaidiyuangonghao() { return kuaidiyuangonghao; } /** * 设置:快递员姓名 */ public void setKuaidiyuanxingming(String kuaidiyuanxingming) { this.kuaidiyuanxingming = kuaidiyuanxingming; } /** * 获取:快递员姓名 */ public String getKuaidiyuanxingming() { return kuaidiyuanxingming; } /** * 设置:联系电话 */ public void setLianxidianhua(String lianxidianhua) { this.lianxidianhua = lianxidianhua; } /** * 获取:联系电话 */ public String getLianxidianhua() { return lianxidianhua; } /** * 设置:年龄 */ public void setNianling(String nianling) { this.nianling = nianling; } /** * 获取:年龄 */ public String getNianling() { return nianling; } /** * 设置:用户id */ public void setUserid(Long userid) { this.userid = userid; } /** * 获取:用户id */ public Long getUserid() { return userid; } }
SimpleGraduationProjects/CampusExpressServiceManagementSystem
src/main/java/com/entity/QuhuoxinxiEntity.java
2,436
/** * 设置:联系电话 */
block_comment
zh-cn
package com.entity; import com.baomidou.mybatisplus.annotations.TableId; import com.baomidou.mybatisplus.annotations.TableName; import javax.validation.constraints.NotBlank; import javax.validation.constraints.NotEmpty; import javax.validation.constraints.NotNull; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import java.lang.reflect.InvocationTargetException; import java.io.Serializable; import java.util.Date; import java.util.List; import org.springframework.format.annotation.DateTimeFormat; import com.fasterxml.jackson.annotation.JsonFormat; import org.apache.commons.beanutils.BeanUtils; import com.baomidou.mybatisplus.annotations.TableField; import com.baomidou.mybatisplus.enums.FieldFill; import com.baomidou.mybatisplus.enums.IdType; /** * 取货信息 * 数据库通用操作实体类(普通增删改查) * @author * @email * @date 2020-12-02 20:04:37 */ @TableName("quhuoxinxi") public class QuhuoxinxiEntity<T> implements Serializable { private static final long serialVersionUID = 1L; public QuhuoxinxiEntity() { } public QuhuoxinxiEntity(T t) { try { BeanUtils.copyProperties(this, t); } catch (IllegalAccessException | InvocationTargetException e) { // TODO Auto-generated catch block e.printStackTrace(); } } /** * 主键id */ @TableId private Long id; /** * 快递编号 */ private String kuaidibianhao; /** * 商品名称 */ private String shangpinmingcheng; /** * 图片 */ private String tupian; /** * 数量 */ private Integer shuliang; /** * 运费险 */ private String yunfeixian; /** * 快递状态 */ private String kuaidizhuangtai; /** * 学号 */ private String xuehao; /** * 学生姓名 */ private String xueshengxingming; /** * 手机 */ private String shouji; /** * 大学 */ private String daxue; /** * 班级 */ private String banji; /** * 楼栋 */ private String loudong; /** * 楼层 */ private String louceng; /** * 备注 */ private String beizhu; /** * 快递员工号 */ private String kuaidiyuangonghao; /** * 快递员姓名 */ private String kuaidiyuanxingming; /** * 联系电话 */ private String lianxidianhua; /** * 年龄 */ private String nianling; /** * 用户id */ private Long userid; @JsonFormat(locale="zh", timezone="GMT+8", pattern="yyyy-MM-dd HH:mm:ss") @DateTimeFormat private Date addtime; public Date getAddtime() { return addtime; } public void setAddtime(Date addtime) { this.addtime = addtime; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } /** * 设置:快递编号 */ public void setKuaidibianhao(String kuaidibianhao) { this.kuaidibianhao = kuaidibianhao; } /** * 获取:快递编号 */ public String getKuaidibianhao() { return kuaidibianhao; } /** * 设置:商品名称 */ public void setShangpinmingcheng(String shangpinmingcheng) { this.shangpinmingcheng = shangpinmingcheng; } /** * 获取:商品名称 */ public String getShangpinmingcheng() { return shangpinmingcheng; } /** * 设置:图片 */ public void setTupian(String tupian) { this.tupian = tupian; } /** * 获取:图片 */ public String getTupian() { return tupian; } /** * 设置:数量 */ public void setShuliang(Integer shuliang) { this.shuliang = shuliang; } /** * 获取:数量 */ public Integer getShuliang() { return shuliang; } /** * 设置:运费险 */ public void setYunfeixian(String yunfeixian) { this.yunfeixian = yunfeixian; } /** * 获取:运费险 */ public String getYunfeixian() { return yunfeixian; } /** * 设置:快递状态 */ public void setKuaidizhuangtai(String kuaidizhuangtai) { this.kuaidizhuangtai = kuaidizhuangtai; } /** * 获取:快递状态 */ public String getKuaidizhuangtai() { return kuaidizhuangtai; } /** * 设置:学号 */ public void setXuehao(String xuehao) { this.xuehao = xuehao; } /** * 获取:学号 */ public String getXuehao() { return xuehao; } /** * 设置:学生姓名 */ public void setXueshengxingming(String xueshengxingming) { this.xueshengxingming = xueshengxingming; } /** * 获取:学生姓名 */ public String getXueshengxingming() { return xueshengxingming; } /** * 设置:手机 */ public void setShouji(String shouji) { this.shouji = shouji; } /** * 获取:手机 */ public String getShouji() { return shouji; } /** * 设置:大学 */ public void setDaxue(String daxue) { this.daxue = daxue; } /** * 获取:大学 */ public String getDaxue() { return daxue; } /** * 设置:班级 */ public void setBanji(String banji) { this.banji = banji; } /** * 获取:班级 */ public String getBanji() { return banji; } /** * 设置:楼栋 */ public void setLoudong(String loudong) { this.loudong = loudong; } /** * 获取:楼栋 */ public String getLoudong() { return loudong; } /** * 设置:楼层 */ public void setLouceng(String louceng) { this.louceng = louceng; } /** * 获取:楼层 */ public String getLouceng() { return louceng; } /** * 设置:备注 */ public void setBeizhu(String beizhu) { this.beizhu = beizhu; } /** * 获取:备注 */ public String getBeizhu() { return beizhu; } /** * 设置:快递员工号 */ public void setKuaidiyuangonghao(String kuaidiyuangonghao) { this.kuaidiyuangonghao = kuaidiyuangonghao; } /** * 获取:快递员工号 */ public String getKuaidiyuangonghao() { return kuaidiyuangonghao; } /** * 设置:快递员姓名 */ public void setKuaidiyuanxingming(String kuaidiyuanxingming) { this.kuaidiyuanxingming = kuaidiyuanxingming; } /** * 获取:快递员姓名 */ public String getKuaidiyuanxingming() { return kuaidiyuanxingming; } /** * 设置: <SUF>*/ public void setLianxidianhua(String lianxidianhua) { this.lianxidianhua = lianxidianhua; } /** * 获取:联系电话 */ public String getLianxidianhua() { return lianxidianhua; } /** * 设置:年龄 */ public void setNianling(String nianling) { this.nianling = nianling; } /** * 获取:年龄 */ public String getNianling() { return nianling; } /** * 设置:用户id */ public void setUserid(Long userid) { this.userid = userid; } /** * 获取:用户id */ public Long getUserid() { return userid; } }
false
2,049
9
2,436
10
2,457
11
2,436
10
3,108
15
false
false
false
false
false
true
22419_5
package com.model; /** * 管理员信息Model类 */ public class Tadmin { public Tadmin() { } /** * id */ private Integer id; /** * 用户名 */ private String uname; /** * 密码 */ private String upwd; /** * 姓名 */ private String name; /** * 联系电话 */ private String tel; /** * 用户类型 */ private String utype; public String getUtype() { return utype; } public void setUtype(String utype) { this.utype = utype; } public Integer getId() { return this.id; } public void setId(Integer id) { this.id = id; } public String getUname() { return this.uname; } public void setUname(String uname) { this.uname = uname; } public String getUpwd() { return this.upwd; } public void setUpwd(String upwd) { this.upwd = upwd; } public String getName() { return this.name; } public void setName(String name) { this.name = name; } public String getTel() { return this.tel; } public void setTel(String tel) { this.tel = tel; } }
SimpleGraduationProjects/OnlineJobRecruitmentManagementSystem
src/com/model/Tadmin.java
380
/** * 联系电话 */
block_comment
zh-cn
package com.model; /** * 管理员信息Model类 */ public class Tadmin { public Tadmin() { } /** * id */ private Integer id; /** * 用户名 */ private String uname; /** * 密码 */ private String upwd; /** * 姓名 */ private String name; /** * 联系电 <SUF>*/ private String tel; /** * 用户类型 */ private String utype; public String getUtype() { return utype; } public void setUtype(String utype) { this.utype = utype; } public Integer getId() { return this.id; } public void setId(Integer id) { this.id = id; } public String getUname() { return this.uname; } public void setUname(String uname) { this.uname = uname; } public String getUpwd() { return this.upwd; } public void setUpwd(String upwd) { this.upwd = upwd; } public String getName() { return this.name; } public void setName(String name) { this.name = name; } public String getTel() { return this.tel; } public void setTel(String tel) { this.tel = tel; } }
false
297
11
380
9
385
10
380
9
438
12
false
false
false
false
false
true
16471_1
package com.entity.vo; import com.entity.YonghuEntity; import com.baomidou.mybatisplus.annotations.TableName; import java.util.Date; import org.springframework.format.annotation.DateTimeFormat; import com.fasterxml.jackson.annotation.JsonFormat; import java.io.Serializable; /** * 用户 * 手机端接口返回实体辅助类 * (主要作用去除一些不必要的字段) * @author * @email * @date 2021-04-18 15:18:17 */ public class YonghuVO implements Serializable { private static final long serialVersionUID = 1L; /** * 密码 */ private String mima; /** * 姓名 */ private String xingming; /** * 性别 */ private String xingbie; /** * 手机 */ private String shouji; /** * 邮箱 */ private String youxiang; /** * 身份证 */ private String shenfenzheng; /** * 照片 */ private String zhaopian; /** * 余额 */ private Float money; /** * 设置:密码 */ public void setMima(String mima) { this.mima = mima; } /** * 获取:密码 */ public String getMima() { return mima; } /** * 设置:姓名 */ public void setXingming(String xingming) { this.xingming = xingming; } /** * 获取:姓名 */ public String getXingming() { return xingming; } /** * 设置:性别 */ public void setXingbie(String xingbie) { this.xingbie = xingbie; } /** * 获取:性别 */ public String getXingbie() { return xingbie; } /** * 设置:手机 */ public void setShouji(String shouji) { this.shouji = shouji; } /** * 获取:手机 */ public String getShouji() { return shouji; } /** * 设置:邮箱 */ public void setYouxiang(String youxiang) { this.youxiang = youxiang; } /** * 获取:邮箱 */ public String getYouxiang() { return youxiang; } /** * 设置:身份证 */ public void setShenfenzheng(String shenfenzheng) { this.shenfenzheng = shenfenzheng; } /** * 获取:身份证 */ public String getShenfenzheng() { return shenfenzheng; } /** * 设置:照片 */ public void setZhaopian(String zhaopian) { this.zhaopian = zhaopian; } /** * 获取:照片 */ public String getZhaopian() { return zhaopian; } /** * 设置:余额 */ public void setMoney(Float money) { this.money = money; } /** * 获取:余额 */ public Float getMoney() { return money; } }
SimpleGraduationProjects/PovertyAlleviationAndAgriculturalAssistanceManagementSystem
src/main/java/com/entity/vo/YonghuVO.java
894
/** * 密码 */
block_comment
zh-cn
package com.entity.vo; import com.entity.YonghuEntity; import com.baomidou.mybatisplus.annotations.TableName; import java.util.Date; import org.springframework.format.annotation.DateTimeFormat; import com.fasterxml.jackson.annotation.JsonFormat; import java.io.Serializable; /** * 用户 * 手机端接口返回实体辅助类 * (主要作用去除一些不必要的字段) * @author * @email * @date 2021-04-18 15:18:17 */ public class YonghuVO implements Serializable { private static final long serialVersionUID = 1L; /** * 密码 <SUF>*/ private String mima; /** * 姓名 */ private String xingming; /** * 性别 */ private String xingbie; /** * 手机 */ private String shouji; /** * 邮箱 */ private String youxiang; /** * 身份证 */ private String shenfenzheng; /** * 照片 */ private String zhaopian; /** * 余额 */ private Float money; /** * 设置:密码 */ public void setMima(String mima) { this.mima = mima; } /** * 获取:密码 */ public String getMima() { return mima; } /** * 设置:姓名 */ public void setXingming(String xingming) { this.xingming = xingming; } /** * 获取:姓名 */ public String getXingming() { return xingming; } /** * 设置:性别 */ public void setXingbie(String xingbie) { this.xingbie = xingbie; } /** * 获取:性别 */ public String getXingbie() { return xingbie; } /** * 设置:手机 */ public void setShouji(String shouji) { this.shouji = shouji; } /** * 获取:手机 */ public String getShouji() { return shouji; } /** * 设置:邮箱 */ public void setYouxiang(String youxiang) { this.youxiang = youxiang; } /** * 获取:邮箱 */ public String getYouxiang() { return youxiang; } /** * 设置:身份证 */ public void setShenfenzheng(String shenfenzheng) { this.shenfenzheng = shenfenzheng; } /** * 获取:身份证 */ public String getShenfenzheng() { return shenfenzheng; } /** * 设置:照片 */ public void setZhaopian(String zhaopian) { this.zhaopian = zhaopian; } /** * 获取:照片 */ public String getZhaopian() { return zhaopian; } /** * 设置:余额 */ public void setMoney(Float money) { this.money = money; } /** * 获取:余额 */ public Float getMoney() { return money; } }
false
782
9
894
7
964
8
894
7
1,221
10
false
false
false
false
false
true
63401_33
package com.entity.model; import com.entity.OrdersEntity; import com.baomidou.mybatisplus.annotations.TableName; import com.fasterxml.jackson.annotation.JsonFormat; import java.util.Date; import org.springframework.format.annotation.DateTimeFormat; import java.io.Serializable; /** * 订单 * 接收传参的实体类 *(实际开发中配合移动端接口开发手动去掉些没用的字段, 后端一般用entity就够用了) * 取自ModelAndView 的model名称 * @author * @email * @date 2020-11-13 14:48:16 */ public class OrdersModel implements Serializable { private static final long serialVersionUID = 1L; /** * 商品表名 */ private String tablename; /** * 用户id */ private Long userid; /** * 商品id */ private Long goodid; /** * 商品名称 */ private String goodname; /** * 商品图片 */ private String picture; /** * 购买数量 */ private Integer buynumber; /** * 价格/积分 */ private Float price; /** * 折扣价格 */ private Float discountprice; /** * 总价格/总积分 */ private Float total; /** * 折扣总价格 */ private Float discounttotal; /** * 支付类型(1:现金 2:积分) */ private Integer type; /** * 状态 */ private String status; /** * 地址 */ private String address; /** * 设置:商品表名 */ public void setTablename(String tablename) { this.tablename = tablename; } /** * 获取:商品表名 */ public String getTablename() { return tablename; } /** * 设置:用户id */ public void setUserid(Long userid) { this.userid = userid; } /** * 获取:用户id */ public Long getUserid() { return userid; } /** * 设置:商品id */ public void setGoodid(Long goodid) { this.goodid = goodid; } /** * 获取:商品id */ public Long getGoodid() { return goodid; } /** * 设置:商品名称 */ public void setGoodname(String goodname) { this.goodname = goodname; } /** * 获取:商品名称 */ public String getGoodname() { return goodname; } /** * 设置:商品图片 */ public void setPicture(String picture) { this.picture = picture; } /** * 获取:商品图片 */ public String getPicture() { return picture; } /** * 设置:购买数量 */ public void setBuynumber(Integer buynumber) { this.buynumber = buynumber; } /** * 获取:购买数量 */ public Integer getBuynumber() { return buynumber; } /** * 设置:价格/积分 */ public void setPrice(Float price) { this.price = price; } /** * 获取:价格/积分 */ public Float getPrice() { return price; } /** * 设置:折扣价格 */ public void setDiscountprice(Float discountprice) { this.discountprice = discountprice; } /** * 获取:折扣价格 */ public Float getDiscountprice() { return discountprice; } /** * 设置:总价格/总积分 */ public void setTotal(Float total) { this.total = total; } /** * 获取:总价格/总积分 */ public Float getTotal() { return total; } /** * 设置:折扣总价格 */ public void setDiscounttotal(Float discounttotal) { this.discounttotal = discounttotal; } /** * 获取:折扣总价格 */ public Float getDiscounttotal() { return discounttotal; } /** * 设置:支付类型(1:现金 2:积分) */ public void setType(Integer type) { this.type = type; } /** * 获取:支付类型(1:现金 2:积分) */ public Integer getType() { return type; } /** * 设置:状态 */ public void setStatus(String status) { this.status = status; } /** * 获取:状态 */ public String getStatus() { return status; } /** * 设置:地址 */ public void setAddress(String address) { this.address = address; } /** * 获取:地址 */ public String getAddress() { return address; } }
SimpleGraduationProjects/SportsGoodsTradingMallManagementSystem
src/main/java/com/entity/model/OrdersModel.java
1,334
/** * 获取:折扣总价格 */
block_comment
zh-cn
package com.entity.model; import com.entity.OrdersEntity; import com.baomidou.mybatisplus.annotations.TableName; import com.fasterxml.jackson.annotation.JsonFormat; import java.util.Date; import org.springframework.format.annotation.DateTimeFormat; import java.io.Serializable; /** * 订单 * 接收传参的实体类 *(实际开发中配合移动端接口开发手动去掉些没用的字段, 后端一般用entity就够用了) * 取自ModelAndView 的model名称 * @author * @email * @date 2020-11-13 14:48:16 */ public class OrdersModel implements Serializable { private static final long serialVersionUID = 1L; /** * 商品表名 */ private String tablename; /** * 用户id */ private Long userid; /** * 商品id */ private Long goodid; /** * 商品名称 */ private String goodname; /** * 商品图片 */ private String picture; /** * 购买数量 */ private Integer buynumber; /** * 价格/积分 */ private Float price; /** * 折扣价格 */ private Float discountprice; /** * 总价格/总积分 */ private Float total; /** * 折扣总价格 */ private Float discounttotal; /** * 支付类型(1:现金 2:积分) */ private Integer type; /** * 状态 */ private String status; /** * 地址 */ private String address; /** * 设置:商品表名 */ public void setTablename(String tablename) { this.tablename = tablename; } /** * 获取:商品表名 */ public String getTablename() { return tablename; } /** * 设置:用户id */ public void setUserid(Long userid) { this.userid = userid; } /** * 获取:用户id */ public Long getUserid() { return userid; } /** * 设置:商品id */ public void setGoodid(Long goodid) { this.goodid = goodid; } /** * 获取:商品id */ public Long getGoodid() { return goodid; } /** * 设置:商品名称 */ public void setGoodname(String goodname) { this.goodname = goodname; } /** * 获取:商品名称 */ public String getGoodname() { return goodname; } /** * 设置:商品图片 */ public void setPicture(String picture) { this.picture = picture; } /** * 获取:商品图片 */ public String getPicture() { return picture; } /** * 设置:购买数量 */ public void setBuynumber(Integer buynumber) { this.buynumber = buynumber; } /** * 获取:购买数量 */ public Integer getBuynumber() { return buynumber; } /** * 设置:价格/积分 */ public void setPrice(Float price) { this.price = price; } /** * 获取:价格/积分 */ public Float getPrice() { return price; } /** * 设置:折扣价格 */ public void setDiscountprice(Float discountprice) { this.discountprice = discountprice; } /** * 获取:折扣价格 */ public Float getDiscountprice() { return discountprice; } /** * 设置:总价格/总积分 */ public void setTotal(Float total) { this.total = total; } /** * 获取:总价格/总积分 */ public Float getTotal() { return total; } /** * 设置:折扣总价格 */ public void setDiscounttotal(Float discounttotal) { this.discounttotal = discounttotal; } /** * 获取: <SUF>*/ public Float getDiscounttotal() { return discounttotal; } /** * 设置:支付类型(1:现金 2:积分) */ public void setType(Integer type) { this.type = type; } /** * 获取:支付类型(1:现金 2:积分) */ public Integer getType() { return type; } /** * 设置:状态 */ public void setStatus(String status) { this.status = status; } /** * 获取:状态 */ public String getStatus() { return status; } /** * 设置:地址 */ public void setAddress(String address) { this.address = address; } /** * 获取:地址 */ public String getAddress() { return address; } }
false
1,136
11
1,334
13
1,489
12
1,334
13
1,893
24
false
false
false
false
false
true