blob_id
stringlengths
40
40
__id__
int64
225
39,780B
directory_id
stringlengths
40
40
path
stringlengths
6
313
content_id
stringlengths
40
40
detected_licenses
sequence
license_type
stringclasses
2 values
repo_name
stringlengths
6
132
repo_url
stringlengths
25
151
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringlengths
4
70
visit_date
timestamp[ns]
revision_date
timestamp[ns]
committer_date
timestamp[ns]
github_id
int64
7.28k
689M
star_events_count
int64
0
131k
fork_events_count
int64
0
48k
gha_license_id
stringclasses
23 values
gha_fork
bool
2 classes
gha_event_created_at
timestamp[ns]
gha_created_at
timestamp[ns]
gha_updated_at
timestamp[ns]
gha_pushed_at
timestamp[ns]
gha_size
int64
0
40.4M
gha_stargazers_count
int32
0
112k
gha_forks_count
int32
0
39.4k
gha_open_issues_count
int32
0
11k
gha_language
stringlengths
1
21
gha_archived
bool
2 classes
gha_disabled
bool
1 class
content
stringlengths
7
4.37M
src_encoding
stringlengths
3
16
language
stringclasses
1 value
length_bytes
int64
7
4.37M
extension
stringclasses
24 values
filename
stringlengths
4
174
language_id
stringclasses
1 value
entities
list
contaminating_dataset
stringclasses
0 values
malware_signatures
sequence
redacted_content
stringlengths
7
4.37M
redacted_length_bytes
int64
7
4.37M
alphanum_fraction
float32
0.25
0.94
alpha_fraction
float32
0.25
0.94
num_lines
int32
1
84k
avg_line_length
float32
0.76
99.9
std_line_length
float32
0
220
max_line_length
int32
5
998
is_vendor
bool
2 classes
is_generated
bool
1 class
max_hex_length
int32
0
319
hex_fraction
float32
0
0.38
max_unicode_length
int32
0
408
unicode_fraction
float32
0
0.36
max_base64_length
int32
0
506
base64_fraction
float32
0
0.5
avg_csv_sep_count
float32
0
4
is_autogen_header
bool
1 class
is_empty_html
bool
1 class
shard
stringclasses
16 values
8f07bdf7a8cf0de4aeed7985a2383606caafdac4
18,476,949,366,990
5f77936a3c7ba14b77a8e6e49ab72fe0ed6c7b8d
/src/main/java/br/com/logicaProgramacao_EP3/Client.java
49e181021ba5f3378490a338d6d3ac92a80c3567
[]
no_license
LeonardoAndriotti/Algorithms-Of-Programming-Logic
https://github.com/LeonardoAndriotti/Algorithms-Of-Programming-Logic
4d2fc2f85dfaa2d01a91053171fe6388f4e82a3b
fcdcc88e8ed8093b81c65bfb7bc803f3031edf1c
refs/heads/master
2017-04-22T14:18:00.556000
2016-04-27T16:36:06
2016-04-27T16:36:06
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package br.com.logicaProgramacao_EP3; /**EP_03 * * Você foi contratado por um grande banco e recebeu a tarefa de construir um sistema de autenticação de clientes. O sistema possui uma classe mãe chamada cliente, duas classes filhas uma chamada cliente comum e a outra cliente especial. Todos os métodos das classes filhas lançam exceções do tipo “IllegalArgumentException”, mas nenhum fornece tratamento. Cada classe filha possui apenas um método chamado “cadastro”. A classe mãe possui dois métodos teste1 e teste2 que disparam as exceções dos respectivos métodos de cada classe filha ao passar uma string “falha” como parâmetros de teste dos métodos. Implemente um código Java que viabilize o teste das exceções como descrito acima. * * @author BmLeonardo * @author Andriotti * */ /** * Classe Cliente, tem como objetivo,fazer a comunicação entre os metódos teste um e teste dois. * os testes tem como principal função, tratar as exeções lançadas pelos metodos cadastro quando tem uma exceção na escrita do nome * do cliente. * * */ public class Client { public void testOne() { try { ClientCommon CC = new ClientCommon(); CC.register(); } catch (IllegalArgumentException a) { System.err.println("Erro de Argumento, em Cliente Comum"); } } public void testTwo() { try { ClientSpecial CS = new ClientSpecial(); CS.register(); } catch (IllegalArgumentException e) { System.err.println("Erro de Argumento, em Cliente Especial"); } } public static void main(String[] args) { new Client().testOne(); new Client().testTwo(); } } class ClientCommon extends Client { public void register() throws IllegalArgumentException { String parameter = "89Leonardo"; if (!parameter.matches("[A-Z][a-z]*")) { throw new IllegalArgumentException(); } } } class ClientSpecial extends Client { public void register() throws IllegalArgumentException { String parameter = "nardo64"; if (!parameter.matches("[A-Za-z]*")) { throw new IllegalArgumentException(); } } }
WINDOWS-1252
Java
2,073
java
Client.java
Java
[ { "context": " das exceções como descrito acima.\n\n * \n * @author BmLeonardo\n * @author Andriotti\n *\n */\n/**\n * Classe Cliente", "end": 764, "score": 0.9253832697868347, "start": 754, "tag": "NAME", "value": "BmLeonardo" }, { "context": "crito acima.\n\n * \n * @author BmLeonardo\n * @author Andriotti\n *\n */\n/**\n * Classe Cliente, tem como objetivo,f", "end": 785, "score": 0.9997223019599915, "start": 776, "tag": "NAME", "value": "Andriotti" } ]
null
[]
package br.com.logicaProgramacao_EP3; /**EP_03 * * Você foi contratado por um grande banco e recebeu a tarefa de construir um sistema de autenticação de clientes. O sistema possui uma classe mãe chamada cliente, duas classes filhas uma chamada cliente comum e a outra cliente especial. Todos os métodos das classes filhas lançam exceções do tipo “IllegalArgumentException”, mas nenhum fornece tratamento. Cada classe filha possui apenas um método chamado “cadastro”. A classe mãe possui dois métodos teste1 e teste2 que disparam as exceções dos respectivos métodos de cada classe filha ao passar uma string “falha” como parâmetros de teste dos métodos. Implemente um código Java que viabilize o teste das exceções como descrito acima. * * @author BmLeonardo * @author Andriotti * */ /** * Classe Cliente, tem como objetivo,fazer a comunicação entre os metódos teste um e teste dois. * os testes tem como principal função, tratar as exeções lançadas pelos metodos cadastro quando tem uma exceção na escrita do nome * do cliente. * * */ public class Client { public void testOne() { try { ClientCommon CC = new ClientCommon(); CC.register(); } catch (IllegalArgumentException a) { System.err.println("Erro de Argumento, em Cliente Comum"); } } public void testTwo() { try { ClientSpecial CS = new ClientSpecial(); CS.register(); } catch (IllegalArgumentException e) { System.err.println("Erro de Argumento, em Cliente Especial"); } } public static void main(String[] args) { new Client().testOne(); new Client().testTwo(); } } class ClientCommon extends Client { public void register() throws IllegalArgumentException { String parameter = "89Leonardo"; if (!parameter.matches("[A-Z][a-z]*")) { throw new IllegalArgumentException(); } } } class ClientSpecial extends Client { public void register() throws IllegalArgumentException { String parameter = "nardo64"; if (!parameter.matches("[A-Za-z]*")) { throw new IllegalArgumentException(); } } }
2,073
0.731299
0.72687
71
27.633802
33.254562
132
false
false
0
0
0
0
0
0
1.15493
false
false
4
284498d831db462b142a4ea4a4628444d2914247
30,279,519,494,246
519f287a82eeaac5e259f688ecf626b1951cf5e6
/src/java/com/acunu/castle/CounterSetRequest.java
cf922b49d67e0c0a55aa6470bcf4598a959bedad
[ "MIT" ]
permissive
samoverton/java-castle
https://github.com/samoverton/java-castle
f948563ced7ad9dd25b01ea06195c8ecfc5149d4
1807c712ec5daad6004c6eb5a8ee446510765596
refs/heads/master
2020-12-11T05:55:57.373000
2012-03-15T16:44:10
2012-03-15T16:44:10
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.acunu.castle; import java.nio.ByteBuffer; public class CounterSetRequest extends Request { protected final Key key; protected final int collection; protected final ByteBuffer keyBuffer; protected final ByteBuffer valueBuffer; protected CounterSetRequest(final Key key, final int collection, final ByteBuffer keyBuffer, final ByteBuffer valueBuffer) { this.key = key; this.collection = collection; this.keyBuffer = keyBuffer; this.valueBuffer = valueBuffer; } static private native void copy_to(long buffer, int index, int collectionId, ByteBuffer keyBuffer, int keyOffset, int keyLength, ByteBuffer valueBuffer, int valueOffset, int valueLength); @Override protected void copy_to(long buffer, int index) throws CastleException { int keyLength = key.copyToBuffer(keyBuffer); copy_to(buffer, index, collection, keyBuffer, keyBuffer.position(), keyLength, valueBuffer, valueBuffer.position(), valueBuffer.remaining()); } }
UTF-8
Java
968
java
CounterSetRequest.java
Java
[]
null
[]
package com.acunu.castle; import java.nio.ByteBuffer; public class CounterSetRequest extends Request { protected final Key key; protected final int collection; protected final ByteBuffer keyBuffer; protected final ByteBuffer valueBuffer; protected CounterSetRequest(final Key key, final int collection, final ByteBuffer keyBuffer, final ByteBuffer valueBuffer) { this.key = key; this.collection = collection; this.keyBuffer = keyBuffer; this.valueBuffer = valueBuffer; } static private native void copy_to(long buffer, int index, int collectionId, ByteBuffer keyBuffer, int keyOffset, int keyLength, ByteBuffer valueBuffer, int valueOffset, int valueLength); @Override protected void copy_to(long buffer, int index) throws CastleException { int keyLength = key.copyToBuffer(keyBuffer); copy_to(buffer, index, collection, keyBuffer, keyBuffer.position(), keyLength, valueBuffer, valueBuffer.position(), valueBuffer.remaining()); } }
968
0.780992
0.780992
30
31.266666
35.392967
123
false
false
0
0
0
0
0
0
2.133333
false
false
4
31a27176784b9f81765b1cf644864b8cec5f3603
11,811,160,107,663
172d29a9522491aa1a6e60077e2f6afadc9de131
/source/dev/new_branch/risk-service/src/test/java/com/rkylin/risk/service/biz/impl/StudentScoreBizImpl.java
8234260386b8b2e3aaea448e4b7dcc6c61da7f86
[]
no_license
moutainhigh/kylin-risk
https://github.com/moutainhigh/kylin-risk
dadc9ab9a1e8910240d51d53694777cc9c43bda1
57079f408f1687ec3ac7aa4eab8f306ddc223d79
refs/heads/master
2020-09-21T10:23:00.318000
2017-10-25T06:01:50
2017-10-25T06:01:50
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.rkylin.risk.service.biz.impl; import com.rkylin.risk.kie.spring.factorybeans.KieContainerSession; import com.rkylin.risk.core.dto.LogicRuleBean; import com.rkylin.risk.core.dto.ResultBean; import javax.annotation.Resource; import org.kie.api.runtime.KieContainer; import org.kie.api.runtime.KieSession; import org.kie.api.runtime.rule.FactHandle; import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; /** * Created by lina on 2016-8-3. */ public class StudentScoreBizImpl implements ApplicationContextAware { private ApplicationContext applicationContext; @Resource KieContainerSession kieContainerSession; public ResultBean calStudentScoreRule(LogicRuleBean logic) { ResultBean score = new ResultBean(); KieContainer kieContainer = kieContainerSession.getBean("com.risk.rule.develop.P000008:P00000514"); KieSession kieSession = kieContainer.newKieSession("P00000514"); FactHandle logicHandle = kieSession.insert(logic); FactHandle scoreHandle = kieSession.insert(score); kieSession.fireAllRules(); kieSession.delete(logicHandle); kieSession.delete(scoreHandle); kieSession.destroy(); return score; } @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.applicationContext = applicationContext; } }
UTF-8
Java
1,461
java
StudentScoreBizImpl.java
Java
[ { "context": "ontext.ApplicationContextAware;\n\n/**\n * Created by lina on 2016-8-3.\n */\n\npublic class StudentScoreBizImp", "end": 547, "score": 0.9251189827919006, "start": 543, "tag": "USERNAME", "value": "lina" } ]
null
[]
package com.rkylin.risk.service.biz.impl; import com.rkylin.risk.kie.spring.factorybeans.KieContainerSession; import com.rkylin.risk.core.dto.LogicRuleBean; import com.rkylin.risk.core.dto.ResultBean; import javax.annotation.Resource; import org.kie.api.runtime.KieContainer; import org.kie.api.runtime.KieSession; import org.kie.api.runtime.rule.FactHandle; import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; /** * Created by lina on 2016-8-3. */ public class StudentScoreBizImpl implements ApplicationContextAware { private ApplicationContext applicationContext; @Resource KieContainerSession kieContainerSession; public ResultBean calStudentScoreRule(LogicRuleBean logic) { ResultBean score = new ResultBean(); KieContainer kieContainer = kieContainerSession.getBean("com.risk.rule.develop.P000008:P00000514"); KieSession kieSession = kieContainer.newKieSession("P00000514"); FactHandle logicHandle = kieSession.insert(logic); FactHandle scoreHandle = kieSession.insert(score); kieSession.fireAllRules(); kieSession.delete(logicHandle); kieSession.delete(scoreHandle); kieSession.destroy(); return score; } @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.applicationContext = applicationContext; } }
1,461
0.793977
0.774812
43
32.976746
24.432621
84
false
false
0
0
0
0
0
0
0.55814
false
false
4
6cbf92b587cca5ddf998447e8ca9d74476ac5337
11,811,160,108,722
8756b50b15dc62307a0218b0306328522cd213a4
/src/gameoflifeattempt1/GameOfLifeAttempt1.java
9cd2f7b916ca948f2866976684dabf6296c7f6d6
[]
no_license
Peachball/Game-of-Life
https://github.com/Peachball/Game-of-Life
65a82aa9ba0ea8263a13f3b4c74a899523750438
9231296ab32a1a843078405eb2b797141e38295f
refs/heads/master
2020-04-07T03:08:24.762000
2014-10-29T20:39:18
2014-10-29T20:39:18
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package gameoflifeattempt1; /** * * @author s-xuch */ public class GameOfLifeAttempt1 { /** * @param args the command line arguments */ public static void main(String[] args) { System.out.println("Input the dimensions plox"); int dimensions = StdIn.readInt(); Rules rules = new Rules(dimensions, dimensions); rules.intializeFrame(); while (true) { rules.create(); rules.draw(); rules.mouseListener(); if (rules.keyListener() == 'p') { StdIn.readString(); } } // TODO code application logic here } }
UTF-8
Java
877
java
GameOfLifeAttempt1.java
Java
[ { "context": "package gameoflifeattempt1;\r\n\r\n/**\r\n *\r\n * @author s-xuch\r\n */\r\npublic class GameOfLifeAttempt1 {\r\n\r\n /*", "end": 247, "score": 0.9991081953048706, "start": 241, "tag": "USERNAME", "value": "s-xuch" } ]
null
[]
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package gameoflifeattempt1; /** * * @author s-xuch */ public class GameOfLifeAttempt1 { /** * @param args the command line arguments */ public static void main(String[] args) { System.out.println("Input the dimensions plox"); int dimensions = StdIn.readInt(); Rules rules = new Rules(dimensions, dimensions); rules.intializeFrame(); while (true) { rules.create(); rules.draw(); rules.mouseListener(); if (rules.keyListener() == 'p') { StdIn.readString(); } } // TODO code application logic here } }
877
0.562144
0.559863
33
24.575758
21.007978
79
false
false
0
0
0
0
0
0
0.393939
false
false
4
a3c599bc0aa9d420eed99e7681e323d43dbe8121
24,326,694,830,142
a64cd2524c2c3e0e7f7dac16d65d05131587628b
/techinterview_backend/src/main/java/com/halcyonmobile/rest/QuestionCardService.java
3581f35222504e7f9f148dc2624e4958b2faea2c
[]
no_license
zoltanaty/Common-Project-ubbse2016
https://github.com/zoltanaty/Common-Project-ubbse2016
3522c147cc39b1afd905cb47ca00405e0f3ea70c
6144ea968c12f016bc159902172750acaa5bc1cf
refs/heads/master
2021-06-16T05:00:31.067000
2017-05-22T06:41:15
2017-05-22T06:41:15
72,003,959
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.halcyonmobile.rest; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Random; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import com.halcyonmobile.model.Answer; import com.halcyonmobile.model.Position; import com.halcyonmobile.model.Question; import com.halcyonmobile.model.QuestionType; import com.halcyonmobile.model.dto.QuestionCardDTO; @Path("/questioncard") public class QuestionCardService { @GET @Path("/{id_position}") @Produces(MediaType.APPLICATION_XML) public List<QuestionCardDTO> findByPosition(@PathParam("id_position") Integer idPosition) { QuestionService questionService = new QuestionService(); AnswerService answerService = new AnswerService(); QuestionTypeService questionTypeService = new QuestionTypeService(); List<QuestionCardDTO> questioncardDTOList = new ArrayList<>(); List<Question> questionList = questionService.findByPosition(idPosition); long seed = System.nanoTime(); Collections.shuffle(questionList, new Random(seed)); PositionService positionService = new PositionService(); Position position = positionService.findById(idPosition); int imax = position.getnrQue(); if(questionList.size()<imax){ imax = questionList.size(); } for(int i = 0; i< imax;i++){ Question question = questionList.get(i); List<Answer> answers = answerService.findByQuestion(question.getId()); QuestionType questionType = questionTypeService.findById(question.getId_questiontype()); QuestionCardDTO questionCardDTO = new QuestionCardDTO(question, answers, questionType); questioncardDTOList.add(questionCardDTO); } return questioncardDTOList; } }
UTF-8
Java
1,901
java
QuestionCardService.java
Java
[]
null
[]
package com.halcyonmobile.rest; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Random; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import com.halcyonmobile.model.Answer; import com.halcyonmobile.model.Position; import com.halcyonmobile.model.Question; import com.halcyonmobile.model.QuestionType; import com.halcyonmobile.model.dto.QuestionCardDTO; @Path("/questioncard") public class QuestionCardService { @GET @Path("/{id_position}") @Produces(MediaType.APPLICATION_XML) public List<QuestionCardDTO> findByPosition(@PathParam("id_position") Integer idPosition) { QuestionService questionService = new QuestionService(); AnswerService answerService = new AnswerService(); QuestionTypeService questionTypeService = new QuestionTypeService(); List<QuestionCardDTO> questioncardDTOList = new ArrayList<>(); List<Question> questionList = questionService.findByPosition(idPosition); long seed = System.nanoTime(); Collections.shuffle(questionList, new Random(seed)); PositionService positionService = new PositionService(); Position position = positionService.findById(idPosition); int imax = position.getnrQue(); if(questionList.size()<imax){ imax = questionList.size(); } for(int i = 0; i< imax;i++){ Question question = questionList.get(i); List<Answer> answers = answerService.findByQuestion(question.getId()); QuestionType questionType = questionTypeService.findById(question.getId_questiontype()); QuestionCardDTO questionCardDTO = new QuestionCardDTO(question, answers, questionType); questioncardDTOList.add(questionCardDTO); } return questioncardDTOList; } }
1,901
0.729616
0.72909
56
31.946428
25.852203
94
false
false
0
0
0
0
0
0
1.696429
false
false
4
22a716391012b1004d68f80f09682448cd547516
7,902,739,833,926
f9deb0ebd64c1c9f7424303e7175ee63cc06c7ad
/Android/app/src/main/java/com/digiapp/jilmusic/beans/SelectionItems.java
b626ec09d75ce0fbe7d30340d116d751c422bb30
[]
no_license
riyanhax/web-bemusic
https://github.com/riyanhax/web-bemusic
e6d1ed4706350400d62c608342bac77f1e47a83a
9a7f760a91d0283a7db7d71c99919f980a65a9b0
refs/heads/master
2021-02-26T02:56:19.976000
2020-01-17T12:31:17
2020-01-17T12:31:17
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.digiapp.jilmusic.beans; import android.arch.persistence.room.ColumnInfo; import android.arch.persistence.room.Entity; import android.arch.persistence.room.PrimaryKey; import android.support.annotation.NonNull; @Entity(tableName = "selections_items") public class SelectionItems { @PrimaryKey @NonNull @ColumnInfo(name = "id") public long id; @ColumnInfo(name = "selectionlist_id") public String selection_id; @ColumnInfo(name = "order") public int order; @ColumnInfo(name = "track_id") public int track_id; public SelectionItems(int track_id){ id = System.currentTimeMillis(); order = 0; this.track_id = track_id; } }
UTF-8
Java
708
java
SelectionItems.java
Java
[]
null
[]
package com.digiapp.jilmusic.beans; import android.arch.persistence.room.ColumnInfo; import android.arch.persistence.room.Entity; import android.arch.persistence.room.PrimaryKey; import android.support.annotation.NonNull; @Entity(tableName = "selections_items") public class SelectionItems { @PrimaryKey @NonNull @ColumnInfo(name = "id") public long id; @ColumnInfo(name = "selectionlist_id") public String selection_id; @ColumnInfo(name = "order") public int order; @ColumnInfo(name = "track_id") public int track_id; public SelectionItems(int track_id){ id = System.currentTimeMillis(); order = 0; this.track_id = track_id; } }
708
0.69209
0.690678
29
23.413794
16.618471
48
false
false
0
0
0
0
0
0
0.413793
false
false
4
1807b6b68b0c6899f6edb4010695b3fd74a8fec4
7,902,739,833,739
ff68a18cff6d3a89e3b9446a714d5a2016024bea
/src/main/java/com/sl/ylyy/manager/entity/RoleInfo.java
c12d81789a1587c9d194dd169402151d71304ee3
[]
no_license
1335443221/idrip_ylyyapp
https://github.com/1335443221/idrip_ylyyapp
68a87682aa3921aedf67bb925f9bfbd030d72413
5e5390821a71aa348001782410cd053b4370711e
refs/heads/master
2023-03-30T15:44:46.422000
2021-04-02T02:10:23
2021-04-02T02:10:23
353,875,379
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.sl.ylyy.manager.entity; import java.io.Serializable; import java.util.List; public class RoleInfo implements Serializable{ private static final long serialVersionUID = 4702946019240523593L; private int id; //id private String name; //角色名称 private String remark; //备注 private String center_role_id; //备注 private String aids; //对应权限id字符串 private List<Auth> authList; //id对应的权限 public String getCenter_role_id() { return center_role_id; } public void setCenter_role_id(String center_role_id) { this.center_role_id = center_role_id; } public List<Auth> getAuthList() { return authList; } public void setAuthList(List<Auth> authList) { this.authList = authList; } public String getAids() { return aids; } public void setAids(String aids) { this.aids = aids; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getRemark() { return remark; } public void setRemark(String remark) { this.remark = remark; } }
UTF-8
Java
1,164
java
RoleInfo.java
Java
[]
null
[]
package com.sl.ylyy.manager.entity; import java.io.Serializable; import java.util.List; public class RoleInfo implements Serializable{ private static final long serialVersionUID = 4702946019240523593L; private int id; //id private String name; //角色名称 private String remark; //备注 private String center_role_id; //备注 private String aids; //对应权限id字符串 private List<Auth> authList; //id对应的权限 public String getCenter_role_id() { return center_role_id; } public void setCenter_role_id(String center_role_id) { this.center_role_id = center_role_id; } public List<Auth> getAuthList() { return authList; } public void setAuthList(List<Auth> authList) { this.authList = authList; } public String getAids() { return aids; } public void setAids(String aids) { this.aids = aids; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getRemark() { return remark; } public void setRemark(String remark) { this.remark = remark; } }
1,164
0.700178
0.683274
59
18.050848
16.749828
67
false
false
0
0
0
0
0
0
1.355932
false
false
4
7af5810b0bfacc6ec7d43c8c9aae3ff0398dae4e
10,642,928,994,324
bdc95d198838f3c6946315731fa11b367c21b73f
/app/src/main/java/com/casino/uri/androidpokedex/provider/favorite/FavoriteContentValues.java
944b4de912d949d9f0a1dd657ead555d5e66bc7a
[]
no_license
48089748z/ANDROIDPokedex
https://github.com/48089748z/ANDROIDPokedex
7442102ad3854760a9da222370baeb5373279827
a26598438f05018902e97f2c457c814745d2cf94
refs/heads/master
2021-01-21T21:47:44.354000
2015-12-22T13:14:10
2015-12-22T13:14:10
48,035,779
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.casino.uri.androidpokedex.provider.favorite; import android.content.Context; import android.content.ContentResolver; import android.net.Uri; import android.support.annotation.Nullable; import com.casino.uri.androidpokedex.provider.base.AbstractContentValues; /** * Content values wrapper for the {@code favorite} table. */ public class FavoriteContentValues extends AbstractContentValues { @Override public Uri uri() { return FavoriteColumns.CONTENT_URI; } /** * Update row(s) using the values stored by this object and the given selection. * * @param contentResolver The content resolver to use. * @param where The selection to use (can be {@code null}). */ public int update(ContentResolver contentResolver, @Nullable FavoriteSelection where) { return contentResolver.update(uri(), values(), where == null ? null : where.sel(), where == null ? null : where.args()); } /** * Update row(s) using the values stored by this object and the given selection. * * @param contentResolver The content resolver to use. * @param where The selection to use (can be {@code null}). */ public int update(Context context, @Nullable FavoriteSelection where) { return context.getContentResolver().update(uri(), values(), where == null ? null : where.sel(), where == null ? null : where.args()); } public FavoriteContentValues putPkdxId(@Nullable String value) { mContentValues.put(FavoriteColumns.PKDX_ID, value); return this; } public FavoriteContentValues putPkdxIdNull() { mContentValues.putNull(FavoriteColumns.PKDX_ID); return this; } public FavoriteContentValues putName(@Nullable String value) { mContentValues.put(FavoriteColumns.NAME, value); return this; } public FavoriteContentValues putNameNull() { mContentValues.putNull(FavoriteColumns.NAME); return this; } public FavoriteContentValues putSpatk(@Nullable String value) { mContentValues.put(FavoriteColumns.SPATK, value); return this; } public FavoriteContentValues putSpatkNull() { mContentValues.putNull(FavoriteColumns.SPATK); return this; } public FavoriteContentValues putSpdef(@Nullable String value) { mContentValues.put(FavoriteColumns.SPDEF, value); return this; } public FavoriteContentValues putSpdefNull() { mContentValues.putNull(FavoriteColumns.SPDEF); return this; } public FavoriteContentValues putWeight(@Nullable String value) { mContentValues.put(FavoriteColumns.WEIGHT, value); return this; } public FavoriteContentValues putWeightNull() { mContentValues.putNull(FavoriteColumns.WEIGHT); return this; } public FavoriteContentValues putHp(@Nullable String value) { mContentValues.put(FavoriteColumns.HP, value); return this; } public FavoriteContentValues putHpNull() { mContentValues.putNull(FavoriteColumns.HP); return this; } public FavoriteContentValues putCreated(@Nullable String value) { mContentValues.put(FavoriteColumns.CREATED, value); return this; } public FavoriteContentValues putCreatedNull() { mContentValues.putNull(FavoriteColumns.CREATED); return this; } public FavoriteContentValues putModified(@Nullable String value) { mContentValues.put(FavoriteColumns.MODIFIED, value); return this; } public FavoriteContentValues putModifiedNull() { mContentValues.putNull(FavoriteColumns.MODIFIED); return this; } public FavoriteContentValues putTypes(@Nullable String value) { mContentValues.put(FavoriteColumns.TYPES, value); return this; } public FavoriteContentValues putTypesNull() { mContentValues.putNull(FavoriteColumns.TYPES); return this; } public FavoriteContentValues putImage(@Nullable String value) { mContentValues.put(FavoriteColumns.IMAGE, value); return this; } public FavoriteContentValues putImageNull() { mContentValues.putNull(FavoriteColumns.IMAGE); return this; } }
UTF-8
Java
4,295
java
FavoriteContentValues.java
Java
[]
null
[]
package com.casino.uri.androidpokedex.provider.favorite; import android.content.Context; import android.content.ContentResolver; import android.net.Uri; import android.support.annotation.Nullable; import com.casino.uri.androidpokedex.provider.base.AbstractContentValues; /** * Content values wrapper for the {@code favorite} table. */ public class FavoriteContentValues extends AbstractContentValues { @Override public Uri uri() { return FavoriteColumns.CONTENT_URI; } /** * Update row(s) using the values stored by this object and the given selection. * * @param contentResolver The content resolver to use. * @param where The selection to use (can be {@code null}). */ public int update(ContentResolver contentResolver, @Nullable FavoriteSelection where) { return contentResolver.update(uri(), values(), where == null ? null : where.sel(), where == null ? null : where.args()); } /** * Update row(s) using the values stored by this object and the given selection. * * @param contentResolver The content resolver to use. * @param where The selection to use (can be {@code null}). */ public int update(Context context, @Nullable FavoriteSelection where) { return context.getContentResolver().update(uri(), values(), where == null ? null : where.sel(), where == null ? null : where.args()); } public FavoriteContentValues putPkdxId(@Nullable String value) { mContentValues.put(FavoriteColumns.PKDX_ID, value); return this; } public FavoriteContentValues putPkdxIdNull() { mContentValues.putNull(FavoriteColumns.PKDX_ID); return this; } public FavoriteContentValues putName(@Nullable String value) { mContentValues.put(FavoriteColumns.NAME, value); return this; } public FavoriteContentValues putNameNull() { mContentValues.putNull(FavoriteColumns.NAME); return this; } public FavoriteContentValues putSpatk(@Nullable String value) { mContentValues.put(FavoriteColumns.SPATK, value); return this; } public FavoriteContentValues putSpatkNull() { mContentValues.putNull(FavoriteColumns.SPATK); return this; } public FavoriteContentValues putSpdef(@Nullable String value) { mContentValues.put(FavoriteColumns.SPDEF, value); return this; } public FavoriteContentValues putSpdefNull() { mContentValues.putNull(FavoriteColumns.SPDEF); return this; } public FavoriteContentValues putWeight(@Nullable String value) { mContentValues.put(FavoriteColumns.WEIGHT, value); return this; } public FavoriteContentValues putWeightNull() { mContentValues.putNull(FavoriteColumns.WEIGHT); return this; } public FavoriteContentValues putHp(@Nullable String value) { mContentValues.put(FavoriteColumns.HP, value); return this; } public FavoriteContentValues putHpNull() { mContentValues.putNull(FavoriteColumns.HP); return this; } public FavoriteContentValues putCreated(@Nullable String value) { mContentValues.put(FavoriteColumns.CREATED, value); return this; } public FavoriteContentValues putCreatedNull() { mContentValues.putNull(FavoriteColumns.CREATED); return this; } public FavoriteContentValues putModified(@Nullable String value) { mContentValues.put(FavoriteColumns.MODIFIED, value); return this; } public FavoriteContentValues putModifiedNull() { mContentValues.putNull(FavoriteColumns.MODIFIED); return this; } public FavoriteContentValues putTypes(@Nullable String value) { mContentValues.put(FavoriteColumns.TYPES, value); return this; } public FavoriteContentValues putTypesNull() { mContentValues.putNull(FavoriteColumns.TYPES); return this; } public FavoriteContentValues putImage(@Nullable String value) { mContentValues.put(FavoriteColumns.IMAGE, value); return this; } public FavoriteContentValues putImageNull() { mContentValues.putNull(FavoriteColumns.IMAGE); return this; } }
4,295
0.687078
0.687078
138
30.123188
29.273932
141
false
false
0
0
0
0
0
0
0.485507
false
false
4
139201509fb83361e1cbb0812b1f50f94141f759
28,140,625,755,136
f6b007b2f7c05bfd7c73ff04ac4b37eab78d2f0e
/goshop-manager/goshop-manager-mapper/src/main/java/com/lcc/goshop/manager/mapper/FindPasswordMapper.java
ca149796d866bd139323b69f61159bad6734b4df
[]
no_license
liangchengcheng/goshop-master
https://github.com/liangchengcheng/goshop-master
64ecc676f6af8ca0602f42997cb269a87348471a
9df3477f198a9575b75d5119a2a33b828c3a0501
refs/heads/master
2021-01-22T03:05:57.482000
2017-02-18T09:45:08
2017-02-18T09:45:08
81,098,199
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.lcc.goshop.manager.mapper; import com.lcc.goshop.manager.pojo.FindPassword; /** * Created by lcc on 2017/2/11. */ public interface FindPasswordMapper { int insert(FindPassword record); int insertSelective(FindPassword record); /** * 删除过期 */ void deleteInvalid(); /** * 通过编码查找用户名 */ String findByKey(String key); /** * 删除此链接 */ int delete(String key); }
UTF-8
Java
471
java
FindPasswordMapper.java
Java
[ { "context": "shop.manager.pojo.FindPassword;\n\n/**\n * Created by lcc on 2017/2/11.\n */\npublic interface FindPasswordMa", "end": 111, "score": 0.9996150135993958, "start": 108, "tag": "USERNAME", "value": "lcc" } ]
null
[]
package com.lcc.goshop.manager.mapper; import com.lcc.goshop.manager.pojo.FindPassword; /** * Created by lcc on 2017/2/11. */ public interface FindPasswordMapper { int insert(FindPassword record); int insertSelective(FindPassword record); /** * 删除过期 */ void deleteInvalid(); /** * 通过编码查找用户名 */ String findByKey(String key); /** * 删除此链接 */ int delete(String key); }
471
0.613793
0.597701
27
15.111111
15.528548
48
false
false
0
0
0
0
0
0
0.259259
false
false
4
06b9e87f7d305b95f4aa733b80173fd751e3a863
6,244,882,481,004
7e4befec4caccaf0a3bc17ea6916e63b8fc022b3
/src/main/java/pl/coderslab/web/RegistrationServlet.java
4208bff7ef8d1b2a5b7b9907f4e60daa31b3d9b3
[]
no_license
arekbednarz1/CodersLab-scrumlab
https://github.com/arekbednarz1/CodersLab-scrumlab
095c3c12b2dc23858699c59640ee415dc77f42b5
6047f32c287c2dc187cc07f30f4a77a16ac22dea
refs/heads/master
2023-01-23T22:44:55.337000
2020-10-03T16:24:11
2020-10-03T16:24:11
315,304,690
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package pl.coderslab.web; import pl.coderslab.dao.AdminsDao; import pl.coderslab.model.Admins; 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.IOException; import java.io.Writer; import java.util.Arrays; @WebServlet(name = "RegistrationServlet",urlPatterns = {"/register"}) public class RegistrationServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String name = request.getParameter("name"); String surname = request.getParameter("surname"); String email = request.getParameter("email"); String[] passwords = request.getParameterValues("password"); Boolean isNull = name != null && surname != null && email != null && passwords != null; Boolean isZero = name.length() != 0 && surname.length() != 0 && email.length() != 0 && passwords.length != 0; Boolean samePass = passwords[0].equals(passwords[1]); AdminsDao adminsDao = new AdminsDao(); Admins admins = adminsDao.readAdminEmail(email); Boolean newEmail = (admins.getEmail() == null); if (isNull && isZero && samePass && newEmail) { admins.setFirstName(name); admins.setLastName(surname); admins.setEmail(email); admins.setPassword(passwords[0]); adminsDao.createAdmin(admins); response.sendRedirect("/login"); } else { if (!samePass) { String wrw = "Hasła nie są takie same"; request.setAttribute("wrong", wrw); } if (!isZero || !isNull) { String wr = "Uzupełnij wszystkie pola"; request.setAttribute("all", wr); } if(!newEmail) { request.setAttribute("userExists", "Taki użytkownik już istnieje"); } getServletContext().getRequestDispatcher("/WEB-INF/register.jsp").forward(request, response); } } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { getServletContext().getRequestDispatcher("/WEB-INF/register.jsp").forward(request,response); } }
UTF-8
Java
2,425
java
RegistrationServlet.java
Java
[]
null
[]
package pl.coderslab.web; import pl.coderslab.dao.AdminsDao; import pl.coderslab.model.Admins; 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.IOException; import java.io.Writer; import java.util.Arrays; @WebServlet(name = "RegistrationServlet",urlPatterns = {"/register"}) public class RegistrationServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String name = request.getParameter("name"); String surname = request.getParameter("surname"); String email = request.getParameter("email"); String[] passwords = request.getParameterValues("password"); Boolean isNull = name != null && surname != null && email != null && passwords != null; Boolean isZero = name.length() != 0 && surname.length() != 0 && email.length() != 0 && passwords.length != 0; Boolean samePass = passwords[0].equals(passwords[1]); AdminsDao adminsDao = new AdminsDao(); Admins admins = adminsDao.readAdminEmail(email); Boolean newEmail = (admins.getEmail() == null); if (isNull && isZero && samePass && newEmail) { admins.setFirstName(name); admins.setLastName(surname); admins.setEmail(email); admins.setPassword(passwords[0]); adminsDao.createAdmin(admins); response.sendRedirect("/login"); } else { if (!samePass) { String wrw = "Hasła nie są takie same"; request.setAttribute("wrong", wrw); } if (!isZero || !isNull) { String wr = "Uzupełnij wszystkie pola"; request.setAttribute("all", wr); } if(!newEmail) { request.setAttribute("userExists", "Taki użytkownik już istnieje"); } getServletContext().getRequestDispatcher("/WEB-INF/register.jsp").forward(request, response); } } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { getServletContext().getRequestDispatcher("/WEB-INF/register.jsp").forward(request,response); } }
2,425
0.651653
0.64876
57
41.456139
31.466536
122
false
false
0
0
0
0
0
0
0.807018
false
false
4
4f202655fa729db9648969886a610f2f076f3eb6
16,707,422,851,070
a03c05171130ae8b977e6d5ee1c138fe0663e968
/src/main/java/Reference/Ref.java
ff51b1465a1306e16d0f93e9329f002b3e02f7a4
[]
no_license
SFR1981/Report-Generator
https://github.com/SFR1981/Report-Generator
74580d0abdcfa8ad0344c0a3a0ad514e1431ae7b
31591c5a5894478444fb4745f9bda80eda9d670c
refs/heads/master
2020-03-29T06:44:56.097000
2018-09-20T17:52:19
2018-09-20T17:52:19
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package Reference; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Unmarshaller; import java.io.File; public class Ref { public static ReferenceData getReference() throws JAXBException { ReferenceData referenceData = null; File file = new File("static/ReferenceData.xml"); try { JAXBContext context = JAXBContext.newInstance(ReferenceData.class); Unmarshaller unmarshaller = context.createUnmarshaller(); referenceData = (ReferenceData) unmarshaller.unmarshal(file); } catch (JAXBException e) { e.printStackTrace(); } return referenceData; } };
UTF-8
Java
707
java
Ref.java
Java
[]
null
[]
package Reference; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Unmarshaller; import java.io.File; public class Ref { public static ReferenceData getReference() throws JAXBException { ReferenceData referenceData = null; File file = new File("static/ReferenceData.xml"); try { JAXBContext context = JAXBContext.newInstance(ReferenceData.class); Unmarshaller unmarshaller = context.createUnmarshaller(); referenceData = (ReferenceData) unmarshaller.unmarshal(file); } catch (JAXBException e) { e.printStackTrace(); } return referenceData; } };
707
0.670438
0.670438
26
25.73077
25.652348
79
false
false
0
0
0
0
0
0
0.5
false
false
4
0db2bb8312e2eaf2fda15ba790948aea713759fc
11,622,181,540,869
391295d0b65b7ecbb458200bcc557b315de10921
/src/main/java/nexussix/quarkus/amqp/CamelRoute.java
d218bff4034c36f3e972b14d90d060f3aa95640d
[]
no_license
nexus-Six/quarkus-amqp-client
https://github.com/nexus-Six/quarkus-amqp-client
39a080c33dc02bec21e81ec6769ec5608b935778
a246121e7eda887b96ddf9b70845a81f22e83c36
refs/heads/master
2022-12-05T06:04:56.616000
2020-09-01T12:28:43
2020-09-01T12:28:43
291,991,098
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package nexussix.quarkus.amqp; import org.apache.camel.builder.RouteBuilder; // Creates a Camel Route that connects to an AMQ Broker over AMQP and listens to messages on the hello queue public class CamelRoute extends RouteBuilder{ @Override public void configure() throws Exception { from("amqp:topic:prices") .to("log:?level=INFO&showBody=true"); } }
UTF-8
Java
439
java
CamelRoute.java
Java
[]
null
[]
package nexussix.quarkus.amqp; import org.apache.camel.builder.RouteBuilder; // Creates a Camel Route that connects to an AMQ Broker over AMQP and listens to messages on the hello queue public class CamelRoute extends RouteBuilder{ @Override public void configure() throws Exception { from("amqp:topic:prices") .to("log:?level=INFO&showBody=true"); } }
439
0.633257
0.633257
17
24.882353
28.608683
108
false
false
0
0
0
0
0
0
0.176471
false
false
4
52551ddeec33e87511f42eb24d6411492ab1a0d0
32,461,362,850,049
f08150c5e001fbfa654ad5d3c73649381f516d8c
/src/test_ex/ArrayOne.java
ac941998afe720b00886f545955f509f8d310309
[]
no_license
ums114/Mymymemine
https://github.com/ums114/Mymymemine
a5bc43f14bfbd5beada151c304fad1d829637997
67b0d29f386ec3c3f6ede44b75ee12602d93a585
refs/heads/master
2021-01-10T02:01:22.612000
2015-12-01T08:13:26
2015-12-01T08:13:26
47,175,164
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package test_ex; public class ArrayOne { public static void main(String args[]) { int[] arr = new int[3]; arr[0] = 1; arr[1] = 2; arr[2] = 3; System.out.println("arr[0] : " + arr[0]); System.out.println("arr[0] : " + arr[1]); System.out.println("arr[0] : " + arr[2]); int[] arr2 = { 1, 2, 3 }; System.out.println("arr2[0] : " + arr2[0]); System.out.println("arr2[1] : " + arr2[1]); System.out.println("arr2[2] : " + arr2[2]); int[] arr3 = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; for (int a : arr3) { System.out.println(a); } int[] arr4 = new int[10]; for(int i = 0; i < 10; i++){ arr4[i] = i + 1; System.out.println(arr4[i]); } } }
UTF-8
Java
740
java
ArrayOne.java
Java
[]
null
[]
package test_ex; public class ArrayOne { public static void main(String args[]) { int[] arr = new int[3]; arr[0] = 1; arr[1] = 2; arr[2] = 3; System.out.println("arr[0] : " + arr[0]); System.out.println("arr[0] : " + arr[1]); System.out.println("arr[0] : " + arr[2]); int[] arr2 = { 1, 2, 3 }; System.out.println("arr2[0] : " + arr2[0]); System.out.println("arr2[1] : " + arr2[1]); System.out.println("arr2[2] : " + arr2[2]); int[] arr3 = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; for (int a : arr3) { System.out.println(a); } int[] arr4 = new int[10]; for(int i = 0; i < 10; i++){ arr4[i] = i + 1; System.out.println(arr4[i]); } } }
740
0.482432
0.413514
36
18.555555
17.730145
59
false
false
0
0
0
0
0
0
2.361111
false
false
4
3d38367cb8d7b4b5c56624f27dc34054160d7714
21,088,289,438,732
b6450cc5c18068a99bc3e2bc7064e119ed026fa6
/steel-store/commons-server/src/main/java/com/ryit/commons/base/controller/GlobalExceptionController.java
b0148cec56717a91f4cb9144834220834c43e421
[ "Apache-2.0" ]
permissive
samphin/finish-projects
https://github.com/samphin/finish-projects
0f36eec553d49c04454a3871e85bd385f46173ae
19d2cb352e8c8209867573e6de00f144ddbe124e
refs/heads/master
2022-12-28T05:51:02.774000
2020-04-03T09:13:52
2020-04-03T09:13:52
225,137,147
1
2
Apache-2.0
false
2022-12-16T00:39:36
2019-12-01T09:38:16
2020-04-03T09:13:58
2022-12-16T00:39:34
605
1
2
28
Java
false
false
package com.ryit.commons.base.controller; import com.ryit.commons.base.vo.ResponseData; import com.ryit.commons.enums.SystemErrorEnum; import com.ryit.commons.exception.CustomException; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.validation.BindException; import org.springframework.validation.BindingResult; import org.springframework.validation.FieldError; import org.springframework.web.bind.MethodArgumentNotValidException; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import java.sql.SQLException; import java.util.List; import java.util.stream.Collectors; /** * 处理Controller层全局异常处理 * * @author samphin * @since 2019-9-28 15:30:14 */ @ControllerAdvice public class GlobalExceptionController { private static Logger LOGGER = LoggerFactory.getLogger(GlobalExceptionController.class); /** * 运行异常错误码 */ private final int runTimeError = 400; /** * 参数绑定出错 */ private final int bindParamError = 300; /** * 数据校验错误码 */ private final int validateError = 301; /** * SQL错误码 */ private final int sqlError = 280; /** * 捕获自定义异常 * * @param ex * @return */ @ExceptionHandler(CustomException.class) public ResponseEntity<ResponseData> handleCustomException(CustomException ex) { String errmsg = null; if (ex.getSystemErrorEnum().equals(SystemErrorEnum.ERROR_PARAM)) { errmsg = ex.getLocalizedMessage(); } else { errmsg = ex.getSystemErrorEnum().getErrorMsg(); if (StringUtils.isEmpty(errmsg)) { errmsg = ex.getMessage(); } } GlobalExceptionController.LOGGER.error("哎呦!异常::" + ex.getLocalizedMessage(), ex); return new ResponseEntity(ResponseData.failure(ex.getSystemErrorEnum().getErrorCode(), errmsg), HttpStatus.OK); } /** * 捕获参数绑定异常 * * @param ex * @return */ @ExceptionHandler(BindException.class) public ResponseEntity<ResponseData> handleValidateException(BindException ex, BindingResult results) { ex.printStackTrace(); StringBuffer sb = new StringBuffer(); if (results.hasErrors()) { List<FieldError> errors = results.getFieldErrors(); errors.stream().forEach(x -> sb.append(x.getField() + "=[" + x.getDefaultMessage()).append("];")); } return new ResponseEntity(ResponseData.failure(bindParamError, sb.toString()), HttpStatus.OK); } /** * 参数校验拦截器 * 针对 @RequestBody参数校验异常 * * @param e * @return */ @ExceptionHandler(MethodArgumentNotValidException.class) public ResponseEntity<ResponseData> handleMethodArgumentNotValidException(MethodArgumentNotValidException e) { String errorMsg = e.getBindingResult().getAllErrors() .stream() .map(objectError -> objectError.getDefaultMessage()) .collect(Collectors.joining(",")); return new ResponseEntity(ResponseData.failure(validateError, errorMsg), HttpStatus.OK); } /** * 捕获运行时异常 * * @param ex * @return */ @ExceptionHandler(RuntimeException.class) public ResponseEntity<ResponseData> handleRuntimeException(RuntimeException ex) { GlobalExceptionController.LOGGER.error(ex.getMessage(), ex); return new ResponseEntity(ResponseData.failure(runTimeError, ex.getMessage()), HttpStatus.OK); } /** * 捕获SQL执行异常 * * @param ex * @return */ @ExceptionHandler(SQLException.class) public ResponseEntity<ResponseData> handleSQLException(SQLException ex) { GlobalExceptionController.LOGGER.error(ex.getMessage(), ex); return new ResponseEntity(ResponseData.failure(sqlError, ex.getMessage()), HttpStatus.OK); } /** * 捕获全局异常 * * @param ex * @return */ @ExceptionHandler(Exception.class) public ResponseEntity<String> handleAllException(Exception ex) { GlobalExceptionController.LOGGER.error(ex.getMessage(), ex); return new ResponseEntity(ex.getLocalizedMessage(), HttpStatus.OK); } }
UTF-8
Java
4,577
java
GlobalExceptionController.java
Java
[ { "context": "lectors;\n\n/**\n * 处理Controller层全局异常处理\n *\n * @author samphin\n * @since 2019-9-28 15:30:14\n */\n@ControllerAdvic", "end": 875, "score": 0.9994261264801025, "start": 868, "tag": "USERNAME", "value": "samphin" } ]
null
[]
package com.ryit.commons.base.controller; import com.ryit.commons.base.vo.ResponseData; import com.ryit.commons.enums.SystemErrorEnum; import com.ryit.commons.exception.CustomException; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.validation.BindException; import org.springframework.validation.BindingResult; import org.springframework.validation.FieldError; import org.springframework.web.bind.MethodArgumentNotValidException; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import java.sql.SQLException; import java.util.List; import java.util.stream.Collectors; /** * 处理Controller层全局异常处理 * * @author samphin * @since 2019-9-28 15:30:14 */ @ControllerAdvice public class GlobalExceptionController { private static Logger LOGGER = LoggerFactory.getLogger(GlobalExceptionController.class); /** * 运行异常错误码 */ private final int runTimeError = 400; /** * 参数绑定出错 */ private final int bindParamError = 300; /** * 数据校验错误码 */ private final int validateError = 301; /** * SQL错误码 */ private final int sqlError = 280; /** * 捕获自定义异常 * * @param ex * @return */ @ExceptionHandler(CustomException.class) public ResponseEntity<ResponseData> handleCustomException(CustomException ex) { String errmsg = null; if (ex.getSystemErrorEnum().equals(SystemErrorEnum.ERROR_PARAM)) { errmsg = ex.getLocalizedMessage(); } else { errmsg = ex.getSystemErrorEnum().getErrorMsg(); if (StringUtils.isEmpty(errmsg)) { errmsg = ex.getMessage(); } } GlobalExceptionController.LOGGER.error("哎呦!异常::" + ex.getLocalizedMessage(), ex); return new ResponseEntity(ResponseData.failure(ex.getSystemErrorEnum().getErrorCode(), errmsg), HttpStatus.OK); } /** * 捕获参数绑定异常 * * @param ex * @return */ @ExceptionHandler(BindException.class) public ResponseEntity<ResponseData> handleValidateException(BindException ex, BindingResult results) { ex.printStackTrace(); StringBuffer sb = new StringBuffer(); if (results.hasErrors()) { List<FieldError> errors = results.getFieldErrors(); errors.stream().forEach(x -> sb.append(x.getField() + "=[" + x.getDefaultMessage()).append("];")); } return new ResponseEntity(ResponseData.failure(bindParamError, sb.toString()), HttpStatus.OK); } /** * 参数校验拦截器 * 针对 @RequestBody参数校验异常 * * @param e * @return */ @ExceptionHandler(MethodArgumentNotValidException.class) public ResponseEntity<ResponseData> handleMethodArgumentNotValidException(MethodArgumentNotValidException e) { String errorMsg = e.getBindingResult().getAllErrors() .stream() .map(objectError -> objectError.getDefaultMessage()) .collect(Collectors.joining(",")); return new ResponseEntity(ResponseData.failure(validateError, errorMsg), HttpStatus.OK); } /** * 捕获运行时异常 * * @param ex * @return */ @ExceptionHandler(RuntimeException.class) public ResponseEntity<ResponseData> handleRuntimeException(RuntimeException ex) { GlobalExceptionController.LOGGER.error(ex.getMessage(), ex); return new ResponseEntity(ResponseData.failure(runTimeError, ex.getMessage()), HttpStatus.OK); } /** * 捕获SQL执行异常 * * @param ex * @return */ @ExceptionHandler(SQLException.class) public ResponseEntity<ResponseData> handleSQLException(SQLException ex) { GlobalExceptionController.LOGGER.error(ex.getMessage(), ex); return new ResponseEntity(ResponseData.failure(sqlError, ex.getMessage()), HttpStatus.OK); } /** * 捕获全局异常 * * @param ex * @return */ @ExceptionHandler(Exception.class) public ResponseEntity<String> handleAllException(Exception ex) { GlobalExceptionController.LOGGER.error(ex.getMessage(), ex); return new ResponseEntity(ex.getLocalizedMessage(), HttpStatus.OK); } }
4,577
0.675369
0.669012
142
30.021128
29.890991
119
false
false
0
0
0
0
0
0
0.422535
false
false
4
3cc62f4ad44f307a22d879df7ac0b7551d1634e5
31,868,657,403,280
528b7976331a7b277892d4212494f87592558740
/seocoo-service-bundle/src/main/java/cn/seocoo/platform/service/merchant/impl/MerchantServiceImpl.java
d3142c7de63010abd9a3ec68abb063c187d359e0
[]
no_license
suevip/platform-6
https://github.com/suevip/platform-6
276afe330254ee5ddb2987d738fe296e2a5fc209
29f71a3283f35fe333262dc9550456166a72dcb4
refs/heads/master
2018-03-25T12:13:59.984000
2017-04-01T02:13:02
2017-04-01T02:13:09
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package cn.seocoo.platform.service.merchant.impl; import cn.seocoo.platform.dao.groupMerchantPay.inf.GroupMerchantPayDao; import cn.seocoo.platform.dao.merchant.inf.MerchantDao; import cn.seocoo.platform.dao.merchantInfo.inf.MerchantInfoDao; import cn.seocoo.platform.dao.merchantRate.inf.MerchantRateDao; import cn.seocoo.platform.dao.merchantUser.inf.MerchantUserDao; import cn.seocoo.platform.dao.rateDimAttr.inf.RateDimAttrDao; import cn.seocoo.platform.dao.rateSku.inf.RateSkuDao; import cn.seocoo.platform.dao.userBank.inf.UserBankDao; import cn.seocoo.platform.dao.userIdinfo.inf.UserIdinfoDao; import cn.seocoo.platform.dao.userRelationship.inf.UserRelationshipDao; import cn.seocoo.platform.model.*; import cn.seocoo.platform.service.merchant.inf.MerchantService; import com.tydic.framework.util.MD5Util; import org.apache.commons.lang3.StringUtils; import org.springframework.transaction.interceptor.TransactionAspectSupport; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Map; public class MerchantServiceImpl implements MerchantService{ private MerchantDao merchantDao; private UserRelationshipDao userRelationshipDao; private MerchantInfoDao merchantInfoDao; private GroupMerchantPayDao groupMerchantPayDao; private MerchantUserDao merchantUserDao; private UserIdinfoDao userIdinfoDao; private UserBankDao userBankDao; private RateDimAttrDao rateDimAttrDao; private RateSkuDao rateSkuDao; private MerchantRateDao merchantRateDao; public MerchantDao getMerchantDao() { return merchantDao; } public void setMerchantDao(MerchantDao merchantDao) { this.merchantDao = merchantDao; } @Override public Merchant queryMerchant(Merchant merchant){ return merchantDao.queryMerchant(merchant); } @Override public List<Merchant> queryMerchantList(Merchant merchant){ return merchantDao.queryMerchantList(merchant); } @Override public void saveMerchant(Merchant merchant){ merchantDao.saveMerchant(merchant); } @Override public void updateMerchant(Merchant merchant){ merchantDao.updateMerchant(merchant); } @Override public void deleteMerchant(Merchant merchant){ merchantDao.deleteMerchant(merchant); } @Override public List<Merchant> queryMerchantPage(Map map){ return merchantDao.queryMerchantPage(map); } @Override public Integer queryMerchantPageCount(Map map){ return merchantDao.queryMerchantPageCount(map); } @Override public void updateMerchantByOutMchntId(Merchant merchant) { // TODO Auto-generated method stub merchantDao.updateMerchantByOutMchntId(merchant); } @Override public void saveMerchantAndMerchantUser(Merchant merchant,String PlatformId,String txnSeq,String loginName,String receiptQrCode, int isAudito) { //保存商户信息以及商户 try { merchant.setCreateTime(new Date()); merchant.setDevType(1); merchant.setFlag(0); merchant.setTxnSeq(txnSeq); merchant.setPlatformId(PlatformId); // 判断拓展人员编号|operId:过长则截取 if (merchant.getOperId().length() > 15) { merchant.setOperId(merchant.getOperId().substring(0, 15)); } //保存商户信息 MerchantInfo info = new MerchantInfo(); //代入上级merchantCode // 获取当前角色的GroupCode if (isAudito != 1) { UserRelationship userRelationship = new UserRelationship(); userRelationship.setLoginName(loginName); List<UserRelationship> userRelationshipList = userRelationshipDao.queryUserRelationshipList(userRelationship); if (userRelationshipList != null & userRelationshipList.size() > 0) { userRelationship = userRelationshipList.get(0); //获取代理商商户信息 GroupMerchantPay groupMerchantPay = new GroupMerchantPay(); groupMerchantPay.setGroupCode(userRelationship.getGroupCode()); List<GroupMerchantPay> groupMerchantPays = groupMerchantPayDao.queryGroupMerchantPayList(groupMerchantPay); if (groupMerchantPays != null && groupMerchantPays.size() > 0) { info.setParentMerchantCode(groupMerchantPays.get(0).getMerchantCode()); info.setParentUser(groupMerchantPays.get(0).getMerchantUser()); } } } receiptQrCode += "/codeToPay.do?merchantCode=" + merchant.getOutMchntId(); info.setReceiptQrCode(receiptQrCode); info.setMerchantCode(merchant.getOutMchntId()); info.setBank("MS"); info.setCertifyStatus(0); info.setCreateTime(new Date()); info.setCreateUser(loginName); info.setCurrentTotalProfit(0.00); info.setTotalProfit(0.00); info.setLevel(merchant.getMerchantLevel()); info.setSubmitAuditTime(new Date()); //身份证信息 UserIdinfo userId = new UserIdinfo(); userId.setMerchantCode(merchant.getOutMchntId()); userId.setRealName(merchant.getCorpName()); userId.setIDNumber(merchant.getIdtCard()); userId.setAddress(merchant.getAddress()); userId.setAuditStatus(1); userId.setCreateUser(loginName); userId.setCreateTime(new Date()); // 保存 银行信息 UserBank userBank = new UserBank(); userBank.setMerchantCode(merchant.getOutMchntId()); userBank.setCardNumber(merchant.getCardNumber()); userBank.setAffiliatedBank(merchant.getAffiliatedBank()); userBank.setBankName(merchant.getBankName()); userBank.setBankArea(merchant.getBankProvince() + "" + merchant.getBankCity()); userBank.setBankAreaCode(merchant.getBankAreaCode()); userBank.setBankNumber(merchant.getBankNumber()); userBank.setAuditStatus(1); userBank.setCreateUser(loginName); userBank.setCreateTime(new Date()); userBank.setProvince(merchant.getProvince()); userBank.setCity(merchant.getBankCity()); // 保存费率 String skuWxString = ""; String skuSFBString = ""; RateDimAttr rateDimAttr = new RateDimAttr(); rateDimAttr.setDimCode("level");// 等级 rateDimAttr.setDimAttrCode(merchant.getMerchantLevel()); List<RateDimAttr> rateDimAttrWithLastLevel = rateDimAttrDao.queryRateDimAttrWithLastLevel(rateDimAttr); if (rateDimAttrWithLastLevel != null && rateDimAttrWithLastLevel.size() > 0) { rateDimAttr = rateDimAttrWithLastLevel.get(0); skuWxString = "bankminsheng" + "tnt001" + rateDimAttr.getDimCode() + rateDimAttr.getDimAttrCode() + "payStyleweixin"; skuSFBString = "bankminsheng" + "tnt001" + rateDimAttr.getDimCode() + rateDimAttr.getDimAttrCode() + "payStylezhifubao"; } skuWxString = MD5Util.getMD5String(skuWxString); skuSFBString = MD5Util.getMD5String(skuSFBString); // 根据SKUCode查询费率 List<MerchantRate> merchantRateList = new ArrayList<MerchantRate>(); List<RateSku> queryRateSkuList = rateSkuDao.queryRateSkuList(new RateSku()); for (RateSku rateSku2 : queryRateSkuList) { MerchantRate merchantRate = new MerchantRate(); merchantRate.setCreateTime(new Date()); merchantRate.setIntoRate(rateSku2.getSetRate()); merchantRate.setTradeRate(rateSku2.getIntoRate()); merchantRate.setMerchantCode(merchant.getOutMchntId() + "_temp"); if (StringUtils.equals(rateSku2.getSkuCode(), skuWxString)) { merchantRate.setPayChannel("weixin"); merchantRateList.add(merchantRate); } if (StringUtils.equals(rateSku2.getSkuCode(), skuSFBString)) { merchantRate.setPayChannel("zhifubao"); merchantRateList.add(merchantRate); } } merchantDao.saveMerchant(merchant); merchantInfoDao.saveMerchantInfo(info); userIdinfoDao.saveUserIdinfo(userId); userBankDao.saveUserBank(userBank); MerchantRate merchantRate = new MerchantRate(); merchantRate.setMerchantCode(merchant.getOutMchntId() + "_temp"); merchantRateDao.deleteMerchantRate(merchantRate); merchantRateDao.batchInsertMerchantRate(merchantRateList); } catch (Exception e) { e.printStackTrace(); TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); } } @Override public void updateMerchantAndMerchantUser(Merchant merchant) { MerchantInfo info = new MerchantInfo(); info.setMerchantCode(merchant.getOutMchntId()); info.setLevel(merchant.getMerchantLevel()); UserIdinfo userId = new UserIdinfo(); userId.setMerchantCode(merchant.getOutMchntId()); userId.setRealName(merchant.getCorpName()); userId.setIDNumber(merchant.getIdtCard()); userId.setAddress(merchant.getAddress()); UserBank userBank = new UserBank(); userBank.setMerchantCode(merchant.getOutMchntId()); userBank.setCardNumber(merchant.getCardNumber()); userBank.setAffiliatedBank(merchant.getAffiliatedBank()); userBank.setBankName(merchant.getBankName()); userBank.setBankArea(merchant.getBankProvince() + "" + merchant.getBankCity()); userBank.setBankAreaCode(merchant.getBankAreaCode()); userBank.setBankNumber(merchant.getBankNumber()); userBank.setProvince(merchant.getProvince()); userBank.setCity(merchant.getBankCity()); // 保存费率 String skuWxString = ""; String skuSFBString = ""; RateDimAttr rateDimAttr = new RateDimAttr(); rateDimAttr.setDimCode("level");// 等级 rateDimAttr.setDimAttrCode(merchant.getMerchantLevel()); List<RateDimAttr> rateDimAttrWithLastLevel = rateDimAttrDao.queryRateDimAttrWithLastLevel(rateDimAttr); if (rateDimAttrWithLastLevel != null && rateDimAttrWithLastLevel.size() > 0) { rateDimAttr = rateDimAttrWithLastLevel.get(0); skuWxString = "bankminsheng" + "tnt001" + rateDimAttr.getDimCode() + rateDimAttr.getDimAttrCode() + "payStyleweixin"; skuSFBString = "bankminsheng" + "tnt001" + rateDimAttr.getDimCode() + rateDimAttr.getDimAttrCode() + "payStylezhifubao"; } skuWxString = MD5Util.getMD5String(skuWxString); skuSFBString = MD5Util.getMD5String(skuSFBString); // 根据SKUCode查询费率 List<MerchantRate> merchantRateList = new ArrayList<MerchantRate>(); List<RateSku> queryRateSkuList = rateSkuDao.queryRateSkuList(new RateSku()); for (RateSku rateSku2 : queryRateSkuList) { MerchantRate merchantRate = new MerchantRate(); merchantRate.setCreateTime(new Date()); merchantRate.setIntoRate(rateSku2.getSetRate()); merchantRate.setTradeRate(rateSku2.getIntoRate()); merchantRate.setMerchantCode(merchant.getOutMchntId() + "_temp"); if (StringUtils.equals(rateSku2.getSkuCode(), skuWxString)) { merchantRate.setPayChannel("weixin"); merchantRateList.add(merchantRate); } if (StringUtils.equals(rateSku2.getSkuCode(), skuSFBString)) { merchantRate.setPayChannel("zhifubao"); merchantRateList.add(merchantRate); } } try { merchantDao.updateMerchant(merchant); merchantInfoDao.updateMerchantInfo(info); userIdinfoDao.updateUserIdinfo(userId); userBankDao.updateUserBank(userBank); MerchantRate merchantRate = new MerchantRate(); merchantRate.setMerchantCode(merchant.getOutMchntId() + "_temp"); merchantRateDao.deleteMerchantRate(merchantRate); merchantRateDao.batchInsertMerchantRate(merchantRateList); } catch (Exception e) { e.printStackTrace(); TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); } } @Override public List<Merchant> queryMerchantWithMerchantInfo(Map map) { return merchantDao.queryMerchantWithMerchantInfo(map); } @Override public Integer queryMerchantWithMerchantInfoCount(Map map) { return merchantDao.queryMerchantWithMerchantInfoCount(map); } public UserRelationshipDao getUserRelationshipDao() { return userRelationshipDao; } public void setUserRelationshipDao(UserRelationshipDao userRelationshipDao) { this.userRelationshipDao = userRelationshipDao; } public MerchantInfoDao getMerchantInfoDao() { return merchantInfoDao; } public void setMerchantInfoDao(MerchantInfoDao merchantInfoDao) { this.merchantInfoDao = merchantInfoDao; } public GroupMerchantPayDao getGroupMerchantPayDao() { return groupMerchantPayDao; } public void setGroupMerchantPayDao(GroupMerchantPayDao groupMerchantPayDao) { this.groupMerchantPayDao = groupMerchantPayDao; } public MerchantUserDao getMerchantUserDao() { return merchantUserDao; } public void setMerchantUserDao(MerchantUserDao merchantUserDao) { this.merchantUserDao = merchantUserDao; } public UserIdinfoDao getUserIdinfoDao() { return userIdinfoDao; } public void setUserIdinfoDao(UserIdinfoDao userIdinfoDao) { this.userIdinfoDao = userIdinfoDao; } public UserBankDao getUserBankDao() { return userBankDao; } public void setUserBankDao(UserBankDao userBankDao) { this.userBankDao = userBankDao; } public RateDimAttrDao getRateDimAttrDao() { return rateDimAttrDao; } public void setRateDimAttrDao(RateDimAttrDao rateDimAttrDao) { this.rateDimAttrDao = rateDimAttrDao; } public RateSkuDao getRateSkuDao() { return rateSkuDao; } public void setRateSkuDao(RateSkuDao rateSkuDao) { this.rateSkuDao = rateSkuDao; } public MerchantRateDao getMerchantRateDao() { return merchantRateDao; } public void setMerchantRateDao(MerchantRateDao merchantRateDao) { this.merchantRateDao = merchantRateDao; } }
UTF-8
Java
14,945
java
MerchantServiceImpl.java
Java
[ { "context": "nt merchant,String PlatformId,String txnSeq,String loginName,String receiptQrCode, int isAudito) {\n //保", "end": 2897, "score": 0.6471854448318481, "start": 2888, "tag": "USERNAME", "value": "loginName" }, { "context": "();\n userRelationship.setLoginName(loginName);\n List<UserRelationship> userRela", "end": 3660, "score": 0.9011021256446838, "start": 3651, "tag": "USERNAME", "value": "loginName" }, { "context": "tAuditStatus(1);\n userId.setCreateUser(loginName);\n userId.setCreateTime(new Date());\n\n", "end": 5515, "score": 0.851224422454834, "start": 5506, "tag": "USERNAME", "value": "loginName" }, { "context": "uditStatus(1);\n userBank.setCreateUser(loginName);\n userBank.setCreateTime(new Date());", "end": 6195, "score": 0.8067171573638916, "start": 6186, "tag": "USERNAME", "value": "loginName" } ]
null
[]
package cn.seocoo.platform.service.merchant.impl; import cn.seocoo.platform.dao.groupMerchantPay.inf.GroupMerchantPayDao; import cn.seocoo.platform.dao.merchant.inf.MerchantDao; import cn.seocoo.platform.dao.merchantInfo.inf.MerchantInfoDao; import cn.seocoo.platform.dao.merchantRate.inf.MerchantRateDao; import cn.seocoo.platform.dao.merchantUser.inf.MerchantUserDao; import cn.seocoo.platform.dao.rateDimAttr.inf.RateDimAttrDao; import cn.seocoo.platform.dao.rateSku.inf.RateSkuDao; import cn.seocoo.platform.dao.userBank.inf.UserBankDao; import cn.seocoo.platform.dao.userIdinfo.inf.UserIdinfoDao; import cn.seocoo.platform.dao.userRelationship.inf.UserRelationshipDao; import cn.seocoo.platform.model.*; import cn.seocoo.platform.service.merchant.inf.MerchantService; import com.tydic.framework.util.MD5Util; import org.apache.commons.lang3.StringUtils; import org.springframework.transaction.interceptor.TransactionAspectSupport; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Map; public class MerchantServiceImpl implements MerchantService{ private MerchantDao merchantDao; private UserRelationshipDao userRelationshipDao; private MerchantInfoDao merchantInfoDao; private GroupMerchantPayDao groupMerchantPayDao; private MerchantUserDao merchantUserDao; private UserIdinfoDao userIdinfoDao; private UserBankDao userBankDao; private RateDimAttrDao rateDimAttrDao; private RateSkuDao rateSkuDao; private MerchantRateDao merchantRateDao; public MerchantDao getMerchantDao() { return merchantDao; } public void setMerchantDao(MerchantDao merchantDao) { this.merchantDao = merchantDao; } @Override public Merchant queryMerchant(Merchant merchant){ return merchantDao.queryMerchant(merchant); } @Override public List<Merchant> queryMerchantList(Merchant merchant){ return merchantDao.queryMerchantList(merchant); } @Override public void saveMerchant(Merchant merchant){ merchantDao.saveMerchant(merchant); } @Override public void updateMerchant(Merchant merchant){ merchantDao.updateMerchant(merchant); } @Override public void deleteMerchant(Merchant merchant){ merchantDao.deleteMerchant(merchant); } @Override public List<Merchant> queryMerchantPage(Map map){ return merchantDao.queryMerchantPage(map); } @Override public Integer queryMerchantPageCount(Map map){ return merchantDao.queryMerchantPageCount(map); } @Override public void updateMerchantByOutMchntId(Merchant merchant) { // TODO Auto-generated method stub merchantDao.updateMerchantByOutMchntId(merchant); } @Override public void saveMerchantAndMerchantUser(Merchant merchant,String PlatformId,String txnSeq,String loginName,String receiptQrCode, int isAudito) { //保存商户信息以及商户 try { merchant.setCreateTime(new Date()); merchant.setDevType(1); merchant.setFlag(0); merchant.setTxnSeq(txnSeq); merchant.setPlatformId(PlatformId); // 判断拓展人员编号|operId:过长则截取 if (merchant.getOperId().length() > 15) { merchant.setOperId(merchant.getOperId().substring(0, 15)); } //保存商户信息 MerchantInfo info = new MerchantInfo(); //代入上级merchantCode // 获取当前角色的GroupCode if (isAudito != 1) { UserRelationship userRelationship = new UserRelationship(); userRelationship.setLoginName(loginName); List<UserRelationship> userRelationshipList = userRelationshipDao.queryUserRelationshipList(userRelationship); if (userRelationshipList != null & userRelationshipList.size() > 0) { userRelationship = userRelationshipList.get(0); //获取代理商商户信息 GroupMerchantPay groupMerchantPay = new GroupMerchantPay(); groupMerchantPay.setGroupCode(userRelationship.getGroupCode()); List<GroupMerchantPay> groupMerchantPays = groupMerchantPayDao.queryGroupMerchantPayList(groupMerchantPay); if (groupMerchantPays != null && groupMerchantPays.size() > 0) { info.setParentMerchantCode(groupMerchantPays.get(0).getMerchantCode()); info.setParentUser(groupMerchantPays.get(0).getMerchantUser()); } } } receiptQrCode += "/codeToPay.do?merchantCode=" + merchant.getOutMchntId(); info.setReceiptQrCode(receiptQrCode); info.setMerchantCode(merchant.getOutMchntId()); info.setBank("MS"); info.setCertifyStatus(0); info.setCreateTime(new Date()); info.setCreateUser(loginName); info.setCurrentTotalProfit(0.00); info.setTotalProfit(0.00); info.setLevel(merchant.getMerchantLevel()); info.setSubmitAuditTime(new Date()); //身份证信息 UserIdinfo userId = new UserIdinfo(); userId.setMerchantCode(merchant.getOutMchntId()); userId.setRealName(merchant.getCorpName()); userId.setIDNumber(merchant.getIdtCard()); userId.setAddress(merchant.getAddress()); userId.setAuditStatus(1); userId.setCreateUser(loginName); userId.setCreateTime(new Date()); // 保存 银行信息 UserBank userBank = new UserBank(); userBank.setMerchantCode(merchant.getOutMchntId()); userBank.setCardNumber(merchant.getCardNumber()); userBank.setAffiliatedBank(merchant.getAffiliatedBank()); userBank.setBankName(merchant.getBankName()); userBank.setBankArea(merchant.getBankProvince() + "" + merchant.getBankCity()); userBank.setBankAreaCode(merchant.getBankAreaCode()); userBank.setBankNumber(merchant.getBankNumber()); userBank.setAuditStatus(1); userBank.setCreateUser(loginName); userBank.setCreateTime(new Date()); userBank.setProvince(merchant.getProvince()); userBank.setCity(merchant.getBankCity()); // 保存费率 String skuWxString = ""; String skuSFBString = ""; RateDimAttr rateDimAttr = new RateDimAttr(); rateDimAttr.setDimCode("level");// 等级 rateDimAttr.setDimAttrCode(merchant.getMerchantLevel()); List<RateDimAttr> rateDimAttrWithLastLevel = rateDimAttrDao.queryRateDimAttrWithLastLevel(rateDimAttr); if (rateDimAttrWithLastLevel != null && rateDimAttrWithLastLevel.size() > 0) { rateDimAttr = rateDimAttrWithLastLevel.get(0); skuWxString = "bankminsheng" + "tnt001" + rateDimAttr.getDimCode() + rateDimAttr.getDimAttrCode() + "payStyleweixin"; skuSFBString = "bankminsheng" + "tnt001" + rateDimAttr.getDimCode() + rateDimAttr.getDimAttrCode() + "payStylezhifubao"; } skuWxString = MD5Util.getMD5String(skuWxString); skuSFBString = MD5Util.getMD5String(skuSFBString); // 根据SKUCode查询费率 List<MerchantRate> merchantRateList = new ArrayList<MerchantRate>(); List<RateSku> queryRateSkuList = rateSkuDao.queryRateSkuList(new RateSku()); for (RateSku rateSku2 : queryRateSkuList) { MerchantRate merchantRate = new MerchantRate(); merchantRate.setCreateTime(new Date()); merchantRate.setIntoRate(rateSku2.getSetRate()); merchantRate.setTradeRate(rateSku2.getIntoRate()); merchantRate.setMerchantCode(merchant.getOutMchntId() + "_temp"); if (StringUtils.equals(rateSku2.getSkuCode(), skuWxString)) { merchantRate.setPayChannel("weixin"); merchantRateList.add(merchantRate); } if (StringUtils.equals(rateSku2.getSkuCode(), skuSFBString)) { merchantRate.setPayChannel("zhifubao"); merchantRateList.add(merchantRate); } } merchantDao.saveMerchant(merchant); merchantInfoDao.saveMerchantInfo(info); userIdinfoDao.saveUserIdinfo(userId); userBankDao.saveUserBank(userBank); MerchantRate merchantRate = new MerchantRate(); merchantRate.setMerchantCode(merchant.getOutMchntId() + "_temp"); merchantRateDao.deleteMerchantRate(merchantRate); merchantRateDao.batchInsertMerchantRate(merchantRateList); } catch (Exception e) { e.printStackTrace(); TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); } } @Override public void updateMerchantAndMerchantUser(Merchant merchant) { MerchantInfo info = new MerchantInfo(); info.setMerchantCode(merchant.getOutMchntId()); info.setLevel(merchant.getMerchantLevel()); UserIdinfo userId = new UserIdinfo(); userId.setMerchantCode(merchant.getOutMchntId()); userId.setRealName(merchant.getCorpName()); userId.setIDNumber(merchant.getIdtCard()); userId.setAddress(merchant.getAddress()); UserBank userBank = new UserBank(); userBank.setMerchantCode(merchant.getOutMchntId()); userBank.setCardNumber(merchant.getCardNumber()); userBank.setAffiliatedBank(merchant.getAffiliatedBank()); userBank.setBankName(merchant.getBankName()); userBank.setBankArea(merchant.getBankProvince() + "" + merchant.getBankCity()); userBank.setBankAreaCode(merchant.getBankAreaCode()); userBank.setBankNumber(merchant.getBankNumber()); userBank.setProvince(merchant.getProvince()); userBank.setCity(merchant.getBankCity()); // 保存费率 String skuWxString = ""; String skuSFBString = ""; RateDimAttr rateDimAttr = new RateDimAttr(); rateDimAttr.setDimCode("level");// 等级 rateDimAttr.setDimAttrCode(merchant.getMerchantLevel()); List<RateDimAttr> rateDimAttrWithLastLevel = rateDimAttrDao.queryRateDimAttrWithLastLevel(rateDimAttr); if (rateDimAttrWithLastLevel != null && rateDimAttrWithLastLevel.size() > 0) { rateDimAttr = rateDimAttrWithLastLevel.get(0); skuWxString = "bankminsheng" + "tnt001" + rateDimAttr.getDimCode() + rateDimAttr.getDimAttrCode() + "payStyleweixin"; skuSFBString = "bankminsheng" + "tnt001" + rateDimAttr.getDimCode() + rateDimAttr.getDimAttrCode() + "payStylezhifubao"; } skuWxString = MD5Util.getMD5String(skuWxString); skuSFBString = MD5Util.getMD5String(skuSFBString); // 根据SKUCode查询费率 List<MerchantRate> merchantRateList = new ArrayList<MerchantRate>(); List<RateSku> queryRateSkuList = rateSkuDao.queryRateSkuList(new RateSku()); for (RateSku rateSku2 : queryRateSkuList) { MerchantRate merchantRate = new MerchantRate(); merchantRate.setCreateTime(new Date()); merchantRate.setIntoRate(rateSku2.getSetRate()); merchantRate.setTradeRate(rateSku2.getIntoRate()); merchantRate.setMerchantCode(merchant.getOutMchntId() + "_temp"); if (StringUtils.equals(rateSku2.getSkuCode(), skuWxString)) { merchantRate.setPayChannel("weixin"); merchantRateList.add(merchantRate); } if (StringUtils.equals(rateSku2.getSkuCode(), skuSFBString)) { merchantRate.setPayChannel("zhifubao"); merchantRateList.add(merchantRate); } } try { merchantDao.updateMerchant(merchant); merchantInfoDao.updateMerchantInfo(info); userIdinfoDao.updateUserIdinfo(userId); userBankDao.updateUserBank(userBank); MerchantRate merchantRate = new MerchantRate(); merchantRate.setMerchantCode(merchant.getOutMchntId() + "_temp"); merchantRateDao.deleteMerchantRate(merchantRate); merchantRateDao.batchInsertMerchantRate(merchantRateList); } catch (Exception e) { e.printStackTrace(); TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); } } @Override public List<Merchant> queryMerchantWithMerchantInfo(Map map) { return merchantDao.queryMerchantWithMerchantInfo(map); } @Override public Integer queryMerchantWithMerchantInfoCount(Map map) { return merchantDao.queryMerchantWithMerchantInfoCount(map); } public UserRelationshipDao getUserRelationshipDao() { return userRelationshipDao; } public void setUserRelationshipDao(UserRelationshipDao userRelationshipDao) { this.userRelationshipDao = userRelationshipDao; } public MerchantInfoDao getMerchantInfoDao() { return merchantInfoDao; } public void setMerchantInfoDao(MerchantInfoDao merchantInfoDao) { this.merchantInfoDao = merchantInfoDao; } public GroupMerchantPayDao getGroupMerchantPayDao() { return groupMerchantPayDao; } public void setGroupMerchantPayDao(GroupMerchantPayDao groupMerchantPayDao) { this.groupMerchantPayDao = groupMerchantPayDao; } public MerchantUserDao getMerchantUserDao() { return merchantUserDao; } public void setMerchantUserDao(MerchantUserDao merchantUserDao) { this.merchantUserDao = merchantUserDao; } public UserIdinfoDao getUserIdinfoDao() { return userIdinfoDao; } public void setUserIdinfoDao(UserIdinfoDao userIdinfoDao) { this.userIdinfoDao = userIdinfoDao; } public UserBankDao getUserBankDao() { return userBankDao; } public void setUserBankDao(UserBankDao userBankDao) { this.userBankDao = userBankDao; } public RateDimAttrDao getRateDimAttrDao() { return rateDimAttrDao; } public void setRateDimAttrDao(RateDimAttrDao rateDimAttrDao) { this.rateDimAttrDao = rateDimAttrDao; } public RateSkuDao getRateSkuDao() { return rateSkuDao; } public void setRateSkuDao(RateSkuDao rateSkuDao) { this.rateSkuDao = rateSkuDao; } public MerchantRateDao getMerchantRateDao() { return merchantRateDao; } public void setMerchantRateDao(MerchantRateDao merchantRateDao) { this.merchantRateDao = merchantRateDao; } }
14,945
0.669892
0.665967
367
39.264305
29.67753
148
false
false
0
0
0
0
0
0
0.547684
false
false
4
15076bb204e80dc9a3c12f0bae4c080bac5c5f7f
27,006,754,405,467
9c50844eb6accf6dcc02b64f9dc67091dddb9643
/src/main/java/com/algaworks/algafood/core/web/ApiDeprecationHandler.java
60427e9a07ffdeb4ba9b1306c010d03980d5de78
[]
no_license
jonathanmdr/Algafood-API
https://github.com/jonathanmdr/Algafood-API
be6b2bdafd31a04425dfd600ee5e195e8bb9a779
132352ca2db73426b35c1fafa000161ffc9be5a1
refs/heads/master
2022-08-30T15:41:36.991000
2022-07-15T23:54:40
2022-07-15T23:54:40
209,103,602
1
0
null
false
2022-07-15T23:54:41
2019-09-17T16:27:27
2020-12-10T13:02:06
2022-07-15T23:54:40
482
1
0
0
Java
false
false
package com.algaworks.algafood.core.web; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.stereotype.Component; import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; @Component public class ApiDeprecationHandler extends HandlerInterceptorAdapter { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { if (request.getRequestURI().startsWith("/v1/")) { response.addHeader("X-Algafood-Deprecated", "Esta versão está depreciada e deixará de existir à partir de 01/01/2021, utilize a versão mais recente disponível da API."); } return true; } }
UTF-8
Java
735
java
ApiDeprecationHandler.java
Java
[]
null
[]
package com.algaworks.algafood.core.web; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.stereotype.Component; import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; @Component public class ApiDeprecationHandler extends HandlerInterceptorAdapter { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { if (request.getRequestURI().startsWith("/v1/")) { response.addHeader("X-Algafood-Deprecated", "Esta versão está depreciada e deixará de existir à partir de 01/01/2021, utilize a versão mais recente disponível da API."); } return true; } }
735
0.802469
0.790123
21
33.714287
44.403069
172
false
false
0
0
0
0
0
0
1.333333
false
false
4
49147699e4e3a6c9f75287a0eb38f56fc43e823b
25,469,156,128,055
dae0c1ab4be0a123324de718a376a889a43b5278
/Labs/Lab2/src/Item.java
5f0bfe7fa73f82c38f99ed93054d3cddd6be5ba7
[]
no_license
Videkourias/ObjOrientedProgramming-Java
https://github.com/Videkourias/ObjOrientedProgramming-Java
0499c0c46ad9b4a766ea11fb0b2da2cdd340d845
4d42328d796e889521dbefadd9ed8f2bb1a0e5fc
refs/heads/master
2020-12-11T20:08:03.109000
2020-01-14T22:30:56
2020-01-14T22:30:56
233,947,201
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.util.*; /** Represents an item with a price, name, and quantity @author Dean Willavoys - 105003751 @since 2019-09-21 */ public class Item { //ATTRIBUTES private String name; //Name of item, non-empty private int quantity; //Quantity of item, greater than 0 private double price; //Price of item, greater than 0 //METHODS //CONSTRUCTORS /** * Default Constructor for Item object */ public Item(){ name = "ITEM_01"; quantity = 0; price = 0.00; } /** * Overloaded Constructor * @param name A non-empty string, the products name * @param quantity Integer quantity of the product, greater than 0 * @param price Double price of the product, greater than 0 */ public Item(String name, int quantity, double price){ this(); //Bad entry prevention setName(name); setQuantity(quantity); setPrice(price); } //ACCESS /** * Gets the parameters of this item from the user and sets them using private methods * @param n An integer representing the number of the item to be populated * @return int The number of the item that was populated */ public int populateItem(int n) { Scanner sc = new Scanner(System.in); System.out.print("Input name of item " + n + ": "); setName(sc.nextLine()); System.out.print("Input quantity of item " + n + ": "); setQuantity(sc.nextInt()); System.out.print("Input price of item " + n + ": "); setPrice(sc.nextDouble()); return n; } /** * Sets the name of the Item, does nothing if name is empty * @param name A string for the name of the item * @return String Returns the passed name */ private String setName(String name){ if(!name.isEmpty()){ this.name = name; } return name; } /** * Sets the quantity of the Item, does nothing if quantity is less than or equal to zero * @param quantity An integer for Item quantity * @return int Returns the passed quantity */ private int setQuantity(int quantity){ if(quantity > 0){ this.quantity = quantity; } return quantity; } /** * Sets the price of the Item, does nothing if price is less than or equal to zero * @param price A double for the price of the item * @return double Returns the passed price */ private double setPrice(double price){ if(price > 0){ this.price = price; } return price; } /** * Gets the name of the item * @return String The name of the item */ public String getName(){ return name; } /** * Gets the quantity of the item * @return int The quantity of the item */ public int getQuantity(){ return quantity; } /** * Gets the price of the item * @return double The price of the item */ public double getPrice(){ return price; } /** * Gets the total cost of the Item based on quantity * @return double The total cost of the item */ public double getTotal() { return calcTotal(); } //UTILITY /** * Overrides default toString method, instead returns attributes of Item object * @return String - Returns the attributes of the object passed */ public String toString(){ return name + "\t" + quantity + "\t$" + price + "\t" + calcTotal(); } /** * Calculates the total cost of an item based on quantity * @return double The total cost of the item */ private double calcTotal() { double total = 0.0; for(int i = 0; i < quantity; i++) { total += price; } return total; } }
UTF-8
Java
3,560
java
Item.java
Java
[ { "context": " an item with a price, name, and quantity\r\n@author Dean Willavoys - 105003751\r\n@since 2019-09-21\r\n*/\r\npublic class ", "end": 103, "score": 0.9997758865356445, "start": 89, "tag": "NAME", "value": "Dean Willavoys" } ]
null
[]
import java.util.*; /** Represents an item with a price, name, and quantity @author <NAME> - 105003751 @since 2019-09-21 */ public class Item { //ATTRIBUTES private String name; //Name of item, non-empty private int quantity; //Quantity of item, greater than 0 private double price; //Price of item, greater than 0 //METHODS //CONSTRUCTORS /** * Default Constructor for Item object */ public Item(){ name = "ITEM_01"; quantity = 0; price = 0.00; } /** * Overloaded Constructor * @param name A non-empty string, the products name * @param quantity Integer quantity of the product, greater than 0 * @param price Double price of the product, greater than 0 */ public Item(String name, int quantity, double price){ this(); //Bad entry prevention setName(name); setQuantity(quantity); setPrice(price); } //ACCESS /** * Gets the parameters of this item from the user and sets them using private methods * @param n An integer representing the number of the item to be populated * @return int The number of the item that was populated */ public int populateItem(int n) { Scanner sc = new Scanner(System.in); System.out.print("Input name of item " + n + ": "); setName(sc.nextLine()); System.out.print("Input quantity of item " + n + ": "); setQuantity(sc.nextInt()); System.out.print("Input price of item " + n + ": "); setPrice(sc.nextDouble()); return n; } /** * Sets the name of the Item, does nothing if name is empty * @param name A string for the name of the item * @return String Returns the passed name */ private String setName(String name){ if(!name.isEmpty()){ this.name = name; } return name; } /** * Sets the quantity of the Item, does nothing if quantity is less than or equal to zero * @param quantity An integer for Item quantity * @return int Returns the passed quantity */ private int setQuantity(int quantity){ if(quantity > 0){ this.quantity = quantity; } return quantity; } /** * Sets the price of the Item, does nothing if price is less than or equal to zero * @param price A double for the price of the item * @return double Returns the passed price */ private double setPrice(double price){ if(price > 0){ this.price = price; } return price; } /** * Gets the name of the item * @return String The name of the item */ public String getName(){ return name; } /** * Gets the quantity of the item * @return int The quantity of the item */ public int getQuantity(){ return quantity; } /** * Gets the price of the item * @return double The price of the item */ public double getPrice(){ return price; } /** * Gets the total cost of the Item based on quantity * @return double The total cost of the item */ public double getTotal() { return calcTotal(); } //UTILITY /** * Overrides default toString method, instead returns attributes of Item object * @return String - Returns the attributes of the object passed */ public String toString(){ return name + "\t" + quantity + "\t$" + price + "\t" + calcTotal(); } /** * Calculates the total cost of an item based on quantity * @return double The total cost of the item */ private double calcTotal() { double total = 0.0; for(int i = 0; i < quantity; i++) { total += price; } return total; } }
3,552
0.631461
0.622472
155
20.980644
22.116545
89
false
false
0
0
0
0
0
0
1.419355
false
false
4
d82026f6463ca71820c903ca1a912f7cc4d59a43
9,113,920,637,430
6f6e9137f5a8d1fda3f34264db6e59e85ea8eafc
/src/main/java/management/Director.java
6aa7f98f0db229e63d1ffdc6cc64890191f7b456
[]
no_license
xeb10154/Week_12_Day_1_Homework
https://github.com/xeb10154/Week_12_Day_1_Homework
3857c2d6012ce235b444b241c7b6bef4cbeda42e
0aa35af28339b3a4e4325fdbc9bdcfb829e7b768
refs/heads/master
2020-04-07T10:37:28.543000
2018-11-19T21:41:24
2018-11-19T21:41:24
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package management; public class Director extends Manager{ private int budget; public Director (String name, String ni, double salary, String deptName, int budget){ super(name, ni, salary, deptName); this.budget = budget; } public int getBudget() { return budget; } }
UTF-8
Java
316
java
Director.java
Java
[]
null
[]
package management; public class Director extends Manager{ private int budget; public Director (String name, String ni, double salary, String deptName, int budget){ super(name, ni, salary, deptName); this.budget = budget; } public int getBudget() { return budget; } }
316
0.64557
0.64557
15
20.066668
23.29368
89
false
false
0
0
0
0
0
0
0.8
false
false
4
7ef94046814b1c1dd0418d24e52d6194b2fc8c9d
11,836,929,902,603
847ac8ec2023390bc606d4f09a51c2da04344429
/WinAPI/src/de/johmat/myjojox/winapi/wmic/dcomapp/DCOMAppInterface.java
7bd71abadb57a1e01decf829af700a3a594750dd
[ "MIT" ]
permissive
MyJojoX/WinApi
https://github.com/MyJojoX/WinApi
3e28240667e395c9d92a67609494b1b6e2286b71
e334061edf1a4f2b8c2443dace648dc938c8c507
refs/heads/master
2019-07-31T20:40:16.984000
2017-06-22T14:39:21
2017-06-22T14:39:21
75,539,667
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package de.johmat.myjojox.winapi.wmic.dcomapp; public interface DCOMAppInterface { public String getAppID(); public String getCaption(); public String getDescription(); public String getInstallDate(); public String getName(); public Integer getStatus(); }
UTF-8
Java
266
java
DCOMAppInterface.java
Java
[]
null
[]
package de.johmat.myjojox.winapi.wmic.dcomapp; public interface DCOMAppInterface { public String getAppID(); public String getCaption(); public String getDescription(); public String getInstallDate(); public String getName(); public Integer getStatus(); }
266
0.770677
0.770677
12
21.166666
15.501792
46
false
false
0
0
0
0
0
0
1.166667
false
false
4
33874ca738f757d557ec40585f28d4ae949a395b
19,112,604,477,967
b5329a5ce192f40406830e6c7ad6a1c1a0c630c8
/TP05/src/Graph.java
4270738b90601182b12e81c024177d45d22ee135
[]
no_license
nabil-dbz/INF2010
https://github.com/nabil-dbz/INF2010
56f41ad380b2e9ca944e5c9afa918c66517158d9
e0ebf3fc3229a927ccd5d9255a2fb1a529a21c8b
refs/heads/master
2022-03-27T07:12:18.773000
2019-11-22T00:41:18
2019-11-22T00:41:18
209,094,187
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.util.ArrayList; import java.util.List; public class Graph { private List<Node> nodes; // Noeuds private List<Edge> edges; // Les arcs public Graph() { nodes = new ArrayList<>(); edges = new ArrayList<>(); } public List<Edge> getEdgesGoingFrom(Node source) { ArrayList<Edge> listRetour = new ArrayList<>(); for (Edge edge : edges) if (edge.getSource().equals(source)) listRetour.add(edge); return listRetour; } public List<Edge> getEdgesGoingTo(Node dest) { ArrayList<Edge> listRetour = new ArrayList<>(); for (Edge edge : edges) if (edge.getDestination().equals(dest)) listRetour.add(edge); return listRetour; } // Accesseurs public List<Node> getNodes() { return nodes; } public void setNodes(List<Node> nodes) { this.nodes = nodes; } public List<Edge> getEdges() { return edges; } public void setEdges(List<Edge> edges) { this.edges = edges; } }
UTF-8
Java
928
java
Graph.java
Java
[]
null
[]
import java.util.ArrayList; import java.util.List; public class Graph { private List<Node> nodes; // Noeuds private List<Edge> edges; // Les arcs public Graph() { nodes = new ArrayList<>(); edges = new ArrayList<>(); } public List<Edge> getEdgesGoingFrom(Node source) { ArrayList<Edge> listRetour = new ArrayList<>(); for (Edge edge : edges) if (edge.getSource().equals(source)) listRetour.add(edge); return listRetour; } public List<Edge> getEdgesGoingTo(Node dest) { ArrayList<Edge> listRetour = new ArrayList<>(); for (Edge edge : edges) if (edge.getDestination().equals(dest)) listRetour.add(edge); return listRetour; } // Accesseurs public List<Node> getNodes() { return nodes; } public void setNodes(List<Node> nodes) { this.nodes = nodes; } public List<Edge> getEdges() { return edges; } public void setEdges(List<Edge> edges) { this.edges = edges; } }
928
0.672414
0.672414
45
19.622223
16.298996
51
false
false
0
0
0
0
0
0
1.666667
false
false
4
a932842b39bd3f9334029efbb1bf96293fce3e10
2,104,534,029,763
c56fe1447be905bb38b50ddda59a14c529b5ee12
/src/LeetCode/Algorithms/Hard/RussianDollEnvelopes.java
66e696e8c7b2def76ce3a1c41cc52f41caf28fc2
[]
no_license
aspspspsp/LeetCode
https://github.com/aspspspsp/LeetCode
99739c1180179bdae6a88c9593c757ce7f512fbd
d57e45bdb77fc1c7dc7fcf3328dc9f54ca2d53dc
refs/heads/master
2021-01-12T13:09:19.141000
2019-02-01T10:37:39
2019-02-01T10:37:39
72,128,221
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package src.LeetCode.Algorithms.Hard; import java.util.Arrays; import java.util.Comparator; public class RussianDollEnvelopes { public int maxEnvelopes(int[][] envelopes) { if(envelopes == null || envelopes.length == 0) { return 0; } //將這個數組進行倒排 Arrays.sort(envelopes, new Comparator<int []>() { public int compare(int[] a, int[] b) { if(a[0] != b[0]) { return a[0] - b[0]; } else { return a[1] - b[1]; } } }); //存儲每個信封的最大容納信封的數量 /* ex: [5,4] [4,3] [4,2] [3, 1] [3, 1] ======================================= 3 2 2 1 1 */ int[] dp = new int[envelopes.length]; //紀錄最大數量 int max = 1; for(int i = 0; i < envelopes.length; i ++) { dp[i] = 1; //往下找尋比較小的信封,若符合條件,則計入數量當中 for(int j = i - 1; j >= 0; j --) { if(envelopes[i][0] > envelopes[j][0] && envelopes[i][1] > envelopes[j][1]) { dp[i] = Math.max(dp[i], dp[j] + 1); } } //維護最大數量 max = Math.max(dp[i], max); } return max; } }
UTF-8
Java
1,453
java
RussianDollEnvelopes.java
Java
[]
null
[]
package src.LeetCode.Algorithms.Hard; import java.util.Arrays; import java.util.Comparator; public class RussianDollEnvelopes { public int maxEnvelopes(int[][] envelopes) { if(envelopes == null || envelopes.length == 0) { return 0; } //將這個數組進行倒排 Arrays.sort(envelopes, new Comparator<int []>() { public int compare(int[] a, int[] b) { if(a[0] != b[0]) { return a[0] - b[0]; } else { return a[1] - b[1]; } } }); //存儲每個信封的最大容納信封的數量 /* ex: [5,4] [4,3] [4,2] [3, 1] [3, 1] ======================================= 3 2 2 1 1 */ int[] dp = new int[envelopes.length]; //紀錄最大數量 int max = 1; for(int i = 0; i < envelopes.length; i ++) { dp[i] = 1; //往下找尋比較小的信封,若符合條件,則計入數量當中 for(int j = i - 1; j >= 0; j --) { if(envelopes[i][0] > envelopes[j][0] && envelopes[i][1] > envelopes[j][1]) { dp[i] = Math.max(dp[i], dp[j] + 1); } } //維護最大數量 max = Math.max(dp[i], max); } return max; } }
1,453
0.379414
0.354621
49
26.183674
19.008778
92
false
false
0
0
0
0
0
0
0.571429
false
false
4
3ca4b90896eaeeaf77d1f8a0b5f34094715a34a5
22,720,377,020,378
60388f20ad90bde1ab52f85c88820f9fb6597afc
/src/main/java/constants/Routes.java
1f423d6842775e43906af19c4275c6b97b68a000
[]
no_license
GeorgeT94/Java-EE-Accounts
https://github.com/GeorgeT94/Java-EE-Accounts
690a3852897851f3f387e862cafeeb8e78b0bf6b
4d87f904d58a3a01d0a909d528723eb5e08fd587
refs/heads/master
2020-03-22T21:40:21.637000
2018-07-16T09:06:01
2018-07-16T09:06:01
140,705,725
0
0
null
false
2018-07-16T09:06:02
2018-07-12T11:43:41
2018-07-12T11:44:28
2018-07-16T09:06:01
34
0
0
0
Java
false
null
package constants; public class Routes { public static final String ROOT_PATH = "/accounts"; public static final String GET_ALL_PATH = "/all"; public static final String CREATE_ACCOUNT_PATH = "/create"; public static final String UPDATE_FIRSTNAME_PATH = "/update/firstName"; public static final String UPDATE_LASTNAME_PATH = "/update/lastName"; public static final String UPDATE_ACCOUNTNUMBER_PATH = "/update/accountNumber"; }
UTF-8
Java
446
java
Routes.java
Java
[]
null
[]
package constants; public class Routes { public static final String ROOT_PATH = "/accounts"; public static final String GET_ALL_PATH = "/all"; public static final String CREATE_ACCOUNT_PATH = "/create"; public static final String UPDATE_FIRSTNAME_PATH = "/update/firstName"; public static final String UPDATE_LASTNAME_PATH = "/update/lastName"; public static final String UPDATE_ACCOUNTNUMBER_PATH = "/update/accountNumber"; }
446
0.742152
0.742152
11
38.545456
29.71184
80
false
false
0
0
0
0
0
0
1.181818
false
false
4
b4d59c1e17c1c40ca91e52cde4f7b25f97c9666a
9,955,734,200,317
4359e1e3392d41527d16c00fb6b4b1235f0e6d67
/src/com/mac/bb4/display/CPUCanvas.java
5a6d0674b7fd9ce5f546df7dab7c71090bd568f9
[]
no_license
cwillison94/RRScheduler
https://github.com/cwillison94/RRScheduler
40325907c2cd8f21d8b32bb373904a98421e82f3
1aef31400cb2027c647b4d5a6c0de67e44c3952c
refs/heads/master
2016-09-06T14:05:49.986000
2015-04-28T02:38:04
2015-04-28T02:38:04
32,620,534
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.mac.bb4.display; import java.awt.Canvas; import java.awt.Color; import java.awt.Dimension; import java.awt.Font; import java.awt.FontMetrics; import java.awt.Graphics; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import javax.imageio.ImageIO; import com.mac.bb4.rrs.Process; public class CPUCanvas extends Canvas { /** * */ private static final long serialVersionUID = 1L; private Process process = null; private Font f1 = new Font("Helvetica", Font.BOLD, 20); // private Font f2 = new Font("Times",Font.ITALIC+Font.BOLD,24); private BufferedImage cpu; public CPUCanvas() { try { this.cpu = ImageIO.read(new File("images/cpu.jpg")); } catch (IOException e) { System.out.println("Image failed to load"); } } public void setProcess(Process p) { this.process = p; repaint(); } @Override public void paint(Graphics g) { Dimension dim = getSize(); if (cpu != null) { int w = cpu.getWidth(); int h = cpu.getHeight(); int x = (dim.width - w) / 2; int y = (dim.height - h) / 2; g.drawImage(cpu, x, y, this); } if (process != null) { String processTxt = "PID: " + process.getID(); g.setFont(f1); FontMetrics fm = g.getFontMetrics(); int w = fm.stringWidth(processTxt); int x = (dim.width - w) / 2; int y = dim.height / 2; int h = fm.getHeight(); g.drawString(processTxt, x, y); String tR = "T.R: " + process.getTimeRemaining(); fm = g.getFontMetrics(); w = fm.stringWidth(tR); x = (dim.width - w) / 2; g.drawString(tR, x, y+h); } } }
UTF-8
Java
1,600
java
CPUCanvas.java
Java
[]
null
[]
package com.mac.bb4.display; import java.awt.Canvas; import java.awt.Color; import java.awt.Dimension; import java.awt.Font; import java.awt.FontMetrics; import java.awt.Graphics; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import javax.imageio.ImageIO; import com.mac.bb4.rrs.Process; public class CPUCanvas extends Canvas { /** * */ private static final long serialVersionUID = 1L; private Process process = null; private Font f1 = new Font("Helvetica", Font.BOLD, 20); // private Font f2 = new Font("Times",Font.ITALIC+Font.BOLD,24); private BufferedImage cpu; public CPUCanvas() { try { this.cpu = ImageIO.read(new File("images/cpu.jpg")); } catch (IOException e) { System.out.println("Image failed to load"); } } public void setProcess(Process p) { this.process = p; repaint(); } @Override public void paint(Graphics g) { Dimension dim = getSize(); if (cpu != null) { int w = cpu.getWidth(); int h = cpu.getHeight(); int x = (dim.width - w) / 2; int y = (dim.height - h) / 2; g.drawImage(cpu, x, y, this); } if (process != null) { String processTxt = "PID: " + process.getID(); g.setFont(f1); FontMetrics fm = g.getFontMetrics(); int w = fm.stringWidth(processTxt); int x = (dim.width - w) / 2; int y = dim.height / 2; int h = fm.getHeight(); g.drawString(processTxt, x, y); String tR = "T.R: " + process.getTimeRemaining(); fm = g.getFontMetrics(); w = fm.stringWidth(tR); x = (dim.width - w) / 2; g.drawString(tR, x, y+h); } } }
1,600
0.6425
0.633125
77
19.779221
16.81575
65
false
false
0
0
0
0
0
0
1.974026
false
false
4
c80615c5a6908f42e00a3b235027320c5c2cbc90
27,900,107,615,365
c83a4638a11b87e016a2f1ffee60beacb69519a3
/task/src/test/java/NumberDecryptionTest.java
f55a93c1a381f920b80932de2bf79b2e1ad2599d
[]
no_license
ValeriaKudravec/decoder
https://github.com/ValeriaKudravec/decoder
b721f5b90ab32c4bd423ef37b6405ea511553532
f4a47cd7e538e2e7f21b19a31cb382c0a2f5d2c2
refs/heads/main
2023-02-17T12:40:22.602000
2021-01-18T22:45:43
2021-01-18T22:45:43
330,803,804
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import org.junit.Assert; import org.junit.Test; import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; public class NumberDecryptionTest { private static final String numberNameFile = "numbers_name.txt"; private static final String numberDigitFile = "numbers_digit.txt"; private static final String fileTest = "fileTest.txt"; @Test public void dataDriverTest(){ try (Scanner scanner = new Scanner(new File(fileTest))){ NumberDecryption numberDecryption = new NumberDecryption(); while (scanner.hasNextLine()){ String[] numbersLineArr = scanner.nextLine().split("-"); Assert.assertEquals(numbersLineArr[1].trim(), numberDecryption.decoding(new StringBuilder(numbersLineArr[0]), numberNameFile, numberDigitFile).trim()); } } catch (FileNotFoundException e) { e.printStackTrace(); } } }
UTF-8
Java
975
java
NumberDecryptionTest.java
Java
[]
null
[]
import org.junit.Assert; import org.junit.Test; import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; public class NumberDecryptionTest { private static final String numberNameFile = "numbers_name.txt"; private static final String numberDigitFile = "numbers_digit.txt"; private static final String fileTest = "fileTest.txt"; @Test public void dataDriverTest(){ try (Scanner scanner = new Scanner(new File(fileTest))){ NumberDecryption numberDecryption = new NumberDecryption(); while (scanner.hasNextLine()){ String[] numbersLineArr = scanner.nextLine().split("-"); Assert.assertEquals(numbersLineArr[1].trim(), numberDecryption.decoding(new StringBuilder(numbersLineArr[0]), numberNameFile, numberDigitFile).trim()); } } catch (FileNotFoundException e) { e.printStackTrace(); } } }
975
0.65641
0.654359
28
33.785713
30.62137
125
false
false
0
0
0
0
0
0
0.535714
false
false
4
d0f18aae00718b452649ca33fb81358dd5813301
498,216,211,886
489dbf038dc81578ee3d1f3465e10d2148a7d3d5
/name.martingeisse.slave-services/src/main/java/name/martingeisse/slave_services/papyros/frontend/template/CreateTemplatePage.java
7b06d496a205748f7ff8a3e34d518838a7f28d63
[ "MIT" ]
permissive
MartinGeisse/public
https://github.com/MartinGeisse/public
9b3360186be7953d2185608da883916622ec84e3
57b905485322222447187ae78a5a56bf3ce67900
refs/heads/master
2023-01-21T03:00:43.350000
2016-03-20T16:30:09
2016-03-20T16:30:09
4,472,103
1
0
NOASSERTION
false
2022-12-27T14:45:54
2012-05-28T15:56:16
2016-02-07T13:57:41
2022-12-27T14:45:51
127,438
2
0
18
Java
false
false
/** * Copyright (c) 2013 Martin Geisse * * This file is distributed under the terms of the MIT license. */ package name.martingeisse.slave_services.papyros.frontend.template; import name.martingeisse.slave_services.common.frontend.AbstractFrontendPage; import name.martingeisse.slave_services.entity.Template; import name.martingeisse.slave_services.entity.TemplateFamily; import name.martingeisse.slave_services.papyros.backend.PapyrosDataUtil; import name.martingeisse.slave_services.papyros.frontend.family.TemplateFamilyPage; import name.martingeisse.wicket.component.stdform.BeanStandardFormPanel; import org.apache.wicket.markup.html.form.FormComponent; import org.apache.wicket.markup.html.link.BookmarkablePageLink; import org.apache.wicket.model.Model; import org.apache.wicket.request.mapper.parameter.PageParameters; import com.mysema.query.QueryException; /** * This page allows the user to create a template family. */ public final class CreateTemplatePage extends AbstractFrontendPage { /** * the languageKeyComponent */ private final FormComponent<?> languageKeyComponent; /** * Constructor. * @param pageParameters the page parameters */ public CreateTemplatePage(PageParameters pageParameters) { final TemplateFamily family = PapyrosDataUtil.loadTemplateFamily(pageParameters); add(new BookmarkablePageLink<>("templateFamilyLink", TemplateFamilyPage.class, new PageParameters().add("key", family.getKey()))); BeanStandardFormPanel<Template> stdform = new BeanStandardFormPanel<Template>("stdform", Model.of(new Template()), true) { @Override protected void onSubmit() { Template template = getBean(); template.setTemplateFamilyId(family.getId()); template.setContent(""); try { template.insert(); } catch (QueryException e) { System.out.println(e); } if (template.getId() == null) { languageKeyComponent.error("could not create template"); } else { setResponsePage(TemplatePage.class, new PageParameters().add("key", family.getKey()).add("language", template.getLanguageKey())); } }; }; languageKeyComponent = stdform.addTextField("Language Key", "languageKey").setRequired().getFormComponent(); stdform.addSubmitButton(); add(stdform); } }
UTF-8
Java
2,271
java
CreateTemplatePage.java
Java
[ { "context": "/**\n * Copyright (c) 2013 Martin Geisse\n *\n * This file is distributed under the terms of", "end": 39, "score": 0.9998437762260437, "start": 26, "tag": "NAME", "value": "Martin Geisse" } ]
null
[]
/** * Copyright (c) 2013 <NAME> * * This file is distributed under the terms of the MIT license. */ package name.martingeisse.slave_services.papyros.frontend.template; import name.martingeisse.slave_services.common.frontend.AbstractFrontendPage; import name.martingeisse.slave_services.entity.Template; import name.martingeisse.slave_services.entity.TemplateFamily; import name.martingeisse.slave_services.papyros.backend.PapyrosDataUtil; import name.martingeisse.slave_services.papyros.frontend.family.TemplateFamilyPage; import name.martingeisse.wicket.component.stdform.BeanStandardFormPanel; import org.apache.wicket.markup.html.form.FormComponent; import org.apache.wicket.markup.html.link.BookmarkablePageLink; import org.apache.wicket.model.Model; import org.apache.wicket.request.mapper.parameter.PageParameters; import com.mysema.query.QueryException; /** * This page allows the user to create a template family. */ public final class CreateTemplatePage extends AbstractFrontendPage { /** * the languageKeyComponent */ private final FormComponent<?> languageKeyComponent; /** * Constructor. * @param pageParameters the page parameters */ public CreateTemplatePage(PageParameters pageParameters) { final TemplateFamily family = PapyrosDataUtil.loadTemplateFamily(pageParameters); add(new BookmarkablePageLink<>("templateFamilyLink", TemplateFamilyPage.class, new PageParameters().add("key", family.getKey()))); BeanStandardFormPanel<Template> stdform = new BeanStandardFormPanel<Template>("stdform", Model.of(new Template()), true) { @Override protected void onSubmit() { Template template = getBean(); template.setTemplateFamilyId(family.getId()); template.setContent(""); try { template.insert(); } catch (QueryException e) { System.out.println(e); } if (template.getId() == null) { languageKeyComponent.error("could not create template"); } else { setResponsePage(TemplatePage.class, new PageParameters().add("key", family.getKey()).add("language", template.getLanguageKey())); } }; }; languageKeyComponent = stdform.addTextField("Language Key", "languageKey").setRequired().getFormComponent(); stdform.addSubmitButton(); add(stdform); } }
2,264
0.761779
0.760018
64
34.484375
35.131001
134
false
false
0
0
0
0
0
0
2.015625
false
false
4
f90d31d71a136887f0edc65608ee77a6e9f7246a
33,698,313,460,610
a94df91a7d7e6d74028eb3ecd6fd6e6034d1cb33
/movieManage2.0/src/main/java/pers/swmmm/common/CustomRealm.java
67bfe3315646eae1c17384088c09b7396e2b0070
[]
no_license
swmmm/VideoManage
https://github.com/swmmm/VideoManage
8186d3787b708c62e153e42e5018eab6523143f1
4747e0d7e76b120b7bd8d351d0d68c32ba20e074
refs/heads/master
2020-08-03T01:20:31.630000
2019-10-22T00:34:26
2019-10-22T00:34:26
211,580,545
0
0
null
false
2021-01-21T00:26:03
2019-09-29T00:58:47
2019-10-22T00:35:46
2021-01-21T00:26:01
853
0
0
6
JavaScript
false
false
package pers.swmmm.common; import org.apache.shiro.authc.AuthenticationException; import org.apache.shiro.authc.AuthenticationInfo; import org.apache.shiro.authc.AuthenticationToken; import org.apache.shiro.authc.SimpleAuthenticationInfo; import org.apache.shiro.authz.AuthorizationInfo; import org.apache.shiro.realm.AuthorizingRealm; import org.apache.shiro.subject.PrincipalCollection; import pers.swmmm.po.Admin; public class CustomRealm extends AuthorizingRealm { @Override protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) { return null; } @Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException { String username = (String) authenticationToken.getPrincipal(); Admin admin = new Admin(1,"swm","123",1); if (admin==null){ return null; } SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(admin,admin.getPassword(),this.getName()); return info; } }
UTF-8
Java
1,111
java
CustomRealm.java
Java
[]
null
[]
package pers.swmmm.common; import org.apache.shiro.authc.AuthenticationException; import org.apache.shiro.authc.AuthenticationInfo; import org.apache.shiro.authc.AuthenticationToken; import org.apache.shiro.authc.SimpleAuthenticationInfo; import org.apache.shiro.authz.AuthorizationInfo; import org.apache.shiro.realm.AuthorizingRealm; import org.apache.shiro.subject.PrincipalCollection; import pers.swmmm.po.Admin; public class CustomRealm extends AuthorizingRealm { @Override protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) { return null; } @Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException { String username = (String) authenticationToken.getPrincipal(); Admin admin = new Admin(1,"swm","123",1); if (admin==null){ return null; } SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(admin,admin.getPassword(),this.getName()); return info; } }
1,111
0.743474
0.738974
30
35.033333
33.489784
130
false
false
0
0
0
0
0
0
0.666667
false
false
4
0e8840ca624c0f9ad99b67174b3abe52190823b7
22,686,017,314,163
1527d49a97859aa6545c230033309e7e451fcd7f
/app/src/main/java/ru/arink_group/deliveryapp/App.java
cf1b4a338fedae9258b21e4134c58ea9757c417e
[]
no_license
Swipesh/DeliveryApp-Burgx
https://github.com/Swipesh/DeliveryApp-Burgx
74d45c56b9c2f0a0bc8eea188697383d9b715a4f
105f0799d5ca336c9e0c94c9f92d0d8352430bc2
refs/heads/master
2020-03-25T17:47:36.285000
2018-08-08T10:11:17
2018-08-08T10:11:17
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package ru.arink_group.deliveryapp; import android.app.Application; import android.content.SharedPreferences; import java.util.UUID; import ru.arink_group.deliveryapp.presentation.di.component.AppComponent; import ru.arink_group.deliveryapp.presentation.di.component.DaggerAppComponent; import ru.arink_group.deliveryapp.presentation.di.module.AppModule; import ru.arink_group.deliveryapp.presentation.di.module.InteractorsModule; /** * Created by kirillvs on 06.10.17. */ public class App extends Application { private static String unigueID = null; private static final String PREF_UNIQ_ID = "PREF_UNIQ_ID"; public static final String DEVICE_NAME = "android"; public static final String APP_SHARED_PREF = "BOOKING FOOD SHARED PREF"; public static final String COMPANY_INFO = "COMPANY INFO"; private static AppComponent component; public static AppComponent getComponent() { return component; } public static String getCompanyId() { return "1"; } public static String getUUID() { return unigueID; } @Override public void onCreate() { super.onCreate(); component = buildComponent(); SharedPreferences sharedPreferences = this.getSharedPreferences(PREF_UNIQ_ID, App.MODE_PRIVATE); unigueID = sharedPreferences.getString(PREF_UNIQ_ID, null); if(unigueID == null) { unigueID = UUID.randomUUID().toString(); SharedPreferences.Editor editor = sharedPreferences.edit(); editor.putString(PREF_UNIQ_ID, unigueID); editor.apply(); } } protected AppComponent buildComponent() { return DaggerAppComponent.builder() .appModule(new AppModule(this)) .interactorsModule(new InteractorsModule()) .build(); } }
UTF-8
Java
1,856
java
App.java
Java
[ { "context": "on.di.module.InteractorsModule;\n\n/**\n * Created by kirillvs on 06.10.17.\n */\n\npublic class App extends Applic", "end": 461, "score": 0.9996802806854248, "start": 453, "tag": "USERNAME", "value": "kirillvs" } ]
null
[]
package ru.arink_group.deliveryapp; import android.app.Application; import android.content.SharedPreferences; import java.util.UUID; import ru.arink_group.deliveryapp.presentation.di.component.AppComponent; import ru.arink_group.deliveryapp.presentation.di.component.DaggerAppComponent; import ru.arink_group.deliveryapp.presentation.di.module.AppModule; import ru.arink_group.deliveryapp.presentation.di.module.InteractorsModule; /** * Created by kirillvs on 06.10.17. */ public class App extends Application { private static String unigueID = null; private static final String PREF_UNIQ_ID = "PREF_UNIQ_ID"; public static final String DEVICE_NAME = "android"; public static final String APP_SHARED_PREF = "BOOKING FOOD SHARED PREF"; public static final String COMPANY_INFO = "COMPANY INFO"; private static AppComponent component; public static AppComponent getComponent() { return component; } public static String getCompanyId() { return "1"; } public static String getUUID() { return unigueID; } @Override public void onCreate() { super.onCreate(); component = buildComponent(); SharedPreferences sharedPreferences = this.getSharedPreferences(PREF_UNIQ_ID, App.MODE_PRIVATE); unigueID = sharedPreferences.getString(PREF_UNIQ_ID, null); if(unigueID == null) { unigueID = UUID.randomUUID().toString(); SharedPreferences.Editor editor = sharedPreferences.edit(); editor.putString(PREF_UNIQ_ID, unigueID); editor.apply(); } } protected AppComponent buildComponent() { return DaggerAppComponent.builder() .appModule(new AppModule(this)) .interactorsModule(new InteractorsModule()) .build(); } }
1,856
0.68319
0.679418
63
28.460318
26.77527
104
false
false
0
0
0
0
0
0
0.460317
false
false
4
469b48ce8d8bf66e0a21252d290e024fafffa773
21,217,138,509,441
c3ac60dd4d1ba474666831cddf8c7e0a4dbe8b5e
/mobile/src/main/java/com/xinrong/web/AccountController.java
a294a8374dc0107a61461a1eecd74027409167b0
[]
no_license
happy6eve/p2p
https://github.com/happy6eve/p2p
a74d87827cb0b260292d0b8884b4f80fe52c2f49
37ff8706a6a8c96f2dafdcae73cca20c89f36c81
refs/heads/master
2018-04-06T23:22:11.850000
2016-11-27T06:19:54
2016-11-27T06:19:54
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.xinrong.web; import java.math.BigDecimal; import java.math.RoundingMode; import java.util.HashMap; import java.util.Map; import javax.annotation.Resource; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import com.xinrong.common.exception.BusinessException; import com.xinrong.constant.CommonConstant; import com.xinrong.constant.account.BusinessTypeEnum; import com.xinrong.constant.account.EnumRedis; import com.xinrong.entity.account.AccountDO; import com.xinrong.service.AccountInfoService; import com.xinrong.service.account.AccountService; import com.xinrong.service.account.OnlineRechargeService; import com.xinrong.service.account.OnlineTakeCashService; import com.xinrong.service.redis.RedisService; import com.xinrong.service.redis.RedislockCommonService; import com.xinrong.util.EnumError; import com.xinrong.web.vo.Message; import com.xinrong.web.vo.TopUpVO; import com.xinrong.web.vo.WithdrawalInfoVO; /** * 账户相关的 * * @author renjinbao */ @Controller public class AccountController { private final Logger logger = Logger.getLogger(AccountController.class); @Autowired AccountInfoService accountInfoService; @Resource private RedislockCommonService redislockCommonService; @Resource private OnlineTakeCashService onlineTakeCashSV; @Resource private RedisService redisService; @Autowired private AccountService accountSV; @Autowired private OnlineRechargeService onlineRechargeService; /** * @Title: changeWithdraw * @Description: TODO转可提现接口 * @param @param withdrawMoney * @param @param uid * @param @return * @return Map<String,Object> * @author kun * @date 2016年7月27日 上午10:20:01 * @throws */ @RequestMapping("account/changeWithdraw") @ResponseBody public Map<String, Object> changeWithdraw(BigDecimal withdrawMoney, Integer uid, Integer step) { Map<String, Object> message = null; AccountDO account = null; try { message = new HashMap<String, Object>(); if (uid == null || uid == 0) { message.put("r", EnumError.PARAMS_NULL.getCode()); message.put("msg", EnumError.PARAMS_NULL.getDesc()); return message; } if (step == null || step == 0) { message.put("r", EnumError.PARAMS_NULL.getCode()); message.put("msg", EnumError.PARAMS_NULL.getDesc()); return message; } // 获取个人账户的详细信息 account = accountSV.validateAccountState(uid); // 不可提现金额 BigDecimal disAvalCash = account.getDisabledcash().subtract(account.getWithdrawfrozen()); if (step == 1) { message.put("r", EnumError.OK.getCode()); message.put("msg", EnumError.OK.getDesc()); message.put("availablecash", account.getAvailablecash());// 账户余额 message.put("disAvalCash", disAvalCash);// 不可提现余额 message.put("factorage", CommonConstant.TRANSFER_CASH_RATE);// 手续费利率 return message; } if (withdrawMoney.compareTo(new BigDecimal(0)) <= 0) { message.put("r", EnumError.PARAMETER_NO.getCode()); message.put("msg", EnumError.PARAMETER_NO.getDesc()); return message; } if (withdrawMoney.compareTo(disAvalCash) > 0) { message.put("r", false); message.put("msg", "输入金额不能大于不可提现余额"); } else { BigDecimal fee = withdrawMoney.multiply(new BigDecimal(CommonConstant.TRANSFER_CASH_RATE)).setScale(2, RoundingMode.CEILING); onlineRechargeService.addTurnCashApply(withdrawMoney, fee, BusinessTypeEnum.C.toString(), uid); /** 转可提现后 可提现金额和不可提现金额 */ account = accountSV.validateAccountState(uid); BigDecimal cannotWithdrawDeposit = account.getDisabledcash().subtract(account.getWithdrawfrozen()); BigDecimal availAmount = account.getAvailablecash().subtract(account.getAvailablefrozen()); message.put("r", EnumError.OK.getCode()); message.put("msg", EnumError.OK.getDesc()); message.put("availablecash", availAmount); message.put("disAvalCash", cannotWithdrawDeposit); message.put("factorage", CommonConstant.TRANSFER_CASH_RATE); } } catch (Exception e) { e.printStackTrace(); message.put("r", EnumError.SYSTEM_BUSY.getCode()); message.put("msg", EnumError.SYSTEM_BUSY.getDesc()); return message; } return message; } /** * 根据用户id查询提现记录 * * @param pageIndex 页码 * @param pageSize 每页记录数 * @param uid 用户id * @return 提现记录集合 */ @ResponseBody @RequestMapping("account/myWithdrawRecord") public Message<WithdrawalInfoVO> querryWithdrawal(Integer pageIndex, Integer pageSize, Integer uid) { return accountInfoService.querryWithdrawal(pageIndex, pageSize, uid); } @RequestMapping("account/rechargeRecord") @ResponseBody public Message<TopUpVO> queryTopUp(Integer uid, Integer pageIndex, Integer pageSize) { return accountInfoService.queryTopUp(uid, pageIndex, pageSize); } /** * 根据用户id查询提现记录 * * @param pageIndex 页码 * @param pageSize 每页记录数 * @param uid 用户id * @return 提现记录集合 */ @ResponseBody @RequestMapping(value = "account/cancelWithdraw", method = RequestMethod.POST) public Map<String, Object> revokeWithdrawal(Integer id, Integer uid) { Map<String, Object> json = new HashMap<String, Object>(); try { String syncKey = CommonConstant.A_ORDER_INFO + id; if (!redislockCommonService.acquireLock(syncKey, 25)) { throw new BusinessException("该订单正在被操作,请稍后再试!"); } onlineTakeCashSV.revokeOnlineOrder(id, uid); json.put("r", EnumError.OK.getCode()); json.put("msg", EnumError.OK.getDesc()); } catch (BusinessException e) { logger.error("撤销提现出错:", e); json.put("r", EnumError.BUSINESS_EXCEPTION.getCode()); json.put("msg", e.getMsg()); } catch (Exception e) { logger.error("撤销提现出错:", e); json.put("r", EnumError.ERROR.getCode()); json.put("msg", EnumError.ERROR.getDesc()); } finally { redislockCommonService.releaseLock(CommonConstant.A_ORDER_INFO + id); redisService.del(EnumRedis.USERACCOUNTINFO.getValue() + uid); } return json; } }
UTF-8
Java
7,497
java
AccountController.java
Java
[ { "context": ".vo.WithdrawalInfoVO;\n\n/**\n * 账户相关的\n * \n * @author renjinbao\n */\n@Controller\npublic class AccountController {\n", "end": 1252, "score": 0.9990886449813843, "start": 1243, "tag": "USERNAME", "value": "renjinbao" }, { "context": "n\n * @return Map<String,Object>\n * @author kun\n * @date 2016年7月27日 上午10:20:01\n * @throws", "end": 2008, "score": 0.7093858122825623, "start": 2005, "tag": "NAME", "value": "kun" } ]
null
[]
package com.xinrong.web; import java.math.BigDecimal; import java.math.RoundingMode; import java.util.HashMap; import java.util.Map; import javax.annotation.Resource; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import com.xinrong.common.exception.BusinessException; import com.xinrong.constant.CommonConstant; import com.xinrong.constant.account.BusinessTypeEnum; import com.xinrong.constant.account.EnumRedis; import com.xinrong.entity.account.AccountDO; import com.xinrong.service.AccountInfoService; import com.xinrong.service.account.AccountService; import com.xinrong.service.account.OnlineRechargeService; import com.xinrong.service.account.OnlineTakeCashService; import com.xinrong.service.redis.RedisService; import com.xinrong.service.redis.RedislockCommonService; import com.xinrong.util.EnumError; import com.xinrong.web.vo.Message; import com.xinrong.web.vo.TopUpVO; import com.xinrong.web.vo.WithdrawalInfoVO; /** * 账户相关的 * * @author renjinbao */ @Controller public class AccountController { private final Logger logger = Logger.getLogger(AccountController.class); @Autowired AccountInfoService accountInfoService; @Resource private RedislockCommonService redislockCommonService; @Resource private OnlineTakeCashService onlineTakeCashSV; @Resource private RedisService redisService; @Autowired private AccountService accountSV; @Autowired private OnlineRechargeService onlineRechargeService; /** * @Title: changeWithdraw * @Description: TODO转可提现接口 * @param @param withdrawMoney * @param @param uid * @param @return * @return Map<String,Object> * @author kun * @date 2016年7月27日 上午10:20:01 * @throws */ @RequestMapping("account/changeWithdraw") @ResponseBody public Map<String, Object> changeWithdraw(BigDecimal withdrawMoney, Integer uid, Integer step) { Map<String, Object> message = null; AccountDO account = null; try { message = new HashMap<String, Object>(); if (uid == null || uid == 0) { message.put("r", EnumError.PARAMS_NULL.getCode()); message.put("msg", EnumError.PARAMS_NULL.getDesc()); return message; } if (step == null || step == 0) { message.put("r", EnumError.PARAMS_NULL.getCode()); message.put("msg", EnumError.PARAMS_NULL.getDesc()); return message; } // 获取个人账户的详细信息 account = accountSV.validateAccountState(uid); // 不可提现金额 BigDecimal disAvalCash = account.getDisabledcash().subtract(account.getWithdrawfrozen()); if (step == 1) { message.put("r", EnumError.OK.getCode()); message.put("msg", EnumError.OK.getDesc()); message.put("availablecash", account.getAvailablecash());// 账户余额 message.put("disAvalCash", disAvalCash);// 不可提现余额 message.put("factorage", CommonConstant.TRANSFER_CASH_RATE);// 手续费利率 return message; } if (withdrawMoney.compareTo(new BigDecimal(0)) <= 0) { message.put("r", EnumError.PARAMETER_NO.getCode()); message.put("msg", EnumError.PARAMETER_NO.getDesc()); return message; } if (withdrawMoney.compareTo(disAvalCash) > 0) { message.put("r", false); message.put("msg", "输入金额不能大于不可提现余额"); } else { BigDecimal fee = withdrawMoney.multiply(new BigDecimal(CommonConstant.TRANSFER_CASH_RATE)).setScale(2, RoundingMode.CEILING); onlineRechargeService.addTurnCashApply(withdrawMoney, fee, BusinessTypeEnum.C.toString(), uid); /** 转可提现后 可提现金额和不可提现金额 */ account = accountSV.validateAccountState(uid); BigDecimal cannotWithdrawDeposit = account.getDisabledcash().subtract(account.getWithdrawfrozen()); BigDecimal availAmount = account.getAvailablecash().subtract(account.getAvailablefrozen()); message.put("r", EnumError.OK.getCode()); message.put("msg", EnumError.OK.getDesc()); message.put("availablecash", availAmount); message.put("disAvalCash", cannotWithdrawDeposit); message.put("factorage", CommonConstant.TRANSFER_CASH_RATE); } } catch (Exception e) { e.printStackTrace(); message.put("r", EnumError.SYSTEM_BUSY.getCode()); message.put("msg", EnumError.SYSTEM_BUSY.getDesc()); return message; } return message; } /** * 根据用户id查询提现记录 * * @param pageIndex 页码 * @param pageSize 每页记录数 * @param uid 用户id * @return 提现记录集合 */ @ResponseBody @RequestMapping("account/myWithdrawRecord") public Message<WithdrawalInfoVO> querryWithdrawal(Integer pageIndex, Integer pageSize, Integer uid) { return accountInfoService.querryWithdrawal(pageIndex, pageSize, uid); } @RequestMapping("account/rechargeRecord") @ResponseBody public Message<TopUpVO> queryTopUp(Integer uid, Integer pageIndex, Integer pageSize) { return accountInfoService.queryTopUp(uid, pageIndex, pageSize); } /** * 根据用户id查询提现记录 * * @param pageIndex 页码 * @param pageSize 每页记录数 * @param uid 用户id * @return 提现记录集合 */ @ResponseBody @RequestMapping(value = "account/cancelWithdraw", method = RequestMethod.POST) public Map<String, Object> revokeWithdrawal(Integer id, Integer uid) { Map<String, Object> json = new HashMap<String, Object>(); try { String syncKey = CommonConstant.A_ORDER_INFO + id; if (!redislockCommonService.acquireLock(syncKey, 25)) { throw new BusinessException("该订单正在被操作,请稍后再试!"); } onlineTakeCashSV.revokeOnlineOrder(id, uid); json.put("r", EnumError.OK.getCode()); json.put("msg", EnumError.OK.getDesc()); } catch (BusinessException e) { logger.error("撤销提现出错:", e); json.put("r", EnumError.BUSINESS_EXCEPTION.getCode()); json.put("msg", e.getMsg()); } catch (Exception e) { logger.error("撤销提现出错:", e); json.put("r", EnumError.ERROR.getCode()); json.put("msg", EnumError.ERROR.getDesc()); } finally { redislockCommonService.releaseLock(CommonConstant.A_ORDER_INFO + id); redisService.del(EnumRedis.USERACCOUNTINFO.getValue() + uid); } return json; } }
7,497
0.626444
0.623243
192
36.421875
28.5667
138
false
false
0
0
0
0
0
0
0.760417
false
false
4
863dc795f475cfbe2ac231670b5d3b0c0acb14d2
16,784,732,256,891
710e573995f9804dc56ac9067e345a7c927b79f7
/src/main/java/edu/matc/entity/placesInfo/Poi.java
aa01abb687a3a011fc14b9ea240b089fba69cc9b
[]
no_license
jtschiss/PizzaGenerator
https://github.com/jtschiss/PizzaGenerator
94d3340850e5ed069e92253b7329501f567ee86d
ff6ccc20c2cd3cb62fbd8f36ebd19b306195a01e
refs/heads/master
2023-01-31T23:04:08.438000
2020-12-17T01:18:55
2020-12-17T01:18:55
296,122,886
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package edu.matc.entity.placesInfo; import java.util.List; import com.fasterxml.jackson.annotation.JsonProperty; /** * The type Poi. */ public class Poi{ @JsonProperty("classifications") private List<ClassificationsItem> classifications; @JsonProperty("phone") private String phone; @JsonProperty("name") private String name; @JsonProperty("categories") private List<String> categories; @JsonProperty("categorySet") private List<CategorySetItem> categorySet; @JsonProperty("brands") private List<BrandsItem> brands; @JsonProperty("url") private String url; /** * Set classifications. * * @param classifications the classifications */ public void setClassifications(List<ClassificationsItem> classifications){ this.classifications = classifications; } /** * Get classifications list. * * @return the list */ public List<ClassificationsItem> getClassifications(){ return classifications; } /** * Set phone. * * @param phone the phone */ public void setPhone(String phone){ this.phone = phone; } /** * Get phone string. * * @return the string */ public String getPhone(){ return phone; } /** * Set name. * * @param name the name */ public void setName(String name){ this.name = name; } /** * Get name string. * * @return the string */ public String getName(){ return name; } /** * Set categories. * * @param categories the categories */ public void setCategories(List<String> categories){ this.categories = categories; } /** * Get categories list. * * @return the list */ public List<String> getCategories(){ return categories; } /** * Set category set. * * @param categorySet the category set */ public void setCategorySet(List<CategorySetItem> categorySet){ this.categorySet = categorySet; } /** * Get category set list. * * @return the list */ public List<CategorySetItem> getCategorySet(){ return categorySet; } /** * Set brands. * * @param brands the brands */ public void setBrands(List<BrandsItem> brands){ this.brands = brands; } /** * Get brands list. * * @return the list */ public List<BrandsItem> getBrands(){ return brands; } /** * Set url. * * @param url the url */ public void setUrl(String url){ this.url = url; } /** * Get url string. * * @return the string */ public String getUrl(){ return url; } @Override public String toString(){ return "Poi{" + "classifications = '" + classifications + '\'' + ",phone = '" + phone + '\'' + ",name = '" + name + '\'' + ",categories = '" + categories + '\'' + ",categorySet = '" + categorySet + '\'' + ",brands = '" + brands + '\'' + ",url = '" + url + '\'' + "}"; } }
UTF-8
Java
2,785
java
Poi.java
Java
[]
null
[]
package edu.matc.entity.placesInfo; import java.util.List; import com.fasterxml.jackson.annotation.JsonProperty; /** * The type Poi. */ public class Poi{ @JsonProperty("classifications") private List<ClassificationsItem> classifications; @JsonProperty("phone") private String phone; @JsonProperty("name") private String name; @JsonProperty("categories") private List<String> categories; @JsonProperty("categorySet") private List<CategorySetItem> categorySet; @JsonProperty("brands") private List<BrandsItem> brands; @JsonProperty("url") private String url; /** * Set classifications. * * @param classifications the classifications */ public void setClassifications(List<ClassificationsItem> classifications){ this.classifications = classifications; } /** * Get classifications list. * * @return the list */ public List<ClassificationsItem> getClassifications(){ return classifications; } /** * Set phone. * * @param phone the phone */ public void setPhone(String phone){ this.phone = phone; } /** * Get phone string. * * @return the string */ public String getPhone(){ return phone; } /** * Set name. * * @param name the name */ public void setName(String name){ this.name = name; } /** * Get name string. * * @return the string */ public String getName(){ return name; } /** * Set categories. * * @param categories the categories */ public void setCategories(List<String> categories){ this.categories = categories; } /** * Get categories list. * * @return the list */ public List<String> getCategories(){ return categories; } /** * Set category set. * * @param categorySet the category set */ public void setCategorySet(List<CategorySetItem> categorySet){ this.categorySet = categorySet; } /** * Get category set list. * * @return the list */ public List<CategorySetItem> getCategorySet(){ return categorySet; } /** * Set brands. * * @param brands the brands */ public void setBrands(List<BrandsItem> brands){ this.brands = brands; } /** * Get brands list. * * @return the list */ public List<BrandsItem> getBrands(){ return brands; } /** * Set url. * * @param url the url */ public void setUrl(String url){ this.url = url; } /** * Get url string. * * @return the string */ public String getUrl(){ return url; } @Override public String toString(){ return "Poi{" + "classifications = '" + classifications + '\'' + ",phone = '" + phone + '\'' + ",name = '" + name + '\'' + ",categories = '" + categories + '\'' + ",categorySet = '" + categorySet + '\'' + ",brands = '" + brands + '\'' + ",url = '" + url + '\'' + "}"; } }
2,785
0.628366
0.628366
171
15.292397
15.695826
75
false
false
0
0
0
0
0
0
1.192982
false
false
4
18ef42a92475d8ed0de6f1228a094327d86a017f
15,049,565,462,154
4e61d154c6e1af22acf811630cf2921e0f1153bc
/src/prng/MultiplyWithCarry.java
3426014e63111b2acb2671c5d2b6c397c80814aa
[]
no_license
drmatthewclark/RedBox
https://github.com/drmatthewclark/RedBox
893898872c20ad1615a5e6cf8fe4c3e6d0b89370
0a4882d213cf83b2c47b6239001e69855ca012e5
refs/heads/master
2021-06-24T04:22:37.287000
2020-12-29T20:27:55
2020-12-29T20:27:55
163,201,163
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package prng; /** * multiply with carry algorithm for pseudo random numbers * * @author CLARKM * */ public class MultiplyWithCarry extends ExtendedRandom { /** * */ private static final long multiplier = 0xffffda61L; /** * provide the next random bits * * @param bits - requested bits, ranges from 1 to 32 */ public final int nextInt() { long s = seedToLong(); s = (multiplier * (s & 0xffffffffL)) + (s >>> 32); setSeed(s); return (int)(s >>> 32); } }
UTF-8
Java
521
java
MultiplyWithCarry.java
Java
[ { "context": "gorithm for pseudo random numbers\r\n * \r\n * @author CLARKM\r\n *\r\n */\r\npublic class MultiplyWithCarry extends ", "end": 104, "score": 0.999476432800293, "start": 98, "tag": "USERNAME", "value": "CLARKM" } ]
null
[]
package prng; /** * multiply with carry algorithm for pseudo random numbers * * @author CLARKM * */ public class MultiplyWithCarry extends ExtendedRandom { /** * */ private static final long multiplier = 0xffffda61L; /** * provide the next random bits * * @param bits - requested bits, ranges from 1 to 32 */ public final int nextInt() { long s = seedToLong(); s = (multiplier * (s & 0xffffffffL)) + (s >>> 32); setSeed(s); return (int)(s >>> 32); } }
521
0.587332
0.566219
30
15.366667
19.448193
58
false
false
0
0
0
0
0
0
0.866667
false
false
4
83e6e5b6f903271f2c2a4312a4b779f9d0a43640
22,454,089,025,605
dab3a1a9b5066ca4af8fb95c66139a04da210c8e
/gitrest/api/src/main/java/git/gitrest/api/dto/TopicsDTO.java
3c4e2c520a9a15cb203985c50b23fe0dcea7fb97
[]
no_license
marocz/gitrest
https://github.com/marocz/gitrest
617681d253dfb2c93040b5df522c201859c5f60c
cbbd27b51bb149d6f3e2f7ae050696a0c41bbca4
refs/heads/master
2023-04-17T21:37:22.981000
2021-05-04T00:49:01
2021-05-04T00:49:01
357,289,367
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package git.gitrest.api.dto; import java.util.List; public class TopicsDTO { public int getTotalcount() { return totalcount; } public void setTotalcount(int totalcount) { this.totalcount = totalcount; } public boolean isIncompleteresults() { return incompleteresults; } public void setIncompleteresults(boolean incompleteresults) { this.incompleteresults = incompleteresults; } public List<Items> getItems() { return items; } public void setItems(List<Items> items) { this.items = items; } private int totalcount; private boolean incompleteresults; private List<Items> items; static public class Items{ public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDisplayname() { return displayname; } public void setDisplayname(String displayname) { this.displayname = displayname; } public String getShortdescription() { return shortdescription; } public void setShortdescription(String shortdescription) { this.shortdescription = shortdescription; } public String getDescription() { return description; } public void setDescription(String getShortdescription) { this.description = getShortdescription; } public String getCreatedby() { return createdby; } public void setCreatedby(String createdby) { this.createdby = createdby; } public String getReleased() { return released; } public void setReleased(String released) { this.released = released; } public String getCreatedat() { return createdat; } public void setCreatedat(String createdat) { this.createdat = createdat; } public String getUpdatedat() { return updatedat; } public void setUpdatedat(String updatedat) { this.updatedat = updatedat; } public boolean isFeatured() { return featured; } public void setFeatured(boolean featured) { this.featured = featured; } public boolean isCurated() { return curated; } public void setCurated(boolean curated) { this.curated = curated; } public Long getScore() { return score; } public void setScore(Long score) { this.score = score; } private String name; private String displayname; private String shortdescription; private String description; private String createdby; private String released; private String createdat; private String updatedat; private boolean featured; private boolean curated; private Long score; } }
UTF-8
Java
3,134
java
TopicsDTO.java
Java
[]
null
[]
package git.gitrest.api.dto; import java.util.List; public class TopicsDTO { public int getTotalcount() { return totalcount; } public void setTotalcount(int totalcount) { this.totalcount = totalcount; } public boolean isIncompleteresults() { return incompleteresults; } public void setIncompleteresults(boolean incompleteresults) { this.incompleteresults = incompleteresults; } public List<Items> getItems() { return items; } public void setItems(List<Items> items) { this.items = items; } private int totalcount; private boolean incompleteresults; private List<Items> items; static public class Items{ public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDisplayname() { return displayname; } public void setDisplayname(String displayname) { this.displayname = displayname; } public String getShortdescription() { return shortdescription; } public void setShortdescription(String shortdescription) { this.shortdescription = shortdescription; } public String getDescription() { return description; } public void setDescription(String getShortdescription) { this.description = getShortdescription; } public String getCreatedby() { return createdby; } public void setCreatedby(String createdby) { this.createdby = createdby; } public String getReleased() { return released; } public void setReleased(String released) { this.released = released; } public String getCreatedat() { return createdat; } public void setCreatedat(String createdat) { this.createdat = createdat; } public String getUpdatedat() { return updatedat; } public void setUpdatedat(String updatedat) { this.updatedat = updatedat; } public boolean isFeatured() { return featured; } public void setFeatured(boolean featured) { this.featured = featured; } public boolean isCurated() { return curated; } public void setCurated(boolean curated) { this.curated = curated; } public Long getScore() { return score; } public void setScore(Long score) { this.score = score; } private String name; private String displayname; private String shortdescription; private String description; private String createdby; private String released; private String createdat; private String updatedat; private boolean featured; private boolean curated; private Long score; } }
3,134
0.574346
0.574346
139
21.546762
18.553141
66
false
false
0
0
0
0
0
0
0.316547
false
false
4
a1b98d575affca016c2f5e4fad558c2fa6aeb51f
30,983,894,105,082
f4e4e3c6be5bb2eabf4e5948a0255edd80ccec08
/test/toleco/unit/.svn/text-base/UnitTest.java.svn-base
9adeaf4c3a9dabc816e0fb35b7bebe6a1619cc1c
[]
no_license
jmoorman/Toleco
https://github.com/jmoorman/Toleco
52bd57126e776355a91f796bbef58dc3f916c6e6
0b8a2abf704ccfead243b7d87ea7fca49b77ff08
refs/heads/master
2021-01-12T09:04:27.782000
2016-12-18T00:20:02
2016-12-18T00:20:02
76,754,623
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/** * * @author eralston */ package toleco.unit; import toleco.unit.ArmorType; import toleco.unit.AttackType; import toleco.unit.Unit; import toleco.controller.Player; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; public class UnitTest { public UnitTest() { } @BeforeClass public static void setUpClass() throws Exception { } @AfterClass public static void tearDownClass() throws Exception { } @Before public void setUp() { } @After public void tearDown() { } @Test public void takeDamageTest() { Unit un = new Unit("Test",Player.kPlayer1, 10, 10, 2, 2, AttackType.kMaul, 10, 1, ArmorType.kBone, 10, true); un.takeDamage(1); assertEquals(9, un.getCurrentHealth()); un.takeDamage(2); assertEquals(7, un.getCurrentHealth()); un.takeDamage(100); assertEquals(0, un.getCurrentHealth()); } @Test public void canAttackTest() { Unit un = new Unit("Test",Player.kPlayer1, 10, 10, 2, 2, AttackType.kMaul, 10, 1, ArmorType.kBone, 10, true); assertTrue(un.canAttack()); un.useAttack(); assertFalse(un.canAttack()); } @Test public void decrementMoveTest() { Unit un = new Unit("Test",Player.kPlayer1, 10, 10, 2, 2, AttackType.kMaul, 10, 1, ArmorType.kBone, 10, true); un.decrementMove(1); assertEquals(1, un.getCurrentMoves()); } @Test public void resetTest() { Unit un = new Unit("Test",Player.kPlayer1, 10, 10, 2, 2, AttackType.kMaul, 10, 1, ArmorType.kBone, 10, true); un.useAttack(); un.decrementMove(5); un.reset(); assertTrue(un.canAttack()); assertEquals(un.getMaxMoves(), un.getCurrentMoves()); } @Test public void toStringTest() { String out = "Test\nHealth: 10/10\nMoves: 2/2\nAttack Value: "+ "10\nAttack Range: 1\nArmor Value: 10"; Unit un = new Unit("Test",Player.kPlayer1, 10, 10, 2, 2, AttackType.kMaul, 10, 1, ArmorType.kBone, 10, true); assertEquals(out, un.toString()); } @Test public void toStringForFileTest() { Unit un = new Unit("Test",Player.kPlayer1, 10, 10, 2, 2, AttackType.kMaul, 10, 1, ArmorType.kBone, 10, true); String out = "Test,kPlayer1,10,2,true"; assertEquals(out, un.toStringForFile()); } @Test public void gettersTest() { Unit un = new Unit("Test",Player.kPlayer1, 10, 10, 2, 2, AttackType.kMaul, 10, 1, ArmorType.kBone, 10, true); assertEquals(10, un.getMaxHealth()); assertEquals("Test", un.getType()); assertEquals(Player.kPlayer1, un.getOwner()); assertEquals(AttackType.kMaul, un.getAttackType()); assertEquals(ArmorType.kBone, un.getArmorType()); } }
UTF-8
Java
3,072
UnitTest.java.svn-base
Java
[ { "context": "/**\n *\n * @author eralston\n */\n\npackage toleco.unit;\n\nimport toleco.unit.Arm", "end": 26, "score": 0.996702253818512, "start": 18, "tag": "USERNAME", "value": "eralston" } ]
null
[]
/** * * @author eralston */ package toleco.unit; import toleco.unit.ArmorType; import toleco.unit.AttackType; import toleco.unit.Unit; import toleco.controller.Player; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; public class UnitTest { public UnitTest() { } @BeforeClass public static void setUpClass() throws Exception { } @AfterClass public static void tearDownClass() throws Exception { } @Before public void setUp() { } @After public void tearDown() { } @Test public void takeDamageTest() { Unit un = new Unit("Test",Player.kPlayer1, 10, 10, 2, 2, AttackType.kMaul, 10, 1, ArmorType.kBone, 10, true); un.takeDamage(1); assertEquals(9, un.getCurrentHealth()); un.takeDamage(2); assertEquals(7, un.getCurrentHealth()); un.takeDamage(100); assertEquals(0, un.getCurrentHealth()); } @Test public void canAttackTest() { Unit un = new Unit("Test",Player.kPlayer1, 10, 10, 2, 2, AttackType.kMaul, 10, 1, ArmorType.kBone, 10, true); assertTrue(un.canAttack()); un.useAttack(); assertFalse(un.canAttack()); } @Test public void decrementMoveTest() { Unit un = new Unit("Test",Player.kPlayer1, 10, 10, 2, 2, AttackType.kMaul, 10, 1, ArmorType.kBone, 10, true); un.decrementMove(1); assertEquals(1, un.getCurrentMoves()); } @Test public void resetTest() { Unit un = new Unit("Test",Player.kPlayer1, 10, 10, 2, 2, AttackType.kMaul, 10, 1, ArmorType.kBone, 10, true); un.useAttack(); un.decrementMove(5); un.reset(); assertTrue(un.canAttack()); assertEquals(un.getMaxMoves(), un.getCurrentMoves()); } @Test public void toStringTest() { String out = "Test\nHealth: 10/10\nMoves: 2/2\nAttack Value: "+ "10\nAttack Range: 1\nArmor Value: 10"; Unit un = new Unit("Test",Player.kPlayer1, 10, 10, 2, 2, AttackType.kMaul, 10, 1, ArmorType.kBone, 10, true); assertEquals(out, un.toString()); } @Test public void toStringForFileTest() { Unit un = new Unit("Test",Player.kPlayer1, 10, 10, 2, 2, AttackType.kMaul, 10, 1, ArmorType.kBone, 10, true); String out = "Test,kPlayer1,10,2,true"; assertEquals(out, un.toStringForFile()); } @Test public void gettersTest() { Unit un = new Unit("Test",Player.kPlayer1, 10, 10, 2, 2, AttackType.kMaul, 10, 1, ArmorType.kBone, 10, true); assertEquals(10, un.getMaxHealth()); assertEquals("Test", un.getType()); assertEquals(Player.kPlayer1, un.getOwner()); assertEquals(AttackType.kMaul, un.getAttackType()); assertEquals(ArmorType.kBone, un.getArmorType()); } }
3,072
0.593099
0.556315
116
25.491379
23.452629
82
false
false
0
0
0
0
0
0
1.172414
false
false
4
42513c037dede2e29aa2106ea11822ee2afec6ef
6,244,882,468,005
08dc21aa1938134f669968699d892a8e102388c0
/bistro/src/main/java/com/qingyang/bistro/fragments/HomeFragment.java
68b6d83b73536a52503cb70f9229f904942307a1
[]
no_license
yangqing0314/QiaoLePei
https://github.com/yangqing0314/QiaoLePei
3b68c1a51d71a01a688850587fbc8e930e8a27d7
b6faa6e00b13836fcc59149a3cfe519c21861669
refs/heads/master
2016-09-06T08:48:19.332000
2015-10-22T11:04:04
2015-10-22T11:04:04
42,060,217
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.qingyang.bistro.fragments; import android.view.LayoutInflater; import android.view.View; import android.widget.TextView; import butterknife.InjectView; import com.qingyang.bannerlibrary.ui.widget.scrollviewpager.CBViewHolderCreator; import com.qingyang.bannerlibrary.ui.widget.scrollviewpager.ConvenientBanner; import com.qingyang.bistro.R; import com.qingyang.bistro.ui.wdiget.NetworkImageHolderView; import java.util.Arrays; import java.util.List; /** * Created by QingYang on 15/9/8. */ public class HomeFragment extends BaseFragment{ @InjectView(R.id.mBannerView) ConvenientBanner mBannerView; @InjectView(R.id.tv_top_bar_title) TextView mTvTitle; private List<String> networkImages; private String[] images = {"http://img2.imgtn.bdimg.com/it/u=3093785514,1341050958&fm=21&gp=0.jpg", "http://img2.3lian.com/2014/f2/37/d/40.jpg", "http://d.3987.com/sqmy_131219/001.jpg", "http://img2.3lian.com/2014/f2/37/d/39.jpg", "http://www.8kmm.com/UploadFiles/2012/8/201208140920132659.jpg", "http://f.hiphotos.baidu.com/image/h%3D200/sign=1478eb74d5a20cf45990f9df460b4b0c/d058ccbf6c81800a5422e5fdb43533fa838b4779.jpg", "http://f.hiphotos.baidu.com/image/pic/item/09fa513d269759ee50f1971ab6fb43166c22dfba.jpg" }; @Override protected View getContentView(LayoutInflater inflater) { return inflater.inflate(R.layout.fragment_home, null); } @Override protected void initView() { super.initView(); mTvTitle.setText("首页"); } @Override protected void initEvents() { super.initEvents(); } @Override protected void onloadData() { super.onloadData(); initBanner(); } private void initBanner() { networkImages = Arrays.asList(images); mBannerView.setPages(new CBViewHolderCreator() { @Override public Object createHolder() { return new NetworkImageHolderView(); } }, networkImages).setPageIndicator(new int[] {R.mipmap.ic_page_indicator, R.mipmap.ic_page_indicator_focused}).setPageTransformer( ConvenientBanner.Transformer.DefaultTransformer); } @Override public void onResume() { super.onResume(); //开始自动翻页 mBannerView.startTurning(5000); } @Override public void onPause() { super.onPause(); //停止翻页 mBannerView.stopTurning(); } }
UTF-8
Java
2,494
java
HomeFragment.java
Java
[ { "context": ".Arrays;\nimport java.util.List;\n\n/**\n * Created by QingYang on 15/9/8.\n */\npublic class HomeFragment extends ", "end": 490, "score": 0.9984707832336426, "start": 482, "tag": "NAME", "value": "QingYang" } ]
null
[]
package com.qingyang.bistro.fragments; import android.view.LayoutInflater; import android.view.View; import android.widget.TextView; import butterknife.InjectView; import com.qingyang.bannerlibrary.ui.widget.scrollviewpager.CBViewHolderCreator; import com.qingyang.bannerlibrary.ui.widget.scrollviewpager.ConvenientBanner; import com.qingyang.bistro.R; import com.qingyang.bistro.ui.wdiget.NetworkImageHolderView; import java.util.Arrays; import java.util.List; /** * Created by QingYang on 15/9/8. */ public class HomeFragment extends BaseFragment{ @InjectView(R.id.mBannerView) ConvenientBanner mBannerView; @InjectView(R.id.tv_top_bar_title) TextView mTvTitle; private List<String> networkImages; private String[] images = {"http://img2.imgtn.bdimg.com/it/u=3093785514,1341050958&fm=21&gp=0.jpg", "http://img2.3lian.com/2014/f2/37/d/40.jpg", "http://d.3987.com/sqmy_131219/001.jpg", "http://img2.3lian.com/2014/f2/37/d/39.jpg", "http://www.8kmm.com/UploadFiles/2012/8/201208140920132659.jpg", "http://f.hiphotos.baidu.com/image/h%3D200/sign=1478eb74d5a20cf45990f9df460b4b0c/d058ccbf6c81800a5422e5fdb43533fa838b4779.jpg", "http://f.hiphotos.baidu.com/image/pic/item/09fa513d269759ee50f1971ab6fb43166c22dfba.jpg" }; @Override protected View getContentView(LayoutInflater inflater) { return inflater.inflate(R.layout.fragment_home, null); } @Override protected void initView() { super.initView(); mTvTitle.setText("首页"); } @Override protected void initEvents() { super.initEvents(); } @Override protected void onloadData() { super.onloadData(); initBanner(); } private void initBanner() { networkImages = Arrays.asList(images); mBannerView.setPages(new CBViewHolderCreator() { @Override public Object createHolder() { return new NetworkImageHolderView(); } }, networkImages).setPageIndicator(new int[] {R.mipmap.ic_page_indicator, R.mipmap.ic_page_indicator_focused}).setPageTransformer( ConvenientBanner.Transformer.DefaultTransformer); } @Override public void onResume() { super.onResume(); //开始自动翻页 mBannerView.startTurning(5000); } @Override public void onPause() { super.onPause(); //停止翻页 mBannerView.stopTurning(); } }
2,494
0.681781
0.614575
73
32.835617
30.548866
139
false
false
0
0
0
0
84
0.034008
0.520548
false
false
4
e91d68ef2c7c44e75cc803a7c1a43eae26567e91
10,368,051,080,437
bf0d59dfda49b5e6fa44a68053c556317b3485a4
/dao-abstract/src/main/java/jm/api/dao/ThreadChannelMessageDAO.java
eb1cb117a6780b91c012aeb8afc9e1a43e7ed50d
[]
no_license
NikitaNesterenko/JM-SYSTEM-MESSAGE
https://github.com/NikitaNesterenko/JM-SYSTEM-MESSAGE
e8d668de695e350b61c302aa544020504a4e37ad
6c919b8531156416789c2e7edb161bc9c5900d0a
refs/heads/dev
2022-07-04T05:02:55.805000
2020-06-22T16:10:32
2020-06-22T16:10:32
211,087,068
12
18
null
false
2022-06-21T02:09:22
2019-09-26T12:46:29
2021-09-28T18:20:22
2022-06-21T02:09:21
11,787
5
9
52
Java
false
false
package jm.api.dao; import jm.model.ThreadChannel; import jm.model.message.ThreadChannelMessage; import java.util.List; public interface ThreadChannelMessageDAO { void persist(ThreadChannelMessage threadChannelMessage); List<ThreadChannelMessage> getAll(); List<ThreadChannelMessage> findAllThreadChannelMessagesByThreadChannel(ThreadChannel threadChannel); List<ThreadChannelMessage> findAllThreadChannelMessagesByThreadChannelId(Long id); }
UTF-8
Java
466
java
ThreadChannelMessageDAO.java
Java
[]
null
[]
package jm.api.dao; import jm.model.ThreadChannel; import jm.model.message.ThreadChannelMessage; import java.util.List; public interface ThreadChannelMessageDAO { void persist(ThreadChannelMessage threadChannelMessage); List<ThreadChannelMessage> getAll(); List<ThreadChannelMessage> findAllThreadChannelMessagesByThreadChannel(ThreadChannel threadChannel); List<ThreadChannelMessage> findAllThreadChannelMessagesByThreadChannelId(Long id); }
466
0.828326
0.828326
17
26.411764
31.704628
104
false
false
0
0
0
0
0
0
0.470588
false
false
4
147353dd87f1e800bba7b9d153781d4db2c7c073
24,481,313,605,447
9222d5b5f7df76c42946af73082172f3d1c2b68e
/src/shopping/service/ProductServices.java
5a8c730819609096093772c5a61665083970eb74
[]
no_license
Rawjyot/ShoppingCartApp
https://github.com/Rawjyot/ShoppingCartApp
a428abec0cf9c37c565033be1f1e01cb0ee6837f
71371e660791514bf234187a632f1374c279953f
refs/heads/master
2020-12-30T18:02:58.865000
2017-05-11T06:51:01
2017-05-11T06:51:01
90,946,771
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package shopping.service; import shopping.domain.Product; import java.io.File; import java.util.List; /** * Created by rawjyot on 2/1/17. */ public interface ProductServices { public List<Product> getProductDetails(); public void addProduct(Product product); public void addProduct(File file); public void deleteProduct(int id); public void updateProduct(int id,Product product); }
UTF-8
Java
409
java
ProductServices.java
Java
[ { "context": "io.File;\nimport java.util.List;\n\n/**\n * Created by rawjyot on 2/1/17.\n */\npublic interface ProductServices {", "end": 130, "score": 0.9996734261512756, "start": 123, "tag": "USERNAME", "value": "rawjyot" } ]
null
[]
package shopping.service; import shopping.domain.Product; import java.io.File; import java.util.List; /** * Created by rawjyot on 2/1/17. */ public interface ProductServices { public List<Product> getProductDetails(); public void addProduct(Product product); public void addProduct(File file); public void deleteProduct(int id); public void updateProduct(int id,Product product); }
409
0.735941
0.726161
19
20.526316
18.394417
54
false
false
0
0
0
0
0
0
0.526316
false
false
4
7f71927469c3b22e69f8677af46f4e9ab5ffe969
3,899,830,329,387
df6a417ed0976e3fc9c55153b0a06f0b9e81d9c2
/src/main/java/barrosmelo/projeto/equipe1/domain/service/IProfessorService.java
24825fd29d6e31c0fe7b46b35e4401a58266e571
[]
no_license
RafaBrito7/Projeto-AESO_Sistema-Escola-XYZ
https://github.com/RafaBrito7/Projeto-AESO_Sistema-Escola-XYZ
dab63777ed9a633bd23008ef48a97c1e99af2670
6d901a9ca89b26fccccb6598a81a1581c7fcf6e3
refs/heads/master
2023-01-15T18:31:13.429000
2020-11-26T23:29:23
2020-11-26T23:29:23
297,802,718
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package barrosmelo.projeto.equipe1.domain.service; import barrosmelo.projeto.equipe1.domain.model.Professor; public interface IProfessorService { public Professor salvar(Professor professor); public void excluir(Long idProfessor); public Professor verificarExistencia(Long id); }
UTF-8
Java
288
java
IProfessorService.java
Java
[]
null
[]
package barrosmelo.projeto.equipe1.domain.service; import barrosmelo.projeto.equipe1.domain.model.Professor; public interface IProfessorService { public Professor salvar(Professor professor); public void excluir(Long idProfessor); public Professor verificarExistencia(Long id); }
288
0.822917
0.815972
12
23
23.352373
57
false
false
0
0
0
0
0
0
0.666667
false
false
4
b381ae3c91abc84de9fb6a2d4074d5c97bdb5d18
30,502,857,786,433
152d2b75637733d179b05cc87fcc64d18db23025
/src/ve/net/dcs/model/MHTEndowmentEmployee.java
0ea55024680d2934880092bcd210a692c0ae4a98
[]
no_license
wjvasquezb/humantalent
https://github.com/wjvasquezb/humantalent
6fed92cc0398a95099907199dd5cd61d63d4c5d0
c5f06ad45c40c86a18dd2afed1dd59882ca86ff5
refs/heads/master
2023-01-08T07:32:25.254000
2020-01-16T16:21:59
2020-01-16T16:21:59
311,749,775
0
2
null
false
2020-11-10T19:51:44
2020-11-10T18:28:50
2020-11-10T18:29:11
2020-11-10T19:50:06
5,822
0
0
1
Java
false
false
package ve.net.dcs.model; import java.sql.ResultSet; import java.util.Properties; public class MHTEndowmentEmployee extends X_HT_EndowmentEmployee { private static final long serialVersionUID = 1832301413821658878L; public MHTEndowmentEmployee(Properties ctx, int HT_EndowmentEmployee_ID, String trxName) { super(ctx, HT_EndowmentEmployee_ID, trxName); } public MHTEndowmentEmployee(Properties ctx, ResultSet rs, String trxName) { super(ctx, rs, trxName); } }
UTF-8
Java
475
java
MHTEndowmentEmployee.java
Java
[]
null
[]
package ve.net.dcs.model; import java.sql.ResultSet; import java.util.Properties; public class MHTEndowmentEmployee extends X_HT_EndowmentEmployee { private static final long serialVersionUID = 1832301413821658878L; public MHTEndowmentEmployee(Properties ctx, int HT_EndowmentEmployee_ID, String trxName) { super(ctx, HT_EndowmentEmployee_ID, trxName); } public MHTEndowmentEmployee(Properties ctx, ResultSet rs, String trxName) { super(ctx, rs, trxName); } }
475
0.787368
0.747368
18
25.388889
30.072392
91
false
false
0
0
0
0
0
0
1.277778
false
false
4
c871c94dc54d44b5a1e2308cd227dfffa2b82254
24,137,716,233,424
3ed2ff1609197f68ed757f52718a0e691f6d78e4
/src/main/java/com/rhcloud/msdm/conference/domain/UserFactory.java
aa3b1e622e7b53835338284056a268f68acf48ba
[]
no_license
makskovalko/TeamProjectOPP
https://github.com/makskovalko/TeamProjectOPP
1a328d4f166b0c1c2c195019f7a8eb708a0f65d7
217400871fb887cde2f347d809eec6a7231a352f
refs/heads/master
2021-01-10T07:50:42.086000
2015-10-27T08:37:39
2015-10-27T08:37:39
42,999,405
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.rhcloud.msdm.conference.domain; import com.rhcloud.msdm.conference.domain.entities.Organizer; import com.rhcloud.msdm.conference.domain.entities.Participant; import com.rhcloud.msdm.conference.domain.entities.Speaker; import com.rhcloud.msdm.conference.domain.entities.User; public class UserFactory { public static User getUserByType(User user) { switch (user.getUserType()) { case "participant": return new Participant(user); case "speaker": return new Speaker(user); case "organizer": return new Organizer(user); } return null; } }
UTF-8
Java
632
java
UserFactory.java
Java
[]
null
[]
package com.rhcloud.msdm.conference.domain; import com.rhcloud.msdm.conference.domain.entities.Organizer; import com.rhcloud.msdm.conference.domain.entities.Participant; import com.rhcloud.msdm.conference.domain.entities.Speaker; import com.rhcloud.msdm.conference.domain.entities.User; public class UserFactory { public static User getUserByType(User user) { switch (user.getUserType()) { case "participant": return new Participant(user); case "speaker": return new Speaker(user); case "organizer": return new Organizer(user); } return null; } }
632
0.69462
0.69462
17
35.294117
23.90118
63
false
false
0
0
0
0
0
0
0.529412
false
false
4
ee875aa1f60eb97c1643f4db192ddb29553bbe13
31,739,808,318,306
3a5985651d77a31437cfdac25e594087c27e93d6
/ojc-core/component-common/bpelmodel/src/com/sun/bpel/model/Pick.java
daede61fcab711ad5c3c7be8c1f73e37f5dfa9d2
[]
no_license
vitalif/openesb-components
https://github.com/vitalif/openesb-components
a37d62133d81edb3fdc091abd5c1d72dbe2fc736
560910d2a1fdf31879e3d76825edf079f76812c7
refs/heads/master
2023-09-04T14:40:55.665000
2016-01-25T13:12:22
2016-01-25T13:12:33
48,222,841
0
5
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * BEGIN_HEADER - DO NOT EDIT * * The contents of this file are subject to the terms * of the Common Development and Distribution License * (the "License"). You may not use this file except * in compliance with the License. * * You can obtain a copy of the license at * https://open-jbi-components.dev.java.net/public/CDDLv1.0.html. * See the License for the specific language governing * permissions and limitations under the License. * * When distributing Covered Code, include this CDDL * HEADER in each file and include the License file at * https://open-jbi-components.dev.java.net/public/CDDLv1.0.html. * If applicable add the following below this CDDL HEADER, * with the fields enclosed by brackets "[]" replaced with * your own identifying information: Portions Copyright * [year] [name of copyright owner] */ /* * @(#)Pick.java * * Copyright 2004-2007 Sun Microsystems, Inc. All Rights Reserved. * * END_HEADER - DO NOT EDIT */ package com.sun.bpel.model; import java.util.Collection; import com.sun.bpel.xml.common.model.XMLNode; /** * Describes the &lt;pick&gt; element. * * @author Sun Microsystems * @version */ public interface Pick extends Activity { /** Tag for this element. */ public static final String TAG = Tags.PICK; /** Describes the attributes of this element. */ public interface ATTR extends Activity.ATTR { /** "createInstance" attribute token */ public static final String CREATE_INSTANCE = "createInstance"; } /** Ordinal position of createInstance attribute */ public static final int CREATE_INSTANCE = NUM_STANDARD_ATTRS; /** Total number of attributes */ public static final int NUM_ATTRS = CREATE_INSTANCE + 1; /** Getter for createInstance attribute. * @return Value of createInstance attribute. */ String getCreateInstance(); /** Setter for createInstance attribute. * @param c Value of createInstance attribute. */ void setCreateInstance(String c); /** Indexed getter for the onMessage sub-element. * @param i Index to onMessage sub-element. * @return onMessage sub-element. */ OnMessage getOnMessage(int i); /** Setter for the onMessage sub-element. * @param i Index to onMessage sub-element. * @param o onMessage sub-element. */ void setOnMessage(int i, OnMessage o); /** Adds a onMessage sub-element. * @param o onMessage sub-element. */ void addOnMessage(OnMessage o); /** Inserts onMessage element at given index within list; pushes all elements after to the right. * @param i Index to insert onMessage at. * @param o onMessage element to insert. */ void addOnMessage(int i, OnMessage o); /** Removes all the onMessage elements within the list. */ void clearOnMessages(); /** Removes a onMessage sub-element. * @param i Index to onMessage sub-element. */ void removeOnMessage(int i); /** Removes a onMessage sub-element. * @param o onMessage sub-element to remove. * @return <code>true</code> if successfully removed. */ boolean removeOnMessage(OnMessage o); /** Getter for the number of onMessage sub-elements there are. * @return Size of list. */ int getOnMessageSize(); /** Index of onMessage element within list. * @param onMsg onMessage element to index * @return Index (0-based) of element. */ int indexOfOnMessage(XMLNode onMsg); /** Gets collection of onMessage elements. * @return Unmodifiable collection of onMessage elements. */ Collection getOnMessages(); /** Indexed getter for the onAlarm sub-element. * @param i Index to onAlarm sub-element. * @return onAlarm sub-element. */ OnAlarm getOnAlarm(int i); /** Setter for the onAlarm sub-element. * @param i Index to onAlarm sub-element. * @param o onAlarm sub-element. */ void setOnAlarm(int i, OnAlarm o); /** Adds a onAlarm sub-element. * @param o onAlarm sub-element. */ void addOnAlarm(OnAlarm o); /** Inserts onAlarm element at given index within list; pushes all elements after to the right. * @param i Index to insert onAlarm at. * @param o onAlarm element to insert. */ void addOnAlarm(int i, OnAlarm o); /** Removes all the onAlarm elements within the list. */ void clearOnAlarms(); /** Removes a onAlarm sub-element. * @param i Index to onAlarm sub-element. */ void removeOnAlarm(int i); /** Removes a onAlarm sub-element. * @param o onAlarm sub-element to remove. * @return <code>true</code> if successfully removed. */ boolean removeOnAlarm(OnAlarm o); /** Getter for the number of onAlarm sub-elements there are. * @return Size of list. */ int getOnAlarmSize(); /** Index of onAlarm element within list. * @param onAlarm onAlarm element to index * @return Index (0-based) of element. */ int indexOfOnAlarm(XMLNode onAlarm); /** Gets collection of onAlarm elements. * @return Unmodifiable collection of onAlarm elements. */ Collection getOnAlarms(); }
UTF-8
Java
5,421
java
Pick.java
Java
[]
null
[]
/* * BEGIN_HEADER - DO NOT EDIT * * The contents of this file are subject to the terms * of the Common Development and Distribution License * (the "License"). You may not use this file except * in compliance with the License. * * You can obtain a copy of the license at * https://open-jbi-components.dev.java.net/public/CDDLv1.0.html. * See the License for the specific language governing * permissions and limitations under the License. * * When distributing Covered Code, include this CDDL * HEADER in each file and include the License file at * https://open-jbi-components.dev.java.net/public/CDDLv1.0.html. * If applicable add the following below this CDDL HEADER, * with the fields enclosed by brackets "[]" replaced with * your own identifying information: Portions Copyright * [year] [name of copyright owner] */ /* * @(#)Pick.java * * Copyright 2004-2007 Sun Microsystems, Inc. All Rights Reserved. * * END_HEADER - DO NOT EDIT */ package com.sun.bpel.model; import java.util.Collection; import com.sun.bpel.xml.common.model.XMLNode; /** * Describes the &lt;pick&gt; element. * * @author Sun Microsystems * @version */ public interface Pick extends Activity { /** Tag for this element. */ public static final String TAG = Tags.PICK; /** Describes the attributes of this element. */ public interface ATTR extends Activity.ATTR { /** "createInstance" attribute token */ public static final String CREATE_INSTANCE = "createInstance"; } /** Ordinal position of createInstance attribute */ public static final int CREATE_INSTANCE = NUM_STANDARD_ATTRS; /** Total number of attributes */ public static final int NUM_ATTRS = CREATE_INSTANCE + 1; /** Getter for createInstance attribute. * @return Value of createInstance attribute. */ String getCreateInstance(); /** Setter for createInstance attribute. * @param c Value of createInstance attribute. */ void setCreateInstance(String c); /** Indexed getter for the onMessage sub-element. * @param i Index to onMessage sub-element. * @return onMessage sub-element. */ OnMessage getOnMessage(int i); /** Setter for the onMessage sub-element. * @param i Index to onMessage sub-element. * @param o onMessage sub-element. */ void setOnMessage(int i, OnMessage o); /** Adds a onMessage sub-element. * @param o onMessage sub-element. */ void addOnMessage(OnMessage o); /** Inserts onMessage element at given index within list; pushes all elements after to the right. * @param i Index to insert onMessage at. * @param o onMessage element to insert. */ void addOnMessage(int i, OnMessage o); /** Removes all the onMessage elements within the list. */ void clearOnMessages(); /** Removes a onMessage sub-element. * @param i Index to onMessage sub-element. */ void removeOnMessage(int i); /** Removes a onMessage sub-element. * @param o onMessage sub-element to remove. * @return <code>true</code> if successfully removed. */ boolean removeOnMessage(OnMessage o); /** Getter for the number of onMessage sub-elements there are. * @return Size of list. */ int getOnMessageSize(); /** Index of onMessage element within list. * @param onMsg onMessage element to index * @return Index (0-based) of element. */ int indexOfOnMessage(XMLNode onMsg); /** Gets collection of onMessage elements. * @return Unmodifiable collection of onMessage elements. */ Collection getOnMessages(); /** Indexed getter for the onAlarm sub-element. * @param i Index to onAlarm sub-element. * @return onAlarm sub-element. */ OnAlarm getOnAlarm(int i); /** Setter for the onAlarm sub-element. * @param i Index to onAlarm sub-element. * @param o onAlarm sub-element. */ void setOnAlarm(int i, OnAlarm o); /** Adds a onAlarm sub-element. * @param o onAlarm sub-element. */ void addOnAlarm(OnAlarm o); /** Inserts onAlarm element at given index within list; pushes all elements after to the right. * @param i Index to insert onAlarm at. * @param o onAlarm element to insert. */ void addOnAlarm(int i, OnAlarm o); /** Removes all the onAlarm elements within the list. */ void clearOnAlarms(); /** Removes a onAlarm sub-element. * @param i Index to onAlarm sub-element. */ void removeOnAlarm(int i); /** Removes a onAlarm sub-element. * @param o onAlarm sub-element to remove. * @return <code>true</code> if successfully removed. */ boolean removeOnAlarm(OnAlarm o); /** Getter for the number of onAlarm sub-elements there are. * @return Size of list. */ int getOnAlarmSize(); /** Index of onAlarm element within list. * @param onAlarm onAlarm element to index * @return Index (0-based) of element. */ int indexOfOnAlarm(XMLNode onAlarm); /** Gets collection of onAlarm elements. * @return Unmodifiable collection of onAlarm elements. */ Collection getOnAlarms(); }
5,421
0.641764
0.638996
179
29.284916
22.489286
101
false
false
0
0
0
0
0
0
0.223464
false
false
4
9e83380784f7aabfe78b15014e4d26b47c8fe2da
22,969,485,128,361
7a99b6a3e8798210e2585f5e99696a7ba4e177a1
/kstore_market_plug/src/main/java/com/ningpai/grab/service/impl/GrabTreasureServiceImpl.java
d1055df1eb0dbec1c31e9066b278097eff24297e
[]
no_license
xuxiaowei007/yangyanshu
https://github.com/xuxiaowei007/yangyanshu
fa106d54057900af8e5d0519fb00d6e15c45763e
352b8f9316128ff0f062ad5cff117461674311ae
refs/heads/master
2020-03-21T19:37:43.074000
2017-06-19T07:33:41
2017-06-19T07:33:41
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.ningpai.grab.service.impl; import com.ningpai.grab.dao.GrabPeriodMapper; import com.ningpai.grab.bean.GrabTreasure; import com.ningpai.grab.dao.GrabTicketMapper; import com.ningpai.grab.dao.GrabTreasureMapper; import com.ningpai.grab.service.GrabPeriodService; import com.ningpai.grab.service.GrabTicketService; import com.ningpai.grab.service.GrabTreasureService; import com.ningpai.grab.util.GrabSearchBean; import com.ningpai.grab.vo.GrabTreasureDetailVo; import com.ningpai.util.MapUtil; import com.ningpai.util.MyLogger; import com.ningpai.util.PageBean; import com.ningpai.util.StringUtil; import org.apache.commons.codec.binary.StringUtils; import org.apache.commons.collections.map.HashedMap; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import javax.annotation.Resource; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.*; /** * @author zhangzhongqiang 一元夺宝ServiceImpl * @since 2016年12月26日上午10:53:47 */ @Service("GrabTreasureService") public class GrabTreasureServiceImpl implements GrabTreasureService { @Autowired private GrabTreasureMapper grabTreasureMapper; @Autowired private GrabPeriodMapper grabPeriodMapper; @Autowired private GrabTicketMapper grabTicketMapper; @Autowired private GrabTicketService grabTicketService; @Resource(name = "GrabPeriodService") private GrabPeriodService grabPeriodService; private static final String START = "start"; private static final String STATUS = "status"; private static final String NUMBER = "number"; private static final String SORT = "sort"; private static final String ORDER = "order"; private static final String DATETIME = "yyyy-MM-dd HH:mm:ss"; private static final MyLogger LOGGER = new MyLogger(GrabTreasureServiceImpl.class); /** * 分页查询夺宝数据 * * @param pageBean 分页参数 * @param grabSearchBeane 查询参数 * @return 查询到的数据 */ @Override public PageBean grabTreasureList(PageBean pageBean, GrabSearchBean grabSearchBeane) { Map<String, Object> paramMap = MapUtil.getParamsMap(grabSearchBeane); // 查询总数 pageBean.setRows(grabTreasureMapper.queryTotalGrabTreasureListByPage(paramMap)); // 计算分页 Integer no = pageBean.getRows() % pageBean.getPageSize() == 0 ? pageBean.getRows() / pageBean.getPageSize() : (pageBean.getRows() / pageBean.getPageSize() + 1); if (no == 0) { no = 1; } try { if (pageBean.getPageNo() >= no) { pageBean.setPageNo(no); pageBean.setStartRowNum((no - 1) * pageBean.getPageSize()); pageBean.setObjectBean(grabSearchBeane); } // 查询条件封装 paramMap.put(START, pageBean.getStartRowNum()); paramMap.put(NUMBER, pageBean.getEndRowNum()); // 查询列表页 pageBean.setList(grabTreasureMapper.queryGrabTreasureListByPage(paramMap)); } catch (Exception e) { LOGGER.error(e.getMessage()); } return pageBean; } /** * 查询夺宝详细数据 * * @return 查询到的数据 */ @Override public PageBean queryGrabDetailForMobile(PageBean pageBean, Long typeId, String sort, String order, String title) { Map<String, Object> paramMap = new HashedMap(); pageBean.setPageSize(10); // 查询总数 if (typeId != null) { paramMap.put("typeId", typeId); } if (title != null) { //pc端设置展示条数 if(title.equals("pc")){ pageBean.setPageSize(12); }else{ paramMap.put("title", title); } } paramMap.put("nowTime",new Date()); pageBean.setRows(grabTreasureMapper.queryTotalGrabDetailForMobile(paramMap)); int no = 0; // 计算分页 try { // 查询条件封装 if ((sort == null || sort.equals("") )&& (order == null || order.equals(""))) { sort = "1"; //默认按人气排序 order = "2"; //倒序 } //pc端分页排序 if(null!=sort&& !"".equals(sort)){ if(sort.equals("5D")) paramMap.put(STATUS, 1); //排序 if(sort.equals("1D")){ order="2"; }else if(sort.equals("11D")){ order="1"; }else if(sort.equals("2D")){ order="2"; }else if(sort.equals("22D")){ order="1"; }else if(sort.equals("3D")){ order="2"; }else if(sort.equals("33D")){ order="1"; }else if(sort.equals("4D")){ order="2"; }else if(sort.equals("44D")){ order="1"; } if(sort.equals("1D")){ sort="1"; }else if(sort.equals("2D")){ sort="2"; }else if(sort.equals("3D")){ sort="3"; }else if(sort.equals("4D")){ sort="4"; }else if(sort.equals("11D")){ sort="1"; }else if(sort.equals("22D")){ sort="2"; }else if(sort.equals("33D")){ sort="3"; }else if(sort.equals("44D")){ sort="4"; } } // no = pageBean.getRows() % pageBean.getPageSize() == 0 ? pageBean.getRows() / pageBean.getPageSize() : (pageBean.getRows() / pageBean.getPageSize() + 1); // no = no == 0 ? 1 : no; // // 若页码超过最大页码 则显示最后一个 // if (pageBean.getPageNo() >= no) { // pageBean.setPageNo(no); // pageBean.setStartRowNum((no - 1) * pageBean.getPageSize()); // } paramMap.put(START, (pageBean.getPageNo()-1)*pageBean.getPageSize()); paramMap.put(NUMBER, pageBean.getPageSize()); paramMap.put(SORT, sort); paramMap.put(ORDER, order); // 查询列表页 pageBean.setList(grabTreasureMapper.queryDetailsForMobile(paramMap)); } catch (Exception e) { LOGGER.error(e.getMessage()); } return pageBean; } /** * 获得即将揭晓的夺宝 * * @return */ @Override public List<GrabTreasureDetailVo> getWillBeRevealed(PageBean pageBean) { Map<String, Object> paramMap = new HashedMap(); paramMap.put(START, (pageBean.getPageNo()-1)*pageBean.getPageSize()); paramMap.put(NUMBER, pageBean.getPageSize()); return grabTreasureMapper.getWillBeRevealed(paramMap); } /** * 添加和更新一元夺宝 * * @param grabTreasure * @param sTime 开始时间 * @param actionFlag 操作标识, 0 :插入,1:更新 * @return 执行数量 */ @Override @Transactional public int doActionGrabTreasure(GrabTreasure grabTreasure, String sTime, String actionFlag) { SimpleDateFormat formatDate = new SimpleDateFormat(DATETIME); try { // 起始日期 grabTreasure.setStartTime(formatDate.parse(sTime)); // 终止日期 } catch (ParseException e) { LOGGER.error("添加夺宝时转换时间错误:" + e); } if (actionFlag != null && actionFlag.equals("0")) { grabTreasure.setCreateTime(new Date()); grabTreasure.setModTime(new Date()); grabTreasure.setDelFlag("0"); int result = grabTreasureMapper.insertGrabTreasure(grabTreasure); if (result == 1) { //默认添加一条该夺宝期数数据 return grabPeriodService.genNext(grabTreasure.getGrabTreasureId(), grabTreasure.getGrabTreasureShare(),grabTreasure.getStartTime()); } return result; } else { GrabTreasure newGrabTreasure = grabTreasureMapper.queryGrabTreasureById(grabTreasure.getGrabTreasureId()); Long grabTreasureShare = newGrabTreasure.getGrabTreasureShare(); newGrabTreasure.setGrabTreasureName(grabTreasure.getGrabTreasureName()); newGrabTreasure.setGrabTreasureShare(grabTreasure.getGrabTreasureShare()); newGrabTreasure.setSingleShare(grabTreasure.getSingleShare()); newGrabTreasure.setStartTime(grabTreasure.getStartTime()); newGrabTreasure.setModTime(new Date()); newGrabTreasure.setStageNum(grabTreasure.getStageNum()); newGrabTreasure.setRemark(grabTreasure.getRemark()); grabTreasureMapper.updateGrabTreasure(newGrabTreasure); //如果夺宝份额修改后,先删除券码再重新插入 if (grabTreasureShare != grabTreasure.getGrabTreasureShare()) { Long periodId = grabPeriodMapper.selectByGrabId(newGrabTreasure.getGrabTreasureId()).get(0).getPeriodId(); grabTicketMapper.deleteByPeriodId(periodId); grabTicketService.genGrabTicket(periodId, newGrabTreasure.getGrabTreasureShare()); } return 1; } } /** * 增加期数 * * @param grabId 夺宝id * @param stageNum 增加的期数 */ @Override @Transactional public void addStageNum(Long grabId, Long stageNum) { Map<String, Object> paramMap = new HashedMap(); paramMap.put("grabId", grabId); paramMap.put("stageNum", stageNum); grabTreasureMapper.addStageNum(paramMap); } /** * 判断夺宝活动是否结束 * * @param grabId * @return */ @Override public boolean checkGrabIsEnd(Long grabId) { return grabTreasureMapper.checkGrabIsEnd(grabId); } /** * 校验夺宝活动能否删除 * * @param grabId * @return */ @Override public boolean checkGrabCanDelete(Long grabId) { return grabTreasureMapper.checkGrabCanDelete(grabId); } @Override @Transactional public int deleteGrabByIds(String[] grabIds) { Integer count = 0; Map<String, Object> paramMap = new HashMap<String, Object>(); try { paramMap.put("grabId", grabIds); count = grabTreasureMapper.deleteGrabByIds(paramMap); grabPeriodMapper.deletePeriodByIds(paramMap); grabTicketMapper.deleteByGrabIds(paramMap); } finally { paramMap = null; } return count; } }
UTF-8
Java
11,045
java
GrabTreasureServiceImpl.java
Java
[ { "context": "pleDateFormat;\nimport java.util.*;\n\n/**\n * @author zhangzhongqiang 一元夺宝ServiceImpl\n * @since 2016年12月26日上午10:53:47\n ", "end": 1043, "score": 0.8592868447303772, "start": 1028, "tag": "NAME", "value": "zhangzhongqiang" } ]
null
[]
package com.ningpai.grab.service.impl; import com.ningpai.grab.dao.GrabPeriodMapper; import com.ningpai.grab.bean.GrabTreasure; import com.ningpai.grab.dao.GrabTicketMapper; import com.ningpai.grab.dao.GrabTreasureMapper; import com.ningpai.grab.service.GrabPeriodService; import com.ningpai.grab.service.GrabTicketService; import com.ningpai.grab.service.GrabTreasureService; import com.ningpai.grab.util.GrabSearchBean; import com.ningpai.grab.vo.GrabTreasureDetailVo; import com.ningpai.util.MapUtil; import com.ningpai.util.MyLogger; import com.ningpai.util.PageBean; import com.ningpai.util.StringUtil; import org.apache.commons.codec.binary.StringUtils; import org.apache.commons.collections.map.HashedMap; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import javax.annotation.Resource; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.*; /** * @author zhangzhongqiang 一元夺宝ServiceImpl * @since 2016年12月26日上午10:53:47 */ @Service("GrabTreasureService") public class GrabTreasureServiceImpl implements GrabTreasureService { @Autowired private GrabTreasureMapper grabTreasureMapper; @Autowired private GrabPeriodMapper grabPeriodMapper; @Autowired private GrabTicketMapper grabTicketMapper; @Autowired private GrabTicketService grabTicketService; @Resource(name = "GrabPeriodService") private GrabPeriodService grabPeriodService; private static final String START = "start"; private static final String STATUS = "status"; private static final String NUMBER = "number"; private static final String SORT = "sort"; private static final String ORDER = "order"; private static final String DATETIME = "yyyy-MM-dd HH:mm:ss"; private static final MyLogger LOGGER = new MyLogger(GrabTreasureServiceImpl.class); /** * 分页查询夺宝数据 * * @param pageBean 分页参数 * @param grabSearchBeane 查询参数 * @return 查询到的数据 */ @Override public PageBean grabTreasureList(PageBean pageBean, GrabSearchBean grabSearchBeane) { Map<String, Object> paramMap = MapUtil.getParamsMap(grabSearchBeane); // 查询总数 pageBean.setRows(grabTreasureMapper.queryTotalGrabTreasureListByPage(paramMap)); // 计算分页 Integer no = pageBean.getRows() % pageBean.getPageSize() == 0 ? pageBean.getRows() / pageBean.getPageSize() : (pageBean.getRows() / pageBean.getPageSize() + 1); if (no == 0) { no = 1; } try { if (pageBean.getPageNo() >= no) { pageBean.setPageNo(no); pageBean.setStartRowNum((no - 1) * pageBean.getPageSize()); pageBean.setObjectBean(grabSearchBeane); } // 查询条件封装 paramMap.put(START, pageBean.getStartRowNum()); paramMap.put(NUMBER, pageBean.getEndRowNum()); // 查询列表页 pageBean.setList(grabTreasureMapper.queryGrabTreasureListByPage(paramMap)); } catch (Exception e) { LOGGER.error(e.getMessage()); } return pageBean; } /** * 查询夺宝详细数据 * * @return 查询到的数据 */ @Override public PageBean queryGrabDetailForMobile(PageBean pageBean, Long typeId, String sort, String order, String title) { Map<String, Object> paramMap = new HashedMap(); pageBean.setPageSize(10); // 查询总数 if (typeId != null) { paramMap.put("typeId", typeId); } if (title != null) { //pc端设置展示条数 if(title.equals("pc")){ pageBean.setPageSize(12); }else{ paramMap.put("title", title); } } paramMap.put("nowTime",new Date()); pageBean.setRows(grabTreasureMapper.queryTotalGrabDetailForMobile(paramMap)); int no = 0; // 计算分页 try { // 查询条件封装 if ((sort == null || sort.equals("") )&& (order == null || order.equals(""))) { sort = "1"; //默认按人气排序 order = "2"; //倒序 } //pc端分页排序 if(null!=sort&& !"".equals(sort)){ if(sort.equals("5D")) paramMap.put(STATUS, 1); //排序 if(sort.equals("1D")){ order="2"; }else if(sort.equals("11D")){ order="1"; }else if(sort.equals("2D")){ order="2"; }else if(sort.equals("22D")){ order="1"; }else if(sort.equals("3D")){ order="2"; }else if(sort.equals("33D")){ order="1"; }else if(sort.equals("4D")){ order="2"; }else if(sort.equals("44D")){ order="1"; } if(sort.equals("1D")){ sort="1"; }else if(sort.equals("2D")){ sort="2"; }else if(sort.equals("3D")){ sort="3"; }else if(sort.equals("4D")){ sort="4"; }else if(sort.equals("11D")){ sort="1"; }else if(sort.equals("22D")){ sort="2"; }else if(sort.equals("33D")){ sort="3"; }else if(sort.equals("44D")){ sort="4"; } } // no = pageBean.getRows() % pageBean.getPageSize() == 0 ? pageBean.getRows() / pageBean.getPageSize() : (pageBean.getRows() / pageBean.getPageSize() + 1); // no = no == 0 ? 1 : no; // // 若页码超过最大页码 则显示最后一个 // if (pageBean.getPageNo() >= no) { // pageBean.setPageNo(no); // pageBean.setStartRowNum((no - 1) * pageBean.getPageSize()); // } paramMap.put(START, (pageBean.getPageNo()-1)*pageBean.getPageSize()); paramMap.put(NUMBER, pageBean.getPageSize()); paramMap.put(SORT, sort); paramMap.put(ORDER, order); // 查询列表页 pageBean.setList(grabTreasureMapper.queryDetailsForMobile(paramMap)); } catch (Exception e) { LOGGER.error(e.getMessage()); } return pageBean; } /** * 获得即将揭晓的夺宝 * * @return */ @Override public List<GrabTreasureDetailVo> getWillBeRevealed(PageBean pageBean) { Map<String, Object> paramMap = new HashedMap(); paramMap.put(START, (pageBean.getPageNo()-1)*pageBean.getPageSize()); paramMap.put(NUMBER, pageBean.getPageSize()); return grabTreasureMapper.getWillBeRevealed(paramMap); } /** * 添加和更新一元夺宝 * * @param grabTreasure * @param sTime 开始时间 * @param actionFlag 操作标识, 0 :插入,1:更新 * @return 执行数量 */ @Override @Transactional public int doActionGrabTreasure(GrabTreasure grabTreasure, String sTime, String actionFlag) { SimpleDateFormat formatDate = new SimpleDateFormat(DATETIME); try { // 起始日期 grabTreasure.setStartTime(formatDate.parse(sTime)); // 终止日期 } catch (ParseException e) { LOGGER.error("添加夺宝时转换时间错误:" + e); } if (actionFlag != null && actionFlag.equals("0")) { grabTreasure.setCreateTime(new Date()); grabTreasure.setModTime(new Date()); grabTreasure.setDelFlag("0"); int result = grabTreasureMapper.insertGrabTreasure(grabTreasure); if (result == 1) { //默认添加一条该夺宝期数数据 return grabPeriodService.genNext(grabTreasure.getGrabTreasureId(), grabTreasure.getGrabTreasureShare(),grabTreasure.getStartTime()); } return result; } else { GrabTreasure newGrabTreasure = grabTreasureMapper.queryGrabTreasureById(grabTreasure.getGrabTreasureId()); Long grabTreasureShare = newGrabTreasure.getGrabTreasureShare(); newGrabTreasure.setGrabTreasureName(grabTreasure.getGrabTreasureName()); newGrabTreasure.setGrabTreasureShare(grabTreasure.getGrabTreasureShare()); newGrabTreasure.setSingleShare(grabTreasure.getSingleShare()); newGrabTreasure.setStartTime(grabTreasure.getStartTime()); newGrabTreasure.setModTime(new Date()); newGrabTreasure.setStageNum(grabTreasure.getStageNum()); newGrabTreasure.setRemark(grabTreasure.getRemark()); grabTreasureMapper.updateGrabTreasure(newGrabTreasure); //如果夺宝份额修改后,先删除券码再重新插入 if (grabTreasureShare != grabTreasure.getGrabTreasureShare()) { Long periodId = grabPeriodMapper.selectByGrabId(newGrabTreasure.getGrabTreasureId()).get(0).getPeriodId(); grabTicketMapper.deleteByPeriodId(periodId); grabTicketService.genGrabTicket(periodId, newGrabTreasure.getGrabTreasureShare()); } return 1; } } /** * 增加期数 * * @param grabId 夺宝id * @param stageNum 增加的期数 */ @Override @Transactional public void addStageNum(Long grabId, Long stageNum) { Map<String, Object> paramMap = new HashedMap(); paramMap.put("grabId", grabId); paramMap.put("stageNum", stageNum); grabTreasureMapper.addStageNum(paramMap); } /** * 判断夺宝活动是否结束 * * @param grabId * @return */ @Override public boolean checkGrabIsEnd(Long grabId) { return grabTreasureMapper.checkGrabIsEnd(grabId); } /** * 校验夺宝活动能否删除 * * @param grabId * @return */ @Override public boolean checkGrabCanDelete(Long grabId) { return grabTreasureMapper.checkGrabCanDelete(grabId); } @Override @Transactional public int deleteGrabByIds(String[] grabIds) { Integer count = 0; Map<String, Object> paramMap = new HashMap<String, Object>(); try { paramMap.put("grabId", grabIds); count = grabTreasureMapper.deleteGrabByIds(paramMap); grabPeriodMapper.deletePeriodByIds(paramMap); grabTicketMapper.deleteByGrabIds(paramMap); } finally { paramMap = null; } return count; } }
11,045
0.586057
0.578195
304
33.726974
27.736799
168
false
false
0
0
0
0
0
0
0.532895
false
false
4
f44e4cd30f7eaf4a9bf283446c30afdeb5ec9f2f
3,358,664,434,665
f843cfd8bad568e85e8a2fb86b597fe5e7bec640
/JAVA/javaPapers-master/javaPapers/class & object/Hello.java
e920537e5afa3470220a427ad855eae153661810
[]
no_license
arjunQ21/Ultimate-Notes-Books-Resources-for-NCIT
https://github.com/arjunQ21/Ultimate-Notes-Books-Resources-for-NCIT
f0622ab2a4108551725aa821275e979f0c0f8de9
39c58c93432547b3f2966772084357fcb583a233
refs/heads/master
2020-07-30T05:52:41.932000
2019-09-19T08:44:26
2019-09-19T08:44:26
210,108,396
2
0
null
true
2019-09-22T07:34:00
2019-09-22T07:34:00
2019-09-19T08:44:30
2019-09-19T08:44:27
1,274,908
0
0
0
null
false
false
class Hello { int num; double num1; void setVal(int n) { num=n; } void setVal(double n) { num1=n; } void showVal() { System.out.println(num1); System.out.println(num); } } class Heeel { public static void main(String ars[]) { Hello h=new Hello(); h.setVal(10); h.setVal(2.4); h.showVal(); } }
UTF-8
Java
362
java
Hello.java
Java
[]
null
[]
class Hello { int num; double num1; void setVal(int n) { num=n; } void setVal(double n) { num1=n; } void showVal() { System.out.println(num1); System.out.println(num); } } class Heeel { public static void main(String ars[]) { Hello h=new Hello(); h.setVal(10); h.setVal(2.4); h.showVal(); } }
362
0.538674
0.519337
32
10.34375
9.998779
39
false
false
0
0
0
0
0
0
0.3125
false
false
4
c3b5826047cc652dda4f636743db950e52ce92a5
16,947,940,964,594
afef5f2c8b68938e938a30c7ef9922ec96ba3dda
/workspace/day09/src/exer/Test1.java
a9c2e2c00d49a12a6349e4b76e62beb986258533
[]
no_license
cxdthd/java
https://github.com/cxdthd/java
9dd02b7e9366f1f6dac62bf09a7be544ce317447
bf85c8854ad3c8999ff167fed0cdbdc3bbf4c0ba
refs/heads/master
2023-06-23T14:45:21.278000
2021-07-22T11:27:51
2021-07-22T11:27:51
388,437,821
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package exer; public class Test1 { public static void main(String[] args) { int[] arr = new int[] { 12, 3, 3, 34, 56, 77, 432 }; testtt(arr); for (int i = 0; i < arr.length; i++) { System.out.print(arr[i] + " "); } } public static void testtt(int[] arr) { // 错误写法 // for (int i = 0; i < arr.length; i++) { // arr[i] = arr[i] / arr[0]; // } // 正确写法一 for (int i = arr.length - 1; i >= 0; i--) { arr[i] = arr[i] / arr[0]; } // 正确写法二 // int temp = arr[0]; // for (int i = 0; i < arr.length; i++) { // arr[i] = arr[i] / temp; // } } }
UTF-8
Java
607
java
Test1.java
Java
[]
null
[]
package exer; public class Test1 { public static void main(String[] args) { int[] arr = new int[] { 12, 3, 3, 34, 56, 77, 432 }; testtt(arr); for (int i = 0; i < arr.length; i++) { System.out.print(arr[i] + " "); } } public static void testtt(int[] arr) { // 错误写法 // for (int i = 0; i < arr.length; i++) { // arr[i] = arr[i] / arr[0]; // } // 正确写法一 for (int i = arr.length - 1; i >= 0; i--) { arr[i] = arr[i] / arr[0]; } // 正确写法二 // int temp = arr[0]; // for (int i = 0; i < arr.length; i++) { // arr[i] = arr[i] / temp; // } } }
607
0.474957
0.43696
30
18.299999
17.117535
54
false
false
0
0
0
0
0
0
2.1
false
false
4
dacf9ecb2910dae4ae6fac83d550b4e4abdbd9ff
26,869,315,473,879
ccd9fc93e3aea64a8c05cf80a353932dad79d419
/ssmv-common/ssmv-common-web/src/main/java/com/ssmv/common/web/controller/CommonController.java
cca03f1a52db7bc698a15d2e0588353900238c0a
[]
no_license
imZZW/ssmv
https://github.com/imZZW/ssmv
47da39d6acbba9481362856071c2204748c82770
83fa9b249fa98cf2ec797970a546ba02198b9e8d
refs/heads/master
2020-03-22T11:12:13.106000
2018-07-12T09:43:01
2018-07-12T09:43:01
139,948,278
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.ssmv.common.web.controller; import com.ssmv.common.entity.User; import com.ssmv.common.model.SignMessage; import com.ssmv.common.service.UserService; import com.ssmv.common.model.NameMessage; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import javax.annotation.Resource; import java.util.UUID; @Controller public class CommonController { @Resource private UserService userService; @RequestMapping("/register/nameExist") @ResponseBody public NameMessage registerNameExist(@RequestParam("username")String username){ return userService.registerExistName(username); } @RequestMapping("/login/nameExist") @ResponseBody public NameMessage loginNameExist(@RequestParam("username")String username){ return userService.loginExistName(username); } @RequestMapping(value = "/register",method = { RequestMethod.POST }) @ResponseBody public SignMessage register(@RequestParam(value = "username",required = false)String username,@RequestParam(value = "password",required = false)String password){ User user = new User(); user.setUuid(UUID.randomUUID().toString()); user.setName(username); user.setPassword(password); return userService.register(user); } @RequestMapping(value = "/login",method = {RequestMethod.POST}) @ResponseBody public SignMessage login(@RequestParam(value = "username",required = false)String username,@RequestParam(value = "password",required = false)String password){ User user = new User(); user.setName(username); user.setPassword(password); return userService.login(user); } }
UTF-8
Java
1,921
java
CommonController.java
Java
[ { "context": "ublic SignMessage register(@RequestParam(value = \"username\",required = false)String username,@RequestParam(v", "end": 1219, "score": 0.9793129563331604, "start": 1211, "tag": "USERNAME", "value": "username" }, { "context": "ID.randomUUID().toString());\n user.setName(username);\n user.setPassword(password);\n ret", "end": 1435, "score": 0.9636507034301758, "start": 1427, "tag": "USERNAME", "value": "username" }, { "context": " user.setName(username);\n user.setPassword(password);\n return userService.register(user);\n ", "end": 1471, "score": 0.9824841618537903, "start": 1463, "tag": "PASSWORD", "value": "password" }, { "context": " public SignMessage login(@RequestParam(value = \"username\",required = false)String username,@RequestParam(v", "end": 1670, "score": 0.9808506965637207, "start": 1662, "tag": "USERNAME", "value": "username" }, { "context": " User user = new User();\n user.setName(username);\n user.setPassword(password);\n ret", "end": 1834, "score": 0.8705697059631348, "start": 1826, "tag": "USERNAME", "value": "username" }, { "context": " user.setName(username);\n user.setPassword(password);\n return userService.login(user);\n }\n}", "end": 1870, "score": 0.9486912488937378, "start": 1862, "tag": "PASSWORD", "value": "password" } ]
null
[]
package com.ssmv.common.web.controller; import com.ssmv.common.entity.User; import com.ssmv.common.model.SignMessage; import com.ssmv.common.service.UserService; import com.ssmv.common.model.NameMessage; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import javax.annotation.Resource; import java.util.UUID; @Controller public class CommonController { @Resource private UserService userService; @RequestMapping("/register/nameExist") @ResponseBody public NameMessage registerNameExist(@RequestParam("username")String username){ return userService.registerExistName(username); } @RequestMapping("/login/nameExist") @ResponseBody public NameMessage loginNameExist(@RequestParam("username")String username){ return userService.loginExistName(username); } @RequestMapping(value = "/register",method = { RequestMethod.POST }) @ResponseBody public SignMessage register(@RequestParam(value = "username",required = false)String username,@RequestParam(value = "password",required = false)String password){ User user = new User(); user.setUuid(UUID.randomUUID().toString()); user.setName(username); user.setPassword(<PASSWORD>); return userService.register(user); } @RequestMapping(value = "/login",method = {RequestMethod.POST}) @ResponseBody public SignMessage login(@RequestParam(value = "username",required = false)String username,@RequestParam(value = "password",required = false)String password){ User user = new User(); user.setName(username); user.setPassword(<PASSWORD>); return userService.login(user); } }
1,925
0.741281
0.741281
52
35.942307
34.23584
165
false
false
0
0
0
0
0
0
0.615385
false
false
4
b03fc1b8f23db93dfa2791ad49efcaf67c10fc72
33,148,557,593,133
f5e7808d62e9785e180d13bbb8ca96caf131d931
/XMLParsers/src/org/numisoft/xmlparsers/ParserFactory.java
9d7df002014a3c25395911b8a94c3feecc5560e7
[]
no_license
kurilenok/it-academy
https://github.com/kurilenok/it-academy
4beed092d43838f67f4f0cbc0236a2827d288d3f
a22b672555f537d30963bd013874f5f64715391d
refs/heads/master
2021-01-10T08:01:22.526000
2016-04-09T08:53:57
2016-04-09T08:53:57
44,406,685
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.numisoft.xmlparsers; /** * This class is SINGLETON FACTORY METHOD! * */ public class ParserFactory { /* SINGLETON */ private ParserFactory() { } private static final ParserFactory INSTANCE = new ParserFactory(); public static ParserFactory getInstance() { return INSTANCE; } /* FACTORY METHOD */ public AbstractParser getParser(String parserType) { switch (parserType) { case "DOM": return new ParserDOM(); case "SAX": return new ParserSAX(); case "StAX": return new ParserStAX(); } return null; } }
UTF-8
Java
552
java
ParserFactory.java
Java
[]
null
[]
package org.numisoft.xmlparsers; /** * This class is SINGLETON FACTORY METHOD! * */ public class ParserFactory { /* SINGLETON */ private ParserFactory() { } private static final ParserFactory INSTANCE = new ParserFactory(); public static ParserFactory getInstance() { return INSTANCE; } /* FACTORY METHOD */ public AbstractParser getParser(String parserType) { switch (parserType) { case "DOM": return new ParserDOM(); case "SAX": return new ParserSAX(); case "StAX": return new ParserStAX(); } return null; } }
552
0.688406
0.688406
31
16.806452
17.173534
67
false
false
0
0
0
0
0
0
1.258065
false
false
4
429f071e2cde31f7e462975086ccdb87e8ef6ce6
26,225,070,369,472
9f090ad986636db2ab499109343e222d21efd089
/international.java
7eb08c43b8678437dd2210b7b126972ebdb969ec
[]
no_license
ChandanCG/DESIGN-PATTERNS
https://github.com/ChandanCG/DESIGN-PATTERNS
71d01b238ab3b401d06f5d51af14a36c1396aa99
fc8e46a02c6ec3d125eb7bc47358bc52b83ce789
refs/heads/master
2021-01-18T11:14:52.299000
2016-05-14T13:00:37
2016-05-14T13:00:37
58,806,065
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.util.*; public class international implements Reporter{ static ArrayList<Reader> in =new ArrayList<>(); Scanner ab=new Scanner(System.in); String text; @Override public void writeArticle() { System.out.println("Enter the international news"); text=ab.nextLine(); System.out.println("Your Article\t" +text+ "\t has been written as national news"); } public void add(Reader r) { // TODO Auto-generated method stub in.add(r); } @Override public void notifyEveryone() { // TODO Auto-generated method stub int length=in.size(); for(int i=0;i<length;i++){ in.get(i).update(); System.out.println("Notified "+in.get(i)); } } @Override public String getState() { // TODO Auto-generated method stub return text; } }
UTF-8
Java
784
java
international.java
Java
[]
null
[]
import java.util.*; public class international implements Reporter{ static ArrayList<Reader> in =new ArrayList<>(); Scanner ab=new Scanner(System.in); String text; @Override public void writeArticle() { System.out.println("Enter the international news"); text=ab.nextLine(); System.out.println("Your Article\t" +text+ "\t has been written as national news"); } public void add(Reader r) { // TODO Auto-generated method stub in.add(r); } @Override public void notifyEveryone() { // TODO Auto-generated method stub int length=in.size(); for(int i=0;i<length;i++){ in.get(i).update(); System.out.println("Notified "+in.get(i)); } } @Override public String getState() { // TODO Auto-generated method stub return text; } }
784
0.668367
0.667092
32
23.5
18.937397
85
false
false
0
0
0
0
0
0
2.4375
false
false
4
3edc4b4359d2347f15e71800310ae7cdff6e2790
30,554,397,370,377
af492cdb1f9c384896884f607403b86f0fe9f88b
/app/src/main/java/com/example/rlysh_000/xmppsms/registerUser.java
37c564cb03aa2288a02ff6df8c80684409b58f10
[]
no_license
rlyshw/XMPPSMS
https://github.com/rlyshw/XMPPSMS
8d002e32c2a9ccd09203812e784124ebda8546bb
ec0f8c5f8fe8b037da2bd3e3c07be2451d4b3cc7
refs/heads/master
2021-01-10T20:05:14.798000
2014-10-08T13:50:01
2014-10-08T13:50:01
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.rlysh_000.xmppsms; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.os.AsyncTask; import android.os.Bundle; import android.telephony.TelephonyManager; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.EditText; import android.widget.TextView; import java.io.FileOutputStream; import java.io.IOException; import java.net.URISyntaxException; import java.util.concurrent.ExecutionException; public class registerUser extends Activity { /* This Activity handles registering the user with the server. This user is what the desktop XMPP client will use to recieve texts. It is not really needed by the application, outside of sending a register request to the server */ public static String uPassword; //determine if this needs to or should exist String authFile = "authFile"; //Do I really need an authfile???? @Override protected void onCreate(Bundle savedInstanceState) { // get user's phone number // I couldn't figure out how to make the phone number public static in one file TelephonyManager tMgr = (TelephonyManager) getApplicationContext().getSystemService(Context.TELEPHONY_SERVICE); String mPhoneNumber = tMgr.getLine1Number(); super.onCreate(savedInstanceState); setContentView(R.layout.register); // Change to the register layout TextView display = (TextView) findViewById(R.id.userName); //Get the userName TextView display.setText(mPhoneNumber + "@rlyshw.com"); // Change it to mPhoneNumber@rlyshw.com } public void createUser(View view) throws ExecutionException, InterruptedException, IOException { // I use this deceleration like 8 separate times. TelephonyManager tMgr = (TelephonyManager) getApplicationContext().getSystemService(Context.TELEPHONY_SERVICE); String mPhoneNumber = tMgr.getLine1Number(); //Should really figure out how to make ONE public static mPhoneNumber // Need to not use file operations in this app FileOutputStream fos = openFileOutput(authFile, Context.MODE_PRIVATE); EditText passwordField = (EditText) findViewById(R.id.userPassword); uPassword = passwordField.getText().toString(); Log.d("PASSWORD: ",uPassword); //Debug purposes //This is important. It calls the AsyncTask to register the new // user with password uPassword, mPhoneNumber@rlyshw.com // This will be the user's credentials for connecting to the xmpp server AsyncTask<String, Integer, Boolean> register = new CreateUser().execute(mPhoneNumber, uPassword); try { // register.get() returns True when the CreateUser task completes successfully if(register.get()){ // Write that password to a file. // MyActivity uses this file to check if the account exists on the server. // This is not the right way to check if the account exists on the server. fos.write(uPassword.getBytes()); fos.close(); } } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } } public void startXMPP(View view) throws IOException, URISyntaxException { // This is called when the button is pressed // Essentially restarts the program Intent intent = new Intent(this, MyActivity.class); startActivity(intent); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.register_user, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); return id == R.id.action_settings || super.onOptionsItemSelected(item); } }
UTF-8
Java
4,272
java
registerUser.java
Java
[ { "context": "ext(mPhoneNumber + \"@rlyshw.com\"); // Change it to mPhoneNumber@rlyshw.com\n }\n\n public void createUser(View view) thro", "end": 1674, "score": 0.9995050430297852, "start": 1651, "tag": "EMAIL", "value": "mPhoneNumber@rlyshw.com" }, { "context": "r the new\n // user with password uPassword, mPhoneNumber@rlyshw.com\n // This will be the user's credentials fo", "end": 2544, "score": 0.9999228715896606, "start": 2521, "tag": "EMAIL", "value": "mPhoneNumber@rlyshw.com" } ]
null
[]
package com.example.rlysh_000.xmppsms; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.os.AsyncTask; import android.os.Bundle; import android.telephony.TelephonyManager; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.EditText; import android.widget.TextView; import java.io.FileOutputStream; import java.io.IOException; import java.net.URISyntaxException; import java.util.concurrent.ExecutionException; public class registerUser extends Activity { /* This Activity handles registering the user with the server. This user is what the desktop XMPP client will use to recieve texts. It is not really needed by the application, outside of sending a register request to the server */ public static String uPassword; //determine if this needs to or should exist String authFile = "authFile"; //Do I really need an authfile???? @Override protected void onCreate(Bundle savedInstanceState) { // get user's phone number // I couldn't figure out how to make the phone number public static in one file TelephonyManager tMgr = (TelephonyManager) getApplicationContext().getSystemService(Context.TELEPHONY_SERVICE); String mPhoneNumber = tMgr.getLine1Number(); super.onCreate(savedInstanceState); setContentView(R.layout.register); // Change to the register layout TextView display = (TextView) findViewById(R.id.userName); //Get the userName TextView display.setText(mPhoneNumber + "@rlyshw.com"); // Change it to <EMAIL> } public void createUser(View view) throws ExecutionException, InterruptedException, IOException { // I use this deceleration like 8 separate times. TelephonyManager tMgr = (TelephonyManager) getApplicationContext().getSystemService(Context.TELEPHONY_SERVICE); String mPhoneNumber = tMgr.getLine1Number(); //Should really figure out how to make ONE public static mPhoneNumber // Need to not use file operations in this app FileOutputStream fos = openFileOutput(authFile, Context.MODE_PRIVATE); EditText passwordField = (EditText) findViewById(R.id.userPassword); uPassword = passwordField.getText().toString(); Log.d("PASSWORD: ",uPassword); //Debug purposes //This is important. It calls the AsyncTask to register the new // user with password uPassword, <EMAIL> // This will be the user's credentials for connecting to the xmpp server AsyncTask<String, Integer, Boolean> register = new CreateUser().execute(mPhoneNumber, uPassword); try { // register.get() returns True when the CreateUser task completes successfully if(register.get()){ // Write that password to a file. // MyActivity uses this file to check if the account exists on the server. // This is not the right way to check if the account exists on the server. fos.write(uPassword.getBytes()); fos.close(); } } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } } public void startXMPP(View view) throws IOException, URISyntaxException { // This is called when the button is pressed // Essentially restarts the program Intent intent = new Intent(this, MyActivity.class); startActivity(intent); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.register_user, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); return id == R.id.action_settings || super.onOptionsItemSelected(item); } }
4,240
0.695225
0.69382
96
43.5
32.680271
122
false
false
0
0
0
0
0
0
0.604167
false
false
4
9076a9a0a0d29dd76077ca639a3e91a411559f10
7,043,746,406,718
6a03a65f3415e5d88c95756a8754f8af199767b3
/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/results/DebugTraceTransactionResult.java
03b5d96259be86164bb8c173f170333456085dcf
[ "Apache-2.0", "LicenseRef-scancode-free-unknown" ]
permissive
hyperledger/besu
https://github.com/hyperledger/besu
ba372cf85c660ceb63b075bdfdfeb57c37978ac1
92ca53e5208a62fdb06a0df2ec3a4cc245df6c8a
refs/heads/main
2023-09-04T02:59:17.383000
2023-09-01T05:06:08
2023-09-01T05:06:08
206,414,745
1,339
725
Apache-2.0
false
2023-09-14T13:04:07
2019-09-04T21:11:20
2023-09-13T02:43:58
2023-09-14T13:04:07
64,392
1,262
630
291
Java
false
false
/* * Copyright ConsenSys AG. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. * * SPDX-License-Identifier: Apache-2.0 */ package org.hyperledger.besu.ethereum.api.jsonrpc.internal.results; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.processor.TransactionTrace; import org.hyperledger.besu.ethereum.debug.TraceFrame; import java.util.Collection; import java.util.List; import java.util.stream.Collectors; import com.fasterxml.jackson.annotation.JsonGetter; import com.fasterxml.jackson.annotation.JsonPropertyOrder; @JsonPropertyOrder({"gas", "failed", "returnValue", "structLogs"}) public class DebugTraceTransactionResult { private final List<StructLog> structLogs; private final String returnValue; private final long gas; private final boolean failed; public DebugTraceTransactionResult(final TransactionTrace transactionTrace) { gas = transactionTrace.getGas(); returnValue = transactionTrace.getResult().getOutput().toString().substring(2); structLogs = transactionTrace.getTraceFrames().stream() .map(DebugTraceTransactionResult::createStructLog) .collect(Collectors.toList()); failed = !transactionTrace.getResult().isSuccessful(); } public static Collection<DebugTraceTransactionResult> of( final Collection<TransactionTrace> traces) { return traces.stream().map(DebugTraceTransactionResult::new).collect(Collectors.toList()); } private static StructLog createStructLog(final TraceFrame frame) { return frame .getExceptionalHaltReason() .map(__ -> (StructLog) new StructLogWithError(frame)) .orElse(new StructLog(frame)); } @JsonGetter(value = "structLogs") public List<StructLog> getStructLogs() { return structLogs; } @JsonGetter(value = "returnValue") public String getReturnValue() { return returnValue; } @JsonGetter(value = "gas") public long getGas() { return gas; } @JsonGetter(value = "failed") public boolean failed() { return failed; } }
UTF-8
Java
2,529
java
DebugTraceTransactionResult.java
Java
[]
null
[]
/* * Copyright ConsenSys AG. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. * * SPDX-License-Identifier: Apache-2.0 */ package org.hyperledger.besu.ethereum.api.jsonrpc.internal.results; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.processor.TransactionTrace; import org.hyperledger.besu.ethereum.debug.TraceFrame; import java.util.Collection; import java.util.List; import java.util.stream.Collectors; import com.fasterxml.jackson.annotation.JsonGetter; import com.fasterxml.jackson.annotation.JsonPropertyOrder; @JsonPropertyOrder({"gas", "failed", "returnValue", "structLogs"}) public class DebugTraceTransactionResult { private final List<StructLog> structLogs; private final String returnValue; private final long gas; private final boolean failed; public DebugTraceTransactionResult(final TransactionTrace transactionTrace) { gas = transactionTrace.getGas(); returnValue = transactionTrace.getResult().getOutput().toString().substring(2); structLogs = transactionTrace.getTraceFrames().stream() .map(DebugTraceTransactionResult::createStructLog) .collect(Collectors.toList()); failed = !transactionTrace.getResult().isSuccessful(); } public static Collection<DebugTraceTransactionResult> of( final Collection<TransactionTrace> traces) { return traces.stream().map(DebugTraceTransactionResult::new).collect(Collectors.toList()); } private static StructLog createStructLog(final TraceFrame frame) { return frame .getExceptionalHaltReason() .map(__ -> (StructLog) new StructLogWithError(frame)) .orElse(new StructLog(frame)); } @JsonGetter(value = "structLogs") public List<StructLog> getStructLogs() { return structLogs; } @JsonGetter(value = "returnValue") public String getReturnValue() { return returnValue; } @JsonGetter(value = "gas") public long getGas() { return gas; } @JsonGetter(value = "failed") public boolean failed() { return failed; } }
2,529
0.741004
0.738236
76
32.276318
30.718843
118
false
false
0
0
0
0
0
0
0.394737
false
false
4
3a8a5d7c0e9854cd376463fba1f17e61462ed163
7,043,746,405,151
9c641714119c93f53293eb7dc85ba1c1be69b94b
/src/main/java/ru/stacy/controllers/UserController.java
02d65063fd2b8f993ce2b233cb659b4de8016499
[]
no_license
SergeyStasko23/TEST-PROJECT
https://github.com/SergeyStasko23/TEST-PROJECT
6a18bdcedc1768975ef61a8a9b907d0aad990e67
42a2523129dccf846c81dce09c22877c3a4d861a
refs/heads/master
2020-07-08T12:31:22.068000
2019-08-21T22:23:36
2019-08-21T22:23:36
203,672,797
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package ru.stacy.controllers; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.Ordered; import org.springframework.core.annotation.Order; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import ru.stacy.dto.UserDTO; import ru.stacy.entities.User; import ru.stacy.services.UserService; import ru.stacy.util.UserStateResponse; import java.util.List; @RestController @RequestMapping("/api") public class UserController { private final UserService userService; @Autowired public UserController(UserService userService) { this.userService = userService; } @PostMapping("/users") public ResponseEntity<Long> createUser(@RequestBody User user) { Long id = userService.createUser(user); return new ResponseEntity<>(id, HttpStatus.CREATED); } @GetMapping("/users/{id}") @Order(Ordered.HIGHEST_PRECEDENCE) public ResponseEntity<UserDTO> getUserById(@PathVariable Long id) { return userService.getUserById(id) .map(ResponseEntity::ok) .orElse(ResponseEntity.notFound().build()); } @PutMapping("/users/{id}") public ResponseEntity<UserStateResponse> updateUserState(@PathVariable Long id, @RequestParam("state") Boolean userState) { UserStateResponse userStateResponse = userService.updateUserState(id, userState); return ResponseEntity.ok(userStateResponse); } @GetMapping("/users/statistics") @Order(Ordered.HIGHEST_PRECEDENCE) public ResponseEntity<List<UserDTO>> getAllUsersByParameters( @RequestParam(name = "unixTimestamp", required = false) Long unixTimestamp, @RequestParam(name = "userState", required = false) Boolean userState) { List<UserDTO> users; if(unixTimestamp != null) { if(userState != null) { users = userService.getAllUsersByUserStateAndTimestampAfter(userState, unixTimestamp); return ResponseEntity.ok(users); } users = userService.getAllUsersByUnixTimestampAfter(unixTimestamp); return ResponseEntity.ok(users); } else if(userState != null) { users = userService.getAllUsersByUserState(userState); return ResponseEntity.ok(users); } users = userService.getAllUsers(); return ResponseEntity.ok(users); } }
UTF-8
Java
2,495
java
UserController.java
Java
[]
null
[]
package ru.stacy.controllers; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.Ordered; import org.springframework.core.annotation.Order; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import ru.stacy.dto.UserDTO; import ru.stacy.entities.User; import ru.stacy.services.UserService; import ru.stacy.util.UserStateResponse; import java.util.List; @RestController @RequestMapping("/api") public class UserController { private final UserService userService; @Autowired public UserController(UserService userService) { this.userService = userService; } @PostMapping("/users") public ResponseEntity<Long> createUser(@RequestBody User user) { Long id = userService.createUser(user); return new ResponseEntity<>(id, HttpStatus.CREATED); } @GetMapping("/users/{id}") @Order(Ordered.HIGHEST_PRECEDENCE) public ResponseEntity<UserDTO> getUserById(@PathVariable Long id) { return userService.getUserById(id) .map(ResponseEntity::ok) .orElse(ResponseEntity.notFound().build()); } @PutMapping("/users/{id}") public ResponseEntity<UserStateResponse> updateUserState(@PathVariable Long id, @RequestParam("state") Boolean userState) { UserStateResponse userStateResponse = userService.updateUserState(id, userState); return ResponseEntity.ok(userStateResponse); } @GetMapping("/users/statistics") @Order(Ordered.HIGHEST_PRECEDENCE) public ResponseEntity<List<UserDTO>> getAllUsersByParameters( @RequestParam(name = "unixTimestamp", required = false) Long unixTimestamp, @RequestParam(name = "userState", required = false) Boolean userState) { List<UserDTO> users; if(unixTimestamp != null) { if(userState != null) { users = userService.getAllUsersByUserStateAndTimestampAfter(userState, unixTimestamp); return ResponseEntity.ok(users); } users = userService.getAllUsersByUnixTimestampAfter(unixTimestamp); return ResponseEntity.ok(users); } else if(userState != null) { users = userService.getAllUsersByUserState(userState); return ResponseEntity.ok(users); } users = userService.getAllUsers(); return ResponseEntity.ok(users); } }
2,495
0.698597
0.698597
68
35.691177
27.530334
127
false
false
0
0
0
0
0
0
0.514706
false
false
4
2f1382e9866920213cdea0378e908d5fd68c7341
6,949,257,108,692
33bfa7d45c4a8c54c2316b01323a941b758abe78
/src/main/java/Airline/domain/Airline.java
04c908664ab9e9bac1b6a9847b2a7fb6b944d6c7
[]
no_license
JakoetTH/Chapter6
https://github.com/JakoetTH/Chapter6
1b9e4b8814a55d486773c0ed912ded05e232a77f
7fa25ff06f161e31be3ab23b14f6d10f0c5f11b5
refs/heads/master
2020-05-16T13:32:02.239000
2015-05-05T07:53:49
2015-05-05T07:53:49
34,174,378
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package Airline.domain; import javax.persistence.*; import java.io.Serializable; /** * Created by student on 2015/04/24. */ @Entity public class Airline implements AirlineDetails, Serializable{ @Id @GeneratedValue(strategy = GenerationType.AUTO) private String ID; private String name; private String nationality; private Airline() { } public Airline(Builder builder) { this.ID=builder.ID; this.name=builder.name; this.nationality=builder.nationality; } @Override public String getID() { return this.ID; } @Override public String getAirlineName() { return this.name; } @Override public String getNationality() { return this.nationality; } public static class Builder { private String ID; private String name; private String nationality; public Builder(String ID) { this.ID=ID; } public Builder name(String name) { this.name=name; return this; } public Builder nationality(String nationality) { this.nationality=nationality; return this; } public Builder copy(Airline airline) { this.ID=airline.getID(); this.name=airline.getAirlineName(); this.nationality=airline.getNationality(); return this; } public Airline build() { return new Airline(this); } } }
UTF-8
Java
1,582
java
Airline.java
Java
[ { "context": ".*;\nimport java.io.Serializable;\n/**\n * Created by student on 2015/04/24.\n */\n@Entity\npublic class Airline i", "end": 107, "score": 0.5169211626052856, "start": 100, "tag": "USERNAME", "value": "student" } ]
null
[]
package Airline.domain; import javax.persistence.*; import java.io.Serializable; /** * Created by student on 2015/04/24. */ @Entity public class Airline implements AirlineDetails, Serializable{ @Id @GeneratedValue(strategy = GenerationType.AUTO) private String ID; private String name; private String nationality; private Airline() { } public Airline(Builder builder) { this.ID=builder.ID; this.name=builder.name; this.nationality=builder.nationality; } @Override public String getID() { return this.ID; } @Override public String getAirlineName() { return this.name; } @Override public String getNationality() { return this.nationality; } public static class Builder { private String ID; private String name; private String nationality; public Builder(String ID) { this.ID=ID; } public Builder name(String name) { this.name=name; return this; } public Builder nationality(String nationality) { this.nationality=nationality; return this; } public Builder copy(Airline airline) { this.ID=airline.getID(); this.name=airline.getAirlineName(); this.nationality=airline.getNationality(); return this; } public Airline build() { return new Airline(this); } } }
1,582
0.56574
0.560683
79
19.025316
15.855339
61
false
false
0
0
0
0
0
0
0.329114
false
false
4
9a6dc770aad459faf2923b153d2e17be1354ba8c
36,696,200,605,563
0517ae9ad164038cc6e6be0509ac9bf23d7ec44c
/hazelcast/src/test/java/com/hazelcast/query/impl/predicates/OrToInVisitorTest.java
b059f6343682c09c08db9e370824d0927b90c46a
[ "Apache-2.0" ]
permissive
atlassian/hazelcast
https://github.com/atlassian/hazelcast
1c8e5ec58f626102d4de0dc97b6f2f4dfd946b9d
174b3db30e001c2a1b60d870cfcc3138f10edecc
refs/heads/master
2023-07-08T07:23:49.811000
2016-11-28T15:01:28
2016-11-28T19:16:15
24,581,214
4
4
null
true
2023-03-23T23:55:52
2014-09-29T05:33:05
2019-07-22T16:36:59
2023-03-23T23:55:52
100,300
5
4
8
Java
false
false
package com.hazelcast.query.impl.predicates; import com.hazelcast.core.TypeConverter; import com.hazelcast.query.Predicate; import com.hazelcast.query.impl.Index; import com.hazelcast.query.impl.Indexes; import com.hazelcast.test.HazelcastParallelClassRunner; import com.hazelcast.test.annotation.ParallelTest; import com.hazelcast.test.annotation.QuickTest; import org.hamcrest.Matchers; import org.junit.Before; import org.junit.Test; import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; import static com.hazelcast.query.Predicates.equal; import static com.hazelcast.query.Predicates.notEqual; import static com.hazelcast.query.Predicates.or; import static com.hazelcast.query.impl.TypeConverters.INTEGER_CONVERTER; import static org.hamcrest.Matchers.arrayWithSize; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.instanceOf; import static org.junit.Assert.assertThat; import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @RunWith(HazelcastParallelClassRunner.class) @Category({QuickTest.class, ParallelTest.class}) public class OrToInVisitorTest { private OrToInVisitor visitor; private Indexes mockIndexes; private Index mockIndex; @Before public void setUp() { mockIndexes = mock(Indexes.class); mockIndex = mock(Index.class); when(mockIndexes.getIndex(anyString())).thenReturn(mockIndex); visitor = new OrToInVisitor(); useConverter(INTEGER_CONVERTER); } @Test public void whenEmptyPredicate_thenReturnItself() { OrPredicate or = new OrPredicate(null); OrPredicate result = (OrPredicate) visitor.visit(or, mockIndexes); assertThat(or, equalTo(result)); } @Test public void whenThresholdNotExceeded_thenReturnItself() { Predicate p1 = equal("age", 1); Predicate p2 = equal("age", 2); OrPredicate or = (OrPredicate) or(p1, p2); OrPredicate result = (OrPredicate) visitor.visit(or, mockIndexes); assertThat(or, equalTo(result)); } @Test public void whenThresholdExceeded_noCandidatesFound_thenReturnItself() { // (age != 1 or age != 2 or age != 3 or age != 4 or age != 5) Predicate p1 = notEqual("age", 1); Predicate p2 = notEqual("age", 2); Predicate p3 = notEqual("age", 3); Predicate p4 = notEqual("age", 4); Predicate p5 = notEqual("age", 5); OrPredicate or = (OrPredicate) or(p1, p2, p3, p4, p5); OrPredicate result = (OrPredicate) visitor.visit(or, mockIndexes); assertThat(or, equalTo(result)); } @Test public void whenThresholdExceeded_noEnoughCandidatesFound_thenReturnItself() { // (age != 1 or age != 2 or age != 3 or age != 4 or age != 5) Predicate p1 = equal("age", 1); Predicate p2 = equal("age", 2); Predicate p3 = equal("age", 3); Predicate p4 = equal("age", 4); Predicate p5 = notEqual("age", 5); OrPredicate or = (OrPredicate) or(p1, p2, p3, p4, p5); OrPredicate result = (OrPredicate) visitor.visit(or, mockIndexes); assertThat(or, equalTo(result)); } @Test public void whenThresholdExceeded_thenRewriteToInPredicate() { // (age = 1 or age = 2 or age = 3 or age = 4 or age = 5) --> (age in (1, 2, 3, 4, 5)) Predicate p1 = equal("age", 1); Predicate p2 = equal("age", 2); Predicate p3 = equal("age", 3); Predicate p4 = equal("age", 4); Predicate p5 = equal("age", 5); OrPredicate or = (OrPredicate) or(p1, p2, p3, p4, p5); InPredicate result = (InPredicate) visitor.visit(or, mockIndexes); Comparable[] values = result.values; assertThat(values, arrayWithSize(5)); assertThat(values, Matchers.is(Matchers.<Comparable>arrayContainingInAnyOrder(1, 2, 3, 4, 5))); } @Test public void whenThresholdExceeded_thenRewriteToOrPredicate() { // (age = 1 or age = 2 or age = 3 or age = 4 or age = 5 or age != 6) --> (age in (1, 2, 3, 4, 5) or age != 6) Predicate p1 = equal("age", 1); Predicate p2 = equal("age", 2); Predicate p3 = equal("age", 3); Predicate p4 = equal("age", 4); Predicate p5 = equal("age", 5); Predicate p6 = notEqual("age", 6); OrPredicate or = (OrPredicate) or(p1, p2, p3, p4, p5, p6); OrPredicate result = (OrPredicate) visitor.visit(or, mockIndexes); Predicate[] predicates = result.predicates; for (Predicate predicate : predicates) { if (predicate instanceof InPredicate) { Comparable[] values = ((InPredicate) predicate).values; assertThat(values, arrayWithSize(5)); assertThat(values, Matchers.is(Matchers.<Comparable>arrayContainingInAnyOrder(1, 2, 3, 4, 5))); } else { assertThat(predicate, instanceOf(NotEqualPredicate.class)); } } } private void useConverter(TypeConverter converter) { when(mockIndex.getConverter()).thenReturn(converter); } }
UTF-8
Java
5,184
java
OrToInVisitorTest.java
Java
[]
null
[]
package com.hazelcast.query.impl.predicates; import com.hazelcast.core.TypeConverter; import com.hazelcast.query.Predicate; import com.hazelcast.query.impl.Index; import com.hazelcast.query.impl.Indexes; import com.hazelcast.test.HazelcastParallelClassRunner; import com.hazelcast.test.annotation.ParallelTest; import com.hazelcast.test.annotation.QuickTest; import org.hamcrest.Matchers; import org.junit.Before; import org.junit.Test; import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; import static com.hazelcast.query.Predicates.equal; import static com.hazelcast.query.Predicates.notEqual; import static com.hazelcast.query.Predicates.or; import static com.hazelcast.query.impl.TypeConverters.INTEGER_CONVERTER; import static org.hamcrest.Matchers.arrayWithSize; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.instanceOf; import static org.junit.Assert.assertThat; import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @RunWith(HazelcastParallelClassRunner.class) @Category({QuickTest.class, ParallelTest.class}) public class OrToInVisitorTest { private OrToInVisitor visitor; private Indexes mockIndexes; private Index mockIndex; @Before public void setUp() { mockIndexes = mock(Indexes.class); mockIndex = mock(Index.class); when(mockIndexes.getIndex(anyString())).thenReturn(mockIndex); visitor = new OrToInVisitor(); useConverter(INTEGER_CONVERTER); } @Test public void whenEmptyPredicate_thenReturnItself() { OrPredicate or = new OrPredicate(null); OrPredicate result = (OrPredicate) visitor.visit(or, mockIndexes); assertThat(or, equalTo(result)); } @Test public void whenThresholdNotExceeded_thenReturnItself() { Predicate p1 = equal("age", 1); Predicate p2 = equal("age", 2); OrPredicate or = (OrPredicate) or(p1, p2); OrPredicate result = (OrPredicate) visitor.visit(or, mockIndexes); assertThat(or, equalTo(result)); } @Test public void whenThresholdExceeded_noCandidatesFound_thenReturnItself() { // (age != 1 or age != 2 or age != 3 or age != 4 or age != 5) Predicate p1 = notEqual("age", 1); Predicate p2 = notEqual("age", 2); Predicate p3 = notEqual("age", 3); Predicate p4 = notEqual("age", 4); Predicate p5 = notEqual("age", 5); OrPredicate or = (OrPredicate) or(p1, p2, p3, p4, p5); OrPredicate result = (OrPredicate) visitor.visit(or, mockIndexes); assertThat(or, equalTo(result)); } @Test public void whenThresholdExceeded_noEnoughCandidatesFound_thenReturnItself() { // (age != 1 or age != 2 or age != 3 or age != 4 or age != 5) Predicate p1 = equal("age", 1); Predicate p2 = equal("age", 2); Predicate p3 = equal("age", 3); Predicate p4 = equal("age", 4); Predicate p5 = notEqual("age", 5); OrPredicate or = (OrPredicate) or(p1, p2, p3, p4, p5); OrPredicate result = (OrPredicate) visitor.visit(or, mockIndexes); assertThat(or, equalTo(result)); } @Test public void whenThresholdExceeded_thenRewriteToInPredicate() { // (age = 1 or age = 2 or age = 3 or age = 4 or age = 5) --> (age in (1, 2, 3, 4, 5)) Predicate p1 = equal("age", 1); Predicate p2 = equal("age", 2); Predicate p3 = equal("age", 3); Predicate p4 = equal("age", 4); Predicate p5 = equal("age", 5); OrPredicate or = (OrPredicate) or(p1, p2, p3, p4, p5); InPredicate result = (InPredicate) visitor.visit(or, mockIndexes); Comparable[] values = result.values; assertThat(values, arrayWithSize(5)); assertThat(values, Matchers.is(Matchers.<Comparable>arrayContainingInAnyOrder(1, 2, 3, 4, 5))); } @Test public void whenThresholdExceeded_thenRewriteToOrPredicate() { // (age = 1 or age = 2 or age = 3 or age = 4 or age = 5 or age != 6) --> (age in (1, 2, 3, 4, 5) or age != 6) Predicate p1 = equal("age", 1); Predicate p2 = equal("age", 2); Predicate p3 = equal("age", 3); Predicate p4 = equal("age", 4); Predicate p5 = equal("age", 5); Predicate p6 = notEqual("age", 6); OrPredicate or = (OrPredicate) or(p1, p2, p3, p4, p5, p6); OrPredicate result = (OrPredicate) visitor.visit(or, mockIndexes); Predicate[] predicates = result.predicates; for (Predicate predicate : predicates) { if (predicate instanceof InPredicate) { Comparable[] values = ((InPredicate) predicate).values; assertThat(values, arrayWithSize(5)); assertThat(values, Matchers.is(Matchers.<Comparable>arrayContainingInAnyOrder(1, 2, 3, 4, 5))); } else { assertThat(predicate, instanceOf(NotEqualPredicate.class)); } } } private void useConverter(TypeConverter converter) { when(mockIndex.getConverter()).thenReturn(converter); } }
5,184
0.652778
0.63098
128
39.5
25.197966
119
false
false
0
0
0
0
0
0
1.195313
false
false
4
af413b307d8a3e592306bf2cac49bdb26ca696d0
31,318,901,581,478
b3c340457f0df7b4cab63a284d846daa871809a3
/Messanger/app/src/main/java/com/example/messanger/ChatCreation/CreateChat.java
a11b329ee7f99b425b0bb8542391751648e58118
[]
no_license
shlokdesai/EncryptionMessenger
https://github.com/shlokdesai/EncryptionMessenger
f5d61a670042175cf8c1da838c8c533cd6f0d199
d07d0c53f08b0f004752d3525dc8d9881de39fb0
refs/heads/master
2023-04-06T02:53:21.086000
2021-04-20T18:50:52
2021-04-20T18:50:52
292,481,835
1
1
null
false
2021-04-20T18:50:53
2020-09-03T06:06:56
2020-09-26T05:20:35
2021-04-20T18:50:52
4,626
2
1
0
Java
false
false
package com.example.messanger.ChatCreation; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.view.Gravity; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.PopupWindow; import android.widget.Toast; import com.example.messanger.Chat.ChatListActivity; import com.example.messanger.R; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; public class CreateChat extends AppCompatActivity { private List<UserObject> userObjects; private Button chatCreate; private RecyclerView rv; private CreateChatAdapter adapter; private View view; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.list_of_users); userObjects = new ArrayList<>(); chatCreate = findViewById(R.id.createChat); rv = findViewById(R.id.List); rv.setNestedScrollingEnabled(true); rv.setHasFixedSize(true); adapter = new CreateChatAdapter( userObjects); rv.setAdapter(adapter); rv.setLayoutManager(new LinearLayoutManager(this)); chatCreate.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { int checked = 0; String userID = ""; for(UserObject user: userObjects){ if(user.getSelected()) { checked++; userID = user.getUid(); } } if(checked == 1 ){ boolean similar = false; for(String chatID: ChatListActivity.users){ if(chatID.equals(userID)){ Toast.makeText(CreateChat.this, "Cannot Create a Duplicate Chat", Toast.LENGTH_LONG).show(); similar = true; } } if(!similar){ CreateChat(); } } } }); final DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference().child("user"); final FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser(); databaseReference.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot snapshot) { if(snapshot.exists()){ for(DataSnapshot snapshot1: snapshot.getChildren()){ if(!(firebaseUser.getUid().equals(snapshot1.getKey()))){ String name = "none"; String email = "none"; if(snapshot1.child("email").exists()) email = snapshot1.child("email").getValue().toString(); String key = snapshot1.getKey(); if(snapshot1.child("Name").exists()) name = snapshot1.child("Name").getValue().toString(); UserObject userObject = new UserObject(email, key, name); userObjects.add(userObject); adapter = new CreateChatAdapter(userObjects); } } rv.setAdapter(adapter); adapter.notifyDataSetChanged(); } } @Override public void onCancelled(@NonNull DatabaseError error) { } }); } private void CreateChat() { int usersChosen = 0; final String key = FirebaseDatabase.getInstance().getReference().child("chat").push().getKey();// push method creates a key for(UserObject object: userObjects){ if(object.getSelected()){ usersChosen += 1; } } if(usersChosen == 1){ //will not make user enter the name String userID = ""; for (UserObject object: userObjects){ if(object.getSelected()){ if(!object.getUid().equals(FirebaseAuth.getInstance().getUid())){ userID = object.getUid(); } } } DatabaseReference databaseReference1 = FirebaseDatabase.getInstance().getReference().child("user").child(userID); databaseReference1.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot snapshot) { final DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference().child("chat").child(key); for(UserObject object: userObjects){ if(object.getSelected()){ FirebaseDatabase.getInstance().getReference().child("user").child(Objects.requireNonNull(FirebaseAuth.getInstance().getUid())).child("chat").child(key).setValue(true); FirebaseDatabase.getInstance().getReference().child("user").child(object.getUid()).child("chat").child(key).setValue(true); } } FirebaseDatabase.getInstance().getReference().child("chat").child(key).setValue(true); FirebaseDatabase.getInstance().getReference().child("chat").child(key).child("users").child(FirebaseAuth.getInstance().getUid()); for (UserObject object: userObjects){ if (object.getSelected()){ FirebaseDatabase.getInstance().getReference().child("chat").child(key).child("users").child(object.getUid()).setValue(true); } } FirebaseDatabase.getInstance().getReference().child("chat").child(key).child("users").child(FirebaseAuth.getInstance().getUid()).setValue(true); FirebaseDatabase.getInstance().getReference().child("chat").child(key).child("Group Name").setValue("NoName"); } @Override public void onCancelled(@NonNull DatabaseError error) { } }); startActivity(new Intent(CreateChat.this, ChatListActivity.class) ) ; } else if(usersChosen > 1){ //will show pop up for the user to enter the name Context context = this; LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE); View popup = inflater.inflate(R.layout.pop_up_for_grpname, null); int width = LinearLayout.LayoutParams.WRAP_CONTENT; int hieght = LinearLayout.LayoutParams.WRAP_CONTENT; boolean focusable = true; final PopupWindow popupWindow = new PopupWindow(popup, width, hieght, focusable); popupWindow.showAtLocation(popup, Gravity.CENTER, 0, 0); Button enterGrpName = popup.findViewById(R.id.enterName); final EditText grpName = popup.findViewById(R.id.GrpName); enterGrpName.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { final DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference().child("chat").child(key); for(UserObject object: userObjects){ if(object.getSelected()){ FirebaseDatabase.getInstance().getReference().child("user").child(Objects.requireNonNull(FirebaseAuth.getInstance().getUid())).child("chat").child(key).setValue(true); FirebaseDatabase.getInstance().getReference().child("user").child(object.getUid()).child("chat").child(key).setValue(true); } } FirebaseDatabase.getInstance().getReference().child("chat").child(key).setValue(true); FirebaseDatabase.getInstance().getReference().child("chat").child(key).child("users").child(FirebaseAuth.getInstance().getUid()); for (UserObject object: userObjects){ if (object.getSelected()){ FirebaseDatabase.getInstance().getReference().child("chat").child(key).child("users").child(object.getUid()).setValue(true); } } FirebaseDatabase.getInstance().getReference().child("chat").child(key).child("users").child(FirebaseAuth.getInstance().getUid()).setValue(true); final DatabaseReference databaseReference1 = FirebaseDatabase.getInstance().getReference().child("chat").child(key); databaseReference1.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot snapshot) { String groupName = grpName.getText().toString(); Map<String, Object> addGrpName = new HashMap<>(); addGrpName.put("Group Name", groupName); databaseReference1.updateChildren(addGrpName); } @Override public void onCancelled(@NonNull DatabaseError error) { } }); startActivity(new Intent(CreateChat.this, ChatListActivity.class)); } }); popup.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View view, MotionEvent motionEvent) { popupWindow.dismiss(); return true; } }); } } }
UTF-8
Java
10,777
java
CreateChat.java
Java
[]
null
[]
package com.example.messanger.ChatCreation; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.view.Gravity; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.PopupWindow; import android.widget.Toast; import com.example.messanger.Chat.ChatListActivity; import com.example.messanger.R; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; public class CreateChat extends AppCompatActivity { private List<UserObject> userObjects; private Button chatCreate; private RecyclerView rv; private CreateChatAdapter adapter; private View view; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.list_of_users); userObjects = new ArrayList<>(); chatCreate = findViewById(R.id.createChat); rv = findViewById(R.id.List); rv.setNestedScrollingEnabled(true); rv.setHasFixedSize(true); adapter = new CreateChatAdapter( userObjects); rv.setAdapter(adapter); rv.setLayoutManager(new LinearLayoutManager(this)); chatCreate.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { int checked = 0; String userID = ""; for(UserObject user: userObjects){ if(user.getSelected()) { checked++; userID = user.getUid(); } } if(checked == 1 ){ boolean similar = false; for(String chatID: ChatListActivity.users){ if(chatID.equals(userID)){ Toast.makeText(CreateChat.this, "Cannot Create a Duplicate Chat", Toast.LENGTH_LONG).show(); similar = true; } } if(!similar){ CreateChat(); } } } }); final DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference().child("user"); final FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser(); databaseReference.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot snapshot) { if(snapshot.exists()){ for(DataSnapshot snapshot1: snapshot.getChildren()){ if(!(firebaseUser.getUid().equals(snapshot1.getKey()))){ String name = "none"; String email = "none"; if(snapshot1.child("email").exists()) email = snapshot1.child("email").getValue().toString(); String key = snapshot1.getKey(); if(snapshot1.child("Name").exists()) name = snapshot1.child("Name").getValue().toString(); UserObject userObject = new UserObject(email, key, name); userObjects.add(userObject); adapter = new CreateChatAdapter(userObjects); } } rv.setAdapter(adapter); adapter.notifyDataSetChanged(); } } @Override public void onCancelled(@NonNull DatabaseError error) { } }); } private void CreateChat() { int usersChosen = 0; final String key = FirebaseDatabase.getInstance().getReference().child("chat").push().getKey();// push method creates a key for(UserObject object: userObjects){ if(object.getSelected()){ usersChosen += 1; } } if(usersChosen == 1){ //will not make user enter the name String userID = ""; for (UserObject object: userObjects){ if(object.getSelected()){ if(!object.getUid().equals(FirebaseAuth.getInstance().getUid())){ userID = object.getUid(); } } } DatabaseReference databaseReference1 = FirebaseDatabase.getInstance().getReference().child("user").child(userID); databaseReference1.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot snapshot) { final DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference().child("chat").child(key); for(UserObject object: userObjects){ if(object.getSelected()){ FirebaseDatabase.getInstance().getReference().child("user").child(Objects.requireNonNull(FirebaseAuth.getInstance().getUid())).child("chat").child(key).setValue(true); FirebaseDatabase.getInstance().getReference().child("user").child(object.getUid()).child("chat").child(key).setValue(true); } } FirebaseDatabase.getInstance().getReference().child("chat").child(key).setValue(true); FirebaseDatabase.getInstance().getReference().child("chat").child(key).child("users").child(FirebaseAuth.getInstance().getUid()); for (UserObject object: userObjects){ if (object.getSelected()){ FirebaseDatabase.getInstance().getReference().child("chat").child(key).child("users").child(object.getUid()).setValue(true); } } FirebaseDatabase.getInstance().getReference().child("chat").child(key).child("users").child(FirebaseAuth.getInstance().getUid()).setValue(true); FirebaseDatabase.getInstance().getReference().child("chat").child(key).child("Group Name").setValue("NoName"); } @Override public void onCancelled(@NonNull DatabaseError error) { } }); startActivity(new Intent(CreateChat.this, ChatListActivity.class) ) ; } else if(usersChosen > 1){ //will show pop up for the user to enter the name Context context = this; LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE); View popup = inflater.inflate(R.layout.pop_up_for_grpname, null); int width = LinearLayout.LayoutParams.WRAP_CONTENT; int hieght = LinearLayout.LayoutParams.WRAP_CONTENT; boolean focusable = true; final PopupWindow popupWindow = new PopupWindow(popup, width, hieght, focusable); popupWindow.showAtLocation(popup, Gravity.CENTER, 0, 0); Button enterGrpName = popup.findViewById(R.id.enterName); final EditText grpName = popup.findViewById(R.id.GrpName); enterGrpName.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { final DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference().child("chat").child(key); for(UserObject object: userObjects){ if(object.getSelected()){ FirebaseDatabase.getInstance().getReference().child("user").child(Objects.requireNonNull(FirebaseAuth.getInstance().getUid())).child("chat").child(key).setValue(true); FirebaseDatabase.getInstance().getReference().child("user").child(object.getUid()).child("chat").child(key).setValue(true); } } FirebaseDatabase.getInstance().getReference().child("chat").child(key).setValue(true); FirebaseDatabase.getInstance().getReference().child("chat").child(key).child("users").child(FirebaseAuth.getInstance().getUid()); for (UserObject object: userObjects){ if (object.getSelected()){ FirebaseDatabase.getInstance().getReference().child("chat").child(key).child("users").child(object.getUid()).setValue(true); } } FirebaseDatabase.getInstance().getReference().child("chat").child(key).child("users").child(FirebaseAuth.getInstance().getUid()).setValue(true); final DatabaseReference databaseReference1 = FirebaseDatabase.getInstance().getReference().child("chat").child(key); databaseReference1.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot snapshot) { String groupName = grpName.getText().toString(); Map<String, Object> addGrpName = new HashMap<>(); addGrpName.put("Group Name", groupName); databaseReference1.updateChildren(addGrpName); } @Override public void onCancelled(@NonNull DatabaseError error) { } }); startActivity(new Intent(CreateChat.this, ChatListActivity.class)); } }); popup.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View view, MotionEvent motionEvent) { popupWindow.dismiss(); return true; } }); } } }
10,777
0.573536
0.57168
234
45.055557
38.844765
195
false
false
0
0
0
0
0
0
0.547009
false
false
14
a9c659f9f9fe02eab7b3b7ef27703a8369378ecd
36,713,380,480,102
691169d1acaf364b64994d3a7e3b8b79ae8806c1
/src/ShinhanDS/CodingTEST/Main3.java
a440a71f4f12d72280884b2813fb73396047eb26
[]
no_license
twooopark/Algorithm
https://github.com/twooopark/Algorithm
ba7f7a5094b6a20f8342de2ad11ab8d5619cabff
cede37de8d4658aab7d8027399a362663a287221
refs/heads/master
2020-03-20T21:10:03.940000
2018-07-10T15:02:18
2018-07-10T15:02:18
137,726,997
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package ShinhanDS.CodingTEST; //숫자는 +3, 10의 자리는 버린다. //특수문자는 그대로. //소문자는 +10 //대문자는 +5 import java.util.Scanner; public class Main3 { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String source = sc.next(); int N = source.length(); for(int i=0; i<N; i++){ char c = source.charAt(i); if('0'<=c && c<='9'){ System.out.print(((c+3-'0')%10)); } else if('a'<=c && c<='z'){ System.out.print((char)((c+10-'a')%26+'a')); } else if('A'<=c && c<='Z'){ System.out.print((char)((c+5-'A')%26+'A')); } else{ System.out.print(c); } } } } /* 2018년 하반기 신입사원 공개채용 실무능력평가 for 박두리 테스트 안내 문의하기(채팅) 도움말 컴파일 옵션 테스트 종료 알고리즘 1 알고리즘 2 알고리즘 3 알고리즘 4 알고리즘 5 문제 설명 본 문제는 표준입출력을 이용하는 문제입니다. 표준 입력(scanf 또는 input 함수)을 사용해 값을 입력받고, 표준 출력(print 함수)를 이용해 정답을 출력하세요. 마동석 선임은 정보유출 방지를 이용하여 자리를 비울 경우 PC 화면보호기를 적극 이용하고 있습니다. 그러나, 마동석 선임은 매번 비밀번호를 잊어버려 메모지에 적고 싶으나 타인이 바로 읽어 알 수 있으므로, 간단한 시저 암호(Caesar cipher)를 이용하여 적기로 하고 코드를 작성합니다. 마동석 선임이 되어 코드를 작성해 보세요. 단어 하나를 입력받아 시저 암호의 단어를 출력하는 코드를 작성하십시오. 예시를 보고 시저 암호 체계를 유추하여 작성하면 됩니다. 제한사항 1) 입력문자에서 한글은 제외합니다.(영문소문자, 영문대문자, 특수문자, 숫자만 처리) 2) 입력문자는 1단어로 제한합니다. 3) 입력문자는 100 바이트로 제한합니다. 입출력 예 Input Output Wellcome! Bovvmywo! 2018WorldCup 5341BybvnHez name88@shinhan.com xkwo11@crsxrkx.myw Solution.java import java.util.Scanner; // 숫자는 +3, 10의 자리는 버린다. // 특수문자는 그대로. // 소문자는 +10 // 대문자는 +5 public class Solution { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String source = sc.next(); int N = source.length(); for(int i=0; i<N; i++){ char c = source.charAt(i); if('0'<=c && c<='9'){ System.out.print(((c+3-'0')%10)); } else if('a'<=c && c<='z'){ System.out.print((char)((c+10-'a')%26+'a')); } else if('A'<=c && c<='Z'){ System.out.print((char)((c+5-'A')%26+'A')); } else{ System.out.print(c); } } } } 1 import java.util.Scanner; 2 // 숫자는 +3, 10의 자리는 버린다. 3 // 특수문자는 그대로. 4 // 소문자는 +10 5 // 대문자는 +5 6 public class Solution { 7 public static void main(String[] args) { 8 Scanner sc = new Scanner(System.in); 9 String source = sc.next(); 10 int N = source.length(); 11 for(int i=0; i<N; i++){ 12 char c = source.charAt(i); 13 if('0'<=c && c<='9'){ 14 System.out.print(((c+3-'0')%10)); 15 } 16 else if('a'<=c && c<='z'){ 17 System.out.print((char)((c+10-'a')%26+'a')); 18 19 } 20 else if('A'<=c && c<='Z'){ 21 System.out.print((char)((c+5-'A')%26+'A')); 22 23 } 24 else{ 25 System.out.print(c); 26 27 } 28 } 29 } 30 } 실행 결과 실행 결과가 여기에 표시됩니다. 종료까지 00:58:28 */
UTF-8
Java
4,050
java
Main3.java
Java
[ { "context": "put\nWellcome!\tBovvmywo!\n2018WorldCup\t5341BybvnHez\nname88@shinhan.com\txkwo11@crsxrkx.myw\nSolution.java\n\nimport java.uti", "end": 1415, "score": 0.999923050403595, "start": 1397, "tag": "EMAIL", "value": "name88@shinhan.com" }, { "context": "ywo!\n2018WorldCup\t5341BybvnHez\nname88@shinhan.com\txkwo11@crsxrkx.myw\nSolution.java\n\nimport java.util.Scanner;\n// 숫자는 +", "end": 1434, "score": 0.999837338924408, "start": 1416, "tag": "EMAIL", "value": "xkwo11@crsxrkx.myw" } ]
null
[]
package ShinhanDS.CodingTEST; //숫자는 +3, 10의 자리는 버린다. //특수문자는 그대로. //소문자는 +10 //대문자는 +5 import java.util.Scanner; public class Main3 { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String source = sc.next(); int N = source.length(); for(int i=0; i<N; i++){ char c = source.charAt(i); if('0'<=c && c<='9'){ System.out.print(((c+3-'0')%10)); } else if('a'<=c && c<='z'){ System.out.print((char)((c+10-'a')%26+'a')); } else if('A'<=c && c<='Z'){ System.out.print((char)((c+5-'A')%26+'A')); } else{ System.out.print(c); } } } } /* 2018년 하반기 신입사원 공개채용 실무능력평가 for 박두리 테스트 안내 문의하기(채팅) 도움말 컴파일 옵션 테스트 종료 알고리즘 1 알고리즘 2 알고리즘 3 알고리즘 4 알고리즘 5 문제 설명 본 문제는 표준입출력을 이용하는 문제입니다. 표준 입력(scanf 또는 input 함수)을 사용해 값을 입력받고, 표준 출력(print 함수)를 이용해 정답을 출력하세요. 마동석 선임은 정보유출 방지를 이용하여 자리를 비울 경우 PC 화면보호기를 적극 이용하고 있습니다. 그러나, 마동석 선임은 매번 비밀번호를 잊어버려 메모지에 적고 싶으나 타인이 바로 읽어 알 수 있으므로, 간단한 시저 암호(Caesar cipher)를 이용하여 적기로 하고 코드를 작성합니다. 마동석 선임이 되어 코드를 작성해 보세요. 단어 하나를 입력받아 시저 암호의 단어를 출력하는 코드를 작성하십시오. 예시를 보고 시저 암호 체계를 유추하여 작성하면 됩니다. 제한사항 1) 입력문자에서 한글은 제외합니다.(영문소문자, 영문대문자, 특수문자, 숫자만 처리) 2) 입력문자는 1단어로 제한합니다. 3) 입력문자는 100 바이트로 제한합니다. 입출력 예 Input Output Wellcome! Bovvmywo! 2018WorldCup 5341BybvnHez <EMAIL> <EMAIL> Solution.java import java.util.Scanner; // 숫자는 +3, 10의 자리는 버린다. // 특수문자는 그대로. // 소문자는 +10 // 대문자는 +5 public class Solution { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String source = sc.next(); int N = source.length(); for(int i=0; i<N; i++){ char c = source.charAt(i); if('0'<=c && c<='9'){ System.out.print(((c+3-'0')%10)); } else if('a'<=c && c<='z'){ System.out.print((char)((c+10-'a')%26+'a')); } else if('A'<=c && c<='Z'){ System.out.print((char)((c+5-'A')%26+'A')); } else{ System.out.print(c); } } } } 1 import java.util.Scanner; 2 // 숫자는 +3, 10의 자리는 버린다. 3 // 특수문자는 그대로. 4 // 소문자는 +10 5 // 대문자는 +5 6 public class Solution { 7 public static void main(String[] args) { 8 Scanner sc = new Scanner(System.in); 9 String source = sc.next(); 10 int N = source.length(); 11 for(int i=0; i<N; i++){ 12 char c = source.charAt(i); 13 if('0'<=c && c<='9'){ 14 System.out.print(((c+3-'0')%10)); 15 } 16 else if('a'<=c && c<='z'){ 17 System.out.print((char)((c+10-'a')%26+'a')); 18 19 } 20 else if('A'<=c && c<='Z'){ 21 System.out.print((char)((c+5-'A')%26+'A')); 22 23 } 24 else{ 25 System.out.print(c); 26 27 } 28 } 29 } 30 } 실행 결과 실행 결과가 여기에 표시됩니다. 종료까지 00:58:28 */
4,028
0.490687
0.443802
164
17.993902
16.935493
95
false
false
0
0
0
0
0
0
0.567073
false
false
14
674bdb4e9cd391779ba2ab152f59b4cdd9012194
36,713,380,478,895
325ae86a09693ed163acc716946319353a67d4d2
/xiaodong/src/bst/Node.java
c5190543b6d523fe1a6c200a9095b353d25a63e3
[]
no_license
game-of-algorithm/List
https://github.com/game-of-algorithm/List
09c6ae60a3d16239b4e51b058c5df733d09d209e
eb48b5862a0abd1e7e69636d208d78c16f42db58
refs/heads/master
2023-01-07T02:22:54.731000
2020-01-14T15:10:08
2020-01-14T15:10:08
195,077,137
0
2
null
false
2023-01-04T04:01:59
2019-07-03T15:03:13
2020-01-14T15:10:09
2023-01-04T04:01:58
1,703
0
2
22
JavaScript
false
false
package src.bst; public class Node { public Integer value; public Node left = null; public Node right = null; public Node(Integer value) { this.value = value; } }
UTF-8
Java
193
java
Node.java
Java
[]
null
[]
package src.bst; public class Node { public Integer value; public Node left = null; public Node right = null; public Node(Integer value) { this.value = value; } }
193
0.61658
0.61658
11
16.545454
12.190635
32
false
false
0
0
0
0
0
0
0.454545
false
false
14
cbd384fe6eaac8feb1081f4bcd9a34f574ff2f64
35,364,760,757,087
f58c9441c367a2adea3e7a3e51132ab181d1ead0
/utils/src/main/java/parser/Parser.java
a6acfbf23447af69012a7c5aff4f265358bca61c
[]
no_license
k0r0tk0ff/WebXlsFileViewer
https://github.com/k0r0tk0ff/WebXlsFileViewer
9ec5f762f447a504cb1c9bb0cedd45a07eb34f5a
f20ab3cde1937ab07f8c155fdcf94bbda69e2722
refs/heads/master
2020-03-22T00:46:31.765000
2018-07-02T18:34:35
2018-07-02T18:34:35
139,264,685
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package parser; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Iterator; public class Parser { private static final Logger LOG = LoggerFactory.getLogger(Parser.class); public ArrayList<ArrayList<String>> parse(String pathToFile) throws IOException { InputStream inputStream; HSSFWorkbook workbook; ArrayList<ArrayList<String>> list = new ArrayList<>(); inputStream = new FileInputStream(pathToFile); workbook = new HSSFWorkbook(inputStream); inputStream.close(); Sheet sheet = workbook.getSheetAt(0); Iterator<Row> it = sheet.iterator(); while (it.hasNext()) { Row row = it.next(); ArrayList<String> arrayList = new ArrayList<>(); for (Cell cell : row) { Enum cellType = cell.getCellTypeEnum(); switch (cellType.toString()) { case "STRING": //arrayList.add(cell.getStringCellValue()); arrayList.add(cell.getRichStringCellValue().getString()); break; case "NUMERIC": arrayList.add(String.valueOf(cell.getNumericCellValue())); break; default: break; } } list.add(arrayList); } LOG.debug("Parse success"); return list; } }
UTF-8
Java
1,763
java
Parser.java
Java
[]
null
[]
package parser; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Iterator; public class Parser { private static final Logger LOG = LoggerFactory.getLogger(Parser.class); public ArrayList<ArrayList<String>> parse(String pathToFile) throws IOException { InputStream inputStream; HSSFWorkbook workbook; ArrayList<ArrayList<String>> list = new ArrayList<>(); inputStream = new FileInputStream(pathToFile); workbook = new HSSFWorkbook(inputStream); inputStream.close(); Sheet sheet = workbook.getSheetAt(0); Iterator<Row> it = sheet.iterator(); while (it.hasNext()) { Row row = it.next(); ArrayList<String> arrayList = new ArrayList<>(); for (Cell cell : row) { Enum cellType = cell.getCellTypeEnum(); switch (cellType.toString()) { case "STRING": //arrayList.add(cell.getStringCellValue()); arrayList.add(cell.getRichStringCellValue().getString()); break; case "NUMERIC": arrayList.add(String.valueOf(cell.getNumericCellValue())); break; default: break; } } list.add(arrayList); } LOG.debug("Parse success"); return list; } }
1,763
0.588769
0.587067
52
32.903847
21.752329
85
false
false
0
0
0
0
0
0
0.634615
false
false
14
34161f56224bc796b1f016e204f9ef69bf81a075
35,210,141,929,364
47b9c68fb13e9ac666176b45a40a79cf55d14cda
/app/src/main/java/ru/smartmediasystems/smallsmarty/data/networks/res/OdataMetaData.java
b6bfed65f07ce72fcf89a15267c047c9002355cf
[]
no_license
ni032mas/Emtol
https://github.com/ni032mas/Emtol
483ca379f9ef6895c0c8bc18ff72a6bb2bb938ea
27af4e0002ec7276c1bd2b1ba964730166e0643c
refs/heads/master
2017-11-10T18:51:28.371000
2017-11-03T11:14:07
2017-11-03T11:14:07
45,353,080
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package ru.smartmediasystems.smallsmarty.data.networks.res; import com.google.gson.annotations.SerializedName; import java.util.ArrayList; import java.util.HashMap; /** * Created by aleksandr.marmyshev on 03.05.2017. */ public class OdataMetaData { @SerializedName("odata.metadata") public String odataMetadata; @SerializedName("value") public ArrayList<HashMap> value; @SerializedName("odata.error") public OdataError odataError; }
UTF-8
Java
463
java
OdataMetaData.java
Java
[ { "context": "List;\nimport java.util.HashMap;\n\n/**\n * Created by aleksandr.marmyshev on 03.05.2017.\n */\n\npublic class OdataM", "end": 195, "score": 0.7941917181015015, "start": 186, "tag": "NAME", "value": "aleksandr" }, { "context": "rt java.util.HashMap;\n\n/**\n * Created by aleksandr.marmyshev on 03.05.2017.\n */\n\npublic class OdataMe", "end": 195, "score": 0.6426811814308167, "start": 195, "tag": "USERNAME", "value": "" }, { "context": "t java.util.HashMap;\n\n/**\n * Created by aleksandr.marmyshev on 03.05.2017.\n */\n\npublic class OdataMetaData {\n", "end": 205, "score": 0.9238371253013611, "start": 196, "tag": "NAME", "value": "marmyshev" } ]
null
[]
package ru.smartmediasystems.smallsmarty.data.networks.res; import com.google.gson.annotations.SerializedName; import java.util.ArrayList; import java.util.HashMap; /** * Created by aleksandr.marmyshev on 03.05.2017. */ public class OdataMetaData { @SerializedName("odata.metadata") public String odataMetadata; @SerializedName("value") public ArrayList<HashMap> value; @SerializedName("odata.error") public OdataError odataError; }
463
0.75378
0.736501
19
23.368422
18.896423
59
false
false
0
0
0
0
0
0
0.368421
false
false
14
5d47a1be2bffc366396995bd175bbca110ef71d1
35,029,753,310,037
3b91ed788572b6d5ac4db1bee814a74560603578
/com/tencent/mm/plugin/wallet_core/ui/WalletPwdConfirmUI$4.java
d3494f35e03178ab34198c2dfbb65e305d4aeb62
[]
no_license
linsir6/WeChat_java
https://github.com/linsir6/WeChat_java
a1deee3035b555fb35a423f367eb5e3e58a17cb0
32e52b88c012051100315af6751111bfb6697a29
refs/heads/master
2020-05-31T05:40:17.161000
2018-08-28T02:07:02
2018-08-28T02:07:02
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.tencent.mm.plugin.wallet_core.ui; import android.widget.ScrollView; import com.tencent.mm.wallet_core.ui.a; class WalletPwdConfirmUI$4 implements a { final /* synthetic */ WalletPwdConfirmUI pxf; final /* synthetic */ ScrollView pxg; WalletPwdConfirmUI$4(WalletPwdConfirmUI walletPwdConfirmUI, ScrollView scrollView) { this.pxf = walletPwdConfirmUI; this.pxg = scrollView; } public final void fI(boolean z) { if (z) { WalletPwdConfirmUI.a(this.pxf, this.pxg, WalletPwdConfirmUI.b(this.pxf)); } else { this.pxg.scrollTo(0, 0); } } }
UTF-8
Java
636
java
WalletPwdConfirmUI$4.java
Java
[]
null
[]
package com.tencent.mm.plugin.wallet_core.ui; import android.widget.ScrollView; import com.tencent.mm.wallet_core.ui.a; class WalletPwdConfirmUI$4 implements a { final /* synthetic */ WalletPwdConfirmUI pxf; final /* synthetic */ ScrollView pxg; WalletPwdConfirmUI$4(WalletPwdConfirmUI walletPwdConfirmUI, ScrollView scrollView) { this.pxf = walletPwdConfirmUI; this.pxg = scrollView; } public final void fI(boolean z) { if (z) { WalletPwdConfirmUI.a(this.pxf, this.pxg, WalletPwdConfirmUI.b(this.pxf)); } else { this.pxg.scrollTo(0, 0); } } }
636
0.658805
0.652516
22
27.90909
25.121359
88
false
false
0
0
0
0
0
0
0.590909
false
false
14
7e5fc2bb57b924dbadc86b2ed59816480577d05f
38,070,590,132,676
d379d6e0322e88d8bc4333956139140aaed3f78a
/src/main/java/org/wmichina/crm/mapper/BizCourseMapper.java
1515cf3278135cbab4447653e68683963d28e813
[]
no_license
navyzh1979/wmi.smvcbatis
https://github.com/navyzh1979/wmi.smvcbatis
7bd42789f6f9b9b53e7f7ca9de8d64e9c4504083
f727eadab6b608849bc86d8513055ae3bc63e614
refs/heads/master
2021-01-02T23:13:17.702000
2012-12-19T07:20:54
2012-12-19T07:20:54
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.wmichina.crm.mapper; import java.util.List; import org.apache.ibatis.annotations.Delete; import org.apache.ibatis.annotations.DeleteProvider; import org.apache.ibatis.annotations.Insert; import org.apache.ibatis.annotations.InsertProvider; import org.apache.ibatis.annotations.Options; import org.apache.ibatis.annotations.Param; import org.apache.ibatis.annotations.Result; import org.apache.ibatis.annotations.Results; import org.apache.ibatis.annotations.Select; import org.apache.ibatis.annotations.SelectProvider; import org.apache.ibatis.annotations.Update; import org.apache.ibatis.annotations.UpdateProvider; import org.apache.ibatis.type.JdbcType; import org.springframework.stereotype.Repository; import org.wmichina.crm.entity.BizCourse; import org.wmichina.crm.entity.example.BizCourseExample; import org.wmichina.crm.provider.BizCourseSqlProvider; @Repository(value="bizCourseMapper") public interface BizCourseMapper { @SelectProvider(type=BizCourseSqlProvider.class, method="countByExample") int countByExample(BizCourseExample example); @DeleteProvider(type=BizCourseSqlProvider.class, method="deleteByExample") int deleteByExample(BizCourseExample example); @Delete({ "delete from biz_course", "where course_id = #{courseId,jdbcType=INTEGER}" }) int deleteByPrimaryKey(Integer courseId); @Insert({ "insert into biz_course (course_id, course_code, ", "course_name, course_category, ", "course_class, course_type, ", "learning_mode, learning_time, ", "learning_hours, learning_term, ", "learning_city, course_price, ", "discount_1, discount_reason_1, ", "discount_2, discount_reason_2, ", "discount_3, discount_reason_3, ", "discount_4, discount_reason_4, ", "discount_5, discount_reason_5, ", "is_valid, is_onsale, on_date, ", "off_date, remark, create_date, ", "create_user, update_date, ", "update_user, description)", "values (#{courseId,jdbcType=INTEGER}, #{courseCode,jdbcType=VARCHAR}, ", "#{courseName,jdbcType=VARCHAR}, #{courseCategory,jdbcType=VARCHAR}, ", "#{courseClass,jdbcType=VARCHAR}, #{courseType,jdbcType=VARCHAR}, ", "#{learningMode,jdbcType=VARCHAR}, #{learningTime,jdbcType=VARCHAR}, ", "#{learningHours,jdbcType=INTEGER}, #{learningTerm,jdbcType=VARCHAR}, ", "#{learningCity,jdbcType=VARCHAR}, #{coursePrice,jdbcType=DOUBLE}, ", "#{discount1,jdbcType=DOUBLE}, #{discountReason1,jdbcType=VARCHAR}, ", "#{discount2,jdbcType=DOUBLE}, #{discountReason2,jdbcType=VARCHAR}, ", "#{discount3,jdbcType=DOUBLE}, #{discountReason3,jdbcType=VARCHAR}, ", "#{discount4,jdbcType=DOUBLE}, #{discountReason4,jdbcType=VARCHAR}, ", "#{discount5,jdbcType=DOUBLE}, #{discountReason5,jdbcType=VARCHAR}, ", "#{isValid,jdbcType=BIT}, #{isOnsale,jdbcType=BIT}, #{onDate,jdbcType=DATE}, ", "#{offDate,jdbcType=DATE}, #{remark,jdbcType=VARCHAR}, #{createDate,jdbcType=TIMESTAMP}, ", "#{createUser,jdbcType=VARCHAR}, #{updateDate,jdbcType=TIMESTAMP}, ", "#{updateUser,jdbcType=VARCHAR}, #{description,jdbcType=LONGVARBINARY})" }) @Options(useGeneratedKeys=true,keyProperty="courseId") int insert(BizCourse record); @InsertProvider(type=BizCourseSqlProvider.class, method="insertSelective") @Options(useGeneratedKeys=true,keyProperty="courseId") int insertSelective(BizCourse record); @SelectProvider(type=BizCourseSqlProvider.class, method="selectByExampleWithBLOBs") @Results({ @Result(column="course_id", property="courseId", jdbcType=JdbcType.INTEGER, id=true), @Result(column="course_code", property="courseCode", jdbcType=JdbcType.VARCHAR), @Result(column="course_name", property="courseName", jdbcType=JdbcType.VARCHAR), @Result(column="course_category", property="courseCategory", jdbcType=JdbcType.VARCHAR), @Result(column="course_class", property="courseClass", jdbcType=JdbcType.VARCHAR), @Result(column="course_type", property="courseType", jdbcType=JdbcType.VARCHAR), @Result(column="learning_mode", property="learningMode", jdbcType=JdbcType.VARCHAR), @Result(column="learning_time", property="learningTime", jdbcType=JdbcType.VARCHAR), @Result(column="learning_hours", property="learningHours", jdbcType=JdbcType.INTEGER), @Result(column="learning_term", property="learningTerm", jdbcType=JdbcType.VARCHAR), @Result(column="learning_city", property="learningCity", jdbcType=JdbcType.VARCHAR), @Result(column="course_price", property="coursePrice", jdbcType=JdbcType.DOUBLE), @Result(column="discount_1", property="discount1", jdbcType=JdbcType.DOUBLE), @Result(column="discount_reason_1", property="discountReason1", jdbcType=JdbcType.VARCHAR), @Result(column="discount_2", property="discount2", jdbcType=JdbcType.DOUBLE), @Result(column="discount_reason_2", property="discountReason2", jdbcType=JdbcType.VARCHAR), @Result(column="discount_3", property="discount3", jdbcType=JdbcType.DOUBLE), @Result(column="discount_reason_3", property="discountReason3", jdbcType=JdbcType.VARCHAR), @Result(column="discount_4", property="discount4", jdbcType=JdbcType.DOUBLE), @Result(column="discount_reason_4", property="discountReason4", jdbcType=JdbcType.VARCHAR), @Result(column="discount_5", property="discount5", jdbcType=JdbcType.DOUBLE), @Result(column="discount_reason_5", property="discountReason5", jdbcType=JdbcType.VARCHAR), @Result(column="is_valid", property="isValid", jdbcType=JdbcType.BIT), @Result(column="is_onsale", property="isOnsale", jdbcType=JdbcType.BIT), @Result(column="on_date", property="onDate", jdbcType=JdbcType.DATE), @Result(column="off_date", property="offDate", jdbcType=JdbcType.DATE), @Result(column="remark", property="remark", jdbcType=JdbcType.VARCHAR), @Result(column="create_date", property="createDate", jdbcType=JdbcType.TIMESTAMP), @Result(column="create_user", property="createUser", jdbcType=JdbcType.VARCHAR), @Result(column="update_date", property="updateDate", jdbcType=JdbcType.TIMESTAMP), @Result(column="update_user", property="updateUser", jdbcType=JdbcType.VARCHAR), @Result(column="description", property="description", jdbcType=JdbcType.LONGVARBINARY) }) List<BizCourse> selectByExampleWithBLOBs(BizCourseExample example); @SelectProvider(type=BizCourseSqlProvider.class, method="selectByExample") @Results({ @Result(column="course_id", property="courseId", jdbcType=JdbcType.INTEGER, id=true), @Result(column="course_code", property="courseCode", jdbcType=JdbcType.VARCHAR), @Result(column="course_name", property="courseName", jdbcType=JdbcType.VARCHAR), @Result(column="course_category", property="courseCategory", jdbcType=JdbcType.VARCHAR), @Result(column="course_class", property="courseClass", jdbcType=JdbcType.VARCHAR), @Result(column="course_type", property="courseType", jdbcType=JdbcType.VARCHAR), @Result(column="learning_mode", property="learningMode", jdbcType=JdbcType.VARCHAR), @Result(column="learning_time", property="learningTime", jdbcType=JdbcType.VARCHAR), @Result(column="learning_hours", property="learningHours", jdbcType=JdbcType.INTEGER), @Result(column="learning_term", property="learningTerm", jdbcType=JdbcType.VARCHAR), @Result(column="learning_city", property="learningCity", jdbcType=JdbcType.VARCHAR), @Result(column="course_price", property="coursePrice", jdbcType=JdbcType.DOUBLE), @Result(column="discount_1", property="discount1", jdbcType=JdbcType.DOUBLE), @Result(column="discount_reason_1", property="discountReason1", jdbcType=JdbcType.VARCHAR), @Result(column="discount_2", property="discount2", jdbcType=JdbcType.DOUBLE), @Result(column="discount_reason_2", property="discountReason2", jdbcType=JdbcType.VARCHAR), @Result(column="discount_3", property="discount3", jdbcType=JdbcType.DOUBLE), @Result(column="discount_reason_3", property="discountReason3", jdbcType=JdbcType.VARCHAR), @Result(column="discount_4", property="discount4", jdbcType=JdbcType.DOUBLE), @Result(column="discount_reason_4", property="discountReason4", jdbcType=JdbcType.VARCHAR), @Result(column="discount_5", property="discount5", jdbcType=JdbcType.DOUBLE), @Result(column="discount_reason_5", property="discountReason5", jdbcType=JdbcType.VARCHAR), @Result(column="is_valid", property="isValid", jdbcType=JdbcType.BIT), @Result(column="is_onsale", property="isOnsale", jdbcType=JdbcType.BIT), @Result(column="on_date", property="onDate", jdbcType=JdbcType.DATE), @Result(column="off_date", property="offDate", jdbcType=JdbcType.DATE), @Result(column="remark", property="remark", jdbcType=JdbcType.VARCHAR), @Result(column="create_date", property="createDate", jdbcType=JdbcType.TIMESTAMP), @Result(column="create_user", property="createUser", jdbcType=JdbcType.VARCHAR), @Result(column="update_date", property="updateDate", jdbcType=JdbcType.TIMESTAMP), @Result(column="update_user", property="updateUser", jdbcType=JdbcType.VARCHAR) }) List<BizCourse> selectByExample(BizCourseExample example); @Select({ "select", "course_id, course_code, course_name, course_category, course_class, course_type, ", "learning_mode, learning_time, learning_hours, learning_term, learning_city, ", "course_price, discount_1, discount_reason_1, discount_2, discount_reason_2, ", "discount_3, discount_reason_3, discount_4, discount_reason_4, discount_5, discount_reason_5, ", "is_valid, is_onsale, on_date, off_date, remark, create_date, create_user, update_date, ", "update_user, description", "from biz_course", "where course_id = #{courseId,jdbcType=INTEGER}" }) @Results({ @Result(column="course_id", property="courseId", jdbcType=JdbcType.INTEGER, id=true), @Result(column="course_code", property="courseCode", jdbcType=JdbcType.VARCHAR), @Result(column="course_name", property="courseName", jdbcType=JdbcType.VARCHAR), @Result(column="course_category", property="courseCategory", jdbcType=JdbcType.VARCHAR), @Result(column="course_class", property="courseClass", jdbcType=JdbcType.VARCHAR), @Result(column="course_type", property="courseType", jdbcType=JdbcType.VARCHAR), @Result(column="learning_mode", property="learningMode", jdbcType=JdbcType.VARCHAR), @Result(column="learning_time", property="learningTime", jdbcType=JdbcType.VARCHAR), @Result(column="learning_hours", property="learningHours", jdbcType=JdbcType.INTEGER), @Result(column="learning_term", property="learningTerm", jdbcType=JdbcType.VARCHAR), @Result(column="learning_city", property="learningCity", jdbcType=JdbcType.VARCHAR), @Result(column="course_price", property="coursePrice", jdbcType=JdbcType.DOUBLE), @Result(column="discount_1", property="discount1", jdbcType=JdbcType.DOUBLE), @Result(column="discount_reason_1", property="discountReason1", jdbcType=JdbcType.VARCHAR), @Result(column="discount_2", property="discount2", jdbcType=JdbcType.DOUBLE), @Result(column="discount_reason_2", property="discountReason2", jdbcType=JdbcType.VARCHAR), @Result(column="discount_3", property="discount3", jdbcType=JdbcType.DOUBLE), @Result(column="discount_reason_3", property="discountReason3", jdbcType=JdbcType.VARCHAR), @Result(column="discount_4", property="discount4", jdbcType=JdbcType.DOUBLE), @Result(column="discount_reason_4", property="discountReason4", jdbcType=JdbcType.VARCHAR), @Result(column="discount_5", property="discount5", jdbcType=JdbcType.DOUBLE), @Result(column="discount_reason_5", property="discountReason5", jdbcType=JdbcType.VARCHAR), @Result(column="is_valid", property="isValid", jdbcType=JdbcType.BIT), @Result(column="is_onsale", property="isOnsale", jdbcType=JdbcType.BIT), @Result(column="on_date", property="onDate", jdbcType=JdbcType.DATE), @Result(column="off_date", property="offDate", jdbcType=JdbcType.DATE), @Result(column="remark", property="remark", jdbcType=JdbcType.VARCHAR), @Result(column="create_date", property="createDate", jdbcType=JdbcType.TIMESTAMP), @Result(column="create_user", property="createUser", jdbcType=JdbcType.VARCHAR), @Result(column="update_date", property="updateDate", jdbcType=JdbcType.TIMESTAMP), @Result(column="update_user", property="updateUser", jdbcType=JdbcType.VARCHAR), @Result(column="description", property="description", jdbcType=JdbcType.LONGVARBINARY) }) BizCourse selectByPrimaryKey(Integer courseId); @UpdateProvider(type=BizCourseSqlProvider.class, method="updateByExampleSelective") int updateByExampleSelective(@Param("record") BizCourse record, @Param("example") BizCourseExample example); @UpdateProvider(type=BizCourseSqlProvider.class, method="updateByExampleWithBLOBs") int updateByExampleWithBLOBs(@Param("record") BizCourse record, @Param("example") BizCourseExample example); @UpdateProvider(type=BizCourseSqlProvider.class, method="updateByExample") int updateByExample(@Param("record") BizCourse record, @Param("example") BizCourseExample example); @UpdateProvider(type=BizCourseSqlProvider.class, method="updateByPrimaryKeySelective") int updateByPrimaryKeySelective(BizCourse record); @Update({ "update biz_course", "set course_code = #{courseCode,jdbcType=VARCHAR},", "course_name = #{courseName,jdbcType=VARCHAR},", "course_category = #{courseCategory,jdbcType=VARCHAR},", "course_class = #{courseClass,jdbcType=VARCHAR},", "course_type = #{courseType,jdbcType=VARCHAR},", "learning_mode = #{learningMode,jdbcType=VARCHAR},", "learning_time = #{learningTime,jdbcType=VARCHAR},", "learning_hours = #{learningHours,jdbcType=INTEGER},", "learning_term = #{learningTerm,jdbcType=VARCHAR},", "learning_city = #{learningCity,jdbcType=VARCHAR},", "course_price = #{coursePrice,jdbcType=DOUBLE},", "discount_1 = #{discount1,jdbcType=DOUBLE},", "discount_reason_1 = #{discountReason1,jdbcType=VARCHAR},", "discount_2 = #{discount2,jdbcType=DOUBLE},", "discount_reason_2 = #{discountReason2,jdbcType=VARCHAR},", "discount_3 = #{discount3,jdbcType=DOUBLE},", "discount_reason_3 = #{discountReason3,jdbcType=VARCHAR},", "discount_4 = #{discount4,jdbcType=DOUBLE},", "discount_reason_4 = #{discountReason4,jdbcType=VARCHAR},", "discount_5 = #{discount5,jdbcType=DOUBLE},", "discount_reason_5 = #{discountReason5,jdbcType=VARCHAR},", "is_valid = #{isValid,jdbcType=BIT},", "is_onsale = #{isOnsale,jdbcType=BIT},", "on_date = #{onDate,jdbcType=DATE},", "off_date = #{offDate,jdbcType=DATE},", "remark = #{remark,jdbcType=VARCHAR},", "create_date = #{createDate,jdbcType=TIMESTAMP},", "create_user = #{createUser,jdbcType=VARCHAR},", "update_date = #{updateDate,jdbcType=TIMESTAMP},", "update_user = #{updateUser,jdbcType=VARCHAR},", "description = #{description,jdbcType=LONGVARBINARY}", "where course_id = #{courseId,jdbcType=INTEGER}" }) int updateByPrimaryKeyWithBLOBs(BizCourse record); @Update({ "update biz_course", "set course_code = #{courseCode,jdbcType=VARCHAR},", "course_name = #{courseName,jdbcType=VARCHAR},", "course_category = #{courseCategory,jdbcType=VARCHAR},", "course_class = #{courseClass,jdbcType=VARCHAR},", "course_type = #{courseType,jdbcType=VARCHAR},", "learning_mode = #{learningMode,jdbcType=VARCHAR},", "learning_time = #{learningTime,jdbcType=VARCHAR},", "learning_hours = #{learningHours,jdbcType=INTEGER},", "learning_term = #{learningTerm,jdbcType=VARCHAR},", "learning_city = #{learningCity,jdbcType=VARCHAR},", "course_price = #{coursePrice,jdbcType=DOUBLE},", "discount_1 = #{discount1,jdbcType=DOUBLE},", "discount_reason_1 = #{discountReason1,jdbcType=VARCHAR},", "discount_2 = #{discount2,jdbcType=DOUBLE},", "discount_reason_2 = #{discountReason2,jdbcType=VARCHAR},", "discount_3 = #{discount3,jdbcType=DOUBLE},", "discount_reason_3 = #{discountReason3,jdbcType=VARCHAR},", "discount_4 = #{discount4,jdbcType=DOUBLE},", "discount_reason_4 = #{discountReason4,jdbcType=VARCHAR},", "discount_5 = #{discount5,jdbcType=DOUBLE},", "discount_reason_5 = #{discountReason5,jdbcType=VARCHAR},", "is_valid = #{isValid,jdbcType=BIT},", "is_onsale = #{isOnsale,jdbcType=BIT},", "on_date = #{onDate,jdbcType=DATE},", "off_date = #{offDate,jdbcType=DATE},", "remark = #{remark,jdbcType=VARCHAR},", "create_date = #{createDate,jdbcType=TIMESTAMP},", "create_user = #{createUser,jdbcType=VARCHAR},", "update_date = #{updateDate,jdbcType=TIMESTAMP},", "update_user = #{updateUser,jdbcType=VARCHAR}", "where course_id = #{courseId,jdbcType=INTEGER}" }) int updateByPrimaryKey(BizCourse record); }
UTF-8
Java
17,871
java
BizCourseMapper.java
Java
[]
null
[]
package org.wmichina.crm.mapper; import java.util.List; import org.apache.ibatis.annotations.Delete; import org.apache.ibatis.annotations.DeleteProvider; import org.apache.ibatis.annotations.Insert; import org.apache.ibatis.annotations.InsertProvider; import org.apache.ibatis.annotations.Options; import org.apache.ibatis.annotations.Param; import org.apache.ibatis.annotations.Result; import org.apache.ibatis.annotations.Results; import org.apache.ibatis.annotations.Select; import org.apache.ibatis.annotations.SelectProvider; import org.apache.ibatis.annotations.Update; import org.apache.ibatis.annotations.UpdateProvider; import org.apache.ibatis.type.JdbcType; import org.springframework.stereotype.Repository; import org.wmichina.crm.entity.BizCourse; import org.wmichina.crm.entity.example.BizCourseExample; import org.wmichina.crm.provider.BizCourseSqlProvider; @Repository(value="bizCourseMapper") public interface BizCourseMapper { @SelectProvider(type=BizCourseSqlProvider.class, method="countByExample") int countByExample(BizCourseExample example); @DeleteProvider(type=BizCourseSqlProvider.class, method="deleteByExample") int deleteByExample(BizCourseExample example); @Delete({ "delete from biz_course", "where course_id = #{courseId,jdbcType=INTEGER}" }) int deleteByPrimaryKey(Integer courseId); @Insert({ "insert into biz_course (course_id, course_code, ", "course_name, course_category, ", "course_class, course_type, ", "learning_mode, learning_time, ", "learning_hours, learning_term, ", "learning_city, course_price, ", "discount_1, discount_reason_1, ", "discount_2, discount_reason_2, ", "discount_3, discount_reason_3, ", "discount_4, discount_reason_4, ", "discount_5, discount_reason_5, ", "is_valid, is_onsale, on_date, ", "off_date, remark, create_date, ", "create_user, update_date, ", "update_user, description)", "values (#{courseId,jdbcType=INTEGER}, #{courseCode,jdbcType=VARCHAR}, ", "#{courseName,jdbcType=VARCHAR}, #{courseCategory,jdbcType=VARCHAR}, ", "#{courseClass,jdbcType=VARCHAR}, #{courseType,jdbcType=VARCHAR}, ", "#{learningMode,jdbcType=VARCHAR}, #{learningTime,jdbcType=VARCHAR}, ", "#{learningHours,jdbcType=INTEGER}, #{learningTerm,jdbcType=VARCHAR}, ", "#{learningCity,jdbcType=VARCHAR}, #{coursePrice,jdbcType=DOUBLE}, ", "#{discount1,jdbcType=DOUBLE}, #{discountReason1,jdbcType=VARCHAR}, ", "#{discount2,jdbcType=DOUBLE}, #{discountReason2,jdbcType=VARCHAR}, ", "#{discount3,jdbcType=DOUBLE}, #{discountReason3,jdbcType=VARCHAR}, ", "#{discount4,jdbcType=DOUBLE}, #{discountReason4,jdbcType=VARCHAR}, ", "#{discount5,jdbcType=DOUBLE}, #{discountReason5,jdbcType=VARCHAR}, ", "#{isValid,jdbcType=BIT}, #{isOnsale,jdbcType=BIT}, #{onDate,jdbcType=DATE}, ", "#{offDate,jdbcType=DATE}, #{remark,jdbcType=VARCHAR}, #{createDate,jdbcType=TIMESTAMP}, ", "#{createUser,jdbcType=VARCHAR}, #{updateDate,jdbcType=TIMESTAMP}, ", "#{updateUser,jdbcType=VARCHAR}, #{description,jdbcType=LONGVARBINARY})" }) @Options(useGeneratedKeys=true,keyProperty="courseId") int insert(BizCourse record); @InsertProvider(type=BizCourseSqlProvider.class, method="insertSelective") @Options(useGeneratedKeys=true,keyProperty="courseId") int insertSelective(BizCourse record); @SelectProvider(type=BizCourseSqlProvider.class, method="selectByExampleWithBLOBs") @Results({ @Result(column="course_id", property="courseId", jdbcType=JdbcType.INTEGER, id=true), @Result(column="course_code", property="courseCode", jdbcType=JdbcType.VARCHAR), @Result(column="course_name", property="courseName", jdbcType=JdbcType.VARCHAR), @Result(column="course_category", property="courseCategory", jdbcType=JdbcType.VARCHAR), @Result(column="course_class", property="courseClass", jdbcType=JdbcType.VARCHAR), @Result(column="course_type", property="courseType", jdbcType=JdbcType.VARCHAR), @Result(column="learning_mode", property="learningMode", jdbcType=JdbcType.VARCHAR), @Result(column="learning_time", property="learningTime", jdbcType=JdbcType.VARCHAR), @Result(column="learning_hours", property="learningHours", jdbcType=JdbcType.INTEGER), @Result(column="learning_term", property="learningTerm", jdbcType=JdbcType.VARCHAR), @Result(column="learning_city", property="learningCity", jdbcType=JdbcType.VARCHAR), @Result(column="course_price", property="coursePrice", jdbcType=JdbcType.DOUBLE), @Result(column="discount_1", property="discount1", jdbcType=JdbcType.DOUBLE), @Result(column="discount_reason_1", property="discountReason1", jdbcType=JdbcType.VARCHAR), @Result(column="discount_2", property="discount2", jdbcType=JdbcType.DOUBLE), @Result(column="discount_reason_2", property="discountReason2", jdbcType=JdbcType.VARCHAR), @Result(column="discount_3", property="discount3", jdbcType=JdbcType.DOUBLE), @Result(column="discount_reason_3", property="discountReason3", jdbcType=JdbcType.VARCHAR), @Result(column="discount_4", property="discount4", jdbcType=JdbcType.DOUBLE), @Result(column="discount_reason_4", property="discountReason4", jdbcType=JdbcType.VARCHAR), @Result(column="discount_5", property="discount5", jdbcType=JdbcType.DOUBLE), @Result(column="discount_reason_5", property="discountReason5", jdbcType=JdbcType.VARCHAR), @Result(column="is_valid", property="isValid", jdbcType=JdbcType.BIT), @Result(column="is_onsale", property="isOnsale", jdbcType=JdbcType.BIT), @Result(column="on_date", property="onDate", jdbcType=JdbcType.DATE), @Result(column="off_date", property="offDate", jdbcType=JdbcType.DATE), @Result(column="remark", property="remark", jdbcType=JdbcType.VARCHAR), @Result(column="create_date", property="createDate", jdbcType=JdbcType.TIMESTAMP), @Result(column="create_user", property="createUser", jdbcType=JdbcType.VARCHAR), @Result(column="update_date", property="updateDate", jdbcType=JdbcType.TIMESTAMP), @Result(column="update_user", property="updateUser", jdbcType=JdbcType.VARCHAR), @Result(column="description", property="description", jdbcType=JdbcType.LONGVARBINARY) }) List<BizCourse> selectByExampleWithBLOBs(BizCourseExample example); @SelectProvider(type=BizCourseSqlProvider.class, method="selectByExample") @Results({ @Result(column="course_id", property="courseId", jdbcType=JdbcType.INTEGER, id=true), @Result(column="course_code", property="courseCode", jdbcType=JdbcType.VARCHAR), @Result(column="course_name", property="courseName", jdbcType=JdbcType.VARCHAR), @Result(column="course_category", property="courseCategory", jdbcType=JdbcType.VARCHAR), @Result(column="course_class", property="courseClass", jdbcType=JdbcType.VARCHAR), @Result(column="course_type", property="courseType", jdbcType=JdbcType.VARCHAR), @Result(column="learning_mode", property="learningMode", jdbcType=JdbcType.VARCHAR), @Result(column="learning_time", property="learningTime", jdbcType=JdbcType.VARCHAR), @Result(column="learning_hours", property="learningHours", jdbcType=JdbcType.INTEGER), @Result(column="learning_term", property="learningTerm", jdbcType=JdbcType.VARCHAR), @Result(column="learning_city", property="learningCity", jdbcType=JdbcType.VARCHAR), @Result(column="course_price", property="coursePrice", jdbcType=JdbcType.DOUBLE), @Result(column="discount_1", property="discount1", jdbcType=JdbcType.DOUBLE), @Result(column="discount_reason_1", property="discountReason1", jdbcType=JdbcType.VARCHAR), @Result(column="discount_2", property="discount2", jdbcType=JdbcType.DOUBLE), @Result(column="discount_reason_2", property="discountReason2", jdbcType=JdbcType.VARCHAR), @Result(column="discount_3", property="discount3", jdbcType=JdbcType.DOUBLE), @Result(column="discount_reason_3", property="discountReason3", jdbcType=JdbcType.VARCHAR), @Result(column="discount_4", property="discount4", jdbcType=JdbcType.DOUBLE), @Result(column="discount_reason_4", property="discountReason4", jdbcType=JdbcType.VARCHAR), @Result(column="discount_5", property="discount5", jdbcType=JdbcType.DOUBLE), @Result(column="discount_reason_5", property="discountReason5", jdbcType=JdbcType.VARCHAR), @Result(column="is_valid", property="isValid", jdbcType=JdbcType.BIT), @Result(column="is_onsale", property="isOnsale", jdbcType=JdbcType.BIT), @Result(column="on_date", property="onDate", jdbcType=JdbcType.DATE), @Result(column="off_date", property="offDate", jdbcType=JdbcType.DATE), @Result(column="remark", property="remark", jdbcType=JdbcType.VARCHAR), @Result(column="create_date", property="createDate", jdbcType=JdbcType.TIMESTAMP), @Result(column="create_user", property="createUser", jdbcType=JdbcType.VARCHAR), @Result(column="update_date", property="updateDate", jdbcType=JdbcType.TIMESTAMP), @Result(column="update_user", property="updateUser", jdbcType=JdbcType.VARCHAR) }) List<BizCourse> selectByExample(BizCourseExample example); @Select({ "select", "course_id, course_code, course_name, course_category, course_class, course_type, ", "learning_mode, learning_time, learning_hours, learning_term, learning_city, ", "course_price, discount_1, discount_reason_1, discount_2, discount_reason_2, ", "discount_3, discount_reason_3, discount_4, discount_reason_4, discount_5, discount_reason_5, ", "is_valid, is_onsale, on_date, off_date, remark, create_date, create_user, update_date, ", "update_user, description", "from biz_course", "where course_id = #{courseId,jdbcType=INTEGER}" }) @Results({ @Result(column="course_id", property="courseId", jdbcType=JdbcType.INTEGER, id=true), @Result(column="course_code", property="courseCode", jdbcType=JdbcType.VARCHAR), @Result(column="course_name", property="courseName", jdbcType=JdbcType.VARCHAR), @Result(column="course_category", property="courseCategory", jdbcType=JdbcType.VARCHAR), @Result(column="course_class", property="courseClass", jdbcType=JdbcType.VARCHAR), @Result(column="course_type", property="courseType", jdbcType=JdbcType.VARCHAR), @Result(column="learning_mode", property="learningMode", jdbcType=JdbcType.VARCHAR), @Result(column="learning_time", property="learningTime", jdbcType=JdbcType.VARCHAR), @Result(column="learning_hours", property="learningHours", jdbcType=JdbcType.INTEGER), @Result(column="learning_term", property="learningTerm", jdbcType=JdbcType.VARCHAR), @Result(column="learning_city", property="learningCity", jdbcType=JdbcType.VARCHAR), @Result(column="course_price", property="coursePrice", jdbcType=JdbcType.DOUBLE), @Result(column="discount_1", property="discount1", jdbcType=JdbcType.DOUBLE), @Result(column="discount_reason_1", property="discountReason1", jdbcType=JdbcType.VARCHAR), @Result(column="discount_2", property="discount2", jdbcType=JdbcType.DOUBLE), @Result(column="discount_reason_2", property="discountReason2", jdbcType=JdbcType.VARCHAR), @Result(column="discount_3", property="discount3", jdbcType=JdbcType.DOUBLE), @Result(column="discount_reason_3", property="discountReason3", jdbcType=JdbcType.VARCHAR), @Result(column="discount_4", property="discount4", jdbcType=JdbcType.DOUBLE), @Result(column="discount_reason_4", property="discountReason4", jdbcType=JdbcType.VARCHAR), @Result(column="discount_5", property="discount5", jdbcType=JdbcType.DOUBLE), @Result(column="discount_reason_5", property="discountReason5", jdbcType=JdbcType.VARCHAR), @Result(column="is_valid", property="isValid", jdbcType=JdbcType.BIT), @Result(column="is_onsale", property="isOnsale", jdbcType=JdbcType.BIT), @Result(column="on_date", property="onDate", jdbcType=JdbcType.DATE), @Result(column="off_date", property="offDate", jdbcType=JdbcType.DATE), @Result(column="remark", property="remark", jdbcType=JdbcType.VARCHAR), @Result(column="create_date", property="createDate", jdbcType=JdbcType.TIMESTAMP), @Result(column="create_user", property="createUser", jdbcType=JdbcType.VARCHAR), @Result(column="update_date", property="updateDate", jdbcType=JdbcType.TIMESTAMP), @Result(column="update_user", property="updateUser", jdbcType=JdbcType.VARCHAR), @Result(column="description", property="description", jdbcType=JdbcType.LONGVARBINARY) }) BizCourse selectByPrimaryKey(Integer courseId); @UpdateProvider(type=BizCourseSqlProvider.class, method="updateByExampleSelective") int updateByExampleSelective(@Param("record") BizCourse record, @Param("example") BizCourseExample example); @UpdateProvider(type=BizCourseSqlProvider.class, method="updateByExampleWithBLOBs") int updateByExampleWithBLOBs(@Param("record") BizCourse record, @Param("example") BizCourseExample example); @UpdateProvider(type=BizCourseSqlProvider.class, method="updateByExample") int updateByExample(@Param("record") BizCourse record, @Param("example") BizCourseExample example); @UpdateProvider(type=BizCourseSqlProvider.class, method="updateByPrimaryKeySelective") int updateByPrimaryKeySelective(BizCourse record); @Update({ "update biz_course", "set course_code = #{courseCode,jdbcType=VARCHAR},", "course_name = #{courseName,jdbcType=VARCHAR},", "course_category = #{courseCategory,jdbcType=VARCHAR},", "course_class = #{courseClass,jdbcType=VARCHAR},", "course_type = #{courseType,jdbcType=VARCHAR},", "learning_mode = #{learningMode,jdbcType=VARCHAR},", "learning_time = #{learningTime,jdbcType=VARCHAR},", "learning_hours = #{learningHours,jdbcType=INTEGER},", "learning_term = #{learningTerm,jdbcType=VARCHAR},", "learning_city = #{learningCity,jdbcType=VARCHAR},", "course_price = #{coursePrice,jdbcType=DOUBLE},", "discount_1 = #{discount1,jdbcType=DOUBLE},", "discount_reason_1 = #{discountReason1,jdbcType=VARCHAR},", "discount_2 = #{discount2,jdbcType=DOUBLE},", "discount_reason_2 = #{discountReason2,jdbcType=VARCHAR},", "discount_3 = #{discount3,jdbcType=DOUBLE},", "discount_reason_3 = #{discountReason3,jdbcType=VARCHAR},", "discount_4 = #{discount4,jdbcType=DOUBLE},", "discount_reason_4 = #{discountReason4,jdbcType=VARCHAR},", "discount_5 = #{discount5,jdbcType=DOUBLE},", "discount_reason_5 = #{discountReason5,jdbcType=VARCHAR},", "is_valid = #{isValid,jdbcType=BIT},", "is_onsale = #{isOnsale,jdbcType=BIT},", "on_date = #{onDate,jdbcType=DATE},", "off_date = #{offDate,jdbcType=DATE},", "remark = #{remark,jdbcType=VARCHAR},", "create_date = #{createDate,jdbcType=TIMESTAMP},", "create_user = #{createUser,jdbcType=VARCHAR},", "update_date = #{updateDate,jdbcType=TIMESTAMP},", "update_user = #{updateUser,jdbcType=VARCHAR},", "description = #{description,jdbcType=LONGVARBINARY}", "where course_id = #{courseId,jdbcType=INTEGER}" }) int updateByPrimaryKeyWithBLOBs(BizCourse record); @Update({ "update biz_course", "set course_code = #{courseCode,jdbcType=VARCHAR},", "course_name = #{courseName,jdbcType=VARCHAR},", "course_category = #{courseCategory,jdbcType=VARCHAR},", "course_class = #{courseClass,jdbcType=VARCHAR},", "course_type = #{courseType,jdbcType=VARCHAR},", "learning_mode = #{learningMode,jdbcType=VARCHAR},", "learning_time = #{learningTime,jdbcType=VARCHAR},", "learning_hours = #{learningHours,jdbcType=INTEGER},", "learning_term = #{learningTerm,jdbcType=VARCHAR},", "learning_city = #{learningCity,jdbcType=VARCHAR},", "course_price = #{coursePrice,jdbcType=DOUBLE},", "discount_1 = #{discount1,jdbcType=DOUBLE},", "discount_reason_1 = #{discountReason1,jdbcType=VARCHAR},", "discount_2 = #{discount2,jdbcType=DOUBLE},", "discount_reason_2 = #{discountReason2,jdbcType=VARCHAR},", "discount_3 = #{discount3,jdbcType=DOUBLE},", "discount_reason_3 = #{discountReason3,jdbcType=VARCHAR},", "discount_4 = #{discount4,jdbcType=DOUBLE},", "discount_reason_4 = #{discountReason4,jdbcType=VARCHAR},", "discount_5 = #{discount5,jdbcType=DOUBLE},", "discount_reason_5 = #{discountReason5,jdbcType=VARCHAR},", "is_valid = #{isValid,jdbcType=BIT},", "is_onsale = #{isOnsale,jdbcType=BIT},", "on_date = #{onDate,jdbcType=DATE},", "off_date = #{offDate,jdbcType=DATE},", "remark = #{remark,jdbcType=VARCHAR},", "create_date = #{createDate,jdbcType=TIMESTAMP},", "create_user = #{createUser,jdbcType=VARCHAR},", "update_date = #{updateDate,jdbcType=TIMESTAMP},", "update_user = #{updateUser,jdbcType=VARCHAR}", "where course_id = #{courseId,jdbcType=INTEGER}" }) int updateByPrimaryKey(BizCourse record); }
17,871
0.687203
0.679928
279
63.057346
28.593748
112
false
false
0
0
0
0
0
0
2.444444
false
false
14
d53bf36de0aebec67165220cafc8d9533055e239
38,388,417,712,618
3b78756c78fb8be4f886799c6dc4a06e7c845da2
/src/main/java/com/thinkgem/jeesite/common/utils/ResponseCode.java
e1c456df89e4700111170665f60e0f9bd4b55a94
[]
no_license
yinyaoyy/SnowLeopard
https://github.com/yinyaoyy/SnowLeopard
c72576447a755d9faac2efc5ac474b1f31d34a53
3b5d6bc2a2f0ca99ed3d9fc518b93a068bf4cd20
refs/heads/master
2020-04-08T15:14:53.676000
2019-01-10T07:20:36
2019-01-10T07:20:36
159,471,194
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.thinkgem.jeesite.common.utils; /** * 返回编码 * @author kakasun * @create 2018-03-11 上午8:28 */ public enum ResponseCode { SUCCESS(0,"SUCCESS"), ERROR(500,"服务器异常"), INVALID_PARAMETER(1000,"参数无效或缺失"), INVALID_API_KEY(1001,"API key无效"), INVALIDCALL_ID_PARAMETER(1003,"Call_id参数无效或已被使用"), INCORRECT_SIGNATURE(1004,"签名无效"), TOO_MANY_PARAMETERS(1005,"参数过多"), SERVICE_TEMPORARILY_UNAVAILABLE(1006,"后端服务暂时不可用"), UNSUPPORTED_OPENAPI_METHOD(1007,"Open API接口不被支持"), REQUEST_LIMIT_REACHED(1008,"应用对open api接口的调用请求数达到上限"), CODE_INVALID(1009,"验证码错误或过期"), NO_PERMISSION_TO_ACCESS_DATA(2000,"没有权限访问数据"), NEED_LOGIN(403000,"用户未登录"), PASSWORD_REEOR(403001,"账号密码不正确"), LOGINNAME_NOT_EXISTS(403002,"账号不存在,请注册"), PASSWORD_WRONG(403003,"密码不正确"), IDENTITY_ERROR_NORMAL(403004,"请使用“服务人员账号登录”"), IDENTITY_ERROR_WORKER(403005,"请使用“社会公众账号登录”"), ACT_PARAM_ERROR(9000,"流程参数不全"), BUSINESS_ID(9001,"业务主键为空"), BUSINESS_ERROR(9003,"业务操作错误"), MEDIATION_ID_PROVE(9004,"登录用户与人民调解申请无关!"), MEDIATION_NOT_LEADER(9005,"当前地区无司法所所长!"), ARTICLE_COMMENT_NOT_STAFF(9006,"该文章所属机构科室下无工作人员!"); private final int code; private final String desc; ResponseCode(int code,String desc){ this.code = code; this.desc = desc; } public int getCode(){ return code; } public String getDesc(){ return desc; } }
UTF-8
Java
1,960
java
ResponseCode.java
Java
[ { "context": "kgem.jeesite.common.utils;\n\n/**\n * 返回编码\n * @author kakasun\n * @create 2018-03-11 上午8:28\n */\npublic enum Resp", "end": 74, "score": 0.9997209906578064, "start": 67, "tag": "USERNAME", "value": "kakasun" } ]
null
[]
package com.thinkgem.jeesite.common.utils; /** * 返回编码 * @author kakasun * @create 2018-03-11 上午8:28 */ public enum ResponseCode { SUCCESS(0,"SUCCESS"), ERROR(500,"服务器异常"), INVALID_PARAMETER(1000,"参数无效或缺失"), INVALID_API_KEY(1001,"API key无效"), INVALIDCALL_ID_PARAMETER(1003,"Call_id参数无效或已被使用"), INCORRECT_SIGNATURE(1004,"签名无效"), TOO_MANY_PARAMETERS(1005,"参数过多"), SERVICE_TEMPORARILY_UNAVAILABLE(1006,"后端服务暂时不可用"), UNSUPPORTED_OPENAPI_METHOD(1007,"Open API接口不被支持"), REQUEST_LIMIT_REACHED(1008,"应用对open api接口的调用请求数达到上限"), CODE_INVALID(1009,"验证码错误或过期"), NO_PERMISSION_TO_ACCESS_DATA(2000,"没有权限访问数据"), NEED_LOGIN(403000,"用户未登录"), PASSWORD_REEOR(403001,"账号密码不正确"), LOGINNAME_NOT_EXISTS(403002,"账号不存在,请注册"), PASSWORD_WRONG(403003,"密码不正确"), IDENTITY_ERROR_NORMAL(403004,"请使用“服务人员账号登录”"), IDENTITY_ERROR_WORKER(403005,"请使用“社会公众账号登录”"), ACT_PARAM_ERROR(9000,"流程参数不全"), BUSINESS_ID(9001,"业务主键为空"), BUSINESS_ERROR(9003,"业务操作错误"), MEDIATION_ID_PROVE(9004,"登录用户与人民调解申请无关!"), MEDIATION_NOT_LEADER(9005,"当前地区无司法所所长!"), ARTICLE_COMMENT_NOT_STAFF(9006,"该文章所属机构科室下无工作人员!"); private final int code; private final String desc; ResponseCode(int code,String desc){ this.code = code; this.desc = desc; } public int getCode(){ return code; } public String getDesc(){ return desc; } }
1,960
0.603053
0.529898
50
30.440001
19.069515
62
false
false
0
0
0
0
0
0
1.12
false
false
14
67df7b9edd1ed355513841dce41cf47e7d6f5fe6
38,706,245,323,875
cf3381752cbd6c599926da28843937e5b024b2e6
/src/main/java/com/wechat/bookinglecture/dao/writedao/TabCollegeWritedaoMapper.java
4432669929940089d9973686970ac18bf9f6c291
[]
no_license
wengui/bookinglecture
https://github.com/wengui/bookinglecture
0b9115fd41973a39404ba88bbaea44ac109e46bd
931ea19ba3278cf39528899fdcaab4236ce5e015
refs/heads/master
2019-12-02T03:40:02.418000
2016-10-21T15:21:50
2016-10-21T15:21:50
54,611,519
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.wechat.bookinglecture.dao.writedao; import com.wechat.bookinglecture.bean.gen.TabCollege; public interface TabCollegeWritedaoMapper { int deleteByPrimaryKey(Integer collegeid); int insert(TabCollege record); int insertSelective(TabCollege record); int updateByPrimaryKeySelective(TabCollege record); int updateByPrimaryKey(TabCollege record); }
UTF-8
Java
396
java
TabCollegeWritedaoMapper.java
Java
[]
null
[]
package com.wechat.bookinglecture.dao.writedao; import com.wechat.bookinglecture.bean.gen.TabCollege; public interface TabCollegeWritedaoMapper { int deleteByPrimaryKey(Integer collegeid); int insert(TabCollege record); int insertSelective(TabCollege record); int updateByPrimaryKeySelective(TabCollege record); int updateByPrimaryKey(TabCollege record); }
396
0.770202
0.770202
15
24.533333
23.240387
55
false
false
0
0
0
0
0
0
0.466667
false
false
14
cded460b2b3bbb716cd52b2138486a94df1646fd
24,240,795,478,556
47db57a0fbbc9ad4f4ff34f34dfc1546a878f29d
/src/main/java/com/xcosy/java/io/netty/task/NettyServerTaskQueueHandler.java
675588d553178abb1303d5edb8d5020558087915
[]
no_license
code-dancing/java
https://github.com/code-dancing/java
e4df296a592a4c77ba51739df519b9dbb211854a
32a8df8eaa2bbabf7d3c7312d19c21d263937d4a
refs/heads/master
2021-04-05T06:12:08.304000
2020-07-04T09:17:33
2020-07-04T09:17:33
248,528,062
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.xcosy.java.io.netty.task; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; import io.netty.util.CharsetUtil; import java.util.concurrent.TimeUnit; /** * 目的: * 了解Netty中NioEventLoop的taskQueue、scheduleTaskQueue */ public class NettyServerTaskQueueHandler extends ChannelInboundHandlerAdapter { /** * 读取客户端发送的数据 */ @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { System.out.println("server ctx = " + ctx); // 将msg转成一个ByteBuf(这个类是Netty提供的,不是NIO的ByteBuffer) // ByteBuf性能更高 ByteBuf buf = (ByteBuf) msg; System.out.println("客户端发送消息是: " + buf.toString(CharsetUtil.UTF_8)); System.out.println("客户端地址: " + ctx.channel().remoteAddress()); } /** * 数据读取完毕 */ @Override public void channelReadComplete(ChannelHandlerContext ctx) throws Exception { ctx.writeAndFlush(Unpooled.copiedBuffer("Hello, Client!", CharsetUtil.UTF_8)); // 将耗时任务加入该channel对应的NioEventLoop的taskQueue中,异步执行,不会导致NettyServer阻塞 // TaskQueue中的任务会依次执行 ctx.channel().eventLoop().execute(() -> { try { Thread.sleep(10 * 1000); ctx.writeAndFlush(Unpooled.copiedBuffer("Hello 2", CharsetUtil.UTF_8)); } catch (InterruptedException e) { e.printStackTrace(); } }); ctx.channel().eventLoop().execute(() -> { try { Thread.sleep(10 * 1000); ctx.writeAndFlush(Unpooled.copiedBuffer("Hello 3", CharsetUtil.UTF_8)); } catch (InterruptedException e) { e.printStackTrace(); } }); // 用户自定义定时任务,该任务提交到scheduleTaskQueue中 // 指定定时时间 ctx.channel().eventLoop().schedule(() -> { try { Thread.sleep(10 * 1000); ctx.writeAndFlush(Unpooled.copiedBuffer("Hello 3", CharsetUtil.UTF_8)); } catch (InterruptedException e) { e.printStackTrace(); } }, 10, TimeUnit.SECONDS); } /** * 处理异常,如果有异常需要关闭通道 */ @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { cause.printStackTrace(); ctx.close(); } }
UTF-8
Java
2,726
java
NettyServerTaskQueueHandler.java
Java
[]
null
[]
package com.xcosy.java.io.netty.task; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; import io.netty.util.CharsetUtil; import java.util.concurrent.TimeUnit; /** * 目的: * 了解Netty中NioEventLoop的taskQueue、scheduleTaskQueue */ public class NettyServerTaskQueueHandler extends ChannelInboundHandlerAdapter { /** * 读取客户端发送的数据 */ @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { System.out.println("server ctx = " + ctx); // 将msg转成一个ByteBuf(这个类是Netty提供的,不是NIO的ByteBuffer) // ByteBuf性能更高 ByteBuf buf = (ByteBuf) msg; System.out.println("客户端发送消息是: " + buf.toString(CharsetUtil.UTF_8)); System.out.println("客户端地址: " + ctx.channel().remoteAddress()); } /** * 数据读取完毕 */ @Override public void channelReadComplete(ChannelHandlerContext ctx) throws Exception { ctx.writeAndFlush(Unpooled.copiedBuffer("Hello, Client!", CharsetUtil.UTF_8)); // 将耗时任务加入该channel对应的NioEventLoop的taskQueue中,异步执行,不会导致NettyServer阻塞 // TaskQueue中的任务会依次执行 ctx.channel().eventLoop().execute(() -> { try { Thread.sleep(10 * 1000); ctx.writeAndFlush(Unpooled.copiedBuffer("Hello 2", CharsetUtil.UTF_8)); } catch (InterruptedException e) { e.printStackTrace(); } }); ctx.channel().eventLoop().execute(() -> { try { Thread.sleep(10 * 1000); ctx.writeAndFlush(Unpooled.copiedBuffer("Hello 3", CharsetUtil.UTF_8)); } catch (InterruptedException e) { e.printStackTrace(); } }); // 用户自定义定时任务,该任务提交到scheduleTaskQueue中 // 指定定时时间 ctx.channel().eventLoop().schedule(() -> { try { Thread.sleep(10 * 1000); ctx.writeAndFlush(Unpooled.copiedBuffer("Hello 3", CharsetUtil.UTF_8)); } catch (InterruptedException e) { e.printStackTrace(); } }, 10, TimeUnit.SECONDS); } /** * 处理异常,如果有异常需要关闭通道 */ @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { cause.printStackTrace(); ctx.close(); } }
2,726
0.602929
0.591538
79
30.113924
27.069992
94
false
false
0
0
0
0
0
0
0.443038
false
false
14
fcf9ab823dc0b4f76ec67cdb18fbdd480edc69e5
39,032,662,802,418
1db6dec4751c2a7efdfe2226146deacb10dd4833
/LFC_Lista02_Final/src/testes/testeSequencia.java
0972fc4788b46da08171f311d19e7f6461e77005
[]
no_license
alanvss/LFC
https://github.com/alanvss/LFC
c12e59ba4bc13f8177091b3c0d5a87b95d14e80e
3e26cddebc3d3a38668da25f952a297d5320b4a0
refs/heads/master
2021-01-23T05:45:15.192000
2014-02-26T00:45:05
2014-02-26T00:45:05
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package testes; import tratadores.Gramatica; import tratadores.Primeiro; import tratadores.Sequencia; public class testeSequencia { public static void main(String[] args) { //Gramatica g = new Gramatica("A->A+T, A->T, T->TxF, T->F, T->E, F->(A), F->n"); Gramatica g = new Gramatica("S->I#,I->Ti,i->+Ti,i->-Ti,i->E,T->Ft,t->*Ft,t->/Ft,t->E,F->c,F->(I)"); Primeiro primeiro = new Primeiro(g); Sequencia sequencia = new Sequencia(primeiro, g); sequencia.imprimir(); } }
UTF-8
Java
510
java
testeSequencia.java
Java
[]
null
[]
package testes; import tratadores.Gramatica; import tratadores.Primeiro; import tratadores.Sequencia; public class testeSequencia { public static void main(String[] args) { //Gramatica g = new Gramatica("A->A+T, A->T, T->TxF, T->F, T->E, F->(A), F->n"); Gramatica g = new Gramatica("S->I#,I->Ti,i->+Ti,i->-Ti,i->E,T->Ft,t->*Ft,t->/Ft,t->E,F->c,F->(I)"); Primeiro primeiro = new Primeiro(g); Sequencia sequencia = new Sequencia(primeiro, g); sequencia.imprimir(); } }
510
0.617647
0.617647
20
23.5
27.938326
101
false
false
0
0
0
0
0
0
2.05
false
false
14
d60703727967bb22800621d050c618dbfdd560fe
25,220,048,028,777
4b41128cdde105057f8cb668720b8e57cf66dcea
/src/main/java/PDB/PDB/ReadXMLFile.java
65a05a4defd20316914713202f97c9f0ea0ea3a2
[]
no_license
hobayam/gp
https://github.com/hobayam/gp
55e5576c77594913e29f667c76913174efbe641d
7516b92356eaf08193eaa9774bb2161abf4a128f
refs/heads/master
2021-01-01T16:46:32.427000
2017-07-21T07:15:46
2017-07-21T07:15:46
97,916,199
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package PDB.PDB; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.DocumentBuilder; import org.w3c.dom.Document; import org.w3c.dom.NodeList; import org.w3c.dom.Node; import org.w3c.dom.Element; import java.io.File; import java.util.ArrayList; import java.util.Comparator; class Ascending implements Comparator<Double> { public int compare(Double d1, Double d2){ return d1.compareTo(d2); } } class Descending implements Comparator<Double> { public int compare(Double d1, Double d2){ return d2.compareTo(d1); } } public class ReadXMLFile { public String[] pdbIDArray; //public double[] eValueArray; public ArrayList<Double> eValueArray; public String sss; private static String getTagValue(String sTag, Element eElement){ NodeList nlList = eElement.getElementsByTagName(sTag).item(0).getChildNodes(); Node nValue = (Node)nlList.item(0); return nValue.getNodeValue(); } /* public static void main(String args[]){ try{ File XMLFile = new File("C:\\16OODP\\eclipse\\workspace\\PDBTest\\test.xml"); DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); Document doc = dBuilder.parse(XMLFile); doc.getDocumentElement().normalize(); NodeList nList = doc.getElementsByTagName("Hit"); String[] pdbIDArray = new String[nList.getLength()]; for(int i = 0; i < nList.getLength(); i++){ Node nNode = nList.item(i); if(nNode.getNodeType() == Node.ELEMENT_NODE){ Element eElement = (Element)nNode; //System.out.println(getTagValue("Hit_def", eElement).substring(0, 4)); pdbIDArray[i] = getTagValue("Hit_def", eElement).substring(0, 4); System.out.println(pdbIDArray[i]); } } } catch(Exception e){ e.printStackTrace(); } } */ public ReadXMLFile() { try{ File XMLFile = new File("test1.xml"); DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); Document doc = dBuilder.parse(XMLFile); doc.getDocumentElement().normalize(); NodeList nList = doc.getElementsByTagName("Hit"); NodeList nList2 = doc.getElementsByTagName("Hsp"); pdbIDArray = new String[nList.getLength()]; eValueArray = new ArrayList<Double>(nList2.getLength()); for(int i = 0; i < nList.getLength(); i++){ Node nNode = nList.item(i); Node nNode2 = nList2.item(i); if(nNode.getNodeType() == Node.ELEMENT_NODE){ Element eElement = (Element)nNode; //System.out.println(getTagValue("Hit_def", eElement).substring(0, 4)); pdbIDArray[i] = getTagValue("Hit_def", eElement).substring(0, 4); System.out.println(pdbIDArray[i]); } if(nNode2.getNodeType() == Node.ELEMENT_NODE){ Element eElement2 = (Element)nNode2; eValueArray.add(Double.parseDouble(getTagValue("Hsp_evalue", eElement2).substring(0, 11))); //System.out.println(eValueArray.get(i)); } } } catch(Exception e){ e.printStackTrace(); } Ascending as = new Ascending(); Descending ds = new Descending(); eValueArray.sort(ds); for(int i = 0; i < eValueArray.size(); i++) System.out.println(eValueArray.get(i)); } public String getPDBID() { return pdbIDArray[0]; } }
UTF-8
Java
3,293
java
ReadXMLFile.java
Java
[]
null
[]
package PDB.PDB; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.DocumentBuilder; import org.w3c.dom.Document; import org.w3c.dom.NodeList; import org.w3c.dom.Node; import org.w3c.dom.Element; import java.io.File; import java.util.ArrayList; import java.util.Comparator; class Ascending implements Comparator<Double> { public int compare(Double d1, Double d2){ return d1.compareTo(d2); } } class Descending implements Comparator<Double> { public int compare(Double d1, Double d2){ return d2.compareTo(d1); } } public class ReadXMLFile { public String[] pdbIDArray; //public double[] eValueArray; public ArrayList<Double> eValueArray; public String sss; private static String getTagValue(String sTag, Element eElement){ NodeList nlList = eElement.getElementsByTagName(sTag).item(0).getChildNodes(); Node nValue = (Node)nlList.item(0); return nValue.getNodeValue(); } /* public static void main(String args[]){ try{ File XMLFile = new File("C:\\16OODP\\eclipse\\workspace\\PDBTest\\test.xml"); DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); Document doc = dBuilder.parse(XMLFile); doc.getDocumentElement().normalize(); NodeList nList = doc.getElementsByTagName("Hit"); String[] pdbIDArray = new String[nList.getLength()]; for(int i = 0; i < nList.getLength(); i++){ Node nNode = nList.item(i); if(nNode.getNodeType() == Node.ELEMENT_NODE){ Element eElement = (Element)nNode; //System.out.println(getTagValue("Hit_def", eElement).substring(0, 4)); pdbIDArray[i] = getTagValue("Hit_def", eElement).substring(0, 4); System.out.println(pdbIDArray[i]); } } } catch(Exception e){ e.printStackTrace(); } } */ public ReadXMLFile() { try{ File XMLFile = new File("test1.xml"); DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); Document doc = dBuilder.parse(XMLFile); doc.getDocumentElement().normalize(); NodeList nList = doc.getElementsByTagName("Hit"); NodeList nList2 = doc.getElementsByTagName("Hsp"); pdbIDArray = new String[nList.getLength()]; eValueArray = new ArrayList<Double>(nList2.getLength()); for(int i = 0; i < nList.getLength(); i++){ Node nNode = nList.item(i); Node nNode2 = nList2.item(i); if(nNode.getNodeType() == Node.ELEMENT_NODE){ Element eElement = (Element)nNode; //System.out.println(getTagValue("Hit_def", eElement).substring(0, 4)); pdbIDArray[i] = getTagValue("Hit_def", eElement).substring(0, 4); System.out.println(pdbIDArray[i]); } if(nNode2.getNodeType() == Node.ELEMENT_NODE){ Element eElement2 = (Element)nNode2; eValueArray.add(Double.parseDouble(getTagValue("Hsp_evalue", eElement2).substring(0, 11))); //System.out.println(eValueArray.get(i)); } } } catch(Exception e){ e.printStackTrace(); } Ascending as = new Ascending(); Descending ds = new Descending(); eValueArray.sort(ds); for(int i = 0; i < eValueArray.size(); i++) System.out.println(eValueArray.get(i)); } public String getPDBID() { return pdbIDArray[0]; } }
3,293
0.695415
0.683268
113
28.097345
23.715111
96
false
false
0
0
0
0
0
0
2.716814
false
false
14
dbd2ef51189a844f1195cce2f581b6f93cdff36c
38,397,007,658,164
f463dd3a6bd73a32364d76f0c6377e7e880f5e49
/src/main/java/com/ncs/iframe4/ps/to/UpdateFormBean.java
4dec8c74c7a1065e85a814184316a0d4b839ae93
[]
no_license
togetherworks/Procurement-System
https://github.com/togetherworks/Procurement-System
2d623375fb63e40c44bb5c5b7906065609eac2d3
768afd46d29e49d7e8ffa5e8d626d3c117206922
refs/heads/master
2021-01-22T06:40:21.262000
2014-05-22T06:04:19
2014-05-22T06:04:19
12,610,464
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.ncs.iframe4.ps.to; import java.util.List; import javax.faces.event.ComponentSystemEvent; import org.springframework.beans.BeanUtils; import com.ncs.iframe4.jsf.component.codelookup.entity.CodeLookup; import com.ncs.iframe4.jsf.component.codelookup.service.CodeLookupService; import com.ncs.iframe4.ps.po.Customer; import com.ncs.iframe4.ps.service.CustomerService; /** * Created by IntelliJ IDEA. * User: qinjun * Date: 12-1-16 * Time: 上�7:35 * To change this template use File | Settings | File Templates. */ public class UpdateFormBean extends CustomerFormTO { private static final long serialVersionUID = 0L; private List<CodeLookup> industryList = null; private CustomerService customerService; private CodeLookupService codeLookupService; public CodeLookupService getCodeLookupService() { return codeLookupService; } public void setCodeLookupService(CodeLookupService codeLookupService) { this.codeLookupService = codeLookupService; } public List<CodeLookup> getIndustryList() { if (industryList == null) { industryList = codeLookupService.getCodes("industry", "true", "TBL_SAMPLE_INDUSTRY", "INDUSTRY_ID", "INDUSTRY_DESC", true, null, null, null); } return industryList; } public void setIndustryList(List<CodeLookup> industryList) { this.industryList = industryList; } public CustomerService getCustomerService() { return customerService; } public void setCustomerService(CustomerService customerService) { this.customerService = customerService; } public void preRenderView(ComponentSystemEvent event) { String customerId = this.getCustomerId(); Customer customer = customerService.findById(customerId); BeanUtils.copyProperties(customer, this); } }
UTF-8
Java
1,932
java
UpdateFormBean.java
Java
[ { "context": "ce;\r\n\r\n/**\r\n * Created by IntelliJ IDEA.\r\n * User: qinjun\r\n * Date: 12-1-16\r\n * Time: 上�7:35\r\n * To cha", "end": 445, "score": 0.9995571970939636, "start": 439, "tag": "USERNAME", "value": "qinjun" } ]
null
[]
package com.ncs.iframe4.ps.to; import java.util.List; import javax.faces.event.ComponentSystemEvent; import org.springframework.beans.BeanUtils; import com.ncs.iframe4.jsf.component.codelookup.entity.CodeLookup; import com.ncs.iframe4.jsf.component.codelookup.service.CodeLookupService; import com.ncs.iframe4.ps.po.Customer; import com.ncs.iframe4.ps.service.CustomerService; /** * Created by IntelliJ IDEA. * User: qinjun * Date: 12-1-16 * Time: 上�7:35 * To change this template use File | Settings | File Templates. */ public class UpdateFormBean extends CustomerFormTO { private static final long serialVersionUID = 0L; private List<CodeLookup> industryList = null; private CustomerService customerService; private CodeLookupService codeLookupService; public CodeLookupService getCodeLookupService() { return codeLookupService; } public void setCodeLookupService(CodeLookupService codeLookupService) { this.codeLookupService = codeLookupService; } public List<CodeLookup> getIndustryList() { if (industryList == null) { industryList = codeLookupService.getCodes("industry", "true", "TBL_SAMPLE_INDUSTRY", "INDUSTRY_ID", "INDUSTRY_DESC", true, null, null, null); } return industryList; } public void setIndustryList(List<CodeLookup> industryList) { this.industryList = industryList; } public CustomerService getCustomerService() { return customerService; } public void setCustomerService(CustomerService customerService) { this.customerService = customerService; } public void preRenderView(ComponentSystemEvent event) { String customerId = this.getCustomerId(); Customer customer = customerService.findById(customerId); BeanUtils.copyProperties(customer, this); } }
1,932
0.704416
0.697143
60
30.083334
29.222874
153
false
false
0
0
0
0
0
0
0.55
false
false
14
b03266c61be25271022b9648b6270165155e46fe
2,405,181,703,381
a874ce520a9e21c1abf304e316f3d08f5e58e67b
/src/main/java/com/example/demo/controller/MainController.java
0c673440b3e8054cf81ad80322dfa5f372d78d97
[]
no_license
Cyn1que/GreetingDeployment
https://github.com/Cyn1que/GreetingDeployment
bb4efb45c7eac2276ce28a35cfc7c7c61083e488
6083f8664529ea8006cb6409e1b691815ab51e03
refs/heads/master
2020-04-11T07:36:46.730000
2018-12-13T10:42:00
2018-12-13T10:42:00
161,616,559
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.demo.controller; import com.example.demo.model.Greeting; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class MainController { @GetMapping("/") public Greeting getGreeting() { return new Greeting("Will this run automatically?"); } }
UTF-8
Java
374
java
MainController.java
Java
[]
null
[]
package com.example.demo.controller; import com.example.demo.model.Greeting; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class MainController { @GetMapping("/") public Greeting getGreeting() { return new Greeting("Will this run automatically?"); } }
374
0.762032
0.762032
14
25.714285
22.495804
62
false
false
0
0
0
0
0
0
0.357143
false
false
14
31e1779ac0fdfc45b29ff3c6b24bdbdb95cc17b3
27,822,798,158,511
92225460ebca1bb6a594d77b6559b3629b7a94fa
/src/com/kingdee/eas/fdc/sellhouse/LoanNotarizeEnum.java
9e0431b7baf388e2106da520d2c1d7d29e3c709c
[]
no_license
yangfan0725/sd
https://github.com/yangfan0725/sd
45182d34575381be3bbdd55f3f68854a6900a362
39ebad6e2eb76286d551a9e21967f3f5dc4880da
refs/heads/master
2023-04-29T01:56:43.770000
2023-04-24T05:41:13
2023-04-24T05:41:13
512,073,641
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
/** * output package name */ package com.kingdee.eas.fdc.sellhouse; import java.util.Map; import java.util.List; import java.util.Iterator; import com.kingdee.util.enums.StringEnum; /** * output class name */ public class LoanNotarizeEnum extends StringEnum { public static final String NOTNOTARIZE_VALUE = "1NotNotarize"; public static final String NOTARIZED_VALUE = "2Notarized"; public static final LoanNotarizeEnum notNotarize = new LoanNotarizeEnum("notNotarize", NOTNOTARIZE_VALUE); public static final LoanNotarizeEnum notarized = new LoanNotarizeEnum("notarized", NOTARIZED_VALUE); /** * construct function * @param String loanNotarizeEnum */ private LoanNotarizeEnum(String name, String loanNotarizeEnum) { super(name, loanNotarizeEnum); } /** * getEnum function * @param String arguments */ public static LoanNotarizeEnum getEnum(String loanNotarizeEnum) { return (LoanNotarizeEnum)getEnum(LoanNotarizeEnum.class, loanNotarizeEnum); } /** * getEnumMap function */ public static Map getEnumMap() { return getEnumMap(LoanNotarizeEnum.class); } /** * getEnumList function */ public static List getEnumList() { return getEnumList(LoanNotarizeEnum.class); } /** * getIterator function */ public static Iterator iterator() { return iterator(LoanNotarizeEnum.class); } }
UTF-8
Java
1,491
java
LoanNotarizeEnum.java
Java
[]
null
[]
/** * output package name */ package com.kingdee.eas.fdc.sellhouse; import java.util.Map; import java.util.List; import java.util.Iterator; import com.kingdee.util.enums.StringEnum; /** * output class name */ public class LoanNotarizeEnum extends StringEnum { public static final String NOTNOTARIZE_VALUE = "1NotNotarize"; public static final String NOTARIZED_VALUE = "2Notarized"; public static final LoanNotarizeEnum notNotarize = new LoanNotarizeEnum("notNotarize", NOTNOTARIZE_VALUE); public static final LoanNotarizeEnum notarized = new LoanNotarizeEnum("notarized", NOTARIZED_VALUE); /** * construct function * @param String loanNotarizeEnum */ private LoanNotarizeEnum(String name, String loanNotarizeEnum) { super(name, loanNotarizeEnum); } /** * getEnum function * @param String arguments */ public static LoanNotarizeEnum getEnum(String loanNotarizeEnum) { return (LoanNotarizeEnum)getEnum(LoanNotarizeEnum.class, loanNotarizeEnum); } /** * getEnumMap function */ public static Map getEnumMap() { return getEnumMap(LoanNotarizeEnum.class); } /** * getEnumList function */ public static List getEnumList() { return getEnumList(LoanNotarizeEnum.class); } /** * getIterator function */ public static Iterator iterator() { return iterator(LoanNotarizeEnum.class); } }
1,491
0.670691
0.669349
63
22.682539
25.692829
110
false
false
0
0
0
0
0
0
0.301587
false
false
14
0074a9f512f7e15ba76b1a8e2ad2c38782e79da2
27,822,798,157,585
2ea61804f97c31b9f5b79d871d9c3cc2526c084f
/admin-service/src/main/java/com/spsolutions/grand/service/UserService.java
66ddd1212206a6a2ad705b68685940e2677ef67b
[]
no_license
rasinduroohansa/workflow-api
https://github.com/rasinduroohansa/workflow-api
0bbb76ff67cb7eafcc125adf508b711aea79a6a0
bdba7982d0d0dc806948b180b802da1a77de7a0c
refs/heads/master
2021-09-04T00:47:52.571000
2018-01-13T15:14:27
2018-01-13T15:14:30
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.spsolutions.grand.service; import com.spsolutions.grand.dao.AllocatedSystemFeature; import com.spsolutions.grand.dao.SystemFeature; import com.spsolutions.grand.domain.*; import com.spsolutions.grand.mappers.MenuMapper; import com.spsolutions.grand.mappers.SystemFeatureMapper; import com.spsolutions.grand.mappers.UserMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Service; import java.util.HashSet; import java.util.List; import java.util.Set; /** * @author Stelan Briyan */ @Service public class UserService { @Autowired private UserMapper userMapper; @Autowired private MenuMapper menuMapper; @Autowired private SystemFeatureMapper featureMapper; public List<Role> findRoleByUsername(String username) { return userMapper.findRoleByUsername(username); } public List<User> findAllUsers() { return userMapper.findAllUsers(); } public void activateUser(Long id) { userMapper.activateUser(id); } public void deactivateUser(Long id) { userMapper.deactivateUser(id); } public void saveRole(Role role) { userMapper.saveRole(role); } public List<User> findActiveUsers() { return userMapper.findActiveUsers(); } public List<Role> findActiveRole() { return userMapper.findActiveRole(); } public List<Long> findUserRoleMapper(Long id) { return userMapper.findUserRoleMapperIds(id); } public void assignRole(Long roleId, Long userId, Boolean status) { MapperUserRole userRole = userMapper.findRoleMapper(roleId, userId); if (userRole == null) { userMapper.assignRole(roleId, userId); } else { userMapper.updateRoleAssign(roleId, userId, status); } } public List<Menu> findMenus(Long roleId) { List<Menu> menus = menuMapper.findMenus(roleId); if (menus.size() > 0) { menus.stream().forEach(value -> { value.setSubMenu(menuMapper.findSubMenuByMenuId(roleId, value.getId())); }); } return menus; } public void assignMenuToRole(Long roleId, Long menuId, Boolean status) { MapperMenu mapperMenu = menuMapper.findMenu(roleId, menuId); if (mapperMenu == null) { menuMapper.assignMenuToRole(roleId, menuId); } else { mapperMenu.setActivated(status); menuMapper.updateMenuMapper(mapperMenu); } } public void assignSubMenuToRole(Long roleId, Long subMenuId, Boolean status) { MapperMenu mapperMenu = menuMapper.findSubMenu(roleId, subMenuId); if (mapperMenu == null) { menuMapper.assignSubMenuToRole(roleId, subMenuId); } else { mapperMenu.setActivated(status); menuMapper.updateMenuMapper(mapperMenu); } } public User findUser(String username) { return userMapper.findUser(username); } public void updateUser(User user) { PasswordEncoder passwordEncoder = new BCryptPasswordEncoder(); user.setPassword(passwordEncoder.encode(user.getPassword())); userMapper.updateUser(user); } public void saveUser(User user) { PasswordEncoder passwordEncoder = new BCryptPasswordEncoder(); user.setPassword(passwordEncoder.encode("123456")); userMapper.saveUser(user); } public List<String> findAccessCode(String username) { return featureMapper.findAccessCode(username); } public Set<User> findUsersByAccessCode(String code) { Set<User> users = new HashSet<>(); List<User> usersR = featureMapper.findUsersByAccessCodeR(code); users.addAll(usersR); List<User> usersU = featureMapper.findUsersByAccessCodeU(code); users.addAll(usersU); users.remove(null); return users; } public List<SystemFeature> findSystemFeatures() { return featureMapper.findSystemFeatures(); } public List<AllocatedSystemFeature> findPrivillegesByUserId(Long fkUser) { return featureMapper.findPrivillegesByUserId(fkUser); } public void savePrivileges(AllocatedSystemFeature feature) { AllocatedSystemFeature systemFeature = featureMapper.findPrivileges(feature.getFkSystemFeatures(), feature.getFkUser()); if (systemFeature == null) { featureMapper.savePrivileges(feature); } else { systemFeature.setRead(feature.isRead()); systemFeature.setWrite(feature.isWrite()); systemFeature.setDelete(feature.isDelete()); systemFeature.setUpdate(feature.isUpdate()); featureMapper.updatePrivileges(systemFeature); } } public void deletePrivilege(Long id) { featureMapper.deletePrivilege(id); } public Set<User> findUsersByRoleGroup(String code) { return userMapper.findUsersByRoleGroup(code); } }
UTF-8
Java
5,163
java
UserService.java
Java
[ { "context": "a.util.List;\nimport java.util.Set;\n\n/**\n * @author Stelan Briyan\n */\n@Service\npublic class UserService {\n\n @Aut", "end": 693, "score": 0.9998583197593689, "start": 680, "tag": "NAME", "value": "Stelan Briyan" }, { "context": "\n user.setPassword(passwordEncoder.encode(\"123456\"));\n userMapper.saveUser(user);\n }\n\n ", "end": 3561, "score": 0.9993927478790283, "start": 3555, "tag": "PASSWORD", "value": "123456" } ]
null
[]
package com.spsolutions.grand.service; import com.spsolutions.grand.dao.AllocatedSystemFeature; import com.spsolutions.grand.dao.SystemFeature; import com.spsolutions.grand.domain.*; import com.spsolutions.grand.mappers.MenuMapper; import com.spsolutions.grand.mappers.SystemFeatureMapper; import com.spsolutions.grand.mappers.UserMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Service; import java.util.HashSet; import java.util.List; import java.util.Set; /** * @author <NAME> */ @Service public class UserService { @Autowired private UserMapper userMapper; @Autowired private MenuMapper menuMapper; @Autowired private SystemFeatureMapper featureMapper; public List<Role> findRoleByUsername(String username) { return userMapper.findRoleByUsername(username); } public List<User> findAllUsers() { return userMapper.findAllUsers(); } public void activateUser(Long id) { userMapper.activateUser(id); } public void deactivateUser(Long id) { userMapper.deactivateUser(id); } public void saveRole(Role role) { userMapper.saveRole(role); } public List<User> findActiveUsers() { return userMapper.findActiveUsers(); } public List<Role> findActiveRole() { return userMapper.findActiveRole(); } public List<Long> findUserRoleMapper(Long id) { return userMapper.findUserRoleMapperIds(id); } public void assignRole(Long roleId, Long userId, Boolean status) { MapperUserRole userRole = userMapper.findRoleMapper(roleId, userId); if (userRole == null) { userMapper.assignRole(roleId, userId); } else { userMapper.updateRoleAssign(roleId, userId, status); } } public List<Menu> findMenus(Long roleId) { List<Menu> menus = menuMapper.findMenus(roleId); if (menus.size() > 0) { menus.stream().forEach(value -> { value.setSubMenu(menuMapper.findSubMenuByMenuId(roleId, value.getId())); }); } return menus; } public void assignMenuToRole(Long roleId, Long menuId, Boolean status) { MapperMenu mapperMenu = menuMapper.findMenu(roleId, menuId); if (mapperMenu == null) { menuMapper.assignMenuToRole(roleId, menuId); } else { mapperMenu.setActivated(status); menuMapper.updateMenuMapper(mapperMenu); } } public void assignSubMenuToRole(Long roleId, Long subMenuId, Boolean status) { MapperMenu mapperMenu = menuMapper.findSubMenu(roleId, subMenuId); if (mapperMenu == null) { menuMapper.assignSubMenuToRole(roleId, subMenuId); } else { mapperMenu.setActivated(status); menuMapper.updateMenuMapper(mapperMenu); } } public User findUser(String username) { return userMapper.findUser(username); } public void updateUser(User user) { PasswordEncoder passwordEncoder = new BCryptPasswordEncoder(); user.setPassword(passwordEncoder.encode(user.getPassword())); userMapper.updateUser(user); } public void saveUser(User user) { PasswordEncoder passwordEncoder = new BCryptPasswordEncoder(); user.setPassword(passwordEncoder.encode("<PASSWORD>")); userMapper.saveUser(user); } public List<String> findAccessCode(String username) { return featureMapper.findAccessCode(username); } public Set<User> findUsersByAccessCode(String code) { Set<User> users = new HashSet<>(); List<User> usersR = featureMapper.findUsersByAccessCodeR(code); users.addAll(usersR); List<User> usersU = featureMapper.findUsersByAccessCodeU(code); users.addAll(usersU); users.remove(null); return users; } public List<SystemFeature> findSystemFeatures() { return featureMapper.findSystemFeatures(); } public List<AllocatedSystemFeature> findPrivillegesByUserId(Long fkUser) { return featureMapper.findPrivillegesByUserId(fkUser); } public void savePrivileges(AllocatedSystemFeature feature) { AllocatedSystemFeature systemFeature = featureMapper.findPrivileges(feature.getFkSystemFeatures(), feature.getFkUser()); if (systemFeature == null) { featureMapper.savePrivileges(feature); } else { systemFeature.setRead(feature.isRead()); systemFeature.setWrite(feature.isWrite()); systemFeature.setDelete(feature.isDelete()); systemFeature.setUpdate(feature.isUpdate()); featureMapper.updatePrivileges(systemFeature); } } public void deletePrivilege(Long id) { featureMapper.deletePrivilege(id); } public Set<User> findUsersByRoleGroup(String code) { return userMapper.findUsersByRoleGroup(code); } }
5,160
0.678869
0.677513
168
29.732143
26.175114
128
false
false
0
0
0
0
0
0
0.488095
false
false
14
aebe8e418486b9f19281940dd10cf840b9046b9d
25,099,788,895,166
e21a51da82ce4a9fc46e7c7a6ff14b2833bd0ea1
/src/by/gomelagro/outcoming/properties/ApplicationProperties.java
a5d2f6a1963828cb7553519b2c4d7d9b11d3a792
[]
no_license
mcfloonyloo/EInvVatOutcoming
https://github.com/mcfloonyloo/EInvVatOutcoming
34739cbb050acff3103f0e906bcaa71987eccf85
8516d7b5472058ddfa17b35fb21b344a3db86ac6
refs/heads/master
2021-01-12T06:03:04.313000
2017-08-11T13:39:32
2017-08-11T13:39:32
77,282,198
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package by.gomelagro.outcoming.properties; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Properties; import javax.swing.JOptionPane; import by.gomelagro.outcoming.gui.db.ConnectionDB; /** * * @author mcfloonyloo * @version 0.3 * */ public class ApplicationProperties {//паттерн Singleton //блок Singleton private static volatile ApplicationProperties instance; public static void setInstance(ApplicationProperties instance){ApplicationProperties.instance = instance;} private ApplicationProperties(){} public static ApplicationProperties getInstance() { ApplicationProperties localInstance = instance; if(localInstance == null){ synchronized (ConnectionDB.class) { localInstance = instance; if(localInstance == null){ File file = new File(PROPFILENAME); if(!file.exists()){ instance = localInstance = ApplicationProperties.Builder.getInstance().build(); instance.saveProperties(); }else{ instance = localInstance = ApplicationProperties.Builder.getInstance().build(); } } } } return localInstance; } //блок ApplicationProperties public static final String PROPFILENAME = "resources/application.properties"; private String libraryPath; //путь к файлам dll папки Avest Java Provider private String classPath; //путь к файлам .class проекта private String filePath; //путь к файлу выгрузки списка private String dbPath; //путь к базе данных private String folderInvoicePath; //путь к папке с ЭСЧФ private String folderXsdPath; //путь к папке с шаблонами XSD private String urlService; //сетевой путь к сервису ЭСЧФ private boolean loadfileMenuitem; //отображение пункта меню Загрузить файл public String getLibraryPath(){return this.libraryPath;} public void setLibraryPath(String libraryPath){this.libraryPath = libraryPath;} public String getClassPath(){return this.classPath;} public void setClassPath(String classPath){this.classPath = classPath;} public String getFilePath(){return this.filePath;} public void setFilePath(String filePath){this.filePath = filePath;} public String getDbPath(){return this.dbPath;} public void setDbPath(String dbPath){this.dbPath = dbPath;} public String getFolderInvoicePath(){return this.folderInvoicePath;} public void setFolderInvoicePath(String folderInvoicePath){this.folderInvoicePath = folderInvoicePath;} public String getFolderXsdPath(){return this.folderXsdPath;} public void setFolderXsdPath(String folderXsdPath){this.folderXsdPath = folderXsdPath;} public String getUrlService(){return this.urlService;} public void setUrlService(String urlService){this.urlService = urlService;} public boolean getLoadfileMenuitem(){return this.loadfileMenuitem;} public void setLoadfileMenuitem(boolean loadfileMenuitem){this.loadfileMenuitem = loadfileMenuitem;} private ApplicationProperties(Builder build){ this.libraryPath = build.libraryPath; this.classPath = build.classPath; this.filePath = build.filePath; this.dbPath = build.dbPath; this.folderInvoicePath = build.folderInvoicePath; this.folderXsdPath = build.folderXsdPath; this.urlService = build.urlService; this.loadfileMenuitem = build.loadfileMenuitem; } public void saveProperties(){ try{ Properties properties = new Properties(); properties.setProperty("path.library", this.libraryPath); properties.setProperty("path.class", this.classPath); properties.setProperty("path.file", this.filePath); properties.setProperty("path.db", this.dbPath); properties.setProperty("path.folder.invoice",this.folderInvoicePath); properties.setProperty("path.folder.xsd", this.folderXsdPath); properties.setProperty("url.service", this.urlService); properties.setProperty("menuitem.loadfile", String.valueOf(this.loadfileMenuitem)); File file = new File(PROPFILENAME); OutputStream out = new FileOutputStream(file); properties.store(out, ""); JOptionPane.showMessageDialog(null, "Изменения настроек завершены","Информация",JOptionPane.INFORMATION_MESSAGE); }catch(Exception e){ JOptionPane.showMessageDialog(null, e.getLocalizedMessage(),"Ошибка",JOptionPane.ERROR_MESSAGE); } } public final static class Builder{ private final static Builder instance = new Builder(); private String libraryPath; private String classPath; private String filePath; private String dbPath; private String folderInvoicePath; private String folderXsdPath; private String urlService; private boolean loadfileMenuitem; public static Builder getInstance(){ return instance; } private Builder(){/*Singleton*/} private Builder loadProperties() throws FileNotFoundException{ Properties prop = new Properties(); String propFileName = PROPFILENAME; try { File file = new File(propFileName); if(file.exists()){ InputStream inputStream = new FileInputStream(file); prop.load(inputStream); this.libraryPath = prop.getProperty("path.library"); this.classPath = prop.getProperty("path.class"); this.filePath = prop.getProperty("path.file"); this.dbPath = prop.getProperty("path.db"); this.folderInvoicePath = prop.getProperty("path.folder.invoice"); this.folderXsdPath = prop.getProperty("path.folder.xsd"); this.urlService = prop.getProperty("url.service"); this.loadfileMenuitem = Boolean.valueOf(prop.getProperty("menuitem.loadfile")); return this; } else{ JOptionPane.showMessageDialog(null, "Файл настроек не обнаружен."+System.lineSeparator()+"Будут загружены стандартные настройки","Внимание",JOptionPane.WARNING_MESSAGE); this.libraryPath = "C:\\Program Files\\Avest\\AvJCEProv\\win32;"; this.classPath = ".\\lib\\*;C:\\Program Files\\Avest\\AvJCEProv\\*;"; this.filePath = "output.txt"; this.dbPath = "database.sqlite "; this.folderInvoicePath = "C:\\"; this.folderXsdPath = ".\\xsd\\"; this.urlService = "https://ws.vat.gov.by:443/InvoicesWS/services/InvoicesPort?wsdl"; this.loadfileMenuitem = false; return this; } } catch (IOException e) { JOptionPane.showMessageDialog(null, e.getLocalizedMessage(),"Ошибка",JOptionPane.ERROR_MESSAGE); this.libraryPath = ""; this.classPath = ""; this.filePath = ""; this.dbPath = ""; this.folderInvoicePath = ""; this.folderXsdPath = ""; this.urlService = ""; this.loadfileMenuitem = false; return this; } } public ApplicationProperties build(){ try { loadProperties(); } catch (FileNotFoundException e) { JOptionPane.showMessageDialog(null, e.getLocalizedMessage(),"Ошибка",JOptionPane.ERROR_MESSAGE); } return new ApplicationProperties(this); } } public boolean equals(ApplicationPropertiesTemp temp){ if(temp == null){return false;} if(!ApplicationPropertiesTemp.class.isAssignableFrom(temp.getClass())){return false;} if((this.getLibraryPath() == null)?(temp.getLibraryPath() != null):!this.getLibraryPath().trim().equals(temp.getLibraryPath().trim().trim())){return false;} if((this.getClassPath() == null)?(temp.getClassPath() != null):!this.getClassPath().trim().equals(temp.getClassPath().trim())){return false;} if((this.getFilePath() == null)?(temp.getFilePath() != null):!this.getFilePath().trim().equals(temp.getFilePath().trim())){return false;} if((this.getDbPath() == null)?(temp.getDbPath() != null):!this.getDbPath().trim().equals(temp.getDbPath().trim())){return false;} if((this.getFolderInvoicePath() == null)?(temp.getFolderInvoicePath() != null):!this.getFolderInvoicePath().trim().equals(temp.getFolderInvoicePath().trim())){return false;} if((this.getFolderXsdPath() == null)?(temp.getFolderXsdPath() != null):!this.getFolderXsdPath().trim().equals(temp.getFolderXsdPath().trim())){return false;} if((this.getUrlService() == null)?(temp.getUrlService() != null):!this.getUrlService().trim().equals(temp.getUrlService().trim())){return false;} if(this.getLoadfileMenuitem() != temp.getLoadfileMenuitem()){return false;} return true; } }
WINDOWS-1251
Java
8,837
java
ApplicationProperties.java
Java
[ { "context": "oming.gui.db.ConnectionDB;\r\n\r\n/**\r\n * \r\n * @author mcfloonyloo\r\n * @version 0.3\r\n *\r\n */\r\n\r\npublic class Applica", "end": 417, "score": 0.999602735042572, "start": 406, "tag": "USERNAME", "value": "mcfloonyloo" } ]
null
[]
package by.gomelagro.outcoming.properties; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Properties; import javax.swing.JOptionPane; import by.gomelagro.outcoming.gui.db.ConnectionDB; /** * * @author mcfloonyloo * @version 0.3 * */ public class ApplicationProperties {//паттерн Singleton //блок Singleton private static volatile ApplicationProperties instance; public static void setInstance(ApplicationProperties instance){ApplicationProperties.instance = instance;} private ApplicationProperties(){} public static ApplicationProperties getInstance() { ApplicationProperties localInstance = instance; if(localInstance == null){ synchronized (ConnectionDB.class) { localInstance = instance; if(localInstance == null){ File file = new File(PROPFILENAME); if(!file.exists()){ instance = localInstance = ApplicationProperties.Builder.getInstance().build(); instance.saveProperties(); }else{ instance = localInstance = ApplicationProperties.Builder.getInstance().build(); } } } } return localInstance; } //блок ApplicationProperties public static final String PROPFILENAME = "resources/application.properties"; private String libraryPath; //путь к файлам dll папки Avest Java Provider private String classPath; //путь к файлам .class проекта private String filePath; //путь к файлу выгрузки списка private String dbPath; //путь к базе данных private String folderInvoicePath; //путь к папке с ЭСЧФ private String folderXsdPath; //путь к папке с шаблонами XSD private String urlService; //сетевой путь к сервису ЭСЧФ private boolean loadfileMenuitem; //отображение пункта меню Загрузить файл public String getLibraryPath(){return this.libraryPath;} public void setLibraryPath(String libraryPath){this.libraryPath = libraryPath;} public String getClassPath(){return this.classPath;} public void setClassPath(String classPath){this.classPath = classPath;} public String getFilePath(){return this.filePath;} public void setFilePath(String filePath){this.filePath = filePath;} public String getDbPath(){return this.dbPath;} public void setDbPath(String dbPath){this.dbPath = dbPath;} public String getFolderInvoicePath(){return this.folderInvoicePath;} public void setFolderInvoicePath(String folderInvoicePath){this.folderInvoicePath = folderInvoicePath;} public String getFolderXsdPath(){return this.folderXsdPath;} public void setFolderXsdPath(String folderXsdPath){this.folderXsdPath = folderXsdPath;} public String getUrlService(){return this.urlService;} public void setUrlService(String urlService){this.urlService = urlService;} public boolean getLoadfileMenuitem(){return this.loadfileMenuitem;} public void setLoadfileMenuitem(boolean loadfileMenuitem){this.loadfileMenuitem = loadfileMenuitem;} private ApplicationProperties(Builder build){ this.libraryPath = build.libraryPath; this.classPath = build.classPath; this.filePath = build.filePath; this.dbPath = build.dbPath; this.folderInvoicePath = build.folderInvoicePath; this.folderXsdPath = build.folderXsdPath; this.urlService = build.urlService; this.loadfileMenuitem = build.loadfileMenuitem; } public void saveProperties(){ try{ Properties properties = new Properties(); properties.setProperty("path.library", this.libraryPath); properties.setProperty("path.class", this.classPath); properties.setProperty("path.file", this.filePath); properties.setProperty("path.db", this.dbPath); properties.setProperty("path.folder.invoice",this.folderInvoicePath); properties.setProperty("path.folder.xsd", this.folderXsdPath); properties.setProperty("url.service", this.urlService); properties.setProperty("menuitem.loadfile", String.valueOf(this.loadfileMenuitem)); File file = new File(PROPFILENAME); OutputStream out = new FileOutputStream(file); properties.store(out, ""); JOptionPane.showMessageDialog(null, "Изменения настроек завершены","Информация",JOptionPane.INFORMATION_MESSAGE); }catch(Exception e){ JOptionPane.showMessageDialog(null, e.getLocalizedMessage(),"Ошибка",JOptionPane.ERROR_MESSAGE); } } public final static class Builder{ private final static Builder instance = new Builder(); private String libraryPath; private String classPath; private String filePath; private String dbPath; private String folderInvoicePath; private String folderXsdPath; private String urlService; private boolean loadfileMenuitem; public static Builder getInstance(){ return instance; } private Builder(){/*Singleton*/} private Builder loadProperties() throws FileNotFoundException{ Properties prop = new Properties(); String propFileName = PROPFILENAME; try { File file = new File(propFileName); if(file.exists()){ InputStream inputStream = new FileInputStream(file); prop.load(inputStream); this.libraryPath = prop.getProperty("path.library"); this.classPath = prop.getProperty("path.class"); this.filePath = prop.getProperty("path.file"); this.dbPath = prop.getProperty("path.db"); this.folderInvoicePath = prop.getProperty("path.folder.invoice"); this.folderXsdPath = prop.getProperty("path.folder.xsd"); this.urlService = prop.getProperty("url.service"); this.loadfileMenuitem = Boolean.valueOf(prop.getProperty("menuitem.loadfile")); return this; } else{ JOptionPane.showMessageDialog(null, "Файл настроек не обнаружен."+System.lineSeparator()+"Будут загружены стандартные настройки","Внимание",JOptionPane.WARNING_MESSAGE); this.libraryPath = "C:\\Program Files\\Avest\\AvJCEProv\\win32;"; this.classPath = ".\\lib\\*;C:\\Program Files\\Avest\\AvJCEProv\\*;"; this.filePath = "output.txt"; this.dbPath = "database.sqlite "; this.folderInvoicePath = "C:\\"; this.folderXsdPath = ".\\xsd\\"; this.urlService = "https://ws.vat.gov.by:443/InvoicesWS/services/InvoicesPort?wsdl"; this.loadfileMenuitem = false; return this; } } catch (IOException e) { JOptionPane.showMessageDialog(null, e.getLocalizedMessage(),"Ошибка",JOptionPane.ERROR_MESSAGE); this.libraryPath = ""; this.classPath = ""; this.filePath = ""; this.dbPath = ""; this.folderInvoicePath = ""; this.folderXsdPath = ""; this.urlService = ""; this.loadfileMenuitem = false; return this; } } public ApplicationProperties build(){ try { loadProperties(); } catch (FileNotFoundException e) { JOptionPane.showMessageDialog(null, e.getLocalizedMessage(),"Ошибка",JOptionPane.ERROR_MESSAGE); } return new ApplicationProperties(this); } } public boolean equals(ApplicationPropertiesTemp temp){ if(temp == null){return false;} if(!ApplicationPropertiesTemp.class.isAssignableFrom(temp.getClass())){return false;} if((this.getLibraryPath() == null)?(temp.getLibraryPath() != null):!this.getLibraryPath().trim().equals(temp.getLibraryPath().trim().trim())){return false;} if((this.getClassPath() == null)?(temp.getClassPath() != null):!this.getClassPath().trim().equals(temp.getClassPath().trim())){return false;} if((this.getFilePath() == null)?(temp.getFilePath() != null):!this.getFilePath().trim().equals(temp.getFilePath().trim())){return false;} if((this.getDbPath() == null)?(temp.getDbPath() != null):!this.getDbPath().trim().equals(temp.getDbPath().trim())){return false;} if((this.getFolderInvoicePath() == null)?(temp.getFolderInvoicePath() != null):!this.getFolderInvoicePath().trim().equals(temp.getFolderInvoicePath().trim())){return false;} if((this.getFolderXsdPath() == null)?(temp.getFolderXsdPath() != null):!this.getFolderXsdPath().trim().equals(temp.getFolderXsdPath().trim())){return false;} if((this.getUrlService() == null)?(temp.getUrlService() != null):!this.getUrlService().trim().equals(temp.getUrlService().trim())){return false;} if(this.getLoadfileMenuitem() != temp.getLoadfileMenuitem()){return false;} return true; } }
8,837
0.712345
0.711525
218
37.155964
35.846943
175
false
false
0
0
0
0
0
0
3.151376
false
false
14
325637c00de1594ebe5aae116408317f813c2685
17,549,236,391,323
744752de1302921bd994101e44152c353ba32b54
/src/objects/RigidBody.java
6a4efe93bfec4f6414288ebc35f483386d5a347c
[]
no_license
Mukilan1600/java-physics-engine
https://github.com/Mukilan1600/java-physics-engine
04777f2d26fc64cbf8d802f04f2de52362cbd115
21a1fc221c7bfbfbc823ce725405c913a623ef3a
refs/heads/master
2023-07-14T06:44:25.706000
2021-08-28T15:48:35
2021-08-28T15:48:35
400,711,238
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package objects; public abstract class RigidBody implements GraphicObject, Collidable { double mass; double massInverse; double inertia; double inertiaInverse; Vector2 position; Vector2 velocity; double angularVelocity; Type type; boolean isStatic; Vector2[] vertices; public RigidBody(double mass, Vector2 position, Vector2 velocity, Type type, boolean isStatic) { this.mass = mass; this.position = position; this.velocity = velocity; this.type = type; this.isStatic = isStatic; if(isStatic) massInverse = 0f; else massInverse = 1f/mass; } public void move(double frameInterval, Vector2 gravity){ if(!isStatic) { Vector2 correctedg = Vector2Utils.multiply(gravity,frameInterval); velocity = Vector2Utils.add(velocity,correctedg); position = Vector2Utils.add(position, Vector2Utils.multiply(velocity, frameInterval)); if (angularVelocity != 0 && type==Type.POLYGON) { rotateVertices(angularVelocity * frameInterval); } } } void rotateVertices(double angle){ // x = x*cosa - y*sina // y = x*sina + y*cosa double cosa = Math.cos(angle); double sina = Math.sin(angle); for(int i=0;i<vertices.length;i++){ Vector2 vertex = vertices[i]; double x = vertex.x*cosa - vertex.y*sina; double y = vertex.x*sina + vertex.y*cosa; vertices[i] = new Vector2(x,y); } } public void move(Vector2 dPosition){ position = Vector2Utils.add(position,dPosition); } public void moveTo(Vector2 newPosition){ position = newPosition; } public void accelerate(Vector2 dVelocity){ velocity = Vector2Utils.add(velocity,dVelocity); } public void accelerateAngular(double dVelocity){ if(!isStatic) angularVelocity += dVelocity; } }
UTF-8
Java
2,016
java
RigidBody.java
Java
[]
null
[]
package objects; public abstract class RigidBody implements GraphicObject, Collidable { double mass; double massInverse; double inertia; double inertiaInverse; Vector2 position; Vector2 velocity; double angularVelocity; Type type; boolean isStatic; Vector2[] vertices; public RigidBody(double mass, Vector2 position, Vector2 velocity, Type type, boolean isStatic) { this.mass = mass; this.position = position; this.velocity = velocity; this.type = type; this.isStatic = isStatic; if(isStatic) massInverse = 0f; else massInverse = 1f/mass; } public void move(double frameInterval, Vector2 gravity){ if(!isStatic) { Vector2 correctedg = Vector2Utils.multiply(gravity,frameInterval); velocity = Vector2Utils.add(velocity,correctedg); position = Vector2Utils.add(position, Vector2Utils.multiply(velocity, frameInterval)); if (angularVelocity != 0 && type==Type.POLYGON) { rotateVertices(angularVelocity * frameInterval); } } } void rotateVertices(double angle){ // x = x*cosa - y*sina // y = x*sina + y*cosa double cosa = Math.cos(angle); double sina = Math.sin(angle); for(int i=0;i<vertices.length;i++){ Vector2 vertex = vertices[i]; double x = vertex.x*cosa - vertex.y*sina; double y = vertex.x*sina + vertex.y*cosa; vertices[i] = new Vector2(x,y); } } public void move(Vector2 dPosition){ position = Vector2Utils.add(position,dPosition); } public void moveTo(Vector2 newPosition){ position = newPosition; } public void accelerate(Vector2 dVelocity){ velocity = Vector2Utils.add(velocity,dVelocity); } public void accelerateAngular(double dVelocity){ if(!isStatic) angularVelocity += dVelocity; } }
2,016
0.608631
0.597718
70
27.799999
23.753256
100
false
false
0
0
0
0
0
0
0.671429
false
false
14
9f812fa76da7cd83570953df461528be0e2fe15f
7,318,624,298,912
13d1f75197f2115b2503555d0e3b19645f92a177
/src/main/java/service/OfferService.java
1c6565dc77b1580cd97b6d7563861b164a726007
[]
no_license
Bartosz-D3V/zopa-technical-test
https://github.com/Bartosz-D3V/zopa-technical-test
1bfae893538d3dd84efa4356a3460d5a3dd22d62
0ed6c054388ce6785e7e1ae27fe99c5282e8351a
refs/heads/master
2023-04-10T19:39:14.977000
2019-07-07T09:24:24
2019-07-07T09:24:24
194,924,798
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package service; import domain.Offer; import domain.Quote; import java.util.ArrayList; import java.util.Collections; import java.util.List; public class OfferService { public static List<Offer> selectOffers(final List<Offer> availableOffers, final double amount) { OfferService.validateAmount(amount); if (availableOffers.stream().map(Offer::getAvailable).reduce(0d, Double::sum) < amount) return null; Collections.sort(availableOffers); final List<Offer> offers = new ArrayList<>(); double amountToBorrow = amount; for (final Offer offer : availableOffers) { final double available = offer.getAvailable(); if (available < amountToBorrow) { offers.add(offer); amountToBorrow -= available; } else if (available >= amountToBorrow) { offers.add(new Offer(offer.getLender(), offer.getRate(), amountToBorrow)); offer.setAvailable(available - amountToBorrow); break; } else break; } return offers; } public static Quote getQuote(final List<Offer> selectedOffers) { final double monthlyPayment = selectedOffers.stream().mapToDouble(offer -> LoanService.calculateMonthlyPayment(offer.getAvailable(), offer.getRate(), 36)).sum(); return new Quote.QuoteBuilder() .setTotalAmount(selectedOffers.stream().map(Offer::getAvailable).reduce(0d, Double::sum)) .setRate(LoanService.getWeightedLoanRate(selectedOffers)) .setMonthlyRepayment(monthlyPayment) .setTotalRepayment(monthlyPayment * 36) .build(); } private static void validateAmount(final double amount) { if (amount < 1000 || amount > 15000) { throw new IllegalArgumentException("Requested amount has to be between £1000 and £15000"); } if (amount % 100 != 0) { throw new IllegalArgumentException("Requested amount must be multiplicity of £100"); } } }
UTF-8
Java
1,879
java
OfferService.java
Java
[]
null
[]
package service; import domain.Offer; import domain.Quote; import java.util.ArrayList; import java.util.Collections; import java.util.List; public class OfferService { public static List<Offer> selectOffers(final List<Offer> availableOffers, final double amount) { OfferService.validateAmount(amount); if (availableOffers.stream().map(Offer::getAvailable).reduce(0d, Double::sum) < amount) return null; Collections.sort(availableOffers); final List<Offer> offers = new ArrayList<>(); double amountToBorrow = amount; for (final Offer offer : availableOffers) { final double available = offer.getAvailable(); if (available < amountToBorrow) { offers.add(offer); amountToBorrow -= available; } else if (available >= amountToBorrow) { offers.add(new Offer(offer.getLender(), offer.getRate(), amountToBorrow)); offer.setAvailable(available - amountToBorrow); break; } else break; } return offers; } public static Quote getQuote(final List<Offer> selectedOffers) { final double monthlyPayment = selectedOffers.stream().mapToDouble(offer -> LoanService.calculateMonthlyPayment(offer.getAvailable(), offer.getRate(), 36)).sum(); return new Quote.QuoteBuilder() .setTotalAmount(selectedOffers.stream().map(Offer::getAvailable).reduce(0d, Double::sum)) .setRate(LoanService.getWeightedLoanRate(selectedOffers)) .setMonthlyRepayment(monthlyPayment) .setTotalRepayment(monthlyPayment * 36) .build(); } private static void validateAmount(final double amount) { if (amount < 1000 || amount > 15000) { throw new IllegalArgumentException("Requested amount has to be between £1000 and £15000"); } if (amount % 100 != 0) { throw new IllegalArgumentException("Requested amount must be multiplicity of £100"); } } }
1,879
0.705224
0.688699
50
36.52
34.278412
165
false
false
0
0
0
0
0
0
0.64
false
false
14
e89bb435bdda11e182c163a46477d4c6c5b12569
2,748,779,092,534
05a6b639335fa7169d0f6ceb8cbe2a49615b5cc4
/src/main/java/com/glqdlt/myho/webapp/model/item/Article.java
2108af95ddf87e9fa12e62e23e65aa7690f60499
[]
no_license
glqdlt/myho
https://github.com/glqdlt/myho
48a8daf894212356339e3d04dac53c9d2bc2d108
1c0c876df922c7a4bba91c3f604f9e5b9fc3a81d
refs/heads/master
2023-03-02T23:12:06.623000
2020-10-14T07:37:01
2020-10-14T07:37:01
301,326,884
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.glqdlt.myho.webapp.model.item; import com.glqdlt.myho.api.Item; import java.util.Collections; public class Article extends Item { private String title; private String writer; public Article() { setAttributes(Collections.singletonList(new ArticleBoardAttribute(0))); } public String getWriter() { return writer; } public void setWriter(String writer) { this.writer = writer; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } @Override public String getName() { return getTitle(); } @Override public void setName(String name) { setTitle(name); } @Override public String getItemTypeName() { return "Article"; } }
UTF-8
Java
836
java
Article.java
Java
[]
null
[]
package com.glqdlt.myho.webapp.model.item; import com.glqdlt.myho.api.Item; import java.util.Collections; public class Article extends Item { private String title; private String writer; public Article() { setAttributes(Collections.singletonList(new ArticleBoardAttribute(0))); } public String getWriter() { return writer; } public void setWriter(String writer) { this.writer = writer; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } @Override public String getName() { return getTitle(); } @Override public void setName(String name) { setTitle(name); } @Override public String getItemTypeName() { return "Article"; } }
836
0.618421
0.617225
46
17.173914
16.955574
79
false
false
0
0
0
0
0
0
0.282609
false
false
14
4ed64758535c89af649219df5630c2a26f72caf9
7,834,020,373,032
e4f8d6814646a1325fb5dbc0b94fc04b837ff464
/grupo-01-01/src/suPropiedadRaiz/empresa/ListaUnidades.java
58653c08249ea25f63d2f786d2ce6e429b2e358a
[]
no_license
kanequito2/Trabajo-1-POO
https://github.com/kanequito2/Trabajo-1-POO
e1e506e6c4cfcfeb3df70828940762712423dc29
7ff1a27dfd703f7972ab8a161a0f87e4da2f605c
refs/heads/master
2021-06-12T12:42:54.372000
2016-10-21T14:48:10
2016-10-21T14:48:10
68,243,786
1
1
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * Autor: Cristian * Almacena todas las Unidades */ package suPropiedadRaiz.empresa; import java.util.ArrayList; import suPropiedadRaiz.inmuebles.*; public abstract class ListaUnidades { private static ArrayList<Unidad> unidadesRegistradas = new ArrayList<Unidad>(); public static void addUnidad(Unidad unidad){ unidadesRegistradas.add(unidad); } public static Unidad getUnidad(long codigo){ for(int i=0; i< unidadesRegistradas.size(); i++){ if(unidadesRegistradas.get(i).getCodigo() == codigo){ return unidadesRegistradas.get(i); } } return null; } }
UTF-8
Java
614
java
ListaUnidades.java
Java
[ { "context": "/*\r\n * Autor: Cristian\r\n * Almacena todas las Unidades\r\n */\r\npackage suP", "end": 22, "score": 0.9998374581336975, "start": 14, "tag": "NAME", "value": "Cristian" } ]
null
[]
/* * Autor: Cristian * Almacena todas las Unidades */ package suPropiedadRaiz.empresa; import java.util.ArrayList; import suPropiedadRaiz.inmuebles.*; public abstract class ListaUnidades { private static ArrayList<Unidad> unidadesRegistradas = new ArrayList<Unidad>(); public static void addUnidad(Unidad unidad){ unidadesRegistradas.add(unidad); } public static Unidad getUnidad(long codigo){ for(int i=0; i< unidadesRegistradas.size(); i++){ if(unidadesRegistradas.get(i).getCodigo() == codigo){ return unidadesRegistradas.get(i); } } return null; } }
614
0.700326
0.698697
26
21.615385
21.88796
80
false
false
0
0
0
0
0
0
1.346154
false
false
14
23b4f2add931b06c6a6ac56b19137c3f19a2a292
10,746,008,194,248
49bfe0a655586732cfb4028111672def439e242c
/src/com/certification/database/Initiate.java
06b2e464dad1ea835cfbff2ca37ceba096c49722
[]
no_license
deeepanshu/Certifications
https://github.com/deeepanshu/Certifications
33a868d958ae0392e420384c4ca73e17f3592d16
b8c7f550f736a0e8914729db8234fbef4b87a588
refs/heads/master
2021-06-21T13:13:28.876000
2017-08-20T16:08:05
2017-08-20T16:08:05
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.certification.database; import java.sql.Connection; import java.sql.Statement; public class Initiate { public Initiate(){ Statement stmt; Connection conn = null; try{ conn = ConnectionFactory.getConnection(); stmt = conn.createStatement(); String users = "create table if not exists login(" + "username varchar(200)," + "password varchar(200)," + "sessionId varchar(200) unique," + "base varchar(200)," + "status int," + "primary key(username)" + ");"; stmt.executeUpdate(users); String eventTable = "create table if not exists events(" + "eventId varchar(200)," + "eventName varchar(200)," + "eventIncharge varchar(200)," + "eventDuration int," + "isScrap int," + "dateStarted date," + "dateEnded date," + "primary key (eventId)" + ");"; stmt.executeUpdate(eventTable); String certificateLayoutTable = "create table if not exists certificateLayouts(" + "certificateId varchar(200)," + "eventId varchar(200)," + "certificateImageLocation varchar(500)," + "property1abscissa int," + "property1ordinate int," + "primary key (certificateId)," + "foreign key (eventId) references events(eventId)" + ");"; stmt.executeUpdate(certificateLayoutTable); String participants = "create table if not exists participants(" + "participantId varchar(200)," + "name varchar(200)," + "email varchar(200)," + "contact varchar(200)," + "institution varchar(200)," + "primary key (participantId)" + ");"; stmt.executeUpdate(participants); String certificateAwarded = "create table if not exists certificateAwarded(" + "certificateId varchar(200)," + "eventId varchar(200)," + "participantId varchar(200)," + "rank varchar(200)," + "isDownloadable int," + "primary key (certificateId, eventId, participantId)," + "foreign key (certificateId) references certificateLayouts(certificateId)," + "foreign key (eventId) references events(eventId)," + "foreign key (participantId) references participants(participantId)" + ");"; stmt.executeUpdate(certificateAwarded); }catch(Exception e){ e.printStackTrace(); } finally { ConnectionFactory.close(conn); stmt=null; } } public static void main(String[] args) { new Initiate(); } }
UTF-8
Java
2,601
java
Initiate.java
Java
[ { "context": "ername varchar(200),\"\n\t \t\t\t+ \"password varchar(200),\"\n\t \t\t\t+ \"sessionId varchar(200) unique,\"\n\t ", "end": 411, "score": 0.8673494458198547, "start": 408, "tag": "PASSWORD", "value": "200" }, { "context": ",\"\n\t \t\t\t+ \"status int,\"\n\t \t\t\t+ \"primary key(username)\"\n\t \t\t\t+ \");\";\n\t \tstmt.executeUpdate(users)", "end": 544, "score": 0.9933435916900635, "start": 536, "tag": "USERNAME", "value": "username" } ]
null
[]
package com.certification.database; import java.sql.Connection; import java.sql.Statement; public class Initiate { public Initiate(){ Statement stmt; Connection conn = null; try{ conn = ConnectionFactory.getConnection(); stmt = conn.createStatement(); String users = "create table if not exists login(" + "username varchar(200)," + "password varchar(200)," + "sessionId varchar(200) unique," + "base varchar(200)," + "status int," + "primary key(username)" + ");"; stmt.executeUpdate(users); String eventTable = "create table if not exists events(" + "eventId varchar(200)," + "eventName varchar(200)," + "eventIncharge varchar(200)," + "eventDuration int," + "isScrap int," + "dateStarted date," + "dateEnded date," + "primary key (eventId)" + ");"; stmt.executeUpdate(eventTable); String certificateLayoutTable = "create table if not exists certificateLayouts(" + "certificateId varchar(200)," + "eventId varchar(200)," + "certificateImageLocation varchar(500)," + "property1abscissa int," + "property1ordinate int," + "primary key (certificateId)," + "foreign key (eventId) references events(eventId)" + ");"; stmt.executeUpdate(certificateLayoutTable); String participants = "create table if not exists participants(" + "participantId varchar(200)," + "name varchar(200)," + "email varchar(200)," + "contact varchar(200)," + "institution varchar(200)," + "primary key (participantId)" + ");"; stmt.executeUpdate(participants); String certificateAwarded = "create table if not exists certificateAwarded(" + "certificateId varchar(200)," + "eventId varchar(200)," + "participantId varchar(200)," + "rank varchar(200)," + "isDownloadable int," + "primary key (certificateId, eventId, participantId)," + "foreign key (certificateId) references certificateLayouts(certificateId)," + "foreign key (eventId) references events(eventId)," + "foreign key (participantId) references participants(participantId)" + ");"; stmt.executeUpdate(certificateAwarded); }catch(Exception e){ e.printStackTrace(); } finally { ConnectionFactory.close(conn); stmt=null; } } public static void main(String[] args) { new Initiate(); } }
2,601
0.596694
0.57401
83
30.337349
20.158575
86
false
false
0
0
0
0
0
0
3.421687
false
false
14
d33594182468137adfeae997c5241cf2097faadb
35,399,120,468,647
b41bef053e4f5209f678db43b38eb287a8bb844a
/main/java/srbrettle/financialformulas/FinancialFormulas.java
49e3082524e5061163335fae581cf70fb330ff11
[ "MIT" ]
permissive
RavikiranKalbag/Financial-Formulas
https://github.com/RavikiranKalbag/Financial-Formulas
97b3f1703ca9e77720cab856235db030e9cdfb14
2bf89605d84d246d4a2b0d87ada305918652893e
refs/heads/master
2022-01-08T16:22:24.257000
2018-09-16T16:11:37
2018-09-16T16:11:37
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package srbrettle.financialformulas; /** * A collection of methods for solving Finance/Accounting equations. * * @author Scott Brettle */ public class FinancialFormulas { /* * ----------------------------------------------------------------------------- * | Formulas - Activity | * ----------------------------------------------------------------------------- */ /** * Calculates Asset Turnover from Net Sales and Total Assets. * @param netSales Net Sales * @param totalAssets Total Assets * @return */ public static double CalcAssetTurnover(double netSales, double totalAssets) { return netSales / totalAssets; } /** * Calculates Average Collection Period from Accounts Receivable and Annual Credit Sales. * @param accountsReceivable Accounts Receivable * @param annualCreditSales Annual Credit Sales * @return */ public static double CalcAverageCollectionPeriod(double accountsReceivable, double annualCreditSales) { return accountsReceivable / (annualCreditSales / 365); } /** * Calcualtes Cash Conversion Cycle from Inventory Conversion Period, Receivables Conversion Period and Payables Conversion Period. * @param inventoryConversionPeriod Inventory Conversion Period * @param receivablesConversionPeriod Receivables Conversion Period * @param payablesConversionPeriod Payables Conversion Period * @return */ public static double CalcCashConversionCycle(double inventoryConversionPeriod, double receivablesConversionPeriod, double payablesConversionPeriod) { return (inventoryConversionPeriod + receivablesConversionPeriod - payablesConversionPeriod); } /** * Calculates Inventory Conversion Period from Inventory Turnover Ratio. * @param inventoryTurnoverRatio Inventory Turnover Ratio * @return */ public static double CalcInventoryConversionPeriod(double inventoryTurnoverRatio) { return 365 / inventoryTurnoverRatio; } /** * Calculates Inventory Conversion Ratio from Sales and Cost Of Goods Sold. * @param sales Sales * @param costOfGoodsSold Cost Of Goods Sold * @return */ public static double CalcInventoryConversionRatio(double sales, double costOfGoodsSold) { return (sales * 0.5) / costOfGoodsSold; } /** * Calculates Inventory Turnover from Sales and Average Inventory. * @param sales Sales * @param averageInventory Average Inventory * @return */ public static double CalcInventoryTurnover(double sales, double averageInventory) { return sales / averageInventory; } /** * Calculates Payables Conversion Period from Accounts Payable and Purchases. * @param accountsPayable Accounts Payable * @param purchases Purchases * @return */ public static double CalcPayablesConversionPeriod(double accountsPayable, double purchases) { return (accountsPayable / purchases) * 365; } /** * Calculates Receivables Conversion Period from Receivables and Net Sales. * @param receivables Receivables * @param netSales Net Sales * @return */ public static double CalcReceivablesConversionPeriod(double receivables, double netSales) { return (receivables / netSales) * 365; } /** * Calculates Receivables Turnover Ratio from Net Credit Sales and Average Net Receivables. * @param netCreditSales Net Credit Sales * @param averageNetReceivables Average Net Receivables * @return */ public static double CalcReceivablesTurnoverRatio(double netCreditSales, double averageNetReceivables) { return netCreditSales / averageNetReceivables; } /* * ----------------------------------------------------------------------------- * | Formulas - Basic | * ----------------------------------------------------------------------------- */ /** * Calculates Assets from Liabilities and Equity. * @param liabilities Liabilities * @param equity Equity * @return */ public static double CalcAssets(double liabilities, double equity) { return liabilities + equity; } /** * Calculates Earnings Before Interest and Taxes (EBIT) from Revenue and Operating Expenses. * @param revenue Revenue * @param operatingExpenses Operating Expenses * @return */ public static double CalcEbit(double revenue, double operatingExpenses) { return revenue - operatingExpenses; } /** * Calculates Equity from Assets and Liabilities. * @param assets Assets * @param liabilities Liabilities * @return */ public static double CalcEquity(double assets, double liabilities) { return assets - liabilities; } /** * Calculates Gross Profit from Revenue and Cost Of Goods Sold (COGS). * @param revenue Revenue * @param costOfGoodsSold Cost Of Goods Sold * @return */ public static double CalcGrossProfit(double revenue, double costOfGoodsSold) { return revenue - costOfGoodsSold; } /** * Calculates Liabilities from Assets and Equity. * @param assets Assets * @param equity Equity * @return */ public static double CalcLiabilities(double assets, double equity) { return assets - equity; } /** * Calculates Net Profit from Gross Profit, Operating Expenses, Taxes and Interest. * @param grossProfit Gross Profit * @param operatingExpenses Operating Expenses * @param taxes Taxes * @param interest Interest * @return */ public static double CalcNetProfit(double grossProfit, double operatingExpenses, double taxes, double interest) { return grossProfit - operatingExpenses - taxes - interest; } /** * Calculates Operation Profit from Gross Profit and Operating Expenses. * @param grossProfit Gross Profit * @param operatingExpenses Operating Expenses * @return */ public static double CalcOperatingProfit(double grossProfit, double operatingExpenses) { return grossProfit - operatingExpenses; } /** * Calculates Sales Revenue from Gross Sales and Sales of Returns and Allowances. * @param grossSales Gross Sales * @param salesOfReturnsAndAllowances Sales of Returns and Allowances * @return */ public static double CalcSalesRevenue(double grossSales, double salesOfReturnsAndAllowances) { return grossSales - salesOfReturnsAndAllowances; } /* * ----------------------------------------------------------------------------- * | Formulas - Debt | * ----------------------------------------------------------------------------- */ /** * Calculates Debt to Equity Ratio from Total Liabilities and Shareholder Equity. * @param totalLiabilities Total Liabilities * @param shareholderEquity Shareholder Equity * @return */ public static double CalcDebtEquityRatio(double totalLiabilities, double shareholderEquity) { return totalLiabilities / shareholderEquity; } /** * Calculates Debt Ratio Total Liabilities and Total Assets. * @param totalLiabilities Total Liabilities * @param totalAssets Total Assets * @return */ public static double CalcDebtRatio(double totalLiabilities, double totalAssets) { return totalLiabilities / totalAssets; } /** * Calculates Debt-Service Coverage Ratio Net Operating Income and Total Debt Service. * @param netOperatingIncome Net Operating Income * @param totalDebtService Total Debt Service * @return */ public static double CalcDebtServiceCoverageRatio(double netOperatingIncome, double totalDebtService) { return netOperatingIncome / totalDebtService; } /** * Calculates Long-Term Debt to Equity Ratio from Long-Term Liabilities and Equity. * @param longTermLiabilities Long-Term Liabilities * @param equity Equity * @return */ public static double CalcLongTermDebtEquityRatio(double longTermLiabilities, double equity) { return longTermLiabilities / equity; } /* * ----------------------------------------------------------------------------- * | Formulas - Depreciation | * ----------------------------------------------------------------------------- */ /** * Calculates Book Value from Acquisition Cost and Depreciation. * @param acquisitionCost Acquisition Cost * @param depreciation Depreciation * @return */ public static double CalcBookValue(double acquisitionCost, double depreciation) { return acquisitionCost - depreciation; } /** * Calculates Decling Balance from Depreciation Rate and Book Value at Beginning of Year. * @param depreciationRate Depreciation Rate * @param bookValueAtBeginningOfYear Book Value at Beginning of Year * @return */ public static double CalcDecliningBalance(double depreciationRate, double bookValueAtBeginningOfYear) { return depreciationRate * bookValueAtBeginningOfYear; } /** * Calculates Units Of Production from Cost of Asset, Residual Value, Estimated Total Production and Actual Production. * @param costOfAsset Cost of Asset * @param residualValue Residual Value * @param estimatedTotalProduction Estimated Total Production * @param actualProduction Actual Production * @return */ public static double CalcUnitsOfProduction(double costOfAsset, double residualValue, double estimatedTotalProduction, double actualProduction) { return ((costOfAsset - residualValue) / estimatedTotalProduction) * actualProduction; } /** * Calculates Straight Line Method from Cost of Fixed Asset, Residual Value and Useful Life of Asset. * @param costOfFixedAsset Cost of Fixed Asset * @param residualValue Residual Value * @param usefulLifeOfAsset Useful Life of Asset * @return */ public static double CalcStraightLineMethod(double costOfFixedAsset, double residualValue, double usefulLifeOfAsset) { return (costOfFixedAsset - residualValue) / usefulLifeOfAsset; } /* * ----------------------------------------------------------------------------- * | Formulas - Liquidity | * ----------------------------------------------------------------------------- */ /** * Calculates Cash Ration from Cash, Marketable Securities and Current Liabilities. * @param cash Cash * @param marketableSecurities Marketable Securities * @param currentLiabilities Current Liabilities * @return */ public static double CalcCashRatio(double cash, double marketableSecurities, double currentLiabilities) { return (cash + marketableSecurities) / currentLiabilities; } /** * Calculates Current Ratio from Current Assets and Current Liabilties. * @param currentAssets Current Assets * @param currentLiabilities Current Liabilities * @return */ public static double CalcCurrentRatio(double currentAssets, double currentLiabilities) { return currentAssets / currentLiabilities; } /** * Calculates Operating Cash Flow Ratio from Operating Cash Flow and Total Debts. * @param operatingCashFlow Operating Cash Flow * @param totalDebts Total Debts * @return */ public static double CalcOperatingCashFlowRatio(double operatingCashFlow, double totalDebts) { return operatingCashFlow / totalDebts; } /** * Calculates Quick Ratio from Current Assets, Inventories and Current Liabilities. * @param currentAssets Current Assets * @param inventories Inventories * @param currentLiabilities Current Liabilities * @return */ public static double CalcQuickRatio(double currentAssets, double inventories, double currentLiabilities) { return (currentAssets - inventories) / currentLiabilities; } /* * ----------------------------------------------------------------------------- * | Formulas - Market | * ----------------------------------------------------------------------------- */ /** * Calculates Dividend Cover from Earnings Per Share and Dividends Per Share. * @param earningsPerShare Earnings Per Share * @param dividendsPerShare Devidends Per Share * @return */ public static double CalcDividendCover(double earningsPerShare, double dividendsPerShare) { return earningsPerShare / dividendsPerShare; } /** * Calculates Dividends Per Share (DPS) from Dividends Paid and Number Of Shares. * @param dividendsPaid Dividends Paid * @param numberOfShares Number of Shares * @return */ public static double CalcDividendsPerShare(double dividendsPaid, double numberOfShares) { return dividendsPaid / numberOfShares; } /** * Calculates Dividend Yield from Annual Dividend Per Share and Price Per Share. * @param annualDividendPerShare Annual Dividend Per Share * @param pricePerShare Price Per Share * @return */ public static double CalcDividendYield(double annualDividendPerShare, double pricePerShare) { return annualDividendPerShare / pricePerShare; } /** * Calculates Earnings Per Share from Net Earnings and Number of Shares. * @param netEarnings Net Earnings * @param numberOfShares Number of Shares * @return */ public static double CalcEarningsPerShare(double netEarnings, double numberOfShares) { return netEarnings / numberOfShares; } /** * Calculates Payout Ratio from Dividends and Earnings. * @param dividends Dividends * @param earnings Earnings * @return */ public static double CalcPayoutRatio(double dividends, double earnings) { return dividends / earnings; } /** * Calculates Price/Earnings to Growth (PEG) Ratio from Price Per Earnings and Annual EPS Growth. * @param pricePerEarnings Price Per Earnings * @param annualEpsGrowth Annual EPS Growth * @return */ public static double CalcPegRatio(double pricePerEarnings, double annualEpsGrowth) { return pricePerEarnings / annualEpsGrowth; } /** * Calculates Price to Sales Ratio from Price Per Share and Revenue Per Share. * @param pricePerShare Price Per Share * @param revenuePerShare Revenue Per Share * @return */ public static double CalcPriceSalesRatio(double pricePerShare, double revenuePerShare) { return pricePerShare / revenuePerShare; } /* * ----------------------------------------------------------------------------- * | Formulas - Profitability | * ----------------------------------------------------------------------------- */ /** * Calculates Efficiency Ratio from Non-Interest Expense and Revenue. * @param nonInterestExpense Non-Interest Expense * @param revenue Revenue * @return */ public static double CalcEfficiencyRatio(double nonInterestExpense, double revenue) { return nonInterestExpense / revenue; } /** * Calculates Gross Profit Margin from Gross Profit and Revenue. * @param grossProfit Gross Profit * @param revenue Revenue * @return */ public static double CalcGrossProfitMargin(double grossProfit, double revenue) { return grossProfit / revenue; } /** * Calculates Operating Margin from Operating Income and Revenue. * @param operatingIncome Operating Income * @param revenue Revenue * @return */ public static double CalcOperatingMargin(double operatingIncome, double revenue) { return operatingIncome / revenue; } /** * Calculates Profit Margin from Net Profit and Revenue. * @param netProfit Net Profit * @param revenue Revenue * @return */ public static double CalcProfitMargin(double netProfit, double revenue) { return netProfit / revenue; } /** * Calculates Return On Assets (ROA) from Net Income and Total Assets. * @param netIncome Net Income * @param totalAssets Total Assets * @return */ public static double CalcReturnOnAssets(double netIncome, double totalAssets) { return netIncome / totalAssets; } /** * Calculates Return On Capital (ROC) from EBIT, Tax Rate and Invested Capital. * @param ebit Earnings Before Interest and Taxes * @param taxRate Tax Rate * @param investedCapital Invested Capital * @return */ public static double CalcReturnOnCapital(double ebit, double taxRate, double investedCapital) { return ebit * (1 - taxRate) / investedCapital; } /** * Calculates Return on Equity (ROE) from Net Income and Average Shareholder Equity. * @param netIncome Net Income * @param averageShareholderEquity Average Shareholder Equity * @return */ public static double CalcReturnOnEquity(double netIncome, double averageShareholderEquity) { return netIncome / averageShareholderEquity; } /** * Calculates Return On Net Assets (RONA) from Net Income, Fixed Assets and Working Capital. * @param netIncome Net Income * @param fixedAssets Fixed Assets * @param workingCapital Working Capital * @return */ public static double CalcReturnOnNetAssets(double netIncome, double fixedAssets, double workingCapital) { return netIncome / (fixedAssets + workingCapital); } /** * Calculates Risk-Adjusted Return On Capital (RAROC) from Expected Return and Economic Capital. * @param expectedReturn Expected Return * @param economicCapital Economic Capital * @return */ public static double CalcRiskAdjustedReturnOnCapital(double expectedReturn, double economicCapital) { return expectedReturn / economicCapital; } /** * Calculates Return on Investment (ROI) from Gain and Cost. * @param gain Gain * @param cost Cost * @return */ public static double CalcReturnOnInvestment(double gain, double cost) { return (gain - cost) / cost; } /** * Calculates Earnings Before Interest, Taxes, Depreciation and Amortization (EBITDA) from EBIT, Depreciation and Amortization. * @param ebit Earnings Before Interest and Taxes * @param depreciation Depreciation * @param amortization Amortization * @return */ public static double CalcEbitda(double ebit, double depreciation, double amortization) { return ebit + depreciation + amortization; } }
UTF-8
Java
20,060
java
FinancialFormulas.java
Java
[ { "context": "Finance/Accounting equations.\r\n *\r\n * @author Scott Brettle\r\n */\r\npublic class FinancialFormulas\r\n{\r\n /*\r\n", "end": 148, "score": 0.999875545501709, "start": 135, "tag": "NAME", "value": "Scott Brettle" } ]
null
[]
package srbrettle.financialformulas; /** * A collection of methods for solving Finance/Accounting equations. * * @author <NAME> */ public class FinancialFormulas { /* * ----------------------------------------------------------------------------- * | Formulas - Activity | * ----------------------------------------------------------------------------- */ /** * Calculates Asset Turnover from Net Sales and Total Assets. * @param netSales Net Sales * @param totalAssets Total Assets * @return */ public static double CalcAssetTurnover(double netSales, double totalAssets) { return netSales / totalAssets; } /** * Calculates Average Collection Period from Accounts Receivable and Annual Credit Sales. * @param accountsReceivable Accounts Receivable * @param annualCreditSales Annual Credit Sales * @return */ public static double CalcAverageCollectionPeriod(double accountsReceivable, double annualCreditSales) { return accountsReceivable / (annualCreditSales / 365); } /** * Calcualtes Cash Conversion Cycle from Inventory Conversion Period, Receivables Conversion Period and Payables Conversion Period. * @param inventoryConversionPeriod Inventory Conversion Period * @param receivablesConversionPeriod Receivables Conversion Period * @param payablesConversionPeriod Payables Conversion Period * @return */ public static double CalcCashConversionCycle(double inventoryConversionPeriod, double receivablesConversionPeriod, double payablesConversionPeriod) { return (inventoryConversionPeriod + receivablesConversionPeriod - payablesConversionPeriod); } /** * Calculates Inventory Conversion Period from Inventory Turnover Ratio. * @param inventoryTurnoverRatio Inventory Turnover Ratio * @return */ public static double CalcInventoryConversionPeriod(double inventoryTurnoverRatio) { return 365 / inventoryTurnoverRatio; } /** * Calculates Inventory Conversion Ratio from Sales and Cost Of Goods Sold. * @param sales Sales * @param costOfGoodsSold Cost Of Goods Sold * @return */ public static double CalcInventoryConversionRatio(double sales, double costOfGoodsSold) { return (sales * 0.5) / costOfGoodsSold; } /** * Calculates Inventory Turnover from Sales and Average Inventory. * @param sales Sales * @param averageInventory Average Inventory * @return */ public static double CalcInventoryTurnover(double sales, double averageInventory) { return sales / averageInventory; } /** * Calculates Payables Conversion Period from Accounts Payable and Purchases. * @param accountsPayable Accounts Payable * @param purchases Purchases * @return */ public static double CalcPayablesConversionPeriod(double accountsPayable, double purchases) { return (accountsPayable / purchases) * 365; } /** * Calculates Receivables Conversion Period from Receivables and Net Sales. * @param receivables Receivables * @param netSales Net Sales * @return */ public static double CalcReceivablesConversionPeriod(double receivables, double netSales) { return (receivables / netSales) * 365; } /** * Calculates Receivables Turnover Ratio from Net Credit Sales and Average Net Receivables. * @param netCreditSales Net Credit Sales * @param averageNetReceivables Average Net Receivables * @return */ public static double CalcReceivablesTurnoverRatio(double netCreditSales, double averageNetReceivables) { return netCreditSales / averageNetReceivables; } /* * ----------------------------------------------------------------------------- * | Formulas - Basic | * ----------------------------------------------------------------------------- */ /** * Calculates Assets from Liabilities and Equity. * @param liabilities Liabilities * @param equity Equity * @return */ public static double CalcAssets(double liabilities, double equity) { return liabilities + equity; } /** * Calculates Earnings Before Interest and Taxes (EBIT) from Revenue and Operating Expenses. * @param revenue Revenue * @param operatingExpenses Operating Expenses * @return */ public static double CalcEbit(double revenue, double operatingExpenses) { return revenue - operatingExpenses; } /** * Calculates Equity from Assets and Liabilities. * @param assets Assets * @param liabilities Liabilities * @return */ public static double CalcEquity(double assets, double liabilities) { return assets - liabilities; } /** * Calculates Gross Profit from Revenue and Cost Of Goods Sold (COGS). * @param revenue Revenue * @param costOfGoodsSold Cost Of Goods Sold * @return */ public static double CalcGrossProfit(double revenue, double costOfGoodsSold) { return revenue - costOfGoodsSold; } /** * Calculates Liabilities from Assets and Equity. * @param assets Assets * @param equity Equity * @return */ public static double CalcLiabilities(double assets, double equity) { return assets - equity; } /** * Calculates Net Profit from Gross Profit, Operating Expenses, Taxes and Interest. * @param grossProfit Gross Profit * @param operatingExpenses Operating Expenses * @param taxes Taxes * @param interest Interest * @return */ public static double CalcNetProfit(double grossProfit, double operatingExpenses, double taxes, double interest) { return grossProfit - operatingExpenses - taxes - interest; } /** * Calculates Operation Profit from Gross Profit and Operating Expenses. * @param grossProfit Gross Profit * @param operatingExpenses Operating Expenses * @return */ public static double CalcOperatingProfit(double grossProfit, double operatingExpenses) { return grossProfit - operatingExpenses; } /** * Calculates Sales Revenue from Gross Sales and Sales of Returns and Allowances. * @param grossSales Gross Sales * @param salesOfReturnsAndAllowances Sales of Returns and Allowances * @return */ public static double CalcSalesRevenue(double grossSales, double salesOfReturnsAndAllowances) { return grossSales - salesOfReturnsAndAllowances; } /* * ----------------------------------------------------------------------------- * | Formulas - Debt | * ----------------------------------------------------------------------------- */ /** * Calculates Debt to Equity Ratio from Total Liabilities and Shareholder Equity. * @param totalLiabilities Total Liabilities * @param shareholderEquity Shareholder Equity * @return */ public static double CalcDebtEquityRatio(double totalLiabilities, double shareholderEquity) { return totalLiabilities / shareholderEquity; } /** * Calculates Debt Ratio Total Liabilities and Total Assets. * @param totalLiabilities Total Liabilities * @param totalAssets Total Assets * @return */ public static double CalcDebtRatio(double totalLiabilities, double totalAssets) { return totalLiabilities / totalAssets; } /** * Calculates Debt-Service Coverage Ratio Net Operating Income and Total Debt Service. * @param netOperatingIncome Net Operating Income * @param totalDebtService Total Debt Service * @return */ public static double CalcDebtServiceCoverageRatio(double netOperatingIncome, double totalDebtService) { return netOperatingIncome / totalDebtService; } /** * Calculates Long-Term Debt to Equity Ratio from Long-Term Liabilities and Equity. * @param longTermLiabilities Long-Term Liabilities * @param equity Equity * @return */ public static double CalcLongTermDebtEquityRatio(double longTermLiabilities, double equity) { return longTermLiabilities / equity; } /* * ----------------------------------------------------------------------------- * | Formulas - Depreciation | * ----------------------------------------------------------------------------- */ /** * Calculates Book Value from Acquisition Cost and Depreciation. * @param acquisitionCost Acquisition Cost * @param depreciation Depreciation * @return */ public static double CalcBookValue(double acquisitionCost, double depreciation) { return acquisitionCost - depreciation; } /** * Calculates Decling Balance from Depreciation Rate and Book Value at Beginning of Year. * @param depreciationRate Depreciation Rate * @param bookValueAtBeginningOfYear Book Value at Beginning of Year * @return */ public static double CalcDecliningBalance(double depreciationRate, double bookValueAtBeginningOfYear) { return depreciationRate * bookValueAtBeginningOfYear; } /** * Calculates Units Of Production from Cost of Asset, Residual Value, Estimated Total Production and Actual Production. * @param costOfAsset Cost of Asset * @param residualValue Residual Value * @param estimatedTotalProduction Estimated Total Production * @param actualProduction Actual Production * @return */ public static double CalcUnitsOfProduction(double costOfAsset, double residualValue, double estimatedTotalProduction, double actualProduction) { return ((costOfAsset - residualValue) / estimatedTotalProduction) * actualProduction; } /** * Calculates Straight Line Method from Cost of Fixed Asset, Residual Value and Useful Life of Asset. * @param costOfFixedAsset Cost of Fixed Asset * @param residualValue Residual Value * @param usefulLifeOfAsset Useful Life of Asset * @return */ public static double CalcStraightLineMethod(double costOfFixedAsset, double residualValue, double usefulLifeOfAsset) { return (costOfFixedAsset - residualValue) / usefulLifeOfAsset; } /* * ----------------------------------------------------------------------------- * | Formulas - Liquidity | * ----------------------------------------------------------------------------- */ /** * Calculates Cash Ration from Cash, Marketable Securities and Current Liabilities. * @param cash Cash * @param marketableSecurities Marketable Securities * @param currentLiabilities Current Liabilities * @return */ public static double CalcCashRatio(double cash, double marketableSecurities, double currentLiabilities) { return (cash + marketableSecurities) / currentLiabilities; } /** * Calculates Current Ratio from Current Assets and Current Liabilties. * @param currentAssets Current Assets * @param currentLiabilities Current Liabilities * @return */ public static double CalcCurrentRatio(double currentAssets, double currentLiabilities) { return currentAssets / currentLiabilities; } /** * Calculates Operating Cash Flow Ratio from Operating Cash Flow and Total Debts. * @param operatingCashFlow Operating Cash Flow * @param totalDebts Total Debts * @return */ public static double CalcOperatingCashFlowRatio(double operatingCashFlow, double totalDebts) { return operatingCashFlow / totalDebts; } /** * Calculates Quick Ratio from Current Assets, Inventories and Current Liabilities. * @param currentAssets Current Assets * @param inventories Inventories * @param currentLiabilities Current Liabilities * @return */ public static double CalcQuickRatio(double currentAssets, double inventories, double currentLiabilities) { return (currentAssets - inventories) / currentLiabilities; } /* * ----------------------------------------------------------------------------- * | Formulas - Market | * ----------------------------------------------------------------------------- */ /** * Calculates Dividend Cover from Earnings Per Share and Dividends Per Share. * @param earningsPerShare Earnings Per Share * @param dividendsPerShare Devidends Per Share * @return */ public static double CalcDividendCover(double earningsPerShare, double dividendsPerShare) { return earningsPerShare / dividendsPerShare; } /** * Calculates Dividends Per Share (DPS) from Dividends Paid and Number Of Shares. * @param dividendsPaid Dividends Paid * @param numberOfShares Number of Shares * @return */ public static double CalcDividendsPerShare(double dividendsPaid, double numberOfShares) { return dividendsPaid / numberOfShares; } /** * Calculates Dividend Yield from Annual Dividend Per Share and Price Per Share. * @param annualDividendPerShare Annual Dividend Per Share * @param pricePerShare Price Per Share * @return */ public static double CalcDividendYield(double annualDividendPerShare, double pricePerShare) { return annualDividendPerShare / pricePerShare; } /** * Calculates Earnings Per Share from Net Earnings and Number of Shares. * @param netEarnings Net Earnings * @param numberOfShares Number of Shares * @return */ public static double CalcEarningsPerShare(double netEarnings, double numberOfShares) { return netEarnings / numberOfShares; } /** * Calculates Payout Ratio from Dividends and Earnings. * @param dividends Dividends * @param earnings Earnings * @return */ public static double CalcPayoutRatio(double dividends, double earnings) { return dividends / earnings; } /** * Calculates Price/Earnings to Growth (PEG) Ratio from Price Per Earnings and Annual EPS Growth. * @param pricePerEarnings Price Per Earnings * @param annualEpsGrowth Annual EPS Growth * @return */ public static double CalcPegRatio(double pricePerEarnings, double annualEpsGrowth) { return pricePerEarnings / annualEpsGrowth; } /** * Calculates Price to Sales Ratio from Price Per Share and Revenue Per Share. * @param pricePerShare Price Per Share * @param revenuePerShare Revenue Per Share * @return */ public static double CalcPriceSalesRatio(double pricePerShare, double revenuePerShare) { return pricePerShare / revenuePerShare; } /* * ----------------------------------------------------------------------------- * | Formulas - Profitability | * ----------------------------------------------------------------------------- */ /** * Calculates Efficiency Ratio from Non-Interest Expense and Revenue. * @param nonInterestExpense Non-Interest Expense * @param revenue Revenue * @return */ public static double CalcEfficiencyRatio(double nonInterestExpense, double revenue) { return nonInterestExpense / revenue; } /** * Calculates Gross Profit Margin from Gross Profit and Revenue. * @param grossProfit Gross Profit * @param revenue Revenue * @return */ public static double CalcGrossProfitMargin(double grossProfit, double revenue) { return grossProfit / revenue; } /** * Calculates Operating Margin from Operating Income and Revenue. * @param operatingIncome Operating Income * @param revenue Revenue * @return */ public static double CalcOperatingMargin(double operatingIncome, double revenue) { return operatingIncome / revenue; } /** * Calculates Profit Margin from Net Profit and Revenue. * @param netProfit Net Profit * @param revenue Revenue * @return */ public static double CalcProfitMargin(double netProfit, double revenue) { return netProfit / revenue; } /** * Calculates Return On Assets (ROA) from Net Income and Total Assets. * @param netIncome Net Income * @param totalAssets Total Assets * @return */ public static double CalcReturnOnAssets(double netIncome, double totalAssets) { return netIncome / totalAssets; } /** * Calculates Return On Capital (ROC) from EBIT, Tax Rate and Invested Capital. * @param ebit Earnings Before Interest and Taxes * @param taxRate Tax Rate * @param investedCapital Invested Capital * @return */ public static double CalcReturnOnCapital(double ebit, double taxRate, double investedCapital) { return ebit * (1 - taxRate) / investedCapital; } /** * Calculates Return on Equity (ROE) from Net Income and Average Shareholder Equity. * @param netIncome Net Income * @param averageShareholderEquity Average Shareholder Equity * @return */ public static double CalcReturnOnEquity(double netIncome, double averageShareholderEquity) { return netIncome / averageShareholderEquity; } /** * Calculates Return On Net Assets (RONA) from Net Income, Fixed Assets and Working Capital. * @param netIncome Net Income * @param fixedAssets Fixed Assets * @param workingCapital Working Capital * @return */ public static double CalcReturnOnNetAssets(double netIncome, double fixedAssets, double workingCapital) { return netIncome / (fixedAssets + workingCapital); } /** * Calculates Risk-Adjusted Return On Capital (RAROC) from Expected Return and Economic Capital. * @param expectedReturn Expected Return * @param economicCapital Economic Capital * @return */ public static double CalcRiskAdjustedReturnOnCapital(double expectedReturn, double economicCapital) { return expectedReturn / economicCapital; } /** * Calculates Return on Investment (ROI) from Gain and Cost. * @param gain Gain * @param cost Cost * @return */ public static double CalcReturnOnInvestment(double gain, double cost) { return (gain - cost) / cost; } /** * Calculates Earnings Before Interest, Taxes, Depreciation and Amortization (EBITDA) from EBIT, Depreciation and Amortization. * @param ebit Earnings Before Interest and Taxes * @param depreciation Depreciation * @param amortization Amortization * @return */ public static double CalcEbitda(double ebit, double depreciation, double amortization) { return ebit + depreciation + amortization; } }
20,053
0.610169
0.609422
580
32.586208
33.23222
151
false
false
0
0
0
0
0
0
0.227586
false
false
14
412b1eec09b406ebde8e159e07e0b247b15becbc
22,505,628,682,599
197a289fb8a49701d8bbc48e52a836b44d1b9f01
/src/util/Tool.java
588ac2fcb88d1dede2923e81e24c6a01d91c4d02
[]
no_license
devdirga/qris-parser
https://github.com/devdirga/qris-parser
1f7b1dff45d08166e46303ce054935011e5799a1
3aecb55e7110c38130d7cf008495b72afa81fb71
refs/heads/master
2022-11-19T06:29:34.283000
2020-07-26T07:48:08
2020-07-26T07:48:08
282,363,947
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package util; import java.time.LocalDateTime; import java.time.Period; import java.time.format.DateTimeFormatter; import java.util.Locale; import java.text.MessageFormat; import java.text.SimpleDateFormat; import java.util.Date; /** * * @author Dirga */ public class Tool { public static String URL = "https://interactiveholic.com/qris/dashboard/getdatafromqristrx.php?"; public static String MID = "195241173626"; public static String EMPTY = ""; public static String NOL = "0"; /** * @return */ public static String GetUrlQuery() { LocalDateTime finishdate = LocalDateTime.now(); return MessageFormat.format("{0}getmid={1}&dtBeg={2}&dtEnd={3}", URL, MID, DateTimeFormatter.ofPattern("yyyy-MM-dd", Locale.ENGLISH).format( finishdate.minus(Period.ofDays(30)) ), DateTimeFormatter.ofPattern("yyyy-MM-dd", Locale.ENGLISH).format(finishdate)); } /** * @param text * @return */ public static String GetNominal(String text) { return text.replace(".00", ""); } /** * @return */ public static String GetTime() { return (new SimpleDateFormat("dd-MM-yyyy HH:mm:ss")).format(new Date()); } /** * @param Header * @param Log */ public static void Logger(String Header, String Log){ System.out.println(MessageFormat.format("{0} {1} : {2}", Header, GetTime(), Log)); } /** * @param Header * @param Log */ public static void Logger(String Header, Exception Log){ System.out.println(MessageFormat.format("{0} {1} : {2}", Header, GetTime(), Log)); } }
UTF-8
Java
1,932
java
Tool.java
Java
[ { "context": "eFormat;\nimport java.util.Date;\n\n/**\n *\n * @author Dirga\n */\npublic class Tool {\n \n public static St", "end": 439, "score": 0.5299104452133179, "start": 434, "tag": "NAME", "value": "Dirga" } ]
null
[]
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package util; import java.time.LocalDateTime; import java.time.Period; import java.time.format.DateTimeFormatter; import java.util.Locale; import java.text.MessageFormat; import java.text.SimpleDateFormat; import java.util.Date; /** * * @author Dirga */ public class Tool { public static String URL = "https://interactiveholic.com/qris/dashboard/getdatafromqristrx.php?"; public static String MID = "195241173626"; public static String EMPTY = ""; public static String NOL = "0"; /** * @return */ public static String GetUrlQuery() { LocalDateTime finishdate = LocalDateTime.now(); return MessageFormat.format("{0}getmid={1}&dtBeg={2}&dtEnd={3}", URL, MID, DateTimeFormatter.ofPattern("yyyy-MM-dd", Locale.ENGLISH).format( finishdate.minus(Period.ofDays(30)) ), DateTimeFormatter.ofPattern("yyyy-MM-dd", Locale.ENGLISH).format(finishdate)); } /** * @param text * @return */ public static String GetNominal(String text) { return text.replace(".00", ""); } /** * @return */ public static String GetTime() { return (new SimpleDateFormat("dd-MM-yyyy HH:mm:ss")).format(new Date()); } /** * @param Header * @param Log */ public static void Logger(String Header, String Log){ System.out.println(MessageFormat.format("{0} {1} : {2}", Header, GetTime(), Log)); } /** * @param Header * @param Log */ public static void Logger(String Header, Exception Log){ System.out.println(MessageFormat.format("{0} {1} : {2}", Header, GetTime(), Log)); } }
1,932
0.60559
0.591615
70
26.6
28.380777
121
false
false
0
0
0
0
0
0
0.514286
false
false
14
e8295c30320e72530e0e9d78a2b3206554b27449
6,365,141,591,750
0fb09bb8bee00745e4d1580ae8f11a27421541c9
/backEnd/src/pojos/Cpu_Cooler.java
4517d919ca83eed429906e7b3a2ebe3d0403a224
[]
no_license
Samad3911/DesktopDesigner
https://github.com/Samad3911/DesktopDesigner
bdbbd6b450f44904dd9276002d06c7f333de75d8
e717692adae387e80670ea07b595e62da8a520a9
refs/heads/main
2023-04-07T19:46:40.314000
2021-04-05T17:28:52
2021-04-05T17:28:52
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package pojos; import javax.persistence.*; @Entity @Table(name="cpu_Cooler") public class Cpu_Cooler { private int product_Id; private String cpu_Cooler_Model,brand,air_Flow,noise,link_Primeabgb,link_Amazon,link_Mdcomputers; private int price; public Cpu_Cooler() { // TODO Auto-generated constructor stub } public Cpu_Cooler(int product_Id, String cpu_Cooler_Model, String brand, String air_Flow, String noise, String link_Primeabgb, String link_Amazon, String link_Mdcomputers, int price) { super(); this.product_Id = product_Id; this.cpu_Cooler_Model = cpu_Cooler_Model; this.brand = brand; this.air_Flow = air_Flow; this.noise = noise; this.link_Primeabgb = link_Primeabgb; this.link_Amazon = link_Amazon; this.link_Mdcomputers = link_Mdcomputers; this.price = price; } @Id @Column(name="product_Id") public int getProduct_Id() { return product_Id; } public void setProduct_Id(int product_Id) { this.product_Id = product_Id; } @Column(name="cpu_Cooler_Model") public String getCpu_Cooler_Model() { return cpu_Cooler_Model; } public void setCpu_Cooler_Model(String cpu_Cooler_Model) { this.cpu_Cooler_Model = cpu_Cooler_Model; } @Column(name="brand") public String getBrand() { return brand; } public void setBrand(String brand) { this.brand = brand; } @Column(name="air_Flow") public String getAir_Flow() { return air_Flow; } public void setAir_Flow(String air_Flow) { this.air_Flow = air_Flow; } @Column(name="noise") public String getNoise() { return noise; } public void setNoise(String noise) { this.noise = noise; } @Column(name="link_Primeabgb") public String getLink_Primeabgb() { return link_Primeabgb; } public void setLink_Primeabgb(String link_Primeabgb) { this.link_Primeabgb = link_Primeabgb; } @Column(name="link_Amazon") public String getLink_Amazon() { return link_Amazon; } public void setLink_Amazon(String link_Amazon) { this.link_Amazon = link_Amazon; } @Column(name="link_Mdcomputers") public String getLink_Mdcomputers() { return link_Mdcomputers; } public void setLink_Mdcomputers(String link_Mdcomputers) { this.link_Mdcomputers = link_Mdcomputers; } @Column(name="price") public int getPrice() { return price; } public void setPrice(int price) { this.price = price; } @Override public String toString() { return "cpu_Cooler [product_Id=" + product_Id + ", cpu_Cooler_Model=" + cpu_Cooler_Model + ", brand=" + brand + ", air_Flow=" + air_Flow + ", noise=" + noise + ", link_Primeabgb=" + link_Primeabgb + ", link_Amazon=" + link_Amazon + ", link_Mdcomputers=" + link_Mdcomputers + ", price=" + price + "]"; } }
UTF-8
Java
2,672
java
Cpu_Cooler.java
Java
[]
null
[]
package pojos; import javax.persistence.*; @Entity @Table(name="cpu_Cooler") public class Cpu_Cooler { private int product_Id; private String cpu_Cooler_Model,brand,air_Flow,noise,link_Primeabgb,link_Amazon,link_Mdcomputers; private int price; public Cpu_Cooler() { // TODO Auto-generated constructor stub } public Cpu_Cooler(int product_Id, String cpu_Cooler_Model, String brand, String air_Flow, String noise, String link_Primeabgb, String link_Amazon, String link_Mdcomputers, int price) { super(); this.product_Id = product_Id; this.cpu_Cooler_Model = cpu_Cooler_Model; this.brand = brand; this.air_Flow = air_Flow; this.noise = noise; this.link_Primeabgb = link_Primeabgb; this.link_Amazon = link_Amazon; this.link_Mdcomputers = link_Mdcomputers; this.price = price; } @Id @Column(name="product_Id") public int getProduct_Id() { return product_Id; } public void setProduct_Id(int product_Id) { this.product_Id = product_Id; } @Column(name="cpu_Cooler_Model") public String getCpu_Cooler_Model() { return cpu_Cooler_Model; } public void setCpu_Cooler_Model(String cpu_Cooler_Model) { this.cpu_Cooler_Model = cpu_Cooler_Model; } @Column(name="brand") public String getBrand() { return brand; } public void setBrand(String brand) { this.brand = brand; } @Column(name="air_Flow") public String getAir_Flow() { return air_Flow; } public void setAir_Flow(String air_Flow) { this.air_Flow = air_Flow; } @Column(name="noise") public String getNoise() { return noise; } public void setNoise(String noise) { this.noise = noise; } @Column(name="link_Primeabgb") public String getLink_Primeabgb() { return link_Primeabgb; } public void setLink_Primeabgb(String link_Primeabgb) { this.link_Primeabgb = link_Primeabgb; } @Column(name="link_Amazon") public String getLink_Amazon() { return link_Amazon; } public void setLink_Amazon(String link_Amazon) { this.link_Amazon = link_Amazon; } @Column(name="link_Mdcomputers") public String getLink_Mdcomputers() { return link_Mdcomputers; } public void setLink_Mdcomputers(String link_Mdcomputers) { this.link_Mdcomputers = link_Mdcomputers; } @Column(name="price") public int getPrice() { return price; } public void setPrice(int price) { this.price = price; } @Override public String toString() { return "cpu_Cooler [product_Id=" + product_Id + ", cpu_Cooler_Model=" + cpu_Cooler_Model + ", brand=" + brand + ", air_Flow=" + air_Flow + ", noise=" + noise + ", link_Primeabgb=" + link_Primeabgb + ", link_Amazon=" + link_Amazon + ", link_Mdcomputers=" + link_Mdcomputers + ", price=" + price + "]"; } }
2,672
0.696108
0.696108
99
25.989899
23.977892
111
false
false
0
0
0
0
0
0
1.868687
false
false
14
aaa7190b4f99f9b04e33cab5dbb6794f3e17d06c
36,498,632,092,929
a13086a28c8bd2c98e86180a91e969918ee24a7c
/src/main/java/uk/ac/susx/tag/dialoguer/dialogue/components/Intent.java
fe15cb2d53e9ada432bd3fa0abde9f6ae450c665
[]
no_license
daoudclarke/tag-dialogue-framework
https://github.com/daoudclarke/tag-dialogue-framework
b660479870f568a80d21117c6b39ac68588f86f1
fa07bd8652a5b9b125c6f8eada5ae0c017c11a5e
refs/heads/master
2021-01-18T06:36:29.860000
2016-04-01T14:00:41
2016-04-01T14:00:41
40,012,269
0
0
null
true
2015-07-31T15:39:50
2015-07-31T15:39:50
2015-07-02T12:29:45
2015-07-02T12:28:36
2,156
0
0
0
null
null
null
package uk.ac.susx.tag.dialoguer.dialogue.components; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Set; /** * Represents an intent of the user. An intent has a name, and potentially text associated with it (optional). * * It also has a number of filled slots. * * Each slot has a type and a value (and optionally, a start and end span in the text). * * There can be multiple values for a single slot type. * * There are a number of default intents. See the public static fields. * * User: Andrew D. Robertson * Date: 16/03/2015 * Time: 14:58 */ public class Intent { // Default intents names that may have default behaviour public static final String nullChoice = "null_choice"; // User is explicitly rejecting a list of choices public static final String noChoice = "no_choice"; // User is ignoring the presented choices public static final String allChoice = "all_choice"; // User is selects everything in multi-choice public static final String choice = "choice"; //User is making a choice. The choice will be in the "choice" slot. public static final String no = "no"; //User wishes to say no or decline or is ignoring a request for confirmation public static final String yes = "yes"; //User wishes to say yes or confirm public static final String cancel = "cancel"; //User wishes to cancel public static final String cancelAutoQuery = "cancel_auto_query"; // User message implies that we should cancel auto-querying private String name; private String text; private HashMap<String, HashSet<Slot>> slots; private String source; public Intent(String name) { this(name, ""); } public Intent(String name, String text){ this(name, text, new HashMap<String, HashSet<Slot>>()); } public Intent(String name, String text, HashMap<String, HashSet<Slot>> slots){ this.name = name; this.text = text; this.slots = slots; this.source = null; } public String getName() { return name; } public void setName(String name) { this.name = name; } public boolean isName(String name) { return this.name.equals(name); } public String getText() { return text; } public void setText(String text) { this.text = text; } public void setSource(String sourceId){ source = sourceId; } public String getSource() { return source; } /********************************************** * Slot management **********************************************/ public void copySlots(List<Intent> intents){ for (Intent i : intents) { Collection<Slot> slots = i.getSlotCollection(); for (Slot slot : slots) { fillSlot(slot); } } } public IntentMatch getIntentMatch(Set<String> requiredSlotNames){ return new IntentMatch(this, requiredSlotNames); } public boolean isSlotTypeFilledWith(String type, String value){ Collection<Slot> slots = getSlotByType(type); for (Slot slot : slots) { if (slot.value.equals(value)) { return true; } } return false; } // public static boolean areSlotsFilled(List<Intent> intents, Map<String, Set<String>> necessarySlotsPerIntent){ // // Only return true if all slots are field on all intents // return intents.stream().allMatch(i -> i.areSlotsFilled(necessarySlotsPerIntent.get(i.getName()))); // } public HashSet<String> getUnfilledSlotNames(Set<String> requiredSlotNames){ HashSet<String> results = new HashSet<>(requiredSlotNames); results.removeAll(slots.keySet()); return results; } public boolean areSlotsFilled(Set<String> requiredSlotNames){ return getUnfilledSlotNames(requiredSlotNames).isEmpty(); } public Intent fillSlot(String name, String value, int start, int end){ HashSet<Slot> slotsToFill = ensureSlotExists(name); slotsToFill.add(new Slot(name, value, start, end)); return this; } public Intent fillSlot(String name, String value){ return fillSlot(name, value, 0, 0); } public Intent fillSlot(Slot s){ HashSet<Slot> slotToFill = ensureSlotExists(s.name); slotToFill.add(s); return this; } public Intent replaceSlot(Slot s){ slots.remove(s.name); return fillSlot(s); } public Intent fillSlots(Collection<Slot> slotlist){ for (Slot s : slotlist) { fillSlot(s); } return this; } public Intent clearSlots(String name){ slots.remove(name); return this; } public Collection<Slot> getSlotByType(String slotType){ return slots.get(slotType);} public List<String> getSlotValuesByType(String slotType){ ArrayList<String> results = new ArrayList<>(); for (Slot slot : slots.get(slotType)) { results.add(slot.value); } return results; } // public Multimap<String, Slot> getSlots() { return slots; } public Collection<Slot> getSlotCollection() { HashSet<Slot> allSlots = new HashSet<>(); for (HashSet<Slot> slotSet : slots.values()) { allSlots.addAll(slotSet); } return allSlots; } // public void setSlots(Multimap<String, Slot> slots) { this.slots = slots; } public boolean isAnySlotFilled() { return !slots.isEmpty(); } public static class Slot { public String name; public String value; public int start; public int end; public Slot(String name, String value, int start, int end) { this.name = name; this.value = value; this.start = start; this.end = end; } public String toString() { return name + ":" + value + "(" + start + ":" + end + ")"; } } /********************************************** * Default intents **********************************************/ public static Intent buildNullChoiceIntent(String userMessage){ return new Intent(nullChoice, userMessage);} public static Intent buildNoChoiceIntent(String userMessage){ return new Intent(noChoice, userMessage); } public static Intent buildCancelIntent(String userMessage){ return new Intent(cancel, userMessage); } public static Intent buildNoIntent(String userMessage) { return new Intent(no, userMessage);} public static Intent buildYesIntent(String userMessage) { return new Intent(yes, userMessage); } public static Intent buildCancelAutoQueryIntent(String userMessage) { return new Intent(cancelAutoQuery, userMessage);} public static Intent buildChoiceIntent(String userMessage, int choiceNumber){ return new Intent(choice, userMessage) .fillSlot("choice", Integer.toString(choiceNumber), 0, 0); } public static Intent buildMultichoiceIntent(String userMessage, List<Integer> choices){ Intent intent = new Intent(choice, userMessage); for (int choiceNumber : choices) { intent = intent.fillSlot("choice", Integer.toString(choiceNumber), 0, 0); } return intent; } /********************************************** * Utility **********************************************/ @Override public String toString() { StringBuilder result = new StringBuilder(name); result.append(":"); for (HashSet<Slot> slotValues : slots.values()) { for (Slot slot : slotValues) { result.append(slot.toString()).append("-"); } } return result.toString(); } public List<Intent> toList(){ ArrayList<Intent> results = new ArrayList<>(); results.add(this); return results; } /** * Return true if an intent with name=*name* is in *intents*. */ public static boolean isPresent(String name, List<Intent> intents){ for (Intent intent : intents) { if (intent.isName(name)) { return true; } } return false; } // public static Intent getIfPresentElseNull(String name, List<Intent> intents){ // for (Intent intent : intents) { // if (intent.isName(name)) { // return intent; // } // } // return null; // } /** * Get first intent from *intents* which has the source specified. * If no such intent, then return null. */ public static Intent getFirstIntentFromSource(String source, List<Intent> intents){ for (Intent intent : intents) { if (intent.getSource().equals(source)) { return intent; } } return null; } // /** // * Create a new list from those elements in *intents* which have the source specified. // * Empty list will be returned if there are no such intents. // */ // public static List<Intent> getAllIntentsFromSource(String source, List<Intent> intents){ // ArrayList<Intent> results = new ArrayList<>(); // for (Intent intent : intents) { // if (intent.getSource().equals(source)) { // results.add(intent); // } // } // return results; // } // @Override // public String toString(){ // return Dialoguer.gson.toJson(this); // } /** * Create a set of slots for the given name if it doesn't exist, and return it, * or return the one that's already there. * @param name The name of the slot * @return The associated set of slots */ private HashSet<Slot> ensureSlotExists(String name) { HashSet<Slot> slotsToFill; if (!slots.containsKey(name)) { slotsToFill = new HashSet<>(); slots.put(name, slotsToFill); } else { slotsToFill = slots.get(name); } return slotsToFill; } }
UTF-8
Java
10,207
java
Intent.java
Java
[ { "context": "intents. See the public static fields.\n *\n * User: Andrew D. Robertson\n * Date: 16/03/2015\n * Time: 14:58\n */\npublic cla", "end": 625, "score": 0.9998676180839539, "start": 606, "tag": "NAME", "value": "Andrew D. Robertson" } ]
null
[]
package uk.ac.susx.tag.dialoguer.dialogue.components; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Set; /** * Represents an intent of the user. An intent has a name, and potentially text associated with it (optional). * * It also has a number of filled slots. * * Each slot has a type and a value (and optionally, a start and end span in the text). * * There can be multiple values for a single slot type. * * There are a number of default intents. See the public static fields. * * User: <NAME> * Date: 16/03/2015 * Time: 14:58 */ public class Intent { // Default intents names that may have default behaviour public static final String nullChoice = "null_choice"; // User is explicitly rejecting a list of choices public static final String noChoice = "no_choice"; // User is ignoring the presented choices public static final String allChoice = "all_choice"; // User is selects everything in multi-choice public static final String choice = "choice"; //User is making a choice. The choice will be in the "choice" slot. public static final String no = "no"; //User wishes to say no or decline or is ignoring a request for confirmation public static final String yes = "yes"; //User wishes to say yes or confirm public static final String cancel = "cancel"; //User wishes to cancel public static final String cancelAutoQuery = "cancel_auto_query"; // User message implies that we should cancel auto-querying private String name; private String text; private HashMap<String, HashSet<Slot>> slots; private String source; public Intent(String name) { this(name, ""); } public Intent(String name, String text){ this(name, text, new HashMap<String, HashSet<Slot>>()); } public Intent(String name, String text, HashMap<String, HashSet<Slot>> slots){ this.name = name; this.text = text; this.slots = slots; this.source = null; } public String getName() { return name; } public void setName(String name) { this.name = name; } public boolean isName(String name) { return this.name.equals(name); } public String getText() { return text; } public void setText(String text) { this.text = text; } public void setSource(String sourceId){ source = sourceId; } public String getSource() { return source; } /********************************************** * Slot management **********************************************/ public void copySlots(List<Intent> intents){ for (Intent i : intents) { Collection<Slot> slots = i.getSlotCollection(); for (Slot slot : slots) { fillSlot(slot); } } } public IntentMatch getIntentMatch(Set<String> requiredSlotNames){ return new IntentMatch(this, requiredSlotNames); } public boolean isSlotTypeFilledWith(String type, String value){ Collection<Slot> slots = getSlotByType(type); for (Slot slot : slots) { if (slot.value.equals(value)) { return true; } } return false; } // public static boolean areSlotsFilled(List<Intent> intents, Map<String, Set<String>> necessarySlotsPerIntent){ // // Only return true if all slots are field on all intents // return intents.stream().allMatch(i -> i.areSlotsFilled(necessarySlotsPerIntent.get(i.getName()))); // } public HashSet<String> getUnfilledSlotNames(Set<String> requiredSlotNames){ HashSet<String> results = new HashSet<>(requiredSlotNames); results.removeAll(slots.keySet()); return results; } public boolean areSlotsFilled(Set<String> requiredSlotNames){ return getUnfilledSlotNames(requiredSlotNames).isEmpty(); } public Intent fillSlot(String name, String value, int start, int end){ HashSet<Slot> slotsToFill = ensureSlotExists(name); slotsToFill.add(new Slot(name, value, start, end)); return this; } public Intent fillSlot(String name, String value){ return fillSlot(name, value, 0, 0); } public Intent fillSlot(Slot s){ HashSet<Slot> slotToFill = ensureSlotExists(s.name); slotToFill.add(s); return this; } public Intent replaceSlot(Slot s){ slots.remove(s.name); return fillSlot(s); } public Intent fillSlots(Collection<Slot> slotlist){ for (Slot s : slotlist) { fillSlot(s); } return this; } public Intent clearSlots(String name){ slots.remove(name); return this; } public Collection<Slot> getSlotByType(String slotType){ return slots.get(slotType);} public List<String> getSlotValuesByType(String slotType){ ArrayList<String> results = new ArrayList<>(); for (Slot slot : slots.get(slotType)) { results.add(slot.value); } return results; } // public Multimap<String, Slot> getSlots() { return slots; } public Collection<Slot> getSlotCollection() { HashSet<Slot> allSlots = new HashSet<>(); for (HashSet<Slot> slotSet : slots.values()) { allSlots.addAll(slotSet); } return allSlots; } // public void setSlots(Multimap<String, Slot> slots) { this.slots = slots; } public boolean isAnySlotFilled() { return !slots.isEmpty(); } public static class Slot { public String name; public String value; public int start; public int end; public Slot(String name, String value, int start, int end) { this.name = name; this.value = value; this.start = start; this.end = end; } public String toString() { return name + ":" + value + "(" + start + ":" + end + ")"; } } /********************************************** * Default intents **********************************************/ public static Intent buildNullChoiceIntent(String userMessage){ return new Intent(nullChoice, userMessage);} public static Intent buildNoChoiceIntent(String userMessage){ return new Intent(noChoice, userMessage); } public static Intent buildCancelIntent(String userMessage){ return new Intent(cancel, userMessage); } public static Intent buildNoIntent(String userMessage) { return new Intent(no, userMessage);} public static Intent buildYesIntent(String userMessage) { return new Intent(yes, userMessage); } public static Intent buildCancelAutoQueryIntent(String userMessage) { return new Intent(cancelAutoQuery, userMessage);} public static Intent buildChoiceIntent(String userMessage, int choiceNumber){ return new Intent(choice, userMessage) .fillSlot("choice", Integer.toString(choiceNumber), 0, 0); } public static Intent buildMultichoiceIntent(String userMessage, List<Integer> choices){ Intent intent = new Intent(choice, userMessage); for (int choiceNumber : choices) { intent = intent.fillSlot("choice", Integer.toString(choiceNumber), 0, 0); } return intent; } /********************************************** * Utility **********************************************/ @Override public String toString() { StringBuilder result = new StringBuilder(name); result.append(":"); for (HashSet<Slot> slotValues : slots.values()) { for (Slot slot : slotValues) { result.append(slot.toString()).append("-"); } } return result.toString(); } public List<Intent> toList(){ ArrayList<Intent> results = new ArrayList<>(); results.add(this); return results; } /** * Return true if an intent with name=*name* is in *intents*. */ public static boolean isPresent(String name, List<Intent> intents){ for (Intent intent : intents) { if (intent.isName(name)) { return true; } } return false; } // public static Intent getIfPresentElseNull(String name, List<Intent> intents){ // for (Intent intent : intents) { // if (intent.isName(name)) { // return intent; // } // } // return null; // } /** * Get first intent from *intents* which has the source specified. * If no such intent, then return null. */ public static Intent getFirstIntentFromSource(String source, List<Intent> intents){ for (Intent intent : intents) { if (intent.getSource().equals(source)) { return intent; } } return null; } // /** // * Create a new list from those elements in *intents* which have the source specified. // * Empty list will be returned if there are no such intents. // */ // public static List<Intent> getAllIntentsFromSource(String source, List<Intent> intents){ // ArrayList<Intent> results = new ArrayList<>(); // for (Intent intent : intents) { // if (intent.getSource().equals(source)) { // results.add(intent); // } // } // return results; // } // @Override // public String toString(){ // return Dialoguer.gson.toJson(this); // } /** * Create a set of slots for the given name if it doesn't exist, and return it, * or return the one that's already there. * @param name The name of the slot * @return The associated set of slots */ private HashSet<Slot> ensureSlotExists(String name) { HashSet<Slot> slotsToFill; if (!slots.containsKey(name)) { slotsToFill = new HashSet<>(); slots.put(name, slotsToFill); } else { slotsToFill = slots.get(name); } return slotsToFill; } }
10,194
0.599687
0.597923
311
31.819935
29.976728
135
false
false
0
0
0
0
0
0
0.517685
false
false
14
3722f6baa558560f179e1cf2e3aebd939b9979c0
34,832,184,781,516
0c5727398af35c369b9428c7a8f6a9e27412ed8a
/L_googleAlgorithm.java
ef63d072b48a2979d02a1e4402ba8774c42a0fe0
[]
no_license
NamKoongUk/GoogleExample
https://github.com/NamKoongUk/GoogleExample
9fa4784ff7e979407cd51722a9006d12116c817a
4552c0c41ce805e12a28b4293be5ebbdbc4e35e7
refs/heads/master
2020-04-17T14:57:53.971000
2019-01-20T15:56:16
2019-01-20T15:56:16
166,679,521
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.one.day; public class L_googleAlgorithm { public static void main(String[] args) { String[] str = new String[10000]; for(int i=0; i<10000; i++) { str[i] = String.valueOf(i); } int count=0; for(int i=0; i<10000; i++) { for(int j=0; j<str[i].length(); j++) { if(str[i].charAt(j) =='8') { count++; } } } System.out.println(count); } }
UTF-8
Java
436
java
L_googleAlgorithm.java
Java
[]
null
[]
package com.one.day; public class L_googleAlgorithm { public static void main(String[] args) { String[] str = new String[10000]; for(int i=0; i<10000; i++) { str[i] = String.valueOf(i); } int count=0; for(int i=0; i<10000; i++) { for(int j=0; j<str[i].length(); j++) { if(str[i].charAt(j) =='8') { count++; } } } System.out.println(count); } }
436
0.488532
0.442661
29
13.034483
14.44486
41
false
false
0
0
0
0
0
0
2.206897
false
false
14
43a393773bd4c366caa3e4ce2c882bfcc506d2f8
18,691,697,730,792
c790fd8a73bf34bca75463554ec500a2338c5312
/src/edu/ieu/hilosJava/MainThread.java
2ba041e4ce9db39b70c8dc7bdec52d4d3362733a
[ "Apache-2.0" ]
permissive
MicheelG1/hilosjava2
https://github.com/MicheelG1/hilosjava2
985b1bf52c99ab473039b0cbb2422a8db2ff380a
ba5865030951b92201f86ca264b0eebb51c137c6
refs/heads/main
2023-05-31T14:17:03.545000
2021-06-12T00:51:50
2021-06-12T00:51:50
376,173,338
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package edu.ieu.hilosJava; public class MainThread { public static void main(String[] args) { Cliente cliente1 = new Cliente("Cliente Micheel", new int[] {2,2,1,5,2}); Cliente cliente2 = new Cliente("Cliente Eduardo", new int[] {1,3,5,1,1}); Cliente cliente3 = new Cliente("Cliente Micheel", new int[] {5,2,4,7,2}); long initialTime = System.currentTimeMillis(); CajeraThread cajero1 = new CajeraThread("Cajero Cesar", cliente1, initialTime); CajeraThread cajero2 = new CajeraThread("Cajero Isidro", cliente2, initialTime); CajeraThread cajero3 = new CajeraThread("Cajero Micheel", cliente3, initialTime); cajero1.start(); cajero2.start(); cajero3.start(); } }
UTF-8
Java
696
java
MainThread.java
Java
[ { "context": " args) {\n\t\tCliente cliente1 = new Cliente(\"Cliente Micheel\", new int[] {2,2,1,5,2});\n\t\tCliente cliente2 = ne", "end": 147, "score": 0.9988696575164795, "start": 140, "tag": "NAME", "value": "Micheel" }, { "context": "1,5,2});\n\t\tCliente cliente2 = new Cliente(\"Cliente Eduardo\", new int[] {1,3,5,1,1});\n\t\tCliente cliente3 = ne", "end": 223, "score": 0.9994022250175476, "start": 216, "tag": "NAME", "value": "Eduardo" }, { "context": "5,1,1});\n\t\tCliente cliente3 = new Cliente(\"Cliente Micheel\", new int[] {5,2,4,7,2});\n\t\t\n\t\tlong initialTime =", "end": 299, "score": 0.9990134835243225, "start": 292, "tag": "NAME", "value": "Micheel" }, { "context": "();\n\t\t\n\t\tCajeraThread cajero1 = new CajeraThread(\"Cajero Cesar\", cliente1, initialTime);\n\t\tCajeraThread cajero2 ", "end": 436, "score": 0.9283658862113953, "start": 424, "tag": "NAME", "value": "Cajero Cesar" }, { "context": "Time);\n\t\tCajeraThread cajero2 = new CajeraThread(\"Cajero Isidro\", cliente2, initialTime);\n\t\tCajeraThread cajero3 ", "end": 519, "score": 0.985919177532196, "start": 506, "tag": "NAME", "value": "Cajero Isidro" }, { "context": "Time);\n\t\tCajeraThread cajero3 = new CajeraThread(\"Cajero Micheel\", cliente3, initialTime);\n\t\t\n\t\tcajero1.st", "end": 595, "score": 0.9959755539894104, "start": 589, "tag": "NAME", "value": "Cajero" }, { "context": "\n\t\tCajeraThread cajero3 = new CajeraThread(\"Cajero Micheel\", cliente3, initialTime);\n\t\t\n\t\tcajero1.start();\n\t", "end": 603, "score": 0.9473493695259094, "start": 596, "tag": "NAME", "value": "Micheel" } ]
null
[]
package edu.ieu.hilosJava; public class MainThread { public static void main(String[] args) { Cliente cliente1 = new Cliente("Cliente Micheel", new int[] {2,2,1,5,2}); Cliente cliente2 = new Cliente("Cliente Eduardo", new int[] {1,3,5,1,1}); Cliente cliente3 = new Cliente("Cliente Micheel", new int[] {5,2,4,7,2}); long initialTime = System.currentTimeMillis(); CajeraThread cajero1 = new CajeraThread("<NAME>", cliente1, initialTime); CajeraThread cajero2 = new CajeraThread("<NAME>", cliente2, initialTime); CajeraThread cajero3 = new CajeraThread("Cajero Micheel", cliente3, initialTime); cajero1.start(); cajero2.start(); cajero3.start(); } }
683
0.706897
0.668103
21
32.142857
32.092552
83
false
false
0
0
0
0
0
0
2.904762
false
false
14
43d8f47a89a074fb55bfe2bbdb215951ec3a37c8
24,455,543,832,552
fbd64cfe70deddfbd8f1641d8a963c86e12b5ce7
/core/src/main/java/net/andreho/core/func/VoidFunc_2.java
cdac5033d6b95dbe8b5bab5c27c1f3b7376d2e31
[ "MIT" ]
permissive
andreho/mfi0
https://github.com/andreho/mfi0
9969ab46acd45e0eae8d9aa5f7d3429d516051b0
0388d77f2512f84008729d86d7557817e46494ba
refs/heads/master
2016-08-12T05:22:52.806000
2016-04-13T00:18:43
2016-04-13T00:18:43
36,656,439
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package net.andreho.core.func; /** * <br/>Created by a.hofmann on 18.05.2014 at 03:53<br/> */ @FunctionalInterface public interface VoidFunc_2<A,B> extends VoidFunc { /** * * @return */ void call(A a, B b); //---------------------------------------------------------------------------------------------------------------- @Override default void invoke(Object... args) { call( (A) args[0], (B) args[1] ); } @Override default int getArity() { return 2; } /** * @param a1 * @return */ default <R> Invokable<R> freeze(A a1, B b1) { return () -> { call(a1, b1); return null; }; } @Override default <R> Func_2<R,A,B> toFuncWith(final R result) { return (a,b) -> { VoidFunc_2.this.call(a,b); return result; }; } }
UTF-8
Java
957
java
VoidFunc_2.java
Java
[ { "context": "age net.andreho.core.func;\n\n/**\n * <br/>Created by a.hofmann on 18.05.2014 at 03:53<br/>\n */\n@FunctionalInterf", "end": 64, "score": 0.8341511487960815, "start": 55, "tag": "USERNAME", "value": "a.hofmann" } ]
null
[]
package net.andreho.core.func; /** * <br/>Created by a.hofmann on 18.05.2014 at 03:53<br/> */ @FunctionalInterface public interface VoidFunc_2<A,B> extends VoidFunc { /** * * @return */ void call(A a, B b); //---------------------------------------------------------------------------------------------------------------- @Override default void invoke(Object... args) { call( (A) args[0], (B) args[1] ); } @Override default int getArity() { return 2; } /** * @param a1 * @return */ default <R> Invokable<R> freeze(A a1, B b1) { return () -> { call(a1, b1); return null; }; } @Override default <R> Func_2<R,A,B> toFuncWith(final R result) { return (a,b) -> { VoidFunc_2.this.call(a,b); return result; }; } }
957
0.392894
0.368861
53
17.056604
20.073841
118
false
false
0
0
0
0
0
0
0.358491
false
false
14
6793c7fdad130b401fcb7374199f3fee52696940
29,532,195,185,206
e14f96899f98cbd5084ab44eb840a3b7f9eaf409
/services/verification-context/domain/entities/src/main/java/uk/co/idv/domain/entities/verificationcontext/method/pushnotification/PushNotificationEligible.java
c4660e48dfd4316c30c23b695429654b56c7b2be
[]
no_license
michaelruocco/idv
https://github.com/michaelruocco/idv
d3b9619495d229a7d4b45a60a2d31d169c1348f5
fb07c68186e197458b57d26ac13d5a577767ebad
refs/heads/master
2021-06-12T18:40:53.572000
2021-04-04T07:52:23
2021-04-04T07:52:23
172,199,037
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package uk.co.idv.domain.entities.verificationcontext.method.pushnotification; import lombok.Builder; import uk.co.idv.domain.entities.verificationcontext.method.VerificationMethodParams; import uk.co.idv.domain.entities.verificationcontext.method.eligibility.Eligible; import uk.co.idv.domain.entities.verificationcontext.result.DefaultVerificationResults; import uk.co.idv.domain.entities.verificationcontext.result.VerificationResults; public class PushNotificationEligible extends PushNotification { public PushNotificationEligible(final VerificationMethodParams params) { this(params, new DefaultVerificationResults()); } @Builder public PushNotificationEligible(final VerificationMethodParams params, final VerificationResults results) { super(params, new Eligible(), results); } }
UTF-8
Java
865
java
PushNotificationEligible.java
Java
[]
null
[]
package uk.co.idv.domain.entities.verificationcontext.method.pushnotification; import lombok.Builder; import uk.co.idv.domain.entities.verificationcontext.method.VerificationMethodParams; import uk.co.idv.domain.entities.verificationcontext.method.eligibility.Eligible; import uk.co.idv.domain.entities.verificationcontext.result.DefaultVerificationResults; import uk.co.idv.domain.entities.verificationcontext.result.VerificationResults; public class PushNotificationEligible extends PushNotification { public PushNotificationEligible(final VerificationMethodParams params) { this(params, new DefaultVerificationResults()); } @Builder public PushNotificationEligible(final VerificationMethodParams params, final VerificationResults results) { super(params, new Eligible(), results); } }
865
0.783815
0.783815
21
40.190475
35.431515
87
false
false
0
0
0
0
0
0
0.571429
false
false
14
59cbfb978dffe8b45fec64aaf80419f100248f1f
9,560,597,215,435
73308ecf567af9e5f4ef8d5ff10f5e9a71e81709
/so66080463/src/main/java/com/example/so66080463/TestService.java
c60ee2b56c4e6d26135a22a6e949751ac9460aca
[]
no_license
yukihane/stackoverflow-qa
https://github.com/yukihane/stackoverflow-qa
bfaf371e3c61919492e2084ed4c65f33323d7231
ba5e6a0d51f5ecfa80bb149456adea49de1bf6fb
refs/heads/main
2023-08-03T06:54:32.086000
2023-07-26T20:02:07
2023-07-26T20:02:07
194,699,870
3
3
null
false
2023-03-02T23:37:45
2019-07-01T15:34:08
2022-12-14T23:02:29
2023-03-02T23:37:45
8,277
3
2
79
Java
false
false
package com.example.so66080463; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; import org.springframework.stereotype.Service; @Service public class TestService { private final TestStringsHolder holder; public TestService(TestStringsHolder holder) { this.holder = holder; } public List<String> getStringsOverLength5() { final String[] testStrings = holder.getTestStrings(); return Arrays.stream(testStrings) .filter(s -> s.length() > 5) .collect(Collectors.toList()); } }
UTF-8
Java
582
java
TestService.java
Java
[]
null
[]
package com.example.so66080463; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; import org.springframework.stereotype.Service; @Service public class TestService { private final TestStringsHolder holder; public TestService(TestStringsHolder holder) { this.holder = holder; } public List<String> getStringsOverLength5() { final String[] testStrings = holder.getTestStrings(); return Arrays.stream(testStrings) .filter(s -> s.length() > 5) .collect(Collectors.toList()); } }
582
0.690722
0.67354
24
23.25
19.933744
61
false
false
0
0
0
0
0
0
0.375
false
false
14
ddaffd66b2b3cb9bcaf816e3492e00364aea8bb2
6,081,673,714,620
54636417ac68e98df5607b34f6b3329ddb7ad647
/src/main/java/cz/muni/fi/pv168/musicManager/gui/MusicManagerFrame.java
273f8e9b1635c847c57dbb0e2a66c9f87fa3764e
[]
no_license
domhanak/pv168_mmanager
https://github.com/domhanak/pv168_mmanager
1e67556bcff5234efa4f6280da0463c973a31023
3a90958d95bb30e6bf76ae6fd2a20ed679e39878
refs/heads/master
2021-01-01T20:10:17.350000
2014-05-07T14:17:38
2014-05-07T14:17:38
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package cz.muni.fi.pv168.musicManager.gui; import cz.muni.fi.pv168.musicManager.api.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import javax.swing.*; /** * Created by Hany on 29.4.2014. */ public class MusicManagerFrame { private AlbumManager albumManager; private SongManager songManager; private MusicManager musicManager; final static Logger log = LoggerFactory.getLogger(MusicManagerFrame.class); private JTabbedPane MainPanel; private JPanel panel1; private JPanel musicTab; private JTable musicTable; private JTable songsInAlbumTable; private JButton deleteAlbumButton; private JPanel albumTab; private JTable albumTable; private JButton createAlbumButton; private JPanel addSongPanel; private JLabel headerLabel; private JTextField nameTextField; private JTextField genreTextField; private JLabel nameLabel; private JLabel rankLabel; private JLabel trackLabel; private JLabel lengthLabel; private JTextField artistTextField; private JTextField yearTextField; private JTable songTable; private JButton pairButton; private JButton deleteAlbumButton1; private JButton deleteSongButton; private JButton addAlbumButton; private JButton deleteSongFromAlbumButton; private JButton createSongButton; private JTextField songNameTextField; private JTextField songTrackTextField; private JTextField songLengthTextField; private JTextField songRankTextField; public JPanel getPanel() { return panel1; } public MusicManagerFrame() { ApplicationContext springContext = new AnnotationConfigApplicationContext(SpringConfig.class); songManager = springContext.getBean("songManager", SongManager.class); albumManager = springContext.getBean("albumManager", AlbumManager.class); musicManager = springContext.getBean("musicManager", MusicManager.class); try { initializeMusicTables(); } catch (AlbumException e) { e.printStackTrace(); } catch (MusicManagerException e) { e.printStackTrace(); } createAlbumButton.addActionListener(e2 -> { /* Get values from textfields */ String name = nameTextField.getText(); String genre = genreTextField.getText(); String artist = artistTextField.getText(); int year = Integer.parseInt(yearTextField.getText()); /* Create new album to add into DB */ Album album = new Album(); album.setName(name); album.setArtist(artist); album.setGenre(genre); album.setYear(year); SwingWorker swingWorker = new SwingWorker() { @Override protected Album doInBackground() throws Exception { try { albumManager.createAlbum(album); log.debug("Created album {}", album); } catch (AlbumException e1) { log.error("Album not created" + e1); e1.printStackTrace(); } return album; } @Override protected void done() { AlbumTableModel aModel = (AlbumTableModel) albumTable.getModel(); aModel.addAlbum(album); } }; swingWorker.execute(); /* try { albumManager.createAlbum(album); log.debug("Created album {}", album); } catch (AlbumException e1) { log.error("Album not created" + e1); e1.printStackTrace(); } AlbumTableModel aModel = (AlbumTableModel) albumTable.getModel(); aModel.addAlbum(album);*/ }); createSongButton.addActionListener(e -> { String name = songNameTextField.getText(); int rank = Integer.parseInt(songRankTextField.getText()); int track = Integer.parseInt(songTrackTextField.getText()); int length = Integer.parseInt(songLengthTextField.getText()); Song song = new Song(); song.setName(name); song.setRank(rank); song.setTrack(track); song.setLength(length); try { songManager.createSong(song); } catch (SongException e1) { log.error(""); e1.printStackTrace(); } }); deleteAlbumButton1.addActionListener((e) -> { int row = albumTable.convertRowIndexToModel(albumTable.getSelectedRow()); AlbumTableModel albumTableModel = (AlbumTableModel) albumTable.getModel(); String name = (String) albumTableModel.getValueAt(row , 0); try { Album album = albumManager.getAlbumByName(name); albumManager.deleteAlbum(album); } catch (AlbumException e1) { e1.printStackTrace(); } }); } private void initializeMusicTables() throws AlbumException, MusicManagerException { musicTable.setModel(new AlbumTableModel()); AlbumTableModel model = (AlbumTableModel) musicTable.getModel(); model.addAlbums(albumManager.findAllAlbums()); musicTable.setOpaque(true); songsInAlbumTable.setModel(new SongTableModel()); SongTableModel stModel = (SongTableModel) songsInAlbumTable.getModel(); Album album = albumManager.getAlbumByName((String) model.getValueAt(0, 0)); stModel.addSongs(musicManager.getAllSongsFromAlbum(album)); songsInAlbumTable.setOpaque(true); albumTable.setModel(new AlbumTableModel()); AlbumTableModel aModel = (AlbumTableModel) albumTable.getModel(); aModel.addAlbums(albumManager.findAllAlbums()); albumTable.setOpaque(true); songTable.setModel(new SongTableModel()); SongTableModel sModel = (SongTableModel) songTable.getModel(); sModel.addSongs(songManager.getAllSongs()); songTable.setOpaque(true); } }
UTF-8
Java
6,375
java
MusicManagerFrame.java
Java
[ { "context": "Context;\n\nimport javax.swing.*;\n\n/**\n * Created by Hany on 29.4.2014.\n */\n\npublic class MusicManagerFrame", "end": 328, "score": 0.6804465055465698, "start": 324, "tag": "NAME", "value": "Hany" } ]
null
[]
package cz.muni.fi.pv168.musicManager.gui; import cz.muni.fi.pv168.musicManager.api.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import javax.swing.*; /** * Created by Hany on 29.4.2014. */ public class MusicManagerFrame { private AlbumManager albumManager; private SongManager songManager; private MusicManager musicManager; final static Logger log = LoggerFactory.getLogger(MusicManagerFrame.class); private JTabbedPane MainPanel; private JPanel panel1; private JPanel musicTab; private JTable musicTable; private JTable songsInAlbumTable; private JButton deleteAlbumButton; private JPanel albumTab; private JTable albumTable; private JButton createAlbumButton; private JPanel addSongPanel; private JLabel headerLabel; private JTextField nameTextField; private JTextField genreTextField; private JLabel nameLabel; private JLabel rankLabel; private JLabel trackLabel; private JLabel lengthLabel; private JTextField artistTextField; private JTextField yearTextField; private JTable songTable; private JButton pairButton; private JButton deleteAlbumButton1; private JButton deleteSongButton; private JButton addAlbumButton; private JButton deleteSongFromAlbumButton; private JButton createSongButton; private JTextField songNameTextField; private JTextField songTrackTextField; private JTextField songLengthTextField; private JTextField songRankTextField; public JPanel getPanel() { return panel1; } public MusicManagerFrame() { ApplicationContext springContext = new AnnotationConfigApplicationContext(SpringConfig.class); songManager = springContext.getBean("songManager", SongManager.class); albumManager = springContext.getBean("albumManager", AlbumManager.class); musicManager = springContext.getBean("musicManager", MusicManager.class); try { initializeMusicTables(); } catch (AlbumException e) { e.printStackTrace(); } catch (MusicManagerException e) { e.printStackTrace(); } createAlbumButton.addActionListener(e2 -> { /* Get values from textfields */ String name = nameTextField.getText(); String genre = genreTextField.getText(); String artist = artistTextField.getText(); int year = Integer.parseInt(yearTextField.getText()); /* Create new album to add into DB */ Album album = new Album(); album.setName(name); album.setArtist(artist); album.setGenre(genre); album.setYear(year); SwingWorker swingWorker = new SwingWorker() { @Override protected Album doInBackground() throws Exception { try { albumManager.createAlbum(album); log.debug("Created album {}", album); } catch (AlbumException e1) { log.error("Album not created" + e1); e1.printStackTrace(); } return album; } @Override protected void done() { AlbumTableModel aModel = (AlbumTableModel) albumTable.getModel(); aModel.addAlbum(album); } }; swingWorker.execute(); /* try { albumManager.createAlbum(album); log.debug("Created album {}", album); } catch (AlbumException e1) { log.error("Album not created" + e1); e1.printStackTrace(); } AlbumTableModel aModel = (AlbumTableModel) albumTable.getModel(); aModel.addAlbum(album);*/ }); createSongButton.addActionListener(e -> { String name = songNameTextField.getText(); int rank = Integer.parseInt(songRankTextField.getText()); int track = Integer.parseInt(songTrackTextField.getText()); int length = Integer.parseInt(songLengthTextField.getText()); Song song = new Song(); song.setName(name); song.setRank(rank); song.setTrack(track); song.setLength(length); try { songManager.createSong(song); } catch (SongException e1) { log.error(""); e1.printStackTrace(); } }); deleteAlbumButton1.addActionListener((e) -> { int row = albumTable.convertRowIndexToModel(albumTable.getSelectedRow()); AlbumTableModel albumTableModel = (AlbumTableModel) albumTable.getModel(); String name = (String) albumTableModel.getValueAt(row , 0); try { Album album = albumManager.getAlbumByName(name); albumManager.deleteAlbum(album); } catch (AlbumException e1) { e1.printStackTrace(); } }); } private void initializeMusicTables() throws AlbumException, MusicManagerException { musicTable.setModel(new AlbumTableModel()); AlbumTableModel model = (AlbumTableModel) musicTable.getModel(); model.addAlbums(albumManager.findAllAlbums()); musicTable.setOpaque(true); songsInAlbumTable.setModel(new SongTableModel()); SongTableModel stModel = (SongTableModel) songsInAlbumTable.getModel(); Album album = albumManager.getAlbumByName((String) model.getValueAt(0, 0)); stModel.addSongs(musicManager.getAllSongsFromAlbum(album)); songsInAlbumTable.setOpaque(true); albumTable.setModel(new AlbumTableModel()); AlbumTableModel aModel = (AlbumTableModel) albumTable.getModel(); aModel.addAlbums(albumManager.findAllAlbums()); albumTable.setOpaque(true); songTable.setModel(new SongTableModel()); SongTableModel sModel = (SongTableModel) songTable.getModel(); sModel.addSongs(songManager.getAllSongs()); songTable.setOpaque(true); } }
6,375
0.626824
0.621647
174
35.637932
23.379944
102
false
false
0
0
0
0
0
0
0.683908
false
false
14
5ad8a86e3e3a48c6ea63d427f81aa39c0386a2f2
15,375,982,963,330
9c82af15512c022bbb03c88d4ee487ef2a6bcd25
/src/main/java/solutions/linked/slds/translation/IriNamespaceTranslator.java
1b7928c155ef1214571e44666713b7f0791de8a9
[]
no_license
linked-solutions/slds
https://github.com/linked-solutions/slds
e7f9ce204f69129c0af0414d2fd1c84229a127e0
23c58145972f3ed9c75c4bac3b311c1fad1f33db
refs/heads/master
2023-05-27T19:58:33.140000
2019-11-08T16:30:16
2019-11-08T16:30:16
88,235,516
1
0
null
false
2021-06-15T16:07:31
2017-04-14T05:21:13
2019-11-08T16:32:30
2021-06-15T16:07:30
87
0
0
3
Java
false
false
package solutions.linked.slds.translation; import org.apache.clerezza.commons.rdf.Graph; import org.apache.clerezza.commons.rdf.IRI; import org.apache.clerezza.rdf.utils.UriMutatingGraph; public class IriNamespaceTranslator implements IriTranslator { final String origPrefix, targetPrefix; public IriNamespaceTranslator(String origPrefix, String targetPrefix) { this.origPrefix = origPrefix; this.targetPrefix = targetPrefix; } @Override public IriTranslator reverse() { return new IriNamespaceTranslator(targetPrefix, origPrefix); } @Override public IRI translate(IRI orig) { String origString = orig.getUnicodeString(); if (origString.startsWith(origPrefix)) { return new IRI(targetPrefix+origString.substring(origPrefix.length())); } else { return orig; } } @Override public Graph translate(Graph orig) { return new UriMutatingGraph(orig, origPrefix, targetPrefix); } }
UTF-8
Java
1,037
java
IriNamespaceTranslator.java
Java
[]
null
[]
package solutions.linked.slds.translation; import org.apache.clerezza.commons.rdf.Graph; import org.apache.clerezza.commons.rdf.IRI; import org.apache.clerezza.rdf.utils.UriMutatingGraph; public class IriNamespaceTranslator implements IriTranslator { final String origPrefix, targetPrefix; public IriNamespaceTranslator(String origPrefix, String targetPrefix) { this.origPrefix = origPrefix; this.targetPrefix = targetPrefix; } @Override public IriTranslator reverse() { return new IriNamespaceTranslator(targetPrefix, origPrefix); } @Override public IRI translate(IRI orig) { String origString = orig.getUnicodeString(); if (origString.startsWith(origPrefix)) { return new IRI(targetPrefix+origString.substring(origPrefix.length())); } else { return orig; } } @Override public Graph translate(Graph orig) { return new UriMutatingGraph(orig, origPrefix, targetPrefix); } }
1,037
0.684667
0.684667
38
26.289474
24.639408
82
false
false
0
0
0
0
0
0
0.447368
false
false
14
1ff3aff1b06436248119862ce79d561712dde9e2
14,766,097,612,230
dcf1c9cdc2864cd015c6300e017effb98daaa57f
/src/main/java/com/sunway/webapp/basicStaticTables/areas/service/AreasService.java
0c5b73b085523b079170dea0d597325b6f3ebf27
[]
no_license
lidk/ssmshiro
https://github.com/lidk/ssmshiro
944245a33303c055ea22989bdbb3610ce8d0f58a
1afe85fa975dd41eca77c2a9c672d808a2e7814e
refs/heads/master
2020-03-26T01:37:47.235000
2018-08-11T10:13:33
2018-08-11T10:13:33
144,375,215
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.sunway.webapp.basicStaticTables.areas.service; public class AreasService { }
UTF-8
Java
91
java
AreasService.java
Java
[]
null
[]
package com.sunway.webapp.basicStaticTables.areas.service; public class AreasService { }
91
0.813187
0.813187
5
17.200001
22.868319
58
false
false
0
0
0
0
0
0
0.2
false
false
14
c1496c8644ad91699d37b0da94d2cd22e2b1ea9d
13,451,837,576,173
89a98882238c01254c9d589090003257cf2c1c2a
/api/Locations.java
dee2a4e8239a8d10e6776bf68fc85b8687b9d40f
[]
no_license
Wowzer69/SimpleBotScripts
https://github.com/Wowzer69/SimpleBotScripts
ae51cf844a4a5089d29542e81a8e8ca6370b8674
c12ede22d8c5ded0ad95a79cce6d87ba0b8a1780
refs/heads/main
2023-06-10T07:38:14.416000
2021-07-03T17:48:13
2021-07-03T17:48:13
337,362,362
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package api; import net.runelite.api.coords.WorldPoint; import simple.robot.utils.WorldArea; public class Locations { public final static WorldArea EDGEVILLE_AREA = new WorldArea(new WorldPoint(3074, 3515, 0), new WorldPoint(3105, 3480, 0)); public final static WorldArea EDGEVILLE_BANK = new WorldArea(new WorldPoint(3098, 3487, 0), new WorldPoint(3090, 3499, 0)); public final static WorldArea BARROWS_HILLS = new WorldArea( new WorldPoint[] { new WorldPoint(3565, 3314, 0), new WorldPoint(3543, 3299, 0), new WorldPoint(3547, 3270, 0), new WorldPoint(3566, 3266, 0), new WorldPoint(3584, 3275, 0), new WorldPoint(3583, 3306, 0) }); public final static WorldArea BURTHORPE_AREA = new WorldArea(new WorldPoint(2892, 3557, 0), new WorldPoint(2934, 3529, 0));; public final static WorldArea BARROWS_FINAL_SARCO = new WorldArea(new WorldPoint(3547, 9700, 0), new WorldPoint(3558, 9690, 0)); public static final WorldArea BANDOS_AREA = new WorldArea(new WorldPoint(2860, 5374, 2), new WorldPoint(2878, 5349, 2));; public final static WorldArea VORKATH_START_AREA = new WorldArea(new WorldPoint(2270, 4054, 0), new WorldPoint(2276, 4035, 0)); }
UTF-8
Java
1,194
java
Locations.java
Java
[]
null
[]
package api; import net.runelite.api.coords.WorldPoint; import simple.robot.utils.WorldArea; public class Locations { public final static WorldArea EDGEVILLE_AREA = new WorldArea(new WorldPoint(3074, 3515, 0), new WorldPoint(3105, 3480, 0)); public final static WorldArea EDGEVILLE_BANK = new WorldArea(new WorldPoint(3098, 3487, 0), new WorldPoint(3090, 3499, 0)); public final static WorldArea BARROWS_HILLS = new WorldArea( new WorldPoint[] { new WorldPoint(3565, 3314, 0), new WorldPoint(3543, 3299, 0), new WorldPoint(3547, 3270, 0), new WorldPoint(3566, 3266, 0), new WorldPoint(3584, 3275, 0), new WorldPoint(3583, 3306, 0) }); public final static WorldArea BURTHORPE_AREA = new WorldArea(new WorldPoint(2892, 3557, 0), new WorldPoint(2934, 3529, 0));; public final static WorldArea BARROWS_FINAL_SARCO = new WorldArea(new WorldPoint(3547, 9700, 0), new WorldPoint(3558, 9690, 0)); public static final WorldArea BANDOS_AREA = new WorldArea(new WorldPoint(2860, 5374, 2), new WorldPoint(2878, 5349, 2));; public final static WorldArea VORKATH_START_AREA = new WorldArea(new WorldPoint(2270, 4054, 0), new WorldPoint(2276, 4035, 0)); }
1,194
0.725293
0.589615
24
47.75
49.148796
125
false
false
0
0
0
0
0
0
3.333333
false
false
14
23d38da50deeaadb04f8512845fe87f9d37901e3
33,208,687,185,129
87ceec16b21d66248cc6ef2ef8cdf743c1742368
/registro-proyectos/src/main/java/sistemainformacion/registroproyectos/RegistroProyectosApplication.java
28ea790ec2f37ac0554cd5a704af8b3e1269a700
[]
no_license
padovil/Prueba
https://github.com/padovil/Prueba
7c381085a154c9ca8cd158cc9c3218c94e08b8a8
1ad0310c45ffa2ccac1f04b5b4e19d7e0a3c3771
refs/heads/main
2023-09-06T01:10:12.433000
2021-11-17T17:38:49
2021-11-17T17:38:49
429,142,216
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package sistemainformacion.registroproyectos; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.domain.EntityScan; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.ComponentScan; @EntityScan(basePackages = {"sistemainformacion.registroproyectos.Model"}) @SpringBootApplication @ComponentScan @EnableConfigurationProperties public class RegistroProyectosApplication { public static void main(String[] args) { SpringApplication.run(RegistroProyectosApplication.class, args); } }
UTF-8
Java
681
java
RegistroProyectosApplication.java
Java
[]
null
[]
package sistemainformacion.registroproyectos; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.domain.EntityScan; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.ComponentScan; @EntityScan(basePackages = {"sistemainformacion.registroproyectos.Model"}) @SpringBootApplication @ComponentScan @EnableConfigurationProperties public class RegistroProyectosApplication { public static void main(String[] args) { SpringApplication.run(RegistroProyectosApplication.class, args); } }
681
0.859031
0.859031
20
33.049999
28.728861
81
false
false
0
0
0
0
0
0
0.6
false
false
14
ceed320fff4f612eb8fb239b9186cc768da7f1cb
27,805,618,299,376
c302d7ef3bbc407c19785ff327fcd70606b9bf5b
/src/main/java/io/grpc/examples/featureengineering/FeatureEngineeringClient.java
16c18a0d591e4970337110e346ad0564793bced3
[]
no_license
sameeraxiomine/grpc-aiml
https://github.com/sameeraxiomine/grpc-aiml
df2a2d553936c5c556e720bbf9a706535fae68f9
b7018573283e03914bbfc644c78493458d8067e6
refs/heads/master
2022-12-27T15:25:30.120000
2020-04-27T14:07:28
2020-04-27T14:07:28
259,312,777
0
0
null
false
2020-10-13T21:32:56
2020-04-27T12:37:30
2020-04-27T14:07:37
2020-10-13T21:32:55
3,367
0
0
1
Python
false
false
/* * Copyright 2015 The gRPC Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.grpc.examples.featureengineering; import io.grpc.Channel; import io.grpc.ManagedChannel; import io.grpc.ManagedChannelBuilder; import io.grpc.StatusRuntimeException; import io.grpc.examples.featureengineering.Event; import io.grpc.examples.featureengineering.EventList; import io.grpc.examples.featureengineering.FEEvent; import io.grpc.examples.featureengineering.FeatureEngineerGrpc; import io.grpc.examples.featureengineering.Event.Builder; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; import java.util.logging.Level; import java.util.logging.Logger; /** * A simple client that requests a greeting from the {@link HelloWorldServer}. */ public class FeatureEngineeringClient { private static final Logger logger = Logger.getLogger(FeatureEngineeringClient.class.getName()); private final FeatureEngineerGrpc.FeatureEngineerBlockingStub blockingStub; /** Construct client for accessing HelloWorld server using the existing channel. */ public FeatureEngineeringClient(Channel channel) { // 'channel' here is a Channel, not a ManagedChannel, so it is not this code's responsibility to // shut it down. // Passing Channels to code makes code easier to test and makes it easier to reuse Channels. blockingStub = FeatureEngineerGrpc.newBlockingStub(channel); } /** Say hello to server. */ public void engineerFeatures(List<Event> myEvents) { logger.info("Engineer Features " + " ..."); //HelloRequest request = HelloRequest.newBuilder().setName(name).build(); io.grpc.examples.featureengineering.Event.Builder builder = Event.newBuilder().setF1(1); builder.setF2(2); builder.setF3(3); builder.setF4(4); Event evt1 = builder.build(); EventList.Builder builder2 = EventList.newBuilder(); builder2.addEvent(evt1); builder2.addEvent(evt1); EventList fe = builder2.build();; FEEvent response; try { response = blockingStub.engineerFeatures(fe); } catch (StatusRuntimeException e) { logger.log(Level.WARNING, "RPC failed: {0}", e.getStatus()); return; } Map<String,Integer> mymap = response.getResultMap(); logger.info("Greeting: " + response.getResultMap()); logger.info("F1:" + mymap.get("f1")); logger.info("F2:" + mymap.get("f2")); logger.info("F3:" + mymap.get("f3")); logger.info("F4:" + mymap.get("f4")); } /** * Greet server. If provided, the first element of {@code args} is the name to use in the * greeting. The second argument is the target server. */ public static void main(String[] args) throws Exception { // Access a service running on the local machine on port 50051 String target = "localhost:50053"; // Allow passing in the user and target strings as command line arguments if (args.length > 0) { if ("--help".equals(args[0])) { System.err.println("Usage: [target]"); System.err.println(""); System.err.println(" target The server to connect to. Defaults to " + target); System.exit(1); } } if (args.length > 0) { target = args[0]; } // Create a communication channel to the server, known as a Channel. Channels are thread-safe // and reusable. It is common to create channels at the beginning of your application and reuse // them until the application shuts down. ManagedChannel channel = ManagedChannelBuilder.forTarget(target) // Channels are secure by default (via SSL/TLS). For the example we disable TLS to avoid // needing certificates. .usePlaintext() .build(); try { FeatureEngineeringClient client = new FeatureEngineeringClient(channel); client.engineerFeatures(new ArrayList<Event>()); } finally { // ManagedChannels use resources like threads and TCP connections. To prevent leaking these // resources the channel should be shut down when it will no longer be used. If it may be used // again leave it running. channel.shutdownNow().awaitTermination(5, TimeUnit.SECONDS); } } }
UTF-8
Java
4,732
java
FeatureEngineeringClient.java
Java
[]
null
[]
/* * Copyright 2015 The gRPC Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.grpc.examples.featureengineering; import io.grpc.Channel; import io.grpc.ManagedChannel; import io.grpc.ManagedChannelBuilder; import io.grpc.StatusRuntimeException; import io.grpc.examples.featureengineering.Event; import io.grpc.examples.featureengineering.EventList; import io.grpc.examples.featureengineering.FEEvent; import io.grpc.examples.featureengineering.FeatureEngineerGrpc; import io.grpc.examples.featureengineering.Event.Builder; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; import java.util.logging.Level; import java.util.logging.Logger; /** * A simple client that requests a greeting from the {@link HelloWorldServer}. */ public class FeatureEngineeringClient { private static final Logger logger = Logger.getLogger(FeatureEngineeringClient.class.getName()); private final FeatureEngineerGrpc.FeatureEngineerBlockingStub blockingStub; /** Construct client for accessing HelloWorld server using the existing channel. */ public FeatureEngineeringClient(Channel channel) { // 'channel' here is a Channel, not a ManagedChannel, so it is not this code's responsibility to // shut it down. // Passing Channels to code makes code easier to test and makes it easier to reuse Channels. blockingStub = FeatureEngineerGrpc.newBlockingStub(channel); } /** Say hello to server. */ public void engineerFeatures(List<Event> myEvents) { logger.info("Engineer Features " + " ..."); //HelloRequest request = HelloRequest.newBuilder().setName(name).build(); io.grpc.examples.featureengineering.Event.Builder builder = Event.newBuilder().setF1(1); builder.setF2(2); builder.setF3(3); builder.setF4(4); Event evt1 = builder.build(); EventList.Builder builder2 = EventList.newBuilder(); builder2.addEvent(evt1); builder2.addEvent(evt1); EventList fe = builder2.build();; FEEvent response; try { response = blockingStub.engineerFeatures(fe); } catch (StatusRuntimeException e) { logger.log(Level.WARNING, "RPC failed: {0}", e.getStatus()); return; } Map<String,Integer> mymap = response.getResultMap(); logger.info("Greeting: " + response.getResultMap()); logger.info("F1:" + mymap.get("f1")); logger.info("F2:" + mymap.get("f2")); logger.info("F3:" + mymap.get("f3")); logger.info("F4:" + mymap.get("f4")); } /** * Greet server. If provided, the first element of {@code args} is the name to use in the * greeting. The second argument is the target server. */ public static void main(String[] args) throws Exception { // Access a service running on the local machine on port 50051 String target = "localhost:50053"; // Allow passing in the user and target strings as command line arguments if (args.length > 0) { if ("--help".equals(args[0])) { System.err.println("Usage: [target]"); System.err.println(""); System.err.println(" target The server to connect to. Defaults to " + target); System.exit(1); } } if (args.length > 0) { target = args[0]; } // Create a communication channel to the server, known as a Channel. Channels are thread-safe // and reusable. It is common to create channels at the beginning of your application and reuse // them until the application shuts down. ManagedChannel channel = ManagedChannelBuilder.forTarget(target) // Channels are secure by default (via SSL/TLS). For the example we disable TLS to avoid // needing certificates. .usePlaintext() .build(); try { FeatureEngineeringClient client = new FeatureEngineeringClient(channel); client.engineerFeatures(new ArrayList<Event>()); } finally { // ManagedChannels use resources like threads and TCP connections. To prevent leaking these // resources the channel should be shut down when it will no longer be used. If it may be used // again leave it running. channel.shutdownNow().awaitTermination(5, TimeUnit.SECONDS); } } }
4,732
0.707523
0.69738
122
37.786884
29.71924
100
false
false
0
0
0
0
0
0
0.52459
false
false
14
e16719b7ee584ca2b8d88d682899ac308aaaf556
28,295,244,551,230
ad395f934a84bba6125cf6d139cca1e6a151faab
/PAT/BasicLevel/1017loudou.java
e571d22d2794dcf24e6e33e1a07b450c00292936
[]
no_license
si-yuan-zhou/PAT-OJ
https://github.com/si-yuan-zhou/PAT-OJ
41f6e96c8f8151505dbe95d842d3dd7f44f58ebe
fa07233e32627dfd0a9f639769c3c967d95df637
refs/heads/master
2023-01-06T19:33:31.813000
2020-11-10T23:59:35
2020-11-10T23:59:35
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.util.Scanner; class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int num = sc.nextInt(); String c = sc.next(); sc.close(); int rst = 0; int i = 3; int rank = 1, div = 0; if(num > 0){ while(rst*2+1 < num){ rank = rst; rst += i; i += 2; } if(rst*2+1 == num) rank = i-2; else{ div = num -1-2*rank; rank = (i-4) != 0 ? i-4:1; } } printShape(rank, c); System.out.println(div); } public static void printShape(int rank,String c){ int i,j,work; for(i = rank, j = 0; i >= 1; i -= 2, j++){ //打印一行 //打印空白 work = 0; while(work < j){ System.out.print(" "); work++; } //打印符号 work = i; while(work != 0){ System.out.print(c); work--; } System.out.print('\n'); } for(i += 4, j -= 2; i <= rank; i+=2,j--){ work = 0; while(work < j){ System.out.print(" "); work++; } //打印符号 work = i; while(work != 0){ System.out.print(c); work--; } System.out.print('\n'); } } }
UTF-8
Java
1,637
java
1017loudou.java
Java
[]
null
[]
import java.util.Scanner; class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int num = sc.nextInt(); String c = sc.next(); sc.close(); int rst = 0; int i = 3; int rank = 1, div = 0; if(num > 0){ while(rst*2+1 < num){ rank = rst; rst += i; i += 2; } if(rst*2+1 == num) rank = i-2; else{ div = num -1-2*rank; rank = (i-4) != 0 ? i-4:1; } } printShape(rank, c); System.out.println(div); } public static void printShape(int rank,String c){ int i,j,work; for(i = rank, j = 0; i >= 1; i -= 2, j++){ //打印一行 //打印空白 work = 0; while(work < j){ System.out.print(" "); work++; } //打印符号 work = i; while(work != 0){ System.out.print(c); work--; } System.out.print('\n'); } for(i += 4, j -= 2; i <= rank; i+=2,j--){ work = 0; while(work < j){ System.out.print(" "); work++; } //打印符号 work = i; while(work != 0){ System.out.print(c); work--; } System.out.print('\n'); } } }
1,637
0.319626
0.302804
63
23.507936
12.3351
53
false
false
0
0
0
0
0
0
0.698413
false
false
14
dfd630312035a40c6a554dec656c47eca89de229
19,327,352,897,053
0562cecc4dfbf5ea09480a52b69ad187443f69d4
/src/main/java/edu/cmu/cs/stage3/alice/gallery/modeleditor/ModelEditor.java
4090b81b07bdb75baaea5e28b1cf5f94473279b8
[ "BSD-2-Clause" ]
permissive
vorburger/Alice
https://github.com/vorburger/Alice
9f12b91200b53c12ee562aad88be4964c9911aa6
af10b6edea7ecbf35bcba08d0853562fbe4a1837
refs/heads/master
2021-01-18T07:37:28.007000
2013-12-12T13:48:17
2013-12-12T13:48:17
3,757,745
1
2
null
null
null
null
null
null
null
null
null
null
null
null
null
package edu.cmu.cs.stage3.alice.gallery.modeleditor; public class ModelEditor extends javax.swing.JFrame { /*public static void main(String[] args) { ModelEditor modelEditor = new ModelEditor(); modelEditor.setLocation( 0, 0 ); modelEditor.setSize( 1280, 1000 ); edu.cmu.cs.stage3.alice.scenegraph.renderer.DefaultRenderTargetFactory drtf = new edu.cmu.cs.stage3.alice.scenegraph.renderer.DefaultRenderTargetFactory(); modelEditor.init( drtf ); if( args.length > 0 ) { modelEditor.onFileOpen( new java.io.File( args[ 0 ] ) ); } else { modelEditor.onFileOpen(); } modelEditor.setVisible( true ); modelEditor.m_tree.requestFocus(); }*/ private edu.cmu.cs.stage3.alice.core.World m_world; private edu.cmu.cs.stage3.alice.core.camera.SymmetricPerspectiveCamera m_camera; private edu.cmu.cs.stage3.alice.core.RenderTarget m_renderTarget; private edu.cmu.cs.stage3.alice.core.decorator.PivotDecorator m_pivotDecorator; private ElementTree m_tree; private ElementTreeModel m_treeModel; private int m_treeMouseEventModifiers = 0; private javax.swing.JButton m_prev; private javax.swing.JButton m_next; private javax.swing.JTextField m_modeledBy; private javax.swing.JTextField m_paintedBy; private javax.swing.JButton m_revert; private javax.swing.JCheckBox m_forceWireframe; private javax.swing.JFileChooser m_fileChooser; private java.io.File m_file; private boolean m_isDirty; public ModelEditor() { addWindowListener(new java.awt.event.WindowAdapter() { public void windowClosing( java.awt.event.WindowEvent e ) { onFileExit(); } }); javax.swing.JMenuBar menuBar = new javax.swing.JMenuBar(); javax.swing.JMenu fileMenu = new javax.swing.JMenu( "File" ); fileMenu.setMnemonic( java.awt.event.KeyEvent.VK_F ); javax.swing.JMenuItem fileOpenMenuItem = new javax.swing.JMenuItem( "Open..." ); fileOpenMenuItem.setMnemonic( java.awt.event.KeyEvent.VK_O ); fileOpenMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed( java.awt.event.ActionEvent e) { onFileOpen(); } }); javax.swing.JMenuItem fileSaveMenuItem = new javax.swing.JMenuItem( "Save" ); fileSaveMenuItem.setMnemonic( java.awt.event.KeyEvent.VK_S ); fileSaveMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed( java.awt.event.ActionEvent e) { onFileSave(); } }); // javax.swing.JMenuItem fileSaveAsMenuItem = new javax.swing.JMenuItem( "Save As..." ); // fileSaveAsMenuItem.setMnemonic( java.awt.event.KeyEvent.VK_A ); // fileSaveAsMenuItem.addActionListener(new java.awt.event.ActionListener() { // public void actionPerformed( java.awt.event.ActionEvent e) { // onFileSaveAs(); // } // }); javax.swing.JMenuItem fileExitMenuItem = new javax.swing.JMenuItem( "Exit..." ); fileExitMenuItem.setMnemonic( java.awt.event.KeyEvent.VK_X ); fileExitMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed( java.awt.event.ActionEvent e) { onFileExit(); } }); javax.swing.JMenu actionMenu = new javax.swing.JMenu( "Action" ); actionMenu.setMnemonic( java.awt.event.KeyEvent.VK_A ); javax.swing.JMenuItem actionNextMenuItem = new javax.swing.JMenuItem( "Next" ); actionNextMenuItem.setMnemonic( java.awt.event.KeyEvent.VK_N ); //actionNextMenuItem.setAccelerator( javax.swing.KeyStroke.getKeyStroke( java.awt.event.KeyEvent.VK_RIGHT, java.awt.event.ActionEvent.CTRL_MASK ) ); actionNextMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed( java.awt.event.ActionEvent e) { onNext(); } }); javax.swing.JMenuItem actionPrevMenuItem = new javax.swing.JMenuItem( "Previous" ); actionPrevMenuItem.setMnemonic( java.awt.event.KeyEvent.VK_P ); //actionPrevMenuItem.setAccelerator( javax.swing.KeyStroke.getKeyStroke( java.awt.event.KeyEvent.VK_LEFT, java.awt.event.ActionEvent.CTRL_MASK ) ); actionPrevMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed( java.awt.event.ActionEvent e) { onPrev(); } }); setJMenuBar( menuBar ); menuBar.add( fileMenu ); fileMenu.add( fileOpenMenuItem ); fileMenu.add( fileSaveMenuItem ); //fileMenu.add( fileSaveAsMenuItem ); fileMenu.add( fileExitMenuItem ); menuBar.add( actionMenu ); actionMenu.add( actionNextMenuItem ); actionMenu.add( actionPrevMenuItem ); m_treeModel = new ElementTreeModel(); m_treeModel.setRoot( new edu.cmu.cs.stage3.alice.core.Model() {} ); m_tree = new ElementTree( m_treeModel ); final ElementTreeCellRenderer cellRenderer = new ElementTreeCellRenderer(); final ElementTreeCellEditor cellEditor = new ElementTreeCellEditor( m_tree, cellRenderer ); m_tree.setCellRenderer( cellRenderer ); m_tree.setCellEditor( cellEditor ); m_tree.setEditable( true ); m_tree.setScrollsOnExpand( true ); javax.swing.ToolTipManager toolTipManager = javax.swing.ToolTipManager.sharedInstance(); toolTipManager.registerComponent( m_tree ); toolTipManager.setLightWeightPopupEnabled( false ); cellEditor.addCellEditorListener( new javax.swing.event.CellEditorListener() { public void editingStopped( javax.swing.event.ChangeEvent e ) { edu.cmu.cs.stage3.alice.core.Element element = (edu.cmu.cs.stage3.alice.core.Element)m_tree.getLastSelectedPathComponent(); String nameValue = (String)cellEditor.getCellEditorValue(); if( element.name.getStringValue().equals( nameValue ) ) { //pass } else { element.name.set( nameValue ); setIsDirty( true ); } } public void editingCanceled( javax.swing.event.ChangeEvent e ) { } } ); m_tree.addTreeSelectionListener( new javax.swing.event.TreeSelectionListener() { public void valueChanged( javax.swing.event.TreeSelectionEvent e ) { javax.swing.tree.TreePath treePath = e.getPath(); onSelect( (edu.cmu.cs.stage3.alice.core.Element)m_tree.getLastSelectedPathComponent() ); } } ); m_tree.addMouseListener( new java.awt.event.MouseAdapter() { private javax.swing.JPopupMenu m_popupMenu; private edu.cmu.cs.stage3.alice.core.Element m_element; private void handlePopup( java.awt.event.MouseEvent e ) { if( m_popupMenu == null ) { m_popupMenu = new javax.swing.JPopupMenu(); javax.swing.JMenuItem menuItem = new javax.swing.JMenuItem( "Delete" ); menuItem.addActionListener( new java.awt.event.ActionListener() { public void actionPerformed( java.awt.event.ActionEvent e ) { edu.cmu.cs.stage3.alice.core.reference.PropertyReference[] propertyReferences = ModelEditor.this.m_world.getPropertyReferencesTo( m_element ); if( propertyReferences.length > 0 ) { StringBuffer sb = new StringBuffer(); sb.append( "Cannot delete " + m_element.getTrimmedKey() + ". The following properties reference it:\n" ); for( int i=0; i<propertyReferences.length; i++ ) { edu.cmu.cs.stage3.alice.core.Property property = propertyReferences[ i ].getProperty(); sb.append( " " ); sb.append( property.getOwner().getTrimmedKey() ); sb.append( '[' ); sb.append( property.getName() ); sb.append( "] = " ); Object value = property.getValue(); if( value instanceof edu.cmu.cs.stage3.alice.core.Element ) { sb.append( ((edu.cmu.cs.stage3.alice.core.Element)value).getTrimmedKey() ); } else { sb.append( value ); } sb.append( '\n' ); } javax.swing.JOptionPane.showMessageDialog( ModelEditor.this, sb.toString() ); } else { int result = javax.swing.JOptionPane.showConfirmDialog( ModelEditor.this, "Would you like to delete: " + m_element.getTrimmedKey() ); if( result == javax.swing.JOptionPane.YES_OPTION ) { m_treeModel.removeDescendant( m_element ); setIsDirty( true ); } } m_element = null; } } ); m_popupMenu.add( menuItem ); } javax.swing.tree.TreePath path = m_tree.getClosestPathForLocation( e.getX(), e.getY() ); m_element = (edu.cmu.cs.stage3.alice.core.Element)path.getLastPathComponent(); if( m_element != null ) { m_popupMenu.show( e.getComponent(), e.getX(), e.getY() ); } } public void mouseReleased( java.awt.event.MouseEvent e ) { if( e.isPopupTrigger() ) { handlePopup( e ); } } public void mousePressed( java.awt.event.MouseEvent e ) { m_treeMouseEventModifiers = e.getModifiers(); if( e.isPopupTrigger() ) { handlePopup( e ); } onSelect( (edu.cmu.cs.stage3.alice.core.Element)m_tree.getLastSelectedPathComponent() ); } } ); m_tree.setShowsRootHandles( true ); m_tree.setToggleClickCount( 0 ); m_prev = new javax.swing.JButton(); m_prev.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed( java.awt.event.ActionEvent e) { onPrev(); } }); m_next = new javax.swing.JButton(); m_next.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed( java.awt.event.ActionEvent e) { onNext(); } }); m_modeledBy = new javax.swing.JTextField(); m_modeledBy.getDocument().addDocumentListener( new javax.swing.event.DocumentListener() { public void insertUpdate( javax.swing.event.DocumentEvent e ) { onModeledByChange(); } public void removeUpdate( javax.swing.event.DocumentEvent e ) { onModeledByChange(); } public void changedUpdate( javax.swing.event.DocumentEvent e ) { onModeledByChange(); } } ); m_paintedBy = new javax.swing.JTextField(); m_paintedBy.getDocument().addDocumentListener( new javax.swing.event.DocumentListener() { public void insertUpdate( javax.swing.event.DocumentEvent e ) { onPaintedByChange(); } public void removeUpdate( javax.swing.event.DocumentEvent e ) { onPaintedByChange(); } public void changedUpdate( javax.swing.event.DocumentEvent e ) { onPaintedByChange(); } } ); m_revert = new javax.swing.JButton( "Revert" ); m_revert.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed( java.awt.event.ActionEvent e ) { onRevert(); } }); m_revert.setEnabled( false ); m_forceWireframe = new javax.swing.JCheckBox( "Force Wireframe" ); m_forceWireframe.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed( java.awt.event.ActionEvent e ) { onForceWireframe( m_forceWireframe.isSelected() ); } }); m_fileChooser = new javax.swing.JFileChooser(); } public void init( edu.cmu.cs.stage3.alice.scenegraph.renderer.RenderTargetFactory renderTargetFactory ) { m_world = new edu.cmu.cs.stage3.alice.core.World(); m_world.atmosphereColor.set( new edu.cmu.cs.stage3.alice.scenegraph.Color( 0.75, 0.75, 1 ) ); m_world.ambientLightBrightness.set( new Double( 0.2 ) ); m_renderTarget = new edu.cmu.cs.stage3.alice.core.RenderTarget(); m_renderTarget.commit( renderTargetFactory ); class CameraOrbiter implements java.awt.event.MouseListener, java.awt.event.MouseMotionListener { private int m_prevX; public void mouseClicked( java.awt.event.MouseEvent e ) { final int x = e.getX(); final int y = e.getY(); new Thread() { public void run() { edu.cmu.cs.stage3.alice.scenegraph.renderer.PickInfo pickInfo = m_renderTarget.pick( x, y, false, true ); if( pickInfo.getCount() > 0 ) { System.err.println( pickInfo.getVisualAt( 0 ).getBonus() ); } else { System.err.println( "null" ); } } //}.start(); }.run(); } public void mousePressed( java.awt.event.MouseEvent e ) { m_prevX = e.getX(); } public void mouseReleased( java.awt.event.MouseEvent e ) { } public void mouseEntered( java.awt.event.MouseEvent e ) { } public void mouseExited( java.awt.event.MouseEvent e ) { } public void mouseMoved( java.awt.event.MouseEvent e ) { } public void mouseDragged( java.awt.event.MouseEvent e ) { int x = e.getX(); m_camera.rotateRightNow( edu.cmu.cs.stage3.math.MathUtilities.getYAxis(), 0.001 * (x-m_prevX), getModel() ); m_prevX = x; } }; CameraOrbiter cameraOrbiter = new CameraOrbiter(); m_renderTarget.addMouseListener( cameraOrbiter ); m_renderTarget.addMouseMotionListener( cameraOrbiter ); edu.cmu.cs.stage3.alice.core.light.DirectionalLight sun = new edu.cmu.cs.stage3.alice.core.light.DirectionalLight(); sun.vehicle.set( m_world ); m_world.addChild( sun ); sun.setOrientationRightNow( 0, -1, 0, 0, 0, 1 ); m_camera = new edu.cmu.cs.stage3.alice.core.camera.SymmetricPerspectiveCamera(); m_camera.verticalViewingAngle.set( new Double( 0.5 ) ); m_camera.vehicle.set( m_world ); m_camera.renderTarget.set( m_renderTarget ); m_camera.name.set( "Camera" ); m_world.addChild( m_camera ); edu.cmu.cs.stage3.alice.core.Model ground = new edu.cmu.cs.stage3.alice.core.Model(); ground.name.set( "Ground" ); m_world.addChild( ground ); m_pivotDecorator = new edu.cmu.cs.stage3.alice.core.decorator.PivotDecorator(); javax.swing.JPanel westPanel = new javax.swing.JPanel(); westPanel.setLayout( new java.awt.GridBagLayout() ); java.awt.GridBagConstraints gbc = new java.awt.GridBagConstraints(); gbc.anchor = java.awt.GridBagConstraints.NORTHWEST; gbc.fill = java.awt.GridBagConstraints.BOTH; gbc.gridwidth = 1; gbc.weightx = 1.0; westPanel.add( m_prev, gbc ); gbc.gridwidth = java.awt.GridBagConstraints.REMAINDER; westPanel.add( m_next, gbc ); gbc.weighty = 1.0; javax.swing.JScrollPane scrollPane = new javax.swing.JScrollPane( m_tree, javax.swing.ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, javax.swing.ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED ); westPanel.add( scrollPane, gbc ); gbc.weighty = 0.0; gbc.gridwidth = java.awt.GridBagConstraints.RELATIVE; westPanel.add( new javax.swing.JLabel( "modeled by: "), gbc ); gbc.gridwidth = java.awt.GridBagConstraints.REMAINDER; westPanel.add( m_modeledBy, gbc ); gbc.gridwidth = java.awt.GridBagConstraints.RELATIVE; westPanel.add( new javax.swing.JLabel( "painted by: "), gbc ); gbc.gridwidth = java.awt.GridBagConstraints.REMAINDER; westPanel.add( m_paintedBy, gbc ); gbc.gridwidth = java.awt.GridBagConstraints.REMAINDER; westPanel.add( m_revert, gbc ); westPanel.add( m_forceWireframe, gbc ); javax.swing.JSplitPane splitPane = new javax.swing.JSplitPane( javax.swing.JSplitPane.HORIZONTAL_SPLIT, westPanel, m_renderTarget.getAWTComponent() ); getContentPane().setLayout( new java.awt.GridLayout( 1, 1 ) ); getContentPane().add( splitPane ); } public void setIsDirty( boolean isDirty ) { if( m_isDirty != isDirty ) { m_isDirty = isDirty; m_revert.setEnabled( m_isDirty ); updateTitle(); } } public edu.cmu.cs.stage3.alice.core.Model getModel() { return (edu.cmu.cs.stage3.alice.core.Model)m_treeModel.getRoot(); } private void expandTree() { for( int i=0; i<m_tree.getRowCount(); i++ ) { m_tree.expandRow( i ); } m_tree.invalidate(); } private void releasePreviousModel() { edu.cmu.cs.stage3.alice.core.Model prevModel = getModel(); if( prevModel != null ) { //prevModel.release(); //System.err.println( prevModel.vehicle.get() ); //System.err.println( prevModel.getParent() ); prevModel.vehicle.set( null ); prevModel.setParent( null ); } } public void setModel( edu.cmu.cs.stage3.alice.core.Model model ) { m_treeMouseEventModifiers = 0; m_treeModel.setRoot( model ); expandTree(); m_tree.setSelectionInterval( 0, 0 ); m_tree.requestFocus(); if( model != null ) { model.setParent( m_world ); //try { // edu.cmu.cs.stage3.alice.scenegraph.io.OBJ.store( new java.io.FileOutputStream( "c:/fighter.obj" ), model.getSceneGraphTransformable() ); //} catch( Throwable t ) { // t.printStackTrace(); //} model.vehicle.set( m_world ); m_camera.getAGoodLookAtRightNow( model ); edu.cmu.cs.stage3.math.Sphere sphere = model.getBoundingSphere(); double radius = sphere.getRadius(); m_camera.nearClippingPlaneDistance.set( new Double( 0.1 ) ); m_camera.farClippingPlaneDistance.set( new Double( radius*2 + m_camera.getDistanceTo( model ) ) ); m_camera.moveRightNow( 0, 0, -m_camera.nearClippingPlaneDistance.doubleValue() ); String modeledBy = (String)model.data.get( "modeled by" ); if( modeledBy != null ) { m_modeledBy.setText( modeledBy ); } else { m_modeledBy.setText( "" ); } String paintedBy = (String)model.data.get( "painted by" ); if( paintedBy != null ) { m_paintedBy.setText( paintedBy ); } else { m_paintedBy.setText( "" ); } onForceWireframe( m_forceWireframe.isSelected() ); } else { m_modeledBy.setText( "" ); m_paintedBy.setText( "" ); } } private boolean isContinueAppropriateAfterCheckingForSave() { if( m_isDirty ) { int option = javax.swing.JOptionPane.showConfirmDialog( this, "Changes have been made. Would you like to save before continuing?", "Check for save", javax.swing.JOptionPane.YES_NO_CANCEL_OPTION, javax.swing.JOptionPane.PLAIN_MESSAGE ); switch( option ) { case javax.swing.JOptionPane.YES_OPTION: onFileSave(); return true; case javax.swing.JOptionPane.NO_OPTION: return true; case javax.swing.JOptionPane.CANCEL_OPTION: case javax.swing.JOptionPane.CLOSED_OPTION: return false; default: throw new Error(); } } return true; } private void updateTitle() { StringBuffer sb = new StringBuffer( "Model editor: " ); if( m_isDirty ) { sb.append( "*" ); } sb.append( m_file.getPath() ); setTitle( sb.toString() ); } private java.io.File[] getSiblingFiles() { java.io.File directory = m_file.getParentFile(); return directory.listFiles( new java.io.FilenameFilter() { public boolean accept( java.io.File dir, String name ) { return name.endsWith( ".a2c" ); } } ); } private void setFile( java.io.File file ) { m_file = file; updateTitle(); java.io.File[] siblingFiles = getSiblingFiles(); int n = siblingFiles.length; for( int i=0; i<n; i++ ) { if( siblingFiles[ i ].equals( m_file ) ) { if( i == 0 ) { m_prev.setEnabled( false ); m_prev.setText( "<< { None }" ); } else { m_prev.setEnabled( true ); m_prev.setText( "<< " + siblingFiles[ i-1 ].getName() ); m_prev.setActionCommand( siblingFiles[ i-1 ].getPath() ); } if( i==n-1 ) { m_next.setEnabled( false ); m_next.setText( "{ None } >>" ); } else { m_next.setEnabled( true ); m_next.setText( siblingFiles[ i+1 ].getName() + " >>" ); m_next.setActionCommand( siblingFiles[ i+1 ].getPath() ); } } } } private void onPrev() { if( isContinueAppropriateAfterCheckingForSave() ) { open( new java.io.File( m_prev.getActionCommand() ) ); } } private void onNext() { if( isContinueAppropriateAfterCheckingForSave() ) { open( new java.io.File( m_next.getActionCommand() ) ); } } private void onRevert() { open( m_file ); } private void onModeledByChange() { getModel().data.put( "modeled by", m_modeledBy.getText() ); setIsDirty( true ); } private void onPaintedByChange() { getModel().data.put( "painted by", m_paintedBy.getText() ); setIsDirty( true ); } private void negativeAppearance( edu.cmu.cs.stage3.alice.core.Model model ) { edu.cmu.cs.stage3.alice.scenegraph.Appearance sgAppearance = model.getSceneGraphAppearance(); //sgAppearance.setFillingStyle( edu.cmu.cs.stage3.alice.scenegraph.FillingStyle.WIREFRAME ); sgAppearance.setShadingStyle( edu.cmu.cs.stage3.alice.scenegraph.ShadingStyle.SMOOTH ); sgAppearance.setOpacity( 0.25 ); for( int i=0; i<model.parts.size(); i++ ) { negativeAppearance( (edu.cmu.cs.stage3.alice.core.Model)model.parts.get( i ) ); } } private void positiveAppearance( edu.cmu.cs.stage3.alice.core.Model model ) { edu.cmu.cs.stage3.alice.scenegraph.Appearance sgAppearance = model.getSceneGraphAppearance(); edu.cmu.cs.stage3.alice.scenegraph.TextureMap sgTextureMap = null; if( model.diffuseColorMap.getTextureMapValue() != null ) { sgTextureMap = model.diffuseColorMap.getTextureMapValue().getSceneGraphTextureMap(); } sgAppearance.setDiffuseColorMap( sgTextureMap ); //sgAppearance.setFillingStyle( model.fillingStyle.getFillingStyleValue() ); sgAppearance.setShadingStyle( model.shadingStyle.getShadingStyleValue() ); sgAppearance.setOpacity( model.opacity.doubleValue() ); for( int i=0; i<model.parts.size(); i++ ) { positiveAppearance( (edu.cmu.cs.stage3.alice.core.Model)model.parts.get( i ) ); } } private void textureMapAppearance( edu.cmu.cs.stage3.alice.core.Model model, edu.cmu.cs.stage3.alice.core.TextureMap textureMap ) { edu.cmu.cs.stage3.alice.scenegraph.Appearance sgAppearance = model.getSceneGraphAppearance(); if( ( m_treeMouseEventModifiers & java.awt.event.InputEvent.CTRL_MASK ) != 0 ) { sgAppearance.setDiffuseColorMap( textureMap.getSceneGraphTextureMap() ); } else { if( model.diffuseColorMap.get() == textureMap ) { //pass } else { sgAppearance.setDiffuseColorMap( null ); } } for( int i=0; i<model.parts.size(); i++ ) { textureMapAppearance( (edu.cmu.cs.stage3.alice.core.Model)model.parts.get( i ), textureMap ); } } private void onSelect( edu.cmu.cs.stage3.alice.core.Element element ) { positiveAppearance( getModel() ); if( element instanceof edu.cmu.cs.stage3.alice.core.Model ) { if( getModel() != element ) { negativeAppearance( getModel() ); positiveAppearance( (edu.cmu.cs.stage3.alice.core.Model)element ); } m_pivotDecorator.setTransformable( (edu.cmu.cs.stage3.alice.core.Model)element ); } else if( element instanceof edu.cmu.cs.stage3.alice.core.TextureMap ) { textureMapAppearance( getModel(), (edu.cmu.cs.stage3.alice.core.TextureMap)element ); } m_pivotDecorator.setIsShowing( element instanceof edu.cmu.cs.stage3.alice.core.Model ); } private void onForceWireframe( edu.cmu.cs.stage3.alice.core.Model model, boolean forceWireframe ) { edu.cmu.cs.stage3.alice.scenegraph.Appearance sgAppearance = model.getSceneGraphAppearance(); edu.cmu.cs.stage3.alice.scenegraph.FillingStyle fillingStyle; if( forceWireframe ) { fillingStyle = edu.cmu.cs.stage3.alice.scenegraph.FillingStyle.WIREFRAME; } else { fillingStyle = model.fillingStyle.getFillingStyleValue(); } sgAppearance.setFillingStyle( fillingStyle ); for( int i=0; i<model.parts.size(); i++ ) { onForceWireframe( (edu.cmu.cs.stage3.alice.core.Model)model.parts.get( i ), forceWireframe ); } } private void onForceWireframe( boolean forceWireframe ) { onForceWireframe( getModel(), forceWireframe ); } private void open( java.io.File file ) { setFile( file ); try { releasePreviousModel(); edu.cmu.cs.stage3.alice.core.Model model = (edu.cmu.cs.stage3.alice.core.Model)edu.cmu.cs.stage3.alice.core.Element.load( file, m_world ); setModel( model ); hardenPoses(); setIsDirty( false ); } catch( edu.cmu.cs.stage3.alice.core.UnresolvablePropertyReferencesException upre ) { edu.cmu.cs.stage3.alice.core.reference.PropertyReference[] propertyReferences = upre.getPropertyReferences(); for( int i=0; i<propertyReferences.length; i++ ) { System.err.println( propertyReferences[ i ] ); } } catch( java.io.IOException ioe ) { ioe.printStackTrace(); } } private void onFileOpen() { onFileOpen( null ); } private void onFileOpen( java.io.File file ) { if( file == null ) { if( m_file != null ) { m_fileChooser.setCurrentDirectory( m_file.getParentFile() ); } } else { if( file.isDirectory() ) { m_fileChooser.setCurrentDirectory( file ); } else { open( file ); return; } } m_fileChooser.setDialogType( javax.swing.JFileChooser.OPEN_DIALOG ); m_fileChooser.setFileSelectionMode( javax.swing.JFileChooser.FILES_ONLY ); m_fileChooser.setFileFilter( new javax.swing.filechooser.FileFilter() { public boolean accept( java.io.File file ) { return file.isDirectory() || file.getName().endsWith( ".a2c" ); } public String getDescription() { return "Alice Character (*.a2c)"; } } ); m_fileChooser.setPreferredSize( new java.awt.Dimension( 500, 300 ) ); m_fileChooser.rescanCurrentDirectory(); if( m_fileChooser.showDialog( this, null ) == javax.swing.JFileChooser.APPROVE_OPTION ) { open( m_fileChooser.getSelectedFile() ); } m_tree.requestFocus(); } private void onFileSave() { try { softenPoses(); getModel().store( m_file ); setIsDirty( false ); } catch( java.io.IOException ioe ) { ioe.printStackTrace(); } } // private void onFileSaveAs() { // } private void onFileExit() { if( isContinueAppropriateAfterCheckingForSave() ) { System.exit( 0 ); } } private void hardenPoses() { edu.cmu.cs.stage3.alice.core.Pose[] poses = (edu.cmu.cs.stage3.alice.core.Pose[])getModel().getDescendants( edu.cmu.cs.stage3.alice.core.Pose.class ); for( int i=0; i<poses.length; i++ ) { poses[ i ].HACK_harden(); } } private void softenPoses() { edu.cmu.cs.stage3.alice.core.Pose[] poses = (edu.cmu.cs.stage3.alice.core.Pose[])getModel().getDescendants( edu.cmu.cs.stage3.alice.core.Pose.class ); for( int i=0; i<poses.length; i++ ) { poses[ i ].HACK_soften(); } } }
UTF-8
Java
25,525
java
ModelEditor.java
Java
[]
null
[]
package edu.cmu.cs.stage3.alice.gallery.modeleditor; public class ModelEditor extends javax.swing.JFrame { /*public static void main(String[] args) { ModelEditor modelEditor = new ModelEditor(); modelEditor.setLocation( 0, 0 ); modelEditor.setSize( 1280, 1000 ); edu.cmu.cs.stage3.alice.scenegraph.renderer.DefaultRenderTargetFactory drtf = new edu.cmu.cs.stage3.alice.scenegraph.renderer.DefaultRenderTargetFactory(); modelEditor.init( drtf ); if( args.length > 0 ) { modelEditor.onFileOpen( new java.io.File( args[ 0 ] ) ); } else { modelEditor.onFileOpen(); } modelEditor.setVisible( true ); modelEditor.m_tree.requestFocus(); }*/ private edu.cmu.cs.stage3.alice.core.World m_world; private edu.cmu.cs.stage3.alice.core.camera.SymmetricPerspectiveCamera m_camera; private edu.cmu.cs.stage3.alice.core.RenderTarget m_renderTarget; private edu.cmu.cs.stage3.alice.core.decorator.PivotDecorator m_pivotDecorator; private ElementTree m_tree; private ElementTreeModel m_treeModel; private int m_treeMouseEventModifiers = 0; private javax.swing.JButton m_prev; private javax.swing.JButton m_next; private javax.swing.JTextField m_modeledBy; private javax.swing.JTextField m_paintedBy; private javax.swing.JButton m_revert; private javax.swing.JCheckBox m_forceWireframe; private javax.swing.JFileChooser m_fileChooser; private java.io.File m_file; private boolean m_isDirty; public ModelEditor() { addWindowListener(new java.awt.event.WindowAdapter() { public void windowClosing( java.awt.event.WindowEvent e ) { onFileExit(); } }); javax.swing.JMenuBar menuBar = new javax.swing.JMenuBar(); javax.swing.JMenu fileMenu = new javax.swing.JMenu( "File" ); fileMenu.setMnemonic( java.awt.event.KeyEvent.VK_F ); javax.swing.JMenuItem fileOpenMenuItem = new javax.swing.JMenuItem( "Open..." ); fileOpenMenuItem.setMnemonic( java.awt.event.KeyEvent.VK_O ); fileOpenMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed( java.awt.event.ActionEvent e) { onFileOpen(); } }); javax.swing.JMenuItem fileSaveMenuItem = new javax.swing.JMenuItem( "Save" ); fileSaveMenuItem.setMnemonic( java.awt.event.KeyEvent.VK_S ); fileSaveMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed( java.awt.event.ActionEvent e) { onFileSave(); } }); // javax.swing.JMenuItem fileSaveAsMenuItem = new javax.swing.JMenuItem( "Save As..." ); // fileSaveAsMenuItem.setMnemonic( java.awt.event.KeyEvent.VK_A ); // fileSaveAsMenuItem.addActionListener(new java.awt.event.ActionListener() { // public void actionPerformed( java.awt.event.ActionEvent e) { // onFileSaveAs(); // } // }); javax.swing.JMenuItem fileExitMenuItem = new javax.swing.JMenuItem( "Exit..." ); fileExitMenuItem.setMnemonic( java.awt.event.KeyEvent.VK_X ); fileExitMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed( java.awt.event.ActionEvent e) { onFileExit(); } }); javax.swing.JMenu actionMenu = new javax.swing.JMenu( "Action" ); actionMenu.setMnemonic( java.awt.event.KeyEvent.VK_A ); javax.swing.JMenuItem actionNextMenuItem = new javax.swing.JMenuItem( "Next" ); actionNextMenuItem.setMnemonic( java.awt.event.KeyEvent.VK_N ); //actionNextMenuItem.setAccelerator( javax.swing.KeyStroke.getKeyStroke( java.awt.event.KeyEvent.VK_RIGHT, java.awt.event.ActionEvent.CTRL_MASK ) ); actionNextMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed( java.awt.event.ActionEvent e) { onNext(); } }); javax.swing.JMenuItem actionPrevMenuItem = new javax.swing.JMenuItem( "Previous" ); actionPrevMenuItem.setMnemonic( java.awt.event.KeyEvent.VK_P ); //actionPrevMenuItem.setAccelerator( javax.swing.KeyStroke.getKeyStroke( java.awt.event.KeyEvent.VK_LEFT, java.awt.event.ActionEvent.CTRL_MASK ) ); actionPrevMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed( java.awt.event.ActionEvent e) { onPrev(); } }); setJMenuBar( menuBar ); menuBar.add( fileMenu ); fileMenu.add( fileOpenMenuItem ); fileMenu.add( fileSaveMenuItem ); //fileMenu.add( fileSaveAsMenuItem ); fileMenu.add( fileExitMenuItem ); menuBar.add( actionMenu ); actionMenu.add( actionNextMenuItem ); actionMenu.add( actionPrevMenuItem ); m_treeModel = new ElementTreeModel(); m_treeModel.setRoot( new edu.cmu.cs.stage3.alice.core.Model() {} ); m_tree = new ElementTree( m_treeModel ); final ElementTreeCellRenderer cellRenderer = new ElementTreeCellRenderer(); final ElementTreeCellEditor cellEditor = new ElementTreeCellEditor( m_tree, cellRenderer ); m_tree.setCellRenderer( cellRenderer ); m_tree.setCellEditor( cellEditor ); m_tree.setEditable( true ); m_tree.setScrollsOnExpand( true ); javax.swing.ToolTipManager toolTipManager = javax.swing.ToolTipManager.sharedInstance(); toolTipManager.registerComponent( m_tree ); toolTipManager.setLightWeightPopupEnabled( false ); cellEditor.addCellEditorListener( new javax.swing.event.CellEditorListener() { public void editingStopped( javax.swing.event.ChangeEvent e ) { edu.cmu.cs.stage3.alice.core.Element element = (edu.cmu.cs.stage3.alice.core.Element)m_tree.getLastSelectedPathComponent(); String nameValue = (String)cellEditor.getCellEditorValue(); if( element.name.getStringValue().equals( nameValue ) ) { //pass } else { element.name.set( nameValue ); setIsDirty( true ); } } public void editingCanceled( javax.swing.event.ChangeEvent e ) { } } ); m_tree.addTreeSelectionListener( new javax.swing.event.TreeSelectionListener() { public void valueChanged( javax.swing.event.TreeSelectionEvent e ) { javax.swing.tree.TreePath treePath = e.getPath(); onSelect( (edu.cmu.cs.stage3.alice.core.Element)m_tree.getLastSelectedPathComponent() ); } } ); m_tree.addMouseListener( new java.awt.event.MouseAdapter() { private javax.swing.JPopupMenu m_popupMenu; private edu.cmu.cs.stage3.alice.core.Element m_element; private void handlePopup( java.awt.event.MouseEvent e ) { if( m_popupMenu == null ) { m_popupMenu = new javax.swing.JPopupMenu(); javax.swing.JMenuItem menuItem = new javax.swing.JMenuItem( "Delete" ); menuItem.addActionListener( new java.awt.event.ActionListener() { public void actionPerformed( java.awt.event.ActionEvent e ) { edu.cmu.cs.stage3.alice.core.reference.PropertyReference[] propertyReferences = ModelEditor.this.m_world.getPropertyReferencesTo( m_element ); if( propertyReferences.length > 0 ) { StringBuffer sb = new StringBuffer(); sb.append( "Cannot delete " + m_element.getTrimmedKey() + ". The following properties reference it:\n" ); for( int i=0; i<propertyReferences.length; i++ ) { edu.cmu.cs.stage3.alice.core.Property property = propertyReferences[ i ].getProperty(); sb.append( " " ); sb.append( property.getOwner().getTrimmedKey() ); sb.append( '[' ); sb.append( property.getName() ); sb.append( "] = " ); Object value = property.getValue(); if( value instanceof edu.cmu.cs.stage3.alice.core.Element ) { sb.append( ((edu.cmu.cs.stage3.alice.core.Element)value).getTrimmedKey() ); } else { sb.append( value ); } sb.append( '\n' ); } javax.swing.JOptionPane.showMessageDialog( ModelEditor.this, sb.toString() ); } else { int result = javax.swing.JOptionPane.showConfirmDialog( ModelEditor.this, "Would you like to delete: " + m_element.getTrimmedKey() ); if( result == javax.swing.JOptionPane.YES_OPTION ) { m_treeModel.removeDescendant( m_element ); setIsDirty( true ); } } m_element = null; } } ); m_popupMenu.add( menuItem ); } javax.swing.tree.TreePath path = m_tree.getClosestPathForLocation( e.getX(), e.getY() ); m_element = (edu.cmu.cs.stage3.alice.core.Element)path.getLastPathComponent(); if( m_element != null ) { m_popupMenu.show( e.getComponent(), e.getX(), e.getY() ); } } public void mouseReleased( java.awt.event.MouseEvent e ) { if( e.isPopupTrigger() ) { handlePopup( e ); } } public void mousePressed( java.awt.event.MouseEvent e ) { m_treeMouseEventModifiers = e.getModifiers(); if( e.isPopupTrigger() ) { handlePopup( e ); } onSelect( (edu.cmu.cs.stage3.alice.core.Element)m_tree.getLastSelectedPathComponent() ); } } ); m_tree.setShowsRootHandles( true ); m_tree.setToggleClickCount( 0 ); m_prev = new javax.swing.JButton(); m_prev.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed( java.awt.event.ActionEvent e) { onPrev(); } }); m_next = new javax.swing.JButton(); m_next.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed( java.awt.event.ActionEvent e) { onNext(); } }); m_modeledBy = new javax.swing.JTextField(); m_modeledBy.getDocument().addDocumentListener( new javax.swing.event.DocumentListener() { public void insertUpdate( javax.swing.event.DocumentEvent e ) { onModeledByChange(); } public void removeUpdate( javax.swing.event.DocumentEvent e ) { onModeledByChange(); } public void changedUpdate( javax.swing.event.DocumentEvent e ) { onModeledByChange(); } } ); m_paintedBy = new javax.swing.JTextField(); m_paintedBy.getDocument().addDocumentListener( new javax.swing.event.DocumentListener() { public void insertUpdate( javax.swing.event.DocumentEvent e ) { onPaintedByChange(); } public void removeUpdate( javax.swing.event.DocumentEvent e ) { onPaintedByChange(); } public void changedUpdate( javax.swing.event.DocumentEvent e ) { onPaintedByChange(); } } ); m_revert = new javax.swing.JButton( "Revert" ); m_revert.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed( java.awt.event.ActionEvent e ) { onRevert(); } }); m_revert.setEnabled( false ); m_forceWireframe = new javax.swing.JCheckBox( "Force Wireframe" ); m_forceWireframe.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed( java.awt.event.ActionEvent e ) { onForceWireframe( m_forceWireframe.isSelected() ); } }); m_fileChooser = new javax.swing.JFileChooser(); } public void init( edu.cmu.cs.stage3.alice.scenegraph.renderer.RenderTargetFactory renderTargetFactory ) { m_world = new edu.cmu.cs.stage3.alice.core.World(); m_world.atmosphereColor.set( new edu.cmu.cs.stage3.alice.scenegraph.Color( 0.75, 0.75, 1 ) ); m_world.ambientLightBrightness.set( new Double( 0.2 ) ); m_renderTarget = new edu.cmu.cs.stage3.alice.core.RenderTarget(); m_renderTarget.commit( renderTargetFactory ); class CameraOrbiter implements java.awt.event.MouseListener, java.awt.event.MouseMotionListener { private int m_prevX; public void mouseClicked( java.awt.event.MouseEvent e ) { final int x = e.getX(); final int y = e.getY(); new Thread() { public void run() { edu.cmu.cs.stage3.alice.scenegraph.renderer.PickInfo pickInfo = m_renderTarget.pick( x, y, false, true ); if( pickInfo.getCount() > 0 ) { System.err.println( pickInfo.getVisualAt( 0 ).getBonus() ); } else { System.err.println( "null" ); } } //}.start(); }.run(); } public void mousePressed( java.awt.event.MouseEvent e ) { m_prevX = e.getX(); } public void mouseReleased( java.awt.event.MouseEvent e ) { } public void mouseEntered( java.awt.event.MouseEvent e ) { } public void mouseExited( java.awt.event.MouseEvent e ) { } public void mouseMoved( java.awt.event.MouseEvent e ) { } public void mouseDragged( java.awt.event.MouseEvent e ) { int x = e.getX(); m_camera.rotateRightNow( edu.cmu.cs.stage3.math.MathUtilities.getYAxis(), 0.001 * (x-m_prevX), getModel() ); m_prevX = x; } }; CameraOrbiter cameraOrbiter = new CameraOrbiter(); m_renderTarget.addMouseListener( cameraOrbiter ); m_renderTarget.addMouseMotionListener( cameraOrbiter ); edu.cmu.cs.stage3.alice.core.light.DirectionalLight sun = new edu.cmu.cs.stage3.alice.core.light.DirectionalLight(); sun.vehicle.set( m_world ); m_world.addChild( sun ); sun.setOrientationRightNow( 0, -1, 0, 0, 0, 1 ); m_camera = new edu.cmu.cs.stage3.alice.core.camera.SymmetricPerspectiveCamera(); m_camera.verticalViewingAngle.set( new Double( 0.5 ) ); m_camera.vehicle.set( m_world ); m_camera.renderTarget.set( m_renderTarget ); m_camera.name.set( "Camera" ); m_world.addChild( m_camera ); edu.cmu.cs.stage3.alice.core.Model ground = new edu.cmu.cs.stage3.alice.core.Model(); ground.name.set( "Ground" ); m_world.addChild( ground ); m_pivotDecorator = new edu.cmu.cs.stage3.alice.core.decorator.PivotDecorator(); javax.swing.JPanel westPanel = new javax.swing.JPanel(); westPanel.setLayout( new java.awt.GridBagLayout() ); java.awt.GridBagConstraints gbc = new java.awt.GridBagConstraints(); gbc.anchor = java.awt.GridBagConstraints.NORTHWEST; gbc.fill = java.awt.GridBagConstraints.BOTH; gbc.gridwidth = 1; gbc.weightx = 1.0; westPanel.add( m_prev, gbc ); gbc.gridwidth = java.awt.GridBagConstraints.REMAINDER; westPanel.add( m_next, gbc ); gbc.weighty = 1.0; javax.swing.JScrollPane scrollPane = new javax.swing.JScrollPane( m_tree, javax.swing.ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, javax.swing.ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED ); westPanel.add( scrollPane, gbc ); gbc.weighty = 0.0; gbc.gridwidth = java.awt.GridBagConstraints.RELATIVE; westPanel.add( new javax.swing.JLabel( "modeled by: "), gbc ); gbc.gridwidth = java.awt.GridBagConstraints.REMAINDER; westPanel.add( m_modeledBy, gbc ); gbc.gridwidth = java.awt.GridBagConstraints.RELATIVE; westPanel.add( new javax.swing.JLabel( "painted by: "), gbc ); gbc.gridwidth = java.awt.GridBagConstraints.REMAINDER; westPanel.add( m_paintedBy, gbc ); gbc.gridwidth = java.awt.GridBagConstraints.REMAINDER; westPanel.add( m_revert, gbc ); westPanel.add( m_forceWireframe, gbc ); javax.swing.JSplitPane splitPane = new javax.swing.JSplitPane( javax.swing.JSplitPane.HORIZONTAL_SPLIT, westPanel, m_renderTarget.getAWTComponent() ); getContentPane().setLayout( new java.awt.GridLayout( 1, 1 ) ); getContentPane().add( splitPane ); } public void setIsDirty( boolean isDirty ) { if( m_isDirty != isDirty ) { m_isDirty = isDirty; m_revert.setEnabled( m_isDirty ); updateTitle(); } } public edu.cmu.cs.stage3.alice.core.Model getModel() { return (edu.cmu.cs.stage3.alice.core.Model)m_treeModel.getRoot(); } private void expandTree() { for( int i=0; i<m_tree.getRowCount(); i++ ) { m_tree.expandRow( i ); } m_tree.invalidate(); } private void releasePreviousModel() { edu.cmu.cs.stage3.alice.core.Model prevModel = getModel(); if( prevModel != null ) { //prevModel.release(); //System.err.println( prevModel.vehicle.get() ); //System.err.println( prevModel.getParent() ); prevModel.vehicle.set( null ); prevModel.setParent( null ); } } public void setModel( edu.cmu.cs.stage3.alice.core.Model model ) { m_treeMouseEventModifiers = 0; m_treeModel.setRoot( model ); expandTree(); m_tree.setSelectionInterval( 0, 0 ); m_tree.requestFocus(); if( model != null ) { model.setParent( m_world ); //try { // edu.cmu.cs.stage3.alice.scenegraph.io.OBJ.store( new java.io.FileOutputStream( "c:/fighter.obj" ), model.getSceneGraphTransformable() ); //} catch( Throwable t ) { // t.printStackTrace(); //} model.vehicle.set( m_world ); m_camera.getAGoodLookAtRightNow( model ); edu.cmu.cs.stage3.math.Sphere sphere = model.getBoundingSphere(); double radius = sphere.getRadius(); m_camera.nearClippingPlaneDistance.set( new Double( 0.1 ) ); m_camera.farClippingPlaneDistance.set( new Double( radius*2 + m_camera.getDistanceTo( model ) ) ); m_camera.moveRightNow( 0, 0, -m_camera.nearClippingPlaneDistance.doubleValue() ); String modeledBy = (String)model.data.get( "modeled by" ); if( modeledBy != null ) { m_modeledBy.setText( modeledBy ); } else { m_modeledBy.setText( "" ); } String paintedBy = (String)model.data.get( "painted by" ); if( paintedBy != null ) { m_paintedBy.setText( paintedBy ); } else { m_paintedBy.setText( "" ); } onForceWireframe( m_forceWireframe.isSelected() ); } else { m_modeledBy.setText( "" ); m_paintedBy.setText( "" ); } } private boolean isContinueAppropriateAfterCheckingForSave() { if( m_isDirty ) { int option = javax.swing.JOptionPane.showConfirmDialog( this, "Changes have been made. Would you like to save before continuing?", "Check for save", javax.swing.JOptionPane.YES_NO_CANCEL_OPTION, javax.swing.JOptionPane.PLAIN_MESSAGE ); switch( option ) { case javax.swing.JOptionPane.YES_OPTION: onFileSave(); return true; case javax.swing.JOptionPane.NO_OPTION: return true; case javax.swing.JOptionPane.CANCEL_OPTION: case javax.swing.JOptionPane.CLOSED_OPTION: return false; default: throw new Error(); } } return true; } private void updateTitle() { StringBuffer sb = new StringBuffer( "Model editor: " ); if( m_isDirty ) { sb.append( "*" ); } sb.append( m_file.getPath() ); setTitle( sb.toString() ); } private java.io.File[] getSiblingFiles() { java.io.File directory = m_file.getParentFile(); return directory.listFiles( new java.io.FilenameFilter() { public boolean accept( java.io.File dir, String name ) { return name.endsWith( ".a2c" ); } } ); } private void setFile( java.io.File file ) { m_file = file; updateTitle(); java.io.File[] siblingFiles = getSiblingFiles(); int n = siblingFiles.length; for( int i=0; i<n; i++ ) { if( siblingFiles[ i ].equals( m_file ) ) { if( i == 0 ) { m_prev.setEnabled( false ); m_prev.setText( "<< { None }" ); } else { m_prev.setEnabled( true ); m_prev.setText( "<< " + siblingFiles[ i-1 ].getName() ); m_prev.setActionCommand( siblingFiles[ i-1 ].getPath() ); } if( i==n-1 ) { m_next.setEnabled( false ); m_next.setText( "{ None } >>" ); } else { m_next.setEnabled( true ); m_next.setText( siblingFiles[ i+1 ].getName() + " >>" ); m_next.setActionCommand( siblingFiles[ i+1 ].getPath() ); } } } } private void onPrev() { if( isContinueAppropriateAfterCheckingForSave() ) { open( new java.io.File( m_prev.getActionCommand() ) ); } } private void onNext() { if( isContinueAppropriateAfterCheckingForSave() ) { open( new java.io.File( m_next.getActionCommand() ) ); } } private void onRevert() { open( m_file ); } private void onModeledByChange() { getModel().data.put( "modeled by", m_modeledBy.getText() ); setIsDirty( true ); } private void onPaintedByChange() { getModel().data.put( "painted by", m_paintedBy.getText() ); setIsDirty( true ); } private void negativeAppearance( edu.cmu.cs.stage3.alice.core.Model model ) { edu.cmu.cs.stage3.alice.scenegraph.Appearance sgAppearance = model.getSceneGraphAppearance(); //sgAppearance.setFillingStyle( edu.cmu.cs.stage3.alice.scenegraph.FillingStyle.WIREFRAME ); sgAppearance.setShadingStyle( edu.cmu.cs.stage3.alice.scenegraph.ShadingStyle.SMOOTH ); sgAppearance.setOpacity( 0.25 ); for( int i=0; i<model.parts.size(); i++ ) { negativeAppearance( (edu.cmu.cs.stage3.alice.core.Model)model.parts.get( i ) ); } } private void positiveAppearance( edu.cmu.cs.stage3.alice.core.Model model ) { edu.cmu.cs.stage3.alice.scenegraph.Appearance sgAppearance = model.getSceneGraphAppearance(); edu.cmu.cs.stage3.alice.scenegraph.TextureMap sgTextureMap = null; if( model.diffuseColorMap.getTextureMapValue() != null ) { sgTextureMap = model.diffuseColorMap.getTextureMapValue().getSceneGraphTextureMap(); } sgAppearance.setDiffuseColorMap( sgTextureMap ); //sgAppearance.setFillingStyle( model.fillingStyle.getFillingStyleValue() ); sgAppearance.setShadingStyle( model.shadingStyle.getShadingStyleValue() ); sgAppearance.setOpacity( model.opacity.doubleValue() ); for( int i=0; i<model.parts.size(); i++ ) { positiveAppearance( (edu.cmu.cs.stage3.alice.core.Model)model.parts.get( i ) ); } } private void textureMapAppearance( edu.cmu.cs.stage3.alice.core.Model model, edu.cmu.cs.stage3.alice.core.TextureMap textureMap ) { edu.cmu.cs.stage3.alice.scenegraph.Appearance sgAppearance = model.getSceneGraphAppearance(); if( ( m_treeMouseEventModifiers & java.awt.event.InputEvent.CTRL_MASK ) != 0 ) { sgAppearance.setDiffuseColorMap( textureMap.getSceneGraphTextureMap() ); } else { if( model.diffuseColorMap.get() == textureMap ) { //pass } else { sgAppearance.setDiffuseColorMap( null ); } } for( int i=0; i<model.parts.size(); i++ ) { textureMapAppearance( (edu.cmu.cs.stage3.alice.core.Model)model.parts.get( i ), textureMap ); } } private void onSelect( edu.cmu.cs.stage3.alice.core.Element element ) { positiveAppearance( getModel() ); if( element instanceof edu.cmu.cs.stage3.alice.core.Model ) { if( getModel() != element ) { negativeAppearance( getModel() ); positiveAppearance( (edu.cmu.cs.stage3.alice.core.Model)element ); } m_pivotDecorator.setTransformable( (edu.cmu.cs.stage3.alice.core.Model)element ); } else if( element instanceof edu.cmu.cs.stage3.alice.core.TextureMap ) { textureMapAppearance( getModel(), (edu.cmu.cs.stage3.alice.core.TextureMap)element ); } m_pivotDecorator.setIsShowing( element instanceof edu.cmu.cs.stage3.alice.core.Model ); } private void onForceWireframe( edu.cmu.cs.stage3.alice.core.Model model, boolean forceWireframe ) { edu.cmu.cs.stage3.alice.scenegraph.Appearance sgAppearance = model.getSceneGraphAppearance(); edu.cmu.cs.stage3.alice.scenegraph.FillingStyle fillingStyle; if( forceWireframe ) { fillingStyle = edu.cmu.cs.stage3.alice.scenegraph.FillingStyle.WIREFRAME; } else { fillingStyle = model.fillingStyle.getFillingStyleValue(); } sgAppearance.setFillingStyle( fillingStyle ); for( int i=0; i<model.parts.size(); i++ ) { onForceWireframe( (edu.cmu.cs.stage3.alice.core.Model)model.parts.get( i ), forceWireframe ); } } private void onForceWireframe( boolean forceWireframe ) { onForceWireframe( getModel(), forceWireframe ); } private void open( java.io.File file ) { setFile( file ); try { releasePreviousModel(); edu.cmu.cs.stage3.alice.core.Model model = (edu.cmu.cs.stage3.alice.core.Model)edu.cmu.cs.stage3.alice.core.Element.load( file, m_world ); setModel( model ); hardenPoses(); setIsDirty( false ); } catch( edu.cmu.cs.stage3.alice.core.UnresolvablePropertyReferencesException upre ) { edu.cmu.cs.stage3.alice.core.reference.PropertyReference[] propertyReferences = upre.getPropertyReferences(); for( int i=0; i<propertyReferences.length; i++ ) { System.err.println( propertyReferences[ i ] ); } } catch( java.io.IOException ioe ) { ioe.printStackTrace(); } } private void onFileOpen() { onFileOpen( null ); } private void onFileOpen( java.io.File file ) { if( file == null ) { if( m_file != null ) { m_fileChooser.setCurrentDirectory( m_file.getParentFile() ); } } else { if( file.isDirectory() ) { m_fileChooser.setCurrentDirectory( file ); } else { open( file ); return; } } m_fileChooser.setDialogType( javax.swing.JFileChooser.OPEN_DIALOG ); m_fileChooser.setFileSelectionMode( javax.swing.JFileChooser.FILES_ONLY ); m_fileChooser.setFileFilter( new javax.swing.filechooser.FileFilter() { public boolean accept( java.io.File file ) { return file.isDirectory() || file.getName().endsWith( ".a2c" ); } public String getDescription() { return "Alice Character (*.a2c)"; } } ); m_fileChooser.setPreferredSize( new java.awt.Dimension( 500, 300 ) ); m_fileChooser.rescanCurrentDirectory(); if( m_fileChooser.showDialog( this, null ) == javax.swing.JFileChooser.APPROVE_OPTION ) { open( m_fileChooser.getSelectedFile() ); } m_tree.requestFocus(); } private void onFileSave() { try { softenPoses(); getModel().store( m_file ); setIsDirty( false ); } catch( java.io.IOException ioe ) { ioe.printStackTrace(); } } // private void onFileSaveAs() { // } private void onFileExit() { if( isContinueAppropriateAfterCheckingForSave() ) { System.exit( 0 ); } } private void hardenPoses() { edu.cmu.cs.stage3.alice.core.Pose[] poses = (edu.cmu.cs.stage3.alice.core.Pose[])getModel().getDescendants( edu.cmu.cs.stage3.alice.core.Pose.class ); for( int i=0; i<poses.length; i++ ) { poses[ i ].HACK_harden(); } } private void softenPoses() { edu.cmu.cs.stage3.alice.core.Pose[] poses = (edu.cmu.cs.stage3.alice.core.Pose[])getModel().getDescendants( edu.cmu.cs.stage3.alice.core.Pose.class ); for( int i=0; i<poses.length; i++ ) { poses[ i ].HACK_soften(); } } }
25,525
0.694574
0.688423
684
36.317253
33.169205
239
false
false
0
0
0
0
0
0
3.188596
false
false
14
576a8aaf352f0f3585889bed8e6152251037154e
5,265,629,939,519
ccf3c01420d8f2bafea469f60bf2667d20e9710c
/mbackend/src/main/java/com/faq/mbackend/dto/out/BaseBoxCollectionData.java
29076ad9a38d357f18040d019f271ccd25be1a73
[ "Apache-2.0" ]
permissive
sang89vh/springmvc-template
https://github.com/sang89vh/springmvc-template
75b6558c2ad3a2c285f00f7ffe61f3992c1185b1
6070d76270f9ac66de45773f1401dabbde5b7ed1
refs/heads/master
2021-01-01T05:18:11.587000
2016-04-20T17:11:47
2016-04-20T17:11:47
56,702,864
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.faq.mbackend.dto.out; import com.fasterxml.jackson.annotation.JsonProperty; public class BaseBoxCollectionData { @JsonProperty("@rid") private String rid; @JsonProperty("@version") private Integer version; @JsonProperty("@class") private String clazz; @JsonProperty("id") private String id; @JsonProperty("_creation_date") private String createDate; @JsonProperty("_author") private String author; public String getRid() { return rid; } public void setRid(String rid) { this.rid = rid; } public Integer getVersion() { return version; } public void setVersion(Integer version) { this.version = version; } public String getClazz() { return clazz; } public void setClazz(String clazz) { this.clazz = clazz; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getCreateDate() { return createDate; } public void setCreateDate(String createDate) { this.createDate = createDate; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } }
UTF-8
Java
1,124
java
BaseBoxCollectionData.java
Java
[]
null
[]
package com.faq.mbackend.dto.out; import com.fasterxml.jackson.annotation.JsonProperty; public class BaseBoxCollectionData { @JsonProperty("@rid") private String rid; @JsonProperty("@version") private Integer version; @JsonProperty("@class") private String clazz; @JsonProperty("id") private String id; @JsonProperty("_creation_date") private String createDate; @JsonProperty("_author") private String author; public String getRid() { return rid; } public void setRid(String rid) { this.rid = rid; } public Integer getVersion() { return version; } public void setVersion(Integer version) { this.version = version; } public String getClazz() { return clazz; } public void setClazz(String clazz) { this.clazz = clazz; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getCreateDate() { return createDate; } public void setCreateDate(String createDate) { this.createDate = createDate; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } }
1,124
0.701957
0.701957
72
14.611111
14.380306
53
false
false
0
0
0
0
0
0
1.111111
false
false
14
da8bcaa9114a9557c147d5c383881eb02a09c363
8,246,337,250,431
0212f406a4e9f134c9972ef9f630ecca33dfc699
/src/ch08/exam01/Example.java
57fb83459a799d4df07c46322f0630d83774ae39
[]
no_license
hooonfgfg/Java
https://github.com/hooonfgfg/Java
649dff409d8a94de993b0baf9715bc6025abc06f
4de3abdc050f9a451f0e03d6f1371606fe71c399
refs/heads/master
2023-03-17T20:57:44.990000
2021-03-11T00:34:07
2021-03-11T00:34:07
339,272,728
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package ch08.exam01; public class Example { public static void main(String[] args) { RemoteControl rc=new Television(); rc.turnOn(); rc.turnOff(); rc.setVolume(5); //RemoteControl rc=new audio(); //오디오객체를 인터페이스로 사용하겠다. } }
UHC
Java
297
java
Example.java
Java
[]
null
[]
package ch08.exam01; public class Example { public static void main(String[] args) { RemoteControl rc=new Television(); rc.turnOn(); rc.turnOff(); rc.setVolume(5); //RemoteControl rc=new audio(); //오디오객체를 인터페이스로 사용하겠다. } }
297
0.61597
0.596958
16
14.4375
16.628172
56
false
false
0
0
0
0
0
0
1.5
false
false
14
f2498f8f75db81954087823eda0cb830b5db2422
19,198,503,850,638
bd0d53af2d12d284e771c9b1f9c2208e90a8fb63
/src/main/java/org/as3commons/asblocks/impl/ASTASCatchClause.java
cb9ca4449247c124b223b49bf3f3a5ebb743b69d
[]
no_license
Blackrush/as3-commons-jasblocks
https://github.com/Blackrush/as3-commons-jasblocks
e43c33b811eb2f162d82985a8169649650d7f50c
65788bd5c1075284b854eac38a532a5830973c65
refs/heads/master
2020-12-24T23:20:07.440000
2013-07-10T11:56:37
2013-07-10T11:56:37
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
//////////////////////////////////////////////////////////////////////////////// // Copyright 2011 Michael Schmalle - Teoti Graphix, LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License // // Author: Michael Schmalle, Principal Architect // mschmalle at teotigraphix dot com //////////////////////////////////////////////////////////////////////////////// package org.as3commons.asblocks.impl; import org.as3commons.asblocks.dom.IASCatchClause; import org.as3commons.asblocks.dom.IStatementContainer; import org.as3commons.asblocks.parser.antlr.LinkedListTree; import org.as3commons.asblocks.parser.antlr.as3.AS3Parser; public class ASTASCatchClause extends ContainerDelegate implements IASCatchClause { public ASTASCatchClause(LinkedListTree ast) { super(ast); } @Override public String getName() { return ast.getFirstChild().getText(); } @Override public String getType() { LinkedListTree type = ASTUtils .findChildByType(ast, AS3Parser.TYPE_SPEC); if (type == null) { return null; } return ASTUtils.typeSpecText(type); } @Override protected IStatementContainer getStatementContainer() { return new ASTStatementList(block()); } private LinkedListTree block() { return ASTUtils.findChildByType(ast, AS3Parser.BLOCK); } }
UTF-8
Java
1,787
java
ASTASCatchClause.java
Java
[ { "context": "////////////////////////////////\n// Copyright 2011 Michael Schmalle - Teoti Graphix, LLC\n// \n// Licensed under the Ap", "end": 115, "score": 0.9998868107795715, "start": 99, "tag": "NAME", "value": "Michael Schmalle" }, { "context": "d \n// limitations under the License\n// \n// Author: Michael Schmalle, Principal Architect\n// mschmalle at teotigraphix", "end": 728, "score": 0.999890923500061, "start": 712, "tag": "NAME", "value": "Michael Schmalle" }, { "context": "/ Author: Michael Schmalle, Principal Architect\n// mschmalle at teotigraphix dot com\n/////////////////", "end": 754, "score": 0.5190865397453308, "start": 753, "tag": "USERNAME", "value": "m" } ]
null
[]
//////////////////////////////////////////////////////////////////////////////// // Copyright 2011 <NAME> - Teoti Graphix, LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License // // Author: <NAME>, Principal Architect // mschmalle at teotigraphix dot com //////////////////////////////////////////////////////////////////////////////// package org.as3commons.asblocks.impl; import org.as3commons.asblocks.dom.IASCatchClause; import org.as3commons.asblocks.dom.IStatementContainer; import org.as3commons.asblocks.parser.antlr.LinkedListTree; import org.as3commons.asblocks.parser.antlr.as3.AS3Parser; public class ASTASCatchClause extends ContainerDelegate implements IASCatchClause { public ASTASCatchClause(LinkedListTree ast) { super(ast); } @Override public String getName() { return ast.getFirstChild().getText(); } @Override public String getType() { LinkedListTree type = ASTUtils .findChildByType(ast, AS3Parser.TYPE_SPEC); if (type == null) { return null; } return ASTUtils.typeSpecText(type); } @Override protected IStatementContainer getStatementContainer() { return new ASTStatementList(block()); } private LinkedListTree block() { return ASTUtils.findChildByType(ast, AS3Parser.BLOCK); } }
1,767
0.687745
0.678232
64
26.921875
26.369553
80
false
false
0
0
0
0
93
0.098489
1.03125
false
false
14
f054cd159e1beb719358c40a611afb2c8f56b120
1,254,130,497,545
4e21594d3031e329e9d71eaccec481ba73bbdc9e
/libs/core/src/test/java/org/elasticsearch/core/internal/net/NetUtilsTests.java
7c17698d8b20e966635cd6c3e8ca8447f013108a
[ "Elastic-2.0", "Apache-2.0", "SSPL-1.0", "LicenseRef-scancode-other-permissive" ]
permissive
diwasjoshi/elasticsearch
https://github.com/diwasjoshi/elasticsearch
be4e0a9fdc4d0ae04591feb743ddeb6e27b0743f
58ce0f94a0bbdf2576e0a00a62abe1854ee7fe2f
refs/heads/master
2022-01-28T23:21:54.452000
2022-01-18T19:56:01
2022-01-18T19:56:01
122,881,381
0
0
Apache-2.0
true
2018-02-25T21:59:00
2018-02-25T21:59:00
2018-02-25T21:44:48
2018-02-25T20:03:00
391,003
0
0
0
null
false
null
/* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License * 2.0 and the Server Side Public License, v 1; you may not use this file except * in compliance with, at your election, the Elastic License 2.0 or the Server * Side Public License, v 1. */ package org.elasticsearch.core.internal.net; import org.apache.lucene.util.Constants; import org.elasticsearch.core.internal.io.IOUtils; import org.elasticsearch.test.ESTestCase; public class NetUtilsTests extends ESTestCase { public void testExtendedSocketOptions() { assumeTrue("JDK possibly not supported", Constants.JVM_NAME.contains("HotSpot") || Constants.JVM_NAME.contains("OpenJDK")); assumeTrue("Platform possibly not supported", IOUtils.LINUX || IOUtils.MAC_OS_X); assertNotNull(NetUtils.getTcpKeepIdleSocketOptionOrNull()); assertNotNull(NetUtils.getTcpKeepIntervalSocketOptionOrNull()); assertNotNull(NetUtils.getTcpKeepCountSocketOptionOrNull()); } }
UTF-8
Java
1,070
java
NetUtilsTests.java
Java
[]
null
[]
/* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License * 2.0 and the Server Side Public License, v 1; you may not use this file except * in compliance with, at your election, the Elastic License 2.0 or the Server * Side Public License, v 1. */ package org.elasticsearch.core.internal.net; import org.apache.lucene.util.Constants; import org.elasticsearch.core.internal.io.IOUtils; import org.elasticsearch.test.ESTestCase; public class NetUtilsTests extends ESTestCase { public void testExtendedSocketOptions() { assumeTrue("JDK possibly not supported", Constants.JVM_NAME.contains("HotSpot") || Constants.JVM_NAME.contains("OpenJDK")); assumeTrue("Platform possibly not supported", IOUtils.LINUX || IOUtils.MAC_OS_X); assertNotNull(NetUtils.getTcpKeepIdleSocketOptionOrNull()); assertNotNull(NetUtils.getTcpKeepIntervalSocketOptionOrNull()); assertNotNull(NetUtils.getTcpKeepCountSocketOptionOrNull()); } }
1,070
0.759813
0.754206
24
43.583332
35.983696
131
false
false
0
0
0
0
0
0
0.833333
false
false
14
5a9d94e2310845923afd6d635cf691ed08ae1744
20,401,094,691,096
00e5e70f0f95a825bc17ffcd950bc9243ed1e59c
/src/com/goodwillcis/lcp/LCPService/service/impl/.svn/text-base/RegistInfoLcpServiceImpl.java.svn-base
83f25d0630863da845b155763f68ebcbb9073cd3
[]
no_license
huzuohuyou/webcp
https://github.com/huzuohuyou/webcp
45300df56d12f16555ebf8a56bd957d24f96d894
11790169974173ec5493d551f854080457000943
refs/heads/master
2021-01-10T10:10:37.746000
2015-12-27T10:06:01
2015-12-27T10:06:01
48,640,699
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/*---------------------------------------------------------------- // Copyright (C) 2011 北京嘉和美康信息技术有限公司版权所有。 // 文件名: RegistInfoLcpServiceImpl .java // 文件功能描述:查询对应表的总数调用函数接口实现类 // 创建人:刘植鑫 // 创建日期:2011/07/27 // //----------------------------------------------------------------*/ package com.goodwillcis.lcp.LCPService.service.impl; import com.goodwillcis.lcp.LCPService.service.RegistInfoLcpService; import com.goodwillcis.lcp.model.DataSet; public class RegistInfoLcpServiceImpl implements RegistInfoLcpService { @Override public int funGetLogDoctor(String patientNo) { // TODO Auto-generated method stub String sql="select count(*)totalNum from LCP_PATIENT_LOG_DOCTOR where PATIENT_NO="+patientNo; DataSet dataSet=new DataSet(); dataSet.funSetDataSetBySql(sql); int row=dataSet.getRowNum(); return row; } @Override public int funGetLogNurse(String patientNo) { // TODO Auto-generated method stub String sql="select count(*)totalNum from LCP_PATIENT_LOG_NURSE where PATIENT_NO="+patientNo; DataSet dataSet=new DataSet(); dataSet.funSetDataSetBySql(sql); int row=dataSet.getRowNum(); return row; } @Override public int funGetLogOrder(String patientNo) { // TODO Auto-generated method stub String sql="select count(*)totalNum from LCP_PATIENT_LOG_ORDER where PATIENT_NO="+patientNo; DataSet dataSet=new DataSet(); dataSet.funSetDataSetBySql(sql); int row=dataSet.getRowNum(); return row; } @Override public int funGetNode(String patientNo) { // TODO Auto-generated method stub String sql="select count(*)totalNum from LCP_PATIENT_NODE where PATIENT_NO="+patientNo; DataSet dataSet=new DataSet(); dataSet.funSetDataSetBySql(sql); int row=dataSet.getRowNum(); return row; } @Override public String funGetPatientCPStatus(String patientNo) { // TODO Auto-generated method stub String sql="select CP_STATE from LCP_PATIENT_VISIT where PATIENT_NO="+patientNo; DataSet dataSet=new DataSet(); dataSet.funSetDataSetBySql(sql); String type=dataSet.funGetFieldByCol(0, "CP_STATE"); return type; } }
UTF-8
Java
2,190
RegistInfoLcpServiceImpl.java.svn-base
Java
[ { "context": "viceImpl .java\n// 文件功能描述:查询对应表的总数调用函数接口实现类\n// 创建人:刘植鑫 \n// 创建日期:2011/07/27\n// \n//-----------------------", "end": 187, "score": 0.9998970031738281, "start": 184, "tag": "NAME", "value": "刘植鑫" } ]
null
[]
/*---------------------------------------------------------------- // Copyright (C) 2011 北京嘉和美康信息技术有限公司版权所有。 // 文件名: RegistInfoLcpServiceImpl .java // 文件功能描述:查询对应表的总数调用函数接口实现类 // 创建人:刘植鑫 // 创建日期:2011/07/27 // //----------------------------------------------------------------*/ package com.goodwillcis.lcp.LCPService.service.impl; import com.goodwillcis.lcp.LCPService.service.RegistInfoLcpService; import com.goodwillcis.lcp.model.DataSet; public class RegistInfoLcpServiceImpl implements RegistInfoLcpService { @Override public int funGetLogDoctor(String patientNo) { // TODO Auto-generated method stub String sql="select count(*)totalNum from LCP_PATIENT_LOG_DOCTOR where PATIENT_NO="+patientNo; DataSet dataSet=new DataSet(); dataSet.funSetDataSetBySql(sql); int row=dataSet.getRowNum(); return row; } @Override public int funGetLogNurse(String patientNo) { // TODO Auto-generated method stub String sql="select count(*)totalNum from LCP_PATIENT_LOG_NURSE where PATIENT_NO="+patientNo; DataSet dataSet=new DataSet(); dataSet.funSetDataSetBySql(sql); int row=dataSet.getRowNum(); return row; } @Override public int funGetLogOrder(String patientNo) { // TODO Auto-generated method stub String sql="select count(*)totalNum from LCP_PATIENT_LOG_ORDER where PATIENT_NO="+patientNo; DataSet dataSet=new DataSet(); dataSet.funSetDataSetBySql(sql); int row=dataSet.getRowNum(); return row; } @Override public int funGetNode(String patientNo) { // TODO Auto-generated method stub String sql="select count(*)totalNum from LCP_PATIENT_NODE where PATIENT_NO="+patientNo; DataSet dataSet=new DataSet(); dataSet.funSetDataSetBySql(sql); int row=dataSet.getRowNum(); return row; } @Override public String funGetPatientCPStatus(String patientNo) { // TODO Auto-generated method stub String sql="select CP_STATE from LCP_PATIENT_VISIT where PATIENT_NO="+patientNo; DataSet dataSet=new DataSet(); dataSet.funSetDataSetBySql(sql); String type=dataSet.funGetFieldByCol(0, "CP_STATE"); return type; } }
2,190
0.708977
0.702703
66
30.39394
25.904182
95
false
false
0
0
0
0
0
0
1.575758
false
false
14
bd3b0fa599b5ab174c1da189497d065436663884
29,944,512,038,062
0f6590e74be2fa943a3ad9e8871ac085c44b7ddc
/src/lyh/calc.java
fd9afaa3d84d854fec12c8ca1c6d2168d3022bb2
[]
no_license
CaiHongLa/LYH
https://github.com/CaiHongLa/LYH
7722c0fbe99b115ddc4f8077d24ad599e3ee1b1d
370096ddeb62e9db9e46cf5fe1682c90fbd60c2f
refs/heads/master
2016-09-01T03:10:07.513000
2016-03-29T10:07:59
2016-03-29T10:07:59
54,436,361
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package lyh; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Dimension; import java.awt.EventQueue; import java.awt.Font; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JTextArea; import javax.swing.DropMode; import java.awt.GridLayout; import java.awt.Dialog.ModalExclusionType; import java.util.ArrayList; import java.util.List; import javax.swing.ImageIcon; public class calc extends JFrame implements ActionListener { /** * * * * * * * * * * * * * * * * */ private static final long serialVersionUID = -3481251830382553631L; private JFrame frame; private JButton num0 = null; private JButton num1 = null; private JButton num2 = null; private JButton num3 = null; private JButton num4 = null; private JButton num5 = null; private JButton num6 = null; private JButton num7 = null; private JButton num8 = null; private JButton num9 = null; private JButton numa = null; private JButton nums = null; private JButton numm = null; private JButton numd = null; private JButton nume = null; private JButton clear = null; private JButton back = null; private JTextArea show = null; /** * Launch the application. */ public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { calc window = new calc(); window.frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } /** * Create the application. */ public calc() { initialize(); } /** * Initialize the contents of the frame. */ private void initialize() { frame = new JFrame(); frame.setResizable(false); frame.setModalExclusionType(ModalExclusionType.APPLICATION_EXCLUDE); frame.setTitle("¼Ó¼õ³Ë³ý¼ÆËãÆ÷v1.0"); frame.setBounds(100, 100, 216, 368); frame.getContentPane().setLayout(new BorderLayout(0, 0)); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JPanel sPanel = new JPanel(); sPanel.setPreferredSize(new Dimension(299, 60)); JPanel bPanel = new JPanel(); bPanel.setPreferredSize(new Dimension(229, 280)); bPanel.setBackground(Color.getHSBColor(255, 0, 100)); sPanel.setLayout(new GridLayout(0, 1, 0, 0)); show = new JTextArea(); show.setDropMode(DropMode.INSERT); show.setEditable(false); show.setWrapStyleWord(true); show.setPreferredSize(new Dimension(229, 60)); show.setBackground(new Color(255, 255, 204)); show.setLineWrap(true); show.setFont(new Font("΢ÈíÑźÚ", Font.PLAIN, 18)); sPanel.add(show); bPanel.setLayout(new GridLayout(5, 4, 0, 0)); num1 = new JButton("1"); num1.setBackground(new Color(255, 153, 0)); num1.setBorder(null); num1.setPreferredSize(new Dimension(50, 20)); bPanel.add(num1); num1.addActionListener(this); num2 = new JButton("2"); num2.setBackground(new Color(255, 153, 0)); num2.setBorder(null); num2.setPreferredSize(new Dimension(50, 20)); bPanel.add(num2); num2.addActionListener(this); num3 = new JButton("3"); num3.setBackground(new Color(255, 153, 0)); num3.setBorder(null); num3.setPreferredSize(new Dimension(50, 20)); bPanel.add(num3); num3.addActionListener(this); frame.getContentPane().add(bPanel, BorderLayout.SOUTH); back = new JButton("¡û"); back.setBackground(new Color(153, 153, 102)); back.addActionListener(this); back.setBorder(null); bPanel.add(back); num4 = new JButton("4"); num4.setBackground(new Color(255, 153, 0)); num4.setBorder(null); num4.setPreferredSize(new Dimension(50, 20)); bPanel.add(num4); num4.addActionListener(this); num5 = new JButton("5"); num5.setBackground(new Color(255, 153, 0)); num5.setBorder(null); num5.setPreferredSize(new Dimension(50, 20)); bPanel.add(num5); num5.addActionListener(this); num6 = new JButton("6"); num6.setBackground(new Color(255, 153, 0)); num6.setBorder(null); num6.setPreferredSize(new Dimension(50, 20)); bPanel.add(num6); num6.addActionListener(this); num0 = new JButton("0"); num0.setBackground(new Color(153, 153, 102)); num0.setBorder(null); num0.setPreferredSize(new Dimension(50, 20)); bPanel.add(num0); num0.addActionListener(this); num7 = new JButton("7"); num7.setForeground(new Color(0, 0, 0)); num7.setBackground(new Color(255, 153, 0)); num7.setBorder(null); num7.setPreferredSize(new Dimension(50, 20)); bPanel.add(num7); num7.addActionListener(this); num8 = new JButton("8"); num8.setBackground(new Color(255, 153, 0)); num8.setBorder(null); num8.setPreferredSize(new Dimension(50, 20)); bPanel.add(num8); num8.addActionListener(this); num9 = new JButton("9"); num9.setBackground(new Color(255, 153, 0)); num9.setBorder(null); num9.setPreferredSize(new Dimension(50, 20)); bPanel.add(num9); num9.addActionListener(this); clear = new JButton("C"); clear.setBackground(new Color(153, 153, 102)); clear.setBorder(null); clear.setPreferredSize(new Dimension(50, 20)); bPanel.add(clear); clear.addActionListener(this); numd = new JButton("/"); numd.setBackground(new Color(153, 153, 102)); numd.setBorder(null); numd.setPreferredSize(new Dimension(50, 20)); bPanel.add(numd); numd.addActionListener(this); numa = new JButton("+"); numa.setBackground(new Color(153, 153, 102)); numa.setBorder(null); numa.setPreferredSize(new Dimension(50, 20)); bPanel.add(numa); numa.addActionListener(this); numm = new JButton("*"); numm.setBackground(new Color(153, 153, 102)); numm.setBorder(null); numm.setPreferredSize(new Dimension(50, 20)); bPanel.add(numm); numm.addActionListener(this); nums = new JButton("-"); nums.setBackground(new Color(153, 153, 102)); nums.setBorder(null); nums.setPreferredSize(new Dimension(50, 20)); bPanel.add(nums); nums.addActionListener(this); nume = new JButton("="); nume.setBackground(new Color(153, 153, 102)); nume.setBorder(null); bPanel.add(nume); nume.addActionListener(this); frame.getContentPane().add(sPanel, BorderLayout.NORTH); } @Override public void actionPerformed(ActionEvent e) { List<String> txt = new ArrayList<String>(); String data = show.getText(); if (e.getSource() == num0) { show.append("0"); } if (e.getSource() == num1) { show.append("1"); } if (e.getSource() == num2) { show.append("2"); } if (e.getSource() == num3) { show.append("3"); } if (e.getSource() == num4) { show.append("4"); } if (e.getSource() == num5) { show.append("5"); } if (e.getSource() == num6) { show.append("6"); } if (e.getSource() == num7) { show.append("7"); } if (e.getSource() == num8) { show.append("8"); } if (e.getSource() == num9) { show.append("9"); } if (e.getSource() == numa) { show.append("+"); } if (e.getSource() == nums) { show.append("-"); } if (e.getSource() == numm) { show.append("*"); } if (e.getSource() == numd) { show.append("/"); } if (e.getSource() == clear) { show.setText(""); } if (e.getSource() == nume) { if (data.startsWith("+") || data.startsWith("-") || data.startsWith("*") || data.startsWith("/")) { show.setText(""); } else if (data.contains("+")) { show.setText(""); show.append(data + "=" + (Integer.parseInt(data.substring(0, data.indexOf("+"))) + Integer.parseInt(data.substring(data .indexOf("+") + 1)) + "")); } else if (data.contains("-")) { show.setText(""); show.append(data + "=" + (Integer.parseInt(data.substring(0, data.indexOf("-"))) - Integer.parseInt(data.substring(data .indexOf("-") + 1)) + "")); } else if (data.contains("*")) { show.setText(""); show.append(data + "=" + (Integer.parseInt(data.substring(0, data.indexOf("*"))) * Integer.parseInt(data.substring(data .indexOf("*") + 1)) + "")); } else if (data.contains("/")) { show.setText(""); Float tmp = (float) (Integer.parseInt(data.substring(0, data.indexOf("/"))) / (float) (Integer.parseInt(data .substring(data.indexOf("/") + 1)))); show.append(data + "=" + tmp + ""); } } txt.add(data); if (e.getSource() == back) { show.setText(txt.get(0).substring(0, txt.get(0).length() - 1)); } } }
WINDOWS-1252
Java
8,424
java
calc.java
Java
[]
null
[]
package lyh; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Dimension; import java.awt.EventQueue; import java.awt.Font; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JTextArea; import javax.swing.DropMode; import java.awt.GridLayout; import java.awt.Dialog.ModalExclusionType; import java.util.ArrayList; import java.util.List; import javax.swing.ImageIcon; public class calc extends JFrame implements ActionListener { /** * * * * * * * * * * * * * * * * */ private static final long serialVersionUID = -3481251830382553631L; private JFrame frame; private JButton num0 = null; private JButton num1 = null; private JButton num2 = null; private JButton num3 = null; private JButton num4 = null; private JButton num5 = null; private JButton num6 = null; private JButton num7 = null; private JButton num8 = null; private JButton num9 = null; private JButton numa = null; private JButton nums = null; private JButton numm = null; private JButton numd = null; private JButton nume = null; private JButton clear = null; private JButton back = null; private JTextArea show = null; /** * Launch the application. */ public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { calc window = new calc(); window.frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } /** * Create the application. */ public calc() { initialize(); } /** * Initialize the contents of the frame. */ private void initialize() { frame = new JFrame(); frame.setResizable(false); frame.setModalExclusionType(ModalExclusionType.APPLICATION_EXCLUDE); frame.setTitle("¼Ó¼õ³Ë³ý¼ÆËãÆ÷v1.0"); frame.setBounds(100, 100, 216, 368); frame.getContentPane().setLayout(new BorderLayout(0, 0)); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JPanel sPanel = new JPanel(); sPanel.setPreferredSize(new Dimension(299, 60)); JPanel bPanel = new JPanel(); bPanel.setPreferredSize(new Dimension(229, 280)); bPanel.setBackground(Color.getHSBColor(255, 0, 100)); sPanel.setLayout(new GridLayout(0, 1, 0, 0)); show = new JTextArea(); show.setDropMode(DropMode.INSERT); show.setEditable(false); show.setWrapStyleWord(true); show.setPreferredSize(new Dimension(229, 60)); show.setBackground(new Color(255, 255, 204)); show.setLineWrap(true); show.setFont(new Font("΢ÈíÑźÚ", Font.PLAIN, 18)); sPanel.add(show); bPanel.setLayout(new GridLayout(5, 4, 0, 0)); num1 = new JButton("1"); num1.setBackground(new Color(255, 153, 0)); num1.setBorder(null); num1.setPreferredSize(new Dimension(50, 20)); bPanel.add(num1); num1.addActionListener(this); num2 = new JButton("2"); num2.setBackground(new Color(255, 153, 0)); num2.setBorder(null); num2.setPreferredSize(new Dimension(50, 20)); bPanel.add(num2); num2.addActionListener(this); num3 = new JButton("3"); num3.setBackground(new Color(255, 153, 0)); num3.setBorder(null); num3.setPreferredSize(new Dimension(50, 20)); bPanel.add(num3); num3.addActionListener(this); frame.getContentPane().add(bPanel, BorderLayout.SOUTH); back = new JButton("¡û"); back.setBackground(new Color(153, 153, 102)); back.addActionListener(this); back.setBorder(null); bPanel.add(back); num4 = new JButton("4"); num4.setBackground(new Color(255, 153, 0)); num4.setBorder(null); num4.setPreferredSize(new Dimension(50, 20)); bPanel.add(num4); num4.addActionListener(this); num5 = new JButton("5"); num5.setBackground(new Color(255, 153, 0)); num5.setBorder(null); num5.setPreferredSize(new Dimension(50, 20)); bPanel.add(num5); num5.addActionListener(this); num6 = new JButton("6"); num6.setBackground(new Color(255, 153, 0)); num6.setBorder(null); num6.setPreferredSize(new Dimension(50, 20)); bPanel.add(num6); num6.addActionListener(this); num0 = new JButton("0"); num0.setBackground(new Color(153, 153, 102)); num0.setBorder(null); num0.setPreferredSize(new Dimension(50, 20)); bPanel.add(num0); num0.addActionListener(this); num7 = new JButton("7"); num7.setForeground(new Color(0, 0, 0)); num7.setBackground(new Color(255, 153, 0)); num7.setBorder(null); num7.setPreferredSize(new Dimension(50, 20)); bPanel.add(num7); num7.addActionListener(this); num8 = new JButton("8"); num8.setBackground(new Color(255, 153, 0)); num8.setBorder(null); num8.setPreferredSize(new Dimension(50, 20)); bPanel.add(num8); num8.addActionListener(this); num9 = new JButton("9"); num9.setBackground(new Color(255, 153, 0)); num9.setBorder(null); num9.setPreferredSize(new Dimension(50, 20)); bPanel.add(num9); num9.addActionListener(this); clear = new JButton("C"); clear.setBackground(new Color(153, 153, 102)); clear.setBorder(null); clear.setPreferredSize(new Dimension(50, 20)); bPanel.add(clear); clear.addActionListener(this); numd = new JButton("/"); numd.setBackground(new Color(153, 153, 102)); numd.setBorder(null); numd.setPreferredSize(new Dimension(50, 20)); bPanel.add(numd); numd.addActionListener(this); numa = new JButton("+"); numa.setBackground(new Color(153, 153, 102)); numa.setBorder(null); numa.setPreferredSize(new Dimension(50, 20)); bPanel.add(numa); numa.addActionListener(this); numm = new JButton("*"); numm.setBackground(new Color(153, 153, 102)); numm.setBorder(null); numm.setPreferredSize(new Dimension(50, 20)); bPanel.add(numm); numm.addActionListener(this); nums = new JButton("-"); nums.setBackground(new Color(153, 153, 102)); nums.setBorder(null); nums.setPreferredSize(new Dimension(50, 20)); bPanel.add(nums); nums.addActionListener(this); nume = new JButton("="); nume.setBackground(new Color(153, 153, 102)); nume.setBorder(null); bPanel.add(nume); nume.addActionListener(this); frame.getContentPane().add(sPanel, BorderLayout.NORTH); } @Override public void actionPerformed(ActionEvent e) { List<String> txt = new ArrayList<String>(); String data = show.getText(); if (e.getSource() == num0) { show.append("0"); } if (e.getSource() == num1) { show.append("1"); } if (e.getSource() == num2) { show.append("2"); } if (e.getSource() == num3) { show.append("3"); } if (e.getSource() == num4) { show.append("4"); } if (e.getSource() == num5) { show.append("5"); } if (e.getSource() == num6) { show.append("6"); } if (e.getSource() == num7) { show.append("7"); } if (e.getSource() == num8) { show.append("8"); } if (e.getSource() == num9) { show.append("9"); } if (e.getSource() == numa) { show.append("+"); } if (e.getSource() == nums) { show.append("-"); } if (e.getSource() == numm) { show.append("*"); } if (e.getSource() == numd) { show.append("/"); } if (e.getSource() == clear) { show.setText(""); } if (e.getSource() == nume) { if (data.startsWith("+") || data.startsWith("-") || data.startsWith("*") || data.startsWith("/")) { show.setText(""); } else if (data.contains("+")) { show.setText(""); show.append(data + "=" + (Integer.parseInt(data.substring(0, data.indexOf("+"))) + Integer.parseInt(data.substring(data .indexOf("+") + 1)) + "")); } else if (data.contains("-")) { show.setText(""); show.append(data + "=" + (Integer.parseInt(data.substring(0, data.indexOf("-"))) - Integer.parseInt(data.substring(data .indexOf("-") + 1)) + "")); } else if (data.contains("*")) { show.setText(""); show.append(data + "=" + (Integer.parseInt(data.substring(0, data.indexOf("*"))) * Integer.parseInt(data.substring(data .indexOf("*") + 1)) + "")); } else if (data.contains("/")) { show.setText(""); Float tmp = (float) (Integer.parseInt(data.substring(0, data.indexOf("/"))) / (float) (Integer.parseInt(data .substring(data.indexOf("/") + 1)))); show.append(data + "=" + tmp + ""); } } txt.add(data); if (e.getSource() == back) { show.setText(txt.get(0).substring(0, txt.get(0).length() - 1)); } } }
8,424
0.6525
0.605714
329
24.531916
16.275171
71
false
false
0
0
0
0
0
0
1.693009
false
false
14
c677fce1008868869d5e15abdc3ab250e53f6ede
31,988,916,462,144
83593598f21cba234f08eca4dec44d2f73a6052d
/prj/otcol/web-mgr-platform/src/main/java/gnnt/MEBS/timebargain/manage/dao/StatuQueryAndUpdateDAO.java
845a86924e5f3d0de9d168bdeded4f9f4a0989ef
[ "Apache-2.0" ]
permissive
bigstar18/prjs
https://github.com/bigstar18/prjs
23a04309a51b0372ddf6c391ee42270e640ec13c
c29da4d0892ce43e074d9e9831f1eedf828cd9d8
refs/heads/master
2021-05-31T19:55:16.217000
2016-06-24T02:35:31
2016-06-24T02:35:31
42,025,473
0
2
null
null
null
null
null
null
null
null
null
null
null
null
null
package gnnt.MEBS.timebargain.manage.dao; import java.util.List; public abstract interface StatuQueryAndUpdateDAO extends DAO { public abstract List getStatus(); public abstract void updateStatus(String paramString); }
UTF-8
Java
241
java
StatuQueryAndUpdateDAO.java
Java
[]
null
[]
package gnnt.MEBS.timebargain.manage.dao; import java.util.List; public abstract interface StatuQueryAndUpdateDAO extends DAO { public abstract List getStatus(); public abstract void updateStatus(String paramString); }
241
0.755187
0.755187
11
19.90909
20.549074
56
false
false
0
0
0
0
0
0
0.363636
false
false
14
928b079af4cd00363ac6a18fde392ea5355e3e81
9,294,309,231,290
a0bcc1007bfa96da9e9ef14e3ada855f98f38a31
/src/main/java/sim/gen/air/PackageGenerator.java
7a60c57c887114ec47cee342c68afe0794b50062
[]
no_license
lesniakbj/JDCG
https://github.com/lesniakbj/JDCG
0dd0433f3f42faacacecfdaa4e7bc29457edc123
4e3e1dce567109b08e768a1480ee81943ad0ac75
refs/heads/master
2020-03-22T14:53:40.660000
2018-08-04T20:33:13
2018-08-04T20:33:13
140,213,154
3
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package sim.gen.air; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import sim.ai.actions.AIAction; import sim.ai.actions.AIActionType; import sim.campaign.DynamicCampaignSim; import sim.domain.enums.SubTaskType; import sim.domain.unit.UnitGroup; import sim.domain.unit.air.AirUnit; import sim.domain.unit.air.Mission; import sim.domain.unit.global.Airfield; import sim.domain.unit.ground.GroundUnit; import sim.domain.unit.ground.defence.AirDefenceUnit; import sim.gen.mission.AirUnitMissionGenerator; import sim.manager.CoalitionManager; import sim.settings.CampaignSettings; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Date; import java.util.List; import java.util.stream.Collectors; public class PackageGenerator { private static final Logger log = LogManager.getLogger(PackageGenerator.class); private AirUnitMissionGenerator missionGenerator; public PackageGenerator() { this.missionGenerator = missionGenerator; } public List<List<Mission>> generateMissionPackages(CampaignSettings campaignSettings, List<AIAction> actions, CoalitionManager friendlyCoalitionManager, CoalitionManager enemyCoalitionManager, Date currentCampaignDate) { // Friendly Information List<Airfield> friendlyAirfields = friendlyCoalitionManager.getCoalitionAirfields(); List<UnitGroup<AirDefenceUnit>> friendlyAirDefences = friendlyCoalitionManager.getCoalitionAirDefences(); List<UnitGroup<GroundUnit>> friendlyGroundUnits = friendlyCoalitionManager.getCoalitionFrontlineGroups(); // Enemy Information List<Airfield> enemyAirfields = enemyCoalitionManager.getCoalitionAirfields(); List<UnitGroup<AirDefenceUnit>> enemyAirDefences = enemyCoalitionManager.getCoalitionAirDefences(); List<UnitGroup<GroundUnit>> enemyGroundUnits = enemyCoalitionManager.getCoalitionFrontlineGroups(); List<UnitGroup<AirUnit>> enemyActiveAirGroups = enemyCoalitionManager.getMissionManager().getPlannedMissions().stream().filter(Mission::isActive).map(Mission::getMissionAircraft).collect(Collectors.toList()); // For each action, generate a package of missions List<List<Mission>> allPackageMissions = new ArrayList<>(); for(AIAction action : actions) { UnitGroup<AirUnit> g = action.getActionGroup(); Airfield startingAirfield = friendlyAirfields.stream().filter(a -> a.getAirfieldType().getAirfieldMapPosition().getX() == g.getMapXLocation() && a.getAirfieldType().getAirfieldMapPosition().getY() == g.getMapYLocation()).findFirst().orElse(null); if(startingAirfield == null || g.getNumberOfUnits() == 0 || action.getType().equals(AIActionType.NOTHING)) { continue; } List<UnitGroup<AirUnit>> units = friendlyCoalitionManager.getCoalitionAirGroupsMap().get(startingAirfield); units.remove(g); List<UnitGroup<AirUnit>> supportingUnits = getSupportingUnitsForMissionType(action.getType(), g, units); for(UnitGroup<AirUnit> support : supportingUnits) { units.remove(support); } // Create a list of missions for all of the units that we gathered for the package allPackageMissions.addAll(generateMissionsForPackage(action.getType(), g, supportingUnits)); // When we plan a mission for a group, remove it from the airfield, // that it was stationed at. This means that it can not be used again // for future missions until it returns. friendlyCoalitionManager.updateCoalitionAirGroups(startingAirfield, units); } return allPackageMissions; } private List<List<Mission>> generateMissionsForPackage(AIActionType type, UnitGroup<AirUnit> g, List<UnitGroup<AirUnit>> supportingUnits) { return new ArrayList<>(); } // Select other aircraft to support this mission // If the mission is not Intercept or a Helicopter: // - Select CAP/Escort planes // - Send CAP/Escort to location 5-10 minutes BEFORE mission flight // - Have CAP/Escort stay on station for duration of mission private List<UnitGroup<AirUnit>> getSupportingUnitsForMissionType(AIActionType type, UnitGroup<AirUnit> missionGroup, List<UnitGroup<AirUnit>> units) { List<UnitGroup<AirUnit>> supportUnits = new ArrayList<>(); boolean isHelicopter = missionGroup.getNumberOfUnits() != 0 && missionGroup.getGroupUnits().get(0).getAircraftType().isHelicopter(); switch (type) { // Try to find 2-4 supporting units (ie. other CAP flights, Escort, etc) case ATTACK_AIRBASE_STRUCTURE: case ATTACK_AIR_DEFENCE: case ATTACK_GROUND_UNIT: supportUnits = findSupportingUnitsForGroundAttack(missionGroup, isHelicopter, units); break; // Check the type of flight, and add CAP/CAS as needed case DEFEND_AIRBASE_STRUCTURE: case DEFEND_AIR_DEFENCE: case DEFEND_GROUND_UNIT: supportUnits = findSupportingUnitsForGroundDefence(missionGroup, isHelicopter, units); break; // Check the size of flight, ensure 2 planes case INTERCEPT_FLIGHT: supportUnits = findSupportingUnitsForIntercept(missionGroup, isHelicopter, units); break; // Always ensure an Escort of 2 planes case TRANSPORT_AIR_DEFENCE: case TRANSPORT_GROUND_UNIT: supportUnits = findSupportingUnitsForEscort(missionGroup, isHelicopter, units); break; // Get the maximum number of escorts we can case STRATEGIC_BOMBING: supportUnits = findSupportingUnitsForStrategicBombing(missionGroup, isHelicopter, units); break; // Goes alone case RECON: break; } return supportUnits; } private List<UnitGroup<AirUnit>> findSupportingUnitsForStrategicBombing(UnitGroup<AirUnit> missionGroup, boolean isHelicopter, List<UnitGroup<AirUnit>> units) { return new ArrayList<>(); } private List<UnitGroup<AirUnit>> findSupportingUnitsForGroundDefence(UnitGroup<AirUnit> missionGroup, boolean isHelicopter, List<UnitGroup<AirUnit>> units) { boolean isGroundStrike = missionGroup.getNumberOfUnits() != 0 && missionGroup.getGroupUnits().get(0).getAircraftType().getPossibleTasks().contains(SubTaskType.GROUND_STRIKE); boolean isCAS = missionGroup.getNumberOfUnits() != 0 && missionGroup.getGroupUnits().get(0).getAircraftType().getPossibleTasks().contains(SubTaskType.CAS); List<UnitGroup<AirUnit>> air = findUnitsOfSubType(units, isHelicopter, Arrays.asList(SubTaskType.ESCORT, SubTaskType.CAP)); List<UnitGroup<AirUnit>> ground = findUnitsOfSubType(units, isHelicopter, Arrays.asList(SubTaskType.GROUND_STRIKE, SubTaskType.CAS)); List<UnitGroup<AirUnit>> groups = new ArrayList<>(); if(isGroundStrike || isCAS) { groups.addAll(findNumberOfUnits(2 + DynamicCampaignSim.getRandomGen().nextInt(3), air)); groups.addAll(findNumberOfUnits(1, ground)); } else { groups.addAll(findNumberOfUnits(2 + DynamicCampaignSim.getRandomGen().nextInt(3), ground)); groups.addAll(findNumberOfUnits(1, air)); } return groups; } private List<UnitGroup<AirUnit>> findSupportingUnitsForGroundAttack(UnitGroup<AirUnit> missionGroup, boolean isHelicopter, List<UnitGroup<AirUnit>> units) { // Try to find 2-4 supporting units (ie. other CAS flights, Escort, etc) List<UnitGroup<AirUnit>> escorts = findUnitsOfSubType(units, isHelicopter, Collections.singletonList(SubTaskType.ESCORT)); List<UnitGroup<AirUnit>> groundStrikers = findUnitsOfSubType(units, isHelicopter, Arrays.asList(SubTaskType.GROUND_STRIKE, SubTaskType.CAS)); List<UnitGroup<AirUnit>> groups = new ArrayList<>(escorts); groups.addAll(groundStrikers); return findNumberOfUnits(2 + DynamicCampaignSim.getRandomGen().nextInt(3), groups); } private List<UnitGroup<AirUnit>> findSupportingUnitsForEscort(UnitGroup<AirUnit> missionGroup, boolean isHelicopter, List<UnitGroup<AirUnit>> units) { List<UnitGroup<AirUnit>> matchedUnits = findUnitsOfSubType(units, isHelicopter, Collections.singletonList(SubTaskType.ESCORT)); return findNumberOfUnits(1, matchedUnits); } private List<UnitGroup<AirUnit>> findSupportingUnitsForIntercept(UnitGroup<AirUnit> missionGroup, boolean isHelicopter, List<UnitGroup<AirUnit>> units) { if(missionGroup.getNumberOfUnits() >= 2) { return new ArrayList<>(); } List<UnitGroup<AirUnit>> matchedUnits = findUnitsOfSubType(units, isHelicopter, Collections.singletonList(SubTaskType.INTERCEPT)); return findNumberOfUnits(1, matchedUnits); } private List<UnitGroup<AirUnit>> findNumberOfUnits(int number, List<UnitGroup<AirUnit>> matchedUnits) { List<UnitGroup<AirUnit>> units = new ArrayList<>(); for(int i = 0; i < number && i < matchedUnits.size(); i++) { units.add(matchedUnits.get(DynamicCampaignSim.getRandomGen().nextInt(matchedUnits.size()))); } return units; } private List<UnitGroup<AirUnit>> findUnitsOfSubType(List<UnitGroup<AirUnit>> units, boolean isHelicopter, List<SubTaskType> subTaskTypes) { List<UnitGroup<AirUnit>> groups = new ArrayList<>(); for(UnitGroup<AirUnit> unit : units) { List<AirUnit> availableTypes = unit.getGroupUnits().stream() .filter(a -> a.getAircraftType().isHelicopter() == isHelicopter) .filter(a -> a.getAircraftType().getPossibleTasks().containsAll(subTaskTypes)) .collect(Collectors.toList()); if(!availableTypes.isEmpty()) { groups.add(unit); } } return groups; } }
UTF-8
Java
10,275
java
PackageGenerator.java
Java
[]
null
[]
package sim.gen.air; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import sim.ai.actions.AIAction; import sim.ai.actions.AIActionType; import sim.campaign.DynamicCampaignSim; import sim.domain.enums.SubTaskType; import sim.domain.unit.UnitGroup; import sim.domain.unit.air.AirUnit; import sim.domain.unit.air.Mission; import sim.domain.unit.global.Airfield; import sim.domain.unit.ground.GroundUnit; import sim.domain.unit.ground.defence.AirDefenceUnit; import sim.gen.mission.AirUnitMissionGenerator; import sim.manager.CoalitionManager; import sim.settings.CampaignSettings; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Date; import java.util.List; import java.util.stream.Collectors; public class PackageGenerator { private static final Logger log = LogManager.getLogger(PackageGenerator.class); private AirUnitMissionGenerator missionGenerator; public PackageGenerator() { this.missionGenerator = missionGenerator; } public List<List<Mission>> generateMissionPackages(CampaignSettings campaignSettings, List<AIAction> actions, CoalitionManager friendlyCoalitionManager, CoalitionManager enemyCoalitionManager, Date currentCampaignDate) { // Friendly Information List<Airfield> friendlyAirfields = friendlyCoalitionManager.getCoalitionAirfields(); List<UnitGroup<AirDefenceUnit>> friendlyAirDefences = friendlyCoalitionManager.getCoalitionAirDefences(); List<UnitGroup<GroundUnit>> friendlyGroundUnits = friendlyCoalitionManager.getCoalitionFrontlineGroups(); // Enemy Information List<Airfield> enemyAirfields = enemyCoalitionManager.getCoalitionAirfields(); List<UnitGroup<AirDefenceUnit>> enemyAirDefences = enemyCoalitionManager.getCoalitionAirDefences(); List<UnitGroup<GroundUnit>> enemyGroundUnits = enemyCoalitionManager.getCoalitionFrontlineGroups(); List<UnitGroup<AirUnit>> enemyActiveAirGroups = enemyCoalitionManager.getMissionManager().getPlannedMissions().stream().filter(Mission::isActive).map(Mission::getMissionAircraft).collect(Collectors.toList()); // For each action, generate a package of missions List<List<Mission>> allPackageMissions = new ArrayList<>(); for(AIAction action : actions) { UnitGroup<AirUnit> g = action.getActionGroup(); Airfield startingAirfield = friendlyAirfields.stream().filter(a -> a.getAirfieldType().getAirfieldMapPosition().getX() == g.getMapXLocation() && a.getAirfieldType().getAirfieldMapPosition().getY() == g.getMapYLocation()).findFirst().orElse(null); if(startingAirfield == null || g.getNumberOfUnits() == 0 || action.getType().equals(AIActionType.NOTHING)) { continue; } List<UnitGroup<AirUnit>> units = friendlyCoalitionManager.getCoalitionAirGroupsMap().get(startingAirfield); units.remove(g); List<UnitGroup<AirUnit>> supportingUnits = getSupportingUnitsForMissionType(action.getType(), g, units); for(UnitGroup<AirUnit> support : supportingUnits) { units.remove(support); } // Create a list of missions for all of the units that we gathered for the package allPackageMissions.addAll(generateMissionsForPackage(action.getType(), g, supportingUnits)); // When we plan a mission for a group, remove it from the airfield, // that it was stationed at. This means that it can not be used again // for future missions until it returns. friendlyCoalitionManager.updateCoalitionAirGroups(startingAirfield, units); } return allPackageMissions; } private List<List<Mission>> generateMissionsForPackage(AIActionType type, UnitGroup<AirUnit> g, List<UnitGroup<AirUnit>> supportingUnits) { return new ArrayList<>(); } // Select other aircraft to support this mission // If the mission is not Intercept or a Helicopter: // - Select CAP/Escort planes // - Send CAP/Escort to location 5-10 minutes BEFORE mission flight // - Have CAP/Escort stay on station for duration of mission private List<UnitGroup<AirUnit>> getSupportingUnitsForMissionType(AIActionType type, UnitGroup<AirUnit> missionGroup, List<UnitGroup<AirUnit>> units) { List<UnitGroup<AirUnit>> supportUnits = new ArrayList<>(); boolean isHelicopter = missionGroup.getNumberOfUnits() != 0 && missionGroup.getGroupUnits().get(0).getAircraftType().isHelicopter(); switch (type) { // Try to find 2-4 supporting units (ie. other CAP flights, Escort, etc) case ATTACK_AIRBASE_STRUCTURE: case ATTACK_AIR_DEFENCE: case ATTACK_GROUND_UNIT: supportUnits = findSupportingUnitsForGroundAttack(missionGroup, isHelicopter, units); break; // Check the type of flight, and add CAP/CAS as needed case DEFEND_AIRBASE_STRUCTURE: case DEFEND_AIR_DEFENCE: case DEFEND_GROUND_UNIT: supportUnits = findSupportingUnitsForGroundDefence(missionGroup, isHelicopter, units); break; // Check the size of flight, ensure 2 planes case INTERCEPT_FLIGHT: supportUnits = findSupportingUnitsForIntercept(missionGroup, isHelicopter, units); break; // Always ensure an Escort of 2 planes case TRANSPORT_AIR_DEFENCE: case TRANSPORT_GROUND_UNIT: supportUnits = findSupportingUnitsForEscort(missionGroup, isHelicopter, units); break; // Get the maximum number of escorts we can case STRATEGIC_BOMBING: supportUnits = findSupportingUnitsForStrategicBombing(missionGroup, isHelicopter, units); break; // Goes alone case RECON: break; } return supportUnits; } private List<UnitGroup<AirUnit>> findSupportingUnitsForStrategicBombing(UnitGroup<AirUnit> missionGroup, boolean isHelicopter, List<UnitGroup<AirUnit>> units) { return new ArrayList<>(); } private List<UnitGroup<AirUnit>> findSupportingUnitsForGroundDefence(UnitGroup<AirUnit> missionGroup, boolean isHelicopter, List<UnitGroup<AirUnit>> units) { boolean isGroundStrike = missionGroup.getNumberOfUnits() != 0 && missionGroup.getGroupUnits().get(0).getAircraftType().getPossibleTasks().contains(SubTaskType.GROUND_STRIKE); boolean isCAS = missionGroup.getNumberOfUnits() != 0 && missionGroup.getGroupUnits().get(0).getAircraftType().getPossibleTasks().contains(SubTaskType.CAS); List<UnitGroup<AirUnit>> air = findUnitsOfSubType(units, isHelicopter, Arrays.asList(SubTaskType.ESCORT, SubTaskType.CAP)); List<UnitGroup<AirUnit>> ground = findUnitsOfSubType(units, isHelicopter, Arrays.asList(SubTaskType.GROUND_STRIKE, SubTaskType.CAS)); List<UnitGroup<AirUnit>> groups = new ArrayList<>(); if(isGroundStrike || isCAS) { groups.addAll(findNumberOfUnits(2 + DynamicCampaignSim.getRandomGen().nextInt(3), air)); groups.addAll(findNumberOfUnits(1, ground)); } else { groups.addAll(findNumberOfUnits(2 + DynamicCampaignSim.getRandomGen().nextInt(3), ground)); groups.addAll(findNumberOfUnits(1, air)); } return groups; } private List<UnitGroup<AirUnit>> findSupportingUnitsForGroundAttack(UnitGroup<AirUnit> missionGroup, boolean isHelicopter, List<UnitGroup<AirUnit>> units) { // Try to find 2-4 supporting units (ie. other CAS flights, Escort, etc) List<UnitGroup<AirUnit>> escorts = findUnitsOfSubType(units, isHelicopter, Collections.singletonList(SubTaskType.ESCORT)); List<UnitGroup<AirUnit>> groundStrikers = findUnitsOfSubType(units, isHelicopter, Arrays.asList(SubTaskType.GROUND_STRIKE, SubTaskType.CAS)); List<UnitGroup<AirUnit>> groups = new ArrayList<>(escorts); groups.addAll(groundStrikers); return findNumberOfUnits(2 + DynamicCampaignSim.getRandomGen().nextInt(3), groups); } private List<UnitGroup<AirUnit>> findSupportingUnitsForEscort(UnitGroup<AirUnit> missionGroup, boolean isHelicopter, List<UnitGroup<AirUnit>> units) { List<UnitGroup<AirUnit>> matchedUnits = findUnitsOfSubType(units, isHelicopter, Collections.singletonList(SubTaskType.ESCORT)); return findNumberOfUnits(1, matchedUnits); } private List<UnitGroup<AirUnit>> findSupportingUnitsForIntercept(UnitGroup<AirUnit> missionGroup, boolean isHelicopter, List<UnitGroup<AirUnit>> units) { if(missionGroup.getNumberOfUnits() >= 2) { return new ArrayList<>(); } List<UnitGroup<AirUnit>> matchedUnits = findUnitsOfSubType(units, isHelicopter, Collections.singletonList(SubTaskType.INTERCEPT)); return findNumberOfUnits(1, matchedUnits); } private List<UnitGroup<AirUnit>> findNumberOfUnits(int number, List<UnitGroup<AirUnit>> matchedUnits) { List<UnitGroup<AirUnit>> units = new ArrayList<>(); for(int i = 0; i < number && i < matchedUnits.size(); i++) { units.add(matchedUnits.get(DynamicCampaignSim.getRandomGen().nextInt(matchedUnits.size()))); } return units; } private List<UnitGroup<AirUnit>> findUnitsOfSubType(List<UnitGroup<AirUnit>> units, boolean isHelicopter, List<SubTaskType> subTaskTypes) { List<UnitGroup<AirUnit>> groups = new ArrayList<>(); for(UnitGroup<AirUnit> unit : units) { List<AirUnit> availableTypes = unit.getGroupUnits().stream() .filter(a -> a.getAircraftType().isHelicopter() == isHelicopter) .filter(a -> a.getAircraftType().getPossibleTasks().containsAll(subTaskTypes)) .collect(Collectors.toList()); if(!availableTypes.isEmpty()) { groups.add(unit); } } return groups; } }
10,275
0.690608
0.687689
190
53.078949
50.939068
258
false
false
0
0
0
0
0
0
0.847368
false
false
14
caa5ab0a3fdb2d149ee54a8778c88301122ef353
28,767,690,985,515
f356d9f88310d4409a72d3573da10b3d900d62eb
/src/main/java/com/indra/finance/dto/PaymentDTO.java
d1e195ae8c42cde1e8320d7010f70afe3af8e089
[]
no_license
FcondeDev/indra-finance-service
https://github.com/FcondeDev/indra-finance-service
bb507f974b8ced68ae9f75afee39bc2198d23042
dba6f8f0cfd579ec2a3c0851e9b6cc1283050b5a
refs/heads/master
2020-12-10T23:11:14.291000
2020-01-17T04:19:43
2020-01-17T04:19:43
233,737,908
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.indra.finance.dto; import java.util.Date; import javax.validation.constraints.NotNull; import com.fasterxml.jackson.annotation.JsonInclude; import lombok.Data; import lombok.NoArgsConstructor; @Data @NoArgsConstructor @JsonInclude(JsonInclude.Include.NON_NULL) public class PaymentDTO { private String paymentId; @NotNull private String clientIdentification; @NotNull private String dutyId; @NotNull private String bankName; private Date paymenteDate; @NotNull private Long paymentValue; @NotNull private Long paymentPeriod; }
UTF-8
Java
558
java
PaymentDTO.java
Java
[]
null
[]
package com.indra.finance.dto; import java.util.Date; import javax.validation.constraints.NotNull; import com.fasterxml.jackson.annotation.JsonInclude; import lombok.Data; import lombok.NoArgsConstructor; @Data @NoArgsConstructor @JsonInclude(JsonInclude.Include.NON_NULL) public class PaymentDTO { private String paymentId; @NotNull private String clientIdentification; @NotNull private String dutyId; @NotNull private String bankName; private Date paymenteDate; @NotNull private Long paymentValue; @NotNull private Long paymentPeriod; }
558
0.808244
0.808244
30
17.6
14.94568
52
false
false
0
0
0
0
0
0
0.833333
false
false
14
24ae58b8d1294baf0402fb6db2be3e46d324b47b
3,788,161,202,788
56427f59c3161bfe15df8b8b64db1bdad25e5032
/app/src/main/java/com/uc_lab/nativeapp/ui/seminar/SeminarFragment.java
9c39aa4b5b143706a90a7472af4c810ed66eed8b
[]
no_license
SeoSeungHwan/UCLAB_NativeApp
https://github.com/SeoSeungHwan/UCLAB_NativeApp
a9e898055c98afd609f63827c977c2cb0e2c72d1
c40aa9702b2e3f40773764f29f205f8686b27e6a
refs/heads/master
2021-01-26T14:39:18.594000
2020-07-14T09:18:21
2020-07-14T09:18:21
243,449,911
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.uc_lab.nativeapp.ui.seminar; import androidx.core.app.ActivityCompat; import androidx.core.content.ContextCompat; import androidx.lifecycle.ViewModelProviders; import android.app.DownloadManager; import android.content.pm.PackageManager; import android.net.Uri; import android.os.Bundle; import androidx.annotation.NonNull; import androidx.fragment.app.Fragment; import android.os.Environment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.webkit.CookieManager; import android.webkit.DownloadListener; import android.webkit.URLUtil; import android.webkit.WebSettings; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.Button; import android.widget.Toast; import com.uc_lab.nativeapp.MainActivity; import com.uc_lab.nativeapp.R; import com.uc_lab.nativeapp.ui.photo.Photoinfo; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import java.io.IOException; import java.net.HttpURLConnection; import java.net.URL; import static android.content.Context.DOWNLOAD_SERVICE; public class SeminarFragment extends Fragment { private SeminarViewModel SeminarViewModel; private WebSettings mWebSettings; private Button downbutton; public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { SeminarViewModel = ViewModelProviders.of(this).get(SeminarViewModel.class); View root = inflater.inflate(R.layout.fragment_seminar, container, false); final WebView mWebView = root.findViewById(R.id.webview); mWebView.setWebViewClient(new WebViewClient()); mWebSettings = mWebView.getSettings(); //각종 환경 설정 가능여부 mWebSettings.setJavaScriptEnabled(true); // 자바스크립트 허용여부 mWebSettings.setSupportMultipleWindows(false); // 윈도우 여러개 사용여부 mWebSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN); // 컨텐츠사이즈 맞추기 mWebSettings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK); // 캐시 허용 여부 mWebSettings.setUseWideViewPort(true); // wide viewport 사용 여부 mWebSettings.setSupportZoom(true); // Zoom사용여부 mWebSettings.setJavaScriptCanOpenWindowsAutomatically(false); // 자바스크립트가 window.open()사용할수있는지 여부 mWebSettings.setLoadWithOverviewMode(true); // 메타태그 허용 여부 mWebSettings.setBuiltInZoomControls(false); // 화면 확대 축소 허용 여부 mWebSettings.setDomStorageEnabled(true); // 로컬저장소 허용 여부 mWebView.loadUrl("http://se.sch.ac.kr/xe/index.php?mid=Seminar"); // 웹뷰 사이트 주소 및 시작 mWebView.setDownloadListener(new DownloadListener() { @Override public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) { } }); return root; } }
UTF-8
Java
3,174
java
SeminarFragment.java
Java
[]
null
[]
package com.uc_lab.nativeapp.ui.seminar; import androidx.core.app.ActivityCompat; import androidx.core.content.ContextCompat; import androidx.lifecycle.ViewModelProviders; import android.app.DownloadManager; import android.content.pm.PackageManager; import android.net.Uri; import android.os.Bundle; import androidx.annotation.NonNull; import androidx.fragment.app.Fragment; import android.os.Environment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.webkit.CookieManager; import android.webkit.DownloadListener; import android.webkit.URLUtil; import android.webkit.WebSettings; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.Button; import android.widget.Toast; import com.uc_lab.nativeapp.MainActivity; import com.uc_lab.nativeapp.R; import com.uc_lab.nativeapp.ui.photo.Photoinfo; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import java.io.IOException; import java.net.HttpURLConnection; import java.net.URL; import static android.content.Context.DOWNLOAD_SERVICE; public class SeminarFragment extends Fragment { private SeminarViewModel SeminarViewModel; private WebSettings mWebSettings; private Button downbutton; public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { SeminarViewModel = ViewModelProviders.of(this).get(SeminarViewModel.class); View root = inflater.inflate(R.layout.fragment_seminar, container, false); final WebView mWebView = root.findViewById(R.id.webview); mWebView.setWebViewClient(new WebViewClient()); mWebSettings = mWebView.getSettings(); //각종 환경 설정 가능여부 mWebSettings.setJavaScriptEnabled(true); // 자바스크립트 허용여부 mWebSettings.setSupportMultipleWindows(false); // 윈도우 여러개 사용여부 mWebSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN); // 컨텐츠사이즈 맞추기 mWebSettings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK); // 캐시 허용 여부 mWebSettings.setUseWideViewPort(true); // wide viewport 사용 여부 mWebSettings.setSupportZoom(true); // Zoom사용여부 mWebSettings.setJavaScriptCanOpenWindowsAutomatically(false); // 자바스크립트가 window.open()사용할수있는지 여부 mWebSettings.setLoadWithOverviewMode(true); // 메타태그 허용 여부 mWebSettings.setBuiltInZoomControls(false); // 화면 확대 축소 허용 여부 mWebSettings.setDomStorageEnabled(true); // 로컬저장소 허용 여부 mWebView.loadUrl("http://se.sch.ac.kr/xe/index.php?mid=Seminar"); // 웹뷰 사이트 주소 및 시작 mWebView.setDownloadListener(new DownloadListener() { @Override public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) { } }); return root; } }
3,174
0.748481
0.748481
85
33.847057
28.834417
135
false
false
0
0
0
0
0
0
0.729412
false
false
14
79095c1928b4d093a4b9435b31b3dd39a4641a5b
15,985,868,292,159
f20b9c07acd726c314c26b694c140429fea1afd0
/day19/src/test/java/advent/TubesTest.java
d6453bab1b04fed5f2acba014c26969e470baaf5
[]
no_license
bmunzenb/advent-of-code-2017
https://github.com/bmunzenb/advent-of-code-2017
06252045c9e111d7db0d0f6eaab10fcd2a2e616d
9cc4acdf7bbcdd94f722c13131c634136b91acce
refs/heads/master
2021-09-01T07:32:39.513000
2017-12-25T18:17:26
2017-12-25T18:17:26
112,773,178
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package advent; import static org.junit.Assert.assertEquals; import org.junit.Test; import advent.Tubes.Result; public class TubesTest { @Test public void walkPath() { String[] input = new String[] { " | ", " | +--+ ", " A | C ", " F---|----E|--+ ", " | | | D ", " +B-+ +--+ " }; Result r = Tubes.walkPath(input); assertEquals("ABCDEF", r.path); assertEquals(38, r.steps); } }
UTF-8
Java
458
java
TubesTest.java
Java
[]
null
[]
package advent; import static org.junit.Assert.assertEquals; import org.junit.Test; import advent.Tubes.Result; public class TubesTest { @Test public void walkPath() { String[] input = new String[] { " | ", " | +--+ ", " A | C ", " F---|----E|--+ ", " | | | D ", " +B-+ +--+ " }; Result r = Tubes.walkPath(input); assertEquals("ABCDEF", r.path); assertEquals(38, r.steps); } }
458
0.497817
0.49345
28
15.357142
13.464807
44
false
false
0
0
0
0
0
0
1.928571
false
false
14